@auxiora/dashboard 1.10.15 → 1.10.18
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.
|
@@ -57,6 +57,6 @@ Error generating stack: `+l.message+`
|
|
|
57
57
|
* @license MIT
|
|
58
58
|
*/var Gh="popstate";function xv(s={}){function r(o,f){let{pathname:m,search:p,hash:x}=o.location;return Ou("",{pathname:m,search:p,hash:x},f.state&&f.state.usr||null,f.state&&f.state.key||"default")}function u(o,f){return typeof f=="string"?f:ws(f)}return jv(r,u,null,s)}function Fe(s,r){if(s===!1||s===null||typeof s>"u")throw new Error(r)}function ca(s,r){if(!s){typeof console<"u"&&console.warn(r);try{throw new Error(r)}catch{}}}function bv(){return Math.random().toString(36).substring(2,10)}function $h(s,r){return{usr:s.state,key:s.key,idx:r}}function Ou(s,r,u=null,o){return{pathname:typeof s=="string"?s:s.pathname,search:"",hash:"",...typeof r=="string"?Cl(r):r,state:u,key:r&&r.key||o||bv()}}function ws({pathname:s="/",search:r="",hash:u=""}){return r&&r!=="?"&&(s+=r.charAt(0)==="?"?r:"?"+r),u&&u!=="#"&&(s+=u.charAt(0)==="#"?u:"#"+u),s}function Cl(s){let r={};if(s){let u=s.indexOf("#");u>=0&&(r.hash=s.substring(u),s=s.substring(0,u));let o=s.indexOf("?");o>=0&&(r.search=s.substring(o),s=s.substring(0,o)),s&&(r.pathname=s)}return r}function jv(s,r,u,o={}){let{window:f=document.defaultView,v5Compat:m=!1}=o,p=f.history,x="POP",y=null,g=b();g==null&&(g=0,p.replaceState({...p.state,idx:g},""));function b(){return(p.state||{idx:null}).idx}function j(){x="POP";let O=b(),E=O==null?null:O-g;g=O,y&&y({action:x,location:D.location,delta:E})}function S(O,E){x="PUSH";let M=Ou(D.location,O,E);g=b()+1;let k=$h(M,g),Z=D.createHref(M);try{p.pushState(k,"",Z)}catch(K){if(K instanceof DOMException&&K.name==="DataCloneError")throw K;f.location.assign(Z)}m&&y&&y({action:x,location:D.location,delta:1})}function w(O,E){x="REPLACE";let M=Ou(D.location,O,E);g=b();let k=$h(M,g),Z=D.createHref(M);p.replaceState(k,"",Z),m&&y&&y({action:x,location:D.location,delta:0})}function A(O){return Sv(O)}let D={get action(){return x},get location(){return s(f,p)},listen(O){if(y)throw new Error("A history only accepts one active listener");return f.addEventListener(Gh,j),y=O,()=>{f.removeEventListener(Gh,j),y=null}},createHref(O){return r(f,O)},createURL:A,encodeLocation(O){let E=A(O);return{pathname:E.pathname,search:E.search,hash:E.hash}},push:S,replace:w,go(O){return p.go(O)}};return D}function Sv(s,r=!1){let u="http://localhost";typeof window<"u"&&(u=window.location.origin!=="null"?window.location.origin:window.location.href),Fe(u,"No window.location.(origin|href) available to create URL");let o=typeof s=="string"?s:ws(s);return o=o.replace(/ $/,"%20"),!r&&o.startsWith("//")&&(o=u+o),new URL(o,u)}function dm(s,r,u="/"){return Nv(s,r,u,!1)}function Nv(s,r,u,o){let f=typeof r=="string"?Cl(r):r,m=Ba(f.pathname||"/",u);if(m==null)return null;let p=fm(s);Cv(p);let x=null;for(let y=0;x==null&&y<p.length;++y){let g=_v(m);x=zv(p[y],g,o)}return x}function fm(s,r=[],u=[],o="",f=!1){let m=(p,x,y=f,g)=>{let b={relativePath:g===void 0?p.path||"":g,caseSensitive:p.caseSensitive===!0,childrenIndex:x,route:p};if(b.relativePath.startsWith("/")){if(!b.relativePath.startsWith(o)&&y)return;Fe(b.relativePath.startsWith(o),`Absolute route path "${b.relativePath}" nested under path "${o}" is not valid. An absolute child route path must start with the combined path of all its parent routes.`),b.relativePath=b.relativePath.slice(o.length)}let j=La([o,b.relativePath]),S=u.concat(b);p.children&&p.children.length>0&&(Fe(p.index!==!0,`Index routes must not have child routes. Please remove all child routes from route path "${j}".`),fm(p.children,r,S,j,y)),!(p.path==null&&!p.index)&&r.push({path:j,score:Rv(j,p.index),routesMeta:S})};return s.forEach((p,x)=>{var y;if(p.path===""||!((y=p.path)!=null&&y.includes("?")))m(p,x);else for(let g of hm(p.path))m(p,x,!0,g)}),r}function hm(s){let r=s.split("/");if(r.length===0)return[];let[u,...o]=r,f=u.endsWith("?"),m=u.replace(/\?$/,"");if(o.length===0)return f?[m,""]:[m];let p=hm(o.join("/")),x=[];return x.push(...p.map(y=>y===""?m:[m,y].join("/"))),f&&x.push(...p),x.map(y=>s.startsWith("/")&&y===""?"/":y)}function Cv(s){s.sort((r,u)=>r.score!==u.score?u.score-r.score:Dv(r.routesMeta.map(o=>o.childrenIndex),u.routesMeta.map(o=>o.childrenIndex)))}var Ev=/^:[\w-]+$/,wv=3,Tv=2,Av=1,Ov=10,Mv=-2,Xh=s=>s==="*";function Rv(s,r){let u=s.split("/"),o=u.length;return u.some(Xh)&&(o+=Mv),r&&(o+=Tv),u.filter(f=>!Xh(f)).reduce((f,m)=>f+(Ev.test(m)?wv:m===""?Av:Ov),o)}function Dv(s,r){return s.length===r.length&&s.slice(0,-1).every((o,f)=>o===r[f])?s[s.length-1]-r[r.length-1]:0}function zv(s,r,u=!1){let{routesMeta:o}=s,f={},m="/",p=[];for(let x=0;x<o.length;++x){let y=o[x],g=x===o.length-1,b=m==="/"?r:r.slice(m.length)||"/",j=Fi({path:y.relativePath,caseSensitive:y.caseSensitive,end:g},b),S=y.route;if(!j&&g&&u&&!o[o.length-1].route.index&&(j=Fi({path:y.relativePath,caseSensitive:y.caseSensitive,end:!1},b)),!j)return null;Object.assign(f,j.params),p.push({params:f,pathname:La([m,j.pathname]),pathnameBase:Hv(La([m,j.pathnameBase])),route:S}),j.pathnameBase!=="/"&&(m=La([m,j.pathnameBase]))}return p}function Fi(s,r){typeof s=="string"&&(s={path:s,caseSensitive:!1,end:!0});let[u,o]=kv(s.path,s.caseSensitive,s.end),f=r.match(u);if(!f)return null;let m=f[0],p=m.replace(/(.)\/+$/,"$1"),x=f.slice(1);return{params:o.reduce((g,{paramName:b,isOptional:j},S)=>{if(b==="*"){let A=x[S]||"";p=m.slice(0,m.length-A.length).replace(/(.)\/+$/,"$1")}const w=x[S];return j&&!w?g[b]=void 0:g[b]=(w||"").replace(/%2F/g,"/"),g},{}),pathname:m,pathnameBase:p,pattern:s}}function kv(s,r=!1,u=!0){ca(s==="*"||!s.endsWith("*")||s.endsWith("/*"),`Route path "${s}" will be treated as if it were "${s.replace(/\*$/,"/*")}" because the \`*\` character must always follow a \`/\` in the pattern. To get rid of this warning, please change the route path to "${s.replace(/\*$/,"/*")}".`);let o=[],f="^"+s.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(p,x,y)=>(o.push({paramName:x,isOptional:y!=null}),y?"/?([^\\/]+)?":"/([^\\/]+)")).replace(/\/([\w-]+)\?(\/|$)/g,"(/$1)?$2");return s.endsWith("*")?(o.push({paramName:"*"}),f+=s==="*"||s==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):u?f+="\\/*$":s!==""&&s!=="/"&&(f+="(?:(?=\\/|$))"),[new RegExp(f,r?void 0:"i"),o]}function _v(s){try{return s.split("/").map(r=>decodeURIComponent(r).replace(/\//g,"%2F")).join("/")}catch(r){return ca(!1,`The URL path "${s}" could not be decoded because it is a malformed URL segment. This is probably due to a bad percent encoding (${r}).`),s}}function Ba(s,r){if(r==="/")return s;if(!s.toLowerCase().startsWith(r.toLowerCase()))return null;let u=r.endsWith("/")?r.length-1:r.length,o=s.charAt(u);return o&&o!=="/"?null:s.slice(u)||"/"}var Uv=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;function Lv(s,r="/"){let{pathname:u,search:o="",hash:f=""}=typeof s=="string"?Cl(s):s,m;return u?(u=u.replace(/\/\/+/g,"/"),u.startsWith("/")?m=Vh(u.substring(1),"/"):m=Vh(u,r)):m=r,{pathname:m,search:qv(o),hash:Yv(f)}}function Vh(s,r){let u=r.replace(/\/+$/,"").split("/");return s.split("/").forEach(f=>{f===".."?u.length>1&&u.pop():f!=="."&&u.push(f)}),u.length>1?u.join("/"):"/"}function bu(s,r,u,o){return`Cannot include a '${s}' character in a manually specified \`to.${r}\` field [${JSON.stringify(o)}]. Please separate it out to the \`to.${u}\` field. Alternatively you may provide the full path as a string in <Link to="..."> and the router will parse it for you.`}function Bv(s){return s.filter((r,u)=>u===0||r.route.path&&r.route.path.length>0)}function zu(s){let r=Bv(s);return r.map((u,o)=>o===r.length-1?u.pathname:u.pathnameBase)}function ku(s,r,u,o=!1){let f;typeof s=="string"?f=Cl(s):(f={...s},Fe(!f.pathname||!f.pathname.includes("?"),bu("?","pathname","search",f)),Fe(!f.pathname||!f.pathname.includes("#"),bu("#","pathname","hash",f)),Fe(!f.search||!f.search.includes("#"),bu("#","search","hash",f)));let m=s===""||f.pathname==="",p=m?"/":f.pathname,x;if(p==null)x=u;else{let j=r.length-1;if(!o&&p.startsWith("..")){let S=p.split("/");for(;S[0]==="..";)S.shift(),j-=1;f.pathname=S.join("/")}x=j>=0?r[j]:"/"}let y=Lv(f,x),g=p&&p!=="/"&&p.endsWith("/"),b=(m||p===".")&&u.endsWith("/");return!y.pathname.endsWith("/")&&(g||b)&&(y.pathname+="/"),y}var La=s=>s.join("/").replace(/\/\/+/g,"/"),Hv=s=>s.replace(/\/+$/,"").replace(/^\/*/,"/"),qv=s=>!s||s==="?"?"":s.startsWith("?")?s:"?"+s,Yv=s=>!s||s==="#"?"":s.startsWith("#")?s:"#"+s,Gv=class{constructor(s,r,u,o=!1){this.status=s,this.statusText=r||"",this.internal=o,u instanceof Error?(this.data=u.toString(),this.error=u):this.data=u}};function $v(s){return s!=null&&typeof s.status=="number"&&typeof s.statusText=="string"&&typeof s.internal=="boolean"&&"data"in s}function Xv(s){return s.map(r=>r.route.path).filter(Boolean).join("/").replace(/\/\/*/g,"/")||"/"}var mm=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function pm(s,r){let u=s;if(typeof u!="string"||!Uv.test(u))return{absoluteURL:void 0,isExternal:!1,to:u};let o=u,f=!1;if(mm)try{let m=new URL(window.location.href),p=u.startsWith("//")?new URL(m.protocol+u):new URL(u),x=Ba(p.pathname,r);p.origin===m.origin&&x!=null?u=x+p.search+p.hash:f=!0}catch{ca(!1,`<Link to="${u}"> contains an invalid URL which will probably break when clicked - please update to a valid URL path.`)}return{absoluteURL:o,isExternal:f,to:u}}Object.getOwnPropertyNames(Object.prototype).sort().join("\0");var gm=["POST","PUT","PATCH","DELETE"];new Set(gm);var Vv=["GET",...gm];new Set(Vv);var El=h.createContext(null);El.displayName="DataRouter";var Ii=h.createContext(null);Ii.displayName="DataRouterState";var Qv=h.createContext(!1),vm=h.createContext({isTransitioning:!1});vm.displayName="ViewTransition";var Kv=h.createContext(new Map);Kv.displayName="Fetchers";var Zv=h.createContext(null);Zv.displayName="Await";var Xt=h.createContext(null);Xt.displayName="Navigation";var Ts=h.createContext(null);Ts.displayName="Location";var ma=h.createContext({outlet:null,matches:[],isDataRoute:!1});ma.displayName="Route";var _u=h.createContext(null);_u.displayName="RouteError";var ym="REACT_ROUTER_ERROR",Jv="REDIRECT",Wv="ROUTE_ERROR_RESPONSE";function Fv(s){if(s.startsWith(`${ym}:${Jv}:{`))try{let r=JSON.parse(s.slice(28));if(typeof r=="object"&&r&&typeof r.status=="number"&&typeof r.statusText=="string"&&typeof r.location=="string"&&typeof r.reloadDocument=="boolean"&&typeof r.replace=="boolean")return r}catch{}}function Pv(s){if(s.startsWith(`${ym}:${Wv}:{`))try{let r=JSON.parse(s.slice(40));if(typeof r=="object"&&r&&typeof r.status=="number"&&typeof r.statusText=="string")return new Gv(r.status,r.statusText,r.data)}catch{}}function Iv(s,{relative:r}={}){Fe(wl(),"useHref() may be used only in the context of a <Router> component.");let{basename:u,navigator:o}=h.useContext(Xt),{hash:f,pathname:m,search:p}=As(s,{relative:r}),x=m;return u!=="/"&&(x=m==="/"?u:La([u,m])),o.createHref({pathname:x,search:p,hash:f})}function wl(){return h.useContext(Ts)!=null}function hn(){return Fe(wl(),"useLocation() may be used only in the context of a <Router> component."),h.useContext(Ts).location}var xm="You should call navigate() in a React.useEffect(), not when your component is first rendered.";function bm(s){h.useContext(Xt).static||h.useLayoutEffect(s)}function Ct(){let{isDataRoute:s}=h.useContext(ma);return s?fy():ey()}function ey(){Fe(wl(),"useNavigate() may be used only in the context of a <Router> component.");let s=h.useContext(El),{basename:r,navigator:u}=h.useContext(Xt),{matches:o}=h.useContext(ma),{pathname:f}=hn(),m=JSON.stringify(zu(o)),p=h.useRef(!1);return bm(()=>{p.current=!0}),h.useCallback((y,g={})=>{if(ca(p.current,xm),!p.current)return;if(typeof y=="number"){u.go(y);return}let b=ku(y,JSON.parse(m),f,g.relative==="path");s==null&&r!=="/"&&(b.pathname=b.pathname==="/"?r:La([r,b.pathname])),(g.replace?u.replace:u.push)(b,g.state,g)},[r,u,m,f,s])}h.createContext(null);function As(s,{relative:r}={}){let{matches:u}=h.useContext(ma),{pathname:o}=hn(),f=JSON.stringify(zu(u));return h.useMemo(()=>ku(s,JSON.parse(f),o,r==="path"),[s,f,o,r])}function ty(s,r){return jm(s,r)}function jm(s,r,u,o,f){var M;Fe(wl(),"useRoutes() may be used only in the context of a <Router> component.");let{navigator:m}=h.useContext(Xt),{matches:p}=h.useContext(ma),x=p[p.length-1],y=x?x.params:{},g=x?x.pathname:"/",b=x?x.pathnameBase:"/",j=x&&x.route;{let k=j&&j.path||"";Nm(g,!j||k.endsWith("*")||k.endsWith("*?"),`You rendered descendant <Routes> (or called \`useRoutes()\`) at "${g}" (under <Route path="${k}">) 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.
|
|
59
59
|
|
|
60
|
-
Please change the parent <Route path="${k}"> to <Route path="${k==="/"?"*":`${k}/*`}">.`)}let S=hn(),w;if(r){let k=typeof r=="string"?Cl(r):r;Fe(b==="/"||((M=k.pathname)==null?void 0:M.startsWith(b)),`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 "${b}" but pathname "${k.pathname}" was given in the \`location\` prop.`),w=k}else w=S;let A=w.pathname||"/",D=A;if(b!=="/"){let k=b.replace(/^\//,"").split("/");D="/"+A.replace(/^\//,"").split("/").slice(k.length).join("/")}let O=dm(s,{pathname:D});ca(j||O!=null,`No routes matched location "${w.pathname}${w.search}${w.hash}" `),ca(O==null||O[O.length-1].route.element!==void 0||O[O.length-1].route.Component!==void 0||O[O.length-1].route.lazy!==void 0,`Matched leaf route at location "${w.pathname}${w.search}${w.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=iy(O&&O.map(k=>Object.assign({},k,{params:Object.assign({},y,k.params),pathname:La([b,m.encodeLocation?m.encodeLocation(k.pathname.replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:k.pathname]),pathnameBase:k.pathnameBase==="/"?b:La([b,m.encodeLocation?m.encodeLocation(k.pathnameBase.replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:k.pathnameBase])})),p,u,o,f);return r&&E?h.createElement(Ts.Provider,{value:{location:{pathname:"/",search:"",hash:"",state:null,key:"default",...w},navigationType:"POP"}},E):E}function ay(){let s=dy(),r=$v(s)?`${s.status} ${s.statusText}`:s instanceof Error?s.message:JSON.stringify(s),u=s instanceof Error?s.stack:null,o="rgba(200,200,200, 0.5)",f={padding:"0.5rem",backgroundColor:o},m={padding:"2px 4px",backgroundColor:o},p=null;return console.error("Error handled by React Router default ErrorBoundary:",s),p=h.createElement(h.Fragment,null,h.createElement("p",null,"💿 Hey developer 👋"),h.createElement("p",null,"You can provide a way better UX than this when your app throws errors by providing your own ",h.createElement("code",{style:m},"ErrorBoundary")," or"," ",h.createElement("code",{style:m},"errorElement")," prop on your route.")),h.createElement(h.Fragment,null,h.createElement("h2",null,"Unexpected Application Error!"),h.createElement("h3",{style:{fontStyle:"italic"}},r),u?h.createElement("pre",{style:f},u):null,p)}var ny=h.createElement(ay,null),Sm=class extends h.Component{constructor(s){super(s),this.state={location:s.location,revalidation:s.revalidation,error:s.error}}static getDerivedStateFromError(s){return{error:s}}static getDerivedStateFromProps(s,r){return r.location!==s.location||r.revalidation!=="idle"&&s.revalidation==="idle"?{error:s.error,location:s.location,revalidation:s.revalidation}:{error:s.error!==void 0?s.error:r.error,location:r.location,revalidation:s.revalidation||r.revalidation}}componentDidCatch(s,r){this.props.onError?this.props.onError(s,r):console.error("React Router caught the following error during render",s)}render(){let s=this.state.error;if(this.context&&typeof s=="object"&&s&&"digest"in s&&typeof s.digest=="string"){const u=Pv(s.digest);u&&(s=u)}let r=s!==void 0?h.createElement(ma.Provider,{value:this.props.routeContext},h.createElement(_u.Provider,{value:s,children:this.props.component})):this.props.children;return this.context?h.createElement(ly,{error:s},r):r}};Sm.contextType=Qv;var ju=new WeakMap;function ly({children:s,error:r}){let{basename:u}=h.useContext(Xt);if(typeof r=="object"&&r&&"digest"in r&&typeof r.digest=="string"){let o=Fv(r.digest);if(o){let f=ju.get(r);if(f)throw f;let m=pm(o.location,u);if(mm&&!ju.get(r))if(m.isExternal||o.reloadDocument)window.location.href=m.absoluteURL||m.to;else{const p=Promise.resolve().then(()=>window.__reactRouterDataRouter.navigate(m.to,{replace:o.replace}));throw ju.set(r,p),p}return h.createElement("meta",{httpEquiv:"refresh",content:`0;url=${m.absoluteURL||m.to}`})}}return s}function sy({routeContext:s,match:r,children:u}){let o=h.useContext(El);return o&&o.static&&o.staticContext&&(r.route.errorElement||r.route.ErrorBoundary)&&(o.staticContext._deepestRenderedBoundaryId=r.route.id),h.createElement(ma.Provider,{value:s},u)}function iy(s,r=[],u=null,o=null,f=null){if(s==null){if(!u)return null;if(u.errors)s=u.matches;else if(r.length===0&&!u.initialized&&u.matches.length>0)s=u.matches;else return null}let m=s,p=u==null?void 0:u.errors;if(p!=null){let b=m.findIndex(j=>j.route.id&&(p==null?void 0:p[j.route.id])!==void 0);Fe(b>=0,`Could not find a matching route for errors on route IDs: ${Object.keys(p).join(",")}`),m=m.slice(0,Math.min(m.length,b+1))}let x=!1,y=-1;if(u)for(let b=0;b<m.length;b++){let j=m[b];if((j.route.HydrateFallback||j.route.hydrateFallbackElement)&&(y=b),j.route.id){let{loaderData:S,errors:w}=u,A=j.route.loader&&!S.hasOwnProperty(j.route.id)&&(!w||w[j.route.id]===void 0);if(j.route.lazy||A){x=!0,y>=0?m=m.slice(0,y+1):m=[m[0]];break}}}let g=u&&o?(b,j)=>{var S,w;o(b,{location:u.location,params:((w=(S=u.matches)==null?void 0:S[0])==null?void 0:w.params)??{},unstable_pattern:Xv(u.matches),errorInfo:j})}:void 0;return m.reduceRight((b,j,S)=>{let w,A=!1,D=null,O=null;u&&(w=p&&j.route.id?p[j.route.id]:void 0,D=j.route.errorElement||ny,x&&(y<0&&S===0?(Nm("route-fallback",!1,"No `HydrateFallback` element provided to render during initial hydration"),A=!0,O=null):y===S&&(A=!0,O=j.route.hydrateFallbackElement||null)));let E=r.concat(m.slice(0,S+1)),M=()=>{let k;return w?k=D:A?k=O:j.route.Component?k=h.createElement(j.route.Component,null):j.route.element?k=j.route.element:k=b,h.createElement(sy,{match:j,routeContext:{outlet:b,matches:E,isDataRoute:u!=null},children:k})};return u&&(j.route.ErrorBoundary||j.route.errorElement||S===0)?h.createElement(Sm,{location:u.location,revalidation:u.revalidation,component:D,error:w,children:M(),routeContext:{outlet:null,matches:E,isDataRoute:!0},onError:g}):M()},null)}function Uu(s){return`${s} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function cy(s){let r=h.useContext(El);return Fe(r,Uu(s)),r}function ry(s){let r=h.useContext(Ii);return Fe(r,Uu(s)),r}function uy(s){let r=h.useContext(ma);return Fe(r,Uu(s)),r}function Lu(s){let r=uy(s),u=r.matches[r.matches.length-1];return Fe(u.route.id,`${s} can only be used on routes that contain a unique "id"`),u.route.id}function oy(){return Lu("useRouteId")}function dy(){var o;let s=h.useContext(_u),r=ry("useRouteError"),u=Lu("useRouteError");return s!==void 0?s:(o=r.errors)==null?void 0:o[u]}function fy(){let{router:s}=cy("useNavigate"),r=Lu("useNavigate"),u=h.useRef(!1);return bm(()=>{u.current=!0}),h.useCallback(async(f,m={})=>{ca(u.current,xm),u.current&&(typeof f=="number"?await s.navigate(f):await s.navigate(f,{fromRouteId:r,...m}))},[s,r])}var Qh={};function Nm(s,r,u){!r&&!Qh[s]&&(Qh[s]=!0,ca(!1,u))}h.memo(hy);function hy({routes:s,future:r,state:u,onError:o}){return jm(s,void 0,u,o,r)}function Kh({to:s,replace:r,state:u,relative:o}){Fe(wl(),"<Navigate> may be used only in the context of a <Router> component.");let{static:f}=h.useContext(Xt);ca(!f,"<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:m}=h.useContext(ma),{pathname:p}=hn(),x=Ct(),y=ku(s,zu(m),p,o==="path"),g=JSON.stringify(y);return h.useEffect(()=>{x(JSON.parse(g),{replace:r,state:u,relative:o})},[x,g,o,r,u]),null}function ke(s){Fe(!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 my({basename:s="/",children:r=null,location:u,navigationType:o="POP",navigator:f,static:m=!1,unstable_useTransitions:p}){Fe(!wl(),"You cannot render a <Router> inside another <Router>. You should never have more than one in your app.");let x=s.replace(/^\/*/,"/"),y=h.useMemo(()=>({basename:x,navigator:f,static:m,unstable_useTransitions:p,future:{}}),[x,f,m,p]);typeof u=="string"&&(u=Cl(u));let{pathname:g="/",search:b="",hash:j="",state:S=null,key:w="default"}=u,A=h.useMemo(()=>{let D=Ba(g,x);return D==null?null:{location:{pathname:D,search:b,hash:j,state:S,key:w},navigationType:o}},[x,g,b,j,S,w,o]);return ca(A!=null,`<Router basename="${x}"> is not able to match the URL "${g}${b}${j}" because it does not start with the basename, so the <Router> won't render anything.`),A==null?null:h.createElement(Xt.Provider,{value:y},h.createElement(Ts.Provider,{children:r,value:A}))}function py({children:s,location:r}){return ty(Mu(s),r)}function Mu(s,r=[]){let u=[];return h.Children.forEach(s,(o,f)=>{if(!h.isValidElement(o))return;let m=[...r,f];if(o.type===h.Fragment){u.push.apply(u,Mu(o.props.children,m));return}Fe(o.type===ke,`[${typeof o.type=="string"?o.type:o.type.name}] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>`),Fe(!o.props.index||!o.props.children,"An index route cannot have child routes.");let p={id:o.props.id||m.join("-"),caseSensitive:o.props.caseSensitive,element:o.props.element,Component:o.props.Component,index:o.props.index,path:o.props.path,middleware:o.props.middleware,loader:o.props.loader,action:o.props.action,hydrateFallbackElement:o.props.hydrateFallbackElement,HydrateFallback:o.props.HydrateFallback,errorElement:o.props.errorElement,ErrorBoundary:o.props.ErrorBoundary,hasErrorBoundary:o.props.hasErrorBoundary===!0||o.props.ErrorBoundary!=null||o.props.errorElement!=null,shouldRevalidate:o.props.shouldRevalidate,handle:o.props.handle,lazy:o.props.lazy};o.props.children&&(p.children=Mu(o.props.children,m)),u.push(p)}),u}var Ji="get",Wi="application/x-www-form-urlencoded";function ec(s){return typeof HTMLElement<"u"&&s instanceof HTMLElement}function gy(s){return ec(s)&&s.tagName.toLowerCase()==="button"}function vy(s){return ec(s)&&s.tagName.toLowerCase()==="form"}function yy(s){return ec(s)&&s.tagName.toLowerCase()==="input"}function xy(s){return!!(s.metaKey||s.altKey||s.ctrlKey||s.shiftKey)}function by(s,r){return s.button===0&&(!r||r==="_self")&&!xy(s)}var Vi=null;function jy(){if(Vi===null)try{new FormData(document.createElement("form"),0),Vi=!1}catch{Vi=!0}return Vi}var Sy=new Set(["application/x-www-form-urlencoded","multipart/form-data","text/plain"]);function Su(s){return s!=null&&!Sy.has(s)?(ca(!1,`"${s}" is not a valid \`encType\` for \`<Form>\`/\`<fetcher.Form>\` and will default to "${Wi}"`),null):s}function Ny(s,r){let u,o,f,m,p;if(vy(s)){let x=s.getAttribute("action");o=x?Ba(x,r):null,u=s.getAttribute("method")||Ji,f=Su(s.getAttribute("enctype"))||Wi,m=new FormData(s)}else if(gy(s)||yy(s)&&(s.type==="submit"||s.type==="image")){let x=s.form;if(x==null)throw new Error('Cannot submit a <button> or <input type="submit"> without a <form>');let y=s.getAttribute("formaction")||x.getAttribute("action");if(o=y?Ba(y,r):null,u=s.getAttribute("formmethod")||x.getAttribute("method")||Ji,f=Su(s.getAttribute("formenctype"))||Su(x.getAttribute("enctype"))||Wi,m=new FormData(x,s),!jy()){let{name:g,type:b,value:j}=s;if(b==="image"){let S=g?`${g}.`:"";m.append(`${S}x`,"0"),m.append(`${S}y`,"0")}else g&&m.append(g,j)}}else{if(ec(s))throw new Error('Cannot submit element that is not <form>, <button>, or <input type="submit|image">');u=Ji,o=null,f=Wi,p=s}return m&&f==="text/plain"&&(p=m,m=void 0),{action:o,method:u.toLowerCase(),encType:f,formData:m,body:p}}Object.getOwnPropertyNames(Object.prototype).sort().join("\0");function Bu(s,r){if(s===!1||s===null||typeof s>"u")throw new Error(r)}function Cy(s,r,u,o){let f=typeof s=="string"?new URL(s,typeof window>"u"?"server://singlefetch/":window.location.origin):s;return u?f.pathname.endsWith("/")?f.pathname=`${f.pathname}_.${o}`:f.pathname=`${f.pathname}.${o}`:f.pathname==="/"?f.pathname=`_root.${o}`:r&&Ba(f.pathname,r)==="/"?f.pathname=`${r.replace(/\/$/,"")}/_root.${o}`:f.pathname=`${f.pathname.replace(/\/$/,"")}.${o}`,f}async function Ey(s,r){if(s.id in r)return r[s.id];try{let u=await import(s.module);return r[s.id]=u,u}catch(u){return console.error(`Error loading route module \`${s.module}\`, reloading page...`),console.error(u),window.__reactRouterContext&&window.__reactRouterContext.isSpaMode,window.location.reload(),new Promise(()=>{})}}function wy(s){return s==null?!1:s.href==null?s.rel==="preload"&&typeof s.imageSrcSet=="string"&&typeof s.imageSizes=="string":typeof s.rel=="string"&&typeof s.href=="string"}async function Ty(s,r,u){let o=await Promise.all(s.map(async f=>{let m=r.routes[f.route.id];if(m){let p=await Ey(m,u);return p.links?p.links():[]}return[]}));return Ry(o.flat(1).filter(wy).filter(f=>f.rel==="stylesheet"||f.rel==="preload").map(f=>f.rel==="stylesheet"?{...f,rel:"prefetch",as:"style"}:{...f,rel:"prefetch"}))}function Zh(s,r,u,o,f,m){let p=(y,g)=>u[g]?y.route.id!==u[g].route.id:!0,x=(y,g)=>{var b;return u[g].pathname!==y.pathname||((b=u[g].route.path)==null?void 0:b.endsWith("*"))&&u[g].params["*"]!==y.params["*"]};return m==="assets"?r.filter((y,g)=>p(y,g)||x(y,g)):m==="data"?r.filter((y,g)=>{var j;let b=o.routes[y.route.id];if(!b||!b.hasLoader)return!1;if(p(y,g)||x(y,g))return!0;if(y.route.shouldRevalidate){let S=y.route.shouldRevalidate({currentUrl:new URL(f.pathname+f.search+f.hash,window.origin),currentParams:((j=u[0])==null?void 0:j.params)||{},nextUrl:new URL(s,window.origin),nextParams:y.params,defaultShouldRevalidate:!0});if(typeof S=="boolean")return S}return!0}):[]}function Ay(s,r,{includeHydrateFallback:u}={}){return Oy(s.map(o=>{let f=r.routes[o.route.id];if(!f)return[];let m=[f.module];return f.clientActionModule&&(m=m.concat(f.clientActionModule)),f.clientLoaderModule&&(m=m.concat(f.clientLoaderModule)),u&&f.hydrateFallbackModule&&(m=m.concat(f.hydrateFallbackModule)),f.imports&&(m=m.concat(f.imports)),m}).flat(1))}function Oy(s){return[...new Set(s)]}function My(s){let r={},u=Object.keys(s).sort();for(let o of u)r[o]=s[o];return r}function Ry(s,r){let u=new Set;return new Set(r),s.reduce((o,f)=>{let m=JSON.stringify(My(f));return u.has(m)||(u.add(m),o.push({key:m,link:f})),o},[])}function Cm(){let s=h.useContext(El);return Bu(s,"You must render this element inside a <DataRouterContext.Provider> element"),s}function Dy(){let s=h.useContext(Ii);return Bu(s,"You must render this element inside a <DataRouterStateContext.Provider> element"),s}var Hu=h.createContext(void 0);Hu.displayName="FrameworkContext";function Em(){let s=h.useContext(Hu);return Bu(s,"You must render this element inside a <HydratedRouter> element"),s}function zy(s,r){let u=h.useContext(Hu),[o,f]=h.useState(!1),[m,p]=h.useState(!1),{onFocus:x,onBlur:y,onMouseEnter:g,onMouseLeave:b,onTouchStart:j}=r,S=h.useRef(null);h.useEffect(()=>{if(s==="render"&&p(!0),s==="viewport"){let D=E=>{E.forEach(M=>{p(M.isIntersecting)})},O=new IntersectionObserver(D,{threshold:.5});return S.current&&O.observe(S.current),()=>{O.disconnect()}}},[s]),h.useEffect(()=>{if(o){let D=setTimeout(()=>{p(!0)},100);return()=>{clearTimeout(D)}}},[o]);let w=()=>{f(!0)},A=()=>{f(!1),p(!1)};return u?s!=="intent"?[m,S,{}]:[m,S,{onFocus:Ns(x,w),onBlur:Ns(y,A),onMouseEnter:Ns(g,w),onMouseLeave:Ns(b,A),onTouchStart:Ns(j,w)}]:[!1,S,{}]}function Ns(s,r){return u=>{s&&s(u),u.defaultPrevented||r(u)}}function ky({page:s,...r}){let{router:u}=Cm(),o=h.useMemo(()=>dm(u.routes,s,u.basename),[u.routes,s,u.basename]);return o?h.createElement(Uy,{page:s,matches:o,...r}):null}function _y(s){let{manifest:r,routeModules:u}=Em(),[o,f]=h.useState([]);return h.useEffect(()=>{let m=!1;return Ty(s,r,u).then(p=>{m||f(p)}),()=>{m=!0}},[s,r,u]),o}function Uy({page:s,matches:r,...u}){let o=hn(),{future:f,manifest:m,routeModules:p}=Em(),{basename:x}=Cm(),{loaderData:y,matches:g}=Dy(),b=h.useMemo(()=>Zh(s,r,g,m,o,"data"),[s,r,g,m,o]),j=h.useMemo(()=>Zh(s,r,g,m,o,"assets"),[s,r,g,m,o]),S=h.useMemo(()=>{if(s===o.pathname+o.search+o.hash)return[];let D=new Set,O=!1;if(r.forEach(M=>{var Z;let k=m.routes[M.route.id];!k||!k.hasLoader||(!b.some(K=>K.route.id===M.route.id)&&M.route.id in y&&((Z=p[M.route.id])!=null&&Z.shouldRevalidate)||k.hasClientLoader?O=!0:D.add(M.route.id))}),D.size===0)return[];let E=Cy(s,x,f.unstable_trailingSlashAwareDataRequests,"data");return O&&D.size>0&&E.searchParams.set("_routes",r.filter(M=>D.has(M.route.id)).map(M=>M.route.id).join(",")),[E.pathname+E.search]},[x,f.unstable_trailingSlashAwareDataRequests,y,o,m,b,r,s,p]),w=h.useMemo(()=>Ay(j,m),[j,m]),A=_y(j);return h.createElement(h.Fragment,null,S.map(D=>h.createElement("link",{key:D,rel:"prefetch",as:"fetch",href:D,...u})),w.map(D=>h.createElement("link",{key:D,rel:"modulepreload",href:D,...u})),A.map(({key:D,link:O})=>h.createElement("link",{key:D,nonce:u.nonce,...O,crossOrigin:O.crossOrigin??u.crossOrigin})))}function Ly(...s){return r=>{s.forEach(u=>{typeof u=="function"?u(r):u!=null&&(u.current=r)})}}var By=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";try{By&&(window.__reactRouterVersion="7.13.0")}catch{}function Hy({basename:s,children:r,unstable_useTransitions:u,window:o}){let f=h.useRef();f.current==null&&(f.current=xv({window:o,v5Compat:!0}));let m=f.current,[p,x]=h.useState({action:m.action,location:m.location}),y=h.useCallback(g=>{u===!1?x(g):h.startTransition(()=>x(g))},[u]);return h.useLayoutEffect(()=>m.listen(y),[m,y]),h.createElement(my,{basename:s,children:r,location:p.location,navigationType:p.action,navigator:m,unstable_useTransitions:u})}var wm=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,Tm=h.forwardRef(function({onClick:r,discover:u="render",prefetch:o="none",relative:f,reloadDocument:m,replace:p,state:x,target:y,to:g,preventScrollReset:b,viewTransition:j,unstable_defaultShouldRevalidate:S,...w},A){let{basename:D,unstable_useTransitions:O}=h.useContext(Xt),E=typeof g=="string"&&wm.test(g),M=pm(g,D);g=M.to;let k=Iv(g,{relative:f}),[Z,K,q]=zy(o,w),W=$y(g,{replace:p,state:x,target:y,preventScrollReset:b,relative:f,viewTransition:j,unstable_defaultShouldRevalidate:S,unstable_useTransitions:O});function G(ce){r&&r(ce),ce.defaultPrevented||W(ce)}let te=h.createElement("a",{...w,...q,href:M.absoluteURL||k,onClick:M.isExternal||m?r:G,ref:Ly(A,K),target:y,"data-discover":!E&&u==="render"?"true":void 0});return Z&&!E?h.createElement(h.Fragment,null,te,h.createElement(ky,{page:k})):te});Tm.displayName="Link";var qy=h.forwardRef(function({"aria-current":r="page",caseSensitive:u=!1,className:o="",end:f=!1,style:m,to:p,viewTransition:x,children:y,...g},b){let j=As(p,{relative:g.relative}),S=hn(),w=h.useContext(Ii),{navigator:A,basename:D}=h.useContext(Xt),O=w!=null&&Zy(j)&&x===!0,E=A.encodeLocation?A.encodeLocation(j).pathname:j.pathname,M=S.pathname,k=w&&w.navigation&&w.navigation.location?w.navigation.location.pathname:null;u||(M=M.toLowerCase(),k=k?k.toLowerCase():null,E=E.toLowerCase()),k&&D&&(k=Ba(k,D)||k);const Z=E!=="/"&&E.endsWith("/")?E.length-1:E.length;let K=M===E||!f&&M.startsWith(E)&&M.charAt(Z)==="/",q=k!=null&&(k===E||!f&&k.startsWith(E)&&k.charAt(E.length)==="/"),W={isActive:K,isPending:q,isTransitioning:O},G=K?r:void 0,te;typeof o=="function"?te=o(W):te=[o,K?"active":null,q?"pending":null,O?"transitioning":null].filter(Boolean).join(" ");let ce=typeof m=="function"?m(W):m;return h.createElement(Tm,{...g,"aria-current":G,className:te,ref:b,style:ce,to:p,viewTransition:x},typeof y=="function"?y(W):y)});qy.displayName="NavLink";var Yy=h.forwardRef(({discover:s="render",fetcherKey:r,navigate:u,reloadDocument:o,replace:f,state:m,method:p=Ji,action:x,onSubmit:y,relative:g,preventScrollReset:b,viewTransition:j,unstable_defaultShouldRevalidate:S,...w},A)=>{let{unstable_useTransitions:D}=h.useContext(Xt),O=Qy(),E=Ky(x,{relative:g}),M=p.toLowerCase()==="get"?"get":"post",k=typeof x=="string"&&wm.test(x),Z=K=>{if(y&&y(K),K.defaultPrevented)return;K.preventDefault();let q=K.nativeEvent.submitter,W=(q==null?void 0:q.getAttribute("formmethod"))||p,G=()=>O(q||K.currentTarget,{fetcherKey:r,method:W,navigate:u,replace:f,state:m,relative:g,preventScrollReset:b,viewTransition:j,unstable_defaultShouldRevalidate:S});D&&u!==!1?h.startTransition(()=>G()):G()};return h.createElement("form",{ref:A,method:M,action:E,onSubmit:o?y:Z,...w,"data-discover":!k&&s==="render"?"true":void 0})});Yy.displayName="Form";function Gy(s){return`${s} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function Am(s){let r=h.useContext(El);return Fe(r,Gy(s)),r}function $y(s,{target:r,replace:u,state:o,preventScrollReset:f,relative:m,viewTransition:p,unstable_defaultShouldRevalidate:x,unstable_useTransitions:y}={}){let g=Ct(),b=hn(),j=As(s,{relative:m});return h.useCallback(S=>{if(by(S,r)){S.preventDefault();let w=u!==void 0?u:ws(b)===ws(j),A=()=>g(s,{replace:w,state:o,preventScrollReset:f,relative:m,viewTransition:p,unstable_defaultShouldRevalidate:x});y?h.startTransition(()=>A()):A()}},[b,g,j,u,o,r,s,f,m,p,x,y])}var Xy=0,Vy=()=>`__${String(++Xy)}__`;function Qy(){let{router:s}=Am("useSubmit"),{basename:r}=h.useContext(Xt),u=oy(),o=s.fetch,f=s.navigate;return h.useCallback(async(m,p={})=>{let{action:x,method:y,encType:g,formData:b,body:j}=Ny(m,r);if(p.navigate===!1){let S=p.fetcherKey||Vy();await o(S,u,p.action||x,{unstable_defaultShouldRevalidate:p.unstable_defaultShouldRevalidate,preventScrollReset:p.preventScrollReset,formData:b,body:j,formMethod:p.method||y,formEncType:p.encType||g,flushSync:p.flushSync})}else await f(p.action||x,{unstable_defaultShouldRevalidate:p.unstable_defaultShouldRevalidate,preventScrollReset:p.preventScrollReset,formData:b,body:j,formMethod:p.method||y,formEncType:p.encType||g,replace:p.replace,state:p.state,fromRouteId:u,flushSync:p.flushSync,viewTransition:p.viewTransition})},[o,f,r,u])}function Ky(s,{relative:r}={}){let{basename:u}=h.useContext(Xt),o=h.useContext(ma);Fe(o,"useFormAction must be used inside a RouteContext");let[f]=o.matches.slice(-1),m={...As(s||".",{relative:r})},p=hn();if(s==null){m.search=p.search;let x=new URLSearchParams(m.search),y=x.getAll("index");if(y.some(b=>b==="")){x.delete("index"),y.filter(j=>j).forEach(j=>x.append("index",j));let b=x.toString();m.search=b?`?${b}`:""}}return(!s||s===".")&&f.route.index&&(m.search=m.search?m.search.replace(/^\?/,"?index&"):"?index"),u!=="/"&&(m.pathname=m.pathname==="/"?u:La([u,m.pathname])),ws(m)}function Zy(s,{relative:r}={}){let u=h.useContext(vm);Fe(u!=null,"`useViewTransitionState` must be used within `react-router-dom`'s `RouterProvider`. Did you accidentally import `RouterProvider` from `react-router`?");let{basename:o}=Am("useViewTransitionState"),f=As(s,{relative:r});if(!u.isTransitioning)return!1;let m=Ba(u.currentLocation.pathname,o)||u.currentLocation.pathname,p=Ba(u.nextLocation.pathname,o)||u.nextLocation.pathname;return Fi(f.pathname,p)!=null||Fi(f.pathname,m)!=null}var Jy=om();const Wy=["nebula","monolith","signal","polar","neon","terra"],Fy=[{id:"nebula",name:"Nebula",description:"Glassmorphism command center",mode:"dark",colors:["#080b16","#8b5cf6","#10b981","#f0f0f5"]},{id:"monolith",name:"Monolith",description:"Cinematic ultra-minimal",mode:"dark",colors:["#000000","#7c3aed","#ffffff","#404040"]},{id:"signal",name:"Signal",description:"Warm sci-fi terminal",mode:"dark",colors:["#0c0c0c","#f59e0b","#22c55e","#e8e4dd"]},{id:"polar",name:"Polar",description:"Premium light mode",mode:"light",colors:["#ffffff","#3b82f6","#059669","#111827"]},{id:"neon",name:"Neon",description:"Cyberpunk vivid",mode:"dark",colors:["#09090b","#06b6d4","#ec4899","#22c55e"]},{id:"terra",name:"Terra",description:"Warm organic dark",mode:"dark",colors:["#1a1612","#c97b5c","#8faa7b","#e8e0d4"]}],Om=h.createContext({theme:"nebula",setTheme:()=>{}});function Py({children:s}){const[r,u]=h.useState(()=>{const f=localStorage.getItem("auxiora-theme");return f&&Wy.includes(f)?f:"nebula"}),o=h.useCallback(f=>{u(f),localStorage.setItem("auxiora-theme",f),document.documentElement.setAttribute("data-theme",f)},[]);return h.useEffect(()=>{document.documentElement.setAttribute("data-theme",r)},[]),n.jsx(Om.Provider,{value:{theme:r,setTheme:o},children:s})}function qu(){return h.useContext(Om)}const Iy="/api/v1/dashboard";async function se(s,r){const u=await fetch(`${Iy}${s}`,{credentials:"include",headers:{"Content-Type":"application/json"},...r});if(u.status===401)throw window.location.href="/dashboard/login",new Error("Unauthorized");if(!u.ok){const o=await u.json().catch(()=>({}));throw new Error(o.error||`HTTP ${u.status}`)}return u.json()}const ex="/api/v1/marketplace";async function Sl(s,r){const u=await fetch(`${ex}${s}`,{credentials:"include",headers:{"Content-Type":"application/json"},...r});if(u.status===401)throw window.location.href="/dashboard/login",new Error("Unauthorized");if(!u.ok){const o=await u.json().catch(()=>({}));throw new Error(o.error||`HTTP ${u.status}`)}return u.json()}const J={checkAuth:()=>se("/auth/check"),login:s=>se("/auth/login",{method:"POST",body:JSON.stringify({password:s})}),logout:()=>se("/auth/logout",{method:"POST"}),getBehaviors:()=>se("/behaviors"),patchBehavior:(s,r)=>se(`/behaviors/${s}`,{method:"PATCH",body:JSON.stringify(r)}),deleteBehavior:s=>se(`/behaviors/${s}`,{method:"DELETE"}),createBehavior:s=>se("/behaviors",{method:"POST",body:JSON.stringify(s)}),getWebhooks:()=>se("/webhooks"),patchWebhook:(s,r)=>se(`/webhooks/${s}`,{method:"PATCH",body:JSON.stringify(r)}),deleteWebhook:s=>se(`/webhooks/${s}`,{method:"DELETE"}),createWebhook:s=>se("/webhooks",{method:"POST",body:JSON.stringify(s)}),getSessions:()=>se("/sessions"),getAudit:s=>{const r=new URLSearchParams;s!=null&&s.type&&r.set("type",s.type),s!=null&&s.limit&&r.set("limit",String(s.limit));const u=r.toString();return se(`/audit${u?`?${u}`:""}`)},getStatus:()=>se("/status"),getActiveAgents:()=>se("/status/agents"),getHealthState:()=>se("/status/health"),getCapabilities:()=>se("/status/capabilities"),getSetupStatus:()=>se("/setup/status"),setupVault:s=>se("/setup/vault",{method:"POST",body:JSON.stringify({password:s})}),setupDashboardPassword:s=>se("/setup/dashboard-password",{method:"POST",body:JSON.stringify({password:s})}),setupIdentity:(s,r,u)=>se("/setup/identity",{method:"POST",body:JSON.stringify({name:s,pronouns:r,vibe:u})}),getSetupTemplates:()=>se("/setup/templates"),setupPersonality:s=>se("/setup/personality",{method:"POST",body:JSON.stringify({template:s})}),setupProvider:(s,r,u)=>se("/setup/provider",{method:"POST",body:JSON.stringify({provider:s,apiKey:r,endpoint:u})}),setupProviders:s=>se("/setup/provider",{method:"POST",body:JSON.stringify({providers:s})}),setupChannels:s=>se("/setup/channels",{method:"POST",body:JSON.stringify({channels:s})}),completeSetup:()=>se("/setup/complete",{method:"POST"}),getModels:()=>se("/models"),getIdentity:()=>se("/identity"),updateIdentity:(s,r)=>se("/identity",{method:"POST",body:JSON.stringify({name:s,pronouns:r})}),getPersonality:()=>se("/personality"),getTemplates:()=>se("/personality/templates"),updatePersonality:s=>se("/personality",{method:"POST",body:JSON.stringify({template:s})}),getPersonalityFull:()=>se("/personality/full"),updatePersonalityFull:s=>se("/personality/full",{method:"PUT",body:JSON.stringify(s)}),updateProvider:(s,r,u)=>se("/provider",{method:"POST",body:JSON.stringify({provider:s,apiKey:r,endpoint:u})}),configureProvider:(s,r,u)=>se("/provider/configure",{method:"POST",body:JSON.stringify({provider:s,apiKey:r,endpoint:u})}),startClaudeOAuth:()=>se("/provider/claude-oauth/start",{method:"POST"}),completeClaudeOAuth:s=>se("/provider/claude-oauth/callback",{method:"POST",body:JSON.stringify({code:s})}),disconnectClaudeOAuth:()=>se("/provider/claude-oauth/disconnect",{method:"POST"}),getClaudeOAuthStatus:()=>se("/provider/claude-oauth/status"),updateRouting:(s,r)=>se("/provider/routing",{method:"POST",body:JSON.stringify({primary:s,fallback:r})}),setProviderModel:(s,r)=>se("/provider/model",{method:"POST",body:JSON.stringify({provider:s,model:r})}),getSessionMessages:()=>se("/session/messages"),getChannels:()=>se("/channels"),updateChannels:s=>se("/channels",{method:"POST",body:JSON.stringify({channels:s})}),changeDashboardPassword:(s,r)=>se("/security/dashboard-password",{method:"POST",body:JSON.stringify({oldPassword:s,newPassword:r})}),changeVaultPassword:s=>se("/security/vault-password",{method:"POST",body:JSON.stringify({newPassword:s})}),getSealStatus:()=>se("/security/seal/status"),enableSeal:(s,r)=>se("/security/seal",{method:"POST",body:JSON.stringify({password:s,pin:r})}),disableSeal:()=>se("/security/seal",{method:"DELETE"}),getConnectorStatus:s=>se(`/connectors/${s}/status`),saveConnectorCredentials:(s,r,u)=>se(`/connectors/${s}/credentials`,{method:"POST",body:JSON.stringify({clientId:r,clientSecret:u})}),disconnectConnector:s=>se(`/connectors/${s}/disconnect`,{method:"POST"}),getAmbientConfig:()=>se("/ambient/config"),updateAmbientConfig:s=>se("/ambient/config",{method:"POST",body:JSON.stringify(s)}),getPersonalityEngine:()=>se("/personality/engine"),setPersonalityEngine:s=>se("/personality/engine",{method:"PUT",body:JSON.stringify({engine:s})}),updateChatPersonality:(s,r)=>se(`/chats/${s}`,{method:"PATCH",body:JSON.stringify({personality:r})}),getArchitectPreferences:()=>se("/architect/preferences"),updateArchitectPreference:(s,r)=>se("/architect/preferences",{method:"PATCH",body:JSON.stringify({key:s,value:r})}),clearArchitectData:()=>se("/architect/data",{method:"DELETE"}),exportArchitectData:()=>se("/architect/data/export"),getAppearance:()=>se("/appearance"),updateAppearance:s=>se("/appearance",{method:"POST",body:JSON.stringify({theme:s})}),getChats:s=>se(`/chats${s?"?archived=true":""}`),createNewChat:s=>se("/chats",{method:"POST",body:JSON.stringify({title:s})}),getChatMessages:s=>se(`/chats/${s}/messages`),renameChat:(s,r)=>se(`/chats/${s}`,{method:"PATCH",body:JSON.stringify({title:r})}),archiveChat:s=>se(`/chats/${s}`,{method:"PATCH",body:JSON.stringify({archived:!0})}),deleteChatThread:s=>se(`/chats/${s}`,{method:"DELETE"}),getNotifications:()=>se("/notifications"),dismissNotification:s=>se(`/notifications/${s}/dismiss`,{method:"POST"}),getNotificationPreferences:()=>se("/notifications/preferences"),updateNotificationPreferences:s=>se("/notifications/preferences",{method:"POST",body:JSON.stringify(s)}),getUserModel:()=>fetch("/api/v1/user-model",{credentials:"include"}).then(async s=>{if(!s.ok){const r=await s.json().catch(()=>({}));throw new Error(r.error||`HTTP ${s.status}`)}return s.json()}),getMemories:s=>{const r=s?`?category=${encodeURIComponent(s)}`:"";return se(`/memories${r}`)},searchMemories:s=>se(`/memories/search?q=${encodeURIComponent(s)}`),deleteMemory:s=>se(`/memories/${encodeURIComponent(s)}`,{method:"DELETE"}),updateMemory:(s,r)=>se(`/memories/${encodeURIComponent(s)}`,{method:"PATCH",body:JSON.stringify(r)}),exportMemories:()=>se("/memories/export"),forgetTopic:s=>se("/forget",{method:"POST",body:JSON.stringify({topic:s})}),exportPersonalization:()=>se("/export/personalization"),searchPlugins:(s={})=>{const r=new URLSearchParams;s.q&&r.set("q",s.q),s.author&&r.set("author",s.author),s.keywords&&r.set("keywords",s.keywords),s.sort&&r.set("sort",s.sort),s.limit&&r.set("limit",String(s.limit)),s.offset&&r.set("offset",String(s.offset));const u=r.toString();return Sl(`/plugins/search${u?`?${u}`:""}`)},getPlugin:s=>Sl(`/plugins/${encodeURIComponent(s)}`),installPlugin:(s,r)=>Sl("/plugins/install",{method:"POST",body:JSON.stringify({name:s,version:r})}),searchPersonalities:(s={})=>{const r=new URLSearchParams;s.q&&r.set("q",s.q),s.author&&r.set("author",s.author),s.sort&&r.set("sort",s.sort),s.limit&&r.set("limit",String(s.limit)),s.offset&&r.set("offset",String(s.offset));const u=r.toString();return Sl(`/personalities/search${u?`?${u}`:""}`)},getMarketplacePersonality:s=>Sl(`/personalities/${encodeURIComponent(s)}`),installPersonality:(s,r)=>Sl("/personalities/install",{method:"POST",body:JSON.stringify({name:s,version:r})}),getJobStats:()=>fetch("/api/v1/jobs/status",{credentials:"include"}).then(s=>s.json()),getJobList:s=>{const r=new URLSearchParams;s!=null&&s.status&&r.set("status",s.status),s!=null&&s.type&&r.set("type",s.type),s!=null&&s.limit&&r.set("limit",String(s.limit));const u=r.toString();return fetch(`/api/v1/jobs/list${u?`?${u}`:""}`,{credentials:"include"}).then(o=>o.json())},retryJob:s=>fetch(`/api/v1/jobs/${encodeURIComponent(s)}/retry`,{method:"POST",credentials:"include"}).then(r=>r.json()),getDarwinStatus:()=>fetch("/api/v1/darwin/status",{credentials:"include"}).then(s=>s.json()),getDarwinArchive:()=>fetch("/api/v1/darwin/archive",{credentials:"include"}).then(s=>s.json()),getDarwinVariant:s=>fetch(`/api/v1/darwin/variants/${encodeURIComponent(s)}`,{credentials:"include"}).then(r=>r.json()),getDarwinGovernor:()=>fetch("/api/v1/darwin/governor",{credentials:"include"}).then(s=>s.json()),getDarwinApprovals:()=>fetch("/api/v1/darwin/approvals",{credentials:"include"}).then(s=>s.json()),approveDarwinVariant:s=>fetch(`/api/v1/darwin/approvals/${encodeURIComponent(s)}/approve`,{method:"POST",credentials:"include"}).then(r=>r.json()),rejectDarwinVariant:s=>fetch(`/api/v1/darwin/approvals/${encodeURIComponent(s)}/reject`,{method:"POST",credentials:"include"}).then(r=>r.json()),pauseDarwin:()=>fetch("/api/v1/darwin/pause",{method:"POST",credentials:"include"}).then(s=>s.json()),resumeDarwin:()=>fetch("/api/v1/darwin/resume",{method:"POST",credentials:"include"}).then(s=>s.json())};async function tx(){const s=await fetch("/api/v1/features/status",{credentials:"include"});if(!s.ok)throw new Error(`HTTP ${s.status}`);return s.json()}function ut(s,r=[]){const[u,o]=h.useState(null),[f,m]=h.useState(!0),[p,x]=h.useState(null),y=h.useCallback(()=>{m(!0),s().then(g=>{o(g),x(null)}).catch(g=>x(g.message)).finally(()=>m(!1))},r);return h.useEffect(()=>{y()},[y]),{data:u,loading:f,error:p,refresh:y}}function Os(s,r=1e4){h.useEffect(()=>{const u=setInterval(s,r);return()=>clearInterval(u)},[s,r])}const Mm="auxiora-windows",Rm="auxiora-snap-grid",Nu=360,Cu=240,ax=600,nx=500,Jh=30,lx=36,Wh=100,Cs=40;function Qi(s,r){return Math.round(s/r)*r}function Ru(s,r,u,o){const f=typeof window<"u"?window.innerWidth:1920,m=typeof window<"u"?window.innerHeight:1080;return{x:Math.max(Wh-u,Math.min(s,f-Wh)),y:Math.max(0,Math.min(r,m-lx))}}function sx(){try{const s=localStorage.getItem(Mm);if(!s)return new Map;const r=JSON.parse(s),u=new Map(Object.entries(r));for(const[o,f]of u){const m=Ru(f.x,f.y,f.width,f.height);(m.x!==f.x||m.y!==f.y)&&u.set(o,{...f,x:m.x,y:m.y})}return u}catch{return new Map}}function ix(s){const r=Object.fromEntries(s);localStorage.setItem(Mm,JSON.stringify(r))}function Eu(s){let r=0;for(const u of s.values())u.zIndex>r&&(r=u.zIndex);return r+1}function cx(){try{return localStorage.getItem(Rm)==="1"}catch{return!1}}function rx(){const[s,r]=h.useState(sx),[u,o]=h.useState(cx),f=h.useCallback(A=>{r(D=>{const O=A(D);return ix(O),O})},[]),m=h.useCallback((A,D,O,E)=>{f(M=>{if(M.has(A)){const G=new Map(M),te=G.get(A);return G.set(A,{...te,zIndex:Eu(G),minimized:!1}),G}const k=new Map(M),Z=k.size,K=Math.max(Nu,O??ax),q=Math.max(Cu,E??nx),W=Ru(80+Z%8*Jh,60+Z%8*Jh,K);return k.set(A,{id:A,title:D,x:W.x,y:W.y,width:K,height:q,zIndex:Eu(k),minimized:!1,maximized:!1}),k})},[f]),p=h.useCallback(A=>{f(D=>{const O=new Map(D);return O.delete(A),O})},[f]),x=h.useCallback(A=>{f(D=>{const O=D.get(A);if(!O)return D;const E=new Map(D);return E.set(A,{...O,zIndex:Eu(E)}),E})},[f]),y=h.useCallback(()=>{o(A=>{const D=!A;try{localStorage.setItem(Rm,D?"1":"0")}catch{}return D})},[]),g=h.useCallback((A,D,O)=>{f(E=>{const M=E.get(A);if(!M)return E;const k=u?Qi(D,Cs):D,Z=u?Qi(O,Cs):O,K=Ru(k,Z,M.width,M.height),q=new Map(E);return q.set(A,{...M,x:K.x,y:K.y}),q})},[f,u]),b=h.useCallback((A,D,O)=>{f(E=>{const M=E.get(A);if(!M)return E;const k=u?Qi(Math.max(Nu,D),Cs):Math.max(Nu,D),Z=u?Qi(Math.max(Cu,O),Cs):Math.max(Cu,O),K=new Map(E);return K.set(A,{...M,width:k,height:Z}),K})},[f,u]),j=h.useCallback(A=>{f(D=>{const O=D.get(A);if(!O)return D;const E=new Map(D);return E.set(A,{...O,minimized:!O.minimized}),E})},[f]),S=h.useCallback(A=>{f(D=>{const O=D.get(A);if(!O)return D;const E=new Map(D);return E.set(A,{...O,maximized:!O.maximized}),E})},[f]),w=h.useMemo(()=>{let A=-1,D=null;for(const O of s.values())!O.minimized&&O.zIndex>A&&(A=O.zIndex,D=O.id);return D},[s]);return{windows:s,activeWindowId:w,snapEnabled:u,gridSize:Cs,openWindow:m,closeWindow:p,focusWindow:x,moveWindow:g,resizeWindow:b,toggleMinimize:j,toggleMaximize:S,toggleSnap:y}}const ux=["n","s","e","w","ne","nw","se","sw"];function ox({id:s,title:r,x:u,y:o,width:f,height:m,zIndex:p,minimized:x,maximized:y,focused:g,onClose:b,onFocus:j,onMinimize:S,onMaximize:w,onMove:A,onResize:D,children:O}){const E=h.useRef(null),M=h.useCallback(q=>{if(y)return;q.preventDefault(),j();const W=q.clientX,G=q.clientY;E.current={startX:W,startY:G,origX:u,origY:o};const te=ie=>{if(!E.current)return;const he=ie.clientX-E.current.startX,ee=ie.clientY-E.current.startY;A(E.current.origX+he,E.current.origY+ee)},ce=()=>{E.current=null,document.removeEventListener("mousemove",te),document.removeEventListener("mouseup",ce)};document.addEventListener("mousemove",te),document.addEventListener("mouseup",ce)},[y,u,o,j,A]),k=h.useCallback((q,W)=>{if(y)return;W.preventDefault(),W.stopPropagation(),j();const G=W.clientX,te=W.clientY,ce=u,ie=o,he=f,ee=m,oe=H=>{const F=H.clientX-G,le=H.clientY-te;let I=ce,de=ie,C=he,L=ee;q.includes("e")&&(C=he+F),q.includes("w")&&(C=he-F,I=ce+F),q.includes("s")&&(L=ee+le),q.includes("n")&&(L=ee-le,de=ie+le),D(C,L),(q.includes("w")||q.includes("n"))&&A(I,de)},ve=()=>{document.removeEventListener("mousemove",oe),document.removeEventListener("mouseup",ve)};document.addEventListener("mousemove",oe),document.addEventListener("mouseup",ve)},[y,u,o,f,m,j,D,A]);if(x)return null;const Z=y?{zIndex:p,inset:"0",width:"100%",height:"100%"}:{left:`${u}px`,top:`${o}px`,width:`${f}px`,height:`${m}px`,zIndex:p},K=["window","glass-mid"];return g&&K.push("focused"),y&&K.push("maximized"),n.jsxs("div",{className:K.join(" "),style:Z,onMouseDown:j,"data-window-id":s,children:[!y&&ux.map(q=>n.jsx("div",{className:`window-resize window-resize-${q}`,onMouseDown:W=>k(q,W)},q)),n.jsxs("div",{className:"window-titlebar",onMouseDown:M,children:[n.jsxs("div",{className:"window-traffic-lights",children:[n.jsx("button",{type:"button",className:"window-traffic-light close","aria-label":"Close window",onClick:q=>{q.stopPropagation(),b()}}),n.jsx("button",{type:"button",className:"window-traffic-light minimize","aria-label":"Minimize window",onClick:q=>{q.stopPropagation(),S()}}),n.jsx("button",{type:"button",className:"window-traffic-light maximize","aria-label":"Maximize window",onClick:q=>{q.stopPropagation(),w()}})]}),n.jsx("span",{className:"window-title",children:r})]}),n.jsx("div",{className:"window-body",children:O})]})}function dx({items:s,openWindows:r,onOpen:u}){const o=h.useRef(null),f=h.useCallback(p=>{const x=o.current;if(!x)return;const y=x.querySelectorAll(".dock-icon-wrapper"),g=p.clientX;y.forEach(b=>{const j=b.getBoundingClientRect(),S=j.left+j.width/2,w=Math.abs(g-S);b.classList.remove("mag-center","mag-near","mag-far"),w<25?b.classList.add("mag-center"):w<60?b.classList.add("mag-near"):w<100&&b.classList.add("mag-far")})},[]),m=h.useCallback(()=>{const p=o.current;p&&p.querySelectorAll(".dock-icon-wrapper").forEach(x=>{x.classList.remove("mag-center","mag-near","mag-far")})},[]);return n.jsx("div",{className:"dock-container",ref:o,onMouseMove:f,onMouseLeave:m,children:s.map(p=>n.jsxs("div",{className:"dock-icon-wrapper",children:[n.jsx("div",{className:"dock-tooltip",children:p.label}),n.jsx("button",{type:"button",className:"dock-icon","aria-label":`Open ${p.label}`,onClick:()=>u(p.id),children:p.icon}),n.jsx("div",{className:`dock-icon-dot${r.has(p.id)?" active":""}`})]},p.id))})}function fx(){const[s,r]=h.useState([]),u=h.useRef(new Set),o=h.useCallback(async()=>{try{const m=await fetch("/api/v1/tool-approvals/pending");if(!m.ok)return;const p=await m.json();r(p.filter(x=>!u.current.has(x.id)))}catch{}},[]);h.useEffect(()=>{o();const m=setInterval(o,3e3);return()=>clearInterval(m)},[o]);const f=h.useCallback(async(m,p)=>{u.current.add(m),r(x=>x.filter(y=>y.id!==m));try{await fetch(`/api/v1/tool-approvals/${m}/resolve`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({approved:p})})}catch{}},[]);return s.length===0?null:n.jsx("div",{className:"ab-banner",children:s.map(m=>n.jsxs("div",{className:"ab-item",children:[n.jsx("span",{className:"ab-tool",children:m.toolName}),n.jsx("span",{className:"ab-args",children:JSON.stringify(m.args)}),n.jsx("button",{className:"ab-approve",onClick:()=>f(m.id,!0),children:"Approve"}),n.jsx("button",{className:"ab-deny",onClick:()=>f(m.id,!1),children:"Deny"})]},m.id))})}const hx={"behavior.executed":s=>s.success?"Behavior ran successfully":`Behavior failed: ${s.error??"unknown"}`,"behavior.created":()=>"Behavior created","behavior.updated":()=>"Behavior updated","behavior.deleted":()=>"Behavior deleted","behavior.paused":()=>"Behavior paused","behavior.failed":s=>`Behavior failed: ${s.error??"unknown"}`,"message.received":s=>`Message received on ${s.channelType??"unknown"}`,"message.sent":s=>`Message sent to ${s.channelType??"unknown"}`,"message.filtered":()=>"Message filtered","channel.connected":s=>`${s.channelType??"Channel"} connected`,"channel.disconnected":s=>`${s.channelType??"Channel"} disconnected`,"channel.error":s=>`${s.channelType??"Channel"} error`,"webhook.triggered":s=>`Webhook triggered: ${s.path??""}`,"webhook.received":()=>"Webhook received","webhook.created":()=>"Webhook created","webhook.deleted":()=>"Webhook deleted","webhook.error":s=>`Webhook error: ${s.error??"unknown"}`,"system.startup":()=>"System started","system.shutdown":()=>"System shut down","system.error":s=>`System error: ${s.error??"unknown"}`,"auth.login":()=>"Login","auth.logout":()=>"Logout"},mx={behavior:"var(--accent)",message:"#3b82f6",channel:"var(--success)",webhook:"#f97316",system:"var(--text-secondary)",auth:"var(--danger)"};function px(s){return s.split(".")[0]}function gx(s,r){const u=hx[s];return u?u(r):s.replace(/\./g," ").replace(/\b\w/g,o=>o.toUpperCase())}function vx(s){const r=(Date.now()-new Date(s).getTime())/1e3;return r<60?"just now":r<3600?`${Math.floor(r/60)}m ago`:r<86400?`${Math.floor(r/3600)}h ago`:`${Math.floor(r/86400)}d ago`}const Fh=100;function yx(){const[s,r]=h.useState([]),u=h.useRef(null);return h.useEffect(()=>{J.getAudit({limit:50}).then(o=>{if(o.data){const f=["behavior.","message.","channel.","webhook.","system.","auth.login","auth.logout"],m=o.data.filter(p=>f.some(x=>p.event.startsWith(x))).reverse();r(m)}}).catch(()=>{})},[]),h.useEffect(()=>{const o=window.location.protocol==="https:"?"wss:":"ws:",f=window.location.host,m=new WebSocket(`${o}//${f}/`);return u.current=m,m.onmessage=p=>{try{const x=JSON.parse(p.data);x.type==="activity"&&x.payload&&r(y=>{const g=[x.payload,...y];return g.length>Fh?g.slice(0,Fh):g})}catch{}},()=>{m.close()}},[]),n.jsxs("div",{className:"activity-feed",children:[n.jsx("h3",{className:"mc-section-title",children:"Live Activity"}),n.jsxs("div",{className:"activity-feed-list",children:[s.length===0&&n.jsx("div",{className:"activity-empty",children:"No recent activity"}),s.map((o,f)=>{const m=px(o.event),p=mx[m]??"var(--text-secondary)";return n.jsxs("div",{className:"activity-item",children:[n.jsx("span",{className:"activity-dot",style:{background:p}}),n.jsx("span",{className:"activity-label",children:gx(o.event,o.details)}),n.jsx("span",{className:"activity-time",children:vx(o.timestamp)})]},`${o.sequence}-${f}`)})]})]})}const xx={discord:"Discord",telegram:"Telegram",slack:"Slack",webchat:"Web"};function bx(s){const r=Date.now()-new Date(s).getTime(),u=Math.floor(r/1e3);return u<60?`${u}s`:`${Math.floor(u/60)}m ${u%60}s`}function jx(){const[s,r]=h.useState([]),u=h.useRef(null),o=h.useRef(null),[,f]=h.useState(0);return h.useEffect(()=>{J.getActiveAgents().then(m=>{m.data&&r(m.data)}).catch(()=>{})},[]),h.useEffect(()=>{const m=window.location.protocol==="https:"?"wss:":"ws:",p=window.location.host,x=new WebSocket(`${m}//${p}/`);return u.current=x,x.onmessage=y=>{try{const g=JSON.parse(y.data);g.type==="agent_start"&&g.payload?r(b=>[...b,g.payload]):g.type==="agent_end"&&g.payload&&r(b=>b.filter(j=>j.id!==g.payload.id))}catch{}},()=>{x.close()}},[]),h.useEffect(()=>(o.current=setInterval(()=>f(m=>m+1),1e3),()=>{o.current&&clearInterval(o.current)}),[]),n.jsxs("div",{className:"agent-activity",children:[n.jsx("h3",{className:"mc-section-title",children:"Active Now"}),s.length===0?n.jsx("div",{className:"agent-activity-quiet",children:"All quiet"}):n.jsx("div",{className:"agent-activity-list",children:s.map(m=>n.jsxs("div",{className:"agent-activity-card",children:[n.jsx("span",{className:"agent-pulse"}),n.jsxs("div",{className:"agent-activity-info",children:[n.jsx("span",{className:"agent-activity-desc",children:m.description}),n.jsxs("span",{className:"agent-activity-meta",children:[m.channelType&&n.jsx("span",{className:"agent-channel-badge",children:xx[m.channelType]??m.channelType}),n.jsx("span",{className:"agent-activity-type",children:m.type}),n.jsx("span",{className:"agent-activity-elapsed",children:bx(m.startedAt)})]})]})]},m.id))})]})}function Sx(s){const r=(Date.now()-new Date(s).getTime())/1e3;return r<60?"just now":r<3600?`${Math.floor(r/60)}m ago`:r<86400?`${Math.floor(r/3600)}h ago`:`${Math.floor(r/86400)}d ago`}function Ph(s){return s.status==="paused"&&s.failCount>=s.maxFailures?"var(--danger)":s.status==="paused"?"var(--text-secondary)":s.failCount>0?"var(--warning)":"var(--success)"}function Nx(s){return s.status==="paused"&&s.failCount>=s.maxFailures?"Auto-paused":s.status==="paused"?"Paused":s.failCount>0?`${s.failCount} failures`:"Healthy"}const Cx={scheduled:"Sched",monitor:"Monitor","one-shot":"Once"};function Ex(){const[s,r]=h.useState([]),u=h.useRef(null);return h.useEffect(()=>{J.getBehaviors().then(o=>{o.data&&r(o.data.filter(f=>f.status!=="deleted"))}).catch(()=>{})},[]),h.useEffect(()=>{const o=window.location.protocol==="https:"?"wss:":"ws:",f=window.location.host,m=new WebSocket(`${o}//${f}/`);return u.current=m,m.onmessage=p=>{var x,y;try{const g=JSON.parse(p.data);g.type==="activity"&&((y=(x=g.payload)==null?void 0:x.event)!=null&&y.startsWith("behavior."))&&J.getBehaviors().then(b=>{b.data&&r(b.data.filter(j=>j.status!=="deleted"))}).catch(()=>{})}catch{}},()=>{m.close()}},[]),n.jsxs("div",{className:"behavior-health",children:[n.jsx("h3",{className:"mc-section-title",children:"Behavior Health"}),s.length===0&&n.jsx("div",{className:"bh-empty",children:"No behaviors configured"}),n.jsx("div",{className:"bh-list",children:s.map(o=>n.jsxs("div",{className:"bh-card",children:[n.jsxs("div",{className:"bh-card-header",children:[n.jsx("span",{className:"bh-dot",style:{background:Ph(o)}}),n.jsx("span",{className:"bh-action",children:o.action.length>60?o.action.slice(0,57)+"...":o.action}),n.jsx("span",{className:"bh-type-badge",children:Cx[o.type]??o.type})]}),n.jsxs("div",{className:"bh-card-meta",children:[n.jsx("span",{className:"bh-health-label",style:{color:Ph(o)},children:Nx(o)}),n.jsxs("span",{className:"bh-stat",children:[o.runCount," runs"]}),o.lastRun&&n.jsx("span",{className:"bh-stat",children:Sx(o.lastRun)})]}),o.lastResult&&n.jsx("div",{className:"bh-result",children:o.lastResult.length>120?o.lastResult.slice(0,117)+"...":o.lastResult})]},o.id))})]})}function Dm(){var y,g,b,j,S,w,A,D,O;const{data:s,refresh:r}=ut(()=>J.getStatus(),[]),{data:u,refresh:o}=ut(()=>J.getModels(),[]),{data:f,refresh:m}=ut(()=>J.getHealthState(),[]);Os(()=>{r(),o(),m()});const p=s==null?void 0:s.data,x=((g=(y=u==null?void 0:u.providers)==null?void 0:y.find(E=>E.available))==null?void 0:g.displayName)??"None";return n.jsxs("div",{className:"page",children:[n.jsx("h2",{children:"Mission Control"}),n.jsxs("div",{className:"status-grid",children:[n.jsxs("div",{className:"status-card",children:[n.jsx("h3",{children:"Connections"}),n.jsx("div",{className:"value",children:(p==null?void 0:p.connections)??0}),n.jsx("div",{className:"sub",children:"Active sessions"})]}),n.jsxs("div",{className:"status-card",children:[n.jsx("h3",{children:"Provider"}),n.jsx("div",{className:"value",children:x}),n.jsx("div",{className:"sub",children:((b=p==null?void 0:p.activeModel)==null?void 0:b.model)??"unknown"})]}),n.jsxs("div",{className:"status-card",children:[n.jsx("h3",{children:"Uptime"}),n.jsx("div",{className:"value",children:p?wx(p.uptime):"-"}),n.jsx("div",{className:"sub",children:"Since last restart"})]}),n.jsxs("div",{className:"status-card",children:[n.jsx("h3",{children:"Health"}),n.jsxs("div",{className:"value",children:[n.jsx("span",{className:`health-dot health-${((j=f==null?void 0:f.data)==null?void 0:j.overall)??"unknown"}`}),Tx(((S=f==null?void 0:f.data)==null?void 0:S.overall)??"unknown")]}),n.jsxs("div",{className:"sub",children:[((A=(w=f==null?void 0:f.data)==null?void 0:w.issues)==null?void 0:A.length)??0," issues"]})]})]}),((O=(D=f==null?void 0:f.data)==null?void 0:D.issues)==null?void 0:O.length)>0&&n.jsx("div",{className:"health-alerts",children:f.data.issues.map(E=>n.jsxs("div",{className:`health-alert health-alert-${E.severity}`,children:[n.jsx("span",{className:"health-alert-text",children:E.description}),E.suggestedFix&&n.jsx("span",{className:"health-alert-fix",children:E.suggestedFix})]},E.id))}),n.jsxs("div",{className:"mc-columns",children:[n.jsxs("div",{className:"mc-left",children:[n.jsx(jx,{}),n.jsx(Ex,{})]}),n.jsx("div",{className:"mc-right",children:n.jsx(yx,{})})]})]})}function wx(s){const r=Math.floor(s/3600),u=Math.floor(s%3600/60);return r>0?`${r}h ${u}m`:`${u}m`}function Tx(s){return s.charAt(0).toUpperCase()+s.slice(1)}const _t={security_review:{icon:"🛡️",label:"Security Review",description:"Adversarial analysis, threat modeling, vulnerability assessment",colorClass:"context-red"},crisis_management:{icon:"🚨",label:"Crisis",description:"Incidents, breaches, outages, urgent response",colorClass:"context-red"},code_engineering:{icon:"💻",label:"Engineering",description:"Writing, reviewing, and optimizing code",colorClass:"context-blue"},architecture_design:{icon:"🏗️",label:"Architecture",description:"System design, patterns, trade-off analysis",colorClass:"context-blue"},debugging:{icon:"🐛",label:"Debugging",description:"Finding and fixing bugs, tracing errors",colorClass:"context-blue"},team_leadership:{icon:"👥",label:"Team Leadership",description:"Managing teams, culture, performance, hiring",colorClass:"context-green"},one_on_one:{icon:"🤝",label:"One-on-One",description:"Coaching, feedback, career development conversations",colorClass:"context-green"},sales_pitch:{icon:"📈",label:"Sales",description:"Pitching, proposals, value positioning, closing",colorClass:"context-purple"},negotiation:{icon:"⚖️",label:"Negotiation",description:"Contract terms, compensation, vendor discussions",colorClass:"context-purple"},marketing_content:{icon:"📣",label:"Marketing",description:"Positioning, messaging, audience building, campaigns",colorClass:"context-purple"},strategic_planning:{icon:"🎯",label:"Strategy",description:"Roadmaps, priorities, resource allocation, OKRs",colorClass:"context-orange"},decision_making:{icon:"⚖️",label:"Decision",description:"Weighing options, trade-offs, choosing between paths",colorClass:"context-orange"},creative_work:{icon:"💡",label:"Creative",description:"Brainstorming, ideation, creative problem solving",colorClass:"context-teal"},writing_content:{icon:"✍️",label:"Writing",description:"Blog posts, articles, documentation, drafting",colorClass:"context-teal"},learning_research:{icon:"📚",label:"Learning",description:"Understanding concepts, deep dives, research",colorClass:"context-gray"},personal_development:{icon:"🌱",label:"Growth",description:"Career planning, skills, growth, interviews",colorClass:"context-gray"},general:{icon:"💬",label:"General",description:"General conversation and assistance",colorClass:"context-gray"}},Nl=Object.keys(_t),zm={stressed:"· Under Pressure",frustrated:"· Working Through It",uncertain:"· Exploring",excited:"· Energized",celebratory:"· Celebrating"};function Ax({context:s,onOverride:r,showOverrideMenu:u,onToggleOverrideMenu:o}){const f=_t[s.domain],m=zm[s.emotionalRegister];return n.jsxs("div",{className:"context-indicator-wrapper",children:[n.jsxs("button",{type:"button",className:`context-indicator ${f.colorClass}`,onClick:o,"aria-label":`Context: ${f.label}`,"aria-expanded":u,"aria-haspopup":"menu",children:[n.jsx("span",{className:"context-indicator-icon","aria-hidden":"true",children:f.icon}),n.jsx("span",{className:"context-indicator-label",children:f.label}),m&&n.jsx("span",{className:"context-indicator-emotion",children:m})]}),u&&n.jsx("ul",{className:"context-override-menu",role:"menu",children:Nl.map(p=>{const x=_t[p];return n.jsx("li",{role:"none",children:n.jsxs("button",{type:"button",role:"menuitem",className:`context-override-item ${p===s.domain?"active":""}`,onClick:()=>r(p),children:[n.jsx("span",{"aria-hidden":"true",children:x.icon})," ",x.label]})},p)})})]})}function Ox(s){return s.replace(/([A-Z])/g," $1").replace(/^./,r=>r.toUpperCase()).trim()}const Mx=10,Rx=29;function Dx({sources:s,context:r,isOpen:u,onClose:o,weights:f}){const[m,p]=h.useState(new Set),[x,y]=h.useState(!1);if(!u)return null;const g=_t[r.domain],b=zm[r.emotionalRegister],j=x?s:s.slice(0,Mx);function S(A){p(D=>{const O=new Set(D);return O.has(A)?O.delete(A):O.add(A),O})}function w(A){return f==null?void 0:f[A]}return n.jsxs("div",{className:"sources-panel",role:"dialog","aria-label":"What shaped this response",children:[n.jsxs("div",{className:"sources-panel-header",children:[n.jsxs("span",{className:"sources-panel-title",children:["🧠"," What shaped this response"]}),n.jsx("button",{type:"button",className:"sources-panel-close",onClick:o,"aria-label":"Close sources panel",children:"✕"})]}),n.jsxs("div",{className:"sources-panel-context",children:[n.jsx("span",{"aria-hidden":"true",children:g.icon})," ",g.label,b&&n.jsx("span",{className:"sources-panel-emotion",children:b})]}),n.jsx("ul",{className:"sources-trait-list",children:j.map(A=>{const D=m.has(A.traitKey),O=w(A.traitKey);return n.jsxs("li",{className:"sources-trait-item",children:[n.jsxs("button",{type:"button",className:"sources-trait-header",onClick:()=>S(A.traitKey),"aria-expanded":D,children:[n.jsx("span",{className:"sources-trait-arrow",children:D?"▾":"▸"}),n.jsx("span",{className:"sources-trait-name",children:Ox(A.traitKey)}),O!=null&&n.jsxs("span",{className:"sources-trait-weight",children:[n.jsx("span",{className:"sources-trait-weight-bar",style:{width:`${Math.round(O*100)}%`},"aria-label":`Weight: ${Math.round(O*100)}%`}),n.jsxs("span",{className:"sources-trait-weight-value",children:[Math.round(O*100),"%"]})]})]}),n.jsx("div",{className:"sources-trait-source",children:n.jsx("strong",{children:A.sourceName})}),D&&n.jsxs("div",{className:"sources-trait-details",children:[n.jsx("div",{className:"sources-trait-work",children:A.sourceWork}),n.jsx("blockquote",{className:"sources-trait-instruction",children:A.behavioralInstruction}),n.jsxs("div",{className:"sources-trait-evidence",children:["Evidence: ",A.evidenceSummary]})]})]},A.traitKey)})}),n.jsxs("div",{className:"sources-panel-footer",children:[n.jsxs("span",{className:"sources-panel-count",children:["Showing top ",j.length," of ",Rx," active traits"]}),n.jsx("button",{type:"button",className:"sources-panel-toggle",onClick:()=>y(A=>!A),children:x?"Show fewer":"Show all"})]})]})}function zx({sources:s,context:r,weights:u}){const[o,f]=h.useState(!1),m=h.useRef(null);return h.useEffect(()=>{if(!o)return;const p=x=>{m.current&&!m.current.contains(x.target)&&f(!1)};return document.addEventListener("mousedown",p),()=>document.removeEventListener("mousedown",p)},[o]),s.length===0?null:n.jsxs("div",{className:"sources-button-container",ref:m,children:[n.jsxs("button",{type:"button",className:"sources-button",onClick:()=>f(p=>!p),"aria-label":"View sources",children:[n.jsx("span",{"aria-hidden":"true",children:"🧠"})," ",n.jsx("span",{className:"sources-button-label",children:"Sources"})]}),n.jsx(Dx,{sources:s,context:r,isOpen:o,onClose:()=>f(!1),weights:u})]})}function kx({currentDomain:s,onSelect:r,onClose:u,isOpen:o}){const[f,m]=h.useState(null),[p,x]=h.useState(-1),y=h.useRef(null),g=h.useRef([]);h.useEffect(()=>{o&&(m(null),x(-1))},[o]),h.useEffect(()=>{if(!o)return;function A(D){y.current&&!y.current.contains(D.target)&&u()}return document.addEventListener("mousedown",A),()=>document.removeEventListener("mousedown",A)},[o,u]);const b=h.useCallback(A=>{var D,O;if(f){A.key==="Escape"&&(m(null),A.preventDefault());return}switch(A.key){case"Escape":u(),A.preventDefault();break;case"ArrowDown":{const E=p<Nl.length-1?p+1:0;x(E),(D=g.current[E])==null||D.focus(),A.preventDefault();break}case"ArrowUp":{const E=p>0?p-1:Nl.length-1;x(E),(O=g.current[E])==null||O.focus(),A.preventDefault();break}case"Enter":p>=0&&(j(Nl[p]),A.preventDefault());break}},[p,u,f]);function j(A){m(A)}function S(A){f&&(r(f,A),m(null))}if(!o)return null;const w=_t[s];return n.jsxs("div",{ref:y,className:"context-override-popover",role:"dialog","aria-label":"Override context",onKeyDown:b,children:[n.jsx("div",{className:"context-override-header",children:n.jsxs("span",{className:"context-override-detected",children:["Detected: ",n.jsx("span",{"aria-hidden":"true",children:w.icon})," ",w.label]})}),f?n.jsxs("div",{className:"context-override-scope",role:"group","aria-label":"Apply scope",children:[n.jsxs("div",{className:"context-override-scope-label",children:["Apply ",n.jsx("strong",{children:_t[f].label})," to:"]}),n.jsxs("button",{type:"button",className:"context-override-scope-btn",onClick:()=>S("message"),children:["This message",n.jsx("span",{className:"context-override-scope-hint",children:"Auto-detection resumes after"})]}),n.jsxs("button",{type:"button",className:"context-override-scope-btn",onClick:()=>S("conversation"),children:["This conversation",n.jsx("span",{className:"context-override-scope-hint",children:"Stays until you change it"})]}),n.jsx("button",{type:"button",className:"context-override-scope-back",onClick:()=>m(null),children:"Back"})]}):n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"context-override-subheader",children:"Switch context:"}),n.jsx("ul",{className:"context-override-list",role:"listbox","aria-label":"Available contexts",children:Nl.map((A,D)=>{const O=_t[A],E=A===s;return n.jsx("li",{role:"none",children:n.jsxs("button",{ref:M=>{g.current[D]=M},type:"button",role:"option","aria-selected":E,className:`context-override-domain-item ${E?"detected":""}`,onClick:()=>j(A),tabIndex:p===D?0:-1,children:[n.jsx("span",{className:"context-override-domain-icon","aria-hidden":"true",children:O.icon}),n.jsxs("span",{className:"context-override-domain-text",children:[n.jsxs("span",{className:"context-override-domain-label",children:[O.label,E&&n.jsx("span",{className:"context-override-detected-badge",children:"detected"})]}),n.jsx("span",{className:"context-override-domain-desc",children:O.description})]})]})},A)})})]})]})}function _x({recommendation:s,onAccept:r,onDismiss:u,autoDismissMs:o=1e4}){const[f,m]=h.useState(!0),p=h.useRef(null),x=h.useRef(!1);if(h.useEffect(()=>{if(!(o<=0))return p.current=setTimeout(()=>{x.current||(m(!1),u())},o),()=>{p.current&&clearTimeout(p.current)}},[o,u]),!f)return null;const y=_t[s.suggestedDomain],g=()=>{x.current=!0,p.current&&clearTimeout(p.current),m(!1),r(s.suggestedDomain)},b=()=>{x.current=!0,p.current&&clearTimeout(p.current),m(!1),u()};return n.jsxs("div",{className:"context-recommendation",role:"status","aria-live":"polite",children:[n.jsx("span",{className:"context-recommendation-icon","aria-hidden":"true",children:y.icon}),n.jsxs("span",{className:"context-recommendation-text",children:[n.jsx("strong",{children:"Suggestion:"})," Switch to ",y.label,"?"," ",n.jsx("span",{className:"context-recommendation-reason",children:s.reason})]}),n.jsx("button",{type:"button",className:"context-recommendation-accept",onClick:g,children:"Switch"}),n.jsx("button",{type:"button",className:"context-recommendation-dismiss",onClick:b,"aria-label":"Dismiss suggestion",children:"✕"})]})}const Ux={tool_result:"🔧",memory_recall:"🧠",knowledge_graph:"🌐",user_data:"👤",model_generation:"🤖"};function Lx({meta:s}){const[r,u]=h.useState(!1);if(!s)return null;const o=s.model.tokens.input+s.model.tokens.output,f=s.confidence.level==="high"?"🟢":s.confidence.level==="medium"?"🟡":"🔴",m=s.personality.knowledgeBoundary;return n.jsxs("div",{className:`transparency-footer confidence-${s.confidence.level}`,children:[n.jsxs("button",{className:"transparency-toggle",onClick:()=>u(!r),"aria-expanded":r,children:[n.jsxs("span",{className:"transparency-summary",children:[f," ",n.jsx("span",{children:s.confidence.level.charAt(0).toUpperCase()+s.confidence.level.slice(1)})," ","(",s.confidence.score,")",m&&n.jsxs("span",{className:"kb-warning",children:[" ","⚠"," Topic previously corrected (",m.corrections,"x)"]})," · ",s.model.model," · ",o," tokens"," · ","$",s.model.cost.total.toFixed(3),s.personality.domain!=="general"&&n.jsxs(n.Fragment,{children:[" · ",s.personality.domain.replace(/_/g," ")]})]}),n.jsx("span",{className:"tf-expand-icon",children:r?"▲":"▼"})]}),r&&n.jsxs("div",{className:"transparency-details",children:[n.jsxs("div",{className:"tf-section",children:[n.jsx("strong",{className:"tf-section-title",children:"Confidence"}),n.jsxs("div",{children:["Score: ",s.confidence.score," (",s.confidence.level.charAt(0).toUpperCase()+s.confidence.level.slice(1),")"]}),s.confidence.factors.map((p,x)=>n.jsxs("div",{className:p.impact==="positive"?"tf-factor-positive":"tf-factor-negative",children:[p.impact==="positive"?" + ":" - ",p.signal,": ",p.detail]},x))]}),n.jsxs("div",{className:"tf-section",children:[n.jsx("strong",{className:"tf-section-title",children:"Sources"}),s.sources.map((p,x)=>n.jsxs("div",{className:"tf-source-line",children:[Ux[p.type]??"❓"," ",p.label," (",p.confidence.toFixed(2),")"]},x))]}),n.jsxs("div",{className:"tf-section tf-section-last",children:[n.jsx("strong",{className:"tf-section-title",children:"Processing"}),n.jsxs("div",{children:["Model: ",s.model.provider," / ",s.model.model]}),n.jsxs("div",{children:["Tokens: ",s.model.tokens.input," in / ",s.model.tokens.output," out"]}),n.jsxs("div",{children:["Cost: $",s.model.cost.input.toFixed(4)," in / $",s.model.cost.output.toFixed(4)," out = $",s.model.cost.total.toFixed(4)," total"]}),n.jsxs("div",{children:["Latency: ",s.model.latencyMs.toLocaleString(),"ms"]}),n.jsxs("div",{children:["Finish: ",s.model.finishReason]}),s.trace.enrichmentStages.length>0&&n.jsxs("div",{children:["Stages: ",s.trace.enrichmentStages.join(" → ")]}),s.trace.toolsUsed.length>0&&n.jsxs("div",{children:["Tools: ",s.trace.toolsUsed.join(", ")]}),n.jsxs("div",{children:["Domain: ",s.personality.domain]}),n.jsxs("div",{children:["Register: ",s.personality.emotionalRegister]}),s.personality.activeTraits.length>0&&n.jsxs("div",{children:["Traits: ",s.personality.activeTraits.map(p=>`${p.name} (${p.weight.toFixed(2)})`).join(", ")]})]})]})]})}const Bx={tool_result:"🔧",memory_recall:"🧠",knowledge_graph:"🌐",user_data:"👤",model_generation:"🤖"};function Hx(s){return s==="high"?"pp-confidence-badge pp-badge-green":s==="medium"?"pp-confidence-badge pp-badge-amber":"pp-confidence-badge pp-badge-red"}function qx({meta:s,onClose:r}){const u=s.personality.knowledgeBoundary;return n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"pp-overlay",onClick:r}),n.jsxs("div",{className:"pp-panel",children:[n.jsxs("div",{className:"pp-header",children:[n.jsx("span",{className:"pp-header-title",children:"Why did I say that?"}),n.jsx("button",{className:"pp-close-btn",onClick:r,"aria-label":"close",children:"X"})]}),n.jsxs("div",{className:"pp-body",children:[n.jsxs("div",{className:"pp-section",children:[n.jsx("div",{className:"pp-section-title",children:"Confidence Breakdown"}),n.jsxs("div",{className:"pp-confidence-row",children:[n.jsx("span",{className:Hx(s.confidence.level),children:s.confidence.score}),n.jsx("span",{className:"pp-confidence-level",children:s.confidence.level.charAt(0).toUpperCase()+s.confidence.level.slice(1)})]}),s.confidence.factors.map((o,f)=>n.jsxs("div",{className:"pp-factor",children:[n.jsx("span",{className:"pp-factor-icon",children:o.impact==="positive"?"+":"-"}),n.jsx("span",{className:"pp-factor-signal",children:o.signal}),n.jsx("span",{className:"pp-factor-detail",children:o.detail})]},f))]}),n.jsxs("div",{className:"pp-section",children:[n.jsx("div",{className:"pp-section-title",children:"Source Attribution"}),s.sources.map((o,f)=>n.jsxs("div",{className:"pp-source-row",children:[n.jsx("span",{className:"pp-source-icon",children:Bx[o.type]??"❓"}),n.jsx("span",{className:"pp-source-label",children:o.label}),n.jsx("div",{className:"pp-source-bar-track",children:n.jsx("div",{className:"pp-source-bar",style:{width:`${Math.round(o.confidence*100)}%`}})}),n.jsx("span",{className:"pp-source-conf",children:o.confidence.toFixed(2)})]},f))]}),n.jsxs("div",{className:"pp-section",children:[n.jsx("div",{className:"pp-section-title",children:"Personality Influence"}),n.jsxs("div",{className:"pp-detail-row",children:[n.jsx("span",{className:"pp-detail-label",children:"Domain"}),n.jsx("span",{className:"pp-detail-value",children:s.personality.domain.replace(/_/g," ")})]}),n.jsxs("div",{className:"pp-detail-row",children:[n.jsx("span",{className:"pp-detail-label",children:"Register"}),n.jsx("span",{className:"pp-detail-value",children:s.personality.emotionalRegister})]}),s.personality.activeTraits.map((o,f)=>n.jsxs("div",{className:"pp-trait-row",children:[n.jsx("span",{className:"pp-trait-name",children:o.name}),n.jsx("div",{className:"pp-trait-bar-track",children:n.jsx("div",{className:"pp-trait-bar",style:{width:`${Math.round(o.weight*100)}%`}})}),n.jsx("span",{className:"pp-trait-weight",children:o.weight.toFixed(2)})]},f)),u&&n.jsxs("div",{className:"pp-kb-warning",children:["⚠"," Knowledge boundary: ",u.topic," (corrected ",u.corrections,"x)"]})]}),n.jsxs("div",{className:"pp-section",children:[n.jsx("div",{className:"pp-section-title",children:"Processing Pipeline"}),n.jsx("div",{className:"pp-pipeline",children:s.trace.enrichmentStages.map((o,f)=>n.jsxs("span",{className:"pp-pipeline-node",children:[f>0&&n.jsx("span",{className:"pp-pipeline-arrow",children:"→"}),n.jsx("span",{className:"pp-pipeline-stage",children:o})]},f))}),s.trace.toolsUsed.length>0&&n.jsxs("div",{className:"pp-detail-row",children:[n.jsx("span",{className:"pp-detail-label",children:"Tools"}),n.jsx("span",{className:"pp-detail-value",children:s.trace.toolsUsed.join(", ")})]}),n.jsxs("div",{className:"pp-detail-row",children:[n.jsx("span",{className:"pp-detail-label",children:"Model"}),n.jsxs("span",{className:"pp-detail-value",children:[s.model.provider," / ",s.model.model]})]}),n.jsxs("div",{className:"pp-detail-row",children:[n.jsx("span",{className:"pp-detail-label",children:"Latency"}),n.jsxs("span",{className:"pp-detail-value",children:[s.model.latencyMs.toLocaleString(),"ms"]})]}),n.jsxs("div",{className:"pp-detail-row",children:[n.jsx("span",{className:"pp-detail-label",children:"Tokens"}),n.jsxs("span",{className:"pp-detail-value",children:[s.model.tokens.input," in / ",s.model.tokens.output," out"]})]})]})]}),n.jsxs("div",{className:"pp-footer",children:["Total processing: ",s.trace.processingMs,"ms"]})]})]})}function Yx({tokens:s,cost:r,latencyMs:u}){const o=s.input+s.output;return o===0?null:n.jsxs("div",{className:"token-cost-badge",children:[n.jsxs("span",{className:"badge-item badge-tokens",title:`${s.input.toLocaleString()} in / ${s.output.toLocaleString()} out`,children:[o.toLocaleString()," tok"]}),n.jsxs("span",{className:"badge-item badge-cost",title:`$${r.input.toFixed(4)} in / $${r.output.toFixed(4)} out`,children:["$",r.total.toFixed(3)]}),n.jsxs("span",{className:"badge-item badge-latency",children:[u.toLocaleString(),"ms"]})]})}const Gx=[{command:"/help",description:"Show available commands"},{command:"/status",description:"Show system status"},{command:"/new",description:"Start a new session"},{command:"/reset",description:"Clear current session"},{command:"/mode",description:"Show current mode"},{command:"/mode auto",description:"Auto-detect mode from messages"},{command:"/mode off",description:"Disable modes for this session"},{command:"/mode operator",description:"Fast, action-oriented execution"},{command:"/mode analyst",description:"Deep reasoning and analysis"},{command:"/mode advisor",description:"Strategic guidance and decisions"},{command:"/mode writer",description:"Creative and polished writing"},{command:"/mode socratic",description:"Question-based learning"},{command:"/mode legal",description:"Legal research and analysis"},{command:"/mode roast",description:"Playful, witty critique"},{command:"/mode companion",description:"Warm, supportive conversation"}];function $x(s){return s.startsWith("claude-opus-4-6")?"Claude Opus 4.6":s.startsWith("claude-sonnet-4-5")?"Claude Sonnet 4.5":s.startsWith("claude-haiku-4-5")?"Claude Haiku 4.5":s.startsWith("claude-opus-4")?"Claude Opus 4":s.startsWith("claude-sonnet-4")?"Claude Sonnet 4":s.startsWith("claude-3-5-haiku")?"Claude Haiku 3.5":s.startsWith("claude-3-5-sonnet")?"Claude Sonnet 3.5":s.startsWith("claude-3-opus")?"Claude Opus 3":s==="gpt-4o"?"GPT-4o":s==="gpt-4o-mini"?"GPT-4o Mini":s==="gpt-4-turbo"?"GPT-4 Turbo":s.startsWith("o1")||s.startsWith("o3")?s.toUpperCase():s.startsWith("gemini-")?s.replace("gemini-","Gemini "):s}function Xx(s){const r=Date.now()-s,u=Math.floor(r/6e4);if(u<1)return"Just now";if(u<60)return`${u}m ago`;const o=Math.floor(u/60);if(o<24)return`${o}h ago`;const f=Math.floor(o/24);return f<7?`${f}d ago`:new Date(s).toLocaleDateString()}function Vx(s){let r=s.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">");return r=r.replace(/```(\w*)\n([\s\S]*?)```/g,(u,o,f)=>`<div class="code-block">${o?`<div class="code-header"><span class="code-lang">${o}</span><button class="code-copy" onclick="navigator.clipboard.writeText(this.closest('.code-block').querySelector('code').textContent)">Copy</button></div>`:`<div class="code-header"><button class="code-copy" onclick="navigator.clipboard.writeText(this.closest('.code-block').querySelector('code').textContent)">Copy</button></div>`}<pre><code>${f}</code></pre></div>`).replace(/`([^`]+)`/g,"<code>$1</code>").replace(/^### (.+)$/gm,"<h4>$1</h4>").replace(/^## (.+)$/gm,"<h3>$1</h3>").replace(/^# (.+)$/gm,"<h2>$1</h2>").replace(/\*\*\*(.+?)\*\*\*/g,"<strong><em>$1</em></strong>").replace(/\*\*(.+?)\*\*/g,"<strong>$1</strong>").replace(/\*(.+?)\*/g,"<em>$1</em>").replace(/^---$/gm,"<hr/>").replace(/^[-*] (.+)$/gm,"<li>$1</li>"),r=r.replace(/((?:<li>.*<\/li>\n?)+)/g,"<ul>$1</ul>"),r=r.replace(/\n\n+/g,"</p><p>"),r=r.replace(/\n/g,"<br/>"),r=`<p>${r}</p>`,r=r.replace(/<p><\/p>/g,"").replace(/<p>(<h[234]>)/g,"$1").replace(/(<\/h[234]>)<\/p>/g,"$1").replace(/<p>(<pre>)/g,"$1").replace(/(<\/pre>)<\/p>/g,"$1").replace(/<p>(<div class="code-block">)/g,"$1").replace(/(<\/div>)<\/p>/g,"$1").replace(/<p>(<ul>)/g,"$1").replace(/(<\/ul>)<\/p>/g,"$1").replace(/<p>(<hr\/>)/g,"$1").replace(/(<hr\/>)<\/p>/g,"$1"),r}function km(){var gn,vn,yn,ua,xn;const[s,r]=h.useState([]),[u,o]=h.useState(""),[f,m]=h.useState(!1),[p,x]=h.useState(!1),[y,g]=h.useState(""),[b,j]=h.useState(null),[S,w]=h.useState(""),[A,D]=h.useState("auto"),[O,E]=h.useState(0),[M,k]=h.useState(!1),[Z,K]=h.useState(!1),[q,W]=h.useState([]),[G,te]=h.useState(null),[ce,ie]=h.useState(!0),[he,ee]=h.useState(null),[oe,ve]=h.useState(null),[H,F]=h.useState(""),[le,I]=h.useState(null),de=h.useRef(null);h.useEffect(()=>{if(!le||!de.current)return;const R=de.current,ae=R.getBoundingClientRect();let{x:me,y:De}=le,Be=!1;ae.bottom>window.innerHeight&&(De=Math.max(4,le.y-ae.height),Be=!0),ae.right>window.innerWidth&&(me=Math.max(4,le.x-ae.width),Be=!0),Be&&(R.style.top=`${De}px`,R.style.left=`${me}px`)},[le]);const[C,L]=h.useState(void 0),[ne,re]=h.useState("standard"),[xe,be]=h.useState(null),[Ce,Pe]=h.useState(null),P=h.useRef(null),X=h.useRef(null),ge=h.useRef(null),qe=h.useRef(!0),$e=h.useRef(""),nt=h.useRef(0),Et=h.useRef(0),pa=h.useRef(null),qa=h.useRef(null),xt=h.useRef(null);ut(()=>J.getStatus(),[]);const{data:_e}=ut(()=>J.getModels(),[]),{data:mn}=ut(()=>J.getIdentity(),[]),{data:pn}=ut(()=>J.getPersonality(),[]);h.useEffect(()=>{xt.current=G},[G]),h.useEffect(()=>{J.getPersonalityEngine().then(R=>{var ae;(ae=R.data)!=null&&ae.engine&&re(R.data.engine)}).catch(()=>{})},[]),h.useEffect(()=>{J.getChats().then(async R=>{if(R.data&&R.data.length>0)W(R.data.map(ae=>{var me;return{id:ae.id,title:ae.title,updatedAt:ae.updatedAt,personality:(me=ae.metadata)==null?void 0:me.personality}})),te(R.data[0].id);else{const me=(await J.createNewChat()).data;W([{id:me.id,title:me.title,updatedAt:me.updatedAt}]),te(me.id),K(!0)}}).catch(()=>{})},[]),h.useEffect(()=>{if(!G){L(void 0);return}const R=q.find(ae=>ae.id===G);L(R==null?void 0:R.personality)},[G,q]),h.useEffect(()=>{if(p&&(Et.current=0,x(!1),$e.current=""),!G){r([]),K(!0);return}K(!1),J.getChatMessages(G).then(R=>{R.data?r(R.data.map(ae=>({id:ae.id,role:ae.role,content:ae.content}))):r([]),K(!0),requestAnimationFrame(()=>{var ae;(ae=X.current)==null||ae.scrollIntoView()})}).catch(()=>{r([]),K(!0)})},[G]),h.useEffect(()=>{if(s.length===0)return;const R=s[s.length-1];if(R.role!=="assistant")return;const ae=R.content.match(/Switched to \*\*(\w+)\*\* mode/);if(ae){D(ae[1].toLowerCase());return}if(R.content.includes("Mode set to **auto**")){D("auto");return}R.content.includes("Modes disabled")&&D("off")},[s]);const Vt=h.useMemo(()=>{if(!u.startsWith("/"))return[];const R=u.toLowerCase();return Gx.filter(ae=>ae.command.startsWith(R))},[u]);h.useEffect(()=>{k(Vt.length>0&&u.startsWith("/")),E(0)},[Vt,u]),h.useEffect(()=>{if(!M||!qa.current)return;const R=qa.current.children[O];R==null||R.scrollIntoView({block:"nearest"})},[O,M]);const Ms=h.useCallback(()=>{var R;qe.current&&((R=X.current)==null||R.scrollIntoView({behavior:"auto"}))},[]);h.useEffect(()=>{const R=ge.current;if(!R)return;const ae=De=>{De.deltaY<0&&(qe.current=!1)},me=()=>{const{scrollTop:De,scrollHeight:Be,clientHeight:wt}=R;Be-De-wt<40&&(qe.current=!0)};return R.addEventListener("wheel",ae,{passive:!0}),R.addEventListener("scroll",me,{passive:!0}),()=>{R.removeEventListener("wheel",ae),R.removeEventListener("scroll",me)}},[]),h.useEffect(()=>{Ms()},[s,Ms]),h.useEffect(()=>{if(!le)return;const R=()=>I(null);return document.addEventListener("click",R),()=>document.removeEventListener("click",R)},[le]),h.useEffect(()=>{const R=window.location.protocol==="https:"?"wss:":"ws:",ae=window.location.host,me=new WebSocket(`${R}//${ae}/`);return P.current=me,me.onopen=()=>m(!0),me.onclose=()=>{m(!1),x(!1)},me.onmessage=De=>{var Be,wt,Ol,Ml,Rl,Hn,qn,Dl,zl,na,lt;try{const we=JSON.parse(De.data);switch(we.type){case"connected":case"auth_success":break;case"chunk":if(g(""),nt.current!==Et.current||we.id!=null&&String(we.id)!==String(Et.current))break;$e.current+=((Be=we.payload)==null?void 0:Be.content)??"",r(ze=>{const Ee=ze[ze.length-1];return(Ee==null?void 0:Ee.role)==="assistant"&&Ee.id===`resp-${Et.current}`?[...ze.slice(0,-1),{...Ee,content:$e.current}]:[...ze,{id:`resp-${Et.current}`,role:"assistant",content:$e.current}]});break;case"message":((wt=we.payload)==null?void 0:wt.role)==="assistant"&&r(ze=>[...ze,{id:`msg-${Date.now()}`,role:"assistant",content:we.payload.content}]);break;case"tool_use":{const ze=((Ol=we.payload)==null?void 0:Ol.tool)??"tool",Ee=(Ml=we.payload)==null?void 0:Ml.params;let ga={web_browser:"Reading web page",browser_navigate:"Navigating browser",browser_click:"Clicking element",browser_type:"Typing text",browser_screenshot:"Taking screenshot",browser_extract:"Extracting data",browse:"Browsing",bash:"Running command",file_read:"Reading file",file_write:"Writing file",file_list:"Listing files"}[ze]||`Using ${ze}`;if(ze==="bash"&&(Ee!=null&&Ee.command)){const Tt=String(Ee.command);ga=`Running: ${Tt.length>60?Tt.slice(0,57)+"...":Tt}`}else if((ze==="web_browser"||ze==="browse")&&(Ee!=null&&Ee.url))try{ga=`Reading ${new URL(String(Ee.url)).hostname}`}catch{}else ze==="file_read"&&(Ee!=null&&Ee.path)&&(ga=`Reading ${String(Ee.path).split("/").pop()}`);g(ga);break}case"tool_result":g("");break;case"status":g(((Rl=we.payload)==null?void 0:Rl.message)??"Processing");break;case"done":{if(x(!1),g(""),$e.current="",nt.current!==Et.current||we.id!=null&&String(we.id)!==String(Et.current))break;const ze=(Hn=we.payload)==null?void 0:Hn.routing,Ee=(qn=we.payload)==null?void 0:qn.architect,Qt={};if(ze){const Tt=ze.model?`${ze.provider}/${ze.model}`:ze.provider;w(Tt),Qt.model=Tt}Ee&&(Qt.detectedContext=Ee.detectedContext,Qt.activeTraits=Ee.activeTraits,Qt.traitWeights=Ee.traitWeights,Qt.recommendation=Ee.recommendation);const ga=(Dl=we.payload)==null?void 0:Dl.transparency;if(ga&&(Qt.transparency=ga),Object.keys(Qt).length>0){const Tt=we.id!=null?String(we.id):null;r(St=>{const Yn=Tt?`resp-${Tt}`:null;let Ut=-1;for(let At=St.length-1;At>=0;At--)if(Yn?St[At].id===Yn:St[At].role==="assistant"){Ut=At;break}if(Ut===-1)return St;const va=St[Ut];if(va.role!=="assistant")return St;const Ga=St.slice(0,Ut).reverse().find(At=>At.role==="user");return Ga&&(Qt.userMessage=Ga.content),[...St.slice(0,Ut),{...va,...Qt},...St.slice(Ut+1)]})}break}case"chat_created":(zl=we.payload)!=null&&zl.chatId&&(te(we.payload.chatId),J.getChats().then(ze=>{ze.data&&W(ze.data.map(Ee=>({id:Ee.id,title:Ee.title,updatedAt:Ee.updatedAt})))}).catch(()=>{}));break;case"chat_titled":(na=we.payload)!=null&&na.chatId&&((lt=we.payload)!=null&<.title)&&W(ze=>ze.map(Ee=>Ee.id===we.payload.chatId?{...Ee,title:we.payload.title}:Ee));break;case"error":x(!1),g(""),$e.current="",r(ze=>{var Ee;return[...ze,{id:`err-${Date.now()}`,role:"error",content:((Ee=we.payload)==null?void 0:Ee.message)??"Unknown error"}]});break}}catch{}},()=>{me.close()}},[]);const vt=[];if(_e!=null&&_e.providers)for(const R of _e.providers)R.available&&R.models&&vt.push({provider:R.name,displayName:R.displayName||R.name,models:Object.keys(R.models)});const tc=R=>{if(!R){j(null);return}const[ae,...me]=R.split("/");j({provider:ae,model:me.join("/")})},Tl=()=>{if(!u.trim()||!P.current||!f)return;const R=u.trim(),ae=++nt.current;Et.current=ae,r(De=>[...De,{id:`user-${ae}`,role:"user",content:R}]),o(""),x(!0),$e.current="",qe.current=!0;const me={content:R};b&&(me.provider=b.provider,me.model=b.model),xt.current&&(me.chatId=xt.current),P.current.send(JSON.stringify({type:"message",id:String(ae),payload:me}))},Al=h.useCallback((R,ae,me)=>{be(null),ae==="conversation"&&(Pe(R),P.current&&f&&P.current.send(JSON.stringify({type:"message",id:String(++nt.current),payload:{content:`/context-override ${R}`,chatId:xt.current}}))),r(De=>{const Be=De.find(wt=>wt.id===me);return Be!=null&&Be.detectedContext&&Be.userMessage&&Be.detectedContext.domain!==R&&P.current&&f&&P.current.send(JSON.stringify({type:"architect_correction",payload:{userMessage:Be.userMessage,detectedDomain:Be.detectedContext.domain,correctedDomain:R}})),De.map(wt=>wt.id===me&&wt.detectedContext?{...wt,detectedContext:{...wt.detectedContext,domain:R},recommendation:void 0}:wt)})},[f]),Bn=h.useCallback((R,ae)=>{r(me=>{const De=me.find(Be=>Be.id===R);return De!=null&&De.detectedContext&&De.userMessage&&De.detectedContext.domain!==ae&&P.current&&f&&P.current.send(JSON.stringify({type:"architect_correction",payload:{userMessage:De.userMessage,detectedDomain:De.detectedContext.domain,correctedDomain:ae}})),me.map(Be=>Be.id===R?{...Be,detectedContext:Be.detectedContext?{...Be.detectedContext,domain:ae}:Be.detectedContext,recommendation:void 0}:Be)})},[f]),ac=h.useCallback(R=>{r(ae=>ae.map(me=>me.id===R?{...me,recommendation:void 0}:me))},[]),Rs=h.useCallback(()=>{Pe(null),P.current&&f&&P.current.send(JSON.stringify({type:"message",id:String(++nt.current),payload:{content:"/context-override clear",chatId:xt.current}}))},[f]),nc=h.useCallback(async R=>{if(!G)return;const ae=R||void 0;try{await J.updateChatPersonality(G,R||"standard"),L(ae),W(me=>me.map(De=>De.id===G?{...De,personality:ae}:De))}catch{}},[G]),lc=async()=>{var R;try{const me=(await J.createNewChat()).data;W(De=>[{id:me.id,title:me.title,updatedAt:me.updatedAt},...De]),te(me.id),r([]),Pe(null),be(null),K(!0),(R=pa.current)==null||R.focus()}catch{}},Ya=async R=>{if(!H.trim()){ve(null);return}try{await J.renameChat(R,H.trim()),W(ae=>ae.map(me=>me.id===R?{...me,title:H.trim()}:me))}catch{}ve(null)},bt=async R=>{try{await J.deleteChatThread(R),W(ae=>ae.filter(me=>me.id!==R)),G===R&&(te(null),r([]))}catch{}I(null)},ra=async R=>{try{await J.archiveChat(R),W(ae=>ae.filter(me=>me.id!==R)),G===R&&(te(null),r([]))}catch{}I(null)},jt=A==="auto"?"Auto":A==="off"?"Off":A.charAt(0).toUpperCase()+A.slice(1),sc=((gn=mn==null?void 0:mn.data)==null?void 0:gn.name)??"Auxiora",Ds=((yn=(vn=pn==null?void 0:pn.data)==null?void 0:vn.template)==null?void 0:yn.name)??null,ic=R=>({__html:Vx(R)});return n.jsxs("div",{className:"page",children:[n.jsx("h2",{children:"Chat"}),n.jsxs("div",{className:"chat-layout",children:[n.jsxs("div",{className:`chat-sidebar${ce?"":" closed"}`,children:[n.jsxs("div",{className:"chat-sidebar-header",children:[n.jsx("button",{className:"new-chat-btn",onClick:lc,children:"+ New Chat"}),n.jsx("button",{className:"sidebar-toggle",onClick:()=>ie(R=>!R),title:ce?"Hide sidebar":"Show sidebar",children:ce?"«":"»"})]}),ce&&n.jsxs("div",{className:"chat-sidebar-list",children:[q.map(R=>n.jsx("div",{className:`chat-sidebar-item${G===R.id?" active":""}`,onClick:()=>{oe!==R.id&&te(R.id)},onContextMenu:ae=>{ae.preventDefault(),I({chatId:R.id,x:ae.clientX,y:ae.clientY})},children:oe===R.id?n.jsx("input",{className:"chat-rename-input",value:H,onChange:ae=>F(ae.target.value),onKeyDown:ae=>{ae.key==="Enter"&&Ya(R.id),ae.key==="Escape"&&ve(null)},onBlur:()=>Ya(R.id),autoFocus:!0}):n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"chat-sidebar-title",children:R.title}),n.jsx("span",{className:"chat-sidebar-time",children:Xx(R.updatedAt)})]})},R.id)),q.length===0&&n.jsx("div",{className:"chat-sidebar-empty",children:"No chats yet"})]})]}),le&&Jy.createPortal(n.jsxs("div",{ref:de,className:"chat-context-menu",style:{position:"fixed",top:le.y,left:le.x},children:[n.jsx("button",{onClick:()=>{const R=q.find(ae=>ae.id===le.chatId);F((R==null?void 0:R.title)??""),ve(le.chatId),I(null)},children:"Rename"}),n.jsx("button",{onClick:()=>ra(le.chatId),children:"Archive"}),n.jsx("button",{className:"danger",onClick:()=>bt(le.chatId),children:"Delete"})]}),document.body),n.jsxs("div",{className:"chat-container",children:[n.jsxs("div",{className:"chat-status",children:[n.jsxs("span",{className:"chat-status-left",children:[n.jsx("span",{className:"chat-status-dot","data-connected":f}),n.jsx("span",{className:"chat-agent-name",children:sc}),n.jsx("span",{className:"chat-status-sep"}),n.jsxs("span",{className:"chat-status-label",children:["Mode: ",n.jsx("strong",{children:jt})]}),n.jsx("span",{className:"chat-status-sep"}),n.jsxs("span",{className:"chat-status-label",children:["Engine:"," ",n.jsxs("select",{className:"chat-personality-select",value:C??"",onChange:R=>nc(R.target.value),title:"Per-chat personality engine",children:[n.jsxs("option",{value:"",children:["Global (",ne==="the-architect"?"Architect":"Standard",")"]}),n.jsx("option",{value:"standard",children:"Standard"}),n.jsx("option",{value:"the-architect",children:"The Architect"})]})]}),Ds&&n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"chat-status-sep"}),n.jsxs("span",{className:"chat-status-label",children:["Personality: ",n.jsx("strong",{children:Ds})]})]})]}),n.jsxs("span",{className:"chat-status-right",children:[n.jsx("button",{className:"sidebar-toggle-inline",onClick:()=>ie(R=>!R),title:ce?"Hide sidebar":"Show sidebar",children:"☰"}),n.jsx("div",{className:"model-selector",children:n.jsxs("select",{value:b?`${b.provider}/${b.model}`:"",onChange:R=>tc(R.target.value),children:[n.jsx("option",{value:"",children:"Auto (router)"}),vt.map(R=>n.jsx("optgroup",{label:R.displayName,children:R.models.map(ae=>n.jsx("option",{value:`${R.provider}/${ae}`,children:$x(ae)},`${R.provider}/${ae}`))},R.provider))]})})]})]}),n.jsxs("div",{className:"chat-messages",ref:ge,children:[!G&&n.jsx("div",{style:{textAlign:"center",color:"var(--text-secondary)",padding:"2rem"},children:"Select a chat or create a new one"}),G&&!Z&&n.jsx("div",{style:{textAlign:"center",color:"var(--text-secondary)",padding:"2rem"},children:"Loading..."}),G&&Z&&s.length===0&&n.jsx("div",{style:{textAlign:"center",color:"var(--text-secondary)",padding:"2rem"},children:"Send a message to start chatting"}),Ce&&n.jsxs("div",{className:"context-override-banner",children:[n.jsxs("span",{children:["Context locked to ",((ua=_t[Ce])==null?void 0:ua.icon)??"🔒"," ",((xn=_t[Ce])==null?void 0:xn.label)??Ce]}),n.jsx("button",{className:"context-override-unlock",onClick:Rs,"aria-label":"Clear context override",children:"Tap to unlock"})]}),s.map(R=>n.jsxs("div",{className:`chat-message ${R.role}`,children:[R.role==="assistant"&&R.detectedContext&&n.jsxs("div",{className:"chat-context-row",children:[n.jsx(Ax,{context:R.detectedContext,onOverride:ae=>Al(ae,"message",R.id)}),n.jsx("button",{className:"context-override-trigger",onClick:()=>be(xe===R.id?null:R.id),"aria-label":"Override context",children:"✎"}),n.jsx(kx,{isOpen:xe===R.id,currentDomain:R.detectedContext.domain,onSelect:(ae,me)=>Al(ae,me,R.id),onClose:()=>be(null)})]}),R.role==="assistant"&&R.recommendation&&n.jsx(_x,{recommendation:R.recommendation,onAccept:ae=>Bn(R.id,ae),onDismiss:()=>ac(R.id)}),R.role==="assistant"?n.jsx("div",{className:"chat-markdown",dangerouslySetInnerHTML:ic(R.content)}):R.content,R.role==="assistant"&&R.activeTraits&&R.activeTraits.length>0&&n.jsx(zx,{sources:R.activeTraits,context:R.detectedContext,weights:R.traitWeights}),R.role==="assistant"&&R.transparency&&n.jsxs("div",{className:"chat-message-meta",children:[n.jsx(Yx,{tokens:R.transparency.model.tokens,cost:R.transparency.model.cost,latencyMs:R.transparency.model.latencyMs}),R.model&&n.jsx("span",{className:"model-label",children:R.model})]}),R.role==="assistant"&&!R.transparency&&R.model&&n.jsx("div",{className:"model-label",children:R.model}),R.role==="assistant"&&R.transparency&&n.jsx(Lx,{meta:R.transparency}),R.role==="assistant"&&R.transparency&&n.jsx("button",{className:"pp-trigger-btn",onClick:()=>ee(R.id),children:"Why?"})]},R.id)),p&&y&&n.jsxs("div",{className:"chat-tool-status",children:[n.jsx("span",{className:"tool-status-dot"}),y,"..."]}),n.jsx("div",{ref:X})]}),he&&(()=>{const R=s.find(ae=>ae.id===he);return R!=null&&R.transparency?n.jsx(qx,{meta:R.transparency,onClose:()=>ee(null)}):null})(),n.jsxs("div",{className:"chat-input-area",children:[n.jsxs("div",{className:"chat-input-wrapper",children:[M&&Vt.length>0&&n.jsx("div",{className:"slash-autocomplete",ref:qa,children:Vt.map((R,ae)=>n.jsxs("div",{className:`slash-ac-item${ae===O?" selected":""}`,onMouseEnter:()=>E(ae),onMouseDown:me=>{var De;me.preventDefault(),o(R.command),k(!1),(De=pa.current)==null||De.focus()},children:[n.jsx("span",{className:"slash-ac-cmd",children:R.command}),n.jsx("span",{className:"slash-ac-desc",children:R.description})]},R.command))}),n.jsx("input",{ref:pa,type:"text",value:u,onChange:R=>o(R.target.value),onKeyDown:R=>{if(M&&Vt.length>0){if(R.key==="ArrowDown"){R.preventDefault(),E(ae=>(ae+1)%Vt.length);return}if(R.key==="ArrowUp"){R.preventDefault(),E(ae=>(ae-1+Vt.length)%Vt.length);return}if(R.key==="Tab"||R.key==="Enter"&&Vt.length>1){R.preventDefault(),o(Vt[O].command),k(!1);return}if(R.key==="Escape"){R.preventDefault(),k(!1);return}}R.key==="Enter"&&Tl()},placeholder:G?f?"Type / for commands...":"Connecting...":"Select or create a chat...",disabled:!f||!G})]}),n.jsx("button",{onClick:Tl,disabled:!f||!u.trim()||!G,children:"Send"})]})]})]})]})}const Qx={active:"badge-green",paused:"badge-yellow",deleted:"badge-red",enabled:"badge-green",disabled:"badge-gray"};function _m({status:s}){const r=Qx[s]||"badge-gray";return n.jsx("span",{className:`badge ${r}`,children:s})}const Um=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],wu=Intl.DateTimeFormat().resolvedOptions().timeZone;function Kx(s,r,u,o,f){if(s==="custom")return f;if(s==="hourly")return"0 * * * *";if(s==="every-n-hours")return`0 */${u} * * *`;const[m,p]=r.split(":").map(Number),x=isNaN(p)?0:p,y=isNaN(m)?8:m;return s==="daily"?`${x} ${y} * * *`:s==="weekday"?`${x} ${y} * * 1-5`:s==="weekly"?`${x} ${y} * * ${o}`:f}function Lm(s){const r=s.trim().split(/\s+/);if(r.length!==5)return{freq:"custom",time:"08:00",everyNHours:2,weekday:1};const[u,o,f,m,p]=r;if(u==="0"&&o==="*"&&f==="*"&&m==="*"&&p==="*")return{freq:"hourly",time:"08:00",everyNHours:2,weekday:1};const x=o.match(/^\*\/(\d+)$/);if(u==="0"&&x&&f==="*"&&m==="*"&&p==="*")return{freq:"every-n-hours",time:"08:00",everyNHours:parseInt(x[1],10),weekday:1};const y=parseInt(u,10),g=parseInt(o,10);if(isNaN(y)||isNaN(g))return{freq:"custom",time:"08:00",everyNHours:2,weekday:1};const b=`${String(g).padStart(2,"0")}:${String(y).padStart(2,"0")}`;if(f==="*"&&m==="*"&&p==="*")return{freq:"daily",time:b,everyNHours:2,weekday:1};if(f==="*"&&m==="*"&&p==="1-5")return{freq:"weekday",time:b,everyNHours:2,weekday:1};const j=parseInt(p,10);return f==="*"&&m==="*"&&!isNaN(j)&&j>=0&&j<=6?{freq:"weekly",time:b,everyNHours:2,weekday:j}:{freq:"custom",time:b,everyNHours:2,weekday:1}}function Ih(s){const r=Lm(s);switch(r.freq){case"daily":return`Daily at ${r.time}`;case"weekday":return`Weekdays at ${r.time}`;case"hourly":return"Every hour";case"every-n-hours":return`Every ${r.everyNHours}h`;case"weekly":return`${Um[r.weekday]}s at ${r.time}`;default:return s}}function Bm(){const{data:s,refresh:r}=ut(()=>J.getBehaviors(),[]);Os(r);const[u,o]=h.useState("closed"),[f,m]=h.useState(null),[p,x]=h.useState("scheduled"),[y,g]=h.useState(""),[b,j]=h.useState("daily"),[S,w]=h.useState("08:00"),[A,D]=h.useState(2),[O,E]=h.useState(1),[M,k]=h.useState(""),[Z,K]=h.useState(wu),[q,W]=h.useState(5),[G,te]=h.useState(""),[ce,ie]=h.useState(""),[he,ee]=h.useState(!1),[oe,ve]=h.useState(""),[H,F]=h.useState(""),le=(s==null?void 0:s.data)??[],I=h.useMemo(()=>Kx(b,S,A,O,M),[b,S,A,O,M]),de=P=>{var X,ge;return(X=P.schedule)!=null&&X.cron?Ih(P.schedule.cron):P.polling?`Every ${Math.round(P.polling.intervalMs/6e4)}m`:(ge=P.delay)!=null&&ge.fireAt?new Date(P.delay.fireAt).toLocaleString():"-"},C=async P=>{try{const X=P.status==="active"?"paused":"active";await J.patchBehavior(P.id,{status:X}),r()}catch(X){alert(X.message||"Failed to update behavior")}},L=async P=>{var X;if(confirm(`Delete behavior "${(X=P.action)==null?void 0:X.slice(0,40)}"?`))try{await J.deleteBehavior(P.id),r()}catch(ge){alert(ge.message||"Failed to delete behavior")}},ne=()=>{m(null),x("scheduled"),g(""),j("daily"),w("08:00"),D(2),E(1),k(""),K(wu),W(5),te(""),ie(""),ve(""),F("")},re=()=>{ne(),o("create")},xe=P=>{var X,ge,qe;if(m(P.id),x(P.type??"scheduled"),g(P.action??""),(X=P.schedule)!=null&&X.cron){const $e=Lm(P.schedule.cron);j($e.freq),w($e.time),D($e.everyNHours),E($e.weekday),k($e.freq==="custom"?P.schedule.cron:"")}if(K(((ge=P.schedule)==null?void 0:ge.timezone)??wu),P.polling&&(W(Math.round(P.polling.intervalMs/6e4)),te(P.polling.condition??"")),(qe=P.delay)!=null&&qe.fireAt){const $e=new Date(P.delay.fireAt);ie($e.toISOString().slice(0,16))}ve(""),F(""),o("edit")},be=()=>{ne(),o("closed")},Ce=async P=>{P.preventDefault(),ve(""),F(""),ee(!0);try{const X={action:y};p==="scheduled"?(X.cron=I,X.timezone=Z):p==="monitor"?(X.intervalMinutes=q,X.condition=G):p==="one-shot"&&(X.runAt=ce),u==="edit"&&f?(await J.patchBehavior(f,X),F("Behavior updated")):(X.type=p,await J.createBehavior(X),F("Behavior created")),ne(),o("closed"),r()}catch(X){ve(X.message||`Failed to ${u==="edit"?"update":"create"} behavior`)}finally{ee(!1)}},Pe=b==="daily"||b==="weekday"||b==="weekly";return n.jsxs("div",{className:"page",children:[n.jsx("h2",{children:"Behaviors"}),n.jsx("div",{className:"create-form-toggle",children:n.jsx("button",{className:"btn-sm",onClick:()=>u!=="closed"?be():re(),children:u!=="closed"?"Cancel":"New Behavior"})}),u!=="closed"&&n.jsx("div",{className:"create-form",children:n.jsxs("form",{onSubmit:Ce,children:[n.jsx("h3",{children:u==="edit"?"Edit Behavior":"New Behavior"}),u==="create"&&n.jsxs(n.Fragment,{children:[n.jsx("label",{children:"Type"}),n.jsxs("select",{value:p,onChange:P=>x(P.target.value),children:[n.jsx("option",{value:"scheduled",children:"Scheduled"}),n.jsx("option",{value:"monitor",children:"Monitor (polling)"}),n.jsx("option",{value:"one-shot",children:"One-shot (run once)"})]})]}),n.jsx("label",{children:"Action"}),n.jsx("textarea",{value:y,onChange:P=>g(P.target.value),placeholder:"What should the agent do?",required:!0,rows:3}),p==="scheduled"&&n.jsxs("div",{className:"create-form-group",children:[n.jsx("label",{children:"How often?"}),n.jsxs("select",{value:b,onChange:P=>j(P.target.value),children:[n.jsx("option",{value:"daily",children:"Every day"}),n.jsx("option",{value:"weekday",children:"Every weekday (Mon-Fri)"}),n.jsx("option",{value:"weekly",children:"Once a week"}),n.jsx("option",{value:"hourly",children:"Every hour"}),n.jsx("option",{value:"every-n-hours",children:"Every few hours"}),n.jsx("option",{value:"custom",children:"Custom (cron)"})]}),b==="weekly"&&n.jsxs(n.Fragment,{children:[n.jsx("label",{children:"Day of week"}),n.jsx("select",{value:O,onChange:P=>E(Number(P.target.value)),children:Um.map((P,X)=>n.jsx("option",{value:X,children:P},X))})]}),Pe&&n.jsxs(n.Fragment,{children:[n.jsx("label",{children:"Time"}),n.jsx("input",{type:"time",value:S,onChange:P=>w(P.target.value),required:!0})]}),b==="every-n-hours"&&n.jsxs(n.Fragment,{children:[n.jsx("label",{children:"Every how many hours?"}),n.jsx("input",{type:"number",value:A,onChange:P=>D(Number(P.target.value)),min:1,max:23,required:!0})]}),b==="custom"&&n.jsxs(n.Fragment,{children:[n.jsx("label",{children:"Cron expression"}),n.jsx("input",{type:"text",value:M,onChange:P=>k(P.target.value),placeholder:"0 8 * * *",required:!0})]}),n.jsx("label",{children:"Timezone"}),n.jsx("input",{type:"text",value:Z,onChange:P=>K(P.target.value)}),n.jsxs("div",{className:"form-hint",children:["Schedule: ",n.jsx("strong",{children:Ih(I)})," (",Z,")"]})]}),p==="monitor"&&n.jsxs("div",{className:"create-form-group",children:[n.jsx("label",{children:"Check every (minutes)"}),n.jsx("input",{type:"number",value:q,onChange:P=>W(Number(P.target.value)),min:1,required:!0}),n.jsx("label",{children:"Condition"}),n.jsx("textarea",{value:G,onChange:P=>te(P.target.value),placeholder:"When should this trigger?",required:!0,rows:2})]}),p==="one-shot"&&n.jsxs("div",{className:"create-form-group",children:[n.jsx("label",{children:"Run at"}),n.jsx("input",{type:"datetime-local",value:ce,onChange:P=>ie(P.target.value),required:!0})]}),oe&&n.jsx("div",{className:"error",children:oe}),H&&n.jsx("div",{className:"settings-success",children:H}),n.jsx("button",{type:"submit",className:"settings-btn",disabled:he||!y,children:he?"Saving...":u==="edit"?"Save Changes":"Create Behavior"})]})}),le.length===0?n.jsx("div",{className:"bv-empty",children:"No behaviors configured yet."}):n.jsx("div",{className:"bv-list",children:le.map(P=>n.jsxs("div",{className:`bv-card ${P.status==="paused"?"bv-card--paused":""}`,children:[n.jsxs("div",{className:"bv-card-main",children:[n.jsx("div",{className:"bv-card-action",children:P.action}),n.jsxs("div",{className:"bv-card-meta",children:[n.jsx("span",{className:"bv-card-schedule",children:de(P)}),n.jsx(_m,{status:P.status}),n.jsx("span",{className:"bv-card-type",children:P.type})]}),n.jsxs("div",{className:"bv-card-stats",children:[n.jsxs("span",{children:[P.runCount??0," run",(P.runCount??0)!==1?"s":""]}),(P.failCount??0)>0&&n.jsxs("span",{className:"bv-card-fails",children:[P.failCount," failed"]}),P.lastRun&&n.jsxs("span",{className:"bv-card-lastrun",children:["Last: ",new Date(P.lastRun).toLocaleString()]})]})]}),n.jsxs("div",{className:"bv-card-actions",children:[n.jsx("button",{className:"btn-sm",onClick:()=>xe(P),children:"Edit"}),n.jsx("button",{className:"btn-sm",onClick:()=>C(P),children:P.status==="active"?"Pause":"Resume"}),n.jsx("button",{className:"btn-sm btn-danger",onClick:()=>L(P),children:"Delete"})]})]},P.id))})]})}function Hm({columns:s,rows:r,keyField:u,actions:o}){return n.jsxs("table",{className:"data-table",children:[n.jsx("thead",{children:n.jsxs("tr",{children:[s.map(f=>n.jsx("th",{children:f.label},f.key)),o&&n.jsx("th",{children:"Actions"})]})}),n.jsx("tbody",{children:r.length===0?n.jsx("tr",{children:n.jsx("td",{colSpan:s.length+(o?1:0),className:"empty-row",children:"No data"})}):r.map(f=>n.jsxs("tr",{children:[s.map(m=>n.jsx("td",{children:m.render?m.render(f):String(f[m.key]??"")},m.key)),o&&n.jsx("td",{className:"actions-cell",children:o(f)})]},f[u]))})]})}function qm(){const{data:s,refresh:r}=ut(()=>J.getWebhooks(),[]),{data:u}=ut(()=>J.getBehaviors(),[]);Os(r);const o=(s==null?void 0:s.data)??[],f=(u==null?void 0:u.data)??[],[m,p]=h.useState(!1),[x,y]=h.useState(""),[g,b]=h.useState(""),[j,S]=h.useState(""),[w,A]=h.useState(!1),[D,O]=h.useState(""),[E,M]=h.useState(""),k=[{key:"name",label:"Name"},{key:"type",label:"Type"},{key:"enabled",label:"Status",render:G=>n.jsx(_m,{status:G.enabled?"enabled":"disabled"})},{key:"behaviorId",label:"Behavior",render:G=>G.behaviorId||"-"},{key:"createdAt",label:"Created",render:G=>new Date(G.createdAt).toLocaleDateString()}],Z=async G=>{try{await J.patchWebhook(G.id,{enabled:!G.enabled}),r()}catch(te){alert(te.message||"Failed to update webhook")}},K=async G=>{if(confirm(`Delete webhook "${G.name}"?`))try{await J.deleteWebhook(G.id),r()}catch(te){alert(te.message||"Failed to delete webhook")}},q=()=>{y(""),b(""),S(""),O(""),M("")},W=async G=>{G.preventDefault(),O(""),M(""),A(!0);try{const te={name:x,secret:g};j&&(te.behaviorId=j),await J.createWebhook(te);const ce=`${window.location.origin}/api/v1/webhooks/custom/${x}`;M(ce),q(),p(!1),r()}catch(te){O(te.message||"Failed to create webhook")}finally{A(!1)}};return n.jsxs("div",{className:"page",children:[n.jsx("h2",{children:"Webhooks"}),n.jsx("div",{className:"create-form-toggle",children:n.jsx("button",{className:"btn-sm",onClick:()=>{p(!m),m&&q()},children:m?"Cancel":"New Webhook"})}),E&&n.jsxs("div",{className:"create-form-success",children:["Webhook created. URL: ",n.jsx("code",{children:E})]}),m&&n.jsx("div",{className:"create-form",children:n.jsxs("form",{onSubmit:W,children:[n.jsx("label",{children:"Name"}),n.jsx("input",{type:"text",value:x,onChange:G=>y(G.target.value),placeholder:"my-webhook",pattern:"[a-zA-Z0-9_-]+",title:"URL-safe: letters, numbers, hyphens, underscores",required:!0}),n.jsx("label",{children:"Secret"}),n.jsx("input",{type:"password",value:g,onChange:G=>b(G.target.value),placeholder:"HMAC signing key",required:!0}),n.jsx("label",{children:"Behavior (optional)"}),n.jsxs("select",{value:j,onChange:G=>S(G.target.value),children:[n.jsx("option",{value:"",children:"None"}),f.map(G=>{var te;return n.jsx("option",{value:G.id,children:((te=G.action)==null?void 0:te.slice(0,50))||G.id},G.id)})]}),D&&n.jsx("div",{className:"error",children:D}),n.jsx("button",{type:"submit",className:"settings-btn",disabled:w||!x||!g,children:w?"Creating...":"Create Webhook"})]})}),n.jsx(Hm,{columns:k,rows:o,keyField:"id",actions:G=>n.jsxs(n.Fragment,{children:[n.jsx("button",{className:"btn-sm",onClick:()=>Z(G),children:G.enabled?"Disable":"Enable"}),n.jsx("button",{className:"btn-sm btn-danger",onClick:()=>K(G),children:"Delete"})]})})]})}const Zx=["professional","apologetic","matter_of_fact","self_deprecating","gentle","detailed","encouraging","terse","educational"],Jx=["she/her","he/him","they/them","it/its"],Wx=["greeting","farewell","thinking","success","error"],Fx=[{key:"warmth",label:"Warmth",low:"Reserved",high:"Warm"},{key:"directness",label:"Directness",low:"Gentle",high:"Direct"},{key:"humor",label:"Humor",low:"Serious",high:"Playful"},{key:"formality",label:"Formality",low:"Casual",high:"Formal"}];function Tu({tags:s,onChange:r,placeholder:u}){const[o,f]=h.useState(""),m=x=>{if(x.key==="Enter"){x.preventDefault();const y=o.trim();y&&!s.includes(y)&&r([...s,y]),f("")}else x.key==="Backspace"&&o===""&&s.length>0&&r(s.slice(0,-1))},p=x=>{r(s.filter((y,g)=>g!==x))};return n.jsxs("div",{className:"tag-input-container",children:[n.jsx("div",{className:"tag-list",children:s.map((x,y)=>n.jsxs("span",{className:"tag",children:[x,n.jsx("button",{type:"button",className:"tag-remove",onClick:()=>p(y),"aria-label":`Remove ${x}`,children:"x"})]},y))}),n.jsx("input",{className:"tag-input",type:"text",value:o,onChange:x=>f(x.target.value),onKeyDown:m,placeholder:u??"Type and press Enter"})]})}function Px({label:s,low:r,high:u,value:o,onChange:f}){const m=Math.round(o*100);return n.jsxs("div",{className:"tone-slider",children:[n.jsxs("div",{className:"tone-slider-header",children:[n.jsx("span",{className:"tone-label",children:s}),n.jsxs("span",{className:"tone-value",children:[m,"%"]})]}),n.jsxs("div",{className:"tone-slider-row",children:[n.jsx("span",{className:"tone-extreme",children:r}),n.jsx("input",{className:"slider",type:"range",min:0,max:100,value:m,onChange:p=>f(Number(p.target.value)/100)}),n.jsx("span",{className:"tone-extreme",children:u})]})]})}const Ix={name:"",pronouns:"they/them",avatar:null,vibe:"",tone:{warmth:.5,directness:.5,humor:.5,formality:.5},errorStyle:"professional",expertise:[],catchphrases:{greeting:"",farewell:"",thinking:"",success:"",error:""},boundaries:{neverJokeAbout:[],neverAdviseOn:[]},customInstructions:"",soulContent:null,activeTemplate:null};function Ym(){const[s,r]=h.useState(null),[u,o]=h.useState(Ix),[f,m]=h.useState(null),[p,x]=h.useState(!1),[y,g]=h.useState(!1),[b,j]=h.useState(""),[S,w]=h.useState(""),[A,D]=h.useState("");h.useEffect(()=>{J.getPersonalityFull().then(ee=>{var H,F,le,I,de,C,L;const oe=ee.data,ve={name:oe.name??"",pronouns:oe.pronouns??"they/them",avatar:oe.avatar??null,vibe:oe.vibe??"",tone:oe.tone??{warmth:.5,directness:.5,humor:.5,formality:.5},errorStyle:oe.errorStyle??"professional",expertise:oe.expertise??[],catchphrases:{greeting:((H=oe.catchphrases)==null?void 0:H.greeting)??"",farewell:((F=oe.catchphrases)==null?void 0:F.farewell)??"",thinking:((le=oe.catchphrases)==null?void 0:le.thinking)??"",success:((I=oe.catchphrases)==null?void 0:I.success)??"",error:((de=oe.catchphrases)==null?void 0:de.error)??""},boundaries:{neverJokeAbout:((C=oe.boundaries)==null?void 0:C.neverJokeAbout)??[],neverAdviseOn:((L=oe.boundaries)==null?void 0:L.neverAdviseOn)??[]},customInstructions:oe.customInstructions??"",soulContent:oe.soulContent??null,activeTemplate:oe.activeTemplate??null};o(ve),r(ve),m(ve.activeTemplate)}).catch(ee=>D(ee.message))},[]);const{data:O,loading:E}=ut(()=>J.getTemplates(),[]),M=(O==null?void 0:O.data)??[],Z=h.useCallback(()=>s?f!==s.activeTemplate?!0:JSON.stringify(u)!==JSON.stringify(s):!1,[u,s,f])(),K=(ee,oe)=>{o(ve=>({...ve,[ee]:oe}))},q=(ee,oe)=>{o(ve=>({...ve,tone:{...ve.tone,[ee]:oe}}))},W=(ee,oe)=>{o(ve=>({...ve,catchphrases:{...ve.catchphrases,[ee]:oe}}))},G=(ee,oe)=>{o(ve=>({...ve,boundaries:{...ve.boundaries,[ee]:oe}}))},te=async()=>{g(!0),w(""),j("");try{const ee={name:u.name,pronouns:u.pronouns,avatar:u.avatar,vibe:u.vibe,tone:u.tone,errorStyle:u.errorStyle,expertise:u.expertise,catchphrases:u.catchphrases,boundaries:u.boundaries,customInstructions:u.customInstructions,soulContent:u.soulContent};f!==(s==null?void 0:s.activeTemplate)&&(ee.activeTemplate=f),await J.updatePersonalityFull(ee);const oe={...u,activeTemplate:f};r(oe),j("Personality settings saved successfully")}catch(ee){w(ee instanceof Error?ee.message:"Failed to save")}finally{g(!1)}},[ce,ie]=h.useState(!1);if(h.useEffect(()=>{if(!u.avatar){ie(!1);return}try{new URL(u.avatar),ie(!0)}catch{ie(!1)}},[u.avatar]),A)return n.jsx("div",{className:"page",children:n.jsxs("div",{className:"error",children:["Failed to load personality data: ",A]})});if(!s)return n.jsx("div",{className:"page",children:n.jsx("p",{children:"Loading personality settings..."})});const he=n.jsx("button",{className:"settings-btn",onClick:te,disabled:y||!Z,children:y?"Saving...":"Save Changes"});return n.jsxs("div",{className:"page",children:[n.jsxs("div",{className:"page-header",children:[n.jsx("h2",{children:"Personality Editor"}),Z&&he]}),b&&n.jsx("div",{className:"settings-success",children:b}),S&&n.jsx("div",{className:"error",children:S}),n.jsxs("div",{className:"settings-form",children:[n.jsxs("div",{className:"editor-section",children:[n.jsx("h3",{children:"Identity"}),n.jsxs("div",{className:"form-grid",children:[n.jsxs("div",{className:"form-field",children:[n.jsx("label",{children:"Name"}),n.jsx("input",{type:"text",value:u.name,onChange:ee=>K("name",ee.target.value),placeholder:"Agent name"})]}),n.jsxs("div",{className:"form-field",children:[n.jsx("label",{children:"Pronouns"}),n.jsx("select",{value:u.pronouns,onChange:ee=>K("pronouns",ee.target.value),children:Jx.map(ee=>n.jsx("option",{value:ee,children:ee},ee))})]}),n.jsxs("div",{className:"form-field full-width",children:[n.jsx("label",{children:"Vibe"}),n.jsx("input",{type:"text",value:u.vibe,onChange:ee=>{ee.target.value.length<=200&&K("vibe",ee.target.value)},placeholder:"A short description of the assistant's personality vibe",maxLength:200}),n.jsxs("span",{className:"field-hint",children:[u.vibe.length,"/200 characters"]})]}),n.jsxs("div",{className:"form-field full-width",children:[n.jsx("label",{children:"Avatar URL"}),n.jsx("input",{type:"text",value:u.avatar??"",onChange:ee=>K("avatar",ee.target.value||null),placeholder:"https://example.com/avatar.png"}),ce&&u.avatar&&n.jsx("img",{src:u.avatar,alt:"Avatar preview",style:{width:64,height:64,borderRadius:8,marginTop:8,objectFit:"cover"},onError:()=>ie(!1)})]})]})]}),n.jsxs("div",{className:"editor-section",children:[n.jsx("h3",{children:"Tone"}),n.jsx("div",{className:"tone-sliders",children:Fx.map(ee=>n.jsx(Px,{label:ee.label,low:ee.low,high:ee.high,value:u.tone[ee.key],onChange:oe=>q(ee.key,oe)},ee.key))})]}),n.jsxs("div",{className:"editor-section",children:[n.jsx("h3",{children:"Quick Start Templates"}),E&&n.jsx("p",{children:"Loading templates..."}),n.jsx("div",{className:"template-grid",children:M.map(ee=>n.jsxs("div",{className:`template-card${f===ee.id?" selected":""}`,onClick:()=>m(ee.id),children:[n.jsx("h4",{children:ee.name}),n.jsx("p",{children:ee.description})]},ee.id))})]}),n.jsxs("div",{className:"editor-section",children:[n.jsx("h3",{children:"Behavior"}),n.jsxs("div",{className:"form-grid",children:[n.jsxs("div",{className:"form-field",children:[n.jsx("label",{children:"Error Style"}),n.jsx("select",{value:u.errorStyle,onChange:ee=>K("errorStyle",ee.target.value),children:Zx.map(ee=>n.jsx("option",{value:ee,children:ee.replace(/_/g," ")},ee))})]}),n.jsxs("div",{className:"form-field full-width",children:[n.jsx("label",{children:"Expertise Areas"}),n.jsx(Tu,{tags:u.expertise,onChange:ee=>K("expertise",ee),placeholder:"Add expertise area and press Enter"})]}),n.jsxs("div",{className:"form-field full-width",children:[n.jsx("label",{children:"Catchphrases"}),n.jsx("div",{className:"catchphrase-grid",children:Wx.map(ee=>n.jsxs("div",{className:"catchphrase-row",children:[n.jsx("span",{className:"catchphrase-label",children:ee}),n.jsx("input",{type:"text",value:u.catchphrases[ee]??"",onChange:oe=>W(ee,oe.target.value),placeholder:`${ee} phrase`})]},ee))})]}),n.jsxs("div",{className:"form-field full-width",children:[n.jsx("label",{children:"Never Joke About"}),n.jsx(Tu,{tags:u.boundaries.neverJokeAbout,onChange:ee=>G("neverJokeAbout",ee),placeholder:"Add topic and press Enter"})]}),n.jsxs("div",{className:"form-field full-width",children:[n.jsx("label",{children:"Never Advise On"}),n.jsx(Tu,{tags:u.boundaries.neverAdviseOn,onChange:ee=>G("neverAdviseOn",ee),placeholder:"Add topic and press Enter"})]})]})]}),n.jsxs("div",{className:"editor-section",children:[n.jsx("h3",{children:"Custom Instructions"}),n.jsxs("div",{className:"form-field full-width",children:[n.jsx("textarea",{className:"custom-instructions-textarea",rows:6,value:u.customInstructions,onChange:ee=>{ee.target.value.length<=4e3&&K("customInstructions",ee.target.value)},maxLength:4e3,placeholder:"Add any custom instructions for the assistant..."}),n.jsxs("span",{className:"field-hint",children:[u.customInstructions.length,"/4000 characters. These instructions are always included in the system prompt and guide the assistant's overall behavior."]})]})]}),n.jsxs("div",{className:"editor-section",children:[n.jsxs("h3",{children:["Advanced",n.jsxs("button",{type:"button",className:"section-toggle",onClick:()=>x(!p),children:[p?"Hide":"Show"," Raw SOUL.md"]})]}),p&&n.jsxs(n.Fragment,{children:[n.jsx("p",{className:"field-hint",style:{marginBottom:"0.5rem"},children:"Warning: selecting a template will overwrite manual edits to this content."}),n.jsx("textarea",{className:"soul-editor-textarea",rows:16,value:u.soulContent??"",onChange:ee=>K("soulContent",ee.target.value||null),placeholder:"Raw SOUL.md content...",style:{fontFamily:"monospace"}})]})]}),Z&&n.jsx("div",{className:"editor-footer",children:he})]})]})}const Ki=[{id:"anthropic",label:"Anthropic (Claude)",needsKey:!0},{id:"claudeOAuth",label:"Claude (OAuth)",needsKey:!1,needsOAuth:!0},{id:"openai",label:"OpenAI",needsKey:!0},{id:"google",label:"Google (Gemini)",needsKey:!0},{id:"ollama",label:"Ollama (Local)",needsKey:!1,needsEndpoint:!0},{id:"groq",label:"Groq",needsKey:!0},{id:"deepseek",label:"DeepSeek",needsKey:!0},{id:"cohere",label:"Cohere",needsKey:!0},{id:"xai",label:"xAI (Grok)",needsKey:!0},{id:"openaiCompatible",label:"OpenAI-Compatible",needsKey:!0,needsEndpoint:!0},{id:"openrouter",label:"OpenRouter",needsKey:!0},{id:"huggingface",label:"HuggingFace",needsKey:!0}];function Es(s){return s.startsWith("claude-opus-4-6")?"Claude Opus 4.6":s.startsWith("claude-sonnet-4-5")?"Claude Sonnet 4.5":s.startsWith("claude-haiku-4-5")?"Claude Haiku 4.5":s.startsWith("claude-opus-4")?"Claude Opus 4":s.startsWith("claude-sonnet-4")?"Claude Sonnet 4":s.startsWith("claude-3-5-haiku")?"Claude Haiku 3.5":s.startsWith("claude-3-5-sonnet")?"Claude Sonnet 3.5":s.startsWith("claude-3-opus")?"Claude Opus 3":s==="gpt-4o"?"GPT-4o":s==="gpt-4o-mini"?"GPT-4o Mini":s==="gpt-4-turbo"?"GPT-4 Turbo":s.startsWith("o1")||s.startsWith("o3")?s.toUpperCase():s.startsWith("gemini-")?s.replace("gemini-","Gemini "):s}function Gm(){const{data:s,refresh:r}=ut(()=>J.getModels(),[]),[u,o]=h.useState(null),[f,m]=h.useState(!1),[p,x]=h.useState(""),[y,g]=h.useState(""),[b,j]=h.useState(!1),[S,w]=h.useState(""),[A,D]=h.useState(!1),[O,E]=h.useState(!1),[M,k]=h.useState(""),[Z,K]=h.useState(""),[q,W]=h.useState(!1),[G,te]=h.useState(""),[ce,ie]=h.useState(""),[he,ee]=h.useState(""),[oe,ve]=h.useState(!1),H=(s==null?void 0:s.providers)??[],F=(s==null?void 0:s.routing)??{enabled:!1,primary:"",fallback:""},le=(s==null?void 0:s.cost)??{today:0,thisMonth:0,isOverBudget:!1,warningThresholdReached:!1};h.useEffect(()=>{F.primary&&k(F.primary),F.fallback&&K(F.fallback)},[F.primary,F.fallback]),h.useEffect(()=>{J.getClaudeOAuthStatus().then(X=>E(X.connected)).catch(X=>console.error("Failed to check OAuth status:",X))},[]);const I=new Set(H.filter(X=>X.available).map(X=>X.name)),de=X=>{const ge=H.find(qe=>qe.name===X);return ge!=null&&ge.models?Object.keys(ge.models):[]},C=[];for(const X of H){if(!X.available||!X.models)continue;const ge=Ki.find(qe=>qe.id===X.name);for(const qe of Object.keys(X.models))C.push({provider:X.name,providerLabel:(ge==null?void 0:ge.label)??X.displayName??X.name,model:qe})}const L=X=>{u===X?o(null):(o(X),te(""),ie(""),ee(""),g(""),x(""))},ne=async X=>{m(!0),g(""),x("");try{const ge=Ki.find(qe=>qe.id===X);await J.configureProvider(X,ge!=null&&ge.needsKey&&G||void 0,ge!=null&&ge.needsEndpoint&&ce||void 0),he&&await J.setProviderModel(X,he),x(`${(ge==null?void 0:ge.label)??X} configured successfully`),te(""),await r()}catch(ge){g(ge.message)}finally{m(!1)}},re=async()=>{j(!0),g(""),x("");try{const{authUrl:X}=await J.startClaudeOAuth();window.open(X,"_blank"),D(!0)}catch(X){g(X instanceof Error?X.message:"Failed to start OAuth")}finally{j(!1)}},xe=async()=>{if(S.trim()){m(!0),g(""),x("");try{await J.completeClaudeOAuth(S.trim()),x("Claude OAuth connected successfully"),D(!1),w(""),E(!0),await r()}catch(X){g(X instanceof Error?X.message:"Failed to complete OAuth")}finally{m(!1)}}},be=async()=>{m(!0),g(""),x("");try{await J.disconnectClaudeOAuth(),x("Claude OAuth disconnected"),E(!1),await r()}catch(X){g(X instanceof Error?X.message:"Failed to disconnect OAuth")}finally{m(!1)}},Ce=async()=>{W(!0),g(""),x("");try{await J.updateRouting(M,Z||void 0),x("Routing updated"),await r()}catch(X){g(X.message)}finally{W(!1)}},Pe=async X=>{if(!X)return;const[ge,...qe]=X.split("/"),$e=qe.join("/");ve(!0),g(""),x("");try{await J.setProviderModel(ge,$e),ge!==F.primary&&await J.updateRouting(ge,F.primary||void 0),x(`Switched to ${Es($e)}`),await r()}catch(nt){g(nt.message)}finally{ve(!1)}},P=H.filter(X=>X.available);return n.jsxs("div",{className:"page",children:[n.jsx("h2",{children:"Providers"}),C.length>0&&n.jsxs("div",{className:"settings-section",children:[n.jsx("h3",{children:"Active Model"}),n.jsx("p",{style:{color:"var(--text-secondary)",fontSize:"0.85rem",marginBottom:"0.75rem"},children:"Choose which AI model to use. This changes the default for all new messages."}),n.jsx("div",{className:"routing-config",children:n.jsxs("div",{className:"routing-field",style:{flex:2},children:[n.jsx("label",{children:"Model"}),n.jsxs("select",{onChange:X=>Pe(X.target.value),disabled:oe,defaultValue:"",children:[n.jsx("option",{value:"",disabled:!0,children:"Select a model..."}),P.map(X=>{const ge=de(X.name);if(ge.length===0)return null;const qe=Ki.find($e=>$e.id===X.name);return n.jsx("optgroup",{label:(qe==null?void 0:qe.label)??X.displayName??X.name,children:ge.map($e=>n.jsx("option",{value:`${X.name}/${$e}`,children:Es($e)},`${X.name}/${$e}`))},X.name)})]})]})}),p&&n.jsx("div",{className:"settings-success",children:p}),y&&n.jsx("div",{className:"error",children:y})]}),P.length>1&&n.jsxs("div",{className:"settings-section",children:[n.jsx("h3",{children:"Provider Routing"}),n.jsx("p",{style:{color:"var(--text-secondary)",fontSize:"0.85rem",marginBottom:"0.75rem"},children:"Set primary and fallback providers. Fallback is used when the primary is unavailable."}),n.jsxs("div",{className:"routing-config",children:[n.jsxs("div",{className:"routing-field",children:[n.jsx("label",{children:"Primary Provider"}),n.jsxs("select",{value:M,onChange:X=>k(X.target.value),children:[n.jsx("option",{value:"",children:"Select..."}),P.map(X=>n.jsx("option",{value:X.name,children:X.displayName||X.name},X.name))]})]}),n.jsxs("div",{className:"routing-field",children:[n.jsx("label",{children:"Fallback Provider"}),n.jsxs("select",{value:Z,onChange:X=>K(X.target.value),children:[n.jsx("option",{value:"",children:"None"}),P.filter(X=>X.name!==M).map(X=>n.jsx("option",{value:X.name,children:X.displayName||X.name},X.name))]})]}),n.jsx("button",{onClick:Ce,disabled:q||!M,children:q?"Saving...":"Save Routing"})]})]}),n.jsxs("div",{className:"settings-section",children:[n.jsx("h3",{children:"Usage"}),n.jsxs("div",{className:"cost-summary",children:[n.jsxs("div",{className:`cost-box${le.isOverBudget?" over-budget":""}`,children:[n.jsx("h4",{children:"Today"}),n.jsxs("div",{className:"cost-value",children:["$",le.today.toFixed(2)]})]}),n.jsxs("div",{className:`cost-box${le.isOverBudget?" over-budget":""}`,children:[n.jsx("h4",{children:"This Month"}),n.jsxs("div",{className:"cost-value",children:["$",le.thisMonth.toFixed(2)]})]}),n.jsxs("div",{className:"cost-box",children:[n.jsx("h4",{children:"Budget Status"}),n.jsx("div",{className:"cost-value",style:{fontSize:"0.95rem"},children:le.isOverBudget?"Over Budget":le.warningThresholdReached?"Warning":"OK"})]})]})]}),n.jsxs("div",{className:"settings-section",children:[n.jsx("h3",{children:"Manage Providers"}),n.jsx("p",{style:{color:"var(--text-secondary)",fontSize:"0.85rem",marginBottom:"0.75rem"},children:"Click a card to configure API keys and endpoints."}),n.jsx("div",{className:"provider-grid",children:Ki.map(X=>{const ge=H.find(_e=>_e.name===X.id),qe=I.has(X.id),nt=X.id==="claudeOAuth"?O:qe,Et=F.primary===X.id,pa=F.fallback===X.id,qa=u===X.id,xt=de(X.id);return n.jsxs("div",{className:`provider-card${nt?" configured":""}${qa?" expanded":""}`,onClick:()=>L(X.id),children:[n.jsxs("div",{className:"provider-card-header",children:[n.jsxs("h3",{children:[n.jsx("span",{className:`status-dot ${nt?"active":"inactive"}`}),nt&&(ge!=null&&ge.displayName)?ge.displayName:X.label]}),n.jsxs("div",{className:"provider-badges",children:[Et&&n.jsx("span",{className:"badge-pill badge-primary",children:"Primary"}),pa&&n.jsx("span",{className:"badge-pill badge-fallback",children:"Fallback"})]})]}),n.jsxs("div",{className:"provider-model",children:[nt?xt.length>0?xt.map(_e=>Es(_e)).join(", "):"Active":"Not configured",(ge==null?void 0:ge.credentialSource)==="claude-cli"&&n.jsx("span",{style:{marginLeft:"0.5rem",fontSize:"0.75rem",color:"var(--accent)"},children:"(Claude Code CLI)"}),(ge==null?void 0:ge.credentialSource)==="oauth"&&n.jsx("span",{style:{marginLeft:"0.5rem",fontSize:"0.75rem",color:"var(--accent)"},children:"(OAuth)"})]}),qa&&n.jsx("div",{className:"provider-expand",onClick:_e=>_e.stopPropagation(),children:X.needsOAuth?n.jsx(n.Fragment,{children:O?n.jsxs(n.Fragment,{children:[n.jsx("p",{style:{color:"var(--text-secondary)",fontSize:"0.85rem",marginBottom:"0.75rem"},children:"Connected via Claude OAuth. Your Claude Pro/Max subscription is being used."}),xt.length>0&&n.jsxs(n.Fragment,{children:[n.jsx("label",{children:"Default Model"}),n.jsxs("select",{value:he,onChange:_e=>ee(_e.target.value),children:[n.jsx("option",{value:"",children:"Keep current"}),xt.map(_e=>n.jsx("option",{value:_e,children:Es(_e)},_e))]})]}),n.jsx("div",{className:"provider-actions",children:n.jsx("button",{className:"btn-save",onClick:be,disabled:f,style:{background:"var(--error, #e74c3c)"},children:f?"Disconnecting...":"Disconnect"})})]}):A?n.jsxs(n.Fragment,{children:[n.jsx("p",{style:{color:"var(--text-secondary)",fontSize:"0.85rem",marginBottom:"0.75rem"},children:"Authorize in the browser tab that opened, then paste the code below."}),n.jsx("label",{children:"Authorization Code"}),n.jsx("input",{type:"text",value:S,onChange:_e=>w(_e.target.value),placeholder:"Paste the code from claude.ai",autoFocus:!0}),n.jsxs("div",{className:"provider-actions",children:[n.jsx("button",{className:"btn-save",onClick:xe,disabled:f||!S.trim(),children:f?"Connecting...":"Complete Connection"}),n.jsx("button",{onClick:()=>{D(!1),w("")},style:{marginLeft:"0.5rem"},children:"Cancel"})]})]}):n.jsxs(n.Fragment,{children:[n.jsx("p",{style:{color:"var(--text-secondary)",fontSize:"0.85rem",marginBottom:"0.75rem"},children:"Connect your Claude Pro or Max subscription. No API key needed."}),n.jsx("div",{className:"provider-actions",children:n.jsx("button",{className:"btn-save",onClick:re,disabled:b,children:b?"Opening...":"Connect with Claude"})})]})}):n.jsxs(n.Fragment,{children:[X.needsKey&&n.jsxs(n.Fragment,{children:[n.jsx("label",{children:"API Key"}),n.jsx("input",{type:"password",value:G,onChange:_e=>te(_e.target.value),placeholder:qe?"•••••••• (leave blank to keep)":"Enter API key"})]}),X.needsEndpoint&&n.jsxs(n.Fragment,{children:[n.jsx("label",{children:"Endpoint URL"}),n.jsx("input",{type:"text",value:ce,onChange:_e=>ie(_e.target.value),placeholder:X.id==="ollama"?"http://localhost:11434":"https://..."})]}),xt.length>0&&n.jsxs(n.Fragment,{children:[n.jsx("label",{children:"Default Model"}),n.jsxs("select",{value:he,onChange:_e=>ee(_e.target.value),children:[n.jsx("option",{value:"",children:"Keep current"}),xt.map(_e=>n.jsx("option",{value:_e,children:Es(_e)},_e))]})]}),n.jsx("div",{className:"provider-actions",children:n.jsx("button",{className:"btn-save",onClick:()=>ne(X.id),disabled:f||!G&&X.needsKey&&!qe&&!X.needsEndpoint,children:f?"Saving...":"Save"})})]})})]},X.id)})})]})]})}const em=[{type:"discord",label:"Discord",fields:[{key:"botToken",label:"Bot Token",secret:!0}]},{type:"telegram",label:"Telegram",fields:[{key:"botToken",label:"Bot Token",secret:!0}]},{type:"slack",label:"Slack",fields:[{key:"botToken",label:"Bot Token",secret:!0},{key:"appToken",label:"App Token",secret:!0}]},{type:"twilio",label:"Twilio",fields:[{key:"accountSid",label:"Account SID",secret:!1},{key:"authToken",label:"Auth Token",secret:!0}]},{type:"matrix",label:"Matrix",fields:[{key:"accessToken",label:"Access Token",secret:!0}]},{type:"email",label:"Email",fields:[{key:"imapHost",label:"IMAP Host",secret:!1},{key:"imapPort",label:"IMAP Port",secret:!1},{key:"smtpHost",label:"SMTP Host",secret:!1},{key:"smtpPort",label:"SMTP Port",secret:!1},{key:"email",label:"Email Address",secret:!1},{key:"password",label:"Password (App Password for Gmail)",secret:!0}]}];function $m(){var D,O;const{data:s}=ut(()=>J.getChannels(),[]),r=((D=s==null?void 0:s.data)==null?void 0:D.connected)??[],u=((O=s==null?void 0:s.data)==null?void 0:O.configured)??[],[o,f]=h.useState({}),[m,p]=h.useState(!1),[x,y]=h.useState(""),[g,b]=h.useState(""),j=E=>{if(o[E])return o[E];const M=u.find(k=>k.type===E);return{enabled:(M==null?void 0:M.enabled)??!1,credentials:{}}},S=E=>{const M=j(E);f(k=>({...k,[E]:{...M,enabled:!M.enabled}}))},w=(E,M,k)=>{const Z=j(E);f(K=>({...K,[E]:{...Z,credentials:{...Z.credentials,[M]:k}}}))},A=async()=>{p(!0),b(""),y("");try{const E=em.filter(M=>j(M.type).enabled||Object.values(j(M.type).credentials).some(k=>k)).map(M=>{const k=j(M.type),Z={};for(const[K,q]of Object.entries(k.credentials))q&&(Z[K]=q);return{type:M.type,enabled:k.enabled,...Object.keys(Z).length>0?{credentials:Z}:{}}});await J.updateChannels(E),y("Channels updated successfully")}catch(E){b(E.message)}finally{p(!1)}};return n.jsxs("div",{className:"page",children:[n.jsx("h2",{children:"Channels"}),n.jsx("div",{className:"channel-grid",children:em.map(E=>{const M=j(E.type),k=r.includes(E.type);return n.jsxs("div",{className:"channel-card",children:[n.jsxs("div",{className:"channel-card-header",children:[n.jsx("h3",{children:E.label}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[k?n.jsx("span",{className:"badge badge-green",children:"Connected"}):M.enabled&&n.jsx("span",{className:"badge badge-yellow",children:"Configured"}),n.jsx("div",{className:`toggle${M.enabled?" active":""}`,onClick:()=>S(E.type)})]})]}),M.enabled&&n.jsx("div",{className:"channel-card-fields",children:E.fields.map(Z=>n.jsxs("div",{children:[n.jsx("label",{children:Z.label}),n.jsx("input",{type:Z.secret?"password":"text",value:M.credentials[Z.key]??"",onChange:K=>w(E.type,Z.key,K.target.value),placeholder:k?"(configured)":`Enter ${Z.label.toLowerCase()}`})]},Z.key))})]},E.type)})}),n.jsx("button",{className:"settings-btn",onClick:A,disabled:m,children:m?"Saving...":"Save Changes"}),x&&n.jsx("div",{className:"settings-success",children:x}),g&&n.jsx("div",{className:"error",children:g})]})}function eb(s){if(s.length===0)return{label:"",color:"transparent",width:"0%"};if(s.length<8)return{label:"Too short",color:"var(--danger)",width:"25%"};const r=/[A-Z]/.test(s),u=/[a-z]/.test(s),o=/[0-9]/.test(s),f=/[^A-Za-z0-9]/.test(s),m=[r,u,o,f].filter(Boolean).length;return s.length>=12&&m>=3?{label:"Strong",color:"var(--success)",width:"100%"}:{label:"Fair",color:"var(--warning)",width:"60%"}}function Pi({password:s}){const r=eb(s);return s?n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"password-strength",children:n.jsx("div",{className:"password-strength-bar",style:{width:r.width,background:r.color}})}),n.jsx("div",{className:"password-strength-label",style:{color:r.color},children:r.label})]}):null}function Xm(){const[s,r]=h.useState(""),[u,o]=h.useState(""),[f,m]=h.useState(""),[p,x]=h.useState(!1),[y,g]=h.useState(""),[b,j]=h.useState(""),[S,w]=h.useState(""),[A,D]=h.useState(""),[O,E]=h.useState(!1),[M,k]=h.useState(""),[Z,K]=h.useState(""),[q,W]=h.useState(null),[G,te]=h.useState(""),[ce,ie]=h.useState(""),[he,ee]=h.useState(!1),[oe,ve]=h.useState(""),[H,F]=h.useState("");h.useEffect(()=>{J.getSealStatus().then(W).catch(()=>W({sealed:!1,pinRequired:!1}))},[]);const le=async L=>{if(L.preventDefault(),j(""),g(""),u!==f){j("New passwords do not match");return}if(u.length<8){j("Password must be at least 8 characters");return}x(!0);try{await J.changeDashboardPassword(s,u),g("Mission Control password changed"),r(""),o(""),m("")}catch(ne){j(ne.message)}finally{x(!1)}},I=async L=>{if(L.preventDefault(),K(""),k(""),S!==A){K("New passwords do not match");return}if(S.length<8){K("Password must be at least 8 characters");return}E(!0);try{await J.changeVaultPassword(S),k("Vault password changed"),w(""),D("")}catch(ne){K(ne.message)}finally{E(!1)}},de=async L=>{if(L.preventDefault(),F(""),ve(""),!G){F("Vault password is required");return}if(ce&&ce.length<4){F("PIN must be at least 4 characters");return}ee(!0);try{await J.enableSeal(G,ce||void 0),ve("Auto-unseal enabled"),te(""),ie(""),W({sealed:!0,pinRequired:ce.length>0})}catch(ne){F(ne.message)}finally{ee(!1)}},C=async()=>{F(""),ve(""),ee(!0);try{await J.disableSeal(),ve("Auto-unseal disabled"),W({sealed:!1,pinRequired:!1})}catch(L){F(L.message)}finally{ee(!1)}};return n.jsxs("div",{className:"page",children:[n.jsx("h2",{children:"Security"}),n.jsxs("div",{className:"settings-section",children:[n.jsx("h3",{children:"Change Mission Control Password"}),n.jsxs("form",{className:"settings-form",onSubmit:le,children:[n.jsx("label",{children:"Current Password"}),n.jsx("input",{type:"password",value:s,onChange:L=>r(L.target.value)}),n.jsx("label",{children:"New Password"}),n.jsx("input",{type:"password",value:u,onChange:L=>o(L.target.value)}),n.jsx(Pi,{password:u}),n.jsx("label",{children:"Confirm New Password"}),n.jsx("input",{type:"password",value:f,onChange:L=>m(L.target.value)}),n.jsx("button",{className:"settings-btn",type:"submit",disabled:p||!s||!u,children:p?"Saving...":"Change Password"}),y&&n.jsx("div",{className:"settings-success",children:y}),b&&n.jsx("div",{className:"error",children:b})]})]}),n.jsxs("div",{className:"settings-section",children:[n.jsx("h3",{children:"Change Vault Password"}),n.jsxs("form",{className:"settings-form",onSubmit:I,children:[n.jsx("label",{children:"New Vault Password"}),n.jsx("input",{type:"password",value:S,onChange:L=>w(L.target.value)}),n.jsx(Pi,{password:S}),n.jsx("label",{children:"Confirm New Password"}),n.jsx("input",{type:"password",value:A,onChange:L=>D(L.target.value)}),n.jsx("button",{className:"settings-btn",type:"submit",disabled:O||!S,children:O?"Saving...":"Change Vault Password"}),M&&n.jsx("div",{className:"settings-success",children:M}),Z&&n.jsx("div",{className:"error",children:Z})]})]}),n.jsxs("div",{className:"settings-section",children:[n.jsx("h3",{children:"Auto-Unseal"}),n.jsx("p",{className:"settings-info",children:"When enabled, the vault automatically unlocks on restart using this machine's identity. No plaintext password is stored on disk. Optionally add a PIN for extra security."}),q===null?n.jsx("p",{children:"Loading..."}):q.sealed?n.jsxs("div",{children:[n.jsxs("p",{children:["Status: ",n.jsx("strong",{children:"Enabled"}),q.pinRequired?" (PIN required)":" (no PIN)"]}),n.jsx("button",{className:"settings-btn",onClick:C,disabled:he,children:he?"Disabling...":"Disable Auto-Unseal"})]}):n.jsxs("form",{className:"settings-form",onSubmit:de,children:[n.jsx("label",{children:"Vault Password"}),n.jsx("input",{type:"password",value:G,onChange:L=>te(L.target.value),placeholder:"Enter vault password to verify"}),n.jsx("label",{children:"PIN (optional, 4+ characters)"}),n.jsx("input",{type:"password",value:ce,onChange:L=>ie(L.target.value),placeholder:"Leave empty for machine-only binding"}),n.jsx("button",{className:"settings-btn",type:"submit",disabled:he||!G,children:he?"Enabling...":"Enable Auto-Unseal"})]}),oe&&n.jsx("div",{className:"settings-success",children:oe}),H&&n.jsx("div",{className:"error",children:H})]})]})}function Vm({selected:s,onSelect:r}){const{theme:u,setTheme:o}=qu(),f=s??u,m=p=>{o(p),r==null||r(p)};return n.jsx("div",{className:"theme-grid",children:Fy.map(p=>n.jsxs("div",{className:`theme-card${f===p.id?" selected":""}`,onClick:()=>m(p.id),children:[n.jsx("div",{className:"theme-swatches",children:p.colors.map((x,y)=>n.jsx("div",{className:"theme-swatch",style:{background:x}},y))}),n.jsxs("div",{className:"theme-info",children:[n.jsx("h3",{children:p.name}),n.jsx("span",{className:`theme-mode-badge ${p.mode}`,children:p.mode})]}),n.jsx("p",{className:"theme-description",children:p.description})]},p.id))})}function Qm(){const{theme:s,setTheme:r}=qu(),[u,o]=h.useState(!1),[f,m]=h.useState(""),[p,x]=h.useState(""),[y,g]=h.useState(null);h.useEffect(()=>{J.getAppearance().then(S=>{const w=S.data.theme;g(w)}).catch(()=>{g(s)})},[]);const b=y!==null&&s!==y,j=async()=>{o(!0),x(""),m("");try{await J.updateAppearance(s),g(s),m("Theme updated successfully")}catch(S){x(S instanceof Error?S.message:"Failed to save theme")}finally{o(!1)}};return n.jsxs("div",{className:"page",children:[n.jsx("h2",{children:"Appearance"}),n.jsx("p",{style:{color:"var(--text-secondary)",marginBottom:"1.5rem"},children:"Choose your theme. Changes preview instantly."}),n.jsx(Vm,{}),b&&n.jsx("button",{className:"btn-primary",onClick:j,disabled:u,style:{marginTop:"1.5rem"},children:u?"Saving...":"Save Theme"}),f&&n.jsx("p",{className:"success",style:{marginTop:"0.75rem"},children:f}),p&&n.jsx("p",{className:"error",style:{marginTop:"0.75rem"},children:p})]})}const tm=[{id:"google-workspace",name:"Google Workspace",description:"Gmail, Google Calendar, and Google Drive",scopes:"Email summaries, calendar awareness, drive file access",setupUrl:"https://console.cloud.google.com/apis/credentials",instructions:["Go to Google Cloud Console > APIs & Services > Credentials","Create an OAuth 2.0 Client ID (Web application type)","Add authorized redirect URI: {callbackUrl}","Enable Gmail API, Google Calendar API, and Google Drive API"]}];function Km(){const[s,r]=h.useState({}),[u,o]=h.useState(""),[f,m]=h.useState(""),[p,x]=h.useState(""),[y,g]=h.useState(""),[b,j]=h.useState(null),S=`${window.location.origin}/api/v1/dashboard/connectors/google-workspace/callback`;h.useEffect(()=>{w()},[]);async function w(){for(const E of tm){r(M=>({...M,[E.id]:{...M[E.id],loading:!0,hasCredentials:!1,connected:!1}}));try{const M=await J.getConnectorStatus(E.id);r(k=>({...k,[E.id]:{hasCredentials:M.data.hasCredentials,connected:M.data.connected,expiresAt:M.data.expiresAt,loading:!1}}))}catch{r(M=>({...M,[E.id]:{hasCredentials:!1,connected:!1,loading:!1}}))}}}async function A(E){if(!u||!f){x("Both Client ID and Client Secret are required");return}x("");try{await J.saveConnectorCredentials(E,u,f),g('Credentials saved. Click "Connect" to authorize.'),o(""),m(""),j(null),w()}catch(M){x(M instanceof Error?M.message:"Failed to save credentials")}}function D(E){window.location.href=`/api/v1/dashboard/connectors/${E}/auth`}async function O(E){try{await J.disconnectConnector(E),g("Disconnected successfully"),w()}catch(M){x(M instanceof Error?M.message:"Failed to disconnect")}}return n.jsxs("div",{className:"page",children:[n.jsx("h2",{children:"Connections"}),n.jsxs("div",{className:"settings-form",children:[y&&n.jsx("div",{className:"settings-success",onClick:()=>g(""),children:y}),p&&n.jsx("div",{className:"error",children:p}),tm.map(E=>{const M=s[E.id],k=M==null?void 0:M.connected,Z=M==null?void 0:M.hasCredentials;return n.jsxs("div",{className:"settings-section",children:[n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[n.jsxs("div",{children:[n.jsx("h3",{children:E.name}),n.jsx("span",{style:{fontSize:"0.85rem",color:"var(--text-secondary)"},children:E.description})]}),n.jsx("span",{className:k?"badge badge-green":"badge badge-gray",children:M!=null&&M.loading?"Checking...":k?"Connected":"Not connected"})]}),n.jsxs("p",{style:{fontSize:"0.8rem",color:"var(--text-secondary)",margin:"0.5rem 0"},children:["Enables: ",E.scopes]}),k?n.jsxs("div",{style:{display:"flex",gap:"0.5rem",marginTop:"1rem",alignItems:"center"},children:[(M==null?void 0:M.expiresAt)&&n.jsxs("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)"},children:["Token expires: ",new Date(M.expiresAt).toLocaleDateString()]}),n.jsx("button",{type:"button",className:"btn-sm",onClick:()=>D(E.id),children:"Reconnect"}),n.jsx("button",{type:"button",className:"btn-sm btn-danger",onClick:()=>O(E.id),children:"Disconnect"})]}):Z?n.jsxs("div",{style:{display:"flex",gap:"0.5rem",marginTop:"1rem"},children:[n.jsx("button",{type:"button",className:"settings-btn",onClick:()=>D(E.id),children:"Connect"}),n.jsx("button",{type:"button",className:"btn-sm",onClick:()=>j(E.id),children:"Update Credentials"})]}):n.jsx("div",{style:{marginTop:"1rem"},children:b!==E.id?n.jsx("button",{type:"button",className:"settings-btn",onClick:()=>j(E.id),children:"Set Up"}):null}),b===E.id&&n.jsxs("div",{style:{marginTop:"1rem",padding:"1rem",background:"var(--bg-hover)",borderRadius:"var(--radius)",border:"1px solid var(--border)"},children:[n.jsx("h4",{style:{margin:"0 0 0.75rem",fontFamily:"var(--font-display)",fontWeight:600},children:"Setup Instructions"}),n.jsx("ol",{style:{fontSize:"0.8rem",color:"var(--text-secondary)",paddingLeft:"1.25rem",margin:"0 0 1rem"},children:E.instructions.map((K,q)=>n.jsx("li",{style:{marginBottom:"0.35rem"},children:K.replace("{callbackUrl}",S)},q))}),n.jsxs("div",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",marginBottom:"1rem",wordBreak:"break-all"},children:["Redirect URI: ",n.jsx("code",{style:{fontFamily:"var(--font-mono)",background:"var(--accent-subtle)",color:"var(--accent)",padding:"0.15rem 0.35rem",borderRadius:"4px",fontSize:"0.82em"},children:S})]}),n.jsx("label",{children:"Client ID"}),n.jsx("input",{type:"text",value:u,onChange:K=>o(K.target.value),placeholder:"your-client-id.apps.googleusercontent.com"}),n.jsx("label",{children:"Client Secret"}),n.jsx("input",{type:"password",value:f,onChange:K=>m(K.target.value),placeholder:"GOCSPX-..."}),n.jsxs("div",{style:{display:"flex",gap:"0.5rem",marginTop:"0.5rem"},children:[n.jsx("button",{type:"button",className:"settings-btn",onClick:()=>A(E.id),children:"Save & Connect"}),n.jsx("button",{type:"button",className:"btn-sm",onClick:()=>{j(null),x("")},children:"Cancel"})]})]})]},E.id)})]})]})}const tb=["Calendar","Email","Tasks","Patterns"],Ln={morningBriefing:{enabled:!0,time:"08:00",categories:["Calendar","Email"]},eveningSummary:{enabled:!1,time:"18:00"},deliveryChannel:"all"};function Zm(){const{data:s,loading:r}=ut(()=>J.getAmbientConfig(),[]),[u,o]=h.useState(Ln),[f,m]=h.useState(!1),[p,x]=h.useState(""),[y,g]=h.useState("");h.useEffect(()=>{var S,w,A,D,O;s!=null&&s.data&&o({morningBriefing:{enabled:((S=s.data.morningBriefing)==null?void 0:S.enabled)??Ln.morningBriefing.enabled,time:((w=s.data.morningBriefing)==null?void 0:w.time)??Ln.morningBriefing.time,categories:((A=s.data.morningBriefing)==null?void 0:A.categories)??Ln.morningBriefing.categories},eveningSummary:{enabled:((D=s.data.eveningSummary)==null?void 0:D.enabled)??Ln.eveningSummary.enabled,time:((O=s.data.eveningSummary)==null?void 0:O.time)??Ln.eveningSummary.time},deliveryChannel:s.data.deliveryChannel??Ln.deliveryChannel})},[s]);const b=S=>{o(w=>{const A=w.morningBriefing.categories,D=A.includes(S)?A.filter(O=>O!==S):[...A,S];return{...w,morningBriefing:{...w.morningBriefing,categories:D}}})},j=async()=>{m(!0),g(""),x("");try{await J.updateAmbientConfig(u),x("Ambient settings saved successfully")}catch(S){g(S instanceof Error?S.message:"Failed to save settings")}finally{m(!1)}};return r?null:n.jsxs("div",{className:"page",children:[n.jsx("h2",{children:"Ambient Intelligence"}),n.jsxs("div",{className:"settings-form",children:[n.jsxs("div",{className:"settings-section",children:[n.jsx("h3",{children:"Morning Briefing"}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",marginBottom:"1rem"},children:[n.jsx("div",{className:`toggle${u.morningBriefing.enabled?" active":""}`,onClick:()=>o(S=>({...S,morningBriefing:{...S.morningBriefing,enabled:!S.morningBriefing.enabled}}))}),n.jsx("span",{style:{fontSize:"0.85rem",color:"var(--text-secondary)"},children:u.morningBriefing.enabled?"Enabled":"Disabled"})]}),u.morningBriefing.enabled&&n.jsxs(n.Fragment,{children:[n.jsx("label",{children:"Delivery Time"}),n.jsx("input",{type:"time",value:u.morningBriefing.time,onChange:S=>o(w=>({...w,morningBriefing:{...w.morningBriefing,time:S.target.value}}))}),n.jsx("label",{children:"Categories"}),n.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:"0.5rem",marginBottom:"1rem"},children:tb.map(S=>n.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.4rem",cursor:"pointer",fontSize:"0.85rem"},children:[n.jsx("input",{type:"checkbox",checked:u.morningBriefing.categories.includes(S),onChange:()=>b(S),style:{width:"auto",marginBottom:0}}),S]},S))})]})]}),n.jsxs("div",{className:"settings-section",children:[n.jsx("h3",{children:"Evening Summary"}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",marginBottom:"1rem"},children:[n.jsx("div",{className:`toggle${u.eveningSummary.enabled?" active":""}`,onClick:()=>o(S=>({...S,eveningSummary:{...S.eveningSummary,enabled:!S.eveningSummary.enabled}}))}),n.jsx("span",{style:{fontSize:"0.85rem",color:"var(--text-secondary)"},children:u.eveningSummary.enabled?"Enabled":"Disabled"})]}),u.eveningSummary.enabled&&n.jsxs(n.Fragment,{children:[n.jsx("label",{children:"Delivery Time"}),n.jsx("input",{type:"time",value:u.eveningSummary.time,onChange:S=>o(w=>({...w,eveningSummary:{...w.eveningSummary,time:S.target.value}}))})]})]}),n.jsxs("div",{className:"settings-section",children:[n.jsx("label",{children:"Delivery Channel"}),n.jsxs("select",{value:u.deliveryChannel,onChange:S=>o(w=>({...w,deliveryChannel:S.target.value})),children:[n.jsx("option",{value:"all",children:"All connected channels"}),n.jsx("option",{value:"webchat",children:"Webchat only"}),n.jsx("option",{value:"discord",children:"Discord"}),n.jsx("option",{value:"telegram",children:"Telegram"}),n.jsx("option",{value:"slack",children:"Slack"}),n.jsx("option",{value:"email",children:"Email"})]})]}),n.jsx("button",{className:"settings-btn",onClick:j,disabled:f,children:f?"Saving...":"Save Settings"}),p&&n.jsx("div",{className:"settings-success",children:p}),y&&n.jsx("div",{className:"error",children:y})]})]})}function ab({loadPreferences:s,updatePreference:r,clearData:u,exportData:o,getEngine:f,setEngine:m}){const[p,x]=h.useState(null),[y,g]=h.useState(!0),[b,j]=h.useState(!1),[S,w]=h.useState(!1),[A,D]=h.useState(""),[O,E]=h.useState(!1);h.useEffect(()=>{s().then(te=>{x(te),g(!1)}).catch(()=>g(!1)),f&&f().then(te=>E(te==="the-architect")).catch(()=>{})},[s,f]);const M=h.useCallback(async()=>{if(!m)return;j(!0);const te=O?"standard":"the-architect";try{await m(te),E(!O),D(te==="the-architect"?"Architect engine enabled":"Architect engine disabled"),setTimeout(()=>D(""),3e3)}finally{j(!1)}},[O,m]),k=h.useCallback(async(te,ce)=>{if(p){j(!0);try{await r(te,ce),x({...p,[te]:ce})}finally{j(!1)}}},[p,r]),Z=h.useCallback(async te=>{if(!p)return;j(!0);const ce=te==="auto"?null:te;try{await r("defaultContext",ce),x({...p,defaultContext:ce})}finally{j(!1)}},[p,r]),K=h.useCallback(async()=>{j(!0);try{await u(),x(await s()),w(!1),D("Learning data cleared"),setTimeout(()=>D(""),3e3)}finally{j(!1)}},[u,s]),q=h.useCallback(async()=>{try{const te=await o(),ce=new Blob([te],{type:"application/json"}),ie=URL.createObjectURL(ce),he=document.createElement("a");he.href=ie,he.download=`architect-data-${new Date().toISOString().slice(0,10)}.json`,he.click(),URL.revokeObjectURL(ie),D("Data exported"),setTimeout(()=>D(""),3e3)}catch{D("Export failed"),setTimeout(()=>D(""),3e3)}},[o]);if(y)return null;if(!p)return n.jsx("div",{className:"error",children:"Failed to load preferences"});const W=p.totalInteractions,G=Object.entries(p.contextUsageHistory).filter(([,te])=>te>0).sort(([,te],[,ce])=>ce-te);return n.jsxs("div",{className:"settings-form",children:[A&&n.jsx("div",{className:"settings-success",role:"status",children:A}),m&&n.jsxs("div",{className:"settings-section",children:[n.jsx("h3",{children:"Engine"}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx("div",{className:`toggle${O?" active":""}`,onClick:()=>!b&&M(),style:b?{opacity:.5,pointerEvents:"none"}:void 0}),n.jsx("span",{style:{fontSize:"0.85rem",color:"var(--text-primary)"},children:O?"Architect engine enabled (global default)":"Architect engine disabled"})]}),n.jsx("p",{style:{fontSize:"0.8rem",color:"var(--text-secondary)",marginTop:"0.5rem"},children:"Controls the default personality for new chats. Individual chats can override this."})]}),n.jsxs("div",{className:"settings-section",children:[n.jsx("h3",{children:"Display"}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",marginBottom:"0.75rem"},children:[n.jsx("div",{className:`toggle${p.showContextIndicator?" active":""}`,onClick:()=>!b&&k("showContextIndicator",!p.showContextIndicator),style:b?{opacity:.5,pointerEvents:"none"}:void 0}),n.jsx("span",{style:{fontSize:"0.85rem",color:"var(--text-primary)"},children:"Show context indicator"})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",marginBottom:"0.75rem"},children:[n.jsx("div",{className:`toggle${p.showSourcesButton?" active":""}`,onClick:()=>!b&&k("showSourcesButton",!p.showSourcesButton),style:b?{opacity:.5,pointerEvents:"none"}:void 0}),n.jsx("span",{style:{fontSize:"0.85rem",color:"var(--text-primary)"},children:"Show sources button"})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx("div",{className:`toggle${p.autoDetectContext?" active":""}`,onClick:()=>!b&&k("autoDetectContext",!p.autoDetectContext),style:b?{opacity:.5,pointerEvents:"none"}:void 0}),n.jsx("span",{style:{fontSize:"0.85rem",color:"var(--text-primary)"},children:"Auto-detect context"})]})]}),n.jsxs("div",{className:"settings-section",children:[n.jsx("h3",{children:"Default Context"}),n.jsx("label",{children:"Context domain"}),n.jsxs("select",{value:p.defaultContext??"auto",onChange:te=>Z(te.target.value),disabled:b,children:[n.jsx("option",{value:"auto",children:"Auto (detect from message)"}),Nl.map(te=>n.jsxs("option",{value:te,children:[_t[te].icon," ",_t[te].label]},te))]})]}),n.jsxs("div",{className:"settings-section",children:[n.jsx("h3",{children:"Detection Stats"}),n.jsx("div",{className:"status-grid",style:{marginBottom:"1rem"},children:n.jsxs("div",{className:"status-card",children:[n.jsx("h3",{children:"Total"}),n.jsx("div",{className:"value",children:W}),n.jsx("div",{className:"sub",children:"interactions"})]})}),G.length>0&&n.jsx("div",{className:"domain-stats-list",children:G.map(([te,ce])=>{var oe,ve,H;const ie=W>0?Math.round(ce/W*100):0,he=((oe=G[0])==null?void 0:oe[1])??1,ee=Math.max(4,Math.round(ce/he*100));return n.jsxs("div",{className:"domain-stat-row",children:[n.jsxs("span",{className:"domain-stat-label",children:[(ve=_t[te])==null?void 0:ve.icon," ",((H=_t[te])==null?void 0:H.label)??te]}),n.jsx("span",{className:"domain-stat-bar-track",children:n.jsx("span",{className:"domain-stat-bar-fill",style:{width:`${ee}%`}})}),n.jsx("span",{className:"domain-stat-count",children:ce}),n.jsxs("span",{className:"domain-stat-pct",children:[ie,"%"]})]},te)})}),G.length===0&&n.jsx("p",{style:{fontSize:"0.85rem",color:"var(--text-secondary)"},children:"No interactions recorded yet. Context stats will appear here as you use The Architect."})]}),n.jsxs("div",{className:"settings-section",style:{borderBottom:"none"},children:[n.jsx("h3",{children:"Data Management"}),n.jsxs("div",{style:{display:"flex",gap:"0.5rem",flexWrap:"wrap",alignItems:"center"},children:[S?n.jsxs(n.Fragment,{children:[n.jsx("span",{style:{fontSize:"0.85rem",color:"var(--danger)",marginRight:"0.25rem"},children:"Clear all learning data? This cannot be undone."}),n.jsx("button",{className:"btn-sm btn-danger",onClick:K,disabled:b,children:"Confirm"}),n.jsx("button",{className:"btn-sm",onClick:()=>w(!1),disabled:b,children:"Cancel"})]}):n.jsx("button",{className:"btn-sm btn-danger",onClick:()=>w(!0),disabled:b,children:"Clear learning data"}),n.jsx("button",{className:"btn-sm",onClick:q,disabled:b,children:"Export data"})]})]})]})}function Jm(){return n.jsxs("div",{className:"page",children:[n.jsx("h2",{children:"The Architect"}),n.jsx(ab,{loadPreferences:async()=>(await J.getArchitectPreferences()).data,updatePreference:async(s,r)=>{await J.updateArchitectPreference(s,r)},clearData:async()=>{await J.clearArchitectData()},exportData:async()=>(await J.exportArchitectData()).data,getEngine:async()=>(await J.getPersonalityEngine()).data.engine,setEngine:async s=>{await J.setPersonalityEngine(s)}})]})}function Zi(s){return new Date(s).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}function nb(s){return new Date(s).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function lb({trend:s}){return s==="improving"?n.jsx("span",{className:"up-trend-arrow",children:"▲"}):s==="declining"?n.jsx("span",{className:"up-trend-decline",children:"▼"}):n.jsx("span",{className:"up-trend-flat",children:"▬"})}function Wm(){const[s,r]=h.useState(null),[u,o]=h.useState(!0),[f,m]=h.useState(null);function p(){o(!0),m(null),J.getUserModel().then(y=>{r(y),o(!1)}).catch(y=>{const g=y instanceof Error?y.message:String(y);g.includes("not available")||g.includes("404")?m("Not enough data yet. Keep chatting and check back later!"):m(g),o(!1)})}if(h.useEffect(()=>{p()},[]),u)return n.jsx("div",{className:"up-page",children:n.jsx("div",{className:"up-loading",children:"Loading user profile..."})});if(f)return n.jsxs("div",{className:"up-page",children:[n.jsx("div",{className:"up-header",children:n.jsx("h2",{className:"up-title",children:"What do you know about me?"})}),n.jsx("div",{className:"up-empty",children:f})]});if(!s)return null;const x=Date.now();return n.jsxs("div",{className:"up-page",children:[n.jsxs("div",{className:"up-header",children:[n.jsx("h2",{className:"up-title",children:"What do you know about me?"}),n.jsxs("div",{className:"up-header-right",children:[n.jsxs("span",{className:"up-synthesized",children:["Synthesized ",nb(s.synthesizedAt)]}),n.jsx("button",{className:"up-refresh-btn",onClick:p,children:"Refresh"})]})]}),s.narrative&&n.jsx("section",{className:"up-section",children:n.jsx("p",{className:"up-narrative",children:s.narrative})}),s.topDomains&&s.topDomains.length>0&&n.jsxs("section",{className:"up-section",children:[n.jsx("h3",{className:"up-section-title",children:"Domain Expertise"}),n.jsx("div",{className:"up-domain-grid",children:s.topDomains.map(y=>n.jsxs("div",{className:"up-domain-card",children:[n.jsx("div",{className:"up-domain-name",children:y.domain}),n.jsx("div",{className:"up-domain-bar-track",children:n.jsx("div",{className:"up-domain-bar-fill",style:{width:`${Math.round(y.share*100)}%`}})}),n.jsxs("div",{className:"up-domain-stats",children:[n.jsxs("span",{className:"up-domain-share",children:[Math.round(y.share*100),"%"]}),y.satisfactionRate!==null&&n.jsxs("span",{className:"up-domain-satisfaction",children:[Math.round(y.satisfactionRate*100),"% satisfied"]})]})]},y.domain))})]}),s.communicationStyle&&n.jsxs("section",{className:"up-section",children:[n.jsx("h3",{className:"up-section-title",children:"Communication Style"}),n.jsxs("div",{className:"up-comm-labels",children:[n.jsx("span",{className:"up-comm-badge",children:s.communicationStyle.verbosityLabel}),n.jsx("span",{className:"up-comm-badge",children:s.communicationStyle.toneLabel})]}),n.jsx("div",{className:"up-comm-bars",children:[{label:"Verbosity",value:s.communicationStyle.verbosityPreference},{label:"Warmth",value:s.communicationStyle.warmthPreference},{label:"Humor",value:s.communicationStyle.humorPreference}].map(y=>n.jsxs("div",{className:"up-comm-row",children:[n.jsx("span",{className:"up-comm-label",children:y.label}),n.jsx("div",{className:"up-comm-track",children:n.jsx("div",{className:"up-comm-fill",style:{width:`${Math.round(Math.min(1,Math.max(0,y.value))*100)}%`}})}),n.jsx("span",{className:"up-comm-value",children:y.value.toFixed(2)})]},y.label))})]}),s.satisfaction&&n.jsxs("section",{className:"up-section",children:[n.jsx("h3",{className:"up-section-title",children:"Satisfaction"}),n.jsxs("div",{className:"up-satisfaction-header",children:[n.jsx(lb,{trend:s.satisfaction.overallTrend}),n.jsx("span",{className:"up-satisfaction-trend",children:s.satisfaction.overallTrend}),n.jsxs("span",{className:"up-satisfaction-count",children:[s.satisfaction.totalFeedback," feedback items"]})]}),s.satisfaction.strongDomains.length>0&&n.jsxs("div",{className:"up-satisfaction-group",children:[n.jsx("span",{className:"up-satisfaction-label",children:"Strong:"}),s.satisfaction.strongDomains.map(y=>n.jsx("span",{className:"up-tag up-tag-strong",children:y},y))]}),s.satisfaction.weakDomains.length>0&&n.jsxs("div",{className:"up-satisfaction-group",children:[n.jsx("span",{className:"up-satisfaction-label",children:"Needs work:"}),s.satisfaction.weakDomains.map(y=>n.jsx("span",{className:"up-tag up-tag-weak",children:y},y))]})]}),s.activeDecisions&&s.activeDecisions.length>0&&n.jsxs("section",{className:"up-section",children:[n.jsx("h3",{className:"up-section-title",children:"Active Decisions"}),n.jsx("div",{className:"up-decision-list",children:s.activeDecisions.map(y=>n.jsxs("div",{className:"up-decision-card",children:[n.jsx("div",{className:"up-decision-summary",children:y.summary}),n.jsxs("div",{className:"up-decision-meta",children:[n.jsx("span",{className:"up-decision-date",children:Zi(y.createdAt)}),y.tags.map(g=>n.jsx("span",{className:"up-tag",children:g},g))]})]},y.id))})]}),s.dueFollowUps&&s.dueFollowUps.length>0&&n.jsxs("section",{className:"up-section",children:[n.jsx("h3",{className:"up-section-title",children:"Due Follow-ups"}),n.jsx("div",{className:"up-decision-list",children:s.dueFollowUps.map(y=>{const g=y.followUpDate&&y.followUpDate<x;return n.jsxs("div",{className:`up-decision-card ${g?"up-overdue":""}`,children:[n.jsxs("div",{className:"up-decision-summary",children:[g&&n.jsx("span",{className:"up-overdue-badge",children:"Overdue"}),y.summary]}),n.jsxs("div",{className:"up-decision-meta",children:[y.followUpDate&&n.jsxs("span",{className:"up-decision-date",children:["Due ",Zi(y.followUpDate)]}),y.tags.map(b=>n.jsx("span",{className:"up-tag",children:b},b))]})]},y.id)})})]}),s.correctionSummary&&s.correctionSummary.totalCorrections>0&&n.jsxs("section",{className:"up-section",children:[n.jsx("h3",{className:"up-section-title",children:"Correction Patterns"}),n.jsxs("div",{className:"up-corrections-total",children:[s.correctionSummary.totalCorrections," total corrections"]}),s.correctionSummary.topPatterns.length>0&&n.jsx("div",{className:"up-corrections-list",children:s.correctionSummary.topPatterns.map((y,g)=>n.jsxs("div",{className:"up-correction-row",children:[n.jsx("span",{className:"up-correction-from",children:y.from}),n.jsx("span",{className:"up-correction-arrow",children:"→"}),n.jsx("span",{className:"up-correction-to",children:y.to}),n.jsxs("span",{className:"up-correction-count",children:[y.count,"x"]})]},g))})]}),n.jsxs("footer",{className:"up-footer",children:[n.jsxs("div",{className:"up-stat",children:[n.jsx("span",{className:"up-stat-label",children:"Interactions"}),n.jsx("span",{className:"up-stat-value",children:s.totalInteractions})]}),n.jsxs("div",{className:"up-stat",children:[n.jsx("span",{className:"up-stat-label",children:"First used"}),n.jsx("span",{className:"up-stat-value",children:Zi(s.firstUsed)})]}),n.jsxs("div",{className:"up-stat",children:[n.jsx("span",{className:"up-stat-label",children:"Last used"}),n.jsx("span",{className:"up-stat-value",children:Zi(s.lastUsed)})]})]})]})}const Ua={dnd:{enabled:!1,schedule:{start:"22:00",end:"08:00"}},urgencyKeywords:[],sources:{email:!0,calendar:!0,github:!0},soundEnabled:!0};function Fm(){const{data:s,loading:r}=ut(()=>J.getNotificationPreferences(),[]),{data:u,loading:o}=ut(()=>J.getNotifications(),[]),[f,m]=h.useState(Ua),[p,x]=h.useState([]),[y,g]=h.useState(!1),[b,j]=h.useState(""),[S,w]=h.useState(""),[A,D]=h.useState("");h.useEffect(()=>{var M,k,Z,K,q,W,G,te;if(s!=null&&s.data&&Object.keys(s.data).length>0){const ce=s.data,ie={dnd:{enabled:((M=ce.dnd)==null?void 0:M.enabled)??Ua.dnd.enabled,schedule:{start:((Z=(k=ce.dnd)==null?void 0:k.schedule)==null?void 0:Z.start)??Ua.dnd.schedule.start,end:((q=(K=ce.dnd)==null?void 0:K.schedule)==null?void 0:q.end)??Ua.dnd.schedule.end}},urgencyKeywords:ce.urgencyKeywords??Ua.urgencyKeywords,sources:{email:((W=ce.sources)==null?void 0:W.email)??Ua.sources.email,calendar:((G=ce.sources)==null?void 0:G.calendar)??Ua.sources.calendar,github:((te=ce.sources)==null?void 0:te.github)??Ua.sources.github},soundEnabled:ce.soundEnabled??Ua.soundEnabled};m(ie),D((ie.urgencyKeywords||[]).join(", "))}},[s]),h.useEffect(()=>{u!=null&&u.data&&x(u.data)},[u]);const O=async()=>{g(!0),w(""),j("");try{const M=A.split(",").map(k=>k.trim()).filter(Boolean);await J.updateNotificationPreferences({...f,urgencyKeywords:M}),j("Notification settings saved successfully")}catch(M){w(M instanceof Error?M.message:"Failed to save settings")}finally{g(!1)}},E=async M=>{try{await J.dismissNotification(M),x(k=>k.filter(Z=>Z.id!==M))}catch{}};return r||o?null:n.jsxs("div",{className:"page",children:[n.jsx("h2",{children:"Notification Settings"}),n.jsxs("div",{className:"settings-form",children:[n.jsxs("div",{className:"settings-section",children:[n.jsx("h3",{children:"Do Not Disturb"}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",marginBottom:"1rem"},children:[n.jsx("div",{className:`toggle${f.dnd.enabled?" active":""}`,onClick:()=>m(M=>({...M,dnd:{...M.dnd,enabled:!M.dnd.enabled}}))}),n.jsx("span",{style:{fontSize:"0.85rem",color:"var(--text-secondary)"},children:f.dnd.enabled?"Enabled":"Disabled"})]}),f.dnd.enabled&&n.jsxs("div",{style:{display:"flex",gap:"1rem",alignItems:"center",marginBottom:"1rem"},children:[n.jsxs("div",{children:[n.jsx("label",{children:"Start"}),n.jsx("input",{type:"time",value:f.dnd.schedule.start,onChange:M=>m(k=>({...k,dnd:{...k.dnd,schedule:{...k.dnd.schedule,start:M.target.value}}}))})]}),n.jsxs("div",{children:[n.jsx("label",{children:"End"}),n.jsx("input",{type:"time",value:f.dnd.schedule.end,onChange:M=>m(k=>({...k,dnd:{...k.dnd,schedule:{...k.dnd.schedule,end:M.target.value}}}))})]})]})]}),n.jsxs("div",{className:"settings-section",children:[n.jsx("h3",{children:"Urgency Keywords"}),n.jsx("label",{children:"Comma-separated keywords that mark a notification as urgent"}),n.jsx("textarea",{rows:3,value:A,onChange:M=>D(M.target.value),placeholder:"urgent, critical, deadline, asap",style:{width:"100%",resize:"vertical"}})]}),n.jsxs("div",{className:"settings-section",children:[n.jsx("h3",{children:"Sources"}),n.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:"0.5rem",marginBottom:"1rem"},children:["email","calendar","github"].map(M=>n.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.4rem",cursor:"pointer",fontSize:"0.85rem"},children:[n.jsx("input",{type:"checkbox",checked:f.sources[M],onChange:()=>m(k=>({...k,sources:{...k.sources,[M]:!k.sources[M]}})),style:{width:"auto",marginBottom:0}}),M.charAt(0).toUpperCase()+M.slice(1)]},M))})]}),n.jsxs("div",{className:"settings-section",children:[n.jsx("h3",{children:"Sound"}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",marginBottom:"1rem"},children:[n.jsx("div",{className:`toggle${f.soundEnabled?" active":""}`,onClick:()=>m(M=>({...M,soundEnabled:!M.soundEnabled}))}),n.jsx("span",{style:{fontSize:"0.85rem",color:"var(--text-secondary)"},children:f.soundEnabled?"Enabled":"Disabled"})]})]}),n.jsx("button",{className:"settings-btn",onClick:O,disabled:y,children:y?"Saving...":"Save Settings"}),b&&n.jsx("div",{className:"settings-success",children:b}),S&&n.jsx("div",{className:"error",children:S}),p.length>0&&n.jsxs("div",{className:"settings-section",style:{marginTop:"2rem"},children:[n.jsx("h3",{children:"Recent Notifications"}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:p.map(M=>n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"0.75rem",background:"var(--bg-secondary, #1a1a2e)",borderRadius:"6px"},children:[n.jsxs("div",{children:[n.jsx("div",{style:{fontWeight:500},children:M.title}),n.jsxs("div",{style:{fontSize:"0.8rem",color:"var(--text-secondary)"},children:[M.source," · ",new Date(M.timestamp).toLocaleString()]})]}),n.jsx("button",{className:"settings-btn",style:{padding:"0.25rem 0.75rem",fontSize:"0.8rem"},onClick:()=>E(M.id),children:"Dismiss"})]},M.id))})]})]})]})}const sb=["","behavior.","webhook.","voice.","system.","auth.","dashboard."];function Pm(){const[s,r]=h.useState(""),{data:u,refresh:o}=ut(()=>J.getAudit({type:s||void 0,limit:200}),[s]);Os(o);const f=(u==null?void 0:u.data)??[],m=[{key:"timestamp",label:"Time",render:p=>new Date(p.timestamp).toLocaleString()},{key:"event",label:"Event"},{key:"details",label:"Details",render:p=>JSON.stringify(p.details).slice(0,80)}];return n.jsxs("div",{className:"page",children:[n.jsx("h2",{children:"Audit Log"}),n.jsx("div",{className:"filters",children:n.jsxs("select",{value:s,onChange:p=>r(p.target.value),children:[n.jsx("option",{value:"",children:"All events"}),sb.filter(Boolean).map(p=>n.jsxs("option",{value:p,children:[p,"*"]},p))]})}),n.jsx(Hm,{columns:m,rows:f,keyField:"sequence"})]})}function ib({rating:s}){const r=Math.floor(s),u=s-r>=.5,o=5-r-(u?1:0);return n.jsxs("span",{className:"marketplace-card-rating",title:`${s.toFixed(1)} / 5`,children:["★".repeat(r),u?"½":"","☆".repeat(o)]})}function cb({item:s,onSelect:r,onInstall:u}){return n.jsxs("div",{className:"marketplace-card glass-mid",onClick:()=>r(s),children:[n.jsxs("div",{className:"marketplace-card-header",children:[n.jsx("span",{className:"marketplace-card-name",children:s.name}),n.jsxs("span",{className:"marketplace-card-version",children:["v",s.version]})]}),n.jsx("p",{className:"marketplace-card-author",children:s.author}),n.jsx("p",{className:"marketplace-card-desc",children:s.description}),n.jsxs("div",{className:"marketplace-card-footer",children:[n.jsxs("span",{className:"marketplace-card-stats",children:[n.jsx(ib,{rating:s.rating}),n.jsxs("span",{className:"marketplace-card-downloads",children:["↓"," ",s.downloads.toLocaleString()]})]}),n.jsx("button",{className:"marketplace-card-install",onClick:o=>{o.stopPropagation(),u(s)},children:"Install"})]})]})}function rb({item:s,onClose:r,onInstall:u}){return n.jsxs("div",{className:"marketplace-detail glass-mid",children:[n.jsxs("div",{className:"marketplace-detail-header",children:[n.jsxs("div",{children:[n.jsx("span",{className:"marketplace-detail-name",children:s.name}),n.jsxs("span",{className:"marketplace-detail-version",children:["v",s.version]})]}),n.jsxs("span",{className:"marketplace-detail-author",children:["by ",s.author]})]}),n.jsxs("div",{className:"marketplace-detail-stats",children:[n.jsxs("span",{children:["★".repeat(Math.floor(s.rating)),"☆".repeat(5-Math.floor(s.rating))," (",s.rating.toFixed(1),")"]}),n.jsxs("span",{children:["↓ ",s.downloads.toLocaleString()," downloads"]})]}),n.jsx("p",{className:"marketplace-detail-desc",children:s.description}),s.preview&&n.jsx("p",{className:"marketplace-detail-preview",children:s.preview}),s.tone&&n.jsxs("div",{className:"marketplace-detail-tone",children:[n.jsxs("span",{children:["Warmth: ",s.tone.warmth]}),n.jsxs("span",{children:["Humor: ",s.tone.humor]}),n.jsxs("span",{children:["Formality: ",s.tone.formality]})]}),n.jsxs("div",{className:"marketplace-detail-meta",children:[s.permissions&&s.permissions.length>0&&n.jsxs("div",{children:[n.jsx("strong",{children:"Permissions:"})," ",s.permissions.join(", ")]}),s.keywords&&s.keywords.length>0&&n.jsxs("div",{children:[n.jsx("strong",{children:"Keywords:"})," ",s.keywords.join(", ")]}),s.license&&n.jsxs("div",{children:[n.jsx("strong",{children:"License:"})," ",s.license]})]}),n.jsxs("div",{className:"marketplace-detail-actions",children:[n.jsx("button",{className:"btn-primary",onClick:()=>u(s),children:"Install"}),n.jsx("button",{className:"btn-secondary",onClick:r,children:"Close"})]})]})}function ub(){const[s,r]=h.useState("plugins"),[u,o]=h.useState(""),[f,m]=h.useState("downloads"),[p,x]=h.useState([]),[y,g]=h.useState([]),[b,j]=h.useState(0),[S,w]=h.useState(0),[A,D]=h.useState(null),[O,E]=h.useState(!1),M=18,k=h.useCallback(async()=>{E(!0);try{if(s==="plugins"){const G=await J.searchPlugins({q:u||void 0,sort:f,limit:M,offset:S});x(G.plugins),j(G.total)}else{const G=await J.searchPersonalities({q:u||void 0,sort:f,limit:M,offset:S});g(G.personalities),j(G.total)}}catch{}E(!1)},[s,u,f,S]);h.useEffect(()=>{k()},[k]);const Z=async G=>{try{s==="plugins"?await J.installPlugin(G.name,G.version):await J.installPersonality(G.name,G.version),k()}catch{}},K=s==="plugins"?p:y,q=Math.ceil(b/M),W=Math.floor(S/M)+1;return n.jsxs("div",{className:"marketplace",children:[n.jsxs("div",{className:"marketplace-toolbar",children:[n.jsxs("div",{className:"marketplace-tabs",children:[n.jsx("button",{className:`marketplace-tab ${s==="plugins"?"active":""}`,onClick:()=>{r("plugins"),w(0)},children:"Plugins"}),n.jsx("button",{className:`marketplace-tab ${s==="personalities"?"active":""}`,onClick:()=>{r("personalities"),w(0)},children:"Personalities"})]}),n.jsx("input",{className:"marketplace-search",type:"text",placeholder:"Search...",value:u,onChange:G=>{o(G.target.value),w(0)}})]}),O?n.jsx("div",{className:"marketplace-loading",children:"Loading..."}):n.jsxs("div",{className:"marketplace-grid",children:[K.map(G=>n.jsx(cb,{item:G,onSelect:D,onInstall:Z},G.name)),K.length===0&&n.jsx("div",{className:"marketplace-empty",children:"No results found."})]}),n.jsxs("div",{className:"marketplace-footer",children:[n.jsxs("select",{className:"marketplace-sort",value:f,onChange:G=>m(G.target.value),children:[n.jsx("option",{value:"downloads",children:"Downloads"}),n.jsx("option",{value:"rating",children:"Rating"}),n.jsx("option",{value:"name",children:"Name"}),n.jsx("option",{value:"updated",children:"Recently Updated"})]}),q>1&&n.jsxs("div",{className:"marketplace-pagination",children:[n.jsx("button",{disabled:S===0,onClick:()=>w(Math.max(0,S-M)),children:"Prev"}),n.jsxs("span",{children:["Page ",W," of ",q]}),n.jsx("button",{disabled:W>=q,onClick:()=>w(S+M),children:"Next"})]})]}),A&&n.jsx("div",{className:"marketplace-overlay",onClick:()=>D(null),children:n.jsx("div",{onClick:G=>G.stopPropagation(),children:n.jsx(rb,{item:A,onClose:()=>D(null),onInstall:Z})})})]})}function ob(){const[s,r]=h.useState([]),[u,o]=h.useState(null),[f,m]=h.useState(null),[p,x]=h.useState("unknown"),[y,g]=h.useState(!0);if(h.useEffect(()=>{Promise.all([J.getModels(),J.getHealthState()]).then(([j,S])=>{var A,D,O;r(j.providers),o(j.routing),m(j.cost);const w=(D=(A=S.data)==null?void 0:A.subsystems)==null?void 0:D.find(E=>E.name==="providers");x((w==null?void 0:w.status)??((O=S.data)==null?void 0:O.overall)??"unknown")}).catch(()=>{}).finally(()=>g(!1))},[]),y)return n.jsx("div",{className:"provider-health",children:n.jsx("p",{children:"Loading..."})});const b=p==="healthy"?"status-dot-green":p==="degraded"?"status-dot-yellow":"status-dot-red";return n.jsxs("div",{className:"provider-health",children:[n.jsxs("div",{className:"provider-health-header",children:[n.jsx("h3",{children:"Providers"}),n.jsx("span",{className:b})," ",n.jsx("span",{className:"provider-health-status",children:p})]}),n.jsx("div",{className:"provider-health-grid",children:s.map(j=>n.jsxs("div",{className:"provider-health-card glass-mid",children:[n.jsxs("div",{className:"provider-health-card-header",children:[n.jsx("strong",{children:j.displayName}),(u==null?void 0:u.primary)===j.name&&n.jsx("span",{className:"badge badge-green",children:"Primary"}),(u==null?void 0:u.fallback)===j.name&&n.jsx("span",{className:"badge badge-yellow",children:"Fallback"})]}),n.jsxs("div",{className:"provider-health-card-models",children:[Object.keys(j.models).length," model",Object.keys(j.models).length!==1?"s":"",Object.values(j.models).some(S=>S.isLocal)&&n.jsx("span",{className:"badge badge-gray",children:"Local"})]})]},j.name))}),f&&n.jsxs("div",{className:"provider-health-cost",children:[n.jsxs("div",{className:"provider-health-cost-item",children:[n.jsx("span",{className:"provider-health-cost-label",children:"Today"}),n.jsxs("span",{className:`provider-health-cost-value ${f.isOverBudget?"cost-over":""}`,children:["$",f.today.toFixed(2)]})]}),n.jsxs("div",{className:"provider-health-cost-item",children:[n.jsx("span",{className:"provider-health-cost-label",children:"This month"}),n.jsxs("span",{className:"provider-health-cost-value",children:["$",f.thisMonth.toFixed(2)]})]}),f.budgetRemaining!=null&&n.jsxs("div",{className:"provider-health-cost-item",children:[n.jsx("span",{className:"provider-health-cost-label",children:"Budget left"}),n.jsxs("span",{className:`provider-health-cost-value ${f.warningThresholdReached?"cost-warning":""}`,children:["$",f.budgetRemaining.toFixed(2)]})]})]})]})}function db(){const[s,r]=h.useState(null),[u,o]=h.useState([]),[f,m]=h.useState(!0),p=h.useCallback(async()=>{try{const[y,g]=await Promise.all([J.getJobStats(),J.getJobList({status:"dead",limit:50})]);r(y),o(g.data)}catch{}m(!1)},[]);h.useEffect(()=>{p()},[p]);const x=async y=>{try{await J.retryJob(y),p()}catch{}};return f?n.jsx("div",{className:"dlq-monitor",children:n.jsx("p",{children:"Loading..."})}):n.jsxs("div",{className:"dlq-monitor",children:[n.jsxs("div",{className:"dlq-header",children:[n.jsx("h3",{children:"Job Queue"}),n.jsx("button",{className:"dlq-refresh",onClick:p,children:"Refresh"})]}),s&&n.jsxs("div",{className:"dlq-stats",children:[n.jsxs("span",{className:"dlq-stat",children:[s.pending," pending"]}),n.jsxs("span",{className:"dlq-stat",children:[s.running," running"]}),n.jsxs("span",{className:"dlq-stat",children:[s.completed24h," completed (24h)"]}),n.jsxs("span",{className:"dlq-stat dlq-stat-warn",children:[s.failed24h," failed (24h)"]}),n.jsxs("span",{className:`dlq-stat ${s.dead>0?"dlq-stat-danger":""}`,children:[s.dead," dead"]})]}),u.length>0&&n.jsxs("div",{className:"dlq-list",children:[n.jsx("h4",{children:"Dead Jobs"}),n.jsxs("table",{className:"dlq-table",children:[n.jsx("thead",{children:n.jsxs("tr",{children:[n.jsx("th",{children:"Type"}),n.jsx("th",{children:"Error"}),n.jsx("th",{children:"Attempts"}),n.jsx("th",{children:"Age"}),n.jsx("th",{})]})}),n.jsx("tbody",{children:u.map(y=>n.jsxs("tr",{children:[n.jsx("td",{children:y.type}),n.jsx("td",{className:"dlq-error",children:String(y.result??"unknown")}),n.jsxs("td",{children:[y.attempt,"/",y.maxAttempts]}),n.jsx("td",{children:fb(y.createdAt)}),n.jsx("td",{children:n.jsx("button",{className:"dlq-retry-btn",onClick:()=>x(y.id),children:"Retry"})})]},y.id))})]})]}),u.length===0&&s&&s.dead===0&&n.jsx("p",{className:"dlq-empty",children:"No dead jobs. All clear."})]})}function fb(s){const r=Date.now()-s;return r<6e4?"<1m":r<36e5?`${Math.floor(r/6e4)}m`:r<864e5?`${Math.floor(r/36e5)}h`:`${Math.floor(r/864e5)}d`}function hb(){const[s,r]=h.useState([]),[u,o]=h.useState(!0),[f,m]=h.useState(null);if(h.useEffect(()=>{tx().then(g=>r(g.features)).catch(g=>m(g instanceof Error?g.message:String(g))).finally(()=>o(!1))},[]),u)return n.jsx("div",{className:"system-status",children:n.jsx("p",{children:"Loading..."})});if(f)return n.jsx("div",{className:"system-status",children:n.jsxs("p",{children:["Error: ",f]})});const p=s.filter(g=>g.enabled&&g.configured&&g.active),x=s.filter(g=>g.enabled&&!g.configured),y=s.filter(g=>!g.enabled);return n.jsxs("div",{className:"system-status",children:[n.jsx("h2",{children:"System Status"}),n.jsx(ob,{}),n.jsx(db,{}),n.jsxs("section",{className:"status-section-active",children:[n.jsxs("h3",{children:["Active (",p.length,")"]}),n.jsxs("div",{className:"status-grid",children:[p.map(g=>n.jsxs("div",{className:"status-card",children:[n.jsx("span",{className:"status-dot-green"}),n.jsxs("div",{className:"status-card-info",children:[n.jsx("strong",{children:g.name}),n.jsx("span",{className:"status-card-category",children:g.category})]})]},g.id)),p.length===0&&n.jsx("p",{className:"status-empty",children:"No active features"})]})]}),n.jsxs("section",{className:"status-section-ready",children:[n.jsxs("h3",{children:["Ready (",x.length,")"]}),n.jsxs("div",{className:"status-grid",children:[x.map(g=>n.jsxs("div",{className:"status-card",children:[n.jsx("span",{className:"status-dot-yellow"}),n.jsxs("div",{className:"status-card-info",children:[n.jsx("strong",{children:g.name}),n.jsx("span",{className:"status-card-category",children:g.category})]}),n.jsx("button",{className:"status-configure-btn",children:"Configure"})]},g.id)),x.length===0&&n.jsx("p",{className:"status-empty",children:"No features awaiting configuration"})]})]}),n.jsxs("section",{className:"status-section-available",children:[n.jsxs("h3",{children:["Available (",y.length,")"]}),n.jsxs("div",{className:"status-grid",children:[y.map(g=>n.jsxs("div",{className:"status-card",children:[n.jsx("span",{className:"status-dot-gray"}),n.jsxs("div",{className:"status-card-info",children:[n.jsx("strong",{children:g.name}),n.jsx("span",{className:"status-card-category",children:g.category})]})]},g.id)),y.length===0&&n.jsx("p",{className:"status-empty",children:"All features are enabled"})]})]})]})}const mb=["all","preference","fact","context","relationship","pattern","personality"],pb={preference:"mm-badge-accent",fact:"mm-badge-blue",context:"mm-badge-gray",relationship:"mm-badge-green",pattern:"mm-badge-amber",personality:"mm-badge-purple"};function am(s){return new Date(s).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function Im(){const[s,r]=h.useState([]),[u,o]=h.useState(!0),[f,m]=h.useState(null),[p,x]=h.useState(""),[y,g]=h.useState("all"),[b,j]=h.useState(null),[S,w]=h.useState(null),[A,D]=h.useState(""),[O,E]=h.useState(0),[M,k]=h.useState(""),[Z,K]=h.useState(null),[q,W]=h.useState(""),[G,te]=h.useState(null),[ce,ie]=h.useState(!1),he=h.useCallback(()=>{o(!0),m(null);const I=y==="all"?void 0:y;(p?J.searchMemories(p):J.getMemories(I)).then(C=>{r(C.data),o(!1)}).catch(C=>{m(C instanceof Error?C.message:String(C)),o(!1)})},[y,p]);h.useEffect(()=>{he()},[he]);function ee(I){w(I.id),D(I.content),E(I.importance),k(I.tags.join(", "))}function oe(){w(null)}function ve(I){const de=M.split(",").map(C=>C.trim()).filter(Boolean);J.updateMemory(I,{content:A,importance:O,tags:de}).then(()=>{w(null),he()}).catch(C=>m(C instanceof Error?C.message:String(C)))}function H(I){J.deleteMemory(I).then(()=>{K(null),he()}).catch(de=>m(de instanceof Error?de.message:String(de)))}function F(){q.trim()&&(ie(!0),te(null),J.forgetTopic(q.trim()).then(I=>{te(`Removed ${I.removed.memories} memories and ${I.removed.decisions} decisions.`),W(""),ie(!1),he()}).catch(I=>{te(I instanceof Error?I.message:String(I)),ie(!1)}))}function le(){J.exportPersonalization().then(I=>{const de=new Blob([JSON.stringify(I,null,2)],{type:"application/json"}),C=URL.createObjectURL(de),L=document.createElement("a");L.href=C,L.download=`auxiora-export-${Date.now()}.json`,L.click(),URL.revokeObjectURL(C)}).catch(I=>m(I instanceof Error?I.message:String(I)))}return u?n.jsx("div",{className:"mm-page",children:n.jsx("div",{className:"mm-loading",children:"Loading memories..."})}):f?n.jsxs("div",{className:"mm-page",children:[n.jsx("div",{className:"mm-header",children:n.jsx("h2",{className:"mm-title",children:"Memories"})}),n.jsx("div",{className:"mm-error",children:f})]}):n.jsxs("div",{className:"mm-page",children:[n.jsxs("div",{className:"mm-header",children:[n.jsx("h2",{className:"mm-title",children:"Memories"}),n.jsx("input",{className:"mm-search",type:"text",placeholder:"Search memories...",value:p,onChange:I=>x(I.target.value)}),n.jsx("select",{className:"mm-filter",value:y,onChange:I=>g(I.target.value),children:mb.map(I=>n.jsx("option",{value:I,children:I==="all"?"All categories":I},I))})]}),s.length===0?n.jsx("div",{className:"mm-empty",children:"No memories yet"}):n.jsx("div",{className:"mm-grid",children:s.map(I=>n.jsx("div",{className:"mm-card",children:S===I.id?n.jsxs("div",{className:"mm-edit-form",children:[n.jsx("textarea",{className:"mm-edit-content",value:A,onChange:de=>D(de.target.value),rows:3}),n.jsxs("label",{className:"mm-edit-label",children:["Importance (",O.toFixed(2),")",n.jsx("input",{type:"range",min:"0",max:"1",step:"0.01",value:O,onChange:de=>E(Number(de.target.value)),className:"mm-edit-slider"})]}),n.jsxs("label",{className:"mm-edit-label",children:["Tags (comma-separated)",n.jsx("input",{type:"text",className:"mm-edit-tags-input",value:M,onChange:de=>k(de.target.value)})]}),n.jsxs("div",{className:"mm-edit-actions",children:[n.jsx("button",{className:"mm-btn mm-btn-save",onClick:()=>ve(I.id),children:"Save"}),n.jsx("button",{className:"mm-btn mm-btn-cancel",onClick:oe,children:"Cancel"})]})]}):n.jsxs(n.Fragment,{children:[n.jsx("div",{className:`mm-content ${b===I.id?"mm-content-expanded":""}`,onClick:()=>j(b===I.id?null:I.id),children:I.content}),n.jsxs("div",{className:"mm-meta-row",children:[n.jsx("span",{className:`mm-category-badge ${pb[I.category]||"mm-badge-gray"}`,children:I.category}),n.jsx("span",{className:"mm-source-badge",children:I.source})]}),n.jsx("div",{className:"mm-importance-track",children:n.jsx("div",{className:"mm-importance-bar","data-level":I.importance>=.7?"high":I.importance>=.4?"mid":"low",style:{width:`${Math.round(I.importance*100)}%`},role:"progressbar","aria-valuenow":I.importance,"aria-valuemin":0,"aria-valuemax":1,"aria-label":`Importance: ${Math.round(I.importance*100)}%`})}),I.tags.length>0&&n.jsx("div",{className:"mm-tags",children:I.tags.map(de=>n.jsx("span",{className:"mm-tag",children:de},de))}),n.jsxs("div",{className:"mm-timestamps",children:[n.jsxs("span",{children:["Created ",am(I.createdAt)]}),n.jsxs("span",{children:["Updated ",am(I.updatedAt)]})]}),n.jsx("div",{className:"mm-card-actions",children:Z===I.id?n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"mm-confirm-text",children:"Delete?"}),n.jsx("button",{className:"mm-btn mm-btn-danger",onClick:()=>H(I.id),children:"Yes"}),n.jsx("button",{className:"mm-btn mm-btn-cancel",onClick:()=>K(null),children:"No"})]}):n.jsxs(n.Fragment,{children:[n.jsx("button",{className:"mm-btn mm-btn-edit",onClick:()=>ee(I),children:"Edit"}),n.jsx("button",{className:"mm-btn mm-btn-delete",onClick:()=>K(I.id),children:"Delete"})]})})]})},I.id))}),n.jsxs("section",{className:"mm-forget-section",children:[n.jsx("h3",{className:"mm-section-title",children:"Selective Forgetting"}),n.jsx("p",{className:"mm-section-desc",children:"Remove all memories and decisions related to a topic."}),n.jsxs("div",{className:"mm-forget-row",children:[n.jsx("input",{className:"mm-forget-input",type:"text",placeholder:"Topic to forget...",value:q,onChange:I=>W(I.target.value)}),n.jsx("button",{className:"mm-btn mm-btn-danger",onClick:F,disabled:ce||!q.trim(),children:ce?"Forgetting...":"Forget"})]}),G&&n.jsx("div",{className:"mm-forget-result",children:G})]}),n.jsxs("section",{className:"mm-export-section",children:[n.jsx("h3",{className:"mm-section-title",children:"Export Data"}),n.jsx("p",{className:"mm-section-desc",children:"Download all personalization data as JSON."}),n.jsx("button",{className:"mm-btn mm-btn-export",onClick:le,children:"Export All Data"})]})]})}function gb({scores:s,maxScore:r=100}){if(!s||Object.keys(s).length===0)return null;const u=Object.entries(s).sort((o,f)=>f[1]-o[1]);return n.jsx("div",{className:"bc-chart",children:u.map(([o,f])=>n.jsxs("div",{className:"bc-row",children:[n.jsx("span",{className:"bc-label",title:o,children:o}),n.jsx("div",{className:"bc-bar-track",children:n.jsx("div",{className:"bc-bar-fill",style:{width:`${Math.min(100,f/r*100)}%`}})}),n.jsx("span",{className:"bc-value",children:f.toFixed(1)})]},o))})}function vb(s){return s>=1e6?`${(s/1e6).toFixed(1)}M`:s>=1e3?`${Math.round(s/1e3)}K`:String(s)}function nm(s){return s===0?"Free":s<.001?`$${s.toFixed(4)}`:`$${s.toFixed(3)}`}function yb(s){const r=Date.now()-s,u=Math.floor(r/6e4);if(u<1)return"just now";if(u<60)return`${u}m ago`;const o=Math.floor(u/60);return o<24?`${o}h ago`:`${Math.floor(o/24)}d ago`}function lm(s){return s>=1e6?`${(s/1e6).toFixed(1)}M`:s>=1e3?`${(s/1e3).toFixed(1)}K`:String(s)}function xb({model:s,onToggleEnabled:r}){const u=s.displayName||s.modelId,o=s.providerSource==="openrouter",f=s.providerSource==="huggingface";return n.jsxs("div",{className:`mc-card ${s.enabled?"":"mc-card-disabled"}`,children:[n.jsxs("div",{className:"mc-header",children:[n.jsx("span",{className:"mc-name",title:s.modelId,children:u}),n.jsx("span",{className:`mc-provider ${o?"mc-provider-openrouter":""} ${f?"mc-provider-hf":""}`,children:s.providerSource})]}),n.jsxs("div",{className:"mc-context",children:[n.jsx("span",{className:"mc-context-label",children:"Context"}),n.jsx("span",{className:"mc-context-value",children:vb(s.contextLength)})]}),n.jsxs("div",{className:"mc-capabilities",children:[s.supportsVision&&n.jsx("span",{className:"mc-badge mc-badge-blue",children:"Vision"}),s.supportsTools&&n.jsx("span",{className:"mc-badge mc-badge-green",children:"Tools"}),s.supportsStreaming&&n.jsx("span",{className:"mc-badge mc-badge-gray",children:"Streaming"}),s.supportsImageGen&&n.jsx("span",{className:"mc-badge mc-badge-purple",children:"ImageGen"})]}),(s.costPer1kInput>0||s.costPer1kOutput>0)&&n.jsxs("div",{className:"mc-cost",children:[n.jsxs("span",{className:"mc-cost-item",children:["In: ",nm(s.costPer1kInput),"/1K"]}),n.jsxs("span",{className:"mc-cost-item",children:["Out: ",nm(s.costPer1kOutput),"/1K"]})]}),s.strengths&&s.strengths.length>0&&n.jsx("div",{className:"mc-strengths",children:s.strengths.map(m=>n.jsx("span",{className:"mc-strength-pill",children:m},m))}),f&&n.jsxs("div",{className:"mc-hf-stats",children:[s.hfDownloads!=null&&n.jsxs("span",{className:"mc-hf-stat",title:"Downloads",children:["↓"," ",lm(s.hfDownloads)]}),s.hfLikes!=null&&n.jsxs("span",{className:"mc-hf-stat",title:"Likes",children:["♥"," ",lm(s.hfLikes)]}),s.hfTrendingScore!=null&&n.jsxs("span",{className:"mc-hf-stat",title:"Trending Score",children:["↑"," ",s.hfTrendingScore.toFixed(1)]})]}),s.hfBenchmarkScores&&Object.keys(s.hfBenchmarkScores).length>0&&n.jsx(gb,{scores:s.hfBenchmarkScores}),n.jsxs("div",{className:"mc-footer",children:[n.jsx("span",{className:"mc-refreshed",title:new Date(s.lastRefreshedAt).toLocaleString(),children:yb(s.lastRefreshedAt)}),n.jsx("button",{className:`mc-toggle ${s.enabled?"mc-toggle-on":"mc-toggle-off"}`,onClick:()=>r(s.id,!s.enabled),title:s.enabled?"Disable model":"Enable model",children:s.enabled?"Enabled":"Disabled"})]})]})}const bb=[{key:"all",label:"All Models"},{key:"openrouter",label:"OpenRouter"},{key:"huggingface",label:"HuggingFace"},{key:"trending",label:"Trending"}];function jb(){const[s,r]=h.useState("all"),[u,o]=h.useState([]),[f,m]=h.useState(""),[p,x]=h.useState(!1),[y,g]=h.useState(!1),[b,j]=h.useState(!1),[S,w]=h.useState(!1),[A,D]=h.useState(null),O=h.useCallback(async()=>{x(!0),D(null);try{let Z;if(s==="trending")Z="/api/v1/models/trending?limit=50";else{const q=new URLSearchParams;s!=="all"&&q.set("source",s),f&&q.set("search",f),b&&q.set("supportsVision","true"),S&&q.set("supportsTools","true"),q.set("limit","200"),Z=`/api/v1/models/discovered?${q}`}const K=await fetch(Z);if(K.ok){const q=await K.json();o(q.models||[])}else D(`Failed to load models (${K.status})`)}catch{D("Failed to fetch models")}x(!1)},[s,f,b,S]);h.useEffect(()=>{O()},[O]);const E=async()=>{g(!0);try{await fetch("/api/v1/models/refresh",{method:"POST"}),setTimeout(()=>{O(),g(!1)},3e3)}catch{g(!1)}},M=async(Z,K)=>{try{await fetch("/api/v1/models/discovered/toggle",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:Z,enabled:K})}),o(q=>q.map(W=>W.id===Z?{...W,enabled:K}:W))}catch{}},k=Z=>{r(Z),m("")};return n.jsxs("div",{className:"me-page",children:[n.jsxs("div",{className:"me-header",children:[n.jsx("h2",{className:"me-title",children:"Model Explorer"}),n.jsxs("div",{className:"me-header-right",children:[n.jsxs("span",{className:"me-count",children:[u.length," model",u.length!==1?"s":""]}),n.jsx("button",{className:"me-refresh-btn",onClick:E,disabled:y,children:y?"Refreshing...":"Refresh"})]})]}),n.jsxs("div",{className:"me-toolbar",children:[n.jsx("div",{className:"me-tabs",children:bb.map(Z=>n.jsx("button",{className:`me-tab ${s===Z.key?"active":""}`,onClick:()=>k(Z.key),children:Z.label},Z.key))}),s!=="trending"&&n.jsx("input",{className:"me-search",type:"text",placeholder:"Search models...",value:f,onChange:Z=>m(Z.target.value)})]}),s!=="trending"&&n.jsxs("div",{className:"me-filters",children:[n.jsxs("label",{className:"me-filter-check",children:[n.jsx("input",{type:"checkbox",checked:b,onChange:Z=>j(Z.target.checked)}),"Vision"]}),n.jsxs("label",{className:"me-filter-check",children:[n.jsx("input",{type:"checkbox",checked:S,onChange:Z=>w(Z.target.checked)}),"Tools"]})]}),p?n.jsx("div",{className:"me-loading",children:"Loading models..."}):A?n.jsx("div",{className:"me-error",children:A}):u.length===0?n.jsx("div",{className:"me-empty",children:"No models found. Try adjusting your filters or refreshing."}):n.jsx("div",{className:"me-grid",children:u.map(Z=>n.jsx(xb,{model:Z,onToggleEnabled:M},Z.id))})]})}function Sb(){const[s,r]=h.useState([]),[u,o]=h.useState(!0),[f,m]=h.useState(""),[p,x]=h.useState(null),[y,g]=h.useState(!1),[b,j]=h.useState(new Map),S=h.useRef(null),w=h.useCallback(async()=>{o(!0),m("");try{const O=await fetch("/api/v1/canvas/sessions");if(!O.ok)throw new Error(`HTTP ${O.status}`);const E=await O.json();r(Array.isArray(E)?E:E.sessions??[])}catch(O){m(O instanceof Error?O.message:"Failed to load sessions")}finally{o(!1)}},[]);h.useEffect(()=>{w()},[w]);const A=h.useCallback(O=>{S.current&&(S.current.close(),S.current=null),x(O),j(new Map),g(!1);const M=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/api/v1/canvas/sessions/${O}/ws`,k=new WebSocket(M);S.current=k,k.addEventListener("open",()=>g(!0)),k.addEventListener("close",()=>g(!1)),k.addEventListener("error",()=>g(!1)),k.addEventListener("message",Z=>{let K;try{K=JSON.parse(String(Z.data))}catch{return}switch(K.type){case"canvas:snapshot":j(new Map(K.objects.map(q=>[q.id,q])));break;case"object:added":case"object:updated":j(q=>{const W=new Map(q);return W.set(K.object.id,K.object),W});break;case"object:removed":j(q=>{const W=new Map(q);return W.delete(K.id),W});break;case"canvas:cleared":j(new Map);break}})},[]),D=h.useCallback(()=>{S.current&&(S.current.close(),S.current=null),x(null),g(!1),j(new Map),w()},[w]);if(h.useEffect(()=>()=>{S.current&&(S.current.close(),S.current=null)},[]),p){const O=Array.from(b.values()).filter(E=>E.visible!==!1);return n.jsxs("div",{style:{padding:16},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,marginBottom:12},children:[n.jsx("button",{className:"btn btn-sm",onClick:D,children:"Back"}),n.jsxs("span",{style:{fontWeight:600},children:["Session: ",p]}),n.jsx("span",{className:`lc-status ${y?"lc-connected":"lc-disconnected"}`,children:y?"Connected":"Disconnected"})]}),n.jsxs("div",{className:"lc-canvas",style:{position:"relative",minHeight:400},children:[O.length===0&&n.jsx("p",{className:"lc-empty",style:{textAlign:"center"},children:"No objects on canvas"}),O.map(E=>n.jsxs("div",{className:"lc-obj",style:{position:"absolute",left:E.x,top:E.y,width:E.width,height:E.height},children:[E.type==="text"&&n.jsx("div",{className:"lc-text",children:E.content??""}),E.type==="image"&&n.jsx("img",{className:"lc-image",src:E.src,alt:E.alt??"",style:{width:"100%",height:"100%"}}),E.type==="widget"&&n.jsx("div",{className:"lc-text",children:E.content??`[widget ${E.id}]`}),E.type!=="text"&&E.type!=="image"&&E.type!=="widget"&&n.jsxs("div",{className:"lc-text",children:["[",E.type,"]"]})]},E.id))]})]})}return n.jsxs("div",{style:{padding:16},children:[n.jsx("h2",{style:{marginBottom:12},children:"Canvas Sessions"}),u&&n.jsx("p",{className:"lc-empty",children:"Loading sessions..."}),f&&n.jsx("p",{style:{color:"var(--error)"},children:f}),!u&&!f&&s.length===0&&n.jsx("p",{className:"lc-empty",children:"No canvas sessions available"}),!u&&s.length>0&&n.jsx("div",{className:"lc-sessions",children:s.map(O=>n.jsx("button",{className:"btn",onClick:()=>A(O.id),children:O.name??O.id},O.id))})]})}function Nb(s){return s>.8?"dw-score-green":s>.6?"dw-score-yellow":s>.4?"dw-score-red":"dw-score-grey"}function Cb(s){const r=Date.now()-s,u=Math.floor(r/6e4);if(u<1)return"just now";if(u<60)return`${u}m ago`;const o=Math.floor(u/60);return o<24?`${o}h ago`:`${Math.floor(o/24)}d ago`}function Eb(){const[s,r]=h.useState(null),[u,o]=h.useState([]),[f,m]=h.useState(null),[p,x]=h.useState([]),[y,g]=h.useState(!0),[b,j]=h.useState(null),[S,w]=h.useState(null),A=h.useCallback(async()=>{try{const[q,W,G,te]=await Promise.all([J.getDarwinStatus(),J.getDarwinArchive(),J.getDarwinGovernor(),J.getDarwinApprovals()]);r(q),o(W),m(G),x(te),j(null)}catch{j("Failed to load Darwin data")}g(!1)},[]);h.useEffect(()=>{A();const q=setInterval(A,1e4);return()=>clearInterval(q)},[A]);const D=async()=>{if(s){w("pause-resume");try{s.running?await J.pauseDarwin():await J.resumeDarwin(),await A()}catch{j("Failed to toggle Darwin")}w(null)}},O=async q=>{w(q);try{await J.approveDarwinVariant(q),await A()}catch{j(`Failed to approve ${q}`)}w(null)},E=async q=>{w(q);try{await J.rejectDarwinVariant(q),await A()}catch{j(`Failed to reject ${q}`)}w(null)};if(y)return n.jsx("div",{className:"dw-page",children:n.jsx("p",{children:"Loading..."})});if(b&&!s)return n.jsx("div",{className:"dw-page",children:n.jsx("p",{className:"dw-error",children:b})});const M=s&&s.totalCycles>0?(s.successfulCycles/s.totalCycles*100).toFixed(1):"0.0",k=[...new Set(u.map(q=>q.niche.domain))].sort(),Z=[...new Set(u.map(q=>q.niche.complexity))].sort(),K=new Map;for(const q of u)K.set(`${q.niche.domain}|${q.niche.complexity}`,q);return n.jsxs("div",{className:"dw-page",children:[n.jsxs("div",{className:"dw-header",children:[n.jsxs("div",{className:"dw-header-left",children:[n.jsx("h2",{className:"dw-title",children:"Evolution"}),s&&n.jsx("span",{className:`dw-badge ${s.running?"dw-badge-running":"dw-badge-paused"}`,children:s.running?"Running":"Paused"})]}),n.jsx("button",{className:"dw-btn dw-btn-toggle",disabled:S==="pause-resume",onClick:D,children:s!=null&&s.running?"Pause":"Resume"})]}),b&&n.jsx("p",{className:"dw-error",children:b}),s&&f&&n.jsxs("div",{className:"dw-stats",children:[n.jsxs("div",{className:"dw-stat-card",children:[n.jsx("span",{className:"dw-stat-value",children:s.totalCycles}),n.jsx("span",{className:"dw-stat-label",children:"Total Cycles"})]}),n.jsxs("div",{className:"dw-stat-card",children:[n.jsxs("span",{className:"dw-stat-value",children:[M,"%"]}),n.jsx("span",{className:"dw-stat-label",children:"Success Rate"})]}),n.jsxs("div",{className:"dw-stat-card",children:[n.jsx("span",{className:"dw-stat-value",children:s.archiveOccupancy}),n.jsx("span",{className:"dw-stat-label",children:"Archive Occupancy"})]}),n.jsxs("div",{className:"dw-stat-card",children:[n.jsx("span",{className:"dw-stat-value",children:f.tokensUsedThisHour.toLocaleString()}),n.jsx("span",{className:"dw-stat-label",children:"Tokens / Hour"})]}),n.jsxs("div",{className:"dw-stat-card",children:[n.jsx("span",{className:"dw-stat-value",children:f.variantsCreatedToday}),n.jsx("span",{className:"dw-stat-label",children:"Variants / Day"})]})]}),u.length>0&&n.jsxs("div",{className:"dw-section",children:[n.jsx("h3",{className:"dw-section-title",children:"Archive"}),n.jsx("div",{className:"dw-table-wrap",children:n.jsxs("table",{className:"dw-archive-table",children:[n.jsx("thead",{children:n.jsxs("tr",{children:[n.jsx("th",{children:"Domain"}),Z.map(q=>n.jsx("th",{children:q},q))]})}),n.jsx("tbody",{children:k.map(q=>n.jsxs("tr",{children:[n.jsx("td",{className:"dw-domain-cell",children:q}),Z.map(W=>{const G=K.get(`${q}|${W}`);return n.jsx("td",{className:"dw-score-cell",children:G?n.jsx("span",{className:`dw-score-badge ${Nb(G.benchmarkScore)}`,title:`Variant: ${G.variantId}
|
|
60
|
+
Please change the parent <Route path="${k}"> to <Route path="${k==="/"?"*":`${k}/*`}">.`)}let S=hn(),w;if(r){let k=typeof r=="string"?Cl(r):r;Fe(b==="/"||((M=k.pathname)==null?void 0:M.startsWith(b)),`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 "${b}" but pathname "${k.pathname}" was given in the \`location\` prop.`),w=k}else w=S;let A=w.pathname||"/",D=A;if(b!=="/"){let k=b.replace(/^\//,"").split("/");D="/"+A.replace(/^\//,"").split("/").slice(k.length).join("/")}let O=dm(s,{pathname:D});ca(j||O!=null,`No routes matched location "${w.pathname}${w.search}${w.hash}" `),ca(O==null||O[O.length-1].route.element!==void 0||O[O.length-1].route.Component!==void 0||O[O.length-1].route.lazy!==void 0,`Matched leaf route at location "${w.pathname}${w.search}${w.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=iy(O&&O.map(k=>Object.assign({},k,{params:Object.assign({},y,k.params),pathname:La([b,m.encodeLocation?m.encodeLocation(k.pathname.replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:k.pathname]),pathnameBase:k.pathnameBase==="/"?b:La([b,m.encodeLocation?m.encodeLocation(k.pathnameBase.replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:k.pathnameBase])})),p,u,o,f);return r&&E?h.createElement(Ts.Provider,{value:{location:{pathname:"/",search:"",hash:"",state:null,key:"default",...w},navigationType:"POP"}},E):E}function ay(){let s=dy(),r=$v(s)?`${s.status} ${s.statusText}`:s instanceof Error?s.message:JSON.stringify(s),u=s instanceof Error?s.stack:null,o="rgba(200,200,200, 0.5)",f={padding:"0.5rem",backgroundColor:o},m={padding:"2px 4px",backgroundColor:o},p=null;return console.error("Error handled by React Router default ErrorBoundary:",s),p=h.createElement(h.Fragment,null,h.createElement("p",null,"💿 Hey developer 👋"),h.createElement("p",null,"You can provide a way better UX than this when your app throws errors by providing your own ",h.createElement("code",{style:m},"ErrorBoundary")," or"," ",h.createElement("code",{style:m},"errorElement")," prop on your route.")),h.createElement(h.Fragment,null,h.createElement("h2",null,"Unexpected Application Error!"),h.createElement("h3",{style:{fontStyle:"italic"}},r),u?h.createElement("pre",{style:f},u):null,p)}var ny=h.createElement(ay,null),Sm=class extends h.Component{constructor(s){super(s),this.state={location:s.location,revalidation:s.revalidation,error:s.error}}static getDerivedStateFromError(s){return{error:s}}static getDerivedStateFromProps(s,r){return r.location!==s.location||r.revalidation!=="idle"&&s.revalidation==="idle"?{error:s.error,location:s.location,revalidation:s.revalidation}:{error:s.error!==void 0?s.error:r.error,location:r.location,revalidation:s.revalidation||r.revalidation}}componentDidCatch(s,r){this.props.onError?this.props.onError(s,r):console.error("React Router caught the following error during render",s)}render(){let s=this.state.error;if(this.context&&typeof s=="object"&&s&&"digest"in s&&typeof s.digest=="string"){const u=Pv(s.digest);u&&(s=u)}let r=s!==void 0?h.createElement(ma.Provider,{value:this.props.routeContext},h.createElement(_u.Provider,{value:s,children:this.props.component})):this.props.children;return this.context?h.createElement(ly,{error:s},r):r}};Sm.contextType=Qv;var ju=new WeakMap;function ly({children:s,error:r}){let{basename:u}=h.useContext(Xt);if(typeof r=="object"&&r&&"digest"in r&&typeof r.digest=="string"){let o=Fv(r.digest);if(o){let f=ju.get(r);if(f)throw f;let m=pm(o.location,u);if(mm&&!ju.get(r))if(m.isExternal||o.reloadDocument)window.location.href=m.absoluteURL||m.to;else{const p=Promise.resolve().then(()=>window.__reactRouterDataRouter.navigate(m.to,{replace:o.replace}));throw ju.set(r,p),p}return h.createElement("meta",{httpEquiv:"refresh",content:`0;url=${m.absoluteURL||m.to}`})}}return s}function sy({routeContext:s,match:r,children:u}){let o=h.useContext(El);return o&&o.static&&o.staticContext&&(r.route.errorElement||r.route.ErrorBoundary)&&(o.staticContext._deepestRenderedBoundaryId=r.route.id),h.createElement(ma.Provider,{value:s},u)}function iy(s,r=[],u=null,o=null,f=null){if(s==null){if(!u)return null;if(u.errors)s=u.matches;else if(r.length===0&&!u.initialized&&u.matches.length>0)s=u.matches;else return null}let m=s,p=u==null?void 0:u.errors;if(p!=null){let b=m.findIndex(j=>j.route.id&&(p==null?void 0:p[j.route.id])!==void 0);Fe(b>=0,`Could not find a matching route for errors on route IDs: ${Object.keys(p).join(",")}`),m=m.slice(0,Math.min(m.length,b+1))}let x=!1,y=-1;if(u)for(let b=0;b<m.length;b++){let j=m[b];if((j.route.HydrateFallback||j.route.hydrateFallbackElement)&&(y=b),j.route.id){let{loaderData:S,errors:w}=u,A=j.route.loader&&!S.hasOwnProperty(j.route.id)&&(!w||w[j.route.id]===void 0);if(j.route.lazy||A){x=!0,y>=0?m=m.slice(0,y+1):m=[m[0]];break}}}let g=u&&o?(b,j)=>{var S,w;o(b,{location:u.location,params:((w=(S=u.matches)==null?void 0:S[0])==null?void 0:w.params)??{},unstable_pattern:Xv(u.matches),errorInfo:j})}:void 0;return m.reduceRight((b,j,S)=>{let w,A=!1,D=null,O=null;u&&(w=p&&j.route.id?p[j.route.id]:void 0,D=j.route.errorElement||ny,x&&(y<0&&S===0?(Nm("route-fallback",!1,"No `HydrateFallback` element provided to render during initial hydration"),A=!0,O=null):y===S&&(A=!0,O=j.route.hydrateFallbackElement||null)));let E=r.concat(m.slice(0,S+1)),M=()=>{let k;return w?k=D:A?k=O:j.route.Component?k=h.createElement(j.route.Component,null):j.route.element?k=j.route.element:k=b,h.createElement(sy,{match:j,routeContext:{outlet:b,matches:E,isDataRoute:u!=null},children:k})};return u&&(j.route.ErrorBoundary||j.route.errorElement||S===0)?h.createElement(Sm,{location:u.location,revalidation:u.revalidation,component:D,error:w,children:M(),routeContext:{outlet:null,matches:E,isDataRoute:!0},onError:g}):M()},null)}function Uu(s){return`${s} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function cy(s){let r=h.useContext(El);return Fe(r,Uu(s)),r}function ry(s){let r=h.useContext(Ii);return Fe(r,Uu(s)),r}function uy(s){let r=h.useContext(ma);return Fe(r,Uu(s)),r}function Lu(s){let r=uy(s),u=r.matches[r.matches.length-1];return Fe(u.route.id,`${s} can only be used on routes that contain a unique "id"`),u.route.id}function oy(){return Lu("useRouteId")}function dy(){var o;let s=h.useContext(_u),r=ry("useRouteError"),u=Lu("useRouteError");return s!==void 0?s:(o=r.errors)==null?void 0:o[u]}function fy(){let{router:s}=cy("useNavigate"),r=Lu("useNavigate"),u=h.useRef(!1);return bm(()=>{u.current=!0}),h.useCallback(async(f,m={})=>{ca(u.current,xm),u.current&&(typeof f=="number"?await s.navigate(f):await s.navigate(f,{fromRouteId:r,...m}))},[s,r])}var Qh={};function Nm(s,r,u){!r&&!Qh[s]&&(Qh[s]=!0,ca(!1,u))}h.memo(hy);function hy({routes:s,future:r,state:u,onError:o}){return jm(s,void 0,u,o,r)}function Kh({to:s,replace:r,state:u,relative:o}){Fe(wl(),"<Navigate> may be used only in the context of a <Router> component.");let{static:f}=h.useContext(Xt);ca(!f,"<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:m}=h.useContext(ma),{pathname:p}=hn(),x=Ct(),y=ku(s,zu(m),p,o==="path"),g=JSON.stringify(y);return h.useEffect(()=>{x(JSON.parse(g),{replace:r,state:u,relative:o})},[x,g,o,r,u]),null}function ke(s){Fe(!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 my({basename:s="/",children:r=null,location:u,navigationType:o="POP",navigator:f,static:m=!1,unstable_useTransitions:p}){Fe(!wl(),"You cannot render a <Router> inside another <Router>. You should never have more than one in your app.");let x=s.replace(/^\/*/,"/"),y=h.useMemo(()=>({basename:x,navigator:f,static:m,unstable_useTransitions:p,future:{}}),[x,f,m,p]);typeof u=="string"&&(u=Cl(u));let{pathname:g="/",search:b="",hash:j="",state:S=null,key:w="default"}=u,A=h.useMemo(()=>{let D=Ba(g,x);return D==null?null:{location:{pathname:D,search:b,hash:j,state:S,key:w},navigationType:o}},[x,g,b,j,S,w,o]);return ca(A!=null,`<Router basename="${x}"> is not able to match the URL "${g}${b}${j}" because it does not start with the basename, so the <Router> won't render anything.`),A==null?null:h.createElement(Xt.Provider,{value:y},h.createElement(Ts.Provider,{children:r,value:A}))}function py({children:s,location:r}){return ty(Mu(s),r)}function Mu(s,r=[]){let u=[];return h.Children.forEach(s,(o,f)=>{if(!h.isValidElement(o))return;let m=[...r,f];if(o.type===h.Fragment){u.push.apply(u,Mu(o.props.children,m));return}Fe(o.type===ke,`[${typeof o.type=="string"?o.type:o.type.name}] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>`),Fe(!o.props.index||!o.props.children,"An index route cannot have child routes.");let p={id:o.props.id||m.join("-"),caseSensitive:o.props.caseSensitive,element:o.props.element,Component:o.props.Component,index:o.props.index,path:o.props.path,middleware:o.props.middleware,loader:o.props.loader,action:o.props.action,hydrateFallbackElement:o.props.hydrateFallbackElement,HydrateFallback:o.props.HydrateFallback,errorElement:o.props.errorElement,ErrorBoundary:o.props.ErrorBoundary,hasErrorBoundary:o.props.hasErrorBoundary===!0||o.props.ErrorBoundary!=null||o.props.errorElement!=null,shouldRevalidate:o.props.shouldRevalidate,handle:o.props.handle,lazy:o.props.lazy};o.props.children&&(p.children=Mu(o.props.children,m)),u.push(p)}),u}var Ji="get",Wi="application/x-www-form-urlencoded";function ec(s){return typeof HTMLElement<"u"&&s instanceof HTMLElement}function gy(s){return ec(s)&&s.tagName.toLowerCase()==="button"}function vy(s){return ec(s)&&s.tagName.toLowerCase()==="form"}function yy(s){return ec(s)&&s.tagName.toLowerCase()==="input"}function xy(s){return!!(s.metaKey||s.altKey||s.ctrlKey||s.shiftKey)}function by(s,r){return s.button===0&&(!r||r==="_self")&&!xy(s)}var Vi=null;function jy(){if(Vi===null)try{new FormData(document.createElement("form"),0),Vi=!1}catch{Vi=!0}return Vi}var Sy=new Set(["application/x-www-form-urlencoded","multipart/form-data","text/plain"]);function Su(s){return s!=null&&!Sy.has(s)?(ca(!1,`"${s}" is not a valid \`encType\` for \`<Form>\`/\`<fetcher.Form>\` and will default to "${Wi}"`),null):s}function Ny(s,r){let u,o,f,m,p;if(vy(s)){let x=s.getAttribute("action");o=x?Ba(x,r):null,u=s.getAttribute("method")||Ji,f=Su(s.getAttribute("enctype"))||Wi,m=new FormData(s)}else if(gy(s)||yy(s)&&(s.type==="submit"||s.type==="image")){let x=s.form;if(x==null)throw new Error('Cannot submit a <button> or <input type="submit"> without a <form>');let y=s.getAttribute("formaction")||x.getAttribute("action");if(o=y?Ba(y,r):null,u=s.getAttribute("formmethod")||x.getAttribute("method")||Ji,f=Su(s.getAttribute("formenctype"))||Su(x.getAttribute("enctype"))||Wi,m=new FormData(x,s),!jy()){let{name:g,type:b,value:j}=s;if(b==="image"){let S=g?`${g}.`:"";m.append(`${S}x`,"0"),m.append(`${S}y`,"0")}else g&&m.append(g,j)}}else{if(ec(s))throw new Error('Cannot submit element that is not <form>, <button>, or <input type="submit|image">');u=Ji,o=null,f=Wi,p=s}return m&&f==="text/plain"&&(p=m,m=void 0),{action:o,method:u.toLowerCase(),encType:f,formData:m,body:p}}Object.getOwnPropertyNames(Object.prototype).sort().join("\0");function Bu(s,r){if(s===!1||s===null||typeof s>"u")throw new Error(r)}function Cy(s,r,u,o){let f=typeof s=="string"?new URL(s,typeof window>"u"?"server://singlefetch/":window.location.origin):s;return u?f.pathname.endsWith("/")?f.pathname=`${f.pathname}_.${o}`:f.pathname=`${f.pathname}.${o}`:f.pathname==="/"?f.pathname=`_root.${o}`:r&&Ba(f.pathname,r)==="/"?f.pathname=`${r.replace(/\/$/,"")}/_root.${o}`:f.pathname=`${f.pathname.replace(/\/$/,"")}.${o}`,f}async function Ey(s,r){if(s.id in r)return r[s.id];try{let u=await import(s.module);return r[s.id]=u,u}catch(u){return console.error(`Error loading route module \`${s.module}\`, reloading page...`),console.error(u),window.__reactRouterContext&&window.__reactRouterContext.isSpaMode,window.location.reload(),new Promise(()=>{})}}function wy(s){return s==null?!1:s.href==null?s.rel==="preload"&&typeof s.imageSrcSet=="string"&&typeof s.imageSizes=="string":typeof s.rel=="string"&&typeof s.href=="string"}async function Ty(s,r,u){let o=await Promise.all(s.map(async f=>{let m=r.routes[f.route.id];if(m){let p=await Ey(m,u);return p.links?p.links():[]}return[]}));return Ry(o.flat(1).filter(wy).filter(f=>f.rel==="stylesheet"||f.rel==="preload").map(f=>f.rel==="stylesheet"?{...f,rel:"prefetch",as:"style"}:{...f,rel:"prefetch"}))}function Zh(s,r,u,o,f,m){let p=(y,g)=>u[g]?y.route.id!==u[g].route.id:!0,x=(y,g)=>{var b;return u[g].pathname!==y.pathname||((b=u[g].route.path)==null?void 0:b.endsWith("*"))&&u[g].params["*"]!==y.params["*"]};return m==="assets"?r.filter((y,g)=>p(y,g)||x(y,g)):m==="data"?r.filter((y,g)=>{var j;let b=o.routes[y.route.id];if(!b||!b.hasLoader)return!1;if(p(y,g)||x(y,g))return!0;if(y.route.shouldRevalidate){let S=y.route.shouldRevalidate({currentUrl:new URL(f.pathname+f.search+f.hash,window.origin),currentParams:((j=u[0])==null?void 0:j.params)||{},nextUrl:new URL(s,window.origin),nextParams:y.params,defaultShouldRevalidate:!0});if(typeof S=="boolean")return S}return!0}):[]}function Ay(s,r,{includeHydrateFallback:u}={}){return Oy(s.map(o=>{let f=r.routes[o.route.id];if(!f)return[];let m=[f.module];return f.clientActionModule&&(m=m.concat(f.clientActionModule)),f.clientLoaderModule&&(m=m.concat(f.clientLoaderModule)),u&&f.hydrateFallbackModule&&(m=m.concat(f.hydrateFallbackModule)),f.imports&&(m=m.concat(f.imports)),m}).flat(1))}function Oy(s){return[...new Set(s)]}function My(s){let r={},u=Object.keys(s).sort();for(let o of u)r[o]=s[o];return r}function Ry(s,r){let u=new Set;return new Set(r),s.reduce((o,f)=>{let m=JSON.stringify(My(f));return u.has(m)||(u.add(m),o.push({key:m,link:f})),o},[])}function Cm(){let s=h.useContext(El);return Bu(s,"You must render this element inside a <DataRouterContext.Provider> element"),s}function Dy(){let s=h.useContext(Ii);return Bu(s,"You must render this element inside a <DataRouterStateContext.Provider> element"),s}var Hu=h.createContext(void 0);Hu.displayName="FrameworkContext";function Em(){let s=h.useContext(Hu);return Bu(s,"You must render this element inside a <HydratedRouter> element"),s}function zy(s,r){let u=h.useContext(Hu),[o,f]=h.useState(!1),[m,p]=h.useState(!1),{onFocus:x,onBlur:y,onMouseEnter:g,onMouseLeave:b,onTouchStart:j}=r,S=h.useRef(null);h.useEffect(()=>{if(s==="render"&&p(!0),s==="viewport"){let D=E=>{E.forEach(M=>{p(M.isIntersecting)})},O=new IntersectionObserver(D,{threshold:.5});return S.current&&O.observe(S.current),()=>{O.disconnect()}}},[s]),h.useEffect(()=>{if(o){let D=setTimeout(()=>{p(!0)},100);return()=>{clearTimeout(D)}}},[o]);let w=()=>{f(!0)},A=()=>{f(!1),p(!1)};return u?s!=="intent"?[m,S,{}]:[m,S,{onFocus:Ns(x,w),onBlur:Ns(y,A),onMouseEnter:Ns(g,w),onMouseLeave:Ns(b,A),onTouchStart:Ns(j,w)}]:[!1,S,{}]}function Ns(s,r){return u=>{s&&s(u),u.defaultPrevented||r(u)}}function ky({page:s,...r}){let{router:u}=Cm(),o=h.useMemo(()=>dm(u.routes,s,u.basename),[u.routes,s,u.basename]);return o?h.createElement(Uy,{page:s,matches:o,...r}):null}function _y(s){let{manifest:r,routeModules:u}=Em(),[o,f]=h.useState([]);return h.useEffect(()=>{let m=!1;return Ty(s,r,u).then(p=>{m||f(p)}),()=>{m=!0}},[s,r,u]),o}function Uy({page:s,matches:r,...u}){let o=hn(),{future:f,manifest:m,routeModules:p}=Em(),{basename:x}=Cm(),{loaderData:y,matches:g}=Dy(),b=h.useMemo(()=>Zh(s,r,g,m,o,"data"),[s,r,g,m,o]),j=h.useMemo(()=>Zh(s,r,g,m,o,"assets"),[s,r,g,m,o]),S=h.useMemo(()=>{if(s===o.pathname+o.search+o.hash)return[];let D=new Set,O=!1;if(r.forEach(M=>{var Z;let k=m.routes[M.route.id];!k||!k.hasLoader||(!b.some(K=>K.route.id===M.route.id)&&M.route.id in y&&((Z=p[M.route.id])!=null&&Z.shouldRevalidate)||k.hasClientLoader?O=!0:D.add(M.route.id))}),D.size===0)return[];let E=Cy(s,x,f.unstable_trailingSlashAwareDataRequests,"data");return O&&D.size>0&&E.searchParams.set("_routes",r.filter(M=>D.has(M.route.id)).map(M=>M.route.id).join(",")),[E.pathname+E.search]},[x,f.unstable_trailingSlashAwareDataRequests,y,o,m,b,r,s,p]),w=h.useMemo(()=>Ay(j,m),[j,m]),A=_y(j);return h.createElement(h.Fragment,null,S.map(D=>h.createElement("link",{key:D,rel:"prefetch",as:"fetch",href:D,...u})),w.map(D=>h.createElement("link",{key:D,rel:"modulepreload",href:D,...u})),A.map(({key:D,link:O})=>h.createElement("link",{key:D,nonce:u.nonce,...O,crossOrigin:O.crossOrigin??u.crossOrigin})))}function Ly(...s){return r=>{s.forEach(u=>{typeof u=="function"?u(r):u!=null&&(u.current=r)})}}var By=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";try{By&&(window.__reactRouterVersion="7.13.0")}catch{}function Hy({basename:s,children:r,unstable_useTransitions:u,window:o}){let f=h.useRef();f.current==null&&(f.current=xv({window:o,v5Compat:!0}));let m=f.current,[p,x]=h.useState({action:m.action,location:m.location}),y=h.useCallback(g=>{u===!1?x(g):h.startTransition(()=>x(g))},[u]);return h.useLayoutEffect(()=>m.listen(y),[m,y]),h.createElement(my,{basename:s,children:r,location:p.location,navigationType:p.action,navigator:m,unstable_useTransitions:u})}var wm=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,Tm=h.forwardRef(function({onClick:r,discover:u="render",prefetch:o="none",relative:f,reloadDocument:m,replace:p,state:x,target:y,to:g,preventScrollReset:b,viewTransition:j,unstable_defaultShouldRevalidate:S,...w},A){let{basename:D,unstable_useTransitions:O}=h.useContext(Xt),E=typeof g=="string"&&wm.test(g),M=pm(g,D);g=M.to;let k=Iv(g,{relative:f}),[Z,K,q]=zy(o,w),W=$y(g,{replace:p,state:x,target:y,preventScrollReset:b,relative:f,viewTransition:j,unstable_defaultShouldRevalidate:S,unstable_useTransitions:O});function G(ce){r&&r(ce),ce.defaultPrevented||W(ce)}let te=h.createElement("a",{...w,...q,href:M.absoluteURL||k,onClick:M.isExternal||m?r:G,ref:Ly(A,K),target:y,"data-discover":!E&&u==="render"?"true":void 0});return Z&&!E?h.createElement(h.Fragment,null,te,h.createElement(ky,{page:k})):te});Tm.displayName="Link";var qy=h.forwardRef(function({"aria-current":r="page",caseSensitive:u=!1,className:o="",end:f=!1,style:m,to:p,viewTransition:x,children:y,...g},b){let j=As(p,{relative:g.relative}),S=hn(),w=h.useContext(Ii),{navigator:A,basename:D}=h.useContext(Xt),O=w!=null&&Zy(j)&&x===!0,E=A.encodeLocation?A.encodeLocation(j).pathname:j.pathname,M=S.pathname,k=w&&w.navigation&&w.navigation.location?w.navigation.location.pathname:null;u||(M=M.toLowerCase(),k=k?k.toLowerCase():null,E=E.toLowerCase()),k&&D&&(k=Ba(k,D)||k);const Z=E!=="/"&&E.endsWith("/")?E.length-1:E.length;let K=M===E||!f&&M.startsWith(E)&&M.charAt(Z)==="/",q=k!=null&&(k===E||!f&&k.startsWith(E)&&k.charAt(E.length)==="/"),W={isActive:K,isPending:q,isTransitioning:O},G=K?r:void 0,te;typeof o=="function"?te=o(W):te=[o,K?"active":null,q?"pending":null,O?"transitioning":null].filter(Boolean).join(" ");let ce=typeof m=="function"?m(W):m;return h.createElement(Tm,{...g,"aria-current":G,className:te,ref:b,style:ce,to:p,viewTransition:x},typeof y=="function"?y(W):y)});qy.displayName="NavLink";var Yy=h.forwardRef(({discover:s="render",fetcherKey:r,navigate:u,reloadDocument:o,replace:f,state:m,method:p=Ji,action:x,onSubmit:y,relative:g,preventScrollReset:b,viewTransition:j,unstable_defaultShouldRevalidate:S,...w},A)=>{let{unstable_useTransitions:D}=h.useContext(Xt),O=Qy(),E=Ky(x,{relative:g}),M=p.toLowerCase()==="get"?"get":"post",k=typeof x=="string"&&wm.test(x),Z=K=>{if(y&&y(K),K.defaultPrevented)return;K.preventDefault();let q=K.nativeEvent.submitter,W=(q==null?void 0:q.getAttribute("formmethod"))||p,G=()=>O(q||K.currentTarget,{fetcherKey:r,method:W,navigate:u,replace:f,state:m,relative:g,preventScrollReset:b,viewTransition:j,unstable_defaultShouldRevalidate:S});D&&u!==!1?h.startTransition(()=>G()):G()};return h.createElement("form",{ref:A,method:M,action:E,onSubmit:o?y:Z,...w,"data-discover":!k&&s==="render"?"true":void 0})});Yy.displayName="Form";function Gy(s){return`${s} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function Am(s){let r=h.useContext(El);return Fe(r,Gy(s)),r}function $y(s,{target:r,replace:u,state:o,preventScrollReset:f,relative:m,viewTransition:p,unstable_defaultShouldRevalidate:x,unstable_useTransitions:y}={}){let g=Ct(),b=hn(),j=As(s,{relative:m});return h.useCallback(S=>{if(by(S,r)){S.preventDefault();let w=u!==void 0?u:ws(b)===ws(j),A=()=>g(s,{replace:w,state:o,preventScrollReset:f,relative:m,viewTransition:p,unstable_defaultShouldRevalidate:x});y?h.startTransition(()=>A()):A()}},[b,g,j,u,o,r,s,f,m,p,x,y])}var Xy=0,Vy=()=>`__${String(++Xy)}__`;function Qy(){let{router:s}=Am("useSubmit"),{basename:r}=h.useContext(Xt),u=oy(),o=s.fetch,f=s.navigate;return h.useCallback(async(m,p={})=>{let{action:x,method:y,encType:g,formData:b,body:j}=Ny(m,r);if(p.navigate===!1){let S=p.fetcherKey||Vy();await o(S,u,p.action||x,{unstable_defaultShouldRevalidate:p.unstable_defaultShouldRevalidate,preventScrollReset:p.preventScrollReset,formData:b,body:j,formMethod:p.method||y,formEncType:p.encType||g,flushSync:p.flushSync})}else await f(p.action||x,{unstable_defaultShouldRevalidate:p.unstable_defaultShouldRevalidate,preventScrollReset:p.preventScrollReset,formData:b,body:j,formMethod:p.method||y,formEncType:p.encType||g,replace:p.replace,state:p.state,fromRouteId:u,flushSync:p.flushSync,viewTransition:p.viewTransition})},[o,f,r,u])}function Ky(s,{relative:r}={}){let{basename:u}=h.useContext(Xt),o=h.useContext(ma);Fe(o,"useFormAction must be used inside a RouteContext");let[f]=o.matches.slice(-1),m={...As(s||".",{relative:r})},p=hn();if(s==null){m.search=p.search;let x=new URLSearchParams(m.search),y=x.getAll("index");if(y.some(b=>b==="")){x.delete("index"),y.filter(j=>j).forEach(j=>x.append("index",j));let b=x.toString();m.search=b?`?${b}`:""}}return(!s||s===".")&&f.route.index&&(m.search=m.search?m.search.replace(/^\?/,"?index&"):"?index"),u!=="/"&&(m.pathname=m.pathname==="/"?u:La([u,m.pathname])),ws(m)}function Zy(s,{relative:r}={}){let u=h.useContext(vm);Fe(u!=null,"`useViewTransitionState` must be used within `react-router-dom`'s `RouterProvider`. Did you accidentally import `RouterProvider` from `react-router`?");let{basename:o}=Am("useViewTransitionState"),f=As(s,{relative:r});if(!u.isTransitioning)return!1;let m=Ba(u.currentLocation.pathname,o)||u.currentLocation.pathname,p=Ba(u.nextLocation.pathname,o)||u.nextLocation.pathname;return Fi(f.pathname,p)!=null||Fi(f.pathname,m)!=null}var Jy=om();const Wy=["nebula","monolith","signal","polar","neon","terra"],Fy=[{id:"nebula",name:"Nebula",description:"Glassmorphism command center",mode:"dark",colors:["#080b16","#8b5cf6","#10b981","#f0f0f5"]},{id:"monolith",name:"Monolith",description:"Cinematic ultra-minimal",mode:"dark",colors:["#000000","#7c3aed","#ffffff","#404040"]},{id:"signal",name:"Signal",description:"Warm sci-fi terminal",mode:"dark",colors:["#0c0c0c","#f59e0b","#22c55e","#e8e4dd"]},{id:"polar",name:"Polar",description:"Premium light mode",mode:"light",colors:["#ffffff","#3b82f6","#059669","#111827"]},{id:"neon",name:"Neon",description:"Cyberpunk vivid",mode:"dark",colors:["#09090b","#06b6d4","#ec4899","#22c55e"]},{id:"terra",name:"Terra",description:"Warm organic dark",mode:"dark",colors:["#1a1612","#c97b5c","#8faa7b","#e8e0d4"]}],Om=h.createContext({theme:"nebula",setTheme:()=>{}});function Py({children:s}){const[r,u]=h.useState(()=>{const f=localStorage.getItem("auxiora-theme");return f&&Wy.includes(f)?f:"nebula"}),o=h.useCallback(f=>{u(f),localStorage.setItem("auxiora-theme",f),document.documentElement.setAttribute("data-theme",f)},[]);return h.useEffect(()=>{document.documentElement.setAttribute("data-theme",r)},[]),n.jsx(Om.Provider,{value:{theme:r,setTheme:o},children:s})}function qu(){return h.useContext(Om)}const Iy="/api/v1/dashboard";async function se(s,r){const u=await fetch(`${Iy}${s}`,{credentials:"include",headers:{"Content-Type":"application/json"},...r});if(u.status===401)throw window.location.href="/dashboard/login",new Error("Unauthorized");if(!u.ok){const o=await u.json().catch(()=>({}));throw new Error(o.error||`HTTP ${u.status}`)}return u.json()}const ex="/api/v1/marketplace";async function Sl(s,r){const u=await fetch(`${ex}${s}`,{credentials:"include",headers:{"Content-Type":"application/json"},...r});if(u.status===401)throw window.location.href="/dashboard/login",new Error("Unauthorized");if(!u.ok){const o=await u.json().catch(()=>({}));throw new Error(o.error||`HTTP ${u.status}`)}return u.json()}const J={checkAuth:()=>se("/auth/check"),login:s=>se("/auth/login",{method:"POST",body:JSON.stringify({password:s})}),logout:()=>se("/auth/logout",{method:"POST"}),getBehaviors:()=>se("/behaviors"),patchBehavior:(s,r)=>se(`/behaviors/${s}`,{method:"PATCH",body:JSON.stringify(r)}),deleteBehavior:s=>se(`/behaviors/${s}`,{method:"DELETE"}),createBehavior:s=>se("/behaviors",{method:"POST",body:JSON.stringify(s)}),getWebhooks:()=>se("/webhooks"),patchWebhook:(s,r)=>se(`/webhooks/${s}`,{method:"PATCH",body:JSON.stringify(r)}),deleteWebhook:s=>se(`/webhooks/${s}`,{method:"DELETE"}),createWebhook:s=>se("/webhooks",{method:"POST",body:JSON.stringify(s)}),getSessions:()=>se("/sessions"),getAudit:s=>{const r=new URLSearchParams;s!=null&&s.type&&r.set("type",s.type),s!=null&&s.limit&&r.set("limit",String(s.limit));const u=r.toString();return se(`/audit${u?`?${u}`:""}`)},getStatus:()=>se("/status"),getActiveAgents:()=>se("/status/agents"),getHealthState:()=>se("/status/health"),getCapabilities:()=>se("/status/capabilities"),getSetupStatus:()=>se("/setup/status"),setupVault:s=>se("/setup/vault",{method:"POST",body:JSON.stringify({password:s})}),setupDashboardPassword:s=>se("/setup/dashboard-password",{method:"POST",body:JSON.stringify({password:s})}),setupIdentity:(s,r,u)=>se("/setup/identity",{method:"POST",body:JSON.stringify({name:s,pronouns:r,vibe:u})}),getSetupTemplates:()=>se("/setup/templates"),setupPersonality:s=>se("/setup/personality",{method:"POST",body:JSON.stringify({template:s})}),setupProvider:(s,r,u)=>se("/setup/provider",{method:"POST",body:JSON.stringify({provider:s,apiKey:r,endpoint:u})}),setupProviders:s=>se("/setup/provider",{method:"POST",body:JSON.stringify({providers:s})}),setupChannels:s=>se("/setup/channels",{method:"POST",body:JSON.stringify({channels:s})}),completeSetup:()=>se("/setup/complete",{method:"POST"}),getModels:()=>se("/models"),getIdentity:()=>se("/identity"),updateIdentity:(s,r)=>se("/identity",{method:"POST",body:JSON.stringify({name:s,pronouns:r})}),getPersonality:()=>se("/personality"),getTemplates:()=>se("/personality/templates"),updatePersonality:s=>se("/personality",{method:"POST",body:JSON.stringify({template:s})}),getPersonalityFull:()=>se("/personality/full"),updatePersonalityFull:s=>se("/personality/full",{method:"PUT",body:JSON.stringify(s)}),updateProvider:(s,r,u)=>se("/provider",{method:"POST",body:JSON.stringify({provider:s,apiKey:r,endpoint:u})}),configureProvider:(s,r,u)=>se("/provider/configure",{method:"POST",body:JSON.stringify({provider:s,apiKey:r,endpoint:u})}),startClaudeOAuth:()=>se("/provider/claude-oauth/start",{method:"POST"}),completeClaudeOAuth:s=>se("/provider/claude-oauth/callback",{method:"POST",body:JSON.stringify({code:s})}),disconnectClaudeOAuth:()=>se("/provider/claude-oauth/disconnect",{method:"POST"}),getClaudeOAuthStatus:()=>se("/provider/claude-oauth/status"),updateRouting:(s,r)=>se("/provider/routing",{method:"POST",body:JSON.stringify({primary:s,fallback:r})}),setProviderModel:(s,r)=>se("/provider/model",{method:"POST",body:JSON.stringify({provider:s,model:r})}),getSessionMessages:()=>se("/session/messages"),getChannels:()=>se("/channels"),updateChannels:s=>se("/channels",{method:"POST",body:JSON.stringify({channels:s})}),changeDashboardPassword:(s,r)=>se("/security/dashboard-password",{method:"POST",body:JSON.stringify({oldPassword:s,newPassword:r})}),changeVaultPassword:s=>se("/security/vault-password",{method:"POST",body:JSON.stringify({newPassword:s})}),getSealStatus:()=>se("/security/seal/status"),enableSeal:(s,r)=>se("/security/seal",{method:"POST",body:JSON.stringify({password:s,pin:r})}),disableSeal:()=>se("/security/seal",{method:"DELETE"}),getConnectorStatus:s=>se(`/connectors/${s}/status`),saveConnectorCredentials:(s,r,u)=>se(`/connectors/${s}/credentials`,{method:"POST",body:JSON.stringify({clientId:r,clientSecret:u})}),disconnectConnector:s=>se(`/connectors/${s}/disconnect`,{method:"POST"}),getAmbientConfig:()=>se("/ambient/config"),updateAmbientConfig:s=>se("/ambient/config",{method:"POST",body:JSON.stringify(s)}),getPersonalityEngine:()=>se("/personality/engine"),setPersonalityEngine:s=>se("/personality/engine",{method:"PUT",body:JSON.stringify({engine:s})}),updateChatPersonality:(s,r)=>se(`/chats/${s}`,{method:"PATCH",body:JSON.stringify({personality:r})}),getArchitectPreferences:()=>se("/architect/preferences"),updateArchitectPreference:(s,r)=>se("/architect/preferences",{method:"PATCH",body:JSON.stringify({key:s,value:r})}),clearArchitectData:()=>se("/architect/data",{method:"DELETE"}),exportArchitectData:()=>se("/architect/data/export"),getAppearance:()=>se("/appearance"),updateAppearance:s=>se("/appearance",{method:"POST",body:JSON.stringify({theme:s})}),getChats:s=>se(`/chats${s?"?archived=true":""}`),createNewChat:s=>se("/chats",{method:"POST",body:JSON.stringify({title:s})}),getChatMessages:s=>se(`/chats/${s}/messages`),renameChat:(s,r)=>se(`/chats/${s}`,{method:"PATCH",body:JSON.stringify({title:r})}),archiveChat:s=>se(`/chats/${s}`,{method:"PATCH",body:JSON.stringify({archived:!0})}),deleteChatThread:s=>se(`/chats/${s}`,{method:"DELETE"}),getNotifications:()=>se("/notifications"),dismissNotification:s=>se(`/notifications/${s}/dismiss`,{method:"POST"}),getNotificationPreferences:()=>se("/notifications/preferences"),updateNotificationPreferences:s=>se("/notifications/preferences",{method:"POST",body:JSON.stringify(s)}),getUserModel:()=>fetch("/api/v1/personality/user-model",{credentials:"include"}).then(async s=>{if(!s.ok){const r=await s.json().catch(()=>({}));throw new Error(r.error||`HTTP ${s.status}`)}return s.json()}),getMemories:s=>{const r=s?`?category=${encodeURIComponent(s)}`:"";return se(`/memories${r}`)},searchMemories:s=>se(`/memories/search?q=${encodeURIComponent(s)}`),deleteMemory:s=>se(`/memories/${encodeURIComponent(s)}`,{method:"DELETE"}),updateMemory:(s,r)=>se(`/memories/${encodeURIComponent(s)}`,{method:"PATCH",body:JSON.stringify(r)}),exportMemories:()=>se("/memories/export"),forgetTopic:s=>se("/forget",{method:"POST",body:JSON.stringify({topic:s})}),exportPersonalization:()=>se("/export/personalization"),searchPlugins:(s={})=>{const r=new URLSearchParams;s.q&&r.set("q",s.q),s.author&&r.set("author",s.author),s.keywords&&r.set("keywords",s.keywords),s.sort&&r.set("sort",s.sort),s.limit&&r.set("limit",String(s.limit)),s.offset&&r.set("offset",String(s.offset));const u=r.toString();return Sl(`/plugins/search${u?`?${u}`:""}`)},getPlugin:s=>Sl(`/plugins/${encodeURIComponent(s)}`),installPlugin:(s,r)=>Sl("/plugins/install",{method:"POST",body:JSON.stringify({name:s,version:r})}),searchPersonalities:(s={})=>{const r=new URLSearchParams;s.q&&r.set("q",s.q),s.author&&r.set("author",s.author),s.sort&&r.set("sort",s.sort),s.limit&&r.set("limit",String(s.limit)),s.offset&&r.set("offset",String(s.offset));const u=r.toString();return Sl(`/personalities/search${u?`?${u}`:""}`)},getMarketplacePersonality:s=>Sl(`/personalities/${encodeURIComponent(s)}`),installPersonality:(s,r)=>Sl("/personalities/install",{method:"POST",body:JSON.stringify({name:s,version:r})}),getJobStats:()=>fetch("/api/v1/jobs/status",{credentials:"include"}).then(s=>s.json()),getJobList:s=>{const r=new URLSearchParams;s!=null&&s.status&&r.set("status",s.status),s!=null&&s.type&&r.set("type",s.type),s!=null&&s.limit&&r.set("limit",String(s.limit));const u=r.toString();return fetch(`/api/v1/jobs/list${u?`?${u}`:""}`,{credentials:"include"}).then(o=>o.json())},retryJob:s=>fetch(`/api/v1/jobs/${encodeURIComponent(s)}/retry`,{method:"POST",credentials:"include"}).then(r=>r.json()),getDarwinStatus:()=>fetch("/api/v1/darwin/status",{credentials:"include"}).then(s=>s.json()),getDarwinArchive:()=>fetch("/api/v1/darwin/archive",{credentials:"include"}).then(s=>s.json()),getDarwinVariant:s=>fetch(`/api/v1/darwin/variants/${encodeURIComponent(s)}`,{credentials:"include"}).then(r=>r.json()),getDarwinGovernor:()=>fetch("/api/v1/darwin/governor",{credentials:"include"}).then(s=>s.json()),getDarwinApprovals:()=>fetch("/api/v1/darwin/approvals",{credentials:"include"}).then(s=>s.json()),approveDarwinVariant:s=>fetch(`/api/v1/darwin/approvals/${encodeURIComponent(s)}/approve`,{method:"POST",credentials:"include"}).then(r=>r.json()),rejectDarwinVariant:s=>fetch(`/api/v1/darwin/approvals/${encodeURIComponent(s)}/reject`,{method:"POST",credentials:"include"}).then(r=>r.json()),pauseDarwin:()=>fetch("/api/v1/darwin/pause",{method:"POST",credentials:"include"}).then(s=>s.json()),resumeDarwin:()=>fetch("/api/v1/darwin/resume",{method:"POST",credentials:"include"}).then(s=>s.json())};async function tx(){const s=await fetch("/api/v1/features/status",{credentials:"include"});if(!s.ok)throw new Error(`HTTP ${s.status}`);return s.json()}function ut(s,r=[]){const[u,o]=h.useState(null),[f,m]=h.useState(!0),[p,x]=h.useState(null),y=h.useCallback(()=>{m(!0),s().then(g=>{o(g),x(null)}).catch(g=>x(g.message)).finally(()=>m(!1))},r);return h.useEffect(()=>{y()},[y]),{data:u,loading:f,error:p,refresh:y}}function Os(s,r=1e4){h.useEffect(()=>{const u=setInterval(s,r);return()=>clearInterval(u)},[s,r])}const Mm="auxiora-windows",Rm="auxiora-snap-grid",Nu=360,Cu=240,ax=600,nx=500,Jh=30,lx=36,Wh=100,Cs=40;function Qi(s,r){return Math.round(s/r)*r}function Ru(s,r,u,o){const f=typeof window<"u"?window.innerWidth:1920,m=typeof window<"u"?window.innerHeight:1080;return{x:Math.max(Wh-u,Math.min(s,f-Wh)),y:Math.max(0,Math.min(r,m-lx))}}function sx(){try{const s=localStorage.getItem(Mm);if(!s)return new Map;const r=JSON.parse(s),u=new Map(Object.entries(r));for(const[o,f]of u){const m=Ru(f.x,f.y,f.width,f.height);(m.x!==f.x||m.y!==f.y)&&u.set(o,{...f,x:m.x,y:m.y})}return u}catch{return new Map}}function ix(s){const r=Object.fromEntries(s);localStorage.setItem(Mm,JSON.stringify(r))}function Eu(s){let r=0;for(const u of s.values())u.zIndex>r&&(r=u.zIndex);return r+1}function cx(){try{return localStorage.getItem(Rm)==="1"}catch{return!1}}function rx(){const[s,r]=h.useState(sx),[u,o]=h.useState(cx),f=h.useCallback(A=>{r(D=>{const O=A(D);return ix(O),O})},[]),m=h.useCallback((A,D,O,E)=>{f(M=>{if(M.has(A)){const G=new Map(M),te=G.get(A);return G.set(A,{...te,zIndex:Eu(G),minimized:!1}),G}const k=new Map(M),Z=k.size,K=Math.max(Nu,O??ax),q=Math.max(Cu,E??nx),W=Ru(80+Z%8*Jh,60+Z%8*Jh,K);return k.set(A,{id:A,title:D,x:W.x,y:W.y,width:K,height:q,zIndex:Eu(k),minimized:!1,maximized:!1}),k})},[f]),p=h.useCallback(A=>{f(D=>{const O=new Map(D);return O.delete(A),O})},[f]),x=h.useCallback(A=>{f(D=>{const O=D.get(A);if(!O)return D;const E=new Map(D);return E.set(A,{...O,zIndex:Eu(E)}),E})},[f]),y=h.useCallback(()=>{o(A=>{const D=!A;try{localStorage.setItem(Rm,D?"1":"0")}catch{}return D})},[]),g=h.useCallback((A,D,O)=>{f(E=>{const M=E.get(A);if(!M)return E;const k=u?Qi(D,Cs):D,Z=u?Qi(O,Cs):O,K=Ru(k,Z,M.width,M.height),q=new Map(E);return q.set(A,{...M,x:K.x,y:K.y}),q})},[f,u]),b=h.useCallback((A,D,O)=>{f(E=>{const M=E.get(A);if(!M)return E;const k=u?Qi(Math.max(Nu,D),Cs):Math.max(Nu,D),Z=u?Qi(Math.max(Cu,O),Cs):Math.max(Cu,O),K=new Map(E);return K.set(A,{...M,width:k,height:Z}),K})},[f,u]),j=h.useCallback(A=>{f(D=>{const O=D.get(A);if(!O)return D;const E=new Map(D);return E.set(A,{...O,minimized:!O.minimized}),E})},[f]),S=h.useCallback(A=>{f(D=>{const O=D.get(A);if(!O)return D;const E=new Map(D);return E.set(A,{...O,maximized:!O.maximized}),E})},[f]),w=h.useMemo(()=>{let A=-1,D=null;for(const O of s.values())!O.minimized&&O.zIndex>A&&(A=O.zIndex,D=O.id);return D},[s]);return{windows:s,activeWindowId:w,snapEnabled:u,gridSize:Cs,openWindow:m,closeWindow:p,focusWindow:x,moveWindow:g,resizeWindow:b,toggleMinimize:j,toggleMaximize:S,toggleSnap:y}}const ux=["n","s","e","w","ne","nw","se","sw"];function ox({id:s,title:r,x:u,y:o,width:f,height:m,zIndex:p,minimized:x,maximized:y,focused:g,onClose:b,onFocus:j,onMinimize:S,onMaximize:w,onMove:A,onResize:D,children:O}){const E=h.useRef(null),M=h.useCallback(q=>{if(y)return;q.preventDefault(),j();const W=q.clientX,G=q.clientY;E.current={startX:W,startY:G,origX:u,origY:o};const te=ie=>{if(!E.current)return;const he=ie.clientX-E.current.startX,ee=ie.clientY-E.current.startY;A(E.current.origX+he,E.current.origY+ee)},ce=()=>{E.current=null,document.removeEventListener("mousemove",te),document.removeEventListener("mouseup",ce)};document.addEventListener("mousemove",te),document.addEventListener("mouseup",ce)},[y,u,o,j,A]),k=h.useCallback((q,W)=>{if(y)return;W.preventDefault(),W.stopPropagation(),j();const G=W.clientX,te=W.clientY,ce=u,ie=o,he=f,ee=m,oe=H=>{const F=H.clientX-G,le=H.clientY-te;let I=ce,de=ie,C=he,L=ee;q.includes("e")&&(C=he+F),q.includes("w")&&(C=he-F,I=ce+F),q.includes("s")&&(L=ee+le),q.includes("n")&&(L=ee-le,de=ie+le),D(C,L),(q.includes("w")||q.includes("n"))&&A(I,de)},ve=()=>{document.removeEventListener("mousemove",oe),document.removeEventListener("mouseup",ve)};document.addEventListener("mousemove",oe),document.addEventListener("mouseup",ve)},[y,u,o,f,m,j,D,A]);if(x)return null;const Z=y?{zIndex:p,inset:"0",width:"100%",height:"100%"}:{left:`${u}px`,top:`${o}px`,width:`${f}px`,height:`${m}px`,zIndex:p},K=["window","glass-mid"];return g&&K.push("focused"),y&&K.push("maximized"),n.jsxs("div",{className:K.join(" "),style:Z,onMouseDown:j,"data-window-id":s,children:[!y&&ux.map(q=>n.jsx("div",{className:`window-resize window-resize-${q}`,onMouseDown:W=>k(q,W)},q)),n.jsxs("div",{className:"window-titlebar",onMouseDown:M,children:[n.jsxs("div",{className:"window-traffic-lights",children:[n.jsx("button",{type:"button",className:"window-traffic-light close","aria-label":"Close window",onClick:q=>{q.stopPropagation(),b()}}),n.jsx("button",{type:"button",className:"window-traffic-light minimize","aria-label":"Minimize window",onClick:q=>{q.stopPropagation(),S()}}),n.jsx("button",{type:"button",className:"window-traffic-light maximize","aria-label":"Maximize window",onClick:q=>{q.stopPropagation(),w()}})]}),n.jsx("span",{className:"window-title",children:r})]}),n.jsx("div",{className:"window-body",children:O})]})}function dx({items:s,openWindows:r,onOpen:u}){const o=h.useRef(null),f=h.useCallback(p=>{const x=o.current;if(!x)return;const y=x.querySelectorAll(".dock-icon-wrapper"),g=p.clientX;y.forEach(b=>{const j=b.getBoundingClientRect(),S=j.left+j.width/2,w=Math.abs(g-S);b.classList.remove("mag-center","mag-near","mag-far"),w<25?b.classList.add("mag-center"):w<60?b.classList.add("mag-near"):w<100&&b.classList.add("mag-far")})},[]),m=h.useCallback(()=>{const p=o.current;p&&p.querySelectorAll(".dock-icon-wrapper").forEach(x=>{x.classList.remove("mag-center","mag-near","mag-far")})},[]);return n.jsx("div",{className:"dock-container",ref:o,onMouseMove:f,onMouseLeave:m,children:s.map(p=>n.jsxs("div",{className:"dock-icon-wrapper",children:[n.jsx("div",{className:"dock-tooltip",children:p.label}),n.jsx("button",{type:"button",className:"dock-icon","aria-label":`Open ${p.label}`,onClick:()=>u(p.id),children:p.icon}),n.jsx("div",{className:`dock-icon-dot${r.has(p.id)?" active":""}`})]},p.id))})}function fx(){const[s,r]=h.useState([]),u=h.useRef(new Set),o=h.useCallback(async()=>{try{const m=await fetch("/api/v1/tool-approvals/pending");if(!m.ok)return;const p=await m.json();r(p.filter(x=>!u.current.has(x.id)))}catch{}},[]);h.useEffect(()=>{o();const m=setInterval(o,3e3);return()=>clearInterval(m)},[o]);const f=h.useCallback(async(m,p)=>{u.current.add(m),r(x=>x.filter(y=>y.id!==m));try{await fetch(`/api/v1/tool-approvals/${m}/resolve`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({approved:p})})}catch{}},[]);return s.length===0?null:n.jsx("div",{className:"ab-banner",children:s.map(m=>n.jsxs("div",{className:"ab-item",children:[n.jsx("span",{className:"ab-tool",children:m.toolName}),n.jsx("span",{className:"ab-args",children:JSON.stringify(m.args)}),n.jsx("button",{className:"ab-approve",onClick:()=>f(m.id,!0),children:"Approve"}),n.jsx("button",{className:"ab-deny",onClick:()=>f(m.id,!1),children:"Deny"})]},m.id))})}const hx={"behavior.executed":s=>s.success?"Behavior ran successfully":`Behavior failed: ${s.error??"unknown"}`,"behavior.created":()=>"Behavior created","behavior.updated":()=>"Behavior updated","behavior.deleted":()=>"Behavior deleted","behavior.paused":()=>"Behavior paused","behavior.failed":s=>`Behavior failed: ${s.error??"unknown"}`,"message.received":s=>`Message received on ${s.channelType??"unknown"}`,"message.sent":s=>`Message sent to ${s.channelType??"unknown"}`,"message.filtered":()=>"Message filtered","channel.connected":s=>`${s.channelType??"Channel"} connected`,"channel.disconnected":s=>`${s.channelType??"Channel"} disconnected`,"channel.error":s=>`${s.channelType??"Channel"} error`,"webhook.triggered":s=>`Webhook triggered: ${s.path??""}`,"webhook.received":()=>"Webhook received","webhook.created":()=>"Webhook created","webhook.deleted":()=>"Webhook deleted","webhook.error":s=>`Webhook error: ${s.error??"unknown"}`,"system.startup":()=>"System started","system.shutdown":()=>"System shut down","system.error":s=>`System error: ${s.error??"unknown"}`,"auth.login":()=>"Login","auth.logout":()=>"Logout"},mx={behavior:"var(--accent)",message:"#3b82f6",channel:"var(--success)",webhook:"#f97316",system:"var(--text-secondary)",auth:"var(--danger)"};function px(s){return s.split(".")[0]}function gx(s,r){const u=hx[s];return u?u(r):s.replace(/\./g," ").replace(/\b\w/g,o=>o.toUpperCase())}function vx(s){const r=(Date.now()-new Date(s).getTime())/1e3;return r<60?"just now":r<3600?`${Math.floor(r/60)}m ago`:r<86400?`${Math.floor(r/3600)}h ago`:`${Math.floor(r/86400)}d ago`}const Fh=100;function yx(){const[s,r]=h.useState([]),u=h.useRef(null);return h.useEffect(()=>{J.getAudit({limit:50}).then(o=>{if(o.data){const f=["behavior.","message.","channel.","webhook.","system.","auth.login","auth.logout"],m=o.data.filter(p=>f.some(x=>p.event.startsWith(x))).reverse();r(m)}}).catch(()=>{})},[]),h.useEffect(()=>{const o=window.location.protocol==="https:"?"wss:":"ws:",f=window.location.host,m=new WebSocket(`${o}//${f}/`);return u.current=m,m.onmessage=p=>{try{const x=JSON.parse(p.data);x.type==="activity"&&x.payload&&r(y=>{const g=[x.payload,...y];return g.length>Fh?g.slice(0,Fh):g})}catch{}},()=>{m.close()}},[]),n.jsxs("div",{className:"activity-feed",children:[n.jsx("h3",{className:"mc-section-title",children:"Live Activity"}),n.jsxs("div",{className:"activity-feed-list",children:[s.length===0&&n.jsx("div",{className:"activity-empty",children:"No recent activity"}),s.map((o,f)=>{const m=px(o.event),p=mx[m]??"var(--text-secondary)";return n.jsxs("div",{className:"activity-item",children:[n.jsx("span",{className:"activity-dot",style:{background:p}}),n.jsx("span",{className:"activity-label",children:gx(o.event,o.details)}),n.jsx("span",{className:"activity-time",children:vx(o.timestamp)})]},`${o.sequence}-${f}`)})]})]})}const xx={discord:"Discord",telegram:"Telegram",slack:"Slack",webchat:"Web"};function bx(s){const r=Date.now()-new Date(s).getTime(),u=Math.floor(r/1e3);return u<60?`${u}s`:`${Math.floor(u/60)}m ${u%60}s`}function jx(){const[s,r]=h.useState([]),u=h.useRef(null),o=h.useRef(null),[,f]=h.useState(0);return h.useEffect(()=>{J.getActiveAgents().then(m=>{m.data&&r(m.data)}).catch(()=>{})},[]),h.useEffect(()=>{const m=window.location.protocol==="https:"?"wss:":"ws:",p=window.location.host,x=new WebSocket(`${m}//${p}/`);return u.current=x,x.onmessage=y=>{try{const g=JSON.parse(y.data);g.type==="agent_start"&&g.payload?r(b=>[...b,g.payload]):g.type==="agent_end"&&g.payload&&r(b=>b.filter(j=>j.id!==g.payload.id))}catch{}},()=>{x.close()}},[]),h.useEffect(()=>(o.current=setInterval(()=>f(m=>m+1),1e3),()=>{o.current&&clearInterval(o.current)}),[]),n.jsxs("div",{className:"agent-activity",children:[n.jsx("h3",{className:"mc-section-title",children:"Active Now"}),s.length===0?n.jsx("div",{className:"agent-activity-quiet",children:"All quiet"}):n.jsx("div",{className:"agent-activity-list",children:s.map(m=>n.jsxs("div",{className:"agent-activity-card",children:[n.jsx("span",{className:"agent-pulse"}),n.jsxs("div",{className:"agent-activity-info",children:[n.jsx("span",{className:"agent-activity-desc",children:m.description}),n.jsxs("span",{className:"agent-activity-meta",children:[m.channelType&&n.jsx("span",{className:"agent-channel-badge",children:xx[m.channelType]??m.channelType}),n.jsx("span",{className:"agent-activity-type",children:m.type}),n.jsx("span",{className:"agent-activity-elapsed",children:bx(m.startedAt)})]})]})]},m.id))})]})}function Sx(s){const r=(Date.now()-new Date(s).getTime())/1e3;return r<60?"just now":r<3600?`${Math.floor(r/60)}m ago`:r<86400?`${Math.floor(r/3600)}h ago`:`${Math.floor(r/86400)}d ago`}function Ph(s){return s.status==="paused"&&s.failCount>=s.maxFailures?"var(--danger)":s.status==="paused"?"var(--text-secondary)":s.failCount>0?"var(--warning)":"var(--success)"}function Nx(s){return s.status==="paused"&&s.failCount>=s.maxFailures?"Auto-paused":s.status==="paused"?"Paused":s.failCount>0?`${s.failCount} failures`:"Healthy"}const Cx={scheduled:"Sched",monitor:"Monitor","one-shot":"Once"};function Ex(){const[s,r]=h.useState([]),u=h.useRef(null);return h.useEffect(()=>{J.getBehaviors().then(o=>{o.data&&r(o.data.filter(f=>f.status!=="deleted"))}).catch(()=>{})},[]),h.useEffect(()=>{const o=window.location.protocol==="https:"?"wss:":"ws:",f=window.location.host,m=new WebSocket(`${o}//${f}/`);return u.current=m,m.onmessage=p=>{var x,y;try{const g=JSON.parse(p.data);g.type==="activity"&&((y=(x=g.payload)==null?void 0:x.event)!=null&&y.startsWith("behavior."))&&J.getBehaviors().then(b=>{b.data&&r(b.data.filter(j=>j.status!=="deleted"))}).catch(()=>{})}catch{}},()=>{m.close()}},[]),n.jsxs("div",{className:"behavior-health",children:[n.jsx("h3",{className:"mc-section-title",children:"Behavior Health"}),s.length===0&&n.jsx("div",{className:"bh-empty",children:"No behaviors configured"}),n.jsx("div",{className:"bh-list",children:s.map(o=>n.jsxs("div",{className:"bh-card",children:[n.jsxs("div",{className:"bh-card-header",children:[n.jsx("span",{className:"bh-dot",style:{background:Ph(o)}}),n.jsx("span",{className:"bh-action",children:o.action.length>60?o.action.slice(0,57)+"...":o.action}),n.jsx("span",{className:"bh-type-badge",children:Cx[o.type]??o.type})]}),n.jsxs("div",{className:"bh-card-meta",children:[n.jsx("span",{className:"bh-health-label",style:{color:Ph(o)},children:Nx(o)}),n.jsxs("span",{className:"bh-stat",children:[o.runCount," runs"]}),o.lastRun&&n.jsx("span",{className:"bh-stat",children:Sx(o.lastRun)})]}),o.lastResult&&n.jsx("div",{className:"bh-result",children:o.lastResult.length>120?o.lastResult.slice(0,117)+"...":o.lastResult})]},o.id))})]})}function Dm(){var y,g,b,j,S,w,A,D,O;const{data:s,refresh:r}=ut(()=>J.getStatus(),[]),{data:u,refresh:o}=ut(()=>J.getModels(),[]),{data:f,refresh:m}=ut(()=>J.getHealthState(),[]);Os(()=>{r(),o(),m()});const p=s==null?void 0:s.data,x=((g=(y=u==null?void 0:u.providers)==null?void 0:y.find(E=>E.available))==null?void 0:g.displayName)??"None";return n.jsxs("div",{className:"page",children:[n.jsx("h2",{children:"Mission Control"}),n.jsxs("div",{className:"status-grid",children:[n.jsxs("div",{className:"status-card",children:[n.jsx("h3",{children:"Connections"}),n.jsx("div",{className:"value",children:(p==null?void 0:p.connections)??0}),n.jsx("div",{className:"sub",children:"Active sessions"})]}),n.jsxs("div",{className:"status-card",children:[n.jsx("h3",{children:"Provider"}),n.jsx("div",{className:"value",children:x}),n.jsx("div",{className:"sub",children:((b=p==null?void 0:p.activeModel)==null?void 0:b.model)??"unknown"})]}),n.jsxs("div",{className:"status-card",children:[n.jsx("h3",{children:"Uptime"}),n.jsx("div",{className:"value",children:p?wx(p.uptime):"-"}),n.jsx("div",{className:"sub",children:"Since last restart"})]}),n.jsxs("div",{className:"status-card",children:[n.jsx("h3",{children:"Health"}),n.jsxs("div",{className:"value",children:[n.jsx("span",{className:`health-dot health-${((j=f==null?void 0:f.data)==null?void 0:j.overall)??"unknown"}`}),Tx(((S=f==null?void 0:f.data)==null?void 0:S.overall)??"unknown")]}),n.jsxs("div",{className:"sub",children:[((A=(w=f==null?void 0:f.data)==null?void 0:w.issues)==null?void 0:A.length)??0," issues"]})]})]}),((O=(D=f==null?void 0:f.data)==null?void 0:D.issues)==null?void 0:O.length)>0&&n.jsx("div",{className:"health-alerts",children:f.data.issues.map(E=>n.jsxs("div",{className:`health-alert health-alert-${E.severity}`,children:[n.jsx("span",{className:"health-alert-text",children:E.description}),E.suggestedFix&&n.jsx("span",{className:"health-alert-fix",children:E.suggestedFix})]},E.id))}),n.jsxs("div",{className:"mc-columns",children:[n.jsxs("div",{className:"mc-left",children:[n.jsx(jx,{}),n.jsx(Ex,{})]}),n.jsx("div",{className:"mc-right",children:n.jsx(yx,{})})]})]})}function wx(s){const r=Math.floor(s/3600),u=Math.floor(s%3600/60);return r>0?`${r}h ${u}m`:`${u}m`}function Tx(s){return s.charAt(0).toUpperCase()+s.slice(1)}const _t={security_review:{icon:"🛡️",label:"Security Review",description:"Adversarial analysis, threat modeling, vulnerability assessment",colorClass:"context-red"},crisis_management:{icon:"🚨",label:"Crisis",description:"Incidents, breaches, outages, urgent response",colorClass:"context-red"},code_engineering:{icon:"💻",label:"Engineering",description:"Writing, reviewing, and optimizing code",colorClass:"context-blue"},architecture_design:{icon:"🏗️",label:"Architecture",description:"System design, patterns, trade-off analysis",colorClass:"context-blue"},debugging:{icon:"🐛",label:"Debugging",description:"Finding and fixing bugs, tracing errors",colorClass:"context-blue"},team_leadership:{icon:"👥",label:"Team Leadership",description:"Managing teams, culture, performance, hiring",colorClass:"context-green"},one_on_one:{icon:"🤝",label:"One-on-One",description:"Coaching, feedback, career development conversations",colorClass:"context-green"},sales_pitch:{icon:"📈",label:"Sales",description:"Pitching, proposals, value positioning, closing",colorClass:"context-purple"},negotiation:{icon:"⚖️",label:"Negotiation",description:"Contract terms, compensation, vendor discussions",colorClass:"context-purple"},marketing_content:{icon:"📣",label:"Marketing",description:"Positioning, messaging, audience building, campaigns",colorClass:"context-purple"},strategic_planning:{icon:"🎯",label:"Strategy",description:"Roadmaps, priorities, resource allocation, OKRs",colorClass:"context-orange"},decision_making:{icon:"⚖️",label:"Decision",description:"Weighing options, trade-offs, choosing between paths",colorClass:"context-orange"},creative_work:{icon:"💡",label:"Creative",description:"Brainstorming, ideation, creative problem solving",colorClass:"context-teal"},writing_content:{icon:"✍️",label:"Writing",description:"Blog posts, articles, documentation, drafting",colorClass:"context-teal"},learning_research:{icon:"📚",label:"Learning",description:"Understanding concepts, deep dives, research",colorClass:"context-gray"},personal_development:{icon:"🌱",label:"Growth",description:"Career planning, skills, growth, interviews",colorClass:"context-gray"},general:{icon:"💬",label:"General",description:"General conversation and assistance",colorClass:"context-gray"}},Nl=Object.keys(_t),zm={stressed:"· Under Pressure",frustrated:"· Working Through It",uncertain:"· Exploring",excited:"· Energized",celebratory:"· Celebrating"};function Ax({context:s,onOverride:r,showOverrideMenu:u,onToggleOverrideMenu:o}){const f=_t[s.domain],m=zm[s.emotionalRegister];return n.jsxs("div",{className:"context-indicator-wrapper",children:[n.jsxs("button",{type:"button",className:`context-indicator ${f.colorClass}`,onClick:o,"aria-label":`Context: ${f.label}`,"aria-expanded":u,"aria-haspopup":"menu",children:[n.jsx("span",{className:"context-indicator-icon","aria-hidden":"true",children:f.icon}),n.jsx("span",{className:"context-indicator-label",children:f.label}),m&&n.jsx("span",{className:"context-indicator-emotion",children:m})]}),u&&n.jsx("ul",{className:"context-override-menu",role:"menu",children:Nl.map(p=>{const x=_t[p];return n.jsx("li",{role:"none",children:n.jsxs("button",{type:"button",role:"menuitem",className:`context-override-item ${p===s.domain?"active":""}`,onClick:()=>r(p),children:[n.jsx("span",{"aria-hidden":"true",children:x.icon})," ",x.label]})},p)})})]})}function Ox(s){return s.replace(/([A-Z])/g," $1").replace(/^./,r=>r.toUpperCase()).trim()}const Mx=10,Rx=29;function Dx({sources:s,context:r,isOpen:u,onClose:o,weights:f}){const[m,p]=h.useState(new Set),[x,y]=h.useState(!1);if(!u)return null;const g=_t[r.domain],b=zm[r.emotionalRegister],j=x?s:s.slice(0,Mx);function S(A){p(D=>{const O=new Set(D);return O.has(A)?O.delete(A):O.add(A),O})}function w(A){return f==null?void 0:f[A]}return n.jsxs("div",{className:"sources-panel",role:"dialog","aria-label":"What shaped this response",children:[n.jsxs("div",{className:"sources-panel-header",children:[n.jsxs("span",{className:"sources-panel-title",children:["🧠"," What shaped this response"]}),n.jsx("button",{type:"button",className:"sources-panel-close",onClick:o,"aria-label":"Close sources panel",children:"✕"})]}),n.jsxs("div",{className:"sources-panel-context",children:[n.jsx("span",{"aria-hidden":"true",children:g.icon})," ",g.label,b&&n.jsx("span",{className:"sources-panel-emotion",children:b})]}),n.jsx("ul",{className:"sources-trait-list",children:j.map(A=>{const D=m.has(A.traitKey),O=w(A.traitKey);return n.jsxs("li",{className:"sources-trait-item",children:[n.jsxs("button",{type:"button",className:"sources-trait-header",onClick:()=>S(A.traitKey),"aria-expanded":D,children:[n.jsx("span",{className:"sources-trait-arrow",children:D?"▾":"▸"}),n.jsx("span",{className:"sources-trait-name",children:Ox(A.traitKey)}),O!=null&&n.jsxs("span",{className:"sources-trait-weight",children:[n.jsx("span",{className:"sources-trait-weight-bar",style:{width:`${Math.round(O*100)}%`},"aria-label":`Weight: ${Math.round(O*100)}%`}),n.jsxs("span",{className:"sources-trait-weight-value",children:[Math.round(O*100),"%"]})]})]}),n.jsx("div",{className:"sources-trait-source",children:n.jsx("strong",{children:A.sourceName})}),D&&n.jsxs("div",{className:"sources-trait-details",children:[n.jsx("div",{className:"sources-trait-work",children:A.sourceWork}),n.jsx("blockquote",{className:"sources-trait-instruction",children:A.behavioralInstruction}),n.jsxs("div",{className:"sources-trait-evidence",children:["Evidence: ",A.evidenceSummary]})]})]},A.traitKey)})}),n.jsxs("div",{className:"sources-panel-footer",children:[n.jsxs("span",{className:"sources-panel-count",children:["Showing top ",j.length," of ",Rx," active traits"]}),n.jsx("button",{type:"button",className:"sources-panel-toggle",onClick:()=>y(A=>!A),children:x?"Show fewer":"Show all"})]})]})}function zx({sources:s,context:r,weights:u}){const[o,f]=h.useState(!1),m=h.useRef(null);return h.useEffect(()=>{if(!o)return;const p=x=>{m.current&&!m.current.contains(x.target)&&f(!1)};return document.addEventListener("mousedown",p),()=>document.removeEventListener("mousedown",p)},[o]),s.length===0?null:n.jsxs("div",{className:"sources-button-container",ref:m,children:[n.jsxs("button",{type:"button",className:"sources-button",onClick:()=>f(p=>!p),"aria-label":"View sources",children:[n.jsx("span",{"aria-hidden":"true",children:"🧠"})," ",n.jsx("span",{className:"sources-button-label",children:"Sources"})]}),n.jsx(Dx,{sources:s,context:r,isOpen:o,onClose:()=>f(!1),weights:u})]})}function kx({currentDomain:s,onSelect:r,onClose:u,isOpen:o}){const[f,m]=h.useState(null),[p,x]=h.useState(-1),y=h.useRef(null),g=h.useRef([]);h.useEffect(()=>{o&&(m(null),x(-1))},[o]),h.useEffect(()=>{if(!o)return;function A(D){y.current&&!y.current.contains(D.target)&&u()}return document.addEventListener("mousedown",A),()=>document.removeEventListener("mousedown",A)},[o,u]);const b=h.useCallback(A=>{var D,O;if(f){A.key==="Escape"&&(m(null),A.preventDefault());return}switch(A.key){case"Escape":u(),A.preventDefault();break;case"ArrowDown":{const E=p<Nl.length-1?p+1:0;x(E),(D=g.current[E])==null||D.focus(),A.preventDefault();break}case"ArrowUp":{const E=p>0?p-1:Nl.length-1;x(E),(O=g.current[E])==null||O.focus(),A.preventDefault();break}case"Enter":p>=0&&(j(Nl[p]),A.preventDefault());break}},[p,u,f]);function j(A){m(A)}function S(A){f&&(r(f,A),m(null))}if(!o)return null;const w=_t[s];return n.jsxs("div",{ref:y,className:"context-override-popover",role:"dialog","aria-label":"Override context",onKeyDown:b,children:[n.jsx("div",{className:"context-override-header",children:n.jsxs("span",{className:"context-override-detected",children:["Detected: ",n.jsx("span",{"aria-hidden":"true",children:w.icon})," ",w.label]})}),f?n.jsxs("div",{className:"context-override-scope",role:"group","aria-label":"Apply scope",children:[n.jsxs("div",{className:"context-override-scope-label",children:["Apply ",n.jsx("strong",{children:_t[f].label})," to:"]}),n.jsxs("button",{type:"button",className:"context-override-scope-btn",onClick:()=>S("message"),children:["This message",n.jsx("span",{className:"context-override-scope-hint",children:"Auto-detection resumes after"})]}),n.jsxs("button",{type:"button",className:"context-override-scope-btn",onClick:()=>S("conversation"),children:["This conversation",n.jsx("span",{className:"context-override-scope-hint",children:"Stays until you change it"})]}),n.jsx("button",{type:"button",className:"context-override-scope-back",onClick:()=>m(null),children:"Back"})]}):n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"context-override-subheader",children:"Switch context:"}),n.jsx("ul",{className:"context-override-list",role:"listbox","aria-label":"Available contexts",children:Nl.map((A,D)=>{const O=_t[A],E=A===s;return n.jsx("li",{role:"none",children:n.jsxs("button",{ref:M=>{g.current[D]=M},type:"button",role:"option","aria-selected":E,className:`context-override-domain-item ${E?"detected":""}`,onClick:()=>j(A),tabIndex:p===D?0:-1,children:[n.jsx("span",{className:"context-override-domain-icon","aria-hidden":"true",children:O.icon}),n.jsxs("span",{className:"context-override-domain-text",children:[n.jsxs("span",{className:"context-override-domain-label",children:[O.label,E&&n.jsx("span",{className:"context-override-detected-badge",children:"detected"})]}),n.jsx("span",{className:"context-override-domain-desc",children:O.description})]})]})},A)})})]})]})}function _x({recommendation:s,onAccept:r,onDismiss:u,autoDismissMs:o=1e4}){const[f,m]=h.useState(!0),p=h.useRef(null),x=h.useRef(!1);if(h.useEffect(()=>{if(!(o<=0))return p.current=setTimeout(()=>{x.current||(m(!1),u())},o),()=>{p.current&&clearTimeout(p.current)}},[o,u]),!f)return null;const y=_t[s.suggestedDomain],g=()=>{x.current=!0,p.current&&clearTimeout(p.current),m(!1),r(s.suggestedDomain)},b=()=>{x.current=!0,p.current&&clearTimeout(p.current),m(!1),u()};return n.jsxs("div",{className:"context-recommendation",role:"status","aria-live":"polite",children:[n.jsx("span",{className:"context-recommendation-icon","aria-hidden":"true",children:y.icon}),n.jsxs("span",{className:"context-recommendation-text",children:[n.jsx("strong",{children:"Suggestion:"})," Switch to ",y.label,"?"," ",n.jsx("span",{className:"context-recommendation-reason",children:s.reason})]}),n.jsx("button",{type:"button",className:"context-recommendation-accept",onClick:g,children:"Switch"}),n.jsx("button",{type:"button",className:"context-recommendation-dismiss",onClick:b,"aria-label":"Dismiss suggestion",children:"✕"})]})}const Ux={tool_result:"🔧",memory_recall:"🧠",knowledge_graph:"🌐",user_data:"👤",model_generation:"🤖"};function Lx({meta:s}){const[r,u]=h.useState(!1);if(!s)return null;const o=s.model.tokens.input+s.model.tokens.output,f=s.confidence.level==="high"?"🟢":s.confidence.level==="medium"?"🟡":"🔴",m=s.personality.knowledgeBoundary;return n.jsxs("div",{className:`transparency-footer confidence-${s.confidence.level}`,children:[n.jsxs("button",{className:"transparency-toggle",onClick:()=>u(!r),"aria-expanded":r,children:[n.jsxs("span",{className:"transparency-summary",children:[f," ",n.jsx("span",{children:s.confidence.level.charAt(0).toUpperCase()+s.confidence.level.slice(1)})," ","(",s.confidence.score,")",m&&n.jsxs("span",{className:"kb-warning",children:[" ","⚠"," Topic previously corrected (",m.corrections,"x)"]})," · ",s.model.model," · ",o," tokens"," · ","$",s.model.cost.total.toFixed(3),s.personality.domain!=="general"&&n.jsxs(n.Fragment,{children:[" · ",s.personality.domain.replace(/_/g," ")]})]}),n.jsx("span",{className:"tf-expand-icon",children:r?"▲":"▼"})]}),r&&n.jsxs("div",{className:"transparency-details",children:[n.jsxs("div",{className:"tf-section",children:[n.jsx("strong",{className:"tf-section-title",children:"Confidence"}),n.jsxs("div",{children:["Score: ",s.confidence.score," (",s.confidence.level.charAt(0).toUpperCase()+s.confidence.level.slice(1),")"]}),s.confidence.factors.map((p,x)=>n.jsxs("div",{className:p.impact==="positive"?"tf-factor-positive":"tf-factor-negative",children:[p.impact==="positive"?" + ":" - ",p.signal,": ",p.detail]},x))]}),n.jsxs("div",{className:"tf-section",children:[n.jsx("strong",{className:"tf-section-title",children:"Sources"}),s.sources.map((p,x)=>n.jsxs("div",{className:"tf-source-line",children:[Ux[p.type]??"❓"," ",p.label," (",p.confidence.toFixed(2),")"]},x))]}),n.jsxs("div",{className:"tf-section tf-section-last",children:[n.jsx("strong",{className:"tf-section-title",children:"Processing"}),n.jsxs("div",{children:["Model: ",s.model.provider," / ",s.model.model]}),n.jsxs("div",{children:["Tokens: ",s.model.tokens.input," in / ",s.model.tokens.output," out"]}),n.jsxs("div",{children:["Cost: $",s.model.cost.input.toFixed(4)," in / $",s.model.cost.output.toFixed(4)," out = $",s.model.cost.total.toFixed(4)," total"]}),n.jsxs("div",{children:["Latency: ",s.model.latencyMs.toLocaleString(),"ms"]}),n.jsxs("div",{children:["Finish: ",s.model.finishReason]}),s.trace.enrichmentStages.length>0&&n.jsxs("div",{children:["Stages: ",s.trace.enrichmentStages.join(" → ")]}),s.trace.toolsUsed.length>0&&n.jsxs("div",{children:["Tools: ",s.trace.toolsUsed.join(", ")]}),n.jsxs("div",{children:["Domain: ",s.personality.domain]}),n.jsxs("div",{children:["Register: ",s.personality.emotionalRegister]}),s.personality.activeTraits.length>0&&n.jsxs("div",{children:["Traits: ",s.personality.activeTraits.map(p=>`${p.name} (${p.weight.toFixed(2)})`).join(", ")]})]})]})]})}const Bx={tool_result:"🔧",memory_recall:"🧠",knowledge_graph:"🌐",user_data:"👤",model_generation:"🤖"};function Hx(s){return s==="high"?"pp-confidence-badge pp-badge-green":s==="medium"?"pp-confidence-badge pp-badge-amber":"pp-confidence-badge pp-badge-red"}function qx({meta:s,onClose:r}){const u=s.personality.knowledgeBoundary;return n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"pp-overlay",onClick:r}),n.jsxs("div",{className:"pp-panel",children:[n.jsxs("div",{className:"pp-header",children:[n.jsx("span",{className:"pp-header-title",children:"Why did I say that?"}),n.jsx("button",{className:"pp-close-btn",onClick:r,"aria-label":"close",children:"X"})]}),n.jsxs("div",{className:"pp-body",children:[n.jsxs("div",{className:"pp-section",children:[n.jsx("div",{className:"pp-section-title",children:"Confidence Breakdown"}),n.jsxs("div",{className:"pp-confidence-row",children:[n.jsx("span",{className:Hx(s.confidence.level),children:s.confidence.score}),n.jsx("span",{className:"pp-confidence-level",children:s.confidence.level.charAt(0).toUpperCase()+s.confidence.level.slice(1)})]}),s.confidence.factors.map((o,f)=>n.jsxs("div",{className:"pp-factor",children:[n.jsx("span",{className:"pp-factor-icon",children:o.impact==="positive"?"+":"-"}),n.jsx("span",{className:"pp-factor-signal",children:o.signal}),n.jsx("span",{className:"pp-factor-detail",children:o.detail})]},f))]}),n.jsxs("div",{className:"pp-section",children:[n.jsx("div",{className:"pp-section-title",children:"Source Attribution"}),s.sources.map((o,f)=>n.jsxs("div",{className:"pp-source-row",children:[n.jsx("span",{className:"pp-source-icon",children:Bx[o.type]??"❓"}),n.jsx("span",{className:"pp-source-label",children:o.label}),n.jsx("div",{className:"pp-source-bar-track",children:n.jsx("div",{className:"pp-source-bar",style:{width:`${Math.round(o.confidence*100)}%`}})}),n.jsx("span",{className:"pp-source-conf",children:o.confidence.toFixed(2)})]},f))]}),n.jsxs("div",{className:"pp-section",children:[n.jsx("div",{className:"pp-section-title",children:"Personality Influence"}),n.jsxs("div",{className:"pp-detail-row",children:[n.jsx("span",{className:"pp-detail-label",children:"Domain"}),n.jsx("span",{className:"pp-detail-value",children:s.personality.domain.replace(/_/g," ")})]}),n.jsxs("div",{className:"pp-detail-row",children:[n.jsx("span",{className:"pp-detail-label",children:"Register"}),n.jsx("span",{className:"pp-detail-value",children:s.personality.emotionalRegister})]}),s.personality.activeTraits.map((o,f)=>n.jsxs("div",{className:"pp-trait-row",children:[n.jsx("span",{className:"pp-trait-name",children:o.name}),n.jsx("div",{className:"pp-trait-bar-track",children:n.jsx("div",{className:"pp-trait-bar",style:{width:`${Math.round(o.weight*100)}%`}})}),n.jsx("span",{className:"pp-trait-weight",children:o.weight.toFixed(2)})]},f)),u&&n.jsxs("div",{className:"pp-kb-warning",children:["⚠"," Knowledge boundary: ",u.topic," (corrected ",u.corrections,"x)"]})]}),n.jsxs("div",{className:"pp-section",children:[n.jsx("div",{className:"pp-section-title",children:"Processing Pipeline"}),n.jsx("div",{className:"pp-pipeline",children:s.trace.enrichmentStages.map((o,f)=>n.jsxs("span",{className:"pp-pipeline-node",children:[f>0&&n.jsx("span",{className:"pp-pipeline-arrow",children:"→"}),n.jsx("span",{className:"pp-pipeline-stage",children:o})]},f))}),s.trace.toolsUsed.length>0&&n.jsxs("div",{className:"pp-detail-row",children:[n.jsx("span",{className:"pp-detail-label",children:"Tools"}),n.jsx("span",{className:"pp-detail-value",children:s.trace.toolsUsed.join(", ")})]}),n.jsxs("div",{className:"pp-detail-row",children:[n.jsx("span",{className:"pp-detail-label",children:"Model"}),n.jsxs("span",{className:"pp-detail-value",children:[s.model.provider," / ",s.model.model]})]}),n.jsxs("div",{className:"pp-detail-row",children:[n.jsx("span",{className:"pp-detail-label",children:"Latency"}),n.jsxs("span",{className:"pp-detail-value",children:[s.model.latencyMs.toLocaleString(),"ms"]})]}),n.jsxs("div",{className:"pp-detail-row",children:[n.jsx("span",{className:"pp-detail-label",children:"Tokens"}),n.jsxs("span",{className:"pp-detail-value",children:[s.model.tokens.input," in / ",s.model.tokens.output," out"]})]})]})]}),n.jsxs("div",{className:"pp-footer",children:["Total processing: ",s.trace.processingMs,"ms"]})]})]})}function Yx({tokens:s,cost:r,latencyMs:u}){const o=s.input+s.output;return o===0?null:n.jsxs("div",{className:"token-cost-badge",children:[n.jsxs("span",{className:"badge-item badge-tokens",title:`${s.input.toLocaleString()} in / ${s.output.toLocaleString()} out`,children:[o.toLocaleString()," tok"]}),n.jsxs("span",{className:"badge-item badge-cost",title:`$${r.input.toFixed(4)} in / $${r.output.toFixed(4)} out`,children:["$",r.total.toFixed(3)]}),n.jsxs("span",{className:"badge-item badge-latency",children:[u.toLocaleString(),"ms"]})]})}const Gx=[{command:"/help",description:"Show available commands"},{command:"/status",description:"Show system status"},{command:"/new",description:"Start a new session"},{command:"/reset",description:"Clear current session"},{command:"/mode",description:"Show current mode"},{command:"/mode auto",description:"Auto-detect mode from messages"},{command:"/mode off",description:"Disable modes for this session"},{command:"/mode operator",description:"Fast, action-oriented execution"},{command:"/mode analyst",description:"Deep reasoning and analysis"},{command:"/mode advisor",description:"Strategic guidance and decisions"},{command:"/mode writer",description:"Creative and polished writing"},{command:"/mode socratic",description:"Question-based learning"},{command:"/mode legal",description:"Legal research and analysis"},{command:"/mode roast",description:"Playful, witty critique"},{command:"/mode companion",description:"Warm, supportive conversation"}];function $x(s){return s.startsWith("claude-opus-4-6")?"Claude Opus 4.6":s.startsWith("claude-sonnet-4-5")?"Claude Sonnet 4.5":s.startsWith("claude-haiku-4-5")?"Claude Haiku 4.5":s.startsWith("claude-opus-4")?"Claude Opus 4":s.startsWith("claude-sonnet-4")?"Claude Sonnet 4":s.startsWith("claude-3-5-haiku")?"Claude Haiku 3.5":s.startsWith("claude-3-5-sonnet")?"Claude Sonnet 3.5":s.startsWith("claude-3-opus")?"Claude Opus 3":s==="gpt-4o"?"GPT-4o":s==="gpt-4o-mini"?"GPT-4o Mini":s==="gpt-4-turbo"?"GPT-4 Turbo":s.startsWith("o1")||s.startsWith("o3")?s.toUpperCase():s.startsWith("gemini-")?s.replace("gemini-","Gemini "):s}function Xx(s){const r=Date.now()-s,u=Math.floor(r/6e4);if(u<1)return"Just now";if(u<60)return`${u}m ago`;const o=Math.floor(u/60);if(o<24)return`${o}h ago`;const f=Math.floor(o/24);return f<7?`${f}d ago`:new Date(s).toLocaleDateString()}function Vx(s){let r=s.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">");return r=r.replace(/```(\w*)\n([\s\S]*?)```/g,(u,o,f)=>`<div class="code-block">${o?`<div class="code-header"><span class="code-lang">${o}</span><button class="code-copy" onclick="navigator.clipboard.writeText(this.closest('.code-block').querySelector('code').textContent)">Copy</button></div>`:`<div class="code-header"><button class="code-copy" onclick="navigator.clipboard.writeText(this.closest('.code-block').querySelector('code').textContent)">Copy</button></div>`}<pre><code>${f}</code></pre></div>`).replace(/`([^`]+)`/g,"<code>$1</code>").replace(/^### (.+)$/gm,"<h4>$1</h4>").replace(/^## (.+)$/gm,"<h3>$1</h3>").replace(/^# (.+)$/gm,"<h2>$1</h2>").replace(/\*\*\*(.+?)\*\*\*/g,"<strong><em>$1</em></strong>").replace(/\*\*(.+?)\*\*/g,"<strong>$1</strong>").replace(/\*(.+?)\*/g,"<em>$1</em>").replace(/^---$/gm,"<hr/>").replace(/^[-*] (.+)$/gm,"<li>$1</li>"),r=r.replace(/((?:<li>.*<\/li>\n?)+)/g,"<ul>$1</ul>"),r=r.replace(/\n\n+/g,"</p><p>"),r=r.replace(/\n/g,"<br/>"),r=`<p>${r}</p>`,r=r.replace(/<p><\/p>/g,"").replace(/<p>(<h[234]>)/g,"$1").replace(/(<\/h[234]>)<\/p>/g,"$1").replace(/<p>(<pre>)/g,"$1").replace(/(<\/pre>)<\/p>/g,"$1").replace(/<p>(<div class="code-block">)/g,"$1").replace(/(<\/div>)<\/p>/g,"$1").replace(/<p>(<ul>)/g,"$1").replace(/(<\/ul>)<\/p>/g,"$1").replace(/<p>(<hr\/>)/g,"$1").replace(/(<hr\/>)<\/p>/g,"$1"),r}function km(){var gn,vn,yn,ua,xn;const[s,r]=h.useState([]),[u,o]=h.useState(""),[f,m]=h.useState(!1),[p,x]=h.useState(!1),[y,g]=h.useState(""),[b,j]=h.useState(null),[S,w]=h.useState(""),[A,D]=h.useState("auto"),[O,E]=h.useState(0),[M,k]=h.useState(!1),[Z,K]=h.useState(!1),[q,W]=h.useState([]),[G,te]=h.useState(null),[ce,ie]=h.useState(!0),[he,ee]=h.useState(null),[oe,ve]=h.useState(null),[H,F]=h.useState(""),[le,I]=h.useState(null),de=h.useRef(null);h.useEffect(()=>{if(!le||!de.current)return;const R=de.current,ae=R.getBoundingClientRect();let{x:me,y:De}=le,Be=!1;ae.bottom>window.innerHeight&&(De=Math.max(4,le.y-ae.height),Be=!0),ae.right>window.innerWidth&&(me=Math.max(4,le.x-ae.width),Be=!0),Be&&(R.style.top=`${De}px`,R.style.left=`${me}px`)},[le]);const[C,L]=h.useState(void 0),[ne,re]=h.useState("standard"),[xe,be]=h.useState(null),[Ce,Pe]=h.useState(null),P=h.useRef(null),X=h.useRef(null),ge=h.useRef(null),qe=h.useRef(!0),$e=h.useRef(""),nt=h.useRef(0),Et=h.useRef(0),pa=h.useRef(null),qa=h.useRef(null),xt=h.useRef(null);ut(()=>J.getStatus(),[]);const{data:_e}=ut(()=>J.getModels(),[]),{data:mn}=ut(()=>J.getIdentity(),[]),{data:pn}=ut(()=>J.getPersonality(),[]);h.useEffect(()=>{xt.current=G},[G]),h.useEffect(()=>{J.getPersonalityEngine().then(R=>{var ae;(ae=R.data)!=null&&ae.engine&&re(R.data.engine)}).catch(()=>{})},[]),h.useEffect(()=>{J.getChats().then(async R=>{if(R.data&&R.data.length>0)W(R.data.map(ae=>{var me;return{id:ae.id,title:ae.title,updatedAt:ae.updatedAt,personality:(me=ae.metadata)==null?void 0:me.personality}})),te(R.data[0].id);else{const me=(await J.createNewChat()).data;W([{id:me.id,title:me.title,updatedAt:me.updatedAt}]),te(me.id),K(!0)}}).catch(()=>{})},[]),h.useEffect(()=>{if(!G){L(void 0);return}const R=q.find(ae=>ae.id===G);L(R==null?void 0:R.personality)},[G,q]),h.useEffect(()=>{if(p&&(Et.current=0,x(!1),$e.current=""),!G){r([]),K(!0);return}K(!1),J.getChatMessages(G).then(R=>{R.data?r(R.data.map(ae=>({id:ae.id,role:ae.role,content:ae.content}))):r([]),K(!0),requestAnimationFrame(()=>{var ae;(ae=X.current)==null||ae.scrollIntoView()})}).catch(()=>{r([]),K(!0)})},[G]),h.useEffect(()=>{if(s.length===0)return;const R=s[s.length-1];if(R.role!=="assistant")return;const ae=R.content.match(/Switched to \*\*(\w+)\*\* mode/);if(ae){D(ae[1].toLowerCase());return}if(R.content.includes("Mode set to **auto**")){D("auto");return}R.content.includes("Modes disabled")&&D("off")},[s]);const Vt=h.useMemo(()=>{if(!u.startsWith("/"))return[];const R=u.toLowerCase();return Gx.filter(ae=>ae.command.startsWith(R))},[u]);h.useEffect(()=>{k(Vt.length>0&&u.startsWith("/")),E(0)},[Vt,u]),h.useEffect(()=>{if(!M||!qa.current)return;const R=qa.current.children[O];R==null||R.scrollIntoView({block:"nearest"})},[O,M]);const Ms=h.useCallback(()=>{var R;qe.current&&((R=X.current)==null||R.scrollIntoView({behavior:"auto"}))},[]);h.useEffect(()=>{const R=ge.current;if(!R)return;const ae=De=>{De.deltaY<0&&(qe.current=!1)},me=()=>{const{scrollTop:De,scrollHeight:Be,clientHeight:wt}=R;Be-De-wt<40&&(qe.current=!0)};return R.addEventListener("wheel",ae,{passive:!0}),R.addEventListener("scroll",me,{passive:!0}),()=>{R.removeEventListener("wheel",ae),R.removeEventListener("scroll",me)}},[]),h.useEffect(()=>{Ms()},[s,Ms]),h.useEffect(()=>{if(!le)return;const R=()=>I(null);return document.addEventListener("click",R),()=>document.removeEventListener("click",R)},[le]),h.useEffect(()=>{const R=window.location.protocol==="https:"?"wss:":"ws:",ae=window.location.host,me=new WebSocket(`${R}//${ae}/`);return P.current=me,me.onopen=()=>m(!0),me.onclose=()=>{m(!1),x(!1)},me.onmessage=De=>{var Be,wt,Ol,Ml,Rl,Hn,qn,Dl,zl,na,lt;try{const we=JSON.parse(De.data);switch(we.type){case"connected":case"auth_success":break;case"chunk":if(g(""),nt.current!==Et.current||we.id!=null&&String(we.id)!==String(Et.current))break;$e.current+=((Be=we.payload)==null?void 0:Be.content)??"",r(ze=>{const Ee=ze[ze.length-1];return(Ee==null?void 0:Ee.role)==="assistant"&&Ee.id===`resp-${Et.current}`?[...ze.slice(0,-1),{...Ee,content:$e.current}]:[...ze,{id:`resp-${Et.current}`,role:"assistant",content:$e.current}]});break;case"message":((wt=we.payload)==null?void 0:wt.role)==="assistant"&&r(ze=>[...ze,{id:`msg-${Date.now()}`,role:"assistant",content:we.payload.content}]);break;case"tool_use":{const ze=((Ol=we.payload)==null?void 0:Ol.tool)??"tool",Ee=(Ml=we.payload)==null?void 0:Ml.params;let ga={web_browser:"Reading web page",browser_navigate:"Navigating browser",browser_click:"Clicking element",browser_type:"Typing text",browser_screenshot:"Taking screenshot",browser_extract:"Extracting data",browse:"Browsing",bash:"Running command",file_read:"Reading file",file_write:"Writing file",file_list:"Listing files"}[ze]||`Using ${ze}`;if(ze==="bash"&&(Ee!=null&&Ee.command)){const Tt=String(Ee.command);ga=`Running: ${Tt.length>60?Tt.slice(0,57)+"...":Tt}`}else if((ze==="web_browser"||ze==="browse")&&(Ee!=null&&Ee.url))try{ga=`Reading ${new URL(String(Ee.url)).hostname}`}catch{}else ze==="file_read"&&(Ee!=null&&Ee.path)&&(ga=`Reading ${String(Ee.path).split("/").pop()}`);g(ga);break}case"tool_result":g("");break;case"status":g(((Rl=we.payload)==null?void 0:Rl.message)??"Processing");break;case"done":{if(x(!1),g(""),$e.current="",nt.current!==Et.current||we.id!=null&&String(we.id)!==String(Et.current))break;const ze=(Hn=we.payload)==null?void 0:Hn.routing,Ee=(qn=we.payload)==null?void 0:qn.architect,Qt={};if(ze){const Tt=ze.model?`${ze.provider}/${ze.model}`:ze.provider;w(Tt),Qt.model=Tt}Ee&&(Qt.detectedContext=Ee.detectedContext,Qt.activeTraits=Ee.activeTraits,Qt.traitWeights=Ee.traitWeights,Qt.recommendation=Ee.recommendation);const ga=(Dl=we.payload)==null?void 0:Dl.transparency;if(ga&&(Qt.transparency=ga),Object.keys(Qt).length>0){const Tt=we.id!=null?String(we.id):null;r(St=>{const Yn=Tt?`resp-${Tt}`:null;let Ut=-1;for(let At=St.length-1;At>=0;At--)if(Yn?St[At].id===Yn:St[At].role==="assistant"){Ut=At;break}if(Ut===-1)return St;const va=St[Ut];if(va.role!=="assistant")return St;const Ga=St.slice(0,Ut).reverse().find(At=>At.role==="user");return Ga&&(Qt.userMessage=Ga.content),[...St.slice(0,Ut),{...va,...Qt},...St.slice(Ut+1)]})}break}case"chat_created":(zl=we.payload)!=null&&zl.chatId&&(te(we.payload.chatId),J.getChats().then(ze=>{ze.data&&W(ze.data.map(Ee=>({id:Ee.id,title:Ee.title,updatedAt:Ee.updatedAt})))}).catch(()=>{}));break;case"chat_titled":(na=we.payload)!=null&&na.chatId&&((lt=we.payload)!=null&<.title)&&W(ze=>ze.map(Ee=>Ee.id===we.payload.chatId?{...Ee,title:we.payload.title}:Ee));break;case"error":x(!1),g(""),$e.current="",r(ze=>{var Ee;return[...ze,{id:`err-${Date.now()}`,role:"error",content:((Ee=we.payload)==null?void 0:Ee.message)??"Unknown error"}]});break}}catch{}},()=>{me.close()}},[]);const vt=[];if(_e!=null&&_e.providers)for(const R of _e.providers)R.available&&R.models&&vt.push({provider:R.name,displayName:R.displayName||R.name,models:Object.keys(R.models)});const tc=R=>{if(!R){j(null);return}const[ae,...me]=R.split("/");j({provider:ae,model:me.join("/")})},Tl=()=>{if(!u.trim()||!P.current||!f)return;const R=u.trim(),ae=++nt.current;Et.current=ae,r(De=>[...De,{id:`user-${ae}`,role:"user",content:R}]),o(""),x(!0),$e.current="",qe.current=!0;const me={content:R};b&&(me.provider=b.provider,me.model=b.model),xt.current&&(me.chatId=xt.current),P.current.send(JSON.stringify({type:"message",id:String(ae),payload:me}))},Al=h.useCallback((R,ae,me)=>{be(null),ae==="conversation"&&(Pe(R),P.current&&f&&P.current.send(JSON.stringify({type:"message",id:String(++nt.current),payload:{content:`/context-override ${R}`,chatId:xt.current}}))),r(De=>{const Be=De.find(wt=>wt.id===me);return Be!=null&&Be.detectedContext&&Be.userMessage&&Be.detectedContext.domain!==R&&P.current&&f&&P.current.send(JSON.stringify({type:"architect_correction",payload:{userMessage:Be.userMessage,detectedDomain:Be.detectedContext.domain,correctedDomain:R}})),De.map(wt=>wt.id===me&&wt.detectedContext?{...wt,detectedContext:{...wt.detectedContext,domain:R},recommendation:void 0}:wt)})},[f]),Bn=h.useCallback((R,ae)=>{r(me=>{const De=me.find(Be=>Be.id===R);return De!=null&&De.detectedContext&&De.userMessage&&De.detectedContext.domain!==ae&&P.current&&f&&P.current.send(JSON.stringify({type:"architect_correction",payload:{userMessage:De.userMessage,detectedDomain:De.detectedContext.domain,correctedDomain:ae}})),me.map(Be=>Be.id===R?{...Be,detectedContext:Be.detectedContext?{...Be.detectedContext,domain:ae}:Be.detectedContext,recommendation:void 0}:Be)})},[f]),ac=h.useCallback(R=>{r(ae=>ae.map(me=>me.id===R?{...me,recommendation:void 0}:me))},[]),Rs=h.useCallback(()=>{Pe(null),P.current&&f&&P.current.send(JSON.stringify({type:"message",id:String(++nt.current),payload:{content:"/context-override clear",chatId:xt.current}}))},[f]),nc=h.useCallback(async R=>{if(!G)return;const ae=R||void 0;try{await J.updateChatPersonality(G,R||"standard"),L(ae),W(me=>me.map(De=>De.id===G?{...De,personality:ae}:De))}catch{}},[G]),lc=async()=>{var R;try{const me=(await J.createNewChat()).data;W(De=>[{id:me.id,title:me.title,updatedAt:me.updatedAt},...De]),te(me.id),r([]),Pe(null),be(null),K(!0),(R=pa.current)==null||R.focus()}catch{}},Ya=async R=>{if(!H.trim()){ve(null);return}try{await J.renameChat(R,H.trim()),W(ae=>ae.map(me=>me.id===R?{...me,title:H.trim()}:me))}catch{}ve(null)},bt=async R=>{try{await J.deleteChatThread(R),W(ae=>ae.filter(me=>me.id!==R)),G===R&&(te(null),r([]))}catch{}I(null)},ra=async R=>{try{await J.archiveChat(R),W(ae=>ae.filter(me=>me.id!==R)),G===R&&(te(null),r([]))}catch{}I(null)},jt=A==="auto"?"Auto":A==="off"?"Off":A.charAt(0).toUpperCase()+A.slice(1),sc=((gn=mn==null?void 0:mn.data)==null?void 0:gn.name)??"Auxiora",Ds=((yn=(vn=pn==null?void 0:pn.data)==null?void 0:vn.template)==null?void 0:yn.name)??null,ic=R=>({__html:Vx(R)});return n.jsxs("div",{className:"page",children:[n.jsx("h2",{children:"Chat"}),n.jsxs("div",{className:"chat-layout",children:[n.jsxs("div",{className:`chat-sidebar${ce?"":" closed"}`,children:[n.jsxs("div",{className:"chat-sidebar-header",children:[n.jsx("button",{className:"new-chat-btn",onClick:lc,children:"+ New Chat"}),n.jsx("button",{className:"sidebar-toggle",onClick:()=>ie(R=>!R),title:ce?"Hide sidebar":"Show sidebar",children:ce?"«":"»"})]}),ce&&n.jsxs("div",{className:"chat-sidebar-list",children:[q.map(R=>n.jsx("div",{className:`chat-sidebar-item${G===R.id?" active":""}`,onClick:()=>{oe!==R.id&&te(R.id)},onContextMenu:ae=>{ae.preventDefault(),I({chatId:R.id,x:ae.clientX,y:ae.clientY})},children:oe===R.id?n.jsx("input",{className:"chat-rename-input",value:H,onChange:ae=>F(ae.target.value),onKeyDown:ae=>{ae.key==="Enter"&&Ya(R.id),ae.key==="Escape"&&ve(null)},onBlur:()=>Ya(R.id),autoFocus:!0}):n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"chat-sidebar-title",children:R.title}),n.jsx("span",{className:"chat-sidebar-time",children:Xx(R.updatedAt)})]})},R.id)),q.length===0&&n.jsx("div",{className:"chat-sidebar-empty",children:"No chats yet"})]})]}),le&&Jy.createPortal(n.jsxs("div",{ref:de,className:"chat-context-menu",style:{position:"fixed",top:le.y,left:le.x},children:[n.jsx("button",{onClick:()=>{const R=q.find(ae=>ae.id===le.chatId);F((R==null?void 0:R.title)??""),ve(le.chatId),I(null)},children:"Rename"}),n.jsx("button",{onClick:()=>ra(le.chatId),children:"Archive"}),n.jsx("button",{className:"danger",onClick:()=>bt(le.chatId),children:"Delete"})]}),document.body),n.jsxs("div",{className:"chat-container",children:[n.jsxs("div",{className:"chat-status",children:[n.jsxs("span",{className:"chat-status-left",children:[n.jsx("span",{className:"chat-status-dot","data-connected":f}),n.jsx("span",{className:"chat-agent-name",children:sc}),n.jsx("span",{className:"chat-status-sep"}),n.jsxs("span",{className:"chat-status-label",children:["Mode: ",n.jsx("strong",{children:jt})]}),n.jsx("span",{className:"chat-status-sep"}),n.jsxs("span",{className:"chat-status-label",children:["Engine:"," ",n.jsxs("select",{className:"chat-personality-select",value:C??"",onChange:R=>nc(R.target.value),title:"Per-chat personality engine",children:[n.jsxs("option",{value:"",children:["Global (",ne==="the-architect"?"Architect":"Standard",")"]}),n.jsx("option",{value:"standard",children:"Standard"}),n.jsx("option",{value:"the-architect",children:"The Architect"})]})]}),Ds&&n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"chat-status-sep"}),n.jsxs("span",{className:"chat-status-label",children:["Personality: ",n.jsx("strong",{children:Ds})]})]})]}),n.jsxs("span",{className:"chat-status-right",children:[n.jsx("button",{className:"sidebar-toggle-inline",onClick:()=>ie(R=>!R),title:ce?"Hide sidebar":"Show sidebar",children:"☰"}),n.jsx("div",{className:"model-selector",children:n.jsxs("select",{value:b?`${b.provider}/${b.model}`:"",onChange:R=>tc(R.target.value),children:[n.jsx("option",{value:"",children:"Auto (router)"}),vt.map(R=>n.jsx("optgroup",{label:R.displayName,children:R.models.map(ae=>n.jsx("option",{value:`${R.provider}/${ae}`,children:$x(ae)},`${R.provider}/${ae}`))},R.provider))]})})]})]}),n.jsxs("div",{className:"chat-messages",ref:ge,children:[!G&&n.jsx("div",{style:{textAlign:"center",color:"var(--text-secondary)",padding:"2rem"},children:"Select a chat or create a new one"}),G&&!Z&&n.jsx("div",{style:{textAlign:"center",color:"var(--text-secondary)",padding:"2rem"},children:"Loading..."}),G&&Z&&s.length===0&&n.jsx("div",{style:{textAlign:"center",color:"var(--text-secondary)",padding:"2rem"},children:"Send a message to start chatting"}),Ce&&n.jsxs("div",{className:"context-override-banner",children:[n.jsxs("span",{children:["Context locked to ",((ua=_t[Ce])==null?void 0:ua.icon)??"🔒"," ",((xn=_t[Ce])==null?void 0:xn.label)??Ce]}),n.jsx("button",{className:"context-override-unlock",onClick:Rs,"aria-label":"Clear context override",children:"Tap to unlock"})]}),s.map(R=>n.jsxs("div",{className:`chat-message ${R.role}`,children:[R.role==="assistant"&&R.detectedContext&&n.jsxs("div",{className:"chat-context-row",children:[n.jsx(Ax,{context:R.detectedContext,onOverride:ae=>Al(ae,"message",R.id)}),n.jsx("button",{className:"context-override-trigger",onClick:()=>be(xe===R.id?null:R.id),"aria-label":"Override context",children:"✎"}),n.jsx(kx,{isOpen:xe===R.id,currentDomain:R.detectedContext.domain,onSelect:(ae,me)=>Al(ae,me,R.id),onClose:()=>be(null)})]}),R.role==="assistant"&&R.recommendation&&n.jsx(_x,{recommendation:R.recommendation,onAccept:ae=>Bn(R.id,ae),onDismiss:()=>ac(R.id)}),R.role==="assistant"?n.jsx("div",{className:"chat-markdown",dangerouslySetInnerHTML:ic(R.content)}):R.content,R.role==="assistant"&&R.activeTraits&&R.activeTraits.length>0&&n.jsx(zx,{sources:R.activeTraits,context:R.detectedContext,weights:R.traitWeights}),R.role==="assistant"&&R.transparency&&n.jsxs("div",{className:"chat-message-meta",children:[n.jsx(Yx,{tokens:R.transparency.model.tokens,cost:R.transparency.model.cost,latencyMs:R.transparency.model.latencyMs}),R.model&&n.jsx("span",{className:"model-label",children:R.model})]}),R.role==="assistant"&&!R.transparency&&R.model&&n.jsx("div",{className:"model-label",children:R.model}),R.role==="assistant"&&R.transparency&&n.jsx(Lx,{meta:R.transparency}),R.role==="assistant"&&R.transparency&&n.jsx("button",{className:"pp-trigger-btn",onClick:()=>ee(R.id),children:"Why?"})]},R.id)),p&&y&&n.jsxs("div",{className:"chat-tool-status",children:[n.jsx("span",{className:"tool-status-dot"}),y,"..."]}),n.jsx("div",{ref:X})]}),he&&(()=>{const R=s.find(ae=>ae.id===he);return R!=null&&R.transparency?n.jsx(qx,{meta:R.transparency,onClose:()=>ee(null)}):null})(),n.jsxs("div",{className:"chat-input-area",children:[n.jsxs("div",{className:"chat-input-wrapper",children:[M&&Vt.length>0&&n.jsx("div",{className:"slash-autocomplete",ref:qa,children:Vt.map((R,ae)=>n.jsxs("div",{className:`slash-ac-item${ae===O?" selected":""}`,onMouseEnter:()=>E(ae),onMouseDown:me=>{var De;me.preventDefault(),o(R.command),k(!1),(De=pa.current)==null||De.focus()},children:[n.jsx("span",{className:"slash-ac-cmd",children:R.command}),n.jsx("span",{className:"slash-ac-desc",children:R.description})]},R.command))}),n.jsx("input",{ref:pa,type:"text",value:u,onChange:R=>o(R.target.value),onKeyDown:R=>{if(M&&Vt.length>0){if(R.key==="ArrowDown"){R.preventDefault(),E(ae=>(ae+1)%Vt.length);return}if(R.key==="ArrowUp"){R.preventDefault(),E(ae=>(ae-1+Vt.length)%Vt.length);return}if(R.key==="Tab"||R.key==="Enter"&&Vt.length>1){R.preventDefault(),o(Vt[O].command),k(!1);return}if(R.key==="Escape"){R.preventDefault(),k(!1);return}}R.key==="Enter"&&Tl()},placeholder:G?f?"Type / for commands...":"Connecting...":"Select or create a chat...",disabled:!f||!G})]}),n.jsx("button",{onClick:Tl,disabled:!f||!u.trim()||!G,children:"Send"})]})]})]})]})}const Qx={active:"badge-green",paused:"badge-yellow",deleted:"badge-red",enabled:"badge-green",disabled:"badge-gray"};function _m({status:s}){const r=Qx[s]||"badge-gray";return n.jsx("span",{className:`badge ${r}`,children:s})}const Um=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],wu=Intl.DateTimeFormat().resolvedOptions().timeZone;function Kx(s,r,u,o,f){if(s==="custom")return f;if(s==="hourly")return"0 * * * *";if(s==="every-n-hours")return`0 */${u} * * *`;const[m,p]=r.split(":").map(Number),x=isNaN(p)?0:p,y=isNaN(m)?8:m;return s==="daily"?`${x} ${y} * * *`:s==="weekday"?`${x} ${y} * * 1-5`:s==="weekly"?`${x} ${y} * * ${o}`:f}function Lm(s){const r=s.trim().split(/\s+/);if(r.length!==5)return{freq:"custom",time:"08:00",everyNHours:2,weekday:1};const[u,o,f,m,p]=r;if(u==="0"&&o==="*"&&f==="*"&&m==="*"&&p==="*")return{freq:"hourly",time:"08:00",everyNHours:2,weekday:1};const x=o.match(/^\*\/(\d+)$/);if(u==="0"&&x&&f==="*"&&m==="*"&&p==="*")return{freq:"every-n-hours",time:"08:00",everyNHours:parseInt(x[1],10),weekday:1};const y=parseInt(u,10),g=parseInt(o,10);if(isNaN(y)||isNaN(g))return{freq:"custom",time:"08:00",everyNHours:2,weekday:1};const b=`${String(g).padStart(2,"0")}:${String(y).padStart(2,"0")}`;if(f==="*"&&m==="*"&&p==="*")return{freq:"daily",time:b,everyNHours:2,weekday:1};if(f==="*"&&m==="*"&&p==="1-5")return{freq:"weekday",time:b,everyNHours:2,weekday:1};const j=parseInt(p,10);return f==="*"&&m==="*"&&!isNaN(j)&&j>=0&&j<=6?{freq:"weekly",time:b,everyNHours:2,weekday:j}:{freq:"custom",time:b,everyNHours:2,weekday:1}}function Ih(s){const r=Lm(s);switch(r.freq){case"daily":return`Daily at ${r.time}`;case"weekday":return`Weekdays at ${r.time}`;case"hourly":return"Every hour";case"every-n-hours":return`Every ${r.everyNHours}h`;case"weekly":return`${Um[r.weekday]}s at ${r.time}`;default:return s}}function Bm(){const{data:s,refresh:r}=ut(()=>J.getBehaviors(),[]);Os(r);const[u,o]=h.useState("closed"),[f,m]=h.useState(null),[p,x]=h.useState("scheduled"),[y,g]=h.useState(""),[b,j]=h.useState("daily"),[S,w]=h.useState("08:00"),[A,D]=h.useState(2),[O,E]=h.useState(1),[M,k]=h.useState(""),[Z,K]=h.useState(wu),[q,W]=h.useState(5),[G,te]=h.useState(""),[ce,ie]=h.useState(""),[he,ee]=h.useState(!1),[oe,ve]=h.useState(""),[H,F]=h.useState(""),le=(s==null?void 0:s.data)??[],I=h.useMemo(()=>Kx(b,S,A,O,M),[b,S,A,O,M]),de=P=>{var X,ge;return(X=P.schedule)!=null&&X.cron?Ih(P.schedule.cron):P.polling?`Every ${Math.round(P.polling.intervalMs/6e4)}m`:(ge=P.delay)!=null&&ge.fireAt?new Date(P.delay.fireAt).toLocaleString():"-"},C=async P=>{try{const X=P.status==="active"?"paused":"active";await J.patchBehavior(P.id,{status:X}),r()}catch(X){alert(X.message||"Failed to update behavior")}},L=async P=>{var X;if(confirm(`Delete behavior "${(X=P.action)==null?void 0:X.slice(0,40)}"?`))try{await J.deleteBehavior(P.id),r()}catch(ge){alert(ge.message||"Failed to delete behavior")}},ne=()=>{m(null),x("scheduled"),g(""),j("daily"),w("08:00"),D(2),E(1),k(""),K(wu),W(5),te(""),ie(""),ve(""),F("")},re=()=>{ne(),o("create")},xe=P=>{var X,ge,qe;if(m(P.id),x(P.type??"scheduled"),g(P.action??""),(X=P.schedule)!=null&&X.cron){const $e=Lm(P.schedule.cron);j($e.freq),w($e.time),D($e.everyNHours),E($e.weekday),k($e.freq==="custom"?P.schedule.cron:"")}if(K(((ge=P.schedule)==null?void 0:ge.timezone)??wu),P.polling&&(W(Math.round(P.polling.intervalMs/6e4)),te(P.polling.condition??"")),(qe=P.delay)!=null&&qe.fireAt){const $e=new Date(P.delay.fireAt);ie($e.toISOString().slice(0,16))}ve(""),F(""),o("edit")},be=()=>{ne(),o("closed")},Ce=async P=>{P.preventDefault(),ve(""),F(""),ee(!0);try{const X={action:y};p==="scheduled"?(X.cron=I,X.timezone=Z):p==="monitor"?(X.intervalMinutes=q,X.condition=G):p==="one-shot"&&(X.runAt=ce),u==="edit"&&f?(await J.patchBehavior(f,X),F("Behavior updated")):(X.type=p,await J.createBehavior(X),F("Behavior created")),ne(),o("closed"),r()}catch(X){ve(X.message||`Failed to ${u==="edit"?"update":"create"} behavior`)}finally{ee(!1)}},Pe=b==="daily"||b==="weekday"||b==="weekly";return n.jsxs("div",{className:"page",children:[n.jsx("h2",{children:"Behaviors"}),n.jsx("div",{className:"create-form-toggle",children:n.jsx("button",{className:"btn-sm",onClick:()=>u!=="closed"?be():re(),children:u!=="closed"?"Cancel":"New Behavior"})}),u!=="closed"&&n.jsx("div",{className:"create-form",children:n.jsxs("form",{onSubmit:Ce,children:[n.jsx("h3",{children:u==="edit"?"Edit Behavior":"New Behavior"}),u==="create"&&n.jsxs(n.Fragment,{children:[n.jsx("label",{children:"Type"}),n.jsxs("select",{value:p,onChange:P=>x(P.target.value),children:[n.jsx("option",{value:"scheduled",children:"Scheduled"}),n.jsx("option",{value:"monitor",children:"Monitor (polling)"}),n.jsx("option",{value:"one-shot",children:"One-shot (run once)"})]})]}),n.jsx("label",{children:"Action"}),n.jsx("textarea",{value:y,onChange:P=>g(P.target.value),placeholder:"What should the agent do?",required:!0,rows:3}),p==="scheduled"&&n.jsxs("div",{className:"create-form-group",children:[n.jsx("label",{children:"How often?"}),n.jsxs("select",{value:b,onChange:P=>j(P.target.value),children:[n.jsx("option",{value:"daily",children:"Every day"}),n.jsx("option",{value:"weekday",children:"Every weekday (Mon-Fri)"}),n.jsx("option",{value:"weekly",children:"Once a week"}),n.jsx("option",{value:"hourly",children:"Every hour"}),n.jsx("option",{value:"every-n-hours",children:"Every few hours"}),n.jsx("option",{value:"custom",children:"Custom (cron)"})]}),b==="weekly"&&n.jsxs(n.Fragment,{children:[n.jsx("label",{children:"Day of week"}),n.jsx("select",{value:O,onChange:P=>E(Number(P.target.value)),children:Um.map((P,X)=>n.jsx("option",{value:X,children:P},X))})]}),Pe&&n.jsxs(n.Fragment,{children:[n.jsx("label",{children:"Time"}),n.jsx("input",{type:"time",value:S,onChange:P=>w(P.target.value),required:!0})]}),b==="every-n-hours"&&n.jsxs(n.Fragment,{children:[n.jsx("label",{children:"Every how many hours?"}),n.jsx("input",{type:"number",value:A,onChange:P=>D(Number(P.target.value)),min:1,max:23,required:!0})]}),b==="custom"&&n.jsxs(n.Fragment,{children:[n.jsx("label",{children:"Cron expression"}),n.jsx("input",{type:"text",value:M,onChange:P=>k(P.target.value),placeholder:"0 8 * * *",required:!0})]}),n.jsx("label",{children:"Timezone"}),n.jsx("input",{type:"text",value:Z,onChange:P=>K(P.target.value)}),n.jsxs("div",{className:"form-hint",children:["Schedule: ",n.jsx("strong",{children:Ih(I)})," (",Z,")"]})]}),p==="monitor"&&n.jsxs("div",{className:"create-form-group",children:[n.jsx("label",{children:"Check every (minutes)"}),n.jsx("input",{type:"number",value:q,onChange:P=>W(Number(P.target.value)),min:1,required:!0}),n.jsx("label",{children:"Condition"}),n.jsx("textarea",{value:G,onChange:P=>te(P.target.value),placeholder:"When should this trigger?",required:!0,rows:2})]}),p==="one-shot"&&n.jsxs("div",{className:"create-form-group",children:[n.jsx("label",{children:"Run at"}),n.jsx("input",{type:"datetime-local",value:ce,onChange:P=>ie(P.target.value),required:!0})]}),oe&&n.jsx("div",{className:"error",children:oe}),H&&n.jsx("div",{className:"settings-success",children:H}),n.jsx("button",{type:"submit",className:"settings-btn",disabled:he||!y,children:he?"Saving...":u==="edit"?"Save Changes":"Create Behavior"})]})}),le.length===0?n.jsx("div",{className:"bv-empty",children:"No behaviors configured yet."}):n.jsx("div",{className:"bv-list",children:le.map(P=>n.jsxs("div",{className:`bv-card ${P.status==="paused"?"bv-card--paused":""}`,children:[n.jsxs("div",{className:"bv-card-main",children:[n.jsx("div",{className:"bv-card-action",children:P.action}),n.jsxs("div",{className:"bv-card-meta",children:[n.jsx("span",{className:"bv-card-schedule",children:de(P)}),n.jsx(_m,{status:P.status}),n.jsx("span",{className:"bv-card-type",children:P.type})]}),n.jsxs("div",{className:"bv-card-stats",children:[n.jsxs("span",{children:[P.runCount??0," run",(P.runCount??0)!==1?"s":""]}),(P.failCount??0)>0&&n.jsxs("span",{className:"bv-card-fails",children:[P.failCount," failed"]}),P.lastRun&&n.jsxs("span",{className:"bv-card-lastrun",children:["Last: ",new Date(P.lastRun).toLocaleString()]})]})]}),n.jsxs("div",{className:"bv-card-actions",children:[n.jsx("button",{className:"btn-sm",onClick:()=>xe(P),children:"Edit"}),n.jsx("button",{className:"btn-sm",onClick:()=>C(P),children:P.status==="active"?"Pause":"Resume"}),n.jsx("button",{className:"btn-sm btn-danger",onClick:()=>L(P),children:"Delete"})]})]},P.id))})]})}function Hm({columns:s,rows:r,keyField:u,actions:o}){return n.jsxs("table",{className:"data-table",children:[n.jsx("thead",{children:n.jsxs("tr",{children:[s.map(f=>n.jsx("th",{children:f.label},f.key)),o&&n.jsx("th",{children:"Actions"})]})}),n.jsx("tbody",{children:r.length===0?n.jsx("tr",{children:n.jsx("td",{colSpan:s.length+(o?1:0),className:"empty-row",children:"No data"})}):r.map(f=>n.jsxs("tr",{children:[s.map(m=>n.jsx("td",{children:m.render?m.render(f):String(f[m.key]??"")},m.key)),o&&n.jsx("td",{className:"actions-cell",children:o(f)})]},f[u]))})]})}function qm(){const{data:s,refresh:r}=ut(()=>J.getWebhooks(),[]),{data:u}=ut(()=>J.getBehaviors(),[]);Os(r);const o=(s==null?void 0:s.data)??[],f=(u==null?void 0:u.data)??[],[m,p]=h.useState(!1),[x,y]=h.useState(""),[g,b]=h.useState(""),[j,S]=h.useState(""),[w,A]=h.useState(!1),[D,O]=h.useState(""),[E,M]=h.useState(""),k=[{key:"name",label:"Name"},{key:"type",label:"Type"},{key:"enabled",label:"Status",render:G=>n.jsx(_m,{status:G.enabled?"enabled":"disabled"})},{key:"behaviorId",label:"Behavior",render:G=>G.behaviorId||"-"},{key:"createdAt",label:"Created",render:G=>new Date(G.createdAt).toLocaleDateString()}],Z=async G=>{try{await J.patchWebhook(G.id,{enabled:!G.enabled}),r()}catch(te){alert(te.message||"Failed to update webhook")}},K=async G=>{if(confirm(`Delete webhook "${G.name}"?`))try{await J.deleteWebhook(G.id),r()}catch(te){alert(te.message||"Failed to delete webhook")}},q=()=>{y(""),b(""),S(""),O(""),M("")},W=async G=>{G.preventDefault(),O(""),M(""),A(!0);try{const te={name:x,secret:g};j&&(te.behaviorId=j),await J.createWebhook(te);const ce=`${window.location.origin}/api/v1/webhooks/custom/${x}`;M(ce),q(),p(!1),r()}catch(te){O(te.message||"Failed to create webhook")}finally{A(!1)}};return n.jsxs("div",{className:"page",children:[n.jsx("h2",{children:"Webhooks"}),n.jsx("div",{className:"create-form-toggle",children:n.jsx("button",{className:"btn-sm",onClick:()=>{p(!m),m&&q()},children:m?"Cancel":"New Webhook"})}),E&&n.jsxs("div",{className:"create-form-success",children:["Webhook created. URL: ",n.jsx("code",{children:E})]}),m&&n.jsx("div",{className:"create-form",children:n.jsxs("form",{onSubmit:W,children:[n.jsx("label",{children:"Name"}),n.jsx("input",{type:"text",value:x,onChange:G=>y(G.target.value),placeholder:"my-webhook",pattern:"[a-zA-Z0-9_-]+",title:"URL-safe: letters, numbers, hyphens, underscores",required:!0}),n.jsx("label",{children:"Secret"}),n.jsx("input",{type:"password",value:g,onChange:G=>b(G.target.value),placeholder:"HMAC signing key",required:!0}),n.jsx("label",{children:"Behavior (optional)"}),n.jsxs("select",{value:j,onChange:G=>S(G.target.value),children:[n.jsx("option",{value:"",children:"None"}),f.map(G=>{var te;return n.jsx("option",{value:G.id,children:((te=G.action)==null?void 0:te.slice(0,50))||G.id},G.id)})]}),D&&n.jsx("div",{className:"error",children:D}),n.jsx("button",{type:"submit",className:"settings-btn",disabled:w||!x||!g,children:w?"Creating...":"Create Webhook"})]})}),n.jsx(Hm,{columns:k,rows:o,keyField:"id",actions:G=>n.jsxs(n.Fragment,{children:[n.jsx("button",{className:"btn-sm",onClick:()=>Z(G),children:G.enabled?"Disable":"Enable"}),n.jsx("button",{className:"btn-sm btn-danger",onClick:()=>K(G),children:"Delete"})]})})]})}const Zx=["professional","apologetic","matter_of_fact","self_deprecating","gentle","detailed","encouraging","terse","educational"],Jx=["she/her","he/him","they/them","it/its"],Wx=["greeting","farewell","thinking","success","error"],Fx=[{key:"warmth",label:"Warmth",low:"Reserved",high:"Warm"},{key:"directness",label:"Directness",low:"Gentle",high:"Direct"},{key:"humor",label:"Humor",low:"Serious",high:"Playful"},{key:"formality",label:"Formality",low:"Casual",high:"Formal"}];function Tu({tags:s,onChange:r,placeholder:u}){const[o,f]=h.useState(""),m=x=>{if(x.key==="Enter"){x.preventDefault();const y=o.trim();y&&!s.includes(y)&&r([...s,y]),f("")}else x.key==="Backspace"&&o===""&&s.length>0&&r(s.slice(0,-1))},p=x=>{r(s.filter((y,g)=>g!==x))};return n.jsxs("div",{className:"tag-input-container",children:[n.jsx("div",{className:"tag-list",children:s.map((x,y)=>n.jsxs("span",{className:"tag",children:[x,n.jsx("button",{type:"button",className:"tag-remove",onClick:()=>p(y),"aria-label":`Remove ${x}`,children:"x"})]},y))}),n.jsx("input",{className:"tag-input",type:"text",value:o,onChange:x=>f(x.target.value),onKeyDown:m,placeholder:u??"Type and press Enter"})]})}function Px({label:s,low:r,high:u,value:o,onChange:f}){const m=Math.round(o*100);return n.jsxs("div",{className:"tone-slider",children:[n.jsxs("div",{className:"tone-slider-header",children:[n.jsx("span",{className:"tone-label",children:s}),n.jsxs("span",{className:"tone-value",children:[m,"%"]})]}),n.jsxs("div",{className:"tone-slider-row",children:[n.jsx("span",{className:"tone-extreme",children:r}),n.jsx("input",{className:"slider",type:"range",min:0,max:100,value:m,onChange:p=>f(Number(p.target.value)/100)}),n.jsx("span",{className:"tone-extreme",children:u})]})]})}const Ix={name:"",pronouns:"they/them",avatar:null,vibe:"",tone:{warmth:.5,directness:.5,humor:.5,formality:.5},errorStyle:"professional",expertise:[],catchphrases:{greeting:"",farewell:"",thinking:"",success:"",error:""},boundaries:{neverJokeAbout:[],neverAdviseOn:[]},customInstructions:"",soulContent:null,activeTemplate:null};function Ym(){const[s,r]=h.useState(null),[u,o]=h.useState(Ix),[f,m]=h.useState(null),[p,x]=h.useState(!1),[y,g]=h.useState(!1),[b,j]=h.useState(""),[S,w]=h.useState(""),[A,D]=h.useState("");h.useEffect(()=>{J.getPersonalityFull().then(ee=>{var H,F,le,I,de,C,L;const oe=ee.data,ve={name:oe.name??"",pronouns:oe.pronouns??"they/them",avatar:oe.avatar??null,vibe:oe.vibe??"",tone:oe.tone??{warmth:.5,directness:.5,humor:.5,formality:.5},errorStyle:oe.errorStyle??"professional",expertise:oe.expertise??[],catchphrases:{greeting:((H=oe.catchphrases)==null?void 0:H.greeting)??"",farewell:((F=oe.catchphrases)==null?void 0:F.farewell)??"",thinking:((le=oe.catchphrases)==null?void 0:le.thinking)??"",success:((I=oe.catchphrases)==null?void 0:I.success)??"",error:((de=oe.catchphrases)==null?void 0:de.error)??""},boundaries:{neverJokeAbout:((C=oe.boundaries)==null?void 0:C.neverJokeAbout)??[],neverAdviseOn:((L=oe.boundaries)==null?void 0:L.neverAdviseOn)??[]},customInstructions:oe.customInstructions??"",soulContent:oe.soulContent??null,activeTemplate:oe.activeTemplate??null};o(ve),r(ve),m(ve.activeTemplate)}).catch(ee=>D(ee.message))},[]);const{data:O,loading:E}=ut(()=>J.getTemplates(),[]),M=(O==null?void 0:O.data)??[],Z=h.useCallback(()=>s?f!==s.activeTemplate?!0:JSON.stringify(u)!==JSON.stringify(s):!1,[u,s,f])(),K=(ee,oe)=>{o(ve=>({...ve,[ee]:oe}))},q=(ee,oe)=>{o(ve=>({...ve,tone:{...ve.tone,[ee]:oe}}))},W=(ee,oe)=>{o(ve=>({...ve,catchphrases:{...ve.catchphrases,[ee]:oe}}))},G=(ee,oe)=>{o(ve=>({...ve,boundaries:{...ve.boundaries,[ee]:oe}}))},te=async()=>{g(!0),w(""),j("");try{const ee={name:u.name,pronouns:u.pronouns,avatar:u.avatar,vibe:u.vibe,tone:u.tone,errorStyle:u.errorStyle,expertise:u.expertise,catchphrases:u.catchphrases,boundaries:u.boundaries,customInstructions:u.customInstructions,soulContent:u.soulContent};f!==(s==null?void 0:s.activeTemplate)&&(ee.activeTemplate=f),await J.updatePersonalityFull(ee);const oe={...u,activeTemplate:f};r(oe),j("Personality settings saved successfully")}catch(ee){w(ee instanceof Error?ee.message:"Failed to save")}finally{g(!1)}},[ce,ie]=h.useState(!1);if(h.useEffect(()=>{if(!u.avatar){ie(!1);return}try{new URL(u.avatar),ie(!0)}catch{ie(!1)}},[u.avatar]),A)return n.jsx("div",{className:"page",children:n.jsxs("div",{className:"error",children:["Failed to load personality data: ",A]})});if(!s)return n.jsx("div",{className:"page",children:n.jsx("p",{children:"Loading personality settings..."})});const he=n.jsx("button",{className:"settings-btn",onClick:te,disabled:y||!Z,children:y?"Saving...":"Save Changes"});return n.jsxs("div",{className:"page",children:[n.jsxs("div",{className:"page-header",children:[n.jsx("h2",{children:"Personality Editor"}),Z&&he]}),b&&n.jsx("div",{className:"settings-success",children:b}),S&&n.jsx("div",{className:"error",children:S}),n.jsxs("div",{className:"settings-form",children:[n.jsxs("div",{className:"editor-section",children:[n.jsx("h3",{children:"Identity"}),n.jsxs("div",{className:"form-grid",children:[n.jsxs("div",{className:"form-field",children:[n.jsx("label",{children:"Name"}),n.jsx("input",{type:"text",value:u.name,onChange:ee=>K("name",ee.target.value),placeholder:"Agent name"})]}),n.jsxs("div",{className:"form-field",children:[n.jsx("label",{children:"Pronouns"}),n.jsx("select",{value:u.pronouns,onChange:ee=>K("pronouns",ee.target.value),children:Jx.map(ee=>n.jsx("option",{value:ee,children:ee},ee))})]}),n.jsxs("div",{className:"form-field full-width",children:[n.jsx("label",{children:"Vibe"}),n.jsx("input",{type:"text",value:u.vibe,onChange:ee=>{ee.target.value.length<=200&&K("vibe",ee.target.value)},placeholder:"A short description of the assistant's personality vibe",maxLength:200}),n.jsxs("span",{className:"field-hint",children:[u.vibe.length,"/200 characters"]})]}),n.jsxs("div",{className:"form-field full-width",children:[n.jsx("label",{children:"Avatar URL"}),n.jsx("input",{type:"text",value:u.avatar??"",onChange:ee=>K("avatar",ee.target.value||null),placeholder:"https://example.com/avatar.png"}),ce&&u.avatar&&n.jsx("img",{src:u.avatar,alt:"Avatar preview",style:{width:64,height:64,borderRadius:8,marginTop:8,objectFit:"cover"},onError:()=>ie(!1)})]})]})]}),n.jsxs("div",{className:"editor-section",children:[n.jsx("h3",{children:"Tone"}),n.jsx("div",{className:"tone-sliders",children:Fx.map(ee=>n.jsx(Px,{label:ee.label,low:ee.low,high:ee.high,value:u.tone[ee.key],onChange:oe=>q(ee.key,oe)},ee.key))})]}),n.jsxs("div",{className:"editor-section",children:[n.jsx("h3",{children:"Quick Start Templates"}),E&&n.jsx("p",{children:"Loading templates..."}),n.jsx("div",{className:"template-grid",children:M.map(ee=>n.jsxs("div",{className:`template-card${f===ee.id?" selected":""}`,onClick:()=>m(ee.id),children:[n.jsx("h4",{children:ee.name}),n.jsx("p",{children:ee.description})]},ee.id))})]}),n.jsxs("div",{className:"editor-section",children:[n.jsx("h3",{children:"Behavior"}),n.jsxs("div",{className:"form-grid",children:[n.jsxs("div",{className:"form-field",children:[n.jsx("label",{children:"Error Style"}),n.jsx("select",{value:u.errorStyle,onChange:ee=>K("errorStyle",ee.target.value),children:Zx.map(ee=>n.jsx("option",{value:ee,children:ee.replace(/_/g," ")},ee))})]}),n.jsxs("div",{className:"form-field full-width",children:[n.jsx("label",{children:"Expertise Areas"}),n.jsx(Tu,{tags:u.expertise,onChange:ee=>K("expertise",ee),placeholder:"Add expertise area and press Enter"})]}),n.jsxs("div",{className:"form-field full-width",children:[n.jsx("label",{children:"Catchphrases"}),n.jsx("div",{className:"catchphrase-grid",children:Wx.map(ee=>n.jsxs("div",{className:"catchphrase-row",children:[n.jsx("span",{className:"catchphrase-label",children:ee}),n.jsx("input",{type:"text",value:u.catchphrases[ee]??"",onChange:oe=>W(ee,oe.target.value),placeholder:`${ee} phrase`})]},ee))})]}),n.jsxs("div",{className:"form-field full-width",children:[n.jsx("label",{children:"Never Joke About"}),n.jsx(Tu,{tags:u.boundaries.neverJokeAbout,onChange:ee=>G("neverJokeAbout",ee),placeholder:"Add topic and press Enter"})]}),n.jsxs("div",{className:"form-field full-width",children:[n.jsx("label",{children:"Never Advise On"}),n.jsx(Tu,{tags:u.boundaries.neverAdviseOn,onChange:ee=>G("neverAdviseOn",ee),placeholder:"Add topic and press Enter"})]})]})]}),n.jsxs("div",{className:"editor-section",children:[n.jsx("h3",{children:"Custom Instructions"}),n.jsxs("div",{className:"form-field full-width",children:[n.jsx("textarea",{className:"custom-instructions-textarea",rows:6,value:u.customInstructions,onChange:ee=>{ee.target.value.length<=4e3&&K("customInstructions",ee.target.value)},maxLength:4e3,placeholder:"Add any custom instructions for the assistant..."}),n.jsxs("span",{className:"field-hint",children:[u.customInstructions.length,"/4000 characters. These instructions are always included in the system prompt and guide the assistant's overall behavior."]})]})]}),n.jsxs("div",{className:"editor-section",children:[n.jsxs("h3",{children:["Advanced",n.jsxs("button",{type:"button",className:"section-toggle",onClick:()=>x(!p),children:[p?"Hide":"Show"," Raw SOUL.md"]})]}),p&&n.jsxs(n.Fragment,{children:[n.jsx("p",{className:"field-hint",style:{marginBottom:"0.5rem"},children:"Warning: selecting a template will overwrite manual edits to this content."}),n.jsx("textarea",{className:"soul-editor-textarea",rows:16,value:u.soulContent??"",onChange:ee=>K("soulContent",ee.target.value||null),placeholder:"Raw SOUL.md content...",style:{fontFamily:"monospace"}})]})]}),Z&&n.jsx("div",{className:"editor-footer",children:he})]})]})}const Ki=[{id:"anthropic",label:"Anthropic (Claude)",needsKey:!0},{id:"claudeOAuth",label:"Claude (OAuth)",needsKey:!1,needsOAuth:!0},{id:"openai",label:"OpenAI",needsKey:!0},{id:"google",label:"Google (Gemini)",needsKey:!0},{id:"ollama",label:"Ollama (Local)",needsKey:!1,needsEndpoint:!0},{id:"groq",label:"Groq",needsKey:!0},{id:"deepseek",label:"DeepSeek",needsKey:!0},{id:"cohere",label:"Cohere",needsKey:!0},{id:"xai",label:"xAI (Grok)",needsKey:!0},{id:"openaiCompatible",label:"OpenAI-Compatible",needsKey:!0,needsEndpoint:!0},{id:"openrouter",label:"OpenRouter",needsKey:!0},{id:"huggingface",label:"HuggingFace",needsKey:!0}];function Es(s){return s.startsWith("claude-opus-4-6")?"Claude Opus 4.6":s.startsWith("claude-sonnet-4-5")?"Claude Sonnet 4.5":s.startsWith("claude-haiku-4-5")?"Claude Haiku 4.5":s.startsWith("claude-opus-4")?"Claude Opus 4":s.startsWith("claude-sonnet-4")?"Claude Sonnet 4":s.startsWith("claude-3-5-haiku")?"Claude Haiku 3.5":s.startsWith("claude-3-5-sonnet")?"Claude Sonnet 3.5":s.startsWith("claude-3-opus")?"Claude Opus 3":s==="gpt-4o"?"GPT-4o":s==="gpt-4o-mini"?"GPT-4o Mini":s==="gpt-4-turbo"?"GPT-4 Turbo":s.startsWith("o1")||s.startsWith("o3")?s.toUpperCase():s.startsWith("gemini-")?s.replace("gemini-","Gemini "):s}function Gm(){const{data:s,refresh:r}=ut(()=>J.getModels(),[]),[u,o]=h.useState(null),[f,m]=h.useState(!1),[p,x]=h.useState(""),[y,g]=h.useState(""),[b,j]=h.useState(!1),[S,w]=h.useState(""),[A,D]=h.useState(!1),[O,E]=h.useState(!1),[M,k]=h.useState(""),[Z,K]=h.useState(""),[q,W]=h.useState(!1),[G,te]=h.useState(""),[ce,ie]=h.useState(""),[he,ee]=h.useState(""),[oe,ve]=h.useState(!1),H=(s==null?void 0:s.providers)??[],F=(s==null?void 0:s.routing)??{enabled:!1,primary:"",fallback:""},le=(s==null?void 0:s.cost)??{today:0,thisMonth:0,isOverBudget:!1,warningThresholdReached:!1};h.useEffect(()=>{F.primary&&k(F.primary),F.fallback&&K(F.fallback)},[F.primary,F.fallback]),h.useEffect(()=>{J.getClaudeOAuthStatus().then(X=>E(X.connected)).catch(X=>console.error("Failed to check OAuth status:",X))},[]);const I=new Set(H.filter(X=>X.available).map(X=>X.name)),de=X=>{const ge=H.find(qe=>qe.name===X);return ge!=null&&ge.models?Object.keys(ge.models):[]},C=[];for(const X of H){if(!X.available||!X.models)continue;const ge=Ki.find(qe=>qe.id===X.name);for(const qe of Object.keys(X.models))C.push({provider:X.name,providerLabel:(ge==null?void 0:ge.label)??X.displayName??X.name,model:qe})}const L=X=>{u===X?o(null):(o(X),te(""),ie(""),ee(""),g(""),x(""))},ne=async X=>{m(!0),g(""),x("");try{const ge=Ki.find(qe=>qe.id===X);await J.configureProvider(X,ge!=null&&ge.needsKey&&G||void 0,ge!=null&&ge.needsEndpoint&&ce||void 0),he&&await J.setProviderModel(X,he),x(`${(ge==null?void 0:ge.label)??X} configured successfully`),te(""),await r()}catch(ge){g(ge.message)}finally{m(!1)}},re=async()=>{j(!0),g(""),x("");try{const{authUrl:X}=await J.startClaudeOAuth();window.open(X,"_blank"),D(!0)}catch(X){g(X instanceof Error?X.message:"Failed to start OAuth")}finally{j(!1)}},xe=async()=>{if(S.trim()){m(!0),g(""),x("");try{await J.completeClaudeOAuth(S.trim()),x("Claude OAuth connected successfully"),D(!1),w(""),E(!0),await r()}catch(X){g(X instanceof Error?X.message:"Failed to complete OAuth")}finally{m(!1)}}},be=async()=>{m(!0),g(""),x("");try{await J.disconnectClaudeOAuth(),x("Claude OAuth disconnected"),E(!1),await r()}catch(X){g(X instanceof Error?X.message:"Failed to disconnect OAuth")}finally{m(!1)}},Ce=async()=>{W(!0),g(""),x("");try{await J.updateRouting(M,Z||void 0),x("Routing updated"),await r()}catch(X){g(X.message)}finally{W(!1)}},Pe=async X=>{if(!X)return;const[ge,...qe]=X.split("/"),$e=qe.join("/");ve(!0),g(""),x("");try{await J.setProviderModel(ge,$e),ge!==F.primary&&await J.updateRouting(ge,F.primary||void 0),x(`Switched to ${Es($e)}`),await r()}catch(nt){g(nt.message)}finally{ve(!1)}},P=H.filter(X=>X.available);return n.jsxs("div",{className:"page",children:[n.jsx("h2",{children:"Providers"}),C.length>0&&n.jsxs("div",{className:"settings-section",children:[n.jsx("h3",{children:"Active Model"}),n.jsx("p",{style:{color:"var(--text-secondary)",fontSize:"0.85rem",marginBottom:"0.75rem"},children:"Choose which AI model to use. This changes the default for all new messages."}),n.jsx("div",{className:"routing-config",children:n.jsxs("div",{className:"routing-field",style:{flex:2},children:[n.jsx("label",{children:"Model"}),n.jsxs("select",{onChange:X=>Pe(X.target.value),disabled:oe,defaultValue:"",children:[n.jsx("option",{value:"",disabled:!0,children:"Select a model..."}),P.map(X=>{const ge=de(X.name);if(ge.length===0)return null;const qe=Ki.find($e=>$e.id===X.name);return n.jsx("optgroup",{label:(qe==null?void 0:qe.label)??X.displayName??X.name,children:ge.map($e=>n.jsx("option",{value:`${X.name}/${$e}`,children:Es($e)},`${X.name}/${$e}`))},X.name)})]})]})}),p&&n.jsx("div",{className:"settings-success",children:p}),y&&n.jsx("div",{className:"error",children:y})]}),P.length>1&&n.jsxs("div",{className:"settings-section",children:[n.jsx("h3",{children:"Provider Routing"}),n.jsx("p",{style:{color:"var(--text-secondary)",fontSize:"0.85rem",marginBottom:"0.75rem"},children:"Set primary and fallback providers. Fallback is used when the primary is unavailable."}),n.jsxs("div",{className:"routing-config",children:[n.jsxs("div",{className:"routing-field",children:[n.jsx("label",{children:"Primary Provider"}),n.jsxs("select",{value:M,onChange:X=>k(X.target.value),children:[n.jsx("option",{value:"",children:"Select..."}),P.map(X=>n.jsx("option",{value:X.name,children:X.displayName||X.name},X.name))]})]}),n.jsxs("div",{className:"routing-field",children:[n.jsx("label",{children:"Fallback Provider"}),n.jsxs("select",{value:Z,onChange:X=>K(X.target.value),children:[n.jsx("option",{value:"",children:"None"}),P.filter(X=>X.name!==M).map(X=>n.jsx("option",{value:X.name,children:X.displayName||X.name},X.name))]})]}),n.jsx("button",{onClick:Ce,disabled:q||!M,children:q?"Saving...":"Save Routing"})]})]}),n.jsxs("div",{className:"settings-section",children:[n.jsx("h3",{children:"Usage"}),n.jsxs("div",{className:"cost-summary",children:[n.jsxs("div",{className:`cost-box${le.isOverBudget?" over-budget":""}`,children:[n.jsx("h4",{children:"Today"}),n.jsxs("div",{className:"cost-value",children:["$",le.today.toFixed(2)]})]}),n.jsxs("div",{className:`cost-box${le.isOverBudget?" over-budget":""}`,children:[n.jsx("h4",{children:"This Month"}),n.jsxs("div",{className:"cost-value",children:["$",le.thisMonth.toFixed(2)]})]}),n.jsxs("div",{className:"cost-box",children:[n.jsx("h4",{children:"Budget Status"}),n.jsx("div",{className:"cost-value",style:{fontSize:"0.95rem"},children:le.isOverBudget?"Over Budget":le.warningThresholdReached?"Warning":"OK"})]})]})]}),n.jsxs("div",{className:"settings-section",children:[n.jsx("h3",{children:"Manage Providers"}),n.jsx("p",{style:{color:"var(--text-secondary)",fontSize:"0.85rem",marginBottom:"0.75rem"},children:"Click a card to configure API keys and endpoints."}),n.jsx("div",{className:"provider-grid",children:Ki.map(X=>{const ge=H.find(_e=>_e.name===X.id),qe=I.has(X.id),nt=X.id==="claudeOAuth"?O:qe,Et=F.primary===X.id,pa=F.fallback===X.id,qa=u===X.id,xt=de(X.id);return n.jsxs("div",{className:`provider-card${nt?" configured":""}${qa?" expanded":""}`,onClick:()=>L(X.id),children:[n.jsxs("div",{className:"provider-card-header",children:[n.jsxs("h3",{children:[n.jsx("span",{className:`status-dot ${nt?"active":"inactive"}`}),nt&&(ge!=null&&ge.displayName)?ge.displayName:X.label]}),n.jsxs("div",{className:"provider-badges",children:[Et&&n.jsx("span",{className:"badge-pill badge-primary",children:"Primary"}),pa&&n.jsx("span",{className:"badge-pill badge-fallback",children:"Fallback"})]})]}),n.jsxs("div",{className:"provider-model",children:[nt?xt.length>0?xt.map(_e=>Es(_e)).join(", "):"Active":"Not configured",(ge==null?void 0:ge.credentialSource)==="claude-cli"&&n.jsx("span",{style:{marginLeft:"0.5rem",fontSize:"0.75rem",color:"var(--accent)"},children:"(Claude Code CLI)"}),(ge==null?void 0:ge.credentialSource)==="oauth"&&n.jsx("span",{style:{marginLeft:"0.5rem",fontSize:"0.75rem",color:"var(--accent)"},children:"(OAuth)"})]}),qa&&n.jsx("div",{className:"provider-expand",onClick:_e=>_e.stopPropagation(),children:X.needsOAuth?n.jsx(n.Fragment,{children:O?n.jsxs(n.Fragment,{children:[n.jsx("p",{style:{color:"var(--text-secondary)",fontSize:"0.85rem",marginBottom:"0.75rem"},children:"Connected via Claude OAuth. Your Claude Pro/Max subscription is being used."}),xt.length>0&&n.jsxs(n.Fragment,{children:[n.jsx("label",{children:"Default Model"}),n.jsxs("select",{value:he,onChange:_e=>ee(_e.target.value),children:[n.jsx("option",{value:"",children:"Keep current"}),xt.map(_e=>n.jsx("option",{value:_e,children:Es(_e)},_e))]})]}),n.jsx("div",{className:"provider-actions",children:n.jsx("button",{className:"btn-save",onClick:be,disabled:f,style:{background:"var(--error, #e74c3c)"},children:f?"Disconnecting...":"Disconnect"})})]}):A?n.jsxs(n.Fragment,{children:[n.jsx("p",{style:{color:"var(--text-secondary)",fontSize:"0.85rem",marginBottom:"0.75rem"},children:"Authorize in the browser tab that opened, then paste the code below."}),n.jsx("label",{children:"Authorization Code"}),n.jsx("input",{type:"text",value:S,onChange:_e=>w(_e.target.value),placeholder:"Paste the code from claude.ai",autoFocus:!0}),n.jsxs("div",{className:"provider-actions",children:[n.jsx("button",{className:"btn-save",onClick:xe,disabled:f||!S.trim(),children:f?"Connecting...":"Complete Connection"}),n.jsx("button",{onClick:()=>{D(!1),w("")},style:{marginLeft:"0.5rem"},children:"Cancel"})]})]}):n.jsxs(n.Fragment,{children:[n.jsx("p",{style:{color:"var(--text-secondary)",fontSize:"0.85rem",marginBottom:"0.75rem"},children:"Connect your Claude Pro or Max subscription. No API key needed."}),n.jsx("div",{className:"provider-actions",children:n.jsx("button",{className:"btn-save",onClick:re,disabled:b,children:b?"Opening...":"Connect with Claude"})})]})}):n.jsxs(n.Fragment,{children:[X.needsKey&&n.jsxs(n.Fragment,{children:[n.jsx("label",{children:"API Key"}),n.jsx("input",{type:"password",value:G,onChange:_e=>te(_e.target.value),placeholder:qe?"•••••••• (leave blank to keep)":"Enter API key"})]}),X.needsEndpoint&&n.jsxs(n.Fragment,{children:[n.jsx("label",{children:"Endpoint URL"}),n.jsx("input",{type:"text",value:ce,onChange:_e=>ie(_e.target.value),placeholder:X.id==="ollama"?"http://localhost:11434":"https://..."})]}),xt.length>0&&n.jsxs(n.Fragment,{children:[n.jsx("label",{children:"Default Model"}),n.jsxs("select",{value:he,onChange:_e=>ee(_e.target.value),children:[n.jsx("option",{value:"",children:"Keep current"}),xt.map(_e=>n.jsx("option",{value:_e,children:Es(_e)},_e))]})]}),n.jsx("div",{className:"provider-actions",children:n.jsx("button",{className:"btn-save",onClick:()=>ne(X.id),disabled:f||!G&&X.needsKey&&!qe&&!X.needsEndpoint,children:f?"Saving...":"Save"})})]})})]},X.id)})})]})]})}const em=[{type:"discord",label:"Discord",fields:[{key:"botToken",label:"Bot Token",secret:!0}]},{type:"telegram",label:"Telegram",fields:[{key:"botToken",label:"Bot Token",secret:!0}]},{type:"slack",label:"Slack",fields:[{key:"botToken",label:"Bot Token",secret:!0},{key:"appToken",label:"App Token",secret:!0}]},{type:"twilio",label:"Twilio",fields:[{key:"accountSid",label:"Account SID",secret:!1},{key:"authToken",label:"Auth Token",secret:!0}]},{type:"matrix",label:"Matrix",fields:[{key:"accessToken",label:"Access Token",secret:!0}]},{type:"email",label:"Email",fields:[{key:"imapHost",label:"IMAP Host",secret:!1},{key:"imapPort",label:"IMAP Port",secret:!1},{key:"smtpHost",label:"SMTP Host",secret:!1},{key:"smtpPort",label:"SMTP Port",secret:!1},{key:"email",label:"Email Address",secret:!1},{key:"password",label:"Password (App Password for Gmail)",secret:!0}]}];function $m(){var D,O;const{data:s}=ut(()=>J.getChannels(),[]),r=((D=s==null?void 0:s.data)==null?void 0:D.connected)??[],u=((O=s==null?void 0:s.data)==null?void 0:O.configured)??[],[o,f]=h.useState({}),[m,p]=h.useState(!1),[x,y]=h.useState(""),[g,b]=h.useState(""),j=E=>{if(o[E])return o[E];const M=u.find(k=>k.type===E);return{enabled:(M==null?void 0:M.enabled)??!1,credentials:{}}},S=E=>{const M=j(E);f(k=>({...k,[E]:{...M,enabled:!M.enabled}}))},w=(E,M,k)=>{const Z=j(E);f(K=>({...K,[E]:{...Z,credentials:{...Z.credentials,[M]:k}}}))},A=async()=>{p(!0),b(""),y("");try{const E=em.filter(M=>j(M.type).enabled||Object.values(j(M.type).credentials).some(k=>k)).map(M=>{const k=j(M.type),Z={};for(const[K,q]of Object.entries(k.credentials))q&&(Z[K]=q);return{type:M.type,enabled:k.enabled,...Object.keys(Z).length>0?{credentials:Z}:{}}});await J.updateChannels(E),y("Channels updated successfully")}catch(E){b(E.message)}finally{p(!1)}};return n.jsxs("div",{className:"page",children:[n.jsx("h2",{children:"Channels"}),n.jsx("div",{className:"channel-grid",children:em.map(E=>{const M=j(E.type),k=r.includes(E.type);return n.jsxs("div",{className:"channel-card",children:[n.jsxs("div",{className:"channel-card-header",children:[n.jsx("h3",{children:E.label}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[k?n.jsx("span",{className:"badge badge-green",children:"Connected"}):M.enabled&&n.jsx("span",{className:"badge badge-yellow",children:"Configured"}),n.jsx("div",{className:`toggle${M.enabled?" active":""}`,onClick:()=>S(E.type)})]})]}),M.enabled&&n.jsx("div",{className:"channel-card-fields",children:E.fields.map(Z=>n.jsxs("div",{children:[n.jsx("label",{children:Z.label}),n.jsx("input",{type:Z.secret?"password":"text",value:M.credentials[Z.key]??"",onChange:K=>w(E.type,Z.key,K.target.value),placeholder:k?"(configured)":`Enter ${Z.label.toLowerCase()}`})]},Z.key))})]},E.type)})}),n.jsx("button",{className:"settings-btn",onClick:A,disabled:m,children:m?"Saving...":"Save Changes"}),x&&n.jsx("div",{className:"settings-success",children:x}),g&&n.jsx("div",{className:"error",children:g})]})}function eb(s){if(s.length===0)return{label:"",color:"transparent",width:"0%"};if(s.length<8)return{label:"Too short",color:"var(--danger)",width:"25%"};const r=/[A-Z]/.test(s),u=/[a-z]/.test(s),o=/[0-9]/.test(s),f=/[^A-Za-z0-9]/.test(s),m=[r,u,o,f].filter(Boolean).length;return s.length>=12&&m>=3?{label:"Strong",color:"var(--success)",width:"100%"}:{label:"Fair",color:"var(--warning)",width:"60%"}}function Pi({password:s}){const r=eb(s);return s?n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"password-strength",children:n.jsx("div",{className:"password-strength-bar",style:{width:r.width,background:r.color}})}),n.jsx("div",{className:"password-strength-label",style:{color:r.color},children:r.label})]}):null}function Xm(){const[s,r]=h.useState(""),[u,o]=h.useState(""),[f,m]=h.useState(""),[p,x]=h.useState(!1),[y,g]=h.useState(""),[b,j]=h.useState(""),[S,w]=h.useState(""),[A,D]=h.useState(""),[O,E]=h.useState(!1),[M,k]=h.useState(""),[Z,K]=h.useState(""),[q,W]=h.useState(null),[G,te]=h.useState(""),[ce,ie]=h.useState(""),[he,ee]=h.useState(!1),[oe,ve]=h.useState(""),[H,F]=h.useState("");h.useEffect(()=>{J.getSealStatus().then(W).catch(()=>W({sealed:!1,pinRequired:!1}))},[]);const le=async L=>{if(L.preventDefault(),j(""),g(""),u!==f){j("New passwords do not match");return}if(u.length<8){j("Password must be at least 8 characters");return}x(!0);try{await J.changeDashboardPassword(s,u),g("Mission Control password changed"),r(""),o(""),m("")}catch(ne){j(ne.message)}finally{x(!1)}},I=async L=>{if(L.preventDefault(),K(""),k(""),S!==A){K("New passwords do not match");return}if(S.length<8){K("Password must be at least 8 characters");return}E(!0);try{await J.changeVaultPassword(S),k("Vault password changed"),w(""),D("")}catch(ne){K(ne.message)}finally{E(!1)}},de=async L=>{if(L.preventDefault(),F(""),ve(""),!G){F("Vault password is required");return}if(ce&&ce.length<4){F("PIN must be at least 4 characters");return}ee(!0);try{await J.enableSeal(G,ce||void 0),ve("Auto-unseal enabled"),te(""),ie(""),W({sealed:!0,pinRequired:ce.length>0})}catch(ne){F(ne.message)}finally{ee(!1)}},C=async()=>{F(""),ve(""),ee(!0);try{await J.disableSeal(),ve("Auto-unseal disabled"),W({sealed:!1,pinRequired:!1})}catch(L){F(L.message)}finally{ee(!1)}};return n.jsxs("div",{className:"page",children:[n.jsx("h2",{children:"Security"}),n.jsxs("div",{className:"settings-section",children:[n.jsx("h3",{children:"Change Mission Control Password"}),n.jsxs("form",{className:"settings-form",onSubmit:le,children:[n.jsx("label",{children:"Current Password"}),n.jsx("input",{type:"password",value:s,onChange:L=>r(L.target.value)}),n.jsx("label",{children:"New Password"}),n.jsx("input",{type:"password",value:u,onChange:L=>o(L.target.value)}),n.jsx(Pi,{password:u}),n.jsx("label",{children:"Confirm New Password"}),n.jsx("input",{type:"password",value:f,onChange:L=>m(L.target.value)}),n.jsx("button",{className:"settings-btn",type:"submit",disabled:p||!s||!u,children:p?"Saving...":"Change Password"}),y&&n.jsx("div",{className:"settings-success",children:y}),b&&n.jsx("div",{className:"error",children:b})]})]}),n.jsxs("div",{className:"settings-section",children:[n.jsx("h3",{children:"Change Vault Password"}),n.jsxs("form",{className:"settings-form",onSubmit:I,children:[n.jsx("label",{children:"New Vault Password"}),n.jsx("input",{type:"password",value:S,onChange:L=>w(L.target.value)}),n.jsx(Pi,{password:S}),n.jsx("label",{children:"Confirm New Password"}),n.jsx("input",{type:"password",value:A,onChange:L=>D(L.target.value)}),n.jsx("button",{className:"settings-btn",type:"submit",disabled:O||!S,children:O?"Saving...":"Change Vault Password"}),M&&n.jsx("div",{className:"settings-success",children:M}),Z&&n.jsx("div",{className:"error",children:Z})]})]}),n.jsxs("div",{className:"settings-section",children:[n.jsx("h3",{children:"Auto-Unseal"}),n.jsx("p",{className:"settings-info",children:"When enabled, the vault automatically unlocks on restart using this machine's identity. No plaintext password is stored on disk. Optionally add a PIN for extra security."}),q===null?n.jsx("p",{children:"Loading..."}):q.sealed?n.jsxs("div",{children:[n.jsxs("p",{children:["Status: ",n.jsx("strong",{children:"Enabled"}),q.pinRequired?" (PIN required)":" (no PIN)"]}),n.jsx("button",{className:"settings-btn",onClick:C,disabled:he,children:he?"Disabling...":"Disable Auto-Unseal"})]}):n.jsxs("form",{className:"settings-form",onSubmit:de,children:[n.jsx("label",{children:"Vault Password"}),n.jsx("input",{type:"password",value:G,onChange:L=>te(L.target.value),placeholder:"Enter vault password to verify"}),n.jsx("label",{children:"PIN (optional, 4+ characters)"}),n.jsx("input",{type:"password",value:ce,onChange:L=>ie(L.target.value),placeholder:"Leave empty for machine-only binding"}),n.jsx("button",{className:"settings-btn",type:"submit",disabled:he||!G,children:he?"Enabling...":"Enable Auto-Unseal"})]}),oe&&n.jsx("div",{className:"settings-success",children:oe}),H&&n.jsx("div",{className:"error",children:H})]})]})}function Vm({selected:s,onSelect:r}){const{theme:u,setTheme:o}=qu(),f=s??u,m=p=>{o(p),r==null||r(p)};return n.jsx("div",{className:"theme-grid",children:Fy.map(p=>n.jsxs("div",{className:`theme-card${f===p.id?" selected":""}`,onClick:()=>m(p.id),children:[n.jsx("div",{className:"theme-swatches",children:p.colors.map((x,y)=>n.jsx("div",{className:"theme-swatch",style:{background:x}},y))}),n.jsxs("div",{className:"theme-info",children:[n.jsx("h3",{children:p.name}),n.jsx("span",{className:`theme-mode-badge ${p.mode}`,children:p.mode})]}),n.jsx("p",{className:"theme-description",children:p.description})]},p.id))})}function Qm(){const{theme:s,setTheme:r}=qu(),[u,o]=h.useState(!1),[f,m]=h.useState(""),[p,x]=h.useState(""),[y,g]=h.useState(null);h.useEffect(()=>{J.getAppearance().then(S=>{const w=S.data.theme;g(w)}).catch(()=>{g(s)})},[]);const b=y!==null&&s!==y,j=async()=>{o(!0),x(""),m("");try{await J.updateAppearance(s),g(s),m("Theme updated successfully")}catch(S){x(S instanceof Error?S.message:"Failed to save theme")}finally{o(!1)}};return n.jsxs("div",{className:"page",children:[n.jsx("h2",{children:"Appearance"}),n.jsx("p",{style:{color:"var(--text-secondary)",marginBottom:"1.5rem"},children:"Choose your theme. Changes preview instantly."}),n.jsx(Vm,{}),b&&n.jsx("button",{className:"btn-primary",onClick:j,disabled:u,style:{marginTop:"1.5rem"},children:u?"Saving...":"Save Theme"}),f&&n.jsx("p",{className:"success",style:{marginTop:"0.75rem"},children:f}),p&&n.jsx("p",{className:"error",style:{marginTop:"0.75rem"},children:p})]})}const tm=[{id:"google-workspace",name:"Google Workspace",description:"Gmail, Google Calendar, and Google Drive",scopes:"Email summaries, calendar awareness, drive file access",setupUrl:"https://console.cloud.google.com/apis/credentials",instructions:["Go to Google Cloud Console > APIs & Services > Credentials","Create an OAuth 2.0 Client ID (Web application type)","Add authorized redirect URI: {callbackUrl}","Enable Gmail API, Google Calendar API, and Google Drive API"]}];function Km(){const[s,r]=h.useState({}),[u,o]=h.useState(""),[f,m]=h.useState(""),[p,x]=h.useState(""),[y,g]=h.useState(""),[b,j]=h.useState(null),S=`${window.location.origin}/api/v1/dashboard/connectors/google-workspace/callback`;h.useEffect(()=>{w()},[]);async function w(){for(const E of tm){r(M=>({...M,[E.id]:{...M[E.id],loading:!0,hasCredentials:!1,connected:!1}}));try{const M=await J.getConnectorStatus(E.id);r(k=>({...k,[E.id]:{hasCredentials:M.data.hasCredentials,connected:M.data.connected,expiresAt:M.data.expiresAt,loading:!1}}))}catch{r(M=>({...M,[E.id]:{hasCredentials:!1,connected:!1,loading:!1}}))}}}async function A(E){if(!u||!f){x("Both Client ID and Client Secret are required");return}x("");try{await J.saveConnectorCredentials(E,u,f),g('Credentials saved. Click "Connect" to authorize.'),o(""),m(""),j(null),w()}catch(M){x(M instanceof Error?M.message:"Failed to save credentials")}}function D(E){window.location.href=`/api/v1/dashboard/connectors/${E}/auth`}async function O(E){try{await J.disconnectConnector(E),g("Disconnected successfully"),w()}catch(M){x(M instanceof Error?M.message:"Failed to disconnect")}}return n.jsxs("div",{className:"page",children:[n.jsx("h2",{children:"Connections"}),n.jsxs("div",{className:"settings-form",children:[y&&n.jsx("div",{className:"settings-success",onClick:()=>g(""),children:y}),p&&n.jsx("div",{className:"error",children:p}),tm.map(E=>{const M=s[E.id],k=M==null?void 0:M.connected,Z=M==null?void 0:M.hasCredentials;return n.jsxs("div",{className:"settings-section",children:[n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[n.jsxs("div",{children:[n.jsx("h3",{children:E.name}),n.jsx("span",{style:{fontSize:"0.85rem",color:"var(--text-secondary)"},children:E.description})]}),n.jsx("span",{className:k?"badge badge-green":"badge badge-gray",children:M!=null&&M.loading?"Checking...":k?"Connected":"Not connected"})]}),n.jsxs("p",{style:{fontSize:"0.8rem",color:"var(--text-secondary)",margin:"0.5rem 0"},children:["Enables: ",E.scopes]}),k?n.jsxs("div",{style:{display:"flex",gap:"0.5rem",marginTop:"1rem",alignItems:"center"},children:[(M==null?void 0:M.expiresAt)&&n.jsxs("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)"},children:["Token expires: ",new Date(M.expiresAt).toLocaleDateString()]}),n.jsx("button",{type:"button",className:"btn-sm",onClick:()=>D(E.id),children:"Reconnect"}),n.jsx("button",{type:"button",className:"btn-sm btn-danger",onClick:()=>O(E.id),children:"Disconnect"})]}):Z?n.jsxs("div",{style:{display:"flex",gap:"0.5rem",marginTop:"1rem"},children:[n.jsx("button",{type:"button",className:"settings-btn",onClick:()=>D(E.id),children:"Connect"}),n.jsx("button",{type:"button",className:"btn-sm",onClick:()=>j(E.id),children:"Update Credentials"})]}):n.jsx("div",{style:{marginTop:"1rem"},children:b!==E.id?n.jsx("button",{type:"button",className:"settings-btn",onClick:()=>j(E.id),children:"Set Up"}):null}),b===E.id&&n.jsxs("div",{style:{marginTop:"1rem",padding:"1rem",background:"var(--bg-hover)",borderRadius:"var(--radius)",border:"1px solid var(--border)"},children:[n.jsx("h4",{style:{margin:"0 0 0.75rem",fontFamily:"var(--font-display)",fontWeight:600},children:"Setup Instructions"}),n.jsx("ol",{style:{fontSize:"0.8rem",color:"var(--text-secondary)",paddingLeft:"1.25rem",margin:"0 0 1rem"},children:E.instructions.map((K,q)=>n.jsx("li",{style:{marginBottom:"0.35rem"},children:K.replace("{callbackUrl}",S)},q))}),n.jsxs("div",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",marginBottom:"1rem",wordBreak:"break-all"},children:["Redirect URI: ",n.jsx("code",{style:{fontFamily:"var(--font-mono)",background:"var(--accent-subtle)",color:"var(--accent)",padding:"0.15rem 0.35rem",borderRadius:"4px",fontSize:"0.82em"},children:S})]}),n.jsx("label",{children:"Client ID"}),n.jsx("input",{type:"text",value:u,onChange:K=>o(K.target.value),placeholder:"your-client-id.apps.googleusercontent.com"}),n.jsx("label",{children:"Client Secret"}),n.jsx("input",{type:"password",value:f,onChange:K=>m(K.target.value),placeholder:"GOCSPX-..."}),n.jsxs("div",{style:{display:"flex",gap:"0.5rem",marginTop:"0.5rem"},children:[n.jsx("button",{type:"button",className:"settings-btn",onClick:()=>A(E.id),children:"Save & Connect"}),n.jsx("button",{type:"button",className:"btn-sm",onClick:()=>{j(null),x("")},children:"Cancel"})]})]})]},E.id)})]})]})}const tb=["Calendar","Email","Tasks","Patterns"],Ln={morningBriefing:{enabled:!0,time:"08:00",categories:["Calendar","Email"]},eveningSummary:{enabled:!1,time:"18:00"},deliveryChannel:"all"};function Zm(){const{data:s,loading:r}=ut(()=>J.getAmbientConfig(),[]),[u,o]=h.useState(Ln),[f,m]=h.useState(!1),[p,x]=h.useState(""),[y,g]=h.useState("");h.useEffect(()=>{var S,w,A,D,O;s!=null&&s.data&&o({morningBriefing:{enabled:((S=s.data.morningBriefing)==null?void 0:S.enabled)??Ln.morningBriefing.enabled,time:((w=s.data.morningBriefing)==null?void 0:w.time)??Ln.morningBriefing.time,categories:((A=s.data.morningBriefing)==null?void 0:A.categories)??Ln.morningBriefing.categories},eveningSummary:{enabled:((D=s.data.eveningSummary)==null?void 0:D.enabled)??Ln.eveningSummary.enabled,time:((O=s.data.eveningSummary)==null?void 0:O.time)??Ln.eveningSummary.time},deliveryChannel:s.data.deliveryChannel??Ln.deliveryChannel})},[s]);const b=S=>{o(w=>{const A=w.morningBriefing.categories,D=A.includes(S)?A.filter(O=>O!==S):[...A,S];return{...w,morningBriefing:{...w.morningBriefing,categories:D}}})},j=async()=>{m(!0),g(""),x("");try{await J.updateAmbientConfig(u),x("Ambient settings saved successfully")}catch(S){g(S instanceof Error?S.message:"Failed to save settings")}finally{m(!1)}};return r?null:n.jsxs("div",{className:"page",children:[n.jsx("h2",{children:"Ambient Intelligence"}),n.jsxs("div",{className:"settings-form",children:[n.jsxs("div",{className:"settings-section",children:[n.jsx("h3",{children:"Morning Briefing"}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",marginBottom:"1rem"},children:[n.jsx("div",{className:`toggle${u.morningBriefing.enabled?" active":""}`,onClick:()=>o(S=>({...S,morningBriefing:{...S.morningBriefing,enabled:!S.morningBriefing.enabled}}))}),n.jsx("span",{style:{fontSize:"0.85rem",color:"var(--text-secondary)"},children:u.morningBriefing.enabled?"Enabled":"Disabled"})]}),u.morningBriefing.enabled&&n.jsxs(n.Fragment,{children:[n.jsx("label",{children:"Delivery Time"}),n.jsx("input",{type:"time",value:u.morningBriefing.time,onChange:S=>o(w=>({...w,morningBriefing:{...w.morningBriefing,time:S.target.value}}))}),n.jsx("label",{children:"Categories"}),n.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:"0.5rem",marginBottom:"1rem"},children:tb.map(S=>n.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.4rem",cursor:"pointer",fontSize:"0.85rem"},children:[n.jsx("input",{type:"checkbox",checked:u.morningBriefing.categories.includes(S),onChange:()=>b(S),style:{width:"auto",marginBottom:0}}),S]},S))})]})]}),n.jsxs("div",{className:"settings-section",children:[n.jsx("h3",{children:"Evening Summary"}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",marginBottom:"1rem"},children:[n.jsx("div",{className:`toggle${u.eveningSummary.enabled?" active":""}`,onClick:()=>o(S=>({...S,eveningSummary:{...S.eveningSummary,enabled:!S.eveningSummary.enabled}}))}),n.jsx("span",{style:{fontSize:"0.85rem",color:"var(--text-secondary)"},children:u.eveningSummary.enabled?"Enabled":"Disabled"})]}),u.eveningSummary.enabled&&n.jsxs(n.Fragment,{children:[n.jsx("label",{children:"Delivery Time"}),n.jsx("input",{type:"time",value:u.eveningSummary.time,onChange:S=>o(w=>({...w,eveningSummary:{...w.eveningSummary,time:S.target.value}}))})]})]}),n.jsxs("div",{className:"settings-section",children:[n.jsx("label",{children:"Delivery Channel"}),n.jsxs("select",{value:u.deliveryChannel,onChange:S=>o(w=>({...w,deliveryChannel:S.target.value})),children:[n.jsx("option",{value:"all",children:"All connected channels"}),n.jsx("option",{value:"webchat",children:"Webchat only"}),n.jsx("option",{value:"discord",children:"Discord"}),n.jsx("option",{value:"telegram",children:"Telegram"}),n.jsx("option",{value:"slack",children:"Slack"}),n.jsx("option",{value:"email",children:"Email"})]})]}),n.jsx("button",{className:"settings-btn",onClick:j,disabled:f,children:f?"Saving...":"Save Settings"}),p&&n.jsx("div",{className:"settings-success",children:p}),y&&n.jsx("div",{className:"error",children:y})]})]})}function ab({loadPreferences:s,updatePreference:r,clearData:u,exportData:o,getEngine:f,setEngine:m}){const[p,x]=h.useState(null),[y,g]=h.useState(!0),[b,j]=h.useState(!1),[S,w]=h.useState(!1),[A,D]=h.useState(""),[O,E]=h.useState(!1);h.useEffect(()=>{s().then(te=>{x(te),g(!1)}).catch(()=>g(!1)),f&&f().then(te=>E(te==="the-architect")).catch(()=>{})},[s,f]);const M=h.useCallback(async()=>{if(!m)return;j(!0);const te=O?"standard":"the-architect";try{await m(te),E(!O),D(te==="the-architect"?"Architect engine enabled":"Architect engine disabled"),setTimeout(()=>D(""),3e3)}finally{j(!1)}},[O,m]),k=h.useCallback(async(te,ce)=>{if(p){j(!0);try{await r(te,ce),x({...p,[te]:ce})}finally{j(!1)}}},[p,r]),Z=h.useCallback(async te=>{if(!p)return;j(!0);const ce=te==="auto"?null:te;try{await r("defaultContext",ce),x({...p,defaultContext:ce})}finally{j(!1)}},[p,r]),K=h.useCallback(async()=>{j(!0);try{await u(),x(await s()),w(!1),D("Learning data cleared"),setTimeout(()=>D(""),3e3)}finally{j(!1)}},[u,s]),q=h.useCallback(async()=>{try{const te=await o(),ce=new Blob([te],{type:"application/json"}),ie=URL.createObjectURL(ce),he=document.createElement("a");he.href=ie,he.download=`architect-data-${new Date().toISOString().slice(0,10)}.json`,he.click(),URL.revokeObjectURL(ie),D("Data exported"),setTimeout(()=>D(""),3e3)}catch{D("Export failed"),setTimeout(()=>D(""),3e3)}},[o]);if(y)return null;if(!p)return n.jsx("div",{className:"error",children:"Failed to load preferences"});const W=p.totalInteractions,G=Object.entries(p.contextUsageHistory).filter(([,te])=>te>0).sort(([,te],[,ce])=>ce-te);return n.jsxs("div",{className:"settings-form",children:[A&&n.jsx("div",{className:"settings-success",role:"status",children:A}),m&&n.jsxs("div",{className:"settings-section",children:[n.jsx("h3",{children:"Engine"}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx("div",{className:`toggle${O?" active":""}`,onClick:()=>!b&&M(),style:b?{opacity:.5,pointerEvents:"none"}:void 0}),n.jsx("span",{style:{fontSize:"0.85rem",color:"var(--text-primary)"},children:O?"Architect engine enabled (global default)":"Architect engine disabled"})]}),n.jsx("p",{style:{fontSize:"0.8rem",color:"var(--text-secondary)",marginTop:"0.5rem"},children:"Controls the default personality for new chats. Individual chats can override this."})]}),n.jsxs("div",{className:"settings-section",children:[n.jsx("h3",{children:"Display"}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",marginBottom:"0.75rem"},children:[n.jsx("div",{className:`toggle${p.showContextIndicator?" active":""}`,onClick:()=>!b&&k("showContextIndicator",!p.showContextIndicator),style:b?{opacity:.5,pointerEvents:"none"}:void 0}),n.jsx("span",{style:{fontSize:"0.85rem",color:"var(--text-primary)"},children:"Show context indicator"})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",marginBottom:"0.75rem"},children:[n.jsx("div",{className:`toggle${p.showSourcesButton?" active":""}`,onClick:()=>!b&&k("showSourcesButton",!p.showSourcesButton),style:b?{opacity:.5,pointerEvents:"none"}:void 0}),n.jsx("span",{style:{fontSize:"0.85rem",color:"var(--text-primary)"},children:"Show sources button"})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx("div",{className:`toggle${p.autoDetectContext?" active":""}`,onClick:()=>!b&&k("autoDetectContext",!p.autoDetectContext),style:b?{opacity:.5,pointerEvents:"none"}:void 0}),n.jsx("span",{style:{fontSize:"0.85rem",color:"var(--text-primary)"},children:"Auto-detect context"})]})]}),n.jsxs("div",{className:"settings-section",children:[n.jsx("h3",{children:"Default Context"}),n.jsx("label",{children:"Context domain"}),n.jsxs("select",{value:p.defaultContext??"auto",onChange:te=>Z(te.target.value),disabled:b,children:[n.jsx("option",{value:"auto",children:"Auto (detect from message)"}),Nl.map(te=>n.jsxs("option",{value:te,children:[_t[te].icon," ",_t[te].label]},te))]})]}),n.jsxs("div",{className:"settings-section",children:[n.jsx("h3",{children:"Detection Stats"}),n.jsx("div",{className:"status-grid",style:{marginBottom:"1rem"},children:n.jsxs("div",{className:"status-card",children:[n.jsx("h3",{children:"Total"}),n.jsx("div",{className:"value",children:W}),n.jsx("div",{className:"sub",children:"interactions"})]})}),G.length>0&&n.jsx("div",{className:"domain-stats-list",children:G.map(([te,ce])=>{var oe,ve,H;const ie=W>0?Math.round(ce/W*100):0,he=((oe=G[0])==null?void 0:oe[1])??1,ee=Math.max(4,Math.round(ce/he*100));return n.jsxs("div",{className:"domain-stat-row",children:[n.jsxs("span",{className:"domain-stat-label",children:[(ve=_t[te])==null?void 0:ve.icon," ",((H=_t[te])==null?void 0:H.label)??te]}),n.jsx("span",{className:"domain-stat-bar-track",children:n.jsx("span",{className:"domain-stat-bar-fill",style:{width:`${ee}%`}})}),n.jsx("span",{className:"domain-stat-count",children:ce}),n.jsxs("span",{className:"domain-stat-pct",children:[ie,"%"]})]},te)})}),G.length===0&&n.jsx("p",{style:{fontSize:"0.85rem",color:"var(--text-secondary)"},children:"No interactions recorded yet. Context stats will appear here as you use The Architect."})]}),n.jsxs("div",{className:"settings-section",style:{borderBottom:"none"},children:[n.jsx("h3",{children:"Data Management"}),n.jsxs("div",{style:{display:"flex",gap:"0.5rem",flexWrap:"wrap",alignItems:"center"},children:[S?n.jsxs(n.Fragment,{children:[n.jsx("span",{style:{fontSize:"0.85rem",color:"var(--danger)",marginRight:"0.25rem"},children:"Clear all learning data? This cannot be undone."}),n.jsx("button",{className:"btn-sm btn-danger",onClick:K,disabled:b,children:"Confirm"}),n.jsx("button",{className:"btn-sm",onClick:()=>w(!1),disabled:b,children:"Cancel"})]}):n.jsx("button",{className:"btn-sm btn-danger",onClick:()=>w(!0),disabled:b,children:"Clear learning data"}),n.jsx("button",{className:"btn-sm",onClick:q,disabled:b,children:"Export data"})]})]})]})}function Jm(){return n.jsxs("div",{className:"page",children:[n.jsx("h2",{children:"The Architect"}),n.jsx(ab,{loadPreferences:async()=>(await J.getArchitectPreferences()).data,updatePreference:async(s,r)=>{await J.updateArchitectPreference(s,r)},clearData:async()=>{await J.clearArchitectData()},exportData:async()=>(await J.exportArchitectData()).data,getEngine:async()=>(await J.getPersonalityEngine()).data.engine,setEngine:async s=>{await J.setPersonalityEngine(s)}})]})}function Zi(s){return new Date(s).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}function nb(s){return new Date(s).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function lb({trend:s}){return s==="improving"?n.jsx("span",{className:"up-trend-arrow",children:"▲"}):s==="declining"?n.jsx("span",{className:"up-trend-decline",children:"▼"}):n.jsx("span",{className:"up-trend-flat",children:"▬"})}function Wm(){const[s,r]=h.useState(null),[u,o]=h.useState(!0),[f,m]=h.useState(null);function p(){o(!0),m(null),J.getUserModel().then(y=>{r(y),o(!1)}).catch(y=>{const g=y instanceof Error?y.message:String(y);g.includes("not available")||g.includes("404")?m("Not enough data yet. Keep chatting and check back later!"):m(g),o(!1)})}if(h.useEffect(()=>{p()},[]),u)return n.jsx("div",{className:"up-page",children:n.jsx("div",{className:"up-loading",children:"Loading user profile..."})});if(f)return n.jsxs("div",{className:"up-page",children:[n.jsx("div",{className:"up-header",children:n.jsx("h2",{className:"up-title",children:"What do you know about me?"})}),n.jsx("div",{className:"up-empty",children:f})]});if(!s)return null;const x=Date.now();return n.jsxs("div",{className:"up-page",children:[n.jsxs("div",{className:"up-header",children:[n.jsx("h2",{className:"up-title",children:"What do you know about me?"}),n.jsxs("div",{className:"up-header-right",children:[n.jsxs("span",{className:"up-synthesized",children:["Synthesized ",nb(s.synthesizedAt)]}),n.jsx("button",{className:"up-refresh-btn",onClick:p,children:"Refresh"})]})]}),s.narrative&&n.jsx("section",{className:"up-section",children:n.jsx("p",{className:"up-narrative",children:s.narrative})}),s.topDomains&&s.topDomains.length>0&&n.jsxs("section",{className:"up-section",children:[n.jsx("h3",{className:"up-section-title",children:"Domain Expertise"}),n.jsx("div",{className:"up-domain-grid",children:s.topDomains.map(y=>n.jsxs("div",{className:"up-domain-card",children:[n.jsx("div",{className:"up-domain-name",children:y.domain}),n.jsx("div",{className:"up-domain-bar-track",children:n.jsx("div",{className:"up-domain-bar-fill",style:{width:`${Math.round(y.share*100)}%`}})}),n.jsxs("div",{className:"up-domain-stats",children:[n.jsxs("span",{className:"up-domain-share",children:[Math.round(y.share*100),"%"]}),y.satisfactionRate!==null&&n.jsxs("span",{className:"up-domain-satisfaction",children:[Math.round(y.satisfactionRate*100),"% satisfied"]})]})]},y.domain))})]}),s.communicationStyle&&n.jsxs("section",{className:"up-section",children:[n.jsx("h3",{className:"up-section-title",children:"Communication Style"}),n.jsxs("div",{className:"up-comm-labels",children:[n.jsx("span",{className:"up-comm-badge",children:s.communicationStyle.verbosityLabel}),n.jsx("span",{className:"up-comm-badge",children:s.communicationStyle.toneLabel})]}),n.jsx("div",{className:"up-comm-bars",children:[{label:"Verbosity",value:s.communicationStyle.verbosityPreference},{label:"Warmth",value:s.communicationStyle.warmthPreference},{label:"Humor",value:s.communicationStyle.humorPreference}].map(y=>n.jsxs("div",{className:"up-comm-row",children:[n.jsx("span",{className:"up-comm-label",children:y.label}),n.jsx("div",{className:"up-comm-track",children:n.jsx("div",{className:"up-comm-fill",style:{width:`${Math.round(Math.min(1,Math.max(0,y.value))*100)}%`}})}),n.jsx("span",{className:"up-comm-value",children:y.value.toFixed(2)})]},y.label))})]}),s.satisfaction&&n.jsxs("section",{className:"up-section",children:[n.jsx("h3",{className:"up-section-title",children:"Satisfaction"}),n.jsxs("div",{className:"up-satisfaction-header",children:[n.jsx(lb,{trend:s.satisfaction.overallTrend}),n.jsx("span",{className:"up-satisfaction-trend",children:s.satisfaction.overallTrend}),n.jsxs("span",{className:"up-satisfaction-count",children:[s.satisfaction.totalFeedback," feedback items"]})]}),s.satisfaction.strongDomains.length>0&&n.jsxs("div",{className:"up-satisfaction-group",children:[n.jsx("span",{className:"up-satisfaction-label",children:"Strong:"}),s.satisfaction.strongDomains.map(y=>n.jsx("span",{className:"up-tag up-tag-strong",children:y},y))]}),s.satisfaction.weakDomains.length>0&&n.jsxs("div",{className:"up-satisfaction-group",children:[n.jsx("span",{className:"up-satisfaction-label",children:"Needs work:"}),s.satisfaction.weakDomains.map(y=>n.jsx("span",{className:"up-tag up-tag-weak",children:y},y))]})]}),s.activeDecisions&&s.activeDecisions.length>0&&n.jsxs("section",{className:"up-section",children:[n.jsx("h3",{className:"up-section-title",children:"Active Decisions"}),n.jsx("div",{className:"up-decision-list",children:s.activeDecisions.map(y=>n.jsxs("div",{className:"up-decision-card",children:[n.jsx("div",{className:"up-decision-summary",children:y.summary}),n.jsxs("div",{className:"up-decision-meta",children:[n.jsx("span",{className:"up-decision-date",children:Zi(y.createdAt)}),y.tags.map(g=>n.jsx("span",{className:"up-tag",children:g},g))]})]},y.id))})]}),s.dueFollowUps&&s.dueFollowUps.length>0&&n.jsxs("section",{className:"up-section",children:[n.jsx("h3",{className:"up-section-title",children:"Due Follow-ups"}),n.jsx("div",{className:"up-decision-list",children:s.dueFollowUps.map(y=>{const g=y.followUpDate&&y.followUpDate<x;return n.jsxs("div",{className:`up-decision-card ${g?"up-overdue":""}`,children:[n.jsxs("div",{className:"up-decision-summary",children:[g&&n.jsx("span",{className:"up-overdue-badge",children:"Overdue"}),y.summary]}),n.jsxs("div",{className:"up-decision-meta",children:[y.followUpDate&&n.jsxs("span",{className:"up-decision-date",children:["Due ",Zi(y.followUpDate)]}),y.tags.map(b=>n.jsx("span",{className:"up-tag",children:b},b))]})]},y.id)})})]}),s.correctionSummary&&s.correctionSummary.totalCorrections>0&&n.jsxs("section",{className:"up-section",children:[n.jsx("h3",{className:"up-section-title",children:"Correction Patterns"}),n.jsxs("div",{className:"up-corrections-total",children:[s.correctionSummary.totalCorrections," total corrections"]}),s.correctionSummary.topPatterns.length>0&&n.jsx("div",{className:"up-corrections-list",children:s.correctionSummary.topPatterns.map((y,g)=>n.jsxs("div",{className:"up-correction-row",children:[n.jsx("span",{className:"up-correction-from",children:y.from}),n.jsx("span",{className:"up-correction-arrow",children:"→"}),n.jsx("span",{className:"up-correction-to",children:y.to}),n.jsxs("span",{className:"up-correction-count",children:[y.count,"x"]})]},g))})]}),n.jsxs("footer",{className:"up-footer",children:[n.jsxs("div",{className:"up-stat",children:[n.jsx("span",{className:"up-stat-label",children:"Interactions"}),n.jsx("span",{className:"up-stat-value",children:s.totalInteractions})]}),n.jsxs("div",{className:"up-stat",children:[n.jsx("span",{className:"up-stat-label",children:"First used"}),n.jsx("span",{className:"up-stat-value",children:Zi(s.firstUsed)})]}),n.jsxs("div",{className:"up-stat",children:[n.jsx("span",{className:"up-stat-label",children:"Last used"}),n.jsx("span",{className:"up-stat-value",children:Zi(s.lastUsed)})]})]})]})}const Ua={dnd:{enabled:!1,schedule:{start:"22:00",end:"08:00"}},urgencyKeywords:[],sources:{email:!0,calendar:!0,github:!0},soundEnabled:!0};function Fm(){const{data:s,loading:r}=ut(()=>J.getNotificationPreferences(),[]),{data:u,loading:o}=ut(()=>J.getNotifications(),[]),[f,m]=h.useState(Ua),[p,x]=h.useState([]),[y,g]=h.useState(!1),[b,j]=h.useState(""),[S,w]=h.useState(""),[A,D]=h.useState("");h.useEffect(()=>{var M,k,Z,K,q,W,G,te;if(s!=null&&s.data&&Object.keys(s.data).length>0){const ce=s.data,ie={dnd:{enabled:((M=ce.dnd)==null?void 0:M.enabled)??Ua.dnd.enabled,schedule:{start:((Z=(k=ce.dnd)==null?void 0:k.schedule)==null?void 0:Z.start)??Ua.dnd.schedule.start,end:((q=(K=ce.dnd)==null?void 0:K.schedule)==null?void 0:q.end)??Ua.dnd.schedule.end}},urgencyKeywords:ce.urgencyKeywords??Ua.urgencyKeywords,sources:{email:((W=ce.sources)==null?void 0:W.email)??Ua.sources.email,calendar:((G=ce.sources)==null?void 0:G.calendar)??Ua.sources.calendar,github:((te=ce.sources)==null?void 0:te.github)??Ua.sources.github},soundEnabled:ce.soundEnabled??Ua.soundEnabled};m(ie),D((ie.urgencyKeywords||[]).join(", "))}},[s]),h.useEffect(()=>{u!=null&&u.data&&x(u.data)},[u]);const O=async()=>{g(!0),w(""),j("");try{const M=A.split(",").map(k=>k.trim()).filter(Boolean);await J.updateNotificationPreferences({...f,urgencyKeywords:M}),j("Notification settings saved successfully")}catch(M){w(M instanceof Error?M.message:"Failed to save settings")}finally{g(!1)}},E=async M=>{try{await J.dismissNotification(M),x(k=>k.filter(Z=>Z.id!==M))}catch{}};return r||o?null:n.jsxs("div",{className:"page",children:[n.jsx("h2",{children:"Notification Settings"}),n.jsxs("div",{className:"settings-form",children:[n.jsxs("div",{className:"settings-section",children:[n.jsx("h3",{children:"Do Not Disturb"}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",marginBottom:"1rem"},children:[n.jsx("div",{className:`toggle${f.dnd.enabled?" active":""}`,onClick:()=>m(M=>({...M,dnd:{...M.dnd,enabled:!M.dnd.enabled}}))}),n.jsx("span",{style:{fontSize:"0.85rem",color:"var(--text-secondary)"},children:f.dnd.enabled?"Enabled":"Disabled"})]}),f.dnd.enabled&&n.jsxs("div",{style:{display:"flex",gap:"1rem",alignItems:"center",marginBottom:"1rem"},children:[n.jsxs("div",{children:[n.jsx("label",{children:"Start"}),n.jsx("input",{type:"time",value:f.dnd.schedule.start,onChange:M=>m(k=>({...k,dnd:{...k.dnd,schedule:{...k.dnd.schedule,start:M.target.value}}}))})]}),n.jsxs("div",{children:[n.jsx("label",{children:"End"}),n.jsx("input",{type:"time",value:f.dnd.schedule.end,onChange:M=>m(k=>({...k,dnd:{...k.dnd,schedule:{...k.dnd.schedule,end:M.target.value}}}))})]})]})]}),n.jsxs("div",{className:"settings-section",children:[n.jsx("h3",{children:"Urgency Keywords"}),n.jsx("label",{children:"Comma-separated keywords that mark a notification as urgent"}),n.jsx("textarea",{rows:3,value:A,onChange:M=>D(M.target.value),placeholder:"urgent, critical, deadline, asap",style:{width:"100%",resize:"vertical"}})]}),n.jsxs("div",{className:"settings-section",children:[n.jsx("h3",{children:"Sources"}),n.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:"0.5rem",marginBottom:"1rem"},children:["email","calendar","github"].map(M=>n.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.4rem",cursor:"pointer",fontSize:"0.85rem"},children:[n.jsx("input",{type:"checkbox",checked:f.sources[M],onChange:()=>m(k=>({...k,sources:{...k.sources,[M]:!k.sources[M]}})),style:{width:"auto",marginBottom:0}}),M.charAt(0).toUpperCase()+M.slice(1)]},M))})]}),n.jsxs("div",{className:"settings-section",children:[n.jsx("h3",{children:"Sound"}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",marginBottom:"1rem"},children:[n.jsx("div",{className:`toggle${f.soundEnabled?" active":""}`,onClick:()=>m(M=>({...M,soundEnabled:!M.soundEnabled}))}),n.jsx("span",{style:{fontSize:"0.85rem",color:"var(--text-secondary)"},children:f.soundEnabled?"Enabled":"Disabled"})]})]}),n.jsx("button",{className:"settings-btn",onClick:O,disabled:y,children:y?"Saving...":"Save Settings"}),b&&n.jsx("div",{className:"settings-success",children:b}),S&&n.jsx("div",{className:"error",children:S}),p.length>0&&n.jsxs("div",{className:"settings-section",style:{marginTop:"2rem"},children:[n.jsx("h3",{children:"Recent Notifications"}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:p.map(M=>n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"0.75rem",background:"var(--bg-secondary, #1a1a2e)",borderRadius:"6px"},children:[n.jsxs("div",{children:[n.jsx("div",{style:{fontWeight:500},children:M.title}),n.jsxs("div",{style:{fontSize:"0.8rem",color:"var(--text-secondary)"},children:[M.source," · ",new Date(M.timestamp).toLocaleString()]})]}),n.jsx("button",{className:"settings-btn",style:{padding:"0.25rem 0.75rem",fontSize:"0.8rem"},onClick:()=>E(M.id),children:"Dismiss"})]},M.id))})]})]})]})}const sb=["","behavior.","webhook.","voice.","system.","auth.","dashboard."];function Pm(){const[s,r]=h.useState(""),{data:u,refresh:o}=ut(()=>J.getAudit({type:s||void 0,limit:200}),[s]);Os(o);const f=(u==null?void 0:u.data)??[],m=[{key:"timestamp",label:"Time",render:p=>new Date(p.timestamp).toLocaleString()},{key:"event",label:"Event"},{key:"details",label:"Details",render:p=>JSON.stringify(p.details).slice(0,80)}];return n.jsxs("div",{className:"page",children:[n.jsx("h2",{children:"Audit Log"}),n.jsx("div",{className:"filters",children:n.jsxs("select",{value:s,onChange:p=>r(p.target.value),children:[n.jsx("option",{value:"",children:"All events"}),sb.filter(Boolean).map(p=>n.jsxs("option",{value:p,children:[p,"*"]},p))]})}),n.jsx(Hm,{columns:m,rows:f,keyField:"sequence"})]})}function ib({rating:s}){const r=Math.floor(s),u=s-r>=.5,o=5-r-(u?1:0);return n.jsxs("span",{className:"marketplace-card-rating",title:`${s.toFixed(1)} / 5`,children:["★".repeat(r),u?"½":"","☆".repeat(o)]})}function cb({item:s,onSelect:r,onInstall:u}){return n.jsxs("div",{className:"marketplace-card glass-mid",onClick:()=>r(s),children:[n.jsxs("div",{className:"marketplace-card-header",children:[n.jsx("span",{className:"marketplace-card-name",children:s.name}),n.jsxs("span",{className:"marketplace-card-version",children:["v",s.version]})]}),n.jsx("p",{className:"marketplace-card-author",children:s.author}),n.jsx("p",{className:"marketplace-card-desc",children:s.description}),n.jsxs("div",{className:"marketplace-card-footer",children:[n.jsxs("span",{className:"marketplace-card-stats",children:[n.jsx(ib,{rating:s.rating}),n.jsxs("span",{className:"marketplace-card-downloads",children:["↓"," ",s.downloads.toLocaleString()]})]}),n.jsx("button",{className:"marketplace-card-install",onClick:o=>{o.stopPropagation(),u(s)},children:"Install"})]})]})}function rb({item:s,onClose:r,onInstall:u}){return n.jsxs("div",{className:"marketplace-detail glass-mid",children:[n.jsxs("div",{className:"marketplace-detail-header",children:[n.jsxs("div",{children:[n.jsx("span",{className:"marketplace-detail-name",children:s.name}),n.jsxs("span",{className:"marketplace-detail-version",children:["v",s.version]})]}),n.jsxs("span",{className:"marketplace-detail-author",children:["by ",s.author]})]}),n.jsxs("div",{className:"marketplace-detail-stats",children:[n.jsxs("span",{children:["★".repeat(Math.floor(s.rating)),"☆".repeat(5-Math.floor(s.rating))," (",s.rating.toFixed(1),")"]}),n.jsxs("span",{children:["↓ ",s.downloads.toLocaleString()," downloads"]})]}),n.jsx("p",{className:"marketplace-detail-desc",children:s.description}),s.preview&&n.jsx("p",{className:"marketplace-detail-preview",children:s.preview}),s.tone&&n.jsxs("div",{className:"marketplace-detail-tone",children:[n.jsxs("span",{children:["Warmth: ",s.tone.warmth]}),n.jsxs("span",{children:["Humor: ",s.tone.humor]}),n.jsxs("span",{children:["Formality: ",s.tone.formality]})]}),n.jsxs("div",{className:"marketplace-detail-meta",children:[s.permissions&&s.permissions.length>0&&n.jsxs("div",{children:[n.jsx("strong",{children:"Permissions:"})," ",s.permissions.join(", ")]}),s.keywords&&s.keywords.length>0&&n.jsxs("div",{children:[n.jsx("strong",{children:"Keywords:"})," ",s.keywords.join(", ")]}),s.license&&n.jsxs("div",{children:[n.jsx("strong",{children:"License:"})," ",s.license]})]}),n.jsxs("div",{className:"marketplace-detail-actions",children:[n.jsx("button",{className:"btn-primary",onClick:()=>u(s),children:"Install"}),n.jsx("button",{className:"btn-secondary",onClick:r,children:"Close"})]})]})}function ub(){const[s,r]=h.useState("plugins"),[u,o]=h.useState(""),[f,m]=h.useState("downloads"),[p,x]=h.useState([]),[y,g]=h.useState([]),[b,j]=h.useState(0),[S,w]=h.useState(0),[A,D]=h.useState(null),[O,E]=h.useState(!1),M=18,k=h.useCallback(async()=>{E(!0);try{if(s==="plugins"){const G=await J.searchPlugins({q:u||void 0,sort:f,limit:M,offset:S});x(G.plugins),j(G.total)}else{const G=await J.searchPersonalities({q:u||void 0,sort:f,limit:M,offset:S});g(G.personalities),j(G.total)}}catch{}E(!1)},[s,u,f,S]);h.useEffect(()=>{k()},[k]);const Z=async G=>{try{s==="plugins"?await J.installPlugin(G.name,G.version):await J.installPersonality(G.name,G.version),k()}catch{}},K=s==="plugins"?p:y,q=Math.ceil(b/M),W=Math.floor(S/M)+1;return n.jsxs("div",{className:"marketplace",children:[n.jsxs("div",{className:"marketplace-toolbar",children:[n.jsxs("div",{className:"marketplace-tabs",children:[n.jsx("button",{className:`marketplace-tab ${s==="plugins"?"active":""}`,onClick:()=>{r("plugins"),w(0)},children:"Plugins"}),n.jsx("button",{className:`marketplace-tab ${s==="personalities"?"active":""}`,onClick:()=>{r("personalities"),w(0)},children:"Personalities"})]}),n.jsx("input",{className:"marketplace-search",type:"text",placeholder:"Search...",value:u,onChange:G=>{o(G.target.value),w(0)}})]}),O?n.jsx("div",{className:"marketplace-loading",children:"Loading..."}):n.jsxs("div",{className:"marketplace-grid",children:[K.map(G=>n.jsx(cb,{item:G,onSelect:D,onInstall:Z},G.name)),K.length===0&&n.jsx("div",{className:"marketplace-empty",children:"No results found."})]}),n.jsxs("div",{className:"marketplace-footer",children:[n.jsxs("select",{className:"marketplace-sort",value:f,onChange:G=>m(G.target.value),children:[n.jsx("option",{value:"downloads",children:"Downloads"}),n.jsx("option",{value:"rating",children:"Rating"}),n.jsx("option",{value:"name",children:"Name"}),n.jsx("option",{value:"updated",children:"Recently Updated"})]}),q>1&&n.jsxs("div",{className:"marketplace-pagination",children:[n.jsx("button",{disabled:S===0,onClick:()=>w(Math.max(0,S-M)),children:"Prev"}),n.jsxs("span",{children:["Page ",W," of ",q]}),n.jsx("button",{disabled:W>=q,onClick:()=>w(S+M),children:"Next"})]})]}),A&&n.jsx("div",{className:"marketplace-overlay",onClick:()=>D(null),children:n.jsx("div",{onClick:G=>G.stopPropagation(),children:n.jsx(rb,{item:A,onClose:()=>D(null),onInstall:Z})})})]})}function ob(){const[s,r]=h.useState([]),[u,o]=h.useState(null),[f,m]=h.useState(null),[p,x]=h.useState("unknown"),[y,g]=h.useState(!0);if(h.useEffect(()=>{Promise.all([J.getModels(),J.getHealthState()]).then(([j,S])=>{var A,D,O;r(j.providers),o(j.routing),m(j.cost);const w=(D=(A=S.data)==null?void 0:A.subsystems)==null?void 0:D.find(E=>E.name==="providers");x((w==null?void 0:w.status)??((O=S.data)==null?void 0:O.overall)??"unknown")}).catch(()=>{}).finally(()=>g(!1))},[]),y)return n.jsx("div",{className:"provider-health",children:n.jsx("p",{children:"Loading..."})});const b=p==="healthy"?"status-dot-green":p==="degraded"?"status-dot-yellow":"status-dot-red";return n.jsxs("div",{className:"provider-health",children:[n.jsxs("div",{className:"provider-health-header",children:[n.jsx("h3",{children:"Providers"}),n.jsx("span",{className:b})," ",n.jsx("span",{className:"provider-health-status",children:p})]}),n.jsx("div",{className:"provider-health-grid",children:s.map(j=>n.jsxs("div",{className:"provider-health-card glass-mid",children:[n.jsxs("div",{className:"provider-health-card-header",children:[n.jsx("strong",{children:j.displayName}),(u==null?void 0:u.primary)===j.name&&n.jsx("span",{className:"badge badge-green",children:"Primary"}),(u==null?void 0:u.fallback)===j.name&&n.jsx("span",{className:"badge badge-yellow",children:"Fallback"})]}),n.jsxs("div",{className:"provider-health-card-models",children:[Object.keys(j.models).length," model",Object.keys(j.models).length!==1?"s":"",Object.values(j.models).some(S=>S.isLocal)&&n.jsx("span",{className:"badge badge-gray",children:"Local"})]})]},j.name))}),f&&n.jsxs("div",{className:"provider-health-cost",children:[n.jsxs("div",{className:"provider-health-cost-item",children:[n.jsx("span",{className:"provider-health-cost-label",children:"Today"}),n.jsxs("span",{className:`provider-health-cost-value ${f.isOverBudget?"cost-over":""}`,children:["$",f.today.toFixed(2)]})]}),n.jsxs("div",{className:"provider-health-cost-item",children:[n.jsx("span",{className:"provider-health-cost-label",children:"This month"}),n.jsxs("span",{className:"provider-health-cost-value",children:["$",f.thisMonth.toFixed(2)]})]}),f.budgetRemaining!=null&&n.jsxs("div",{className:"provider-health-cost-item",children:[n.jsx("span",{className:"provider-health-cost-label",children:"Budget left"}),n.jsxs("span",{className:`provider-health-cost-value ${f.warningThresholdReached?"cost-warning":""}`,children:["$",f.budgetRemaining.toFixed(2)]})]})]})]})}function db(){const[s,r]=h.useState(null),[u,o]=h.useState([]),[f,m]=h.useState(!0),p=h.useCallback(async()=>{try{const[y,g]=await Promise.all([J.getJobStats(),J.getJobList({status:"dead",limit:50})]);r(y),o(g.data)}catch{}m(!1)},[]);h.useEffect(()=>{p()},[p]);const x=async y=>{try{await J.retryJob(y),p()}catch{}};return f?n.jsx("div",{className:"dlq-monitor",children:n.jsx("p",{children:"Loading..."})}):n.jsxs("div",{className:"dlq-monitor",children:[n.jsxs("div",{className:"dlq-header",children:[n.jsx("h3",{children:"Job Queue"}),n.jsx("button",{className:"dlq-refresh",onClick:p,children:"Refresh"})]}),s&&n.jsxs("div",{className:"dlq-stats",children:[n.jsxs("span",{className:"dlq-stat",children:[s.pending," pending"]}),n.jsxs("span",{className:"dlq-stat",children:[s.running," running"]}),n.jsxs("span",{className:"dlq-stat",children:[s.completed24h," completed (24h)"]}),n.jsxs("span",{className:"dlq-stat dlq-stat-warn",children:[s.failed24h," failed (24h)"]}),n.jsxs("span",{className:`dlq-stat ${s.dead>0?"dlq-stat-danger":""}`,children:[s.dead," dead"]})]}),u.length>0&&n.jsxs("div",{className:"dlq-list",children:[n.jsx("h4",{children:"Dead Jobs"}),n.jsxs("table",{className:"dlq-table",children:[n.jsx("thead",{children:n.jsxs("tr",{children:[n.jsx("th",{children:"Type"}),n.jsx("th",{children:"Error"}),n.jsx("th",{children:"Attempts"}),n.jsx("th",{children:"Age"}),n.jsx("th",{})]})}),n.jsx("tbody",{children:u.map(y=>n.jsxs("tr",{children:[n.jsx("td",{children:y.type}),n.jsx("td",{className:"dlq-error",children:String(y.result??"unknown")}),n.jsxs("td",{children:[y.attempt,"/",y.maxAttempts]}),n.jsx("td",{children:fb(y.createdAt)}),n.jsx("td",{children:n.jsx("button",{className:"dlq-retry-btn",onClick:()=>x(y.id),children:"Retry"})})]},y.id))})]})]}),u.length===0&&s&&s.dead===0&&n.jsx("p",{className:"dlq-empty",children:"No dead jobs. All clear."})]})}function fb(s){const r=Date.now()-s;return r<6e4?"<1m":r<36e5?`${Math.floor(r/6e4)}m`:r<864e5?`${Math.floor(r/36e5)}h`:`${Math.floor(r/864e5)}d`}function hb(){const[s,r]=h.useState([]),[u,o]=h.useState(!0),[f,m]=h.useState(null);if(h.useEffect(()=>{tx().then(g=>r(g.features)).catch(g=>m(g instanceof Error?g.message:String(g))).finally(()=>o(!1))},[]),u)return n.jsx("div",{className:"system-status",children:n.jsx("p",{children:"Loading..."})});if(f)return n.jsx("div",{className:"system-status",children:n.jsxs("p",{children:["Error: ",f]})});const p=s.filter(g=>g.enabled&&g.configured&&g.active),x=s.filter(g=>g.enabled&&!g.configured),y=s.filter(g=>!g.enabled);return n.jsxs("div",{className:"system-status",children:[n.jsx("h2",{children:"System Status"}),n.jsx(ob,{}),n.jsx(db,{}),n.jsxs("section",{className:"status-section-active",children:[n.jsxs("h3",{children:["Active (",p.length,")"]}),n.jsxs("div",{className:"status-grid",children:[p.map(g=>n.jsxs("div",{className:"status-card",children:[n.jsx("span",{className:"status-dot-green"}),n.jsxs("div",{className:"status-card-info",children:[n.jsx("strong",{children:g.name}),n.jsx("span",{className:"status-card-category",children:g.category})]})]},g.id)),p.length===0&&n.jsx("p",{className:"status-empty",children:"No active features"})]})]}),n.jsxs("section",{className:"status-section-ready",children:[n.jsxs("h3",{children:["Ready (",x.length,")"]}),n.jsxs("div",{className:"status-grid",children:[x.map(g=>n.jsxs("div",{className:"status-card",children:[n.jsx("span",{className:"status-dot-yellow"}),n.jsxs("div",{className:"status-card-info",children:[n.jsx("strong",{children:g.name}),n.jsx("span",{className:"status-card-category",children:g.category})]}),n.jsx("button",{className:"status-configure-btn",children:"Configure"})]},g.id)),x.length===0&&n.jsx("p",{className:"status-empty",children:"No features awaiting configuration"})]})]}),n.jsxs("section",{className:"status-section-available",children:[n.jsxs("h3",{children:["Available (",y.length,")"]}),n.jsxs("div",{className:"status-grid",children:[y.map(g=>n.jsxs("div",{className:"status-card",children:[n.jsx("span",{className:"status-dot-gray"}),n.jsxs("div",{className:"status-card-info",children:[n.jsx("strong",{children:g.name}),n.jsx("span",{className:"status-card-category",children:g.category})]})]},g.id)),y.length===0&&n.jsx("p",{className:"status-empty",children:"All features are enabled"})]})]})]})}const mb=["all","preference","fact","context","relationship","pattern","personality"],pb={preference:"mm-badge-accent",fact:"mm-badge-blue",context:"mm-badge-gray",relationship:"mm-badge-green",pattern:"mm-badge-amber",personality:"mm-badge-purple"};function am(s){return new Date(s).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function Im(){const[s,r]=h.useState([]),[u,o]=h.useState(!0),[f,m]=h.useState(null),[p,x]=h.useState(""),[y,g]=h.useState("all"),[b,j]=h.useState(null),[S,w]=h.useState(null),[A,D]=h.useState(""),[O,E]=h.useState(0),[M,k]=h.useState(""),[Z,K]=h.useState(null),[q,W]=h.useState(""),[G,te]=h.useState(null),[ce,ie]=h.useState(!1),he=h.useCallback(()=>{o(!0),m(null);const I=y==="all"?void 0:y;(p?J.searchMemories(p):J.getMemories(I)).then(C=>{r(C.data),o(!1)}).catch(C=>{m(C instanceof Error?C.message:String(C)),o(!1)})},[y,p]);h.useEffect(()=>{he()},[he]);function ee(I){w(I.id),D(I.content),E(I.importance),k(I.tags.join(", "))}function oe(){w(null)}function ve(I){const de=M.split(",").map(C=>C.trim()).filter(Boolean);J.updateMemory(I,{content:A,importance:O,tags:de}).then(()=>{w(null),he()}).catch(C=>m(C instanceof Error?C.message:String(C)))}function H(I){J.deleteMemory(I).then(()=>{K(null),he()}).catch(de=>m(de instanceof Error?de.message:String(de)))}function F(){q.trim()&&(ie(!0),te(null),J.forgetTopic(q.trim()).then(I=>{te(`Removed ${I.removed.memories} memories and ${I.removed.decisions} decisions.`),W(""),ie(!1),he()}).catch(I=>{te(I instanceof Error?I.message:String(I)),ie(!1)}))}function le(){J.exportPersonalization().then(I=>{const de=new Blob([JSON.stringify(I,null,2)],{type:"application/json"}),C=URL.createObjectURL(de),L=document.createElement("a");L.href=C,L.download=`auxiora-export-${Date.now()}.json`,L.click(),URL.revokeObjectURL(C)}).catch(I=>m(I instanceof Error?I.message:String(I)))}return u?n.jsx("div",{className:"mm-page",children:n.jsx("div",{className:"mm-loading",children:"Loading memories..."})}):f?n.jsxs("div",{className:"mm-page",children:[n.jsx("div",{className:"mm-header",children:n.jsx("h2",{className:"mm-title",children:"Memories"})}),n.jsx("div",{className:"mm-error",children:f})]}):n.jsxs("div",{className:"mm-page",children:[n.jsxs("div",{className:"mm-header",children:[n.jsx("h2",{className:"mm-title",children:"Memories"}),n.jsx("input",{className:"mm-search",type:"text",placeholder:"Search memories...",value:p,onChange:I=>x(I.target.value)}),n.jsx("select",{className:"mm-filter",value:y,onChange:I=>g(I.target.value),children:mb.map(I=>n.jsx("option",{value:I,children:I==="all"?"All categories":I},I))})]}),s.length===0?n.jsx("div",{className:"mm-empty",children:"No memories yet"}):n.jsx("div",{className:"mm-grid",children:s.map(I=>n.jsx("div",{className:"mm-card",children:S===I.id?n.jsxs("div",{className:"mm-edit-form",children:[n.jsx("textarea",{className:"mm-edit-content",value:A,onChange:de=>D(de.target.value),rows:3}),n.jsxs("label",{className:"mm-edit-label",children:["Importance (",O.toFixed(2),")",n.jsx("input",{type:"range",min:"0",max:"1",step:"0.01",value:O,onChange:de=>E(Number(de.target.value)),className:"mm-edit-slider"})]}),n.jsxs("label",{className:"mm-edit-label",children:["Tags (comma-separated)",n.jsx("input",{type:"text",className:"mm-edit-tags-input",value:M,onChange:de=>k(de.target.value)})]}),n.jsxs("div",{className:"mm-edit-actions",children:[n.jsx("button",{className:"mm-btn mm-btn-save",onClick:()=>ve(I.id),children:"Save"}),n.jsx("button",{className:"mm-btn mm-btn-cancel",onClick:oe,children:"Cancel"})]})]}):n.jsxs(n.Fragment,{children:[n.jsx("div",{className:`mm-content ${b===I.id?"mm-content-expanded":""}`,onClick:()=>j(b===I.id?null:I.id),children:I.content}),n.jsxs("div",{className:"mm-meta-row",children:[n.jsx("span",{className:`mm-category-badge ${pb[I.category]||"mm-badge-gray"}`,children:I.category}),n.jsx("span",{className:"mm-source-badge",children:I.source})]}),n.jsx("div",{className:"mm-importance-track",children:n.jsx("div",{className:"mm-importance-bar","data-level":I.importance>=.7?"high":I.importance>=.4?"mid":"low",style:{width:`${Math.round(I.importance*100)}%`},role:"progressbar","aria-valuenow":I.importance,"aria-valuemin":0,"aria-valuemax":1,"aria-label":`Importance: ${Math.round(I.importance*100)}%`})}),I.tags.length>0&&n.jsx("div",{className:"mm-tags",children:I.tags.map(de=>n.jsx("span",{className:"mm-tag",children:de},de))}),n.jsxs("div",{className:"mm-timestamps",children:[n.jsxs("span",{children:["Created ",am(I.createdAt)]}),n.jsxs("span",{children:["Updated ",am(I.updatedAt)]})]}),n.jsx("div",{className:"mm-card-actions",children:Z===I.id?n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"mm-confirm-text",children:"Delete?"}),n.jsx("button",{className:"mm-btn mm-btn-danger",onClick:()=>H(I.id),children:"Yes"}),n.jsx("button",{className:"mm-btn mm-btn-cancel",onClick:()=>K(null),children:"No"})]}):n.jsxs(n.Fragment,{children:[n.jsx("button",{className:"mm-btn mm-btn-edit",onClick:()=>ee(I),children:"Edit"}),n.jsx("button",{className:"mm-btn mm-btn-delete",onClick:()=>K(I.id),children:"Delete"})]})})]})},I.id))}),n.jsxs("section",{className:"mm-forget-section",children:[n.jsx("h3",{className:"mm-section-title",children:"Selective Forgetting"}),n.jsx("p",{className:"mm-section-desc",children:"Remove all memories and decisions related to a topic."}),n.jsxs("div",{className:"mm-forget-row",children:[n.jsx("input",{className:"mm-forget-input",type:"text",placeholder:"Topic to forget...",value:q,onChange:I=>W(I.target.value)}),n.jsx("button",{className:"mm-btn mm-btn-danger",onClick:F,disabled:ce||!q.trim(),children:ce?"Forgetting...":"Forget"})]}),G&&n.jsx("div",{className:"mm-forget-result",children:G})]}),n.jsxs("section",{className:"mm-export-section",children:[n.jsx("h3",{className:"mm-section-title",children:"Export Data"}),n.jsx("p",{className:"mm-section-desc",children:"Download all personalization data as JSON."}),n.jsx("button",{className:"mm-btn mm-btn-export",onClick:le,children:"Export All Data"})]})]})}function gb({scores:s,maxScore:r=100}){if(!s||Object.keys(s).length===0)return null;const u=Object.entries(s).sort((o,f)=>f[1]-o[1]);return n.jsx("div",{className:"bc-chart",children:u.map(([o,f])=>n.jsxs("div",{className:"bc-row",children:[n.jsx("span",{className:"bc-label",title:o,children:o}),n.jsx("div",{className:"bc-bar-track",children:n.jsx("div",{className:"bc-bar-fill",style:{width:`${Math.min(100,f/r*100)}%`}})}),n.jsx("span",{className:"bc-value",children:f.toFixed(1)})]},o))})}function vb(s){return s>=1e6?`${(s/1e6).toFixed(1)}M`:s>=1e3?`${Math.round(s/1e3)}K`:String(s)}function nm(s){return s===0?"Free":s<.001?`$${s.toFixed(4)}`:`$${s.toFixed(3)}`}function yb(s){const r=Date.now()-s,u=Math.floor(r/6e4);if(u<1)return"just now";if(u<60)return`${u}m ago`;const o=Math.floor(u/60);return o<24?`${o}h ago`:`${Math.floor(o/24)}d ago`}function lm(s){return s>=1e6?`${(s/1e6).toFixed(1)}M`:s>=1e3?`${(s/1e3).toFixed(1)}K`:String(s)}function xb({model:s,onToggleEnabled:r}){const u=s.displayName||s.modelId,o=s.providerSource==="openrouter",f=s.providerSource==="huggingface";return n.jsxs("div",{className:`mc-card ${s.enabled?"":"mc-card-disabled"}`,children:[n.jsxs("div",{className:"mc-header",children:[n.jsx("span",{className:"mc-name",title:s.modelId,children:u}),n.jsx("span",{className:`mc-provider ${o?"mc-provider-openrouter":""} ${f?"mc-provider-hf":""}`,children:s.providerSource})]}),n.jsxs("div",{className:"mc-context",children:[n.jsx("span",{className:"mc-context-label",children:"Context"}),n.jsx("span",{className:"mc-context-value",children:vb(s.contextLength)})]}),n.jsxs("div",{className:"mc-capabilities",children:[s.supportsVision&&n.jsx("span",{className:"mc-badge mc-badge-blue",children:"Vision"}),s.supportsTools&&n.jsx("span",{className:"mc-badge mc-badge-green",children:"Tools"}),s.supportsStreaming&&n.jsx("span",{className:"mc-badge mc-badge-gray",children:"Streaming"}),s.supportsImageGen&&n.jsx("span",{className:"mc-badge mc-badge-purple",children:"ImageGen"})]}),(s.costPer1kInput>0||s.costPer1kOutput>0)&&n.jsxs("div",{className:"mc-cost",children:[n.jsxs("span",{className:"mc-cost-item",children:["In: ",nm(s.costPer1kInput),"/1K"]}),n.jsxs("span",{className:"mc-cost-item",children:["Out: ",nm(s.costPer1kOutput),"/1K"]})]}),s.strengths&&s.strengths.length>0&&n.jsx("div",{className:"mc-strengths",children:s.strengths.map(m=>n.jsx("span",{className:"mc-strength-pill",children:m},m))}),f&&n.jsxs("div",{className:"mc-hf-stats",children:[s.hfDownloads!=null&&n.jsxs("span",{className:"mc-hf-stat",title:"Downloads",children:["↓"," ",lm(s.hfDownloads)]}),s.hfLikes!=null&&n.jsxs("span",{className:"mc-hf-stat",title:"Likes",children:["♥"," ",lm(s.hfLikes)]}),s.hfTrendingScore!=null&&n.jsxs("span",{className:"mc-hf-stat",title:"Trending Score",children:["↑"," ",s.hfTrendingScore.toFixed(1)]})]}),s.hfBenchmarkScores&&Object.keys(s.hfBenchmarkScores).length>0&&n.jsx(gb,{scores:s.hfBenchmarkScores}),n.jsxs("div",{className:"mc-footer",children:[n.jsx("span",{className:"mc-refreshed",title:new Date(s.lastRefreshedAt).toLocaleString(),children:yb(s.lastRefreshedAt)}),n.jsx("button",{className:`mc-toggle ${s.enabled?"mc-toggle-on":"mc-toggle-off"}`,onClick:()=>r(s.id,!s.enabled),title:s.enabled?"Disable model":"Enable model",children:s.enabled?"Enabled":"Disabled"})]})]})}const bb=[{key:"all",label:"All Models"},{key:"openrouter",label:"OpenRouter"},{key:"huggingface",label:"HuggingFace"},{key:"trending",label:"Trending"}];function jb(){const[s,r]=h.useState("all"),[u,o]=h.useState([]),[f,m]=h.useState(""),[p,x]=h.useState(!1),[y,g]=h.useState(!1),[b,j]=h.useState(!1),[S,w]=h.useState(!1),[A,D]=h.useState(null),O=h.useCallback(async()=>{x(!0),D(null);try{let Z;if(s==="trending")Z="/api/v1/models/trending?limit=50";else{const q=new URLSearchParams;s!=="all"&&q.set("source",s),f&&q.set("search",f),b&&q.set("supportsVision","true"),S&&q.set("supportsTools","true"),q.set("limit","200"),Z=`/api/v1/models/discovered?${q}`}const K=await fetch(Z);if(K.ok){const q=await K.json();o(q.models||[])}else D(`Failed to load models (${K.status})`)}catch{D("Failed to fetch models")}x(!1)},[s,f,b,S]);h.useEffect(()=>{O()},[O]);const E=async()=>{g(!0);try{await fetch("/api/v1/models/refresh",{method:"POST"}),setTimeout(()=>{O(),g(!1)},3e3)}catch{g(!1)}},M=async(Z,K)=>{try{await fetch("/api/v1/models/discovered/toggle",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:Z,enabled:K})}),o(q=>q.map(W=>W.id===Z?{...W,enabled:K}:W))}catch{}},k=Z=>{r(Z),m("")};return n.jsxs("div",{className:"me-page",children:[n.jsxs("div",{className:"me-header",children:[n.jsx("h2",{className:"me-title",children:"Model Explorer"}),n.jsxs("div",{className:"me-header-right",children:[n.jsxs("span",{className:"me-count",children:[u.length," model",u.length!==1?"s":""]}),n.jsx("button",{className:"me-refresh-btn",onClick:E,disabled:y,children:y?"Refreshing...":"Refresh"})]})]}),n.jsxs("div",{className:"me-toolbar",children:[n.jsx("div",{className:"me-tabs",children:bb.map(Z=>n.jsx("button",{className:`me-tab ${s===Z.key?"active":""}`,onClick:()=>k(Z.key),children:Z.label},Z.key))}),s!=="trending"&&n.jsx("input",{className:"me-search",type:"text",placeholder:"Search models...",value:f,onChange:Z=>m(Z.target.value)})]}),s!=="trending"&&n.jsxs("div",{className:"me-filters",children:[n.jsxs("label",{className:"me-filter-check",children:[n.jsx("input",{type:"checkbox",checked:b,onChange:Z=>j(Z.target.checked)}),"Vision"]}),n.jsxs("label",{className:"me-filter-check",children:[n.jsx("input",{type:"checkbox",checked:S,onChange:Z=>w(Z.target.checked)}),"Tools"]})]}),p?n.jsx("div",{className:"me-loading",children:"Loading models..."}):A?n.jsx("div",{className:"me-error",children:A}):u.length===0?n.jsx("div",{className:"me-empty",children:"No models found. Try adjusting your filters or refreshing."}):n.jsx("div",{className:"me-grid",children:u.map(Z=>n.jsx(xb,{model:Z,onToggleEnabled:M},Z.id))})]})}function Sb(){const[s,r]=h.useState([]),[u,o]=h.useState(!0),[f,m]=h.useState(""),[p,x]=h.useState(null),[y,g]=h.useState(!1),[b,j]=h.useState(new Map),S=h.useRef(null),w=h.useCallback(async()=>{o(!0),m("");try{const O=await fetch("/api/v1/canvas/sessions");if(!O.ok)throw new Error(`HTTP ${O.status}`);const E=await O.json();r(Array.isArray(E)?E:E.sessions??[])}catch(O){m(O instanceof Error?O.message:"Failed to load sessions")}finally{o(!1)}},[]);h.useEffect(()=>{w()},[w]);const A=h.useCallback(O=>{S.current&&(S.current.close(),S.current=null),x(O),j(new Map),g(!1);const M=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/api/v1/canvas/sessions/${O}/ws`,k=new WebSocket(M);S.current=k,k.addEventListener("open",()=>g(!0)),k.addEventListener("close",()=>g(!1)),k.addEventListener("error",()=>g(!1)),k.addEventListener("message",Z=>{let K;try{K=JSON.parse(String(Z.data))}catch{return}switch(K.type){case"canvas:snapshot":j(new Map(K.objects.map(q=>[q.id,q])));break;case"object:added":case"object:updated":j(q=>{const W=new Map(q);return W.set(K.object.id,K.object),W});break;case"object:removed":j(q=>{const W=new Map(q);return W.delete(K.id),W});break;case"canvas:cleared":j(new Map);break}})},[]),D=h.useCallback(()=>{S.current&&(S.current.close(),S.current=null),x(null),g(!1),j(new Map),w()},[w]);if(h.useEffect(()=>()=>{S.current&&(S.current.close(),S.current=null)},[]),p){const O=Array.from(b.values()).filter(E=>E.visible!==!1);return n.jsxs("div",{style:{padding:16},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,marginBottom:12},children:[n.jsx("button",{className:"btn btn-sm",onClick:D,children:"Back"}),n.jsxs("span",{style:{fontWeight:600},children:["Session: ",p]}),n.jsx("span",{className:`lc-status ${y?"lc-connected":"lc-disconnected"}`,children:y?"Connected":"Disconnected"})]}),n.jsxs("div",{className:"lc-canvas",style:{position:"relative",minHeight:400},children:[O.length===0&&n.jsx("p",{className:"lc-empty",style:{textAlign:"center"},children:"No objects on canvas"}),O.map(E=>n.jsxs("div",{className:"lc-obj",style:{position:"absolute",left:E.x,top:E.y,width:E.width,height:E.height},children:[E.type==="text"&&n.jsx("div",{className:"lc-text",children:E.content??""}),E.type==="image"&&n.jsx("img",{className:"lc-image",src:E.src,alt:E.alt??"",style:{width:"100%",height:"100%"}}),E.type==="widget"&&n.jsx("div",{className:"lc-text",children:E.content??`[widget ${E.id}]`}),E.type!=="text"&&E.type!=="image"&&E.type!=="widget"&&n.jsxs("div",{className:"lc-text",children:["[",E.type,"]"]})]},E.id))]})]})}return n.jsxs("div",{style:{padding:16},children:[n.jsx("h2",{style:{marginBottom:12},children:"Canvas Sessions"}),u&&n.jsx("p",{className:"lc-empty",children:"Loading sessions..."}),f&&n.jsx("p",{style:{color:"var(--error)"},children:f}),!u&&!f&&s.length===0&&n.jsx("p",{className:"lc-empty",children:"No canvas sessions available"}),!u&&s.length>0&&n.jsx("div",{className:"lc-sessions",children:s.map(O=>n.jsx("button",{className:"btn",onClick:()=>A(O.id),children:O.name??O.id},O.id))})]})}function Nb(s){return s>.8?"dw-score-green":s>.6?"dw-score-yellow":s>.4?"dw-score-red":"dw-score-grey"}function Cb(s){const r=Date.now()-s,u=Math.floor(r/6e4);if(u<1)return"just now";if(u<60)return`${u}m ago`;const o=Math.floor(u/60);return o<24?`${o}h ago`:`${Math.floor(o/24)}d ago`}function Eb(){const[s,r]=h.useState(null),[u,o]=h.useState([]),[f,m]=h.useState(null),[p,x]=h.useState([]),[y,g]=h.useState(!0),[b,j]=h.useState(null),[S,w]=h.useState(null),A=h.useCallback(async()=>{try{const[q,W,G,te]=await Promise.all([J.getDarwinStatus(),J.getDarwinArchive(),J.getDarwinGovernor(),J.getDarwinApprovals()]);r(q),o(W),m(G),x(te),j(null)}catch{j("Failed to load Darwin data")}g(!1)},[]);h.useEffect(()=>{A();const q=setInterval(A,1e4);return()=>clearInterval(q)},[A]);const D=async()=>{if(s){w("pause-resume");try{s.running?await J.pauseDarwin():await J.resumeDarwin(),await A()}catch{j("Failed to toggle Darwin")}w(null)}},O=async q=>{w(q);try{await J.approveDarwinVariant(q),await A()}catch{j(`Failed to approve ${q}`)}w(null)},E=async q=>{w(q);try{await J.rejectDarwinVariant(q),await A()}catch{j(`Failed to reject ${q}`)}w(null)};if(y)return n.jsx("div",{className:"dw-page",children:n.jsx("p",{children:"Loading..."})});if(b&&!s)return n.jsx("div",{className:"dw-page",children:n.jsx("p",{className:"dw-error",children:b})});const M=s&&s.totalCycles>0?(s.successfulCycles/s.totalCycles*100).toFixed(1):"0.0",k=[...new Set(u.map(q=>q.niche.domain))].sort(),Z=[...new Set(u.map(q=>q.niche.complexity))].sort(),K=new Map;for(const q of u)K.set(`${q.niche.domain}|${q.niche.complexity}`,q);return n.jsxs("div",{className:"dw-page",children:[n.jsxs("div",{className:"dw-header",children:[n.jsxs("div",{className:"dw-header-left",children:[n.jsx("h2",{className:"dw-title",children:"Evolution"}),s&&n.jsx("span",{className:`dw-badge ${s.running?"dw-badge-running":"dw-badge-paused"}`,children:s.running?"Running":"Paused"})]}),n.jsx("button",{className:"dw-btn dw-btn-toggle",disabled:S==="pause-resume",onClick:D,children:s!=null&&s.running?"Pause":"Resume"})]}),b&&n.jsx("p",{className:"dw-error",children:b}),s&&f&&n.jsxs("div",{className:"dw-stats",children:[n.jsxs("div",{className:"dw-stat-card",children:[n.jsx("span",{className:"dw-stat-value",children:s.totalCycles}),n.jsx("span",{className:"dw-stat-label",children:"Total Cycles"})]}),n.jsxs("div",{className:"dw-stat-card",children:[n.jsxs("span",{className:"dw-stat-value",children:[M,"%"]}),n.jsx("span",{className:"dw-stat-label",children:"Success Rate"})]}),n.jsxs("div",{className:"dw-stat-card",children:[n.jsx("span",{className:"dw-stat-value",children:s.archiveOccupancy}),n.jsx("span",{className:"dw-stat-label",children:"Archive Occupancy"})]}),n.jsxs("div",{className:"dw-stat-card",children:[n.jsx("span",{className:"dw-stat-value",children:f.tokensUsedThisHour.toLocaleString()}),n.jsx("span",{className:"dw-stat-label",children:"Tokens / Hour"})]}),n.jsxs("div",{className:"dw-stat-card",children:[n.jsx("span",{className:"dw-stat-value",children:f.variantsCreatedToday}),n.jsx("span",{className:"dw-stat-label",children:"Variants / Day"})]})]}),u.length>0&&n.jsxs("div",{className:"dw-section",children:[n.jsx("h3",{className:"dw-section-title",children:"Archive"}),n.jsx("div",{className:"dw-table-wrap",children:n.jsxs("table",{className:"dw-archive-table",children:[n.jsx("thead",{children:n.jsxs("tr",{children:[n.jsx("th",{children:"Domain"}),Z.map(q=>n.jsx("th",{children:q},q))]})}),n.jsx("tbody",{children:k.map(q=>n.jsxs("tr",{children:[n.jsx("td",{className:"dw-domain-cell",children:q}),Z.map(W=>{const G=K.get(`${q}|${W}`);return n.jsx("td",{className:"dw-score-cell",children:G?n.jsx("span",{className:`dw-score-badge ${Nb(G.benchmarkScore)}`,title:`Variant: ${G.variantId}
|
|
61
61
|
Score: ${G.benchmarkScore.toFixed(3)}
|
|
62
62
|
Staleness: ${G.staleness}`,children:G.benchmarkScore.toFixed(2)}):n.jsx("span",{className:"dw-score-badge dw-score-grey",children:"--"})},W)})]},q))})]})})]}),n.jsxs("div",{className:"dw-section",children:[n.jsxs("h3",{className:"dw-section-title",children:["Pending Approvals (",p.length,")"]}),p.length===0?n.jsx("p",{className:"dw-empty",children:"No pending approvals."}):n.jsx("div",{className:"dw-approval-list",children:p.map(q=>n.jsxs("div",{className:"dw-approval-item",children:[n.jsxs("div",{className:"dw-approval-info",children:[n.jsx("span",{className:"dw-approval-id",children:q.variantId}),n.jsx("span",{className:"dw-approval-time",children:Cb(q.queuedAt)})]}),n.jsxs("div",{className:"dw-approval-actions",children:[n.jsx("button",{className:"dw-btn dw-btn-approve",disabled:S===q.variantId,onClick:()=>O(q.variantId),children:"Approve"}),n.jsx("button",{className:"dw-btn dw-btn-reject",disabled:S===q.variantId,onClick:()=>E(q.variantId),children:"Reject"})]})]},q.variantId))})]})]})}const ep=[{id:"chat",label:"Chat",icon:"💬",component:()=>n.jsx(km,{}),defaultWidth:860,defaultHeight:600},{id:"status",label:"System Status",icon:"📊",component:()=>n.jsx(hb,{}),defaultWidth:860,defaultHeight:640},{id:"overview",label:"Mission Control",icon:"🎯",component:()=>n.jsx(Dm,{}),defaultWidth:820,defaultHeight:600},{id:"architect",label:"The Architect",icon:"🏗️",component:()=>n.jsx(Jm,{}),defaultWidth:780,defaultHeight:600},{id:"profile",label:"About Me",icon:"👤",component:()=>n.jsx(Wm,{}),defaultWidth:780,defaultHeight:600},{id:"memories",label:"Memories",icon:"🧠",component:()=>n.jsx(Im,{}),defaultWidth:860,defaultHeight:640},{id:"behaviors",label:"Behaviors",icon:"🧩",component:()=>n.jsx(Bm,{}),defaultWidth:780,defaultHeight:560},{id:"webhooks",label:"Webhooks",icon:"🔗",component:()=>n.jsx(qm,{}),defaultWidth:780,defaultHeight:560},{id:"personality",label:"Personality",icon:"🎭",component:()=>n.jsx(Ym,{}),defaultWidth:680,defaultHeight:520},{id:"provider",label:"Provider",icon:"🔌",component:()=>n.jsx(Gm,{}),defaultWidth:680,defaultHeight:520},{id:"channels",label:"Channels",icon:"📡",component:()=>n.jsx($m,{}),defaultWidth:680,defaultHeight:520},{id:"connections",label:"Connections",icon:"🌐",component:()=>n.jsx(Km,{}),defaultWidth:780,defaultHeight:560},{id:"ambient",label:"Ambient",icon:"🌊",component:()=>n.jsx(Zm,{}),defaultWidth:680,defaultHeight:520},{id:"appearance",label:"Appearance",icon:"🎨",component:()=>n.jsx(Qm,{}),defaultWidth:680,defaultHeight:520},{id:"notifications",label:"Notifications",icon:"🔔",component:()=>n.jsx(Fm,{}),defaultWidth:680,defaultHeight:520},{id:"security",label:"Security",icon:"🛡️",component:()=>n.jsx(Xm,{}),defaultWidth:680,defaultHeight:520},{id:"marketplace",label:"Marketplace",icon:"🏪",component:()=>n.jsx(ub,{}),defaultWidth:900,defaultHeight:640},{id:"models",label:"Models",icon:"🤖",component:()=>n.jsx(jb,{}),defaultWidth:900,defaultHeight:650},{id:"canvas",label:"Canvas",icon:"🖌️",component:()=>n.jsx(Sb,{}),defaultWidth:900,defaultHeight:640},{id:"evolution",label:"Evolution",icon:"🧬",component:()=>n.jsx(Eb,{}),defaultWidth:900,defaultHeight:650},{id:"audit",label:"Audit Log",icon:"📋",component:()=>n.jsx(Pm,{}),defaultWidth:820,defaultHeight:600}],Au=new Map(ep.map(s=>[s.id,s])),wb=ep.map(s=>({id:s.id,label:s.label,icon:s.icon}));function Tb(){const[s,r]=h.useState(()=>sm(new Date));return h.useEffect(()=>{const u=setInterval(()=>r(sm(new Date)),6e4);return()=>clearInterval(u)},[]),s}function sm(s){return s.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}function Ab(){var ce;const[s,r]=h.useState(!0),[u,o]=h.useState(!1),[f,m]=h.useState("Auxiora"),[p,x]=h.useState(""),y=Ct(),g=Tb();h.useEffect(()=>{J.getSetupStatus().then(ie=>{ie.agentName&&m(ie.agentName),ie.needsSetup?y("/setup",{replace:!0}):ie.vaultUnlocked?o(!0):y("/unlock",{replace:!0})}).catch(()=>{}).finally(()=>r(!1)),fetch("/health").then(ie=>ie.json()).then(ie=>{ie.version&&x(ie.version)}).catch(()=>{})},[]);const{refresh:b}=ut(()=>u?J.getStatus():Promise.resolve(null),[u]),{refresh:j}=ut(()=>u?J.getSessions():Promise.resolve(null),[u]);Os(()=>{u&&(b(),j())});const{windows:S,activeWindowId:w,snapEnabled:A,gridSize:D,openWindow:O,closeWindow:E,focusWindow:M,moveWindow:k,resizeWindow:Z,toggleMinimize:K,toggleMaximize:q,toggleSnap:W}=rx(),G=h.useMemo(()=>new Set(S.keys()),[S]),te=h.useCallback(ie=>{const he=Au.get(ie);he&&O(ie,he.label,he.defaultWidth,he.defaultHeight)},[O]);return s?null:n.jsxs("div",{className:"desktop-shell",children:[n.jsx("div",{className:"desktop-bg"}),n.jsxs("div",{className:"topbar",children:[n.jsx("div",{className:"topbar-left",children:n.jsx("span",{children:f})}),n.jsx("div",{className:"topbar-center",children:w&&((ce=Au.get(w))==null?void 0:ce.label)}),n.jsxs("div",{className:"topbar-right",children:[n.jsx("button",{className:`grid-toggle${A?" grid-toggle--active":""}`,onClick:W,title:A?"Disable snap to grid":"Enable snap to grid",children:n.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",children:[n.jsx("rect",{x:"0.5",y:"0.5",width:"5",height:"5",rx:"0.5",stroke:"currentColor",strokeWidth:"1"}),n.jsx("rect",{x:"8.5",y:"0.5",width:"5",height:"5",rx:"0.5",stroke:"currentColor",strokeWidth:"1"}),n.jsx("rect",{x:"0.5",y:"8.5",width:"5",height:"5",rx:"0.5",stroke:"currentColor",strokeWidth:"1"}),n.jsx("rect",{x:"8.5",y:"8.5",width:"5",height:"5",rx:"0.5",stroke:"currentColor",strokeWidth:"1"})]})}),p&&n.jsxs("span",{style:{opacity:.5,marginRight:8,fontSize:"0.85em"},children:["v",p]}),n.jsx("span",{children:g})]})]}),n.jsx(fx,{}),n.jsxs("div",{style:{position:"relative",flex:1},children:[A&&n.jsx("div",{className:"grid-overlay",style:{backgroundSize:`${D}px ${D}px`}}),Array.from(S.values()).map(ie=>{const he=Au.get(ie.id);return he?n.jsx(ox,{id:ie.id,title:he.label,x:ie.x,y:ie.y,width:ie.width,height:ie.height,zIndex:ie.zIndex,minimized:ie.minimized,maximized:ie.maximized,focused:ie.id===w,onClose:()=>E(ie.id),onFocus:()=>M(ie.id),onMinimize:()=>K(ie.id),onMaximize:()=>q(ie.id),onMove:(ee,oe)=>k(ie.id,ee,oe),onResize:(ee,oe)=>Z(ie.id,ee,oe),children:he.component()},ie.id):null})]}),n.jsx(dx,{items:wb,openWindows:G,onOpen:te})]})}function Ob(){const[s,r]=h.useState(""),[u,o]=h.useState(""),[f,m]=h.useState(!1),[p,x]=h.useState(!0),[y,g]=h.useState("Auxiora"),b=Ct();h.useEffect(()=>{J.getSetupStatus().then(S=>{S.agentName&&g(S.agentName),S.needsSetup?b("/setup",{replace:!0}):S.vaultUnlocked||b("/unlock",{replace:!0})}).catch(()=>{}).finally(()=>x(!1))},[]);const j=async S=>{S.preventDefault(),m(!0),o("");try{await J.login(s),b("/")}catch(w){o(w.message||"Login failed")}finally{m(!1)}};return p?null:n.jsx("div",{className:"login-page",children:n.jsxs("div",{className:"login-card",children:[n.jsxs("h1",{children:[y," Mission Control"]}),n.jsxs("form",{onSubmit:j,children:[n.jsx("input",{type:"password",value:s,onChange:S=>r(S.target.value),placeholder:"Password",autoFocus:!0}),n.jsx("button",{type:"submit",disabled:f,children:f?"Logging in...":"Login"}),u&&n.jsx("p",{className:"error",children:u})]})]})})}function Mb(){const[s,r]=h.useState(""),[u,o]=h.useState(""),[f,m]=h.useState(!1),[p,x]=h.useState("Auxiora"),y=Ct();h.useEffect(()=>{J.getSetupStatus().then(b=>{b.agentName&&x(b.agentName)}).catch(()=>{})},[]);const g=async b=>{if(b.preventDefault(),!!s){m(!0),o("");try{await J.setupVault(s),y("/login",{replace:!0})}catch(j){o(j instanceof Error?j.message:"Wrong password")}finally{m(!1)}}};return n.jsx("div",{className:"login-page",children:n.jsxs("div",{className:"login-card",children:[n.jsx("h1",{children:"Unlock Vault"}),n.jsxs("p",{style:{color:"var(--text-secondary)",marginBottom:"1.5rem",fontSize:"0.9rem"},children:["Enter your vault password to start ",p,"."]}),n.jsxs("form",{onSubmit:g,children:[n.jsx("input",{type:"password",value:s,onChange:b=>r(b.target.value),placeholder:"Vault password",autoFocus:!0}),n.jsx("button",{type:"submit",disabled:f||!s,children:f?"Unlocking...":"Unlock"}),u&&n.jsx("p",{className:"error",children:u})]})]})})}function Rb(){const s=Ct();return n.jsx("div",{className:"setup-page",children:n.jsxs("div",{className:"setup-card",style:{textAlign:"center"},children:[n.jsx("h1",{children:"Welcome to Auxiora"}),n.jsx("p",{className:"subtitle",children:"Your personal AI assistant. Let's get you set up — it only takes a minute."}),n.jsx("button",{className:"setup-btn-primary",onClick:()=>s("/setup/vault"),children:"Get Started"})]})})}function Ha({currentStep:s,totalSteps:r=8}){return n.jsx("div",{className:"setup-progress",children:Array.from({length:r},(u,o)=>{const f=o+1,m=f<s,p=f===s;return n.jsxs("div",{style:{display:"flex",alignItems:"center"},children:[o>0&&n.jsx("div",{className:`setup-progress-line${m||p?" completed":""}`}),n.jsx("div",{className:`setup-progress-step${p?" active":""}${m?" completed":""}`,children:m?"✓":f})]},f)})})}function Db(){const[s,r]=h.useState(""),[u,o]=h.useState(""),[f,m]=h.useState(""),[p,x]=h.useState(!1),y=Ct(),g=async b=>{if(b.preventDefault(),s.length<8){m("Password must be at least 8 characters");return}if(s!==u){m("Passwords do not match");return}x(!0),m("");try{await J.setupVault(s),y("/setup/dashboard-password")}catch(j){m(j instanceof Error?j.message:"Failed to create vault")}finally{x(!1)}};return n.jsxs("div",{className:"setup-page",children:[n.jsx(Ha,{currentStep:1}),n.jsxs("div",{className:"setup-card",children:[n.jsx("h1",{children:"Create Vault Password"}),n.jsx("p",{className:"subtitle",children:"This password encrypts your secrets. Store it somewhere safe — it cannot be recovered."}),n.jsxs("form",{onSubmit:g,children:[n.jsx("label",{children:"Vault password"}),n.jsx("input",{type:"password",value:s,onChange:b=>r(b.target.value),autoFocus:!0}),n.jsx(Pi,{password:s}),n.jsx("label",{children:"Confirm password"}),n.jsx("input",{type:"password",value:u,onChange:b=>o(b.target.value)}),n.jsx("button",{type:"submit",className:"setup-btn-primary",disabled:p,children:p?"Creating...":"Create Vault"}),f&&n.jsx("p",{className:"error",children:f})]})]})]})}function zb(){const[s,r]=h.useState(""),[u,o]=h.useState(""),[f,m]=h.useState(""),[p,x]=h.useState(!1),y=Ct(),g=async b=>{if(b.preventDefault(),s.length<8){m("Password must be at least 8 characters");return}if(s!==u){m("Passwords do not match");return}x(!0),m("");try{await J.setupDashboardPassword(s),y("/setup/identity")}catch(j){m(j instanceof Error?j.message:"Failed to set password")}finally{x(!1)}};return n.jsxs("div",{className:"setup-page",children:[n.jsx(Ha,{currentStep:2}),n.jsxs("div",{className:"setup-card",children:[n.jsx("h1",{children:"Mission Control Password"}),n.jsx("p",{className:"subtitle",children:"This password protects Mission Control. You'll use it to log in."}),n.jsxs("form",{onSubmit:g,children:[n.jsx("label",{children:"Password"}),n.jsx("input",{type:"password",value:s,onChange:b=>r(b.target.value),autoFocus:!0}),n.jsx(Pi,{password:s}),n.jsx("label",{children:"Confirm password"}),n.jsx("input",{type:"password",value:u,onChange:b=>o(b.target.value)}),n.jsx("button",{type:"submit",className:"setup-btn-primary",disabled:p,children:p?"Saving...":"Set Password"}),f&&n.jsx("p",{className:"error",children:f})]})]})]})}const im=["Nova","Atlas","Jasper","Echo","Sage","Onyx","Iris","Phoenix","Kai","Luna","Orion","Zephyr","Rune","Pixel","Nyx","Sol","Cleo","Juno","Vex","Aura"];function kb(){const s=h.useMemo(()=>im[Math.floor(Math.random()*im.length)],[]),[r,u]=h.useState(""),[o,f]=h.useState("she/her"),[m,p]=h.useState(""),[x,y]=h.useState(""),[g,b]=h.useState(!1),j=Ct();h.useEffect(()=>{J.getSetupStatus().then(w=>{w.agentName&&w.agentName!=="Auxiora"&&u(w.agentName)}).catch(()=>{})},[]);const S=async w=>{w.preventDefault(),b(!0),y("");try{await J.setupIdentity(r||s,o,m||void 0),m&&localStorage.setItem("auxiora_setup_vibe",m),j("/setup/preferences")}catch(A){y(A instanceof Error?A.message:"Failed to save identity")}finally{b(!1)}};return n.jsxs("div",{className:"setup-page",children:[n.jsx(Ha,{currentStep:3}),n.jsxs("div",{className:"setup-card",children:[n.jsx("h1",{children:"Agent Identity"}),n.jsx("p",{className:"subtitle",children:"Give your AI assistant a name, pronouns, and vibe."}),n.jsxs("form",{onSubmit:S,children:[n.jsx("label",{children:"Agent name"}),n.jsx("input",{type:"text",value:r,onChange:w=>u(w.target.value),placeholder:s,autoFocus:!0}),n.jsx("label",{children:"Pronouns"}),n.jsxs("select",{value:o,onChange:w=>f(w.target.value),children:[n.jsx("option",{value:"she/her",children:"she/her"}),n.jsx("option",{value:"he/him",children:"he/him"}),n.jsx("option",{value:"they/them",children:"they/them"}),n.jsx("option",{value:"it/its",children:"it/its"})]}),n.jsx("label",{children:"Describe the vibe"}),n.jsx("textarea",{value:m,onChange:w=>p(w.target.value),placeholder:"e.g. chill and witty, professional and sharp, warm like a best friend",rows:3,style:{width:"100%",resize:"vertical"}}),n.jsx("button",{type:"submit",className:"setup-btn-primary",disabled:g,children:g?"Saving...":"Continue"}),x&&n.jsx("p",{className:"error",children:x})]})]})]})}const _b={chill:["chill","relaxed","laid-back","easygoing","calm"],professional:["professional","formal","precise","corporate","business"],friendly:["friendly","warm","kind","caring","supportive","best friend"],creative:["creative","imaginative","artistic","playful","quirky"],mentor:["mentor","teacher","guide","coach","wise"],technical:["technical","code","developer","engineer","hacker"]};function Ub(s){const r=s.toLowerCase();for(const[u,o]of Object.entries(_b))if(o.some(f=>r.includes(f)))return u;return null}function Lb(){const{data:s,loading:r,error:u}=ut(()=>J.getSetupTemplates(),[]),[o,f]=h.useState(""),[m,p]=h.useState(""),[x,y]=h.useState(!1),g=Ct(),b=h.useMemo(()=>{const S=localStorage.getItem("auxiora_setup_vibe");return S?(localStorage.removeItem("auxiora_setup_vibe"),Ub(S)):null},[]),j=async S=>{f(S),y(!0),p("");try{await J.setupPersonality(S),g("/setup/appearance")}catch(w){p(w instanceof Error?w.message:"Failed to set personality"),y(!1)}};return n.jsxs("div",{className:"setup-page",children:[n.jsx(Ha,{currentStep:4}),n.jsxs("div",{className:"setup-card",style:{maxWidth:680},children:[n.jsx("h1",{children:"Personality"}),n.jsx("p",{className:"subtitle",children:"Choose a personality template for your assistant."}),r&&n.jsx("p",{style:{color:"var(--text-secondary)"},children:"Loading templates..."}),u&&n.jsx("p",{className:"error",children:u}),s&&n.jsx("div",{className:"template-grid",children:s.data.map(S=>n.jsxs("div",{className:`template-card${o===S.id?" selected":""}${b===S.id?" recommended":""}`,onClick:()=>!x&&j(S.id),children:[n.jsxs("h3",{children:[S.name,b===S.id&&n.jsx("span",{className:"badge badge-primary",style:{marginLeft:"0.5rem",fontSize:"0.6rem"},children:"Recommended"})]}),n.jsx("p",{children:S.description}),S.preview&&n.jsx("p",{style:{marginTop:"0.5rem",fontStyle:"italic",fontSize:"0.75rem"},children:S.preview})]},S.id))}),m&&n.jsx("p",{className:"error",children:m}),x&&n.jsx("p",{style:{color:"var(--text-secondary)",textAlign:"center"},children:"Saving..."})]})]})}const cm=[{name:"anthropic",label:"Anthropic (Claude)",keyPlaceholder:"sk-ant-...",keyLabel:"API Key"},{name:"openai",label:"OpenAI (GPT)",keyPlaceholder:"sk-...",keyLabel:"API Key"},{name:"google",label:"Google (Gemini)",keyPlaceholder:"AI...",keyLabel:"API Key"},{name:"groq",label:"Groq",keyPlaceholder:"gsk_...",keyLabel:"API Key"},{name:"deepseek",label:"DeepSeek",keyPlaceholder:"sk-...",keyLabel:"API Key"},{name:"xai",label:"xAI (Grok)",keyPlaceholder:"xai-...",keyLabel:"API Key"},{name:"cohere",label:"Cohere",keyPlaceholder:"...",keyLabel:"API Key"},{name:"replicate",label:"Replicate",keyPlaceholder:"r8_...",keyLabel:"API Token"},{name:"ollama",label:"Ollama (Local)",keyPlaceholder:"",keyLabel:"",isLocal:!0}];function Bb(){const[s,r]=h.useState({}),[u,o]=h.useState("http://localhost:11434"),[f,m]=h.useState(""),[p,x]=h.useState(!1),y=Ct(),g=(S,w)=>{r(A=>({...A,[S]:w}))},b=Object.values(s).some(S=>S.trim())||s.ollama!==void 0,j=async S=>{var A;S.preventDefault(),x(!0),m("");const w=[];for(const D of cm){if(D.isLocal){s.ollama!==void 0&&w.push({name:"ollama",endpoint:u});continue}const O=(A=s[D.name])==null?void 0:A.trim();O&&w.push({name:D.name,apiKey:O})}if(w.length===0){m("Add at least one provider API key to continue"),x(!1);return}try{await J.setupProviders(w),y("/setup/channels")}catch(D){m(D instanceof Error?D.message:"Failed to configure providers")}finally{x(!1)}};return n.jsxs("div",{className:"setup-page",children:[n.jsx(Ha,{currentStep:6}),n.jsxs("div",{className:"setup-card",children:[n.jsx("h1",{children:"AI Providers"}),n.jsx("p",{className:"subtitle",children:"Add API keys for the providers you want to use. The first one with a key becomes the default. You can add more later in Settings."}),n.jsxs("form",{onSubmit:j,children:[cm.map(S=>n.jsxs("div",{className:"setup-provider-row",children:[n.jsx("label",{className:"setup-provider-label",children:S.label}),S.isLocal?n.jsxs("div",{style:{display:"flex",gap:"0.5rem",alignItems:"center"},children:[n.jsx("input",{type:"checkbox",checked:s.ollama!==void 0,onChange:w=>{w.target.checked?g("ollama","enabled"):r(A=>{const D={...A};return delete D.ollama,D})}}),n.jsx("input",{type:"text",value:u,onChange:w=>o(w.target.value),placeholder:"http://localhost:11434",disabled:s.ollama===void 0,style:{flex:1}})]}):n.jsx("input",{type:"password",value:s[S.name]||"",onChange:w=>g(S.name,w.target.value),placeholder:S.keyPlaceholder})]},S.name)),n.jsx("button",{type:"submit",className:"setup-btn-primary",disabled:p||!b,children:p?"Saving...":"Continue"}),f&&n.jsx("p",{className:"error",children:f})]})]})]})}const rm=[{type:"webchat",name:"Webchat",description:"Built-in, no setup needed",fields:[]},{type:"discord",name:"Discord",description:"Connect a Discord bot",fields:[{key:"botToken",label:"Bot Token",type:"password"}]},{type:"telegram",name:"Telegram",description:"Connect a Telegram bot",fields:[{key:"botToken",label:"Bot Token",type:"password"}]},{type:"slack",name:"Slack",description:"Connect to a Slack workspace",fields:[{key:"botToken",label:"Bot Token",type:"password"},{key:"appToken",label:"App Token",type:"password"}]},{type:"matrix",name:"Matrix",description:"Connect to a Matrix homeserver",fields:[{key:"homeserverUrl",label:"Homeserver URL",type:"text"},{key:"userId",label:"User ID",type:"text"},{key:"accessToken",label:"Access Token",type:"password"}]},{type:"signal",name:"Signal",description:"Connect via Signal CLI",fields:[{key:"cliEndpoint",label:"CLI Endpoint",type:"text"},{key:"phoneNumber",label:"Phone Number",type:"text"}]},{type:"teams",name:"Teams",description:"Connect to Microsoft Teams",fields:[{key:"appId",label:"App ID",type:"text"},{key:"appPassword",label:"App Password",type:"password"}]},{type:"whatsapp",name:"WhatsApp",description:"Connect via WhatsApp Business API",fields:[{key:"phoneNumberId",label:"Phone Number ID",type:"text"},{key:"accessToken",label:"Access Token",type:"password"},{key:"verifyToken",label:"Verify Token",type:"text"}]},{type:"twilio",name:"Twilio",description:"Connect via Twilio SMS",fields:[{key:"accountSid",label:"Account SID",type:"text"},{key:"authToken",label:"Auth Token",type:"password"},{key:"phoneNumber",label:"Phone Number",type:"text"}]},{type:"email",name:"Email",description:"Connect via IMAP/SMTP",fields:[{key:"imapHost",label:"IMAP Host",type:"text"},{key:"imapPort",label:"IMAP Port",type:"text"},{key:"smtpHost",label:"SMTP Host",type:"text"},{key:"smtpPort",label:"SMTP Port",type:"text"},{key:"email",label:"Email",type:"text"},{key:"password",label:"Password",type:"password"}]}];function Hb(){const[s,r]=h.useState({webchat:!0}),[u,o]=h.useState({}),[f,m]=h.useState(""),[p,x]=h.useState(!1),y=Ct(),g=S=>{S!=="webchat"&&r(w=>({...w,[S]:!w[S]}))},b=(S,w,A)=>{o(D=>({...D,[S]:{...D[S],[w]:A}}))},j=async()=>{x(!0),m("");try{const S=rm.filter(w=>s[w.type]).map(w=>({type:w.type,enabled:!0,credentials:u[w.type]}));await J.setupChannels(S),y("/setup/connections")}catch(S){m(S instanceof Error?S.message:"Failed to save channels")}finally{x(!1)}};return n.jsxs("div",{className:"setup-page",children:[n.jsx(Ha,{currentStep:7}),n.jsxs("div",{className:"setup-card",style:{maxWidth:720},children:[n.jsx("h1",{children:"Channels"}),n.jsx("p",{className:"subtitle",children:"Enable the messaging channels you want to connect."}),n.jsx("div",{className:"channel-grid",children:rm.map(S=>n.jsxs("div",{className:"channel-card",children:[n.jsxs("div",{className:"channel-card-header",children:[n.jsx("h3",{children:S.name}),S.type==="webchat"?n.jsx("span",{style:{fontSize:"0.75rem",color:"var(--success)"},children:"Always on"}):n.jsx("div",{className:`toggle${s[S.type]?" active":""}`,onClick:()=>g(S.type)})]}),n.jsx("p",{style:{fontSize:"0.8rem",color:"var(--text-secondary)",marginBottom:"0.5rem"},children:S.description}),s[S.type]&&S.fields.length>0&&n.jsx("div",{className:"channel-card-fields",children:S.fields.map(w=>{var A;return n.jsxs("div",{children:[n.jsx("label",{children:w.label}),n.jsx("input",{type:w.type,value:((A=u[S.type])==null?void 0:A[w.key])||"",onChange:D=>b(S.type,w.key,D.target.value)})]},w.key)})})]},S.type))}),n.jsx("button",{className:"setup-btn-primary",onClick:j,disabled:p,children:p?"Saving...":"Save & Continue"}),f&&n.jsx("p",{className:"error",children:f}),n.jsx("span",{className:"skip-link",onClick:()=>y("/setup/connections"),children:"Skip for now"})]})]})}function qb(){const[s,r]=h.useState(""),[u,o]=h.useState(""),[f,m]=h.useState(""),[p,x]=h.useState(!1),y=Ct(),g=async()=>{if(!s||!u){m("Both Client ID and Client Secret are required");return}x(!0),m("");try{const b=await J.saveConnectorCredentials("google-workspace",s,u);b.oauthUrl?window.location.href=b.oauthUrl:y("/setup/complete")}catch(b){m(b instanceof Error?b.message:"Failed to save credentials")}finally{x(!1)}};return n.jsxs("div",{className:"setup-page",children:[n.jsx(Ha,{currentStep:8}),n.jsxs("div",{className:"setup-card",children:[n.jsx("h1",{children:"Connections"}),n.jsx("p",{className:"subtitle",children:"Connect external services for calendar, email, and task intelligence."}),n.jsxs("div",{className:"settings-section",children:[n.jsx("h3",{children:"Google Workspace"}),n.jsx("p",{style:{fontSize:"0.8rem",color:"var(--text-secondary)",marginBottom:"1rem"},children:"Connect your Google account to enable calendar awareness, email summaries, and task sync."}),n.jsx("label",{children:"Client ID"}),n.jsx("input",{type:"text",value:s,onChange:b=>r(b.target.value),placeholder:"your-client-id.apps.googleusercontent.com"}),n.jsx("label",{children:"Client Secret"}),n.jsx("input",{type:"password",value:u,onChange:b=>o(b.target.value),placeholder:"GOCSPX-..."}),n.jsx("button",{type:"button",className:"setup-btn-primary",onClick:g,disabled:p,children:p?"Connecting...":"Connect Google Account"}),f&&n.jsx("p",{className:"error",children:f})]}),n.jsx("button",{type:"button",className:"setup-btn-secondary",onClick:()=>y("/setup/complete"),children:"Continue without connecting"}),n.jsx("span",{className:"skip-link",onClick:()=>y("/setup/complete"),children:"Skip for now"})]})]})}function Yb(){const[s,r]=h.useState("");return h.useEffect(()=>{J.completeSetup().catch(u=>{r(u instanceof Error?u.message:"Failed to finalize setup")})},[]),n.jsx("div",{className:"setup-page",children:n.jsxs("div",{className:"setup-card",style:{textAlign:"center"},children:[n.jsx("div",{className:"setup-complete-check",children:"✓"}),n.jsx("h1",{children:"Setup Complete!"}),n.jsx("p",{className:"subtitle",children:"Your assistant is ready to go."}),s&&n.jsx("p",{className:"error",children:s}),n.jsxs("div",{className:"setup-complete-buttons",children:[n.jsx("button",{className:"setup-btn-primary",onClick:()=>{window.location.href="/"},children:"Open Chat"}),n.jsx("button",{className:"setup-btn-secondary",onClick:()=>{window.location.href="/dashboard"},children:"Go to Mission Control"})]})]})})}const um=[{id:"verbosity",label:"Preferred response style",trait:"verbosity",options:[{label:"Concise",value:-.2},{label:"Balanced",value:0},{label:"Detailed",value:.2}]},{id:"warmth",label:"Communication tone",trait:"warmth",options:[{label:"Analytical",value:-.15},{label:"Balanced",value:0},{label:"Warm",value:.2}]},{id:"humor",label:"Humor level",trait:"humor",options:[{label:"Serious",value:-.15},{label:"Occasional",value:0},{label:"Frequent",value:.2}]},{id:"formality",label:"Formality",trait:"formality",options:[{label:"Casual",value:-.2},{label:"Balanced",value:0},{label:"Formal",value:.2}]},{id:"depth",label:"Explanation depth",trait:"secondOrder",options:[{label:"Surface level",value:-.1},{label:"Standard",value:0},{label:"Deep analysis",value:.15}]}];function Gb(){const[s,r]=h.useState({}),[u,o]=h.useState(!1),[f,m]=h.useState(""),p=Ct(),x=(g,b)=>{r(j=>({...j,[g]:b}))},y=async()=>{o(!0),m("");try{const g=um.filter(b=>s[b.id]&&s[b.id]!==0);for(const b of g)await J.updateArchitectPreference(b.trait,s[b.id]);p("/setup/personality")}catch(g){m(g instanceof Error?g.message:"Failed to save preferences")}finally{o(!1)}};return n.jsxs("div",{className:"setup-page",children:[n.jsx(Ha,{currentStep:4}),n.jsxs("div",{className:"setup-card",children:[n.jsx("h1",{children:"Your Preferences"}),n.jsx("p",{className:"subtitle",children:"Help your assistant understand how you like to communicate. You can always change these later."}),n.jsx("div",{className:"preferences-questions",children:um.map(g=>n.jsxs("div",{className:"preferences-question",children:[n.jsx("label",{children:g.label}),n.jsx("div",{className:"preferences-options",children:g.options.map(b=>n.jsx("button",{className:`preferences-option ${s[g.id]===b.value?"active":""}`,onClick:()=>x(g.id,b.value),type:"button",children:b.label},b.label))})]},g.id))}),f&&n.jsx("p",{className:"error",children:f}),n.jsxs("div",{className:"preferences-actions",children:[n.jsx("button",{className:"setup-btn-secondary",onClick:()=>p("/setup/personality"),children:"Skip"}),n.jsx("button",{className:"setup-btn-primary",onClick:y,disabled:u,children:u?"Saving...":"Continue"})]})]})]})}function $b(){const{theme:s}=qu(),[r,u]=h.useState(""),[o,f]=h.useState(!1),m=Ct(),p=async()=>{f(!0),u("");try{await J.updateAppearance(s),m("/setup/provider")}catch(x){u(x instanceof Error?x.message:"Failed to save appearance"),f(!1)}};return n.jsxs("div",{className:"setup-page",children:[n.jsx(Ha,{currentStep:5}),n.jsxs("div",{className:"setup-card",style:{maxWidth:720},children:[n.jsx("h1",{children:"Appearance"}),n.jsx("p",{className:"subtitle",children:"Choose a visual theme for Mission Control. You can change this later in settings."}),n.jsx(Vm,{}),r&&n.jsx("p",{className:"error",children:r}),n.jsx("button",{className:"btn-primary",onClick:p,disabled:o,style:{marginTop:"1.5rem",width:"100%"},children:o?"Saving...":"Continue"})]})]})}function Xb(){return n.jsxs(py,{children:[n.jsx(ke,{path:"/login",element:n.jsx(Ob,{})}),n.jsx(ke,{path:"/unlock",element:n.jsx(Mb,{})}),n.jsx(ke,{path:"/setup",element:n.jsx(Rb,{})}),n.jsx(ke,{path:"/setup/vault",element:n.jsx(Db,{})}),n.jsx(ke,{path:"/setup/dashboard-password",element:n.jsx(zb,{})}),n.jsx(ke,{path:"/setup/identity",element:n.jsx(kb,{})}),n.jsx(ke,{path:"/setup/preferences",element:n.jsx(Gb,{})}),n.jsx(ke,{path:"/setup/personality",element:n.jsx(Lb,{})}),n.jsx(ke,{path:"/setup/appearance",element:n.jsx($b,{})}),n.jsx(ke,{path:"/setup/provider",element:n.jsx(Bb,{})}),n.jsx(ke,{path:"/setup/channels",element:n.jsx(Hb,{})}),n.jsx(ke,{path:"/setup/connections",element:n.jsx(qb,{})}),n.jsx(ke,{path:"/setup/complete",element:n.jsx(Yb,{})}),n.jsxs(ke,{element:n.jsx(Ab,{}),children:[n.jsx(ke,{index:!0,element:n.jsx(Dm,{})}),n.jsx(ke,{path:"chat",element:n.jsx(km,{})}),n.jsx(ke,{path:"behaviors",element:n.jsx(Bm,{})}),n.jsx(ke,{path:"webhooks",element:n.jsx(qm,{})}),n.jsx(ke,{path:"settings/personality",element:n.jsx(Ym,{})}),n.jsx(ke,{path:"settings/identity",element:n.jsx(Kh,{to:"/settings/personality",replace:!0})}),n.jsx(ke,{path:"settings/provider",element:n.jsx(Gm,{})}),n.jsx(ke,{path:"settings/channels",element:n.jsx($m,{})}),n.jsx(ke,{path:"settings/connections",element:n.jsx(Km,{})}),n.jsx(ke,{path:"settings/architect",element:n.jsx(Jm,{})}),n.jsx(ke,{path:"settings/ambient",element:n.jsx(Zm,{})}),n.jsx(ke,{path:"settings/appearance",element:n.jsx(Qm,{})}),n.jsx(ke,{path:"settings/notifications",element:n.jsx(Fm,{})}),n.jsx(ke,{path:"settings/security",element:n.jsx(Xm,{})}),n.jsx(ke,{path:"settings/audit",element:n.jsx(Pm,{})}),n.jsx(ke,{path:"profile",element:n.jsx(Wm,{})}),n.jsx(ke,{path:"memories",element:n.jsx(Im,{})})]}),n.jsx(ke,{path:"*",element:n.jsx(Kh,{to:"/",replace:!0})})]})}yv.createRoot(document.getElementById("root")).render(n.jsx(h.StrictMode,{children:n.jsx(Hy,{basename:"/dashboard",children:n.jsx(Py,{children:n.jsx(Xb,{})})})}));
|