tide-commander 0.71.4 → 0.71.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/browser-ponyfill-DIm4hKhx.js","assets/vendor-react-uS-d4TUT.js","assets/web-DNsSwQTa.js","assets/modulepreload-polyfill-B5Qt9EMX.js","assets/vendor-three-DJ4p3FLF.js"])))=>i.map(i=>d[i]);
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/browser-ponyfill-DIm4hKhx.js","assets/vendor-react-uS-d4TUT.js","assets/web-C2T66Tt9.js","assets/modulepreload-polyfill-B5Qt9EMX.js","assets/vendor-three-DJ4p3FLF.js"])))=>i.map(i=>d[i]);
2
2
  var wD=Object.defineProperty;var kD=(s,e,t)=>e in s?wD(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var W=(s,e,t)=>kD(s,typeof e!="symbol"?e+"":e,t);import"./modulepreload-polyfill-B5Qt9EMX.js";import{r as ex,g as ud,a as tA,c as Xk}from"./vendor-react-uS-d4TUT.js";import{T as SD,a as Yb,b as nA,L as sA,c as $u,F as gp,M as Ai,V as _s,C as Bt,d as Ci,S as Va,e as jD,P as aA,D as sc,f as Vo,g as yt,I as Ji,Q as Ko,h as CD,O as iA,i as tx,j as ND,B as Ka,k as AD,l as Hu,N as MD,m as TD,n as ED,o as In,p as rA,R as Oo,q as _D,r as DD,s as nm,t as Ur,u as Io,v as rt,w as ws,x as We,y as PD,z as La,A as Vb,E as De,G as nx,H as zr,J as RD,K as dd,U as Bn,W as sx,X as oA,Y as lA,Z as LD,_ as OD,$ as ID,a0 as BD,a1 as cA,a2 as FD,a3 as Zk,a4 as Qk,a5 as Jk,a6 as eS,a7 as Kb,a8 as uA,a9 as zD,aa as bp,ab as $D,ac as HD,ad as Uu,ae as Xb,af as Hn,ag as Yn,ah as Xo,ai as Jn,aj as Un,ak as UD,al as dA,am as GD,an as WD,ao as tr,ap as Zo,aq as Ut,ar as hA,as as sn,at as uc,au as tS,av as qD,aw as ax,ax as YD,ay as VD,az as pA,aA as yp,aB as Zb,aC as ac,aD as mA,aE as nS,aF as KD,aG as XD,aH as $o,aI as Ql,aJ as ZD,aK as sS,aL as Qb,aM as QD,aN as JD,aO as eP,aP as tP,aQ as fA,aR as ix,aS as gA,aT as nP,aU as sP}from"./vendor-three-DJ4p3FLF.js";function aP(s,e){for(var t=0;t<e.length;t++){const n=e[t];if(typeof n!="string"&&!Array.isArray(n)){for(const a in n)if(a!=="default"&&!(a in s)){const i=Object.getOwnPropertyDescriptor(n,a);i&&Object.defineProperty(s,a,i.get?i:{enumerable:!0,get:()=>n[a]})}}}return Object.freeze(Object.defineProperty(s,Symbol.toStringTag,{value:"Module"}))}var Rg={exports:{}},bu={};/**
3
3
  * @license React
4
4
  * react-jsx-runtime.production.js
@@ -39,7 +39,7 @@ Error generating stack: `+v.message+`
39
39
  *
40
40
  * This source code is licensed under the MIT license found in the
41
41
  * LICENSE file in the root directory of this source tree.
42
- */var NS;function qP(){if(NS)return Hg;NS=1;var s=ex();function e(p,f){return p===f&&(p!==0||1/p===1/f)||p!==p&&f!==f}var t=typeof Object.is=="function"?Object.is:e,n=s.useState,a=s.useEffect,i=s.useLayoutEffect,o=s.useDebugValue;function l(p,f){var b=f(),y=n({inst:{value:b,getSnapshot:f}}),w=y[0].inst,k=y[1];return i(function(){w.value=b,w.getSnapshot=f,c(w)&&k({inst:w})},[p,b,f]),a(function(){return c(w)&&k({inst:w}),p(function(){c(w)&&k({inst:w})})},[p]),o(b),b}function c(p){var f=p.getSnapshot;p=p.value;try{var b=f();return!t(p,b)}catch{return!0}}function d(p,f){return f()}var m=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?d:l;return Hg.useSyncExternalStore=s.useSyncExternalStore!==void 0?s.useSyncExternalStore:m,Hg}var AS;function YP(){return AS||(AS=1,$g.exports=qP()),$g.exports}var VP=YP();const KP=(s,e)=>Qo(e)?e:RP(e)&&Qo(e.defaultValue)?e.defaultValue:Array.isArray(s)?s[s.length-1]:s,XP={t:KP,ready:!1},ZP=()=>()=>{},Ue=(s,e={})=>{var _,P,L;const{i18n:t}=e,{i18n:n,defaultNS:a}=x.useContext(GP)||{},i=t||n||HP();i&&!i.reportNamespaces&&(i.reportNamespaces=new WP),i||wA(i,"NO_I18NEXT_INSTANCE","useTranslation: You will need to pass in an i18next instance by using initReactI18next");const o=x.useMemo(()=>{var R;return{...zP(),...(R=i==null?void 0:i.options)==null?void 0:R.react,...e}},[i,e]),{useSuspense:l,keyPrefix:c}=o,d=s||a||((_=i==null?void 0:i.options)==null?void 0:_.defaultNS),m=Qo(d)?[d]:d||["translation"],p=x.useMemo(()=>m,m);(L=(P=i==null?void 0:i.reportNamespaces)==null?void 0:P.addUsedNamespaces)==null||L.call(P,p);const f=x.useRef(0),b=x.useCallback(R=>{if(!i)return ZP;const{bindI18n:z,bindI18nStore:F}=o,$=()=>{f.current+=1,R()};return z&&i.on(z,$),F&&i.store.on(F,$),()=>{z&&z.split(" ").forEach(U=>i.off(U,$)),F&&F.split(" ").forEach(U=>i.store.off(U,$))}},[i,o]),y=x.useRef(),w=x.useCallback(()=>{if(!i)return XP;const R=!!(i.isInitialized||i.initializedStoreOnce)&&p.every(K=>PP(K,i,o)),z=e.lng||i.language,F=f.current,$=y.current;if($&&$.ready===R&&$.lng===z&&$.keyPrefix===c&&$.revision===F)return $;const G={t:i.getFixedT(z,o.nsMode==="fallback"?p:p[0],c),ready:R,lng:z,keyPrefix:c,revision:F};return y.current=G,G},[i,p,c,o,e.lng]),[k,S]=x.useState(0),{t:j,ready:C}=VP.useSyncExternalStore(b,w,w);x.useEffect(()=>{if(i&&!C&&!l){const R=()=>S(z=>z+1);e.lng?CS(i,e.lng,p,R):ty(i,p,R)}},[i,e.lng,p,C,l,k]);const A=i||{},D=x.useRef(null),M=x.useRef(),I=R=>{const z=Object.getOwnPropertyDescriptors(R);z.__original&&delete z.__original;const F=Object.create(Object.getPrototypeOf(R),z);if(!Object.prototype.hasOwnProperty.call(F,"__original"))try{Object.defineProperty(F,"__original",{value:R,writable:!1,enumerable:!1,configurable:!1})}catch{}return F},E=x.useMemo(()=>{const R=A,z=R==null?void 0:R.language;let F=R;R&&(D.current&&D.current.__original===R?M.current!==z?(F=I(R),D.current=F,M.current=z):F=D.current:(F=I(R),D.current=F,M.current=z));const $=[j,F,C];return $.t=j,$.i18n=F,$.ready=C,$},[j,A,C,A.resolvedLanguage,A.language,A.languages]);if(i&&l&&!C)throw new Promise(R=>{const z=()=>R();e.lng?CS(i,e.lng,p,z):ty(i,p,z)});return E};function sy(s){"@babel/helpers - typeof";return sy=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},sy(s)}function jA(){return typeof XMLHttpRequest=="function"||(typeof XMLHttpRequest>"u"?"undefined":sy(XMLHttpRequest))==="object"}function QP(s){return!!s&&typeof s.then=="function"}function JP(s){return QP(s)?s:Promise.resolve(s)}const eR="modulepreload",tR=function(s){return"/"+s},MS={},CA=function(e,t,n){let a=Promise.resolve();if(t&&t.length>0){let o=function(d){return Promise.all(d.map(m=>Promise.resolve(m).then(p=>({status:"fulfilled",value:p}),p=>({status:"rejected",reason:p}))))};document.getElementsByTagName("link");const l=document.querySelector("meta[property=csp-nonce]"),c=(l==null?void 0:l.nonce)||(l==null?void 0:l.getAttribute("nonce"));a=o(t.map(d=>{if(d=tR(d),d in MS)return;MS[d]=!0;const m=d.endsWith(".css"),p=m?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${p}`))return;const f=document.createElement("link");if(f.rel=m?"stylesheet":eR,m||(f.as="script"),f.crossOrigin="",f.href=d,c&&f.setAttribute("nonce",c),document.head.appendChild(f),m)return new Promise((b,y)=>{f.addEventListener("load",b),f.addEventListener("error",()=>y(new Error(`Unable to preload CSS for ${d}`)))})}))}function i(o){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=o,window.dispatchEvent(l),!l.defaultPrevented)throw o}return a.then(o=>{for(const l of o||[])l.status==="rejected"&&i(l.reason);return e().catch(i)})};function TS(s,e){var t=Object.keys(s);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(s);e&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(s,a).enumerable})),t.push.apply(t,n)}return t}function ES(s){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?TS(Object(t),!0).forEach(function(n){nR(s,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(s,Object.getOwnPropertyDescriptors(t)):TS(Object(t)).forEach(function(n){Object.defineProperty(s,n,Object.getOwnPropertyDescriptor(t,n))})}return s}function nR(s,e,t){return(e=sR(e))in s?Object.defineProperty(s,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):s[e]=t,s}function sR(s){var e=aR(s,"string");return Jo(e)=="symbol"?e:e+""}function aR(s,e){if(Jo(s)!="object"||!s)return s;var t=s[Symbol.toPrimitive];if(t!==void 0){var n=t.call(s,e);if(Jo(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(s)}function Jo(s){"@babel/helpers - typeof";return Jo=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Jo(s)}var Kr=typeof fetch=="function"?fetch:void 0;typeof global<"u"&&global.fetch?Kr=global.fetch:typeof window<"u"&&window.fetch&&(Kr=window.fetch);var ed;jA()&&(typeof global<"u"&&global.XMLHttpRequest?ed=global.XMLHttpRequest:typeof window<"u"&&window.XMLHttpRequest&&(ed=window.XMLHttpRequest));var kp;typeof ActiveXObject=="function"&&(typeof global<"u"&&global.ActiveXObject?kp=global.ActiveXObject:typeof window<"u"&&window.ActiveXObject&&(kp=window.ActiveXObject));typeof Kr!="function"&&(Kr=void 0);if(!Kr&&!ed&&!kp)try{CA(()=>import("./browser-ponyfill-DIm4hKhx.js").then(s=>s.b),__vite__mapDeps([0,1])).then(function(s){Kr=s.default}).catch(function(){})}catch{}var ay=function(e,t){if(t&&Jo(t)==="object"){var n="";for(var a in t)n+="&"+encodeURIComponent(a)+"="+encodeURIComponent(t[a]);if(!n)return e;e=e+(e.indexOf("?")!==-1?"&":"?")+n.slice(1)}return e},_S=function(e,t,n,a){var i=function(c){if(!c.ok)return n(c.statusText||"Error",{status:c.status});c.text().then(function(d){n(null,{status:c.status,data:d})}).catch(n)};if(a){var o=a(e,t);if(o instanceof Promise){o.then(i).catch(n);return}}typeof fetch=="function"?fetch(e,t).then(i).catch(n):Kr(e,t).then(i).catch(n)},DS=!1,iR=function(e,t,n,a){e.queryStringParams&&(t=ay(t,e.queryStringParams));var i=ES({},typeof e.customHeaders=="function"?e.customHeaders():e.customHeaders);typeof window>"u"&&typeof global<"u"&&typeof global.process<"u"&&global.process.versions&&global.process.versions.node&&(i["User-Agent"]="i18next-http-backend (node/".concat(global.process.version,"; ").concat(global.process.platform," ").concat(global.process.arch,")")),n&&(i["Content-Type"]="application/json");var o=typeof e.requestOptions=="function"?e.requestOptions(n):e.requestOptions,l=ES({method:n?"POST":"GET",body:n?e.stringify(n):void 0,headers:i},DS?{}:o),c=typeof e.alternateFetch=="function"&&e.alternateFetch.length>=1?e.alternateFetch:void 0;try{_S(t,l,a,c)}catch(d){if(!o||Object.keys(o).length===0||!d.message||d.message.indexOf("not implemented")<0)return a(d);try{Object.keys(o).forEach(function(m){delete l[m]}),_S(t,l,a,c),DS=!0}catch(m){a(m)}}},rR=function(e,t,n,a){n&&Jo(n)==="object"&&(n=ay("",n).slice(1)),e.queryStringParams&&(t=ay(t,e.queryStringParams));try{var i=ed?new ed:new kp("MSXML2.XMLHTTP.3.0");i.open(n?"POST":"GET",t,1),e.crossDomain||i.setRequestHeader("X-Requested-With","XMLHttpRequest"),i.withCredentials=!!e.withCredentials,n&&i.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),i.overrideMimeType&&i.overrideMimeType("application/json");var o=e.customHeaders;if(o=typeof o=="function"?o():o,o)for(var l in o)i.setRequestHeader(l,o[l]);i.onreadystatechange=function(){i.readyState>3&&a(i.status>=400?i.statusText:null,{status:i.status,data:i.responseText})},i.send(n)}catch(c){console&&console.log(c)}},oR=function(e,t,n,a){if(typeof n=="function"&&(a=n,n=void 0),a=a||function(){},Kr&&t.indexOf("file:")!==0)return iR(e,t,n,a);if(jA()||typeof ActiveXObject=="function")return rR(e,t,n,a);a(new Error("No fetch and no xhr implementation found!"))};function dc(s){"@babel/helpers - typeof";return dc=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},dc(s)}function PS(s,e){var t=Object.keys(s);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(s);e&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(s,a).enumerable})),t.push.apply(t,n)}return t}function Ug(s){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?PS(Object(t),!0).forEach(function(n){NA(s,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(s,Object.getOwnPropertyDescriptors(t)):PS(Object(t)).forEach(function(n){Object.defineProperty(s,n,Object.getOwnPropertyDescriptor(t,n))})}return s}function lR(s,e){if(!(s instanceof e))throw new TypeError("Cannot call a class as a function")}function cR(s,e){for(var t=0;t<e.length;t++){var n=e[t];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(s,AA(n.key),n)}}function uR(s,e,t){return e&&cR(s.prototype,e),Object.defineProperty(s,"prototype",{writable:!1}),s}function NA(s,e,t){return(e=AA(e))in s?Object.defineProperty(s,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):s[e]=t,s}function AA(s){var e=dR(s,"string");return dc(e)=="symbol"?e:e+""}function dR(s,e){if(dc(s)!="object"||!s)return s;var t=s[Symbol.toPrimitive];if(t!==void 0){var n=t.call(s,e);if(dc(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(s)}var hR=function(){return{loadPath:"/locales/{{lng}}/{{ns}}.json",addPath:"/locales/add/{{lng}}/{{ns}}",parse:function(t){return JSON.parse(t)},stringify:JSON.stringify,parsePayload:function(t,n,a){return NA({},n,a||"")},parseLoadPayload:function(t,n){},request:oR,reloadInterval:typeof window<"u"?!1:3600*1e3,customHeaders:{},queryStringParams:{},crossDomain:!1,withCredentials:!1,overrideMimeType:!1,requestOptions:{mode:"cors",credentials:"same-origin",cache:"default"}}},MA=(function(){function s(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};lR(this,s),this.services=e,this.options=t,this.allOptions=n,this.type="backend",this.init(e,t,n)}return uR(s,[{key:"init",value:function(t){var n=this,a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};if(this.services=t,this.options=Ug(Ug(Ug({},hR()),this.options||{}),a),this.allOptions=i,this.services&&this.options.reloadInterval){var o=setInterval(function(){return n.reload()},this.options.reloadInterval);dc(o)==="object"&&typeof o.unref=="function"&&o.unref()}}},{key:"readMulti",value:function(t,n,a){this._readAny(t,t,n,n,a)}},{key:"read",value:function(t,n,a){this._readAny([t],t,[n],n,a)}},{key:"_readAny",value:function(t,n,a,i,o){var l=this,c=this.options.loadPath;typeof this.options.loadPath=="function"&&(c=this.options.loadPath(t,a)),c=JP(c),c.then(function(d){if(!d)return o(null,{});var m=l.services.interpolator.interpolate(d,{lng:t.join("+"),ns:a.join("+")});l.loadUrl(m,o,n,i)})}},{key:"loadUrl",value:function(t,n,a,i){var o=this,l=typeof a=="string"?[a]:a,c=typeof i=="string"?[i]:i,d=this.options.parseLoadPayload(l,c);this.options.request(this.options,t,d,function(m,p){if(p&&(p.status>=500&&p.status<600||!p.status))return n("failed loading "+t+"; status code: "+p.status,!0);if(p&&p.status>=400&&p.status<500)return n("failed loading "+t+"; status code: "+p.status,!1);if(!p&&m&&m.message){var f=m.message.toLowerCase(),b=["failed","fetch","network","load"].find(function(k){return f.indexOf(k)>-1});if(b)return n("failed loading "+t+": "+m.message,!0)}if(m)return n(m,!1);var y,w;try{typeof p.data=="string"?y=o.options.parse(p.data,a,i):y=p.data}catch{w="failed parsing "+t+" to json"}if(w)return n(w,!1);n(null,y)})}},{key:"create",value:function(t,n,a,i,o){var l=this;if(this.options.addPath){typeof t=="string"&&(t=[t]);var c=this.options.parsePayload(n,a,i),d=0,m=[],p=[];t.forEach(function(f){var b=l.options.addPath;typeof l.options.addPath=="function"&&(b=l.options.addPath(f,n));var y=l.services.interpolator.interpolate(b,{lng:f,ns:n});l.options.request(l.options,y,c,function(w,k){d+=1,m.push(w),p.push(k),d===t.length&&typeof o=="function"&&o(m,p)})})}}},{key:"reload",value:function(){var t=this,n=this.services,a=n.backendConnector,i=n.languageUtils,o=n.logger,l=a.language;if(!(l&&l.toLowerCase()==="cimode")){var c=[],d=function(p){var f=i.toResolveHierarchy(p);f.forEach(function(b){c.indexOf(b)<0&&c.push(b)})};d(l),this.allOptions.preload&&this.allOptions.preload.forEach(function(m){return d(m)}),c.forEach(function(m){t.allOptions.ns.forEach(function(p){a.read(m,p,"read",null,null,function(f,b){f&&o.warn("loading namespace ".concat(p," for language ").concat(m," failed"),f),!f&&b&&o.log("loaded namespace ".concat(p," for language ").concat(m),b),a.loaded("".concat(m,"|").concat(p),f,b)})})})}}}])})();MA.type="backend";const{slice:pR,forEach:mR}=[];function fR(s){return mR.call(pR.call(arguments,1),e=>{if(e)for(const t in e)s[t]===void 0&&(s[t]=e[t])}),s}function gR(s){return typeof s!="string"?!1:[/<\s*script.*?>/i,/<\s*\/\s*script\s*>/i,/<\s*img.*?on\w+\s*=/i,/<\s*\w+\s*on\w+\s*=.*?>/i,/javascript\s*:/i,/vbscript\s*:/i,/expression\s*\(/i,/eval\s*\(/i,/alert\s*\(/i,/document\.cookie/i,/document\.write\s*\(/i,/window\.location/i,/innerHTML/i].some(t=>t.test(s))}const RS=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/,bR=function(s,e){const n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{path:"/"},a=encodeURIComponent(e);let i=`${s}=${a}`;if(n.maxAge>0){const o=n.maxAge-0;if(Number.isNaN(o))throw new Error("maxAge should be a Number");i+=`; Max-Age=${Math.floor(o)}`}if(n.domain){if(!RS.test(n.domain))throw new TypeError("option domain is invalid");i+=`; Domain=${n.domain}`}if(n.path){if(!RS.test(n.path))throw new TypeError("option path is invalid");i+=`; Path=${n.path}`}if(n.expires){if(typeof n.expires.toUTCString!="function")throw new TypeError("option expires is invalid");i+=`; Expires=${n.expires.toUTCString()}`}if(n.httpOnly&&(i+="; HttpOnly"),n.secure&&(i+="; Secure"),n.sameSite)switch(typeof n.sameSite=="string"?n.sameSite.toLowerCase():n.sameSite){case!0:i+="; SameSite=Strict";break;case"lax":i+="; SameSite=Lax";break;case"strict":i+="; SameSite=Strict";break;case"none":i+="; SameSite=None";break;default:throw new TypeError("option sameSite is invalid")}return n.partitioned&&(i+="; Partitioned"),i},LS={create(s,e,t,n){let a=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{path:"/",sameSite:"strict"};t&&(a.expires=new Date,a.expires.setTime(a.expires.getTime()+t*60*1e3)),n&&(a.domain=n),document.cookie=bR(s,e,a)},read(s){const e=`${s}=`,t=document.cookie.split(";");for(let n=0;n<t.length;n++){let a=t[n];for(;a.charAt(0)===" ";)a=a.substring(1,a.length);if(a.indexOf(e)===0)return a.substring(e.length,a.length)}return null},remove(s,e){this.create(s,"",-1,e)}};var yR={name:"cookie",lookup(s){let{lookupCookie:e}=s;if(e&&typeof document<"u")return LS.read(e)||void 0},cacheUserLanguage(s,e){let{lookupCookie:t,cookieMinutes:n,cookieDomain:a,cookieOptions:i}=e;t&&typeof document<"u"&&LS.create(t,s,n,a,i)}},xR={name:"querystring",lookup(s){var n;let{lookupQuerystring:e}=s,t;if(typeof window<"u"){let{search:a}=window.location;!window.location.search&&((n=window.location.hash)==null?void 0:n.indexOf("?"))>-1&&(a=window.location.hash.substring(window.location.hash.indexOf("?")));const o=a.substring(1).split("&");for(let l=0;l<o.length;l++){const c=o[l].indexOf("=");c>0&&o[l].substring(0,c)===e&&(t=o[l].substring(c+1))}}return t}},vR={name:"hash",lookup(s){var a;let{lookupHash:e,lookupFromHashIndex:t}=s,n;if(typeof window<"u"){const{hash:i}=window.location;if(i&&i.length>2){const o=i.substring(1);if(e){const l=o.split("&");for(let c=0;c<l.length;c++){const d=l[c].indexOf("=");d>0&&l[c].substring(0,d)===e&&(n=l[c].substring(d+1))}}if(n)return n;if(!n&&t>-1){const l=i.match(/\/([a-zA-Z-]*)/g);return Array.isArray(l)?(a=l[typeof t=="number"?t:0])==null?void 0:a.replace("/",""):void 0}}}return n}};let zl=null;const OS=()=>{if(zl!==null)return zl;try{if(zl=typeof window<"u"&&window.localStorage!==null,!zl)return!1;const s="i18next.translate.boo";window.localStorage.setItem(s,"foo"),window.localStorage.removeItem(s)}catch{zl=!1}return zl};var wR={name:"localStorage",lookup(s){let{lookupLocalStorage:e}=s;if(e&&OS())return window.localStorage.getItem(e)||void 0},cacheUserLanguage(s,e){let{lookupLocalStorage:t}=e;t&&OS()&&window.localStorage.setItem(t,s)}};let $l=null;const IS=()=>{if($l!==null)return $l;try{if($l=typeof window<"u"&&window.sessionStorage!==null,!$l)return!1;const s="i18next.translate.boo";window.sessionStorage.setItem(s,"foo"),window.sessionStorage.removeItem(s)}catch{$l=!1}return $l};var kR={name:"sessionStorage",lookup(s){let{lookupSessionStorage:e}=s;if(e&&IS())return window.sessionStorage.getItem(e)||void 0},cacheUserLanguage(s,e){let{lookupSessionStorage:t}=e;t&&IS()&&window.sessionStorage.setItem(t,s)}},SR={name:"navigator",lookup(s){const e=[];if(typeof navigator<"u"){const{languages:t,userLanguage:n,language:a}=navigator;if(t)for(let i=0;i<t.length;i++)e.push(t[i]);n&&e.push(n),a&&e.push(a)}return e.length>0?e:void 0}},jR={name:"htmlTag",lookup(s){let{htmlTag:e}=s,t;const n=e||(typeof document<"u"?document.documentElement:null);return n&&typeof n.getAttribute=="function"&&(t=n.getAttribute("lang")),t}},CR={name:"path",lookup(s){var a;let{lookupFromPathIndex:e}=s;if(typeof window>"u")return;const t=window.location.pathname.match(/\/([a-zA-Z-]*)/g);return Array.isArray(t)?(a=t[typeof e=="number"?e:0])==null?void 0:a.replace("/",""):void 0}},NR={name:"subdomain",lookup(s){var a,i;let{lookupFromSubdomainIndex:e}=s;const t=typeof e=="number"?e+1:1,n=typeof window<"u"&&((i=(a=window.location)==null?void 0:a.hostname)==null?void 0:i.match(/^(\w{2,5})\.(([a-z0-9-]{1,63}\.[a-z]{2,6})|localhost)/i));if(n)return n[t]}};let TA=!1;try{document.cookie,TA=!0}catch{}const EA=["querystring","cookie","localStorage","sessionStorage","navigator","htmlTag"];TA||EA.splice(1,1);const AR=()=>({order:EA,lookupQuerystring:"lng",lookupCookie:"i18next",lookupLocalStorage:"i18nextLng",lookupSessionStorage:"i18nextLng",caches:["localStorage"],excludeCacheFor:["cimode"],convertDetectedLanguage:s=>s});class _A{constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.type="languageDetector",this.detectors={},this.init(e,t)}init(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{languageUtils:{}},t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};this.services=e,this.options=fR(t,this.options||{},AR()),typeof this.options.convertDetectedLanguage=="string"&&this.options.convertDetectedLanguage.indexOf("15897")>-1&&(this.options.convertDetectedLanguage=a=>a.replace("-","_")),this.options.lookupFromUrlIndex&&(this.options.lookupFromPathIndex=this.options.lookupFromUrlIndex),this.i18nOptions=n,this.addDetector(yR),this.addDetector(xR),this.addDetector(wR),this.addDetector(kR),this.addDetector(SR),this.addDetector(jR),this.addDetector(CR),this.addDetector(NR),this.addDetector(vR)}addDetector(e){return this.detectors[e.name]=e,this}detect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.options.order,t=[];return e.forEach(n=>{if(this.detectors[n]){let a=this.detectors[n].lookup(this.options);a&&typeof a=="string"&&(a=[a]),a&&(t=t.concat(a))}}),t=t.filter(n=>n!=null&&!gR(n)).map(n=>this.options.convertDetectedLanguage(n)),this.services&&this.services.languageUtils&&this.services.languageUtils.getBestMatchFromCodes?t:t.length>0?t[0]:null}cacheUserLanguage(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.options.caches;t&&(this.options.excludeCacheFor&&this.options.excludeCacheFor.indexOf(e)>-1||t.forEach(n=>{this.detectors[n]&&this.detectors[n].cacheUserLanguage(e,this.options)}))}}_A.type="languageDetector";const Sp={idle:"#4aff9e",working:"#4a9eff",waiting:"#ff9e4a",waiting_permission:"#ffcc00",error:"#ff4a4a",offline:"#888888",orphaned:"#ff9e4a",default:"#888888"},Xr={running:"#4aff9e",stopped:"#888888",error:"#ff4a4a",unknown:"#ffaa00",starting:"#4a9eff",stopping:"#ffaa00"},DA={on_track:"#4aff9e",stalled:"#ff9e4a",blocked:"#ff4a4a",completed:"#4a9eff",idle:"#888888"},MR=["#4a9eff","#4aff9e","#ff9e4a","#ff4a9e","#9e4aff","#ff4a4a","#4affff","#ffff4a","#4ad7ff","#00e6a8","#ff6b4a","#ff66cc","#b84aff","#ff4a7a","#00d9ff","#e6ff4a","#1a3a6e","#1a5e3a","#6e3a1a","#6e1a4a","#4a1a6e","#6e1a1a","#1a5e5e","#5e5e1a","#1a4a6e","#145a47","#6e2c1a","#6e1a5e","#3b1a6e","#6e1a33","#14566e","#4f5e1a"],Lh={recent:"#50fa7b",short:"#f1fa8c",medium:"#ffb86c",long:"#ff5555"};function am(s){const t=Math.floor((Date.now()-s)/1e3)/60;return t<1?Lh.recent:t<5?Lh.short:t<30?Lh.medium:Lh.long}function iy(s){return Sp[s]??Sp.default}let rp=null;function PA(){if(!rp)try{rp=globalThis.__i18n}catch{}return rp}function TR(s){rp=s}function ER(s){return s>=1e6?(s/1e6).toFixed(1)+"M":s>=1e3?(s/1e3).toFixed(1)+"K":s.toString()}function ry(s){return s>=1e6?(s/1e6).toFixed(1)+"M":s>=1e3?(s/1e3).toFixed(1)+"K":s.toString()}function RA(s){var a;const e=PA(),t=(a=e==null?void 0:e.t)==null?void 0:a.bind(e),n=Math.floor((Date.now()-s)/1e3);return n<60?t?t("common:time.seconds",{count:n}):`${n}s`:n<3600?t?t("common:time.minutes",{count:Math.floor(n/60)}):`${Math.floor(n/60)}m`:n<86400?t?t("common:time.hours",{count:Math.floor(n/3600)}):`${Math.floor(n/3600)}h`:t?t("common:time.days",{count:Math.floor(n/86400)}):`${Math.floor(n/86400)}d`}function im(s){var d;const e=PA(),t=(d=e==null?void 0:e.t)==null?void 0:d.bind(e),n=Math.floor((Date.now()-s)/1e3);if(n<5)return t?t("common:time.justNow"):"just now";if(n<60)return t?t("common:time.secondsAgo",{count:n}):`${n}s ago`;const a=Math.floor(n/60);if(a<60){const m=n%60;return m>0?t?t("common:time.minutesSecondsAgo",{minutes:a,seconds:m}):`${a}m ${m}s ago`:t?t("common:time.minutesAgo",{count:a}):`${a}m ago`}const i=Math.floor(a/60),o=a%60;if(i<24)return o>0?t?t("common:time.hoursMinutesAgo",{hours:i,minutes:o}):`${i}h ${o}m ago`:t?t("common:time.hoursAgo",{count:i}):`${i}h ago`;const l=Math.floor(i/24),c=i%24;return c>0?t?t("common:time.daysHoursAgo",{days:l,hours:c}):`${l}d ${c}h ago`:t?t("common:time.daysAgo",{count:l}):`${l}d ago`}function Gr(s,e){return s?e?s.replace(/\s*\(?\s*~?\$[\d,.]+\s*\)?/g,"").replace(/\s*cost[:\s]+~?\$[\d,.]+/gi,"").replace(/\s*price[:\s]+~?\$[\d,.]+/gi,"").replace(/\s*\(~?\$[\d,.]+\s*(?:USD|cost|spent)?\)/gi,"").replace(/\s*-\s*~?\$[\d,.]+\s*$/g,"").replace(/[^\S\n]+/g," ").trim():s:""}yn.use(MA).use(_A).use(UP).init({fallbackLng:"en",ns:["common","tools","config","errors","notifications","dashboard","terminal"],defaultNS:"common",backend:{loadPath:"/locales/{{lng}}/{{ns}}.json"},detection:{order:["localStorage","navigator"],lookupLocalStorage:"tide-commander-language",caches:["localStorage"]},interpolation:{escapeValue:!1},react:{useSuspense:!0}}).then(()=>{TR(yn)});const pt={CONFIG:"tide-commander-config",SHOW_FPS:"tide-show-fps",SETTINGS:"tide-settings",SHORTCUTS:"tide-shortcuts",MOUSE_CONTROLS:"tide-mouse-controls",BACKEND_URL:"tide-backend-url",AUTH_TOKEN:"tide-auth-token",SCENE_VIEW_MODE:"tide-scene-view-mode",CAMERA_STATE:"tide-camera-state",CAMERA_STATE_2D:"tide-camera-state-2d",VIEW_MODE:"guake-view-mode",ADVANCED_VIEW:"guake-advanced-view",TERMINAL_HEIGHT:"guake-terminal-height",INPUT_TEXT_PREFIX:"guake-input-",PASTED_TEXTS_PREFIX:"guake-pasted-",COMMANDER_TAB:"commander-active-tab",COMMANDER_FILTERS:"commander-filters",LAST_CWD:"tide-last-cwd",GLOBAL_SUPERVISOR_COLLAPSED:"tide-global-supervisor-collapsed",TOOLS_COLLAPSED:"tide-tool-history-collapsed",FILES_COLLAPSED:"tide-file-history-collapsed",MOBILE_VIEW:"tide-mobile-view",TREE_PANEL_WIDTH:"tide-tree-panel-width",AGENT_ORDER:"tide-agent-order",AOP_CONFIG:"tide-aop-config",UNSEEN_AGENTS:"tide-unseen-agents"};function Ya(s,e){try{const t=localStorage.getItem(s);return t===null?e:JSON.parse(t)}catch{return e}}function As(s,e=""){try{return localStorage.getItem(s)??e}catch{return e}}function oy(s,e=!1){try{const t=localStorage.getItem(s);return t===null?e:t==="true"}catch{return e}}function LA(s,e){try{const t=localStorage.getItem(s);if(t===null)return e;const n=Number(t);return isNaN(n)?e:n}catch{return e}}function yi(s,e){try{localStorage.setItem(s,JSON.stringify(e))}catch(t){console.error(`Failed to save to localStorage: ${s}`,t)}}function ta(s,e){try{localStorage.setItem(s,e)}catch(t){console.error(`Failed to save to localStorage: ${s}`,t)}}function ly(s,e){try{localStorage.setItem(s,String(e))}catch(t){console.error(`Failed to save to localStorage: ${s}`,t)}}function OA(s,e){try{localStorage.setItem(s,String(e))}catch(t){console.error(`Failed to save to localStorage: ${s}`,t)}}function BS(s){try{localStorage.removeItem(s)}catch(e){console.error(`Failed to remove from localStorage: ${s}`,e)}}function IA(){const s=As(pt.BACKEND_URL,"");return s?s.replace(/\/$/,""):`${window.location.protocol}//${window.location.host}`}function ti(){return As(pt.AUTH_TOKEN,"")}function st(s){return`${IA()}${s}`}async function mt(s,e){const t=ti(),n=new Headers(e==null?void 0:e.headers);return t&&n.set("X-Auth-Token",t),fetch(s,{...e,headers:n})}function hd(s){const e=ti();if(!e)return s;try{const t=!s.startsWith("http://")&&!s.startsWith("https://"),n=t?"http://dummy":void 0,a=new URL(s,n);return a.searchParams.set("token",e),t?a.pathname+a.search:a.toString()}catch{const t=s.includes("?")?"&":"?";return`${s}${t}token=${encodeURIComponent(e)}`}}function Bs(s=!1,e){const[t,n]=x.useState(s),[a,i]=x.useState(e),o=x.useCallback(d=>{d!==void 0&&i(d),n(!0)},[]),l=x.useCallback(()=>{n(!1)},[]),c=x.useCallback(()=>{n(d=>!d)},[]);return{isOpen:t,data:a,open:o,close:l,toggle:c,setData:i}}function _R(){const[s,e]=x.useState(null),t=x.useCallback(a=>{e(a)},[]),n=x.useCallback(()=>{e(null)},[]);return{isOpen:s!==null,id:s,open:t,close:n}}function DR(){const[s,e]=x.useState(!1),[t,n]=x.useState({x:0,y:0}),[a,i]=x.useState({x:0,z:0}),[o,l]=x.useState({type:"ground"}),c=x.useCallback((m,p,f)=>{n(m),i(p),l(f),e(!0)},[]),d=x.useCallback(()=>{e(!1)},[]);return{isOpen:s,screenPosition:t,worldPosition:a,target:o,open:c,close:d}}const qa=[],PR=new Set;function jp(){PR.forEach(s=>s())}function RR(s,e){const t=qa.findIndex(n=>n.id===s);return t!==-1&&qa.splice(t,1),qa.push({id:s,close:e}),jp(),()=>{const n=qa.findIndex(a=>a.id===s);n!==-1&&(qa.splice(n,1),jp())}}function cy(){return qa.length===0?!1:(qa.pop().close(),jp(),!0)}function LR(...s){const e=new Set(s);for(;qa.length>0;){const t=qa[qa.length-1];if(e.has(t.id))break;qa.pop().close()}jp()}function Pn(s,e,t){const n=x.useRef(t);n.current=t,x.useEffect(()=>e?RR(s,()=>n.current()):void 0,[s,e])}let uy,dy;try{uy=require("@capacitor/haptics").Haptics,dy=require("@capacitor/haptics").ImpactStyle}catch{}function FS(s,e){const{threshold:t=80,maxVerticalMovement:n=50,enabled:a=!0,onSwipeLeft:i,onSwipeRight:o,onSwipeMove:l,onSwipeCancel:c}=e,d=x.useRef({startX:0,startY:0,startTime:0,isTracking:!1,hasMovedEnough:!1}),m=x.useCallback(b=>{if(b.touches.length!==1)return;const y=b.touches[0];d.current={startX:y.clientX,startY:y.clientY,startTime:Date.now(),isTracking:!0,hasMovedEnough:!1}},[]),p=x.useCallback(b=>{if(!d.current.isTracking||b.touches.length!==1)return;const y=b.touches[0],w=y.clientX-d.current.startX;if(Math.abs(y.clientY-d.current.startY)>n){d.current.isTracking=!1,d.current.hasMovedEnough&&(c==null||c());return}const j=window.innerWidth*.4,C=Math.max(-1,Math.min(1,w/j));Math.abs(w)>=12&&(d.current.hasMovedEnough=!0,l==null||l(C))},[n,l,c]),f=x.useCallback(b=>{const y=d.current.isTracking,w=d.current.hasMovedEnough;if(!y)return;const k=b.changedTouches[0],S=k.clientX-d.current.startX,j=Math.abs(k.clientY-d.current.startY),C=Date.now()-d.current.startTime;d.current.isTracking=!1,d.current.hasMovedEnough=!1,Math.abs(S)>=t&&j<=n&&C<500?(uy&&dy?uy.impact({style:dy.Light}).catch(()=>{navigator.vibrate&&navigator.vibrate(8)}):navigator.vibrate&&navigator.vibrate(8),S>0?o==null||o():i==null||i()):w&&(c==null||c())},[t,n,i,o,c]);x.useEffect(()=>{const b=s.current;if(!(!b||!a||!(window.innerWidth<=768&&"ontouchstart"in window)))return b.addEventListener("touchstart",m,{passive:!0}),b.addEventListener("touchmove",p,{passive:!0}),b.addEventListener("touchend",f,{passive:!0}),()=>{b.removeEventListener("touchstart",m),b.removeEventListener("touchmove",p),b.removeEventListener("touchend",f)}},[s,a,m,p,f])}const OR={width:400,height:300,copyStyleSheets:!0,keepOnTop:"focus"};function IR(){return"documentPictureInPicture"in window}function BR(s,e){for(const i of s.styleSheets)try{if(i.cssRules){const o=e.createElement("style");for(const l of i.cssRules)o.appendChild(e.createTextNode(l.cssText));e.head.appendChild(o)}}catch{if(i.href){const o=e.createElement("link");o.rel="stylesheet",o.href=i.href,e.head.appendChild(o)}}const t=s.documentElement.style.cssText;t&&(e.documentElement.style.cssText=t);const n=getComputedStyle(s.documentElement),a=[];for(let i=0;i<n.length;i++){const o=n[i];o.startsWith("--")&&a.push(`${o}: ${n.getPropertyValue(o)}`)}if(a.length>0){const i=e.createElement("style");i.textContent=`:root { ${a.join("; ")} }`,e.head.appendChild(i)}}function FR(){const[s,e]=x.useState(!1),[t,n]=x.useState(null),[a,i]=x.useState(null),o=x.useRef(null),l=IR(),c=x.useCallback(()=>{if(o.current){const p=o.current.__cleanupFns;p&&p.forEach(f=>f()),o.current.close(),o.current=null}n(null),i(null),e(!1)},[]),d=x.useCallback(async p=>{if(!l)return console.warn("Document Picture-in-Picture is not supported in this browser"),!1;o.current&&c();const f={...OR,...p};try{const y=await window.documentPictureInPicture.requestWindow({width:f.width,height:f.height,disallowReturnToOpener:!0});o.current=y,f.copyStyleSheets&&BR(document,y.document);const w=y.document.createElement("div");w.id="pip-root",w.style.width="100%",w.style.height="100%",y.document.body.appendChild(w),y.document.body.style.margin="0",y.document.body.style.padding="0",y.document.body.style.overflow="hidden",y.addEventListener("pagehide",()=>{o.current=null,n(null),i(null),e(!1)});const k=[];if(f.keepOnTop&&f.keepOnTop!=="none"){const S=f.keepOnTop==="raise",j=()=>{o.current&&!o.current.closed&&setTimeout(()=>{o.current&&!o.current.closed&&(o.current.focus(),S&&setTimeout(()=>window.focus(),10))},50)},C=()=>{document.visibilityState==="visible"&&o.current&&!o.current.closed&&setTimeout(()=>{o.current&&!o.current.closed&&(o.current.focus(),S&&setTimeout(()=>window.focus(),10))},100)};window.addEventListener("focus",j),document.addEventListener("visibilitychange",C),k.push(()=>window.removeEventListener("focus",j),()=>document.removeEventListener("visibilitychange",C))}return y.__cleanupFns=k,n(y),i(w),e(!0),!0}catch(b){return console.error("Failed to open Picture-in-Picture window:",b),!1}},[l,c]),m=x.useCallback(async p=>{s?c():await d(p)},[s,d,c]);return x.useEffect(()=>()=>{o.current&&o.current.close()},[]),{isOpen:s,pipWindow:t,pipContainer:a,isSupported:l,open:d,close:c,toggle:m}}function vu(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,s=>{const e=Math.random()*16|0;return(s==="x"?e:e&3|8).toString(16)})}class zR{constructor(){W(this,"messages",new Map);W(this,"logs",[]);W(this,"maxMessagesPerAgent",200);W(this,"maxLogs",500);W(this,"enabled",!1);W(this,"listeners",new Set);W(this,"logListeners",new Set)}setEnabled(e){this.enabled=e,this.notifyListeners("all")}isEnabled(){return this.enabled}captureSent(e,t){if(this.enabled)try{const n=JSON.parse(t);console.log(`[AgentDebugger] SENT - agent: ${e.slice(0,4)}, type: ${n.type}, size: ${t.length}B`),this.addMessage(e,{id:vu(),agentId:e,direction:"sent",type:n.type||"unknown",payload:n.payload||n,timestamp:Date.now(),size:t.length,raw:t})}catch(n){console.error("[AgentDebugger] Failed to parse SENT message:",String(n).slice(0,80)),this.addMessage(e,{id:vu(),agentId:e,direction:"sent",type:"parse_error",payload:{error:String(n)},timestamp:Date.now(),size:t.length,raw:t})}}captureReceived(e,t){if(this.enabled)try{const n=JSON.parse(t);console.log(`[AgentDebugger] RECEIVED - agent: ${e.slice(0,4)}, type: ${n.type}, size: ${t.length}B`),this.addMessage(e,{id:vu(),agentId:e,direction:"received",type:n.type||"unknown",payload:n.payload||n,timestamp:Date.now(),size:t.length,raw:t})}catch(n){console.error("[AgentDebugger] Failed to parse RECEIVED message:",String(n).slice(0,80)),this.addMessage(e,{id:vu(),agentId:e,direction:"received",type:"parse_error",payload:{error:String(n)},timestamp:Date.now(),size:t.length,raw:t})}}addMessage(e,t){let n=this.messages.get(e);n||(n=[],this.messages.set(e,n)),n.push(t),console.log(`[AgentDebugger] Added message for ${e}, total: ${n.length}, type: ${t.type}, direction: ${t.direction}`),n.length>this.maxMessagesPerAgent&&n.shift(),this.notifyListeners(e)}getMessages(e){return this.messages.get(e)||[]}getStats(e){const t=this.getMessages(e),n=t.filter(o=>o.direction==="sent").length,a=t.filter(o=>o.direction==="received").length,i=[...new Set(t.map(o=>o.type))];return{total:t.length,sent:n,received:a,messageTypes:i}}clearMessages(e){this.messages.delete(e),this.notifyListeners(e)}clearAllMessages(){this.messages.clear(),this.notifyListeners("all")}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}notifyListeners(e){this.listeners.forEach(t=>t(e))}getAgentIds(){return Array.from(this.messages.keys())}log(e,t,n,a){const i={id:vu(),level:e,message:t,data:n,timestamp:Date.now(),source:a};this.logs.push(i),this.logs.length>this.maxLogs&&this.logs.shift(),this.notifyLogListeners()}debug(e,t,n){this.log("debug",e,t,n)}info(e,t,n){this.log("info",e,t,n)}warn(e,t,n){this.log("warn",e,t,n)}error(e,t,n){this.log("error",e,t,n)}getLogs(){return this.logs}clearLogs(){this.logs=[],this.notifyLogListeners()}subscribeLogs(e){return this.logListeners.add(e),()=>this.logListeners.delete(e)}notifyLogListeners(){this.logListeners.forEach(e=>e())}}const vs=new zR,td={debug:(s,e,t)=>vs.debug(s,e,t),info:(s,e,t)=>vs.info(s,e,t),warn:(s,e,t)=>vs.warn(s,e,t),error:(s,e,t)=>vs.error(s,e,t)};/*! Capacitor: https://capacitorjs.com/ - MIT License */var hc;(function(s){s.Unimplemented="UNIMPLEMENTED",s.Unavailable="UNAVAILABLE"})(hc||(hc={}));class Gg extends Error{constructor(e,t,n){super(e),this.message=e,this.code=t,this.data=n}}const $R=s=>{var e,t;return s!=null&&s.androidBridge?"android":!((t=(e=s==null?void 0:s.webkit)===null||e===void 0?void 0:e.messageHandlers)===null||t===void 0)&&t.bridge?"ios":"web"},HR=s=>{const e=s.CapacitorCustomPlatform||null,t=s.Capacitor||{},n=t.Plugins=t.Plugins||{},a=()=>e!==null?e.name:$R(s),i=()=>a()!=="web",o=p=>{const f=d.get(p);return!!(f!=null&&f.platforms.has(a())||l(p))},l=p=>{var f;return(f=t.PluginHeaders)===null||f===void 0?void 0:f.find(b=>b.name===p)},c=p=>s.console.error(p),d=new Map,m=(p,f={})=>{const b=d.get(p);if(b)return console.warn(`Capacitor plugin "${p}" already registered. Cannot register plugins twice.`),b.proxy;const y=a(),w=l(p);let k;const S=async()=>(!k&&y in f?k=typeof f[y]=="function"?k=await f[y]():k=f[y]:e!==null&&!k&&"web"in f&&(k=typeof f.web=="function"?k=await f.web():k=f.web),k),j=(E,_)=>{var P,L;if(w){const R=w==null?void 0:w.methods.find(z=>_===z.name);if(R)return R.rtype==="promise"?z=>t.nativePromise(p,_.toString(),z):(z,F)=>t.nativeCallback(p,_.toString(),z,F);if(E)return(P=E[_])===null||P===void 0?void 0:P.bind(E)}else{if(E)return(L=E[_])===null||L===void 0?void 0:L.bind(E);throw new Gg(`"${p}" plugin is not implemented on ${y}`,hc.Unimplemented)}},C=E=>{let _;const P=(...L)=>{const R=S().then(z=>{const F=j(z,E);if(F){const $=F(...L);return _=$==null?void 0:$.remove,$}else throw new Gg(`"${p}.${E}()" is not implemented on ${y}`,hc.Unimplemented)});return E==="addListener"&&(R.remove=async()=>_()),R};return P.toString=()=>`${E.toString()}() { [capacitor code] }`,Object.defineProperty(P,"name",{value:E,writable:!1,configurable:!1}),P},A=C("addListener"),D=C("removeListener"),M=(E,_)=>{const P=A({eventName:E},_),L=async()=>{const z=await P;D({eventName:E,callbackId:z},_)},R=new Promise(z=>P.then(()=>z({remove:L})));return R.remove=async()=>{console.warn("Using addListener() without 'await' is deprecated."),await L()},R},I=new Proxy({},{get(E,_){switch(_){case"$$typeof":return;case"toJSON":return()=>({});case"addListener":return w?M:A;case"removeListener":return D;default:return C(_)}}});return n[p]=I,d.set(p,{name:p,proxy:I,platforms:new Set([...Object.keys(f),...w?[y]:[]])}),I};return t.convertFileSrc||(t.convertFileSrc=p=>p),t.getPlatform=a,t.handleError=c,t.isNativePlatform=i,t.isPluginAvailable=o,t.registerPlugin=m,t.Exception=Gg,t.DEBUG=!!t.DEBUG,t.isLoggingEnabled=!!t.isLoggingEnabled,t},UR=s=>s.Capacitor=HR(s),ba=UR(typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{}),pd=ba.registerPlugin;class rx{constructor(){this.listeners={},this.retainedEventArguments={},this.windowListeners={}}addListener(e,t){let n=!1;this.listeners[e]||(this.listeners[e]=[],n=!0),this.listeners[e].push(t);const i=this.windowListeners[e];i&&!i.registered&&this.addWindowListener(i),n&&this.sendRetainedArgumentsForEvent(e);const o=async()=>this.removeListener(e,t);return Promise.resolve({remove:o})}async removeAllListeners(){this.listeners={};for(const e in this.windowListeners)this.removeWindowListener(this.windowListeners[e]);this.windowListeners={}}notifyListeners(e,t,n){const a=this.listeners[e];if(!a){if(n){let i=this.retainedEventArguments[e];i||(i=[]),i.push(t),this.retainedEventArguments[e]=i}return}a.forEach(i=>i(t))}hasListeners(e){var t;return!!(!((t=this.listeners[e])===null||t===void 0)&&t.length)}registerWindowListener(e,t){this.windowListeners[t]={registered:!1,windowEventName:e,pluginEventName:t,handler:n=>{this.notifyListeners(t,n)}}}unimplemented(e="not implemented"){return new ba.Exception(e,hc.Unimplemented)}unavailable(e="not available"){return new ba.Exception(e,hc.Unavailable)}async removeListener(e,t){const n=this.listeners[e];if(!n)return;const a=n.indexOf(t);this.listeners[e].splice(a,1),this.listeners[e].length||this.removeWindowListener(this.windowListeners[e])}addWindowListener(e){window.addEventListener(e.windowEventName,e.handler),e.registered=!0}removeWindowListener(e){e&&(window.removeEventListener(e.windowEventName,e.handler),e.registered=!1)}sendRetainedArgumentsForEvent(e){const t=this.retainedEventArguments[e];t&&(delete this.retainedEventArguments[e],t.forEach(n=>{this.notifyListeners(e,n)}))}}const zS=s=>encodeURIComponent(s).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape),$S=s=>s.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent);class GR extends rx{async getCookies(){const e=document.cookie,t={};return e.split(";").forEach(n=>{if(n.length<=0)return;let[a,i]=n.replace(/=/,"CAP_COOKIE").split("CAP_COOKIE");a=$S(a).trim(),i=$S(i).trim(),t[a]=i}),t}async setCookie(e){try{const t=zS(e.key),n=zS(e.value),a=e.expires?`; expires=${e.expires.replace("expires=","")}`:"",i=(e.path||"/").replace("path=",""),o=e.url!=null&&e.url.length>0?`domain=${e.url}`:"";document.cookie=`${t}=${n||""}${a}; path=${i}; ${o};`}catch(t){return Promise.reject(t)}}async deleteCookie(e){try{document.cookie=`${e.key}=; Max-Age=0`}catch(t){return Promise.reject(t)}}async clearCookies(){try{const e=document.cookie.split(";")||[];for(const t of e)document.cookie=t.replace(/^ +/,"").replace(/=.*/,`=;expires=${new Date().toUTCString()};path=/`)}catch(e){return Promise.reject(e)}}async clearAllCookies(){try{await this.clearCookies()}catch(e){return Promise.reject(e)}}}pd("CapacitorCookies",{web:()=>new GR});const WR=async s=>new Promise((e,t)=>{const n=new FileReader;n.onload=()=>{const a=n.result;e(a.indexOf(",")>=0?a.split(",")[1]:a)},n.onerror=a=>t(a),n.readAsDataURL(s)}),qR=(s={})=>{const e=Object.keys(s);return Object.keys(s).map(a=>a.toLocaleLowerCase()).reduce((a,i,o)=>(a[i]=s[e[o]],a),{})},YR=(s,e=!0)=>s?Object.entries(s).reduce((n,a)=>{const[i,o]=a;let l,c;return Array.isArray(o)?(c="",o.forEach(d=>{l=e?encodeURIComponent(d):d,c+=`${i}=${l}&`}),c.slice(0,-1)):(l=e?encodeURIComponent(o):o,c=`${i}=${l}`),`${n}&${c}`},"").substr(1):null,VR=(s,e={})=>{const t=Object.assign({method:s.method||"GET",headers:s.headers},e),a=qR(s.headers)["content-type"]||"";if(typeof s.data=="string")t.body=s.data;else if(a.includes("application/x-www-form-urlencoded")){const i=new URLSearchParams;for(const[o,l]of Object.entries(s.data||{}))i.set(o,l);t.body=i.toString()}else if(a.includes("multipart/form-data")||s.data instanceof FormData){const i=new FormData;if(s.data instanceof FormData)s.data.forEach((l,c)=>{i.append(c,l)});else for(const l of Object.keys(s.data))i.append(l,s.data[l]);t.body=i;const o=new Headers(t.headers);o.delete("content-type"),t.headers=o}else(a.includes("application/json")||typeof s.data=="object")&&(t.body=JSON.stringify(s.data));return t};class KR extends rx{async request(e){const t=VR(e,e.webFetchExtra),n=YR(e.params,e.shouldEncodeUrlParams),a=n?`${e.url}?${n}`:e.url,i=await fetch(a,t),o=i.headers.get("content-type")||"";let{responseType:l="text"}=i.ok?e:{};o.includes("application/json")&&(l="json");let c,d;switch(l){case"arraybuffer":case"blob":d=await i.blob(),c=await WR(d);break;case"json":c=await i.json();break;case"document":case"text":default:c=await i.text()}const m={};return i.headers.forEach((p,f)=>{m[f]=p}),{data:c,headers:m,status:i.status,url:i.url}}async get(e){return this.request(Object.assign(Object.assign({},e),{method:"GET"}))}async post(e){return this.request(Object.assign(Object.assign({},e),{method:"POST"}))}async put(e){return this.request(Object.assign(Object.assign({},e),{method:"PUT"}))}async patch(e){return this.request(Object.assign(Object.assign({},e),{method:"PATCH"}))}async delete(e){return this.request(Object.assign(Object.assign({},e),{method:"DELETE"}))}}const HS=pd("CapacitorHttp",{web:()=>new KR});var US;(function(s){s.Dark="DARK",s.Light="LIGHT",s.Default="DEFAULT"})(US||(US={}));var GS;(function(s){s.StatusBar="StatusBar",s.NavigationBar="NavigationBar"})(GS||(GS={}));class XR extends rx{async setStyle(){this.unavailable("not available for web")}async setAnimation(){this.unavailable("not available for web")}async show(){this.unavailable("not available for web")}async hide(){this.unavailable("not available for web")}}pd("SystemBars",{web:()=>new XR});var WS;(function(s){s[s.Sunday=1]="Sunday",s[s.Monday=2]="Monday",s[s.Tuesday=3]="Tuesday",s[s.Wednesday=4]="Wednesday",s[s.Thursday=5]="Thursday",s[s.Friday=6]="Friday",s[s.Saturday=7]="Saturday"})(WS||(WS={}));const ox=pd("LocalNotifications",{web:()=>CA(()=>import("./web-DNsSwQTa.js"),__vite__mapDeps([2,3,1,4])).then(s=>new s.LocalNotificationsWeb)}),ZR=pd("ServerConfig");let QR=100;const JR="agent_alerts",hy="tide-notification-tap";function eL(){return typeof window<"u"&&window.innerWidth<=768&&"ontouchstart"in window}function BA(s){if(eL()){H.openTerminalOnMobile(s);return}H.selectAgent(s),H.setTerminalOpen(!0)}function md(){try{return ba.isNativePlatform()}catch{return!1}}async function tL(){if(md())try{const s=await ox.requestPermissions();return console.log("[Notifications] Permission result:",s.display),s.display==="granted"}catch(s){return console.error("[Notifications] Failed to request permissions:",s),!1}else return"Notification"in window?await Notification.requestPermission()==="granted":!1}async function nL(s){const{title:e,body:t,icon:n,data:a}=s;if(md())try{const i=QR++;console.log("[Notifications] Scheduling native notification id="+i,e),await ox.schedule({notifications:[{id:i,title:e,body:t,extra:a,channelId:JR,smallIcon:"ic_launcher",autoCancel:!0}]}),console.log("[Notifications] Notification scheduled successfully")}catch(i){console.error("[Notifications] Failed to schedule notification:",i)}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(hy,{detail:a}))}}}let Wg=!1;async function sL(s){const e=[];if(Wg)return()=>{};if(Wg=!0,s){const t=n=>{const a=n;a.detail&&s(a.detail)};window.addEventListener(hy,t),e.push(()=>window.removeEventListener(hy,t))}if(md())try{const t=await ox.addListener("localNotificationActionPerformed",n=>{s&&n.notification.extra&&s(n.notification.extra)});e.push(()=>t.remove())}catch(t){console.error("[Notifications] Failed to add tap listener:",t)}return()=>{e.forEach(t=>t()),Wg=!1}}function aL(s,e){md()&&ZR.syncConfig({url:s,token:e}).catch(t=>{console.warn("[Notifications] Failed to sync config to native service:",t)})}window.__tideWsState||(window.__tideWsState={ws:null,isConnecting:!1,reconnectAttempts:0,reconnectTimeout:null});const lx=()=>window.__tideWsState.ws,qS=s=>{window.__tideWsState.ws=s},iL=()=>window.__tideWsState.isConnecting,wu=s=>{window.__tideWsState.isConnecting=s},py=()=>window.__tideWsState.reconnectAttempts,my=s=>{window.__tideWsState.reconnectAttempts=s},FA=()=>window.__tideWsState.reconnectTimeout,zA=s=>{window.__tideWsState.reconnectTimeout=s},YS=10,cx="tide_ws_has_connected";function VS(){return sessionStorage.getItem(cx)==="true"}function rL(s){sessionStorage.setItem(cx,"true")}function oL(){sessionStorage.removeItem(cx)}let $A=null;const lL=s=>{$A=s},KS=()=>$A,$e={onToast:null,onAgentCreated:null,onAgentUpdated:null,onAgentDeleted:null,onAgentsSync:null,onAreasSync:null,onSpawnError:null,onSpawnSuccess:null,onToolUse:null,onDirectoryNotFound:null,onDelegation:null,onCustomClassesSync:null,onReconnect:null,onAgentNotification:null,onBuildingUpdated:null,onSubagentStarted:null,onSubagentCompleted:null};function HA(s){s.onToast&&($e.onToast=s.onToast),s.onAgentCreated&&($e.onAgentCreated=s.onAgentCreated),s.onAgentUpdated&&($e.onAgentUpdated=s.onAgentUpdated),s.onAgentDeleted&&($e.onAgentDeleted=s.onAgentDeleted),s.onAgentsSync&&($e.onAgentsSync=s.onAgentsSync),s.onAreasSync&&($e.onAreasSync=s.onAreasSync),s.onSpawnError&&($e.onSpawnError=s.onSpawnError),s.onSpawnSuccess&&($e.onSpawnSuccess=s.onSpawnSuccess),s.onToolUse&&($e.onToolUse=s.onToolUse),s.onDirectoryNotFound&&($e.onDirectoryNotFound=s.onDirectoryNotFound),s.onDelegation&&($e.onDelegation=s.onDelegation),s.onCustomClassesSync&&($e.onCustomClassesSync=s.onCustomClassesSync),s.onReconnect&&($e.onReconnect=s.onReconnect),s.onAgentNotification&&($e.onAgentNotification=s.onAgentNotification),s.onBuildingUpdated&&($e.onBuildingUpdated=s.onBuildingUpdated),s.onSubagentStarted&&($e.onSubagentStarted=s.onSubagentStarted),s.onSubagentCompleted&&($e.onSubagentCompleted=s.onSubagentCompleted)}function cL(){$e.onToast=null,$e.onAgentCreated=null,$e.onAgentUpdated=null,$e.onAgentDeleted=null,$e.onAgentsSync=null,$e.onAreasSync=null,$e.onSpawnError=null,$e.onSpawnSuccess=null,$e.onToolUse=null,$e.onDirectoryNotFound=null,$e.onDelegation=null,$e.onCustomClassesSync=null,$e.onReconnect=null,$e.onAgentNotification=null,$e.onSubagentStarted=null,$e.onSubagentCompleted=null}function uL(){$e.onAgentCreated=null,$e.onAgentUpdated=null,$e.onAgentDeleted=null,$e.onAgentsSync=null,$e.onAreasSync=null,$e.onToolUse=null,$e.onDelegation=null,$e.onCustomClassesSync=null,$e.onBuildingUpdated=null,$e.onSubagentStarted=null,$e.onSubagentCompleted=null}const Oh=new Map,dL=new Map,fy={start(s){},end(s){},async measure(s,e){this.start(s);try{return await e()}finally{this.end(s)}},measureSync(s,e){this.start(s);try{return e()}finally{this.end(s)}},getMetrics(s){const e={},t=s?Oh.has(s)?[[s,Oh.get(s)]]:[]:Array.from(Oh.entries());for(const[n,a]of t){const i=[...a.samples].sort((d,m)=>d-m),o=Math.floor(i.length*.5),l=Math.floor(i.length*.95),c=Math.floor(i.length*.99);e[n]={count:a.count,avgMs:a.totalMs/a.count,minMs:a.minMs,maxMs:a.maxMs,lastMs:a.lastMs,p50Ms:i[o]||0,p95Ms:i[l]||0,p99Ms:i[c]||0}}return e},clear(){Oh.clear(),dL.clear()},report(){}};class hL{constructor(){W(this,"frames",[]);W(this,"lastFrameTime",0);W(this,"frameCount",0);W(this,"fps",0);W(this,"minFps",1/0);W(this,"maxFps",0);W(this,"fpsHistory",[]);W(this,"maxHistorySize",60)}tick(e=200){const t=performance.now();if(this.lastFrameTime>0){const n=t-this.lastFrameTime;n<e&&(this.frames.push(n),this.frames.length>60&&this.frames.shift())}this.lastFrameTime=t,this.frameCount++}update(){if(this.frames.length===0)return;const e=this.frames.reduce((t,n)=>t+n,0)/this.frames.length;this.fps=1e3/e,this.minFps=Math.min(this.minFps,this.fps),this.maxFps=Math.max(this.maxFps,this.fps),this.fpsHistory.push(this.fps),this.fpsHistory.length>this.maxHistorySize&&this.fpsHistory.shift()}getFPS(){return Math.round(this.fps)}getStats(){const e=this.fpsHistory.length>0?this.fpsHistory.reduce((t,n)=>t+n,0)/this.fpsHistory.length:this.fps;return{current:Math.round(this.fps),min:Math.round(this.minFps===1/0?0:this.minFps),max:Math.round(this.maxFps),avg:Math.round(e)}}reset(){this.frames=[],this.lastFrameTime=0,this.frameCount=0,this.fps=0,this.minFps=1/0,this.maxFps=0,this.fpsHistory=[]}}const Jl=new hL;class pL{constructor(){W(this,"snapshots",[]);W(this,"maxSnapshots",120);W(this,"intervalId",null);W(this,"leakThresholdMB",50);W(this,"baselineUsedMB",0)}getUsage(){const e=performance.memory;return e?{usedMB:Math.round(e.usedJSHeapSize/1024/1024),totalMB:Math.round(e.totalJSHeapSize/1024/1024),limitMB:Math.round(e.jsHeapSizeLimit/1024/1024)}:null}log(){const e=this.getUsage();e&&console.log(`[Memory] Used: ${e.usedMB}MB / ${e.totalMB}MB (limit: ${e.limitMB}MB)`)}startMonitoring(e=1e3){if(this.intervalId)return;const t=this.getUsage();t&&(this.baselineUsedMB=t.usedMB),this.intervalId=setInterval(()=>{this.takeSnapshot()},e),console.log("[Memory] Monitoring started. Use memory.report() to see analysis.")}stopMonitoring(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null,console.log("[Memory] Monitoring stopped."))}takeSnapshot(){const e=this.getUsage();if(!e)return;const t={timestamp:Date.now(),heapUsedMB:e.usedMB,heapTotalMB:e.totalMB,heapLimitMB:e.limitMB};this.snapshots.push(t),this.snapshots.length>this.maxSnapshots&&this.snapshots.shift();const n=e.usedMB-this.baselineUsedMB;n>this.leakThresholdMB&&console.warn(`[Memory] Warning: Heap grew by ${n}MB since monitoring started (baseline: ${this.baselineUsedMB}MB, current: ${e.usedMB}MB)`)}getGrowthRate(){if(this.snapshots.length<10)return null;const e=this.snapshots[0],t=this.snapshots[this.snapshots.length-1],n=(t.timestamp-e.timestamp)/1e3/60;return n<.1?null:(t.heapUsedMB-e.heapUsedMB)/n}report(){const e=this.getUsage();if(!e){console.log("[Memory] Memory API not available (Chrome only)");return}console.group("%c[Memory Report]","color: #ff6600; font-weight: bold"),console.log(`Current: ${e.usedMB}MB / ${e.totalMB}MB (limit: ${e.limitMB}MB)`),console.log(`Baseline: ${this.baselineUsedMB}MB`),console.log(`Growth: ${e.usedMB-this.baselineUsedMB}MB since monitoring started`);const t=this.getGrowthRate();if(t!==null&&(console.log(`Growth Rate: ${t.toFixed(2)}MB/min`),t>5&&console.warn("POTENTIAL MEMORY LEAK: Growth rate exceeds 5MB/min")),this.snapshots.length>1){const n=Math.min(...this.snapshots.map(i=>i.heapUsedMB)),a=Math.max(...this.snapshots.map(i=>i.heapUsedMB));console.log(`Range: ${n}MB - ${a}MB (${a-n}MB variance)`)}console.groupEnd()}getThreeJsInfo(e){var t;return(t=e==null?void 0:e.info)!=null&&t.memory?{geometries:e.info.memory.geometries,textures:e.info.memory.textures}:null}reset(){this.snapshots=[];const e=this.getUsage();e&&(this.baselineUsedMB=e.usedMB),console.log("[Memory] Reset. New baseline:",this.baselineUsedMB,"MB")}}const Kl=new pL;function Ou(s,e,t,n,a,i){}function UA(s){if(s.payload&&typeof s.payload=="object"){const e=s.payload;if(e.agentId)return e.agentId;if(e.id)return e.id}return null}function ux(s){var t,n,a,i,o,l;const e=lx();if(!e){(t=KS())==null||t(),(n=$e.onToast)==null||n.call($e,"error","Not Connected","Connecting to server... Please try again in a moment.");return}if(e.readyState!==WebSocket.OPEN){e.readyState===WebSocket.CONNECTING?(a=$e.onToast)==null||a.call($e,"warning","Connecting...","WebSocket is still connecting. Please wait a moment and try again."):(e.readyState===WebSocket.CLOSED||e.readyState===WebSocket.CLOSING)&&((i=KS())==null||i(),(o=$e.onToast)==null||o.call($e,"warning","Reconnecting...","Connection lost. Reconnecting to server..."));return}try{const c=JSON.stringify(s);if(vs.isEnabled()){const m=UA(s);console.log("[AgentDebugger] SENT - type:",s.type,"agentId:",m,"payload:",s.payload),m&&vs.captureSent(m,c)}e.send(c)}catch(c){(l=$e.onToast)==null||l.call($e,"error","Send Failed",`Failed to send message: ${c}`)}}const Iu=new Set,mL=5e3;function XS(s){if(!s.isDetached||!s.sessionId){Iu.delete(s.id);return}Iu.has(s.id)||(Iu.add(s.id),ux({type:"reattach_agent",payload:{agentId:s.id}}),setTimeout(()=>{Iu.delete(s.id)},mL))}function fL(s){var e,t,n,a,i,o,l,c,d,m,p,f,b,y,w,k,S,j,C,A,D,M,I;switch(fy.start(`ws:${s.type}`),s.type){case"agents_update":{const E=s.payload,_=E.filter(P=>P.class==="boss"||P.isBoss);_.length>0&&console.log("[WS agents_update] Boss agents received:",_.map(P=>({id:P.id,name:P.name,subordinateIds:P.subordinateIds}))),H.setAgents(E),(e=$e.onAgentsSync)==null||e.call($e,E),H.loadToolHistory();for(const P of E)XS(P);break}case"agent_created":{const E=s.payload;console.log("[WebSocket] Agent created:",E),H.addAgent(E),H.selectAgent(E.id),(t=$e.onAgentCreated)==null||t.call($e,E),(n=$e.onSpawnSuccess)==null||n.call($e),window.__spawnModalSuccess&&(console.log("[WebSocket] Calling __spawnModalSuccess"),window.__spawnModalSuccess()),(a=$e.onToast)==null||a.call($e,"success","Agent Deployed",`${E.name} is ready for commands`);break}case"agent_updated":{const E=s.payload,P=H.getState().agents.get(E.id),L=(P==null?void 0:P.status)!==E.status;console.log(`[Tide] Agent updated: ${E.name} (${E.id}) status=${E.status} (was ${P==null?void 0:P.status})${L?" ⚡ STATUS CHANGED":""}`),L&&console.log(`[Tide] 🔔 Status change for ${E.name}: ${P==null?void 0:P.status} → ${E.status}`);const R=P?P.position.x!==E.position.x||P.position.z!==E.position.z:!1;H.updateAgent(E),XS(E),(i=$e.onAgentUpdated)==null||i.call($e,E,R);break}case"agent_deleted":{const{id:E}=s.payload;Iu.delete(E),H.removeAgent(E),(o=$e.onAgentDeleted)==null||o.call($e,E);break}case"activity":{const E=s.payload;H.addActivity(E);break}case"event":{const E=s.payload;if(td.debug(`Event: ${E.type}`,{agentId:E.agentId,toolName:E.toolName},"ws:event"),E.type==="tool_start"&&E.toolName&&((l=$e.onToolUse)==null||l.call($e,E.agentId,E.toolName,E.toolInput),H.addToolExecution(E.agentId,E.toolName,E.toolInput),E.toolInput)){const _=E.toolInput.file_path||E.toolInput.path;_&&(E.toolName==="Write"?H.addFileChange(E.agentId,"created",_):E.toolName==="Edit"?H.addFileChange(E.agentId,"modified",_):E.toolName==="Read"&&H.addFileChange(E.agentId,"read",_))}break}case"output":{const E=s.payload;td.debug(`Output: "${E.text.slice(0,80)}..."`,{agentId:E.agentId,isStreaming:E.isStreaming,length:E.text.length,hasSkillUpdate:!!E.skillUpdate,uuid:E.uuid,toolName:E.toolName},"ws:output"),H.addOutput(E.agentId,{text:E.text,isStreaming:E.isStreaming,timestamp:E.timestamp,isDelegation:E.isDelegation,skillUpdate:E.skillUpdate,subagentName:E.subagentName,uuid:E.uuid,toolName:E.toolName,toolInput:E.toolInput,toolOutput:E.toolOutput});break}case"context_stats":{const{agentId:E,stats:_}=s.payload;console.log(`[Tide] Received context stats for agent ${E}: ${_.usedPercent}% used`),H.updateAgentContextStats(E,_);break}case"context_update":{const{agentId:E,contextUsed:_,contextLimit:P}=s.payload;H.updateAgentContext(E,_,P);break}case"error":{const E=s.payload;console.error("[WebSocket] Error from server:",E.message),(c=$e.onToast)==null||c.call($e,"error","Error",E.message),(d=$e.onSpawnError)==null||d.call($e),window.__spawnModalError&&(console.log("[WebSocket] Calling __spawnModalError"),window.__spawnModalError());break}case"directory_not_found":{const{path:E}=s.payload;console.log("[WebSocket] Directory not found:",E),(m=$e.onDirectoryNotFound)==null||m.call($e,E),window.__spawnModalDirNotFound&&(console.log("[WebSocket] Calling __spawnModalDirNotFound"),window.__spawnModalDirNotFound(E));break}case"command_started":{const{agentId:E,command:_}=s.payload,P=_.trim();if(P==="/context"||P==="/cost"||P==="/compact")break;H.addUserPromptToOutput(E,_);break}case"session_updated":{const{agentId:E}=s.payload;H.loadToolHistory();const _=H.getState().agents.get(E);_&&H.updateAgent({..._});break}case"supervisor_report":{const E=s.payload;H.setSupervisorReport(E);break}case"narrative_update":{const{agentId:E,narrative:_}=s.payload;H.addNarrative(E,_);break}case"supervisor_status":{const E=s.payload;H.setSupervisorStatus(E);break}case"agent_supervisor_history":{const E=s.payload;H.setAgentSupervisorHistory(E);break}case"agent_analysis":{const{agentId:E,analysis:_}=s.payload;H.addAgentAnalysis(E,_);break}case"areas_update":{const E=s.payload;H.setAreasFromServer(E),(p=$e.onAreasSync)==null||p.call($e);break}case"buildings_update":{const E=s.payload;H.setBuildingsFromServer(E);break}case"building_created":{const E=s.payload;H.addBuilding(E);break}case"building_updated":{const E=s.payload;H.updateBuildingFromServer(E),(f=$e.onBuildingUpdated)==null||f.call($e,E);break}case"building_deleted":{const{id:E}=s.payload;H.removeBuildingFromServer(E);break}case"building_logs":{const{buildingId:E,logs:_}=s.payload;H.addBuildingLogs(E,_);break}case"pm2_logs_chunk":{const{buildingId:E,chunk:_}=s.payload;H.appendStreamingLogChunk(E,_);break}case"pm2_logs_streaming":{const{buildingId:E,streaming:_}=s.payload;H.setStreamingStatus(E,_);break}case"docker_logs_chunk":{const{buildingId:E,chunk:_}=s.payload;H.appendStreamingLogChunk(E,_);break}case"docker_logs_streaming":{const{buildingId:E,streaming:_}=s.payload;H.setStreamingStatus(E,_);break}case"docker_containers_list":{const{containers:E,composeProjects:_}=s.payload;console.log(`[WebSocket] Received ${E.length} containers, ${_.length} compose projects`),H.setDockerContainersList(E,_);break}case"boss_building_logs_chunk":{const{bossBuildingId:E,subordinateBuildingId:_,subordinateBuildingName:P,chunk:L,isError:R}=s.payload;H.appendBossStreamingLogChunk(E,_,P,L,R);break}case"boss_building_subordinates_updated":{const{bossBuildingId:E,subordinateBuildingIds:_}=s.payload;H.updateBuilding(E,{subordinateBuildingIds:_});break}case"permission_request":{const E=s.payload;H.addPermissionRequest(E);break}case"permission_resolved":{const{requestId:E,approved:_}=s.payload;H.resolvePermissionRequest(E,_);break}case"delegation_decision":{const E=s.payload;H.handleDelegationDecision(E),E.status==="sent"&&((b=$e.onToast)==null||b.call($e,"info","Task Delegated",`Delegated to ${E.selectedAgentName}: ${E.reasoning.slice(0,80)}...`),E.bossId&&E.selectedAgentId&&((y=$e.onDelegation)==null||y.call($e,E.bossId,E.selectedAgentId)));break}case"boss_subordinates_updated":{const{bossId:E,subordinateIds:_}=s.payload;H.updateBossSubordinates(E,_);break}case"delegation_history":{const{bossId:E,decisions:_}=s.payload;H.setDelegationHistory(E,_);break}case"boss_spawned_agent":{const{agent:E,bossPosition:_}=s.payload;console.log("[WebSocket] Boss spawned agent:",E.name,"- walking to boss at",_),H.addAgent(E),(w=$e.onAgentCreated)==null||w.call($e,E),ux({type:"move_agent",payload:{agentId:E.id,position:_}}),(k=$e.onToast)==null||k.call($e,"success","Agent Deployed",`${E.name} spawned by boss, walking to position`);break}case"agent_task_started":{const{bossId:E,subordinateId:_,subordinateName:P,taskDescription:L}=s.payload;console.log(`[WebSocket] Agent ${P} started task for boss ${E}: ${L.slice(0,50)}...`),H.handleAgentTaskStarted(E,_,P,L);break}case"agent_task_output":{const{bossId:E,subordinateId:_,output:P}=s.payload;H.handleAgentTaskOutput(E,_,P);break}case"agent_task_completed":{const{bossId:E,subordinateId:_,success:P}=s.payload;console.log(`[WebSocket] Agent task completed for boss ${E}, subordinate ${_}, success: ${P}`),H.handleAgentTaskCompleted(E,_,P);break}case"skills_update":{const E=s.payload;H.setSkillsFromServer(E);break}case"skill_created":{const E=s.payload;H.addSkillFromServer(E),console.log(`[WebSocket] Skill created: ${E.name}`);break}case"skill_updated":{const E=s.payload;H.updateSkillFromServer(E),console.log(`[WebSocket] Skill updated: ${E.name}`);break}case"skill_deleted":{const{id:E}=s.payload;H.removeSkillFromServer(E),console.log(`[WebSocket] Skill deleted: ${E}`);break}case"agent_skills":{const{agentId:E,skills:_}=s.payload;console.log(`[WebSocket] Agent ${E} has ${_.length} skills`);break}case"custom_agent_classes_update":{const E=s.payload;H.setCustomAgentClassesFromServer(E),console.log(`[WebSocket] Received ${E.length} custom agent classes`);const _=new Map;for(const P of E)_.set(P.id,P);(S=$e.onCustomClassesSync)==null||S.call($e,_);break}case"custom_agent_class_created":{const E=s.payload;H.addCustomAgentClassFromServer(E),console.log(`[WebSocket] Custom agent class created: ${E.name}`),(j=$e.onCustomClassesSync)==null||j.call($e,H.getState().customAgentClasses);break}case"custom_agent_class_updated":{const E=s.payload;H.updateCustomAgentClassFromServer(E),console.log(`[WebSocket] Custom agent class updated: ${E.name}`),(C=$e.onCustomClassesSync)==null||C.call($e,H.getState().customAgentClasses);break}case"custom_agent_class_deleted":{const{id:E}=s.payload;H.removeCustomAgentClassFromServer(E),console.log(`[WebSocket] Custom agent class deleted: ${E}`),(A=$e.onCustomClassesSync)==null||A.call($e,H.getState().customAgentClasses);break}case"global_usage":{const E=s.payload;console.log("[WebSocket] Global usage update:",E),H.setGlobalUsage(E);break}case"agent_notification":{const E=s.payload;console.log(`[WebSocket] Agent notification from ${E.agentName}: ${E.title}`),(D=$e.onAgentNotification)==null||D.call($e,E);break}case"focus_agent":{const{agentId:E,openTerminal:_}=s.payload;if(!H.getState().agents.get(E)){console.warn(`[WebSocket] focus_agent ignored - agent not found: ${E}`);break}H.selectAgent(E),_&&H.setTerminalOpen(!0);const L=[0,80,220,500,1e3];for(const R of L)window.setTimeout(()=>{window.focus()},R);break}case"exec_task_started":{const{taskId:E,agentId:_,agentName:P,command:L,cwd:R}=s.payload;console.log(`[WebSocket] Exec task started: ${E} for agent ${P}: ${L.slice(0,50)}...`),H.handleExecTaskStarted(E,_,P,L,R);break}case"exec_task_output":{const{taskId:E,agentId:_,output:P,isError:L}=s.payload;H.handleExecTaskOutput(E,_,P,L);break}case"exec_task_completed":{const{taskId:E,agentId:_,exitCode:P,success:L}=s.payload;console.log(`[WebSocket] Exec task completed: ${E} for agent ${_}, success: ${L}`),H.handleExecTaskCompleted(E,_,P,L);break}case"subagent_started":{const E=s.payload;console.log(`[WebSocket] Subagent started: ${E.name} (${E.id}) for agent ${E.parentAgentId}`),H.addSubagent(E),(M=$e.onSubagentStarted)==null||M.call($e,E);break}case"subagent_output":{const{subagentId:E,parentAgentId:_,text:P,timestamp:L}=s.payload,R=P.indexOf(":");if(R>0){const z=P.slice(0,R).trim(),F=P.slice(R+1).trim();H.addSubagentActivity(E,_,{toolName:z,description:F,timestamp:L})}else P.startsWith("Using ")&&H.addSubagentActivity(E,_,{toolName:P.slice(6).trim(),description:"",timestamp:L});break}case"subagent_completed":{const{subagentId:E,parentAgentId:_,success:P,resultPreview:L,subagentName:R,durationMs:z,tokensUsed:F,toolUseCount:$}=s.payload;console.log(`[WebSocket] Subagent completed: ${E} for agent ${_}, success: ${P}`),(z||F||$)&&H.updateSubagentStats(E,_,{durationMs:z||0,tokensUsed:F||0,toolUseCount:$||0}),H.completeSubagent(E,_,P),(I=$e.onSubagentCompleted)==null||I.call($e,E);const U=H.getSubagent(E)||H.getSubagentByToolUseId(E),G=R||(U==null?void 0:U.name)||E,K=P?"✅":"❌",Z=z?` (${(z/1e3).toFixed(0)}s · ${((F||0)/1e3).toFixed(1)}K tokens · ${$||0} tools)`:"";H.addOutput(_,{text:`${K} Subagent ${G} ${P?"completed":"failed"}${Z}`,isStreaming:!1,timestamp:Date.now(),subagentName:G,toolOutput:L});break}case"subagent_stream":{const{toolUseId:E,parentAgentId:_,entries:P}=s.payload;H.addSubagentStreamEntries(E,_,P);break}case"secrets_update":{const E=s.payload;H.setSecretsFromServer(E),console.log(`[WebSocket] Received ${E.length} secrets`);break}case"secret_created":{const E=s.payload;H.addSecretFromServer(E),console.log(`[WebSocket] Secret created: ${E.name}`);break}case"secret_updated":{const E=s.payload;H.updateSecretFromServer(E),console.log(`[WebSocket] Secret updated: ${E.name}`);break}case"secret_deleted":{const{id:E}=s.payload;H.removeSecretFromServer(E),console.log(`[WebSocket] Secret deleted: ${E}`);break}case"database_connection_result":{const{buildingId:E,connectionId:_,success:P,error:L,serverVersion:R}=s.payload;H.setConnectionStatus(E,_,{connected:P,error:L,serverVersion:R}),console.log(`[WebSocket] Database connection ${P?"succeeded":"failed"}: ${_}`);break}case"databases_list":{const{buildingId:E,connectionId:_,databases:P}=s.payload;H.setDatabases(E,_,P),console.log(`[WebSocket] Received ${P.length} databases for ${_}`);break}case"tables_list":{const{buildingId:E,connectionId:_,database:P,tables:L}=s.payload;H.setTables(E,_,P,L),console.log(`[WebSocket] Received ${L.length} tables for ${P}`);break}case"table_schema":{const{buildingId:E,connectionId:_,database:P,table:L,columns:R,indexes:z,foreignKeys:F}=s.payload;H.setTableSchema(E,_,P,L,{columns:R,indexes:z||[],foreignKeys:F||[]}),console.log(`[WebSocket] Received schema for ${L}`);break}case"query_result":{const{buildingId:E,result:_}=s.payload;H.setQueryResult(E,_),console.log(`[WebSocket] Query ${_.status}: ${_.rowCount??_.affectedRows??0} rows in ${_.duration}ms`);break}case"silent_query_result":{const{buildingId:E,query:_,requestId:P,success:L,affectedRows:R,error:z}=s.payload;H.setSilentQueryResult(E,{query:_,requestId:P,success:L,affectedRows:R,error:z}),console.log(`[WebSocket] Silent query ${L?"succeeded":"failed"}: ${R??0} affected rows`);break}case"query_history_update":{const{buildingId:E,history:_}=s.payload;H.setQueryHistory(E,_),console.log(`[WebSocket] Received ${_.length} query history entries for ${E}`);break}}fy.end(`ws:${s.type}`)}lL(()=>nd());let ZS=!1;function GA(){const s=lx();s&&s.readyState===WebSocket.OPEN&&s.close(1e3,"Page unloading");const e=FA();e&&clearTimeout(e),window.__tideWsState&&(window.__tideWsState.ws=null,window.__tideWsState.reconnectTimeout=null,window.__tideWsState.isConnecting=!1,window.__tideWsState.reconnectAttempts=0),oL()}function gL(){ZS||(window.addEventListener("beforeunload",GA),ZS=!0)}function WA(){GA(),H.setConnected(!1),H.stopStatusPolling()}function qu(){WA(),my(0),setTimeout(()=>nd(),100)}function nd(){gL();const s=FA();s&&(clearTimeout(s),zA(null));const e=lx();if(iL()||e&&e.readyState===WebSocket.CONNECTING)return;if(e&&e.readyState===WebSocket.OPEN){VS()&&$e.onReconnect&&$e.onReconnect();return}my(py()+1),wu(!0);const t=As(pt.BACKEND_URL,""),n=ti(),a=6200;let i;if(t){const l=t.replace(/^https:\/\//,"wss://").replace(/^http:\/\//,"ws://");i=l.endsWith("/ws")?l:`${l.replace(/\/$/,"")}/ws`}else i=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws`;let o=null;try{n?o=new WebSocket(i,[`auth-${n}`]):o=new WebSocket(i)}catch{wu(!1),QS();return}qS(o),o.onopen=()=>{var c,d,m;const l=VS();wu(!1),my(0),rL(),H.setConnected(!0),H.startStatusPolling(),H.clearAllPermissions(),l?((c=$e.onToast)==null||c.call($e,"success","Reconnected","Connection restored - refreshing data..."),(d=$e.onReconnect)==null||d.call($e)):(m=$e.onToast)==null||m.call($e,"success","Connected","Connected to Tide Commander server"),aL(t,n)},o.onmessage=l=>{try{const c=JSON.parse(l.data);if(vs.isEnabled()){const m=UA(c);console.log("[AgentDebugger] RECEIVED - type:",c.type,"agentId:",m,"payload:",c.payload),m&&vs.captureReceived(m,l.data)}fL(c)}catch(c){const d=l.data.substring(0,200);console.error("[WS] Failed to parse message:",c),console.error("[WS] Raw data (first 200 chars):",d),console.error("[WS] Full data length:",l.data.length),l.data.length<5e3&&console.error("[WS] Full malformed message:",l.data)}},o.onclose=()=>{var c,d;wu(!1),qS(null),H.setConnected(!1),H.stopStatusPolling();const l=py();l<YS?((c=$e.onToast)==null||c.call($e,"warning","Disconnected",`Connection lost. Reconnecting... (attempt ${l+1}/${YS})`),QS()):(d=$e.onToast)==null||d.call($e,"error","Connection Failed",`Could not connect to server. Please check if the backend is running on port ${a}.`)},o.onerror=()=>{wu(!1)},H.setSendMessage(ux)}function QS(){const s=py(),e=Math.min(1e3*Math.pow(2,s-1),3e4);zA(setTimeout(nd,e))}function JS(s,e){if(e===SD)return console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."),s;if(e===Yb||e===nA){let t=s.getIndex();if(t===null){const o=[],l=s.getAttribute("position");if(l!==void 0){for(let c=0;c<l.count;c++)o.push(c);s.setIndex(o),t=s.getIndex()}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible."),s}const n=t.count-2,a=[];if(e===Yb)for(let o=1;o<=n;o++)a.push(t.getX(0)),a.push(t.getX(o)),a.push(t.getX(o+1));else for(let o=0;o<n;o++)o%2===0?(a.push(t.getX(o)),a.push(t.getX(o+1)),a.push(t.getX(o+2))):(a.push(t.getX(o+2)),a.push(t.getX(o+1)),a.push(t.getX(o)));a.length/3!==n&&console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.");const i=s.clone();return i.setIndex(a),i.clearGroups(),i}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:",e),s}class dx extends sA{constructor(e){super(e),this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register(function(t){return new wL(t)}),this.register(function(t){return new kL(t)}),this.register(function(t){return new _L(t)}),this.register(function(t){return new DL(t)}),this.register(function(t){return new PL(t)}),this.register(function(t){return new jL(t)}),this.register(function(t){return new CL(t)}),this.register(function(t){return new NL(t)}),this.register(function(t){return new AL(t)}),this.register(function(t){return new vL(t)}),this.register(function(t){return new ML(t)}),this.register(function(t){return new SL(t)}),this.register(function(t){return new EL(t)}),this.register(function(t){return new TL(t)}),this.register(function(t){return new yL(t)}),this.register(function(t){return new RL(t)}),this.register(function(t){return new LL(t)})}load(e,t,n,a){const i=this;let o;if(this.resourcePath!=="")o=this.resourcePath;else if(this.path!==""){const d=$u.extractUrlBase(e);o=$u.resolveURL(d,this.path)}else o=$u.extractUrlBase(e);this.manager.itemStart(e);const l=function(d){a?a(d):console.error(d),i.manager.itemError(e),i.manager.itemEnd(e)},c=new gp(this.manager);c.setPath(this.path),c.setResponseType("arraybuffer"),c.setRequestHeader(this.requestHeader),c.setWithCredentials(this.withCredentials),c.load(e,function(d){try{i.parse(d,o,function(m){t(m),i.manager.itemEnd(e)},l)}catch(m){l(m)}},n,l)}setDRACOLoader(e){return this.dracoLoader=e,this}setKTX2Loader(e){return this.ktx2Loader=e,this}setMeshoptDecoder(e){return this.meshoptDecoder=e,this}register(e){return this.pluginCallbacks.indexOf(e)===-1&&this.pluginCallbacks.push(e),this}unregister(e){return this.pluginCallbacks.indexOf(e)!==-1&&this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(e),1),this}parse(e,t,n,a){let i;const o={},l={},c=new TextDecoder;if(typeof e=="string")i=JSON.parse(e);else if(e instanceof ArrayBuffer)if(c.decode(new Uint8Array(e,0,4))===qA){try{o[Xt.KHR_BINARY_GLTF]=new OL(e)}catch(p){a&&a(p);return}i=JSON.parse(o[Xt.KHR_BINARY_GLTF].content)}else i=JSON.parse(c.decode(e));else i=e;if(i.asset===void 0||i.asset.version[0]<2){a&&a(new Error("THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported."));return}const d=new KL(i,{path:t||this.resourcePath||"",crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});d.fileLoader.setRequestHeader(this.requestHeader);for(let m=0;m<this.pluginCallbacks.length;m++){const p=this.pluginCallbacks[m](d);p.name||console.error("THREE.GLTFLoader: Invalid plugin found: missing name"),l[p.name]=p,o[p.name]=!0}if(i.extensionsUsed)for(let m=0;m<i.extensionsUsed.length;++m){const p=i.extensionsUsed[m],f=i.extensionsRequired||[];switch(p){case Xt.KHR_MATERIALS_UNLIT:o[p]=new xL;break;case Xt.KHR_DRACO_MESH_COMPRESSION:o[p]=new IL(i,this.dracoLoader);break;case Xt.KHR_TEXTURE_TRANSFORM:o[p]=new BL;break;case Xt.KHR_MESH_QUANTIZATION:o[p]=new FL;break;default:f.indexOf(p)>=0&&l[p]===void 0&&console.warn('THREE.GLTFLoader: Unknown extension "'+p+'".')}}d.setExtensions(o),d.setPlugins(l),d.parse(n,a)}parseAsync(e,t){const n=this;return new Promise(function(a,i){n.parse(e,t,a,i)})}}function bL(){let s={};return{get:function(e){return s[e]},add:function(e,t){s[e]=t},remove:function(e){delete s[e]},removeAll:function(){s={}}}}const Xt={KHR_BINARY_GLTF:"KHR_binary_glTF",KHR_DRACO_MESH_COMPRESSION:"KHR_draco_mesh_compression",KHR_LIGHTS_PUNCTUAL:"KHR_lights_punctual",KHR_MATERIALS_CLEARCOAT:"KHR_materials_clearcoat",KHR_MATERIALS_DISPERSION:"KHR_materials_dispersion",KHR_MATERIALS_IOR:"KHR_materials_ior",KHR_MATERIALS_SHEEN:"KHR_materials_sheen",KHR_MATERIALS_SPECULAR:"KHR_materials_specular",KHR_MATERIALS_TRANSMISSION:"KHR_materials_transmission",KHR_MATERIALS_IRIDESCENCE:"KHR_materials_iridescence",KHR_MATERIALS_ANISOTROPY:"KHR_materials_anisotropy",KHR_MATERIALS_UNLIT:"KHR_materials_unlit",KHR_MATERIALS_VOLUME:"KHR_materials_volume",KHR_TEXTURE_BASISU:"KHR_texture_basisu",KHR_TEXTURE_TRANSFORM:"KHR_texture_transform",KHR_MESH_QUANTIZATION:"KHR_mesh_quantization",KHR_MATERIALS_EMISSIVE_STRENGTH:"KHR_materials_emissive_strength",EXT_MATERIALS_BUMP:"EXT_materials_bump",EXT_TEXTURE_WEBP:"EXT_texture_webp",EXT_TEXTURE_AVIF:"EXT_texture_avif",EXT_MESHOPT_COMPRESSION:"EXT_meshopt_compression",EXT_MESH_GPU_INSTANCING:"EXT_mesh_gpu_instancing"};class yL{constructor(e){this.parser=e,this.name=Xt.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){const e=this.parser,t=this.parser.json.nodes||[];for(let n=0,a=t.length;n<a;n++){const i=t[n];i.extensions&&i.extensions[this.name]&&i.extensions[this.name].light!==void 0&&e._addNodeRef(this.cache,i.extensions[this.name].light)}}_loadLight(e){const t=this.parser,n="light:"+e;let a=t.cache.get(n);if(a)return a;const i=t.json,c=((i.extensions&&i.extensions[this.name]||{}).lights||[])[e];let d;const m=new Bt(16777215);c.color!==void 0&&m.setRGB(c.color[0],c.color[1],c.color[2],Ci);const p=c.range!==void 0?c.range:0;switch(c.type){case"directional":d=new sc(m),d.target.position.set(0,0,-1),d.add(d.target);break;case"point":d=new aA(m),d.distance=p;break;case"spot":d=new jD(m),d.distance=p,c.spot=c.spot||{},c.spot.innerConeAngle=c.spot.innerConeAngle!==void 0?c.spot.innerConeAngle:0,c.spot.outerConeAngle=c.spot.outerConeAngle!==void 0?c.spot.outerConeAngle:Math.PI/4,d.angle=c.spot.outerConeAngle,d.penumbra=1-c.spot.innerConeAngle/c.spot.outerConeAngle,d.target.position.set(0,0,-1),d.add(d.target);break;default:throw new Error("THREE.GLTFLoader: Unexpected light type: "+c.type)}return d.position.set(0,0,0),d.decay=2,Qi(d,c),c.intensity!==void 0&&(d.intensity=c.intensity),d.name=t.createUniqueName(c.name||"light_"+e),a=Promise.resolve(d),t.cache.add(n,a),a}getDependency(e,t){if(e==="light")return this._loadLight(t)}createNodeAttachment(e){const t=this,n=this.parser,i=n.json.nodes[e],l=(i.extensions&&i.extensions[this.name]||{}).light;return l===void 0?null:this._loadLight(l).then(function(c){return n._getNodeRef(t.cache,l,c)})}}class xL{constructor(){this.name=Xt.KHR_MATERIALS_UNLIT}getMaterialType(){return We}extendParams(e,t,n){const a=[];e.color=new Bt(1,1,1),e.opacity=1;const i=t.pbrMetallicRoughness;if(i){if(Array.isArray(i.baseColorFactor)){const o=i.baseColorFactor;e.color.setRGB(o[0],o[1],o[2],Ci),e.opacity=o[3]}i.baseColorTexture!==void 0&&a.push(n.assignTexture(e,"map",i.baseColorTexture,Va))}return Promise.all(a)}}class vL{constructor(e){this.parser=e,this.name=Xt.KHR_MATERIALS_EMISSIVE_STRENGTH}extendMaterialParams(e,t){const a=this.parser.json.materials[e];if(!a.extensions||!a.extensions[this.name])return Promise.resolve();const i=a.extensions[this.name].emissiveStrength;return i!==void 0&&(t.emissiveIntensity=i),Promise.resolve()}}class wL{constructor(e){this.parser=e,this.name=Xt.KHR_MATERIALS_CLEARCOAT}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Ai}extendMaterialParams(e,t){const n=this.parser,a=n.json.materials[e];if(!a.extensions||!a.extensions[this.name])return Promise.resolve();const i=[],o=a.extensions[this.name];if(o.clearcoatFactor!==void 0&&(t.clearcoat=o.clearcoatFactor),o.clearcoatTexture!==void 0&&i.push(n.assignTexture(t,"clearcoatMap",o.clearcoatTexture)),o.clearcoatRoughnessFactor!==void 0&&(t.clearcoatRoughness=o.clearcoatRoughnessFactor),o.clearcoatRoughnessTexture!==void 0&&i.push(n.assignTexture(t,"clearcoatRoughnessMap",o.clearcoatRoughnessTexture)),o.clearcoatNormalTexture!==void 0&&(i.push(n.assignTexture(t,"clearcoatNormalMap",o.clearcoatNormalTexture)),o.clearcoatNormalTexture.scale!==void 0)){const l=o.clearcoatNormalTexture.scale;t.clearcoatNormalScale=new _s(l,l)}return Promise.all(i)}}class kL{constructor(e){this.parser=e,this.name=Xt.KHR_MATERIALS_DISPERSION}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Ai}extendMaterialParams(e,t){const a=this.parser.json.materials[e];if(!a.extensions||!a.extensions[this.name])return Promise.resolve();const i=a.extensions[this.name];return t.dispersion=i.dispersion!==void 0?i.dispersion:0,Promise.resolve()}}class SL{constructor(e){this.parser=e,this.name=Xt.KHR_MATERIALS_IRIDESCENCE}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Ai}extendMaterialParams(e,t){const n=this.parser,a=n.json.materials[e];if(!a.extensions||!a.extensions[this.name])return Promise.resolve();const i=[],o=a.extensions[this.name];return o.iridescenceFactor!==void 0&&(t.iridescence=o.iridescenceFactor),o.iridescenceTexture!==void 0&&i.push(n.assignTexture(t,"iridescenceMap",o.iridescenceTexture)),o.iridescenceIor!==void 0&&(t.iridescenceIOR=o.iridescenceIor),t.iridescenceThicknessRange===void 0&&(t.iridescenceThicknessRange=[100,400]),o.iridescenceThicknessMinimum!==void 0&&(t.iridescenceThicknessRange[0]=o.iridescenceThicknessMinimum),o.iridescenceThicknessMaximum!==void 0&&(t.iridescenceThicknessRange[1]=o.iridescenceThicknessMaximum),o.iridescenceThicknessTexture!==void 0&&i.push(n.assignTexture(t,"iridescenceThicknessMap",o.iridescenceThicknessTexture)),Promise.all(i)}}class jL{constructor(e){this.parser=e,this.name=Xt.KHR_MATERIALS_SHEEN}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Ai}extendMaterialParams(e,t){const n=this.parser,a=n.json.materials[e];if(!a.extensions||!a.extensions[this.name])return Promise.resolve();const i=[];t.sheenColor=new Bt(0,0,0),t.sheenRoughness=0,t.sheen=1;const o=a.extensions[this.name];if(o.sheenColorFactor!==void 0){const l=o.sheenColorFactor;t.sheenColor.setRGB(l[0],l[1],l[2],Ci)}return o.sheenRoughnessFactor!==void 0&&(t.sheenRoughness=o.sheenRoughnessFactor),o.sheenColorTexture!==void 0&&i.push(n.assignTexture(t,"sheenColorMap",o.sheenColorTexture,Va)),o.sheenRoughnessTexture!==void 0&&i.push(n.assignTexture(t,"sheenRoughnessMap",o.sheenRoughnessTexture)),Promise.all(i)}}class CL{constructor(e){this.parser=e,this.name=Xt.KHR_MATERIALS_TRANSMISSION}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Ai}extendMaterialParams(e,t){const n=this.parser,a=n.json.materials[e];if(!a.extensions||!a.extensions[this.name])return Promise.resolve();const i=[],o=a.extensions[this.name];return o.transmissionFactor!==void 0&&(t.transmission=o.transmissionFactor),o.transmissionTexture!==void 0&&i.push(n.assignTexture(t,"transmissionMap",o.transmissionTexture)),Promise.all(i)}}class NL{constructor(e){this.parser=e,this.name=Xt.KHR_MATERIALS_VOLUME}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Ai}extendMaterialParams(e,t){const n=this.parser,a=n.json.materials[e];if(!a.extensions||!a.extensions[this.name])return Promise.resolve();const i=[],o=a.extensions[this.name];t.thickness=o.thicknessFactor!==void 0?o.thicknessFactor:0,o.thicknessTexture!==void 0&&i.push(n.assignTexture(t,"thicknessMap",o.thicknessTexture)),t.attenuationDistance=o.attenuationDistance||1/0;const l=o.attenuationColor||[1,1,1];return t.attenuationColor=new Bt().setRGB(l[0],l[1],l[2],Ci),Promise.all(i)}}class AL{constructor(e){this.parser=e,this.name=Xt.KHR_MATERIALS_IOR}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Ai}extendMaterialParams(e,t){const a=this.parser.json.materials[e];if(!a.extensions||!a.extensions[this.name])return Promise.resolve();const i=a.extensions[this.name];return t.ior=i.ior!==void 0?i.ior:1.5,Promise.resolve()}}class ML{constructor(e){this.parser=e,this.name=Xt.KHR_MATERIALS_SPECULAR}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Ai}extendMaterialParams(e,t){const n=this.parser,a=n.json.materials[e];if(!a.extensions||!a.extensions[this.name])return Promise.resolve();const i=[],o=a.extensions[this.name];t.specularIntensity=o.specularFactor!==void 0?o.specularFactor:1,o.specularTexture!==void 0&&i.push(n.assignTexture(t,"specularIntensityMap",o.specularTexture));const l=o.specularColorFactor||[1,1,1];return t.specularColor=new Bt().setRGB(l[0],l[1],l[2],Ci),o.specularColorTexture!==void 0&&i.push(n.assignTexture(t,"specularColorMap",o.specularColorTexture,Va)),Promise.all(i)}}class TL{constructor(e){this.parser=e,this.name=Xt.EXT_MATERIALS_BUMP}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Ai}extendMaterialParams(e,t){const n=this.parser,a=n.json.materials[e];if(!a.extensions||!a.extensions[this.name])return Promise.resolve();const i=[],o=a.extensions[this.name];return t.bumpScale=o.bumpFactor!==void 0?o.bumpFactor:1,o.bumpTexture!==void 0&&i.push(n.assignTexture(t,"bumpMap",o.bumpTexture)),Promise.all(i)}}class EL{constructor(e){this.parser=e,this.name=Xt.KHR_MATERIALS_ANISOTROPY}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Ai}extendMaterialParams(e,t){const n=this.parser,a=n.json.materials[e];if(!a.extensions||!a.extensions[this.name])return Promise.resolve();const i=[],o=a.extensions[this.name];return o.anisotropyStrength!==void 0&&(t.anisotropy=o.anisotropyStrength),o.anisotropyRotation!==void 0&&(t.anisotropyRotation=o.anisotropyRotation),o.anisotropyTexture!==void 0&&i.push(n.assignTexture(t,"anisotropyMap",o.anisotropyTexture)),Promise.all(i)}}class _L{constructor(e){this.parser=e,this.name=Xt.KHR_TEXTURE_BASISU}loadTexture(e){const t=this.parser,n=t.json,a=n.textures[e];if(!a.extensions||!a.extensions[this.name])return null;const i=a.extensions[this.name],o=t.options.ktx2Loader;if(!o){if(n.extensionsRequired&&n.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures");return null}return t.loadTextureImage(e,i.source,o)}}class DL{constructor(e){this.parser=e,this.name=Xt.EXT_TEXTURE_WEBP,this.isSupported=null}loadTexture(e){const t=this.name,n=this.parser,a=n.json,i=a.textures[e];if(!i.extensions||!i.extensions[t])return null;const o=i.extensions[t],l=a.images[o.source];let c=n.textureLoader;if(l.uri){const d=n.options.manager.getHandler(l.uri);d!==null&&(c=d)}return this.detectSupport().then(function(d){if(d)return n.loadTextureImage(e,o.source,c);if(a.extensionsRequired&&a.extensionsRequired.indexOf(t)>=0)throw new Error("THREE.GLTFLoader: WebP required by asset but unsupported.");return n.loadTexture(e)})}detectSupport(){return this.isSupported||(this.isSupported=new Promise(function(e){const t=new Image;t.src="data:image/webp;base64,UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA",t.onload=t.onerror=function(){e(t.height===1)}})),this.isSupported}}class PL{constructor(e){this.parser=e,this.name=Xt.EXT_TEXTURE_AVIF,this.isSupported=null}loadTexture(e){const t=this.name,n=this.parser,a=n.json,i=a.textures[e];if(!i.extensions||!i.extensions[t])return null;const o=i.extensions[t],l=a.images[o.source];let c=n.textureLoader;if(l.uri){const d=n.options.manager.getHandler(l.uri);d!==null&&(c=d)}return this.detectSupport().then(function(d){if(d)return n.loadTextureImage(e,o.source,c);if(a.extensionsRequired&&a.extensionsRequired.indexOf(t)>=0)throw new Error("THREE.GLTFLoader: AVIF required by asset but unsupported.");return n.loadTexture(e)})}detectSupport(){return this.isSupported||(this.isSupported=new Promise(function(e){const t=new Image;t.src="data:image/avif;base64,AAAAIGZ0eXBhdmlmAAAAAGF2aWZtaWYxbWlhZk1BMUIAAADybWV0YQAAAAAAAAAoaGRscgAAAAAAAAAAcGljdAAAAAAAAAAAAAAAAGxpYmF2aWYAAAAADnBpdG0AAAAAAAEAAAAeaWxvYwAAAABEAAABAAEAAAABAAABGgAAABcAAAAoaWluZgAAAAAAAQAAABppbmZlAgAAAAABAABhdjAxQ29sb3IAAAAAamlwcnAAAABLaXBjbwAAABRpc3BlAAAAAAAAAAEAAAABAAAAEHBpeGkAAAAAAwgICAAAAAxhdjFDgQAMAAAAABNjb2xybmNseAACAAIABoAAAAAXaXBtYQAAAAAAAAABAAEEAQKDBAAAAB9tZGF0EgAKCBgABogQEDQgMgkQAAAAB8dSLfI=",t.onload=t.onerror=function(){e(t.height===1)}})),this.isSupported}}class RL{constructor(e){this.name=Xt.EXT_MESHOPT_COMPRESSION,this.parser=e}loadBufferView(e){const t=this.parser.json,n=t.bufferViews[e];if(n.extensions&&n.extensions[this.name]){const a=n.extensions[this.name],i=this.parser.getDependency("buffer",a.buffer),o=this.parser.options.meshoptDecoder;if(!o||!o.supported){if(t.extensionsRequired&&t.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files");return null}return i.then(function(l){const c=a.byteOffset||0,d=a.byteLength||0,m=a.count,p=a.byteStride,f=new Uint8Array(l,c,d);return o.decodeGltfBufferAsync?o.decodeGltfBufferAsync(m,p,f,a.mode,a.filter).then(function(b){return b.buffer}):o.ready.then(function(){const b=new ArrayBuffer(m*p);return o.decodeGltfBuffer(new Uint8Array(b),m,p,f,a.mode,a.filter),b})})}else return null}}class LL{constructor(e){this.name=Xt.EXT_MESH_GPU_INSTANCING,this.parser=e}createNodeMesh(e){const t=this.parser.json,n=t.nodes[e];if(!n.extensions||!n.extensions[this.name]||n.mesh===void 0)return null;const a=t.meshes[n.mesh];for(const d of a.primitives)if(d.mode!==Da.TRIANGLES&&d.mode!==Da.TRIANGLE_STRIP&&d.mode!==Da.TRIANGLE_FAN&&d.mode!==void 0)return null;const o=n.extensions[this.name].attributes,l=[],c={};for(const d in o)l.push(this.parser.getDependency("accessor",o[d]).then(m=>(c[d]=m,c[d])));return l.length<1?null:(l.push(this.parser.createNodeMesh(e)),Promise.all(l).then(d=>{const m=d.pop(),p=m.isGroup?m.children:[m],f=d[0].count,b=[];for(const y of p){const w=new Vo,k=new yt,S=new Ko,j=new yt(1,1,1),C=new Ji(y.geometry,y.material,f);for(let A=0;A<f;A++)c.TRANSLATION&&k.fromBufferAttribute(c.TRANSLATION,A),c.ROTATION&&S.fromBufferAttribute(c.ROTATION,A),c.SCALE&&j.fromBufferAttribute(c.SCALE,A),C.setMatrixAt(A,w.compose(k,S,j));for(const A in c)if(A==="_COLOR_0"){const D=c[A];C.instanceColor=new CD(D.array,D.itemSize,D.normalized)}else A!=="TRANSLATION"&&A!=="ROTATION"&&A!=="SCALE"&&y.geometry.setAttribute(A,c[A]);iA.prototype.copy.call(C,y),this.parser.assignFinalMaterial(C),b.push(C)}return m.isGroup?(m.clear(),m.add(...b),m):b[0]}))}}const qA="glTF",ku=12,ej={JSON:1313821514,BIN:5130562};class OL{constructor(e){this.name=Xt.KHR_BINARY_GLTF,this.content=null,this.body=null;const t=new DataView(e,0,ku),n=new TextDecoder;if(this.header={magic:n.decode(new Uint8Array(e.slice(0,4))),version:t.getUint32(4,!0),length:t.getUint32(8,!0)},this.header.magic!==qA)throw new Error("THREE.GLTFLoader: Unsupported glTF-Binary header.");if(this.header.version<2)throw new Error("THREE.GLTFLoader: Legacy binary file detected.");const a=this.header.length-ku,i=new DataView(e,ku);let o=0;for(;o<a;){const l=i.getUint32(o,!0);o+=4;const c=i.getUint32(o,!0);if(o+=4,c===ej.JSON){const d=new Uint8Array(e,ku+o,l);this.content=n.decode(d)}else if(c===ej.BIN){const d=ku+o;this.body=e.slice(d,d+l)}o+=l}if(this.content===null)throw new Error("THREE.GLTFLoader: JSON content not found.")}}class IL{constructor(e,t){if(!t)throw new Error("THREE.GLTFLoader: No DRACOLoader instance provided.");this.name=Xt.KHR_DRACO_MESH_COMPRESSION,this.json=e,this.dracoLoader=t,this.dracoLoader.preload()}decodePrimitive(e,t){const n=this.json,a=this.dracoLoader,i=e.extensions[this.name].bufferView,o=e.extensions[this.name].attributes,l={},c={},d={};for(const m in o){const p=gy[m]||m.toLowerCase();l[p]=o[m]}for(const m in e.attributes){const p=gy[m]||m.toLowerCase();if(o[m]!==void 0){const f=n.accessors[e.attributes[m]],b=ic[f.componentType];d[p]=b.name,c[p]=f.normalized===!0}}return t.getDependency("bufferView",i).then(function(m){return new Promise(function(p,f){a.decodeDracoFile(m,function(b){for(const y in b.attributes){const w=b.attributes[y],k=c[y];k!==void 0&&(w.normalized=k)}p(b)},l,d,Ci,f)})})}}class BL{constructor(){this.name=Xt.KHR_TEXTURE_TRANSFORM}extendTexture(e,t){return(t.texCoord===void 0||t.texCoord===e.channel)&&t.offset===void 0&&t.rotation===void 0&&t.scale===void 0||(e=e.clone(),t.texCoord!==void 0&&(e.channel=t.texCoord),t.offset!==void 0&&e.offset.fromArray(t.offset),t.rotation!==void 0&&(e.rotation=t.rotation),t.scale!==void 0&&e.repeat.fromArray(t.scale),e.needsUpdate=!0),e}}class FL{constructor(){this.name=Xt.KHR_MESH_QUANTIZATION}}class YA extends zD{constructor(e,t,n,a){super(e,t,n,a)}copySampleValue_(e){const t=this.resultBuffer,n=this.sampleValues,a=this.valueSize,i=e*a*3+a;for(let o=0;o!==a;o++)t[o]=n[i+o];return t}interpolate_(e,t,n,a){const i=this.resultBuffer,o=this.sampleValues,l=this.valueSize,c=l*2,d=l*3,m=a-t,p=(n-t)/m,f=p*p,b=f*p,y=e*d,w=y-d,k=-2*b+3*f,S=b-f,j=1-k,C=S-f+p;for(let A=0;A!==l;A++){const D=o[w+A+l],M=o[w+A+c]*m,I=o[y+A+l],E=o[y+A]*m;i[A]=j*D+C*M+k*I+S*E}return i}}const zL=new Ko;class $L extends YA{interpolate_(e,t,n,a){const i=super.interpolate_(e,t,n,a);return zL.fromArray(i).normalize().toArray(i),i}}const Da={POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6},ic={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},tj={9728:rA,9729:In,9984:ED,9985:TD,9986:MD,9987:Hu},nj={33071:DD,33648:_D,10497:Oo},qg={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},gy={POSITION:"position",NORMAL:"normal",TANGENT:"tangent",TEXCOORD_0:"uv",TEXCOORD_1:"uv1",TEXCOORD_2:"uv2",TEXCOORD_3:"uv3",COLOR_0:"color",WEIGHTS_0:"skinWeight",JOINTS_0:"skinIndex"},Ir={scale:"scale",translation:"position",rotation:"quaternion",weights:"morphTargetInfluences"},HL={CUBICSPLINE:void 0,LINEAR:cA,STEP:BD},Yg={OPAQUE:"OPAQUE",MASK:"MASK",BLEND:"BLEND"};function UL(s){return s.DefaultMaterial===void 0&&(s.DefaultMaterial=new rt({color:16777215,emissive:0,metalness:1,roughness:1,transparent:!1,depthTest:!0,side:uA})),s.DefaultMaterial}function To(s,e,t){for(const n in t.extensions)s[n]===void 0&&(e.userData.gltfExtensions=e.userData.gltfExtensions||{},e.userData.gltfExtensions[n]=t.extensions[n])}function Qi(s,e){e.extras!==void 0&&(typeof e.extras=="object"?Object.assign(s.userData,e.extras):console.warn("THREE.GLTFLoader: Ignoring primitive type .extras, "+e.extras))}function GL(s,e,t){let n=!1,a=!1,i=!1;for(let d=0,m=e.length;d<m;d++){const p=e[d];if(p.POSITION!==void 0&&(n=!0),p.NORMAL!==void 0&&(a=!0),p.COLOR_0!==void 0&&(i=!0),n&&a&&i)break}if(!n&&!a&&!i)return Promise.resolve(s);const o=[],l=[],c=[];for(let d=0,m=e.length;d<m;d++){const p=e[d];if(n){const f=p.POSITION!==void 0?t.getDependency("accessor",p.POSITION):s.attributes.position;o.push(f)}if(a){const f=p.NORMAL!==void 0?t.getDependency("accessor",p.NORMAL):s.attributes.normal;l.push(f)}if(i){const f=p.COLOR_0!==void 0?t.getDependency("accessor",p.COLOR_0):s.attributes.color;c.push(f)}}return Promise.all([Promise.all(o),Promise.all(l),Promise.all(c)]).then(function(d){const m=d[0],p=d[1],f=d[2];return n&&(s.morphAttributes.position=m),a&&(s.morphAttributes.normal=p),i&&(s.morphAttributes.color=f),s.morphTargetsRelative=!0,s})}function WL(s,e){if(s.updateMorphTargets(),e.weights!==void 0)for(let t=0,n=e.weights.length;t<n;t++)s.morphTargetInfluences[t]=e.weights[t];if(e.extras&&Array.isArray(e.extras.targetNames)){const t=e.extras.targetNames;if(s.morphTargetInfluences.length===t.length){s.morphTargetDictionary={};for(let n=0,a=t.length;n<a;n++)s.morphTargetDictionary[t[n]]=n}else console.warn("THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.")}}function qL(s){let e;const t=s.extensions&&s.extensions[Xt.KHR_DRACO_MESH_COMPRESSION];if(t?e="draco:"+t.bufferView+":"+t.indices+":"+Vg(t.attributes):e=s.indices+":"+Vg(s.attributes)+":"+s.mode,s.targets!==void 0)for(let n=0,a=s.targets.length;n<a;n++)e+=":"+Vg(s.targets[n]);return e}function Vg(s){let e="";const t=Object.keys(s).sort();for(let n=0,a=t.length;n<a;n++)e+=t[n]+":"+s[t[n]]+";";return e}function by(s){switch(s){case Int8Array:return 1/127;case Uint8Array:return 1/255;case Int16Array:return 1/32767;case Uint16Array:return 1/65535;default:throw new Error("THREE.GLTFLoader: Unsupported normalized accessor component type.")}}function YL(s){return s.search(/\.jpe?g($|\?)/i)>0||s.search(/^data\:image\/jpeg/)===0?"image/jpeg":s.search(/\.webp($|\?)/i)>0||s.search(/^data\:image\/webp/)===0?"image/webp":s.search(/\.ktx2($|\?)/i)>0||s.search(/^data\:image\/ktx2/)===0?"image/ktx2":"image/png"}const VL=new Vo;class KL{constructor(e={},t={}){this.json=e,this.extensions={},this.plugins={},this.options=t,this.cache=new bL,this.associations=new Map,this.primitiveCache={},this.nodeCache={},this.meshCache={refs:{},uses:{}},this.cameraCache={refs:{},uses:{}},this.lightCache={refs:{},uses:{}},this.sourceCache={},this.textureCache={},this.nodeNamesUsed={};let n=!1,a=-1,i=!1,o=-1;if(typeof navigator<"u"){const l=navigator.userAgent;n=/^((?!chrome|android).)*safari/i.test(l)===!0;const c=l.match(/Version\/(\d+)/);a=n&&c?parseInt(c[1],10):-1,i=l.indexOf("Firefox")>-1,o=i?l.match(/Firefox\/([0-9]+)\./)[1]:-1}typeof createImageBitmap>"u"||n&&a<17||i&&o<98?this.textureLoader=new tx(this.options.manager):this.textureLoader=new ND(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new gp(this.options.manager),this.fileLoader.setResponseType("arraybuffer"),this.options.crossOrigin==="use-credentials"&&this.fileLoader.setWithCredentials(!0)}setExtensions(e){this.extensions=e}setPlugins(e){this.plugins=e}parse(e,t){const n=this,a=this.json,i=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(o){return o._markDefs&&o._markDefs()}),Promise.all(this._invokeAll(function(o){return o.beforeRoot&&o.beforeRoot()})).then(function(){return Promise.all([n.getDependencies("scene"),n.getDependencies("animation"),n.getDependencies("camera")])}).then(function(o){const l={scene:o[0][a.scene||0],scenes:o[0],animations:o[1],cameras:o[2],asset:a.asset,parser:n,userData:{}};return To(i,l,a),Qi(l,a),Promise.all(n._invokeAll(function(c){return c.afterRoot&&c.afterRoot(l)})).then(function(){for(const c of l.scenes)c.updateMatrixWorld();e(l)})}).catch(t)}_markDefs(){const e=this.json.nodes||[],t=this.json.skins||[],n=this.json.meshes||[];for(let a=0,i=t.length;a<i;a++){const o=t[a].joints;for(let l=0,c=o.length;l<c;l++)e[o[l]].isBone=!0}for(let a=0,i=e.length;a<i;a++){const o=e[a];o.mesh!==void 0&&(this._addNodeRef(this.meshCache,o.mesh),o.skin!==void 0&&(n[o.mesh].isSkinnedMesh=!0)),o.camera!==void 0&&this._addNodeRef(this.cameraCache,o.camera)}}_addNodeRef(e,t){t!==void 0&&(e.refs[t]===void 0&&(e.refs[t]=e.uses[t]=0),e.refs[t]++)}_getNodeRef(e,t,n){if(e.refs[t]<=1)return n;const a=n.clone(),i=(o,l)=>{const c=this.associations.get(o);c!=null&&this.associations.set(l,c);for(const[d,m]of o.children.entries())i(m,l.children[d])};return i(n,a),a.name+="_instance_"+e.uses[t]++,a}_invokeOne(e){const t=Object.values(this.plugins);t.push(this);for(let n=0;n<t.length;n++){const a=e(t[n]);if(a)return a}return null}_invokeAll(e){const t=Object.values(this.plugins);t.unshift(this);const n=[];for(let a=0;a<t.length;a++){const i=e(t[a]);i&&n.push(i)}return n}getDependency(e,t){const n=e+":"+t;let a=this.cache.get(n);if(!a){switch(e){case"scene":a=this.loadScene(t);break;case"node":a=this._invokeOne(function(i){return i.loadNode&&i.loadNode(t)});break;case"mesh":a=this._invokeOne(function(i){return i.loadMesh&&i.loadMesh(t)});break;case"accessor":a=this.loadAccessor(t);break;case"bufferView":a=this._invokeOne(function(i){return i.loadBufferView&&i.loadBufferView(t)});break;case"buffer":a=this.loadBuffer(t);break;case"material":a=this._invokeOne(function(i){return i.loadMaterial&&i.loadMaterial(t)});break;case"texture":a=this._invokeOne(function(i){return i.loadTexture&&i.loadTexture(t)});break;case"skin":a=this.loadSkin(t);break;case"animation":a=this._invokeOne(function(i){return i.loadAnimation&&i.loadAnimation(t)});break;case"camera":a=this.loadCamera(t);break;default:if(a=this._invokeOne(function(i){return i!=this&&i.getDependency&&i.getDependency(e,t)}),!a)throw new Error("Unknown type: "+e);break}this.cache.add(n,a)}return a}getDependencies(e){let t=this.cache.get(e);if(!t){const n=this,a=this.json[e+(e==="mesh"?"es":"s")]||[];t=Promise.all(a.map(function(i,o){return n.getDependency(e,o)})),this.cache.add(e,t)}return t}loadBuffer(e){const t=this.json.buffers[e],n=this.fileLoader;if(t.type&&t.type!=="arraybuffer")throw new Error("THREE.GLTFLoader: "+t.type+" buffer type is not supported.");if(t.uri===void 0&&e===0)return Promise.resolve(this.extensions[Xt.KHR_BINARY_GLTF].body);const a=this.options;return new Promise(function(i,o){n.load($u.resolveURL(t.uri,a.path),i,void 0,function(){o(new Error('THREE.GLTFLoader: Failed to load buffer "'+t.uri+'".'))})})}loadBufferView(e){const t=this.json.bufferViews[e];return this.getDependency("buffer",t.buffer).then(function(n){const a=t.byteLength||0,i=t.byteOffset||0;return n.slice(i,i+a)})}loadAccessor(e){const t=this,n=this.json,a=this.json.accessors[e];if(a.bufferView===void 0&&a.sparse===void 0){const o=qg[a.type],l=ic[a.componentType],c=a.normalized===!0,d=new l(a.count*o);return Promise.resolve(new Ka(d,o,c))}const i=[];return a.bufferView!==void 0?i.push(this.getDependency("bufferView",a.bufferView)):i.push(null),a.sparse!==void 0&&(i.push(this.getDependency("bufferView",a.sparse.indices.bufferView)),i.push(this.getDependency("bufferView",a.sparse.values.bufferView))),Promise.all(i).then(function(o){const l=o[0],c=qg[a.type],d=ic[a.componentType],m=d.BYTES_PER_ELEMENT,p=m*c,f=a.byteOffset||0,b=a.bufferView!==void 0?n.bufferViews[a.bufferView].byteStride:void 0,y=a.normalized===!0;let w,k;if(b&&b!==p){const S=Math.floor(f/b),j="InterleavedBuffer:"+a.bufferView+":"+a.componentType+":"+S+":"+a.count;let C=t.cache.get(j);C||(w=new d(l,S*b,a.count*b/m),C=new AD(w,b/m),t.cache.add(j,C)),k=new FD(C,c,f%b/m,y)}else l===null?w=new d(a.count*c):w=new d(l,f,a.count*c),k=new Ka(w,c,y);if(a.sparse!==void 0){const S=qg.SCALAR,j=ic[a.sparse.indices.componentType],C=a.sparse.indices.byteOffset||0,A=a.sparse.values.byteOffset||0,D=new j(o[1],C,a.sparse.count*S),M=new d(o[2],A,a.sparse.count*c);l!==null&&(k=new Ka(k.array.slice(),k.itemSize,k.normalized)),k.normalized=!1;for(let I=0,E=D.length;I<E;I++){const _=D[I];if(k.setX(_,M[I*c]),c>=2&&k.setY(_,M[I*c+1]),c>=3&&k.setZ(_,M[I*c+2]),c>=4&&k.setW(_,M[I*c+3]),c>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}k.normalized=y}return k})}loadTexture(e){const t=this.json,n=this.options,i=t.textures[e].source,o=t.images[i];let l=this.textureLoader;if(o.uri){const c=n.manager.getHandler(o.uri);c!==null&&(l=c)}return this.loadTextureImage(e,i,l)}loadTextureImage(e,t,n){const a=this,i=this.json,o=i.textures[e],l=i.images[t],c=(l.uri||l.bufferView)+":"+o.sampler;if(this.textureCache[c])return this.textureCache[c];const d=this.loadImageSource(t,n).then(function(m){m.flipY=!1,m.name=o.name||l.name||"",m.name===""&&typeof l.uri=="string"&&l.uri.startsWith("data:image/")===!1&&(m.name=l.uri);const f=(i.samplers||{})[o.sampler]||{};return m.magFilter=tj[f.magFilter]||In,m.minFilter=tj[f.minFilter]||Hu,m.wrapS=nj[f.wrapS]||Oo,m.wrapT=nj[f.wrapT]||Oo,m.generateMipmaps=!m.isCompressedTexture&&m.minFilter!==rA&&m.minFilter!==In,a.associations.set(m,{textures:e}),m}).catch(function(){return null});return this.textureCache[c]=d,d}loadImageSource(e,t){const n=this,a=this.json,i=this.options;if(this.sourceCache[e]!==void 0)return this.sourceCache[e].then(p=>p.clone());const o=a.images[e],l=self.URL||self.webkitURL;let c=o.uri||"",d=!1;if(o.bufferView!==void 0)c=n.getDependency("bufferView",o.bufferView).then(function(p){d=!0;const f=new Blob([p],{type:o.mimeType});return c=l.createObjectURL(f),c});else if(o.uri===void 0)throw new Error("THREE.GLTFLoader: Image "+e+" is missing URI and bufferView");const m=Promise.resolve(c).then(function(p){return new Promise(function(f,b){let y=f;t.isImageBitmapLoader===!0&&(y=function(w){const k=new Zk(w);k.needsUpdate=!0,f(k)}),t.load($u.resolveURL(p,i.path),y,void 0,b)})}).then(function(p){return d===!0&&l.revokeObjectURL(c),Qi(p,o),p.userData.mimeType=o.mimeType||YL(o.uri),p}).catch(function(p){throw console.error("THREE.GLTFLoader: Couldn't load texture",c),p});return this.sourceCache[e]=m,m}assignTexture(e,t,n,a){const i=this;return this.getDependency("texture",n.index).then(function(o){if(!o)return null;if(n.texCoord!==void 0&&n.texCoord>0&&(o=o.clone(),o.channel=n.texCoord),i.extensions[Xt.KHR_TEXTURE_TRANSFORM]){const l=n.extensions!==void 0?n.extensions[Xt.KHR_TEXTURE_TRANSFORM]:void 0;if(l){const c=i.associations.get(o);o=i.extensions[Xt.KHR_TEXTURE_TRANSFORM].extendTexture(o,l),i.associations.set(o,c)}}return a!==void 0&&(o.colorSpace=a),e[t]=o,o})}assignFinalMaterial(e){const t=e.geometry;let n=e.material;const a=t.attributes.tangent===void 0,i=t.attributes.color!==void 0,o=t.attributes.normal===void 0;if(e.isPoints){const l="PointsMaterial:"+n.uuid;let c=this.cache.get(l);c||(c=new nm,Ur.prototype.copy.call(c,n),c.color.copy(n.color),c.map=n.map,c.sizeAttenuation=!1,this.cache.add(l,c)),n=c}else if(e.isLine){const l="LineBasicMaterial:"+n.uuid;let c=this.cache.get(l);c||(c=new Io,Ur.prototype.copy.call(c,n),c.color.copy(n.color),c.map=n.map,this.cache.add(l,c)),n=c}if(a||i||o){let l="ClonedMaterial:"+n.uuid+":";a&&(l+="derivative-tangents:"),i&&(l+="vertex-colors:"),o&&(l+="flat-shading:");let c=this.cache.get(l);c||(c=n.clone(),i&&(c.vertexColors=!0),o&&(c.flatShading=!0),a&&(c.normalScale&&(c.normalScale.y*=-1),c.clearcoatNormalScale&&(c.clearcoatNormalScale.y*=-1)),this.cache.add(l,c),this.associations.set(c,this.associations.get(n))),n=c}e.material=n}getMaterialType(){return rt}loadMaterial(e){const t=this,n=this.json,a=this.extensions,i=n.materials[e];let o;const l={},c=i.extensions||{},d=[];if(c[Xt.KHR_MATERIALS_UNLIT]){const p=a[Xt.KHR_MATERIALS_UNLIT];o=p.getMaterialType(),d.push(p.extendParams(l,i,t))}else{const p=i.pbrMetallicRoughness||{};if(l.color=new Bt(1,1,1),l.opacity=1,Array.isArray(p.baseColorFactor)){const f=p.baseColorFactor;l.color.setRGB(f[0],f[1],f[2],Ci),l.opacity=f[3]}p.baseColorTexture!==void 0&&d.push(t.assignTexture(l,"map",p.baseColorTexture,Va)),l.metalness=p.metallicFactor!==void 0?p.metallicFactor:1,l.roughness=p.roughnessFactor!==void 0?p.roughnessFactor:1,p.metallicRoughnessTexture!==void 0&&(d.push(t.assignTexture(l,"metalnessMap",p.metallicRoughnessTexture)),d.push(t.assignTexture(l,"roughnessMap",p.metallicRoughnessTexture))),o=this._invokeOne(function(f){return f.getMaterialType&&f.getMaterialType(e)}),d.push(Promise.all(this._invokeAll(function(f){return f.extendMaterialParams&&f.extendMaterialParams(e,l)})))}i.doubleSided===!0&&(l.side=ws);const m=i.alphaMode||Yg.OPAQUE;if(m===Yg.BLEND?(l.transparent=!0,l.depthWrite=!1):(l.transparent=!1,m===Yg.MASK&&(l.alphaTest=i.alphaCutoff!==void 0?i.alphaCutoff:.5)),i.normalTexture!==void 0&&o!==We&&(d.push(t.assignTexture(l,"normalMap",i.normalTexture)),l.normalScale=new _s(1,1),i.normalTexture.scale!==void 0)){const p=i.normalTexture.scale;l.normalScale.set(p,p)}if(i.occlusionTexture!==void 0&&o!==We&&(d.push(t.assignTexture(l,"aoMap",i.occlusionTexture)),i.occlusionTexture.strength!==void 0&&(l.aoMapIntensity=i.occlusionTexture.strength)),i.emissiveFactor!==void 0&&o!==We){const p=i.emissiveFactor;l.emissive=new Bt().setRGB(p[0],p[1],p[2],Ci)}return i.emissiveTexture!==void 0&&o!==We&&d.push(t.assignTexture(l,"emissiveMap",i.emissiveTexture,Va)),Promise.all(d).then(function(){const p=new o(l);return i.name&&(p.name=i.name),Qi(p,i),t.associations.set(p,{materials:e}),i.extensions&&To(a,p,i),p})}createUniqueName(e){const t=PD.sanitizeNodeName(e||"");return t in this.nodeNamesUsed?t+"_"+ ++this.nodeNamesUsed[t]:(this.nodeNamesUsed[t]=0,t)}loadGeometries(e){const t=this,n=this.extensions,a=this.primitiveCache;function i(l){return n[Xt.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(l,t).then(function(c){return sj(c,l,t)})}const o=[];for(let l=0,c=e.length;l<c;l++){const d=e[l],m=qL(d),p=a[m];if(p)o.push(p.promise);else{let f;d.extensions&&d.extensions[Xt.KHR_DRACO_MESH_COMPRESSION]?f=i(d):f=sj(new La,d,t),a[m]={primitive:d,promise:f},o.push(f)}}return Promise.all(o)}loadMesh(e){const t=this,n=this.json,a=this.extensions,i=n.meshes[e],o=i.primitives,l=[];for(let c=0,d=o.length;c<d;c++){const m=o[c].material===void 0?UL(this.cache):this.getDependency("material",o[c].material);l.push(m)}return l.push(t.loadGeometries(o)),Promise.all(l).then(function(c){const d=c.slice(0,c.length-1),m=c[c.length-1],p=[];for(let b=0,y=m.length;b<y;b++){const w=m[b],k=o[b];let S;const j=d[b];if(k.mode===Da.TRIANGLES||k.mode===Da.TRIANGLE_STRIP||k.mode===Da.TRIANGLE_FAN||k.mode===void 0)S=i.isSkinnedMesh===!0?new Vb(w,j):new De(w,j),S.isSkinnedMesh===!0&&S.normalizeSkinWeights(),k.mode===Da.TRIANGLE_STRIP?S.geometry=JS(S.geometry,nA):k.mode===Da.TRIANGLE_FAN&&(S.geometry=JS(S.geometry,Yb));else if(k.mode===Da.LINES)S=new nx(w,j);else if(k.mode===Da.LINE_STRIP)S=new zr(w,j);else if(k.mode===Da.LINE_LOOP)S=new RD(w,j);else if(k.mode===Da.POINTS)S=new dd(w,j);else throw new Error("THREE.GLTFLoader: Primitive mode unsupported: "+k.mode);Object.keys(S.geometry.morphAttributes).length>0&&WL(S,i),S.name=t.createUniqueName(i.name||"mesh_"+e),Qi(S,i),k.extensions&&To(a,S,k),t.assignFinalMaterial(S),p.push(S)}for(let b=0,y=p.length;b<y;b++)t.associations.set(p[b],{meshes:e,primitives:b});if(p.length===1)return i.extensions&&To(a,p[0],i),p[0];const f=new Bn;i.extensions&&To(a,f,i),t.associations.set(f,{meshes:e});for(let b=0,y=p.length;b<y;b++)f.add(p[b]);return f})}loadCamera(e){let t;const n=this.json.cameras[e],a=n[n.type];if(!a){console.warn("THREE.GLTFLoader: Missing camera parameters.");return}return n.type==="perspective"?t=new sx(oA.radToDeg(a.yfov),a.aspectRatio||1,a.znear||1,a.zfar||2e6):n.type==="orthographic"&&(t=new lA(-a.xmag,a.xmag,a.ymag,-a.ymag,a.znear,a.zfar)),n.name&&(t.name=this.createUniqueName(n.name)),Qi(t,n),Promise.resolve(t)}loadSkin(e){const t=this.json.skins[e],n=[];for(let a=0,i=t.joints.length;a<i;a++)n.push(this._loadNodeShallow(t.joints[a]));return t.inverseBindMatrices!==void 0?n.push(this.getDependency("accessor",t.inverseBindMatrices)):n.push(null),Promise.all(n).then(function(a){const i=a.pop(),o=a,l=[],c=[];for(let d=0,m=o.length;d<m;d++){const p=o[d];if(p){l.push(p);const f=new Vo;i!==null&&f.fromArray(i.array,d*16),c.push(f)}else console.warn('THREE.GLTFLoader: Joint "%s" could not be found.',t.joints[d])}return new LD(l,c)})}loadAnimation(e){const t=this.json,n=this,a=t.animations[e],i=a.name?a.name:"animation_"+e,o=[],l=[],c=[],d=[],m=[];for(let p=0,f=a.channels.length;p<f;p++){const b=a.channels[p],y=a.samplers[b.sampler],w=b.target,k=w.node,S=a.parameters!==void 0?a.parameters[y.input]:y.input,j=a.parameters!==void 0?a.parameters[y.output]:y.output;w.node!==void 0&&(o.push(this.getDependency("node",k)),l.push(this.getDependency("accessor",S)),c.push(this.getDependency("accessor",j)),d.push(y),m.push(w))}return Promise.all([Promise.all(o),Promise.all(l),Promise.all(c),Promise.all(d),Promise.all(m)]).then(function(p){const f=p[0],b=p[1],y=p[2],w=p[3],k=p[4],S=[];for(let j=0,C=f.length;j<C;j++){const A=f[j],D=b[j],M=y[j],I=w[j],E=k[j];if(A===void 0)continue;A.updateMatrix&&A.updateMatrix();const _=n._createAnimationTracks(A,D,M,I,E);if(_)for(let P=0;P<_.length;P++)S.push(_[P])}return new OD(i,void 0,S)})}createNodeMesh(e){const t=this.json,n=this,a=t.nodes[e];return a.mesh===void 0?null:n.getDependency("mesh",a.mesh).then(function(i){const o=n._getNodeRef(n.meshCache,a.mesh,i);return a.weights!==void 0&&o.traverse(function(l){if(l.isMesh)for(let c=0,d=a.weights.length;c<d;c++)l.morphTargetInfluences[c]=a.weights[c]}),o})}loadNode(e){const t=this.json,n=this,a=t.nodes[e],i=n._loadNodeShallow(e),o=[],l=a.children||[];for(let d=0,m=l.length;d<m;d++)o.push(n.getDependency("node",l[d]));const c=a.skin===void 0?Promise.resolve(null):n.getDependency("skin",a.skin);return Promise.all([i,Promise.all(o),c]).then(function(d){const m=d[0],p=d[1],f=d[2];f!==null&&m.traverse(function(b){b.isSkinnedMesh&&b.bind(f,VL)});for(let b=0,y=p.length;b<y;b++)m.add(p[b]);return m})}_loadNodeShallow(e){const t=this.json,n=this.extensions,a=this;if(this.nodeCache[e]!==void 0)return this.nodeCache[e];const i=t.nodes[e],o=i.name?a.createUniqueName(i.name):"",l=[],c=a._invokeOne(function(d){return d.createNodeMesh&&d.createNodeMesh(e)});return c&&l.push(c),i.camera!==void 0&&l.push(a.getDependency("camera",i.camera).then(function(d){return a._getNodeRef(a.cameraCache,i.camera,d)})),a._invokeAll(function(d){return d.createNodeAttachment&&d.createNodeAttachment(e)}).forEach(function(d){l.push(d)}),this.nodeCache[e]=Promise.all(l).then(function(d){let m;if(i.isBone===!0?m=new ID:d.length>1?m=new Bn:d.length===1?m=d[0]:m=new iA,m!==d[0])for(let p=0,f=d.length;p<f;p++)m.add(d[p]);if(i.name&&(m.userData.name=i.name,m.name=o),Qi(m,i),i.extensions&&To(n,m,i),i.matrix!==void 0){const p=new Vo;p.fromArray(i.matrix),m.applyMatrix4(p)}else i.translation!==void 0&&m.position.fromArray(i.translation),i.rotation!==void 0&&m.quaternion.fromArray(i.rotation),i.scale!==void 0&&m.scale.fromArray(i.scale);return a.associations.has(m)||a.associations.set(m,{}),a.associations.get(m).nodes=e,m}),this.nodeCache[e]}loadScene(e){const t=this.extensions,n=this.json.scenes[e],a=this,i=new Bn;n.name&&(i.name=a.createUniqueName(n.name)),Qi(i,n),n.extensions&&To(t,i,n);const o=n.nodes||[],l=[];for(let c=0,d=o.length;c<d;c++)l.push(a.getDependency("node",o[c]));return Promise.all(l).then(function(c){for(let m=0,p=c.length;m<p;m++)i.add(c[m]);const d=m=>{const p=new Map;for(const[f,b]of a.associations)(f instanceof Ur||f instanceof Zk)&&p.set(f,b);return m.traverse(f=>{const b=a.associations.get(f);b!=null&&p.set(f,b)}),p};return a.associations=d(i),i})}_createAnimationTracks(e,t,n,a,i){const o=[],l=e.name?e.name:e.uuid,c=[];Ir[i.path]===Ir.weights?e.traverse(function(f){f.morphTargetInfluences&&c.push(f.name?f.name:f.uuid)}):c.push(l);let d;switch(Ir[i.path]){case Ir.weights:d=Jk;break;case Ir.rotation:d=eS;break;case Ir.position:case Ir.scale:d=Qk;break;default:switch(n.itemSize){case 1:d=Jk;break;case 2:case 3:default:d=Qk;break}break}const m=a.interpolation!==void 0?HL[a.interpolation]:cA,p=this._getArrayFromAccessor(n);for(let f=0,b=c.length;f<b;f++){const y=new d(c[f]+"."+Ir[i.path],t.array,p,m);a.interpolation==="CUBICSPLINE"&&this._createCubicSplineTrackInterpolant(y),o.push(y)}return o}_getArrayFromAccessor(e){let t=e.array;if(e.normalized){const n=by(t.constructor),a=new Float32Array(t.length);for(let i=0,o=t.length;i<o;i++)a[i]=t[i]*n;t=a}return t}_createCubicSplineTrackInterpolant(e){e.createInterpolant=function(n){const a=this instanceof eS?$L:YA;return new a(this.times,this.values,this.getValueSize()/3,n)},e.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline=!0}}function XL(s,e,t){const n=e.attributes,a=new bp;if(n.POSITION!==void 0){const l=t.json.accessors[n.POSITION],c=l.min,d=l.max;if(c!==void 0&&d!==void 0){if(a.set(new yt(c[0],c[1],c[2]),new yt(d[0],d[1],d[2])),l.normalized){const m=by(ic[l.componentType]);a.min.multiplyScalar(m),a.max.multiplyScalar(m)}}else{console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.");return}}else return;const i=e.targets;if(i!==void 0){const l=new yt,c=new yt;for(let d=0,m=i.length;d<m;d++){const p=i[d];if(p.POSITION!==void 0){const f=t.json.accessors[p.POSITION],b=f.min,y=f.max;if(b!==void 0&&y!==void 0){if(c.setX(Math.max(Math.abs(b[0]),Math.abs(y[0]))),c.setY(Math.max(Math.abs(b[1]),Math.abs(y[1]))),c.setZ(Math.max(Math.abs(b[2]),Math.abs(y[2]))),f.normalized){const w=by(ic[f.componentType]);c.multiplyScalar(w)}l.max(c)}else console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.")}}a.expandByVector(l)}s.boundingBox=a;const o=new $D;a.getCenter(o.center),o.radius=a.min.distanceTo(a.max)/2,s.boundingSphere=o}function sj(s,e,t){const n=e.attributes,a=[];function i(o,l){return t.getDependency("accessor",o).then(function(c){s.setAttribute(l,c)})}for(const o in n){const l=gy[o]||o.toLowerCase();l in s.attributes||a.push(i(n[o],l))}if(e.indices!==void 0&&!s.index){const o=t.getDependency("accessor",e.indices).then(function(l){s.setIndex(l)});a.push(o)}return Kb.workingColorSpace!==Ci&&"COLOR_0"in n&&console.warn(`THREE.GLTFLoader: Converting vertex colors from "srgb-linear" to "${Kb.workingColorSpace}" not supported.`),Qi(s,e),XL(s,e,t),Promise.all(a).then(function(){return e.targets!==void 0?GL(s,e.targets,t):s})}const Kg=new WeakMap;class hx extends sA{constructor(e){super(e),this.decoderPath="",this.decoderConfig={},this.decoderBinary=null,this.decoderPending=null,this.workerLimit=4,this.workerPool=[],this.workerNextTaskID=1,this.workerSourceURL="",this.defaultAttributeIDs={position:"POSITION",normal:"NORMAL",color:"COLOR",uv:"TEX_COORD"},this.defaultAttributeTypes={position:"Float32Array",normal:"Float32Array",color:"Float32Array",uv:"Float32Array"}}setDecoderPath(e){return this.decoderPath=e,this}setDecoderConfig(e){return this.decoderConfig=e,this}setWorkerLimit(e){return this.workerLimit=e,this}load(e,t,n,a){const i=new gp(this.manager);i.setPath(this.path),i.setResponseType("arraybuffer"),i.setRequestHeader(this.requestHeader),i.setWithCredentials(this.withCredentials),i.load(e,o=>{this.parse(o,t,a)},n,a)}parse(e,t,n=()=>{}){this.decodeDracoFile(e,t,null,null,Va,n).catch(n)}decodeDracoFile(e,t,n,a,i=Ci,o=()=>{}){const l={attributeIDs:n||this.defaultAttributeIDs,attributeTypes:a||this.defaultAttributeTypes,useUniqueIDs:!!n,vertexColorSpace:i};return this.decodeGeometry(e,l).then(t).catch(o)}decodeGeometry(e,t){const n=JSON.stringify(t);if(Kg.has(e)){const c=Kg.get(e);if(c.key===n)return c.promise;if(e.byteLength===0)throw new Error("THREE.DRACOLoader: Unable to re-decode a buffer with different settings. Buffer has already been transferred.")}let a;const i=this.workerNextTaskID++,o=e.byteLength,l=this._getWorker(i,o).then(c=>(a=c,new Promise((d,m)=>{a._callbacks[i]={resolve:d,reject:m},a.postMessage({type:"decode",id:i,taskConfig:t,buffer:e},[e])}))).then(c=>this._createGeometry(c.geometry));return l.catch(()=>!0).then(()=>{a&&i&&this._releaseTask(a,i)}),Kg.set(e,{key:n,promise:l}),l}_createGeometry(e){const t=new La;e.index&&t.setIndex(new Ka(e.index.array,1));for(let n=0;n<e.attributes.length;n++){const a=e.attributes[n],i=a.name,o=a.array,l=a.itemSize,c=new Ka(o,l);i==="color"&&(this._assignVertexColorSpace(c,a.vertexColorSpace),c.normalized=!(o instanceof Float32Array)),t.setAttribute(i,c)}return t}_assignVertexColorSpace(e,t){if(t!==Va)return;const n=new Bt;for(let a=0,i=e.count;a<i;a++)n.fromBufferAttribute(e,a),Kb.toWorkingColorSpace(n,Va),e.setXYZ(a,n.r,n.g,n.b)}_loadLibrary(e,t){const n=new gp(this.manager);return n.setPath(this.decoderPath),n.setResponseType(t),n.setWithCredentials(this.withCredentials),new Promise((a,i)=>{n.load(e,a,void 0,i)})}preload(){return this._initDecoder(),this}_initDecoder(){if(this.decoderPending)return this.decoderPending;const e=typeof WebAssembly!="object"||this.decoderConfig.type==="js",t=[];return e?t.push(this._loadLibrary("draco_decoder.js","text")):(t.push(this._loadLibrary("draco_wasm_wrapper.js","text")),t.push(this._loadLibrary("draco_decoder.wasm","arraybuffer"))),this.decoderPending=Promise.all(t).then(n=>{const a=n[0];e||(this.decoderConfig.wasmBinary=n[1]);const i=ZL.toString(),o=["/* draco decoder */",a,"","/* worker */",i.substring(i.indexOf("{")+1,i.lastIndexOf("}"))].join(`
42
+ */var NS;function qP(){if(NS)return Hg;NS=1;var s=ex();function e(p,f){return p===f&&(p!==0||1/p===1/f)||p!==p&&f!==f}var t=typeof Object.is=="function"?Object.is:e,n=s.useState,a=s.useEffect,i=s.useLayoutEffect,o=s.useDebugValue;function l(p,f){var b=f(),y=n({inst:{value:b,getSnapshot:f}}),w=y[0].inst,k=y[1];return i(function(){w.value=b,w.getSnapshot=f,c(w)&&k({inst:w})},[p,b,f]),a(function(){return c(w)&&k({inst:w}),p(function(){c(w)&&k({inst:w})})},[p]),o(b),b}function c(p){var f=p.getSnapshot;p=p.value;try{var b=f();return!t(p,b)}catch{return!0}}function d(p,f){return f()}var m=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?d:l;return Hg.useSyncExternalStore=s.useSyncExternalStore!==void 0?s.useSyncExternalStore:m,Hg}var AS;function YP(){return AS||(AS=1,$g.exports=qP()),$g.exports}var VP=YP();const KP=(s,e)=>Qo(e)?e:RP(e)&&Qo(e.defaultValue)?e.defaultValue:Array.isArray(s)?s[s.length-1]:s,XP={t:KP,ready:!1},ZP=()=>()=>{},Ue=(s,e={})=>{var _,P,L;const{i18n:t}=e,{i18n:n,defaultNS:a}=x.useContext(GP)||{},i=t||n||HP();i&&!i.reportNamespaces&&(i.reportNamespaces=new WP),i||wA(i,"NO_I18NEXT_INSTANCE","useTranslation: You will need to pass in an i18next instance by using initReactI18next");const o=x.useMemo(()=>{var R;return{...zP(),...(R=i==null?void 0:i.options)==null?void 0:R.react,...e}},[i,e]),{useSuspense:l,keyPrefix:c}=o,d=s||a||((_=i==null?void 0:i.options)==null?void 0:_.defaultNS),m=Qo(d)?[d]:d||["translation"],p=x.useMemo(()=>m,m);(L=(P=i==null?void 0:i.reportNamespaces)==null?void 0:P.addUsedNamespaces)==null||L.call(P,p);const f=x.useRef(0),b=x.useCallback(R=>{if(!i)return ZP;const{bindI18n:z,bindI18nStore:F}=o,$=()=>{f.current+=1,R()};return z&&i.on(z,$),F&&i.store.on(F,$),()=>{z&&z.split(" ").forEach(U=>i.off(U,$)),F&&F.split(" ").forEach(U=>i.store.off(U,$))}},[i,o]),y=x.useRef(),w=x.useCallback(()=>{if(!i)return XP;const R=!!(i.isInitialized||i.initializedStoreOnce)&&p.every(K=>PP(K,i,o)),z=e.lng||i.language,F=f.current,$=y.current;if($&&$.ready===R&&$.lng===z&&$.keyPrefix===c&&$.revision===F)return $;const G={t:i.getFixedT(z,o.nsMode==="fallback"?p:p[0],c),ready:R,lng:z,keyPrefix:c,revision:F};return y.current=G,G},[i,p,c,o,e.lng]),[k,S]=x.useState(0),{t:j,ready:C}=VP.useSyncExternalStore(b,w,w);x.useEffect(()=>{if(i&&!C&&!l){const R=()=>S(z=>z+1);e.lng?CS(i,e.lng,p,R):ty(i,p,R)}},[i,e.lng,p,C,l,k]);const A=i||{},D=x.useRef(null),M=x.useRef(),I=R=>{const z=Object.getOwnPropertyDescriptors(R);z.__original&&delete z.__original;const F=Object.create(Object.getPrototypeOf(R),z);if(!Object.prototype.hasOwnProperty.call(F,"__original"))try{Object.defineProperty(F,"__original",{value:R,writable:!1,enumerable:!1,configurable:!1})}catch{}return F},E=x.useMemo(()=>{const R=A,z=R==null?void 0:R.language;let F=R;R&&(D.current&&D.current.__original===R?M.current!==z?(F=I(R),D.current=F,M.current=z):F=D.current:(F=I(R),D.current=F,M.current=z));const $=[j,F,C];return $.t=j,$.i18n=F,$.ready=C,$},[j,A,C,A.resolvedLanguage,A.language,A.languages]);if(i&&l&&!C)throw new Promise(R=>{const z=()=>R();e.lng?CS(i,e.lng,p,z):ty(i,p,z)});return E};function sy(s){"@babel/helpers - typeof";return sy=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},sy(s)}function jA(){return typeof XMLHttpRequest=="function"||(typeof XMLHttpRequest>"u"?"undefined":sy(XMLHttpRequest))==="object"}function QP(s){return!!s&&typeof s.then=="function"}function JP(s){return QP(s)?s:Promise.resolve(s)}const eR="modulepreload",tR=function(s){return"/"+s},MS={},CA=function(e,t,n){let a=Promise.resolve();if(t&&t.length>0){let o=function(d){return Promise.all(d.map(m=>Promise.resolve(m).then(p=>({status:"fulfilled",value:p}),p=>({status:"rejected",reason:p}))))};document.getElementsByTagName("link");const l=document.querySelector("meta[property=csp-nonce]"),c=(l==null?void 0:l.nonce)||(l==null?void 0:l.getAttribute("nonce"));a=o(t.map(d=>{if(d=tR(d),d in MS)return;MS[d]=!0;const m=d.endsWith(".css"),p=m?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${p}`))return;const f=document.createElement("link");if(f.rel=m?"stylesheet":eR,m||(f.as="script"),f.crossOrigin="",f.href=d,c&&f.setAttribute("nonce",c),document.head.appendChild(f),m)return new Promise((b,y)=>{f.addEventListener("load",b),f.addEventListener("error",()=>y(new Error(`Unable to preload CSS for ${d}`)))})}))}function i(o){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=o,window.dispatchEvent(l),!l.defaultPrevented)throw o}return a.then(o=>{for(const l of o||[])l.status==="rejected"&&i(l.reason);return e().catch(i)})};function TS(s,e){var t=Object.keys(s);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(s);e&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(s,a).enumerable})),t.push.apply(t,n)}return t}function ES(s){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?TS(Object(t),!0).forEach(function(n){nR(s,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(s,Object.getOwnPropertyDescriptors(t)):TS(Object(t)).forEach(function(n){Object.defineProperty(s,n,Object.getOwnPropertyDescriptor(t,n))})}return s}function nR(s,e,t){return(e=sR(e))in s?Object.defineProperty(s,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):s[e]=t,s}function sR(s){var e=aR(s,"string");return Jo(e)=="symbol"?e:e+""}function aR(s,e){if(Jo(s)!="object"||!s)return s;var t=s[Symbol.toPrimitive];if(t!==void 0){var n=t.call(s,e);if(Jo(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(s)}function Jo(s){"@babel/helpers - typeof";return Jo=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Jo(s)}var Kr=typeof fetch=="function"?fetch:void 0;typeof global<"u"&&global.fetch?Kr=global.fetch:typeof window<"u"&&window.fetch&&(Kr=window.fetch);var ed;jA()&&(typeof global<"u"&&global.XMLHttpRequest?ed=global.XMLHttpRequest:typeof window<"u"&&window.XMLHttpRequest&&(ed=window.XMLHttpRequest));var kp;typeof ActiveXObject=="function"&&(typeof global<"u"&&global.ActiveXObject?kp=global.ActiveXObject:typeof window<"u"&&window.ActiveXObject&&(kp=window.ActiveXObject));typeof Kr!="function"&&(Kr=void 0);if(!Kr&&!ed&&!kp)try{CA(()=>import("./browser-ponyfill-DIm4hKhx.js").then(s=>s.b),__vite__mapDeps([0,1])).then(function(s){Kr=s.default}).catch(function(){})}catch{}var ay=function(e,t){if(t&&Jo(t)==="object"){var n="";for(var a in t)n+="&"+encodeURIComponent(a)+"="+encodeURIComponent(t[a]);if(!n)return e;e=e+(e.indexOf("?")!==-1?"&":"?")+n.slice(1)}return e},_S=function(e,t,n,a){var i=function(c){if(!c.ok)return n(c.statusText||"Error",{status:c.status});c.text().then(function(d){n(null,{status:c.status,data:d})}).catch(n)};if(a){var o=a(e,t);if(o instanceof Promise){o.then(i).catch(n);return}}typeof fetch=="function"?fetch(e,t).then(i).catch(n):Kr(e,t).then(i).catch(n)},DS=!1,iR=function(e,t,n,a){e.queryStringParams&&(t=ay(t,e.queryStringParams));var i=ES({},typeof e.customHeaders=="function"?e.customHeaders():e.customHeaders);typeof window>"u"&&typeof global<"u"&&typeof global.process<"u"&&global.process.versions&&global.process.versions.node&&(i["User-Agent"]="i18next-http-backend (node/".concat(global.process.version,"; ").concat(global.process.platform," ").concat(global.process.arch,")")),n&&(i["Content-Type"]="application/json");var o=typeof e.requestOptions=="function"?e.requestOptions(n):e.requestOptions,l=ES({method:n?"POST":"GET",body:n?e.stringify(n):void 0,headers:i},DS?{}:o),c=typeof e.alternateFetch=="function"&&e.alternateFetch.length>=1?e.alternateFetch:void 0;try{_S(t,l,a,c)}catch(d){if(!o||Object.keys(o).length===0||!d.message||d.message.indexOf("not implemented")<0)return a(d);try{Object.keys(o).forEach(function(m){delete l[m]}),_S(t,l,a,c),DS=!0}catch(m){a(m)}}},rR=function(e,t,n,a){n&&Jo(n)==="object"&&(n=ay("",n).slice(1)),e.queryStringParams&&(t=ay(t,e.queryStringParams));try{var i=ed?new ed:new kp("MSXML2.XMLHTTP.3.0");i.open(n?"POST":"GET",t,1),e.crossDomain||i.setRequestHeader("X-Requested-With","XMLHttpRequest"),i.withCredentials=!!e.withCredentials,n&&i.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),i.overrideMimeType&&i.overrideMimeType("application/json");var o=e.customHeaders;if(o=typeof o=="function"?o():o,o)for(var l in o)i.setRequestHeader(l,o[l]);i.onreadystatechange=function(){i.readyState>3&&a(i.status>=400?i.statusText:null,{status:i.status,data:i.responseText})},i.send(n)}catch(c){console&&console.log(c)}},oR=function(e,t,n,a){if(typeof n=="function"&&(a=n,n=void 0),a=a||function(){},Kr&&t.indexOf("file:")!==0)return iR(e,t,n,a);if(jA()||typeof ActiveXObject=="function")return rR(e,t,n,a);a(new Error("No fetch and no xhr implementation found!"))};function dc(s){"@babel/helpers - typeof";return dc=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},dc(s)}function PS(s,e){var t=Object.keys(s);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(s);e&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(s,a).enumerable})),t.push.apply(t,n)}return t}function Ug(s){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?PS(Object(t),!0).forEach(function(n){NA(s,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(s,Object.getOwnPropertyDescriptors(t)):PS(Object(t)).forEach(function(n){Object.defineProperty(s,n,Object.getOwnPropertyDescriptor(t,n))})}return s}function lR(s,e){if(!(s instanceof e))throw new TypeError("Cannot call a class as a function")}function cR(s,e){for(var t=0;t<e.length;t++){var n=e[t];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(s,AA(n.key),n)}}function uR(s,e,t){return e&&cR(s.prototype,e),Object.defineProperty(s,"prototype",{writable:!1}),s}function NA(s,e,t){return(e=AA(e))in s?Object.defineProperty(s,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):s[e]=t,s}function AA(s){var e=dR(s,"string");return dc(e)=="symbol"?e:e+""}function dR(s,e){if(dc(s)!="object"||!s)return s;var t=s[Symbol.toPrimitive];if(t!==void 0){var n=t.call(s,e);if(dc(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(s)}var hR=function(){return{loadPath:"/locales/{{lng}}/{{ns}}.json",addPath:"/locales/add/{{lng}}/{{ns}}",parse:function(t){return JSON.parse(t)},stringify:JSON.stringify,parsePayload:function(t,n,a){return NA({},n,a||"")},parseLoadPayload:function(t,n){},request:oR,reloadInterval:typeof window<"u"?!1:3600*1e3,customHeaders:{},queryStringParams:{},crossDomain:!1,withCredentials:!1,overrideMimeType:!1,requestOptions:{mode:"cors",credentials:"same-origin",cache:"default"}}},MA=(function(){function s(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};lR(this,s),this.services=e,this.options=t,this.allOptions=n,this.type="backend",this.init(e,t,n)}return uR(s,[{key:"init",value:function(t){var n=this,a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};if(this.services=t,this.options=Ug(Ug(Ug({},hR()),this.options||{}),a),this.allOptions=i,this.services&&this.options.reloadInterval){var o=setInterval(function(){return n.reload()},this.options.reloadInterval);dc(o)==="object"&&typeof o.unref=="function"&&o.unref()}}},{key:"readMulti",value:function(t,n,a){this._readAny(t,t,n,n,a)}},{key:"read",value:function(t,n,a){this._readAny([t],t,[n],n,a)}},{key:"_readAny",value:function(t,n,a,i,o){var l=this,c=this.options.loadPath;typeof this.options.loadPath=="function"&&(c=this.options.loadPath(t,a)),c=JP(c),c.then(function(d){if(!d)return o(null,{});var m=l.services.interpolator.interpolate(d,{lng:t.join("+"),ns:a.join("+")});l.loadUrl(m,o,n,i)})}},{key:"loadUrl",value:function(t,n,a,i){var o=this,l=typeof a=="string"?[a]:a,c=typeof i=="string"?[i]:i,d=this.options.parseLoadPayload(l,c);this.options.request(this.options,t,d,function(m,p){if(p&&(p.status>=500&&p.status<600||!p.status))return n("failed loading "+t+"; status code: "+p.status,!0);if(p&&p.status>=400&&p.status<500)return n("failed loading "+t+"; status code: "+p.status,!1);if(!p&&m&&m.message){var f=m.message.toLowerCase(),b=["failed","fetch","network","load"].find(function(k){return f.indexOf(k)>-1});if(b)return n("failed loading "+t+": "+m.message,!0)}if(m)return n(m,!1);var y,w;try{typeof p.data=="string"?y=o.options.parse(p.data,a,i):y=p.data}catch{w="failed parsing "+t+" to json"}if(w)return n(w,!1);n(null,y)})}},{key:"create",value:function(t,n,a,i,o){var l=this;if(this.options.addPath){typeof t=="string"&&(t=[t]);var c=this.options.parsePayload(n,a,i),d=0,m=[],p=[];t.forEach(function(f){var b=l.options.addPath;typeof l.options.addPath=="function"&&(b=l.options.addPath(f,n));var y=l.services.interpolator.interpolate(b,{lng:f,ns:n});l.options.request(l.options,y,c,function(w,k){d+=1,m.push(w),p.push(k),d===t.length&&typeof o=="function"&&o(m,p)})})}}},{key:"reload",value:function(){var t=this,n=this.services,a=n.backendConnector,i=n.languageUtils,o=n.logger,l=a.language;if(!(l&&l.toLowerCase()==="cimode")){var c=[],d=function(p){var f=i.toResolveHierarchy(p);f.forEach(function(b){c.indexOf(b)<0&&c.push(b)})};d(l),this.allOptions.preload&&this.allOptions.preload.forEach(function(m){return d(m)}),c.forEach(function(m){t.allOptions.ns.forEach(function(p){a.read(m,p,"read",null,null,function(f,b){f&&o.warn("loading namespace ".concat(p," for language ").concat(m," failed"),f),!f&&b&&o.log("loaded namespace ".concat(p," for language ").concat(m),b),a.loaded("".concat(m,"|").concat(p),f,b)})})})}}}])})();MA.type="backend";const{slice:pR,forEach:mR}=[];function fR(s){return mR.call(pR.call(arguments,1),e=>{if(e)for(const t in e)s[t]===void 0&&(s[t]=e[t])}),s}function gR(s){return typeof s!="string"?!1:[/<\s*script.*?>/i,/<\s*\/\s*script\s*>/i,/<\s*img.*?on\w+\s*=/i,/<\s*\w+\s*on\w+\s*=.*?>/i,/javascript\s*:/i,/vbscript\s*:/i,/expression\s*\(/i,/eval\s*\(/i,/alert\s*\(/i,/document\.cookie/i,/document\.write\s*\(/i,/window\.location/i,/innerHTML/i].some(t=>t.test(s))}const RS=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/,bR=function(s,e){const n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{path:"/"},a=encodeURIComponent(e);let i=`${s}=${a}`;if(n.maxAge>0){const o=n.maxAge-0;if(Number.isNaN(o))throw new Error("maxAge should be a Number");i+=`; Max-Age=${Math.floor(o)}`}if(n.domain){if(!RS.test(n.domain))throw new TypeError("option domain is invalid");i+=`; Domain=${n.domain}`}if(n.path){if(!RS.test(n.path))throw new TypeError("option path is invalid");i+=`; Path=${n.path}`}if(n.expires){if(typeof n.expires.toUTCString!="function")throw new TypeError("option expires is invalid");i+=`; Expires=${n.expires.toUTCString()}`}if(n.httpOnly&&(i+="; HttpOnly"),n.secure&&(i+="; Secure"),n.sameSite)switch(typeof n.sameSite=="string"?n.sameSite.toLowerCase():n.sameSite){case!0:i+="; SameSite=Strict";break;case"lax":i+="; SameSite=Lax";break;case"strict":i+="; SameSite=Strict";break;case"none":i+="; SameSite=None";break;default:throw new TypeError("option sameSite is invalid")}return n.partitioned&&(i+="; Partitioned"),i},LS={create(s,e,t,n){let a=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{path:"/",sameSite:"strict"};t&&(a.expires=new Date,a.expires.setTime(a.expires.getTime()+t*60*1e3)),n&&(a.domain=n),document.cookie=bR(s,e,a)},read(s){const e=`${s}=`,t=document.cookie.split(";");for(let n=0;n<t.length;n++){let a=t[n];for(;a.charAt(0)===" ";)a=a.substring(1,a.length);if(a.indexOf(e)===0)return a.substring(e.length,a.length)}return null},remove(s,e){this.create(s,"",-1,e)}};var yR={name:"cookie",lookup(s){let{lookupCookie:e}=s;if(e&&typeof document<"u")return LS.read(e)||void 0},cacheUserLanguage(s,e){let{lookupCookie:t,cookieMinutes:n,cookieDomain:a,cookieOptions:i}=e;t&&typeof document<"u"&&LS.create(t,s,n,a,i)}},xR={name:"querystring",lookup(s){var n;let{lookupQuerystring:e}=s,t;if(typeof window<"u"){let{search:a}=window.location;!window.location.search&&((n=window.location.hash)==null?void 0:n.indexOf("?"))>-1&&(a=window.location.hash.substring(window.location.hash.indexOf("?")));const o=a.substring(1).split("&");for(let l=0;l<o.length;l++){const c=o[l].indexOf("=");c>0&&o[l].substring(0,c)===e&&(t=o[l].substring(c+1))}}return t}},vR={name:"hash",lookup(s){var a;let{lookupHash:e,lookupFromHashIndex:t}=s,n;if(typeof window<"u"){const{hash:i}=window.location;if(i&&i.length>2){const o=i.substring(1);if(e){const l=o.split("&");for(let c=0;c<l.length;c++){const d=l[c].indexOf("=");d>0&&l[c].substring(0,d)===e&&(n=l[c].substring(d+1))}}if(n)return n;if(!n&&t>-1){const l=i.match(/\/([a-zA-Z-]*)/g);return Array.isArray(l)?(a=l[typeof t=="number"?t:0])==null?void 0:a.replace("/",""):void 0}}}return n}};let zl=null;const OS=()=>{if(zl!==null)return zl;try{if(zl=typeof window<"u"&&window.localStorage!==null,!zl)return!1;const s="i18next.translate.boo";window.localStorage.setItem(s,"foo"),window.localStorage.removeItem(s)}catch{zl=!1}return zl};var wR={name:"localStorage",lookup(s){let{lookupLocalStorage:e}=s;if(e&&OS())return window.localStorage.getItem(e)||void 0},cacheUserLanguage(s,e){let{lookupLocalStorage:t}=e;t&&OS()&&window.localStorage.setItem(t,s)}};let $l=null;const IS=()=>{if($l!==null)return $l;try{if($l=typeof window<"u"&&window.sessionStorage!==null,!$l)return!1;const s="i18next.translate.boo";window.sessionStorage.setItem(s,"foo"),window.sessionStorage.removeItem(s)}catch{$l=!1}return $l};var kR={name:"sessionStorage",lookup(s){let{lookupSessionStorage:e}=s;if(e&&IS())return window.sessionStorage.getItem(e)||void 0},cacheUserLanguage(s,e){let{lookupSessionStorage:t}=e;t&&IS()&&window.sessionStorage.setItem(t,s)}},SR={name:"navigator",lookup(s){const e=[];if(typeof navigator<"u"){const{languages:t,userLanguage:n,language:a}=navigator;if(t)for(let i=0;i<t.length;i++)e.push(t[i]);n&&e.push(n),a&&e.push(a)}return e.length>0?e:void 0}},jR={name:"htmlTag",lookup(s){let{htmlTag:e}=s,t;const n=e||(typeof document<"u"?document.documentElement:null);return n&&typeof n.getAttribute=="function"&&(t=n.getAttribute("lang")),t}},CR={name:"path",lookup(s){var a;let{lookupFromPathIndex:e}=s;if(typeof window>"u")return;const t=window.location.pathname.match(/\/([a-zA-Z-]*)/g);return Array.isArray(t)?(a=t[typeof e=="number"?e:0])==null?void 0:a.replace("/",""):void 0}},NR={name:"subdomain",lookup(s){var a,i;let{lookupFromSubdomainIndex:e}=s;const t=typeof e=="number"?e+1:1,n=typeof window<"u"&&((i=(a=window.location)==null?void 0:a.hostname)==null?void 0:i.match(/^(\w{2,5})\.(([a-z0-9-]{1,63}\.[a-z]{2,6})|localhost)/i));if(n)return n[t]}};let TA=!1;try{document.cookie,TA=!0}catch{}const EA=["querystring","cookie","localStorage","sessionStorage","navigator","htmlTag"];TA||EA.splice(1,1);const AR=()=>({order:EA,lookupQuerystring:"lng",lookupCookie:"i18next",lookupLocalStorage:"i18nextLng",lookupSessionStorage:"i18nextLng",caches:["localStorage"],excludeCacheFor:["cimode"],convertDetectedLanguage:s=>s});class _A{constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.type="languageDetector",this.detectors={},this.init(e,t)}init(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{languageUtils:{}},t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};this.services=e,this.options=fR(t,this.options||{},AR()),typeof this.options.convertDetectedLanguage=="string"&&this.options.convertDetectedLanguage.indexOf("15897")>-1&&(this.options.convertDetectedLanguage=a=>a.replace("-","_")),this.options.lookupFromUrlIndex&&(this.options.lookupFromPathIndex=this.options.lookupFromUrlIndex),this.i18nOptions=n,this.addDetector(yR),this.addDetector(xR),this.addDetector(wR),this.addDetector(kR),this.addDetector(SR),this.addDetector(jR),this.addDetector(CR),this.addDetector(NR),this.addDetector(vR)}addDetector(e){return this.detectors[e.name]=e,this}detect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.options.order,t=[];return e.forEach(n=>{if(this.detectors[n]){let a=this.detectors[n].lookup(this.options);a&&typeof a=="string"&&(a=[a]),a&&(t=t.concat(a))}}),t=t.filter(n=>n!=null&&!gR(n)).map(n=>this.options.convertDetectedLanguage(n)),this.services&&this.services.languageUtils&&this.services.languageUtils.getBestMatchFromCodes?t:t.length>0?t[0]:null}cacheUserLanguage(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.options.caches;t&&(this.options.excludeCacheFor&&this.options.excludeCacheFor.indexOf(e)>-1||t.forEach(n=>{this.detectors[n]&&this.detectors[n].cacheUserLanguage(e,this.options)}))}}_A.type="languageDetector";const Sp={idle:"#4aff9e",working:"#4a9eff",waiting:"#ff9e4a",waiting_permission:"#ffcc00",error:"#ff4a4a",offline:"#888888",orphaned:"#ff9e4a",default:"#888888"},Xr={running:"#4aff9e",stopped:"#888888",error:"#ff4a4a",unknown:"#ffaa00",starting:"#4a9eff",stopping:"#ffaa00"},DA={on_track:"#4aff9e",stalled:"#ff9e4a",blocked:"#ff4a4a",completed:"#4a9eff",idle:"#888888"},MR=["#4a9eff","#4aff9e","#ff9e4a","#ff4a9e","#9e4aff","#ff4a4a","#4affff","#ffff4a","#4ad7ff","#00e6a8","#ff6b4a","#ff66cc","#b84aff","#ff4a7a","#00d9ff","#e6ff4a","#1a3a6e","#1a5e3a","#6e3a1a","#6e1a4a","#4a1a6e","#6e1a1a","#1a5e5e","#5e5e1a","#1a4a6e","#145a47","#6e2c1a","#6e1a5e","#3b1a6e","#6e1a33","#14566e","#4f5e1a"],Lh={recent:"#50fa7b",short:"#f1fa8c",medium:"#ffb86c",long:"#ff5555"};function am(s){const t=Math.floor((Date.now()-s)/1e3)/60;return t<1?Lh.recent:t<5?Lh.short:t<30?Lh.medium:Lh.long}function iy(s){return Sp[s]??Sp.default}let rp=null;function PA(){if(!rp)try{rp=globalThis.__i18n}catch{}return rp}function TR(s){rp=s}function ER(s){return s>=1e6?(s/1e6).toFixed(1)+"M":s>=1e3?(s/1e3).toFixed(1)+"K":s.toString()}function ry(s){return s>=1e6?(s/1e6).toFixed(1)+"M":s>=1e3?(s/1e3).toFixed(1)+"K":s.toString()}function RA(s){var a;const e=PA(),t=(a=e==null?void 0:e.t)==null?void 0:a.bind(e),n=Math.floor((Date.now()-s)/1e3);return n<60?t?t("common:time.seconds",{count:n}):`${n}s`:n<3600?t?t("common:time.minutes",{count:Math.floor(n/60)}):`${Math.floor(n/60)}m`:n<86400?t?t("common:time.hours",{count:Math.floor(n/3600)}):`${Math.floor(n/3600)}h`:t?t("common:time.days",{count:Math.floor(n/86400)}):`${Math.floor(n/86400)}d`}function im(s){var d;const e=PA(),t=(d=e==null?void 0:e.t)==null?void 0:d.bind(e),n=Math.floor((Date.now()-s)/1e3);if(n<5)return t?t("common:time.justNow"):"just now";if(n<60)return t?t("common:time.secondsAgo",{count:n}):`${n}s ago`;const a=Math.floor(n/60);if(a<60){const m=n%60;return m>0?t?t("common:time.minutesSecondsAgo",{minutes:a,seconds:m}):`${a}m ${m}s ago`:t?t("common:time.minutesAgo",{count:a}):`${a}m ago`}const i=Math.floor(a/60),o=a%60;if(i<24)return o>0?t?t("common:time.hoursMinutesAgo",{hours:i,minutes:o}):`${i}h ${o}m ago`:t?t("common:time.hoursAgo",{count:i}):`${i}h ago`;const l=Math.floor(i/24),c=i%24;return c>0?t?t("common:time.daysHoursAgo",{days:l,hours:c}):`${l}d ${c}h ago`:t?t("common:time.daysAgo",{count:l}):`${l}d ago`}function Gr(s,e){return s?e?s.replace(/\s*\(?\s*~?\$[\d,.]+\s*\)?/g,"").replace(/\s*cost[:\s]+~?\$[\d,.]+/gi,"").replace(/\s*price[:\s]+~?\$[\d,.]+/gi,"").replace(/\s*\(~?\$[\d,.]+\s*(?:USD|cost|spent)?\)/gi,"").replace(/\s*-\s*~?\$[\d,.]+\s*$/g,"").replace(/[^\S\n]+/g," ").trim():s:""}yn.use(MA).use(_A).use(UP).init({fallbackLng:"en",ns:["common","tools","config","errors","notifications","dashboard","terminal"],defaultNS:"common",backend:{loadPath:"/locales/{{lng}}/{{ns}}.json"},detection:{order:["localStorage","navigator"],lookupLocalStorage:"tide-commander-language",caches:["localStorage"]},interpolation:{escapeValue:!1},react:{useSuspense:!0}}).then(()=>{TR(yn)});const pt={CONFIG:"tide-commander-config",SHOW_FPS:"tide-show-fps",SETTINGS:"tide-settings",SHORTCUTS:"tide-shortcuts",MOUSE_CONTROLS:"tide-mouse-controls",BACKEND_URL:"tide-backend-url",AUTH_TOKEN:"tide-auth-token",SCENE_VIEW_MODE:"tide-scene-view-mode",CAMERA_STATE:"tide-camera-state",CAMERA_STATE_2D:"tide-camera-state-2d",VIEW_MODE:"guake-view-mode",ADVANCED_VIEW:"guake-advanced-view",TERMINAL_HEIGHT:"guake-terminal-height",INPUT_TEXT_PREFIX:"guake-input-",PASTED_TEXTS_PREFIX:"guake-pasted-",COMMANDER_TAB:"commander-active-tab",COMMANDER_FILTERS:"commander-filters",LAST_CWD:"tide-last-cwd",GLOBAL_SUPERVISOR_COLLAPSED:"tide-global-supervisor-collapsed",TOOLS_COLLAPSED:"tide-tool-history-collapsed",FILES_COLLAPSED:"tide-file-history-collapsed",MOBILE_VIEW:"tide-mobile-view",TREE_PANEL_WIDTH:"tide-tree-panel-width",AGENT_ORDER:"tide-agent-order",AOP_CONFIG:"tide-aop-config",UNSEEN_AGENTS:"tide-unseen-agents"};function Ya(s,e){try{const t=localStorage.getItem(s);return t===null?e:JSON.parse(t)}catch{return e}}function As(s,e=""){try{return localStorage.getItem(s)??e}catch{return e}}function oy(s,e=!1){try{const t=localStorage.getItem(s);return t===null?e:t==="true"}catch{return e}}function LA(s,e){try{const t=localStorage.getItem(s);if(t===null)return e;const n=Number(t);return isNaN(n)?e:n}catch{return e}}function yi(s,e){try{localStorage.setItem(s,JSON.stringify(e))}catch(t){console.error(`Failed to save to localStorage: ${s}`,t)}}function ta(s,e){try{localStorage.setItem(s,e)}catch(t){console.error(`Failed to save to localStorage: ${s}`,t)}}function ly(s,e){try{localStorage.setItem(s,String(e))}catch(t){console.error(`Failed to save to localStorage: ${s}`,t)}}function OA(s,e){try{localStorage.setItem(s,String(e))}catch(t){console.error(`Failed to save to localStorage: ${s}`,t)}}function BS(s){try{localStorage.removeItem(s)}catch(e){console.error(`Failed to remove from localStorage: ${s}`,e)}}function IA(){const s=As(pt.BACKEND_URL,"");return s?s.replace(/\/$/,""):`${window.location.protocol}//${window.location.host}`}function ti(){return As(pt.AUTH_TOKEN,"")}function st(s){return`${IA()}${s}`}async function mt(s,e){const t=ti(),n=new Headers(e==null?void 0:e.headers);return t&&n.set("X-Auth-Token",t),fetch(s,{...e,headers:n})}function hd(s){const e=ti();if(!e)return s;try{const t=!s.startsWith("http://")&&!s.startsWith("https://"),n=t?"http://dummy":void 0,a=new URL(s,n);return a.searchParams.set("token",e),t?a.pathname+a.search:a.toString()}catch{const t=s.includes("?")?"&":"?";return`${s}${t}token=${encodeURIComponent(e)}`}}function Bs(s=!1,e){const[t,n]=x.useState(s),[a,i]=x.useState(e),o=x.useCallback(d=>{d!==void 0&&i(d),n(!0)},[]),l=x.useCallback(()=>{n(!1)},[]),c=x.useCallback(()=>{n(d=>!d)},[]);return{isOpen:t,data:a,open:o,close:l,toggle:c,setData:i}}function _R(){const[s,e]=x.useState(null),t=x.useCallback(a=>{e(a)},[]),n=x.useCallback(()=>{e(null)},[]);return{isOpen:s!==null,id:s,open:t,close:n}}function DR(){const[s,e]=x.useState(!1),[t,n]=x.useState({x:0,y:0}),[a,i]=x.useState({x:0,z:0}),[o,l]=x.useState({type:"ground"}),c=x.useCallback((m,p,f)=>{n(m),i(p),l(f),e(!0)},[]),d=x.useCallback(()=>{e(!1)},[]);return{isOpen:s,screenPosition:t,worldPosition:a,target:o,open:c,close:d}}const qa=[],PR=new Set;function jp(){PR.forEach(s=>s())}function RR(s,e){const t=qa.findIndex(n=>n.id===s);return t!==-1&&qa.splice(t,1),qa.push({id:s,close:e}),jp(),()=>{const n=qa.findIndex(a=>a.id===s);n!==-1&&(qa.splice(n,1),jp())}}function cy(){return qa.length===0?!1:(qa.pop().close(),jp(),!0)}function LR(...s){const e=new Set(s);for(;qa.length>0;){const t=qa[qa.length-1];if(e.has(t.id))break;qa.pop().close()}jp()}function Pn(s,e,t){const n=x.useRef(t);n.current=t,x.useEffect(()=>e?RR(s,()=>n.current()):void 0,[s,e])}let uy,dy;try{uy=require("@capacitor/haptics").Haptics,dy=require("@capacitor/haptics").ImpactStyle}catch{}function FS(s,e){const{threshold:t=80,maxVerticalMovement:n=50,enabled:a=!0,onSwipeLeft:i,onSwipeRight:o,onSwipeMove:l,onSwipeCancel:c}=e,d=x.useRef({startX:0,startY:0,startTime:0,isTracking:!1,hasMovedEnough:!1}),m=x.useCallback(b=>{if(b.touches.length!==1)return;const y=b.touches[0];d.current={startX:y.clientX,startY:y.clientY,startTime:Date.now(),isTracking:!0,hasMovedEnough:!1}},[]),p=x.useCallback(b=>{if(!d.current.isTracking||b.touches.length!==1)return;const y=b.touches[0],w=y.clientX-d.current.startX;if(Math.abs(y.clientY-d.current.startY)>n){d.current.isTracking=!1,d.current.hasMovedEnough&&(c==null||c());return}const j=window.innerWidth*.4,C=Math.max(-1,Math.min(1,w/j));Math.abs(w)>=12&&(d.current.hasMovedEnough=!0,l==null||l(C))},[n,l,c]),f=x.useCallback(b=>{const y=d.current.isTracking,w=d.current.hasMovedEnough;if(!y)return;const k=b.changedTouches[0],S=k.clientX-d.current.startX,j=Math.abs(k.clientY-d.current.startY),C=Date.now()-d.current.startTime;d.current.isTracking=!1,d.current.hasMovedEnough=!1,Math.abs(S)>=t&&j<=n&&C<500?(uy&&dy?uy.impact({style:dy.Light}).catch(()=>{navigator.vibrate&&navigator.vibrate(8)}):navigator.vibrate&&navigator.vibrate(8),S>0?o==null||o():i==null||i()):w&&(c==null||c())},[t,n,i,o,c]);x.useEffect(()=>{const b=s.current;if(!(!b||!a||!(window.innerWidth<=768&&"ontouchstart"in window)))return b.addEventListener("touchstart",m,{passive:!0}),b.addEventListener("touchmove",p,{passive:!0}),b.addEventListener("touchend",f,{passive:!0}),()=>{b.removeEventListener("touchstart",m),b.removeEventListener("touchmove",p),b.removeEventListener("touchend",f)}},[s,a,m,p,f])}const OR={width:400,height:300,copyStyleSheets:!0,keepOnTop:"focus"};function IR(){return"documentPictureInPicture"in window}function BR(s,e){for(const i of s.styleSheets)try{if(i.cssRules){const o=e.createElement("style");for(const l of i.cssRules)o.appendChild(e.createTextNode(l.cssText));e.head.appendChild(o)}}catch{if(i.href){const o=e.createElement("link");o.rel="stylesheet",o.href=i.href,e.head.appendChild(o)}}const t=s.documentElement.style.cssText;t&&(e.documentElement.style.cssText=t);const n=getComputedStyle(s.documentElement),a=[];for(let i=0;i<n.length;i++){const o=n[i];o.startsWith("--")&&a.push(`${o}: ${n.getPropertyValue(o)}`)}if(a.length>0){const i=e.createElement("style");i.textContent=`:root { ${a.join("; ")} }`,e.head.appendChild(i)}}function FR(){const[s,e]=x.useState(!1),[t,n]=x.useState(null),[a,i]=x.useState(null),o=x.useRef(null),l=IR(),c=x.useCallback(()=>{if(o.current){const p=o.current.__cleanupFns;p&&p.forEach(f=>f()),o.current.close(),o.current=null}n(null),i(null),e(!1)},[]),d=x.useCallback(async p=>{if(!l)return console.warn("Document Picture-in-Picture is not supported in this browser"),!1;o.current&&c();const f={...OR,...p};try{const y=await window.documentPictureInPicture.requestWindow({width:f.width,height:f.height,disallowReturnToOpener:!0});o.current=y,f.copyStyleSheets&&BR(document,y.document);const w=y.document.createElement("div");w.id="pip-root",w.style.width="100%",w.style.height="100%",y.document.body.appendChild(w),y.document.body.style.margin="0",y.document.body.style.padding="0",y.document.body.style.overflow="hidden",y.addEventListener("pagehide",()=>{o.current=null,n(null),i(null),e(!1)});const k=[];if(f.keepOnTop&&f.keepOnTop!=="none"){const S=f.keepOnTop==="raise",j=()=>{o.current&&!o.current.closed&&setTimeout(()=>{o.current&&!o.current.closed&&(o.current.focus(),S&&setTimeout(()=>window.focus(),10))},50)},C=()=>{document.visibilityState==="visible"&&o.current&&!o.current.closed&&setTimeout(()=>{o.current&&!o.current.closed&&(o.current.focus(),S&&setTimeout(()=>window.focus(),10))},100)};window.addEventListener("focus",j),document.addEventListener("visibilitychange",C),k.push(()=>window.removeEventListener("focus",j),()=>document.removeEventListener("visibilitychange",C))}return y.__cleanupFns=k,n(y),i(w),e(!0),!0}catch(b){return console.error("Failed to open Picture-in-Picture window:",b),!1}},[l,c]),m=x.useCallback(async p=>{s?c():await d(p)},[s,d,c]);return x.useEffect(()=>()=>{o.current&&o.current.close()},[]),{isOpen:s,pipWindow:t,pipContainer:a,isSupported:l,open:d,close:c,toggle:m}}function vu(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,s=>{const e=Math.random()*16|0;return(s==="x"?e:e&3|8).toString(16)})}class zR{constructor(){W(this,"messages",new Map);W(this,"logs",[]);W(this,"maxMessagesPerAgent",200);W(this,"maxLogs",500);W(this,"enabled",!1);W(this,"listeners",new Set);W(this,"logListeners",new Set)}setEnabled(e){this.enabled=e,this.notifyListeners("all")}isEnabled(){return this.enabled}captureSent(e,t){if(this.enabled)try{const n=JSON.parse(t);console.log(`[AgentDebugger] SENT - agent: ${e.slice(0,4)}, type: ${n.type}, size: ${t.length}B`),this.addMessage(e,{id:vu(),agentId:e,direction:"sent",type:n.type||"unknown",payload:n.payload||n,timestamp:Date.now(),size:t.length,raw:t})}catch(n){console.error("[AgentDebugger] Failed to parse SENT message:",String(n).slice(0,80)),this.addMessage(e,{id:vu(),agentId:e,direction:"sent",type:"parse_error",payload:{error:String(n)},timestamp:Date.now(),size:t.length,raw:t})}}captureReceived(e,t){if(this.enabled)try{const n=JSON.parse(t);console.log(`[AgentDebugger] RECEIVED - agent: ${e.slice(0,4)}, type: ${n.type}, size: ${t.length}B`),this.addMessage(e,{id:vu(),agentId:e,direction:"received",type:n.type||"unknown",payload:n.payload||n,timestamp:Date.now(),size:t.length,raw:t})}catch(n){console.error("[AgentDebugger] Failed to parse RECEIVED message:",String(n).slice(0,80)),this.addMessage(e,{id:vu(),agentId:e,direction:"received",type:"parse_error",payload:{error:String(n)},timestamp:Date.now(),size:t.length,raw:t})}}addMessage(e,t){let n=this.messages.get(e);n||(n=[],this.messages.set(e,n)),n.push(t),console.log(`[AgentDebugger] Added message for ${e}, total: ${n.length}, type: ${t.type}, direction: ${t.direction}`),n.length>this.maxMessagesPerAgent&&n.shift(),this.notifyListeners(e)}getMessages(e){return this.messages.get(e)||[]}getStats(e){const t=this.getMessages(e),n=t.filter(o=>o.direction==="sent").length,a=t.filter(o=>o.direction==="received").length,i=[...new Set(t.map(o=>o.type))];return{total:t.length,sent:n,received:a,messageTypes:i}}clearMessages(e){this.messages.delete(e),this.notifyListeners(e)}clearAllMessages(){this.messages.clear(),this.notifyListeners("all")}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}notifyListeners(e){this.listeners.forEach(t=>t(e))}getAgentIds(){return Array.from(this.messages.keys())}log(e,t,n,a){const i={id:vu(),level:e,message:t,data:n,timestamp:Date.now(),source:a};this.logs.push(i),this.logs.length>this.maxLogs&&this.logs.shift(),this.notifyLogListeners()}debug(e,t,n){this.log("debug",e,t,n)}info(e,t,n){this.log("info",e,t,n)}warn(e,t,n){this.log("warn",e,t,n)}error(e,t,n){this.log("error",e,t,n)}getLogs(){return this.logs}clearLogs(){this.logs=[],this.notifyLogListeners()}subscribeLogs(e){return this.logListeners.add(e),()=>this.logListeners.delete(e)}notifyLogListeners(){this.logListeners.forEach(e=>e())}}const vs=new zR,td={debug:(s,e,t)=>vs.debug(s,e,t),info:(s,e,t)=>vs.info(s,e,t),warn:(s,e,t)=>vs.warn(s,e,t),error:(s,e,t)=>vs.error(s,e,t)};/*! Capacitor: https://capacitorjs.com/ - MIT License */var hc;(function(s){s.Unimplemented="UNIMPLEMENTED",s.Unavailable="UNAVAILABLE"})(hc||(hc={}));class Gg extends Error{constructor(e,t,n){super(e),this.message=e,this.code=t,this.data=n}}const $R=s=>{var e,t;return s!=null&&s.androidBridge?"android":!((t=(e=s==null?void 0:s.webkit)===null||e===void 0?void 0:e.messageHandlers)===null||t===void 0)&&t.bridge?"ios":"web"},HR=s=>{const e=s.CapacitorCustomPlatform||null,t=s.Capacitor||{},n=t.Plugins=t.Plugins||{},a=()=>e!==null?e.name:$R(s),i=()=>a()!=="web",o=p=>{const f=d.get(p);return!!(f!=null&&f.platforms.has(a())||l(p))},l=p=>{var f;return(f=t.PluginHeaders)===null||f===void 0?void 0:f.find(b=>b.name===p)},c=p=>s.console.error(p),d=new Map,m=(p,f={})=>{const b=d.get(p);if(b)return console.warn(`Capacitor plugin "${p}" already registered. Cannot register plugins twice.`),b.proxy;const y=a(),w=l(p);let k;const S=async()=>(!k&&y in f?k=typeof f[y]=="function"?k=await f[y]():k=f[y]:e!==null&&!k&&"web"in f&&(k=typeof f.web=="function"?k=await f.web():k=f.web),k),j=(E,_)=>{var P,L;if(w){const R=w==null?void 0:w.methods.find(z=>_===z.name);if(R)return R.rtype==="promise"?z=>t.nativePromise(p,_.toString(),z):(z,F)=>t.nativeCallback(p,_.toString(),z,F);if(E)return(P=E[_])===null||P===void 0?void 0:P.bind(E)}else{if(E)return(L=E[_])===null||L===void 0?void 0:L.bind(E);throw new Gg(`"${p}" plugin is not implemented on ${y}`,hc.Unimplemented)}},C=E=>{let _;const P=(...L)=>{const R=S().then(z=>{const F=j(z,E);if(F){const $=F(...L);return _=$==null?void 0:$.remove,$}else throw new Gg(`"${p}.${E}()" is not implemented on ${y}`,hc.Unimplemented)});return E==="addListener"&&(R.remove=async()=>_()),R};return P.toString=()=>`${E.toString()}() { [capacitor code] }`,Object.defineProperty(P,"name",{value:E,writable:!1,configurable:!1}),P},A=C("addListener"),D=C("removeListener"),M=(E,_)=>{const P=A({eventName:E},_),L=async()=>{const z=await P;D({eventName:E,callbackId:z},_)},R=new Promise(z=>P.then(()=>z({remove:L})));return R.remove=async()=>{console.warn("Using addListener() without 'await' is deprecated."),await L()},R},I=new Proxy({},{get(E,_){switch(_){case"$$typeof":return;case"toJSON":return()=>({});case"addListener":return w?M:A;case"removeListener":return D;default:return C(_)}}});return n[p]=I,d.set(p,{name:p,proxy:I,platforms:new Set([...Object.keys(f),...w?[y]:[]])}),I};return t.convertFileSrc||(t.convertFileSrc=p=>p),t.getPlatform=a,t.handleError=c,t.isNativePlatform=i,t.isPluginAvailable=o,t.registerPlugin=m,t.Exception=Gg,t.DEBUG=!!t.DEBUG,t.isLoggingEnabled=!!t.isLoggingEnabled,t},UR=s=>s.Capacitor=HR(s),ba=UR(typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{}),pd=ba.registerPlugin;class rx{constructor(){this.listeners={},this.retainedEventArguments={},this.windowListeners={}}addListener(e,t){let n=!1;this.listeners[e]||(this.listeners[e]=[],n=!0),this.listeners[e].push(t);const i=this.windowListeners[e];i&&!i.registered&&this.addWindowListener(i),n&&this.sendRetainedArgumentsForEvent(e);const o=async()=>this.removeListener(e,t);return Promise.resolve({remove:o})}async removeAllListeners(){this.listeners={};for(const e in this.windowListeners)this.removeWindowListener(this.windowListeners[e]);this.windowListeners={}}notifyListeners(e,t,n){const a=this.listeners[e];if(!a){if(n){let i=this.retainedEventArguments[e];i||(i=[]),i.push(t),this.retainedEventArguments[e]=i}return}a.forEach(i=>i(t))}hasListeners(e){var t;return!!(!((t=this.listeners[e])===null||t===void 0)&&t.length)}registerWindowListener(e,t){this.windowListeners[t]={registered:!1,windowEventName:e,pluginEventName:t,handler:n=>{this.notifyListeners(t,n)}}}unimplemented(e="not implemented"){return new ba.Exception(e,hc.Unimplemented)}unavailable(e="not available"){return new ba.Exception(e,hc.Unavailable)}async removeListener(e,t){const n=this.listeners[e];if(!n)return;const a=n.indexOf(t);this.listeners[e].splice(a,1),this.listeners[e].length||this.removeWindowListener(this.windowListeners[e])}addWindowListener(e){window.addEventListener(e.windowEventName,e.handler),e.registered=!0}removeWindowListener(e){e&&(window.removeEventListener(e.windowEventName,e.handler),e.registered=!1)}sendRetainedArgumentsForEvent(e){const t=this.retainedEventArguments[e];t&&(delete this.retainedEventArguments[e],t.forEach(n=>{this.notifyListeners(e,n)}))}}const zS=s=>encodeURIComponent(s).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape),$S=s=>s.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent);class GR extends rx{async getCookies(){const e=document.cookie,t={};return e.split(";").forEach(n=>{if(n.length<=0)return;let[a,i]=n.replace(/=/,"CAP_COOKIE").split("CAP_COOKIE");a=$S(a).trim(),i=$S(i).trim(),t[a]=i}),t}async setCookie(e){try{const t=zS(e.key),n=zS(e.value),a=e.expires?`; expires=${e.expires.replace("expires=","")}`:"",i=(e.path||"/").replace("path=",""),o=e.url!=null&&e.url.length>0?`domain=${e.url}`:"";document.cookie=`${t}=${n||""}${a}; path=${i}; ${o};`}catch(t){return Promise.reject(t)}}async deleteCookie(e){try{document.cookie=`${e.key}=; Max-Age=0`}catch(t){return Promise.reject(t)}}async clearCookies(){try{const e=document.cookie.split(";")||[];for(const t of e)document.cookie=t.replace(/^ +/,"").replace(/=.*/,`=;expires=${new Date().toUTCString()};path=/`)}catch(e){return Promise.reject(e)}}async clearAllCookies(){try{await this.clearCookies()}catch(e){return Promise.reject(e)}}}pd("CapacitorCookies",{web:()=>new GR});const WR=async s=>new Promise((e,t)=>{const n=new FileReader;n.onload=()=>{const a=n.result;e(a.indexOf(",")>=0?a.split(",")[1]:a)},n.onerror=a=>t(a),n.readAsDataURL(s)}),qR=(s={})=>{const e=Object.keys(s);return Object.keys(s).map(a=>a.toLocaleLowerCase()).reduce((a,i,o)=>(a[i]=s[e[o]],a),{})},YR=(s,e=!0)=>s?Object.entries(s).reduce((n,a)=>{const[i,o]=a;let l,c;return Array.isArray(o)?(c="",o.forEach(d=>{l=e?encodeURIComponent(d):d,c+=`${i}=${l}&`}),c.slice(0,-1)):(l=e?encodeURIComponent(o):o,c=`${i}=${l}`),`${n}&${c}`},"").substr(1):null,VR=(s,e={})=>{const t=Object.assign({method:s.method||"GET",headers:s.headers},e),a=qR(s.headers)["content-type"]||"";if(typeof s.data=="string")t.body=s.data;else if(a.includes("application/x-www-form-urlencoded")){const i=new URLSearchParams;for(const[o,l]of Object.entries(s.data||{}))i.set(o,l);t.body=i.toString()}else if(a.includes("multipart/form-data")||s.data instanceof FormData){const i=new FormData;if(s.data instanceof FormData)s.data.forEach((l,c)=>{i.append(c,l)});else for(const l of Object.keys(s.data))i.append(l,s.data[l]);t.body=i;const o=new Headers(t.headers);o.delete("content-type"),t.headers=o}else(a.includes("application/json")||typeof s.data=="object")&&(t.body=JSON.stringify(s.data));return t};class KR extends rx{async request(e){const t=VR(e,e.webFetchExtra),n=YR(e.params,e.shouldEncodeUrlParams),a=n?`${e.url}?${n}`:e.url,i=await fetch(a,t),o=i.headers.get("content-type")||"";let{responseType:l="text"}=i.ok?e:{};o.includes("application/json")&&(l="json");let c,d;switch(l){case"arraybuffer":case"blob":d=await i.blob(),c=await WR(d);break;case"json":c=await i.json();break;case"document":case"text":default:c=await i.text()}const m={};return i.headers.forEach((p,f)=>{m[f]=p}),{data:c,headers:m,status:i.status,url:i.url}}async get(e){return this.request(Object.assign(Object.assign({},e),{method:"GET"}))}async post(e){return this.request(Object.assign(Object.assign({},e),{method:"POST"}))}async put(e){return this.request(Object.assign(Object.assign({},e),{method:"PUT"}))}async patch(e){return this.request(Object.assign(Object.assign({},e),{method:"PATCH"}))}async delete(e){return this.request(Object.assign(Object.assign({},e),{method:"DELETE"}))}}const HS=pd("CapacitorHttp",{web:()=>new KR});var US;(function(s){s.Dark="DARK",s.Light="LIGHT",s.Default="DEFAULT"})(US||(US={}));var GS;(function(s){s.StatusBar="StatusBar",s.NavigationBar="NavigationBar"})(GS||(GS={}));class XR extends rx{async setStyle(){this.unavailable("not available for web")}async setAnimation(){this.unavailable("not available for web")}async show(){this.unavailable("not available for web")}async hide(){this.unavailable("not available for web")}}pd("SystemBars",{web:()=>new XR});var WS;(function(s){s[s.Sunday=1]="Sunday",s[s.Monday=2]="Monday",s[s.Tuesday=3]="Tuesday",s[s.Wednesday=4]="Wednesday",s[s.Thursday=5]="Thursday",s[s.Friday=6]="Friday",s[s.Saturday=7]="Saturday"})(WS||(WS={}));const ox=pd("LocalNotifications",{web:()=>CA(()=>import("./web-C2T66Tt9.js"),__vite__mapDeps([2,3,1,4])).then(s=>new s.LocalNotificationsWeb)}),ZR=pd("ServerConfig");let QR=100;const JR="agent_alerts",hy="tide-notification-tap";function eL(){return typeof window<"u"&&window.innerWidth<=768&&"ontouchstart"in window}function BA(s){if(eL()){H.openTerminalOnMobile(s);return}H.selectAgent(s),H.setTerminalOpen(!0)}function md(){try{return ba.isNativePlatform()}catch{return!1}}async function tL(){if(md())try{const s=await ox.requestPermissions();return console.log("[Notifications] Permission result:",s.display),s.display==="granted"}catch(s){return console.error("[Notifications] Failed to request permissions:",s),!1}else return"Notification"in window?await Notification.requestPermission()==="granted":!1}async function nL(s){const{title:e,body:t,icon:n,data:a}=s;if(md())try{const i=QR++;console.log("[Notifications] Scheduling native notification id="+i,e),await ox.schedule({notifications:[{id:i,title:e,body:t,extra:a,channelId:JR,smallIcon:"ic_launcher",autoCancel:!0}]}),console.log("[Notifications] Notification scheduled successfully")}catch(i){console.error("[Notifications] Failed to schedule notification:",i)}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(hy,{detail:a}))}}}let Wg=!1;async function sL(s){const e=[];if(Wg)return()=>{};if(Wg=!0,s){const t=n=>{const a=n;a.detail&&s(a.detail)};window.addEventListener(hy,t),e.push(()=>window.removeEventListener(hy,t))}if(md())try{const t=await ox.addListener("localNotificationActionPerformed",n=>{s&&n.notification.extra&&s(n.notification.extra)});e.push(()=>t.remove())}catch(t){console.error("[Notifications] Failed to add tap listener:",t)}return()=>{e.forEach(t=>t()),Wg=!1}}function aL(s,e){md()&&ZR.syncConfig({url:s,token:e}).catch(t=>{console.warn("[Notifications] Failed to sync config to native service:",t)})}window.__tideWsState||(window.__tideWsState={ws:null,isConnecting:!1,reconnectAttempts:0,reconnectTimeout:null});const lx=()=>window.__tideWsState.ws,qS=s=>{window.__tideWsState.ws=s},iL=()=>window.__tideWsState.isConnecting,wu=s=>{window.__tideWsState.isConnecting=s},py=()=>window.__tideWsState.reconnectAttempts,my=s=>{window.__tideWsState.reconnectAttempts=s},FA=()=>window.__tideWsState.reconnectTimeout,zA=s=>{window.__tideWsState.reconnectTimeout=s},YS=10,cx="tide_ws_has_connected";function VS(){return sessionStorage.getItem(cx)==="true"}function rL(s){sessionStorage.setItem(cx,"true")}function oL(){sessionStorage.removeItem(cx)}let $A=null;const lL=s=>{$A=s},KS=()=>$A,$e={onToast:null,onAgentCreated:null,onAgentUpdated:null,onAgentDeleted:null,onAgentsSync:null,onAreasSync:null,onSpawnError:null,onSpawnSuccess:null,onToolUse:null,onDirectoryNotFound:null,onDelegation:null,onCustomClassesSync:null,onReconnect:null,onAgentNotification:null,onBuildingUpdated:null,onSubagentStarted:null,onSubagentCompleted:null};function HA(s){s.onToast&&($e.onToast=s.onToast),s.onAgentCreated&&($e.onAgentCreated=s.onAgentCreated),s.onAgentUpdated&&($e.onAgentUpdated=s.onAgentUpdated),s.onAgentDeleted&&($e.onAgentDeleted=s.onAgentDeleted),s.onAgentsSync&&($e.onAgentsSync=s.onAgentsSync),s.onAreasSync&&($e.onAreasSync=s.onAreasSync),s.onSpawnError&&($e.onSpawnError=s.onSpawnError),s.onSpawnSuccess&&($e.onSpawnSuccess=s.onSpawnSuccess),s.onToolUse&&($e.onToolUse=s.onToolUse),s.onDirectoryNotFound&&($e.onDirectoryNotFound=s.onDirectoryNotFound),s.onDelegation&&($e.onDelegation=s.onDelegation),s.onCustomClassesSync&&($e.onCustomClassesSync=s.onCustomClassesSync),s.onReconnect&&($e.onReconnect=s.onReconnect),s.onAgentNotification&&($e.onAgentNotification=s.onAgentNotification),s.onBuildingUpdated&&($e.onBuildingUpdated=s.onBuildingUpdated),s.onSubagentStarted&&($e.onSubagentStarted=s.onSubagentStarted),s.onSubagentCompleted&&($e.onSubagentCompleted=s.onSubagentCompleted)}function cL(){$e.onToast=null,$e.onAgentCreated=null,$e.onAgentUpdated=null,$e.onAgentDeleted=null,$e.onAgentsSync=null,$e.onAreasSync=null,$e.onSpawnError=null,$e.onSpawnSuccess=null,$e.onToolUse=null,$e.onDirectoryNotFound=null,$e.onDelegation=null,$e.onCustomClassesSync=null,$e.onReconnect=null,$e.onAgentNotification=null,$e.onSubagentStarted=null,$e.onSubagentCompleted=null}function uL(){$e.onAgentCreated=null,$e.onAgentUpdated=null,$e.onAgentDeleted=null,$e.onAgentsSync=null,$e.onAreasSync=null,$e.onToolUse=null,$e.onDelegation=null,$e.onCustomClassesSync=null,$e.onBuildingUpdated=null,$e.onSubagentStarted=null,$e.onSubagentCompleted=null}const Oh=new Map,dL=new Map,fy={start(s){},end(s){},async measure(s,e){this.start(s);try{return await e()}finally{this.end(s)}},measureSync(s,e){this.start(s);try{return e()}finally{this.end(s)}},getMetrics(s){const e={},t=s?Oh.has(s)?[[s,Oh.get(s)]]:[]:Array.from(Oh.entries());for(const[n,a]of t){const i=[...a.samples].sort((d,m)=>d-m),o=Math.floor(i.length*.5),l=Math.floor(i.length*.95),c=Math.floor(i.length*.99);e[n]={count:a.count,avgMs:a.totalMs/a.count,minMs:a.minMs,maxMs:a.maxMs,lastMs:a.lastMs,p50Ms:i[o]||0,p95Ms:i[l]||0,p99Ms:i[c]||0}}return e},clear(){Oh.clear(),dL.clear()},report(){}};class hL{constructor(){W(this,"frames",[]);W(this,"lastFrameTime",0);W(this,"frameCount",0);W(this,"fps",0);W(this,"minFps",1/0);W(this,"maxFps",0);W(this,"fpsHistory",[]);W(this,"maxHistorySize",60)}tick(e=200){const t=performance.now();if(this.lastFrameTime>0){const n=t-this.lastFrameTime;n<e&&(this.frames.push(n),this.frames.length>60&&this.frames.shift())}this.lastFrameTime=t,this.frameCount++}update(){if(this.frames.length===0)return;const e=this.frames.reduce((t,n)=>t+n,0)/this.frames.length;this.fps=1e3/e,this.minFps=Math.min(this.minFps,this.fps),this.maxFps=Math.max(this.maxFps,this.fps),this.fpsHistory.push(this.fps),this.fpsHistory.length>this.maxHistorySize&&this.fpsHistory.shift()}getFPS(){return Math.round(this.fps)}getStats(){const e=this.fpsHistory.length>0?this.fpsHistory.reduce((t,n)=>t+n,0)/this.fpsHistory.length:this.fps;return{current:Math.round(this.fps),min:Math.round(this.minFps===1/0?0:this.minFps),max:Math.round(this.maxFps),avg:Math.round(e)}}reset(){this.frames=[],this.lastFrameTime=0,this.frameCount=0,this.fps=0,this.minFps=1/0,this.maxFps=0,this.fpsHistory=[]}}const Jl=new hL;class pL{constructor(){W(this,"snapshots",[]);W(this,"maxSnapshots",120);W(this,"intervalId",null);W(this,"leakThresholdMB",50);W(this,"baselineUsedMB",0)}getUsage(){const e=performance.memory;return e?{usedMB:Math.round(e.usedJSHeapSize/1024/1024),totalMB:Math.round(e.totalJSHeapSize/1024/1024),limitMB:Math.round(e.jsHeapSizeLimit/1024/1024)}:null}log(){const e=this.getUsage();e&&console.log(`[Memory] Used: ${e.usedMB}MB / ${e.totalMB}MB (limit: ${e.limitMB}MB)`)}startMonitoring(e=1e3){if(this.intervalId)return;const t=this.getUsage();t&&(this.baselineUsedMB=t.usedMB),this.intervalId=setInterval(()=>{this.takeSnapshot()},e),console.log("[Memory] Monitoring started. Use memory.report() to see analysis.")}stopMonitoring(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null,console.log("[Memory] Monitoring stopped."))}takeSnapshot(){const e=this.getUsage();if(!e)return;const t={timestamp:Date.now(),heapUsedMB:e.usedMB,heapTotalMB:e.totalMB,heapLimitMB:e.limitMB};this.snapshots.push(t),this.snapshots.length>this.maxSnapshots&&this.snapshots.shift();const n=e.usedMB-this.baselineUsedMB;n>this.leakThresholdMB&&console.warn(`[Memory] Warning: Heap grew by ${n}MB since monitoring started (baseline: ${this.baselineUsedMB}MB, current: ${e.usedMB}MB)`)}getGrowthRate(){if(this.snapshots.length<10)return null;const e=this.snapshots[0],t=this.snapshots[this.snapshots.length-1],n=(t.timestamp-e.timestamp)/1e3/60;return n<.1?null:(t.heapUsedMB-e.heapUsedMB)/n}report(){const e=this.getUsage();if(!e){console.log("[Memory] Memory API not available (Chrome only)");return}console.group("%c[Memory Report]","color: #ff6600; font-weight: bold"),console.log(`Current: ${e.usedMB}MB / ${e.totalMB}MB (limit: ${e.limitMB}MB)`),console.log(`Baseline: ${this.baselineUsedMB}MB`),console.log(`Growth: ${e.usedMB-this.baselineUsedMB}MB since monitoring started`);const t=this.getGrowthRate();if(t!==null&&(console.log(`Growth Rate: ${t.toFixed(2)}MB/min`),t>5&&console.warn("POTENTIAL MEMORY LEAK: Growth rate exceeds 5MB/min")),this.snapshots.length>1){const n=Math.min(...this.snapshots.map(i=>i.heapUsedMB)),a=Math.max(...this.snapshots.map(i=>i.heapUsedMB));console.log(`Range: ${n}MB - ${a}MB (${a-n}MB variance)`)}console.groupEnd()}getThreeJsInfo(e){var t;return(t=e==null?void 0:e.info)!=null&&t.memory?{geometries:e.info.memory.geometries,textures:e.info.memory.textures}:null}reset(){this.snapshots=[];const e=this.getUsage();e&&(this.baselineUsedMB=e.usedMB),console.log("[Memory] Reset. New baseline:",this.baselineUsedMB,"MB")}}const Kl=new pL;function Ou(s,e,t,n,a,i){}function UA(s){if(s.payload&&typeof s.payload=="object"){const e=s.payload;if(e.agentId)return e.agentId;if(e.id)return e.id}return null}function ux(s){var t,n,a,i,o,l;const e=lx();if(!e){(t=KS())==null||t(),(n=$e.onToast)==null||n.call($e,"error","Not Connected","Connecting to server... Please try again in a moment.");return}if(e.readyState!==WebSocket.OPEN){e.readyState===WebSocket.CONNECTING?(a=$e.onToast)==null||a.call($e,"warning","Connecting...","WebSocket is still connecting. Please wait a moment and try again."):(e.readyState===WebSocket.CLOSED||e.readyState===WebSocket.CLOSING)&&((i=KS())==null||i(),(o=$e.onToast)==null||o.call($e,"warning","Reconnecting...","Connection lost. Reconnecting to server..."));return}try{const c=JSON.stringify(s);if(vs.isEnabled()){const m=UA(s);console.log("[AgentDebugger] SENT - type:",s.type,"agentId:",m,"payload:",s.payload),m&&vs.captureSent(m,c)}e.send(c)}catch(c){(l=$e.onToast)==null||l.call($e,"error","Send Failed",`Failed to send message: ${c}`)}}const Iu=new Set,mL=5e3;function XS(s){if(!s.isDetached||!s.sessionId){Iu.delete(s.id);return}Iu.has(s.id)||(Iu.add(s.id),ux({type:"reattach_agent",payload:{agentId:s.id}}),setTimeout(()=>{Iu.delete(s.id)},mL))}function fL(s){var e,t,n,a,i,o,l,c,d,m,p,f,b,y,w,k,S,j,C,A,D,M,I;switch(fy.start(`ws:${s.type}`),s.type){case"agents_update":{const E=s.payload,_=E.filter(P=>P.class==="boss"||P.isBoss);_.length>0&&console.log("[WS agents_update] Boss agents received:",_.map(P=>({id:P.id,name:P.name,subordinateIds:P.subordinateIds}))),H.setAgents(E),(e=$e.onAgentsSync)==null||e.call($e,E),H.loadToolHistory();for(const P of E)XS(P);break}case"agent_created":{const E=s.payload;console.log("[WebSocket] Agent created:",E),H.addAgent(E),H.selectAgent(E.id),(t=$e.onAgentCreated)==null||t.call($e,E),(n=$e.onSpawnSuccess)==null||n.call($e),window.__spawnModalSuccess&&(console.log("[WebSocket] Calling __spawnModalSuccess"),window.__spawnModalSuccess()),(a=$e.onToast)==null||a.call($e,"success","Agent Deployed",`${E.name} is ready for commands`);break}case"agent_updated":{const E=s.payload,P=H.getState().agents.get(E.id),L=(P==null?void 0:P.status)!==E.status;console.log(`[Tide] Agent updated: ${E.name} (${E.id}) status=${E.status} (was ${P==null?void 0:P.status})${L?" ⚡ STATUS CHANGED":""}`),L&&console.log(`[Tide] 🔔 Status change for ${E.name}: ${P==null?void 0:P.status} → ${E.status}`);const R=P?P.position.x!==E.position.x||P.position.z!==E.position.z:!1;H.updateAgent(E),XS(E),(i=$e.onAgentUpdated)==null||i.call($e,E,R);break}case"agent_deleted":{const{id:E}=s.payload;Iu.delete(E),H.removeAgent(E),(o=$e.onAgentDeleted)==null||o.call($e,E);break}case"activity":{const E=s.payload;H.addActivity(E);break}case"event":{const E=s.payload;if(td.debug(`Event: ${E.type}`,{agentId:E.agentId,toolName:E.toolName},"ws:event"),E.type==="tool_start"&&E.toolName&&((l=$e.onToolUse)==null||l.call($e,E.agentId,E.toolName,E.toolInput),H.addToolExecution(E.agentId,E.toolName,E.toolInput),E.toolInput)){const _=E.toolInput.file_path||E.toolInput.path;_&&(E.toolName==="Write"?H.addFileChange(E.agentId,"created",_):E.toolName==="Edit"?H.addFileChange(E.agentId,"modified",_):E.toolName==="Read"&&H.addFileChange(E.agentId,"read",_))}break}case"output":{const E=s.payload;td.debug(`Output: "${E.text.slice(0,80)}..."`,{agentId:E.agentId,isStreaming:E.isStreaming,length:E.text.length,hasSkillUpdate:!!E.skillUpdate,uuid:E.uuid,toolName:E.toolName},"ws:output"),H.addOutput(E.agentId,{text:E.text,isStreaming:E.isStreaming,timestamp:E.timestamp,isDelegation:E.isDelegation,skillUpdate:E.skillUpdate,subagentName:E.subagentName,uuid:E.uuid,toolName:E.toolName,toolInput:E.toolInput,toolOutput:E.toolOutput});break}case"context_stats":{const{agentId:E,stats:_}=s.payload;console.log(`[Tide] Received context stats for agent ${E}: ${_.usedPercent}% used`),H.updateAgentContextStats(E,_);break}case"context_update":{const{agentId:E,contextUsed:_,contextLimit:P}=s.payload;H.updateAgentContext(E,_,P);break}case"error":{const E=s.payload;console.error("[WebSocket] Error from server:",E.message),(c=$e.onToast)==null||c.call($e,"error","Error",E.message),(d=$e.onSpawnError)==null||d.call($e),window.__spawnModalError&&(console.log("[WebSocket] Calling __spawnModalError"),window.__spawnModalError());break}case"directory_not_found":{const{path:E}=s.payload;console.log("[WebSocket] Directory not found:",E),(m=$e.onDirectoryNotFound)==null||m.call($e,E),window.__spawnModalDirNotFound&&(console.log("[WebSocket] Calling __spawnModalDirNotFound"),window.__spawnModalDirNotFound(E));break}case"command_started":{const{agentId:E,command:_}=s.payload,P=_.trim();if(P==="/context"||P==="/cost"||P==="/compact")break;H.addUserPromptToOutput(E,_);break}case"session_updated":{const{agentId:E}=s.payload;H.loadToolHistory();const _=H.getState().agents.get(E);_&&H.updateAgent({..._});break}case"supervisor_report":{const E=s.payload;H.setSupervisorReport(E);break}case"narrative_update":{const{agentId:E,narrative:_}=s.payload;H.addNarrative(E,_);break}case"supervisor_status":{const E=s.payload;H.setSupervisorStatus(E);break}case"agent_supervisor_history":{const E=s.payload;H.setAgentSupervisorHistory(E);break}case"agent_analysis":{const{agentId:E,analysis:_}=s.payload;H.addAgentAnalysis(E,_);break}case"areas_update":{const E=s.payload;H.setAreasFromServer(E),(p=$e.onAreasSync)==null||p.call($e);break}case"buildings_update":{const E=s.payload;H.setBuildingsFromServer(E);break}case"building_created":{const E=s.payload;H.addBuilding(E);break}case"building_updated":{const E=s.payload;H.updateBuildingFromServer(E),(f=$e.onBuildingUpdated)==null||f.call($e,E);break}case"building_deleted":{const{id:E}=s.payload;H.removeBuildingFromServer(E);break}case"building_logs":{const{buildingId:E,logs:_}=s.payload;H.addBuildingLogs(E,_);break}case"pm2_logs_chunk":{const{buildingId:E,chunk:_}=s.payload;H.appendStreamingLogChunk(E,_);break}case"pm2_logs_streaming":{const{buildingId:E,streaming:_}=s.payload;H.setStreamingStatus(E,_);break}case"docker_logs_chunk":{const{buildingId:E,chunk:_}=s.payload;H.appendStreamingLogChunk(E,_);break}case"docker_logs_streaming":{const{buildingId:E,streaming:_}=s.payload;H.setStreamingStatus(E,_);break}case"docker_containers_list":{const{containers:E,composeProjects:_}=s.payload;console.log(`[WebSocket] Received ${E.length} containers, ${_.length} compose projects`),H.setDockerContainersList(E,_);break}case"boss_building_logs_chunk":{const{bossBuildingId:E,subordinateBuildingId:_,subordinateBuildingName:P,chunk:L,isError:R}=s.payload;H.appendBossStreamingLogChunk(E,_,P,L,R);break}case"boss_building_subordinates_updated":{const{bossBuildingId:E,subordinateBuildingIds:_}=s.payload;H.updateBuilding(E,{subordinateBuildingIds:_});break}case"permission_request":{const E=s.payload;H.addPermissionRequest(E);break}case"permission_resolved":{const{requestId:E,approved:_}=s.payload;H.resolvePermissionRequest(E,_);break}case"delegation_decision":{const E=s.payload;H.handleDelegationDecision(E),E.status==="sent"&&((b=$e.onToast)==null||b.call($e,"info","Task Delegated",`Delegated to ${E.selectedAgentName}: ${E.reasoning.slice(0,80)}...`),E.bossId&&E.selectedAgentId&&((y=$e.onDelegation)==null||y.call($e,E.bossId,E.selectedAgentId)));break}case"boss_subordinates_updated":{const{bossId:E,subordinateIds:_}=s.payload;H.updateBossSubordinates(E,_);break}case"delegation_history":{const{bossId:E,decisions:_}=s.payload;H.setDelegationHistory(E,_);break}case"boss_spawned_agent":{const{agent:E,bossPosition:_}=s.payload;console.log("[WebSocket] Boss spawned agent:",E.name,"- walking to boss at",_),H.addAgent(E),(w=$e.onAgentCreated)==null||w.call($e,E),ux({type:"move_agent",payload:{agentId:E.id,position:_}}),(k=$e.onToast)==null||k.call($e,"success","Agent Deployed",`${E.name} spawned by boss, walking to position`);break}case"agent_task_started":{const{bossId:E,subordinateId:_,subordinateName:P,taskDescription:L}=s.payload;console.log(`[WebSocket] Agent ${P} started task for boss ${E}: ${L.slice(0,50)}...`),H.handleAgentTaskStarted(E,_,P,L);break}case"agent_task_output":{const{bossId:E,subordinateId:_,output:P}=s.payload;H.handleAgentTaskOutput(E,_,P);break}case"agent_task_completed":{const{bossId:E,subordinateId:_,success:P}=s.payload;console.log(`[WebSocket] Agent task completed for boss ${E}, subordinate ${_}, success: ${P}`),H.handleAgentTaskCompleted(E,_,P);break}case"skills_update":{const E=s.payload;H.setSkillsFromServer(E);break}case"skill_created":{const E=s.payload;H.addSkillFromServer(E),console.log(`[WebSocket] Skill created: ${E.name}`);break}case"skill_updated":{const E=s.payload;H.updateSkillFromServer(E),console.log(`[WebSocket] Skill updated: ${E.name}`);break}case"skill_deleted":{const{id:E}=s.payload;H.removeSkillFromServer(E),console.log(`[WebSocket] Skill deleted: ${E}`);break}case"agent_skills":{const{agentId:E,skills:_}=s.payload;console.log(`[WebSocket] Agent ${E} has ${_.length} skills`);break}case"custom_agent_classes_update":{const E=s.payload;H.setCustomAgentClassesFromServer(E),console.log(`[WebSocket] Received ${E.length} custom agent classes`);const _=new Map;for(const P of E)_.set(P.id,P);(S=$e.onCustomClassesSync)==null||S.call($e,_);break}case"custom_agent_class_created":{const E=s.payload;H.addCustomAgentClassFromServer(E),console.log(`[WebSocket] Custom agent class created: ${E.name}`),(j=$e.onCustomClassesSync)==null||j.call($e,H.getState().customAgentClasses);break}case"custom_agent_class_updated":{const E=s.payload;H.updateCustomAgentClassFromServer(E),console.log(`[WebSocket] Custom agent class updated: ${E.name}`),(C=$e.onCustomClassesSync)==null||C.call($e,H.getState().customAgentClasses);break}case"custom_agent_class_deleted":{const{id:E}=s.payload;H.removeCustomAgentClassFromServer(E),console.log(`[WebSocket] Custom agent class deleted: ${E}`),(A=$e.onCustomClassesSync)==null||A.call($e,H.getState().customAgentClasses);break}case"global_usage":{const E=s.payload;console.log("[WebSocket] Global usage update:",E),H.setGlobalUsage(E);break}case"agent_notification":{const E=s.payload;console.log(`[WebSocket] Agent notification from ${E.agentName}: ${E.title}`),(D=$e.onAgentNotification)==null||D.call($e,E);break}case"focus_agent":{const{agentId:E,openTerminal:_}=s.payload;if(!H.getState().agents.get(E)){console.warn(`[WebSocket] focus_agent ignored - agent not found: ${E}`);break}H.selectAgent(E),_&&H.setTerminalOpen(!0);const L=[0,80,220,500,1e3];for(const R of L)window.setTimeout(()=>{window.focus()},R);break}case"exec_task_started":{const{taskId:E,agentId:_,agentName:P,command:L,cwd:R}=s.payload;console.log(`[WebSocket] Exec task started: ${E} for agent ${P}: ${L.slice(0,50)}...`),H.handleExecTaskStarted(E,_,P,L,R);break}case"exec_task_output":{const{taskId:E,agentId:_,output:P,isError:L}=s.payload;H.handleExecTaskOutput(E,_,P,L);break}case"exec_task_completed":{const{taskId:E,agentId:_,exitCode:P,success:L}=s.payload;console.log(`[WebSocket] Exec task completed: ${E} for agent ${_}, success: ${L}`),H.handleExecTaskCompleted(E,_,P,L);break}case"subagent_started":{const E=s.payload;console.log(`[WebSocket] Subagent started: ${E.name} (${E.id}) for agent ${E.parentAgentId}`),H.addSubagent(E),(M=$e.onSubagentStarted)==null||M.call($e,E);break}case"subagent_output":{const{subagentId:E,parentAgentId:_,text:P,timestamp:L}=s.payload,R=P.indexOf(":");if(R>0){const z=P.slice(0,R).trim(),F=P.slice(R+1).trim();H.addSubagentActivity(E,_,{toolName:z,description:F,timestamp:L})}else P.startsWith("Using ")&&H.addSubagentActivity(E,_,{toolName:P.slice(6).trim(),description:"",timestamp:L});break}case"subagent_completed":{const{subagentId:E,parentAgentId:_,success:P,resultPreview:L,subagentName:R,durationMs:z,tokensUsed:F,toolUseCount:$}=s.payload;console.log(`[WebSocket] Subagent completed: ${E} for agent ${_}, success: ${P}`),(z||F||$)&&H.updateSubagentStats(E,_,{durationMs:z||0,tokensUsed:F||0,toolUseCount:$||0}),H.completeSubagent(E,_,P),(I=$e.onSubagentCompleted)==null||I.call($e,E);const U=H.getSubagent(E)||H.getSubagentByToolUseId(E),G=R||(U==null?void 0:U.name)||E,K=P?"✅":"❌",Z=z?` (${(z/1e3).toFixed(0)}s · ${((F||0)/1e3).toFixed(1)}K tokens · ${$||0} tools)`:"";H.addOutput(_,{text:`${K} Subagent ${G} ${P?"completed":"failed"}${Z}`,isStreaming:!1,timestamp:Date.now(),subagentName:G,toolOutput:L});break}case"subagent_stream":{const{toolUseId:E,parentAgentId:_,entries:P}=s.payload;H.addSubagentStreamEntries(E,_,P);break}case"secrets_update":{const E=s.payload;H.setSecretsFromServer(E),console.log(`[WebSocket] Received ${E.length} secrets`);break}case"secret_created":{const E=s.payload;H.addSecretFromServer(E),console.log(`[WebSocket] Secret created: ${E.name}`);break}case"secret_updated":{const E=s.payload;H.updateSecretFromServer(E),console.log(`[WebSocket] Secret updated: ${E.name}`);break}case"secret_deleted":{const{id:E}=s.payload;H.removeSecretFromServer(E),console.log(`[WebSocket] Secret deleted: ${E}`);break}case"database_connection_result":{const{buildingId:E,connectionId:_,success:P,error:L,serverVersion:R}=s.payload;H.setConnectionStatus(E,_,{connected:P,error:L,serverVersion:R}),console.log(`[WebSocket] Database connection ${P?"succeeded":"failed"}: ${_}`);break}case"databases_list":{const{buildingId:E,connectionId:_,databases:P}=s.payload;H.setDatabases(E,_,P),console.log(`[WebSocket] Received ${P.length} databases for ${_}`);break}case"tables_list":{const{buildingId:E,connectionId:_,database:P,tables:L}=s.payload;H.setTables(E,_,P,L),console.log(`[WebSocket] Received ${L.length} tables for ${P}`);break}case"table_schema":{const{buildingId:E,connectionId:_,database:P,table:L,columns:R,indexes:z,foreignKeys:F}=s.payload;H.setTableSchema(E,_,P,L,{columns:R,indexes:z||[],foreignKeys:F||[]}),console.log(`[WebSocket] Received schema for ${L}`);break}case"query_result":{const{buildingId:E,result:_}=s.payload;H.setQueryResult(E,_),console.log(`[WebSocket] Query ${_.status}: ${_.rowCount??_.affectedRows??0} rows in ${_.duration}ms`);break}case"silent_query_result":{const{buildingId:E,query:_,requestId:P,success:L,affectedRows:R,error:z}=s.payload;H.setSilentQueryResult(E,{query:_,requestId:P,success:L,affectedRows:R,error:z}),console.log(`[WebSocket] Silent query ${L?"succeeded":"failed"}: ${R??0} affected rows`);break}case"query_history_update":{const{buildingId:E,history:_}=s.payload;H.setQueryHistory(E,_),console.log(`[WebSocket] Received ${_.length} query history entries for ${E}`);break}}fy.end(`ws:${s.type}`)}lL(()=>nd());let ZS=!1;function GA(){const s=lx();s&&s.readyState===WebSocket.OPEN&&s.close(1e3,"Page unloading");const e=FA();e&&clearTimeout(e),window.__tideWsState&&(window.__tideWsState.ws=null,window.__tideWsState.reconnectTimeout=null,window.__tideWsState.isConnecting=!1,window.__tideWsState.reconnectAttempts=0),oL()}function gL(){ZS||(window.addEventListener("beforeunload",GA),ZS=!0)}function WA(){GA(),H.setConnected(!1),H.stopStatusPolling()}function qu(){WA(),my(0),setTimeout(()=>nd(),100)}function nd(){gL();const s=FA();s&&(clearTimeout(s),zA(null));const e=lx();if(iL()||e&&e.readyState===WebSocket.CONNECTING)return;if(e&&e.readyState===WebSocket.OPEN){VS()&&$e.onReconnect&&$e.onReconnect();return}my(py()+1),wu(!0);const t=As(pt.BACKEND_URL,""),n=ti(),a=6200;let i;if(t){const l=t.replace(/^https:\/\//,"wss://").replace(/^http:\/\//,"ws://");i=l.endsWith("/ws")?l:`${l.replace(/\/$/,"")}/ws`}else i=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws`;let o=null;try{n?o=new WebSocket(i,[`auth-${n}`]):o=new WebSocket(i)}catch{wu(!1),QS();return}qS(o),o.onopen=()=>{var c,d,m;const l=VS();wu(!1),my(0),rL(),H.setConnected(!0),H.startStatusPolling(),H.clearAllPermissions(),l?((c=$e.onToast)==null||c.call($e,"success","Reconnected","Connection restored - refreshing data..."),(d=$e.onReconnect)==null||d.call($e)):(m=$e.onToast)==null||m.call($e,"success","Connected","Connected to Tide Commander server"),aL(t,n)},o.onmessage=l=>{try{const c=JSON.parse(l.data);if(vs.isEnabled()){const m=UA(c);console.log("[AgentDebugger] RECEIVED - type:",c.type,"agentId:",m,"payload:",c.payload),m&&vs.captureReceived(m,l.data)}fL(c)}catch(c){const d=l.data.substring(0,200);console.error("[WS] Failed to parse message:",c),console.error("[WS] Raw data (first 200 chars):",d),console.error("[WS] Full data length:",l.data.length),l.data.length<5e3&&console.error("[WS] Full malformed message:",l.data)}},o.onclose=()=>{var c,d;wu(!1),qS(null),H.setConnected(!1),H.stopStatusPolling();const l=py();l<YS?((c=$e.onToast)==null||c.call($e,"warning","Disconnected",`Connection lost. Reconnecting... (attempt ${l+1}/${YS})`),QS()):(d=$e.onToast)==null||d.call($e,"error","Connection Failed",`Could not connect to server. Please check if the backend is running on port ${a}.`)},o.onerror=()=>{wu(!1)},H.setSendMessage(ux)}function QS(){const s=py(),e=Math.min(1e3*Math.pow(2,s-1),3e4);zA(setTimeout(nd,e))}function JS(s,e){if(e===SD)return console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."),s;if(e===Yb||e===nA){let t=s.getIndex();if(t===null){const o=[],l=s.getAttribute("position");if(l!==void 0){for(let c=0;c<l.count;c++)o.push(c);s.setIndex(o),t=s.getIndex()}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible."),s}const n=t.count-2,a=[];if(e===Yb)for(let o=1;o<=n;o++)a.push(t.getX(0)),a.push(t.getX(o)),a.push(t.getX(o+1));else for(let o=0;o<n;o++)o%2===0?(a.push(t.getX(o)),a.push(t.getX(o+1)),a.push(t.getX(o+2))):(a.push(t.getX(o+2)),a.push(t.getX(o+1)),a.push(t.getX(o)));a.length/3!==n&&console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.");const i=s.clone();return i.setIndex(a),i.clearGroups(),i}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:",e),s}class dx extends sA{constructor(e){super(e),this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register(function(t){return new wL(t)}),this.register(function(t){return new kL(t)}),this.register(function(t){return new _L(t)}),this.register(function(t){return new DL(t)}),this.register(function(t){return new PL(t)}),this.register(function(t){return new jL(t)}),this.register(function(t){return new CL(t)}),this.register(function(t){return new NL(t)}),this.register(function(t){return new AL(t)}),this.register(function(t){return new vL(t)}),this.register(function(t){return new ML(t)}),this.register(function(t){return new SL(t)}),this.register(function(t){return new EL(t)}),this.register(function(t){return new TL(t)}),this.register(function(t){return new yL(t)}),this.register(function(t){return new RL(t)}),this.register(function(t){return new LL(t)})}load(e,t,n,a){const i=this;let o;if(this.resourcePath!=="")o=this.resourcePath;else if(this.path!==""){const d=$u.extractUrlBase(e);o=$u.resolveURL(d,this.path)}else o=$u.extractUrlBase(e);this.manager.itemStart(e);const l=function(d){a?a(d):console.error(d),i.manager.itemError(e),i.manager.itemEnd(e)},c=new gp(this.manager);c.setPath(this.path),c.setResponseType("arraybuffer"),c.setRequestHeader(this.requestHeader),c.setWithCredentials(this.withCredentials),c.load(e,function(d){try{i.parse(d,o,function(m){t(m),i.manager.itemEnd(e)},l)}catch(m){l(m)}},n,l)}setDRACOLoader(e){return this.dracoLoader=e,this}setKTX2Loader(e){return this.ktx2Loader=e,this}setMeshoptDecoder(e){return this.meshoptDecoder=e,this}register(e){return this.pluginCallbacks.indexOf(e)===-1&&this.pluginCallbacks.push(e),this}unregister(e){return this.pluginCallbacks.indexOf(e)!==-1&&this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(e),1),this}parse(e,t,n,a){let i;const o={},l={},c=new TextDecoder;if(typeof e=="string")i=JSON.parse(e);else if(e instanceof ArrayBuffer)if(c.decode(new Uint8Array(e,0,4))===qA){try{o[Xt.KHR_BINARY_GLTF]=new OL(e)}catch(p){a&&a(p);return}i=JSON.parse(o[Xt.KHR_BINARY_GLTF].content)}else i=JSON.parse(c.decode(e));else i=e;if(i.asset===void 0||i.asset.version[0]<2){a&&a(new Error("THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported."));return}const d=new KL(i,{path:t||this.resourcePath||"",crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});d.fileLoader.setRequestHeader(this.requestHeader);for(let m=0;m<this.pluginCallbacks.length;m++){const p=this.pluginCallbacks[m](d);p.name||console.error("THREE.GLTFLoader: Invalid plugin found: missing name"),l[p.name]=p,o[p.name]=!0}if(i.extensionsUsed)for(let m=0;m<i.extensionsUsed.length;++m){const p=i.extensionsUsed[m],f=i.extensionsRequired||[];switch(p){case Xt.KHR_MATERIALS_UNLIT:o[p]=new xL;break;case Xt.KHR_DRACO_MESH_COMPRESSION:o[p]=new IL(i,this.dracoLoader);break;case Xt.KHR_TEXTURE_TRANSFORM:o[p]=new BL;break;case Xt.KHR_MESH_QUANTIZATION:o[p]=new FL;break;default:f.indexOf(p)>=0&&l[p]===void 0&&console.warn('THREE.GLTFLoader: Unknown extension "'+p+'".')}}d.setExtensions(o),d.setPlugins(l),d.parse(n,a)}parseAsync(e,t){const n=this;return new Promise(function(a,i){n.parse(e,t,a,i)})}}function bL(){let s={};return{get:function(e){return s[e]},add:function(e,t){s[e]=t},remove:function(e){delete s[e]},removeAll:function(){s={}}}}const Xt={KHR_BINARY_GLTF:"KHR_binary_glTF",KHR_DRACO_MESH_COMPRESSION:"KHR_draco_mesh_compression",KHR_LIGHTS_PUNCTUAL:"KHR_lights_punctual",KHR_MATERIALS_CLEARCOAT:"KHR_materials_clearcoat",KHR_MATERIALS_DISPERSION:"KHR_materials_dispersion",KHR_MATERIALS_IOR:"KHR_materials_ior",KHR_MATERIALS_SHEEN:"KHR_materials_sheen",KHR_MATERIALS_SPECULAR:"KHR_materials_specular",KHR_MATERIALS_TRANSMISSION:"KHR_materials_transmission",KHR_MATERIALS_IRIDESCENCE:"KHR_materials_iridescence",KHR_MATERIALS_ANISOTROPY:"KHR_materials_anisotropy",KHR_MATERIALS_UNLIT:"KHR_materials_unlit",KHR_MATERIALS_VOLUME:"KHR_materials_volume",KHR_TEXTURE_BASISU:"KHR_texture_basisu",KHR_TEXTURE_TRANSFORM:"KHR_texture_transform",KHR_MESH_QUANTIZATION:"KHR_mesh_quantization",KHR_MATERIALS_EMISSIVE_STRENGTH:"KHR_materials_emissive_strength",EXT_MATERIALS_BUMP:"EXT_materials_bump",EXT_TEXTURE_WEBP:"EXT_texture_webp",EXT_TEXTURE_AVIF:"EXT_texture_avif",EXT_MESHOPT_COMPRESSION:"EXT_meshopt_compression",EXT_MESH_GPU_INSTANCING:"EXT_mesh_gpu_instancing"};class yL{constructor(e){this.parser=e,this.name=Xt.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){const e=this.parser,t=this.parser.json.nodes||[];for(let n=0,a=t.length;n<a;n++){const i=t[n];i.extensions&&i.extensions[this.name]&&i.extensions[this.name].light!==void 0&&e._addNodeRef(this.cache,i.extensions[this.name].light)}}_loadLight(e){const t=this.parser,n="light:"+e;let a=t.cache.get(n);if(a)return a;const i=t.json,c=((i.extensions&&i.extensions[this.name]||{}).lights||[])[e];let d;const m=new Bt(16777215);c.color!==void 0&&m.setRGB(c.color[0],c.color[1],c.color[2],Ci);const p=c.range!==void 0?c.range:0;switch(c.type){case"directional":d=new sc(m),d.target.position.set(0,0,-1),d.add(d.target);break;case"point":d=new aA(m),d.distance=p;break;case"spot":d=new jD(m),d.distance=p,c.spot=c.spot||{},c.spot.innerConeAngle=c.spot.innerConeAngle!==void 0?c.spot.innerConeAngle:0,c.spot.outerConeAngle=c.spot.outerConeAngle!==void 0?c.spot.outerConeAngle:Math.PI/4,d.angle=c.spot.outerConeAngle,d.penumbra=1-c.spot.innerConeAngle/c.spot.outerConeAngle,d.target.position.set(0,0,-1),d.add(d.target);break;default:throw new Error("THREE.GLTFLoader: Unexpected light type: "+c.type)}return d.position.set(0,0,0),d.decay=2,Qi(d,c),c.intensity!==void 0&&(d.intensity=c.intensity),d.name=t.createUniqueName(c.name||"light_"+e),a=Promise.resolve(d),t.cache.add(n,a),a}getDependency(e,t){if(e==="light")return this._loadLight(t)}createNodeAttachment(e){const t=this,n=this.parser,i=n.json.nodes[e],l=(i.extensions&&i.extensions[this.name]||{}).light;return l===void 0?null:this._loadLight(l).then(function(c){return n._getNodeRef(t.cache,l,c)})}}class xL{constructor(){this.name=Xt.KHR_MATERIALS_UNLIT}getMaterialType(){return We}extendParams(e,t,n){const a=[];e.color=new Bt(1,1,1),e.opacity=1;const i=t.pbrMetallicRoughness;if(i){if(Array.isArray(i.baseColorFactor)){const o=i.baseColorFactor;e.color.setRGB(o[0],o[1],o[2],Ci),e.opacity=o[3]}i.baseColorTexture!==void 0&&a.push(n.assignTexture(e,"map",i.baseColorTexture,Va))}return Promise.all(a)}}class vL{constructor(e){this.parser=e,this.name=Xt.KHR_MATERIALS_EMISSIVE_STRENGTH}extendMaterialParams(e,t){const a=this.parser.json.materials[e];if(!a.extensions||!a.extensions[this.name])return Promise.resolve();const i=a.extensions[this.name].emissiveStrength;return i!==void 0&&(t.emissiveIntensity=i),Promise.resolve()}}class wL{constructor(e){this.parser=e,this.name=Xt.KHR_MATERIALS_CLEARCOAT}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Ai}extendMaterialParams(e,t){const n=this.parser,a=n.json.materials[e];if(!a.extensions||!a.extensions[this.name])return Promise.resolve();const i=[],o=a.extensions[this.name];if(o.clearcoatFactor!==void 0&&(t.clearcoat=o.clearcoatFactor),o.clearcoatTexture!==void 0&&i.push(n.assignTexture(t,"clearcoatMap",o.clearcoatTexture)),o.clearcoatRoughnessFactor!==void 0&&(t.clearcoatRoughness=o.clearcoatRoughnessFactor),o.clearcoatRoughnessTexture!==void 0&&i.push(n.assignTexture(t,"clearcoatRoughnessMap",o.clearcoatRoughnessTexture)),o.clearcoatNormalTexture!==void 0&&(i.push(n.assignTexture(t,"clearcoatNormalMap",o.clearcoatNormalTexture)),o.clearcoatNormalTexture.scale!==void 0)){const l=o.clearcoatNormalTexture.scale;t.clearcoatNormalScale=new _s(l,l)}return Promise.all(i)}}class kL{constructor(e){this.parser=e,this.name=Xt.KHR_MATERIALS_DISPERSION}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Ai}extendMaterialParams(e,t){const a=this.parser.json.materials[e];if(!a.extensions||!a.extensions[this.name])return Promise.resolve();const i=a.extensions[this.name];return t.dispersion=i.dispersion!==void 0?i.dispersion:0,Promise.resolve()}}class SL{constructor(e){this.parser=e,this.name=Xt.KHR_MATERIALS_IRIDESCENCE}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Ai}extendMaterialParams(e,t){const n=this.parser,a=n.json.materials[e];if(!a.extensions||!a.extensions[this.name])return Promise.resolve();const i=[],o=a.extensions[this.name];return o.iridescenceFactor!==void 0&&(t.iridescence=o.iridescenceFactor),o.iridescenceTexture!==void 0&&i.push(n.assignTexture(t,"iridescenceMap",o.iridescenceTexture)),o.iridescenceIor!==void 0&&(t.iridescenceIOR=o.iridescenceIor),t.iridescenceThicknessRange===void 0&&(t.iridescenceThicknessRange=[100,400]),o.iridescenceThicknessMinimum!==void 0&&(t.iridescenceThicknessRange[0]=o.iridescenceThicknessMinimum),o.iridescenceThicknessMaximum!==void 0&&(t.iridescenceThicknessRange[1]=o.iridescenceThicknessMaximum),o.iridescenceThicknessTexture!==void 0&&i.push(n.assignTexture(t,"iridescenceThicknessMap",o.iridescenceThicknessTexture)),Promise.all(i)}}class jL{constructor(e){this.parser=e,this.name=Xt.KHR_MATERIALS_SHEEN}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Ai}extendMaterialParams(e,t){const n=this.parser,a=n.json.materials[e];if(!a.extensions||!a.extensions[this.name])return Promise.resolve();const i=[];t.sheenColor=new Bt(0,0,0),t.sheenRoughness=0,t.sheen=1;const o=a.extensions[this.name];if(o.sheenColorFactor!==void 0){const l=o.sheenColorFactor;t.sheenColor.setRGB(l[0],l[1],l[2],Ci)}return o.sheenRoughnessFactor!==void 0&&(t.sheenRoughness=o.sheenRoughnessFactor),o.sheenColorTexture!==void 0&&i.push(n.assignTexture(t,"sheenColorMap",o.sheenColorTexture,Va)),o.sheenRoughnessTexture!==void 0&&i.push(n.assignTexture(t,"sheenRoughnessMap",o.sheenRoughnessTexture)),Promise.all(i)}}class CL{constructor(e){this.parser=e,this.name=Xt.KHR_MATERIALS_TRANSMISSION}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Ai}extendMaterialParams(e,t){const n=this.parser,a=n.json.materials[e];if(!a.extensions||!a.extensions[this.name])return Promise.resolve();const i=[],o=a.extensions[this.name];return o.transmissionFactor!==void 0&&(t.transmission=o.transmissionFactor),o.transmissionTexture!==void 0&&i.push(n.assignTexture(t,"transmissionMap",o.transmissionTexture)),Promise.all(i)}}class NL{constructor(e){this.parser=e,this.name=Xt.KHR_MATERIALS_VOLUME}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Ai}extendMaterialParams(e,t){const n=this.parser,a=n.json.materials[e];if(!a.extensions||!a.extensions[this.name])return Promise.resolve();const i=[],o=a.extensions[this.name];t.thickness=o.thicknessFactor!==void 0?o.thicknessFactor:0,o.thicknessTexture!==void 0&&i.push(n.assignTexture(t,"thicknessMap",o.thicknessTexture)),t.attenuationDistance=o.attenuationDistance||1/0;const l=o.attenuationColor||[1,1,1];return t.attenuationColor=new Bt().setRGB(l[0],l[1],l[2],Ci),Promise.all(i)}}class AL{constructor(e){this.parser=e,this.name=Xt.KHR_MATERIALS_IOR}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Ai}extendMaterialParams(e,t){const a=this.parser.json.materials[e];if(!a.extensions||!a.extensions[this.name])return Promise.resolve();const i=a.extensions[this.name];return t.ior=i.ior!==void 0?i.ior:1.5,Promise.resolve()}}class ML{constructor(e){this.parser=e,this.name=Xt.KHR_MATERIALS_SPECULAR}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Ai}extendMaterialParams(e,t){const n=this.parser,a=n.json.materials[e];if(!a.extensions||!a.extensions[this.name])return Promise.resolve();const i=[],o=a.extensions[this.name];t.specularIntensity=o.specularFactor!==void 0?o.specularFactor:1,o.specularTexture!==void 0&&i.push(n.assignTexture(t,"specularIntensityMap",o.specularTexture));const l=o.specularColorFactor||[1,1,1];return t.specularColor=new Bt().setRGB(l[0],l[1],l[2],Ci),o.specularColorTexture!==void 0&&i.push(n.assignTexture(t,"specularColorMap",o.specularColorTexture,Va)),Promise.all(i)}}class TL{constructor(e){this.parser=e,this.name=Xt.EXT_MATERIALS_BUMP}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Ai}extendMaterialParams(e,t){const n=this.parser,a=n.json.materials[e];if(!a.extensions||!a.extensions[this.name])return Promise.resolve();const i=[],o=a.extensions[this.name];return t.bumpScale=o.bumpFactor!==void 0?o.bumpFactor:1,o.bumpTexture!==void 0&&i.push(n.assignTexture(t,"bumpMap",o.bumpTexture)),Promise.all(i)}}class EL{constructor(e){this.parser=e,this.name=Xt.KHR_MATERIALS_ANISOTROPY}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Ai}extendMaterialParams(e,t){const n=this.parser,a=n.json.materials[e];if(!a.extensions||!a.extensions[this.name])return Promise.resolve();const i=[],o=a.extensions[this.name];return o.anisotropyStrength!==void 0&&(t.anisotropy=o.anisotropyStrength),o.anisotropyRotation!==void 0&&(t.anisotropyRotation=o.anisotropyRotation),o.anisotropyTexture!==void 0&&i.push(n.assignTexture(t,"anisotropyMap",o.anisotropyTexture)),Promise.all(i)}}class _L{constructor(e){this.parser=e,this.name=Xt.KHR_TEXTURE_BASISU}loadTexture(e){const t=this.parser,n=t.json,a=n.textures[e];if(!a.extensions||!a.extensions[this.name])return null;const i=a.extensions[this.name],o=t.options.ktx2Loader;if(!o){if(n.extensionsRequired&&n.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures");return null}return t.loadTextureImage(e,i.source,o)}}class DL{constructor(e){this.parser=e,this.name=Xt.EXT_TEXTURE_WEBP,this.isSupported=null}loadTexture(e){const t=this.name,n=this.parser,a=n.json,i=a.textures[e];if(!i.extensions||!i.extensions[t])return null;const o=i.extensions[t],l=a.images[o.source];let c=n.textureLoader;if(l.uri){const d=n.options.manager.getHandler(l.uri);d!==null&&(c=d)}return this.detectSupport().then(function(d){if(d)return n.loadTextureImage(e,o.source,c);if(a.extensionsRequired&&a.extensionsRequired.indexOf(t)>=0)throw new Error("THREE.GLTFLoader: WebP required by asset but unsupported.");return n.loadTexture(e)})}detectSupport(){return this.isSupported||(this.isSupported=new Promise(function(e){const t=new Image;t.src="data:image/webp;base64,UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA",t.onload=t.onerror=function(){e(t.height===1)}})),this.isSupported}}class PL{constructor(e){this.parser=e,this.name=Xt.EXT_TEXTURE_AVIF,this.isSupported=null}loadTexture(e){const t=this.name,n=this.parser,a=n.json,i=a.textures[e];if(!i.extensions||!i.extensions[t])return null;const o=i.extensions[t],l=a.images[o.source];let c=n.textureLoader;if(l.uri){const d=n.options.manager.getHandler(l.uri);d!==null&&(c=d)}return this.detectSupport().then(function(d){if(d)return n.loadTextureImage(e,o.source,c);if(a.extensionsRequired&&a.extensionsRequired.indexOf(t)>=0)throw new Error("THREE.GLTFLoader: AVIF required by asset but unsupported.");return n.loadTexture(e)})}detectSupport(){return this.isSupported||(this.isSupported=new Promise(function(e){const t=new Image;t.src="data:image/avif;base64,AAAAIGZ0eXBhdmlmAAAAAGF2aWZtaWYxbWlhZk1BMUIAAADybWV0YQAAAAAAAAAoaGRscgAAAAAAAAAAcGljdAAAAAAAAAAAAAAAAGxpYmF2aWYAAAAADnBpdG0AAAAAAAEAAAAeaWxvYwAAAABEAAABAAEAAAABAAABGgAAABcAAAAoaWluZgAAAAAAAQAAABppbmZlAgAAAAABAABhdjAxQ29sb3IAAAAAamlwcnAAAABLaXBjbwAAABRpc3BlAAAAAAAAAAEAAAABAAAAEHBpeGkAAAAAAwgICAAAAAxhdjFDgQAMAAAAABNjb2xybmNseAACAAIABoAAAAAXaXBtYQAAAAAAAAABAAEEAQKDBAAAAB9tZGF0EgAKCBgABogQEDQgMgkQAAAAB8dSLfI=",t.onload=t.onerror=function(){e(t.height===1)}})),this.isSupported}}class RL{constructor(e){this.name=Xt.EXT_MESHOPT_COMPRESSION,this.parser=e}loadBufferView(e){const t=this.parser.json,n=t.bufferViews[e];if(n.extensions&&n.extensions[this.name]){const a=n.extensions[this.name],i=this.parser.getDependency("buffer",a.buffer),o=this.parser.options.meshoptDecoder;if(!o||!o.supported){if(t.extensionsRequired&&t.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files");return null}return i.then(function(l){const c=a.byteOffset||0,d=a.byteLength||0,m=a.count,p=a.byteStride,f=new Uint8Array(l,c,d);return o.decodeGltfBufferAsync?o.decodeGltfBufferAsync(m,p,f,a.mode,a.filter).then(function(b){return b.buffer}):o.ready.then(function(){const b=new ArrayBuffer(m*p);return o.decodeGltfBuffer(new Uint8Array(b),m,p,f,a.mode,a.filter),b})})}else return null}}class LL{constructor(e){this.name=Xt.EXT_MESH_GPU_INSTANCING,this.parser=e}createNodeMesh(e){const t=this.parser.json,n=t.nodes[e];if(!n.extensions||!n.extensions[this.name]||n.mesh===void 0)return null;const a=t.meshes[n.mesh];for(const d of a.primitives)if(d.mode!==Da.TRIANGLES&&d.mode!==Da.TRIANGLE_STRIP&&d.mode!==Da.TRIANGLE_FAN&&d.mode!==void 0)return null;const o=n.extensions[this.name].attributes,l=[],c={};for(const d in o)l.push(this.parser.getDependency("accessor",o[d]).then(m=>(c[d]=m,c[d])));return l.length<1?null:(l.push(this.parser.createNodeMesh(e)),Promise.all(l).then(d=>{const m=d.pop(),p=m.isGroup?m.children:[m],f=d[0].count,b=[];for(const y of p){const w=new Vo,k=new yt,S=new Ko,j=new yt(1,1,1),C=new Ji(y.geometry,y.material,f);for(let A=0;A<f;A++)c.TRANSLATION&&k.fromBufferAttribute(c.TRANSLATION,A),c.ROTATION&&S.fromBufferAttribute(c.ROTATION,A),c.SCALE&&j.fromBufferAttribute(c.SCALE,A),C.setMatrixAt(A,w.compose(k,S,j));for(const A in c)if(A==="_COLOR_0"){const D=c[A];C.instanceColor=new CD(D.array,D.itemSize,D.normalized)}else A!=="TRANSLATION"&&A!=="ROTATION"&&A!=="SCALE"&&y.geometry.setAttribute(A,c[A]);iA.prototype.copy.call(C,y),this.parser.assignFinalMaterial(C),b.push(C)}return m.isGroup?(m.clear(),m.add(...b),m):b[0]}))}}const qA="glTF",ku=12,ej={JSON:1313821514,BIN:5130562};class OL{constructor(e){this.name=Xt.KHR_BINARY_GLTF,this.content=null,this.body=null;const t=new DataView(e,0,ku),n=new TextDecoder;if(this.header={magic:n.decode(new Uint8Array(e.slice(0,4))),version:t.getUint32(4,!0),length:t.getUint32(8,!0)},this.header.magic!==qA)throw new Error("THREE.GLTFLoader: Unsupported glTF-Binary header.");if(this.header.version<2)throw new Error("THREE.GLTFLoader: Legacy binary file detected.");const a=this.header.length-ku,i=new DataView(e,ku);let o=0;for(;o<a;){const l=i.getUint32(o,!0);o+=4;const c=i.getUint32(o,!0);if(o+=4,c===ej.JSON){const d=new Uint8Array(e,ku+o,l);this.content=n.decode(d)}else if(c===ej.BIN){const d=ku+o;this.body=e.slice(d,d+l)}o+=l}if(this.content===null)throw new Error("THREE.GLTFLoader: JSON content not found.")}}class IL{constructor(e,t){if(!t)throw new Error("THREE.GLTFLoader: No DRACOLoader instance provided.");this.name=Xt.KHR_DRACO_MESH_COMPRESSION,this.json=e,this.dracoLoader=t,this.dracoLoader.preload()}decodePrimitive(e,t){const n=this.json,a=this.dracoLoader,i=e.extensions[this.name].bufferView,o=e.extensions[this.name].attributes,l={},c={},d={};for(const m in o){const p=gy[m]||m.toLowerCase();l[p]=o[m]}for(const m in e.attributes){const p=gy[m]||m.toLowerCase();if(o[m]!==void 0){const f=n.accessors[e.attributes[m]],b=ic[f.componentType];d[p]=b.name,c[p]=f.normalized===!0}}return t.getDependency("bufferView",i).then(function(m){return new Promise(function(p,f){a.decodeDracoFile(m,function(b){for(const y in b.attributes){const w=b.attributes[y],k=c[y];k!==void 0&&(w.normalized=k)}p(b)},l,d,Ci,f)})})}}class BL{constructor(){this.name=Xt.KHR_TEXTURE_TRANSFORM}extendTexture(e,t){return(t.texCoord===void 0||t.texCoord===e.channel)&&t.offset===void 0&&t.rotation===void 0&&t.scale===void 0||(e=e.clone(),t.texCoord!==void 0&&(e.channel=t.texCoord),t.offset!==void 0&&e.offset.fromArray(t.offset),t.rotation!==void 0&&(e.rotation=t.rotation),t.scale!==void 0&&e.repeat.fromArray(t.scale),e.needsUpdate=!0),e}}class FL{constructor(){this.name=Xt.KHR_MESH_QUANTIZATION}}class YA extends zD{constructor(e,t,n,a){super(e,t,n,a)}copySampleValue_(e){const t=this.resultBuffer,n=this.sampleValues,a=this.valueSize,i=e*a*3+a;for(let o=0;o!==a;o++)t[o]=n[i+o];return t}interpolate_(e,t,n,a){const i=this.resultBuffer,o=this.sampleValues,l=this.valueSize,c=l*2,d=l*3,m=a-t,p=(n-t)/m,f=p*p,b=f*p,y=e*d,w=y-d,k=-2*b+3*f,S=b-f,j=1-k,C=S-f+p;for(let A=0;A!==l;A++){const D=o[w+A+l],M=o[w+A+c]*m,I=o[y+A+l],E=o[y+A]*m;i[A]=j*D+C*M+k*I+S*E}return i}}const zL=new Ko;class $L extends YA{interpolate_(e,t,n,a){const i=super.interpolate_(e,t,n,a);return zL.fromArray(i).normalize().toArray(i),i}}const Da={POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6},ic={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},tj={9728:rA,9729:In,9984:ED,9985:TD,9986:MD,9987:Hu},nj={33071:DD,33648:_D,10497:Oo},qg={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},gy={POSITION:"position",NORMAL:"normal",TANGENT:"tangent",TEXCOORD_0:"uv",TEXCOORD_1:"uv1",TEXCOORD_2:"uv2",TEXCOORD_3:"uv3",COLOR_0:"color",WEIGHTS_0:"skinWeight",JOINTS_0:"skinIndex"},Ir={scale:"scale",translation:"position",rotation:"quaternion",weights:"morphTargetInfluences"},HL={CUBICSPLINE:void 0,LINEAR:cA,STEP:BD},Yg={OPAQUE:"OPAQUE",MASK:"MASK",BLEND:"BLEND"};function UL(s){return s.DefaultMaterial===void 0&&(s.DefaultMaterial=new rt({color:16777215,emissive:0,metalness:1,roughness:1,transparent:!1,depthTest:!0,side:uA})),s.DefaultMaterial}function To(s,e,t){for(const n in t.extensions)s[n]===void 0&&(e.userData.gltfExtensions=e.userData.gltfExtensions||{},e.userData.gltfExtensions[n]=t.extensions[n])}function Qi(s,e){e.extras!==void 0&&(typeof e.extras=="object"?Object.assign(s.userData,e.extras):console.warn("THREE.GLTFLoader: Ignoring primitive type .extras, "+e.extras))}function GL(s,e,t){let n=!1,a=!1,i=!1;for(let d=0,m=e.length;d<m;d++){const p=e[d];if(p.POSITION!==void 0&&(n=!0),p.NORMAL!==void 0&&(a=!0),p.COLOR_0!==void 0&&(i=!0),n&&a&&i)break}if(!n&&!a&&!i)return Promise.resolve(s);const o=[],l=[],c=[];for(let d=0,m=e.length;d<m;d++){const p=e[d];if(n){const f=p.POSITION!==void 0?t.getDependency("accessor",p.POSITION):s.attributes.position;o.push(f)}if(a){const f=p.NORMAL!==void 0?t.getDependency("accessor",p.NORMAL):s.attributes.normal;l.push(f)}if(i){const f=p.COLOR_0!==void 0?t.getDependency("accessor",p.COLOR_0):s.attributes.color;c.push(f)}}return Promise.all([Promise.all(o),Promise.all(l),Promise.all(c)]).then(function(d){const m=d[0],p=d[1],f=d[2];return n&&(s.morphAttributes.position=m),a&&(s.morphAttributes.normal=p),i&&(s.morphAttributes.color=f),s.morphTargetsRelative=!0,s})}function WL(s,e){if(s.updateMorphTargets(),e.weights!==void 0)for(let t=0,n=e.weights.length;t<n;t++)s.morphTargetInfluences[t]=e.weights[t];if(e.extras&&Array.isArray(e.extras.targetNames)){const t=e.extras.targetNames;if(s.morphTargetInfluences.length===t.length){s.morphTargetDictionary={};for(let n=0,a=t.length;n<a;n++)s.morphTargetDictionary[t[n]]=n}else console.warn("THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.")}}function qL(s){let e;const t=s.extensions&&s.extensions[Xt.KHR_DRACO_MESH_COMPRESSION];if(t?e="draco:"+t.bufferView+":"+t.indices+":"+Vg(t.attributes):e=s.indices+":"+Vg(s.attributes)+":"+s.mode,s.targets!==void 0)for(let n=0,a=s.targets.length;n<a;n++)e+=":"+Vg(s.targets[n]);return e}function Vg(s){let e="";const t=Object.keys(s).sort();for(let n=0,a=t.length;n<a;n++)e+=t[n]+":"+s[t[n]]+";";return e}function by(s){switch(s){case Int8Array:return 1/127;case Uint8Array:return 1/255;case Int16Array:return 1/32767;case Uint16Array:return 1/65535;default:throw new Error("THREE.GLTFLoader: Unsupported normalized accessor component type.")}}function YL(s){return s.search(/\.jpe?g($|\?)/i)>0||s.search(/^data\:image\/jpeg/)===0?"image/jpeg":s.search(/\.webp($|\?)/i)>0||s.search(/^data\:image\/webp/)===0?"image/webp":s.search(/\.ktx2($|\?)/i)>0||s.search(/^data\:image\/ktx2/)===0?"image/ktx2":"image/png"}const VL=new Vo;class KL{constructor(e={},t={}){this.json=e,this.extensions={},this.plugins={},this.options=t,this.cache=new bL,this.associations=new Map,this.primitiveCache={},this.nodeCache={},this.meshCache={refs:{},uses:{}},this.cameraCache={refs:{},uses:{}},this.lightCache={refs:{},uses:{}},this.sourceCache={},this.textureCache={},this.nodeNamesUsed={};let n=!1,a=-1,i=!1,o=-1;if(typeof navigator<"u"){const l=navigator.userAgent;n=/^((?!chrome|android).)*safari/i.test(l)===!0;const c=l.match(/Version\/(\d+)/);a=n&&c?parseInt(c[1],10):-1,i=l.indexOf("Firefox")>-1,o=i?l.match(/Firefox\/([0-9]+)\./)[1]:-1}typeof createImageBitmap>"u"||n&&a<17||i&&o<98?this.textureLoader=new tx(this.options.manager):this.textureLoader=new ND(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new gp(this.options.manager),this.fileLoader.setResponseType("arraybuffer"),this.options.crossOrigin==="use-credentials"&&this.fileLoader.setWithCredentials(!0)}setExtensions(e){this.extensions=e}setPlugins(e){this.plugins=e}parse(e,t){const n=this,a=this.json,i=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(o){return o._markDefs&&o._markDefs()}),Promise.all(this._invokeAll(function(o){return o.beforeRoot&&o.beforeRoot()})).then(function(){return Promise.all([n.getDependencies("scene"),n.getDependencies("animation"),n.getDependencies("camera")])}).then(function(o){const l={scene:o[0][a.scene||0],scenes:o[0],animations:o[1],cameras:o[2],asset:a.asset,parser:n,userData:{}};return To(i,l,a),Qi(l,a),Promise.all(n._invokeAll(function(c){return c.afterRoot&&c.afterRoot(l)})).then(function(){for(const c of l.scenes)c.updateMatrixWorld();e(l)})}).catch(t)}_markDefs(){const e=this.json.nodes||[],t=this.json.skins||[],n=this.json.meshes||[];for(let a=0,i=t.length;a<i;a++){const o=t[a].joints;for(let l=0,c=o.length;l<c;l++)e[o[l]].isBone=!0}for(let a=0,i=e.length;a<i;a++){const o=e[a];o.mesh!==void 0&&(this._addNodeRef(this.meshCache,o.mesh),o.skin!==void 0&&(n[o.mesh].isSkinnedMesh=!0)),o.camera!==void 0&&this._addNodeRef(this.cameraCache,o.camera)}}_addNodeRef(e,t){t!==void 0&&(e.refs[t]===void 0&&(e.refs[t]=e.uses[t]=0),e.refs[t]++)}_getNodeRef(e,t,n){if(e.refs[t]<=1)return n;const a=n.clone(),i=(o,l)=>{const c=this.associations.get(o);c!=null&&this.associations.set(l,c);for(const[d,m]of o.children.entries())i(m,l.children[d])};return i(n,a),a.name+="_instance_"+e.uses[t]++,a}_invokeOne(e){const t=Object.values(this.plugins);t.push(this);for(let n=0;n<t.length;n++){const a=e(t[n]);if(a)return a}return null}_invokeAll(e){const t=Object.values(this.plugins);t.unshift(this);const n=[];for(let a=0;a<t.length;a++){const i=e(t[a]);i&&n.push(i)}return n}getDependency(e,t){const n=e+":"+t;let a=this.cache.get(n);if(!a){switch(e){case"scene":a=this.loadScene(t);break;case"node":a=this._invokeOne(function(i){return i.loadNode&&i.loadNode(t)});break;case"mesh":a=this._invokeOne(function(i){return i.loadMesh&&i.loadMesh(t)});break;case"accessor":a=this.loadAccessor(t);break;case"bufferView":a=this._invokeOne(function(i){return i.loadBufferView&&i.loadBufferView(t)});break;case"buffer":a=this.loadBuffer(t);break;case"material":a=this._invokeOne(function(i){return i.loadMaterial&&i.loadMaterial(t)});break;case"texture":a=this._invokeOne(function(i){return i.loadTexture&&i.loadTexture(t)});break;case"skin":a=this.loadSkin(t);break;case"animation":a=this._invokeOne(function(i){return i.loadAnimation&&i.loadAnimation(t)});break;case"camera":a=this.loadCamera(t);break;default:if(a=this._invokeOne(function(i){return i!=this&&i.getDependency&&i.getDependency(e,t)}),!a)throw new Error("Unknown type: "+e);break}this.cache.add(n,a)}return a}getDependencies(e){let t=this.cache.get(e);if(!t){const n=this,a=this.json[e+(e==="mesh"?"es":"s")]||[];t=Promise.all(a.map(function(i,o){return n.getDependency(e,o)})),this.cache.add(e,t)}return t}loadBuffer(e){const t=this.json.buffers[e],n=this.fileLoader;if(t.type&&t.type!=="arraybuffer")throw new Error("THREE.GLTFLoader: "+t.type+" buffer type is not supported.");if(t.uri===void 0&&e===0)return Promise.resolve(this.extensions[Xt.KHR_BINARY_GLTF].body);const a=this.options;return new Promise(function(i,o){n.load($u.resolveURL(t.uri,a.path),i,void 0,function(){o(new Error('THREE.GLTFLoader: Failed to load buffer "'+t.uri+'".'))})})}loadBufferView(e){const t=this.json.bufferViews[e];return this.getDependency("buffer",t.buffer).then(function(n){const a=t.byteLength||0,i=t.byteOffset||0;return n.slice(i,i+a)})}loadAccessor(e){const t=this,n=this.json,a=this.json.accessors[e];if(a.bufferView===void 0&&a.sparse===void 0){const o=qg[a.type],l=ic[a.componentType],c=a.normalized===!0,d=new l(a.count*o);return Promise.resolve(new Ka(d,o,c))}const i=[];return a.bufferView!==void 0?i.push(this.getDependency("bufferView",a.bufferView)):i.push(null),a.sparse!==void 0&&(i.push(this.getDependency("bufferView",a.sparse.indices.bufferView)),i.push(this.getDependency("bufferView",a.sparse.values.bufferView))),Promise.all(i).then(function(o){const l=o[0],c=qg[a.type],d=ic[a.componentType],m=d.BYTES_PER_ELEMENT,p=m*c,f=a.byteOffset||0,b=a.bufferView!==void 0?n.bufferViews[a.bufferView].byteStride:void 0,y=a.normalized===!0;let w,k;if(b&&b!==p){const S=Math.floor(f/b),j="InterleavedBuffer:"+a.bufferView+":"+a.componentType+":"+S+":"+a.count;let C=t.cache.get(j);C||(w=new d(l,S*b,a.count*b/m),C=new AD(w,b/m),t.cache.add(j,C)),k=new FD(C,c,f%b/m,y)}else l===null?w=new d(a.count*c):w=new d(l,f,a.count*c),k=new Ka(w,c,y);if(a.sparse!==void 0){const S=qg.SCALAR,j=ic[a.sparse.indices.componentType],C=a.sparse.indices.byteOffset||0,A=a.sparse.values.byteOffset||0,D=new j(o[1],C,a.sparse.count*S),M=new d(o[2],A,a.sparse.count*c);l!==null&&(k=new Ka(k.array.slice(),k.itemSize,k.normalized)),k.normalized=!1;for(let I=0,E=D.length;I<E;I++){const _=D[I];if(k.setX(_,M[I*c]),c>=2&&k.setY(_,M[I*c+1]),c>=3&&k.setZ(_,M[I*c+2]),c>=4&&k.setW(_,M[I*c+3]),c>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}k.normalized=y}return k})}loadTexture(e){const t=this.json,n=this.options,i=t.textures[e].source,o=t.images[i];let l=this.textureLoader;if(o.uri){const c=n.manager.getHandler(o.uri);c!==null&&(l=c)}return this.loadTextureImage(e,i,l)}loadTextureImage(e,t,n){const a=this,i=this.json,o=i.textures[e],l=i.images[t],c=(l.uri||l.bufferView)+":"+o.sampler;if(this.textureCache[c])return this.textureCache[c];const d=this.loadImageSource(t,n).then(function(m){m.flipY=!1,m.name=o.name||l.name||"",m.name===""&&typeof l.uri=="string"&&l.uri.startsWith("data:image/")===!1&&(m.name=l.uri);const f=(i.samplers||{})[o.sampler]||{};return m.magFilter=tj[f.magFilter]||In,m.minFilter=tj[f.minFilter]||Hu,m.wrapS=nj[f.wrapS]||Oo,m.wrapT=nj[f.wrapT]||Oo,m.generateMipmaps=!m.isCompressedTexture&&m.minFilter!==rA&&m.minFilter!==In,a.associations.set(m,{textures:e}),m}).catch(function(){return null});return this.textureCache[c]=d,d}loadImageSource(e,t){const n=this,a=this.json,i=this.options;if(this.sourceCache[e]!==void 0)return this.sourceCache[e].then(p=>p.clone());const o=a.images[e],l=self.URL||self.webkitURL;let c=o.uri||"",d=!1;if(o.bufferView!==void 0)c=n.getDependency("bufferView",o.bufferView).then(function(p){d=!0;const f=new Blob([p],{type:o.mimeType});return c=l.createObjectURL(f),c});else if(o.uri===void 0)throw new Error("THREE.GLTFLoader: Image "+e+" is missing URI and bufferView");const m=Promise.resolve(c).then(function(p){return new Promise(function(f,b){let y=f;t.isImageBitmapLoader===!0&&(y=function(w){const k=new Zk(w);k.needsUpdate=!0,f(k)}),t.load($u.resolveURL(p,i.path),y,void 0,b)})}).then(function(p){return d===!0&&l.revokeObjectURL(c),Qi(p,o),p.userData.mimeType=o.mimeType||YL(o.uri),p}).catch(function(p){throw console.error("THREE.GLTFLoader: Couldn't load texture",c),p});return this.sourceCache[e]=m,m}assignTexture(e,t,n,a){const i=this;return this.getDependency("texture",n.index).then(function(o){if(!o)return null;if(n.texCoord!==void 0&&n.texCoord>0&&(o=o.clone(),o.channel=n.texCoord),i.extensions[Xt.KHR_TEXTURE_TRANSFORM]){const l=n.extensions!==void 0?n.extensions[Xt.KHR_TEXTURE_TRANSFORM]:void 0;if(l){const c=i.associations.get(o);o=i.extensions[Xt.KHR_TEXTURE_TRANSFORM].extendTexture(o,l),i.associations.set(o,c)}}return a!==void 0&&(o.colorSpace=a),e[t]=o,o})}assignFinalMaterial(e){const t=e.geometry;let n=e.material;const a=t.attributes.tangent===void 0,i=t.attributes.color!==void 0,o=t.attributes.normal===void 0;if(e.isPoints){const l="PointsMaterial:"+n.uuid;let c=this.cache.get(l);c||(c=new nm,Ur.prototype.copy.call(c,n),c.color.copy(n.color),c.map=n.map,c.sizeAttenuation=!1,this.cache.add(l,c)),n=c}else if(e.isLine){const l="LineBasicMaterial:"+n.uuid;let c=this.cache.get(l);c||(c=new Io,Ur.prototype.copy.call(c,n),c.color.copy(n.color),c.map=n.map,this.cache.add(l,c)),n=c}if(a||i||o){let l="ClonedMaterial:"+n.uuid+":";a&&(l+="derivative-tangents:"),i&&(l+="vertex-colors:"),o&&(l+="flat-shading:");let c=this.cache.get(l);c||(c=n.clone(),i&&(c.vertexColors=!0),o&&(c.flatShading=!0),a&&(c.normalScale&&(c.normalScale.y*=-1),c.clearcoatNormalScale&&(c.clearcoatNormalScale.y*=-1)),this.cache.add(l,c),this.associations.set(c,this.associations.get(n))),n=c}e.material=n}getMaterialType(){return rt}loadMaterial(e){const t=this,n=this.json,a=this.extensions,i=n.materials[e];let o;const l={},c=i.extensions||{},d=[];if(c[Xt.KHR_MATERIALS_UNLIT]){const p=a[Xt.KHR_MATERIALS_UNLIT];o=p.getMaterialType(),d.push(p.extendParams(l,i,t))}else{const p=i.pbrMetallicRoughness||{};if(l.color=new Bt(1,1,1),l.opacity=1,Array.isArray(p.baseColorFactor)){const f=p.baseColorFactor;l.color.setRGB(f[0],f[1],f[2],Ci),l.opacity=f[3]}p.baseColorTexture!==void 0&&d.push(t.assignTexture(l,"map",p.baseColorTexture,Va)),l.metalness=p.metallicFactor!==void 0?p.metallicFactor:1,l.roughness=p.roughnessFactor!==void 0?p.roughnessFactor:1,p.metallicRoughnessTexture!==void 0&&(d.push(t.assignTexture(l,"metalnessMap",p.metallicRoughnessTexture)),d.push(t.assignTexture(l,"roughnessMap",p.metallicRoughnessTexture))),o=this._invokeOne(function(f){return f.getMaterialType&&f.getMaterialType(e)}),d.push(Promise.all(this._invokeAll(function(f){return f.extendMaterialParams&&f.extendMaterialParams(e,l)})))}i.doubleSided===!0&&(l.side=ws);const m=i.alphaMode||Yg.OPAQUE;if(m===Yg.BLEND?(l.transparent=!0,l.depthWrite=!1):(l.transparent=!1,m===Yg.MASK&&(l.alphaTest=i.alphaCutoff!==void 0?i.alphaCutoff:.5)),i.normalTexture!==void 0&&o!==We&&(d.push(t.assignTexture(l,"normalMap",i.normalTexture)),l.normalScale=new _s(1,1),i.normalTexture.scale!==void 0)){const p=i.normalTexture.scale;l.normalScale.set(p,p)}if(i.occlusionTexture!==void 0&&o!==We&&(d.push(t.assignTexture(l,"aoMap",i.occlusionTexture)),i.occlusionTexture.strength!==void 0&&(l.aoMapIntensity=i.occlusionTexture.strength)),i.emissiveFactor!==void 0&&o!==We){const p=i.emissiveFactor;l.emissive=new Bt().setRGB(p[0],p[1],p[2],Ci)}return i.emissiveTexture!==void 0&&o!==We&&d.push(t.assignTexture(l,"emissiveMap",i.emissiveTexture,Va)),Promise.all(d).then(function(){const p=new o(l);return i.name&&(p.name=i.name),Qi(p,i),t.associations.set(p,{materials:e}),i.extensions&&To(a,p,i),p})}createUniqueName(e){const t=PD.sanitizeNodeName(e||"");return t in this.nodeNamesUsed?t+"_"+ ++this.nodeNamesUsed[t]:(this.nodeNamesUsed[t]=0,t)}loadGeometries(e){const t=this,n=this.extensions,a=this.primitiveCache;function i(l){return n[Xt.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(l,t).then(function(c){return sj(c,l,t)})}const o=[];for(let l=0,c=e.length;l<c;l++){const d=e[l],m=qL(d),p=a[m];if(p)o.push(p.promise);else{let f;d.extensions&&d.extensions[Xt.KHR_DRACO_MESH_COMPRESSION]?f=i(d):f=sj(new La,d,t),a[m]={primitive:d,promise:f},o.push(f)}}return Promise.all(o)}loadMesh(e){const t=this,n=this.json,a=this.extensions,i=n.meshes[e],o=i.primitives,l=[];for(let c=0,d=o.length;c<d;c++){const m=o[c].material===void 0?UL(this.cache):this.getDependency("material",o[c].material);l.push(m)}return l.push(t.loadGeometries(o)),Promise.all(l).then(function(c){const d=c.slice(0,c.length-1),m=c[c.length-1],p=[];for(let b=0,y=m.length;b<y;b++){const w=m[b],k=o[b];let S;const j=d[b];if(k.mode===Da.TRIANGLES||k.mode===Da.TRIANGLE_STRIP||k.mode===Da.TRIANGLE_FAN||k.mode===void 0)S=i.isSkinnedMesh===!0?new Vb(w,j):new De(w,j),S.isSkinnedMesh===!0&&S.normalizeSkinWeights(),k.mode===Da.TRIANGLE_STRIP?S.geometry=JS(S.geometry,nA):k.mode===Da.TRIANGLE_FAN&&(S.geometry=JS(S.geometry,Yb));else if(k.mode===Da.LINES)S=new nx(w,j);else if(k.mode===Da.LINE_STRIP)S=new zr(w,j);else if(k.mode===Da.LINE_LOOP)S=new RD(w,j);else if(k.mode===Da.POINTS)S=new dd(w,j);else throw new Error("THREE.GLTFLoader: Primitive mode unsupported: "+k.mode);Object.keys(S.geometry.morphAttributes).length>0&&WL(S,i),S.name=t.createUniqueName(i.name||"mesh_"+e),Qi(S,i),k.extensions&&To(a,S,k),t.assignFinalMaterial(S),p.push(S)}for(let b=0,y=p.length;b<y;b++)t.associations.set(p[b],{meshes:e,primitives:b});if(p.length===1)return i.extensions&&To(a,p[0],i),p[0];const f=new Bn;i.extensions&&To(a,f,i),t.associations.set(f,{meshes:e});for(let b=0,y=p.length;b<y;b++)f.add(p[b]);return f})}loadCamera(e){let t;const n=this.json.cameras[e],a=n[n.type];if(!a){console.warn("THREE.GLTFLoader: Missing camera parameters.");return}return n.type==="perspective"?t=new sx(oA.radToDeg(a.yfov),a.aspectRatio||1,a.znear||1,a.zfar||2e6):n.type==="orthographic"&&(t=new lA(-a.xmag,a.xmag,a.ymag,-a.ymag,a.znear,a.zfar)),n.name&&(t.name=this.createUniqueName(n.name)),Qi(t,n),Promise.resolve(t)}loadSkin(e){const t=this.json.skins[e],n=[];for(let a=0,i=t.joints.length;a<i;a++)n.push(this._loadNodeShallow(t.joints[a]));return t.inverseBindMatrices!==void 0?n.push(this.getDependency("accessor",t.inverseBindMatrices)):n.push(null),Promise.all(n).then(function(a){const i=a.pop(),o=a,l=[],c=[];for(let d=0,m=o.length;d<m;d++){const p=o[d];if(p){l.push(p);const f=new Vo;i!==null&&f.fromArray(i.array,d*16),c.push(f)}else console.warn('THREE.GLTFLoader: Joint "%s" could not be found.',t.joints[d])}return new LD(l,c)})}loadAnimation(e){const t=this.json,n=this,a=t.animations[e],i=a.name?a.name:"animation_"+e,o=[],l=[],c=[],d=[],m=[];for(let p=0,f=a.channels.length;p<f;p++){const b=a.channels[p],y=a.samplers[b.sampler],w=b.target,k=w.node,S=a.parameters!==void 0?a.parameters[y.input]:y.input,j=a.parameters!==void 0?a.parameters[y.output]:y.output;w.node!==void 0&&(o.push(this.getDependency("node",k)),l.push(this.getDependency("accessor",S)),c.push(this.getDependency("accessor",j)),d.push(y),m.push(w))}return Promise.all([Promise.all(o),Promise.all(l),Promise.all(c),Promise.all(d),Promise.all(m)]).then(function(p){const f=p[0],b=p[1],y=p[2],w=p[3],k=p[4],S=[];for(let j=0,C=f.length;j<C;j++){const A=f[j],D=b[j],M=y[j],I=w[j],E=k[j];if(A===void 0)continue;A.updateMatrix&&A.updateMatrix();const _=n._createAnimationTracks(A,D,M,I,E);if(_)for(let P=0;P<_.length;P++)S.push(_[P])}return new OD(i,void 0,S)})}createNodeMesh(e){const t=this.json,n=this,a=t.nodes[e];return a.mesh===void 0?null:n.getDependency("mesh",a.mesh).then(function(i){const o=n._getNodeRef(n.meshCache,a.mesh,i);return a.weights!==void 0&&o.traverse(function(l){if(l.isMesh)for(let c=0,d=a.weights.length;c<d;c++)l.morphTargetInfluences[c]=a.weights[c]}),o})}loadNode(e){const t=this.json,n=this,a=t.nodes[e],i=n._loadNodeShallow(e),o=[],l=a.children||[];for(let d=0,m=l.length;d<m;d++)o.push(n.getDependency("node",l[d]));const c=a.skin===void 0?Promise.resolve(null):n.getDependency("skin",a.skin);return Promise.all([i,Promise.all(o),c]).then(function(d){const m=d[0],p=d[1],f=d[2];f!==null&&m.traverse(function(b){b.isSkinnedMesh&&b.bind(f,VL)});for(let b=0,y=p.length;b<y;b++)m.add(p[b]);return m})}_loadNodeShallow(e){const t=this.json,n=this.extensions,a=this;if(this.nodeCache[e]!==void 0)return this.nodeCache[e];const i=t.nodes[e],o=i.name?a.createUniqueName(i.name):"",l=[],c=a._invokeOne(function(d){return d.createNodeMesh&&d.createNodeMesh(e)});return c&&l.push(c),i.camera!==void 0&&l.push(a.getDependency("camera",i.camera).then(function(d){return a._getNodeRef(a.cameraCache,i.camera,d)})),a._invokeAll(function(d){return d.createNodeAttachment&&d.createNodeAttachment(e)}).forEach(function(d){l.push(d)}),this.nodeCache[e]=Promise.all(l).then(function(d){let m;if(i.isBone===!0?m=new ID:d.length>1?m=new Bn:d.length===1?m=d[0]:m=new iA,m!==d[0])for(let p=0,f=d.length;p<f;p++)m.add(d[p]);if(i.name&&(m.userData.name=i.name,m.name=o),Qi(m,i),i.extensions&&To(n,m,i),i.matrix!==void 0){const p=new Vo;p.fromArray(i.matrix),m.applyMatrix4(p)}else i.translation!==void 0&&m.position.fromArray(i.translation),i.rotation!==void 0&&m.quaternion.fromArray(i.rotation),i.scale!==void 0&&m.scale.fromArray(i.scale);return a.associations.has(m)||a.associations.set(m,{}),a.associations.get(m).nodes=e,m}),this.nodeCache[e]}loadScene(e){const t=this.extensions,n=this.json.scenes[e],a=this,i=new Bn;n.name&&(i.name=a.createUniqueName(n.name)),Qi(i,n),n.extensions&&To(t,i,n);const o=n.nodes||[],l=[];for(let c=0,d=o.length;c<d;c++)l.push(a.getDependency("node",o[c]));return Promise.all(l).then(function(c){for(let m=0,p=c.length;m<p;m++)i.add(c[m]);const d=m=>{const p=new Map;for(const[f,b]of a.associations)(f instanceof Ur||f instanceof Zk)&&p.set(f,b);return m.traverse(f=>{const b=a.associations.get(f);b!=null&&p.set(f,b)}),p};return a.associations=d(i),i})}_createAnimationTracks(e,t,n,a,i){const o=[],l=e.name?e.name:e.uuid,c=[];Ir[i.path]===Ir.weights?e.traverse(function(f){f.morphTargetInfluences&&c.push(f.name?f.name:f.uuid)}):c.push(l);let d;switch(Ir[i.path]){case Ir.weights:d=Jk;break;case Ir.rotation:d=eS;break;case Ir.position:case Ir.scale:d=Qk;break;default:switch(n.itemSize){case 1:d=Jk;break;case 2:case 3:default:d=Qk;break}break}const m=a.interpolation!==void 0?HL[a.interpolation]:cA,p=this._getArrayFromAccessor(n);for(let f=0,b=c.length;f<b;f++){const y=new d(c[f]+"."+Ir[i.path],t.array,p,m);a.interpolation==="CUBICSPLINE"&&this._createCubicSplineTrackInterpolant(y),o.push(y)}return o}_getArrayFromAccessor(e){let t=e.array;if(e.normalized){const n=by(t.constructor),a=new Float32Array(t.length);for(let i=0,o=t.length;i<o;i++)a[i]=t[i]*n;t=a}return t}_createCubicSplineTrackInterpolant(e){e.createInterpolant=function(n){const a=this instanceof eS?$L:YA;return new a(this.times,this.values,this.getValueSize()/3,n)},e.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline=!0}}function XL(s,e,t){const n=e.attributes,a=new bp;if(n.POSITION!==void 0){const l=t.json.accessors[n.POSITION],c=l.min,d=l.max;if(c!==void 0&&d!==void 0){if(a.set(new yt(c[0],c[1],c[2]),new yt(d[0],d[1],d[2])),l.normalized){const m=by(ic[l.componentType]);a.min.multiplyScalar(m),a.max.multiplyScalar(m)}}else{console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.");return}}else return;const i=e.targets;if(i!==void 0){const l=new yt,c=new yt;for(let d=0,m=i.length;d<m;d++){const p=i[d];if(p.POSITION!==void 0){const f=t.json.accessors[p.POSITION],b=f.min,y=f.max;if(b!==void 0&&y!==void 0){if(c.setX(Math.max(Math.abs(b[0]),Math.abs(y[0]))),c.setY(Math.max(Math.abs(b[1]),Math.abs(y[1]))),c.setZ(Math.max(Math.abs(b[2]),Math.abs(y[2]))),f.normalized){const w=by(ic[f.componentType]);c.multiplyScalar(w)}l.max(c)}else console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.")}}a.expandByVector(l)}s.boundingBox=a;const o=new $D;a.getCenter(o.center),o.radius=a.min.distanceTo(a.max)/2,s.boundingSphere=o}function sj(s,e,t){const n=e.attributes,a=[];function i(o,l){return t.getDependency("accessor",o).then(function(c){s.setAttribute(l,c)})}for(const o in n){const l=gy[o]||o.toLowerCase();l in s.attributes||a.push(i(n[o],l))}if(e.indices!==void 0&&!s.index){const o=t.getDependency("accessor",e.indices).then(function(l){s.setIndex(l)});a.push(o)}return Kb.workingColorSpace!==Ci&&"COLOR_0"in n&&console.warn(`THREE.GLTFLoader: Converting vertex colors from "srgb-linear" to "${Kb.workingColorSpace}" not supported.`),Qi(s,e),XL(s,e,t),Promise.all(a).then(function(){return e.targets!==void 0?GL(s,e.targets,t):s})}const Kg=new WeakMap;class hx extends sA{constructor(e){super(e),this.decoderPath="",this.decoderConfig={},this.decoderBinary=null,this.decoderPending=null,this.workerLimit=4,this.workerPool=[],this.workerNextTaskID=1,this.workerSourceURL="",this.defaultAttributeIDs={position:"POSITION",normal:"NORMAL",color:"COLOR",uv:"TEX_COORD"},this.defaultAttributeTypes={position:"Float32Array",normal:"Float32Array",color:"Float32Array",uv:"Float32Array"}}setDecoderPath(e){return this.decoderPath=e,this}setDecoderConfig(e){return this.decoderConfig=e,this}setWorkerLimit(e){return this.workerLimit=e,this}load(e,t,n,a){const i=new gp(this.manager);i.setPath(this.path),i.setResponseType("arraybuffer"),i.setRequestHeader(this.requestHeader),i.setWithCredentials(this.withCredentials),i.load(e,o=>{this.parse(o,t,a)},n,a)}parse(e,t,n=()=>{}){this.decodeDracoFile(e,t,null,null,Va,n).catch(n)}decodeDracoFile(e,t,n,a,i=Ci,o=()=>{}){const l={attributeIDs:n||this.defaultAttributeIDs,attributeTypes:a||this.defaultAttributeTypes,useUniqueIDs:!!n,vertexColorSpace:i};return this.decodeGeometry(e,l).then(t).catch(o)}decodeGeometry(e,t){const n=JSON.stringify(t);if(Kg.has(e)){const c=Kg.get(e);if(c.key===n)return c.promise;if(e.byteLength===0)throw new Error("THREE.DRACOLoader: Unable to re-decode a buffer with different settings. Buffer has already been transferred.")}let a;const i=this.workerNextTaskID++,o=e.byteLength,l=this._getWorker(i,o).then(c=>(a=c,new Promise((d,m)=>{a._callbacks[i]={resolve:d,reject:m},a.postMessage({type:"decode",id:i,taskConfig:t,buffer:e},[e])}))).then(c=>this._createGeometry(c.geometry));return l.catch(()=>!0).then(()=>{a&&i&&this._releaseTask(a,i)}),Kg.set(e,{key:n,promise:l}),l}_createGeometry(e){const t=new La;e.index&&t.setIndex(new Ka(e.index.array,1));for(let n=0;n<e.attributes.length;n++){const a=e.attributes[n],i=a.name,o=a.array,l=a.itemSize,c=new Ka(o,l);i==="color"&&(this._assignVertexColorSpace(c,a.vertexColorSpace),c.normalized=!(o instanceof Float32Array)),t.setAttribute(i,c)}return t}_assignVertexColorSpace(e,t){if(t!==Va)return;const n=new Bt;for(let a=0,i=e.count;a<i;a++)n.fromBufferAttribute(e,a),Kb.toWorkingColorSpace(n,Va),e.setXYZ(a,n.r,n.g,n.b)}_loadLibrary(e,t){const n=new gp(this.manager);return n.setPath(this.decoderPath),n.setResponseType(t),n.setWithCredentials(this.withCredentials),new Promise((a,i)=>{n.load(e,a,void 0,i)})}preload(){return this._initDecoder(),this}_initDecoder(){if(this.decoderPending)return this.decoderPending;const e=typeof WebAssembly!="object"||this.decoderConfig.type==="js",t=[];return e?t.push(this._loadLibrary("draco_decoder.js","text")):(t.push(this._loadLibrary("draco_wasm_wrapper.js","text")),t.push(this._loadLibrary("draco_decoder.wasm","arraybuffer"))),this.decoderPending=Promise.all(t).then(n=>{const a=n[0];e||(this.decoderConfig.wasmBinary=n[1]);const i=ZL.toString(),o=["/* draco decoder */",a,"","/* worker */",i.substring(i.indexOf("{")+1,i.lastIndexOf("}"))].join(`
43
43
  `);this.workerSourceURL=URL.createObjectURL(new Blob([o]))}),this.decoderPending}_getWorker(e,t){return this._initDecoder().then(()=>{if(this.workerPool.length<this.workerLimit){const a=new Worker(this.workerSourceURL);a._callbacks={},a._taskCosts={},a._taskLoad=0,a.postMessage({type:"init",decoderConfig:this.decoderConfig}),a.onmessage=function(i){const o=i.data;switch(o.type){case"decode":a._callbacks[o.id].resolve(o);break;case"error":a._callbacks[o.id].reject(o);break;default:console.error('THREE.DRACOLoader: Unexpected message, "'+o.type+'"')}},this.workerPool.push(a)}else this.workerPool.sort(function(a,i){return a._taskLoad>i._taskLoad?-1:1});const n=this.workerPool[this.workerPool.length-1];return n._taskCosts[e]=t,n._taskLoad+=t,n})}_releaseTask(e,t){e._taskLoad-=e._taskCosts[t],delete e._callbacks[t],delete e._taskCosts[t]}debug(){console.log("Task load: ",this.workerPool.map(e=>e._taskLoad))}dispose(){for(let e=0;e<this.workerPool.length;++e)this.workerPool[e].terminate();return this.workerPool.length=0,this.workerSourceURL!==""&&URL.revokeObjectURL(this.workerSourceURL),this}}function ZL(){let s,e;onmessage=function(o){const l=o.data;switch(l.type){case"init":s=l.decoderConfig,e=new Promise(function(m){s.onModuleLoaded=function(p){m({draco:p})},DracoDecoderModule(s)});break;case"decode":const c=l.buffer,d=l.taskConfig;e.then(m=>{const p=m.draco,f=new p.Decoder;try{const b=t(p,f,new Int8Array(c),d),y=b.attributes.map(w=>w.array.buffer);b.index&&y.push(b.index.array.buffer),self.postMessage({type:"decode",id:l.id,geometry:b},y)}catch(b){console.error(b),self.postMessage({type:"error",id:l.id,error:b.message})}finally{p.destroy(f)}});break}};function t(o,l,c,d){const m=d.attributeIDs,p=d.attributeTypes;let f,b;const y=l.GetEncodedGeometryType(c);if(y===o.TRIANGULAR_MESH)f=new o.Mesh,b=l.DecodeArrayToMesh(c,c.byteLength,f);else if(y===o.POINT_CLOUD)f=new o.PointCloud,b=l.DecodeArrayToPointCloud(c,c.byteLength,f);else throw new Error("THREE.DRACOLoader: Unexpected geometry type.");if(!b.ok()||f.ptr===0)throw new Error("THREE.DRACOLoader: Decoding failed: "+b.error_msg());const w={index:null,attributes:[]};for(const k in m){const S=self[p[k]];let j,C;if(d.useUniqueIDs)C=m[k],j=l.GetAttributeByUniqueId(f,C);else{if(C=l.GetAttributeId(f,o[m[k]]),C===-1)continue;j=l.GetAttribute(f,C)}const A=a(o,l,f,k,S,j);k==="color"&&(A.vertexColorSpace=d.vertexColorSpace),w.attributes.push(A)}return y===o.TRIANGULAR_MESH&&(w.index=n(o,l,f)),o.destroy(f),w}function n(o,l,c){const m=c.num_faces()*3,p=m*4,f=o._malloc(p);l.GetTrianglesUInt32Array(c,p,f);const b=new Uint32Array(o.HEAPF32.buffer,f,m).slice();return o._free(f),{array:b,itemSize:1}}function a(o,l,c,d,m,p){const f=p.num_components(),y=c.num_points()*f,w=y*m.BYTES_PER_ELEMENT,k=i(o,m),S=o._malloc(w);l.GetAttributeDataArrayForAllPoints(c,p,k,w,S);const j=new m(o.HEAPF32.buffer,S,y).slice();return o._free(S),{name:d,array:j,itemSize:f}}function i(o,l){switch(l){case Float32Array:return o.DT_FLOAT32;case Int8Array:return o.DT_INT8;case Int16Array:return o.DT_INT16;case Int32Array:return o.DT_INT32;case Uint8Array:return o.DT_UINT8;case Uint16Array:return o.DT_UINT16;case Uint32Array:return o.DT_UINT32}}}var px=(function(){var s="b9H79Tebbbe8Fv9Gbb9Gvuuuuueu9Giuuub9Geueu9Giuuueuikqbeeedddillviebeoweuec:q;iekr;leDo9TW9T9VV95dbH9F9F939H79T9F9J9H229F9Jt9VV7bb8A9TW79O9V9Wt9F9KW9J9V9KW9wWVtW949c919M9MWVbeY9TW79O9V9Wt9F9KW9J9V9KW69U9KW949c919M9MWVbdE9TW79O9V9Wt9F9KW9J9V9KW69U9KW949tWG91W9U9JWbiL9TW79O9V9Wt9F9KW9J9V9KWS9P2tWV9p9JtblK9TW79O9V9Wt9F9KW9J9V9KWS9P2tWV9r919HtbvL9TW79O9V9Wt9F9KW9J9V9KWS9P2tWVT949Wbol79IV9Rbrq:P8Yqdbk;3sezu8Jjjjjbcj;eb9Rgv8Kjjjjbc9:hodnadcefal0mbcuhoaiRbbc:Ge9hmbavaialfgrad9Radz1jjjbhwcj;abad9UhoaicefhldnadTmbaoc;WFbGgocjdaocjd6EhDcbhqinaqae9pmeaDaeaq9RaqaDfae6Egkcsfgocl4cifcd4hxdndndndnaoc9WGgmTmbcbhPcehsawcjdfhzalhHinaraH9Rax6midnaraHaxfgl9RcK6mbczhoinawcj;cbfaogifgoc9WfhOdndndndndnaHaic9WfgAco4fRbbaAci4coG4ciGPlbedibkaO9cb83ibaOcwf9cb83ibxikaOalRblalRbbgAco4gCaCciSgCE86bbaocGfalclfaCfgORbbaAcl4ciGgCaCciSgCE86bbaocVfaOaCfgORbbaAcd4ciGgCaCciSgCE86bbaoc7faOaCfgORbbaAciGgAaAciSgAE86bbaoctfaOaAfgARbbalRbegOco4gCaCciSgCE86bbaoc91faAaCfgARbbaOcl4ciGgCaCciSgCE86bbaoc4faAaCfgARbbaOcd4ciGgCaCciSgCE86bbaoc93faAaCfgARbbaOciGgOaOciSgOE86bbaoc94faAaOfgARbbalRbdgOco4gCaCciSgCE86bbaoc95faAaCfgARbbaOcl4ciGgCaCciSgCE86bbaoc96faAaCfgARbbaOcd4ciGgCaCciSgCE86bbaoc97faAaCfgARbbaOciGgOaOciSgOE86bbaoc98faAaOfgORbbalRbiglco4gAaAciSgAE86bbaoc99faOaAfgORbbalcl4ciGgAaAciSgAE86bbaoc9:faOaAfgORbbalcd4ciGgAaAciSgAE86bbaocufaOaAfgoRbbalciGglalciSglE86bbaoalfhlxdkaOalRbwalRbbgAcl4gCaCcsSgCE86bbaocGfalcwfaCfgORbbaAcsGgAaAcsSgAE86bbaocVfaOaAfgORbbalRbegAcl4gCaCcsSgCE86bbaoc7faOaCfgORbbaAcsGgAaAcsSgAE86bbaoctfaOaAfgORbbalRbdgAcl4gCaCcsSgCE86bbaoc91faOaCfgORbbaAcsGgAaAcsSgAE86bbaoc4faOaAfgORbbalRbigAcl4gCaCcsSgCE86bbaoc93faOaCfgORbbaAcsGgAaAcsSgAE86bbaoc94faOaAfgORbbalRblgAcl4gCaCcsSgCE86bbaoc95faOaCfgORbbaAcsGgAaAcsSgAE86bbaoc96faOaAfgORbbalRbvgAcl4gCaCcsSgCE86bbaoc97faOaCfgORbbaAcsGgAaAcsSgAE86bbaoc98faOaAfgORbbalRbogAcl4gCaCcsSgCE86bbaoc99faOaCfgORbbaAcsGgAaAcsSgAE86bbaoc9:faOaAfgORbbalRbrglcl4gAaAcsSgAE86bbaocufaOaAfgoRbbalcsGglalcsSglE86bbaoalfhlxekaOal8Pbb83bbaOcwfalcwf8Pbb83bbalczfhlkdnaiam9pmbaiczfhoaral9RcL0mekkaiam6mialTmidnakTmbawaPfRbbhOcbhoazhiinaiawcj;cbfaofRbbgAce4cbaAceG9R7aOfgO86bbaiadfhiaocefgoak9hmbkkazcefhzaPcefgPad6hsalhHaPad9hmexvkkcbhlasceGmdxikalaxad2fhCdnakTmbcbhHcehsawcjdfhminaral9Rax6mialTmdalaxfhlawaHfRbbhOcbhoamhiinaiawcj;cbfaofRbbgAce4cbaAceG9R7aOfgO86bbaiadfhiaocefgoak9hmbkamcefhmaHcefgHad6hsaHad9hmbkaChlxikcbhocehsinaral9Rax6mdalTmealaxfhlaocefgoad6hsadao9hmbkaChlxdkcbhlasceGTmekc9:hoxikabaqad2fawcjdfakad2z1jjjb8Aawawcjdfakcufad2fadz1jjjb8Aakaqfhqalmbkc9:hoxekcbc99aral9Radcaadca0ESEhokavcj;ebf8Kjjjjbaok;yzeHu8Jjjjjbc;ae9Rgv8Kjjjjbc9:hodnaeci9UgrcHfal0mbcuhoaiRbbgwc;WeGc;Ge9hmbawcsGgDce0mbavc;abfcFecjez:jjjjb8AavcUf9cu83ibavc8Wf9cu83ibavcyf9cu83ibavcaf9cu83ibavcKf9cu83ibavczf9cu83ibav9cu83iwav9cu83ibaialfc9WfhqaicefgwarfhodnaeTmbcmcsaDceSEhkcbhxcbhmcbhDcbhicbhlindnaoaq9nmbc9:hoxikdndnawRbbgrc;Ve0mbavc;abfalarcl4cu7fcsGcitfgPydlhsaPydbhzdnarcsGgPak9pmbavaiarcu7fcsGcdtfydbaxaPEhraPThPdndnadcd9hmbabaDcetfgHaz87ebaHcdfas87ebaHclfar87ebxekabaDcdtfgHazBdbaHclfasBdbaHcwfarBdbkaxaPfhxavc;abfalcitfgHarBdbaHasBdlavaicdtfarBdbavc;abfalcefcsGglcitfgHazBdbaHarBdlaiaPfhialcefhlxdkdndnaPcsSmbamaPfaPc987fcefhmxekaocefhrao8SbbgPcFeGhHdndnaPcu9mmbarhoxekaocvfhoaHcFbGhHcrhPdninar8SbbgOcFbGaPtaHVhHaOcu9kmearcefhraPcrfgPc8J9hmbxdkkarcefhokaHce4cbaHceG9R7amfhmkdndnadcd9hmbabaDcetfgraz87ebarcdfas87ebarclfam87ebxekabaDcdtfgrazBdbarclfasBdbarcwfamBdbkavc;abfalcitfgramBdbarasBdlavaicdtfamBdbavc;abfalcefcsGglcitfgrazBdbaramBdlaicefhialcefhlxekdnarcpe0mbaxcefgOavaiaqarcsGfRbbgPcl49RcsGcdtfydbaPcz6gHEhravaiaP9RcsGcdtfydbaOaHfgsaPcsGgOEhPaOThOdndnadcd9hmbabaDcetfgzax87ebazcdfar87ebazclfaP87ebxekabaDcdtfgzaxBdbazclfarBdbazcwfaPBdbkavaicdtfaxBdbavc;abfalcitfgzarBdbazaxBdlavaicefgicsGcdtfarBdbavc;abfalcefcsGcitfgzaPBdbazarBdlavaiaHfcsGgicdtfaPBdbavc;abfalcdfcsGglcitfgraxBdbaraPBdlalcefhlaiaOfhiasaOfhxxekaxcbaoRbbgzEgAarc;:eSgrfhsazcsGhCazcl4hXdndnazcs0mbascefhOxekashOavaiaX9RcsGcdtfydbhskdndnaCmbaOcefhxxekaOhxavaiaz9RcsGcdtfydbhOkdndnarTmbaocefhrxekaocdfhrao8SbegHcFeGhPdnaHcu9kmbaocofhAaPcFbGhPcrhodninar8SbbgHcFbGaotaPVhPaHcu9kmearcefhraocrfgoc8J9hmbkaAhrxekarcefhrkaPce4cbaPceG9R7amfgmhAkdndnaXcsSmbarhPxekarcefhPar8SbbgocFeGhHdnaocu9kmbarcvfhsaHcFbGhHcrhodninaP8SbbgrcFbGaotaHVhHarcu9kmeaPcefhPaocrfgoc8J9hmbkashPxekaPcefhPkaHce4cbaHceG9R7amfgmhskdndnaCcsSmbaPhoxekaPcefhoaP8SbbgrcFeGhHdnarcu9kmbaPcvfhOaHcFbGhHcrhrdninao8SbbgPcFbGartaHVhHaPcu9kmeaocefhoarcrfgrc8J9hmbkaOhoxekaocefhokaHce4cbaHceG9R7amfgmhOkdndnadcd9hmbabaDcetfgraA87ebarcdfas87ebarclfaO87ebxekabaDcdtfgraABdbarclfasBdbarcwfaOBdbkavc;abfalcitfgrasBdbaraABdlavaicdtfaABdbavc;abfalcefcsGcitfgraOBdbarasBdlavaicefgicsGcdtfasBdbavc;abfalcdfcsGcitfgraABdbaraOBdlavaiazcz6aXcsSVfgicsGcdtfaOBdbaiaCTaCcsSVfhialcifhlkawcefhwalcsGhlaicsGhiaDcifgDae6mbkkcbc99aoaqSEhokavc;aef8Kjjjjbaok:llevu8Jjjjjbcz9Rhvc9:hodnaecvfal0mbcuhoaiRbbc;:eGc;qe9hmbav9cb83iwaicefhraialfc98fhwdnaeTmbdnadcdSmbcbhDindnaraw6mbc9:skarcefhoar8SbbglcFeGhidndnalcu9mmbaohrxekarcvfhraicFbGhicrhldninao8SbbgdcFbGaltaiVhiadcu9kmeaocefhoalcrfglc8J9hmbxdkkaocefhrkabaDcdtfaicd4cbaice4ceG9R7avcwfaiceGcdtVgoydbfglBdbaoalBdbaDcefgDae9hmbxdkkcbhDindnaraw6mbc9:skarcefhoar8SbbglcFeGhidndnalcu9mmbaohrxekarcvfhraicFbGhicrhldninao8SbbgdcFbGaltaiVhiadcu9kmeaocefhoalcrfglc8J9hmbxdkkaocefhrkabaDcetfaicd4cbaice4ceG9R7avcwfaiceGcdtVgoydbfgl87ebaoalBdbaDcefgDae9hmbkkcbc99arawSEhokaok:Lvoeue99dud99eud99dndnadcl9hmbaeTmeindndnabcdfgd8Sbb:Yab8Sbbgi:Ygl:l:tabcefgv8Sbbgo:Ygr:l:tgwJbb;:9cawawNJbbbbawawJbbbb9GgDEgq:mgkaqaicb9iEalMgwawNakaqaocb9iEarMgqaqNMM:r:vglNJbbbZJbbb:;aDEMgr:lJbbb9p9DTmbar:Ohixekcjjjj94hikadai86bbdndnaqalNJbbbZJbbb:;aqJbbbb9GEMgq:lJbbb9p9DTmbaq:Ohdxekcjjjj94hdkavad86bbdndnawalNJbbbZJbbb:;awJbbbb9GEMgw:lJbbb9p9DTmbaw:Ohdxekcjjjj94hdkabad86bbabclfhbaecufgembxdkkaeTmbindndnabclfgd8Ueb:Yab8Uebgi:Ygl:l:tabcdfgv8Uebgo:Ygr:l:tgwJb;:FSawawNJbbbbawawJbbbb9GgDEgq:mgkaqaicb9iEalMgwawNakaqaocb9iEarMgqaqNMM:r:vglNJbbbZJbbb:;aDEMgr:lJbbb9p9DTmbar:Ohixekcjjjj94hikadai87ebdndnaqalNJbbbZJbbb:;aqJbbbb9GEMgq:lJbbb9p9DTmbaq:Ohdxekcjjjj94hdkavad87ebdndnawalNJbbbZJbbb:;awJbbbb9GEMgw:lJbbb9p9DTmbaw:Ohdxekcjjjj94hdkabad87ebabcwfhbaecufgembkkk;siliui99iue99dnaeTmbcbhiabhlindndnJ;Zl81Zalcof8UebgvciV:Y:vgoal8Ueb:YNgrJb;:FSNJbbbZJbbb:;arJbbbb9GEMgw:lJbbb9p9DTmbaw:OhDxekcjjjj94hDkalclf8Uebhqalcdf8UebhkabavcefciGaiVcetfaD87ebdndnaoak:YNgwJb;:FSNJbbbZJbbb:;awJbbbb9GEMgx:lJbbb9p9DTmbax:Ohkxekcjjjj94hkkabavcdfciGaiVcetfak87ebdndnaoaq:YNgoJb;:FSNJbbbZJbbb:;aoJbbbb9GEMgx:lJbbb9p9DTmbax:Ohqxekcjjjj94hqkabavcufciGaiVcetfaq87ebdndnJbbjZararN:tawawN:taoaoN:tgrJbbbbarJbbbb9GE:rJb;:FSNJbbbZMgr:lJbbb9p9DTmbar:Ohqxekcjjjj94hqkabavciGaiVcetfaq87ebalcwfhlaiclfhiaecufgembkkk9mbdnadcd4ae2geTmbinababydbgdcwtcw91:Yadce91cjjj;8ifcjjj98G::NUdbabclfhbaecufgembkkk9teiucbcbydj1jjbgeabcifc98GfgbBdj1jjbdndnabZbcztgd9nmbcuhiabad9RcFFifcz4nbcuSmekaehikaik;LeeeudndnaeabVciGTmbabhixekdndnadcz9pmbabhixekabhiinaiaeydbBdbaiclfaeclfydbBdbaicwfaecwfydbBdbaicxfaecxfydbBdbaiczfhiaeczfheadc9Wfgdcs0mbkkadcl6mbinaiaeydbBdbaeclfheaiclfhiadc98fgdci0mbkkdnadTmbinaiaeRbb86bbaicefhiaecefheadcufgdmbkkabk;aeedudndnabciGTmbabhixekaecFeGc:b:c:ew2hldndnadcz9pmbabhixekabhiinaialBdbaicxfalBdbaicwfalBdbaiclfalBdbaiczfhiadc9Wfgdcs0mbkkadcl6mbinaialBdbaiclfhiadc98fgdci0mbkkdnadTmbinaiae86bbaicefhiadcufgdmbkkabkkkebcjwklz9Kbb",e="b9H79TebbbeKl9Gbb9Gvuuuuueu9Giuuub9Geueuikqbbebeedddilve9Weeeviebeoweuec:q;Aekr;leDo9TW9T9VV95dbH9F9F939H79T9F9J9H229F9Jt9VV7bb8A9TW79O9V9Wt9F9KW9J9V9KW9wWVtW949c919M9MWVbdY9TW79O9V9Wt9F9KW9J9V9KW69U9KW949c919M9MWVblE9TW79O9V9Wt9F9KW9J9V9KW69U9KW949tWG91W9U9JWbvL9TW79O9V9Wt9F9KW9J9V9KWS9P2tWV9p9JtboK9TW79O9V9Wt9F9KW9J9V9KWS9P2tWV9r919HtbrL9TW79O9V9Wt9F9KW9J9V9KWS9P2tWVT949Wbwl79IV9RbDq;t9tqlbzik9:evu8Jjjjjbcz9Rhbcbheincbhdcbhiinabcwfadfaicjuaead4ceGglE86bbaialfhiadcefgdcw9hmbkaec:q:yjjbfai86bbaecitc:q1jjbfab8Piw83ibaecefgecjd9hmbkk;h8JlHud97euo978Jjjjjbcj;kb9Rgv8Kjjjjbc9:hodnadcefal0mbcuhoaiRbbc:Ge9hmbavaialfgrad9Rad;8qbbcj;abad9UhoaicefhldnadTmbaoc;WFbGgocjdaocjd6EhwcbhDinaDae9pmeawaeaD9RaDawfae6Egqcsfgoc9WGgkci2hxakcethmaocl4cifcd4hPabaDad2fhscbhzdnincehHalhOcbhAdninaraO9RaP6miavcj;cbfaAak2fhCaOaPfhlcbhidnakc;ab6mbaral9Rc;Gb6mbcbhoinaCaofhidndndndndnaOaoco4fRbbgXciGPlbedibkaipxbbbbbbbbbbbbbbbbpklbxikaialpbblalpbbbgQclp:meaQpmbzeHdOiAlCvXoQrLgQcdp:meaQpmbzeHdOiAlCvXoQrLpxiiiiiiiiiiiiiiiip9ogLpxiiiiiiiiiiiiiiiip8JgQp5b9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibaKc:q:yjjbfpbbbgYaYpmbbbbbbbbbbbbbbbbaQp5e9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPaLaQp9spklbalclfaYpQbfaKc:q:yjjbfRbbfhlxdkaialpbbwalpbbbgQclp:meaQpmbzeHdOiAlCvXoQrLpxssssssssssssssssp9ogLpxssssssssssssssssp8JgQp5b9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibaKc:q:yjjbfpbbbgYaYpmbbbbbbbbbbbbbbbbaQp5e9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPaLaQp9spklbalcwfaYpQbfaKc:q:yjjbfRbbfhlxekaialpbbbpklbalczfhlkdndndndndnaXcd4ciGPlbedibkaipxbbbbbbbbbbbbbbbbpklzxikaialpbblalpbbbgQclp:meaQpmbzeHdOiAlCvXoQrLgQcdp:meaQpmbzeHdOiAlCvXoQrLpxiiiiiiiiiiiiiiiip9ogLpxiiiiiiiiiiiiiiiip8JgQp5b9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibaKc:q:yjjbfpbbbgYaYpmbbbbbbbbbbbbbbbbaQp5e9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPaLaQp9spklzalclfaYpQbfaKc:q:yjjbfRbbfhlxdkaialpbbwalpbbbgQclp:meaQpmbzeHdOiAlCvXoQrLpxssssssssssssssssp9ogLpxssssssssssssssssp8JgQp5b9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibaKc:q:yjjbfpbbbgYaYpmbbbbbbbbbbbbbbbbaQp5e9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPaLaQp9spklzalcwfaYpQbfaKc:q:yjjbfRbbfhlxekaialpbbbpklzalczfhlkdndndndndnaXcl4ciGPlbedibkaipxbbbbbbbbbbbbbbbbpklaxikaialpbblalpbbbgQclp:meaQpmbzeHdOiAlCvXoQrLgQcdp:meaQpmbzeHdOiAlCvXoQrLpxiiiiiiiiiiiiiiiip9ogLpxiiiiiiiiiiiiiiiip8JgQp5b9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibaKc:q:yjjbfpbbbgYaYpmbbbbbbbbbbbbbbbbaQp5e9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPaLaQp9spklaalclfaYpQbfaKc:q:yjjbfRbbfhlxdkaialpbbwalpbbbgQclp:meaQpmbzeHdOiAlCvXoQrLpxssssssssssssssssp9ogLpxssssssssssssssssp8JgQp5b9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibaKc:q:yjjbfpbbbgYaYpmbbbbbbbbbbbbbbbbaQp5e9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPaLaQp9spklaalcwfaYpQbfaKc:q:yjjbfRbbfhlxekaialpbbbpklaalczfhlkdndndndndnaXco4Plbedibkaipxbbbbbbbbbbbbbbbbpkl8WxikaialpbblalpbbbgQclp:meaQpmbzeHdOiAlCvXoQrLgQcdp:meaQpmbzeHdOiAlCvXoQrLpxiiiiiiiiiiiiiiiip9ogLpxiiiiiiiiiiiiiiiip8JgQp5b9cjF;8;4;W;G;ab9:9cU1:NgXcitc:q1jjbfpbibaXc:q:yjjbfpbbbgYaYpmbbbbbbbbbbbbbbbbaQp5e9cjF;8;4;W;G;ab9:9cU1:NgXcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPaLaQp9spkl8WalclfaYpQbfaXc:q:yjjbfRbbfhlxdkaialpbbwalpbbbgQclp:meaQpmbzeHdOiAlCvXoQrLpxssssssssssssssssp9ogLpxssssssssssssssssp8JgQp5b9cjF;8;4;W;G;ab9:9cU1:NgXcitc:q1jjbfpbibaXc:q:yjjbfpbbbgYaYpmbbbbbbbbbbbbbbbbaQp5e9cjF;8;4;W;G;ab9:9cU1:NgXcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPaLaQp9spkl8WalcwfaYpQbfaXc:q:yjjbfRbbfhlxekaialpbbbpkl8Walczfhlkaoc;abfhiaocjefak0meaihoaral9Rc;Fb0mbkkdndnaiak9pmbaici4hoinaral9RcK6mdaCaifhXdndndndndnaOaico4fRbbaocoG4ciGPlbedibkaXpxbbbbbbbbbbbbbbbbpklbxikaXalpbblalpbbbgQclp:meaQpmbzeHdOiAlCvXoQrLgQcdp:meaQpmbzeHdOiAlCvXoQrLpxiiiiiiiiiiiiiiiip9ogLpxiiiiiiiiiiiiiiiip8JgQp5b9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibaKc:q:yjjbfpbbbgYaYpmbbbbbbbbbbbbbbbbaQp5e9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPaLaQp9spklbalclfaYpQbfaKc:q:yjjbfRbbfhlxdkaXalpbbwalpbbbgQclp:meaQpmbzeHdOiAlCvXoQrLpxssssssssssssssssp9ogLpxssssssssssssssssp8JgQp5b9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibaKc:q:yjjbfpbbbgYaYpmbbbbbbbbbbbbbbbbaQp5e9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPaLaQp9spklbalcwfaYpQbfaKc:q:yjjbfRbbfhlxekaXalpbbbpklbalczfhlkaocdfhoaiczfgiak6mbkkalTmbaAci6hHalhOaAcefgohAaoclSmdxekkcbhlaHceGmdkdnakTmbavcjdfazfhiavazfpbdbhYcbhXinaiavcj;cbfaXfgopblbgLcep9TaLpxeeeeeeeeeeeeeeeegQp9op9Hp9rgLaoakfpblbg8Acep9Ta8AaQp9op9Hp9rg8ApmbzeHdOiAlCvXoQrLgEaoamfpblbg3cep9Ta3aQp9op9Hp9rg3aoaxfpblbg5cep9Ta5aQp9op9Hp9rg5pmbzeHdOiAlCvXoQrLg8EpmbezHdiOAlvCXorQLgQaQpmbedibedibedibediaYp9UgYp9AdbbaiadfgoaYaQaQpmlvorlvorlvorlvorp9UgYp9AdbbaoadfgoaYaQaQpmwDqkwDqkwDqkwDqkp9UgYp9AdbbaoadfgoaYaQaQpmxmPsxmPsxmPsxmPsp9UgYp9AdbbaoadfgoaYaEa8EpmwDKYqk8AExm35Ps8E8FgQaQpmbedibedibedibedip9UgYp9AdbbaoadfgoaYaQaQpmlvorlvorlvorlvorp9UgYp9AdbbaoadfgoaYaQaQpmwDqkwDqkwDqkwDqkp9UgYp9AdbbaoadfgoaYaQaQpmxmPsxmPsxmPsxmPsp9UgYp9AdbbaoadfgoaYaLa8ApmwKDYq8AkEx3m5P8Es8FgLa3a5pmwKDYq8AkEx3m5P8Es8Fg8ApmbezHdiOAlvCXorQLgQaQpmbedibedibedibedip9UgYp9AdbbaoadfgoaYaQaQpmlvorlvorlvorlvorp9UgYp9AdbbaoadfgoaYaQaQpmwDqkwDqkwDqkwDqkp9UgYp9AdbbaoadfgoaYaQaQpmxmPsxmPsxmPsxmPsp9UgYp9AdbbaoadfgoaYaLa8ApmwDKYqk8AExm35Ps8E8FgQaQpmbedibedibedibedip9UgYp9AdbbaoadfgoaYaQaQpmlvorlvorlvorlvorp9UgYp9AdbbaoadfgoaYaQaQpmwDqkwDqkwDqkwDqkp9UgYp9AdbbaoadfgoaYaQaQpmxmPsxmPsxmPsxmPsp9UgYp9AdbbaoadfhiaXczfgXak6mbkkazclfgzad6mbkasavcjdfaqad2;8qbbavavcjdfaqcufad2fad;8qbbaqaDfhDc9:hoalmexikkc9:hoxekcbc99aral9Radcaadca0ESEhokavcj;kbf8Kjjjjbaokwbz:bjjjbk;uzeHu8Jjjjjbc;ae9Rgv8Kjjjjbc9:hodnaeci9UgrcHfal0mbcuhoaiRbbgwc;WeGc;Ge9hmbawcsGgDce0mbavc;abfcFecje;8kbavcUf9cu83ibavc8Wf9cu83ibavcyf9cu83ibavcaf9cu83ibavcKf9cu83ibavczf9cu83ibav9cu83iwav9cu83ibaialfc9WfhqaicefgwarfhodnaeTmbcmcsaDceSEhkcbhxcbhmcbhDcbhicbhlindnaoaq9nmbc9:hoxikdndnawRbbgrc;Ve0mbavc;abfalarcl4cu7fcsGcitfgPydlhsaPydbhzdnarcsGgPak9pmbavaiarcu7fcsGcdtfydbaxaPEhraPThPdndnadcd9hmbabaDcetfgHaz87ebaHcdfas87ebaHclfar87ebxekabaDcdtfgHazBdbaHclfasBdbaHcwfarBdbkaxaPfhxavc;abfalcitfgHarBdbaHasBdlavaicdtfarBdbavc;abfalcefcsGglcitfgHazBdbaHarBdlaiaPfhialcefhlxdkdndnaPcsSmbamaPfaPc987fcefhmxekaocefhrao8SbbgPcFeGhHdndnaPcu9mmbarhoxekaocvfhoaHcFbGhHcrhPdninar8SbbgOcFbGaPtaHVhHaOcu9kmearcefhraPcrfgPc8J9hmbxdkkarcefhokaHce4cbaHceG9R7amfhmkdndnadcd9hmbabaDcetfgraz87ebarcdfas87ebarclfam87ebxekabaDcdtfgrazBdbarclfasBdbarcwfamBdbkavc;abfalcitfgramBdbarasBdlavaicdtfamBdbavc;abfalcefcsGglcitfgrazBdbaramBdlaicefhialcefhlxekdnarcpe0mbaxcefgOavaiaqarcsGfRbbgPcl49RcsGcdtfydbaPcz6gHEhravaiaP9RcsGcdtfydbaOaHfgsaPcsGgOEhPaOThOdndnadcd9hmbabaDcetfgzax87ebazcdfar87ebazclfaP87ebxekabaDcdtfgzaxBdbazclfarBdbazcwfaPBdbkavaicdtfaxBdbavc;abfalcitfgzarBdbazaxBdlavaicefgicsGcdtfarBdbavc;abfalcefcsGcitfgzaPBdbazarBdlavaiaHfcsGgicdtfaPBdbavc;abfalcdfcsGglcitfgraxBdbaraPBdlalcefhlaiaOfhiasaOfhxxekaxcbaoRbbgzEgAarc;:eSgrfhsazcsGhCazcl4hXdndnazcs0mbascefhOxekashOavaiaX9RcsGcdtfydbhskdndnaCmbaOcefhxxekaOhxavaiaz9RcsGcdtfydbhOkdndnarTmbaocefhrxekaocdfhrao8SbegHcFeGhPdnaHcu9kmbaocofhAaPcFbGhPcrhodninar8SbbgHcFbGaotaPVhPaHcu9kmearcefhraocrfgoc8J9hmbkaAhrxekarcefhrkaPce4cbaPceG9R7amfgmhAkdndnaXcsSmbarhPxekarcefhPar8SbbgocFeGhHdnaocu9kmbarcvfhsaHcFbGhHcrhodninaP8SbbgrcFbGaotaHVhHarcu9kmeaPcefhPaocrfgoc8J9hmbkashPxekaPcefhPkaHce4cbaHceG9R7amfgmhskdndnaCcsSmbaPhoxekaPcefhoaP8SbbgrcFeGhHdnarcu9kmbaPcvfhOaHcFbGhHcrhrdninao8SbbgPcFbGartaHVhHaPcu9kmeaocefhoarcrfgrc8J9hmbkaOhoxekaocefhokaHce4cbaHceG9R7amfgmhOkdndnadcd9hmbabaDcetfgraA87ebarcdfas87ebarclfaO87ebxekabaDcdtfgraABdbarclfasBdbarcwfaOBdbkavc;abfalcitfgrasBdbaraABdlavaicdtfaABdbavc;abfalcefcsGcitfgraOBdbarasBdlavaicefgicsGcdtfasBdbavc;abfalcdfcsGcitfgraABdbaraOBdlavaiazcz6aXcsSVfgicsGcdtfaOBdbaiaCTaCcsSVfhialcifhlkawcefhwalcsGhlaicsGhiaDcifgDae6mbkkcbc99aoaqSEhokavc;aef8Kjjjjbaok:llevu8Jjjjjbcz9Rhvc9:hodnaecvfal0mbcuhoaiRbbc;:eGc;qe9hmbav9cb83iwaicefhraialfc98fhwdnaeTmbdnadcdSmbcbhDindnaraw6mbc9:skarcefhoar8SbbglcFeGhidndnalcu9mmbaohrxekarcvfhraicFbGhicrhldninao8SbbgdcFbGaltaiVhiadcu9kmeaocefhoalcrfglc8J9hmbxdkkaocefhrkabaDcdtfaicd4cbaice4ceG9R7avcwfaiceGcdtVgoydbfglBdbaoalBdbaDcefgDae9hmbxdkkcbhDindnaraw6mbc9:skarcefhoar8SbbglcFeGhidndnalcu9mmbaohrxekarcvfhraicFbGhicrhldninao8SbbgdcFbGaltaiVhiadcu9kmeaocefhoalcrfglc8J9hmbxdkkaocefhrkabaDcetfaicd4cbaice4ceG9R7avcwfaiceGcdtVgoydbfgl87ebaoalBdbaDcefgDae9hmbkkcbc99arawSEhokaok:EPliuo97eue978Jjjjjbca9Rhidndnadcl9hmbdnaec98GglTmbcbhvabhdinadadpbbbgocKp:RecKp:Sep;6egraocwp:RecKp:Sep;6earp;Geaoczp:RecKp:Sep;6egwp;Gep;Kep;LegDpxbbbbbbbbbbbbbbbbp:2egqarpxbbbjbbbjbbbjbbbjgkp9op9rp;Kegrpxbb;:9cbb;:9cbb;:9cbb;:9cararp;MeaDaDp;Meawaqawakp9op9rp;Kegrarp;Mep;Kep;Kep;Jep;Negwp;Mepxbbn0bbn0bbn0bbn0gqp;KepxFbbbFbbbFbbbFbbbp9oaopxbbbFbbbFbbbFbbbFp9op9qarawp;Meaqp;Kecwp:RepxbFbbbFbbbFbbbFbbp9op9qaDawp;Meaqp;Keczp:RepxbbFbbbFbbbFbbbFbp9op9qpkbbadczfhdavclfgval6mbkkalae9pmeaiaeciGgvcdtgdVcbczad9R;8kbaiabalcdtfglad;8qbbdnavTmbaiaipblbgocKp:RecKp:Sep;6egraocwp:RecKp:Sep;6earp;Geaoczp:RecKp:Sep;6egwp;Gep;Kep;LegDpxbbbbbbbbbbbbbbbbp:2egqarpxbbbjbbbjbbbjbbbjgkp9op9rp;Kegrpxbb;:9cbb;:9cbb;:9cbb;:9cararp;MeaDaDp;Meawaqawakp9op9rp;Kegrarp;Mep;Kep;Kep;Jep;Negwp;Mepxbbn0bbn0bbn0bbn0gqp;KepxFbbbFbbbFbbbFbbbp9oaopxbbbFbbbFbbbFbbbFp9op9qarawp;Meaqp;Kecwp:RepxbFbbbFbbbFbbbFbbp9op9qaDawp;Meaqp;Keczp:RepxbbFbbbFbbbFbbbFbp9op9qpklbkalaiad;8qbbskdnaec98GgxTmbcbhvabhdinadczfglalpbbbgopxbbbbbbFFbbbbbbFFgkp9oadpbbbgDaopmlvorxmPsCXQL358E8FpxFubbFubbFubbFubbp9op;6eaDaopmbediwDqkzHOAKY8AEgoczp:Sep;6egrp;Geaoczp:Reczp:Sep;6egwp;Gep;Kep;Legopxb;:FSb;:FSb;:FSb;:FSawaopxbbbbbbbbbbbbbbbbp:2egqawpxbbbjbbbjbbbjbbbjgmp9op9rp;Kegwawp;Meaoaop;Mearaqaramp9op9rp;Kegoaop;Mep;Kep;Kep;Jep;Negrp;Mepxbbn0bbn0bbn0bbn0gqp;Keczp:Reawarp;Meaqp;KepxFFbbFFbbFFbbFFbbp9op9qgwaoarp;Meaqp;KepxFFbbFFbbFFbbFFbbp9ogopmwDKYqk8AExm35Ps8E8Fp9qpkbbadaDakp9oawaopmbezHdiOAlvCXorQLp9qpkbbadcafhdavclfgvax6mbkkaxae9pmbaiaeciGgvcitgdfcbcaad9R;8kbaiabaxcitfglad;8qbbdnavTmbaiaipblzgopxbbbbbbFFbbbbbbFFgkp9oaipblbgDaopmlvorxmPsCXQL358E8FpxFubbFubbFubbFubbp9op;6eaDaopmbediwDqkzHOAKY8AEgoczp:Sep;6egrp;Geaoczp:Reczp:Sep;6egwp;Gep;Kep;Legopxb;:FSb;:FSb;:FSb;:FSawaopxbbbbbbbbbbbbbbbbp:2egqawpxbbbjbbbjbbbjbbbjgmp9op9rp;Kegwawp;Meaoaop;Mearaqaramp9op9rp;Kegoaop;Mep;Kep;Kep;Jep;Negrp;Mepxbbn0bbn0bbn0bbn0gqp;Keczp:Reawarp;Meaqp;KepxFFbbFFbbFFbbFFbbp9op9qgwaoarp;Meaqp;KepxFFbbFFbbFFbbFFbbp9ogopmwDKYqk8AExm35Ps8E8Fp9qpklzaiaDakp9oawaopmbezHdiOAlvCXorQLp9qpklbkalaiad;8qbbkk;4wllue97euv978Jjjjjbc8W9Rhidnaec98GglTmbcbhvabhoinaiaopbbbgraoczfgwpbbbgDpmlvorxmPsCXQL358E8Fgqczp:Segkclp:RepklbaopxbbjZbbjZbbjZbbjZpx;Zl81Z;Zl81Z;Zl81Z;Zl81Zakpxibbbibbbibbbibbbp9qp;6ep;NegkaraDpmbediwDqkzHOAKY8AEgrczp:Reczp:Sep;6ep;MegDaDp;Meakarczp:Sep;6ep;Megxaxp;Meakaqczp:Reczp:Sep;6ep;Megqaqp;Mep;Kep;Kep;Lepxbbbbbbbbbbbbbbbbp:4ep;Jepxb;:FSb;:FSb;:FSb;:FSgkp;Mepxbbn0bbn0bbn0bbn0grp;KepxFFbbFFbbFFbbFFbbgmp9oaxakp;Mearp;Keczp:Rep9qgxaqakp;Mearp;Keczp:ReaDakp;Mearp;Keamp9op9qgkpmbezHdiOAlvCXorQLgrp5baipblbpEb:T:j83ibaocwfarp5eaipblbpEe:T:j83ibawaxakpmwDKYqk8AExm35Ps8E8Fgkp5baipblbpEd:T:j83ibaocKfakp5eaipblbpEi:T:j83ibaocafhoavclfgval6mbkkdnalae9pmbaiaeciGgvcitgofcbcaao9R;8kbaiabalcitfgwao;8qbbdnavTmbaiaipblbgraipblzgDpmlvorxmPsCXQL358E8Fgqczp:Segkclp:RepklaaipxbbjZbbjZbbjZbbjZpx;Zl81Z;Zl81Z;Zl81Z;Zl81Zakpxibbbibbbibbbibbbp9qp;6ep;NegkaraDpmbediwDqkzHOAKY8AEgrczp:Reczp:Sep;6ep;MegDaDp;Meakarczp:Sep;6ep;Megxaxp;Meakaqczp:Reczp:Sep;6ep;Megqaqp;Mep;Kep;Kep;Lepxbbbbbbbbbbbbbbbbp:4ep;Jepxb;:FSb;:FSb;:FSb;:FSgkp;Mepxbbn0bbn0bbn0bbn0grp;KepxFFbbFFbbFFbbFFbbgmp9oaxakp;Mearp;Keczp:Rep9qgxaqakp;Mearp;Keczp:ReaDakp;Mearp;Keamp9op9qgkpmbezHdiOAlvCXorQLgrp5baipblapEb:T:j83ibaiarp5eaipblapEe:T:j83iwaiaxakpmwDKYqk8AExm35Ps8E8Fgkp5baipblapEd:T:j83izaiakp5eaipblapEi:T:j83iKkawaiao;8qbbkk:Pddiue978Jjjjjbc;ab9Rhidnadcd4ae2glc98GgvTmbcbhdabheinaeaepbbbgocwp:Recwp:Sep;6eaocep:SepxbbjZbbjZbbjZbbjZp:UepxbbjFbbjFbbjFbbjFp9op;Mepkbbaeczfheadclfgdav6mbkkdnaval9pmbaialciGgdcdtgeVcbc;abae9R;8kbaiabavcdtfgvae;8qbbdnadTmbaiaipblbgocwp:Recwp:Sep;6eaocep:SepxbbjZbbjZbbjZbbjZp:UepxbbjFbbjFbbjFbbjFp9op;Mepklbkavaiae;8qbbkk9teiucbcbydj1jjbgeabcifc98GfgbBdj1jjbdndnabZbcztgd9nmbcuhiabad9RcFFifcz4nbcuSmekaehikaikkkebcjwklz9Tbb",t=new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,3,2,0,0,5,3,1,0,1,12,1,0,10,22,2,12,0,65,0,65,0,65,0,252,10,0,0,11,7,0,65,0,253,15,26,11]),n=new Uint8Array([32,0,65,2,1,106,34,33,3,128,11,4,13,64,6,253,10,7,15,116,127,5,8,12,40,16,19,54,20,9,27,255,113,17,42,67,24,23,146,148,18,14,22,45,70,69,56,114,101,21,25,63,75,136,108,28,118,29,73,115]);if(typeof WebAssembly!="object")return{supported:!1};var a=WebAssembly.validate(t)?e:s,i,o=WebAssembly.instantiate(l(a),{}).then(function(S){i=S.instance,i.exports.__wasm_call_ctors()});function l(S){for(var j=new Uint8Array(S.length),C=0;C<S.length;++C){var A=S.charCodeAt(C);j[C]=A>96?A-97:A>64?A-39:A+4}for(var D=0,C=0;C<S.length;++C)j[D++]=j[C]<60?n[j[C]]:(j[C]-60)*64+j[++C];return j.buffer.slice(0,D)}function c(S,j,C,A,D,M){var I=i.exports.sbrk,E=C+3&-4,_=I(E*A),P=I(D.length),L=new Uint8Array(i.exports.memory.buffer);L.set(D,P);var R=S(_,C,A,P,D.length);if(R==0&&M&&M(_,E,A),j.set(L.subarray(_,_+C*A)),I(_-I(0)),R!=0)throw new Error("Malformed buffer data: "+R)}var d={NONE:"",OCTAHEDRAL:"meshopt_decodeFilterOct",QUATERNION:"meshopt_decodeFilterQuat",EXPONENTIAL:"meshopt_decodeFilterExp"},m={ATTRIBUTES:"meshopt_decodeVertexBuffer",TRIANGLES:"meshopt_decodeIndexBuffer",INDICES:"meshopt_decodeIndexSequence"},p=[],f=0;function b(S){var j={object:new Worker(S),pending:0,requests:{}};return j.object.onmessage=function(C){var A=C.data;j.pending-=A.count,j.requests[A.id][A.action](A.value),delete j.requests[A.id]},j}function y(S){for(var j="var instance; var ready = WebAssembly.instantiate(new Uint8Array(["+new Uint8Array(l(a))+"]), {}).then(function(result) { instance = result.instance; instance.exports.__wasm_call_ctors(); });self.onmessage = workerProcess;"+c.toString()+k.toString(),C=new Blob([j],{type:"text/javascript"}),A=URL.createObjectURL(C),D=0;D<S;++D)p[D]=b(A);URL.revokeObjectURL(A)}function w(S,j,C,A,D){for(var M=p[0],I=1;I<p.length;++I)p[I].pending<M.pending&&(M=p[I]);return new Promise(function(E,_){var P=new Uint8Array(C),L=f++;M.pending+=S,M.requests[L]={resolve:E,reject:_},M.object.postMessage({id:L,count:S,size:j,source:P,mode:A,filter:D},[P.buffer])})}function k(S){o.then(function(){var j=S.data;try{var C=new Uint8Array(j.count*j.size);c(i.exports[j.mode],C,j.count,j.size,j.source,i.exports[j.filter]),self.postMessage({id:j.id,count:j.count,action:"resolve",value:C},[C.buffer])}catch(A){self.postMessage({id:j.id,count:j.count,action:"reject",value:A})}})}return{ready:o,supported:!0,useWorkers:function(S){y(S)},decodeVertexBuffer:function(S,j,C,A,D){c(i.exports.meshopt_decodeVertexBuffer,S,j,C,A,i.exports[d[D]])},decodeIndexBuffer:function(S,j,C,A){c(i.exports.meshopt_decodeIndexBuffer,S,j,C,A)},decodeIndexSequence:function(S,j,C,A){c(i.exports.meshopt_decodeIndexSequence,S,j,C,A)},decodeGltfBuffer:function(S,j,C,A,D,M){c(i.exports[m[D]],S,j,C,A,i.exports[d[M]])},decodeGltfBufferAsync:function(S,j,C,A,D){return p.length>0?w(S,j,C,m[A],d[D]):o.then(function(){var M=new Uint8Array(S*j);return c(i.exports[m[A]],M,S,j,C,i.exports[d[D]]),M})}}})();function aj(s){const e=new Map,t=new Map,n=s.clone();return VA(s,n,function(a,i){e.set(i,a),t.set(a,i)}),n.traverse(function(a){if(!a.isSkinnedMesh)return;const i=a,o=e.get(a),l=o.skeleton.bones;i.skeleton=o.skeleton.clone(),i.bindMatrix.copy(o.bindMatrix),i.skeleton.bones=l.map(function(c){return t.get(c)}),i.bind(i.skeleton,i.bindMatrix)}),n}function VA(s,e,t){t(s,e);for(let n=0;n<s.children.length;n++)VA(s.children[n],e.children[n],t)}const Ba={scout:{icon:"🔍",color:4890367,description:"Explores and searches codebase"},builder:{icon:"🔨",color:16752202,description:"Creates and builds features"},debugger:{icon:"🐛",color:16730698,description:"Finds and fixes bugs"},architect:{icon:"📐",color:10373887,description:"Plans and designs systems"},warrior:{icon:"⚔️",color:16730782,description:"Tackles tough problems"},support:{icon:"💚",color:4915102,description:"Helps and assists others"},boss:{icon:"👑",color:16766720,description:"Manages and delegates to subordinates"}},mx=["Alex","Sam","Jordan","Taylor","Casey","Morgan","Riley","Quinn","Avery","Blake","Cameron","Drew","Emery","Finley","Harper","Jamie","Kai","Logan","Max","Nico","Parker","Reese","Sage","Sky"],Ho=mx,ec={scout:"character-male-a.glb",builder:"character-male-b.glb",debugger:"character-female-a.glb",architect:"character-male-c.glb",warrior:"character-female-b.glb",support:"character-female-c.glb",boss:"character-male-c.glb"},Uo=[{id:"scout",model:"character-male-a.glb",name:"Explorer",gender:"Male"},{id:"builder",model:"character-male-b.glb",name:"Crafter",gender:"Male"},{id:"architect",model:"character-male-c.glb",name:"Planner",gender:"Male"},{id:"debugger",model:"character-female-a.glb",name:"Analyst",gender:"Female"},{id:"warrior",model:"character-female-b.glb",name:"Fighter",gender:"Female"},{id:"support",model:"character-female-c.glb",name:"Healer",gender:"Female"}],ui=[{file:"character-male-a.glb",name:"Male A (Explorer)",gender:"Male"},{file:"character-male-b.glb",name:"Male B (Crafter)",gender:"Male"},{file:"character-male-c.glb",name:"Male C (Planner)",gender:"Male"},{file:"character-male-d.glb",name:"Male D",gender:"Male"},{file:"character-male-e.glb",name:"Male E",gender:"Male"},{file:"character-male-f.glb",name:"Male F",gender:"Male"},{file:"character-female-a.glb",name:"Female A (Analyst)",gender:"Female"},{file:"character-female-b.glb",name:"Female B (Fighter)",gender:"Female"},{file:"character-female-c.glb",name:"Female C (Healer)",gender:"Female"},{file:"character-female-d.glb",name:"Female D",gender:"Female"},{file:"character-female-e.glb",name:"Female E",gender:"Female"},{file:"character-female-f.glb",name:"Female F",gender:"Female"}],QL=3,tc=5,JL=1e3,mi=1.2;class eO{constructor(){W(this,"models",new Map);W(this,"customModels",new Map);W(this,"loaded",!1);W(this,"loadingPromise",null);W(this,"loader");W(this,"dracoLoader");W(this,"loadingCustomModels",new Map);this.loader=new dx,this.dracoLoader=new hx,this.dracoLoader.setDecoderPath("https://www.gstatic.com/draco/versioned/decoders/1.5.7/"),this.loader.setDRACOLoader(this.dracoLoader),this.loader.setMeshoptDecoder(px)}get isLoaded(){return this.loaded}async loadAll(){if(this.loaded){console.log("[CharacterLoader] Already loaded, skipping");return}if(this.loadingPromise)return console.log("[CharacterLoader] Already loading, waiting for existing promise"),this.loadingPromise;const e=[...new Set([...Object.values(ec),...ui.map(t=>t.file)])];return console.log(`[CharacterLoader] Starting to load ${e.length} models`),this.loadingPromise=Promise.all(e.map(t=>this.loadModel(t))).then(()=>{this.loaded=!0,console.log(`[CharacterLoader] All models loaded. Cache size: ${this.models.size}`)}),this.loadingPromise}loadModel(e){return new Promise(t=>{const n=`/assets/characters/${e}`;console.log(`[CharacterLoader] Loading model: ${n}`),this.loader.load(n,a=>{console.log(`[CharacterLoader] Successfully loaded: ${e}`);const i=this.prepareModel(a.scene);this.models.set(e,{scene:i,animations:a.animations}),t()},a=>{},a=>{console.error(`[CharacterLoader] Failed to load ${e}:`,a),t()})})}prepareModel(e){return e.scale.setScalar(1),e.position.set(0,0,0),e.rotation.set(0,0,0),e.visible=!1,e.traverse(t=>{if(t instanceof De&&(t.castShadow=!0,t.receiveShadow=!0,t.material)){const n=t.material;n.map&&(n.map.colorSpace=Va),n.isMeshStandardMaterial&&(n.roughness=n.roughness??.6,n.metalness=n.metalness??0,n.envMapIntensity=.8,n.needsUpdate=!0)}}),e}clone(e){const t=ec[e];return this.cloneByModelFile(t)}cloneByModelFile(e){const t=this.models.get(e);if(!t)return console.warn(`[CharacterLoader] Model not found: ${e}`),null;const n=aj(t.scene);return n.visible=!0,n.position.set(0,0,0),n.rotation.set(0,0,0),n.traverse(a=>{a.visible=!0,a instanceof De&&a.material&&(Array.isArray(a.material)?a.material=a.material.map(i=>i.clone()):a.material=a.material.clone())}),{mesh:n,animations:t.animations}}getAnimations(e){const t=ec[e],n=this.models.get(t);return(n==null?void 0:n.animations)??null}hasModel(e){const t=ec[e];return this.models.has(t)}async loadCustomModel(e){if(this.customModels.has(e))return;const t=this.loadingCustomModels.get(e);if(t)return t;const n=new Promise(a=>{this.loader.load(hd(st(`/api/custom-models/${e}`)),i=>{const o=this.prepareModel(i.scene);this.customModels.set(e,{scene:o,animations:i.animations}),console.log(`[CharacterLoader] Loaded custom model for class: ${e} (${i.animations.length} animations)`),a()},void 0,i=>{console.error(`[CharacterLoader] Failed to load custom model for ${e}:`,i),a()})});this.loadingCustomModels.set(e,n);try{await n}finally{this.loadingCustomModels.delete(e)}}hasCustomModel(e){return this.customModels.has(e)}cloneCustomModel(e){const t=this.customModels.get(e);if(!t)return null;const n=aj(t.scene);return n.visible=!0,n.position.set(0,0,0),n.rotation.set(0,0,0),n.traverse(a=>{a.visible=!0,a instanceof De&&a.material&&(Array.isArray(a.material)?a.material=a.material.map(i=>i.clone()):a.material=a.material.clone())}),{mesh:n,animations:t.animations}}getCustomModelAnimations(e){const t=this.customModels.get(e);return(t==null?void 0:t.animations)??null}unloadCustomModel(e){const t=this.customModels.get(e);t&&(this.disposeCachedModel(t),this.customModels.delete(e),console.log(`[CharacterLoader] Unloaded custom model for class: ${e}`))}disposeCachedModel(e){e.scene.traverse(t=>{var n;t instanceof De&&((n=t.geometry)==null||n.dispose(),Array.isArray(t.material)?t.material.forEach(a=>this.disposeMaterial(a)):t.material&&this.disposeMaterial(t.material))})}disposeMaterial(e){var t,n,a,i,o,l,c,d,m,p,f;(e instanceof rt||e instanceof We||e instanceof HD)&&((t=e.map)==null||t.dispose(),"normalMap"in e&&((n=e.normalMap)==null||n.dispose()),"roughnessMap"in e&&((a=e.roughnessMap)==null||a.dispose()),"metalnessMap"in e&&((i=e.metalnessMap)==null||i.dispose()),"emissiveMap"in e&&((o=e.emissiveMap)==null||o.dispose()),"aoMap"in e&&((l=e.aoMap)==null||l.dispose()),"lightMap"in e&&((c=e.lightMap)==null||c.dispose()),"bumpMap"in e&&((d=e.bumpMap)==null||d.dispose()),"displacementMap"in e&&((m=e.displacementMap)==null||m.dispose()),"alphaMap"in e&&((p=e.alphaMap)==null||p.dispose()),"envMap"in e&&((f=e.envMap)==null||f.dispose())),e.dispose()}dispose(){for(const[e,t]of this.models)this.disposeCachedModel(t),console.log(`[CharacterLoader] Disposed model template: ${e}`);this.models.clear();for(const[e,t]of this.customModels)this.disposeCachedModel(t),console.log(`[CharacterLoader] Disposed custom model: ${e}`);this.customModels.clear(),this.dracoLoader.dispose(),this.loaded=!1,this.loadingPromise=null,this.loadingCustomModels.clear(),console.log("[CharacterLoader] All model caches disposed")}getCacheStats(){return{builtInModels:this.models.size,customModels:this.customModels.size,modelNames:Array.from(this.models.keys()),customModelIds:Array.from(this.customModels.keys())}}}const tO="character-male-a.glb";class nO{constructor(e){W(this,"customClasses",new Map);this.characterLoader=e}setCustomClasses(e){this.customClasses=e}getClassConfig(e){const t=Ba[e];if(t)return t;const n=this.customClasses.get(e);if(n){const a=parseInt(n.color.replace("#",""),16);return{icon:n.icon,color:isNaN(a)?8947848:a,description:n.description}}return{icon:"❓",color:8947848,description:"Unknown class"}}getModelInfo(e){const t=ec[e];if(t)return{file:t,isCustomModel:!1};const n=this.customClasses.get(e);if(n){if(n.customModelPath)return{file:n.customModelPath,isCustomModel:!0,customClassId:n.id,scale:n.modelScale,offset:n.modelOffset};if(n.model)return{file:n.model,isCustomModel:!1,scale:n.modelScale,offset:n.modelOffset}}return{file:tO,isCustomModel:!1}}createCharacterBody(e,t){const n=this.getModelInfo(e.class);let a=null;if(n.isCustomModel&&n.customClassId&&(a=this.characterLoader.cloneCustomModel(n.customClassId)),a||(a=this.characterLoader.cloneByModelFile(n.file)),a){a.mesh.name="characterBody";const c=n.scale??1;a.mesh.userData.customModelScale=c,a.mesh.userData.isCustomModel=n.isCustomModel,n.offset&&(n.offset.x!==0||n.offset.y!==0||n.offset.z!==0)&&a.mesh.position.set(n.offset.x,n.offset.z,n.offset.y);const d=this.customClasses.get(e.class);d!=null&&d.animationMapping&&(a.mesh.userData.animationMapping=d.animationMapping);const m=new Uu(a.mesh),p=new Map;for(const f of a.animations){const b=f.name.toLowerCase();p.set(b,f),p.set(f.name,f)}return{body:a.mesh,mixer:m,animations:p}}const i=new Xb(.5,1,4,16),o=new rt({color:t,roughness:.4,metalness:.3}),l=new De(i,o);return l.position.y=1,l.castShadow=!0,l.receiveShadow=!0,l.name="characterBody",{body:l,mixer:null,animations:new Map}}calculateModelHeight(e,t){return t?2:1.5}upgradeToCharacterModel(e,t){const n=e.getObjectByName("characterBody");if(!(n instanceof De)||!(n.geometry instanceof Xb))return null;const a=this.characterLoader.clone(t.class);if(!a)return null;e.remove(n),n.geometry.dispose(),n.material.dispose(),a.mesh.name="characterBody",e.add(a.mesh);const i=new Uu(a.mesh),o=new Map;for(const l of a.animations){const c=l.name.toLowerCase();o.set(c,l)}return{group:e,mixer:i,animations:o,currentAction:null}}replaceAgentModel(e,t){const{group:n}=e,a=this.getModelInfo(t.class);let i=null;if(a.isCustomModel&&a.customClassId&&(i=this.characterLoader.cloneCustomModel(a.customClassId)),i||(i=this.characterLoader.cloneByModelFile(a.file)),!i)return console.warn(`[ModelLoader] Could not load model for class ${t.class}, keeping current model`),n.userData.agentClass=t.class,null;const o=n.getObjectByName("characterBody");o&&(n.remove(o),o.traverse(p=>{var f;(p instanceof De||p instanceof Vb)&&((f=p.geometry)==null||f.dispose(),Array.isArray(p.material)?p.material.forEach(b=>this.disposeMaterial(b)):p.material&&this.disposeMaterial(p.material))})),e.mixer&&(e.mixer.stopAllAction(),e.mixer.uncacheRoot(n)),i.mesh.name="characterBody";const l=a.scale??1;i.mesh.userData.customModelScale=l,i.mesh.userData.isCustomModel=a.isCustomModel,a.offset&&(a.offset.x!==0||a.offset.y!==0||a.offset.z!==0)&&i.mesh.position.set(a.offset.x,a.offset.z,a.offset.y);const c=this.customClasses.get(t.class);c!=null&&c.animationMapping&&(i.mesh.userData.animationMapping=c.animationMapping),n.add(i.mesh);const d=new Uu(i.mesh),m=new Map;for(const p of i.animations){const f=p.name.toLowerCase();m.set(f,p),m.set(p.name,p)}return n.userData.agentClass=t.class,console.log(`[ModelLoader] Agent ${t.name} model updated to ${a.file}`),{group:n,mixer:d,animations:m,currentAction:null}}disposeAgentMesh(e){for(e.mixer&&(e.mixer.stopAllAction(),e.mixer.uncacheRoot(e.group)),e.group.traverse(t=>{var n,a;t instanceof De?((n=t.geometry)==null||n.dispose(),Array.isArray(t.material)?t.material.forEach(i=>this.disposeMaterial(i)):t.material&&this.disposeMaterial(t.material)):t instanceof Hn?this.disposeMaterial(t.material):t instanceof Vb&&((a=t.geometry)==null||a.dispose(),Array.isArray(t.material)?t.material.forEach(i=>this.disposeMaterial(i)):t.material&&this.disposeMaterial(t.material))});e.group.children.length>0;)e.group.remove(e.group.children[0]);e.animations.clear()}disposeMaterial(e){var t,n,a,i,o;(e instanceof rt||e instanceof We||e instanceof Yn)&&((t=e.map)==null||t.dispose(),"normalMap"in e&&((n=e.normalMap)==null||n.dispose()),"roughnessMap"in e&&((a=e.roughnessMap)==null||a.dispose()),"metalnessMap"in e&&((i=e.metalnessMap)==null||i.dispose()),"emissiveMap"in e&&((o=e.emissiveMap)==null||o.dispose())),e.dispose()}}class sO{createAnimationSetup(e,t,n){n!=null&&n.animationMapping&&(e.userData.animationMapping=n.animationMapping);const a=new Uu(e),i=new Map;for(const o of t)i.set(o.name.toLowerCase(),o),i.set(o.name,o);return{mixer:a,animations:i}}getIdleTimerColor(e){const a=Math.min(e/60,60)/60,i=Math.pow(a,.7),o=120*(1-i),l=80+20*i,c=60-10*i,d=`hsl(${Math.round(o)}, ${Math.round(l)}%, ${Math.round(c)}%)`;return{text:d,border:d}}formatIdleTimeShort(e){if(e<60)return`${e}s`;const t=Math.floor(e/60);if(t<60){const o=e%60;return o>0?`${t}m ${o}s`:`${t}m`}const n=Math.floor(t/60),a=t%60;return n<24?a>0?`${n}h ${a}m`:`${n}h`:`${Math.floor(n/24)}d`}}const ij={idle:4915102,working:4890367,waiting:16752202,waiting_permission:16763904,error:16730698,orphaned:16711935,default:8947848};function KA(s){if(s.contextStats)return 100-s.contextStats.usedPercent;const e=s.contextUsed||0,t=s.contextLimit||2e5;return Math.max(0,t-e)/t*100}class aO{constructor(e){W(this,"idleTimerCanvas",null);W(this,"idleTimerCtx",null);W(this,"manaBarCanvas",null);W(this,"manaBarCtx",null);this.animConfig=e}getStatusColor(e){return ij[e]??ij.default}createSelectionRing(e,t=!1){const n=t?1.5:1,a=new Xo(.8*n,.95*n,32),i=new We({color:e,side:ws,transparent:!0,opacity:0,depthTest:!1}),o=new De(a,i);return o.rotation.x=-Math.PI/2,o.position.y=.05,o.renderOrder=999,o.name="selectionRing",o}createStatusBarSprite(e,t,n,a,i=2){const o=document.createElement("canvas"),l=o.getContext("2d");o.width=4096,o.height=2560,this.drawStatusBar(l,o.width,o.height,e,t,n,a);const c=new Jn(o);c.minFilter=Hu,c.magFilter=In,c.generateMipmaps=!0,c.anisotropy=16,c.needsUpdate=!0;const d=new Yn({map:c,transparent:!0,depthTest:!1}),m=new Hn(d),p=a?.8:.5;m.position.y=i+p;const f=a?2:1.6,b=o.height/o.width;return m.scale.set(f,f*b,1),m.name="statusBar",m.userData.modelHeight=i,m.userData.baseIndicatorScale=f,m.userData.aspectRatio=b,m}createNameLabelSprite(e,t,n,a){const i=document.createElement("canvas"),o=i.getContext("2d");i.width=4096,i.height=1024,this.drawNameLabel(o,i.width,i.height,e,t,a);const l=new Jn(i);l.minFilter=Hu,l.magFilter=In,l.generateMipmaps=!0,l.anisotropy=16,l.needsUpdate=!0;const c=new Yn({map:l,transparent:!0,depthTest:!1}),d=new Hn(c);d.position.y=n?-.74:-.56;const m=n?1.5:1.25,p=i.height/i.width;return d.scale.set(m,m*p,1),d.name="nameLabelSprite",d.userData.baseIndicatorScale=m,d.userData.aspectRatio=p,d}drawNameLabel(e,t,n,a,i,o){e.clearRect(0,0,t,n);const l=`#${i.toString(16).padStart(6,"0")}`;let c=800;const d=300,m=o==="claude"||o==="codex",p=m?c*.42:0,f=m?c*.3:0,b=t-400-(m?p+f:0);e.font=`bold ${c}px Arial`;let y=e.measureText(a).width;for(;y>b&&c>d;)c-=40,e.font=`bold ${c}px Arial`,y=e.measureText(a).width;const w=m?c*.42:0,k=m?c*.3:0,S=w+k,j=y+S,C=t/2+S/2;if(e.textAlign="center",e.textBaseline="middle",e.shadowColor="rgba(0, 0, 0, 0.9)",e.shadowBlur=c*.12,e.shadowOffsetX=c*.04,e.shadowOffsetY=c*.04,e.strokeStyle="#000",e.lineWidth=c*.14,e.lineJoin="round",e.strokeText(a,C,n/2),e.shadowColor="transparent",e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0,m){const A=t/2-j/2+w/2,D=n/2,M=o==="codex"?"#4a9eff":"#ff9e4a";e.beginPath(),e.arc(A,D,w/2,0,Math.PI*2),e.fillStyle=M,e.fill(),e.strokeStyle="rgba(255, 255, 255, 0.9)",e.lineWidth=Math.max(4,w*.1),e.stroke()}e.fillStyle=l,e.fillText(a,C,n/2)}drawStatusBar(e,t,n,a,i,o,l){e.clearRect(0,0,t,n);const c=t/2048;let d=80*c;l&&(e.font=`${400*c}px serif`,e.textAlign="center",e.textBaseline="top",e.fillText("👑",t/2,d),d+=440*c);const m=200*c,p=1350*c,f=(t-p)/2,b=d,y=200*c,w=f+y/2+30*c,k=b+m/2;let S;switch(i){case"working":S="#4a9eff";break;case"orphaned":S="#c060e0";break;case"error":S="#e05050";break;case"waiting":case"waiting_permission":S="#e0a030";break;default:S="#40c090"}e.beginPath(),e.arc(w,k,y/2,0,Math.PI*2),e.fillStyle=S,e.shadowColor=S,e.shadowBlur=20*c,e.fill(),e.shadowBlur=0,e.strokeStyle="rgba(0, 0, 0, 0.4)",e.lineWidth=4*c,e.stroke();const j=f+y+60*c,C=p-y-90*c,A=m-80*c,D=b+40*c,M=30*c;e.fillStyle="#0d0d14",e.beginPath(),e.roundRect(j,D,C,A,M),e.fill(),e.strokeStyle="rgba(80, 90, 110, 0.5)",e.lineWidth=4*c,e.stroke();const I=Math.max(0,Math.min(100,a))/100,E=8*c,_=Math.max(0,(C-E*2)*I);if(_>0){let z;I>.5?z="#00c896":I>.2?z="#e8a020":z="#e84040",e.fillStyle=z,e.beginPath(),e.roundRect(j+E,D+E,_,A-E*2,M-E),e.fill(),e.shadowColor=z,e.shadowBlur=12*c,e.fill(),e.shadowBlur=0}const P=`${Math.round(I*100)}%`;e.font=`bold ${180*c}px "Segoe UI", Arial, sans-serif`,e.textAlign="center",e.textBaseline="middle";const L=j+C/2,R=D+A/2;if(e.shadowColor="rgba(0, 0, 0, 0.8)",e.shadowBlur=8*c,e.shadowOffsetX=2*c,e.shadowOffsetY=2*c,e.strokeStyle="rgba(0, 0, 0, 0.9)",e.lineWidth=24*c,e.lineJoin="round",e.strokeText(P,L,R),e.shadowColor="transparent",e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0,e.fillStyle="rgba(255, 255, 255, 0.95)",e.fillText(P,L,R),d+=m+60*c,i==="idle"&&o>0){const z=Math.floor((Date.now()-o)/1e3),F=this.animConfig.formatIdleTimeShort(z),$=this.animConfig.getIdleTimerColor(z);e.font=`bold ${140*c}px Arial`;const G=e.measureText(`⏱ ${F}`).width+140*c,K=180*c,Z=(t-G)/2,B=d;e.fillStyle="rgba(0, 0, 0, 0.85)",e.beginPath(),e.roundRect(Z,B,G,K,28*c),e.fill(),e.strokeStyle=$.border,e.lineWidth=12*c,e.stroke(),e.textAlign="center",e.textBaseline="middle",e.strokeStyle="#000",e.lineWidth=14*c,e.strokeText(`⏱ ${F}`,t/2,B+K/2),e.fillStyle=$.text,e.fillText(`⏱ ${F}`,t/2,B+K/2)}}createCombinedUISprite(e,t,n,a,i,o){const l=document.createElement("canvas"),c=l.getContext("2d");l.width=4096,l.height=2048,this.drawCombinedUI(c,l.width,l.height,e,t,n,a,i,o);const d=new Jn(l);d.minFilter=Hu,d.magFilter=In,d.generateMipmaps=!0,d.anisotropy=16,d.needsUpdate=!0;const m=new Yn({map:d,transparent:!0,depthTest:!1}),p=new Hn(m);p.position.y=o?3.2:2.2;const f=o?3:2.4,b=l.height/l.width;return p.scale.set(f,f*b,1),p.name="combinedUI",p.userData.baseIndicatorScale=f,p.userData.aspectRatio=b,p}drawCombinedUI(e,t,n,a,i,o,l,c,d){e.clearRect(0,0,t,n);const m=`#${i.toString(16).padStart(6,"0")}`,p=t/2048;let f=80*p;d&&(e.font=`${288*p}px serif`,e.textAlign="center",e.textBaseline="top",e.fillText("👑",t/2,f),f+=320*p);const b=224*p,y=t-240*p;e.font=`bold ${b}px Arial`;let w=a;if(e.measureText(w).width>y){for(;w.length>3&&e.measureText(w+"...").width>y;)w=w.slice(0,-1);w+="..."}e.textAlign="center",e.textBaseline="middle";const S=f+b/2;e.strokeStyle="#000",e.lineWidth=24*p,e.lineJoin="round",e.strokeText(w,t/2,S),e.fillStyle=m,e.fillText(w,t/2,S),f+=b+64*p;const j=200*p,C=1350*p,A=(t-C)/2,D=f,M=176*p,I=A+M/2+24*p,E=D+j/2;let _;switch(l){case"working":_="#00a8ff";break;case"orphaned":_="#e040ff";break;case"error":_="#ff3030";break;case"waiting":case"waiting_permission":_="#ffc000";break;default:_="#00e090"}e.beginPath(),e.arc(I,E,M/2,0,Math.PI*2),e.fillStyle=_,e.fill(),e.shadowColor=_,e.shadowBlur=32*p,e.fill(),e.shadowBlur=0,e.strokeStyle="#000",e.lineWidth=12*p,e.stroke();const P=A+M+64*p,L=C-M-88*p,R=j-48*p,z=D+24*p;e.fillStyle="#000",e.beginPath(),e.roundRect(P,z,L,R,24*p),e.fill(),e.strokeStyle="#5a8a8a",e.lineWidth=8*p,e.stroke();const F=Math.max(0,Math.min(100,o))/100,$=16*p,U=Math.max(0,(L-$*2)*F);if(U>0){let B;F>.5?B="#00ff88":F>.2?B="#ffaa00":B="#ff3366",e.fillStyle=B,e.beginPath(),e.roundRect(P+$,z+$,U,R-$*2,16*p),e.fill(),e.shadowColor=B,e.shadowBlur=32*p,e.fill(),e.shadowBlur=0}const G=`${Math.round(F*100)}%`;e.font=`bold ${128*p}px Arial`,e.textAlign="center",e.textBaseline="middle";const K=P+L/2,Z=z+R/2;if(e.strokeStyle="#000",e.lineWidth=28*p,e.lineJoin="round",e.strokeText(G,K,Z),e.fillStyle="#fff",e.shadowColor="#000",e.shadowBlur=8*p,e.fillText(G,K,Z),e.shadowBlur=0,f+=j+48*p,l==="idle"&&c>0){const B=Math.floor((Date.now()-c)/1e3),ee=this.animConfig.formatIdleTimeShort(B),se=this.animConfig.getIdleTimerColor(B);e.font=`bold ${160*p}px Arial`;const Y=e.measureText(`⏱ ${ee}`).width+160*p,Q=216*p,ie=(t-Y)/2,J=f;e.fillStyle="rgba(0, 0, 0, 0.85)",e.beginPath(),e.roundRect(ie,J,Y,Q,32*p),e.fill(),e.strokeStyle=se.border,e.lineWidth=12*p,e.stroke(),e.textAlign="center",e.textBaseline="middle",e.strokeStyle="#000",e.lineWidth=16*p,e.strokeText(`⏱ ${ee}`,t/2,J+Q/2),e.fillStyle=se.text,e.fillText(`⏱ ${ee}`,t/2,J+Q/2)}}createNameLabel(e,t,n=!1){const a=document.createElement("canvas"),i=a.getContext("2d"),o=72,l=32,c=100,d=256;a.width=2048,a.height=d,i.font=`bold ${o}px Arial`;const m=i.measureText(e).width,p=512,f=m+l*2+16;a.width=Math.max(p,f),i.clearRect(0,0,a.width,a.height),i.font=`bold ${o}px Arial`;const b=m+l*2,y=(a.width-b)/2,w=(a.height-c)/2;i.fillStyle="rgba(0, 0, 0, 0.8)",i.beginPath(),i.roundRect(y,w,b,c,12),i.fill(),i.fillStyle=`#${t.toString(16).padStart(6,"0")}`,i.textAlign="center",i.textBaseline="middle",i.fillText(e,a.width/2,a.height/2);const k=new Jn(a);k.minFilter=In,k.magFilter=In,k.needsUpdate=!0;const S=new Yn({map:k,transparent:!0,depthTest:!1}),j=new Hn(S);j.position.y=n?-.2:-.3;const C=n?.75:.6,D=(n?1.5:1.2)*(a.width/512);return j.scale.set(D,C,1),j.name="nameLabel",j.userData.aspectRatio=a.width/a.height,j}createManaBar(e,t,n=!1){const a=document.createElement("canvas"),i=a.getContext("2d");a.width=400,a.height=64,this.drawManaBar(i,a.width,a.height,e,t);const o=new Jn(a);o.minFilter=In,o.magFilter=In,o.needsUpdate=!0;const l=new Yn({map:o,transparent:!0,depthTest:!1}),c=new Hn(l);return c.position.y=n?3:2,c.scale.set(n?1.4:1.1,n?.22:.18,1),c.name="manaBar",c}drawManaBar(e,t,n,a,i){const o=Math.max(0,Math.min(100,a))/100;e.clearRect(0,0,t,n);const l=n/32,c=20*l,d=6*l,m=c+d+4*l,p=6*l,f=t-m-10*l,b=n-12*l,y=6*l;let w;switch(i){case"working":w="#4a9eff";break;case"orphaned":w="#ff00ff";break;case"error":w="#ff4a4a";break;case"waiting":case"waiting_permission":w="#ffcc00";break;default:w="#4aff9e"}const k=c/2+4*l,S=n/2;e.beginPath(),e.arc(k,S,c/2,0,Math.PI*2),e.fillStyle=w,e.fill(),e.shadowColor=w,e.shadowBlur=8*l,e.fill(),e.shadowBlur=0,e.strokeStyle="#000000",e.lineWidth=2*l,e.stroke(),e.fillStyle="#000000",e.beginPath(),e.roundRect(m,p,f,b,y),e.fill(),e.strokeStyle="#5a8a8a",e.lineWidth=2*l,e.stroke();const j=Math.max(0,(f-4*l)*o);if(j>0){let A,D;o>.5?(A="#00ff88",D="#00ff88"):o>.2?(A="#ffaa00",D="#ffaa00"):(A="#ff3366",D="#ff3366"),e.fillStyle=A,e.beginPath(),e.roundRect(m+2*l,p+2*l,j,b-4*l,y-2),e.fill(),e.shadowColor=D,e.shadowBlur=8*l,e.fill(),e.shadowBlur=0}const C=`${Math.round(o*100)}%`;e.font=`bold ${Math.round(24*l)}px Arial`,e.textAlign="center",e.textBaseline="middle",e.strokeStyle="#000000",e.lineWidth=4*l,e.strokeText(C,t/2,n/2),e.fillStyle="#ffffff",e.shadowColor="#ffffff",e.shadowBlur=2*l,e.fillText(C,t/2,n/2),e.shadowBlur=0}createIdleTimer(e,t,n=!1){const a=document.createElement("canvas"),i=a.getContext("2d");a.width=400,a.height=64,this.drawIdleTimer(i,a.width,a.height,e,t);const o=new Jn(a);o.minFilter=In,o.magFilter=In,o.needsUpdate=!0;const l=new Yn({map:o,transparent:!0,depthTest:!1}),c=new Hn(l);return c.position.set(0,n?3.5:2.4,0),c.scale.set(n?1.4:1.1,n?.22:.18,1),c.name="idleTimer",c}createBossCrown(){const e=document.createElement("canvas"),t=e.getContext("2d");e.width=128,e.height=128,t.clearRect(0,0,e.width,e.height),t.font="96px serif",t.textAlign="center",t.textBaseline="middle",t.fillText("👑",e.width/2,e.height/2);const n=new Jn(e);n.minFilter=In,n.magFilter=In,n.needsUpdate=!0;const a=new Yn({map:n,transparent:!0,depthTest:!1}),i=new Hn(a);return i.position.set(0,4,0),i.scale.set(.8,.8,1),i.name="bossCrown",i}drawIdleTimer(e,t,n,a,i){if(e.clearRect(0,0,t,n),a!=="idle"||i<=0)return;const o=Math.floor((Date.now()-i)/1e3),l=this.animConfig.formatIdleTimeShort(o),c=this.animConfig.getIdleTimerColor(o),d=n/80,m=24*d;e.font=`bold ${Math.round(44*d)}px Arial`;const f=e.measureText(`⏱ ${l}`).width+m*2,b=n-12*d,y=(t-f)/2,w=6*d;e.fillStyle="rgba(0, 0, 0, 0.9)",e.beginPath(),e.roundRect(y,w,f,b,10*d),e.fill(),e.strokeStyle=c.border,e.lineWidth=3*d,e.stroke(),e.textAlign="center",e.textBaseline="middle",e.strokeStyle="#000000",e.lineWidth=4*d,e.strokeText(`⏱ ${l}`,t/2,n/2),e.fillStyle=c.text,e.fillText(`⏱ ${l}`,t/2,n/2)}getIdleTimerCanvas(){return this.idleTimerCanvas||(this.idleTimerCanvas=document.createElement("canvas"),this.idleTimerCanvas.width=400,this.idleTimerCanvas.height=64,this.idleTimerCtx=this.idleTimerCanvas.getContext("2d")),{canvas:this.idleTimerCanvas,ctx:this.idleTimerCtx}}getManaBarCanvas(){return this.manaBarCanvas||(this.manaBarCanvas=document.createElement("canvas"),this.manaBarCanvas.width=400,this.manaBarCanvas.height=64,this.manaBarCtx=this.manaBarCanvas.getContext("2d")),{canvas:this.manaBarCanvas,ctx:this.manaBarCtx}}updateIdleTimer(e,t,n){const a=e.getObjectByName("idleTimer");if(!a)return;const i=a.material;if(!i.map)return;const o=i.map.image;if(!o||!(o instanceof HTMLCanvasElement))return;const l=o.getContext("2d");l&&(this.drawIdleTimer(l,o.width,o.height,t,n),i.map.needsUpdate=!0)}updateManaBar(e,t,n){const a=e.getObjectByName("manaBar");if(!a)return;const i=a.material;if(!i.map)return;const o=i.map.image;if(!o||!(o instanceof HTMLCanvasElement))return;const l=o.getContext("2d");l&&(this.drawManaBar(l,o.width,o.height,t,n),i.map.needsUpdate=!0)}updateNameLabel(e,t,n,a){var m;const i=e.getObjectByName("nameLabel");i&&((m=i.material.map)==null||m.dispose(),i.material.dispose(),e.remove(i));const o=Ba[n],l=(o==null?void 0:o.color)??16777215,c=n==="boss"||e.userData.isBoss,d=this.createNameLabelSprite(t,l,c,a);e.add(d)}updateVisuals(e,t,n,a,i){const o=t.isBoss===!0||t.class==="boss",l=Math.round(KA(t)),c=e.userData;if(c._cachedStatus!==t.status||c._cachedPercent!==l||c._cachedIsBoss!==o||t.status==="idle"&&c._cachedIdleBucket!==Math.floor((Date.now()-t.lastActivity)/6e4)){c._cachedStatus=t.status,c._cachedPercent=l,c._cachedIsBoss=o,c._cachedIdleBucket=t.status==="idle"?Math.floor((Date.now()-t.lastActivity)/6e4):0;const p=e.getObjectByName("statusBar");if(p){const w=p.material;if(w.map){const k=w.map.image;if(k instanceof HTMLCanvasElement){const S=k.getContext("2d");S&&(this.drawStatusBar(S,k.width,k.height,l,t.status,t.lastActivity,o),w.map.needsUpdate=!0)}}}const f=e.getObjectByName("combinedUI");if(f){const w=f.material;if(w.map){const k=w.map.image;if(k instanceof HTMLCanvasElement){const S=k.getContext("2d");S&&(this.drawCombinedUI(S,k.width,k.height,t.name,i,l,t.status,t.lastActivity,o),w.map.needsUpdate=!0)}}}const b=!!e.getObjectByName("statusBar"),y=!!e.getObjectByName("combinedUI");!b&&!y&&(this.updateManaBar(e,l,t.status),this.updateIdleTimer(e,t.status,t.lastActivity))}if(c.agentName!==t.name){const p=e.getObjectByName("nameLabelSprite");if(p){const y=p.material;if(y.map){const w=y.map.image;if(w instanceof HTMLCanvasElement){const k=w.getContext("2d");k&&(this.drawNameLabel(k,w.width,w.height,t.name,i),y.map.needsUpdate=!0,c.agentName=t.name)}}}const f=!!e.getObjectByName("statusBar"),b=!!e.getObjectByName("combinedUI");!f&&!b&&(this.updateNameLabel(e,t.name,t.class,t.provider),c.agentName=t.name)}const m=e.getObjectByName("selectionRing");if(m){const p=m.material;if(n){const f=Ba[t.class];p.color.setHex((f==null?void 0:f.color)??i),p.opacity=.8}else a?(p.color.setHex(16766720),p.opacity=.5):p.opacity=0}}}class iO{constructor(e){W(this,"modelLoader");W(this,"animConfig");W(this,"visualConfig");this.modelLoader=new nO(e),this.animConfig=new sO,this.visualConfig=new aO(this.animConfig)}setCustomClasses(e){this.modelLoader.setCustomClasses(e)}createAgentMesh(e){const t=new Bn;t.userData.agentId=e.id;const n=this.modelLoader.getClassConfig(e.class),a=e.isBoss===!0||e.class==="boss",{body:i,mixer:o,animations:l}=this.modelLoader.createCharacterBody(e,n.color);t.add(i);const c=this.modelLoader.calculateModelHeight(i,a),d=this.visualConfig.createSelectionRing(n.color,a);t.add(d);const m=KA(e),p=this.visualConfig.createStatusBarSprite(m,e.status,e.lastActivity,a,c);t.add(p);const f=this.visualConfig.createNameLabelSprite(e.name,n.color,a,e.provider);t.add(f),t.userData.agentName=e.name,t.userData.agentClass=e.class,t.userData.isBoss=a,t.position.set(e.position.x,e.position.y,e.position.z);const b=a?1:.75,y=a?3.5:2.5,w=new Un(b,b,y,8),k=new We({visible:!1,transparent:!0,opacity:0}),S=new De(w,k);return S.position.y=y/2,S.name="clickHitbox",t.add(S),{group:t,mixer:o,animations:l,currentAction:null}}updateAgentClass(e,t){const{group:n}=e,a=n.userData.agentClass;if(a===t.class)return null;console.log(`[CharacterFactory] Agent ${t.name} class changed: ${a} -> ${t.class}`);const i=this.modelLoader.replaceAgentModel(e,t);return i&&this.visualConfig.updateNameLabel(n,t.name,t.class),i}updateVisuals(e,t,n,a=!1){const i=this.modelLoader.getClassConfig(t.class);this.visualConfig.updateVisuals(e,t,n,a,i.color)}upgradeToCharacterModel(e,t){return this.modelLoader.upgradeToCharacterModel(e,t)}disposeAgentMesh(e){this.modelLoader.disposeAgentMesh(e)}getStatusColor(e){return this.visualConfig.getStatusColor(e)}updateIdleTimer(e,t,n){this.visualConfig.updateIdleTimer(e,t,n)}updateManaBar(e,t,n){this.visualConfig.updateManaBar(e,t,n)}}const Qn={STATIC:"static",IDLE:"idle",WALK:"walk",JUMP:"jump",SIT:"sit",DIE:"die",EMOTE_YES:"emote-yes",EMOTE_NO:"emote-no"},rj={height:.5,speed:1.5};class rO{constructor(){W(this,"movements",new Map);W(this,"jumpingAgents",new Map);W(this,"animatingAgents",new Set);W(this,"jumpTime",0)}isMoving(e){return this.movements.has(e)}hasActiveMovements(){return this.movements.size>0}resolveAnimationName(e,t){var i;const n=e.group.getObjectByName("characterBody"),a=(i=n==null?void 0:n.userData)==null?void 0:i.animationMapping;if(a){const o=a[t];if(o&&e.animations.has(o))return o;if(o&&e.animations.has(o.toLowerCase()))return o.toLowerCase()}switch(t){case"idle":return Qn.IDLE;case"walk":return Qn.WALK;case"working":return Qn.JUMP;default:return Qn.IDLE}}playAnimationForState(e,t,n){const a=this.resolveAnimationName(e,t);this.playAnimation(e,a,n)}startMovement(e,t,n){const a=t.group.position.clone(),i=new yt(n.x,n.y,n.z),l=a.distanceTo(i)/QL*1e3;this.movements.delete(e),this.movements.set(e,{agentId:e,startPos:a,endPos:i,startTime:performance.now(),duration:Math.max(l,200)});const c=this.resolveAnimationName(t,"walk");this.playAnimation(t,c),this.faceDirection(t,a,i)}cancelMovement(e,t){this.movements.delete(e);const n=this.resolveAnimationName(t,"idle");this.playAnimation(t,n)}playAnimation(e,t,n){if(!e.mixer)return;const a=e.group.userData.agentId;let i=e.animations.get(t);if(i||(i=e.animations.get(t.toLowerCase())),!i){console.warn(`[MovementAnimator] Animation not found: ${t}, available:`,Array.from(e.animations.keys()));const m=this.jumpingAgents.get(a);if(this.jumpingAgents.delete(a),m!==void 0){const p=e.group.getObjectByName("characterBody");p&&(p.position.y=m)}e.currentAction&&(e.currentAction.fadeOut(.2),e.currentAction=null);return}console.log(`[MovementAnimator] Playing: ${t}`);const{loop:o=!0,fadeTime:l=.2,timeScale:c=1}=n??{},d=e.mixer.clipAction(i);if(d.setLoop(o?UD:dA,1/0),d.clampWhenFinished=!o,d.timeScale=c,e.currentAction&&e.currentAction!==d?(e.currentAction.fadeOut(l),d.reset().fadeIn(l).play()):d.reset().play(),e.currentAction=d,this.animatingAgents.add(a),t===Qn.JUMP&&o){if(!this.jumpingAgents.has(a)){const m=e.group.getObjectByName("characterBody"),p=(m==null?void 0:m.position.y)??0;this.jumpingAgents.set(a,p)}}else{const m=this.jumpingAgents.get(a);if(this.jumpingAgents.delete(a),m!==void 0){const p=e.group.getObjectByName("characterBody");p&&(p.position.y=m)}}}stopAnimation(e){this.animatingAgents.delete(e),this.jumpingAgents.delete(e)}faceDirection(e,t,n){const a=new yt().subVectors(n,t).normalize();if(a.x!==0||a.z!==0){const i=e.group.getObjectByName("characterBody");if(i){const o=Math.atan2(a.x,a.z);i.rotation.y=o}}}update(e,t){var i;const n=performance.now(),a=[];this.jumpTime+=t;for(const o of this.animatingAgents){const l=e.get(o);(i=l==null?void 0:l.mixer)==null||i.update(t)}for(const[o,l]of this.jumpingAgents){const c=e.get(o);if(!c)continue;const d=c.group.getObjectByName("characterBody");if(d){const m=Math.abs(Math.sin(this.jumpTime*rj.speed*Math.PI*2))*rj.height;d.position.y=l+m}}for(const[o,l]of this.movements){const c=e.get(o);if(!c){a.push(o);continue}const d=n-l.startTime;let m=Math.min(d/l.duration,1);m=this.easeOutCubic(m),c.group.position.lerpVectors(l.startPos,l.endPos,m),this.smoothRotateToDirection(c,l.startPos,l.endPos,t),m>=1&&(a.push(o),c.group.position.copy(l.endPos))}for(const o of a)this.movements.delete(o);return a}smoothRotateToDirection(e,t,n,a){const i=new yt().subVectors(n,t).normalize();if(i.x===0&&i.z===0)return;const o=e.group.getObjectByName("characterBody");if(!o)return;const l=Math.atan2(i.x,i.z),c=o.rotation.y,d=l-c,m=Math.atan2(Math.sin(d),Math.cos(d)),p=10;o.rotation.y+=m*Math.min(1,p*a)}easeOutCubic(e){return 1-Math.pow(1-e,3)}get activeCount(){return this.movements.size}clear(){this.movements.clear(),this.jumpingAgents.clear(),this.animatingAgents.clear(),this.jumpTime=0}}const Vn={Read:"📖",Write:"✏️",Edit:"📝",Bash:"💻",Glob:"🔍",Grep:"🔎",Task:"📋",WebFetch:"🌐",WebSearch:"🌍",TodoWrite:"✅",NotebookEdit:"📓",AskFollowupQuestion:"❓",AskUserQuestion:"❓",AttemptCompletion:"✨",ListFiles:"📂",SearchFiles:"🔎",ExecuteCommand:"⚙️",default:"⚡"},oO={Read:"tools:display.toolNames.read",Write:"tools:display.toolNames.write",Edit:"tools:display.toolNames.edit",Bash:"tools:display.toolNames.bash",Glob:"tools:display.toolNames.glob",Grep:"tools:display.toolNames.grep",Task:"tools:display.toolNames.task",WebFetch:"tools:display.toolNames.webFetch",WebSearch:"tools:display.toolNames.webSearch",TodoWrite:"tools:display.toolNames.todoWrite",NotebookEdit:"tools:display.toolNames.notebookEdit",AskFollowupQuestion:"tools:display.toolNames.askFollowupQuestion",AskUserQuestion:"tools:display.toolNames.askUserQuestion",AttemptCompletion:"tools:display.toolNames.attemptCompletion",ListFiles:"tools:display.toolNames.listFiles",SearchFiles:"tools:display.toolNames.searchFiles",ExecuteCommand:"tools:display.toolNames.executeCommand"};function XA(s,e){const t=oO[s];return t&&e(t,{defaultValue:s})||s}function Cp(s){return(typeof s=="string"?new Date(s):new Date(s)).toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1})}function ZA(s,e){var t;try{const n=JSON.parse(e);switch(s){case"Read":case"Write":case"Edit":case"NotebookEdit":{const a=n.file_path||n.path||n.notebook_path;if(a)return a;break}case"Bash":{const a=n.command;if(a)return QA(a);break}case"Grep":{const a=n.pattern,i=n.path;if(a&&i)return`"${a}" in ${i}`;if(a)return`"${a}"`;break}case"Glob":{const a=n.pattern,i=n.path;if(a&&i)return`${a} in ${i}`;if(a)return a;break}case"WebFetch":{const a=n.url;if(a)return a;break}case"WebSearch":{const a=n.query;if(a)return`"${a}"`;break}case"Task":{const a=n.description,i=n.subagent_type;if(a)return i?`[${i}] ${a}`:a;if(n.prompt)return n.prompt;break}case"ExitPlanMode":case"EnterPlanMode":{const a=n.allowedPrompts;return Array.isArray(a)&&a.length>0?a.map(i=>i.prompt||i.tool||"").filter(Boolean).join(", "):s==="ExitPlanMode"?"Plan ready":"Entering plan mode"}case"TodoWrite":{const a=n.todos;if(Array.isArray(a)&&a.length>0){const i=a.filter(d=>d.status==="completed").length,o=a.filter(d=>d.status==="in_progress").length,l=a.filter(d=>d.status==="pending").length,c=[];return i>0&&c.push(`${i} done`),o>0&&c.push(`${o} active`),l>0&&c.push(`${l} pending`),`${a.length} items (${c.join(", ")})`}break}case"AskUserQuestion":case"AskFollowupQuestion":{const a=n.questions||n.question;if(a){const i=Array.isArray(a)?(t=a[0])==null?void 0:t.question:a;if(i)return i}break}default:{for(const[,a]of Object.entries(n))if(typeof a=="string"&&a.length>0)return a;break}}}catch{}return null}function lO(s){if(!s.includes("curl")||!s.includes("/api/exec"))return null;const e=[],t=[/(?:-d|--data|--data-raw)\s+'((?:\\'|[^'])*)'/g,/(?:-d|--data|--data-raw)\s+"((?:\\"|[^"])*)"/g];for(const n of t){let a;for(;(a=n.exec(s))!==null;)a[1]&&e.push(a[1])}for(const n of e){const a=[n,n.replace(/\\"/g,'"'),n.replace(/\\'/g,"'"),n.replace(/\\"/g,'"').replace(/\\\\/g,"\\")];for(const i of a){const o=i.trim();if(!(!o.startsWith("{")||!o.endsWith("}")))try{const l=JSON.parse(o);if(typeof l.command=="string"&&l.command.length>0)return l.command}catch{}}}return null}function QA(s){return lO(s)||s}const oj=/(^|[\s("'`])((?:\.{1,2}\/|~\/|\/)?[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)*\.[A-Za-z0-9._-]+(?::\d+(?::\d+)?)?)/g;function cO(s){return!s||s.startsWith("-")||s.includes("://")||s.includes("*")?!1:s.includes(".")&&!s.endsWith(".")}function JA(s){if(!s)return[{text:""}];const e=[];let t=0;oj.lastIndex=0;let n;for(;(n=oj.exec(s))!==null;){const a=n[0],i=n[1]||"",o=n[2]||"",l=n.index;l>t&&e.push({text:s.slice(t,l)}),i&&e.push({text:i}),cO(o)?e.push({text:o,fileRef:o}):e.push({text:o}),t=l+a.length}return t<s.length&&e.push({text:s.slice(t)}),e.length>0?e:[{text:s}]}const Np="tide-file://",uO=/(^|[\s(>])((?:\.\.?\/|\/)?(?:[A-Za-z0-9._-]+\/)*[A-Za-z0-9._-]+(?:\.[A-Za-z0-9._-]+)+(?:#L\d+(?:C\d+)?)?(?::\d+(?::\d+)?)?)(?=$|[\s),.;])/g,dO=/`((?:\.\.?\/|\/)?(?:[A-Za-z0-9._-]+\/)*[A-Za-z0-9._-]+(?:\.[A-Za-z0-9._-]+)+(?:#L\d+(?:C\d+)?)?(?::\d+(?::\d+)?)?)`/g,hO=/\.(com|org|net|io|dev|app|co|me|info|biz|us|uk|de|fr|jp|cn|ru|edu|gov|mil|int|xyz|tech|online|site|store|blog|cloud|ai|gg|tv|cc|sh|fm|to|ly|gl|so|is|it|at|nl|ch|se|no|fi|dk|be|cz|pl|pt|br|mx|ar|cl|in|au|nz|za|sg|hk|tw|kr|id|ph|th|vn|my)(?:[:/\s#?]|$)/i;function lj(s){if(!s||s.includes("://")||s.startsWith("www.")||s.includes("@"))return!1;const e=s.split("/")[0];return hO.test(e)?!1:s.includes(".")&&!s.endsWith(".")}function Xg(s){if(!s||!s.includes("."))return s;const e=s.split(`
44
44
  `);let t=!1;return e.map(a=>{if(a.trimStart().startsWith("```"))return t=!t,a;if(t)return a;const o=a.replace(dO,(l,c)=>{if(!lj(c))return l;const d=encodeURIComponent(c);return`[\`${c}\`](${Np}${d})`});return o.replace(uO,(l,c,d,m)=>{const p=m+c.length,f=p>0?o[p-1]:"",b=p+d.length<o.length?o[p+d.length]:"";if(f==="("&&p>1&&o[p-2]==="]"||f==="["||b==="]"||!lj(d))return l;const y=encodeURIComponent(d);return`${c}[${d}](${Np}${y})`})}).join(`
45
45
  `)}function pO(s){if(!s||!s.startsWith(Np))return null;const e=s.slice(Np.length);if(!e)return null;try{return decodeURIComponent(e)}catch{return e}}function Ap(s){return s.startsWith('"')&&s.endsWith('"')||s.startsWith("'")&&s.endsWith("'")?s.slice(1,-1):s}function eM(s){const e=s.trim();if(!e)return null;let t,n=e;const a=e.match(/^(\S+)\s+-lc\s+([\s\S]+)$/);if(a&&(t=`${a[1]} -lc`,n=Ap(a[2].trim())),!/\brg\s+--files\b/.test(n)||!/\|\s*rg\b/.test(n))return null;const i=n.match(/\|\s*rg\b\s+(.+)$/);if(!i)return null;const o=i[1].trim();if(!o)return null;const l=o.replace(/^(?:-\S+\s+)*/,"").trim(),c=Ap(l||o);return c?{shellPrefix:t,commandBody:n,searchTerm:c}:null}function tM(s){const e=s.trim();if(!e)return null;let t,n=e;const a=e.match(/^(\S+)\s+-lc\s+([\s\S]+)$/);a&&(t=`${a[1]} -lc`,n=Ap(a[2].trim()));const i=/\bcurl\b[\s\S]*\/api\/notify\b/.test(n),o=/\bgdbus\b[\s\S]*org\.freedesktop\.Notifications\.Notify\b/.test(n);if(!i&&!o)return null;let l,c;const d=n.match(/-d\s+((['"])([\s\S]*?)\2)/);if(d){const m=Ap(d[1]).replace(/\\"/g,'"'),p=m.match(/"title"\s*:\s*"([^"]*)"/),f=m.match(/"message"\s*:\s*"([^"]*)"/);p!=null&&p[1]&&(l=p[1]),f!=null&&f[1]&&(c=f[1])}if(!l||!c){const m=n.match(/Notifications\.Notify[\s\S]*?\s'[^']*'\s+\d+\s+'[^']*'\s+'([^']*)'\s+'([^']*)'/);!l&&(m!=null&&m[1])&&(l=m[1]),!c&&(m!=null&&m[2])&&(c=m[2])}return{shellPrefix:t,commandBody:n,title:l,message:c,viaCurl:i,viaGdbus:o}}const Zu=class Zu{constructor(e){W(this,"scene");W(this,"moveOrderEffects",[]);W(this,"speechBubbles",[]);W(this,"sleepingEffects",[]);W(this,"waitingPermissionEffects",[]);W(this,"delegationEffects",[]);W(this,"subagentEffects",[]);W(this,"agentMeshes",new Map);W(this,"ringGeometry",null);W(this,"pulseGeometry",null);W(this,"chevronGeometry",null);W(this,"delegationPaperTexture",null);W(this,"sleepingBubbleTexture",null);W(this,"waitingPermissionTexture",null);W(this,"delegationSpritePool",[]);W(this,"moveOrderGroupPool",[]);W(this,"_needsUpdate",!1);W(this,"camera",null);W(this,"indicatorScale",1);this.scene=e,this.initializeCachedResources()}get needsUpdate(){return this._needsUpdate||this.moveOrderEffects.length>0||this.speechBubbles.length>0||this.sleepingEffects.length>0||this.waitingPermissionEffects.length>0||this.delegationEffects.length>0||this.subagentEffects.length>0}markDirty(){this._needsUpdate=!0}clearDirty(){this._needsUpdate=!1}initializeCachedResources(){this.ringGeometry=new Xo(.3,.4,32),this.pulseGeometry=new Xo(.1,.2,32);const e=new GD;e.moveTo(0,.15),e.lineTo(.12,.35),e.lineTo(.08,.35),e.lineTo(0,.2),e.lineTo(-.08,.35),e.lineTo(-.12,.35),e.closePath(),this.chevronGeometry=new WD(e),this.createDelegationPaperTexture(),this.createSleepingBubbleTexture(),this.createWaitingPermissionTexture(),this.initializePools()}initializePools(){for(let e=0;e<Zu.POOL_SIZE;e++)if(this.delegationPaperTexture){const t=new Yn({map:this.delegationPaperTexture,transparent:!0,opacity:0,depthTest:!1}),n=new Hn(t);n.scale.set(.3,.3,1),n.visible=!1,this.delegationSpritePool.push({sprite:n,inUse:!1})}for(let e=0;e<Zu.POOL_SIZE;e++){const t=this.createMoveOrderGroup();t.visible=!1,this.moveOrderGroupPool.push(t)}}createMoveOrderGroup(){const e=new Bn,t=new We({color:4915102,side:ws,transparent:!0,opacity:.8}),n=new De(this.ringGeometry,t);n.rotation.x=-Math.PI/2,n.name="ring",e.add(n);const a=new We({color:4915102,side:ws,transparent:!0,opacity:.6}),i=new De(this.pulseGeometry,a);i.rotation.x=-Math.PI/2,i.name="pulse",e.add(i);for(let o=0;o<3;o++){const l=new We({color:4915102,side:ws,transparent:!0,opacity:.9}),c=new De(this.chevronGeometry,l);c.rotation.x=-Math.PI/2,c.position.y=.5+o*.25,c.name=`chevron${o}`,e.add(c)}return e}getDelegationSprite(){for(const n of this.delegationSpritePool)if(!n.inUse)return n.inUse=!0,n.sprite.visible=!0,n.sprite.material.opacity=1,n.sprite;const e=new Yn({map:this.delegationPaperTexture,transparent:!0,opacity:1,depthTest:!1}),t=new Hn(e);return t.scale.set(.3,.3,1),t}returnDelegationSprite(e){for(const t of this.delegationSpritePool)if(t.sprite===e){t.inUse=!1,t.sprite.visible=!1,this.scene.remove(e);return}this.scene.remove(e),e.material.dispose()}getMoveOrderGroup(){for(const e of this.moveOrderGroupPool)if(!e.visible)return e.visible=!0,e.traverse(t=>{if(t instanceof De){const n=t.material;n.opacity=t.name==="ring"?.8:t.name==="pulse"?.6:.9}}),e;return this.createMoveOrderGroup()}returnMoveOrderGroup(e){this.moveOrderGroupPool.includes(e)?(e.visible=!1,this.scene.remove(e)):(this.scene.remove(e),e.traverse(n=>{n instanceof De&&n.material.dispose()}))}createDelegationPaperTexture(){const e=document.createElement("canvas"),t=e.getContext("2d");e.width=64,e.height=64,t.fillStyle="#ffffff",t.strokeStyle="#ffd700",t.lineWidth=2,t.save(),t.translate(32,32),t.rotate(-.2),t.beginPath(),t.moveTo(-12,-18),t.lineTo(8,-18),t.lineTo(12,-14),t.lineTo(12,18),t.lineTo(-12,18),t.closePath(),t.fill(),t.stroke(),t.beginPath(),t.moveTo(8,-18),t.lineTo(8,-14),t.lineTo(12,-14),t.strokeStyle="#cccccc",t.stroke(),t.fillStyle="#f0f0f0",t.fill(),t.strokeStyle="#888888",t.lineWidth=1;for(let n=0;n<4;n++){const a=-8+n*6,i=n===3?10:16;t.beginPath(),t.moveTo(-8,a),t.lineTo(-8+i,a),t.stroke()}t.restore(),this.delegationPaperTexture=new Jn(e),this.delegationPaperTexture.minFilter=In,this.delegationPaperTexture.magFilter=In}createSleepingBubbleTexture(){const e=document.createElement("canvas"),t=e.getContext("2d");e.width=128,e.height=128,t.fillStyle="rgba(40, 42, 54, 0.95)",t.strokeStyle="#bd93f9",t.lineWidth=2;const n=64,a=50,i=40;t.beginPath(),t.arc(n,a,i,0,Math.PI*2),t.fill(),t.stroke(),t.beginPath(),t.arc(30,95,10,0,Math.PI*2),t.fill(),t.stroke(),t.beginPath(),t.arc(18,115,6,0,Math.PI*2),t.fill(),t.stroke(),t.fillStyle="#8be9fd",t.font="bold 28px Arial",t.textAlign="center",t.textBaseline="middle",t.shadowColor="#8be9fd",t.shadowBlur=4,t.fillText("ZZZ",n,a),this.sleepingBubbleTexture=new Jn(e),this.sleepingBubbleTexture.minFilter=In,this.sleepingBubbleTexture.magFilter=In}createWaitingPermissionTexture(){const e=document.createElement("canvas"),t=e.getContext("2d");e.width=128,e.height=128,t.fillStyle="rgba(40, 42, 54, 0.95)",t.strokeStyle="#ffcc00",t.lineWidth=2;const n=64,a=50,i=40;t.beginPath(),t.arc(n,a,i,0,Math.PI*2),t.fill(),t.stroke(),t.beginPath(),t.arc(30,95,10,0,Math.PI*2),t.fill(),t.stroke(),t.beginPath(),t.arc(18,115,6,0,Math.PI*2),t.fill(),t.stroke(),t.fillStyle="#ffcc00",t.font="bold 32px Arial",t.textAlign="center",t.textBaseline="middle",t.shadowColor="#ffcc00",t.shadowBlur=6,t.fillText("🔒",n,a),this.waitingPermissionTexture=new Jn(e),this.waitingPermissionTexture.minFilter=In,this.waitingPermissionTexture.magFilter=In}setAgentMeshes(e){this.agentMeshes.clear();for(const[t,n]of e)this.agentMeshes.set(t,n.group)}updateSleepingEffect(e,t){const n=this.sleepingEffects.find(a=>a.agentId===e);t&&!n?this.createSleepingEffect(e):!t&&n&&this.removeSleepingEffect(e)}updateWaitingPermissionEffect(e,t){const n=this.waitingPermissionEffects.find(a=>a.agentId===e);t&&!n?this.createWaitingPermissionEffect(e):!t&&n&&this.removeWaitingPermissionEffect(e)}createSleepingEffect(e){const t=this.agentMeshes.get(e);if(!t||!this.sleepingBubbleTexture)return;const n=[],a=new Yn({map:this.sleepingBubbleTexture,transparent:!0,opacity:.95,depthTest:!1}),i=new Hn(a);i.scale.set(.12,.12,1),i.userData.isBubble=!0,i.position.copy(t.position),i.position.y=2,i.position.x+=.15,this.scene.add(i),n.push(i),this.sleepingEffects.push({sprites:n,agentId:e,startTime:performance.now()}),this.markDirty()}removeSleepingEffect(e){const t=this.sleepingEffects.findIndex(n=>n.agentId===e);if(t!==-1){const n=this.sleepingEffects[t];for(const a of n.sprites)this.scene.remove(a),a.material.dispose();this.sleepingEffects.splice(t,1),this.markDirty()}}createWaitingPermissionEffect(e){const t=this.agentMeshes.get(e);if(!t||!this.waitingPermissionTexture)return;const n=[],a=new Yn({map:this.waitingPermissionTexture,transparent:!0,opacity:.95,depthTest:!1}),i=new Hn(a);i.scale.set(.12,.12,1),i.userData.isBubble=!0,i.position.copy(t.position),i.position.y=2,i.position.x+=.15,this.scene.add(i),n.push(i),this.waitingPermissionEffects.push({sprites:n,agentId:e,startTime:performance.now()}),this.markDirty()}removeWaitingPermissionEffect(e){const t=this.waitingPermissionEffects.findIndex(n=>n.agentId===e);if(t!==-1){const n=this.waitingPermissionEffects[t];for(const a of n.sprites)this.scene.remove(a),a.material.dispose();this.waitingPermissionEffects.splice(t,1),this.markDirty()}}createDelegationEffect(e,t){const n=this.agentMeshes.get(e),a=this.agentMeshes.get(t);if(!n||!a||!this.delegationPaperTexture){console.log("[EffectsManager] Cannot create delegation effect - missing agent meshes or texture");return}const i=this.getDelegationSprite(),o=new yt(n.position.x,n.position.y+1.5,n.position.z),l=new yt(a.position.x,a.position.y+1.2,a.position.z);i.position.copy(o),this.scene.add(i),this.delegationEffects.push({sprite:i,startPosition:o.clone(),endPosition:l.clone(),startTime:performance.now(),duration:800}),this.markDirty()}createSpeechBubble(e,t,n){const a=this.agentMeshes.get(e);if(!a)return;this.removeSpeechBubble(e);const i=Vn[t]||"🔧",o=this.formatToolParams(t,n),l=document.createElement("canvas"),c=l.getContext("2d");l.width=400,l.height=100;const d=o?`${i} ${t}: ${o}`:`${i} ${t}`;c.font="bold 32px Arial";const f=Math.min(c.measureText(d).width,l.width-40)+16*2,b=48,y=(l.width-f)/2,w=(l.height-b)/2,k=b/2;c.fillStyle="rgba(15, 15, 25, 0.85)",c.strokeStyle="#4a9eff",c.lineWidth=2,c.beginPath(),c.moveTo(y+k,w),c.lineTo(y+f-k,w),c.arc(y+f-k,w+k,k,-Math.PI/2,Math.PI/2),c.lineTo(y+k,w+b),c.arc(y+k,w+k,k,Math.PI/2,-Math.PI/2),c.closePath(),c.fill(),c.stroke(),c.fillStyle="#ffffff",c.font="bold 30px Arial",c.textAlign="center",c.textBaseline="middle";let S=d;const j=l.width-40;for(;c.measureText(S).width>j&&S.length>3;)S=S.slice(0,-4)+"...";c.fillText(S,l.width/2,l.height/2);const C=new Jn(l);C.minFilter=In,C.magFilter=In,C.needsUpdate=!0;const A=new Yn({map:C,transparent:!0,opacity:0,depthTest:!1}),D=new Hn(A);D.scale.set(2.4,.6,1),D.renderOrder=1e3;const M=a.position.y-1.3;D.position.copy(a.position),D.position.y=M,this.scene.add(D),this.speechBubbles.push({sprite:D,agentId:e,startTime:performance.now(),duration:4e3,baseY:M})}formatToolParams(e,t){if(!t)return"";switch(e){case"WebSearch":return t.query||"";case"WebFetch":return t.url||"";case"Read":case"Write":case"Edit":const n=t.file_path||t.path||"";return n.length>40?".../"+n.split("/").slice(-2).join("/"):n;case"Bash":const a=(t.command||"").slice(0,60);return a+(a.length>=60?"...":"");case"Grep":return`"${t.pattern||""}"`;case"Glob":return t.pattern||"";case"Task":return(t.description||"").slice(0,50);default:for(const[i,o]of Object.entries(t))if(typeof o=="string"&&o.length>0&&o.length<100)return o.slice(0,50);return""}}removeSpeechBubble(e){var n;const t=this.speechBubbles.findIndex(a=>a.agentId===e);if(t!==-1){const a=this.speechBubbles[t];this.scene.remove(a.sprite),(n=a.sprite.material.map)==null||n.dispose(),a.sprite.material.dispose(),this.speechBubbles.splice(t,1)}}createMoveOrderEffect(e){const t=this.getMoveOrderGroup();t.position.copy(e),t.position.y=.05;for(let i=0;i<3;i++){const o=t.getObjectByName(`chevron${i}`);o&&(o.position.y=.5+i*.25)}const n=t.getObjectByName("ring");n&&n.scale.setScalar(1);const a=t.getObjectByName("pulse");a&&a.scale.setScalar(1),this.scene.add(t),this.moveOrderEffects.push({group:t,startTime:performance.now(),duration:800}),this.markDirty()}setIndicatorScale(e){this.indicatorScale=e}update(){const e=performance.now();this.updateMoveOrderEffects(e),this.updateSpeechBubbles(e),this.updateSleepingEffects(),this.updateWaitingPermissionEffects(),this.updateDelegationEffects(e),this.updateSubagentEffects(e)}updateWithCamera(e){this.camera=e}calculateZoomScale(e){if(!this.camera)return this.indicatorScale;const t=this.camera.position.distanceTo(e);return Math.max(.5,Math.min(2.5,t/15))*this.indicatorScale}updateSleepingEffects(){const e=performance.now();for(const t of this.sleepingEffects){const n=this.agentMeshes.get(t.agentId);if(!n)continue;const a=e-t.startTime,i=this.calculateZoomScale(n.position);for(const o of t.sprites){o.position.x=n.position.x+.25*i,o.position.z=n.position.z;const l=.002,c=.04*i;o.position.y=2+Math.sin(a*l)*c;const d=.35*i,m=Math.sin(a*.003)*.015*i;o.scale.set(d+m,d+m,1);const p=Math.min(a/500,1);o.material.opacity=.95*p}}}updateWaitingPermissionEffects(){const e=performance.now();for(const t of this.waitingPermissionEffects){const n=this.agentMeshes.get(t.agentId);if(!n)continue;const a=e-t.startTime,i=this.calculateZoomScale(n.position);for(const o of t.sprites){o.position.x=n.position.x+.25*i,o.position.z=n.position.z;const l=.004,c=.06*i;o.position.y=2+Math.sin(a*l)*c;const d=.38*i,m=Math.sin(a*.006)*.03*i;o.scale.set(d+m,d+m,1);const p=Math.min(a/300,1),f=.85+Math.sin(a*.005)*.1;o.material.opacity=f*p}}}updateDelegationEffects(e){const t=[];for(let n=0;n<this.delegationEffects.length;n++){const a=this.delegationEffects[n],i=Math.min((e-a.startTime)/a.duration,1),o=1-(1-i)*(1-i),l=a.endPosition.x-a.startPosition.x,c=a.endPosition.y-a.startPosition.y,d=a.endPosition.z-a.startPosition.z,m=4*i*(1-i)*.8;a.sprite.position.x=a.startPosition.x+l*o,a.sprite.position.y=a.startPosition.y+c*o+m,a.sprite.position.z=a.startPosition.z+d*o,a.sprite.material.rotation=i*Math.PI*1.5,a.sprite.material.opacity=i>.8?(1-i)*5:1,i>=1&&t.push(n)}for(let n=t.length-1;n>=0;n--){const a=t[n],i=this.delegationEffects[a];this.returnDelegationSprite(i.sprite),this.delegationEffects.splice(a,1)}}updateMoveOrderEffects(e){const t=[];for(let n=0;n<this.moveOrderEffects.length;n++){const a=this.moveOrderEffects[n],i=e-a.startTime,o=Math.min(i/a.duration,1),l=1-o,c=a.group.getObjectByName("ring");c&&(c.scale.setScalar(1+o*1.5),c.material.opacity=l*.8);const d=a.group.getObjectByName("pulse");if(d){const m=(Math.sin(o*Math.PI*4)+1)/2;d.scale.setScalar(.8+m*.4),d.material.opacity=l*.6}for(let m=0;m<3;m++){const p=a.group.getObjectByName(`chevron${m}`);if(p){const f=m*.15,b=Math.max(0,Math.min((o-f)/(1-f),1));p.position.y=.5+m*.25-b*(.4+m*.15),p.material.opacity=(1-b)*.9}}o>=1&&t.push(n)}for(let n=t.length-1;n>=0;n--){const a=t[n];this.returnMoveOrderGroup(this.moveOrderEffects[a].group),this.moveOrderEffects.splice(a,1)}}updateSpeechBubbles(e){var n;const t=[];for(let a=0;a<this.speechBubbles.length;a++){const i=this.speechBubbles[a],o=e-i.startTime,l=Math.min(o/i.duration,1),c=this.agentMeshes.get(i.agentId);if(c){i.sprite.position.x=c.position.x,i.sprite.position.z=c.position.z;const f=this.calculateZoomScale(c.position);i.sprite.scale.set(2.4*f,.6*f,1)}const d=Math.min(o/200,1),m=l>.7?1-(l-.7)/.3:1;i.sprite.material.opacity=d*m;const p=c?c.position.y:0;i.sprite.position.y=p-1.3,l>=1&&t.push(a)}for(let a=t.length-1;a>=0;a--){const i=t[a],o=this.speechBubbles[i];this.scene.remove(o.sprite),(n=o.sprite.material.map)==null||n.dispose(),o.sprite.material.dispose(),this.speechBubbles.splice(i,1)}}disposeEffect(e){this.scene.remove(e.group),e.group.traverse(t=>{t instanceof De&&t.material.dispose()})}addSubagentEffect(e,t,n,a){const i=this.agentMeshes.get(t);if(!i){console.warn(`[EffectsManager] Cannot add subagent effect: parent agent ${t} not found`);return}if(this.subagentEffects.find(S=>S.subagentId===e))return;const o=document.createElement("canvas");o.width=256,o.height=64;const l=o.getContext("2d");l.fillStyle="rgba(30, 30, 60, 0.85)";const c=12;l.beginPath(),l.moveTo(c,0),l.lineTo(o.width-c,0),l.quadraticCurveTo(o.width,0,o.width,c),l.lineTo(o.width,o.height-c),l.quadraticCurveTo(o.width,o.height,o.width-c,o.height),l.lineTo(c,o.height),l.quadraticCurveTo(0,o.height,0,o.height-c),l.lineTo(0,c),l.quadraticCurveTo(0,0,c,0),l.closePath(),l.fill(),l.strokeStyle="rgba(100, 180, 255, 0.8)",l.lineWidth=2,l.stroke(),l.fillStyle="#64b4ff",l.font="bold 28px monospace",l.fillText("⑂",8,40),l.fillStyle="#ffffff",l.font="22px sans-serif";const d=n.length>14?n.slice(0,12)+"..":n;l.fillText(d,40,38);const m=new Jn(o);m.needsUpdate=!0;const p=new Yn({map:m,transparent:!0,opacity:.85,depthTest:!1}),f=new Hn(p);f.scale.set(1.5,.4,1);const b=this.subagentEffects.filter(S=>S.parentAgentId===t&&!S.completed).length,y=b*Math.PI/4-Math.PI/4,w=1.5,k=i.position;f.position.set(k.x+Math.sin(y)*w,k.y+2.5+b*.5,k.z+Math.cos(y)*w),this.scene.add(f),this.subagentEffects.push({sprite:f,subagentId:e,parentAgentId:t,name:n,subagentType:a,startTime:performance.now(),completed:!1,completedAt:0}),this.markDirty(),console.log(`[EffectsManager] Added subagent effect: ${n} (${e}) near ${t}`)}completeSubagentEffect(e){const t=this.subagentEffects.find(n=>n.subagentId===e);t?(t.completed=!0,t.completedAt=performance.now(),this.markDirty(),console.log(`[EffectsManager] Marked subagent effect completed: ${t.name} (${e})`)):console.warn(`[EffectsManager] completeSubagentEffect: no effect found for subagentId=${e}`)}removeSubagentEffect(e){var n;const t=this.subagentEffects.findIndex(a=>a.subagentId===e);if(t!==-1){const a=this.subagentEffects[t];this.scene.remove(a.sprite),(n=a.sprite.material.map)==null||n.dispose(),a.sprite.material.dispose(),this.subagentEffects.splice(t,1),this.markDirty()}}updateSubagentEffects(e){var n;const t=[];for(let a=0;a<this.subagentEffects.length;a++){const i=this.subagentEffects[a],o=this.agentMeshes.get(i.parentAgentId);if(!o){t.push(a);continue}const l=this.subagentEffects.slice(0,a).filter(f=>f.parentAgentId===i.parentAgentId&&!f.completed).length,c=l*Math.PI/4-Math.PI/4,d=1.5,m=o.position;i.sprite.position.set(m.x+Math.sin(c)*d,m.y+2.5+l*.5,m.z+Math.cos(c)*d);const p=(e-i.startTime)/1e3;if(i.sprite.position.y+=Math.sin(p*1.5)*.05,i.completed&&i.completedAt>0){const f=(e-i.completedAt)/1e3;if(f>2){const b=Math.max(0,.85-(f-2)*.3);i.sprite.material.opacity=b,b<=0&&t.push(a)}}i.completed||(i.sprite.material.opacity=.75+Math.sin(p*2)*.1)}for(let a=t.length-1;a>=0;a--){const i=t[a],o=this.subagentEffects[i];this.scene.remove(o.sprite),(n=o.sprite.material.map)==null||n.dispose(),o.sprite.material.dispose(),this.subagentEffects.splice(i,1)}}removeAgentEffects(e){this.removeSleepingEffect(e),this.removeWaitingPermissionEffect(e),this.removeSpeechBubble(e);const t=this.subagentEffects.filter(n=>n.parentAgentId===e).map(n=>n.subagentId);for(const n of t)this.removeSubagentEffect(n);this.agentMeshes.delete(e)}clear(){var e,t;for(const n of this.moveOrderEffects)this.returnMoveOrderGroup(n.group);this.moveOrderEffects=[];for(const n of this.sleepingEffects)for(const a of n.sprites)this.scene.remove(a),a.material.dispose();this.sleepingEffects=[];for(const n of this.waitingPermissionEffects)for(const a of n.sprites)this.scene.remove(a),a.material.dispose();this.waitingPermissionEffects=[];for(const n of this.delegationEffects)this.returnDelegationSprite(n.sprite);this.delegationEffects=[];for(const n of this.speechBubbles)this.scene.remove(n.sprite),(e=n.sprite.material.map)==null||e.dispose(),n.sprite.material.dispose();this.speechBubbles=[];for(const n of this.subagentEffects)this.scene.remove(n.sprite),(t=n.sprite.material.map)==null||t.dispose(),n.sprite.material.dispose();this.subagentEffects=[]}dispose(){var e,t,n,a,i,o;this.clear(),(e=this.ringGeometry)==null||e.dispose(),(t=this.pulseGeometry)==null||t.dispose(),(n=this.chevronGeometry)==null||n.dispose(),this.ringGeometry=null,this.pulseGeometry=null,this.chevronGeometry=null,(a=this.delegationPaperTexture)==null||a.dispose(),(i=this.sleepingBubbleTexture)==null||i.dispose(),(o=this.waitingPermissionTexture)==null||o.dispose(),this.delegationPaperTexture=null,this.sleepingBubbleTexture=null,this.waitingPermissionTexture=null;for(const l of this.delegationSpritePool)l.sprite.material.dispose();this.delegationSpritePool=[];for(const l of this.moveOrderGroupPool)l.traverse(c=>{c instanceof De&&c.material.dispose()});this.moveOrderGroupPool=[],this.agentMeshes.clear()}};W(Zu,"POOL_SIZE",10);let yy=Zu;class mO{constructor(){W(this,"animations",new Map)}register(e,t,n="idle"){this.animations.set(e,{state:n,time:Math.random()*Math.PI*2,basePosition:t.position.clone(),baseRotation:t.rotation.clone(),baseScale:t.scale.clone()})}unregister(e){this.animations.delete(e)}has(e){return this.animations.has(e)}setState(e,t){const n=this.animations.get(e);n&&n.state!==t&&(n.state=t,n.time=0)}updateBasePosition(e,t){const n=this.animations.get(e);n&&n.basePosition.copy(t)}update(e,t){for(const[n,a]of this.animations){const i=t.get(n);if(i)switch(a.time+=e,a.state){case"idle":this.applyIdleAnimation(i,a);break;case"working":this.applyWorkingAnimation(i,a);break;case"waiting":this.applyWaitingAnimation(i,a);break;case"error":this.applyErrorAnimation(i,a);break;case"static":this.resetToBase(i,a);break}}}applyIdleAnimation(e,t){const n=t.time,o=Math.sin(n*1.5)*.02,d=Math.sin(n*.8)*.01;e.position.set(t.basePosition.x+d,t.basePosition.y+o,t.basePosition.z)}applyWorkingAnimation(e,t){const n=t.time,o=Math.abs(Math.sin(n*6))*.25,l=.15,c=3,d=Math.sin(n*c)*l,f=Math.sin(n*3)*.22,y=Math.sin(n*c*.7)*.1,S=Math.sin(n*4)*.12;e.position.set(t.basePosition.x+d,t.basePosition.y+o,t.basePosition.z+y),e.rotation.set(t.baseRotation.x+f,t.baseRotation.y+S,t.baseRotation.z)}applyWaitingAnimation(e,t){const n=t.time,a=.02,i=1.2,o=Math.sin(n*i)*a,c=Math.sin(n*i)*.03,p=Math.sin(n*2)*.01;e.position.set(t.basePosition.x+o,t.basePosition.y+p,t.basePosition.z),e.rotation.set(t.baseRotation.x,t.baseRotation.y,t.baseRotation.z+c)}applyErrorAnimation(e,t){const n=t.time,a=.015,i=15,o=Math.sin(n*i)*a,l=Math.cos(n*i*1.3)*a*.5;e.position.set(t.basePosition.x+o,t.basePosition.y,t.basePosition.z+l)}resetToBase(e,t){e.position.copy(t.basePosition),e.rotation.copy(t.baseRotation),e.scale.copy(t.baseScale)}clear(){this.animations.clear()}}function cj(s){const e=document.createElement("canvas"),t=e.getContext("2d"),n=s==="pokemon-stadium"?1024:512;switch(e.width=n,e.height=n,s){case"galactic":gO(t,e.width,e.height);break;case"metal":bO(t,e.width,e.height);break;case"hex":yO(t,e.width,e.height);break;case"circuit":xO(t,e.width,e.height);break;case"pokemon-stadium":vO(t,e.width,e.height);break;default:fO(t,e.width,e.height)}return new Jn(e)}function fO(s,e,t){s.fillStyle="#4a4a4a",s.fillRect(0,0,e,t);for(let n=0;n<5e3;n++){const a=Math.random()*e,i=Math.random()*t,o=60+Math.random()*40;s.fillStyle=`rgba(${o}, ${o}, ${o}, 0.3)`,s.fillRect(a,i,2,2)}s.strokeStyle="rgba(30, 30, 30, 0.4)",s.lineWidth=1;for(let n=0;n<8;n++){s.beginPath();let a=Math.random()*e,i=Math.random()*t;s.moveTo(a,i);for(let o=0;o<5;o++)a+=(Math.random()-.5)*100,i+=(Math.random()-.5)*100,s.lineTo(a,i);s.stroke()}}function gO(s,e,t){const n=s.createRadialGradient(e/2,t/2,0,e/2,t/2,e/1.5);n.addColorStop(0,"#1a0a30"),n.addColorStop(.5,"#0d0520"),n.addColorStop(1,"#050210"),s.fillStyle=n,s.fillRect(0,0,e,t);for(let a=0;a<3;a++){const i=Math.random()*e,o=Math.random()*t,l=100+Math.random()*150,c=["#ff00ff","#00ffff","#ff6600","#6600ff","#00ff66"],d=c[Math.floor(Math.random()*c.length)],m=s.createRadialGradient(i,o,0,i,o,l);m.addColorStop(0,d.replace("ff","66")+"40"),m.addColorStop(.5,d+"20"),m.addColorStop(1,"transparent"),s.fillStyle=m,s.fillRect(0,0,e,t)}for(let a=0;a<300;a++){const i=Math.random()*e,o=Math.random()*t,l=Math.random()*2,c=150+Math.random()*105;if(Math.random()>.8){const d=s.createRadialGradient(i,o,0,i,o,l*4);d.addColorStop(0,`rgba(${c}, ${c}, 255, 0.8)`),d.addColorStop(1,"transparent"),s.fillStyle=d,s.fillRect(i-l*4,o-l*4,l*8,l*8)}s.fillStyle=`rgba(${c}, ${c}, 255, 1)`,s.beginPath(),s.arc(i,o,l,0,Math.PI*2),s.fill()}s.strokeStyle="rgba(100, 50, 150, 0.15)",s.lineWidth=20,s.beginPath();for(let a=0;a<Math.PI*4;a+=.1){const i=20+a*30,o=e/2+Math.cos(a)*i,l=t/2+Math.sin(a)*i;a===0?s.moveTo(o,l):s.lineTo(o,l)}s.stroke()}function bO(s,e,t){s.fillStyle="#3a3a44",s.fillRect(0,0,e,t);for(let a=0;a<200;a++){const i=Math.random()*t,o=50+Math.random()*30;s.strokeStyle=`rgba(${o+20}, ${o+20}, ${o+30}, 0.3)`,s.lineWidth=1,s.beginPath(),s.moveTo(0,i),s.lineTo(e,i+(Math.random()-.5)*4),s.stroke()}s.strokeStyle="rgba(20, 20, 25, 0.8)",s.lineWidth=3;const n=e/4;for(let a=0;a<=e;a+=n)s.beginPath(),s.moveTo(a,0),s.lineTo(a,t),s.stroke();for(let a=0;a<=t;a+=n)s.beginPath(),s.moveTo(0,a),s.lineTo(e,a),s.stroke();s.fillStyle="#555566";for(let a=0;a<=e;a+=n)for(let i=0;i<=t;i+=n)s.beginPath(),s.arc(a,i,8,0,Math.PI*2),s.fill(),s.fillStyle="#666677",s.beginPath(),s.arc(a-2,i-2,4,0,Math.PI*2),s.fill(),s.fillStyle="#555566"}function yO(s,e,t){s.fillStyle="#1a2530",s.fillRect(0,0,e,t);const n=30,a=n*Math.sqrt(3);for(let i=-1;i<t/a+1;i++)for(let o=-1;o<e/(n*1.5)+1;o++){const l=o*n*1.5,c=i*a+(o%2===0?0:a/2),d=30+Math.random()*20;s.fillStyle=`rgb(${d}, ${d+20}, ${d+40})`,s.beginPath();for(let m=0;m<6;m++){const p=Math.PI/3*m+Math.PI/6,f=l+Math.cos(p)*(n-2),b=c+Math.sin(p)*(n-2);m===0?s.moveTo(f,b):s.lineTo(f,b)}if(s.closePath(),s.fill(),s.strokeStyle="rgba(80, 150, 200, 0.5)",s.lineWidth=2,s.stroke(),Math.random()>.85){const m=s.createRadialGradient(l,c,0,l,c,n);m.addColorStop(0,"rgba(100, 200, 255, 0.3)"),m.addColorStop(1,"transparent"),s.fillStyle=m,s.fill()}}}function xO(s,e,t){s.fillStyle="#0a1a0f",s.fillRect(0,0,e,t),s.strokeStyle="#00ff66",s.lineWidth=2,s.shadowColor="#00ff66",s.shadowBlur=4;for(let n=20;n<t;n+=40){s.beginPath();let a=0;for(s.moveTo(a,n);a<e;){const i=20+Math.random()*60;if(a+=i,s.lineTo(a,n),Math.random()>.7&&a<e-40){const o=n+(Math.random()>.5?20:-20);s.lineTo(a,o),s.lineTo(a+20,o),a+=20}}s.stroke()}for(let n=20;n<e;n+=40)if(Math.random()>.5){s.beginPath(),s.moveTo(n,0);let a=0;for(;a<t;){const i=20+Math.random()*60;if(a+=i,s.lineTo(n,a),Math.random()>.7&&a<t-40){const o=n+(Math.random()>.5?20:-20);s.lineTo(o,a),s.lineTo(o,a+20),a+=20,s.lineTo(n,a)}}s.stroke()}s.shadowBlur=0,s.fillStyle="#111";for(let n=0;n<6;n++){const a=50+Math.random()*(e-100),i=50+Math.random()*(t-100),o=30+Math.random()*40,l=20+Math.random()*30;s.fillRect(a-o/2,i-l/2,o,l),s.fillStyle="#888";for(let c=0;c<o;c+=8)s.fillRect(a-o/2+c,i-l/2-4,4,4),s.fillRect(a-o/2+c,i+l/2,4,4);s.fillStyle="#111"}s.fillStyle="#997700";for(let n=0;n<50;n++){const a=Math.random()*e,i=Math.random()*t;s.beginPath(),s.arc(a,i,4,0,Math.PI*2),s.fill()}}function vO(s,e,t){const n=e/2,a=t/2;s.fillStyle="#2E4F2C",s.fillRect(0,0,e,t);for(let w=0;w<6e3;w++){const k=Math.random()*e,S=Math.random()*t,j=Math.random()>.5;s.fillStyle=j?"rgba(30, 50, 28, 0.3)":"rgba(55, 90, 52, 0.12)",s.fillRect(k,S,2,4)}const i=e*.05,o=30;s.strokeStyle="#ffffff",s.lineWidth=6,s.beginPath(),s.roundRect(i,i,e-i*2,t-i*2,o),s.stroke(),s.lineWidth=4,s.beginPath(),s.moveTo(i,a),s.lineTo(e-i,a),s.stroke();const l=Math.min(e,t)*.2;s.beginPath(),s.arc(n,a,l,0,Math.PI*2),s.stroke();const c=l*.6;s.fillStyle="#cc3333",s.beginPath(),s.arc(n,a,c,Math.PI,0),s.closePath(),s.fill(),s.fillStyle="#f0f0f0",s.beginPath(),s.arc(n,a,c,0,Math.PI),s.closePath(),s.fill(),s.fillStyle="#1a1a1a",s.fillRect(n-c,a-5,c*2,10),s.strokeStyle="#1a1a1a",s.lineWidth=4,s.beginPath(),s.arc(n,a,c,0,Math.PI*2),s.stroke();const d=c*.28;s.fillStyle="#f0f0f0",s.beginPath(),s.arc(n,a,d,0,Math.PI*2),s.fill(),s.strokeStyle="#1a1a1a",s.lineWidth=4,s.stroke(),s.fillStyle="#ffffff",s.beginPath(),s.arc(n,a,d*.5,0,Math.PI*2),s.fill();const m=e*.08,p=t*.05,f=l+t*.08;s.strokeStyle="#ffffff",s.lineWidth=3,s.strokeRect(n-m/2,a-f-p,m,p),s.strokeRect(n-m/2,a+f,m,p);const b=e*.05,y=i+15;s.lineWidth=3,s.beginPath(),s.moveTo(y,y+b),s.lineTo(y,y),s.lineTo(y+b,y),s.stroke(),s.beginPath(),s.moveTo(e-y-b,y),s.lineTo(e-y,y),s.lineTo(e-y,y+b),s.stroke(),s.beginPath(),s.moveTo(y,t-y-b),s.lineTo(y,t-y),s.lineTo(y+b,t-y),s.stroke(),s.beginPath(),s.moveTo(e-y-b,t-y),s.lineTo(e-y,t-y),s.lineTo(e-y,t-y-b),s.stroke()}function wO(s){const e=new Bn;e.name="galacticFloor";const t=[];kO(e);const n=SO(e);return jO(e,t),NO(e),CO(e),s.add(e),console.log("[Battlefield] Galactic group added to scene:",e),{group:e,stars:n,nebulas:t,time:0}}function kO(s){const e=document.createElement("canvas"),t=e.getContext("2d");e.width=2048,e.height=2048;const n=t.createRadialGradient(1024,1024,0,1024,1024,1024);n.addColorStop(0,"#2a1050"),n.addColorStop(.2,"#1a0a40"),n.addColorStop(.5,"#0d0525"),n.addColorStop(.8,"#060215"),n.addColorStop(1,"#020108"),t.fillStyle=n,t.fillRect(0,0,2048,2048),t.save(),t.translate(1024,1024);for(let m=0;m<3;m++){const p=m/3*Math.PI*2;t.save(),t.rotate(p);for(let f=0;f<1500;f++){const b=f/1500*800,y=b*.012,w=b*.15,k=Math.cos(y)*b+(Math.random()-.5)*w,S=Math.sin(y)*b+(Math.random()-.5)*w,j=1-b/800*.6,C=(1-b/800)*4+Math.random()*3,A=Math.floor(220*j+35),D=Math.floor(200*j+55),M=Math.floor(255);if(t.fillStyle=`rgba(${A}, ${D}, ${M}, ${j})`,t.beginPath(),t.arc(k,S,C,0,Math.PI*2),t.fill(),j>.7&&Math.random()>.5){const I=t.createRadialGradient(k,S,0,k,S,C*3);I.addColorStop(0,`rgba(${A}, ${D}, ${M}, 0.6)`),I.addColorStop(1,"transparent"),t.fillStyle=I,t.beginPath(),t.arc(k,S,C*3,0,Math.PI*2),t.fill()}}t.restore()}const a=t.createRadialGradient(0,0,0,0,0,200);a.addColorStop(0,"rgba(255, 255, 255, 1)"),a.addColorStop(.1,"rgba(255, 240, 220, 0.95)"),a.addColorStop(.3,"rgba(255, 200, 150, 0.7)"),a.addColorStop(.6,"rgba(200, 150, 255, 0.4)"),a.addColorStop(1,"transparent"),t.fillStyle=a,t.beginPath(),t.arc(0,0,200,0,Math.PI*2),t.fill(),t.restore();for(let m=0;m<1e3;m++){const p=Math.random()*2048,f=Math.random()*2048,b=.5+Math.random()*2.5,y=150+Math.random()*105,w=Math.random();let k,S,j;if(w<.6?(k=y,S=y,j=255):w<.8?(k=255,S=y,j=y*.7):(k=255,S=y*.6,j=y),t.fillStyle=`rgba(${k}, ${S}, ${j}, 1)`,t.beginPath(),t.arc(p,f,b,0,Math.PI*2),t.fill(),Math.random()>.85){const C=t.createRadialGradient(p,f,0,p,f,b*6);C.addColorStop(0,`rgba(${k}, ${S}, ${j}, 0.7)`),C.addColorStop(.5,`rgba(${k}, ${S}, ${j}, 0.2)`),C.addColorStop(1,"transparent"),t.fillStyle=C,t.beginPath(),t.arc(p,f,b*6,0,Math.PI*2),t.fill()}}const i=["#ff00ff","#00ffff","#ff6600","#6600ff"];for(let m=0;m<8;m++){const p=300+Math.random()*1448,f=300+Math.random()*1448,b=100+Math.random()*200,y=i[m%i.length],w=t.createRadialGradient(p,f,0,p,f,b);w.addColorStop(0,y+"40"),w.addColorStop(.5,y+"15"),w.addColorStop(1,"transparent"),t.fillStyle=w,t.beginPath(),t.arc(p,f,b,0,Math.PI*2),t.fill()}const o=new Jn(e);o.colorSpace=Va;const l=new tr(30,30),c=new We({map:o,side:ws}),d=new De(l,c);d.rotation.x=-Math.PI/2,d.position.y=.01,d.name="galaxyPlane",d.receiveShadow=!0,s.add(d),console.log("[Battlefield] Galaxy plane created:",d.position)}function SO(s){const e=new La,t=500,n=new Float32Array(t*3),a=new Float32Array(t*3);for(let l=0;l<t;l++){const c=Math.random()*Math.PI*2,d=Math.random()*14;n[l*3]=Math.cos(c)*d,n[l*3+1]=.05+Math.random()*.3,n[l*3+2]=Math.sin(c)*d;const m=Math.random();m<.4?(a[l*3]=.9,a[l*3+1]=.9,a[l*3+2]=1):m<.6?(a[l*3]=1,a[l*3+1]=.8,a[l*3+2]=.4):m<.8?(a[l*3]=1,a[l*3+1]=.4,a[l*3+2]=.8):(a[l*3]=.4,a[l*3+1]=1,a[l*3+2]=1)}e.setAttribute("position",new Ka(n,3)),e.setAttribute("color",new Ka(a,3));const i=new nm({size:.15,transparent:!0,opacity:.9,vertexColors:!0,blending:Zo,depthWrite:!1}),o=new dd(e,i);return o.name="galacticStars",o.renderOrder=5,s.add(o),o}function jO(s,e){const t=[16711935,65535,16737792,6684927,65382];for(let n=0;n<4;n++){const a=document.createElement("canvas"),i=a.getContext("2d");a.width=256,a.height=256;const o=i.createRadialGradient(128,128,0,128,128,128);o.addColorStop(0,"rgba(255, 255, 255, 0.6)"),o.addColorStop(.3,"rgba(255, 255, 255, 0.3)"),o.addColorStop(.6,"rgba(255, 255, 255, 0.1)"),o.addColorStop(1,"transparent"),i.fillStyle=o,i.fillRect(0,0,256,256);const l=new Jn(a),c=6+Math.random()*6,d=new tr(c,c),m=new We({map:l,color:t[n%t.length],transparent:!0,opacity:.25,blending:Zo,depthWrite:!1,side:ws}),p=new De(d,m);p.rotation.x=-Math.PI/2,p.position.set((Math.random()-.5)*20,.03+n*.01,(Math.random()-.5)*20),p.name=`nebula_${n}`,p.renderOrder=2+n,e.push(p),s.add(p)}}function CO(s){const e=new La,t=150,n=new Float32Array(t*3);for(let o=0;o<t;o++){const l=Math.random()*Math.PI*2,c=Math.random()*14;n[o*3]=Math.cos(l)*c,n[o*3+1]=.1+Math.random()*2,n[o*3+2]=Math.sin(l)*c}e.setAttribute("position",new Ka(n,3));const a=new nm({size:.15,color:8947967,transparent:!0,opacity:.5,blending:Zo,depthWrite:!1}),i=new dd(e,a);i.name="cosmicDust",s.add(i)}function NO(s){const e=new Xo(14.5,15.5,64),t=new We({color:4491519,transparent:!0,opacity:.6,side:ws,blending:Zo}),n=new De(e,t);n.rotation.x=-Math.PI/2,n.position.y=.02,n.name="portalRim",s.add(n);const a=new Xo(13.5,14.5,64),i=new We({color:8930559,transparent:!0,opacity:.3,side:ws,blending:Zo}),o=new De(a,i);o.rotation.x=-Math.PI/2,o.position.y=.01,o.name="portalInnerRim",s.add(o)}function uj(s,e,t){e&&(e.group.traverse(n=>{var a,i;n instanceof De?((a=n.geometry)==null||a.dispose(),n.material instanceof Ur?t(n.material):Array.isArray(n.material)&&n.material.forEach(o=>t(o))):n instanceof dd&&((i=n.geometry)==null||i.dispose(),n.material instanceof Ur&&n.material.dispose())}),s.remove(e.group))}function AO(s,e){s.time+=e;const t=s.group.getObjectByName("galaxyPlane");t&&(t.rotation.z=s.time*.02),s.nebulas.forEach((o,l)=>{o.rotation.z+=e*.03*(l%2===0?1:-1),o.position.x+=Math.sin(s.time*.2+l*2)*e*.1,o.position.z+=Math.cos(s.time*.15+l*2)*e*.1,Math.abs(o.position.x)>12&&(o.position.x*=.9),Math.abs(o.position.z)>12&&(o.position.z*=.9);const c=o.material;c.opacity=.15+Math.sin(s.time*.5+l)*.1});const n=s.group.getObjectByName("portalRim");if(n){const o=n.material;o.opacity=.5+Math.sin(s.time*2)*.3}const a=s.group.getObjectByName("portalInnerRim");if(a){const o=a.material;o.opacity=.3+Math.sin(s.time*3+1)*.2}const i=s.group.getObjectByName("cosmicDust");if(i){const o=i.geometry.attributes.position.array;for(let l=0;l<o.length;l+=3)if(o[l+1]+=e*.15,o[l+1]>3){o[l+1]=.1;const c=Math.random()*Math.PI*2,d=Math.random()*14;o[l]=Math.cos(c)*d,o[l+2]=Math.sin(c)*d}i.geometry.attributes.position.needsUpdate=!0}if(s.stars){const o=s.stars.material;o.opacity=.7+Math.sin(s.time*4)*.2,s.stars.rotation.y=s.time*.01}}const dj=new yt,hj=new yt;function pj(){return{phase:"dawn",sunPosition:new yt(50,10,-60),moonPosition:new yt(-40,15,-50),ambientColor:10075101,ambientIntensity:.6,hemiSkyColor:6724044,hemiGroundColor:4478310,hemiIntensity:.75,mainLightColor:12312063,mainLightIntensity:1.1,fogColor:4487082,fogDensity:.008,skyColor:3368618,starsOpacity:.2,moonOpacity:.3,sunOpacity:.9,lampIntensity:.5,windowEmissive:.3}}function mj(){return{phase:"dusk",sunPosition:new yt(-50,8,-60),moonPosition:new yt(40,12,-50),ambientColor:7833787,ambientIntensity:.55,hemiSkyColor:4482747,hemiGroundColor:3359829,hemiIntensity:.65,mainLightColor:10075118,mainLightIntensity:.9,fogColor:2245802,fogDensity:.01,skyColor:2245802,starsOpacity:.3,moonOpacity:.4,sunOpacity:.8,lampIntensity:1.5,windowEmissive:.5}}function Zg(){return{phase:"night",sunPosition:new yt(30,-20,-50),moonPosition:new yt(-30,35,-50),ambientColor:5596842,ambientIntensity:.5,hemiSkyColor:3359863,hemiGroundColor:2236996,hemiIntensity:.6,mainLightColor:13426175,mainLightIntensity:.9,fogColor:662058,fogDensity:.012,skyColor:662058,starsOpacity:.9,moonOpacity:1,sunOpacity:0,lampIntensity:2.5,windowEmissive:.8}}function Qg(){return{phase:"day",sunPosition:new yt(30,50,-30),moonPosition:new yt(-30,-20,-50),ambientColor:16777215,ambientIntensity:.85,hemiSkyColor:5939433,hemiGroundColor:5596791,hemiIntensity:1,mainLightColor:16777198,mainLightIntensity:1.5,fogColor:6990048,fogDensity:.005,skyColor:4886745,starsOpacity:0,moonOpacity:0,sunOpacity:1,lampIntensity:0,windowEmissive:.1}}function Ih(s,e,t,n){const a=(o,l)=>o+(l-o)*t,i=(o,l)=>{const c=o>>16&255,d=o>>8&255,m=o&255,p=l>>16&255,f=l>>8&255,b=l&255,y=Math.round(a(c,p)),w=Math.round(a(d,f)),k=Math.round(a(m,b));return y<<16|w<<8|k};return dj.lerpVectors(s.sunPosition,e.sunPosition,t),hj.lerpVectors(s.moonPosition,e.moonPosition,t),{phase:n,sunPosition:dj,moonPosition:hj,ambientColor:i(s.ambientColor,e.ambientColor),ambientIntensity:a(s.ambientIntensity,e.ambientIntensity),hemiSkyColor:i(s.hemiSkyColor,e.hemiSkyColor),hemiGroundColor:i(s.hemiGroundColor,e.hemiGroundColor),hemiIntensity:a(s.hemiIntensity,e.hemiIntensity),mainLightColor:i(s.mainLightColor,e.mainLightColor),mainLightIntensity:a(s.mainLightIntensity,e.mainLightIntensity),fogColor:i(s.fogColor,e.fogColor),fogDensity:a(s.fogDensity,e.fogDensity),skyColor:i(s.skyColor,e.skyColor),starsOpacity:a(s.starsOpacity,e.starsOpacity),moonOpacity:a(s.moonOpacity,e.moonOpacity),sunOpacity:a(s.sunOpacity,e.sunOpacity),lampIntensity:a(s.lampIntensity,e.lampIntensity),windowEmissive:a(s.windowEmissive,e.windowEmissive)}}function MO(s){if(s>=5&&s<6){const e=s-5;return Ih(Zg(),pj(),e,"dawn")}else if(s>=6&&s<7){const e=s-6;return Ih(pj(),Qg(),e,"dawn")}else{if(s>=7&&s<18)return Qg();if(s>=18&&s<19.5){const e=(s-18)/1.5;return Ih(Qg(),mj(),e,"dusk")}else if(s>=19.5&&s<21){const e=(s-19.5)/1.5;return Ih(mj(),Zg(),e,"dusk")}else return Zg()}}function TO(){const s=document.createElement("canvas"),e=s.getContext("2d");s.width=512,s.height=512;const t=256,n=256,a=e.createRadialGradient(t,n,50,t,n,256);a.addColorStop(0,"rgba(255, 255, 200, 1)"),a.addColorStop(.2,"rgba(255, 240, 150, 0.8)"),a.addColorStop(.4,"rgba(255, 220, 100, 0.4)"),a.addColorStop(.7,"rgba(255, 200, 80, 0.1)"),a.addColorStop(1,"rgba(255, 180, 50, 0)"),e.fillStyle=a,e.fillRect(0,0,512,512);const i=e.createRadialGradient(t,n,0,t,n,80);i.addColorStop(0,"rgba(255, 255, 255, 1)"),i.addColorStop(.5,"rgba(255, 255, 220, 1)"),i.addColorStop(1,"rgba(255, 240, 150, 0.8)"),e.fillStyle=i,e.beginPath(),e.arc(t,n,80,0,Math.PI*2),e.fill(),e.beginPath(),e.arc(t,n,60,0,Math.PI*2),e.fillStyle="#ffffee",e.fill();const o=new Jn(s),l=new Yn({map:o,transparent:!0,depthWrite:!1,blending:Zo}),c=new Hn(l);return c.position.set(30,50,-30),c.scale.set(50,50,1),c.name="sun",c.visible=!1,c}function EO(){const s=document.createElement("canvas"),e=s.getContext("2d");s.width=512,s.height=512;const t=256,n=256,a=e.createRadialGradient(t,n,60,t,n,256);a.addColorStop(0,"rgba(200, 220, 255, 1)"),a.addColorStop(.2,"rgba(180, 200, 240, 0.8)"),a.addColorStop(.4,"rgba(150, 180, 220, 0.5)"),a.addColorStop(.7,"rgba(120, 150, 200, 0.2)"),a.addColorStop(1,"rgba(100, 130, 180, 0)"),e.fillStyle=a,e.fillRect(0,0,512,512);const i=e.createRadialGradient(t,n,0,t,n,100);i.addColorStop(0,"rgba(255, 255, 255, 1)"),i.addColorStop(.5,"rgba(230, 240, 255, 0.9)"),i.addColorStop(1,"rgba(200, 220, 255, 0.3)"),e.fillStyle=i,e.beginPath(),e.arc(t,n,100,0,Math.PI*2),e.fill(),e.beginPath(),e.arc(t,n,70,0,Math.PI*2),e.fillStyle="#e8eeff",e.fill(),e.fillStyle="rgba(180, 190, 210, 0.6)",e.beginPath(),e.arc(t-25,n-20,18,0,Math.PI*2),e.fill(),e.beginPath(),e.arc(t+25,n+15,12,0,Math.PI*2),e.fill(),e.beginPath(),e.arc(t-5,n+30,10,0,Math.PI*2),e.fill();const o=new Jn(s),l=new Yn({map:o,transparent:!0,depthWrite:!1,blending:Zo}),c=new Hn(l);return c.position.set(-30,35,-50),c.scale.set(40,40,1),c.name="moon",c}function _O(s=1){const e=new Bn,t=new rt({color:16777215,transparent:!0,opacity:.85,roughness:1,metalness:0,depthWrite:!1}),n=new Ut(1,16,12);return[{x:0,y:0,z:0,scale:1.2},{x:-1,y:.1,z:.2,scale:1},{x:1,y:.15,z:-.1,scale:1.1},{x:-.5,y:.3,z:.4,scale:.8},{x:.6,y:.35,z:.3,scale:.9},{x:-1.5,y:-.1,z:0,scale:.7},{x:1.5,y:-.05,z:.1,scale:.75},{x:0,y:.4,z:0,scale:.7}].forEach(i=>{const o=new De(n,t);o.position.set(i.x*s,i.y*s,i.z*s),o.scale.setScalar(i.scale*s),e.add(o)}),e.userData.material=t,e}function DO(){const s=new Bn;s.name="clouds";const e=[];return[{x:-25,y:35,z:-20,scale:3.5,speed:.8},{x:15,y:40,z:-35,scale:4,speed:1},{x:-40,y:38,z:10,scale:3,speed:.9},{x:30,y:42,z:15,scale:3.8,speed:1.1},{x:0,y:36,z:-45,scale:3.2,speed:.85},{x:-15,y:44,z:30,scale:2.8,speed:1.05},{x:45,y:37,z:-10,scale:3.6,speed:.95},{x:-35,y:41,z:-30,scale:2.5,speed:1.15}].forEach((n,a)=>{const i=_O(n.scale);i.position.set(n.x,n.y,n.z),i.userData.baseX=n.x,i.userData.speed=n.speed,i.userData.index=a,s.add(i),e.push(i)}),{group:s,clouds:e,time:0}}function PO(s,e){s.time+=e,s.clouds.forEach(t=>{const n=t.userData.baseX,a=t.userData.speed,i=t.userData.index,o=60,l=.015*a,c=i*.7,d=Math.sin(s.time*l+c)*o*.5;t.position.x=n+d;const m=.3*a,p=.5;t.position.y+=Math.sin(s.time*m+c)*p*e})}function RO(s,e){s.clouds.forEach(t=>{const n=t.userData.material;n&&(n.opacity=e*.85)})}function LO(){const s=new La,e=300,t=new Float32Array(e*3);for(let i=0;i<e;i++){const o=Math.random()*Math.PI*2,l=Math.random()*Math.PI*.5,c=80+Math.random()*40;t[i*3]=c*Math.sin(l)*Math.cos(o),t[i*3+1]=c*Math.cos(l)+20,t[i*3+2]=c*Math.sin(l)*Math.sin(o)}s.setAttribute("position",new Ka(t,3));const n=new nm({color:16777215,size:.5,transparent:!0,opacity:.8}),a=new dd(s,n);return a.name="stars",a}function OO(s){const e=IO(s),t=FO(s),{house:n,windowMaterials:a}=zO(s),{lamps:i,lampLights:o}=$O(s);return{trees:e,bushes:t,house:n,lamps:i,lampLights:o,windowMaterials:a}}const fj=[{x:-20,z:-18,scale:1.2},{x:-22,z:-8,scale:1.4},{x:-20,z:5,scale:1.1},{x:18,z:-20,scale:1.3},{x:22,z:-5,scale:1},{x:20,z:10,scale:1.5},{x:-8,z:-22,scale:1.25},{x:5,z:-20,scale:1.35}];function IO(s){const e=new Bn;e.name="trees_instanced";const t=fj.length,n=new rt({color:4863784,roughness:.9}),a=new rt({color:2972199,roughness:.8}),i=new Un(.3,.5,3,8),o=new Ut(2,8,6),l=new Ut(1.5,8,6),c=new Ji(i,n,t),d=new Ji(o,a,t),m=new Ji(l,a,t);c.castShadow=!0,c.receiveShadow=!0,d.castShadow=!0,m.castShadow=!0,c.name="trees_trunks",d.name="trees_foliage1",m.name="trees_foliage2";const p=new Vo,f=new yt,b=new Ko,y=new yt;return fj.forEach((w,k)=>{const S=w.scale,j=Math.random()*Math.PI*2;f.set(w.x,1.5*S,w.z),b.setFromEuler(new hA(0,j,0)),y.set(S,S,S),p.compose(f,b,y),c.setMatrixAt(k,p),f.set(w.x,4*S,w.z),y.set(S,S*.8,S),p.compose(f,b,y),d.setMatrixAt(k,p),f.set(w.x,5.5*S,w.z),y.set(S,S,S),p.compose(f,b,y),m.setMatrixAt(k,p)}),c.instanceMatrix.needsUpdate=!0,d.instanceMatrix.needsUpdate=!0,m.instanceMatrix.needsUpdate=!0,e.add(c),e.add(d),e.add(m),s.add(e),e}const BO=[{x:-17,z:-14},{x:-16,z:0},{x:-17,z:12},{x:17,z:-15},{x:16,z:3},{x:17,z:15},{x:-12,z:-17},{x:0,z:-17},{x:12,z:-17},{x:-10,z:17},{x:3,z:17},{x:14,z:17},{x:-25,z:8},{x:-28,z:12}];function FO(s){const e=[],t=m=>{const p=Math.sin(m)*1e4;return p-Math.floor(p)};BO.forEach((m,p)=>{const f=2+Math.floor(t(p*100)*2);for(let b=0;b<f;b++){const y=p*100+b,w=.6+t(y)*.4,k=(t(y+1)-.5)*.8,S=(t(y+2)-.5)*.8,j=.7+t(y+3)*.2;e.push({x:m.x+k,y:w*.7,z:m.z+S,scaleX:w,scaleY:w*j,scaleZ:w})}});const n=new rt({color:4024887,roughness:.85}),a=new Ut(1,8,6),i=new Ji(a,n,e.length);i.castShadow=!0,i.receiveShadow=!0,i.name="bushes_instanced";const o=new Vo,l=new yt,c=new Ko,d=new yt;return e.forEach((m,p)=>{l.set(m.x,m.y,m.z),c.identity(),d.set(m.scaleX,m.scaleY,m.scaleZ),o.compose(l,c,d),i.setMatrixAt(p,o)}),i.instanceMatrix.needsUpdate=!0,s.add(i),i}function zO(s){const e=new Bn,t=[],n=new sn(6,4,5),a=new rt({color:13935988,roughness:.8}),i=new De(n,a);i.position.y=2,i.castShadow=!0,i.receiveShadow=!0,e.add(i);const o=new uc(5,3,4),l=new rt({color:9127187,roughness:.7}),c=new De(o,l);c.position.y=5.5,c.rotation.y=Math.PI/4,c.castShadow=!0,e.add(c);const d=new sn(1.2,2,.1),m=new rt({color:6045747,roughness:.6}),p=new De(d,m);p.position.set(0,1,2.55),e.add(p);const f=new sn(.8,.8,.1),b=new rt({color:16777130,emissive:16755268,emissiveIntensity:.5,roughness:.3});t.push(b);const y=new De(f,b);y.position.set(-1.5,2.5,2.55),e.add(y);const w=new De(f,b);w.position.set(1.5,2.5,2.55),e.add(w);const k=new sn(.8,2,.8),S=new rt({color:9127187,roughness:.8}),j=new De(k,S);return j.position.set(1.5,6,-1),j.castShadow=!0,e.add(j),e.position.set(-25,0,10),e.rotation.y=Math.PI/6,e.name="house",s.add(e),{house:e,windowMaterials:t}}const gj=[{x:-16,z:-16},{x:16,z:-16},{x:-16,z:16},{x:16,z:16}];function $O(s){const e=new Bn;e.name="lamps_instanced";const t=[],n=gj.length,a=new rt({color:3355443,roughness:.5,metalness:.5}),i=new rt({color:2236962,roughness:.4,metalness:.6}),o=new rt({color:16772778,emissive:16755268,emissiveIntensity:2,roughness:.2}),l=new Un(.1,.15,5,8),c=new Un(.05,.05,1,8),d=new Un(.4,.3,.6,8),m=new Ut(.25,8,8),p=new Ji(l,a,n),f=new Ji(c,a,n),b=new Ji(d,i,n),y=new Ji(m,o,n);p.castShadow=!0,p.name="lamps_poles",f.name="lamps_arms",b.name="lamps_housings",y.name="lamps_bulbs";const w=new Vo,k=new yt,S=new Ko,j=new yt(1,1,1);return gj.forEach((C,A)=>{k.set(C.x,2.5,C.z),S.identity(),w.compose(k,S,j),p.setMatrixAt(A,w),k.set(C.x+.4,4.8,C.z),S.setFromEuler(new hA(0,0,Math.PI/2)),w.compose(k,S,j),f.setMatrixAt(A,w),k.set(C.x+.8,4.8,C.z),S.identity(),w.compose(k,S,j),b.setMatrixAt(A,w),k.set(C.x+.8,4.5,C.z),w.compose(k,S,j),y.setMatrixAt(A,w);const D=new aA(16755285,1.5,15);D.position.set(C.x,5,C.z),t.push(D),s.add(D)}),p.instanceMatrix.needsUpdate=!0,f.instanceMatrix.needsUpdate=!0,b.instanceMatrix.needsUpdate=!0,y.instanceMatrix.needsUpdate=!0,e.add(p),e.add(f),e.add(b),e.add(y),s.add(e),{lamps:e,lampLights:t}}function HO(s){const e=new tr(80,80),t=new rt({color:2972199,roughness:.9,metalness:0}),n=new De(e,t);return n.rotation.x=-Math.PI/2,n.position.y=-.05,n.receiveShadow=!0,n.name="grass",s.add(n),n}class UO{constructor(e){W(this,"scene");W(this,"ground",null);W(this,"gridHelper",null);W(this,"sun",null);W(this,"moon",null);W(this,"stars",null);W(this,"ambientLight",null);W(this,"hemiLight",null);W(this,"mainLight",null);W(this,"fillLight",null);W(this,"lampLights",[]);W(this,"windowMaterials",[]);W(this,"trees",null);W(this,"bushes",null);W(this,"house",null);W(this,"lamps",null);W(this,"grass",null);W(this,"baseFogDensity",.01);W(this,"brightness",1);W(this,"skyColorOverride",null);W(this,"currentFloorStyle","concrete");W(this,"galacticState",null);W(this,"cloudState",null);W(this,"cloudsVisible",!0);W(this,"debugHourOverride",null);W(this,"tempColor",new Bt);this.scene=e}setGridVisible(e){this.gridHelper&&(this.gridHelper.visible=e)}create(){this.createGround(),this.grass=HO(this.scene),this.createGrid(),this.sun=TO(),this.scene.add(this.sun),this.moon=EO(),this.scene.add(this.moon),this.stars=LO(),this.scene.add(this.stars),this.cloudState=DO(),this.scene.add(this.cloudState.group);const e=OO(this.scene);this.trees=e.trees,this.bushes=e.bushes,this.house=e.house,this.lamps=e.lamps,this.lampLights=e.lampLights,this.windowMaterials=e.windowMaterials,this.createLighting(),this.createFog(),this.updateTimeOfDay()}updateTimeOfDay(){const e=MO(this.getCurrentHour());this.applyTimeConfig(e)}getCurrentHour(){if(this.debugHourOverride!==null)return this.debugHourOverride;const e=new Date;return e.getHours()+e.getMinutes()/60}setDebugTime(e){this.debugHourOverride=e,this.updateTimeOfDay(),console.log(`[Battlefield] Time set to: ${e!==null?`${e}:00`:"real time"}`)}setTimeMode(e){const n={auto:null,day:12,night:23,dawn:6,dusk:19.5}[e]??null;this.debugHourOverride=n,this.updateTimeOfDay(),console.log(`[Battlefield] Time mode set to: ${e} (${n!==null?`${n}:00`:"real time"})`)}setTerrainConfig(e){this.trees&&(this.trees.visible=e.showTrees),this.bushes&&(this.bushes.visible=e.showBushes),this.house&&(this.house.visible=e.showHouse),this.lamps&&(this.lamps.visible=e.showLamps),this.lampLights.forEach(t=>{t.visible=e.showLamps}),this.grass&&(this.grass.visible=e.showGrass),e.showClouds!==void 0&&(this.cloudsVisible=e.showClouds,this.cloudState&&(this.cloudState.group.visible=e.showClouds)),this.baseFogDensity=e.fogDensity*.008,e.brightness!==void 0&&(this.brightness=e.brightness),e.skyColor!==void 0&&(this.skyColorOverride=e.skyColor),this.updateTimeOfDay()}setFloorStyle(e,t=!1){if(this.currentFloorStyle===e&&!t)return;const n=this.currentFloorStyle;if(this.currentFloorStyle=e,typeof window<"u"&&window.__TIDE_MEMORY_DEBUG__&&console.log(`[Battlefield] Memory: Switching floor from ${n} to ${e}`),n==="galactic"&&(uj(this.scene,this.galacticState,this.disposeMaterial.bind(this)),this.galacticState=null,this.ground&&(this.ground.visible=!0)),this.ground){const a=this.ground.material;if(e==="galactic")console.log("[Battlefield] Creating galactic floor..."),this.ground.visible=!1,this.galacticState=wO(this.scene),console.log("[Battlefield] Galactic elements created");else{this.ground.visible=!0,a.transparent=!1,a.opacity=1,a.side=uA,a.depthWrite=!0,this.ground.renderOrder=0;const i=a.map;if(e==="none")a.map=null,a.color.setHex(2972199),a.roughness=.9,a.metalness=0,a.emissive.setHex(0),a.emissiveIntensity=0,a.needsUpdate=!0;else{const o=cj(e);o.wrapS=Oo,o.wrapT=Oo,o.repeat.set(e==="pokemon-stadium"?1:6,e==="pokemon-stadium"?1:6),a.map=o,a.needsUpdate=!0}switch(i&&(i.dispose(),typeof window<"u"&&window.__TIDE_MEMORY_DEBUG__&&console.log("[Battlefield] Memory: Disposed old floor texture")),e){case"none":break;case"metal":a.color.setHex(8947865),a.roughness=.4,a.metalness=.8,a.emissive.setHex(0),a.emissiveIntensity=0;break;case"hex":a.color.setHex(4482696),a.roughness=.6,a.metalness=.4,a.emissive.setHex(1122867),a.emissiveIntensity=.2;break;case"circuit":a.color.setHex(2245683),a.roughness=.7,a.metalness=.3,a.emissive.setHex(13090),a.emissiveIntensity=.4;break;case"pokemon-stadium":a.color.setHex(11184810),a.roughness=1,a.metalness=0,a.emissive.setHex(0),a.emissiveIntensity=0;break;default:a.color.setHex(5592405),a.roughness=.8,a.metalness=.1,a.emissive.setHex(0),a.emissiveIntensity=0}}}console.log(`[Battlefield] Floor style set to: ${e}`)}updateGalacticAnimation(e){this.currentFloorStyle!=="galactic"||!this.galacticState||AO(this.galacticState,e)}updateCloudAnimation(e){!this.cloudState||!this.cloudsVisible||PO(this.cloudState,e)}disposeMaterial(e){var t;(e instanceof We||e instanceof rt||e instanceof Yn)&&((t=e.map)==null||t.dispose()),e.dispose()}applyTimeConfig(e){const t=this.skyColorOverride?parseInt(this.skyColorOverride.replace("#",""),16):e.skyColor;if(this.scene.background instanceof Bt?this.scene.background.setHex(t):this.scene.background=this.tempColor.setHex(t).clone(),this.scene.fog instanceof tS){const n=this.skyColorOverride?parseInt(this.skyColorOverride.replace("#",""),16):e.fogColor;this.scene.fog.color.setHex(n);const a=this.baseFogDensity>0?this.baseFogDensity/.008:0;this.scene.fog.density=e.fogDensity*a}if(this.sun&&(this.sun.position.copy(e.sunPosition),this.sun.material.opacity=e.sunOpacity,this.sun.visible=e.sunOpacity>.01),this.moon&&(this.moon.position.copy(e.moonPosition),this.moon.material.opacity=e.moonOpacity,this.moon.visible=e.moonOpacity>.01),this.stars&&(this.stars.material.opacity=e.starsOpacity,this.stars.visible=e.starsOpacity>.01),this.ambientLight&&(this.ambientLight.color.setHex(e.ambientColor),this.ambientLight.intensity=e.ambientIntensity*this.brightness),this.hemiLight&&(this.hemiLight.color.setHex(e.hemiSkyColor),this.hemiLight.groundColor.setHex(e.hemiGroundColor),this.hemiLight.intensity=e.hemiIntensity*this.brightness),this.mainLight&&(this.mainLight.color.setHex(e.mainLightColor),this.mainLight.intensity=e.mainLightIntensity*this.brightness,e.sunOpacity>e.moonOpacity?this.mainLight.position.copy(e.sunPosition):this.mainLight.position.copy(e.moonPosition)),this.lampLights.forEach(n=>{n.intensity=e.lampIntensity}),this.windowMaterials.forEach(n=>{n.emissiveIntensity=e.windowEmissive}),this.cloudState&&this.cloudsVisible){let n;switch(e.phase){case"day":n=1;break;case"dawn":case"dusk":n=.7;break;case"night":n=.2;break;default:n=1}RO(this.cloudState,n)}}getGround(){return this.ground}createGround(){const e=new tr(30,30),t=cj(this.currentFloorStyle);t.wrapS=Oo,t.wrapT=Oo,t.repeat.set(this.currentFloorStyle==="galactic"?1:6,this.currentFloorStyle==="galactic"?1:6);const n=new rt({map:t,color:5592405,roughness:.8,metalness:.1});this.ground=new De(e,n),this.ground.rotation.x=-Math.PI/2,this.ground.receiveShadow=!0,this.ground.name="ground",this.scene.add(this.ground)}createGrid(){this.gridHelper=new qD(30,30,2763322,1710634),this.gridHelper.position.y=.01,this.scene.add(this.gridHelper)}createLogo(){const t=new tx().load("/assets/textures/logo-blanco.png"),n=10,a=4,i=new tr(n,a),o=new We({map:t,transparent:!0,opacity:.8,side:ws,depthWrite:!1}),l=new De(i,o);l.rotation.x=-Math.PI/2,l.position.set(0,.02,0),l.name="tideLogo",this.scene.add(l)}createFog(){this.scene.fog=new tS(662058,.01),this.scene.background=new Bt(662058)}createLighting(){this.ambientLight=new ax(16777215,.6),this.scene.add(this.ambientLight),this.hemiLight=new YD(16777198,5596791,.7),this.hemiLight.position.set(0,20,0),this.scene.add(this.hemiLight),this.mainLight=new sc(16777215,1.2),this.mainLight.position.set(30,50,-30),this.mainLight.castShadow=!0,this.mainLight.shadow.mapSize.width=2048,this.mainLight.shadow.mapSize.height=2048,this.mainLight.shadow.camera.near=.5,this.mainLight.shadow.camera.far=150,this.mainLight.shadow.camera.left=-35,this.mainLight.shadow.camera.right=35,this.mainLight.shadow.camera.top=35,this.mainLight.shadow.camera.bottom=-35,this.scene.add(this.mainLight),this.fillLight=new sc(16777215,.6),this.fillLight.position.set(-10,15,10),this.scene.add(this.fillLight);const e=new sc(11193599,.5);e.position.set(0,20,30),this.scene.add(e)}dispose(){var t,n;uj(this.scene,this.galacticState,this.disposeMaterial.bind(this)),this.galacticState=null;const e=this.scene.getObjectByName("tideLogo");e&&((t=e.geometry)==null||t.dispose(),this.disposeMaterial(e.material),this.scene.remove(e)),this.ground&&(this.ground.geometry.dispose(),this.disposeMaterial(this.ground.material),this.scene.remove(this.ground)),this.gridHelper&&(this.gridHelper.geometry.dispose(),this.gridHelper.material instanceof Ur&&this.gridHelper.material.dispose(),this.scene.remove(this.gridHelper)),this.grass&&(this.grass.geometry.dispose(),this.disposeMaterial(this.grass.material),this.scene.remove(this.grass)),this.sun&&(this.disposeMaterial(this.sun.material),this.scene.remove(this.sun)),this.moon&&(this.disposeMaterial(this.moon.material),this.scene.remove(this.moon)),this.stars&&(this.stars.geometry.dispose(),this.stars.material.dispose(),this.scene.remove(this.stars)),this.trees&&(this.disposeGroup(this.trees),this.scene.remove(this.trees),this.trees=null),this.bushes&&(this.bushes.geometry.dispose(),this.bushes.material.dispose(),this.scene.remove(this.bushes),this.bushes=null),this.house&&(this.disposeGroup(this.house),this.scene.remove(this.house),this.house=null),this.lamps&&(this.disposeGroup(this.lamps),this.scene.remove(this.lamps),this.lamps=null);for(const a of this.lampLights)this.scene.remove(a),a.dispose();this.lampLights=[],this.windowMaterials=[],this.ambientLight&&this.scene.remove(this.ambientLight),this.hemiLight&&this.scene.remove(this.hemiLight),this.mainLight&&((n=this.mainLight.shadow.map)==null||n.dispose(),this.scene.remove(this.mainLight)),this.fillLight&&this.scene.remove(this.fillLight)}disposeGroup(e){e.traverse(t=>{var n;t instanceof De&&((n=t.geometry)==null||n.dispose(),t.material instanceof Ur?this.disposeMaterial(t.material):Array.isArray(t.material)&&t.material.forEach(a=>this.disposeMaterial(a)))})}}function Et(s,e,t,n,a={},i="global"){return{id:s,name:e,description:t,key:n,modifiers:a,enabled:!0,context:i}}const Jg=[Et("toggle-commander","Toggle Commander","Open/close Commander View","k",{ctrl:!0}),Et("toggle-commander-tab","Toggle Commander (Tab)","Open/close Commander View with Tab","Tab",{}),Et("spawn-agent","Spawn Agent","Open new agent spawn modal","n",{alt:!0}),Et("select-agent-1","Select Agent 1","Select first agent","1",{ctrl:!0}),Et("select-agent-2","Select Agent 2","Select second agent","2",{ctrl:!0}),Et("select-agent-3","Select Agent 3","Select third agent","3",{ctrl:!0}),Et("select-agent-4","Select Agent 4","Select fourth agent","4",{ctrl:!0}),Et("select-agent-5","Select Agent 5","Select fifth agent","5",{ctrl:!0}),Et("select-agent-6","Select Agent 6","Select sixth agent","6",{ctrl:!0}),Et("select-agent-7","Select Agent 7","Select seventh agent","7",{ctrl:!0}),Et("select-agent-8","Select Agent 8","Select eighth agent","8",{ctrl:!0}),Et("select-agent-9","Select Agent 9","Select ninth agent","9",{ctrl:!0}),Et("delete-selected","Delete Selected","Remove selected agents","Delete",{}),Et("delete-selected-backspace","Delete Selected (Backspace)","Remove selected agents","Backspace",{}),Et("deselect-all","Deselect All","Clear agent selection","Escape",{}),Et("open-terminal","Open Terminal","Open terminal for selected agent","Space",{}),Et("dashboard-selector-toggle","Dashboard Selector","Enable dashboard card selector",",",{}),Et("dashboard-vim-left","Dashboard Left","Move dashboard selector left","h",{}),Et("dashboard-vim-down","Dashboard Down","Move dashboard selector down","j",{}),Et("dashboard-vim-up","Dashboard Up","Move dashboard selector up","k",{}),Et("dashboard-vim-right","Dashboard Right","Move dashboard selector right","l",{}),Et("next-agent","Next Agent","Select next agent on battlefield","l",{alt:!0}),Et("prev-agent","Previous Agent","Select previous agent on battlefield","h",{alt:!0}),Et("next-working-agent","Next Working Agent","Select next working agent on battlefield","l",{alt:!0,shift:!0}),Et("prev-working-agent","Previous Working Agent","Select previous working agent on battlefield","h",{alt:!0,shift:!0}),Et("next-message","Next Message","Navigate to next message in terminal","j",{alt:!0}),Et("prev-message","Previous Message","Navigate to previous message in terminal","k",{alt:!0}),Et("page-down-messages","Page Down Messages","Jump down 10 messages in terminal","d",{alt:!0,shift:!0}),Et("page-up-messages","Page Up Messages","Jump up 10 messages in terminal","u",{alt:!0}),Et("next-agent-terminal","Next Agent (Terminal)","Switch to next agent in terminal","l",{alt:!0}),Et("prev-agent-terminal","Previous Agent (Terminal)","Switch to previous agent in terminal","h",{alt:!0}),Et("activate-message","Activate Message","Click on interactive element in selected message","Space",{}),Et("toggle-file-explorer","Toggle File Explorer","Open/close file explorer","e",{alt:!0}),Et("file-explorer-close-tab","Close File Tab","Close active file tab in explorer","w",{alt:!0}),Et("toggle-spotlight","Toggle Spotlight","Open/close global search","p",{alt:!0}),Et("open-database","Open Database","Open last used database query builder","d",{alt:!0}),Et("toggle-2d-view","Cycle View Mode","Cycle between 3D, 2D, and Dashboard views","2",{alt:!0}),Et("commander-close","Close Commander","Close Commander View","Escape",{},"commander"),Et("commander-vim-left","Navigate Left","Move focus left (Vim H)","h",{alt:!0},"commander"),Et("commander-vim-down","Navigate Down","Move focus down (Vim J)","j",{alt:!0},"commander"),Et("commander-vim-up","Navigate Up","Move focus up (Vim K)","k",{alt:!0},"commander"),Et("commander-vim-right","Navigate Right","Move focus right (Vim L)","l",{alt:!0},"commander"),Et("commander-expand","Expand/Collapse","Toggle agent expansion","o",{alt:!0},"commander"),Et("commander-new-agent","New Agent","Open spawn form in commander","n",{alt:!0},"commander"),Et("commander-next-tab","Next Tab","Switch to next area tab","Tab",{},"commander"),Et("commander-prev-tab","Previous Tab","Switch to previous area tab","Tab",{shift:!0},"commander"),Et("toolbox-close","Close Toolbox","Close Settings panel","Escape",{},"toolbox")];function vt(s,e){if(!e||!e.enabled)return!1;const{ctrl:t,alt:n,shift:a}=e.modifiers,i=t?s.ctrlKey||s.metaKey:!s.ctrlKey&&!s.metaKey,o=n?s.altKey:!s.altKey,l=a?s.shiftKey:!s.shiftKey;let c;if(t?c=(s.ctrlKey||s.metaKey)&&o&&l:c=i&&o&&l,!c)return!1;const d=e.key;if(d.length===1&&/^[a-zA-Z]$/.test(d)){const p=`Key${d.toUpperCase()}`;return s.code===p}if(d.length===1&&/^[0-9]$/.test(d)){const p=`Digit${d}`;return s.code===p}return d==="Space"||d===" "?s.code==="Space":s.key===d}function Go(s){const e=[];if(s.modifiers.ctrl){const n=navigator.platform.toUpperCase().indexOf("MAC")>=0;e.push(n?"⌘":"Ctrl")}if(s.modifiers.alt){const n=navigator.platform.toUpperCase().indexOf("MAC")>=0;e.push(n?"⌥":"Alt")}s.modifiers.shift&&e.push("Shift"),s.modifiers.meta&&e.push("⌘");let t=s.key;return t===" "?t="Space":t.length===1&&(t=t.toUpperCase()),e.push(t),e.join("+")}function GO(s,e,t,n){return s.filter(a=>{if(a.id===t||!a.enabled||n&&a.context!=="global"&&a.context!==n)return!1;const i=m=>m===" "||m==="Space"?"Space":m.length===1?m.toLowerCase():m,o=i(a.key),l=i(e.key);if(o!==l)return!1;const c=a.modifiers,d=e.modifiers;return(c.ctrl||!1)===(d.ctrl||!1)&&(c.alt||!1)===(d.alt||!1)&&(c.shift||!1)===(d.shift||!1)&&(c.meta||!1)===(d.meta||!1)})}class Bh{constructor(e=200){W(this,"lastClickTime",0);W(this,"lastClickId",null);W(this,"clickTimer",null);W(this,"threshold");this.threshold=e}handleClick(e){const t=performance.now(),n=t-this.lastClickTime;return this.lastClickTime>0&&this.lastClickId===e&&n<this.threshold?(this.clearTimer(),this.reset(),"double"):(this.lastClickId=e,this.lastClickTime=t,this.clearTimer(),this.clickTimer=setTimeout(()=>{this.clickTimer=null,this.lastClickId=null,this.lastClickTime=0},this.threshold),"single")}reset(){this.clearTimer(),this.lastClickId=null,this.lastClickTime=0}clearTimer(){this.clickTimer&&(clearTimeout(this.clickTimer),this.clickTimer=null)}dispose(){this.clearTimer()}}const em=class em{constructor(e,t,n){W(this,"canvas");W(this,"controls");W(this,"callbacks");W(this,"activePointers",new Map);W(this,"touchStartTime",0);W(this,"touchStartPos",{x:0,y:0});W(this,"isTouchDragging",!1);W(this,"isTouchPanning",!1);W(this,"touchPanStart",{x:0,y:0});W(this,"longPressTimer",null);W(this,"longPressTriggered",!1);W(this,"isPinching",!1);W(this,"lastPinchDistance",0);W(this,"twoFingerPanStart",{x:0,y:0});W(this,"lastTwoFingerAngle",0);W(this,"isThreeFingerDrag",!1);W(this,"threeFingerStart",{x:0,y:0});this.canvas=e,this.controls=t,this.callbacks=n}onTouchStart(e){for(let t=0;t<e.changedTouches.length;t++){const n=e.changedTouches[t];this.activePointers.set(n.identifier,{x:n.clientX,y:n.clientY})}this.clearLongPressTimer(),this.longPressTriggered=!1,e.touches.length===1?this.handleSingleTouchStart(e.touches[0]):e.touches.length===2?this.handleTwoTouchStart(e):e.touches.length>=3&&this.handleThreeTouchStart(e)}onTouchMove(e){for(let t=0;t<e.changedTouches.length;t++){const n=e.changedTouches[t];this.activePointers.set(n.identifier,{x:n.clientX,y:n.clientY})}e.touches.length>=3&&this.isThreeFingerDrag?this.handleThreeTouchMove(e):e.touches.length===2&&this.isPinching?this.handleTwoTouchMove(e):e.touches.length===1&&!this.isPinching&&this.handleSingleTouchMove(e.touches[0])}onTouchEnd(e){this.clearLongPressTimer();for(let t=0;t<e.changedTouches.length;t++){const n=e.changedTouches[t];this.activePointers.delete(n.identifier)}return e.touches.length===0?this.handleAllTouchesEnd(e):(e.touches.length===2?this.transitionToTwoTouches(e):e.touches.length===1&&this.transitionToOneTouch(e.touches[0]),!1)}onPointerCancel(e){this.activePointers.delete(e),this.reset()}reset(){this.isTouchPanning=!1,this.isPinching=!1,this.isThreeFingerDrag=!1,this.lastPinchDistance=0,this.isTouchDragging=!1,this.longPressTriggered=!1,this.clearLongPressTimer()}get isDragging(){return this.isTouchDragging}get wasLongPress(){return this.longPressTriggered}dispose(){this.clearLongPressTimer(),this.activePointers.clear()}reattach(e,t){this.canvas=e,this.controls=t}handleSingleTouchStart(e){this.touchStartTime=performance.now(),this.touchStartPos={x:e.clientX,y:e.clientY},this.isTouchDragging=!1,this.isTouchPanning=!1;const t=e.clientX,n=e.clientY;this.longPressTimer=setTimeout(()=>{this.longPressTriggered=!0,this.longPressTimer=null,this.callbacks.onLongPress(t,n),navigator.vibrate&&navigator.vibrate(50)},em.LONG_PRESS_DURATION)}handleTwoTouchStart(e){e.preventDefault(),this.isPinching=!0,this.isTouchPanning=!1,this.isThreeFingerDrag=!1,this.lastPinchDistance=this.getTouchDistance(e.touches[0],e.touches[1]);const t=this.getTouchCenter(e.touches[0],e.touches[1]);this.twoFingerPanStart={x:t.x,y:t.y},this.lastTwoFingerAngle=this.getTwoFingerAngle(e.touches[0],e.touches[1])}handleThreeTouchStart(e){e.preventDefault(),this.isPinching=!1,this.isThreeFingerDrag=!0,this.controls.enableRotate=!0;const t=this.getMultiTouchCenter(e.touches);this.threeFingerStart={x:t.x,y:t.y}}handleSingleTouchMove(e){const t=e.clientX-this.touchStartPos.x,n=e.clientY-this.touchStartPos.y;if(!this.isTouchPanning&&(Math.abs(t)>tc||Math.abs(n)>tc)&&(this.clearLongPressTimer(),this.isTouchPanning=!0,this.isTouchDragging=!0,this.touchPanStart={x:e.clientX,y:e.clientY}),this.isTouchPanning){const a=e.clientX-this.touchPanStart.x,i=e.clientY-this.touchPanStart.y;this.callbacks.onPan(a,i),this.touchPanStart={x:e.clientX,y:e.clientY}}}handleTwoTouchMove(e){this.clearLongPressTimer(),e.preventDefault();const t=this.getTouchDistance(e.touches[0],e.touches[1]),n=this.getTouchCenter(e.touches[0],e.touches[1]),a=this.getTwoFingerAngle(e.touches[0],e.touches[1]);if(this.lastPinchDistance>0){const c=this.lastPinchDistance/t;this.callbacks.onPinchZoom(c,n)}this.lastPinchDistance=t;const i=n.x-this.twoFingerPanStart.x,o=n.y-this.twoFingerPanStart.y;(Math.abs(i)>1||Math.abs(o)>1)&&(this.callbacks.onOrbit(i,o),this.twoFingerPanStart={x:n.x,y:n.y});let l=a-this.lastTwoFingerAngle;l>Math.PI&&(l-=2*Math.PI),l<-Math.PI&&(l+=2*Math.PI),Math.abs(l)>.01&&(this.callbacks.onRotation(l),this.lastTwoFingerAngle=a)}handleThreeTouchMove(e){this.clearLongPressTimer(),e.preventDefault();const t=this.getMultiTouchCenter(e.touches),n=t.x-this.threeFingerStart.x,a=t.y-this.threeFingerStart.y;(Math.abs(n)>1||Math.abs(a)>1)&&(this.callbacks.onOrbit(n,a),this.threeFingerStart={x:t.x,y:t.y})}handleAllTouchesEnd(e){const t=performance.now()-this.touchStartTime,n=!this.isTouchDragging&&!this.longPressTriggered&&t<400;if(n&&e.changedTouches.length>0){const a=e.changedTouches[0];this.callbacks.onTap(a.clientX,a.clientY)}return this.reset(),n}transitionToTwoTouches(e){this.isThreeFingerDrag=!1,this.isPinching=!0,this.lastPinchDistance=this.getTouchDistance(e.touches[0],e.touches[1]);const t=this.getTouchCenter(e.touches[0],e.touches[1]);this.twoFingerPanStart={x:t.x,y:t.y}}transitionToOneTouch(e){this.isPinching=!1,this.isThreeFingerDrag=!1,this.lastPinchDistance=0,this.touchPanStart={x:e.clientX,y:e.clientY},this.touchStartPos={x:e.clientX,y:e.clientY}}clearLongPressTimer(){this.longPressTimer&&(clearTimeout(this.longPressTimer),this.longPressTimer=null)}getTouchDistance(e,t){const n=t.clientX-e.clientX,a=t.clientY-e.clientY;return Math.sqrt(n*n+a*a)}getTouchCenter(e,t){return{x:(e.clientX+t.clientX)/2,y:(e.clientY+t.clientY)/2}}getTwoFingerAngle(e,t){const n=t.clientX-e.clientX,a=t.clientY-e.clientY;return Math.atan2(a,n)}getMultiTouchCenter(e){let t=0,n=0;for(let a=0;a<e.length;a++)t+=e[a].clientX,n+=e[a].clientY;return{x:t/e.length,y:n/e.length}}};W(em,"LONG_PRESS_DURATION",500);let xy=em;function WO(s){const e=Math.abs(s.deltaX),t=Math.abs(s.deltaY);return s.ctrlKey||e>1?!0:t>80&&e<1?!1:t>0&&t<=80}class qO{constructor(e,t,n){W(this,"cameraController");W(this,"callbacks");W(this,"canvas");W(this,"isGestureActive",!1);W(this,"gestureScale",1);W(this,"onGestureStart",e=>{const t=e;t.preventDefault(),H.getTrackpadConfig().enabled&&(this.isGestureActive=!0,this.gestureScale=t.scale)});W(this,"onGestureChange",e=>{const t=e;t.preventDefault();const n=H.getTrackpadConfig();if(!(!n.enabled||!this.isGestureActive)&&n.pinchToZoom&&t.scale!==this.gestureScale){const a=t.scale-this.gestureScale;this.callbacks.onZoom(a*n.sensitivity.zoom,t.clientX,t.clientY),this.gestureScale=t.scale}});W(this,"onGestureEnd",e=>{e.preventDefault(),this.isGestureActive=!1,this.gestureScale=1});this.cameraController=e,this.canvas=t,this.callbacks=n,this.setupGestureEvents()}setupGestureEvents(){"GestureEvent"in window&&(this.canvas.addEventListener("gesturestart",this.onGestureStart),this.canvas.addEventListener("gesturechange",this.onGestureChange),this.canvas.addEventListener("gestureend",this.onGestureEnd))}handleWheel(e){const t=H.getTrackpadConfig();if(!t.enabled||!WO(e))return!1;if(e.ctrlKey&&t.pinchToZoom){e.preventDefault();const n=-e.deltaY*.01*t.sensitivity.zoom;return this.callbacks.onZoom(n,e.clientX,e.clientY),!0}if(e.shiftKey&&t.shiftTwoFingerOrbit){e.preventDefault();const n=-e.deltaX*t.sensitivity.orbit,a=-e.deltaY*t.sensitivity.orbit;return this.callbacks.onOrbit(n,a),!0}if(t.twoFingerPan){e.preventDefault();const n=-e.deltaX*t.sensitivity.pan,a=-e.deltaY*t.sensitivity.pan;return this.callbacks.onPan(n,a),!0}return!1}setCameraController(e){this.cameraController=e}setCanvas(e){"GestureEvent"in window&&(this.canvas.removeEventListener("gesturestart",this.onGestureStart),this.canvas.removeEventListener("gesturechange",this.onGestureChange),this.canvas.removeEventListener("gestureend",this.onGestureEnd)),this.canvas=e,this.setupGestureEvents()}dispose(){"GestureEvent"in window&&(this.canvas.removeEventListener("gesturestart",this.onGestureStart),this.canvas.removeEventListener("gesturechange",this.onGestureChange),this.canvas.removeEventListener("gestureend",this.onGestureEnd))}}class YO{constructor(e,t){W(this,"camera");W(this,"canvas");W(this,"raycaster",new VD);W(this,"mouse",new _s);W(this,"ground",null);W(this,"agentMeshes",new Map);W(this,"agentHitboxes",[]);W(this,"resizeHandlesGetter",()=>[]);W(this,"folderIconMeshesGetter",()=>[]);this.camera=e,this.canvas=t}setReferences(e,t){this.ground=e,this.agentMeshes=t,this.agentHitboxes=[];for(const n of t.values()){const a=n.group.getObjectByName("clickHitbox");this.agentHitboxes.push(a??n.group)}}setResizeHandlesGetter(e){this.resizeHandlesGetter=e}setFolderIconMeshesGetter(e){this.folderIconMeshesGetter=e}setCanvas(e){this.canvas=e}raycastGroundFromEvent(e){if(!this.ground)return null;this.updateMouseFromEvent(e),this.raycaster.setFromCamera(this.mouse,this.camera);const t=this.raycaster.intersectObject(this.ground);if(t.length>0){const n=t[0].point;return{x:n.x,z:n.z}}return null}raycastGroundFromPoint(e,t){if(!this.ground)return null;this.updateMouseFromPoint(e,t),this.raycaster.setFromCamera(this.mouse,this.camera);const n=this.raycaster.intersectObject(this.ground);if(n.length>0){const a=n[0].point;return{x:a.x,z:a.z}}return null}checkResizeHandleClick(e){const t=this.resizeHandlesGetter();if(t.length===0)return null;this.updateMouseFromEvent(e),this.raycaster.setFromCamera(this.mouse,this.camera);const n=this.raycaster.intersectObjects(t);return n.length>0?n[0].object:null}checkFolderIconClick(e){const t=this.folderIconMeshesGetter();if(t.length===0)return null;this.updateMouseFromEvent(e),this.raycaster.setFromCamera(this.mouse,this.camera);const n=this.raycaster.intersectObjects(t);return n.length>0?n[0].object:null}findAgentAtPosition(e){if(this.updateMouseFromEvent(e),this.raycaster.setFromCamera(this.mouse,this.camera),this.agentHitboxes.length===0)return null;const t=this.raycaster.intersectObjects(this.agentHitboxes,!1);if(t.length>0){let n=t[0].object;for(;n&&!n.userData.agentId;)n=n.parent;if(n&&n.userData.agentId)return n.userData.agentId}return null}findAgentAtPoint(e,t){if(this.updateMouseFromPoint(e,t),this.raycaster.setFromCamera(this.mouse,this.camera),this.agentHitboxes.length===0)return null;const n=this.raycaster.intersectObjects(this.agentHitboxes,!1);if(n.length>0){let a=n[0].object;for(;a&&!a.userData.agentId;)a=a.parent;if(a&&a.userData.agentId)return a.userData.agentId}return null}raycastToPlane(e,t){if(this.mouse.set(e,t),this.raycaster.setFromCamera(this.mouse,this.camera),this.ground){const i=this.raycaster.intersectObject(this.ground);if(i.length>0)return i[0].point}const n=new pA(new yt(0,1,0),0),a=new yt;return this.raycaster.ray.intersectPlane(n,a)?a:null}projectToScreen(e){const t=this.canvas.getBoundingClientRect(),n=e.clone().project(this.camera);return{x:(n.x+1)/2*t.width+t.left,y:(-n.y+1)/2*t.height+t.top}}getNormalizedMouseFromEvent(e){return this.updateMouseFromEvent(e),this.mouse.clone()}getNormalizedMouseFromPoint(e,t){return this.updateMouseFromPoint(e,t),this.mouse.clone()}getAgentMeshes(){return this.agentMeshes}updateMouseFromEvent(e){const t=this.canvas.getBoundingClientRect();this.mouse.x=(e.clientX-t.left)/t.width*2-1,this.mouse.y=-((e.clientY-t.top)/t.height)*2+1}updateMouseFromPoint(e,t){const n=this.canvas.getBoundingClientRect();this.mouse.x=(e-n.left)/n.width*2-1,this.mouse.y=-((t-n.top)/n.height)*2+1}}class VO{constructor(e,t,n){W(this,"camera");W(this,"controls");W(this,"canvas");W(this,"raycastProvider",null);this.camera=e,this.controls=t,this.canvas=n}setRaycastProvider(e){this.raycastProvider=e}setControls(e){this.controls=e}setCanvas(e){this.canvas=e}handleWheelZoom(e,t=1){e.preventDefault();const n=Math.sign(e.deltaY)*Math.min(Math.abs(e.deltaY),100)/100,a=n<0,i=.03*Math.abs(n)*t,o=this.camera.position.clone().sub(this.controls.target),l=o.length(),c=this.controls.minDistance,d=this.controls.maxDistance,m=a?Math.max(c,l*(1-i)):Math.min(d,l*(1+i));if(m===l)return;let p=null;if(this.raycastProvider){const S=this.raycastProvider.getNormalizedMouseFromEvent(e);p=this.raycastProvider.raycastToPlane(S.x,S.y)}if(!p){const S=o.normalize();this.camera.position.copy(this.controls.target).add(S.multiplyScalar(m));return}const f=m/l,b=p.clone().sub(this.controls.target),y=1-f,w=this.controls.target.clone().add(b.multiplyScalar(y));w.y=Math.max(0,w.y),this.controls.target.copy(w);const k=o.normalize();this.camera.position.copy(w).add(k.multiplyScalar(m))}handlePinchZoom(e,t){const n=this.camera.position.clone().sub(this.controls.target),a=n.length(),i=this.controls.minDistance,o=this.controls.maxDistance,l=Math.max(i,Math.min(o,a*e));if(l===a)return;const c=this.canvas.getBoundingClientRect(),d=(t.x-c.left)/c.width*2-1,m=-((t.y-c.top)/c.height)*2+1;let p=null;if(this.raycastProvider&&(p=this.raycastProvider.raycastToPlane(d,m)),!p){const S=n.normalize();this.camera.position.copy(this.controls.target).add(S.multiplyScalar(l));return}const f=l/a,b=p.clone().sub(this.controls.target),y=1-f,w=this.controls.target.clone().add(b.multiplyScalar(y));w.y=Math.max(0,w.y),this.controls.target.copy(w);const k=n.normalize();this.camera.position.copy(w).add(k.multiplyScalar(l))}handlePan(e,t){const n=new yt;this.camera.getWorldDirection(n);const a=new yt(-n.z,0,n.x).normalize(),i=new yt(n.x,0,n.z).normalize(),l=this.camera.position.distanceTo(this.controls.target)*.005,c=new yt;c.add(a.multiplyScalar(-e*l)),c.add(i.multiplyScalar(t*l)),this.controls.target.add(c),this.camera.position.add(c)}handleOrbit(e,t){const a=-e*.005,i=-t*.005,o=this.camera.position.clone().sub(this.controls.target),l=new yp;l.setFromVector3(o),l.theta+=a,l.phi+=i,l.phi=Math.max(.1,Math.min(Math.PI-.1,l.phi)),o.setFromSpherical(l),this.camera.position.copy(this.controls.target).add(o),this.camera.lookAt(this.controls.target)}handleTwistRotation(e){const t=this.camera.position.clone().sub(this.controls.target),n=new yp;n.setFromVector3(t),n.theta+=e,n.phi=Math.max(.1,Math.min(Math.PI-.1,n.phi)),t.setFromSpherical(n),this.camera.position.copy(this.controls.target).add(t),this.camera.lookAt(this.controls.target)}}const eb={panSpeed:1,orbitSpeed:1,zoomSpeed:1,smoothing:.3,invertPanX:!1,invertPanY:!1,invertOrbitX:!1,invertOrbitY:!1},Fh={enabled:!0,pinchToZoom:!0,twoFingerPan:!0,shiftTwoFingerOrbit:!0,sensitivity:{zoom:1,pan:1,orbit:1}};function Eo(s,e,t,n,a,i,o){return{id:s,name:e,description:t,button:n,modifiers:a,action:i,enabled:!0,sensitivity:o}}const tb=[Eo("left-click-select","Select/Click","Select agents, click on buildings/areas","left",{},"primary-action"),Eo("left-drag-selection","Selection Box","Drag to select multiple agents","left",{},"selection-box"),Eo("right-click-context","Context Menu / Move","Show context menu or move selected agents","right",{},"context-menu"),Eo("alt-right-drag-pan","Camera Pan","Pan camera with Alt+Right-drag","right",{alt:!0},"camera-pan",1),Eo("middle-drag-orbit","Camera Orbit","Orbit camera with middle-drag","middle",{},"camera-orbit",1),Eo("shift-middle-drag-pan","Camera Pan (Alt)","Alternative pan with Shift+Middle-drag","middle",{shift:!0},"camera-pan",1),Eo("wheel-zoom","Zoom","Zoom camera with scroll wheel","middle",{},"camera-zoom",1)],KO={0:"left",1:"middle",2:"right",3:"back",4:"forward"},XO={left:"Left Click",right:"Right Click",middle:"Middle Click",back:"Back Button",forward:"Forward Button"};function bj(s,e){const t=[];if(s.modifiers.ctrl){const n=typeof navigator<"u"&&navigator.platform.toUpperCase().includes("MAC");t.push(n?"⌘":"Ctrl")}if(s.modifiers.alt){const n=typeof navigator<"u"&&navigator.platform.toUpperCase().includes("MAC");t.push(n?"⌥":"Alt")}return s.modifiers.shift&&t.push("Shift"),t.push(e?e(s.button):XO[s.button]),t.join("+")}function ZO(s,e){const t=e.ctrl?s.ctrlKey||s.metaKey:!s.ctrlKey&&!s.metaKey,n=e.alt?s.altKey:!s.altKey,a=e.shift?s.shiftKey:!s.shiftKey;return t&&n&&a}function yj(s,e,t){return s.filter(n=>{if(n.id===t||!n.enabled||n.button!==e.button)return!1;const a=n.modifiers,i=e.modifiers;return(a.ctrl||!1)===(i.ctrl||!1)&&(a.alt||!1)===(i.alt||!1)&&(a.shift||!1)===(i.shift||!1)})}class QO{constructor(e,t){W(this,"cameraController");W(this,"callbacks");W(this,"activeDragAction",null);W(this,"activeBinding",null);W(this,"dragStartPos",{x:0,y:0});W(this,"lastDragPos",{x:0,y:0});this.cameraController=e,this.callbacks=t}setCameraController(e){this.cameraController=e}findBinding(e,t){const n=H.getMouseControls(),a=KO[t];if(!a)return null;const i=n.bindings.filter(o=>o.enabled&&o.button===a).sort((o,l)=>{const c=Object.values(o.modifiers).filter(Boolean).length;return Object.values(l.modifiers).filter(Boolean).length-c});for(const o of i)if(ZO(e,o.modifiers))return o;return null}isCameraAction(e){return e==="camera-pan"||e==="camera-orbit"||e==="camera-rotate"||e==="camera-tilt"}handlePointerDown(e){const t=this.findBinding(e,e.button);return t?(this.dragStartPos={x:e.clientX,y:e.clientY},this.lastDragPos={x:e.clientX,y:e.clientY},this.isCameraAction(t.action)?(this.activeDragAction=t.action,this.activeBinding=t,!0):!1):!1}handlePointerMove(e){if(!this.activeDragAction||!this.activeBinding)return!1;const t=e.clientX-this.lastDragPos.x,n=e.clientY-this.lastDragPos.y,a=H.getMouseControls().sensitivity;switch(this.activeDragAction){case"camera-pan":{const i=(a.invertPanX?-t:t)*a.panSpeed,o=(a.invertPanY?-n:n)*a.panSpeed;this.cameraController.handlePan(i,o);break}case"camera-orbit":{const i=(a.invertOrbitX?-t:t)*a.orbitSpeed,o=(a.invertOrbitY?-n:n)*a.orbitSpeed;this.cameraController.handleOrbit(i,o);break}case"camera-rotate":this.cameraController.handleOrbit(t*a.orbitSpeed,0);break;case"camera-tilt":this.cameraController.handleOrbit(0,n*a.orbitSpeed);break;case"selection-box":this.callbacks.onSelectionBoxMove(e.clientX,e.clientY);break}return this.lastDragPos={x:e.clientX,y:e.clientY},!0}handlePointerUp(e){const t=this.activeDragAction!==null;return this.activeDragAction==="selection-box"&&this.callbacks.onSelectionBoxEnd(e.clientX,e.clientY),this.activeDragAction=null,this.activeBinding=null,t}handleWheel(e){const t=H.getMouseControls();if(!t.bindings.find(i=>i.enabled&&i.action==="camera-zoom"))return!1;const a=t.sensitivity;return this.cameraController.handleWheelZoom(e,a.zoomSpeed),!0}get isDragging(){return this.activeDragAction!==null}get currentAction(){return this.activeDragAction}cancelDrag(){this.activeDragAction=null,this.activeBinding=null}}const $r=class $r{constructor(e,t,n,a,i){W(this,"canvas");W(this,"camera");W(this,"controls");W(this,"selectionBox");W(this,"callbacks");W(this,"raycaster");W(this,"cameraController");W(this,"mouseControlHandler");W(this,"trackpadHandler");W(this,"touchHandler");W(this,"agentClickDetector");W(this,"agentTapDetector");W(this,"buildingClickDetector");W(this,"areaClickDetector");W(this,"isDragging",!1);W(this,"dragStart",{x:0,y:0});W(this,"dragCurrent",{x:0,y:0});W(this,"pointerDownOnCanvas",!1);W(this,"isRightDragging",!1);W(this,"rightDragStart",{x:0,y:0});W(this,"isDrawing",!1);W(this,"drawingModeChecker",()=>!1);W(this,"isResizing",!1);W(this,"resizeModeChecker",()=>!1);W(this,"areaAtPositionGetter",()=>null);W(this,"buildingAtPositionGetter",()=>null);W(this,"buildingPositionsGetter",()=>new Map);W(this,"isDraggingBuilding",!1);W(this,"draggingBuildingId",null);W(this,"buildingDragStartPos",null);W(this,"hoveredAgentId",null);W(this,"hoverTimer",null);W(this,"lastMousePos",{x:0,y:0});W(this,"lastHoverCheckTime",0);W(this,"hoveredBuildingId",null);W(this,"buildingHoverTimer",null);W(this,"onPointerDown",e=>{var n,a,i,o,l,c;if(!document.hasFocus()||document.visibilityState==="hidden")return;(a=(n=this.callbacks).onActivity)==null||a.call(n);const t=e.pointerType==="touch";if(e.button===0){if(this.controls.mouseButtons.LEFT=null,!t){const m=this.raycaster.checkResizeHandleClick(e);if(m){const p=this.raycaster.raycastGroundFromEvent(e);p&&(this.isResizing=!0,(o=(i=this.callbacks).onResizeStart)==null||o.call(i,m,p));return}}if(!t&&this.drawingModeChecker()){const m=this.raycaster.raycastGroundFromEvent(e);m&&(this.isDrawing=!0,(c=(l=this.callbacks).onDrawStart)==null||c.call(l,m));return}const d=this.raycaster.raycastGroundFromEvent(e);if(d){const m=this.buildingAtPositionGetter(d);if(m&&!t){this.draggingBuildingId=m.id,this.buildingDragStartPos=d,this.isDraggingBuilding=!1;return}}this.isDragging=!1,this.dragStart={x:e.clientX,y:e.clientY},this.dragCurrent={x:e.clientX,y:e.clientY},this.pointerDownOnCanvas=!0}if(e.button===2){if(this.mouseControlHandler.handlePointerDown(e)){this.controls.mouseButtons.RIGHT=null;return}this.controls.mouseButtons.RIGHT=null,this.isRightDragging=!1,this.rightDragStart={x:e.clientX,y:e.clientY}}if(e.button===1&&this.mouseControlHandler.handlePointerDown(e)){this.controls.mouseButtons.MIDDLE=null;return}});W(this,"onPointerMove",e=>{var t,n,a,i,o,l,c,d;if(!document.hasFocus()||document.hidden){this.isDragging&&(this.isDragging=!1,this.selectionBox.classList.remove("active"),this.pointerDownOnCanvas=!1);return}if(e.buttons&1){if(this.isResizing){const f=this.raycaster.raycastGroundFromEvent(e);f&&((n=(t=this.callbacks).onResizeMove)==null||n.call(t,f));return}if(this.isDrawing){const f=this.raycaster.raycastGroundFromEvent(e);f&&((i=(a=this.callbacks).onDrawMove)==null||i.call(a,f));return}if(this.draggingBuildingId&&this.buildingDragStartPos){const f=this.raycaster.raycastGroundFromEvent(e);if(f){const b=f.x-this.buildingDragStartPos.x,y=f.z-this.buildingDragStartPos.z,w=Math.sqrt(b*b+y*y);!this.isDraggingBuilding&&w>.2&&(this.isDraggingBuilding=!0,(l=(o=this.callbacks).onBuildingDragStart)==null||l.call(o,this.draggingBuildingId,this.buildingDragStartPos)),this.isDraggingBuilding&&((d=(c=this.callbacks).onBuildingDragMove)==null||d.call(c,this.draggingBuildingId,f))}return}if(e.pointerType==="touch"||!this.pointerDownOnCanvas||H.getState().terminalResizing)return;const m=e.clientX-this.dragStart.x,p=e.clientY-this.dragStart.y;!this.isDragging&&(Math.abs(m)>tc||Math.abs(p)>tc)&&(this.isDragging=!0,this.selectionBox.classList.add("active")),this.isDragging&&(this.dragCurrent={x:e.clientX,y:e.clientY},this.updateSelectionBox())}if(e.buttons&2){if(this.mouseControlHandler.handlePointerMove(e))return;const m=e.clientX-this.rightDragStart.x,p=e.clientY-this.rightDragStart.y;!this.isRightDragging&&(Math.abs(m)>tc||Math.abs(p)>tc)&&(this.isRightDragging=!0)}if(!(e.buttons&4&&this.mouseControlHandler.handlePointerMove(e))&&e.buttons===0&&e.pointerType!=="touch"){const m=performance.now();m-this.lastHoverCheckTime>$r.HOVER_CHECK_INTERVAL&&(this.handleHoverDetection(e),this.lastHoverCheckTime=m)}});W(this,"onPointerUp",e=>{var t,n,a,i,o,l;if(e.button===0){if(this.controls.mouseButtons.LEFT=null,e.pointerType==="touch"){this.pointerDownOnCanvas=!1;return}if(this.isResizing){(n=(t=this.callbacks).onResizeEnd)==null||n.call(t),this.isResizing=!1;return}if(this.isDrawing){const c=this.raycaster.raycastGroundFromEvent(e);c&&((i=(a=this.callbacks).onDrawEnd)==null||i.call(a,c)),this.isDrawing=!1;return}if(this.draggingBuildingId){const c=this.draggingBuildingId,d=this.raycaster.raycastGroundFromEvent(e),m={x:e.clientX,y:e.clientY};this.isDraggingBuilding&&d?(l=(o=this.callbacks).onBuildingDragEnd)==null||l.call(o,c,d):this.handleBuildingClick(c,m),this.draggingBuildingId=null,this.buildingDragStartPos=null,this.isDraggingBuilding=!1;return}this.isDragging?(this.isDragging=!1,this.selectionBox.classList.remove("active"),this.selectAgentsInBox(this.dragStart,this.dragCurrent)):e.ctrlKey||this.handleSingleClick(e),this.pointerDownOnCanvas=!1}e.button===2&&(this.mouseControlHandler.handlePointerUp(e),this.controls.mouseButtons.RIGHT=null,this.isRightDragging=!1),e.button===1&&(this.mouseControlHandler.handlePointerUp(e),this.controls.mouseButtons.MIDDLE=null)});W(this,"onPointerCancel",e=>{this.touchHandler.onPointerCancel(e.pointerId)});W(this,"onPointerLeave",e=>{this.clearHoverState(),this.clearBuildingHoverState()});W(this,"onWindowBlur",()=>{this.cancelAllDragStates()});W(this,"onVisibilityChange",()=>{document.hidden&&this.cancelAllDragStates()});W(this,"onKeyDown",e=>{var f,b;const t=e.target,n=H.getState(),a=t.tagName==="INPUT"||t.tagName==="TEXTAREA"||t.isContentEditable,i=t.closest(".guake-terminal"),o=i==null?void 0:i.classList.contains("collapsed"),l=H.getShortcuts(),c=l.find(y=>y.id==="toggle-spotlight"),d=l.find(y=>y.id==="next-agent"),m=l.find(y=>y.id==="prev-agent"),p=l.find(y=>y.id==="open-terminal");if(!vt(e,c)){if(a){const y=H.getShortcuts();if((vt(e,y.find(k=>k.id==="next-agent"))||vt(e,y.find(k=>k.id==="prev-agent"))||vt(e,y.find(k=>k.id==="next-working-agent"))||vt(e,y.find(k=>k.id==="prev-working-agent")))&&o)t.blur();else return}if((vt(e,d)||vt(e,m))&&!n.terminalOpen){const y=this.getOrderedAgents(n.agents);if(y.length<=1)return;const w=n.selectedAgentIds.size===1?Array.from(n.selectedAgentIds)[0]:null,k=w?y.findIndex(j=>j.id===w):-1;let S;vt(e,d)?S=k===-1?0:(k+1)%y.length:S=k===-1?y.length-1:(k-1+y.length)%y.length,e.preventDefault(),H.selectAgent(y[S].id),(b=(f=this.callbacks).onActivity)==null||b.call(f);return}if(vt(e,p)){if(i&&!o||t.tagName==="BUTTON"||t.tagName==="A")return;if(n.terminalOpen)if(i&&o)H.setTerminalOpen(!1);else return;const y=document.querySelector(".guake-terminal");if(y&&y.classList.contains("collapsed")&&n.terminalOpen&&H.setTerminalOpen(!1),n.selectedBuildingIds.size>0||n.selectedAreaId!==null)return;if(n.selectedAgentIds.size===0){const w=n.lastSelectedAgentId;w&&n.agents.has(w)&&(e.preventDefault(),H.selectAgent(w),H.setTerminalOpen(!0));return}e.preventDefault(),H.setTerminalOpen(!0)}}});W(this,"onContextMenu",e=>{var a,i;if(e.preventDefault(),e.altKey)return;if(this.controls.mouseButtons.RIGHT=null,this.isRightDragging){this.isRightDragging=!1;return}const t=H.getState(),n=this.raycaster.raycastGroundFromEvent(e);if(n){if(t.selectedAgentIds.size>0){this.callbacks.onAreaRightClick&&this.callbacks.onAreaRightClick(n);const o=Array.from(t.selectedAgentIds),l=new yt(n.x,0,n.z);this.callbacks.onMoveCommand(l,o);return}if(this.callbacks.onContextMenu){const o=this.raycaster.findAgentAtPosition(e),l=(a=this.areaAtPositionGetter)==null?void 0:a.call(this,n),c=(i=this.buildingAtPositionGetter)==null?void 0:i.call(this,n);let d;o?d={type:"agent",id:o}:c?d={type:"building",id:c.id}:l?d={type:"area",id:l.id}:d={type:"ground"},this.callbacks.onContextMenu({x:e.clientX,y:e.clientY},n,d)}}});W(this,"onWheel",e=>{var t,n;(n=(t=this.callbacks).onActivity)==null||n.call(t),!this.trackpadHandler.handleWheel(e)&&this.mouseControlHandler.handleWheel(e)});W(this,"onTouchStart",e=>{this.touchHandler.onTouchStart(e)});W(this,"onTouchMove",e=>{this.touchHandler.onTouchMove(e)});W(this,"onTouchEnd",e=>{this.touchHandler.onTouchEnd(e)});W(this,"handleTouchTap",(e,t)=>{var i,o,l,c,d,m;const n=this.raycaster.findAgentAtPoint(e,t);if(n){this.agentTapDetector.handleClick(n)==="double"?this.callbacks.onAgentDoubleClick(n):this.callbacks.onAgentClick(n,!1);return}const a=this.raycaster.raycastGroundFromPoint(e,t);if(a){const p=this.buildingAtPositionGetter(a);if(p){const b={x:e,y:t};this.handleBuildingClick(p.id,b);return}const f=this.areaAtPositionGetter(a);if(f){this.areaClickDetector.handleClick(f.id)==="double"?(o=(i=this.callbacks).onAreaDoubleClick)==null||o.call(i,f.id):(c=(l=this.callbacks).onAreaClick)==null||c.call(l,f.id);return}}this.agentClickDetector.reset(),this.callbacks.onGroundClick(),(m=(d=this.callbacks).onGroundClickOutsideArea)==null||m.call(d)});W(this,"handleLongPress",(e,t)=>{var c,d;const n=H.getState(),a=this.raycaster.raycastGroundFromPoint(e,t);if(!a)return;const i=this.raycaster.findAgentAtPoint(e,t);if(i){this.callbacks.onContextMenu&&this.callbacks.onContextMenu({x:e,y:t},a,{type:"agent",id:i});return}const o=(c=this.buildingAtPositionGetter)==null?void 0:c.call(this,a);if(o){this.callbacks.onContextMenu&&this.callbacks.onContextMenu({x:e,y:t},a,{type:"building",id:o.id});return}const l=(d=this.areaAtPositionGetter)==null?void 0:d.call(this,a);if(l){this.callbacks.onContextMenu&&this.callbacks.onContextMenu({x:e,y:t},a,{type:"area",id:l.id});return}if(n.selectedAgentIds.size>0){const m=Array.from(n.selectedAgentIds),p=new yt(a.x,0,a.z);this.callbacks.onMoveCommand(p,m);return}this.callbacks.onContextMenu&&this.callbacks.onContextMenu({x:e,y:t},a,{type:"ground"})});this.canvas=e,this.camera=t,this.controls=n,this.selectionBox=a,this.callbacks=i,this.raycaster=new YO(t,e),this.cameraController=new VO(t,n,e),this.cameraController.setRaycastProvider(this.raycaster),this.mouseControlHandler=new QO(this.cameraController,{onSelectionBoxStart:(o,l)=>{this.dragStart={x:o,y:l},this.dragCurrent={x:o,y:l},this.isDragging=!0,this.selectionBox.classList.add("active")},onSelectionBoxMove:(o,l)=>{this.dragCurrent={x:o,y:l},this.updateSelectionBox()},onSelectionBoxEnd:(o,l)=>{this.isDragging=!1,this.selectionBox.classList.remove("active"),this.selectAgentsInBox(this.dragStart,{x:o,y:l})}}),this.trackpadHandler=new qO(this.cameraController,e,{onPan:(o,l)=>{this.cameraController.handlePan(o,l)},onZoom:(o,l,c)=>{const d=1-o;this.cameraController.handlePinchZoom(d,{x:l,y:c})},onOrbit:(o,l)=>{this.cameraController.handleOrbit(o,l)}}),this.agentClickDetector=new Bh(300),this.agentTapDetector=new Bh(450),this.buildingClickDetector=new Bh(300),this.areaClickDetector=new Bh(300),this.touchHandler=new xy(e,n,{onTap:this.handleTouchTap,onLongPress:this.handleLongPress,onPan:(o,l)=>this.cameraController.handlePan(o,l),onPinchZoom:(o,l)=>this.cameraController.handlePinchZoom(o,l),onOrbit:(o,l)=>this.cameraController.handleOrbit(o,l),onRotation:o=>this.cameraController.handleTwistRotation(o)}),this.setupEventListeners()}setReferences(e,t){this.raycaster.setReferences(e,t)}setDrawingModeChecker(e){this.drawingModeChecker=e}setResizeHandlers(e,t){this.raycaster.setResizeHandlesGetter(e),this.resizeModeChecker=t}setFolderIconMeshesGetter(e){this.raycaster.setFolderIconMeshesGetter(e)}setAreaAtPositionGetter(e){this.areaAtPositionGetter=e}setBuildingAtPositionGetter(e){this.buildingAtPositionGetter=e}setBuildingPositionsGetter(e){this.buildingPositionsGetter=e}raycastGround(e){return this.raycaster.raycastGroundFromEvent(e)}dispose(){this.canvas.removeEventListener("pointerdown",this.onPointerDown,!0),this.canvas.removeEventListener("pointermove",this.onPointerMove),this.canvas.removeEventListener("pointerup",this.onPointerUp),this.canvas.removeEventListener("pointercancel",this.onPointerCancel),this.canvas.removeEventListener("pointerleave",this.onPointerLeave),this.canvas.removeEventListener("contextmenu",this.onContextMenu),this.canvas.removeEventListener("wheel",this.onWheel),this.canvas.removeEventListener("touchstart",this.onTouchStart),this.canvas.removeEventListener("touchmove",this.onTouchMove),this.canvas.removeEventListener("touchend",this.onTouchEnd),this.agentClickDetector.dispose(),this.agentTapDetector.dispose(),this.buildingClickDetector.dispose(),this.areaClickDetector.dispose(),this.touchHandler.dispose(),this.trackpadHandler.dispose(),this.clearHoverTimer(),this.clearBuildingHoverTimer(),window.removeEventListener("blur",this.onWindowBlur),document.removeEventListener("visibilitychange",this.onVisibilityChange),document.removeEventListener("keydown",this.onKeyDown,!0)}reattach(e,t,n){this.dispose(),this.canvas=e,this.selectionBox=t,this.controls=n,this.raycaster.setCanvas(e),this.cameraController.setCanvas(e),this.cameraController.setControls(n),this.mouseControlHandler.setCameraController(this.cameraController),this.trackpadHandler.setCameraController(this.cameraController),this.trackpadHandler.setCanvas(e),this.touchHandler.reattach(e,n),this.setupEventListeners()}calculateFormationPositions(e,t){const n=[];if(t===1)return[{x:e.x,y:0,z:e.z}];if(t<=6){const a=mi*Math.max(1,t/3);for(let i=0;i<t;i++){const o=i/t*Math.PI*2-Math.PI/2;n.push({x:e.x+Math.cos(o)*a,y:0,z:e.z+Math.sin(o)*a})}}else{const a=Math.ceil(Math.sqrt(t)),i=Math.ceil(t/a),o=(a-1)*mi/2,l=(i-1)*mi/2;for(let c=0;c<t;c++){const d=c%a,m=Math.floor(c/a);n.push({x:e.x+d*mi-o,y:0,z:e.z+m*mi-l})}}return n}setupEventListeners(){this.canvas.addEventListener("pointerdown",this.onPointerDown,!0),this.canvas.addEventListener("pointermove",this.onPointerMove),this.canvas.addEventListener("pointerup",this.onPointerUp),this.canvas.addEventListener("pointercancel",this.onPointerCancel),this.canvas.addEventListener("pointerleave",this.onPointerLeave),this.canvas.addEventListener("contextmenu",this.onContextMenu),this.canvas.addEventListener("wheel",this.onWheel,{passive:!1}),this.canvas.addEventListener("touchstart",this.onTouchStart,{passive:!1}),this.canvas.addEventListener("touchmove",this.onTouchMove,{passive:!1}),this.canvas.addEventListener("touchend",this.onTouchEnd,{passive:!1}),window.addEventListener("blur",this.onWindowBlur),document.addEventListener("visibilitychange",this.onVisibilityChange),document.addEventListener("keydown",this.onKeyDown,!0)}cancelAllDragStates(){this.clearHoverState(),this.clearBuildingHoverState(),this.isDragging&&(this.isDragging=!1,this.selectionBox.classList.remove("active")),this.pointerDownOnCanvas=!1}clearHoverState(){var e,t;this.clearHoverTimer(),this.hoveredAgentId!==null&&(this.hoveredAgentId=null,(t=(e=this.callbacks).onAgentHover)==null||t.call(e,null,null))}handleSingleClick(e){var i,o,l,c,d,m,p,f;const t=this.raycaster.checkFolderIconClick(e);if(t){const b=t.userData.areaId,y=t.userData.folderPath;if(b){(o=(i=this.callbacks).onFolderIconClick)==null||o.call(i,b,y);return}}const n=this.raycaster.findAgentAtPosition(e);if(n){this.agentClickDetector.handleClick(n)==="double"?this.callbacks.onAgentDoubleClick(n):this.callbacks.onAgentClick(n,e.shiftKey);return}this.agentClickDetector.reset();const a=this.raycaster.raycastGroundFromEvent(e);if(a){const b=this.areaAtPositionGetter(a);if(b){this.areaClickDetector.handleClick(b.id)==="double"?(c=(l=this.callbacks).onAreaDoubleClick)==null||c.call(l,b.id):(m=(d=this.callbacks).onAreaClick)==null||m.call(d,b.id);return}}this.areaClickDetector.reset(),e.shiftKey||(this.callbacks.onGroundClick(),(f=(p=this.callbacks).onGroundClickOutsideArea)==null||f.call(p))}handleBuildingClick(e,t){var a,i,o,l;if(this.buildingClickDetector.handleClick(e)==="double")(i=(a=this.callbacks).onBuildingDoubleClick)==null||i.call(a,e);else{const c=t||{x:window.innerWidth/2,y:window.innerHeight/2};(l=(o=this.callbacks).onBuildingClick)==null||l.call(o,e,c)}}updateSelectionBox(){const e=Math.min(this.dragStart.x,this.dragCurrent.x),t=Math.min(this.dragStart.y,this.dragCurrent.y),n=Math.abs(this.dragCurrent.x-this.dragStart.x),a=Math.abs(this.dragCurrent.y-this.dragStart.y);this.selectionBox.style.left=`${e}px`,this.selectionBox.style.top=`${t}px`,this.selectionBox.style.width=`${n}px`,this.selectionBox.style.height=`${a}px`}selectAgentsInBox(e,t){this.canvas.getBoundingClientRect();const n=Math.min(e.x,t.x),a=Math.max(e.x,t.x),i=Math.min(e.y,t.y),o=Math.max(e.y,t.y),l=[],c=[];for(const[m,p]of this.raycaster.getAgentMeshes()){const f=this.raycaster.projectToScreen(p.group.position);f.x>=n&&f.x<=a&&f.y>=i&&f.y<=o&&l.push(m)}const d=this.buildingPositionsGetter();for(const[m,p]of d){const f=this.raycaster.projectToScreen(p);f.x>=n&&f.x<=a&&f.y>=i&&f.y<=o&&c.push(m)}this.callbacks.onSelectionBox(l,c)}handleHoverDetection(e){var o,l,c,d;this.lastMousePos={x:e.clientX,y:e.clientY};const t=this.raycaster.findAgentAtPosition(e);t!==this.hoveredAgentId&&(this.clearHoverTimer(),this.hoveredAgentId!==null&&((l=(o=this.callbacks).onAgentHover)==null||l.call(o,null,null)),this.hoveredAgentId=t,t&&(this.hoverTimer=setTimeout(()=>{this.triggerHoverCallback()},$r.HOVER_DELAY)));const n=this.raycaster.raycastGroundFromEvent(e),a=n?this.buildingAtPositionGetter(n):null,i=(a==null?void 0:a.id)??null;i!==this.hoveredBuildingId&&(this.clearBuildingHoverTimer(),this.hoveredBuildingId!==null&&((d=(c=this.callbacks).onBuildingHover)==null||d.call(c,null,null)),this.hoveredBuildingId=i,i&&(this.buildingHoverTimer=setTimeout(()=>{this.triggerBuildingHoverCallback()},$r.BUILDING_HOVER_DELAY)))}triggerHoverCallback(){if(this.hoveredAgentId&&this.callbacks.onAgentHover){const e=this.raycaster.getAgentMeshes().get(this.hoveredAgentId);if(e){const t=this.raycaster.projectToScreen(e.group.position);this.callbacks.onAgentHover(this.hoveredAgentId,t)}}}clearHoverTimer(){this.hoverTimer&&(clearTimeout(this.hoverTimer),this.hoverTimer=null)}triggerBuildingHoverCallback(){if(this.hoveredBuildingId&&this.callbacks.onBuildingHover){const t=this.buildingPositionsGetter().get(this.hoveredBuildingId);if(t){const n=this.raycaster.projectToScreen(t);this.callbacks.onBuildingHover(this.hoveredBuildingId,n)}}}clearBuildingHoverTimer(){this.buildingHoverTimer&&(clearTimeout(this.buildingHoverTimer),this.buildingHoverTimer=null)}clearBuildingHoverState(){var e,t;this.clearBuildingHoverTimer(),this.hoveredBuildingId!==null&&(this.hoveredBuildingId=null,(t=(e=this.callbacks).onBuildingHover)==null||t.call(e,null,null))}getOrderedAgents(e){const t=Array.from(e.values()),n=new Set(t.map(b=>b.id)),i=Ya(pt.AGENT_ORDER,[]).filter(b=>n.has(b)),l=t.filter(b=>!i.includes(b.id)).sort((b,y)=>(b.createdAt||0)-(y.createdAt||0)).map(b=>b.id),c=[...i,...l],d=new Map(t.map(b=>[b.id,b])),m=c.map(b=>d.get(b)).filter(b=>b!==void 0),p=new Map;for(const b of m){const y=H.getAreaForAgent(b.id),w=(y==null?void 0:y.id)||null;p.has(w)||p.set(w,{area:y?{name:y.name}:null,agents:[]}),p.get(w).agents.push(b)}const f=Array.from(p.values());return f.sort((b,y)=>{var w,k;return!b.area&&y.area?1:b.area&&!y.area?-1:!b.area&&!y.area?0:(((w=b.area)==null?void 0:w.name)||"").localeCompare(((k=y.area)==null?void 0:k.name)||"")}),f.flatMap(b=>b.agents)}};W($r,"HOVER_DELAY",400),W($r,"HOVER_CHECK_INTERVAL",50),W($r,"BUILDING_HOVER_DELAY",5e3);let vy=$r;class JO{constructor(e){W(this,"scene");W(this,"areaMeshes",new Map);W(this,"previewMesh",null);W(this,"isDrawing",!1);W(this,"drawStartPos",null);W(this,"currentTool",null);W(this,"resizeHandles",[]);W(this,"selectedAreaId",null);W(this,"isResizing",!1);W(this,"resizeHandleType",null);W(this,"resizeStartPos",null);W(this,"resizeOriginalArea",null);W(this,"areaDragAgentStartPositions",new Map);W(this,"areaDragBuildingStartPositions",new Map);W(this,"onAreaCreated",null);W(this,"onFolderIconClick",null);W(this,"folderIconMeshes",[]);W(this,"brightness",1);W(this,"logoTextures",new Map);W(this,"loadingLogoTextures",new Set);this.scene=e}setOnAreaCreated(e){this.onAreaCreated=e}setOnFolderIconClick(e){this.onFolderIconClick=e}getFolderIconMeshes(){return this.folderIconMeshes}handleFolderIconClick(e){const t=e.userData.areaId,n=e.userData.folderPath;t&&this.onFolderIconClick&&this.onFolderIconClick(t,n)}setBrightness(e){this.brightness=e;for(const[t,n]of this.areaMeshes){const a=t===this.selectedAreaId;n.traverse(i=>{if(i instanceof De&&i.name!=="resizeHandle"&&i.name!=="areaLogo"){const o=i.material,l=a?.3:.15;o.opacity=l*this.brightness}})}}setTool(e){this.currentTool=e,(!e||e==="select")&&this.cancelDrawing()}getTool(){return this.currentTool}isInDrawingMode(){return this.currentTool==="rectangle"||this.currentTool==="circle"}startDrawing(e){this.isInDrawingMode()&&(this.isDrawing=!0,this.drawStartPos=e,this.createPreview(e))}updateDrawing(e){!this.isDrawing||!this.drawStartPos||!this.previewMesh||this.updatePreview(e)}finishDrawing(e){var n;if(!this.isDrawing||!this.drawStartPos)return this.cancelDrawing(),null;const t=this.createAreaFromDraw(this.drawStartPos,e);return this.cancelDrawing(),t&&(H.addArea(t),this.renderArea(t),(n=this.onAreaCreated)==null||n.call(this,t)),t}cancelDrawing(){this.isDrawing=!1,this.drawStartPos=null,this.previewMesh&&(this.scene.remove(this.previewMesh),this.disposeGroup(this.previewMesh),this.previewMesh=null)}isCurrentlyDrawing(){return this.isDrawing}renderAllAreas(){const e=H.getState();for(const t of e.areas.values()){if(t.archived){this.areaMeshes.has(t.id)&&this.removeAreaMesh(t.id);continue}this.areaMeshes.has(t.id)||this.renderArea(t)}}renderArea(e){var o;this.removeAreaMesh(e.id);const t=new Bn;t.userData.areaId=e.id,t.userData.zIndex=e.zIndex??0;const n=new Bt(e.color),a=(e.zIndex??0)*.001;if(e.type==="rectangle"&&e.width&&e.height){const l=new tr(e.width,e.height),c=new We({color:n,transparent:!0,opacity:.15*this.brightness,side:ws}),d=new De(l,c);d.rotation.x=-Math.PI/2,d.position.y=.02+a,t.add(d);const m=[new yt(-e.width/2,0,-e.height/2),new yt(e.width/2,0,-e.height/2),new yt(e.width/2,0,e.height/2),new yt(-e.width/2,0,e.height/2),new yt(-e.width/2,0,-e.height/2)],p=new La().setFromPoints(m),f=new Io({color:n,linewidth:2}),b=new zr(p,f);b.position.y=.03+a,t.add(b)}else if(e.type==="circle"&&e.radius){const l=new Zb(e.radius,32),c=new We({color:n,transparent:!0,opacity:.15*this.brightness,side:ws}),d=new De(l,c);d.rotation.x=-Math.PI/2,d.position.y=.02+a,t.add(d);const m=[];for(let y=0;y<=32;y++){const w=y/32*Math.PI*2;m.push(new yt(Math.cos(w)*e.radius,0,Math.sin(w)*e.radius))}const p=new La().setFromPoints(m),f=new Io({color:n,linewidth:2}),b=new zr(p,f);b.position.y=.03+a,t.add(b)}const i=this.createTextLabel(e.name,e.color);if(i.position.y=.05+a,i.name="areaLabel",t.add(i),e.directories&&e.directories.length>0){let d=0,m=0,p=3;if(e.type==="rectangle"&&e.width&&e.height)d=-e.width/2+.4,m=-e.height/2+.4,p=Math.max(1,Math.floor((e.width-.6)/.81));else if(e.type==="circle"&&e.radius){const f=e.radius*.707;d=-f+.3,m=-f+.3,p=Math.max(1,Math.floor((e.radius*1.414-.5)/.81))}e.directories.forEach((f,b)=>{var D;const y=Math.floor(b/p),w=b%p,k=((D=e.directoryGitCounts)==null?void 0:D[b])??0,S=this.createFolderIconSprite(e.color,k);S.name="folderIcon",S.userData.areaId=e.id,S.userData.folderPath=f,S.userData.isFolderIcon=!0,S.position.set(d+w*.81,.3+a,m+y*.81),t.add(S);const j=new Ut(.3,8,8),C=new We({visible:!1}),A=new De(j,C);A.position.copy(S.position),A.position.x+=e.center.x,A.position.z+=e.center.z,A.name="folderIconHit",A.userData.areaId=e.id,A.userData.folderPath=f,A.userData.isFolderIcon=!0,this.scene.add(A),this.folderIconMeshes.push(A)})}(o=e.logo)!=null&&o.filename&&this.addLogoToGroup(t,e,a),t.position.set(e.center.x,0,e.center.z),this.scene.add(t),this.areaMeshes.set(e.id,t)}createTextLabel(e,t){const n=document.createElement("canvas"),a=n.getContext("2d"),i=32,o=20,l=64;n.width=1024,n.height=l,a.font=`bold ${i}px Arial`;const c=a.measureText(e).width,d=256;n.width=Math.max(d,c+o*2),a.clearRect(0,0,n.width,n.height),a.font=`bold ${i}px Arial`,a.textAlign="center",a.textBaseline="middle",a.strokeStyle="#000000",a.lineWidth=4,a.strokeText(e,n.width/2,n.height/2),a.fillStyle=t,a.fillText(e,n.width/2,n.height/2);const m=new Jn(n);m.needsUpdate=!0;const p=new Yn({map:m,transparent:!0,depthTest:!1}),f=new Hn(p),b=.5,y=2*(n.width/256);return f.scale.set(y,b,1),f}createFolderIconSprite(e,t=0){const n=document.createElement("canvas"),a=128;n.width=a,n.height=a;const i=n.getContext("2d");i.fillStyle="rgba(0, 0, 0, 0.6)",i.beginPath(),i.arc(a/2,a/2,a*.45,0,Math.PI*2),i.fill(),i.strokeStyle=e,i.lineWidth=3,i.beginPath(),i.arc(a/2,a/2,a*.45,0,Math.PI*2),i.stroke();const o=a*.5,l=a*.35,c=(a-o)/2,d=(a-l)/2+2,m=o*.35,p=l*.22;if(i.fillStyle=e,i.beginPath(),i.moveTo(c+4,d+p),i.lineTo(c+m,d+p),i.lineTo(c+m+p,d),i.lineTo(c+4,d),i.moveTo(c,d+p),i.lineTo(c,d+l),i.lineTo(c+o,d+l),i.lineTo(c+o,d+p),i.closePath(),i.fill(),i.strokeStyle="rgba(255, 255, 255, 0.3)",i.lineWidth=1.5,i.beginPath(),i.moveTo(c+4,d+p+3),i.lineTo(c+o-4,d+p+3),i.stroke(),t>0){const w=a*.16,k=a*.78,S=a*.78;i.fillStyle="#e8943a",i.beginPath(),i.arc(k,S,w,0,Math.PI*2),i.fill(),i.strokeStyle="rgba(0, 0, 0, 0.7)",i.lineWidth=2,i.beginPath(),i.arc(k,S,w,0,Math.PI*2),i.stroke();const j=t>99?"99+":String(t),C=w*1.3;i.font=`bold ${C}px "Segoe UI", Arial, sans-serif`,i.fillStyle="#ffffff",i.textAlign="center",i.textBaseline="middle",i.fillText(j,k,S)}const f=new Jn(n);f.needsUpdate=!0;const b=new Yn({map:f,transparent:!0,depthTest:!1}),y=new Hn(b);return y.scale.set(.6,.6,1),y}addLogoToGroup(e,t,n){const a=t.logo,i=hd(st(`/api/areas/logos/${a.filename}`)),o=this.logoTextures.get(a.filename);if(o){this.createLogoMesh(e,t,o,n);return}if(this.loadingLogoTextures.has(a.filename))return;this.loadingLogoTextures.add(a.filename);const l=t.id;new tx().load(i,d=>{var f;this.logoTextures.set(a.filename,d),this.loadingLogoTextures.delete(a.filename);const m=this.areaMeshes.get(l),p=H.getState().areas.get(l);if(m&&((f=p==null?void 0:p.logo)!=null&&f.filename)){const b=(p.zIndex??0)*.001;this.createLogoMesh(m,p,d,b)}},void 0,()=>{this.loadingLogoTextures.delete(a.filename)})}createLogoMesh(e,t,n,a){const i=t.logo,o=new tr(i.width,i.height),l=new We({map:n,transparent:!0,opacity:i.opacity??.8,side:ws,depthWrite:!0,alphaTest:.01}),c=new De(o,l);c.rotation.x=-Math.PI/2,c.name="areaLogo",c.renderOrder=-1;const d=this.calculateLogoOffset(t,i.position,i.width,i.height);c.position.set(d.x,.04+a,d.z),e.add(c)}calculateLogoOffset(e,t,n,a){if(t==="center")return{x:0,z:0};let i=0,o=0;e.type==="rectangle"&&e.width&&e.height?(i=e.width,o=e.height):e.type==="circle"&&e.radius&&(i=e.radius*1.414,o=e.radius*1.414);const l=n/2+.2,c=a/2+.2;switch(t){case"top-left":return{x:-i/2+l,z:-o/2+c};case"top-right":return{x:i/2-l,z:-o/2+c};case"bottom-left":return{x:-i/2+l,z:o/2-c};case"bottom-right":return{x:i/2-l,z:o/2-c};default:return{x:0,z:0}}}updateAreaMesh(e){this.renderArea(e)}removeAreaMesh(e){const t=this.areaMeshes.get(e);t&&(this.scene.remove(t),this.disposeGroup(t),this.areaMeshes.delete(e)),this.folderIconMeshes=this.folderIconMeshes.filter(n=>n.userData.areaId===e?(this.scene.remove(n),n.geometry.dispose(),n.material.dispose(),!1):!0)}highlightArea(e){this.selectedAreaId=e,this.removeResizeHandles();for(const[t,n]of this.areaMeshes){const a=t===e;n.traverse(i=>{if(i instanceof De&&i.name!=="resizeHandle"&&i.name!=="areaLogo"){const o=i.material,l=a?.3:.15;o.opacity=l*this.brightness}if(i instanceof zr){const o=i.material;o.opacity=a?1:.8}})}if(e){const t=H.getState().areas.get(e);t&&this.createResizeHandles(t)}}createResizeHandles(e){const t=new Ut(.15,16,16),n=new We({color:16777215,transparent:!0,opacity:.9}),a=new We({color:16763904,transparent:!0,opacity:.9}),i=(e.zIndex??0)*.001,o=new De(t.clone(),a.clone());if(o.position.set(e.center.x,.25+i,e.center.z),o.name="resizeHandle",o.userData.handleType="move",o.userData.areaId=e.id,this.scene.add(o),this.resizeHandles.push(o),e.type==="rectangle"&&e.width&&e.height){const l=[{type:"nw",x:-e.width/2,z:-e.height/2},{type:"ne",x:e.width/2,z:-e.height/2},{type:"sw",x:-e.width/2,z:e.height/2},{type:"se",x:e.width/2,z:e.height/2}];for(const p of l){const f=new De(t.clone(),n.clone());f.position.set(e.center.x+p.x,.2+i,e.center.z+p.z),f.name="resizeHandle",f.userData.handleType=p.type,f.userData.areaId=e.id,this.scene.add(f),this.resizeHandles.push(f)}const c=new We({color:11197951,transparent:!0,opacity:.9}),d=new Ut(.12,16,16),m=[{type:"n",x:0,z:-e.height/2},{type:"s",x:0,z:e.height/2},{type:"e",x:e.width/2,z:0},{type:"w",x:-e.width/2,z:0}];for(const p of m){const f=new De(d.clone(),c.clone());f.position.set(e.center.x+p.x,.2+i,e.center.z+p.z),f.name="resizeHandle",f.userData.handleType=p.type,f.userData.areaId=e.id,this.scene.add(f),this.resizeHandles.push(f)}c.dispose(),d.dispose()}else if(e.type==="circle"&&e.radius){const l=new De(t.clone(),n.clone());l.position.set(e.center.x+e.radius,.2+i,e.center.z),l.name="resizeHandle",l.userData.handleType="radius",l.userData.areaId=e.id,this.scene.add(l),this.resizeHandles.push(l)}t.dispose(),n.dispose(),a.dispose()}removeResizeHandles(){for(const e of this.resizeHandles)this.scene.remove(e),e.geometry.dispose(),e.material.dispose();this.resizeHandles=[]}getResizeHandles(){return this.resizeHandles}isCurrentlyResizing(){return this.isResizing}startResize(e,t){const n=e.userData.areaId,a=e.userData.handleType,i=H.getState().areas.get(n);if(i&&(this.isResizing=!0,this.resizeHandleType=a,this.resizeStartPos=t,this.resizeOriginalArea={...i},this.areaDragAgentStartPositions.clear(),this.areaDragBuildingStartPositions.clear(),a==="move")){const o=H.getState();for(const l of o.agents.values())this.isPointInsideArea(l.position.x,l.position.z,i)&&this.areaDragAgentStartPositions.set(l.id,{...l.position});for(const l of o.buildings.values())this.isPointInsideArea(l.position.x,l.position.z,i)&&this.areaDragBuildingStartPositions.set(l.id,{...l.position})}}updateResize(e){if(!this.isResizing||!this.resizeOriginalArea||!this.resizeHandleType||!this.resizeStartPos)return;const t=this.resizeOriginalArea;let n={};if(this.resizeHandleType==="move"){const a=e.x-this.resizeStartPos.x,i=e.z-this.resizeStartPos.z;n={center:{x:t.center.x+a,z:t.center.z+i}};for(const[o,l]of this.areaDragAgentStartPositions)H.moveAgentLocal(o,{x:l.x+a,y:l.y,z:l.z+i});for(const[o,l]of this.areaDragBuildingStartPositions)H.updateBuildingLocal(o,{position:{x:l.x+a,z:l.z+i}})}else if(t.type==="rectangle"&&t.width&&t.height){const a=e.x-this.resizeStartPos.x,i=e.z-this.resizeStartPos.z,o=t.width,l=t.height,c=t.center.x,d=t.center.z,m=y=>{const w=Math.max(.5,o+y);return{width:w,cx:c+(w-o)/2}},p=y=>{const w=Math.max(.5,o-y);return{width:w,cx:c+(o-w)/2}},f=y=>{const w=Math.max(.5,l+y);return{height:w,cz:d+(w-l)/2}},b=y=>{const w=Math.max(.5,l-y);return{height:w,cz:d+(l-w)/2}};switch(this.resizeHandleType){case"se":{const y=m(a),w=f(i);n={width:y.width,height:w.height,center:{x:y.cx,z:w.cz}};break}case"sw":{const y=p(a),w=f(i);n={width:y.width,height:w.height,center:{x:y.cx,z:w.cz}};break}case"ne":{const y=m(a),w=b(i);n={width:y.width,height:w.height,center:{x:y.cx,z:w.cz}};break}case"nw":{const y=p(a),w=b(i);n={width:y.width,height:w.height,center:{x:y.cx,z:w.cz}};break}case"e":{const y=m(a);n={width:y.width,center:{x:y.cx,z:d}};break}case"w":{const y=p(a);n={width:y.width,center:{x:y.cx,z:d}};break}case"s":{const y=f(i);n={height:y.height,center:{x:c,z:y.cz}};break}case"n":{const y=b(i);n={height:y.height,center:{x:c,z:y.cz}};break}}}else if(t.type==="circle"&&this.resizeHandleType==="radius"){const a=e.x-t.center.x,i=e.z-t.center.z;n={radius:Math.max(.5,Math.sqrt(a*a+i*i))}}Object.keys(n).length>0&&H.updateArea(t.id,n)}finishResize(){if(this.resizeHandleType==="move"&&this.resizeOriginalArea&&this.resizeStartPos){const t=H.getState().areas.get(this.resizeOriginalArea.id);if(t){const n=t.center.x-this.resizeOriginalArea.center.x,a=t.center.z-this.resizeOriginalArea.center.z;if(n!==0||a!==0){for(const[i,o]of this.areaDragAgentStartPositions)H.moveAgent(i,{x:o.x+n,y:o.y,z:o.z+a});for(const[i,o]of this.areaDragBuildingStartPositions)H.moveBuilding(i,{x:o.x+n,z:o.z+a})}}}if(this.isResizing=!1,this.resizeHandleType=null,this.resizeStartPos=null,this.resizeOriginalArea=null,this.areaDragAgentStartPositions.clear(),this.areaDragBuildingStartPositions.clear(),this.selectedAreaId){this.removeResizeHandles();const e=H.getState().areas.get(this.selectedAreaId);e&&this.createResizeHandles(e)}}isPointInsideArea(e,t,n){if(n.type==="rectangle"&&n.width&&n.height){const a=n.width/2,i=n.height/2;return e>=n.center.x-a&&e<=n.center.x+a&&t>=n.center.z-i&&t<=n.center.z+i}if(n.type==="circle"&&n.radius){const a=e-n.center.x,i=t-n.center.z;return a*a+i*i<=n.radius*n.radius}return!1}getAreaAtPosition(e){const t=H.getState(),n=Array.from(t.areas.values()).filter(a=>!a.archived).sort((a,i)=>(i.zIndex??0)-(a.zIndex??0));for(const a of n)if(a.type==="rectangle"&&a.width&&a.height){const i=a.width/2,o=a.height/2;if(e.x>=a.center.x-i&&e.x<=a.center.x+i&&e.z>=a.center.z-o&&e.z<=a.center.z+o)return a}else if(a.type==="circle"&&a.radius){const i=e.x-a.center.x,o=e.z-a.center.z;if(Math.sqrt(i*i+o*o)<=a.radius)return a}return null}syncFromStore(){const e=H.getState();for(const t of this.areaMeshes.keys()){const n=e.areas.get(t);(!n||n.archived)&&this.removeAreaMesh(t)}for(const t of e.areas.values())t.archived||this.renderArea(t)}createPreview(e){this.previewMesh=new Bn,this.scene.add(this.previewMesh)}updatePreview(e){if(!this.previewMesh||!this.drawStartPos)return;for(;this.previewMesh.children.length>0;){const n=this.previewMesh.children[0];this.previewMesh.remove(n),(n instanceof De||n instanceof zr)&&(n.geometry.dispose(),n.material.dispose())}const t=new Bt("#4a9eff");if(this.currentTool==="rectangle"){const n=Math.abs(e.x-this.drawStartPos.x),a=Math.abs(e.z-this.drawStartPos.z),i=(e.x+this.drawStartPos.x)/2,o=(e.z+this.drawStartPos.z)/2;if(n>.1&&a>.1){const l=new tr(n,a),c=new We({color:t,transparent:!0,opacity:.2,side:ws}),d=new De(l,c);d.rotation.x=-Math.PI/2,d.position.set(i,.02,o),this.previewMesh.add(d);const m=[new yt(this.drawStartPos.x,.03,this.drawStartPos.z),new yt(e.x,.03,this.drawStartPos.z),new yt(e.x,.03,e.z),new yt(this.drawStartPos.x,.03,e.z),new yt(this.drawStartPos.x,.03,this.drawStartPos.z)],p=new La().setFromPoints(m),f=new Io({color:t}),b=new zr(p,f);this.previewMesh.add(b)}}else if(this.currentTool==="circle"){const n=e.x-this.drawStartPos.x,a=e.z-this.drawStartPos.z,i=Math.sqrt(n*n+a*a);if(i>.1){const o=new Zb(i,32),l=new We({color:t,transparent:!0,opacity:.2,side:ws}),c=new De(o,l);c.rotation.x=-Math.PI/2,c.position.set(this.drawStartPos.x,.02,this.drawStartPos.z),this.previewMesh.add(c);const d=[];for(let b=0;b<=32;b++){const y=b/32*Math.PI*2;d.push(new yt(this.drawStartPos.x+Math.cos(y)*i,.03,this.drawStartPos.z+Math.sin(y)*i))}const m=new La().setFromPoints(d),p=new Io({color:t}),f=new zr(m,p);this.previewMesh.add(f)}}}createAreaFromDraw(e,t){const n=`area_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,a=H.getState().areas.size,i=H.getNextZIndex();if(this.currentTool==="rectangle"){const o=Math.abs(t.x-e.x),l=Math.abs(t.z-e.z);return o<.5||l<.5?null:{id:n,name:`Area ${a+1}`,type:"rectangle",center:{x:(e.x+t.x)/2,z:(e.z+t.z)/2},width:o,height:l,color:"#4a9eff",zIndex:i,assignedAgentIds:[],directories:[]}}else if(this.currentTool==="circle"){const o=t.x-e.x,l=t.z-e.z,c=Math.sqrt(o*o+l*l);return c<.5?null:{id:n,name:`Area ${a+1}`,type:"circle",center:{x:e.x,z:e.z},radius:c,color:"#4a9eff",zIndex:i,assignedAgentIds:[],directories:[]}}return null}disposeGroup(e){e.traverse(t=>{if(t instanceof De&&(t.geometry.dispose(),Array.isArray(t.material)?t.material.forEach(n=>n.dispose()):t.material.dispose()),t instanceof zr&&(t.geometry.dispose(),t.material.dispose()),t instanceof Hn){const n=t.material;n.map&&n.map.dispose(),n.dispose()}})}dispose(){this.cancelDrawing(),this.removeResizeHandles();for(const e of this.areaMeshes.keys())this.removeAreaMesh(e);for(const e of this.folderIconMeshes)this.scene.remove(e),e.geometry.dispose(),e.material.dispose();this.folderIconMeshes=[]}}const rs={running:4915102,stopped:8947848,error:16730698,unknown:16755200,starting:4890367,stopping:16755200},fd={desktop:{primary:7438486,secondary:4871528,accent:6534125,glow:4915102},"filing-cabinet":{primary:6869905,secondary:4766584,accent:10151604,glow:4915102},satellite:{primary:8411861,secondary:7030465,accent:12031220,glow:4890367},crystal:{primary:15557798,secondary:13975436,accent:16156595,glow:10451690},factory:{primary:15567158,secondary:14510880,accent:16166229,glow:16755200}};function Mi(s){return s.name}function ni(s){const e=document.createElement("canvas"),t=e.getContext("2d"),n=56,a=28,i=72,o=144;e.width=1024,e.height=o,t.font=`bold ${n}px Arial`;const l=t.measureText(s).width,c=256,d=l+a*2+16;e.width=Math.max(c,d),t.clearRect(0,0,e.width,e.height),t.font=`bold ${n}px Arial`;const m=l+a*2,p=(e.width-m)/2,f=(e.height-i)/2;t.fillStyle="rgba(0, 0, 0, 0.8)",t.beginPath(),t.roundRect(p,f,m,i,10),t.fill(),t.textAlign="center",t.textBaseline="middle",t.fillStyle="#ffffff",t.fillText(s,e.width/2,e.height/2);const b=new Jn(e);b.minFilter=In,b.magFilter=In,b.needsUpdate=!0;const y=new Yn({map:b,transparent:!0,depthTest:!1}),w=new Hn(y),k=.5,S=e.width/e.height;return w.scale.set(k*S,k,1),w.userData.aspectRatio=S,w}function nM(s){const e=document.createElement("canvas"),t=e.getContext("2d");e.width=64,e.height=64,t.fillStyle="#c89a5a",t.beginPath(),t.arc(32,32,28,0,Math.PI*2),t.fill(),t.strokeStyle="rgba(0, 0, 0, 0.5)",t.lineWidth=3,t.beginPath(),t.arc(32,32,28,0,Math.PI*2),t.stroke(),t.fillStyle="#ffffff",t.font="bold 28px Arial",t.textAlign="center",t.textBaseline="middle",t.fillText(s>99?"99+":String(s),32,32);const n=new Jn(e);n.minFilter=In,n.magFilter=In;const a=new Yn({map:n,transparent:!0,depthTest:!1}),i=new Hn(a);return i.scale.set(.35,.35,1),i.name="gitIndicator",i}function eI(s,e){const t=s.material;t.map&&t.map.dispose(),t.dispose();const n=nM(e);s.material=n.material}function tI(s,e){const t=s.label,n=ni(e);n.position.copy(t.position),n.name="buildingLabel",s.group.remove(t),t.material instanceof Yn&&(t.material.map&&t.material.map.dispose(),t.material.dispose()),s.group.add(n),s.label=n}function nI(s){const e=new Bn;e.userData.buildingId=s.id,e.userData.isBuilding=!0;const t=s.color?new Bt(s.color):new Bt(2763322),n=new sn(1.2,2.5,.8),a=new rt({color:t,metalness:.7,roughness:.3}),i=new De(n,a);i.position.y=1.25,i.castShadow=!0,i.receiveShadow=!0,i.name="buildingBody",e.add(i);for(let C=0;C<5;C++){const A=new sn(1.1,.02,.75),D=new rt({color:1710634,metalness:.5,roughness:.5}),M=new De(A,D);M.position.set(0,.5+C*.45,.03),e.add(M)}for(let C=0;C<5;C++){const A=new sn(.08,.08,.05),D=new We({color:4915102,transparent:!0,opacity:.9}),M=new De(A,D);M.position.set(-.45,.5+C*.45,.43),M.name=`led_${C}`,e.add(M);const I=new De(A.clone(),D.clone());I.position.set(-.3,.5+C*.45,.43),I.name=`activityLed_${C}`,e.add(I)}const o=new sn(1,.1,.6),l=new rt({color:1710634,metalness:.3,roughness:.7}),c=new De(o,l);c.position.set(0,2.55,0),e.add(c);const d=new Ut(.15,16,16),m=new We({color:rs[s.status],transparent:!0,opacity:.95}),p=new De(d,m);p.position.set(0,2.75,0),p.name="statusLight",e.add(p);const f=new Ut(.25,16,16),b=new We({color:rs[s.status],transparent:!0,opacity:.3}),y=new De(f,b);y.position.set(0,2.75,0),y.name="statusGlow",e.add(y);const w=new sn(1.5,.1,1.1),k=new rt({color:3816010,metalness:.5,roughness:.5}),S=new De(w,k);S.position.y=.05,S.receiveShadow=!0,e.add(S);const j=ni(Mi(s));return j.position.set(0,3.2,0),j.name="buildingLabel",e.add(j),e.position.set(s.position.x,0,s.position.z),{group:e,statusLight:p,label:j}}function sI(s,e){for(let t=0;t<5;t++){const n=s.group.getObjectByName(`led_${t}`);if(n&&n.material instanceof We){const i=Math.sin(e*.8+t*1.2);n.material.opacity=i>.3?.6:.15}const a=s.group.getObjectByName(`activityLed_${t}`);a&&a.material instanceof We&&(a.material.opacity=Math.random()>.97?.5:.1)}}function aI(s,e){for(let t=0;t<5;t++){const n=s.group.getObjectByName(`activityLed_${t}`);n&&n.material instanceof We&&Math.random()>.95&&(n.material.opacity=n.material.opacity>.5?.2:.9)}}function iI(s){const e=new Bn;e.userData.buildingId=s.id,e.userData.isBuilding=!0;const t=s.color?new Bt(s.color):new Bt(2767434),n=new Un(.5,.7,3,8),a=new rt({color:t,metalness:.6,roughness:.4}),i=new De(n,a);i.position.y=1.5,i.castShadow=!0,i.receiveShadow=!0,i.name="buildingBody",e.add(i);for(let L=0;L<4;L++){const R=new Un(.52-L*.03,.62-L*.03,.1,8),z=new We({color:4890367,transparent:!0,opacity:.7}),F=new De(R,z);F.position.y=.7+L*.6,F.name=`windowBand_${L}`,e.add(F)}const o=new Un(.6,.5,.2,8),l=new rt({color:3816010,metalness:.7,roughness:.3}),c=new De(o,l);c.position.y=3.1,e.add(c);const d=new Un(.15,.2,.3,6),m=new rt({color:4868698,metalness:.8,roughness:.2}),p=new De(d,m);p.position.y=3.35,e.add(p);const f=new Bn;f.position.y=3.6,f.name="antenna";const b=new sn(.05,.6,.05),y=new rt({color:6974074,metalness:.9,roughness:.1}),w=new De(b,y);w.position.y=.3,f.add(w);const k=new uc(.15,.1,8);for(let L=0;L<2;L++){const R=new De(k,y);R.rotation.x=Math.PI/2,R.position.set(L===0?.2:-.2,.4,0),R.rotation.z=L===0?Math.PI/2:-Math.PI/2,f.add(R)}e.add(f);const S=new Ut(.12,16,16),j=new We({color:rs[s.status],transparent:!0,opacity:.95}),C=new De(S,j);C.position.set(0,4.3,0),C.name="statusLight",e.add(C);const A=new Ut(.2,16,16),D=new We({color:rs[s.status],transparent:!0,opacity:.3}),M=new De(A,D);M.position.set(0,4.3,0),M.name="statusGlow",e.add(M);const I=new Un(.9,1,.15,8),E=new rt({color:3816010,metalness:.5,roughness:.5}),_=new De(I,E);_.position.y=.075,_.receiveShadow=!0,e.add(_);const P=ni(Mi(s));return P.position.set(0,4.7,0),P.name="buildingLabel",e.add(P),e.position.set(s.position.x,0,s.position.z),{group:e,statusLight:C,label:P}}function rI(s,e,t){const n=s.group.getObjectByName("antenna");n&&(n.rotation.y+=t*.3);for(let a=0;a<4;a++){const i=s.group.getObjectByName(`windowBand_${a}`);i&&i.material instanceof We&&(i.material.opacity=.3+Math.sin(e*.5+a*.4)*.15)}}function oI(s,e,t){const n=s.group.getObjectByName("antenna");n&&(n.rotation.y+=t*2);for(let a=0;a<4;a++){const i=s.group.getObjectByName(`windowBand_${a}`);if(i&&i.material instanceof We){const o=Math.sin(e*4+a*.5)*.3+.7;i.material.opacity=o}}}function lI(s){const e=new Bn;e.userData.buildingId=s.id,e.userData.isBuilding=!0;const t=s.color?new Bt(s.color):new Bt(2763338),n=new Ut(1.2,32,16,0,Math.PI*2,0,Math.PI/2),a=new rt({color:t,metalness:.4,roughness:.6,transparent:!0,opacity:.9}),i=new De(n,a);i.position.y=.15,i.castShadow=!0,i.receiveShadow=!0,i.name="buildingBody",e.add(i);const o=new Ut(.8,24,12,0,Math.PI*2,0,Math.PI/2),l=new We({color:4890367,transparent:!0,opacity:.3}),c=new De(o,l);c.position.y=.15,c.name="innerDome",e.add(c);const d=new ac(1,.05,8,32),m=new We({color:4915102,transparent:!0,opacity:.8}),p=new De(d,m);p.position.y=.6,p.rotation.x=Math.PI/2,p.name="energyRing",e.add(p);const f=new De(d.clone(),m.clone());f.position.y=.8,f.rotation.x=Math.PI/3,f.name="energyRing2",e.add(f);for(let I=0;I<4;I++){const E=new Un(.03,.03,1.2,8),_=new We({color:4890367,transparent:!0,opacity:.6}),P=new De(E,_),L=I/4*Math.PI*2;P.position.set(Math.cos(L)*.5,.75,Math.sin(L)*.5),P.name=`beam_${I}`,e.add(P)}const b=new Ut(.15,16,16),y=new We({color:rs[s.status],transparent:!0,opacity:.95}),w=new De(b,y);w.position.set(0,1.4,0),w.name="statusLight",e.add(w);const k=new Ut(.25,16,16),S=new We({color:rs[s.status],transparent:!0,opacity:.3}),j=new De(k,S);j.position.set(0,1.4,0),j.name="statusGlow",e.add(j);const C=new Un(1.4,1.5,.15,32),A=new rt({color:3816010,metalness:.6,roughness:.4}),D=new De(C,A);D.position.y=.075,D.receiveShadow=!0,e.add(D);const M=ni(Mi(s));return M.position.set(0,1.9,0),M.name="buildingLabel",e.add(M),e.position.set(s.position.x,0,s.position.z),{group:e,statusLight:w,label:M}}function cI(s,e,t){const n=s.group.getObjectByName("energyRing"),a=s.group.getObjectByName("energyRing2");n&&(n.rotation.z+=t*.2),a&&(a.rotation.z-=t*.15);const i=s.group.getObjectByName("innerDome");i&&i.material instanceof We&&(i.material.opacity=.15+Math.sin(e*.6)*.1);for(let o=0;o<4;o++){const l=s.group.getObjectByName(`beam_${o}`);l&&l.material instanceof We&&(l.material.opacity=.2+Math.sin(e*.5+o*.3)*.1)}}function uI(s,e,t){const n=s.group.getObjectByName("energyRing"),a=s.group.getObjectByName("energyRing2");n&&(n.rotation.z+=t*1.5),a&&(a.rotation.z-=t*1.2);const i=s.group.getObjectByName("innerDome");i&&i.material instanceof We&&(i.material.opacity=.2+Math.sin(e*2)*.15);for(let o=0;o<4;o++){const l=s.group.getObjectByName(`beam_${o}`);if(l&&l.material instanceof We){const c=Math.sin(e*5+o*1.5)*.3+.6;l.material.opacity=c}}}function dI(s){const e=new Bn;e.userData.buildingId=s.id,e.userData.isBuilding=!0;const t=s.color?new Bt(s.color):new Bt(3815978),n=new uc(1.3,2.5,4),a=new rt({color:t,metalness:.3,roughness:.7}),i=new De(n,a);i.position.y=1.25,i.rotation.y=Math.PI/4,i.castShadow=!0,i.receiveShadow=!0,i.name="buildingBody",e.add(i);const o=new uc(.6,1.2,4),l=new We({color:16755200,transparent:!0,opacity:.6}),c=new De(o,l);c.position.y=.8,c.rotation.y=Math.PI/4,c.name="pyramidCore",e.add(c);const d=[{x:.9,z:0},{x:-.9,z:0},{x:0,z:.9},{x:0,z:-.9}];for(let P=0;P<4;P++){const L=new Un(.02,.02,2.7,8),R=new We({color:4915102,transparent:!0,opacity:.7}),z=new De(L,R),F=d[P];z.position.set(F.x*.5,1.25,F.z*.5);const $=Math.atan2(1.25,.65);P<2?z.rotation.z=P===0?-$:$:z.rotation.x=P===2?$:-$,z.name=`edgeLine_${P}`,e.add(z)}const m=new Ut(.15,16,16),p=new We({color:16755200,transparent:!0,opacity:.9}),f=new De(m,p);f.position.y=2.7,f.name="pyramidEye",e.add(f);const b=new Ut(.25,16,16),y=new We({color:16755200,transparent:!0,opacity:.3}),w=new De(b,y);w.position.y=2.7,w.name="pyramidEyeGlow",e.add(w);const k=new Ut(.12,16,16),S=new We({color:rs[s.status],transparent:!0,opacity:.95}),j=new De(k,S);j.position.set(1.2,.3,0),j.name="statusLight",e.add(j);const C=new Ut(.2,16,16),A=new We({color:rs[s.status],transparent:!0,opacity:.3}),D=new De(C,A);D.position.set(1.2,.3,0),D.name="statusGlow",e.add(D);const M=new sn(2.8,.15,2.8),I=new rt({color:4868666,metalness:.2,roughness:.8}),E=new De(M,I);E.position.y=.075,E.receiveShadow=!0,e.add(E);const _=ni(Mi(s));return _.position.set(0,3.2,0),_.name="buildingLabel",e.add(_),e.position.set(s.position.x,0,s.position.z),{group:e,statusLight:j,label:_}}function hI(s,e){const t=s.group.getObjectByName("pyramidEye"),n=s.group.getObjectByName("pyramidEyeGlow");t&&(t.position.y=2.7+Math.sin(e*.5)*.03,t.material instanceof We&&(t.material.opacity=.4+Math.sin(e*.7)*.2)),n&&(n.position.y=2.7+Math.sin(e*.5)*.03,n.material instanceof We&&(n.material.opacity=.15+Math.sin(e*.7)*.1));const a=s.group.getObjectByName("pyramidCore");a&&a.material instanceof We&&(a.material.opacity=.2+Math.sin(e*.5)*.1)}function pI(s,e){const t=s.group.getObjectByName("pyramidCore");t&&t.material instanceof We&&(t.material.opacity=.4+Math.sin(e*2)*.2);const n=s.group.getObjectByName("pyramidEye"),a=s.group.getObjectByName("pyramidEyeGlow");n&&n.material instanceof We&&(n.material.opacity=.7+Math.sin(e*3)*.3),a&&a.material instanceof We&&(a.material.opacity=.2+Math.sin(e*3)*.15),n&&(n.position.y=2.7+Math.sin(e*1.5)*.1),a&&(a.position.y=2.7+Math.sin(e*1.5)*.1)}function mI(s){const e=new Bn;e.userData.buildingId=s.id,e.userData.isBuilding=!0;const t=fd.desktop,n=s.color?new Bt(s.color):new Bt(t.primary),a=new sn(1.4,1,.15),i=new rt({color:n,metalness:.4,roughness:.6}),o=new De(a,i);o.position.set(0,1.4,0),o.castShadow=!0,o.name="buildingBody",e.add(o);const l=new sn(1.2,.8,.02),c=new We({color:661032,transparent:!0,opacity:.95}),d=new De(l,c);d.position.set(0,1.4,.09),d.name="screen",e.add(d);for(let K=0;K<6;K++){const Z=new sn(.8-K%3*.2,.05,.01),B=new We({color:t.glow,transparent:!0,opacity:.9}),ee=new De(Z,B);ee.position.set(-.1+K%2*.1,1.65-K*.1,.1),ee.name=`codeLine_${K}`,e.add(ee)}const m=new sn(.15,.6,.15),p=new rt({color:t.secondary,metalness:.5,roughness:.5}),f=new De(m,p);f.position.set(0,.6,0),e.add(f);const b=new sn(.6,.08,.4),y=new De(b,p);y.position.set(0,.25,0),e.add(y);const w=new sn(1,.08,.35),k=new rt({color:t.secondary,metalness:.3,roughness:.7}),S=new De(w,k);S.position.set(0,.2,.6),S.rotation.x=-.1,e.add(S);for(let K=0;K<3;K++)for(let Z=0;Z<10;Z++){const B=new sn(.07,.03,.07),ee=new rt({color:t.accent,metalness:.2,roughness:.8}),se=new De(B,ee);se.position.set(-.38+Z*.085,.25,.45+K*.1),e.add(se)}const j=new sn(.4,.9,.8),C=new rt({color:n,metalness:.4,roughness:.6}),A=new De(j,C);A.position.set(-1.1,.55,0),A.castShadow=!0,e.add(A);const D=new sn(.05,.05,.02),M=new We({color:4915102,transparent:!0,opacity:.9}),I=new De(D,M);I.position.set(-.88,.7,.3),I.name="cpuLed",e.add(I);const E=new Ut(.1,16,16),_=new We({color:rs[s.status],transparent:!0,opacity:.95}),P=new De(E,_);P.position.set(.6,1.85,.1),P.name="statusLight",e.add(P);const L=new Ut(.18,16,16),R=new We({color:rs[s.status],transparent:!0,opacity:.3}),z=new De(L,R);z.position.set(.6,1.85,.1),z.name="statusGlow",e.add(z);const F=new sn(2.6,.1,1.4),$=new rt({color:3816010,metalness:.5,roughness:.5}),U=new De(F,$);U.position.y=.05,U.receiveShadow=!0,e.add(U);const G=ni(Mi(s));return G.position.set(0,2.3,0),G.name="buildingLabel",e.add(G),e.position.set(s.position.x,0,s.position.z),{group:e,statusLight:P,label:G}}function fI(s,e){const t=s.group.getObjectByName("buildingBody");t&&(t.rotation.y=Math.sin(e*.3)*.01);for(let n=0;n<6;n++){const a=s.group.getObjectByName(`codeLine_${n}`);a&&a.material instanceof We&&(a.material.opacity=.3+Math.sin(e*.4+n*.2)*.1)}}function gI(s,e){for(let n=0;n<6;n++){const a=s.group.getObjectByName(`codeLine_${n}`);if(a&&a.material instanceof We){const i=Math.random()>.98?.4:.8;a.material.opacity=i}}const t=s.group.getObjectByName("cpuLed");if(t&&t.material instanceof We){const n=Math.sin(e*6)>0?.9:.3;t.material.opacity=n}}function bI(s){const e=new Bn;e.userData.buildingId=s.id,e.userData.isBuilding=!0;const t=fd["filing-cabinet"],n=s.color?new Bt(s.color):new Bt(t.primary),a=new sn(1,2.4,.8),i=new rt({color:n,metalness:.5,roughness:.5}),o=new De(a,i);o.position.y=1.2,o.castShadow=!0,o.name="buildingBody",e.add(o);for(let S=0;S<4;S++){const j=new sn(.9,.5,.05),C=new rt({color:t.secondary,metalness:.4,roughness:.6}),A=new De(j,C);A.position.set(0,.35+S*.55,.4),A.name=`drawer_${S}`,e.add(A);const D=new sn(.3,.06,.05),M=new rt({color:t.accent,metalness:.7,roughness:.3}),I=new De(D,M);I.position.set(0,.35+S*.55,.47),I.name=`handle_${S}`,e.add(I);const E=new sn(.4,.15,.02),_=new We({color:16777198}),P=new De(E,_);P.position.set(0,.45+S*.55,.44),e.add(P)}for(let S=0;S<4;S++){const j=new sn(.06,.06,.02),C=new We({color:S%2===0?t.glow:t.accent,transparent:!0,opacity:.9}),A=new De(j,C);A.position.set(-.38,.35+S*.55,.42),A.name=`indicator_${S}`,e.add(A)}const l=new Ut(.12,16,16),c=new We({color:rs[s.status],transparent:!0,opacity:.95}),d=new De(l,c);d.position.set(0,2.55,0),d.name="statusLight",e.add(d);const m=new Ut(.2,16,16),p=new We({color:rs[s.status],transparent:!0,opacity:.3}),f=new De(m,p);f.position.set(0,2.55,0),f.name="statusGlow",e.add(f);const b=new sn(1.3,.1,1.1),y=new rt({color:3816010,metalness:.5,roughness:.5}),w=new De(b,y);w.position.y=.05,w.receiveShadow=!0,e.add(w);const k=ni(Mi(s));return k.position.set(0,3,0),k.name="buildingLabel",e.add(k),e.position.set(s.position.x,0,s.position.z),{group:e,statusLight:d,label:k}}function yI(s,e){s.group.rotation.y=Math.sin(e*.5)*.005;for(let t=0;t<4;t++){const n=s.group.getObjectByName(`indicator_${t}`);n&&n.material instanceof We&&(n.material.opacity=.3+Math.sin(e*.6+t*.4)*.15)}}function xI(s,e){for(let t=0;t<4;t++){const n=s.group.getObjectByName(`indicator_${t}`);if(n&&n.material instanceof We){const a=Math.sin(e*3+t*.8)*.3+.7;n.material.opacity=a}}for(let t=0;t<4;t++){const n=s.group.getObjectByName(`handle_${t}`);n&&(n.position.z=.47+Math.sin(e*8+t)*.005)}}function vI(s){const e=new Bn;e.userData.buildingId=s.id,e.userData.isBuilding=!0;const t=fd.satellite,n=s.color?new Bt(s.color):new Bt(t.primary),a=new Un(.1,.15,2,8),i=new rt({color:t.secondary,metalness:.6,roughness:.4}),o=new De(a,i);o.position.y=1,o.castShadow=!0,e.add(o);const l=new sn(.3,.2,.3),c=new De(l,i);c.position.y=2.1,e.add(c);const d=new Bn;d.position.y=2.3,d.name="dishGroup";const m=new Ut(1,32,16,0,Math.PI*2,0,Math.PI/3),p=new rt({color:n,metalness:.5,roughness:.5,side:ws}),f=new De(m,p);f.rotation.x=Math.PI/2+.3,f.name="buildingBody",d.add(f);const b=new Ut(.95,32,16,0,Math.PI*2,0,Math.PI/3),y=new rt({color:t.accent,metalness:.3,roughness:.7,side:mA}),w=new De(b,y);w.rotation.x=Math.PI/2+.3,d.add(w);const k=new Un(.03,.03,.8,8),S=new rt({color:t.secondary,metalness:.6,roughness:.4}),j=new De(k,S);j.position.set(0,.1,.5),j.rotation.x=-.6,d.add(j);const C=new uc(.1,.2,8),A=new rt({color:t.accent,metalness:.4,roughness:.6}),D=new De(C,A);D.position.set(0,.5,.85),D.rotation.x=Math.PI/2-.6,d.add(D);const M=new Ut(.08,16,16),I=new We({color:t.glow,transparent:!0,opacity:.9}),E=new De(M,I);E.position.set(0,.55,.92),E.name="signal",d.add(E),e.add(d);for(let Z=0;Z<3;Z++){const B=new Xo(.2+Z*.15,.22+Z*.15,16),ee=new We({color:t.glow,transparent:!0,opacity:.6-Z*.15,side:ws}),se=new De(B,ee);se.position.set(0,2.85+Z*.1,.92+Z*.1),se.rotation.x=-.6,se.name=`wave_${Z}`,e.add(se)}const _=new Ut(.1,16,16),P=new We({color:rs[s.status],transparent:!0,opacity:.95}),L=new De(_,P);L.position.set(0,.3,.5),L.name="statusLight",e.add(L);const R=new Ut(.18,16,16),z=new We({color:rs[s.status],transparent:!0,opacity:.3}),F=new De(R,z);F.position.set(0,.3,.5),F.name="statusGlow",e.add(F);const $=new Un(.6,.7,.15,16),U=new rt({color:t.secondary,metalness:.5,roughness:.5}),G=new De($,U);G.position.y=.075,G.receiveShadow=!0,e.add(G);const K=ni(Mi(s));return K.position.set(0,3.8,0),K.name="buildingLabel",e.add(K),e.position.set(s.position.x,0,s.position.z),{group:e,statusLight:L,label:K}}function wI(s,e,t){const n=s.group.getObjectByName("dishGroup");n&&(n.rotation.y+=t*.1);for(let a=0;a<3;a++){const i=s.group.getObjectByName(`wave_${a}`);i&&i.material instanceof We&&(i.material.opacity=.15+Math.sin(e*.5+a*.3)*.1)}}function kI(s,e,t){const n=s.group.getObjectByName("dishGroup");n&&(n.rotation.y+=t*.5);const a=s.group.getObjectByName("signal");a&&a.material instanceof We&&(a.material.opacity=.6+Math.sin(e*8)*.4);for(let i=0;i<3;i++){const o=s.group.getObjectByName(`wave_${i}`);if(o&&o.material instanceof We){const l=1+Math.sin(e*4+i)*.1;o.scale.set(l,l,1),o.material.opacity=(.5-i*.15)*(.5+Math.sin(e*4+i)*.5)}}}function SI(s){const e=new Bn;e.userData.buildingId=s.id,e.userData.isBuilding=!0;const t=fd.crystal,n=s.color?new Bt(s.color):new Bt(t.primary),a=new nS(.8),i=new rt({color:n,metalness:.3,roughness:.2,transparent:!0,opacity:.85}),o=new De(a,i);o.position.y=1.8,o.castShadow=!0,o.name="buildingBody",e.add(o);const l=new nS(.5),c=new We({color:t.glow,transparent:!0,opacity:.6}),d=new De(l,c);d.position.y=1.8,d.name="crystalInner",e.add(d);for(let z=0;z<6;z++){const F=new Ut(.06,8,8),$=new We({color:z%2===0?t.accent:t.glow,transparent:!0,opacity:.9}),U=new De(F,$),G=z/6*Math.PI*2;U.position.set(Math.cos(G)*1.2,1.8+Math.sin(G*2)*.3,Math.sin(G)*1.2),U.name=`particle_${z}`,e.add(U)}const m=new KD(1.3,1),p=new We({color:t.accent,wireframe:!0,transparent:!0,opacity:.4}),f=new De(m,p);f.position.y=1.8,f.name="energyField",e.add(f);const b=new Un(.3,.5,.8,6),y=new rt({color:t.secondary,metalness:.5,roughness:.5}),w=new De(b,y);w.position.y=.4,e.add(w);const k=new Un(.05,.05,.9,8),S=new We({color:t.glow,transparent:!0,opacity:.7}),j=new De(k,S);j.position.y=1.25,j.name="energyBeam",e.add(j);const C=new Ut(.1,16,16),A=new We({color:rs[s.status],transparent:!0,opacity:.95}),D=new De(C,A);D.position.set(.7,.5,0),D.name="statusLight",e.add(D);const M=new Ut(.18,16,16),I=new We({color:rs[s.status],transparent:!0,opacity:.3}),E=new De(M,I);E.position.set(.7,.5,0),E.name="statusGlow",e.add(E);const _=new Un(.8,.9,.1,6),P=new rt({color:t.secondary,metalness:.6,roughness:.4}),L=new De(_,P);L.position.y=.05,L.receiveShadow=!0,e.add(L);const R=ni(Mi(s));return R.position.set(0,3,0),R.name="buildingLabel",e.add(R),e.position.set(s.position.x,0,s.position.z),{group:e,statusLight:D,label:R}}function jI(s,e,t){const n=s.group.getObjectByName("buildingBody");n&&(n.rotation.y+=t*.2,n.position.y=1.8+Math.sin(e*.8)*.05);const a=s.group.getObjectByName("crystalInner");a&&(a.rotation.y-=t*.3,a.position.y=1.8+Math.sin(e*.8)*.05,a.material instanceof We&&(a.material.opacity=.25+Math.sin(e*.6)*.15));const i=s.group.getObjectByName("energyField");i&&(i.rotation.y+=t*.1,i.position.y=1.8+Math.sin(e*.8)*.05,i.material instanceof We&&(i.material.opacity=.15+Math.sin(e*.5)*.1));for(let l=0;l<6;l++){const c=s.group.getObjectByName(`particle_${l}`);if(c){const d=l/6*Math.PI*2+e*.3;c.position.x=Math.cos(d)*1.2,c.position.z=Math.sin(d)*1.2,c.position.y=1.8+Math.sin(e*.8)*.05+Math.sin(d*2)*.2}}const o=s.group.getObjectByName("energyBeam");o&&o.material instanceof We&&(o.material.opacity=.2+Math.sin(e*.7)*.15)}function CI(s,e,t){const n=s.group.getObjectByName("buildingBody"),a=s.group.getObjectByName("crystalInner"),i=s.group.getObjectByName("energyField");n&&(n.rotation.y+=t*.8,n.position.y=1.8+Math.sin(e*1.5)*.1),a&&(a.rotation.y-=t*1.2,a.position.y=1.8+Math.sin(e*1.5)*.1,a.material instanceof We&&(a.material.opacity=.4+Math.sin(e*3)*.2)),i&&(i.rotation.y+=t*.3,i.rotation.x+=t*.2,i.position.y=1.8+Math.sin(e*1.5)*.1);for(let l=0;l<6;l++){const c=s.group.getObjectByName(`particle_${l}`);if(c){const d=l/6*Math.PI*2+e*1.5,m=1.2+Math.sin(e*2+l)*.1;c.position.x=Math.cos(d)*m,c.position.z=Math.sin(d)*m,c.position.y=1.8+Math.sin(e*1.5)*.1+Math.sin(d*2)*.3}}const o=s.group.getObjectByName("energyBeam");o&&o.material instanceof We&&(o.material.opacity=.4+Math.sin(e*4)*.3)}function NI(s){const e=new Bn;e.userData.buildingId=s.id,e.userData.isBuilding=!0;const t=fd.factory,n=s.color?new Bt(s.color):new Bt(t.primary),a=new sn(1.8,1.2,1.2),i=new rt({color:n,metalness:.4,roughness:.6}),o=new De(a,i);o.position.set(0,.6,0),o.castShadow=!0,o.name="buildingBody",e.add(o);const l=new sn(2,.15,1.4),c=new rt({color:t.secondary,metalness:.5,roughness:.5}),d=new De(l,c);d.position.set(0,1.25,0),d.rotation.z=.05,e.add(d);const m=new Un(.15,.18,1.2,8),p=new rt({color:t.secondary,metalness:.5,roughness:.5}),f=new De(m,p);f.position.set(.5,1.8,.3),e.add(f);const b=new ac(.17,.03,8,16),y=new De(b,p);y.position.set(.5,2.4,.3),y.rotation.x=Math.PI/2,e.add(y);for(let Z=0;Z<4;Z++){const B=new Ut(.08+Z*.03,8,8),ee=new We({color:11184810,transparent:!0,opacity:.7-Z*.12}),se=new De(B,ee);se.position.set(.5,2.5+Z*.25,.3),se.name=`smoke_${Z}`,e.add(se)}for(let Z=0;Z<3;Z++){const B=new sn(.25,.35,.05),ee=new We({color:t.glow,transparent:!0,opacity:.9}),se=new De(B,ee);se.position.set(-.6+Z*.5,.7,.63),se.name=`window_${Z}`,e.add(se)}const w=new sn(.4,.6,.05),k=new rt({color:t.secondary,metalness:.4,roughness:.6}),S=new De(w,k);S.position.set(.6,.35,.63),e.add(S);const j=new sn(.3,.1,1.6),C=new rt({color:t.secondary,metalness:.6,roughness:.4}),A=new De(j,C);A.position.set(-1,.25,0),e.add(A);for(let Z=0;Z<3;Z++){const B=new sn(.15,.15,.15),ee=new We({color:Z%2===0?t.accent:t.glow}),se=new De(B,ee);se.position.set(-1,.38,-.5+Z*.4),se.name=`conveyorItem_${Z}`,e.add(se)}const D=new ac(.2,.05,6,8),M=new rt({color:t.accent,metalness:.6,roughness:.4}),I=new De(D,M);I.position.set(-.8,.9,.63),I.name="gear1",e.add(I);const E=new De(D.clone(),M.clone());E.position.set(-.5,1.05,.63),E.name="gear2",e.add(E);const _=new Ut(.12,16,16),P=new We({color:rs[s.status],transparent:!0,opacity:.95}),L=new De(_,P);L.position.set(.85,1,.65),L.name="statusLight",e.add(L);const R=new Ut(.2,16,16),z=new We({color:rs[s.status],transparent:!0,opacity:.3}),F=new De(R,z);F.position.set(.85,1,.65),F.name="statusGlow",e.add(F);const $=new sn(2.4,.1,1.8),U=new rt({color:4868682,metalness:.4,roughness:.6}),G=new De($,U);G.position.y=.05,G.receiveShadow=!0,e.add(G);const K=ni(Mi(s));return K.position.set(0,2.9,0),K.name="buildingLabel",e.add(K),e.position.set(s.position.x,0,s.position.z),{group:e,statusLight:L,label:K}}function AI(s,e,t){const n=s.group.getObjectByName("gear1"),a=s.group.getObjectByName("gear2");n&&(n.rotation.z+=t*.3),a&&(a.rotation.z-=t*.4);for(let i=0;i<3;i++){const o=s.group.getObjectByName(`window_${i}`);o&&o.material instanceof We&&(o.material.opacity=.3+Math.sin(e*.4+i*.5)*.15)}for(let i=0;i<3;i++){const o=s.group.getObjectByName(`conveyorItem_${i}`);o&&(o.position.z=(o.position.z+t*.05+.5)%1.2-.5)}for(let i=0;i<4;i++){const o=s.group.getObjectByName(`smoke_${i}`);if(o){const l=2.5+i*.25,c=(e*.15+i*.3)%1.5;o.position.y=l+c,o.position.x=.5+Math.sin(e*.3+i)*.05,o.material instanceof We&&(o.material.opacity=Math.max(0,(.25-i*.05)*(1-c/1.5)))}}}function MI(s,e,t){for(let i=0;i<4;i++){const o=s.group.getObjectByName(`smoke_${i}`);if(o){const l=2.5+i*.25,c=(e*.5+i*.3)%1.5;o.position.y=l+c,o.position.x=.5+Math.sin(e+i)*.1,o.material instanceof We&&(o.material.opacity=Math.max(0,(.6-i*.12)*(1-c/1.5))),c>1.4&&(o.position.y=l)}}const n=s.group.getObjectByName("gear1"),a=s.group.getObjectByName("gear2");n&&(n.rotation.z+=t*2),a&&(a.rotation.z-=t*2.5);for(let i=0;i<3;i++){const o=s.group.getObjectByName(`conveyorItem_${i}`);o&&(o.position.z=(o.position.z+t*.3+.5)%1.2-.5)}for(let i=0;i<3;i++){const o=s.group.getObjectByName(`window_${i}`);if(o&&o.material instanceof We){const l=Math.random()>.99?.5:.8;o.material.opacity=l}}}function TI(s){const e=new Bn;e.userData.buildingId=s.id,e.userData.isBuilding=!0;const t=s.color?new Bt(s.color):new Bt(2763322),n=16766720,a=new Un(1.8,2,.3,6),i=new rt({color:t,metalness:.7,roughness:.3}),o=new De(a,i);o.position.y=.15,o.receiveShadow=!0,e.add(o);const l=new Un(1.2,1.4,.2,6),c=new rt({color:3816010,metalness:.8,roughness:.2}),d=new De(l,c);d.position.y=.4,e.add(d);const m=new Un(.4,.6,2,6),p=new rt({color:t,metalness:.6,roughness:.4}),f=new De(m,p);f.position.y=1.5,f.castShadow=!0,f.receiveShadow=!0,f.name="buildingBody",e.add(f);const b=new Un(.5,.4,.3,6),y=new rt({color:n,metalness:.9,roughness:.1,emissive:new Bt(n),emissiveIntensity:.3}),w=new De(b,y);w.position.y=2.65,w.name="crownBase",e.add(w);for(let U=0;U<5;U++){const G=U/5*Math.PI*2,K=new uc(.08,.4,4),Z=new De(K,y);Z.position.set(Math.cos(G)*.35,2.95,Math.sin(G)*.35),Z.name=`crownSpike_${U}`,e.add(Z)}const k=new ac(.8,.03,8,32),S=new We({color:n,transparent:!0,opacity:.6}),j=new De(k,S);j.position.y=1.2,j.rotation.x=Math.PI/2,j.name="holoRing1",e.add(j);const C=new ac(1.1,.02,8,32),A=new We({color:4915102,transparent:!0,opacity:.5}),D=new De(C,A);D.position.y=1.5,D.rotation.x=Math.PI/2,D.name="holoRing2",e.add(D);const M=new ac(1.4,.02,8,32),I=new We({color:4890367,transparent:!0,opacity:.4}),E=new De(M,I);E.position.y=1.8,E.rotation.x=Math.PI/2,E.name="holoRing3",e.add(E);for(let U=0;U<6;U++){const G=U/6*Math.PI*2,K=new Bn,Z=new sn(.3,.25,.2),B=new rt({color:3816010,metalness:.6,roughness:.4}),ee=new De(Z,B);ee.position.y=.45,K.add(ee);const se=new tr(.25,.15),O=new We({color:4890367,transparent:!0,opacity:.8}),Y=new De(se,O);Y.position.y=.52,Y.position.z=.11,Y.rotation.x=-.3,Y.name=`consoleScreen_${U}`,K.add(Y),K.position.set(Math.cos(G)*1.5,0,Math.sin(G)*1.5),K.rotation.y=-G+Math.PI,e.add(K)}const _=new Ut(.15,16,16),P=new We({color:rs[s.status],transparent:!0,opacity:.95}),L=new De(_,P);L.position.set(0,3.3,0),L.name="statusLight",e.add(L);const R=new Ut(.25,16,16),z=new We({color:rs[s.status],transparent:!0,opacity:.3}),F=new De(R,z);F.position.set(0,3.3,0),F.name="statusGlow",e.add(F);for(let U=0;U<6;U++){const G=U/6*Math.PI*2+Math.PI/6,K=new Un(.06,.08,1,6),Z=new rt({color:n,metalness:.8,roughness:.2,emissive:new Bt(n),emissiveIntensity:.2}),B=new De(K,Z);B.position.set(Math.cos(G)*1.85,.8,Math.sin(G)*1.85),B.name=`energyPillar_${U}`,e.add(B);const ee=new Ut(.08,8,8),se=new We({color:n,transparent:!0,opacity:.8}),O=new De(ee,se);O.position.set(Math.cos(G)*1.85,1.35,Math.sin(G)*1.85),O.name=`pillarLight_${U}`,e.add(O)}const $=ni(Mi(s));return $.position.set(0,3.8,0),$.name="buildingLabel",e.add($),e.position.set(s.position.x,0,s.position.z),{group:e,statusLight:L,label:$}}function EI(s,e,t){const n=s.group.getObjectByName("holoRing1"),a=s.group.getObjectByName("holoRing2"),i=s.group.getObjectByName("holoRing3");n&&(n.rotation.z+=t*.3,n.material instanceof We&&(n.material.opacity=.3+Math.sin(e*.5)*.1)),a&&(a.rotation.z-=t*.2,a.material instanceof We&&(a.material.opacity=.25+Math.sin(e*.7+1)*.1)),i&&(i.rotation.z+=t*.1,i.material instanceof We&&(i.material.opacity=.2+Math.sin(e*.4+2)*.1));for(let o=0;o<6;o++){const l=s.group.getObjectByName(`pillarLight_${o}`);l&&l.material instanceof We&&(l.material.opacity=.4+Math.sin(e*.5+o*.5)*.2)}for(let o=0;o<6;o++){const l=s.group.getObjectByName(`consoleScreen_${o}`);l&&l.material instanceof We&&(l.material.opacity=.4+Math.sin(e*.3+o*.3)*.1)}}function _I(s,e,t){const n=s.group.getObjectByName("holoRing1"),a=s.group.getObjectByName("holoRing2"),i=s.group.getObjectByName("holoRing3");n&&(n.rotation.z+=t*1.5,n.rotation.x=Math.PI/2+Math.sin(e*2)*.1,n.material instanceof We&&(n.material.opacity=.5+Math.sin(e*3)*.2)),a&&(a.rotation.z-=t*1,a.rotation.x=Math.PI/2+Math.sin(e*1.5+1)*.15,a.material instanceof We&&(a.material.opacity=.4+Math.sin(e*2.5+1)*.15)),i&&(i.rotation.z+=t*.5,i.rotation.x=Math.PI/2+Math.sin(e*1+2)*.1,i.material instanceof We&&(i.material.opacity=.35+Math.sin(e*2+2)*.15));for(let l=0;l<6;l++){const c=s.group.getObjectByName(`pillarLight_${l}`);if(c&&c.material instanceof We){const d=(e*2+l*.3)%(Math.PI*2);c.material.opacity=.6+Math.sin(d)*.3}}for(let l=0;l<6;l++){const c=s.group.getObjectByName(`consoleScreen_${l}`);if(c&&c.material instanceof We){c.material.opacity=.7+Math.sin(e*4+l*.5)*.2;const d=(e*.1+l*.1)%1;c.material.color.setHSL(d*.2+.5,.8,.5)}}const o=s.group.getObjectByName("crownBase");o&&o.material instanceof rt&&(o.material.emissiveIntensity=.4+Math.sin(e*2)*.2)}function DI(s){switch(s.style||"server-rack"){case"tower":return iI(s);case"dome":return lI(s);case"pyramid":return dI(s);case"desktop":return mI(s);case"filing-cabinet":return bI(s);case"satellite":return vI(s);case"crystal":return SI(s);case"factory":return NI(s);case"command-center":return TI(s);case"server-rack":default:return nI(s)}}function PI(s,e,t,n){switch(e.style||"server-rack"){case"server-rack":sI(s,t);break;case"desktop":fI(s,t);break;case"filing-cabinet":yI(s,t);break;case"satellite":wI(s,t,n);break;case"crystal":jI(s,t,n);break;case"factory":AI(s,t,n);break;case"tower":rI(s,t,n);break;case"dome":cI(s,t,n);break;case"pyramid":hI(s,t);break;case"command-center":EI(s,t,n);break}}function RI(s,e,t,n){const a=e.style||"server-rack",i=s.group.getObjectByName("statusGlow"),o=Math.sin(t*3)*.2+.8;switch(i&&i.material instanceof We&&(i.material.opacity=.3*o),a){case"server-rack":aI(s);break;case"tower":oI(s,t,n);break;case"dome":uI(s,t,n);break;case"pyramid":pI(s,t);break;case"desktop":gI(s,t);break;case"filing-cabinet":xI(s,t);break;case"satellite":kI(s,t,n);break;case"crystal":CI(s,t,n);break;case"factory":MI(s,t,n);break;case"command-center":_I(s,t,n);break}}function LI(s,e){const t=s.group.getObjectByName("statusGlow"),n=Math.sin(e*8)*.5+.5;t&&t.material instanceof We&&(t.material.opacity=.5*n)}function OI(s,e){const t=s.group.getObjectByName("statusGlow"),n=Math.sin(e*2)*.5+.5;t&&t.material instanceof We&&(t.material.opacity=.4*n)}class II{constructor(e){W(this,"scene");W(this,"buildingMeshes",new Map);W(this,"selectedBuildingIds",new Set);W(this,"animationTime",0);W(this,"brightness",1);W(this,"bossSubordinateLines",null);W(this,"bossSubordinateMaterial",null);W(this,"cachedBossConnections",[]);W(this,"maxLineSegments",50);W(this,"onBuildingClick",null);W(this,"onBuildingDoubleClick",null);this.scene=e}setOnBuildingClick(e){this.onBuildingClick=e}setOnBuildingDoubleClick(e){this.onBuildingDoubleClick=e}setBrightness(e){this.brightness=e;for(const t of this.buildingMeshes.values()){const n=t.group.getObjectByName("statusGlow");n&&n.material instanceof We&&(n.material.opacity=.3*e),t.group.traverse(a=>{if(a instanceof De&&a.material instanceof rt){const i=a.material;i.emissiveIntensity!==void 0&&(i.userData.baseEmissiveIntensity===void 0&&(i.userData.baseEmissiveIntensity=i.emissiveIntensity||1),i.emissiveIntensity=i.userData.baseEmissiveIntensity*e)}})}}addBuilding(e){this.removeBuilding(e.id);const t=DI(e);t.group.userData.style=e.style,t.group.userData.color=e.color||"";const n=e.scale||1;t.group.scale.setScalar(n),this.scene.add(t.group),this.buildingMeshes.set(e.id,t)}removeBuilding(e){const t=this.buildingMeshes.get(e);t&&(this.scene.remove(t.group),this.disposeGroup(t.group),this.buildingMeshes.delete(e))}setBuildingPosition(e,t){const n=this.buildingMeshes.get(e);n&&(n.group.position.set(t.x,0,t.z),this.updateBossLinePositions())}updateBuilding(e){var b;const t=this.buildingMeshes.get(e.id);if(!t){this.addBuilding(e);return}const n=t.group.userData.style,a=t.group.userData.color;if(n!==e.style||a!==(e.color||"")){this.removeBuilding(e.id),this.addBuilding(e);return}t.group.position.set(e.position.x,0,e.position.z);const i=e.scale||1;t.group.scale.setScalar(i);const o=rs[e.status],l=t.group.getObjectByName("statusLight");l&&l.material instanceof We&&l.material.color.setHex(o);const c=t.group.getObjectByName("statusGlow");c&&c.material instanceof We&&c.material.color.setHex(o),((b=t.label.material.map)==null?void 0:b.image)&&tI(t,e.name);const p=e.gitChangesCount||0,f=t.group.getObjectByName("gitIndicator");if(p>0){if(f)f.userData.gitCount!==p&&(eI(f,p),f.userData.gitCount=p);else{const y=nM(p),w=t.label.position;y.position.set(w.x+.6,w.y+.15,w.z),t.group.add(y),t.gitIndicator=y}t.gitIndicator&&(t.gitIndicator.userData.gitCount=p)}else if(f){t.group.remove(f);const y=f.material;y.map&&y.map.dispose(),y.dispose(),t.gitIndicator=void 0}}highlightBuilding(e){for(const t of this.selectedBuildingIds){const n=this.buildingMeshes.get(t);if(n){const a=n.group.getObjectByName("buildingBody");a&&a.material instanceof rt&&a.material.emissive.setHex(0)}}if(this.selectedBuildingIds.clear(),e){this.selectedBuildingIds.add(e);const t=this.buildingMeshes.get(e);if(t){const n=t.group.getObjectByName("buildingBody");n&&n.material instanceof rt&&n.material.emissive.setHex(2236996)}}this.updateBossConnectionLines()}highlightBuildings(e){for(const t of this.selectedBuildingIds){const n=this.buildingMeshes.get(t);if(n){const a=n.group.getObjectByName("buildingBody");a&&a.material instanceof rt&&a.material.emissive.setHex(0)}}this.selectedBuildingIds.clear();for(const t of e){this.selectedBuildingIds.add(t);const n=this.buildingMeshes.get(t);if(n){const a=n.group.getObjectByName("buildingBody");a&&a.material instanceof rt&&a.material.emissive.setHex(2236996)}}this.updateBossConnectionLines()}getBuildingMeshData(){return this.buildingMeshes}getHitboxForStyle(e){switch(e){case"desktop":return{halfWidth:2,halfDepth:2};case"filing-cabinet":return{halfWidth:1.8,halfDepth:1.2};case"factory":return{halfWidth:1.5,halfDepth:1.2};case"satellite":return{halfWidth:1.2,halfDepth:1.2};case"crystal":return{halfWidth:1.5,halfDepth:1.5};case"tower":return{halfWidth:1.2,halfDepth:1};case"dome":return{halfWidth:1.5,halfDepth:1.5};case"pyramid":return{halfWidth:1.5,halfDepth:1.5};case"command-center":return{halfWidth:2.2,halfDepth:2.2};case"server-rack":default:return{halfWidth:1.2,halfDepth:1}}}getBuildingAtPosition(e){const t=H.getState();for(const n of t.buildings.values()){const a=this.getHitboxForStyle(n.style),i=n.scale||1,o={halfWidth:a.halfWidth*i,halfDepth:a.halfDepth*i},l=Math.abs(e.x-n.position.x),c=Math.abs(e.z-n.position.z);if(l<=o.halfWidth&&c<=o.halfDepth)return n}return null}getBuildingMeshes(){return Array.from(this.buildingMeshes.values()).map(e=>e.group)}syncFromStore(){const e=H.getState();for(const t of this.buildingMeshes.keys())e.buildings.has(t)||this.removeBuilding(t);for(const t of e.buildings.values())this.buildingMeshes.has(t.id)?this.updateBuilding(t):this.addBuilding(t)}update(e){this.animationTime+=e;const t=H.getState();for(const[n,a]of this.buildingMeshes){const i=t.buildings.get(n);i&&(PI(a,i,this.animationTime,e),i.status==="running"?RI(a,i,this.animationTime,e):i.status==="starting"||i.status==="stopping"?LI(a,this.animationTime):i.status==="error"&&OI(a,this.animationTime))}}updateBossConnectionLines(){var a;const e=H.getState(),t=[],n=new Set;for(const i of this.selectedBuildingIds){const o=e.buildings.get(i);if(o&&o.type==="boss"&&o.subordinateBuildingIds){t.push(o);for(const l of o.subordinateBuildingIds)n.add(l)}if(o){for(const[,l]of e.buildings)if(l.type==="boss"&&((a=l.subordinateBuildingIds)!=null&&a.includes(o.id))&&!t.find(c=>c.id===l.id)){t.push(l);for(const c of l.subordinateBuildingIds||[])n.add(c)}}}this.cachedBossConnections=[];for(const i of t)if(!(!this.buildingMeshes.get(i.id)||!i.subordinateBuildingIds))for(const l of i.subordinateBuildingIds)this.buildingMeshes.get(l)&&this.cachedBossConnections.push({bossId:i.id,subId:l});if(this.cachedBossConnections.length>0){if(!this.bossSubordinateLines){const l=new Float32Array(this.maxLineSegments*6),c=new La;c.setAttribute("position",new Ka(l,3)),c.setDrawRange(0,0),this.bossSubordinateMaterial=new Io({color:16766720,transparent:!0,opacity:.4}),this.bossSubordinateLines=new nx(c,this.bossSubordinateMaterial),this.bossSubordinateLines.frustumCulled=!1,this.scene.add(this.bossSubordinateLines)}const i=this.bossSubordinateLines.geometry.attributes.position,o=i.array;for(let l=0;l<this.cachedBossConnections.length&&l<this.maxLineSegments;l++){const{bossId:c,subId:d}=this.cachedBossConnections[l],m=this.buildingMeshes.get(c),p=this.buildingMeshes.get(d);if(m&&p){const f=l*6;o[f]=m.group.position.x,o[f+1]=.1,o[f+2]=m.group.position.z,o[f+3]=p.group.position.x,o[f+4]=.1,o[f+5]=p.group.position.z}}i.needsUpdate=!0,this.bossSubordinateLines.geometry.setDrawRange(0,this.cachedBossConnections.length*2),this.bossSubordinateLines.visible=!0}else this.bossSubordinateLines&&(this.bossSubordinateLines.visible=!1);for(const[i,o]of this.buildingMeshes){if(!e.buildings.get(i))continue;const c=n.has(i),d=o.group.getObjectByName("buildingBody");d&&d.material instanceof rt&&(c&&!this.selectedBuildingIds.has(i)?d.material.emissive.setHex(3351040):this.selectedBuildingIds.has(i)||d.material.emissive.setHex(0))}}updateBossLinePositions(){if(!this.bossSubordinateLines||this.cachedBossConnections.length===0)return;const e=this.bossSubordinateLines.geometry.attributes.position,t=e.array;for(let n=0;n<this.cachedBossConnections.length&&n<this.maxLineSegments;n++){const{bossId:a,subId:i}=this.cachedBossConnections[n],o=this.buildingMeshes.get(a),l=this.buildingMeshes.get(i);if(!o||!l)continue;const c=n*6;t[c]=o.group.position.x,t[c+1]=.1,t[c+2]=o.group.position.z,t[c+3]=l.group.position.x,t[c+4]=.1,t[c+5]=l.group.position.z}e.needsUpdate=!0}disposeGroup(e){e.traverse(t=>{if(t instanceof De&&(t.geometry.dispose(),Array.isArray(t.material)?t.material.forEach(n=>n.dispose()):t.material.dispose()),t instanceof Hn){const n=t.material;n.map&&n.map.dispose(),n.dispose()}})}dispose(){var e;for(const t of this.buildingMeshes.keys())this.removeBuilding(t);this.bossSubordinateLines&&(this.scene.remove(this.bossSubordinateLines),this.bossSubordinateLines.geometry.dispose(),(e=this.bossSubordinateMaterial)==null||e.dispose(),this.bossSubordinateLines=null,this.bossSubordinateMaterial=null),this.cachedBossConnections=[]}}const Qu=class Qu{constructor(e,t,n,a,i,o){W(this,"scene");W(this,"characterLoader");W(this,"characterFactory");W(this,"movementAnimator");W(this,"proceduralAnimator");W(this,"effectsManager");W(this,"agentMeshes",new Map);W(this,"pendingAgents",[]);W(this,"modelsReady",!1);W(this,"characterScale",.5);W(this,"brightness",1);W(this,"idleAnimation",Qn.SIT);W(this,"workingAnimation",Qn.WALK);W(this,"previousAgentStatuses",new Map);W(this,"modelStyle",{saturation:1,roughness:-1,metalness:-1,emissiveBoost:0,envMapIntensity:-1,wireframe:!1,colorMode:"normal"});W(this,"onAgentMeshesChanged",null);W(this,"onProceduralCacheInvalidated",null);W(this,"onToast",null);this.scene=e,this.characterLoader=t,this.characterFactory=n,this.movementAnimator=a,this.proceduralAnimator=i,this.effectsManager=o}setOnAgentMeshesChanged(e){this.onAgentMeshesChanged=e}setOnProceduralCacheInvalidated(e){this.onProceduralCacheInvalidated=e}setOnToast(e){this.onToast=e}getAgentMeshes(){return this.agentMeshes}isModelsReady(){return this.modelsReady}setCharacterScale(e){this.characterScale=e;for(const t of this.agentMeshes.values()){const n=t.group.getObjectByName("characterBody");if(n){const a=n.userData.customModelScale??1,i=t.group.userData.isBoss===!0,o=i?1.5:1;n.scale.setScalar(a*e*o);const l=t.group.getObjectByName("statusBar");if(l){const d=new bp().setFromObject(n).max.y,m=i?.2:.3,p=i?3:2.2;l.position.y=Math.min(Math.max(d,1)+m,p)}}}}setBrightness(e){this.brightness=e;for(const t of this.agentMeshes.values())this.applyStyleToMesh(t.group)}setModelStyle(e){Object.assign(this.modelStyle,e);for(const t of this.agentMeshes.values())this.applyStyleToMesh(t.group)}getModelStyle(){return{...this.modelStyle}}injectColorShader(e){const t=this.modelStyle.saturation,n=Qu.COLOR_MODE_INDEX[this.modelStyle.colorMode]??0;if(e.userData.hasColorShader)e.userData.shader&&(e.userData.shader.uniforms.uSaturation.value=t,e.userData.shader.uniforms.uColorMode.value=n);else{e.userData.hasColorShader=!0;const a=this;e.onBeforeCompile=i=>{i.uniforms.uSaturation={value:a.modelStyle.saturation},i.uniforms.uColorMode={value:Qu.COLOR_MODE_INDEX[a.modelStyle.colorMode]??0},i.fragmentShader=i.fragmentShader.replace("#include <common>",`#include <common>
@@ -145,7 +145,7 @@ Error generating stack: `+v.message+`
145
145
  float h = normalize(vWorldPosition + offset).y;
146
146
  gl_FragColor = vec4(mix(bottomColor, topColor, max(pow(max(h, 0.0), exponent), 0.0)), 1.0);
147
147
  }
148
- `,side:mA});a.add(new De(i,o)),a.add(new ax(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,f=typeof c.userData.aspectRatio=="number"?c.userData.aspectRatio:2560/4096;c.scale.set(p*o,p*f*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 m=a.group.getObjectByName("combinedUI");if(m){const p=typeof m.userData.baseIndicatorScale=="number"?m.userData.baseIndicatorScale:l?3:2.4,f=typeof m.userData.aspectRatio=="number"?m.userData.aspectRatio:1024/2048;m.scale.set(p*o,p*f*o,1)}if(!c&&!m){const p=a.group.getObjectByName("nameLabel");if(p){const y=.3*o;p.scale.set(y*(p.userData.aspectRatio||2),y,1)}const f=a.group.getObjectByName("manaBar");f&&f.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 yt(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:Kl.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 Mp="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 om(){return typeof window<"u"?window.__tidePersistedScene??null:null}function iM(){return typeof window<"u"?window.__tidePersistedCanvas??null:null}function fB(){return typeof window<"u"?window.__tideWsConnected??!1:!1}function sd(s){typeof window<"u"&&(window.__tidePersistedScene=s)}function Tp(s){typeof window<"u"&&(window.__tidePersistedCanvas=s)}function rM(s){typeof window<"u"&&(window.__tideWsConnected=s)}function gB(s){typeof window<"u"&&(window.__tideIsPageUnloading=s)}function bB(){sessionStorage.setItem(Mp,"true")}function $h(s){gB(!0),sessionStorage.removeItem(Mp),WA(),cL(),window.__tideScene&&(window.__tideScene=null);const e=om();e?(console.log("[App] Calling persistedScene.dispose()"),e.dispose(),sd(null)):console.log("[App] No persistedScene to dispose"),Tp(null),rM(!1);const t=document.getElementById("battlefield");t&&t.remove();const n=document.getElementById("app");n&&(n.innerHTML="")}function yB(){var a,i;if(window.__tideAppInitialized)return;if(window.__tideAppInitialized=!0,sessionStorage.getItem(Mp)==="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=om();if(e){console.log("[App] Cleaning up stale persistedScene");try{e.dispose()}catch{}sd(null)}const t=document.getElementById("battlefield"),n=iM();t&&t!==n&&t.remove(),sessionStorage.removeItem(Mp)}function xB(){typeof window>"u"||(yB(),window.addEventListener("pageshow",s=>{s.persisted&&(console.log("[App] Page restored from bfcache - cleaning up"),$h(),window.location.reload())}),window.onunload=()=>$h(),window.onbeforeunload=s=>{$h()},window.addEventListener("pagehide",s=>{$h(`pagehide (persisted=${s.persisted})`)}))}xB();const Cj={showTrees:!0,showBushes:!0,showHouse:!0,showLamps:!0,showGrass:!0,showClouds:!0,fogDensity:1,floorStyle:"metal",brightness:1,skyColor:null},Nj={saturation:2,roughness:.5,metalness:-1,emissiveBoost:0,envMapIntensity:1,wireframe:!1,colorMode:"normal"},Aj={idleAnimation:"sit",workingAnimation:"sprint"},vB=0;function oM(){const s={characterScale:2,indicatorScale:1,gridVisible:!1,timeMode:"day",terrain:Cj,modelStyle:Nj,animations:Aj,fpsLimit:vB},e=Ya(pt.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:{...Cj,...e.terrain},modelStyle:{...Nj,...e.modelStyle},animations:{...Aj,...e.animations},fpsLimit:e.fpsLimit??s.fpsLimit}:s}function wB(s){yi(pt.CONFIG,s)}typeof window<"u"&&!window.__tideHmrRefreshListeners&&(window.__tideHmrRefreshListeners=new Set);function lM(){console.log("[Tide HMR] Manual scene refresh triggered");const s=om();if(s){try{s.dispose()}catch(t){console.warn("[Tide HMR] Error disposing scene:",t)}sd(null)}Tp(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=lM);function kB({canvasRef:s,selectionBoxRef:e,showToast:t,showAgentNotification:n,toolboxModal:a,contextMenu:i,setHoveredAgentPopup:o,setBuildingPopup:l,getBuildingPopup:c,openBuildingModal:d,openPM2LogsModal:m,openBossLogsModal:p,openDatabasePanel:f}){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=om(),C=iM()===s.current;function A(){var D,M,I,E,_,P,L,R;(D=b.current)==null||D.setOnToast(t),(M=b.current)==null||M.setOnBuildingClick((z,F)=>{H.selectBuilding(z);const $=H.getState().buildings.get(z);($==null?void 0:$.type)==="folder"&&$.folderPath?H.openFileExplorer($.folderPath):($==null?void 0:$.type)==="server"||($==null?void 0:$.type)==="boss"||($==null?void 0:$.type)==="database"?(y.current&&clearTimeout(y.current),y.current=setTimeout(()=>{l({buildingId:z,screenPos:F,fromClick:!0}),y.current=null},150)):d(z)}),(I=b.current)==null||I.setOnContextMenu((z,F,$)=>{i.open(z,F,$)}),(E=b.current)==null||E.setOnAgentHover(()=>{}),(_=b.current)==null||_.setOnBuildingHover((z,F)=>{const $=c();if(z&&F){const U=H.getState().buildings.get(z);((U==null?void 0:U.type)==="server"||(U==null?void 0:U.type)==="boss"||(U==null?void 0:U.type)==="database")&&!($!=null&&$.fromClick)&&l({buildingId:z,screenPos:F,fromClick:!1})}else $!=null&&$.fromClick||l(null)}),(P=b.current)==null||P.setOnGroundClick(()=>{l(null)}),(L=b.current)==null||L.setOnAreaDoubleClick(z=>{H.selectArea(z),a.open()}),(R=b.current)==null||R.setOnBuildingDoubleClick(z=>{var $;y.current&&(clearTimeout(y.current),y.current=null),l(null);const F=H.getState().buildings.get(z);(F==null?void 0:F.type)==="server"&&(($=F.pm2)!=null&&$.enabled)?m==null||m(z):(F==null?void 0:F.type)==="boss"?p==null||p(z):(F==null?void 0:F.type)==="database"?f==null||f(z):(F==null?void 0:F.type)==="folder"&&F.folderPath?H.openFileExplorer(F.folderPath):d(z)})}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()))),A()}else{const D=s.current,M=e.current,I=()=>{if(k){console.log("[Tide] Effect cleaned up before scene init, skipping");return}if(!D.isConnected||!M.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),bB();try{const E=new mB(D,M);b.current=E,sd(E),Tp(D);const _=oM();E.setCharacterScale(_.characterScale),E.setIndicatorScale(_.indicatorScale),E.setGridVisible(_.gridVisible),E.setTimeMode(_.timeMode),E.setTerrainConfig(_.terrain),E.setFloorStyle(_.terrain.floorStyle,!0),E.setAgentModelStyle(_.modelStyle),E.setIdleAnimation(_.animations.idleAnimation),E.setWorkingAnimation(_.animations.workingAnimation),E.setFpsLimit(_.fpsLimit),E.syncAreas(),E.syncBuildings(),E.loadCharacterModels().then(()=>{console.log("[Tide] Character models ready");const P=H.getState();P.customAgentClasses.size>0&&(console.log("[Tide] Applying custom classes from store:",P.customAgentClasses.size),E.setCustomAgentClasses(P.customAgentClasses)),P.agents.size>0&&(console.log("[Tide] Syncing agents from store:",P.agents.size),E.syncAgents(Array.from(P.agents.values()))),E.upgradeAgentModels()}).catch(P=>{console.warn("[Tide] Some models failed to load, using fallback:",P)}),A()}catch(E){console.error("[Tide] Failed to initialize 3D scene:",E)}};w.current=requestAnimationFrame(I)}return HA({onAgentCreated:D=>{var M,I;(M=b.current)==null||M.addAgent(D),(I=window.__spawnModalSuccess)==null||I.call(window)},onAgentUpdated:(D,M)=>{var I;(I=b.current)==null||I.updateAgent(D,M)},onAgentDeleted:D=>{var M;(M=b.current)==null||M.removeAgent(D)},onAgentsSync:D=>{var M;(M=b.current)==null||M.syncAgents(D)},onAreasSync:()=>{var M,I;(M=b.current)==null||M.syncAreas();const D=Array.from(H.getState().agents.values());(I=b.current)==null||I.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 M;(M=window.__spawnModalDirNotFound)==null||M.call(window,D)},onToolUse:(D,M,I)=>{var E;(E=b.current)==null||E.showToolBubble(D,M,I)},onDelegation:(D,M)=>{var I;(I=b.current)==null||I.showDelegationEffect(D,M)},onCustomClassesSync:D=>{var M,I;(M=b.current)==null||M.setCustomAgentClasses(D),(I=b.current)==null||I.upgradeAgentModels()},onBuildingUpdated:D=>{var M;(M=b.current)==null||M.updateBuilding(D)},onSubagentStarted:D=>{var M;(M=b.current)==null||M.addSubagentEffect(D.id,D.parentAgentId,D.name,D.subagentType)},onSubagentCompleted:D=>{var E;const M=H.getSubagent(D)||H.getSubagentByToolUseId(D),I=(M==null?void 0:M.id)||D;(E=b.current)==null||E.completeSubagentEffect(I),setTimeout(()=>{var _;(_=b.current)==null||_.removeSubagentEffect(I)},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"),uL(),b.current.dispose(),b.current=null,sd(null),Tp(null))}},[s.current,e.current]),b}function SB({showToast:s,showAgentNotification:e}){const t=x.useRef(!1);x.useEffect(()=>{if(t.current||fB())return;t.current=!0,HA({onToast:s,onReconnect:()=>{H.triggerReconnect()},onAgentNotification:i=>{e(i)}}),nd(),rM(!0),tL();let n;sL(i=>{i.type==="agent_notification"&&typeof i.agentId=="string"&&BA(i.agentId)}).then(i=>{n=i});const a=()=>{console.log("[Tide] App resumed from background, reconnecting..."),setTimeout(()=>nd(),100)};return window.addEventListener("tideAppResume",a),()=>{window.removeEventListener("tideAppResume",a),n==null||n()}},[s,e])}function jB(s){x.useEffect(()=>{let e="",t="",n=new Map;const a=i=>{var c;let o=!1;const l=new Map;for(const[d,m]of i){const f=`${m.position.x.toFixed(2)},${m.position.z.toFixed(2)},${m.status},${m.class},${m.isBoss},${((c=m.subordinateIds)==null?void 0:c.length)??0}`.split("").reduce((b,y)=>(b<<5)-b+y.charCodeAt(0),0);l.set(d,f),n.get(d)!==f&&(o=!0)}return l.size!==n.size&&(o=!0),{newVersion:l,changed:o}};return H.subscribe(()=>{var f;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:m,changed:p}=a(i.agents);(c||d||p)&&(e=o,t=l,n=m,(f=s.current)==null||f.refreshSelectionVisuals())})},[s])}function CB(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,m]of i){let p=d.charCodeAt(0);p+=(m.width??0)+(m.height??0)+(m.radius??0),p+=Math.floor(m.center.x*100)+Math.floor(m.center.z*100),p+=(m.zIndex??0)*1e3;for(let f=0;f<m.name.length;f++)p+=m.name.charCodeAt(f);for(let f=0;f<m.color.length;f++)p+=m.color.charCodeAt(f);if(m.directoryGitCounts)for(const f of m.directoryGitCounts)p+=(f+1)*7;if(m.logo){p+=Math.floor((m.logo.opacity??.8)*1e3),p+=Math.floor(m.logo.width*100)+Math.floor(m.logo.height*100);for(let f=0;f<m.logo.position.length;f++)p+=m.logo.position.charCodeAt(f);if(m.logo.filename)for(let f=0;f<m.logo.filename.length;f++)p+=m.logo.filename.charCodeAt(f)}o^=p|0}o!==t&&(t=o,(c=s.current)==null||c.syncAreas())})},[s])}function NB(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,m]of i){o^=m.position.x*1e3+m.position.z|0,o^=(m.scale||1)*1e4|0;const p=`${m.style||""}${m.name}${m.status}${m.gitChangesCount||0}`;for(let f=0;f<p.length;f++)o=(o<<5)-o+p.charCodeAt(f)|0}o!==t&&(t=o,(c=s.current)==null||c.syncBuildings())})},[s])}function AB(s,e){x.useEffect(()=>{var t;(t=s.current)==null||t.highlightArea(e)},[s,e])}function MB(s,e){x.useEffect(()=>{var t;(t=s.current)==null||t.setPowerSaving(e)},[s,e])}function TB({sceneRef:s,spawnModal:e,commanderModal:t,explorerModal:n,spotlightModal:a,deleteConfirmModal:i,onRequestBuildingDelete:o,onOpenDatabasePanel:l,onCloseDatabasePanel:c,databasePanelOpen:d}){x.useEffect(()=>{const m=p=>{var P,L,R,z;const f=H.getShortcuts(),b=p.target,y=b.tagName==="INPUT"||b.tagName==="TEXTAREA",w=f.find(F=>F.id==="deselect-all");if(vt(p,w)){if(cy()){p.preventDefault();return}const F=H.getState();if(F.activeTool==="rectangle"||F.activeTool==="circle"){(P=s.current)==null||P.setDrawingTool(null),typeof window<"u"&&window.__tideScene2D_setDrawingTool&&window.__tideScene2D_setDrawingTool(null);return}e.isOpen?e.close():F.terminalOpen?(H.setTerminalOpen(!1),document.activeElement instanceof HTMLElement&&document.activeElement.blur()):(H.deselectAll(),(L=s.current)==null||L.refreshSelectionVisuals())}for(let F=1;F<=9;F++){const $=f.find(U=>U.id===`select-agent-${F}`);if(vt(p,$)){p.preventDefault();const U=H.getState(),G=F-1,K=Array.from(U.agents.keys());G<K.length&&(H.selectAgent(K[G]),(R=s.current)==null||R.refreshSelectionVisuals());return}}const k=f.find(F=>F.id==="spawn-agent");if(vt(p,k)){p.preventDefault(),e.open();return}const S=f.find(F=>F.id==="toggle-commander-tab");if(vt(p,S)&&!y){p.preventDefault(),t.toggle();return}const j=f.find(F=>F.id==="toggle-commander");if(vt(p,j)){p.preventDefault(),t.toggle();return}const C=f.find(F=>F.id==="toggle-file-explorer");if(vt(p,C)){p.preventDefault();const F=H.getState();if(n.isOpen||F.explorerFolderPath!==null||F.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(F.areas.has(U.areaId))n.open(U.areaId);else{const G=Array.from(F.areas.values()).filter(K=>K.directories&&K.directories.length>0);G.length>0&&n.open(G[0].id)}else{const G=Array.from(F.areas.values()).filter(K=>K.directories&&K.directories.length>0);G.length>0&&n.open(G[0].id)}}return}if(p.altKey&&!p.ctrlKey&&!p.shiftKey&&!p.metaKey&&p.code==="KeyD"){if(p.preventDefault(),p.stopPropagation(),d){c();return}const F=localStorage.getItem("tide-commander-last-database-building"),$=H.getState();if(F){const U=$.buildings.get(F);if((U==null?void 0:U.type)==="database"){l(F);return}}for(const[U,G]of $.buildings)if(G.type==="database"){l(U);return}return}const A=f.find(F=>F.id==="toggle-spotlight");if(vt(p,A)||p.altKey&&!p.ctrlKey&&!p.metaKey&&p.code==="KeyP"){console.log("[useKeyboardShortcuts] Spotlight shortcut matched!",{spotlightShortcut:A,altKey:p.altKey,code:p.code}),p.preventDefault(),a.toggle();return}const D=f.find(F=>F.id==="toggle-2d-view");if(vt(p,D)){p.preventDefault();const F=H.getState().viewMode,$=F==="3d"?"2d":F==="2d"?"dashboard":"3d";H.setViewMode($);return}const M=f.find(F=>F.id==="next-working-agent"),I=f.find(F=>F.id==="prev-working-agent");if((vt(p,M)||vt(p,I))&&!y){const F=H.getState();if(F.terminalOpen)return;const $=Array.from(F.agents.values());let U=$.filter(B=>F.agentsWithUnseenOutput.has(B.id));if(U.length===0&&(U=$.filter(B=>B.status==="working")),U.length===0)return;p.preventDefault();const G=F.selectedAgentIds.size===1?Array.from(F.selectedAgentIds)[0]:null,K=G?U.findIndex(B=>B.id===G):-1;let Z;vt(p,M)?Z=K===-1?0:(K+1)%U.length:Z=K===-1?U.length-1:(K-1+U.length)%U.length,H.selectAgent(U[Z].id),(z=s.current)==null||z.refreshSelectionVisuals();return}const E=f.find(F=>F.id==="delete-selected"),_=f.find(F=>F.id==="delete-selected-backspace");if((vt(p,E)||vt(p,_))&&!y){const F=H.getState();if(F.selectedAgentIds.size>0){p.preventDefault(),i.open();return}if(F.selectedBuildingIds.size>0){p.preventDefault(),o();return}return}};return document.addEventListener("keydown",m,!0),()=>document.removeEventListener("keydown",m,!0)},[s,e,t,n,a,i,o,l,c,d])}function EB(){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",cy()||(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),cy()||(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 sb="agent-order-change";function cM(s){const e=x.useMemo(()=>new Set(s.map(c=>c.id)),[s]),[t,n]=x.useState(()=>Ya(pt.AGENT_ORDER,[]));x.useEffect(()=>{const c=d=>{n(d.detail)};return window.addEventListener(sb,c),()=>{window.removeEventListener(sb,c)}},[]);const a=x.useMemo(()=>{const c=t.filter(f=>e.has(f)),d=s.filter(f=>!c.includes(f.id)).map(f=>f.id),m=[...c,...d],p=new Map(s.map(f=>[f.id,f]));return m.map(f=>p.get(f)).filter(f=>f!==void 0)},[s,t,e]),i=x.useCallback(c=>{n(c),yi(pt.AGENT_ORDER,c),window.dispatchEvent(new CustomEvent(sb,{detail:c}))},[]),o=x.useCallback((c,d)=>{const m=a.map(f=>f.id),[p]=m.splice(c,1);m.splice(d,0,p),i(m)},[a,i]),l=x.useCallback(()=>{n([]),yi(pt.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}}const gx="deivid11/tide-commander",_B=`https://api.github.com/repos/${gx}/releases/latest`,DB=`https://api.github.com/repos/${gx}/releases?per_page=3`,PB=3600*1e3,Mj="app_update_dismissed_version",Tj="0.71.4";function RB(){var m;const[s,e]=x.useState({isChecking:!1,updateAvailable:!1,updateInfo:null,recentReleases:[],error:null,currentVersion:Tj}),t=((m=ba==null?void 0:ba.getPlatform)==null?void 0:m.call(ba))==="android"||!1,n=p=>p.replace(/^v/,"").split(".").map(b=>parseInt(b,10)||0),a=(p,f)=>{const b=n(p),y=n(f),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(ba&&HS&&((b=ba.isNativePlatform)==null?void 0:b.call(ba))===!0){const y=await HS.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(f=>({...f,isChecking:!0,error:null}));try{const[f,b]=await Promise.all([i(_B),i(DB)]);if(f.status!==200)throw new Error(`GitHub API error: ${f.status}`);const y=f.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(Mj);if(!p&&S===w)return e(D=>({...D,isChecking:!1,updateAvailable:!1,recentReleases:k})),null;if(!(a(w,Tj)>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"),A={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:A,recentReleases:k})),A}catch(f){const b=f instanceof Error?f.message:"Failed to check for updates";return e(y=>({...y,isChecking:!1,error:b})),null}},[]),l=x.useCallback(async()=>{var p,f,b;if(!((p=s.updateInfo)!=null&&p.apkUrl)){(f=s.updateInfo)!=null&&f.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(Mj,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/${gx}/releases`,"_blank")},[s.updateInfo]);return x.useEffect(()=>{if(!t)return;const p=setTimeout(()=>{o()},5e3),f=setInterval(()=>{o()},PB);return()=>{clearTimeout(p),clearInterval(f)}},[t,o]),{...s,isAndroid:t,checkForUpdate:o,downloadAndInstall:l,dismissUpdate:c,openReleasePage:d}}function Ms(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 LB=3e4;function OB(){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 m=d.folderPath||d.cwd;m&&(a.has(m)||a.set(m,[]),a.get(m).push(c))}for(const[c,d]of a)try{const m=await mt(st(`/api/files/git-status?path=${encodeURIComponent(c)}`));if(!m.ok)continue;const f=((o=(await m.json()).files)==null?void 0:o.length)||0;n.set(c,f);for(const b of d){const y=H.getState().buildings.get(b);y&&y.gitChangesCount!==f&&H.updateBuildingLocal(b,{gitChangesCount:f})}}catch{}const i=new Map;for(const[c,d]of t.areas)d.archived||!d.directories||d.directories.forEach((m,p)=>{m&&(i.has(m)||i.set(m,[]),i.get(m).push({areaId:c,dirIndex:p}))});if(i.size!==0)for(const[c,d]of i)try{let m;if(n.has(c))m=n.get(c);else{const f=await mt(st(`/api/files/git-status?path=${encodeURIComponent(c)}`));if(!f.ok)continue;m=((l=(await f.json()).files)==null?void 0:l.length)||0,n.set(c,m)}const p=new Map;for(const f of d)p.has(f.areaId)||p.set(f.areaId,[]),p.get(f.areaId).push({dirIndex:f.dirIndex,count:m});for(const[f,b]of p){const y=H.getState().areas.get(f);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(f,{directoryGitCounts:w})}}catch{}};return e(),s.current=setInterval(e,LB),()=>{s.current&&(clearInterval(s.current),s.current=null)}},[])}const Ej={historyLimit:500,hideCost:!0,showFPS:!1,powerSaving:!1,customAgentNames:[],experimental2DView:!1,experimentalVoiceAssistant:!1,experimentalTTS:!1,experimentalEchoPrompt:!1,externalEditorCommand:""};function IB(s,e,t,n,a){return{setAgents(i){const o=new Map;for(const c of i)o.set(c.id,c),(c.class==="boss"||c.isBoss)&&console.log("[Store.setAgents] Boss agent:",c.name,"subordinateIds:",c.subordinateIds);const l=i.find(c=>c.status==="working");e(c=>{c.agents=o,l&&c.selectedAgentIds.size===0&&(c.selectedAgentIds.add(l.id),c.terminalOpen=!0)}),t()},addAgent(i){e(o=>{const l=new Map(o.agents);l.set(i.id,i),o.agents=l}),t()},updateAgent(i){var m;const l=s().agents.get(i.id),c=(l==null?void 0:l.status)!==i.status;c&&console.log(`[Store] Agent ${i.name} status update: ${l==null?void 0:l.status} → ${i.status}`);let d=!1;e(p=>{const f=new Map(p.agents);f.set(i.id,i),p.agents=f,c&&(l==null?void 0:l.status)==="working"&&i.status==="idle"&&(p.terminalOpen&&p.selectedAgentIds.has(i.id)||(p.agentsWithUnseenOutput=new Set(p.agentsWithUnseenOutput),p.agentsWithUnseenOutput.add(i.id),console.log(`[Store] Agent ${i.name} completed work - marked as unseen`),d=!0))}),d&&a&&a(),t(),c&&console.log(`[Store] Agent ${i.name} status now in store: ${(m=s().agents.get(i.id))==null?void 0:m.status}`)},updateAgentContextStats(i,o){const c=s().agents.get(i);c&&(e(d=>{const m=new Map(d.agents);m.set(i,{...c,contextStats:o,contextUsed:o.totalTokens,contextLimit:o.contextWindow}),d.agents=m}),t())},updateAgentContext(i,o,l){const d=s().agents.get(i);if(d){const m=Math.max(1,l||2e5),p=Math.max(0,Math.min(100,Number((o/m*100).toFixed(1))));e(f=>{const b=new Map(f.agents),y=d.contextStats?{...d.contextStats,totalTokens:o,contextWindow:m,usedPercent:p,lastUpdated:Date.now()}:void 0;b.set(i,{...d,contextUsed:o,contextLimit:m,contextStats:y}),f.agents=b}),t()}},removeAgent(i){const o=s().agentsWithUnseenOutput.has(i);e(l=>{const c=new Map(l.agents);c.delete(i),l.agents=c,l.selectedAgentIds.delete(i),l.agentOutputs.delete(i),l.agentsWithUnseenOutput.has(i)&&(l.agentsWithUnseenOutput=new Set(l.agentsWithUnseenOutput),l.agentsWithUnseenOutput.delete(i))}),o&&a&&a(),t()},selectAgent(i){let o=!1;e(l=>{l.selectedAgentIds.clear(),i&&(l.selectedAgentIds.add(i),l.lastSelectedAgentId=i,l.agentsWithUnseenOutput.has(i)&&(l.agentsWithUnseenOutput=new Set(l.agentsWithUnseenOutput),l.agentsWithUnseenOutput.delete(i),console.log(`[Store] Cleared unseen badge for selected agent ${i}`),o=!0)),l.currentSnapshot=null}),o&&a&&a(),t()},addToSelection(i){let o=!1;e(l=>{l.selectedAgentIds.has(i)?l.selectedAgentIds.delete(i):(l.selectedAgentIds.add(i),l.agentsWithUnseenOutput.has(i)&&(l.agentsWithUnseenOutput=new Set(l.agentsWithUnseenOutput),l.agentsWithUnseenOutput.delete(i),console.log(`[Store] Cleared unseen badge for multi-selected agent ${i}`),o=!0))}),o&&a&&a(),t()},selectMultiple(i){e(o=>{o.selectedAgentIds.clear();for(const l of i)o.selectedAgentIds.add(l)}),t()},deselectAll(){e(i=>{i.selectedAgentIds.clear()}),t()},spawnAgent(i,o,l,c,d,m,p,f,b,y,w,k,S){console.log("[Store] spawnAgent called with:",{name:i,agentClass:o,cwd:l,position:c,sessionId:d,useChrome:m,permissionMode:p,initialSkillIds:f,provider:b,codexConfig:y,codexModel:w,model:k,customInstructions:S?`${S.length} chars`:void 0});const j=c?{x:c.x,y:0,z:c.z}:void 0,C={type:"spawn_agent",payload:{name:i,class:o,cwd:l,position:j,sessionId:d,useChrome:m,permissionMode:p,initialSkillIds:f,provider:b,codexConfig:y,codexModel:w,model:k,customInstructions:S}},A=n();if(!A){console.error("[Store] sendMessage is not defined! WebSocket may not be connected");return}A(C),console.log("[Store] Message sent to WebSocket")},createDirectoryAndSpawn(i,o,l){var c;(c=n())==null||c({type:"create_directory",payload:{path:i,name:o,class:l}})},sendCommand(i,o){var l;e(c=>{c.lastPrompts.set(i,{text:o,timestamp:Date.now()})}),t(),(l=n())==null||l({type:"send_command",payload:{agentId:i,command:o}})},refreshAgentContext(i){var o;(o=n())==null||o({type:"request_context_stats",payload:{agentId:i}})},moveAgentLocal(i,o){const c=s().agents.get(i);c&&(e(d=>{const m={...c,position:o},p=new Map(d.agents);p.set(i,m),d.agents=p}),t())},moveAgent(i,o){var d;const c=s().agents.get(i);c&&(e(m=>{const p={...c,position:o},f=new Map(m.agents);f.set(i,p),m.agents=f}),t()),(d=n())==null||d({type:"move_agent",payload:{agentId:i,position:o}})},killAgent(i){var o;(o=n())==null||o({type:"kill_agent",payload:{agentId:i}})},stopAgent(i){var o;(o=n())==null||o({type:"stop_agent",payload:{agentId:i}})},clearContext(i){var o;(o=n())==null||o({type:"clear_context",payload:{agentId:i}}),e(l=>{const c=new Map(l.agentOutputs);c.delete(i),l.agentOutputs=c}),t()},collapseContext(i){var o;(o=n())==null||o({type:"collapse_context",payload:{agentId:i}})},removeAgentFromServer(i){var o;(o=n())==null||o({type:"remove_agent",payload:{agentId:i}})},renameAgent(i,o){var d;const c=s().agents.get(i);c&&(e(m=>{const p={...c,name:o},f=new Map(m.agents);f.set(i,p),m.agents=f}),t()),(d=n())==null||d({type:"rename_agent",payload:{agentId:i,name:o}})},updateAgentProperties(i,o){var d;const c=s().agents.get(i);c&&(e(m=>{const p={...c};o.class!==void 0&&(p.class=o.class),o.permissionMode!==void 0&&(p.permissionMode=o.permissionMode),o.model!==void 0&&(p.model=o.model),o.provider!==void 0&&(p.provider=o.provider),o.codexConfig!==void 0&&(p.codexConfig=o.codexConfig),o.codexModel!==void 0&&(p.codexModel=o.codexModel),o.useChrome!==void 0&&(p.useChrome=o.useChrome),o.cwd!==void 0&&(p.cwd=o.cwd);const f=new Map(m.agents);f.set(i,p),m.agents=f}),t()),(d=n())==null||d({type:"update_agent_properties",payload:{agentId:i,updates:o}})},getTotalTokens(){let i=0;for(const o of s().agents.values())i+=o.tokensUsed;return i},getSelectedAgents(){const i=s(),o=[];for(const l of i.selectedAgentIds){const c=i.agents.get(l);c&&o.push(c)}return o},addActivity(i){e(o=>{o.activities.unshift(i),o.activities.length>100&&o.activities.pop()}),t()},addToolExecution(i,o,l){const d=s().agents.get(i);e(m=>{m.toolExecutions.unshift({agentId:i,agentName:(d==null?void 0:d.name)||"Unknown",toolName:o,toolInput:l,timestamp:Date.now()}),m.toolExecutions.length>200&&m.toolExecutions.pop()}),t()},addFileChange(i,o,l){const d=s().agents.get(i);e(m=>{m.fileChanges.unshift({agentId:i,agentName:(d==null?void 0:d.name)||"Unknown",action:o,filePath:l,timestamp:Date.now()}),m.fileChanges.length>200&&m.fileChanges.pop()}),t()},async loadToolHistory(){try{const o=await(await mt(st("/api/agents/tool-history?limit=100"))).json();e(l=>{o.toolExecutions&&(l.toolExecutions=o.toolExecutions),o.fileChanges&&(l.fileChanges=o.fileChanges)}),t()}catch(i){console.error("[Store] Failed to load tool history:",i)}}}}function BB(s,e,t,n){return{addOutput(a,i){const o=n();e(l=>{const c=l.agentOutputs.get(a)||[];if(i.uuid&&c.some(f=>f.uuid===i.uuid))return;let d=[...c,i];d.length>200&&(d=d.slice(-200)),td.info(`Store: ${c.length} -> ${d.length}`,{agentId:a,text:i.text.slice(0,60),isStreaming:i.isStreaming,listeners:o},"store:addOutput");const m=new Map(l.agentOutputs);m.set(a,d),l.agentOutputs=m}),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 FB(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(m=>m.reportId===a.id)){const m=[d,...c];m.length>50&&m.pop(),o.set(l.agentId,m)}}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 zB(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 m of d.areas.values()){const p=m.assignedAgentIds.indexOf(i);p!==-1&&m.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(m=>{m.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(m=>{m.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)),m=d+1,p=l.zIndex??0,f=c.filter(b=>(b.zIndex??0)===d);p===d&&f.length===1||(e(b=>{b.areas.get(i).zIndex=m}),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(f=>f.zIndex??0)),m=l.zIndex??0,p=c.filter(f=>(f.zIndex??0)===d);m===d&&p.length===1||(e(f=>{for(const b of f.areas.values())b.id!==i&&(b.zIndex=(b.zIndex??0)+1);f.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 m=d.areas.get(i);m.archived=!0,m.archivedAt=Date.now(),m.originalCenter={...m.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,m=o||c.originalCenter||c.center,p=m.x-d.x,f=m.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=m,S.zIndex=w,p!==0||f!==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+f})}}),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 $B(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 m of o.selectedBuildingIds){const p=o.buildings.get(m);((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:m,command:"delete"}}))}e(m=>{const p=new Map(m.buildings);for(const f of m.selectedBuildingIds)p.delete(f);m.buildings=p,m.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(m=>{const p=new Map(m.buildings);p.set(o,{...d,...l}),m.buildings=p}),a(),t())},updateBuildingLocal(o,l){const d=s().buildings.get(o);d&&(e(m=>{const p=new Map(m.buildings);p.set(o,{...d,...l}),m.buildings=p}),t())},deleteBuilding(o){var d,m,p;const c=s().buildings.get(o);((d=c==null?void 0:c.pm2)!=null&&d.enabled||(m=c==null?void 0:c.docker)!=null&&m.enabled)&&((p=n())==null||p({type:"building_command",payload:{buildingId:o,command:"delete"}})),e(f=>{const b=new Map(f.buildings);b.delete(o),f.buildings=b,f.selectedBuildingIds.delete(o)}),a(),t()},moveBuilding(o,l){const d=s().buildings.get(o);d&&(e(m=>{const p=new Map(m.buildings);p.set(o,{...d,position:l}),m.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 m=[...c.buildingLogs.get(o)||[],l];m.length>500&&m.splice(0,m.length-500);const p=new Map(c.buildingLogs);p.set(o,m),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,m,p;const c=s().buildings.get(o);e(f=>{const b=new Map(f.streamingBuildingLogs);b.set(o,""),f.streamingBuildingLogs=b}),(d=c==null?void 0:c.docker)!=null&&d.enabled?(m=n())==null||m({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,m;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}}):(m=n())==null||m({type:"pm2_logs_stop",payload:{buildingId:o}})},appendStreamingLogChunk(o,l){e(c=>{const d=c.streamingBuildingLogs.get(o)||"",m=500*1024;let p=d+l;if(p.length>m){const b=p.indexOf(`
148
+ `,side:mA});a.add(new De(i,o)),a.add(new ax(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,f=typeof c.userData.aspectRatio=="number"?c.userData.aspectRatio:2560/4096;c.scale.set(p*o,p*f*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 m=a.group.getObjectByName("combinedUI");if(m){const p=typeof m.userData.baseIndicatorScale=="number"?m.userData.baseIndicatorScale:l?3:2.4,f=typeof m.userData.aspectRatio=="number"?m.userData.aspectRatio:1024/2048;m.scale.set(p*o,p*f*o,1)}if(!c&&!m){const p=a.group.getObjectByName("nameLabel");if(p){const y=.3*o;p.scale.set(y*(p.userData.aspectRatio||2),y,1)}const f=a.group.getObjectByName("manaBar");f&&f.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 yt(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:Kl.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 Mp="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 om(){return typeof window<"u"?window.__tidePersistedScene??null:null}function iM(){return typeof window<"u"?window.__tidePersistedCanvas??null:null}function fB(){return typeof window<"u"?window.__tideWsConnected??!1:!1}function sd(s){typeof window<"u"&&(window.__tidePersistedScene=s)}function Tp(s){typeof window<"u"&&(window.__tidePersistedCanvas=s)}function rM(s){typeof window<"u"&&(window.__tideWsConnected=s)}function gB(s){typeof window<"u"&&(window.__tideIsPageUnloading=s)}function bB(){sessionStorage.setItem(Mp,"true")}function $h(s){gB(!0),sessionStorage.removeItem(Mp),WA(),cL(),window.__tideScene&&(window.__tideScene=null);const e=om();e?(console.log("[App] Calling persistedScene.dispose()"),e.dispose(),sd(null)):console.log("[App] No persistedScene to dispose"),Tp(null),rM(!1);const t=document.getElementById("battlefield");t&&t.remove();const n=document.getElementById("app");n&&(n.innerHTML="")}function yB(){var a,i;if(window.__tideAppInitialized)return;if(window.__tideAppInitialized=!0,sessionStorage.getItem(Mp)==="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=om();if(e){console.log("[App] Cleaning up stale persistedScene");try{e.dispose()}catch{}sd(null)}const t=document.getElementById("battlefield"),n=iM();t&&t!==n&&t.remove(),sessionStorage.removeItem(Mp)}function xB(){typeof window>"u"||(yB(),window.addEventListener("pageshow",s=>{s.persisted&&(console.log("[App] Page restored from bfcache - cleaning up"),$h(),window.location.reload())}),window.onunload=()=>$h(),window.onbeforeunload=s=>{$h()},window.addEventListener("pagehide",s=>{$h(`pagehide (persisted=${s.persisted})`)}))}xB();const Cj={showTrees:!0,showBushes:!0,showHouse:!0,showLamps:!0,showGrass:!0,showClouds:!0,fogDensity:1,floorStyle:"metal",brightness:1,skyColor:null},Nj={saturation:2,roughness:.5,metalness:-1,emissiveBoost:0,envMapIntensity:1,wireframe:!1,colorMode:"normal"},Aj={idleAnimation:"sit",workingAnimation:"sprint"},vB=0;function oM(){const s={characterScale:2,indicatorScale:1,gridVisible:!1,timeMode:"day",terrain:Cj,modelStyle:Nj,animations:Aj,fpsLimit:vB},e=Ya(pt.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:{...Cj,...e.terrain},modelStyle:{...Nj,...e.modelStyle},animations:{...Aj,...e.animations},fpsLimit:e.fpsLimit??s.fpsLimit}:s}function wB(s){yi(pt.CONFIG,s)}typeof window<"u"&&!window.__tideHmrRefreshListeners&&(window.__tideHmrRefreshListeners=new Set);function lM(){console.log("[Tide HMR] Manual scene refresh triggered");const s=om();if(s){try{s.dispose()}catch(t){console.warn("[Tide HMR] Error disposing scene:",t)}sd(null)}Tp(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=lM);function kB({canvasRef:s,selectionBoxRef:e,showToast:t,showAgentNotification:n,toolboxModal:a,contextMenu:i,setHoveredAgentPopup:o,setBuildingPopup:l,getBuildingPopup:c,openBuildingModal:d,openPM2LogsModal:m,openBossLogsModal:p,openDatabasePanel:f}){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=om(),C=iM()===s.current;function A(){var D,M,I,E,_,P,L,R;(D=b.current)==null||D.setOnToast(t),(M=b.current)==null||M.setOnBuildingClick((z,F)=>{H.selectBuilding(z);const $=H.getState().buildings.get(z);($==null?void 0:$.type)==="folder"&&$.folderPath?H.openFileExplorer($.folderPath):($==null?void 0:$.type)==="server"||($==null?void 0:$.type)==="boss"||($==null?void 0:$.type)==="database"?(y.current&&clearTimeout(y.current),y.current=setTimeout(()=>{l({buildingId:z,screenPos:F,fromClick:!0}),y.current=null},150)):d(z)}),(I=b.current)==null||I.setOnContextMenu((z,F,$)=>{i.open(z,F,$)}),(E=b.current)==null||E.setOnAgentHover(()=>{}),(_=b.current)==null||_.setOnBuildingHover((z,F)=>{const $=c();if(z&&F){const U=H.getState().buildings.get(z);((U==null?void 0:U.type)==="server"||(U==null?void 0:U.type)==="boss"||(U==null?void 0:U.type)==="database")&&!($!=null&&$.fromClick)&&l({buildingId:z,screenPos:F,fromClick:!1})}else $!=null&&$.fromClick||l(null)}),(P=b.current)==null||P.setOnGroundClick(()=>{l(null)}),(L=b.current)==null||L.setOnAreaDoubleClick(z=>{H.selectArea(z),a.open()}),(R=b.current)==null||R.setOnBuildingDoubleClick(z=>{var $;y.current&&(clearTimeout(y.current),y.current=null),l(null);const F=H.getState().buildings.get(z);(F==null?void 0:F.type)==="server"&&(($=F.pm2)!=null&&$.enabled)?m==null||m(z):(F==null?void 0:F.type)==="boss"?p==null||p(z):(F==null?void 0:F.type)==="database"?f==null||f(z):(F==null?void 0:F.type)==="folder"&&F.folderPath?H.openFileExplorer(F.folderPath):d(z)})}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()))),A()}else{const D=s.current,M=e.current,I=()=>{if(k){console.log("[Tide] Effect cleaned up before scene init, skipping");return}if(!D.isConnected||!M.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),bB();try{const E=new mB(D,M);b.current=E,sd(E),Tp(D);const _=oM();E.setCharacterScale(_.characterScale),E.setIndicatorScale(_.indicatorScale),E.setGridVisible(_.gridVisible),E.setTimeMode(_.timeMode),E.setTerrainConfig(_.terrain),E.setFloorStyle(_.terrain.floorStyle,!0),E.setAgentModelStyle(_.modelStyle),E.setIdleAnimation(_.animations.idleAnimation),E.setWorkingAnimation(_.animations.workingAnimation),E.setFpsLimit(_.fpsLimit),E.syncAreas(),E.syncBuildings(),E.loadCharacterModels().then(()=>{console.log("[Tide] Character models ready");const P=H.getState();P.customAgentClasses.size>0&&(console.log("[Tide] Applying custom classes from store:",P.customAgentClasses.size),E.setCustomAgentClasses(P.customAgentClasses)),P.agents.size>0&&(console.log("[Tide] Syncing agents from store:",P.agents.size),E.syncAgents(Array.from(P.agents.values()))),E.upgradeAgentModels()}).catch(P=>{console.warn("[Tide] Some models failed to load, using fallback:",P)}),A()}catch(E){console.error("[Tide] Failed to initialize 3D scene:",E)}};w.current=requestAnimationFrame(I)}return HA({onAgentCreated:D=>{var M,I;(M=b.current)==null||M.addAgent(D),(I=window.__spawnModalSuccess)==null||I.call(window)},onAgentUpdated:(D,M)=>{var I;(I=b.current)==null||I.updateAgent(D,M)},onAgentDeleted:D=>{var M;(M=b.current)==null||M.removeAgent(D)},onAgentsSync:D=>{var M;(M=b.current)==null||M.syncAgents(D)},onAreasSync:()=>{var M,I;(M=b.current)==null||M.syncAreas();const D=Array.from(H.getState().agents.values());(I=b.current)==null||I.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 M;(M=window.__spawnModalDirNotFound)==null||M.call(window,D)},onToolUse:(D,M,I)=>{var E;(E=b.current)==null||E.showToolBubble(D,M,I)},onDelegation:(D,M)=>{var I;(I=b.current)==null||I.showDelegationEffect(D,M)},onCustomClassesSync:D=>{var M,I;(M=b.current)==null||M.setCustomAgentClasses(D),(I=b.current)==null||I.upgradeAgentModels()},onBuildingUpdated:D=>{var M;(M=b.current)==null||M.updateBuilding(D)},onSubagentStarted:D=>{var M;(M=b.current)==null||M.addSubagentEffect(D.id,D.parentAgentId,D.name,D.subagentType)},onSubagentCompleted:D=>{var E;const M=H.getSubagent(D)||H.getSubagentByToolUseId(D),I=(M==null?void 0:M.id)||D;(E=b.current)==null||E.completeSubagentEffect(I),setTimeout(()=>{var _;(_=b.current)==null||_.removeSubagentEffect(I)},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"),uL(),b.current.dispose(),b.current=null,sd(null),Tp(null))}},[s.current,e.current]),b}function SB({showToast:s,showAgentNotification:e}){const t=x.useRef(!1);x.useEffect(()=>{if(t.current||fB())return;t.current=!0,HA({onToast:s,onReconnect:()=>{H.triggerReconnect()},onAgentNotification:i=>{e(i)}}),nd(),rM(!0),tL();let n;sL(i=>{i.type==="agent_notification"&&typeof i.agentId=="string"&&BA(i.agentId)}).then(i=>{n=i});const a=()=>{console.log("[Tide] App resumed from background, reconnecting..."),setTimeout(()=>nd(),100)};return window.addEventListener("tideAppResume",a),()=>{window.removeEventListener("tideAppResume",a),n==null||n()}},[s,e])}function jB(s){x.useEffect(()=>{let e="",t="",n=new Map;const a=i=>{var c;let o=!1;const l=new Map;for(const[d,m]of i){const f=`${m.position.x.toFixed(2)},${m.position.z.toFixed(2)},${m.status},${m.class},${m.isBoss},${((c=m.subordinateIds)==null?void 0:c.length)??0}`.split("").reduce((b,y)=>(b<<5)-b+y.charCodeAt(0),0);l.set(d,f),n.get(d)!==f&&(o=!0)}return l.size!==n.size&&(o=!0),{newVersion:l,changed:o}};return H.subscribe(()=>{var f;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:m,changed:p}=a(i.agents);(c||d||p)&&(e=o,t=l,n=m,(f=s.current)==null||f.refreshSelectionVisuals())})},[s])}function CB(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,m]of i){let p=d.charCodeAt(0);p+=(m.width??0)+(m.height??0)+(m.radius??0),p+=Math.floor(m.center.x*100)+Math.floor(m.center.z*100),p+=(m.zIndex??0)*1e3;for(let f=0;f<m.name.length;f++)p+=m.name.charCodeAt(f);for(let f=0;f<m.color.length;f++)p+=m.color.charCodeAt(f);if(m.directoryGitCounts)for(const f of m.directoryGitCounts)p+=(f+1)*7;if(m.logo){p+=Math.floor((m.logo.opacity??.8)*1e3),p+=Math.floor(m.logo.width*100)+Math.floor(m.logo.height*100);for(let f=0;f<m.logo.position.length;f++)p+=m.logo.position.charCodeAt(f);if(m.logo.filename)for(let f=0;f<m.logo.filename.length;f++)p+=m.logo.filename.charCodeAt(f)}o^=p|0}o!==t&&(t=o,(c=s.current)==null||c.syncAreas())})},[s])}function NB(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,m]of i){o^=m.position.x*1e3+m.position.z|0,o^=(m.scale||1)*1e4|0;const p=`${m.style||""}${m.name}${m.status}${m.gitChangesCount||0}`;for(let f=0;f<p.length;f++)o=(o<<5)-o+p.charCodeAt(f)|0}o!==t&&(t=o,(c=s.current)==null||c.syncBuildings())})},[s])}function AB(s,e){x.useEffect(()=>{var t;(t=s.current)==null||t.highlightArea(e)},[s,e])}function MB(s,e){x.useEffect(()=>{var t;(t=s.current)==null||t.setPowerSaving(e)},[s,e])}function TB({sceneRef:s,spawnModal:e,commanderModal:t,explorerModal:n,spotlightModal:a,deleteConfirmModal:i,onRequestBuildingDelete:o,onOpenDatabasePanel:l,onCloseDatabasePanel:c,databasePanelOpen:d}){x.useEffect(()=>{const m=p=>{var P,L,R,z;const f=H.getShortcuts(),b=p.target,y=b.tagName==="INPUT"||b.tagName==="TEXTAREA",w=f.find(F=>F.id==="deselect-all");if(vt(p,w)){if(cy()){p.preventDefault();return}const F=H.getState();if(F.activeTool==="rectangle"||F.activeTool==="circle"){(P=s.current)==null||P.setDrawingTool(null),typeof window<"u"&&window.__tideScene2D_setDrawingTool&&window.__tideScene2D_setDrawingTool(null);return}e.isOpen?e.close():F.terminalOpen?(H.setTerminalOpen(!1),document.activeElement instanceof HTMLElement&&document.activeElement.blur()):(H.deselectAll(),(L=s.current)==null||L.refreshSelectionVisuals())}for(let F=1;F<=9;F++){const $=f.find(U=>U.id===`select-agent-${F}`);if(vt(p,$)){p.preventDefault();const U=H.getState(),G=F-1,K=Array.from(U.agents.keys());G<K.length&&(H.selectAgent(K[G]),(R=s.current)==null||R.refreshSelectionVisuals());return}}const k=f.find(F=>F.id==="spawn-agent");if(vt(p,k)){p.preventDefault(),e.open();return}const S=f.find(F=>F.id==="toggle-commander-tab");if(vt(p,S)&&!y){p.preventDefault(),t.toggle();return}const j=f.find(F=>F.id==="toggle-commander");if(vt(p,j)){p.preventDefault(),t.toggle();return}const C=f.find(F=>F.id==="toggle-file-explorer");if(vt(p,C)){p.preventDefault();const F=H.getState();if(n.isOpen||F.explorerFolderPath!==null||F.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(F.areas.has(U.areaId))n.open(U.areaId);else{const G=Array.from(F.areas.values()).filter(K=>K.directories&&K.directories.length>0);G.length>0&&n.open(G[0].id)}else{const G=Array.from(F.areas.values()).filter(K=>K.directories&&K.directories.length>0);G.length>0&&n.open(G[0].id)}}return}if(p.altKey&&!p.ctrlKey&&!p.shiftKey&&!p.metaKey&&p.code==="KeyD"){if(p.preventDefault(),p.stopPropagation(),d){c();return}const F=localStorage.getItem("tide-commander-last-database-building"),$=H.getState();if(F){const U=$.buildings.get(F);if((U==null?void 0:U.type)==="database"){l(F);return}}for(const[U,G]of $.buildings)if(G.type==="database"){l(U);return}return}const A=f.find(F=>F.id==="toggle-spotlight");if(vt(p,A)||p.altKey&&!p.ctrlKey&&!p.metaKey&&p.code==="KeyP"){console.log("[useKeyboardShortcuts] Spotlight shortcut matched!",{spotlightShortcut:A,altKey:p.altKey,code:p.code}),p.preventDefault(),a.toggle();return}const D=f.find(F=>F.id==="toggle-2d-view");if(vt(p,D)){p.preventDefault();const F=H.getState().viewMode,$=F==="3d"?"2d":F==="2d"?"dashboard":"3d";H.setViewMode($);return}const M=f.find(F=>F.id==="next-working-agent"),I=f.find(F=>F.id==="prev-working-agent");if((vt(p,M)||vt(p,I))&&!y){const F=H.getState();if(F.terminalOpen)return;const $=Array.from(F.agents.values());let U=$.filter(B=>F.agentsWithUnseenOutput.has(B.id));if(U.length===0&&(U=$.filter(B=>B.status==="working")),U.length===0)return;p.preventDefault();const G=F.selectedAgentIds.size===1?Array.from(F.selectedAgentIds)[0]:null,K=G?U.findIndex(B=>B.id===G):-1;let Z;vt(p,M)?Z=K===-1?0:(K+1)%U.length:Z=K===-1?U.length-1:(K-1+U.length)%U.length,H.selectAgent(U[Z].id),(z=s.current)==null||z.refreshSelectionVisuals();return}const E=f.find(F=>F.id==="delete-selected"),_=f.find(F=>F.id==="delete-selected-backspace");if((vt(p,E)||vt(p,_))&&!y){const F=H.getState();if(F.selectedAgentIds.size>0){p.preventDefault(),i.open();return}if(F.selectedBuildingIds.size>0){p.preventDefault(),o();return}return}};return document.addEventListener("keydown",m,!0),()=>document.removeEventListener("keydown",m,!0)},[s,e,t,n,a,i,o,l,c,d])}function EB(){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",cy()||(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),cy()||(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 sb="agent-order-change";function cM(s){const e=x.useMemo(()=>new Set(s.map(c=>c.id)),[s]),[t,n]=x.useState(()=>Ya(pt.AGENT_ORDER,[]));x.useEffect(()=>{const c=d=>{n(d.detail)};return window.addEventListener(sb,c),()=>{window.removeEventListener(sb,c)}},[]);const a=x.useMemo(()=>{const c=t.filter(f=>e.has(f)),d=s.filter(f=>!c.includes(f.id)).map(f=>f.id),m=[...c,...d],p=new Map(s.map(f=>[f.id,f]));return m.map(f=>p.get(f)).filter(f=>f!==void 0)},[s,t,e]),i=x.useCallback(c=>{n(c),yi(pt.AGENT_ORDER,c),window.dispatchEvent(new CustomEvent(sb,{detail:c}))},[]),o=x.useCallback((c,d)=>{const m=a.map(f=>f.id),[p]=m.splice(c,1);m.splice(d,0,p),i(m)},[a,i]),l=x.useCallback(()=>{n([]),yi(pt.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}}const gx="deivid11/tide-commander",_B=`https://api.github.com/repos/${gx}/releases/latest`,DB=`https://api.github.com/repos/${gx}/releases?per_page=3`,PB=3600*1e3,Mj="app_update_dismissed_version",Tj="0.71.5";function RB(){var m;const[s,e]=x.useState({isChecking:!1,updateAvailable:!1,updateInfo:null,recentReleases:[],error:null,currentVersion:Tj}),t=((m=ba==null?void 0:ba.getPlatform)==null?void 0:m.call(ba))==="android"||!1,n=p=>p.replace(/^v/,"").split(".").map(b=>parseInt(b,10)||0),a=(p,f)=>{const b=n(p),y=n(f),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(ba&&HS&&((b=ba.isNativePlatform)==null?void 0:b.call(ba))===!0){const y=await HS.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(f=>({...f,isChecking:!0,error:null}));try{const[f,b]=await Promise.all([i(_B),i(DB)]);if(f.status!==200)throw new Error(`GitHub API error: ${f.status}`);const y=f.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(Mj);if(!p&&S===w)return e(D=>({...D,isChecking:!1,updateAvailable:!1,recentReleases:k})),null;if(!(a(w,Tj)>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"),A={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:A,recentReleases:k})),A}catch(f){const b=f instanceof Error?f.message:"Failed to check for updates";return e(y=>({...y,isChecking:!1,error:b})),null}},[]),l=x.useCallback(async()=>{var p,f,b;if(!((p=s.updateInfo)!=null&&p.apkUrl)){(f=s.updateInfo)!=null&&f.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(Mj,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/${gx}/releases`,"_blank")},[s.updateInfo]);return x.useEffect(()=>{if(!t)return;const p=setTimeout(()=>{o()},5e3),f=setInterval(()=>{o()},PB);return()=>{clearTimeout(p),clearInterval(f)}},[t,o]),{...s,isAndroid:t,checkForUpdate:o,downloadAndInstall:l,dismissUpdate:c,openReleasePage:d}}function Ms(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 LB=3e4;function OB(){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 m=d.folderPath||d.cwd;m&&(a.has(m)||a.set(m,[]),a.get(m).push(c))}for(const[c,d]of a)try{const m=await mt(st(`/api/files/git-status?path=${encodeURIComponent(c)}`));if(!m.ok)continue;const f=((o=(await m.json()).files)==null?void 0:o.length)||0;n.set(c,f);for(const b of d){const y=H.getState().buildings.get(b);y&&y.gitChangesCount!==f&&H.updateBuildingLocal(b,{gitChangesCount:f})}}catch{}const i=new Map;for(const[c,d]of t.areas)d.archived||!d.directories||d.directories.forEach((m,p)=>{m&&(i.has(m)||i.set(m,[]),i.get(m).push({areaId:c,dirIndex:p}))});if(i.size!==0)for(const[c,d]of i)try{let m;if(n.has(c))m=n.get(c);else{const f=await mt(st(`/api/files/git-status?path=${encodeURIComponent(c)}`));if(!f.ok)continue;m=((l=(await f.json()).files)==null?void 0:l.length)||0,n.set(c,m)}const p=new Map;for(const f of d)p.has(f.areaId)||p.set(f.areaId,[]),p.get(f.areaId).push({dirIndex:f.dirIndex,count:m});for(const[f,b]of p){const y=H.getState().areas.get(f);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(f,{directoryGitCounts:w})}}catch{}};return e(),s.current=setInterval(e,LB),()=>{s.current&&(clearInterval(s.current),s.current=null)}},[])}const Ej={historyLimit:500,hideCost:!0,showFPS:!1,powerSaving:!1,customAgentNames:[],experimental2DView:!1,experimentalVoiceAssistant:!1,experimentalTTS:!1,experimentalEchoPrompt:!1,externalEditorCommand:""};function IB(s,e,t,n,a){return{setAgents(i){const o=new Map;for(const c of i)o.set(c.id,c),(c.class==="boss"||c.isBoss)&&console.log("[Store.setAgents] Boss agent:",c.name,"subordinateIds:",c.subordinateIds);const l=i.find(c=>c.status==="working");e(c=>{c.agents=o,l&&c.selectedAgentIds.size===0&&(c.selectedAgentIds.add(l.id),c.terminalOpen=!0)}),t()},addAgent(i){e(o=>{const l=new Map(o.agents);l.set(i.id,i),o.agents=l}),t()},updateAgent(i){var m;const l=s().agents.get(i.id),c=(l==null?void 0:l.status)!==i.status;c&&console.log(`[Store] Agent ${i.name} status update: ${l==null?void 0:l.status} → ${i.status}`);let d=!1;e(p=>{const f=new Map(p.agents);f.set(i.id,i),p.agents=f,c&&(l==null?void 0:l.status)==="working"&&i.status==="idle"&&(p.terminalOpen&&p.selectedAgentIds.has(i.id)||(p.agentsWithUnseenOutput=new Set(p.agentsWithUnseenOutput),p.agentsWithUnseenOutput.add(i.id),console.log(`[Store] Agent ${i.name} completed work - marked as unseen`),d=!0))}),d&&a&&a(),t(),c&&console.log(`[Store] Agent ${i.name} status now in store: ${(m=s().agents.get(i.id))==null?void 0:m.status}`)},updateAgentContextStats(i,o){const c=s().agents.get(i);c&&(e(d=>{const m=new Map(d.agents);m.set(i,{...c,contextStats:o,contextUsed:o.totalTokens,contextLimit:o.contextWindow}),d.agents=m}),t())},updateAgentContext(i,o,l){const d=s().agents.get(i);if(d){const m=Math.max(1,l||2e5),p=Math.max(0,Math.min(100,Number((o/m*100).toFixed(1))));e(f=>{const b=new Map(f.agents),y=d.contextStats?{...d.contextStats,totalTokens:o,contextWindow:m,usedPercent:p,lastUpdated:Date.now()}:void 0;b.set(i,{...d,contextUsed:o,contextLimit:m,contextStats:y}),f.agents=b}),t()}},removeAgent(i){const o=s().agentsWithUnseenOutput.has(i);e(l=>{const c=new Map(l.agents);c.delete(i),l.agents=c,l.selectedAgentIds.delete(i),l.agentOutputs.delete(i),l.agentsWithUnseenOutput.has(i)&&(l.agentsWithUnseenOutput=new Set(l.agentsWithUnseenOutput),l.agentsWithUnseenOutput.delete(i))}),o&&a&&a(),t()},selectAgent(i){let o=!1;e(l=>{l.selectedAgentIds.clear(),i&&(l.selectedAgentIds.add(i),l.lastSelectedAgentId=i,l.agentsWithUnseenOutput.has(i)&&(l.agentsWithUnseenOutput=new Set(l.agentsWithUnseenOutput),l.agentsWithUnseenOutput.delete(i),console.log(`[Store] Cleared unseen badge for selected agent ${i}`),o=!0)),l.currentSnapshot=null}),o&&a&&a(),t()},addToSelection(i){let o=!1;e(l=>{l.selectedAgentIds.has(i)?l.selectedAgentIds.delete(i):(l.selectedAgentIds.add(i),l.agentsWithUnseenOutput.has(i)&&(l.agentsWithUnseenOutput=new Set(l.agentsWithUnseenOutput),l.agentsWithUnseenOutput.delete(i),console.log(`[Store] Cleared unseen badge for multi-selected agent ${i}`),o=!0))}),o&&a&&a(),t()},selectMultiple(i){e(o=>{o.selectedAgentIds.clear();for(const l of i)o.selectedAgentIds.add(l)}),t()},deselectAll(){e(i=>{i.selectedAgentIds.clear()}),t()},spawnAgent(i,o,l,c,d,m,p,f,b,y,w,k,S){console.log("[Store] spawnAgent called with:",{name:i,agentClass:o,cwd:l,position:c,sessionId:d,useChrome:m,permissionMode:p,initialSkillIds:f,provider:b,codexConfig:y,codexModel:w,model:k,customInstructions:S?`${S.length} chars`:void 0});const j=c?{x:c.x,y:0,z:c.z}:void 0,C={type:"spawn_agent",payload:{name:i,class:o,cwd:l,position:j,sessionId:d,useChrome:m,permissionMode:p,initialSkillIds:f,provider:b,codexConfig:y,codexModel:w,model:k,customInstructions:S}},A=n();if(!A){console.error("[Store] sendMessage is not defined! WebSocket may not be connected");return}A(C),console.log("[Store] Message sent to WebSocket")},createDirectoryAndSpawn(i,o,l){var c;(c=n())==null||c({type:"create_directory",payload:{path:i,name:o,class:l}})},sendCommand(i,o){var l;e(c=>{c.lastPrompts.set(i,{text:o,timestamp:Date.now()})}),t(),(l=n())==null||l({type:"send_command",payload:{agentId:i,command:o}})},refreshAgentContext(i){var o;(o=n())==null||o({type:"request_context_stats",payload:{agentId:i}})},moveAgentLocal(i,o){const c=s().agents.get(i);c&&(e(d=>{const m={...c,position:o},p=new Map(d.agents);p.set(i,m),d.agents=p}),t())},moveAgent(i,o){var d;const c=s().agents.get(i);c&&(e(m=>{const p={...c,position:o},f=new Map(m.agents);f.set(i,p),m.agents=f}),t()),(d=n())==null||d({type:"move_agent",payload:{agentId:i,position:o}})},killAgent(i){var o;(o=n())==null||o({type:"kill_agent",payload:{agentId:i}})},stopAgent(i){var o;(o=n())==null||o({type:"stop_agent",payload:{agentId:i}})},clearContext(i){var o;(o=n())==null||o({type:"clear_context",payload:{agentId:i}}),e(l=>{const c=new Map(l.agentOutputs);c.delete(i),l.agentOutputs=c}),t()},collapseContext(i){var o;(o=n())==null||o({type:"collapse_context",payload:{agentId:i}})},removeAgentFromServer(i){var o;(o=n())==null||o({type:"remove_agent",payload:{agentId:i}})},renameAgent(i,o){var d;const c=s().agents.get(i);c&&(e(m=>{const p={...c,name:o},f=new Map(m.agents);f.set(i,p),m.agents=f}),t()),(d=n())==null||d({type:"rename_agent",payload:{agentId:i,name:o}})},updateAgentProperties(i,o){var d;const c=s().agents.get(i);c&&(e(m=>{const p={...c};o.class!==void 0&&(p.class=o.class),o.permissionMode!==void 0&&(p.permissionMode=o.permissionMode),o.model!==void 0&&(p.model=o.model),o.provider!==void 0&&(p.provider=o.provider),o.codexConfig!==void 0&&(p.codexConfig=o.codexConfig),o.codexModel!==void 0&&(p.codexModel=o.codexModel),o.useChrome!==void 0&&(p.useChrome=o.useChrome),o.cwd!==void 0&&(p.cwd=o.cwd);const f=new Map(m.agents);f.set(i,p),m.agents=f}),t()),(d=n())==null||d({type:"update_agent_properties",payload:{agentId:i,updates:o}})},getTotalTokens(){let i=0;for(const o of s().agents.values())i+=o.tokensUsed;return i},getSelectedAgents(){const i=s(),o=[];for(const l of i.selectedAgentIds){const c=i.agents.get(l);c&&o.push(c)}return o},addActivity(i){e(o=>{o.activities.unshift(i),o.activities.length>100&&o.activities.pop()}),t()},addToolExecution(i,o,l){const d=s().agents.get(i);e(m=>{m.toolExecutions.unshift({agentId:i,agentName:(d==null?void 0:d.name)||"Unknown",toolName:o,toolInput:l,timestamp:Date.now()}),m.toolExecutions.length>200&&m.toolExecutions.pop()}),t()},addFileChange(i,o,l){const d=s().agents.get(i);e(m=>{m.fileChanges.unshift({agentId:i,agentName:(d==null?void 0:d.name)||"Unknown",action:o,filePath:l,timestamp:Date.now()}),m.fileChanges.length>200&&m.fileChanges.pop()}),t()},async loadToolHistory(){try{const o=await(await mt(st("/api/agents/tool-history?limit=100"))).json();e(l=>{o.toolExecutions&&(l.toolExecutions=o.toolExecutions),o.fileChanges&&(l.fileChanges=o.fileChanges)}),t()}catch(i){console.error("[Store] Failed to load tool history:",i)}}}}function BB(s,e,t,n){return{addOutput(a,i){const o=n();e(l=>{const c=l.agentOutputs.get(a)||[];if(i.uuid&&c.some(f=>f.uuid===i.uuid))return;let d=[...c,i];d.length>200&&(d=d.slice(-200)),td.info(`Store: ${c.length} -> ${d.length}`,{agentId:a,text:i.text.slice(0,60),isStreaming:i.isStreaming,listeners:o},"store:addOutput");const m=new Map(l.agentOutputs);m.set(a,d),l.agentOutputs=m}),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 FB(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(m=>m.reportId===a.id)){const m=[d,...c];m.length>50&&m.pop(),o.set(l.agentId,m)}}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 zB(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 m of d.areas.values()){const p=m.assignedAgentIds.indexOf(i);p!==-1&&m.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(m=>{m.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(m=>{m.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)),m=d+1,p=l.zIndex??0,f=c.filter(b=>(b.zIndex??0)===d);p===d&&f.length===1||(e(b=>{b.areas.get(i).zIndex=m}),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(f=>f.zIndex??0)),m=l.zIndex??0,p=c.filter(f=>(f.zIndex??0)===d);m===d&&p.length===1||(e(f=>{for(const b of f.areas.values())b.id!==i&&(b.zIndex=(b.zIndex??0)+1);f.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 m=d.areas.get(i);m.archived=!0,m.archivedAt=Date.now(),m.originalCenter={...m.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,m=o||c.originalCenter||c.center,p=m.x-d.x,f=m.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=m,S.zIndex=w,p!==0||f!==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+f})}}),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 $B(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 m of o.selectedBuildingIds){const p=o.buildings.get(m);((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:m,command:"delete"}}))}e(m=>{const p=new Map(m.buildings);for(const f of m.selectedBuildingIds)p.delete(f);m.buildings=p,m.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(m=>{const p=new Map(m.buildings);p.set(o,{...d,...l}),m.buildings=p}),a(),t())},updateBuildingLocal(o,l){const d=s().buildings.get(o);d&&(e(m=>{const p=new Map(m.buildings);p.set(o,{...d,...l}),m.buildings=p}),t())},deleteBuilding(o){var d,m,p;const c=s().buildings.get(o);((d=c==null?void 0:c.pm2)!=null&&d.enabled||(m=c==null?void 0:c.docker)!=null&&m.enabled)&&((p=n())==null||p({type:"building_command",payload:{buildingId:o,command:"delete"}})),e(f=>{const b=new Map(f.buildings);b.delete(o),f.buildings=b,f.selectedBuildingIds.delete(o)}),a(),t()},moveBuilding(o,l){const d=s().buildings.get(o);d&&(e(m=>{const p=new Map(m.buildings);p.set(o,{...d,position:l}),m.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 m=[...c.buildingLogs.get(o)||[],l];m.length>500&&m.splice(0,m.length-500);const p=new Map(c.buildingLogs);p.set(o,m),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,m,p;const c=s().buildings.get(o);e(f=>{const b=new Map(f.streamingBuildingLogs);b.set(o,""),f.streamingBuildingLogs=b}),(d=c==null?void 0:c.docker)!=null&&d.enabled?(m=n())==null||m({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,m;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}}):(m=n())==null||m({type:"pm2_logs_stop",payload:{buildingId:o}})},appendStreamingLogChunk(o,l){e(c=>{const d=c.streamingBuildingLogs.get(o)||"",m=500*1024;let p=d+l;if(p.length>m){const b=p.indexOf(`
149
149
  `,p.length-m);b>0?p=p.slice(b+1):p=p.slice(-m)}const f=new Map(c.streamingBuildingLogs);f.set(o,p),c.streamingBuildingLogs=f}),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 m;const d=s().buildings.get(o);d&&(e(p=>{const f=new Map(p.buildings);f.set(o,{...d,subordinateBuildingIds:l}),p.buildings=f}),a(),t()),(m=n())==null||m({type:"assign_buildings",payload:{bossBuildingId:o,subordinateBuildingIds:l}})},startBossLogStreaming(o,l=50){var c;e(d=>{const m=new Map(d.bossStreamingLogs);m.set(o,[]),d.bossStreamingLogs=m}),(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,m){e(p=>{const f=p.bossStreamingLogs.get(o)||[],b={subordinateId:l,subordinateName:c,chunk:d,timestamp:Date.now(),isError:m},y=[...f,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 HB(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 UB(s,e,t,n){return{spawnBossAgent(a,i,o,l,c,d,m,p,f,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:m,provider:p,codexConfig:f,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(m=>m.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 m=i.agents.get(a.bossId),p=new Map(i.lastDelegationReceived);p.set(a.selectedAgentId,{bossName:(m==null?void 0:m.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},m=new Map(c.agents);m.set(a,d),c.agents=m}),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 m=d.get(a);m||(m=new Map,d.set(a,m)),m.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 m=new Map(l.agentTaskProgress),p=new Map(c);p.set(i,{...d,output:[...d.output,o]}),m.set(a,p),l.agentTaskProgress=m}),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 m=new Map(l.agentTaskProgress),p=new Map(c);p.set(i,{...d,status:o?"completed":"failed",completedAt:Date.now()}),m.set(a,p),l.agentTaskProgress=m}),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 m=new Map(d.agentOutputs);for(const p of o.subordinateIds||[])m.delete(p);d.agentOutputs=m}),t(),console.log("[Store] clearAllSubordinatesContext: Completed")}}}function GB(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 WB(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 m=i.split(`
150
150
  `);for(const p of m)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 qB(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 _j(){return{connectionStatus:new Map,databases:new Map,tables:new Map,tableSchemas:new Map,queryResults:[],queryHistory:[],executingQuery:!1,activeConnectionId:null,activeDatabase:null,lastSilentQueryResult:null}}function YB(s,e,t,n){const a=o=>{s().databaseState.has(o)||e(c=>{const d=new Map(c.databaseState);d.set(o,_j()),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 m=d.databaseState.get(o);if(m){const p=new Map(m.connectionStatus);p.set(l,c);const f={...m,connectionStatus:p},b=new Map(d.databaseState);b.set(o,f),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 m=d.databaseState.get(o);if(m){const p=new Map(m.databases);p.set(l,c);const f={...m,databases:p},b=new Map(d.databaseState);b.set(o,f),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 m=`${l}:${c}`;e(p=>{const f=p.databaseState.get(o);if(f){const b=new Map(f.tables);b.set(m,d);const y={...f,tables:b},w=new Map(p.databaseState);w.set(o,y),p.databaseState=w}}),t()},getTableSchema(o,l,c,d){var m;(m=n())==null||m({type:"get_table_schema",payload:{buildingId:o,connectionId:l,database:c,table:d}})},setTableSchema(o,l,c,d,m){a(o);const p=`${l}:${c}:${d}`;e(f=>{const b=f.databaseState.get(o);if(b){const y=new Map(b.tableSchemas);y.set(p,m);const w={...b,tableSchemas:y},k=new Map(f.databaseState);k.set(o,w),f.databaseState=k}}),t()},executeQuery(o,l,c,d,m=1e3){var p;a(o),e(f=>{const b=f.databaseState.get(o);if(b){const y={...b,executingQuery:!0},w=new Map(f.databaseState);w.set(o,y),f.databaseState=w}}),t(),(p=n())==null||p({type:"execute_query",payload:{buildingId:o,connectionId:l,database:c,query:d,limit:m}})},executeSilentQuery(o,l,c,d,m){var p;(p=n())==null||p({type:"execute_query",payload:{buildingId:o,connectionId:l,database:c,query:d,limit:0,silent:!0,requestId:m}})},setSilentQueryResult(o,l){a(o),e(c=>{const d=c.databaseState.get(o);if(d){const m={...d,lastSilentQueryResult:{...l,timestamp:Date.now()}},p=new Map(c.databaseState);p.set(o,m),c.databaseState=p}}),t()},setQueryResult(o,l){a(o),e(c=>{const d=c.databaseState.get(o);if(d){const m=[l,...d.queryResults].slice(0,20),p={...d,queryResults:m,executingQuery:!1},f=new Map(c.databaseState);f.set(o,p),c.databaseState=f}}),t()},setExecutingQuery(o,l){a(o),e(c=>{const d=c.databaseState.get(o);if(d){const m={...d,executingQuery:l},p=new Map(c.databaseState);p.set(o,m),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 m={...d,queryHistory:l},p=new Map(c.databaseState);p.set(o,m),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 m={...d,activeConnectionId:l,activeDatabase:null},p=new Map(c.databaseState);p.set(o,m),c.databaseState=p}}),t()},setActiveDatabase(o,l){a(o),e(c=>{const d=c.databaseState.get(o);if(d){const m={...d,activeDatabase:l},p=new Map(c.databaseState);p.set(o,m),c.databaseState=p}}),t()},getDatabaseState(o){return s().databaseState.get(o)||_j()},clearDatabaseState(o){e(l=>{const c=new Map(l.databaseState);c.delete(o),l.databaseState=c}),t()}}}function VB(s,e,t){return{async fetchSnapshots(){e(n=>{n.snapshotsLoading=!0,n.snapshotsError=null}),t();try{const n=await mt(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||[]},m=await mt(st("/api/snapshots"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(d)});if(!m.ok)throw new Error(`Failed to create snapshot: ${m.statusText}`);const p=await m.json();return await this.fetchSnapshots(),p}catch(d){const m=d instanceof Error?d.message:"Failed to create snapshot";throw this.setError(m),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 mt(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 mt(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 mt(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()}}}const KB=3e4,ab=new Map;function Hh(s,e,t){let n=s.get(e);if(!n){for(const[,a]of s)if(a.toolUseId===e&&a.parentAgentId===t){n=a;break}}return n}function Dj(s,e,t){const n=ab.get(s);n&&clearTimeout(n),ab.set(s,setTimeout(()=>{ab.delete(s),e(a=>{const i=a.subagents.get(s);if(i&&(i.status==="completed"||i.status==="failed")){const o=new Map(a.subagents);o.delete(s),a.subagents=o}}),t()},KB))}function XB(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=>{const l=Hh(o.subagents,n,a);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}`),Dj(l.id,e,t)}}),t()},addSubagentActivity(n,a,i){e(o=>{const l=Hh(o.subagents,n,a);if(l){const c=[...l.activities||[],i].slice(-50),d=new Map(o.subagents);d.set(l.id,{...l,activities:c}),o.subagents=d}}),t()},updateSubagentStats(n,a,i){e(o=>{const l=Hh(o.subagents,n,a);if(l){const c=new Map(o.subagents);c.set(l.id,{...l,stats:i}),o.subagents=c}}),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()},addSubagentStreamEntries(n,a,i){e(o=>{const l=Hh(o.subagents,n,a);if(l){const d=[...l.streamEntries||[],...i].slice(-200),m=new Map(o.subagents);m.set(l.id,{...l,streamEntries:d}),o.subagents=m,(l.status==="completed"||l.status==="failed")&&Dj(l.id,e,t)}}),t()},getSubagentByToolUseId(n){const a=s();for(const[,i]of a.subagents)if(i.toolUseId===n)return i}}}function na(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 or(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 ZB(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 Dt(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 _n(){const[,s]=x.useState({});return x.useEffect(()=>H.subscribe(()=>s({})),[]),H.getState()}function lr(){return Dt(x.useCallback(s=>s.agents,[]),or)}function lm(){const s=lr(),e=x.useRef([]),t=Array.from(s.values());return na(e.current,t)||(e.current=t),e.current}function bx(s){return Dt(x.useCallback(e=>s?e.agents.get(s):void 0,[s]))}function uM(){return Dt(x.useCallback(s=>s.selectedAgentIds,[]),ZB)}function yx(s){const e=x.useRef([]),t=x.useRef(0),n=Dt(x.useCallback(a=>s&&a.agentOutputs.get(s)||e.current,[s]),na);return n.length!==t.current&&(td.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 QB(s){return Dt(x.useCallback(e=>s?e.lastPrompts.get(s):void 0,[s]))}function xx(){return Dt(x.useCallback(s=>s.lastPrompts,[]),or)}function JB(){return Dt(x.useCallback(s=>s.isConnected,[]))}function cm(){return Dt(x.useCallback(s=>s.areas,[]),or)}function eF(){return Dt(x.useCallback(s=>s.buildings,[]),or)}function dM(){return Dt(x.useCallback(s=>s.supervisor,[]))}function al(){return Dt(x.useCallback(s=>s.settings,[]))}function hM(){return Dt(x.useCallback(s=>s.settings.hideCost,[]))}function tF(){return Dt(x.useCallback(s=>s.settings.customAgentNames,[]),na)}function nF(){return Dt(x.useCallback(s=>s.shortcuts,[]),na)}function pM(){return Dt(x.useCallback(s=>s.mouseControls,[]))}function sF(){return Dt(x.useCallback(s=>s.mouseControls.trackpad,[]))}function mM(){return Dt(x.useCallback(s=>s.terminalOpen,[]))}function fM(){return Dt(x.useCallback(s=>s.mobileView,[]))}function vx(){return Dt(x.useCallback(s=>s.fileViewerPath,[]))}function aF(){return Dt(x.useCallback(s=>s.fileViewerEditData,[]))}function iF(){return Dt(x.useCallback(s=>s.fileViewerSearchRoot,[]))}function rF(){return Dt(x.useCallback(s=>s.explorerFolderPath,[]))}function wx(){return Dt(x.useCallback(s=>s.contextModalAgentId,[]))}function gM(){return Dt(x.useCallback(s=>s.toolExecutions,[]),na)}function oF(){return Dt(x.useCallback(s=>s.fileChanges,[]),na)}function bM(){return Dt(x.useCallback(s=>s.skills,[]),or)}function um(){const s=bM(),e=x.useRef([]),t=Array.from(s.values());return na(e.current,t)||(e.current=t),e.current}function lF(s){return Dt(x.useCallback(e=>s?e.skills.get(s):void 0,[s]))}function cF(s){const e=x.useRef([]),t=lr(),n=bM();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 uF(){return Dt(x.useCallback(s=>s.customAgentClasses,[]),or)}function si(){const s=uF(),e=x.useRef([]),t=Array.from(s.values());return na(e.current,t)||(e.current=t),e.current}function yM(s){return Dt(x.useCallback(e=>s?e.customAgentClasses.get(s):void 0,[s]))}function kx(){return Dt(x.useCallback(s=>s.reconnectCount,[]))}function dF(){return Dt(x.useCallback(s=>s.supervisor.globalUsage,[]))}function hF(){return Dt(x.useCallback(s=>s.supervisor.refreshingUsage,[]))}function pF(s){const e=x.useRef(new Map);return Dt(x.useCallback(t=>s&&t.agentTaskProgress.get(s)||e.current,[s]),or)}function mF(s){return Dt(x.useCallback(e=>!s||!e.execTasks?[]:Array.from(e.execTasks.values()).filter(t=>t.agentId===s),[s]),na)}function fF(){return Dt(x.useCallback(s=>s.secrets,[]),or)}function gF(){const s=fF(),e=x.useRef([]),t=Array.from(s.values());return na(e.current,t)||(e.current=t),e.current}const bF={connectionStatus:new Map,databases:new Map,tables:new Map,tableSchemas:new Map,queryResults:[],queryHistory:[],executingQuery:!1,activeConnectionId:null,activeDatabase:null,lastSilentQueryResult:null};function dm(s){return Dt(x.useCallback(e=>(s?e.databaseState.get(s):void 0)??bF,[s]))}function yF(s){return Dt(x.useCallback(e=>{if(!s)return[];const t=e.databaseState.get(s);return(t==null?void 0:t.queryResults)??[]},[s]),na)}function xF(s){return Dt(x.useCallback(e=>{if(!s)return[];const t=e.databaseState.get(s);return(t==null?void 0:t.queryHistory)??[]},[s]),na)}function vF(s){return Dt(x.useCallback(e=>{if(!s)return!1;const t=e.databaseState.get(s);return(t==null?void 0:t.executingQuery)??!1},[s]))}function wF(){return Dt(s=>s.dockerContainersList,na)}function kF(){return Dt(s=>s.currentSnapshot)}function xM(){return Dt(s=>s.subagents,or)}function SF(s){return Dt(x.useCallback(e=>s?Array.from(e.subagents.values()).filter(t=>t.parentAgentId===s):[],[s]),na)}function jF(){return Dt(s=>s.viewMode)}function CF(){return Dt(x.useCallback(s=>s.overviewPanelOpen,[]))}function Sx(){return Dt(x.useCallback(s=>s.agentsWithUnseenOutput,[]))}class Pj{constructor(){W(this,"state");W(this,"listeners",new Set);W(this,"sendMessage",null);W(this,"agentActions");W(this,"outputActions");W(this,"supervisorActions");W(this,"areaActions");W(this,"buildingActions");W(this,"permissionActions");W(this,"delegationActions");W(this,"skillActions");W(this,"execTaskActions");W(this,"secretActions");W(this,"databaseActions");W(this,"snapshotActions");W(this,"subagentActions");W(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=As(pt.SCENE_VIEW_MODE,"3d");return o==="2d"||o==="3d"||o==="dashboard"?o:"3d"})(),overviewPanelOpen:!1,agentsWithUnseenOutput:this.loadUnseenAgents()};const e=()=>this.state,t=o=>{o(this.state)},n=()=>this.notify(),a=()=>this.sendMessage,i=()=>this.listeners.size;this.agentActions=IB(e,t,n,a,()=>this.saveUnseenAgents()),this.outputActions=BB(e,t,n,i),this.supervisorActions=FB(e,t,n,a),this.areaActions=zB(e,t,n,a),this.buildingActions=$B(e,t,n,a),this.permissionActions=HB(e,t,n,a),this.delegationActions=UB(e,t,n,a),this.skillActions=GB(e,t,n,a),this.execTaskActions=WB(e,t,n),this.secretActions=qB(e,t,n,a),this.databaseActions=YB(e,t,n,a),this.snapshotActions=VB(e,t,n),this.subagentActions=XB(e,t,n)}loadSettings(){const e=Ya(pt.SETTINGS,null);return e?{...Ej,...e}:{...Ej}}loadShortcuts(){const e=Ya(pt.SHORTCUTS,null);return e?Jg.map(n=>{const a=e.find(i=>i.id===n.id);return a?{...n,...a}:n}):[...Jg]}loadMouseControls(){var t;const e=Ya(pt.MOUSE_CONTROLS,null);return e?{bindings:tb.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:{...eb,...e.sensitivity},trackpad:{...Fh,...e.trackpad,sensitivity:{...Fh.sensitivity,...(t=e.trackpad)==null?void 0:t.sensitivity}}}:{bindings:[...tb],sensitivity:{...eb},trackpad:{...Fh}}}loadMobileView(){const e=As(pt.MOBILE_VIEW,"");return e==="terminal"||e==="3d"?e:typeof window<"u"&&window.innerWidth<=768&&"ontouchstart"in window?"3d":"terminal"}loadUnseenAgents(){const e=Ya(pt.UNSEEN_AGENTS,[]);return new Set(e)}saveUnseenAgents(){const e=Array.from(this.state.agentsWithUnseenOutput);yi(pt.UNSEEN_AGENTS,e)}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){if(this.state.mobileView="terminal",this.state.selectedAgentIds.size===0&&this.state.agents.size>0&&!this.state.currentSnapshot){const n=Array.from(this.state.agents.keys())[0];console.log("[Store] Auto-selecting first agent for terminal open:",n),this.state.selectedAgentIds=new Set([n])}let t=!1;for(const n of this.state.selectedAgentIds)this.state.agentsWithUnseenOutput.has(n)&&(t||(this.state.agentsWithUnseenOutput=new Set(this.state.agentsWithUnseenOutput),t=!0),this.state.agentsWithUnseenOutput.delete(n),console.log(`[Store] Cleared unseen badge for agent ${n}`));t&&this.saveUnseenAgents()}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,ta(pt.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,ta(pt.SCENE_VIEW_MODE,e),this.state.settings.experimental2DView=e==="2d",this.notify()}openTerminalOnMobile(e){console.log("[Store] openTerminalOnMobile called for agent:",e),LR("terminal"),this.state.selectedAgentIds.clear(),this.state.selectedAgentIds.add(e),this.state.terminalOpen=!0,this.state.mobileView="terminal",this.state.agentsWithUnseenOutput.has(e)&&(this.state.agentsWithUnseenOutput=new Set(this.state.agentsWithUnseenOutput),this.state.agentsWithUnseenOutput.delete(e),console.log(`[Store] Cleared unseen badge for agent ${e}`),this.saveUnseenAgents()),this.notify()}clearUnseenForAgent(e){this.state.agentsWithUnseenOutput.has(e)&&(this.state.agentsWithUnseenOutput=new Set(this.state.agentsWithUnseenOutput),this.state.agentsWithUnseenOutput.delete(e),this.saveUnseenAgents(),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},yi(pt.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=[...Jg],this.saveShortcuts(),this.notify()}saveShortcuts(){yi(pt.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:[...tb],sensitivity:{...eb},trackpad:{...Fh}},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(){yi(pt.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)}updateAgentContext(...e){return this.agentActions.updateAgentContext(...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)}addSubagentActivity(...e){return this.subagentActions.addSubagentActivity(...e)}updateSubagentStats(...e){return this.subagentActions.updateSubagentStats(...e)}addSubagentStreamEntries(...e){return this.subagentActions.addSubagentStreamEntries(...e)}}const Rj=1;function NF(){return typeof window<"u"?(window.__tideStore&&window.__tideStoreVersion===Rj||(window.__tideStore=new Pj,window.__tideStoreVersion=Rj),window.__tideStore):new Pj}const H=NF(),vM=x.createContext(null),AF={error:"❌",success:"✅",warning:"⚠️",info:"ℹ️"};let MF=0;function TF({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,m,p=5e3)=>{const b={id:++MF,type:c,title:d,message:m,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(vM.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:AF[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 jx(){const s=x.useContext(vM);if(!s)throw new Error("useToast must be used within ToastProvider");return s}const ar={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"}},ki=ar,Xa={bypass:{label:"Permissionless",description:"Skip all permission prompts (less safe, faster)"},interactive:{label:"Interactive",description:"Ask for approval before sensitive operations"}},Oa={"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:"🧩"}},Ia={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:"🚀"}},Sy="<<<BOSS_CONTEXT_START>>>",Lj="<<<BOSS_CONTEXT_END>>>",rc={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"}},op={"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"}},Oj={"":{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)"}},Ij={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"}},Bj={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"}},Su={mysql:{label:"MySQL",icon:"🐬",defaultPort:3306},postgresql:{label:"PostgreSQL",icon:"🐘",defaultPort:5432},oracle:{label:"Oracle",icon:"🔶",defaultPort:1521}},wM=x.createContext(null);function EF(s){const e=ar[s];if(e)return e.icon;const n=H.getState().customAgentClasses.get(s);return n?n.icon:"🤖"}function _F(s){const e=ar[s];if(e)return e.color;const n=H.getState().customAgentClasses.get(s);return n?n.color:"#888888"}const DF=3;function PF({children:s}){const{t:e}=Ue(["notifications"]),[t,n]=x.useState([]),a=x.useRef(new Map);x.useEffect(()=>()=>{a.current.forEach(c=>clearTimeout(c))},[]);const i=x.useCallback(c=>{n(m=>m.filter(p=>p.id!==c));const d=a.current.get(c);d&&(clearTimeout(d),a.current.delete(c))},[]),o=x.useCallback(c=>{n(m=>{const p=[...m,c];if(p.length>DF){const f=p.shift();if(f){const b=a.current.get(f.id);b&&(clearTimeout(b),a.current.delete(f.id))}}return p});const d=window.setTimeout(()=>{i(c.id)},8e3);a.current.set(c.id,d),md()||nL({title:`${c.agentName}: ${c.title}`,body:c.message,data:{type:"agent_notification",agentId:c.agentId,notificationId:c.id}})},[i]),l=x.useCallback(c=>{BA(c.agentId),i(c.id)},[i]);return r.jsxs(wM.Provider,{value:{showAgentNotification:o},children:[s,r.jsx("div",{id:"agent-notification-container",children:t.map(c=>{const d=EF(c.agentClass),m=_F(c.agentClass);return r.jsxs("div",{className:"agent-notification",onClick:()=>l(c),style:{"--agent-color":m},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 RF(){const s=x.useContext(wM);if(!s)throw new Error("useAgentNotification must be used within AgentNotificationProvider");return s}function LF(s){return typeof s=="string"?s:"#"+s.toString(16).padStart(6,"0")}function Zr(s,e){const t=Ba[s];if(t)return{icon:t.icon,color:LF(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 OF(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 Ep(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 kM(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 IF(s){return s<20?"#c85858":s<50?"#c89858":"#6a9a78"}function BF(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 FF(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 Fj({onOpenAreaExplorer:s}){const{t:e}=Ue(["common"]),t=_n(),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=BF(n,d=>H.getAreaForAgent(d));for(const d of a)l.has(d.id)||l.set(d.id,[]);const c=FF(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 m=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:m.length})]}),m.length>0&&r.jsx("div",{className:"agents-group-items",style:p?{background:`${p.color}08`}:void 0,children:m.map(f=>r.jsx(zF,{agent:f,area:p},f.id))})]},d||"unassigned")}),n.length>0&&r.jsx($F,{agents:n})]})}const zF=x.memo(function({agent:e,area:t}){const n=_n(),a=si(),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(f=>f+1)},15e3);return()=>clearInterval(p)}},[e.status]);const c=()=>{H.selectAgent(e.id)},d=e.status==="idle"&&e.lastActivity>0,m=e.lastActivity>0?am(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:m},title:im(e.lastActivity),children:[" ","⏱ ",OF(e.lastActivity)]})]})]}),r.jsx("div",{className:`agent-status-dot ${e.status}`})]})}),$F=x.memo(function({agents:e}){const{t}=Ue(["common"]),n=_n(),a=si(),i=n.settings.hideCost,[o,l]=x.useState(()=>oy(pt.GLOBAL_SUPERVISOR_COLLAPSED)),c=()=>{const p=!o;l(p),ly(pt.GLOBAL_SUPERVISOR_COLLAPSED,p)},d=x.useMemo(()=>e.map(p=>{const f=H.getAgentSupervisorHistory(p.id),b=f.length>0?f[0]:null;return{agent:p,entry:b,timestamp:(b==null?void 0:b.timestamp)||p.lastActivity||0}}).filter(p=>p.entry!==null).sort((p,f)=>f.timestamp-p.timestamp),[e,n.supervisor.agentHistories]),m=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:Ep(m)})]}),!o&&r.jsx("div",{className:"global-supervisor-list",children:d.map(({agent:p,entry:f})=>{const b=Zr(p.class,a),y=f.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:DA[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:Ep(f.timestamp)})]}),r.jsx("div",{className:"global-supervisor-status-line",children:Gr(y.statusDescription,i)}),r.jsx("div",{className:"global-supervisor-summary-text",children:Gr(y.recentWorkSummary,i)})]},p.id)})})]})}),HF={idle:"idle",working:"walk",waiting:"sit",waiting_permission:"idle",error:"emote-no",offline:"static",orphaned:"idle"},zj={idle:4915102,working:4890367,waiting:16752202,waiting_permission:16763904,error:16730698,offline:8947848,orphaned:16752202};function pc({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 m=x.useRef(null),p=x.useRef(null),f=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),A=x.useRef(new fA),[D,M]=x.useState(!1),[I,E]=x.useState(!1),_=x.useRef(!1),P=x.useRef(0),L=x.useRef(new yt),R=x.useRef(!1),z=x.useRef({x:0,y:0}),F=x.useRef({x:0,y:0});x.useEffect(()=>{const U=m.current;if(!U)return;E(!1);const G=new ix;G.background=new Bt(1710628),f.current=G;const K=new sx(45,c/d,.1,100);K.position.set(0,1.2,1.4),K.lookAt(0,.4,0),b.current=K;let Z;try{Z=new gA({antialias:!0,alpha:!0})}catch{console.warn("[ModelPreview] WebGL context creation failed — too many active contexts"),E(!0);return}Z.setSize(c,d),Z.setPixelRatio(Math.min(window.devicePixelRatio,2)),Z.setClearColor(1710628,1),U.appendChild(Z.domElement),p.current=Z;const B=new ax(16777215,1);G.add(B);const ee=new sc(16777215,1.5);ee.position.set(2,3,2),G.add(ee);const se=new sc(4890367,.6);se.position.set(-2,1,-1),G.add(se);const O=new Zb(1,32),Y=new rt({color:2763322,roughness:.8}),Q=new De(O,Y);Q.rotation.x=-Math.PI/2,Q.position.y=0,G.add(Q);const ie=new Xo(.35,.42,32),J=new We({color:zj.idle,side:ws,transparent:!0,opacity:.8}),re=new De(ie,J);re.rotation.x=-Math.PI/2,re.position.y=.01,G.add(re),j.current=re,M(!0);const V=pe=>{R.current=!0,z.current={x:pe.clientX,y:pe.clientY},U.style.cursor="grabbing"},ne=pe=>{if(!R.current||!y.current)return;const Te=pe.clientX-z.current.x,Me=pe.clientY-z.current.y;F.current.y+=Te*.01,F.current.x+=Me*.01,F.current.x=Math.max(-Math.PI/4,Math.min(Math.PI/4,F.current.x)),y.current.rotation.y=F.current.y,y.current.rotation.x=F.current.x,z.current={x:pe.clientX,y:pe.clientY}},de=()=>{R.current=!1,U.style.cursor="grab"},be=()=>{R.current=!1,U.style.cursor="grab"};U.addEventListener("mousedown",V),window.addEventListener("mousemove",ne),window.addEventListener("mouseup",de),U.addEventListener("mouseleave",be),U.style.cursor="grab";const ve=()=>{C.current=requestAnimationFrame(ve);const pe=A.current.getDelta();if(w.current)w.current.update(pe);else if(y.current&&!_.current){P.current+=pe;const Te=P.current,X=Math.sin(Te*1.5)*.02,le=Math.sin(Te*.8)*.01;y.current.position.set(L.current.x+le,L.current.y+X,L.current.z)}p.current&&f.current&&b.current&&p.current.render(f.current,b.current)};return ve(),()=>{if(cancelAnimationFrame(C.current),U.removeEventListener("mousedown",V),window.removeEventListener("mousemove",ne),window.removeEventListener("mouseup",de),U.removeEventListener("mouseleave",be),y.current&&f.current&&(f.current.remove(y.current),y.current.traverse(pe=>{var Te,Me;pe instanceof De&&((Te=pe.geometry)==null||Te.dispose(),Array.isArray(pe.material)?pe.material.forEach(Le=>{Le.map&&Le.map.dispose(),Le.dispose()}):pe.material&&(pe.material.map&&((Me=pe.material.map)==null||Me.dispose()),pe.material.dispose()))}),y.current=null),j.current&&f.current&&(f.current.remove(j.current),j.current.geometry.dispose(),j.current.material.dispose(),j.current=null),f.current&&(f.current.traverse(pe=>{var Te;pe instanceof De&&((Te=pe.geometry)==null||Te.dispose(),pe.material instanceof Ur&&pe.material.dispose())}),f.current.clear()),w.current=null,S.current=null,k.current.clear(),p.current){try{const Te=p.current.getContext().getExtension("WEBGL_lose_context");Te&&Te.loseContext()}catch{}p.current.dispose(),U.contains(p.current.domElement)&&U.removeChild(p.current.domElement),p.current=null}f.current=null,b.current=null,M(!1)}},[c,d]),x.useEffect(()=>{if(!D||!f.current)return;const U=new dx,G=new hx;G.setDecoderPath("https://www.gstatic.com/draco/versioned/decoders/1.5.7/"),U.setDRACOLoader(G),U.setMeshoptDecoder(px);let K=null;const Z=B=>{y.current&&f.current&&(f.current.remove(y.current),y.current=null,w.current=null,S.current=null);const ee=B.scene;ee.scale.setScalar(a);const se=(i==null?void 0:i.x)??0,O=(i==null?void 0:i.y)??0,Y=(i==null?void 0:i.z)??0;if(ee.position.set(se,Y,O),ee.visible=!0,F.current={x:0,y:0},ee.rotation.set(0,0,0),ee.traverse(Q=>{if(Q instanceof De&&(Q.castShadow=!0,Q.receiveShadow=!0,Q.material)){const ie=Q.material;ie.map&&(ie.map.colorSpace=Va)}}),f.current)if(f.current.add(ee),y.current=ee,L.current.copy(ee.position),B.animations.length>0){_.current=!0;const Q=new Uu(ee);w.current=Q,k.current.clear();for(const ie of B.animations)k.current.set(ie.name.toLowerCase(),ie);if(o!==""){const ie=o?k.current.get(o.toLowerCase())||B.animations[0]:k.current.get("idle")||B.animations[0];if(ie){const J=Q.clipAction(ie);J.reset().play(),S.current=J}}}else _.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,B=>{console.log("[ModelPreview] Successfully loaded custom model file, animations:",B.animations.length),Z(B)},void 0,B=>{console.error("[ModelPreview] Failed to load custom model file:",B)});else if(n){const B=hd(n);console.log("[ModelPreview] Loading custom model from URL:",n),U.load(B,ee=>{console.log("[ModelPreview] Successfully loaded custom model URL, animations:",ee.animations.length),Z(ee)},void 0,ee=>{console.error("[ModelPreview] Failed to load custom model URL:",n,ee)})}else{const B=e||(s?ec[s]:void 0)||"character-male-a.glb";U.load(`/assets/characters/${B}`,Z,void 0,ee=>{console.error("[ModelPreview] Failed to load model:",B,ee)})}return()=>{K&&URL.revokeObjectURL(K),G.dispose()}},[s,e,t,n,a,i,D]);const $=U=>{if(!w.current)return;const G=HF[U],K=k.current.get(G);if(!K){const B=k.current.get("idle");if(B){const ee=w.current.clipAction(B);ee.reset().play(),S.current=ee}return}const Z=w.current.clipAction(K);U==="working"?Z.timeScale=1.5:U==="error"&&(Z.setLoop(dA,1),Z.clampWhenFinished=!0),S.current&&S.current!==Z?(S.current.fadeOut(.3),Z.reset().fadeIn(.3).play()):Z.reset().play(),S.current=Z};return x.useEffect(()=>{if(D){if(j.current){const U=j.current.material;U.color.setHex(zj[l]),l==="working"?U.opacity=.6+Math.sin(Date.now()*.005)*.4:U.opacity=.8}$(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",G=k.current.get(U);if(G){const K=w.current.clipAction(G);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]),I?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:m,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,m]=x.useState([]),[p,f]=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),A=x.useCallback(async L=>{if(!L){m([]);return}k(!0);try{const R=new URLSearchParams({path:L,dirs:i?"true":"false",limit:"15"}),z=await mt(st(`/api/files/autocomplete?${R}`));if(z.ok){const F=await z.json();m(F.suggestions||[]),f(-1)}}catch(R){console.error("Failed to fetch path suggestions:",R)}finally{k(!1)}},[i]);x.useEffect(()=>(C.current&&clearTimeout(C.current),s&&b?C.current=setTimeout(()=>{A(s)},150):m([]),()=>{C.current&&clearTimeout(C.current)}),[s,b,A]);const D=L=>{e(L.target.value),y(!0)},M=x.useCallback(L=>{var z;const R=L.isDirectory?L.path+"/":L.path;e(R),y(L.isDirectory),f(-1),(z=S.current)==null||z.focus(),L.isDirectory&&A(R)},[e,A]),I=L=>{if(!b||d.length===0){L.key==="Enter"&&t&&(L.preventDefault(),t()),L.key==="Escape"&&y(!1);return}switch(L.key){case"ArrowDown":L.preventDefault(),f(R=>R<d.length-1?R+1:R);break;case"ArrowUp":L.preventDefault(),f(R=>R>0?R-1:-1);break;case"Tab":if(L.preventDefault(),d.length>0){const R=p>=0?p:0;M(d[R])}break;case"Enter":L.preventDefault(),p>=0&&d[p]?M(d[p]):t&&(y(!1),t());break;case"Escape":L.preventDefault(),y(!1),f(-1);break}},E=()=>{y(!0),s&&A(s)},_=()=>{setTimeout(()=>{y(!1),f(-1)},200)};x.useEffect(()=>{if(p>=0&&j.current){const R=j.current.querySelectorAll(".folder-input-suggestion")[p];R&&R.scrollIntoView({block:"nearest"})}},[p]);const P=["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:P,value:s,onChange:D,onKeyDown:I,onFocus:E,onBlur:_,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((L,R)=>r.jsxs("div",{className:`folder-input-suggestion ${R===p?"selected":""}`,onClick:()=>M(L),onMouseEnter:()=>f(R),children:[r.jsx("span",{className:"folder-input-suggestion-icon",children:L.isDirectory?"📁":"📄"}),r.jsx("span",{className:"folder-input-suggestion-name",children:L.name}),L.isDirectory&&r.jsx("span",{className:"folder-input-suggestion-hint",children:"/"})]},L.path))})]})}function SM({agent:s,isOpen:e,onClose:t}){const{t:n}=Ue(["terminal","common","tools"]),a=um(),i=si(),[o,l]=x.useState(s.name),[c,d]=x.useState(s.class),[m,p]=x.useState(s.permissionMode),[f,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"),[A,D]=x.useState(s.useChrome||!1),[M,I]=x.useState(s.cwd),[E,_]=x.useState(new Set),[P,L]=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(ie=>ie.assignedAgentIds.includes(s.id)).map(ie=>ie.id);_(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),I(s.cwd);const Q=a.filter(ie=>ie.assignedAgentIds.includes(s.id)).map(ie=>ie.id);_(new Set(Q))}},[e,s,a]);const R=x.useMemo(()=>a.filter(Q=>Q.enabled),[a]),z=x.useMemo(()=>{if(!P.trim())return R;const Q=P.toLowerCase();return R.filter(ie=>ie.name.toLowerCase().includes(Q)||ie.description.toLowerCase().includes(Q)||ie.slug.toLowerCase().includes(Q))},[R,P]),F=x.useMemo(()=>R.filter(Q=>Q.assignedAgentClasses.includes(c)),[R,c]),$=x.useCallback(Q=>{_(ie=>{const J=new Set(ie);return J.has(Q)?J.delete(Q):J.add(Q),J})},[]),U=x.useMemo(()=>{const Q=i.find(ie=>ie.id===c);if(Q!=null&&Q.model)return Q.model},[i,c]),G=x.useMemo(()=>{const Q=i.find(ie=>ie.id===c);if(Q!=null&&Q.customModelPath)return st(`/api/custom-models/${Q.id}`)},[i,c]),K=x.useMemo(()=>{const Q=i.find(ie=>ie.id===c);return Q==null?void 0:Q.modelScale},[i,c]),Z=x.useMemo(()=>i.find(Q=>Q.id===c),[i,c]),B=x.useMemo(()=>i.find(ie=>ie.id===c)?"scout":c,[i,c]),ee=x.useMemo(()=>{const Q=o.trim();if(Q&&Q!==s.name||c!==s.class||m!==s.permissionMode||f!==(s.provider||"claude")||f==="claude"&&k!==(s.model||"sonnet")||f==="codex"&&j!==(s.codexModel||"gpt-5.3-codex")||f==="codex"&&JSON.stringify(y||{})!==JSON.stringify(s.codexConfig||{})||A!==(s.useChrome||!1)||M!==s.cwd)return!0;const ie=a.filter(re=>re.assignedAgentIds.includes(s.id)).map(re=>re.id).sort().join(","),J=Array.from(E).sort().join(",");return ie!==J},[o,c,m,f,k,j,y,A,M,E,s,a]),se=()=>{const Q=o.trim(),ie={};Q&&Q!==s.name&&H.renameAgent(s.id,Q),c!==s.class&&(ie.class=c),m!==s.permissionMode&&(ie.permissionMode=m),f!==(s.provider||"claude")&&(ie.provider=f),f==="codex"&&JSON.stringify(y||{})!==JSON.stringify(s.codexConfig||{})&&(ie.codexConfig=y),f==="codex"&&j!==(s.codexModel||"gpt-5.3-codex")&&(ie.codexModel=j),f==="claude"&&k!==(s.model||"sonnet")&&(ie.model=k),A!==(s.useChrome||!1)&&(ie.useChrome=A),M!==s.cwd&&(ie.cwd=M);const J=a.filter(V=>V.assignedAgentIds.includes(s.id)).map(V=>V.id).sort().join(","),re=Array.from(E).sort().join(",");J!==re&&(ie.skillIds=Array.from(E)),Object.keys(ie).length>0&&H.updateAgentProperties(s.id,ie),t()},{handleMouseDown:O,handleClick:Y}=Ms(t);return e?r.jsx("div",{className:"modal-overlay visible",onMouseDown:O,onClick:Y,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(pc,{agentClass:B,modelFile:U,customModelUrl:G,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(ar).filter(([Q])=>Q!=="boss").map(([Q,ie])=>r.jsxs("button",{className:`class-chip ${c===Q?"selected":""}`,onClick:()=>d(Q),title:ie.description,children:[r.jsx("span",{className:"class-chip-icon",children:ie.icon}),r.jsx("span",{className:"class-chip-name",children:Q.charAt(0).toUpperCase()+Q.slice(1)})]},Q))]})]})]}),(Z==null?void 0:Z.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:Z.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 ${f==="claude"?"selected":""}`,onClick:()=>b("claude"),children:[r.jsx("span",{children:"🧠"}),r.jsx("span",{children:"Claude"})]}),r.jsxs("button",{className:`spawn-select-btn ${f==="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(Xa).map(Q=>r.jsxs("button",{className:`spawn-select-btn ${m===Q?"selected":""}`,onClick:()=>p(Q),title:Xa[Q].description,children:[r.jsx("span",{children:Q==="bypass"?"⚡":"🔐"}),r.jsx("span",{children:Xa[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")}),f==="claude"?r.jsx("div",{className:"spawn-select-row",children:Object.keys(Ia).map(Q=>r.jsxs("button",{className:`spawn-select-btn ${k===Q?"selected":""}`,onClick:()=>S(Q),title:Ia[Q].description,children:[r.jsx("span",{children:Ia[Q].icon}),r.jsx("span",{children:Ia[Q].label})]},Q))}):f==="codex"?r.jsx("div",{className:"spawn-select-row spawn-select-row--codex-models",children:Object.keys(Oa).map(Q=>r.jsxs("button",{className:`spawn-select-btn ${j===Q?"selected":""}`,onClick:()=>C(Q),title:Oa[Q].description,children:[r.jsx("span",{children:Oa[Q].icon}),r.jsx("span",{children:Oa[Q].label})]},Q))}):r.jsx("div",{className:"spawn-inline-hint",children:n("terminal:spawn.codex.configuration")})]})}),f==="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(ie=>({...ie,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(ie=>({...ie,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(ie=>({...ie,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(ie=>({...ie,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(ie=>({...ie,profile:Q.target.value||void 0}))})]})]})}),f==="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:A,onChange:Q=>D(Q.target.checked),disabled:f!=="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:M,onChange:I,placeholder:n("terminal:spawn.workingDirPlaceholder"),className:"spawn-input",directoriesOnly:!0})]})}),M!==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"),")"]})]}),R.length>6&&r.jsx("input",{type:"text",className:"spawn-input skill-search-input",placeholder:n("terminal:spawn.filterSkills"),value:P,onChange:Q=>L(Q.target.value)}),r.jsx("div",{className:"skills-chips-compact",children:R.length===0?r.jsx("div",{className:"skills-empty",children:n("terminal:spawn.noEnabledSkills")}):z.length===0?r.jsx("div",{className:"skills-empty",children:n("terminal:spawn.noSkillsMatch",{query:P})}):z.map(Q=>{const ie=F.includes(Q),re=E.has(Q.id)||ie;return r.jsxs("button",{className:`skill-chip ${re?"selected":""} ${ie?"class-based":""}`,onClick:()=>!ie&&$(Q.id),title:ie?n("terminal:spawn.assignedViaClass"):Q.name,children:[re&&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"}),ie&&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:se,disabled:!ee,children:n("common:buttons2.saveChanges")})]})]})}):null}var jc=tA();const UF=ud(jc);function to({children:s}){return typeof document>"u"?null:jc.createPortal(s,document.body)}function ju(s){return s>=1e6?`${(s/1e6).toFixed(1)}M`:s>=1e3?`${(s/1e3).toFixed(1)}K`:s.toString()}function $j(s){return`${s.toFixed(1)}%`}function GF(s){return s>=80?"#ff4a4a":s>=60?"#ff9e4a":s>=40?"#ffd700":"#4aff9e"}const WF={systemPrompt:"#4a9eff",systemTools:"#9e4aff",messages:"#4aff9e",freeSpace:"rgba(255,255,255,0.1)",autocompactBuffer:"#ff9e4a"},qF={systemPrompt:"terminal:context.systemPrompt",systemTools:"terminal:context.systemTools",messages:"terminal:context.messagesCategory",freeSpace:"terminal:context.freeSpace",autocompactBuffer:"terminal:context.autocompactBuffer"},YF={systemPrompt:"terminal:context.systemPromptDesc",systemTools:"terminal:context.systemToolsDesc",messages:"terminal:context.messagesDesc",freeSpace:"terminal:context.freeSpaceDesc",autocompactBuffer:"terminal:context.autocompactBufferDesc"};function jM({agent:s,isOpen:e,onClose:t,onRefresh:n}){const{t:a}=Ue(["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"],m=x.useMemo(()=>i?d.map(y=>({key:y,...i.categories[y],label:a(qF[y]),description:a(YF[y]),color:WF[y]})):[],[i]),p=x.useMemo(()=>m.filter(y=>y.key!=="freeSpace"),[m]),{handleMouseDown:f,handleClick:b}=Ms(t);return e?r.jsx(to,{children:r.jsx("div",{className:"modal-overlay visible",onMouseDown:f,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:ju(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:GF(i.usedPercent)},children:[ju(i.totalTokens)," / ",ju(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}: ${ju(y.tokens)} (${$j(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:m.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:ju(y.tokens)}),r.jsx("div",{style:{fontSize:"11px",color:"var(--text-secondary)"},children:$j(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 VF=x.memo(function({tokensUsed:e,createdAt:t}){const{t:n}=Ue(["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:ry(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:RA(t)})]})]})}),CM=x.memo(function({contextInfo:e,onClick:t}){const{t:n}=Ue(["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:IF(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")})]})}),KF=x.memo(function({lastActivity:e}){const{t}=Ue(["common"]);return r.jsxs("div",{className:"unit-idle-timer",title:t("unitPanel.timeSinceActivity"),style:{color:am(e)},children:["⏱ ",im(e)]})}),XF=x.memo(function({toolName:e}){const{t}=Ue(["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})]})}),ZF=x.memo(function({task:e}){const{t}=Ue(["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})]})}),QF=x.memo(function({cwd:e}){const{t}=Ue(["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})]})}),JF=x.memo(function({text:e,maxLength:t=150}){const{t:n}=Ue(["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})]})}),ez=x.memo(function({text:e,maxLength:t=200}){const{t:n}=Ue(["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 tz({agent:s,onFocusAgent:e,onKillAgent:t,onCallSubordinates:n,onOpenAreaExplorer:a}){var V,ne;const{t:i}=Ue(["common"]),o=_n(),l=si(),{showToast:c}=jx(),d=o.agents.get(s.id)||s,m=Zr(d.class,l),p=l.find(de=>de.id===d.class),f=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),[,A]=x.useState(0),[D,M]=x.useState(!0),[I,E]=x.useState(!1),[_,P]=x.useState([]),[L,R]=x.useState(null),[z,F]=x.useState(!1),[$,U]=x.useState(!1),G=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 de=setInterval(()=>{A(be=>be+1)},15e3);return()=>clearInterval(de)}},[d.status]),x.useEffect(()=>{d.permissionMode==="interactive"&&mt(st("/api/remembered-patterns")).then(de=>de.json()).then(P).catch(de=>console.error("Failed to fetch remembered patterns:",de))},[d.permissionMode]);const Z=x.useMemo(()=>kM(d),[d.contextStats,d.contextUsed,d.contextLimit]),B=H.getAreaForAgent(d.id),ee=o.agentOutputs.get(d.id)||[],se=ee.length>0?ee[ee.length-1]:null,O=o.lastPrompts.get(d.id),Y=async(de,be)=>{try{(await mt(st(`/api/remembered-patterns/${de}/${encodeURIComponent(be)}`),{method:"DELETE"})).ok&&P(pe=>pe.filter(Te=>!(Te.tool===de&&Te.pattern===be)))}catch(ve){console.error("Failed to remove pattern:",ve)}},Q=async()=>{if(confirm(i("confirm.clearPatterns")))try{(await mt(st("/api/remembered-patterns"),{method:"DELETE"})).ok&&P([])}catch(de){console.error("Failed to clear patterns:",de)}},ie=()=>{confirm(i("confirm.terminateAgent"))&&t(d.id)},J=()=>{const de=S.trim();de&&de!==d.name?H.renameAgent(d.id,de):j(d.name),k(!1)},re=de=>{de.key==="Enter"?J():de.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(pc,{agentClass:d.class,modelFile:f,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:`${m.color}20`},children:m.icon}),r.jsxs("div",{className:"unit-header-info",children:[w?r.jsx("input",{ref:C,type:"text",className:"unit-name-input",value:S,onChange:de=>j(de.target.value),onBlur:J,onKeyDown:re}):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:Sp[d.status]||Sp.default},children:d.status}),r.jsxs("span",{children:[" • ",d.class," • ",d.provider]})]}),d.status==="idle"&&d.lastActivity>0&&r.jsx(KF,{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:()=>F(!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:()=>R("collapse"),title:i("unitPanel.collapseContext"),disabled:d.status!=="idle",children:"📦"}),r.jsx("button",{className:"unit-action-icon warning",onClick:()=>R("clear"),title:i("unitPanel.clearContext"),children:"🗑️"}),r.jsx("button",{className:"unit-action-icon danger",onClick:ie,title:i("unitPanel.killAgent"),children:"☠️"})]})]}),B&&r.jsxs("div",{className:"unit-area",children:[r.jsx("span",{className:"unit-area-dot",style:{background:B.color}}),r.jsx("span",{className:"unit-area-name",children:B.name})]}),O&&r.jsx(JF,{text:O.text}),se&&r.jsx(ez,{text:se.text}),r.jsx(VF,{tokensUsed:d.tokensUsed,createdAt:d.createdAt}),r.jsx(CM,{contextInfo:Z,onClick:()=>U(!0)}),d.currentTool&&r.jsx(XF,{toolName:d.currentTool}),d.currentTask&&r.jsx(ZF,{task:d.currentTask}),r.jsx(QF,{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:(V=Xa[d.permissionMode])==null?void 0:V.description,children:[r.jsx("span",{className:"unit-permission-mode-icon",children:d.permissionMode==="bypass"?"⚡":"🔐"}),r.jsx("span",{className:"unit-permission-mode-label",children:((ne=Xa[d.permissionMode])==null?void 0:ne.label)||d.permissionMode})]})]}),d.permissionMode==="interactive"&&r.jsx(nz,{patterns:_,showPatterns:I,onToggle:()=>E(!I),onRemovePattern:Y,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()=>{const de=d.provider==="codex"?`codex resume ${d.sessionId}`:`claude --resume ${d.sessionId}`;try{await navigator.clipboard.writeText(de),c("success",i("toast.copied"),i("toast.resumeCommandCopied"),2e3)}catch{c("error",i("toast.errorTitle"),i("toast.failedToCopy"),3e3)}},children:[d.provider==="codex"?"codex resume":"claude --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:()=>M(!D),children:[r.jsx("div",{className:"unit-stat-label",children:i("unitPanel.supervisorHistory")}),r.jsxs("span",{className:"unit-supervisor-history-toggle",children:[G.length>0&&r.jsx("span",{className:"unit-supervisor-history-count",children:G.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")}):G.length===0?r.jsx("div",{className:"unit-supervisor-history-empty",children:i("unitPanel.noSupervisorReports")}):G.slice(0,10).map((de,be)=>r.jsx(az,{entry:de,defaultExpanded:be===0},de.id))})]}),(d.isBoss||d.class==="boss")&&r.jsx(iz,{agent:d}),d.bossId&&r.jsx(oz,{agentId:d.id,bossId:d.bossId}),d.class!=="boss"&&!d.isBoss&&!d.bossId&&r.jsx(lz,{agentId:d.id}),L&&r.jsx(sz,{action:L,agentName:d.name,onClose:()=>R(null),onConfirm:()=>{L==="collapse"?H.collapseContext(d.id):H.clearContext(d.id),R(null)}}),r.jsx(SM,{agent:d,isOpen:z,onClose:()=>F(!1)}),r.jsx(jM,{agent:d,isOpen:$,onClose:()=>U(!1),onRefresh:()=>{H.refreshAgentContext(d.id)}})]})}const nz=x.memo(function({patterns:e,showPatterns:t,onToggle:n,onRemovePattern:a,onClearAll:i}){const{t:o}=Ue(["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")})]})})]})}),sz=x.memo(function({action:e,agentName:t,onClose:n,onConfirm:a}){const{t:i}=Ue(["common"]),{handleMouseDown:o,handleClick:l}=Ms(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")})]})]})})}),az=x.memo(function({entry:e,defaultExpanded:t=!1}){var f;const{t:n}=Ue(["common"]),[a,i]=x.useState(t),o=_n(),{analysis:l}=e,c=o.settings.hideCost,d=Gr(l.statusDescription,c),m=Gr(l.recentWorkSummary,c),p=(f=l.concerns)==null?void 0:f.map(b=>Gr(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:DA[l.progress]||"#888"},title:l.progress}),r.jsx("span",{className:"supervisor-history-status",children:d}),r.jsx("span",{className:"supervisor-history-time",children:Ep(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"),":"]})," ",m]}),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))})]})]})]})}),iz=x.memo(function({agent:e}){const{t}=Ue(["common"]),n=_n(),a=si(),[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]),m=H.getDelegationHistory(e.id),p=n.pendingDelegation,f=(p==null?void 0:p.bossId)===e.id;x.useEffect(()=>{H.requestDelegationHistory(e.id)},[e.id]);const b=ki.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")," (",m.length,")"]}),r.jsx("span",{className:"boss-toggle",children:l?"▼":"▶"})]}),l&&r.jsxs("div",{className:"boss-delegation-history-list",children:[f&&r.jsxs("div",{className:"boss-delegation-pending",children:[r.jsx("span",{className:"delegation-spinner",children:"⏳"}),t("unitPanel.analyzingRequest")]}),m.length===0&&!f?r.jsx("div",{className:"boss-delegation-empty",children:t("unitPanel.noDelegationHistory")}):m.slice(0,10).map(y=>r.jsx(rz,{decision:y},y.id))]})]})]})}),rz=x.memo(function({decision:e}){const{t}=Ue(["common"]),[n,a]=x.useState(!1),o=_n().agents.get(e.selectedAgentId),l=o?ki[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:Ep(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(", ")]})]})]})}),oz=x.memo(function({agentId:e,bossId:t}){const{t:n}=Ue(["common"]),i=_n().agents.get(t);if(!i)return null;const o=ki.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:"✕"})]})}),lz=x.memo(function({agentId:e}){const{t}=Ue(["common"]),n=_n(),[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=ki.boss,c=d=>{const m=n.agents.get(d);if(!m)return;const p=m.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 m;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:((m=d.subordinateIds)==null?void 0:m.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")})]})})}),cz=x.memo(function({agents:e}){const{t}=Ue(["common"]),n=si(),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:ER(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(uz,{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")})})]})}),uz=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 Hj({onFocusAgent:s,onKillAgent:e,onCallSubordinates:t,onOpenAreaExplorer:n}){const a=_n(),i=H.getSelectedAgents();if(a.selectedAgentIds.size===0)return r.jsx(Fj,{onOpenAreaExplorer:n});if(a.selectedAgentIds.size===1){const o=i[0];return o?r.jsx(tz,{agent:o,onFocusAgent:s,onKillAgent:e,onCallSubordinates:t,onOpenAreaExplorer:n}):r.jsx(Fj,{onOpenAreaExplorer:n})}return r.jsx(cz,{agents:i})}function dz(s,e){const t={};return(s[s.length-1]===""?[...s,""]:s).join((t.padRight?" ":"")+","+(t.padLeft===!1?"":" ")).trim()}const hz=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,pz=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,mz={};function Uj(s,e){return(mz.jsx?pz:hz).test(s)}const fz=/[ \t\n\f\r]/g;function gz(s){return typeof s=="object"?s.type==="text"?Gj(s.value):!1:Gj(s)}function Gj(s){return s.replace(fz,"")===""}class gd{constructor(e,t,n){this.normal=t,this.property=e,n&&(this.space=n)}}gd.prototype.normal={};gd.prototype.property={};gd.prototype.space=void 0;function NM(s,e){const t={},n={};for(const a of s)Object.assign(t,a.property),Object.assign(n,a.normal);return new gd(t,n,e)}function jy(s){return s.toLowerCase()}class sa{constructor(e,t){this.attribute=t,this.property=e}}sa.prototype.attribute="";sa.prototype.booleanish=!1;sa.prototype.boolean=!1;sa.prototype.commaOrSpaceSeparated=!1;sa.prototype.commaSeparated=!1;sa.prototype.defined=!1;sa.prototype.mustUseProperty=!1;sa.prototype.number=!1;sa.prototype.overloadedBoolean=!1;sa.prototype.property="";sa.prototype.spaceSeparated=!1;sa.prototype.space=void 0;let bz=0;const It=il(),ds=il(),Cy=il(),tt=il(),On=il(),oc=il(),fa=il();function il(){return 2**++bz}const Ny=Object.freeze(Object.defineProperty({__proto__:null,boolean:It,booleanish:ds,commaOrSpaceSeparated:fa,commaSeparated:oc,number:tt,overloadedBoolean:Cy,spaceSeparated:On},Symbol.toStringTag,{value:"Module"})),ib=Object.keys(Ny);class Cx extends sa{constructor(e,t,n,a){let i=-1;if(super(e,t),Wj(this,"space",a),typeof n=="number")for(;++i<ib.length;){const o=ib[i];Wj(this,ib[i],(n&Ny[o])===Ny[o])}}}Cx.prototype.defined=!0;function Wj(s,e,t){t&&(s[e]=t)}function Cc(s){const e={},t={};for(const[n,a]of Object.entries(s.properties)){const i=new Cx(n,s.transform(s.attributes||{},n),a,s.space);s.mustUseProperty&&s.mustUseProperty.includes(n)&&(i.mustUseProperty=!0),e[n]=i,t[jy(n)]=n,t[jy(i.attribute)]=n}return new gd(e,t,s.space)}const AM=Cc({properties:{ariaActiveDescendant:null,ariaAtomic:ds,ariaAutoComplete:null,ariaBusy:ds,ariaChecked:ds,ariaColCount:tt,ariaColIndex:tt,ariaColSpan:tt,ariaControls:On,ariaCurrent:null,ariaDescribedBy:On,ariaDetails:null,ariaDisabled:ds,ariaDropEffect:On,ariaErrorMessage:null,ariaExpanded:ds,ariaFlowTo:On,ariaGrabbed:ds,ariaHasPopup:null,ariaHidden:ds,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:On,ariaLevel:tt,ariaLive:null,ariaModal:ds,ariaMultiLine:ds,ariaMultiSelectable:ds,ariaOrientation:null,ariaOwns:On,ariaPlaceholder:null,ariaPosInSet:tt,ariaPressed:ds,ariaReadOnly:ds,ariaRelevant:null,ariaRequired:ds,ariaRoleDescription:On,ariaRowCount:tt,ariaRowIndex:tt,ariaRowSpan:tt,ariaSelected:ds,ariaSetSize:tt,ariaSort:null,ariaValueMax:tt,ariaValueMin:tt,ariaValueNow:tt,ariaValueText:null,role:null},transform(s,e){return e==="role"?e:"aria-"+e.slice(4).toLowerCase()}});function MM(s,e){return e in s?s[e]:e}function TM(s,e){return MM(s,e.toLowerCase())}const yz=Cc({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:oc,acceptCharset:On,accessKey:On,action:null,allow:null,allowFullScreen:It,allowPaymentRequest:It,allowUserMedia:It,alt:null,as:null,async:It,autoCapitalize:null,autoComplete:On,autoFocus:It,autoPlay:It,blocking:On,capture:null,charSet:null,checked:It,cite:null,className:On,cols:tt,colSpan:null,content:null,contentEditable:ds,controls:It,controlsList:On,coords:tt|oc,crossOrigin:null,data:null,dateTime:null,decoding:null,default:It,defer:It,dir:null,dirName:null,disabled:It,download:Cy,draggable:ds,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:It,formTarget:null,headers:On,height:tt,hidden:Cy,high:tt,href:null,hrefLang:null,htmlFor:On,httpEquiv:On,id:null,imageSizes:null,imageSrcSet:null,inert:It,inputMode:null,integrity:null,is:null,isMap:It,itemId:null,itemProp:On,itemRef:On,itemScope:It,itemType:On,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:It,low:tt,manifest:null,max:null,maxLength:tt,media:null,method:null,min:null,minLength:tt,multiple:It,muted:It,name:null,nonce:null,noModule:It,noValidate:It,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:It,optimum:tt,pattern:null,ping:On,placeholder:null,playsInline:It,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:It,referrerPolicy:null,rel:On,required:It,reversed:It,rows:tt,rowSpan:tt,sandbox:On,scope:null,scoped:It,seamless:It,selected:It,shadowRootClonable:It,shadowRootDelegatesFocus:It,shadowRootMode:null,shape:null,size:tt,sizes:null,slot:null,span:tt,spellCheck:ds,src:null,srcDoc:null,srcLang:null,srcSet:null,start:tt,step:null,style:null,tabIndex:tt,target:null,title:null,translate:null,type:null,typeMustMatch:It,useMap:null,value:ds,width:tt,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:On,axis:null,background:null,bgColor:null,border:tt,borderColor:null,bottomMargin:tt,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:It,declare:It,event:null,face:null,frame:null,frameBorder:null,hSpace:tt,leftMargin:tt,link:null,longDesc:null,lowSrc:null,marginHeight:tt,marginWidth:tt,noResize:It,noHref:It,noShade:It,noWrap:It,object:null,profile:null,prompt:null,rev:null,rightMargin:tt,rules:null,scheme:null,scrolling:ds,standby:null,summary:null,text:null,topMargin:tt,valueType:null,version:null,vAlign:null,vLink:null,vSpace:tt,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:It,disableRemotePlayback:It,prefix:null,property:null,results:tt,security:null,unselectable:null},space:"html",transform:TM}),xz=Cc({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:fa,accentHeight:tt,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:tt,amplitude:tt,arabicForm:null,ascent:tt,attributeName:null,attributeType:null,azimuth:tt,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:tt,by:null,calcMode:null,capHeight:tt,className:On,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:tt,diffuseConstant:tt,direction:null,display:null,dur:null,divisor:tt,dominantBaseline:null,download:It,dx:null,dy:null,edgeMode:null,editable:null,elevation:tt,enableBackground:null,end:null,event:null,exponent:tt,externalResourcesRequired:null,fill:null,fillOpacity:tt,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:oc,g2:oc,glyphName:oc,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:tt,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:tt,horizOriginX:tt,horizOriginY:tt,id:null,ideographic:tt,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:tt,k:tt,k1:tt,k2:tt,k3:tt,k4:tt,kernelMatrix:fa,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:tt,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:tt,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:tt,overlineThickness:tt,paintOrder:null,panose1:null,path:null,pathLength:tt,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:On,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:tt,pointsAtY:tt,pointsAtZ:tt,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:fa,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:fa,rev:fa,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:fa,requiredFeatures:fa,requiredFonts:fa,requiredFormats:fa,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:tt,specularExponent:tt,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:tt,strikethroughThickness:tt,string:null,stroke:null,strokeDashArray:fa,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:tt,strokeOpacity:tt,strokeWidth:null,style:null,surfaceScale:tt,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:fa,tabIndex:tt,tableValues:null,target:null,targetX:tt,targetY:tt,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:fa,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:tt,underlineThickness:tt,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:tt,values:null,vAlphabetic:tt,vMathematical:tt,vectorEffect:null,vHanging:tt,vIdeographic:tt,version:null,vertAdvY:tt,vertOriginX:tt,vertOriginY:tt,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:tt,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:MM}),EM=Cc({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()}}),_M=Cc({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:TM}),DM=Cc({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(s,e){return"xml:"+e.slice(3).toLowerCase()}}),vz={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"},wz=/[A-Z]/g,qj=/-[a-z]/g,kz=/^data[-\w.:]+$/i;function Sz(s,e){const t=jy(e);let n=e,a=sa;if(t in s.normal)return s.property[s.normal[t]];if(t.length>4&&t.slice(0,4)==="data"&&kz.test(e)){if(e.charAt(4)==="-"){const i=e.slice(5).replace(qj,Cz);n="data"+i.charAt(0).toUpperCase()+i.slice(1)}else{const i=e.slice(4);if(!qj.test(i)){let o=i.replace(wz,jz);o.charAt(0)!=="-"&&(o="-"+o),e="data"+o}}a=Cx}return new a(n,e)}function jz(s){return"-"+s.toLowerCase()}function Cz(s){return s.charAt(1).toUpperCase()}const Nz=NM([AM,yz,EM,_M,DM],"html"),Nx=NM([AM,xz,EM,_M,DM],"svg");function Az(s){return s.join(" ").trim()}var Hl={},rb,Yj;function Mz(){if(Yj)return rb;Yj=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=`
151
151
  `,d="/",m="*",p="",f="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 A(F){var $=F.match(e);$&&(j+=$.length);var U=F.lastIndexOf(c);C=~U?F.length-U:C+F.length}function D(){var F={line:j,column:C};return function($){return $.position=new M(F),_(),$}}function M(F){this.start=F,this.end={line:j,column:C},this.source=S.source}M.prototype.content=k;function I(F){var $=new Error(S.source+":"+j+":"+C+": "+F);if($.reason=F,$.filename=S.source,$.line=j,$.column=C,$.source=k,!S.silent)throw $}function E(F){var $=F.exec(k);if($){var U=$[0];return A(U),k=k.slice(U.length),$}}function _(){E(t)}function P(F){var $;for(F=F||[];$=L();)$!==!1&&F.push($);return F}function L(){var F=D();if(!(d!=k.charAt(0)||m!=k.charAt(1))){for(var $=2;p!=k.charAt($)&&(m!=k.charAt($)||d!=k.charAt($+1));)++$;if($+=2,p===k.charAt($-1))return I("End of comment missing");var U=k.slice(2,$-2);return C+=2,A(U),k=k.slice($),C+=2,F({type:f,comment:U})}}function R(){var F=D(),$=E(n);if($){if(L(),!E(a))return I("property missing ':'");var U=E(i),G=F({type:b,property:w($[0].replace(s,p)),value:U?w(U[0].replace(s,p)):p});return E(o),G}}function z(){var F=[];P(F);for(var $;$=R();)$!==!1&&(F.push($),P(F));return F}return _(),z()}function w(k){return k?k.replace(l,p):p}return rb=y,rb}var Vj;function Tz(){if(Vj)return Hl;Vj=1;var s=Hl&&Hl.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(Hl,"__esModule",{value:!0}),Hl.default=t;const e=s(Mz());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:m}=c;l?a(d,m,c):m&&(i=i||{},i[d]=m)}),i}return Hl}var Cu={},Kj;function Ez(){if(Kj)return Cu;Kj=1,Object.defineProperty(Cu,"__esModule",{value:!0}),Cu.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,m){return m.toUpperCase()},l=function(d,m){return"".concat(m,"-")},c=function(d,m){return m===void 0&&(m={}),i(d)?d:(d=d.toLowerCase(),m.reactCompat?d=d.replace(a,l):d=d.replace(n,l),d.replace(e,o))};return Cu.camelCase=c,Cu}var Nu,Xj;function _z(){if(Xj)return Nu;Xj=1;var s=Nu&&Nu.__importDefault||function(a){return a&&a.__esModule?a:{default:a}},e=s(Tz()),t=Ez();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,Nu=n,Nu}var Dz=_z();const Pz=ud(Dz),PM=RM("end"),Ax=RM("start");function RM(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 Rz(s){const e=Ax(s),t=PM(s);if(e&&t)return{start:e,end:t}}function Yu(s){return!s||typeof s!="object"?"":"position"in s||"type"in s?Zj(s.position):"start"in s||"end"in s?Zj(s):"line"in s||"column"in s?Ay(s):""}function Ay(s){return Qj(s&&s.line)+":"+Qj(s&&s.column)}function Zj(s){return Ay(s&&s.start)+"-"+Ay(s&&s.end)}function Qj(s){return s&&typeof s=="number"?s:1}class Ls 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=Yu(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}}Ls.prototype.file="";Ls.prototype.name="";Ls.prototype.reason="";Ls.prototype.message="";Ls.prototype.stack="";Ls.prototype.column=void 0;Ls.prototype.line=void 0;Ls.prototype.ancestors=void 0;Ls.prototype.cause=void 0;Ls.prototype.fatal=void 0;Ls.prototype.place=void 0;Ls.prototype.ruleId=void 0;Ls.prototype.source=void 0;const Mx={}.hasOwnProperty,Lz=new Map,Oz=/[A-Z]/g,Iz=new Set(["table","tbody","thead","tfoot","tr"]),Bz=new Set(["td","th"]),LM="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function Fz(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=Yz(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=qz(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"?Nx:Nz,stylePropertyNameCase:e.stylePropertyNameCase||"dom",tableCellAlignToStyle:e.tableCellAlignToStyle!==!1},i=OM(a,s,void 0);return i&&typeof i!="string"?i:a.create(s,a.Fragment,{children:i||void 0},void 0)}function OM(s,e,t){if(e.type==="element")return zz(s,e,t);if(e.type==="mdxFlowExpression"||e.type==="mdxTextExpression")return $z(s,e);if(e.type==="mdxJsxFlowElement"||e.type==="mdxJsxTextElement")return Uz(s,e,t);if(e.type==="mdxjsEsm")return Hz(s,e);if(e.type==="root")return Gz(s,e,t);if(e.type==="text")return Wz(s,e)}function zz(s,e,t){const n=s.schema;let a=n;e.tagName.toLowerCase()==="svg"&&n.space==="html"&&(a=Nx,s.schema=a),s.ancestors.push(e);const i=BM(s,e.tagName,!1),o=Vz(s,e);let l=Ex(s,e);return Iz.has(e.tagName)&&(l=l.filter(function(c){return typeof c=="string"?!gz(c):!0})),IM(s,o,i,e),Tx(o,l),s.ancestors.pop(),s.schema=n,s.create(e,i,o,t)}function $z(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)}ad(s,e.position)}function Hz(s,e){if(e.data&&e.data.estree&&s.evaluater)return s.evaluater.evaluateProgram(e.data.estree);ad(s,e.position)}function Uz(s,e,t){const n=s.schema;let a=n;e.name==="svg"&&n.space==="html"&&(a=Nx,s.schema=a),s.ancestors.push(e);const i=e.name===null?s.Fragment:BM(s,e.name,!0),o=Kz(s,e),l=Ex(s,e);return IM(s,o,i,e),Tx(o,l),s.ancestors.pop(),s.schema=n,s.create(e,i,o,t)}function Gz(s,e,t){const n={};return Tx(n,Ex(s,e)),s.create(e,s.Fragment,n,t)}function Wz(s,e){return e.value}function IM(s,e,t,n){typeof t!="string"&&t!==s.Fragment&&s.passNode&&(e.node=n)}function Tx(s,e){if(e.length>0){const t=e.length>1?e:e[0];t&&(s.children=t)}}function qz(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 Yz(s,e){return t;function t(n,a,i,o){const l=Array.isArray(i.children),c=Ax(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 Vz(s,e){const t={};let n,a;for(a in e.properties)if(a!=="children"&&Mx.call(e.properties,a)){const i=Xz(s,a,e.properties[a]);if(i){const[o,l]=i;s.tableCellAlignToStyle&&o==="align"&&typeof l=="string"&&Bz.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 Kz(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 ad(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 ad(s,e.position);else i=n.value===null?!0:n.value;t[a]=i}return t}function Ex(s,e){const t=[];let n=-1;const a=s.passKeys?new Map:Lz;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=OM(s,i,o);l!==void 0&&t.push(l)}return t}function Xz(s,e,t){const n=Sz(s.schema,e);if(!(t==null||typeof t=="number"&&Number.isNaN(t))){if(Array.isArray(t)&&(t=n.commaSeparated?dz(t):Az(t)),n.property==="style"){let a=typeof t=="object"?t:Zz(s,String(t));return s.stylePropertyNameCase==="css"&&(a=Qz(a)),["style",a]}return[s.elementAttributeNameCase==="react"&&n.space?vz[n.property]||n.property:n.attribute,t]}}function Zz(s,e){try{return Pz(e,{reactCompat:!0})}catch(t){if(s.ignoreInvalidStyle)return{};const n=t,a=new Ls("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=LM+"#cannot-parse-style-attribute",a}}function BM(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=Uj(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=Uj(e)&&!/^[a-z]/.test(e)?{type:"Identifier",name:e}:{type:"Literal",value:e};if(n.type==="Literal"){const a=n.value;return Mx.call(s.components,a)?s.components[a]:a}if(s.evaluater)return s.evaluater.evaluateExpression(n);ad(s)}function ad(s,e){const t=new Ls("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=LM+"#cannot-handle-mdx-estrees-without-createevaluater",t}function Qz(s){const e={};let t;for(t in s)Mx.call(s,t)&&(e[Jz(t)]=s[t]);return e}function Jz(s){let e=s.replace(Oz,e5);return e.slice(0,3)==="ms-"&&(e="-"+e),e}function e5(s){return"-"+s.toLowerCase()}const ob={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"]},t5={};function _x(s,e){const t=t5,n=typeof t.includeImageAlt=="boolean"?t.includeImageAlt:!0,a=typeof t.includeHtml=="boolean"?t.includeHtml:!0;return FM(s,n,a)}function FM(s,e,t){if(n5(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 Jj(s.children,e,t)}return Array.isArray(s)?Jj(s,e,t):""}function Jj(s,e,t){const n=[];let a=-1;for(;++a<s.length;)n[a]=FM(s[a],e,t);return n.join("")}function n5(s){return!!(s&&typeof s=="object")}const eC=document.createElement("i");function Dx(s){const e="&"+s+";";eC.innerHTML=e;const t=eC.textContent;return t.charCodeAt(t.length-1)===59&&s!=="semi"||t===e?!1:t}function va(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 Pa(s,e){return s.length>0?(va(s,s.length,0,e),s):e}const tC={}.hasOwnProperty;function zM(s){const e={};let t=-1;for(;++t<s.length;)s5(e,s[t]);return e}function s5(s,e){let t;for(t in e){const a=(tC.call(s,t)?s[t]:void 0)||(s[t]={}),i=e[t];let o;if(i)for(o in i){tC.call(a,o)||(a[o]=[]);const l=i[o];a5(a[o],Array.isArray(l)?l:l?[l]:[])}}}function a5(s,e){let t=-1;const n=[];for(;++t<e.length;)(e[t].add==="after"?s:n).push(e[t]);va(s,0,0,n)}function $M(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 Za(s){return s.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const $s=no(/[A-Za-z]/),Rs=no(/[\dA-Za-z]/),i5=no(/[#-'*+\--9=?A-Z^-~]/);function _p(s){return s!==null&&(s<32||s===127)}const My=no(/\d/),r5=no(/[\dA-Fa-f]/),o5=no(/[!-/:-@[-`{-~]/);function Ct(s){return s!==null&&s<-2}function Rn(s){return s!==null&&(s<0||s===32)}function Qt(s){return s===-2||s===-1||s===32}const hm=no(new RegExp("\\p{P}|\\p{S}","u")),el=no(/\s/);function no(s){return e;function e(t){return t!==null&&t>-1&&s.test(String.fromCharCode(t))}}function Nc(s){const e=[];let t=-1,n=0,a=0;for(;++t<s.length;){const i=s.charCodeAt(t);let o="";if(i===37&&Rs(s.charCodeAt(t+1))&&Rs(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 ln(s,e,t,n){const a=n?n-1:Number.POSITIVE_INFINITY;let i=0;return o;function o(c){return Qt(c)?(s.enter(t),l(c)):e(c)}function l(c){return Qt(c)&&i++<a?(s.consume(c),l):(s.exit(t),e(c))}}const l5={tokenize:c5};function c5(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"),ln(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 Ct(l)?(s.consume(l),s.exit("chunkText"),i):(s.consume(l),o)}}const u5={tokenize:d5},nC={tokenize:h5};function d5(s){const e=this,t=[];let n=0,a,i,o;return l;function l(C){if(n<t.length){const A=t[n];return e.containerState=A[1],s.attempt(A[0].continuation,c,d)(C)}return d(C)}function c(C){if(n++,e.containerState._closeFlow){e.containerState._closeFlow=void 0,a&&j();const A=e.events.length;let D=A,M;for(;D--;)if(e.events[D][0]==="exit"&&e.events[D][1].type==="chunkFlow"){M=e.events[D][1].end;break}S(n);let I=A;for(;I<e.events.length;)e.events[I][1].end={...M},I++;return va(e.events,D+1,0,e.events.slice(A)),e.events.length=I,d(C)}return l(C)}function d(C){if(n===t.length){if(!a)return f(C);if(a.currentConstruct&&a.currentConstruct.concrete)return y(C);e.interrupt=!!(a.currentConstruct&&!a._gfmTableDynamicInterruptHack)}return e.containerState={},s.check(nC,m,p)(C)}function m(C){return a&&j(),S(n),f(C)}function p(C){return e.parser.lazy[e.now().line]=n!==t.length,o=e.now().offset,y(C)}function f(C){return e.containerState={},s.attempt(nC,b,y)(C)}function b(C){return n++,t.push([e.currentConstruct,e.containerState]),f(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 Ct(C)?(s.consume(C),k(s.exit("chunkFlow")),n=0,e.interrupt=void 0,l):(s.consume(C),w)}function k(C,A){const D=e.sliceStream(C);if(A&&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 M=a.events.length;for(;M--;)if(a.events[M][1].start.offset<o&&(!a.events[M][1].end||a.events[M][1].end.offset>o))return;const I=e.events.length;let E=I,_,P;for(;E--;)if(e.events[E][0]==="exit"&&e.events[E][1].type==="chunkFlow"){if(_){P=e.events[E][1].end;break}_=!0}for(S(n),M=I;M<e.events.length;)e.events[M][1].end={...P},M++;va(e.events,E+1,0,e.events.slice(I)),e.events.length=M}}function S(C){let A=t.length;for(;A-- >C;){const D=t[A];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 h5(s,e,t){return ln(s,s.attempt(this.parser.constructs.document,e,t),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function mc(s){if(s===null||Rn(s)||el(s))return 1;if(hm(s))return 2}function pm(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 Ty={name:"attention",resolveAll:p5,tokenize:m5};function p5(s,e){let t=-1,n,a,i,o,l,c,d,m;for(;++t<s.length;)if(s[t][0]==="enter"&&s[t][1].type==="attentionSequence"&&s[t][1]._close){for(n=t;n--;)if(s[n][0]==="exit"&&s[n][1].type==="attentionSequence"&&s[n][1]._open&&e.sliceSerialize(s[n][1]).charCodeAt(0)===e.sliceSerialize(s[t][1]).charCodeAt(0)){if((s[n][1]._close||s[t][1]._open)&&(s[t][1].end.offset-s[t][1].start.offset)%3&&!((s[n][1].end.offset-s[n][1].start.offset+s[t][1].end.offset-s[t][1].start.offset)%3))continue;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},f={...s[t][1].start};sC(p,-c),sC(f,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:f},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=Pa(d,[["enter",s[n][1],e],["exit",s[n][1],e]])),d=Pa(d,[["enter",a,e],["enter",o,e],["exit",o,e],["enter",i,e]]),d=Pa(d,pm(e.parser.constructs.insideSpan.null,s.slice(n+1,t),e)),d=Pa(d,[["exit",i,e],["enter",l,e],["exit",l,e],["exit",a,e]]),s[t][1].end.offset-s[t][1].start.offset?(m=2,d=Pa(d,[["enter",s[t][1],e],["exit",s[t][1],e]])):m=0,va(s,n-1,t-n+3,d),t=n+d.length-m-2;break}}for(t=-1;++t<s.length;)s[t][1].type==="attentionSequence"&&(s[t][1].type="data");return s}function m5(s,e){const t=this.parser.constructs.attentionMarkers.null,n=this.previous,a=mc(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"),m=mc(c),p=!m||m===2&&a||t.includes(c),f=!a||a===2&&m||t.includes(n);return d._open=!!(i===42?p:p&&(a||!f)),d._close=!!(i===42?f:f&&(m||!p)),e(c)}}function sC(s,e){s.column+=e,s.offset+=e,s._bufferIndex+=e}const f5={name:"autolink",tokenize:g5};function g5(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 $s(b)?(s.consume(b),o):b===64?t(b):d(b)}function o(b){return b===43||b===45||b===46||Rs(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||Rs(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||_p(b)?t(b):(s.consume(b),c)}function d(b){return b===64?(s.consume(b),m):i5(b)?(s.consume(b),d):t(b)}function m(b){return Rs(b)?p(b):t(b)}function p(b){return b===46?(s.consume(b),n=0,m):b===62?(s.exit("autolinkProtocol").type="autolinkEmail",s.enter("autolinkMarker"),s.consume(b),s.exit("autolinkMarker"),s.exit("autolink"),e):f(b)}function f(b){if((b===45||Rs(b))&&n++<63){const y=b===45?f:p;return s.consume(b),y}return t(b)}}const bd={partial:!0,tokenize:b5};function b5(s,e,t){return n;function n(i){return Qt(i)?ln(s,a,"linePrefix")(i):a(i)}function a(i){return i===null||Ct(i)?e(i):t(i)}}const HM={continuation:{tokenize:x5},exit:v5,name:"blockQuote",tokenize:y5};function y5(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 Qt(o)?(s.enter("blockQuotePrefixWhitespace"),s.consume(o),s.exit("blockQuotePrefixWhitespace"),s.exit("blockQuotePrefix"),e):(s.exit("blockQuotePrefix"),e(o))}}function x5(s,e,t){const n=this;return a;function a(o){return Qt(o)?ln(s,i,"linePrefix",n.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(o):i(o)}function i(o){return s.attempt(HM,e,t)(o)}}function v5(s){s.exit("blockQuote")}const UM={name:"characterEscape",tokenize:w5};function w5(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 o5(i)?(s.enter("characterEscapeValue"),s.consume(i),s.exit("characterEscapeValue"),s.exit("characterEscape"),e):t(i)}}const GM={name:"characterReference",tokenize:k5};function k5(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=Rs,m(p))}function d(p){return p===88||p===120?(s.enter("characterReferenceMarkerHexadecimal"),s.consume(p),s.exit("characterReferenceMarkerHexadecimal"),s.enter("characterReferenceValue"),i=6,o=r5,m):(s.enter("characterReferenceValue"),i=7,o=My,m(p))}function m(p){if(p===59&&a){const f=s.exit("characterReferenceValue");return o===Rs&&!Dx(n.sliceSerialize(f))?t(p):(s.enter("characterReferenceMarker"),s.consume(p),s.exit("characterReferenceMarker"),s.exit("characterReference"),e)}return o(p)&&a++<i?(s.consume(p),m):t(p)}}const aC={partial:!0,tokenize:j5},iC={concrete:!0,name:"codeFenced",tokenize:S5};function S5(s,e,t){const n=this,a={partial:!0,tokenize:D};let i=0,o=0,l;return c;function c(M){return d(M)}function d(M){const I=n.events[n.events.length-1];return i=I&&I[1].type==="linePrefix"?I[2].sliceSerialize(I[1],!0).length:0,l=M,s.enter("codeFenced"),s.enter("codeFencedFence"),s.enter("codeFencedFenceSequence"),m(M)}function m(M){return M===l?(o++,s.consume(M),m):o<3?t(M):(s.exit("codeFencedFenceSequence"),Qt(M)?ln(s,p,"whitespace")(M):p(M))}function p(M){return M===null||Ct(M)?(s.exit("codeFencedFence"),n.interrupt?e(M):s.check(aC,w,A)(M)):(s.enter("codeFencedFenceInfo"),s.enter("chunkString",{contentType:"string"}),f(M))}function f(M){return M===null||Ct(M)?(s.exit("chunkString"),s.exit("codeFencedFenceInfo"),p(M)):Qt(M)?(s.exit("chunkString"),s.exit("codeFencedFenceInfo"),ln(s,b,"whitespace")(M)):M===96&&M===l?t(M):(s.consume(M),f)}function b(M){return M===null||Ct(M)?p(M):(s.enter("codeFencedFenceMeta"),s.enter("chunkString",{contentType:"string"}),y(M))}function y(M){return M===null||Ct(M)?(s.exit("chunkString"),s.exit("codeFencedFenceMeta"),p(M)):M===96&&M===l?t(M):(s.consume(M),y)}function w(M){return s.attempt(a,A,k)(M)}function k(M){return s.enter("lineEnding"),s.consume(M),s.exit("lineEnding"),S}function S(M){return i>0&&Qt(M)?ln(s,j,"linePrefix",i+1)(M):j(M)}function j(M){return M===null||Ct(M)?s.check(aC,w,A)(M):(s.enter("codeFlowValue"),C(M))}function C(M){return M===null||Ct(M)?(s.exit("codeFlowValue"),j(M)):(s.consume(M),C)}function A(M){return s.exit("codeFenced"),e(M)}function D(M,I,E){let _=0;return P;function P($){return M.enter("lineEnding"),M.consume($),M.exit("lineEnding"),L}function L($){return M.enter("codeFencedFence"),Qt($)?ln(M,R,"linePrefix",n.parser.constructs.disable.null.includes("codeIndented")?void 0:4)($):R($)}function R($){return $===l?(M.enter("codeFencedFenceSequence"),z($)):E($)}function z($){return $===l?(_++,M.consume($),z):_>=o?(M.exit("codeFencedFenceSequence"),Qt($)?ln(M,F,"whitespace")($):F($)):E($)}function F($){return $===null||Ct($)?(M.exit("codeFencedFence"),I($)):E($)}}}function j5(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 lb={name:"codeIndented",tokenize:N5},C5={partial:!0,tokenize:A5};function N5(s,e,t){const n=this;return a;function a(d){return s.enter("codeIndented"),ln(s,i,"linePrefix",5)(d)}function i(d){const m=n.events[n.events.length-1];return m&&m[1].type==="linePrefix"&&m[2].sliceSerialize(m[1],!0).length>=4?o(d):t(d)}function o(d){return d===null?c(d):Ct(d)?s.attempt(C5,o,c)(d):(s.enter("codeFlowValue"),l(d))}function l(d){return d===null||Ct(d)?(s.exit("codeFlowValue"),o(d)):(s.consume(d),l)}function c(d){return s.exit("codeIndented"),e(d)}}function A5(s,e,t){const n=this;return a;function a(o){return n.parser.lazy[n.now().line]?t(o):Ct(o)?(s.enter("lineEnding"),s.consume(o),s.exit("lineEnding"),a):ln(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):Ct(o)?a(o):t(o)}}const M5={name:"codeText",previous:E5,resolve:T5,tokenize:_5};function T5(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 E5(s){return s!==96||this.events[this.events.length-1][1].type==="characterEscape"}function _5(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,m(p)):Ct(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||Ct(p)?(s.exit("codeTextData"),c(p)):(s.consume(p),d)}function m(p){return p===96?(s.consume(p),a++,m):a===n?(s.exit("codeTextSequence"),s.exit("codeText"),e(p)):(i.type="codeTextData",d(p))}}class D5{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&&Au(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),Au(this.left,e)}unshift(e){this.setCursor(0),this.right.push(e)}unshiftMany(e){this.setCursor(0),Au(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);Au(this.right,t.reverse())}else{const t=this.right.splice(this.left.length+this.right.length-e,Number.POSITIVE_INFINITY);Au(this.left,t.reverse())}}}function Au(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 WM(s){const e={};let t=-1,n,a,i,o,l,c,d;const m=new D5(s);for(;++t<m.length;){for(;t in e;)t=e[t];if(n=m.get(t),t&&n[1].type==="chunkFlow"&&m.get(t-1)[1].type==="listItemPrefix"&&(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,P5(m,t)),t=e[t],d=!0);else if(n[1]._container){for(i=t,a=void 0;i--;)if(o=m.get(i),o[1].type==="lineEnding"||o[1].type==="lineEndingBlank")o[0]==="enter"&&(a&&(m.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={...m.get(a)[1].start},l=m.slice(a,t),l.unshift(n),m.splice(a,t-a+1,l))}}return va(s,0,Number.POSITIVE_INFINITY,m.slice(0)),!d}function P5(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 m,p,f=-1,b=t,y=0,w=0;const k=[w];for(;b;){for(;s.get(++a)[1]!==b;);i.push(a),b._tokenizer||(m=n.sliceStream(b),b.next||m.push(null),p&&o.defineSkip(b.start),b._isInFirstContentOfListItem&&(o._gfmTasklistFirstContentOfListItem=!0),o.write(m),b._isInFirstContentOfListItem&&(o._gfmTasklistFirstContentOfListItem=void 0)),p=b,b=b.next}for(b=t;++f<l.length;)l[f][0]==="exit"&&l[f-1][0]==="enter"&&l[f][1].type===l[f-1][1].type&&l[f][1].start.line!==l[f][1].end.line&&(w=f+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(),f=k.length;f--;){const S=l.slice(k[f],k[f+1]),j=i.pop();c.push([j,j+S.length-1]),s.splice(j,2,S)}for(c.reverse(),f=-1;++f<c.length;)d[y+c[f][0]]=y+c[f][1],y+=c[f][1]-c[f][0]-1;return d}const R5={resolve:O5,tokenize:I5},L5={partial:!0,tokenize:B5};function O5(s){return WM(s),s}function I5(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):Ct(l)?s.check(L5,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 B5(s,e,t){const n=this;return a;function a(o){return s.exit("chunkContent"),s.enter("lineEnding"),s.consume(o),s.exit("lineEnding"),ln(s,i,"linePrefix")}function i(o){if(o===null||Ct(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 qM(s,e,t,n,a,i,o,l,c){const d=c||Number.POSITIVE_INFINITY;let m=0;return p;function p(S){return S===60?(s.enter(n),s.enter(a),s.enter(i),s.consume(S),s.exit(i),f):S===null||S===32||S===41||_p(S)?t(S):(s.enter(n),s.enter(o),s.enter(l),s.enter("chunkString",{contentType:"string"}),w(S))}function f(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),f(S)):S===null||S===60||Ct(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!m&&(S===null||S===41||Rn(S))?(s.exit("chunkString"),s.exit(l),s.exit(o),s.exit(n),e(S)):m<d&&S===40?(s.consume(S),m++,w):S===41?(s.consume(S),m--,w):S===null||S===32||S===40||_p(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 YM(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),m}function m(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):Ct(b)?(s.enter("lineEnding"),s.consume(b),s.exit("lineEnding"),m):(s.enter("chunkString",{contentType:"string"}),p(b))}function p(b){return b===null||b===91||b===93||Ct(b)||l++>999?(s.exit("chunkString"),m(b)):(s.consume(b),c||(c=!Qt(b)),b===92?f:p)}function f(b){return b===91||b===92||b===93?(s.consume(b),l++,p):p(b)}}function VM(s,e,t,n,a,i){let o;return l;function l(f){return f===34||f===39||f===40?(s.enter(n),s.enter(a),s.consume(f),s.exit(a),o=f===40?41:f,c):t(f)}function c(f){return f===o?(s.enter(a),s.consume(f),s.exit(a),s.exit(n),e):(s.enter(i),d(f))}function d(f){return f===o?(s.exit(i),c(o)):f===null?t(f):Ct(f)?(s.enter("lineEnding"),s.consume(f),s.exit("lineEnding"),ln(s,d,"linePrefix")):(s.enter("chunkString",{contentType:"string"}),m(f))}function m(f){return f===o||f===null||Ct(f)?(s.exit("chunkString"),d(f)):(s.consume(f),f===92?p:m)}function p(f){return f===o||f===92?(s.consume(f),m):m(f)}}function Vu(s,e){let t;return n;function n(a){return Ct(a)?(s.enter("lineEnding"),s.consume(a),s.exit("lineEnding"),t=!0,n):Qt(a)?ln(s,n,t?"linePrefix":"lineSuffix")(a):e(a)}}const F5={name:"definition",tokenize:$5},z5={partial:!0,tokenize:H5};function $5(s,e,t){const n=this;let a;return i;function i(b){return s.enter("definition"),o(b)}function o(b){return YM.call(n,s,l,t,"definitionLabel","definitionLabelMarker","definitionLabelString")(b)}function l(b){return a=Za(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 Rn(b)?Vu(s,d)(b):d(b)}function d(b){return qM(s,m,t,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(b)}function m(b){return s.attempt(z5,p,p)(b)}function p(b){return Qt(b)?ln(s,f,"whitespace")(b):f(b)}function f(b){return b===null||Ct(b)?(s.exit("definition"),n.parser.defined.push(a),e(b)):t(b)}}function H5(s,e,t){return n;function n(l){return Rn(l)?Vu(s,a)(l):t(l)}function a(l){return VM(s,i,t,"definitionTitle","definitionTitleMarker","definitionTitleString")(l)}function i(l){return Qt(l)?ln(s,o,"whitespace")(l):o(l)}function o(l){return l===null||Ct(l)?e(l):t(l)}}const U5={name:"hardBreakEscape",tokenize:G5};function G5(s,e,t){return n;function n(i){return s.enter("hardBreakEscape"),s.consume(i),a}function a(i){return Ct(i)?(s.exit("hardBreakEscape"),e(i)):t(i)}}const W5={name:"headingAtx",resolve:q5,tokenize:Y5};function q5(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"},va(s,n,t-n+1,[["enter",a,e],["enter",i,e],["exit",i,e],["exit",a,e]])),s}function Y5(s,e,t){let n=0;return a;function a(m){return s.enter("atxHeading"),i(m)}function i(m){return s.enter("atxHeadingSequence"),o(m)}function o(m){return m===35&&n++<6?(s.consume(m),o):m===null||Rn(m)?(s.exit("atxHeadingSequence"),l(m)):t(m)}function l(m){return m===35?(s.enter("atxHeadingSequence"),c(m)):m===null||Ct(m)?(s.exit("atxHeading"),e(m)):Qt(m)?ln(s,l,"whitespace")(m):(s.enter("atxHeadingText"),d(m))}function c(m){return m===35?(s.consume(m),c):(s.exit("atxHeadingSequence"),l(m))}function d(m){return m===null||m===35||Rn(m)?(s.exit("atxHeadingText"),l(m)):(s.consume(m),d)}}const V5=["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"],rC=["pre","script","style","textarea"],K5={concrete:!0,name:"htmlFlow",resolveTo:Q5,tokenize:J5},X5={partial:!0,tokenize:t3},Z5={partial:!0,tokenize:e3};function Q5(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 J5(s,e,t){const n=this;let a,i,o,l,c;return d;function d(O){return m(O)}function m(O){return s.enter("htmlFlow"),s.enter("htmlFlowData"),s.consume(O),p}function p(O){return O===33?(s.consume(O),f):O===47?(s.consume(O),i=!0,w):O===63?(s.consume(O),a=3,n.interrupt?e:B):$s(O)?(s.consume(O),o=String.fromCharCode(O),k):t(O)}function f(O){return O===45?(s.consume(O),a=2,b):O===91?(s.consume(O),a=5,l=0,y):$s(O)?(s.consume(O),a=4,n.interrupt?e:B):t(O)}function b(O){return O===45?(s.consume(O),n.interrupt?e:B):t(O)}function y(O){const Y="CDATA[";return O===Y.charCodeAt(l++)?(s.consume(O),l===Y.length?n.interrupt?e:R:y):t(O)}function w(O){return $s(O)?(s.consume(O),o=String.fromCharCode(O),k):t(O)}function k(O){if(O===null||O===47||O===62||Rn(O)){const Y=O===47,Q=o.toLowerCase();return!Y&&!i&&rC.includes(Q)?(a=1,n.interrupt?e(O):R(O)):V5.includes(o.toLowerCase())?(a=6,Y?(s.consume(O),S):n.interrupt?e(O):R(O)):(a=7,n.interrupt&&!n.parser.lazy[n.now().line]?t(O):i?j(O):C(O))}return O===45||Rs(O)?(s.consume(O),o+=String.fromCharCode(O),k):t(O)}function S(O){return O===62?(s.consume(O),n.interrupt?e:R):t(O)}function j(O){return Qt(O)?(s.consume(O),j):P(O)}function C(O){return O===47?(s.consume(O),P):O===58||O===95||$s(O)?(s.consume(O),A):Qt(O)?(s.consume(O),C):P(O)}function A(O){return O===45||O===46||O===58||O===95||Rs(O)?(s.consume(O),A):D(O)}function D(O){return O===61?(s.consume(O),M):Qt(O)?(s.consume(O),D):C(O)}function M(O){return O===null||O===60||O===61||O===62||O===96?t(O):O===34||O===39?(s.consume(O),c=O,I):Qt(O)?(s.consume(O),M):E(O)}function I(O){return O===c?(s.consume(O),c=null,_):O===null||Ct(O)?t(O):(s.consume(O),I)}function E(O){return O===null||O===34||O===39||O===47||O===60||O===61||O===62||O===96||Rn(O)?D(O):(s.consume(O),E)}function _(O){return O===47||O===62||Qt(O)?C(O):t(O)}function P(O){return O===62?(s.consume(O),L):t(O)}function L(O){return O===null||Ct(O)?R(O):Qt(O)?(s.consume(O),L):t(O)}function R(O){return O===45&&a===2?(s.consume(O),U):O===60&&a===1?(s.consume(O),G):O===62&&a===4?(s.consume(O),ee):O===63&&a===3?(s.consume(O),B):O===93&&a===5?(s.consume(O),Z):Ct(O)&&(a===6||a===7)?(s.exit("htmlFlowData"),s.check(X5,se,z)(O)):O===null||Ct(O)?(s.exit("htmlFlowData"),z(O)):(s.consume(O),R)}function z(O){return s.check(Z5,F,se)(O)}function F(O){return s.enter("lineEnding"),s.consume(O),s.exit("lineEnding"),$}function $(O){return O===null||Ct(O)?z(O):(s.enter("htmlFlowData"),R(O))}function U(O){return O===45?(s.consume(O),B):R(O)}function G(O){return O===47?(s.consume(O),o="",K):R(O)}function K(O){if(O===62){const Y=o.toLowerCase();return rC.includes(Y)?(s.consume(O),ee):R(O)}return $s(O)&&o.length<8?(s.consume(O),o+=String.fromCharCode(O),K):R(O)}function Z(O){return O===93?(s.consume(O),B):R(O)}function B(O){return O===62?(s.consume(O),ee):O===45&&a===2?(s.consume(O),B):R(O)}function ee(O){return O===null||Ct(O)?(s.exit("htmlFlowData"),se(O)):(s.consume(O),ee)}function se(O){return s.exit("htmlFlow"),e(O)}}function e3(s,e,t){const n=this;return a;function a(o){return Ct(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 t3(s,e,t){return n;function n(a){return s.enter("lineEnding"),s.consume(a),s.exit("lineEnding"),s.attempt(bd,e,t)}}const n3={name:"htmlText",tokenize:s3};function s3(s,e,t){const n=this;let a,i,o;return l;function l(B){return s.enter("htmlText"),s.enter("htmlTextData"),s.consume(B),c}function c(B){return B===33?(s.consume(B),d):B===47?(s.consume(B),D):B===63?(s.consume(B),C):$s(B)?(s.consume(B),E):t(B)}function d(B){return B===45?(s.consume(B),m):B===91?(s.consume(B),i=0,y):$s(B)?(s.consume(B),j):t(B)}function m(B){return B===45?(s.consume(B),b):t(B)}function p(B){return B===null?t(B):B===45?(s.consume(B),f):Ct(B)?(o=p,G(B)):(s.consume(B),p)}function f(B){return B===45?(s.consume(B),b):p(B)}function b(B){return B===62?U(B):B===45?f(B):p(B)}function y(B){const ee="CDATA[";return B===ee.charCodeAt(i++)?(s.consume(B),i===ee.length?w:y):t(B)}function w(B){return B===null?t(B):B===93?(s.consume(B),k):Ct(B)?(o=w,G(B)):(s.consume(B),w)}function k(B){return B===93?(s.consume(B),S):w(B)}function S(B){return B===62?U(B):B===93?(s.consume(B),S):w(B)}function j(B){return B===null||B===62?U(B):Ct(B)?(o=j,G(B)):(s.consume(B),j)}function C(B){return B===null?t(B):B===63?(s.consume(B),A):Ct(B)?(o=C,G(B)):(s.consume(B),C)}function A(B){return B===62?U(B):C(B)}function D(B){return $s(B)?(s.consume(B),M):t(B)}function M(B){return B===45||Rs(B)?(s.consume(B),M):I(B)}function I(B){return Ct(B)?(o=I,G(B)):Qt(B)?(s.consume(B),I):U(B)}function E(B){return B===45||Rs(B)?(s.consume(B),E):B===47||B===62||Rn(B)?_(B):t(B)}function _(B){return B===47?(s.consume(B),U):B===58||B===95||$s(B)?(s.consume(B),P):Ct(B)?(o=_,G(B)):Qt(B)?(s.consume(B),_):U(B)}function P(B){return B===45||B===46||B===58||B===95||Rs(B)?(s.consume(B),P):L(B)}function L(B){return B===61?(s.consume(B),R):Ct(B)?(o=L,G(B)):Qt(B)?(s.consume(B),L):_(B)}function R(B){return B===null||B===60||B===61||B===62||B===96?t(B):B===34||B===39?(s.consume(B),a=B,z):Ct(B)?(o=R,G(B)):Qt(B)?(s.consume(B),R):(s.consume(B),F)}function z(B){return B===a?(s.consume(B),a=void 0,$):B===null?t(B):Ct(B)?(o=z,G(B)):(s.consume(B),z)}function F(B){return B===null||B===34||B===39||B===60||B===61||B===96?t(B):B===47||B===62||Rn(B)?_(B):(s.consume(B),F)}function $(B){return B===47||B===62||Rn(B)?_(B):t(B)}function U(B){return B===62?(s.consume(B),s.exit("htmlTextData"),s.exit("htmlText"),e):t(B)}function G(B){return s.exit("htmlTextData"),s.enter("lineEnding"),s.consume(B),s.exit("lineEnding"),K}function K(B){return Qt(B)?ln(s,Z,"linePrefix",n.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(B):Z(B)}function Z(B){return s.enter("htmlTextData"),o(B)}}const Px={name:"labelEnd",resolveAll:o3,resolveTo:l3,tokenize:c3},a3={tokenize:u3},i3={tokenize:d3},r3={tokenize:h3};function o3(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&&va(s,0,s.length,t),s}function l3(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}},m={type:"labelText",start:{...s[i+n+2][1].end},end:{...s[o-2][1].start}};return l=[["enter",c,e],["enter",d,e]],l=Pa(l,s.slice(i+1,i+n+3)),l=Pa(l,[["enter",m,e]]),l=Pa(l,pm(e.parser.constructs.insideSpan.null,s.slice(i+n+4,o-3),e)),l=Pa(l,[["exit",m,e],s[o-2],s[o-1],["exit",d,e]]),l=Pa(l,s.slice(o+1)),l=Pa(l,[["exit",c,e]]),va(s,i,s.length,l),s}function c3(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(f){return i?i._inactive?p(f):(o=n.parser.defined.includes(Za(n.sliceSerialize({start:i.end,end:n.now()}))),s.enter("labelEnd"),s.enter("labelMarker"),s.consume(f),s.exit("labelMarker"),s.exit("labelEnd"),c):t(f)}function c(f){return f===40?s.attempt(a3,m,o?m:p)(f):f===91?s.attempt(i3,m,o?d:p)(f):o?m(f):p(f)}function d(f){return s.attempt(r3,m,p)(f)}function m(f){return e(f)}function p(f){return i._balanced=!0,t(f)}}function u3(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 Rn(p)?Vu(s,i)(p):i(p)}function i(p){return p===41?m(p):qM(s,o,l,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(p)}function o(p){return Rn(p)?Vu(s,c)(p):m(p)}function l(p){return t(p)}function c(p){return p===34||p===39||p===40?VM(s,d,t,"resourceTitle","resourceTitleMarker","resourceTitleString")(p):m(p)}function d(p){return Rn(p)?Vu(s,m)(p):m(p)}function m(p){return p===41?(s.enter("resourceMarker"),s.consume(p),s.exit("resourceMarker"),s.exit("resource"),e):t(p)}}function d3(s,e,t){const n=this;return a;function a(l){return YM.call(n,s,i,o,"reference","referenceMarker","referenceString")(l)}function i(l){return n.parser.defined.includes(Za(n.sliceSerialize(n.events[n.events.length-1][1]).slice(1,-1)))?e(l):t(l)}function o(l){return t(l)}}function h3(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 p3={name:"labelStartImage",resolveAll:Px.resolveAll,tokenize:m3};function m3(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 f3={name:"labelStartLink",resolveAll:Px.resolveAll,tokenize:g3};function g3(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 cb={name:"lineEnding",tokenize:b3};function b3(s,e){return t;function t(n){return s.enter("lineEnding"),s.consume(n),s.exit("lineEnding"),ln(s,e,"linePrefix")}}const lp={name:"thematicBreak",tokenize:y3};function y3(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||Ct(d))?(s.exit("thematicBreak"),e(d)):t(d)}function c(d){return d===a?(s.consume(d),n++,c):(s.exit("thematicBreakSequence"),Qt(d)?ln(s,l,"whitespace")(d):l(d))}}const Zs={continuation:{tokenize:k3},exit:j3,name:"list",tokenize:w3},x3={partial:!0,tokenize:C3},v3={partial:!0,tokenize:S3};function w3(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:My(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(lp,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 My(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(bd,n.interrupt?t:m,s.attempt(x3,f,p))}function m(b){return n.containerState.initialBlankLine=!0,i++,f(b)}function p(b){return Qt(b)?(s.enter("listItemPrefixWhitespace"),s.consume(b),s.exit("listItemPrefixWhitespace"),f):t(b)}function f(b){return n.containerState.size=i+n.sliceSerialize(s.exit("listItemPrefix"),!0).length,e(b)}}function k3(s,e,t){const n=this;return n.containerState._closeFlow=void 0,s.check(bd,a,i);function a(l){return n.containerState.furtherBlankLines=n.containerState.furtherBlankLines||n.containerState.initialBlankLine,ln(s,e,"listItemIndent",n.containerState.size+1)(l)}function i(l){return n.containerState.furtherBlankLines||!Qt(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(v3,e,o)(l))}function o(l){return n.containerState._closeFlow=!0,n.interrupt=void 0,ln(s,s.attempt(Zs,e,t),"linePrefix",n.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(l)}}function S3(s,e,t){const n=this;return ln(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 j3(s){s.exit(this.containerState.type)}function C3(s,e,t){const n=this;return ln(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!Qt(i)&&o&&o[1].type==="listItemPrefixWhitespace"?e(i):t(i)}}const oC={name:"setextUnderline",resolveTo:N3,tokenize:A3};function N3(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 A3(s,e,t){const n=this;let a;return i;function i(d){let m=n.events.length,p;for(;m--;)if(n.events[m][1].type!=="lineEnding"&&n.events[m][1].type!=="linePrefix"&&n.events[m][1].type!=="content"){p=n.events[m][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"),Qt(d)?ln(s,c,"lineSuffix")(d):c(d))}function c(d){return d===null||Ct(d)?(s.exit("setextHeadingLine"),e(d)):t(d)}}const M3={tokenize:T3};function T3(s){const e=this,t=s.attempt(bd,n,s.attempt(this.parser.constructs.flowInitial,a,ln(s,s.attempt(this.parser.constructs.flow,a,s.attempt(R5,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 E3={resolveAll:XM()},_3=KM("string"),D3=KM("text");function KM(s){return{resolveAll:XM(s==="text"?P3: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(m){return d(m)?i(m):l(m)}function l(m){if(m===null){t.consume(m);return}return t.enter("data"),t.consume(m),c}function c(m){return d(m)?(t.exit("data"),i(m)):(t.consume(m),c)}function d(m){if(m===null)return!0;const p=a[m];let f=-1;if(p)for(;++f<p.length;){const b=p[f];if(!b.previous||b.previous.call(n,n.previous))return!0}return!1}}}function XM(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 P3(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 R3={42:Zs,43:Zs,45:Zs,48:Zs,49:Zs,50:Zs,51:Zs,52:Zs,53:Zs,54:Zs,55:Zs,56:Zs,57:Zs,62:HM},L3={91:F5},O3={[-2]:lb,[-1]:lb,32:lb},I3={35:W5,42:lp,45:[oC,lp],60:K5,61:oC,95:lp,96:iC,126:iC},B3={38:GM,92:UM},F3={[-5]:cb,[-4]:cb,[-3]:cb,33:p3,38:GM,42:Ty,60:[f5,n3],91:f3,92:[U5,UM],93:Px,95:Ty,96:M5},z3={null:[Ty,E3]},$3={null:[42,95]},H3={null:[]},U3=Object.freeze(Object.defineProperty({__proto__:null,attentionMarkers:$3,contentInitial:L3,disable:H3,document:R3,flow:I3,flowInitial:O3,insideSpan:z3,string:B3,text:F3},Symbol.toStringTag,{value:"Module"}));function G3(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:I(D),check:I(M),consume:j,enter:C,exit:A,interrupt:I(M,{interrupt:!0})},d={code:null,containerState:{},defineSkip:w,events:[],now:y,parser:s,previous:null,sliceSerialize:f,sliceStream:b,write:p};let m=e.tokenize.call(d,c);return e.resolveAll&&i.push(e),d;function p(L){return o=Pa(o,L),k(),o[o.length-1]!==null?[]:(E(e,0),d.events=pm(i,d.events,d),d.events)}function f(L,R){return q3(b(L),R)}function b(L){return W3(o,L)}function y(){const{_bufferIndex:L,_index:R,line:z,column:F,offset:$}=n;return{_bufferIndex:L,_index:R,line:z,column:F,offset:$}}function w(L){a[L.line]=L.column,P()}function k(){let L;for(;n._index<o.length;){const R=o[n._index];if(typeof R=="string")for(L=n._index,n._bufferIndex<0&&(n._bufferIndex=0);n._index===L&&n._bufferIndex<R.length;)S(R.charCodeAt(n._bufferIndex));else S(R)}}function S(L){m=m(L)}function j(L){Ct(L)?(n.line++,n.column=1,n.offset+=L===-3?2:1,P()):L!==-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=L}function C(L,R){const z=R||{};return z.type=L,z.start=y(),d.events.push(["enter",z,d]),l.push(z),z}function A(L){const R=l.pop();return R.end=y(),d.events.push(["exit",R,d]),R}function D(L,R){E(L,R.from)}function M(L,R){R.restore()}function I(L,R){return z;function z(F,$,U){let G,K,Z,B;return Array.isArray(F)?se(F):"tokenize"in F?se([F]):ee(F);function ee(ie){return J;function J(re){const V=re!==null&&ie[re],ne=re!==null&&ie.null,de=[...Array.isArray(V)?V:V?[V]:[],...Array.isArray(ne)?ne:ne?[ne]:[]];return se(de)(re)}}function se(ie){return G=ie,K=0,ie.length===0?U:O(ie[K])}function O(ie){return J;function J(re){return B=_(),Z=ie,ie.partial||(d.currentConstruct=ie),ie.name&&d.parser.constructs.disable.null.includes(ie.name)?Q():ie.tokenize.call(R?Object.assign(Object.create(d),R):d,c,Y,Q)(re)}}function Y(ie){return L(Z,B),$}function Q(ie){return B.restore(),++K<G.length?O(G[K]):U}}}function E(L,R){L.resolveAll&&!i.includes(L)&&i.push(L),L.resolve&&va(d.events,R,d.events.length-R,L.resolve(d.events.slice(R),d)),L.resolveTo&&(d.events=L.resolveTo(d.events,d))}function _(){const L=y(),R=d.previous,z=d.currentConstruct,F=d.events.length,$=Array.from(l);return{from:F,restore:U};function U(){n=L,d.previous=R,d.currentConstruct=z,d.events.length=F,l=$,P()}}function P(){n.line in a&&n.column<2&&(n.column=a[n.line],n.offset+=a[n.line]-1)}}function W3(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 q3(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=`
@@ -228,7 +228,7 @@ ${ce}`:X=ce}H.sendCommand(e,X),a(""),o(!1),w(new Map),d([]),k(),window.innerWidt
228
228
  `),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]})]}),f&&r.jsxs("div",{className:`aop-last-message ${f.isUserPrompt?"user":"assistant"}`,title:f.text.split(`
229
229
  `)[0],children:[r.jsx("span",{className:"lm-prefix",children:f.isUserPrompt?"▶":"◀"}),r.jsx("span",{className:"lm-text",children:m1(f.text,80)}),r.jsx("span",{className:"lm-time",children:Cp(f.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:m1(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,A;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||((A=k.toolInput.prompt)==null?void 0:A.slice(0,50)))||"";return r.jsxs("div",{className:"aop-timeline-entry",children:[r.jsx("span",{className:"tl-time",children:Cp(k.timestamp)}),r.jsx("span",{className:"tl-icon",children:Vn[k.toolName]||Vn.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 tH({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}=Ue(["tools"]),m={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,f=()=>{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:m[s.status]}),r.jsx("span",{className:"agent-progress-elapsed",children:f()}),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(nH,{output:s.output,agentId:s.agentId,maxHeight:200})})]})]})}function nH({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=Ux({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(vm,{output:o,agentId:e},`progress-${l}`))})}const sH={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"}},eE={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"}},aH={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"}},iH={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"}},rH={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"}},oH={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"}},lH={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"}},cH={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"}},uH={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"}},dH={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"}},hH={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"}},pH={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"}},mH={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"}},fH={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"}},gH={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"}},ga=[gH,hH,sH,eE,aH,iH,rH,oH,lH,cH,uH,dH,pH,mH,fH];function Xu(s){return ga.find(e=>e.id===s)||eE}const bH="classic";function Fp(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 Xx(){try{const s=localStorage.getItem("tide-theme");if(s&&ga.some(e=>e.id===s))return s}catch{}return bH}function yH(){const s=Xx(),e=Xu(s);Fp(e)}function xH(){const{t:s}=Ue(["terminal"]),[e,t]=x.useState(!1),[n,a]=x.useState(()=>Xx()),[i,o]=x.useState(-1),l=x.useRef(null),c=x.useRef(null),d=ga.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 m=y=>{const w=y==="next"?(d+1)%ga.length:(d-1+ga.length)%ga.length,k=ga[w],S=Xu(k.id);Fp(S),a(k.id)},p=y=>{e||(y.key==="ArrowUp"||y.key==="ArrowLeft"?(y.preventDefault(),m("prev")):y.key==="ArrowDown"||y.key==="ArrowRight"?(y.preventDefault(),m("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)%ga.length)):w.key==="ArrowUp"?(w.preventDefault(),o(j=>(j-1+ga.length)%ga.length)):w.key==="Enter"&&i>=0&&(w.preventDefault(),f(ga[i].id),(S=c.current)==null||S.focus())};return document.addEventListener("keydown",y),()=>document.removeEventListener("keydown",y)},[e,i]);const f=y=>{const w=Xu(y);Fp(w),a(y),t(!1)},b=Xu(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:ga.map((y,w)=>r.jsxs("button",{className:`theme-selector-option ${y.id===n?"active":""} ${w===i?"highlighted":""}`,onClick:k=>{k.stopPropagation(),f(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 f1=1e4,vH=3e4,g1=12e4;function Nb(s){const e=Wx(s);return qx(e.userMessage).userMessage.trim().replace(/\r\n/g,`
230
230
  `)}function Vh(s){return s.trim().replace(/\r\n/g,`
231
- `)}function wH(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 kH({onSaveSnapshot:s}={}){var Xe,ot,on,Nn,Jt;const{t:e}=Ue(["terminal","common"]),t=lr(),n=uM(),a=mM(),i=xx(),o=kx(),l=fM(),c=vx(),d=wx(),m=kF(),p=!!m,f=x.useMemo(()=>m?{id:m.agentId,name:m.agentName,class:m.agentClass,status:"idle",provider:"claude",position:{x:0,y:0,z:0},cwd:m.cwd,permissionMode:"interactive",tokensUsed:0,contextUsed:0,contextLimit:2e5,taskCount:0,createdAt:m.createdAt,lastActivity:m.createdAt}:null,[m]),b=Array.from(n),w=b.length===1?b[0]:null,S=(bx(w)||null)??(p?f:null),j=w??(p?(m==null?void 0:m.agentId)??null:null),C=!!(S!=null&&S.sessionId)&&!p,{terminalHeight:A,terminalRef:D,handleResizeStart:M}=J6(),I=Z6(),E=yx(j),_=p&&m?m.outputs.map(Ve=>((!Ve.text||!Ve.text.trim())&&console.warn("[GuakeOutputPanel] Empty snapshot output:",Ve),{text:Ve.text||"",timestamp:Ve.timestamp,isStreaming:!1,isUserPrompt:!1})):E,P=x.useRef(null),L=x.useRef(null),R=x.useRef(null),[z,F]=x.useState(()=>{const Ve=As(pt.VIEW_MODE);return Ve==="simple"||Ve==="chat"||Ve==="advanced"?Ve:As(pt.ADVANCED_VIEW)==="true"?"advanced":"simple"}),[$,U]=x.useState(null),[G,K]=x.useState(null),[Z,B]=x.useState(null),[ee,se]=x.useState(null),[O,Y]=x.useState(!1);Pn("guake-image-modal",$!==null,()=>U(null)),Pn("guake-bash-modal",G!==null,()=>K(null)),Pn("guake-response-modal",ee!==null,()=>se(null)),Pn("guake-context-confirm",Z!==null,()=>B(null)),Pn("guake-agent-info",O,()=>Y(!1));const[Q,ie]=x.useState(!1),[J,re]=x.useState(()=>vs.isEnabled()),V=CF(),ne=x.useCallback(Ve=>H.setOverviewPanelOpen(Ve),[]),[de,be]=x.useState(!1),[ve,pe]=x.useState(null),Te=x.useRef(null),Me=x.useRef(null),[Le,X]=x.useState(!1),[fe,me]=x.useState(!1),le=a&&S!==null,ce=PT({selectedAgentId:j,hasSessionId:C,reconnectCount:o,lastPrompts:i,outputScrollRef:P}),Ne=s9({selectedAgentId:j,isOpen:le}),we=e9({agents:t,selectedAgentId:j,isOpen:le,loadingHistory:ce.fetchingHistory,hasModalOpen:!!($||G||ee||c||d),outputRef:P}),Ke=RT({selectedAgentId:w}),he=!p&&j?H.getPendingPermissionsForAgent(j):[],ae=(S==null?void 0:S.class)==="boss"||(S==null?void 0:S.isBoss),ye=pF(!p&&ae?j:null),oe=mF(p?null:j),Ee=xM();x.useEffect(()=>{Q&&!J&&(re(!0),vs.setEnabled(!0))},[Q,J]),x.useEffect(()=>{le||Y(!1)},[le]),x.useEffect(()=>{const Ve=S==null?void 0:S.status;if(Te.current==="working"&&Ve==="idle"){Me.current&&clearTimeout(Me.current);const ft=j?i.get(j):void 0;pe(ft!=null&&ft.timestamp?Date.now()-ft.timestamp:null),be(!0),Me.current=setTimeout(()=>{be(!1),pe(null),Me.current=null},4e3)}else Ve==="working"&&(Me.current&&(clearTimeout(Me.current),Me.current=null),be(!1),pe(null));return Te.current=Ve||null,()=>{Me.current&&clearTimeout(Me.current)}},[S==null?void 0:S.status]);const _e=x.useMemo(()=>{const{history:Ve}=ce,Je=new Map;for(const wt of Ve)wt.type==="tool_result"&&wt.toolUseId&&Je.set(wt.toolUseId,wt.content);return(wt=>wt.map(Nt=>{if(Nt.type==="tool_use"&&Nt.toolName==="Bash"&&Nt.toolUseId){const qt=Je.get(Nt.toolUseId);let bn;try{bn=(Nt.toolInput||(Nt.content?JSON.parse(Nt.content):{})).command}catch{}return{...Nt,_bashOutput:qt,_bashCommand:bn}}return Nt}))(Ve)},[ce.history,z]),Be=LT({outputs:_,viewMode:z}),nt=x.useMemo(()=>{const Ve=[],Je=new Set,ft=new Set;let wt=null,Nt=0;for(const qt of _e){if(qt.type==="assistant"){const Fn=qt.uuid?`uuid:${qt.uuid}:${Vh(qt.content)}`:`sig:${qt.timestamp}:${Vh(qt.content)}`;if(Je.has(Fn))continue;Je.add(Fn),Ve.push(qt);continue}if(qt.type!=="user"){Ve.push(qt);continue}const bn=Nb(qt.content),Mt=qt.uuid?`uuid:${qt.uuid}:${bn}`:null;if(Mt&&ft.has(Mt))continue;const zt=qt.timestamp?new Date(qt.timestamp).getTime():0;wt===bn&&Math.abs(zt-Nt)<=f1||(Ve.push(qt),Mt&&ft.add(Mt),wt=bn,Nt=zt)}return Ve},[_e]),Qe=x.useMemo(()=>{const Ve=new Map,Je=new Set,ft=new Map;for(const Mt of nt){const zt=Mt.timestamp?new Date(Mt.timestamp).getTime():0;if(Mt.type==="user"){const $t=Nb(Mt.content),an=Ve.get($t)??0;zt>an&&Ve.set($t,zt);continue}if(Mt.type!=="assistant")continue;Mt.uuid&&Je.add(Mt.uuid);const Fn=Vh(Mt.content),lt=ft.get(Fn)??0;zt>lt&&ft.set(Fn,zt)}const wt=[];let Nt=null,qt=0,bn=0;for(const Mt of Be){if(!Mt.isUserPrompt){if(!Mt.isStreaming&&!wH(Mt.text)){if(Mt.uuid&&Je.has(Mt.uuid)){bn++,console.warn(`[DEDUP-DROP] UUID match → dropped live output: uuid=${Mt.uuid} text="${Mt.text.slice(0,80)}"`);continue}const $t=Vh(Mt.text),an=Mt.timestamp||0,ts=ft.get($t);if(ts&&Math.abs(an-ts)<=g1){bn++,console.warn(`[DEDUP-DROP] Text match (within ${g1}ms) → dropped live output: ts=${an} historyTs=${ts} diff=${Math.abs(an-ts)}ms text="${Mt.text.slice(0,80)}"`);continue}}wt.push(Mt);continue}const zt=Nb(Mt.text),Fn=Mt.timestamp||0,lt=Ve.get(zt);if(lt&&Fn>=lt&&Fn-lt<=vH){bn++,console.warn(`[DEDUP-DROP] User prompt history match → dropped: ts=${Fn} historyTs=${lt} text="${Mt.text.slice(0,80)}"`);continue}if(Nt===zt&&Math.abs(Fn-qt)<=f1){bn++,console.warn(`[DEDUP-DROP] Duplicate command_started → dropped: text="${Mt.text.slice(0,80)}"`);continue}wt.push(Mt),Nt=zt,qt=Fn}return bn>0&&console.warn(`[DEDUP] Dropped ${bn}/${Be.length} outputs (kept ${wt.length}). historyUuids=${Je.size} historyTextKeys=${ft.size}`),wt},[Be,nt]),gt=nt.length+Qe.length,et=a9({totalMessages:gt,isOpen:le,hasModalOpen:!!($||G||ee||c),scrollContainerRef:P,selectedAgentId:j,inputRef:L,textareaRef:R,useTextarea:Ke.useTextarea});x.useEffect(()=>{if(!(!(G!=null&&G.isLive)||!G.command)){for(const Ve of Qe)if(Ve._bashCommand===G.command&&Ve._bashOutput){K({command:G.command,output:Ve._bashOutput,isLive:!1});return}}},[G,Qe]);const St=x.useCallback((Ve,Je)=>{U({url:Ve,name:Je})},[]),Lt=x.useCallback((Ve,Je)=>{const ft=xd(Ve,S==null?void 0:S.cwd),wt=ft.line?{...Je||{},targetLine:ft.line}:Je;H.setFileViewerPath(ft.path,wt,S==null?void 0:S.cwd)},[S==null?void 0:S.cwd]),Pt=x.useCallback((Ve,Je)=>{K({command:Ve,output:Je,isLive:Je==="Running..."})},[]),Cn=x.useCallback(Ve=>{se(Ve)},[]),[je,ue]=x.useState(!0),Fe=x.useRef(!1),at=x.useRef(!1),ct=x.useCallback(()=>{at.current||(Fe.current=!0,ue(!1))},[]);x.useEffect(()=>{ue(!0),Fe.current=!1,at.current=!0;const Ve=setTimeout(()=>{at.current=!1},3e3);return()=>clearTimeout(Ve)},[j]);const Ft=x.useCallback(()=>{if(!P.current||I.keyboardScrollLockRef.current)return;const{scrollTop:Ve,scrollHeight:Je,clientHeight:ft}=P.current,wt=Je-Ve-ft<150;at.current||(Fe.current=!wt,wt&&ue(!0)),ce.handleScroll(I.keyboardScrollLockRef)},[P,I.keyboardScrollLockRef,ce]),xn=E.length>0&&((ot=(Xe=E[E.length-1])==null?void 0:Xe.text)==null?void 0:ot.length)||0;x.useEffect(()=>{I.keyboardScrollLockRef.current||Fe.current||requestAnimationFrame(()=>{if(P.current){const{scrollTop:Ve,scrollHeight:Je,clientHeight:ft}=P.current;Je-Ve-ft<150&&(P.current.scrollTop=Je)}})},[E.length,xn,I.keyboardScrollLockRef,P]);const ut=x.useRef(null);x.useLayoutEffect(()=>{X(!1);const Je=ut.current!==w;ut.current=w,Je&&H.getState().currentSnapshot&&H.setCurrentSnapshot(null)},[w]);const ht=x.useRef(!1);x.useEffect(()=>{le&&w&&H.clearUnseenForAgent(w)},[le,w]),x.useEffect(()=>{ht.current=!0,me(!0)},[j,o]),x.useEffect(()=>{ce.fetchingHistory&&(ht.current=!0,me(!0))},[ce.fetchingHistory]),x.useEffect(()=>{if(!fe||!le||ce.fetchingHistory)return;const Ve=P.current;if(!Ve)return;let Je=null;const ft=performance.now();let wt=0,Nt=-1;const qt=()=>{const{scrollTop:Mt,scrollHeight:zt,clientHeight:Fn}=Ve;return zt-Mt-Fn<=2},bn=()=>{const Mt=performance.now(),zt=Ve.scrollHeight,Fn=Math.abs(zt-Nt)<=1,lt=qt();if(Fn&&lt?wt+=1:wt=0,Nt=zt,wt>=8){me(!1),Je=null;return}if(Mt-ft>8e3){me(!1),Je=null;return}Je=requestAnimationFrame(bn)};return Je=requestAnimationFrame(bn),()=>{Je!==null&&cancelAnimationFrame(Je)}},[fe,le,ce.fetchingHistory,ce.historyLoadVersion]),x.useEffect(()=>{if(!le||!ht.current)return;const Ve=setTimeout(()=>{requestAnimationFrame(()=>{ht.current=!1,X(!0)})},50);return()=>clearTimeout(Ve)},[ce.historyLoadVersion,le,P]),x.useEffect(()=>{const Ve=Je=>{if(Je.key==="`"&&!Je.ctrlKey&&!Je.altKey&&S){const ft=Je.target;ft.tagName!=="INPUT"&&ft.tagName!=="TEXTAREA"&&(Je.preventDefault(),H.toggleTerminal())}};return document.addEventListener("keydown",Ve),()=>document.removeEventListener("keydown",Ve)},[S]),x.useEffect(()=>{const Ve=Je=>{Je.key==="Escape"&&(c?(Je.stopImmediatePropagation(),H.clearFileViewerPath()):d?(Je.stopImmediatePropagation(),H.closeContextModal()):ee?(Je.stopImmediatePropagation(),se(null)):G?(Je.stopImmediatePropagation(),K(null)):$?(Je.stopImmediatePropagation(),U(null)):Ne.searchMode&&(Je.stopImmediatePropagation(),Ne.closeSearch()))};return document.addEventListener("keydown",Ve,!0),()=>document.removeEventListener("keydown",Ve,!0)},[$,G,ee,Ne,c,d]);const Gt=x.useRef(le),cn=x.useRef(!1);x.useEffect(()=>{Gt.current=le},[le]),x.useEffect(()=>{if(window.innerWidth<=768)return;const Je=Nt=>{var zt;if(!(Nt instanceof Element))return!1;const qt=(zt=D.current)==null?void 0:zt.contains(Nt),bn=Nt.closest(".agent-bar"),Mt=!!Nt.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!!qt||!!bn||Mt},ft=Nt=>{if(!Gt.current){cn.current=!1;return}cn.current=!Je(Nt.target)},wt=Nt=>{cn.current&&(Je(Nt.target)||H.setTerminalOpen(!1),cn.current=!1)};return document.addEventListener("mousedown",ft,!0),document.addEventListener("mouseup",wt,!0),()=>{document.removeEventListener("mousedown",ft,!0),document.removeEventListener("mouseup",wt,!0)}},[]),x.useEffect(()=>{const Ve=()=>{document.hidden&&I.cleanup()};return document.addEventListener("visibilitychange",Ve),()=>document.removeEventListener("visibilitychange",Ve)},[I]);const Ce=typeof window<"u"&&window.innerWidth<=768;return S?j?r.jsxs("div",{ref:D,className:`guake-terminal ${le?"open":"collapsed"} ${Q&&le?"with-debug-panel":""} ${V&&le?"with-overview-panel":""}`,style:{"--terminal-height":`${A}%`},children:[!p&&Q&&le&&j&&r.jsx(K9,{agentId:j,onClose:()=>ie(!1)}),!p&&V&&le&&j&&r.jsx(J9,{activeAgentId:j,onClose:()=>ne(!1),onSelectAgent:Ve=>{H.selectAgent(Ve)}}),r.jsxs("div",{className:"guake-content",children:[r.jsx(p9,{selectedAgent:S,selectedAgentId:j,sortedAgents:we.sortedAgents,swipeOffset:we.swipeOffset,viewMode:z,setViewMode:F,searchMode:Ne.searchMode,toggleSearch:Ne.toggleSearch,closeSearch:Ne.closeSearch,debugPanelOpen:Q,setDebugPanelOpen:ie,debuggerEnabled:J,setDebuggerEnabled:re,overviewPanelOpen:V,setOverviewPanelOpen:ne,agentInfoOpen:O,onToggleAgentInfo:()=>Y(!O),outputsLength:nt.length+Qe.length,setContextConfirm:B,headerRef:we.headerRef,onSaveSnapshot:p?void 0:s,isSnapshotView:p}),Ne.searchMode&&r.jsx(m9,{searchInputRef:Ne.searchInputRef,searchQuery:Ne.searchQuery,setSearchQuery:Ne.setSearchQuery,handleSearch:Ne.handleSearch,closeSearch:Ne.closeSearch,searchLoading:Ne.searchLoading,searchResultsCount:Ne.searchResults.length}),r.jsxs("div",{className:`guake-swipe-container ${we.swipeAnimationClass}`,style:we.swipeOffset!==0?{transform:`translateX(${we.swipeOffset*40}%)`}:void 0,children:[we.sortedAgents.length>1&&we.swipeOffset!==0&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:`swipe-indicator left ${we.swipeOffset>.3?"visible":""}`,children:[r.jsx("span",{className:"indicator-icon",children:"←"}),r.jsx("span",{className:"indicator-name",children:(on=we.prevAgent)==null?void 0:on.name})]}),r.jsxs("div",{className:`swipe-indicator right ${we.swipeOffset<-.3?"visible":""}`,children:[r.jsx("span",{className:"indicator-name",children:(Nn=we.nextAgent)==null?void 0:Nn.name}),r.jsx("span",{className:"indicator-icon",children:"→"})]})]}),we.sortedAgents.length>1&&we.sortedAgents.length<=8&&we.swipeOffset!==0&&r.jsx("div",{className:`swipe-dots ${Math.abs(we.swipeOffset)>.1?"visible":""}`,children:we.sortedAgents.map((Ve,Je)=>r.jsx("div",{className:`swipe-dot ${Je===we.currentAgentIndex?"active":""}`},Ve.id))}),r.jsx("div",{className:"guake-output",ref:P,onScroll:Ft,children:Ne.searchMode&&Ne.searchResults.length>0?r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"guake-search-header",children:e("terminal:header.searchResultsTitle")}),Ne.searchResults.map((Ve,Je)=>r.jsx(xm,{message:Ve,agentId:j,highlight:Ne.searchQuery,onImageClick:St,onFileClick:Lt,onBashClick:Pt,onViewMarkdown:Cn},`s-${Je}`))]}):r.jsxs("div",{className:`guake-history-content ${Le?"fade-in":""}`,children:[ce.loadingHistory&&ce.history.length===0&&E.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",{})]})]}),!ce.loadingHistory&&ce.history.length===0&&_.length===0&&S.status!=="working"&&r.jsx("div",{className:"guake-empty",children:e("terminal:empty.noOutput")}),ce.hasMore&&!Ne.searchMode&&r.jsx("div",{className:"guake-load-more",children:ce.loadingMore?r.jsx("span",{children:e("terminal:empty.loadingOlder")}):r.jsx("button",{onClick:ce.loadMoreHistory,children:e("terminal:empty.loadMore",{count:ce.totalCount-ce.history.length})})}),r.jsx(V9,{historyMessages:nt,liveOutputs:Qe,agentId:j,execTasks:oe,subagents:Ee,viewMode:z,selectedMessageIndex:et.selectedIndex,isMessageSelected:et.isSelected,onImageClick:St,onFileClick:Lt,onBashClick:Pt,onViewMarkdown:Cn,scrollContainerRef:P,onScrollTopReached:ce.loadMoreHistory,isLoadingMore:ce.loadingMore,hasMore:ce.hasMore,shouldAutoScroll:je,onUserScroll:ct,pinToBottom:fe,onPinCancel:()=>me(!1),isLoadingHistory:ce.fetchingHistory}),ae&&ye.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:ye.size})})]}),Array.from(ye.values()).map(Ve=>r.jsx(tH,{progress:Ve,defaultExpanded:Ve.status==="working",onAgentClick:Je=>H.selectAgent(Je)},Ve.agentId))]})]})})]}),r.jsx(v9,{selectedAgent:S,selectedAgentId:j,isOpen:le,command:Ke.command,setCommand:Ke.setCommand,forceTextarea:Ke.forceTextarea,setForceTextarea:Ke.setForceTextarea,useTextarea:Ke.useTextarea,attachedFiles:Ke.attachedFiles,setAttachedFiles:Ke.setAttachedFiles,removeAttachedFile:Ke.removeAttachedFile,uploadFile:Ke.uploadFile,pastedTexts:Ke.pastedTexts,expandPastedTexts:Ke.expandPastedTexts,incrementPastedCount:Ke.incrementPastedCount,setPastedTexts:Ke.setPastedTexts,resetPastedCount:Ke.resetPastedCount,handleInputFocus:I.handleInputFocus,handleInputBlur:I.handleInputBlur,pendingPermissions:he,showCompletion:de,completionElapsed:ve,onImageClick:St,inputRef:L,textareaRef:R,isSnapshotView:p,onClearHistory:ce.clearHistory}),r.jsxs("div",{className:"guake-agent-status-bar",children:[!p&&(S==null?void 0:S.isDetached)&&r.jsx(Op,{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 Ve=S.contextStats,Je=!!Ve,ft=Ve?Ve.totalTokens:S.contextUsed||0,wt=Ve?Ve.contextWindow:S.contextLimit||2e5,Nt=Ve?Ve.usedPercent:Math.round(ft/wt*100),qt=Math.round(100-Nt),bn=Nt>=80?"#ff4a4a":Nt>=60?"#ff9e4a":Nt>=40?"#ffd700":"#4aff9e",Mt=(ft/1e3).toFixed(1),zt=(wt/1e3).toFixed(1);return r.jsxs("span",{className:"guake-agent-context",onClick:()=>H.setContextModalAgentId(j),title:e(Je?"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,Nt)}%`,backgroundColor:bn}})}),r.jsxs("span",{className:"context-tokens",style:{color:bn},children:[Mt,"k/",zt,"k"]}),r.jsxs("span",{className:"context-free",children:["(",e("terminal:context.percentFree",{percent:qt}),")"]}),!Je&&r.jsx("span",{className:"context-warning",title:e("terminal:context.clickToFetchStats"),children:"⚠️"})]})})(),r.jsx(xH,{})]})]}),le&&r.jsx("div",{className:"guake-resize-handle",onMouseDown:M,title:e("common:rightPanel.dragToResize")}),r.jsxs("div",{className:"guake-handle",onClick:()=>{le&&H.toggleTerminal()},onDoubleClick:()=>{le||H.toggleTerminal()},style:{top:le?`min(${A}%, calc(100vh - 72px))`:"0"},children:[r.jsx("span",{className:"guake-handle-icon",children:le?"▲":"▼"}),r.jsx("span",{className:"guake-handle-text",children:S.name})]}),$&&r.jsx(GT,{url:$.url,name:$.name,onClose:()=>U(null)}),G&&r.jsx(WT,{state:G,onClose:()=>K(null)}),Z&&r.jsx(S9,{action:Z,selectedAgentId:j,subordinateCount:((Jt=S==null?void 0:S.subordinateIds)==null?void 0:Jt.length)||0,onClose:()=>B(null),onClearHistory:ce.clearHistory}),r.jsx(j9,{}),r.jsx(C9,{}),r.jsx(N9,{agent:S,isOpen:O,onClose:()=>Y(!1)}),!p&&r.jsx(qT,{agent:S,content:ee,onClose:()=>se(null)})]}):null:Ce&&l==="terminal"&&n.size===0?r.jsx("div",{ref:D,className:"guake-terminal open",style:{"--terminal-height":`${A}%`},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")})]})})})}):Ce&&l==="terminal"&&n.size>0?r.jsx("div",{ref:D,className:"guake-terminal open",style:{"--terminal-height":`${A}%`},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 SH(s){return s.trim().replace(/^v/i,"")}function b1(s){const t=SH(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 jH(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 CH(s,e){const t=b1(s),n=b1(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 jH(t.prerelease,n.prerelease)}function NH(s,e){const t=CH(s,e);return t===null?"unknown":t<0?"behind":t>0?"ahead":"equal"}async function AH(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 MH(s,e,t={}){const n=await AH(s,t);return n?{currentVersion:e,latestVersion:n,relation:NH(e,n)}:{currentVersion:e,latestVersion:null,relation:"unknown"}}const TH="tide-commander",Ab="0.71.4";function EH(){const[s,e]=x.useState({currentVersion:Ab,latestVersion:null,relation:"unknown",isChecking:!1}),t=x.useCallback(async()=>{e(a=>({...a,isChecking:!0}));const n=await MH(TH,Ab);e({currentVersion:Ab,latestVersion:n.latestVersion,relation:n.relation,isChecking:!1})},[]);return x.useEffect(()=>{t()},[t]),{...s,refresh:t}}function _H({onFocusAgent:s,onSpawnClick:e,onSpawnBossClick:t,onNewBuildingClick:n,onNewAreaClick:a}){const{t:i}=Ue(["common"]),o=_n(),l=al(),c=si(),d=Sx(),[m,p]=x.useState(!1),f=x.useRef(null),b=x.useRef(null),y=x.useRef(null),w=x.useRef(new Map);x.useEffect(()=>{{p(!1);return}},[l.experimental2DView]),x.useEffect(()=>{const ne=b.current;if(!ne)return;const de=be=>{ne.scrollWidth<=ne.clientWidth||(be.preventDefault(),ne.scrollLeft+=be.deltaY)};return ne.addEventListener("wheel",de,{passive:!1}),()=>ne.removeEventListener("wheel",de)},[]);const[k,S]=x.useState(null),[j,C]=x.useState(new Map),[A,D]=x.useState(null),[M,I]=x.useState(null),E=x.useRef(0),_=x.useMemo(()=>Array.from(o.agents.values()).filter(ne=>!H.isAgentInArchivedArea(ne.id)).sort((ne,de)=>(ne.createdAt||0)-(de.createdAt||0)),[o.agents,o.areas]),{orderedAgents:P,moveAgent:L}=cM(_),R=P,z=x.useMemo(()=>{const ne=new Map;for(const de of R)ne.set(de.id,H.getAreaForAgent(de.id));return ne},[R,o.areas]),F=x.useMemo(()=>{const ne=new Map;for(const be of R){const ve=z.get(be.id)||null,pe=(ve==null?void 0:ve.id)||null;ne.has(pe)||ne.set(pe,{area:ve,agents:[]}),ne.get(pe).agents.push(be)}const de=Array.from(ne.values());return de.sort((be,ve)=>{var pe,Te;return!be.area&&ve.area?1:be.area&&!ve.area?-1:!be.area&&!ve.area?0:(((pe=be.area)==null?void 0:pe.name)||"").localeCompare(((Te=ve.area)==null?void 0:Te.name)||"")}),de},[R,z]);x.useEffect(()=>{const ne=new Map(j);let de=!1;for(const be of R){const ve=j.get(be.id);be.currentTool?(!ve||ve.tool!==be.currentTool)&&(ne.set(be.id,{tool:be.currentTool,key:Date.now()}),de=!0):ve&&setTimeout(()=>{C(pe=>{const Te=new Map(pe);return Te.delete(be.id),Te})},1500)}de&&C(ne)},[R.map(ne=>ne.currentTool).join(",")]),x.useEffect(()=>{const ne=o.lastSelectedAgentId;if(!ne)return;const de=w.current.get(ne),be=b.current;de&&be&&requestAnimationFrame(()=>{const ve=de.getBoundingClientRect(),pe=be.getBoundingClientRect(),Me=ve.left-pe.left+be.scrollLeft+ve.width/2,Le=be.clientWidth;be.scrollTo({left:Me-Le/2,behavior:"smooth"})})},[o.lastSelectedAgentId]);const $=(ne,de)=>{H.setLastSelectionViaDirectClick(!0),de.shiftKey?H.addToSelection(ne.id):H.selectAgent(ne.id),(window.innerWidth<=768||o.terminalOpen)&&H.setTerminalOpen(!0)},U=ne=>{s==null||s(ne.id),H.setTerminalOpen(!0)},G=x.useCallback((ne,de)=>{D(de),ne.dataTransfer.effectAllowed="move",ne.dataTransfer.setData("text/plain",de.id),requestAnimationFrame(()=>{ne.target.classList.add("dragging")})},[]),K=x.useCallback(ne=>{D(null),I(null),E.current=0,ne.target.classList.remove("dragging")},[]),Z=x.useCallback((ne,de)=>{if(ne.preventDefault(),A){const be=z.get(A.id),ve=R[de],pe=ve?z.get(ve.id):null,Te=(be==null?void 0:be.id)??null,Me=(pe==null?void 0:pe.id)??null;ne.dataTransfer.dropEffect=Te===Me?"move":"none"}else ne.dataTransfer.dropEffect="move"},[A,R,z]),B=x.useCallback((ne,de)=>{if(ne.preventDefault(),E.current++,A){const be=z.get(A.id),ve=R[de],pe=ve?z.get(ve.id):null,Te=(be==null?void 0:be.id)??null,Me=(pe==null?void 0:pe.id)??null;I(Te===Me?de:null)}else I(de)},[A,R,z]),ee=x.useCallback(ne=>{E.current--,E.current===0&&I(null)},[]),se=x.useCallback((ne,de)=>{if(ne.preventDefault(),!A)return;const be=R.findIndex(ve=>ve.id===A.id);if(be!==-1&&be!==de){const ve=z.get(A.id),pe=R[de],Te=pe?z.get(pe.id):null,Me=(ve==null?void 0:ve.id)??null,Le=(Te==null?void 0:Te.id)??null;Me===Le&&L(be,de)}D(null),I(null),E.current=0},[A,R,L,z]),O=ne=>{const de=`common:status.${ne}`;return i(de,{defaultValue:i("common:status.unknown")})},{currentVersion:Y,latestVersion:Q,relation:ie,isChecking:J}=EH(),re=Y;let V=0;return r.jsxs("div",{className:"agent-bar",ref:f,children:[r.jsxs("div",{className:"agent-bar-scroll",ref:b,children:[r.jsxs("div",{className:"agent-bar-version",title:Q?`Tide Commander v${re} (npm: v${Q})`:`Tide Commander v${re}`,children:[r.jsxs("span",{children:["v",re]}),ie==="behind"&&Q?r.jsxs("span",{className:"agent-bar-version-badge agent-bar-version-badge-behind",title:`Behind npm latest v${Q}`,children:["npm v",Q]}):ie==="ahead"&&Q?r.jsxs("span",{className:"agent-bar-version-badge agent-bar-version-badge-ahead",title:`Ahead of npm latest v${Q}`,children:["npm v",Q]}):null,ie==="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)"})}):ie==="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)"})}):ie==="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)"})}),m&&r.jsx("button",{className:"agent-bar-hmr-refresh",onClick:lM,title:"Refresh 3D Scene (HMR changes pending)",children:"↻"})]}),r.jsxs("div",{className:"agent-bar-list",ref:y,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(ne=>{var ve,pe,Te,Me,Le;const de=ne.agents,be=!ne.area;return r.jsxs("div",{className:`agent-bar-group ${be?"unassigned":""}`,style:{borderColor:((ve=ne.area)==null?void 0:ve.color)||void 0,background:ne.area?`${ne.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:((pe=ne.area)==null?void 0:pe.color)||"#888"},children:((Te=ne.area)==null?void 0:Te.name)||i("common:agentBar.unassigned")})}),((Me=ne.area)==null?void 0:Me.directories)&&ne.area.directories.length>0&&r.jsx("div",{className:"agent-bar-folders",children:ne.area.directories.map((X,fe)=>r.jsxs("div",{className:"agent-bar-folder-item",onClick:me=>{me.stopPropagation(),H.openFileExplorer(X)},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:X}),r.jsx("div",{className:"agent-bar-folder-tooltip-hint",children:i("common:agentBar.clickToOpen")})]})]},fe))}),de.map(X=>{const fe=V++,me=R.findIndex(ae=>ae.id===X.id),le=o.selectedAgentIds.has(X.id),ce=Zr(X.class,c),Ne=o.lastPrompts.get(X.id),we=j.get(X.id);we&&(Vn[we.tool]||Vn.default),Ne!=null&&Ne.text&&(Ne.text.length>30?Ne.text.substring(0,30)+"":Ne.text);const Ke=(A==null?void 0:A.id)===X.id,he=M===me;return r.jsxs("div",{ref:ae=>{ae?w.current.set(X.id,ae):w.current.delete(X.id)},className:`agent-bar-item ${le?"selected":""} ${X.status} ${X.isBoss?"is-boss":""} ${Ke?"dragging":""} ${he?"drag-over":""}`,draggable:!0,onDragStart:ae=>G(ae,X),onDragEnd:K,onDragOver:ae=>Z(ae,me),onDragEnter:ae=>B(ae,me),onDragLeave:ee,onDrop:ae=>se(ae,me),onClick:ae=>$(X,ae),onDoubleClick:()=>U(X),onMouseEnter:()=>S(X),onMouseLeave:()=>S(null),title:`${X.name} (${fe+1}) - Drag to reorder within group`,children:[r.jsxs("div",{className:"agent-bar-avatar",children:[r.jsx("span",{className:"agent-bar-icon",children:ce.icon}),r.jsx("span",{className:"agent-bar-status",style:{backgroundColor:iy(X.status)}}),d.has(X.id)&&r.jsx("span",{className:"agent-bar-notification-badge",title:"New output available - click to view"}),X.status==="idle"&&X.lastActivity>0&&r.jsx("span",{className:"agent-bar-idle-clock",style:{color:am(X.lastActivity)},title:im(X.lastActivity),children:"⏱"})]}),r.jsxs("span",{className:"agent-bar-hotkey",title:`Ctrl+${fe+1}`,children:["^",fe+1]})]},X.id)})]},((Le=ne.area)==null?void 0:Le.id)||"unassigned")})]})]}),Array.from(j.entries()).map(([ne,de])=>{const be=w.current.get(ne);if(!be)return null;const ve=be.getBoundingClientRect(),pe=Vn[de.tool]||Vn.default;return r.jsxs("div",{className:"agent-bar-tool-bubble",title:de.tool,style:{position:"fixed",left:ve.left+ve.width/2,bottom:window.innerHeight-ve.top+8},children:[r.jsx("span",{className:"agent-bar-tool-icon",children:pe}),r.jsx("span",{className:"agent-bar-tool-name",children:de.tool})]},`tool-${ne}-${de.key}`)}),k&&(()=>{const ne=H.getAreaForAgent(k.id),de=o.lastPrompts.get(k.id),be=Zr(k.class,c),ve=H.getAgentSupervisorHistory(k.id),pe=ve.length>0?ve[ve.length-1]:void 0,Te=Date.now()-(k.createdAt||Date.now()),Me=Math.floor(Te/6e4),Le=Math.floor(Me/60),X=Le>0?`${Le}h ${Me%60}m`:`${Me}m`,fe=we=>we>=1e6?`${(we/1e6).toFixed(1)}M`:we>=1e3?`${(we/1e3).toFixed(1)}K`:we.toString(),me=k.contextLimit>0?Math.round(k.contextUsed/k.contextLimit*100):0,le=we=>{switch(we){case"on_track":return"#4aff9e";case"completed":return"#4a9eff";case"stalled":return"#ff9e4a";case"blocked":return"#ff4a4a";case"idle":return"#888888";default:return"#888888"}},ce=w.current.get(k.id),Ne={};if(ce){const we=ce.getBoundingClientRect();Ne.position="fixed",Ne.left=we.left+we.width/2,Ne.bottom=window.innerHeight-we.top+12}return r.jsxs("div",{className:"agent-bar-tooltip",style:Ne,children:[r.jsxs("div",{className:"agent-bar-tooltip-header",children:[r.jsx("span",{className:"agent-bar-tooltip-icon",children:be.icon}),r.jsxs("span",{className:"agent-bar-tooltip-name",children:[r.jsx("img",{src:k.provider==="codex"?"/assets/codex.png":"/assets/claude.png",alt:k.provider,className:"agent-bar-provider-icon",title:k.provider==="codex"?"Codex Agent":"Claude Agent"}),k.name]}),r.jsx("span",{className:"agent-bar-tooltip-status",style:{color:iy(k.status)},children:O(k.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:[k.class," — ",be.description]})]}),ne&&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:ne.color},children:ne.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:k.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:X})]}),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:[fe(k.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:me>80?"#ff4a4a":me>60?"#ff9e4a":void 0},children:[fe(k.contextUsed)," / ",fe(k.contextLimit)," (",me,"%)"]})]}),k.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:[Vn[k.currentTool]||Vn.default," ",k.currentTool]})]}),k.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:[k.currentTask.substring(0,150),k.currentTask.length>150?"...":""]})]}),k.lastAssignedTask&&!k.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:[k.lastAssignedTask.substring(0,200),k.lastAssignedTask.length>200?"...":""]})]}),de&&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:[de.text.substring(0,300),de.text.length>300?"...":""]})]}),pe&&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:le(pe.analysis.progress)},children:pe.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:pe.analysis.statusDescription})]}),pe.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:[pe.analysis.recentWorkSummary.substring(0,300),pe.analysis.recentWorkSummary.length>300?"...":""]})]}),pe.analysis.concerns&&pe.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:pe.analysis.concerns.join("; ")})]})]})]})]})})()]})}function DH({activeTool:s,onExit:e}){const{t}=Ue(["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 PH={idle:"common:status.idle",working:"common:status.working",waiting:"common:status.waiting",error:"common:status.error",offline:"common:status.offline"},Mb=s=>s>=1e6?`${(s/1e6).toFixed(1)}M`:s>=1e3?`${(s/1e3).toFixed(1)}K`:s.toString(),RH=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"}},LH=x.memo(function({agent:e,screenPos:t,onClose:n}){const{t:a}=Ue(["common"]),i=si(),o=H.getAreaForAgent(e.id),l=H.getState().lastPrompts.get(e.id),c=Zr(e.class,i),d=H.getAgentSupervisorHistory(e.id),m=d.length>0?d[d.length-1]:void 0,p=Date.now()-(e.createdAt||Date.now()),f=Math.floor(p/6e4),b=Math.floor(f/60),y=b>0?`${b}h ${f%60}m`:`${f}m`,w=e.contextLimit>0?Math.round(e.contextUsed/e.contextLimit*100):0,k=x.useMemo(()=>{let C=t.x-150,A=t.y-320-10;return typeof window<"u"&&(C<10?C=10:C+300>window.innerWidth-10&&(C=window.innerWidth-300-10),A<10&&(A=t.y+10)),{position:"fixed",left:C,top:A,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:iy(e.status)},children:a(PH[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:[Mb(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:[Mb(e.contextUsed)," / ",Mb(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:[Vn[e.currentTool]||Vn.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?"...":""]})]}),m&&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:RH(m.analysis.progress)},children:m.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:m.analysis.statusDescription})]}),m.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:[m.analysis.recentWorkSummary.substring(0,300),m.analysis.recentWorkSummary.length>300?"...":""]})]}),m.analysis.concerns&&m.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:m.analysis.concerns.join("; ")})]})]})]})]})});function y1(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 x1(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 v1={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 OH(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:v1[l]&&(a=v1[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 IH=x.memo(function({building:e,screenPos:t,onClose:n,onOpenSettings:a,onOpenLogsModal:i,onOpenUrlInModal:o}){var U,G,K,Z,B,ee,se,O,Y,Q,ie,J,re,V,ne,de,be,ve,pe,Te;const{t:l}=Ue(["terminal","common"]),[c,d]=x.useState(!1),[m,p]=x.useState(null),[f,b]=x.useState(!1),y=x.useRef(null),w=x.useRef(m);w.current=m;const{buildingLogs:k}=_n(),S=H.getBuildingLogs(e.id),j=(U=e.pm2)==null?void 0:U.enabled,C=(G=e.docker)==null?void 0:G.enabled,A=x.useRef(null),D=x.useRef(null),M=x.useCallback(Me=>{Me.preventDefault();const Le=w.current?w.current.x:0,X=w.current?w.current.y:0;y.current={mouseX:Me.clientX,mouseY:Me.clientY,popupX:Le,popupY:X},b(!0),A.current=fe=>{if(!y.current)return;const me=fe.clientX-y.current.mouseX,le=fe.clientY-y.current.mouseY;p({x:y.current.popupX+me,y:y.current.popupY+le})},D.current=()=>{b(!1),y.current=null,A.current&&document.removeEventListener("mousemove",A.current),D.current&&document.removeEventListener("mouseup",D.current)},document.addEventListener("mousemove",A.current),document.addEventListener("mouseup",D.current)},[]);x.useEffect(()=>()=>{A.current&&document.removeEventListener("mousemove",A.current),D.current&&document.removeEventListener("mouseup",D.current)},[]);const I=Me=>{if(Me==="logs"){if((j||C)&&i){i();return}H.sendBuildingCommand(e.id,Me),d(!0)}else H.sendBuildingCommand(e.id,Me)},E=(Me,Le)=>{if(Me){const X=`http://localhost:${Me}`;Le&&o?o(X):window.open(X,"_blank")}},_=((K=e.pm2Status)==null?void 0:K.ports)||[],P=((B=(Z=e.dockerStatus)==null?void 0:Z.ports)==null?void 0:B.map(Me=>Me.host))||[],L=j?_:C?P:[],R=j?!!((ee=e.pm2)!=null&&ee.script):C?!!((se=e.docker)!=null&&se.image)||((O=e.docker)==null?void 0:O.mode)==="compose"||((Y=e.docker)==null?void 0:Y.mode)==="existing":!!((Q=e.commands)!=null&&Q.start),z=j?!!((ie=e.pm2)!=null&&ie.script):C?!0:!!((J=e.commands)!=null&&J.stop),F=j?!!((re=e.pm2)!=null&&re.script):C?!0:!!((V=e.commands)!=null&&V.restart),$=x.useMemo(()=>{const Le=c?400:250;let X=t.x+20,fe=t.y-80;return typeof window<"u"&&!m&&(t.x+20+280>window.innerWidth&&(X=t.x-280-20),t.y-80<0?fe=10:t.y-80+Le>window.innerHeight&&(fe=window.innerHeight-Le-10)),{position:"fixed",left:X+((m==null?void 0:m.x)||0),top:fe+((m==null?void 0:m.y)||0),zIndex:1e3,cursor:f?"grabbing":void 0}},[t.x,t.y,c,m,f]);return r.jsxs("div",{className:"building-action-popup",style:$,onClick:Me=>Me.stopPropagation(),children:[r.jsxs("div",{className:`building-popup-header ${f?"dragging":""}`,onMouseDown:M,children:[r.jsx("span",{className:"building-popup-name",children:e.name}),L.length>0&&r.jsx("span",{className:"building-popup-ports",children:L.map(Me=>r.jsxs("a",{href:`http://localhost:${Me}`,className:"building-popup-port-link",onClick:Le=>{Le.preventDefault(),Le.stopPropagation(),E(Me,Le.altKey)},onMouseDown:Le=>Le.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:[((ne=e.pm2Status.cpu)==null?void 0:ne.toFixed(1))||"0","%"]})]}),r.jsxs("span",{className:"metric",children:[r.jsx("span",{className:"label",children:"MEM"}),r.jsx("span",{className:"value",children:y1(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:x1(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:y1(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:x1(e.dockerStatus.startedAt)})]})]}),C&&((de=e.dockerStatus)==null?void 0:de.services)&&e.dockerStatus.services.length>0&&r.jsx("div",{className:"building-popup-services",children:e.dockerStatus.services.map((Me,Le)=>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})]},Le))}),(e.lastError||j&&((be=e.pm2Status)==null?void 0:be.status)==="errored"||C&&((ve=e.dockerStatus)==null?void 0:ve.status)==="dead")&&r.jsxs("div",{className:"building-popup-error",children:[e.lastError||l("terminal:building.processFailedToStart"),j&&((pe=e.pm2Status)==null?void 0:pe.restarts)&&e.pm2Status.restarts>5&&r.jsxs("span",{className:"error-hint",children:[" - ",l("terminal:building.checkLogsOrConfig")]}),C&&((Te=e.dockerStatus)==null?void 0:Te.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:()=>I("start"),disabled:!R||e.status==="running"||e.status==="starting",title:l(R?"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:()=>I("stop"),disabled:!z||e.status==="stopped"||e.status==="stopping",title:l(z?"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:()=>I("restart"),disabled:!F,title:l(F?"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:()=>I("logs"),title:l("terminal:buildingAction.viewLogs"),children:[r.jsx("span",{className:"icon",children:"📄"}),l("terminal:logs.title")]}),L.length===1&&r.jsxs("button",{className:"action-btn open-url",onClick:Me=>E(L[0],Me.altKey),title:`Open http://localhost:${L[0]} (Alt+Click for modal)`,children:[r.jsx("span",{className:"icon",children:"🔗"}),l("terminal:buildingAction.openInBrowser")]}),L.length>1&&r.jsxs("div",{className:"action-btn-group",children:[r.jsxs("span",{className:"action-btn-label",children:[l("terminal:buildingAction.openInBrowser"),":"]}),L.map(Me=>r.jsxs("button",{className:"action-btn open-url port-btn",onClick:Le=>E(Me,Le.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,Le)=>r.jsx("pre",{children:OH(Me)},Le))})]}),r.jsx("button",{className:"building-popup-settings",onClick:a,children:l("terminal:buildingAction.fullSettings")})]})});function BH(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 FH(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 zH=x.memo(function({building:e,screenPos:t,onClose:n,onOpenSettings:a,onOpenLogsModal:i,onOpenUrlInModal:o}){const{t:l}=Ue(["terminal","common"]),[c,d]=x.useState(null),[m,p]=x.useState(!1),f=x.useRef(null),b=x.useRef(c);b.current=c;const{buildings:y}=_n(),k=(e.subordinateBuildingIds||[]).map(_=>y.get(_)).filter(_=>_!==void 0),S=x.useRef(null),j=x.useRef(null),C=x.useCallback(_=>{_.preventDefault();const P=b.current?b.current.x:0,L=b.current?b.current.y:0;f.current={mouseX:_.clientX,mouseY:_.clientY,popupX:P,popupY:L},p(!0),S.current=R=>{if(!f.current)return;const z=R.clientX-f.current.mouseX,F=R.clientY-f.current.mouseY;d({x:f.current.popupX+z,y:f.current.popupY+F})},j.current=()=>{p(!1),f.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 A=_=>{H.sendBossBuildingCommand(e.id,_)},D=k.reduce((_,P)=>(_[P.status]=(_[P.status]||0)+1,_),{}),M=k.some(_=>{var P;return(P=_.pm2)==null?void 0:P.enabled}),I=(_,P)=>{const L=`http://localhost:${_}`;P&&o?o(L):window.open(L,"_blank")},E=x.useMemo(()=>{let L=t.x+20,R=t.y-80;return typeof window<"u"&&!c&&(t.x+20+340>window.innerWidth&&(L=t.x-340-20),t.y-80<0?R=10:t.y-80+350>window.innerHeight&&(R=window.innerHeight-350-10)),{position:"fixed",left:L+((c==null?void 0:c.x)||0),top:R+((c==null?void 0:c.y)||0),zIndex:1e3,cursor:m?"grabbing":void 0}},[t.x,t.y,c,m]);return r.jsxs("div",{className:"building-action-popup boss-building-popup",style:E,onClick:_=>_.stopPropagation(),children:[r.jsxs("div",{className:`building-popup-header boss-header ${m?"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(([_,P])=>r.jsxs("span",{className:"status-badge",style:{backgroundColor:Xr[_]||"#666"},children:[P," ",_]},_)),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(_=>{var P,L,R;return r.jsxs("div",{className:"subordinate-item",children:[r.jsx("span",{className:"sub-status-dot",style:{backgroundColor:Xr[_.status]}}),r.jsx("span",{className:"sub-name",children:_.name}),((P=_.pm2Status)==null?void 0:P.ports)&&_.pm2Status.ports.length>0&&r.jsx("span",{className:"sub-port",children:_.pm2Status.ports.map(z=>r.jsxs("a",{href:`http://localhost:${z}`,className:"building-popup-port-link",onClick:F=>{F.preventDefault(),F.stopPropagation(),I(z,F.altKey)},title:`Open http://localhost:${z} (Alt+Click for modal)`,children:[":",z]},z))}),_.pm2Status&&r.jsxs("span",{className:"sub-metrics",children:[(L=_.pm2Status.cpu)==null?void 0:L.toFixed(0),"% | ",BH(_.pm2Status.memory||0)]}),((R=_.pm2Status)==null?void 0:R.uptime)&&r.jsx("span",{className:"sub-uptime",children:FH(_.pm2Status.uptime)})]},_.id)})}),r.jsxs("div",{className:"building-popup-actions boss-actions",children:[r.jsxs("button",{className:"action-btn start",onClick:()=>A("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:()=>A("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:()=>A("restart_all"),disabled:k.length===0,title:l("terminal:building.restartAllSubs"),children:[r.jsx("span",{className:"icon",children:"↺"}),l("terminal:building.restartAll")]}),M&&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")})]})}),$H=x.memo(function({building:e,screenPos:t,onClose:n,onOpenSettings:a,onOpenDatabasePanel:i}){var D;const{t:o}=Ue(["terminal","common"]),[l,c]=x.useState(null),[d,m]=x.useState(!1),p=x.useRef(null),f=x.useRef(l);f.current=l;const b=dm(e.id),y=((D=e.database)==null?void 0:D.connections)??[],w=x.useRef(null),k=x.useRef(null),S=x.useCallback(M=>{M.preventDefault();const I=f.current?f.current.x:0,E=f.current?f.current.y:0;p.current={mouseX:M.clientX,mouseY:M.clientY,popupX:I,popupY:E},m(!0),w.current=_=>{if(!p.current)return;const P=_.clientX-p.current.mouseX,L=_.clientY-p.current.mouseY;c({x:p.current.popupX+P,y:p.current.popupY+L})},k.current=()=>{m(!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=M=>{H.testDatabaseConnection(e.id,M)},C=M=>b.connectionStatus.get(M),A=x.useMemo(()=>{let E=t.x+20,_=t.y-80;return typeof window<"u"&&!l&&(t.x+20+320>window.innerWidth&&(E=t.x-320-20),t.y-80<0?_=10:t.y-80+300>window.innerHeight&&(_=window.innerHeight-300-10)),{position:"fixed",left:E+((l==null?void 0:l.x)||0),top:_+((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:A,onClick:M=>M.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(M=>{const I=C(M.id);return r.jsxs("div",{className:"database-connection-item",children:[r.jsx("span",{className:"conn-engine",children:M.engine==="mysql"?"🐬":"🐘"}),r.jsx("span",{className:"conn-name",children:M.name}),r.jsxs("span",{className:"conn-host",children:[M.host,":",M.port]}),I&&r.jsx("span",{className:`conn-status ${I.connected?"connected":"disconnected"}`,children:I.connected?"●":"○"}),r.jsx("button",{className:"conn-test-btn",onClick:()=>j(M.id),title:o("terminal:building.testConnection"),children:"↻"})]},M.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(M=>j(M.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")})]})}),HH=({building:s,connections:e,activeConnectionId:t,activeDatabase:n,collapsed:a,onToggleCollapse:i,onConnectionChange:o,onDatabaseChange:l,onInsertTable:c,onSelectTableQuery:d})=>{const{t:m}=Ue(["terminal"]),p=dm(s.id),[f,b]=x.useState(new Set),[y,w]=x.useState(""),[k,S]=x.useState(!1),[j,C]=x.useState(null),A=x.useRef(null),D=x.useRef(null),M=t?p.databases.get(t)??[]:[],I=t&&n?`${t}:${n}`:"",E=I?p.tables.get(I)??[]:[],_=t?p.connectionStatus.get(t):void 0,P=x.useMemo(()=>{if(!y.trim())return M;const z=y.toLowerCase();return M.filter(F=>F.toLowerCase().includes(z))},[M,y]);x.useEffect(()=>{const z=F=>{D.current&&!D.current.contains(F.target)&&S(!1)};return k&&document.addEventListener("mousedown",z),()=>document.removeEventListener("mousedown",z)},[k]),x.useEffect(()=>{t&&!_&&H.testDatabaseConnection(s.id,t)},[s.id,t,_]),x.useEffect(()=>{t&&(_!=null&&_.connected)&&M.length===0&&H.listDatabases(s.id,t)},[s.id,t,_==null?void 0:_.connected,M.length]),x.useEffect(()=>{t&&n&&E.length===0&&H.listTables(s.id,t,n)},[s.id,t,n,E.length]),x.useEffect(()=>{C(null)},[t,n]);const L=x.useCallback(z=>{b(F=>{const $=new Set(F);if($.has(z))$.delete(z);else if($.add(z),t&&n){const U=`${t}:${n}:${z}`;p.tableSchemas.has(U)||H.getTableSchema(s.id,t,n,z)}return $})},[s.id,t,n,p.tableSchemas]),R=z=>{if(!t||!n)return null;const F=`${t}:${n}:${z}`;return p.tableSchemas.get(F)};return a?r.jsx("div",{className:"database-sidebar database-sidebar--collapsed",children:r.jsx("button",{className:"database-sidebar__toggle",onClick:i,title:m("terminal:database.expandSidebar"),children:"»"})}):r.jsxs("div",{className:"database-sidebar",children:[r.jsxs("div",{className:"database-sidebar__header",children:[r.jsx("span",{children:m("terminal:database.explorer")}),r.jsx("button",{className:"database-sidebar__toggle",onClick:i,title:m("terminal:database.collapseSidebar"),children:"«"})]}),r.jsxs("div",{className:"database-sidebar__section",children:[r.jsx("div",{className:"database-sidebar__section-title",children:m("terminal:database.connection")}),r.jsx("select",{className:"database-sidebar__select",value:t||"",onChange:z=>o(z.target.value),children:e.length===0?r.jsx("option",{value:"",children:m("terminal:database.noConnections")}):e.map(z=>r.jsxs("option",{value:z.id,children:[z.engine==="mysql"?"🐬":"🐘"," ",z.name]},z.id))}),_&&r.jsx("div",{className:`database-sidebar__status ${_.connected?"database-sidebar__status--connected":"database-sidebar__status--error"}`,children:_.connected?r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"database-sidebar__status-icon",children:"✓"}),m("terminal:database.connected"),_.serverVersion&&r.jsxs("span",{className:"database-sidebar__version",children:["(",_.serverVersion,")"]})]}):r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"database-sidebar__status-icon",children:"✗"}),_.error||m("terminal:database.disconnected")]})})]}),M.length>0&&r.jsxs("div",{className:"database-sidebar__section",children:[r.jsx("div",{className:"database-sidebar__section-title",children:m("terminal:database.databaseTitle")}),r.jsxs("div",{className:"database-sidebar__searchable-select",ref:D,children:[r.jsx("input",{ref:A,className:"database-sidebar__search-input",type:"text",value:k?y:n||"",placeholder:m("terminal:database.selectDatabase"),onChange:z=>{w(z.target.value),k||S(!0)},onFocus:()=>{S(!0),w("")},onKeyDown:z=>{var F,$;z.key==="Escape"?(S(!1),w(""),(F=A.current)==null||F.blur()):z.key==="Enter"&&P.length===1&&(l(P[0]),S(!1),w(""),($=A.current)==null||$.blur())}}),k&&r.jsx("div",{className:"database-sidebar__dropdown",children:P.length===0?r.jsx("div",{className:"database-sidebar__dropdown-empty",children:"No matches"}):P.map(z=>r.jsx("div",{className:`database-sidebar__dropdown-item ${z===n?"database-sidebar__dropdown-item--active":""}`,onMouseDown:F=>{F.preventDefault(),l(z),S(!1),w("")},children:z},z))})]})]}),E.length>0&&r.jsxs("div",{className:"database-sidebar__section database-sidebar__section--tables",children:[r.jsx("div",{className:"database-sidebar__section-title",children:m("terminal:database.tablesCount",{count:E.length})}),r.jsx("div",{className:"database-sidebar__tables",children:E.map(z=>{const F=f.has(z.name),$=F?R(z.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:()=>L(z.name),title:F?"Collapse table schema":"Expand table schema",children:F?"▼":"▶"}),r.jsx("span",{className:"database-sidebar__table-icon",children:z.type==="view"?"👁":"📋"}),r.jsx("span",{className:`database-sidebar__table-name ${j===z.name?"database-sidebar__table-name--selected":""}`,onClick:()=>C(z.name),onDoubleClick:()=>{C(z.name),d(z.name)},children:z.name}),r.jsx("button",{className:"database-sidebar__table-insert",onClick:U=>{U.stopPropagation(),c(z.name)},title:m("terminal:database.insertTableName"),children:"+"})]}),F&&$&&r.jsx("div",{className:"database-sidebar__table-columns",children:$.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))})]},z.name)})})]})]})};function Zx(s){const e=[];let t=!1,n=!1,a=!1,i=!1,o=0;for(let c=0;c<s.length;c++){const d=s[c],m=s[c+1];if(a){d===`
231
+ `)}function wH(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 kH({onSaveSnapshot:s}={}){var Xe,ot,on,Nn,Jt;const{t:e}=Ue(["terminal","common"]),t=lr(),n=uM(),a=mM(),i=xx(),o=kx(),l=fM(),c=vx(),d=wx(),m=kF(),p=!!m,f=x.useMemo(()=>m?{id:m.agentId,name:m.agentName,class:m.agentClass,status:"idle",provider:"claude",position:{x:0,y:0,z:0},cwd:m.cwd,permissionMode:"interactive",tokensUsed:0,contextUsed:0,contextLimit:2e5,taskCount:0,createdAt:m.createdAt,lastActivity:m.createdAt}:null,[m]),b=Array.from(n),w=b.length===1?b[0]:null,S=(bx(w)||null)??(p?f:null),j=w??(p?(m==null?void 0:m.agentId)??null:null),C=!!(S!=null&&S.sessionId)&&!p,{terminalHeight:A,terminalRef:D,handleResizeStart:M}=J6(),I=Z6(),E=yx(j),_=p&&m?m.outputs.map(Ve=>((!Ve.text||!Ve.text.trim())&&console.warn("[GuakeOutputPanel] Empty snapshot output:",Ve),{text:Ve.text||"",timestamp:Ve.timestamp,isStreaming:!1,isUserPrompt:!1})):E,P=x.useRef(null),L=x.useRef(null),R=x.useRef(null),[z,F]=x.useState(()=>{const Ve=As(pt.VIEW_MODE);return Ve==="simple"||Ve==="chat"||Ve==="advanced"?Ve:As(pt.ADVANCED_VIEW)==="true"?"advanced":"simple"}),[$,U]=x.useState(null),[G,K]=x.useState(null),[Z,B]=x.useState(null),[ee,se]=x.useState(null),[O,Y]=x.useState(!1);Pn("guake-image-modal",$!==null,()=>U(null)),Pn("guake-bash-modal",G!==null,()=>K(null)),Pn("guake-response-modal",ee!==null,()=>se(null)),Pn("guake-context-confirm",Z!==null,()=>B(null)),Pn("guake-agent-info",O,()=>Y(!1));const[Q,ie]=x.useState(!1),[J,re]=x.useState(()=>vs.isEnabled()),V=CF(),ne=x.useCallback(Ve=>H.setOverviewPanelOpen(Ve),[]),[de,be]=x.useState(!1),[ve,pe]=x.useState(null),Te=x.useRef(null),Me=x.useRef(null),[Le,X]=x.useState(!1),[fe,me]=x.useState(!1),le=a&&S!==null,ce=PT({selectedAgentId:j,hasSessionId:C,reconnectCount:o,lastPrompts:i,outputScrollRef:P}),Ne=s9({selectedAgentId:j,isOpen:le}),we=e9({agents:t,selectedAgentId:j,isOpen:le,loadingHistory:ce.fetchingHistory,hasModalOpen:!!($||G||ee||c||d),outputRef:P}),Ke=RT({selectedAgentId:w}),he=!p&&j?H.getPendingPermissionsForAgent(j):[],ae=(S==null?void 0:S.class)==="boss"||(S==null?void 0:S.isBoss),ye=pF(!p&&ae?j:null),oe=mF(p?null:j),Ee=xM();x.useEffect(()=>{Q&&!J&&(re(!0),vs.setEnabled(!0))},[Q,J]),x.useEffect(()=>{le||Y(!1)},[le]),x.useEffect(()=>{const Ve=S==null?void 0:S.status;if(Te.current==="working"&&Ve==="idle"){Me.current&&clearTimeout(Me.current);const ft=j?i.get(j):void 0;pe(ft!=null&&ft.timestamp?Date.now()-ft.timestamp:null),be(!0),Me.current=setTimeout(()=>{be(!1),pe(null),Me.current=null},4e3)}else Ve==="working"&&(Me.current&&(clearTimeout(Me.current),Me.current=null),be(!1),pe(null));return Te.current=Ve||null,()=>{Me.current&&clearTimeout(Me.current)}},[S==null?void 0:S.status]);const _e=x.useMemo(()=>{const{history:Ve}=ce,Je=new Map;for(const wt of Ve)wt.type==="tool_result"&&wt.toolUseId&&Je.set(wt.toolUseId,wt.content);return(wt=>wt.map(Nt=>{if(Nt.type==="tool_use"&&Nt.toolName==="Bash"&&Nt.toolUseId){const qt=Je.get(Nt.toolUseId);let bn;try{bn=(Nt.toolInput||(Nt.content?JSON.parse(Nt.content):{})).command}catch{}return{...Nt,_bashOutput:qt,_bashCommand:bn}}return Nt}))(Ve)},[ce.history,z]),Be=LT({outputs:_,viewMode:z}),nt=x.useMemo(()=>{const Ve=[],Je=new Set,ft=new Set;let wt=null,Nt=0;for(const qt of _e){if(qt.type==="assistant"){const Fn=qt.uuid?`uuid:${qt.uuid}:${Vh(qt.content)}`:`sig:${qt.timestamp}:${Vh(qt.content)}`;if(Je.has(Fn))continue;Je.add(Fn),Ve.push(qt);continue}if(qt.type!=="user"){Ve.push(qt);continue}const bn=Nb(qt.content),Mt=qt.uuid?`uuid:${qt.uuid}:${bn}`:null;if(Mt&&ft.has(Mt))continue;const zt=qt.timestamp?new Date(qt.timestamp).getTime():0;wt===bn&&Math.abs(zt-Nt)<=f1||(Ve.push(qt),Mt&&ft.add(Mt),wt=bn,Nt=zt)}return Ve},[_e]),Qe=x.useMemo(()=>{const Ve=new Map,Je=new Set,ft=new Map;for(const Mt of nt){const zt=Mt.timestamp?new Date(Mt.timestamp).getTime():0;if(Mt.type==="user"){const $t=Nb(Mt.content),an=Ve.get($t)??0;zt>an&&Ve.set($t,zt);continue}if(Mt.type!=="assistant")continue;Mt.uuid&&Je.add(Mt.uuid);const Fn=Vh(Mt.content),lt=ft.get(Fn)??0;zt>lt&&ft.set(Fn,zt)}const wt=[];let Nt=null,qt=0,bn=0;for(const Mt of Be){if(!Mt.isUserPrompt){if(!Mt.isStreaming&&!wH(Mt.text)){if(Mt.uuid&&Je.has(Mt.uuid)){bn++,console.warn(`[DEDUP-DROP] UUID match → dropped live output: uuid=${Mt.uuid} text="${Mt.text.slice(0,80)}"`);continue}const $t=Vh(Mt.text),an=Mt.timestamp||0,ts=ft.get($t);if(ts&&Math.abs(an-ts)<=g1){bn++,console.warn(`[DEDUP-DROP] Text match (within ${g1}ms) → dropped live output: ts=${an} historyTs=${ts} diff=${Math.abs(an-ts)}ms text="${Mt.text.slice(0,80)}"`);continue}}wt.push(Mt);continue}const zt=Nb(Mt.text),Fn=Mt.timestamp||0,lt=Ve.get(zt);if(lt&&Fn>=lt&&Fn-lt<=vH){bn++,console.warn(`[DEDUP-DROP] User prompt history match → dropped: ts=${Fn} historyTs=${lt} text="${Mt.text.slice(0,80)}"`);continue}if(Nt===zt&&Math.abs(Fn-qt)<=f1){bn++,console.warn(`[DEDUP-DROP] Duplicate command_started → dropped: text="${Mt.text.slice(0,80)}"`);continue}wt.push(Mt),Nt=zt,qt=Fn}return bn>0&&console.warn(`[DEDUP] Dropped ${bn}/${Be.length} outputs (kept ${wt.length}). historyUuids=${Je.size} historyTextKeys=${ft.size}`),wt},[Be,nt]),gt=nt.length+Qe.length,et=a9({totalMessages:gt,isOpen:le,hasModalOpen:!!($||G||ee||c),scrollContainerRef:P,selectedAgentId:j,inputRef:L,textareaRef:R,useTextarea:Ke.useTextarea});x.useEffect(()=>{if(!(!(G!=null&&G.isLive)||!G.command)){for(const Ve of Qe)if(Ve._bashCommand===G.command&&Ve._bashOutput){K({command:G.command,output:Ve._bashOutput,isLive:!1});return}}},[G,Qe]);const St=x.useCallback((Ve,Je)=>{U({url:Ve,name:Je})},[]),Lt=x.useCallback((Ve,Je)=>{const ft=xd(Ve,S==null?void 0:S.cwd),wt=ft.line?{...Je||{},targetLine:ft.line}:Je;H.setFileViewerPath(ft.path,wt,S==null?void 0:S.cwd)},[S==null?void 0:S.cwd]),Pt=x.useCallback((Ve,Je)=>{K({command:Ve,output:Je,isLive:Je==="Running..."})},[]),Cn=x.useCallback(Ve=>{se(Ve)},[]),[je,ue]=x.useState(!0),Fe=x.useRef(!1),at=x.useRef(!1),ct=x.useCallback(()=>{at.current||(Fe.current=!0,ue(!1))},[]);x.useEffect(()=>{ue(!0),Fe.current=!1,at.current=!0;const Ve=setTimeout(()=>{at.current=!1},3e3);return()=>clearTimeout(Ve)},[j]);const Ft=x.useCallback(()=>{if(!P.current||I.keyboardScrollLockRef.current)return;const{scrollTop:Ve,scrollHeight:Je,clientHeight:ft}=P.current,wt=Je-Ve-ft<150;at.current||(Fe.current=!wt,wt&&ue(!0)),ce.handleScroll(I.keyboardScrollLockRef)},[P,I.keyboardScrollLockRef,ce]),xn=E.length>0&&((ot=(Xe=E[E.length-1])==null?void 0:Xe.text)==null?void 0:ot.length)||0;x.useEffect(()=>{I.keyboardScrollLockRef.current||Fe.current||requestAnimationFrame(()=>{if(P.current){const{scrollTop:Ve,scrollHeight:Je,clientHeight:ft}=P.current;Je-Ve-ft<150&&(P.current.scrollTop=Je)}})},[E.length,xn,I.keyboardScrollLockRef,P]);const ut=x.useRef(null);x.useLayoutEffect(()=>{X(!1);const Je=ut.current!==w;ut.current=w,Je&&H.getState().currentSnapshot&&H.setCurrentSnapshot(null)},[w]);const ht=x.useRef(!1);x.useEffect(()=>{le&&w&&H.clearUnseenForAgent(w)},[le,w]),x.useEffect(()=>{ht.current=!0,me(!0)},[j,o]),x.useEffect(()=>{ce.fetchingHistory&&(ht.current=!0,me(!0))},[ce.fetchingHistory]),x.useEffect(()=>{if(!fe||!le||ce.fetchingHistory)return;const Ve=P.current;if(!Ve)return;let Je=null;const ft=performance.now();let wt=0,Nt=-1;const qt=()=>{const{scrollTop:Mt,scrollHeight:zt,clientHeight:Fn}=Ve;return zt-Mt-Fn<=2},bn=()=>{const Mt=performance.now(),zt=Ve.scrollHeight,Fn=Math.abs(zt-Nt)<=1,lt=qt();if(Fn&&lt?wt+=1:wt=0,Nt=zt,wt>=8){me(!1),Je=null;return}if(Mt-ft>8e3){me(!1),Je=null;return}Je=requestAnimationFrame(bn)};return Je=requestAnimationFrame(bn),()=>{Je!==null&&cancelAnimationFrame(Je)}},[fe,le,ce.fetchingHistory,ce.historyLoadVersion]),x.useEffect(()=>{if(!le||!ht.current)return;const Ve=setTimeout(()=>{requestAnimationFrame(()=>{ht.current=!1,X(!0)})},50);return()=>clearTimeout(Ve)},[ce.historyLoadVersion,le,P]),x.useEffect(()=>{const Ve=Je=>{if(Je.key==="`"&&!Je.ctrlKey&&!Je.altKey&&S){const ft=Je.target;ft.tagName!=="INPUT"&&ft.tagName!=="TEXTAREA"&&(Je.preventDefault(),H.toggleTerminal())}};return document.addEventListener("keydown",Ve),()=>document.removeEventListener("keydown",Ve)},[S]),x.useEffect(()=>{const Ve=Je=>{Je.key==="Escape"&&(c?(Je.stopImmediatePropagation(),H.clearFileViewerPath()):d?(Je.stopImmediatePropagation(),H.closeContextModal()):ee?(Je.stopImmediatePropagation(),se(null)):G?(Je.stopImmediatePropagation(),K(null)):$?(Je.stopImmediatePropagation(),U(null)):Ne.searchMode&&(Je.stopImmediatePropagation(),Ne.closeSearch()))};return document.addEventListener("keydown",Ve,!0),()=>document.removeEventListener("keydown",Ve,!0)},[$,G,ee,Ne,c,d]);const Gt=x.useRef(le),cn=x.useRef(!1);x.useEffect(()=>{Gt.current=le},[le]),x.useEffect(()=>{if(window.innerWidth<=768)return;const Je=Nt=>{var zt;if(!(Nt instanceof Element))return!1;const qt=(zt=D.current)==null?void 0:zt.contains(Nt),bn=Nt.closest(".agent-bar"),Mt=!!Nt.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!!qt||!!bn||Mt},ft=Nt=>{if(!Gt.current){cn.current=!1;return}cn.current=!Je(Nt.target)},wt=Nt=>{cn.current&&(Je(Nt.target)||H.setTerminalOpen(!1),cn.current=!1)};return document.addEventListener("mousedown",ft,!0),document.addEventListener("mouseup",wt,!0),()=>{document.removeEventListener("mousedown",ft,!0),document.removeEventListener("mouseup",wt,!0)}},[]),x.useEffect(()=>{const Ve=()=>{document.hidden&&I.cleanup()};return document.addEventListener("visibilitychange",Ve),()=>document.removeEventListener("visibilitychange",Ve)},[I]);const Ce=typeof window<"u"&&window.innerWidth<=768;return S?j?r.jsxs("div",{ref:D,className:`guake-terminal ${le?"open":"collapsed"} ${Q&&le?"with-debug-panel":""} ${V&&le?"with-overview-panel":""}`,style:{"--terminal-height":`${A}%`},children:[!p&&Q&&le&&j&&r.jsx(K9,{agentId:j,onClose:()=>ie(!1)}),!p&&V&&le&&j&&r.jsx(J9,{activeAgentId:j,onClose:()=>ne(!1),onSelectAgent:Ve=>{H.selectAgent(Ve)}}),r.jsxs("div",{className:"guake-content",children:[r.jsx(p9,{selectedAgent:S,selectedAgentId:j,sortedAgents:we.sortedAgents,swipeOffset:we.swipeOffset,viewMode:z,setViewMode:F,searchMode:Ne.searchMode,toggleSearch:Ne.toggleSearch,closeSearch:Ne.closeSearch,debugPanelOpen:Q,setDebugPanelOpen:ie,debuggerEnabled:J,setDebuggerEnabled:re,overviewPanelOpen:V,setOverviewPanelOpen:ne,agentInfoOpen:O,onToggleAgentInfo:()=>Y(!O),outputsLength:nt.length+Qe.length,setContextConfirm:B,headerRef:we.headerRef,onSaveSnapshot:p?void 0:s,isSnapshotView:p}),Ne.searchMode&&r.jsx(m9,{searchInputRef:Ne.searchInputRef,searchQuery:Ne.searchQuery,setSearchQuery:Ne.setSearchQuery,handleSearch:Ne.handleSearch,closeSearch:Ne.closeSearch,searchLoading:Ne.searchLoading,searchResultsCount:Ne.searchResults.length}),r.jsxs("div",{className:`guake-swipe-container ${we.swipeAnimationClass}`,style:we.swipeOffset!==0?{transform:`translateX(${we.swipeOffset*40}%)`}:void 0,children:[we.sortedAgents.length>1&&we.swipeOffset!==0&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:`swipe-indicator left ${we.swipeOffset>.3?"visible":""}`,children:[r.jsx("span",{className:"indicator-icon",children:"←"}),r.jsx("span",{className:"indicator-name",children:(on=we.prevAgent)==null?void 0:on.name})]}),r.jsxs("div",{className:`swipe-indicator right ${we.swipeOffset<-.3?"visible":""}`,children:[r.jsx("span",{className:"indicator-name",children:(Nn=we.nextAgent)==null?void 0:Nn.name}),r.jsx("span",{className:"indicator-icon",children:"→"})]})]}),we.sortedAgents.length>1&&we.sortedAgents.length<=8&&we.swipeOffset!==0&&r.jsx("div",{className:`swipe-dots ${Math.abs(we.swipeOffset)>.1?"visible":""}`,children:we.sortedAgents.map((Ve,Je)=>r.jsx("div",{className:`swipe-dot ${Je===we.currentAgentIndex?"active":""}`},Ve.id))}),r.jsx("div",{className:"guake-output",ref:P,onScroll:Ft,children:Ne.searchMode&&Ne.searchResults.length>0?r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"guake-search-header",children:e("terminal:header.searchResultsTitle")}),Ne.searchResults.map((Ve,Je)=>r.jsx(xm,{message:Ve,agentId:j,highlight:Ne.searchQuery,onImageClick:St,onFileClick:Lt,onBashClick:Pt,onViewMarkdown:Cn},`s-${Je}`))]}):r.jsxs("div",{className:`guake-history-content ${Le?"fade-in":""}`,children:[ce.loadingHistory&&ce.history.length===0&&E.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",{})]})]}),!ce.loadingHistory&&ce.history.length===0&&_.length===0&&S.status!=="working"&&r.jsx("div",{className:"guake-empty",children:e("terminal:empty.noOutput")}),ce.hasMore&&!Ne.searchMode&&r.jsx("div",{className:"guake-load-more",children:ce.loadingMore?r.jsx("span",{children:e("terminal:empty.loadingOlder")}):r.jsx("button",{onClick:ce.loadMoreHistory,children:e("terminal:empty.loadMore",{count:ce.totalCount-ce.history.length})})}),r.jsx(V9,{historyMessages:nt,liveOutputs:Qe,agentId:j,execTasks:oe,subagents:Ee,viewMode:z,selectedMessageIndex:et.selectedIndex,isMessageSelected:et.isSelected,onImageClick:St,onFileClick:Lt,onBashClick:Pt,onViewMarkdown:Cn,scrollContainerRef:P,onScrollTopReached:ce.loadMoreHistory,isLoadingMore:ce.loadingMore,hasMore:ce.hasMore,shouldAutoScroll:je,onUserScroll:ct,pinToBottom:fe,onPinCancel:()=>me(!1),isLoadingHistory:ce.fetchingHistory}),ae&&ye.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:ye.size})})]}),Array.from(ye.values()).map(Ve=>r.jsx(tH,{progress:Ve,defaultExpanded:Ve.status==="working",onAgentClick:Je=>H.selectAgent(Je)},Ve.agentId))]})]})})]}),r.jsx(v9,{selectedAgent:S,selectedAgentId:j,isOpen:le,command:Ke.command,setCommand:Ke.setCommand,forceTextarea:Ke.forceTextarea,setForceTextarea:Ke.setForceTextarea,useTextarea:Ke.useTextarea,attachedFiles:Ke.attachedFiles,setAttachedFiles:Ke.setAttachedFiles,removeAttachedFile:Ke.removeAttachedFile,uploadFile:Ke.uploadFile,pastedTexts:Ke.pastedTexts,expandPastedTexts:Ke.expandPastedTexts,incrementPastedCount:Ke.incrementPastedCount,setPastedTexts:Ke.setPastedTexts,resetPastedCount:Ke.resetPastedCount,handleInputFocus:I.handleInputFocus,handleInputBlur:I.handleInputBlur,pendingPermissions:he,showCompletion:de,completionElapsed:ve,onImageClick:St,inputRef:L,textareaRef:R,isSnapshotView:p,onClearHistory:ce.clearHistory}),r.jsxs("div",{className:"guake-agent-status-bar",children:[!p&&(S==null?void 0:S.isDetached)&&r.jsx(Op,{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 Ve=S.contextStats,Je=!!Ve,ft=Ve?Ve.totalTokens:S.contextUsed||0,wt=Ve?Ve.contextWindow:S.contextLimit||2e5,Nt=Ve?Ve.usedPercent:Math.round(ft/wt*100),qt=Math.round(100-Nt),bn=Nt>=80?"#ff4a4a":Nt>=60?"#ff9e4a":Nt>=40?"#ffd700":"#4aff9e",Mt=(ft/1e3).toFixed(1),zt=(wt/1e3).toFixed(1);return r.jsxs("span",{className:"guake-agent-context",onClick:()=>H.setContextModalAgentId(j),title:e(Je?"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,Nt)}%`,backgroundColor:bn}})}),r.jsxs("span",{className:"context-tokens",style:{color:bn},children:[Mt,"k/",zt,"k"]}),r.jsxs("span",{className:"context-free",children:["(",e("terminal:context.percentFree",{percent:qt}),")"]}),!Je&&r.jsx("span",{className:"context-warning",title:e("terminal:context.clickToFetchStats"),children:"⚠️"})]})})(),r.jsx(xH,{})]})]}),le&&r.jsx("div",{className:"guake-resize-handle",onMouseDown:M,title:e("common:rightPanel.dragToResize")}),r.jsxs("div",{className:"guake-handle",onClick:()=>{le&&H.toggleTerminal()},onDoubleClick:()=>{le||H.toggleTerminal()},style:{top:le?`min(${A}%, calc(100vh - 72px))`:"0"},children:[r.jsx("span",{className:"guake-handle-icon",children:le?"▲":"▼"}),r.jsx("span",{className:"guake-handle-text",children:S.name})]}),$&&r.jsx(GT,{url:$.url,name:$.name,onClose:()=>U(null)}),G&&r.jsx(WT,{state:G,onClose:()=>K(null)}),Z&&r.jsx(S9,{action:Z,selectedAgentId:j,subordinateCount:((Jt=S==null?void 0:S.subordinateIds)==null?void 0:Jt.length)||0,onClose:()=>B(null),onClearHistory:ce.clearHistory}),r.jsx(j9,{}),r.jsx(C9,{}),r.jsx(N9,{agent:S,isOpen:O,onClose:()=>Y(!1)}),!p&&r.jsx(qT,{agent:S,content:ee,onClose:()=>se(null)})]}):null:Ce&&l==="terminal"&&n.size===0?r.jsx("div",{ref:D,className:"guake-terminal open",style:{"--terminal-height":`${A}%`},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")})]})})})}):Ce&&l==="terminal"&&n.size>0?r.jsx("div",{ref:D,className:"guake-terminal open",style:{"--terminal-height":`${A}%`},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 SH(s){return s.trim().replace(/^v/i,"")}function b1(s){const t=SH(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 jH(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 CH(s,e){const t=b1(s),n=b1(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 jH(t.prerelease,n.prerelease)}function NH(s,e){const t=CH(s,e);return t===null?"unknown":t<0?"behind":t>0?"ahead":"equal"}async function AH(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 MH(s,e,t={}){const n=await AH(s,t);return n?{currentVersion:e,latestVersion:n,relation:NH(e,n)}:{currentVersion:e,latestVersion:null,relation:"unknown"}}const TH="tide-commander",Ab="0.71.5";function EH(){const[s,e]=x.useState({currentVersion:Ab,latestVersion:null,relation:"unknown",isChecking:!1}),t=x.useCallback(async()=>{e(a=>({...a,isChecking:!0}));const n=await MH(TH,Ab);e({currentVersion:Ab,latestVersion:n.latestVersion,relation:n.relation,isChecking:!1})},[]);return x.useEffect(()=>{t()},[t]),{...s,refresh:t}}function _H({onFocusAgent:s,onSpawnClick:e,onSpawnBossClick:t,onNewBuildingClick:n,onNewAreaClick:a}){const{t:i}=Ue(["common"]),o=_n(),l=al(),c=si(),d=Sx(),[m,p]=x.useState(!1),f=x.useRef(null),b=x.useRef(null),y=x.useRef(null),w=x.useRef(new Map);x.useEffect(()=>{{p(!1);return}},[l.experimental2DView]),x.useEffect(()=>{const ne=b.current;if(!ne)return;const de=be=>{ne.scrollWidth<=ne.clientWidth||(be.preventDefault(),ne.scrollLeft+=be.deltaY)};return ne.addEventListener("wheel",de,{passive:!1}),()=>ne.removeEventListener("wheel",de)},[]);const[k,S]=x.useState(null),[j,C]=x.useState(new Map),[A,D]=x.useState(null),[M,I]=x.useState(null),E=x.useRef(0),_=x.useMemo(()=>Array.from(o.agents.values()).filter(ne=>!H.isAgentInArchivedArea(ne.id)).sort((ne,de)=>(ne.createdAt||0)-(de.createdAt||0)),[o.agents,o.areas]),{orderedAgents:P,moveAgent:L}=cM(_),R=P,z=x.useMemo(()=>{const ne=new Map;for(const de of R)ne.set(de.id,H.getAreaForAgent(de.id));return ne},[R,o.areas]),F=x.useMemo(()=>{const ne=new Map;for(const be of R){const ve=z.get(be.id)||null,pe=(ve==null?void 0:ve.id)||null;ne.has(pe)||ne.set(pe,{area:ve,agents:[]}),ne.get(pe).agents.push(be)}const de=Array.from(ne.values());return de.sort((be,ve)=>{var pe,Te;return!be.area&&ve.area?1:be.area&&!ve.area?-1:!be.area&&!ve.area?0:(((pe=be.area)==null?void 0:pe.name)||"").localeCompare(((Te=ve.area)==null?void 0:Te.name)||"")}),de},[R,z]);x.useEffect(()=>{const ne=new Map(j);let de=!1;for(const be of R){const ve=j.get(be.id);be.currentTool?(!ve||ve.tool!==be.currentTool)&&(ne.set(be.id,{tool:be.currentTool,key:Date.now()}),de=!0):ve&&setTimeout(()=>{C(pe=>{const Te=new Map(pe);return Te.delete(be.id),Te})},1500)}de&&C(ne)},[R.map(ne=>ne.currentTool).join(",")]),x.useEffect(()=>{const ne=o.lastSelectedAgentId;if(!ne)return;const de=w.current.get(ne),be=b.current;de&&be&&requestAnimationFrame(()=>{const ve=de.getBoundingClientRect(),pe=be.getBoundingClientRect(),Me=ve.left-pe.left+be.scrollLeft+ve.width/2,Le=be.clientWidth;be.scrollTo({left:Me-Le/2,behavior:"smooth"})})},[o.lastSelectedAgentId]);const $=(ne,de)=>{H.setLastSelectionViaDirectClick(!0),de.shiftKey?H.addToSelection(ne.id):H.selectAgent(ne.id),(window.innerWidth<=768||o.terminalOpen)&&H.setTerminalOpen(!0)},U=ne=>{s==null||s(ne.id),H.setTerminalOpen(!0)},G=x.useCallback((ne,de)=>{D(de),ne.dataTransfer.effectAllowed="move",ne.dataTransfer.setData("text/plain",de.id),requestAnimationFrame(()=>{ne.target.classList.add("dragging")})},[]),K=x.useCallback(ne=>{D(null),I(null),E.current=0,ne.target.classList.remove("dragging")},[]),Z=x.useCallback((ne,de)=>{if(ne.preventDefault(),A){const be=z.get(A.id),ve=R[de],pe=ve?z.get(ve.id):null,Te=(be==null?void 0:be.id)??null,Me=(pe==null?void 0:pe.id)??null;ne.dataTransfer.dropEffect=Te===Me?"move":"none"}else ne.dataTransfer.dropEffect="move"},[A,R,z]),B=x.useCallback((ne,de)=>{if(ne.preventDefault(),E.current++,A){const be=z.get(A.id),ve=R[de],pe=ve?z.get(ve.id):null,Te=(be==null?void 0:be.id)??null,Me=(pe==null?void 0:pe.id)??null;I(Te===Me?de:null)}else I(de)},[A,R,z]),ee=x.useCallback(ne=>{E.current--,E.current===0&&I(null)},[]),se=x.useCallback((ne,de)=>{if(ne.preventDefault(),!A)return;const be=R.findIndex(ve=>ve.id===A.id);if(be!==-1&&be!==de){const ve=z.get(A.id),pe=R[de],Te=pe?z.get(pe.id):null,Me=(ve==null?void 0:ve.id)??null,Le=(Te==null?void 0:Te.id)??null;Me===Le&&L(be,de)}D(null),I(null),E.current=0},[A,R,L,z]),O=ne=>{const de=`common:status.${ne}`;return i(de,{defaultValue:i("common:status.unknown")})},{currentVersion:Y,latestVersion:Q,relation:ie,isChecking:J}=EH(),re=Y;let V=0;return r.jsxs("div",{className:"agent-bar",ref:f,children:[r.jsxs("div",{className:"agent-bar-scroll",ref:b,children:[r.jsxs("div",{className:"agent-bar-version",title:Q?`Tide Commander v${re} (npm: v${Q})`:`Tide Commander v${re}`,children:[r.jsxs("span",{children:["v",re]}),ie==="behind"&&Q?r.jsxs("span",{className:"agent-bar-version-badge agent-bar-version-badge-behind",title:`Behind npm latest v${Q}`,children:["npm v",Q]}):ie==="ahead"&&Q?r.jsxs("span",{className:"agent-bar-version-badge agent-bar-version-badge-ahead",title:`Ahead of npm latest v${Q}`,children:["npm v",Q]}):null,ie==="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)"})}):ie==="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)"})}):ie==="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)"})}),m&&r.jsx("button",{className:"agent-bar-hmr-refresh",onClick:lM,title:"Refresh 3D Scene (HMR changes pending)",children:"↻"})]}),r.jsxs("div",{className:"agent-bar-list",ref:y,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(ne=>{var ve,pe,Te,Me,Le;const de=ne.agents,be=!ne.area;return r.jsxs("div",{className:`agent-bar-group ${be?"unassigned":""}`,style:{borderColor:((ve=ne.area)==null?void 0:ve.color)||void 0,background:ne.area?`${ne.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:((pe=ne.area)==null?void 0:pe.color)||"#888"},children:((Te=ne.area)==null?void 0:Te.name)||i("common:agentBar.unassigned")})}),((Me=ne.area)==null?void 0:Me.directories)&&ne.area.directories.length>0&&r.jsx("div",{className:"agent-bar-folders",children:ne.area.directories.map((X,fe)=>r.jsxs("div",{className:"agent-bar-folder-item",onClick:me=>{me.stopPropagation(),H.openFileExplorer(X)},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:X}),r.jsx("div",{className:"agent-bar-folder-tooltip-hint",children:i("common:agentBar.clickToOpen")})]})]},fe))}),de.map(X=>{const fe=V++,me=R.findIndex(ae=>ae.id===X.id),le=o.selectedAgentIds.has(X.id),ce=Zr(X.class,c),Ne=o.lastPrompts.get(X.id),we=j.get(X.id);we&&(Vn[we.tool]||Vn.default),Ne!=null&&Ne.text&&(Ne.text.length>30?Ne.text.substring(0,30)+"":Ne.text);const Ke=(A==null?void 0:A.id)===X.id,he=M===me;return r.jsxs("div",{ref:ae=>{ae?w.current.set(X.id,ae):w.current.delete(X.id)},className:`agent-bar-item ${le?"selected":""} ${X.status} ${X.isBoss?"is-boss":""} ${Ke?"dragging":""} ${he?"drag-over":""}`,draggable:!0,onDragStart:ae=>G(ae,X),onDragEnd:K,onDragOver:ae=>Z(ae,me),onDragEnter:ae=>B(ae,me),onDragLeave:ee,onDrop:ae=>se(ae,me),onClick:ae=>$(X,ae),onDoubleClick:()=>U(X),onMouseEnter:()=>S(X),onMouseLeave:()=>S(null),title:`${X.name} (${fe+1}) - Drag to reorder within group`,children:[r.jsxs("div",{className:"agent-bar-avatar",children:[r.jsx("span",{className:"agent-bar-icon",children:ce.icon}),r.jsx("span",{className:"agent-bar-status",style:{backgroundColor:iy(X.status)}}),d.has(X.id)&&r.jsx("span",{className:"agent-bar-notification-badge",title:"New output available - click to view"}),X.status==="idle"&&X.lastActivity>0&&r.jsx("span",{className:"agent-bar-idle-clock",style:{color:am(X.lastActivity)},title:im(X.lastActivity),children:"⏱"})]}),r.jsxs("span",{className:"agent-bar-hotkey",title:`Ctrl+${fe+1}`,children:["^",fe+1]})]},X.id)})]},((Le=ne.area)==null?void 0:Le.id)||"unassigned")})]})]}),Array.from(j.entries()).map(([ne,de])=>{const be=w.current.get(ne);if(!be)return null;const ve=be.getBoundingClientRect(),pe=Vn[de.tool]||Vn.default;return r.jsxs("div",{className:"agent-bar-tool-bubble",title:de.tool,style:{position:"fixed",left:ve.left+ve.width/2,bottom:window.innerHeight-ve.top+8},children:[r.jsx("span",{className:"agent-bar-tool-icon",children:pe}),r.jsx("span",{className:"agent-bar-tool-name",children:de.tool})]},`tool-${ne}-${de.key}`)}),k&&(()=>{const ne=H.getAreaForAgent(k.id),de=o.lastPrompts.get(k.id),be=Zr(k.class,c),ve=H.getAgentSupervisorHistory(k.id),pe=ve.length>0?ve[ve.length-1]:void 0,Te=Date.now()-(k.createdAt||Date.now()),Me=Math.floor(Te/6e4),Le=Math.floor(Me/60),X=Le>0?`${Le}h ${Me%60}m`:`${Me}m`,fe=we=>we>=1e6?`${(we/1e6).toFixed(1)}M`:we>=1e3?`${(we/1e3).toFixed(1)}K`:we.toString(),me=k.contextLimit>0?Math.round(k.contextUsed/k.contextLimit*100):0,le=we=>{switch(we){case"on_track":return"#4aff9e";case"completed":return"#4a9eff";case"stalled":return"#ff9e4a";case"blocked":return"#ff4a4a";case"idle":return"#888888";default:return"#888888"}},ce=w.current.get(k.id),Ne={};if(ce){const we=ce.getBoundingClientRect();Ne.position="fixed",Ne.left=we.left+we.width/2,Ne.bottom=window.innerHeight-we.top+12}return r.jsxs("div",{className:"agent-bar-tooltip",style:Ne,children:[r.jsxs("div",{className:"agent-bar-tooltip-header",children:[r.jsx("span",{className:"agent-bar-tooltip-icon",children:be.icon}),r.jsxs("span",{className:"agent-bar-tooltip-name",children:[r.jsx("img",{src:k.provider==="codex"?"/assets/codex.png":"/assets/claude.png",alt:k.provider,className:"agent-bar-provider-icon",title:k.provider==="codex"?"Codex Agent":"Claude Agent"}),k.name]}),r.jsx("span",{className:"agent-bar-tooltip-status",style:{color:iy(k.status)},children:O(k.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:[k.class," — ",be.description]})]}),ne&&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:ne.color},children:ne.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:k.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:X})]}),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:[fe(k.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:me>80?"#ff4a4a":me>60?"#ff9e4a":void 0},children:[fe(k.contextUsed)," / ",fe(k.contextLimit)," (",me,"%)"]})]}),k.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:[Vn[k.currentTool]||Vn.default," ",k.currentTool]})]}),k.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:[k.currentTask.substring(0,150),k.currentTask.length>150?"...":""]})]}),k.lastAssignedTask&&!k.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:[k.lastAssignedTask.substring(0,200),k.lastAssignedTask.length>200?"...":""]})]}),de&&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:[de.text.substring(0,300),de.text.length>300?"...":""]})]}),pe&&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:le(pe.analysis.progress)},children:pe.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:pe.analysis.statusDescription})]}),pe.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:[pe.analysis.recentWorkSummary.substring(0,300),pe.analysis.recentWorkSummary.length>300?"...":""]})]}),pe.analysis.concerns&&pe.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:pe.analysis.concerns.join("; ")})]})]})]})]})})()]})}function DH({activeTool:s,onExit:e}){const{t}=Ue(["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 PH={idle:"common:status.idle",working:"common:status.working",waiting:"common:status.waiting",error:"common:status.error",offline:"common:status.offline"},Mb=s=>s>=1e6?`${(s/1e6).toFixed(1)}M`:s>=1e3?`${(s/1e3).toFixed(1)}K`:s.toString(),RH=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"}},LH=x.memo(function({agent:e,screenPos:t,onClose:n}){const{t:a}=Ue(["common"]),i=si(),o=H.getAreaForAgent(e.id),l=H.getState().lastPrompts.get(e.id),c=Zr(e.class,i),d=H.getAgentSupervisorHistory(e.id),m=d.length>0?d[d.length-1]:void 0,p=Date.now()-(e.createdAt||Date.now()),f=Math.floor(p/6e4),b=Math.floor(f/60),y=b>0?`${b}h ${f%60}m`:`${f}m`,w=e.contextLimit>0?Math.round(e.contextUsed/e.contextLimit*100):0,k=x.useMemo(()=>{let C=t.x-150,A=t.y-320-10;return typeof window<"u"&&(C<10?C=10:C+300>window.innerWidth-10&&(C=window.innerWidth-300-10),A<10&&(A=t.y+10)),{position:"fixed",left:C,top:A,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:iy(e.status)},children:a(PH[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:[Mb(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:[Mb(e.contextUsed)," / ",Mb(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:[Vn[e.currentTool]||Vn.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?"...":""]})]}),m&&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:RH(m.analysis.progress)},children:m.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:m.analysis.statusDescription})]}),m.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:[m.analysis.recentWorkSummary.substring(0,300),m.analysis.recentWorkSummary.length>300?"...":""]})]}),m.analysis.concerns&&m.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:m.analysis.concerns.join("; ")})]})]})]})]})});function y1(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 x1(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 v1={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 OH(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:v1[l]&&(a=v1[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 IH=x.memo(function({building:e,screenPos:t,onClose:n,onOpenSettings:a,onOpenLogsModal:i,onOpenUrlInModal:o}){var U,G,K,Z,B,ee,se,O,Y,Q,ie,J,re,V,ne,de,be,ve,pe,Te;const{t:l}=Ue(["terminal","common"]),[c,d]=x.useState(!1),[m,p]=x.useState(null),[f,b]=x.useState(!1),y=x.useRef(null),w=x.useRef(m);w.current=m;const{buildingLogs:k}=_n(),S=H.getBuildingLogs(e.id),j=(U=e.pm2)==null?void 0:U.enabled,C=(G=e.docker)==null?void 0:G.enabled,A=x.useRef(null),D=x.useRef(null),M=x.useCallback(Me=>{Me.preventDefault();const Le=w.current?w.current.x:0,X=w.current?w.current.y:0;y.current={mouseX:Me.clientX,mouseY:Me.clientY,popupX:Le,popupY:X},b(!0),A.current=fe=>{if(!y.current)return;const me=fe.clientX-y.current.mouseX,le=fe.clientY-y.current.mouseY;p({x:y.current.popupX+me,y:y.current.popupY+le})},D.current=()=>{b(!1),y.current=null,A.current&&document.removeEventListener("mousemove",A.current),D.current&&document.removeEventListener("mouseup",D.current)},document.addEventListener("mousemove",A.current),document.addEventListener("mouseup",D.current)},[]);x.useEffect(()=>()=>{A.current&&document.removeEventListener("mousemove",A.current),D.current&&document.removeEventListener("mouseup",D.current)},[]);const I=Me=>{if(Me==="logs"){if((j||C)&&i){i();return}H.sendBuildingCommand(e.id,Me),d(!0)}else H.sendBuildingCommand(e.id,Me)},E=(Me,Le)=>{if(Me){const X=`http://localhost:${Me}`;Le&&o?o(X):window.open(X,"_blank")}},_=((K=e.pm2Status)==null?void 0:K.ports)||[],P=((B=(Z=e.dockerStatus)==null?void 0:Z.ports)==null?void 0:B.map(Me=>Me.host))||[],L=j?_:C?P:[],R=j?!!((ee=e.pm2)!=null&&ee.script):C?!!((se=e.docker)!=null&&se.image)||((O=e.docker)==null?void 0:O.mode)==="compose"||((Y=e.docker)==null?void 0:Y.mode)==="existing":!!((Q=e.commands)!=null&&Q.start),z=j?!!((ie=e.pm2)!=null&&ie.script):C?!0:!!((J=e.commands)!=null&&J.stop),F=j?!!((re=e.pm2)!=null&&re.script):C?!0:!!((V=e.commands)!=null&&V.restart),$=x.useMemo(()=>{const Le=c?400:250;let X=t.x+20,fe=t.y-80;return typeof window<"u"&&!m&&(t.x+20+280>window.innerWidth&&(X=t.x-280-20),t.y-80<0?fe=10:t.y-80+Le>window.innerHeight&&(fe=window.innerHeight-Le-10)),{position:"fixed",left:X+((m==null?void 0:m.x)||0),top:fe+((m==null?void 0:m.y)||0),zIndex:1e3,cursor:f?"grabbing":void 0}},[t.x,t.y,c,m,f]);return r.jsxs("div",{className:"building-action-popup",style:$,onClick:Me=>Me.stopPropagation(),children:[r.jsxs("div",{className:`building-popup-header ${f?"dragging":""}`,onMouseDown:M,children:[r.jsx("span",{className:"building-popup-name",children:e.name}),L.length>0&&r.jsx("span",{className:"building-popup-ports",children:L.map(Me=>r.jsxs("a",{href:`http://localhost:${Me}`,className:"building-popup-port-link",onClick:Le=>{Le.preventDefault(),Le.stopPropagation(),E(Me,Le.altKey)},onMouseDown:Le=>Le.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:[((ne=e.pm2Status.cpu)==null?void 0:ne.toFixed(1))||"0","%"]})]}),r.jsxs("span",{className:"metric",children:[r.jsx("span",{className:"label",children:"MEM"}),r.jsx("span",{className:"value",children:y1(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:x1(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:y1(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:x1(e.dockerStatus.startedAt)})]})]}),C&&((de=e.dockerStatus)==null?void 0:de.services)&&e.dockerStatus.services.length>0&&r.jsx("div",{className:"building-popup-services",children:e.dockerStatus.services.map((Me,Le)=>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})]},Le))}),(e.lastError||j&&((be=e.pm2Status)==null?void 0:be.status)==="errored"||C&&((ve=e.dockerStatus)==null?void 0:ve.status)==="dead")&&r.jsxs("div",{className:"building-popup-error",children:[e.lastError||l("terminal:building.processFailedToStart"),j&&((pe=e.pm2Status)==null?void 0:pe.restarts)&&e.pm2Status.restarts>5&&r.jsxs("span",{className:"error-hint",children:[" - ",l("terminal:building.checkLogsOrConfig")]}),C&&((Te=e.dockerStatus)==null?void 0:Te.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:()=>I("start"),disabled:!R||e.status==="running"||e.status==="starting",title:l(R?"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:()=>I("stop"),disabled:!z||e.status==="stopped"||e.status==="stopping",title:l(z?"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:()=>I("restart"),disabled:!F,title:l(F?"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:()=>I("logs"),title:l("terminal:buildingAction.viewLogs"),children:[r.jsx("span",{className:"icon",children:"📄"}),l("terminal:logs.title")]}),L.length===1&&r.jsxs("button",{className:"action-btn open-url",onClick:Me=>E(L[0],Me.altKey),title:`Open http://localhost:${L[0]} (Alt+Click for modal)`,children:[r.jsx("span",{className:"icon",children:"🔗"}),l("terminal:buildingAction.openInBrowser")]}),L.length>1&&r.jsxs("div",{className:"action-btn-group",children:[r.jsxs("span",{className:"action-btn-label",children:[l("terminal:buildingAction.openInBrowser"),":"]}),L.map(Me=>r.jsxs("button",{className:"action-btn open-url port-btn",onClick:Le=>E(Me,Le.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,Le)=>r.jsx("pre",{children:OH(Me)},Le))})]}),r.jsx("button",{className:"building-popup-settings",onClick:a,children:l("terminal:buildingAction.fullSettings")})]})});function BH(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 FH(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 zH=x.memo(function({building:e,screenPos:t,onClose:n,onOpenSettings:a,onOpenLogsModal:i,onOpenUrlInModal:o}){const{t:l}=Ue(["terminal","common"]),[c,d]=x.useState(null),[m,p]=x.useState(!1),f=x.useRef(null),b=x.useRef(c);b.current=c;const{buildings:y}=_n(),k=(e.subordinateBuildingIds||[]).map(_=>y.get(_)).filter(_=>_!==void 0),S=x.useRef(null),j=x.useRef(null),C=x.useCallback(_=>{_.preventDefault();const P=b.current?b.current.x:0,L=b.current?b.current.y:0;f.current={mouseX:_.clientX,mouseY:_.clientY,popupX:P,popupY:L},p(!0),S.current=R=>{if(!f.current)return;const z=R.clientX-f.current.mouseX,F=R.clientY-f.current.mouseY;d({x:f.current.popupX+z,y:f.current.popupY+F})},j.current=()=>{p(!1),f.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 A=_=>{H.sendBossBuildingCommand(e.id,_)},D=k.reduce((_,P)=>(_[P.status]=(_[P.status]||0)+1,_),{}),M=k.some(_=>{var P;return(P=_.pm2)==null?void 0:P.enabled}),I=(_,P)=>{const L=`http://localhost:${_}`;P&&o?o(L):window.open(L,"_blank")},E=x.useMemo(()=>{let L=t.x+20,R=t.y-80;return typeof window<"u"&&!c&&(t.x+20+340>window.innerWidth&&(L=t.x-340-20),t.y-80<0?R=10:t.y-80+350>window.innerHeight&&(R=window.innerHeight-350-10)),{position:"fixed",left:L+((c==null?void 0:c.x)||0),top:R+((c==null?void 0:c.y)||0),zIndex:1e3,cursor:m?"grabbing":void 0}},[t.x,t.y,c,m]);return r.jsxs("div",{className:"building-action-popup boss-building-popup",style:E,onClick:_=>_.stopPropagation(),children:[r.jsxs("div",{className:`building-popup-header boss-header ${m?"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(([_,P])=>r.jsxs("span",{className:"status-badge",style:{backgroundColor:Xr[_]||"#666"},children:[P," ",_]},_)),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(_=>{var P,L,R;return r.jsxs("div",{className:"subordinate-item",children:[r.jsx("span",{className:"sub-status-dot",style:{backgroundColor:Xr[_.status]}}),r.jsx("span",{className:"sub-name",children:_.name}),((P=_.pm2Status)==null?void 0:P.ports)&&_.pm2Status.ports.length>0&&r.jsx("span",{className:"sub-port",children:_.pm2Status.ports.map(z=>r.jsxs("a",{href:`http://localhost:${z}`,className:"building-popup-port-link",onClick:F=>{F.preventDefault(),F.stopPropagation(),I(z,F.altKey)},title:`Open http://localhost:${z} (Alt+Click for modal)`,children:[":",z]},z))}),_.pm2Status&&r.jsxs("span",{className:"sub-metrics",children:[(L=_.pm2Status.cpu)==null?void 0:L.toFixed(0),"% | ",BH(_.pm2Status.memory||0)]}),((R=_.pm2Status)==null?void 0:R.uptime)&&r.jsx("span",{className:"sub-uptime",children:FH(_.pm2Status.uptime)})]},_.id)})}),r.jsxs("div",{className:"building-popup-actions boss-actions",children:[r.jsxs("button",{className:"action-btn start",onClick:()=>A("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:()=>A("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:()=>A("restart_all"),disabled:k.length===0,title:l("terminal:building.restartAllSubs"),children:[r.jsx("span",{className:"icon",children:"↺"}),l("terminal:building.restartAll")]}),M&&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")})]})}),$H=x.memo(function({building:e,screenPos:t,onClose:n,onOpenSettings:a,onOpenDatabasePanel:i}){var D;const{t:o}=Ue(["terminal","common"]),[l,c]=x.useState(null),[d,m]=x.useState(!1),p=x.useRef(null),f=x.useRef(l);f.current=l;const b=dm(e.id),y=((D=e.database)==null?void 0:D.connections)??[],w=x.useRef(null),k=x.useRef(null),S=x.useCallback(M=>{M.preventDefault();const I=f.current?f.current.x:0,E=f.current?f.current.y:0;p.current={mouseX:M.clientX,mouseY:M.clientY,popupX:I,popupY:E},m(!0),w.current=_=>{if(!p.current)return;const P=_.clientX-p.current.mouseX,L=_.clientY-p.current.mouseY;c({x:p.current.popupX+P,y:p.current.popupY+L})},k.current=()=>{m(!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=M=>{H.testDatabaseConnection(e.id,M)},C=M=>b.connectionStatus.get(M),A=x.useMemo(()=>{let E=t.x+20,_=t.y-80;return typeof window<"u"&&!l&&(t.x+20+320>window.innerWidth&&(E=t.x-320-20),t.y-80<0?_=10:t.y-80+300>window.innerHeight&&(_=window.innerHeight-300-10)),{position:"fixed",left:E+((l==null?void 0:l.x)||0),top:_+((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:A,onClick:M=>M.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(M=>{const I=C(M.id);return r.jsxs("div",{className:"database-connection-item",children:[r.jsx("span",{className:"conn-engine",children:M.engine==="mysql"?"🐬":"🐘"}),r.jsx("span",{className:"conn-name",children:M.name}),r.jsxs("span",{className:"conn-host",children:[M.host,":",M.port]}),I&&r.jsx("span",{className:`conn-status ${I.connected?"connected":"disconnected"}`,children:I.connected?"●":"○"}),r.jsx("button",{className:"conn-test-btn",onClick:()=>j(M.id),title:o("terminal:building.testConnection"),children:"↻"})]},M.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(M=>j(M.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")})]})}),HH=({building:s,connections:e,activeConnectionId:t,activeDatabase:n,collapsed:a,onToggleCollapse:i,onConnectionChange:o,onDatabaseChange:l,onInsertTable:c,onSelectTableQuery:d})=>{const{t:m}=Ue(["terminal"]),p=dm(s.id),[f,b]=x.useState(new Set),[y,w]=x.useState(""),[k,S]=x.useState(!1),[j,C]=x.useState(null),A=x.useRef(null),D=x.useRef(null),M=t?p.databases.get(t)??[]:[],I=t&&n?`${t}:${n}`:"",E=I?p.tables.get(I)??[]:[],_=t?p.connectionStatus.get(t):void 0,P=x.useMemo(()=>{if(!y.trim())return M;const z=y.toLowerCase();return M.filter(F=>F.toLowerCase().includes(z))},[M,y]);x.useEffect(()=>{const z=F=>{D.current&&!D.current.contains(F.target)&&S(!1)};return k&&document.addEventListener("mousedown",z),()=>document.removeEventListener("mousedown",z)},[k]),x.useEffect(()=>{t&&!_&&H.testDatabaseConnection(s.id,t)},[s.id,t,_]),x.useEffect(()=>{t&&(_!=null&&_.connected)&&M.length===0&&H.listDatabases(s.id,t)},[s.id,t,_==null?void 0:_.connected,M.length]),x.useEffect(()=>{t&&n&&E.length===0&&H.listTables(s.id,t,n)},[s.id,t,n,E.length]),x.useEffect(()=>{C(null)},[t,n]);const L=x.useCallback(z=>{b(F=>{const $=new Set(F);if($.has(z))$.delete(z);else if($.add(z),t&&n){const U=`${t}:${n}:${z}`;p.tableSchemas.has(U)||H.getTableSchema(s.id,t,n,z)}return $})},[s.id,t,n,p.tableSchemas]),R=z=>{if(!t||!n)return null;const F=`${t}:${n}:${z}`;return p.tableSchemas.get(F)};return a?r.jsx("div",{className:"database-sidebar database-sidebar--collapsed",children:r.jsx("button",{className:"database-sidebar__toggle",onClick:i,title:m("terminal:database.expandSidebar"),children:"»"})}):r.jsxs("div",{className:"database-sidebar",children:[r.jsxs("div",{className:"database-sidebar__header",children:[r.jsx("span",{children:m("terminal:database.explorer")}),r.jsx("button",{className:"database-sidebar__toggle",onClick:i,title:m("terminal:database.collapseSidebar"),children:"«"})]}),r.jsxs("div",{className:"database-sidebar__section",children:[r.jsx("div",{className:"database-sidebar__section-title",children:m("terminal:database.connection")}),r.jsx("select",{className:"database-sidebar__select",value:t||"",onChange:z=>o(z.target.value),children:e.length===0?r.jsx("option",{value:"",children:m("terminal:database.noConnections")}):e.map(z=>r.jsxs("option",{value:z.id,children:[z.engine==="mysql"?"🐬":"🐘"," ",z.name]},z.id))}),_&&r.jsx("div",{className:`database-sidebar__status ${_.connected?"database-sidebar__status--connected":"database-sidebar__status--error"}`,children:_.connected?r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"database-sidebar__status-icon",children:"✓"}),m("terminal:database.connected"),_.serverVersion&&r.jsxs("span",{className:"database-sidebar__version",children:["(",_.serverVersion,")"]})]}):r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"database-sidebar__status-icon",children:"✗"}),_.error||m("terminal:database.disconnected")]})})]}),M.length>0&&r.jsxs("div",{className:"database-sidebar__section",children:[r.jsx("div",{className:"database-sidebar__section-title",children:m("terminal:database.databaseTitle")}),r.jsxs("div",{className:"database-sidebar__searchable-select",ref:D,children:[r.jsx("input",{ref:A,className:"database-sidebar__search-input",type:"text",value:k?y:n||"",placeholder:m("terminal:database.selectDatabase"),onChange:z=>{w(z.target.value),k||S(!0)},onFocus:()=>{S(!0),w("")},onKeyDown:z=>{var F,$;z.key==="Escape"?(S(!1),w(""),(F=A.current)==null||F.blur()):z.key==="Enter"&&P.length===1&&(l(P[0]),S(!1),w(""),($=A.current)==null||$.blur())}}),k&&r.jsx("div",{className:"database-sidebar__dropdown",children:P.length===0?r.jsx("div",{className:"database-sidebar__dropdown-empty",children:"No matches"}):P.map(z=>r.jsx("div",{className:`database-sidebar__dropdown-item ${z===n?"database-sidebar__dropdown-item--active":""}`,onMouseDown:F=>{F.preventDefault(),l(z),S(!1),w("")},children:z},z))})]})]}),E.length>0&&r.jsxs("div",{className:"database-sidebar__section database-sidebar__section--tables",children:[r.jsx("div",{className:"database-sidebar__section-title",children:m("terminal:database.tablesCount",{count:E.length})}),r.jsx("div",{className:"database-sidebar__tables",children:E.map(z=>{const F=f.has(z.name),$=F?R(z.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:()=>L(z.name),title:F?"Collapse table schema":"Expand table schema",children:F?"▼":"▶"}),r.jsx("span",{className:"database-sidebar__table-icon",children:z.type==="view"?"👁":"📋"}),r.jsx("span",{className:`database-sidebar__table-name ${j===z.name?"database-sidebar__table-name--selected":""}`,onClick:()=>C(z.name),onDoubleClick:()=>{C(z.name),d(z.name)},children:z.name}),r.jsx("button",{className:"database-sidebar__table-insert",onClick:U=>{U.stopPropagation(),c(z.name)},title:m("terminal:database.insertTableName"),children:"+"})]}),F&&$&&r.jsx("div",{className:"database-sidebar__table-columns",children:$.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))})]},z.name)})})]})]})};function Zx(s){const e=[];let t=!1,n=!1,a=!1,i=!1,o=0;for(let c=0;c<s.length;c++){const d=s[c],m=s[c+1];if(a){d===`
232
232
  `&&(a=!1);continue}if(i){d==="*"&&m==="/"&&(i=!1,c++);continue}if(t){if(d==="'"&&m==="'"){c++;continue}d==="'"&&(t=!1);continue}if(n){if(d==='"'&&m==='"'){c++;continue}d==='"'&&(n=!1);continue}if(d==="-"&&m==="-"){a=!0,c++;continue}if(d==="/"&&m==="*"){i=!0,c++;continue}if(d==="'"){t=!0;continue}if(d==='"'){n=!0;continue}if(d===";"){const p=s.slice(o,c).trim();p&&e.push({sql:p,start:o,end:c}),o=c+1}}const l=s.slice(o).trim();return l&&e.push({sql:l,start:o,end:s.length}),e}function UH(s,e){const t=Zx(s);if(t.length===0)return null;for(const n of t)if(e>=n.start&&e<=n.end)return n.sql;return t[t.length-1].sql}const GH=({query:s,onChange:e,onExecute:t,isExecuting:n,disabled:a,autoFocus:i=!0})=>{const{t:o}=Ue(["terminal"]),l=x.useRef(null),c=x.useRef(null),d=x.useRef(!1),m="query-editor-height",p=80,f=800,[b,y]=x.useState(()=>{try{const I=localStorage.getItem(m);if(I){const E=Number(I);if(E>=p&&E<=f)return E}}catch{}return 150}),w=x.useCallback(I=>{try{localStorage.setItem(m,String(I))}catch{}},[]),k=x.useCallback(I=>{I.preventDefault(),d.current=!0;const E=I.clientY,_=b,P=R=>{const z=R.clientY-E,F=Math.max(p,Math.min(f,_+z));y(F)},L=()=>{var z;d.current=!1,document.removeEventListener("mousemove",P),document.removeEventListener("mouseup",L),document.body.style.cursor="",document.body.style.userSelect="";const R=(z=l.current)==null?void 0:z.parentElement;R&&w(R.getBoundingClientRect().height)};document.addEventListener("mousemove",P),document.addEventListener("mouseup",L),document.body.style.cursor="row-resize",document.body.style.userSelect="none"},[b,w]);x.useEffect(()=>{if(i&&!a&&l.current){const I=setTimeout(()=>{var E;(E=l.current)==null||E.focus()},100);return()=>clearTimeout(I)}},[i,a]);const S=x.useCallback(I=>{const E=I.currentTarget;c.current&&(c.current.scrollLeft=E.scrollLeft,c.current.scrollTop=E.scrollTop)},[]),j=x.useMemo(()=>Zx(s).length>1,[s]),C=x.useCallback(I=>{if((I.ctrlKey||I.metaKey)&&I.shiftKey&&I.key==="Enter"){I.preventDefault(),!a&&!n&&t("all");return}if((I.ctrlKey||I.metaKey)&&I.key==="Enter"&&(I.preventDefault(),!a&&!n&&t("cursor")),I.key==="Tab"){I.preventDefault();const E=I.currentTarget,_=E.selectionStart,P=E.selectionEnd,L=s.substring(0,_)+" "+s.substring(P);e(L),setTimeout(()=>{E.selectionStart=E.selectionEnd=_+2},0)}},[s,e,t,a,n]),A=x.useMemo(()=>{if(!s)return"";try{return tl.highlight(s,tl.languages.sql,"sql")}catch{return s}},[s]),D=x.useMemo(()=>s.split(`
233
233
  `).map((E,_)=>_+1),[s]),M=x.useCallback(()=>{var I;return((I=l.current)==null?void 0:I.selectionStart)??0},[]);return r.jsxs("div",{className:"query-editor",children:[r.jsxs("div",{className:"query-editor__toolbar",children:[r.jsxs("div",{className:"query-editor__buttons",children:[r.jsx("button",{className:"query-editor__execute",onClick:()=>t("cursor"),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(j?"terminal:database.runAtCursor":"terminal:database.runQuery")]})}),j&&r.jsxs("button",{className:"query-editor__execute-cursor",onClick:()=>t("all"),disabled:a||n||!s.trim(),title:o("terminal:database.executeCursorShortcut"),children:[r.jsx("span",{className:"query-editor__cursor-icon",children:"▶▶"}),o("terminal:database.runAll")]})]}),r.jsx("div",{className:"query-editor__hint",children:o(j?"terminal:database.pressCtrlEnterMulti":"terminal:database.pressCtrlEnter")})]}),r.jsxs("div",{className:"query-editor__input-wrapper",children:[r.jsx("div",{className:"query-editor__line-numbers",children:D.map(I=>r.jsx("span",{children:I},I))}),r.jsxs("div",{className:"query-editor__editor",style:{height:b},children:[r.jsx("pre",{ref:c,className:"query-editor__highlight","aria-hidden":"true",dangerouslySetInnerHTML:{__html:A+`
234
234
  `}}),r.jsx("textarea",{ref:l,className:"query-editor__textarea",value:s,onChange:I=>e(I.target.value),onKeyDown:C,onScroll:S,placeholder:o(a?"terminal:database.selectDbPlaceholder":"terminal:database.enterQueryPlaceholder"),disabled:a,spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off","data-cursor-pos":M()})]})]}),r.jsx("div",{className:"query-editor__resize-handle",onMouseDown:k})]})};function tE(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=tE(s[e]))&&(n&&(n+=" "),n+=t)}else for(t in s)s[t]&&(n&&(n+=" "),n+=t);return n}function fs(){for(var s,e,t=0,n="",a=arguments.length;t<a;t++)(s=arguments[t])&&(e=tE(s))&&(n&&(n+=" "),n+=e);return n}const nE=6048e5,WH=864e5,wm=6e4,km=36e5,qH=1e3,w1=Symbol.for("constructDateFrom");function jn(s,e){return typeof s=="function"?s(e):s&&typeof s=="object"&&w1 in s?s[w1](e):s instanceof Date?new s.constructor(e):new Date(e)}function xt(s,e){return jn(e||s,s)}function Qa(s,e,t){const n=xt(s,t==null?void 0:t.in);return isNaN(e)?jn((t==null?void 0:t.in)||s,NaN):(e&&n.setDate(n.getDate()+e),n)}function ei(s,e,t){const n=xt(s,t==null?void 0:t.in);if(isNaN(e))return jn(s,NaN);if(!e)return n;const a=n.getDate(),i=jn(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 sE(s,e,t){return jn(s,+xt(s)+e)}function YH(s,e,t){return sE(s,e*km)}let VH={};function rl(){return VH}function ir(s,e){var l,c,d,m;const t=rl(),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??((m=(d=t.locale)==null?void 0:d.options)==null?void 0:m.weekStartsOn)??0,a=xt(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 gc(s,e){return ir(s,{...e,weekStartsOn:1})}function aE(s,e){const t=xt(s,e==null?void 0:e.in),n=t.getFullYear(),a=jn(t,0);a.setFullYear(n+1,0,4),a.setHours(0,0,0,0);const i=gc(a),o=jn(t,0);o.setFullYear(n,0,4),o.setHours(0,0,0,0);const l=gc(o);return t.getTime()>=i.getTime()?n+1:t.getTime()>=l.getTime()?n:n-1}function zp(s){const e=xt(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 ur(s,...e){const t=jn.bind(null,e.find(n=>typeof n=="object"));return e.map(t)}function nl(s,e){const t=xt(s,e==null?void 0:e.in);return t.setHours(0,0,0,0),t}function bc(s,e,t){const[n,a]=ur(t==null?void 0:t.in,s,e),i=nl(n),o=nl(a),l=+i-zp(i),c=+o-zp(o);return Math.round((l-c)/WH)}function KH(s,e){const t=aE(s,e),n=jn(s,0);return n.setFullYear(t,0,4),n.setHours(0,0,0,0),gc(n)}function od(s,e,t){const n=xt(s,t==null?void 0:t.in);return n.setTime(n.getTime()+e*wm),n}function Qx(s,e,t){return ei(s,e*3,t)}function XH(s,e,t){return sE(s,e*1e3)}function $p(s,e,t){return Qa(s,e*7,t)}function Ja(s,e,t){return ei(s,e*12,t)}function k1(s,e){let t,n=e==null?void 0:e.in;return s.forEach(a=>{!n&&typeof a=="object"&&(n=jn.bind(null,a));const i=xt(a,n);(!t||t<i||isNaN(+i))&&(t=i)}),jn(n,t||NaN)}function S1(s,e){let t,n=e==null?void 0:e.in;return s.forEach(a=>{!n&&typeof a=="object"&&(n=jn.bind(null,a));const i=xt(a,n);(!t||t>i||isNaN(+i))&&(t=i)}),jn(n,t||NaN)}function ZH(s,e,t){const[n,a]=ur(t==null?void 0:t.in,s,e);return+nl(n)==+nl(a)}function Si(s){return s instanceof Date||typeof s=="object"&&Object.prototype.toString.call(s)==="[object Date]"}function yc(s){return!(!Si(s)&&typeof s!="number"||isNaN(+xt(s)))}function Hp(s,e,t){const[n,a]=ur(t==null?void 0:t.in,s,e),i=n.getFullYear()-a.getFullYear(),o=n.getMonth()-a.getMonth();return i*12+o}function Hr(s,e){const t=xt(s,e==null?void 0:e.in);return Math.trunc(t.getMonth()/3)+1}function Up(s,e,t){const[n,a]=ur(t==null?void 0:t.in,s,e),i=n.getFullYear()-a.getFullYear(),o=Hr(n)-Hr(a);return i*4+o}function Gp(s,e,t){const[n,a]=ur(t==null?void 0:t.in,s,e);return n.getFullYear()-a.getFullYear()}function QH(s,e,t){const[n,a]=ur(t==null?void 0:t.in,s,e),i=j1(n,a),o=Math.abs(bc(n,a));n.setDate(n.getDate()-i*o);const l=+(j1(n,a)===-i),c=i*(o-l);return c===0?0:c}function j1(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 iE(s,e){const t=xt(s,e==null?void 0:e.in);return t.setHours(23,59,59,999),t}function rE(s,e){const t=xt(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 By(s,e){const t=xt(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 oE(s,e){const t=xt(s,e==null?void 0:e.in);return t.setDate(1),t.setHours(0,0,0,0),t}function lE(s,e){const t=xt(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 Sm(s,e){const t=xt(s,e==null?void 0:e.in);return t.setFullYear(t.getFullYear(),0,1),t.setHours(0,0,0,0),t}function JH(s,e){var l,c;const t=rl(),n=t.weekStartsOn??((c=(l=t.locale)==null?void 0:l.options)==null?void 0:c.weekStartsOn)??0,a=xt(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 eU={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"}},tU=(s,e,t)=>{let n;const a=eU[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 Tb(s){return(e={})=>{const t=e.width?String(e.width):s.defaultWidth;return s.formats[t]||s.formats[s.defaultWidth]}}const nU={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},sU={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},aU={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},iU={date:Tb({formats:nU,defaultWidth:"full"}),time:Tb({formats:sU,defaultWidth:"full"}),dateTime:Tb({formats:aU,defaultWidth:"full"})},rU={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},oU=(s,e,t,n)=>rU[s];function Eu(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 lU={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},cU={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},uU={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"]},dU={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"]},hU={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"}},pU={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"}},mU=(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"},fU={ordinalNumber:mU,era:Eu({values:lU,defaultWidth:"wide"}),quarter:Eu({values:cU,defaultWidth:"wide",argumentCallback:s=>s-1}),month:Eu({values:uU,defaultWidth:"wide"}),day:Eu({values:dU,defaultWidth:"wide"}),dayPeriod:Eu({values:hU,defaultWidth:"wide",formattingValues:pU,defaultFormattingWidth:"wide"})};function _u(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)?bU(l,p=>p.test(o)):gU(l,p=>p.test(o));let d;d=s.valueCallback?s.valueCallback(c):c,d=t.valueCallback?t.valueCallback(d):d;const m=e.slice(o.length);return{value:d,rest:m}}}function gU(s,e){for(const t in s)if(Object.prototype.hasOwnProperty.call(s,t)&&e(s[t]))return t}function bU(s,e){for(let t=0;t<s.length;t++)if(e(s[t]))return t}function yU(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 xU=/^(\d+)(th|st|nd|rd)?/i,vU=/\d+/i,wU={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},kU={any:[/^b/i,/^(a|c)/i]},SU={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},jU={any:[/1/i,/2/i,/3/i,/4/i]},CU={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},NU={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]},AU={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},MU={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]},TU={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},EU={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}},_U={ordinalNumber:yU({matchPattern:xU,parsePattern:vU,valueCallback:s=>parseInt(s,10)}),era:_u({matchPatterns:wU,defaultMatchWidth:"wide",parsePatterns:kU,defaultParseWidth:"any"}),quarter:_u({matchPatterns:SU,defaultMatchWidth:"wide",parsePatterns:jU,defaultParseWidth:"any",valueCallback:s=>s+1}),month:_u({matchPatterns:CU,defaultMatchWidth:"wide",parsePatterns:NU,defaultParseWidth:"any"}),day:_u({matchPatterns:AU,defaultMatchWidth:"wide",parsePatterns:MU,defaultParseWidth:"any"}),dayPeriod:_u({matchPatterns:TU,defaultMatchWidth:"any",parsePatterns:EU,defaultParseWidth:"any"})},cE={code:"en-US",formatDistance:tU,formatLong:iU,formatRelative:oU,localize:fU,match:_U,options:{weekStartsOn:0,firstWeekContainsDate:1}};function DU(s,e){const t=xt(s,e==null?void 0:e.in);return bc(t,Sm(t))+1}function Jx(s,e){const t=xt(s,e==null?void 0:e.in),n=+gc(t)-+KH(t);return Math.round(n/nE)+1}function ev(s,e){var m,p,f,b;const t=xt(s,e==null?void 0:e.in),n=t.getFullYear(),a=rl(),i=(e==null?void 0:e.firstWeekContainsDate)??((p=(m=e==null?void 0:e.locale)==null?void 0:m.options)==null?void 0:p.firstWeekContainsDate)??a.firstWeekContainsDate??((b=(f=a.locale)==null?void 0:f.options)==null?void 0:b.firstWeekContainsDate)??1,o=jn((e==null?void 0:e.in)||s,0);o.setFullYear(n+1,0,i),o.setHours(0,0,0,0);const l=ir(o,e),c=jn((e==null?void 0:e.in)||s,0);c.setFullYear(n,0,i),c.setHours(0,0,0,0);const d=ir(c,e);return+t>=+l?n+1:+t>=+d?n:n-1}function PU(s,e){var l,c,d,m;const t=rl(),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??((m=(d=t.locale)==null?void 0:d.options)==null?void 0:m.firstWeekContainsDate)??1,a=ev(s,e),i=jn((e==null?void 0:e.in)||s,0);return i.setFullYear(a,0,n),i.setHours(0,0,0,0),ir(i,e)}function uE(s,e){const t=xt(s,e==null?void 0:e.in),n=+ir(t,e)-+PU(t,e);return Math.round(n/nE)+1}function Sn(s,e){const t=s<0?"-":"",n=Math.abs(s).toString().padStart(e,"0");return t+n}const Fr={y(s,e){const t=s.getFullYear(),n=t>0?t:1-t;return Sn(e==="yy"?n%100:n,e.length)},M(s,e){const t=s.getMonth();return e==="M"?String(t+1):Sn(t+1,2)},d(s,e){return Sn(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 Sn(s.getHours()%12||12,e.length)},H(s,e){return Sn(s.getHours(),e.length)},m(s,e){return Sn(s.getMinutes(),e.length)},s(s,e){return Sn(s.getSeconds(),e.length)},S(s,e){const t=e.length,n=s.getMilliseconds(),a=Math.trunc(n*Math.pow(10,t-3));return Sn(a,e.length)}},ql={midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},C1={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 Fr.y(s,e)},Y:function(s,e,t,n){const a=ev(s,n),i=a>0?a:1-a;if(e==="YY"){const o=i%100;return Sn(o,2)}return e==="Yo"?t.ordinalNumber(i,{unit:"year"}):Sn(i,e.length)},R:function(s,e){const t=aE(s);return Sn(t,e.length)},u:function(s,e){const t=s.getFullYear();return Sn(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 Sn(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 Sn(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 Fr.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 Sn(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=uE(s,n);return e==="wo"?t.ordinalNumber(a,{unit:"week"}):Sn(a,e.length)},I:function(s,e,t){const n=Jx(s);return e==="Io"?t.ordinalNumber(n,{unit:"week"}):Sn(n,e.length)},d:function(s,e,t){return e==="do"?t.ordinalNumber(s.getDate(),{unit:"date"}):Fr.d(s,e)},D:function(s,e,t){const n=DU(s);return e==="Do"?t.ordinalNumber(n,{unit:"dayOfYear"}):Sn(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 Sn(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 Sn(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 Sn(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=ql.noon:n===0?a=ql.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=ql.evening:n>=12?a=ql.afternoon:n>=4?a=ql.morning:a=ql.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 Fr.h(s,e)},H:function(s,e,t){return e==="Ho"?t.ordinalNumber(s.getHours(),{unit:"hour"}):Fr.H(s,e)},K:function(s,e,t){const n=s.getHours()%12;return e==="Ko"?t.ordinalNumber(n,{unit:"hour"}):Sn(n,e.length)},k:function(s,e,t){let n=s.getHours();return n===0&&(n=24),e==="ko"?t.ordinalNumber(n,{unit:"hour"}):Sn(n,e.length)},m:function(s,e,t){return e==="mo"?t.ordinalNumber(s.getMinutes(),{unit:"minute"}):Fr.m(s,e)},s:function(s,e,t){return e==="so"?t.ordinalNumber(s.getSeconds(),{unit:"second"}):Fr.s(s,e)},S:function(s,e){return Fr.S(s,e)},X:function(s,e,t){const n=s.getTimezoneOffset();if(n===0)return"Z";switch(e){case"X":return A1(n);case"XXXX":case"XX":return Po(n);case"XXXXX":case"XXX":default:return Po(n,":")}},x:function(s,e,t){const n=s.getTimezoneOffset();switch(e){case"x":return A1(n);case"xxxx":case"xx":return Po(n);case"xxxxx":case"xxx":default:return Po(n,":")}},O:function(s,e,t){const n=s.getTimezoneOffset();switch(e){case"O":case"OO":case"OOO":return"GMT"+N1(n,":");case"OOOO":default:return"GMT"+Po(n,":")}},z:function(s,e,t){const n=s.getTimezoneOffset();switch(e){case"z":case"zz":case"zzz":return"GMT"+N1(n,":");case"zzzz":default:return"GMT"+Po(n,":")}},t:function(s,e,t){const n=Math.trunc(+s/1e3);return Sn(n,e.length)},T:function(s,e,t){return Sn(+s,e.length)}};function N1(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+Sn(i,2)}function A1(s,e){return s%60===0?(s>0?"-":"+")+Sn(Math.abs(s)/60,2):Po(s,e)}function Po(s,e=""){const t=s>0?"-":"+",n=Math.abs(s),a=Sn(Math.trunc(n/60),2),i=Sn(n%60,2);return t+a+e+i}const M1=(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"})}},dE=(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"})}},RU=(s,e)=>{const t=s.match(/(P+)(p+)?/)||[],n=t[1],a=t[2];if(!a)return M1(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}}",M1(n,e)).replace("{{time}}",dE(a,e))},Fy={p:dE,P:RU},LU=/^D+$/,OU=/^Y+$/,IU=["D","DD","YY","YYYY"];function BU(s){return LU.test(s)}function FU(s){return OU.test(s)}function zU(s,e,t){const n=$U(s,e,t);if(console.warn(n),IU.includes(s))throw new RangeError(n)}function $U(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 HU=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,UU=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,GU=/^'([^]*?)'?$/,WU=/''/g,qU=/[a-zA-Z]/;function T1(s,e,t){var m,p,f,b,y,w,k,S;const n=rl(),a=(t==null?void 0:t.locale)??n.locale??cE,i=(t==null?void 0:t.firstWeekContainsDate)??((p=(m=t==null?void 0:t.locale)==null?void 0:m.options)==null?void 0:p.firstWeekContainsDate)??n.firstWeekContainsDate??((b=(f=n.locale)==null?void 0:f.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=xt(s,t==null?void 0:t.in);if(!yc(l))throw new RangeError("Invalid time value");let c=e.match(UU).map(j=>{const C=j[0];if(C==="p"||C==="P"){const A=Fy[C];return A(j,a.formatLong)}return j}).join("").match(HU).map(j=>{if(j==="''")return{isToken:!1,value:"'"};const C=j[0];if(C==="'")return{isToken:!1,value:YU(j)};if(C1[C])return{isToken:!0,value:j};if(C.match(qU))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)&&FU(C)||!(t!=null&&t.useAdditionalDayOfYearTokens)&&BU(C))&&zU(C,e,String(s));const A=C1[C[0]];return A(l,C,a.localize,d)}).join("")}function YU(s){const e=s.match(GU);return e?e[1].replace(WU,"'"):s}function E1(s,e){return xt(s,e==null?void 0:e.in).getDate()}function VU(s,e){return xt(s,e==null?void 0:e.in).getDay()}function KU(s,e){const t=xt(s,e==null?void 0:e.in),n=t.getFullYear(),a=t.getMonth(),i=jn(t,0);return i.setFullYear(n,a+1,0),i.setHours(0,0,0,0),i.getDate()}function XU(){return Object.assign({},rl())}function Ds(s,e){return xt(s,e==null?void 0:e.in).getHours()}function ZU(s,e){const t=xt(s,e==null?void 0:e.in).getDay();return t===0?7:t}function Ps(s,e){return xt(s,e==null?void 0:e.in).getMinutes()}function ea(s,e){return xt(s,e==null?void 0:e.in).getMonth()}function Yr(s){return xt(s).getSeconds()}function zy(s){return+xt(s)}function Zt(s,e){return xt(s,e==null?void 0:e.in).getFullYear()}function nr(s,e){return+xt(s)>+xt(e)}function xi(s,e){return+xt(s)<+xt(e)}function QU(s,e){return+xt(s)==+xt(e)}function JU(s,e){const t=eG(e)?new e(0):jn(e,0);return t.setFullYear(s.getFullYear(),s.getMonth(),s.getDate()),t.setHours(s.getHours(),s.getMinutes(),s.getSeconds(),s.getMilliseconds()),t}function eG(s){var e;return typeof s=="function"&&((e=s.prototype)==null?void 0:e.constructor)===s}const tG=10;class hE{constructor(){W(this,"subPriority",0)}validate(e,t){return!0}}class nG extends hE{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 sG extends hE{constructor(t,n){super();W(this,"priority",tG);W(this,"subPriority",-1);this.context=t||(a=>jn(n,a))}set(t,n){return n.timestampIsSet?t:jn(t,JU(t,this.context))}}class gn{run(e,t,n,a){const i=this.parse(e,t,n,a);return i?{setter:new nG(i.value,this.validate,this.set,this.priority,this.subPriority),rest:i.rest}:null}validate(e,t,n){return!0}}class aG extends gn{constructor(){super(...arguments);W(this,"priority",140);W(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 as={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}/},fi={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 is(s,e){return s&&{value:e(s.value),rest:s.rest}}function Kn(s,e){const t=e.match(s);return t?{value:parseInt(t[0],10),rest:e.slice(t[0].length)}:null}function gi(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*km+i*wm+o*qH),rest:e.slice(t[0].length)}}function pE(s){return Kn(as.anyDigitsSigned,s)}function es(s,e){switch(s){case 1:return Kn(as.singleDigit,e);case 2:return Kn(as.twoDigits,e);case 3:return Kn(as.threeDigits,e);case 4:return Kn(as.fourDigits,e);default:return Kn(new RegExp("^\\d{1,"+s+"}"),e)}}function Wp(s,e){switch(s){case 1:return Kn(as.singleDigitSigned,e);case 2:return Kn(as.twoDigitsSigned,e);case 3:return Kn(as.threeDigitsSigned,e);case 4:return Kn(as.fourDigitsSigned,e);default:return Kn(new RegExp("^-?\\d{1,"+s+"}"),e)}}function tv(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 mE(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 fE(s){return s%400===0||s%4===0&&s%100!==0}class iG extends gn{constructor(){super(...arguments);W(this,"priority",130);W(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 is(es(4,t),i);case"yo":return is(a.ordinalNumber(t,{unit:"year"}),i);default:return is(es(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=mE(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 rG extends gn{constructor(){super(...arguments);W(this,"priority",130);W(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 is(es(4,t),i);case"Yo":return is(a.ordinalNumber(t,{unit:"year"}),i);default:return is(es(n.length,t),i)}}validate(t,n){return n.isTwoDigitYear||n.year>0}set(t,n,a,i){const o=ev(t,i);if(a.isTwoDigitYear){const c=mE(a.year,o);return t.setFullYear(c,0,i.firstWeekContainsDate),t.setHours(0,0,0,0),ir(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),ir(t,i)}}class oG extends gn{constructor(){super(...arguments);W(this,"priority",130);W(this,"incompatibleTokens",["G","y","Y","u","Q","q","M","L","w","d","D","e","c","t","T"])}parse(t,n){return Wp(n==="R"?4:n.length,t)}set(t,n,a){const i=jn(t,0);return i.setFullYear(a,0,4),i.setHours(0,0,0,0),gc(i)}}class lG extends gn{constructor(){super(...arguments);W(this,"priority",130);W(this,"incompatibleTokens",["G","y","Y","R","w","I","i","e","c","t","T"])}parse(t,n){return Wp(n==="u"?4:n.length,t)}set(t,n,a){return t.setFullYear(a,0,1),t.setHours(0,0,0,0),t}}class cG extends gn{constructor(){super(...arguments);W(this,"priority",120);W(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 es(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 uG extends gn{constructor(){super(...arguments);W(this,"priority",120);W(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 es(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 dG extends gn{constructor(){super(...arguments);W(this,"incompatibleTokens",["Y","R","q","Q","L","w","I","D","i","e","c","t","T"]);W(this,"priority",110)}parse(t,n,a){const i=o=>o-1;switch(n){case"M":return is(Kn(as.month,t),i);case"MM":return is(es(2,t),i);case"Mo":return is(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 hG extends gn{constructor(){super(...arguments);W(this,"priority",110);W(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 is(Kn(as.month,t),i);case"LL":return is(es(2,t),i);case"Lo":return is(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 pG(s,e,t){const n=xt(s,t==null?void 0:t.in),a=uE(n,t)-e;return n.setDate(n.getDate()-a*7),xt(n,t==null?void 0:t.in)}class mG extends gn{constructor(){super(...arguments);W(this,"priority",100);W(this,"incompatibleTokens",["y","R","u","q","Q","M","L","I","d","D","i","t","T"])}parse(t,n,a){switch(n){case"w":return Kn(as.week,t);case"wo":return a.ordinalNumber(t,{unit:"week"});default:return es(n.length,t)}}validate(t,n){return n>=1&&n<=53}set(t,n,a,i){return ir(pG(t,a,i),i)}}function fG(s,e,t){const n=xt(s,t==null?void 0:t.in),a=Jx(n,t)-e;return n.setDate(n.getDate()-a*7),n}class gG extends gn{constructor(){super(...arguments);W(this,"priority",100);W(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 Kn(as.week,t);case"Io":return a.ordinalNumber(t,{unit:"week"});default:return es(n.length,t)}}validate(t,n){return n>=1&&n<=53}set(t,n,a){return gc(fG(t,a))}}const bG=[31,28,31,30,31,30,31,31,30,31,30,31],yG=[31,29,31,30,31,30,31,31,30,31,30,31];class xG extends gn{constructor(){super(...arguments);W(this,"priority",90);W(this,"subPriority",1);W(this,"incompatibleTokens",["Y","R","q","Q","w","I","D","i","e","c","t","T"])}parse(t,n,a){switch(n){case"d":return Kn(as.date,t);case"do":return a.ordinalNumber(t,{unit:"date"});default:return es(n.length,t)}}validate(t,n){const a=t.getFullYear(),i=fE(a),o=t.getMonth();return i?n>=1&&n<=yG[o]:n>=1&&n<=bG[o]}set(t,n,a){return t.setDate(a),t.setHours(0,0,0,0),t}}class vG extends gn{constructor(){super(...arguments);W(this,"priority",90);W(this,"subpriority",1);W(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 Kn(as.dayOfYear,t);case"Do":return a.ordinalNumber(t,{unit:"date"});default:return es(n.length,t)}}validate(t,n){const a=t.getFullYear();return fE(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 nv(s,e,t){var p,f,b,y;const n=rl(),a=(t==null?void 0:t.weekStartsOn)??((f=(p=t==null?void 0:t.locale)==null?void 0:p.options)==null?void 0:f.weekStartsOn)??n.weekStartsOn??((y=(b=n.locale)==null?void 0:b.options)==null?void 0:y.weekStartsOn)??0,i=xt(s,t==null?void 0:t.in),o=i.getDay(),c=(e%7+7)%7,d=7-a,m=e<0||e>6?e-(o+d)%7:(c+d)%7-(o+d)%7;return Qa(i,m,t)}class wG extends gn{constructor(){super(...arguments);W(this,"priority",90);W(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=nv(t,a,i),t.setHours(0,0,0,0),t}}class kG extends gn{constructor(){super(...arguments);W(this,"priority",90);W(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 is(es(n.length,t),o);case"eo":return is(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=nv(t,a,i),t.setHours(0,0,0,0),t}}class SG extends gn{constructor(){super(...arguments);W(this,"priority",90);W(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 is(es(n.length,t),o);case"co":return is(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=nv(t,a,i),t.setHours(0,0,0,0),t}}function jG(s,e,t){const n=xt(s,t==null?void 0:t.in),a=ZU(n,t),i=e-a;return Qa(n,i,t)}class CG extends gn{constructor(){super(...arguments);W(this,"priority",90);W(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 es(n.length,t);case"io":return a.ordinalNumber(t,{unit:"day"});case"iii":return is(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 is(a.day(t,{width:"narrow",context:"formatting"}),i);case"iiiiii":return is(a.day(t,{width:"short",context:"formatting"})||a.day(t,{width:"narrow",context:"formatting"}),i);case"iiii":default:return is(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=jG(t,a),t.setHours(0,0,0,0),t}}class NG extends gn{constructor(){super(...arguments);W(this,"priority",80);W(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(tv(a),0,0,0),t}}class AG extends gn{constructor(){super(...arguments);W(this,"priority",80);W(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(tv(a),0,0,0),t}}class MG extends gn{constructor(){super(...arguments);W(this,"priority",80);W(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(tv(a),0,0,0),t}}class TG extends gn{constructor(){super(...arguments);W(this,"priority",70);W(this,"incompatibleTokens",["H","K","k","t","T"])}parse(t,n,a){switch(n){case"h":return Kn(as.hour12h,t);case"ho":return a.ordinalNumber(t,{unit:"hour"});default:return es(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 EG extends gn{constructor(){super(...arguments);W(this,"priority",70);W(this,"incompatibleTokens",["a","b","h","K","k","t","T"])}parse(t,n,a){switch(n){case"H":return Kn(as.hour23h,t);case"Ho":return a.ordinalNumber(t,{unit:"hour"});default:return es(n.length,t)}}validate(t,n){return n>=0&&n<=23}set(t,n,a){return t.setHours(a,0,0,0),t}}class _G extends gn{constructor(){super(...arguments);W(this,"priority",70);W(this,"incompatibleTokens",["h","H","k","t","T"])}parse(t,n,a){switch(n){case"K":return Kn(as.hour11h,t);case"Ko":return a.ordinalNumber(t,{unit:"hour"});default:return es(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 DG extends gn{constructor(){super(...arguments);W(this,"priority",70);W(this,"incompatibleTokens",["a","b","h","H","K","t","T"])}parse(t,n,a){switch(n){case"k":return Kn(as.hour24h,t);case"ko":return a.ordinalNumber(t,{unit:"hour"});default:return es(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 PG extends gn{constructor(){super(...arguments);W(this,"priority",60);W(this,"incompatibleTokens",["t","T"])}parse(t,n,a){switch(n){case"m":return Kn(as.minute,t);case"mo":return a.ordinalNumber(t,{unit:"minute"});default:return es(n.length,t)}}validate(t,n){return n>=0&&n<=59}set(t,n,a){return t.setMinutes(a,0,0),t}}class RG extends gn{constructor(){super(...arguments);W(this,"priority",50);W(this,"incompatibleTokens",["t","T"])}parse(t,n,a){switch(n){case"s":return Kn(as.second,t);case"so":return a.ordinalNumber(t,{unit:"second"});default:return es(n.length,t)}}validate(t,n){return n>=0&&n<=59}set(t,n,a){return t.setSeconds(a,0),t}}class LG extends gn{constructor(){super(...arguments);W(this,"priority",30);W(this,"incompatibleTokens",["t","T"])}parse(t,n){const a=i=>Math.trunc(i*Math.pow(10,-n.length+3));return is(es(n.length,t),a)}set(t,n,a){return t.setMilliseconds(a),t}}class OG extends gn{constructor(){super(...arguments);W(this,"priority",10);W(this,"incompatibleTokens",["t","T","x"])}parse(t,n){switch(n){case"X":return gi(fi.basicOptionalMinutes,t);case"XX":return gi(fi.basic,t);case"XXXX":return gi(fi.basicOptionalSeconds,t);case"XXXXX":return gi(fi.extendedOptionalSeconds,t);case"XXX":default:return gi(fi.extended,t)}}set(t,n,a){return n.timestampIsSet?t:jn(t,t.getTime()-zp(t)-a)}}class IG extends gn{constructor(){super(...arguments);W(this,"priority",10);W(this,"incompatibleTokens",["t","T","X"])}parse(t,n){switch(n){case"x":return gi(fi.basicOptionalMinutes,t);case"xx":return gi(fi.basic,t);case"xxxx":return gi(fi.basicOptionalSeconds,t);case"xxxxx":return gi(fi.extendedOptionalSeconds,t);case"xxx":default:return gi(fi.extended,t)}}set(t,n,a){return n.timestampIsSet?t:jn(t,t.getTime()-zp(t)-a)}}class BG extends gn{constructor(){super(...arguments);W(this,"priority",40);W(this,"incompatibleTokens","*")}parse(t){return pE(t)}set(t,n,a){return[jn(t,a*1e3),{timestampIsSet:!0}]}}class FG extends gn{constructor(){super(...arguments);W(this,"priority",20);W(this,"incompatibleTokens","*")}parse(t){return pE(t)}set(t,n,a){return[jn(t,a),{timestampIsSet:!0}]}}const zG={G:new aG,y:new iG,Y:new rG,R:new oG,u:new lG,Q:new cG,q:new uG,M:new dG,L:new hG,w:new mG,I:new gG,d:new xG,D:new vG,E:new wG,e:new kG,c:new SG,i:new CG,a:new NG,b:new AG,B:new MG,h:new TG,H:new EG,K:new _G,k:new DG,m:new PG,s:new RG,S:new LG,X:new OG,x:new IG,t:new BG,T:new FG},$G=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,HG=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,UG=/^'([^]*?)'?$/,GG=/''/g,WG=/\S/,qG=/[a-zA-Z]/;function YG(s,e,t,n){var k,S,j,C,A,D,M,I;const a=()=>jn((n==null?void 0:n.in)||t,NaN),i=XU(),o=(n==null?void 0:n.locale)??i.locale??cE,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=(A=n==null?void 0:n.locale)==null?void 0:A.options)==null?void 0:D.weekStartsOn)??i.weekStartsOn??((I=(M=i.locale)==null?void 0:M.options)==null?void 0:I.weekStartsOn)??0;if(!e)return s?a():xt(t,n==null?void 0:n.in);const d={firstWeekContainsDate:l,weekStartsOn:c,locale:o},m=[new sG(n==null?void 0:n.in,t)],p=e.match(HG).map(E=>{const _=E[0];if(_ in Fy){const P=Fy[_];return P(E,o.formatLong)}return E}).join("").match($G),f=[];for(let E of p){const _=E[0],P=zG[_];if(P){const{incompatibleTokens:L}=P;if(Array.isArray(L)){const z=f.find(F=>L.includes(F.token)||F.token===_);if(z)throw new RangeError(`The format string mustn't contain \`${z.fullToken}\` and \`${E}\` at the same time`)}else if(P.incompatibleTokens==="*"&&f.length>0)throw new RangeError(`The format string mustn't contain \`${E}\` and any other token at the same time`);f.push({token:_,fullToken:E});const R=P.run(s,E,o.match,d);if(!R)return a();m.push(R.setter),s=R.rest}else{if(_.match(qG))throw new RangeError("Format string contains an unescaped latin alphabet character `"+_+"`");if(E==="''"?E="'":_==="'"&&(E=VG(E)),s.indexOf(E)===0)s=s.slice(E.length);else return a()}}if(s.length>0&&WG.test(s))return a();const b=m.map(E=>E.priority).sort((E,_)=>_-E).filter((E,_,P)=>P.indexOf(E)===_).map(E=>m.filter(_=>_.priority===E).sort((_,P)=>P.subPriority-_.subPriority)).map(E=>E[0]);let y=xt(t,n==null?void 0:n.in);if(isNaN(+y))return a();const w={};for(const E of b){if(!E.validate(y,d))return a();const _=E.set(y,w,d);Array.isArray(_)?(y=_[0],Object.assign(w,_[1])):y=_}return y}function VG(s){return s.match(UG)[1].replace(GG,"'")}function KG(s,e,t){const[n,a]=ur(t==null?void 0:t.in,s,e);return n.getFullYear()===a.getFullYear()&&n.getMonth()===a.getMonth()}function XG(s,e,t){const[n,a]=ur(t==null?void 0:t.in,s,e);return+By(n)==+By(a)}function ZG(s,e,t){const[n,a]=ur(t==null?void 0:t.in,s,e);return n.getFullYear()===a.getFullYear()}function ld(s,e,t){const n=+xt(s,t==null?void 0:t.in),[a,i]=[+xt(e.start,t==null?void 0:t.in),+xt(e.end,t==null?void 0:t.in)].sort((o,l)=>o-l);return n>=a&&n<=i}function QG(s,e,t){return Qa(s,-1,t)}function JG(s,e){const t=()=>jn(e==null?void 0:e.in,NaN),a=sW(s);let i;if(a.date){const d=aW(a.date,2);i=iW(d.restDateString,d.year)}if(!i||isNaN(+i))return t();const o=+i;let l=0,c;if(a.time&&(l=rW(a.time),isNaN(l)))return t();if(a.timezone){if(c=oW(a.timezone),isNaN(c))return t()}else{const d=new Date(o+l),m=xt(0,e==null?void 0:e.in);return m.setFullYear(d.getUTCFullYear(),d.getUTCMonth(),d.getUTCDate()),m.setHours(d.getUTCHours(),d.getUTCMinutes(),d.getUTCSeconds(),d.getUTCMilliseconds()),m}return xt(o+l+c,e==null?void 0:e.in)}const Kh={dateTimeDelimiter:/[T ]/,timeZoneDelimiter:/[Z ]/i,timezone:/([Z+-].*)$/},eW=/^-?(?:(\d{3})|(\d{2})(?:-?(\d{2}))?|W(\d{2})(?:-?(\d{1}))?|)$/,tW=/^(\d{2}(?:[.,]\d*)?)(?::?(\d{2}(?:[.,]\d*)?))?(?::?(\d{2}(?:[.,]\d*)?))?$/,nW=/^([+-])(\d{2})(?::?(\d{2}))?$/;function sW(s){const e={},t=s.split(Kh.dateTimeDelimiter);let n;if(t.length>2)return e;if(/:/.test(t[0])?n=t[0]:(e.date=t[0],n=t[1],Kh.timeZoneDelimiter.test(e.date)&&(e.date=s.split(Kh.timeZoneDelimiter)[0],n=s.substr(e.date.length,s.length))),n){const a=Kh.timezone.exec(n);a?(e.time=n.replace(a[1],""),e.timezone=a[1]):e.time=n}return e}function aW(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 iW(s,e){if(e===null)return new Date(NaN);const t=s.match(eW);if(!t)return new Date(NaN);const n=!!t[4],a=Du(t[1]),i=Du(t[2])-1,o=Du(t[3]),l=Du(t[4]),c=Du(t[5])-1;if(n)return hW(e,l,c)?lW(e,l,c):new Date(NaN);{const d=new Date(0);return!uW(e,i,o)||!dW(e,a)?new Date(NaN):(d.setUTCFullYear(e,i,Math.max(a,o)),d)}}function Du(s){return s?parseInt(s):1}function rW(s){const e=s.match(tW);if(!e)return NaN;const t=Eb(e[1]),n=Eb(e[2]),a=Eb(e[3]);return pW(t,n,a)?t*km+n*wm+a*1e3:NaN}function Eb(s){return s&&parseFloat(s.replace(",","."))||0}function oW(s){if(s==="Z")return 0;const e=s.match(nW);if(!e)return 0;const t=e[1]==="+"?-1:1,n=parseInt(e[2]),a=e[3]&&parseInt(e[3])||0;return mW(n,a)?t*(n*km+a*wm):NaN}function lW(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 cW=[31,null,31,30,31,30,31,31,30,31,30,31];function gE(s){return s%400===0||s%4===0&&s%100!==0}function uW(s,e,t){return e>=0&&e<=11&&t>=1&&t<=(cW[e]||(gE(s)?29:28))}function dW(s,e){return e>=1&&e<=(gE(s)?366:365)}function hW(s,e,t){return e>=1&&e<=53&&t>=0&&t<=6}function pW(s,e,t){return s===24?e===0&&t===0:t>=0&&t<60&&e>=0&&e<60&&s>=0&&s<25}function mW(s,e){return e>=0&&e<=59}function ya(s,e,t){const n=xt(s,t==null?void 0:t.in),a=n.getFullYear(),i=n.getDate(),o=jn(s,0);o.setFullYear(a,e,15),o.setHours(0,0,0,0);const l=KU(o);return n.setMonth(e,Math.min(i,l)),n}function cp(s,e,t){const n=xt(s,t==null?void 0:t.in);return n.setHours(e),n}function up(s,e,t){const n=xt(s,t==null?void 0:t.in);return n.setMinutes(e),n}function Zl(s,e,t){const n=xt(s,t==null?void 0:t.in),a=Math.trunc(n.getMonth()/3)+1,i=e-a;return ya(n,n.getMonth()+i*3)}function dp(s,e,t){const n=xt(s,t==null?void 0:t.in);return n.setSeconds(e),n}function hi(s,e,t){const n=xt(s,t==null?void 0:t.in);return isNaN(+n)?jn(s,NaN):(n.setFullYear(e),n)}function Wo(s,e,t){return ei(s,-e,t)}function bE(s,e,t){return Qx(s,-1,t)}function _1(s,e,t){return $p(s,-1,t)}function Jr(s,e,t){return Ja(s,-e,t)}function jm(){return typeof window<"u"}function Mc(s){return yE(s)?(s.nodeName||"").toLowerCase():"#document"}function wa(s){var e;return(s==null||(e=s.ownerDocument)==null?void 0:e.defaultView)||window}function Ei(s){var e;return(e=(yE(s)?s.ownerDocument:s.document)||window.document)==null?void 0:e.documentElement}function yE(s){return jm()?s instanceof Node||s instanceof wa(s).Node:!1}function Hs(s){return jm()?s instanceof Element||s instanceof wa(s).Element:!1}function Ni(s){return jm()?s instanceof HTMLElement||s instanceof wa(s).HTMLElement:!1}function D1(s){return!jm()||typeof ShadowRoot>"u"?!1:s instanceof ShadowRoot||s instanceof wa(s).ShadowRoot}const fW=new Set(["inline","contents"]);function vd(s){const{overflow:e,overflowX:t,overflowY:n,display:a}=Fa(s);return/auto|scroll|overlay|hidden|clip/.test(e+n+t)&&!fW.has(a)}const gW=new Set(["table","td","th"]);function bW(s){return gW.has(Mc(s))}const yW=[":popover-open",":modal"];function Cm(s){return yW.some(e=>{try{return s.matches(e)}catch{return!1}})}const xW=["transform","translate","scale","rotate","perspective"],vW=["transform","translate","scale","rotate","perspective","filter"],wW=["paint","layout","strict","content"];function sv(s){const e=av(),t=Hs(s)?Fa(s):s;return xW.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)||vW.some(n=>(t.willChange||"").includes(n))||wW.some(n=>(t.contain||"").includes(n))}function kW(s){let e=eo(s);for(;Ni(e)&&!xc(e);){if(sv(e))return e;if(Cm(e))return null;e=eo(e)}return null}function av(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}const SW=new Set(["html","body","#document"]);function xc(s){return SW.has(Mc(s))}function Fa(s){return wa(s).getComputedStyle(s)}function Nm(s){return Hs(s)?{scrollLeft:s.scrollLeft,scrollTop:s.scrollTop}:{scrollLeft:s.scrollX,scrollTop:s.scrollY}}function eo(s){if(Mc(s)==="html")return s;const e=s.assignedSlot||s.parentNode||D1(s)&&s.host||Ei(s);return D1(e)?e.host:e}function xE(s){const e=eo(s);return xc(e)?s.ownerDocument?s.ownerDocument.body:s.body:Ni(e)&&vd(e)?e:xE(e)}function cd(s,e,t){var n;e===void 0&&(e=[]),t===void 0&&(t=!0);const a=xE(s),i=a===((n=s.ownerDocument)==null?void 0:n.body),o=wa(a);if(i){const l=$y(o);return e.concat(o,o.visualViewport||[],vd(a)?a:[],l&&t?cd(l):[])}return e.concat(a,cd(a,[],t))}function $y(s){return s.parent&&Object.getPrototypeOf(s.parent)?s.frameElement:null}const vc=Math.min,qo=Math.max,qp=Math.round,Xh=Math.floor,ji=s=>({x:s,y:s}),jW={left:"right",right:"left",bottom:"top",top:"bottom"},CW={start:"end",end:"start"};function NW(s,e,t){return qo(s,vc(e,t))}function Am(s,e){return typeof s=="function"?s(e):s}function wc(s){return s.split("-")[0]}function wd(s){return s.split("-")[1]}function AW(s){return s==="x"?"y":"x"}function iv(s){return s==="y"?"height":"width"}const MW=new Set(["top","bottom"]);function Bo(s){return MW.has(wc(s))?"y":"x"}function rv(s){return AW(Bo(s))}function TW(s,e,t){t===void 0&&(t=!1);const n=wd(s),a=rv(s),i=iv(a);let o=a==="x"?n===(t?"end":"start")?"right":"left":n==="start"?"bottom":"top";return e.reference[i]>e.floating[i]&&(o=Yp(o)),[o,Yp(o)]}function EW(s){const e=Yp(s);return[Hy(s),e,Hy(e)]}function Hy(s){return s.replace(/start|end/g,e=>CW[e])}const P1=["left","right"],R1=["right","left"],_W=["top","bottom"],DW=["bottom","top"];function PW(s,e,t){switch(s){case"top":case"bottom":return t?e?R1:P1:e?P1:R1;case"left":case"right":return e?_W:DW;default:return[]}}function RW(s,e,t,n){const a=wd(s);let i=PW(wc(s),t==="start",n);return a&&(i=i.map(o=>o+"-"+a),e&&(i=i.concat(i.map(Hy)))),i}function Yp(s){return s.replace(/left|right|bottom|top/g,e=>jW[e])}function LW(s){return{top:0,right:0,bottom:0,left:0,...s}}function vE(s){return typeof s!="number"?LW(s):{top:s,right:s,bottom:s,left:s}}function Vp(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 OW=typeof document<"u",IW=function(){},Kp=OW?x.useLayoutEffect:IW;const BW={...bA},FW=BW.useInsertionEffect,zW=FW||(s=>s());function $W(s){const e=x.useRef(()=>{});return zW(()=>{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 L1(s,e,t){let{reference:n,floating:a}=s;const i=Bo(e),o=rv(e),l=iv(o),c=wc(e),d=i==="y",m=n.x+n.width/2-a.width/2,p=n.y+n.height/2-a.height/2,f=n[l]/2-a[l]/2;let b;switch(c){case"top":b={x:m,y:n.y-a.height};break;case"bottom":b={x:m,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(wd(e)){case"start":b[o]-=f*(t&&d?-1:1);break;case"end":b[o]+=f*(t&&d?-1:1);break}return b}async function HW(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:m="viewport",elementContext:p="floating",altBoundary:f=!1,padding:b=0}=Am(e,s),y=vE(b),k=l[f?p==="floating"?"reference":"floating":p],S=Vp(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:m,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)),A=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=Vp(i.convertOffsetParentRelativeRectToViewportRelativeRect?await i.convertOffsetParentRelativeRectToViewportRelativeRect({elements:l,rect:j,offsetParent:C,strategy:c}):j);return{top:(S.top-D.top+y.top)/A.y,bottom:(D.bottom-S.bottom+y.bottom)/A.y,left:(S.left-D.left+y.left)/A.x,right:(D.right-S.right+y.right)/A.x}}const UW=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:m,y:p}=L1(d,n,c),f=n,b={},y=0;for(let k=0;k<l.length;k++){var w;const{name:S,fn:j}=l[k],{x:C,y:A,data:D,reset:M}=await j({x:m,y:p,initialPlacement:n,placement:f,strategy:a,middlewareData:b,rects:d,platform:{...o,detectOverflow:(w=o.detectOverflow)!=null?w:HW},elements:{reference:s,floating:e}});m=C??m,p=A??p,b={...b,[S]:{...b[S],...D}},M&&y<=50&&(y++,typeof M=="object"&&(M.placement&&(f=M.placement),M.rects&&(d=M.rects===!0?await o.getElementRects({reference:s,floating:e,strategy:a}):M.rects),{x:m,y:p}=L1(d,f,c)),k=-1)}return{x:m,y:p,placement:f,strategy:a,middlewareData:b}},GW=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:m=0}=Am(s,e)||{};if(d==null)return{};const p=vE(m),f={x:t,y:n},b=rv(a),y=iv(b),w=await o.getDimensions(d),k=b==="y",S=k?"top":"left",j=k?"bottom":"right",C=k?"clientHeight":"clientWidth",A=i.reference[y]+i.reference[b]-f[b]-i.floating[y],D=f[b]-i.reference[b],M=await(o.getOffsetParent==null?void 0:o.getOffsetParent(d));let I=M?M[C]:0;(!I||!await(o.isElement==null?void 0:o.isElement(M)))&&(I=l.floating[C]||i.floating[y]);const E=A/2-D/2,_=I/2-w[y]/2-1,P=vc(p[S],_),L=vc(p[j],_),R=P,z=I-w[y]-L,F=I/2-w[y]/2+E,$=NW(R,F,z),U=!c.arrow&&wd(a)!=null&&F!==$&&i.reference[y]/2-(F<R?P:L)-w[y]/2<0,G=U?F<R?F-R:F-z:0;return{[b]:f[b]+G,data:{[b]:$,centerOffset:F-$-G,...U&&{alignmentOffset:G}},reset:U}}}),WW=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:m=!0,crossAxis:p=!0,fallbackPlacements:f,fallbackStrategy:b="bestFit",fallbackAxisSideDirection:y="none",flipAlignment:w=!0,...k}=Am(s,e);if((t=i.arrow)!=null&&t.alignmentOffset)return{};const S=wc(a),j=Bo(l),C=wc(l)===l,A=await(c.isRTL==null?void 0:c.isRTL(d.floating)),D=f||(C||!w?[Yp(l)]:EW(l)),M=y!=="none";!f&&M&&D.push(...RW(l,w,y,A));const I=[l,...D],E=await c.detectOverflow(e,k),_=[];let P=((n=i.flip)==null?void 0:n.overflows)||[];if(m&&_.push(E[S]),p){const F=TW(a,o,A);_.push(E[F[0]],E[F[1]])}if(P=[...P,{placement:a,overflows:_}],!_.every(F=>F<=0)){var L,R;const F=(((L=i.flip)==null?void 0:L.index)||0)+1,$=I[F];if($&&(!(p==="alignment"?j!==Bo($):!1)||P.every(K=>Bo(K.placement)===j?K.overflows[0]>0:!0)))return{data:{index:F,overflows:P},reset:{placement:$}};let U=(R=P.filter(G=>G.overflows[0]<=0).sort((G,K)=>G.overflows[1]-K.overflows[1])[0])==null?void 0:R.placement;if(!U)switch(b){case"bestFit":{var z;const G=(z=P.filter(K=>{if(M){const Z=Bo(K.placement);return Z===j||Z==="y"}return!0}).map(K=>[K.placement,K.overflows.filter(Z=>Z>0).reduce((Z,B)=>Z+B,0)]).sort((K,Z)=>K[1]-Z[1])[0])==null?void 0:z[0];G&&(U=G);break}case"initialPlacement":U=l;break}if(a!==U)return{reset:{placement:U}}}return{}}}},qW=new Set(["left","top"]);async function YW(s,e){const{placement:t,platform:n,elements:a}=s,i=await(n.isRTL==null?void 0:n.isRTL(a.floating)),o=wc(t),l=wd(t),c=Bo(t)==="y",d=qW.has(o)?-1:1,m=i&&c?-1:1,p=Am(e,s);let{mainAxis:f,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*m,y:f*d}:{x:f*d,y:b*m}}const VW=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 YW(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 wE(s){const e=Fa(s);let t=parseFloat(e.width)||0,n=parseFloat(e.height)||0;const a=Ni(s),i=a?s.offsetWidth:t,o=a?s.offsetHeight:n,l=qp(t)!==i||qp(n)!==o;return l&&(t=i,n=o),{width:t,height:n,$:l}}function ov(s){return Hs(s)?s:s.contextElement}function lc(s){const e=ov(s);if(!Ni(e))return ji(1);const t=e.getBoundingClientRect(),{width:n,height:a,$:i}=wE(e);let o=(i?qp(t.width):t.width)/n,l=(i?qp(t.height):t.height)/a;return(!o||!Number.isFinite(o))&&(o=1),(!l||!Number.isFinite(l))&&(l=1),{x:o,y:l}}const KW=ji(0);function kE(s){const e=wa(s);return!av()||!e.visualViewport?KW:{x:e.visualViewport.offsetLeft,y:e.visualViewport.offsetTop}}function XW(s,e,t){return e===void 0&&(e=!1),!t||e&&t!==wa(s)?!1:e}function sl(s,e,t,n){e===void 0&&(e=!1),t===void 0&&(t=!1);const a=s.getBoundingClientRect(),i=ov(s);let o=ji(1);e&&(n?Hs(n)&&(o=lc(n)):o=lc(s));const l=XW(i,t,n)?kE(i):ji(0);let c=(a.left+l.x)/o.x,d=(a.top+l.y)/o.y,m=a.width/o.x,p=a.height/o.y;if(i){const f=wa(i),b=n&&Hs(n)?wa(n):n;let y=f,w=$y(y);for(;w&&n&&b!==y;){const k=lc(w),S=w.getBoundingClientRect(),j=Fa(w),C=S.left+(w.clientLeft+parseFloat(j.paddingLeft))*k.x,A=S.top+(w.clientTop+parseFloat(j.paddingTop))*k.y;c*=k.x,d*=k.y,m*=k.x,p*=k.y,c+=C,d+=A,y=wa(w),w=$y(y)}}return Vp({width:m,height:p,x:c,y:d})}function Mm(s,e){const t=Nm(s).scrollLeft;return e?e.left+t:sl(Ei(s)).left+t}function SE(s,e){const t=s.getBoundingClientRect(),n=t.left+e.scrollLeft-Mm(s,t),a=t.top+e.scrollTop;return{x:n,y:a}}function ZW(s){let{elements:e,rect:t,offsetParent:n,strategy:a}=s;const i=a==="fixed",o=Ei(n),l=e?Cm(e.floating):!1;if(n===o||l&&i)return t;let c={scrollLeft:0,scrollTop:0},d=ji(1);const m=ji(0),p=Ni(n);if((p||!p&&!i)&&((Mc(n)!=="body"||vd(o))&&(c=Nm(n)),Ni(n))){const b=sl(n);d=lc(n),m.x=b.x+n.clientLeft,m.y=b.y+n.clientTop}const f=o&&!p&&!i?SE(o,c):ji(0);return{width:t.width*d.x,height:t.height*d.y,x:t.x*d.x-c.scrollLeft*d.x+m.x+f.x,y:t.y*d.y-c.scrollTop*d.y+m.y+f.y}}function QW(s){return Array.from(s.getClientRects())}function JW(s){const e=Ei(s),t=Nm(s),n=s.ownerDocument.body,a=qo(e.scrollWidth,e.clientWidth,n.scrollWidth,n.clientWidth),i=qo(e.scrollHeight,e.clientHeight,n.scrollHeight,n.clientHeight);let o=-t.scrollLeft+Mm(s);const l=-t.scrollTop;return Fa(n).direction==="rtl"&&(o+=qo(e.clientWidth,n.clientWidth)-a),{width:a,height:i,x:o,y:l}}const O1=25;function e7(s,e){const t=wa(s),n=Ei(s),a=t.visualViewport;let i=n.clientWidth,o=n.clientHeight,l=0,c=0;if(a){i=a.width,o=a.height;const m=av();(!m||m&&e==="fixed")&&(l=a.offsetLeft,c=a.offsetTop)}const d=Mm(n);if(d<=0){const m=n.ownerDocument,p=m.body,f=getComputedStyle(p),b=m.compatMode==="CSS1Compat"&&parseFloat(f.marginLeft)+parseFloat(f.marginRight)||0,y=Math.abs(n.clientWidth-p.clientWidth-b);y<=O1&&(i-=y)}else d<=O1&&(i+=d);return{width:i,height:o,x:l,y:c}}const t7=new Set(["absolute","fixed"]);function n7(s,e){const t=sl(s,!0,e==="fixed"),n=t.top+s.clientTop,a=t.left+s.clientLeft,i=Ni(s)?lc(s):ji(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 I1(s,e,t){let n;if(e==="viewport")n=e7(s,t);else if(e==="document")n=JW(Ei(s));else if(Hs(e))n=n7(e,t);else{const a=kE(s);n={x:e.x-a.x,y:e.y-a.y,width:e.width,height:e.height}}return Vp(n)}function jE(s,e){const t=eo(s);return t===e||!Hs(t)||xc(t)?!1:Fa(t).position==="fixed"||jE(t,e)}function s7(s,e){const t=e.get(s);if(t)return t;let n=cd(s,[],!1).filter(l=>Hs(l)&&Mc(l)!=="body"),a=null;const i=Fa(s).position==="fixed";let o=i?eo(s):s;for(;Hs(o)&&!xc(o);){const l=Fa(o),c=sv(o);!c&&l.position==="fixed"&&(a=null),(i?!c&&!a:!c&&l.position==="static"&&!!a&&t7.has(a.position)||vd(o)&&!c&&jE(s,o))?n=n.filter(m=>m!==o):a=l,o=eo(o)}return e.set(s,n),n}function a7(s){let{element:e,boundary:t,rootBoundary:n,strategy:a}=s;const o=[...t==="clippingAncestors"?Cm(e)?[]:s7(e,this._c):[].concat(t),n],l=o[0],c=o.reduce((d,m)=>{const p=I1(e,m,a);return d.top=qo(p.top,d.top),d.right=vc(p.right,d.right),d.bottom=vc(p.bottom,d.bottom),d.left=qo(p.left,d.left),d},I1(e,l,a));return{width:c.right-c.left,height:c.bottom-c.top,x:c.left,y:c.top}}function i7(s){const{width:e,height:t}=wE(s);return{width:e,height:t}}function r7(s,e,t){const n=Ni(e),a=Ei(e),i=t==="fixed",o=sl(s,!0,i,e);let l={scrollLeft:0,scrollTop:0};const c=ji(0);function d(){c.x=Mm(a)}if(n||!n&&!i)if((Mc(e)!=="body"||vd(a))&&(l=Nm(e)),n){const b=sl(e,!0,i,e);c.x=b.x+e.clientLeft,c.y=b.y+e.clientTop}else a&&d();i&&!n&&a&&d();const m=a&&!n&&!i?SE(a,l):ji(0),p=o.left+l.scrollLeft-c.x-m.x,f=o.top+l.scrollTop-c.y-m.y;return{x:p,y:f,width:o.width,height:o.height}}function _b(s){return Fa(s).position==="static"}function B1(s,e){if(!Ni(s)||Fa(s).position==="fixed")return null;if(e)return e(s);let t=s.offsetParent;return Ei(s)===t&&(t=t.ownerDocument.body),t}function CE(s,e){const t=wa(s);if(Cm(s))return t;if(!Ni(s)){let a=eo(s);for(;a&&!xc(a);){if(Hs(a)&&!_b(a))return a;a=eo(a)}return t}let n=B1(s,e);for(;n&&bW(n)&&_b(n);)n=B1(n,e);return n&&xc(n)&&_b(n)&&!sv(n)?t:n||kW(s)||t}const o7=async function(s){const e=this.getOffsetParent||CE,t=this.getDimensions,n=await t(s.floating);return{reference:r7(s.reference,await e(s.floating),s.strategy),floating:{x:0,y:0,width:n.width,height:n.height}}};function l7(s){return Fa(s).direction==="rtl"}const c7={convertOffsetParentRelativeRectToViewportRelativeRect:ZW,getDocumentElement:Ei,getClippingRect:a7,getOffsetParent:CE,getElementRects:o7,getClientRects:QW,getDimensions:i7,getScale:lc,isElement:Hs,isRTL:l7};function NE(s,e){return s.x===e.x&&s.y===e.y&&s.width===e.width&&s.height===e.height}function u7(s,e){let t=null,n;const a=Ei(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:m,top:p,width:f,height:b}=d;if(l||e(),!f||!b)return;const y=Xh(p),w=Xh(a.clientWidth-(m+f)),k=Xh(a.clientHeight-(p+b)),S=Xh(m),C={rootMargin:-y+"px "+-w+"px "+-k+"px "+-S+"px",threshold:qo(0,vc(1,c))||1};let A=!0;function D(M){const I=M[0].intersectionRatio;if(I!==c){if(!A)return o();I?o(!1,I):n=setTimeout(()=>{o(!1,1e-7)},1e3)}I===1&&!NE(d,s.getBoundingClientRect())&&o(),A=!1}try{t=new IntersectionObserver(D,{...C,root:a.ownerDocument})}catch{t=new IntersectionObserver(D,C)}t.observe(s)}return o(!0),i}function d7(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=ov(s),m=a||i?[...d?cd(d):[],...cd(e)]:[];m.forEach(S=>{a&&S.addEventListener("scroll",t,{passive:!0}),i&&S.addEventListener("resize",t)});const p=d&&l?u7(d,t):null;let f=-1,b=null;o&&(b=new ResizeObserver(S=>{let[j]=S;j&&j.target===d&&b&&(b.unobserve(e),cancelAnimationFrame(f),f=requestAnimationFrame(()=>{var C;(C=b)==null||C.observe(e)})),t()}),d&&!c&&b.observe(d),b.observe(e));let y,w=c?sl(s):null;c&&k();function k(){const S=sl(s);w&&!NE(w,S)&&t(),w=S,y=requestAnimationFrame(k)}return t(),()=>{var S;m.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 h7=VW,p7=WW,F1=GW,m7=(s,e,t)=>{const n=new Map,a={platform:c7,...t},i={...a.platform,_c:n};return UW(s,e,{...a,platform:i})};var f7=typeof document<"u",g7=function(){},hp=f7?x.useLayoutEffect:g7;function Xp(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(!Xp(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)&&!Xp(s[i],e[i]))return!1}return!0}return s!==s&&e!==e}function AE(s){return typeof window>"u"?1:(s.ownerDocument.defaultView||window).devicePixelRatio||1}function z1(s,e){const t=AE(s);return Math.round(e*t)/t}function Db(s){const e=x.useRef(s);return hp(()=>{e.current=s}),e}function b7(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,[m,p]=x.useState({x:0,y:0,strategy:t,placement:e,middlewareData:{},isPositioned:!1}),[f,b]=x.useState(n);Xp(f,n)||b(n);const[y,w]=x.useState(null),[k,S]=x.useState(null),j=x.useCallback(K=>{K!==M.current&&(M.current=K,w(K))},[]),C=x.useCallback(K=>{K!==I.current&&(I.current=K,S(K))},[]),A=i||y,D=o||k,M=x.useRef(null),I=x.useRef(null),E=x.useRef(m),_=c!=null,P=Db(c),L=Db(a),R=Db(d),z=x.useCallback(()=>{if(!M.current||!I.current)return;const K={placement:e,strategy:t,middleware:f};L.current&&(K.platform=L.current),m7(M.current,I.current,K).then(Z=>{const B={...Z,isPositioned:R.current!==!1};F.current&&!Xp(E.current,B)&&(E.current=B,jc.flushSync(()=>{p(B)}))})},[f,e,t,L,R]);hp(()=>{d===!1&&E.current.isPositioned&&(E.current.isPositioned=!1,p(K=>({...K,isPositioned:!1})))},[d]);const F=x.useRef(!1);hp(()=>(F.current=!0,()=>{F.current=!1}),[]),hp(()=>{if(A&&(M.current=A),D&&(I.current=D),A&&D){if(P.current)return P.current(A,D,z);z()}},[A,D,z,P,_]);const $=x.useMemo(()=>({reference:M,floating:I,setReference:j,setFloating:C}),[j,C]),U=x.useMemo(()=>({reference:A,floating:D}),[A,D]),G=x.useMemo(()=>{const K={position:t,left:0,top:0};if(!U.floating)return K;const Z=z1(U.floating,m.x),B=z1(U.floating,m.y);return l?{...K,transform:"translate("+Z+"px, "+B+"px)",...AE(U.floating)>=1.5&&{willChange:"transform"}}:{position:t,left:Z,top:B}},[t,l,U.floating,m.x,m.y]);return x.useMemo(()=>({...m,update:z,refs:$,elements:U,floatingStyles:G}),[m,z,$,U,G])}const y7=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?F1({element:n.current,padding:a}).fn(t):{}:n?F1({element:n,padding:a}).fn(t):{}}}},x7=(s,e)=>({...h7(s),options:[s,e]}),v7=(s,e)=>({...p7(s),options:[s,e]}),w7=(s,e)=>({...y7(s),options:[s,e]}),k7={...bA};let $1=!1,S7=0;const H1=()=>"floating-ui-"+Math.random().toString(36).slice(2,6)+S7++;function j7(){const[s,e]=x.useState(()=>$1?H1():void 0);return Kp(()=>{s==null&&e(H1())},[]),x.useEffect(()=>{$1=!0},[]),s}const C7=k7.useId,ME=C7||j7,N7=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:m=0,staticOffset:p,stroke:f,d:b,style:{transform:y,...w}={},...k}=e,S=ME(),[j,C]=x.useState(!1);if(Kp(()=>{if(!a)return;Fa(a).direction==="rtl"&&C(!0)},[a]),!a)return null;const[A,D]=n.split("-"),M=A==="top"||A==="bottom";let I=p;(M&&o!=null&&o.x||!M&&o!=null&&o.y)&&(I=null);const E=m*2,_=E/2,P=l/2*(d/-8+1),L=c/2*d/4,R=!!b,z=I&&D==="end"?"bottom":"top";let F=I&&D==="end"?"right":"left";I&&j&&(F=D==="end"?"left":"right");const $=(i==null?void 0:i.x)!=null?I||i.x:"",U=(i==null?void 0:i.y)!=null?I||i.y:"",G=b||"M0,0"+(" H"+l)+(" L"+(l-P)+","+(c-L))+(" Q"+l/2+","+c+" "+P+","+(c-L))+" Z",K={top:R?"rotate(180deg)":"",left:R?"rotate(90deg)":"rotate(-90deg)",bottom:R?"":"rotate(180deg)",right:R?"rotate(-90deg)":"rotate(90deg)"}[A];return r.jsxs("svg",{...k,"aria-hidden":!0,ref:t,width:R?l:l+E,height:l,viewBox:"0 0 "+l+" "+(c>l?c:l),style:{position:"absolute",pointerEvents:"none",[F]:$,[z]:U,[A]:M||R?"100%":"calc(100% - "+E/2+"px)",transform:[K,y].filter(Z=>!!Z).join(" "),...w},children:[E>0&&r.jsx("path",{clipPath:"url(#"+S+")",fill:"none",stroke:f,strokeWidth:E+(b?0:1),d:G}),r.jsx("path",{stroke:E&&!b?k.fill:"none",d:G}),r.jsx("clipPath",{id:S,children:r.jsx("rect",{x:-_,y:_*(R?-1:1),width:l+E,height:l})})]})});function A7(){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 M7=x.createContext(null),T7=x.createContext(null),E7=()=>{var s;return((s=x.useContext(M7))==null?void 0:s.id)||null},_7=()=>x.useContext(T7);function D7(s){const{open:e=!1,onOpenChange:t,elements:n}=s,a=ME(),i=x.useRef({}),[o]=x.useState(()=>A7()),l=E7()!=null,[c,d]=x.useState(n.reference),m=$W((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}),[]),f=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:m,elements:f,events:o,floatingId:a,refs:p}),[e,m,f,o,a,p])}function P7(s){s===void 0&&(s={});const{nodeId:e}=s,t=D7({...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),m=(a==null?void 0:a.domReference)||i,p=x.useRef(null),f=_7();Kp(()=>{m&&(p.current=m)},[m]);const b=b7({...s,elements:{...a,...l&&{reference:l}}}),y=x.useCallback(C=>{const A=Hs(C)?{getBoundingClientRect:()=>C.getBoundingClientRect(),getClientRects:()=>C.getClientRects(),contextElement:C}:C;c(A),b.refs.setReference(A)},[b.refs]),w=x.useCallback(C=>{(Hs(C)||C===null)&&(p.current=C,o(C)),(Hs(b.refs.reference.current)||b.refs.reference.current===null||C!==null&&!Hs(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:m}),[b.elements,m]),j=x.useMemo(()=>({...b,...n,refs:k,elements:S,nodeId:e}),[b,k,S,e,n]);return Kp(()=>{n.dataRef.current.floatingContext=j;const C=f==null?void 0:f.nodesRef.current.find(A=>A.id===e);C&&(C.context=j)}),x.useMemo(()=>({...b,context:j,refs:k,elements:S}),[b,k,S,j])}/*!