@agentxjs/portagent 0.0.7 → 0.0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -48,9 +48,9 @@ Error generating stack: `+x.message+`
48
48
  * @license MIT
49
49
  */var Ny="popstate";function gE(e={}){function t(r,o){let{pathname:a,search:l,hash:c}=r.location;return Uf("",{pathname:a,search:l,hash:c},o.state&&o.state.usr||null,o.state&&o.state.key||"default")}function n(r,o){return typeof o=="string"?o:ja(o)}return vE(t,n,null,e)}function at(e,t){if(e===!1||e===null||typeof e>"u")throw new Error(t)}function Gn(e,t){if(!e){typeof console<"u"&&console.warn(t);try{throw new Error(t)}catch{}}}function yE(){return Math.random().toString(36).substring(2,10)}function jy(e,t){return{usr:e.state,key:e.key,idx:t}}function Uf(e,t,n=null,r){return{pathname:typeof e=="string"?e:e.pathname,search:"",hash:"",...typeof t=="string"?po(t):t,state:n,key:t&&t.key||r||yE()}}function ja({pathname:e="/",search:t="",hash:n=""}){return t&&t!=="?"&&(e+=t.charAt(0)==="?"?t:"?"+t),n&&n!=="#"&&(e+=n.charAt(0)==="#"?n:"#"+n),e}function po(e){let t={};if(e){let n=e.indexOf("#");n>=0&&(t.hash=e.substring(n),e=e.substring(0,n));let r=e.indexOf("?");r>=0&&(t.search=e.substring(r),e=e.substring(0,r)),e&&(t.pathname=e)}return t}function vE(e,t,n,r={}){let{window:o=document.defaultView,v5Compat:a=!1}=r,l=o.history,c="POP",d=null,f=p();f==null&&(f=0,l.replaceState({...l.state,idx:f},""));function p(){return(l.state||{idx:null}).idx}function m(){c="POP";let C=p(),E=C==null?null:C-f;f=C,d&&d({action:c,location:S.location,delta:E})}function y(C,E){c="PUSH";let P=Uf(S.location,C,E);f=p()+1;let T=jy(P,f),O=S.createHref(P);try{l.pushState(T,"",O)}catch(V){if(V instanceof DOMException&&V.name==="DataCloneError")throw V;o.location.assign(O)}a&&d&&d({action:c,location:S.location,delta:1})}function v(C,E){c="REPLACE";let P=Uf(S.location,C,E);f=p();let T=jy(P,f),O=S.createHref(P);l.replaceState(T,"",O),a&&d&&d({action:c,location:S.location,delta:0})}function b(C){return xE(C)}let S={get action(){return c},get location(){return e(o,l)},listen(C){if(d)throw new Error("A history only accepts one active listener");return o.addEventListener(Ny,m),d=C,()=>{o.removeEventListener(Ny,m),d=null}},createHref(C){return t(o,C)},createURL:b,encodeLocation(C){let E=b(C);return{pathname:E.pathname,search:E.search,hash:E.hash}},push:y,replace:v,go(C){return l.go(C)}};return S}function xE(e,t=!1){let n="http://localhost";typeof window<"u"&&(n=window.location.origin!=="null"?window.location.origin:window.location.href),at(n,"No window.location.(origin|href) available to create URL");let r=typeof e=="string"?e:ja(e);return r=r.replace(/ $/,"%20"),!t&&r.startsWith("//")&&(r=n+r),new URL(r,n)}function jx(e,t,n="/"){return wE(e,t,n,!1)}function wE(e,t,n,r){let o=typeof t=="string"?po(t):t,a=Wr(o.pathname||"/",n);if(a==null)return null;let l=Mx(e);bE(l);let c=null;for(let d=0;c==null&&d<l.length;++d){let f=NE(a);c=AE(l[d],f,r)}return c}function Mx(e,t=[],n=[],r="",o=!1){let a=(l,c,d=o,f)=>{let p={relativePath:f===void 0?l.path||"":f,caseSensitive:l.caseSensitive===!0,childrenIndex:c,route:l};if(p.relativePath.startsWith("/")){if(!p.relativePath.startsWith(r)&&d)return;at(p.relativePath.startsWith(r),`Absolute route path "${p.relativePath}" nested under path "${r}" is not valid. An absolute child route path must start with the combined path of all its parent routes.`),p.relativePath=p.relativePath.slice(r.length)}let m=Hr([r,p.relativePath]),y=n.concat(p);l.children&&l.children.length>0&&(at(l.index!==!0,`Index routes must not have child routes. Please remove all child routes from route path "${m}".`),Mx(l.children,t,y,m,d)),!(l.path==null&&!l.index)&&t.push({path:m,score:_E(m,l.index),routesMeta:y})};return e.forEach((l,c)=>{var d;if(l.path===""||!((d=l.path)!=null&&d.includes("?")))a(l,c);else for(let f of Dx(l.path))a(l,c,!0,f)}),t}function Dx(e){let t=e.split("/");if(t.length===0)return[];let[n,...r]=t,o=n.endsWith("?"),a=n.replace(/\?$/,"");if(r.length===0)return o?[a,""]:[a];let l=Dx(r.join("/")),c=[];return c.push(...l.map(d=>d===""?a:[a,d].join("/"))),o&&c.push(...l),c.map(d=>e.startsWith("/")&&d===""?"/":d)}function bE(e){e.sort((t,n)=>t.score!==n.score?n.score-t.score:PE(t.routesMeta.map(r=>r.childrenIndex),n.routesMeta.map(r=>r.childrenIndex)))}var SE=/^:[\w-]+$/,kE=3,EE=2,CE=1,IE=10,TE=-2,My=e=>e==="*";function _E(e,t){let n=e.split("/"),r=n.length;return n.some(My)&&(r+=TE),t&&(r+=EE),n.filter(o=>!My(o)).reduce((o,a)=>o+(SE.test(a)?kE:a===""?CE:IE),r)}function PE(e,t){return e.length===t.length&&e.slice(0,-1).every((r,o)=>r===t[o])?e[e.length-1]-t[t.length-1]:0}function AE(e,t,n=!1){let{routesMeta:r}=e,o={},a="/",l=[];for(let c=0;c<r.length;++c){let d=r[c],f=c===r.length-1,p=a==="/"?t:t.slice(a.length)||"/",m=zu({path:d.relativePath,caseSensitive:d.caseSensitive,end:f},p),y=d.route;if(!m&&f&&n&&!r[r.length-1].route.index&&(m=zu({path:d.relativePath,caseSensitive:d.caseSensitive,end:!1},p)),!m)return null;Object.assign(o,m.params),l.push({params:o,pathname:Hr([a,m.pathname]),pathnameBase:zE(Hr([a,m.pathnameBase])),route:y}),m.pathnameBase!=="/"&&(a=Hr([a,m.pathnameBase]))}return l}function zu(e,t){typeof e=="string"&&(e={path:e,caseSensitive:!1,end:!0});let[n,r]=RE(e.path,e.caseSensitive,e.end),o=t.match(n);if(!o)return null;let a=o[0],l=a.replace(/(.)\/+$/,"$1"),c=o.slice(1);return{params:r.reduce((f,{paramName:p,isOptional:m},y)=>{if(p==="*"){let b=c[y]||"";l=a.slice(0,a.length-b.length).replace(/(.)\/+$/,"$1")}const v=c[y];return m&&!v?f[p]=void 0:f[p]=(v||"").replace(/%2F/g,"/"),f},{}),pathname:a,pathnameBase:l,pattern:e}}function RE(e,t=!1,n=!0){Gn(e==="*"||!e.endsWith("*")||e.endsWith("/*"),`Route path "${e}" will be treated as if it were "${e.replace(/\*$/,"/*")}" because the \`*\` character must always follow a \`/\` in the pattern. To get rid of this warning, please change the route path to "${e.replace(/\*$/,"/*")}".`);let r=[],o="^"+e.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(l,c,d)=>(r.push({paramName:c,isOptional:d!=null}),d?"/?([^\\/]+)?":"/([^\\/]+)")).replace(/\/([\w-]+)\?(\/|$)/g,"(/$1)?$2");return e.endsWith("*")?(r.push({paramName:"*"}),o+=e==="*"||e==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):n?o+="\\/*$":e!==""&&e!=="/"&&(o+="(?:(?=\\/|$))"),[new RegExp(o,t?void 0:"i"),r]}function NE(e){try{return e.split("/").map(t=>decodeURIComponent(t).replace(/\//g,"%2F")).join("/")}catch(t){return Gn(!1,`The URL path "${e}" could not be decoded because it is a malformed URL segment. This is probably due to a bad percent encoding (${t}).`),e}}function Wr(e,t){if(t==="/")return e;if(!e.toLowerCase().startsWith(t.toLowerCase()))return null;let n=t.endsWith("/")?t.length-1:t.length,r=e.charAt(n);return r&&r!=="/"?null:e.slice(n)||"/"}var jE=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,ME=e=>jE.test(e);function DE(e,t="/"){let{pathname:n,search:r="",hash:o=""}=typeof e=="string"?po(e):e,a;if(n)if(ME(n))a=n;else{if(n.includes("//")){let l=n;n=n.replace(/\/\/+/g,"/"),Gn(!1,`Pathnames cannot have embedded double slashes - normalizing ${l} -> ${n}`)}n.startsWith("/")?a=Dy(n.substring(1),"/"):a=Dy(n,t)}else a=t;return{pathname:a,search:OE(r),hash:FE(o)}}function Dy(e,t){let n=t.replace(/\/+$/,"").split("/");return e.split("/").forEach(o=>{o===".."?n.length>1&&n.pop():o!=="."&&n.push(o)}),n.length>1?n.join("/"):"/"}function Xd(e,t,n,r){return`Cannot include a '${e}' character in a manually specified \`to.${t}\` field [${JSON.stringify(r)}]. Please separate it out to the \`to.${n}\` field. Alternatively you may provide the full path as a string in <Link to="..."> and the router will parse it for you.`}function LE(e){return e.filter((t,n)=>n===0||t.route.path&&t.route.path.length>0)}function Uh(e){let t=LE(e);return t.map((n,r)=>r===t.length-1?n.pathname:n.pathnameBase)}function Hh(e,t,n,r=!1){let o;typeof e=="string"?o=po(e):(o={...e},at(!o.pathname||!o.pathname.includes("?"),Xd("?","pathname","search",o)),at(!o.pathname||!o.pathname.includes("#"),Xd("#","pathname","hash",o)),at(!o.search||!o.search.includes("#"),Xd("#","search","hash",o)));let a=e===""||o.pathname==="",l=a?"/":o.pathname,c;if(l==null)c=n;else{let m=t.length-1;if(!r&&l.startsWith("..")){let y=l.split("/");for(;y[0]==="..";)y.shift(),m-=1;o.pathname=y.join("/")}c=m>=0?t[m]:"/"}let d=DE(o,c),f=l&&l!=="/"&&l.endsWith("/"),p=(a||l===".")&&n.endsWith("/");return!d.pathname.endsWith("/")&&(f||p)&&(d.pathname+="/"),d}var Hr=e=>e.join("/").replace(/\/\/+/g,"/"),zE=e=>e.replace(/\/+$/,"").replace(/^\/*/,"/"),OE=e=>!e||e==="?"?"":e.startsWith("?")?e:"?"+e,FE=e=>!e||e==="#"?"":e.startsWith("#")?e:"#"+e;function VE(e){return e!=null&&typeof e.status=="number"&&typeof e.statusText=="string"&&typeof e.internal=="boolean"&&"data"in e}Object.getOwnPropertyNames(Object.prototype).sort().join("\0");var Lx=["POST","PUT","PATCH","DELETE"];new Set(Lx);var BE=["GET",...Lx];new Set(BE);var mo=I.createContext(null);mo.displayName="DataRouter";var Ju=I.createContext(null);Ju.displayName="DataRouterState";I.createContext(!1);var zx=I.createContext({isTransitioning:!1});zx.displayName="ViewTransition";var $E=I.createContext(new Map);$E.displayName="Fetchers";var UE=I.createContext(null);UE.displayName="Await";var dr=I.createContext(null);dr.displayName="Navigation";var Ha=I.createContext(null);Ha.displayName="Location";var Ir=I.createContext({outlet:null,matches:[],isDataRoute:!1});Ir.displayName="Route";var Wh=I.createContext(null);Wh.displayName="RouteError";function HE(e,{relative:t}={}){at(go(),"useHref() may be used only in the context of a <Router> component.");let{basename:n,navigator:r}=I.useContext(dr),{hash:o,pathname:a,search:l}=Wa(e,{relative:t}),c=a;return n!=="/"&&(c=a==="/"?n:Hr([n,a])),r.createHref({pathname:c,search:l,hash:o})}function go(){return I.useContext(Ha)!=null}function Ri(){return at(go(),"useLocation() may be used only in the context of a <Router> component."),I.useContext(Ha).location}var Ox="You should call navigate() in a React.useEffect(), not when your component is first rendered.";function Fx(e){I.useContext(dr).static||I.useLayoutEffect(e)}function Zu(){let{isDataRoute:e}=I.useContext(Ir);return e?rC():WE()}function WE(){at(go(),"useNavigate() may be used only in the context of a <Router> component.");let e=I.useContext(mo),{basename:t,navigator:n}=I.useContext(dr),{matches:r}=I.useContext(Ir),{pathname:o}=Ri(),a=JSON.stringify(Uh(r)),l=I.useRef(!1);return Fx(()=>{l.current=!0}),I.useCallback((d,f={})=>{if(Gn(l.current,Ox),!l.current)return;if(typeof d=="number"){n.go(d);return}let p=Hh(d,JSON.parse(a),o,f.relative==="path");e==null&&t!=="/"&&(p.pathname=p.pathname==="/"?t:Hr([t,p.pathname])),(f.replace?n.replace:n.push)(p,f.state,f)},[t,n,a,o,e])}I.createContext(null);function Wa(e,{relative:t}={}){let{matches:n}=I.useContext(Ir),{pathname:r}=Ri(),o=JSON.stringify(Uh(n));return I.useMemo(()=>Hh(e,JSON.parse(o),r,t==="path"),[e,o,r,t])}function qE(e,t){return Vx(e,t)}function Vx(e,t,n,r,o){var P;at(go(),"useRoutes() may be used only in the context of a <Router> component.");let{navigator:a}=I.useContext(dr),{matches:l}=I.useContext(Ir),c=l[l.length-1],d=c?c.params:{},f=c?c.pathname:"/",p=c?c.pathnameBase:"/",m=c&&c.route;{let T=m&&m.path||"";Bx(f,!m||T.endsWith("*")||T.endsWith("*?"),`You rendered descendant <Routes> (or called \`useRoutes()\`) at "${f}" (under <Route path="${T}">) but the parent route path has no trailing "*". This means if you navigate deeper, the parent won't match anymore and therefore the child routes will never render.
50
50
 
51
- Please change the parent <Route path="${T}"> to <Route path="${T==="/"?"*":`${T}/*`}">.`)}let y=Ri(),v;if(t){let T=typeof t=="string"?po(t):t;at(p==="/"||((P=T.pathname)==null?void 0:P.startsWith(p)),`When overriding the location using \`<Routes location>\` or \`useRoutes(routes, location)\`, the location pathname must begin with the portion of the URL pathname that was matched by all parent routes. The current pathname base is "${p}" but pathname "${T.pathname}" was given in the \`location\` prop.`),v=T}else v=y;let b=v.pathname||"/",S=b;if(p!=="/"){let T=p.replace(/^\//,"").split("/");S="/"+b.replace(/^\//,"").split("/").slice(T.length).join("/")}let C=jx(e,{pathname:S});Gn(m||C!=null,`No routes matched location "${v.pathname}${v.search}${v.hash}" `),Gn(C==null||C[C.length-1].route.element!==void 0||C[C.length-1].route.Component!==void 0||C[C.length-1].route.lazy!==void 0,`Matched leaf route at location "${v.pathname}${v.search}${v.hash}" does not have an element or Component. This means it will render an <Outlet /> with a null value by default resulting in an "empty" page.`);let E=QE(C&&C.map(T=>Object.assign({},T,{params:Object.assign({},d,T.params),pathname:Hr([p,a.encodeLocation?a.encodeLocation(T.pathname.replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:T.pathname]),pathnameBase:T.pathnameBase==="/"?p:Hr([p,a.encodeLocation?a.encodeLocation(T.pathnameBase.replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:T.pathnameBase])})),l,n,r,o);return t&&E?I.createElement(Ha.Provider,{value:{location:{pathname:"/",search:"",hash:"",state:null,key:"default",...v},navigationType:"POP"}},E):E}function GE(){let e=nC(),t=VE(e)?`${e.status} ${e.statusText}`:e instanceof Error?e.message:JSON.stringify(e),n=e instanceof Error?e.stack:null,r="rgba(200,200,200, 0.5)",o={padding:"0.5rem",backgroundColor:r},a={padding:"2px 4px",backgroundColor:r},l=null;return console.error("Error handled by React Router default ErrorBoundary:",e),l=I.createElement(I.Fragment,null,I.createElement("p",null,"💿 Hey developer 👋"),I.createElement("p",null,"You can provide a way better UX than this when your app throws errors by providing your own ",I.createElement("code",{style:a},"ErrorBoundary")," or"," ",I.createElement("code",{style:a},"errorElement")," prop on your route.")),I.createElement(I.Fragment,null,I.createElement("h2",null,"Unexpected Application Error!"),I.createElement("h3",{style:{fontStyle:"italic"}},t),n?I.createElement("pre",{style:o},n):null,l)}var KE=I.createElement(GE,null),YE=class extends I.Component{constructor(e){super(e),this.state={location:e.location,revalidation:e.revalidation,error:e.error}}static getDerivedStateFromError(e){return{error:e}}static getDerivedStateFromProps(e,t){return t.location!==e.location||t.revalidation!=="idle"&&e.revalidation==="idle"?{error:e.error,location:e.location,revalidation:e.revalidation}:{error:e.error!==void 0?e.error:t.error,location:t.location,revalidation:e.revalidation||t.revalidation}}componentDidCatch(e,t){this.props.onError?this.props.onError(e,t):console.error("React Router caught the following error during render",e)}render(){return this.state.error!==void 0?I.createElement(Ir.Provider,{value:this.props.routeContext},I.createElement(Wh.Provider,{value:this.state.error,children:this.props.component})):this.props.children}};function XE({routeContext:e,match:t,children:n}){let r=I.useContext(mo);return r&&r.static&&r.staticContext&&(t.route.errorElement||t.route.ErrorBoundary)&&(r.staticContext._deepestRenderedBoundaryId=t.route.id),I.createElement(Ir.Provider,{value:e},n)}function QE(e,t=[],n=null,r=null,o=null){if(e==null){if(!n)return null;if(n.errors)e=n.matches;else if(t.length===0&&!n.initialized&&n.matches.length>0)e=n.matches;else return null}let a=e,l=n==null?void 0:n.errors;if(l!=null){let p=a.findIndex(m=>m.route.id&&(l==null?void 0:l[m.route.id])!==void 0);at(p>=0,`Could not find a matching route for errors on route IDs: ${Object.keys(l).join(",")}`),a=a.slice(0,Math.min(a.length,p+1))}let c=!1,d=-1;if(n)for(let p=0;p<a.length;p++){let m=a[p];if((m.route.HydrateFallback||m.route.hydrateFallbackElement)&&(d=p),m.route.id){let{loaderData:y,errors:v}=n,b=m.route.loader&&!y.hasOwnProperty(m.route.id)&&(!v||v[m.route.id]===void 0);if(m.route.lazy||b){c=!0,d>=0?a=a.slice(0,d+1):a=[a[0]];break}}}let f=n&&r?(p,m)=>{var y,v;r(p,{location:n.location,params:((v=(y=n.matches)==null?void 0:y[0])==null?void 0:v.params)??{},errorInfo:m})}:void 0;return a.reduceRight((p,m,y)=>{let v,b=!1,S=null,C=null;n&&(v=l&&m.route.id?l[m.route.id]:void 0,S=m.route.errorElement||KE,c&&(d<0&&y===0?(Bx("route-fallback",!1,"No `HydrateFallback` element provided to render during initial hydration"),b=!0,C=null):d===y&&(b=!0,C=m.route.hydrateFallbackElement||null)));let E=t.concat(a.slice(0,y+1)),P=()=>{let T;return v?T=S:b?T=C:m.route.Component?T=I.createElement(m.route.Component,null):m.route.element?T=m.route.element:T=p,I.createElement(XE,{match:m,routeContext:{outlet:p,matches:E,isDataRoute:n!=null},children:T})};return n&&(m.route.ErrorBoundary||m.route.errorElement||y===0)?I.createElement(YE,{location:n.location,revalidation:n.revalidation,component:S,error:v,children:P(),routeContext:{outlet:null,matches:E,isDataRoute:!0},onError:f}):P()},null)}function qh(e){return`${e} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function JE(e){let t=I.useContext(mo);return at(t,qh(e)),t}function ZE(e){let t=I.useContext(Ju);return at(t,qh(e)),t}function eC(e){let t=I.useContext(Ir);return at(t,qh(e)),t}function Gh(e){let t=eC(e),n=t.matches[t.matches.length-1];return at(n.route.id,`${e} can only be used on routes that contain a unique "id"`),n.route.id}function tC(){return Gh("useRouteId")}function nC(){var r;let e=I.useContext(Wh),t=ZE("useRouteError"),n=Gh("useRouteError");return e!==void 0?e:(r=t.errors)==null?void 0:r[n]}function rC(){let{router:e}=JE("useNavigate"),t=Gh("useNavigate"),n=I.useRef(!1);return Fx(()=>{n.current=!0}),I.useCallback(async(o,a={})=>{Gn(n.current,Ox),n.current&&(typeof o=="number"?e.navigate(o):await e.navigate(o,{fromRouteId:t,...a}))},[e,t])}var Ly={};function Bx(e,t,n){!t&&!Ly[e]&&(Ly[e]=!0,Gn(!1,n))}I.memo(iC);function iC({routes:e,future:t,state:n,unstable_onError:r}){return Vx(e,void 0,n,r,t)}function Hf({to:e,replace:t,state:n,relative:r}){at(go(),"<Navigate> may be used only in the context of a <Router> component.");let{static:o}=I.useContext(dr);Gn(!o,"<Navigate> must not be used on the initial render in a <StaticRouter>. This is a no-op, but you should modify your code so the <Navigate> is only ever rendered in response to some user interaction or state change.");let{matches:a}=I.useContext(Ir),{pathname:l}=Ri(),c=Zu(),d=Hh(e,Uh(a),l,r==="path"),f=JSON.stringify(d);return I.useEffect(()=>{c(JSON.parse(f),{replace:t,state:n,relative:r})},[c,f,r,t,n]),null}function Js(e){at(!1,"A <Route> is only ever to be used as the child of <Routes> element, never rendered directly. Please wrap your <Route> in a <Routes>.")}function sC({basename:e="/",children:t=null,location:n,navigationType:r="POP",navigator:o,static:a=!1}){at(!go(),"You cannot render a <Router> inside another <Router>. You should never have more than one in your app.");let l=e.replace(/^\/*/,"/"),c=I.useMemo(()=>({basename:l,navigator:o,static:a,future:{}}),[l,o,a]);typeof n=="string"&&(n=po(n));let{pathname:d="/",search:f="",hash:p="",state:m=null,key:y="default"}=n,v=I.useMemo(()=>{let b=Wr(d,l);return b==null?null:{location:{pathname:b,search:f,hash:p,state:m,key:y},navigationType:r}},[l,d,f,p,m,y,r]);return Gn(v!=null,`<Router basename="${l}"> is not able to match the URL "${d}${f}${p}" because it does not start with the basename, so the <Router> won't render anything.`),v==null?null:I.createElement(dr.Provider,{value:c},I.createElement(Ha.Provider,{children:t,value:v}))}function oC({children:e,location:t}){return qE(Wf(e),t)}function Wf(e,t=[]){let n=[];return I.Children.forEach(e,(r,o)=>{if(!I.isValidElement(r))return;let a=[...t,o];if(r.type===I.Fragment){n.push.apply(n,Wf(r.props.children,a));return}at(r.type===Js,`[${typeof r.type=="string"?r.type:r.type.name}] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>`),at(!r.props.index||!r.props.children,"An index route cannot have child routes.");let l={id:r.props.id||a.join("-"),caseSensitive:r.props.caseSensitive,element:r.props.element,Component:r.props.Component,index:r.props.index,path:r.props.path,middleware:r.props.middleware,loader:r.props.loader,action:r.props.action,hydrateFallbackElement:r.props.hydrateFallbackElement,HydrateFallback:r.props.HydrateFallback,errorElement:r.props.errorElement,ErrorBoundary:r.props.ErrorBoundary,hasErrorBoundary:r.props.hasErrorBoundary===!0||r.props.ErrorBoundary!=null||r.props.errorElement!=null,shouldRevalidate:r.props.shouldRevalidate,handle:r.props.handle,lazy:r.props.lazy};r.props.children&&(l.children=Wf(r.props.children,a)),n.push(l)}),n}var Tu="get",_u="application/x-www-form-urlencoded";function ec(e){return e!=null&&typeof e.tagName=="string"}function aC(e){return ec(e)&&e.tagName.toLowerCase()==="button"}function lC(e){return ec(e)&&e.tagName.toLowerCase()==="form"}function uC(e){return ec(e)&&e.tagName.toLowerCase()==="input"}function cC(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}function dC(e,t){return e.button===0&&(!t||t==="_self")&&!cC(e)}var lu=null;function fC(){if(lu===null)try{new FormData(document.createElement("form"),0),lu=!1}catch{lu=!0}return lu}var hC=new Set(["application/x-www-form-urlencoded","multipart/form-data","text/plain"]);function Qd(e){return e!=null&&!hC.has(e)?(Gn(!1,`"${e}" is not a valid \`encType\` for \`<Form>\`/\`<fetcher.Form>\` and will default to "${_u}"`),null):e}function pC(e,t){let n,r,o,a,l;if(lC(e)){let c=e.getAttribute("action");r=c?Wr(c,t):null,n=e.getAttribute("method")||Tu,o=Qd(e.getAttribute("enctype"))||_u,a=new FormData(e)}else if(aC(e)||uC(e)&&(e.type==="submit"||e.type==="image")){let c=e.form;if(c==null)throw new Error('Cannot submit a <button> or <input type="submit"> without a <form>');let d=e.getAttribute("formaction")||c.getAttribute("action");if(r=d?Wr(d,t):null,n=e.getAttribute("formmethod")||c.getAttribute("method")||Tu,o=Qd(e.getAttribute("formenctype"))||Qd(c.getAttribute("enctype"))||_u,a=new FormData(c,e),!fC()){let{name:f,type:p,value:m}=e;if(p==="image"){let y=f?`${f}.`:"";a.append(`${y}x`,"0"),a.append(`${y}y`,"0")}else f&&a.append(f,m)}}else{if(ec(e))throw new Error('Cannot submit element that is not <form>, <button>, or <input type="submit|image">');n=Tu,r=null,o=_u,l=e}return a&&o==="text/plain"&&(l=a,a=void 0),{action:r,method:n.toLowerCase(),encType:o,formData:a,body:l}}Object.getOwnPropertyNames(Object.prototype).sort().join("\0");function Kh(e,t){if(e===!1||e===null||typeof e>"u")throw new Error(t)}function mC(e,t,n){let r=typeof e=="string"?new URL(e,typeof window>"u"?"server://singlefetch/":window.location.origin):e;return r.pathname==="/"?r.pathname=`_root.${n}`:t&&Wr(r.pathname,t)==="/"?r.pathname=`${t.replace(/\/$/,"")}/_root.${n}`:r.pathname=`${r.pathname.replace(/\/$/,"")}.${n}`,r}async function gC(e,t){if(e.id in t)return t[e.id];try{let n=await import(e.module);return t[e.id]=n,n}catch(n){return console.error(`Error loading route module \`${e.module}\`, reloading page...`),console.error(n),window.__reactRouterContext&&window.__reactRouterContext.isSpaMode,window.location.reload(),new Promise(()=>{})}}function yC(e){return e==null?!1:e.href==null?e.rel==="preload"&&typeof e.imageSrcSet=="string"&&typeof e.imageSizes=="string":typeof e.rel=="string"&&typeof e.href=="string"}async function vC(e,t,n){let r=await Promise.all(e.map(async o=>{let a=t.routes[o.route.id];if(a){let l=await gC(a,n);return l.links?l.links():[]}return[]}));return SC(r.flat(1).filter(yC).filter(o=>o.rel==="stylesheet"||o.rel==="preload").map(o=>o.rel==="stylesheet"?{...o,rel:"prefetch",as:"style"}:{...o,rel:"prefetch"}))}function zy(e,t,n,r,o,a){let l=(d,f)=>n[f]?d.route.id!==n[f].route.id:!0,c=(d,f)=>{var p;return n[f].pathname!==d.pathname||((p=n[f].route.path)==null?void 0:p.endsWith("*"))&&n[f].params["*"]!==d.params["*"]};return a==="assets"?t.filter((d,f)=>l(d,f)||c(d,f)):a==="data"?t.filter((d,f)=>{var m;let p=r.routes[d.route.id];if(!p||!p.hasLoader)return!1;if(l(d,f)||c(d,f))return!0;if(d.route.shouldRevalidate){let y=d.route.shouldRevalidate({currentUrl:new URL(o.pathname+o.search+o.hash,window.origin),currentParams:((m=n[0])==null?void 0:m.params)||{},nextUrl:new URL(e,window.origin),nextParams:d.params,defaultShouldRevalidate:!0});if(typeof y=="boolean")return y}return!0}):[]}function xC(e,t,{includeHydrateFallback:n}={}){return wC(e.map(r=>{let o=t.routes[r.route.id];if(!o)return[];let a=[o.module];return o.clientActionModule&&(a=a.concat(o.clientActionModule)),o.clientLoaderModule&&(a=a.concat(o.clientLoaderModule)),n&&o.hydrateFallbackModule&&(a=a.concat(o.hydrateFallbackModule)),o.imports&&(a=a.concat(o.imports)),a}).flat(1))}function wC(e){return[...new Set(e)]}function bC(e){let t={},n=Object.keys(e).sort();for(let r of n)t[r]=e[r];return t}function SC(e,t){let n=new Set;return new Set(t),e.reduce((r,o)=>{let a=JSON.stringify(bC(o));return n.has(a)||(n.add(a),r.push({key:a,link:o})),r},[])}function $x(){let e=I.useContext(mo);return Kh(e,"You must render this element inside a <DataRouterContext.Provider> element"),e}function kC(){let e=I.useContext(Ju);return Kh(e,"You must render this element inside a <DataRouterStateContext.Provider> element"),e}var Yh=I.createContext(void 0);Yh.displayName="FrameworkContext";function Ux(){let e=I.useContext(Yh);return Kh(e,"You must render this element inside a <HydratedRouter> element"),e}function EC(e,t){let n=I.useContext(Yh),[r,o]=I.useState(!1),[a,l]=I.useState(!1),{onFocus:c,onBlur:d,onMouseEnter:f,onMouseLeave:p,onTouchStart:m}=t,y=I.useRef(null);I.useEffect(()=>{if(e==="render"&&l(!0),e==="viewport"){let S=E=>{E.forEach(P=>{l(P.isIntersecting)})},C=new IntersectionObserver(S,{threshold:.5});return y.current&&C.observe(y.current),()=>{C.disconnect()}}},[e]),I.useEffect(()=>{if(r){let S=setTimeout(()=>{l(!0)},100);return()=>{clearTimeout(S)}}},[r]);let v=()=>{o(!0)},b=()=>{o(!1),l(!1)};return n?e!=="intent"?[a,y,{}]:[a,y,{onFocus:ua(c,v),onBlur:ua(d,b),onMouseEnter:ua(f,v),onMouseLeave:ua(p,b),onTouchStart:ua(m,v)}]:[!1,y,{}]}function ua(e,t){return n=>{e&&e(n),n.defaultPrevented||t(n)}}function CC({page:e,...t}){let{router:n}=$x(),r=I.useMemo(()=>jx(n.routes,e,n.basename),[n.routes,e,n.basename]);return r?I.createElement(TC,{page:e,matches:r,...t}):null}function IC(e){let{manifest:t,routeModules:n}=Ux(),[r,o]=I.useState([]);return I.useEffect(()=>{let a=!1;return vC(e,t,n).then(l=>{a||o(l)}),()=>{a=!0}},[e,t,n]),r}function TC({page:e,matches:t,...n}){let r=Ri(),{manifest:o,routeModules:a}=Ux(),{basename:l}=$x(),{loaderData:c,matches:d}=kC(),f=I.useMemo(()=>zy(e,t,d,o,r,"data"),[e,t,d,o,r]),p=I.useMemo(()=>zy(e,t,d,o,r,"assets"),[e,t,d,o,r]),m=I.useMemo(()=>{if(e===r.pathname+r.search+r.hash)return[];let b=new Set,S=!1;if(t.forEach(E=>{var T;let P=o.routes[E.route.id];!P||!P.hasLoader||(!f.some(O=>O.route.id===E.route.id)&&E.route.id in c&&((T=a[E.route.id])!=null&&T.shouldRevalidate)||P.hasClientLoader?S=!0:b.add(E.route.id))}),b.size===0)return[];let C=mC(e,l,"data");return S&&b.size>0&&C.searchParams.set("_routes",t.filter(E=>b.has(E.route.id)).map(E=>E.route.id).join(",")),[C.pathname+C.search]},[l,c,r,o,f,t,e,a]),y=I.useMemo(()=>xC(p,o),[p,o]),v=IC(p);return I.createElement(I.Fragment,null,m.map(b=>I.createElement("link",{key:b,rel:"prefetch",as:"fetch",href:b,...n})),y.map(b=>I.createElement("link",{key:b,rel:"modulepreload",href:b,...n})),v.map(({key:b,link:S})=>I.createElement("link",{key:b,nonce:n.nonce,...S})))}function _C(...e){return t=>{e.forEach(n=>{typeof n=="function"?n(t):n!=null&&(n.current=t)})}}var Hx=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";try{Hx&&(window.__reactRouterVersion="7.9.6")}catch{}function PC({basename:e,children:t,window:n}){let r=I.useRef();r.current==null&&(r.current=gE({window:n,v5Compat:!0}));let o=r.current,[a,l]=I.useState({action:o.action,location:o.location}),c=I.useCallback(d=>{I.startTransition(()=>l(d))},[l]);return I.useLayoutEffect(()=>o.listen(c),[o,c]),I.createElement(sC,{basename:e,children:t,location:a.location,navigationType:a.action,navigator:o})}var Wx=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,tc=I.forwardRef(function({onClick:t,discover:n="render",prefetch:r="none",relative:o,reloadDocument:a,replace:l,state:c,target:d,to:f,preventScrollReset:p,viewTransition:m,...y},v){let{basename:b}=I.useContext(dr),S=typeof f=="string"&&Wx.test(f),C,E=!1;if(typeof f=="string"&&S&&(C=f,Hx))try{let ee=new URL(window.location.href),L=f.startsWith("//")?new URL(ee.protocol+f):new URL(f),te=Wr(L.pathname,b);L.origin===ee.origin&&te!=null?f=te+L.search+L.hash:E=!0}catch{Gn(!1,`<Link to="${f}"> contains an invalid URL which will probably break when clicked - please update to a valid URL path.`)}let P=HE(f,{relative:o}),[T,O,V]=EC(r,y),N=jC(f,{replace:l,state:c,target:d,preventScrollReset:p,relative:o,viewTransition:m});function D(ee){t&&t(ee),ee.defaultPrevented||N(ee)}let H=I.createElement("a",{...y,...V,href:C||P,onClick:E||a?t:D,ref:_C(v,O),target:d,"data-discover":!S&&n==="render"?"true":void 0});return T&&!S?I.createElement(I.Fragment,null,H,I.createElement(CC,{page:P})):H});tc.displayName="Link";var AC=I.forwardRef(function({"aria-current":t="page",caseSensitive:n=!1,className:r="",end:o=!1,style:a,to:l,viewTransition:c,children:d,...f},p){let m=Wa(l,{relative:f.relative}),y=Ri(),v=I.useContext(Ju),{navigator:b,basename:S}=I.useContext(dr),C=v!=null&&OC(m)&&c===!0,E=b.encodeLocation?b.encodeLocation(m).pathname:m.pathname,P=y.pathname,T=v&&v.navigation&&v.navigation.location?v.navigation.location.pathname:null;n||(P=P.toLowerCase(),T=T?T.toLowerCase():null,E=E.toLowerCase()),T&&S&&(T=Wr(T,S)||T);const O=E!=="/"&&E.endsWith("/")?E.length-1:E.length;let V=P===E||!o&&P.startsWith(E)&&P.charAt(O)==="/",N=T!=null&&(T===E||!o&&T.startsWith(E)&&T.charAt(E.length)==="/"),D={isActive:V,isPending:N,isTransitioning:C},H=V?t:void 0,ee;typeof r=="function"?ee=r(D):ee=[r,V?"active":null,N?"pending":null,C?"transitioning":null].filter(Boolean).join(" ");let L=typeof a=="function"?a(D):a;return I.createElement(tc,{...f,"aria-current":H,className:ee,ref:p,style:L,to:l,viewTransition:c},typeof d=="function"?d(D):d)});AC.displayName="NavLink";var RC=I.forwardRef(({discover:e="render",fetcherKey:t,navigate:n,reloadDocument:r,replace:o,state:a,method:l=Tu,action:c,onSubmit:d,relative:f,preventScrollReset:p,viewTransition:m,...y},v)=>{let b=LC(),S=zC(c,{relative:f}),C=l.toLowerCase()==="get"?"get":"post",E=typeof c=="string"&&Wx.test(c),P=T=>{if(d&&d(T),T.defaultPrevented)return;T.preventDefault();let O=T.nativeEvent.submitter,V=(O==null?void 0:O.getAttribute("formmethod"))||l;b(O||T.currentTarget,{fetcherKey:t,method:V,navigate:n,replace:o,state:a,relative:f,preventScrollReset:p,viewTransition:m})};return I.createElement("form",{ref:v,method:C,action:S,onSubmit:r?d:P,...y,"data-discover":!E&&e==="render"?"true":void 0})});RC.displayName="Form";function NC(e){return`${e} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function qx(e){let t=I.useContext(mo);return at(t,NC(e)),t}function jC(e,{target:t,replace:n,state:r,preventScrollReset:o,relative:a,viewTransition:l}={}){let c=Zu(),d=Ri(),f=Wa(e,{relative:a});return I.useCallback(p=>{if(dC(p,t)){p.preventDefault();let m=n!==void 0?n:ja(d)===ja(f);c(e,{replace:m,state:r,preventScrollReset:o,relative:a,viewTransition:l})}},[d,c,f,n,r,t,e,o,a,l])}var MC=0,DC=()=>`__${String(++MC)}__`;function LC(){let{router:e}=qx("useSubmit"),{basename:t}=I.useContext(dr),n=tC();return I.useCallback(async(r,o={})=>{let{action:a,method:l,encType:c,formData:d,body:f}=pC(r,t);if(o.navigate===!1){let p=o.fetcherKey||DC();await e.fetch(p,n,o.action||a,{preventScrollReset:o.preventScrollReset,formData:d,body:f,formMethod:o.method||l,formEncType:o.encType||c,flushSync:o.flushSync})}else await e.navigate(o.action||a,{preventScrollReset:o.preventScrollReset,formData:d,body:f,formMethod:o.method||l,formEncType:o.encType||c,replace:o.replace,state:o.state,fromRouteId:n,flushSync:o.flushSync,viewTransition:o.viewTransition})},[e,t,n])}function zC(e,{relative:t}={}){let{basename:n}=I.useContext(dr),r=I.useContext(Ir);at(r,"useFormAction must be used inside a RouteContext");let[o]=r.matches.slice(-1),a={...Wa(e||".",{relative:t})},l=Ri();if(e==null){a.search=l.search;let c=new URLSearchParams(a.search),d=c.getAll("index");if(d.some(p=>p==="")){c.delete("index"),d.filter(m=>m).forEach(m=>c.append("index",m));let p=c.toString();a.search=p?`?${p}`:""}}return(!e||e===".")&&o.route.index&&(a.search=a.search?a.search.replace(/^\?/,"?index&"):"?index"),n!=="/"&&(a.pathname=a.pathname==="/"?n:Hr([n,a.pathname])),ja(a)}function OC(e,{relative:t}={}){let n=I.useContext(zx);at(n!=null,"`useViewTransitionState` must be used within `react-router-dom`'s `RouterProvider`. Did you accidentally import `RouterProvider` from `react-router`?");let{basename:r}=qx("useViewTransitionState"),o=Wa(e,{relative:t});if(!n.isTransitioning)return!1;let a=Wr(n.currentLocation.pathname,r)||n.currentLocation.pathname,l=Wr(n.nextLocation.pathname,r)||n.nextLocation.pathname;return zu(o.pathname,l)!=null||zu(o.pathname,a)!=null}var FC=Nx();const Gx=I.createContext(null),ss="portagent_token",qs="portagent_user";async function VC(e,t){try{const n=await fetch("/api/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({usernameOrEmail:e,password:t})}),r=await n.json();return n.ok?{token:r.token,user:r.user}:{error:r.error||"Login failed"}}catch{return{error:"Network error"}}}async function BC(e,t,n,r){try{const o=await fetch("/api/auth/register",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:e,email:t,password:n,displayName:r})}),a=await o.json();return o.ok?{token:a.token,user:a.user}:{error:a.error||"Registration failed"}}catch{return{error:"Network error"}}}async function $C(e){try{const t=await fetch("/api/auth/verify",{headers:{Authorization:`Bearer ${e}`}});return t.ok?(await t.json()).user:null}catch{return null}}function UC({children:e}){const[t,n]=I.useState(null),[r,o]=I.useState(null),[a,l]=I.useState(!0);I.useEffect(()=>{const p=localStorage.getItem(ss),m=localStorage.getItem(qs);if(p&&m)try{$C(p).then(y=>{y?(n(p),o(y)):(localStorage.removeItem(ss),localStorage.removeItem(qs)),l(!1)})}catch{localStorage.removeItem(ss),localStorage.removeItem(qs),l(!1)}else l(!1)},[]);const c=I.useCallback(async(p,m)=>{const y=await VC(p,m);return"token"in y?(localStorage.setItem(ss,y.token),localStorage.setItem(qs,JSON.stringify(y.user)),n(y.token),o(y.user),{success:!0}):{success:!1,error:y.error}},[]),d=I.useCallback(async(p,m,y,v)=>{const b=await BC(p,m,y,v);return"token"in b?(localStorage.setItem(ss,b.token),localStorage.setItem(qs,JSON.stringify(b.user)),n(b.token),o(b.user),{success:!0}):{success:!1,error:b.error}},[]),f=I.useCallback(()=>{localStorage.removeItem(ss),localStorage.removeItem(qs),n(null),o(null)},[]);return w.jsx(Gx.Provider,{value:{isAuthenticated:!!t,isLoading:a,token:t,user:r,login:c,register:d,logout:f},children:e})}function nc(){const e=I.useContext(Gx);if(!e)throw new Error("useAuth must be used within AuthProvider");return e}function HC(){return localStorage.getItem(ss)}function WC(){const[e,t]=I.useState(""),[n,r]=I.useState(""),[o,a]=I.useState(""),[l,c]=I.useState(!1),{login:d,isAuthenticated:f}=nc(),p=Zu();I.useEffect(()=>{f&&p("/studio",{replace:!0})},[f,p]);const m=async y=>{y.preventDefault(),a(""),c(!0);const v=await d(e,n);v.success?p("/studio",{replace:!0}):(a(v.error||"Login failed"),c(!1))};return w.jsx("div",{className:"min-h-screen bg-background flex items-center justify-center p-4",children:w.jsxs("div",{className:"w-full max-w-md",children:[w.jsxs("div",{className:"text-center mb-8",children:[w.jsx("h1",{className:"text-4xl font-bold text-foreground mb-2",children:"Portagent"}),w.jsx("p",{className:"text-muted-foreground",children:"AgentX Portal"})]}),w.jsxs("div",{className:"bg-card rounded-lg p-8 shadow-xl border border-border",children:[w.jsxs("form",{onSubmit:m,className:"space-y-6",children:[w.jsxs("div",{children:[w.jsx("label",{htmlFor:"usernameOrEmail",className:"block text-sm font-medium text-foreground mb-2",children:"Username or Email"}),w.jsx("input",{id:"usernameOrEmail",type:"text",value:e,onChange:y=>t(y.target.value),placeholder:"Enter your username or email",className:"w-full px-4 py-3 bg-muted border border-input rounded-lg text-foreground placeholder-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:border-transparent",autoFocus:!0,required:!0})]}),w.jsxs("div",{children:[w.jsx("label",{htmlFor:"password",className:"block text-sm font-medium text-foreground mb-2",children:"Password"}),w.jsx("input",{id:"password",type:"password",value:n,onChange:y=>r(y.target.value),placeholder:"Enter your password",className:"w-full px-4 py-3 bg-muted border border-input rounded-lg text-foreground placeholder-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:border-transparent",required:!0})]}),o&&w.jsx("div",{className:"text-destructive text-sm text-center",children:o}),w.jsx("button",{type:"submit",disabled:l||!e||!n,className:"w-full py-3 px-4 bg-primary hover:bg-primary/90 disabled:bg-muted disabled:text-muted-foreground disabled:cursor-not-allowed text-primary-foreground font-medium rounded-lg transition-colors",children:l?"Signing in...":"Sign In"})]}),w.jsx("div",{className:"mt-6 text-center text-sm text-muted-foreground",children:w.jsxs("p",{children:["Don't have an account?"," ",w.jsx(tc,{to:"/register",className:"text-primary hover:underline",children:"Sign up"})]})})]})]})})}function qC(){const[e,t]=I.useState(""),[n,r]=I.useState(""),[o,a]=I.useState(""),[l,c]=I.useState(""),[d,f]=I.useState(""),[p,m]=I.useState(""),[y,v]=I.useState(!1),{register:b,isAuthenticated:S}=nc(),C=Zu();I.useEffect(()=>{S&&C("/studio",{replace:!0})},[S,C]);const E=async P=>{if(P.preventDefault(),m(""),o!==l){m("Passwords do not match");return}if(o.length<6){m("Password must be at least 6 characters");return}if(e.length<3){m("Username must be at least 3 characters");return}if(!n.includes("@")){m("Invalid email address");return}v(!0);const T=await b(e,n,o,d||void 0);T.success?C("/studio",{replace:!0}):(m(T.error||"Registration failed"),v(!1))};return w.jsx("div",{className:"min-h-screen bg-background flex items-center justify-center p-4",children:w.jsxs("div",{className:"w-full max-w-md",children:[w.jsxs("div",{className:"text-center mb-8",children:[w.jsx("h1",{className:"text-4xl font-bold text-foreground mb-2",children:"Portagent"}),w.jsx("p",{className:"text-muted-foreground",children:"Create your account"})]}),w.jsxs("div",{className:"bg-card rounded-lg p-8 shadow-xl border border-border",children:[w.jsxs("form",{onSubmit:E,className:"space-y-4",children:[w.jsxs("div",{children:[w.jsx("label",{htmlFor:"username",className:"block text-sm font-medium text-foreground mb-2",children:"Username *"}),w.jsx("input",{id:"username",type:"text",value:e,onChange:P=>t(P.target.value),placeholder:"Choose a username",className:"w-full px-4 py-3 bg-muted border border-input rounded-lg text-foreground placeholder-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:border-transparent",autoFocus:!0,required:!0,minLength:3})]}),w.jsxs("div",{children:[w.jsx("label",{htmlFor:"email",className:"block text-sm font-medium text-foreground mb-2",children:"Email *"}),w.jsx("input",{id:"email",type:"email",value:n,onChange:P=>r(P.target.value),placeholder:"your@email.com",className:"w-full px-4 py-3 bg-muted border border-input rounded-lg text-foreground placeholder-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:border-transparent",required:!0})]}),w.jsxs("div",{children:[w.jsx("label",{htmlFor:"displayName",className:"block text-sm font-medium text-foreground mb-2",children:"Display Name (optional)"}),w.jsx("input",{id:"displayName",type:"text",value:d,onChange:P=>f(P.target.value),placeholder:"How you want to be called",className:"w-full px-4 py-3 bg-muted border border-input rounded-lg text-foreground placeholder-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:border-transparent"})]}),w.jsxs("div",{children:[w.jsx("label",{htmlFor:"password",className:"block text-sm font-medium text-foreground mb-2",children:"Password *"}),w.jsx("input",{id:"password",type:"password",value:o,onChange:P=>a(P.target.value),placeholder:"At least 6 characters",className:"w-full px-4 py-3 bg-muted border border-input rounded-lg text-foreground placeholder-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:border-transparent",required:!0,minLength:6})]}),w.jsxs("div",{children:[w.jsx("label",{htmlFor:"confirmPassword",className:"block text-sm font-medium text-foreground mb-2",children:"Confirm Password *"}),w.jsx("input",{id:"confirmPassword",type:"password",value:l,onChange:P=>c(P.target.value),placeholder:"Re-enter your password",className:"w-full px-4 py-3 bg-muted border border-input rounded-lg text-foreground placeholder-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:border-transparent",required:!0,minLength:6})]}),p&&w.jsx("div",{className:"text-destructive text-sm text-center",children:p}),w.jsx("button",{type:"submit",disabled:y||!e||!n||!o||!l,className:"w-full py-3 px-4 bg-primary hover:bg-primary/90 disabled:bg-muted disabled:text-muted-foreground disabled:cursor-not-allowed text-primary-foreground font-medium rounded-lg transition-colors",children:y?"Creating account...":"Sign Up"})]}),w.jsx("div",{className:"mt-6 text-center text-sm text-muted-foreground",children:w.jsxs("p",{children:["Already have an account?"," ",w.jsx(tc,{to:"/login",className:"text-primary hover:underline",children:"Sign in"})]})})]})]})})}var cn=(e=>(e[e.DEBUG=0]="DEBUG",e[e.INFO=1]="INFO",e[e.WARN=2]="WARN",e[e.ERROR=3]="ERROR",e[e.SILENT=4]="SILENT",e))(cn||{}),GC=["agent_initializing","agent_ready","agent_destroyed","conversation_queued","conversation_start","conversation_thinking","conversation_responding","conversation_end","conversation_interrupted","tool_planned","tool_executing","tool_completed","tool_failed","error_occurred"],KC=new Set(GC),YC=["user_message","assistant_message","tool_call_message","tool_result_message"];new Set(YC);var XC=["error"];new Set(XC);var QC=["turn_request","turn_response"];new Set(QC);var Kx=["message_start","message_delta","message_stop","text_content_block_start","text_delta","text_content_block_stop","tool_use_content_block_start","input_json_delta","tool_use_content_block_stop","tool_call","tool_result","interrupted"];new Set(Kx);function JC(e){return"type"in e&&KC.has(e.type)}class qf extends Error{constructor(n,r,o){const a=n.status||n.status===0?n.status:"",l=n.statusText??"",c=`${a} ${l}`.trim(),d=c?`status code ${c}`:"an unknown error";super(`Request failed with ${d}: ${r.method} ${r.url}`);wn(this,"response");wn(this,"request");wn(this,"options");this.name="HTTPError",this.response=n,this.request=r,this.options=o}}class Yx extends Error{constructor(n){let r="Non-error value was thrown";try{typeof n=="string"?r=n:n&&typeof n=="object"&&"message"in n&&typeof n.message=="string"&&(r=n.message)}catch{}super(r);wn(this,"name","NonError");wn(this,"value");this.value=n}}class Jd extends Error{constructor(n){const r=n!=null&&n.cause?n.cause instanceof Error?n.cause:new Yx(n.cause):void 0;super(n!=null&&n.code?`Forced retry: ${n.code}`:"Forced retry",r?{cause:r}:void 0);wn(this,"name","ForceRetryError");wn(this,"customDelay");wn(this,"code");wn(this,"customRequest");this.customDelay=n==null?void 0:n.delay,this.code=n==null?void 0:n.code,this.customRequest=n==null?void 0:n.request}}const Oy=(()=>{let e=!1,t=!1;const n=typeof globalThis.ReadableStream=="function",r=typeof globalThis.Request=="function";if(n&&r)try{t=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type")}catch(o){if(o instanceof Error&&o.message==="unsupported BodyInit type")return!1;throw o}return e&&!t})(),ZC=typeof globalThis.AbortController=="function",Xx=typeof globalThis.AbortSignal=="function"&&typeof globalThis.AbortSignal.any=="function",eI=typeof globalThis.ReadableStream=="function",tI=typeof globalThis.FormData=="function",Qx=["get","post","put","patch","head","delete"],nI={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*",bytes:"*/*"},Zd=2147483647,rI=new TextEncoder().encode("------WebKitFormBoundaryaxpyiPgbbPti10Rw").length,Jx=Symbol("stop");class Zx{constructor(t){wn(this,"options");this.options=t}}const iI=e=>new Zx(e),sI={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,onUploadProgress:!0,fetch:!0,context:!0},oI={next:!0},aI={method:!0,headers:!0,body:!0,mode:!0,credentials:!0,cache:!0,redirect:!0,referrer:!0,referrerPolicy:!0,integrity:!0,keepalive:!0,signal:!0,window:!0,duplex:!0},lI=e=>{if(!e)return 0;if(e instanceof FormData){let t=0;for(const[n,r]of e)t+=rI,t+=new TextEncoder().encode(`Content-Disposition: form-data; name="${n}"`).length,t+=typeof r=="string"?new TextEncoder().encode(r).length:r.size;return t}if(e instanceof Blob)return e.size;if(e instanceof ArrayBuffer)return e.byteLength;if(typeof e=="string")return new TextEncoder().encode(e).length;if(e instanceof URLSearchParams)return new TextEncoder().encode(e.toString()).length;if("byteLength"in e)return e.byteLength;if(typeof e=="object"&&e!==null)try{const t=JSON.stringify(e);return new TextEncoder().encode(t).length}catch{return 0}return 0},ew=(e,t,n)=>{let r,o=0;return e.pipeThrough(new TransformStream({transform(a,l){if(l.enqueue(a),r){o+=r.byteLength;let c=t===0?0:o/t;c>=1&&(c=1-Number.EPSILON),n==null||n({percent:c,totalBytes:Math.max(t,o),transferredBytes:o},r)}r=a},flush(){r&&(o+=r.byteLength,n==null||n({percent:1,totalBytes:Math.max(t,o),transferredBytes:o},r))}}))},uI=(e,t)=>{if(!e.body)return e;if(e.status===204)return new Response(null,{status:e.status,statusText:e.statusText,headers:e.headers});const n=Math.max(0,Number(e.headers.get("content-length"))||0);return new Response(ew(e.body,n,t),{status:e.status,statusText:e.statusText,headers:e.headers})},cI=(e,t,n)=>{if(!e.body)return e;const r=lI(n??e.body);return new Request(e,{duplex:"half",body:ew(e.body,r,t)})},as=e=>e!==null&&typeof e=="object",uu=(...e)=>{for(const t of e)if((!as(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return Xh({},...e)},tw=(e={},t={})=>{const n=new globalThis.Headers(e),r=t instanceof globalThis.Headers,o=new globalThis.Headers(t);for(const[a,l]of o.entries())r&&l==="undefined"||l===void 0?n.delete(a):n.set(a,l);return n};function cu(e,t,n){return Object.hasOwn(t,n)&&t[n]===void 0?[]:Xh(e[n]??[],t[n]??[])}const nw=(e={},t={})=>({beforeRequest:cu(e,t,"beforeRequest"),beforeRetry:cu(e,t,"beforeRetry"),afterResponse:cu(e,t,"afterResponse"),beforeError:cu(e,t,"beforeError")}),dI=(e,t)=>{const n=new URLSearchParams;for(const r of[e,t])if(r!==void 0)if(r instanceof URLSearchParams)for(const[o,a]of r.entries())n.append(o,a);else if(Array.isArray(r))for(const o of r){if(!Array.isArray(o)||o.length!==2)throw new TypeError("Array search parameters must be provided in [[key, value], ...] format");n.append(String(o[0]),String(o[1]))}else if(as(r))for(const[o,a]of Object.entries(r))a!==void 0&&n.append(o,String(a));else{const o=new URLSearchParams(r);for(const[a,l]of o.entries())n.append(a,l)}return n},Xh=(...e)=>{let t={},n={},r={},o;const a=[];for(const l of e)if(Array.isArray(l))Array.isArray(t)||(t=[]),t=[...t,...l];else if(as(l)){for(let[c,d]of Object.entries(l)){if(c==="signal"&&d instanceof globalThis.AbortSignal){a.push(d);continue}if(c==="context"){if(d!=null&&(!as(d)||Array.isArray(d)))throw new TypeError("The `context` option must be an object");t={...t,context:d==null?{}:{...t.context,...d}};continue}if(c==="searchParams"){d==null?o=void 0:o=o===void 0?d:dI(o,d);continue}as(d)&&c in t&&(d=Xh(t[c],d)),t={...t,[c]:d}}as(l.hooks)&&(r=nw(r,l.hooks),t.hooks=r),as(l.headers)&&(n=tw(n,l.headers),t.headers=n)}return o!==void 0&&(t.searchParams=o),a.length>0&&(a.length===1?t.signal=a[0]:Xx?t.signal=AbortSignal.any(a):t.signal=a.at(-1)),t.context===void 0&&(t.context={}),t},fI=e=>Qx.includes(e)?e.toUpperCase():e,hI=["get","put","head","delete","options","trace"],pI=[408,413,429,500,502,503,504],mI=[413,429,503],Fy={limit:2,methods:hI,statusCodes:pI,afterStatusCodes:mI,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3,jitter:void 0,retryOnTimeout:!1},gI=(e={})=>{if(typeof e=="number")return{...Fy,limit:e};if(e.methods&&!Array.isArray(e.methods))throw new Error("retry.methods must be an array");if(e.statusCodes&&!Array.isArray(e.statusCodes))throw new Error("retry.statusCodes must be an array");return{...Fy,...e}};class Gf extends Error{constructor(n){super(`Request timed out: ${n.method} ${n.url}`);wn(this,"request");this.name="TimeoutError",this.request=n}}async function yI(e,t,n,r){return new Promise((o,a)=>{const l=setTimeout(()=>{n&&n.abort(),a(new Gf(e))},r.timeout);r.fetch(e,t).then(o).catch(a).then(()=>{clearTimeout(l)})})}async function vI(e,{signal:t}){return new Promise((n,r)=>{t&&(t.throwIfAborted(),t.addEventListener("abort",o,{once:!0}));function o(){clearTimeout(a),r(t.reason)}const a=setTimeout(()=>{t==null||t.removeEventListener("abort",o),n()},e)})}const xI=(e,t)=>{const n={};for(const r in t)Object.hasOwn(t,r)&&!(r in aI)&&!(r in sI)&&(!(r in e)||r in oI)&&(n[r]=t[r]);return n},wI=e=>e===void 0?!1:Array.isArray(e)?e.length>0:e instanceof URLSearchParams?e.size>0:typeof e=="object"?Object.keys(e).length>0:typeof e=="string"?e.trim().length>0:!!e;function bI(e){return e instanceof qf||(e==null?void 0:e.name)===qf.name}function SI(e){return e instanceof Gf||(e==null?void 0:e.name)===Gf.name}var Qu,rw,ur,$n,Ut,ge,Ti,Sr,fs,Xe,Pu,iw,Kf,Yf,sw,wa,Au,Xf;const Na=class Na{constructor(t,n={}){xr(this,Xe);wn(this,"request");xr(this,ur);xr(this,$n,0);xr(this,Ut);xr(this,ge);xr(this,Ti);xr(this,Sr);xr(this,fs);var o,a,l;if(ir(this,Ut,t),ir(this,ge,{...n,headers:tw(J(this,Ut).headers,n.headers),hooks:nw({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},n.hooks),method:fI(n.method??J(this,Ut).method??"GET"),prefixUrl:String(n.prefixUrl||""),retry:gI(n.retry),throwHttpErrors:n.throwHttpErrors??!0,timeout:n.timeout??1e4,fetch:n.fetch??globalThis.fetch.bind(globalThis),context:n.context??{}}),typeof J(this,Ut)!="string"&&!(J(this,Ut)instanceof URL||J(this,Ut)instanceof globalThis.Request))throw new TypeError("`input` must be a string, URL, or Request");if(J(this,ge).prefixUrl&&typeof J(this,Ut)=="string"){if(J(this,Ut).startsWith("/"))throw new Error("`input` must not begin with a slash when using `prefixUrl`");J(this,ge).prefixUrl.endsWith("/")||(J(this,ge).prefixUrl+="/"),ir(this,Ut,J(this,ge).prefixUrl+J(this,Ut))}ZC&&Xx&&(ir(this,Sr,J(this,ge).signal??J(this,Ut).signal),ir(this,ur,new globalThis.AbortController),J(this,ge).signal=J(this,Sr)?AbortSignal.any([J(this,Sr),J(this,ur).signal]):J(this,ur).signal),Oy&&(J(this,ge).duplex="half"),J(this,ge).json!==void 0&&(J(this,ge).body=((a=(o=J(this,ge)).stringifyJson)==null?void 0:a.call(o,J(this,ge).json))??JSON.stringify(J(this,ge).json),J(this,ge).headers.set("content-type",J(this,ge).headers.get("content-type")??"application/json"));const r=n.headers&&new globalThis.Headers(n.headers).has("content-type");if(J(this,Ut)instanceof globalThis.Request&&(tI&&J(this,ge).body instanceof globalThis.FormData||J(this,ge).body instanceof URLSearchParams)&&!r&&J(this,ge).headers.delete("content-type"),this.request=new globalThis.Request(J(this,Ut),J(this,ge)),wI(J(this,ge).searchParams)){const d="?"+(typeof J(this,ge).searchParams=="string"?J(this,ge).searchParams.replace(/^\?/,""):new URLSearchParams(vt(l=Na,Qu,rw).call(l,J(this,ge).searchParams)).toString()),f=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,d);this.request=new globalThis.Request(f,J(this,ge))}if(J(this,ge).onUploadProgress){if(typeof J(this,ge).onUploadProgress!="function")throw new TypeError("The `onUploadProgress` option must be a function");if(!Oy)throw new Error("Request streams are not supported in your environment. The `duplex` option for `Request` is not available.");this.request=vt(this,Xe,Xf).call(this,this.request,J(this,ge).body??void 0)}}static create(t,n){var l,c,d;const r=new Na(t,n),o=async()=>{var p,m,y,v,b,S,C;if(typeof J(r,ge).timeout=="number"&&J(r,ge).timeout>Zd)throw new RangeError(`The \`timeout\` option cannot be greater than ${Zd}`);await Promise.resolve();let f=await vt(p=r,Xe,sw).call(p);for(const E of J(r,ge).hooks.afterResponse){const P=vt(m=r,Xe,Kf).call(m,f.clone()),T=await E(r.request,vt(y=r,Xe,wa).call(y),P,{retryCount:J(r,$n)});if(T instanceof globalThis.Response&&(f=T),T instanceof Zx)throw await Promise.all([(v=P.body)==null?void 0:v.cancel(),(b=f.body)==null?void 0:b.cancel()]),new Jd(T.options)}if(vt(S=r,Xe,Kf).call(S,f),!f.ok&&(typeof J(r,ge).throwHttpErrors=="function"?J(r,ge).throwHttpErrors(f.status):J(r,ge).throwHttpErrors)){let E=new qf(f,r.request,vt(C=r,Xe,wa).call(C));for(const P of J(r,ge).hooks.beforeError)E=await P(E,{retryCount:J(r,$n)});throw E}if(J(r,ge).onDownloadProgress){if(typeof J(r,ge).onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!eI)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return uI(f.clone(),J(r,ge).onDownloadProgress)}return f},a=vt(l=r,Xe,Yf).call(l,o).finally(async()=>{var m,y;const f=J(r,Ti),p=[];f&&!f.bodyUsed&&p.push((m=f.body)==null?void 0:m.cancel()),r.request.bodyUsed||p.push((y=r.request.body)==null?void 0:y.cancel()),await Promise.all(p)});for(const[f,p]of Object.entries(nI))f==="bytes"&&typeof((d=(c=globalThis.Response)==null?void 0:c.prototype)==null?void 0:d.bytes)!="function"||(a[f]=async()=>{r.request.headers.set("accept",r.request.headers.get("accept")||p);const m=await a;if(f==="json"){if(m.status===204)return"";const y=await m.text();return y===""?"":n.parseJson?n.parseJson(y):JSON.parse(y)}return m[f]()});return a}};Qu=new WeakSet,rw=function(t){return t&&typeof t=="object"&&!Array.isArray(t)&&!(t instanceof URLSearchParams)?Object.fromEntries(Object.entries(t).filter(([,n])=>n!==void 0)):t},ur=new WeakMap,$n=new WeakMap,Ut=new WeakMap,ge=new WeakMap,Ti=new WeakMap,Sr=new WeakMap,fs=new WeakMap,Xe=new WeakSet,Pu=function(){const t=J(this,ge).retry.delay(J(this,$n));let n=t;return J(this,ge).retry.jitter===!0?n=Math.random()*t:typeof J(this,ge).retry.jitter=="function"&&(n=J(this,ge).retry.jitter(t),(!Number.isFinite(n)||n<0)&&(n=t)),Math.min(J(this,ge).retry.backoffLimit,n)},iw=async function(t){if(Sy(this,$n)._++,J(this,$n)>J(this,ge).retry.limit)throw t;const n=t instanceof Error?t:new Yx(t);if(n instanceof Jd)return n.customDelay??vt(this,Xe,Pu).call(this);if(!J(this,ge).retry.methods.includes(this.request.method.toLowerCase()))throw t;if(J(this,ge).retry.shouldRetry!==void 0){const r=await J(this,ge).retry.shouldRetry({error:n,retryCount:J(this,$n)});if(r===!1)throw t;if(r===!0)return vt(this,Xe,Pu).call(this)}if(SI(t)&&!J(this,ge).retry.retryOnTimeout)throw t;if(bI(t)){if(!J(this,ge).retry.statusCodes.includes(t.response.status))throw t;const r=t.response.headers.get("Retry-After")??t.response.headers.get("RateLimit-Reset")??t.response.headers.get("X-RateLimit-Retry-After")??t.response.headers.get("X-RateLimit-Reset")??t.response.headers.get("X-Rate-Limit-Reset");if(r&&J(this,ge).retry.afterStatusCodes.includes(t.response.status)){let o=Number(r)*1e3;Number.isNaN(o)?o=Date.parse(r)-Date.now():o>=Date.parse("2024-01-01")&&(o-=Date.now());const a=J(this,ge).retry.maxRetryAfter??o;return o<a?o:a}if(t.response.status===413)throw t}return vt(this,Xe,Pu).call(this)},Kf=function(t){return J(this,ge).parseJson&&(t.json=async()=>J(this,ge).parseJson(await t.text())),t},Yf=async function(t){try{return await t()}catch(n){const r=Math.min(await vt(this,Xe,iw).call(this,n),Zd);if(J(this,$n)<1)throw n;if(await vI(r,J(this,Sr)?{signal:J(this,Sr)}:{}),n instanceof Jd&&n.customRequest){const o=J(this,ge).signal?new globalThis.Request(n.customRequest,{signal:J(this,ge).signal}):new globalThis.Request(n.customRequest);vt(this,Xe,Au).call(this,o)}for(const o of J(this,ge).hooks.beforeRetry){const a=await o({request:this.request,options:vt(this,Xe,wa).call(this),error:n,retryCount:J(this,$n)});if(a instanceof globalThis.Request){vt(this,Xe,Au).call(this,a);break}if(a instanceof globalThis.Response)return a;if(a===Jx)return}return vt(this,Xe,Yf).call(this,t)}},sw=async function(){var n;(n=J(this,ur))!=null&&n.signal.aborted&&(ir(this,ur,new globalThis.AbortController),J(this,ge).signal=J(this,Sr)?AbortSignal.any([J(this,Sr),J(this,ur).signal]):J(this,ur).signal,this.request=new globalThis.Request(this.request,{signal:J(this,ge).signal}));for(const r of J(this,ge).hooks.beforeRequest){const o=await r(this.request,vt(this,Xe,wa).call(this),{retryCount:J(this,$n)});if(o instanceof Response)return o;if(o instanceof globalThis.Request){vt(this,Xe,Au).call(this,o);break}}const t=xI(this.request,J(this,ge));return ir(this,Ti,this.request),this.request=J(this,Ti).clone(),J(this,ge).timeout===!1?J(this,ge).fetch(J(this,Ti),t):yI(J(this,Ti),t,J(this,ur),J(this,ge))},wa=function(){if(!J(this,fs)){const{hooks:t,...n}=J(this,ge);ir(this,fs,Object.freeze(n))}return J(this,fs)},Au=function(t){ir(this,fs,void 0),this.request=vt(this,Xe,Xf).call(this,t)},Xf=function(t,n){return!J(this,ge).onUploadProgress||!t.body?t:cI(t,J(this,ge).onUploadProgress,n??J(this,ge).body??void 0)},xr(Na,Qu);let Ou=Na;/*! MIT License © Sindre Sorhus */const Qf=e=>{const t=(n,r)=>Ou.create(n,uu(e,r));for(const n of Qx)t[n]=(r,o)=>Ou.create(r,uu(e,o,{method:n}));return t.create=n=>Qf(uu(n)),t.extend=n=>(typeof n=="function"&&(n=n(e??{})),Qf(uu(e,n))),t.stop=Jx,t.retry=iI,t},kI=Qf();var Jf=function(e,t){return Jf=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,r){n.__proto__=r}||function(n,r){for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(n[o]=r[o])},Jf(e,t)};function qa(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");Jf(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}function Zf(e){var t=typeof Symbol=="function"&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function eh(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),o,a=[],l;try{for(;(t===void 0||t-- >0)&&!(o=r.next()).done;)a.push(o.value)}catch(c){l={error:c}}finally{try{o&&!o.done&&(n=r.return)&&n.call(r)}finally{if(l)throw l.error}}return a}function th(e,t,n){if(n||arguments.length===2)for(var r=0,o=t.length,a;r<o;r++)(a||!(r in t))&&(a||(a=Array.prototype.slice.call(t,0,r)),a[r]=t[r]);return e.concat(a||Array.prototype.slice.call(t))}function kr(e){return typeof e=="function"}function ow(e){var t=function(r){Error.call(r),r.stack=new Error().stack},n=e(t);return n.prototype=Object.create(Error.prototype),n.prototype.constructor=n,n}var ef=ow(function(e){return function(n){e(this),this.message=n?n.length+` errors occurred during unsubscription:
51
+ Please change the parent <Route path="${T}"> to <Route path="${T==="/"?"*":`${T}/*`}">.`)}let y=Ri(),v;if(t){let T=typeof t=="string"?po(t):t;at(p==="/"||((P=T.pathname)==null?void 0:P.startsWith(p)),`When overriding the location using \`<Routes location>\` or \`useRoutes(routes, location)\`, the location pathname must begin with the portion of the URL pathname that was matched by all parent routes. The current pathname base is "${p}" but pathname "${T.pathname}" was given in the \`location\` prop.`),v=T}else v=y;let b=v.pathname||"/",S=b;if(p!=="/"){let T=p.replace(/^\//,"").split("/");S="/"+b.replace(/^\//,"").split("/").slice(T.length).join("/")}let C=jx(e,{pathname:S});Gn(m||C!=null,`No routes matched location "${v.pathname}${v.search}${v.hash}" `),Gn(C==null||C[C.length-1].route.element!==void 0||C[C.length-1].route.Component!==void 0||C[C.length-1].route.lazy!==void 0,`Matched leaf route at location "${v.pathname}${v.search}${v.hash}" does not have an element or Component. This means it will render an <Outlet /> with a null value by default resulting in an "empty" page.`);let E=QE(C&&C.map(T=>Object.assign({},T,{params:Object.assign({},d,T.params),pathname:Hr([p,a.encodeLocation?a.encodeLocation(T.pathname.replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:T.pathname]),pathnameBase:T.pathnameBase==="/"?p:Hr([p,a.encodeLocation?a.encodeLocation(T.pathnameBase.replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:T.pathnameBase])})),l,n,r,o);return t&&E?I.createElement(Ha.Provider,{value:{location:{pathname:"/",search:"",hash:"",state:null,key:"default",...v},navigationType:"POP"}},E):E}function GE(){let e=nC(),t=VE(e)?`${e.status} ${e.statusText}`:e instanceof Error?e.message:JSON.stringify(e),n=e instanceof Error?e.stack:null,r="rgba(200,200,200, 0.5)",o={padding:"0.5rem",backgroundColor:r},a={padding:"2px 4px",backgroundColor:r},l=null;return console.error("Error handled by React Router default ErrorBoundary:",e),l=I.createElement(I.Fragment,null,I.createElement("p",null,"💿 Hey developer 👋"),I.createElement("p",null,"You can provide a way better UX than this when your app throws errors by providing your own ",I.createElement("code",{style:a},"ErrorBoundary")," or"," ",I.createElement("code",{style:a},"errorElement")," prop on your route.")),I.createElement(I.Fragment,null,I.createElement("h2",null,"Unexpected Application Error!"),I.createElement("h3",{style:{fontStyle:"italic"}},t),n?I.createElement("pre",{style:o},n):null,l)}var KE=I.createElement(GE,null),YE=class extends I.Component{constructor(e){super(e),this.state={location:e.location,revalidation:e.revalidation,error:e.error}}static getDerivedStateFromError(e){return{error:e}}static getDerivedStateFromProps(e,t){return t.location!==e.location||t.revalidation!=="idle"&&e.revalidation==="idle"?{error:e.error,location:e.location,revalidation:e.revalidation}:{error:e.error!==void 0?e.error:t.error,location:t.location,revalidation:e.revalidation||t.revalidation}}componentDidCatch(e,t){this.props.onError?this.props.onError(e,t):console.error("React Router caught the following error during render",e)}render(){return this.state.error!==void 0?I.createElement(Ir.Provider,{value:this.props.routeContext},I.createElement(Wh.Provider,{value:this.state.error,children:this.props.component})):this.props.children}};function XE({routeContext:e,match:t,children:n}){let r=I.useContext(mo);return r&&r.static&&r.staticContext&&(t.route.errorElement||t.route.ErrorBoundary)&&(r.staticContext._deepestRenderedBoundaryId=t.route.id),I.createElement(Ir.Provider,{value:e},n)}function QE(e,t=[],n=null,r=null,o=null){if(e==null){if(!n)return null;if(n.errors)e=n.matches;else if(t.length===0&&!n.initialized&&n.matches.length>0)e=n.matches;else return null}let a=e,l=n==null?void 0:n.errors;if(l!=null){let p=a.findIndex(m=>m.route.id&&(l==null?void 0:l[m.route.id])!==void 0);at(p>=0,`Could not find a matching route for errors on route IDs: ${Object.keys(l).join(",")}`),a=a.slice(0,Math.min(a.length,p+1))}let c=!1,d=-1;if(n)for(let p=0;p<a.length;p++){let m=a[p];if((m.route.HydrateFallback||m.route.hydrateFallbackElement)&&(d=p),m.route.id){let{loaderData:y,errors:v}=n,b=m.route.loader&&!y.hasOwnProperty(m.route.id)&&(!v||v[m.route.id]===void 0);if(m.route.lazy||b){c=!0,d>=0?a=a.slice(0,d+1):a=[a[0]];break}}}let f=n&&r?(p,m)=>{var y,v;r(p,{location:n.location,params:((v=(y=n.matches)==null?void 0:y[0])==null?void 0:v.params)??{},errorInfo:m})}:void 0;return a.reduceRight((p,m,y)=>{let v,b=!1,S=null,C=null;n&&(v=l&&m.route.id?l[m.route.id]:void 0,S=m.route.errorElement||KE,c&&(d<0&&y===0?(Bx("route-fallback",!1,"No `HydrateFallback` element provided to render during initial hydration"),b=!0,C=null):d===y&&(b=!0,C=m.route.hydrateFallbackElement||null)));let E=t.concat(a.slice(0,y+1)),P=()=>{let T;return v?T=S:b?T=C:m.route.Component?T=I.createElement(m.route.Component,null):m.route.element?T=m.route.element:T=p,I.createElement(XE,{match:m,routeContext:{outlet:p,matches:E,isDataRoute:n!=null},children:T})};return n&&(m.route.ErrorBoundary||m.route.errorElement||y===0)?I.createElement(YE,{location:n.location,revalidation:n.revalidation,component:S,error:v,children:P(),routeContext:{outlet:null,matches:E,isDataRoute:!0},onError:f}):P()},null)}function qh(e){return`${e} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function JE(e){let t=I.useContext(mo);return at(t,qh(e)),t}function ZE(e){let t=I.useContext(Ju);return at(t,qh(e)),t}function eC(e){let t=I.useContext(Ir);return at(t,qh(e)),t}function Gh(e){let t=eC(e),n=t.matches[t.matches.length-1];return at(n.route.id,`${e} can only be used on routes that contain a unique "id"`),n.route.id}function tC(){return Gh("useRouteId")}function nC(){var r;let e=I.useContext(Wh),t=ZE("useRouteError"),n=Gh("useRouteError");return e!==void 0?e:(r=t.errors)==null?void 0:r[n]}function rC(){let{router:e}=JE("useNavigate"),t=Gh("useNavigate"),n=I.useRef(!1);return Fx(()=>{n.current=!0}),I.useCallback(async(o,a={})=>{Gn(n.current,Ox),n.current&&(typeof o=="number"?e.navigate(o):await e.navigate(o,{fromRouteId:t,...a}))},[e,t])}var Ly={};function Bx(e,t,n){!t&&!Ly[e]&&(Ly[e]=!0,Gn(!1,n))}I.memo(iC);function iC({routes:e,future:t,state:n,unstable_onError:r}){return Vx(e,void 0,n,r,t)}function Hf({to:e,replace:t,state:n,relative:r}){at(go(),"<Navigate> may be used only in the context of a <Router> component.");let{static:o}=I.useContext(dr);Gn(!o,"<Navigate> must not be used on the initial render in a <StaticRouter>. This is a no-op, but you should modify your code so the <Navigate> is only ever rendered in response to some user interaction or state change.");let{matches:a}=I.useContext(Ir),{pathname:l}=Ri(),c=Zu(),d=Hh(e,Uh(a),l,r==="path"),f=JSON.stringify(d);return I.useEffect(()=>{c(JSON.parse(f),{replace:t,state:n,relative:r})},[c,f,r,t,n]),null}function Js(e){at(!1,"A <Route> is only ever to be used as the child of <Routes> element, never rendered directly. Please wrap your <Route> in a <Routes>.")}function sC({basename:e="/",children:t=null,location:n,navigationType:r="POP",navigator:o,static:a=!1}){at(!go(),"You cannot render a <Router> inside another <Router>. You should never have more than one in your app.");let l=e.replace(/^\/*/,"/"),c=I.useMemo(()=>({basename:l,navigator:o,static:a,future:{}}),[l,o,a]);typeof n=="string"&&(n=po(n));let{pathname:d="/",search:f="",hash:p="",state:m=null,key:y="default"}=n,v=I.useMemo(()=>{let b=Wr(d,l);return b==null?null:{location:{pathname:b,search:f,hash:p,state:m,key:y},navigationType:r}},[l,d,f,p,m,y,r]);return Gn(v!=null,`<Router basename="${l}"> is not able to match the URL "${d}${f}${p}" because it does not start with the basename, so the <Router> won't render anything.`),v==null?null:I.createElement(dr.Provider,{value:c},I.createElement(Ha.Provider,{children:t,value:v}))}function oC({children:e,location:t}){return qE(Wf(e),t)}function Wf(e,t=[]){let n=[];return I.Children.forEach(e,(r,o)=>{if(!I.isValidElement(r))return;let a=[...t,o];if(r.type===I.Fragment){n.push.apply(n,Wf(r.props.children,a));return}at(r.type===Js,`[${typeof r.type=="string"?r.type:r.type.name}] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>`),at(!r.props.index||!r.props.children,"An index route cannot have child routes.");let l={id:r.props.id||a.join("-"),caseSensitive:r.props.caseSensitive,element:r.props.element,Component:r.props.Component,index:r.props.index,path:r.props.path,middleware:r.props.middleware,loader:r.props.loader,action:r.props.action,hydrateFallbackElement:r.props.hydrateFallbackElement,HydrateFallback:r.props.HydrateFallback,errorElement:r.props.errorElement,ErrorBoundary:r.props.ErrorBoundary,hasErrorBoundary:r.props.hasErrorBoundary===!0||r.props.ErrorBoundary!=null||r.props.errorElement!=null,shouldRevalidate:r.props.shouldRevalidate,handle:r.props.handle,lazy:r.props.lazy};r.props.children&&(l.children=Wf(r.props.children,a)),n.push(l)}),n}var Tu="get",_u="application/x-www-form-urlencoded";function ec(e){return e!=null&&typeof e.tagName=="string"}function aC(e){return ec(e)&&e.tagName.toLowerCase()==="button"}function lC(e){return ec(e)&&e.tagName.toLowerCase()==="form"}function uC(e){return ec(e)&&e.tagName.toLowerCase()==="input"}function cC(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}function dC(e,t){return e.button===0&&(!t||t==="_self")&&!cC(e)}var lu=null;function fC(){if(lu===null)try{new FormData(document.createElement("form"),0),lu=!1}catch{lu=!0}return lu}var hC=new Set(["application/x-www-form-urlencoded","multipart/form-data","text/plain"]);function Qd(e){return e!=null&&!hC.has(e)?(Gn(!1,`"${e}" is not a valid \`encType\` for \`<Form>\`/\`<fetcher.Form>\` and will default to "${_u}"`),null):e}function pC(e,t){let n,r,o,a,l;if(lC(e)){let c=e.getAttribute("action");r=c?Wr(c,t):null,n=e.getAttribute("method")||Tu,o=Qd(e.getAttribute("enctype"))||_u,a=new FormData(e)}else if(aC(e)||uC(e)&&(e.type==="submit"||e.type==="image")){let c=e.form;if(c==null)throw new Error('Cannot submit a <button> or <input type="submit"> without a <form>');let d=e.getAttribute("formaction")||c.getAttribute("action");if(r=d?Wr(d,t):null,n=e.getAttribute("formmethod")||c.getAttribute("method")||Tu,o=Qd(e.getAttribute("formenctype"))||Qd(c.getAttribute("enctype"))||_u,a=new FormData(c,e),!fC()){let{name:f,type:p,value:m}=e;if(p==="image"){let y=f?`${f}.`:"";a.append(`${y}x`,"0"),a.append(`${y}y`,"0")}else f&&a.append(f,m)}}else{if(ec(e))throw new Error('Cannot submit element that is not <form>, <button>, or <input type="submit|image">');n=Tu,r=null,o=_u,l=e}return a&&o==="text/plain"&&(l=a,a=void 0),{action:r,method:n.toLowerCase(),encType:o,formData:a,body:l}}Object.getOwnPropertyNames(Object.prototype).sort().join("\0");function Kh(e,t){if(e===!1||e===null||typeof e>"u")throw new Error(t)}function mC(e,t,n){let r=typeof e=="string"?new URL(e,typeof window>"u"?"server://singlefetch/":window.location.origin):e;return r.pathname==="/"?r.pathname=`_root.${n}`:t&&Wr(r.pathname,t)==="/"?r.pathname=`${t.replace(/\/$/,"")}/_root.${n}`:r.pathname=`${r.pathname.replace(/\/$/,"")}.${n}`,r}async function gC(e,t){if(e.id in t)return t[e.id];try{let n=await import(e.module);return t[e.id]=n,n}catch(n){return console.error(`Error loading route module \`${e.module}\`, reloading page...`),console.error(n),window.__reactRouterContext&&window.__reactRouterContext.isSpaMode,window.location.reload(),new Promise(()=>{})}}function yC(e){return e==null?!1:e.href==null?e.rel==="preload"&&typeof e.imageSrcSet=="string"&&typeof e.imageSizes=="string":typeof e.rel=="string"&&typeof e.href=="string"}async function vC(e,t,n){let r=await Promise.all(e.map(async o=>{let a=t.routes[o.route.id];if(a){let l=await gC(a,n);return l.links?l.links():[]}return[]}));return SC(r.flat(1).filter(yC).filter(o=>o.rel==="stylesheet"||o.rel==="preload").map(o=>o.rel==="stylesheet"?{...o,rel:"prefetch",as:"style"}:{...o,rel:"prefetch"}))}function zy(e,t,n,r,o,a){let l=(d,f)=>n[f]?d.route.id!==n[f].route.id:!0,c=(d,f)=>{var p;return n[f].pathname!==d.pathname||((p=n[f].route.path)==null?void 0:p.endsWith("*"))&&n[f].params["*"]!==d.params["*"]};return a==="assets"?t.filter((d,f)=>l(d,f)||c(d,f)):a==="data"?t.filter((d,f)=>{var m;let p=r.routes[d.route.id];if(!p||!p.hasLoader)return!1;if(l(d,f)||c(d,f))return!0;if(d.route.shouldRevalidate){let y=d.route.shouldRevalidate({currentUrl:new URL(o.pathname+o.search+o.hash,window.origin),currentParams:((m=n[0])==null?void 0:m.params)||{},nextUrl:new URL(e,window.origin),nextParams:d.params,defaultShouldRevalidate:!0});if(typeof y=="boolean")return y}return!0}):[]}function xC(e,t,{includeHydrateFallback:n}={}){return wC(e.map(r=>{let o=t.routes[r.route.id];if(!o)return[];let a=[o.module];return o.clientActionModule&&(a=a.concat(o.clientActionModule)),o.clientLoaderModule&&(a=a.concat(o.clientLoaderModule)),n&&o.hydrateFallbackModule&&(a=a.concat(o.hydrateFallbackModule)),o.imports&&(a=a.concat(o.imports)),a}).flat(1))}function wC(e){return[...new Set(e)]}function bC(e){let t={},n=Object.keys(e).sort();for(let r of n)t[r]=e[r];return t}function SC(e,t){let n=new Set;return new Set(t),e.reduce((r,o)=>{let a=JSON.stringify(bC(o));return n.has(a)||(n.add(a),r.push({key:a,link:o})),r},[])}function $x(){let e=I.useContext(mo);return Kh(e,"You must render this element inside a <DataRouterContext.Provider> element"),e}function kC(){let e=I.useContext(Ju);return Kh(e,"You must render this element inside a <DataRouterStateContext.Provider> element"),e}var Yh=I.createContext(void 0);Yh.displayName="FrameworkContext";function Ux(){let e=I.useContext(Yh);return Kh(e,"You must render this element inside a <HydratedRouter> element"),e}function EC(e,t){let n=I.useContext(Yh),[r,o]=I.useState(!1),[a,l]=I.useState(!1),{onFocus:c,onBlur:d,onMouseEnter:f,onMouseLeave:p,onTouchStart:m}=t,y=I.useRef(null);I.useEffect(()=>{if(e==="render"&&l(!0),e==="viewport"){let S=E=>{E.forEach(P=>{l(P.isIntersecting)})},C=new IntersectionObserver(S,{threshold:.5});return y.current&&C.observe(y.current),()=>{C.disconnect()}}},[e]),I.useEffect(()=>{if(r){let S=setTimeout(()=>{l(!0)},100);return()=>{clearTimeout(S)}}},[r]);let v=()=>{o(!0)},b=()=>{o(!1),l(!1)};return n?e!=="intent"?[a,y,{}]:[a,y,{onFocus:ua(c,v),onBlur:ua(d,b),onMouseEnter:ua(f,v),onMouseLeave:ua(p,b),onTouchStart:ua(m,v)}]:[!1,y,{}]}function ua(e,t){return n=>{e&&e(n),n.defaultPrevented||t(n)}}function CC({page:e,...t}){let{router:n}=$x(),r=I.useMemo(()=>jx(n.routes,e,n.basename),[n.routes,e,n.basename]);return r?I.createElement(TC,{page:e,matches:r,...t}):null}function IC(e){let{manifest:t,routeModules:n}=Ux(),[r,o]=I.useState([]);return I.useEffect(()=>{let a=!1;return vC(e,t,n).then(l=>{a||o(l)}),()=>{a=!0}},[e,t,n]),r}function TC({page:e,matches:t,...n}){let r=Ri(),{manifest:o,routeModules:a}=Ux(),{basename:l}=$x(),{loaderData:c,matches:d}=kC(),f=I.useMemo(()=>zy(e,t,d,o,r,"data"),[e,t,d,o,r]),p=I.useMemo(()=>zy(e,t,d,o,r,"assets"),[e,t,d,o,r]),m=I.useMemo(()=>{if(e===r.pathname+r.search+r.hash)return[];let b=new Set,S=!1;if(t.forEach(E=>{var T;let P=o.routes[E.route.id];!P||!P.hasLoader||(!f.some(O=>O.route.id===E.route.id)&&E.route.id in c&&((T=a[E.route.id])!=null&&T.shouldRevalidate)||P.hasClientLoader?S=!0:b.add(E.route.id))}),b.size===0)return[];let C=mC(e,l,"data");return S&&b.size>0&&C.searchParams.set("_routes",t.filter(E=>b.has(E.route.id)).map(E=>E.route.id).join(",")),[C.pathname+C.search]},[l,c,r,o,f,t,e,a]),y=I.useMemo(()=>xC(p,o),[p,o]),v=IC(p);return I.createElement(I.Fragment,null,m.map(b=>I.createElement("link",{key:b,rel:"prefetch",as:"fetch",href:b,...n})),y.map(b=>I.createElement("link",{key:b,rel:"modulepreload",href:b,...n})),v.map(({key:b,link:S})=>I.createElement("link",{key:b,nonce:n.nonce,...S})))}function _C(...e){return t=>{e.forEach(n=>{typeof n=="function"?n(t):n!=null&&(n.current=t)})}}var Hx=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";try{Hx&&(window.__reactRouterVersion="7.9.6")}catch{}function PC({basename:e,children:t,window:n}){let r=I.useRef();r.current==null&&(r.current=gE({window:n,v5Compat:!0}));let o=r.current,[a,l]=I.useState({action:o.action,location:o.location}),c=I.useCallback(d=>{I.startTransition(()=>l(d))},[l]);return I.useLayoutEffect(()=>o.listen(c),[o,c]),I.createElement(sC,{basename:e,children:t,location:a.location,navigationType:a.action,navigator:o})}var Wx=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,tc=I.forwardRef(function({onClick:t,discover:n="render",prefetch:r="none",relative:o,reloadDocument:a,replace:l,state:c,target:d,to:f,preventScrollReset:p,viewTransition:m,...y},v){let{basename:b}=I.useContext(dr),S=typeof f=="string"&&Wx.test(f),C,E=!1;if(typeof f=="string"&&S&&(C=f,Hx))try{let ee=new URL(window.location.href),L=f.startsWith("//")?new URL(ee.protocol+f):new URL(f),te=Wr(L.pathname,b);L.origin===ee.origin&&te!=null?f=te+L.search+L.hash:E=!0}catch{Gn(!1,`<Link to="${f}"> contains an invalid URL which will probably break when clicked - please update to a valid URL path.`)}let P=HE(f,{relative:o}),[T,O,V]=EC(r,y),N=jC(f,{replace:l,state:c,target:d,preventScrollReset:p,relative:o,viewTransition:m});function D(ee){t&&t(ee),ee.defaultPrevented||N(ee)}let H=I.createElement("a",{...y,...V,href:C||P,onClick:E||a?t:D,ref:_C(v,O),target:d,"data-discover":!S&&n==="render"?"true":void 0});return T&&!S?I.createElement(I.Fragment,null,H,I.createElement(CC,{page:P})):H});tc.displayName="Link";var AC=I.forwardRef(function({"aria-current":t="page",caseSensitive:n=!1,className:r="",end:o=!1,style:a,to:l,viewTransition:c,children:d,...f},p){let m=Wa(l,{relative:f.relative}),y=Ri(),v=I.useContext(Ju),{navigator:b,basename:S}=I.useContext(dr),C=v!=null&&OC(m)&&c===!0,E=b.encodeLocation?b.encodeLocation(m).pathname:m.pathname,P=y.pathname,T=v&&v.navigation&&v.navigation.location?v.navigation.location.pathname:null;n||(P=P.toLowerCase(),T=T?T.toLowerCase():null,E=E.toLowerCase()),T&&S&&(T=Wr(T,S)||T);const O=E!=="/"&&E.endsWith("/")?E.length-1:E.length;let V=P===E||!o&&P.startsWith(E)&&P.charAt(O)==="/",N=T!=null&&(T===E||!o&&T.startsWith(E)&&T.charAt(E.length)==="/"),D={isActive:V,isPending:N,isTransitioning:C},H=V?t:void 0,ee;typeof r=="function"?ee=r(D):ee=[r,V?"active":null,N?"pending":null,C?"transitioning":null].filter(Boolean).join(" ");let L=typeof a=="function"?a(D):a;return I.createElement(tc,{...f,"aria-current":H,className:ee,ref:p,style:L,to:l,viewTransition:c},typeof d=="function"?d(D):d)});AC.displayName="NavLink";var RC=I.forwardRef(({discover:e="render",fetcherKey:t,navigate:n,reloadDocument:r,replace:o,state:a,method:l=Tu,action:c,onSubmit:d,relative:f,preventScrollReset:p,viewTransition:m,...y},v)=>{let b=LC(),S=zC(c,{relative:f}),C=l.toLowerCase()==="get"?"get":"post",E=typeof c=="string"&&Wx.test(c),P=T=>{if(d&&d(T),T.defaultPrevented)return;T.preventDefault();let O=T.nativeEvent.submitter,V=(O==null?void 0:O.getAttribute("formmethod"))||l;b(O||T.currentTarget,{fetcherKey:t,method:V,navigate:n,replace:o,state:a,relative:f,preventScrollReset:p,viewTransition:m})};return I.createElement("form",{ref:v,method:C,action:S,onSubmit:r?d:P,...y,"data-discover":!E&&e==="render"?"true":void 0})});RC.displayName="Form";function NC(e){return`${e} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function qx(e){let t=I.useContext(mo);return at(t,NC(e)),t}function jC(e,{target:t,replace:n,state:r,preventScrollReset:o,relative:a,viewTransition:l}={}){let c=Zu(),d=Ri(),f=Wa(e,{relative:a});return I.useCallback(p=>{if(dC(p,t)){p.preventDefault();let m=n!==void 0?n:ja(d)===ja(f);c(e,{replace:m,state:r,preventScrollReset:o,relative:a,viewTransition:l})}},[d,c,f,n,r,t,e,o,a,l])}var MC=0,DC=()=>`__${String(++MC)}__`;function LC(){let{router:e}=qx("useSubmit"),{basename:t}=I.useContext(dr),n=tC();return I.useCallback(async(r,o={})=>{let{action:a,method:l,encType:c,formData:d,body:f}=pC(r,t);if(o.navigate===!1){let p=o.fetcherKey||DC();await e.fetch(p,n,o.action||a,{preventScrollReset:o.preventScrollReset,formData:d,body:f,formMethod:o.method||l,formEncType:o.encType||c,flushSync:o.flushSync})}else await e.navigate(o.action||a,{preventScrollReset:o.preventScrollReset,formData:d,body:f,formMethod:o.method||l,formEncType:o.encType||c,replace:o.replace,state:o.state,fromRouteId:n,flushSync:o.flushSync,viewTransition:o.viewTransition})},[e,t,n])}function zC(e,{relative:t}={}){let{basename:n}=I.useContext(dr),r=I.useContext(Ir);at(r,"useFormAction must be used inside a RouteContext");let[o]=r.matches.slice(-1),a={...Wa(e||".",{relative:t})},l=Ri();if(e==null){a.search=l.search;let c=new URLSearchParams(a.search),d=c.getAll("index");if(d.some(p=>p==="")){c.delete("index"),d.filter(m=>m).forEach(m=>c.append("index",m));let p=c.toString();a.search=p?`?${p}`:""}}return(!e||e===".")&&o.route.index&&(a.search=a.search?a.search.replace(/^\?/,"?index&"):"?index"),n!=="/"&&(a.pathname=a.pathname==="/"?n:Hr([n,a.pathname])),ja(a)}function OC(e,{relative:t}={}){let n=I.useContext(zx);at(n!=null,"`useViewTransitionState` must be used within `react-router-dom`'s `RouterProvider`. Did you accidentally import `RouterProvider` from `react-router`?");let{basename:r}=qx("useViewTransitionState"),o=Wa(e,{relative:t});if(!n.isTransitioning)return!1;let a=Wr(n.currentLocation.pathname,r)||n.currentLocation.pathname,l=Wr(n.nextLocation.pathname,r)||n.nextLocation.pathname;return zu(o.pathname,l)!=null||zu(o.pathname,a)!=null}var FC=Nx();const Gx=I.createContext(null),ss="portagent_token",qs="portagent_user";async function VC(e,t){try{const n=await fetch("/api/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({usernameOrEmail:e,password:t})}),r=await n.json();return n.ok?{token:r.token,user:r.user}:{error:r.error||"Login failed"}}catch{return{error:"Network error"}}}async function BC(e,t,n,r){try{const o=await fetch("/api/auth/register",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:e,email:t,password:n,displayName:r})}),a=await o.json();return o.ok?{token:a.token,user:a.user}:{error:a.error||"Registration failed"}}catch{return{error:"Network error"}}}async function $C(e){try{const t=await fetch("/api/auth/verify",{headers:{Authorization:`Bearer ${e}`}});return t.ok?(await t.json()).user:null}catch{return null}}function UC({children:e}){const[t,n]=I.useState(null),[r,o]=I.useState(null),[a,l]=I.useState(!0);I.useEffect(()=>{const p=localStorage.getItem(ss),m=localStorage.getItem(qs);if(p&&m)try{$C(p).then(y=>{y?(n(p),o(y)):(localStorage.removeItem(ss),localStorage.removeItem(qs)),l(!1)})}catch{localStorage.removeItem(ss),localStorage.removeItem(qs),l(!1)}else l(!1)},[]);const c=I.useCallback(async(p,m)=>{const y=await VC(p,m);return"token"in y?(localStorage.setItem(ss,y.token),localStorage.setItem(qs,JSON.stringify(y.user)),n(y.token),o(y.user),{success:!0}):{success:!1,error:y.error}},[]),d=I.useCallback(async(p,m,y,v)=>{const b=await BC(p,m,y,v);return"token"in b?(localStorage.setItem(ss,b.token),localStorage.setItem(qs,JSON.stringify(b.user)),n(b.token),o(b.user),{success:!0}):{success:!1,error:b.error}},[]),f=I.useCallback(()=>{localStorage.removeItem(ss),localStorage.removeItem(qs),n(null),o(null)},[]);return w.jsx(Gx.Provider,{value:{isAuthenticated:!!t,isLoading:a,token:t,user:r,login:c,register:d,logout:f},children:e})}function nc(){const e=I.useContext(Gx);if(!e)throw new Error("useAuth must be used within AuthProvider");return e}function HC(){return localStorage.getItem(ss)}function WC(){const[e,t]=I.useState(""),[n,r]=I.useState(""),[o,a]=I.useState(""),[l,c]=I.useState(!1),{login:d,isAuthenticated:f}=nc(),p=Zu();I.useEffect(()=>{f&&p("/studio",{replace:!0})},[f,p]);const m=async y=>{y.preventDefault(),a(""),c(!0);const v=await d(e,n);v.success?p("/studio",{replace:!0}):(a(v.error||"Login failed"),c(!1))};return w.jsx("div",{className:"min-h-screen bg-background flex items-center justify-center p-4",children:w.jsxs("div",{className:"w-full max-w-md",children:[w.jsxs("div",{className:"text-center mb-8",children:[w.jsx("h1",{className:"text-4xl font-bold text-foreground mb-2",children:"Portagent"}),w.jsx("p",{className:"text-muted-foreground",children:"AgentX Portal"})]}),w.jsxs("div",{className:"bg-card rounded-lg p-8 shadow-xl border border-border",children:[w.jsxs("form",{onSubmit:m,className:"space-y-6",children:[w.jsxs("div",{children:[w.jsx("label",{htmlFor:"usernameOrEmail",className:"block text-sm font-medium text-foreground mb-2",children:"Username or Email"}),w.jsx("input",{id:"usernameOrEmail",type:"text",value:e,onChange:y=>t(y.target.value),placeholder:"Enter your username or email",className:"w-full px-4 py-3 bg-muted border border-input rounded-lg text-foreground placeholder-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:border-transparent",autoFocus:!0,required:!0})]}),w.jsxs("div",{children:[w.jsx("label",{htmlFor:"password",className:"block text-sm font-medium text-foreground mb-2",children:"Password"}),w.jsx("input",{id:"password",type:"password",value:n,onChange:y=>r(y.target.value),placeholder:"Enter your password",className:"w-full px-4 py-3 bg-muted border border-input rounded-lg text-foreground placeholder-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:border-transparent",required:!0})]}),o&&w.jsx("div",{className:"text-destructive text-sm text-center",children:o}),w.jsx("button",{type:"submit",disabled:l||!e||!n,className:"w-full py-3 px-4 bg-primary hover:bg-primary/90 disabled:bg-muted disabled:text-muted-foreground disabled:cursor-not-allowed text-primary-foreground font-medium rounded-lg transition-colors",children:l?"Signing in...":"Sign In"})]}),w.jsx("div",{className:"mt-6 text-center text-sm text-muted-foreground",children:w.jsxs("p",{children:["Don't have an account?"," ",w.jsx(tc,{to:"/register",className:"text-primary hover:underline",children:"Sign up"})]})})]})]})})}function qC(){const[e,t]=I.useState(""),[n,r]=I.useState(""),[o,a]=I.useState(""),[l,c]=I.useState(""),[d,f]=I.useState(""),[p,m]=I.useState(""),[y,v]=I.useState(!1),{register:b,isAuthenticated:S}=nc(),C=Zu();I.useEffect(()=>{S&&C("/studio",{replace:!0})},[S,C]);const E=async P=>{if(P.preventDefault(),m(""),o!==l){m("Passwords do not match");return}if(o.length<6){m("Password must be at least 6 characters");return}if(e.length<3){m("Username must be at least 3 characters");return}if(!n.includes("@")){m("Invalid email address");return}v(!0);const T=await b(e,n,o,d||void 0);T.success?C("/studio",{replace:!0}):(m(T.error||"Registration failed"),v(!1))};return w.jsx("div",{className:"min-h-screen bg-background flex items-center justify-center p-4",children:w.jsxs("div",{className:"w-full max-w-md",children:[w.jsxs("div",{className:"text-center mb-8",children:[w.jsx("h1",{className:"text-4xl font-bold text-foreground mb-2",children:"Portagent"}),w.jsx("p",{className:"text-muted-foreground",children:"Create your account"})]}),w.jsxs("div",{className:"bg-card rounded-lg p-8 shadow-xl border border-border",children:[w.jsxs("form",{onSubmit:E,className:"space-y-4",children:[w.jsxs("div",{children:[w.jsx("label",{htmlFor:"username",className:"block text-sm font-medium text-foreground mb-2",children:"Username *"}),w.jsx("input",{id:"username",type:"text",value:e,onChange:P=>t(P.target.value),placeholder:"Choose a username",className:"w-full px-4 py-3 bg-muted border border-input rounded-lg text-foreground placeholder-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:border-transparent",autoFocus:!0,required:!0,minLength:3})]}),w.jsxs("div",{children:[w.jsx("label",{htmlFor:"email",className:"block text-sm font-medium text-foreground mb-2",children:"Email *"}),w.jsx("input",{id:"email",type:"email",value:n,onChange:P=>r(P.target.value),placeholder:"your@email.com",className:"w-full px-4 py-3 bg-muted border border-input rounded-lg text-foreground placeholder-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:border-transparent",required:!0})]}),w.jsxs("div",{children:[w.jsx("label",{htmlFor:"displayName",className:"block text-sm font-medium text-foreground mb-2",children:"Display Name (optional)"}),w.jsx("input",{id:"displayName",type:"text",value:d,onChange:P=>f(P.target.value),placeholder:"How you want to be called",className:"w-full px-4 py-3 bg-muted border border-input rounded-lg text-foreground placeholder-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:border-transparent"})]}),w.jsxs("div",{children:[w.jsx("label",{htmlFor:"password",className:"block text-sm font-medium text-foreground mb-2",children:"Password *"}),w.jsx("input",{id:"password",type:"password",value:o,onChange:P=>a(P.target.value),placeholder:"At least 6 characters",className:"w-full px-4 py-3 bg-muted border border-input rounded-lg text-foreground placeholder-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:border-transparent",required:!0,minLength:6})]}),w.jsxs("div",{children:[w.jsx("label",{htmlFor:"confirmPassword",className:"block text-sm font-medium text-foreground mb-2",children:"Confirm Password *"}),w.jsx("input",{id:"confirmPassword",type:"password",value:l,onChange:P=>c(P.target.value),placeholder:"Re-enter your password",className:"w-full px-4 py-3 bg-muted border border-input rounded-lg text-foreground placeholder-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:border-transparent",required:!0,minLength:6})]}),p&&w.jsx("div",{className:"text-destructive text-sm text-center",children:p}),w.jsx("button",{type:"submit",disabled:y||!e||!n||!o||!l,className:"w-full py-3 px-4 bg-primary hover:bg-primary/90 disabled:bg-muted disabled:text-muted-foreground disabled:cursor-not-allowed text-primary-foreground font-medium rounded-lg transition-colors",children:y?"Creating account...":"Sign Up"})]}),w.jsx("div",{className:"mt-6 text-center text-sm text-muted-foreground",children:w.jsxs("p",{children:["Already have an account?"," ",w.jsx(tc,{to:"/login",className:"text-primary hover:underline",children:"Sign in"})]})})]})]})})}var cn=(e=>(e[e.DEBUG=0]="DEBUG",e[e.INFO=1]="INFO",e[e.WARN=2]="WARN",e[e.ERROR=3]="ERROR",e[e.SILENT=4]="SILENT",e))(cn||{}),GC=["agent_initializing","agent_ready","agent_destroyed","conversation_queued","conversation_start","conversation_thinking","conversation_responding","conversation_end","conversation_interrupted","tool_planned","tool_executing","tool_completed","tool_failed","error_occurred"],KC=new Set(GC),YC=["user_message","assistant_message","tool_call_message","tool_result_message"];new Set(YC);var XC=["error"];new Set(XC);var QC=["turn_request","turn_response"];new Set(QC);var Kx=["message_start","message_delta","message_stop","text_content_block_start","text_delta","text_content_block_stop","tool_use_content_block_start","input_json_delta","tool_use_content_block_stop","tool_call","tool_result","interrupted"];new Set(Kx);function JC(e){return"type"in e&&KC.has(e.type)}var ZC=Object.defineProperty,eI=(e,t,n)=>t in e?ZC(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,ls=(e,t,n)=>eI(e,typeof t!="symbol"?t+"":t,n),Yx=class qf{constructor(t,n={}){ls(this,"name"),ls(this,"level"),ls(this,"colors"),ls(this,"timestamps"),this.name=t,this.level=n.level??cn.INFO,this.colors=n.colors??this.isNodeEnvironment(),this.timestamps=n.timestamps??!0}debug(t,n){this.isDebugEnabled()&&this.log("DEBUG",t,n)}info(t,n){this.isInfoEnabled()&&this.log("INFO",t,n)}warn(t,n){this.isWarnEnabled()&&this.log("WARN",t,n)}error(t,n){this.isErrorEnabled()&&(t instanceof Error?this.log("ERROR",t.message,{...n,stack:t.stack}):this.log("ERROR",t,n))}isDebugEnabled(){return this.level<=cn.DEBUG}isInfoEnabled(){return this.level<=cn.INFO}isWarnEnabled(){return this.level<=cn.WARN}isErrorEnabled(){return this.level<=cn.ERROR}log(t,n,r){const o=[];if(this.timestamps&&o.push(new Date().toISOString()),this.colors){const c=qf.COLORS[t];o.push(`${c}${t.padEnd(5)}${qf.COLORS.RESET}`)}else o.push(t.padEnd(5));o.push(`[${this.name}]`),o.push(n);const a=o.join(" "),l=this.getConsoleMethod(t);r&&Object.keys(r).length>0?l(a,r):l(a)}getConsoleMethod(t){switch(t){case"DEBUG":return console.debug.bind(console);case"INFO":return console.info.bind(console);case"WARN":return console.warn.bind(console);case"ERROR":return console.error.bind(console);default:return console.log.bind(console)}}isNodeEnvironment(){var t;return typeof process<"u"&&((t=process.versions)==null?void 0:t.node)!==void 0}};ls(Yx,"COLORS",{DEBUG:"\x1B[36m",INFO:"\x1B[32m",WARN:"\x1B[33m",ERROR:"\x1B[31m",RESET:"\x1B[0m"});var tI=Yx,ka=null,rc=class{static getLogger(t){const n=typeof t=="string"?t:t.name;if(this.loggers.has(n))return this.loggers.get(n);const r=this.createLazyLogger(n);return this.loggers.set(n,r),r}static configure(t){this.config={...this.config,...t}}static reset(){this.loggers.clear(),this.config={defaultLevel:cn.INFO},ka=null}static createLazyLogger(t){let n=null;const r=()=>(n||(n=this.createLogger(t)),n);return{name:t,level:this.config.defaultLevel||cn.INFO,debug:(o,a)=>r().debug(o,a),info:(o,a)=>r().info(o,a),warn:(o,a)=>r().warn(o,a),error:(o,a)=>r().error(o,a),isDebugEnabled:()=>r().isDebugEnabled(),isInfoEnabled:()=>r().isInfoEnabled(),isWarnEnabled:()=>r().isWarnEnabled(),isErrorEnabled:()=>r().isErrorEnabled()}}static createLogger(t){return ka?ka.getLogger(t):this.config.defaultImplementation?this.config.defaultImplementation(t):new tI(t,{level:this.config.defaultLevel,...this.config.consoleOptions})}};ls(rc,"loggers",new Map);ls(rc,"config",{defaultLevel:cn.INFO});function nI(e){ka=e,rc.reset(),ka=e}function qt(e){return rc.getLogger(e)}class Gf extends Error{constructor(n,r,o){const a=n.status||n.status===0?n.status:"",l=n.statusText??"",c=`${a} ${l}`.trim(),d=c?`status code ${c}`:"an unknown error";super(`Request failed with ${d}: ${r.method} ${r.url}`);wn(this,"response");wn(this,"request");wn(this,"options");this.name="HTTPError",this.response=n,this.request=r,this.options=o}}class Xx extends Error{constructor(n){let r="Non-error value was thrown";try{typeof n=="string"?r=n:n&&typeof n=="object"&&"message"in n&&typeof n.message=="string"&&(r=n.message)}catch{}super(r);wn(this,"name","NonError");wn(this,"value");this.value=n}}class Jd extends Error{constructor(n){const r=n!=null&&n.cause?n.cause instanceof Error?n.cause:new Xx(n.cause):void 0;super(n!=null&&n.code?`Forced retry: ${n.code}`:"Forced retry",r?{cause:r}:void 0);wn(this,"name","ForceRetryError");wn(this,"customDelay");wn(this,"code");wn(this,"customRequest");this.customDelay=n==null?void 0:n.delay,this.code=n==null?void 0:n.code,this.customRequest=n==null?void 0:n.request}}const Oy=(()=>{let e=!1,t=!1;const n=typeof globalThis.ReadableStream=="function",r=typeof globalThis.Request=="function";if(n&&r)try{t=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type")}catch(o){if(o instanceof Error&&o.message==="unsupported BodyInit type")return!1;throw o}return e&&!t})(),rI=typeof globalThis.AbortController=="function",Qx=typeof globalThis.AbortSignal=="function"&&typeof globalThis.AbortSignal.any=="function",iI=typeof globalThis.ReadableStream=="function",sI=typeof globalThis.FormData=="function",Jx=["get","post","put","patch","head","delete"],oI={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*",bytes:"*/*"},Zd=2147483647,aI=new TextEncoder().encode("------WebKitFormBoundaryaxpyiPgbbPti10Rw").length,Zx=Symbol("stop");class ew{constructor(t){wn(this,"options");this.options=t}}const lI=e=>new ew(e),uI={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,onUploadProgress:!0,fetch:!0,context:!0},cI={next:!0},dI={method:!0,headers:!0,body:!0,mode:!0,credentials:!0,cache:!0,redirect:!0,referrer:!0,referrerPolicy:!0,integrity:!0,keepalive:!0,signal:!0,window:!0,duplex:!0},fI=e=>{if(!e)return 0;if(e instanceof FormData){let t=0;for(const[n,r]of e)t+=aI,t+=new TextEncoder().encode(`Content-Disposition: form-data; name="${n}"`).length,t+=typeof r=="string"?new TextEncoder().encode(r).length:r.size;return t}if(e instanceof Blob)return e.size;if(e instanceof ArrayBuffer)return e.byteLength;if(typeof e=="string")return new TextEncoder().encode(e).length;if(e instanceof URLSearchParams)return new TextEncoder().encode(e.toString()).length;if("byteLength"in e)return e.byteLength;if(typeof e=="object"&&e!==null)try{const t=JSON.stringify(e);return new TextEncoder().encode(t).length}catch{return 0}return 0},tw=(e,t,n)=>{let r,o=0;return e.pipeThrough(new TransformStream({transform(a,l){if(l.enqueue(a),r){o+=r.byteLength;let c=t===0?0:o/t;c>=1&&(c=1-Number.EPSILON),n==null||n({percent:c,totalBytes:Math.max(t,o),transferredBytes:o},r)}r=a},flush(){r&&(o+=r.byteLength,n==null||n({percent:1,totalBytes:Math.max(t,o),transferredBytes:o},r))}}))},hI=(e,t)=>{if(!e.body)return e;if(e.status===204)return new Response(null,{status:e.status,statusText:e.statusText,headers:e.headers});const n=Math.max(0,Number(e.headers.get("content-length"))||0);return new Response(tw(e.body,n,t),{status:e.status,statusText:e.statusText,headers:e.headers})},pI=(e,t,n)=>{if(!e.body)return e;const r=fI(n??e.body);return new Request(e,{duplex:"half",body:tw(e.body,r,t)})},as=e=>e!==null&&typeof e=="object",uu=(...e)=>{for(const t of e)if((!as(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return Xh({},...e)},nw=(e={},t={})=>{const n=new globalThis.Headers(e),r=t instanceof globalThis.Headers,o=new globalThis.Headers(t);for(const[a,l]of o.entries())r&&l==="undefined"||l===void 0?n.delete(a):n.set(a,l);return n};function cu(e,t,n){return Object.hasOwn(t,n)&&t[n]===void 0?[]:Xh(e[n]??[],t[n]??[])}const rw=(e={},t={})=>({beforeRequest:cu(e,t,"beforeRequest"),beforeRetry:cu(e,t,"beforeRetry"),afterResponse:cu(e,t,"afterResponse"),beforeError:cu(e,t,"beforeError")}),mI=(e,t)=>{const n=new URLSearchParams;for(const r of[e,t])if(r!==void 0)if(r instanceof URLSearchParams)for(const[o,a]of r.entries())n.append(o,a);else if(Array.isArray(r))for(const o of r){if(!Array.isArray(o)||o.length!==2)throw new TypeError("Array search parameters must be provided in [[key, value], ...] format");n.append(String(o[0]),String(o[1]))}else if(as(r))for(const[o,a]of Object.entries(r))a!==void 0&&n.append(o,String(a));else{const o=new URLSearchParams(r);for(const[a,l]of o.entries())n.append(a,l)}return n},Xh=(...e)=>{let t={},n={},r={},o;const a=[];for(const l of e)if(Array.isArray(l))Array.isArray(t)||(t=[]),t=[...t,...l];else if(as(l)){for(let[c,d]of Object.entries(l)){if(c==="signal"&&d instanceof globalThis.AbortSignal){a.push(d);continue}if(c==="context"){if(d!=null&&(!as(d)||Array.isArray(d)))throw new TypeError("The `context` option must be an object");t={...t,context:d==null?{}:{...t.context,...d}};continue}if(c==="searchParams"){d==null?o=void 0:o=o===void 0?d:mI(o,d);continue}as(d)&&c in t&&(d=Xh(t[c],d)),t={...t,[c]:d}}as(l.hooks)&&(r=rw(r,l.hooks),t.hooks=r),as(l.headers)&&(n=nw(n,l.headers),t.headers=n)}return o!==void 0&&(t.searchParams=o),a.length>0&&(a.length===1?t.signal=a[0]:Qx?t.signal=AbortSignal.any(a):t.signal=a.at(-1)),t.context===void 0&&(t.context={}),t},gI=e=>Jx.includes(e)?e.toUpperCase():e,yI=["get","put","head","delete","options","trace"],vI=[408,413,429,500,502,503,504],xI=[413,429,503],Fy={limit:2,methods:yI,statusCodes:vI,afterStatusCodes:xI,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3,jitter:void 0,retryOnTimeout:!1},wI=(e={})=>{if(typeof e=="number")return{...Fy,limit:e};if(e.methods&&!Array.isArray(e.methods))throw new Error("retry.methods must be an array");if(e.statusCodes&&!Array.isArray(e.statusCodes))throw new Error("retry.statusCodes must be an array");return{...Fy,...e}};class Kf extends Error{constructor(n){super(`Request timed out: ${n.method} ${n.url}`);wn(this,"request");this.name="TimeoutError",this.request=n}}async function bI(e,t,n,r){return new Promise((o,a)=>{const l=setTimeout(()=>{n&&n.abort(),a(new Kf(e))},r.timeout);r.fetch(e,t).then(o).catch(a).then(()=>{clearTimeout(l)})})}async function SI(e,{signal:t}){return new Promise((n,r)=>{t&&(t.throwIfAborted(),t.addEventListener("abort",o,{once:!0}));function o(){clearTimeout(a),r(t.reason)}const a=setTimeout(()=>{t==null||t.removeEventListener("abort",o),n()},e)})}const kI=(e,t)=>{const n={};for(const r in t)Object.hasOwn(t,r)&&!(r in dI)&&!(r in uI)&&(!(r in e)||r in cI)&&(n[r]=t[r]);return n},EI=e=>e===void 0?!1:Array.isArray(e)?e.length>0:e instanceof URLSearchParams?e.size>0:typeof e=="object"?Object.keys(e).length>0:typeof e=="string"?e.trim().length>0:!!e;function CI(e){return e instanceof Gf||(e==null?void 0:e.name)===Gf.name}function II(e){return e instanceof Kf||(e==null?void 0:e.name)===Kf.name}var Qu,iw,ur,$n,Ut,ge,Ti,Sr,fs,Xe,Pu,sw,Yf,Xf,ow,wa,Au,Qf;const Na=class Na{constructor(t,n={}){xr(this,Xe);wn(this,"request");xr(this,ur);xr(this,$n,0);xr(this,Ut);xr(this,ge);xr(this,Ti);xr(this,Sr);xr(this,fs);var o,a,l;if(ir(this,Ut,t),ir(this,ge,{...n,headers:nw(J(this,Ut).headers,n.headers),hooks:rw({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},n.hooks),method:gI(n.method??J(this,Ut).method??"GET"),prefixUrl:String(n.prefixUrl||""),retry:wI(n.retry),throwHttpErrors:n.throwHttpErrors??!0,timeout:n.timeout??1e4,fetch:n.fetch??globalThis.fetch.bind(globalThis),context:n.context??{}}),typeof J(this,Ut)!="string"&&!(J(this,Ut)instanceof URL||J(this,Ut)instanceof globalThis.Request))throw new TypeError("`input` must be a string, URL, or Request");if(J(this,ge).prefixUrl&&typeof J(this,Ut)=="string"){if(J(this,Ut).startsWith("/"))throw new Error("`input` must not begin with a slash when using `prefixUrl`");J(this,ge).prefixUrl.endsWith("/")||(J(this,ge).prefixUrl+="/"),ir(this,Ut,J(this,ge).prefixUrl+J(this,Ut))}rI&&Qx&&(ir(this,Sr,J(this,ge).signal??J(this,Ut).signal),ir(this,ur,new globalThis.AbortController),J(this,ge).signal=J(this,Sr)?AbortSignal.any([J(this,Sr),J(this,ur).signal]):J(this,ur).signal),Oy&&(J(this,ge).duplex="half"),J(this,ge).json!==void 0&&(J(this,ge).body=((a=(o=J(this,ge)).stringifyJson)==null?void 0:a.call(o,J(this,ge).json))??JSON.stringify(J(this,ge).json),J(this,ge).headers.set("content-type",J(this,ge).headers.get("content-type")??"application/json"));const r=n.headers&&new globalThis.Headers(n.headers).has("content-type");if(J(this,Ut)instanceof globalThis.Request&&(sI&&J(this,ge).body instanceof globalThis.FormData||J(this,ge).body instanceof URLSearchParams)&&!r&&J(this,ge).headers.delete("content-type"),this.request=new globalThis.Request(J(this,Ut),J(this,ge)),EI(J(this,ge).searchParams)){const d="?"+(typeof J(this,ge).searchParams=="string"?J(this,ge).searchParams.replace(/^\?/,""):new URLSearchParams(vt(l=Na,Qu,iw).call(l,J(this,ge).searchParams)).toString()),f=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,d);this.request=new globalThis.Request(f,J(this,ge))}if(J(this,ge).onUploadProgress){if(typeof J(this,ge).onUploadProgress!="function")throw new TypeError("The `onUploadProgress` option must be a function");if(!Oy)throw new Error("Request streams are not supported in your environment. The `duplex` option for `Request` is not available.");this.request=vt(this,Xe,Qf).call(this,this.request,J(this,ge).body??void 0)}}static create(t,n){var l,c,d;const r=new Na(t,n),o=async()=>{var p,m,y,v,b,S,C;if(typeof J(r,ge).timeout=="number"&&J(r,ge).timeout>Zd)throw new RangeError(`The \`timeout\` option cannot be greater than ${Zd}`);await Promise.resolve();let f=await vt(p=r,Xe,ow).call(p);for(const E of J(r,ge).hooks.afterResponse){const P=vt(m=r,Xe,Yf).call(m,f.clone()),T=await E(r.request,vt(y=r,Xe,wa).call(y),P,{retryCount:J(r,$n)});if(T instanceof globalThis.Response&&(f=T),T instanceof ew)throw await Promise.all([(v=P.body)==null?void 0:v.cancel(),(b=f.body)==null?void 0:b.cancel()]),new Jd(T.options)}if(vt(S=r,Xe,Yf).call(S,f),!f.ok&&(typeof J(r,ge).throwHttpErrors=="function"?J(r,ge).throwHttpErrors(f.status):J(r,ge).throwHttpErrors)){let E=new Gf(f,r.request,vt(C=r,Xe,wa).call(C));for(const P of J(r,ge).hooks.beforeError)E=await P(E,{retryCount:J(r,$n)});throw E}if(J(r,ge).onDownloadProgress){if(typeof J(r,ge).onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!iI)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return hI(f.clone(),J(r,ge).onDownloadProgress)}return f},a=vt(l=r,Xe,Xf).call(l,o).finally(async()=>{var m,y;const f=J(r,Ti),p=[];f&&!f.bodyUsed&&p.push((m=f.body)==null?void 0:m.cancel()),r.request.bodyUsed||p.push((y=r.request.body)==null?void 0:y.cancel()),await Promise.all(p)});for(const[f,p]of Object.entries(oI))f==="bytes"&&typeof((d=(c=globalThis.Response)==null?void 0:c.prototype)==null?void 0:d.bytes)!="function"||(a[f]=async()=>{r.request.headers.set("accept",r.request.headers.get("accept")||p);const m=await a;if(f==="json"){if(m.status===204)return"";const y=await m.text();return y===""?"":n.parseJson?n.parseJson(y):JSON.parse(y)}return m[f]()});return a}};Qu=new WeakSet,iw=function(t){return t&&typeof t=="object"&&!Array.isArray(t)&&!(t instanceof URLSearchParams)?Object.fromEntries(Object.entries(t).filter(([,n])=>n!==void 0)):t},ur=new WeakMap,$n=new WeakMap,Ut=new WeakMap,ge=new WeakMap,Ti=new WeakMap,Sr=new WeakMap,fs=new WeakMap,Xe=new WeakSet,Pu=function(){const t=J(this,ge).retry.delay(J(this,$n));let n=t;return J(this,ge).retry.jitter===!0?n=Math.random()*t:typeof J(this,ge).retry.jitter=="function"&&(n=J(this,ge).retry.jitter(t),(!Number.isFinite(n)||n<0)&&(n=t)),Math.min(J(this,ge).retry.backoffLimit,n)},sw=async function(t){if(Sy(this,$n)._++,J(this,$n)>J(this,ge).retry.limit)throw t;const n=t instanceof Error?t:new Xx(t);if(n instanceof Jd)return n.customDelay??vt(this,Xe,Pu).call(this);if(!J(this,ge).retry.methods.includes(this.request.method.toLowerCase()))throw t;if(J(this,ge).retry.shouldRetry!==void 0){const r=await J(this,ge).retry.shouldRetry({error:n,retryCount:J(this,$n)});if(r===!1)throw t;if(r===!0)return vt(this,Xe,Pu).call(this)}if(II(t)&&!J(this,ge).retry.retryOnTimeout)throw t;if(CI(t)){if(!J(this,ge).retry.statusCodes.includes(t.response.status))throw t;const r=t.response.headers.get("Retry-After")??t.response.headers.get("RateLimit-Reset")??t.response.headers.get("X-RateLimit-Retry-After")??t.response.headers.get("X-RateLimit-Reset")??t.response.headers.get("X-Rate-Limit-Reset");if(r&&J(this,ge).retry.afterStatusCodes.includes(t.response.status)){let o=Number(r)*1e3;Number.isNaN(o)?o=Date.parse(r)-Date.now():o>=Date.parse("2024-01-01")&&(o-=Date.now());const a=J(this,ge).retry.maxRetryAfter??o;return o<a?o:a}if(t.response.status===413)throw t}return vt(this,Xe,Pu).call(this)},Yf=function(t){return J(this,ge).parseJson&&(t.json=async()=>J(this,ge).parseJson(await t.text())),t},Xf=async function(t){try{return await t()}catch(n){const r=Math.min(await vt(this,Xe,sw).call(this,n),Zd);if(J(this,$n)<1)throw n;if(await SI(r,J(this,Sr)?{signal:J(this,Sr)}:{}),n instanceof Jd&&n.customRequest){const o=J(this,ge).signal?new globalThis.Request(n.customRequest,{signal:J(this,ge).signal}):new globalThis.Request(n.customRequest);vt(this,Xe,Au).call(this,o)}for(const o of J(this,ge).hooks.beforeRetry){const a=await o({request:this.request,options:vt(this,Xe,wa).call(this),error:n,retryCount:J(this,$n)});if(a instanceof globalThis.Request){vt(this,Xe,Au).call(this,a);break}if(a instanceof globalThis.Response)return a;if(a===Zx)return}return vt(this,Xe,Xf).call(this,t)}},ow=async function(){var n;(n=J(this,ur))!=null&&n.signal.aborted&&(ir(this,ur,new globalThis.AbortController),J(this,ge).signal=J(this,Sr)?AbortSignal.any([J(this,Sr),J(this,ur).signal]):J(this,ur).signal,this.request=new globalThis.Request(this.request,{signal:J(this,ge).signal}));for(const r of J(this,ge).hooks.beforeRequest){const o=await r(this.request,vt(this,Xe,wa).call(this),{retryCount:J(this,$n)});if(o instanceof Response)return o;if(o instanceof globalThis.Request){vt(this,Xe,Au).call(this,o);break}}const t=kI(this.request,J(this,ge));return ir(this,Ti,this.request),this.request=J(this,Ti).clone(),J(this,ge).timeout===!1?J(this,ge).fetch(J(this,Ti),t):bI(J(this,Ti),t,J(this,ur),J(this,ge))},wa=function(){if(!J(this,fs)){const{hooks:t,...n}=J(this,ge);ir(this,fs,Object.freeze(n))}return J(this,fs)},Au=function(t){ir(this,fs,void 0),this.request=vt(this,Xe,Qf).call(this,t)},Qf=function(t,n){return!J(this,ge).onUploadProgress||!t.body?t:pI(t,J(this,ge).onUploadProgress,n??J(this,ge).body??void 0)},xr(Na,Qu);let Ou=Na;/*! MIT License © Sindre Sorhus */const Jf=e=>{const t=(n,r)=>Ou.create(n,uu(e,r));for(const n of Jx)t[n]=(r,o)=>Ou.create(r,uu(e,o,{method:n}));return t.create=n=>Jf(uu(n)),t.extend=n=>(typeof n=="function"&&(n=n(e??{})),Jf(uu(e,n))),t.stop=Zx,t.retry=lI,t},TI=Jf();var Zf=function(e,t){return Zf=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,r){n.__proto__=r}||function(n,r){for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(n[o]=r[o])},Zf(e,t)};function qa(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");Zf(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}function eh(e){var t=typeof Symbol=="function"&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function th(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),o,a=[],l;try{for(;(t===void 0||t-- >0)&&!(o=r.next()).done;)a.push(o.value)}catch(c){l={error:c}}finally{try{o&&!o.done&&(n=r.return)&&n.call(r)}finally{if(l)throw l.error}}return a}function nh(e,t,n){if(n||arguments.length===2)for(var r=0,o=t.length,a;r<o;r++)(a||!(r in t))&&(a||(a=Array.prototype.slice.call(t,0,r)),a[r]=t[r]);return e.concat(a||Array.prototype.slice.call(t))}function kr(e){return typeof e=="function"}function aw(e){var t=function(r){Error.call(r),r.stack=new Error().stack},n=e(t);return n.prototype=Object.create(Error.prototype),n.prototype.constructor=n,n}var ef=aw(function(e){return function(n){e(this),this.message=n?n.length+` errors occurred during unsubscription:
52
52
  `+n.map(function(r,o){return o+1+") "+r.toString()}).join(`
53
- `):"",this.name="UnsubscriptionError",this.errors=n}});function nh(e,t){if(e){var n=e.indexOf(t);0<=n&&e.splice(n,1)}}var rc=(function(){function e(t){this.initialTeardown=t,this.closed=!1,this._parentage=null,this._finalizers=null}return e.prototype.unsubscribe=function(){var t,n,r,o,a;if(!this.closed){this.closed=!0;var l=this._parentage;if(l)if(this._parentage=null,Array.isArray(l))try{for(var c=Zf(l),d=c.next();!d.done;d=c.next()){var f=d.value;f.remove(this)}}catch(S){t={error:S}}finally{try{d&&!d.done&&(n=c.return)&&n.call(c)}finally{if(t)throw t.error}}else l.remove(this);var p=this.initialTeardown;if(kr(p))try{p()}catch(S){a=S instanceof ef?S.errors:[S]}var m=this._finalizers;if(m){this._finalizers=null;try{for(var y=Zf(m),v=y.next();!v.done;v=y.next()){var b=v.value;try{Vy(b)}catch(S){a=a??[],S instanceof ef?a=th(th([],eh(a)),eh(S.errors)):a.push(S)}}}catch(S){r={error:S}}finally{try{v&&!v.done&&(o=y.return)&&o.call(y)}finally{if(r)throw r.error}}}if(a)throw new ef(a)}},e.prototype.add=function(t){var n;if(t&&t!==this)if(this.closed)Vy(t);else{if(t instanceof e){if(t.closed||t._hasParent(this))return;t._addParent(this)}(this._finalizers=(n=this._finalizers)!==null&&n!==void 0?n:[]).push(t)}},e.prototype._hasParent=function(t){var n=this._parentage;return n===t||Array.isArray(n)&&n.includes(t)},e.prototype._addParent=function(t){var n=this._parentage;this._parentage=Array.isArray(n)?(n.push(t),n):n?[n,t]:t},e.prototype._removeParent=function(t){var n=this._parentage;n===t?this._parentage=null:Array.isArray(n)&&nh(n,t)},e.prototype.remove=function(t){var n=this._finalizers;n&&nh(n,t),t instanceof e&&t._removeParent(this)},e.EMPTY=(function(){var t=new e;return t.closed=!0,t})(),e})(),aw=rc.EMPTY;function lw(e){return e instanceof rc||e&&"closed"in e&&kr(e.remove)&&kr(e.add)&&kr(e.unsubscribe)}function Vy(e){kr(e)?e():e.unsubscribe()}var EI={Promise:void 0},CI={setTimeout:function(e,t){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];return setTimeout.apply(void 0,th([e,t],eh(n)))},clearTimeout:function(e){return clearTimeout(e)},delegate:void 0};function II(e){CI.setTimeout(function(){throw e})}function By(){}function Ru(e){e()}var Qh=(function(e){qa(t,e);function t(n){var r=e.call(this)||this;return r.isStopped=!1,n?(r.destination=n,lw(n)&&n.add(r)):r.destination=PI,r}return t.create=function(n,r,o){return new rh(n,r,o)},t.prototype.next=function(n){this.isStopped||this._next(n)},t.prototype.error=function(n){this.isStopped||(this.isStopped=!0,this._error(n))},t.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},t.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,e.prototype.unsubscribe.call(this),this.destination=null)},t.prototype._next=function(n){this.destination.next(n)},t.prototype._error=function(n){try{this.destination.error(n)}finally{this.unsubscribe()}},t.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},t})(rc),TI=(function(){function e(t){this.partialObserver=t}return e.prototype.next=function(t){var n=this.partialObserver;if(n.next)try{n.next(t)}catch(r){du(r)}},e.prototype.error=function(t){var n=this.partialObserver;if(n.error)try{n.error(t)}catch(r){du(r)}else du(t)},e.prototype.complete=function(){var t=this.partialObserver;if(t.complete)try{t.complete()}catch(n){du(n)}},e})(),rh=(function(e){qa(t,e);function t(n,r,o){var a=e.call(this)||this,l;return kr(n)||!n?l={next:n??void 0,error:r??void 0,complete:o??void 0}:l=n,a.destination=new TI(l),a}return t})(Qh);function du(e){II(e)}function _I(e){throw e}var PI={closed:!0,next:By,error:_I,complete:By},AI=(function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"})();function RI(e){return e}function NI(e){return e.length===0?RI:e.length===1?e[0]:function(n){return e.reduce(function(r,o){return o(r)},n)}}var ih=(function(){function e(t){t&&(this._subscribe=t)}return e.prototype.lift=function(t){var n=new e;return n.source=this,n.operator=t,n},e.prototype.subscribe=function(t,n,r){var o=this,a=MI(t)?t:new rh(t,n,r);return Ru(function(){var l=o,c=l.operator,d=l.source;a.add(c?c.call(a,d):d?o._subscribe(a):o._trySubscribe(a))}),a},e.prototype._trySubscribe=function(t){try{return this._subscribe(t)}catch(n){t.error(n)}},e.prototype.forEach=function(t,n){var r=this;return n=$y(n),new n(function(o,a){var l=new rh({next:function(c){try{t(c)}catch(d){a(d),l.unsubscribe()}},error:a,complete:o});r.subscribe(l)})},e.prototype._subscribe=function(t){var n;return(n=this.source)===null||n===void 0?void 0:n.subscribe(t)},e.prototype[AI]=function(){return this},e.prototype.pipe=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return NI(t)(this)},e.prototype.toPromise=function(t){var n=this;return t=$y(t),new t(function(r,o){var a;n.subscribe(function(l){return a=l},function(l){return o(l)},function(){return r(a)})})},e.create=function(t){return new e(t)},e})();function $y(e){var t;return(t=e??EI.Promise)!==null&&t!==void 0?t:Promise}function jI(e){return e&&kr(e.next)&&kr(e.error)&&kr(e.complete)}function MI(e){return e&&e instanceof Qh||jI(e)&&lw(e)}function DI(e){return kr(e==null?void 0:e.lift)}function uw(e){return function(t){if(DI(t))return t.lift(function(n){try{return e(n,this)}catch(r){this.error(r)}});throw new TypeError("Unable to lift unknown Observable type")}}function cw(e,t,n,r,o){return new LI(e,t,n,r,o)}var LI=(function(e){qa(t,e);function t(n,r,o,a,l,c){var d=e.call(this,n)||this;return d.onFinalize=l,d.shouldUnsubscribe=c,d._next=r?function(f){try{r(f)}catch(p){n.error(p)}}:e.prototype._next,d._error=a?function(f){try{a(f)}catch(p){n.error(p)}finally{this.unsubscribe()}}:e.prototype._error,d._complete=o?function(){try{o()}catch(f){n.error(f)}finally{this.unsubscribe()}}:e.prototype._complete,d}return t.prototype.unsubscribe=function(){var n;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var r=this.closed;e.prototype.unsubscribe.call(this),!r&&((n=this.onFinalize)===null||n===void 0||n.call(this))}},t})(Qh),zI=ow(function(e){return function(){e(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}}),dw=(function(e){qa(t,e);function t(){var n=e.call(this)||this;return n.closed=!1,n.currentObservers=null,n.observers=[],n.isStopped=!1,n.hasError=!1,n.thrownError=null,n}return t.prototype.lift=function(n){var r=new Uy(this,this);return r.operator=n,r},t.prototype._throwIfClosed=function(){if(this.closed)throw new zI},t.prototype.next=function(n){var r=this;Ru(function(){var o,a;if(r._throwIfClosed(),!r.isStopped){r.currentObservers||(r.currentObservers=Array.from(r.observers));try{for(var l=Zf(r.currentObservers),c=l.next();!c.done;c=l.next()){var d=c.value;d.next(n)}}catch(f){o={error:f}}finally{try{c&&!c.done&&(a=l.return)&&a.call(l)}finally{if(o)throw o.error}}}})},t.prototype.error=function(n){var r=this;Ru(function(){if(r._throwIfClosed(),!r.isStopped){r.hasError=r.isStopped=!0,r.thrownError=n;for(var o=r.observers;o.length;)o.shift().error(n)}})},t.prototype.complete=function(){var n=this;Ru(function(){if(n._throwIfClosed(),!n.isStopped){n.isStopped=!0;for(var r=n.observers;r.length;)r.shift().complete()}})},t.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(t.prototype,"observed",{get:function(){var n;return((n=this.observers)===null||n===void 0?void 0:n.length)>0},enumerable:!1,configurable:!0}),t.prototype._trySubscribe=function(n){return this._throwIfClosed(),e.prototype._trySubscribe.call(this,n)},t.prototype._subscribe=function(n){return this._throwIfClosed(),this._checkFinalizedStatuses(n),this._innerSubscribe(n)},t.prototype._innerSubscribe=function(n){var r=this,o=this,a=o.hasError,l=o.isStopped,c=o.observers;return a||l?aw:(this.currentObservers=null,c.push(n),new rc(function(){r.currentObservers=null,nh(c,n)}))},t.prototype._checkFinalizedStatuses=function(n){var r=this,o=r.hasError,a=r.thrownError,l=r.isStopped;o?n.error(a):l&&n.complete()},t.prototype.asObservable=function(){var n=new ih;return n.source=this,n},t.create=function(n,r){return new Uy(n,r)},t})(ih),Uy=(function(e){qa(t,e);function t(n,r){var o=e.call(this)||this;return o.destination=n,o.source=r,o}return t.prototype.next=function(n){var r,o;(o=(r=this.destination)===null||r===void 0?void 0:r.next)===null||o===void 0||o.call(r,n)},t.prototype.error=function(n){var r,o;(o=(r=this.destination)===null||r===void 0?void 0:r.error)===null||o===void 0||o.call(r,n)},t.prototype.complete=function(){var n,r;(r=(n=this.destination)===null||n===void 0?void 0:n.complete)===null||r===void 0||r.call(n)},t.prototype._subscribe=function(n){var r,o;return(o=(r=this.source)===null||r===void 0?void 0:r.subscribe(n))!==null&&o!==void 0?o:aw},t})(dw),OI=new ih(function(e){return e.complete()});function tf(e,t){return uw(function(n,r){var o=0;n.subscribe(cw(r,function(a){return e.call(t,a,o++)&&r.next(a)}))})}function Hy(e){return e<=0?function(){return OI}:uw(function(t,n){var r=0;t.subscribe(cw(n,function(o){++r<=e&&(n.next(o),e<=r&&n.complete())}))})}var FI=Object.defineProperty,VI=(e,t,n)=>t in e?FI(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,me=(e,t,n)=>VI(e,typeof t!="symbol"?t+"":t,n),BI=Object.defineProperty,$I=(e,t,n)=>t in e?BI(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,ls=(e,t,n)=>$I(e,typeof t!="symbol"?t+"":t,n),fw=class sh{constructor(t,n={}){ls(this,"name"),ls(this,"level"),ls(this,"colors"),ls(this,"timestamps"),this.name=t,this.level=n.level??cn.INFO,this.colors=n.colors??this.isNodeEnvironment(),this.timestamps=n.timestamps??!0}debug(t,n){this.isDebugEnabled()&&this.log("DEBUG",t,n)}info(t,n){this.isInfoEnabled()&&this.log("INFO",t,n)}warn(t,n){this.isWarnEnabled()&&this.log("WARN",t,n)}error(t,n){this.isErrorEnabled()&&(t instanceof Error?this.log("ERROR",t.message,{...n,stack:t.stack}):this.log("ERROR",t,n))}isDebugEnabled(){return this.level<=cn.DEBUG}isInfoEnabled(){return this.level<=cn.INFO}isWarnEnabled(){return this.level<=cn.WARN}isErrorEnabled(){return this.level<=cn.ERROR}log(t,n,r){const o=[];if(this.timestamps&&o.push(new Date().toISOString()),this.colors){const c=sh.COLORS[t];o.push(`${c}${t.padEnd(5)}${sh.COLORS.RESET}`)}else o.push(t.padEnd(5));o.push(`[${this.name}]`),o.push(n);const a=o.join(" "),l=this.getConsoleMethod(t);r&&Object.keys(r).length>0?l(a,r):l(a)}getConsoleMethod(t){switch(t){case"DEBUG":return console.debug.bind(console);case"INFO":return console.info.bind(console);case"WARN":return console.warn.bind(console);case"ERROR":return console.error.bind(console);default:return console.log.bind(console)}}isNodeEnvironment(){var t;return typeof process<"u"&&((t=process.versions)==null?void 0:t.node)!==void 0}};ls(fw,"COLORS",{DEBUG:"\x1B[36m",INFO:"\x1B[32m",WARN:"\x1B[33m",ERROR:"\x1B[31m",RESET:"\x1B[0m"});var UI=fw,ka=null,ic=class{static getLogger(t){const n=typeof t=="string"?t:t.name;if(this.loggers.has(n))return this.loggers.get(n);const r=this.createLazyLogger(n);return this.loggers.set(n,r),r}static configure(t){this.config={...this.config,...t}}static reset(){this.loggers.clear(),this.config={defaultLevel:cn.INFO},ka=null}static createLazyLogger(t){let n=null;const r=()=>(n||(n=this.createLogger(t)),n);return{name:t,level:this.config.defaultLevel||cn.INFO,debug:(o,a)=>r().debug(o,a),info:(o,a)=>r().info(o,a),warn:(o,a)=>r().warn(o,a),error:(o,a)=>r().error(o,a),isDebugEnabled:()=>r().isDebugEnabled(),isInfoEnabled:()=>r().isInfoEnabled(),isWarnEnabled:()=>r().isWarnEnabled(),isErrorEnabled:()=>r().isErrorEnabled()}}static createLogger(t){return ka?ka.getLogger(t):this.config.defaultImplementation?this.config.defaultImplementation(t):new UI(t,{level:this.config.defaultLevel,...this.config.consoleOptions})}};ls(ic,"loggers",new Map);ls(ic,"config",{defaultLevel:cn.INFO});function HI(e){ka=e,ic.reset(),ka=e}function qt(e){return ic.getLogger(e)}var Gs=qt("agentx/DefinitionManager");function Wy(e){return`meta_${e}`}function WI(e){const t=new Date;return{name:e.name,description:e.description,systemPrompt:e.systemPrompt,definition:e,source:"code",createdAt:t,updatedAt:t}}var qI=class{constructor(e){this.repository=e,me(this,"cache",new Map)}register(e){if(this.cache.has(e.name))throw new Error(`Definition already exists: ${e.name}`);this.cache.set(e.name,e);const t=WI(e);this.repository.saveDefinition(t).catch(o=>{Gs.error("Failed to save definition",{name:e.name,error:o})});const n=Wy(e.name),r={imageId:n,type:"meta",definitionName:e.name,parentImageId:null,definition:e,config:{},messages:[],createdAt:new Date};this.repository.saveImage(r).catch(o=>{Gs.error("Failed to save MetaImage",{definitionName:e.name,error:o})}),Gs.info("Definition registered",{name:e.name,metaImageId:n})}get(e){return this.cache.get(e)}list(){return Array.from(this.cache.values())}has(e){return this.cache.has(e)}unregister(e){if(!this.cache.get(e))return!1;this.cache.delete(e),this.repository.deleteDefinition(e).catch(r=>{Gs.error("Failed to delete definition",{name:e,error:r})});const n=Wy(e);return this.repository.deleteImage(n).catch(r=>{Gs.error("Failed to delete MetaImage",{definitionName:e,error:r})}),Gs.info("Definition unregistered",{name:e}),!0}},fu=qt("agentx/ImageManager");function GI(e){return`meta_${e}`}function hu(e){const t=e.definition;return e.type==="meta"?{type:"meta",imageId:e.imageId,definitionName:e.definitionName,definition:t,config:e.config,messages:[],createdAt:e.createdAt}:{type:"derived",imageId:e.imageId,parentImageId:e.parentImageId,definitionName:e.definitionName,definition:t,config:e.config,messages:e.messages,createdAt:e.createdAt}}var KI=class{constructor(e,t,n){me(this,"repository"),me(this,"containerManager"),me(this,"defaultContainerId"),this.repository=e,this.containerManager=t,this.defaultContainerId=n}async get(e){const t=await this.repository.findImageById(e);if(t)return hu(t)}async getMetaImage(e){const t=GI(e),n=await this.repository.findImageById(t);if(!(!n||n.type!=="meta"))return hu(n)}async list(){return(await this.repository.findAllImages()).map(hu)}async listByDefinition(e){return(await this.repository.findAllImages()).filter(r=>r.definitionName===e).map(hu)}async exists(e){return this.repository.imageExists(e)}async delete(e){const t=await this.repository.findImageById(e);return t?t.type==="meta"?(fu.warn("Cannot delete MetaImage directly",{imageId:e}),!1):(await this.repository.deleteImage(e),fu.info("Image deleted",{imageId:e}),!0):!1}async run(e,t){fu.info("Running agent from image",{imageId:e,containerId:t==null?void 0:t.containerId});const n=await this.get(e);if(!n)throw new Error(`Image not found: ${e}`);let r=(t==null?void 0:t.containerId)||this.defaultContainerId;return r||(r=(await this.containerManager.create()).containerId,this.defaultContainerId=r,fu.debug("Auto-created default container",{containerId:r})),this.containerManager.run(n,r)}},pu=qt("agentx/AgentManager"),YI=class{constructor(e){this.containerManager=e}get(e){return this.containerManager.getAgent(e)}has(e){return this.containerManager.hasAgent(e)}list(){return this.containerManager.listAgents()}async destroy(e){pu.debug("Destroying agent",{agentId:e}),await this.containerManager.destroyAgent(e),pu.info("Agent destroyed",{agentId:e})}async destroyAll(){const e=this.containerManager.listAgents();pu.debug("Destroying all agents",{count:e.length}),await this.containerManager.destroyAllAgents(),pu.info("All agents destroyed",{count:e.length})}},Sn=qt("agentx/SessionManager");function hw(){const e=Date.now().toString(36),t=Math.random().toString(36).substring(2,8);return`session_${e}_${t}`}function XI(){const e=Date.now().toString(36),t=Math.random().toString(36).substring(2,8);return`image_${e}_${t}`}var ca=class pw{constructor(t,n,r,o){me(this,"sessionId"),me(this,"userId"),me(this,"imageId"),me(this,"createdAt"),me(this,"_title"),me(this,"_updatedAt"),me(this,"repository"),me(this,"containerManager"),me(this,"defaultContainerId"),this.sessionId=t.sessionId,this.userId=t.userId,this.imageId=t.imageId,this._title=t.title,this.createdAt=t.createdAt.getTime(),this._updatedAt=t.updatedAt.getTime(),this.repository=n,this.containerManager=r,this.defaultContainerId=o}get title(){return this._title}get updatedAt(){return this._updatedAt}async resume(t){Sn.info("Resuming agent from session",{sessionId:this.sessionId,imageId:this.imageId,containerId:t==null?void 0:t.containerId});let n=(t==null?void 0:t.containerId)||this.defaultContainerId;n||(n=(await this.containerManager.create()).containerId,Sn.debug("Auto-created default container for session",{containerId:n,sessionId:this.sessionId}));const r=await this.containerManager.resume(this,n);return this.collect(r),r}collect(t){Sn.debug("Collecting messages from agent",{sessionId:this.sessionId,agentId:t.agentId});const n=this.sessionId,r=this.repository,o=(a,l)=>{const c={messageId:a.id,sessionId:n,role:l,content:a,createdAt:new Date(a.timestamp??Date.now())};r.saveMessage(c).catch(d=>{Sn.error("Failed to persist message",{sessionId:n,messageId:c.messageId,error:d})})};t.on("user_message",a=>o(a.data,"user")),t.on("assistant_message",a=>o(a.data,"assistant")),t.on("tool_call_message",a=>o(a.data,"tool")),t.on("tool_result_message",a=>o(a.data,"tool"))}async getMessages(){return Sn.debug("Getting messages for session",{sessionId:this.sessionId}),(await this.repository.findMessagesBySessionId(this.sessionId)).map(n=>n.content)}async fork(){Sn.info("Forking session",{sessionId:this.sessionId});const t=await this.repository.findImageById(this.imageId);if(!t)throw new Error(`Image not found: ${this.imageId}`);const n=XI(),r={imageId:n,type:"derived",definitionName:t.definitionName,parentImageId:t.imageId,definition:t.definition,config:t.config,messages:[...t.messages],createdAt:new Date};await this.repository.saveImage(r);const o=hw(),a=new Date,l={sessionId:o,userId:this.userId,imageId:n,title:this._title?`Fork of ${this._title}`:null,createdAt:a,updatedAt:a};return await this.repository.saveSession(l),Sn.info("Session forked",{originalSessionId:this.sessionId,newSessionId:o,newImageId:n}),new pw(l,this.repository,this.containerManager,this.defaultContainerId)}async setTitle(t){Sn.debug("Setting session title",{sessionId:this.sessionId,title:t});const n=new Date;await this.repository.saveSession({sessionId:this.sessionId,userId:this.userId,imageId:this.imageId,title:t,createdAt:new Date(this.createdAt),updatedAt:n}),this._title=t,this._updatedAt=n.getTime(),Sn.info("Session title updated",{sessionId:this.sessionId,title:t})}},QI=class{constructor(e,t,n){me(this,"repository"),me(this,"containerManager"),me(this,"defaultContainerId"),this.repository=e,this.containerManager=t,this.defaultContainerId=n}async create(e,t){const n=hw(),r=new Date,o={sessionId:n,userId:t,imageId:e,title:null,createdAt:r,updatedAt:r};return await this.repository.saveSession(o),Sn.info("Session created",{sessionId:n,imageId:e,userId:t}),new ca(o,this.repository,this.containerManager,this.defaultContainerId)}async get(e){const t=await this.repository.findSessionById(e);if(t)return new ca(t,this.repository,this.containerManager,this.defaultContainerId)}async has(e){return this.repository.sessionExists(e)}async list(){return(await this.repository.findAllSessions()).map(t=>new ca(t,this.repository,this.containerManager,this.defaultContainerId))}async listByImage(e){return(await this.repository.findSessionsByImageId(e)).map(n=>new ca(n,this.repository,this.containerManager,this.defaultContainerId))}async listByUser(e){return(await this.repository.findSessionsByUserId(e)).map(n=>new ca(n,this.repository,this.containerManager,this.defaultContainerId))}async destroy(e){await this.repository.deleteSession(e),Sn.info("Session destroyed",{sessionId:e})}async destroyByImage(e){await this.repository.deleteSessionsByImageId(e),Sn.info("Sessions destroyed by image",{imageId:e})}async destroyAll(){const e=await this.repository.findAllSessions();for(const t of e)await this.repository.deleteSession(t.sessionId);Sn.info("All sessions destroyed")}},mu=qt("agentx/ErrorManager"),JI=class{constructor(){me(this,"handlers",new Set)}handle(e,t,n){this.logError(e,t);for(const r of this.handlers)try{r.handle(e,t,n)}catch(o){mu.error("ErrorHandler failed",{error:o})}}addHandler(e){return this.handlers.add(e),()=>{this.handlers.delete(e)}}removeHandler(e){this.handlers.delete(e)}logError(e,t){const n=`[${e}] ${t.category}/${t.code}`;t.severity==="fatal"?mu.error(`${n}: ${t.message}`,{error:t}):t.severity==="error"?mu.error(`${n}: ${t.message}`):mu.warn(`${n}: ${t.message}`)}},ZI=class extends Error{constructor(e,t,n){super(t),this.code=e,this.details=n,this.name="ApiError"}};function mw(e){return kI.create({prefixUrl:e.baseUrl.replace(/\/+$/,""),headers:e.headers,timeout:e.timeout||3e4,hooks:{afterResponse:[async(t,n,r)=>{var o,a,l;if(!r.ok){const c=await r.json().catch(()=>({}));throw new ZI(((o=c.error)==null?void 0:o.code)||"UNKNOWN_ERROR",((a=c.error)==null?void 0:a.message)||`Request failed: ${r.status}`,(l=c.error)==null?void 0:l.details)}return r}]}})}var qy=qt("core/AgentStateMachine"),eT=class{constructor(){me(this,"_state","idle"),me(this,"handlers",new Set)}get state(){return this._state}process(e){const t=this._state,n=this.mapEventToState(e);n!==null&&t!==n&&(this._state=n,qy.debug("State transition",{eventType:e.type,from:t,to:n}),this.notifyHandlers({prev:t,current:n}))}onStateChange(e){return this.handlers.add(e),()=>{this.handlers.delete(e)}}reset(){this._state,this._state="idle",this.handlers.clear()}mapEventToState(e){switch(e.type){case"agent_initializing":return"initializing";case"agent_ready":return"idle";case"agent_destroyed":return"idle";case"conversation_queued":return"queued";case"conversation_start":return"conversation_active";case"conversation_thinking":return"thinking";case"conversation_responding":return"responding";case"conversation_end":return"idle";case"conversation_interrupted":return"idle";case"tool_planned":return"planning_tool";case"tool_executing":return"awaiting_tool_result";case"tool_completed":return"responding";case"tool_failed":return"responding";case"error_occurred":return"idle";default:return null}}notifyHandlers(e){for(const t of this.handlers)try{t(e)}catch(n){qy.error("State change handler error",{from:e.prev,to:e.current,error:n})}}},Ks=qt("core/AgentEventBus"),tT=class{constructor(){me(this,"subject",new dw),me(this,"typeSubscriptions",new Map),me(this,"globalSubscriptions",[]),me(this,"nextId",0),me(this,"isDestroyed",!1),me(this,"producerView",null),me(this,"consumerView",null)}emit(e){if(this.isDestroyed){Ks.warn("Emit called on destroyed EventBus",{eventType:e.type});return}this.subject.next(e)}emitBatch(e){for(const t of e)this.emit(t)}on(e,t,n={}){if(this.isDestroyed)return Ks.warn("Subscribe called on destroyed EventBus"),()=>{};const r=Array.isArray(e)?e:[e],o=[];for(const a of r){const l=this.subscribeToType(a,t,n);o.push(l)}return()=>o.forEach(a=>a())}onAny(e,t={}){return this.isDestroyed?(Ks.warn("Subscribe called on destroyed EventBus"),()=>{}):this.subscribeGlobal(e,t)}once(e,t){return this.on(e,t,{once:!0})}asConsumer(){return this.consumerView||(this.consumerView={on:this.on.bind(this),onAny:this.onAny.bind(this),once:this.once.bind(this)}),this.consumerView}asProducer(){return this.producerView||(this.producerView={emit:this.emit.bind(this),emitBatch:this.emitBatch.bind(this)}),this.producerView}destroy(){if(!this.isDestroyed){this.isDestroyed=!0;for(const e of this.typeSubscriptions.values())for(const t of e)t.unsubscribe();this.typeSubscriptions.clear();for(const e of this.globalSubscriptions)e.unsubscribe();this.globalSubscriptions.length=0,this.subject.complete(),Ks.debug("EventBus destroyed")}}subscribeToType(e,t,n){const{filter:r,priority:o=0,once:a=!1}=n,l=this.nextId++;let c=this.subject.pipe(tf(y=>y.type===e));r&&(c=c.pipe(tf(r))),a&&(c=c.pipe(Hy(1)));const d=c.subscribe({next:y=>{this.executeWithPriority(e,y,t,l)}}),f=()=>{d.unsubscribe();const y=this.typeSubscriptions.get(e);if(y){const v=y.findIndex(b=>b.id===l);v!==-1&&y.splice(v,1)}};this.typeSubscriptions.has(e)||this.typeSubscriptions.set(e,[]);const p={id:l,priority:o,handler:t,unsubscribe:f},m=this.typeSubscriptions.get(e);return m.push(p),m.sort((y,v)=>v.priority-y.priority),f}subscribeGlobal(e,t){const{filter:n,priority:r=0,once:o=!1}=t,a=this.nextId++;let l=this.subject.asObservable();n&&(l=l.pipe(tf(n))),o&&(l=l.pipe(Hy(1)));const c=l.subscribe({next:p=>{this.executeGlobalWithPriority(p,e,a)}}),d=()=>{c.unsubscribe();const p=this.globalSubscriptions.findIndex(m=>m.id===a);p!==-1&&this.globalSubscriptions.splice(p,1)},f={id:a,priority:r,handler:e,unsubscribe:d};return this.globalSubscriptions.push(f),this.globalSubscriptions.sort((p,m)=>m.priority-p.priority),d}executeWithPriority(e,t,n,r){if((this.typeSubscriptions.get(e)||[]).find(l=>l.id===r))try{n(t)}catch(l){Ks.error("Event handler error",{eventType:e,error:l})}}executeGlobalWithPriority(e,t,n){if(this.globalSubscriptions.find(o=>o.id===n))try{t(e)}catch(o){Ks.error("Global event handler error",{eventType:e.type,error:o})}}},nT=class{constructor(e){this.agentId=e}classify(e){const t=e instanceof Error?e:new Error(String(e)),n=t.message;return n.includes("rate limit")||n.includes("429")?this.create("llm","RATE_LIMITED",n,!0,t):n.includes("api key")||n.includes("401")||n.includes("unauthorized")?this.create("llm","INVALID_API_KEY",n,!1,t):n.includes("context")&&n.includes("long")?this.create("llm","CONTEXT_TOO_LONG",n,!0,t):n.includes("overloaded")||n.includes("503")?this.create("llm","OVERLOADED",n,!0,t):n.includes("timeout")||n.includes("ETIMEDOUT")?this.create("network","TIMEOUT",n,!0,t):n.includes("ECONNREFUSED")||n.includes("connection")?this.create("network","CONNECTION_FAILED",n,!0,t):n.includes("network")||n.includes("fetch")?this.create("network","CONNECTION_FAILED",n,!0,t):n.includes("driver")?this.create("driver","RECEIVE_FAILED",n,!0,t):this.create("system","UNKNOWN",n,!0,t)}create(e,t,n,r,o){return{category:e,code:t,message:n,severity:r?"error":"fatal",recoverable:r,cause:o}}createEvent(e){return{type:"error",uuid:`${Date.now()}_${Math.random().toString(36).substring(2,9)}`,agentId:this.agentId,timestamp:Date.now(),data:{error:e}}}},rT=class{constructor(){me(this,"middlewares",[])}use(e){return this.middlewares.push(e),()=>{const t=this.middlewares.indexOf(e);t!==-1&&this.middlewares.splice(t,1)}}async execute(e,t){let n=0;const r=async o=>{if(n<this.middlewares.length){const a=this.middlewares[n++];await a(o,r)}else await t(o)};await r(e)}clear(){this.middlewares.length=0}get size(){return this.middlewares.length}},iT=qt("core/InterceptorChain"),sT=class{constructor(e){me(this,"interceptors",[]),me(this,"agentId"),this.agentId=e}intercept(e){return this.interceptors.push(e),()=>{const t=this.interceptors.indexOf(e);t!==-1&&this.interceptors.splice(t,1)}}execute(e,t){let n=0;const r=o=>{if(n<this.interceptors.length){const a=this.interceptors[n++];try{a(o,r)}catch(l){iT.error("Interceptor error",{agentId:this.agentId,eventType:o.type,interceptorIndex:n-1,error:l}),r(o)}}else t(o)};r(e)}clear(){this.interceptors.length=0}get size(){return this.interceptors.length}},oT={onMessageStart:"message_start",onMessageDelta:"message_delta",onMessageStop:"message_stop",onTextContentBlockStart:"text_content_block_start",onTextDelta:"text_delta",onTextContentBlockStop:"text_content_block_stop",onToolUseContentBlockStart:"tool_use_content_block_start",onInputJsonDelta:"input_json_delta",onToolUseContentBlockStop:"tool_use_content_block_stop",onToolCall:"tool_call",onToolResult:"tool_result",onUserMessage:"user_message",onAssistantMessage:"assistant_message",onToolCallMessage:"tool_call_message",onToolResultMessage:"tool_result_message",onError:"error",onTurnRequest:"turn_request",onTurnResponse:"turn_response"};function aT(e){const t={};for(const[n,r]of Object.entries(oT)){const o=e[n];o&&(t[r]=o)}return t}var zn=qt("core/AgentInstance"),Gy=class{constructor(e,t,n,r,o){me(this,"agentId"),me(this,"definition"),me(this,"context"),me(this,"createdAt"),me(this,"sandbox"),me(this,"_lifecycle","running"),me(this,"engine"),me(this,"driver"),me(this,"stateMachine",new eT),me(this,"eventBus",new tT),me(this,"errorClassifier"),me(this,"middlewareChain",new rT),me(this,"interceptorChain"),me(this,"readyHandlers",new Set),me(this,"destroyHandlers",new Set),this.agentId=t.agentId,this.definition=e,this.context=t,this.engine=n,this.createdAt=t.createdAt,this.sandbox=o,this.driver=r,this.errorClassifier=new nT(this.agentId),this.interceptorChain=new sT(this.agentId),zn.debug("AgentInstance created",{agentId:this.agentId,definitionName:e.name,driverName:this.driver.name})}get lifecycle(){return this._lifecycle}get state(){return this.stateMachine.state}async receive(e){if(this._lifecycle==="destroyed"){zn.warn("Receive called on destroyed agent",{agentId:this.agentId});const r=this.errorClassifier.create("system","AGENT_DESTROYED","Agent has been destroyed",!1),o=this.errorClassifier.createEvent(r);throw this.notifyHandlers(o),new Error("[Agent] Agent has been destroyed")}if(this.state!=="idle"){zn.warn("Receive called while agent is busy",{agentId:this.agentId,currentState:this.state});const r=this.errorClassifier.create("system","AGENT_BUSY",`Agent is busy (state: ${this.state}), please wait for current operation to complete`,!1),o=this.errorClassifier.createEvent(r);throw this.notifyHandlers(o),new Error(`[Agent] Agent is busy (state: ${this.state})`)}const t=typeof e=="string"?{id:`msg_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,role:"user",subtype:"user",content:e,timestamp:Date.now()}:e;zn.debug("Receiving message",{agentId:this.agentId,messageId:t.id});const n={uuid:`evt_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,type:"user_message",agentId:this.agentId,timestamp:Date.now(),data:t};this.presentOutput(n),this.notifyHandlers(n),await this.executeMiddlewareChain(t)}async executeMiddlewareChain(e){await this.middlewareChain.execute(e,t=>this.doReceive(t))}processStreamEvent(e){const t=this.engine.process(this.agentId,e);for(const n of t)this.presentOutput(n);for(const n of t)this.notifyHandlers(n)}async doReceive(e){try{zn.debug("Processing message through driver",{agentId:this.agentId,messageId:e.id});const t={type:"conversation_queued",uuid:`${Date.now()}_${Math.random().toString(36).substring(2,9)}`,agentId:this.agentId,timestamp:Date.now(),data:{userMessage:e}};this.notifyHandlers(t);const n=this.driver.receive(e);for await(const r of n)this.processStreamEvent(r);zn.debug("Message processing completed",{agentId:this.agentId,messageId:e.id})}catch(t){const n=this.errorClassifier.classify(t),r=this.errorClassifier.createEvent(n);throw zn.error("Message processing failed",{agentId:this.agentId,messageId:e.id,errorCategory:n.category,errorCode:n.code,error:t}),this.notifyHandlers(r),t}}presentOutput(e){}on(e,t){if(typeof e=="function")return this.eventBus.onAny(e);if(this.isEventHandlerMap(e)){const o=[];for(const[a,l]of Object.entries(e))l&&o.push(this.eventBus.on(a,l));return()=>{for(const a of o)a()}}const n=Array.isArray(e)?e:[e],r=t;return this.eventBus.on(n,r)}isEventHandlerMap(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;const t=Object.keys(e);return t.length===0?!1:t.every(n=>{const r=e[n];return r===void 0||typeof r=="function"})}onStateChange(e){return this.stateMachine.onStateChange(e)}react(e){const t=aT(e);return this.on(t)}onReady(e){if(this._lifecycle==="running")try{e()}catch(t){zn.error("onReady handler error",{agentId:this.agentId,error:t})}return this.readyHandlers.add(e),()=>{this.readyHandlers.delete(e)}}onDestroy(e){return this.destroyHandlers.add(e),()=>{this.destroyHandlers.delete(e)}}use(e){return this.middlewareChain.use(e)}intercept(e){return this.interceptorChain.intercept(e)}interrupt(){zn.debug("User interrupt requested",{agentId:this.agentId,currentState:this.state}),this.driver.interrupt()}async destroy(){zn.debug("Destroying agent",{agentId:this.agentId});for(const e of this.destroyHandlers)try{e()}catch(t){zn.error("onDestroy handler error",{agentId:this.agentId,error:t})}this._lifecycle="destroyed",this.stateMachine.reset(),this.eventBus.destroy(),this.readyHandlers.clear(),this.destroyHandlers.clear(),this.middlewareChain.clear(),this.interceptorChain.clear(),this.engine.clearState(this.agentId),zn.info("Agent destroyed",{agentId:this.agentId})}notifyHandlers(e){JC(e)&&this.stateMachine.process(e),this.executeInterceptorChain(e)}executeInterceptorChain(e){this.interceptorChain.execute(e,t=>this.eventBus.emit(t))}getEventConsumer(){return this.eventBus.asConsumer()}},lT=class{constructor(){me(this,"states",new Map)}get(e){return this.states.get(e)}set(e,t){this.states.set(e,t)}delete(e){this.states.delete(e)}has(e){return this.states.has(e)}clear(){this.states.clear()}get size(){return this.states.size}keys(){return this.states.keys()}};qt("engine/Mealy");function uT(e){return(t,n)=>{const r={},o=[];for(const a in e){const l=e[a],c=t[a],[d,f]=l(c,n);r[a]=d,o.push(...f)}return[r,o]}}function cT(e){return()=>{const t={};for(const n in e)t[n]=e[n]();return t}}function oh(){return{currentMessageId:null,messageStartTime:null,pendingContents:{},pendingToolCalls:{}}}function hs(){return`msg_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}var dT=(e,t)=>{switch(t.type){case"message_start":return fT(e,t);case"text_delta":return hT(e,t);case"tool_use_content_block_start":return pT(e,t);case"input_json_delta":return mT(e,t);case"tool_use_content_block_stop":return gT(e,t);case"tool_result":return yT(e,t);case"message_stop":return vT(e,t);default:return[e,[]]}};function fT(e,t){return[{...e,currentMessageId:hs(),messageStartTime:t.timestamp,pendingContents:{}},[]]}function hT(e,t){const r=e.pendingContents[0],o=(r==null?void 0:r.type)==="text"?{...r,textDeltas:[...r.textDeltas||[],t.data.text]}:{type:"text",index:0,textDeltas:[t.data.text]};return[{...e,pendingContents:{...e.pendingContents,0:o}},[]]}function pT(e,t){const r={type:"tool_use",index:1,toolId:t.data.id,toolName:t.data.name,toolInputJson:""};return[{...e,pendingContents:{...e.pendingContents,1:r}},[]]}function mT(e,t){const r=e.pendingContents[1];if(!r||r.type!=="tool_use")return[e,[]];const o={...r,toolInputJson:(r.toolInputJson||"")+t.data.partialJson};return[{...e,pendingContents:{...e.pendingContents,1:o}},[]]}function gT(e,t){const r=e.pendingContents[1];if(!r||r.type!=="tool_use")return[e,[]];let o={};try{o=r.toolInputJson?JSON.parse(r.toolInputJson):{}}catch{o={}}const a=[],l=r.toolId,c=r.toolName,d={type:"tool_call",uuid:hs(),agentId:t.agentId,timestamp:Date.now(),data:{id:l,name:c,input:o}};a.push(d);const f={type:"tool-call",id:l,name:c,input:o},p={id:hs(),role:"assistant",subtype:"tool-call",toolCall:f,timestamp:Date.now()},m={type:"tool_call_message",uuid:hs(),agentId:t.agentId,timestamp:Date.now(),data:p};a.push(m);const{[1]:y,...v}=e.pendingContents;return[{...e,pendingContents:v,pendingToolCalls:{...e.pendingToolCalls,[l]:{id:l,name:c}}},a]}function yT(e,t){const{toolId:n,content:r,isError:o}=t.data,a=e.pendingToolCalls[n],l=(a==null?void 0:a.name)||"unknown",c={type:"tool-result",id:n,name:l,output:{type:o?"error-text":"text",value:typeof r=="string"?r:JSON.stringify(r)}},d={id:hs(),role:"tool",subtype:"tool-result",toolResult:c,toolCallId:n,timestamp:Date.now()},f={type:"tool_result_message",uuid:hs(),agentId:t.agentId,timestamp:Date.now(),data:d},{[n]:p,...m}=e.pendingToolCalls;return[{...e,pendingToolCalls:m},[f]]}function vT(e,t){if(!e.currentMessageId)return[e,[]];const n=[],r=Object.values(e.pendingContents).sort((f,p)=>f.index-p.index);for(const f of r)f.type==="text"&&f.textDeltas&&n.push(f.textDeltas.join(""));const o=n.join(""),a=t.data.stopReason;if(!o||o.trim().length===0){const f=a==="tool_use";return[{...oh(),pendingToolCalls:f?e.pendingToolCalls:{}},[]]}const l={id:e.currentMessageId,role:"assistant",subtype:"assistant",content:o,timestamp:e.messageStartTime||Date.now(),usage:void 0},c={type:"assistant_message",uuid:hs(),agentId:t.agentId,timestamp:Date.now(),data:l},d=a==="tool_use";return[{...oh(),pendingToolCalls:d?e.pendingToolCalls:{}},[c]]}var Ma=qt("engine/stateEventProcessor");function xT(){return{}}function uo(){return`state_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}var wT=(e,t)=>{switch(Ma.debug(`[Stream Event] ${t.type}`,{context:e,eventData:"data"in t?t.data:void 0}),t.type){case"message_start":return bT(e,t);case"message_delta":return ST(e);case"message_stop":return kT(e,t);case"text_content_block_start":return ET(e,t);case"tool_use_content_block_start":return CT(e,t);case"tool_use_content_block_stop":return IT(e);case"tool_call":return TT(e);case"interrupted":return _T(e,t);default:return Ma.debug(`[Stream Event] ${t.type} (unhandled)`),[e,[]]}};function bT(e,t){const n={type:"conversation_start",uuid:uo(),agentId:t.agentId,timestamp:t.timestamp,transition:{reason:"conversation_started",trigger:"message_start"},data:{userMessage:{}}};return[e,[n]]}function ST(e,t){return[e,[]]}function kT(e,t){const n=t.data.stopReason;if(Ma.debug("message_stop received",{stopReason:n}),n==="tool_use")return Ma.debug("Skipping conversation_end (tool_use in progress)"),[e,[]];const r={type:"conversation_end",uuid:uo(),agentId:t.agentId,timestamp:t.timestamp,transition:{reason:"conversation_completed",trigger:"message_stop"},data:{assistantMessage:{},durationMs:0,durationApiMs:0,numTurns:0,result:"completed",totalCostUsd:0,usage:{input:0,output:0}}};return[e,[r]]}function ET(e,t){const n={type:"conversation_responding",uuid:uo(),agentId:t.agentId,timestamp:Date.now(),transition:{reason:"assistant_responding",trigger:"text_content_block_start"},data:{}};return[e,[n]]}function CT(e,t){const n=[],r={type:"tool_planned",uuid:uo(),agentId:t.agentId,timestamp:t.timestamp,data:{id:t.data.id,name:t.data.name,input:{}}};n.push(r);const o={type:"tool_executing",uuid:uo(),agentId:t.agentId,timestamp:t.timestamp,transition:{reason:"tool_planning_started",trigger:"tool_use_content_block_start"},data:{}};return n.push(o),[e,n]}function IT(e,t){return[e,[]]}function TT(e,t){return[e,[]]}function _T(e,t){Ma.debug("interrupted event received",{reason:t.data.reason});const n={type:"conversation_interrupted",uuid:uo(),agentId:t.agentId,timestamp:t.timestamp,transition:{reason:t.data.reason,trigger:"interrupted"},data:{reason:t.data.reason}};return[e,[n]]}function PT(){return{pendingTurn:null,costPerInputToken:3e-6,costPerOutputToken:15e-6}}function Fu(){return`turn_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function AT(e,t,n){const r=e.input*t,o=e.output*n;return r+o}var RT=(e,t)=>{switch(t.type){case"user_message":return NT(e,t);case"message_stop":return jT(e,t);case"assistant_message":return[e,[]];default:return[e,[]]}};function NT(e,t){const n=Fu(),r={turnId:n,userMessage:t.data,requestedAt:t.timestamp},o={type:"turn_request",uuid:Fu(),agentId:t.agentId,timestamp:Date.now(),turnId:n,data:{userMessage:t.data,requestedAt:t.timestamp}};return[{...e,pendingTurn:r},[o]]}function jT(e,t){if(!e.pendingTurn)return[e,[]];const n=t.data.stopReason;return n==="end_turn"||n==="max_tokens"||n==="stop_sequence"?MT(e,t.agentId,t.timestamp):[e,[]]}function MT(e,t,n){if(!e.pendingTurn)return[e,[]];const{turnId:r,requestedAt:o}=e.pendingTurn,a=n-o,l={input:0,output:0},c=AT(l,e.costPerInputToken,e.costPerOutputToken),d={type:"turn_response",uuid:Fu(),agentId:t,timestamp:Date.now(),turnId:r,data:{assistantMessage:{id:Fu(),role:"assistant",subtype:"assistant",content:"",timestamp:n},respondedAt:n,durationMs:a,usage:l,costUsd:c}};return[{...e,pendingTurn:null},[d]]}var Ky=uT({messageAssembler:dT,stateEventProcessor:wT,turnTracker:RT}),DT=cT({messageAssembler:oh,stateEventProcessor:xT,turnTracker:PT}),da=qt("engine/AgentEngine"),LT=class{constructor(){me(this,"store"),this.store=new lT,da.debug("AgentEngine initialized")}process(e,t){const n=t.type||"unknown";da.debug("Processing event",{agentId:e,eventType:n});const r=!this.store.has(e);let o=this.store.get(e)??DT();r&&da.debug("Created initial state for agent",{agentId:e});const a=[];a.push(t);const[l,c]=Ky(o,t);o=l;for(const d of c){a.push(d);const[f,p]=this.processChained(o,d);o=f,a.push(...p)}return this.store.set(e,o),c.length>0&&da.debug("Produced outputs",{agentId:e,inputEvent:n,outputCount:a.length,processorOutputs:c.length}),a}processChained(e,t){const[n,r]=Ky(e,t);if(r.length===0)return[n,[]];const o=[...r];let a=n;for(const l of r){const[c,d]=this.processChained(a,l);a=c,o.push(...d)}return[a,o]}clearState(e){da.debug("Clearing state",{agentId:e}),this.store.delete(e)}hasState(e){return this.store.has(e)}},sr=qt("agentx/ContainerManager");function zT(){const e=Date.now().toString(36),t=Math.random().toString(36).substring(2,8);return`container_${e}_${t}`}function Yy(){const e=Date.now().toString(36),t=Math.random().toString(36).substring(2,8);return`agent_${e}_${t}`}var OT=class{constructor(e,t){me(this,"agents",new Map),me(this,"engine"),me(this,"runtime"),me(this,"repository"),this.runtime=e,this.repository=t,this.engine=new LT}async create(e){const t=zT(),n=Date.now(),r={containerId:t,createdAt:n,updatedAt:n,config:e};return await this.repository.saveContainer(r),sr.info("Container created",{containerId:t}),r}async get(e){return this.repository.findContainerById(e)}async list(){return this.repository.findAllContainers()}async delete(e){return await this.repository.containerExists(e)?(await this.repository.deleteContainer(e),sr.info("Container deleted",{containerId:e}),!0):!1}async exists(e){return this.repository.containerExists(e)}async run(e,t){if(sr.info("Running agent from image",{imageId:e.imageId,containerId:t}),!await this.repository.findContainerById(t))throw new Error(`Container not found: ${t}`);let r;this.runtime.agentIdResolver?r=await this.runtime.agentIdResolver.resolveForRun(e.imageId,t):r=Yy();const o={agentId:r,createdAt:Date.now()},a=this.runtime.createSandbox(t),l=this.runtime.createDriver(e.definition,o,a),c=new Gy(e.definition,o,this.engine,l,a);return this.agents.set(r,c),sr.info("Agent started",{agentId:r,imageId:e.imageId,containerId:t,definitionName:e.definition.name}),c}async resume(e,t){if(sr.info("Resuming agent from session",{sessionId:e.sessionId,imageId:e.imageId,containerId:t}),!await this.repository.findContainerById(t))throw new Error(`Container not found: ${t}`);const r=await this.repository.findImageById(e.imageId);if(!r)throw new Error(`Image not found: ${e.imageId}`);let o;this.runtime.agentIdResolver?o=await this.runtime.agentIdResolver.resolveForResume(e.sessionId,t):o=Yy();const a={agentId:o,createdAt:Date.now()},l=this.runtime.createSandbox(t),c=r.definition,d=this.runtime.createDriver(c,a,l),f=new Gy(c,a,this.engine,d,l);return this.agents.set(o,f),sr.info("Agent resumed",{agentId:o,sessionId:e.sessionId,imageId:e.imageId,containerId:t}),f}async destroyAgent(e){const t=this.agents.get(e);if(!t){sr.warn("Agent not found for destroy",{agentId:e});return}sr.debug("Destroying agent",{agentId:e}),await t.destroy(),this.agents.delete(e),sr.info("Agent destroyed",{agentId:e})}getAgent(e){return this.agents.get(e)}hasAgent(e){return this.agents.has(e)}listAgents(){return Array.from(this.agents.values())}async destroyAllAgents(){const e=Array.from(this.agents.keys());sr.debug("Destroying all agents",{count:e.length}),await Promise.all(e.map(t=>this.destroyAgent(t))),sr.info("All agents destroyed",{count:e.length})}},Xy=qt("agentx/AgentX");function FT(e,t){if(Xy.info("Creating AgentX instance",{runtime:e.name}),!e.repository)throw new Error("Runtime must have a repository for persistence");const n=e.repository,r=new OT(e,n),o=new JI,a=new qI(n),l=new YI(r),c=new KI(n,r,t==null?void 0:t.containerId),d=new QI(n,r,t==null?void 0:t.containerId);return Xy.debug("AgentX instance created",{runtime:e.name}),{mode:"local",containers:r,definitions:a,images:c,agents:l,sessions:d,errors:o}}var VT=class{constructor(e,t,n={}){this.serverUrl=e,this.agentId=t,this.sseParams=n,me(this,"eventSource",null),me(this,"messageQueue",[]),me(this,"activeIterators",new Set),me(this,"isDone",!1)}connect(){if(this.eventSource)return;let e=`${this.serverUrl}/agents/${this.agentId}/sse`;if(Object.keys(this.sseParams).length>0){const r=new URLSearchParams(this.sseParams);e+=`?${r.toString()}`}this.eventSource=new EventSource(e);const t=r=>{try{const o=JSON.parse(r.data);if(this.activeIterators.size>0){const a=this.activeIterators.values().next().value;a&&(this.activeIterators.delete(a),a.resolve({value:o,done:!1}))}else this.messageQueue.push(o)}catch{}},n=()=>{var r;this.isDone=!0,(r=this.eventSource)==null||r.close(),this.eventSource=null;for(const o of this.activeIterators)o.reject(new Error("SSE connection error"));this.activeIterators.clear()};for(const r of Kx)this.eventSource.addEventListener(r,t);this.eventSource.addEventListener("error",t),this.eventSource.onmessage=t,this.eventSource.onerror=n}createIterator(){const e=this;return{[Symbol.asyncIterator](){let t=!1;return{async next(){if(e.messageQueue.length>0){const n=e.messageQueue.shift();return n.type==="message_stop"&&n.data.stopReason!=="tool_use"&&(t=!0),{value:n,done:!1}}return t?{done:!0,value:void 0}:e.isDone?{done:!0,value:void 0}:new Promise((n,r)=>{const a={resolve:l=>{l.done||l.value.type==="message_stop"&&l.value.data.stopReason!=="tool_use"&&(t=!0),n(l)},reject:r};e.activeIterators.add(a)})},async return(){return{done:!0,value:void 0}}}}}}close(){this.isDone=!0,this.eventSource&&(this.eventSource.close(),this.eventSource=null);for(const e of this.activeIterators)e.reject(new Error("Connection closed"));this.activeIterators.clear(),this.messageQueue=[]}};function BT(e){const{serverUrl:t,agentId:n,headers:r={},sseParams:o={}}=e;let a=null;return{name:"SSEDriver",async*receive(l){var f;a||(a=new VT(t,n,o),a.connect());const c=`${t}/agents/${n}/messages`,d=await fetch(c,{method:"POST",headers:{"Content-Type":"application/json",...r},body:JSON.stringify({content:(typeof l.content=="string",l.content)})});if(!d.ok){const p=await d.json().catch(()=>({}));throw new Error(((f=p.error)==null?void 0:f.message)||`HTTP ${d.status}`)}yield*a.createIterator()},interrupt(){const l=`${t}/agents/${n}/interrupt`;fetch(l,{method:"POST",headers:{"Content-Type":"application/json",...r}}).catch(()=>{})}}}var Qy=qt("agentx/RemoteRepository"),$T=class{constructor(e){me(this,"client"),this.client=mw({baseUrl:e.serverUrl,headers:e.headers}),Qy.debug("RemoteRepository created",{serverUrl:e.serverUrl})}async saveDefinition(e){await this.client.put(`definitions/${e.name}`,{json:e})}async findDefinitionByName(e){try{const t=await this.client.get(`definitions/${e}`).json();return this.parseDefinitionRecord(t)}catch(t){if(this.isNotFound(t))return null;throw t}}async findAllDefinitions(){return(await this.client.get("definitions").json()).map(t=>this.parseDefinitionRecord(t))}async deleteDefinition(e){await this.client.delete(`definitions/${e}`)}async definitionExists(e){try{return await this.client.head(`definitions/${e}`),!0}catch{return!1}}async saveImage(e){await this.client.put(`images/${e.imageId}`,{json:e})}async findImageById(e){try{const t=await this.client.get(`images/${e}`).json();return this.parseImageRecord(t)}catch(t){if(this.isNotFound(t))return null;throw t}}async findAllImages(){return(await this.client.get("images").json()).map(t=>this.parseImageRecord(t))}async deleteImage(e){await this.client.delete(`images/${e}`)}async imageExists(e){try{return await this.client.head(`images/${e}`),!0}catch{return!1}}async saveSession(e){await this.client.put(`sessions/${e.sessionId}`,{json:e})}async findSessionById(e){try{const t=await this.client.get(`sessions/${e}`).json();return this.parseSessionRecord(t)}catch(t){if(this.isNotFound(t))return null;throw t}}async findSessionsByImageId(e){return(await this.client.get(`images/${e}/sessions`).json()).map(n=>this.parseSessionRecord(n))}async findSessionsByUserId(e){return(await this.client.get(`users/${e}/sessions`).json()).map(n=>this.parseSessionRecord(n))}async findAllSessions(){return(await this.client.get("sessions").json()).map(t=>this.parseSessionRecord(t))}async deleteSession(e){await this.client.delete(`sessions/${e}`)}async deleteSessionsByImageId(e){await this.client.delete(`images/${e}/sessions`)}async sessionExists(e){try{return await this.client.head(`sessions/${e}`),!0}catch{return!1}}async saveMessage(e){Qy.debug("saveMessage called (noop in browser)")}async findMessageById(e){try{const t=await this.client.get(`messages/${e}`).json();return this.parseMessageRecord(t)}catch(t){if(this.isNotFound(t))return null;throw t}}async findMessagesBySessionId(e){return(await this.client.get(`sessions/${e}/messages`).json()).map(n=>this.parseMessageRecord(n))}async deleteMessage(e){await this.client.delete(`messages/${e}`)}async deleteMessagesBySessionId(e){await this.client.delete(`sessions/${e}/messages`)}async countMessagesBySessionId(e){return(await this.client.get(`sessions/${e}/messages/count`).json()).count}async saveContainer(e){await this.client.put(`containers/${e.containerId}`,{json:e})}async findContainerById(e){try{const t=await this.client.get(`containers/${e}`).json();return this.parseContainerRecord(t)}catch(t){if(this.isNotFound(t))return null;throw t}}async findAllContainers(){return(await this.client.get("containers").json()).map(t=>this.parseContainerRecord(t))}async deleteContainer(e){await this.client.delete(`containers/${e}`)}async containerExists(e){try{return await this.client.head(`containers/${e}`),!0}catch{return!1}}isNotFound(e){var t;return((t=e==null?void 0:e.response)==null?void 0:t.status)===404}parseDefinitionRecord(e){return{...e,createdAt:new Date(e.createdAt),updatedAt:new Date(e.updatedAt)}}parseImageRecord(e){return{...e,createdAt:new Date(e.createdAt)}}parseSessionRecord(e){return{...e,createdAt:new Date(e.createdAt),updatedAt:new Date(e.updatedAt)}}parseMessageRecord(e){return{...e,createdAt:new Date(e.createdAt)}}parseContainerRecord(e){return{...e}}},Jh=class ba{constructor(t,n={}){me(this,"name"),me(this,"level"),me(this,"collapsed"),this.name=t,this.level=n.level??cn.INFO,this.collapsed=n.collapsed??!0}debug(t,n){this.isDebugEnabled()&&this.log("DEBUG",t,n)}info(t,n){this.isInfoEnabled()&&this.log("INFO",t,n)}warn(t,n){this.isWarnEnabled()&&this.log("WARN",t,n)}error(t,n){this.isErrorEnabled()&&(t instanceof Error?this.log("ERROR",t.message,{...n,stack:t.stack}):this.log("ERROR",t,n))}isDebugEnabled(){return this.level<=cn.DEBUG}isInfoEnabled(){return this.level<=cn.INFO}isWarnEnabled(){return this.level<=cn.WARN}isErrorEnabled(){return this.level<=cn.ERROR}log(t,n,r){const o=new Date().toLocaleTimeString(),a=this.getConsoleMethod(t),l=ba.BADGE_STYLES[t],c=`%c${o} %c${t}%c %c[${this.name}]%c ${n}`,d=[ba.STYLES.TIMESTAMP,l,"",ba.STYLES.NAME,ba.STYLES.MESSAGE];r&&Object.keys(r).length>0?((this.collapsed?console.groupCollapsed:console.group).call(console,c,...d),console.log("Context:",r),console.groupEnd()):a(c,...d)}getConsoleMethod(t){switch(t){case"DEBUG":return console.debug.bind(console);case"INFO":return console.info.bind(console);case"WARN":return console.warn.bind(console);case"ERROR":return console.error.bind(console);default:return console.log.bind(console)}}};me(Jh,"STYLES",{DEBUG:"color: #6B7280; font-weight: normal;",INFO:"color: #10B981; font-weight: normal;",WARN:"color: #F59E0B; font-weight: bold;",ERROR:"color: #EF4444; font-weight: bold;",TIMESTAMP:"color: #9CA3AF; font-weight: normal;",NAME:"color: #8B5CF6; font-weight: normal;",MESSAGE:"color: inherit; font-weight: normal;"});me(Jh,"BADGE_STYLES",{DEBUG:"background: #E5E7EB; color: #374151; padding: 2px 6px; border-radius: 3px; font-size: 11px;",INFO:"background: #D1FAE5; color: #065F46; padding: 2px 6px; border-radius: 3px; font-size: 11px;",WARN:"background: #FEF3C7; color: #92400E; padding: 2px 6px; border-radius: 3px; font-size: 11px;",ERROR:"background: #FEE2E2; color: #991B1B; padding: 2px 6px; border-radius: 3px; font-size: 11px;"});var UT=Jh,HT=class{constructor(e={}){me(this,"options"),me(this,"loggers",new Map),this.options=e}getLogger(e){if(this.loggers.has(e))return this.loggers.get(e);const t=new UT(e,this.options);return this.loggers.set(e,t),t}},gu=qt("agentx/RemoteAgentIdResolver"),WT=class{constructor(e){me(this,"client"),this.client=mw({baseUrl:e.serverUrl,headers:e.headers})}async resolveForRun(e,t){gu.debug("Resolving agent ID for run",{imageId:e,containerId:t});const n=await this.client.post(`images/${e}/run`,{json:{containerId:t}}).json();return gu.info("Agent ID resolved for run",{imageId:e,agentId:n.agentId}),n.agentId}async resolveForResume(e,t){gu.debug("Resolving agent ID for resume",{sessionId:e,containerId:t});const n=await this.client.post(`sessions/${e}/resume`,{json:{containerId:t}}).json();return gu.info("Agent ID resolved for resume",{sessionId:e,agentId:n.agentId}),n.agentId}},Jy={name:"browser-noop",workspace:{id:"noop",name:"noop",path:""},llm:{name:"noop",provide:()=>({})}},qT=class{constructor(e){me(this,"name","sse"),me(this,"repository"),me(this,"loggerFactory"),me(this,"agentIdResolver"),me(this,"serverUrl"),me(this,"headers"),me(this,"sseParams"),this.serverUrl=e.serverUrl.replace(/\/+$/,""),this.headers=e.headers??{},this.sseParams=e.sseParams??{},this.loggerFactory=new HT({collapsed:!0}),HI(this.loggerFactory),this.repository=new $T({serverUrl:this.serverUrl,headers:this.headers}),this.agentIdResolver=new WT({serverUrl:this.serverUrl,headers:this.headers})}createSandbox(e){return Jy}createDriver(e,t,n){return{...BT({serverUrl:this.serverUrl,agentId:t.agentId,headers:this.headers,sseParams:this.sseParams}),sandbox:Jy}}createLogger(e){return this.loggerFactory.getLogger(e)}};function GT(e){return new qT(e)}var KT=Object.defineProperty,YT=(e,t,n)=>t in e?KT(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Zy=(e,t,n)=>YT(e,typeof t!="symbol"?t+"":t,n);function XT(e,t={}){const{initialMessages:n=[],onSend:r,onError:o,onStatusChange:a}=t,[l,c]=I.useState(n),[d,f]=I.useState(""),[p,m]=I.useState((e==null?void 0:e.state)??"idle"),[y,v]=I.useState([]),b=I.useRef(!0),S=p==="queued"||p==="responding"||p==="thinking"||p==="planning_tool"||p==="awaiting_tool_result"||p==="conversation_active";I.useEffect(()=>{c([]),f(""),v([]),m((e==null?void 0:e.state)??"idle")},[e]),I.useEffect(()=>{if(!e)return;b.current=!0;const O=e.react({onTextDelta:N=>{b.current&&f(D=>D+N.data.text)},onAssistantMessage:N=>{if(!b.current)return;const D=N.data;f(""),c(H=>H.some(ee=>ee.id===D.id)?H:[...H,D])},onToolCallMessage:N=>{if(!b.current)return;const D=N.data;c(H=>H.some(ee=>ee.id===D.id)?H:[...H,D])},onToolResultMessage:N=>{if(!b.current)return;const D=N.data;c(H=>H.some(ee=>ee.id===D.id)?H:[...H,D])},onError:N=>{if(!b.current)return;const D=N.data.error;v(H=>[...H,D]),f(""),o==null||o(D)}}),V=e.onStateChange(N=>{b.current&&(m(N.current),a==null||a(N.current))});return m(e.state),()=>{b.current=!1,O(),V()}},[e,o,a]);const C=I.useCallback(O=>{if(!e)return;v([]),r==null||r(O);const V={id:`msg_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,role:"user",subtype:"user",content:O,timestamp:Date.now()};c(N=>[...N,V]),e.receive(O).catch(()=>{})},[e,r]),E=I.useCallback(()=>{e==null||e.interrupt()},[e]),P=I.useCallback(()=>{c([]),f("")},[]),T=I.useCallback(()=>{v([])},[]);return{messages:l,streaming:d,status:p,errors:y,send:C,interrupt:E,isLoading:S,clearMessages:P,clearErrors:T}}function ev(e){return{sessionId:e.sessionId,userId:e.userId,imageId:e.imageId,title:e.title,createdAt:e.createdAt,updatedAt:e.updatedAt}}function QT(e,t,n={}){const{autoLoad:r=!0,onSessionChange:o,onSessionsChange:a}=n,[l,c]=I.useState([]),[d,f]=I.useState(null),[p,m]=I.useState(!1),[y,v]=I.useState(null),b=I.useCallback(async()=>{if(!(!e||!("sessions"in e))){m(!0),v(null);try{const O=(await e.sessions.listByUser(t)).map(ev);c(O),a==null||a(O)}catch(T){v(T instanceof Error?T:new Error(String(T)))}finally{m(!1)}}},[e,t,a]);I.useEffect(()=>{r&&b()},[r,b]);const S=I.useCallback(T=>{f(T),o==null||o(T)},[o]),C=I.useCallback(async(T,O)=>{if(!e||!("sessions"in e))throw new Error("AgentX sessions not available");m(!0),v(null);try{const V=await e.sessions.create(T,t);O&&await V.setTitle(O);const N=ev(V);return c(D=>[N,...D]),a==null||a([N,...l]),N}catch(V){const N=V instanceof Error?V:new Error(String(V));throw v(N),N}finally{m(!1)}},[e,t,l,a]),E=I.useCallback(async T=>{if(!e||!("sessions"in e))throw new Error("AgentX sessions not available");m(!0),v(null);try{await e.sessions.destroy(T);const O=l.filter(V=>V.sessionId!==T);c(O),a==null||a(O),(d==null?void 0:d.sessionId)===T&&(f(null),o==null||o(null))}catch(O){const V=O instanceof Error?O:new Error(String(O));throw v(V),V}finally{m(!1)}},[e,l,d,o,a]),P=I.useCallback(async(T,O)=>{if(!e||!("sessions"in e))throw new Error("AgentX sessions not available");v(null);try{const V=await e.sessions.get(T);if(V){await V.setTitle(O);const N=Date.now();c(D=>D.map(H=>H.sessionId===T?{...H,title:O,updatedAt:N}:H)),(d==null?void 0:d.sessionId)===T&&f(D=>D&&{...D,title:O,updatedAt:N})}}catch(V){const N=V instanceof Error?V:new Error(String(V));throw v(N),N}},[e,d]);return{sessions:l,currentSession:d,selectSession:S,createSession:C,deleteSession:E,setSessionTitle:P,refresh:b,isLoading:p,error:y}}/**
53
+ `):"",this.name="UnsubscriptionError",this.errors=n}});function rh(e,t){if(e){var n=e.indexOf(t);0<=n&&e.splice(n,1)}}var ic=(function(){function e(t){this.initialTeardown=t,this.closed=!1,this._parentage=null,this._finalizers=null}return e.prototype.unsubscribe=function(){var t,n,r,o,a;if(!this.closed){this.closed=!0;var l=this._parentage;if(l)if(this._parentage=null,Array.isArray(l))try{for(var c=eh(l),d=c.next();!d.done;d=c.next()){var f=d.value;f.remove(this)}}catch(S){t={error:S}}finally{try{d&&!d.done&&(n=c.return)&&n.call(c)}finally{if(t)throw t.error}}else l.remove(this);var p=this.initialTeardown;if(kr(p))try{p()}catch(S){a=S instanceof ef?S.errors:[S]}var m=this._finalizers;if(m){this._finalizers=null;try{for(var y=eh(m),v=y.next();!v.done;v=y.next()){var b=v.value;try{Vy(b)}catch(S){a=a??[],S instanceof ef?a=nh(nh([],th(a)),th(S.errors)):a.push(S)}}}catch(S){r={error:S}}finally{try{v&&!v.done&&(o=y.return)&&o.call(y)}finally{if(r)throw r.error}}}if(a)throw new ef(a)}},e.prototype.add=function(t){var n;if(t&&t!==this)if(this.closed)Vy(t);else{if(t instanceof e){if(t.closed||t._hasParent(this))return;t._addParent(this)}(this._finalizers=(n=this._finalizers)!==null&&n!==void 0?n:[]).push(t)}},e.prototype._hasParent=function(t){var n=this._parentage;return n===t||Array.isArray(n)&&n.includes(t)},e.prototype._addParent=function(t){var n=this._parentage;this._parentage=Array.isArray(n)?(n.push(t),n):n?[n,t]:t},e.prototype._removeParent=function(t){var n=this._parentage;n===t?this._parentage=null:Array.isArray(n)&&rh(n,t)},e.prototype.remove=function(t){var n=this._finalizers;n&&rh(n,t),t instanceof e&&t._removeParent(this)},e.EMPTY=(function(){var t=new e;return t.closed=!0,t})(),e})(),lw=ic.EMPTY;function uw(e){return e instanceof ic||e&&"closed"in e&&kr(e.remove)&&kr(e.add)&&kr(e.unsubscribe)}function Vy(e){kr(e)?e():e.unsubscribe()}var _I={Promise:void 0},PI={setTimeout:function(e,t){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];return setTimeout.apply(void 0,nh([e,t],th(n)))},clearTimeout:function(e){return clearTimeout(e)},delegate:void 0};function AI(e){PI.setTimeout(function(){throw e})}function By(){}function Ru(e){e()}var Qh=(function(e){qa(t,e);function t(n){var r=e.call(this)||this;return r.isStopped=!1,n?(r.destination=n,uw(n)&&n.add(r)):r.destination=jI,r}return t.create=function(n,r,o){return new ih(n,r,o)},t.prototype.next=function(n){this.isStopped||this._next(n)},t.prototype.error=function(n){this.isStopped||(this.isStopped=!0,this._error(n))},t.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},t.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,e.prototype.unsubscribe.call(this),this.destination=null)},t.prototype._next=function(n){this.destination.next(n)},t.prototype._error=function(n){try{this.destination.error(n)}finally{this.unsubscribe()}},t.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},t})(ic),RI=(function(){function e(t){this.partialObserver=t}return e.prototype.next=function(t){var n=this.partialObserver;if(n.next)try{n.next(t)}catch(r){du(r)}},e.prototype.error=function(t){var n=this.partialObserver;if(n.error)try{n.error(t)}catch(r){du(r)}else du(t)},e.prototype.complete=function(){var t=this.partialObserver;if(t.complete)try{t.complete()}catch(n){du(n)}},e})(),ih=(function(e){qa(t,e);function t(n,r,o){var a=e.call(this)||this,l;return kr(n)||!n?l={next:n??void 0,error:r??void 0,complete:o??void 0}:l=n,a.destination=new RI(l),a}return t})(Qh);function du(e){AI(e)}function NI(e){throw e}var jI={closed:!0,next:By,error:NI,complete:By},MI=(function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"})();function DI(e){return e}function LI(e){return e.length===0?DI:e.length===1?e[0]:function(n){return e.reduce(function(r,o){return o(r)},n)}}var sh=(function(){function e(t){t&&(this._subscribe=t)}return e.prototype.lift=function(t){var n=new e;return n.source=this,n.operator=t,n},e.prototype.subscribe=function(t,n,r){var o=this,a=OI(t)?t:new ih(t,n,r);return Ru(function(){var l=o,c=l.operator,d=l.source;a.add(c?c.call(a,d):d?o._subscribe(a):o._trySubscribe(a))}),a},e.prototype._trySubscribe=function(t){try{return this._subscribe(t)}catch(n){t.error(n)}},e.prototype.forEach=function(t,n){var r=this;return n=$y(n),new n(function(o,a){var l=new ih({next:function(c){try{t(c)}catch(d){a(d),l.unsubscribe()}},error:a,complete:o});r.subscribe(l)})},e.prototype._subscribe=function(t){var n;return(n=this.source)===null||n===void 0?void 0:n.subscribe(t)},e.prototype[MI]=function(){return this},e.prototype.pipe=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return LI(t)(this)},e.prototype.toPromise=function(t){var n=this;return t=$y(t),new t(function(r,o){var a;n.subscribe(function(l){return a=l},function(l){return o(l)},function(){return r(a)})})},e.create=function(t){return new e(t)},e})();function $y(e){var t;return(t=e??_I.Promise)!==null&&t!==void 0?t:Promise}function zI(e){return e&&kr(e.next)&&kr(e.error)&&kr(e.complete)}function OI(e){return e&&e instanceof Qh||zI(e)&&uw(e)}function FI(e){return kr(e==null?void 0:e.lift)}function cw(e){return function(t){if(FI(t))return t.lift(function(n){try{return e(n,this)}catch(r){this.error(r)}});throw new TypeError("Unable to lift unknown Observable type")}}function dw(e,t,n,r,o){return new VI(e,t,n,r,o)}var VI=(function(e){qa(t,e);function t(n,r,o,a,l,c){var d=e.call(this,n)||this;return d.onFinalize=l,d.shouldUnsubscribe=c,d._next=r?function(f){try{r(f)}catch(p){n.error(p)}}:e.prototype._next,d._error=a?function(f){try{a(f)}catch(p){n.error(p)}finally{this.unsubscribe()}}:e.prototype._error,d._complete=o?function(){try{o()}catch(f){n.error(f)}finally{this.unsubscribe()}}:e.prototype._complete,d}return t.prototype.unsubscribe=function(){var n;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var r=this.closed;e.prototype.unsubscribe.call(this),!r&&((n=this.onFinalize)===null||n===void 0||n.call(this))}},t})(Qh),BI=aw(function(e){return function(){e(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}}),fw=(function(e){qa(t,e);function t(){var n=e.call(this)||this;return n.closed=!1,n.currentObservers=null,n.observers=[],n.isStopped=!1,n.hasError=!1,n.thrownError=null,n}return t.prototype.lift=function(n){var r=new Uy(this,this);return r.operator=n,r},t.prototype._throwIfClosed=function(){if(this.closed)throw new BI},t.prototype.next=function(n){var r=this;Ru(function(){var o,a;if(r._throwIfClosed(),!r.isStopped){r.currentObservers||(r.currentObservers=Array.from(r.observers));try{for(var l=eh(r.currentObservers),c=l.next();!c.done;c=l.next()){var d=c.value;d.next(n)}}catch(f){o={error:f}}finally{try{c&&!c.done&&(a=l.return)&&a.call(l)}finally{if(o)throw o.error}}}})},t.prototype.error=function(n){var r=this;Ru(function(){if(r._throwIfClosed(),!r.isStopped){r.hasError=r.isStopped=!0,r.thrownError=n;for(var o=r.observers;o.length;)o.shift().error(n)}})},t.prototype.complete=function(){var n=this;Ru(function(){if(n._throwIfClosed(),!n.isStopped){n.isStopped=!0;for(var r=n.observers;r.length;)r.shift().complete()}})},t.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(t.prototype,"observed",{get:function(){var n;return((n=this.observers)===null||n===void 0?void 0:n.length)>0},enumerable:!1,configurable:!0}),t.prototype._trySubscribe=function(n){return this._throwIfClosed(),e.prototype._trySubscribe.call(this,n)},t.prototype._subscribe=function(n){return this._throwIfClosed(),this._checkFinalizedStatuses(n),this._innerSubscribe(n)},t.prototype._innerSubscribe=function(n){var r=this,o=this,a=o.hasError,l=o.isStopped,c=o.observers;return a||l?lw:(this.currentObservers=null,c.push(n),new ic(function(){r.currentObservers=null,rh(c,n)}))},t.prototype._checkFinalizedStatuses=function(n){var r=this,o=r.hasError,a=r.thrownError,l=r.isStopped;o?n.error(a):l&&n.complete()},t.prototype.asObservable=function(){var n=new sh;return n.source=this,n},t.create=function(n,r){return new Uy(n,r)},t})(sh),Uy=(function(e){qa(t,e);function t(n,r){var o=e.call(this)||this;return o.destination=n,o.source=r,o}return t.prototype.next=function(n){var r,o;(o=(r=this.destination)===null||r===void 0?void 0:r.next)===null||o===void 0||o.call(r,n)},t.prototype.error=function(n){var r,o;(o=(r=this.destination)===null||r===void 0?void 0:r.error)===null||o===void 0||o.call(r,n)},t.prototype.complete=function(){var n,r;(r=(n=this.destination)===null||n===void 0?void 0:n.complete)===null||r===void 0||r.call(n)},t.prototype._subscribe=function(n){var r,o;return(o=(r=this.source)===null||r===void 0?void 0:r.subscribe(n))!==null&&o!==void 0?o:lw},t})(fw),$I=new sh(function(e){return e.complete()});function tf(e,t){return cw(function(n,r){var o=0;n.subscribe(dw(r,function(a){return e.call(t,a,o++)&&r.next(a)}))})}function Hy(e){return e<=0?function(){return $I}:cw(function(t,n){var r=0;t.subscribe(dw(n,function(o){++r<=e&&(n.next(o),e<=r&&n.complete())}))})}var UI=Object.defineProperty,HI=(e,t,n)=>t in e?UI(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,me=(e,t,n)=>HI(e,typeof t!="symbol"?t+"":t,n),Gs=qt("agentx/DefinitionManager");function Wy(e){return`meta_${e}`}function WI(e){const t=new Date;return{name:e.name,description:e.description,systemPrompt:e.systemPrompt,definition:e,source:"code",createdAt:t,updatedAt:t}}var qI=class{constructor(e){this.repository=e,me(this,"cache",new Map)}register(e){if(this.cache.has(e.name))throw new Error(`Definition already exists: ${e.name}`);this.cache.set(e.name,e);const t=WI(e);this.repository.saveDefinition(t).catch(o=>{Gs.error("Failed to save definition",{name:e.name,error:o})});const n=Wy(e.name),r={imageId:n,type:"meta",definitionName:e.name,parentImageId:null,definition:e,config:{},messages:[],createdAt:new Date};this.repository.saveImage(r).catch(o=>{Gs.error("Failed to save MetaImage",{definitionName:e.name,error:o})}),Gs.info("Definition registered",{name:e.name,metaImageId:n})}get(e){return this.cache.get(e)}list(){return Array.from(this.cache.values())}has(e){return this.cache.has(e)}unregister(e){if(!this.cache.get(e))return!1;this.cache.delete(e),this.repository.deleteDefinition(e).catch(r=>{Gs.error("Failed to delete definition",{name:e,error:r})});const n=Wy(e);return this.repository.deleteImage(n).catch(r=>{Gs.error("Failed to delete MetaImage",{definitionName:e,error:r})}),Gs.info("Definition unregistered",{name:e}),!0}},fu=qt("agentx/ImageManager");function GI(e){return`meta_${e}`}function hu(e){const t=e.definition;return e.type==="meta"?{type:"meta",imageId:e.imageId,definitionName:e.definitionName,definition:t,config:e.config,messages:[],createdAt:e.createdAt}:{type:"derived",imageId:e.imageId,parentImageId:e.parentImageId,definitionName:e.definitionName,definition:t,config:e.config,messages:e.messages,createdAt:e.createdAt}}var KI=class{constructor(e,t,n){me(this,"repository"),me(this,"containerManager"),me(this,"defaultContainerId"),this.repository=e,this.containerManager=t,this.defaultContainerId=n}async get(e){const t=await this.repository.findImageById(e);if(t)return hu(t)}async getMetaImage(e){const t=GI(e),n=await this.repository.findImageById(t);if(!(!n||n.type!=="meta"))return hu(n)}async list(){return(await this.repository.findAllImages()).map(hu)}async listByDefinition(e){return(await this.repository.findAllImages()).filter(r=>r.definitionName===e).map(hu)}async exists(e){return this.repository.imageExists(e)}async delete(e){const t=await this.repository.findImageById(e);return t?t.type==="meta"?(fu.warn("Cannot delete MetaImage directly",{imageId:e}),!1):(await this.repository.deleteImage(e),fu.info("Image deleted",{imageId:e}),!0):!1}async run(e,t){fu.info("Running agent from image",{imageId:e,containerId:t==null?void 0:t.containerId});const n=await this.get(e);if(!n)throw new Error(`Image not found: ${e}`);let r=(t==null?void 0:t.containerId)||this.defaultContainerId;return r||(r=(await this.containerManager.create()).containerId,this.defaultContainerId=r,fu.debug("Auto-created default container",{containerId:r})),this.containerManager.run(n,r)}},pu=qt("agentx/AgentManager"),YI=class{constructor(e){this.containerManager=e}get(e){return this.containerManager.getAgent(e)}has(e){return this.containerManager.hasAgent(e)}list(){return this.containerManager.listAgents()}async destroy(e){pu.debug("Destroying agent",{agentId:e}),await this.containerManager.destroyAgent(e),pu.info("Agent destroyed",{agentId:e})}async destroyAll(){const e=this.containerManager.listAgents();pu.debug("Destroying all agents",{count:e.length}),await this.containerManager.destroyAllAgents(),pu.info("All agents destroyed",{count:e.length})}},Sn=qt("agentx/SessionManager");function hw(){const e=Date.now().toString(36),t=Math.random().toString(36).substring(2,8);return`session_${e}_${t}`}function XI(){const e=Date.now().toString(36),t=Math.random().toString(36).substring(2,8);return`image_${e}_${t}`}var ca=class pw{constructor(t,n,r,o){me(this,"sessionId"),me(this,"userId"),me(this,"imageId"),me(this,"createdAt"),me(this,"_title"),me(this,"_updatedAt"),me(this,"repository"),me(this,"containerManager"),me(this,"defaultContainerId"),this.sessionId=t.sessionId,this.userId=t.userId,this.imageId=t.imageId,this._title=t.title,this.createdAt=t.createdAt.getTime(),this._updatedAt=t.updatedAt.getTime(),this.repository=n,this.containerManager=r,this.defaultContainerId=o}get title(){return this._title}get updatedAt(){return this._updatedAt}async resume(t){Sn.info("Resuming agent from session",{sessionId:this.sessionId,imageId:this.imageId,containerId:t==null?void 0:t.containerId});let n=(t==null?void 0:t.containerId)||this.defaultContainerId;n||(n=(await this.containerManager.create()).containerId,Sn.debug("Auto-created default container for session",{containerId:n,sessionId:this.sessionId}));const r=await this.containerManager.resume(this,n);return this.collect(r),r}collect(t){Sn.debug("Collecting messages from agent",{sessionId:this.sessionId,agentId:t.agentId});const n=this.sessionId,r=this.repository,o=(a,l)=>{const c={messageId:a.id,sessionId:n,role:l,content:a,createdAt:new Date(a.timestamp??Date.now())};r.saveMessage(c).catch(d=>{Sn.error("Failed to persist message",{sessionId:n,messageId:c.messageId,error:d})})};t.on("user_message",a=>o(a.data,"user")),t.on("assistant_message",a=>o(a.data,"assistant")),t.on("tool_call_message",a=>o(a.data,"tool")),t.on("tool_result_message",a=>o(a.data,"tool"))}async getMessages(){return Sn.debug("Getting messages for session",{sessionId:this.sessionId}),(await this.repository.findMessagesBySessionId(this.sessionId)).map(n=>n.content)}async fork(){Sn.info("Forking session",{sessionId:this.sessionId});const t=await this.repository.findImageById(this.imageId);if(!t)throw new Error(`Image not found: ${this.imageId}`);const n=XI(),r={imageId:n,type:"derived",definitionName:t.definitionName,parentImageId:t.imageId,definition:t.definition,config:t.config,messages:[...t.messages],createdAt:new Date};await this.repository.saveImage(r);const o=hw(),a=new Date,l={sessionId:o,userId:this.userId,imageId:n,title:this._title?`Fork of ${this._title}`:null,createdAt:a,updatedAt:a};return await this.repository.saveSession(l),Sn.info("Session forked",{originalSessionId:this.sessionId,newSessionId:o,newImageId:n}),new pw(l,this.repository,this.containerManager,this.defaultContainerId)}async setTitle(t){Sn.debug("Setting session title",{sessionId:this.sessionId,title:t});const n=new Date;await this.repository.saveSession({sessionId:this.sessionId,userId:this.userId,imageId:this.imageId,title:t,createdAt:new Date(this.createdAt),updatedAt:n}),this._title=t,this._updatedAt=n.getTime(),Sn.info("Session title updated",{sessionId:this.sessionId,title:t})}},QI=class{constructor(e,t,n){me(this,"repository"),me(this,"containerManager"),me(this,"defaultContainerId"),this.repository=e,this.containerManager=t,this.defaultContainerId=n}async create(e,t){const n=hw(),r=new Date,o={sessionId:n,userId:t,imageId:e,title:null,createdAt:r,updatedAt:r};return await this.repository.saveSession(o),Sn.info("Session created",{sessionId:n,imageId:e,userId:t}),new ca(o,this.repository,this.containerManager,this.defaultContainerId)}async get(e){const t=await this.repository.findSessionById(e);if(t)return new ca(t,this.repository,this.containerManager,this.defaultContainerId)}async has(e){return this.repository.sessionExists(e)}async list(){return(await this.repository.findAllSessions()).map(t=>new ca(t,this.repository,this.containerManager,this.defaultContainerId))}async listByImage(e){return(await this.repository.findSessionsByImageId(e)).map(n=>new ca(n,this.repository,this.containerManager,this.defaultContainerId))}async listByUser(e){return(await this.repository.findSessionsByUserId(e)).map(n=>new ca(n,this.repository,this.containerManager,this.defaultContainerId))}async destroy(e){await this.repository.deleteSession(e),Sn.info("Session destroyed",{sessionId:e})}async destroyByImage(e){await this.repository.deleteSessionsByImageId(e),Sn.info("Sessions destroyed by image",{imageId:e})}async destroyAll(){const e=await this.repository.findAllSessions();for(const t of e)await this.repository.deleteSession(t.sessionId);Sn.info("All sessions destroyed")}},mu=qt("agentx/ErrorManager"),JI=class{constructor(){me(this,"handlers",new Set)}handle(e,t,n){this.logError(e,t);for(const r of this.handlers)try{r.handle(e,t,n)}catch(o){mu.error("ErrorHandler failed",{error:o})}}addHandler(e){return this.handlers.add(e),()=>{this.handlers.delete(e)}}removeHandler(e){this.handlers.delete(e)}logError(e,t){const n=`[${e}] ${t.category}/${t.code}`;t.severity==="fatal"?mu.error(`${n}: ${t.message}`,{error:t}):t.severity==="error"?mu.error(`${n}: ${t.message}`):mu.warn(`${n}: ${t.message}`)}},ZI=class extends Error{constructor(e,t,n){super(t),this.code=e,this.details=n,this.name="ApiError"}};function mw(e){return TI.create({prefixUrl:e.baseUrl.replace(/\/+$/,""),headers:e.headers,timeout:e.timeout||3e4,hooks:{afterResponse:[async(t,n,r)=>{var o,a,l;if(!r.ok){const c=await r.json().catch(()=>({}));throw new ZI(((o=c.error)==null?void 0:o.code)||"UNKNOWN_ERROR",((a=c.error)==null?void 0:a.message)||`Request failed: ${r.status}`,(l=c.error)==null?void 0:l.details)}return r}]}})}var qy=qt("core/AgentStateMachine"),eT=class{constructor(){me(this,"_state","idle"),me(this,"handlers",new Set)}get state(){return this._state}process(e){const t=this._state,n=this.mapEventToState(e);n!==null&&t!==n&&(this._state=n,qy.debug("State transition",{eventType:e.type,from:t,to:n}),this.notifyHandlers({prev:t,current:n}))}onStateChange(e){return this.handlers.add(e),()=>{this.handlers.delete(e)}}reset(){this._state,this._state="idle",this.handlers.clear()}mapEventToState(e){switch(e.type){case"agent_initializing":return"initializing";case"agent_ready":return"idle";case"agent_destroyed":return"idle";case"conversation_queued":return"queued";case"conversation_start":return"conversation_active";case"conversation_thinking":return"thinking";case"conversation_responding":return"responding";case"conversation_end":return"idle";case"conversation_interrupted":return"idle";case"tool_planned":return"planning_tool";case"tool_executing":return"awaiting_tool_result";case"tool_completed":return"responding";case"tool_failed":return"responding";case"error_occurred":return"idle";default:return null}}notifyHandlers(e){for(const t of this.handlers)try{t(e)}catch(n){qy.error("State change handler error",{from:e.prev,to:e.current,error:n})}}},Ks=qt("core/AgentEventBus"),tT=class{constructor(){me(this,"subject",new fw),me(this,"typeSubscriptions",new Map),me(this,"globalSubscriptions",[]),me(this,"nextId",0),me(this,"isDestroyed",!1),me(this,"producerView",null),me(this,"consumerView",null)}emit(e){if(this.isDestroyed){Ks.warn("Emit called on destroyed EventBus",{eventType:e.type});return}this.subject.next(e)}emitBatch(e){for(const t of e)this.emit(t)}on(e,t,n={}){if(this.isDestroyed)return Ks.warn("Subscribe called on destroyed EventBus"),()=>{};const r=Array.isArray(e)?e:[e],o=[];for(const a of r){const l=this.subscribeToType(a,t,n);o.push(l)}return()=>o.forEach(a=>a())}onAny(e,t={}){return this.isDestroyed?(Ks.warn("Subscribe called on destroyed EventBus"),()=>{}):this.subscribeGlobal(e,t)}once(e,t){return this.on(e,t,{once:!0})}asConsumer(){return this.consumerView||(this.consumerView={on:this.on.bind(this),onAny:this.onAny.bind(this),once:this.once.bind(this)}),this.consumerView}asProducer(){return this.producerView||(this.producerView={emit:this.emit.bind(this),emitBatch:this.emitBatch.bind(this)}),this.producerView}destroy(){if(!this.isDestroyed){this.isDestroyed=!0;for(const e of this.typeSubscriptions.values())for(const t of e)t.unsubscribe();this.typeSubscriptions.clear();for(const e of this.globalSubscriptions)e.unsubscribe();this.globalSubscriptions.length=0,this.subject.complete(),Ks.debug("EventBus destroyed")}}subscribeToType(e,t,n){const{filter:r,priority:o=0,once:a=!1}=n,l=this.nextId++;let c=this.subject.pipe(tf(y=>y.type===e));r&&(c=c.pipe(tf(r))),a&&(c=c.pipe(Hy(1)));const d=c.subscribe({next:y=>{this.executeWithPriority(e,y,t,l)}}),f=()=>{d.unsubscribe();const y=this.typeSubscriptions.get(e);if(y){const v=y.findIndex(b=>b.id===l);v!==-1&&y.splice(v,1)}};this.typeSubscriptions.has(e)||this.typeSubscriptions.set(e,[]);const p={id:l,priority:o,handler:t,unsubscribe:f},m=this.typeSubscriptions.get(e);return m.push(p),m.sort((y,v)=>v.priority-y.priority),f}subscribeGlobal(e,t){const{filter:n,priority:r=0,once:o=!1}=t,a=this.nextId++;let l=this.subject.asObservable();n&&(l=l.pipe(tf(n))),o&&(l=l.pipe(Hy(1)));const c=l.subscribe({next:p=>{this.executeGlobalWithPriority(p,e,a)}}),d=()=>{c.unsubscribe();const p=this.globalSubscriptions.findIndex(m=>m.id===a);p!==-1&&this.globalSubscriptions.splice(p,1)},f={id:a,priority:r,handler:e,unsubscribe:d};return this.globalSubscriptions.push(f),this.globalSubscriptions.sort((p,m)=>m.priority-p.priority),d}executeWithPriority(e,t,n,r){if((this.typeSubscriptions.get(e)||[]).find(l=>l.id===r))try{n(t)}catch(l){Ks.error("Event handler error",{eventType:e,error:l})}}executeGlobalWithPriority(e,t,n){if(this.globalSubscriptions.find(o=>o.id===n))try{t(e)}catch(o){Ks.error("Global event handler error",{eventType:e.type,error:o})}}},nT=class{constructor(e){this.agentId=e}classify(e){const t=e instanceof Error?e:new Error(String(e)),n=t.message;return n.includes("rate limit")||n.includes("429")?this.create("llm","RATE_LIMITED",n,!0,t):n.includes("api key")||n.includes("401")||n.includes("unauthorized")?this.create("llm","INVALID_API_KEY",n,!1,t):n.includes("context")&&n.includes("long")?this.create("llm","CONTEXT_TOO_LONG",n,!0,t):n.includes("overloaded")||n.includes("503")?this.create("llm","OVERLOADED",n,!0,t):n.includes("timeout")||n.includes("ETIMEDOUT")?this.create("network","TIMEOUT",n,!0,t):n.includes("ECONNREFUSED")||n.includes("connection")?this.create("network","CONNECTION_FAILED",n,!0,t):n.includes("network")||n.includes("fetch")?this.create("network","CONNECTION_FAILED",n,!0,t):n.includes("driver")?this.create("driver","RECEIVE_FAILED",n,!0,t):this.create("system","UNKNOWN",n,!0,t)}create(e,t,n,r,o){return{category:e,code:t,message:n,severity:r?"error":"fatal",recoverable:r,cause:o}}createEvent(e){return{type:"error",uuid:`${Date.now()}_${Math.random().toString(36).substring(2,9)}`,agentId:this.agentId,timestamp:Date.now(),data:{error:e}}}},rT=class{constructor(){me(this,"middlewares",[])}use(e){return this.middlewares.push(e),()=>{const t=this.middlewares.indexOf(e);t!==-1&&this.middlewares.splice(t,1)}}async execute(e,t){let n=0;const r=async o=>{if(n<this.middlewares.length){const a=this.middlewares[n++];await a(o,r)}else await t(o)};await r(e)}clear(){this.middlewares.length=0}get size(){return this.middlewares.length}},iT=qt("core/InterceptorChain"),sT=class{constructor(e){me(this,"interceptors",[]),me(this,"agentId"),this.agentId=e}intercept(e){return this.interceptors.push(e),()=>{const t=this.interceptors.indexOf(e);t!==-1&&this.interceptors.splice(t,1)}}execute(e,t){let n=0;const r=o=>{if(n<this.interceptors.length){const a=this.interceptors[n++];try{a(o,r)}catch(l){iT.error("Interceptor error",{agentId:this.agentId,eventType:o.type,interceptorIndex:n-1,error:l}),r(o)}}else t(o)};r(e)}clear(){this.interceptors.length=0}get size(){return this.interceptors.length}},oT={onMessageStart:"message_start",onMessageDelta:"message_delta",onMessageStop:"message_stop",onTextContentBlockStart:"text_content_block_start",onTextDelta:"text_delta",onTextContentBlockStop:"text_content_block_stop",onToolUseContentBlockStart:"tool_use_content_block_start",onInputJsonDelta:"input_json_delta",onToolUseContentBlockStop:"tool_use_content_block_stop",onToolCall:"tool_call",onToolResult:"tool_result",onUserMessage:"user_message",onAssistantMessage:"assistant_message",onToolCallMessage:"tool_call_message",onToolResultMessage:"tool_result_message",onError:"error",onTurnRequest:"turn_request",onTurnResponse:"turn_response"};function aT(e){const t={};for(const[n,r]of Object.entries(oT)){const o=e[n];o&&(t[r]=o)}return t}var zn=qt("core/AgentInstance"),Gy=class{constructor(e,t,n,r,o){me(this,"agentId"),me(this,"definition"),me(this,"context"),me(this,"createdAt"),me(this,"sandbox"),me(this,"_lifecycle","running"),me(this,"engine"),me(this,"driver"),me(this,"stateMachine",new eT),me(this,"eventBus",new tT),me(this,"errorClassifier"),me(this,"middlewareChain",new rT),me(this,"interceptorChain"),me(this,"readyHandlers",new Set),me(this,"destroyHandlers",new Set),this.agentId=t.agentId,this.definition=e,this.context=t,this.engine=n,this.createdAt=t.createdAt,this.sandbox=o,this.driver=r,this.errorClassifier=new nT(this.agentId),this.interceptorChain=new sT(this.agentId),zn.debug("AgentInstance created",{agentId:this.agentId,definitionName:e.name,driverName:this.driver.name})}get lifecycle(){return this._lifecycle}get state(){return this.stateMachine.state}async receive(e){if(this._lifecycle==="destroyed"){zn.warn("Receive called on destroyed agent",{agentId:this.agentId});const r=this.errorClassifier.create("system","AGENT_DESTROYED","Agent has been destroyed",!1),o=this.errorClassifier.createEvent(r);throw this.notifyHandlers(o),new Error("[Agent] Agent has been destroyed")}if(this.state!=="idle"){zn.warn("Receive called while agent is busy",{agentId:this.agentId,currentState:this.state});const r=this.errorClassifier.create("system","AGENT_BUSY",`Agent is busy (state: ${this.state}), please wait for current operation to complete`,!1),o=this.errorClassifier.createEvent(r);throw this.notifyHandlers(o),new Error(`[Agent] Agent is busy (state: ${this.state})`)}const t=typeof e=="string"?{id:`msg_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,role:"user",subtype:"user",content:e,timestamp:Date.now()}:e;zn.debug("Receiving message",{agentId:this.agentId,messageId:t.id});const n={uuid:`evt_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,type:"user_message",agentId:this.agentId,timestamp:Date.now(),data:t};this.presentOutput(n),this.notifyHandlers(n),await this.executeMiddlewareChain(t)}async executeMiddlewareChain(e){await this.middlewareChain.execute(e,t=>this.doReceive(t))}processStreamEvent(e){const t=this.engine.process(this.agentId,e);for(const n of t)this.presentOutput(n);for(const n of t)this.notifyHandlers(n)}async doReceive(e){try{zn.debug("Processing message through driver",{agentId:this.agentId,messageId:e.id});const t={type:"conversation_queued",uuid:`${Date.now()}_${Math.random().toString(36).substring(2,9)}`,agentId:this.agentId,timestamp:Date.now(),data:{userMessage:e}};this.notifyHandlers(t);const n=this.driver.receive(e);for await(const r of n)this.processStreamEvent(r);zn.debug("Message processing completed",{agentId:this.agentId,messageId:e.id})}catch(t){const n=this.errorClassifier.classify(t),r=this.errorClassifier.createEvent(n);throw zn.error("Message processing failed",{agentId:this.agentId,messageId:e.id,errorCategory:n.category,errorCode:n.code,error:t}),this.notifyHandlers(r),t}}presentOutput(e){}on(e,t){if(typeof e=="function")return this.eventBus.onAny(e);if(this.isEventHandlerMap(e)){const o=[];for(const[a,l]of Object.entries(e))l&&o.push(this.eventBus.on(a,l));return()=>{for(const a of o)a()}}const n=Array.isArray(e)?e:[e],r=t;return this.eventBus.on(n,r)}isEventHandlerMap(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;const t=Object.keys(e);return t.length===0?!1:t.every(n=>{const r=e[n];return r===void 0||typeof r=="function"})}onStateChange(e){return this.stateMachine.onStateChange(e)}react(e){const t=aT(e);return this.on(t)}onReady(e){if(this._lifecycle==="running")try{e()}catch(t){zn.error("onReady handler error",{agentId:this.agentId,error:t})}return this.readyHandlers.add(e),()=>{this.readyHandlers.delete(e)}}onDestroy(e){return this.destroyHandlers.add(e),()=>{this.destroyHandlers.delete(e)}}use(e){return this.middlewareChain.use(e)}intercept(e){return this.interceptorChain.intercept(e)}interrupt(){zn.debug("User interrupt requested",{agentId:this.agentId,currentState:this.state}),this.driver.interrupt()}async destroy(){zn.debug("Destroying agent",{agentId:this.agentId});for(const e of this.destroyHandlers)try{e()}catch(t){zn.error("onDestroy handler error",{agentId:this.agentId,error:t})}this._lifecycle="destroyed",this.stateMachine.reset(),this.eventBus.destroy(),this.readyHandlers.clear(),this.destroyHandlers.clear(),this.middlewareChain.clear(),this.interceptorChain.clear(),this.engine.clearState(this.agentId),zn.info("Agent destroyed",{agentId:this.agentId})}notifyHandlers(e){JC(e)&&this.stateMachine.process(e),this.executeInterceptorChain(e)}executeInterceptorChain(e){this.interceptorChain.execute(e,t=>this.eventBus.emit(t))}getEventConsumer(){return this.eventBus.asConsumer()}},lT=class{constructor(){me(this,"states",new Map)}get(e){return this.states.get(e)}set(e,t){this.states.set(e,t)}delete(e){this.states.delete(e)}has(e){return this.states.has(e)}clear(){this.states.clear()}get size(){return this.states.size}keys(){return this.states.keys()}};qt("engine/Mealy");function uT(e){return(t,n)=>{const r={},o=[];for(const a in e){const l=e[a],c=t[a],[d,f]=l(c,n);r[a]=d,o.push(...f)}return[r,o]}}function cT(e){return()=>{const t={};for(const n in e)t[n]=e[n]();return t}}function oh(){return{currentMessageId:null,messageStartTime:null,pendingContents:{},pendingToolCalls:{}}}function hs(){return`msg_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}var dT=(e,t)=>{switch(t.type){case"message_start":return fT(e,t);case"text_delta":return hT(e,t);case"tool_use_content_block_start":return pT(e,t);case"input_json_delta":return mT(e,t);case"tool_use_content_block_stop":return gT(e,t);case"tool_result":return yT(e,t);case"message_stop":return vT(e,t);default:return[e,[]]}};function fT(e,t){return[{...e,currentMessageId:hs(),messageStartTime:t.timestamp,pendingContents:{}},[]]}function hT(e,t){const r=e.pendingContents[0],o=(r==null?void 0:r.type)==="text"?{...r,textDeltas:[...r.textDeltas||[],t.data.text]}:{type:"text",index:0,textDeltas:[t.data.text]};return[{...e,pendingContents:{...e.pendingContents,0:o}},[]]}function pT(e,t){const r={type:"tool_use",index:1,toolId:t.data.id,toolName:t.data.name,toolInputJson:""};return[{...e,pendingContents:{...e.pendingContents,1:r}},[]]}function mT(e,t){const r=e.pendingContents[1];if(!r||r.type!=="tool_use")return[e,[]];const o={...r,toolInputJson:(r.toolInputJson||"")+t.data.partialJson};return[{...e,pendingContents:{...e.pendingContents,1:o}},[]]}function gT(e,t){const r=e.pendingContents[1];if(!r||r.type!=="tool_use")return[e,[]];let o={};try{o=r.toolInputJson?JSON.parse(r.toolInputJson):{}}catch{o={}}const a=[],l=r.toolId,c=r.toolName,d={type:"tool_call",uuid:hs(),agentId:t.agentId,timestamp:Date.now(),data:{id:l,name:c,input:o}};a.push(d);const f={type:"tool-call",id:l,name:c,input:o},p={id:hs(),role:"assistant",subtype:"tool-call",toolCall:f,timestamp:Date.now()},m={type:"tool_call_message",uuid:hs(),agentId:t.agentId,timestamp:Date.now(),data:p};a.push(m);const{[1]:y,...v}=e.pendingContents;return[{...e,pendingContents:v,pendingToolCalls:{...e.pendingToolCalls,[l]:{id:l,name:c}}},a]}function yT(e,t){const{toolId:n,content:r,isError:o}=t.data,a=e.pendingToolCalls[n],l=(a==null?void 0:a.name)||"unknown",c={type:"tool-result",id:n,name:l,output:{type:o?"error-text":"text",value:typeof r=="string"?r:JSON.stringify(r)}},d={id:hs(),role:"tool",subtype:"tool-result",toolResult:c,toolCallId:n,timestamp:Date.now()},f={type:"tool_result_message",uuid:hs(),agentId:t.agentId,timestamp:Date.now(),data:d},{[n]:p,...m}=e.pendingToolCalls;return[{...e,pendingToolCalls:m},[f]]}function vT(e,t){if(!e.currentMessageId)return[e,[]];const n=[],r=Object.values(e.pendingContents).sort((f,p)=>f.index-p.index);for(const f of r)f.type==="text"&&f.textDeltas&&n.push(f.textDeltas.join(""));const o=n.join(""),a=t.data.stopReason;if(!o||o.trim().length===0){const f=a==="tool_use";return[{...oh(),pendingToolCalls:f?e.pendingToolCalls:{}},[]]}const l={id:e.currentMessageId,role:"assistant",subtype:"assistant",content:o,timestamp:e.messageStartTime||Date.now(),usage:void 0},c={type:"assistant_message",uuid:hs(),agentId:t.agentId,timestamp:Date.now(),data:l},d=a==="tool_use";return[{...oh(),pendingToolCalls:d?e.pendingToolCalls:{}},[c]]}var Ma=qt("engine/stateEventProcessor");function xT(){return{}}function uo(){return`state_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}var wT=(e,t)=>{switch(Ma.debug(`[Stream Event] ${t.type}`,{context:e,eventData:"data"in t?t.data:void 0}),t.type){case"message_start":return bT(e,t);case"message_delta":return ST(e);case"message_stop":return kT(e,t);case"text_content_block_start":return ET(e,t);case"tool_use_content_block_start":return CT(e,t);case"tool_use_content_block_stop":return IT(e);case"tool_call":return TT(e);case"interrupted":return _T(e,t);default:return Ma.debug(`[Stream Event] ${t.type} (unhandled)`),[e,[]]}};function bT(e,t){const n={type:"conversation_start",uuid:uo(),agentId:t.agentId,timestamp:t.timestamp,transition:{reason:"conversation_started",trigger:"message_start"},data:{userMessage:{}}};return[e,[n]]}function ST(e,t){return[e,[]]}function kT(e,t){const n=t.data.stopReason;if(Ma.debug("message_stop received",{stopReason:n}),n==="tool_use")return Ma.debug("Skipping conversation_end (tool_use in progress)"),[e,[]];const r={type:"conversation_end",uuid:uo(),agentId:t.agentId,timestamp:t.timestamp,transition:{reason:"conversation_completed",trigger:"message_stop"},data:{assistantMessage:{},durationMs:0,durationApiMs:0,numTurns:0,result:"completed",totalCostUsd:0,usage:{input:0,output:0}}};return[e,[r]]}function ET(e,t){const n={type:"conversation_responding",uuid:uo(),agentId:t.agentId,timestamp:Date.now(),transition:{reason:"assistant_responding",trigger:"text_content_block_start"},data:{}};return[e,[n]]}function CT(e,t){const n=[],r={type:"tool_planned",uuid:uo(),agentId:t.agentId,timestamp:t.timestamp,data:{id:t.data.id,name:t.data.name,input:{}}};n.push(r);const o={type:"tool_executing",uuid:uo(),agentId:t.agentId,timestamp:t.timestamp,transition:{reason:"tool_planning_started",trigger:"tool_use_content_block_start"},data:{}};return n.push(o),[e,n]}function IT(e,t){return[e,[]]}function TT(e,t){return[e,[]]}function _T(e,t){Ma.debug("interrupted event received",{reason:t.data.reason});const n={type:"conversation_interrupted",uuid:uo(),agentId:t.agentId,timestamp:t.timestamp,transition:{reason:t.data.reason,trigger:"interrupted"},data:{reason:t.data.reason}};return[e,[n]]}function PT(){return{pendingTurn:null,costPerInputToken:3e-6,costPerOutputToken:15e-6}}function Fu(){return`turn_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function AT(e,t,n){const r=e.input*t,o=e.output*n;return r+o}var RT=(e,t)=>{switch(t.type){case"user_message":return NT(e,t);case"message_stop":return jT(e,t);case"assistant_message":return[e,[]];default:return[e,[]]}};function NT(e,t){const n=Fu(),r={turnId:n,userMessage:t.data,requestedAt:t.timestamp},o={type:"turn_request",uuid:Fu(),agentId:t.agentId,timestamp:Date.now(),turnId:n,data:{userMessage:t.data,requestedAt:t.timestamp}};return[{...e,pendingTurn:r},[o]]}function jT(e,t){if(!e.pendingTurn)return[e,[]];const n=t.data.stopReason;return n==="end_turn"||n==="max_tokens"||n==="stop_sequence"?MT(e,t.agentId,t.timestamp):[e,[]]}function MT(e,t,n){if(!e.pendingTurn)return[e,[]];const{turnId:r,requestedAt:o}=e.pendingTurn,a=n-o,l={input:0,output:0},c=AT(l,e.costPerInputToken,e.costPerOutputToken),d={type:"turn_response",uuid:Fu(),agentId:t,timestamp:Date.now(),turnId:r,data:{assistantMessage:{id:Fu(),role:"assistant",subtype:"assistant",content:"",timestamp:n},respondedAt:n,durationMs:a,usage:l,costUsd:c}};return[{...e,pendingTurn:null},[d]]}var Ky=uT({messageAssembler:dT,stateEventProcessor:wT,turnTracker:RT}),DT=cT({messageAssembler:oh,stateEventProcessor:xT,turnTracker:PT}),da=qt("engine/AgentEngine"),LT=class{constructor(){me(this,"store"),this.store=new lT,da.debug("AgentEngine initialized")}process(e,t){const n=t.type||"unknown";da.debug("Processing event",{agentId:e,eventType:n});const r=!this.store.has(e);let o=this.store.get(e)??DT();r&&da.debug("Created initial state for agent",{agentId:e});const a=[];a.push(t);const[l,c]=Ky(o,t);o=l;for(const d of c){a.push(d);const[f,p]=this.processChained(o,d);o=f,a.push(...p)}return this.store.set(e,o),c.length>0&&da.debug("Produced outputs",{agentId:e,inputEvent:n,outputCount:a.length,processorOutputs:c.length}),a}processChained(e,t){const[n,r]=Ky(e,t);if(r.length===0)return[n,[]];const o=[...r];let a=n;for(const l of r){const[c,d]=this.processChained(a,l);a=c,o.push(...d)}return[a,o]}clearState(e){da.debug("Clearing state",{agentId:e}),this.store.delete(e)}hasState(e){return this.store.has(e)}},sr=qt("agentx/ContainerManager");function zT(){const e=Date.now().toString(36),t=Math.random().toString(36).substring(2,8);return`container_${e}_${t}`}function Yy(){const e=Date.now().toString(36),t=Math.random().toString(36).substring(2,8);return`agent_${e}_${t}`}var OT=class{constructor(e,t){me(this,"agents",new Map),me(this,"engine"),me(this,"runtime"),me(this,"repository"),this.runtime=e,this.repository=t,this.engine=new LT}async create(e){const t=zT(),n=Date.now(),r={containerId:t,createdAt:n,updatedAt:n,config:e};return await this.repository.saveContainer(r),sr.info("Container created",{containerId:t}),r}async get(e){return this.repository.findContainerById(e)}async list(){return this.repository.findAllContainers()}async delete(e){return await this.repository.containerExists(e)?(await this.repository.deleteContainer(e),sr.info("Container deleted",{containerId:e}),!0):!1}async exists(e){return this.repository.containerExists(e)}async run(e,t){if(sr.info("Running agent from image",{imageId:e.imageId,containerId:t}),!await this.repository.findContainerById(t))throw new Error(`Container not found: ${t}`);let r;this.runtime.agentIdResolver?r=await this.runtime.agentIdResolver.resolveForRun(e.imageId,t):r=Yy();const o={agentId:r,createdAt:Date.now()},a=this.runtime.createSandbox(t),l=this.runtime.createDriver(e.definition,o,a),c=new Gy(e.definition,o,this.engine,l,a);return this.agents.set(r,c),sr.info("Agent started",{agentId:r,imageId:e.imageId,containerId:t,definitionName:e.definition.name}),c}async resume(e,t){if(sr.info("Resuming agent from session",{sessionId:e.sessionId,imageId:e.imageId,containerId:t}),!await this.repository.findContainerById(t))throw new Error(`Container not found: ${t}`);const r=await this.repository.findImageById(e.imageId);if(!r)throw new Error(`Image not found: ${e.imageId}`);let o;this.runtime.agentIdResolver?o=await this.runtime.agentIdResolver.resolveForResume(e.sessionId,t):o=Yy();const a={agentId:o,createdAt:Date.now()},l=this.runtime.createSandbox(t),c=r.definition,d=this.runtime.createDriver(c,a,l),f=new Gy(c,a,this.engine,d,l);return this.agents.set(o,f),sr.info("Agent resumed",{agentId:o,sessionId:e.sessionId,imageId:e.imageId,containerId:t}),f}async destroyAgent(e){const t=this.agents.get(e);if(!t){sr.warn("Agent not found for destroy",{agentId:e});return}sr.debug("Destroying agent",{agentId:e}),await t.destroy(),this.agents.delete(e),sr.info("Agent destroyed",{agentId:e})}getAgent(e){return this.agents.get(e)}hasAgent(e){return this.agents.has(e)}listAgents(){return Array.from(this.agents.values())}async destroyAllAgents(){const e=Array.from(this.agents.keys());sr.debug("Destroying all agents",{count:e.length}),await Promise.all(e.map(t=>this.destroyAgent(t))),sr.info("All agents destroyed",{count:e.length})}},Xy=qt("agentx/AgentX");function FT(e,t){if(Xy.info("Creating AgentX instance",{runtime:e.name}),!e.repository)throw new Error("Runtime must have a repository for persistence");const n=e.repository,r=new OT(e,n),o=new JI,a=new qI(n),l=new YI(r),c=new KI(n,r,t==null?void 0:t.containerId),d=new QI(n,r,t==null?void 0:t.containerId);return Xy.debug("AgentX instance created",{runtime:e.name}),{mode:"local",containers:r,definitions:a,images:c,agents:l,sessions:d,errors:o}}var VT=class{constructor(e,t,n={}){this.serverUrl=e,this.agentId=t,this.sseParams=n,me(this,"eventSource",null),me(this,"messageQueue",[]),me(this,"activeIterators",new Set),me(this,"isDone",!1)}connect(){if(this.eventSource)return;let e=`${this.serverUrl}/agents/${this.agentId}/sse`;if(Object.keys(this.sseParams).length>0){const r=new URLSearchParams(this.sseParams);e+=`?${r.toString()}`}this.eventSource=new EventSource(e);const t=r=>{try{const o=JSON.parse(r.data);if(this.activeIterators.size>0){const a=this.activeIterators.values().next().value;a&&(this.activeIterators.delete(a),a.resolve({value:o,done:!1}))}else this.messageQueue.push(o)}catch{}},n=()=>{var r;this.isDone=!0,(r=this.eventSource)==null||r.close(),this.eventSource=null;for(const o of this.activeIterators)o.reject(new Error("SSE connection error"));this.activeIterators.clear()};for(const r of Kx)this.eventSource.addEventListener(r,t);this.eventSource.addEventListener("error",t),this.eventSource.onmessage=t,this.eventSource.onerror=n}createIterator(){const e=this;return{[Symbol.asyncIterator](){let t=!1;return{async next(){if(e.messageQueue.length>0){const n=e.messageQueue.shift();return n.type==="message_stop"&&n.data.stopReason!=="tool_use"&&(t=!0),{value:n,done:!1}}return t?{done:!0,value:void 0}:e.isDone?{done:!0,value:void 0}:new Promise((n,r)=>{const a={resolve:l=>{l.done||l.value.type==="message_stop"&&l.value.data.stopReason!=="tool_use"&&(t=!0),n(l)},reject:r};e.activeIterators.add(a)})},async return(){return{done:!0,value:void 0}}}}}}close(){this.isDone=!0,this.eventSource&&(this.eventSource.close(),this.eventSource=null);for(const e of this.activeIterators)e.reject(new Error("Connection closed"));this.activeIterators.clear(),this.messageQueue=[]}};function BT(e){const{serverUrl:t,agentId:n,headers:r={},sseParams:o={}}=e;let a=null;return{name:"SSEDriver",async*receive(l){var f;a||(a=new VT(t,n,o),a.connect());const c=`${t}/agents/${n}/messages`,d=await fetch(c,{method:"POST",headers:{"Content-Type":"application/json",...r},body:JSON.stringify({content:(typeof l.content=="string",l.content)})});if(!d.ok){const p=await d.json().catch(()=>({}));throw new Error(((f=p.error)==null?void 0:f.message)||`HTTP ${d.status}`)}yield*a.createIterator()},interrupt(){const l=`${t}/agents/${n}/interrupt`;fetch(l,{method:"POST",headers:{"Content-Type":"application/json",...r}}).catch(()=>{})}}}var Qy=qt("agentx/RemoteRepository"),$T=class{constructor(e){me(this,"client"),this.client=mw({baseUrl:e.serverUrl,headers:e.headers}),Qy.debug("RemoteRepository created",{serverUrl:e.serverUrl})}async saveDefinition(e){await this.client.put(`definitions/${e.name}`,{json:e})}async findDefinitionByName(e){try{const t=await this.client.get(`definitions/${e}`).json();return this.parseDefinitionRecord(t)}catch(t){if(this.isNotFound(t))return null;throw t}}async findAllDefinitions(){return(await this.client.get("definitions").json()).map(t=>this.parseDefinitionRecord(t))}async deleteDefinition(e){await this.client.delete(`definitions/${e}`)}async definitionExists(e){try{return await this.client.head(`definitions/${e}`),!0}catch{return!1}}async saveImage(e){await this.client.put(`images/${e.imageId}`,{json:e})}async findImageById(e){try{const t=await this.client.get(`images/${e}`).json();return this.parseImageRecord(t)}catch(t){if(this.isNotFound(t))return null;throw t}}async findAllImages(){return(await this.client.get("images").json()).map(t=>this.parseImageRecord(t))}async deleteImage(e){await this.client.delete(`images/${e}`)}async imageExists(e){try{return await this.client.head(`images/${e}`),!0}catch{return!1}}async saveSession(e){await this.client.put(`sessions/${e.sessionId}`,{json:e})}async findSessionById(e){try{const t=await this.client.get(`sessions/${e}`).json();return this.parseSessionRecord(t)}catch(t){if(this.isNotFound(t))return null;throw t}}async findSessionsByImageId(e){return(await this.client.get(`images/${e}/sessions`).json()).map(n=>this.parseSessionRecord(n))}async findSessionsByUserId(e){return(await this.client.get(`users/${e}/sessions`).json()).map(n=>this.parseSessionRecord(n))}async findAllSessions(){return(await this.client.get("sessions").json()).map(t=>this.parseSessionRecord(t))}async deleteSession(e){await this.client.delete(`sessions/${e}`)}async deleteSessionsByImageId(e){await this.client.delete(`images/${e}/sessions`)}async sessionExists(e){try{return await this.client.head(`sessions/${e}`),!0}catch{return!1}}async saveMessage(e){Qy.debug("saveMessage called (noop in browser)")}async findMessageById(e){try{const t=await this.client.get(`messages/${e}`).json();return this.parseMessageRecord(t)}catch(t){if(this.isNotFound(t))return null;throw t}}async findMessagesBySessionId(e){return(await this.client.get(`sessions/${e}/messages`).json()).map(n=>this.parseMessageRecord(n))}async deleteMessage(e){await this.client.delete(`messages/${e}`)}async deleteMessagesBySessionId(e){await this.client.delete(`sessions/${e}/messages`)}async countMessagesBySessionId(e){return(await this.client.get(`sessions/${e}/messages/count`).json()).count}async saveContainer(e){await this.client.put(`containers/${e.containerId}`,{json:e})}async findContainerById(e){try{const t=await this.client.get(`containers/${e}`).json();return this.parseContainerRecord(t)}catch(t){if(this.isNotFound(t))return null;throw t}}async findAllContainers(){return(await this.client.get("containers").json()).map(t=>this.parseContainerRecord(t))}async deleteContainer(e){await this.client.delete(`containers/${e}`)}async containerExists(e){try{return await this.client.head(`containers/${e}`),!0}catch{return!1}}isNotFound(e){var t;return((t=e==null?void 0:e.response)==null?void 0:t.status)===404}parseDefinitionRecord(e){return{...e,createdAt:new Date(e.createdAt),updatedAt:new Date(e.updatedAt)}}parseImageRecord(e){return{...e,createdAt:new Date(e.createdAt)}}parseSessionRecord(e){return{...e,createdAt:new Date(e.createdAt),updatedAt:new Date(e.updatedAt)}}parseMessageRecord(e){return{...e,createdAt:new Date(e.createdAt)}}parseContainerRecord(e){return{...e}}},Jh=class ba{constructor(t,n={}){me(this,"name"),me(this,"level"),me(this,"collapsed"),this.name=t,this.level=n.level??cn.INFO,this.collapsed=n.collapsed??!0}debug(t,n){this.isDebugEnabled()&&this.log("DEBUG",t,n)}info(t,n){this.isInfoEnabled()&&this.log("INFO",t,n)}warn(t,n){this.isWarnEnabled()&&this.log("WARN",t,n)}error(t,n){this.isErrorEnabled()&&(t instanceof Error?this.log("ERROR",t.message,{...n,stack:t.stack}):this.log("ERROR",t,n))}isDebugEnabled(){return this.level<=cn.DEBUG}isInfoEnabled(){return this.level<=cn.INFO}isWarnEnabled(){return this.level<=cn.WARN}isErrorEnabled(){return this.level<=cn.ERROR}log(t,n,r){const o=new Date().toLocaleTimeString(),a=this.getConsoleMethod(t),l=ba.BADGE_STYLES[t],c=`%c${o} %c${t}%c %c[${this.name}]%c ${n}`,d=[ba.STYLES.TIMESTAMP,l,"",ba.STYLES.NAME,ba.STYLES.MESSAGE];r&&Object.keys(r).length>0?((this.collapsed?console.groupCollapsed:console.group).call(console,c,...d),console.log("Context:",r),console.groupEnd()):a(c,...d)}getConsoleMethod(t){switch(t){case"DEBUG":return console.debug.bind(console);case"INFO":return console.info.bind(console);case"WARN":return console.warn.bind(console);case"ERROR":return console.error.bind(console);default:return console.log.bind(console)}}};me(Jh,"STYLES",{DEBUG:"color: #6B7280; font-weight: normal;",INFO:"color: #10B981; font-weight: normal;",WARN:"color: #F59E0B; font-weight: bold;",ERROR:"color: #EF4444; font-weight: bold;",TIMESTAMP:"color: #9CA3AF; font-weight: normal;",NAME:"color: #8B5CF6; font-weight: normal;",MESSAGE:"color: inherit; font-weight: normal;"});me(Jh,"BADGE_STYLES",{DEBUG:"background: #E5E7EB; color: #374151; padding: 2px 6px; border-radius: 3px; font-size: 11px;",INFO:"background: #D1FAE5; color: #065F46; padding: 2px 6px; border-radius: 3px; font-size: 11px;",WARN:"background: #FEF3C7; color: #92400E; padding: 2px 6px; border-radius: 3px; font-size: 11px;",ERROR:"background: #FEE2E2; color: #991B1B; padding: 2px 6px; border-radius: 3px; font-size: 11px;"});var UT=Jh,HT=class{constructor(e={}){me(this,"options"),me(this,"loggers",new Map),this.options=e}getLogger(e){if(this.loggers.has(e))return this.loggers.get(e);const t=new UT(e,this.options);return this.loggers.set(e,t),t}},gu=qt("agentx/RemoteAgentIdResolver"),WT=class{constructor(e){me(this,"client"),this.client=mw({baseUrl:e.serverUrl,headers:e.headers})}async resolveForRun(e,t){gu.debug("Resolving agent ID for run",{imageId:e,containerId:t});const n=await this.client.post(`images/${e}/run`,{json:{containerId:t}}).json();return gu.info("Agent ID resolved for run",{imageId:e,agentId:n.agentId}),n.agentId}async resolveForResume(e,t){gu.debug("Resolving agent ID for resume",{sessionId:e,containerId:t});const n=await this.client.post(`sessions/${e}/resume`,{json:{containerId:t}}).json();return gu.info("Agent ID resolved for resume",{sessionId:e,agentId:n.agentId}),n.agentId}},Jy={name:"browser-noop",workspace:{id:"noop",name:"noop",path:""},llm:{name:"noop",provide:()=>({})}},qT=class{constructor(e){me(this,"name","sse"),me(this,"repository"),me(this,"loggerFactory"),me(this,"agentIdResolver"),me(this,"serverUrl"),me(this,"headers"),me(this,"sseParams"),this.serverUrl=e.serverUrl.replace(/\/+$/,""),this.headers=e.headers??{},this.sseParams=e.sseParams??{},this.loggerFactory=new HT({collapsed:!0}),nI(this.loggerFactory),this.repository=new $T({serverUrl:this.serverUrl,headers:this.headers}),this.agentIdResolver=new WT({serverUrl:this.serverUrl,headers:this.headers})}createSandbox(e){return Jy}createDriver(e,t,n){return{...BT({serverUrl:this.serverUrl,agentId:t.agentId,headers:this.headers,sseParams:this.sseParams}),sandbox:Jy}}createLogger(e){return this.loggerFactory.getLogger(e)}};function GT(e){return new qT(e)}var KT=Object.defineProperty,YT=(e,t,n)=>t in e?KT(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Zy=(e,t,n)=>YT(e,typeof t!="symbol"?t+"":t,n);function XT(e,t={}){const{initialMessages:n=[],onSend:r,onError:o,onStatusChange:a}=t,[l,c]=I.useState(n),[d,f]=I.useState(""),[p,m]=I.useState((e==null?void 0:e.state)??"idle"),[y,v]=I.useState([]),b=I.useRef(!0),S=p==="queued"||p==="responding"||p==="thinking"||p==="planning_tool"||p==="awaiting_tool_result"||p==="conversation_active";I.useEffect(()=>{c([]),f(""),v([]),m((e==null?void 0:e.state)??"idle")},[e]),I.useEffect(()=>{if(!e)return;b.current=!0;const O=e.react({onTextDelta:N=>{b.current&&f(D=>D+N.data.text)},onAssistantMessage:N=>{if(!b.current)return;const D=N.data;f(""),c(H=>H.some(ee=>ee.id===D.id)?H:[...H,D])},onToolCallMessage:N=>{if(!b.current)return;const D=N.data;c(H=>H.some(ee=>ee.id===D.id)?H:[...H,D])},onToolResultMessage:N=>{if(!b.current)return;const D=N.data;c(H=>H.some(ee=>ee.id===D.id)?H:[...H,D])},onError:N=>{if(!b.current)return;const D=N.data.error;v(H=>[...H,D]),f(""),o==null||o(D)}}),V=e.onStateChange(N=>{b.current&&(m(N.current),a==null||a(N.current))});return m(e.state),()=>{b.current=!1,O(),V()}},[e,o,a]);const C=I.useCallback(O=>{if(!e)return;v([]),r==null||r(O);const V={id:`msg_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,role:"user",subtype:"user",content:O,timestamp:Date.now()};c(N=>[...N,V]),e.receive(O).catch(()=>{})},[e,r]),E=I.useCallback(()=>{e==null||e.interrupt()},[e]),P=I.useCallback(()=>{c([]),f("")},[]),T=I.useCallback(()=>{v([])},[]);return{messages:l,streaming:d,status:p,errors:y,send:C,interrupt:E,isLoading:S,clearMessages:P,clearErrors:T}}function ev(e){return{sessionId:e.sessionId,userId:e.userId,imageId:e.imageId,title:e.title,createdAt:e.createdAt,updatedAt:e.updatedAt}}function QT(e,t,n={}){const{autoLoad:r=!0,onSessionChange:o,onSessionsChange:a}=n,[l,c]=I.useState([]),[d,f]=I.useState(null),[p,m]=I.useState(!1),[y,v]=I.useState(null),b=I.useCallback(async()=>{if(!(!e||!("sessions"in e))){m(!0),v(null);try{const O=(await e.sessions.listByUser(t)).map(ev);c(O),a==null||a(O)}catch(T){v(T instanceof Error?T:new Error(String(T)))}finally{m(!1)}}},[e,t,a]);I.useEffect(()=>{r&&b()},[r,b]);const S=I.useCallback(T=>{f(T),o==null||o(T)},[o]),C=I.useCallback(async(T,O)=>{if(!e||!("sessions"in e))throw new Error("AgentX sessions not available");m(!0),v(null);try{const V=await e.sessions.create(T,t);O&&await V.setTitle(O);const N=ev(V);return c(D=>[N,...D]),a==null||a([N,...l]),N}catch(V){const N=V instanceof Error?V:new Error(String(V));throw v(N),N}finally{m(!1)}},[e,t,l,a]),E=I.useCallback(async T=>{if(!e||!("sessions"in e))throw new Error("AgentX sessions not available");m(!0),v(null);try{await e.sessions.destroy(T);const O=l.filter(V=>V.sessionId!==T);c(O),a==null||a(O),(d==null?void 0:d.sessionId)===T&&(f(null),o==null||o(null))}catch(O){const V=O instanceof Error?O:new Error(String(O));throw v(V),V}finally{m(!1)}},[e,l,d,o,a]),P=I.useCallback(async(T,O)=>{if(!e||!("sessions"in e))throw new Error("AgentX sessions not available");v(null);try{const V=await e.sessions.get(T);if(V){await V.setTitle(O);const N=Date.now();c(D=>D.map(H=>H.sessionId===T?{...H,title:O,updatedAt:N}:H)),(d==null?void 0:d.sessionId)===T&&f(D=>D&&{...D,title:O,updatedAt:N})}}catch(V){const N=V instanceof Error?V:new Error(String(V));throw v(N),N}},[e,d]);return{sessions:l,currentSession:d,selectSession:S,createSession:C,deleteSession:E,setSessionTitle:P,refresh:b,isLoading:p,error:y}}/**
54
54
  * @license lucide-react v0.460.0 - ISC
55
55
  *
56
56
  * This source code is licensed under the ISC license.
@@ -242,4 +242,4 @@ ${c.stack||""}`:JSON.stringify(c,null,2)})]})]})})]})})}function v3({messages:e,
242
242
  Licensed under the MIT License (MIT), see
243
243
  http://jedwatson.github.io/classnames
244
244
  */var Lf,hx,px,k3=(dx||(dx=1,Lf=fx,(function(){var e={}.hasOwnProperty;function t(){for(var n=[],r=0;r<arguments.length;r++){var o=arguments[r];if(o){var a=typeof o;if(a==="string"||a==="number")n.push(o);else if(Array.isArray(o)){if(o.length){var l=t.apply(null,o);l&&n.push(l)}}else if(a==="object")if(o.toString===Object.prototype.toString)for(var c in o)e.call(o,c)&&o[c]&&n.push(c);else n.push(o.toString())}}return n.join(" ")}Lf.exports?(t.default=t,Lf.exports=t):window.classNames=t})()),fx.exports),Vh=el(k3),mx,lr=el((function(){if(px)return hx;px=1;var e=/^\s+|\s+$/g,t=/^[-+]0x[0-9a-f]+$/i,n=/^0b[01]+$/i,r=/^0o[0-7]+$/i,o=parseInt,a=Object.prototype.toString;function l(d){var f=typeof d;return!!d&&(f=="object"||f=="function")}function c(d){if(typeof d=="number")return d;if((function(m){return typeof m=="symbol"||(function(y){return!!y&&typeof y=="object"})(m)&&a.call(m)=="[object Symbol]"})(d))return NaN;if(l(d)){var f=typeof d.valueOf=="function"?d.valueOf():d;d=l(f)?f+"":f}if(typeof d!="string")return d===0?d:+d;d=d.replace(e,"");var p=n.test(d);return p||r.test(d)?o(d.slice(2),p?2:8):t.test(d)?NaN:+d}return hx=function(d,f,p){return p===void 0&&(p=f,f=void 0),p!==void 0&&(p=(p=c(p))==p?p:0),f!==void 0&&(f=(f=c(f))==f?f:0),(function(m,y,v){return m==m&&(v!==void 0&&(m=m<=v?m:v),y!==void 0&&(m=m>=y?m:y)),m})(c(d),f,p)}})()),zf={exports:{}},E3=(mx||(mx=1,(function(e,t){var n="__lodash_hash_undefined__",r=9007199254740991,o="[object Arguments]",a="[object Array]",l="[object Boolean]",c="[object Date]",d="[object Error]",f="[object Function]",p="[object Map]",m="[object Number]",y="[object Object]",v="[object Promise]",b="[object RegExp]",S="[object Set]",C="[object String]",E="[object Symbol]",P="[object WeakMap]",T="[object ArrayBuffer]",O="[object DataView]",V=/^\[object .+?Constructor\]$/,N=/^(?:0|[1-9]\d*)$/,D={};D["[object Float32Array]"]=D["[object Float64Array]"]=D["[object Int8Array]"]=D["[object Int16Array]"]=D["[object Int32Array]"]=D["[object Uint8Array]"]=D["[object Uint8ClampedArray]"]=D["[object Uint16Array]"]=D["[object Uint32Array]"]=!0,D[o]=D[a]=D[T]=D[l]=D[O]=D[c]=D[d]=D[f]=D[p]=D[m]=D[y]=D[b]=D[S]=D[C]=D[P]=!1;var H=typeof _i=="object"&&_i&&_i.Object===Object&&_i,ee=typeof self=="object"&&self&&self.Object===Object&&self,L=H||ee||Function("return this")(),te=t&&!t.nodeType&&t,G=te&&e&&!e.nodeType&&e,X=G&&G.exports===te,Q=X&&H.process,re=(function(){try{return Q&&Q.binding&&Q.binding("util")}catch{}})(),fe=re&&re.isTypedArray;function oe(F,q){for(var ce=-1,we=F==null?0:F.length;++ce<we;)if(q(F[ce],ce,F))return!0;return!1}function U(F){var q=-1,ce=Array(F.size);return F.forEach(function(we,Ye){ce[++q]=[Ye,we]}),ce}function se(F){var q=-1,ce=Array(F.size);return F.forEach(function(we){ce[++q]=we}),ce}var _,j,Y,A=Array.prototype,Se=Function.prototype,Te=Object.prototype,ke=L["__core-js_shared__"],ze=Se.toString,de=Te.hasOwnProperty,he=(_=/[^.]+$/.exec(ke&&ke.keys&&ke.keys.IE_PROTO||""))?"Symbol(src)_1."+_:"",Ne=Te.toString,Ke=RegExp("^"+ze.call(de).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Mi=X?L.Buffer:void 0,Kn=L.Symbol,Yr=L.Uint8Array,Xr=Te.propertyIsEnumerable,Di=A.splice,en=Kn?Kn.toStringTag:void 0,Li=Object.getOwnPropertySymbols,Qr=Mi?Mi.isBuffer:void 0,fr=(j=Object.keys,Y=Object,function(F){return j(Y(F))}),Cn=Pr(L,"DataView"),Yn=Pr(L,"Map"),Jr=Pr(L,"Promise"),Zr=Pr(L,"Set"),ei=Pr(L,"WeakMap"),K=Pr(Object,"create"),ue=Ar(Cn),_e=Ar(Yn),Le=Ar(Jr),Be=Ar(Zr),St=Ar(ei),In=Kn?Kn.prototype:void 0,Lt=In?In.valueOf:void 0;function zt(F){var q=-1,ce=F==null?0:F.length;for(this.clear();++q<ce;){var we=F[q];this.set(we[0],we[1])}}function Rt(F){var q=-1,ce=F==null?0:F.length;for(this.clear();++q<ce;){var we=F[q];this.set(we[0],we[1])}}function et(F){var q=-1,ce=F==null?0:F.length;for(this.clear();++q<ce;){var we=F[q];this.set(we[0],we[1])}}function Kt(F){var q=-1,ce=F==null?0:F.length;for(this.__data__=new et;++q<ce;)this.add(F[q])}function ft(F){var q=this.__data__=new Rt(F);this.size=q.size}function Eo(F,q){var ce=Rr(F),we=!ce&&vs(F),Ye=!ce&&!we&&Fi(F),Oe=!ce&&!we&&!Ye&&_o(F),it=ce||we||Ye||Oe,je=it?(function(ht,Yt){for(var Xn=-1,It=Array(ht);++Xn<ht;)It[Xn]=Yt(Xn);return It})(F.length,String):[],pn=je.length;for(var lt in F)!de.call(F,lt)||it&&(lt=="length"||Ye&&(lt=="offset"||lt=="parent")||Oe&&(lt=="buffer"||lt=="byteLength"||lt=="byteOffset")||Oi(lt,pn))||je.push(lt);return je}function ti(F,q){for(var ce=F.length;ce--;)if(ri(F[ce][0],q))return ce;return-1}function Tn(F){return F==null?F===void 0?"[object Undefined]":"[object Null]":en&&en in Object(F)?(function(q){var ce=de.call(q,en),we=q[en];try{q[en]=void 0;var Ye=!0}catch{}var Oe=Ne.call(q);return Ye&&(ce?q[en]=we:delete q[en]),Oe})(F):(function(q){return Ne.call(q)})(F)}function _r(F){return hn(F)&&Tn(F)==o}function Co(F,q,ce,we,Ye){return F===q||(F==null||q==null||!hn(F)&&!hn(q)?F!=F&&q!=q:(function(Oe,it,je,pn,lt,ht){var Yt=Rr(Oe),Xn=Rr(it),It=Yt?a:_n(Oe),tn=Xn?a:_n(it),Nt=(It=It==o?y:It)==y,xs=(tn=tn==o?y:tn)==y,Tt=It==tn;if(Tt&&Fi(Oe)){if(!Fi(it))return!1;Yt=!0,Nt=!1}if(Tt&&!Nt)return ht||(ht=new ft),Yt||_o(Oe)?Io(Oe,it,je,pn,lt,ht):(function(qe,$e,Nr,hr,Po,Ot,Pn){switch(Nr){case O:if(qe.byteLength!=$e.byteLength||qe.byteOffset!=$e.byteOffset)return!1;qe=qe.buffer,$e=$e.buffer;case T:return!(qe.byteLength!=$e.byteLength||!Ot(new Yr(qe),new Yr($e)));case l:case c:case m:return ri(+qe,+$e);case d:return qe.name==$e.name&&qe.message==$e.message;case b:case C:return qe==$e+"";case p:var An=U;case S:var Qn=1&hr;if(An||(An=se),qe.size!=$e.size&&!Qn)return!1;var bs=Pn.get(qe);if(bs)return bs==$e;hr|=2,Pn.set(qe,$e);var Bi=Io(An(qe),An($e),hr,Po,Ot,Pn);return Pn.delete(qe),Bi;case E:if(Lt)return Lt.call(qe)==Lt.call($e)}return!1})(Oe,it,It,je,pn,lt,ht);if(!(1&je)){var Vi=Nt&&de.call(Oe,"__wrapped__"),al=xs&&de.call(it,"__wrapped__");if(Vi||al){var mc=Vi?Oe.value():Oe,ws=al?it.value():it;return ht||(ht=new ft),lt(mc,ws,je,pn,ht)}}return!!Tt&&(ht||(ht=new ft),(function(qe,$e,Nr,hr,Po,Ot){var Pn=1&Nr,An=To(qe),Qn=An.length,bs=To($e),Bi=bs.length;if(Qn!=Bi&&!Pn)return!1;for(var Ue=Qn;Ue--;){var pr=An[Ue];if(!(Pn?pr in $e:de.call($e,pr)))return!1}var Ao=Ot.get(qe);if(Ao&&Ot.get($e))return Ao==$e;var ii=!0;Ot.set(qe,$e),Ot.set($e,qe);for(var Ss=Pn;++Ue<Qn;){var $i=qe[pr=An[Ue]],Ui=$e[pr];if(hr)var ks=Pn?hr(Ui,$i,pr,$e,qe,Ot):hr($i,Ui,pr,qe,$e,Ot);if(!(ks===void 0?$i===Ui||Po($i,Ui,Nr,hr,Ot):ks)){ii=!1;break}Ss||(Ss=pr=="constructor")}if(ii&&!Ss){var jr=qe.constructor,mn=$e.constructor;jr==mn||!("constructor"in qe)||!("constructor"in $e)||typeof jr=="function"&&jr instanceof jr&&typeof mn=="function"&&mn instanceof mn||(ii=!1)}return Ot.delete(qe),Ot.delete($e),ii})(Oe,it,je,pn,lt,ht))})(F,q,ce,we,Co,Ye))}function tl(F){return!(!sl(F)||(function(q){return!!he&&he in q})(F))&&(rl(F)?Ke:V).test(Ar(F))}function nl(F){if(ce=(q=F)&&q.constructor,we=typeof ce=="function"&&ce.prototype||Te,q!==we)return fr(F);var q,ce,we,Ye=[];for(var Oe in Object(F))de.call(F,Oe)&&Oe!="constructor"&&Ye.push(Oe);return Ye}function Io(F,q,ce,we,Ye,Oe){var it=1&ce,je=F.length,pn=q.length;if(je!=pn&&!(it&&pn>je))return!1;var lt=Oe.get(F);if(lt&&Oe.get(q))return lt==q;var ht=-1,Yt=!0,Xn=2&ce?new Kt:void 0;for(Oe.set(F,q),Oe.set(q,F);++ht<je;){var It=F[ht],tn=q[ht];if(we)var Nt=it?we(tn,It,ht,q,F,Oe):we(It,tn,ht,F,q,Oe);if(Nt!==void 0){if(Nt)continue;Yt=!1;break}if(Xn){if(!oe(q,function(xs,Tt){if(Vi=Tt,!Xn.has(Vi)&&(It===xs||Ye(It,xs,ce,we,Oe)))return Xn.push(Tt);var Vi})){Yt=!1;break}}else if(It!==tn&&!Ye(It,tn,ce,we,Oe)){Yt=!1;break}}return Oe.delete(F),Oe.delete(q),Yt}function To(F){return(function(q,ce,we){var Ye=ce(q);return Rr(q)?Ye:(function(Oe,it){for(var je=-1,pn=it.length,lt=Oe.length;++je<pn;)Oe[lt+je]=it[je];return Oe})(Ye,we(q))})(F,ol,zi)}function ni(F,q){var ce,we,Ye=F.__data__;return((we=typeof(ce=q))=="string"||we=="number"||we=="symbol"||we=="boolean"?ce!=="__proto__":ce===null)?Ye[typeof q=="string"?"string":"hash"]:Ye.map}function Pr(F,q){var ce=(function(we,Ye){return we==null?void 0:we[Ye]})(F,q);return tl(ce)?ce:void 0}zt.prototype.clear=function(){this.__data__=K?K(null):{},this.size=0},zt.prototype.delete=function(F){var q=this.has(F)&&delete this.__data__[F];return this.size-=q?1:0,q},zt.prototype.get=function(F){var q=this.__data__;if(K){var ce=q[F];return ce===n?void 0:ce}return de.call(q,F)?q[F]:void 0},zt.prototype.has=function(F){var q=this.__data__;return K?q[F]!==void 0:de.call(q,F)},zt.prototype.set=function(F,q){var ce=this.__data__;return this.size+=this.has(F)?0:1,ce[F]=K&&q===void 0?n:q,this},Rt.prototype.clear=function(){this.__data__=[],this.size=0},Rt.prototype.delete=function(F){var q=this.__data__,ce=ti(q,F);return!(ce<0||(ce==q.length-1?q.pop():Di.call(q,ce,1),--this.size,0))},Rt.prototype.get=function(F){var q=this.__data__,ce=ti(q,F);return ce<0?void 0:q[ce][1]},Rt.prototype.has=function(F){return ti(this.__data__,F)>-1},Rt.prototype.set=function(F,q){var ce=this.__data__,we=ti(ce,F);return we<0?(++this.size,ce.push([F,q])):ce[we][1]=q,this},et.prototype.clear=function(){this.size=0,this.__data__={hash:new zt,map:new(Yn||Rt),string:new zt}},et.prototype.delete=function(F){var q=ni(this,F).delete(F);return this.size-=q?1:0,q},et.prototype.get=function(F){return ni(this,F).get(F)},et.prototype.has=function(F){return ni(this,F).has(F)},et.prototype.set=function(F,q){var ce=ni(this,F),we=ce.size;return ce.set(F,q),this.size+=ce.size==we?0:1,this},Kt.prototype.add=Kt.prototype.push=function(F){return this.__data__.set(F,n),this},Kt.prototype.has=function(F){return this.__data__.has(F)},ft.prototype.clear=function(){this.__data__=new Rt,this.size=0},ft.prototype.delete=function(F){var q=this.__data__,ce=q.delete(F);return this.size=q.size,ce},ft.prototype.get=function(F){return this.__data__.get(F)},ft.prototype.has=function(F){return this.__data__.has(F)},ft.prototype.set=function(F,q){var ce=this.__data__;if(ce instanceof Rt){var we=ce.__data__;if(!Yn||we.length<199)return we.push([F,q]),this.size=++ce.size,this;ce=this.__data__=new et(we)}return ce.set(F,q),this.size=ce.size,this};var zi=Li?function(F){return F==null?[]:(F=Object(F),(function(q,ce){for(var we=-1,Ye=q==null?0:q.length,Oe=0,it=[];++we<Ye;){var je=q[we];ce(je,we,q)&&(it[Oe++]=je)}return it})(Li(F),function(q){return Xr.call(F,q)}))}:function(){return[]},_n=Tn;function Oi(F,q){return!!(q=q??r)&&(typeof F=="number"||N.test(F))&&F>-1&&F%1==0&&F<q}function Ar(F){if(F!=null){try{return ze.call(F)}catch{}try{return F+""}catch{}}return""}function ri(F,q){return F===q||F!=F&&q!=q}(Cn&&_n(new Cn(new ArrayBuffer(1)))!=O||Yn&&_n(new Yn)!=p||Jr&&_n(Jr.resolve())!=v||Zr&&_n(new Zr)!=S||ei&&_n(new ei)!=P)&&(_n=function(F){var q=Tn(F),ce=q==y?F.constructor:void 0,we=ce?Ar(ce):"";if(we)switch(we){case ue:return O;case _e:return p;case Le:return v;case Be:return S;case St:return P}return q});var vs=_r((function(){return arguments})())?_r:function(F){return hn(F)&&de.call(F,"callee")&&!Xr.call(F,"callee")},Rr=Array.isArray,Fi=Qr||function(){return!1};function rl(F){if(!sl(F))return!1;var q=Tn(F);return q==f||q=="[object GeneratorFunction]"||q=="[object AsyncFunction]"||q=="[object Proxy]"}function il(F){return typeof F=="number"&&F>-1&&F%1==0&&F<=r}function sl(F){var q=typeof F;return F!=null&&(q=="object"||q=="function")}function hn(F){return F!=null&&typeof F=="object"}var _o=fe?(function(F){return function(q){return F(q)}})(fe):function(F){return hn(F)&&il(F.length)&&!!D[Tn(F)]};function ol(F){return(q=F)!=null&&il(q.length)&&!rl(q)?Eo(F):nl(F);var q}e.exports=function(F,q){return Co(F,q)}})(zf,zf.exports)),zf.exports),C3=el(E3);function gx(e,t,n){return e[t]?e[t][0]?e[t][0][n]:e[t][n]:t==="contentBoxSize"?e.contentRect[n==="inlineSize"?"width":"height"]:void 0}function I3(e){e===void 0&&(e={});var t=e.onResize,n=I.useRef(void 0);n.current=t;var r=e.round||Math.round,o=I.useRef(),a=I.useState({width:void 0,height:void 0}),l=a[0],c=a[1],d=I.useRef(!1);I.useEffect(function(){return d.current=!1,function(){d.current=!0}},[]);var f=I.useRef({width:void 0,height:void 0}),p=(function(m,y){var v=I.useRef(null),b=I.useRef(null);b.current=y;var S=I.useRef(null);I.useEffect(function(){C()});var C=I.useCallback(function(){var E=S.current,P=b.current,T=E||(P?P instanceof Element?P:P.current:null);v.current&&v.current.element===T&&v.current.subscriber===m||(v.current&&v.current.cleanup&&v.current.cleanup(),v.current={element:T,subscriber:m,cleanup:T?m(T):void 0})},[m]);return I.useEffect(function(){return function(){v.current&&v.current.cleanup&&(v.current.cleanup(),v.current=null)}},[]),I.useCallback(function(E){S.current=E,C()},[C])})(I.useCallback(function(m){return o.current&&o.current.box===e.box&&o.current.round===r||(o.current={box:e.box,round:r,instance:new ResizeObserver(function(y){var v=y[0],b=e.box==="border-box"?"borderBoxSize":e.box==="device-pixel-content-box"?"devicePixelContentBoxSize":"contentBoxSize",S=gx(v,b,"inlineSize"),C=gx(v,b,"blockSize"),E=S?r(S):void 0,P=C?r(C):void 0;if(f.current.width!==E||f.current.height!==P){var T={width:E,height:P};f.current.width=E,f.current.height=P,n.current?n.current(T):d.current||c(T)}})}),o.current.instance.observe(m,{box:e.box}),function(){o.current&&o.current.instance.unobserve(m)}},[e.box,r]),e.ref);return I.useMemo(function(){return{ref:p,width:l.width,height:l.height}},[p,l.width,l.height])}var T3="allotment-module_splitView__L-yRc",_3="allotment-module_sashContainer__fzwJF",P3="allotment-module_splitViewContainer__rQnVa",fS="allotment-module_splitViewView__MGZ6O",A3="allotment-module_vertical__WSwwa",R3="allotment-module_horizontal__7doS8",N3="allotment-module_separatorBorder__x-rDS";let xa,hS=!1,pS=!1;typeof navigator=="object"&&(xa=navigator.userAgent,pS=xa.indexOf("Macintosh")>=0,hS=(xa.indexOf("Macintosh")>=0||xa.indexOf("iPad")>=0||xa.indexOf("iPhone")>=0)&&!!navigator.maxTouchPoints&&navigator.maxTouchPoints>0);const mS=hS,j3=pS,yx=typeof window<"u"&&window.document!==void 0&&window.document.createElement!==void 0?I.useLayoutEffect:I.useEffect;class M3{constructor(){this._size=void 0}getSize(){return this._size}setSize(t){this._size=t}}function Cu(e,t){const n=e.length,r=n-t.length;return r>=0&&e.slice(r,n)===t}var vx,xx={exports:{}},wx,bx,D3=(vx||(vx=1,(function(e){var t=Object.prototype.hasOwnProperty,n="~";function r(){}function o(d,f,p){this.fn=d,this.context=f,this.once=p||!1}function a(d,f,p,m,y){if(typeof p!="function")throw new TypeError("The listener must be a function");var v=new o(p,m||d,y),b=n?n+f:f;return d._events[b]?d._events[b].fn?d._events[b]=[d._events[b],v]:d._events[b].push(v):(d._events[b]=v,d._eventsCount++),d}function l(d,f){--d._eventsCount==0?d._events=new r:delete d._events[f]}function c(){this._events=new r,this._eventsCount=0}Object.create&&(r.prototype=Object.create(null),new r().__proto__||(n=!1)),c.prototype.eventNames=function(){var d,f,p=[];if(this._eventsCount===0)return p;for(f in d=this._events)t.call(d,f)&&p.push(n?f.slice(1):f);return Object.getOwnPropertySymbols?p.concat(Object.getOwnPropertySymbols(d)):p},c.prototype.listeners=function(d){var f=n?n+d:d,p=this._events[f];if(!p)return[];if(p.fn)return[p.fn];for(var m=0,y=p.length,v=new Array(y);m<y;m++)v[m]=p[m].fn;return v},c.prototype.listenerCount=function(d){var f=n?n+d:d,p=this._events[f];return p?p.fn?1:p.length:0},c.prototype.emit=function(d,f,p,m,y,v){var b=n?n+d:d;if(!this._events[b])return!1;var S,C,E=this._events[b],P=arguments.length;if(E.fn){switch(E.once&&this.removeListener(d,E.fn,void 0,!0),P){case 1:return E.fn.call(E.context),!0;case 2:return E.fn.call(E.context,f),!0;case 3:return E.fn.call(E.context,f,p),!0;case 4:return E.fn.call(E.context,f,p,m),!0;case 5:return E.fn.call(E.context,f,p,m,y),!0;case 6:return E.fn.call(E.context,f,p,m,y,v),!0}for(C=1,S=new Array(P-1);C<P;C++)S[C-1]=arguments[C];E.fn.apply(E.context,S)}else{var T,O=E.length;for(C=0;C<O;C++)switch(E[C].once&&this.removeListener(d,E[C].fn,void 0,!0),P){case 1:E[C].fn.call(E[C].context);break;case 2:E[C].fn.call(E[C].context,f);break;case 3:E[C].fn.call(E[C].context,f,p);break;case 4:E[C].fn.call(E[C].context,f,p,m);break;default:if(!S)for(T=1,S=new Array(P-1);T<P;T++)S[T-1]=arguments[T];E[C].fn.apply(E[C].context,S)}}return!0},c.prototype.on=function(d,f,p){return a(this,d,f,p,!1)},c.prototype.once=function(d,f,p){return a(this,d,f,p,!0)},c.prototype.removeListener=function(d,f,p,m){var y=n?n+d:d;if(!this._events[y])return this;if(!f)return l(this,y),this;var v=this._events[y];if(v.fn)v.fn!==f||m&&!v.once||p&&v.context!==p||l(this,y);else{for(var b=0,S=[],C=v.length;b<C;b++)(v[b].fn!==f||m&&!v[b].once||p&&v[b].context!==p)&&S.push(v[b]);S.length?this._events[y]=S.length===1?S[0]:S:l(this,y)}return this},c.prototype.removeAllListeners=function(d){var f;return d?(f=n?n+d:d,this._events[f]&&l(this,f)):(this._events=new r,this._eventsCount=0),this},c.prototype.off=c.prototype.removeListener,c.prototype.addListener=c.prototype.on,c.prefixed=n,c.EventEmitter=c,e.exports=c})(xx)),xx.exports),em=el(D3);function Sx(e,t){const n=e.indexOf(t);n>-1&&(e.splice(n,1),e.unshift(t))}function Of(e,t){const n=e.indexOf(t);n>-1&&(e.splice(n,1),e.push(t))}function On(e,t,n=1){const r=Math.max(0,Math.ceil((t-e)/n)),o=new Array(r);let a=-1;for(;++a<r;)o[a]=e+a*n;return o}var L3=el((function(){if(bx)return wx;bx=1;var e=/^\s+|\s+$/g,t=/^[-+]0x[0-9a-f]+$/i,n=/^0b[01]+$/i,r=/^0o[0-7]+$/i,o=parseInt,a=typeof _i=="object"&&_i&&_i.Object===Object&&_i,l=typeof self=="object"&&self&&self.Object===Object&&self,c=a||l||Function("return this")(),d=Object.prototype.toString,f=Math.max,p=Math.min,m=function(){return c.Date.now()};function y(b){var S=typeof b;return!!b&&(S=="object"||S=="function")}function v(b){if(typeof b=="number")return b;if((function(E){return typeof E=="symbol"||(function(P){return!!P&&typeof P=="object"})(E)&&d.call(E)=="[object Symbol]"})(b))return NaN;if(y(b)){var S=typeof b.valueOf=="function"?b.valueOf():b;b=y(S)?S+"":S}if(typeof b!="string")return b===0?b:+b;b=b.replace(e,"");var C=n.test(b);return C||r.test(b)?o(b.slice(2),C?2:8):t.test(b)?NaN:+b}return wx=function(b,S,C){var E,P,T,O,V,N,D=0,H=!1,ee=!1,L=!0;if(typeof b!="function")throw new TypeError("Expected a function");function te(fe){var oe=E,U=P;return E=P=void 0,D=fe,O=b.apply(U,oe)}function G(fe){var oe=fe-N;return N===void 0||oe>=S||oe<0||ee&&fe-D>=T}function X(){var fe=m();if(G(fe))return Q(fe);V=setTimeout(X,(function(oe){var U=S-(oe-N);return ee?p(U,T-(oe-D)):U})(fe))}function Q(fe){return V=void 0,L&&E?te(fe):(E=P=void 0,O)}function re(){var fe=m(),oe=G(fe);if(E=arguments,P=this,N=fe,oe){if(V===void 0)return(function(U){return D=U,V=setTimeout(X,S),H?te(U):O})(N);if(ee)return V=setTimeout(X,S),te(N)}return V===void 0&&(V=setTimeout(X,S)),O}return S=v(S)||0,y(C)&&(H=!!C.leading,T=(ee="maxWait"in C)?f(v(C.maxWait)||0,S):T,L="trailing"in C?!!C.trailing:L),re.cancel=function(){V!==void 0&&clearTimeout(V),D=0,E=N=P=V=void 0},re.flush=function(){return V===void 0?O:Q(m())},re}})()),z3="sash-module_sash__K-9lB",O3="sash-module_disabled__Hm-wx",F3="sash-module_mac__Jf6OJ",kx="sash-module_vertical__pB-rs",V3="sash-module_minimum__-UKxp",B3="sash-module_maximum__TCWxD",Ex="sash-module_horizontal__kFbiw",Ff="sash-module_hover__80W6I",Vf="sash-module_active__bJspD";let Hn=(function(e){return e.Vertical="VERTICAL",e.Horizontal="HORIZONTAL",e})({}),kn=(function(e){return e.Disabled="DISABLED",e.Minimum="MINIMUM",e.Maximum="MAXIMUM",e.Enabled="ENABLED",e})({}),gS=mS?20:8;const yS=new em;class Cx extends em{get state(){return this._state}set state(t){this._state!==t&&(this.el.classList.toggle(O3,t===kn.Disabled),this.el.classList.toggle("sash-disabled",t===kn.Disabled),this.el.classList.toggle(V3,t===kn.Minimum),this.el.classList.toggle("sash-minimum",t===kn.Minimum),this.el.classList.toggle(B3,t===kn.Maximum),this.el.classList.toggle("sash-maximum",t===kn.Maximum),this._state=t,this.emit("enablementChange",t))}constructor(t,n,r){var o;super(),this.el=void 0,this.layoutProvider=void 0,this.orientation=void 0,this.size=void 0,this.hoverDelay=300,this.hoverDelayer=L3(a=>a.classList.add("sash-hover",Ff),this.hoverDelay),this._state=kn.Enabled,this.onPointerStart=a=>{const l=a.pageX,c=a.pageY,d={startX:l,currentX:l,startY:c,currentY:c};this.el.classList.add("sash-active",Vf),this.emit("start",d),this.el.setPointerCapture(a.pointerId);const f=m=>{m.preventDefault();const y={startX:l,currentX:m.pageX,startY:c,currentY:m.pageY};this.emit("change",y)},p=m=>{m.preventDefault(),this.el.classList.remove("sash-active",Vf),this.hoverDelayer.cancel(),this.emit("end"),this.el.releasePointerCapture(m.pointerId),window.removeEventListener("pointermove",f),window.removeEventListener("pointerup",p)};window.addEventListener("pointermove",f),window.addEventListener("pointerup",p)},this.onPointerDoublePress=()=>{this.emit("reset")},this.onMouseEnter=()=>{this.el.classList.contains(Vf)?(this.hoverDelayer.cancel(),this.el.classList.add("sash-hover",Ff)):this.hoverDelayer(this.el)},this.onMouseLeave=()=>{this.hoverDelayer.cancel(),this.el.classList.remove("sash-hover",Ff)},this.el=document.createElement("div"),this.el.classList.add("sash",z3),this.el.dataset.testid="sash",t.append(this.el),j3&&this.el.classList.add("sash-mac",F3),this.el.addEventListener("pointerdown",this.onPointerStart),this.el.addEventListener("dblclick",this.onPointerDoublePress),this.el.addEventListener("mouseenter",this.onMouseEnter),this.el.addEventListener("mouseleave",this.onMouseLeave),typeof r.size=="number"?(this.size=r.size,r.orientation===Hn.Vertical?this.el.style.width=`${this.size}px`:this.el.style.height=`${this.size}px`):(this.size=gS,yS.on("onDidChangeGlobalSize",a=>{this.size=a,this.layout()})),this.layoutProvider=n,this.orientation=(o=r.orientation)!=null?o:Hn.Vertical,this.orientation===Hn.Horizontal?(this.el.classList.add("sash-horizontal",Ex),this.el.classList.remove("sash-vertical",kx)):(this.el.classList.remove("sash-horizontal",Ex),this.el.classList.add("sash-vertical",kx)),this.layout()}layout(){if(this.orientation===Hn.Vertical){const t=this.layoutProvider;this.el.style.left=t.getVerticalSashLeft(this)-this.size/2+"px",t.getVerticalSashTop&&(this.el.style.top=t.getVerticalSashTop(this)+"px"),t.getVerticalSashHeight&&(this.el.style.height=t.getVerticalSashHeight(this)+"px")}else{const t=this.layoutProvider;this.el.style.top=t.getHorizontalSashTop(this)-this.size/2+"px",t.getHorizontalSashLeft&&(this.el.style.left=t.getHorizontalSashLeft(this)+"px"),t.getHorizontalSashWidth&&(this.el.style.width=t.getHorizontalSashWidth(this)+"px")}}dispose(){this.el.removeEventListener("pointerdown",this.onPointerStart),this.el.removeEventListener("dblclick",this.onPointerDoublePress),this.el.removeEventListener("mouseenter",this.onMouseEnter),this.el.removeEventListener("mouseleave",()=>this.onMouseLeave),this.el.remove()}}let Xu;var Bf;(Bf=Xu||(Xu={})).Distribute={type:"distribute"},Bf.Split=function(e){return{type:"split",index:e}},Bf.Invisible=function(e){return{type:"invisible",cachedVisibleSize:e}};let Bn=(function(e){return e.Normal="NORMAL",e.Low="LOW",e.High="HIGH",e})({});class vS{constructor(t,n,r){this.container=void 0,this.view=void 0,this._size=void 0,this._cachedVisibleSize=void 0,this.container=t,this.view=n,this.container.classList.add("split-view-view",fS),this.container.dataset.testid="split-view-view",typeof r=="number"?(this._size=r,this._cachedVisibleSize=void 0,t.classList.add("split-view-view-visible")):(this._size=0,this._cachedVisibleSize=r.cachedVisibleSize)}set size(t){this._size=t}get size(){return this._size}get priority(){return this.view.priority}get snap(){return!!this.view.snap}get cachedVisibleSize(){return this._cachedVisibleSize}get visible(){return this._cachedVisibleSize===void 0}setVisible(t,n){t!==this.visible&&(t?(this.size=lr(this._cachedVisibleSize,this.viewMinimumSize,this.viewMaximumSize),this._cachedVisibleSize=void 0):(this._cachedVisibleSize=typeof n=="number"?n:this.size,this.size=0),this.container.classList.toggle("split-view-view-visible",t),this.view.setVisible&&this.view.setVisible(t))}get minimumSize(){return this.visible?this.view.minimumSize:0}get viewMinimumSize(){return this.view.minimumSize}get maximumSize(){return this.visible?this.view.maximumSize:0}get viewMaximumSize(){return this.view.maximumSize}set enabled(t){this.container.style.pointerEvents=t?"":"none"}layout(t){this.layoutContainer(t),this.view.layout(this.size,t)}}class $3 extends vS{layoutContainer(t){this.container.style.left=`${t}px`,this.container.style.width=`${this.size}px`}}class U3 extends vS{layoutContainer(t){this.container.style.top=`${t}px`,this.container.style.height=`${this.size}px`}}class H3 extends em{get startSnappingEnabled(){return this._startSnappingEnabled}set startSnappingEnabled(t){this._startSnappingEnabled!==t&&(this._startSnappingEnabled=t,this.updateSashEnablement())}get endSnappingEnabled(){return this._endSnappingEnabled}set endSnappingEnabled(t){this._endSnappingEnabled!==t&&(this._endSnappingEnabled=t,this.updateSashEnablement())}constructor(t,n={},r,o,a){var l,c;if(super(),this.onDidChange=void 0,this.onDidDragStart=void 0,this.onDidDragEnd=void 0,this.orientation=void 0,this.sashContainer=void 0,this.size=0,this.contentSize=0,this.proportions=void 0,this.viewItems=[],this.sashItems=[],this.sashDragState=void 0,this.proportionalLayout=void 0,this.getSashOrthogonalSize=void 0,this._startSnappingEnabled=!0,this._endSnappingEnabled=!0,this.onSashEnd=d=>{this.emit("sashchange",d),this.saveProportions();for(const f of this.viewItems)f.enabled=!0},this.orientation=(l=n.orientation)!=null?l:Hn.Vertical,this.proportionalLayout=(c=n.proportionalLayout)!=null?c:!0,this.getSashOrthogonalSize=n.getSashOrthogonalSize,r&&(this.onDidChange=r),o&&(this.onDidDragStart=o),a&&(this.onDidDragEnd=a),this.sashContainer=document.createElement("div"),this.sashContainer.classList.add("sash-container",_3),t.prepend(this.sashContainer),n.descriptor){this.size=n.descriptor.size;for(const[d,f]of n.descriptor.views.entries()){const p=f.size,m=f.container,y=f.view;this.addView(m,y,p,d,!0)}this.contentSize=this.viewItems.reduce((d,f)=>d+f.size,0),this.saveProportions()}}addView(t,n,r,o=this.viewItems.length,a){let l;l=typeof r=="number"?r:r.type==="split"?this.getViewSize(r.index)/2:r.type==="invisible"?{cachedVisibleSize:r.cachedVisibleSize}:n.minimumSize;const c=this.orientation===Hn.Vertical?new U3(t,n,l):new $3(t,n,l);if(this.viewItems.splice(o,0,c),this.viewItems.length>1){const d=this.orientation===Hn.Vertical?new Cx(this.sashContainer,{getHorizontalSashTop:m=>this.getSashPosition(m),getHorizontalSashWidth:this.getSashOrthogonalSize},{orientation:Hn.Horizontal}):new Cx(this.sashContainer,{getVerticalSashLeft:m=>this.getSashPosition(m),getVerticalSashHeight:this.getSashOrthogonalSize},{orientation:Hn.Vertical}),f=this.orientation===Hn.Vertical?m=>({sash:d,start:m.startY,current:m.currentY}):m=>({sash:d,start:m.startX,current:m.currentX});d.on("start",m=>{var y;this.emit("sashDragStart"),this.onSashStart(f(m));const v=this.viewItems.map(b=>b.size);(y=this.onDidDragStart)==null||y.call(this,v)}),d.on("change",m=>this.onSashChange(f(m))),d.on("end",()=>{var m;this.emit("sashDragEnd"),this.onSashEnd(this.sashItems.findIndex(v=>v.sash===d));const y=this.viewItems.map(v=>v.size);(m=this.onDidDragEnd)==null||m.call(this,y)}),d.on("reset",()=>{const m=this.sashItems.findIndex(C=>C.sash===d),y=On(m,-1,-1),v=On(m+1,this.viewItems.length),b=this.findFirstSnapIndex(y),S=this.findFirstSnapIndex(v);(typeof b!="number"||this.viewItems[b].visible)&&(typeof S!="number"||this.viewItems[S].visible)&&this.emit("sashreset",m)});const p={sash:d};this.sashItems.splice(o-1,0,p)}a||this.relayout(),a||typeof r=="number"||r.type!=="distribute"||this.distributeViewSizes()}removeView(t,n){if(t<0||t>=this.viewItems.length)throw new Error("Index out of bounds");const r=this.viewItems.splice(t,1)[0].view;if(this.viewItems.length>=1){const o=Math.max(t-1,0);this.sashItems.splice(o,1)[0].sash.dispose()}return this.relayout(),n&&n.type==="distribute"&&this.distributeViewSizes(),r}moveView(t,n,r){const o=this.getViewCachedVisibleSize(n),a=o===void 0?this.getViewSize(n):Xu.Invisible(o),l=this.removeView(n);this.addView(t,l,a,r)}getViewCachedVisibleSize(t){if(t<0||t>=this.viewItems.length)throw new Error("Index out of bounds");return this.viewItems[t].cachedVisibleSize}layout(t=this.size){const n=Math.max(this.size,this.contentSize);if(this.size=t,this.proportions)for(let r=0;r<this.viewItems.length;r++){const o=this.viewItems[r];o.size=lr(Math.round(this.proportions[r]*t),o.minimumSize,o.maximumSize)}else{const r=On(0,this.viewItems.length),o=r.filter(l=>this.viewItems[l].priority===Bn.Low),a=r.filter(l=>this.viewItems[l].priority===Bn.High);this.resize(this.viewItems.length-1,t-n,void 0,o,a)}this.distributeEmptySpace(),this.layoutViews()}resizeView(t,n){if(t<0||t>=this.viewItems.length)return;const r=On(0,this.viewItems.length).filter(c=>c!==t),o=[...r.filter(c=>this.viewItems[c].priority===Bn.Low),t],a=r.filter(c=>this.viewItems[c].priority===Bn.High),l=this.viewItems[t];n=Math.round(n),n=lr(n,l.minimumSize,Math.min(l.maximumSize,this.size)),l.size=n,this.relayout(o,a)}resizeViews(t){for(let n=0;n<t.length;n++){const r=this.viewItems[n];let o=t[n];o=Math.round(o),o=lr(o,r.minimumSize,Math.min(r.maximumSize,this.size)),r.size=o}this.contentSize=this.viewItems.reduce((n,r)=>n+r.size,0),this.saveProportions(),this.layout(this.size)}getViewSize(t){return t<0||t>=this.viewItems.length?-1:this.viewItems[t].size}isViewVisible(t){if(t<0||t>=this.viewItems.length)throw new Error("Index out of bounds");return this.viewItems[t].visible}setViewVisible(t,n){if(t<0||t>=this.viewItems.length)throw new Error("Index out of bounds");this.viewItems[t].setVisible(n),this.distributeEmptySpace(t),this.layoutViews(),this.saveProportions()}distributeViewSizes(){const t=[];let n=0;for(const c of this.viewItems)c.maximumSize-c.minimumSize>0&&(t.push(c),n+=c.size);const r=Math.floor(n/t.length);for(const c of t)c.size=lr(r,c.minimumSize,c.maximumSize);const o=On(0,this.viewItems.length),a=o.filter(c=>this.viewItems[c].priority===Bn.Low),l=o.filter(c=>this.viewItems[c].priority===Bn.High);this.relayout(a,l)}dispose(){this.sashItems.forEach(t=>t.sash.dispose()),this.sashItems=[],this.sashContainer.remove()}relayout(t,n){const r=this.viewItems.reduce((o,a)=>o+a.size,0);this.resize(this.viewItems.length-1,this.size-r,void 0,t,n),this.distributeEmptySpace(),this.layoutViews(),this.saveProportions()}onSashStart({sash:t,start:n}){const r=this.sashItems.findIndex(o=>o.sash===t);(o=>{const a=this.viewItems.map(P=>P.size);let l,c,d=Number.NEGATIVE_INFINITY,f=Number.POSITIVE_INFINITY;const p=On(r,-1,-1),m=On(r+1,this.viewItems.length),y=p.reduce((P,T)=>P+(this.viewItems[T].minimumSize-a[T]),0),v=p.reduce((P,T)=>P+(this.viewItems[T].viewMaximumSize-a[T]),0),b=m.length===0?Number.POSITIVE_INFINITY:m.reduce((P,T)=>P+(a[T]-this.viewItems[T].minimumSize),0),S=m.length===0?Number.NEGATIVE_INFINITY:m.reduce((P,T)=>P+(a[T]-this.viewItems[T].viewMaximumSize),0);d=Math.max(y,S),f=Math.min(b,v);const C=this.findFirstSnapIndex(p),E=this.findFirstSnapIndex(m);if(typeof C=="number"){const P=this.viewItems[C],T=Math.floor(P.viewMinimumSize/2);l={index:C,limitDelta:P.visible?d-T:d+T,size:P.size}}if(typeof E=="number"){const P=this.viewItems[E],T=Math.floor(P.viewMinimumSize/2);c={index:E,limitDelta:P.visible?f+T:f-T,size:P.size}}this.sashDragState={start:o,current:o,index:r,sizes:a,minDelta:d,maxDelta:f,snapBefore:l,snapAfter:c}})(n)}onSashChange({current:t}){const{index:n,start:r,sizes:o,minDelta:a,maxDelta:l,snapBefore:c,snapAfter:d}=this.sashDragState;this.sashDragState.current=t;const f=t-r;this.resize(n,f,o,void 0,void 0,a,l,c,d),this.distributeEmptySpace(),this.layoutViews()}getSashPosition(t){let n=0;for(let r=0;r<this.sashItems.length;r++)if(n+=this.viewItems[r].size,this.sashItems[r].sash===t)return n;return 0}resize(t,n,r=this.viewItems.map(p=>p.size),o,a,l=Number.NEGATIVE_INFINITY,c=Number.POSITIVE_INFINITY,d,f){if(t<0||t>=this.viewItems.length)return 0;const p=On(t,-1,-1),m=On(t+1,this.viewItems.length);if(a)for(const D of a)Sx(p,D),Sx(m,D);if(o)for(const D of o)Of(p,D),Of(m,D);const y=p.map(D=>this.viewItems[D]),v=p.map(D=>r[D]),b=m.map(D=>this.viewItems[D]),S=m.map(D=>r[D]),C=p.reduce((D,H)=>D+(this.viewItems[H].minimumSize-r[H]),0),E=p.reduce((D,H)=>D+(this.viewItems[H].maximumSize-r[H]),0),P=m.length===0?Number.POSITIVE_INFINITY:m.reduce((D,H)=>D+(r[H]-this.viewItems[H].minimumSize),0),T=m.length===0?Number.NEGATIVE_INFINITY:m.reduce((D,H)=>D+(r[H]-this.viewItems[H].maximumSize),0),O=Math.max(C,T,l),V=Math.min(P,E,c);let N=!1;if(d){const D=this.viewItems[d.index],H=n>=d.limitDelta;N=H!==D.visible,D.setVisible(H,d.size)}if(!N&&f){const D=this.viewItems[f.index],H=n<f.limitDelta;N=H!==D.visible,D.setVisible(H,f.size)}if(N)return this.resize(t,n,r,o,a,l,c);for(let D=0,H=n=lr(n,O,V);D<y.length;D++){const ee=y[D],L=lr(v[D]+H,ee.minimumSize,ee.maximumSize);H-=L-v[D],ee.size=L}for(let D=0,H=n;D<b.length;D++){const ee=b[D],L=lr(S[D]-H,ee.minimumSize,ee.maximumSize);H+=L-S[D],ee.size=L}return n}distributeEmptySpace(t){const n=this.viewItems.reduce((f,p)=>f+p.size,0);let r=this.size-n;const o=On(0,this.viewItems.length),a=[],l=o.filter(f=>this.viewItems[f].priority===Bn.Low),c=o.filter(f=>this.viewItems[f].priority===Bn.Normal),d=o.filter(f=>this.viewItems[f].priority===Bn.High);a.push(...d,...c,...l),typeof t=="number"&&Of(a,t);for(let f=0;r!==0&&f<a.length;f++){const p=this.viewItems[a[f]],m=lr(p.size+r,p.minimumSize,p.maximumSize);r-=m-p.size,p.size=m}}layoutViews(){var t;this.contentSize=this.viewItems.reduce((r,o)=>r+o.size,0);let n=0;for(const r of this.viewItems)r.layout(n),n+=r.size;(t=this.onDidChange)!=null&&t.call(this,this.viewItems.map(r=>r.size)),this.sashItems.forEach(r=>r.sash.layout()),this.updateSashEnablement()}saveProportions(){this.proportionalLayout&&this.contentSize>0&&(this.proportions=this.viewItems.map(t=>t.size/this.contentSize))}updateSashEnablement(){let t=!1;const n=this.viewItems.map(d=>t=d.size-d.minimumSize>0||t);t=!1;const r=this.viewItems.map(d=>t=d.maximumSize-d.size>0||t),o=[...this.viewItems].reverse();t=!1;const a=o.map(d=>t=d.size-d.minimumSize>0||t).reverse();t=!1;const l=o.map(d=>t=d.maximumSize-d.size>0||t).reverse();let c=0;for(let d=0;d<this.sashItems.length;d++){const{sash:f}=this.sashItems[d];c+=this.viewItems[d].size;const p=!(n[d]&&l[d+1]),m=!(r[d]&&a[d+1]);if(p&&m){const y=On(d,-1,-1),v=On(d+1,this.viewItems.length),b=this.findFirstSnapIndex(y),S=this.findFirstSnapIndex(v),C=typeof b=="number"&&!this.viewItems[b].visible,E=typeof S=="number"&&!this.viewItems[S].visible;C&&a[d]&&(c>0||this.startSnappingEnabled)?f.state=kn.Minimum:E&&n[d]&&(c<this.contentSize||this.endSnappingEnabled)?f.state=kn.Maximum:f.state=kn.Disabled}else f.state=p&&!m?kn.Minimum:!p&&m?kn.Maximum:kn.Enabled}}findFirstSnapIndex(t){for(const n of t){const r=this.viewItems[n];if(r.visible&&r.snap)return n}for(const n of t){const r=this.viewItems[n];if(r.visible&&r.maximumSize-r.minimumSize>0)return;if(!r.visible&&r.snap)return n}}}class Qs{constructor(t){this.size=void 0,this.size=t}getPreferredSize(){return this.size}}class Ix{constructor(t,n){this.proportion=void 0,this.layoutService=void 0,this.proportion=t,this.layoutService=n}getPreferredSize(){return this.proportion*this.layoutService.getSize()}}class Iu{getPreferredSize(){}}class Tx{get preferredSize(){return this.layoutStrategy.getPreferredSize()}set preferredSize(t){if(typeof t=="number")this.layoutStrategy=new Qs(t);else if(typeof t=="string"){const n=t.trim();if(Cu(n,"%")){const r=Number(n.slice(0,-1))/100;this.layoutStrategy=new Ix(r,this.layoutService)}else if(Cu(n,"px")){const r=Number(n.slice(0,-2))/100;this.layoutStrategy=new Qs(r)}else if(typeof Number.parseFloat(n)=="number"){const r=Number.parseFloat(n);this.layoutStrategy=new Qs(r)}else this.layoutStrategy=new Iu}else this.layoutStrategy=new Iu}constructor(t,n){var r;if(this.minimumSize=0,this.maximumSize=Number.POSITIVE_INFINITY,this.element=void 0,this.priority=void 0,this.snap=void 0,this.layoutService=void 0,this.layoutStrategy=void 0,this.layoutService=t,this.element=n.element,this.minimumSize=typeof n.minimumSize=="number"?n.minimumSize:30,this.maximumSize=typeof n.maximumSize=="number"?n.maximumSize:Number.POSITIVE_INFINITY,typeof n.preferredSize=="number")this.layoutStrategy=new Qs(n.preferredSize);else if(typeof n.preferredSize=="string"){const o=n.preferredSize.trim();if(Cu(o,"%")){const a=Number(o.slice(0,-1))/100;this.layoutStrategy=new Ix(a,this.layoutService)}else if(Cu(o,"px")){const a=Number(o.slice(0,-2));this.layoutStrategy=new Qs(a)}else if(typeof Number.parseFloat(o)=="number"){const a=Number.parseFloat(o);this.layoutStrategy=new Qs(a)}else this.layoutStrategy=new Iu}else this.layoutStrategy=new Iu;this.priority=(r=n.priority)!=null?r:Bn.Normal,this.snap=typeof n.snap=="boolean"&&n.snap}layout(t){}}function _x(e){return e.minSize!==void 0||e.maxSize!==void 0||e.preferredSize!==void 0||e.priority!==void 0||e.visible!==void 0}const tm=I.forwardRef(({className:e,children:t},n)=>wr.createElement("div",{ref:n,className:Vh("split-view-view",fS,e)},t));tm.displayName="Allotment.Pane";const xS=I.forwardRef(({children:e,className:t,id:n,maxSize:r=1/0,minSize:o=30,proportionalLayout:a=!0,separator:l=!0,sizes:c,defaultSizes:d=c,snap:f=!1,vertical:p=!1,onChange:m,onReset:y,onVisibleChange:v,onDragStart:b,onDragEnd:S},C)=>{const E=I.useRef(null),P=I.useRef([]),T=I.useRef(new Map),O=I.useRef(null),V=I.useRef(new Map),N=I.useRef(new M3),D=I.useRef([]),[H,ee]=I.useState(!1),L=I.useMemo(()=>wr.Children.toArray(e).filter(wr.isValidElement),[e]),te=I.useCallback(G=>{var X,Q;const re=(X=D.current)==null?void 0:X[G];return typeof(re==null?void 0:re.preferredSize)=="number"&&((Q=O.current)!=null&&Q.resizeView(G,Math.round(re.preferredSize)),!0)},[]);return I.useImperativeHandle(C,()=>({reset:()=>{if(y)y();else{var G;(G=O.current)==null||G.distributeViewSizes();for(let X=0;X<D.current.length;X++)te(X)}},resize:G=>{var X;(X=O.current)==null||X.resizeViews(G)}})),yx(()=>{let G=!0;d&&V.current.size!==d.length&&(G=!1,console.warn(`Expected ${d.length} children based on defaultSizes but found ${V.current.size}`)),G&&d&&(P.current=L.map(re=>re.key));const X=Ra({orientation:p?Hn.Vertical:Hn.Horizontal,proportionalLayout:a},G&&d&&{descriptor:{size:d.reduce((re,fe)=>re+fe,0),views:d.map((re,fe)=>{var oe,U,se,_;const j=T.current.get(P.current[fe]),Y=new Tx(N.current,Ra({element:document.createElement("div"),minimumSize:(oe=j==null?void 0:j.minSize)!=null?oe:o,maximumSize:(U=j==null?void 0:j.maxSize)!=null?U:r,priority:(se=j==null?void 0:j.priority)!=null?se:Bn.Normal},(j==null?void 0:j.preferredSize)&&{preferredSize:j==null?void 0:j.preferredSize},{snap:(_=j==null?void 0:j.snap)!=null?_:f}));return D.current.push(Y),{container:[...V.current.values()][fe],size:re,view:Y}})}});O.current=new H3(E.current,X,m,b,S),O.current.on("sashDragStart",()=>{var re;(re=E.current)==null||re.classList.add("split-view-sash-dragging")}),O.current.on("sashDragEnd",()=>{var re;(re=E.current)==null||re.classList.remove("split-view-sash-dragging")}),O.current.on("sashchange",re=>{if(v&&O.current){const fe=L.map(oe=>oe.key);for(let oe=0;oe<fe.length;oe++){const U=T.current.get(fe[oe]);(U==null?void 0:U.visible)!==void 0&&U.visible!==O.current.isViewVisible(oe)&&v(oe,O.current.isViewVisible(oe))}}}),O.current.on("sashreset",re=>{if(y)y();else{var fe;if(te(re)||te(re+1))return;(fe=O.current)==null||fe.distributeViewSizes()}});const Q=O.current;return()=>{Q.dispose()}},[]),yx(()=>{if(H){const A=L.map(de=>de.key),Se=[...P.current],Te=A.filter(de=>!P.current.includes(de)),ke=A.filter(de=>P.current.includes(de)),ze=P.current.map(de=>!A.includes(de));for(let de=ze.length-1;de>=0;de--){var G;ze[de]&&((G=O.current)!=null&&G.removeView(de),Se.splice(de,1),D.current.splice(de,1))}for(const de of Te){var X,Q,re,fe,oe;const he=T.current.get(de),Ne=new Tx(N.current,Ra({element:document.createElement("div"),minimumSize:(X=he==null?void 0:he.minSize)!=null?X:o,maximumSize:(Q=he==null?void 0:he.maxSize)!=null?Q:r,priority:(re=he==null?void 0:he.priority)!=null?re:Bn.Normal},(he==null?void 0:he.preferredSize)&&{preferredSize:he==null?void 0:he.preferredSize},{snap:(fe=he==null?void 0:he.snap)!=null?fe:f}));(oe=O.current)!=null&&oe.addView(V.current.get(de),Ne,Xu.Distribute,A.findIndex(Ke=>Ke===de)),Se.splice(A.findIndex(Ke=>Ke===de),0,de),D.current.splice(A.findIndex(Ke=>Ke===de),0,Ne)}for(;!C3(A,Se);)for(const[de,he]of A.entries()){const Ne=Se.findIndex(Ke=>Ke===he);if(Ne!==de){var U;(U=O.current)==null||U.moveView(V.current.get(he),Ne,de);const Ke=Se[Ne];Se.splice(Ne,1),Se.splice(de,0,Ke);break}}for(const de of Te){var se;const he=A.findIndex(Ke=>Ke===de),Ne=D.current[he].preferredSize;Ne!==void 0&&((se=O.current)==null||se.resizeView(he,Ne))}for(const de of[...Te,...ke]){var _,j;const he=T.current.get(de),Ne=A.findIndex(Ke=>Ke===de);he&&_x(he)&&he.visible!==void 0&&((_=O.current)==null?void 0:_.isViewVisible(Ne))!==he.visible&&((j=O.current)==null||j.setViewVisible(Ne,he.visible))}for(const de of ke){const he=T.current.get(de),Ne=A.findIndex(Ke=>Ke===de);if(he&&_x(he)){var Y;he.preferredSize!==void 0&&D.current[Ne].preferredSize!==he.preferredSize&&(D.current[Ne].preferredSize=he.preferredSize);let Ke=!1;he.minSize!==void 0&&D.current[Ne].minimumSize!==he.minSize&&(D.current[Ne].minimumSize=he.minSize,Ke=!0),he.maxSize!==void 0&&D.current[Ne].maximumSize!==he.maxSize&&(D.current[Ne].maximumSize=he.maxSize,Ke=!0),Ke&&((Y=O.current)==null||Y.layout())}}(Te.length>0||ze.length>0)&&(P.current=A)}},[L,H,r,o,f]),I.useEffect(()=>{O.current&&(O.current.onDidChange=m)},[m]),I.useEffect(()=>{O.current&&(O.current.onDidDragStart=b)},[b]),I.useEffect(()=>{O.current&&(O.current.onDidDragEnd=S)},[S]),I3({ref:E,onResize:({width:G,height:X})=>{var Q;G&&X&&((Q=O.current)!=null&&Q.layout(p?X:G),N.current.setSize(p?X:G),ee(!0))}}),I.useEffect(()=>{mS&&W3(20)},[]),wr.createElement("div",{ref:E,className:Vh("split-view",p?"split-view-vertical":"split-view-horizontal",{"split-view-separator-border":l},T3,p?A3:R3,{[N3]:l},t),id:n},wr.createElement("div",{className:Vh("split-view-container",P3)},wr.Children.toArray(e).map(G=>{if(!wr.isValidElement(G))return null;const X=G.key;return G.type.displayName==="Allotment.Pane"?(T.current.set(X,G.props),wr.cloneElement(G,{key:X,ref:Q=>{const re=G.ref;re&&(re.current=Q),Q?V.current.set(X,Q):V.current.delete(X)}})):wr.createElement(tm,{key:X,ref:Q=>{Q?V.current.set(X,Q):V.current.delete(X)}},G)})))});function W3(e){const t=lr(e,4,20),n=lr(e,1,8);document.documentElement.style.setProperty("--sash-size",t+"px"),document.documentElement.style.setProperty("--sash-hover-size",n+"px"),(function(r){gS=r,yS.emit("onDidChangeGlobalSize",r)})(t)}xS.displayName="Allotment";var is=Object.assign(xS,{Pane:tm});const wS=I.forwardRef(({position:e="left",className:t,children:n,...r},o)=>w.jsx("div",{ref:o,className:Re("h-full w-full flex flex-col","bg-muted/30 border-border",e==="left"?"border-r":"border-l",t),...r,children:n}));wS.displayName="Sidebar";const bS=I.forwardRef(({className:e,children:t,...n},r)=>w.jsx("div",{ref:r,className:Re("h-full w-full flex flex-col bg-background",e),...n,children:t}));bS.displayName="MainContent";var Ur=(e=>(e[e.DEBUG=0]="DEBUG",e[e.INFO=1]="INFO",e[e.WARN=2]="WARN",e[e.ERROR=3]="ERROR",e[e.SILENT=4]="SILENT",e))(Ur||{}),q3=["agent_initializing","agent_ready","agent_destroyed","conversation_queued","conversation_start","conversation_thinking","conversation_responding","conversation_end","conversation_interrupted","tool_planned","tool_executing","tool_completed","tool_failed","error_occurred"];new Set(q3);var G3=["user_message","assistant_message","tool_call_message","tool_result_message"];new Set(G3);var K3=["error"];new Set(K3);var Y3=["turn_request","turn_response"];new Set(Y3);var X3=["message_start","message_delta","message_stop","text_content_block_start","text_delta","text_content_block_stop","tool_use_content_block_start","input_json_delta","tool_use_content_block_stop","tool_call","tool_result","interrupted"];new Set(X3);var Q3=Object.defineProperty,J3=(e,t,n)=>t in e?Q3(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,ds=(e,t,n)=>J3(e,typeof t!="symbol"?t+"":t,n),SS=class Bh{constructor(t,n={}){ds(this,"name"),ds(this,"level"),ds(this,"colors"),ds(this,"timestamps"),this.name=t,this.level=n.level??Ur.INFO,this.colors=n.colors??this.isNodeEnvironment(),this.timestamps=n.timestamps??!0}debug(t,n){this.isDebugEnabled()&&this.log("DEBUG",t,n)}info(t,n){this.isInfoEnabled()&&this.log("INFO",t,n)}warn(t,n){this.isWarnEnabled()&&this.log("WARN",t,n)}error(t,n){this.isErrorEnabled()&&(t instanceof Error?this.log("ERROR",t.message,{...n,stack:t.stack}):this.log("ERROR",t,n))}isDebugEnabled(){return this.level<=Ur.DEBUG}isInfoEnabled(){return this.level<=Ur.INFO}isWarnEnabled(){return this.level<=Ur.WARN}isErrorEnabled(){return this.level<=Ur.ERROR}log(t,n,r){const o=[];if(this.timestamps&&o.push(new Date().toISOString()),this.colors){const c=Bh.COLORS[t];o.push(`${c}${t.padEnd(5)}${Bh.COLORS.RESET}`)}else o.push(t.padEnd(5));o.push(`[${this.name}]`),o.push(n);const a=o.join(" "),l=this.getConsoleMethod(t);r&&Object.keys(r).length>0?l(a,r):l(a)}getConsoleMethod(t){switch(t){case"DEBUG":return console.debug.bind(console);case"INFO":return console.info.bind(console);case"WARN":return console.warn.bind(console);case"ERROR":return console.error.bind(console);default:return console.log.bind(console)}}isNodeEnvironment(){var t;return typeof process<"u"&&((t=process.versions)==null?void 0:t.node)!==void 0}};ds(SS,"COLORS",{DEBUG:"\x1B[36m",INFO:"\x1B[32m",WARN:"\x1B[33m",ERROR:"\x1B[31m",RESET:"\x1B[0m"});var Z3=SS,$f=null,nm=class{static getLogger(e){const t=typeof e=="string"?e:e.name;if(this.loggers.has(t))return this.loggers.get(t);const n=this.createLazyLogger(t);return this.loggers.set(t,n),n}static configure(e){this.config={...this.config,...e}}static reset(){this.loggers.clear(),this.config={defaultLevel:Ur.INFO},$f=null}static createLazyLogger(e){let t=null;const n=()=>(t||(t=this.createLogger(e)),t);return{name:e,level:this.config.defaultLevel||Ur.INFO,debug:(r,o)=>n().debug(r,o),info:(r,o)=>n().info(r,o),warn:(r,o)=>n().warn(r,o),error:(r,o)=>n().error(r,o),isDebugEnabled:()=>n().isDebugEnabled(),isInfoEnabled:()=>n().isInfoEnabled(),isWarnEnabled:()=>n().isWarnEnabled(),isErrorEnabled:()=>n().isErrorEnabled()}}static createLogger(e){return $f?$f.getLogger(e):this.config.defaultImplementation?this.config.defaultImplementation(e):new Z3(e,{level:this.config.defaultLevel,...this.config.consoleOptions})}};ds(nm,"loggers",new Map);ds(nm,"config",{defaultLevel:Ur.INFO});function e4(e){return nm.getLogger(e)}const Fn=e4("ui/Studio");function t4({agentx:e,userId:t,containerId:n,definitions:r,onSessionChange:o,onDefinitionChange:a,className:l=""}){const[c,d]=I.useState(r[0]??null),{sessions:f,currentSession:p,selectSession:m,createSession:y,deleteSession:v,isLoading:b}=QT(e,t,{onSessionChange:U=>{o==null||o(U)}}),[S,C]=I.useState(null),[E,P]=I.useState([]);I.useEffect(()=>()=>{var U;S&&(Fn.debug("Cleaning up agent on unmount",{agentId:S.agentId}),(U=S.destroy)==null||U.call(S).catch(se=>Fn.error("Failed to destroy agent",{error:se})))},[S]);const{messages:T,streaming:O,errors:V,send:N,status:D,interrupt:H,isLoading:ee}=XT(S),L=[...E,...T],te=I.useCallback(async()=>{var U;S&&(Fn.debug("Destroying current agent",{agentId:S.agentId}),await((U=S.destroy)==null?void 0:U.call(S)),C(null),P([]))},[S]),G=I.useCallback(async U=>{Fn.debug("Selecting definition",{name:U.name}),await te(),d(U),a==null||a(U),m(null)},[te,m,a]),X=I.useCallback(async U=>{Fn.info("Selecting existing session",{sessionId:U.sessionId}),await te();try{const se=await e.sessions.get(U.sessionId);if(!se){Fn.error("Session not found",{sessionId:U.sessionId});return}const _=await se.getMessages();P(_);const j=await se.resume({containerId:n});C(j),m(U),Fn.info("Session selected and agent resumed",{sessionId:U.sessionId,agentId:j.agentId})}catch(se){Fn.error("Failed to select session",{sessionId:U.sessionId,error:se})}},[e,n,te,m]),Q=I.useCallback(async U=>{if(!c)return null;Fn.info("Creating new session",{definition:c.name}),await te();try{const se=await e.images.getMetaImage(c.name);if(!se)return Fn.error("MetaImage not found",{definition:c.name}),null;const _=await y(se.imageId,`New Chat ${f.length+1}`),j=await e.images.run(se.imageId,{containerId:n}),Y=await e.sessions.get(_.sessionId);return Y&&Y.collect(j),FC.flushSync(()=>{P([]),C(j)}),m(_),Fn.info("Session created and agent started",{sessionId:_.sessionId,agentId:j.agentId}),U&&j.receive(U),j}catch(se){return Fn.error("Failed to create session",{error:se}),null}},[e,c,n,y,f.length,te,m]),re=I.useCallback(async U=>{(p==null?void 0:p.sessionId)===U&&await te(),await v(U)},[p==null?void 0:p.sessionId,te,v]),fe=I.useCallback(async U=>{p?N(U):await Q(U)},[p,Q,N]),oe=b||ee;return w.jsx("div",{className:`h-full bg-background ${l}`,children:w.jsxs(is,{children:[w.jsx(is.Pane,{minSize:56,maxSize:56,children:w.jsx("div",{className:"h-full bg-muted/30 border-r border-border",children:w.jsx(y_,{definitions:r,current:c,onSelect:G,onSettings:()=>{console.log("Open settings")}})})}),w.jsx(is.Pane,{minSize:200,maxSize:400,preferredSize:280,children:w.jsx(wS,{children:w.jsx(ej,{sessions:f,current:p,agentName:c==null?void 0:c.name,onSelect:X,onCreate:Q,onDelete:re})})}),w.jsx(is.Pane,{children:w.jsx(bS,{children:w.jsxs(is,{vertical:!0,children:[w.jsx(is.Pane,{children:w.jsx(x3,{definition:c,session:p,agentId:S==null?void 0:S.agentId,messages:L,streaming:O,errors:V,status:D,isLoading:oe,onAbort:H,onCreateSession:Q})}),w.jsx(is.Pane,{minSize:150,maxSize:600,preferredSize:220,children:w.jsx(S3,{onSend:fe,disabled:oe},(p==null?void 0:p.sessionId)??"new")})]})})})]})})}const n4=I.forwardRef(({items:e,bottomItems:t,activeId:n,onItemClick:r,position:o="left",className:a,...l},c)=>{const d=f=>{const p=f.id===n;return w.jsxs("button",{type:"button",onClick:()=>r==null?void 0:r(f.id),className:Re("relative w-12 h-12 flex items-center justify-center","text-muted-foreground hover:text-foreground","transition-colors duration-200","group",p&&["text-foreground",o==="left"?"border-l-2 border-primary":"border-r-2 border-primary"]),title:f.label,"aria-label":f.label,"aria-current":p?"page":void 0,children:[w.jsx("div",{className:"w-6 h-6 flex items-center justify-center",children:f.icon}),f.badge&&w.jsx("span",{className:Re("absolute top-1 right-1","min-w-[16px] h-4 px-1","flex items-center justify-center","text-[10px] font-semibold","bg-primary text-primary-foreground","rounded-full"),children:f.badge}),w.jsx("div",{className:Re("absolute inset-0 bg-accent/0 group-hover:bg-accent/50","transition-colors duration-200")})]},f.id)};return w.jsxs("div",{ref:c,className:Re("flex flex-col bg-muted/30 border-border",o==="left"?"border-r":"border-l",a),...l,children:[w.jsx("div",{className:"flex-1 flex flex-col",children:e.map(d)}),t&&t.length>0&&w.jsx("div",{className:"flex flex-col border-t border-border",children:t.map(d)})]})});n4.displayName="ActivityBar";const r4=I.forwardRef(({left:e,center:t,right:n,height:r=56,className:o,children:a,...l},c)=>w.jsxs("div",{ref:c,className:Re("w-full flex items-center","bg-background border-b border-border","px-4",o),style:{height:`${r}px`,minHeight:`${r}px`},...l,children:[e&&w.jsx("div",{className:"flex items-center gap-3 flex-shrink-0",children:e}),t&&w.jsx("div",{className:"flex-1 flex items-center justify-center px-4",children:t}),n&&w.jsx("div",{className:"flex items-center gap-3 flex-shrink-0",children:n}),!e&&!t&&!n&&a]}));r4.displayName="Header";const i4=I.forwardRef(({height:e=200,minHeight:t=100,maxHeight:n=500,className:r,children:o,...a},l)=>w.jsx("div",{ref:l,className:Re("w-full flex flex-col","bg-muted/30 border-t border-border",r),style:{height:`${e}px`,minHeight:`${t}px`,maxHeight:`${n}px`},...a,children:o}));i4.displayName="Panel";const s4=I.forwardRef(({width:e=300,minWidth:t=200,maxWidth:n=600,className:r,children:o,...a},l)=>w.jsx("div",{ref:l,className:Re("h-full flex flex-col","bg-muted/30 border-l border-border",r),style:{width:`${e}px`,minWidth:`${t}px`,maxWidth:`${n}px`},...a,children:o}));s4.displayName="RightSidebar";const o4=I.forwardRef(({icon:e,children:t,clickable:n=!1,className:r,...o},a)=>w.jsxs("div",{ref:a,className:Re("flex items-center gap-1.5 px-2 py-0.5 text-xs",n&&"hover:bg-accent cursor-pointer rounded",r),...o,children:[e&&w.jsx("span",{className:"flex items-center",children:e}),w.jsx("span",{children:t})]}));o4.displayName="StatusBarItem";const a4=I.forwardRef(({align:e="left",children:t,className:n,...r},o)=>w.jsx("div",{ref:o,className:Re("flex items-center gap-1",e==="left"&&"justify-start",e==="center"&&"justify-center flex-1",e==="right"&&"justify-end",n),...r,children:t}));a4.displayName="StatusBarSection";const l4=I.forwardRef(({height:e=24,children:t,className:n,...r},o)=>w.jsx("div",{ref:o,className:Re("w-full flex items-center","bg-primary text-primary-foreground","px-2",n),style:{height:`${e}px`,minHeight:`${e}px`},...r,children:t}));l4.displayName="StatusBar";const u4=uc("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{default:"bg-primary text-primary-foreground shadow hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90",outline:"border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2",sm:"h-8 rounded-md px-3 text-xs",lg:"h-10 rounded-md px-8",icon:"h-9 w-9"}},defaultVariants:{variant:"default",size:"default"}}),rm=I.forwardRef(({className:e,variant:t,size:n,...r},o)=>w.jsx("button",{className:Re(u4({variant:t,size:n,className:e})),ref:o,...r}));rm.displayName="Button";const kS=I.forwardRef(({children:e,className:t,...n},r)=>w.jsx("div",{ref:r,className:Re("flex gap-2",t),...n,children:e}));kS.displayName="ActionBar";const ES=I.forwardRef(({children:e,loading:t=!1,variant:n="default",size:r="sm",className:o,disabled:a,...l},c)=>w.jsx(rm,{ref:c,variant:n,size:r,className:Re("flex-1 h-8 text-xs transition-all duration-200",o),disabled:a||t,...l,children:t?w.jsxs(w.Fragment,{children:[w.jsx("div",{className:"w-3.5 h-3.5 mr-1.5 animate-spin rounded-full border-2 border-current border-t-transparent"}),"Loading..."]}):e}));ES.displayName="ActionBar.Primary";const CS=I.forwardRef(({children:e,loading:t=!1,variant:n="outline",size:r="sm",className:o,disabled:a,...l},c)=>w.jsx(rm,{ref:c,variant:n,size:r,className:Re("h-8 w-8 px-0 transition-colors duration-200 group",o),disabled:a||t,...l,children:t?w.jsx("div",{className:"w-3.5 h-3.5 animate-spin rounded-full border-2 border-current border-t-transparent"}):e}));CS.displayName="ActionBar.Icon";const IS=I.forwardRef(({children:e,className:t,...n},r)=>w.jsx("div",{ref:r,className:Re("flex gap-2",t),...n,children:e}));IS.displayName="ActionBar.Group";Object.assign(kS,{Primary:ES,Icon:CS,Group:IS});const c4=I.forwardRef(({className:e,src:t="/icons/agent-ai-icon.svg",alt:n="Agent",...r},o)=>w.jsx("img",{ref:o,src:t,alt:n,className:Re("w-5 h-5",e),...r}));c4.displayName="AgentLogo";const d4=I.forwardRef(({logo:e,title:t,subtitle:n,actions:r,showBorder:o=!0,isMobile:a=!1,isPWA:l=!1,className:c,...d},f)=>w.jsx("div",{ref:f,className:Re("p-4",o&&"border-b border-border",a&&"md:hidden p-3",!a&&"hidden md:block",c),style:l&&a?{paddingTop:"16px"}:void 0,...d,children:w.jsxs("div",{className:"flex items-center justify-between",children:[w.jsxs("div",{className:"flex items-center gap-3",children:[e&&w.jsx("div",{className:Re("bg-primary rounded-lg flex items-center justify-center text-primary-foreground",a?"w-8 h-8":"w-8 h-8 shadow-sm"),children:e}),w.jsxs("div",{children:[w.jsx("h1",{className:Re("font-bold text-foreground",a?"text-lg font-semibold":"text-lg"),children:t}),n&&w.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:n})]})]}),r&&w.jsx("div",{className:"flex items-center gap-2",children:r})]})}));d4.displayName="AppHeader";const f4=I.forwardRef(({icon:e,title:t,description:n,action:r,spacing:o="md",className:a,...l},c)=>{const d={sm:"py-8",md:"py-12",lg:"py-16"},f={sm:"mb-3",md:"mb-4",lg:"mb-6"},p={sm:"mb-1",md:"mb-2",lg:"mb-3"},m={sm:"mt-3",md:"mt-4",lg:"mt-6"};return w.jsxs("div",{ref:c,className:Re("text-center px-4",d[o],a),...l,children:[e&&w.jsx("div",{className:Re("w-12 h-12 bg-muted rounded-lg flex items-center justify-center mx-auto text-muted-foreground",f[o]),children:e}),w.jsx("h3",{className:Re("text-base font-medium text-foreground",p[o]),children:t}),n&&w.jsx("p",{className:"text-sm text-muted-foreground max-w-md mx-auto",children:n}),r&&w.jsx("div",{className:Re(m[o]),children:r})]})});f4.displayName="EmptyState";const h4=I.forwardRef(({className:e,type:t,...n},r)=>w.jsx("input",{type:t,className:Re("flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",e),ref:r,...n}));h4.displayName="Input";const p4=I.forwardRef(({selected:e=!1,active:t=!1,showActiveIndicator:n=!1,leading:r,title:o,subtitle:a,trailing:l,actions:c,variant:d="default",isMobile:f=!1,onClick:p,className:m,...y},v)=>{const b=d==="compact",S=!!p;return w.jsxs("div",{ref:v,className:Re("group relative",m),...y,children:[n&&t&&w.jsx("div",{className:"absolute left-2 top-1/2 transform -translate-y-1/2 z-10",children:w.jsx("div",{className:"w-2 h-2 bg-green-500 rounded-full animate-pulse"})}),f&&w.jsx("div",{className:Re("p-3 mx-3 my-1 rounded-lg bg-card border border-border/50 active:scale-[0.98] transition-all duration-150",e&&"bg-primary/5 border-primary/20",t&&!e&&"border-green-500/30 bg-green-50/5 dark:bg-green-900/5",S&&"cursor-pointer"),onClick:p,children:w.jsxs("div",{className:"flex items-center gap-2",children:[r&&w.jsx("div",{className:"flex-shrink-0",children:r}),w.jsxs("div",{className:"min-w-0 flex-1",children:[w.jsx("div",{className:Re("font-medium truncate text-foreground","text-xs"),children:o}),a&&w.jsx("div",{className:"flex items-center gap-1 mt-0.5",children:a})]}),l&&w.jsx("div",{className:"flex-shrink-0",children:l}),c&&w.jsx("div",{className:"flex items-center gap-1 ml-1",children:c})]})}),!f&&w.jsxs(w.Fragment,{children:[w.jsx("div",{className:Re("w-full p-2 rounded-md transition-colors duration-200",S&&"cursor-pointer hover:bg-accent/50",e&&"bg-accent text-accent-foreground",!S&&!e&&"pointer-events-none"),onClick:p,children:w.jsxs("div",{className:"flex items-start gap-2 min-w-0 w-full",children:[r&&w.jsx("div",{className:"flex-shrink-0 mt-0.5",children:r}),w.jsxs("div",{className:"min-w-0 flex-1",children:[w.jsx("div",{className:Re("font-medium truncate text-foreground","text-xs"),children:o}),a&&w.jsx("div",{className:"flex items-center gap-1 mt-0.5",children:a})]}),l&&w.jsx("div",{className:"flex-shrink-0 ml-auto",children:l})]})}),c&&w.jsx("div",{className:"absolute right-2 top-1/2 transform -translate-y-1/2 flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-all duration-200",children:c})]})]})});p4.displayName="ListItem";const m4=I.forwardRef(({icon:e,title:t,description:n,spacing:r="md",showSpinner:o=!0,className:a,...l},c)=>{const d={sm:"py-8",md:"py-12",lg:"py-16"},f={sm:"mb-3",md:"mb-4",lg:"mb-6"},p={sm:"mb-1",md:"mb-2",lg:"mb-3"},m={sm:"w-5 h-5",md:"w-6 h-6",lg:"w-8 h-8"},v=e||(o?w.jsx("div",{className:Re("animate-spin rounded-full border-2 border-muted-foreground border-t-transparent",m[r])}):null);return w.jsxs("div",{ref:c,className:Re("text-center px-4",d[r],a),...l,children:[v&&w.jsx("div",{className:Re("w-12 h-12 bg-muted rounded-lg flex items-center justify-center mx-auto",f[r]),children:v}),t&&w.jsx("h3",{className:Re("text-base font-medium text-foreground",p[r]),children:t}),n&&w.jsx("p",{className:"text-sm text-muted-foreground max-w-md mx-auto",children:n})]})});m4.displayName="LoadingState";const g4=I.forwardRef(({title:e,subtitle:t,leading:n,trailing:r,showBorder:o=!0,isMobile:a=!1,className:l,...c},d)=>w.jsx("div",{ref:d,className:Re("flex-shrink-0",o&&"border-b border-border",a?"p-3":"p-4","bg-card",l),...c,children:w.jsxs("div",{className:"flex items-center justify-between gap-3",children:[w.jsxs("div",{className:"flex items-center gap-2 sm:gap-3 min-w-0 flex-1",children:[n&&w.jsx("div",{className:"flex-shrink-0",children:n}),w.jsxs("div",{className:"min-w-0 flex-1",children:[w.jsx("h1",{className:Re("font-semibold text-foreground truncate",a?"text-base":"text-base sm:text-lg"),children:e}),t&&w.jsx("p",{className:Re("text-xs text-muted-foreground truncate",a?"mt-0":"mt-0.5"),children:t})]})]}),r&&w.jsx("div",{className:"flex-shrink-0 hidden sm:block",children:r})]})}));g4.displayName="PageHeader";I.createContext(void 0);const y4=I.forwardRef(({className:e,children:t,...n},r)=>w.jsx("div",{ref:r,className:Re("relative overflow-hidden",e),...n,children:w.jsx("div",{className:"h-full w-full rounded-[inherit] overflow-auto",style:{WebkitOverflowScrolling:"touch",touchAction:"pan-y"},children:t})}));y4.displayName="ScrollArea";const v4=I.forwardRef(({value:e,onChange:t,onClear:n,showSearchIcon:r=!0,showClearButton:o=!0,searchIcon:a,clearIcon:l,placeholder:c="Search...",className:d,...f},p)=>{const m=b=>{t(b.target.value)},y=()=>{n?n():t("")},v=e&&e.length>0;return w.jsxs("div",{className:"relative",children:[r&&w.jsx("div",{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground pointer-events-none",children:a||w.jsx(vw,{className:"w-4 h-4"})}),w.jsx("input",{ref:p,type:"text",value:e,onChange:m,placeholder:c,className:Re("w-full h-9 rounded-md border border-input bg-background px-3 py-2 text-sm","placeholder:text-muted-foreground","focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-0","disabled:cursor-not-allowed disabled:opacity-50","transition-colors",r&&"pl-9",v&&o&&"pr-9",d),...f}),v&&o&&w.jsx("button",{type:"button",onClick:y,className:Re("absolute right-2 top-1/2 transform -translate-y-1/2","p-1 rounded hover:bg-accent transition-colors","text-muted-foreground hover:text-foreground"),"aria-label":"Clear search",children:l||w.jsx(p_,{className:"w-3 h-3"})})]})});v4.displayName="SearchInput";const x4=uc("inline-flex items-center justify-center rounded-lg p-1",{variants:{variant:{pills:"bg-muted",underline:"border-b border-border bg-transparent p-0"}},defaultVariants:{variant:"pills"}}),w4=uc("inline-flex items-center justify-center whitespace-nowrap rounded-md px-3 py-1.5 text-sm font-medium transition-all duration-200 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50",{variants:{variant:{pills:"",underline:"rounded-none border-b-2 border-transparent"},active:{true:"",false:""}},compoundVariants:[{variant:"pills",active:!0,className:"bg-background text-foreground shadow-sm"},{variant:"pills",active:!1,className:"text-muted-foreground hover:text-foreground hover:bg-background/50"},{variant:"underline",active:!0,className:"border-primary text-foreground"},{variant:"underline",active:!1,className:"text-muted-foreground hover:text-foreground hover:border-border"}],defaultVariants:{variant:"pills",active:!1}}),b4=I.forwardRef(({tabs:e,activeTab:t,onTabChange:n,variant:r="pills",iconOnlyMobile:o=!1,className:a,...l},c)=>w.jsx("div",{ref:c,role:"tablist",className:Re(x4({variant:r}),a),...l,children:e.map(d=>{const f=d.id===t;return w.jsxs("button",{role:"tab",type:"button","aria-selected":f,"aria-controls":`tabpanel-${d.id}`,disabled:d.disabled,onClick:()=>!d.disabled&&n(d.id),className:Re(w4({variant:r,active:f})),children:[d.icon&&w.jsx("span",{className:"flex items-center justify-center w-4 h-4",children:d.icon}),d.label&&w.jsx("span",{className:Re(d.icon&&"ml-1.5",o&&"hidden sm:inline"),children:d.label})]},d.id)})}));b4.displayName="TabNavigation";function S4(e,t=new Date){const n=typeof e=="string"?new Date(e):e;if(isNaN(n.getTime()))return"Unknown";const r=t.getTime()-n.getTime(),o=Math.floor(r/1e3),a=Math.floor(r/(1e3*60)),l=Math.floor(r/(1e3*60*60)),c=Math.floor(r/(1e3*60*60*24));return o<60?"Just now":a===1?"1 min ago":a<60?`${a} mins ago`:l===1?"1 hour ago":l<24?`${l} hours ago`:c===1?"1 day ago":c<7?`${c} days ago`:n.toLocaleDateString()}const k4=I.forwardRef(({date:e,updateInterval:t=6e4,showTooltip:n=!0,className:r,...o},a)=>{const[l,c]=I.useState(new Date);I.useEffect(()=>{if(t<=0)return;const p=setInterval(()=>{c(new Date)},t);return()=>clearInterval(p)},[t]);const d=S4(e,l),f=I.useMemo(()=>{const p=typeof e=="string"?new Date(e):e;if(!isNaN(p.getTime()))return p.toLocaleString()},[e]);return w.jsx("span",{ref:a,className:Re("inline-block",r),title:n?f:void 0,...o,children:d})});k4.displayName="TimeAgo";function E4(e){return{all:e=e||new Map,on:function(t,n){var r=e.get(t);r?r.push(n):e.set(t,[n])},off:function(t,n){var r=e.get(t);r&&(n?r.splice(r.indexOf(n)>>>0,1):e.set(t,[]))},emit:function(t,n){var r=e.get(t);r&&r.slice().map(function(o){o(n)}),(r=e.get("*"))&&r.slice().map(function(o){o(t,n)})}}}class C4{constructor(){Zy(this,"emitter"),Zy(this,"debugMode",!1),this.emitter=E4()}emit(t,n){this.debugMode&&console.log("[EventBus]",t,n),this.emitter.emit(t,n)}on(t,n){this.emitter.on(t,n)}off(t,n){this.emitter.off(t,n)}onAll(t){this.emitter.on("*",t)}clear(){this.emitter.all.clear()}enableDebug(){this.debugMode=!0,typeof console<"u"&&console.log("[EventBus] Debug mode enabled")}disableDebug(){this.debugMode=!1,typeof console<"u"&&console.log("[EventBus] Debug mode disabled")}}new C4;typeof window<"u"&&setTimeout(()=>{},0);const Px="/agentx",I4=[{name:"Assistant",description:"AI Assistant powered by Claude",icon:"A",color:"bg-primary",isOnline:!0}];function T4(){return w.jsx("div",{className:"h-screen bg-background flex items-center justify-center",children:w.jsxs("div",{className:"text-center",children:[w.jsx("div",{className:"text-4xl mb-4 animate-pulse text-muted-foreground",children:"..."}),w.jsx("p",{className:"text-muted-foreground",children:"Connecting to server..."})]})})}function Ax({message:e,onRetry:t}){return w.jsx("div",{className:"h-screen bg-background flex items-center justify-center",children:w.jsxs("div",{className:"text-center p-8 max-w-md",children:[w.jsx("h2",{className:"text-xl font-semibold text-foreground mb-2",children:"Connection Error"}),w.jsx("p",{className:"text-muted-foreground mb-4",children:e}),w.jsx("button",{onClick:t,className:"px-4 py-2 bg-primary text-primary-foreground rounded-md hover:bg-primary/90",children:"Retry"})]})})}function _4({onLogout:e}){return w.jsxs("div",{className:"h-12 bg-card border-b border-border flex items-center justify-between px-4",children:[w.jsxs("div",{className:"flex items-center gap-2",children:[w.jsx("span",{className:"text-lg font-semibold text-foreground",children:"Portagent"}),w.jsx("span",{className:"text-xs text-muted-foreground",children:"AgentX Portal"})]}),w.jsx("button",{onClick:e,className:"text-sm text-muted-foreground hover:text-foreground transition-colors",children:"Sign Out"})]})}function P4(){const{user:e,logout:t}=nc(),[n,r]=I.useState(null),[o,a]=I.useState(null),[l,c]=I.useState(!0);I.useEffect(()=>{let f=!0;return(async()=>{try{const m=HC();if(!m){a("Not authenticated");return}if(!(await fetch(`${Px}/info`,{headers:{Authorization:`Bearer ${m}`}})).ok)throw new Error("Server returned error");if(!f)return;const v=FT(GT({serverUrl:Px,headers:{Authorization:`Bearer ${m}`},sseParams:{token:m}}));if(!f)return;r(v),a(null)}catch(m){if(!f)return;console.error("Connection error:",m),a("Cannot connect to server")}finally{f&&c(!1)}})(),()=>{f=!1}},[]);const d=()=>{c(!0),a(null),window.location.reload()};return l?w.jsx(T4,{}):o?w.jsx(Ax,{message:o,onRetry:d}):!n||!e?w.jsx(Ax,{message:"Failed to initialize",onRetry:d}):w.jsxs("div",{className:"h-screen flex flex-col bg-background",children:[w.jsx(_4,{onLogout:t}),w.jsx("div",{className:"flex-1 overflow-hidden",children:w.jsx(t4,{agentx:n,userId:e.userId,containerId:e.containerId,definitions:I4})})]})}function A4({children:e}){const{isAuthenticated:t,isLoading:n}=nc();return n?w.jsx("div",{className:"h-screen flex items-center justify-center bg-slate-900",children:w.jsx("div",{className:"text-slate-400",children:"Loading..."})}):t?w.jsx(w.Fragment,{children:e}):w.jsx(Hf,{to:"/login",replace:!0})}function R4(){return w.jsx(UC,{children:w.jsxs(oC,{children:[w.jsx(Js,{path:"/login",element:w.jsx(WC,{})}),w.jsx(Js,{path:"/register",element:w.jsx(qC,{})}),w.jsx(Js,{path:"/studio",element:w.jsx(A4,{children:w.jsx(P4,{})})}),w.jsx(Js,{path:"/",element:w.jsx(Hf,{to:"/studio",replace:!0})}),w.jsx(Js,{path:"*",element:w.jsx(Hf,{to:"/studio",replace:!0})})]})})}mE.createRoot(document.getElementById("root")).render(w.jsx(wr.StrictMode,{children:w.jsx(PC,{children:w.jsx(R4,{})})}));
245
- //# sourceMappingURL=index-CRtZvfg5.js.map
245
+ //# sourceMappingURL=index-Diy1g-AB.js.map