@suveren/gateway 0.13.1 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -48,30 +48,30 @@ Error generating stack: `+o.message+`
48
48
  * @license MIT
49
49
  */var eu="popstate";function tu(e){return typeof e=="object"&&e!=null&&"pathname"in e&&"search"in e&&"hash"in e&&"state"in e&&"key"in e}function og(e={}){function t(r,a){var d;let o=(d=a.state)==null?void 0:d.masked,{pathname:i,search:l,hash:c}=o||r.location;return Ti("",{pathname:i,search:l,hash:c},a.state&&a.state.usr||null,a.state&&a.state.key||"default",o?{pathname:r.location.pathname,search:r.location.search,hash:r.location.hash}:void 0)}function n(r,a){return typeof a=="string"?a:fs(a)}return lg(t,n,null,e)}function ke(e,t){if(e===!1||e===null||typeof e>"u")throw new Error(t)}function Ct(e,t){if(!e){typeof console<"u"&&console.warn(t);try{throw new Error(t)}catch{}}}function ig(){return Math.random().toString(36).substring(2,10)}function nu(e,t){return{usr:e.state,key:e.key,idx:t,masked:e.unstable_mask?{pathname:e.pathname,search:e.search,hash:e.hash}:void 0}}function Ti(e,t,n=null,r,a){return{pathname:typeof e=="string"?e:e.pathname,search:"",hash:"",...typeof t=="string"?vr(t):t,state:n,key:t&&t.key||r||ig(),unstable_mask:a}}function fs({pathname:e="/",search:t="",hash:n=""}){return t&&t!=="?"&&(e+=t.charAt(0)==="?"?t:"?"+t),n&&n!=="#"&&(e+=n.charAt(0)==="#"?n:"#"+n),e}function vr(e){let t={};if(e){let n=e.indexOf("#");n>=0&&(t.hash=e.substring(n),e=e.substring(0,n));let r=e.indexOf("?");r>=0&&(t.search=e.substring(r),e=e.substring(0,r)),e&&(t.pathname=e)}return t}function lg(e,t,n,r={}){let{window:a=document.defaultView,v5Compat:o=!1}=r,i=a.history,l="POP",c=null,d=f();d==null&&(d=0,i.replaceState({...i.state,idx:d},""));function f(){return(i.state||{idx:null}).idx}function p(){l="POP";let k=f(),g=k==null?null:k-d;d=k,c&&c({action:l,location:x.location,delta:g})}function m(k,g){l="PUSH";let h=tu(k)?k:Ti(x.location,k,g);d=f()+1;let y=nu(h,d),S=x.createHref(h.unstable_mask||h);try{i.pushState(y,"",S)}catch(b){if(b instanceof DOMException&&b.name==="DataCloneError")throw b;a.location.assign(S)}o&&c&&c({action:l,location:x.location,delta:1})}function w(k,g){l="REPLACE";let h=tu(k)?k:Ti(x.location,k,g);d=f();let y=nu(h,d),S=x.createHref(h.unstable_mask||h);i.replaceState(y,"",S),o&&c&&c({action:l,location:x.location,delta:0})}function v(k){return cg(k)}let x={get action(){return l},get location(){return e(a,i)},listen(k){if(c)throw new Error("A history only accepts one active listener");return a.addEventListener(eu,p),c=k,()=>{a.removeEventListener(eu,p),c=null}},createHref(k){return t(a,k)},createURL:v,encodeLocation(k){let g=v(k);return{pathname:g.pathname,search:g.search,hash:g.hash}},push:m,replace:w,go(k){return i.go(k)}};return x}function cg(e,t=!1){let n="http://localhost";typeof window<"u"&&(n=window.location.origin!=="null"?window.location.origin:window.location.href),ke(n,"No window.location.(origin|href) available to create URL");let r=typeof e=="string"?e:fs(e);return r=r.replace(/ $/,"%20"),!t&&r.startsWith("//")&&(r=n+r),new URL(r,n)}function Ff(e,t,n="/"){return ug(e,t,n,!1)}function ug(e,t,n,r){let a=typeof t=="string"?vr(t):t,o=en(a.pathname||"/",n);if(o==null)return null;let i=Of(e);dg(i);let l=null;for(let c=0;l==null&&c<i.length;++c){let d=jg(o);l=wg(i[c],d,r)}return l}function Of(e,t=[],n=[],r="",a=!1){let o=(i,l,c=a,d)=>{let f={relativePath:d===void 0?i.path||"":d,caseSensitive:i.caseSensitive===!0,childrenIndex:l,route:i};if(f.relativePath.startsWith("/")){if(!f.relativePath.startsWith(r)&&c)return;ke(f.relativePath.startsWith(r),`Absolute route path "${f.relativePath}" nested under path "${r}" is not valid. An absolute child route path must start with the combined path of all its parent routes.`),f.relativePath=f.relativePath.slice(r.length)}let p=Dt([r,f.relativePath]),m=n.concat(f);i.children&&i.children.length>0&&(ke(i.index!==!0,`Index routes must not have child routes. Please remove all child routes from route path "${p}".`),Of(i.children,t,m,p,c)),!(i.path==null&&!i.index)&&t.push({path:p,score:vg(p,i.index),routesMeta:m})};return e.forEach((i,l)=>{var c;if(i.path===""||!((c=i.path)!=null&&c.includes("?")))o(i,l);else for(let d of Bf(i.path))o(i,l,!0,d)}),t}function Bf(e){let t=e.split("/");if(t.length===0)return[];let[n,...r]=t,a=n.endsWith("?"),o=n.replace(/\?$/,"");if(r.length===0)return a?[o,""]:[o];let i=Bf(r.join("/")),l=[];return l.push(...i.map(c=>c===""?o:[o,c].join("/"))),a&&l.push(...i),l.map(c=>e.startsWith("/")&&c===""?"/":c)}function dg(e){e.sort((t,n)=>t.score!==n.score?n.score-t.score:xg(t.routesMeta.map(r=>r.childrenIndex),n.routesMeta.map(r=>r.childrenIndex)))}var fg=/^:[\w-]+$/,mg=3,pg=2,hg=1,gg=10,yg=-2,ru=e=>e==="*";function vg(e,t){let n=e.split("/"),r=n.length;return n.some(ru)&&(r+=yg),t&&(r+=pg),n.filter(a=>!ru(a)).reduce((a,o)=>a+(fg.test(o)?mg:o===""?hg:gg),r)}function xg(e,t){return e.length===t.length&&e.slice(0,-1).every((r,a)=>r===t[a])?e[e.length-1]-t[t.length-1]:0}function wg(e,t,n=!1){let{routesMeta:r}=e,a={},o="/",i=[];for(let l=0;l<r.length;++l){let c=r[l],d=l===r.length-1,f=o==="/"?t:t.slice(o.length)||"/",p=Ra({path:c.relativePath,caseSensitive:c.caseSensitive,end:d},f),m=c.route;if(!p&&d&&n&&!r[r.length-1].route.index&&(p=Ra({path:c.relativePath,caseSensitive:c.caseSensitive,end:!1},f)),!p)return null;Object.assign(a,p.params),i.push({params:a,pathname:Dt([o,p.pathname]),pathnameBase:Ng(Dt([o,p.pathnameBase])),route:m}),p.pathnameBase!=="/"&&(o=Dt([o,p.pathnameBase]))}return i}function Ra(e,t){typeof e=="string"&&(e={path:e,caseSensitive:!1,end:!0});let[n,r]=Sg(e.path,e.caseSensitive,e.end),a=t.match(n);if(!a)return null;let o=a[0],i=o.replace(/(.)\/+$/,"$1"),l=a.slice(1);return{params:r.reduce((d,{paramName:f,isOptional:p},m)=>{if(f==="*"){let v=l[m]||"";i=o.slice(0,o.length-v.length).replace(/(.)\/+$/,"$1")}const w=l[m];return p&&!w?d[f]=void 0:d[f]=(w||"").replace(/%2F/g,"/"),d},{}),pathname:o,pathnameBase:i,pattern:e}}function Sg(e,t=!1,n=!0){Ct(e==="*"||!e.endsWith("*")||e.endsWith("/*"),`Route path "${e}" will be treated as if it were "${e.replace(/\*$/,"/*")}" because the \`*\` character must always follow a \`/\` in the pattern. To get rid of this warning, please change the route path to "${e.replace(/\*$/,"/*")}".`);let r=[],a="^"+e.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(i,l,c,d,f)=>{if(r.push({paramName:l,isOptional:c!=null}),c){let p=f.charAt(d+i.length);return p&&p!=="/"?"/([^\\/]*)":"(?:/([^\\/]*))?"}return"/([^\\/]+)"}).replace(/\/([\w-]+)\?(\/|$)/g,"(/$1)?$2");return e.endsWith("*")?(r.push({paramName:"*"}),a+=e==="*"||e==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):n?a+="\\/*$":e!==""&&e!=="/"&&(a+="(?:(?=\\/|$))"),[new RegExp(a,t?void 0:"i"),r]}function jg(e){try{return e.split("/").map(t=>decodeURIComponent(t).replace(/\//g,"%2F")).join("/")}catch(t){return Ct(!1,`The URL path "${e}" could not be decoded because it is a malformed URL segment. This is probably due to a bad percent encoding (${t}).`),e}}function en(e,t){if(t==="/")return e;if(!e.toLowerCase().startsWith(t.toLowerCase()))return null;let n=t.endsWith("/")?t.length-1:t.length,r=e.charAt(n);return r&&r!=="/"?null:e.slice(n)||"/"}var kg=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;function bg(e,t="/"){let{pathname:n,search:r="",hash:a=""}=typeof e=="string"?vr(e):e,o;return n?(n=n.replace(/\/\/+/g,"/"),n.startsWith("/")?o=su(n.substring(1),"/"):o=su(n,t)):o=t,{pathname:o,search:Eg(r),hash:Tg(a)}}function su(e,t){let n=t.replace(/\/+$/,"").split("/");return e.split("/").forEach(a=>{a===".."?n.length>1&&n.pop():a!=="."&&n.push(a)}),n.length>1?n.join("/"):"/"}function To(e,t,n,r){return`Cannot include a '${e}' character in a manually specified \`to.${t}\` field [${JSON.stringify(r)}]. Please separate it out to the \`to.${n}\` field. Alternatively you may provide the full path as a string in <Link to="..."> and the router will parse it for you.`}function Cg(e){return e.filter((t,n)=>n===0||t.route.path&&t.route.path.length>0)}function _l(e){let t=Cg(e);return t.map((n,r)=>r===t.length-1?n.pathname:n.pathnameBase)}function Ja(e,t,n,r=!1){let a;typeof e=="string"?a=vr(e):(a={...e},ke(!a.pathname||!a.pathname.includes("?"),To("?","pathname","search",a)),ke(!a.pathname||!a.pathname.includes("#"),To("#","pathname","hash",a)),ke(!a.search||!a.search.includes("#"),To("#","search","hash",a)));let o=e===""||a.pathname==="",i=o?"/":a.pathname,l;if(i==null)l=n;else{let p=t.length-1;if(!r&&i.startsWith("..")){let m=i.split("/");for(;m[0]==="..";)m.shift(),p-=1;a.pathname=m.join("/")}l=p>=0?t[p]:"/"}let c=bg(a,l),d=i&&i!=="/"&&i.endsWith("/"),f=(o||i===".")&&n.endsWith("/");return!c.pathname.endsWith("/")&&(d||f)&&(c.pathname+="/"),c}var Dt=e=>e.join("/").replace(/\/\/+/g,"/"),Ng=e=>e.replace(/\/+$/,"").replace(/^\/*/,"/"),Eg=e=>!e||e==="?"?"":e.startsWith("?")?e:"?"+e,Tg=e=>!e||e==="#"?"":e.startsWith("#")?e:"#"+e,Ig=class{constructor(e,t,n,r=!1){this.status=e,this.statusText=t||"",this.internal=r,n instanceof Error?(this.data=n.toString(),this.error=n):this.data=n}};function Rg(e){return e!=null&&typeof e.status=="number"&&typeof e.statusText=="string"&&typeof e.internal=="boolean"&&"data"in e}function Pg(e){return e.map(t=>t.route.path).filter(Boolean).join("/").replace(/\/\/*/g,"/")||"/"}var Df=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function Uf(e,t){let n=e;if(typeof n!="string"||!kg.test(n))return{absoluteURL:void 0,isExternal:!1,to:n};let r=n,a=!1;if(Df)try{let o=new URL(window.location.href),i=n.startsWith("//")?new URL(o.protocol+n):new URL(n),l=en(i.pathname,t);i.origin===o.origin&&l!=null?n=l+i.search+i.hash:a=!0}catch{Ct(!1,`<Link to="${n}"> contains an invalid URL which will probably break when clicked - please update to a valid URL path.`)}return{absoluteURL:r,isExternal:a,to:n}}Object.getOwnPropertyNames(Object.prototype).sort().join("\0");var Wf=["POST","PUT","PATCH","DELETE"];new Set(Wf);var _g=["GET",...Wf];new Set(_g);var xr=u.createContext(null);xr.displayName="DataRouter";var Xa=u.createContext(null);Xa.displayName="DataRouterState";var Ag=u.createContext(!1),Hf=u.createContext({isTransitioning:!1});Hf.displayName="ViewTransition";var zg=u.createContext(new Map);zg.displayName="Fetchers";var $g=u.createContext(null);$g.displayName="Await";var ht=u.createContext(null);ht.displayName="Navigation";var vs=u.createContext(null);vs.displayName="Location";var $t=u.createContext({outlet:null,matches:[],isDataRoute:!1});$t.displayName="Route";var Al=u.createContext(null);Al.displayName="RouteError";var Vf="REACT_ROUTER_ERROR",Lg="REDIRECT",Mg="ROUTE_ERROR_RESPONSE";function Fg(e){if(e.startsWith(`${Vf}:${Lg}:{`))try{let t=JSON.parse(e.slice(28));if(typeof t=="object"&&t&&typeof t.status=="number"&&typeof t.statusText=="string"&&typeof t.location=="string"&&typeof t.reloadDocument=="boolean"&&typeof t.replace=="boolean")return t}catch{}}function Og(e){if(e.startsWith(`${Vf}:${Mg}:{`))try{let t=JSON.parse(e.slice(40));if(typeof t=="object"&&t&&typeof t.status=="number"&&typeof t.statusText=="string")return new Ig(t.status,t.statusText,t.data)}catch{}}function Bg(e,{relative:t}={}){ke(wr(),"useHref() may be used only in the context of a <Router> component.");let{basename:n,navigator:r}=u.useContext(ht),{hash:a,pathname:o,search:i}=xs(e,{relative:t}),l=o;return n!=="/"&&(l=o==="/"?n:Dt([n,o])),r.createHref({pathname:l,search:i,hash:a})}function wr(){return u.useContext(vs)!=null}function gt(){return ke(wr(),"useLocation() may be used only in the context of a <Router> component."),u.useContext(vs).location}var Gf="You should call navigate() in a React.useEffect(), not when your component is first rendered.";function Kf(e){u.useContext(ht).static||u.useLayoutEffect(e)}function nn(){let{isDataRoute:e}=u.useContext($t);return e?ty():Dg()}function Dg(){ke(wr(),"useNavigate() may be used only in the context of a <Router> component.");let e=u.useContext(xr),{basename:t,navigator:n}=u.useContext(ht),{matches:r}=u.useContext($t),{pathname:a}=gt(),o=JSON.stringify(_l(r)),i=u.useRef(!1);return Kf(()=>{i.current=!0}),u.useCallback((c,d={})=>{if(Ct(i.current,Gf),!i.current)return;if(typeof c=="number"){n.go(c);return}let f=Ja(c,JSON.parse(o),a,d.relative==="path");e==null&&t!=="/"&&(f.pathname=f.pathname==="/"?t:Dt([t,f.pathname])),(d.replace?n.replace:n.push)(f,d.state,d)},[t,n,o,a,e])}var Ug=u.createContext(null);function Wg(e){let t=u.useContext($t).outlet;return u.useMemo(()=>t&&u.createElement(Ug.Provider,{value:e},t),[t,e])}function xs(e,{relative:t}={}){let{matches:n}=u.useContext($t),{pathname:r}=gt(),a=JSON.stringify(_l(n));return u.useMemo(()=>Ja(e,JSON.parse(a),r,t==="path"),[e,a,r,t])}function Hg(e,t){return Yf(e,t)}function Yf(e,t,n){var k;ke(wr(),"useRoutes() may be used only in the context of a <Router> component.");let{navigator:r}=u.useContext(ht),{matches:a}=u.useContext($t),o=a[a.length-1],i=o?o.params:{},l=o?o.pathname:"/",c=o?o.pathnameBase:"/",d=o&&o.route;{let g=d&&d.path||"";Jf(l,!d||g.endsWith("*")||g.endsWith("*?"),`You rendered descendant <Routes> (or called \`useRoutes()\`) at "${l}" (under <Route path="${g}">) but the parent route path has no trailing "*". This means if you navigate deeper, the parent won't match anymore and therefore the child routes will never render.
50
50
 
51
- Please change the parent <Route path="${g}"> to <Route path="${g==="/"?"*":`${g}/*`}">.`)}let f=gt(),p;if(t){let g=typeof t=="string"?vr(t):t;ke(c==="/"||((k=g.pathname)==null?void 0:k.startsWith(c)),`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 "${c}" but pathname "${g.pathname}" was given in the \`location\` prop.`),p=g}else p=f;let m=p.pathname||"/",w=m;if(c!=="/"){let g=c.replace(/^\//,"").split("/");w="/"+m.replace(/^\//,"").split("/").slice(g.length).join("/")}let v=Ff(e,{pathname:w});Ct(d||v!=null,`No routes matched location "${p.pathname}${p.search}${p.hash}" `),Ct(v==null||v[v.length-1].route.element!==void 0||v[v.length-1].route.Component!==void 0||v[v.length-1].route.lazy!==void 0,`Matched leaf route at location "${p.pathname}${p.search}${p.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 x=Qg(v&&v.map(g=>Object.assign({},g,{params:Object.assign({},i,g.params),pathname:Dt([c,r.encodeLocation?r.encodeLocation(g.pathname.replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:g.pathname]),pathnameBase:g.pathnameBase==="/"?c:Dt([c,r.encodeLocation?r.encodeLocation(g.pathnameBase.replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:g.pathnameBase])})),a,n);return t&&x?u.createElement(vs.Provider,{value:{location:{pathname:"/",search:"",hash:"",state:null,key:"default",unstable_mask:void 0,...p},navigationType:"POP"}},x):x}function Vg(){let e=ey(),t=Rg(e)?`${e.status} ${e.statusText}`:e instanceof Error?e.message:JSON.stringify(e),n=e instanceof Error?e.stack:null,r="rgba(200,200,200, 0.5)",a={padding:"0.5rem",backgroundColor:r},o={padding:"2px 4px",backgroundColor:r},i=null;return console.error("Error handled by React Router default ErrorBoundary:",e),i=u.createElement(u.Fragment,null,u.createElement("p",null,"💿 Hey developer 👋"),u.createElement("p",null,"You can provide a way better UX than this when your app throws errors by providing your own ",u.createElement("code",{style:o},"ErrorBoundary")," or"," ",u.createElement("code",{style:o},"errorElement")," prop on your route.")),u.createElement(u.Fragment,null,u.createElement("h2",null,"Unexpected Application Error!"),u.createElement("h3",{style:{fontStyle:"italic"}},t),n?u.createElement("pre",{style:a},n):null,i)}var Gg=u.createElement(Vg,null),Qf=class extends u.Component{constructor(e){super(e),this.state={location:e.location,revalidation:e.revalidation,error:e.error}}static getDerivedStateFromError(e){return{error:e}}static getDerivedStateFromProps(e,t){return t.location!==e.location||t.revalidation!=="idle"&&e.revalidation==="idle"?{error:e.error,location:e.location,revalidation:e.revalidation}:{error:e.error!==void 0?e.error:t.error,location:t.location,revalidation:e.revalidation||t.revalidation}}componentDidCatch(e,t){this.props.onError?this.props.onError(e,t):console.error("React Router caught the following error during render",e)}render(){let e=this.state.error;if(this.context&&typeof e=="object"&&e&&"digest"in e&&typeof e.digest=="string"){const n=Og(e.digest);n&&(e=n)}let t=e!==void 0?u.createElement($t.Provider,{value:this.props.routeContext},u.createElement(Al.Provider,{value:e,children:this.props.component})):this.props.children;return this.context?u.createElement(Kg,{error:e},t):t}};Qf.contextType=Ag;var Io=new WeakMap;function Kg({children:e,error:t}){let{basename:n}=u.useContext(ht);if(typeof t=="object"&&t&&"digest"in t&&typeof t.digest=="string"){let r=Fg(t.digest);if(r){let a=Io.get(t);if(a)throw a;let o=Uf(r.location,n);if(Df&&!Io.get(t))if(o.isExternal||r.reloadDocument)window.location.href=o.absoluteURL||o.to;else{const i=Promise.resolve().then(()=>window.__reactRouterDataRouter.navigate(o.to,{replace:r.replace}));throw Io.set(t,i),i}return u.createElement("meta",{httpEquiv:"refresh",content:`0;url=${o.absoluteURL||o.to}`})}}return e}function Yg({routeContext:e,match:t,children:n}){let r=u.useContext(xr);return r&&r.static&&r.staticContext&&(t.route.errorElement||t.route.ErrorBoundary)&&(r.staticContext._deepestRenderedBoundaryId=t.route.id),u.createElement($t.Provider,{value:e},n)}function Qg(e,t=[],n){let r=n==null?void 0:n.state;if(e==null){if(!r)return null;if(r.errors)e=r.matches;else if(t.length===0&&!r.initialized&&r.matches.length>0)e=r.matches;else return null}let a=e,o=r==null?void 0:r.errors;if(o!=null){let f=a.findIndex(p=>p.route.id&&(o==null?void 0:o[p.route.id])!==void 0);ke(f>=0,`Could not find a matching route for errors on route IDs: ${Object.keys(o).join(",")}`),a=a.slice(0,Math.min(a.length,f+1))}let i=!1,l=-1;if(n&&r){i=r.renderFallback;for(let f=0;f<a.length;f++){let p=a[f];if((p.route.HydrateFallback||p.route.hydrateFallbackElement)&&(l=f),p.route.id){let{loaderData:m,errors:w}=r,v=p.route.loader&&!m.hasOwnProperty(p.route.id)&&(!w||w[p.route.id]===void 0);if(p.route.lazy||v){n.isStatic&&(i=!0),l>=0?a=a.slice(0,l+1):a=[a[0]];break}}}}let c=n==null?void 0:n.onError,d=r&&c?(f,p)=>{var m,w;c(f,{location:r.location,params:((w=(m=r.matches)==null?void 0:m[0])==null?void 0:w.params)??{},unstable_pattern:Pg(r.matches),errorInfo:p})}:void 0;return a.reduceRight((f,p,m)=>{let w,v=!1,x=null,k=null;r&&(w=o&&p.route.id?o[p.route.id]:void 0,x=p.route.errorElement||Gg,i&&(l<0&&m===0?(Jf("route-fallback",!1,"No `HydrateFallback` element provided to render during initial hydration"),v=!0,k=null):l===m&&(v=!0,k=p.route.hydrateFallbackElement||null)));let g=t.concat(a.slice(0,m+1)),h=()=>{let y;return w?y=x:v?y=k:p.route.Component?y=u.createElement(p.route.Component,null):p.route.element?y=p.route.element:y=f,u.createElement(Yg,{match:p,routeContext:{outlet:f,matches:g,isDataRoute:r!=null},children:y})};return r&&(p.route.ErrorBoundary||p.route.errorElement||m===0)?u.createElement(Qf,{location:r.location,revalidation:r.revalidation,component:x,error:w,children:h(),routeContext:{outlet:null,matches:g,isDataRoute:!0},onError:d}):h()},null)}function zl(e){return`${e} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function Jg(e){let t=u.useContext(xr);return ke(t,zl(e)),t}function Xg(e){let t=u.useContext(Xa);return ke(t,zl(e)),t}function qg(e){let t=u.useContext($t);return ke(t,zl(e)),t}function $l(e){let t=qg(e),n=t.matches[t.matches.length-1];return ke(n.route.id,`${e} can only be used on routes that contain a unique "id"`),n.route.id}function Zg(){return $l("useRouteId")}function ey(){var r;let e=u.useContext(Al),t=Xg("useRouteError"),n=$l("useRouteError");return e!==void 0?e:(r=t.errors)==null?void 0:r[n]}function ty(){let{router:e}=Jg("useNavigate"),t=$l("useNavigate"),n=u.useRef(!1);return Kf(()=>{n.current=!0}),u.useCallback(async(a,o={})=>{Ct(n.current,Gf),n.current&&(typeof a=="number"?await e.navigate(a):await e.navigate(a,{fromRouteId:t,...o}))},[e,t])}var au={};function Jf(e,t,n){!t&&!au[e]&&(au[e]=!0,Ct(!1,n))}u.memo(ny);function ny({routes:e,future:t,state:n,isStatic:r,onError:a}){return Yf(e,void 0,{state:n,isStatic:r,onError:a})}function Gt({to:e,replace:t,state:n,relative:r}){ke(wr(),"<Navigate> may be used only in the context of a <Router> component.");let{static:a}=u.useContext(ht);Ct(!a,"<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:o}=u.useContext($t),{pathname:i}=gt(),l=nn(),c=Ja(e,_l(o),i,r==="path"),d=JSON.stringify(c);return u.useEffect(()=>{l(JSON.parse(d),{replace:t,state:n,relative:r})},[l,d,r,t,n]),null}function ry(e){return Wg(e.context)}function Se(e){ke(!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 sy({basename:e="/",children:t=null,location:n,navigationType:r="POP",navigator:a,static:o=!1,unstable_useTransitions:i}){ke(!wr(),"You cannot render a <Router> inside another <Router>. You should never have more than one in your app.");let l=e.replace(/^\/*/,"/"),c=u.useMemo(()=>({basename:l,navigator:a,static:o,unstable_useTransitions:i,future:{}}),[l,a,o,i]);typeof n=="string"&&(n=vr(n));let{pathname:d="/",search:f="",hash:p="",state:m=null,key:w="default",unstable_mask:v}=n,x=u.useMemo(()=>{let k=en(d,l);return k==null?null:{location:{pathname:k,search:f,hash:p,state:m,key:w,unstable_mask:v},navigationType:r}},[l,d,f,p,m,w,r,v]);return Ct(x!=null,`<Router basename="${l}"> is not able to match the URL "${d}${f}${p}" because it does not start with the basename, so the <Router> won't render anything.`),x==null?null:u.createElement(ht.Provider,{value:c},u.createElement(vs.Provider,{children:t,value:x}))}function ay({children:e,location:t}){return Hg(Ii(e),t)}function Ii(e,t=[]){let n=[];return u.Children.forEach(e,(r,a)=>{if(!u.isValidElement(r))return;let o=[...t,a];if(r.type===u.Fragment){n.push.apply(n,Ii(r.props.children,o));return}ke(r.type===Se,`[${typeof r.type=="string"?r.type:r.type.name}] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>`),ke(!r.props.index||!r.props.children,"An index route cannot have child routes.");let i={id:r.props.id||o.join("-"),caseSensitive:r.props.caseSensitive,element:r.props.element,Component:r.props.Component,index:r.props.index,path:r.props.path,middleware:r.props.middleware,loader:r.props.loader,action:r.props.action,hydrateFallbackElement:r.props.hydrateFallbackElement,HydrateFallback:r.props.HydrateFallback,errorElement:r.props.errorElement,ErrorBoundary:r.props.ErrorBoundary,hasErrorBoundary:r.props.hasErrorBoundary===!0||r.props.ErrorBoundary!=null||r.props.errorElement!=null,shouldRevalidate:r.props.shouldRevalidate,handle:r.props.handle,lazy:r.props.lazy};r.props.children&&(i.children=Ii(r.props.children,o)),n.push(i)}),n}var na="get",ra="application/x-www-form-urlencoded";function qa(e){return typeof HTMLElement<"u"&&e instanceof HTMLElement}function oy(e){return qa(e)&&e.tagName.toLowerCase()==="button"}function iy(e){return qa(e)&&e.tagName.toLowerCase()==="form"}function ly(e){return qa(e)&&e.tagName.toLowerCase()==="input"}function cy(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}function uy(e,t){return e.button===0&&(!t||t==="_self")&&!cy(e)}function Ri(e=""){return new URLSearchParams(typeof e=="string"||Array.isArray(e)||e instanceof URLSearchParams?e:Object.keys(e).reduce((t,n)=>{let r=e[n];return t.concat(Array.isArray(r)?r.map(a=>[n,a]):[[n,r]])},[]))}function dy(e,t){let n=Ri(e);return t&&t.forEach((r,a)=>{n.has(a)||t.getAll(a).forEach(o=>{n.append(a,o)})}),n}var Os=null;function fy(){if(Os===null)try{new FormData(document.createElement("form"),0),Os=!1}catch{Os=!0}return Os}var my=new Set(["application/x-www-form-urlencoded","multipart/form-data","text/plain"]);function Ro(e){return e!=null&&!my.has(e)?(Ct(!1,`"${e}" is not a valid \`encType\` for \`<Form>\`/\`<fetcher.Form>\` and will default to "${ra}"`),null):e}function py(e,t){let n,r,a,o,i;if(iy(e)){let l=e.getAttribute("action");r=l?en(l,t):null,n=e.getAttribute("method")||na,a=Ro(e.getAttribute("enctype"))||ra,o=new FormData(e)}else if(oy(e)||ly(e)&&(e.type==="submit"||e.type==="image")){let l=e.form;if(l==null)throw new Error('Cannot submit a <button> or <input type="submit"> without a <form>');let c=e.getAttribute("formaction")||l.getAttribute("action");if(r=c?en(c,t):null,n=e.getAttribute("formmethod")||l.getAttribute("method")||na,a=Ro(e.getAttribute("formenctype"))||Ro(l.getAttribute("enctype"))||ra,o=new FormData(l,e),!fy()){let{name:d,type:f,value:p}=e;if(f==="image"){let m=d?`${d}.`:"";o.append(`${m}x`,"0"),o.append(`${m}y`,"0")}else d&&o.append(d,p)}}else{if(qa(e))throw new Error('Cannot submit element that is not <form>, <button>, or <input type="submit|image">');n=na,r=null,a=ra,i=e}return o&&a==="text/plain"&&(i=o,o=void 0),{action:r,method:n.toLowerCase(),encType:a,formData:o,body:i}}Object.getOwnPropertyNames(Object.prototype).sort().join("\0");function Ll(e,t){if(e===!1||e===null||typeof e>"u")throw new Error(t)}function hy(e,t,n,r){let a=typeof e=="string"?new URL(e,typeof window>"u"?"server://singlefetch/":window.location.origin):e;return n?a.pathname.endsWith("/")?a.pathname=`${a.pathname}_.${r}`:a.pathname=`${a.pathname}.${r}`:a.pathname==="/"?a.pathname=`_root.${r}`:t&&en(a.pathname,t)==="/"?a.pathname=`${t.replace(/\/$/,"")}/_root.${r}`:a.pathname=`${a.pathname.replace(/\/$/,"")}.${r}`,a}async function gy(e,t){if(e.id in t)return t[e.id];try{let n=await import(e.module);return t[e.id]=n,n}catch(n){return console.error(`Error loading route module \`${e.module}\`, reloading page...`),console.error(n),window.__reactRouterContext&&window.__reactRouterContext.isSpaMode,window.location.reload(),new Promise(()=>{})}}function yy(e){return e==null?!1:e.href==null?e.rel==="preload"&&typeof e.imageSrcSet=="string"&&typeof e.imageSizes=="string":typeof e.rel=="string"&&typeof e.href=="string"}async function vy(e,t,n){let r=await Promise.all(e.map(async a=>{let o=t.routes[a.route.id];if(o){let i=await gy(o,n);return i.links?i.links():[]}return[]}));return jy(r.flat(1).filter(yy).filter(a=>a.rel==="stylesheet"||a.rel==="preload").map(a=>a.rel==="stylesheet"?{...a,rel:"prefetch",as:"style"}:{...a,rel:"prefetch"}))}function ou(e,t,n,r,a,o){let i=(c,d)=>n[d]?c.route.id!==n[d].route.id:!0,l=(c,d)=>{var f;return n[d].pathname!==c.pathname||((f=n[d].route.path)==null?void 0:f.endsWith("*"))&&n[d].params["*"]!==c.params["*"]};return o==="assets"?t.filter((c,d)=>i(c,d)||l(c,d)):o==="data"?t.filter((c,d)=>{var p;let f=r.routes[c.route.id];if(!f||!f.hasLoader)return!1;if(i(c,d)||l(c,d))return!0;if(c.route.shouldRevalidate){let m=c.route.shouldRevalidate({currentUrl:new URL(a.pathname+a.search+a.hash,window.origin),currentParams:((p=n[0])==null?void 0:p.params)||{},nextUrl:new URL(e,window.origin),nextParams:c.params,defaultShouldRevalidate:!0});if(typeof m=="boolean")return m}return!0}):[]}function xy(e,t,{includeHydrateFallback:n}={}){return wy(e.map(r=>{let a=t.routes[r.route.id];if(!a)return[];let o=[a.module];return a.clientActionModule&&(o=o.concat(a.clientActionModule)),a.clientLoaderModule&&(o=o.concat(a.clientLoaderModule)),n&&a.hydrateFallbackModule&&(o=o.concat(a.hydrateFallbackModule)),a.imports&&(o=o.concat(a.imports)),o}).flat(1))}function wy(e){return[...new Set(e)]}function Sy(e){let t={},n=Object.keys(e).sort();for(let r of n)t[r]=e[r];return t}function jy(e,t){let n=new Set;return new Set(t),e.reduce((r,a)=>{let o=JSON.stringify(Sy(a));return n.has(o)||(n.add(o),r.push({key:o,link:a})),r},[])}function Xf(){let e=u.useContext(xr);return Ll(e,"You must render this element inside a <DataRouterContext.Provider> element"),e}function ky(){let e=u.useContext(Xa);return Ll(e,"You must render this element inside a <DataRouterStateContext.Provider> element"),e}var Ml=u.createContext(void 0);Ml.displayName="FrameworkContext";function qf(){let e=u.useContext(Ml);return Ll(e,"You must render this element inside a <HydratedRouter> element"),e}function by(e,t){let n=u.useContext(Ml),[r,a]=u.useState(!1),[o,i]=u.useState(!1),{onFocus:l,onBlur:c,onMouseEnter:d,onMouseLeave:f,onTouchStart:p}=t,m=u.useRef(null);u.useEffect(()=>{if(e==="render"&&i(!0),e==="viewport"){let x=g=>{g.forEach(h=>{i(h.isIntersecting)})},k=new IntersectionObserver(x,{threshold:.5});return m.current&&k.observe(m.current),()=>{k.disconnect()}}},[e]),u.useEffect(()=>{if(r){let x=setTimeout(()=>{i(!0)},100);return()=>{clearTimeout(x)}}},[r]);let w=()=>{a(!0)},v=()=>{a(!1),i(!1)};return n?e!=="intent"?[o,m,{}]:[o,m,{onFocus:Rr(l,w),onBlur:Rr(c,v),onMouseEnter:Rr(d,w),onMouseLeave:Rr(f,v),onTouchStart:Rr(p,w)}]:[!1,m,{}]}function Rr(e,t){return n=>{e&&e(n),n.defaultPrevented||t(n)}}function Cy({page:e,...t}){let{router:n}=Xf(),r=u.useMemo(()=>Ff(n.routes,e,n.basename),[n.routes,e,n.basename]);return r?u.createElement(Ey,{page:e,matches:r,...t}):null}function Ny(e){let{manifest:t,routeModules:n}=qf(),[r,a]=u.useState([]);return u.useEffect(()=>{let o=!1;return vy(e,t,n).then(i=>{o||a(i)}),()=>{o=!0}},[e,t,n]),r}function Ey({page:e,matches:t,...n}){let r=gt(),{future:a,manifest:o,routeModules:i}=qf(),{basename:l}=Xf(),{loaderData:c,matches:d}=ky(),f=u.useMemo(()=>ou(e,t,d,o,r,"data"),[e,t,d,o,r]),p=u.useMemo(()=>ou(e,t,d,o,r,"assets"),[e,t,d,o,r]),m=u.useMemo(()=>{if(e===r.pathname+r.search+r.hash)return[];let x=new Set,k=!1;if(t.forEach(h=>{var S;let y=o.routes[h.route.id];!y||!y.hasLoader||(!f.some(b=>b.route.id===h.route.id)&&h.route.id in c&&((S=i[h.route.id])!=null&&S.shouldRevalidate)||y.hasClientLoader?k=!0:x.add(h.route.id))}),x.size===0)return[];let g=hy(e,l,a.unstable_trailingSlashAwareDataRequests,"data");return k&&x.size>0&&g.searchParams.set("_routes",t.filter(h=>x.has(h.route.id)).map(h=>h.route.id).join(",")),[g.pathname+g.search]},[l,a.unstable_trailingSlashAwareDataRequests,c,r,o,f,t,e,i]),w=u.useMemo(()=>xy(p,o),[p,o]),v=Ny(p);return u.createElement(u.Fragment,null,m.map(x=>u.createElement("link",{key:x,rel:"prefetch",as:"fetch",href:x,...n})),w.map(x=>u.createElement("link",{key:x,rel:"modulepreload",href:x,...n})),v.map(({key:x,link:k})=>u.createElement("link",{key:x,nonce:n.nonce,...k,crossOrigin:k.crossOrigin??n.crossOrigin})))}function Ty(...e){return t=>{e.forEach(n=>{typeof n=="function"?n(t):n!=null&&(n.current=t)})}}var Iy=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";try{Iy&&(window.__reactRouterVersion="7.13.1")}catch{}function Ry({basename:e,children:t,unstable_useTransitions:n,window:r}){let a=u.useRef();a.current==null&&(a.current=og({window:r,v5Compat:!0}));let o=a.current,[i,l]=u.useState({action:o.action,location:o.location}),c=u.useCallback(d=>{n===!1?l(d):u.startTransition(()=>l(d))},[n]);return u.useLayoutEffect(()=>o.listen(c),[o,c]),u.createElement(sy,{basename:e,children:t,location:i.location,navigationType:i.action,navigator:o,unstable_useTransitions:n})}var Zf=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,Ye=u.forwardRef(function({onClick:t,discover:n="render",prefetch:r="none",relative:a,reloadDocument:o,replace:i,unstable_mask:l,state:c,target:d,to:f,preventScrollReset:p,viewTransition:m,unstable_defaultShouldRevalidate:w,...v},x){let{basename:k,navigator:g,unstable_useTransitions:h}=u.useContext(ht),y=typeof f=="string"&&Zf.test(f),S=Uf(f,k);f=S.to;let b=Bg(f,{relative:a}),N=gt(),C=null;if(l){let _=Ja(l,[],N.unstable_mask?N.unstable_mask.pathname:"/",!0);k!=="/"&&(_.pathname=_.pathname==="/"?k:Dt([k,_.pathname])),C=g.createHref(_)}let[I,E,$]=by(r,v),U=Ay(f,{replace:i,unstable_mask:l,state:c,target:d,preventScrollReset:p,relative:a,viewTransition:m,unstable_defaultShouldRevalidate:w,unstable_useTransitions:h});function V(_){t&&t(_),_.defaultPrevented||U(_)}let J=!(S.isExternal||o),D=u.createElement("a",{...v,...$,href:(J?C:void 0)||S.absoluteURL||b,onClick:J?V:t,ref:Ty(x,E),target:d,"data-discover":!y&&n==="render"?"true":void 0});return I&&!y?u.createElement(u.Fragment,null,D,u.createElement(Cy,{page:b})):D});Ye.displayName="Link";var Fl=u.forwardRef(function({"aria-current":t="page",caseSensitive:n=!1,className:r="",end:a=!1,style:o,to:i,viewTransition:l,children:c,...d},f){let p=xs(i,{relative:d.relative}),m=gt(),w=u.useContext(Xa),{navigator:v,basename:x}=u.useContext(ht),k=w!=null&&Fy(p)&&l===!0,g=v.encodeLocation?v.encodeLocation(p).pathname:p.pathname,h=m.pathname,y=w&&w.navigation&&w.navigation.location?w.navigation.location.pathname:null;n||(h=h.toLowerCase(),y=y?y.toLowerCase():null,g=g.toLowerCase()),y&&x&&(y=en(y,x)||y);const S=g!=="/"&&g.endsWith("/")?g.length-1:g.length;let b=h===g||!a&&h.startsWith(g)&&h.charAt(S)==="/",N=y!=null&&(y===g||!a&&y.startsWith(g)&&y.charAt(g.length)==="/"),C={isActive:b,isPending:N,isTransitioning:k},I=b?t:void 0,E;typeof r=="function"?E=r(C):E=[r,b?"active":null,N?"pending":null,k?"transitioning":null].filter(Boolean).join(" ");let $=typeof o=="function"?o(C):o;return u.createElement(Ye,{...d,"aria-current":I,className:E,ref:f,style:$,to:i,viewTransition:l},typeof c=="function"?c(C):c)});Fl.displayName="NavLink";var Py=u.forwardRef(({discover:e="render",fetcherKey:t,navigate:n,reloadDocument:r,replace:a,state:o,method:i=na,action:l,onSubmit:c,relative:d,preventScrollReset:f,viewTransition:p,unstable_defaultShouldRevalidate:m,...w},v)=>{let{unstable_useTransitions:x}=u.useContext(ht),k=Ly(),g=My(l,{relative:d}),h=i.toLowerCase()==="get"?"get":"post",y=typeof l=="string"&&Zf.test(l),S=b=>{if(c&&c(b),b.defaultPrevented)return;b.preventDefault();let N=b.nativeEvent.submitter,C=(N==null?void 0:N.getAttribute("formmethod"))||i,I=()=>k(N||b.currentTarget,{fetcherKey:t,method:C,navigate:n,replace:a,state:o,relative:d,preventScrollReset:f,viewTransition:p,unstable_defaultShouldRevalidate:m});x&&n!==!1?u.startTransition(()=>I()):I()};return u.createElement("form",{ref:v,method:h,action:g,onSubmit:r?c:S,...w,"data-discover":!y&&e==="render"?"true":void 0})});Py.displayName="Form";function _y(e){return`${e} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function em(e){let t=u.useContext(xr);return ke(t,_y(e)),t}function Ay(e,{target:t,replace:n,unstable_mask:r,state:a,preventScrollReset:o,relative:i,viewTransition:l,unstable_defaultShouldRevalidate:c,unstable_useTransitions:d}={}){let f=nn(),p=gt(),m=xs(e,{relative:i});return u.useCallback(w=>{if(uy(w,t)){w.preventDefault();let v=n!==void 0?n:fs(p)===fs(m),x=()=>f(e,{replace:v,unstable_mask:r,state:a,preventScrollReset:o,relative:i,viewTransition:l,unstable_defaultShouldRevalidate:c});d?u.startTransition(()=>x()):x()}},[p,f,m,n,r,a,t,e,o,i,l,c,d])}function tm(e){Ct(typeof URLSearchParams<"u","You cannot use the `useSearchParams` hook in a browser that does not support the URLSearchParams API. If you need to support Internet Explorer 11, we recommend you load a polyfill such as https://github.com/ungap/url-search-params.");let t=u.useRef(Ri(e)),n=u.useRef(!1),r=gt(),a=u.useMemo(()=>dy(r.search,n.current?null:t.current),[r.search]),o=nn(),i=u.useCallback((l,c)=>{const d=Ri(typeof l=="function"?l(new URLSearchParams(a)):l);n.current=!0,o("?"+d,c)},[o,a]);return[a,i]}var zy=0,$y=()=>`__${String(++zy)}__`;function Ly(){let{router:e}=em("useSubmit"),{basename:t}=u.useContext(ht),n=Zg(),r=e.fetch,a=e.navigate;return u.useCallback(async(o,i={})=>{let{action:l,method:c,encType:d,formData:f,body:p}=py(o,t);if(i.navigate===!1){let m=i.fetcherKey||$y();await r(m,n,i.action||l,{unstable_defaultShouldRevalidate:i.unstable_defaultShouldRevalidate,preventScrollReset:i.preventScrollReset,formData:f,body:p,formMethod:i.method||c,formEncType:i.encType||d,flushSync:i.flushSync})}else await a(i.action||l,{unstable_defaultShouldRevalidate:i.unstable_defaultShouldRevalidate,preventScrollReset:i.preventScrollReset,formData:f,body:p,formMethod:i.method||c,formEncType:i.encType||d,replace:i.replace,state:i.state,fromRouteId:n,flushSync:i.flushSync,viewTransition:i.viewTransition})},[r,a,t,n])}function My(e,{relative:t}={}){let{basename:n}=u.useContext(ht),r=u.useContext($t);ke(r,"useFormAction must be used inside a RouteContext");let[a]=r.matches.slice(-1),o={...xs(e||".",{relative:t})},i=gt();if(e==null){o.search=i.search;let l=new URLSearchParams(o.search),c=l.getAll("index");if(c.some(f=>f==="")){l.delete("index"),c.filter(p=>p).forEach(p=>l.append("index",p));let f=l.toString();o.search=f?`?${f}`:""}}return(!e||e===".")&&a.route.index&&(o.search=o.search?o.search.replace(/^\?/,"?index&"):"?index"),n!=="/"&&(o.pathname=o.pathname==="/"?n:Dt([n,o.pathname])),fs(o)}function Fy(e,{relative:t}={}){let n=u.useContext(Hf);ke(n!=null,"`useViewTransitionState` must be used within `react-router-dom`'s `RouterProvider`. Did you accidentally import `RouterProvider` from `react-router`?");let{basename:r}=em("useViewTransitionState"),a=xs(e,{relative:t});if(!n.isTransitioning)return!1;let o=en(n.currentLocation.pathname,r)||n.currentLocation.pathname,i=en(n.nextLocation.pathname,r)||n.nextLocation.pathname;return Ra(a.pathname,i)!=null||Ra(a.pathname,o)!=null}class nm extends Error{constructor(n){super("different_account");Sr(this,"summary");this.name="DifferentAccountError",this.summary=n}}class Oy{constructor(){Sr(this,"apiKey",null)}setApiKey(t){this.apiKey=t}clearApiKey(){this.apiKey=null}getApiKey(){return this.apiKey}async fetch(t,n){return globalThis.fetch(t,{...n,headers:{"Content-Type":"application/json",...this.apiKey?{"X-API-Key":this.apiKey}:{},...n==null?void 0:n.headers}})}async login(t,n={}){const r=await this.fetch("/auth/login",{method:"POST",headers:{"X-API-Key":t,"Content-Type":"application/json"},body:JSON.stringify({confirmWipe:n.confirmWipe===!0})});if(r.status===409){const o=await r.json().catch(()=>({}));if(o!=null&&o.wouldWipe)throw new nm(o.summary??{credentialCount:0,serviceCount:0,credentialIds:[]})}if(!r.ok){const o=await r.json().catch(()=>({error:"Invalid API key"}));throw new Error(o.error||`Login failed: ${r.status}`)}return(await r.json()).user}async logout(){await this.fetch("/auth/logout",{method:"POST"})}async getGroups(){const t=await this.fetch("/api/groups");if(!t.ok)throw new Error(`Failed to fetch groups: ${t.status}`);const n=await t.json();return n.groups??n}async listProfiles(){const t=await this.fetch("/api/profiles");if(!t.ok)throw new Error(`Failed to fetch profiles: ${t.status}`);return(await t.json()).profiles}async getProfile(t){const n=await this.fetch(`/api/profiles/${encodeURIComponent(t)}`);if(!n.ok)throw new Error(`Failed to fetch profile: ${n.status}`);return n.json()}async attest(t){const n=await this.fetch("/api/as/attest",{method:"POST",body:JSON.stringify(t)});if(!n.ok){const r=await n.json().catch(()=>({error:"Unknown error"}));throw new Error(r.error||`Attest failed: ${n.status}`)}return n.json()}async getPending(t){const n=await this.fetch(`/api/attestations/pending?domain=${encodeURIComponent(t)}`);if(!n.ok)throw new Error(`Failed to fetch pending: ${n.status}`);const r=await n.json();return r.pending??r}async getMyAttestations(t){const n=t?`?status=${encodeURIComponent(t)}`:"",r=await this.fetch(`/api/attestations/mine${n}`);if(!r.ok)throw new Error(`Failed to fetch attestations: ${r.status}`);return((await r.json()).attestations??[]).map(o=>{var i,l;return{authorization_id:o.authorization_id,profile_id:o.profileId,path:o.path,title:o.title??null,sp_status:o.status??null,frame:o.bounds??o.frame??{},required_domains:o.requiredDomains??[],attested_domains:o.attestedDomains??[],missing_domains:(o.requiredDomains??[]).filter(c=>!(o.attestedDomains??[]).includes(c)),deferred_commitment_domains:o.deferredCommitmentDomains??[],approvers_frozen:o.approversFrozen??[],above_cap:o.aboveCap??!1,created_at:o.createdAt?new Date(o.createdAt*1e3).toISOString():"",earliest_expiry:(i=o.attestations)!=null&&i.length?new Date(Math.min(...o.attestations.map(c=>c.expiresAt))*1e3).toISOString():null,remaining_seconds:(l=o.attestations)!=null&&l.length?Math.max(0,Math.min(...o.attestations.map(c=>c.expiresAt))-Math.floor(Date.now()/1e3)):null}})}async getDenials(t){const n=new URLSearchParams;t!=null&&t.since&&n.set("since",String(t.since)),t!=null&&t.limit&&n.set("limit",String(t.limit));const r=n.toString()?`?${n.toString()}`:"",a=await this.fetch(`/denials${r}`);if(!a.ok)throw new Error(`Failed to fetch denials: ${a.status}`);return a.json()}async getMyReceipts(t){const n=new URLSearchParams;t!=null&&t.date&&n.set("date",t.date),t!=null&&t.profile&&n.set("profile",t.profile),t!=null&&t.limit&&n.set("limit",String(t.limit));const r=n.toString(),a=await this.fetch(`/api/receipts/mine${r?"?"+r:""}`);if(!a.ok)throw new Error(`Failed to fetch receipts: ${a.status}`);return(await a.json()).receipts??[]}async fetchEvidenceBundle(){var a;const t=await this.fetch("/api/evidence-export"),n=await t.json();if(!t.ok)throw new Error(n.error??`Export failed (${t.status})`);const r=((a=/filename="([^"]+)"/.exec(t.headers.get("content-disposition")??""))==null?void 0:a[1])??"suveren-evidence.json";return{bundle:n,filename:r}}async getLocalAuthorizations(){const t=await this.fetch("/api/evidence/authorizations");if(!t.ok)throw new Error(`Local evidence unavailable (${t.status})`);const n=await t.json();return{authorizations:n.authorizations??{},signatures:n.signatures??{}}}async getArchivedReceipt(t){const n=await this.fetch(`/api/evidence/receipt/${encodeURIComponent(t)}`);if(n.status===404)return null;if(!n.ok)throw new Error(`Local evidence unavailable (${n.status})`);return await n.json()}async revokeAttestation(t,n){const r=await this.fetch(`/api/authorizations/${encodeURIComponent(t)}/revoke`,{method:"POST",body:JSON.stringify({reason:n??"Revoked by user"})});if(!r.ok){const a=await r.json().catch(()=>({error:"Failed to revoke"}));throw new Error(a.error||`Revoke failed: ${r.status}`)}}async getAttestations(t){const n=await this.fetch(`/api/attestations?authorization_id=${encodeURIComponent(t)}`);if(!n.ok)throw new Error(`Failed to fetch attestations: ${n.status}`);return n.json()}async getGroupById(t){const n=await this.fetch(`/api/groups/${encodeURIComponent(t)}`);if(!n.ok)throw new Error(`Failed to fetch group: ${n.status}`);return n.json()}async createGroup(t){const n=await this.fetch("/api/groups",{method:"POST",body:JSON.stringify({name:t})});if(!n.ok){const o=await n.json().catch(()=>({error:"Unknown error"}));throw new Error(o.error||`Create group failed: ${n.status}`)}const r=await n.json(),a=r.group||r;return{id:a.id,name:a.name,myDomains:a.myDomains||[],isAdmin:!0}}async joinGroup(t){const n=await this.fetch("/api/groups/join",{method:"POST",body:JSON.stringify({inviteCode:t})});if(!n.ok){const o=await n.json().catch(()=>({error:"Unknown error"}));throw new Error(o.error||`Join group failed: ${n.status}`)}const r=await n.json(),a=r.group||r;return{id:a.id,name:a.name,myDomains:a.myDomains||[],isAdmin:a.isAdmin||!1}}async inviteToGroup(t){const n=await this.fetch(`/api/groups/${encodeURIComponent(t)}/invite`,{method:"POST"});if(!n.ok){const r=await n.json().catch(()=>({error:"Unknown error"}));throw new Error(r.error||`Invite failed: ${n.status}`)}return n.json()}async getMyTeam(){const t=await this.fetch("/api/groups/me");if(!t.ok)return null;const n=await t.json();return n.group?{group:n.group,membership:n.membership}:null}async listUsers(){const t=await this.fetch("/api/users");return t.ok?(await t.json()).users??[]:[]}async setPubkey(t){const n=await this.fetch("/api/users/me/pubkey",{method:"PUT",body:JSON.stringify({pubkey:t})});if(!n.ok){const r=await n.json().catch(()=>({error:"Failed to set pubkey"}));throw new Error(r.error||`setPubkey failed: ${n.status}`)}}async getPubkey(t){const n=await this.fetch(`/api/users/${encodeURIComponent(t)}/pubkey`);return n.status===404||!n.ok?null:(await n.json()).pubkey??null}async leaveTeam(t){const n=await this.fetch(`/api/groups/${encodeURIComponent(t)}/leave`,{method:"POST"});if(!n.ok){const r=await n.json().catch(()=>({error:"Failed to leave team"}));throw new Error(r.error||`Leave failed: ${n.status}`)}}async getVaultStatus(){const t=await this.fetch("/vault/status");if(!t.ok)throw new Error(`Failed to fetch vault status: ${t.status}`);return t.json()}async getGatewaySettings(){const t=await this.fetch("/api/gateway-settings");if(!t.ok)throw new Error(`Failed to load settings: ${t.status}`);return t.json()}async setGatewaySettings(t){const n=await this.fetch("/api/gateway-settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok)throw new Error(`Failed to save settings: ${n.status}`);return n.json()}async getArchivedMandates(){const t=await this.fetch("/api/archived-mandates");if(!t.ok)throw new Error(`Failed to load archived mandates: ${t.status}`);return(await t.json()).archived}async setMandateArchived(t,n){const r=await this.fetch(`/api/archived-mandates/${encodeURIComponent(t)}`,{method:n?"PUT":"DELETE"});if(!r.ok)throw new Error(`Failed to ${n?"archive":"unarchive"} mandate: ${r.status}`);return(await r.json()).archived}async getCredential(t){const n=await this.fetch(`/vault/credentials/${encodeURIComponent(t)}`);if(!n.ok)throw new Error(`Failed to check credential: ${n.status}`);return n.json()}async setCredential(t,n){const r=await this.fetch(`/vault/credentials/${encodeURIComponent(t)}`,{method:"PUT",body:JSON.stringify(n)});if(!r.ok)throw new Error(`Failed to save credential: ${r.status}`)}async testCredential(t){const n=await this.fetch(`/vault/test/${encodeURIComponent(t)}`,{method:"POST"});if(!n.ok)throw new Error(`Test failed: ${n.status}`);return n.json()}async aiAssist(t){const n=await this.fetch("/ai/assist",{method:"POST",body:JSON.stringify(t)});return n.ok?n.json():{success:!1,error:(await n.json().catch(()=>({error:"AI request failed"}))).error,disclaimer:"AI surfaces reality. You supply intent."}}async aiIntentReview(t){const n=await this.fetch("/ai/intent-review",{method:"POST",body:JSON.stringify(t)});return n.ok?n.json():{success:!1,error:(await n.json().catch(()=>({error:"AI request failed"}))).error}}async aiTest(t){const n=await this.fetch("/ai/test",{method:"POST",body:JSON.stringify(t??{})});if(!n.ok)throw new Error(`AI test failed: ${n.status}`);return n.json()}async aiModels(t){const n=await this.fetch("/ai/models",{method:"POST",body:JSON.stringify(t??{})});if(!n.ok)throw new Error(`Model list failed: ${n.status}`);return n.json()}async getMcpHealth(){const t=await this.fetch("/mcp/health");if(!t.ok)throw new Error(`MCP server unreachable: ${t.status}`);return t.json()}async getMcpIntegrations(){const t=await this.fetch("/mcp/integrations");if(!t.ok)throw new Error(`Failed to fetch integrations: ${t.status}`);return t.json()}async getOAuthHealth(t){try{const n=await this.fetch(`/auth/oauth/${encodeURIComponent(t)}/health`);return n.ok?await n.json():{status:"unverified"}}catch{return{status:"unverified"}}}async getIntegrationManifests(){const t=await this.fetch("/mcp/integrations/manifests");if(!t.ok)throw new Error(`Failed to fetch manifests: ${t.status}`);return t.json()}async discoverScopeField(t,n){const r=await this.fetch(`/integrations/${encodeURIComponent(t)}/discover/${encodeURIComponent(n)}`);if(!r.ok){const a=await r.json().catch(()=>({error:`Discovery failed: ${r.status}`}));throw new Error(a.error)}return r.json()}async activateIntegration(t){const n=await this.fetch(`/mcp/integrations/${encodeURIComponent(t)}/activate`,{method:"POST"});if(!n.ok){const r=await n.json().catch(()=>({error:"Failed"}));throw new Error(r.error||`Failed: ${n.status}`)}return n.json()}async removeMcpIntegration(t){const n=await this.fetch(`/mcp/integrations/${encodeURIComponent(t)}`,{method:"DELETE"});if(!n.ok)throw new Error(`Failed to remove integration: ${n.status}`)}async setReadPolicy(t,n){const r=await this.fetch(`/integrations/${encodeURIComponent(t)}/read-policy`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({readAgeDays:n})});if(!r.ok){const a=await r.json().catch(()=>({error:`HTTP ${r.status}`}));throw new Error(a.error)}}async getTeamProfileConfig(t,n){const r=await this.fetch(`/api/groups/${encodeURIComponent(t)}/profile-config/${encodeURIComponent(n)}`);if(r.status===404||!r.ok)return null;const a=await r.json();return(a==null?void 0:a.config)??null}async setTeamProfileConfig(t,n,r){const a=await this.fetch(`/api/groups/${encodeURIComponent(t)}/profile-config/${encodeURIComponent(n)}`,{method:"PUT",body:JSON.stringify(r)});if(!a.ok){const o=await a.json().catch(()=>({error:"Failed to set profile config"}));throw new Error(o.error||`setTeamProfileConfig failed: ${a.status}`)}}async encryptIntent(t,n){const r=await this.fetch("/api/encrypt-intent",{method:"POST",body:JSON.stringify({intent:t,recipients:n})});if(!r.ok){const a=await r.json().catch(()=>({error:"Encryption failed"}));throw new Error(a.error||`encryptIntent failed: ${r.status}`)}return r.json()}async getApproversPubkeys(t,n){const r=await this.fetch(`/api/groups/${encodeURIComponent(t)}/profile-config/${encodeURIComponent(n)}/approvers/pubkeys`);return r.ok?(await r.json()).approvers??[]:[]}async deleteTeamProfileConfig(t,n){const r=await this.fetch(`/api/groups/${encodeURIComponent(t)}/profile-config/${encodeURIComponent(n)}`,{method:"DELETE"});if(!r.ok){const a=await r.json().catch(()=>({error:"Failed to delete profile config"}));throw new Error(a.error||`deleteTeamProfileConfig failed: ${r.status}`)}}async getProposals(t){const n=await this.fetch(`/api/proposals?domain=${encodeURIComponent(t)}`);if(!n.ok)throw new Error(`Failed to fetch proposals: ${n.status}`);return(await n.json()).proposals??[]}async resolveProposal(t,n,r){const a=await this.fetch(`/api/proposals/${encodeURIComponent(t)}/resolve`,{method:"POST",body:JSON.stringify({action:n,domain:r})});if(!a.ok){const o=await a.json().catch(()=>({error:"Failed"}));throw new Error(o.error||`Failed: ${a.status}`)}return a.json()}async getProposalsForApprover(){const t=await this.fetch("/api/proposals?approver=me");if(!t.ok)throw new Error(`Failed to fetch approver proposals: ${t.status}`);return(await t.json()).proposals??[]}async approveProposal(t){const n=await this.fetch(`/api/proposals/${encodeURIComponent(t)}/approve`,{method:"POST"});if(!n.ok){const r=await n.json().catch(()=>({error:"Failed"}));throw new Error(r.error||`approveProposal failed: ${n.status}`)}return n.json()}async rejectProposal(t,n){const r=await this.fetch(`/api/proposals/${encodeURIComponent(t)}/reject`,{method:"POST",body:JSON.stringify({reason:n})});if(!r.ok){const a=await r.json().catch(()=>({error:"Failed"}));throw new Error(a.error||`rejectProposal failed: ${r.status}`)}return r.json()}async getAttestationIntent(t){const n=await this.fetch(`/api/authorizations/${encodeURIComponent(t)}/intent`);return n.status===404||n.status===403||!n.ok?null:n.json()}async decryptIntent(t){const n=await this.fetch("/api/decrypt-intent",{method:"POST",body:JSON.stringify(t)});if(!n.ok){const a=await n.json().catch(()=>({error:"Decryption failed"}));throw new Error(a.error||`decryptIntent failed: ${n.status}`)}return(await n.json()).intent}async storeApprovedIntent(t,n){const r=await this.fetch("/api/approved-intents",{method:"POST",body:JSON.stringify({authorityId:t,intent:n})});if(!r.ok){const a=await r.json().catch(()=>({error:"Failed"}));throw new Error(a.error||`storeApprovedIntent failed: ${r.status}`)}}async listTeamAuthorizations(t){const n=await this.fetch(`/api/groups/${encodeURIComponent(t)}/attestations`);if(!n.ok)throw new Error(`Failed to fetch team authorizations: ${n.status}`);return((await n.json()).items??[]).map(a=>{var l,c;const o=a.owner??{userId:""};return{authorization_id:a.authorization_id??a.authorizationId,profile_id:a.profileId??a.profile_id,path:a.path??"",title:a.title??null,sp_status:a.status??a.sp_status??null,frame:a.bounds??a.frame??{},required_domains:a.requiredDomains??a.required_domains??[],attested_domains:a.attestedDomains??a.attested_domains??[],missing_domains:(a.requiredDomains??a.required_domains??[]).filter(d=>!(a.attestedDomains??a.attested_domains??[]).includes(d)),deferred_commitment_domains:a.deferredCommitmentDomains??a.deferred_commitment_domains??[],approvers_frozen:a.approversFrozen??a.approvers_frozen??[],above_cap:a.aboveCap??a.above_cap??!1,created_at:a.createdAt?new Date(a.createdAt*1e3).toISOString():a.created_at??"",earliest_expiry:(l=a.attestations)!=null&&l.length?new Date(Math.min(...a.attestations.map(d=>d.expiresAt))*1e3).toISOString():null,remaining_seconds:(c=a.attestations)!=null&&c.length?Math.max(0,Math.min(...a.attestations.map(d=>d.expiresAt))-Math.floor(Date.now()/1e3)):null,owner:o}})}async listTeamReceipts(t){const n=await this.fetch(`/api/groups/${encodeURIComponent(t)}/receipts`);if(!n.ok)throw new Error(`Failed to fetch team receipts: ${n.status}`);return(await n.json()).receipts??[]}async getMyReceiptsPage(t){const n=new URLSearchParams;t!=null&&t.before&&n.set("before",t.before),t!=null&&t.profile&&n.set("profile",t.profile),t!=null&&t.limit&&n.set("limit",String(t.limit));const r=n.toString(),a=await this.fetch(`/api/receipts/mine${r?"?"+r:""}`);if(!a.ok)throw new Error(`Failed to fetch receipts: ${a.status}`);const o=await a.json();return{receipts:o.receipts??[],nextBefore:o.nextBefore??null}}async listTeamReceiptsPage(t,n){const r=new URLSearchParams;n!=null&&n.before&&r.set("before",n.before),n!=null&&n.profile&&r.set("profile",n.profile),n!=null&&n.limit&&r.set("limit",String(n.limit));const a=r.toString(),o=await this.fetch(`/api/groups/${encodeURIComponent(t)}/receipts${a?"?"+a:""}`);if(!o.ok)throw new Error(`Failed to fetch team receipts: ${o.status}`);const i=await o.json();return{receipts:i.receipts??[],nextBefore:i.nextBefore??null}}async getThread(t){const n=t.sinceDays??7,r=t.status??"pending",a=t.domain||"owner",o=await this.getProposals(a);let i=[];if(r==="all"){const l=[],c=new Date;for(let f=0;f<n;f++){const p=new Date(c);p.setUTCDate(c.getUTCDate()-f),l.push(p.toISOString().slice(0,10))}i=(await Promise.all(l.map(f=>this.getMyReceipts({date:f,profile:t.profile})))).flat()}return{proposals:o,receipts:i}}async getAutostart(){const t=await this.fetch("/autostart");if(!t.ok)throw new Error(`HTTP ${t.status}`);return t.json()}async setAutostart(t){const n=await this.fetch("/autostart",{method:t?"POST":"DELETE"});if(!n.ok){const r=await n.json().catch(()=>({}));throw new Error(r.message||`HTTP ${n.status}`)}}async getAsPairing(){const t=await this.fetch("/as-pairing");if(!t.ok)throw new Error(`HTTP ${t.status}`);return t.json()}async getSkippedCommitments(){const t=await this.fetch("/skipped-commitments");if(!t.ok)throw new Error(`HTTP ${t.status}`);return t.json()}async getGateContent(t){const n=await this.fetch(`/gate-content?path=${encodeURIComponent(t)}`);if(!n.ok)throw new Error(`Failed to fetch gate content: ${n.status}`);return(await n.json()).entry??null}async resyncGates(){const t=await this.fetch("/resync-gates",{method:"POST"});if(!t.ok)throw new Error(`Failed to resync gates: ${t.status}`)}async getEnrichedAuthorizations(){const t=await this.fetch("/active-authorizations");if(!t.ok)throw new Error(`Failed to fetch authorizations: ${t.status}`);return(await t.json()).authorizations??[]}async pushGateContent(t){const n=await this.fetch("/gate-content",{method:"POST",body:JSON.stringify(t)});if(!n.ok){const r=await n.json().catch(()=>({error:"Failed to push gate content"}));throw new Error(r.error||`Push gate content failed: ${n.status}`)}}async getAgentContext(){const t=await this.fetch("/agent-brief/context");if(!t.ok)throw new Error(`Failed to fetch agent context: ${t.status}`);return(await t.json()).content}async saveAgentContext(t){const n=await this.fetch("/agent-brief/context",{method:"PUT",body:JSON.stringify({content:t})});if(!n.ok){const r=await n.json().catch(()=>({error:"Failed to save agent context"}));throw new Error(r.error||`Save failed: ${n.status}`)}}async aiChat(t){const n=await this.fetch("/ai/chat",{method:"POST",body:JSON.stringify(t)});return n.ok?n.json():{success:!1,error:(await n.json().catch(()=>({error:"AI chat failed"}))).error||`Chat failed: ${n.status}`}}async getAIPrompts(){const t=await this.fetch("/ai-prompts");if(!t.ok)throw new Error(`Failed to load AI prompts: ${t.status}`);return t.json()}async setAIPrompt(t,n){const r=await this.fetch(`/ai-prompts/${t}`,{method:"PUT",body:JSON.stringify({value:n})});if(!r.ok){const a=await r.json().catch(()=>({error:"Save failed"}));throw new Error(a.error||`Save failed: ${r.status}`)}}}const T=new Oy,rm=u.createContext(null);function By({children:e}){const[t,n]=u.useState(null),[r,a]=u.useState("personal"),[o,i]=u.useState(null),[l,c]=u.useState(""),[d,f]=u.useState(null),[p,m]=u.useState(null),[w,v]=u.useState(!1),[x,k]=u.useState(""),g=u.useRef(!1),h=u.useRef(null),y=u.useCallback(async()=>{if(g.current)try{const E=await T.getMyTeam();if(E){const{group:$,membership:U}=E;f($),m(U),a("team"),i($);const V=h.current??U.domains[0]??"owner";c(V)}else f(null),m(null),a("personal")}catch{}},[]);u.useEffect(()=>{const E=()=>{document.visibilityState==="visible"&&y()};return document.addEventListener("visibilitychange",E),()=>document.removeEventListener("visibilitychange",E)},[y]),u.useEffect(()=>{fetch("/health").then(E=>E.json()).then(E=>{var $;(($=E.session)==null?void 0:$.lockedReason)==="as-url-changed"&&k(`Authority Server changed to ${E.spUrl??"a new server"} — sign in again.`)}).catch(()=>{})},[]);const S=u.useCallback(async(E,$={})=>{v(!0),k("");try{T.setApiKey(E),g.current=!0;const U=await T.login(E,$);n(U),h.current=U.id;const V=await T.getGroups(),J=V.find(D=>D.isPersonal)??V[0]??null;i(J),c("owner"),await y()}catch(U){throw T.clearApiKey(),g.current=!1,k(U instanceof Error?U.message:"Login failed"),U}finally{v(!1)}},[y]),b=u.useCallback(async()=>{await T.logout(),T.clearApiKey(),g.current=!1,h.current=null,n(null),i(null),c(""),f(null),m(null),a("personal"),k("")},[]),N=u.useCallback(E=>{T.clearApiKey(),g.current=!1,h.current=null,n(null),i(null),c(""),f(null),m(null),a("personal"),k(E??"Your sign-in ended after 30 days or was revoked. Sign in again.")},[]),C=u.useCallback(()=>k(""),[]),I=u.useCallback((E,$)=>{i(E),c($)},[]);return s.jsx(rm.Provider,{value:{user:t,mode:r,group:o,domain:l,groupId:(o==null?void 0:o.id)??null,activeTeam:d,activeMembership:p,isLoading:w,error:x,login:S,logout:b,clearError:C,handleSessionLocked:N,activeGroup:o,activeDomain:l,groups:o?[o]:[],setActiveContext:I,refreshGroups:y},children:e})}function Fe(){const e=u.useContext(rm);if(!e)throw new Error("useAuth must be used within AuthProvider");return e}const sm=u.createContext(null);function Dy({children:e}){const{user:t}=Fe(),n=u.useRef(null),[r,a]=u.useState(!1),o=u.useRef(new Map),i=u.useCallback((l,c)=>{const d=o.current;return d.has(l)||d.set(l,new Set),d.get(l).add(c),()=>{var f;(f=d.get(l))==null||f.delete(c)}},[]);return u.useEffect(()=>{if(!t){n.current&&(n.current.close(),n.current=null,a(!1));return}if(n.current)return;const l=T.getApiKey();if(!l)return;const c=new EventSource(`/events?key=${encodeURIComponent(l)}`);n.current=c,c.onopen=()=>a(!0),c.onerror=()=>a(!1);const d=["integration-changed","attestation-changed","proposal-added","proposal-resolved","team-membership-changed","action-approval-needed","action-resolved","proposal-approved","proposal-rejected","session-locked"];for(const f of d)c.addEventListener(f,p=>{let m;try{m=JSON.parse(p.data)}catch{m=null}const w=o.current.get(f);if(w)for(const v of w)try{v(m)}catch(x){console.error(`[EventSource] handler for "${f}" threw:`,x)}});return()=>{c.close(),n.current=null,a(!1)}},[t]),s.jsx(sm.Provider,{value:{connected:r,addListener:i},children:e})}function fe(e,t){const n=u.useContext(sm);if(!n)return;const{addListener:r}=n;u.useEffect(()=>r(e,t),[e,t,r])}const Yr="suveren-theme",iu="hap-theme";function Bs(e){return e!=="system"?e:window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}(function(){const t=localStorage.getItem(iu);t!==null&&localStorage.getItem(Yr)===null&&localStorage.setItem(Yr,t),t!==null&&localStorage.removeItem(iu)})();function am(){const[e,t]=u.useState(()=>{const o=localStorage.getItem(Yr);return o==="light"||o==="dark"?o:"system"}),[n,r]=u.useState(()=>Bs(e));u.useEffect(()=>{const o=document.documentElement,i=Bs(e);o.setAttribute("data-theme",i),e==="system"?localStorage.removeItem(Yr):localStorage.setItem(Yr,e),r(Bs(e))},[e]),u.useEffect(()=>{if(e!=="system")return;const o=window.matchMedia("(prefers-color-scheme: dark)"),i=()=>r(Bs("system"));return o.addEventListener("change",i),()=>o.removeEventListener("change",i)},[e]);const a=u.useCallback(()=>{t(o=>o==="system"?"light":o==="light"?"dark":"system")},[]);return{theme:e,effectiveTheme:n,toggle:a}}const Uy=5*60*1e3,Wy=2e3;function Ol(){const[e,t]=u.useState(!1),[n,r]=u.useState("docker"),[a,o]=u.useState(""),[i,l]=u.useState(null),[c,d]=u.useState(!1),[f,p]=u.useState(!1),[m,w]=u.useState(!1),v=u.useRef(null);return u.useEffect(()=>{let x=!1;const k=(y=!1)=>{fetch(y?"/health?refresh=1":"/health").then(S=>S.json()).then(S=>{x||(S.installMethod&&r(S.installMethod),typeof S.latestVersion<"u"&&l(S.latestVersion),S.updateAvailable&&t(!0),S.version&&(o(S.version),v.current===null?v.current=S.version:S.version!==v.current&&S.version!=="dev"&&d(!0)))}).catch(()=>{})};k(!0);const g=setInterval(()=>k(!1),m?Wy:Uy),h=()=>{document.visibilityState==="visible"&&k(!1)};return document.addEventListener("visibilitychange",h),window.addEventListener("focus",h),()=>{x=!0,clearInterval(g),document.removeEventListener("visibilitychange",h),window.removeEventListener("focus",h)}},[m]),{updateAvailable:e&&!f,installMethod:n,version:a,latestVersion:i,serverRestarted:c,startFastPolling:()=>w(!0),dismiss:()=>p(!0)}}function Hy({size:e=20}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 128 128",fill:"none","aria-hidden":"true",focusable:"false",children:[s.jsx("path",{d:"M 104.6 58.29 A 41 41 0 1 1 48.64 25.99",stroke:"currentColor",strokeWidth:"15",strokeLinecap:"round"}),s.jsx("line",{x1:"73.24",y1:"21.99",x2:"95.76",y2:"34.99",stroke:"currentColor",strokeWidth:"15",strokeLinecap:"round"})]})}function Vy(e){return e?e==="dev"?"dev":/^[0-9a-f]{40}$/i.test(e)?e.slice(0,7):e:""}const lu={system:"◑",light:"☀",dark:"☾"};function Bl({onMenuToggle:e}){const{user:t,logout:n}=Fe(),{theme:r,toggle:a}=am(),{version:o,updateAvailable:i,latestVersion:l}=Ol(),c=Vy(o);return s.jsx("nav",{className:"top-nav",children:s.jsxs("div",{className:"top-nav-inner",children:[s.jsxs("div",{className:"logo-group",children:[s.jsx(Hy,{size:20}),s.jsx("span",{className:"logo",children:"Suveren"}),s.jsx("span",{className:"version-badge",children:"Local Gateway"}),c&&s.jsxs("span",{className:"gw-version",title:i&&l?`Running v${c} — v${l} is available`:"Running gateway version","data-stale":i?"true":void 0,children:["v",c,i&&l?` → ${l}`:""]})]}),s.jsx("div",{className:"nav-spacer"}),s.jsx("div",{className:"nav-actions nav-actions-desktop",children:t?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"user-chip",children:s.jsx("strong",{children:t.name})}),s.jsx("button",{className:"theme-toggle",onClick:a,title:`Theme: ${r}`,children:lu[r]}),s.jsx("button",{className:"nav-logout",onClick:n,children:"Logout"})]}):s.jsx("button",{className:"theme-toggle",onClick:a,title:`Theme: ${r}`,children:lu[r]})}),t&&e&&s.jsx("button",{className:"mobile-menu-btn",onClick:e,"aria-label":"Menu",children:"☰"})]})})}function Dl(e,t){var n;if((n=t==null?void 0:t.revokedSet)!=null&&n.has(e.authorization_id))return"revoked";switch(e.sp_status){case"revoked":return"revoked";case"expired":return"expired";case"active":return"active";case"pending":return"pending"}return e.remaining_seconds===null||e.remaining_seconds<=0?"expired":e.missing_domains.length>0?"pending":"active"}function om(e){return e==="expired"||e==="revoked"}function im(e,t){var n;return!!((n=t==null?void 0:t.archivedSet)!=null&&n.has(e.authorization_id))&&om(Dl(e,t))}function Pa(e,t){return im(e,t)?"archived":Dl(e,t)}function lm(e,t){const n={active:[],pending:[],expired:[],revoked:[],archived:[]};for(const r of e)n[Pa(r,t)].push(r);return n}function Gy(e,t){return t==="expired"?e.earliest_expiry?{iso:e.earliest_expiry,meaning:"expired"}:null:e.created_at?{iso:e.created_at,meaning:"created"}:null}function Pt(e,t,n){const r=u.useRef(e);r.current=e,u.useEffect(()=>{let a=null;const o=()=>typeof document>"u"?!0:document.visibilityState==="visible",i=()=>{o()&&r.current()},l=()=>{a===null&&(a=setInterval(i,t))},c=()=>{a!==null&&(clearInterval(a),a=null)},d=()=>{o()?(r.current(),l()):c()};return o()&&(r.current(),l()),document.addEventListener("visibilitychange",d),()=>{c(),document.removeEventListener("visibilitychange",d)}},[t,n])}const cm=u.createContext(null),Ky=3e4,Yy=5e3,Qy=3e5;function Jy(e,t,n){return t===0?"loading":e!=null&&e.running?"running":e!=null&&e.paused?"paused":e!=null&&e.error?"error":e&&n?"starting":"not-running"}function Xy({children:e}){const[t,n]=u.useState({manifests:[],integrations:[],activeSessions:0,mcpServerUp:null,manifestsError:!1,fetchCount:0,authHealth:{}}),r=u.useRef(null),a=u.useCallback(async()=>{let d=!1;const[f,p]=await Promise.all([T.getIntegrationManifests().catch(()=>(d=!0,{manifests:[]})),T.getMcpHealth().catch(()=>null)]);n(w=>({...w,manifests:f.manifests,integrations:(p==null?void 0:p.integrations)??w.integrations,activeSessions:(p==null?void 0:p.activeSessions)??w.activeSessions,mcpServerUp:!!p,manifestsError:d,fetchCount:w.fetchCount+1}));const m=f.manifests.filter(w=>w.oauth);if(m.length>0){const w=await Promise.all(m.map(async v=>[v.id,await T.getOAuthHealth(v.id)]));n(v=>({...v,authHealth:Object.fromEntries(w)}))}},[]),o=t.fetchCount>0&&t.manifests.some(d=>{const f=t.integrations.find(p=>p.id===d.id);return f&&!f.running&&!f.paused});fe("integration-changed",a),Pt(a,o?Yy:Qy);const i=u.useMemo(()=>{const d=new Map(t.integrations.map(m=>[m.id,m])),f=Date.now();o&&r.current===null?r.current=f:o||(r.current=null);const p=r.current!==null&&f-r.current<Ky;return t.manifests.map(m=>{const w=d.get(m.id),v=Jy(w,t.fetchCount,p),x=t.authHealth[m.id];return{id:m.id,manifest:m,integration:w,state:v,authStatus:x==null?void 0:x.status,authAccount:x==null?void 0:x.account,authError:x==null?void 0:x.error}})},[t,o]),l=u.useMemo(()=>i.filter(d=>d.state==="not-running"||d.state==="error"||d.authStatus==="failed").length,[i]),c={loading:t.fetchCount===0,mcpServerUp:t.mcpServerUp,manifestsError:t.manifestsError,entries:i,attentionCount:l,activeSessions:t.activeSessions,refresh:a};return s.jsx(cm.Provider,{value:c,children:e})}function Ul(){const e=u.useContext(cm);if(!e)throw new Error("useIntegrationStatus must be used inside IntegrationStatusProvider");return e}const qy=[{to:"/",icon:"□",label:"Dashboard"},{to:"/approvals",icon:"▷",label:"Pending Approvals",statusKey:"proposals"},{to:"/mandates",icon:"☰",label:"Mandates",statusKey:"authorizations"},{to:"/agent-brief",icon:"▤",label:"Agent Brief",statusKey:"brief"},{to:"/tickets",icon:"▣",label:"Tickets"},{to:"/team",icon:"◉",label:"Team",teamOnly:!0},{to:"/integrations",icon:"⧗",label:"Integrations",statusKey:"integrations"},{to:"/settings",icon:"⚙",label:"Settings",statusKey:"assistant"}];function Zy(){const{activeDomain:e}=Fe(),[t,n]=u.useState({}),r=u.useCallback(async()=>{try{const[a,o,i,l,c,d]=await Promise.all([T.getCredential("ai-config").catch(()=>null),T.getMyAttestations().catch(()=>null),T.getProposals(e||"owner").catch(()=>null),T.getProposalsForApprover().catch(()=>null),T.getAgentContext().catch(()=>""),T.getArchivedMandates().catch(()=>[])]),f={};if(a&&!a.configured&&(f.assistant=1),o){const v=lm(o,{archivedSet:new Set(d)}).expired.length;v>0&&(f.authorizations=v)}const p=(i==null?void 0:i.length)??0,m=(l==null?void 0:l.length)??0,w=p+m;w>0&&(f.proposals=w),(!c||!c.trim())&&(f.brief=1),n(f)}catch{}},[e]);return fe("attestation-changed",r),fe("proposal-added",r),fe("proposal-resolved",r),fe("proposal-approved",r),fe("proposal-rejected",r),fe("team-membership-changed",r),u.useEffect(()=>(window.addEventListener("suveren:archived-changed",r),()=>window.removeEventListener("suveren:archived-changed",r)),[r]),Pt(r,3e5,e),t}const ev={marginLeft:"auto",minWidth:"1.25rem",height:"1.25rem",padding:"0 0.375rem",borderRadius:"0.625rem",background:"var(--warning)",color:"var(--bg-elevated)",fontSize:"0.7rem",fontWeight:600,display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0},tv={position:"fixed",bottom:"1.5rem",left:"50%",transform:"translateX(-50%)",background:"var(--bg-elevated, #1e1e2e)",color:"var(--text-primary, #e2e8f0)",border:"1px solid var(--border)",borderRadius:"0.5rem",padding:"0.625rem 1rem",fontSize:"0.85rem",boxShadow:"0 4px 16px rgba(0,0,0,0.3)",zIndex:9999,whiteSpace:"nowrap",pointerEvents:"none"};function nv(){const{mode:e,group:t,domain:n,activeTeam:r}=Fe(),a=Zy(),{attentionCount:o}=Ul(),i={...a};o>0&&(i.integrations=o);const l=qy.filter(m=>!m.teamOnly||e==="team"),c=u.useRef(null),[d,f]=u.useState(null),p=gt();return u.useEffect(()=>{if(c.current===null){c.current=e;return}c.current!==e&&(e==="team"&&r?f(`You are now acting in team context — ${r.name}`):e==="personal"&&f("You have left the team — back to personal context"),c.current=e)},[e,r]),u.useEffect(()=>{f(null)},[p.pathname]),s.jsxs("div",{className:"sidebar",children:[s.jsx("ul",{className:"sidebar-nav",children:l.map(m=>{const w=m.statusKey?i[m.statusKey]:0;return s.jsx("li",{children:s.jsxs(Fl,{to:m.to,end:m.to==="/",className:({isActive:v})=>`sidebar-item${v?" active":""}`,children:[s.jsx("span",{className:"icon",children:m.icon}),m.label,w?s.jsx("span",{style:ev,children:w}):null]})},m.to)})}),s.jsxs("div",{className:"sidebar-context",children:[s.jsx("div",{className:"ctx-label",children:"Active context"}),s.jsx("div",{className:"ctx-value",children:e==="personal"?"personal":t?`${t.name} / ${n}`:n})]}),d&&s.jsx("div",{style:tv,role:"status","aria-live":"polite",children:d})]})}const Po="suveren:updatedTo";function rv(e){return e==="managed"?null:e==="npm"?"npm install -g @suveren/gateway@latest && suveren-gateway restart":e==="dev"?"git pull && pnpm install":"docker rm -f suveren-gateway 2>/dev/null; docker ps -q --filter publish=7400 --filter publish=7430 | xargs -r docker rm -f; docker pull ghcr.io/suverenai/suveren-gateway:latest && docker run -d --name suveren-gateway -p 7400:3000 -p 7430:3030 -v $HOME/.suveren:/app/data ghcr.io/suverenai/suveren-gateway"}const sv="Updates for this gateway come from your company's IT — no action needed here.";function av(e){return e==="managed"?"update-banner is-managed":"update-banner"}function ov(){const e=document.querySelectorAll('[role="dialog"], .modal-overlay, .modal');for(const n of e)if(!n.closest(".update-overlay"))return!0;const t=document.activeElement;if(t&&(t.tagName==="INPUT"||t.tagName==="TEXTAREA"||t.isContentEditable)){const n=t.value;if(n&&n.trim())return!0}return!1}function um(){const{updateAvailable:e,installMethod:t,version:n,latestVersion:r,serverRestarted:a,startFastPolling:o,dismiss:i}=Ol(),[l,c]=u.useState(!1),[d,f]=u.useState(!1),[p,m]=u.useState(()=>{try{const y=sessionStorage.getItem(Po);if(y)return sessionStorage.removeItem(Po),y}catch{}return null}),w=rv(t),v=u.useRef(null),x=y=>{try{sessionStorage.setItem(Po,y||r||"✓")}catch{}window.location.reload()};u.useEffect(()=>{if(!p)return;const y=setTimeout(()=>m(null),6e3);return()=>clearTimeout(y)},[p]),u.useEffect(()=>{if(!l||!a)return;const y=()=>ov()?!1:(x(n),!0);if(y())return;const S=setInterval(y,1500);return()=>clearInterval(S)},[l,a,n]),u.useEffect(()=>(document.body.classList.toggle("is-updating",l),()=>document.body.classList.remove("is-updating")),[l]);const k=e&&!l&&!p||!!p&&!l;u.useEffect(()=>{if(!k){document.documentElement.style.removeProperty("--update-banner-h"),document.body.classList.remove("has-update-banner");return}document.body.classList.add("has-update-banner");const y=()=>{var N;const b=((N=v.current)==null?void 0:N.offsetHeight)??0;document.documentElement.style.setProperty("--update-banner-h",`${b}px`)};y();const S=new ResizeObserver(y);return v.current&&S.observe(v.current),()=>{S.disconnect(),document.documentElement.style.removeProperty("--update-banner-h"),document.body.classList.remove("has-update-banner")}},[k]);const g=()=>{c(!0),o()},h=async()=>{if(w)try{await navigator.clipboard.writeText(w),f(!0),setTimeout(()=>f(!1),1800)}catch{}};return s.jsxs(s.Fragment,{children:[p&&!l&&s.jsx("div",{ref:v,className:"update-banner is-live",role:"status","aria-live":"polite",children:s.jsxs("div",{className:"update-banner-row",children:[s.jsxs("span",{className:"update-banner-text",children:["✓"," You","’","re on the latest version",p&&p!=="✓"?` — ${p} is live`:" — now live","."]}),s.jsx("button",{className:"update-banner-x",onClick:()=>m(null),"aria-label":"Dismiss",children:"×"})]})}),e&&!l&&!p&&s.jsxs("div",{ref:v,className:av(t),role:"status","aria-live":"polite",children:[s.jsxs("div",{className:"update-banner-row",children:[s.jsx("span",{className:"update-banner-text",children:"Update available."}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem",alignItems:"center"},children:[t!=="managed"&&s.jsx("button",{className:"btn btn-sm btn-secondary",onClick:g,children:"Update"}),s.jsx("button",{className:"update-banner-x",onClick:i,"aria-label":"Dismiss",children:"×"})]})]}),t==="managed"&&s.jsx("p",{className:"update-banner-hint",children:sv})]}),l&&s.jsx("div",{className:"update-overlay",children:s.jsxs("div",{className:"update-overlay-card",role:"dialog","aria-modal":"true","aria-label":"Finishing the update",children:[s.jsx("div",{className:"update-spinner"}),s.jsxs("h2",{children:["Finishing the update","…"]}),s.jsxs("p",{children:["Copy this command and run it in your terminal. The gateway will restart, and"," ",s.jsx("strong",{children:"this page updates automatically"})," when it comes back ","—"," no need to refresh."]}),s.jsxs("div",{className:"update-cmd-row",children:[s.jsx("code",{className:"update-cmd",children:w}),s.jsx("button",{className:"btn btn-sm btn-primary",onClick:h,children:d?"Copied":"Copy"})]}),s.jsxs("div",{className:"update-status",children:[s.jsx("span",{className:"update-pulse"})," Waiting for the gateway to restart","…"]}),s.jsxs("div",{className:"update-overlay-actions",children:[s.jsx("button",{className:"btn btn-primary",onClick:()=>x(n),children:"Reload now"}),s.jsx("button",{className:"btn btn-secondary",onClick:()=>c(!1),children:"Cancel"})]})]})})]})}function dm(){const[e,t]=u.useState(!1);return u.useEffect(()=>{let n=!1;const r=()=>{fetch("/health").then(i=>i.json()).then(i=>{n||t(i.simulation===!0)}).catch(()=>{})};r();const a=setInterval(r,3e4),o=()=>{document.visibilityState==="visible"&&r()};return document.addEventListener("visibilitychange",o),()=>{n=!0,clearInterval(a),document.removeEventListener("visibilitychange",o)}},[]),e}function fm(){const e=dm(),t=u.useRef(null);return u.useEffect(()=>{if(!e){document.documentElement.style.removeProperty("--sim-banner-h");return}const n=()=>{var o;const a=((o=t.current)==null?void 0:o.offsetHeight)??0;document.documentElement.style.setProperty("--sim-banner-h",`${a}px`)};n();const r=new ResizeObserver(n);return t.current&&r.observe(t.current),()=>{r.disconnect(),document.documentElement.style.removeProperty("--sim-banner-h")}},[e]),e?s.jsx("div",{ref:t,className:"simulation-banner",role:"status","aria-live":"polite",children:s.jsx("span",{className:"simulation-banner-text",children:"Simulation mode — real systems are blocked."})}):null}const iv={system:"◑",light:"☀",dark:"☾"},lv=[{to:"/",icon:"□",label:"Dashboard"},{to:"/approvals",icon:"▷",label:"Pending Approvals"},{to:"/mandates",icon:"☰",label:"Mandates"},{to:"/agent-brief",icon:"▤",label:"Agent Brief"},{to:"/tickets",icon:"▣",label:"Tickets"},{to:"/team",icon:"◉",label:"Team"},{to:"/integrations",icon:"⧗",label:"Integrations"},{to:"/settings",icon:"⚙",label:"Settings"}];function cv({open:e,onClose:t}){const{user:n,activeGroup:r,activeDomain:a,logout:o}=Fe(),{theme:i,toggle:l}=am(),c=gt();return u.useEffect(()=>{t()},[c.pathname]),e?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"mobile-menu-backdrop",onClick:t}),s.jsxs("div",{className:"mobile-menu-panel",children:[n&&s.jsxs("div",{className:"mobile-menu-header",children:[s.jsx("strong",{children:n.name}),s.jsx("span",{style:{fontSize:"0.8rem",color:"var(--text-secondary)"},children:r?`${r.name} / ${a}`:a||"personal"})]}),s.jsx("nav",{className:"mobile-menu-nav",children:lv.map(d=>s.jsxs(Fl,{to:d.to,end:d.to==="/",className:({isActive:f})=>`mobile-menu-item${f?" active":""}`,onClick:t,children:[s.jsx("span",{className:"icon",children:d.icon}),d.label]},d.to))}),s.jsxs("div",{className:"mobile-menu-footer",children:[s.jsxs("button",{className:"mobile-menu-action",onClick:()=>{l()},children:[s.jsx("span",{className:"icon",children:iv[i]}),"Theme: ",i]}),s.jsx("button",{className:"mobile-menu-action",onClick:()=>{o(),t()},children:"Logout"})]})]})]}):null}function mm(e){return e.status==="pending"}function uv(e,t){return e.filter(mm).length+t.length}const Cn=["proposal-added","proposal-resolved","proposal-approved","proposal-rejected","action-approval-needed","action-resolved","team-membership-changed"],dv=500;function pm(){const{user:e,domain:t}=Fe(),[n,r]=u.useState(0),a=u.useRef(null),o=u.useCallback(async()=>{if(!e){r(0);return}try{const[l,c]=await Promise.all([T.getProposals(t||"owner").catch(()=>[]),T.getProposalsForApprover().catch(()=>[])]);r(uv(l,c))}catch{r(0)}},[e,t]),i=u.useCallback(()=>{a.current&&clearTimeout(a.current),a.current=setTimeout(()=>{o()},dv)},[o]);return u.useEffect(()=>(o(),()=>{a.current&&clearTimeout(a.current)}),[o]),fe(Cn[0],i),fe(Cn[1],i),fe(Cn[2],i),fe(Cn[3],i),fe(Cn[4],i),fe(Cn[5],i),fe(Cn[6],i),n}const cu="Suveren",fv="/favicon.svg",mv="M 104.94 61.85 A 41 41 0 1 1 45.39 27.47",Ds={x1:74.54,y1:22.74,x2:94.46,y2:34.24},pv=14,hv="#f59e0b";function gv(e){const t=Wl(e);return t>0?`(${t}) ${cu}`:cu}function Wl(e){return Number.isFinite(e)&&e>0?Math.floor(e):0}function yv(){const e=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128" fill="none">
52
- <path class="m" d="${mv}"/>
51
+ Please change the parent <Route path="${g}"> to <Route path="${g==="/"?"*":`${g}/*`}">.`)}let f=gt(),p;if(t){let g=typeof t=="string"?vr(t):t;ke(c==="/"||((k=g.pathname)==null?void 0:k.startsWith(c)),`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 "${c}" but pathname "${g.pathname}" was given in the \`location\` prop.`),p=g}else p=f;let m=p.pathname||"/",w=m;if(c!=="/"){let g=c.replace(/^\//,"").split("/");w="/"+m.replace(/^\//,"").split("/").slice(g.length).join("/")}let v=Ff(e,{pathname:w});Ct(d||v!=null,`No routes matched location "${p.pathname}${p.search}${p.hash}" `),Ct(v==null||v[v.length-1].route.element!==void 0||v[v.length-1].route.Component!==void 0||v[v.length-1].route.lazy!==void 0,`Matched leaf route at location "${p.pathname}${p.search}${p.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 x=Qg(v&&v.map(g=>Object.assign({},g,{params:Object.assign({},i,g.params),pathname:Dt([c,r.encodeLocation?r.encodeLocation(g.pathname.replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:g.pathname]),pathnameBase:g.pathnameBase==="/"?c:Dt([c,r.encodeLocation?r.encodeLocation(g.pathnameBase.replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:g.pathnameBase])})),a,n);return t&&x?u.createElement(vs.Provider,{value:{location:{pathname:"/",search:"",hash:"",state:null,key:"default",unstable_mask:void 0,...p},navigationType:"POP"}},x):x}function Vg(){let e=ey(),t=Rg(e)?`${e.status} ${e.statusText}`:e instanceof Error?e.message:JSON.stringify(e),n=e instanceof Error?e.stack:null,r="rgba(200,200,200, 0.5)",a={padding:"0.5rem",backgroundColor:r},o={padding:"2px 4px",backgroundColor:r},i=null;return console.error("Error handled by React Router default ErrorBoundary:",e),i=u.createElement(u.Fragment,null,u.createElement("p",null,"💿 Hey developer 👋"),u.createElement("p",null,"You can provide a way better UX than this when your app throws errors by providing your own ",u.createElement("code",{style:o},"ErrorBoundary")," or"," ",u.createElement("code",{style:o},"errorElement")," prop on your route.")),u.createElement(u.Fragment,null,u.createElement("h2",null,"Unexpected Application Error!"),u.createElement("h3",{style:{fontStyle:"italic"}},t),n?u.createElement("pre",{style:a},n):null,i)}var Gg=u.createElement(Vg,null),Qf=class extends u.Component{constructor(e){super(e),this.state={location:e.location,revalidation:e.revalidation,error:e.error}}static getDerivedStateFromError(e){return{error:e}}static getDerivedStateFromProps(e,t){return t.location!==e.location||t.revalidation!=="idle"&&e.revalidation==="idle"?{error:e.error,location:e.location,revalidation:e.revalidation}:{error:e.error!==void 0?e.error:t.error,location:t.location,revalidation:e.revalidation||t.revalidation}}componentDidCatch(e,t){this.props.onError?this.props.onError(e,t):console.error("React Router caught the following error during render",e)}render(){let e=this.state.error;if(this.context&&typeof e=="object"&&e&&"digest"in e&&typeof e.digest=="string"){const n=Og(e.digest);n&&(e=n)}let t=e!==void 0?u.createElement($t.Provider,{value:this.props.routeContext},u.createElement(Al.Provider,{value:e,children:this.props.component})):this.props.children;return this.context?u.createElement(Kg,{error:e},t):t}};Qf.contextType=Ag;var Io=new WeakMap;function Kg({children:e,error:t}){let{basename:n}=u.useContext(ht);if(typeof t=="object"&&t&&"digest"in t&&typeof t.digest=="string"){let r=Fg(t.digest);if(r){let a=Io.get(t);if(a)throw a;let o=Uf(r.location,n);if(Df&&!Io.get(t))if(o.isExternal||r.reloadDocument)window.location.href=o.absoluteURL||o.to;else{const i=Promise.resolve().then(()=>window.__reactRouterDataRouter.navigate(o.to,{replace:r.replace}));throw Io.set(t,i),i}return u.createElement("meta",{httpEquiv:"refresh",content:`0;url=${o.absoluteURL||o.to}`})}}return e}function Yg({routeContext:e,match:t,children:n}){let r=u.useContext(xr);return r&&r.static&&r.staticContext&&(t.route.errorElement||t.route.ErrorBoundary)&&(r.staticContext._deepestRenderedBoundaryId=t.route.id),u.createElement($t.Provider,{value:e},n)}function Qg(e,t=[],n){let r=n==null?void 0:n.state;if(e==null){if(!r)return null;if(r.errors)e=r.matches;else if(t.length===0&&!r.initialized&&r.matches.length>0)e=r.matches;else return null}let a=e,o=r==null?void 0:r.errors;if(o!=null){let f=a.findIndex(p=>p.route.id&&(o==null?void 0:o[p.route.id])!==void 0);ke(f>=0,`Could not find a matching route for errors on route IDs: ${Object.keys(o).join(",")}`),a=a.slice(0,Math.min(a.length,f+1))}let i=!1,l=-1;if(n&&r){i=r.renderFallback;for(let f=0;f<a.length;f++){let p=a[f];if((p.route.HydrateFallback||p.route.hydrateFallbackElement)&&(l=f),p.route.id){let{loaderData:m,errors:w}=r,v=p.route.loader&&!m.hasOwnProperty(p.route.id)&&(!w||w[p.route.id]===void 0);if(p.route.lazy||v){n.isStatic&&(i=!0),l>=0?a=a.slice(0,l+1):a=[a[0]];break}}}}let c=n==null?void 0:n.onError,d=r&&c?(f,p)=>{var m,w;c(f,{location:r.location,params:((w=(m=r.matches)==null?void 0:m[0])==null?void 0:w.params)??{},unstable_pattern:Pg(r.matches),errorInfo:p})}:void 0;return a.reduceRight((f,p,m)=>{let w,v=!1,x=null,k=null;r&&(w=o&&p.route.id?o[p.route.id]:void 0,x=p.route.errorElement||Gg,i&&(l<0&&m===0?(Jf("route-fallback",!1,"No `HydrateFallback` element provided to render during initial hydration"),v=!0,k=null):l===m&&(v=!0,k=p.route.hydrateFallbackElement||null)));let g=t.concat(a.slice(0,m+1)),h=()=>{let y;return w?y=x:v?y=k:p.route.Component?y=u.createElement(p.route.Component,null):p.route.element?y=p.route.element:y=f,u.createElement(Yg,{match:p,routeContext:{outlet:f,matches:g,isDataRoute:r!=null},children:y})};return r&&(p.route.ErrorBoundary||p.route.errorElement||m===0)?u.createElement(Qf,{location:r.location,revalidation:r.revalidation,component:x,error:w,children:h(),routeContext:{outlet:null,matches:g,isDataRoute:!0},onError:d}):h()},null)}function zl(e){return`${e} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function Jg(e){let t=u.useContext(xr);return ke(t,zl(e)),t}function Xg(e){let t=u.useContext(Xa);return ke(t,zl(e)),t}function qg(e){let t=u.useContext($t);return ke(t,zl(e)),t}function $l(e){let t=qg(e),n=t.matches[t.matches.length-1];return ke(n.route.id,`${e} can only be used on routes that contain a unique "id"`),n.route.id}function Zg(){return $l("useRouteId")}function ey(){var r;let e=u.useContext(Al),t=Xg("useRouteError"),n=$l("useRouteError");return e!==void 0?e:(r=t.errors)==null?void 0:r[n]}function ty(){let{router:e}=Jg("useNavigate"),t=$l("useNavigate"),n=u.useRef(!1);return Kf(()=>{n.current=!0}),u.useCallback(async(a,o={})=>{Ct(n.current,Gf),n.current&&(typeof a=="number"?await e.navigate(a):await e.navigate(a,{fromRouteId:t,...o}))},[e,t])}var au={};function Jf(e,t,n){!t&&!au[e]&&(au[e]=!0,Ct(!1,n))}u.memo(ny);function ny({routes:e,future:t,state:n,isStatic:r,onError:a}){return Yf(e,void 0,{state:n,isStatic:r,onError:a})}function Gt({to:e,replace:t,state:n,relative:r}){ke(wr(),"<Navigate> may be used only in the context of a <Router> component.");let{static:a}=u.useContext(ht);Ct(!a,"<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:o}=u.useContext($t),{pathname:i}=gt(),l=nn(),c=Ja(e,_l(o),i,r==="path"),d=JSON.stringify(c);return u.useEffect(()=>{l(JSON.parse(d),{replace:t,state:n,relative:r})},[l,d,r,t,n]),null}function ry(e){return Wg(e.context)}function Se(e){ke(!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 sy({basename:e="/",children:t=null,location:n,navigationType:r="POP",navigator:a,static:o=!1,unstable_useTransitions:i}){ke(!wr(),"You cannot render a <Router> inside another <Router>. You should never have more than one in your app.");let l=e.replace(/^\/*/,"/"),c=u.useMemo(()=>({basename:l,navigator:a,static:o,unstable_useTransitions:i,future:{}}),[l,a,o,i]);typeof n=="string"&&(n=vr(n));let{pathname:d="/",search:f="",hash:p="",state:m=null,key:w="default",unstable_mask:v}=n,x=u.useMemo(()=>{let k=en(d,l);return k==null?null:{location:{pathname:k,search:f,hash:p,state:m,key:w,unstable_mask:v},navigationType:r}},[l,d,f,p,m,w,r,v]);return Ct(x!=null,`<Router basename="${l}"> is not able to match the URL "${d}${f}${p}" because it does not start with the basename, so the <Router> won't render anything.`),x==null?null:u.createElement(ht.Provider,{value:c},u.createElement(vs.Provider,{children:t,value:x}))}function ay({children:e,location:t}){return Hg(Ii(e),t)}function Ii(e,t=[]){let n=[];return u.Children.forEach(e,(r,a)=>{if(!u.isValidElement(r))return;let o=[...t,a];if(r.type===u.Fragment){n.push.apply(n,Ii(r.props.children,o));return}ke(r.type===Se,`[${typeof r.type=="string"?r.type:r.type.name}] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>`),ke(!r.props.index||!r.props.children,"An index route cannot have child routes.");let i={id:r.props.id||o.join("-"),caseSensitive:r.props.caseSensitive,element:r.props.element,Component:r.props.Component,index:r.props.index,path:r.props.path,middleware:r.props.middleware,loader:r.props.loader,action:r.props.action,hydrateFallbackElement:r.props.hydrateFallbackElement,HydrateFallback:r.props.HydrateFallback,errorElement:r.props.errorElement,ErrorBoundary:r.props.ErrorBoundary,hasErrorBoundary:r.props.hasErrorBoundary===!0||r.props.ErrorBoundary!=null||r.props.errorElement!=null,shouldRevalidate:r.props.shouldRevalidate,handle:r.props.handle,lazy:r.props.lazy};r.props.children&&(i.children=Ii(r.props.children,o)),n.push(i)}),n}var na="get",ra="application/x-www-form-urlencoded";function qa(e){return typeof HTMLElement<"u"&&e instanceof HTMLElement}function oy(e){return qa(e)&&e.tagName.toLowerCase()==="button"}function iy(e){return qa(e)&&e.tagName.toLowerCase()==="form"}function ly(e){return qa(e)&&e.tagName.toLowerCase()==="input"}function cy(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}function uy(e,t){return e.button===0&&(!t||t==="_self")&&!cy(e)}function Ri(e=""){return new URLSearchParams(typeof e=="string"||Array.isArray(e)||e instanceof URLSearchParams?e:Object.keys(e).reduce((t,n)=>{let r=e[n];return t.concat(Array.isArray(r)?r.map(a=>[n,a]):[[n,r]])},[]))}function dy(e,t){let n=Ri(e);return t&&t.forEach((r,a)=>{n.has(a)||t.getAll(a).forEach(o=>{n.append(a,o)})}),n}var Os=null;function fy(){if(Os===null)try{new FormData(document.createElement("form"),0),Os=!1}catch{Os=!0}return Os}var my=new Set(["application/x-www-form-urlencoded","multipart/form-data","text/plain"]);function Ro(e){return e!=null&&!my.has(e)?(Ct(!1,`"${e}" is not a valid \`encType\` for \`<Form>\`/\`<fetcher.Form>\` and will default to "${ra}"`),null):e}function py(e,t){let n,r,a,o,i;if(iy(e)){let l=e.getAttribute("action");r=l?en(l,t):null,n=e.getAttribute("method")||na,a=Ro(e.getAttribute("enctype"))||ra,o=new FormData(e)}else if(oy(e)||ly(e)&&(e.type==="submit"||e.type==="image")){let l=e.form;if(l==null)throw new Error('Cannot submit a <button> or <input type="submit"> without a <form>');let c=e.getAttribute("formaction")||l.getAttribute("action");if(r=c?en(c,t):null,n=e.getAttribute("formmethod")||l.getAttribute("method")||na,a=Ro(e.getAttribute("formenctype"))||Ro(l.getAttribute("enctype"))||ra,o=new FormData(l,e),!fy()){let{name:d,type:f,value:p}=e;if(f==="image"){let m=d?`${d}.`:"";o.append(`${m}x`,"0"),o.append(`${m}y`,"0")}else d&&o.append(d,p)}}else{if(qa(e))throw new Error('Cannot submit element that is not <form>, <button>, or <input type="submit|image">');n=na,r=null,a=ra,i=e}return o&&a==="text/plain"&&(i=o,o=void 0),{action:r,method:n.toLowerCase(),encType:a,formData:o,body:i}}Object.getOwnPropertyNames(Object.prototype).sort().join("\0");function Ll(e,t){if(e===!1||e===null||typeof e>"u")throw new Error(t)}function hy(e,t,n,r){let a=typeof e=="string"?new URL(e,typeof window>"u"?"server://singlefetch/":window.location.origin):e;return n?a.pathname.endsWith("/")?a.pathname=`${a.pathname}_.${r}`:a.pathname=`${a.pathname}.${r}`:a.pathname==="/"?a.pathname=`_root.${r}`:t&&en(a.pathname,t)==="/"?a.pathname=`${t.replace(/\/$/,"")}/_root.${r}`:a.pathname=`${a.pathname.replace(/\/$/,"")}.${r}`,a}async function gy(e,t){if(e.id in t)return t[e.id];try{let n=await import(e.module);return t[e.id]=n,n}catch(n){return console.error(`Error loading route module \`${e.module}\`, reloading page...`),console.error(n),window.__reactRouterContext&&window.__reactRouterContext.isSpaMode,window.location.reload(),new Promise(()=>{})}}function yy(e){return e==null?!1:e.href==null?e.rel==="preload"&&typeof e.imageSrcSet=="string"&&typeof e.imageSizes=="string":typeof e.rel=="string"&&typeof e.href=="string"}async function vy(e,t,n){let r=await Promise.all(e.map(async a=>{let o=t.routes[a.route.id];if(o){let i=await gy(o,n);return i.links?i.links():[]}return[]}));return jy(r.flat(1).filter(yy).filter(a=>a.rel==="stylesheet"||a.rel==="preload").map(a=>a.rel==="stylesheet"?{...a,rel:"prefetch",as:"style"}:{...a,rel:"prefetch"}))}function ou(e,t,n,r,a,o){let i=(c,d)=>n[d]?c.route.id!==n[d].route.id:!0,l=(c,d)=>{var f;return n[d].pathname!==c.pathname||((f=n[d].route.path)==null?void 0:f.endsWith("*"))&&n[d].params["*"]!==c.params["*"]};return o==="assets"?t.filter((c,d)=>i(c,d)||l(c,d)):o==="data"?t.filter((c,d)=>{var p;let f=r.routes[c.route.id];if(!f||!f.hasLoader)return!1;if(i(c,d)||l(c,d))return!0;if(c.route.shouldRevalidate){let m=c.route.shouldRevalidate({currentUrl:new URL(a.pathname+a.search+a.hash,window.origin),currentParams:((p=n[0])==null?void 0:p.params)||{},nextUrl:new URL(e,window.origin),nextParams:c.params,defaultShouldRevalidate:!0});if(typeof m=="boolean")return m}return!0}):[]}function xy(e,t,{includeHydrateFallback:n}={}){return wy(e.map(r=>{let a=t.routes[r.route.id];if(!a)return[];let o=[a.module];return a.clientActionModule&&(o=o.concat(a.clientActionModule)),a.clientLoaderModule&&(o=o.concat(a.clientLoaderModule)),n&&a.hydrateFallbackModule&&(o=o.concat(a.hydrateFallbackModule)),a.imports&&(o=o.concat(a.imports)),o}).flat(1))}function wy(e){return[...new Set(e)]}function Sy(e){let t={},n=Object.keys(e).sort();for(let r of n)t[r]=e[r];return t}function jy(e,t){let n=new Set;return new Set(t),e.reduce((r,a)=>{let o=JSON.stringify(Sy(a));return n.has(o)||(n.add(o),r.push({key:o,link:a})),r},[])}function Xf(){let e=u.useContext(xr);return Ll(e,"You must render this element inside a <DataRouterContext.Provider> element"),e}function ky(){let e=u.useContext(Xa);return Ll(e,"You must render this element inside a <DataRouterStateContext.Provider> element"),e}var Ml=u.createContext(void 0);Ml.displayName="FrameworkContext";function qf(){let e=u.useContext(Ml);return Ll(e,"You must render this element inside a <HydratedRouter> element"),e}function by(e,t){let n=u.useContext(Ml),[r,a]=u.useState(!1),[o,i]=u.useState(!1),{onFocus:l,onBlur:c,onMouseEnter:d,onMouseLeave:f,onTouchStart:p}=t,m=u.useRef(null);u.useEffect(()=>{if(e==="render"&&i(!0),e==="viewport"){let x=g=>{g.forEach(h=>{i(h.isIntersecting)})},k=new IntersectionObserver(x,{threshold:.5});return m.current&&k.observe(m.current),()=>{k.disconnect()}}},[e]),u.useEffect(()=>{if(r){let x=setTimeout(()=>{i(!0)},100);return()=>{clearTimeout(x)}}},[r]);let w=()=>{a(!0)},v=()=>{a(!1),i(!1)};return n?e!=="intent"?[o,m,{}]:[o,m,{onFocus:Rr(l,w),onBlur:Rr(c,v),onMouseEnter:Rr(d,w),onMouseLeave:Rr(f,v),onTouchStart:Rr(p,w)}]:[!1,m,{}]}function Rr(e,t){return n=>{e&&e(n),n.defaultPrevented||t(n)}}function Cy({page:e,...t}){let{router:n}=Xf(),r=u.useMemo(()=>Ff(n.routes,e,n.basename),[n.routes,e,n.basename]);return r?u.createElement(Ey,{page:e,matches:r,...t}):null}function Ny(e){let{manifest:t,routeModules:n}=qf(),[r,a]=u.useState([]);return u.useEffect(()=>{let o=!1;return vy(e,t,n).then(i=>{o||a(i)}),()=>{o=!0}},[e,t,n]),r}function Ey({page:e,matches:t,...n}){let r=gt(),{future:a,manifest:o,routeModules:i}=qf(),{basename:l}=Xf(),{loaderData:c,matches:d}=ky(),f=u.useMemo(()=>ou(e,t,d,o,r,"data"),[e,t,d,o,r]),p=u.useMemo(()=>ou(e,t,d,o,r,"assets"),[e,t,d,o,r]),m=u.useMemo(()=>{if(e===r.pathname+r.search+r.hash)return[];let x=new Set,k=!1;if(t.forEach(h=>{var S;let y=o.routes[h.route.id];!y||!y.hasLoader||(!f.some(b=>b.route.id===h.route.id)&&h.route.id in c&&((S=i[h.route.id])!=null&&S.shouldRevalidate)||y.hasClientLoader?k=!0:x.add(h.route.id))}),x.size===0)return[];let g=hy(e,l,a.unstable_trailingSlashAwareDataRequests,"data");return k&&x.size>0&&g.searchParams.set("_routes",t.filter(h=>x.has(h.route.id)).map(h=>h.route.id).join(",")),[g.pathname+g.search]},[l,a.unstable_trailingSlashAwareDataRequests,c,r,o,f,t,e,i]),w=u.useMemo(()=>xy(p,o),[p,o]),v=Ny(p);return u.createElement(u.Fragment,null,m.map(x=>u.createElement("link",{key:x,rel:"prefetch",as:"fetch",href:x,...n})),w.map(x=>u.createElement("link",{key:x,rel:"modulepreload",href:x,...n})),v.map(({key:x,link:k})=>u.createElement("link",{key:x,nonce:n.nonce,...k,crossOrigin:k.crossOrigin??n.crossOrigin})))}function Ty(...e){return t=>{e.forEach(n=>{typeof n=="function"?n(t):n!=null&&(n.current=t)})}}var Iy=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";try{Iy&&(window.__reactRouterVersion="7.13.1")}catch{}function Ry({basename:e,children:t,unstable_useTransitions:n,window:r}){let a=u.useRef();a.current==null&&(a.current=og({window:r,v5Compat:!0}));let o=a.current,[i,l]=u.useState({action:o.action,location:o.location}),c=u.useCallback(d=>{n===!1?l(d):u.startTransition(()=>l(d))},[n]);return u.useLayoutEffect(()=>o.listen(c),[o,c]),u.createElement(sy,{basename:e,children:t,location:i.location,navigationType:i.action,navigator:o,unstable_useTransitions:n})}var Zf=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,Ye=u.forwardRef(function({onClick:t,discover:n="render",prefetch:r="none",relative:a,reloadDocument:o,replace:i,unstable_mask:l,state:c,target:d,to:f,preventScrollReset:p,viewTransition:m,unstable_defaultShouldRevalidate:w,...v},x){let{basename:k,navigator:g,unstable_useTransitions:h}=u.useContext(ht),y=typeof f=="string"&&Zf.test(f),S=Uf(f,k);f=S.to;let b=Bg(f,{relative:a}),N=gt(),C=null;if(l){let _=Ja(l,[],N.unstable_mask?N.unstable_mask.pathname:"/",!0);k!=="/"&&(_.pathname=_.pathname==="/"?k:Dt([k,_.pathname])),C=g.createHref(_)}let[I,E,$]=by(r,v),U=Ay(f,{replace:i,unstable_mask:l,state:c,target:d,preventScrollReset:p,relative:a,viewTransition:m,unstable_defaultShouldRevalidate:w,unstable_useTransitions:h});function V(_){t&&t(_),_.defaultPrevented||U(_)}let J=!(S.isExternal||o),D=u.createElement("a",{...v,...$,href:(J?C:void 0)||S.absoluteURL||b,onClick:J?V:t,ref:Ty(x,E),target:d,"data-discover":!y&&n==="render"?"true":void 0});return I&&!y?u.createElement(u.Fragment,null,D,u.createElement(Cy,{page:b})):D});Ye.displayName="Link";var Fl=u.forwardRef(function({"aria-current":t="page",caseSensitive:n=!1,className:r="",end:a=!1,style:o,to:i,viewTransition:l,children:c,...d},f){let p=xs(i,{relative:d.relative}),m=gt(),w=u.useContext(Xa),{navigator:v,basename:x}=u.useContext(ht),k=w!=null&&Fy(p)&&l===!0,g=v.encodeLocation?v.encodeLocation(p).pathname:p.pathname,h=m.pathname,y=w&&w.navigation&&w.navigation.location?w.navigation.location.pathname:null;n||(h=h.toLowerCase(),y=y?y.toLowerCase():null,g=g.toLowerCase()),y&&x&&(y=en(y,x)||y);const S=g!=="/"&&g.endsWith("/")?g.length-1:g.length;let b=h===g||!a&&h.startsWith(g)&&h.charAt(S)==="/",N=y!=null&&(y===g||!a&&y.startsWith(g)&&y.charAt(g.length)==="/"),C={isActive:b,isPending:N,isTransitioning:k},I=b?t:void 0,E;typeof r=="function"?E=r(C):E=[r,b?"active":null,N?"pending":null,k?"transitioning":null].filter(Boolean).join(" ");let $=typeof o=="function"?o(C):o;return u.createElement(Ye,{...d,"aria-current":I,className:E,ref:f,style:$,to:i,viewTransition:l},typeof c=="function"?c(C):c)});Fl.displayName="NavLink";var Py=u.forwardRef(({discover:e="render",fetcherKey:t,navigate:n,reloadDocument:r,replace:a,state:o,method:i=na,action:l,onSubmit:c,relative:d,preventScrollReset:f,viewTransition:p,unstable_defaultShouldRevalidate:m,...w},v)=>{let{unstable_useTransitions:x}=u.useContext(ht),k=Ly(),g=My(l,{relative:d}),h=i.toLowerCase()==="get"?"get":"post",y=typeof l=="string"&&Zf.test(l),S=b=>{if(c&&c(b),b.defaultPrevented)return;b.preventDefault();let N=b.nativeEvent.submitter,C=(N==null?void 0:N.getAttribute("formmethod"))||i,I=()=>k(N||b.currentTarget,{fetcherKey:t,method:C,navigate:n,replace:a,state:o,relative:d,preventScrollReset:f,viewTransition:p,unstable_defaultShouldRevalidate:m});x&&n!==!1?u.startTransition(()=>I()):I()};return u.createElement("form",{ref:v,method:h,action:g,onSubmit:r?c:S,...w,"data-discover":!y&&e==="render"?"true":void 0})});Py.displayName="Form";function _y(e){return`${e} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function em(e){let t=u.useContext(xr);return ke(t,_y(e)),t}function Ay(e,{target:t,replace:n,unstable_mask:r,state:a,preventScrollReset:o,relative:i,viewTransition:l,unstable_defaultShouldRevalidate:c,unstable_useTransitions:d}={}){let f=nn(),p=gt(),m=xs(e,{relative:i});return u.useCallback(w=>{if(uy(w,t)){w.preventDefault();let v=n!==void 0?n:fs(p)===fs(m),x=()=>f(e,{replace:v,unstable_mask:r,state:a,preventScrollReset:o,relative:i,viewTransition:l,unstable_defaultShouldRevalidate:c});d?u.startTransition(()=>x()):x()}},[p,f,m,n,r,a,t,e,o,i,l,c,d])}function tm(e){Ct(typeof URLSearchParams<"u","You cannot use the `useSearchParams` hook in a browser that does not support the URLSearchParams API. If you need to support Internet Explorer 11, we recommend you load a polyfill such as https://github.com/ungap/url-search-params.");let t=u.useRef(Ri(e)),n=u.useRef(!1),r=gt(),a=u.useMemo(()=>dy(r.search,n.current?null:t.current),[r.search]),o=nn(),i=u.useCallback((l,c)=>{const d=Ri(typeof l=="function"?l(new URLSearchParams(a)):l);n.current=!0,o("?"+d,c)},[o,a]);return[a,i]}var zy=0,$y=()=>`__${String(++zy)}__`;function Ly(){let{router:e}=em("useSubmit"),{basename:t}=u.useContext(ht),n=Zg(),r=e.fetch,a=e.navigate;return u.useCallback(async(o,i={})=>{let{action:l,method:c,encType:d,formData:f,body:p}=py(o,t);if(i.navigate===!1){let m=i.fetcherKey||$y();await r(m,n,i.action||l,{unstable_defaultShouldRevalidate:i.unstable_defaultShouldRevalidate,preventScrollReset:i.preventScrollReset,formData:f,body:p,formMethod:i.method||c,formEncType:i.encType||d,flushSync:i.flushSync})}else await a(i.action||l,{unstable_defaultShouldRevalidate:i.unstable_defaultShouldRevalidate,preventScrollReset:i.preventScrollReset,formData:f,body:p,formMethod:i.method||c,formEncType:i.encType||d,replace:i.replace,state:i.state,fromRouteId:n,flushSync:i.flushSync,viewTransition:i.viewTransition})},[r,a,t,n])}function My(e,{relative:t}={}){let{basename:n}=u.useContext(ht),r=u.useContext($t);ke(r,"useFormAction must be used inside a RouteContext");let[a]=r.matches.slice(-1),o={...xs(e||".",{relative:t})},i=gt();if(e==null){o.search=i.search;let l=new URLSearchParams(o.search),c=l.getAll("index");if(c.some(f=>f==="")){l.delete("index"),c.filter(p=>p).forEach(p=>l.append("index",p));let f=l.toString();o.search=f?`?${f}`:""}}return(!e||e===".")&&a.route.index&&(o.search=o.search?o.search.replace(/^\?/,"?index&"):"?index"),n!=="/"&&(o.pathname=o.pathname==="/"?n:Dt([n,o.pathname])),fs(o)}function Fy(e,{relative:t}={}){let n=u.useContext(Hf);ke(n!=null,"`useViewTransitionState` must be used within `react-router-dom`'s `RouterProvider`. Did you accidentally import `RouterProvider` from `react-router`?");let{basename:r}=em("useViewTransitionState"),a=xs(e,{relative:t});if(!n.isTransitioning)return!1;let o=en(n.currentLocation.pathname,r)||n.currentLocation.pathname,i=en(n.nextLocation.pathname,r)||n.nextLocation.pathname;return Ra(a.pathname,i)!=null||Ra(a.pathname,o)!=null}class nm extends Error{constructor(n){super("different_account");Sr(this,"summary");this.name="DifferentAccountError",this.summary=n}}class Oy{constructor(){Sr(this,"apiKey",null)}setApiKey(t){this.apiKey=t}clearApiKey(){this.apiKey=null}getApiKey(){return this.apiKey}async fetch(t,n){return globalThis.fetch(t,{...n,headers:{"Content-Type":"application/json",...this.apiKey?{"X-API-Key":this.apiKey}:{},...n==null?void 0:n.headers}})}async login(t,n={}){const r=await this.fetch("/auth/login",{method:"POST",headers:{"X-API-Key":t,"Content-Type":"application/json"},body:JSON.stringify({confirmWipe:n.confirmWipe===!0})});if(r.status===409){const o=await r.json().catch(()=>({}));if(o!=null&&o.wouldWipe)throw new nm(o.summary??{credentialCount:0,serviceCount:0,credentialIds:[]})}if(!r.ok){const o=await r.json().catch(()=>({error:"Invalid API key"}));throw new Error(o.error||`Login failed: ${r.status}`)}return(await r.json()).user}async logout(){await this.fetch("/auth/logout",{method:"POST"})}async getGroups(){const t=await this.fetch("/api/groups");if(!t.ok)throw new Error(`Failed to fetch groups: ${t.status}`);const n=await t.json();return n.groups??n}async listProfiles(){const t=await this.fetch("/api/profiles");if(!t.ok)throw new Error(`Failed to fetch profiles: ${t.status}`);return(await t.json()).profiles}async getProfile(t){const n=await this.fetch(`/api/profiles/${encodeURIComponent(t)}`);if(!n.ok)throw new Error(`Failed to fetch profile: ${n.status}`);return n.json()}async attest(t){const n=await this.fetch("/api/as/attest",{method:"POST",body:JSON.stringify(t)});if(!n.ok){const r=await n.json().catch(()=>({error:"Unknown error"}));throw new Error(r.error||`Attest failed: ${n.status}`)}return n.json()}async getPending(t){const n=await this.fetch(`/api/attestations/pending?domain=${encodeURIComponent(t)}`);if(!n.ok)throw new Error(`Failed to fetch pending: ${n.status}`);const r=await n.json();return r.pending??r}async getMyAttestations(t){const n=t?`?status=${encodeURIComponent(t)}`:"",r=await this.fetch(`/api/attestations/mine${n}`);if(!r.ok)throw new Error(`Failed to fetch attestations: ${r.status}`);return((await r.json()).attestations??[]).map(o=>{var i,l;return{authorization_id:o.authorization_id,profile_id:o.profileId,path:o.path,title:o.title??null,sp_status:o.status??null,frame:o.bounds??o.frame??{},required_domains:o.requiredDomains??[],attested_domains:o.attestedDomains??[],missing_domains:(o.requiredDomains??[]).filter(c=>!(o.attestedDomains??[]).includes(c)),deferred_commitment_domains:o.deferredCommitmentDomains??[],approvers_frozen:o.approversFrozen??[],above_cap:o.aboveCap??!1,created_at:o.createdAt?new Date(o.createdAt*1e3).toISOString():"",earliest_expiry:(i=o.attestations)!=null&&i.length?new Date(Math.min(...o.attestations.map(c=>c.expiresAt))*1e3).toISOString():null,remaining_seconds:(l=o.attestations)!=null&&l.length?Math.max(0,Math.min(...o.attestations.map(c=>c.expiresAt))-Math.floor(Date.now()/1e3)):null}})}async getDenials(t){const n=new URLSearchParams;t!=null&&t.since&&n.set("since",String(t.since)),t!=null&&t.limit&&n.set("limit",String(t.limit));const r=n.toString()?`?${n.toString()}`:"",a=await this.fetch(`/denials${r}`);if(!a.ok)throw new Error(`Failed to fetch denials: ${a.status}`);return a.json()}async getMyReceipts(t){const n=new URLSearchParams;t!=null&&t.date&&n.set("date",t.date),t!=null&&t.profile&&n.set("profile",t.profile),t!=null&&t.limit&&n.set("limit",String(t.limit));const r=n.toString(),a=await this.fetch(`/api/receipts/mine${r?"?"+r:""}`);if(!a.ok)throw new Error(`Failed to fetch receipts: ${a.status}`);return(await a.json()).receipts??[]}async fetchEvidenceBundle(){var a;const t=await this.fetch("/api/evidence-export"),n=await t.json();if(!t.ok)throw new Error(n.error??`Export failed (${t.status})`);const r=((a=/filename="([^"]+)"/.exec(t.headers.get("content-disposition")??""))==null?void 0:a[1])??"suveren-evidence.json";return{bundle:n,filename:r}}async getLocalAuthorizations(){const t=await this.fetch("/api/evidence/authorizations");if(!t.ok)throw new Error(`Local evidence unavailable (${t.status})`);const n=await t.json();return{authorizations:n.authorizations??{},signatures:n.signatures??{}}}async getArchivedReceipt(t){const n=await this.fetch(`/api/evidence/receipt/${encodeURIComponent(t)}`);if(n.status===404)return null;if(!n.ok)throw new Error(`Local evidence unavailable (${n.status})`);return await n.json()}async revokeAttestation(t,n){const r=await this.fetch(`/api/authorizations/${encodeURIComponent(t)}/revoke`,{method:"POST",body:JSON.stringify({reason:n??"Revoked by user"})});if(!r.ok){const a=await r.json().catch(()=>({error:"Failed to revoke"}));throw new Error(a.error||`Revoke failed: ${r.status}`)}}async getAttestations(t){const n=await this.fetch(`/api/attestations?authorization_id=${encodeURIComponent(t)}`);if(!n.ok)throw new Error(`Failed to fetch attestations: ${n.status}`);return n.json()}async getGroupById(t){const n=await this.fetch(`/api/groups/${encodeURIComponent(t)}`);if(!n.ok)throw new Error(`Failed to fetch group: ${n.status}`);return n.json()}async createGroup(t){const n=await this.fetch("/api/groups",{method:"POST",body:JSON.stringify({name:t})});if(!n.ok){const o=await n.json().catch(()=>({error:"Unknown error"}));throw new Error(o.error||`Create group failed: ${n.status}`)}const r=await n.json(),a=r.group||r;return{id:a.id,name:a.name,myDomains:a.myDomains||[],isAdmin:!0}}async joinGroup(t){const n=await this.fetch("/api/groups/join",{method:"POST",body:JSON.stringify({inviteCode:t})});if(!n.ok){const o=await n.json().catch(()=>({error:"Unknown error"}));throw new Error(o.error||`Join group failed: ${n.status}`)}const r=await n.json(),a=r.group||r;return{id:a.id,name:a.name,myDomains:a.myDomains||[],isAdmin:a.isAdmin||!1}}async inviteToGroup(t){const n=await this.fetch(`/api/groups/${encodeURIComponent(t)}/invite`,{method:"POST"});if(!n.ok){const r=await n.json().catch(()=>({error:"Unknown error"}));throw new Error(r.error||`Invite failed: ${n.status}`)}return n.json()}async getMyTeam(){const t=await this.fetch("/api/groups/me");if(!t.ok)return null;const n=await t.json();return n.group?{group:n.group,membership:n.membership}:null}async listUsers(){const t=await this.fetch("/api/users");return t.ok?(await t.json()).users??[]:[]}async setPubkey(t){const n=await this.fetch("/api/users/me/pubkey",{method:"PUT",body:JSON.stringify({pubkey:t})});if(!n.ok){const r=await n.json().catch(()=>({error:"Failed to set pubkey"}));throw new Error(r.error||`setPubkey failed: ${n.status}`)}}async getPubkey(t){const n=await this.fetch(`/api/users/${encodeURIComponent(t)}/pubkey`);return n.status===404||!n.ok?null:(await n.json()).pubkey??null}async leaveTeam(t){const n=await this.fetch(`/api/groups/${encodeURIComponent(t)}/leave`,{method:"POST"});if(!n.ok){const r=await n.json().catch(()=>({error:"Failed to leave team"}));throw new Error(r.error||`Leave failed: ${n.status}`)}}async getVaultStatus(){const t=await this.fetch("/vault/status");if(!t.ok)throw new Error(`Failed to fetch vault status: ${t.status}`);return t.json()}async getGatewaySettings(){const t=await this.fetch("/api/gateway-settings");if(!t.ok)throw new Error(`Failed to load settings: ${t.status}`);return t.json()}async setGatewaySettings(t){const n=await this.fetch("/api/gateway-settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok)throw new Error(`Failed to save settings: ${n.status}`);return n.json()}async getArchivedMandates(){const t=await this.fetch("/api/archived-mandates");if(!t.ok)throw new Error(`Failed to load archived mandates: ${t.status}`);return(await t.json()).archived}async setMandateArchived(t,n){const r=await this.fetch(`/api/archived-mandates/${encodeURIComponent(t)}`,{method:n?"PUT":"DELETE"});if(!r.ok)throw new Error(`Failed to ${n?"archive":"unarchive"} mandate: ${r.status}`);return(await r.json()).archived}async getCredential(t){const n=await this.fetch(`/vault/credentials/${encodeURIComponent(t)}`);if(!n.ok)throw new Error(`Failed to check credential: ${n.status}`);return n.json()}async setCredential(t,n){const r=await this.fetch(`/vault/credentials/${encodeURIComponent(t)}`,{method:"PUT",body:JSON.stringify(n)});if(!r.ok)throw new Error(`Failed to save credential: ${r.status}`)}async testCredential(t){const n=await this.fetch(`/vault/test/${encodeURIComponent(t)}`,{method:"POST"});if(!n.ok)throw new Error(`Test failed: ${n.status}`);return n.json()}async aiAssist(t){const n=await this.fetch("/ai/assist",{method:"POST",body:JSON.stringify(t)});return n.ok?n.json():{success:!1,error:(await n.json().catch(()=>({error:"AI request failed"}))).error,disclaimer:"AI surfaces reality. You supply intent."}}async aiIntentReview(t){const n=await this.fetch("/ai/intent-review",{method:"POST",body:JSON.stringify(t)});return n.ok?n.json():{success:!1,error:(await n.json().catch(()=>({error:"AI request failed"}))).error}}async aiTest(t){const n=await this.fetch("/ai/test",{method:"POST",body:JSON.stringify(t??{})});if(!n.ok)throw new Error(`AI test failed: ${n.status}`);return n.json()}async aiModels(t){const n=await this.fetch("/ai/models",{method:"POST",body:JSON.stringify(t??{})});if(!n.ok)throw new Error(`Model list failed: ${n.status}`);return n.json()}async getMcpHealth(){const t=await this.fetch("/mcp/health");if(!t.ok)throw new Error(`MCP server unreachable: ${t.status}`);return t.json()}async getMcpIntegrations(){const t=await this.fetch("/mcp/integrations");if(!t.ok)throw new Error(`Failed to fetch integrations: ${t.status}`);return t.json()}async getOAuthHealth(t){try{const n=await this.fetch(`/auth/oauth/${encodeURIComponent(t)}/health`);return n.ok?await n.json():{status:"unverified"}}catch{return{status:"unverified"}}}async getIntegrationManifests(){const t=await this.fetch("/mcp/integrations/manifests");if(!t.ok)throw new Error(`Failed to fetch manifests: ${t.status}`);return t.json()}async discoverScopeField(t,n){const r=await this.fetch(`/integrations/${encodeURIComponent(t)}/discover/${encodeURIComponent(n)}`);if(!r.ok){const a=await r.json().catch(()=>({error:`Discovery failed: ${r.status}`}));throw new Error(a.error)}return r.json()}async activateIntegration(t){const n=await this.fetch(`/mcp/integrations/${encodeURIComponent(t)}/activate`,{method:"POST"});if(!n.ok){const r=await n.json().catch(()=>({error:"Failed"}));throw new Error(r.error||`Failed: ${n.status}`)}return n.json()}async removeMcpIntegration(t){const n=await this.fetch(`/mcp/integrations/${encodeURIComponent(t)}`,{method:"DELETE"});if(!n.ok)throw new Error(`Failed to remove integration: ${n.status}`)}async setReadPolicy(t,n){const r=await this.fetch(`/integrations/${encodeURIComponent(t)}/read-policy`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({readAgeDays:n})});if(!r.ok){const a=await r.json().catch(()=>({error:`HTTP ${r.status}`}));throw new Error(a.error)}}async getTeamProfileConfig(t,n){const r=await this.fetch(`/api/groups/${encodeURIComponent(t)}/profile-config/${encodeURIComponent(n)}`);if(r.status===404||!r.ok)return null;const a=await r.json();return(a==null?void 0:a.config)??null}async setTeamProfileConfig(t,n,r){const a=await this.fetch(`/api/groups/${encodeURIComponent(t)}/profile-config/${encodeURIComponent(n)}`,{method:"PUT",body:JSON.stringify(r)});if(!a.ok){const o=await a.json().catch(()=>({error:"Failed to set profile config"}));throw new Error(o.error||`setTeamProfileConfig failed: ${a.status}`)}}async encryptIntent(t,n){const r=await this.fetch("/api/encrypt-intent",{method:"POST",body:JSON.stringify({intent:t,recipients:n})});if(!r.ok){const a=await r.json().catch(()=>({error:"Encryption failed"}));throw new Error(a.error||`encryptIntent failed: ${r.status}`)}return r.json()}async getApproversPubkeys(t,n){const r=await this.fetch(`/api/groups/${encodeURIComponent(t)}/profile-config/${encodeURIComponent(n)}/approvers/pubkeys`);return r.ok?(await r.json()).approvers??[]:[]}async deleteTeamProfileConfig(t,n){const r=await this.fetch(`/api/groups/${encodeURIComponent(t)}/profile-config/${encodeURIComponent(n)}`,{method:"DELETE"});if(!r.ok){const a=await r.json().catch(()=>({error:"Failed to delete profile config"}));throw new Error(a.error||`deleteTeamProfileConfig failed: ${r.status}`)}}async getProposals(t){const n=await this.fetch(`/api/proposals?domain=${encodeURIComponent(t)}`);if(!n.ok)throw new Error(`Failed to fetch proposals: ${n.status}`);return(await n.json()).proposals??[]}async resolveProposal(t,n,r){const a=await this.fetch(`/api/proposals/${encodeURIComponent(t)}/resolve`,{method:"POST",body:JSON.stringify({action:n,domain:r})});if(!a.ok){const o=await a.json().catch(()=>({error:"Failed"}));throw new Error(o.error||`Failed: ${a.status}`)}return a.json()}async getProposalsForApprover(){const t=await this.fetch("/api/proposals?approver=me");if(!t.ok)throw new Error(`Failed to fetch approver proposals: ${t.status}`);return(await t.json()).proposals??[]}async approveProposal(t){const n=await this.fetch(`/api/proposals/${encodeURIComponent(t)}/approve`,{method:"POST"});if(!n.ok){const r=await n.json().catch(()=>({error:"Failed"}));throw new Error(r.error||`approveProposal failed: ${n.status}`)}return n.json()}async rejectProposal(t,n){const r=await this.fetch(`/api/proposals/${encodeURIComponent(t)}/reject`,{method:"POST",body:JSON.stringify({reason:n})});if(!r.ok){const a=await r.json().catch(()=>({error:"Failed"}));throw new Error(a.error||`rejectProposal failed: ${r.status}`)}return r.json()}async getAttestationIntent(t){const n=await this.fetch(`/api/authorizations/${encodeURIComponent(t)}/intent`);return n.status===404||n.status===403||!n.ok?null:n.json()}async decryptIntent(t){const n=await this.fetch("/api/decrypt-intent",{method:"POST",body:JSON.stringify(t)});if(!n.ok){const a=await n.json().catch(()=>({error:"Decryption failed"}));throw new Error(a.error||`decryptIntent failed: ${n.status}`)}return(await n.json()).intent}async storeApprovedIntent(t,n){const r=await this.fetch("/api/approved-intents",{method:"POST",body:JSON.stringify({authorityId:t,intent:n})});if(!r.ok){const a=await r.json().catch(()=>({error:"Failed"}));throw new Error(a.error||`storeApprovedIntent failed: ${r.status}`)}}async listTeamAuthorizations(t){const n=await this.fetch(`/api/groups/${encodeURIComponent(t)}/attestations`);if(!n.ok)throw new Error(`Failed to fetch team authorizations: ${n.status}`);return((await n.json()).items??[]).map(a=>{var l,c;const o=a.owner??{userId:""};return{authorization_id:a.authorization_id??a.authorizationId,profile_id:a.profileId??a.profile_id,path:a.path??"",title:a.title??null,sp_status:a.status??a.sp_status??null,frame:a.bounds??a.frame??{},required_domains:a.requiredDomains??a.required_domains??[],attested_domains:a.attestedDomains??a.attested_domains??[],missing_domains:(a.requiredDomains??a.required_domains??[]).filter(d=>!(a.attestedDomains??a.attested_domains??[]).includes(d)),deferred_commitment_domains:a.deferredCommitmentDomains??a.deferred_commitment_domains??[],approvers_frozen:a.approversFrozen??a.approvers_frozen??[],above_cap:a.aboveCap??a.above_cap??!1,created_at:a.createdAt?new Date(a.createdAt*1e3).toISOString():a.created_at??"",earliest_expiry:(l=a.attestations)!=null&&l.length?new Date(Math.min(...a.attestations.map(d=>d.expiresAt))*1e3).toISOString():null,remaining_seconds:(c=a.attestations)!=null&&c.length?Math.max(0,Math.min(...a.attestations.map(d=>d.expiresAt))-Math.floor(Date.now()/1e3)):null,owner:o}})}async listTeamReceipts(t){const n=await this.fetch(`/api/groups/${encodeURIComponent(t)}/receipts`);if(!n.ok)throw new Error(`Failed to fetch team receipts: ${n.status}`);return(await n.json()).receipts??[]}async getMyReceiptsPage(t){const n=new URLSearchParams;t!=null&&t.before&&n.set("before",t.before),t!=null&&t.profile&&n.set("profile",t.profile),t!=null&&t.limit&&n.set("limit",String(t.limit));const r=n.toString(),a=await this.fetch(`/api/receipts/mine${r?"?"+r:""}`);if(!a.ok)throw new Error(`Failed to fetch receipts: ${a.status}`);const o=await a.json();return{receipts:o.receipts??[],nextBefore:o.nextBefore??null}}async listTeamReceiptsPage(t,n){const r=new URLSearchParams;n!=null&&n.before&&r.set("before",n.before),n!=null&&n.profile&&r.set("profile",n.profile),n!=null&&n.limit&&r.set("limit",String(n.limit));const a=r.toString(),o=await this.fetch(`/api/groups/${encodeURIComponent(t)}/receipts${a?"?"+a:""}`);if(!o.ok)throw new Error(`Failed to fetch team receipts: ${o.status}`);const i=await o.json();return{receipts:i.receipts??[],nextBefore:i.nextBefore??null}}async getThread(t){const n=t.sinceDays??7,r=t.status??"pending",a=t.domain||"owner",o=await this.getProposals(a);let i=[];if(r==="all"){const l=[],c=new Date;for(let f=0;f<n;f++){const p=new Date(c);p.setUTCDate(c.getUTCDate()-f),l.push(p.toISOString().slice(0,10))}i=(await Promise.all(l.map(f=>this.getMyReceipts({date:f,profile:t.profile})))).flat()}return{proposals:o,receipts:i}}async getAutostart(){const t=await this.fetch("/autostart");if(!t.ok)throw new Error(`HTTP ${t.status}`);return t.json()}async setAutostart(t){const n=await this.fetch("/autostart",{method:t?"POST":"DELETE"});if(!n.ok){const r=await n.json().catch(()=>({}));throw new Error(r.message||`HTTP ${n.status}`)}}async getAsPairing(){const t=await this.fetch("/as-pairing");if(!t.ok)throw new Error(`HTTP ${t.status}`);return t.json()}async getSkippedCommitments(){const t=await this.fetch("/skipped-commitments");if(!t.ok)throw new Error(`HTTP ${t.status}`);return t.json()}async getGateContent(t){const n=await this.fetch(`/gate-content?path=${encodeURIComponent(t)}`);if(!n.ok)throw new Error(`Failed to fetch gate content: ${n.status}`);return(await n.json()).entry??null}async resyncGates(){const t=await this.fetch("/resync-gates",{method:"POST"});if(!t.ok)throw new Error(`Failed to resync gates: ${t.status}`)}async getEnrichedAuthorizations(){const t=await this.fetch("/active-authorizations");if(!t.ok)throw new Error(`Failed to fetch authorizations: ${t.status}`);return(await t.json()).authorizations??[]}async pushGateContent(t){const n=await this.fetch("/gate-content",{method:"POST",body:JSON.stringify(t)});if(!n.ok){const r=await n.json().catch(()=>({error:"Failed to push gate content"}));throw new Error(r.error||`Push gate content failed: ${n.status}`)}}async getAgentContext(){const t=await this.fetch("/agent-brief/context");if(!t.ok)throw new Error(`Failed to fetch agent context: ${t.status}`);return(await t.json()).content}async saveAgentContext(t){const n=await this.fetch("/agent-brief/context",{method:"PUT",body:JSON.stringify({content:t})});if(!n.ok){const r=await n.json().catch(()=>({error:"Failed to save agent context"}));throw new Error(r.error||`Save failed: ${n.status}`)}}async aiChat(t){const n=await this.fetch("/ai/chat",{method:"POST",body:JSON.stringify(t)});return n.ok?n.json():{success:!1,error:(await n.json().catch(()=>({error:"AI chat failed"}))).error||`Chat failed: ${n.status}`}}async getAIPrompts(){const t=await this.fetch("/ai-prompts");if(!t.ok)throw new Error(`Failed to load AI prompts: ${t.status}`);return t.json()}async setAIPrompt(t,n){const r=await this.fetch(`/ai-prompts/${t}`,{method:"PUT",body:JSON.stringify({value:n})});if(!r.ok){const a=await r.json().catch(()=>({error:"Save failed"}));throw new Error(a.error||`Save failed: ${r.status}`)}}}const T=new Oy,rm=u.createContext(null);function By({children:e}){const[t,n]=u.useState(null),[r,a]=u.useState("personal"),[o,i]=u.useState(null),[l,c]=u.useState(""),[d,f]=u.useState(null),[p,m]=u.useState(null),[w,v]=u.useState(!1),[x,k]=u.useState(""),g=u.useRef(!1),h=u.useRef(null),y=u.useCallback(async()=>{if(g.current)try{const E=await T.getMyTeam();if(E){const{group:$,membership:U}=E;f($),m(U),a("team"),i($);const V=h.current??U.domains[0]??"owner";c(V)}else f(null),m(null),a("personal")}catch{}},[]);u.useEffect(()=>{const E=()=>{document.visibilityState==="visible"&&y()};return document.addEventListener("visibilitychange",E),()=>document.removeEventListener("visibilitychange",E)},[y]),u.useEffect(()=>{fetch("/health").then(E=>E.json()).then(E=>{var $;(($=E.session)==null?void 0:$.lockedReason)==="as-url-changed"&&k(`Authority Server changed to ${E.spUrl??"a new server"} — sign in again.`)}).catch(()=>{})},[]);const S=u.useCallback(async(E,$={})=>{v(!0),k("");try{T.setApiKey(E),g.current=!0;const U=await T.login(E,$);n(U),h.current=U.id;const V=await T.getGroups(),J=V.find(D=>D.isPersonal)??V[0]??null;i(J),c("owner"),await y()}catch(U){throw T.clearApiKey(),g.current=!1,k(U instanceof Error?U.message:"Login failed"),U}finally{v(!1)}},[y]),b=u.useCallback(async()=>{await T.logout(),T.clearApiKey(),g.current=!1,h.current=null,n(null),i(null),c(""),f(null),m(null),a("personal"),k("")},[]),N=u.useCallback(E=>{T.clearApiKey(),g.current=!1,h.current=null,n(null),i(null),c(""),f(null),m(null),a("personal"),k(E??"Your sign-in ended after 30 days or was revoked. Sign in again.")},[]),C=u.useCallback(()=>k(""),[]),I=u.useCallback((E,$)=>{i(E),c($)},[]);return s.jsx(rm.Provider,{value:{user:t,mode:r,group:o,domain:l,groupId:(o==null?void 0:o.id)??null,activeTeam:d,activeMembership:p,isLoading:w,error:x,login:S,logout:b,clearError:C,handleSessionLocked:N,activeGroup:o,activeDomain:l,groups:o?[o]:[],setActiveContext:I,refreshGroups:y},children:e})}function Fe(){const e=u.useContext(rm);if(!e)throw new Error("useAuth must be used within AuthProvider");return e}const sm=u.createContext(null);function Dy({children:e}){const{user:t}=Fe(),n=u.useRef(null),[r,a]=u.useState(!1),o=u.useRef(new Map),i=u.useCallback((l,c)=>{const d=o.current;return d.has(l)||d.set(l,new Set),d.get(l).add(c),()=>{var f;(f=d.get(l))==null||f.delete(c)}},[]);return u.useEffect(()=>{if(!t){n.current&&(n.current.close(),n.current=null,a(!1));return}if(n.current)return;const l=T.getApiKey();if(!l)return;const c=new EventSource(`/events?key=${encodeURIComponent(l)}`);n.current=c,c.onopen=()=>a(!0),c.onerror=()=>a(!1);const d=["integration-changed","attestation-changed","proposal-added","proposal-resolved","team-membership-changed","action-approval-needed","action-resolved","proposal-approved","proposal-rejected","session-locked"];for(const f of d)c.addEventListener(f,p=>{let m;try{m=JSON.parse(p.data)}catch{m=null}const w=o.current.get(f);if(w)for(const v of w)try{v(m)}catch(x){console.error(`[EventSource] handler for "${f}" threw:`,x)}});return()=>{c.close(),n.current=null,a(!1)}},[t]),s.jsx(sm.Provider,{value:{connected:r,addListener:i},children:e})}function fe(e,t){const n=u.useContext(sm);if(!n)return;const{addListener:r}=n;u.useEffect(()=>r(e,t),[e,t,r])}const Yr="suveren-theme",iu="hap-theme";function Bs(e){return e!=="system"?e:window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}(function(){const t=localStorage.getItem(iu);t!==null&&localStorage.getItem(Yr)===null&&localStorage.setItem(Yr,t),t!==null&&localStorage.removeItem(iu)})();function am(){const[e,t]=u.useState(()=>{const o=localStorage.getItem(Yr);return o==="light"||o==="dark"?o:"system"}),[n,r]=u.useState(()=>Bs(e));u.useEffect(()=>{const o=document.documentElement,i=Bs(e);o.setAttribute("data-theme",i),e==="system"?localStorage.removeItem(Yr):localStorage.setItem(Yr,e),r(Bs(e))},[e]),u.useEffect(()=>{if(e!=="system")return;const o=window.matchMedia("(prefers-color-scheme: dark)"),i=()=>r(Bs("system"));return o.addEventListener("change",i),()=>o.removeEventListener("change",i)},[e]);const a=u.useCallback(()=>{t(o=>o==="system"?"light":o==="light"?"dark":"system")},[]);return{theme:e,effectiveTheme:n,toggle:a}}const Uy=5*60*1e3,Wy=2e3;function Ol(){const[e,t]=u.useState(!1),[n,r]=u.useState("docker"),[a,o]=u.useState(""),[i,l]=u.useState(null),[c,d]=u.useState(!1),[f,p]=u.useState(!1),[m,w]=u.useState(!1),v=u.useRef(null);return u.useEffect(()=>{let x=!1;const k=(y=!1)=>{fetch(y?"/health?refresh=1":"/health").then(S=>S.json()).then(S=>{x||(S.installMethod&&r(S.installMethod),typeof S.latestVersion<"u"&&l(S.latestVersion),S.updateAvailable&&t(!0),S.version&&(o(S.version),v.current===null?v.current=S.version:S.version!==v.current&&S.version!=="dev"&&d(!0)))}).catch(()=>{})};k(!0);const g=setInterval(()=>k(!1),m?Wy:Uy),h=()=>{document.visibilityState==="visible"&&k(!1)};return document.addEventListener("visibilitychange",h),window.addEventListener("focus",h),()=>{x=!0,clearInterval(g),document.removeEventListener("visibilitychange",h),window.removeEventListener("focus",h)}},[m]),{updateAvailable:e&&!f,installMethod:n,version:a,latestVersion:i,serverRestarted:c,startFastPolling:()=>w(!0),dismiss:()=>p(!0)}}function Hy({size:e=20}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 128 128",fill:"none","aria-hidden":"true",focusable:"false",children:[s.jsx("path",{d:"M 104.6 58.29 A 41 41 0 1 1 48.64 25.99",stroke:"currentColor",strokeWidth:"15",strokeLinecap:"round"}),s.jsx("line",{x1:"73.24",y1:"21.99",x2:"95.76",y2:"34.99",stroke:"currentColor",strokeWidth:"15",strokeLinecap:"round"})]})}function Vy(e){return e?e==="dev"?"dev":/^[0-9a-f]{40}$/i.test(e)?e.slice(0,7):e:""}const lu={system:"◑",light:"☀",dark:"☾"};function Bl({onMenuToggle:e}){const{user:t,logout:n}=Fe(),{theme:r,toggle:a}=am(),{version:o,updateAvailable:i,latestVersion:l}=Ol(),c=Vy(o);return s.jsx("nav",{className:"top-nav",children:s.jsxs("div",{className:"top-nav-inner",children:[s.jsxs("div",{className:"logo-group",children:[s.jsx(Hy,{size:20}),s.jsx("span",{className:"logo",children:"Suveren"}),s.jsx("span",{className:"version-badge",children:"Local Gateway"}),c&&s.jsxs("span",{className:"gw-version",title:i&&l?`Running v${c} — v${l} is available`:"Running gateway version","data-stale":i?"true":void 0,children:["v",c,i&&l?` → ${l}`:""]})]}),s.jsx("div",{className:"nav-spacer"}),s.jsx("div",{className:"nav-actions nav-actions-desktop",children:t?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"user-chip",children:s.jsx("strong",{children:t.name})}),s.jsx("button",{className:"theme-toggle",onClick:a,title:`Theme: ${r}`,children:lu[r]}),s.jsx("button",{className:"nav-logout",onClick:n,children:"Logout"})]}):s.jsx("button",{className:"theme-toggle",onClick:a,title:`Theme: ${r}`,children:lu[r]})}),t&&e&&s.jsx("button",{className:"mobile-menu-btn",onClick:e,"aria-label":"Menu",children:"☰"})]})})}function Dl(e,t){var n;if((n=t==null?void 0:t.revokedSet)!=null&&n.has(e.authorization_id))return"revoked";switch(e.sp_status){case"revoked":return"revoked";case"expired":return"expired";case"active":return"active";case"pending":return"pending"}return e.remaining_seconds===null||e.remaining_seconds<=0?"expired":e.missing_domains.length>0?"pending":"active"}function om(e){return e==="expired"||e==="revoked"}function im(e,t){var n;return!!((n=t==null?void 0:t.archivedSet)!=null&&n.has(e.authorization_id))&&om(Dl(e,t))}function Pa(e,t){return im(e,t)?"archived":Dl(e,t)}function lm(e,t){const n={active:[],pending:[],expired:[],revoked:[],archived:[]};for(const r of e)n[Pa(r,t)].push(r);return n}function Gy(e,t){return t==="expired"?e.earliest_expiry?{iso:e.earliest_expiry,meaning:"expired"}:null:e.created_at?{iso:e.created_at,meaning:"created"}:null}function Pt(e,t,n){const r=u.useRef(e);r.current=e,u.useEffect(()=>{let a=null;const o=()=>typeof document>"u"?!0:document.visibilityState==="visible",i=()=>{o()&&r.current()},l=()=>{a===null&&(a=setInterval(i,t))},c=()=>{a!==null&&(clearInterval(a),a=null)},d=()=>{o()?(r.current(),l()):c()};return o()&&(r.current(),l()),document.addEventListener("visibilitychange",d),()=>{c(),document.removeEventListener("visibilitychange",d)}},[t,n])}const cm=u.createContext(null),Ky=3e4,Yy=5e3,Qy=3e5;function Jy(e,t,n){return t===0?"loading":e!=null&&e.running?"running":e!=null&&e.paused?"paused":e!=null&&e.error?"error":e&&n?"starting":"not-running"}function Xy({children:e}){const[t,n]=u.useState({manifests:[],integrations:[],activeSessions:0,mcpServerUp:null,manifestsError:!1,fetchCount:0,authHealth:{}}),r=u.useRef(null),a=u.useCallback(async()=>{let d=!1;const[f,p]=await Promise.all([T.getIntegrationManifests().catch(()=>(d=!0,{manifests:[]})),T.getMcpHealth().catch(()=>null)]);n(w=>({...w,manifests:f.manifests,integrations:(p==null?void 0:p.integrations)??w.integrations,activeSessions:(p==null?void 0:p.activeSessions)??w.activeSessions,mcpServerUp:!!p,manifestsError:d,fetchCount:w.fetchCount+1}));const m=f.manifests.filter(w=>w.oauth);if(m.length>0){const w=await Promise.all(m.map(async v=>[v.id,await T.getOAuthHealth(v.id)]));n(v=>({...v,authHealth:Object.fromEntries(w)}))}},[]),o=t.fetchCount>0&&t.manifests.some(d=>{const f=t.integrations.find(p=>p.id===d.id);return f&&!f.running&&!f.paused});fe("integration-changed",a),Pt(a,o?Yy:Qy);const i=u.useMemo(()=>{const d=new Map(t.integrations.map(m=>[m.id,m])),f=Date.now();o&&r.current===null?r.current=f:o||(r.current=null);const p=r.current!==null&&f-r.current<Ky;return t.manifests.map(m=>{const w=d.get(m.id),v=Jy(w,t.fetchCount,p),x=t.authHealth[m.id];return{id:m.id,manifest:m,integration:w,state:v,authStatus:x==null?void 0:x.status,authAccount:x==null?void 0:x.account,authError:x==null?void 0:x.error}})},[t,o]),l=u.useMemo(()=>i.filter(d=>d.state==="not-running"||d.state==="error"||d.authStatus==="failed").length,[i]),c={loading:t.fetchCount===0,mcpServerUp:t.mcpServerUp,manifestsError:t.manifestsError,entries:i,attentionCount:l,activeSessions:t.activeSessions,refresh:a};return s.jsx(cm.Provider,{value:c,children:e})}function Ul(){const e=u.useContext(cm);if(!e)throw new Error("useIntegrationStatus must be used inside IntegrationStatusProvider");return e}const qy=[{to:"/",icon:"□",label:"Dashboard"},{to:"/approvals",icon:"▷",label:"Pending Approvals",statusKey:"proposals"},{to:"/mandates",icon:"☰",label:"Mandates",statusKey:"authorizations"},{to:"/agent-brief",icon:"▤",label:"Agent Brief",statusKey:"brief"},{to:"/tickets",icon:"▣",label:"Tickets"},{to:"/team",icon:"◉",label:"Team",teamOnly:!0},{to:"/integrations",icon:"⧗",label:"Integrations",statusKey:"integrations"},{to:"/settings",icon:"⚙",label:"Settings",statusKey:"assistant"}];function Zy(){const{activeDomain:e}=Fe(),[t,n]=u.useState({}),r=u.useCallback(async()=>{try{const[a,o,i,l,c,d]=await Promise.all([T.getCredential("ai-config").catch(()=>null),T.getMyAttestations().catch(()=>null),T.getProposals(e||"owner").catch(()=>null),T.getProposalsForApprover().catch(()=>null),T.getAgentContext().catch(()=>""),T.getArchivedMandates().catch(()=>[])]),f={};if(a&&!a.configured&&(f.assistant=1),o){const v=lm(o,{archivedSet:new Set(d)}).expired.length;v>0&&(f.authorizations=v)}const p=(i==null?void 0:i.length)??0,m=(l==null?void 0:l.length)??0,w=p+m;w>0&&(f.proposals=w),(!c||!c.trim())&&(f.brief=1),n(f)}catch{}},[e]);return fe("attestation-changed",r),fe("proposal-added",r),fe("proposal-resolved",r),fe("proposal-approved",r),fe("proposal-rejected",r),fe("team-membership-changed",r),u.useEffect(()=>(window.addEventListener("suveren:archived-changed",r),()=>window.removeEventListener("suveren:archived-changed",r)),[r]),Pt(r,3e5,e),t}const ev={marginLeft:"auto",minWidth:"1.25rem",height:"1.25rem",padding:"0 0.375rem",borderRadius:"0.625rem",background:"var(--warning)",color:"var(--bg-elevated)",fontSize:"0.7rem",fontWeight:600,display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0},tv={position:"fixed",bottom:"1.5rem",left:"50%",transform:"translateX(-50%)",background:"var(--bg-elevated, #1e1e2e)",color:"var(--text-primary, #e2e8f0)",border:"1px solid var(--border)",borderRadius:"0.5rem",padding:"0.625rem 1rem",fontSize:"0.85rem",boxShadow:"0 4px 16px rgba(0,0,0,0.3)",zIndex:9999,whiteSpace:"nowrap",pointerEvents:"none"};function nv(){const{mode:e,group:t,domain:n,activeTeam:r}=Fe(),a=Zy(),{attentionCount:o}=Ul(),i={...a};o>0&&(i.integrations=o);const l=qy.filter(m=>!m.teamOnly||e==="team"),c=u.useRef(null),[d,f]=u.useState(null),p=gt();return u.useEffect(()=>{if(c.current===null){c.current=e;return}c.current!==e&&(e==="team"&&r?f(`You are now acting in team context — ${r.name}`):e==="personal"&&f("You have left the team — back to personal context"),c.current=e)},[e,r]),u.useEffect(()=>{f(null)},[p.pathname]),s.jsxs("div",{className:"sidebar",children:[s.jsx("ul",{className:"sidebar-nav",children:l.map(m=>{const w=m.statusKey?i[m.statusKey]:0;return s.jsx("li",{children:s.jsxs(Fl,{to:m.to,end:m.to==="/",className:({isActive:v})=>`sidebar-item${v?" active":""}`,children:[s.jsx("span",{className:"icon",children:m.icon}),m.label,w?s.jsx("span",{style:ev,children:w}):null]})},m.to)})}),s.jsxs("div",{className:"sidebar-context",children:[s.jsx("div",{className:"ctx-label",children:"Active context"}),s.jsx("div",{className:"ctx-value",children:e==="personal"?"personal":t?`${t.name} / ${n}`:n})]}),d&&s.jsx("div",{style:tv,role:"status","aria-live":"polite",children:d})]})}const Po="suveren:updatedTo";function rv(e){return e==="managed"||e==="msi"?null:e==="npm"?"npm install -g @suveren/gateway@latest && suveren-gateway restart":e==="dev"?"git pull && pnpm install":"docker rm -f suveren-gateway 2>/dev/null; docker ps -q --filter publish=7400 --filter publish=7430 | xargs -r docker rm -f; docker pull ghcr.io/suverenai/suveren-gateway:latest && docker run -d --name suveren-gateway -p 7400:3000 -p 7430:3030 -v $HOME/.suveren:/app/data ghcr.io/suverenai/suveren-gateway"}const sv="Updates for this gateway come from your company's IT — no action needed here.";function av(e){return e==="managed"?"update-banner is-managed":"update-banner"}const ov="Download the new installer and run it. Your settings and mandates stay.";function iv(e){const t="https://github.com/suverenai/suveren-gateway/releases";return e?`${t}/tag/v${e}`:`${t}/latest`}function lv(){const e=document.querySelectorAll('[role="dialog"], .modal-overlay, .modal');for(const n of e)if(!n.closest(".update-overlay"))return!0;const t=document.activeElement;if(t&&(t.tagName==="INPUT"||t.tagName==="TEXTAREA"||t.isContentEditable)){const n=t.value;if(n&&n.trim())return!0}return!1}function um(){const{updateAvailable:e,installMethod:t,version:n,latestVersion:r,serverRestarted:a,startFastPolling:o,dismiss:i}=Ol(),[l,c]=u.useState(!1),[d,f]=u.useState(!1),[p,m]=u.useState(()=>{try{const y=sessionStorage.getItem(Po);if(y)return sessionStorage.removeItem(Po),y}catch{}return null}),w=rv(t),v=u.useRef(null),x=y=>{try{sessionStorage.setItem(Po,y||r||"✓")}catch{}window.location.reload()};u.useEffect(()=>{if(!p)return;const y=setTimeout(()=>m(null),6e3);return()=>clearTimeout(y)},[p]),u.useEffect(()=>{if(!l||!a)return;const y=()=>lv()?!1:(x(n),!0);if(y())return;const S=setInterval(y,1500);return()=>clearInterval(S)},[l,a,n]),u.useEffect(()=>(document.body.classList.toggle("is-updating",l),()=>document.body.classList.remove("is-updating")),[l]);const k=e&&!l&&!p||!!p&&!l;u.useEffect(()=>{if(!k){document.documentElement.style.removeProperty("--update-banner-h"),document.body.classList.remove("has-update-banner");return}document.body.classList.add("has-update-banner");const y=()=>{var N;const b=((N=v.current)==null?void 0:N.offsetHeight)??0;document.documentElement.style.setProperty("--update-banner-h",`${b}px`)};y();const S=new ResizeObserver(y);return v.current&&S.observe(v.current),()=>{S.disconnect(),document.documentElement.style.removeProperty("--update-banner-h"),document.body.classList.remove("has-update-banner")}},[k]);const g=()=>{c(!0),o()},h=async()=>{if(w)try{await navigator.clipboard.writeText(w),f(!0),setTimeout(()=>f(!1),1800)}catch{}};return s.jsxs(s.Fragment,{children:[p&&!l&&s.jsx("div",{ref:v,className:"update-banner is-live",role:"status","aria-live":"polite",children:s.jsxs("div",{className:"update-banner-row",children:[s.jsxs("span",{className:"update-banner-text",children:["✓"," You","’","re on the latest version",p&&p!=="✓"?` — ${p} is live`:" — now live","."]}),s.jsx("button",{className:"update-banner-x",onClick:()=>m(null),"aria-label":"Dismiss",children:"×"})]})}),e&&!l&&!p&&s.jsxs("div",{ref:v,className:av(t),role:"status","aria-live":"polite",children:[s.jsxs("div",{className:"update-banner-row",children:[s.jsx("span",{className:"update-banner-text",children:t==="msi"&&r?`Update available — version ${r}.`:"Update available."}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem",alignItems:"center"},children:[t==="msi"&&s.jsx("a",{className:"btn btn-sm btn-secondary",href:iv(r),target:"_blank",rel:"noopener noreferrer",children:"Download installer"}),t!=="managed"&&t!=="msi"&&s.jsx("button",{className:"btn btn-sm btn-secondary",onClick:g,children:"Update"}),s.jsx("button",{className:"update-banner-x",onClick:i,"aria-label":"Dismiss",children:"×"})]})]}),t==="managed"&&s.jsx("p",{className:"update-banner-hint",children:sv}),t==="msi"&&s.jsx("p",{className:"update-banner-hint",children:ov})]}),l&&s.jsx("div",{className:"update-overlay",children:s.jsxs("div",{className:"update-overlay-card",role:"dialog","aria-modal":"true","aria-label":"Finishing the update",children:[s.jsx("div",{className:"update-spinner"}),s.jsxs("h2",{children:["Finishing the update","…"]}),s.jsxs("p",{children:["Copy this command and run it in your terminal. The gateway will restart, and"," ",s.jsx("strong",{children:"this page updates automatically"})," when it comes back ","—"," no need to refresh."]}),s.jsxs("div",{className:"update-cmd-row",children:[s.jsx("code",{className:"update-cmd",children:w}),s.jsx("button",{className:"btn btn-sm btn-primary",onClick:h,children:d?"Copied":"Copy"})]}),s.jsxs("div",{className:"update-status",children:[s.jsx("span",{className:"update-pulse"})," Waiting for the gateway to restart","…"]}),s.jsxs("div",{className:"update-overlay-actions",children:[s.jsx("button",{className:"btn btn-primary",onClick:()=>x(n),children:"Reload now"}),s.jsx("button",{className:"btn btn-secondary",onClick:()=>c(!1),children:"Cancel"})]})]})})]})}function dm(){const[e,t]=u.useState(!1);return u.useEffect(()=>{let n=!1;const r=()=>{fetch("/health").then(i=>i.json()).then(i=>{n||t(i.simulation===!0)}).catch(()=>{})};r();const a=setInterval(r,3e4),o=()=>{document.visibilityState==="visible"&&r()};return document.addEventListener("visibilitychange",o),()=>{n=!0,clearInterval(a),document.removeEventListener("visibilitychange",o)}},[]),e}function fm(){const e=dm(),t=u.useRef(null);return u.useEffect(()=>{if(!e){document.documentElement.style.removeProperty("--sim-banner-h");return}const n=()=>{var o;const a=((o=t.current)==null?void 0:o.offsetHeight)??0;document.documentElement.style.setProperty("--sim-banner-h",`${a}px`)};n();const r=new ResizeObserver(n);return t.current&&r.observe(t.current),()=>{r.disconnect(),document.documentElement.style.removeProperty("--sim-banner-h")}},[e]),e?s.jsx("div",{ref:t,className:"simulation-banner",role:"status","aria-live":"polite",children:s.jsx("span",{className:"simulation-banner-text",children:"Simulation mode — real systems are blocked."})}):null}const cv={system:"◑",light:"☀",dark:"☾"},uv=[{to:"/",icon:"□",label:"Dashboard"},{to:"/approvals",icon:"▷",label:"Pending Approvals"},{to:"/mandates",icon:"☰",label:"Mandates"},{to:"/agent-brief",icon:"▤",label:"Agent Brief"},{to:"/tickets",icon:"▣",label:"Tickets"},{to:"/team",icon:"◉",label:"Team"},{to:"/integrations",icon:"⧗",label:"Integrations"},{to:"/settings",icon:"⚙",label:"Settings"}];function dv({open:e,onClose:t}){const{user:n,activeGroup:r,activeDomain:a,logout:o}=Fe(),{theme:i,toggle:l}=am(),c=gt();return u.useEffect(()=>{t()},[c.pathname]),e?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"mobile-menu-backdrop",onClick:t}),s.jsxs("div",{className:"mobile-menu-panel",children:[n&&s.jsxs("div",{className:"mobile-menu-header",children:[s.jsx("strong",{children:n.name}),s.jsx("span",{style:{fontSize:"0.8rem",color:"var(--text-secondary)"},children:r?`${r.name} / ${a}`:a||"personal"})]}),s.jsx("nav",{className:"mobile-menu-nav",children:uv.map(d=>s.jsxs(Fl,{to:d.to,end:d.to==="/",className:({isActive:f})=>`mobile-menu-item${f?" active":""}`,onClick:t,children:[s.jsx("span",{className:"icon",children:d.icon}),d.label]},d.to))}),s.jsxs("div",{className:"mobile-menu-footer",children:[s.jsxs("button",{className:"mobile-menu-action",onClick:()=>{l()},children:[s.jsx("span",{className:"icon",children:cv[i]}),"Theme: ",i]}),s.jsx("button",{className:"mobile-menu-action",onClick:()=>{o(),t()},children:"Logout"})]})]})]}):null}function mm(e){return e.status==="pending"}function fv(e,t){return e.filter(mm).length+t.length}const Cn=["proposal-added","proposal-resolved","proposal-approved","proposal-rejected","action-approval-needed","action-resolved","team-membership-changed"],mv=500;function pm(){const{user:e,domain:t}=Fe(),[n,r]=u.useState(0),a=u.useRef(null),o=u.useCallback(async()=>{if(!e){r(0);return}try{const[l,c]=await Promise.all([T.getProposals(t||"owner").catch(()=>[]),T.getProposalsForApprover().catch(()=>[])]);r(fv(l,c))}catch{r(0)}},[e,t]),i=u.useCallback(()=>{a.current&&clearTimeout(a.current),a.current=setTimeout(()=>{o()},mv)},[o]);return u.useEffect(()=>(o(),()=>{a.current&&clearTimeout(a.current)}),[o]),fe(Cn[0],i),fe(Cn[1],i),fe(Cn[2],i),fe(Cn[3],i),fe(Cn[4],i),fe(Cn[5],i),fe(Cn[6],i),n}const cu="Suveren",pv="/favicon.svg",hv="M 104.94 61.85 A 41 41 0 1 1 45.39 27.47",Ds={x1:74.54,y1:22.74,x2:94.46,y2:34.24},gv=14,yv="#f59e0b";function vv(e){const t=Wl(e);return t>0?`(${t}) ${cu}`:cu}function Wl(e){return Number.isFinite(e)&&e>0?Math.floor(e):0}function xv(){const e=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128" fill="none">
52
+ <path class="m" d="${hv}"/>
53
53
  <line class="m" x1="${Ds.x1}" y1="${Ds.y1}" x2="${Ds.x2}" y2="${Ds.y2}"/>
54
- <circle cx="103" cy="103" r="25" fill="${hv}"/>
55
- <style>.m{stroke:#111111;stroke-width:${pv};fill:none;stroke-linecap:round}@media (prefers-color-scheme:dark){.m{stroke:#ffffff;stroke-width:13.3}}</style>
56
- </svg>`;return`data:image/svg+xml,${encodeURIComponent(e)}`}function vv(){return document.querySelector('link[rel="icon"]')}function hm(e){const t=Wl(e);document.title=gv(t),gm(t);const n=vv();if(!n)return;const r=t>0?yv():fv;n.getAttribute("href")!==r&&n.setAttribute("href",r)}function xv(){hm(0)}function gm(e,t=globalThis.navigator){var a;if(!t||typeof t.setAppBadge!="function")return;const n=Wl(e),r=n>0?t.setAppBadge(n):t.clearAppBadge?t.clearAppBadge():t.setAppBadge(0);(a=r==null?void 0:r.catch)==null||a.call(r,()=>{})}function wv(){const e=pm();return u.useEffect(()=>{hm(e)},[e]),u.useEffect(()=>xv,[]),null}const ym="suveren:dockBadgePrompt";function Sv(){var r;if(typeof window>"u"||!("Notification"in window)||!("setAppBadge"in navigator)||!(((r=window.matchMedia)==null?void 0:r.call(window,"(display-mode: standalone)").matches)||navigator.standalone===!0))return!1;const t=navigator.userAgent;if(!(/Safari\//.test(t)&&!/Chrome\/|Chromium\/|Edg\//.test(t))||Notification.permission!=="default")return!1;try{if(localStorage.getItem(ym))return!1}catch{}return!0}function jv(){const[e,t]=u.useState(!1),n=pm();if(u.useEffect(()=>{t(Sv())},[]),!e)return null;const r=()=>{try{localStorage.setItem(ym,"1")}catch{}t(!1)},a=async()=>{try{await Notification.requestPermission()==="granted"&&gm(n)}catch{}r()};return s.jsxs("div",{className:"hint-box",style:{marginBottom:"1rem",alignItems:"center"},children:[s.jsxs("div",{className:"hint-body",children:[s.jsx("div",{className:"hint-head",children:"Show waiting approvals on the Dock icon"}),"Safari needs your permission once. The icon then shows how many approvals are waiting, and nothing else."]}),s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:a,children:"Allow"}),s.jsx("button",{type:"button",className:"btn btn-ghost btn-sm",onClick:r,"aria-label":"Not now",children:"Not now"})]})}function kv(){const[e,t]=u.useState(!1);return s.jsxs(Xy,{children:[s.jsx(wv,{}),s.jsx(Bl,{onMenuToggle:()=>t(!e)}),s.jsx(um,{}),s.jsx(fm,{}),s.jsx(nv,{}),s.jsx(cv,{open:e,onClose:()=>t(!1)}),s.jsx("div",{className:"main-content",children:s.jsxs("div",{className:"page-inner",children:[s.jsx(jv,{}),s.jsx(ry,{})]})})]})}function bv(){const[e,t]=u.useState(""),{login:n,isLoading:r,error:a,clearError:o}=Fe(),[i,l]=u.useState(null),c=async()=>{if(e.trim()){o();try{await n(e)}catch(p){if(p instanceof nm){l(p.summary);return}}}},d=async()=>{l(null),o();try{await n(e,{confirmWipe:!0})}catch{}},f=()=>{l(null)};return s.jsxs(s.Fragment,{children:[s.jsx(Bl,{}),s.jsx(um,{}),s.jsx(fm,{}),s.jsxs("div",{className:"login-split",children:[s.jsx("div",{className:"login-split-left",children:s.jsxs("div",{style:{maxWidth:"28rem"},children:[s.jsx("h1",{style:{fontSize:"clamp(2.25rem, 4vw, 3.25rem)",letterSpacing:"-0.03em",lineHeight:1.1,marginBottom:"1.25rem"},children:"Your agents, your intent, your rules."}),s.jsx("p",{style:{fontSize:"1.125rem",color:"var(--text-secondary)",lineHeight:1.6,marginBottom:"3rem"},children:"The gateway runs on your machine, between your agents and the tools they use. Your signature. Your bounds. Your tickets."})]})}),s.jsx("div",{className:"login-split-right",children:s.jsxs("div",{style:{width:"100%",maxWidth:"24rem"},children:[s.jsxs("div",{style:{textAlign:"center",marginBottom:"2.5rem"},children:[s.jsx("div",{style:{fontSize:"1.75rem",fontWeight:700,marginBottom:"0.5rem"},children:"Sign In"}),s.jsx("div",{style:{fontSize:"0.95rem",color:"var(--text-secondary)",lineHeight:1.5},children:"Enter your API key to manage mandates."})]}),a&&s.jsx("div",{className:"error-message",children:a}),s.jsxs("div",{className:"form-group",style:{marginBottom:"1.5rem"},children:[s.jsx("label",{className:"form-label",children:"API Key"}),s.jsx("input",{className:"form-input",type:"password",placeholder:"hap_sk_...",value:e,onChange:p=>t(p.target.value),onKeyDown:p=>p.key==="Enter"&&c(),disabled:r,style:{padding:"0.75rem"}}),s.jsx("div",{className:"form-hint",children:"From your Suveren account."})]}),s.jsx("button",{className:"btn btn-primary btn-full btn-lg",onClick:c,disabled:r,style:{marginBottom:"2rem"},children:r?"Signing in...":"Sign In"}),s.jsx("div",{className:"login-divider",children:"New here?"}),s.jsxs("div",{style:{textAlign:"center",marginBottom:"2.5rem"},children:[s.jsxs("p",{style:{fontSize:"0.9rem",color:"var(--text-secondary)",marginBottom:"1rem",lineHeight:1.5},children:["Create an account on Suveren,",s.jsx("br",{}),"then come back to sign in."]}),s.jsx("a",{href:"https://www.suveren.ai/get-started",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-full",style:{textDecoration:"none"},children:"Create Account"})]}),s.jsxs("div",{style:{paddingTop:"1.75rem",borderTop:"1px solid var(--border)"},children:[s.jsx("div",{style:{fontSize:"0.75rem",fontWeight:600,color:"var(--text-tertiary)",marginBottom:"0.875rem"},children:"Getting started"}),s.jsx("div",{style:{fontSize:"0.85rem",color:"var(--text-secondary)",lineHeight:1.8},children:[s.jsxs(s.Fragment,{children:["Create an account at ",s.jsx("a",{href:"https://www.suveren.ai/get-started",target:"_blank",rel:"noopener noreferrer",style:{color:"var(--accent)"},children:"Suveren"})]}),"Join or create a team to get domain authority","Sign in here with your API key to start giving mandates"].map((p,m)=>s.jsxs("div",{style:{display:"flex",gap:"0.625rem",alignItems:"baseline",marginBottom:m<2?"0.5rem":0},children:[s.jsxs("span",{style:{color:"var(--accent)",fontWeight:700,fontSize:"0.95rem"},children:[m+1,"."]}),p]},m))})]})]})})]}),i&&s.jsx("div",{role:"dialog","aria-modal":"true","aria-labelledby":"wipe-warning-title",style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.5)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3,padding:"1rem"},onClick:f,children:s.jsxs("div",{className:"card",onClick:p=>p.stopPropagation(),style:{maxWidth:520,width:"100%",margin:0},children:[s.jsx("h3",{id:"wipe-warning-title",className:"card-title",style:{marginBottom:"0.5rem"},children:"Sign in with a different account?"}),s.jsxs("p",{style:{fontSize:"0.875rem",color:"var(--text-secondary)",marginBottom:"0.75rem"},children:["This gateway already holds data for another account. Signing in with this API key will ",s.jsx("strong",{children:"permanently wipe"})," the following local data:"]}),s.jsxs("ul",{style:{fontSize:"0.875rem",color:"var(--text-secondary)",marginBottom:"1rem",paddingLeft:"1.25rem",lineHeight:1.6},children:[s.jsxs("li",{children:[i.credentialCount," stored service credential",i.credentialCount===1?"":"s",i.credentialIds.length>0&&s.jsxs("span",{style:{color:"var(--text-tertiary)",fontSize:"0.825rem"},children:[" ","(",i.credentialIds.slice(0,5).join(", "),i.credentialIds.length>5?`, +${i.credentialIds.length-5} more`:"",")"]})]}),s.jsxs("li",{children:[i.serviceCount," configured integration",i.serviceCount===1?"":"s"]}),s.jsx("li",{children:"The local E2EE keypair (a new one will be generated for this account)"}),s.jsx("li",{children:"Any unsynchronised gate content stored locally"})]}),s.jsx("p",{style:{fontSize:"0.875rem",color:"var(--text-secondary)",marginBottom:"1rem"},children:"Mandates and tickets on the Authority Server are NOT affected — only this gateway's local state is wiped."}),s.jsx("p",{style:{fontSize:"0.825rem",color:"var(--text-tertiary)",marginBottom:"1rem"},children:"If this isn't what you wanted, cancel and sign back in with the original API key, or use a different gateway instance for this account."}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem",justifyContent:"flex-end"},children:[s.jsx("button",{className:"btn btn-ghost",onClick:f,disabled:r,children:"Cancel"}),s.jsx("button",{className:"btn btn-secondary",style:{color:"var(--danger, #e53e3e)"},onClick:d,disabled:r,children:r?"Signing in...":"Wipe local data and sign in"})]})]})})]})}function Cv(){const{setActiveContext:e}=Fe(),t=nn(),[n,r]=u.useState(""),[a,o]=u.useState(""),[i,l]=u.useState(""),[c,d]=u.useState(!1),f=async()=>{if(n.trim()){d(!0),l("");try{const m=await T.joinGroup(n.trim());e(m,m.myDomains[0]||""),t("/")}catch(m){l(m instanceof Error?m.message:"Failed to join group")}finally{d(!1)}}},p=async()=>{if(a.trim()){d(!0),l("");try{const m=await T.createGroup(a.trim());e(m,m.myDomains[0]||""),t("/")}catch(m){l(m instanceof Error?m.message:"Failed to create group")}finally{d(!1)}}};return s.jsxs(s.Fragment,{children:[s.jsx(Bl,{}),s.jsx("div",{className:"main-content no-sidebar",style:{marginTop:"var(--nav-height)"},children:s.jsxs("div",{style:{maxWidth:"30rem",margin:"3rem auto",padding:"0 1rem"},children:[s.jsxs("div",{style:{textAlign:"center",marginBottom:"2.5rem"},children:[s.jsx("h2",{style:{fontSize:"1.5rem",marginBottom:"0.5rem"},children:"Join Your Team"}),s.jsx("p",{style:{fontSize:"0.9rem",color:"var(--text-secondary)",lineHeight:1.6},children:"Join an existing team or create a new one to share authority across domains."})]}),i&&s.jsx("div",{className:"error-message",children:i}),s.jsxs("div",{className:"card",style:{marginBottom:"1rem"},children:[s.jsx("h4",{style:{fontSize:"0.95rem",marginBottom:"0.25rem"},children:"Join an existing group"}),s.jsx("p",{style:{fontSize:"0.825rem",color:"var(--text-secondary)",marginBottom:"1rem"},children:"Ask your team admin for an invite code."}),s.jsxs("div",{className:"invite-input-row",children:[s.jsx("input",{className:"form-input",placeholder:"Paste invite code...",value:n,onChange:m=>r(m.target.value),onKeyDown:m=>m.key==="Enter"&&f(),style:{fontFamily:"'SF Mono', Monaco, monospace",fontSize:"0.85rem"},disabled:c}),s.jsx("button",{className:"btn btn-primary",onClick:f,disabled:c,children:"Join"})]})]}),s.jsxs("div",{className:"card",children:[s.jsx("h4",{style:{fontSize:"0.95rem",marginBottom:"0.25rem"},children:"Create a new group"}),s.jsx("p",{style:{fontSize:"0.825rem",color:"var(--text-secondary)",marginBottom:"1rem"},children:"Start a new team and invite members. Assign domains after creation."}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[s.jsx("input",{className:"form-input",placeholder:"Group name (e.g., Acme Corp)",value:a,onChange:m=>o(m.target.value),onKeyDown:m=>m.key==="Enter"&&p(),style:{flex:1},disabled:c}),s.jsx("button",{className:"btn btn-secondary",onClick:p,disabled:c,children:"Create"})]})]})]})})]})}const Pi="suveren-setup-ai-skipped",_i="suveren-setup-agent-done",Ai="suveren-setup-dismissed",Nv={"hap-setup-ai-skipped":Pi,"hap-setup-agent-done":_i,"hap-setup-dismissed":Ai};function Ev(){for(const[e,t]of Object.entries(Nv)){const n=localStorage.getItem(e);n!==null&&localStorage.getItem(t)===null&&localStorage.setItem(t,n),n!==null&&localStorage.removeItem(e)}}Ev();const _o={"claude-code":{label:"Claude Code",snippet:e=>JSON.stringify({mcpServers:{"suveren-gateway":{url:`${e}/sse`}}},null,2)},"claude-desktop":{label:"Claude Desktop",snippet:e=>`Add to ~/Library/Application Support/Claude/claude_desktop_config.json:
54
+ <circle cx="103" cy="103" r="25" fill="${yv}"/>
55
+ <style>.m{stroke:#111111;stroke-width:${gv};fill:none;stroke-linecap:round}@media (prefers-color-scheme:dark){.m{stroke:#ffffff;stroke-width:13.3}}</style>
56
+ </svg>`;return`data:image/svg+xml,${encodeURIComponent(e)}`}function wv(){return document.querySelector('link[rel="icon"]')}function hm(e){const t=Wl(e);document.title=vv(t),gm(t);const n=wv();if(!n)return;const r=t>0?xv():pv;n.getAttribute("href")!==r&&n.setAttribute("href",r)}function Sv(){hm(0)}function gm(e,t=globalThis.navigator){var a;if(!t||typeof t.setAppBadge!="function")return;const n=Wl(e),r=n>0?t.setAppBadge(n):t.clearAppBadge?t.clearAppBadge():t.setAppBadge(0);(a=r==null?void 0:r.catch)==null||a.call(r,()=>{})}function jv(){const e=pm();return u.useEffect(()=>{hm(e)},[e]),u.useEffect(()=>Sv,[]),null}const ym="suveren:dockBadgePrompt";function kv(){var r;if(typeof window>"u"||!("Notification"in window)||!("setAppBadge"in navigator)||!(((r=window.matchMedia)==null?void 0:r.call(window,"(display-mode: standalone)").matches)||navigator.standalone===!0))return!1;const t=navigator.userAgent;if(!(/Safari\//.test(t)&&!/Chrome\/|Chromium\/|Edg\//.test(t))||Notification.permission!=="default")return!1;try{if(localStorage.getItem(ym))return!1}catch{}return!0}function bv(){const[e,t]=u.useState(!1),n=pm();if(u.useEffect(()=>{t(kv())},[]),!e)return null;const r=()=>{try{localStorage.setItem(ym,"1")}catch{}t(!1)},a=async()=>{try{await Notification.requestPermission()==="granted"&&gm(n)}catch{}r()};return s.jsxs("div",{className:"hint-box",style:{marginBottom:"1rem",alignItems:"center"},children:[s.jsxs("div",{className:"hint-body",children:[s.jsx("div",{className:"hint-head",children:"Show waiting approvals on the Dock icon"}),"Safari needs your permission once. The icon then shows how many approvals are waiting, and nothing else."]}),s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:a,children:"Allow"}),s.jsx("button",{type:"button",className:"btn btn-ghost btn-sm",onClick:r,"aria-label":"Not now",children:"Not now"})]})}function Cv(){const[e,t]=u.useState(!1);return s.jsxs(Xy,{children:[s.jsx(jv,{}),s.jsx(Bl,{onMenuToggle:()=>t(!e)}),s.jsx(um,{}),s.jsx(fm,{}),s.jsx(nv,{}),s.jsx(dv,{open:e,onClose:()=>t(!1)}),s.jsx("div",{className:"main-content",children:s.jsxs("div",{className:"page-inner",children:[s.jsx(bv,{}),s.jsx(ry,{})]})})]})}function Nv(){const[e,t]=u.useState(""),{login:n,isLoading:r,error:a,clearError:o}=Fe(),[i,l]=u.useState(null),c=async()=>{if(e.trim()){o();try{await n(e)}catch(p){if(p instanceof nm){l(p.summary);return}}}},d=async()=>{l(null),o();try{await n(e,{confirmWipe:!0})}catch{}},f=()=>{l(null)};return s.jsxs(s.Fragment,{children:[s.jsx(Bl,{}),s.jsx(um,{}),s.jsx(fm,{}),s.jsxs("div",{className:"login-split",children:[s.jsx("div",{className:"login-split-left",children:s.jsxs("div",{style:{maxWidth:"28rem"},children:[s.jsx("h1",{style:{fontSize:"clamp(2.25rem, 4vw, 3.25rem)",letterSpacing:"-0.03em",lineHeight:1.1,marginBottom:"1.25rem"},children:"Your agents, your intent, your rules."}),s.jsx("p",{style:{fontSize:"1.125rem",color:"var(--text-secondary)",lineHeight:1.6,marginBottom:"3rem"},children:"The gateway runs on your machine, between your agents and the tools they use. Your signature. Your bounds. Your tickets."})]})}),s.jsx("div",{className:"login-split-right",children:s.jsxs("div",{style:{width:"100%",maxWidth:"24rem"},children:[s.jsxs("div",{style:{textAlign:"center",marginBottom:"2.5rem"},children:[s.jsx("div",{style:{fontSize:"1.75rem",fontWeight:700,marginBottom:"0.5rem"},children:"Sign In"}),s.jsx("div",{style:{fontSize:"0.95rem",color:"var(--text-secondary)",lineHeight:1.5},children:"Enter your API key to manage mandates."})]}),a&&s.jsx("div",{className:"error-message",children:a}),s.jsxs("div",{className:"form-group",style:{marginBottom:"1.5rem"},children:[s.jsx("label",{className:"form-label",children:"API Key"}),s.jsx("input",{className:"form-input",type:"password",placeholder:"hap_sk_...",value:e,onChange:p=>t(p.target.value),onKeyDown:p=>p.key==="Enter"&&c(),disabled:r,style:{padding:"0.75rem"}}),s.jsx("div",{className:"form-hint",children:"From your Suveren account."})]}),s.jsx("button",{className:"btn btn-primary btn-full btn-lg",onClick:c,disabled:r,style:{marginBottom:"2rem"},children:r?"Signing in...":"Sign In"}),s.jsx("div",{className:"login-divider",children:"New here?"}),s.jsxs("div",{style:{textAlign:"center",marginBottom:"2.5rem"},children:[s.jsxs("p",{style:{fontSize:"0.9rem",color:"var(--text-secondary)",marginBottom:"1rem",lineHeight:1.5},children:["Create an account on Suveren,",s.jsx("br",{}),"then come back to sign in."]}),s.jsx("a",{href:"https://www.suveren.ai/get-started",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-full",style:{textDecoration:"none"},children:"Create Account"})]}),s.jsxs("div",{style:{paddingTop:"1.75rem",borderTop:"1px solid var(--border)"},children:[s.jsx("div",{style:{fontSize:"0.75rem",fontWeight:600,color:"var(--text-tertiary)",marginBottom:"0.875rem"},children:"Getting started"}),s.jsx("div",{style:{fontSize:"0.85rem",color:"var(--text-secondary)",lineHeight:1.8},children:[s.jsxs(s.Fragment,{children:["Create an account at ",s.jsx("a",{href:"https://www.suveren.ai/get-started",target:"_blank",rel:"noopener noreferrer",style:{color:"var(--accent)"},children:"Suveren"})]}),"Join or create a team to get domain authority","Sign in here with your API key to start giving mandates"].map((p,m)=>s.jsxs("div",{style:{display:"flex",gap:"0.625rem",alignItems:"baseline",marginBottom:m<2?"0.5rem":0},children:[s.jsxs("span",{style:{color:"var(--accent)",fontWeight:700,fontSize:"0.95rem"},children:[m+1,"."]}),p]},m))})]})]})})]}),i&&s.jsx("div",{role:"dialog","aria-modal":"true","aria-labelledby":"wipe-warning-title",style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.5)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3,padding:"1rem"},onClick:f,children:s.jsxs("div",{className:"card",onClick:p=>p.stopPropagation(),style:{maxWidth:520,width:"100%",margin:0},children:[s.jsx("h3",{id:"wipe-warning-title",className:"card-title",style:{marginBottom:"0.5rem"},children:"Sign in with a different account?"}),s.jsxs("p",{style:{fontSize:"0.875rem",color:"var(--text-secondary)",marginBottom:"0.75rem"},children:["This gateway already holds data for another account. Signing in with this API key will ",s.jsx("strong",{children:"permanently wipe"})," the following local data:"]}),s.jsxs("ul",{style:{fontSize:"0.875rem",color:"var(--text-secondary)",marginBottom:"1rem",paddingLeft:"1.25rem",lineHeight:1.6},children:[s.jsxs("li",{children:[i.credentialCount," stored service credential",i.credentialCount===1?"":"s",i.credentialIds.length>0&&s.jsxs("span",{style:{color:"var(--text-tertiary)",fontSize:"0.825rem"},children:[" ","(",i.credentialIds.slice(0,5).join(", "),i.credentialIds.length>5?`, +${i.credentialIds.length-5} more`:"",")"]})]}),s.jsxs("li",{children:[i.serviceCount," configured integration",i.serviceCount===1?"":"s"]}),s.jsx("li",{children:"The local E2EE keypair (a new one will be generated for this account)"}),s.jsx("li",{children:"Any unsynchronised gate content stored locally"})]}),s.jsx("p",{style:{fontSize:"0.875rem",color:"var(--text-secondary)",marginBottom:"1rem"},children:"Mandates and tickets on the Authority Server are NOT affected — only this gateway's local state is wiped."}),s.jsx("p",{style:{fontSize:"0.825rem",color:"var(--text-tertiary)",marginBottom:"1rem"},children:"If this isn't what you wanted, cancel and sign back in with the original API key, or use a different gateway instance for this account."}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem",justifyContent:"flex-end"},children:[s.jsx("button",{className:"btn btn-ghost",onClick:f,disabled:r,children:"Cancel"}),s.jsx("button",{className:"btn btn-secondary",style:{color:"var(--danger, #e53e3e)"},onClick:d,disabled:r,children:r?"Signing in...":"Wipe local data and sign in"})]})]})})]})}function Ev(){const{setActiveContext:e}=Fe(),t=nn(),[n,r]=u.useState(""),[a,o]=u.useState(""),[i,l]=u.useState(""),[c,d]=u.useState(!1),f=async()=>{if(n.trim()){d(!0),l("");try{const m=await T.joinGroup(n.trim());e(m,m.myDomains[0]||""),t("/")}catch(m){l(m instanceof Error?m.message:"Failed to join group")}finally{d(!1)}}},p=async()=>{if(a.trim()){d(!0),l("");try{const m=await T.createGroup(a.trim());e(m,m.myDomains[0]||""),t("/")}catch(m){l(m instanceof Error?m.message:"Failed to create group")}finally{d(!1)}}};return s.jsxs(s.Fragment,{children:[s.jsx(Bl,{}),s.jsx("div",{className:"main-content no-sidebar",style:{marginTop:"var(--nav-height)"},children:s.jsxs("div",{style:{maxWidth:"30rem",margin:"3rem auto",padding:"0 1rem"},children:[s.jsxs("div",{style:{textAlign:"center",marginBottom:"2.5rem"},children:[s.jsx("h2",{style:{fontSize:"1.5rem",marginBottom:"0.5rem"},children:"Join Your Team"}),s.jsx("p",{style:{fontSize:"0.9rem",color:"var(--text-secondary)",lineHeight:1.6},children:"Join an existing team or create a new one to share authority across domains."})]}),i&&s.jsx("div",{className:"error-message",children:i}),s.jsxs("div",{className:"card",style:{marginBottom:"1rem"},children:[s.jsx("h4",{style:{fontSize:"0.95rem",marginBottom:"0.25rem"},children:"Join an existing group"}),s.jsx("p",{style:{fontSize:"0.825rem",color:"var(--text-secondary)",marginBottom:"1rem"},children:"Ask your team admin for an invite code."}),s.jsxs("div",{className:"invite-input-row",children:[s.jsx("input",{className:"form-input",placeholder:"Paste invite code...",value:n,onChange:m=>r(m.target.value),onKeyDown:m=>m.key==="Enter"&&f(),style:{fontFamily:"'SF Mono', Monaco, monospace",fontSize:"0.85rem"},disabled:c}),s.jsx("button",{className:"btn btn-primary",onClick:f,disabled:c,children:"Join"})]})]}),s.jsxs("div",{className:"card",children:[s.jsx("h4",{style:{fontSize:"0.95rem",marginBottom:"0.25rem"},children:"Create a new group"}),s.jsx("p",{style:{fontSize:"0.825rem",color:"var(--text-secondary)",marginBottom:"1rem"},children:"Start a new team and invite members. Assign domains after creation."}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[s.jsx("input",{className:"form-input",placeholder:"Group name (e.g., Acme Corp)",value:a,onChange:m=>o(m.target.value),onKeyDown:m=>m.key==="Enter"&&p(),style:{flex:1},disabled:c}),s.jsx("button",{className:"btn btn-secondary",onClick:p,disabled:c,children:"Create"})]})]})]})})]})}const Pi="suveren-setup-ai-skipped",_i="suveren-setup-agent-done",Ai="suveren-setup-dismissed",Tv={"hap-setup-ai-skipped":Pi,"hap-setup-agent-done":_i,"hap-setup-dismissed":Ai};function Iv(){for(const[e,t]of Object.entries(Tv)){const n=localStorage.getItem(e);n!==null&&localStorage.getItem(t)===null&&localStorage.setItem(t,n),n!==null&&localStorage.removeItem(e)}}Iv();const _o={"claude-code":{label:"Claude Code",snippet:e=>JSON.stringify({mcpServers:{"suveren-gateway":{url:`${e}/sse`}}},null,2)},"claude-desktop":{label:"Claude Desktop",snippet:e=>`Add to ~/Library/Application Support/Claude/claude_desktop_config.json:
57
57
 
58
58
  ${JSON.stringify({mcpServers:{"suveren-gateway":{url:`${e}/sse`}}},null,2)}`},other:{label:"Other",snippet:e=>`Streamable HTTP: POST ${e}/mcp
59
59
  SSE transport: GET ${e}/sse
60
- Health check: GET ${e}/health`}};function Tv({aiConfigured:e,hasRunningIntegration:t,hasActiveAuth:n,hasAgentConnected:r,mcpEndpoint:a}){const[o,i]=u.useState(()=>localStorage.getItem(Pi)==="true"),[l,c]=u.useState(()=>localStorage.getItem(_i)==="true"),[d,f]=u.useState(()=>localStorage.getItem(Ai)==="true"),[p,m]=u.useState(null),[w,v]=u.useState("claude-code"),[x,k]=u.useState(!1),g=[{label:"AI Assistant",detail:"A trusted AI helps you think through mandates — surfacing risks and asking the right questions.",to:"/settings",status:e?"done":o?"skipped":"pending",optional:!0},{label:"Connect a service",to:"/integrations",status:t?"done":"pending"},{label:"Give your agent a mandate",to:"/mandates?new=1",status:n?"done":"pending"},{label:"Connect your agent",status:r||l?"done":"pending"}],h=g.filter(E=>E.status==="done"||E.status==="skipped").length,y=h===g.length,S=u.useCallback(()=>{localStorage.setItem(Pi,"true"),i(!0)},[]),b=u.useCallback(()=>{localStorage.setItem(_i,"true"),c(!0),m(null)},[]),N=u.useCallback(()=>{localStorage.setItem(Ai,"true"),f(!0)},[]),C=u.useCallback(async E=>{try{await navigator.clipboard.writeText(E),k(!0),setTimeout(()=>k(!1),2e3)}catch{}},[]);if(d||y)return null;const I=g.findIndex(E=>E.status==="pending");return s.jsxs("div",{style:{border:"2px solid var(--accent)",borderRadius:"0.75rem",padding:"1.5rem",marginBottom:"1.5rem",background:"var(--bg-elevated)"},children:[s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",marginBottom:"1.25rem"},children:[s.jsx("h2",{style:{fontSize:"1.1rem",fontWeight:700,margin:0},children:"Get Started"}),s.jsx("button",{onClick:N,style:{background:"none",border:"none",color:"var(--text-tertiary)",cursor:"pointer",fontSize:"1.1rem",padding:"0 0.25rem",lineHeight:1},title:"Hide setup guide",children:"×"})]}),s.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem"},children:g.map((E,$)=>{const U=$===I,V=E.status==="done"||E.status==="skipped"?"●":"○",J=E.status==="done"?"var(--success)":E.status==="skipped"?"var(--text-tertiary)":U?"var(--accent)":"var(--text-tertiary)";return s.jsxs("div",{children:[s.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"0.75rem",padding:U?"0.75rem":"0.25rem 0",borderRadius:U?"0.5rem":void 0,background:U?"var(--accent-subtle)":void 0},children:[s.jsx("span",{style:{color:J,fontSize:"0.75rem",marginTop:"0.2rem",flexShrink:0},children:V}),s.jsxs("div",{style:{flex:1,minWidth:0},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[E.to&&E.status==="pending"?s.jsx(Ye,{to:E.to,style:{fontSize:"0.9rem",fontWeight:U?600:500,color:U?"var(--accent)":"var(--text-primary)",textDecoration:"none"},children:E.label}):E.status==="pending"&&$===3?s.jsx("button",{onClick:()=>m(p===3?null:3),style:{background:"none",border:"none",padding:0,cursor:"pointer",fontSize:"0.9rem",fontWeight:U?600:500,color:U?"var(--accent)":"var(--text-primary)"},children:E.label}):s.jsx("span",{style:{fontSize:"0.9rem",fontWeight:500,color:E.status==="done"?"var(--text-secondary)":"var(--text-tertiary)"},children:E.label}),E.optional&&E.status==="pending"&&s.jsx("span",{style:{fontSize:"0.7rem",color:"var(--text-tertiary)",fontStyle:"italic"},children:"optional"}),E.status==="skipped"&&s.jsx("span",{style:{fontSize:"0.7rem",color:"var(--text-tertiary)"},children:"skipped"})]}),E.detail&&E.status==="pending"&&U&&s.jsx("div",{style:{fontSize:"0.8rem",color:"var(--text-secondary)",marginTop:"0.25rem",lineHeight:1.5},children:E.detail})]}),E.optional&&E.status==="pending"&&s.jsx("button",{onClick:S,style:{background:"none",border:"none",color:"var(--text-tertiary)",cursor:"pointer",fontSize:"0.75rem",padding:"0.125rem 0.5rem",flexShrink:0},children:"Skip"}),E.to&&E.status==="pending"&&s.jsx(Ye,{to:E.to,style:{color:"var(--text-tertiary)",textDecoration:"none",fontSize:"0.8rem",flexShrink:0},children:"›"})]}),$===3&&p===3&&s.jsxs("div",{style:{marginTop:"0.75rem",marginLeft:"1.5rem",padding:"1rem",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"0.5rem"},children:[s.jsx("div",{style:{fontSize:"0.8rem",fontWeight:600,marginBottom:"0.75rem",color:"var(--text-primary)"},children:"MCP Endpoint"}),s.jsx("div",{style:{fontFamily:"monospace",fontSize:"0.85rem",padding:"0.5rem 0.75rem",background:"var(--bg-elevated)",border:"1px solid var(--border)",borderRadius:"0.375rem",marginBottom:"1rem",wordBreak:"break-all"},children:a}),s.jsx("div",{style:{display:"flex",gap:"0.25rem",marginBottom:"0.75rem"},children:Object.entries(_o).map(([D,_])=>s.jsx("button",{onClick:()=>v(D),style:{padding:"0.375rem 0.75rem",fontSize:"0.75rem",fontWeight:w===D?600:400,background:w===D?"var(--accent-subtle)":"transparent",color:w===D?"var(--accent)":"var(--text-secondary)",border:`1px solid ${w===D?"var(--accent)":"var(--border)"}`,borderRadius:"0.375rem",cursor:"pointer"},children:_.label},D))}),s.jsx("pre",{style:{fontFamily:"monospace",fontSize:"0.78rem",lineHeight:1.6,padding:"0.75rem",background:"var(--bg-elevated)",border:"1px solid var(--border)",borderRadius:"0.375rem",overflow:"auto",whiteSpace:"pre-wrap",margin:0,marginBottom:"0.75rem"},children:_o[w].snippet(a)}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>C(_o[w].snippet(a)),children:x?"Copied":"Copy"}),s.jsx("button",{className:"btn btn-primary btn-sm",onClick:b,children:"Done"})]})]})]},$)})}),s.jsxs("div",{style:{marginTop:"1.25rem"},children:[s.jsx("div",{style:{height:"4px",background:"var(--border)",borderRadius:"2px",overflow:"hidden"},children:s.jsx("div",{style:{height:"100%",width:`${h/g.length*100}%`,background:"var(--accent)",borderRadius:"2px",transition:"width 0.3s ease"}})}),s.jsxs("div",{style:{fontSize:"0.7rem",color:"var(--text-tertiary)",marginTop:"0.375rem"},children:[h," of ",g.length," complete"]})]})]})}function _n({variant:e="base",style:t,className:n,...r}){const a=e==="title"?"skeleton skeleton-title":e==="line"?"skeleton skeleton-line":e==="line-sm"?"skeleton skeleton-line-sm":"skeleton";return s.jsx("span",{className:`${a}${n?` ${n}`:""}`,style:t,role:"status","aria-busy":"true","aria-label":r["aria-label"]??"Loading"})}function Ao(){return s.jsxs("div",{className:"skeleton-card",role:"status","aria-busy":"true","aria-label":"Loading",children:[s.jsx(_n,{style:{width:"0.5rem",height:"0.5rem",borderRadius:"50%",flexShrink:0}}),s.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",gap:"0.35rem"},children:[s.jsx(_n,{variant:"line",style:{width:"35%"}}),s.jsx(_n,{variant:"line-sm",style:{width:"65%"}})]})]})}const Iv={gmail:"Gmail",calendar:"Google Calendar",crm:"CRM",linkedin:"LinkedIn",records:"Records",mollie:"Mollie"},vm=e=>Iv[e]??e,Rv={resource:{chip:"Restricted",sev:"warn"},spam:{chip:"Spam / Trash",sev:"info"},age:{chip:"Too old",sev:"warn"},unset_age:{chip:"Needs setup",sev:"act",fixTo:"/integrations"},read_gate:{chip:"Not granted",sev:"act",fixTo:"/mandates"},ungoverned:{chip:"Unconfigured",sev:"act"},query_unsafe:{chip:"Unsafe search",sev:"info"}};function Pv(e){return Rv[e]??{chip:"Blocked",sev:"info"}}function _v(e){const t=vm(e.integrationId);switch(e.reason){case"resource":return e.integrationId==="calendar"?s.jsxs(s.Fragment,{children:["Tried to read your ",s.jsx("b",{children:e.target??"restricted"})," calendar"]}):s.jsxs(s.Fragment,{children:["Tried to read a restricted location in ",t]});case"spam":return s.jsxs(s.Fragment,{children:["Tried to open a message in ",s.jsx("b",{children:"spam or trash"})]});case"age":return s.jsxs(s.Fragment,{children:["Tried to read ",t," older than your read window"]});case"unset_age":return s.jsxs(s.Fragment,{children:["Your ",t," has ",s.jsx("b",{children:"no read window set"}),", so reads are blocked"]});case"read_gate":return s.jsxs(s.Fragment,{children:["Read access isn't granted on your ",t," mandate"]});case"ungoverned":return s.jsxs(s.Fragment,{children:["A ",t," tool isn't configured for safe reading"]});case"query_unsafe":return s.jsx(s.Fragment,{children:"A search couldn't be safely limited and was refused"});default:return s.jsx(s.Fragment,{children:e.detail})}}function Av(e,t){const n=Math.max(0,(t-e)/1e3);if(n<60)return"Just now";if(n<3600)return`${Math.floor(n/60)} min ago`;if(n<86400)return`${Math.floor(n/3600)} hr ago`;const r=Math.floor(n/86400);return r===1?"Yesterday":`${r} days ago`}const uu=5,zv=24*60*60*1e3,sa=7;function $v(e,t){const n=t-sa*zv;return{recent:e.filter(r=>r.ts>=n),all:e}}function Lv(){const[e,t]=u.useState(null),[n,r]=u.useState(!1),[a,o]=u.useState(!1),i=u.useCallback(()=>{T.getDenials({limit:200}).then(({records:m})=>{t(m),o(!1)}).catch(()=>o(!0))},[]);if(u.useEffect(()=>{i()},[i]),Pt(i,12e4),a||e===null)return null;const{recent:l,all:c}=$v(e,Date.now()),d=n?c:l.slice(0,uu),f=c.length-l.length,p=(m,w)=>{const v=Pv(m.reason);return s.jsxs("div",{className:"rb-row",children:[s.jsx("span",{className:`rb-dot ${v.sev==="act"?"act":v.sev==="info"?"info":""}`,"aria-hidden":"true"}),s.jsxs("div",{className:"rb-body",children:[s.jsx("div",{className:"rb-line",children:_v(m)}),s.jsxs("div",{className:"rb-meta",children:[s.jsx("span",{className:`rb-chip ${v.sev==="act"?"act":v.sev==="warn"?"warn":""}`,children:v.chip}),s.jsx("span",{className:"rb-via",children:vm(m.integrationId)})]}),v.fixTo&&s.jsx(Ye,{className:"rb-fix",to:v.fixTo,children:"Set a read window →"})]}),s.jsx("div",{className:"rb-when",children:Av(m.ts,Date.now())})]},`${m.ts}-${w}`)};return s.jsxs("section",{className:"card recent-blocks","aria-label":"Recent blocks",style:{marginTop:"1.5rem"},children:[s.jsxs("div",{className:"card-header",children:[s.jsx("h2",{className:"card-title",children:"Recent blocks"}),(n?c.length:l.length)>0&&s.jsx("span",{className:"rb-count",children:n?c.length:l.length})]}),d.length===0?s.jsxs("div",{className:"rb-empty",children:[s.jsx("span",{className:"rb-mark","aria-hidden":"true",children:s.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round",children:s.jsx("path",{d:"M20 6 9 17l-5-5"})})}),s.jsxs("h3",{children:["Nothing blocked in the last ",sa," days"]}),s.jsx("p",{children:"Your agent has stayed within every limit you set."}),f>0&&s.jsxs("button",{className:"rb-viewall",type:"button",onClick:()=>r(!0),children:["Show the last 30 days (",f,")"]})]}):s.jsxs(s.Fragment,{children:[s.jsxs("p",{className:"rb-sub",children:[n?"Last 30 days. ":`Last ${sa} days. `,"Limits you set that stopped your agent. Seeing them here means the gateway is doing its job."]}),s.jsx("div",{className:"rb-rows",children:d.map(p)}),!n&&c.length>d.length&&s.jsx("div",{className:"rb-foot",children:s.jsxs("button",{className:"rb-viewall",type:"button",onClick:()=>r(!0),children:["View all ",c.length," blocks from the last 30 days"]})}),n&&c.length>Math.min(l.length,uu)&&s.jsx("div",{className:"rb-foot",children:s.jsxs("button",{className:"rb-viewall",type:"button",onClick:()=>r(!1),children:["Show only the last ",sa," days"]})})]})]})}function Mv(){const[e,t]=u.useState([]);return Pt(async()=>{try{const{skipped:r}=await T.getSkippedCommitments();t(r)}catch{}},3e4),e.length===0?null:s.jsxs("div",{className:"card",style:{padding:"1.5rem",marginTop:"1.5rem",borderLeft:"3px solid var(--warn, #b58900)"},children:[s.jsxs("h2",{style:{fontSize:"1rem",fontWeight:700,margin:0},children:["Approved, but not run here (",e.length,")"]}),s.jsx("p",{style:{margin:"0.5rem 0 1rem",fontSize:"0.9rem",color:"var(--text-secondary)"},children:"These were approved, but this gateway has no local record of asking for them — usually because a different device/installation of yours submitted them, or its local record is gone. Re-run the same request on this gateway to execute it here."}),s.jsx("ul",{style:{margin:0,paddingLeft:"1.25rem",fontSize:"0.9rem"},children:e.map(r=>s.jsxs("li",{style:{marginBottom:"0.35rem"},children:[s.jsx("code",{children:r.tool})," ",s.jsxs("span",{style:{color:"var(--text-tertiary)"},children:["(",r.id,")"]})]},r.id))})]})}function Fv(e,t){const n=e.simulation;return n?(((t==null?void 0:t[n.field])??"").trim().toLowerCase()||n.default.trim().toLowerCase())==="simulation":!1}function zi(e){return!!(e!=null&&e.simulation)}function Ov(e){var n;const t=[];for(const r of e)r.state==="error"?t.push({label:"Integration error",detail:(n=r.integration)!=null&&n.error?`${r.manifest.name}: ${r.integration.error}`:`${r.manifest.name} is not running`,to:"/integrations",color:"var(--danger)"}):r.state==="not-running"&&(zi(r.manifest)?t.push({label:`${r.manifest.name} is not running`,detail:"Activate it to use it in the test.",to:"/integrations",color:"var(--danger)"}):t.push({label:"Integration stopped",detail:`${r.manifest.name} is not running`,to:"/integrations",color:"var(--danger)"}));return t}function Bv(e){const t=e.filter(n=>n.state==="paused");return t.length===0?null:{count:t.length,namesText:t.map(n=>n.manifest.name).join(", ")}}const Dv=30*60;function zo(e){return e.replace(/@.*$/,"").split("/").pop()??e}function Uv(){const{domain:e}=Fe(),[t,n]=u.useState([]),[r,a]=u.useState([]),[o,i]=u.useState([]),[l,c]=u.useState(!0),[d,f]=u.useState(!1),[p,m]=u.useState([]),[w,v]=u.useState(!1),[x,k]=u.useState(!1),{entries:g,activeSessions:h,loading:y}=Ul(),S=!y,b=u.useCallback(()=>{T.getMyAttestations().then(B=>{n(B),f(!0)}).catch(()=>f(!0)),T.getArchivedMandates().then(m).catch(()=>m([])),T.getProposals(e||"owner").then(B=>{a(B),v(!0)}).catch(()=>v(!0)),T.getProposalsForApprover().then(B=>i(B)).catch(()=>i([])),T.getCredential("ai-config").then(B=>{c(B.configured),k(!0)}).catch(()=>k(!0))},[e]);fe("attestation-changed",b),fe("proposal-added",b),fe("proposal-resolved",b),fe("proposal-approved",b),fe("proposal-rejected",b),Pt(b,3e5,e);const N=d&&w&&x&&S,C=lm(t,{archivedSet:new Set(p)}),I=C.active,E=C.expired,$=I.filter(B=>B.remaining_seconds!==null&&B.remaining_seconds<=Dv),U=r.filter(mm),V=g.filter(B=>B.state==="running"),J=g.filter(B=>B.state==="starting"),D=Bv(g),_=[];for(const B of o)_.push({label:"Approval needed",detail:`${B.tool} — above-cap action under ${zo(B.profileId)}`,to:"/approvals",color:"var(--warning)"});for(const B of U)_.push({label:"Approval pending",detail:`${B.tool} awaiting your approval`,to:"/approvals",color:"var(--warning)"});for(const B of $){const ne=Math.ceil((B.remaining_seconds??0)/60);_.push({label:"Expiring soon",detail:`${B.title??zo(B.profile_id)} — ${ne} min remaining`,to:"/mandates",color:"var(--warning)"})}for(const B of E)_.push({label:"Expired",detail:B.title??zo(B.profile_id),to:"/mandates",color:"var(--danger)"});_.push(...Ov(g));for(const B of J)_.push({label:"Integration starting",detail:`${B.manifest.name} is coming up…`,to:"/integrations",color:"var(--warning)"});for(const B of g)B.authStatus==="failed"&&B.state!=="not-running"&&B.state!=="error"&&B.state!=="paused"&&_.push({label:"Reconnect needed",detail:`${B.manifest.name}: authorization expired — reconnect to restore access`,to:"/integrations",color:"var(--danger)"});return l||_.push({label:"AI Assistant",detail:"Not configured — needed for gate advisory",to:"/settings",color:"var(--text-tertiary)"}),s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"page-header",children:s.jsx("h1",{className:"page-title",children:"Dashboard"})}),N&&s.jsx(Tv,{aiConfigured:l,hasRunningIntegration:V.length>0,hasActiveAuth:I.length>0,hasAgentConnected:h>0,mcpEndpoint:`http://localhost:${window.location.port==="3400"?"3430":"7430"}`}),s.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(8rem, 1fr))",gap:"0.75rem",marginBottom:"1.5rem"},children:[s.jsx(Ye,{to:"/mandates",style:{textDecoration:"none"},children:s.jsxs("div",{className:"card",style:{padding:"1rem",textAlign:"center"},children:[d?s.jsx("div",{style:{fontSize:"1.5rem",fontWeight:700,color:I.length>0?"var(--success)":"var(--text-tertiary)"},children:I.length}):s.jsx(_n,{variant:"title"}),s.jsx("div",{style:{fontSize:"0.75rem",color:"var(--text-secondary)"},children:"Active"})]})}),s.jsx(Ye,{to:"/approvals",style:{textDecoration:"none"},children:s.jsxs("div",{className:"card",style:{padding:"1rem",textAlign:"center"},children:[w?s.jsx("div",{style:{fontSize:"1.5rem",fontWeight:700,color:U.length>0?"var(--warning)":"var(--text-tertiary)"},children:U.length}):s.jsx(_n,{variant:"title"}),s.jsx("div",{style:{fontSize:"0.75rem",color:"var(--text-secondary)"},children:"Pending Approvals"})]})}),s.jsx(Ye,{to:"/mandates",style:{textDecoration:"none"},children:s.jsxs("div",{className:"card",style:{padding:"1rem",textAlign:"center"},children:[d?s.jsx("div",{style:{fontSize:"1.5rem",fontWeight:700,color:E.length>0?"var(--danger)":"var(--text-tertiary)"},children:E.length}):s.jsx(_n,{variant:"title"}),s.jsx("div",{style:{fontSize:"0.75rem",color:"var(--text-secondary)"},children:"Expired"})]})}),s.jsx(Ye,{to:"/integrations",style:{textDecoration:"none"},children:s.jsxs("div",{className:"card",style:{padding:"1rem",textAlign:"center"},children:[S?s.jsx("div",{style:{fontSize:"1.5rem",fontWeight:700,color:V.length>0?"var(--success)":"var(--text-tertiary)"},children:V.length}):s.jsx(_n,{variant:"title"}),s.jsx("div",{style:{fontSize:"0.75rem",color:"var(--text-secondary)"},children:"Integrations Running"})]})})]}),s.jsxs("section",{className:"card attention","aria-label":"Needs your attention",children:[s.jsxs("div",{className:"card-header",children:[s.jsx("h2",{className:"card-title",children:"Needs your attention"}),_.length>0&&s.jsx("span",{className:"rb-count",children:_.length})]}),_.length>0?s.jsx("div",{className:"attention-rows",children:_.map((B,ne)=>s.jsxs(Ye,{to:B.to,className:"attention-row",children:[s.jsx("span",{className:"attention-dot",style:{background:B.color},"aria-hidden":"true"}),s.jsxs("div",{style:{flex:1,minWidth:0},children:[s.jsx("div",{style:{fontSize:"0.8rem",fontWeight:600,color:"var(--text-primary)"},children:B.label}),s.jsx("div",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:B.detail})]}),s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-tertiary)"},children:"›"})]},ne))}):N?s.jsxs("div",{className:"all-clear",children:[s.jsx("span",{className:"rb-mark","aria-hidden":"true",children:s.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round",children:s.jsx("path",{d:"M20 6 9 17l-5-5"})})}),s.jsx("h3",{children:"All clear"}),s.jsx("p",{children:"Nothing needs your attention."})]}):s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[s.jsx(Ao,{}),s.jsx(Ao,{}),s.jsx(Ao,{})]})]}),D&&s.jsxs("div",{className:"sim-paused-summary",role:"status",children:[s.jsx("span",{className:"sim-paused-summary-icon","aria-hidden":"true",children:"⏸"}),s.jsxs("span",{children:[s.jsxs("b",{children:[D.count," real system",D.count===1?"":"s"," ",D.count===1?"is":"are"," paused"]})," ","while simulation mode is on — ",D.namesText,"."]})]}),s.jsx(Mv,{}),s.jsx(Lv,{})]})}const Wv=["Scope & Limits","Intent","Sign"];function xm({currentStep:e,onStepClick:t}){const n=nn();return s.jsxs("div",{className:"wizard-progress",children:[s.jsx("ol",{className:"wizard-steps",children:Wv.map((r,a)=>{const o=a+2,i=o<e,l=o===e,c=o-1<e,d=i&&!!t;return s.jsxs("li",{className:`wizard-step${c?" reached":""}`,"aria-current":l?"step":void 0,children:[s.jsx("button",{type:"button",className:`step-circle${i?" completed":""}${l?" current":""}`,onClick:d?()=>t(o):void 0,disabled:!d,"aria-label":`${r}${i?" (done)":l?" (current)":""}`,children:i?"✓":a+1}),s.jsx("span",{className:`step-label-text${l?" current":i?" completed":""}`,children:r})]},o)})}),s.jsx("button",{type:"button",className:"btn btn-ghost btn-sm wizard-cancel",onClick:()=>n("/mandates?new=1"),children:"Cancel"})]})}const Hv=40;function $e(e,t){const n=e.lastIndexOf("/"),r=n>=0?e.slice(n+1):e,a=r.indexOf("@"),o=a>=0?r.slice(0,a):r;return(o.charAt(0).toUpperCase()+o.slice(1)).slice(0,Hv)}function Vv({profileId:e,bounds:t,groupName:n,domain:r,onSwitch:a}){return s.jsxs("div",{className:"context-strip",children:[n&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"context-strip-label",children:"Team:"}),s.jsxs("span",{children:[s.jsx("strong",{children:n}),r?` / ${r}`:""]})]}),e&&s.jsxs("span",{children:[s.jsx("strong",{children:"Profile:"})," ",$e(e)]}),t&&s.jsxs("span",{children:[s.jsx("strong",{children:"Bounds:"})," ",t]}),a&&s.jsx("button",{className:"btn btn-ghost btn-sm",style:{marginLeft:"auto",padding:"0.2rem 0.5rem",fontSize:"0.7rem"},onClick:a,children:"Switch"})]})}function Gv({integrationId:e,field:t,value:n,onChange:r,disabled:a,onLabels:o}){const[i,l]=u.useState(null),[c,d]=u.useState(null),[f,p]=u.useState(!0);u.useEffect(()=>{let v=!1;return T.discoverScopeField(e,t).then(x=>{var k;v||(l(x.options),p(!1),(k=x.options)!=null&&k.length&&(o==null||o(Object.fromEntries(x.options.map(g=>[g.value,g.label])))))}).catch(x=>{v||(d(x instanceof Error?x.message:String(x)),p(!1))}),()=>{v=!0}},[e,t]);const m=new Set(n.split(",").map(v=>v.trim()).filter(Boolean)),w=v=>{const x=new Set(m);x.has(v)?x.delete(v):x.add(v),r(Array.from(x).join(","))};return f?s.jsxs("p",{className:"hint-text",style:{color:"var(--text-tertiary)"},children:["Loading options from ",e,"…"]}):c||!i?s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:{fontSize:"0.8rem",color:"var(--warning)",marginBottom:"0.5rem"},children:["Couldn't fetch options (",c??"no response","). Enter values manually, separated by commas."]}),s.jsx("input",{className:"form-input",type:"text",value:n,onChange:v=>r(v.target.value),disabled:a})]}):i.length===0?s.jsxs("p",{className:"hint-text",style:{color:"var(--text-tertiary)"},children:["No options available from ",e," for this field."]}):s.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.25rem"},children:i.map(v=>{const x=v.extras??{},k=typeof x.access=="string"?x.access:void 0,g=k==="reader",h=x.primary===!0;return s.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem",fontSize:"0.875rem",color:g?"var(--text-tertiary)":"var(--text-primary)",cursor:a||g?"not-allowed":"pointer"},title:g?"Read-only — you can authorize list/read but not writes":void 0,children:[s.jsx("input",{type:"checkbox",checked:m.has(String(v.value)),onChange:()=>w(String(v.value)),disabled:a||g}),s.jsx("span",{children:v.label||v.value}),h&&s.jsx("span",{style:{fontSize:"0.7rem",color:"var(--accent)",textTransform:"uppercase",letterSpacing:"0.04em"},children:"primary"}),k&&s.jsxs("span",{style:{fontSize:"0.7rem",color:"var(--text-tertiary)"},children:["· ",k]})]},v.value)})})}function Hl(e){if(e.type!=="number")return 0;const t=e.boundType,n=e.unit;return(t==null?void 0:t.kind)==="per_transaction"&&n==="count"?1:0}function Kv(e,t){return t!==void 0?String(t):Hl(e)===1?"1":""}function du(e,t){const n=Hl(e);return t===""?n:Math.max(n,Number(t))}function Yv(e){return e.replace(/@.*$/,"").split("/").pop()??e}function Qv(e,t){return t.displayName?t.displayName:e.replace(/_/g," ").replace(/\b\w/g,n=>n.toUpperCase())}function Jv(e){return e.type==="string"&&(e.format==="email"||e.format==="domain")}function Xv(e){var t;return!!(e.enum&&((t=e.constraint)!=null&&t.enforceable.includes("subset")))}function fu(e,t){const n=e.trim();return n?t==="email"?n.includes("@")&&n.indexOf(".",n.indexOf("@"))>-1:t==="domain"?n.includes(".")&&!n.includes("@"):!0:!1}function qv(e){return!e||e==="count"?"":e==="minutes"?"min":e==="hours"?"hr":e==="days"?"days":e==="percent"?"%":e.startsWith("currency:")?e.slice(9):e}function Zv(e){return e?e==="minutes"?15:e==="percent"?5:e.startsWith("currency:")?10:1:1}function ex(e){return e?e==="minutes"?[{value:15,label:"15m"},{value:30,label:"30m"},{value:60,label:"1h"},{value:120,label:"2h"},{value:240,label:"4h"}]:e==="hours"?[{value:1,label:"1h"},{value:4,label:"4h"},{value:8,label:"8h"},{value:24,label:"1d"}]:e==="days"?[{value:1,label:"1d"},{value:7,label:"1w"},{value:30,label:"1mo"},{value:90,label:"3mo"}]:e==="percent"?[{value:10,label:"10%"},{value:25,label:"25%"},{value:50,label:"50%"},{value:100,label:"100%"}]:e.startsWith("currency:")?[{value:10,label:"10"},{value:50,label:"50"},{value:100,label:"100"},{value:500,label:"500"},{value:1e3,label:"1k"}]:[]:[]}function tx(e,t){if(!e||!t)return"";const n=Number(e);if(!Number.isFinite(n)||n<=0)return"";if(t==="minutes"&&n>=60){const r=Math.floor(n/60),a=n%60;return a===0?`${r} hour${r!==1?"s":""}`:`${r}h ${a}m`}if(t==="hours"&&n>=24&&n%24===0){const r=n/24;return`${r} day${r!==1?"s":""}`}if(t==="days"){if(n>=30&&n%30===0)return`${n/30} month${n/30!==1?"s":""}`;if(n>=7&&n%7===0)return`${n/7} week${n/7!==1?"s":""}`}return""}function nx({id:e,value:t,onChange:n,disabled:r,placeholder:a,unit:o,min:i=0}){const l=Zv(o),c=ex(o),d=qv(o),f=tx(t,o),p=t===""?null:Number(t),m=()=>{const v=t===""?0:Number(t),x=v%l,k=x===0?v+l:v+(l-x);n(String(k))},w=()=>{const v=t===""?0:Number(t);if(v<=i)return;const x=v%l,k=x===0?v-l:v-x;n(String(Math.max(i,k)))};return s.jsxs("div",{className:"bounded-input",children:[s.jsxs("div",{className:"bounded-input-field",children:[s.jsx("button",{type:"button",className:"stepper-btn stepper-decrement",onClick:w,disabled:r||t===""||Number(t)<=i,"aria-label":"Decrease",children:"−"}),s.jsx("input",{id:e,className:"stepper-input",type:"number",min:i,step:l,value:t,placeholder:a??String(i),onChange:v=>n(v.target.value),onFocus:v=>v.target.select(),disabled:r}),s.jsx("button",{type:"button",className:"stepper-btn stepper-increment",onClick:m,disabled:r,"aria-label":"Increase",children:"+"}),d&&s.jsx("span",{className:"bounded-input-unit","aria-hidden":"true",children:d})]}),c.length>0&&!r&&s.jsx("div",{className:"bounded-input-presets",role:"group","aria-label":"Quick presets",children:c.map(v=>s.jsx("button",{type:"button",className:`preset-chip${p===v.value?" preset-chip-selected":""}`,onClick:()=>n(String(v.value)),children:v.label},v.value))}),f&&s.jsxs("div",{className:"bounded-input-echo",children:["≈ ",f]})]})}function mu({htmlFor:e,label:t,description:n}){const[r,a]=u.useState(!1);return s.jsxs("div",{className:"field-label-with-tip",children:[s.jsx("label",{className:"form-label",htmlFor:e,children:t}),n&&s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"field-tip-trigger","aria-label":`What does "${t}" mean?`,"aria-expanded":r,onClick:()=>a(o=>!o),onMouseEnter:()=>a(!0),onMouseLeave:()=>a(!1),onBlur:()=>a(!1),children:"i"}),r&&s.jsx("div",{className:"field-tip-bubble",role:"tooltip",children:n})]})]})}function rx({id:e,value:t,onChange:n,disabled:r,format:a,placeholder:o}){const[i,l]=u.useState(""),[c,d]=u.useState(!1),f=u.useRef(null),p=t?t.split(",").map(g=>g.trim()).filter(Boolean):[],m=g=>{const h=g.trim();if(!h)return;if(!fu(h,a)){d(!0);return}d(!1);const y=p.includes(h)?p:[...p,h];n(y.join(",")),l("")},w=g=>{const h=p.filter((y,S)=>S!==g);n(h.join(","))},v=g=>{g.key==="Enter"||g.key===","||g.key==="Tab"?i.trim()&&(g.preventDefault(),m(i)):g.key==="Backspace"&&!i&&p.length>0&&w(p.length-1)},x=g=>{const h=g.clipboardData.getData("text");if(h.includes(",")){g.preventDefault();const S=h.split(",").map(N=>N.trim()).filter(Boolean).filter(N=>fu(N,a)),b=[...new Set([...p,...S])];n(b.join(",")),l(""),d(!1)}},k=a==="email"?"Type email and press Enter...":"Type domain and press Enter...";return s.jsxs("div",{className:`tag-input${c?" tag-input-invalid":""}`,onClick:()=>{var g;return(g=f.current)==null?void 0:g.focus()},children:[p.map((g,h)=>s.jsxs("span",{className:"tag-pill",children:[g,!r&&s.jsx("button",{type:"button",className:"tag-remove",onClick:y=>{y.stopPropagation(),w(h)},"aria-label":`Remove ${g}`,children:"×"})]},g)),!r&&s.jsx("input",{ref:f,id:e,className:"tag-input-field",type:"text",value:i,onChange:g=>{l(g.target.value),d(!1)},onKeyDown:v,onPaste:x,onBlur:()=>{i.trim()&&m(i)},placeholder:p.length===0?o??k:""})]})}function sx({id:e,options:t,value:n,onChange:r,disabled:a}){const o=n?n.split(",").map(l=>l.trim()).filter(Boolean):[],i=l=>{const c=o.includes(l)?o.filter(d=>d!==l):[...o,l];r(c.join(","))};return s.jsx("div",{className:"checkbox-group",id:e,children:t.map(l=>s.jsxs("label",{className:`checkbox-pill${o.includes(l)?" checkbox-pill-selected":""}`,children:[s.jsx("input",{type:"checkbox",checked:o.includes(l),onChange:()=>i(l),disabled:a}),s.jsx("span",{children:l})]},l))})}function pu({fieldKey:e,fieldDef:t,value:n,onChange:r,prefix:a,readOnly:o,twoColumn:i,discoveryIntegrationId:l,onLabels:c}){const d=Qv(e,t),f=`${a}-field-${e}`,p=s.jsx(s.Fragment,{children:Xv(t)?s.jsx(sx,{id:f,options:t.enum,value:n,onChange:m=>r(e,m),disabled:o}):(()=>{const m=t.boundType;return(m==null?void 0:m.kind)==="enum"&&Array.isArray(m.values)})()?s.jsxs("select",{id:f,className:"form-select",value:n,onChange:m=>r(e,m.target.value),disabled:o,children:[s.jsx("option",{value:"",children:"Select..."}),t.boundType.values.map(m=>s.jsx("option",{value:m,children:m},m))]}):"enum"in t&&t.enum?s.jsxs("select",{id:f,className:"form-select",value:n,onChange:m=>r(e,m.target.value),disabled:o,children:[s.jsx("option",{value:"",children:"Select..."}),t.enum.map(m=>s.jsx("option",{value:m,children:m},m))]}):t.type==="number"?s.jsx(nx,{id:f,value:n,onChange:m=>r(e,m),disabled:o,unit:t.unit,min:Hl(t)}):Jv(t)?s.jsx(rx,{id:f,value:n,onChange:m=>r(e,m),disabled:o,format:t.format}):l?s.jsx(Gv,{integrationId:l,field:e,value:n,onChange:m=>r(e,m),disabled:o,onLabels:m=>c==null?void 0:c(e,m)}):s.jsx("input",{id:f,className:"form-input",type:"text",value:n,onChange:m=>r(e,m.target.value),disabled:o})});return i?s.jsxs("div",{className:"bounds-field-row",children:[s.jsx("div",{className:"bounds-field-label",children:s.jsx(mu,{htmlFor:f,label:d,description:t.description})}),s.jsx("div",{className:"bounds-field-input",children:p})]},`${a}-${e}`):s.jsxs("div",{className:"form-group",children:[s.jsx(mu,{htmlFor:f,label:d,description:t.description}),p]},`${a}-${e}`)}function ax(e,t){if(!t)return"no-config";const n=t.caps,r=Array.isArray(t.approvers)&&t.approvers.length>0;if(!(n&&Object.keys(n).length>0))return r?"approvers-dormant":"no-config";let o=!1;for(const[i,l]of Object.entries(n)){const c=e[i];if(c===""||c===void 0)continue;const d=Number(c);if(!isNaN(d)&&d>l){o=!0;break}}return o?r?"above-approvers":"hard-ceiling":"within-cap"}function ox(e,t){const n=new Set;if(!t)return n;for(const[r,a]of Object.entries(t)){const o=e[r];if(o===""||o===void 0)continue;const i=Number(o);!isNaN(i)&&i>a&&n.add(r)}return n}function ix({profile:e,onConfirm:t,onCancel:n,readOnly:r,initialBounds:a,initialContext:o,initialFrame:i,profileConfig:l,approverNames:c,adminName:d}){const f=e.boundsSchema??e.frameSchema,p=e.contextSchema,m=f?Object.entries(f.fields).filter(([R,F])=>!(R==="profile"||R==="path"||F.enforced===!1||F.enforcedBy==="gatekeeper")):[],w=f?Object.entries(f.fields).filter(([,R])=>R.enforcedBy==="gatekeeper").filter(([,R])=>R.enforced!==!1).map(([R,F])=>F.displayName??R):[],v=p&&p.keyOrder.length>0?Object.entries(p.fields):[],x=a??i??{},k=o??{},g={};for(const[R,F]of m)g[R]=Kv(F,x[R]);const h={};for(const[R]of v)h[R]=k[R]!==void 0?String(k[R]):"";const[y,S]=u.useState(g),[b,N]=u.useState(h),[C,I]=u.useState({}),[E,$]=u.useState(null);u.useEffect(()=>{const R=Yv(e.id);T.getIntegrationManifests().then(({manifests:F})=>{const Q=F.find(q=>q.profile===R&&q.contextDiscovery&&Object.keys(q.contextDiscovery).length>0);$(Q??null)}).catch(()=>$(null))},[e.id]);const U=ax(y,l),V=ox(y,l==null?void 0:l.caps),J=(R,F)=>{S(Q=>({...Q,[R]:F}))},D=(R,F)=>{N(Q=>({...Q,[R]:F}))},_=()=>{const R={profile:e.id};for(const[Q,q]of m)q.type==="number"?R[Q]=du(q,y[Q]):R[Q]=y[Q];const F={};for(const[Q,q]of v)q.type==="number"?F[Q]=b[Q]===""?0:Number(b[Q]):F[Q]=b[Q];return[R,F]},B=()=>{const[R,F]=_();t(R,F,C)},ne=()=>{const R=(l==null?void 0:l.caps)??{},F={...y};for(const te of V)R[te]!==void 0&&(F[te]=String(R[te]));S(F);const Q={profile:e.id};for(const[te,ce]of m)ce.type==="number"?Q[te]=du(ce,F[te]??""):Q[te]=F[te]??"";const q={};for(const[te,ce]of v)ce.type==="number"?q[te]=b[te]===""?0:Number(b[te]):q[te]=b[te];t(Q,q,C)},L=R=>{const F=l==null?void 0:l.caps;if(!F||F[R]===void 0)return null;const Q=F[R],q=V.has(R);return U==="hard-ceiling"&&q?s.jsxs("span",{style:{fontSize:"0.72rem",color:"var(--danger)",marginLeft:"0.5rem",whiteSpace:"nowrap"},children:["Cap: ",Q," — exceeds team ceiling"]}):U==="above-approvers"&&q?s.jsxs("span",{style:{fontSize:"0.72rem",color:"var(--warning)",marginLeft:"0.5rem",whiteSpace:"nowrap"},children:["Cap: ",Q," — above cap"]}):s.jsxs("span",{style:{fontSize:"0.72rem",color:"var(--success)",marginLeft:"0.5rem",whiteSpace:"nowrap"},children:["Cap: ",Q," ok"]})},z=()=>{var R;if(U==="no-config")return null;if(U==="approvers-dormant"){const F=c&&c.length>0?c.join(", "):"the configured approvers";return s.jsxs("div",{style:{marginTop:"0.75rem",padding:"0.75rem 1rem",border:"1px solid var(--accent)",borderRadius:"0.375rem",background:"var(--bg-elevated)",fontSize:"0.82rem"},children:[s.jsxs("div",{style:{fontWeight:600,color:"var(--accent)",marginBottom:"0.25rem"},children:["Profile approvers: ",F]}),s.jsxs("div",{children:["No caps are set on this profile, so ",F," won't gate any action under this mandate. Your intent will still be encrypted and shared with them as an accountability record — they can read what you authorised, even though they aren't reviewing individual actions."]})]})}if(U==="within-cap")return s.jsx("div",{style:{marginTop:"0.75rem",padding:"0.75rem 1rem",border:"1px solid var(--border)",borderRadius:"0.375rem",background:"var(--bg-elevated)",fontSize:"0.82rem"},children:s.jsx("div",{style:{fontWeight:600,marginBottom:"0.25rem"},children:"Within all team caps — your responsibility."})});if(U==="above-approvers"){const F=c&&c.length>0?c.join(", "):"the required approvers";return s.jsxs("div",{style:{marginTop:"0.75rem",padding:"0.75rem 1rem",border:"1px solid var(--warning)",borderRadius:"0.375rem",background:"var(--bg-elevated)",fontSize:"0.82rem"},children:[s.jsx("div",{style:{fontWeight:600,color:"var(--warning)",marginBottom:"0.25rem"},children:"Above team cap."}),s.jsxs("div",{children:[s.jsx("strong",{children:"Over-cap actions"})," will require approval from you and ",F,". Within-cap actions run per the mode you choose."]})]})}if(U==="hard-ceiling"){const F=Array.from(V)[0],Q=F?(R=l==null?void 0:l.caps)==null?void 0:R[F]:void 0,q=d??"the team admin";return s.jsxs("div",{style:{marginTop:"0.75rem",padding:"0.75rem 1rem",border:"1px solid var(--danger)",borderRadius:"0.375rem",background:"var(--bg-elevated)",fontSize:"0.82rem"},children:[s.jsx("div",{style:{fontWeight:600,color:"var(--danger)",marginBottom:"0.25rem"},children:"Hard team ceiling."}),s.jsxs("div",{style:{marginBottom:"0.75rem"},children:["Team policy caps this at ",Q??"the configured limit",". Lower your bound or ask ",q," to add an approver path above the cap."]}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:ne,children:"Save below cap"}),n&&s.jsx("button",{type:"button",className:"btn btn-ghost btn-sm",onClick:n,children:"Cancel"})]})]})}return null},W=U==="hard-ceiling";return s.jsxs("div",{children:[v.length>0&&s.jsxs("div",{className:"context-section",children:[s.jsxs("div",{className:"bounds-section-header",children:[s.jsx("span",{className:"bounds-section-icon",children:"🛡"}),s.jsxs("div",{children:[s.jsx("div",{className:"bounds-section-title",children:"Allowed scope"}),s.jsx("div",{className:"bounds-section-subtitle",children:"Encrypted on your device, never sent to the Authority Server"})]})]}),v.map(([R,F])=>{var q;const Q=!!((q=E==null?void 0:E.contextDiscovery)!=null&&q[R]);return s.jsx(pu,{fieldKey:R,fieldDef:F,value:b[R],onChange:D,prefix:"context",readOnly:r,discoveryIntegrationId:Q?E.id:void 0,onLabels:(te,ce)=>I(me=>({...me,[te]:ce}))},`context-${R}`)})]}),m.length>0&&s.jsxs("div",{className:"bounds-section",children:[s.jsxs("div",{className:"bounds-section-header",children:[s.jsx("span",{className:"bounds-section-icon",children:"🔒"}),s.jsxs("div",{children:[s.jsx("div",{className:"bounds-section-title",children:"Limits"}),s.jsx("div",{className:"bounds-section-subtitle",children:"Enforced by the Authority Server"})]})]}),s.jsx("div",{className:"bounds-fields-grid",children:m.map(([R,F])=>{var Q;return s.jsxs("div",{style:{display:"contents"},children:[s.jsx(pu,{fieldKey:R,fieldDef:F,value:y[R],onChange:J,prefix:"bounds",readOnly:r,twoColumn:!0}),U!=="no-config"&&((Q=l==null?void 0:l.caps)==null?void 0:Q[R])!==void 0&&s.jsx("div",{style:{gridColumn:"2 / 3",display:"flex",alignItems:"center",paddingBottom:"0.5rem"},children:L(R)})]},`bounds-${R}`)})}),z(),w.length>0&&s.jsxs("div",{className:"bounds-local-note",style:{marginTop:"0.75rem",fontSize:"0.78rem",color:"var(--text-muted)"},children:[w.join(", ")," ",w.length===1?"is":"are"," set on the integration, not here — reads are checked on this device, so the limit applies immediately and can be changed any time under"," ",s.jsx(Ye,{to:"/integrations",children:"Integrations"}),"."]})]}),s.jsx("button",{className:"btn btn-primary",onClick:B,disabled:W,style:{marginTop:"0.5rem"},children:r?"Next: Gates":"Next: Problem Statement"})]})}function lx(e){var n;const t=e.match(/```(?:markdown|md)?\s*\n([\s\S]*?)```/);return((n=t==null?void 0:t[1])==null?void 0:n.trim())??null}function cx(e){return e.replace(/```(?:markdown|md)?\s*\n[\s\S]*?```/,"").trim()}const ux="Tell me what your agent should do — I'll help shape it. Or ask me to draft a full intent and we'll iterate.";function _a({target:e,currentText:t,onApply:n,greeting:r,placeholder:a,title:o}){const[i,l]=u.useState([{role:"assistant",content:r??ux}]),[c,d]=u.useState(""),[f,p]=u.useState(!1),[m,w]=u.useState(null),v=u.useRef(null),x=u.useRef(null);u.useEffect(()=>{const h=v.current;if(!h)return;const y=i[i.length-1],S=x.current;!f&&(y==null?void 0:y.role)==="assistant"&&i.length>1&&S?h.scrollTop=S.offsetTop:h.scrollTop=h.scrollHeight},[i,f]);const k=async()=>{const h=c.trim();if(!h||f)return;const y=[...i,{role:"user",content:h}];l(y),d(""),w(null),p(!0);try{const S=await T.aiChat({target:e,currentText:t,messages:y.filter((b,N)=>!(N===0&&b.role==="assistant"))});S.success&&S.reply?l(b=>[...b,{role:"assistant",content:S.reply}]):w(S.error??"AI returned no reply")}catch(S){w(S instanceof Error?S.message:"Chat failed")}finally{p(!1)}},g=h=>{h.key==="Enter"&&!h.shiftKey&&!h.nativeEvent.isComposing&&(h.preventDefault(),k())};return s.jsxs("div",{className:"intent-chat",children:[s.jsx("h3",{className:"card-title",children:o??"AI Assistant"}),s.jsxs("div",{ref:v,className:"chat-messages",children:[i.map((h,y)=>{const S=h.role==="assistant"?lx(h.content):null,b=S?cx(h.content):h.content;return s.jsx("div",{className:`chat-msg ${h.role}`,ref:y===i.length-1?x:void 0,children:s.jsxs("div",{className:"chat-msg-body",children:[b&&s.jsx("div",{className:"chat-msg-prose",children:b}),S!==null&&s.jsxs(s.Fragment,{children:[s.jsx("pre",{className:"chat-fenced-block",children:S}),s.jsx("button",{type:"button",className:"btn btn-primary btn-sm chat-apply-btn",onClick:()=>n(S),children:"Apply this draft"})]})]})},y)}),f&&s.jsx("div",{className:"chat-msg assistant",children:s.jsx("div",{className:"chat-msg-body chat-msg-thinking",children:"Thinking…"})})]}),m&&s.jsx("div",{className:"error-message",children:m}),s.jsxs("div",{className:"chat-composer",children:[s.jsxs("div",{className:"chat-composer-pill",children:[s.jsx("textarea",{className:"chat-input",value:c,onChange:h=>d(h.target.value),onKeyDown:g,placeholder:a??"Ask for help articulating the intent…",rows:1,disabled:f}),s.jsx("button",{type:"button",className:"chat-send-btn",onClick:k,disabled:f||!c.trim(),"aria-label":"Send",children:"↑"})]}),s.jsx("div",{className:"chat-composer-hint",children:"Enter to send · Shift+Enter for newline"})]})]})}function wm({open:e,onClose:t,children:n,ariaLabel:r}){const a=u.useRef(null),o=u.useRef(null);return u.useEffect(()=>{var l;if(!e)return;o.current=document.activeElement,document.body.style.overflow="hidden";const i=c=>{c.key==="Escape"&&t()};return document.addEventListener("keydown",i),(l=a.current)==null||l.focus(),()=>{document.removeEventListener("keydown",i),document.body.style.overflow="",o.current instanceof HTMLElement&&o.current.focus()}},[e,t]),Lf.createPortal(s.jsxs(s.Fragment,{children:[s.jsx("div",{className:`bottom-sheet-backdrop${e?" is-open":""}`,onClick:t,"aria-hidden":"true"}),s.jsxs("aside",{ref:a,className:`bottom-sheet${e?" is-open":""}`,role:"dialog","aria-modal":"true","aria-label":r,tabIndex:-1,children:[s.jsx("div",{className:"bottom-sheet-handle","aria-hidden":"true"}),s.jsx("button",{type:"button",className:"bottom-sheet-close",onClick:t,"aria-label":"Close",children:"×"}),n]})]}),document.body)}function dx(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function fx(e,t,n){if(t.length===0)return[{text:e,label:e,matched:null}];const r=[],a=new Set;for(const c of t)if(!(!c.scope||c.scope==="all (unscoped)"))for(const d of[c.scope,...c.scope.split(",").map(f=>f.trim())]){const f=d.toLowerCase();d&&!a.has(f)&&(a.add(f),r.push(d))}r.sort((c,d)=>d.length-c.length);const o=c=>{const d=c.toLowerCase();return t.filter(f=>{var p,m;return((p=f.scope)==null?void 0:p.toLowerCase())===d||((m=f.scope)==null?void 0:m.split(",").map(w=>w.trim().toLowerCase()).includes(d))})},i=["\\[\\d+\\]",...r.map(dx)],l=new RegExp(`(${i.join("|")})`,"gi");return e.split(l).filter(c=>c!=="").map(c=>{const d=/^\[(\d+)\]$/.exec(c);if(d){const f=t[Number(d[1])-1];if(f){const p=f.scope&&f.scope!=="all (unscoped)"?f.scope:"all recipients",m=n?`${n}: ${p}`:p;return{text:c,label:m,matched:[f]}}}else if(r.some(f=>f.toLowerCase()===c.toLowerCase())){const f=o(c);if(f.length>0)return{text:c,label:c,matched:f}}return{text:c,label:c,matched:null}})}const hu=`Why — What's the situation? Why does this need to happen?
60
+ Health check: GET ${e}/health`}};function Rv({aiConfigured:e,hasRunningIntegration:t,hasActiveAuth:n,hasAgentConnected:r,mcpEndpoint:a}){const[o,i]=u.useState(()=>localStorage.getItem(Pi)==="true"),[l,c]=u.useState(()=>localStorage.getItem(_i)==="true"),[d,f]=u.useState(()=>localStorage.getItem(Ai)==="true"),[p,m]=u.useState(null),[w,v]=u.useState("claude-code"),[x,k]=u.useState(!1),g=[{label:"AI Assistant",detail:"A trusted AI helps you think through mandates — surfacing risks and asking the right questions.",to:"/settings",status:e?"done":o?"skipped":"pending",optional:!0},{label:"Connect a service",to:"/integrations",status:t?"done":"pending"},{label:"Give your agent a mandate",to:"/mandates?new=1",status:n?"done":"pending"},{label:"Connect your agent",status:r||l?"done":"pending"}],h=g.filter(E=>E.status==="done"||E.status==="skipped").length,y=h===g.length,S=u.useCallback(()=>{localStorage.setItem(Pi,"true"),i(!0)},[]),b=u.useCallback(()=>{localStorage.setItem(_i,"true"),c(!0),m(null)},[]),N=u.useCallback(()=>{localStorage.setItem(Ai,"true"),f(!0)},[]),C=u.useCallback(async E=>{try{await navigator.clipboard.writeText(E),k(!0),setTimeout(()=>k(!1),2e3)}catch{}},[]);if(d||y)return null;const I=g.findIndex(E=>E.status==="pending");return s.jsxs("div",{style:{border:"2px solid var(--accent)",borderRadius:"0.75rem",padding:"1.5rem",marginBottom:"1.5rem",background:"var(--bg-elevated)"},children:[s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",marginBottom:"1.25rem"},children:[s.jsx("h2",{style:{fontSize:"1.1rem",fontWeight:700,margin:0},children:"Get Started"}),s.jsx("button",{onClick:N,style:{background:"none",border:"none",color:"var(--text-tertiary)",cursor:"pointer",fontSize:"1.1rem",padding:"0 0.25rem",lineHeight:1},title:"Hide setup guide",children:"×"})]}),s.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem"},children:g.map((E,$)=>{const U=$===I,V=E.status==="done"||E.status==="skipped"?"●":"○",J=E.status==="done"?"var(--success)":E.status==="skipped"?"var(--text-tertiary)":U?"var(--accent)":"var(--text-tertiary)";return s.jsxs("div",{children:[s.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"0.75rem",padding:U?"0.75rem":"0.25rem 0",borderRadius:U?"0.5rem":void 0,background:U?"var(--accent-subtle)":void 0},children:[s.jsx("span",{style:{color:J,fontSize:"0.75rem",marginTop:"0.2rem",flexShrink:0},children:V}),s.jsxs("div",{style:{flex:1,minWidth:0},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[E.to&&E.status==="pending"?s.jsx(Ye,{to:E.to,style:{fontSize:"0.9rem",fontWeight:U?600:500,color:U?"var(--accent)":"var(--text-primary)",textDecoration:"none"},children:E.label}):E.status==="pending"&&$===3?s.jsx("button",{onClick:()=>m(p===3?null:3),style:{background:"none",border:"none",padding:0,cursor:"pointer",fontSize:"0.9rem",fontWeight:U?600:500,color:U?"var(--accent)":"var(--text-primary)"},children:E.label}):s.jsx("span",{style:{fontSize:"0.9rem",fontWeight:500,color:E.status==="done"?"var(--text-secondary)":"var(--text-tertiary)"},children:E.label}),E.optional&&E.status==="pending"&&s.jsx("span",{style:{fontSize:"0.7rem",color:"var(--text-tertiary)",fontStyle:"italic"},children:"optional"}),E.status==="skipped"&&s.jsx("span",{style:{fontSize:"0.7rem",color:"var(--text-tertiary)"},children:"skipped"})]}),E.detail&&E.status==="pending"&&U&&s.jsx("div",{style:{fontSize:"0.8rem",color:"var(--text-secondary)",marginTop:"0.25rem",lineHeight:1.5},children:E.detail})]}),E.optional&&E.status==="pending"&&s.jsx("button",{onClick:S,style:{background:"none",border:"none",color:"var(--text-tertiary)",cursor:"pointer",fontSize:"0.75rem",padding:"0.125rem 0.5rem",flexShrink:0},children:"Skip"}),E.to&&E.status==="pending"&&s.jsx(Ye,{to:E.to,style:{color:"var(--text-tertiary)",textDecoration:"none",fontSize:"0.8rem",flexShrink:0},children:"›"})]}),$===3&&p===3&&s.jsxs("div",{style:{marginTop:"0.75rem",marginLeft:"1.5rem",padding:"1rem",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"0.5rem"},children:[s.jsx("div",{style:{fontSize:"0.8rem",fontWeight:600,marginBottom:"0.75rem",color:"var(--text-primary)"},children:"MCP Endpoint"}),s.jsx("div",{style:{fontFamily:"monospace",fontSize:"0.85rem",padding:"0.5rem 0.75rem",background:"var(--bg-elevated)",border:"1px solid var(--border)",borderRadius:"0.375rem",marginBottom:"1rem",wordBreak:"break-all"},children:a}),s.jsx("div",{style:{display:"flex",gap:"0.25rem",marginBottom:"0.75rem"},children:Object.entries(_o).map(([D,_])=>s.jsx("button",{onClick:()=>v(D),style:{padding:"0.375rem 0.75rem",fontSize:"0.75rem",fontWeight:w===D?600:400,background:w===D?"var(--accent-subtle)":"transparent",color:w===D?"var(--accent)":"var(--text-secondary)",border:`1px solid ${w===D?"var(--accent)":"var(--border)"}`,borderRadius:"0.375rem",cursor:"pointer"},children:_.label},D))}),s.jsx("pre",{style:{fontFamily:"monospace",fontSize:"0.78rem",lineHeight:1.6,padding:"0.75rem",background:"var(--bg-elevated)",border:"1px solid var(--border)",borderRadius:"0.375rem",overflow:"auto",whiteSpace:"pre-wrap",margin:0,marginBottom:"0.75rem"},children:_o[w].snippet(a)}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>C(_o[w].snippet(a)),children:x?"Copied":"Copy"}),s.jsx("button",{className:"btn btn-primary btn-sm",onClick:b,children:"Done"})]})]})]},$)})}),s.jsxs("div",{style:{marginTop:"1.25rem"},children:[s.jsx("div",{style:{height:"4px",background:"var(--border)",borderRadius:"2px",overflow:"hidden"},children:s.jsx("div",{style:{height:"100%",width:`${h/g.length*100}%`,background:"var(--accent)",borderRadius:"2px",transition:"width 0.3s ease"}})}),s.jsxs("div",{style:{fontSize:"0.7rem",color:"var(--text-tertiary)",marginTop:"0.375rem"},children:[h," of ",g.length," complete"]})]})]})}function _n({variant:e="base",style:t,className:n,...r}){const a=e==="title"?"skeleton skeleton-title":e==="line"?"skeleton skeleton-line":e==="line-sm"?"skeleton skeleton-line-sm":"skeleton";return s.jsx("span",{className:`${a}${n?` ${n}`:""}`,style:t,role:"status","aria-busy":"true","aria-label":r["aria-label"]??"Loading"})}function Ao(){return s.jsxs("div",{className:"skeleton-card",role:"status","aria-busy":"true","aria-label":"Loading",children:[s.jsx(_n,{style:{width:"0.5rem",height:"0.5rem",borderRadius:"50%",flexShrink:0}}),s.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",gap:"0.35rem"},children:[s.jsx(_n,{variant:"line",style:{width:"35%"}}),s.jsx(_n,{variant:"line-sm",style:{width:"65%"}})]})]})}const Pv={gmail:"Gmail",calendar:"Google Calendar",crm:"CRM",linkedin:"LinkedIn",records:"Records",mollie:"Mollie"},vm=e=>Pv[e]??e,_v={resource:{chip:"Restricted",sev:"warn"},spam:{chip:"Spam / Trash",sev:"info"},age:{chip:"Too old",sev:"warn"},unset_age:{chip:"Needs setup",sev:"act",fixTo:"/integrations"},read_gate:{chip:"Not granted",sev:"act",fixTo:"/mandates"},ungoverned:{chip:"Unconfigured",sev:"act"},query_unsafe:{chip:"Unsafe search",sev:"info"}};function Av(e){return _v[e]??{chip:"Blocked",sev:"info"}}function zv(e){const t=vm(e.integrationId);switch(e.reason){case"resource":return e.integrationId==="calendar"?s.jsxs(s.Fragment,{children:["Tried to read your ",s.jsx("b",{children:e.target??"restricted"})," calendar"]}):s.jsxs(s.Fragment,{children:["Tried to read a restricted location in ",t]});case"spam":return s.jsxs(s.Fragment,{children:["Tried to open a message in ",s.jsx("b",{children:"spam or trash"})]});case"age":return s.jsxs(s.Fragment,{children:["Tried to read ",t," older than your read window"]});case"unset_age":return s.jsxs(s.Fragment,{children:["Your ",t," has ",s.jsx("b",{children:"no read window set"}),", so reads are blocked"]});case"read_gate":return s.jsxs(s.Fragment,{children:["Read access isn't granted on your ",t," mandate"]});case"ungoverned":return s.jsxs(s.Fragment,{children:["A ",t," tool isn't configured for safe reading"]});case"query_unsafe":return s.jsx(s.Fragment,{children:"A search couldn't be safely limited and was refused"});default:return s.jsx(s.Fragment,{children:e.detail})}}function $v(e,t){const n=Math.max(0,(t-e)/1e3);if(n<60)return"Just now";if(n<3600)return`${Math.floor(n/60)} min ago`;if(n<86400)return`${Math.floor(n/3600)} hr ago`;const r=Math.floor(n/86400);return r===1?"Yesterday":`${r} days ago`}const uu=5,Lv=24*60*60*1e3,sa=7;function Mv(e,t){const n=t-sa*Lv;return{recent:e.filter(r=>r.ts>=n),all:e}}function Fv(){const[e,t]=u.useState(null),[n,r]=u.useState(!1),[a,o]=u.useState(!1),i=u.useCallback(()=>{T.getDenials({limit:200}).then(({records:m})=>{t(m),o(!1)}).catch(()=>o(!0))},[]);if(u.useEffect(()=>{i()},[i]),Pt(i,12e4),a||e===null)return null;const{recent:l,all:c}=Mv(e,Date.now()),d=n?c:l.slice(0,uu),f=c.length-l.length,p=(m,w)=>{const v=Av(m.reason);return s.jsxs("div",{className:"rb-row",children:[s.jsx("span",{className:`rb-dot ${v.sev==="act"?"act":v.sev==="info"?"info":""}`,"aria-hidden":"true"}),s.jsxs("div",{className:"rb-body",children:[s.jsx("div",{className:"rb-line",children:zv(m)}),s.jsxs("div",{className:"rb-meta",children:[s.jsx("span",{className:`rb-chip ${v.sev==="act"?"act":v.sev==="warn"?"warn":""}`,children:v.chip}),s.jsx("span",{className:"rb-via",children:vm(m.integrationId)})]}),v.fixTo&&s.jsx(Ye,{className:"rb-fix",to:v.fixTo,children:"Set a read window →"})]}),s.jsx("div",{className:"rb-when",children:$v(m.ts,Date.now())})]},`${m.ts}-${w}`)};return s.jsxs("section",{className:"card recent-blocks","aria-label":"Recent blocks",style:{marginTop:"1.5rem"},children:[s.jsxs("div",{className:"card-header",children:[s.jsx("h2",{className:"card-title",children:"Recent blocks"}),(n?c.length:l.length)>0&&s.jsx("span",{className:"rb-count",children:n?c.length:l.length})]}),d.length===0?s.jsxs("div",{className:"rb-empty",children:[s.jsx("span",{className:"rb-mark","aria-hidden":"true",children:s.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round",children:s.jsx("path",{d:"M20 6 9 17l-5-5"})})}),s.jsxs("h3",{children:["Nothing blocked in the last ",sa," days"]}),s.jsx("p",{children:"Your agent has stayed within every limit you set."}),f>0&&s.jsxs("button",{className:"rb-viewall",type:"button",onClick:()=>r(!0),children:["Show the last 30 days (",f,")"]})]}):s.jsxs(s.Fragment,{children:[s.jsxs("p",{className:"rb-sub",children:[n?"Last 30 days. ":`Last ${sa} days. `,"Limits you set that stopped your agent. Seeing them here means the gateway is doing its job."]}),s.jsx("div",{className:"rb-rows",children:d.map(p)}),!n&&c.length>d.length&&s.jsx("div",{className:"rb-foot",children:s.jsxs("button",{className:"rb-viewall",type:"button",onClick:()=>r(!0),children:["View all ",c.length," blocks from the last 30 days"]})}),n&&c.length>Math.min(l.length,uu)&&s.jsx("div",{className:"rb-foot",children:s.jsxs("button",{className:"rb-viewall",type:"button",onClick:()=>r(!1),children:["Show only the last ",sa," days"]})})]})]})}function Ov(){const[e,t]=u.useState([]);return Pt(async()=>{try{const{skipped:r}=await T.getSkippedCommitments();t(r)}catch{}},3e4),e.length===0?null:s.jsxs("div",{className:"card",style:{padding:"1.5rem",marginTop:"1.5rem",borderLeft:"3px solid var(--warn, #b58900)"},children:[s.jsxs("h2",{style:{fontSize:"1rem",fontWeight:700,margin:0},children:["Approved, but not run here (",e.length,")"]}),s.jsx("p",{style:{margin:"0.5rem 0 1rem",fontSize:"0.9rem",color:"var(--text-secondary)"},children:"These were approved, but this gateway has no local record of asking for them — usually because a different device/installation of yours submitted them, or its local record is gone. Re-run the same request on this gateway to execute it here."}),s.jsx("ul",{style:{margin:0,paddingLeft:"1.25rem",fontSize:"0.9rem"},children:e.map(r=>s.jsxs("li",{style:{marginBottom:"0.35rem"},children:[s.jsx("code",{children:r.tool})," ",s.jsxs("span",{style:{color:"var(--text-tertiary)"},children:["(",r.id,")"]})]},r.id))})]})}function Bv(e,t){const n=e.simulation;return n?(((t==null?void 0:t[n.field])??"").trim().toLowerCase()||n.default.trim().toLowerCase())==="simulation":!1}function zi(e){return!!(e!=null&&e.simulation)}function Dv(e){var n;const t=[];for(const r of e)r.state==="error"?t.push({label:"Integration error",detail:(n=r.integration)!=null&&n.error?`${r.manifest.name}: ${r.integration.error}`:`${r.manifest.name} is not running`,to:"/integrations",color:"var(--danger)"}):r.state==="not-running"&&(zi(r.manifest)?t.push({label:`${r.manifest.name} is not running`,detail:"Activate it to use it in the test.",to:"/integrations",color:"var(--danger)"}):t.push({label:"Integration stopped",detail:`${r.manifest.name} is not running`,to:"/integrations",color:"var(--danger)"}));return t}function Uv(e){const t=e.filter(n=>n.state==="paused");return t.length===0?null:{count:t.length,namesText:t.map(n=>n.manifest.name).join(", ")}}const Wv=30*60;function zo(e){return e.replace(/@.*$/,"").split("/").pop()??e}function Hv(){const{domain:e}=Fe(),[t,n]=u.useState([]),[r,a]=u.useState([]),[o,i]=u.useState([]),[l,c]=u.useState(!0),[d,f]=u.useState(!1),[p,m]=u.useState([]),[w,v]=u.useState(!1),[x,k]=u.useState(!1),{entries:g,activeSessions:h,loading:y}=Ul(),S=!y,b=u.useCallback(()=>{T.getMyAttestations().then(B=>{n(B),f(!0)}).catch(()=>f(!0)),T.getArchivedMandates().then(m).catch(()=>m([])),T.getProposals(e||"owner").then(B=>{a(B),v(!0)}).catch(()=>v(!0)),T.getProposalsForApprover().then(B=>i(B)).catch(()=>i([])),T.getCredential("ai-config").then(B=>{c(B.configured),k(!0)}).catch(()=>k(!0))},[e]);fe("attestation-changed",b),fe("proposal-added",b),fe("proposal-resolved",b),fe("proposal-approved",b),fe("proposal-rejected",b),Pt(b,3e5,e);const N=d&&w&&x&&S,C=lm(t,{archivedSet:new Set(p)}),I=C.active,E=C.expired,$=I.filter(B=>B.remaining_seconds!==null&&B.remaining_seconds<=Wv),U=r.filter(mm),V=g.filter(B=>B.state==="running"),J=g.filter(B=>B.state==="starting"),D=Uv(g),_=[];for(const B of o)_.push({label:"Approval needed",detail:`${B.tool} — above-cap action under ${zo(B.profileId)}`,to:"/approvals",color:"var(--warning)"});for(const B of U)_.push({label:"Approval pending",detail:`${B.tool} awaiting your approval`,to:"/approvals",color:"var(--warning)"});for(const B of $){const ne=Math.ceil((B.remaining_seconds??0)/60);_.push({label:"Expiring soon",detail:`${B.title??zo(B.profile_id)} — ${ne} min remaining`,to:"/mandates",color:"var(--warning)"})}for(const B of E)_.push({label:"Expired",detail:B.title??zo(B.profile_id),to:"/mandates",color:"var(--danger)"});_.push(...Dv(g));for(const B of J)_.push({label:"Integration starting",detail:`${B.manifest.name} is coming up…`,to:"/integrations",color:"var(--warning)"});for(const B of g)B.authStatus==="failed"&&B.state!=="not-running"&&B.state!=="error"&&B.state!=="paused"&&_.push({label:"Reconnect needed",detail:`${B.manifest.name}: authorization expired — reconnect to restore access`,to:"/integrations",color:"var(--danger)"});return l||_.push({label:"AI Assistant",detail:"Not configured — needed for gate advisory",to:"/settings",color:"var(--text-tertiary)"}),s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"page-header",children:s.jsx("h1",{className:"page-title",children:"Dashboard"})}),N&&s.jsx(Rv,{aiConfigured:l,hasRunningIntegration:V.length>0,hasActiveAuth:I.length>0,hasAgentConnected:h>0,mcpEndpoint:`http://localhost:${window.location.port==="3400"?"3430":"7430"}`}),s.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(8rem, 1fr))",gap:"0.75rem",marginBottom:"1.5rem"},children:[s.jsx(Ye,{to:"/mandates",style:{textDecoration:"none"},children:s.jsxs("div",{className:"card",style:{padding:"1rem",textAlign:"center"},children:[d?s.jsx("div",{style:{fontSize:"1.5rem",fontWeight:700,color:I.length>0?"var(--success)":"var(--text-tertiary)"},children:I.length}):s.jsx(_n,{variant:"title"}),s.jsx("div",{style:{fontSize:"0.75rem",color:"var(--text-secondary)"},children:"Active"})]})}),s.jsx(Ye,{to:"/approvals",style:{textDecoration:"none"},children:s.jsxs("div",{className:"card",style:{padding:"1rem",textAlign:"center"},children:[w?s.jsx("div",{style:{fontSize:"1.5rem",fontWeight:700,color:U.length>0?"var(--warning)":"var(--text-tertiary)"},children:U.length}):s.jsx(_n,{variant:"title"}),s.jsx("div",{style:{fontSize:"0.75rem",color:"var(--text-secondary)"},children:"Pending Approvals"})]})}),s.jsx(Ye,{to:"/mandates",style:{textDecoration:"none"},children:s.jsxs("div",{className:"card",style:{padding:"1rem",textAlign:"center"},children:[d?s.jsx("div",{style:{fontSize:"1.5rem",fontWeight:700,color:E.length>0?"var(--danger)":"var(--text-tertiary)"},children:E.length}):s.jsx(_n,{variant:"title"}),s.jsx("div",{style:{fontSize:"0.75rem",color:"var(--text-secondary)"},children:"Expired"})]})}),s.jsx(Ye,{to:"/integrations",style:{textDecoration:"none"},children:s.jsxs("div",{className:"card",style:{padding:"1rem",textAlign:"center"},children:[S?s.jsx("div",{style:{fontSize:"1.5rem",fontWeight:700,color:V.length>0?"var(--success)":"var(--text-tertiary)"},children:V.length}):s.jsx(_n,{variant:"title"}),s.jsx("div",{style:{fontSize:"0.75rem",color:"var(--text-secondary)"},children:"Integrations Running"})]})})]}),s.jsxs("section",{className:"card attention","aria-label":"Needs your attention",children:[s.jsxs("div",{className:"card-header",children:[s.jsx("h2",{className:"card-title",children:"Needs your attention"}),_.length>0&&s.jsx("span",{className:"rb-count",children:_.length})]}),_.length>0?s.jsx("div",{className:"attention-rows",children:_.map((B,ne)=>s.jsxs(Ye,{to:B.to,className:"attention-row",children:[s.jsx("span",{className:"attention-dot",style:{background:B.color},"aria-hidden":"true"}),s.jsxs("div",{style:{flex:1,minWidth:0},children:[s.jsx("div",{style:{fontSize:"0.8rem",fontWeight:600,color:"var(--text-primary)"},children:B.label}),s.jsx("div",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:B.detail})]}),s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-tertiary)"},children:"›"})]},ne))}):N?s.jsxs("div",{className:"all-clear",children:[s.jsx("span",{className:"rb-mark","aria-hidden":"true",children:s.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round",children:s.jsx("path",{d:"M20 6 9 17l-5-5"})})}),s.jsx("h3",{children:"All clear"}),s.jsx("p",{children:"Nothing needs your attention."})]}):s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[s.jsx(Ao,{}),s.jsx(Ao,{}),s.jsx(Ao,{})]})]}),D&&s.jsxs("div",{className:"sim-paused-summary",role:"status",children:[s.jsx("span",{className:"sim-paused-summary-icon","aria-hidden":"true",children:"⏸"}),s.jsxs("span",{children:[s.jsxs("b",{children:[D.count," real system",D.count===1?"":"s"," ",D.count===1?"is":"are"," paused"]})," ","while simulation mode is on — ",D.namesText,"."]})]}),s.jsx(Ov,{}),s.jsx(Fv,{})]})}const Vv=["Scope & Limits","Intent","Sign"];function xm({currentStep:e,onStepClick:t}){const n=nn();return s.jsxs("div",{className:"wizard-progress",children:[s.jsx("ol",{className:"wizard-steps",children:Vv.map((r,a)=>{const o=a+2,i=o<e,l=o===e,c=o-1<e,d=i&&!!t;return s.jsxs("li",{className:`wizard-step${c?" reached":""}`,"aria-current":l?"step":void 0,children:[s.jsx("button",{type:"button",className:`step-circle${i?" completed":""}${l?" current":""}`,onClick:d?()=>t(o):void 0,disabled:!d,"aria-label":`${r}${i?" (done)":l?" (current)":""}`,children:i?"✓":a+1}),s.jsx("span",{className:`step-label-text${l?" current":i?" completed":""}`,children:r})]},o)})}),s.jsx("button",{type:"button",className:"btn btn-ghost btn-sm wizard-cancel",onClick:()=>n("/mandates?new=1"),children:"Cancel"})]})}const Gv=40;function $e(e,t){const n=e.lastIndexOf("/"),r=n>=0?e.slice(n+1):e,a=r.indexOf("@"),o=a>=0?r.slice(0,a):r;return(o.charAt(0).toUpperCase()+o.slice(1)).slice(0,Gv)}function Kv({profileId:e,bounds:t,groupName:n,domain:r,onSwitch:a}){return s.jsxs("div",{className:"context-strip",children:[n&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"context-strip-label",children:"Team:"}),s.jsxs("span",{children:[s.jsx("strong",{children:n}),r?` / ${r}`:""]})]}),e&&s.jsxs("span",{children:[s.jsx("strong",{children:"Profile:"})," ",$e(e)]}),t&&s.jsxs("span",{children:[s.jsx("strong",{children:"Bounds:"})," ",t]}),a&&s.jsx("button",{className:"btn btn-ghost btn-sm",style:{marginLeft:"auto",padding:"0.2rem 0.5rem",fontSize:"0.7rem"},onClick:a,children:"Switch"})]})}function Yv({integrationId:e,field:t,value:n,onChange:r,disabled:a,onLabels:o}){const[i,l]=u.useState(null),[c,d]=u.useState(null),[f,p]=u.useState(!0);u.useEffect(()=>{let v=!1;return T.discoverScopeField(e,t).then(x=>{var k;v||(l(x.options),p(!1),(k=x.options)!=null&&k.length&&(o==null||o(Object.fromEntries(x.options.map(g=>[g.value,g.label])))))}).catch(x=>{v||(d(x instanceof Error?x.message:String(x)),p(!1))}),()=>{v=!0}},[e,t]);const m=new Set(n.split(",").map(v=>v.trim()).filter(Boolean)),w=v=>{const x=new Set(m);x.has(v)?x.delete(v):x.add(v),r(Array.from(x).join(","))};return f?s.jsxs("p",{className:"hint-text",style:{color:"var(--text-tertiary)"},children:["Loading options from ",e,"…"]}):c||!i?s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:{fontSize:"0.8rem",color:"var(--warning)",marginBottom:"0.5rem"},children:["Couldn't fetch options (",c??"no response","). Enter values manually, separated by commas."]}),s.jsx("input",{className:"form-input",type:"text",value:n,onChange:v=>r(v.target.value),disabled:a})]}):i.length===0?s.jsxs("p",{className:"hint-text",style:{color:"var(--text-tertiary)"},children:["No options available from ",e," for this field."]}):s.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.25rem"},children:i.map(v=>{const x=v.extras??{},k=typeof x.access=="string"?x.access:void 0,g=k==="reader",h=x.primary===!0;return s.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem",fontSize:"0.875rem",color:g?"var(--text-tertiary)":"var(--text-primary)",cursor:a||g?"not-allowed":"pointer"},title:g?"Read-only — you can authorize list/read but not writes":void 0,children:[s.jsx("input",{type:"checkbox",checked:m.has(String(v.value)),onChange:()=>w(String(v.value)),disabled:a||g}),s.jsx("span",{children:v.label||v.value}),h&&s.jsx("span",{style:{fontSize:"0.7rem",color:"var(--accent)",textTransform:"uppercase",letterSpacing:"0.04em"},children:"primary"}),k&&s.jsxs("span",{style:{fontSize:"0.7rem",color:"var(--text-tertiary)"},children:["· ",k]})]},v.value)})})}function Hl(e){if(e.type!=="number")return 0;const t=e.boundType,n=e.unit;return(t==null?void 0:t.kind)==="per_transaction"&&n==="count"?1:0}function Qv(e,t){return t!==void 0?String(t):Hl(e)===1?"1":""}function du(e,t){const n=Hl(e);return t===""?n:Math.max(n,Number(t))}function Jv(e){return e.replace(/@.*$/,"").split("/").pop()??e}function Xv(e,t){return t.displayName?t.displayName:e.replace(/_/g," ").replace(/\b\w/g,n=>n.toUpperCase())}function qv(e){return e.type==="string"&&(e.format==="email"||e.format==="domain")}function Zv(e){var t;return!!(e.enum&&((t=e.constraint)!=null&&t.enforceable.includes("subset")))}function fu(e,t){const n=e.trim();return n?t==="email"?n.includes("@")&&n.indexOf(".",n.indexOf("@"))>-1:t==="domain"?n.includes(".")&&!n.includes("@"):!0:!1}function ex(e){return!e||e==="count"?"":e==="minutes"?"min":e==="hours"?"hr":e==="days"?"days":e==="percent"?"%":e.startsWith("currency:")?e.slice(9):e}function tx(e){return e?e==="minutes"?15:e==="percent"?5:e.startsWith("currency:")?10:1:1}function nx(e){return e?e==="minutes"?[{value:15,label:"15m"},{value:30,label:"30m"},{value:60,label:"1h"},{value:120,label:"2h"},{value:240,label:"4h"}]:e==="hours"?[{value:1,label:"1h"},{value:4,label:"4h"},{value:8,label:"8h"},{value:24,label:"1d"}]:e==="days"?[{value:1,label:"1d"},{value:7,label:"1w"},{value:30,label:"1mo"},{value:90,label:"3mo"}]:e==="percent"?[{value:10,label:"10%"},{value:25,label:"25%"},{value:50,label:"50%"},{value:100,label:"100%"}]:e.startsWith("currency:")?[{value:10,label:"10"},{value:50,label:"50"},{value:100,label:"100"},{value:500,label:"500"},{value:1e3,label:"1k"}]:[]:[]}function rx(e,t){if(!e||!t)return"";const n=Number(e);if(!Number.isFinite(n)||n<=0)return"";if(t==="minutes"&&n>=60){const r=Math.floor(n/60),a=n%60;return a===0?`${r} hour${r!==1?"s":""}`:`${r}h ${a}m`}if(t==="hours"&&n>=24&&n%24===0){const r=n/24;return`${r} day${r!==1?"s":""}`}if(t==="days"){if(n>=30&&n%30===0)return`${n/30} month${n/30!==1?"s":""}`;if(n>=7&&n%7===0)return`${n/7} week${n/7!==1?"s":""}`}return""}function sx({id:e,value:t,onChange:n,disabled:r,placeholder:a,unit:o,min:i=0}){const l=tx(o),c=nx(o),d=ex(o),f=rx(t,o),p=t===""?null:Number(t),m=()=>{const v=t===""?0:Number(t),x=v%l,k=x===0?v+l:v+(l-x);n(String(k))},w=()=>{const v=t===""?0:Number(t);if(v<=i)return;const x=v%l,k=x===0?v-l:v-x;n(String(Math.max(i,k)))};return s.jsxs("div",{className:"bounded-input",children:[s.jsxs("div",{className:"bounded-input-field",children:[s.jsx("button",{type:"button",className:"stepper-btn stepper-decrement",onClick:w,disabled:r||t===""||Number(t)<=i,"aria-label":"Decrease",children:"−"}),s.jsx("input",{id:e,className:"stepper-input",type:"number",min:i,step:l,value:t,placeholder:a??String(i),onChange:v=>n(v.target.value),onFocus:v=>v.target.select(),disabled:r}),s.jsx("button",{type:"button",className:"stepper-btn stepper-increment",onClick:m,disabled:r,"aria-label":"Increase",children:"+"}),d&&s.jsx("span",{className:"bounded-input-unit","aria-hidden":"true",children:d})]}),c.length>0&&!r&&s.jsx("div",{className:"bounded-input-presets",role:"group","aria-label":"Quick presets",children:c.map(v=>s.jsx("button",{type:"button",className:`preset-chip${p===v.value?" preset-chip-selected":""}`,onClick:()=>n(String(v.value)),children:v.label},v.value))}),f&&s.jsxs("div",{className:"bounded-input-echo",children:["≈ ",f]})]})}function mu({htmlFor:e,label:t,description:n}){const[r,a]=u.useState(!1);return s.jsxs("div",{className:"field-label-with-tip",children:[s.jsx("label",{className:"form-label",htmlFor:e,children:t}),n&&s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"field-tip-trigger","aria-label":`What does "${t}" mean?`,"aria-expanded":r,onClick:()=>a(o=>!o),onMouseEnter:()=>a(!0),onMouseLeave:()=>a(!1),onBlur:()=>a(!1),children:"i"}),r&&s.jsx("div",{className:"field-tip-bubble",role:"tooltip",children:n})]})]})}function ax({id:e,value:t,onChange:n,disabled:r,format:a,placeholder:o}){const[i,l]=u.useState(""),[c,d]=u.useState(!1),f=u.useRef(null),p=t?t.split(",").map(g=>g.trim()).filter(Boolean):[],m=g=>{const h=g.trim();if(!h)return;if(!fu(h,a)){d(!0);return}d(!1);const y=p.includes(h)?p:[...p,h];n(y.join(",")),l("")},w=g=>{const h=p.filter((y,S)=>S!==g);n(h.join(","))},v=g=>{g.key==="Enter"||g.key===","||g.key==="Tab"?i.trim()&&(g.preventDefault(),m(i)):g.key==="Backspace"&&!i&&p.length>0&&w(p.length-1)},x=g=>{const h=g.clipboardData.getData("text");if(h.includes(",")){g.preventDefault();const S=h.split(",").map(N=>N.trim()).filter(Boolean).filter(N=>fu(N,a)),b=[...new Set([...p,...S])];n(b.join(",")),l(""),d(!1)}},k=a==="email"?"Type email and press Enter...":"Type domain and press Enter...";return s.jsxs("div",{className:`tag-input${c?" tag-input-invalid":""}`,onClick:()=>{var g;return(g=f.current)==null?void 0:g.focus()},children:[p.map((g,h)=>s.jsxs("span",{className:"tag-pill",children:[g,!r&&s.jsx("button",{type:"button",className:"tag-remove",onClick:y=>{y.stopPropagation(),w(h)},"aria-label":`Remove ${g}`,children:"×"})]},g)),!r&&s.jsx("input",{ref:f,id:e,className:"tag-input-field",type:"text",value:i,onChange:g=>{l(g.target.value),d(!1)},onKeyDown:v,onPaste:x,onBlur:()=>{i.trim()&&m(i)},placeholder:p.length===0?o??k:""})]})}function ox({id:e,options:t,value:n,onChange:r,disabled:a}){const o=n?n.split(",").map(l=>l.trim()).filter(Boolean):[],i=l=>{const c=o.includes(l)?o.filter(d=>d!==l):[...o,l];r(c.join(","))};return s.jsx("div",{className:"checkbox-group",id:e,children:t.map(l=>s.jsxs("label",{className:`checkbox-pill${o.includes(l)?" checkbox-pill-selected":""}`,children:[s.jsx("input",{type:"checkbox",checked:o.includes(l),onChange:()=>i(l),disabled:a}),s.jsx("span",{children:l})]},l))})}function pu({fieldKey:e,fieldDef:t,value:n,onChange:r,prefix:a,readOnly:o,twoColumn:i,discoveryIntegrationId:l,onLabels:c}){const d=Xv(e,t),f=`${a}-field-${e}`,p=s.jsx(s.Fragment,{children:Zv(t)?s.jsx(ox,{id:f,options:t.enum,value:n,onChange:m=>r(e,m),disabled:o}):(()=>{const m=t.boundType;return(m==null?void 0:m.kind)==="enum"&&Array.isArray(m.values)})()?s.jsxs("select",{id:f,className:"form-select",value:n,onChange:m=>r(e,m.target.value),disabled:o,children:[s.jsx("option",{value:"",children:"Select..."}),t.boundType.values.map(m=>s.jsx("option",{value:m,children:m},m))]}):"enum"in t&&t.enum?s.jsxs("select",{id:f,className:"form-select",value:n,onChange:m=>r(e,m.target.value),disabled:o,children:[s.jsx("option",{value:"",children:"Select..."}),t.enum.map(m=>s.jsx("option",{value:m,children:m},m))]}):t.type==="number"?s.jsx(sx,{id:f,value:n,onChange:m=>r(e,m),disabled:o,unit:t.unit,min:Hl(t)}):qv(t)?s.jsx(ax,{id:f,value:n,onChange:m=>r(e,m),disabled:o,format:t.format}):l?s.jsx(Yv,{integrationId:l,field:e,value:n,onChange:m=>r(e,m),disabled:o,onLabels:m=>c==null?void 0:c(e,m)}):s.jsx("input",{id:f,className:"form-input",type:"text",value:n,onChange:m=>r(e,m.target.value),disabled:o})});return i?s.jsxs("div",{className:"bounds-field-row",children:[s.jsx("div",{className:"bounds-field-label",children:s.jsx(mu,{htmlFor:f,label:d,description:t.description})}),s.jsx("div",{className:"bounds-field-input",children:p})]},`${a}-${e}`):s.jsxs("div",{className:"form-group",children:[s.jsx(mu,{htmlFor:f,label:d,description:t.description}),p]},`${a}-${e}`)}function ix(e,t){if(!t)return"no-config";const n=t.caps,r=Array.isArray(t.approvers)&&t.approvers.length>0;if(!(n&&Object.keys(n).length>0))return r?"approvers-dormant":"no-config";let o=!1;for(const[i,l]of Object.entries(n)){const c=e[i];if(c===""||c===void 0)continue;const d=Number(c);if(!isNaN(d)&&d>l){o=!0;break}}return o?r?"above-approvers":"hard-ceiling":"within-cap"}function lx(e,t){const n=new Set;if(!t)return n;for(const[r,a]of Object.entries(t)){const o=e[r];if(o===""||o===void 0)continue;const i=Number(o);!isNaN(i)&&i>a&&n.add(r)}return n}function cx({profile:e,onConfirm:t,onCancel:n,readOnly:r,initialBounds:a,initialContext:o,initialFrame:i,profileConfig:l,approverNames:c,adminName:d}){const f=e.boundsSchema??e.frameSchema,p=e.contextSchema,m=f?Object.entries(f.fields).filter(([R,F])=>!(R==="profile"||R==="path"||F.enforced===!1||F.enforcedBy==="gatekeeper")):[],w=f?Object.entries(f.fields).filter(([,R])=>R.enforcedBy==="gatekeeper").filter(([,R])=>R.enforced!==!1).map(([R,F])=>F.displayName??R):[],v=p&&p.keyOrder.length>0?Object.entries(p.fields):[],x=a??i??{},k=o??{},g={};for(const[R,F]of m)g[R]=Qv(F,x[R]);const h={};for(const[R]of v)h[R]=k[R]!==void 0?String(k[R]):"";const[y,S]=u.useState(g),[b,N]=u.useState(h),[C,I]=u.useState({}),[E,$]=u.useState(null);u.useEffect(()=>{const R=Jv(e.id);T.getIntegrationManifests().then(({manifests:F})=>{const Q=F.find(q=>q.profile===R&&q.contextDiscovery&&Object.keys(q.contextDiscovery).length>0);$(Q??null)}).catch(()=>$(null))},[e.id]);const U=ix(y,l),V=lx(y,l==null?void 0:l.caps),J=(R,F)=>{S(Q=>({...Q,[R]:F}))},D=(R,F)=>{N(Q=>({...Q,[R]:F}))},_=()=>{const R={profile:e.id};for(const[Q,q]of m)q.type==="number"?R[Q]=du(q,y[Q]):R[Q]=y[Q];const F={};for(const[Q,q]of v)q.type==="number"?F[Q]=b[Q]===""?0:Number(b[Q]):F[Q]=b[Q];return[R,F]},B=()=>{const[R,F]=_();t(R,F,C)},ne=()=>{const R=(l==null?void 0:l.caps)??{},F={...y};for(const te of V)R[te]!==void 0&&(F[te]=String(R[te]));S(F);const Q={profile:e.id};for(const[te,ce]of m)ce.type==="number"?Q[te]=du(ce,F[te]??""):Q[te]=F[te]??"";const q={};for(const[te,ce]of v)ce.type==="number"?q[te]=b[te]===""?0:Number(b[te]):q[te]=b[te];t(Q,q,C)},L=R=>{const F=l==null?void 0:l.caps;if(!F||F[R]===void 0)return null;const Q=F[R],q=V.has(R);return U==="hard-ceiling"&&q?s.jsxs("span",{style:{fontSize:"0.72rem",color:"var(--danger)",marginLeft:"0.5rem",whiteSpace:"nowrap"},children:["Cap: ",Q," — exceeds team ceiling"]}):U==="above-approvers"&&q?s.jsxs("span",{style:{fontSize:"0.72rem",color:"var(--warning)",marginLeft:"0.5rem",whiteSpace:"nowrap"},children:["Cap: ",Q," — above cap"]}):s.jsxs("span",{style:{fontSize:"0.72rem",color:"var(--success)",marginLeft:"0.5rem",whiteSpace:"nowrap"},children:["Cap: ",Q," ok"]})},z=()=>{var R;if(U==="no-config")return null;if(U==="approvers-dormant"){const F=c&&c.length>0?c.join(", "):"the configured approvers";return s.jsxs("div",{style:{marginTop:"0.75rem",padding:"0.75rem 1rem",border:"1px solid var(--accent)",borderRadius:"0.375rem",background:"var(--bg-elevated)",fontSize:"0.82rem"},children:[s.jsxs("div",{style:{fontWeight:600,color:"var(--accent)",marginBottom:"0.25rem"},children:["Profile approvers: ",F]}),s.jsxs("div",{children:["No caps are set on this profile, so ",F," won't gate any action under this mandate. Your intent will still be encrypted and shared with them as an accountability record — they can read what you authorised, even though they aren't reviewing individual actions."]})]})}if(U==="within-cap")return s.jsx("div",{style:{marginTop:"0.75rem",padding:"0.75rem 1rem",border:"1px solid var(--border)",borderRadius:"0.375rem",background:"var(--bg-elevated)",fontSize:"0.82rem"},children:s.jsx("div",{style:{fontWeight:600,marginBottom:"0.25rem"},children:"Within all team caps — your responsibility."})});if(U==="above-approvers"){const F=c&&c.length>0?c.join(", "):"the required approvers";return s.jsxs("div",{style:{marginTop:"0.75rem",padding:"0.75rem 1rem",border:"1px solid var(--warning)",borderRadius:"0.375rem",background:"var(--bg-elevated)",fontSize:"0.82rem"},children:[s.jsx("div",{style:{fontWeight:600,color:"var(--warning)",marginBottom:"0.25rem"},children:"Above team cap."}),s.jsxs("div",{children:[s.jsx("strong",{children:"Over-cap actions"})," will require approval from you and ",F,". Within-cap actions run per the mode you choose."]})]})}if(U==="hard-ceiling"){const F=Array.from(V)[0],Q=F?(R=l==null?void 0:l.caps)==null?void 0:R[F]:void 0,q=d??"the team admin";return s.jsxs("div",{style:{marginTop:"0.75rem",padding:"0.75rem 1rem",border:"1px solid var(--danger)",borderRadius:"0.375rem",background:"var(--bg-elevated)",fontSize:"0.82rem"},children:[s.jsx("div",{style:{fontWeight:600,color:"var(--danger)",marginBottom:"0.25rem"},children:"Hard team ceiling."}),s.jsxs("div",{style:{marginBottom:"0.75rem"},children:["Team policy caps this at ",Q??"the configured limit",". Lower your bound or ask ",q," to add an approver path above the cap."]}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:ne,children:"Save below cap"}),n&&s.jsx("button",{type:"button",className:"btn btn-ghost btn-sm",onClick:n,children:"Cancel"})]})]})}return null},W=U==="hard-ceiling";return s.jsxs("div",{children:[v.length>0&&s.jsxs("div",{className:"context-section",children:[s.jsxs("div",{className:"bounds-section-header",children:[s.jsx("span",{className:"bounds-section-icon",children:"🛡"}),s.jsxs("div",{children:[s.jsx("div",{className:"bounds-section-title",children:"Allowed scope"}),s.jsx("div",{className:"bounds-section-subtitle",children:"Encrypted on your device, never sent to the Authority Server"})]})]}),v.map(([R,F])=>{var q;const Q=!!((q=E==null?void 0:E.contextDiscovery)!=null&&q[R]);return s.jsx(pu,{fieldKey:R,fieldDef:F,value:b[R],onChange:D,prefix:"context",readOnly:r,discoveryIntegrationId:Q?E.id:void 0,onLabels:(te,ce)=>I(me=>({...me,[te]:ce}))},`context-${R}`)})]}),m.length>0&&s.jsxs("div",{className:"bounds-section",children:[s.jsxs("div",{className:"bounds-section-header",children:[s.jsx("span",{className:"bounds-section-icon",children:"🔒"}),s.jsxs("div",{children:[s.jsx("div",{className:"bounds-section-title",children:"Limits"}),s.jsx("div",{className:"bounds-section-subtitle",children:"Enforced by the Authority Server"})]})]}),s.jsx("div",{className:"bounds-fields-grid",children:m.map(([R,F])=>{var Q;return s.jsxs("div",{style:{display:"contents"},children:[s.jsx(pu,{fieldKey:R,fieldDef:F,value:y[R],onChange:J,prefix:"bounds",readOnly:r,twoColumn:!0}),U!=="no-config"&&((Q=l==null?void 0:l.caps)==null?void 0:Q[R])!==void 0&&s.jsx("div",{style:{gridColumn:"2 / 3",display:"flex",alignItems:"center",paddingBottom:"0.5rem"},children:L(R)})]},`bounds-${R}`)})}),z(),w.length>0&&s.jsxs("div",{className:"bounds-local-note",style:{marginTop:"0.75rem",fontSize:"0.78rem",color:"var(--text-muted)"},children:[w.join(", ")," ",w.length===1?"is":"are"," set on the integration, not here — reads are checked on this device, so the limit applies immediately and can be changed any time under"," ",s.jsx(Ye,{to:"/integrations",children:"Integrations"}),"."]})]}),s.jsx("button",{className:"btn btn-primary",onClick:B,disabled:W,style:{marginTop:"0.5rem"},children:r?"Next: Gates":"Next: Problem Statement"})]})}function ux(e){var n;const t=e.match(/```(?:markdown|md)?\s*\n([\s\S]*?)```/);return((n=t==null?void 0:t[1])==null?void 0:n.trim())??null}function dx(e){return e.replace(/```(?:markdown|md)?\s*\n[\s\S]*?```/,"").trim()}const fx="Tell me what your agent should do — I'll help shape it. Or ask me to draft a full intent and we'll iterate.";function _a({target:e,currentText:t,onApply:n,greeting:r,placeholder:a,title:o}){const[i,l]=u.useState([{role:"assistant",content:r??fx}]),[c,d]=u.useState(""),[f,p]=u.useState(!1),[m,w]=u.useState(null),v=u.useRef(null),x=u.useRef(null);u.useEffect(()=>{const h=v.current;if(!h)return;const y=i[i.length-1],S=x.current;!f&&(y==null?void 0:y.role)==="assistant"&&i.length>1&&S?h.scrollTop=S.offsetTop:h.scrollTop=h.scrollHeight},[i,f]);const k=async()=>{const h=c.trim();if(!h||f)return;const y=[...i,{role:"user",content:h}];l(y),d(""),w(null),p(!0);try{const S=await T.aiChat({target:e,currentText:t,messages:y.filter((b,N)=>!(N===0&&b.role==="assistant"))});S.success&&S.reply?l(b=>[...b,{role:"assistant",content:S.reply}]):w(S.error??"AI returned no reply")}catch(S){w(S instanceof Error?S.message:"Chat failed")}finally{p(!1)}},g=h=>{h.key==="Enter"&&!h.shiftKey&&!h.nativeEvent.isComposing&&(h.preventDefault(),k())};return s.jsxs("div",{className:"intent-chat",children:[s.jsx("h3",{className:"card-title",children:o??"AI Assistant"}),s.jsxs("div",{ref:v,className:"chat-messages",children:[i.map((h,y)=>{const S=h.role==="assistant"?ux(h.content):null,b=S?dx(h.content):h.content;return s.jsx("div",{className:`chat-msg ${h.role}`,ref:y===i.length-1?x:void 0,children:s.jsxs("div",{className:"chat-msg-body",children:[b&&s.jsx("div",{className:"chat-msg-prose",children:b}),S!==null&&s.jsxs(s.Fragment,{children:[s.jsx("pre",{className:"chat-fenced-block",children:S}),s.jsx("button",{type:"button",className:"btn btn-primary btn-sm chat-apply-btn",onClick:()=>n(S),children:"Apply this draft"})]})]})},y)}),f&&s.jsx("div",{className:"chat-msg assistant",children:s.jsx("div",{className:"chat-msg-body chat-msg-thinking",children:"Thinking…"})})]}),m&&s.jsx("div",{className:"error-message",children:m}),s.jsxs("div",{className:"chat-composer",children:[s.jsxs("div",{className:"chat-composer-pill",children:[s.jsx("textarea",{className:"chat-input",value:c,onChange:h=>d(h.target.value),onKeyDown:g,placeholder:a??"Ask for help articulating the intent…",rows:1,disabled:f}),s.jsx("button",{type:"button",className:"chat-send-btn",onClick:k,disabled:f||!c.trim(),"aria-label":"Send",children:"↑"})]}),s.jsx("div",{className:"chat-composer-hint",children:"Enter to send · Shift+Enter for newline"})]})]})}function wm({open:e,onClose:t,children:n,ariaLabel:r}){const a=u.useRef(null),o=u.useRef(null);return u.useEffect(()=>{var l;if(!e)return;o.current=document.activeElement,document.body.style.overflow="hidden";const i=c=>{c.key==="Escape"&&t()};return document.addEventListener("keydown",i),(l=a.current)==null||l.focus(),()=>{document.removeEventListener("keydown",i),document.body.style.overflow="",o.current instanceof HTMLElement&&o.current.focus()}},[e,t]),Lf.createPortal(s.jsxs(s.Fragment,{children:[s.jsx("div",{className:`bottom-sheet-backdrop${e?" is-open":""}`,onClick:t,"aria-hidden":"true"}),s.jsxs("aside",{ref:a,className:`bottom-sheet${e?" is-open":""}`,role:"dialog","aria-modal":"true","aria-label":r,tabIndex:-1,children:[s.jsx("div",{className:"bottom-sheet-handle","aria-hidden":"true"}),s.jsx("button",{type:"button",className:"bottom-sheet-close",onClick:t,"aria-label":"Close",children:"×"}),n]})]}),document.body)}function mx(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function px(e,t,n){if(t.length===0)return[{text:e,label:e,matched:null}];const r=[],a=new Set;for(const c of t)if(!(!c.scope||c.scope==="all (unscoped)"))for(const d of[c.scope,...c.scope.split(",").map(f=>f.trim())]){const f=d.toLowerCase();d&&!a.has(f)&&(a.add(f),r.push(d))}r.sort((c,d)=>d.length-c.length);const o=c=>{const d=c.toLowerCase();return t.filter(f=>{var p,m;return((p=f.scope)==null?void 0:p.toLowerCase())===d||((m=f.scope)==null?void 0:m.split(",").map(w=>w.trim().toLowerCase()).includes(d))})},i=["\\[\\d+\\]",...r.map(mx)],l=new RegExp(`(${i.join("|")})`,"gi");return e.split(l).filter(c=>c!=="").map(c=>{const d=/^\[(\d+)\]$/.exec(c);if(d){const f=t[Number(d[1])-1];if(f){const p=f.scope&&f.scope!=="all (unscoped)"?f.scope:"all recipients",m=n?`${n}: ${p}`:p;return{text:c,label:m,matched:[f]}}}else if(r.some(f=>f.toLowerCase()===c.toLowerCase())){const f=o(c);if(f.length>0)return{text:c,label:c,matched:f}}return{text:c,label:c,matched:null}})}const hu=`Why — What's the situation? Why does this need to happen?
61
61
 
62
62
  Goal — What should the agent try to achieve?
63
63
 
64
- Watch out — What should the agent avoid or be careful about?`;function mx(e,t,n,r){return fx(e,t,r).map((a,o)=>{if(!a.matched)return s.jsx("span",{children:a.text},o);const i=a.matched;return s.jsx("button",{type:"button",onClick:()=>n(i),style:{background:"none",border:"none",padding:0,cursor:"pointer",color:"var(--accent)",textDecoration:"underline",font:"inherit"},children:a.label},o)})}function px(){var re;const e=nn(),[t]=tm(),n=Number(t.get("step"))||2,[r,a]=u.useState(null),[o,i]=u.useState(null),[l,c]=u.useState(n),[d,f]=u.useState(null),[p,m]=u.useState(null),[w,v]=u.useState({}),[x,k]=u.useState(hu),[g,h]=u.useState(!1),[y,S]=u.useState(!0),[b,N]=u.useState(null),[C,I]=u.useState([]),[E,$]=u.useState(void 0),[U,V]=u.useState(!1),[J,D]=u.useState(null),[_,B]=u.useState(null),[ne,L]=u.useState(null),[z,W]=u.useState([]),[R,F]=u.useState(null);u.useEffect(()=>{var ge;const A=sessionStorage.getItem("agentAuth");if(!A){e("/mandates?new=1");return}const X=JSON.parse(A);a(X);const ae=sessionStorage.getItem("agentGate");if(ae){const he=JSON.parse(ae);he.bounds&&f(he.bounds),he.context&&m(he.context),(ge=he.gateContent)!=null&&ge.intent&&k(he.gateContent.intent)}T.getProfile(X.profileId).then(he=>i(he)).catch(()=>e("/mandates?new=1")).finally(()=>S(!1)),X.groupId&&Promise.all([T.getTeamProfileConfig(X.groupId,X.profileId).catch(()=>null),T.getGroupById(X.groupId).catch(()=>null),T.listUsers().catch(()=>[])]).then(([he,Pe,qe])=>{if(N(he),he){const _e=new Map;for(const le of qe){const et=le.name&&le.email?`${le.name} (${le.email})`:le.name||le.email||le.id;_e.set(le.id,et)}const yt=(Pe==null?void 0:Pe.members)??[];for(const le of yt){const et=le.userId??le.id;et&&(le.name&&le.email?_e.set(et,`${le.name} (${le.email})`):le.name&&_e.set(et,le.name))}const Ze=(he.approvers??[]).map(le=>_e.get(le)??le);I(Ze);const Ge=yt.find(le=>le.role==="admin");if(Ge){const le=Ge.userId??Ge.id;le&&$(_e.get(le)??Ge.name)}}})},[e]);const Q=d?Object.entries(d).filter(([A])=>A!=="profile"&&A!=="path").map(([A,X])=>`${A} = ${X}`).join(", "):"",q=(A,X,ae)=>{f(A),m(X),ae&&v(ae),c(3)},te=x.trim()!==hu.trim()&&x.trim()!=="",ce=A=>{te&&!confirm("Replace your current intent with the AI draft?")||k(A)},me=()=>{const A=o==null?void 0:o.ttl,X={intent:x},ae=JSON.parse(sessionStorage.getItem("agentGate")??"{}");sessionStorage.setItem("agentGate",JSON.stringify({...ae,bounds:d,context:p,contextLabels:w,gateContent:X,ttlConfig:A})),e("/mandates/new/sign")},ee=async()=>{if(r){V(!0),D(null),B(null),L(null),W([]),F(null);try{const A=await T.aiIntentReview({profileId:r.profileId,newIntent:x,context:p??void 0});W(A.grants??[]),A.success?A.review?D(A.review):B(A.note??"No other mandates on this profile to compare against."):L(A.error??"Check failed.")}catch(A){L(A instanceof Error?A.message:"Check failed.")}finally{V(!1)}}},oe=A=>{k(A),(J||_||ne)&&(D(null),B(null),L(null),W([]),F(null))};return y||!r||!o?s.jsx("p",{style:{color:"var(--text-tertiary)"},children:"Loading..."}):s.jsxs(s.Fragment,{children:[s.jsx(xm,{currentStep:l,onStepClick:A=>{A>=2&&c(A)}}),s.jsx(Vv,{profileId:r.profileId,bounds:Q||void 0,groupName:r.groupName,domain:r.domain}),l===2&&s.jsx("div",{className:"card",children:s.jsx(ix,{profile:o,onConfirm:q,onCancel:()=>e("/mandates?new=1"),initialBounds:d||void 0,initialContext:p||void 0,profileConfig:b,approverNames:C,adminName:E})}),l===3&&s.jsxs("div",{className:"intent-layout",children:[s.jsx("div",{className:"card intent-pane chat tool",children:s.jsx(_a,{target:{kind:"intent",profileId:r.profileId,bounds:Q||void 0},currentText:x,onApply:ce})}),s.jsxs("div",{className:"card intent-pane document",children:[s.jsx("h3",{className:"card-title",children:"What should your agent know?"}),s.jsxs("div",{className:"field-editable",style:{marginBottom:0},children:[s.jsxs("div",{className:"field-label",children:[s.jsx("span",{className:"pen",children:"✎"})," Intent — your words, signed with the grant"]}),s.jsx("textarea",{className:"intent-textarea",value:x,onChange:A=>oe(A.target.value)}),s.jsxs("div",{className:"char-counter",children:[x.length," / 2000"]})]}),s.jsxs("div",{style:{marginTop:"0.5rem"},children:[s.jsx("button",{type:"button",className:"btn btn-ghost",style:{fontSize:"0.8rem",padding:"0.4rem 0.75rem"},onClick:ee,disabled:U||!te,children:U?"Checking…":"Check against my other grants"}),ne&&s.jsxs("div",{className:"hint-box",role:"note",style:{marginTop:"0.5rem",borderLeftColor:"var(--danger)"},children:[s.jsx("span",{className:"hint-icon","aria-hidden":"true",children:"!"}),s.jsx("div",{className:"hint-body",children:ne})]}),_&&s.jsxs("div",{className:"hint-box",role:"note",style:{marginTop:"0.5rem"},children:[s.jsx("span",{className:"hint-icon","aria-hidden":"true",children:"i"}),s.jsx("div",{className:"hint-body",children:_})]}),J&&s.jsxs("div",{className:"hint-box",role:"note",style:{marginTop:"0.5rem"},children:[s.jsx("span",{className:"hint-icon","aria-hidden":"true",children:"i"}),s.jsxs("div",{className:"hint-body",children:[s.jsx("div",{className:"hint-head",children:"Intent review (advisory)"}),s.jsx("div",{style:{whiteSpace:"pre-wrap"},children:mx(J,z,F,$e(r.profileId))}),s.jsx("div",{style:{fontSize:"0.7rem",color:"var(--text-tertiary)",marginTop:"0.4rem"},children:"Checked with your configured assistant. AI surfaces reality — you decide."})]})]})]}),s.jsxs("div",{className:"intent-footer",children:[s.jsx("button",{className:"btn btn-ghost",onClick:()=>c(2),children:"Back"}),s.jsx("button",{className:"btn btn-primary intent-continue-btn",onClick:me,disabled:!te,children:"Continue to Review"})]}),(((re=b==null?void 0:b.approvers)==null?void 0:re.length)??0)>0&&s.jsxs("div",{className:"hint-box",role:"note",children:[s.jsx("span",{className:"hint-icon","aria-hidden":"true",children:"i"}),s.jsxs("div",{className:"hint-body",children:[s.jsxs("div",{className:"hint-head",children:["Visible to ",C.length>0?C.join(", "):"the configured approvers"]}),"Your intent will be encrypted and shared with"," ",C.length>0?C.join(", "):"this profile's required approvers",". Only they can decrypt it — your Authority Server cannot. Each approver stores a copy as their accountability record."]})]})]}),s.jsx("button",{type:"button",className:"floating-help",onClick:()=>h(!0),"aria-label":"Open intent assistant",children:"Get help with intent"}),s.jsx(wm,{open:g,onClose:()=>h(!1),ariaLabel:"Intent assistant",children:s.jsx(_a,{target:{kind:"intent",profileId:r.profileId,bounds:Q||void 0},currentText:x,onApply:A=>{ce(A),h(!1)}})}),R&&s.jsx("div",{className:"modal-backdrop",onClick:A=>A.target===A.currentTarget&&F(null),children:s.jsxs("div",{className:"modal",children:[s.jsxs("div",{className:"modal-header",children:[s.jsx("h3",{className:"modal-title",children:R.length>1?`Existing mandates (${R.length})`:"Existing mandate"}),s.jsx("button",{className:"modal-close",onClick:()=>F(null),children:"×"})]}),s.jsx("div",{className:"modal-body",children:R.map((A,X)=>{var ae;return s.jsxs("div",{style:{marginBottom:X<R.length-1?"1rem":0,paddingBottom:X<R.length-1?"1rem":0,borderBottom:X<R.length-1?"1px solid var(--border)":"none"},children:[s.jsx("div",{style:{fontSize:"0.7rem",fontWeight:600,color:"var(--text-tertiary)",textTransform:"uppercase",letterSpacing:"0.04em",marginBottom:"0.25rem"},children:"Scope"}),s.jsx("div",{style:{marginBottom:"0.75rem"},children:A.scope}),s.jsx("div",{style:{fontSize:"0.7rem",fontWeight:600,color:"var(--text-tertiary)",textTransform:"uppercase",letterSpacing:"0.04em",marginBottom:"0.25rem"},children:"Intent"}),s.jsx("div",{style:{whiteSpace:"pre-wrap",marginBottom:"0.75rem"},children:((ae=A.intent)==null?void 0:ae.trim())||"(no intent recorded)"}),Object.entries(A.bounds).filter(([ge])=>ge!=="profile"&&ge!=="path").length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{style:{fontSize:"0.7rem",fontWeight:600,color:"var(--text-tertiary)",textTransform:"uppercase",letterSpacing:"0.04em",marginBottom:"0.25rem"},children:"Limits"}),s.jsx("div",{style:{fontSize:"0.85rem",color:"var(--text-secondary)"},children:Object.entries(A.bounds).filter(([ge])=>ge!=="profile"&&ge!=="path").map(([ge,he])=>`${ge}: ${he}`).join(" · ")})]})]},X)})})]})})]})]})}function hx(e){return e.normalize("NFC").replace(/\r\n?/g,`
64
+ Watch out — What should the agent avoid or be careful about?`;function hx(e,t,n,r){return px(e,t,r).map((a,o)=>{if(!a.matched)return s.jsx("span",{children:a.text},o);const i=a.matched;return s.jsx("button",{type:"button",onClick:()=>n(i),style:{background:"none",border:"none",padding:0,cursor:"pointer",color:"var(--accent)",textDecoration:"underline",font:"inherit"},children:a.label},o)})}function gx(){var re;const e=nn(),[t]=tm(),n=Number(t.get("step"))||2,[r,a]=u.useState(null),[o,i]=u.useState(null),[l,c]=u.useState(n),[d,f]=u.useState(null),[p,m]=u.useState(null),[w,v]=u.useState({}),[x,k]=u.useState(hu),[g,h]=u.useState(!1),[y,S]=u.useState(!0),[b,N]=u.useState(null),[C,I]=u.useState([]),[E,$]=u.useState(void 0),[U,V]=u.useState(!1),[J,D]=u.useState(null),[_,B]=u.useState(null),[ne,L]=u.useState(null),[z,W]=u.useState([]),[R,F]=u.useState(null);u.useEffect(()=>{var ge;const A=sessionStorage.getItem("agentAuth");if(!A){e("/mandates?new=1");return}const X=JSON.parse(A);a(X);const ae=sessionStorage.getItem("agentGate");if(ae){const he=JSON.parse(ae);he.bounds&&f(he.bounds),he.context&&m(he.context),(ge=he.gateContent)!=null&&ge.intent&&k(he.gateContent.intent)}T.getProfile(X.profileId).then(he=>i(he)).catch(()=>e("/mandates?new=1")).finally(()=>S(!1)),X.groupId&&Promise.all([T.getTeamProfileConfig(X.groupId,X.profileId).catch(()=>null),T.getGroupById(X.groupId).catch(()=>null),T.listUsers().catch(()=>[])]).then(([he,Pe,qe])=>{if(N(he),he){const _e=new Map;for(const le of qe){const et=le.name&&le.email?`${le.name} (${le.email})`:le.name||le.email||le.id;_e.set(le.id,et)}const yt=(Pe==null?void 0:Pe.members)??[];for(const le of yt){const et=le.userId??le.id;et&&(le.name&&le.email?_e.set(et,`${le.name} (${le.email})`):le.name&&_e.set(et,le.name))}const Ze=(he.approvers??[]).map(le=>_e.get(le)??le);I(Ze);const Ge=yt.find(le=>le.role==="admin");if(Ge){const le=Ge.userId??Ge.id;le&&$(_e.get(le)??Ge.name)}}})},[e]);const Q=d?Object.entries(d).filter(([A])=>A!=="profile"&&A!=="path").map(([A,X])=>`${A} = ${X}`).join(", "):"",q=(A,X,ae)=>{f(A),m(X),ae&&v(ae),c(3)},te=x.trim()!==hu.trim()&&x.trim()!=="",ce=A=>{te&&!confirm("Replace your current intent with the AI draft?")||k(A)},me=()=>{const A=o==null?void 0:o.ttl,X={intent:x},ae=JSON.parse(sessionStorage.getItem("agentGate")??"{}");sessionStorage.setItem("agentGate",JSON.stringify({...ae,bounds:d,context:p,contextLabels:w,gateContent:X,ttlConfig:A})),e("/mandates/new/sign")},ee=async()=>{if(r){V(!0),D(null),B(null),L(null),W([]),F(null);try{const A=await T.aiIntentReview({profileId:r.profileId,newIntent:x,context:p??void 0});W(A.grants??[]),A.success?A.review?D(A.review):B(A.note??"No other mandates on this profile to compare against."):L(A.error??"Check failed.")}catch(A){L(A instanceof Error?A.message:"Check failed.")}finally{V(!1)}}},oe=A=>{k(A),(J||_||ne)&&(D(null),B(null),L(null),W([]),F(null))};return y||!r||!o?s.jsx("p",{style:{color:"var(--text-tertiary)"},children:"Loading..."}):s.jsxs(s.Fragment,{children:[s.jsx(xm,{currentStep:l,onStepClick:A=>{A>=2&&c(A)}}),s.jsx(Kv,{profileId:r.profileId,bounds:Q||void 0,groupName:r.groupName,domain:r.domain}),l===2&&s.jsx("div",{className:"card",children:s.jsx(cx,{profile:o,onConfirm:q,onCancel:()=>e("/mandates?new=1"),initialBounds:d||void 0,initialContext:p||void 0,profileConfig:b,approverNames:C,adminName:E})}),l===3&&s.jsxs("div",{className:"intent-layout",children:[s.jsx("div",{className:"card intent-pane chat tool",children:s.jsx(_a,{target:{kind:"intent",profileId:r.profileId,bounds:Q||void 0},currentText:x,onApply:ce})}),s.jsxs("div",{className:"card intent-pane document",children:[s.jsx("h3",{className:"card-title",children:"What should your agent know?"}),s.jsxs("div",{className:"field-editable",style:{marginBottom:0},children:[s.jsxs("div",{className:"field-label",children:[s.jsx("span",{className:"pen",children:"✎"})," Intent — your words, signed with the grant"]}),s.jsx("textarea",{className:"intent-textarea",value:x,onChange:A=>oe(A.target.value)}),s.jsxs("div",{className:"char-counter",children:[x.length," / 2000"]})]}),s.jsxs("div",{style:{marginTop:"0.5rem"},children:[s.jsx("button",{type:"button",className:"btn btn-ghost",style:{fontSize:"0.8rem",padding:"0.4rem 0.75rem"},onClick:ee,disabled:U||!te,children:U?"Checking…":"Check against my other grants"}),ne&&s.jsxs("div",{className:"hint-box",role:"note",style:{marginTop:"0.5rem",borderLeftColor:"var(--danger)"},children:[s.jsx("span",{className:"hint-icon","aria-hidden":"true",children:"!"}),s.jsx("div",{className:"hint-body",children:ne})]}),_&&s.jsxs("div",{className:"hint-box",role:"note",style:{marginTop:"0.5rem"},children:[s.jsx("span",{className:"hint-icon","aria-hidden":"true",children:"i"}),s.jsx("div",{className:"hint-body",children:_})]}),J&&s.jsxs("div",{className:"hint-box",role:"note",style:{marginTop:"0.5rem"},children:[s.jsx("span",{className:"hint-icon","aria-hidden":"true",children:"i"}),s.jsxs("div",{className:"hint-body",children:[s.jsx("div",{className:"hint-head",children:"Intent review (advisory)"}),s.jsx("div",{style:{whiteSpace:"pre-wrap"},children:hx(J,z,F,$e(r.profileId))}),s.jsx("div",{style:{fontSize:"0.7rem",color:"var(--text-tertiary)",marginTop:"0.4rem"},children:"Checked with your configured assistant. AI surfaces reality — you decide."})]})]})]}),s.jsxs("div",{className:"intent-footer",children:[s.jsx("button",{className:"btn btn-ghost",onClick:()=>c(2),children:"Back"}),s.jsx("button",{className:"btn btn-primary intent-continue-btn",onClick:me,disabled:!te,children:"Continue to Review"})]}),(((re=b==null?void 0:b.approvers)==null?void 0:re.length)??0)>0&&s.jsxs("div",{className:"hint-box",role:"note",children:[s.jsx("span",{className:"hint-icon","aria-hidden":"true",children:"i"}),s.jsxs("div",{className:"hint-body",children:[s.jsxs("div",{className:"hint-head",children:["Visible to ",C.length>0?C.join(", "):"the configured approvers"]}),"Your intent will be encrypted and shared with"," ",C.length>0?C.join(", "):"this profile's required approvers",". Only they can decrypt it — your Authority Server cannot. Each approver stores a copy as their accountability record."]})]})]}),s.jsx("button",{type:"button",className:"floating-help",onClick:()=>h(!0),"aria-label":"Open intent assistant",children:"Get help with intent"}),s.jsx(wm,{open:g,onClose:()=>h(!1),ariaLabel:"Intent assistant",children:s.jsx(_a,{target:{kind:"intent",profileId:r.profileId,bounds:Q||void 0},currentText:x,onApply:A=>{ce(A),h(!1)}})}),R&&s.jsx("div",{className:"modal-backdrop",onClick:A=>A.target===A.currentTarget&&F(null),children:s.jsxs("div",{className:"modal",children:[s.jsxs("div",{className:"modal-header",children:[s.jsx("h3",{className:"modal-title",children:R.length>1?`Existing mandates (${R.length})`:"Existing mandate"}),s.jsx("button",{className:"modal-close",onClick:()=>F(null),children:"×"})]}),s.jsx("div",{className:"modal-body",children:R.map((A,X)=>{var ae;return s.jsxs("div",{style:{marginBottom:X<R.length-1?"1rem":0,paddingBottom:X<R.length-1?"1rem":0,borderBottom:X<R.length-1?"1px solid var(--border)":"none"},children:[s.jsx("div",{style:{fontSize:"0.7rem",fontWeight:600,color:"var(--text-tertiary)",textTransform:"uppercase",letterSpacing:"0.04em",marginBottom:"0.25rem"},children:"Scope"}),s.jsx("div",{style:{marginBottom:"0.75rem"},children:A.scope}),s.jsx("div",{style:{fontSize:"0.7rem",fontWeight:600,color:"var(--text-tertiary)",textTransform:"uppercase",letterSpacing:"0.04em",marginBottom:"0.25rem"},children:"Intent"}),s.jsx("div",{style:{whiteSpace:"pre-wrap",marginBottom:"0.75rem"},children:((ae=A.intent)==null?void 0:ae.trim())||"(no intent recorded)"}),Object.entries(A.bounds).filter(([ge])=>ge!=="profile"&&ge!=="path").length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{style:{fontSize:"0.7rem",fontWeight:600,color:"var(--text-tertiary)",textTransform:"uppercase",letterSpacing:"0.04em",marginBottom:"0.25rem"},children:"Limits"}),s.jsx("div",{style:{fontSize:"0.85rem",color:"var(--text-secondary)"},children:Object.entries(A.bounds).filter(([ge])=>ge!=="profile"&&ge!=="path").map(([ge,he])=>`${ge}: ${he}`).join(" · ")})]})]},X)})})]})})]})]})}function yx(e){return e.normalize("NFC").replace(/\r\n?/g,`
65
65
  `).split(`
66
66
  `).map(a=>a.replace(/[ \t]+$/,"")).join(`
67
- `).replace(/\n+$/,"")}async function Sm(e){const n=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",n);return Array.from(new Uint8Array(r)).map(o=>o.toString(16).padStart(2,"0")).join("")}class gx extends Error{constructor(n,r,a){super(a);Sr(this,"code");Sr(this,"field");this.name="CanonicalValueError",this.code=n,this.field=r}}function yx(e){const t=new TextEncoder().encode(e);let n="";for(const r of t)r===61||r===37||r<32||r>126?n+="%"+r.toString(16).toUpperCase().padStart(2,"0"):n+=String.fromCharCode(r);return n}function jm(e,t,n){const r=[];for(const a of t){const o=e[a];if(o==null)continue;const i=String(o);if(i.includes(`
68
- `)||i.includes("\r"))throw new gx(n,a,`Value for "${a}" contains a raw newline or carriage return. Refusing: a hash over stripped or normalized input would not represent what was authorized.`);r.push(`${a}=${yx(i)}`)}return r.join(`
69
- `)}async function aa(e,t){const n=t.boundsSchema??t.frameSchema;if(!n)throw new Error("Profile has no boundsSchema or frameSchema");const r=jm(e,n.keyOrder,"BOUNDS_INVALID_VALUE");return`sha256:${await Sm(r)}`}async function km(e,t){const n=t.contextSchema?jm(e,t.contextSchema.keyOrder,"CONTEXT_INVALID_VALUE"):"";return`sha256:${await Sm(n)}`}async function Aa(e){const t=new TextEncoder().encode(hx(e)),n=await crypto.subtle.digest("SHA-256",t);return`sha256:${Array.from(new Uint8Array(n)).map(o=>o.toString(16).padStart(2,"0")).join("")}`}function bm(e,t){if(!e.authorization_id)throw new Error("Attest result lacks authorization_id — the Authority Server predates per-ceremony identity. Update the Authority Server (lockstep deploy).");return{authorizationId:e.authorization_id,boundsHash:e.bounds_hash??t.boundsHash,contextHash:t.contextHash,context:t.context,...t.contextLabels&&Object.keys(t.contextLabels).length>0?{contextLabels:t.contextLabels}:{},gateContent:t.gateContent,...t.path?{path:t.path}:{}}}function gu(e){return e==null?new Set:new Set(String(e).split(",").map(t=>t.trim().toLowerCase()).filter(Boolean))}function vx(e,t){for(const n of e)if(t.has(n))return!0;return!1}function xx(e,t,n){for(const r of e){const a=gu(t[r]),o=gu(n[r]);if(!(a.size===0||o.size===0)&&!vx(a,o))return!1}return!0}function wx(e){return e.length>24?`${e.slice(0,10)}…`:e}function Cm(e,t,n){const r=n==null?void 0:n[e];return String(t).split(",").map(o=>o.trim()).filter(Boolean).map(o=>{const i=r==null?void 0:r[o];return i?`${i} (${wx(o)})`:o}).join(", ")}function Sx(e,t,n){return e.isPersonal?!1:t&&((n==null?void 0:n.length)??0)===0}function jx(){var le,et,Ut;const e=nn(),{user:t,mode:n,domain:r}=Fe(),[a,o]=u.useState(null),[i,l]=u.useState(null),[c,d]=u.useState(null),[f,p]=u.useState("per-action"),[m,w]=u.useState(1800),[v,x]=u.useState(86400),[k,g]=u.useState(""),[h,y]=u.useState("hours"),[S,b]=u.useState(""),[N,C]=u.useState(!0),[I,E]=u.useState(!1),[$,U]=u.useState(""),[V,J]=u.useState(null),[D,_]=u.useState([]),[B,ne]=u.useState(!1),[L,z]=u.useState([]),[W,R]=u.useState(0);u.useEffect(()=>{var bn;const j=sessionStorage.getItem("agentAuth"),P=sessionStorage.getItem("agentGate");if(!j||!P){e("/mandates?new=1");return}const O=JSON.parse(j),G=JSON.parse(P),se={bounds:G.bounds??{},context:G.context??{},contextLabels:G.contextLabels??void 0,gateContent:G.gateContent};o(O),l(se),G.ttlConfig&&(w(G.ttlConfig.default??1800),x(G.ttlConfig.max??86400)),G.templateMode==="automatic"?p("immediate"):G.templateMode==="review"&&p("per-action");const Nt=((bn=G.ttlConfig)==null?void 0:bn.max)??86400;if(typeof G.templateTtl=="number"&&G.templateTtl>0){const Ie=Math.min(G.templateTtl,Nt);w(Ie),[3600,86400,604800,2592e3,31536e3].includes(Ie)||(Ie%86400===0?(g(String(Ie/86400)),y("days")):(g(String(Math.max(1,Math.round(Ie/3600)))),y("hours")))}T.getProfile(O.profileId).then(Ie=>{var it;if(d(Ie),!S){const vt=Ie.name??((it=O.profileId.split("/").pop())==null?void 0:it.replace(/@.*$/,""))??"",tt=[];if(se.context&&Ie.contextSchema)for(const Z of Ie.contextSchema.keyOrder){const K=se.context[Z];if(K!==void 0&&K!==""){const de=String(K).split(",").map(ye=>ye.trim()).filter(Boolean);tt.push(de.join(", "))}}const H=tt.length>0?`${vt}: ${tt.join(" · ")}`:vt;b(H)}}).catch(()=>{}),O.isPersonal?ne(!0):Promise.all([T.getTeamProfileConfig(O.groupId,O.profileId).catch(()=>null),T.getGroupById(O.groupId).catch(()=>null),T.listUsers().catch(()=>[])]).then(([Ie,it,vt])=>{if(J(Ie),Ie){const tt=new Map;for(const K of vt){const de=K.name&&K.email?`${K.name} (${K.email})`:K.name||K.email||K.id;tt.set(K.id,de)}const H=(it==null?void 0:it.members)??[];for(const K of H){const de=K.userId??K.id;de&&(K.name&&K.email?tt.set(de,`${K.name} (${K.email})`):K.name&&tt.set(de,K.name))}const Z=(Ie.approvers??[]).map(K=>tt.get(K)??K);_(Z)}}).finally(()=>{ne(!0)})},[e]),u.useEffect(()=>{if(!(a!=null&&a.profileId))return;const j=a.profileId,P=sessionStorage.getItem("agentEditReplaces");T.getEnrichedAuthorizations().then(O=>{const G=O.filter(se=>se.profileId===j&&se.authorizationId!==P).map(se=>({authorizationId:se.authorizationId,bounds:se.bounds,context:se.context??{},intent:se.intent}));z(G)}).catch(()=>z([]))},[a==null?void 0:a.profileId]),u.useEffect(()=>{if(!i||!c||L.length===0){R(0);return}let j=!1;return(async()=>{const P=await aa(i.bounds,c),O=await Promise.all(L.map(G=>aa(G.bounds,c).catch(()=>null)));j||R(O.filter(G=>G===P).length)})().catch(()=>{j||R(0)}),()=>{j=!0}},[i,c,L]);const F=async()=>{if(!(!a||!i||!c||!t)){if(!a.groupId){U("No active group; cannot create mandate.");return}E(!0),U("");try{const j=r||a.domain||"owner",P=await aa(i.bounds,c),O=await km(i.context,c),[G,se]=await Promise.all([Aa(i.gateContent.intent),Aa(JSON.stringify({profile:a.profileId,domain:j,group:a.groupId}))]);let Nt,bn,Ie,it;if(a.isTeam){const Z=await T.getApproversPubkeys(a.groupId,a.profileId);if(Z.length>0){const K=await T.encryptIntent(i.gateContent.intent,Z);Nt=K.intentCiphertext,bn=K.encryptedKeys,Ie=K.approversFrozen,it=K.intentDisclosureHash}}const vt=`authz_${crypto.randomUUID()}`,tt=sessionStorage.getItem("agentEditReplaces")||void 0,H=await T.attest({authorization_id:vt,replaces:tt,profile_id:a.profileId,bounds:i.bounds,bounds_hash:P,context_hash:O,domain:j,did:t.did,gate_content_hashes:{intent:G},execution_context_hash:se,group_id:a.groupId,ttl:m,commitment_mode:f==="per-action"?"review":"automatic",title:S.trim(),intent_ciphertext:Nt,encrypted_keys:bn,approvers_frozen:Ie,intent_disclosure_hash:it,disclose_identity:N});try{await T.pushGateContent(bm(H,{boundsHash:P,contextHash:O,context:i.context,contextLabels:i.contextLabels,gateContent:i.gateContent}))}catch(Z){try{await T.revokeAttestation(vt,"Auto-revoked: gate content push failed")}catch{}throw new Error(`Mandate signed but gate content delivery failed. The mandate was revoked. Please try again. (${Z instanceof Error?Z.message:"Unknown error"})`)}if(tt)try{await T.revokeAttestation(tt,`Replaced by ${vt} (edit)`),T.resyncGates().catch(()=>{})}catch{}sessionStorage.removeItem("agentAuth"),sessionStorage.removeItem("agentGate"),sessionStorage.removeItem("agentEditReplaces"),e(`/mandates?highlight=${encodeURIComponent(vt)}`)}catch(j){U(j instanceof Error?j.message:"Signing the mandate failed")}finally{E(!1)}}};if(!a||!i)return s.jsx("p",{style:{color:"var(--text-tertiary)"},children:"Loading..."});const Q=Object.entries(i.bounds).filter(([j])=>j!=="profile"&&j!=="path"),q=Object.entries(i.context),ce=((V==null?void 0:V.caps)!=null?Object.keys(V.caps):[]).length!==0,me=D.length>0?D.join(", "):((V==null?void 0:V.approvers)??[]).join(", "),ee=ce?`Within-cap actions run per the mode you choose above. Over-cap actions will require approval from you and ${me}, regardless of your mode.`:"No caps set — they won't gate any action, but your intent is encrypted and shared with them as an accountability record.",oe=ce?`Over-cap actions will be reviewed by you and ${me}. Within-cap actions run per the mode you chose above.`:`Approvers ${me} can read your intent but won't gate any action — no caps configured on this profile.`,re=!!((le=V==null?void 0:V.approvers)!=null&&le.length),A=Sx(a,B,V==null?void 0:V.approvers),X=m>v,ae={flex:1,padding:"0.75rem",border:f==="immediate"?"2px solid var(--accent)":"1px solid var(--border)",borderRadius:"var(--radius)",background:f==="immediate"?"var(--accent-subtle)":"var(--bg-elevated)",cursor:"pointer",textAlign:"left",fontFamily:"inherit"},ge={flex:1,padding:"0.75rem",border:f==="per-action"?"2px solid var(--accent)":"1px solid var(--border)",borderRadius:"var(--radius)",background:f==="per-action"?"var(--accent-subtle)":"var(--bg-elevated)",cursor:"pointer",textAlign:"left",fontFamily:"inherit"},he=((et=c==null?void 0:c.contextSchema)==null?void 0:et.keyOrder)??[],Pe=L.filter(j=>xx(he,i.context,j.context)),qe=Pe.length>0,_e=$e(a.profileId),yt=j=>{const P=Object.values(j).map(O=>String(O).trim()).filter(Boolean);return P.length>0?P.join(", "):"all (unscoped)"},Ze=Pe.map(j=>yt(j.context)).join("; "),Ge=`This grant's scope overlaps an existing grant on ${_e} (scoped to: ${Ze}). The agent may act under either. Per-action limits take the more permissive value, and daily limits add together — two grants of 10/day allow 20/day. Approval is not weakened: if either grant requires review, review still applies. Confirm this is intended before authorizing.`;return s.jsxs(s.Fragment,{children:[s.jsx(xm,{currentStep:4,onStepClick:j=>{j<=3&&e(`/mandates/new/intent?step=${j}`)}}),s.jsxs("div",{className:"card",children:[s.jsx("h3",{className:"card-title",style:{marginBottom:"0.25rem"},children:"Review & Commit"}),s.jsx("p",{style:{fontSize:"0.85rem",color:"var(--text-secondary)",marginBottom:"1.5rem"},children:"Review your mandate details before signing."}),$&&s.jsx("div",{className:"error-message",children:$}),s.jsxs("div",{className:"field-editable",children:[s.jsxs("div",{className:"field-label",children:[s.jsx("span",{className:"pen",children:"✎"})," Title"]}),s.jsx("input",{type:"text",className:"form-input",placeholder:`e.g. ${$e(a.profileId)}: daily operations`,value:S,onChange:j=>b(j.target.value),maxLength:80,style:{fontSize:"0.9rem"}}),s.jsx("div",{style:{fontSize:"0.7rem",color:"var(--text-tertiary)",marginTop:"0.25rem"},children:"A short name to identify this mandate on your dashboard."})]}),s.jsxs("div",{className:"field-editable",children:[s.jsxs("div",{className:"field-label",children:[s.jsx("span",{className:"pen",children:"✎"})," Commitment"]}),s.jsxs("div",{style:{display:"flex",gap:"0.75rem"},children:[s.jsxs("button",{onClick:()=>p("per-action"),style:ge,children:[s.jsx("div",{style:{fontWeight:600,fontSize:"0.85rem",marginBottom:"0.25rem",color:"var(--text-primary)"},children:"Review Each Action"}),s.jsx("div",{style:{fontSize:"0.75rem",color:"var(--text-secondary)"},children:"You review and approve each action before it executes."})]}),s.jsxs("button",{onClick:()=>p("immediate"),style:ae,children:[s.jsx("div",{style:{fontWeight:600,fontSize:"0.85rem",marginBottom:"0.25rem",color:"var(--text-primary)"},children:"Automatic"}),s.jsx("div",{style:{fontSize:"0.75rem",color:"var(--text-secondary)"},children:"Agent acts freely within your limits."})]})]})]}),s.jsxs("div",{className:"field-editable",children:[s.jsxs("div",{className:"field-label",children:[s.jsx("span",{className:"pen",children:"✎"})," Duration"]}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem",flexWrap:"wrap",alignItems:"center"},children:[[{label:"1 hour",seconds:3600},{label:"24 hours",seconds:86400},{label:"7 days",seconds:604800},{label:"30 days",seconds:2592e3},{label:"1 year",seconds:31536e3}].filter(j=>j.seconds<=v).map(j=>s.jsx("button",{onClick:()=>{w(j.seconds),g("")},style:{padding:"0.5rem 0.85rem",border:m===j.seconds?"2px solid var(--accent)":"1px solid var(--border)",borderRadius:"0.375rem",background:m===j.seconds?"var(--accent-subtle)":"var(--bg-elevated)",cursor:"pointer",fontSize:"0.85rem",fontFamily:"inherit",color:"var(--text-primary)"},children:j.label},j.seconds)),s.jsxs("div",{style:{display:"flex",gap:"0.375rem",alignItems:"center"},children:[s.jsx("input",{type:"number",className:"form-input",style:{width:"5rem",padding:"0.45rem 0.6rem",fontSize:"0.85rem"},placeholder:"Custom",value:k,onChange:j=>{g(j.target.value);const P=parseInt(j.target.value,10);if(P>0){const O=h==="days"?P*86400:P*3600;w(Math.min(O,v))}}}),s.jsxs("select",{className:"form-input",style:{padding:"0.45rem 0.5rem",fontSize:"0.85rem"},value:h,onChange:j=>{y(j.target.value);const P=parseInt(k,10);if(P>0){const O=j.target.value==="days"?P*86400:P*3600;w(Math.min(O,v))}},children:[s.jsx("option",{value:"hours",children:"hours"}),s.jsx("option",{value:"days",children:"days"})]})]}),X&&s.jsxs("span",{style:{fontSize:"0.75rem",color:"var(--danger)"},children:["Maximum: ",v>=86400?`${Math.floor(v/86400)} days`:`${Math.floor(v/3600)} hours`]})]})]}),s.jsx("div",{className:"field-editable",children:s.jsxs("label",{style:{display:"flex",alignItems:"flex-start",gap:"0.5rem",cursor:"pointer"},children:[s.jsx("input",{type:"checkbox",checked:N,onChange:j=>C(j.target.checked),style:{marginTop:"0.15rem"}}),s.jsxs("span",{style:{fontSize:"0.8rem"},children:["Show my verified name on actions under this mandate",s.jsx("div",{style:{fontSize:"0.7rem",color:"var(--text-tertiary)",marginTop:"0.15rem"},children:'Adds "verified by Suveren" with your name to outgoing content. Takes effect only if your identity is verified; otherwise actions stay pseudonymous.'})]})]})}),s.jsx("div",{className:"info-section-label",children:"What you are signing — set in previous steps"}),s.jsxs("div",{className:"info-block",children:[s.jsxs("div",{className:"info-head",children:[s.jsx("span",{className:"info-title",children:"Intent"}),s.jsx("button",{className:"info-edit",onClick:()=>e("/mandates/new/intent?step=3"),children:"edit in step 3"})]}),s.jsx("div",{style:{whiteSpace:"pre-wrap"},children:i.gateContent.intent})]}),(!!Q.length||!!q.length)&&s.jsxs("div",{className:"info-block",children:[s.jsxs("div",{className:"info-head",children:[s.jsx("span",{className:"info-title",children:"Scope & Limits"}),s.jsx("button",{className:"info-edit",onClick:()=>e("/mandates/new/intent?step=2"),children:"edit in step 2"})]}),s.jsxs("dl",{className:"info-kv",children:[q.map(([j,P])=>s.jsxs("span",{style:{display:"contents"},children:[s.jsx("dt",{children:j}),s.jsx("dd",{children:Cm(j,P,i.contextLabels)})]},j)),Q.map(([j,P])=>s.jsxs("span",{style:{display:"contents"},children:[s.jsx("dt",{children:j}),s.jsx("dd",{children:String(P)})]},j))]})]}),s.jsxs("div",{className:"info-block",children:[s.jsx("div",{className:"info-head",children:s.jsx("span",{className:"info-title",children:"Authority"})}),s.jsxs("dl",{className:"info-kv",children:[s.jsx("dt",{children:"Profile"}),s.jsxs("dd",{children:[$e(a.profileId),s.jsx("div",{style:{fontSize:"0.75rem",color:"var(--text-tertiary)",marginTop:"0.125rem"},children:a.profileId})]}),!a.isPersonal&&a.groupName&&s.jsxs(s.Fragment,{children:[s.jsx("dt",{children:"Team"}),s.jsx("dd",{children:a.groupName})]}),!a.isPersonal&&s.jsxs(s.Fragment,{children:[s.jsx("dt",{children:"Approvers"}),s.jsx("dd",{children:B?(((Ut=V==null?void 0:V.approvers)==null?void 0:Ut.length)??0)===0?s.jsxs(s.Fragment,{children:[s.jsxs("span",{style:{color:"var(--danger)",fontWeight:600},children:["Not enabled for ",a.groupName??"this team"]}),s.jsx("div",{style:{fontSize:"0.75rem",color:"var(--text-tertiary)",marginTop:"0.125rem"},children:"A team admin must name at least one approver for this profile on the Authority Server (team → Profiles) before anyone can grant under it. Personal use is unaffected."})]}):s.jsxs(s.Fragment,{children:[me,s.jsx("div",{style:{fontSize:"0.75rem",color:"var(--text-tertiary)",marginTop:"0.125rem"},children:ee})]}):s.jsx("span",{style:{color:"var(--text-tertiary)"},children:"Loading…"})})]})]})]}),W>0?s.jsxs("div",{style:{display:"flex",gap:"0.625rem",padding:"0.75rem 0.875rem",marginBottom:"1.25rem",border:"1px solid var(--warning)",borderLeft:"3px solid var(--warning)",borderRadius:"0.5rem",background:"var(--bg-elevated)",fontSize:"0.82rem",color:"var(--text-primary)"},children:[s.jsx("span",{"aria-hidden":"true",style:{color:"var(--warning)",fontWeight:700},children:"⚠"}),s.jsxs("div",{children:[s.jsx("div",{style:{fontWeight:600,color:"var(--warning)",marginBottom:"0.2rem"},children:"Identical limits to an existing grant"}),s.jsxs("div",{children:[W===1?`An active grant on ${_e} already has exactly these limits.`:`${W} active grants on ${_e} already have exactly these limits.`," ","If you meant to give the existing grant more time, use ",s.jsx("strong",{children:"Extend"})," on the Mandates page instead — authorizing here creates a separate, independent grant with its own intent and usage counters."]})]})]}):null,qe?s.jsxs("div",{style:{display:"flex",gap:"0.625rem",padding:"0.75rem 0.875rem",marginBottom:"1.25rem",border:"1px solid var(--warning)",borderLeft:"3px solid var(--warning)",borderRadius:"0.5rem",background:"var(--bg-elevated)",fontSize:"0.82rem",color:"var(--text-primary)"},children:[s.jsx("span",{"aria-hidden":"true",style:{color:"var(--warning)",fontWeight:700},children:"⚠"}),s.jsxs("div",{children:[s.jsx("div",{style:{fontWeight:600,color:"var(--warning)",marginBottom:"0.2rem"},children:"Overlapping scope"}),s.jsx("div",{children:Ge})]})]}):null,s.jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[s.jsx("button",{className:"btn btn-ghost",onClick:()=>e("/mandates/new/intent"),children:"Back"}),s.jsx("button",{className:"btn btn-primary btn-lg",style:{flex:1},onClick:F,disabled:I||!S.trim()||A,children:I?"Signing...":f==="immediate"?"Sign mandate":"Sign mandate (asks first)"})]}),s.jsx("div",{style:{marginTop:"1rem",fontSize:"0.75rem",color:"var(--text-tertiary)",textAlign:"center",display:re?"block":"none"},children:oe})]})]})}const kx={card:"💳",mail:"✉️"};function Nm(e){return kx[e]??"🔧"}function bx(e){const t=e==null?void 0:e.overrides;return!t||typeof t!="object"?!1:Object.values(t).some(n=>{var r;return typeof((r=n==null?void 0:n.read)==null?void 0:r.ageField)=="string"})}const Cx=[0,7,30,90,365,3650];function Us(e){return e===null?"From your mandate":e===0?"Read nothing":e===1?"1 day back":e===365?"1 year back":e%365===0?`${e/365} years back`:`${e} days back`}function Nx(e){return(e==null?void 0:e.paused)==="simulation"?{chip:{c:"int-chip-paused",t:"Paused"},showStart:!1}:e&&!e.running&&e.error?{chip:{c:"int-chip-bad",t:"Crashed"},showStart:!0}:{chip:{c:"int-chip-idle",t:"Stopped"},showStart:!0}}function $o({manifest:e,integration:t,state:n,onStatusChange:r,onSuccess:a}){var Ut;const[o,i]=u.useState({}),[l,c]=u.useState(!1),[d,f]=u.useState(!1),[p,m]=u.useState({}),[w,v]=u.useState({}),[x,k]=u.useState(void 0),[g,h]=u.useState(!1),[y,S]=u.useState(null),[b,N]=u.useState(!1),[C,I]=u.useState(!1),[E,$]=u.useState(!1),[U,V]=u.useState(!1),[J,D]=u.useState({}),[_,B]=u.useState(null),[ne,L]=u.useState(!1),[z,W]=u.useState(null),[R,F]=u.useState(!1);u.useEffect(()=>{let j=!1;return T.getCredential(e.id).then(P=>{var O;if(!(j||!P.configured)){if(c(!0),f(!0),P.fields){const G={};for(const se of e.credentials.fields)P.fields[se.key]!=null&&(G[se.key]=P.fields[se.key]);m(G)}if(v(P.secrets??{}),k(P.updatedAt),e.oauth){const G=((O=P.fieldNames)==null?void 0:O.includes(e.oauth.tokenStorage))??!1;h(G),G&&T.getOAuthHealth(e.id).then(se=>{j||S(se)})}}}).catch(()=>{}),()=>{j=!0}},[e.id,e.oauth]);const Q=bx(e.toolGating),q=t?t.readAgeDays??null:void 0,te=ne&&_?_.value:q,ce=async j=>{B({value:j}),L(!0),W(null);try{await T.setReadPolicy(e.id,j),a(j===null?`${e.name} read window now follows your mandate`:`${e.name} read window set to ${Us(j).toLowerCase()}`),r()}catch(P){W(P instanceof Error?P.message:"Could not save")}finally{L(!1),B(null)}},me=!!e.oauth||e.credentials.fields.some(j=>!j.optional),ee=e.oauth?g:l,oe=!me||ee,re=n==="starting"?"starting":oe?t!=null&&t.running?"running":!l&&e.credentials.fields.length>0?"unconfigured":"ready":e.oauth&&l&&!g?"needs-oauth":"unconfigured",A=async()=>{if(e.credentials.fields.some(P=>{var O;return(O=o[P.key])==null?void 0:O.trim()})){N(!0);try{await T.setCredential(e.id,o),c(!0),i({}),e.oauth?a(`${e.name} credentials saved!`):(a(`${e.name} credentials saved — starting integration...`),await Pe())}catch{a(`Failed to save ${e.name} credentials`)}finally{N(!1)}}},X=()=>{const j={};for(const P of e.credentials.fields){const O=o[P.key];P.type==="password"?O!=null&&O.trim()&&(j[P.key]=O):O!=null&&O!==(p[P.key]??"")&&(j[P.key]=O)}return j},ae=Object.keys(X()).length>0,ge=async()=>{const j=X();if(Object.keys(j).length!==0){N(!0);try{await T.setCredential(e.id,j),i({}),c(!0),e.oauth?a(`${e.name} credentials saved — now click Connect.`):(V(!1),a(`${e.name} credentials updated — restarting...`),await Pe())}catch{a(`Failed to update ${e.name} credentials`)}finally{N(!1)}}},he=()=>{window.open(`/auth/oauth/${e.id}/start`,"_blank","width=600,height=700");const j=setInterval(async()=>{var P;try{const O=await T.getCredential(e.id);O.configured&&e.oauth&&((P=O.fieldNames)!=null&&P.includes(e.oauth.tokenStorage))&&(h(!0),V(!1),S(null),clearInterval(j),a(`${e.name} connected — starting integration...`),T.getOAuthHealth(e.id).then(S).catch(()=>{}),await Pe())}catch{}},2e3);setTimeout(()=>clearInterval(j),12e4)},Pe=async()=>{$(!0);try{const j=await T.activateIntegration(e.id);j.warning?a(j.warning):a(`${e.name} integration started with ${j.tools.length} tools`),r()}catch(j){a(`Failed to start ${e.name}: ${j instanceof Error?j.message:"Unknown error"}`)}finally{$(!1)}},qe=async()=>{try{await T.removeMcpIntegration(e.id),a(`${e.name} integration removed`),r()}catch{a(`Failed to remove ${e.name}`)}},_e=Nm(e.icon),yt=Nx(t),Ze=re==="running"?{c:"int-chip-ok",t:"Running"}:re==="starting"?{c:"int-chip-idle",t:"Starting"}:yt.chip,Ge=e.oauth&&g&&(y==null?void 0:y.status)==="failed",le=me?Ge?{c:"int-chip-bad",t:"Auth failed"}:ee?{c:"int-chip-ok",t:"Auth OK"}:{c:"int-chip-idle",t:"Not set up"}:{c:"int-chip-idle",t:"No auth"},et=j=>j.replace(/https?:\/\/[^\s)]+\/auth\/oauth\/[a-z-]+\/callback/gi,`${window.location.origin}/auth/oauth/${e.id}/callback`);return s.jsxs("div",{className:"card",style:{marginBottom:"1rem"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"0.75rem"},children:[s.jsx("span",{style:{fontSize:"1.4rem",lineHeight:1.2},children:_e}),s.jsx("h3",{className:"card-title",style:{margin:0,flex:1,alignSelf:"center"},children:e.name}),s.jsxs("div",{style:{display:"flex",gap:"0.4rem",flexWrap:"wrap",justifyContent:"flex-end"},children:[re!=="unconfigured"&&re!=="needs-oauth"&&s.jsxs("span",{className:`int-chip ${Ze.c}`,children:[s.jsx("span",{className:"int-dot"}),Ze.t]}),s.jsxs("span",{className:`int-chip ${le.c}`,children:[s.jsx("span",{className:"int-dot"}),le.t]}),Fv(e,p)&&s.jsxs("span",{className:"int-chip int-chip-sim",title:"This connector answers from a simulated system with test data. Nothing reaches your real systems.",children:[s.jsx("span",{className:"int-dot"}),"Simulation"]})]})]}),e.oauth&&g&&s.jsx("div",{className:"int-account",style:{marginTop:"0.7rem"},children:y!=null&&y.account?s.jsxs(s.Fragment,{children:["Connected as ",s.jsx("b",{children:y.account})]}):s.jsx("span",{className:"int-none",children:"Account not recorded — reconnect to capture which account is used"})}),Ge&&!U&&s.jsxs("div",{style:{marginTop:"0.7rem",border:"1px solid var(--danger)",borderRadius:"10px",padding:"0.8rem 0.95rem",background:"color-mix(in srgb, var(--danger) 5%, var(--bg-elevated))"},children:[s.jsxs("div",{style:{fontSize:"0.86rem",fontWeight:700},children:[e.name," stopped accepting the stored credentials"]}),s.jsxs("p",{style:{fontSize:"0.8rem",color:"var(--text-muted)",margin:"0.3rem 0 0",lineHeight:1.55},children:[(y==null?void 0:y.error)==="invalid_grant"?s.jsxs(s.Fragment,{children:["The refresh token was revoked (",s.jsx("code",{children:"invalid_grant"}),") — this usually follows a password change or a security checkup on the provider's side."]}):y!=null&&y.error?s.jsxs(s.Fragment,{children:["The provider reported ",s.jsx("code",{children:y.error}),"."]}):s.jsx(s.Fragment,{children:"The provider rejected the stored authentication."})," ","Your agent's ",e.name," actions are ",s.jsx("b",{children:"blocked"}),", not failing silently."]}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem",marginTop:"0.6rem"},children:[s.jsxs("button",{className:"btn btn-primary btn-sm",onClick:he,children:["Reconnect ",e.name]}),s.jsx("button",{className:"btn btn-ghost btn-sm",onClick:()=>{i({...p}),V(!0)},children:"Edit credentials"})]})]}),s.jsxs("details",{className:"int-details",style:{marginTop:"0.85rem",marginBottom:"1.25rem"},children:[s.jsx("summary",{children:"Details"}),s.jsxs("div",{className:"int-meta",children:[s.jsx("span",{className:"int-k",children:"What"}),s.jsx("span",{children:e.description}),e.profile&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"int-k",children:"Profile"}),s.jsx("span",{children:e.profile})]}),e.oauth&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"int-k",children:"Scopes"}),s.jsx("span",{children:((Ut=e.oauth.scopes)==null?void 0:Ut.join(", "))||"—"})]}),t&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"int-k",children:"Tools"}),s.jsxs("span",{children:[t.toolCount," gated"]})]})]})]}),e.setupGuide&&e.setupGuide.length>0&&(re!=="running"||Ge)&&s.jsxs("div",{style:{marginBottom:"0.75rem"},children:[s.jsxs("button",{onClick:()=>I(!C),style:{background:"none",border:"none",padding:0,fontSize:"0.8rem",color:"var(--accent)",cursor:"pointer",display:"flex",alignItems:"center",gap:"0.375rem"},children:[s.jsx("span",{style:{transition:"transform 0.2s",transform:C?"rotate(90deg)":"rotate(0deg)",display:"inline-block"},children:"▶"}),"How to set up ",e.name]}),C&&s.jsx("div",{style:{marginTop:"0.75rem",paddingLeft:"0.25rem"},children:e.setupGuide.map((j,P)=>s.jsxs("div",{style:{display:"flex",gap:"0.75rem",marginBottom:"0.75rem"},children:[s.jsx("div",{style:{width:"1.5rem",height:"1.5rem",borderRadius:"50%",background:"var(--border)",color:"var(--text-secondary)",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"0.7rem",fontWeight:700,flexShrink:0,marginTop:"0.1rem"},children:P+1}),s.jsxs("div",{children:[s.jsx("div",{style:{fontSize:"0.85rem",fontWeight:600,color:"var(--text-primary)",marginBottom:"0.125rem"},children:j.title}),s.jsxs("div",{style:{fontSize:"0.8rem",color:"var(--text-secondary)",lineHeight:1.5},children:[et(j.description),j.link&&s.jsxs(s.Fragment,{children:[" ",s.jsxs("a",{href:j.link,target:"_blank",rel:"noopener noreferrer",style:{fontSize:"0.8rem"},children:["Open ","↗"]})]})]})]})]},P))})]}),re==="starting"&&s.jsxs("div",{className:"service-status",style:{color:"var(--warning)"},children:[s.jsx("span",{className:"service-status-dot",style:{background:"var(--warning)"}}),"Starting…"]}),U&&s.jsxs("div",{style:{marginTop:"0.7rem",paddingTop:"0.85rem",borderTop:"1px solid var(--border)"},children:[s.jsx("div",{style:{fontSize:"0.85rem",fontWeight:600,marginBottom:"0.5rem"},children:"Change credentials"}),d&&s.jsxs("p",{style:{fontSize:"0.8rem",color:"var(--text-muted)",marginBottom:"0.6rem"},children:["Leaving a secret blank keeps the stored one — editing other fields can never silently wipe it.",e.oauth?" Save, then Connect to re-link the account.":""]}),e.credentials.fields.map(j=>{var P;return s.jsxs("div",{className:"form-group",style:{marginBottom:"0.6rem"},children:[s.jsx("label",{className:"form-label",children:j.label}),j.type==="password"?s.jsxs("div",{className:"cred-field",children:[s.jsx("input",{className:"form-input",type:J[j.key]?"text":"password",name:`${e.id}-${j.key}-credential`,autoComplete:"new-password",placeholder:(P=w[j.key])!=null&&P.preview?`Unchanged — ends in ${w[j.key].preview}`:d?"Unchanged — paste a new value to replace":j.placeholder,value:o[j.key]||"",onChange:O=>i(G=>({...G,[j.key]:O.target.value}))}),s.jsx("button",{className:"cred-toggle",onClick:()=>D(O=>({...O,[j.key]:!O[j.key]})),children:J[j.key]?"hide":"show"})]}):s.jsx("input",{className:"form-input",type:"text",name:`${e.id}-${j.key}-credential`,autoComplete:"off",placeholder:j.placeholder,value:o[j.key]||"",onChange:O=>i(G=>({...G,[j.key]:O.target.value}))})]},j.key)}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem",flexWrap:"wrap",marginTop:"0.25rem"},children:[s.jsx("button",{className:"btn btn-primary btn-sm",onClick:ge,disabled:b||!ae,children:b?"Saving…":"Save"}),!ae&&!b&&s.jsx("span",{style:{fontSize:"0.78rem",color:"var(--text-muted)",alignSelf:"center"},children:"No changes yet"}),e.oauth&&s.jsxs("button",{className:"btn btn-secondary btn-sm",onClick:he,children:["Connect ",e.name]}),s.jsx("button",{className:"btn btn-ghost btn-sm",onClick:()=>{V(!1),i({})},children:"Cancel"})]})]}),!U&&re==="running"&&t&&s.jsxs(s.Fragment,{children:[(Object.keys(p).length>0||Object.keys(w).length>0)&&s.jsx("div",{style:{display:"grid",gap:"0.3rem",margin:"0.15rem 0 0.7rem",fontSize:"0.82rem"},children:e.credentials.fields.map(j=>{const P=j.type==="password",O=w[j.key];return!P&&p[j.key]==null||P&&O==null?null:s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",gap:"1rem"},children:[s.jsx("span",{style:{color:"var(--text-muted)"},children:j.label}),s.jsxs("span",{style:{fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace",fontSize:"0.78rem",textAlign:"right",wordBreak:"break-all"},children:[P?O.preview??"set":p[j.key],P&&x&&s.jsxs("span",{style:{color:"var(--text-muted)",fontFamily:"inherit"},children:[" ","· added ",new Date(x).toLocaleDateString(void 0,{month:"short",day:"numeric"})]})]})]},j.key)})}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[s.jsx(Ye,{to:"/mandates?new=1",className:"btn btn-primary btn-sm",style:{textDecoration:"none"},children:"Give a mandate"}),(e.credentials.fields.length>0||e.oauth)&&s.jsx("button",{className:"btn btn-sm btn-secondary",onClick:()=>{i({...p}),V(!0)},title:"Re-enter client ID / secret (e.g. a new OAuth client).",children:"Edit credentials"}),s.jsx("span",{style:{flex:1}}),s.jsx("button",{className:"btn btn-sm btn-ghost",style:{color:"var(--danger)"},onClick:qe,title:"Stops the subprocess and removes the integration from the registry. It will NOT auto-start on next gateway restart. Re-enable with Install.",children:"Disable"})]}),Q&&te!==void 0&&!R&&s.jsx("div",{style:{marginTop:"0.9rem",paddingTop:"0.85rem",borderTop:"1px solid var(--border)"},children:s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"0.6rem"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"baseline",gap:"0.5rem",minWidth:0},children:[s.jsx("span",{style:{fontSize:"0.85rem",fontWeight:600},children:"Reads"}),s.jsx("span",{style:{fontSize:"0.82rem",color:"var(--text-muted)"},children:te===null?"window from your mandate":Us(te).toLowerCase()}),ne&&s.jsx("span",{style:{fontSize:"0.78rem",color:"var(--text-muted)"},children:"saving…"}),z&&s.jsx("span",{style:{fontSize:"0.78rem",color:"var(--danger)"},children:z})]}),s.jsx("button",{className:"btn btn-sm btn-secondary",onClick:()=>F(!0),children:"Edit"})]})}),Q&&te!==void 0&&R&&s.jsxs("div",{style:{marginTop:"0.9rem",paddingTop:"0.85rem",borderTop:"1px solid var(--border)"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"0.6rem",marginBottom:"0.35rem"},children:[s.jsx("span",{style:{fontSize:"0.85rem",fontWeight:600},children:"How far back may your agent read?"}),s.jsx("button",{className:"btn btn-sm btn-ghost",onClick:()=>F(!1),children:"Done"})]}),s.jsx("p",{style:{fontSize:"0.78rem",color:"var(--text-tertiary)",margin:"0 0 0.55rem"},children:"Applies immediately — no Save, no new mandate."}),s.jsxs("div",{style:{display:"flex",gap:"0.4rem",flexWrap:"wrap"},children:[Cx.map(j=>{const P=te===j;return s.jsx("button",{className:`btn btn-sm ${P?"btn-primary":"btn-secondary"}`,"aria-pressed":P,disabled:ne,onClick:()=>ce(j),children:Us(j)},j)}),s.jsx("button",{className:`btn btn-sm ${te===null?"btn-primary":"btn-ghost"}`,"aria-pressed":te===null,disabled:ne,onClick:()=>ce(null),title:"Clear the local setting and use the read window from your signed mandate instead.",children:Us(null)})]}),s.jsx("div",{style:{fontSize:"0.78rem",marginTop:"0.5rem"},children:z?s.jsx("span",{style:{color:"var(--danger)"},children:z}):ne?s.jsx("span",{style:{color:"var(--text-muted)"},children:"Saving…"}):te===null?s.jsx("span",{style:{color:"var(--text-muted)"},children:"Using the window from your mandate. If none is set there, reads are blocked."}):te===0?s.jsx("span",{style:{color:"var(--text-muted)"},children:"Your agent cannot read any mail."}):s.jsxs("span",{style:{color:"var(--text-muted)"},children:["Anything older than ",te," days is blocked, whoever it is from."]})})]}),s.jsx("div",{style:{display:"none"},children:s.jsx(Ye,{to:"/mandates?new=1",className:"btn btn-ghost btn-sm",style:{textDecoration:"none",display:"block",textAlign:"center"},children:"Give your agent a mandate"})})]}),re==="unconfigured"&&(()=>{const j=e.credentials.fields.every(G=>G.optional),P=e.credentials.fields.some(G=>!G.optional),O=e.credentials.fields.some(G=>{var se;return(se=o[G.key])==null?void 0:se.trim()});return s.jsxs(s.Fragment,{children:[d&&s.jsxs("div",{className:"alert",style:{fontSize:"0.8rem",background:"var(--bg-main)",border:"1px solid var(--border)",borderRadius:"0.375rem",padding:"0.5rem 0.75rem",marginBottom:"0.75rem",color:"var(--text-secondary)"},children:[s.jsx("strong",{style:{color:"var(--text-primary)"},children:"Credentials on file."})," ","Existing values are encrypted in the vault and not shown. Enter new values below to replace them, or"," ",s.jsx("button",{onClick:()=>{c(!0),e.oauth&&h(!0)},style:{background:"none",border:"none",padding:0,color:"var(--accent)",cursor:"pointer",textDecoration:"underline"},children:"keep existing"}),"."]}),e.oauth&&!d&&s.jsx("p",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)",marginBottom:"0.5rem"},children:"Step 1 of 2 — enter credentials, then connect your account."}),e.setupHint&&!d&&s.jsx("p",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)",marginBottom:"0.75rem"},children:e.setupHint}),e.credentials.fields.map(G=>s.jsxs("div",{className:"form-group",style:{marginBottom:"0.75rem"},children:[s.jsx("label",{className:"form-label",children:G.label}),G.type==="password"?s.jsxs("div",{className:"cred-field",children:[s.jsx("input",{className:"form-input",type:J[G.key]?"text":"password",name:`${e.id}-${G.key}-credential`,autoComplete:"new-password",placeholder:G.placeholder,value:o[G.key]||"",onChange:se=>i(Nt=>({...Nt,[G.key]:se.target.value}))}),s.jsx("button",{className:"cred-toggle",onClick:()=>D(se=>({...se,[G.key]:!se[G.key]})),children:J[G.key]?"hide":"show"})]}):s.jsx("input",{className:"form-input",type:"text",name:`${e.id}-${G.key}-credential`,autoComplete:"off",placeholder:G.placeholder,value:o[G.key]||"",onChange:se=>i(Nt=>({...Nt,[G.key]:se.target.value}))})]},G.key)),s.jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[O&&s.jsx("button",{className:"btn btn-primary",onClick:A,disabled:b||P&&!e.credentials.fields.filter(G=>!G.optional).every(G=>{var se;return(se=o[G.key])==null?void 0:se.trim()}),children:b?"Saving...":"Save & Encrypt"}),j&&!O&&s.jsx("button",{className:"btn btn-primary",onClick:Pe,disabled:E,children:E?"Starting...":`Activate ${e.name}`})]})]})})(),re==="needs-oauth"&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:{fontSize:"0.8rem",color:"var(--success)",marginBottom:"0.25rem"},children:["✓"," Step 1 done — credentials saved"]}),s.jsxs("div",{style:{fontSize:"0.8rem",color:"var(--text-secondary)",marginBottom:"0.75rem"},children:["Step 2: connect your ",e.name," account to authorize access."]}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem",flexWrap:"wrap"},children:[s.jsxs("button",{className:"btn btn-primary",onClick:he,children:["Connect ",e.name," Account"]}),s.jsx("button",{className:"btn btn-ghost",onClick:()=>c(!1),children:"Change Credentials"})]})]}),re==="ready"&&!t&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:{fontSize:"0.8rem",color:"var(--success)",marginBottom:"0.75rem"},children:["✓"," ",e.oauth?`${e.name} account connected`:"Credentials configured"]}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem",flexWrap:"wrap"},children:[s.jsx("button",{className:"btn btn-primary",onClick:Pe,disabled:E,children:E?"Starting...":`Start ${e.name} Integration`}),!e.oauth&&s.jsx("button",{className:"btn btn-ghost",onClick:()=>c(!1),children:"Update Credentials"}),e.oauth&&s.jsx("button",{className:"btn btn-ghost",onClick:()=>{c(!1),h(!1)},children:"Change Credentials"})]})]}),re==="ready"&&t&&!t.running&&(yt.showStart?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"service-status service-status-error",style:{marginBottom:"0.75rem"},children:[s.jsx("span",{className:"service-status-dot"}),"Not running"]}),t.error&&s.jsx("div",{style:{fontSize:"0.8rem",color:"var(--danger)",marginBottom:"0.75rem"},children:t.error}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[s.jsx("button",{className:"btn btn-primary",onClick:Pe,disabled:E,children:E?"Starting...":"Start"}),s.jsx("button",{className:"btn btn-ghost",style:{color:"var(--danger)"},onClick:qe,children:"Disable"})]})]}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"service-status",style:{marginBottom:"0.5rem",color:"var(--text-muted)"},children:[s.jsx("span",{className:"service-status-dot",style:{background:"var(--text-muted)"}}),"Paused"]}),s.jsx("p",{style:{fontSize:"0.8rem",color:"var(--text-muted)",marginBottom:"0.75rem"},children:"Real systems are off while simulation mode is on."}),s.jsx("div",{style:{display:"flex",gap:"0.5rem"},children:s.jsx("button",{className:"btn btn-ghost",style:{color:"var(--danger)"},onClick:qe,children:"Disable"})})]}))]})}function Ex(e,t){if(!t)return{grouped:!1,testSystems:[],realErrors:[],pausedReal:[],ungrouped:e};const n=e.filter(i=>zi(i.manifest)),r=e.filter(i=>!zi(i.manifest)),a=r.filter(i=>i.state==="error"),o=r.filter(i=>i.state!=="error");return{grouped:!0,testSystems:n,realErrors:a,pausedReal:o,ungrouped:[]}}function Tx({entry:e}){return s.jsxs("div",{className:"int-paused-row",children:[s.jsx("span",{"aria-hidden":"true",children:Nm(e.manifest.icon)}),s.jsx("span",{className:"int-paused-name",children:e.manifest.name}),s.jsxs("span",{className:"int-chip int-chip-paused",children:[s.jsx("span",{className:"int-dot"}),"Paused"]})]})}function Ix(){const{loading:e,mcpServerUp:t,manifestsError:n,entries:r,refresh:a}=Ul(),o=dm(),[i,l]=u.useState(""),c=u.useCallback(f=>{l(f),setTimeout(()=>l(""),5e3)},[]),d=Ex(r,o);return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"page-header",children:[s.jsx("h1",{className:"page-title",children:"Integrations"}),s.jsx("p",{className:"page-subtitle",children:"Connect external services and manage MCP integrations."})]}),i&&s.jsx("div",{className:"alert alert-success",children:i}),e?s.jsx("p",{style:{color:"var(--text-tertiary)"},children:"Loading integrations..."}):t===!1?s.jsxs("div",{className:"status-banner status-banner-error",children:[s.jsx("span",{className:"status-banner-icon",children:"!"}),s.jsx("span",{className:"status-banner-text",children:"MCP server is not reachable. Make sure it is running."})]}):d.grouped?s.jsxs(s.Fragment,{children:[d.testSystems.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"int-group-label",children:"Test systems"}),d.testSystems.map(f=>s.jsx($o,{manifest:f.manifest,integration:f.integration,state:f.state,onStatusChange:a,onSuccess:c},f.id))]}),(d.realErrors.length>0||d.pausedReal.length>0)&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"int-group-label",children:"Real systems"}),d.realErrors.map(f=>s.jsx($o,{manifest:f.manifest,integration:f.integration,state:f.state,onStatusChange:a,onSuccess:c},f.id)),d.pausedReal.length>0&&s.jsxs("details",{className:"int-paused-group",open:!0,children:[s.jsxs("summary",{children:["Paused while simulation mode is on (",d.pausedReal.length,")"]}),s.jsxs("p",{className:"int-paused-group-note",children:["Nothing is lost — mandates, credentials and data stay. They start again when simulation mode is switched off (",s.jsx("code",{children:"suveren-gateway simulation off"}),")."]}),d.pausedReal.map(f=>s.jsx(Tx,{entry:f},f.id))]})]}),r.length===0&&s.jsx(yu,{manifestsError:n})]}):s.jsxs(s.Fragment,{children:[r.map(f=>s.jsx($o,{manifest:f.manifest,integration:f.integration,state:f.state,onStatusChange:a,onSuccess:c},f.id)),r.length===0&&s.jsx(yu,{manifestsError:n})]})]})}function yu({manifestsError:e}){return e?s.jsxs("div",{className:"status-banner status-banner-error",children:[s.jsx("span",{className:"status-banner-icon",children:"!"}),s.jsxs("span",{className:"status-banner-text",children:["Couldn't load integrations — the gateway can't reach its MCP server (or you're signed out). Check the control-plane's"," ",s.jsx("code",{children:"SUVEREN_MCP_INTERNAL_URL"})," (dev MCP is :3431), then refresh."]})]}):s.jsx("p",{style:{color:"var(--text-tertiary)",textAlign:"center",marginTop:"2rem"},children:"No integrations available yet."})}function Rx(){var U,V,J;const{activeTeam:e,activeMembership:t,refreshGroups:n,user:r}=Fe(),[a,o]=u.useState(null),[i,l]=u.useState(!1),[c,d]=u.useState(""),[f,p]=u.useState(""),[m,w]=u.useState(!1),[v,x]=u.useState(""),[k,g]=u.useState("");u.useEffect(()=>{fetch("/health").then(D=>D.json()).then(D=>{typeof D.spUrl=="string"&&g(D.spUrl)}).catch(()=>{})},[]),u.useEffect(()=>{if(!e){o(null);return}T.getGroupById(e.id).then(D=>{const _=D.group??D,B=D.members??[],ne=D.isAdmin??!1,L=B.map(z=>{const W=z.userId||z.id||"",R=z.role||(ne&&W===_.createdBy?"admin":"member");return{id:W,name:z.name||W.slice(0,8)||"Member",email:z.email||"",domains:z.domains||[],role:R,isAdmin:R==="admin"||ne&&W===_.createdBy}});o({id:_.id,name:_.name,members:L})}).catch(()=>o(null))},[e==null?void 0:e.id]);const h=(a==null?void 0:a.members.filter(D=>D.isAdmin))??[],y=(e==null?void 0:e.isAdmin)===!0&&h.length<=1&&h.some(D=>D.id===(r==null?void 0:r.id)),S=(e==null?void 0:e.name)??"",b=v.trim()===S&&!i,N=()=>{x(""),w(!0)},C=()=>{w(!1),x("")},I=async()=>{if(!(!e||!b)){l(!0),d("");try{await T.leaveTeam(e.id),await n(),p("You have left the team."),o(null),C()}catch(D){d(D instanceof Error?D.message:"Failed to leave team")}finally{l(!1)}}},E=e&&k?`${k}/dashboard/groups/${e.id}`:void 0,$=k?`${k}/dashboard/groups`:void 0;return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"page-header",children:s.jsxs("div",{children:[s.jsx("h1",{className:"page-title",children:"Team"}),s.jsx("p",{className:"page-subtitle",children:"Your current team context. Team management lives in your Authority Server dashboard."})]})}),c&&s.jsx("div",{className:"error-message",children:c}),f&&s.jsx("div",{className:"alert alert-success",children:f}),e?s.jsxs("div",{className:"card",style:{marginBottom:"1.5rem"},children:[s.jsxs("div",{className:"card-header",children:[s.jsxs("div",{children:[s.jsx("h3",{className:"card-title",children:e.name}),s.jsxs("p",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)",marginTop:"0.125rem"},children:[((U=a==null?void 0:a.members)==null?void 0:U.length)??0," ",(((V=a==null?void 0:a.members)==null?void 0:V.length)??0)===1?"member":"members",e.isAdmin&&" · You are admin"]})]}),s.jsx("span",{className:"status-badge status-active",children:"Active"})]}),(J=a==null?void 0:a.members)==null?void 0:J.map(D=>s.jsxs("div",{className:"member-row",children:[s.jsx("div",{className:"member-avatar",children:D.name.split(" ").map(_=>_[0]).join("").slice(0,2).toUpperCase()}),s.jsxs("div",{className:"member-info",children:[s.jsx("div",{className:"member-name",children:D.name}),s.jsx("div",{className:"member-email",children:D.email})]}),s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-tertiary)"},children:D.role})]},D.id)),s.jsxs("div",{style:{marginTop:"1.25rem",paddingTop:"1rem",borderTop:"1px solid var(--border)",display:"flex",alignItems:"center",gap:"0.75rem",flexWrap:"wrap"},children:[E&&s.jsx("a",{className:"btn btn-secondary btn-sm",href:E,target:"_blank",rel:"noopener noreferrer",children:"Manage this team in your Authority Server →"}),s.jsx("span",{title:y?"You are the only admin. Transfer admin to another member in your Authority Server dashboard before leaving.":void 0,style:{marginLeft:"auto"},children:s.jsx("button",{className:"btn btn-ghost btn-sm",style:{color:"var(--text-tertiary)"},onClick:N,disabled:i||y,children:"Leave team"})})]})]}):s.jsxs("div",{className:"card",style:{textAlign:"center",padding:"2rem 1.5rem"},children:[s.jsx("h3",{style:{margin:"0 0 0.5rem 0",fontSize:"1rem"},children:"You are working solo."}),s.jsx("p",{style:{fontSize:"0.875rem",color:"var(--text-secondary)",marginBottom:"1rem",maxWidth:480,marginLeft:"auto",marginRight:"auto"},children:"Every mandate you create here is in your personal context. You can join an existing team or create a new one in your Authority Server dashboard."}),$&&s.jsx("a",{className:"btn btn-primary btn-sm",href:$,target:"_blank",rel:"noopener noreferrer",children:"Open Authority Server dashboard →"})]}),m&&e&&s.jsx("div",{role:"dialog","aria-modal":"true","aria-labelledby":"leave-team-title",style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.5)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3,padding:"1rem"},onClick:C,children:s.jsxs("div",{className:"card",onClick:D=>D.stopPropagation(),style:{maxWidth:480,width:"100%",margin:0},children:[s.jsxs("h3",{id:"leave-team-title",className:"card-title",style:{marginBottom:"0.5rem"},children:["Leave ",S,"?"]}),s.jsx("p",{style:{fontSize:"0.875rem",color:"var(--text-secondary)",marginBottom:"0.75rem"},children:"Leaving will:"}),s.jsxs("ul",{style:{fontSize:"0.875rem",color:"var(--text-secondary)",marginBottom:"1rem",paddingLeft:"1.25rem",lineHeight:1.6},children:[s.jsx("li",{children:"Revoke all mandates you created in this team's context"}),s.jsx("li",{children:"Reject any pending action proposals you authored"}),s.jsx("li",{children:"Disable your membership — rejoining requires admin reactivation"})]}),s.jsxs("p",{style:{fontSize:"0.875rem",color:"var(--text-secondary)",marginBottom:"1rem"},children:["Your ",s.jsx("strong",{children:"personal"})," mandates are not affected."]}),s.jsxs("div",{className:"form-group",children:[s.jsxs("label",{htmlFor:"leave-confirm-input",style:{fontSize:"0.825rem",display:"block",marginBottom:"0.375rem"},children:["Type ",s.jsx("code",{children:S})," to confirm:"]}),s.jsx("input",{id:"leave-confirm-input",className:"form-input",type:"text",value:v,onChange:D=>x(D.target.value),placeholder:S,disabled:i,autoFocus:!0})]}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem",justifyContent:"flex-end",marginTop:"1rem"},children:[s.jsx("button",{className:"btn btn-ghost",onClick:C,disabled:i,children:"Cancel"}),s.jsx("button",{className:"btn btn-secondary",style:{color:"var(--danger, #e53e3e)"},onClick:I,disabled:!b,children:i?"Leaving...":"Leave team"})]})]})})]})}function Px({onDismiss:e}){const t=nn(),{group:n,groupId:r,domain:a}=Fe(),[o,i]=u.useState([]),[l,c]=u.useState([]),[d,f]=u.useState([]),[p,m]=u.useState(!0),[w,v]=u.useState({});u.useEffect(()=>{Promise.all([T.listProfiles().catch(()=>[]),T.getIntegrationManifests().then(C=>C.manifests??[]).catch(()=>[]),T.getMcpHealth().then(C=>C.integrations??[]).catch(()=>[])]).then(async([C,I,E])=>{if(i(C),c(I),f(E),r){const $=await Promise.all(C.map(V=>T.getTeamProfileConfig(r,V.id).catch(()=>null))),U={};C.forEach((V,J)=>{const D=$[J];D&&(U[V.id]=D)}),v(U)}}).finally(()=>m(!1))},[r]);const x=new Map;for(const C of l)C.profile&&x.set(C.profile,C);const k=C=>C.replace(/@.*$/,"").split("/").pop()??C,g=C=>C.split("@")[1]??"",h=new Map;for(const C of o){const I=k(C.id);if(!x.has(I))continue;const E=h.get(I);(!E||g(C.id).localeCompare(g(E.id),void 0,{numeric:!0})>0)&&h.set(I,C)}const y=l.map(C=>{const I=C.profile?h.get(C.profile):void 0;return I?{manifest:C,profile:I,integration:d.find(E=>E.id===C.id)}:null}).filter(C=>C!==null),S=C=>C in w,b=C=>{if(!r){console.error("No active group when creating authorization");return}const I=S(C);sessionStorage.setItem("agentAuth",JSON.stringify({profileId:C,groupId:r,groupName:(n==null?void 0:n.name)??null,domain:a,isTeam:I,isPersonal:!!(n!=null&&n.isPersonal)})),sessionStorage.removeItem("agentGate"),e==null||e(),t("/mandates/new/intent")},N=C=>{r&&b(C)};return s.jsxs(s.Fragment,{children:[s.jsx("style",{children:`
67
+ `).replace(/\n+$/,"")}async function Sm(e){const n=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",n);return Array.from(new Uint8Array(r)).map(o=>o.toString(16).padStart(2,"0")).join("")}class vx extends Error{constructor(n,r,a){super(a);Sr(this,"code");Sr(this,"field");this.name="CanonicalValueError",this.code=n,this.field=r}}function xx(e){const t=new TextEncoder().encode(e);let n="";for(const r of t)r===61||r===37||r<32||r>126?n+="%"+r.toString(16).toUpperCase().padStart(2,"0"):n+=String.fromCharCode(r);return n}function jm(e,t,n){const r=[];for(const a of t){const o=e[a];if(o==null)continue;const i=String(o);if(i.includes(`
68
+ `)||i.includes("\r"))throw new vx(n,a,`Value for "${a}" contains a raw newline or carriage return. Refusing: a hash over stripped or normalized input would not represent what was authorized.`);r.push(`${a}=${xx(i)}`)}return r.join(`
69
+ `)}async function aa(e,t){const n=t.boundsSchema??t.frameSchema;if(!n)throw new Error("Profile has no boundsSchema or frameSchema");const r=jm(e,n.keyOrder,"BOUNDS_INVALID_VALUE");return`sha256:${await Sm(r)}`}async function km(e,t){const n=t.contextSchema?jm(e,t.contextSchema.keyOrder,"CONTEXT_INVALID_VALUE"):"";return`sha256:${await Sm(n)}`}async function Aa(e){const t=new TextEncoder().encode(yx(e)),n=await crypto.subtle.digest("SHA-256",t);return`sha256:${Array.from(new Uint8Array(n)).map(o=>o.toString(16).padStart(2,"0")).join("")}`}function bm(e,t){if(!e.authorization_id)throw new Error("Attest result lacks authorization_id — the Authority Server predates per-ceremony identity. Update the Authority Server (lockstep deploy).");return{authorizationId:e.authorization_id,boundsHash:e.bounds_hash??t.boundsHash,contextHash:t.contextHash,context:t.context,...t.contextLabels&&Object.keys(t.contextLabels).length>0?{contextLabels:t.contextLabels}:{},gateContent:t.gateContent,...t.path?{path:t.path}:{}}}function gu(e){return e==null?new Set:new Set(String(e).split(",").map(t=>t.trim().toLowerCase()).filter(Boolean))}function wx(e,t){for(const n of e)if(t.has(n))return!0;return!1}function Sx(e,t,n){for(const r of e){const a=gu(t[r]),o=gu(n[r]);if(!(a.size===0||o.size===0)&&!wx(a,o))return!1}return!0}function jx(e){return e.length>24?`${e.slice(0,10)}…`:e}function Cm(e,t,n){const r=n==null?void 0:n[e];return String(t).split(",").map(o=>o.trim()).filter(Boolean).map(o=>{const i=r==null?void 0:r[o];return i?`${i} (${jx(o)})`:o}).join(", ")}function kx(e,t,n){return e.isPersonal?!1:t&&((n==null?void 0:n.length)??0)===0}function bx(){var le,et,Ut;const e=nn(),{user:t,mode:n,domain:r}=Fe(),[a,o]=u.useState(null),[i,l]=u.useState(null),[c,d]=u.useState(null),[f,p]=u.useState("per-action"),[m,w]=u.useState(1800),[v,x]=u.useState(86400),[k,g]=u.useState(""),[h,y]=u.useState("hours"),[S,b]=u.useState(""),[N,C]=u.useState(!0),[I,E]=u.useState(!1),[$,U]=u.useState(""),[V,J]=u.useState(null),[D,_]=u.useState([]),[B,ne]=u.useState(!1),[L,z]=u.useState([]),[W,R]=u.useState(0);u.useEffect(()=>{var bn;const j=sessionStorage.getItem("agentAuth"),P=sessionStorage.getItem("agentGate");if(!j||!P){e("/mandates?new=1");return}const O=JSON.parse(j),G=JSON.parse(P),se={bounds:G.bounds??{},context:G.context??{},contextLabels:G.contextLabels??void 0,gateContent:G.gateContent};o(O),l(se),G.ttlConfig&&(w(G.ttlConfig.default??1800),x(G.ttlConfig.max??86400)),G.templateMode==="automatic"?p("immediate"):G.templateMode==="review"&&p("per-action");const Nt=((bn=G.ttlConfig)==null?void 0:bn.max)??86400;if(typeof G.templateTtl=="number"&&G.templateTtl>0){const Ie=Math.min(G.templateTtl,Nt);w(Ie),[3600,86400,604800,2592e3,31536e3].includes(Ie)||(Ie%86400===0?(g(String(Ie/86400)),y("days")):(g(String(Math.max(1,Math.round(Ie/3600)))),y("hours")))}T.getProfile(O.profileId).then(Ie=>{var it;if(d(Ie),!S){const vt=Ie.name??((it=O.profileId.split("/").pop())==null?void 0:it.replace(/@.*$/,""))??"",tt=[];if(se.context&&Ie.contextSchema)for(const Z of Ie.contextSchema.keyOrder){const K=se.context[Z];if(K!==void 0&&K!==""){const de=String(K).split(",").map(ye=>ye.trim()).filter(Boolean);tt.push(de.join(", "))}}const H=tt.length>0?`${vt}: ${tt.join(" · ")}`:vt;b(H)}}).catch(()=>{}),O.isPersonal?ne(!0):Promise.all([T.getTeamProfileConfig(O.groupId,O.profileId).catch(()=>null),T.getGroupById(O.groupId).catch(()=>null),T.listUsers().catch(()=>[])]).then(([Ie,it,vt])=>{if(J(Ie),Ie){const tt=new Map;for(const K of vt){const de=K.name&&K.email?`${K.name} (${K.email})`:K.name||K.email||K.id;tt.set(K.id,de)}const H=(it==null?void 0:it.members)??[];for(const K of H){const de=K.userId??K.id;de&&(K.name&&K.email?tt.set(de,`${K.name} (${K.email})`):K.name&&tt.set(de,K.name))}const Z=(Ie.approvers??[]).map(K=>tt.get(K)??K);_(Z)}}).finally(()=>{ne(!0)})},[e]),u.useEffect(()=>{if(!(a!=null&&a.profileId))return;const j=a.profileId,P=sessionStorage.getItem("agentEditReplaces");T.getEnrichedAuthorizations().then(O=>{const G=O.filter(se=>se.profileId===j&&se.authorizationId!==P).map(se=>({authorizationId:se.authorizationId,bounds:se.bounds,context:se.context??{},intent:se.intent}));z(G)}).catch(()=>z([]))},[a==null?void 0:a.profileId]),u.useEffect(()=>{if(!i||!c||L.length===0){R(0);return}let j=!1;return(async()=>{const P=await aa(i.bounds,c),O=await Promise.all(L.map(G=>aa(G.bounds,c).catch(()=>null)));j||R(O.filter(G=>G===P).length)})().catch(()=>{j||R(0)}),()=>{j=!0}},[i,c,L]);const F=async()=>{if(!(!a||!i||!c||!t)){if(!a.groupId){U("No active group; cannot create mandate.");return}E(!0),U("");try{const j=r||a.domain||"owner",P=await aa(i.bounds,c),O=await km(i.context,c),[G,se]=await Promise.all([Aa(i.gateContent.intent),Aa(JSON.stringify({profile:a.profileId,domain:j,group:a.groupId}))]);let Nt,bn,Ie,it;if(a.isTeam){const Z=await T.getApproversPubkeys(a.groupId,a.profileId);if(Z.length>0){const K=await T.encryptIntent(i.gateContent.intent,Z);Nt=K.intentCiphertext,bn=K.encryptedKeys,Ie=K.approversFrozen,it=K.intentDisclosureHash}}const vt=`authz_${crypto.randomUUID()}`,tt=sessionStorage.getItem("agentEditReplaces")||void 0,H=await T.attest({authorization_id:vt,replaces:tt,profile_id:a.profileId,bounds:i.bounds,bounds_hash:P,context_hash:O,domain:j,did:t.did,gate_content_hashes:{intent:G},execution_context_hash:se,group_id:a.groupId,ttl:m,commitment_mode:f==="per-action"?"review":"automatic",title:S.trim(),intent_ciphertext:Nt,encrypted_keys:bn,approvers_frozen:Ie,intent_disclosure_hash:it,disclose_identity:N});try{await T.pushGateContent(bm(H,{boundsHash:P,contextHash:O,context:i.context,contextLabels:i.contextLabels,gateContent:i.gateContent}))}catch(Z){try{await T.revokeAttestation(vt,"Auto-revoked: gate content push failed")}catch{}throw new Error(`Mandate signed but gate content delivery failed. The mandate was revoked. Please try again. (${Z instanceof Error?Z.message:"Unknown error"})`)}if(tt)try{await T.revokeAttestation(tt,`Replaced by ${vt} (edit)`),T.resyncGates().catch(()=>{})}catch{}sessionStorage.removeItem("agentAuth"),sessionStorage.removeItem("agentGate"),sessionStorage.removeItem("agentEditReplaces"),e(`/mandates?highlight=${encodeURIComponent(vt)}`)}catch(j){U(j instanceof Error?j.message:"Signing the mandate failed")}finally{E(!1)}}};if(!a||!i)return s.jsx("p",{style:{color:"var(--text-tertiary)"},children:"Loading..."});const Q=Object.entries(i.bounds).filter(([j])=>j!=="profile"&&j!=="path"),q=Object.entries(i.context),ce=((V==null?void 0:V.caps)!=null?Object.keys(V.caps):[]).length!==0,me=D.length>0?D.join(", "):((V==null?void 0:V.approvers)??[]).join(", "),ee=ce?`Within-cap actions run per the mode you choose above. Over-cap actions will require approval from you and ${me}, regardless of your mode.`:"No caps set — they won't gate any action, but your intent is encrypted and shared with them as an accountability record.",oe=ce?`Over-cap actions will be reviewed by you and ${me}. Within-cap actions run per the mode you chose above.`:`Approvers ${me} can read your intent but won't gate any action — no caps configured on this profile.`,re=!!((le=V==null?void 0:V.approvers)!=null&&le.length),A=kx(a,B,V==null?void 0:V.approvers),X=m>v,ae={flex:1,padding:"0.75rem",border:f==="immediate"?"2px solid var(--accent)":"1px solid var(--border)",borderRadius:"var(--radius)",background:f==="immediate"?"var(--accent-subtle)":"var(--bg-elevated)",cursor:"pointer",textAlign:"left",fontFamily:"inherit"},ge={flex:1,padding:"0.75rem",border:f==="per-action"?"2px solid var(--accent)":"1px solid var(--border)",borderRadius:"var(--radius)",background:f==="per-action"?"var(--accent-subtle)":"var(--bg-elevated)",cursor:"pointer",textAlign:"left",fontFamily:"inherit"},he=((et=c==null?void 0:c.contextSchema)==null?void 0:et.keyOrder)??[],Pe=L.filter(j=>Sx(he,i.context,j.context)),qe=Pe.length>0,_e=$e(a.profileId),yt=j=>{const P=Object.values(j).map(O=>String(O).trim()).filter(Boolean);return P.length>0?P.join(", "):"all (unscoped)"},Ze=Pe.map(j=>yt(j.context)).join("; "),Ge=`This grant's scope overlaps an existing grant on ${_e} (scoped to: ${Ze}). The agent may act under either. Per-action limits take the more permissive value, and daily limits add together — two grants of 10/day allow 20/day. Approval is not weakened: if either grant requires review, review still applies. Confirm this is intended before authorizing.`;return s.jsxs(s.Fragment,{children:[s.jsx(xm,{currentStep:4,onStepClick:j=>{j<=3&&e(`/mandates/new/intent?step=${j}`)}}),s.jsxs("div",{className:"card",children:[s.jsx("h3",{className:"card-title",style:{marginBottom:"0.25rem"},children:"Review & Commit"}),s.jsx("p",{style:{fontSize:"0.85rem",color:"var(--text-secondary)",marginBottom:"1.5rem"},children:"Review your mandate details before signing."}),$&&s.jsx("div",{className:"error-message",children:$}),s.jsxs("div",{className:"field-editable",children:[s.jsxs("div",{className:"field-label",children:[s.jsx("span",{className:"pen",children:"✎"})," Title"]}),s.jsx("input",{type:"text",className:"form-input",placeholder:`e.g. ${$e(a.profileId)}: daily operations`,value:S,onChange:j=>b(j.target.value),maxLength:80,style:{fontSize:"0.9rem"}}),s.jsx("div",{style:{fontSize:"0.7rem",color:"var(--text-tertiary)",marginTop:"0.25rem"},children:"A short name to identify this mandate on your dashboard."})]}),s.jsxs("div",{className:"field-editable",children:[s.jsxs("div",{className:"field-label",children:[s.jsx("span",{className:"pen",children:"✎"})," Commitment"]}),s.jsxs("div",{style:{display:"flex",gap:"0.75rem"},children:[s.jsxs("button",{onClick:()=>p("per-action"),style:ge,children:[s.jsx("div",{style:{fontWeight:600,fontSize:"0.85rem",marginBottom:"0.25rem",color:"var(--text-primary)"},children:"Review Each Action"}),s.jsx("div",{style:{fontSize:"0.75rem",color:"var(--text-secondary)"},children:"You review and approve each action before it executes."})]}),s.jsxs("button",{onClick:()=>p("immediate"),style:ae,children:[s.jsx("div",{style:{fontWeight:600,fontSize:"0.85rem",marginBottom:"0.25rem",color:"var(--text-primary)"},children:"Automatic"}),s.jsx("div",{style:{fontSize:"0.75rem",color:"var(--text-secondary)"},children:"Agent acts freely within your limits."})]})]})]}),s.jsxs("div",{className:"field-editable",children:[s.jsxs("div",{className:"field-label",children:[s.jsx("span",{className:"pen",children:"✎"})," Duration"]}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem",flexWrap:"wrap",alignItems:"center"},children:[[{label:"1 hour",seconds:3600},{label:"24 hours",seconds:86400},{label:"7 days",seconds:604800},{label:"30 days",seconds:2592e3},{label:"1 year",seconds:31536e3}].filter(j=>j.seconds<=v).map(j=>s.jsx("button",{onClick:()=>{w(j.seconds),g("")},style:{padding:"0.5rem 0.85rem",border:m===j.seconds?"2px solid var(--accent)":"1px solid var(--border)",borderRadius:"0.375rem",background:m===j.seconds?"var(--accent-subtle)":"var(--bg-elevated)",cursor:"pointer",fontSize:"0.85rem",fontFamily:"inherit",color:"var(--text-primary)"},children:j.label},j.seconds)),s.jsxs("div",{style:{display:"flex",gap:"0.375rem",alignItems:"center"},children:[s.jsx("input",{type:"number",className:"form-input",style:{width:"5rem",padding:"0.45rem 0.6rem",fontSize:"0.85rem"},placeholder:"Custom",value:k,onChange:j=>{g(j.target.value);const P=parseInt(j.target.value,10);if(P>0){const O=h==="days"?P*86400:P*3600;w(Math.min(O,v))}}}),s.jsxs("select",{className:"form-input",style:{padding:"0.45rem 0.5rem",fontSize:"0.85rem"},value:h,onChange:j=>{y(j.target.value);const P=parseInt(k,10);if(P>0){const O=j.target.value==="days"?P*86400:P*3600;w(Math.min(O,v))}},children:[s.jsx("option",{value:"hours",children:"hours"}),s.jsx("option",{value:"days",children:"days"})]})]}),X&&s.jsxs("span",{style:{fontSize:"0.75rem",color:"var(--danger)"},children:["Maximum: ",v>=86400?`${Math.floor(v/86400)} days`:`${Math.floor(v/3600)} hours`]})]})]}),s.jsx("div",{className:"field-editable",children:s.jsxs("label",{style:{display:"flex",alignItems:"flex-start",gap:"0.5rem",cursor:"pointer"},children:[s.jsx("input",{type:"checkbox",checked:N,onChange:j=>C(j.target.checked),style:{marginTop:"0.15rem"}}),s.jsxs("span",{style:{fontSize:"0.8rem"},children:["Show my verified name on actions under this mandate",s.jsx("div",{style:{fontSize:"0.7rem",color:"var(--text-tertiary)",marginTop:"0.15rem"},children:'Adds "verified by Suveren" with your name to outgoing content. Takes effect only if your identity is verified; otherwise actions stay pseudonymous.'})]})]})}),s.jsx("div",{className:"info-section-label",children:"What you are signing — set in previous steps"}),s.jsxs("div",{className:"info-block",children:[s.jsxs("div",{className:"info-head",children:[s.jsx("span",{className:"info-title",children:"Intent"}),s.jsx("button",{className:"info-edit",onClick:()=>e("/mandates/new/intent?step=3"),children:"edit in step 3"})]}),s.jsx("div",{style:{whiteSpace:"pre-wrap"},children:i.gateContent.intent})]}),(!!Q.length||!!q.length)&&s.jsxs("div",{className:"info-block",children:[s.jsxs("div",{className:"info-head",children:[s.jsx("span",{className:"info-title",children:"Scope & Limits"}),s.jsx("button",{className:"info-edit",onClick:()=>e("/mandates/new/intent?step=2"),children:"edit in step 2"})]}),s.jsxs("dl",{className:"info-kv",children:[q.map(([j,P])=>s.jsxs("span",{style:{display:"contents"},children:[s.jsx("dt",{children:j}),s.jsx("dd",{children:Cm(j,P,i.contextLabels)})]},j)),Q.map(([j,P])=>s.jsxs("span",{style:{display:"contents"},children:[s.jsx("dt",{children:j}),s.jsx("dd",{children:String(P)})]},j))]})]}),s.jsxs("div",{className:"info-block",children:[s.jsx("div",{className:"info-head",children:s.jsx("span",{className:"info-title",children:"Authority"})}),s.jsxs("dl",{className:"info-kv",children:[s.jsx("dt",{children:"Profile"}),s.jsxs("dd",{children:[$e(a.profileId),s.jsx("div",{style:{fontSize:"0.75rem",color:"var(--text-tertiary)",marginTop:"0.125rem"},children:a.profileId})]}),!a.isPersonal&&a.groupName&&s.jsxs(s.Fragment,{children:[s.jsx("dt",{children:"Team"}),s.jsx("dd",{children:a.groupName})]}),!a.isPersonal&&s.jsxs(s.Fragment,{children:[s.jsx("dt",{children:"Approvers"}),s.jsx("dd",{children:B?(((Ut=V==null?void 0:V.approvers)==null?void 0:Ut.length)??0)===0?s.jsxs(s.Fragment,{children:[s.jsxs("span",{style:{color:"var(--danger)",fontWeight:600},children:["Not enabled for ",a.groupName??"this team"]}),s.jsx("div",{style:{fontSize:"0.75rem",color:"var(--text-tertiary)",marginTop:"0.125rem"},children:"A team admin must name at least one approver for this profile on the Authority Server (team → Profiles) before anyone can grant under it. Personal use is unaffected."})]}):s.jsxs(s.Fragment,{children:[me,s.jsx("div",{style:{fontSize:"0.75rem",color:"var(--text-tertiary)",marginTop:"0.125rem"},children:ee})]}):s.jsx("span",{style:{color:"var(--text-tertiary)"},children:"Loading…"})})]})]})]}),W>0?s.jsxs("div",{style:{display:"flex",gap:"0.625rem",padding:"0.75rem 0.875rem",marginBottom:"1.25rem",border:"1px solid var(--warning)",borderLeft:"3px solid var(--warning)",borderRadius:"0.5rem",background:"var(--bg-elevated)",fontSize:"0.82rem",color:"var(--text-primary)"},children:[s.jsx("span",{"aria-hidden":"true",style:{color:"var(--warning)",fontWeight:700},children:"⚠"}),s.jsxs("div",{children:[s.jsx("div",{style:{fontWeight:600,color:"var(--warning)",marginBottom:"0.2rem"},children:"Identical limits to an existing grant"}),s.jsxs("div",{children:[W===1?`An active grant on ${_e} already has exactly these limits.`:`${W} active grants on ${_e} already have exactly these limits.`," ","If you meant to give the existing grant more time, use ",s.jsx("strong",{children:"Extend"})," on the Mandates page instead — authorizing here creates a separate, independent grant with its own intent and usage counters."]})]})]}):null,qe?s.jsxs("div",{style:{display:"flex",gap:"0.625rem",padding:"0.75rem 0.875rem",marginBottom:"1.25rem",border:"1px solid var(--warning)",borderLeft:"3px solid var(--warning)",borderRadius:"0.5rem",background:"var(--bg-elevated)",fontSize:"0.82rem",color:"var(--text-primary)"},children:[s.jsx("span",{"aria-hidden":"true",style:{color:"var(--warning)",fontWeight:700},children:"⚠"}),s.jsxs("div",{children:[s.jsx("div",{style:{fontWeight:600,color:"var(--warning)",marginBottom:"0.2rem"},children:"Overlapping scope"}),s.jsx("div",{children:Ge})]})]}):null,s.jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[s.jsx("button",{className:"btn btn-ghost",onClick:()=>e("/mandates/new/intent"),children:"Back"}),s.jsx("button",{className:"btn btn-primary btn-lg",style:{flex:1},onClick:F,disabled:I||!S.trim()||A,children:I?"Signing...":f==="immediate"?"Sign mandate":"Sign mandate (asks first)"})]}),s.jsx("div",{style:{marginTop:"1rem",fontSize:"0.75rem",color:"var(--text-tertiary)",textAlign:"center",display:re?"block":"none"},children:oe})]})]})}const Cx={card:"💳",mail:"✉️"};function Nm(e){return Cx[e]??"🔧"}function Nx(e){const t=e==null?void 0:e.overrides;return!t||typeof t!="object"?!1:Object.values(t).some(n=>{var r;return typeof((r=n==null?void 0:n.read)==null?void 0:r.ageField)=="string"})}const Ex=[0,7,30,90,365,3650];function Us(e){return e===null?"From your mandate":e===0?"Read nothing":e===1?"1 day back":e===365?"1 year back":e%365===0?`${e/365} years back`:`${e} days back`}function Tx(e){return(e==null?void 0:e.paused)==="simulation"?{chip:{c:"int-chip-paused",t:"Paused"},showStart:!1}:e&&!e.running&&e.error?{chip:{c:"int-chip-bad",t:"Crashed"},showStart:!0}:{chip:{c:"int-chip-idle",t:"Stopped"},showStart:!0}}function $o({manifest:e,integration:t,state:n,onStatusChange:r,onSuccess:a}){var Ut;const[o,i]=u.useState({}),[l,c]=u.useState(!1),[d,f]=u.useState(!1),[p,m]=u.useState({}),[w,v]=u.useState({}),[x,k]=u.useState(void 0),[g,h]=u.useState(!1),[y,S]=u.useState(null),[b,N]=u.useState(!1),[C,I]=u.useState(!1),[E,$]=u.useState(!1),[U,V]=u.useState(!1),[J,D]=u.useState({}),[_,B]=u.useState(null),[ne,L]=u.useState(!1),[z,W]=u.useState(null),[R,F]=u.useState(!1);u.useEffect(()=>{let j=!1;return T.getCredential(e.id).then(P=>{var O;if(!(j||!P.configured)){if(c(!0),f(!0),P.fields){const G={};for(const se of e.credentials.fields)P.fields[se.key]!=null&&(G[se.key]=P.fields[se.key]);m(G)}if(v(P.secrets??{}),k(P.updatedAt),e.oauth){const G=((O=P.fieldNames)==null?void 0:O.includes(e.oauth.tokenStorage))??!1;h(G),G&&T.getOAuthHealth(e.id).then(se=>{j||S(se)})}}}).catch(()=>{}),()=>{j=!0}},[e.id,e.oauth]);const Q=Nx(e.toolGating),q=t?t.readAgeDays??null:void 0,te=ne&&_?_.value:q,ce=async j=>{B({value:j}),L(!0),W(null);try{await T.setReadPolicy(e.id,j),a(j===null?`${e.name} read window now follows your mandate`:`${e.name} read window set to ${Us(j).toLowerCase()}`),r()}catch(P){W(P instanceof Error?P.message:"Could not save")}finally{L(!1),B(null)}},me=!!e.oauth||e.credentials.fields.some(j=>!j.optional),ee=e.oauth?g:l,oe=!me||ee,re=n==="starting"?"starting":oe?t!=null&&t.running?"running":!l&&e.credentials.fields.length>0?"unconfigured":"ready":e.oauth&&l&&!g?"needs-oauth":"unconfigured",A=async()=>{if(e.credentials.fields.some(P=>{var O;return(O=o[P.key])==null?void 0:O.trim()})){N(!0);try{await T.setCredential(e.id,o),c(!0),i({}),e.oauth?a(`${e.name} credentials saved!`):(a(`${e.name} credentials saved — starting integration...`),await Pe())}catch{a(`Failed to save ${e.name} credentials`)}finally{N(!1)}}},X=()=>{const j={};for(const P of e.credentials.fields){const O=o[P.key];P.type==="password"?O!=null&&O.trim()&&(j[P.key]=O):O!=null&&O!==(p[P.key]??"")&&(j[P.key]=O)}return j},ae=Object.keys(X()).length>0,ge=async()=>{const j=X();if(Object.keys(j).length!==0){N(!0);try{await T.setCredential(e.id,j),i({}),c(!0),e.oauth?a(`${e.name} credentials saved — now click Connect.`):(V(!1),a(`${e.name} credentials updated — restarting...`),await Pe())}catch{a(`Failed to update ${e.name} credentials`)}finally{N(!1)}}},he=()=>{window.open(`/auth/oauth/${e.id}/start`,"_blank","width=600,height=700");const j=setInterval(async()=>{var P;try{const O=await T.getCredential(e.id);O.configured&&e.oauth&&((P=O.fieldNames)!=null&&P.includes(e.oauth.tokenStorage))&&(h(!0),V(!1),S(null),clearInterval(j),a(`${e.name} connected — starting integration...`),T.getOAuthHealth(e.id).then(S).catch(()=>{}),await Pe())}catch{}},2e3);setTimeout(()=>clearInterval(j),12e4)},Pe=async()=>{$(!0);try{const j=await T.activateIntegration(e.id);j.warning?a(j.warning):a(`${e.name} integration started with ${j.tools.length} tools`),r()}catch(j){a(`Failed to start ${e.name}: ${j instanceof Error?j.message:"Unknown error"}`)}finally{$(!1)}},qe=async()=>{try{await T.removeMcpIntegration(e.id),a(`${e.name} integration removed`),r()}catch{a(`Failed to remove ${e.name}`)}},_e=Nm(e.icon),yt=Tx(t),Ze=re==="running"?{c:"int-chip-ok",t:"Running"}:re==="starting"?{c:"int-chip-idle",t:"Starting"}:yt.chip,Ge=e.oauth&&g&&(y==null?void 0:y.status)==="failed",le=me?Ge?{c:"int-chip-bad",t:"Auth failed"}:ee?{c:"int-chip-ok",t:"Auth OK"}:{c:"int-chip-idle",t:"Not set up"}:{c:"int-chip-idle",t:"No auth"},et=j=>j.replace(/https?:\/\/[^\s)]+\/auth\/oauth\/[a-z-]+\/callback/gi,`${window.location.origin}/auth/oauth/${e.id}/callback`);return s.jsxs("div",{className:"card",style:{marginBottom:"1rem"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"0.75rem"},children:[s.jsx("span",{style:{fontSize:"1.4rem",lineHeight:1.2},children:_e}),s.jsx("h3",{className:"card-title",style:{margin:0,flex:1,alignSelf:"center"},children:e.name}),s.jsxs("div",{style:{display:"flex",gap:"0.4rem",flexWrap:"wrap",justifyContent:"flex-end"},children:[re!=="unconfigured"&&re!=="needs-oauth"&&s.jsxs("span",{className:`int-chip ${Ze.c}`,children:[s.jsx("span",{className:"int-dot"}),Ze.t]}),s.jsxs("span",{className:`int-chip ${le.c}`,children:[s.jsx("span",{className:"int-dot"}),le.t]}),Bv(e,p)&&s.jsxs("span",{className:"int-chip int-chip-sim",title:"This connector answers from a simulated system with test data. Nothing reaches your real systems.",children:[s.jsx("span",{className:"int-dot"}),"Simulation"]})]})]}),e.oauth&&g&&s.jsx("div",{className:"int-account",style:{marginTop:"0.7rem"},children:y!=null&&y.account?s.jsxs(s.Fragment,{children:["Connected as ",s.jsx("b",{children:y.account})]}):s.jsx("span",{className:"int-none",children:"Account not recorded — reconnect to capture which account is used"})}),Ge&&!U&&s.jsxs("div",{style:{marginTop:"0.7rem",border:"1px solid var(--danger)",borderRadius:"10px",padding:"0.8rem 0.95rem",background:"color-mix(in srgb, var(--danger) 5%, var(--bg-elevated))"},children:[s.jsxs("div",{style:{fontSize:"0.86rem",fontWeight:700},children:[e.name," stopped accepting the stored credentials"]}),s.jsxs("p",{style:{fontSize:"0.8rem",color:"var(--text-muted)",margin:"0.3rem 0 0",lineHeight:1.55},children:[(y==null?void 0:y.error)==="invalid_grant"?s.jsxs(s.Fragment,{children:["The refresh token was revoked (",s.jsx("code",{children:"invalid_grant"}),") — this usually follows a password change or a security checkup on the provider's side."]}):y!=null&&y.error?s.jsxs(s.Fragment,{children:["The provider reported ",s.jsx("code",{children:y.error}),"."]}):s.jsx(s.Fragment,{children:"The provider rejected the stored authentication."})," ","Your agent's ",e.name," actions are ",s.jsx("b",{children:"blocked"}),", not failing silently."]}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem",marginTop:"0.6rem"},children:[s.jsxs("button",{className:"btn btn-primary btn-sm",onClick:he,children:["Reconnect ",e.name]}),s.jsx("button",{className:"btn btn-ghost btn-sm",onClick:()=>{i({...p}),V(!0)},children:"Edit credentials"})]})]}),s.jsxs("details",{className:"int-details",style:{marginTop:"0.85rem",marginBottom:"1.25rem"},children:[s.jsx("summary",{children:"Details"}),s.jsxs("div",{className:"int-meta",children:[s.jsx("span",{className:"int-k",children:"What"}),s.jsx("span",{children:e.description}),e.profile&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"int-k",children:"Profile"}),s.jsx("span",{children:e.profile})]}),e.oauth&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"int-k",children:"Scopes"}),s.jsx("span",{children:((Ut=e.oauth.scopes)==null?void 0:Ut.join(", "))||"—"})]}),t&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"int-k",children:"Tools"}),s.jsxs("span",{children:[t.toolCount," gated"]})]})]})]}),e.setupGuide&&e.setupGuide.length>0&&(re!=="running"||Ge)&&s.jsxs("div",{style:{marginBottom:"0.75rem"},children:[s.jsxs("button",{onClick:()=>I(!C),style:{background:"none",border:"none",padding:0,fontSize:"0.8rem",color:"var(--accent)",cursor:"pointer",display:"flex",alignItems:"center",gap:"0.375rem"},children:[s.jsx("span",{style:{transition:"transform 0.2s",transform:C?"rotate(90deg)":"rotate(0deg)",display:"inline-block"},children:"▶"}),"How to set up ",e.name]}),C&&s.jsx("div",{style:{marginTop:"0.75rem",paddingLeft:"0.25rem"},children:e.setupGuide.map((j,P)=>s.jsxs("div",{style:{display:"flex",gap:"0.75rem",marginBottom:"0.75rem"},children:[s.jsx("div",{style:{width:"1.5rem",height:"1.5rem",borderRadius:"50%",background:"var(--border)",color:"var(--text-secondary)",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"0.7rem",fontWeight:700,flexShrink:0,marginTop:"0.1rem"},children:P+1}),s.jsxs("div",{children:[s.jsx("div",{style:{fontSize:"0.85rem",fontWeight:600,color:"var(--text-primary)",marginBottom:"0.125rem"},children:j.title}),s.jsxs("div",{style:{fontSize:"0.8rem",color:"var(--text-secondary)",lineHeight:1.5},children:[et(j.description),j.link&&s.jsxs(s.Fragment,{children:[" ",s.jsxs("a",{href:j.link,target:"_blank",rel:"noopener noreferrer",style:{fontSize:"0.8rem"},children:["Open ","↗"]})]})]})]})]},P))})]}),re==="starting"&&s.jsxs("div",{className:"service-status",style:{color:"var(--warning)"},children:[s.jsx("span",{className:"service-status-dot",style:{background:"var(--warning)"}}),"Starting…"]}),U&&s.jsxs("div",{style:{marginTop:"0.7rem",paddingTop:"0.85rem",borderTop:"1px solid var(--border)"},children:[s.jsx("div",{style:{fontSize:"0.85rem",fontWeight:600,marginBottom:"0.5rem"},children:"Change credentials"}),d&&s.jsxs("p",{style:{fontSize:"0.8rem",color:"var(--text-muted)",marginBottom:"0.6rem"},children:["Leaving a secret blank keeps the stored one — editing other fields can never silently wipe it.",e.oauth?" Save, then Connect to re-link the account.":""]}),e.credentials.fields.map(j=>{var P;return s.jsxs("div",{className:"form-group",style:{marginBottom:"0.6rem"},children:[s.jsx("label",{className:"form-label",children:j.label}),j.type==="password"?s.jsxs("div",{className:"cred-field",children:[s.jsx("input",{className:"form-input",type:J[j.key]?"text":"password",name:`${e.id}-${j.key}-credential`,autoComplete:"new-password",placeholder:(P=w[j.key])!=null&&P.preview?`Unchanged — ends in ${w[j.key].preview}`:d?"Unchanged — paste a new value to replace":j.placeholder,value:o[j.key]||"",onChange:O=>i(G=>({...G,[j.key]:O.target.value}))}),s.jsx("button",{className:"cred-toggle",onClick:()=>D(O=>({...O,[j.key]:!O[j.key]})),children:J[j.key]?"hide":"show"})]}):s.jsx("input",{className:"form-input",type:"text",name:`${e.id}-${j.key}-credential`,autoComplete:"off",placeholder:j.placeholder,value:o[j.key]||"",onChange:O=>i(G=>({...G,[j.key]:O.target.value}))})]},j.key)}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem",flexWrap:"wrap",marginTop:"0.25rem"},children:[s.jsx("button",{className:"btn btn-primary btn-sm",onClick:ge,disabled:b||!ae,children:b?"Saving…":"Save"}),!ae&&!b&&s.jsx("span",{style:{fontSize:"0.78rem",color:"var(--text-muted)",alignSelf:"center"},children:"No changes yet"}),e.oauth&&s.jsxs("button",{className:"btn btn-secondary btn-sm",onClick:he,children:["Connect ",e.name]}),s.jsx("button",{className:"btn btn-ghost btn-sm",onClick:()=>{V(!1),i({})},children:"Cancel"})]})]}),!U&&re==="running"&&t&&s.jsxs(s.Fragment,{children:[(Object.keys(p).length>0||Object.keys(w).length>0)&&s.jsx("div",{style:{display:"grid",gap:"0.3rem",margin:"0.15rem 0 0.7rem",fontSize:"0.82rem"},children:e.credentials.fields.map(j=>{const P=j.type==="password",O=w[j.key];return!P&&p[j.key]==null||P&&O==null?null:s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",gap:"1rem"},children:[s.jsx("span",{style:{color:"var(--text-muted)"},children:j.label}),s.jsxs("span",{style:{fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace",fontSize:"0.78rem",textAlign:"right",wordBreak:"break-all"},children:[P?O.preview??"set":p[j.key],P&&x&&s.jsxs("span",{style:{color:"var(--text-muted)",fontFamily:"inherit"},children:[" ","· added ",new Date(x).toLocaleDateString(void 0,{month:"short",day:"numeric"})]})]})]},j.key)})}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[s.jsx(Ye,{to:"/mandates?new=1",className:"btn btn-primary btn-sm",style:{textDecoration:"none"},children:"Give a mandate"}),(e.credentials.fields.length>0||e.oauth)&&s.jsx("button",{className:"btn btn-sm btn-secondary",onClick:()=>{i({...p}),V(!0)},title:"Re-enter client ID / secret (e.g. a new OAuth client).",children:"Edit credentials"}),s.jsx("span",{style:{flex:1}}),s.jsx("button",{className:"btn btn-sm btn-ghost",style:{color:"var(--danger)"},onClick:qe,title:"Stops the subprocess and removes the integration from the registry. It will NOT auto-start on next gateway restart. Re-enable with Install.",children:"Disable"})]}),Q&&te!==void 0&&!R&&s.jsx("div",{style:{marginTop:"0.9rem",paddingTop:"0.85rem",borderTop:"1px solid var(--border)"},children:s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"0.6rem"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"baseline",gap:"0.5rem",minWidth:0},children:[s.jsx("span",{style:{fontSize:"0.85rem",fontWeight:600},children:"Reads"}),s.jsx("span",{style:{fontSize:"0.82rem",color:"var(--text-muted)"},children:te===null?"window from your mandate":Us(te).toLowerCase()}),ne&&s.jsx("span",{style:{fontSize:"0.78rem",color:"var(--text-muted)"},children:"saving…"}),z&&s.jsx("span",{style:{fontSize:"0.78rem",color:"var(--danger)"},children:z})]}),s.jsx("button",{className:"btn btn-sm btn-secondary",onClick:()=>F(!0),children:"Edit"})]})}),Q&&te!==void 0&&R&&s.jsxs("div",{style:{marginTop:"0.9rem",paddingTop:"0.85rem",borderTop:"1px solid var(--border)"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"0.6rem",marginBottom:"0.35rem"},children:[s.jsx("span",{style:{fontSize:"0.85rem",fontWeight:600},children:"How far back may your agent read?"}),s.jsx("button",{className:"btn btn-sm btn-ghost",onClick:()=>F(!1),children:"Done"})]}),s.jsx("p",{style:{fontSize:"0.78rem",color:"var(--text-tertiary)",margin:"0 0 0.55rem"},children:"Applies immediately — no Save, no new mandate."}),s.jsxs("div",{style:{display:"flex",gap:"0.4rem",flexWrap:"wrap"},children:[Ex.map(j=>{const P=te===j;return s.jsx("button",{className:`btn btn-sm ${P?"btn-primary":"btn-secondary"}`,"aria-pressed":P,disabled:ne,onClick:()=>ce(j),children:Us(j)},j)}),s.jsx("button",{className:`btn btn-sm ${te===null?"btn-primary":"btn-ghost"}`,"aria-pressed":te===null,disabled:ne,onClick:()=>ce(null),title:"Clear the local setting and use the read window from your signed mandate instead.",children:Us(null)})]}),s.jsx("div",{style:{fontSize:"0.78rem",marginTop:"0.5rem"},children:z?s.jsx("span",{style:{color:"var(--danger)"},children:z}):ne?s.jsx("span",{style:{color:"var(--text-muted)"},children:"Saving…"}):te===null?s.jsx("span",{style:{color:"var(--text-muted)"},children:"Using the window from your mandate. If none is set there, reads are blocked."}):te===0?s.jsx("span",{style:{color:"var(--text-muted)"},children:"Your agent cannot read any mail."}):s.jsxs("span",{style:{color:"var(--text-muted)"},children:["Anything older than ",te," days is blocked, whoever it is from."]})})]}),s.jsx("div",{style:{display:"none"},children:s.jsx(Ye,{to:"/mandates?new=1",className:"btn btn-ghost btn-sm",style:{textDecoration:"none",display:"block",textAlign:"center"},children:"Give your agent a mandate"})})]}),re==="unconfigured"&&(()=>{const j=e.credentials.fields.every(G=>G.optional),P=e.credentials.fields.some(G=>!G.optional),O=e.credentials.fields.some(G=>{var se;return(se=o[G.key])==null?void 0:se.trim()});return s.jsxs(s.Fragment,{children:[d&&s.jsxs("div",{className:"alert",style:{fontSize:"0.8rem",background:"var(--bg-main)",border:"1px solid var(--border)",borderRadius:"0.375rem",padding:"0.5rem 0.75rem",marginBottom:"0.75rem",color:"var(--text-secondary)"},children:[s.jsx("strong",{style:{color:"var(--text-primary)"},children:"Credentials on file."})," ","Existing values are encrypted in the vault and not shown. Enter new values below to replace them, or"," ",s.jsx("button",{onClick:()=>{c(!0),e.oauth&&h(!0)},style:{background:"none",border:"none",padding:0,color:"var(--accent)",cursor:"pointer",textDecoration:"underline"},children:"keep existing"}),"."]}),e.oauth&&!d&&s.jsx("p",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)",marginBottom:"0.5rem"},children:"Step 1 of 2 — enter credentials, then connect your account."}),e.setupHint&&!d&&s.jsx("p",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)",marginBottom:"0.75rem"},children:e.setupHint}),e.credentials.fields.map(G=>s.jsxs("div",{className:"form-group",style:{marginBottom:"0.75rem"},children:[s.jsx("label",{className:"form-label",children:G.label}),G.type==="password"?s.jsxs("div",{className:"cred-field",children:[s.jsx("input",{className:"form-input",type:J[G.key]?"text":"password",name:`${e.id}-${G.key}-credential`,autoComplete:"new-password",placeholder:G.placeholder,value:o[G.key]||"",onChange:se=>i(Nt=>({...Nt,[G.key]:se.target.value}))}),s.jsx("button",{className:"cred-toggle",onClick:()=>D(se=>({...se,[G.key]:!se[G.key]})),children:J[G.key]?"hide":"show"})]}):s.jsx("input",{className:"form-input",type:"text",name:`${e.id}-${G.key}-credential`,autoComplete:"off",placeholder:G.placeholder,value:o[G.key]||"",onChange:se=>i(Nt=>({...Nt,[G.key]:se.target.value}))})]},G.key)),s.jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[O&&s.jsx("button",{className:"btn btn-primary",onClick:A,disabled:b||P&&!e.credentials.fields.filter(G=>!G.optional).every(G=>{var se;return(se=o[G.key])==null?void 0:se.trim()}),children:b?"Saving...":"Save & Encrypt"}),j&&!O&&s.jsx("button",{className:"btn btn-primary",onClick:Pe,disabled:E,children:E?"Starting...":`Activate ${e.name}`})]})]})})(),re==="needs-oauth"&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:{fontSize:"0.8rem",color:"var(--success)",marginBottom:"0.25rem"},children:["✓"," Step 1 done — credentials saved"]}),s.jsxs("div",{style:{fontSize:"0.8rem",color:"var(--text-secondary)",marginBottom:"0.75rem"},children:["Step 2: connect your ",e.name," account to authorize access."]}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem",flexWrap:"wrap"},children:[s.jsxs("button",{className:"btn btn-primary",onClick:he,children:["Connect ",e.name," Account"]}),s.jsx("button",{className:"btn btn-ghost",onClick:()=>c(!1),children:"Change Credentials"})]})]}),re==="ready"&&!t&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:{fontSize:"0.8rem",color:"var(--success)",marginBottom:"0.75rem"},children:["✓"," ",e.oauth?`${e.name} account connected`:"Credentials configured"]}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem",flexWrap:"wrap"},children:[s.jsx("button",{className:"btn btn-primary",onClick:Pe,disabled:E,children:E?"Starting...":`Start ${e.name} Integration`}),!e.oauth&&s.jsx("button",{className:"btn btn-ghost",onClick:()=>c(!1),children:"Update Credentials"}),e.oauth&&s.jsx("button",{className:"btn btn-ghost",onClick:()=>{c(!1),h(!1)},children:"Change Credentials"})]})]}),re==="ready"&&t&&!t.running&&(yt.showStart?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"service-status service-status-error",style:{marginBottom:"0.75rem"},children:[s.jsx("span",{className:"service-status-dot"}),"Not running"]}),t.error&&s.jsx("div",{style:{fontSize:"0.8rem",color:"var(--danger)",marginBottom:"0.75rem"},children:t.error}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[s.jsx("button",{className:"btn btn-primary",onClick:Pe,disabled:E,children:E?"Starting...":"Start"}),s.jsx("button",{className:"btn btn-ghost",style:{color:"var(--danger)"},onClick:qe,children:"Disable"})]})]}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"service-status",style:{marginBottom:"0.5rem",color:"var(--text-muted)"},children:[s.jsx("span",{className:"service-status-dot",style:{background:"var(--text-muted)"}}),"Paused"]}),s.jsx("p",{style:{fontSize:"0.8rem",color:"var(--text-muted)",marginBottom:"0.75rem"},children:"Real systems are off while simulation mode is on."}),s.jsx("div",{style:{display:"flex",gap:"0.5rem"},children:s.jsx("button",{className:"btn btn-ghost",style:{color:"var(--danger)"},onClick:qe,children:"Disable"})})]}))]})}function Ix(e,t){if(!t)return{grouped:!1,testSystems:[],realErrors:[],pausedReal:[],ungrouped:e};const n=e.filter(i=>zi(i.manifest)),r=e.filter(i=>!zi(i.manifest)),a=r.filter(i=>i.state==="error"),o=r.filter(i=>i.state!=="error");return{grouped:!0,testSystems:n,realErrors:a,pausedReal:o,ungrouped:[]}}function Rx({entry:e}){return s.jsxs("div",{className:"int-paused-row",children:[s.jsx("span",{"aria-hidden":"true",children:Nm(e.manifest.icon)}),s.jsx("span",{className:"int-paused-name",children:e.manifest.name}),s.jsxs("span",{className:"int-chip int-chip-paused",children:[s.jsx("span",{className:"int-dot"}),"Paused"]})]})}function Px(){const{loading:e,mcpServerUp:t,manifestsError:n,entries:r,refresh:a}=Ul(),o=dm(),[i,l]=u.useState(""),c=u.useCallback(f=>{l(f),setTimeout(()=>l(""),5e3)},[]),d=Ix(r,o);return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"page-header",children:[s.jsx("h1",{className:"page-title",children:"Integrations"}),s.jsx("p",{className:"page-subtitle",children:"Connect external services and manage MCP integrations."})]}),i&&s.jsx("div",{className:"alert alert-success",children:i}),e?s.jsx("p",{style:{color:"var(--text-tertiary)"},children:"Loading integrations..."}):t===!1?s.jsxs("div",{className:"status-banner status-banner-error",children:[s.jsx("span",{className:"status-banner-icon",children:"!"}),s.jsx("span",{className:"status-banner-text",children:"MCP server is not reachable. Make sure it is running."})]}):d.grouped?s.jsxs(s.Fragment,{children:[d.testSystems.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"int-group-label",children:"Test systems"}),d.testSystems.map(f=>s.jsx($o,{manifest:f.manifest,integration:f.integration,state:f.state,onStatusChange:a,onSuccess:c},f.id))]}),(d.realErrors.length>0||d.pausedReal.length>0)&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"int-group-label",children:"Real systems"}),d.realErrors.map(f=>s.jsx($o,{manifest:f.manifest,integration:f.integration,state:f.state,onStatusChange:a,onSuccess:c},f.id)),d.pausedReal.length>0&&s.jsxs("details",{className:"int-paused-group",open:!0,children:[s.jsxs("summary",{children:["Paused while simulation mode is on (",d.pausedReal.length,")"]}),s.jsxs("p",{className:"int-paused-group-note",children:["Nothing is lost — mandates, credentials and data stay. They start again when simulation mode is switched off (",s.jsx("code",{children:"suveren-gateway simulation off"}),")."]}),d.pausedReal.map(f=>s.jsx(Rx,{entry:f},f.id))]})]}),r.length===0&&s.jsx(yu,{manifestsError:n})]}):s.jsxs(s.Fragment,{children:[r.map(f=>s.jsx($o,{manifest:f.manifest,integration:f.integration,state:f.state,onStatusChange:a,onSuccess:c},f.id)),r.length===0&&s.jsx(yu,{manifestsError:n})]})]})}function yu({manifestsError:e}){return e?s.jsxs("div",{className:"status-banner status-banner-error",children:[s.jsx("span",{className:"status-banner-icon",children:"!"}),s.jsxs("span",{className:"status-banner-text",children:["Couldn't load integrations — the gateway can't reach its MCP server (or you're signed out). Check the control-plane's"," ",s.jsx("code",{children:"SUVEREN_MCP_INTERNAL_URL"})," (dev MCP is :3431), then refresh."]})]}):s.jsx("p",{style:{color:"var(--text-tertiary)",textAlign:"center",marginTop:"2rem"},children:"No integrations available yet."})}function _x(){var U,V,J;const{activeTeam:e,activeMembership:t,refreshGroups:n,user:r}=Fe(),[a,o]=u.useState(null),[i,l]=u.useState(!1),[c,d]=u.useState(""),[f,p]=u.useState(""),[m,w]=u.useState(!1),[v,x]=u.useState(""),[k,g]=u.useState("");u.useEffect(()=>{fetch("/health").then(D=>D.json()).then(D=>{typeof D.spUrl=="string"&&g(D.spUrl)}).catch(()=>{})},[]),u.useEffect(()=>{if(!e){o(null);return}T.getGroupById(e.id).then(D=>{const _=D.group??D,B=D.members??[],ne=D.isAdmin??!1,L=B.map(z=>{const W=z.userId||z.id||"",R=z.role||(ne&&W===_.createdBy?"admin":"member");return{id:W,name:z.name||W.slice(0,8)||"Member",email:z.email||"",domains:z.domains||[],role:R,isAdmin:R==="admin"||ne&&W===_.createdBy}});o({id:_.id,name:_.name,members:L})}).catch(()=>o(null))},[e==null?void 0:e.id]);const h=(a==null?void 0:a.members.filter(D=>D.isAdmin))??[],y=(e==null?void 0:e.isAdmin)===!0&&h.length<=1&&h.some(D=>D.id===(r==null?void 0:r.id)),S=(e==null?void 0:e.name)??"",b=v.trim()===S&&!i,N=()=>{x(""),w(!0)},C=()=>{w(!1),x("")},I=async()=>{if(!(!e||!b)){l(!0),d("");try{await T.leaveTeam(e.id),await n(),p("You have left the team."),o(null),C()}catch(D){d(D instanceof Error?D.message:"Failed to leave team")}finally{l(!1)}}},E=e&&k?`${k}/dashboard/groups/${e.id}`:void 0,$=k?`${k}/dashboard/groups`:void 0;return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"page-header",children:s.jsxs("div",{children:[s.jsx("h1",{className:"page-title",children:"Team"}),s.jsx("p",{className:"page-subtitle",children:"Your current team context. Team management lives in your Authority Server dashboard."})]})}),c&&s.jsx("div",{className:"error-message",children:c}),f&&s.jsx("div",{className:"alert alert-success",children:f}),e?s.jsxs("div",{className:"card",style:{marginBottom:"1.5rem"},children:[s.jsxs("div",{className:"card-header",children:[s.jsxs("div",{children:[s.jsx("h3",{className:"card-title",children:e.name}),s.jsxs("p",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)",marginTop:"0.125rem"},children:[((U=a==null?void 0:a.members)==null?void 0:U.length)??0," ",(((V=a==null?void 0:a.members)==null?void 0:V.length)??0)===1?"member":"members",e.isAdmin&&" · You are admin"]})]}),s.jsx("span",{className:"status-badge status-active",children:"Active"})]}),(J=a==null?void 0:a.members)==null?void 0:J.map(D=>s.jsxs("div",{className:"member-row",children:[s.jsx("div",{className:"member-avatar",children:D.name.split(" ").map(_=>_[0]).join("").slice(0,2).toUpperCase()}),s.jsxs("div",{className:"member-info",children:[s.jsx("div",{className:"member-name",children:D.name}),s.jsx("div",{className:"member-email",children:D.email})]}),s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-tertiary)"},children:D.role})]},D.id)),s.jsxs("div",{style:{marginTop:"1.25rem",paddingTop:"1rem",borderTop:"1px solid var(--border)",display:"flex",alignItems:"center",gap:"0.75rem",flexWrap:"wrap"},children:[E&&s.jsx("a",{className:"btn btn-secondary btn-sm",href:E,target:"_blank",rel:"noopener noreferrer",children:"Manage this team in your Authority Server →"}),s.jsx("span",{title:y?"You are the only admin. Transfer admin to another member in your Authority Server dashboard before leaving.":void 0,style:{marginLeft:"auto"},children:s.jsx("button",{className:"btn btn-ghost btn-sm",style:{color:"var(--text-tertiary)"},onClick:N,disabled:i||y,children:"Leave team"})})]})]}):s.jsxs("div",{className:"card",style:{textAlign:"center",padding:"2rem 1.5rem"},children:[s.jsx("h3",{style:{margin:"0 0 0.5rem 0",fontSize:"1rem"},children:"You are working solo."}),s.jsx("p",{style:{fontSize:"0.875rem",color:"var(--text-secondary)",marginBottom:"1rem",maxWidth:480,marginLeft:"auto",marginRight:"auto"},children:"Every mandate you create here is in your personal context. You can join an existing team or create a new one in your Authority Server dashboard."}),$&&s.jsx("a",{className:"btn btn-primary btn-sm",href:$,target:"_blank",rel:"noopener noreferrer",children:"Open Authority Server dashboard →"})]}),m&&e&&s.jsx("div",{role:"dialog","aria-modal":"true","aria-labelledby":"leave-team-title",style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.5)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3,padding:"1rem"},onClick:C,children:s.jsxs("div",{className:"card",onClick:D=>D.stopPropagation(),style:{maxWidth:480,width:"100%",margin:0},children:[s.jsxs("h3",{id:"leave-team-title",className:"card-title",style:{marginBottom:"0.5rem"},children:["Leave ",S,"?"]}),s.jsx("p",{style:{fontSize:"0.875rem",color:"var(--text-secondary)",marginBottom:"0.75rem"},children:"Leaving will:"}),s.jsxs("ul",{style:{fontSize:"0.875rem",color:"var(--text-secondary)",marginBottom:"1rem",paddingLeft:"1.25rem",lineHeight:1.6},children:[s.jsx("li",{children:"Revoke all mandates you created in this team's context"}),s.jsx("li",{children:"Reject any pending action proposals you authored"}),s.jsx("li",{children:"Disable your membership — rejoining requires admin reactivation"})]}),s.jsxs("p",{style:{fontSize:"0.875rem",color:"var(--text-secondary)",marginBottom:"1rem"},children:["Your ",s.jsx("strong",{children:"personal"})," mandates are not affected."]}),s.jsxs("div",{className:"form-group",children:[s.jsxs("label",{htmlFor:"leave-confirm-input",style:{fontSize:"0.825rem",display:"block",marginBottom:"0.375rem"},children:["Type ",s.jsx("code",{children:S})," to confirm:"]}),s.jsx("input",{id:"leave-confirm-input",className:"form-input",type:"text",value:v,onChange:D=>x(D.target.value),placeholder:S,disabled:i,autoFocus:!0})]}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem",justifyContent:"flex-end",marginTop:"1rem"},children:[s.jsx("button",{className:"btn btn-ghost",onClick:C,disabled:i,children:"Cancel"}),s.jsx("button",{className:"btn btn-secondary",style:{color:"var(--danger, #e53e3e)"},onClick:I,disabled:!b,children:i?"Leaving...":"Leave team"})]})]})})]})}function Ax({onDismiss:e}){const t=nn(),{group:n,groupId:r,domain:a}=Fe(),[o,i]=u.useState([]),[l,c]=u.useState([]),[d,f]=u.useState([]),[p,m]=u.useState(!0),[w,v]=u.useState({});u.useEffect(()=>{Promise.all([T.listProfiles().catch(()=>[]),T.getIntegrationManifests().then(C=>C.manifests??[]).catch(()=>[]),T.getMcpHealth().then(C=>C.integrations??[]).catch(()=>[])]).then(async([C,I,E])=>{if(i(C),c(I),f(E),r){const $=await Promise.all(C.map(V=>T.getTeamProfileConfig(r,V.id).catch(()=>null))),U={};C.forEach((V,J)=>{const D=$[J];D&&(U[V.id]=D)}),v(U)}}).finally(()=>m(!1))},[r]);const x=new Map;for(const C of l)C.profile&&x.set(C.profile,C);const k=C=>C.replace(/@.*$/,"").split("/").pop()??C,g=C=>C.split("@")[1]??"",h=new Map;for(const C of o){const I=k(C.id);if(!x.has(I))continue;const E=h.get(I);(!E||g(C.id).localeCompare(g(E.id),void 0,{numeric:!0})>0)&&h.set(I,C)}const y=l.map(C=>{const I=C.profile?h.get(C.profile):void 0;return I?{manifest:C,profile:I,integration:d.find(E=>E.id===C.id)}:null}).filter(C=>C!==null),S=C=>C in w,b=C=>{if(!r){console.error("No active group when creating authorization");return}const I=S(C);sessionStorage.setItem("agentAuth",JSON.stringify({profileId:C,groupId:r,groupName:(n==null?void 0:n.name)??null,domain:a,isTeam:I,isPersonal:!!(n!=null&&n.isPersonal)})),sessionStorage.removeItem("agentGate"),e==null||e(),t("/mandates/new/intent")},N=C=>{r&&b(C)};return s.jsxs(s.Fragment,{children:[s.jsx("style",{children:`
70
70
  .profile-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 1.25rem; align-items: stretch; }
71
71
  .profile-grid .card { display: flex; flex-direction: column; height: 100%; margin-top: 0 !important; }
72
72
  @media (max-width: 900px) { .profile-grid { grid-template-columns: repeat(2, 1fr); } }
73
73
  @media (max-width: 560px) { .profile-grid { grid-template-columns: 1fr; } }
74
- `}),p?s.jsx("p",{style:{color:"var(--text-tertiary)",fontSize:"0.9rem"},children:"Loading..."}):y.length===0?s.jsxs("div",{className:"card",style:{padding:"2rem",textAlign:"center"},children:[s.jsx("p",{style:{color:"var(--text-secondary)",fontSize:"0.9rem",marginBottom:"1rem"},children:"No integrations set up yet. Connect a service first."}),s.jsx(Ye,{to:"/integrations",className:"btn btn-primary btn-sm",onClick:()=>e==null?void 0:e(),children:"Go to Integrations"})]}):s.jsx("div",{className:"profile-grid",children:y.map(({manifest:C,profile:I,integration:E})=>{const $=S(I.id),U=(E==null?void 0:E.running)===!0;return s.jsxs("div",{className:"card",style:U?void 0:{opacity:.7},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem",marginBottom:"0.125rem"},children:[s.jsx("h3",{className:"card-title",style:{margin:0},children:C.name}),$?s.jsx("span",{style:{fontSize:"0.6rem",padding:"0.1rem 0.35rem",borderRadius:"0.2rem",background:"var(--accent-subtle)",color:"var(--accent)",fontWeight:600},children:"Team"}):s.jsx("span",{style:{fontSize:"0.6rem",padding:"0.1rem 0.35rem",borderRadius:"0.2rem",background:"var(--bg-main)",color:"var(--text-tertiary)",fontWeight:600,border:"1px solid var(--border)"},children:"Personal"})]}),s.jsx("p",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)",marginBottom:"1rem",flex:1},children:C.description||I.description}),U?s.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>N(I.id),children:"Give a mandate"}):s.jsxs(Ye,{to:`/integrations?setup=${(C==null?void 0:C.id)??""}`,className:"btn btn-secondary btn-sm",style:{textDecoration:"none",textAlign:"center"},onClick:()=>e==null?void 0:e(),children:["Set up ",(C==null?void 0:C.name)??"integration"]})]},C.id)})})]})}const _x={active:"Active",pending:"Pending",expired:"Expired",revoked:"Revoked"};function Ax({status:e,label:t}){return s.jsx("span",{className:`status-badge status-${e}`,children:t||_x[e]})}function zx({domain:e,attested:t}){const n=t===!0?"domain-attested":t===!1?"domain-missing":"";return s.jsx("span",{className:`domain-badge ${n}`,style:{fontSize:"0.75rem"},children:e})}const Tn=86400,Fr=3600,Ws=60,$x=30*Tn;function Lx(e){if(e<=0)return"Expired";if(e>90*Tn){const t=Math.floor(e/$x);return`${t} ${t===1?"month":"months"} remaining`}if(e>7*Tn){const t=Math.floor(e/Tn);return`${t} ${t===1?"day":"days"} remaining`}if(e>=2*Tn){const t=Math.floor(e/Tn),n=Math.floor(e%Tn/Fr);return`${t} ${t===1?"day":"days"} ${n}h remaining`}if(e>=2*Fr){const t=Math.floor(e/Fr),n=Math.floor(e%Fr/Ws);return`${t}h ${String(n).padStart(2,"0")}m remaining`}if(e>=Ws){const t=Math.floor(e/Ws),n=Math.floor(e%Ws);return`${t}m ${String(n).padStart(2,"0")}s remaining`}return`${Math.floor(e)}s remaining`}function Mx({expiresAt:e}){const[t,n]=u.useState(()=>e-Date.now()/1e3),r=t<2*Fr;u.useEffect(()=>{const o=setInterval(()=>n(e-Date.now()/1e3),r?1e3:6e4);return()=>clearInterval(o)},[e,r]);const a=t<300;return s.jsx("span",{className:`ttl-badge ${a?"ttl-warn":"ttl-ok"}`,children:Lx(t)})}function Em({icon:e,title:t,text:n,children:r}){return s.jsxs("div",{className:"empty-state",children:[e&&s.jsx("div",{className:"empty-state-icon",children:e}),s.jsx("div",{className:"empty-state-title",children:t}),n&&s.jsx("div",{className:"empty-state-text",children:n}),r]})}function Fx(e){const t=Math.floor(e/86400);if(t>=1)return`${t} day${t===1?"":"s"}`;const n=Math.floor(e/3600);if(n>=1)return`${n} hour${n===1?"":"s"}`;const r=Math.ceil(e/60);return`${r} minute${r===1?"":"s"}`}const Ox=[{label:"30m",seconds:1800},{label:"1h",seconds:3600},{label:"2h",seconds:7200},{label:"4h",seconds:14400},{label:"8h",seconds:28800},{label:"24h",seconds:86400},{label:"7d",seconds:604800},{label:"30d",seconds:2592e3},{label:"1y",seconds:31536e3}];function Bx({item:e,onClose:t,onSuccess:n}){var y;const{user:r,activeDomain:a,groupId:o}=Fe(),[i,l]=u.useState(null);u.useEffect(()=>{let S=!1;return T.getProfile(e.profile_id).then(b=>{var N;S||l(((N=b==null?void 0:b.ttl)==null?void 0:N.max)??null)}).catch(()=>{}),()=>{S=!0}},[e.profile_id]);const c=e.remaining_seconds??0,d=Ox.filter(S=>S.seconds>c&&(i===null||S.seconds<=i)),f=((y=d[0])==null?void 0:y.seconds)??2592e3,[p,m]=u.useState(f);u.useEffect(()=>{var S;if(i!==null&&p>i){const b=(S=d[d.length-1])==null?void 0:S.seconds;b&&m(b)}},[i]);const[w,v]=u.useState(!1),[x,k]=u.useState(""),g=Object.entries(e.frame).filter(([S])=>S!=="profile"&&S!=="path"),h=async()=>{var S;if(r){v(!0),k("");try{const b=e.authorization_id,N=await T.getGateContent(b);if(!N)throw new Error("Gate content not found locally. The MCP server may have restarted. Please re-authorize through the full wizard instead.");const C=await T.getProfile(e.profile_id),I=e.frame,E=N.context??{},$=e.attested_domains[0]||a||"owner",U=await aa(I,C),V=await km(E,C),[J,D]=await Promise.all([Aa(N.gateContent.intent),Aa(JSON.stringify({profile:e.profile_id,path:e.path,domain:$}))]);if(!o)throw new Error("No active group; cannot extend mandate.");const _=(((S=e.deferred_commitment_domains)==null?void 0:S.length)??0)>0?"review":"automatic",B=await T.attest({authorization_id:e.authorization_id,renew:!0,profile_id:e.profile_id,bounds:I,bounds_hash:U,context_hash:V,domain:$,did:r.did,gate_content_hashes:{intent:J},execution_context_hash:D,group_id:o,commitment_mode:_,ttl:p});await T.pushGateContent(bm(B,{boundsHash:U,contextHash:V,context:E,path:e.path,gateContent:N.gateContent})),n()}catch(b){k(b instanceof Error?b.message:"Extension failed")}finally{v(!1)}}};return s.jsx("div",{className:"modal-backdrop",onClick:S=>S.target===S.currentTarget&&t(),children:s.jsxs("div",{className:"modal",children:[s.jsxs("div",{className:"modal-header",children:[s.jsx("h3",{className:"modal-title",children:"Extend mandate"}),s.jsx("button",{className:"modal-close",onClick:t,children:"×"})]}),s.jsxs("div",{className:"modal-body",children:[s.jsxs("div",{style:{marginBottom:"1rem"},children:[s.jsxs("div",{style:{fontWeight:600,marginBottom:"0.25rem"},children:[$e(e.profile_id)," / ",e.path]}),g.length>0&&s.jsx("div",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)"},children:g.map(([S,b])=>`${S}=${b}`).join(" · ")})]}),s.jsxs("div",{style:{marginBottom:"1rem"},children:[s.jsx("div",{style:{fontSize:"0.75rem",fontWeight:600,color:"var(--text-tertiary)",textTransform:"uppercase",letterSpacing:"0.04em",marginBottom:"0.5rem"},children:"New duration"}),c>0&&s.jsxs("div",{style:{fontSize:"0.75rem",color:"var(--text-tertiary)",marginBottom:"0.5rem"},children:["Currently valid for ",Fx(c),". Only longer durations are shown."]}),s.jsx("div",{style:{display:"flex",gap:"0.5rem",flexWrap:"wrap"},children:d.length===0?s.jsx("div",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)"},children:"This mandate is already on the longest available duration. Nothing to extend."}):d.map(S=>s.jsx("button",{className:`btn ${p===S.seconds?"btn-primary":"btn-secondary"}`,onClick:()=>m(S.seconds),style:{minWidth:"3.5rem"},children:S.label},S.seconds))})]}),s.jsx("div",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)",marginBottom:"0.5rem"},children:"Same bounds, scope, and gate content will be re-signed with a new TTL (measured from now)."}),x&&s.jsx("div",{className:"error-message",children:x})]}),s.jsxs("div",{className:"modal-footer",children:[s.jsx("button",{className:"btn btn-secondary",onClick:t,disabled:w,children:"Cancel"}),s.jsx("button",{className:"btn btn-primary",onClick:h,disabled:w,children:w?"Extending...":"Extend"})]})]})})}function Dx(e,t,n){return[...e].sort((r,a)=>{if(n){if(r.authorization_id===n&&a.authorization_id!==n)return-1;if(a.authorization_id===n&&r.authorization_id!==n)return 1}const o=Pa(r,t),i=Pa(a,t),l={active:0,pending:1,expired:2,revoked:3,archived:4};return l[o]!==l[i]?l[o]-l[i]:new Date(a.created_at).getTime()-new Date(r.created_at).getTime()})}function Ux({item:e,newerProfile:t,revokedSet:n,expandedHash:r,gateCache:a,gateLoading:o,copiedHash:i,revokingHash:l,copyingHash:c,profileConfigCache:d,mode:f,ownerLabel:p,isAdmin:m,onExpand:w,onCopyHash:v,onCopy:x,onRevoke:k,onExtend:g,archivedSet:h,archivingHash:y,onArchive:S,highlightHash:b}){var me;const N=Dl(e,{revokedSet:n}),C=im(e,{revokedSet:n,archivedSet:h}),I=!p&&!!S&&om(N),E=r===e.authorization_id,$=a[e.authorization_id],U=N==="active"||N==="pending"||N==="expired",V=Object.entries(e.frame).filter(([ee])=>ee!=="profile"&&ee!=="path"),J=d.get(e.profile_id)??null,D=(((me=J==null?void 0:J.approvers)==null?void 0:me.length)??0)>0,_=new Map;if(J!=null&&J.caps&&f==="team")for(const[ee,oe]of V){const re=J.caps[ee];re!==void 0&&Number(oe)>re&&_.set(ee,{authorized:Number(oe),cap:re})}const B=_.size>0,ne=e.approvers_frozen??[],L=(J==null?void 0:J.approvers)??[],z=f==="team"&&ne.length>0&&L.length>0&&(ne.length!==L.length||ne.some(ee=>!L.includes(ee))||L.some(ee=>!ne.includes(ee))),W=Array.from(_.entries()).map(([ee,oe])=>`${ee}: ${oe.authorized} (cap ${oe.cap})`).join(", "),R=Array.from(_.entries()).map(([ee,oe])=>`${ee}: ${oe.authorized} → ${oe.cap}`).join(", "),F=B?D?_.size===1?`Above team cap: ${W} — actions require approval`:`Above team cap (${_.size}): ${W} — actions require approval`:_.size===1?`Reduced by hard cap: ${R}`:`Reduced by hard cap (${_.size}): ${R}`:"",Q=B?D?"Above-cap actions under this mandate require per-action approval from the profile's approvers. Bounds remain authorized at their original values.":"No approvers are configured for this profile, so the team cap is a hard ceiling. Bounds above the cap are effectively reduced to the cap. Ask the admin to raise the cap or add approvers, or copy this mandate to reissue within the cap.":void 0,q=$e(e.profile_id),te=t?s.jsxs("div",{style:{fontSize:"0.75rem",color:"var(--text-tertiary)",marginBottom:"0.5rem",padding:"0.4rem 0.6rem",border:"1px solid var(--border)",borderRadius:6},children:[s.jsxs("strong",{style:{color:"var(--text-secondary)"},children:[q,"@",t.version," available"]}),t.whatsNew?s.jsxs(s.Fragment,{children:[" — ",t.whatsNew]}):null,s.jsx("br",{}),s.jsxs("span",{children:["This mandate stays on ",e.profile_id.split("@")[1]??"its pinned version","; authorize again to move it."]})]}):null,ce=b!=null&&e.authorization_id===b;return s.jsxs("div",{className:`card${ce?" card-highlight":""}`,style:{marginBottom:0},children:[te,p&&s.jsxs("div",{style:{fontSize:"0.75rem",color:"var(--text-tertiary)",marginBottom:"0.375rem"},children:["Owner: ",s.jsx("span",{style:{color:"var(--text-secondary)",fontWeight:500},children:p})]}),s.jsxs("div",{className:"auth-card-header",children:[s.jsx("span",{style:{fontWeight:700,fontSize:"1rem",color:"var(--text-primary)",letterSpacing:"0.01em"},children:q}),e.title&&s.jsx("span",{style:{fontWeight:500,fontSize:"0.85rem",color:"var(--text-secondary)"},children:e.title}),s.jsx(Ax,{status:N}),N==="active"&&e.earliest_expiry&&s.jsx(Mx,{expiresAt:new Date(e.earliest_expiry).getTime()/1e3}),N==="expired"&&(()=>{const ee=Gy(e,N);return ee?s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-tertiary)"},title:`Expired ${new Date(ee.iso).toLocaleString()}`,children:new Date(ee.iso).toLocaleDateString(void 0,{month:"short",day:"numeric"})}):null})()]}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem",flexWrap:"wrap",marginBottom:"0.5rem",alignItems:"center"},children:[e.required_domains.map(ee=>s.jsx(zx,{domain:ee,attested:e.attested_domains.includes(ee)},ee)),e.deferred_commitment_domains.length>0&&s.jsx("span",{style:{fontSize:"0.65rem",padding:"0.15rem 0.4rem",borderRadius:"0.25rem",background:"var(--accent-subtle)",color:"var(--accent)",fontWeight:600},children:"Review Mode"}),B&&s.jsx("span",{title:Q,style:{fontSize:"0.65rem",padding:"0.15rem 0.4rem",borderRadius:"0.25rem",background:D?"var(--accent-subtle)":"var(--danger-subtle)",color:D?"var(--accent)":"var(--danger)",fontWeight:600,cursor:"help"},children:F}),z&&s.jsx("button",{className:"btn btn-ghost btn-sm",style:{fontSize:"0.65rem",padding:"0.15rem 0.5rem",borderRadius:"0.25rem",background:"var(--warning-subtle, rgba(234,179,8,0.12))",color:"var(--warning, #ca8a04)",fontWeight:600,border:"1px solid var(--warning-border, rgba(234,179,8,0.3))",cursor:"pointer",lineHeight:1.4},onClick:()=>x(e),disabled:c===e.authorization_id,title:"The approver list for this profile has changed since this mandate was created. Copy to reissue with the current approvers.",children:c===e.authorization_id?"Copying...":"Approver list updated · Copy with new approvers"})]}),V.length>0&&s.jsx("div",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)"},children:V.map(([ee,oe],re)=>{const A=_.get(ee);return s.jsxs("span",{children:[re>0&&" · ",A?D?s.jsxs("span",{title:`Team cap on ${ee} is ${A.cap}. Actions exceeding the cap require per-action approval. Bound remains authorized at ${A.authorized}.`,children:[s.jsxs("span",{style:{color:"var(--text-tertiary)"},children:[ee,"=",String(oe)]}),s.jsxs("span",{style:{color:"var(--accent)",marginLeft:"0.25rem",fontWeight:600},children:["↑ approval at ",A.cap]})]}):s.jsxs("span",{title:`Team cap on ${ee} is ${A.cap} with no approvers configured (hard cap). Authorized for ${A.authorized}; effective ${A.cap}.`,children:[s.jsxs("span",{style:{textDecoration:"line-through",color:"var(--text-tertiary)"},children:[ee,"=",String(oe)]}),s.jsxs("span",{style:{color:"var(--danger)",marginLeft:"0.25rem",fontWeight:600},children:["→"," ",A.cap]})]}):s.jsxs("span",{children:[ee,"=",String(oe)]})]},ee)})}),s.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:"0.5rem",marginTop:"0.5rem"},children:[I&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>S(e.authorization_id,!C),disabled:y===e.authorization_id,title:C?"Move back to the Expired or Revoked list":"Hide from the list and the nav badge. Nothing is deleted: the mandate and its tickets stay stored and verifiable.",children:y===e.authorization_id?C?"Unarchiving…":"Archiving…":C?"↩ Unarchive":"⊟ Archive"}),s.jsx("button",{className:"btn btn-ghost btn-sm",onClick:()=>w(e),children:E?"▲ Hide Details":"▼ Details"})]}),E&&s.jsxs("div",{style:{borderTop:"1px solid var(--border)",marginTop:"0.75rem",paddingTop:"0.75rem"},children:[V.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{style:{fontSize:"0.75rem",fontWeight:600,color:"var(--text-tertiary)",textTransform:"uppercase",letterSpacing:"0.04em",marginBottom:"0.25rem"},children:"Bounds"}),s.jsx("dl",{className:"review-grid",children:V.map(([ee,oe])=>s.jsxs("span",{style:{display:"contents"},children:[s.jsx("dt",{children:ee}),s.jsx("dd",{children:String(oe)})]},ee))})]}),($==null?void 0:$.context)&&Object.keys($.context).length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{style:{fontSize:"0.75rem",fontWeight:600,color:"var(--text-tertiary)",textTransform:"uppercase",letterSpacing:"0.04em",marginTop:"1rem",marginBottom:"0.25rem"},children:"Scope"}),s.jsx("dl",{className:"review-grid",children:Object.entries($.context).map(([ee,oe])=>s.jsxs("span",{style:{display:"contents"},children:[s.jsx("dt",{children:ee}),s.jsx("dd",{title:String(oe),children:Cm(ee,oe,$.contextLabels)})]},ee))})]}),s.jsx("div",{style:{fontSize:"0.75rem",fontWeight:600,color:"var(--text-tertiary)",textTransform:"uppercase",letterSpacing:"0.04em",marginTop:"1rem",marginBottom:"0.25rem"},children:"Intent"}),o===e.authorization_id?s.jsx("p",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)"},children:"Loading gate content..."}):$?s.jsx("div",{className:"gate-content-block",children:s.jsx("div",{className:"gate-content-item",children:s.jsx("div",{className:"gate-content-text",children:$.gateContent.intent})})}):s.jsx("p",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)"},children:"Gate content not available."}),s.jsxs("div",{style:{fontSize:"0.75rem",color:"var(--text-tertiary)",marginTop:"1rem"},children:["Created: ",new Date(e.created_at).toLocaleString(),e.earliest_expiry&&` · Expires: ${new Date(e.earliest_expiry).toLocaleString()}`]}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem",marginTop:"0.25rem"},children:[s.jsx("span",{style:{fontSize:"0.7rem",color:"var(--text-tertiary)",fontFamily:"'SF Mono', Monaco, monospace",wordBreak:"break-all"},children:e.authorization_id}),s.jsx("button",{className:"btn btn-ghost btn-sm",style:{fontSize:"0.7rem",padding:"0.125rem 0.375rem"},onClick:()=>v(e.authorization_id),children:i===e.authorization_id?"copied":"copy"})]}),s.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:"0.5rem",marginTop:"0.75rem"},children:[!p&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>x(e),disabled:c===e.authorization_id,title:"Start a new mandate pre-filled with these bounds, scope, and intent",children:c===e.authorization_id?"Copying…":"⧉ Copy"}),!p&&(N==="active"||N==="pending")&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>x(e,{asEdit:!0}),disabled:c===e.authorization_id,title:"Adjust intent, bounds, or scope: opens the ceremony pre-filled; signing the new mandate revokes this one",children:"✎ Edit"}),!p&&U&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>g(e),children:"↻ Extend"}),p&&m&&N!=="revoked"?s.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>k(e.authorization_id,p,q),disabled:l===e.authorization_id,children:l===e.authorization_id?"Revoking…":"Revoke"}):!p&&(N==="active"||N==="pending")?s.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>k(e.authorization_id),disabled:l===e.authorization_id,children:l===e.authorization_id?"Revoking…":"Revoke"}):null]})]})]},e.authorization_id)}function Wx(){const[e,t]=u.useState([]),[n,r]=u.useState(!0),[a,o]=u.useState([]),[i,l]=u.useState(!1),[c,d]=u.useState(new Map),[f,p]=u.useState("mine"),[m,w]=u.useState("active"),[v,x]=u.useState(null),[k,g]=u.useState(null),[h,y]=tm(),[S,b]=u.useState(()=>h.get("new")==="1"),[N,C]=u.useState(()=>h.get("highlight")),[I,E]=u.useState(null),[$,U]=u.useState({}),[V,J]=u.useState(null),[D,_]=u.useState(null),[B,ne]=u.useState(null),[L,z]=u.useState(new Set),[W,R]=u.useState(null),[F,Q]=u.useState(new Set),[q,te]=u.useState(null),[ce,me]=u.useState(null),ee=nn(),{group:oe,groupId:re,domain:A,mode:X,activeTeam:ae}=Fe(),ge=(ae==null?void 0:ae.isAdmin)===!0,[he,Pe]=u.useState(()=>new Map),qe=u.useCallback(()=>{r(!0),T.getMyAttestations().then(t).catch(()=>{}).finally(()=>r(!1))},[]),_e=u.useCallback(()=>{T.getArchivedMandates().then(H=>Q(new Set(H))).catch(()=>{})},[]);u.useEffect(()=>{_e()},[_e]);const yt=async(H,Z)=>{te(H);try{const K=await T.setMandateArchived(H,Z);Q(new Set(K)),window.dispatchEvent(new Event("suveren:archived-changed"))}catch(K){alert(K instanceof Error?K.message:"Failed to update archive")}finally{te(null)}},Ze=u.useCallback(()=>{re&&(l(!0),T.listTeamAuthorizations(re).then(o).catch(()=>{}).finally(()=>l(!1)))},[re]);fe("attestation-changed",()=>{qe(),ge&&re&&Ze()}),u.useEffect(()=>{if(!N)return;h.get("highlight")&&(h.delete("highlight"),y(h,{replace:!0}));const H=window.setTimeout(()=>C(null),3e3);return()=>window.clearTimeout(H)},[]),Pt(qe,3e5),u.useEffect(()=>{f==="team"&&ge&&re&&a.length===0&&!i&&Ze()},[f,ge,re,a.length,i,Ze]),u.useEffect(()=>{let H=!1;return T.listProfiles().then(Z=>{if(H)return;const K=lt=>lt.replace(/@.*$/,"").split("/").pop()??lt,de=lt=>lt.split("@")[1]??"",ye=new Map;for(const lt of Z){const Wt=K(lt.id),ws=ye.get(Wt);(!ws||de(lt.id).localeCompare(de(ws.id),void 0,{numeric:!0})>0)&&ye.set(Wt,lt)}d(ye)}).catch(()=>{}),()=>{H=!0}},[]);const Ge=u.useCallback(H=>{const Z=Wt=>Wt.replace(/@.*$/,"").split("/").pop()??Wt,K=Wt=>Wt.split("@")[1]??"",de=c.get(Z(H));if(!de)return;const ye=K(H),lt=K(de.id);if(!(!ye||!lt))return lt.localeCompare(ye,void 0,{numeric:!0})>0?de:void 0},[c]);u.useEffect(()=>{if(X!=="team"||!re)return;const H=f==="mine"?e:a;if(H.length===0)return;const Z=[...new Set(H.map(K=>K.profile_id))].filter(K=>!he.has(K));if(Z.length!==0){Pe(K=>{const de=new Map(K);for(const ye of Z)de.set(ye,null);return de});for(const K of Z)T.getTeamProfileConfig(re,K).then(de=>{Pe(ye=>new Map(ye).set(K,de))}).catch(()=>{})}},[e,a,f,re,X,he]);const le=async H=>{if(I===H.authorization_id){E(null);return}E(H.authorization_id);const Z=H.authorization_id;if(!(Z in $)){J(H.authorization_id);try{const K=await T.getGateContent(Z);U(de=>({...de,[Z]:K}))}catch{U(K=>({...K,[Z]:null}))}finally{J(null)}}},et=H=>{navigator.clipboard.writeText(H).then(()=>{ne(H),setTimeout(()=>ne(null),2e3)})},Ut=async(H,Z)=>{var K;if(!re){alert("No active group; cannot copy mandate.");return}me(H.authorization_id);try{const de=H.authorization_id;let ye=$[de]??null;de in $||(ye=await T.getGateContent(de),U(Ss=>({...Ss,[de]:ye})));const lt=Object.fromEntries(Object.entries(H.frame).filter(([Ss])=>Ss!=="profile"&&Ss!=="path")),Wt=(ye==null?void 0:ye.context)??{},ws=((K=ye==null?void 0:ye.gateContent)==null?void 0:K.intent)??"",Rm=H.deferred_commitment_domains.length>0?"review":"automatic",Pm=H.attested_domains[0]||A||"owner",Za=Date.parse(H.created_at),eo=H.earliest_expiry?Date.parse(H.earliest_expiry):NaN,_m=Number.isFinite(Za)&&Number.isFinite(eo)&&eo>Za?Math.round((eo-Za)/1e3):void 0;sessionStorage.setItem("agentAuth",JSON.stringify({profileId:H.profile_id,groupId:re,groupName:(oe==null?void 0:oe.name)??null,domain:Pm,isPersonal:!!(oe!=null&&oe.isPersonal)})),sessionStorage.setItem("agentGate",JSON.stringify({bounds:lt,context:Wt,gateContent:{intent:ws},templateMode:Rm,templateTtl:_m})),Z!=null&&Z.asEdit?sessionStorage.setItem("agentEditReplaces",H.authorization_id):sessionStorage.removeItem("agentEditReplaces"),ee("/mandates/new/intent")}catch(de){alert(de instanceof Error?de.message:"Failed to copy mandate")}finally{me(null)}},j=async(H,Z,K)=>{const de=Z&&K?`Revoke ${Z}'s ${K} mandate? This cannot be undone.`:"Revoke this mandate? The agent will no longer be able to execute actions under it.";if(confirm(de)){R(H);try{await T.revokeAttestation(H),z(ye=>new Set(ye).add(H)),T.resyncGates().catch(()=>{}),Z&&re&&Ze()}catch(ye){alert(ye instanceof Error?ye.message:"Failed to revoke mandate")}finally{R(null)}}},P=f==="mine"?e:a,O=f==="mine"?n:i,G=f==="mine"?{revokedSet:L,archivedSet:F}:{revokedSet:L},se=H=>Pa(H,G),Nt={active:0,pending:0,expired:0,revoked:0,archived:0};for(const H of P)Nt[se(H)]+=1;const bn=f==="mine"?["active","pending","expired","revoked","archived"]:["active","pending","expired","revoked"],Ie=(()=>{const H=new Map;for(const Z of P){if(se(Z)!==m)continue;const K=H.get(Z.profile_id)??{count:0,review:!1};K.count+=1,Z.deferred_commitment_domains.length>0&&(K.review=!0),H.set(Z.profile_id,K)}return Array.from(H.entries()).map(([Z,K])=>({profileId:Z,...K})).sort((Z,K)=>$e(Z.profileId).localeCompare($e(K.profileId)))})(),it=Dx(P.filter(H=>{if(se(H)!==m||v!==null&&H.profile_id!==v)return!1;if(k!==null){const Z=H.deferred_commitment_domains.length>0;if(k==="review"&&!Z||k==="auto"&&Z)return!1}return!0}),G,N),vt={revokedSet:L,expandedHash:I,gateCache:$,gateLoading:V,copiedHash:B,revokingHash:W,copyingHash:ce,profileConfigCache:he,mode:X,activeDomain:A,group:oe,groupId:re,onExpand:le,onCopyHash:et,onCopy:Ut,onRevoke:j,onExtend:_,highlightHash:N},tt={...vt,archivedSet:F,archivingHash:q,onArchive:yt};return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"page-header",style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",gap:"1rem",flexWrap:"wrap"},children:[s.jsxs("div",{children:[s.jsx("h1",{className:"page-title",children:"Mandates"}),s.jsx("p",{className:"page-subtitle",children:"Active, pending, expired, and archived agent mandates."})]}),s.jsx("button",{className:"btn btn-primary",onClick:()=>b(!0),children:"+ New mandate"})]}),S&&s.jsx("div",{className:"modal-backdrop",onClick:()=>{b(!1),h.get("new")&&(h.delete("new"),y(h,{replace:!0}))},children:s.jsxs("div",{className:"modal",onClick:H=>H.stopPropagation(),style:{maxWidth:"960px",width:"90vw"},children:[s.jsxs("div",{className:"modal-header",children:[s.jsx("h2",{className:"modal-title",children:"New mandate"}),s.jsx("button",{className:"modal-close",onClick:()=>{b(!1),h.get("new")&&(h.delete("new"),y(h,{replace:!0}))},children:"×"})]}),s.jsxs("div",{className:"modal-body",children:[s.jsx("p",{style:{color:"var(--text-tertiary)",fontSize:"0.9rem",marginTop:0,marginBottom:"1rem"},children:"What should your agent be able to do? Pick a profile, set limits, then authorize."}),s.jsx(Px,{onDismiss:()=>b(!1)})]})]})}),ge&&s.jsxs("div",{className:"nav-tabs",style:{marginBottom:"0.5rem"},children:[s.jsx("button",{className:`nav-tab${f==="mine"?" active":""}`,onClick:()=>{p("mine"),w("active"),x(null),g(null),E(null)},children:"Mine"}),s.jsx("button",{className:`nav-tab${f==="team"?" active":""}`,onClick:()=>{p("team"),w("active"),x(null),g(null),E(null)},children:"Team"})]}),s.jsx("div",{className:"nav-tabs",children:bn.map(H=>s.jsxs("button",{className:`nav-tab${m===H?" active":""}`,onClick:()=>{w(H),x(null),g(null)},children:[H.charAt(0).toUpperCase()+H.slice(1)," (",Nt[H],")"]},H))}),Ie.length>0&&s.jsxs("div",{style:{display:"flex",gap:"0.5rem",flexWrap:"wrap",alignItems:"center",marginTop:"-0.25rem",marginBottom:"1rem"},children:[Ie.map(H=>{const Z=v===H.profileId;return s.jsx("button",{className:`btn btn-sm ${Z?"btn-primary":"btn-secondary"}`,onClick:()=>x(Z?null:H.profileId),children:$e(H.profileId)},H.profileId)}),s.jsx("span",{"aria-hidden":"true",style:{color:"var(--border)",fontSize:"1.1rem",padding:"0 0.25rem",userSelect:"none"},children:"|"}),["auto","review"].map(H=>{const Z=k===H;return s.jsx("button",{className:`btn btn-sm ${Z?"btn-primary":"btn-secondary"}`,onClick:()=>g(Z?null:H),children:H==="auto"?"Auto":"Review"},H)})]}),O&&P.length===0?s.jsx("p",{style:{color:"var(--text-tertiary)"},children:"Loading..."}):it.length===0?s.jsx(Em,{icon:"☰",title:"No mandates",text:m==="archived"?"Nothing archived. Archive an expired or revoked mandate to move it here.":`No ${m} mandates found.`}):s.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem"},children:it.map(H=>{const Z=f==="team"?H:null,K=Z!=null&&Z.owner?Z.owner.name??Z.owner.email??Z.owner.userId:void 0;return s.jsx(Ux,{item:H,newerProfile:Ge(H.profile_id),ownerLabel:K,isAdmin:ge,...f==="mine"?tt:vt},H.authorization_id)})}),D&&s.jsx(Bx,{item:D,onClose:()=>_(null),onSuccess:()=>{_(null),qe()}})]})}function Hx(e){const t=e.indexOf("__");return t<0?{integrationId:"",toolName:e}:{integrationId:e.slice(0,t),toolName:e.slice(t+2)}}function Vx(e,t){var c,d,f;const{integrationId:n,toolName:r}=Hx(e.action),a=t.find(p=>p.id===n),o=(d=(c=a==null?void 0:a.toolGating)==null?void 0:c.overrides)==null?void 0:d[r];if(o!=null&&o.actionLabel)return o.actionLabel;const i=$e(e.profileId),l=(f=e.executionContext)==null?void 0:f.action_type;return typeof l=="string"&&l?`${i} · ${l}`:`${i} · ${r}`}function Gx(e){const t=[];for(const[n,r]of Object.entries(e.executionContext??{})){if(!n.startsWith("allowed_"))continue;const a=String(r??"").trim();a&&t.push(a.split(",").map(o=>o.trim()).filter(Boolean).join(", "))}return t.join(" · ")}function Kx(e){if(!e)return"";const t=[];for(const[n,r]of Object.entries(e)){if(n==="action_type")continue;const a=String(r??"").trim();if(!a)continue;const o=n.replace(/^allowed_/,"").replace(/_/g," ");t.push(`${o} ${a.split(",").map(i=>i.trim()).filter(Boolean).join(", ")}`)}return t.join(" · ")}function Yx(e,t){var o,i;const n=[{window:"daily",label:"today"},{window:"monthly",label:"this month"}],r=e.actionType??(typeof((o=e.executionContext)==null?void 0:o.action_type)=="string"?e.executionContext.action_type:void 0),a=[];for(const{window:l,label:c}of n){const d=(i=e.cumulativeState)==null?void 0:i[l];if(!d)continue;const f=`_${l}_max`,p=Object.keys(t??{}).filter(k=>k.endsWith(f)),m=(r&&p.find(k=>k.startsWith(`${r}_`)))??(p.length===1?p[0]:void 0),v=(m?/^(amount|spend)_/.test(m):!1)?d.amount:d.count,x=m?Number(t==null?void 0:t[m]):NaN;m&&Number.isFinite(x)?a.push(`${v} of ${x} ${c}`):a.push(`${d.count} ${d.count===1?"call":"calls"} ${c}`)}return a.join(" · ")}function Qx(e){return typeof e.proposalId=="string"&&e.proposalId.length>0}function Jx(e){const t=$e(e),n=e.split("@")[1];return n?`${t}@${n}`:t}function Pr({label:e,children:t}){return s.jsxs(s.Fragment,{children:[s.jsx("dt",{className:"receipt-row-label",children:e}),s.jsx("dd",{className:"receipt-row-value",children:t})]})}function Xx({receipt:e,manifests:t,localAuth:n,localUnavailable:r,signature:a,grantTitle:o,ownerLabel:i,spUrl:l,formatDate:c,onOpenComplete:d}){var v;const f=Gx(e),p=Kx(n==null?void 0:n.context),m=Yx(e,(n==null?void 0:n.bounds)??e.limits),w=n==null?void 0:n.intent;return s.jsxs("div",{className:"card",style:{marginBottom:0},children:[s.jsxs("div",{className:"receipt-head",children:[s.jsx("span",{className:"receipt-what",children:Vx(e,t)}),s.jsx("span",{className:"receipt-tag",children:Qx(e)?"review":"automatic"}),e.contentHash&&s.jsx("span",{className:"receipt-tag receipt-tag-bound",title:(v=e.contentBinding)!=null&&v.fields?`The ticket binds: ${e.contentBinding.fields.join(", ")}`:"This exact content was authorized",children:"content bound"}),s.jsx("span",{className:"auth-card-time",children:c(e.timestamp)})]}),f&&s.jsx("div",{className:"receipt-scope",children:f}),s.jsxs("dl",{className:"receipt-rows",children:[s.jsx(Pr,{label:"mandate",children:s.jsx("strong",{children:o||Jx(e.profileId)})}),i&&s.jsx(Pr,{label:"owner",children:i}),p&&s.jsx(Pr,{label:"allowed",children:p}),m&&s.jsx(Pr,{label:"used",children:s.jsx("span",{className:"receipt-num",children:m})}),s.jsx(Pr,{label:"intent",children:w?s.jsx("span",{className:"receipt-intent",children:w}):s.jsx("span",{className:"receipt-absent",children:r?"local store unreachable — sign in to the gateway to read it":"not on this device — the Authority Server stores only its hash"})})]}),s.jsxs("div",{className:"receipt-foot",children:[a==="valid"&&s.jsx("span",{className:"receipt-verified",title:"Ed25519 signature checked on this device against the issuer key archived when the ticket was issued — no Authority Server involved.",children:"✓ Verified on this device"}),a==="invalid"&&s.jsx("span",{className:"receipt-tamper",title:"The stored ticket does not match what was signed.",children:"⚠ Signature check FAILED"}),s.jsx("button",{type:"button",className:"receipt-evidence-link",onClick:d,children:"Complete ticket"}),l&&s.jsxs("span",{className:"receipt-public",children:["redacted, shareable:"," ",s.jsx("a",{className:"receipt-link",href:`${l}/r/${e.id}`,target:"_blank",rel:"noreferrer",children:"public link ↗"})]})]}),s.jsxs("details",{className:"receipt-more",children:[s.jsx("summary",{children:"Raw"}),s.jsxs("div",{className:"receipt-kv",children:[s.jsxs("div",{children:["ticket · ",e.id]}),s.jsxs("div",{children:["action · ",e.action]}),s.jsxs("div",{children:["profile · ",e.profileId]}),e.authorizationId&&s.jsxs("div",{children:["mandate · ",e.authorizationId]}),Object.keys(e.executionContext??{}).length>0&&s.jsxs("div",{children:["scope ·"," ",Object.entries(e.executionContext).map(([x,k])=>`${x}=${k}`).join(" · ")]}),(n==null?void 0:n.boundsHash)&&s.jsxs("div",{children:["bounds hash · ",n.boundsHash]}),(n==null?void 0:n.contextHash)&&s.jsxs("div",{children:["scope hash · ",n.contextHash]}),e.contentHash&&s.jsxs("div",{children:["content · ",e.contentHash]}),e.proposalId&&s.jsxs("div",{children:["proposal · ",e.proposalId]}),s.jsxs("div",{children:["signature · ",e.signature]})]})]})]})}function qx({receipt:e,onClose:t}){const[n,r]=u.useState(null),[a,o]=u.useState(null),[i,l]=u.useState(null),[c,d]=u.useState(!0),[f,p]=u.useState(!1);u.useEffect(()=>{let k=!1;return d(!0),T.getArchivedReceipt(e.id).then(g=>{k||(r(g),o(g?"local":"authority-server"),l((g==null?void 0:g.signature)??null))}).catch(()=>{k||o("authority-server")}).finally(()=>{k||d(!1)}),()=>{k=!0}},[e.id]);const m=n?n.entry:{receipt:e},w=JSON.stringify(m,null,2);function v(){const k=URL.createObjectURL(new Blob([w],{type:"application/json"})),g=document.createElement("a");g.href=k,g.download=`suveren-ticket-${e.id.slice(0,8)}.json`,g.click(),URL.revokeObjectURL(k)}async function x(){try{await navigator.clipboard.writeText(w),p(!0),setTimeout(()=>p(!1),2e3)}catch{p(!1)}}return s.jsx("div",{className:"modal-backdrop",onClick:k=>k.target===k.currentTarget&&t(),children:s.jsxs("div",{className:"modal",style:{maxWidth:"44rem"},children:[s.jsxs("div",{className:"modal-header",children:[s.jsx("h3",{className:"modal-title",children:"Complete ticket"}),s.jsx("button",{className:"modal-close",onClick:t,"aria-label":"Close",children:"×"})]}),s.jsxs("div",{className:"modal-body",children:[i==="valid"&&s.jsx("p",{className:"receipt-verified",style:{margin:"0 0 0.5rem",fontSize:"0.8rem"},children:"✓ Ed25519 signature verified on this device, against the issuer key archived when this ticket was issued."}),i==="invalid"&&s.jsx("p",{className:"receipt-tamper",style:{margin:"0 0 0.5rem",fontSize:"0.8rem"},children:"⚠ Signature check FAILED — the stored ticket does not match what was signed."}),s.jsx("p",{style:{fontSize:"0.8rem",color:"var(--text-muted)",margin:"0 0 0.75rem"},children:c?"Loading…":a==="local"?"Held on this device — the signed ticket, the mandate it ran under, and the issuer key. Anyone with this file and that key can verify it offline, without Suveren.":"No local copy of this ticket (it predates local archiving, or ran on another device). Shown from the Authority Server — complete and signed, but it needs the server to retrieve."}),s.jsx("pre",{style:{fontFamily:"'SF Mono', Monaco, monospace",fontSize:"0.68rem",lineHeight:1.65,margin:0,background:"var(--accent-subtle)",border:"1px solid var(--border)",borderRadius:"6px",padding:"0.75rem 0.85rem",overflowX:"auto",maxHeight:"22rem",overflowY:"auto"},children:w})]}),s.jsxs("div",{className:"modal-footer",children:[s.jsx("button",{className:"btn btn-primary btn-sm",onClick:v,children:"Download"}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:x,children:f?"Copied":"Copy"})]})]})})}function Zx(e){return new Date(e*1e3).toLocaleString()}function e0(e,t){if(t==="all")return!0;const n=t==="1d"?1:t==="7d"?7:30,r=Math.floor(Date.now()/1e3)-n*86400;return e.timestamp>=r}function t0(e,t){if(!t)return!0;const n=t.toLowerCase();return e.profileId.toLowerCase().includes(n)||$e(e.profileId).toLowerCase().includes(n)||e.path.toLowerCase().includes(n)||e.action.toLowerCase().includes(n)||e.attestationHash.toLowerCase().includes(n)||e.id.toLowerCase().includes(n)||JSON.stringify(e.executionContext).toLowerCase().includes(n)}function vu(e,t){const n=new Map(e.map(r=>[r.id,r]));for(const r of t)n.set(r.id,r);return[...n.values()].sort((r,a)=>a.timestamp-r.timestamp)}function n0(){const{activeTeam:e,groupId:t}=Fe(),n=(e==null?void 0:e.isAdmin)===!0,[r,a]=u.useState("mine"),[o,i]=u.useState([]),[l,c]=u.useState([]),[d,f]=u.useState(""),[p,m]=u.useState(!0),[w,v]=u.useState({}),[x,k]=u.useState(new Set),[g,h]=u.useState(""),[y,S]=u.useState(new Set),[b,N]=u.useState(new Set),[C,I]=u.useState("all"),[E,$]=u.useState(!1),[U,V]=u.useState(!1),[J,D]=u.useState(null),[_,B]=u.useState({}),[ne,L]=u.useState(!1),[z,W]=u.useState({}),[R,F]=u.useState({}),[Q,q]=u.useState(null),[te,ce]=u.useState(null),[me,ee]=u.useState(!1),[oe,re]=u.useState(!1),A=u.useRef(""),X=u.useCallback(j=>r==="team"&&n&&t?T.listTeamReceiptsPage(t,{before:j,limit:200}):T.getMyReceiptsPage({before:j,limit:200}),[r,n,t]),ae=u.useCallback(()=>{const j=r==="team"?`team:${t}`:"mine",P=A.current!==j;A.current=j,m(!0),re(!1),X().then(O=>{i(G=>P?O.receipts:vu(G,O.receipts)),ce(G=>P?O.nextBefore:G??O.nextBefore)}).catch(()=>{P&&i([]),re(!0)}).finally(()=>m(!1))},[X,r,t]),ge=u.useCallback(()=>{!te||me||(ee(!0),re(!1),X(te).then(j=>{i(P=>vu(P,j.receipts)),ce(j.nextBefore)}).catch(()=>re(!0)).finally(()=>ee(!1)))},[te,me,X]);Pt(ae,12e4),u.useEffect(()=>{T.getIntegrationManifests().then(({manifests:j})=>c(j)).catch(()=>{}),fetch("/health").then(j=>j.json()).then(j=>{typeof j.spUrl=="string"&&f(j.spUrl.replace(/\/$/,""))}).catch(()=>{})},[]),u.useEffect(()=>{T.getLocalAuthorizations().then(({authorizations:j,signatures:P})=>{B(j),W(P),L(!1)}).catch(()=>{B({}),W({}),L(!0)}),T.getMyAttestations().then(j=>{const P={};for(const O of j)O.authorization_id&&O.title&&(P[O.authorization_id]=O.title);F(P)}).catch(()=>{})},[]),u.useEffect(()=>{r!=="team"||Object.keys(w).length>0||T.listUsers().then(j=>{const P={};for(const O of j)P[O.id]={name:O.name,email:O.email};v(P)}).catch(()=>{})},[r,w]);const he=u.useMemo(()=>{const j=new Set;for(const P of o)j.add($e(P.profileId));return[...j].sort()},[o]),Pe=u.useMemo(()=>{const j=new Set;for(const P of o)j.add(P.action);return[...j].sort()},[o]),qe=u.useMemo(()=>{if(r!=="team")return[];const j=new Set;for(const P of o)P.userId&&j.add(P.userId);return[...j].map(P=>{var O;return{id:P,label:(O=w[P])!=null&&O.name?`${w[P].name} (${w[P].email})`:P}}).sort((P,O)=>P.label.localeCompare(O.label))},[r,o,w]),_e=u.useMemo(()=>o.filter(j=>!(!t0(j,g)||y.size>0&&!y.has($e(j.profileId))||b.size>0&&!b.has(j.action)||x.size>0&&j.userId&&!x.has(j.userId)||!e0(j,C))),[o,g,y,b,x,C]),yt=y.size>0||b.size>0||x.size>0||C!=="all";function Ze(j){S(P=>{const O=new Set(P);return O.has(j)?O.delete(j):O.add(j),O})}function Ge(j){N(P=>{const O=new Set(P);return O.has(j)?O.delete(j):O.add(j),O})}function le(j){k(P=>{const O=new Set(P);return O.has(j)?O.delete(j):O.add(j),O})}function et(){S(new Set),N(new Set),k(new Set),I("all"),h("")}async function Ut(){V(!0),D(null);try{const{bundle:j,filename:P}=await T.fetchEvidenceBundle(),O=URL.createObjectURL(new Blob([JSON.stringify(j,null,2)],{type:"application/json"})),G=document.createElement("a");G.href=O,G.download=P,G.click(),URL.revokeObjectURL(O);const se=j.sources??{};se.authorityServer?se.local||D(`Downloaded Authority Server history only — ${se.localError??"local archive unavailable."}`):D(`Downloaded local evidence only — ${se.asError??"Authority Server export unavailable."}`)}catch(j){D(`Export failed: ${j instanceof Error?j.message:String(j)}`)}finally{V(!1)}}return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"page-header",style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",gap:"1rem",flexWrap:"wrap"},children:[s.jsxs("div",{children:[s.jsx("h1",{className:"page-title",children:"Tickets"}),s.jsx("p",{className:"page-subtitle",children:"Execution history for agent actions."})]}),s.jsx("button",{className:"btn btn-secondary",onClick:Ut,disabled:U,children:U?"Preparing…":"Download evidence"})]}),J&&s.jsx("div",{style:{marginBottom:"1rem",color:"var(--text-tertiary)",fontSize:"0.875rem"},children:J}),n&&s.jsx("div",{style:{display:"flex",gap:"0.5rem",marginBottom:"1rem",borderBottom:"1px solid var(--border)"},children:["mine","team"].map(j=>s.jsx("button",{onClick:()=>a(j),className:"btn btn-ghost",style:{borderRadius:0,padding:"0.5rem 0.875rem",borderBottom:r===j?"2px solid var(--accent)":"2px solid transparent",color:r===j?"var(--text-primary)":"var(--text-tertiary)",fontWeight:r===j?600:500},children:j==="mine"?"Mine":"Team"},j))}),s.jsxs("div",{className:"search-filter-bar",children:[s.jsxs("div",{className:"search-input-wrap",children:[s.jsx("span",{className:"search-icon",children:"⌕"}),s.jsx("input",{type:"text",className:"form-input search-input",placeholder:"Search by profile, action, path, or hash\\u2026",value:g,onChange:j=>h(j.target.value)}),g&&s.jsx("button",{className:"search-clear",onClick:()=>h(""),children:"×"})]}),s.jsxs("button",{className:`btn btn-sm btn-secondary${E?" active":""}`,onClick:()=>$(!E),children:["Filters",yt?` (${y.size+b.size+(C!=="all"?1:0)})`:""]})]}),E&&s.jsxs("div",{className:"filter-panel",children:[he.length>1&&s.jsxs("div",{className:"filter-section",children:[s.jsx("div",{className:"filter-label",children:"Profile"}),s.jsx("div",{className:"filter-chips",children:he.map(j=>s.jsx("button",{className:`filter-chip${y.has(j)?" selected":""}`,onClick:()=>Ze(j),children:j},j))})]}),Pe.length>1&&s.jsxs("div",{className:"filter-section",children:[s.jsx("div",{className:"filter-label",children:"Action"}),s.jsx("div",{className:"filter-chips",children:Pe.map(j=>s.jsx("button",{className:`filter-chip${b.has(j)?" selected":""}`,onClick:()=>Ge(j),children:j},j))})]}),r==="team"&&qe.length>1&&s.jsxs("div",{className:"filter-section",children:[s.jsx("div",{className:"filter-label",children:"Owner"}),s.jsx("div",{className:"filter-chips",children:qe.map(j=>s.jsx("button",{className:`filter-chip${x.has(j.id)?" selected":""}`,onClick:()=>le(j.id),children:j.label},j.id))})]}),s.jsxs("div",{className:"filter-section",children:[s.jsx("div",{className:"filter-label",children:"Time range"}),s.jsx("div",{className:"filter-chips",children:[["1d","Today"],["7d","7 days"],["30d","30 days"],["all","All time"]].map(([j,P])=>s.jsx("button",{className:`filter-chip${C===j?" selected":""}`,onClick:()=>I(j),children:P},j))})]})]}),yt&&s.jsxs("div",{className:"active-filters",children:[[...y].map(j=>s.jsxs("span",{className:"active-chip",onClick:()=>Ze(j),children:[j," ",s.jsx("span",{className:"chip-remove",children:"×"})]},j)),[...b].map(j=>s.jsxs("span",{className:"active-chip",onClick:()=>Ge(j),children:[j," ",s.jsx("span",{className:"chip-remove",children:"×"})]},j)),[...x].map(j=>{const P=w[j],O=P?P.name:j;return s.jsxs("span",{className:"active-chip",onClick:()=>le(j),children:[O," ",s.jsx("span",{className:"chip-remove",children:"×"})]},j)}),C!=="all"&&s.jsxs("span",{className:"active-chip",onClick:()=>I("all"),children:[C==="1d"?"Today":C==="7d"?"7 days":"30 days"," ",s.jsx("span",{className:"chip-remove",children:"×"})]}),s.jsx("button",{className:"clear-filters",onClick:et,children:"Clear all"})]}),oe&&s.jsx("div",{className:"card",style:{borderColor:"var(--danger, #c0392b)",marginBottom:"0.75rem"},children:s.jsx("span",{style:{color:"var(--danger, #c0392b)",fontSize:"0.85rem"},children:"Couldn’t load tickets — your session may have expired. Try signing out and back in."})}),p&&o.length===0?s.jsx("p",{style:{color:"var(--text-tertiary)"},children:"Loading..."}):_e.length===0?s.jsx(Em,{icon:"⌕",title:o.length===0?"No tickets in the last 30 days":"No matching tickets",text:o.length===0?"Tickets appear here after an agent uses an authorized tool. Older tickets can be loaded below.":"Try adjusting your search or filters."}):s.jsxs(s.Fragment,{children:[s.jsx("div",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)",marginBottom:"0.75rem"},children:_e.length===o.length?`${o.length} ticket${o.length!==1?"s":""}`:`${_e.length} of ${o.length} tickets`}),s.jsx("div",{className:"timeline",children:_e.map(j=>{const P=j.userId?w[j.userId]:void 0;return s.jsx("div",{className:"timeline-event",children:s.jsx(Xx,{receipt:j,manifests:l,localAuth:j.authorizationId?_[j.authorizationId]:void 0,localUnavailable:ne,signature:z[j.id],grantTitle:j.authorizationId?R[j.authorizationId]:null,ownerLabel:r==="team"&&j.userId?P?`${P.name} (${P.email})`:j.userId:null,spUrl:d,formatDate:Zx,onOpenComplete:()=>q(j)})},j.id)})})]}),Q&&s.jsx(qx,{receipt:Q,onClose:()=>q(null)}),te&&s.jsx("div",{style:{textAlign:"center",marginTop:"1rem"},children:s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:ge,disabled:me,children:me?"Loading…":"Load older"})})]})}const r0={darwin:"a macOS login item",win32:"a Windows scheduled task",linux:"a systemd user service"};function s0(){const[e,t]=u.useState(null),[n,r]=u.useState(!1),[a,o]=u.useState(null),i=u.useCallback(async()=>{try{t(await T.getAutostart())}catch(d){o(d instanceof Error?d.message:"Could not read autostart state")}},[]);u.useEffect(()=>{i()},[i]);const l=u.useCallback(async()=>{if(!(!(e!=null&&e.supported)||n)){r(!0),o(null);try{await T.setAutostart(!e.installed)}catch(d){o(d instanceof Error?d.message:"Failed")}finally{try{t(await T.getAutostart()),o(null)}catch(d){o(d instanceof Error?d.message:"Could not re-read state")}r(!1)}}},[e,n,i]);if(!e)return s.jsxs("div",{className:"card",style:{padding:"1.5rem",marginTop:"2rem"},children:[s.jsx("h2",{style:{fontSize:"1rem",fontWeight:700,margin:0},children:"Keep Suveren running"}),s.jsx("p",{role:a?"alert":void 0,style:{margin:"0.5rem 0 0",fontSize:"0.9rem",color:"var(--text-secondary)"},children:a?`Could not read autostart state: ${a}`:"Checking…"})]});const c=r0[e.platform]??"a login service";return s.jsxs("div",{className:"card",style:{padding:"1.5rem",marginTop:"2rem"},children:[s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",gap:"1rem"},children:[s.jsxs("div",{children:[s.jsx("h2",{style:{fontSize:"1rem",fontWeight:700,margin:0},children:"Keep Suveren running"}),s.jsx("p",{style:{color:"var(--text-secondary)",margin:"0.5rem 0 0",fontSize:"0.9rem"},children:e.supported?s.jsxs(s.Fragment,{children:["Starts automatically when you log in, and restarts if it crashes. Uses ",c," — no admin rights needed."]}):e.reason})]}),e.supported&&s.jsx("button",{type:"button",onClick:()=>void l(),disabled:n,"aria-pressed":e.installed,className:e.installed?"btn btn-secondary":"btn btn-primary",style:{whiteSpace:"nowrap"},children:n?"Working…":e.installed?"Turn off":"Turn on"})]}),e.supported&&s.jsxs("p",{style:{margin:"1rem 0 0",fontSize:"0.85rem",color:"var(--text-tertiary)"},children:["Status: ",s.jsx("strong",{children:e.installed?"On — starts from your next login":"Off"})]}),e.supported&&s.jsxs("p",{style:{margin:"0.5rem 0 0",fontSize:"0.85rem",color:"var(--text-tertiary)"},children:["Turning this on doesn't interrupt the gateway you're using — it takes effect at your next login. After any restart Suveren comes back ",s.jsx("strong",{children:"locked"}),": you enter your API key once to unlock it, because nothing stored on this machine can unlock it for you."]}),a&&s.jsx("p",{role:"alert",style:{margin:"0.75rem 0 0",fontSize:"0.85rem",color:"var(--danger, #c00)"},children:a})]})}function a0(){const[e,t]=u.useState(null),[n,r]=u.useState(!1),[a,o]=u.useState(null),i=u.useCallback(async()=>{try{const c=await T.getGatewaySettings();t(c.desktopNotifications),o(null)}catch(c){o(c instanceof Error?c.message:"Could not read notification setting")}},[]);u.useEffect(()=>{i()},[i]);const l=u.useCallback(async()=>{if(!(e===null||n)){r(!0),o(null);try{const c=await T.setGatewaySettings({desktopNotifications:!e});t(c.desktopNotifications)}catch(c){o(c instanceof Error?c.message:"Failed to save"),await i()}finally{r(!1)}}},[e,n,i]);return e===null?s.jsxs("div",{className:"card",style:{padding:"1.5rem",marginTop:"2rem"},children:[s.jsx("h2",{style:{fontSize:"1rem",fontWeight:700,margin:0},children:"Desktop notifications"}),s.jsx("p",{role:a?"alert":void 0,style:{margin:"0.5rem 0 0",fontSize:"0.9rem",color:"var(--text-secondary)"},children:a?`Could not read the setting: ${a}`:"Checking…"})]}):s.jsxs("div",{className:"card",style:{padding:"1.5rem",marginTop:"2rem"},children:[s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",gap:"1rem"},children:[s.jsxs("div",{children:[s.jsx("h2",{style:{fontSize:"1rem",fontWeight:700,margin:0},children:"Desktop notifications"}),s.jsx("p",{style:{color:"var(--text-secondary)",margin:"0.5rem 0 0",fontSize:"0.9rem"},children:"Tells you something is waiting for review — never what it is, and never with an approve button. Open Suveren to see and decide. At most one notification a minute; the browser tab always shows the count."})]}),s.jsx("button",{type:"button",onClick:()=>void l(),disabled:n,"aria-pressed":e,className:e?"btn btn-secondary":"btn btn-primary",style:{whiteSpace:"nowrap"},children:n?"Saving…":e?"Turn off":"Turn on"})]}),a&&s.jsx("p",{role:"alert",style:{margin:"0.75rem 0 0",fontSize:"0.85rem",color:"var(--danger)"},children:a})]})}const o0={npm:"Checking npm for new releases",docker:"Checking the container registry for new images",dev:"Git checkout — comparing against origin/main, not npm releases",managed:"Checking npm for new releases — managed by your IT"};function i0(){const{version:e,latestVersion:t,updateAvailable:n,installMethod:r}=Ol();return e?s.jsxs("div",{className:"card",style:{padding:"1.5rem",marginTop:"2rem"},children:[s.jsx("h2",{style:{fontSize:"1rem",fontWeight:700,margin:0},children:"Version"}),s.jsxs("p",{style:{margin:"0.5rem 0 0",fontSize:"0.9rem",color:"var(--text-secondary)"},children:["Running ",s.jsx("strong",{children:e}),n&&t?s.jsxs(s.Fragment,{children:[" — ",s.jsx("strong",{children:t})," is available"]}):null]}),s.jsxs("p",{style:{margin:"0.5rem 0 0",fontSize:"0.85rem",color:"var(--text-tertiary)"},children:[o0[r]??"Update checking is unavailable",r==="dev"&&s.jsx(s.Fragment,{children:" — a development checkout is not told about published releases."})]})]}):null}function $i({title:e}){return s.jsxs("span",{className:"it-locked-badge",title:e,children:[s.jsx("span",{className:"lock-icon","aria-hidden":"true",children:"🔒"})," Set by your IT"]})}function xu(e){return e===!0}function l0(){const[e,t]=u.useState(null),[n,r]=u.useState(null);u.useEffect(()=>{let i=!1;return T.getAsPairing().then(l=>{i||t(l)}).catch(l=>{i||r(l instanceof Error?l.message:"Could not read Authority Server info")}),()=>{i=!0}},[]);const a=xu(e==null?void 0:e.asUrlLockedByPolicy),o=xu(e==null?void 0:e.pinTlsLockedByPolicy);return s.jsxs("div",{className:"card",style:{padding:"1.5rem",marginTop:"2rem"},children:[s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",gap:"1rem"},children:[s.jsx("h2",{style:{fontSize:"1rem",fontWeight:700,margin:0},children:"Authority Server"}),a&&s.jsx($i,{})]}),!e&&!n&&s.jsx("p",{style:{margin:"0.5rem 0 0",fontSize:"0.9rem",color:"var(--text-secondary)"},children:"Checking…"}),n&&s.jsx("p",{role:"alert",style:{margin:"0.5rem 0 0",fontSize:"0.9rem",color:"var(--danger, #c00)"},children:n}),e&&s.jsxs(s.Fragment,{children:[s.jsxs("p",{style:{margin:"0.5rem 0 0",fontSize:"0.9rem",color:"var(--text-secondary)"},children:[s.jsx("strong",{children:"URL:"})," ",s.jsx("code",{children:e.asUrl})]}),e.paired&&e.fingerprint?s.jsxs("p",{style:{margin:"0.5rem 0 0",fontSize:"0.9rem",color:"var(--text-secondary)"},children:[s.jsx("strong",{children:"Key fingerprint:"})," ",s.jsx("code",{children:e.fingerprint}),s.jsx("br",{}),s.jsx("span",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)"},children:"Compare this with the fingerprint on the Authority Server's own admin page over a second channel (phone, video call) to confirm this gateway is talking to the right server."})]}):s.jsx("p",{style:{margin:"0.5rem 0 0",fontSize:"0.85rem",color:"var(--text-tertiary)"},children:"Not yet paired — sign in once to pin this server's key."}),(e.tlsPinFingerprint||e.pinTlsEnabled)&&s.jsxs("p",{style:{margin:"0.5rem 0 0",fontSize:"0.9rem",color:"var(--text-secondary)"},children:[s.jsx("strong",{children:"TLS certificate pin:"})," ",o&&s.jsx($i,{title:"TLS pinning is set by your IT policy"})," ",e.tlsPinFingerprint?s.jsx("code",{children:e.tlsPinFingerprint}):s.jsxs("span",{style:{color:"var(--text-tertiary)"},children:["not yet captured — this URL has no recorded pairing over TLS",e.pinTlsEnabled?"; sign in to establish one (re-pairing required)":""]}),s.jsx("br",{}),s.jsxs("span",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)"},children:[e.pinTlsEnabled?s.jsxs(s.Fragment,{children:["TLS pinning is ON",o?s.jsx(s.Fragment,{children:", set by your organization's IT policy"}):s.jsxs(s.Fragment,{children:[" (",s.jsx("code",{children:"config set pin-tls on"}),")"]}),". Every connection to the Authority Server must present this certificate's public key, or the gateway refuses it and locks."]}):s.jsxs(s.Fragment,{children:["Captured at sign-in; not currently enforced",o?s.jsx(s.Fragment,{children:" — controlled by your organization's IT policy on this computer"}):s.jsxs(s.Fragment,{children:[" (",s.jsx("code",{children:"config set pin-tls on"})," to require it on every connection)"]}),"."]})," ","A certificate renewal with the SAME key keeps this pin; a NEW key needs re-pairing."]})]}),a?s.jsx("p",{style:{margin:"0.75rem 0 0",fontSize:"0.8rem",color:"var(--text-tertiary)"},children:"This Authority Server URL is set by your organization's IT policy and cannot be changed from this computer. Contact your IT administrator if it needs to change."}):s.jsxs("p",{style:{margin:"0.75rem 0 0",fontSize:"0.8rem",color:"var(--text-tertiary)"},children:["To point this gateway at a different Authority Server:"," ",s.jsx("code",{children:"suveren-gateway config set as-url <url>"}),", then restart. Changing it ends the current sign-in and clears cached mandates — you sign in again against the new server."]})]})]})}function c0(e){if(!e||typeof e!="object")return{simulation:null,locked:!1};const t=Array.isArray(e.policyLocked)&&e.policyLocked.includes("simulation");return{simulation:typeof e.simulation=="boolean"?e.simulation:null,locked:t}}function u0(){const[e,t]=u.useState({simulation:null,locked:!1});return u.useEffect(()=>{let n=!1;return fetch("/health").then(r=>r.json()).then(r=>{n||t(c0(r))}).catch(()=>{}),()=>{n=!0}},[]),e}function d0(){const{simulation:e,locked:t}=u0();return t?s.jsxs("div",{className:"card",style:{padding:"1.5rem",marginTop:"2rem"},children:[s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",gap:"1rem"},children:[s.jsxs("div",{children:[s.jsx("h2",{style:{fontSize:"1rem",fontWeight:700,margin:0},children:"Simulation mode"}),s.jsxs("p",{style:{color:"var(--text-secondary)",margin:"0.5rem 0 0",fontSize:"0.9rem"},children:['Blocks every real connector without a manifest "simulation" marker.',e!==null&&s.jsxs(s.Fragment,{children:[" ","Currently ",s.jsx("strong",{children:e?"ON":"OFF"}),e?" — real systems are not reachable from this gateway.":"."]})]})]}),s.jsx($i,{})]}),s.jsxs("p",{style:{margin:"1rem 0 0",fontSize:"0.78rem",color:"var(--text-tertiary)"},children:["Simulation mode is set by your organization's IT policy",e!==null?` (currently ${e?"on":"off"})`:""," and cannot be changed from this computer — not even from the command line."]})]}):null}const f0={ollama:{provider:"ollama",endpoint:"http://localhost:11434",models:["gemma4:e4b","gemma4:e2b","gemma4:26b","gemma4:31b","llama3.2","llama3.1","mistral","qwen2.5"]},openrouter:{provider:"openai-compatible",endpoint:"https://openrouter.ai/api/v1",models:["google/gemma-4-31b-it","qwen/qwen3.6-plus:free","stepfun/step-3.5-flash:free","google/gemini-2.5-flash","openai/gpt-4o-mini","anthropic/claude-haiku-4"]},openai:{provider:"openai-compatible",endpoint:"https://api.openai.com/v1",models:["gpt-4o-mini","gpt-4o","o3-mini"]},groq:{provider:"openai-compatible",endpoint:"https://api.groq.com/openai/v1",models:["llama-3.1-8b-instant","llama-3.3-70b-versatile","gemma2-9b-it"]},together:{provider:"openai-compatible",endpoint:"https://api.together.xyz/v1",models:["meta-llama/Llama-3-8b-chat-hf","meta-llama/Llama-3-70b-chat-hf"]}},_r=["AI Assistant","Authority Server","This computer","Security","Version"],Ar={fontSize:"1rem",fontWeight:700,marginBottom:"1rem"};function m0(){const[e,t]=u.useState(""),[n,r]=u.useState("openrouter"),[a,o]=u.useState("openai-compatible"),[i,l]=u.useState("https://openrouter.ai/api/v1"),[c,d]=u.useState("google/gemma-4-31b-it"),[f,p]=u.useState(""),[m,w]=u.useState(!1),[v,x]=u.useState(!1),[k,g]=u.useState(!1),[h,y]=u.useState(null),[S,b]=u.useState([]),[N,C]=u.useState(!1),[I,E]=u.useState(null),[$,U]=u.useState(""),V=u.useCallback(z=>{t(z),setTimeout(()=>t(""),3e3)},[]),J=u.useCallback(async(z,W,R)=>{C(!0),E(null);try{const F=await T.aiModels({provider:z,endpoint:W,...R?{apiKey:R}:{}});F.ok&&F.models.length>0?(b(F.models),E(`${F.models.length} models available`)):(b([]),E(F.message||"No models returned — using defaults"))}catch(F){b([]),E(F instanceof Error?F.message:"Failed to load models")}finally{C(!1)}},[]),D=u.useCallback(async()=>{try{const z=await T.getCredential("ai-config");if(w(z.configured),z.configured&&z.fields){const W=z.fields.provider||"openai-compatible",R=z.fields.endpoint||"";z.fields.provider&&o(W),z.fields.endpoint&&l(R),z.fields.model&&d(z.fields.model),R.includes("openai.com")?r("openai"):R.includes("groq.com")?r("groq"):R.includes("together.xyz")?r("together"):R.includes("openrouter.ai")?r("openrouter"):r("ollama"),R&&J(W,R)}}catch{}},[J]);u.useEffect(()=>{D()},[D]);const _=z=>{r(z),b([]),E(null),U("");const W=f0[z];W&&(o(W.provider),l(W.endpoint),d(""),J(W.provider,W.endpoint,f||void 0))},B=()=>J(a,i,f||void 0),ne=async()=>{x(!0);try{await T.setCredential("ai-config",{provider:a,endpoint:i,model:c,...f?{apiKey:f}:{}}),w(!0),V("AI configuration saved!")}catch{V("Failed to save AI config")}finally{x(!1)}},L=async()=>{g(!0),y(null);try{const z=await T.aiTest({provider:a,endpoint:i,model:c,...f?{apiKey:f}:{}});y(z.ok?`OK: ${z.message}`:`Failed: ${z.message}`)}catch(z){y(`Error: ${z instanceof Error?z.message:"Unknown"}`)}finally{g(!1)}};return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"page-header",children:[s.jsx("h1",{className:"page-title",children:"Settings"}),s.jsx("p",{className:"page-subtitle",children:"Your AI assistant, the connection to your Authority Server, security and version."})]}),e&&s.jsx("div",{className:"alert alert-success",children:e}),s.jsxs("section",{style:{marginBottom:"2rem"},children:[s.jsx("h2",{style:Ar,children:_r[0]}),s.jsx("p",{style:{fontSize:"0.85rem",color:"var(--text-secondary)",marginBottom:"1rem"},children:"Advisory AI to help you think through intent when giving mandates."}),s.jsxs("div",{className:"card",children:[s.jsx("h3",{className:"card-title",children:"Configuration"}),s.jsx("p",{style:{fontSize:"0.85rem",color:"var(--text-secondary)",marginBottom:"1rem"},children:"Connect a trusted AI model that has access to your intent — problem, objective, and tradeoffs — to help you think through mandates. Keys are encrypted in your vault."}),m&&s.jsxs("div",{className:"status-banner status-banner-success",style:{marginBottom:"1rem",fontSize:"0.8rem"},children:[s.jsx("span",{className:"status-banner-icon",children:"✓"}),s.jsx("span",{className:"status-banner-text",children:"AI configured"})]}),s.jsxs("div",{className:"form-group",style:{marginBottom:"0.75rem"},children:[s.jsx("label",{className:"form-label",children:"Provider Preset"}),s.jsxs("select",{className:"form-input",value:n,onChange:z=>_(z.target.value),children:[s.jsx("option",{value:"openrouter",children:"OpenRouter (recommended)"}),s.jsx("option",{value:"ollama",children:"Ollama (local)"}),s.jsx("option",{value:"openai",children:"OpenAI"}),s.jsx("option",{value:"groq",children:"Groq"}),s.jsx("option",{value:"together",children:"Together"})]})]}),s.jsxs("div",{className:"form-group",style:{marginBottom:"0.75rem"},children:[s.jsxs("label",{className:"form-label",children:["API Key ",a==="ollama"?"(not needed for Ollama)":"(required to load models)"]}),s.jsx("input",{className:"form-input",type:"password",name:"ai-provider-api-key-credential-top",autoComplete:"new-password",value:f,onChange:z=>p(z.target.value),onBlur:()=>{f.trim()&&J(a,i,f.trim())},placeholder:m?"••••••••••••••••":"sk-... (not needed for Ollama)"}),s.jsx("p",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",margin:"0.375rem 0 0"},children:"Each provider uses its own key — paste it and the model list loads automatically."})]}),s.jsxs("div",{className:"form-group",style:{marginBottom:"0.75rem"},children:[s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[s.jsx("label",{className:"form-label",children:"Model"}),s.jsx("button",{type:"button",className:"btn btn-ghost",style:{fontSize:"0.75rem",padding:"0.125rem 0.5rem"},onClick:B,disabled:N,title:"Re-fetch the model list from the provider",children:N?"Loading…":"↻ Refresh"})]}),S.length===0?s.jsx("div",{className:"form-input",style:{display:"flex",alignItems:"center",minHeight:"2.5rem",color:"var(--text-secondary)",fontSize:"0.85rem"},children:N?"Loading models…":a==="ollama"?"Start Ollama locally, then ↻ Refresh to load models.":"Enter a valid API key above to load available models."}):(()=>{const z=S,W=z.includes(c),R=z.length>12,F=$.trim().toLowerCase();let Q=F?z.filter(q=>q.toLowerCase().includes(F)):z;return W&&!Q.includes(c)&&(Q=[c,...Q]),s.jsxs(s.Fragment,{children:[R&&s.jsx("input",{className:"form-input",value:$,onChange:q=>U(q.target.value),placeholder:"Filter models… (e.g. kimi)",style:{marginBottom:"0.375rem"}}),s.jsxs("select",{className:"form-input",value:W?c:"__unset__",onChange:q=>d(q.target.value==="__unset__"?"":q.target.value),children:[s.jsx("option",{value:"__unset__",disabled:!0,children:"Select a model…"}),Q.map(q=>s.jsx("option",{value:q,children:q},q)),F&&Q.length===0&&s.jsxs("option",{value:"__unset__",disabled:!0,children:["No models match “",$,"”"]})]})]})})(),I&&s.jsx("p",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",margin:"0.375rem 0 0"},children:I})]}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem",alignItems:"center"},children:[s.jsx("button",{className:"btn btn-primary",onClick:ne,disabled:v||!c.trim(),title:c.trim()?void 0:"Select a model first",children:v?"Saving...":"Save & Encrypt"}),m&&s.jsx("button",{className:"btn btn-ghost",onClick:L,disabled:k,children:k?"Testing...":"Test Connection"})]}),h&&s.jsx("div",{className:`alert ${h.startsWith("OK")?"alert-success":"alert-error"}`,style:{marginTop:"0.75rem"},children:h})]}),s.jsx(p0,{})]}),s.jsxs("section",{style:{marginBottom:"2rem"},children:[s.jsx("h2",{style:Ar,children:_r[1]}),s.jsx(l0,{})]}),s.jsxs("section",{style:{marginBottom:"2rem"},children:[s.jsx("h2",{style:Ar,children:_r[2]}),s.jsx(s0,{}),s.jsx(a0,{}),s.jsx(d0,{})]}),s.jsxs("section",{style:{marginBottom:"2rem"},children:[s.jsx("h2",{style:Ar,children:_r[3]}),s.jsx("div",{className:"card",style:{padding:"1.5rem"},children:s.jsxs("div",{style:{fontSize:"0.85rem",color:"var(--text-secondary)",lineHeight:1.7},children:[s.jsxs("div",{style:{marginBottom:"1rem"},children:[s.jsx("div",{style:{fontWeight:600,color:"var(--text-primary)",marginBottom:"0.375rem"},children:"What the gateway protects"}),s.jsxs("ul",{style:{margin:0,paddingLeft:"1.25rem"},children:[s.jsx("li",{children:"Every tool call verified against your mandate bounds"}),s.jsx("li",{children:"Credentials never exposed to agents through MCP"}),s.jsx("li",{children:"Every action produces a signed ticket"})]})]}),s.jsxs("div",{children:[s.jsx("div",{style:{fontWeight:600,color:"var(--text-primary)",marginBottom:"0.375rem"},children:"Your responsibility"}),s.jsxs("ul",{style:{margin:0,paddingLeft:"1.25rem"},children:[s.jsx("li",{children:"If your AI agent has full access to your computer, it could bypass the gateway"}),s.jsx("li",{children:"For best security, run agents in sandboxed environments"}),s.jsx("li",{children:"The gateway secures what agents do through tools — not what they do on your machine"})]})]})]})})]}),s.jsxs("section",{children:[s.jsx("h2",{style:Ar,children:_r[4]}),s.jsx(i0,{})]})]})}function p0(){const[e,t]=u.useState(null),[n,r]=u.useState({intent:"",context:""}),[a,o]=u.useState(null),[i,l]=u.useState(null),[c,d]=u.useState(null),[f,p]=u.useState(!1),m=u.useCallback(async()=>{if(!f)try{const x=await T.getAIPrompts();t(x),r({intent:x.intent.current,context:x.context.current}),p(!0)}catch(x){l(x instanceof Error?x.message:"Failed to load prompts")}},[f]),w=async x=>{if(e){o(x),l(null);try{const k=n[x],g=k.trim()===e[x].default.trim()?"":k;await T.setAIPrompt(x,g);const h=await T.getAIPrompts();t(h),r({intent:h.intent.current,context:h.context.current}),d(x),setTimeout(()=>d(null),2e3)}catch(k){l(k instanceof Error?k.message:"Save failed")}finally{o(null)}}},v=async x=>{if(confirm(`Revert ${x} prompt to the built-in default?`)){o(x),l(null);try{await T.setAIPrompt(x,"");const k=await T.getAIPrompts();t(k),r({intent:k.intent.current,context:k.context.current})}catch(k){l(k instanceof Error?k.message:"Revert failed")}finally{o(null)}}};return s.jsxs("details",{className:"card",style:{padding:"1.5rem",marginTop:"1rem"},onToggle:x=>{x.currentTarget.open&&m()},children:[s.jsx("summary",{style:{fontSize:"1rem",fontWeight:700,cursor:"pointer",listStyle:"revert",userSelect:"none"},children:"Advanced — AI assistant prompts"}),s.jsx("p",{style:{fontSize:"0.85rem",color:"var(--text-secondary)",margin:"0.75rem 0 1rem 0",lineHeight:1.55},children:"These are the system prompts the AI assistant sees when helping you write Intent (per-mandate) or Context (your standing-orders brief). Edit with care — changes apply on the next chat turn."}),i&&s.jsx("div",{className:"alert alert-error",style:{marginBottom:"0.75rem"},children:i}),!f&&!i&&s.jsx("p",{style:{color:"var(--text-muted)",fontSize:"0.85rem"},children:"Loading prompts…"}),e&&s.jsxs(s.Fragment,{children:[s.jsx(wu,{kind:"intent",label:"Intent — per-mandate",description:"Used on the Intent gate when creating a new mandate.",state:e.intent,draft:n.intent,onChange:x=>r(k=>({...k,intent:x})),onSave:()=>w("intent"),onRevert:()=>v("intent"),saving:a==="intent",justSaved:c==="intent"}),s.jsx(wu,{kind:"context",label:"Context — standing-orders brief",description:"Used on the Brief page when refining your context.md.",state:e.context,draft:n.context,onChange:x=>r(k=>({...k,context:x})),onSave:()=>w("context"),onRevert:()=>v("context"),saving:a==="context",justSaved:c==="context"})]})]})}function wu({kind:e,label:t,description:n,state:r,draft:a,onChange:o,onSave:i,onRevert:l,saving:c,justSaved:d}){const f=a!==r.current;return s.jsxs("section",{style:{marginBottom:"1.5rem"},children:[s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"baseline",marginBottom:"0.25rem",gap:"1rem",flexWrap:"wrap"},children:[s.jsxs("div",{children:[s.jsx("div",{style:{fontWeight:600,fontSize:"0.9rem"},children:t}),s.jsx("div",{style:{fontSize:"0.78rem",color:"var(--text-secondary)"},children:n})]}),r.overridden&&s.jsx("span",{style:{fontSize:"0.7rem",color:"var(--accent)",fontWeight:600,textTransform:"uppercase",letterSpacing:"0.05em"},children:"Custom"})]}),s.jsx("textarea",{className:"form-textarea",value:a,onChange:p=>o(p.target.value),rows:12,spellCheck:!1,style:{width:"100%",fontFamily:"'SF Mono', Monaco, 'Cascadia Code', monospace",fontSize:"0.82rem",lineHeight:1.55,resize:"vertical",minHeight:"14rem",marginTop:"0.5rem"},"aria-label":`${t} system prompt`}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem",alignItems:"center",marginTop:"0.5rem",flexWrap:"wrap"},children:[s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:i,disabled:c||!f,children:c?"Saving…":"Save"}),r.overridden&&s.jsx("button",{type:"button",className:"btn btn-ghost btn-sm",onClick:l,disabled:c,title:"Discard the override and use the built-in default",children:"Revert to default"}),d&&s.jsx("span",{style:{fontSize:"0.78rem",color:"var(--success)"},children:"Saved"}),f&&!c&&!d&&s.jsx("span",{style:{fontSize:"0.78rem",color:"var(--text-muted)"},children:"Unsaved changes"})]}),s.jsxs("details",{style:{marginTop:"0.5rem"},children:[s.jsx("summary",{style:{fontSize:"0.78rem",color:"var(--text-muted)",cursor:"pointer"},children:"Show built-in default"}),s.jsx("pre",{style:{marginTop:"0.5rem",padding:"0.75rem 1rem",background:"var(--bg-main)",border:"1px solid var(--border)",borderRadius:"0.5rem",fontSize:"0.78rem",lineHeight:1.55,whiteSpace:"pre-wrap",maxHeight:"20rem",overflowY:"auto"},children:r.default})]}),s.jsx("span",{style:{display:"none"},children:e})]})}function h0(e){return e.proposalId?"review":"automatic"}function Su(e,t,n={}){const r=n.status??"pending",a=n.includeAutonomous??!1,o=[];for(const i of e)r==="pending"&&i.status!=="pending"||n.profile&&i.profileId!==n.profile||o.push({kind:"proposal",id:i.id,sortTimestamp:i.createdAt,commitmentMode:"review",profileId:i.profileId,proposal:i});if(r==="all")for(const i of t){const l=h0(i);!a&&l==="automatic"||n.profile&&i.profileId!==n.profile||o.push({kind:"receipt",id:i.id,sortTimestamp:i.timestamp,commitmentMode:l,profileId:i.profileId,receipt:i})}return o.sort((i,l)=>l.sortTimestamp-i.sortTimestamp),typeof n.limit=="number"&&n.limit>0?o.slice(0,n.limit):o}const g0=["https://","http://"];function Tm(e,t){return e!=null&&e.length?e.flatMap(n=>{const r=n.template.replace(/\{(\w+)\}/g,(a,o)=>{const i=t[o];return typeof i=="string"||typeof i=="number"?String(i):"\0"});return r.includes("\0")||/\{|\}/.test(r)?[]:g0.some(a=>r.toLowerCase().startsWith(a))?[{label:n.label,href:r,description:n.description}]:[]}):[]}function y0({profileId:e}){return s.jsx("span",{className:"profile-badge",children:$e(e)})}function Im(e,t){const n=e-Math.floor(t/1e3);if(n<=0)return{label:"expired",urgent:!1,expired:!0};const r=Math.floor(n/86400),a=Math.floor(n%86400/3600),o=Math.floor(n%3600/60);let i;return r>0?i=`expires in ${r}d ${a}h`:a>0?i=`expires in ${a}h ${o}m`:i=`expires in ${Math.max(1,o)}m`,{label:i,urgent:n<2*3600,expired:!1}}const v0={pending:"Pending",committed:"Approved",executed:"Executed",rejected:"Rejected",expired:"Expired"},x0={pending:"status-pending",committed:"status-active",executed:"status-active",rejected:"status-revoked",expired:"status-expired"};function w0(e){const t=Date.now()-e*1e3,n=t/36e5;return n<48?n<1?`${Math.max(1,Math.round(t/6e4))}m ago`:`${Math.round(n)}h ago`:new Date(e*1e3).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function S0(e){return e.split("__").pop()??e}function j0(e){const t=e.toLowerCase();return t.includes("delete")||t.includes("refund")||t.includes("cancel")||t.includes("revoke")}const k0=new Set(["apiKey","api_key","accessToken","access_token","password","secret","signature","_imagePreview"]),b0=/^(image|img|photo|picture|thumbnail)(_?url)?$/i;function C0(e,t){return typeof t!="string"?!1:/^data:image\//i.test(t)?!0:b0.test(e)?/^https?:\/\//.test(t):/^https?:\/\/.+\.(jpe?g|png|gif|webp|svg|avif)(\?|$)/i.test(t)}function Li(e){if(e==null)return"—";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);if(Array.isArray(e))return e.map(t=>Li(t)).join(", ");try{return JSON.stringify(e,null,2)}catch{return String(e)}}function ju({item:e,onApprove:t,onReject:n,resolving:r,proposalLinks:a}){const o=e.kind==="proposal",i=o?e.proposal.status:"executed",l=o?e.proposal.tool:e.receipt.action,c=S0(l),d=j0(l),f=o?e.proposal.toolArgs:null,p=o?e.proposal.executionContext:e.receipt.executionContext,m=o?null:e.receipt.cumulativeState,w=o?Tm(a,e.proposal.toolArgs):[],v=f?Object.entries(f).filter(([k])=>!k0.has(k)):[],x=Object.entries(p??{});return s.jsxs("div",{className:"card",children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem",marginBottom:"0.75rem",flexWrap:"wrap"},children:[s.jsx(y0,{profileId:e.profileId}),s.jsx("code",{style:{fontSize:"0.85rem"},children:c}),e.commitmentMode==="automatic"&&s.jsx("span",{style:{fontSize:"0.7rem",color:"var(--text-tertiary)",textTransform:"uppercase",letterSpacing:"0.04em"},children:"autonomous"}),s.jsxs("span",{style:{marginLeft:"auto",display:"flex",alignItems:"center",gap:"0.5rem"},children:[o&&i==="pending"&&(()=>{const k=Im(e.proposal.expiresAt,Date.now());return s.jsx("span",{style:{fontSize:"0.72rem",color:k.urgent?"var(--warning)":"var(--text-tertiary)",fontWeight:k.urgent?600:400,whiteSpace:"nowrap"},children:k.label})})(),s.jsx("span",{className:`status-badge ${x0[i]}`,children:v0[i]}),s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-tertiary)"},children:w0(e.sortTimestamp)})]})]}),d&&s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.4rem",fontSize:"0.8rem",color:"var(--warning)",background:"var(--bg-main)",border:"1px solid var(--border)",borderRadius:"0.375rem",padding:"0.4rem 0.6rem",marginBottom:"0.75rem"},children:[s.jsx("span",{children:"⚠"}),s.jsx("span",{children:"Irreversible action"})]}),o&&typeof(f==null?void 0:f._imagePreview)=="string"&&s.jsxs("div",{style:{marginBottom:"0.75rem"},children:[s.jsx("div",{style:{fontSize:"0.7rem",fontWeight:600,color:"var(--text-tertiary)",textTransform:"uppercase",letterSpacing:"0.04em",marginBottom:"0.35rem"},children:"Preview"}),s.jsx("img",{src:f._imagePreview,alt:typeof(f==null?void 0:f.altText)=="string"?f.altText:"local image preview",style:{display:"block",maxWidth:"100%",maxHeight:"240px",borderRadius:"0.375rem",border:"1px solid var(--border)"}})]}),w.length>0&&s.jsx("div",{style:{marginBottom:"0.75rem",display:"flex",gap:"0.5rem",flexWrap:"wrap"},children:w.map(k=>s.jsxs("a",{href:k.href,target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm",style:{textDecoration:"none"},title:k.description??k.href,children:[k.label," ↗"]},k.label))}),o&&v.length>0&&s.jsxs("div",{style:{marginBottom:"0.75rem"},children:[s.jsx("div",{style:{fontSize:"0.7rem",fontWeight:600,color:"var(--text-tertiary)",textTransform:"uppercase",letterSpacing:"0.04em",marginBottom:"0.35rem"},children:"Arguments"}),s.jsx("dl",{style:{display:"grid",gridTemplateColumns:"max-content 1fr",gap:"0.2rem 0.75rem",fontSize:"0.85rem",margin:0},children:v.map(([k,g])=>s.jsxs(u.Fragment,{children:[s.jsx("dt",{style:{color:"var(--text-tertiary)",whiteSpace:"nowrap",alignSelf:"start"},children:k}),s.jsx("dd",{style:{color:"var(--text-primary)",margin:0,wordBreak:"break-word",whiteSpace:"pre-wrap"},children:C0(k,g)?s.jsx("img",{src:g,alt:typeof(f==null?void 0:f.altText)=="string"?f.altText:k,style:{display:"block",maxWidth:"100%",maxHeight:"240px",borderRadius:"0.375rem",border:"1px solid var(--border)"},onError:h=>{const y=h.currentTarget,S=y.parentElement;if(!S)return;y.style.display="none";const b=document.createElement("span");b.textContent=g,b.style.color="var(--text-tertiary)",S.appendChild(b)}}):Li(g)})]},k))})]}),x.length>0&&s.jsx("div",{style:{marginBottom:"0.75rem",fontSize:"0.8rem",color:"var(--text-secondary)"},children:x.map(([k,g])=>`${k}=${Li(g)}`).join(" · ")}),m&&s.jsxs("div",{style:{fontSize:"0.75rem",color:"var(--text-tertiary)",marginBottom:"0.5rem"},children:["After this action · today: ",m.daily.count," action",m.daily.count===1?"":"s",m.daily.amount>0?`, ${m.daily.amount}`:""," · ","this month: ",m.monthly.count,m.monthly.amount>0?`, ${m.monthly.amount}`:""]}),o&&i==="pending"&&s.jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[s.jsx("button",{className:"btn btn-primary",onClick:()=>t==null?void 0:t(e.id),disabled:r,children:r?"Approving…":"Approve"}),s.jsx("button",{className:"btn btn-ghost",style:{color:"var(--danger)"},onClick:()=>n==null?void 0:n(e.id),disabled:r,children:"Reject"})]}),s.jsxs("div",{style:{marginTop:"0.5rem",fontSize:"0.7rem",color:"var(--text-tertiary)"},children:[o?"Proposal":"Ticket",": ",e.id]})]})}const N0=new Set(["apiKey","api_key","accessToken","access_token","password","secret","signature","_imagePreview"]);function Mi(e){if(e==null)return"—";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);if(Array.isArray(e))return e.map(t=>Mi(t)).join(", ");try{return JSON.stringify(e,null,2)}catch{return String(e)}}function E0(e){const t=Date.now()-e*1e3,n=Math.floor(t/6e4);if(n<60)return`${Math.max(1,n)}m ago`;const r=Math.floor(t/36e5);return r<48?`${r}h ago`:`${Math.floor(r/24)}d ago`}function T0({proposal:e,currentUserId:t,onAction:n,onMessage:r,proposalLinks:a}){const[o,i]=u.useState(!1),[l,c]=u.useState(!1),[d,f]=u.useState(null),[p,m]=u.useState(!1),[w,v]=u.useState(null),[x,k]=u.useState(!1),g=e.tool.split("__").pop()??e.tool,h=Object.entries(e.toolArgs).filter(([_])=>!N0.has(_)),y=Object.entries(e.executionContext),S=Tm(a,e.toolArgs),b=e.pendingApprovers??[],N=e.approvedBy??{},C=Object.keys(N).length,I=b.filter(_=>!(_ in N)).length,E=t in N,$=async()=>{if(d===null){m(!0),v(null);try{const _=await T.getAttestationIntent(e.authorizationId);if(!_){v("Intent not available or you are not an authorized approver.");return}const B=await T.decryptIntent({intentCiphertext:_.intentCiphertext,encryptedKey:_.encryptedKey,approverId:t});f(B)}catch(_){v(_ instanceof Error?_.message:"Failed to decrypt intent")}finally{m(!1)}}},U=async()=>{x?k(!1):(k(!0),await $())},V=async()=>{i(!0),r("");try{await T.approveProposal(e.id);try{if(d===null){const _=await T.getAttestationIntent(e.authorizationId);if(_){const B=await T.decryptIntent({intentCiphertext:_.intentCiphertext,encryptedKey:_.encryptedKey,approverId:t});f(B),await T.storeApprovedIntent(e.authorizationId,B)}}else await T.storeApprovedIntent(e.authorizationId,d)}catch{}r(`Approved. ${I-1>0?`${I-1} more approver(s) still needed.`:"All approvers signed off — action is ready to execute."}`),n()}catch(_){r(_ instanceof Error?_.message:"Approval failed")}finally{i(!1)}},J=async()=>{const _=prompt("Rejection reason (optional):");if(_!==null){c(!0),r("");try{await T.rejectProposal(e.id,_||void 0),r("Action rejected."),n()}catch(B){r(B instanceof Error?B.message:"Rejection failed")}finally{c(!1)}}},D=o||l;return s.jsxs("div",{className:"card",children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem",marginBottom:"0.5rem",flexWrap:"wrap"},children:[s.jsx("span",{style:{fontWeight:600,fontSize:"0.9rem"},children:$e(e.profileId)}),s.jsx("span",{style:{fontSize:"0.65rem",padding:"0.15rem 0.4rem",borderRadius:"0.25rem",background:"var(--accent-subtle)",color:"var(--accent)",fontWeight:600},children:"Above cap"}),s.jsxs("span",{style:{marginLeft:"auto",display:"flex",alignItems:"center",gap:"0.5rem"},children:[(()=>{const _=Im(e.expiresAt,Date.now());return s.jsx("span",{style:{fontSize:"0.72rem",color:_.urgent?"var(--warning)":"var(--text-tertiary)",fontWeight:_.urgent?600:400,whiteSpace:"nowrap"},children:_.label})})(),s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-tertiary)"},children:E0(e.createdAt)})]})]}),s.jsxs("div",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)",marginBottom:"0.5rem"},children:[C," of ",b.length," approver",b.length===1?"":"s"," signed off",b.map(_=>{const B=_ in N;return s.jsxs("span",{style:{marginLeft:"0.5rem",color:B?"var(--success, green)":"var(--text-tertiary)"},children:[B?"✓":"○"," ",_===t?"You":_]},_)})]}),s.jsxs("div",{style:{marginBottom:"0.5rem"},children:[s.jsx("div",{style:{fontSize:"0.7rem",fontWeight:600,color:"var(--text-tertiary)",textTransform:"uppercase",letterSpacing:"0.04em",marginBottom:"0.25rem"},children:"Proposed action"}),s.jsx("code",{style:{fontSize:"0.85rem"},children:g})]}),S.length>0&&s.jsx("div",{style:{marginBottom:"0.75rem",display:"flex",gap:"0.5rem",flexWrap:"wrap"},children:S.map(_=>s.jsxs("a",{href:_.href,target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm",style:{textDecoration:"none"},title:_.description??_.href,children:[_.label," ↗"]},_.label))}),h.length>0&&s.jsxs("div",{style:{marginBottom:"0.75rem"},children:[s.jsx("div",{style:{fontSize:"0.7rem",fontWeight:600,color:"var(--text-tertiary)",textTransform:"uppercase",letterSpacing:"0.04em",marginBottom:"0.25rem"},children:"Arguments"}),s.jsx("dl",{style:{display:"grid",gridTemplateColumns:"max-content 1fr",gap:"0.2rem 0.75rem",fontSize:"0.85rem",margin:0},children:h.map(([_,B])=>s.jsxs(u.Fragment,{children:[s.jsx("dt",{style:{color:"var(--text-tertiary)",whiteSpace:"nowrap",alignSelf:"start"},children:_}),s.jsx("dd",{style:{color:"var(--text-primary)",margin:0,wordBreak:"break-word",whiteSpace:"pre-wrap"},children:Mi(B)})]},_))})]}),y.length>0&&s.jsx("div",{style:{fontSize:"0.8rem",color:"var(--text-secondary)",marginBottom:"0.5rem"},children:y.map(([_,B])=>`${_}=${Mi(B)}`).join(" · ")}),s.jsxs("div",{style:{marginBottom:"0.75rem"},children:[s.jsxs("button",{className:"btn btn-ghost btn-sm",style:{padding:"0.2rem 0",fontSize:"0.75rem"},onClick:U,disabled:p,children:[x?"▲ Hide intent":"▼ Show intent",p&&" (decrypting...)"]}),x&&s.jsx("div",{style:{marginTop:"0.5rem",padding:"0.75rem",background:"var(--bg-main)",borderRadius:"0.375rem",border:"1px solid var(--border)"},children:w?s.jsx("p",{style:{color:"var(--danger)",fontSize:"0.8rem",margin:0},children:w}):d!==null?s.jsx("p",{style:{fontSize:"0.85rem",margin:0,whiteSpace:"pre-wrap",color:"var(--text-primary)"},children:d}):s.jsx("p",{style:{color:"var(--text-tertiary)",fontSize:"0.8rem",margin:0},children:"No intent available for this mandate."})})]}),!E&&s.jsxs("div",{style:{display:"flex",gap:"0.5rem",marginTop:"0.25rem"},children:[s.jsx("button",{className:"btn btn-primary",onClick:V,disabled:D,children:o?"Approving...":"Approve"}),s.jsx("button",{className:"btn btn-ghost",style:{color:"var(--danger)"},onClick:J,disabled:D,children:l?"Rejecting...":"Reject"})]}),E&&s.jsx("p",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)",marginTop:"0.25rem"},children:"You approved this action. Waiting on other approvers."}),s.jsxs("div",{style:{marginTop:"0.5rem",fontSize:"0.7rem",color:"var(--text-tertiary)"},children:["Proposal: ",e.id]})]})}function I0(){const{domain:e,user:t}=Fe(),n=(t==null?void 0:t.id)??"",[r,a]=u.useState("awaiting-me"),[o,i]=u.useState([]),[l,c]=u.useState([]),[d,f]=u.useState(!0),[p,m]=u.useState(""),w=u.useCallback(async()=>{try{const A=await T.getProposalsForApprover();i(A)}catch{}finally{f(!1)}},[]);fe("proposal-added",w),fe("proposal-approved",w),fe("proposal-rejected",w),fe("proposal-resolved",w),Pt(w,3e4);const[v,x]=u.useState([]),k=u.useCallback(async()=>{try{const A=await T.getProposals(e||"owner");x(A)}catch{}},[e]);fe("proposal-added",k),fe("proposal-approved",k),fe("proposal-rejected",k),fe("proposal-resolved",k),Pt(k,3e4,e);const g=u.useMemo(()=>v.filter(A=>{var X;return A.status==="pending"&&(((X=A.pendingApprovers)==null?void 0:X.length)??0)===0}),[v]),h=u.useMemo(()=>Su(g,[],{status:"pending"}),[g]),[y,S]=u.useState([]),b=u.useCallback(async()=>{if(n)try{const X=(await T.getProposals(e||"owner")).filter(ae=>ae.status==="pending"&&ae.pendingApprovers&&ae.pendingApprovers.includes(n)&&ae.approvedBy&&n in ae.approvedBy);S(X)}catch{}},[n,e]);fe("proposal-approved",b),fe("proposal-rejected",b),Pt(b,3e4,`${n}:${e}`),u.useEffect(()=>{T.getIntegrationManifests().then(A=>c(A.manifests??[])).catch(()=>{})},[]);const N=A=>{var X;return(X=l.find(ae=>ae.id===A.split("__")[0]))==null?void 0:X.proposalLinks};u.useEffect(()=>{w(),k(),b()},[]);const[C,I]=u.useState([]),[E,$]=u.useState([]),[U,V]=u.useState(!0),[J,D]=u.useState(null),[_,B]=u.useState(""),[ne,L]=u.useState("pending"),[z,W]=u.useState(null),[R,F]=u.useState(!1),Q=u.useCallback(async()=>{try{const{proposals:A,receipts:X}=await T.getThread({domain:e,status:ne,sinceDays:7});I(A),$(X)}catch{}finally{V(!1)}},[e,ne]);Pt(Q,3e4,`${e}:${ne}`);const q=async(A,X)=>{D(A),B("");try{const ae=e||"owner",ge=await T.resolveProposal(A,X,ae);B(X==="commit"?`Action approved. Status: ${ge.status}`:"Action rejected."),await Promise.all([Q(),k()])}catch(ae){B(ae instanceof Error?ae.message:"Failed")}finally{D(null)}},te=u.useMemo(()=>{const A=new Set;for(const X of C)A.add(X.profileId);for(const X of E)A.add(X.profileId);return Array.from(A).sort()},[C,E]),ce=u.useMemo(()=>Su(C,E,{status:ne,profile:z??void 0,includeAutonomous:R}),[C,E,ne,z,R]),me=u.useCallback(()=>{w(),b()},[w,b]),ee=u.useMemo(()=>{const A=new Set,X=[];for(const ae of y)A.has(ae.id)||(A.add(ae.id),X.push(ae));return X.sort((ae,ge)=>ge.createdAt-ae.createdAt)},[y]),oe=o.length+h.length,re=ee.length;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"page-header",children:[s.jsx("h1",{className:"page-title",children:"Pending Approvals"}),s.jsx("p",{className:"page-subtitle",children:"Actions awaiting approval, plus recent activity from the last 7 days."})]}),s.jsxs("div",{className:"nav-tabs",style:{marginBottom:"1rem"},children:[s.jsxs("button",{className:`nav-tab${r==="awaiting-me"?" active":""}`,onClick:()=>a("awaiting-me"),children:["Awaiting me ",oe>0&&s.jsx("span",{style:{marginLeft:"0.4rem",background:"var(--warning)",color:"var(--bg-elevated)",borderRadius:"0.625rem",padding:"0 0.375rem",fontSize:"0.7rem",fontWeight:600},children:oe})]}),s.jsxs("button",{className:`nav-tab${r==="awaiting-others"?" active":""}`,onClick:()=>a("awaiting-others"),children:["Awaiting others ",re>0&&s.jsx("span",{style:{marginLeft:"0.4rem",background:"var(--border)",color:"var(--text-secondary)",borderRadius:"0.625rem",padding:"0 0.375rem",fontSize:"0.7rem",fontWeight:600},children:re})]}),s.jsx("button",{className:`nav-tab${r==="all"?" active":""}`,onClick:()=>{a("all"),Q()},children:"All"})]}),r==="awaiting-me"&&s.jsx(s.Fragment,{children:d&&oe===0?s.jsx("p",{style:{color:"var(--text-tertiary)"},children:"Loading..."}):oe===0?s.jsxs("div",{className:"card",style:{textAlign:"center",padding:"2rem"},children:[s.jsx("p",{style:{color:"var(--text-tertiary)",marginBottom:"0.5rem"},children:"No actions awaiting your approval."}),s.jsx("p",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)"},children:"Review-mode actions and above-cap actions you must approve will appear here."})]}):s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"1rem"},children:[(p||_)&&s.jsx("div",{className:"alert alert-success",children:p||_}),h.map(A=>s.jsx(ju,{proposalLinks:A.kind==="proposal"?N(A.proposal.tool):void 0,item:A,onApprove:X=>q(X,"commit"),onReject:X=>q(X,"reject"),resolving:J===A.id},A.id)),o.map(A=>s.jsx(T0,{proposal:A,currentUserId:n,onAction:me,onMessage:m,proposalLinks:N(A.tool)},A.id))]})}),r==="awaiting-others"&&s.jsx(s.Fragment,{children:ee.length===0?s.jsxs("div",{className:"card",style:{textAlign:"center",padding:"2rem"},children:[s.jsx("p",{style:{color:"var(--text-tertiary)",marginBottom:"0.5rem"},children:"No actions waiting on others."}),s.jsx("p",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)"},children:"Actions you proposed or approved that are pending other approvers will appear here."})]}):s.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"1rem"},children:ee.map(A=>s.jsx(P0,{proposal:A,currentUserId:n,onCancel:async()=>{try{await T.rejectProposal(A.id,"cancelled by creator"),b(),k()}catch(X){alert(X instanceof Error?X.message:"Cancel failed")}}},A.id))})}),r==="all"&&s.jsxs(s.Fragment,{children:[_&&s.jsx("div",{className:"alert alert-success",style:{marginBottom:"1rem"},children:_}),s.jsxs("div",{className:"filter-chips",style:{marginBottom:"1rem"},children:[s.jsx("button",{className:`filter-chip ${ne==="pending"?"selected":""}`,onClick:()=>L("pending"),children:"Pending"}),s.jsx("button",{className:`filter-chip ${ne==="all"?"selected":""}`,onClick:()=>L("all"),children:"All"}),te.length>0&&s.jsx("span",{style:{width:1,background:"var(--border)",alignSelf:"stretch",margin:"0 0.25rem"}}),te.map(A=>s.jsx("button",{className:`filter-chip ${z===A?"selected":""}`,onClick:()=>W(z===A?null:A),children:$e(A)},A)),ne==="all"&&s.jsxs(s.Fragment,{children:[s.jsx("span",{style:{width:1,background:"var(--border)",alignSelf:"stretch",margin:"0 0.25rem"}}),s.jsxs("button",{className:`filter-chip ${R?"selected":""}`,onClick:()=>F(!R),title:"Include actions executed without human review (automatic commitment mode)",children:[R?"✓ ":"","Autonomous actions"]})]})]}),U&&ce.length===0?s.jsx("p",{style:{color:"var(--text-tertiary)"},children:"Loading..."}):ce.length===0?s.jsxs("div",{className:"card",style:{textAlign:"center",padding:"2rem"},children:[s.jsx("p",{style:{color:"var(--text-tertiary)",marginBottom:"0.5rem"},children:ne==="pending"?"No actions awaiting your approval.":"Nothing here yet."}),s.jsx("p",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)"},children:ne==="pending"?"Your agents are operating within their mandates. Switch to All to see recent activity.":"When an agent calls a gated tool, activity will appear here."})]}):s.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"1rem"},children:ce.map(A=>s.jsx(ju,{proposalLinks:A.kind==="proposal"?N(A.proposal.tool):void 0,item:A,onApprove:X=>q(X,"commit"),onReject:X=>q(X,"reject"),resolving:J===A.id},A.id))})]})]})}function R0(e){const t=Date.now()-e*1e3,n=Math.floor(t/6e4);if(n<60)return`${Math.max(1,n)}m ago`;const r=Math.floor(t/36e5);return r<48?`${r}h ago`:`${Math.floor(r/24)}d ago`}function P0({proposal:e,currentUserId:t,onCancel:n}){var d;const[r,a]=u.useState(!1),o=Object.keys(e.approvedBy??{}),i=(e.pendingApprovers??[]).filter(f=>!(f in(e.approvedBy??{}))),l=(((d=e.pendingApprovers)==null?void 0:d.length)??0)>0,c=async()=>{if(confirm("Cancel this action? All approvers will be notified.")){a(!0);try{await n()}finally{a(!1)}}};return s.jsxs("div",{className:"card",children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem",marginBottom:"0.5rem",flexWrap:"wrap"},children:[s.jsx("span",{style:{fontWeight:600,fontSize:"0.9rem"},children:$e(e.profileId)}),l&&s.jsx("span",{style:{fontSize:"0.65rem",padding:"0.15rem 0.4rem",borderRadius:"0.25rem",background:"var(--accent-subtle)",color:"var(--accent)",fontWeight:600},children:"Above cap"}),s.jsx("span",{style:{marginLeft:"auto",fontSize:"0.75rem",color:"var(--text-tertiary)"},children:R0(e.createdAt)})]}),s.jsx("div",{style:{fontSize:"0.85rem",color:"var(--text-secondary)",marginBottom:"0.5rem"},children:s.jsx("code",{children:e.tool.split("__").pop()??e.tool})}),l&&s.jsxs("div",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)",marginBottom:"0.5rem"},children:[o.map(f=>s.jsx("span",{style:{marginRight:"0.75rem",color:"var(--success, green)"},children:f===t?"You approved":`${f} approved`},f)),i.map(f=>s.jsxs("span",{style:{marginRight:"0.75rem",color:"var(--text-tertiary)"},children:["Waiting on ",f===t?"you":f]},f))]}),s.jsx("div",{style:{display:"flex",justifyContent:"flex-end",gap:"0.5rem",marginTop:"0.5rem"},children:s.jsx("button",{className:"btn btn-ghost btn-sm",style:{color:"var(--danger)"},onClick:c,disabled:r,children:r?"Cancelling...":"Cancel"})})]})}const _0=`# Agent Brief
74
+ `}),p?s.jsx("p",{style:{color:"var(--text-tertiary)",fontSize:"0.9rem"},children:"Loading..."}):y.length===0?s.jsxs("div",{className:"card",style:{padding:"2rem",textAlign:"center"},children:[s.jsx("p",{style:{color:"var(--text-secondary)",fontSize:"0.9rem",marginBottom:"1rem"},children:"No integrations set up yet. Connect a service first."}),s.jsx(Ye,{to:"/integrations",className:"btn btn-primary btn-sm",onClick:()=>e==null?void 0:e(),children:"Go to Integrations"})]}):s.jsx("div",{className:"profile-grid",children:y.map(({manifest:C,profile:I,integration:E})=>{const $=S(I.id),U=(E==null?void 0:E.running)===!0;return s.jsxs("div",{className:"card",style:U?void 0:{opacity:.7},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem",marginBottom:"0.125rem"},children:[s.jsx("h3",{className:"card-title",style:{margin:0},children:C.name}),$?s.jsx("span",{style:{fontSize:"0.6rem",padding:"0.1rem 0.35rem",borderRadius:"0.2rem",background:"var(--accent-subtle)",color:"var(--accent)",fontWeight:600},children:"Team"}):s.jsx("span",{style:{fontSize:"0.6rem",padding:"0.1rem 0.35rem",borderRadius:"0.2rem",background:"var(--bg-main)",color:"var(--text-tertiary)",fontWeight:600,border:"1px solid var(--border)"},children:"Personal"})]}),s.jsx("p",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)",marginBottom:"1rem",flex:1},children:C.description||I.description}),U?s.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>N(I.id),children:"Give a mandate"}):s.jsxs(Ye,{to:`/integrations?setup=${(C==null?void 0:C.id)??""}`,className:"btn btn-secondary btn-sm",style:{textDecoration:"none",textAlign:"center"},onClick:()=>e==null?void 0:e(),children:["Set up ",(C==null?void 0:C.name)??"integration"]})]},C.id)})})]})}const zx={active:"Active",pending:"Pending",expired:"Expired",revoked:"Revoked"};function $x({status:e,label:t}){return s.jsx("span",{className:`status-badge status-${e}`,children:t||zx[e]})}function Lx({domain:e,attested:t}){const n=t===!0?"domain-attested":t===!1?"domain-missing":"";return s.jsx("span",{className:`domain-badge ${n}`,style:{fontSize:"0.75rem"},children:e})}const Tn=86400,Fr=3600,Ws=60,Mx=30*Tn;function Fx(e){if(e<=0)return"Expired";if(e>90*Tn){const t=Math.floor(e/Mx);return`${t} ${t===1?"month":"months"} remaining`}if(e>7*Tn){const t=Math.floor(e/Tn);return`${t} ${t===1?"day":"days"} remaining`}if(e>=2*Tn){const t=Math.floor(e/Tn),n=Math.floor(e%Tn/Fr);return`${t} ${t===1?"day":"days"} ${n}h remaining`}if(e>=2*Fr){const t=Math.floor(e/Fr),n=Math.floor(e%Fr/Ws);return`${t}h ${String(n).padStart(2,"0")}m remaining`}if(e>=Ws){const t=Math.floor(e/Ws),n=Math.floor(e%Ws);return`${t}m ${String(n).padStart(2,"0")}s remaining`}return`${Math.floor(e)}s remaining`}function Ox({expiresAt:e}){const[t,n]=u.useState(()=>e-Date.now()/1e3),r=t<2*Fr;u.useEffect(()=>{const o=setInterval(()=>n(e-Date.now()/1e3),r?1e3:6e4);return()=>clearInterval(o)},[e,r]);const a=t<300;return s.jsx("span",{className:`ttl-badge ${a?"ttl-warn":"ttl-ok"}`,children:Fx(t)})}function Em({icon:e,title:t,text:n,children:r}){return s.jsxs("div",{className:"empty-state",children:[e&&s.jsx("div",{className:"empty-state-icon",children:e}),s.jsx("div",{className:"empty-state-title",children:t}),n&&s.jsx("div",{className:"empty-state-text",children:n}),r]})}function Bx(e){const t=Math.floor(e/86400);if(t>=1)return`${t} day${t===1?"":"s"}`;const n=Math.floor(e/3600);if(n>=1)return`${n} hour${n===1?"":"s"}`;const r=Math.ceil(e/60);return`${r} minute${r===1?"":"s"}`}const Dx=[{label:"30m",seconds:1800},{label:"1h",seconds:3600},{label:"2h",seconds:7200},{label:"4h",seconds:14400},{label:"8h",seconds:28800},{label:"24h",seconds:86400},{label:"7d",seconds:604800},{label:"30d",seconds:2592e3},{label:"1y",seconds:31536e3}];function Ux({item:e,onClose:t,onSuccess:n}){var y;const{user:r,activeDomain:a,groupId:o}=Fe(),[i,l]=u.useState(null);u.useEffect(()=>{let S=!1;return T.getProfile(e.profile_id).then(b=>{var N;S||l(((N=b==null?void 0:b.ttl)==null?void 0:N.max)??null)}).catch(()=>{}),()=>{S=!0}},[e.profile_id]);const c=e.remaining_seconds??0,d=Dx.filter(S=>S.seconds>c&&(i===null||S.seconds<=i)),f=((y=d[0])==null?void 0:y.seconds)??2592e3,[p,m]=u.useState(f);u.useEffect(()=>{var S;if(i!==null&&p>i){const b=(S=d[d.length-1])==null?void 0:S.seconds;b&&m(b)}},[i]);const[w,v]=u.useState(!1),[x,k]=u.useState(""),g=Object.entries(e.frame).filter(([S])=>S!=="profile"&&S!=="path"),h=async()=>{var S;if(r){v(!0),k("");try{const b=e.authorization_id,N=await T.getGateContent(b);if(!N)throw new Error("Gate content not found locally. The MCP server may have restarted. Please re-authorize through the full wizard instead.");const C=await T.getProfile(e.profile_id),I=e.frame,E=N.context??{},$=e.attested_domains[0]||a||"owner",U=await aa(I,C),V=await km(E,C),[J,D]=await Promise.all([Aa(N.gateContent.intent),Aa(JSON.stringify({profile:e.profile_id,path:e.path,domain:$}))]);if(!o)throw new Error("No active group; cannot extend mandate.");const _=(((S=e.deferred_commitment_domains)==null?void 0:S.length)??0)>0?"review":"automatic",B=await T.attest({authorization_id:e.authorization_id,renew:!0,profile_id:e.profile_id,bounds:I,bounds_hash:U,context_hash:V,domain:$,did:r.did,gate_content_hashes:{intent:J},execution_context_hash:D,group_id:o,commitment_mode:_,ttl:p});await T.pushGateContent(bm(B,{boundsHash:U,contextHash:V,context:E,path:e.path,gateContent:N.gateContent})),n()}catch(b){k(b instanceof Error?b.message:"Extension failed")}finally{v(!1)}}};return s.jsx("div",{className:"modal-backdrop",onClick:S=>S.target===S.currentTarget&&t(),children:s.jsxs("div",{className:"modal",children:[s.jsxs("div",{className:"modal-header",children:[s.jsx("h3",{className:"modal-title",children:"Extend mandate"}),s.jsx("button",{className:"modal-close",onClick:t,children:"×"})]}),s.jsxs("div",{className:"modal-body",children:[s.jsxs("div",{style:{marginBottom:"1rem"},children:[s.jsxs("div",{style:{fontWeight:600,marginBottom:"0.25rem"},children:[$e(e.profile_id)," / ",e.path]}),g.length>0&&s.jsx("div",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)"},children:g.map(([S,b])=>`${S}=${b}`).join(" · ")})]}),s.jsxs("div",{style:{marginBottom:"1rem"},children:[s.jsx("div",{style:{fontSize:"0.75rem",fontWeight:600,color:"var(--text-tertiary)",textTransform:"uppercase",letterSpacing:"0.04em",marginBottom:"0.5rem"},children:"New duration"}),c>0&&s.jsxs("div",{style:{fontSize:"0.75rem",color:"var(--text-tertiary)",marginBottom:"0.5rem"},children:["Currently valid for ",Bx(c),". Only longer durations are shown."]}),s.jsx("div",{style:{display:"flex",gap:"0.5rem",flexWrap:"wrap"},children:d.length===0?s.jsx("div",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)"},children:"This mandate is already on the longest available duration. Nothing to extend."}):d.map(S=>s.jsx("button",{className:`btn ${p===S.seconds?"btn-primary":"btn-secondary"}`,onClick:()=>m(S.seconds),style:{minWidth:"3.5rem"},children:S.label},S.seconds))})]}),s.jsx("div",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)",marginBottom:"0.5rem"},children:"Same bounds, scope, and gate content will be re-signed with a new TTL (measured from now)."}),x&&s.jsx("div",{className:"error-message",children:x})]}),s.jsxs("div",{className:"modal-footer",children:[s.jsx("button",{className:"btn btn-secondary",onClick:t,disabled:w,children:"Cancel"}),s.jsx("button",{className:"btn btn-primary",onClick:h,disabled:w,children:w?"Extending...":"Extend"})]})]})})}function Wx(e,t,n){return[...e].sort((r,a)=>{if(n){if(r.authorization_id===n&&a.authorization_id!==n)return-1;if(a.authorization_id===n&&r.authorization_id!==n)return 1}const o=Pa(r,t),i=Pa(a,t),l={active:0,pending:1,expired:2,revoked:3,archived:4};return l[o]!==l[i]?l[o]-l[i]:new Date(a.created_at).getTime()-new Date(r.created_at).getTime()})}function Hx({item:e,newerProfile:t,revokedSet:n,expandedHash:r,gateCache:a,gateLoading:o,copiedHash:i,revokingHash:l,copyingHash:c,profileConfigCache:d,mode:f,ownerLabel:p,isAdmin:m,onExpand:w,onCopyHash:v,onCopy:x,onRevoke:k,onExtend:g,archivedSet:h,archivingHash:y,onArchive:S,highlightHash:b}){var me;const N=Dl(e,{revokedSet:n}),C=im(e,{revokedSet:n,archivedSet:h}),I=!p&&!!S&&om(N),E=r===e.authorization_id,$=a[e.authorization_id],U=N==="active"||N==="pending"||N==="expired",V=Object.entries(e.frame).filter(([ee])=>ee!=="profile"&&ee!=="path"),J=d.get(e.profile_id)??null,D=(((me=J==null?void 0:J.approvers)==null?void 0:me.length)??0)>0,_=new Map;if(J!=null&&J.caps&&f==="team")for(const[ee,oe]of V){const re=J.caps[ee];re!==void 0&&Number(oe)>re&&_.set(ee,{authorized:Number(oe),cap:re})}const B=_.size>0,ne=e.approvers_frozen??[],L=(J==null?void 0:J.approvers)??[],z=f==="team"&&ne.length>0&&L.length>0&&(ne.length!==L.length||ne.some(ee=>!L.includes(ee))||L.some(ee=>!ne.includes(ee))),W=Array.from(_.entries()).map(([ee,oe])=>`${ee}: ${oe.authorized} (cap ${oe.cap})`).join(", "),R=Array.from(_.entries()).map(([ee,oe])=>`${ee}: ${oe.authorized} → ${oe.cap}`).join(", "),F=B?D?_.size===1?`Above team cap: ${W} — actions require approval`:`Above team cap (${_.size}): ${W} — actions require approval`:_.size===1?`Reduced by hard cap: ${R}`:`Reduced by hard cap (${_.size}): ${R}`:"",Q=B?D?"Above-cap actions under this mandate require per-action approval from the profile's approvers. Bounds remain authorized at their original values.":"No approvers are configured for this profile, so the team cap is a hard ceiling. Bounds above the cap are effectively reduced to the cap. Ask the admin to raise the cap or add approvers, or copy this mandate to reissue within the cap.":void 0,q=$e(e.profile_id),te=t?s.jsxs("div",{style:{fontSize:"0.75rem",color:"var(--text-tertiary)",marginBottom:"0.5rem",padding:"0.4rem 0.6rem",border:"1px solid var(--border)",borderRadius:6},children:[s.jsxs("strong",{style:{color:"var(--text-secondary)"},children:[q,"@",t.version," available"]}),t.whatsNew?s.jsxs(s.Fragment,{children:[" — ",t.whatsNew]}):null,s.jsx("br",{}),s.jsxs("span",{children:["This mandate stays on ",e.profile_id.split("@")[1]??"its pinned version","; authorize again to move it."]})]}):null,ce=b!=null&&e.authorization_id===b;return s.jsxs("div",{className:`card${ce?" card-highlight":""}`,style:{marginBottom:0},children:[te,p&&s.jsxs("div",{style:{fontSize:"0.75rem",color:"var(--text-tertiary)",marginBottom:"0.375rem"},children:["Owner: ",s.jsx("span",{style:{color:"var(--text-secondary)",fontWeight:500},children:p})]}),s.jsxs("div",{className:"auth-card-header",children:[s.jsx("span",{style:{fontWeight:700,fontSize:"1rem",color:"var(--text-primary)",letterSpacing:"0.01em"},children:q}),e.title&&s.jsx("span",{style:{fontWeight:500,fontSize:"0.85rem",color:"var(--text-secondary)"},children:e.title}),s.jsx($x,{status:N}),N==="active"&&e.earliest_expiry&&s.jsx(Ox,{expiresAt:new Date(e.earliest_expiry).getTime()/1e3}),N==="expired"&&(()=>{const ee=Gy(e,N);return ee?s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-tertiary)"},title:`Expired ${new Date(ee.iso).toLocaleString()}`,children:new Date(ee.iso).toLocaleDateString(void 0,{month:"short",day:"numeric"})}):null})()]}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem",flexWrap:"wrap",marginBottom:"0.5rem",alignItems:"center"},children:[e.required_domains.map(ee=>s.jsx(Lx,{domain:ee,attested:e.attested_domains.includes(ee)},ee)),e.deferred_commitment_domains.length>0&&s.jsx("span",{style:{fontSize:"0.65rem",padding:"0.15rem 0.4rem",borderRadius:"0.25rem",background:"var(--accent-subtle)",color:"var(--accent)",fontWeight:600},children:"Review Mode"}),B&&s.jsx("span",{title:Q,style:{fontSize:"0.65rem",padding:"0.15rem 0.4rem",borderRadius:"0.25rem",background:D?"var(--accent-subtle)":"var(--danger-subtle)",color:D?"var(--accent)":"var(--danger)",fontWeight:600,cursor:"help"},children:F}),z&&s.jsx("button",{className:"btn btn-ghost btn-sm",style:{fontSize:"0.65rem",padding:"0.15rem 0.5rem",borderRadius:"0.25rem",background:"var(--warning-subtle, rgba(234,179,8,0.12))",color:"var(--warning, #ca8a04)",fontWeight:600,border:"1px solid var(--warning-border, rgba(234,179,8,0.3))",cursor:"pointer",lineHeight:1.4},onClick:()=>x(e),disabled:c===e.authorization_id,title:"The approver list for this profile has changed since this mandate was created. Copy to reissue with the current approvers.",children:c===e.authorization_id?"Copying...":"Approver list updated · Copy with new approvers"})]}),V.length>0&&s.jsx("div",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)"},children:V.map(([ee,oe],re)=>{const A=_.get(ee);return s.jsxs("span",{children:[re>0&&" · ",A?D?s.jsxs("span",{title:`Team cap on ${ee} is ${A.cap}. Actions exceeding the cap require per-action approval. Bound remains authorized at ${A.authorized}.`,children:[s.jsxs("span",{style:{color:"var(--text-tertiary)"},children:[ee,"=",String(oe)]}),s.jsxs("span",{style:{color:"var(--accent)",marginLeft:"0.25rem",fontWeight:600},children:["↑ approval at ",A.cap]})]}):s.jsxs("span",{title:`Team cap on ${ee} is ${A.cap} with no approvers configured (hard cap). Authorized for ${A.authorized}; effective ${A.cap}.`,children:[s.jsxs("span",{style:{textDecoration:"line-through",color:"var(--text-tertiary)"},children:[ee,"=",String(oe)]}),s.jsxs("span",{style:{color:"var(--danger)",marginLeft:"0.25rem",fontWeight:600},children:["→"," ",A.cap]})]}):s.jsxs("span",{children:[ee,"=",String(oe)]})]},ee)})}),s.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:"0.5rem",marginTop:"0.5rem"},children:[I&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>S(e.authorization_id,!C),disabled:y===e.authorization_id,title:C?"Move back to the Expired or Revoked list":"Hide from the list and the nav badge. Nothing is deleted: the mandate and its tickets stay stored and verifiable.",children:y===e.authorization_id?C?"Unarchiving…":"Archiving…":C?"↩ Unarchive":"⊟ Archive"}),s.jsx("button",{className:"btn btn-ghost btn-sm",onClick:()=>w(e),children:E?"▲ Hide Details":"▼ Details"})]}),E&&s.jsxs("div",{style:{borderTop:"1px solid var(--border)",marginTop:"0.75rem",paddingTop:"0.75rem"},children:[V.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{style:{fontSize:"0.75rem",fontWeight:600,color:"var(--text-tertiary)",textTransform:"uppercase",letterSpacing:"0.04em",marginBottom:"0.25rem"},children:"Bounds"}),s.jsx("dl",{className:"review-grid",children:V.map(([ee,oe])=>s.jsxs("span",{style:{display:"contents"},children:[s.jsx("dt",{children:ee}),s.jsx("dd",{children:String(oe)})]},ee))})]}),($==null?void 0:$.context)&&Object.keys($.context).length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{style:{fontSize:"0.75rem",fontWeight:600,color:"var(--text-tertiary)",textTransform:"uppercase",letterSpacing:"0.04em",marginTop:"1rem",marginBottom:"0.25rem"},children:"Scope"}),s.jsx("dl",{className:"review-grid",children:Object.entries($.context).map(([ee,oe])=>s.jsxs("span",{style:{display:"contents"},children:[s.jsx("dt",{children:ee}),s.jsx("dd",{title:String(oe),children:Cm(ee,oe,$.contextLabels)})]},ee))})]}),s.jsx("div",{style:{fontSize:"0.75rem",fontWeight:600,color:"var(--text-tertiary)",textTransform:"uppercase",letterSpacing:"0.04em",marginTop:"1rem",marginBottom:"0.25rem"},children:"Intent"}),o===e.authorization_id?s.jsx("p",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)"},children:"Loading gate content..."}):$?s.jsx("div",{className:"gate-content-block",children:s.jsx("div",{className:"gate-content-item",children:s.jsx("div",{className:"gate-content-text",children:$.gateContent.intent})})}):s.jsx("p",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)"},children:"Gate content not available."}),s.jsxs("div",{style:{fontSize:"0.75rem",color:"var(--text-tertiary)",marginTop:"1rem"},children:["Created: ",new Date(e.created_at).toLocaleString(),e.earliest_expiry&&` · Expires: ${new Date(e.earliest_expiry).toLocaleString()}`]}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem",marginTop:"0.25rem"},children:[s.jsx("span",{style:{fontSize:"0.7rem",color:"var(--text-tertiary)",fontFamily:"'SF Mono', Monaco, monospace",wordBreak:"break-all"},children:e.authorization_id}),s.jsx("button",{className:"btn btn-ghost btn-sm",style:{fontSize:"0.7rem",padding:"0.125rem 0.375rem"},onClick:()=>v(e.authorization_id),children:i===e.authorization_id?"copied":"copy"})]}),s.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:"0.5rem",marginTop:"0.75rem"},children:[!p&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>x(e),disabled:c===e.authorization_id,title:"Start a new mandate pre-filled with these bounds, scope, and intent",children:c===e.authorization_id?"Copying…":"⧉ Copy"}),!p&&(N==="active"||N==="pending")&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>x(e,{asEdit:!0}),disabled:c===e.authorization_id,title:"Adjust intent, bounds, or scope: opens the ceremony pre-filled; signing the new mandate revokes this one",children:"✎ Edit"}),!p&&U&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>g(e),children:"↻ Extend"}),p&&m&&N!=="revoked"?s.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>k(e.authorization_id,p,q),disabled:l===e.authorization_id,children:l===e.authorization_id?"Revoking…":"Revoke"}):!p&&(N==="active"||N==="pending")?s.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>k(e.authorization_id),disabled:l===e.authorization_id,children:l===e.authorization_id?"Revoking…":"Revoke"}):null]})]})]},e.authorization_id)}function Vx(){const[e,t]=u.useState([]),[n,r]=u.useState(!0),[a,o]=u.useState([]),[i,l]=u.useState(!1),[c,d]=u.useState(new Map),[f,p]=u.useState("mine"),[m,w]=u.useState("active"),[v,x]=u.useState(null),[k,g]=u.useState(null),[h,y]=tm(),[S,b]=u.useState(()=>h.get("new")==="1"),[N,C]=u.useState(()=>h.get("highlight")),[I,E]=u.useState(null),[$,U]=u.useState({}),[V,J]=u.useState(null),[D,_]=u.useState(null),[B,ne]=u.useState(null),[L,z]=u.useState(new Set),[W,R]=u.useState(null),[F,Q]=u.useState(new Set),[q,te]=u.useState(null),[ce,me]=u.useState(null),ee=nn(),{group:oe,groupId:re,domain:A,mode:X,activeTeam:ae}=Fe(),ge=(ae==null?void 0:ae.isAdmin)===!0,[he,Pe]=u.useState(()=>new Map),qe=u.useCallback(()=>{r(!0),T.getMyAttestations().then(t).catch(()=>{}).finally(()=>r(!1))},[]),_e=u.useCallback(()=>{T.getArchivedMandates().then(H=>Q(new Set(H))).catch(()=>{})},[]);u.useEffect(()=>{_e()},[_e]);const yt=async(H,Z)=>{te(H);try{const K=await T.setMandateArchived(H,Z);Q(new Set(K)),window.dispatchEvent(new Event("suveren:archived-changed"))}catch(K){alert(K instanceof Error?K.message:"Failed to update archive")}finally{te(null)}},Ze=u.useCallback(()=>{re&&(l(!0),T.listTeamAuthorizations(re).then(o).catch(()=>{}).finally(()=>l(!1)))},[re]);fe("attestation-changed",()=>{qe(),ge&&re&&Ze()}),u.useEffect(()=>{if(!N)return;h.get("highlight")&&(h.delete("highlight"),y(h,{replace:!0}));const H=window.setTimeout(()=>C(null),3e3);return()=>window.clearTimeout(H)},[]),Pt(qe,3e5),u.useEffect(()=>{f==="team"&&ge&&re&&a.length===0&&!i&&Ze()},[f,ge,re,a.length,i,Ze]),u.useEffect(()=>{let H=!1;return T.listProfiles().then(Z=>{if(H)return;const K=lt=>lt.replace(/@.*$/,"").split("/").pop()??lt,de=lt=>lt.split("@")[1]??"",ye=new Map;for(const lt of Z){const Wt=K(lt.id),ws=ye.get(Wt);(!ws||de(lt.id).localeCompare(de(ws.id),void 0,{numeric:!0})>0)&&ye.set(Wt,lt)}d(ye)}).catch(()=>{}),()=>{H=!0}},[]);const Ge=u.useCallback(H=>{const Z=Wt=>Wt.replace(/@.*$/,"").split("/").pop()??Wt,K=Wt=>Wt.split("@")[1]??"",de=c.get(Z(H));if(!de)return;const ye=K(H),lt=K(de.id);if(!(!ye||!lt))return lt.localeCompare(ye,void 0,{numeric:!0})>0?de:void 0},[c]);u.useEffect(()=>{if(X!=="team"||!re)return;const H=f==="mine"?e:a;if(H.length===0)return;const Z=[...new Set(H.map(K=>K.profile_id))].filter(K=>!he.has(K));if(Z.length!==0){Pe(K=>{const de=new Map(K);for(const ye of Z)de.set(ye,null);return de});for(const K of Z)T.getTeamProfileConfig(re,K).then(de=>{Pe(ye=>new Map(ye).set(K,de))}).catch(()=>{})}},[e,a,f,re,X,he]);const le=async H=>{if(I===H.authorization_id){E(null);return}E(H.authorization_id);const Z=H.authorization_id;if(!(Z in $)){J(H.authorization_id);try{const K=await T.getGateContent(Z);U(de=>({...de,[Z]:K}))}catch{U(K=>({...K,[Z]:null}))}finally{J(null)}}},et=H=>{navigator.clipboard.writeText(H).then(()=>{ne(H),setTimeout(()=>ne(null),2e3)})},Ut=async(H,Z)=>{var K;if(!re){alert("No active group; cannot copy mandate.");return}me(H.authorization_id);try{const de=H.authorization_id;let ye=$[de]??null;de in $||(ye=await T.getGateContent(de),U(Ss=>({...Ss,[de]:ye})));const lt=Object.fromEntries(Object.entries(H.frame).filter(([Ss])=>Ss!=="profile"&&Ss!=="path")),Wt=(ye==null?void 0:ye.context)??{},ws=((K=ye==null?void 0:ye.gateContent)==null?void 0:K.intent)??"",Rm=H.deferred_commitment_domains.length>0?"review":"automatic",Pm=H.attested_domains[0]||A||"owner",Za=Date.parse(H.created_at),eo=H.earliest_expiry?Date.parse(H.earliest_expiry):NaN,_m=Number.isFinite(Za)&&Number.isFinite(eo)&&eo>Za?Math.round((eo-Za)/1e3):void 0;sessionStorage.setItem("agentAuth",JSON.stringify({profileId:H.profile_id,groupId:re,groupName:(oe==null?void 0:oe.name)??null,domain:Pm,isPersonal:!!(oe!=null&&oe.isPersonal)})),sessionStorage.setItem("agentGate",JSON.stringify({bounds:lt,context:Wt,gateContent:{intent:ws},templateMode:Rm,templateTtl:_m})),Z!=null&&Z.asEdit?sessionStorage.setItem("agentEditReplaces",H.authorization_id):sessionStorage.removeItem("agentEditReplaces"),ee("/mandates/new/intent")}catch(de){alert(de instanceof Error?de.message:"Failed to copy mandate")}finally{me(null)}},j=async(H,Z,K)=>{const de=Z&&K?`Revoke ${Z}'s ${K} mandate? This cannot be undone.`:"Revoke this mandate? The agent will no longer be able to execute actions under it.";if(confirm(de)){R(H);try{await T.revokeAttestation(H),z(ye=>new Set(ye).add(H)),T.resyncGates().catch(()=>{}),Z&&re&&Ze()}catch(ye){alert(ye instanceof Error?ye.message:"Failed to revoke mandate")}finally{R(null)}}},P=f==="mine"?e:a,O=f==="mine"?n:i,G=f==="mine"?{revokedSet:L,archivedSet:F}:{revokedSet:L},se=H=>Pa(H,G),Nt={active:0,pending:0,expired:0,revoked:0,archived:0};for(const H of P)Nt[se(H)]+=1;const bn=f==="mine"?["active","pending","expired","revoked","archived"]:["active","pending","expired","revoked"],Ie=(()=>{const H=new Map;for(const Z of P){if(se(Z)!==m)continue;const K=H.get(Z.profile_id)??{count:0,review:!1};K.count+=1,Z.deferred_commitment_domains.length>0&&(K.review=!0),H.set(Z.profile_id,K)}return Array.from(H.entries()).map(([Z,K])=>({profileId:Z,...K})).sort((Z,K)=>$e(Z.profileId).localeCompare($e(K.profileId)))})(),it=Wx(P.filter(H=>{if(se(H)!==m||v!==null&&H.profile_id!==v)return!1;if(k!==null){const Z=H.deferred_commitment_domains.length>0;if(k==="review"&&!Z||k==="auto"&&Z)return!1}return!0}),G,N),vt={revokedSet:L,expandedHash:I,gateCache:$,gateLoading:V,copiedHash:B,revokingHash:W,copyingHash:ce,profileConfigCache:he,mode:X,activeDomain:A,group:oe,groupId:re,onExpand:le,onCopyHash:et,onCopy:Ut,onRevoke:j,onExtend:_,highlightHash:N},tt={...vt,archivedSet:F,archivingHash:q,onArchive:yt};return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"page-header",style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",gap:"1rem",flexWrap:"wrap"},children:[s.jsxs("div",{children:[s.jsx("h1",{className:"page-title",children:"Mandates"}),s.jsx("p",{className:"page-subtitle",children:"Active, pending, expired, and archived agent mandates."})]}),s.jsx("button",{className:"btn btn-primary",onClick:()=>b(!0),children:"+ New mandate"})]}),S&&s.jsx("div",{className:"modal-backdrop",onClick:()=>{b(!1),h.get("new")&&(h.delete("new"),y(h,{replace:!0}))},children:s.jsxs("div",{className:"modal",onClick:H=>H.stopPropagation(),style:{maxWidth:"960px",width:"90vw"},children:[s.jsxs("div",{className:"modal-header",children:[s.jsx("h2",{className:"modal-title",children:"New mandate"}),s.jsx("button",{className:"modal-close",onClick:()=>{b(!1),h.get("new")&&(h.delete("new"),y(h,{replace:!0}))},children:"×"})]}),s.jsxs("div",{className:"modal-body",children:[s.jsx("p",{style:{color:"var(--text-tertiary)",fontSize:"0.9rem",marginTop:0,marginBottom:"1rem"},children:"What should your agent be able to do? Pick a profile, set limits, then authorize."}),s.jsx(Ax,{onDismiss:()=>b(!1)})]})]})}),ge&&s.jsxs("div",{className:"nav-tabs",style:{marginBottom:"0.5rem"},children:[s.jsx("button",{className:`nav-tab${f==="mine"?" active":""}`,onClick:()=>{p("mine"),w("active"),x(null),g(null),E(null)},children:"Mine"}),s.jsx("button",{className:`nav-tab${f==="team"?" active":""}`,onClick:()=>{p("team"),w("active"),x(null),g(null),E(null)},children:"Team"})]}),s.jsx("div",{className:"nav-tabs",children:bn.map(H=>s.jsxs("button",{className:`nav-tab${m===H?" active":""}`,onClick:()=>{w(H),x(null),g(null)},children:[H.charAt(0).toUpperCase()+H.slice(1)," (",Nt[H],")"]},H))}),Ie.length>0&&s.jsxs("div",{style:{display:"flex",gap:"0.5rem",flexWrap:"wrap",alignItems:"center",marginTop:"-0.25rem",marginBottom:"1rem"},children:[Ie.map(H=>{const Z=v===H.profileId;return s.jsx("button",{className:`btn btn-sm ${Z?"btn-primary":"btn-secondary"}`,onClick:()=>x(Z?null:H.profileId),children:$e(H.profileId)},H.profileId)}),s.jsx("span",{"aria-hidden":"true",style:{color:"var(--border)",fontSize:"1.1rem",padding:"0 0.25rem",userSelect:"none"},children:"|"}),["auto","review"].map(H=>{const Z=k===H;return s.jsx("button",{className:`btn btn-sm ${Z?"btn-primary":"btn-secondary"}`,onClick:()=>g(Z?null:H),children:H==="auto"?"Auto":"Review"},H)})]}),O&&P.length===0?s.jsx("p",{style:{color:"var(--text-tertiary)"},children:"Loading..."}):it.length===0?s.jsx(Em,{icon:"☰",title:"No mandates",text:m==="archived"?"Nothing archived. Archive an expired or revoked mandate to move it here.":`No ${m} mandates found.`}):s.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem"},children:it.map(H=>{const Z=f==="team"?H:null,K=Z!=null&&Z.owner?Z.owner.name??Z.owner.email??Z.owner.userId:void 0;return s.jsx(Hx,{item:H,newerProfile:Ge(H.profile_id),ownerLabel:K,isAdmin:ge,...f==="mine"?tt:vt},H.authorization_id)})}),D&&s.jsx(Ux,{item:D,onClose:()=>_(null),onSuccess:()=>{_(null),qe()}})]})}function Gx(e){const t=e.indexOf("__");return t<0?{integrationId:"",toolName:e}:{integrationId:e.slice(0,t),toolName:e.slice(t+2)}}function Kx(e,t){var c,d,f;const{integrationId:n,toolName:r}=Gx(e.action),a=t.find(p=>p.id===n),o=(d=(c=a==null?void 0:a.toolGating)==null?void 0:c.overrides)==null?void 0:d[r];if(o!=null&&o.actionLabel)return o.actionLabel;const i=$e(e.profileId),l=(f=e.executionContext)==null?void 0:f.action_type;return typeof l=="string"&&l?`${i} · ${l}`:`${i} · ${r}`}function Yx(e){const t=[];for(const[n,r]of Object.entries(e.executionContext??{})){if(!n.startsWith("allowed_"))continue;const a=String(r??"").trim();a&&t.push(a.split(",").map(o=>o.trim()).filter(Boolean).join(", "))}return t.join(" · ")}function Qx(e){if(!e)return"";const t=[];for(const[n,r]of Object.entries(e)){if(n==="action_type")continue;const a=String(r??"").trim();if(!a)continue;const o=n.replace(/^allowed_/,"").replace(/_/g," ");t.push(`${o} ${a.split(",").map(i=>i.trim()).filter(Boolean).join(", ")}`)}return t.join(" · ")}function Jx(e,t){var o,i;const n=[{window:"daily",label:"today"},{window:"monthly",label:"this month"}],r=e.actionType??(typeof((o=e.executionContext)==null?void 0:o.action_type)=="string"?e.executionContext.action_type:void 0),a=[];for(const{window:l,label:c}of n){const d=(i=e.cumulativeState)==null?void 0:i[l];if(!d)continue;const f=`_${l}_max`,p=Object.keys(t??{}).filter(k=>k.endsWith(f)),m=(r&&p.find(k=>k.startsWith(`${r}_`)))??(p.length===1?p[0]:void 0),v=(m?/^(amount|spend)_/.test(m):!1)?d.amount:d.count,x=m?Number(t==null?void 0:t[m]):NaN;m&&Number.isFinite(x)?a.push(`${v} of ${x} ${c}`):a.push(`${d.count} ${d.count===1?"call":"calls"} ${c}`)}return a.join(" · ")}function Xx(e){return typeof e.proposalId=="string"&&e.proposalId.length>0}function qx(e){const t=$e(e),n=e.split("@")[1];return n?`${t}@${n}`:t}function Pr({label:e,children:t}){return s.jsxs(s.Fragment,{children:[s.jsx("dt",{className:"receipt-row-label",children:e}),s.jsx("dd",{className:"receipt-row-value",children:t})]})}function Zx({receipt:e,manifests:t,localAuth:n,localUnavailable:r,signature:a,grantTitle:o,ownerLabel:i,spUrl:l,formatDate:c,onOpenComplete:d}){var v;const f=Yx(e),p=Qx(n==null?void 0:n.context),m=Jx(e,(n==null?void 0:n.bounds)??e.limits),w=n==null?void 0:n.intent;return s.jsxs("div",{className:"card",style:{marginBottom:0},children:[s.jsxs("div",{className:"receipt-head",children:[s.jsx("span",{className:"receipt-what",children:Kx(e,t)}),s.jsx("span",{className:"receipt-tag",children:Xx(e)?"review":"automatic"}),e.contentHash&&s.jsx("span",{className:"receipt-tag receipt-tag-bound",title:(v=e.contentBinding)!=null&&v.fields?`The ticket binds: ${e.contentBinding.fields.join(", ")}`:"This exact content was authorized",children:"content bound"}),s.jsx("span",{className:"auth-card-time",children:c(e.timestamp)})]}),f&&s.jsx("div",{className:"receipt-scope",children:f}),s.jsxs("dl",{className:"receipt-rows",children:[s.jsx(Pr,{label:"mandate",children:s.jsx("strong",{children:o||qx(e.profileId)})}),i&&s.jsx(Pr,{label:"owner",children:i}),p&&s.jsx(Pr,{label:"allowed",children:p}),m&&s.jsx(Pr,{label:"used",children:s.jsx("span",{className:"receipt-num",children:m})}),s.jsx(Pr,{label:"intent",children:w?s.jsx("span",{className:"receipt-intent",children:w}):s.jsx("span",{className:"receipt-absent",children:r?"local store unreachable — sign in to the gateway to read it":"not on this device — the Authority Server stores only its hash"})})]}),s.jsxs("div",{className:"receipt-foot",children:[a==="valid"&&s.jsx("span",{className:"receipt-verified",title:"Ed25519 signature checked on this device against the issuer key archived when the ticket was issued — no Authority Server involved.",children:"✓ Verified on this device"}),a==="invalid"&&s.jsx("span",{className:"receipt-tamper",title:"The stored ticket does not match what was signed.",children:"⚠ Signature check FAILED"}),s.jsx("button",{type:"button",className:"receipt-evidence-link",onClick:d,children:"Complete ticket"}),l&&s.jsxs("span",{className:"receipt-public",children:["redacted, shareable:"," ",s.jsx("a",{className:"receipt-link",href:`${l}/r/${e.id}`,target:"_blank",rel:"noreferrer",children:"public link ↗"})]})]}),s.jsxs("details",{className:"receipt-more",children:[s.jsx("summary",{children:"Raw"}),s.jsxs("div",{className:"receipt-kv",children:[s.jsxs("div",{children:["ticket · ",e.id]}),s.jsxs("div",{children:["action · ",e.action]}),s.jsxs("div",{children:["profile · ",e.profileId]}),e.authorizationId&&s.jsxs("div",{children:["mandate · ",e.authorizationId]}),Object.keys(e.executionContext??{}).length>0&&s.jsxs("div",{children:["scope ·"," ",Object.entries(e.executionContext).map(([x,k])=>`${x}=${k}`).join(" · ")]}),(n==null?void 0:n.boundsHash)&&s.jsxs("div",{children:["bounds hash · ",n.boundsHash]}),(n==null?void 0:n.contextHash)&&s.jsxs("div",{children:["scope hash · ",n.contextHash]}),e.contentHash&&s.jsxs("div",{children:["content · ",e.contentHash]}),e.proposalId&&s.jsxs("div",{children:["proposal · ",e.proposalId]}),s.jsxs("div",{children:["signature · ",e.signature]})]})]})]})}function e0({receipt:e,onClose:t}){const[n,r]=u.useState(null),[a,o]=u.useState(null),[i,l]=u.useState(null),[c,d]=u.useState(!0),[f,p]=u.useState(!1);u.useEffect(()=>{let k=!1;return d(!0),T.getArchivedReceipt(e.id).then(g=>{k||(r(g),o(g?"local":"authority-server"),l((g==null?void 0:g.signature)??null))}).catch(()=>{k||o("authority-server")}).finally(()=>{k||d(!1)}),()=>{k=!0}},[e.id]);const m=n?n.entry:{receipt:e},w=JSON.stringify(m,null,2);function v(){const k=URL.createObjectURL(new Blob([w],{type:"application/json"})),g=document.createElement("a");g.href=k,g.download=`suveren-ticket-${e.id.slice(0,8)}.json`,g.click(),URL.revokeObjectURL(k)}async function x(){try{await navigator.clipboard.writeText(w),p(!0),setTimeout(()=>p(!1),2e3)}catch{p(!1)}}return s.jsx("div",{className:"modal-backdrop",onClick:k=>k.target===k.currentTarget&&t(),children:s.jsxs("div",{className:"modal",style:{maxWidth:"44rem"},children:[s.jsxs("div",{className:"modal-header",children:[s.jsx("h3",{className:"modal-title",children:"Complete ticket"}),s.jsx("button",{className:"modal-close",onClick:t,"aria-label":"Close",children:"×"})]}),s.jsxs("div",{className:"modal-body",children:[i==="valid"&&s.jsx("p",{className:"receipt-verified",style:{margin:"0 0 0.5rem",fontSize:"0.8rem"},children:"✓ Ed25519 signature verified on this device, against the issuer key archived when this ticket was issued."}),i==="invalid"&&s.jsx("p",{className:"receipt-tamper",style:{margin:"0 0 0.5rem",fontSize:"0.8rem"},children:"⚠ Signature check FAILED — the stored ticket does not match what was signed."}),s.jsx("p",{style:{fontSize:"0.8rem",color:"var(--text-muted)",margin:"0 0 0.75rem"},children:c?"Loading…":a==="local"?"Held on this device — the signed ticket, the mandate it ran under, and the issuer key. Anyone with this file and that key can verify it offline, without Suveren.":"No local copy of this ticket (it predates local archiving, or ran on another device). Shown from the Authority Server — complete and signed, but it needs the server to retrieve."}),s.jsx("pre",{style:{fontFamily:"'SF Mono', Monaco, monospace",fontSize:"0.68rem",lineHeight:1.65,margin:0,background:"var(--accent-subtle)",border:"1px solid var(--border)",borderRadius:"6px",padding:"0.75rem 0.85rem",overflowX:"auto",maxHeight:"22rem",overflowY:"auto"},children:w})]}),s.jsxs("div",{className:"modal-footer",children:[s.jsx("button",{className:"btn btn-primary btn-sm",onClick:v,children:"Download"}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:x,children:f?"Copied":"Copy"})]})]})})}function t0(e){return new Date(e*1e3).toLocaleString()}function n0(e,t){if(t==="all")return!0;const n=t==="1d"?1:t==="7d"?7:30,r=Math.floor(Date.now()/1e3)-n*86400;return e.timestamp>=r}function r0(e,t){if(!t)return!0;const n=t.toLowerCase();return e.profileId.toLowerCase().includes(n)||$e(e.profileId).toLowerCase().includes(n)||e.path.toLowerCase().includes(n)||e.action.toLowerCase().includes(n)||e.attestationHash.toLowerCase().includes(n)||e.id.toLowerCase().includes(n)||JSON.stringify(e.executionContext).toLowerCase().includes(n)}function vu(e,t){const n=new Map(e.map(r=>[r.id,r]));for(const r of t)n.set(r.id,r);return[...n.values()].sort((r,a)=>a.timestamp-r.timestamp)}function s0(){const{activeTeam:e,groupId:t}=Fe(),n=(e==null?void 0:e.isAdmin)===!0,[r,a]=u.useState("mine"),[o,i]=u.useState([]),[l,c]=u.useState([]),[d,f]=u.useState(""),[p,m]=u.useState(!0),[w,v]=u.useState({}),[x,k]=u.useState(new Set),[g,h]=u.useState(""),[y,S]=u.useState(new Set),[b,N]=u.useState(new Set),[C,I]=u.useState("all"),[E,$]=u.useState(!1),[U,V]=u.useState(!1),[J,D]=u.useState(null),[_,B]=u.useState({}),[ne,L]=u.useState(!1),[z,W]=u.useState({}),[R,F]=u.useState({}),[Q,q]=u.useState(null),[te,ce]=u.useState(null),[me,ee]=u.useState(!1),[oe,re]=u.useState(!1),A=u.useRef(""),X=u.useCallback(j=>r==="team"&&n&&t?T.listTeamReceiptsPage(t,{before:j,limit:200}):T.getMyReceiptsPage({before:j,limit:200}),[r,n,t]),ae=u.useCallback(()=>{const j=r==="team"?`team:${t}`:"mine",P=A.current!==j;A.current=j,m(!0),re(!1),X().then(O=>{i(G=>P?O.receipts:vu(G,O.receipts)),ce(G=>P?O.nextBefore:G??O.nextBefore)}).catch(()=>{P&&i([]),re(!0)}).finally(()=>m(!1))},[X,r,t]),ge=u.useCallback(()=>{!te||me||(ee(!0),re(!1),X(te).then(j=>{i(P=>vu(P,j.receipts)),ce(j.nextBefore)}).catch(()=>re(!0)).finally(()=>ee(!1)))},[te,me,X]);Pt(ae,12e4),u.useEffect(()=>{T.getIntegrationManifests().then(({manifests:j})=>c(j)).catch(()=>{}),fetch("/health").then(j=>j.json()).then(j=>{typeof j.spUrl=="string"&&f(j.spUrl.replace(/\/$/,""))}).catch(()=>{})},[]),u.useEffect(()=>{T.getLocalAuthorizations().then(({authorizations:j,signatures:P})=>{B(j),W(P),L(!1)}).catch(()=>{B({}),W({}),L(!0)}),T.getMyAttestations().then(j=>{const P={};for(const O of j)O.authorization_id&&O.title&&(P[O.authorization_id]=O.title);F(P)}).catch(()=>{})},[]),u.useEffect(()=>{r!=="team"||Object.keys(w).length>0||T.listUsers().then(j=>{const P={};for(const O of j)P[O.id]={name:O.name,email:O.email};v(P)}).catch(()=>{})},[r,w]);const he=u.useMemo(()=>{const j=new Set;for(const P of o)j.add($e(P.profileId));return[...j].sort()},[o]),Pe=u.useMemo(()=>{const j=new Set;for(const P of o)j.add(P.action);return[...j].sort()},[o]),qe=u.useMemo(()=>{if(r!=="team")return[];const j=new Set;for(const P of o)P.userId&&j.add(P.userId);return[...j].map(P=>{var O;return{id:P,label:(O=w[P])!=null&&O.name?`${w[P].name} (${w[P].email})`:P}}).sort((P,O)=>P.label.localeCompare(O.label))},[r,o,w]),_e=u.useMemo(()=>o.filter(j=>!(!r0(j,g)||y.size>0&&!y.has($e(j.profileId))||b.size>0&&!b.has(j.action)||x.size>0&&j.userId&&!x.has(j.userId)||!n0(j,C))),[o,g,y,b,x,C]),yt=y.size>0||b.size>0||x.size>0||C!=="all";function Ze(j){S(P=>{const O=new Set(P);return O.has(j)?O.delete(j):O.add(j),O})}function Ge(j){N(P=>{const O=new Set(P);return O.has(j)?O.delete(j):O.add(j),O})}function le(j){k(P=>{const O=new Set(P);return O.has(j)?O.delete(j):O.add(j),O})}function et(){S(new Set),N(new Set),k(new Set),I("all"),h("")}async function Ut(){V(!0),D(null);try{const{bundle:j,filename:P}=await T.fetchEvidenceBundle(),O=URL.createObjectURL(new Blob([JSON.stringify(j,null,2)],{type:"application/json"})),G=document.createElement("a");G.href=O,G.download=P,G.click(),URL.revokeObjectURL(O);const se=j.sources??{};se.authorityServer?se.local||D(`Downloaded Authority Server history only — ${se.localError??"local archive unavailable."}`):D(`Downloaded local evidence only — ${se.asError??"Authority Server export unavailable."}`)}catch(j){D(`Export failed: ${j instanceof Error?j.message:String(j)}`)}finally{V(!1)}}return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"page-header",style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",gap:"1rem",flexWrap:"wrap"},children:[s.jsxs("div",{children:[s.jsx("h1",{className:"page-title",children:"Tickets"}),s.jsx("p",{className:"page-subtitle",children:"Execution history for agent actions."})]}),s.jsx("button",{className:"btn btn-secondary",onClick:Ut,disabled:U,children:U?"Preparing…":"Download evidence"})]}),J&&s.jsx("div",{style:{marginBottom:"1rem",color:"var(--text-tertiary)",fontSize:"0.875rem"},children:J}),n&&s.jsx("div",{style:{display:"flex",gap:"0.5rem",marginBottom:"1rem",borderBottom:"1px solid var(--border)"},children:["mine","team"].map(j=>s.jsx("button",{onClick:()=>a(j),className:"btn btn-ghost",style:{borderRadius:0,padding:"0.5rem 0.875rem",borderBottom:r===j?"2px solid var(--accent)":"2px solid transparent",color:r===j?"var(--text-primary)":"var(--text-tertiary)",fontWeight:r===j?600:500},children:j==="mine"?"Mine":"Team"},j))}),s.jsxs("div",{className:"search-filter-bar",children:[s.jsxs("div",{className:"search-input-wrap",children:[s.jsx("span",{className:"search-icon",children:"⌕"}),s.jsx("input",{type:"text",className:"form-input search-input",placeholder:"Search by profile, action, path, or hash\\u2026",value:g,onChange:j=>h(j.target.value)}),g&&s.jsx("button",{className:"search-clear",onClick:()=>h(""),children:"×"})]}),s.jsxs("button",{className:`btn btn-sm btn-secondary${E?" active":""}`,onClick:()=>$(!E),children:["Filters",yt?` (${y.size+b.size+(C!=="all"?1:0)})`:""]})]}),E&&s.jsxs("div",{className:"filter-panel",children:[he.length>1&&s.jsxs("div",{className:"filter-section",children:[s.jsx("div",{className:"filter-label",children:"Profile"}),s.jsx("div",{className:"filter-chips",children:he.map(j=>s.jsx("button",{className:`filter-chip${y.has(j)?" selected":""}`,onClick:()=>Ze(j),children:j},j))})]}),Pe.length>1&&s.jsxs("div",{className:"filter-section",children:[s.jsx("div",{className:"filter-label",children:"Action"}),s.jsx("div",{className:"filter-chips",children:Pe.map(j=>s.jsx("button",{className:`filter-chip${b.has(j)?" selected":""}`,onClick:()=>Ge(j),children:j},j))})]}),r==="team"&&qe.length>1&&s.jsxs("div",{className:"filter-section",children:[s.jsx("div",{className:"filter-label",children:"Owner"}),s.jsx("div",{className:"filter-chips",children:qe.map(j=>s.jsx("button",{className:`filter-chip${x.has(j.id)?" selected":""}`,onClick:()=>le(j.id),children:j.label},j.id))})]}),s.jsxs("div",{className:"filter-section",children:[s.jsx("div",{className:"filter-label",children:"Time range"}),s.jsx("div",{className:"filter-chips",children:[["1d","Today"],["7d","7 days"],["30d","30 days"],["all","All time"]].map(([j,P])=>s.jsx("button",{className:`filter-chip${C===j?" selected":""}`,onClick:()=>I(j),children:P},j))})]})]}),yt&&s.jsxs("div",{className:"active-filters",children:[[...y].map(j=>s.jsxs("span",{className:"active-chip",onClick:()=>Ze(j),children:[j," ",s.jsx("span",{className:"chip-remove",children:"×"})]},j)),[...b].map(j=>s.jsxs("span",{className:"active-chip",onClick:()=>Ge(j),children:[j," ",s.jsx("span",{className:"chip-remove",children:"×"})]},j)),[...x].map(j=>{const P=w[j],O=P?P.name:j;return s.jsxs("span",{className:"active-chip",onClick:()=>le(j),children:[O," ",s.jsx("span",{className:"chip-remove",children:"×"})]},j)}),C!=="all"&&s.jsxs("span",{className:"active-chip",onClick:()=>I("all"),children:[C==="1d"?"Today":C==="7d"?"7 days":"30 days"," ",s.jsx("span",{className:"chip-remove",children:"×"})]}),s.jsx("button",{className:"clear-filters",onClick:et,children:"Clear all"})]}),oe&&s.jsx("div",{className:"card",style:{borderColor:"var(--danger, #c0392b)",marginBottom:"0.75rem"},children:s.jsx("span",{style:{color:"var(--danger, #c0392b)",fontSize:"0.85rem"},children:"Couldn’t load tickets — your session may have expired. Try signing out and back in."})}),p&&o.length===0?s.jsx("p",{style:{color:"var(--text-tertiary)"},children:"Loading..."}):_e.length===0?s.jsx(Em,{icon:"⌕",title:o.length===0?"No tickets in the last 30 days":"No matching tickets",text:o.length===0?"Tickets appear here after an agent uses an authorized tool. Older tickets can be loaded below.":"Try adjusting your search or filters."}):s.jsxs(s.Fragment,{children:[s.jsx("div",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)",marginBottom:"0.75rem"},children:_e.length===o.length?`${o.length} ticket${o.length!==1?"s":""}`:`${_e.length} of ${o.length} tickets`}),s.jsx("div",{className:"timeline",children:_e.map(j=>{const P=j.userId?w[j.userId]:void 0;return s.jsx("div",{className:"timeline-event",children:s.jsx(Zx,{receipt:j,manifests:l,localAuth:j.authorizationId?_[j.authorizationId]:void 0,localUnavailable:ne,signature:z[j.id],grantTitle:j.authorizationId?R[j.authorizationId]:null,ownerLabel:r==="team"&&j.userId?P?`${P.name} (${P.email})`:j.userId:null,spUrl:d,formatDate:t0,onOpenComplete:()=>q(j)})},j.id)})})]}),Q&&s.jsx(e0,{receipt:Q,onClose:()=>q(null)}),te&&s.jsx("div",{style:{textAlign:"center",marginTop:"1rem"},children:s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:ge,disabled:me,children:me?"Loading…":"Load older"})})]})}const a0={darwin:"a macOS login item",win32:"a Windows scheduled task",linux:"a systemd user service"};function o0(){const[e,t]=u.useState(null),[n,r]=u.useState(!1),[a,o]=u.useState(null),i=u.useCallback(async()=>{try{t(await T.getAutostart())}catch(d){o(d instanceof Error?d.message:"Could not read autostart state")}},[]);u.useEffect(()=>{i()},[i]);const l=u.useCallback(async()=>{if(!(!(e!=null&&e.supported)||n)){r(!0),o(null);try{await T.setAutostart(!e.installed)}catch(d){o(d instanceof Error?d.message:"Failed")}finally{try{t(await T.getAutostart()),o(null)}catch(d){o(d instanceof Error?d.message:"Could not re-read state")}r(!1)}}},[e,n,i]);if(!e)return s.jsxs("div",{className:"card",style:{padding:"1.5rem",marginTop:"2rem"},children:[s.jsx("h2",{style:{fontSize:"1rem",fontWeight:700,margin:0},children:"Keep Suveren running"}),s.jsx("p",{role:a?"alert":void 0,style:{margin:"0.5rem 0 0",fontSize:"0.9rem",color:"var(--text-secondary)"},children:a?`Could not read autostart state: ${a}`:"Checking…"})]});const c=a0[e.platform]??"a login service";return s.jsxs("div",{className:"card",style:{padding:"1.5rem",marginTop:"2rem"},children:[s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",gap:"1rem"},children:[s.jsxs("div",{children:[s.jsx("h2",{style:{fontSize:"1rem",fontWeight:700,margin:0},children:"Keep Suveren running"}),s.jsx("p",{style:{color:"var(--text-secondary)",margin:"0.5rem 0 0",fontSize:"0.9rem"},children:e.supported?s.jsxs(s.Fragment,{children:["Starts automatically when you log in, and restarts if it crashes. Uses ",c," — no admin rights needed."]}):e.reason})]}),e.supported&&s.jsx("button",{type:"button",onClick:()=>void l(),disabled:n,"aria-pressed":e.installed,className:e.installed?"btn btn-secondary":"btn btn-primary",style:{whiteSpace:"nowrap"},children:n?"Working…":e.installed?"Turn off":"Turn on"})]}),e.supported&&s.jsxs("p",{style:{margin:"1rem 0 0",fontSize:"0.85rem",color:"var(--text-tertiary)"},children:["Status: ",s.jsx("strong",{children:e.installed?"On — starts from your next login":"Off"})]}),e.supported&&s.jsxs("p",{style:{margin:"0.5rem 0 0",fontSize:"0.85rem",color:"var(--text-tertiary)"},children:["Turning this on doesn't interrupt the gateway you're using — it takes effect at your next login. After any restart Suveren comes back ",s.jsx("strong",{children:"locked"}),": you enter your API key once to unlock it, because nothing stored on this machine can unlock it for you."]}),a&&s.jsx("p",{role:"alert",style:{margin:"0.75rem 0 0",fontSize:"0.85rem",color:"var(--danger, #c00)"},children:a})]})}function i0(){const[e,t]=u.useState(null),[n,r]=u.useState(!1),[a,o]=u.useState(null),i=u.useCallback(async()=>{try{const c=await T.getGatewaySettings();t(c.desktopNotifications),o(null)}catch(c){o(c instanceof Error?c.message:"Could not read notification setting")}},[]);u.useEffect(()=>{i()},[i]);const l=u.useCallback(async()=>{if(!(e===null||n)){r(!0),o(null);try{const c=await T.setGatewaySettings({desktopNotifications:!e});t(c.desktopNotifications)}catch(c){o(c instanceof Error?c.message:"Failed to save"),await i()}finally{r(!1)}}},[e,n,i]);return e===null?s.jsxs("div",{className:"card",style:{padding:"1.5rem",marginTop:"2rem"},children:[s.jsx("h2",{style:{fontSize:"1rem",fontWeight:700,margin:0},children:"Desktop notifications"}),s.jsx("p",{role:a?"alert":void 0,style:{margin:"0.5rem 0 0",fontSize:"0.9rem",color:"var(--text-secondary)"},children:a?`Could not read the setting: ${a}`:"Checking…"})]}):s.jsxs("div",{className:"card",style:{padding:"1.5rem",marginTop:"2rem"},children:[s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",gap:"1rem"},children:[s.jsxs("div",{children:[s.jsx("h2",{style:{fontSize:"1rem",fontWeight:700,margin:0},children:"Desktop notifications"}),s.jsx("p",{style:{color:"var(--text-secondary)",margin:"0.5rem 0 0",fontSize:"0.9rem"},children:"Tells you something is waiting for review — never what it is, and never with an approve button. Open Suveren to see and decide. At most one notification a minute; the browser tab always shows the count."})]}),s.jsx("button",{type:"button",onClick:()=>void l(),disabled:n,"aria-pressed":e,className:e?"btn btn-secondary":"btn btn-primary",style:{whiteSpace:"nowrap"},children:n?"Saving…":e?"Turn off":"Turn on"})]}),a&&s.jsx("p",{role:"alert",style:{margin:"0.75rem 0 0",fontSize:"0.85rem",color:"var(--danger)"},children:a})]})}const l0={npm:"Checking npm for new releases",docker:"Checking the container registry for new images",dev:"Git checkout — comparing against origin/main, not npm releases",managed:"Checking npm for new releases — managed by your IT",msi:"Checking for new releases — update with the Windows installer"};function c0(){const{version:e,latestVersion:t,updateAvailable:n,installMethod:r}=Ol();return e?s.jsxs("div",{className:"card",style:{padding:"1.5rem",marginTop:"2rem"},children:[s.jsx("h2",{style:{fontSize:"1rem",fontWeight:700,margin:0},children:"Version"}),s.jsxs("p",{style:{margin:"0.5rem 0 0",fontSize:"0.9rem",color:"var(--text-secondary)"},children:["Running ",s.jsx("strong",{children:e}),n&&t?s.jsxs(s.Fragment,{children:[" — ",s.jsx("strong",{children:t})," is available"]}):null]}),s.jsxs("p",{style:{margin:"0.5rem 0 0",fontSize:"0.85rem",color:"var(--text-tertiary)"},children:[l0[r]??"Update checking is unavailable",r==="dev"&&s.jsx(s.Fragment,{children:" — a development checkout is not told about published releases."})]})]}):null}function $i({title:e}){return s.jsxs("span",{className:"it-locked-badge",title:e,children:[s.jsx("span",{className:"lock-icon","aria-hidden":"true",children:"🔒"})," Set by your IT"]})}function xu(e){return e===!0}function u0(){const[e,t]=u.useState(null),[n,r]=u.useState(null);u.useEffect(()=>{let i=!1;return T.getAsPairing().then(l=>{i||t(l)}).catch(l=>{i||r(l instanceof Error?l.message:"Could not read Authority Server info")}),()=>{i=!0}},[]);const a=xu(e==null?void 0:e.asUrlLockedByPolicy),o=xu(e==null?void 0:e.pinTlsLockedByPolicy);return s.jsxs("div",{className:"card",style:{padding:"1.5rem",marginTop:"2rem"},children:[s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",gap:"1rem"},children:[s.jsx("h2",{style:{fontSize:"1rem",fontWeight:700,margin:0},children:"Authority Server"}),a&&s.jsx($i,{})]}),!e&&!n&&s.jsx("p",{style:{margin:"0.5rem 0 0",fontSize:"0.9rem",color:"var(--text-secondary)"},children:"Checking…"}),n&&s.jsx("p",{role:"alert",style:{margin:"0.5rem 0 0",fontSize:"0.9rem",color:"var(--danger, #c00)"},children:n}),e&&s.jsxs(s.Fragment,{children:[s.jsxs("p",{style:{margin:"0.5rem 0 0",fontSize:"0.9rem",color:"var(--text-secondary)"},children:[s.jsx("strong",{children:"URL:"})," ",s.jsx("code",{children:e.asUrl})]}),e.paired&&e.fingerprint?s.jsxs("p",{style:{margin:"0.5rem 0 0",fontSize:"0.9rem",color:"var(--text-secondary)"},children:[s.jsx("strong",{children:"Key fingerprint:"})," ",s.jsx("code",{children:e.fingerprint}),s.jsx("br",{}),s.jsx("span",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)"},children:"Compare this with the fingerprint on the Authority Server's own admin page over a second channel (phone, video call) to confirm this gateway is talking to the right server."})]}):s.jsx("p",{style:{margin:"0.5rem 0 0",fontSize:"0.85rem",color:"var(--text-tertiary)"},children:"Not yet paired — sign in once to pin this server's key."}),(e.tlsPinFingerprint||e.pinTlsEnabled)&&s.jsxs("p",{style:{margin:"0.5rem 0 0",fontSize:"0.9rem",color:"var(--text-secondary)"},children:[s.jsx("strong",{children:"TLS certificate pin:"})," ",o&&s.jsx($i,{title:"TLS pinning is set by your IT policy"})," ",e.tlsPinFingerprint?s.jsx("code",{children:e.tlsPinFingerprint}):s.jsxs("span",{style:{color:"var(--text-tertiary)"},children:["not yet captured — this URL has no recorded pairing over TLS",e.pinTlsEnabled?"; sign in to establish one (re-pairing required)":""]}),s.jsx("br",{}),s.jsxs("span",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)"},children:[e.pinTlsEnabled?s.jsxs(s.Fragment,{children:["TLS pinning is ON",o?s.jsx(s.Fragment,{children:", set by your organization's IT policy"}):s.jsxs(s.Fragment,{children:[" (",s.jsx("code",{children:"config set pin-tls on"}),")"]}),". Every connection to the Authority Server must present this certificate's public key, or the gateway refuses it and locks."]}):s.jsxs(s.Fragment,{children:["Captured at sign-in; not currently enforced",o?s.jsx(s.Fragment,{children:" — controlled by your organization's IT policy on this computer"}):s.jsxs(s.Fragment,{children:[" (",s.jsx("code",{children:"config set pin-tls on"})," to require it on every connection)"]}),"."]})," ","A certificate renewal with the SAME key keeps this pin; a NEW key needs re-pairing."]})]}),a?s.jsx("p",{style:{margin:"0.75rem 0 0",fontSize:"0.8rem",color:"var(--text-tertiary)"},children:"This Authority Server URL is set by your organization's IT policy and cannot be changed from this computer. Contact your IT administrator if it needs to change."}):s.jsxs("p",{style:{margin:"0.75rem 0 0",fontSize:"0.8rem",color:"var(--text-tertiary)"},children:["To point this gateway at a different Authority Server:"," ",s.jsx("code",{children:"suveren-gateway config set as-url <url>"}),", then restart. Changing it ends the current sign-in and clears cached mandates — you sign in again against the new server."]})]})]})}function d0(e){if(!e||typeof e!="object")return{simulation:null,locked:!1};const t=Array.isArray(e.policyLocked)&&e.policyLocked.includes("simulation");return{simulation:typeof e.simulation=="boolean"?e.simulation:null,locked:t}}function f0(){const[e,t]=u.useState({simulation:null,locked:!1});return u.useEffect(()=>{let n=!1;return fetch("/health").then(r=>r.json()).then(r=>{n||t(d0(r))}).catch(()=>{}),()=>{n=!0}},[]),e}function m0(){const{simulation:e,locked:t}=f0();return t?s.jsxs("div",{className:"card",style:{padding:"1.5rem",marginTop:"2rem"},children:[s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",gap:"1rem"},children:[s.jsxs("div",{children:[s.jsx("h2",{style:{fontSize:"1rem",fontWeight:700,margin:0},children:"Simulation mode"}),s.jsxs("p",{style:{color:"var(--text-secondary)",margin:"0.5rem 0 0",fontSize:"0.9rem"},children:['Blocks every real connector without a manifest "simulation" marker.',e!==null&&s.jsxs(s.Fragment,{children:[" ","Currently ",s.jsx("strong",{children:e?"ON":"OFF"}),e?" — real systems are not reachable from this gateway.":"."]})]})]}),s.jsx($i,{})]}),s.jsxs("p",{style:{margin:"1rem 0 0",fontSize:"0.78rem",color:"var(--text-tertiary)"},children:["Simulation mode is set by your organization's IT policy",e!==null?` (currently ${e?"on":"off"})`:""," and cannot be changed from this computer — not even from the command line."]})]}):null}const p0={ollama:{provider:"ollama",endpoint:"http://localhost:11434",models:["gemma4:e4b","gemma4:e2b","gemma4:26b","gemma4:31b","llama3.2","llama3.1","mistral","qwen2.5"]},openrouter:{provider:"openai-compatible",endpoint:"https://openrouter.ai/api/v1",models:["google/gemma-4-31b-it","qwen/qwen3.6-plus:free","stepfun/step-3.5-flash:free","google/gemini-2.5-flash","openai/gpt-4o-mini","anthropic/claude-haiku-4"]},openai:{provider:"openai-compatible",endpoint:"https://api.openai.com/v1",models:["gpt-4o-mini","gpt-4o","o3-mini"]},groq:{provider:"openai-compatible",endpoint:"https://api.groq.com/openai/v1",models:["llama-3.1-8b-instant","llama-3.3-70b-versatile","gemma2-9b-it"]},together:{provider:"openai-compatible",endpoint:"https://api.together.xyz/v1",models:["meta-llama/Llama-3-8b-chat-hf","meta-llama/Llama-3-70b-chat-hf"]}},_r=["AI Assistant","Authority Server","This computer","Security","Version"],Ar={fontSize:"1rem",fontWeight:700,marginBottom:"1rem"};function h0(){const[e,t]=u.useState(""),[n,r]=u.useState("openrouter"),[a,o]=u.useState("openai-compatible"),[i,l]=u.useState("https://openrouter.ai/api/v1"),[c,d]=u.useState("google/gemma-4-31b-it"),[f,p]=u.useState(""),[m,w]=u.useState(!1),[v,x]=u.useState(!1),[k,g]=u.useState(!1),[h,y]=u.useState(null),[S,b]=u.useState([]),[N,C]=u.useState(!1),[I,E]=u.useState(null),[$,U]=u.useState(""),V=u.useCallback(z=>{t(z),setTimeout(()=>t(""),3e3)},[]),J=u.useCallback(async(z,W,R)=>{C(!0),E(null);try{const F=await T.aiModels({provider:z,endpoint:W,...R?{apiKey:R}:{}});F.ok&&F.models.length>0?(b(F.models),E(`${F.models.length} models available`)):(b([]),E(F.message||"No models returned — using defaults"))}catch(F){b([]),E(F instanceof Error?F.message:"Failed to load models")}finally{C(!1)}},[]),D=u.useCallback(async()=>{try{const z=await T.getCredential("ai-config");if(w(z.configured),z.configured&&z.fields){const W=z.fields.provider||"openai-compatible",R=z.fields.endpoint||"";z.fields.provider&&o(W),z.fields.endpoint&&l(R),z.fields.model&&d(z.fields.model),R.includes("openai.com")?r("openai"):R.includes("groq.com")?r("groq"):R.includes("together.xyz")?r("together"):R.includes("openrouter.ai")?r("openrouter"):r("ollama"),R&&J(W,R)}}catch{}},[J]);u.useEffect(()=>{D()},[D]);const _=z=>{r(z),b([]),E(null),U("");const W=p0[z];W&&(o(W.provider),l(W.endpoint),d(""),J(W.provider,W.endpoint,f||void 0))},B=()=>J(a,i,f||void 0),ne=async()=>{x(!0);try{await T.setCredential("ai-config",{provider:a,endpoint:i,model:c,...f?{apiKey:f}:{}}),w(!0),V("AI configuration saved!")}catch{V("Failed to save AI config")}finally{x(!1)}},L=async()=>{g(!0),y(null);try{const z=await T.aiTest({provider:a,endpoint:i,model:c,...f?{apiKey:f}:{}});y(z.ok?`OK: ${z.message}`:`Failed: ${z.message}`)}catch(z){y(`Error: ${z instanceof Error?z.message:"Unknown"}`)}finally{g(!1)}};return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"page-header",children:[s.jsx("h1",{className:"page-title",children:"Settings"}),s.jsx("p",{className:"page-subtitle",children:"Your AI assistant, the connection to your Authority Server, security and version."})]}),e&&s.jsx("div",{className:"alert alert-success",children:e}),s.jsxs("section",{style:{marginBottom:"2rem"},children:[s.jsx("h2",{style:Ar,children:_r[0]}),s.jsx("p",{style:{fontSize:"0.85rem",color:"var(--text-secondary)",marginBottom:"1rem"},children:"Advisory AI to help you think through intent when giving mandates."}),s.jsxs("div",{className:"card",children:[s.jsx("h3",{className:"card-title",children:"Configuration"}),s.jsx("p",{style:{fontSize:"0.85rem",color:"var(--text-secondary)",marginBottom:"1rem"},children:"Connect a trusted AI model that has access to your intent — problem, objective, and tradeoffs — to help you think through mandates. Keys are encrypted in your vault."}),m&&s.jsxs("div",{className:"status-banner status-banner-success",style:{marginBottom:"1rem",fontSize:"0.8rem"},children:[s.jsx("span",{className:"status-banner-icon",children:"✓"}),s.jsx("span",{className:"status-banner-text",children:"AI configured"})]}),s.jsxs("div",{className:"form-group",style:{marginBottom:"0.75rem"},children:[s.jsx("label",{className:"form-label",children:"Provider Preset"}),s.jsxs("select",{className:"form-input",value:n,onChange:z=>_(z.target.value),children:[s.jsx("option",{value:"openrouter",children:"OpenRouter (recommended)"}),s.jsx("option",{value:"ollama",children:"Ollama (local)"}),s.jsx("option",{value:"openai",children:"OpenAI"}),s.jsx("option",{value:"groq",children:"Groq"}),s.jsx("option",{value:"together",children:"Together"})]})]}),s.jsxs("div",{className:"form-group",style:{marginBottom:"0.75rem"},children:[s.jsxs("label",{className:"form-label",children:["API Key ",a==="ollama"?"(not needed for Ollama)":"(required to load models)"]}),s.jsx("input",{className:"form-input",type:"password",name:"ai-provider-api-key-credential-top",autoComplete:"new-password",value:f,onChange:z=>p(z.target.value),onBlur:()=>{f.trim()&&J(a,i,f.trim())},placeholder:m?"••••••••••••••••":"sk-... (not needed for Ollama)"}),s.jsx("p",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",margin:"0.375rem 0 0"},children:"Each provider uses its own key — paste it and the model list loads automatically."})]}),s.jsxs("div",{className:"form-group",style:{marginBottom:"0.75rem"},children:[s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[s.jsx("label",{className:"form-label",children:"Model"}),s.jsx("button",{type:"button",className:"btn btn-ghost",style:{fontSize:"0.75rem",padding:"0.125rem 0.5rem"},onClick:B,disabled:N,title:"Re-fetch the model list from the provider",children:N?"Loading…":"↻ Refresh"})]}),S.length===0?s.jsx("div",{className:"form-input",style:{display:"flex",alignItems:"center",minHeight:"2.5rem",color:"var(--text-secondary)",fontSize:"0.85rem"},children:N?"Loading models…":a==="ollama"?"Start Ollama locally, then ↻ Refresh to load models.":"Enter a valid API key above to load available models."}):(()=>{const z=S,W=z.includes(c),R=z.length>12,F=$.trim().toLowerCase();let Q=F?z.filter(q=>q.toLowerCase().includes(F)):z;return W&&!Q.includes(c)&&(Q=[c,...Q]),s.jsxs(s.Fragment,{children:[R&&s.jsx("input",{className:"form-input",value:$,onChange:q=>U(q.target.value),placeholder:"Filter models… (e.g. kimi)",style:{marginBottom:"0.375rem"}}),s.jsxs("select",{className:"form-input",value:W?c:"__unset__",onChange:q=>d(q.target.value==="__unset__"?"":q.target.value),children:[s.jsx("option",{value:"__unset__",disabled:!0,children:"Select a model…"}),Q.map(q=>s.jsx("option",{value:q,children:q},q)),F&&Q.length===0&&s.jsxs("option",{value:"__unset__",disabled:!0,children:["No models match “",$,"”"]})]})]})})(),I&&s.jsx("p",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",margin:"0.375rem 0 0"},children:I})]}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem",alignItems:"center"},children:[s.jsx("button",{className:"btn btn-primary",onClick:ne,disabled:v||!c.trim(),title:c.trim()?void 0:"Select a model first",children:v?"Saving...":"Save & Encrypt"}),m&&s.jsx("button",{className:"btn btn-ghost",onClick:L,disabled:k,children:k?"Testing...":"Test Connection"})]}),h&&s.jsx("div",{className:`alert ${h.startsWith("OK")?"alert-success":"alert-error"}`,style:{marginTop:"0.75rem"},children:h})]}),s.jsx(g0,{})]}),s.jsxs("section",{style:{marginBottom:"2rem"},children:[s.jsx("h2",{style:Ar,children:_r[1]}),s.jsx(u0,{})]}),s.jsxs("section",{style:{marginBottom:"2rem"},children:[s.jsx("h2",{style:Ar,children:_r[2]}),s.jsx(o0,{}),s.jsx(i0,{}),s.jsx(m0,{})]}),s.jsxs("section",{style:{marginBottom:"2rem"},children:[s.jsx("h2",{style:Ar,children:_r[3]}),s.jsx("div",{className:"card",style:{padding:"1.5rem"},children:s.jsxs("div",{style:{fontSize:"0.85rem",color:"var(--text-secondary)",lineHeight:1.7},children:[s.jsxs("div",{style:{marginBottom:"1rem"},children:[s.jsx("div",{style:{fontWeight:600,color:"var(--text-primary)",marginBottom:"0.375rem"},children:"What the gateway protects"}),s.jsxs("ul",{style:{margin:0,paddingLeft:"1.25rem"},children:[s.jsx("li",{children:"Every tool call verified against your mandate bounds"}),s.jsx("li",{children:"Credentials never exposed to agents through MCP"}),s.jsx("li",{children:"Every action produces a signed ticket"})]})]}),s.jsxs("div",{children:[s.jsx("div",{style:{fontWeight:600,color:"var(--text-primary)",marginBottom:"0.375rem"},children:"Your responsibility"}),s.jsxs("ul",{style:{margin:0,paddingLeft:"1.25rem"},children:[s.jsx("li",{children:"If your AI agent has full access to your computer, it could bypass the gateway"}),s.jsx("li",{children:"For best security, run agents in sandboxed environments"}),s.jsx("li",{children:"The gateway secures what agents do through tools — not what they do on your machine"})]})]})]})})]}),s.jsxs("section",{children:[s.jsx("h2",{style:Ar,children:_r[4]}),s.jsx(c0,{})]})]})}function g0(){const[e,t]=u.useState(null),[n,r]=u.useState({intent:"",context:""}),[a,o]=u.useState(null),[i,l]=u.useState(null),[c,d]=u.useState(null),[f,p]=u.useState(!1),m=u.useCallback(async()=>{if(!f)try{const x=await T.getAIPrompts();t(x),r({intent:x.intent.current,context:x.context.current}),p(!0)}catch(x){l(x instanceof Error?x.message:"Failed to load prompts")}},[f]),w=async x=>{if(e){o(x),l(null);try{const k=n[x],g=k.trim()===e[x].default.trim()?"":k;await T.setAIPrompt(x,g);const h=await T.getAIPrompts();t(h),r({intent:h.intent.current,context:h.context.current}),d(x),setTimeout(()=>d(null),2e3)}catch(k){l(k instanceof Error?k.message:"Save failed")}finally{o(null)}}},v=async x=>{if(confirm(`Revert ${x} prompt to the built-in default?`)){o(x),l(null);try{await T.setAIPrompt(x,"");const k=await T.getAIPrompts();t(k),r({intent:k.intent.current,context:k.context.current})}catch(k){l(k instanceof Error?k.message:"Revert failed")}finally{o(null)}}};return s.jsxs("details",{className:"card",style:{padding:"1.5rem",marginTop:"1rem"},onToggle:x=>{x.currentTarget.open&&m()},children:[s.jsx("summary",{style:{fontSize:"1rem",fontWeight:700,cursor:"pointer",listStyle:"revert",userSelect:"none"},children:"Advanced — AI assistant prompts"}),s.jsx("p",{style:{fontSize:"0.85rem",color:"var(--text-secondary)",margin:"0.75rem 0 1rem 0",lineHeight:1.55},children:"These are the system prompts the AI assistant sees when helping you write Intent (per-mandate) or Context (your standing-orders brief). Edit with care — changes apply on the next chat turn."}),i&&s.jsx("div",{className:"alert alert-error",style:{marginBottom:"0.75rem"},children:i}),!f&&!i&&s.jsx("p",{style:{color:"var(--text-muted)",fontSize:"0.85rem"},children:"Loading prompts…"}),e&&s.jsxs(s.Fragment,{children:[s.jsx(wu,{kind:"intent",label:"Intent — per-mandate",description:"Used on the Intent gate when creating a new mandate.",state:e.intent,draft:n.intent,onChange:x=>r(k=>({...k,intent:x})),onSave:()=>w("intent"),onRevert:()=>v("intent"),saving:a==="intent",justSaved:c==="intent"}),s.jsx(wu,{kind:"context",label:"Context — standing-orders brief",description:"Used on the Brief page when refining your context.md.",state:e.context,draft:n.context,onChange:x=>r(k=>({...k,context:x})),onSave:()=>w("context"),onRevert:()=>v("context"),saving:a==="context",justSaved:c==="context"})]})]})}function wu({kind:e,label:t,description:n,state:r,draft:a,onChange:o,onSave:i,onRevert:l,saving:c,justSaved:d}){const f=a!==r.current;return s.jsxs("section",{style:{marginBottom:"1.5rem"},children:[s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"baseline",marginBottom:"0.25rem",gap:"1rem",flexWrap:"wrap"},children:[s.jsxs("div",{children:[s.jsx("div",{style:{fontWeight:600,fontSize:"0.9rem"},children:t}),s.jsx("div",{style:{fontSize:"0.78rem",color:"var(--text-secondary)"},children:n})]}),r.overridden&&s.jsx("span",{style:{fontSize:"0.7rem",color:"var(--accent)",fontWeight:600,textTransform:"uppercase",letterSpacing:"0.05em"},children:"Custom"})]}),s.jsx("textarea",{className:"form-textarea",value:a,onChange:p=>o(p.target.value),rows:12,spellCheck:!1,style:{width:"100%",fontFamily:"'SF Mono', Monaco, 'Cascadia Code', monospace",fontSize:"0.82rem",lineHeight:1.55,resize:"vertical",minHeight:"14rem",marginTop:"0.5rem"},"aria-label":`${t} system prompt`}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem",alignItems:"center",marginTop:"0.5rem",flexWrap:"wrap"},children:[s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:i,disabled:c||!f,children:c?"Saving…":"Save"}),r.overridden&&s.jsx("button",{type:"button",className:"btn btn-ghost btn-sm",onClick:l,disabled:c,title:"Discard the override and use the built-in default",children:"Revert to default"}),d&&s.jsx("span",{style:{fontSize:"0.78rem",color:"var(--success)"},children:"Saved"}),f&&!c&&!d&&s.jsx("span",{style:{fontSize:"0.78rem",color:"var(--text-muted)"},children:"Unsaved changes"})]}),s.jsxs("details",{style:{marginTop:"0.5rem"},children:[s.jsx("summary",{style:{fontSize:"0.78rem",color:"var(--text-muted)",cursor:"pointer"},children:"Show built-in default"}),s.jsx("pre",{style:{marginTop:"0.5rem",padding:"0.75rem 1rem",background:"var(--bg-main)",border:"1px solid var(--border)",borderRadius:"0.5rem",fontSize:"0.78rem",lineHeight:1.55,whiteSpace:"pre-wrap",maxHeight:"20rem",overflowY:"auto"},children:r.default})]}),s.jsx("span",{style:{display:"none"},children:e})]})}function y0(e){return e.proposalId?"review":"automatic"}function Su(e,t,n={}){const r=n.status??"pending",a=n.includeAutonomous??!1,o=[];for(const i of e)r==="pending"&&i.status!=="pending"||n.profile&&i.profileId!==n.profile||o.push({kind:"proposal",id:i.id,sortTimestamp:i.createdAt,commitmentMode:"review",profileId:i.profileId,proposal:i});if(r==="all")for(const i of t){const l=y0(i);!a&&l==="automatic"||n.profile&&i.profileId!==n.profile||o.push({kind:"receipt",id:i.id,sortTimestamp:i.timestamp,commitmentMode:l,profileId:i.profileId,receipt:i})}return o.sort((i,l)=>l.sortTimestamp-i.sortTimestamp),typeof n.limit=="number"&&n.limit>0?o.slice(0,n.limit):o}const v0=["https://","http://"];function Tm(e,t){return e!=null&&e.length?e.flatMap(n=>{const r=n.template.replace(/\{(\w+)\}/g,(a,o)=>{const i=t[o];return typeof i=="string"||typeof i=="number"?String(i):"\0"});return r.includes("\0")||/\{|\}/.test(r)?[]:v0.some(a=>r.toLowerCase().startsWith(a))?[{label:n.label,href:r,description:n.description}]:[]}):[]}function x0({profileId:e}){return s.jsx("span",{className:"profile-badge",children:$e(e)})}function Im(e,t){const n=e-Math.floor(t/1e3);if(n<=0)return{label:"expired",urgent:!1,expired:!0};const r=Math.floor(n/86400),a=Math.floor(n%86400/3600),o=Math.floor(n%3600/60);let i;return r>0?i=`expires in ${r}d ${a}h`:a>0?i=`expires in ${a}h ${o}m`:i=`expires in ${Math.max(1,o)}m`,{label:i,urgent:n<2*3600,expired:!1}}const w0={pending:"Pending",committed:"Approved",executed:"Executed",rejected:"Rejected",expired:"Expired"},S0={pending:"status-pending",committed:"status-active",executed:"status-active",rejected:"status-revoked",expired:"status-expired"};function j0(e){const t=Date.now()-e*1e3,n=t/36e5;return n<48?n<1?`${Math.max(1,Math.round(t/6e4))}m ago`:`${Math.round(n)}h ago`:new Date(e*1e3).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function k0(e){return e.split("__").pop()??e}function b0(e){const t=e.toLowerCase();return t.includes("delete")||t.includes("refund")||t.includes("cancel")||t.includes("revoke")}const C0=new Set(["apiKey","api_key","accessToken","access_token","password","secret","signature","_imagePreview"]),N0=/^(image|img|photo|picture|thumbnail)(_?url)?$/i;function E0(e,t){return typeof t!="string"?!1:/^data:image\//i.test(t)?!0:N0.test(e)?/^https?:\/\//.test(t):/^https?:\/\/.+\.(jpe?g|png|gif|webp|svg|avif)(\?|$)/i.test(t)}function Li(e){if(e==null)return"—";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);if(Array.isArray(e))return e.map(t=>Li(t)).join(", ");try{return JSON.stringify(e,null,2)}catch{return String(e)}}function ju({item:e,onApprove:t,onReject:n,resolving:r,proposalLinks:a}){const o=e.kind==="proposal",i=o?e.proposal.status:"executed",l=o?e.proposal.tool:e.receipt.action,c=k0(l),d=b0(l),f=o?e.proposal.toolArgs:null,p=o?e.proposal.executionContext:e.receipt.executionContext,m=o?null:e.receipt.cumulativeState,w=o?Tm(a,e.proposal.toolArgs):[],v=f?Object.entries(f).filter(([k])=>!C0.has(k)):[],x=Object.entries(p??{});return s.jsxs("div",{className:"card",children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem",marginBottom:"0.75rem",flexWrap:"wrap"},children:[s.jsx(x0,{profileId:e.profileId}),s.jsx("code",{style:{fontSize:"0.85rem"},children:c}),e.commitmentMode==="automatic"&&s.jsx("span",{style:{fontSize:"0.7rem",color:"var(--text-tertiary)",textTransform:"uppercase",letterSpacing:"0.04em"},children:"autonomous"}),s.jsxs("span",{style:{marginLeft:"auto",display:"flex",alignItems:"center",gap:"0.5rem"},children:[o&&i==="pending"&&(()=>{const k=Im(e.proposal.expiresAt,Date.now());return s.jsx("span",{style:{fontSize:"0.72rem",color:k.urgent?"var(--warning)":"var(--text-tertiary)",fontWeight:k.urgent?600:400,whiteSpace:"nowrap"},children:k.label})})(),s.jsx("span",{className:`status-badge ${S0[i]}`,children:w0[i]}),s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-tertiary)"},children:j0(e.sortTimestamp)})]})]}),d&&s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.4rem",fontSize:"0.8rem",color:"var(--warning)",background:"var(--bg-main)",border:"1px solid var(--border)",borderRadius:"0.375rem",padding:"0.4rem 0.6rem",marginBottom:"0.75rem"},children:[s.jsx("span",{children:"⚠"}),s.jsx("span",{children:"Irreversible action"})]}),o&&typeof(f==null?void 0:f._imagePreview)=="string"&&s.jsxs("div",{style:{marginBottom:"0.75rem"},children:[s.jsx("div",{style:{fontSize:"0.7rem",fontWeight:600,color:"var(--text-tertiary)",textTransform:"uppercase",letterSpacing:"0.04em",marginBottom:"0.35rem"},children:"Preview"}),s.jsx("img",{src:f._imagePreview,alt:typeof(f==null?void 0:f.altText)=="string"?f.altText:"local image preview",style:{display:"block",maxWidth:"100%",maxHeight:"240px",borderRadius:"0.375rem",border:"1px solid var(--border)"}})]}),w.length>0&&s.jsx("div",{style:{marginBottom:"0.75rem",display:"flex",gap:"0.5rem",flexWrap:"wrap"},children:w.map(k=>s.jsxs("a",{href:k.href,target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm",style:{textDecoration:"none"},title:k.description??k.href,children:[k.label," ↗"]},k.label))}),o&&v.length>0&&s.jsxs("div",{style:{marginBottom:"0.75rem"},children:[s.jsx("div",{style:{fontSize:"0.7rem",fontWeight:600,color:"var(--text-tertiary)",textTransform:"uppercase",letterSpacing:"0.04em",marginBottom:"0.35rem"},children:"Arguments"}),s.jsx("dl",{style:{display:"grid",gridTemplateColumns:"max-content 1fr",gap:"0.2rem 0.75rem",fontSize:"0.85rem",margin:0},children:v.map(([k,g])=>s.jsxs(u.Fragment,{children:[s.jsx("dt",{style:{color:"var(--text-tertiary)",whiteSpace:"nowrap",alignSelf:"start"},children:k}),s.jsx("dd",{style:{color:"var(--text-primary)",margin:0,wordBreak:"break-word",whiteSpace:"pre-wrap"},children:E0(k,g)?s.jsx("img",{src:g,alt:typeof(f==null?void 0:f.altText)=="string"?f.altText:k,style:{display:"block",maxWidth:"100%",maxHeight:"240px",borderRadius:"0.375rem",border:"1px solid var(--border)"},onError:h=>{const y=h.currentTarget,S=y.parentElement;if(!S)return;y.style.display="none";const b=document.createElement("span");b.textContent=g,b.style.color="var(--text-tertiary)",S.appendChild(b)}}):Li(g)})]},k))})]}),x.length>0&&s.jsx("div",{style:{marginBottom:"0.75rem",fontSize:"0.8rem",color:"var(--text-secondary)"},children:x.map(([k,g])=>`${k}=${Li(g)}`).join(" · ")}),m&&s.jsxs("div",{style:{fontSize:"0.75rem",color:"var(--text-tertiary)",marginBottom:"0.5rem"},children:["After this action · today: ",m.daily.count," action",m.daily.count===1?"":"s",m.daily.amount>0?`, ${m.daily.amount}`:""," · ","this month: ",m.monthly.count,m.monthly.amount>0?`, ${m.monthly.amount}`:""]}),o&&i==="pending"&&s.jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[s.jsx("button",{className:"btn btn-primary",onClick:()=>t==null?void 0:t(e.id),disabled:r,children:r?"Approving…":"Approve"}),s.jsx("button",{className:"btn btn-ghost",style:{color:"var(--danger)"},onClick:()=>n==null?void 0:n(e.id),disabled:r,children:"Reject"})]}),s.jsxs("div",{style:{marginTop:"0.5rem",fontSize:"0.7rem",color:"var(--text-tertiary)"},children:[o?"Proposal":"Ticket",": ",e.id]})]})}const T0=new Set(["apiKey","api_key","accessToken","access_token","password","secret","signature","_imagePreview"]);function Mi(e){if(e==null)return"—";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);if(Array.isArray(e))return e.map(t=>Mi(t)).join(", ");try{return JSON.stringify(e,null,2)}catch{return String(e)}}function I0(e){const t=Date.now()-e*1e3,n=Math.floor(t/6e4);if(n<60)return`${Math.max(1,n)}m ago`;const r=Math.floor(t/36e5);return r<48?`${r}h ago`:`${Math.floor(r/24)}d ago`}function R0({proposal:e,currentUserId:t,onAction:n,onMessage:r,proposalLinks:a}){const[o,i]=u.useState(!1),[l,c]=u.useState(!1),[d,f]=u.useState(null),[p,m]=u.useState(!1),[w,v]=u.useState(null),[x,k]=u.useState(!1),g=e.tool.split("__").pop()??e.tool,h=Object.entries(e.toolArgs).filter(([_])=>!T0.has(_)),y=Object.entries(e.executionContext),S=Tm(a,e.toolArgs),b=e.pendingApprovers??[],N=e.approvedBy??{},C=Object.keys(N).length,I=b.filter(_=>!(_ in N)).length,E=t in N,$=async()=>{if(d===null){m(!0),v(null);try{const _=await T.getAttestationIntent(e.authorizationId);if(!_){v("Intent not available or you are not an authorized approver.");return}const B=await T.decryptIntent({intentCiphertext:_.intentCiphertext,encryptedKey:_.encryptedKey,approverId:t});f(B)}catch(_){v(_ instanceof Error?_.message:"Failed to decrypt intent")}finally{m(!1)}}},U=async()=>{x?k(!1):(k(!0),await $())},V=async()=>{i(!0),r("");try{await T.approveProposal(e.id);try{if(d===null){const _=await T.getAttestationIntent(e.authorizationId);if(_){const B=await T.decryptIntent({intentCiphertext:_.intentCiphertext,encryptedKey:_.encryptedKey,approverId:t});f(B),await T.storeApprovedIntent(e.authorizationId,B)}}else await T.storeApprovedIntent(e.authorizationId,d)}catch{}r(`Approved. ${I-1>0?`${I-1} more approver(s) still needed.`:"All approvers signed off — action is ready to execute."}`),n()}catch(_){r(_ instanceof Error?_.message:"Approval failed")}finally{i(!1)}},J=async()=>{const _=prompt("Rejection reason (optional):");if(_!==null){c(!0),r("");try{await T.rejectProposal(e.id,_||void 0),r("Action rejected."),n()}catch(B){r(B instanceof Error?B.message:"Rejection failed")}finally{c(!1)}}},D=o||l;return s.jsxs("div",{className:"card",children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem",marginBottom:"0.5rem",flexWrap:"wrap"},children:[s.jsx("span",{style:{fontWeight:600,fontSize:"0.9rem"},children:$e(e.profileId)}),s.jsx("span",{style:{fontSize:"0.65rem",padding:"0.15rem 0.4rem",borderRadius:"0.25rem",background:"var(--accent-subtle)",color:"var(--accent)",fontWeight:600},children:"Above cap"}),s.jsxs("span",{style:{marginLeft:"auto",display:"flex",alignItems:"center",gap:"0.5rem"},children:[(()=>{const _=Im(e.expiresAt,Date.now());return s.jsx("span",{style:{fontSize:"0.72rem",color:_.urgent?"var(--warning)":"var(--text-tertiary)",fontWeight:_.urgent?600:400,whiteSpace:"nowrap"},children:_.label})})(),s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-tertiary)"},children:I0(e.createdAt)})]})]}),s.jsxs("div",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)",marginBottom:"0.5rem"},children:[C," of ",b.length," approver",b.length===1?"":"s"," signed off",b.map(_=>{const B=_ in N;return s.jsxs("span",{style:{marginLeft:"0.5rem",color:B?"var(--success, green)":"var(--text-tertiary)"},children:[B?"✓":"○"," ",_===t?"You":_]},_)})]}),s.jsxs("div",{style:{marginBottom:"0.5rem"},children:[s.jsx("div",{style:{fontSize:"0.7rem",fontWeight:600,color:"var(--text-tertiary)",textTransform:"uppercase",letterSpacing:"0.04em",marginBottom:"0.25rem"},children:"Proposed action"}),s.jsx("code",{style:{fontSize:"0.85rem"},children:g})]}),S.length>0&&s.jsx("div",{style:{marginBottom:"0.75rem",display:"flex",gap:"0.5rem",flexWrap:"wrap"},children:S.map(_=>s.jsxs("a",{href:_.href,target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm",style:{textDecoration:"none"},title:_.description??_.href,children:[_.label," ↗"]},_.label))}),h.length>0&&s.jsxs("div",{style:{marginBottom:"0.75rem"},children:[s.jsx("div",{style:{fontSize:"0.7rem",fontWeight:600,color:"var(--text-tertiary)",textTransform:"uppercase",letterSpacing:"0.04em",marginBottom:"0.25rem"},children:"Arguments"}),s.jsx("dl",{style:{display:"grid",gridTemplateColumns:"max-content 1fr",gap:"0.2rem 0.75rem",fontSize:"0.85rem",margin:0},children:h.map(([_,B])=>s.jsxs(u.Fragment,{children:[s.jsx("dt",{style:{color:"var(--text-tertiary)",whiteSpace:"nowrap",alignSelf:"start"},children:_}),s.jsx("dd",{style:{color:"var(--text-primary)",margin:0,wordBreak:"break-word",whiteSpace:"pre-wrap"},children:Mi(B)})]},_))})]}),y.length>0&&s.jsx("div",{style:{fontSize:"0.8rem",color:"var(--text-secondary)",marginBottom:"0.5rem"},children:y.map(([_,B])=>`${_}=${Mi(B)}`).join(" · ")}),s.jsxs("div",{style:{marginBottom:"0.75rem"},children:[s.jsxs("button",{className:"btn btn-ghost btn-sm",style:{padding:"0.2rem 0",fontSize:"0.75rem"},onClick:U,disabled:p,children:[x?"▲ Hide intent":"▼ Show intent",p&&" (decrypting...)"]}),x&&s.jsx("div",{style:{marginTop:"0.5rem",padding:"0.75rem",background:"var(--bg-main)",borderRadius:"0.375rem",border:"1px solid var(--border)"},children:w?s.jsx("p",{style:{color:"var(--danger)",fontSize:"0.8rem",margin:0},children:w}):d!==null?s.jsx("p",{style:{fontSize:"0.85rem",margin:0,whiteSpace:"pre-wrap",color:"var(--text-primary)"},children:d}):s.jsx("p",{style:{color:"var(--text-tertiary)",fontSize:"0.8rem",margin:0},children:"No intent available for this mandate."})})]}),!E&&s.jsxs("div",{style:{display:"flex",gap:"0.5rem",marginTop:"0.25rem"},children:[s.jsx("button",{className:"btn btn-primary",onClick:V,disabled:D,children:o?"Approving...":"Approve"}),s.jsx("button",{className:"btn btn-ghost",style:{color:"var(--danger)"},onClick:J,disabled:D,children:l?"Rejecting...":"Reject"})]}),E&&s.jsx("p",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)",marginTop:"0.25rem"},children:"You approved this action. Waiting on other approvers."}),s.jsxs("div",{style:{marginTop:"0.5rem",fontSize:"0.7rem",color:"var(--text-tertiary)"},children:["Proposal: ",e.id]})]})}function P0(){const{domain:e,user:t}=Fe(),n=(t==null?void 0:t.id)??"",[r,a]=u.useState("awaiting-me"),[o,i]=u.useState([]),[l,c]=u.useState([]),[d,f]=u.useState(!0),[p,m]=u.useState(""),w=u.useCallback(async()=>{try{const A=await T.getProposalsForApprover();i(A)}catch{}finally{f(!1)}},[]);fe("proposal-added",w),fe("proposal-approved",w),fe("proposal-rejected",w),fe("proposal-resolved",w),Pt(w,3e4);const[v,x]=u.useState([]),k=u.useCallback(async()=>{try{const A=await T.getProposals(e||"owner");x(A)}catch{}},[e]);fe("proposal-added",k),fe("proposal-approved",k),fe("proposal-rejected",k),fe("proposal-resolved",k),Pt(k,3e4,e);const g=u.useMemo(()=>v.filter(A=>{var X;return A.status==="pending"&&(((X=A.pendingApprovers)==null?void 0:X.length)??0)===0}),[v]),h=u.useMemo(()=>Su(g,[],{status:"pending"}),[g]),[y,S]=u.useState([]),b=u.useCallback(async()=>{if(n)try{const X=(await T.getProposals(e||"owner")).filter(ae=>ae.status==="pending"&&ae.pendingApprovers&&ae.pendingApprovers.includes(n)&&ae.approvedBy&&n in ae.approvedBy);S(X)}catch{}},[n,e]);fe("proposal-approved",b),fe("proposal-rejected",b),Pt(b,3e4,`${n}:${e}`),u.useEffect(()=>{T.getIntegrationManifests().then(A=>c(A.manifests??[])).catch(()=>{})},[]);const N=A=>{var X;return(X=l.find(ae=>ae.id===A.split("__")[0]))==null?void 0:X.proposalLinks};u.useEffect(()=>{w(),k(),b()},[]);const[C,I]=u.useState([]),[E,$]=u.useState([]),[U,V]=u.useState(!0),[J,D]=u.useState(null),[_,B]=u.useState(""),[ne,L]=u.useState("pending"),[z,W]=u.useState(null),[R,F]=u.useState(!1),Q=u.useCallback(async()=>{try{const{proposals:A,receipts:X}=await T.getThread({domain:e,status:ne,sinceDays:7});I(A),$(X)}catch{}finally{V(!1)}},[e,ne]);Pt(Q,3e4,`${e}:${ne}`);const q=async(A,X)=>{D(A),B("");try{const ae=e||"owner",ge=await T.resolveProposal(A,X,ae);B(X==="commit"?`Action approved. Status: ${ge.status}`:"Action rejected."),await Promise.all([Q(),k()])}catch(ae){B(ae instanceof Error?ae.message:"Failed")}finally{D(null)}},te=u.useMemo(()=>{const A=new Set;for(const X of C)A.add(X.profileId);for(const X of E)A.add(X.profileId);return Array.from(A).sort()},[C,E]),ce=u.useMemo(()=>Su(C,E,{status:ne,profile:z??void 0,includeAutonomous:R}),[C,E,ne,z,R]),me=u.useCallback(()=>{w(),b()},[w,b]),ee=u.useMemo(()=>{const A=new Set,X=[];for(const ae of y)A.has(ae.id)||(A.add(ae.id),X.push(ae));return X.sort((ae,ge)=>ge.createdAt-ae.createdAt)},[y]),oe=o.length+h.length,re=ee.length;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"page-header",children:[s.jsx("h1",{className:"page-title",children:"Pending Approvals"}),s.jsx("p",{className:"page-subtitle",children:"Actions awaiting approval, plus recent activity from the last 7 days."})]}),s.jsxs("div",{className:"nav-tabs",style:{marginBottom:"1rem"},children:[s.jsxs("button",{className:`nav-tab${r==="awaiting-me"?" active":""}`,onClick:()=>a("awaiting-me"),children:["Awaiting me ",oe>0&&s.jsx("span",{style:{marginLeft:"0.4rem",background:"var(--warning)",color:"var(--bg-elevated)",borderRadius:"0.625rem",padding:"0 0.375rem",fontSize:"0.7rem",fontWeight:600},children:oe})]}),s.jsxs("button",{className:`nav-tab${r==="awaiting-others"?" active":""}`,onClick:()=>a("awaiting-others"),children:["Awaiting others ",re>0&&s.jsx("span",{style:{marginLeft:"0.4rem",background:"var(--border)",color:"var(--text-secondary)",borderRadius:"0.625rem",padding:"0 0.375rem",fontSize:"0.7rem",fontWeight:600},children:re})]}),s.jsx("button",{className:`nav-tab${r==="all"?" active":""}`,onClick:()=>{a("all"),Q()},children:"All"})]}),r==="awaiting-me"&&s.jsx(s.Fragment,{children:d&&oe===0?s.jsx("p",{style:{color:"var(--text-tertiary)"},children:"Loading..."}):oe===0?s.jsxs("div",{className:"card",style:{textAlign:"center",padding:"2rem"},children:[s.jsx("p",{style:{color:"var(--text-tertiary)",marginBottom:"0.5rem"},children:"No actions awaiting your approval."}),s.jsx("p",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)"},children:"Review-mode actions and above-cap actions you must approve will appear here."})]}):s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"1rem"},children:[(p||_)&&s.jsx("div",{className:"alert alert-success",children:p||_}),h.map(A=>s.jsx(ju,{proposalLinks:A.kind==="proposal"?N(A.proposal.tool):void 0,item:A,onApprove:X=>q(X,"commit"),onReject:X=>q(X,"reject"),resolving:J===A.id},A.id)),o.map(A=>s.jsx(R0,{proposal:A,currentUserId:n,onAction:me,onMessage:m,proposalLinks:N(A.tool)},A.id))]})}),r==="awaiting-others"&&s.jsx(s.Fragment,{children:ee.length===0?s.jsxs("div",{className:"card",style:{textAlign:"center",padding:"2rem"},children:[s.jsx("p",{style:{color:"var(--text-tertiary)",marginBottom:"0.5rem"},children:"No actions waiting on others."}),s.jsx("p",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)"},children:"Actions you proposed or approved that are pending other approvers will appear here."})]}):s.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"1rem"},children:ee.map(A=>s.jsx(A0,{proposal:A,currentUserId:n,onCancel:async()=>{try{await T.rejectProposal(A.id,"cancelled by creator"),b(),k()}catch(X){alert(X instanceof Error?X.message:"Cancel failed")}}},A.id))})}),r==="all"&&s.jsxs(s.Fragment,{children:[_&&s.jsx("div",{className:"alert alert-success",style:{marginBottom:"1rem"},children:_}),s.jsxs("div",{className:"filter-chips",style:{marginBottom:"1rem"},children:[s.jsx("button",{className:`filter-chip ${ne==="pending"?"selected":""}`,onClick:()=>L("pending"),children:"Pending"}),s.jsx("button",{className:`filter-chip ${ne==="all"?"selected":""}`,onClick:()=>L("all"),children:"All"}),te.length>0&&s.jsx("span",{style:{width:1,background:"var(--border)",alignSelf:"stretch",margin:"0 0.25rem"}}),te.map(A=>s.jsx("button",{className:`filter-chip ${z===A?"selected":""}`,onClick:()=>W(z===A?null:A),children:$e(A)},A)),ne==="all"&&s.jsxs(s.Fragment,{children:[s.jsx("span",{style:{width:1,background:"var(--border)",alignSelf:"stretch",margin:"0 0.25rem"}}),s.jsxs("button",{className:`filter-chip ${R?"selected":""}`,onClick:()=>F(!R),title:"Include actions executed without human review (automatic commitment mode)",children:[R?"✓ ":"","Autonomous actions"]})]})]}),U&&ce.length===0?s.jsx("p",{style:{color:"var(--text-tertiary)"},children:"Loading..."}):ce.length===0?s.jsxs("div",{className:"card",style:{textAlign:"center",padding:"2rem"},children:[s.jsx("p",{style:{color:"var(--text-tertiary)",marginBottom:"0.5rem"},children:ne==="pending"?"No actions awaiting your approval.":"Nothing here yet."}),s.jsx("p",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)"},children:ne==="pending"?"Your agents are operating within their mandates. Switch to All to see recent activity.":"When an agent calls a gated tool, activity will appear here."})]}):s.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"1rem"},children:ce.map(A=>s.jsx(ju,{proposalLinks:A.kind==="proposal"?N(A.proposal.tool):void 0,item:A,onApprove:X=>q(X,"commit"),onReject:X=>q(X,"reject"),resolving:J===A.id},A.id))})]})]})}function _0(e){const t=Date.now()-e*1e3,n=Math.floor(t/6e4);if(n<60)return`${Math.max(1,n)}m ago`;const r=Math.floor(t/36e5);return r<48?`${r}h ago`:`${Math.floor(r/24)}d ago`}function A0({proposal:e,currentUserId:t,onCancel:n}){var d;const[r,a]=u.useState(!1),o=Object.keys(e.approvedBy??{}),i=(e.pendingApprovers??[]).filter(f=>!(f in(e.approvedBy??{}))),l=(((d=e.pendingApprovers)==null?void 0:d.length)??0)>0,c=async()=>{if(confirm("Cancel this action? All approvers will be notified.")){a(!0);try{await n()}finally{a(!1)}}};return s.jsxs("div",{className:"card",children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem",marginBottom:"0.5rem",flexWrap:"wrap"},children:[s.jsx("span",{style:{fontWeight:600,fontSize:"0.9rem"},children:$e(e.profileId)}),l&&s.jsx("span",{style:{fontSize:"0.65rem",padding:"0.15rem 0.4rem",borderRadius:"0.25rem",background:"var(--accent-subtle)",color:"var(--accent)",fontWeight:600},children:"Above cap"}),s.jsx("span",{style:{marginLeft:"auto",fontSize:"0.75rem",color:"var(--text-tertiary)"},children:_0(e.createdAt)})]}),s.jsx("div",{style:{fontSize:"0.85rem",color:"var(--text-secondary)",marginBottom:"0.5rem"},children:s.jsx("code",{children:e.tool.split("__").pop()??e.tool})}),l&&s.jsxs("div",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)",marginBottom:"0.5rem"},children:[o.map(f=>s.jsx("span",{style:{marginRight:"0.75rem",color:"var(--success, green)"},children:f===t?"You approved":`${f} approved`},f)),i.map(f=>s.jsxs("span",{style:{marginRight:"0.75rem",color:"var(--text-tertiary)"},children:["Waiting on ",f===t?"you":f]},f))]}),s.jsx("div",{style:{display:"flex",justifyContent:"flex-end",gap:"0.5rem",marginTop:"0.5rem"},children:s.jsx("button",{className:"btn btn-ghost btn-sm",style:{color:"var(--danger)"},onClick:c,disabled:r,children:r?"Cancelling...":"Cancel"})})]})}const z0=`# Agent Brief
75
75
 
76
76
  You act on my behalf through Suveren — the gateway that gates every
77
77
  privileged tool call you make. Suveren implements the bounded-authority
@@ -107,4 +107,4 @@ executes. When you propose an action:
107
107
  next.
108
108
  - Never email anyone outside the company without asking first.
109
109
  - When drafting posts, prefer plain language over marketing copy.
110
- `;function A0(){const[e,t]=u.useState(""),[n,r]=u.useState(""),[a,o]=u.useState(!0),[i,l]=u.useState(!1),[c,d]=u.useState(null),[f,p]=u.useState(!1),m=e!==n,w=new Blob([e]).size,v=16*1024;u.useEffect(()=>{if(!m)return;const h=S=>{S.preventDefault(),S.returnValue=""},y=S=>{var C,I;if(S.defaultPrevented||S.button!==0||S.metaKey||S.ctrlKey||S.shiftKey||S.altKey)return;const b=(I=(C=S.target)==null?void 0:C.closest)==null?void 0:I.call(C,"a");if(!b||!b.href)return;let N;try{N=new URL(b.href)}catch{return}N.origin===window.location.origin&&N.pathname!==window.location.pathname&&(confirm("You have unsaved changes to your agent brief. Leave anyway?")||(S.preventDefault(),S.stopPropagation()))};return window.addEventListener("beforeunload",h),document.addEventListener("click",y,!0),()=>{window.removeEventListener("beforeunload",h),document.removeEventListener("click",y,!0)}},[m]),u.useEffect(()=>{let h=!1;return T.getAgentContext().then(y=>{h||(t(y),r(y))}).catch(y=>{h||d({kind:"error",text:y instanceof Error?y.message:"Failed to load context"})}).finally(()=>{h||o(!1)}),()=>{h=!0}},[]);const x=async()=>{l(!0),d(null);try{await T.saveAgentContext(e),r(e),d({kind:"ok",text:"Saved. New MCP sessions will pick this up on next connect."})}catch(h){d({kind:"error",text:h instanceof Error?h.message:"Save failed"})}finally{l(!1)}},k=()=>{t(n),d(null)},g=()=>{e.trim()&&!confirm("Replace current context with the starter template?")||t(_0)};return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"page-header",children:[s.jsx("h1",{className:"page-title",children:"Agent Brief"}),s.jsx("p",{className:"page-subtitle",children:"Standing orders for agents that connect via MCP. This text prepends every new session — keep it tight."}),!e.trim()&&!a&&s.jsx("button",{className:"btn btn-primary btn-sm",onClick:g,disabled:i,title:"Insert a starter brief covering Suveren basics and example standing orders",style:{marginTop:"0.5rem"},children:"Insert starter template"})]}),c&&s.jsx("div",{className:c.kind==="ok"?"alert alert-success":"error-message",style:{marginBottom:"1rem"},children:c.text}),s.jsxs("div",{className:"intent-layout",style:{marginBottom:"1rem"},children:[s.jsx("div",{className:"card intent-pane chat",children:s.jsx(_a,{target:{kind:"context"},currentText:e,onApply:h=>{e.trim()&&!confirm("Replace the current context with the applied draft?")||t(h)},greeting:"Tell me what your agent should know — I'll help shape your standing orders. Or ask me to draft a full brief and we'll iterate.",placeholder:"Ask for help with your brief…"})}),s.jsxs("div",{className:"card intent-pane document",children:[s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"baseline",gap:"0.5rem",flexWrap:"wrap",marginBottom:"0.5rem"},children:[s.jsx("h3",{className:"card-title",style:{marginBottom:0},children:"context.md"}),s.jsxs("span",{style:{fontSize:"0.75rem",color:w>v?"var(--danger)":"var(--text-muted)"},children:[w.toLocaleString()," / ",v.toLocaleString()," bytes"]})]}),s.jsx("textarea",{className:"form-textarea",value:e,onChange:h=>t(h.target.value),placeholder:a?"Loading…":'Type your standing orders here, or click "Insert starter template" below.',disabled:a,rows:18,style:{fontFamily:"'SF Mono', Monaco, monospace",fontSize:"0.85rem",lineHeight:1.5,minHeight:"22rem"}}),s.jsxs("div",{className:"intent-footer",style:{marginTop:"0.75rem"},children:[s.jsx("button",{className:"btn btn-ghost",onClick:k,disabled:i||!m,children:"Revert"}),s.jsx("button",{className:"btn btn-primary",style:{flex:1},onClick:x,disabled:i||!m||w>v||a,children:i?"Saving…":"Save"})]})]}),s.jsx("button",{type:"button",className:"floating-help",onClick:()=>p(!0),"aria-label":"Open brief assistant",children:"Get help with brief"}),s.jsx(wm,{open:f,onClose:()=>p(!1),ariaLabel:"Brief assistant",children:s.jsx(_a,{target:{kind:"context"},currentText:e,onApply:h=>{e.trim()&&!confirm("Replace the current context with the applied draft?")||(t(h),p(!1))},greeting:"Tell me what your agent should know — I'll help shape your standing orders.",placeholder:"Ask for help with your brief…"})})]})]})}function Wn({to:e}){const{search:t,hash:n}=gt();return s.jsx(Gt,{to:`${e}${t}${n}`,replace:!0})}function z0({children:e}){const{user:t,mode:n,domain:r}=Fe();return t?n==="team"&&!r?s.jsx(Gt,{to:"/onboarding",replace:!0}):s.jsx(s.Fragment,{children:e}):s.jsx(Gt,{to:"/login",replace:!0})}function $0(){const{user:e,handleSessionLocked:t}=Fe();return fe("session-locked",n=>{const r=n==null?void 0:n.message;t(r)}),s.jsxs(ay,{children:[s.jsx(Se,{path:"/login",element:e?s.jsx(Gt,{to:"/",replace:!0}):s.jsx(bv,{})}),s.jsx(Se,{path:"/onboarding",element:e?s.jsx(Cv,{}):s.jsx(Gt,{to:"/login",replace:!0})}),s.jsxs(Se,{element:s.jsx(z0,{children:s.jsx(kv,{})}),children:[s.jsx(Se,{path:"/",element:s.jsx(Uv,{})}),s.jsx(Se,{path:"/mandates",element:s.jsx(Wx,{})}),s.jsx(Se,{path:"/mandates/new/intent",element:s.jsx(px,{})}),s.jsx(Se,{path:"/mandates/new/sign",element:s.jsx(jx,{})}),s.jsx(Se,{path:"/integrations",element:s.jsx(Ix,{})}),s.jsx(Se,{path:"/team",element:s.jsx(Rx,{})}),s.jsx(Se,{path:"/tickets",element:s.jsx(n0,{})}),s.jsx(Se,{path:"/approvals",element:s.jsx(I0,{})}),s.jsx(Se,{path:"/agent/new",element:s.jsx(Gt,{to:"/mandates?new=1",replace:!0})}),s.jsx(Se,{path:"/agent/gate",element:s.jsx(Wn,{to:"/mandates/new/intent"})}),s.jsx(Se,{path:"/agent/review",element:s.jsx(Wn,{to:"/mandates/new/sign"})}),s.jsx(Se,{path:"/authorizations",element:s.jsx(Wn,{to:"/mandates"})}),s.jsx(Se,{path:"/groups",element:s.jsx(Wn,{to:"/team"})}),s.jsx(Se,{path:"/audit",element:s.jsx(Wn,{to:"/tickets"})}),s.jsx(Se,{path:"/proposals",element:s.jsx(Wn,{to:"/approvals"})}),s.jsx(Se,{path:"/agent-brief",element:s.jsx(A0,{})}),s.jsx(Se,{path:"/settings",element:s.jsx(m0,{})}),s.jsx(Se,{path:"/settings/services",element:s.jsx(Gt,{to:"/settings",replace:!0})}),s.jsx(Se,{path:"/deploy",element:s.jsx(Gt,{to:"/integrations",replace:!0})})]}),s.jsx(Se,{path:"*",element:s.jsx(Gt,{to:"/",replace:!0})})]})}function L0(){return s.jsx(Ry,{children:s.jsx(By,{children:s.jsx(Dy,{children:s.jsx($0,{})})})})}Mf(document.getElementById("root")).render(s.jsx(u.StrictMode,{children:s.jsx(L0,{})}));
110
+ `;function $0(){const[e,t]=u.useState(""),[n,r]=u.useState(""),[a,o]=u.useState(!0),[i,l]=u.useState(!1),[c,d]=u.useState(null),[f,p]=u.useState(!1),m=e!==n,w=new Blob([e]).size,v=16*1024;u.useEffect(()=>{if(!m)return;const h=S=>{S.preventDefault(),S.returnValue=""},y=S=>{var C,I;if(S.defaultPrevented||S.button!==0||S.metaKey||S.ctrlKey||S.shiftKey||S.altKey)return;const b=(I=(C=S.target)==null?void 0:C.closest)==null?void 0:I.call(C,"a");if(!b||!b.href)return;let N;try{N=new URL(b.href)}catch{return}N.origin===window.location.origin&&N.pathname!==window.location.pathname&&(confirm("You have unsaved changes to your agent brief. Leave anyway?")||(S.preventDefault(),S.stopPropagation()))};return window.addEventListener("beforeunload",h),document.addEventListener("click",y,!0),()=>{window.removeEventListener("beforeunload",h),document.removeEventListener("click",y,!0)}},[m]),u.useEffect(()=>{let h=!1;return T.getAgentContext().then(y=>{h||(t(y),r(y))}).catch(y=>{h||d({kind:"error",text:y instanceof Error?y.message:"Failed to load context"})}).finally(()=>{h||o(!1)}),()=>{h=!0}},[]);const x=async()=>{l(!0),d(null);try{await T.saveAgentContext(e),r(e),d({kind:"ok",text:"Saved. New MCP sessions will pick this up on next connect."})}catch(h){d({kind:"error",text:h instanceof Error?h.message:"Save failed"})}finally{l(!1)}},k=()=>{t(n),d(null)},g=()=>{e.trim()&&!confirm("Replace current context with the starter template?")||t(z0)};return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"page-header",children:[s.jsx("h1",{className:"page-title",children:"Agent Brief"}),s.jsx("p",{className:"page-subtitle",children:"Standing orders for agents that connect via MCP. This text prepends every new session — keep it tight."}),!e.trim()&&!a&&s.jsx("button",{className:"btn btn-primary btn-sm",onClick:g,disabled:i,title:"Insert a starter brief covering Suveren basics and example standing orders",style:{marginTop:"0.5rem"},children:"Insert starter template"})]}),c&&s.jsx("div",{className:c.kind==="ok"?"alert alert-success":"error-message",style:{marginBottom:"1rem"},children:c.text}),s.jsxs("div",{className:"intent-layout",style:{marginBottom:"1rem"},children:[s.jsx("div",{className:"card intent-pane chat",children:s.jsx(_a,{target:{kind:"context"},currentText:e,onApply:h=>{e.trim()&&!confirm("Replace the current context with the applied draft?")||t(h)},greeting:"Tell me what your agent should know — I'll help shape your standing orders. Or ask me to draft a full brief and we'll iterate.",placeholder:"Ask for help with your brief…"})}),s.jsxs("div",{className:"card intent-pane document",children:[s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"baseline",gap:"0.5rem",flexWrap:"wrap",marginBottom:"0.5rem"},children:[s.jsx("h3",{className:"card-title",style:{marginBottom:0},children:"context.md"}),s.jsxs("span",{style:{fontSize:"0.75rem",color:w>v?"var(--danger)":"var(--text-muted)"},children:[w.toLocaleString()," / ",v.toLocaleString()," bytes"]})]}),s.jsx("textarea",{className:"form-textarea",value:e,onChange:h=>t(h.target.value),placeholder:a?"Loading…":'Type your standing orders here, or click "Insert starter template" below.',disabled:a,rows:18,style:{fontFamily:"'SF Mono', Monaco, monospace",fontSize:"0.85rem",lineHeight:1.5,minHeight:"22rem"}}),s.jsxs("div",{className:"intent-footer",style:{marginTop:"0.75rem"},children:[s.jsx("button",{className:"btn btn-ghost",onClick:k,disabled:i||!m,children:"Revert"}),s.jsx("button",{className:"btn btn-primary",style:{flex:1},onClick:x,disabled:i||!m||w>v||a,children:i?"Saving…":"Save"})]})]}),s.jsx("button",{type:"button",className:"floating-help",onClick:()=>p(!0),"aria-label":"Open brief assistant",children:"Get help with brief"}),s.jsx(wm,{open:f,onClose:()=>p(!1),ariaLabel:"Brief assistant",children:s.jsx(_a,{target:{kind:"context"},currentText:e,onApply:h=>{e.trim()&&!confirm("Replace the current context with the applied draft?")||(t(h),p(!1))},greeting:"Tell me what your agent should know — I'll help shape your standing orders.",placeholder:"Ask for help with your brief…"})})]})]})}function Wn({to:e}){const{search:t,hash:n}=gt();return s.jsx(Gt,{to:`${e}${t}${n}`,replace:!0})}function L0({children:e}){const{user:t,mode:n,domain:r}=Fe();return t?n==="team"&&!r?s.jsx(Gt,{to:"/onboarding",replace:!0}):s.jsx(s.Fragment,{children:e}):s.jsx(Gt,{to:"/login",replace:!0})}function M0(){const{user:e,handleSessionLocked:t}=Fe();return fe("session-locked",n=>{const r=n==null?void 0:n.message;t(r)}),s.jsxs(ay,{children:[s.jsx(Se,{path:"/login",element:e?s.jsx(Gt,{to:"/",replace:!0}):s.jsx(Nv,{})}),s.jsx(Se,{path:"/onboarding",element:e?s.jsx(Ev,{}):s.jsx(Gt,{to:"/login",replace:!0})}),s.jsxs(Se,{element:s.jsx(L0,{children:s.jsx(Cv,{})}),children:[s.jsx(Se,{path:"/",element:s.jsx(Hv,{})}),s.jsx(Se,{path:"/mandates",element:s.jsx(Vx,{})}),s.jsx(Se,{path:"/mandates/new/intent",element:s.jsx(gx,{})}),s.jsx(Se,{path:"/mandates/new/sign",element:s.jsx(bx,{})}),s.jsx(Se,{path:"/integrations",element:s.jsx(Px,{})}),s.jsx(Se,{path:"/team",element:s.jsx(_x,{})}),s.jsx(Se,{path:"/tickets",element:s.jsx(s0,{})}),s.jsx(Se,{path:"/approvals",element:s.jsx(P0,{})}),s.jsx(Se,{path:"/agent/new",element:s.jsx(Gt,{to:"/mandates?new=1",replace:!0})}),s.jsx(Se,{path:"/agent/gate",element:s.jsx(Wn,{to:"/mandates/new/intent"})}),s.jsx(Se,{path:"/agent/review",element:s.jsx(Wn,{to:"/mandates/new/sign"})}),s.jsx(Se,{path:"/authorizations",element:s.jsx(Wn,{to:"/mandates"})}),s.jsx(Se,{path:"/groups",element:s.jsx(Wn,{to:"/team"})}),s.jsx(Se,{path:"/audit",element:s.jsx(Wn,{to:"/tickets"})}),s.jsx(Se,{path:"/proposals",element:s.jsx(Wn,{to:"/approvals"})}),s.jsx(Se,{path:"/agent-brief",element:s.jsx($0,{})}),s.jsx(Se,{path:"/settings",element:s.jsx(h0,{})}),s.jsx(Se,{path:"/settings/services",element:s.jsx(Gt,{to:"/settings",replace:!0})}),s.jsx(Se,{path:"/deploy",element:s.jsx(Gt,{to:"/integrations",replace:!0})})]}),s.jsx(Se,{path:"*",element:s.jsx(Gt,{to:"/",replace:!0})})]})}function F0(){return s.jsx(Ry,{children:s.jsx(By,{children:s.jsx(Dy,{children:s.jsx(M0,{})})})})}Mf(document.getElementById("root")).render(s.jsx(u.StrictMode,{children:s.jsx(F0,{})}));