@suveren/gateway 0.8.1 → 0.8.3
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.
- package/content/integrations/deploy-github.json +3 -5
- package/dist/mcp-server/http.mjs +77 -66
- package/dist/ui/assets/{index-BFnSVa9N.js → index-76gJM-3o.js} +2 -2
- package/dist/ui/index.html +1 -1
- package/node_modules/jose/dist/types/index.d.ts +1 -2
- package/node_modules/jose/dist/types/jwe/compact/decrypt.d.ts +7 -11
- package/node_modules/jose/dist/types/jwe/compact/encrypt.d.ts +13 -16
- package/node_modules/jose/dist/types/jwe/flattened/decrypt.d.ts +7 -11
- package/node_modules/jose/dist/types/jwe/flattened/encrypt.d.ts +16 -19
- package/node_modules/jose/dist/types/jwe/general/decrypt.d.ts +10 -16
- package/node_modules/jose/dist/types/jwe/general/encrypt.d.ts +18 -21
- package/node_modules/jose/dist/types/jwk/embedded.d.ts +3 -1
- package/node_modules/jose/dist/types/jwk/thumbprint.d.ts +4 -6
- package/node_modules/jose/dist/types/jwks/local.d.ts +5 -4
- package/node_modules/jose/dist/types/jwks/remote.d.ts +20 -21
- package/node_modules/jose/dist/types/jws/compact/sign.d.ts +4 -4
- package/node_modules/jose/dist/types/jws/compact/verify.d.ts +8 -11
- package/node_modules/jose/dist/types/jws/flattened/sign.d.ts +5 -5
- package/node_modules/jose/dist/types/jws/flattened/verify.d.ts +8 -11
- package/node_modules/jose/dist/types/jws/general/sign.d.ts +10 -14
- package/node_modules/jose/dist/types/jws/general/verify.d.ts +11 -17
- package/node_modules/jose/dist/types/jwt/decrypt.d.ts +14 -11
- package/node_modules/jose/dist/types/jwt/encrypt.d.ts +24 -22
- package/node_modules/jose/dist/types/jwt/sign.d.ts +3 -7
- package/node_modules/jose/dist/types/jwt/unsecured.d.ts +2 -6
- package/node_modules/jose/dist/types/jwt/verify.d.ts +13 -6
- package/node_modules/jose/dist/types/key/export.d.ts +6 -6
- package/node_modules/jose/dist/types/key/generate_key_pair.d.ts +9 -14
- package/node_modules/jose/dist/types/key/generate_secret.d.ts +10 -10
- package/node_modules/jose/dist/types/key/import.d.ts +19 -18
- package/node_modules/jose/dist/types/types.d.ts +152 -247
- package/node_modules/jose/dist/types/util/base64url.d.ts +7 -7
- package/node_modules/jose/dist/types/util/decode_jwt.d.ts +6 -1
- package/node_modules/jose/dist/types/util/decode_protected_header.d.ts +4 -3
- package/node_modules/jose/dist/types/util/errors.d.ts +29 -40
- package/node_modules/jose/dist/webapi/jwe/compact/decrypt.js +1 -2
- package/node_modules/jose/dist/webapi/jwe/compact/encrypt.js +9 -26
- package/node_modules/jose/dist/webapi/jwe/flattened/decrypt.js +3 -3
- package/node_modules/jose/dist/webapi/jwe/flattened/encrypt.js +11 -30
- package/node_modules/jose/dist/webapi/jwe/general/decrypt.js +6 -6
- package/node_modules/jose/dist/webapi/jwe/general/encrypt.js +33 -57
- package/node_modules/jose/dist/webapi/jwk/embedded.js +3 -4
- package/node_modules/jose/dist/webapi/jwk/thumbprint.js +3 -6
- package/node_modules/jose/dist/webapi/jwks/local.js +16 -10
- package/node_modules/jose/dist/webapi/jwks/remote.js +2 -2
- package/node_modules/jose/dist/webapi/jws/compact/sign.js +2 -4
- package/node_modules/jose/dist/webapi/jws/compact/verify.js +2 -2
- package/node_modules/jose/dist/webapi/jws/flattened/sign.js +8 -15
- package/node_modules/jose/dist/webapi/jws/flattened/verify.js +4 -14
- package/node_modules/jose/dist/webapi/jws/general/sign.js +4 -11
- package/node_modules/jose/dist/webapi/jws/general/verify.js +5 -7
- package/node_modules/jose/dist/webapi/jwt/decrypt.js +2 -3
- package/node_modules/jose/dist/webapi/jwt/encrypt.js +11 -25
- package/node_modules/jose/dist/webapi/jwt/sign.js +1 -1
- package/node_modules/jose/dist/webapi/jwt/unsecured.js +1 -2
- package/node_modules/jose/dist/webapi/jwt/verify.js +4 -4
- package/node_modules/jose/dist/webapi/key/export.js +12 -16
- package/node_modules/jose/dist/webapi/key/generate_key_pair.js +4 -13
- package/node_modules/jose/dist/webapi/key/generate_secret.js +1 -1
- package/node_modules/jose/dist/webapi/key/import.js +5 -9
- package/node_modules/jose/dist/webapi/lib/asn1.js +2 -4
- package/node_modules/jose/dist/webapi/lib/buffer_utils.js +35 -0
- package/node_modules/jose/dist/webapi/lib/content_encryption.js +21 -29
- package/node_modules/jose/dist/webapi/lib/deflate.js +9 -19
- package/node_modules/jose/dist/webapi/lib/jwe_algorithms.js +0 -4
- package/node_modules/jose/dist/webapi/lib/jwe_decrypt.js +21 -54
- package/node_modules/jose/dist/webapi/lib/jwe_encrypt.js +26 -59
- package/node_modules/jose/dist/webapi/lib/jws_sign.js +29 -43
- package/node_modules/jose/dist/webapi/lib/jws_verify.js +37 -45
- package/node_modules/jose/dist/webapi/lib/jwt_claims_set.js +1 -1
- package/node_modules/jose/dist/webapi/lib/key.js +119 -59
- package/node_modules/jose/dist/webapi/lib/key_management.js +45 -80
- package/node_modules/jose/dist/webapi/lib/{options.js → validate.js} +64 -3
- package/node_modules/jose/dist/webapi/util/base64url.js +5 -19
- package/node_modules/jose/dist/webapi/util/decode_jwt.js +1 -1
- package/node_modules/jose/dist/webapi/util/decode_protected_header.js +1 -1
- package/node_modules/jose/package.json +1 -1
- package/package.json +1 -1
- package/profiles/deploy/0.10.profile.json +178 -0
- package/profiles/index.json +1 -0
- package/node_modules/jose/dist/webapi/lib/base64.js +0 -20
- package/node_modules/jose/dist/webapi/lib/crypto_key.js +0 -27
- package/node_modules/jose/dist/webapi/lib/helpers.js +0 -45
- package/node_modules/jose/dist/webapi/lib/invalid_key_input.js +0 -12
- package/node_modules/jose/dist/webapi/lib/is_key_like.js +0 -19
- package/node_modules/jose/dist/webapi/lib/jwk_metadata.js +0 -19
- package/node_modules/jose/dist/webapi/lib/jwk_to_key.js +0 -10
- package/node_modules/jose/dist/webapi/lib/key_options.js +0 -8
- package/node_modules/jose/dist/webapi/lib/signing.js +0 -22
- package/node_modules/jose/dist/webapi/lib/type_checks.js +0 -30
|
@@ -48,7 +48,7 @@ Error generating stack: `+o.message+`
|
|
|
48
48
|
* @license MIT
|
|
49
49
|
*/var Mc="popstate";function Fc(e){return typeof e=="object"&&e!=null&&"pathname"in e&&"search"in e&&"hash"in e&&"state"in e&&"key"in e}function zh(e={}){function t(r,s){var d;let o=(d=s.state)==null?void 0:d.masked,{pathname:i,search:l,hash:c}=o||r.location;return gi("",{pathname:i,search:l,hash:c},s.state&&s.state.usr||null,s.state&&s.state.key||"default",o?{pathname:r.location.pathname,search:r.location.search,hash:r.location.hash}:void 0)}function n(r,s){return typeof s=="string"?s:is(s)}return Rh(t,n,null,e)}function xe(e,t){if(e===!1||e===null||typeof e>"u")throw new Error(t)}function jt(e,t){if(!e){typeof console<"u"&&console.warn(t);try{throw new Error(t)}catch{}}}function Ih(){return Math.random().toString(36).substring(2,10)}function Oc(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 gi(e,t,n=null,r,s){return{pathname:typeof e=="string"?e:e.pathname,search:"",hash:"",...typeof t=="string"?hr(t):t,state:n,key:t&&t.key||r||Ih(),unstable_mask:s}}function is({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 hr(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 Rh(e,t,n,r={}){let{window:s=document.defaultView,v5Compat:o=!1}=r,i=s.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 m(){l="POP";let j=f(),h=j==null?null:j-d;d=j,c&&c({action:l,location:v.location,delta:h})}function p(j,h){l="PUSH";let g=Fc(j)?j:gi(v.location,j,h);d=f()+1;let y=Oc(g,d),S=v.createHref(g.unstable_mask||g);try{i.pushState(y,"",S)}catch(k){if(k instanceof DOMException&&k.name==="DataCloneError")throw k;s.location.assign(S)}o&&c&&c({action:l,location:v.location,delta:1})}function x(j,h){l="REPLACE";let g=Fc(j)?j:gi(v.location,j,h);d=f();let y=Oc(g,d),S=v.createHref(g.unstable_mask||g);i.replaceState(y,"",S),o&&c&&c({action:l,location:v.location,delta:0})}function w(j){return Ph(j)}let v={get action(){return l},get location(){return e(s,i)},listen(j){if(c)throw new Error("A history only accepts one active listener");return s.addEventListener(Mc,m),c=j,()=>{s.removeEventListener(Mc,m),c=null}},createHref(j){return t(s,j)},createURL:w,encodeLocation(j){let h=w(j);return{pathname:h.pathname,search:h.search,hash:h.hash}},push:p,replace:x,go(j){return i.go(j)}};return v}function Ph(e,t=!1){let n="http://localhost";typeof window<"u"&&(n=window.location.origin!=="null"?window.location.origin:window.location.href),xe(n,"No window.location.(origin|href) available to create URL");let r=typeof e=="string"?e:is(e);return r=r.replace(/ $/,"%20"),!t&&r.startsWith("//")&&(r=n+r),new URL(r,n)}function yf(e,t,n="/"){return _h(e,t,n,!1)}function _h(e,t,n,r){let s=typeof t=="string"?hr(t):t,o=Jt(s.pathname||"/",n);if(o==null)return null;let i=vf(e);Ah(i);let l=null;for(let c=0;l==null&&c<i.length;++c){let d=Vh(o);l=Wh(i[c],d,r)}return l}function vf(e,t=[],n=[],r="",s=!1){let o=(i,l,c=s,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;xe(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 m=Ot([r,f.relativePath]),p=n.concat(f);i.children&&i.children.length>0&&(xe(i.index!==!0,`Index routes must not have child routes. Please remove all child routes from route path "${m}".`),vf(i.children,t,p,m,c)),!(i.path==null&&!i.index)&&t.push({path:m,score:Dh(m,i.index),routesMeta:p})};return e.forEach((i,l)=>{var c;if(i.path===""||!((c=i.path)!=null&&c.includes("?")))o(i,l);else for(let d of xf(i.path))o(i,l,!0,d)}),t}function xf(e){let t=e.split("/");if(t.length===0)return[];let[n,...r]=t,s=n.endsWith("?"),o=n.replace(/\?$/,"");if(r.length===0)return s?[o,""]:[o];let i=xf(r.join("/")),l=[];return l.push(...i.map(c=>c===""?o:[o,c].join("/"))),s&&l.push(...i),l.map(c=>e.startsWith("/")&&c===""?"/":c)}function Ah(e){e.sort((t,n)=>t.score!==n.score?n.score-t.score:Uh(t.routesMeta.map(r=>r.childrenIndex),n.routesMeta.map(r=>r.childrenIndex)))}var $h=/^:[\w-]+$/,Lh=3,Mh=2,Fh=1,Oh=10,Bh=-2,Bc=e=>e==="*";function Dh(e,t){let n=e.split("/"),r=n.length;return n.some(Bc)&&(r+=Bh),t&&(r+=Mh),n.filter(s=>!Bc(s)).reduce((s,o)=>s+($h.test(o)?Lh:o===""?Fh:Oh),r)}function Uh(e,t){return e.length===t.length&&e.slice(0,-1).every((r,s)=>r===t[s])?e[e.length-1]-t[t.length-1]:0}function Wh(e,t,n=!1){let{routesMeta:r}=e,s={},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)||"/",m=ja({path:c.relativePath,caseSensitive:c.caseSensitive,end:d},f),p=c.route;if(!m&&d&&n&&!r[r.length-1].route.index&&(m=ja({path:c.relativePath,caseSensitive:c.caseSensitive,end:!1},f)),!m)return null;Object.assign(s,m.params),i.push({params:s,pathname:Ot([o,m.pathname]),pathnameBase:Qh(Ot([o,m.pathnameBase])),route:p}),m.pathnameBase!=="/"&&(o=Ot([o,m.pathnameBase]))}return i}function ja(e,t){typeof e=="string"&&(e={path:e,caseSensitive:!1,end:!0});let[n,r]=Hh(e.path,e.caseSensitive,e.end),s=t.match(n);if(!s)return null;let o=s[0],i=o.replace(/(.)\/+$/,"$1"),l=s.slice(1);return{params:r.reduce((d,{paramName:f,isOptional:m},p)=>{if(f==="*"){let w=l[p]||"";i=o.slice(0,o.length-w.length).replace(/(.)\/+$/,"$1")}const x=l[p];return m&&!x?d[f]=void 0:d[f]=(x||"").replace(/%2F/g,"/"),d},{}),pathname:o,pathnameBase:i,pattern:e}}function Hh(e,t=!1,n=!0){jt(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=[],s="^"+e.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(i,l,c,d,f)=>{if(r.push({paramName:l,isOptional:c!=null}),c){let m=f.charAt(d+i.length);return m&&m!=="/"?"/([^\\/]*)":"(?:/([^\\/]*))?"}return"/([^\\/]+)"}).replace(/\/([\w-]+)\?(\/|$)/g,"(/$1)?$2");return e.endsWith("*")?(r.push({paramName:"*"}),s+=e==="*"||e==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):n?s+="\\/*$":e!==""&&e!=="/"&&(s+="(?:(?=\\/|$))"),[new RegExp(s,t?void 0:"i"),r]}function Vh(e){try{return e.split("/").map(t=>decodeURIComponent(t).replace(/\//g,"%2F")).join("/")}catch(t){return jt(!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 Jt(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 Gh=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;function Kh(e,t="/"){let{pathname:n,search:r="",hash:s=""}=typeof e=="string"?hr(e):e,o;return n?(n=n.replace(/\/\/+/g,"/"),n.startsWith("/")?o=Dc(n.substring(1),"/"):o=Dc(n,t)):o=t,{pathname:o,search:Jh(r),hash:Xh(s)}}function Dc(e,t){let n=t.replace(/\/+$/,"").split("/");return e.split("/").forEach(s=>{s===".."?n.length>1&&n.pop():s!=="."&&n.push(s)}),n.length>1?n.join("/"):"/"}function yo(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 Yh(e){return e.filter((t,n)=>n===0||t.route.path&&t.route.path.length>0)}function vl(e){let t=Yh(e);return t.map((n,r)=>r===t.length-1?n.pathname:n.pathnameBase)}function Da(e,t,n,r=!1){let s;typeof e=="string"?s=hr(e):(s={...e},xe(!s.pathname||!s.pathname.includes("?"),yo("?","pathname","search",s)),xe(!s.pathname||!s.pathname.includes("#"),yo("#","pathname","hash",s)),xe(!s.search||!s.search.includes("#"),yo("#","search","hash",s)));let o=e===""||s.pathname==="",i=o?"/":s.pathname,l;if(i==null)l=n;else{let m=t.length-1;if(!r&&i.startsWith("..")){let p=i.split("/");for(;p[0]==="..";)p.shift(),m-=1;s.pathname=p.join("/")}l=m>=0?t[m]:"/"}let c=Kh(s,l),d=i&&i!=="/"&&i.endsWith("/"),f=(o||i===".")&&n.endsWith("/");return!c.pathname.endsWith("/")&&(d||f)&&(c.pathname+="/"),c}var Ot=e=>e.join("/").replace(/\/\/+/g,"/"),Qh=e=>e.replace(/\/+$/,"").replace(/^\/*/,"/"),Jh=e=>!e||e==="?"?"":e.startsWith("?")?e:"?"+e,Xh=e=>!e||e==="#"?"":e.startsWith("#")?e:"#"+e,qh=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 Zh(e){return e!=null&&typeof e.status=="number"&&typeof e.statusText=="string"&&typeof e.internal=="boolean"&&"data"in e}function eg(e){return e.map(t=>t.route.path).filter(Boolean).join("/").replace(/\/\/*/g,"/")||"/"}var wf=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function Sf(e,t){let n=e;if(typeof n!="string"||!Gh.test(n))return{absoluteURL:void 0,isExternal:!1,to:n};let r=n,s=!1;if(wf)try{let o=new URL(window.location.href),i=n.startsWith("//")?new URL(o.protocol+n):new URL(n),l=Jt(i.pathname,t);i.origin===o.origin&&l!=null?n=l+i.search+i.hash:s=!0}catch{jt(!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:s,to:n}}Object.getOwnPropertyNames(Object.prototype).sort().join("\0");var jf=["POST","PUT","PATCH","DELETE"];new Set(jf);var tg=["GET",...jf];new Set(tg);var gr=u.createContext(null);gr.displayName="DataRouter";var Ua=u.createContext(null);Ua.displayName="DataRouterState";var ng=u.createContext(!1),kf=u.createContext({isTransitioning:!1});kf.displayName="ViewTransition";var rg=u.createContext(new Map);rg.displayName="Fetchers";var sg=u.createContext(null);sg.displayName="Await";var mt=u.createContext(null);mt.displayName="Navigation";var ps=u.createContext(null);ps.displayName="Location";var Rt=u.createContext({outlet:null,matches:[],isDataRoute:!1});Rt.displayName="Route";var xl=u.createContext(null);xl.displayName="RouteError";var bf="REACT_ROUTER_ERROR",ag="REDIRECT",og="ROUTE_ERROR_RESPONSE";function ig(e){if(e.startsWith(`${bf}:${ag}:{`))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 lg(e){if(e.startsWith(`${bf}:${og}:{`))try{let t=JSON.parse(e.slice(40));if(typeof t=="object"&&t&&typeof t.status=="number"&&typeof t.statusText=="string")return new qh(t.status,t.statusText,t.data)}catch{}}function cg(e,{relative:t}={}){xe(yr(),"useHref() may be used only in the context of a <Router> component.");let{basename:n,navigator:r}=u.useContext(mt),{hash:s,pathname:o,search:i}=ms(e,{relative:t}),l=o;return n!=="/"&&(l=o==="/"?n:Ot([n,o])),r.createHref({pathname:l,search:i,hash:s})}function yr(){return u.useContext(ps)!=null}function kt(){return xe(yr(),"useLocation() may be used only in the context of a <Router> component."),u.useContext(ps).location}var Cf="You should call navigate() in a React.useEffect(), not when your component is first rendered.";function Nf(e){u.useContext(mt).static||u.useLayoutEffect(e)}function qt(){let{isDataRoute:e}=u.useContext(Rt);return e?bg():ug()}function ug(){xe(yr(),"useNavigate() may be used only in the context of a <Router> component.");let e=u.useContext(gr),{basename:t,navigator:n}=u.useContext(mt),{matches:r}=u.useContext(Rt),{pathname:s}=kt(),o=JSON.stringify(vl(r)),i=u.useRef(!1);return Nf(()=>{i.current=!0}),u.useCallback((c,d={})=>{if(jt(i.current,Cf),!i.current)return;if(typeof c=="number"){n.go(c);return}let f=Da(c,JSON.parse(o),s,d.relative==="path");e==null&&t!=="/"&&(f.pathname=f.pathname==="/"?t:Ot([t,f.pathname])),(d.replace?n.replace:n.push)(f,d.state,d)},[t,n,o,s,e])}var dg=u.createContext(null);function fg(e){let t=u.useContext(Rt).outlet;return u.useMemo(()=>t&&u.createElement(dg.Provider,{value:e},t),[t,e])}function ms(e,{relative:t}={}){let{matches:n}=u.useContext(Rt),{pathname:r}=kt(),s=JSON.stringify(vl(n));return u.useMemo(()=>Da(e,JSON.parse(s),r,t==="path"),[e,s,r,t])}function pg(e,t){return Ef(e,t)}function Ef(e,t,n){var j;xe(yr(),"useRoutes() may be used only in the context of a <Router> component.");let{navigator:r}=u.useContext(mt),{matches:s}=u.useContext(Rt),o=s[s.length-1],i=o?o.params:{},l=o?o.pathname:"/",c=o?o.pathnameBase:"/",d=o&&o.route;{let h=d&&d.path||"";zf(l,!d||h.endsWith("*")||h.endsWith("*?"),`You rendered descendant <Routes> (or called \`useRoutes()\`) at "${l}" (under <Route path="${h}">) 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="${h}"> to <Route path="${h==="/"?"*":`${h}/*`}">.`)}let f=kt(),m;if(t){let h=typeof t=="string"?hr(t):t;xe(c==="/"||((j=h.pathname)==null?void 0:j.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 "${h.pathname}" was given in the \`location\` prop.`),m=h}else m=f;let p=m.pathname||"/",x=p;if(c!=="/"){let h=c.replace(/^\//,"").split("/");x="/"+p.replace(/^\//,"").split("/").slice(h.length).join("/")}let w=yf(e,{pathname:x});jt(d||w!=null,`No routes matched location "${m.pathname}${m.search}${m.hash}" `),jt(w==null||w[w.length-1].route.element!==void 0||w[w.length-1].route.Component!==void 0||w[w.length-1].route.lazy!==void 0,`Matched leaf route at location "${m.pathname}${m.search}${m.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 v=vg(w&&w.map(h=>Object.assign({},h,{params:Object.assign({},i,h.params),pathname:Ot([c,r.encodeLocation?r.encodeLocation(h.pathname.replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:h.pathname]),pathnameBase:h.pathnameBase==="/"?c:Ot([c,r.encodeLocation?r.encodeLocation(h.pathnameBase.replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:h.pathnameBase])})),s,n);return t&&v?u.createElement(ps.Provider,{value:{location:{pathname:"/",search:"",hash:"",state:null,key:"default",unstable_mask:void 0,...m},navigationType:"POP"}},v):v}function mg(){let e=kg(),t=Zh(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)",s={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:s},n):null,i)}var hg=u.createElement(mg,null),Tf=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=lg(e.digest);n&&(e=n)}let t=e!==void 0?u.createElement(Rt.Provider,{value:this.props.routeContext},u.createElement(xl.Provider,{value:e,children:this.props.component})):this.props.children;return this.context?u.createElement(gg,{error:e},t):t}};Tf.contextType=ng;var vo=new WeakMap;function gg({children:e,error:t}){let{basename:n}=u.useContext(mt);if(typeof t=="object"&&t&&"digest"in t&&typeof t.digest=="string"){let r=ig(t.digest);if(r){let s=vo.get(t);if(s)throw s;let o=Sf(r.location,n);if(wf&&!vo.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 vo.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(gr);return r&&r.static&&r.staticContext&&(t.route.errorElement||t.route.ErrorBoundary)&&(r.staticContext._deepestRenderedBoundaryId=t.route.id),u.createElement(Rt.Provider,{value:e},n)}function vg(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 s=e,o=r==null?void 0:r.errors;if(o!=null){let f=s.findIndex(m=>m.route.id&&(o==null?void 0:o[m.route.id])!==void 0);xe(f>=0,`Could not find a matching route for errors on route IDs: ${Object.keys(o).join(",")}`),s=s.slice(0,Math.min(s.length,f+1))}let i=!1,l=-1;if(n&&r){i=r.renderFallback;for(let f=0;f<s.length;f++){let m=s[f];if((m.route.HydrateFallback||m.route.hydrateFallbackElement)&&(l=f),m.route.id){let{loaderData:p,errors:x}=r,w=m.route.loader&&!p.hasOwnProperty(m.route.id)&&(!x||x[m.route.id]===void 0);if(m.route.lazy||w){n.isStatic&&(i=!0),l>=0?s=s.slice(0,l+1):s=[s[0]];break}}}}let c=n==null?void 0:n.onError,d=r&&c?(f,m)=>{var p,x;c(f,{location:r.location,params:((x=(p=r.matches)==null?void 0:p[0])==null?void 0:x.params)??{},unstable_pattern:eg(r.matches),errorInfo:m})}:void 0;return s.reduceRight((f,m,p)=>{let x,w=!1,v=null,j=null;r&&(x=o&&m.route.id?o[m.route.id]:void 0,v=m.route.errorElement||hg,i&&(l<0&&p===0?(zf("route-fallback",!1,"No `HydrateFallback` element provided to render during initial hydration"),w=!0,j=null):l===p&&(w=!0,j=m.route.hydrateFallbackElement||null)));let h=t.concat(s.slice(0,p+1)),g=()=>{let y;return x?y=v:w?y=j:m.route.Component?y=u.createElement(m.route.Component,null):m.route.element?y=m.route.element:y=f,u.createElement(yg,{match:m,routeContext:{outlet:f,matches:h,isDataRoute:r!=null},children:y})};return r&&(m.route.ErrorBoundary||m.route.errorElement||p===0)?u.createElement(Tf,{location:r.location,revalidation:r.revalidation,component:v,error:x,children:g(),routeContext:{outlet:null,matches:h,isDataRoute:!0},onError:d}):g()},null)}function wl(e){return`${e} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function xg(e){let t=u.useContext(gr);return xe(t,wl(e)),t}function wg(e){let t=u.useContext(Ua);return xe(t,wl(e)),t}function Sg(e){let t=u.useContext(Rt);return xe(t,wl(e)),t}function Sl(e){let t=Sg(e),n=t.matches[t.matches.length-1];return xe(n.route.id,`${e} can only be used on routes that contain a unique "id"`),n.route.id}function jg(){return Sl("useRouteId")}function kg(){var r;let e=u.useContext(xl),t=wg("useRouteError"),n=Sl("useRouteError");return e!==void 0?e:(r=t.errors)==null?void 0:r[n]}function bg(){let{router:e}=xg("useNavigate"),t=Sl("useNavigate"),n=u.useRef(!1);return Nf(()=>{n.current=!0}),u.useCallback(async(s,o={})=>{jt(n.current,Cf),n.current&&(typeof s=="number"?await e.navigate(s):await e.navigate(s,{fromRouteId:t,...o}))},[e,t])}var Uc={};function zf(e,t,n){!t&&!Uc[e]&&(Uc[e]=!0,jt(!1,n))}u.memo(Cg);function Cg({routes:e,future:t,state:n,isStatic:r,onError:s}){return Ef(e,void 0,{state:n,isStatic:r,onError:s})}function nn({to:e,replace:t,state:n,relative:r}){xe(yr(),"<Navigate> may be used only in the context of a <Router> component.");let{static:s}=u.useContext(mt);jt(!s,"<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(Rt),{pathname:i}=kt(),l=qt(),c=Da(e,vl(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 Ng(e){return fg(e.context)}function Re(e){xe(!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 Eg({basename:e="/",children:t=null,location:n,navigationType:r="POP",navigator:s,static:o=!1,unstable_useTransitions:i}){xe(!yr(),"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:s,static:o,unstable_useTransitions:i,future:{}}),[l,s,o,i]);typeof n=="string"&&(n=hr(n));let{pathname:d="/",search:f="",hash:m="",state:p=null,key:x="default",unstable_mask:w}=n,v=u.useMemo(()=>{let j=Jt(d,l);return j==null?null:{location:{pathname:j,search:f,hash:m,state:p,key:x,unstable_mask:w},navigationType:r}},[l,d,f,m,p,x,r,w]);return jt(v!=null,`<Router basename="${l}"> is not able to match the URL "${d}${f}${m}" because it does not start with the basename, so the <Router> won't render anything.`),v==null?null:u.createElement(mt.Provider,{value:c},u.createElement(ps.Provider,{children:t,value:v}))}function Tg({children:e,location:t}){return pg(yi(e),t)}function yi(e,t=[]){let n=[];return u.Children.forEach(e,(r,s)=>{if(!u.isValidElement(r))return;let o=[...t,s];if(r.type===u.Fragment){n.push.apply(n,yi(r.props.children,o));return}xe(r.type===Re,`[${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>`),xe(!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=yi(r.props.children,o)),n.push(i)}),n}var Qs="get",Js="application/x-www-form-urlencoded";function Wa(e){return typeof HTMLElement<"u"&&e instanceof HTMLElement}function zg(e){return Wa(e)&&e.tagName.toLowerCase()==="button"}function Ig(e){return Wa(e)&&e.tagName.toLowerCase()==="form"}function Rg(e){return Wa(e)&&e.tagName.toLowerCase()==="input"}function Pg(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}function _g(e,t){return e.button===0&&(!t||t==="_self")&&!Pg(e)}function vi(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(s=>[n,s]):[[n,r]])},[]))}function Ag(e,t){let n=vi(e);return t&&t.forEach((r,s)=>{n.has(s)||t.getAll(s).forEach(o=>{n.append(s,o)})}),n}var Ps=null;function $g(){if(Ps===null)try{new FormData(document.createElement("form"),0),Ps=!1}catch{Ps=!0}return Ps}var Lg=new Set(["application/x-www-form-urlencoded","multipart/form-data","text/plain"]);function xo(e){return e!=null&&!Lg.has(e)?(jt(!1,`"${e}" is not a valid \`encType\` for \`<Form>\`/\`<fetcher.Form>\` and will default to "${Js}"`),null):e}function Mg(e,t){let n,r,s,o,i;if(Ig(e)){let l=e.getAttribute("action");r=l?Jt(l,t):null,n=e.getAttribute("method")||Qs,s=xo(e.getAttribute("enctype"))||Js,o=new FormData(e)}else if(zg(e)||Rg(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?Jt(c,t):null,n=e.getAttribute("formmethod")||l.getAttribute("method")||Qs,s=xo(e.getAttribute("formenctype"))||xo(l.getAttribute("enctype"))||Js,o=new FormData(l,e),!$g()){let{name:d,type:f,value:m}=e;if(f==="image"){let p=d?`${d}.`:"";o.append(`${p}x`,"0"),o.append(`${p}y`,"0")}else d&&o.append(d,m)}}else{if(Wa(e))throw new Error('Cannot submit element that is not <form>, <button>, or <input type="submit|image">');n=Qs,r=null,s=Js,i=e}return o&&s==="text/plain"&&(i=o,o=void 0),{action:r,method:n.toLowerCase(),encType:s,formData:o,body:i}}Object.getOwnPropertyNames(Object.prototype).sort().join("\0");function jl(e,t){if(e===!1||e===null||typeof e>"u")throw new Error(t)}function Fg(e,t,n,r){let s=typeof e=="string"?new URL(e,typeof window>"u"?"server://singlefetch/":window.location.origin):e;return n?s.pathname.endsWith("/")?s.pathname=`${s.pathname}_.${r}`:s.pathname=`${s.pathname}.${r}`:s.pathname==="/"?s.pathname=`_root.${r}`:t&&Jt(s.pathname,t)==="/"?s.pathname=`${t.replace(/\/$/,"")}/_root.${r}`:s.pathname=`${s.pathname.replace(/\/$/,"")}.${r}`,s}async function Og(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 Bg(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 Dg(e,t,n){let r=await Promise.all(e.map(async s=>{let o=t.routes[s.route.id];if(o){let i=await Og(o,n);return i.links?i.links():[]}return[]}));return Vg(r.flat(1).filter(Bg).filter(s=>s.rel==="stylesheet"||s.rel==="preload").map(s=>s.rel==="stylesheet"?{...s,rel:"prefetch",as:"style"}:{...s,rel:"prefetch"}))}function Wc(e,t,n,r,s,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 m;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 p=c.route.shouldRevalidate({currentUrl:new URL(s.pathname+s.search+s.hash,window.origin),currentParams:((m=n[0])==null?void 0:m.params)||{},nextUrl:new URL(e,window.origin),nextParams:c.params,defaultShouldRevalidate:!0});if(typeof p=="boolean")return p}return!0}):[]}function Ug(e,t,{includeHydrateFallback:n}={}){return Wg(e.map(r=>{let s=t.routes[r.route.id];if(!s)return[];let o=[s.module];return s.clientActionModule&&(o=o.concat(s.clientActionModule)),s.clientLoaderModule&&(o=o.concat(s.clientLoaderModule)),n&&s.hydrateFallbackModule&&(o=o.concat(s.hydrateFallbackModule)),s.imports&&(o=o.concat(s.imports)),o}).flat(1))}function Wg(e){return[...new Set(e)]}function Hg(e){let t={},n=Object.keys(e).sort();for(let r of n)t[r]=e[r];return t}function Vg(e,t){let n=new Set;return new Set(t),e.reduce((r,s)=>{let o=JSON.stringify(Hg(s));return n.has(o)||(n.add(o),r.push({key:o,link:s})),r},[])}function If(){let e=u.useContext(gr);return jl(e,"You must render this element inside a <DataRouterContext.Provider> element"),e}function Gg(){let e=u.useContext(Ua);return jl(e,"You must render this element inside a <DataRouterStateContext.Provider> element"),e}var kl=u.createContext(void 0);kl.displayName="FrameworkContext";function Rf(){let e=u.useContext(kl);return jl(e,"You must render this element inside a <HydratedRouter> element"),e}function Kg(e,t){let n=u.useContext(kl),[r,s]=u.useState(!1),[o,i]=u.useState(!1),{onFocus:l,onBlur:c,onMouseEnter:d,onMouseLeave:f,onTouchStart:m}=t,p=u.useRef(null);u.useEffect(()=>{if(e==="render"&&i(!0),e==="viewport"){let v=h=>{h.forEach(g=>{i(g.isIntersecting)})},j=new IntersectionObserver(v,{threshold:.5});return p.current&&j.observe(p.current),()=>{j.disconnect()}}},[e]),u.useEffect(()=>{if(r){let v=setTimeout(()=>{i(!0)},100);return()=>{clearTimeout(v)}}},[r]);let x=()=>{s(!0)},w=()=>{s(!1),i(!1)};return n?e!=="intent"?[o,p,{}]:[o,p,{onFocus:Er(l,x),onBlur:Er(c,w),onMouseEnter:Er(d,x),onMouseLeave:Er(f,w),onTouchStart:Er(m,x)}]:[!1,p,{}]}function Er(e,t){return n=>{e&&e(n),n.defaultPrevented||t(n)}}function Yg({page:e,...t}){let{router:n}=If(),r=u.useMemo(()=>yf(n.routes,e,n.basename),[n.routes,e,n.basename]);return r?u.createElement(Jg,{page:e,matches:r,...t}):null}function Qg(e){let{manifest:t,routeModules:n}=Rf(),[r,s]=u.useState([]);return u.useEffect(()=>{let o=!1;return Dg(e,t,n).then(i=>{o||s(i)}),()=>{o=!0}},[e,t,n]),r}function Jg({page:e,matches:t,...n}){let r=kt(),{future:s,manifest:o,routeModules:i}=Rf(),{basename:l}=If(),{loaderData:c,matches:d}=Gg(),f=u.useMemo(()=>Wc(e,t,d,o,r,"data"),[e,t,d,o,r]),m=u.useMemo(()=>Wc(e,t,d,o,r,"assets"),[e,t,d,o,r]),p=u.useMemo(()=>{if(e===r.pathname+r.search+r.hash)return[];let v=new Set,j=!1;if(t.forEach(g=>{var S;let y=o.routes[g.route.id];!y||!y.hasLoader||(!f.some(k=>k.route.id===g.route.id)&&g.route.id in c&&((S=i[g.route.id])!=null&&S.shouldRevalidate)||y.hasClientLoader?j=!0:v.add(g.route.id))}),v.size===0)return[];let h=Fg(e,l,s.unstable_trailingSlashAwareDataRequests,"data");return j&&v.size>0&&h.searchParams.set("_routes",t.filter(g=>v.has(g.route.id)).map(g=>g.route.id).join(",")),[h.pathname+h.search]},[l,s.unstable_trailingSlashAwareDataRequests,c,r,o,f,t,e,i]),x=u.useMemo(()=>Ug(m,o),[m,o]),w=Qg(m);return u.createElement(u.Fragment,null,p.map(v=>u.createElement("link",{key:v,rel:"prefetch",as:"fetch",href:v,...n})),x.map(v=>u.createElement("link",{key:v,rel:"modulepreload",href:v,...n})),w.map(({key:v,link:j})=>u.createElement("link",{key:v,nonce:n.nonce,...j,crossOrigin:j.crossOrigin??n.crossOrigin})))}function Xg(...e){return t=>{e.forEach(n=>{typeof n=="function"?n(t):n!=null&&(n.current=t)})}}var qg=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";try{qg&&(window.__reactRouterVersion="7.13.1")}catch{}function Zg({basename:e,children:t,unstable_useTransitions:n,window:r}){let s=u.useRef();s.current==null&&(s.current=zh({window:r,v5Compat:!0}));let o=s.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(Eg,{basename:e,children:t,location:i.location,navigationType:i.action,navigator:o,unstable_useTransitions:n})}var Pf=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,Qe=u.forwardRef(function({onClick:t,discover:n="render",prefetch:r="none",relative:s,reloadDocument:o,replace:i,unstable_mask:l,state:c,target:d,to:f,preventScrollReset:m,viewTransition:p,unstable_defaultShouldRevalidate:x,...w},v){let{basename:j,navigator:h,unstable_useTransitions:g}=u.useContext(mt),y=typeof f=="string"&&Pf.test(f),S=Sf(f,j);f=S.to;let k=cg(f,{relative:s}),I=kt(),R=null;if(l){let T=Da(l,[],I.unstable_mask?I.unstable_mask.pathname:"/",!0);j!=="/"&&(T.pathname=T.pathname==="/"?j:Ot([j,T.pathname])),R=h.createHref(T)}let[_,C,z]=Kg(r,w),D=ny(f,{replace:i,unstable_mask:l,state:c,target:d,preventScrollReset:m,relative:s,viewTransition:p,unstable_defaultShouldRevalidate:x,unstable_useTransitions:g});function Y(T){t&&t(T),T.defaultPrevented||D(T)}let K=!(S.isExternal||o),W=u.createElement("a",{...w,...z,href:(K?R:void 0)||S.absoluteURL||k,onClick:K?Y:t,ref:Xg(v,C),target:d,"data-discover":!y&&n==="render"?"true":void 0});return _&&!y?u.createElement(u.Fragment,null,W,u.createElement(Yg,{page:k})):W});Qe.displayName="Link";var bl=u.forwardRef(function({"aria-current":t="page",caseSensitive:n=!1,className:r="",end:s=!1,style:o,to:i,viewTransition:l,children:c,...d},f){let m=ms(i,{relative:d.relative}),p=kt(),x=u.useContext(Ua),{navigator:w,basename:v}=u.useContext(mt),j=x!=null&&iy(m)&&l===!0,h=w.encodeLocation?w.encodeLocation(m).pathname:m.pathname,g=p.pathname,y=x&&x.navigation&&x.navigation.location?x.navigation.location.pathname:null;n||(g=g.toLowerCase(),y=y?y.toLowerCase():null,h=h.toLowerCase()),y&&v&&(y=Jt(y,v)||y);const S=h!=="/"&&h.endsWith("/")?h.length-1:h.length;let k=g===h||!s&&g.startsWith(h)&&g.charAt(S)==="/",I=y!=null&&(y===h||!s&&y.startsWith(h)&&y.charAt(h.length)==="/"),R={isActive:k,isPending:I,isTransitioning:j},_=k?t:void 0,C;typeof r=="function"?C=r(R):C=[r,k?"active":null,I?"pending":null,j?"transitioning":null].filter(Boolean).join(" ");let z=typeof o=="function"?o(R):o;return u.createElement(Qe,{...d,"aria-current":_,className:C,ref:f,style:z,to:i,viewTransition:l},typeof c=="function"?c(R):c)});bl.displayName="NavLink";var ey=u.forwardRef(({discover:e="render",fetcherKey:t,navigate:n,reloadDocument:r,replace:s,state:o,method:i=Qs,action:l,onSubmit:c,relative:d,preventScrollReset:f,viewTransition:m,unstable_defaultShouldRevalidate:p,...x},w)=>{let{unstable_useTransitions:v}=u.useContext(mt),j=ay(),h=oy(l,{relative:d}),g=i.toLowerCase()==="get"?"get":"post",y=typeof l=="string"&&Pf.test(l),S=k=>{if(c&&c(k),k.defaultPrevented)return;k.preventDefault();let I=k.nativeEvent.submitter,R=(I==null?void 0:I.getAttribute("formmethod"))||i,_=()=>j(I||k.currentTarget,{fetcherKey:t,method:R,navigate:n,replace:s,state:o,relative:d,preventScrollReset:f,viewTransition:m,unstable_defaultShouldRevalidate:p});v&&n!==!1?u.startTransition(()=>_()):_()};return u.createElement("form",{ref:w,method:g,action:h,onSubmit:r?c:S,...x,"data-discover":!y&&e==="render"?"true":void 0})});ey.displayName="Form";function ty(e){return`${e} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function _f(e){let t=u.useContext(gr);return xe(t,ty(e)),t}function ny(e,{target:t,replace:n,unstable_mask:r,state:s,preventScrollReset:o,relative:i,viewTransition:l,unstable_defaultShouldRevalidate:c,unstable_useTransitions:d}={}){let f=qt(),m=kt(),p=ms(e,{relative:i});return u.useCallback(x=>{if(_g(x,t)){x.preventDefault();let w=n!==void 0?n:is(m)===is(p),v=()=>f(e,{replace:w,unstable_mask:r,state:s,preventScrollReset:o,relative:i,viewTransition:l,unstable_defaultShouldRevalidate:c});d?u.startTransition(()=>v()):v()}},[m,f,p,n,r,s,t,e,o,i,l,c,d])}function Af(e){jt(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(vi(e)),n=u.useRef(!1),r=kt(),s=u.useMemo(()=>Ag(r.search,n.current?null:t.current),[r.search]),o=qt(),i=u.useCallback((l,c)=>{const d=vi(typeof l=="function"?l(new URLSearchParams(s)):l);n.current=!0,o("?"+d,c)},[o,s]);return[s,i]}var ry=0,sy=()=>`__${String(++ry)}__`;function ay(){let{router:e}=_f("useSubmit"),{basename:t}=u.useContext(mt),n=jg(),r=e.fetch,s=e.navigate;return u.useCallback(async(o,i={})=>{let{action:l,method:c,encType:d,formData:f,body:m}=Mg(o,t);if(i.navigate===!1){let p=i.fetcherKey||sy();await r(p,n,i.action||l,{unstable_defaultShouldRevalidate:i.unstable_defaultShouldRevalidate,preventScrollReset:i.preventScrollReset,formData:f,body:m,formMethod:i.method||c,formEncType:i.encType||d,flushSync:i.flushSync})}else await s(i.action||l,{unstable_defaultShouldRevalidate:i.unstable_defaultShouldRevalidate,preventScrollReset:i.preventScrollReset,formData:f,body:m,formMethod:i.method||c,formEncType:i.encType||d,replace:i.replace,state:i.state,fromRouteId:n,flushSync:i.flushSync,viewTransition:i.viewTransition})},[r,s,t,n])}function oy(e,{relative:t}={}){let{basename:n}=u.useContext(mt),r=u.useContext(Rt);xe(r,"useFormAction must be used inside a RouteContext");let[s]=r.matches.slice(-1),o={...ms(e||".",{relative:t})},i=kt();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(m=>m).forEach(m=>l.append("index",m));let f=l.toString();o.search=f?`?${f}`:""}}return(!e||e===".")&&s.route.index&&(o.search=o.search?o.search.replace(/^\?/,"?index&"):"?index"),n!=="/"&&(o.pathname=o.pathname==="/"?n:Ot([n,o.pathname])),is(o)}function iy(e,{relative:t}={}){let n=u.useContext(kf);xe(n!=null,"`useViewTransitionState` must be used within `react-router-dom`'s `RouterProvider`. Did you accidentally import `RouterProvider` from `react-router`?");let{basename:r}=_f("useViewTransitionState"),s=ms(e,{relative:t});if(!n.isTransitioning)return!1;let o=Jt(n.currentLocation.pathname,r)||n.currentLocation.pathname,i=Jt(n.nextLocation.pathname,r)||n.nextLocation.pathname;return ja(s.pathname,i)!=null||ja(s.pathname,o)!=null}class $f extends Error{constructor(n){super("different_account");vr(this,"summary");this.name="DifferentAccountError",this.summary=n}}class ly{constructor(){vr(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 $f(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()}`:"",s=await this.fetch(`/denials${r}`);if(!s.ok)throw new Error(`Failed to fetch denials: ${s.status}`);return s.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(),s=await this.fetch(`/api/receipts/mine${r?"?"+r:""}`);if(!s.ok)throw new Error(`Failed to fetch receipts: ${s.status}`);return(await s.json()).receipts??[]}async fetchEvidenceBundle(){var s;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=((s=/filename="([^"]+)"/.exec(t.headers.get("content-disposition")??""))==null?void 0:s[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 s=await r.json().catch(()=>({error:"Failed to revoke"}));throw new Error(s.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(),s=r.group||r;return{id:s.id,name:s.name,myDomains:s.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(),s=r.group||r;return{id:s.id,name:s.name,myDomains:s.myDomains||[],isAdmin:s.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 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 s=await r.json().catch(()=>({error:`Discovery failed: ${r.status}`}));throw new Error(s.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 s=await r.json().catch(()=>({error:`HTTP ${r.status}`}));throw new Error(s.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 s=await r.json();return(s==null?void 0:s.config)??null}async setTeamProfileConfig(t,n,r){const s=await this.fetch(`/api/groups/${encodeURIComponent(t)}/profile-config/${encodeURIComponent(n)}`,{method:"PUT",body:JSON.stringify(r)});if(!s.ok){const o=await s.json().catch(()=>({error:"Failed to set profile config"}));throw new Error(o.error||`setTeamProfileConfig failed: ${s.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 s=await r.json().catch(()=>({error:"Encryption failed"}));throw new Error(s.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 s=await r.json().catch(()=>({error:"Failed to delete profile config"}));throw new Error(s.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 s=await this.fetch(`/api/proposals/${encodeURIComponent(t)}/resolve`,{method:"POST",body:JSON.stringify({action:n,domain:r})});if(!s.ok){const o=await s.json().catch(()=>({error:"Failed"}));throw new Error(o.error||`Failed: ${s.status}`)}return s.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 s=await r.json().catch(()=>({error:"Failed"}));throw new Error(s.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 s=await n.json().catch(()=>({error:"Decryption failed"}));throw new Error(s.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 s=await r.json().catch(()=>({error:"Failed"}));throw new Error(s.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(s=>{var l,c;const o=s.owner??{userId:""};return{authorization_id:s.authorization_id??s.authorizationId,profile_id:s.profileId??s.profile_id,path:s.path??"",title:s.title??null,sp_status:s.status??s.sp_status??null,frame:s.bounds??s.frame??{},required_domains:s.requiredDomains??s.required_domains??[],attested_domains:s.attestedDomains??s.attested_domains??[],missing_domains:(s.requiredDomains??s.required_domains??[]).filter(d=>!(s.attestedDomains??s.attested_domains??[]).includes(d)),deferred_commitment_domains:s.deferredCommitmentDomains??s.deferred_commitment_domains??[],approvers_frozen:s.approversFrozen??s.approvers_frozen??[],above_cap:s.aboveCap??s.above_cap??!1,created_at:s.createdAt?new Date(s.createdAt*1e3).toISOString():s.created_at??"",earliest_expiry:(l=s.attestations)!=null&&l.length?new Date(Math.min(...s.attestations.map(d=>d.expiresAt))*1e3).toISOString():null,remaining_seconds:(c=s.attestations)!=null&&c.length?Math.max(0,Math.min(...s.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(),s=await this.fetch(`/api/receipts/mine${r?"?"+r:""}`);if(!s.ok)throw new Error(`Failed to fetch receipts: ${s.status}`);const o=await s.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 s=r.toString(),o=await this.fetch(`/api/groups/${encodeURIComponent(t)}/receipts${s?"?"+s:""}`);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",s=t.domain||"owner",o=await this.getProposals(s);let i=[];if(r==="all"){const l=[],c=new Date;for(let f=0;f<n;f++){const m=new Date(c);m.setUTCDate(c.getUTCDate()-f),l.push(m.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 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 s=await r.json().catch(()=>({error:"Save failed"}));throw new Error(s.error||`Save failed: ${r.status}`)}}}const $=new ly,Lf=u.createContext(null);function cy({children:e}){const[t,n]=u.useState(null),[r,s]=u.useState("personal"),[o,i]=u.useState(null),[l,c]=u.useState(""),[d,f]=u.useState(null),[m,p]=u.useState(null),[x,w]=u.useState(!1),[v,j]=u.useState(""),h=u.useRef(!1),g=u.useRef(null),y=u.useCallback(async()=>{if(h.current)try{const _=await $.getMyTeam();if(_){const{group:C,membership:z}=_;f(C),p(z),s("team"),i(C);const D=g.current??z.domains[0]??"owner";c(D)}else f(null),p(null),s("personal")}catch{}},[]);u.useEffect(()=>{const _=()=>{document.visibilityState==="visible"&&y()};return document.addEventListener("visibilitychange",_),()=>document.removeEventListener("visibilitychange",_)},[y]);const S=u.useCallback(async(_,C={})=>{w(!0),j("");try{$.setApiKey(_),h.current=!0;const z=await $.login(_,C);n(z),g.current=z.id;const D=await $.getGroups(),Y=D.find(K=>K.isPersonal)??D[0]??null;i(Y),c("owner"),await y()}catch(z){throw $.clearApiKey(),h.current=!1,j(z instanceof Error?z.message:"Login failed"),z}finally{w(!1)}},[y]),k=u.useCallback(async()=>{await $.logout(),$.clearApiKey(),h.current=!1,g.current=null,n(null),i(null),c(""),f(null),p(null),s("personal"),j("")},[]),I=u.useCallback(()=>j(""),[]),R=u.useCallback((_,C)=>{i(_),c(C)},[]);return a.jsx(Lf.Provider,{value:{user:t,mode:r,group:o,domain:l,groupId:(o==null?void 0:o.id)??null,activeTeam:d,activeMembership:m,isLoading:x,error:v,login:S,logout:k,clearError:I,activeGroup:o,activeDomain:l,groups:o?[o]:[],setActiveContext:R,refreshGroups:y},children:e})}function Ae(){const e=u.useContext(Lf);if(!e)throw new Error("useAuth must be used within AuthProvider");return e}const Mf=u.createContext(null);function uy({children:e}){const{user:t}=Ae(),n=u.useRef(null),[r,s]=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,s(!1));return}if(n.current)return;const l=$.getApiKey();if(!l)return;const c=new EventSource(`/events?key=${encodeURIComponent(l)}`);n.current=c,c.onopen=()=>s(!0),c.onerror=()=>s(!1);const d=["integration-changed","attestation-changed","proposal-added","proposal-resolved","team-membership-changed","action-approval-needed","action-resolved","proposal-approved","proposal-rejected"];for(const f of d)c.addEventListener(f,m=>{let p;try{p=JSON.parse(m.data)}catch{p=null}const x=o.current.get(f);if(x)for(const w of x)try{w(p)}catch(v){console.error(`[EventSource] handler for "${f}" threw:`,v)}});return()=>{c.close(),n.current=null,s(!1)}},[t]),a.jsx(Mf.Provider,{value:{connected:r,addListener:i},children:e})}function ue(e,t){const n=u.useContext(Mf);if(!n)return;const{addListener:r}=n;u.useEffect(()=>r(e,t),[e,t,r])}const Wr="suveren-theme",Hc="hap-theme";function _s(e){return e!=="system"?e:window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}(function(){const t=localStorage.getItem(Hc);t!==null&&localStorage.getItem(Wr)===null&&localStorage.setItem(Wr,t),t!==null&&localStorage.removeItem(Hc)})();function Ff(){const[e,t]=u.useState(()=>{const o=localStorage.getItem(Wr);return o==="light"||o==="dark"?o:"system"}),[n,r]=u.useState(()=>_s(e));u.useEffect(()=>{const o=document.documentElement,i=_s(e);o.setAttribute("data-theme",i),e==="system"?localStorage.removeItem(Wr):localStorage.setItem(Wr,e),r(_s(e))},[e]),u.useEffect(()=>{if(e!=="system")return;const o=window.matchMedia("(prefers-color-scheme: dark)"),i=()=>r(_s("system"));return o.addEventListener("change",i),()=>o.removeEventListener("change",i)},[e]);const s=u.useCallback(()=>{t(o=>o==="system"?"light":o==="light"?"dark":"system")},[]);return{theme:e,effectiveTheme:n,toggle:s}}const dy=5*60*1e3,fy=2e3;function Cl(){const[e,t]=u.useState(!1),[n,r]=u.useState("docker"),[s,o]=u.useState(""),[i,l]=u.useState(null),[c,d]=u.useState(!1),[f,m]=u.useState(!1),[p,x]=u.useState(!1),w=u.useRef(null);return u.useEffect(()=>{let v=!1;const j=(y=!1)=>{fetch(y?"/health?refresh=1":"/health").then(S=>S.json()).then(S=>{v||(S.installMethod&&r(S.installMethod),typeof S.latestVersion<"u"&&l(S.latestVersion),S.updateAvailable&&t(!0),S.version&&(o(S.version),w.current===null?w.current=S.version:S.version!==w.current&&S.version!=="dev"&&d(!0)))}).catch(()=>{})};j(!0);const h=setInterval(()=>j(!1),p?fy:dy),g=()=>{document.visibilityState==="visible"&&j(!1)};return document.addEventListener("visibilitychange",g),window.addEventListener("focus",g),()=>{v=!0,clearInterval(h),document.removeEventListener("visibilitychange",g),window.removeEventListener("focus",g)}},[p]),{updateAvailable:e&&!f,installMethod:n,version:s,latestVersion:i,serverRestarted:c,startFastPolling:()=>x(!0),dismiss:()=>m(!0)}}function py({size:e=20}){return a.jsxs("svg",{width:e,height:e,viewBox:"0 0 128 128",fill:"none","aria-hidden":"true",focusable:"false",children:[a.jsx("path",{d:"M 104.6 58.29 A 41 41 0 1 1 48.64 25.99",stroke:"currentColor",strokeWidth:"15",strokeLinecap:"round"}),a.jsx("line",{x1:"73.24",y1:"21.99",x2:"95.76",y2:"34.99",stroke:"currentColor",strokeWidth:"15",strokeLinecap:"round"})]})}function my(e){return e?e==="dev"?"dev":/^[0-9a-f]{40}$/i.test(e)?e.slice(0,7):e:""}const Vc={system:"◑",light:"☀",dark:"☾"};function Nl({onMenuToggle:e}){const{user:t,logout:n}=Ae(),{theme:r,toggle:s}=Ff(),{version:o,updateAvailable:i,latestVersion:l}=Cl(),c=my(o);return a.jsx("nav",{className:"top-nav",children:a.jsxs("div",{className:"top-nav-inner",children:[a.jsxs("div",{className:"logo-group",children:[a.jsx(py,{size:20}),a.jsx("span",{className:"logo",children:"Suveren"}),a.jsx("span",{className:"version-badge",children:"Local Gateway"}),c&&a.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}`:""]})]}),a.jsx("div",{className:"nav-spacer"}),a.jsx("div",{className:"nav-actions nav-actions-desktop",children:t?a.jsxs(a.Fragment,{children:[a.jsx("span",{className:"user-chip",children:a.jsx("strong",{children:t.name})}),a.jsx("button",{className:"theme-toggle",onClick:s,title:`Theme: ${r}`,children:Vc[r]}),a.jsx("button",{className:"nav-logout",onClick:n,children:"Logout"})]}):a.jsx("button",{className:"theme-toggle",onClick:s,title:`Theme: ${r}`,children:Vc[r]})}),t&&e&&a.jsx("button",{className:"mobile-menu-btn",onClick:e,"aria-label":"Menu",children:"☰"})]})})}function At(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 Of(e,t){const n={active:[],pending:[],expired:[],revoked:[]};for(const r of e)n[At(r,t)].push(r);return n}function hy(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 Lt(e,t,n){const r=u.useRef(e);r.current=e,u.useEffect(()=>{let s=null;const o=()=>typeof document>"u"?!0:document.visibilityState==="visible",i=()=>{o()&&r.current()},l=()=>{s===null&&(s=setInterval(i,t))},c=()=>{s!==null&&(clearInterval(s),s=null)},d=()=>{o()?(r.current(),l()):c()};return o()&&(r.current(),l()),document.addEventListener("visibilitychange",d),()=>{c(),document.removeEventListener("visibilitychange",d)}},[t,n])}const Bf=u.createContext(null),gy=3e4,yy=5e3,vy=3e5;function xy(e,t,n){return t===0?"loading":e!=null&&e.running?"running":e!=null&&e.error?"error":e&&n?"starting":"not-running"}function wy({children:e}){const[t,n]=u.useState({manifests:[],integrations:[],activeSessions:0,mcpServerUp:null,manifestsError:!1,fetchCount:0,authHealth:{}}),r=u.useRef(null),s=u.useCallback(async()=>{let d=!1;const[f,m]=await Promise.all([$.getIntegrationManifests().catch(()=>(d=!0,{manifests:[]})),$.getMcpHealth().catch(()=>null)]);n(x=>({...x,manifests:f.manifests,integrations:(m==null?void 0:m.integrations)??x.integrations,activeSessions:(m==null?void 0:m.activeSessions)??x.activeSessions,mcpServerUp:!!m,manifestsError:d,fetchCount:x.fetchCount+1}));const p=f.manifests.filter(x=>x.oauth);if(p.length>0){const x=await Promise.all(p.map(async w=>[w.id,await $.getOAuthHealth(w.id)]));n(w=>({...w,authHealth:Object.fromEntries(x)}))}},[]),o=t.fetchCount>0&&t.manifests.some(d=>{const f=t.integrations.find(m=>m.id===d.id);return f&&!f.running});ue("integration-changed",s),Lt(s,o?yy:vy);const i=u.useMemo(()=>{const d=new Map(t.integrations.map(p=>[p.id,p])),f=Date.now();o&&r.current===null?r.current=f:o||(r.current=null);const m=r.current!==null&&f-r.current<gy;return t.manifests.map(p=>{const x=d.get(p.id),w=xy(x,t.fetchCount,m),v=t.authHealth[p.id];return{id:p.id,manifest:p,integration:x,state:w,authStatus:v==null?void 0:v.status,authAccount:v==null?void 0:v.account,authError:v==null?void 0:v.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:s};return a.jsx(Bf.Provider,{value:c,children:e})}function El(){const e=u.useContext(Bf);if(!e)throw new Error("useIntegrationStatus must be used inside IntegrationStatusProvider");return e}const Sy=[{to:"/",icon:"□",label:"Dashboard"},{to:"/proposals",icon:"▷",label:"Pending Approvals",statusKey:"proposals"},{to:"/authorizations",icon:"☰",label:"Authorizations",statusKey:"authorizations"},{to:"/agent-brief",icon:"▤",label:"Agent Brief",statusKey:"brief"},{to:"/audit",icon:"▣",label:"Receipts"},{to:"/groups",icon:"◉",label:"Team",teamOnly:!0},{to:"/integrations",icon:"⧗",label:"Integrations",statusKey:"integrations"},{to:"/settings",icon:"⚙",label:"AI Assistant",statusKey:"assistant"}];function jy(){const{activeDomain:e}=Ae(),[t,n]=u.useState({}),r=u.useCallback(async()=>{try{const[s,o,i,l,c]=await Promise.all([$.getCredential("ai-config").catch(()=>null),$.getMyAttestations().catch(()=>null),$.getProposals(e||"owner").catch(()=>null),$.getProposalsForApprover().catch(()=>null),$.getAgentContext().catch(()=>"")]),d={};if(s&&!s.configured&&(d.assistant=1),o){const x=Of(o).expired.length;x>0&&(d.authorizations=x)}const f=(i==null?void 0:i.length)??0,m=(l==null?void 0:l.length)??0,p=f+m;p>0&&(d.proposals=p),(!c||!c.trim())&&(d.brief=1),n(d)}catch{}},[e]);return ue("attestation-changed",r),ue("proposal-added",r),ue("proposal-resolved",r),ue("proposal-approved",r),ue("proposal-rejected",r),ue("team-membership-changed",r),Lt(r,3e5,e),t}const ky={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},by={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 Cy(){const{mode:e,group:t,domain:n,activeTeam:r}=Ae(),s=jy(),{attentionCount:o}=El(),i={...s};o>0&&(i.integrations=o);const l=Sy.filter(p=>!p.teamOnly||e==="team"),c=u.useRef(null),[d,f]=u.useState(null),m=kt();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)},[m.pathname]),a.jsxs("div",{className:"sidebar",children:[a.jsx("ul",{className:"sidebar-nav",children:l.map(p=>{const x=p.statusKey?i[p.statusKey]:0;return a.jsx("li",{children:a.jsxs(bl,{to:p.to,end:p.to==="/",className:({isActive:w})=>`sidebar-item${w?" active":""}`,children:[a.jsx("span",{className:"icon",children:p.icon}),p.label,x?a.jsx("span",{style:ky,children:x}):null]})},p.to)})}),a.jsxs("div",{className:"sidebar-context",children:[a.jsx("div",{className:"ctx-label",children:"Active context"}),a.jsx("div",{className:"ctx-value",children:e==="personal"?"personal":t?`${t.name} / ${n}`:n})]}),d&&a.jsx("div",{style:by,role:"status","aria-live":"polite",children:d})]})}const wo="suveren:updatedTo";function Ny(e){return 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"}function Ey(){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 Df(){const{updateAvailable:e,installMethod:t,version:n,latestVersion:r,serverRestarted:s,startFastPolling:o,dismiss:i}=Cl(),[l,c]=u.useState(!1),[d,f]=u.useState(!1),[m,p]=u.useState(()=>{try{const y=sessionStorage.getItem(wo);if(y)return sessionStorage.removeItem(wo),y}catch{}return null}),x=Ny(t),w=u.useRef(null),v=y=>{try{sessionStorage.setItem(wo,y||r||"✓")}catch{}window.location.reload()};u.useEffect(()=>{if(!m)return;const y=setTimeout(()=>p(null),6e3);return()=>clearTimeout(y)},[m]),u.useEffect(()=>{if(!l||!s)return;const y=()=>Ey()?!1:(v(n),!0);if(y())return;const S=setInterval(y,1500);return()=>clearInterval(S)},[l,s,n]),u.useEffect(()=>(document.body.classList.toggle("is-updating",l),()=>document.body.classList.remove("is-updating")),[l]);const j=e&&!l&&!m||!!m&&!l;u.useEffect(()=>{if(!j){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 I;const k=((I=w.current)==null?void 0:I.offsetHeight)??0;document.documentElement.style.setProperty("--update-banner-h",`${k}px`)};y();const S=new ResizeObserver(y);return w.current&&S.observe(w.current),()=>{S.disconnect(),document.documentElement.style.removeProperty("--update-banner-h"),document.body.classList.remove("has-update-banner")}},[j]);const h=()=>{c(!0),o()},g=async()=>{try{await navigator.clipboard.writeText(x),f(!0),setTimeout(()=>f(!1),1800)}catch{}};return a.jsxs(a.Fragment,{children:[m&&!l&&a.jsx("div",{ref:w,className:"update-banner is-live",role:"status","aria-live":"polite",children:a.jsxs("div",{className:"update-banner-row",children:[a.jsxs("span",{className:"update-banner-text",children:["✓"," You","’","re on the latest version",m&&m!=="✓"?` — ${m} is live`:" — now live","."]}),a.jsx("button",{className:"update-banner-x",onClick:()=>p(null),"aria-label":"Dismiss",children:"×"})]})}),e&&!l&&!m&&a.jsx("div",{ref:w,className:"update-banner",role:"status","aria-live":"polite",children:a.jsxs("div",{className:"update-banner-row",children:[a.jsx("span",{className:"update-banner-text",children:"Update available."}),a.jsxs("div",{style:{display:"flex",gap:"0.5rem",alignItems:"center"},children:[a.jsx("button",{className:"btn btn-sm btn-secondary",onClick:h,children:"Update"}),a.jsx("button",{className:"update-banner-x",onClick:i,"aria-label":"Dismiss",children:"×"})]})]})}),l&&a.jsx("div",{className:"update-overlay",children:a.jsxs("div",{className:"update-overlay-card",role:"dialog","aria-modal":"true","aria-label":"Finishing the update",children:[a.jsx("div",{className:"update-spinner"}),a.jsxs("h2",{children:["Finishing the update","…"]}),a.jsxs("p",{children:["Copy this command and run it in your terminal. The gateway will restart, and"," ",a.jsx("strong",{children:"this page updates automatically"})," when it comes back ","—"," no need to refresh."]}),a.jsxs("div",{className:"update-cmd-row",children:[a.jsx("code",{className:"update-cmd",children:x}),a.jsx("button",{className:"btn btn-sm btn-primary",onClick:g,children:d?"Copied":"Copy"})]}),a.jsxs("div",{className:"update-status",children:[a.jsx("span",{className:"update-pulse"})," Waiting for the gateway to restart","…"]}),a.jsxs("div",{className:"update-overlay-actions",children:[a.jsx("button",{className:"btn btn-primary",onClick:()=>v(n),children:"Reload now"}),a.jsx("button",{className:"btn btn-secondary",onClick:()=>c(!1),children:"Cancel"})]})]})})]})}const Ty={system:"◑",light:"☀",dark:"☾"},zy=[{to:"/",icon:"□",label:"Dashboard"},{to:"/proposals",icon:"▷",label:"Pending Approvals"},{to:"/authorizations",icon:"☰",label:"Authorizations"},{to:"/agent-brief",icon:"▤",label:"Agent Brief"},{to:"/audit",icon:"▣",label:"Receipts"},{to:"/groups",icon:"◉",label:"Team"},{to:"/integrations",icon:"⧗",label:"Integrations"},{to:"/settings",icon:"⚙",label:"AI Assistant"}];function Iy({open:e,onClose:t}){const{user:n,activeGroup:r,activeDomain:s,logout:o}=Ae(),{theme:i,toggle:l}=Ff(),c=kt();return u.useEffect(()=>{t()},[c.pathname]),e?a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"mobile-menu-backdrop",onClick:t}),a.jsxs("div",{className:"mobile-menu-panel",children:[n&&a.jsxs("div",{className:"mobile-menu-header",children:[a.jsx("strong",{children:n.name}),a.jsx("span",{style:{fontSize:"0.8rem",color:"var(--text-secondary)"},children:r?`${r.name} / ${s}`:s||"personal"})]}),a.jsx("nav",{className:"mobile-menu-nav",children:zy.map(d=>a.jsxs(bl,{to:d.to,end:d.to==="/",className:({isActive:f})=>`mobile-menu-item${f?" active":""}`,onClick:t,children:[a.jsx("span",{className:"icon",children:d.icon}),d.label]},d.to))}),a.jsxs("div",{className:"mobile-menu-footer",children:[a.jsxs("button",{className:"mobile-menu-action",onClick:()=>{l()},children:[a.jsx("span",{className:"icon",children:Ty[i]}),"Theme: ",i]}),a.jsx("button",{className:"mobile-menu-action",onClick:()=>{o(),t()},children:"Logout"})]})]})]}):null}function Uf(e){return e.status==="pending"}function Ry(e,t){return e.filter(Uf).length+t.length}const jn=["proposal-added","proposal-resolved","proposal-approved","proposal-rejected","action-approval-needed","action-resolved","team-membership-changed"],Py=500;function _y(){const{user:e,domain:t}=Ae(),[n,r]=u.useState(0),s=u.useRef(null),o=u.useCallback(async()=>{if(!e){r(0);return}try{const[l,c]=await Promise.all([$.getProposals(t||"owner").catch(()=>[]),$.getProposalsForApprover().catch(()=>[])]);r(Ry(l,c))}catch{r(0)}},[e,t]),i=u.useCallback(()=>{s.current&&clearTimeout(s.current),s.current=setTimeout(()=>{o()},Py)},[o]);return u.useEffect(()=>(o(),()=>{s.current&&clearTimeout(s.current)}),[o]),ue(jn[0],i),ue(jn[1],i),ue(jn[2],i),ue(jn[3],i),ue(jn[4],i),ue(jn[5],i),ue(jn[6],i),n}const Gc="Suveren",Ay="/favicon.svg",$y="M 104.94 61.85 A 41 41 0 1 1 45.39 27.47",As={x1:74.54,y1:22.74,x2:94.46,y2:34.24},Ly=14,My="#f59e0b";function Fy(e){const t=Wf(e);return t>0?`(${t}) ${Gc}`:Gc}function Wf(e){return Number.isFinite(e)&&e>0?Math.floor(e):0}function Oy(){const e=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128" fill="none">
|
|
51
|
+
Please change the parent <Route path="${h}"> to <Route path="${h==="/"?"*":`${h}/*`}">.`)}let f=kt(),m;if(t){let h=typeof t=="string"?hr(t):t;xe(c==="/"||((j=h.pathname)==null?void 0:j.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 "${h.pathname}" was given in the \`location\` prop.`),m=h}else m=f;let p=m.pathname||"/",x=p;if(c!=="/"){let h=c.replace(/^\//,"").split("/");x="/"+p.replace(/^\//,"").split("/").slice(h.length).join("/")}let w=yf(e,{pathname:x});jt(d||w!=null,`No routes matched location "${m.pathname}${m.search}${m.hash}" `),jt(w==null||w[w.length-1].route.element!==void 0||w[w.length-1].route.Component!==void 0||w[w.length-1].route.lazy!==void 0,`Matched leaf route at location "${m.pathname}${m.search}${m.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 v=vg(w&&w.map(h=>Object.assign({},h,{params:Object.assign({},i,h.params),pathname:Ot([c,r.encodeLocation?r.encodeLocation(h.pathname.replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:h.pathname]),pathnameBase:h.pathnameBase==="/"?c:Ot([c,r.encodeLocation?r.encodeLocation(h.pathnameBase.replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:h.pathnameBase])})),s,n);return t&&v?u.createElement(ps.Provider,{value:{location:{pathname:"/",search:"",hash:"",state:null,key:"default",unstable_mask:void 0,...m},navigationType:"POP"}},v):v}function mg(){let e=kg(),t=Zh(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)",s={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:s},n):null,i)}var hg=u.createElement(mg,null),Tf=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=lg(e.digest);n&&(e=n)}let t=e!==void 0?u.createElement(Rt.Provider,{value:this.props.routeContext},u.createElement(xl.Provider,{value:e,children:this.props.component})):this.props.children;return this.context?u.createElement(gg,{error:e},t):t}};Tf.contextType=ng;var vo=new WeakMap;function gg({children:e,error:t}){let{basename:n}=u.useContext(mt);if(typeof t=="object"&&t&&"digest"in t&&typeof t.digest=="string"){let r=ig(t.digest);if(r){let s=vo.get(t);if(s)throw s;let o=Sf(r.location,n);if(wf&&!vo.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 vo.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(gr);return r&&r.static&&r.staticContext&&(t.route.errorElement||t.route.ErrorBoundary)&&(r.staticContext._deepestRenderedBoundaryId=t.route.id),u.createElement(Rt.Provider,{value:e},n)}function vg(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 s=e,o=r==null?void 0:r.errors;if(o!=null){let f=s.findIndex(m=>m.route.id&&(o==null?void 0:o[m.route.id])!==void 0);xe(f>=0,`Could not find a matching route for errors on route IDs: ${Object.keys(o).join(",")}`),s=s.slice(0,Math.min(s.length,f+1))}let i=!1,l=-1;if(n&&r){i=r.renderFallback;for(let f=0;f<s.length;f++){let m=s[f];if((m.route.HydrateFallback||m.route.hydrateFallbackElement)&&(l=f),m.route.id){let{loaderData:p,errors:x}=r,w=m.route.loader&&!p.hasOwnProperty(m.route.id)&&(!x||x[m.route.id]===void 0);if(m.route.lazy||w){n.isStatic&&(i=!0),l>=0?s=s.slice(0,l+1):s=[s[0]];break}}}}let c=n==null?void 0:n.onError,d=r&&c?(f,m)=>{var p,x;c(f,{location:r.location,params:((x=(p=r.matches)==null?void 0:p[0])==null?void 0:x.params)??{},unstable_pattern:eg(r.matches),errorInfo:m})}:void 0;return s.reduceRight((f,m,p)=>{let x,w=!1,v=null,j=null;r&&(x=o&&m.route.id?o[m.route.id]:void 0,v=m.route.errorElement||hg,i&&(l<0&&p===0?(zf("route-fallback",!1,"No `HydrateFallback` element provided to render during initial hydration"),w=!0,j=null):l===p&&(w=!0,j=m.route.hydrateFallbackElement||null)));let h=t.concat(s.slice(0,p+1)),g=()=>{let y;return x?y=v:w?y=j:m.route.Component?y=u.createElement(m.route.Component,null):m.route.element?y=m.route.element:y=f,u.createElement(yg,{match:m,routeContext:{outlet:f,matches:h,isDataRoute:r!=null},children:y})};return r&&(m.route.ErrorBoundary||m.route.errorElement||p===0)?u.createElement(Tf,{location:r.location,revalidation:r.revalidation,component:v,error:x,children:g(),routeContext:{outlet:null,matches:h,isDataRoute:!0},onError:d}):g()},null)}function wl(e){return`${e} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function xg(e){let t=u.useContext(gr);return xe(t,wl(e)),t}function wg(e){let t=u.useContext(Ua);return xe(t,wl(e)),t}function Sg(e){let t=u.useContext(Rt);return xe(t,wl(e)),t}function Sl(e){let t=Sg(e),n=t.matches[t.matches.length-1];return xe(n.route.id,`${e} can only be used on routes that contain a unique "id"`),n.route.id}function jg(){return Sl("useRouteId")}function kg(){var r;let e=u.useContext(xl),t=wg("useRouteError"),n=Sl("useRouteError");return e!==void 0?e:(r=t.errors)==null?void 0:r[n]}function bg(){let{router:e}=xg("useNavigate"),t=Sl("useNavigate"),n=u.useRef(!1);return Nf(()=>{n.current=!0}),u.useCallback(async(s,o={})=>{jt(n.current,Cf),n.current&&(typeof s=="number"?await e.navigate(s):await e.navigate(s,{fromRouteId:t,...o}))},[e,t])}var Uc={};function zf(e,t,n){!t&&!Uc[e]&&(Uc[e]=!0,jt(!1,n))}u.memo(Cg);function Cg({routes:e,future:t,state:n,isStatic:r,onError:s}){return Ef(e,void 0,{state:n,isStatic:r,onError:s})}function nn({to:e,replace:t,state:n,relative:r}){xe(yr(),"<Navigate> may be used only in the context of a <Router> component.");let{static:s}=u.useContext(mt);jt(!s,"<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(Rt),{pathname:i}=kt(),l=qt(),c=Da(e,vl(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 Ng(e){return fg(e.context)}function Re(e){xe(!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 Eg({basename:e="/",children:t=null,location:n,navigationType:r="POP",navigator:s,static:o=!1,unstable_useTransitions:i}){xe(!yr(),"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:s,static:o,unstable_useTransitions:i,future:{}}),[l,s,o,i]);typeof n=="string"&&(n=hr(n));let{pathname:d="/",search:f="",hash:m="",state:p=null,key:x="default",unstable_mask:w}=n,v=u.useMemo(()=>{let j=Jt(d,l);return j==null?null:{location:{pathname:j,search:f,hash:m,state:p,key:x,unstable_mask:w},navigationType:r}},[l,d,f,m,p,x,r,w]);return jt(v!=null,`<Router basename="${l}"> is not able to match the URL "${d}${f}${m}" because it does not start with the basename, so the <Router> won't render anything.`),v==null?null:u.createElement(mt.Provider,{value:c},u.createElement(ps.Provider,{children:t,value:v}))}function Tg({children:e,location:t}){return pg(yi(e),t)}function yi(e,t=[]){let n=[];return u.Children.forEach(e,(r,s)=>{if(!u.isValidElement(r))return;let o=[...t,s];if(r.type===u.Fragment){n.push.apply(n,yi(r.props.children,o));return}xe(r.type===Re,`[${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>`),xe(!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=yi(r.props.children,o)),n.push(i)}),n}var Qs="get",Js="application/x-www-form-urlencoded";function Wa(e){return typeof HTMLElement<"u"&&e instanceof HTMLElement}function zg(e){return Wa(e)&&e.tagName.toLowerCase()==="button"}function Ig(e){return Wa(e)&&e.tagName.toLowerCase()==="form"}function Rg(e){return Wa(e)&&e.tagName.toLowerCase()==="input"}function Pg(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}function _g(e,t){return e.button===0&&(!t||t==="_self")&&!Pg(e)}function vi(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(s=>[n,s]):[[n,r]])},[]))}function Ag(e,t){let n=vi(e);return t&&t.forEach((r,s)=>{n.has(s)||t.getAll(s).forEach(o=>{n.append(s,o)})}),n}var Ps=null;function $g(){if(Ps===null)try{new FormData(document.createElement("form"),0),Ps=!1}catch{Ps=!0}return Ps}var Lg=new Set(["application/x-www-form-urlencoded","multipart/form-data","text/plain"]);function xo(e){return e!=null&&!Lg.has(e)?(jt(!1,`"${e}" is not a valid \`encType\` for \`<Form>\`/\`<fetcher.Form>\` and will default to "${Js}"`),null):e}function Mg(e,t){let n,r,s,o,i;if(Ig(e)){let l=e.getAttribute("action");r=l?Jt(l,t):null,n=e.getAttribute("method")||Qs,s=xo(e.getAttribute("enctype"))||Js,o=new FormData(e)}else if(zg(e)||Rg(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?Jt(c,t):null,n=e.getAttribute("formmethod")||l.getAttribute("method")||Qs,s=xo(e.getAttribute("formenctype"))||xo(l.getAttribute("enctype"))||Js,o=new FormData(l,e),!$g()){let{name:d,type:f,value:m}=e;if(f==="image"){let p=d?`${d}.`:"";o.append(`${p}x`,"0"),o.append(`${p}y`,"0")}else d&&o.append(d,m)}}else{if(Wa(e))throw new Error('Cannot submit element that is not <form>, <button>, or <input type="submit|image">');n=Qs,r=null,s=Js,i=e}return o&&s==="text/plain"&&(i=o,o=void 0),{action:r,method:n.toLowerCase(),encType:s,formData:o,body:i}}Object.getOwnPropertyNames(Object.prototype).sort().join("\0");function jl(e,t){if(e===!1||e===null||typeof e>"u")throw new Error(t)}function Fg(e,t,n,r){let s=typeof e=="string"?new URL(e,typeof window>"u"?"server://singlefetch/":window.location.origin):e;return n?s.pathname.endsWith("/")?s.pathname=`${s.pathname}_.${r}`:s.pathname=`${s.pathname}.${r}`:s.pathname==="/"?s.pathname=`_root.${r}`:t&&Jt(s.pathname,t)==="/"?s.pathname=`${t.replace(/\/$/,"")}/_root.${r}`:s.pathname=`${s.pathname.replace(/\/$/,"")}.${r}`,s}async function Og(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 Bg(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 Dg(e,t,n){let r=await Promise.all(e.map(async s=>{let o=t.routes[s.route.id];if(o){let i=await Og(o,n);return i.links?i.links():[]}return[]}));return Vg(r.flat(1).filter(Bg).filter(s=>s.rel==="stylesheet"||s.rel==="preload").map(s=>s.rel==="stylesheet"?{...s,rel:"prefetch",as:"style"}:{...s,rel:"prefetch"}))}function Wc(e,t,n,r,s,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 m;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 p=c.route.shouldRevalidate({currentUrl:new URL(s.pathname+s.search+s.hash,window.origin),currentParams:((m=n[0])==null?void 0:m.params)||{},nextUrl:new URL(e,window.origin),nextParams:c.params,defaultShouldRevalidate:!0});if(typeof p=="boolean")return p}return!0}):[]}function Ug(e,t,{includeHydrateFallback:n}={}){return Wg(e.map(r=>{let s=t.routes[r.route.id];if(!s)return[];let o=[s.module];return s.clientActionModule&&(o=o.concat(s.clientActionModule)),s.clientLoaderModule&&(o=o.concat(s.clientLoaderModule)),n&&s.hydrateFallbackModule&&(o=o.concat(s.hydrateFallbackModule)),s.imports&&(o=o.concat(s.imports)),o}).flat(1))}function Wg(e){return[...new Set(e)]}function Hg(e){let t={},n=Object.keys(e).sort();for(let r of n)t[r]=e[r];return t}function Vg(e,t){let n=new Set;return new Set(t),e.reduce((r,s)=>{let o=JSON.stringify(Hg(s));return n.has(o)||(n.add(o),r.push({key:o,link:s})),r},[])}function If(){let e=u.useContext(gr);return jl(e,"You must render this element inside a <DataRouterContext.Provider> element"),e}function Gg(){let e=u.useContext(Ua);return jl(e,"You must render this element inside a <DataRouterStateContext.Provider> element"),e}var kl=u.createContext(void 0);kl.displayName="FrameworkContext";function Rf(){let e=u.useContext(kl);return jl(e,"You must render this element inside a <HydratedRouter> element"),e}function Kg(e,t){let n=u.useContext(kl),[r,s]=u.useState(!1),[o,i]=u.useState(!1),{onFocus:l,onBlur:c,onMouseEnter:d,onMouseLeave:f,onTouchStart:m}=t,p=u.useRef(null);u.useEffect(()=>{if(e==="render"&&i(!0),e==="viewport"){let v=h=>{h.forEach(g=>{i(g.isIntersecting)})},j=new IntersectionObserver(v,{threshold:.5});return p.current&&j.observe(p.current),()=>{j.disconnect()}}},[e]),u.useEffect(()=>{if(r){let v=setTimeout(()=>{i(!0)},100);return()=>{clearTimeout(v)}}},[r]);let x=()=>{s(!0)},w=()=>{s(!1),i(!1)};return n?e!=="intent"?[o,p,{}]:[o,p,{onFocus:Er(l,x),onBlur:Er(c,w),onMouseEnter:Er(d,x),onMouseLeave:Er(f,w),onTouchStart:Er(m,x)}]:[!1,p,{}]}function Er(e,t){return n=>{e&&e(n),n.defaultPrevented||t(n)}}function Yg({page:e,...t}){let{router:n}=If(),r=u.useMemo(()=>yf(n.routes,e,n.basename),[n.routes,e,n.basename]);return r?u.createElement(Jg,{page:e,matches:r,...t}):null}function Qg(e){let{manifest:t,routeModules:n}=Rf(),[r,s]=u.useState([]);return u.useEffect(()=>{let o=!1;return Dg(e,t,n).then(i=>{o||s(i)}),()=>{o=!0}},[e,t,n]),r}function Jg({page:e,matches:t,...n}){let r=kt(),{future:s,manifest:o,routeModules:i}=Rf(),{basename:l}=If(),{loaderData:c,matches:d}=Gg(),f=u.useMemo(()=>Wc(e,t,d,o,r,"data"),[e,t,d,o,r]),m=u.useMemo(()=>Wc(e,t,d,o,r,"assets"),[e,t,d,o,r]),p=u.useMemo(()=>{if(e===r.pathname+r.search+r.hash)return[];let v=new Set,j=!1;if(t.forEach(g=>{var S;let y=o.routes[g.route.id];!y||!y.hasLoader||(!f.some(k=>k.route.id===g.route.id)&&g.route.id in c&&((S=i[g.route.id])!=null&&S.shouldRevalidate)||y.hasClientLoader?j=!0:v.add(g.route.id))}),v.size===0)return[];let h=Fg(e,l,s.unstable_trailingSlashAwareDataRequests,"data");return j&&v.size>0&&h.searchParams.set("_routes",t.filter(g=>v.has(g.route.id)).map(g=>g.route.id).join(",")),[h.pathname+h.search]},[l,s.unstable_trailingSlashAwareDataRequests,c,r,o,f,t,e,i]),x=u.useMemo(()=>Ug(m,o),[m,o]),w=Qg(m);return u.createElement(u.Fragment,null,p.map(v=>u.createElement("link",{key:v,rel:"prefetch",as:"fetch",href:v,...n})),x.map(v=>u.createElement("link",{key:v,rel:"modulepreload",href:v,...n})),w.map(({key:v,link:j})=>u.createElement("link",{key:v,nonce:n.nonce,...j,crossOrigin:j.crossOrigin??n.crossOrigin})))}function Xg(...e){return t=>{e.forEach(n=>{typeof n=="function"?n(t):n!=null&&(n.current=t)})}}var qg=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";try{qg&&(window.__reactRouterVersion="7.13.1")}catch{}function Zg({basename:e,children:t,unstable_useTransitions:n,window:r}){let s=u.useRef();s.current==null&&(s.current=zh({window:r,v5Compat:!0}));let o=s.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(Eg,{basename:e,children:t,location:i.location,navigationType:i.action,navigator:o,unstable_useTransitions:n})}var Pf=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,Qe=u.forwardRef(function({onClick:t,discover:n="render",prefetch:r="none",relative:s,reloadDocument:o,replace:i,unstable_mask:l,state:c,target:d,to:f,preventScrollReset:m,viewTransition:p,unstable_defaultShouldRevalidate:x,...w},v){let{basename:j,navigator:h,unstable_useTransitions:g}=u.useContext(mt),y=typeof f=="string"&&Pf.test(f),S=Sf(f,j);f=S.to;let k=cg(f,{relative:s}),I=kt(),R=null;if(l){let T=Da(l,[],I.unstable_mask?I.unstable_mask.pathname:"/",!0);j!=="/"&&(T.pathname=T.pathname==="/"?j:Ot([j,T.pathname])),R=h.createHref(T)}let[_,C,z]=Kg(r,w),D=ny(f,{replace:i,unstable_mask:l,state:c,target:d,preventScrollReset:m,relative:s,viewTransition:p,unstable_defaultShouldRevalidate:x,unstable_useTransitions:g});function Y(T){t&&t(T),T.defaultPrevented||D(T)}let K=!(S.isExternal||o),W=u.createElement("a",{...w,...z,href:(K?R:void 0)||S.absoluteURL||k,onClick:K?Y:t,ref:Xg(v,C),target:d,"data-discover":!y&&n==="render"?"true":void 0});return _&&!y?u.createElement(u.Fragment,null,W,u.createElement(Yg,{page:k})):W});Qe.displayName="Link";var bl=u.forwardRef(function({"aria-current":t="page",caseSensitive:n=!1,className:r="",end:s=!1,style:o,to:i,viewTransition:l,children:c,...d},f){let m=ms(i,{relative:d.relative}),p=kt(),x=u.useContext(Ua),{navigator:w,basename:v}=u.useContext(mt),j=x!=null&&iy(m)&&l===!0,h=w.encodeLocation?w.encodeLocation(m).pathname:m.pathname,g=p.pathname,y=x&&x.navigation&&x.navigation.location?x.navigation.location.pathname:null;n||(g=g.toLowerCase(),y=y?y.toLowerCase():null,h=h.toLowerCase()),y&&v&&(y=Jt(y,v)||y);const S=h!=="/"&&h.endsWith("/")?h.length-1:h.length;let k=g===h||!s&&g.startsWith(h)&&g.charAt(S)==="/",I=y!=null&&(y===h||!s&&y.startsWith(h)&&y.charAt(h.length)==="/"),R={isActive:k,isPending:I,isTransitioning:j},_=k?t:void 0,C;typeof r=="function"?C=r(R):C=[r,k?"active":null,I?"pending":null,j?"transitioning":null].filter(Boolean).join(" ");let z=typeof o=="function"?o(R):o;return u.createElement(Qe,{...d,"aria-current":_,className:C,ref:f,style:z,to:i,viewTransition:l},typeof c=="function"?c(R):c)});bl.displayName="NavLink";var ey=u.forwardRef(({discover:e="render",fetcherKey:t,navigate:n,reloadDocument:r,replace:s,state:o,method:i=Qs,action:l,onSubmit:c,relative:d,preventScrollReset:f,viewTransition:m,unstable_defaultShouldRevalidate:p,...x},w)=>{let{unstable_useTransitions:v}=u.useContext(mt),j=ay(),h=oy(l,{relative:d}),g=i.toLowerCase()==="get"?"get":"post",y=typeof l=="string"&&Pf.test(l),S=k=>{if(c&&c(k),k.defaultPrevented)return;k.preventDefault();let I=k.nativeEvent.submitter,R=(I==null?void 0:I.getAttribute("formmethod"))||i,_=()=>j(I||k.currentTarget,{fetcherKey:t,method:R,navigate:n,replace:s,state:o,relative:d,preventScrollReset:f,viewTransition:m,unstable_defaultShouldRevalidate:p});v&&n!==!1?u.startTransition(()=>_()):_()};return u.createElement("form",{ref:w,method:g,action:h,onSubmit:r?c:S,...x,"data-discover":!y&&e==="render"?"true":void 0})});ey.displayName="Form";function ty(e){return`${e} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function _f(e){let t=u.useContext(gr);return xe(t,ty(e)),t}function ny(e,{target:t,replace:n,unstable_mask:r,state:s,preventScrollReset:o,relative:i,viewTransition:l,unstable_defaultShouldRevalidate:c,unstable_useTransitions:d}={}){let f=qt(),m=kt(),p=ms(e,{relative:i});return u.useCallback(x=>{if(_g(x,t)){x.preventDefault();let w=n!==void 0?n:is(m)===is(p),v=()=>f(e,{replace:w,unstable_mask:r,state:s,preventScrollReset:o,relative:i,viewTransition:l,unstable_defaultShouldRevalidate:c});d?u.startTransition(()=>v()):v()}},[m,f,p,n,r,s,t,e,o,i,l,c,d])}function Af(e){jt(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(vi(e)),n=u.useRef(!1),r=kt(),s=u.useMemo(()=>Ag(r.search,n.current?null:t.current),[r.search]),o=qt(),i=u.useCallback((l,c)=>{const d=vi(typeof l=="function"?l(new URLSearchParams(s)):l);n.current=!0,o("?"+d,c)},[o,s]);return[s,i]}var ry=0,sy=()=>`__${String(++ry)}__`;function ay(){let{router:e}=_f("useSubmit"),{basename:t}=u.useContext(mt),n=jg(),r=e.fetch,s=e.navigate;return u.useCallback(async(o,i={})=>{let{action:l,method:c,encType:d,formData:f,body:m}=Mg(o,t);if(i.navigate===!1){let p=i.fetcherKey||sy();await r(p,n,i.action||l,{unstable_defaultShouldRevalidate:i.unstable_defaultShouldRevalidate,preventScrollReset:i.preventScrollReset,formData:f,body:m,formMethod:i.method||c,formEncType:i.encType||d,flushSync:i.flushSync})}else await s(i.action||l,{unstable_defaultShouldRevalidate:i.unstable_defaultShouldRevalidate,preventScrollReset:i.preventScrollReset,formData:f,body:m,formMethod:i.method||c,formEncType:i.encType||d,replace:i.replace,state:i.state,fromRouteId:n,flushSync:i.flushSync,viewTransition:i.viewTransition})},[r,s,t,n])}function oy(e,{relative:t}={}){let{basename:n}=u.useContext(mt),r=u.useContext(Rt);xe(r,"useFormAction must be used inside a RouteContext");let[s]=r.matches.slice(-1),o={...ms(e||".",{relative:t})},i=kt();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(m=>m).forEach(m=>l.append("index",m));let f=l.toString();o.search=f?`?${f}`:""}}return(!e||e===".")&&s.route.index&&(o.search=o.search?o.search.replace(/^\?/,"?index&"):"?index"),n!=="/"&&(o.pathname=o.pathname==="/"?n:Ot([n,o.pathname])),is(o)}function iy(e,{relative:t}={}){let n=u.useContext(kf);xe(n!=null,"`useViewTransitionState` must be used within `react-router-dom`'s `RouterProvider`. Did you accidentally import `RouterProvider` from `react-router`?");let{basename:r}=_f("useViewTransitionState"),s=ms(e,{relative:t});if(!n.isTransitioning)return!1;let o=Jt(n.currentLocation.pathname,r)||n.currentLocation.pathname,i=Jt(n.nextLocation.pathname,r)||n.nextLocation.pathname;return ja(s.pathname,i)!=null||ja(s.pathname,o)!=null}class $f extends Error{constructor(n){super("different_account");vr(this,"summary");this.name="DifferentAccountError",this.summary=n}}class ly{constructor(){vr(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 $f(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()}`:"",s=await this.fetch(`/denials${r}`);if(!s.ok)throw new Error(`Failed to fetch denials: ${s.status}`);return s.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(),s=await this.fetch(`/api/receipts/mine${r?"?"+r:""}`);if(!s.ok)throw new Error(`Failed to fetch receipts: ${s.status}`);return(await s.json()).receipts??[]}async fetchEvidenceBundle(){var s;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=((s=/filename="([^"]+)"/.exec(t.headers.get("content-disposition")??""))==null?void 0:s[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 s=await r.json().catch(()=>({error:"Failed to revoke"}));throw new Error(s.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(),s=r.group||r;return{id:s.id,name:s.name,myDomains:s.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(),s=r.group||r;return{id:s.id,name:s.name,myDomains:s.myDomains||[],isAdmin:s.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 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 s=await r.json().catch(()=>({error:`Discovery failed: ${r.status}`}));throw new Error(s.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 s=await r.json().catch(()=>({error:`HTTP ${r.status}`}));throw new Error(s.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 s=await r.json();return(s==null?void 0:s.config)??null}async setTeamProfileConfig(t,n,r){const s=await this.fetch(`/api/groups/${encodeURIComponent(t)}/profile-config/${encodeURIComponent(n)}`,{method:"PUT",body:JSON.stringify(r)});if(!s.ok){const o=await s.json().catch(()=>({error:"Failed to set profile config"}));throw new Error(o.error||`setTeamProfileConfig failed: ${s.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 s=await r.json().catch(()=>({error:"Encryption failed"}));throw new Error(s.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 s=await r.json().catch(()=>({error:"Failed to delete profile config"}));throw new Error(s.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 s=await this.fetch(`/api/proposals/${encodeURIComponent(t)}/resolve`,{method:"POST",body:JSON.stringify({action:n,domain:r})});if(!s.ok){const o=await s.json().catch(()=>({error:"Failed"}));throw new Error(o.error||`Failed: ${s.status}`)}return s.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 s=await r.json().catch(()=>({error:"Failed"}));throw new Error(s.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 s=await n.json().catch(()=>({error:"Decryption failed"}));throw new Error(s.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 s=await r.json().catch(()=>({error:"Failed"}));throw new Error(s.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(s=>{var l,c;const o=s.owner??{userId:""};return{authorization_id:s.authorization_id??s.authorizationId,profile_id:s.profileId??s.profile_id,path:s.path??"",title:s.title??null,sp_status:s.status??s.sp_status??null,frame:s.bounds??s.frame??{},required_domains:s.requiredDomains??s.required_domains??[],attested_domains:s.attestedDomains??s.attested_domains??[],missing_domains:(s.requiredDomains??s.required_domains??[]).filter(d=>!(s.attestedDomains??s.attested_domains??[]).includes(d)),deferred_commitment_domains:s.deferredCommitmentDomains??s.deferred_commitment_domains??[],approvers_frozen:s.approversFrozen??s.approvers_frozen??[],above_cap:s.aboveCap??s.above_cap??!1,created_at:s.createdAt?new Date(s.createdAt*1e3).toISOString():s.created_at??"",earliest_expiry:(l=s.attestations)!=null&&l.length?new Date(Math.min(...s.attestations.map(d=>d.expiresAt))*1e3).toISOString():null,remaining_seconds:(c=s.attestations)!=null&&c.length?Math.max(0,Math.min(...s.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(),s=await this.fetch(`/api/receipts/mine${r?"?"+r:""}`);if(!s.ok)throw new Error(`Failed to fetch receipts: ${s.status}`);const o=await s.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 s=r.toString(),o=await this.fetch(`/api/groups/${encodeURIComponent(t)}/receipts${s?"?"+s:""}`);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",s=t.domain||"owner",o=await this.getProposals(s);let i=[];if(r==="all"){const l=[],c=new Date;for(let f=0;f<n;f++){const m=new Date(c);m.setUTCDate(c.getUTCDate()-f),l.push(m.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 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 s=await r.json().catch(()=>({error:"Save failed"}));throw new Error(s.error||`Save failed: ${r.status}`)}}}const $=new ly,Lf=u.createContext(null);function cy({children:e}){const[t,n]=u.useState(null),[r,s]=u.useState("personal"),[o,i]=u.useState(null),[l,c]=u.useState(""),[d,f]=u.useState(null),[m,p]=u.useState(null),[x,w]=u.useState(!1),[v,j]=u.useState(""),h=u.useRef(!1),g=u.useRef(null),y=u.useCallback(async()=>{if(h.current)try{const _=await $.getMyTeam();if(_){const{group:C,membership:z}=_;f(C),p(z),s("team"),i(C);const D=g.current??z.domains[0]??"owner";c(D)}else f(null),p(null),s("personal")}catch{}},[]);u.useEffect(()=>{const _=()=>{document.visibilityState==="visible"&&y()};return document.addEventListener("visibilitychange",_),()=>document.removeEventListener("visibilitychange",_)},[y]);const S=u.useCallback(async(_,C={})=>{w(!0),j("");try{$.setApiKey(_),h.current=!0;const z=await $.login(_,C);n(z),g.current=z.id;const D=await $.getGroups(),Y=D.find(K=>K.isPersonal)??D[0]??null;i(Y),c("owner"),await y()}catch(z){throw $.clearApiKey(),h.current=!1,j(z instanceof Error?z.message:"Login failed"),z}finally{w(!1)}},[y]),k=u.useCallback(async()=>{await $.logout(),$.clearApiKey(),h.current=!1,g.current=null,n(null),i(null),c(""),f(null),p(null),s("personal"),j("")},[]),I=u.useCallback(()=>j(""),[]),R=u.useCallback((_,C)=>{i(_),c(C)},[]);return a.jsx(Lf.Provider,{value:{user:t,mode:r,group:o,domain:l,groupId:(o==null?void 0:o.id)??null,activeTeam:d,activeMembership:m,isLoading:x,error:v,login:S,logout:k,clearError:I,activeGroup:o,activeDomain:l,groups:o?[o]:[],setActiveContext:R,refreshGroups:y},children:e})}function Ae(){const e=u.useContext(Lf);if(!e)throw new Error("useAuth must be used within AuthProvider");return e}const Mf=u.createContext(null);function uy({children:e}){const{user:t}=Ae(),n=u.useRef(null),[r,s]=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,s(!1));return}if(n.current)return;const l=$.getApiKey();if(!l)return;const c=new EventSource(`/events?key=${encodeURIComponent(l)}`);n.current=c,c.onopen=()=>s(!0),c.onerror=()=>s(!1);const d=["integration-changed","attestation-changed","proposal-added","proposal-resolved","team-membership-changed","action-approval-needed","action-resolved","proposal-approved","proposal-rejected"];for(const f of d)c.addEventListener(f,m=>{let p;try{p=JSON.parse(m.data)}catch{p=null}const x=o.current.get(f);if(x)for(const w of x)try{w(p)}catch(v){console.error(`[EventSource] handler for "${f}" threw:`,v)}});return()=>{c.close(),n.current=null,s(!1)}},[t]),a.jsx(Mf.Provider,{value:{connected:r,addListener:i},children:e})}function ue(e,t){const n=u.useContext(Mf);if(!n)return;const{addListener:r}=n;u.useEffect(()=>r(e,t),[e,t,r])}const Wr="suveren-theme",Hc="hap-theme";function _s(e){return e!=="system"?e:window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}(function(){const t=localStorage.getItem(Hc);t!==null&&localStorage.getItem(Wr)===null&&localStorage.setItem(Wr,t),t!==null&&localStorage.removeItem(Hc)})();function Ff(){const[e,t]=u.useState(()=>{const o=localStorage.getItem(Wr);return o==="light"||o==="dark"?o:"system"}),[n,r]=u.useState(()=>_s(e));u.useEffect(()=>{const o=document.documentElement,i=_s(e);o.setAttribute("data-theme",i),e==="system"?localStorage.removeItem(Wr):localStorage.setItem(Wr,e),r(_s(e))},[e]),u.useEffect(()=>{if(e!=="system")return;const o=window.matchMedia("(prefers-color-scheme: dark)"),i=()=>r(_s("system"));return o.addEventListener("change",i),()=>o.removeEventListener("change",i)},[e]);const s=u.useCallback(()=>{t(o=>o==="system"?"light":o==="light"?"dark":"system")},[]);return{theme:e,effectiveTheme:n,toggle:s}}const dy=5*60*1e3,fy=2e3;function Cl(){const[e,t]=u.useState(!1),[n,r]=u.useState("docker"),[s,o]=u.useState(""),[i,l]=u.useState(null),[c,d]=u.useState(!1),[f,m]=u.useState(!1),[p,x]=u.useState(!1),w=u.useRef(null);return u.useEffect(()=>{let v=!1;const j=(y=!1)=>{fetch(y?"/health?refresh=1":"/health").then(S=>S.json()).then(S=>{v||(S.installMethod&&r(S.installMethod),typeof S.latestVersion<"u"&&l(S.latestVersion),S.updateAvailable&&t(!0),S.version&&(o(S.version),w.current===null?w.current=S.version:S.version!==w.current&&S.version!=="dev"&&d(!0)))}).catch(()=>{})};j(!0);const h=setInterval(()=>j(!1),p?fy:dy),g=()=>{document.visibilityState==="visible"&&j(!1)};return document.addEventListener("visibilitychange",g),window.addEventListener("focus",g),()=>{v=!0,clearInterval(h),document.removeEventListener("visibilitychange",g),window.removeEventListener("focus",g)}},[p]),{updateAvailable:e&&!f,installMethod:n,version:s,latestVersion:i,serverRestarted:c,startFastPolling:()=>x(!0),dismiss:()=>m(!0)}}function py({size:e=20}){return a.jsxs("svg",{width:e,height:e,viewBox:"0 0 128 128",fill:"none","aria-hidden":"true",focusable:"false",children:[a.jsx("path",{d:"M 104.6 58.29 A 41 41 0 1 1 48.64 25.99",stroke:"currentColor",strokeWidth:"15",strokeLinecap:"round"}),a.jsx("line",{x1:"73.24",y1:"21.99",x2:"95.76",y2:"34.99",stroke:"currentColor",strokeWidth:"15",strokeLinecap:"round"})]})}function my(e){return e?e==="dev"?"dev":/^[0-9a-f]{40}$/i.test(e)?e.slice(0,7):e:""}const Vc={system:"◑",light:"☀",dark:"☾"};function Nl({onMenuToggle:e}){const{user:t,logout:n}=Ae(),{theme:r,toggle:s}=Ff(),{version:o,updateAvailable:i,latestVersion:l}=Cl(),c=my(o);return a.jsx("nav",{className:"top-nav",children:a.jsxs("div",{className:"top-nav-inner",children:[a.jsxs("div",{className:"logo-group",children:[a.jsx(py,{size:20}),a.jsx("span",{className:"logo",children:"Suveren"}),a.jsx("span",{className:"version-badge",children:"Local Gateway"}),c&&a.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}`:""]})]}),a.jsx("div",{className:"nav-spacer"}),a.jsx("div",{className:"nav-actions nav-actions-desktop",children:t?a.jsxs(a.Fragment,{children:[a.jsx("span",{className:"user-chip",children:a.jsx("strong",{children:t.name})}),a.jsx("button",{className:"theme-toggle",onClick:s,title:`Theme: ${r}`,children:Vc[r]}),a.jsx("button",{className:"nav-logout",onClick:n,children:"Logout"})]}):a.jsx("button",{className:"theme-toggle",onClick:s,title:`Theme: ${r}`,children:Vc[r]})}),t&&e&&a.jsx("button",{className:"mobile-menu-btn",onClick:e,"aria-label":"Menu",children:"☰"})]})})}function At(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 Of(e,t){const n={active:[],pending:[],expired:[],revoked:[]};for(const r of e)n[At(r,t)].push(r);return n}function hy(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 Lt(e,t,n){const r=u.useRef(e);r.current=e,u.useEffect(()=>{let s=null;const o=()=>typeof document>"u"?!0:document.visibilityState==="visible",i=()=>{o()&&r.current()},l=()=>{s===null&&(s=setInterval(i,t))},c=()=>{s!==null&&(clearInterval(s),s=null)},d=()=>{o()?(r.current(),l()):c()};return o()&&(r.current(),l()),document.addEventListener("visibilitychange",d),()=>{c(),document.removeEventListener("visibilitychange",d)}},[t,n])}const Bf=u.createContext(null),gy=3e4,yy=5e3,vy=3e5;function xy(e,t,n){return t===0?"loading":e!=null&&e.running?"running":e!=null&&e.error?"error":e&&n?"starting":"not-running"}function wy({children:e}){const[t,n]=u.useState({manifests:[],integrations:[],activeSessions:0,mcpServerUp:null,manifestsError:!1,fetchCount:0,authHealth:{}}),r=u.useRef(null),s=u.useCallback(async()=>{let d=!1;const[f,m]=await Promise.all([$.getIntegrationManifests().catch(()=>(d=!0,{manifests:[]})),$.getMcpHealth().catch(()=>null)]);n(x=>({...x,manifests:f.manifests,integrations:(m==null?void 0:m.integrations)??x.integrations,activeSessions:(m==null?void 0:m.activeSessions)??x.activeSessions,mcpServerUp:!!m,manifestsError:d,fetchCount:x.fetchCount+1}));const p=f.manifests.filter(x=>x.oauth);if(p.length>0){const x=await Promise.all(p.map(async w=>[w.id,await $.getOAuthHealth(w.id)]));n(w=>({...w,authHealth:Object.fromEntries(x)}))}},[]),o=t.fetchCount>0&&t.manifests.some(d=>{const f=t.integrations.find(m=>m.id===d.id);return f&&!f.running});ue("integration-changed",s),Lt(s,o?yy:vy);const i=u.useMemo(()=>{const d=new Map(t.integrations.map(p=>[p.id,p])),f=Date.now();o&&r.current===null?r.current=f:o||(r.current=null);const m=r.current!==null&&f-r.current<gy;return t.manifests.map(p=>{const x=d.get(p.id),w=xy(x,t.fetchCount,m),v=t.authHealth[p.id];return{id:p.id,manifest:p,integration:x,state:w,authStatus:v==null?void 0:v.status,authAccount:v==null?void 0:v.account,authError:v==null?void 0:v.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:s};return a.jsx(Bf.Provider,{value:c,children:e})}function El(){const e=u.useContext(Bf);if(!e)throw new Error("useIntegrationStatus must be used inside IntegrationStatusProvider");return e}const Sy=[{to:"/",icon:"□",label:"Dashboard"},{to:"/proposals",icon:"▷",label:"Pending Approvals",statusKey:"proposals"},{to:"/authorizations",icon:"☰",label:"Mandates",statusKey:"authorizations"},{to:"/agent-brief",icon:"▤",label:"Agent Brief",statusKey:"brief"},{to:"/audit",icon:"▣",label:"Tickets"},{to:"/groups",icon:"◉",label:"Team",teamOnly:!0},{to:"/integrations",icon:"⧗",label:"Integrations",statusKey:"integrations"},{to:"/settings",icon:"⚙",label:"AI Assistant",statusKey:"assistant"}];function jy(){const{activeDomain:e}=Ae(),[t,n]=u.useState({}),r=u.useCallback(async()=>{try{const[s,o,i,l,c]=await Promise.all([$.getCredential("ai-config").catch(()=>null),$.getMyAttestations().catch(()=>null),$.getProposals(e||"owner").catch(()=>null),$.getProposalsForApprover().catch(()=>null),$.getAgentContext().catch(()=>"")]),d={};if(s&&!s.configured&&(d.assistant=1),o){const x=Of(o).expired.length;x>0&&(d.authorizations=x)}const f=(i==null?void 0:i.length)??0,m=(l==null?void 0:l.length)??0,p=f+m;p>0&&(d.proposals=p),(!c||!c.trim())&&(d.brief=1),n(d)}catch{}},[e]);return ue("attestation-changed",r),ue("proposal-added",r),ue("proposal-resolved",r),ue("proposal-approved",r),ue("proposal-rejected",r),ue("team-membership-changed",r),Lt(r,3e5,e),t}const ky={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},by={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 Cy(){const{mode:e,group:t,domain:n,activeTeam:r}=Ae(),s=jy(),{attentionCount:o}=El(),i={...s};o>0&&(i.integrations=o);const l=Sy.filter(p=>!p.teamOnly||e==="team"),c=u.useRef(null),[d,f]=u.useState(null),m=kt();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)},[m.pathname]),a.jsxs("div",{className:"sidebar",children:[a.jsx("ul",{className:"sidebar-nav",children:l.map(p=>{const x=p.statusKey?i[p.statusKey]:0;return a.jsx("li",{children:a.jsxs(bl,{to:p.to,end:p.to==="/",className:({isActive:w})=>`sidebar-item${w?" active":""}`,children:[a.jsx("span",{className:"icon",children:p.icon}),p.label,x?a.jsx("span",{style:ky,children:x}):null]})},p.to)})}),a.jsxs("div",{className:"sidebar-context",children:[a.jsx("div",{className:"ctx-label",children:"Active context"}),a.jsx("div",{className:"ctx-value",children:e==="personal"?"personal":t?`${t.name} / ${n}`:n})]}),d&&a.jsx("div",{style:by,role:"status","aria-live":"polite",children:d})]})}const wo="suveren:updatedTo";function Ny(e){return 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"}function Ey(){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 Df(){const{updateAvailable:e,installMethod:t,version:n,latestVersion:r,serverRestarted:s,startFastPolling:o,dismiss:i}=Cl(),[l,c]=u.useState(!1),[d,f]=u.useState(!1),[m,p]=u.useState(()=>{try{const y=sessionStorage.getItem(wo);if(y)return sessionStorage.removeItem(wo),y}catch{}return null}),x=Ny(t),w=u.useRef(null),v=y=>{try{sessionStorage.setItem(wo,y||r||"✓")}catch{}window.location.reload()};u.useEffect(()=>{if(!m)return;const y=setTimeout(()=>p(null),6e3);return()=>clearTimeout(y)},[m]),u.useEffect(()=>{if(!l||!s)return;const y=()=>Ey()?!1:(v(n),!0);if(y())return;const S=setInterval(y,1500);return()=>clearInterval(S)},[l,s,n]),u.useEffect(()=>(document.body.classList.toggle("is-updating",l),()=>document.body.classList.remove("is-updating")),[l]);const j=e&&!l&&!m||!!m&&!l;u.useEffect(()=>{if(!j){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 I;const k=((I=w.current)==null?void 0:I.offsetHeight)??0;document.documentElement.style.setProperty("--update-banner-h",`${k}px`)};y();const S=new ResizeObserver(y);return w.current&&S.observe(w.current),()=>{S.disconnect(),document.documentElement.style.removeProperty("--update-banner-h"),document.body.classList.remove("has-update-banner")}},[j]);const h=()=>{c(!0),o()},g=async()=>{try{await navigator.clipboard.writeText(x),f(!0),setTimeout(()=>f(!1),1800)}catch{}};return a.jsxs(a.Fragment,{children:[m&&!l&&a.jsx("div",{ref:w,className:"update-banner is-live",role:"status","aria-live":"polite",children:a.jsxs("div",{className:"update-banner-row",children:[a.jsxs("span",{className:"update-banner-text",children:["✓"," You","’","re on the latest version",m&&m!=="✓"?` — ${m} is live`:" — now live","."]}),a.jsx("button",{className:"update-banner-x",onClick:()=>p(null),"aria-label":"Dismiss",children:"×"})]})}),e&&!l&&!m&&a.jsx("div",{ref:w,className:"update-banner",role:"status","aria-live":"polite",children:a.jsxs("div",{className:"update-banner-row",children:[a.jsx("span",{className:"update-banner-text",children:"Update available."}),a.jsxs("div",{style:{display:"flex",gap:"0.5rem",alignItems:"center"},children:[a.jsx("button",{className:"btn btn-sm btn-secondary",onClick:h,children:"Update"}),a.jsx("button",{className:"update-banner-x",onClick:i,"aria-label":"Dismiss",children:"×"})]})]})}),l&&a.jsx("div",{className:"update-overlay",children:a.jsxs("div",{className:"update-overlay-card",role:"dialog","aria-modal":"true","aria-label":"Finishing the update",children:[a.jsx("div",{className:"update-spinner"}),a.jsxs("h2",{children:["Finishing the update","…"]}),a.jsxs("p",{children:["Copy this command and run it in your terminal. The gateway will restart, and"," ",a.jsx("strong",{children:"this page updates automatically"})," when it comes back ","—"," no need to refresh."]}),a.jsxs("div",{className:"update-cmd-row",children:[a.jsx("code",{className:"update-cmd",children:x}),a.jsx("button",{className:"btn btn-sm btn-primary",onClick:g,children:d?"Copied":"Copy"})]}),a.jsxs("div",{className:"update-status",children:[a.jsx("span",{className:"update-pulse"})," Waiting for the gateway to restart","…"]}),a.jsxs("div",{className:"update-overlay-actions",children:[a.jsx("button",{className:"btn btn-primary",onClick:()=>v(n),children:"Reload now"}),a.jsx("button",{className:"btn btn-secondary",onClick:()=>c(!1),children:"Cancel"})]})]})})]})}const Ty={system:"◑",light:"☀",dark:"☾"},zy=[{to:"/",icon:"□",label:"Dashboard"},{to:"/proposals",icon:"▷",label:"Pending Approvals"},{to:"/authorizations",icon:"☰",label:"Mandates"},{to:"/agent-brief",icon:"▤",label:"Agent Brief"},{to:"/audit",icon:"▣",label:"Tickets"},{to:"/groups",icon:"◉",label:"Team"},{to:"/integrations",icon:"⧗",label:"Integrations"},{to:"/settings",icon:"⚙",label:"AI Assistant"}];function Iy({open:e,onClose:t}){const{user:n,activeGroup:r,activeDomain:s,logout:o}=Ae(),{theme:i,toggle:l}=Ff(),c=kt();return u.useEffect(()=>{t()},[c.pathname]),e?a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"mobile-menu-backdrop",onClick:t}),a.jsxs("div",{className:"mobile-menu-panel",children:[n&&a.jsxs("div",{className:"mobile-menu-header",children:[a.jsx("strong",{children:n.name}),a.jsx("span",{style:{fontSize:"0.8rem",color:"var(--text-secondary)"},children:r?`${r.name} / ${s}`:s||"personal"})]}),a.jsx("nav",{className:"mobile-menu-nav",children:zy.map(d=>a.jsxs(bl,{to:d.to,end:d.to==="/",className:({isActive:f})=>`mobile-menu-item${f?" active":""}`,onClick:t,children:[a.jsx("span",{className:"icon",children:d.icon}),d.label]},d.to))}),a.jsxs("div",{className:"mobile-menu-footer",children:[a.jsxs("button",{className:"mobile-menu-action",onClick:()=>{l()},children:[a.jsx("span",{className:"icon",children:Ty[i]}),"Theme: ",i]}),a.jsx("button",{className:"mobile-menu-action",onClick:()=>{o(),t()},children:"Logout"})]})]})]}):null}function Uf(e){return e.status==="pending"}function Ry(e,t){return e.filter(Uf).length+t.length}const jn=["proposal-added","proposal-resolved","proposal-approved","proposal-rejected","action-approval-needed","action-resolved","team-membership-changed"],Py=500;function _y(){const{user:e,domain:t}=Ae(),[n,r]=u.useState(0),s=u.useRef(null),o=u.useCallback(async()=>{if(!e){r(0);return}try{const[l,c]=await Promise.all([$.getProposals(t||"owner").catch(()=>[]),$.getProposalsForApprover().catch(()=>[])]);r(Ry(l,c))}catch{r(0)}},[e,t]),i=u.useCallback(()=>{s.current&&clearTimeout(s.current),s.current=setTimeout(()=>{o()},Py)},[o]);return u.useEffect(()=>(o(),()=>{s.current&&clearTimeout(s.current)}),[o]),ue(jn[0],i),ue(jn[1],i),ue(jn[2],i),ue(jn[3],i),ue(jn[4],i),ue(jn[5],i),ue(jn[6],i),n}const Gc="Suveren",Ay="/favicon.svg",$y="M 104.94 61.85 A 41 41 0 1 1 45.39 27.47",As={x1:74.54,y1:22.74,x2:94.46,y2:34.24},Ly=14,My="#f59e0b";function Fy(e){const t=Wf(e);return t>0?`(${t}) ${Gc}`:Gc}function Wf(e){return Number.isFinite(e)&&e>0?Math.floor(e):0}function Oy(){const e=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128" fill="none">
|
|
52
52
|
<path class="m" d="${$y}"/>
|
|
53
53
|
<line class="m" x1="${As.x1}" y1="${As.y1}" x2="${As.x2}" y2="${As.y2}"/>
|
|
54
54
|
<circle cx="103" cy="103" r="25" fill="${My}"/>
|
|
@@ -71,7 +71,7 @@ Watch out — What should the agent avoid or be careful about?`;function Ev(e,t,
|
|
|
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
|
-
`}),m?a.jsx("p",{style:{color:"var(--text-tertiary)",fontSize:"0.9rem"},children:"Loading..."}):k.length===0?a.jsxs("div",{className:"card",style:{padding:"2rem",textAlign:"center"},children:[a.jsx("p",{style:{color:"var(--text-secondary)",fontSize:"0.9rem",marginBottom:"1rem"},children:"No integrations set up yet. Connect a service first."}),a.jsx(Qe,{to:"/integrations",className:"btn btn-primary btn-sm",onClick:()=>e==null?void 0:e(),children:"Go to Integrations"})]}):a.jsx("div",{className:"profile-grid",children:k.map(({manifest:C,profile:z,integration:D})=>{const Y=I(z.id),K=(D==null?void 0:D.running)===!0;return a.jsxs("div",{className:"card",style:K?void 0:{opacity:.7},children:[a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem",marginBottom:"0.125rem"},children:[a.jsx("h3",{className:"card-title",style:{margin:0},children:C.name}),Y?a.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"}):a.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"})]}),a.jsx("p",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)",marginBottom:"1rem",flex:1},children:C.description||z.description}),K?a.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>_(z.id,C),children:"Authorize"}):a.jsxs(Qe,{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 Wv={active:"Active",pending:"Pending",expired:"Expired",revoked:"Revoked"};function Hv({status:e,label:t}){return a.jsx("span",{className:`status-badge status-${e}`,children:t||Wv[e]})}function Vv({domain:e,attested:t}){const n=t===!0?"domain-attested":t===!1?"domain-missing":"";return a.jsx("span",{className:`domain-badge ${n}`,style:{fontSize:"0.75rem"},children:e})}const Cn=86400,_r=3600,Ls=60,Gv=30*Cn;function Kv(e){if(e<=0)return"Expired";if(e>90*Cn){const t=Math.floor(e/Gv);return`${t} ${t===1?"month":"months"} remaining`}if(e>7*Cn){const t=Math.floor(e/Cn);return`${t} ${t===1?"day":"days"} remaining`}if(e>=2*Cn){const t=Math.floor(e/Cn),n=Math.floor(e%Cn/_r);return`${t} ${t===1?"day":"days"} ${n}h remaining`}if(e>=2*_r){const t=Math.floor(e/_r),n=Math.floor(e%_r/Ls);return`${t}h ${String(n).padStart(2,"0")}m remaining`}if(e>=Ls){const t=Math.floor(e/Ls),n=Math.floor(e%Ls);return`${t}m ${String(n).padStart(2,"0")}s remaining`}return`${Math.floor(e)}s remaining`}function Yv({expiresAt:e}){const[t,n]=u.useState(()=>e-Date.now()/1e3),r=t<2*_r;u.useEffect(()=>{const o=setInterval(()=>n(e-Date.now()/1e3),r?1e3:6e4);return()=>clearInterval(o)},[e,r]);const s=t<300;return a.jsx("span",{className:`ttl-badge ${s?"ttl-warn":"ttl-ok"}`,children:Kv(t)})}function Zf({icon:e,title:t,text:n,children:r}){return a.jsxs("div",{className:"empty-state",children:[e&&a.jsx("div",{className:"empty-state-icon",children:e}),a.jsx("div",{className:"empty-state-title",children:t}),n&&a.jsx("div",{className:"empty-state-text",children:n}),r]})}function Qv(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 Jv=[{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 Xv({item:e,onClose:t,onSuccess:n}){var y;const{user:r,activeDomain:s,groupId:o}=Ae(),[i,l]=u.useState(null);u.useEffect(()=>{let S=!1;return $.getProfile(e.profile_id).then(k=>{var I;S||l(((I=k==null?void 0:k.ttl)==null?void 0:I.max)??null)}).catch(()=>{}),()=>{S=!0}},[e.profile_id]);const c=e.remaining_seconds??0,d=Jv.filter(S=>S.seconds>c&&(i===null||S.seconds<=i)),f=((y=d[0])==null?void 0:y.seconds)??2592e3,[m,p]=u.useState(f);u.useEffect(()=>{var S;if(i!==null&&m>i){const k=(S=d[d.length-1])==null?void 0:S.seconds;k&&p(k)}},[i]);const[x,w]=u.useState(!1),[v,j]=u.useState(""),h=Object.entries(e.frame).filter(([S])=>S!=="profile"&&S!=="path"),g=async()=>{var S;if(r){w(!0),j("");try{const k=e.authorization_id,I=await $.getGateContent(k);if(!I)throw new Error("Gate content not found locally. The MCP server may have restarted. Please re-authorize through the full wizard instead.");const R=await $.getProfile(e.profile_id),_=e.frame,C=I.context??{},z=e.attested_domains[0]||s||"owner",D=await Xs(_,R),Y=await Jf(C,R),[K,W]=await Promise.all([ba(I.gateContent.intent),ba(JSON.stringify({profile:e.profile_id,path:e.path,domain:z}))]);if(!o)throw new Error("No active group; cannot extend authorization.");const T=(((S=e.deferred_commitment_domains)==null?void 0:S.length)??0)>0?"review":"automatic",q=await $.attest({authorization_id:e.authorization_id,renew:!0,profile_id:e.profile_id,bounds:_,bounds_hash:D,context_hash:Y,domain:z,did:r.did,gate_content_hashes:{intent:K},execution_context_hash:W,group_id:o,commitment_mode:T,ttl:m});await $.pushGateContent(Xf(q,{boundsHash:D,contextHash:Y,context:C,path:e.path,gateContent:I.gateContent})),n()}catch(k){j(k instanceof Error?k.message:"Extension failed")}finally{w(!1)}}};return a.jsx("div",{className:"modal-backdrop",onClick:S=>S.target===S.currentTarget&&t(),children:a.jsxs("div",{className:"modal",children:[a.jsxs("div",{className:"modal-header",children:[a.jsx("h3",{className:"modal-title",children:"Extend Authorization"}),a.jsx("button",{className:"modal-close",onClick:t,children:"×"})]}),a.jsxs("div",{className:"modal-body",children:[a.jsxs("div",{style:{marginBottom:"1rem"},children:[a.jsxs("div",{style:{fontWeight:600,marginBottom:"0.25rem"},children:[ze(e.profile_id)," / ",e.path]}),h.length>0&&a.jsx("div",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)"},children:h.map(([S,k])=>`${S}=${k}`).join(" · ")})]}),a.jsxs("div",{style:{marginBottom:"1rem"},children:[a.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&&a.jsxs("div",{style:{fontSize:"0.75rem",color:"var(--text-tertiary)",marginBottom:"0.5rem"},children:["Currently valid for ",Qv(c),". Only longer durations are shown."]}),a.jsx("div",{style:{display:"flex",gap:"0.5rem",flexWrap:"wrap"},children:d.length===0?a.jsx("div",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)"},children:"This authorization is already on the longest available duration. Nothing to extend."}):d.map(S=>a.jsx("button",{className:`btn ${m===S.seconds?"btn-primary":"btn-secondary"}`,onClick:()=>p(S.seconds),style:{minWidth:"3.5rem"},children:S.label},S.seconds))})]}),a.jsx("div",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)",marginBottom:"0.5rem"},children:"Same bounds, context, and gate content will be re-attested with a new TTL (measured from now)."}),v&&a.jsx("div",{className:"error-message",children:v})]}),a.jsxs("div",{className:"modal-footer",children:[a.jsx("button",{className:"btn btn-secondary",onClick:t,disabled:x,children:"Cancel"}),a.jsx("button",{className:"btn btn-primary",onClick:g,disabled:x,children:x?"Extending...":"Extend"})]})]})})}function qv(e,t,n){return[...e].sort((r,s)=>{if(n){if(r.authorization_id===n&&s.authorization_id!==n)return-1;if(s.authorization_id===n&&r.authorization_id!==n)return 1}const o=At(r,{revokedSet:t}),i=At(s,{revokedSet:t}),l={active:0,pending:1,expired:2,revoked:3};return l[o]!==l[i]?l[o]-l[i]:new Date(s.created_at).getTime()-new Date(r.created_at).getTime()})}function Zv({item:e,newerProfile:t,revokedSet:n,expandedHash:r,gateCache:s,gateLoading:o,copiedHash:i,revokingHash:l,copyingHash:c,profileConfigCache:d,mode:f,ownerLabel:m,isAdmin:p,onExpand:x,onCopyHash:w,onCopy:v,onRevoke:j,onExtend:h,highlightHash:g}){var U;const y=At(e,{revokedSet:n}),S=r===e.authorization_id,k=s[e.authorization_id],I=y==="active"||y==="pending"||y==="expired",R=Object.entries(e.frame).filter(([O])=>O!=="profile"&&O!=="path"),_=d.get(e.profile_id)??null,C=(((U=_==null?void 0:_.approvers)==null?void 0:U.length)??0)>0,z=new Map;if(_!=null&&_.caps&&f==="team")for(const[O,G]of R){const X=_.caps[O];X!==void 0&&Number(G)>X&&z.set(O,{authorized:Number(G),cap:X})}const D=z.size>0,Y=e.approvers_frozen??[],K=(_==null?void 0:_.approvers)??[],W=f==="team"&&Y.length>0&&K.length>0&&(Y.length!==K.length||Y.some(O=>!K.includes(O))||K.some(O=>!Y.includes(O))),T=Array.from(z.entries()).map(([O,G])=>`${O}: ${G.authorized} (cap ${G.cap})`).join(", "),q=Array.from(z.entries()).map(([O,G])=>`${O}: ${G.authorized} → ${G.cap}`).join(", "),ee=D?C?z.size===1?`Above team cap: ${T} — actions require approval`:`Above team cap (${z.size}): ${T} — actions require approval`:z.size===1?`Reduced by hard cap: ${q}`:`Reduced by hard cap (${z.size}): ${q}`:"",F=D?C?"Above-cap actions under this authority 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 authorization to reissue within the cap.":void 0,L=ze(e.profile_id),H=t?a.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:[a.jsxs("strong",{style:{color:"var(--text-secondary)"},children:[L,"@",t.version," available"]}),t.whatsNew?a.jsxs(a.Fragment,{children:[" — ",t.whatsNew]}):null,a.jsx("br",{}),a.jsxs("span",{children:["This authority stays on ",e.profile_id.split("@")[1]??"its pinned version","; authorize again to move it."]})]}):null,A=g!=null&&e.authorization_id===g;return a.jsxs("div",{className:`card${A?" card-highlight":""}`,style:{marginBottom:0},children:[H,m&&a.jsxs("div",{style:{fontSize:"0.75rem",color:"var(--text-tertiary)",marginBottom:"0.375rem"},children:["Owner: ",a.jsx("span",{style:{color:"var(--text-secondary)",fontWeight:500},children:m})]}),a.jsxs("div",{className:"auth-card-header",children:[a.jsx("span",{style:{fontWeight:700,fontSize:"1rem",color:"var(--text-primary)",letterSpacing:"0.01em"},children:L}),e.title&&a.jsx("span",{style:{fontWeight:500,fontSize:"0.85rem",color:"var(--text-secondary)"},children:e.title}),a.jsx(Hv,{status:y}),y==="active"&&e.earliest_expiry&&a.jsx(Yv,{expiresAt:new Date(e.earliest_expiry).getTime()/1e3}),y==="expired"&&(()=>{const O=hy(e,y);return O?a.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-tertiary)"},title:`Expired ${new Date(O.iso).toLocaleString()}`,children:new Date(O.iso).toLocaleDateString(void 0,{month:"short",day:"numeric"})}):null})()]}),a.jsxs("div",{style:{display:"flex",gap:"0.5rem",flexWrap:"wrap",marginBottom:"0.5rem",alignItems:"center"},children:[e.required_domains.map(O=>a.jsx(Vv,{domain:O,attested:e.attested_domains.includes(O)},O)),e.deferred_commitment_domains.length>0&&a.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"}),D&&a.jsx("span",{title:F,style:{fontSize:"0.65rem",padding:"0.15rem 0.4rem",borderRadius:"0.25rem",background:C?"var(--accent-subtle)":"var(--danger-subtle)",color:C?"var(--accent)":"var(--danger)",fontWeight:600,cursor:"help"},children:ee}),W&&a.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:()=>v(e),disabled:c===e.authorization_id,title:"The approver list for this profile has changed since this authority was created. Copy to reissue with the current approvers.",children:c===e.authorization_id?"Copying...":"Approver list updated · Copy with new approvers"})]}),R.length>0&&a.jsx("div",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)"},children:R.map(([O,G],X)=>{const Z=z.get(O);return a.jsxs("span",{children:[X>0&&" · ",Z?C?a.jsxs("span",{title:`Team cap on ${O} is ${Z.cap}. Actions exceeding the cap require per-action approval. Bound remains authorized at ${Z.authorized}.`,children:[a.jsxs("span",{style:{color:"var(--text-tertiary)"},children:[O,"=",String(G)]}),a.jsxs("span",{style:{color:"var(--accent)",marginLeft:"0.25rem",fontWeight:600},children:["↑ approval at ",Z.cap]})]}):a.jsxs("span",{title:`Team cap on ${O} is ${Z.cap} with no approvers configured (hard cap). Authorized for ${Z.authorized}; effective ${Z.cap}.`,children:[a.jsxs("span",{style:{textDecoration:"line-through",color:"var(--text-tertiary)"},children:[O,"=",String(G)]}),a.jsxs("span",{style:{color:"var(--danger)",marginLeft:"0.25rem",fontWeight:600},children:["→"," ",Z.cap]})]}):a.jsxs("span",{children:[O,"=",String(G)]})]},O)})}),a.jsx("div",{style:{display:"flex",justifyContent:"flex-end",gap:"0.5rem",marginTop:"0.5rem"},children:a.jsx("button",{className:"btn btn-ghost btn-sm",onClick:()=>x(e),children:S?"▲ Hide Details":"▼ Details"})}),S&&a.jsxs("div",{style:{borderTop:"1px solid var(--border)",marginTop:"0.75rem",paddingTop:"0.75rem"},children:[R.length>0&&a.jsxs(a.Fragment,{children:[a.jsx("div",{style:{fontSize:"0.75rem",fontWeight:600,color:"var(--text-tertiary)",textTransform:"uppercase",letterSpacing:"0.04em",marginBottom:"0.25rem"},children:"Bounds"}),a.jsx("dl",{className:"review-grid",children:R.map(([O,G])=>a.jsxs("span",{style:{display:"contents"},children:[a.jsx("dt",{children:O}),a.jsx("dd",{children:String(G)})]},O))})]}),(k==null?void 0:k.context)&&Object.keys(k.context).length>0&&a.jsxs(a.Fragment,{children:[a.jsx("div",{style:{fontSize:"0.75rem",fontWeight:600,color:"var(--text-tertiary)",textTransform:"uppercase",letterSpacing:"0.04em",marginTop:"1rem",marginBottom:"0.25rem"},children:"Context"}),a.jsx("dl",{className:"review-grid",children:Object.entries(k.context).map(([O,G])=>a.jsxs("span",{style:{display:"contents"},children:[a.jsx("dt",{children:O}),a.jsx("dd",{title:String(G),children:qf(O,G,k.contextLabels)})]},O))})]}),a.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?a.jsx("p",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)"},children:"Loading gate content..."}):k?a.jsx("div",{className:"gate-content-block",children:a.jsx("div",{className:"gate-content-item",children:a.jsx("div",{className:"gate-content-text",children:k.gateContent.intent})})}):a.jsx("p",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)"},children:"Gate content not available."}),a.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()}`]}),a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem",marginTop:"0.25rem"},children:[a.jsx("span",{style:{fontSize:"0.7rem",color:"var(--text-tertiary)",fontFamily:"'SF Mono', Monaco, monospace",wordBreak:"break-all"},children:e.authorization_id}),a.jsx("button",{className:"btn btn-ghost btn-sm",style:{fontSize:"0.7rem",padding:"0.125rem 0.375rem"},onClick:()=>w(e.authorization_id),children:i===e.authorization_id?"copied":"copy"})]}),a.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:"0.5rem",marginTop:"0.75rem"},children:[!m&&a.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>v(e),disabled:c===e.authorization_id,title:"Start a new authorization pre-filled with these bounds, context, and intent",children:c===e.authorization_id?"Copying…":"⧉ Copy"}),!m&&(y==="active"||y==="pending")&&a.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>v(e,{asEdit:!0}),disabled:c===e.authorization_id,title:"Adjust intent, bounds, or scope: opens the ceremony pre-filled; signing the new authorization revokes this one",children:"✎ Edit"}),!m&&I&&a.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>h(e),children:"↻ Extend"}),m&&p&&y!=="revoked"?a.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>j(e.authorization_id,m,L),disabled:l===e.authorization_id,children:l===e.authorization_id?"Revoking…":"Revoke"}):!m&&(y==="active"||y==="pending")?a.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>j(e.authorization_id),disabled:l===e.authorization_id,children:l===e.authorization_id?"Revoking…":"Revoke"}):null]})]})]},e.authorization_id)}function ex(){const[e,t]=u.useState([]),[n,r]=u.useState(!0),[s,o]=u.useState([]),[i,l]=u.useState(!1),[c,d]=u.useState(new Map),[f,m]=u.useState("mine"),[p,x]=u.useState("active"),[w,v]=u.useState(null),[j,h]=u.useState(null),[g,y]=Af(),[S,k]=u.useState(()=>g.get("new")==="1"),[I,R]=u.useState(()=>g.get("highlight")),[_,C]=u.useState(null),[z,D]=u.useState({}),[Y,K]=u.useState(null),[W,T]=u.useState(null),[q,ee]=u.useState(null),[F,L]=u.useState(new Set),[H,A]=u.useState(null),[U,O]=u.useState(null),G=qt(),{group:X,groupId:Z,domain:de,mode:$e,activeTeam:Be}=Ae(),le=(Be==null?void 0:Be.isAdmin)===!0,[M,J]=u.useState(()=>new Map),te=u.useCallback(()=>{r(!0),$.getMyAttestations().then(t).catch(()=>{}).finally(()=>r(!1))},[]),he=u.useCallback(()=>{Z&&(l(!0),$.listTeamAuthorizations(Z).then(o).catch(()=>{}).finally(()=>l(!1)))},[Z]);ue("attestation-changed",()=>{te(),le&&Z&&he()}),u.useEffect(()=>{if(!I)return;g.get("highlight")&&(g.delete("highlight"),y(g,{replace:!0}));const N=window.setTimeout(()=>R(null),3e3);return()=>window.clearTimeout(N)},[]),Lt(te,3e5),u.useEffect(()=>{f==="team"&&le&&Z&&s.length===0&&!i&&he()},[f,le,Z,s.length,i,he]),u.useEffect(()=>{let N=!1;return $.listProfiles().then(E=>{if(N)return;const V=ie=>ie.replace(/@.*$/,"").split("/").pop()??ie,ne=ie=>ie.split("@")[1]??"",ce=new Map;for(const ie of E){const Ce=V(ie.id),Ze=ce.get(Ce);(!Ze||ne(ie.id).localeCompare(ne(Ze.id),void 0,{numeric:!0})>0)&&ce.set(Ce,ie)}d(ce)}).catch(()=>{}),()=>{N=!0}},[]);const pe=u.useCallback(N=>{const E=Ce=>Ce.replace(/@.*$/,"").split("/").pop()??Ce,V=Ce=>Ce.split("@")[1]??"",ne=c.get(E(N));if(!ne)return;const ce=V(N),ie=V(ne.id);if(!(!ce||!ie))return ie.localeCompare(ce,void 0,{numeric:!0})>0?ne:void 0},[c]);u.useEffect(()=>{if($e!=="team"||!Z)return;const N=f==="mine"?e:s;if(N.length===0)return;const E=[...new Set(N.map(V=>V.profile_id))].filter(V=>!M.has(V));if(E.length!==0){J(V=>{const ne=new Map(V);for(const ce of E)ne.set(ce,null);return ne});for(const V of E)$.getTeamProfileConfig(Z,V).then(ne=>{J(ce=>new Map(ce).set(V,ne))}).catch(()=>{})}},[e,s,f,Z,$e,M]);const Le=async N=>{if(_===N.authorization_id){C(null);return}C(N.authorization_id);const E=N.authorization_id;if(!(E in z)){K(N.authorization_id);try{const V=await $.getGateContent(E);D(ne=>({...ne,[E]:V}))}catch{D(V=>({...V,[E]:null}))}finally{K(null)}}},ot=N=>{navigator.clipboard.writeText(N).then(()=>{ee(N),setTimeout(()=>ee(null),2e3)})},De=async(N,E)=>{var V;if(!Z){alert("No active group; cannot copy authorization.");return}O(N.authorization_id);try{const ne=N.authorization_id;let ce=z[ne]??null;ne in z||(ce=await $.getGateContent(ne),D(On=>({...On,[ne]:ce})));const ie=Object.fromEntries(Object.entries(N.frame).filter(([On])=>On!=="profile"&&On!=="path")),Ce=(ce==null?void 0:ce.context)??{},Ze=((V=ce==null?void 0:ce.gateContent)==null?void 0:V.intent)??"",et=N.deferred_commitment_domains.length>0?"review":"automatic",Sn=N.attested_domains[0]||de||"owner",it=Date.parse(N.created_at),ae=N.earliest_expiry?Date.parse(N.earliest_expiry):NaN,Bt=Number.isFinite(it)&&Number.isFinite(ae)&&ae>it?Math.round((ae-it)/1e3):void 0;sessionStorage.setItem("agentAuth",JSON.stringify({profileId:N.profile_id,groupId:Z,groupName:(X==null?void 0:X.name)??null,domain:Sn})),sessionStorage.setItem("agentGate",JSON.stringify({bounds:ie,context:Ce,gateContent:{intent:Ze},templateMode:et,templateTtl:Bt})),E!=null&&E.asEdit?sessionStorage.setItem("agentEditReplaces",N.authorization_id):sessionStorage.removeItem("agentEditReplaces"),G("/agent/gate")}catch(ne){alert(ne instanceof Error?ne.message:"Failed to copy authorization")}finally{O(null)}},ht=async(N,E,V)=>{const ne=E&&V?`Revoke ${E}'s ${V} authorization? This cannot be undone.`:"Revoke this authorization? The agent will no longer be able to execute actions under this attestation.";if(confirm(ne)){A(N);try{await $.revokeAttestation(N),L(ce=>new Set(ce).add(N)),$.resyncGates().catch(()=>{}),E&&Z&&he()}catch(ce){alert(ce instanceof Error?ce.message:"Failed to revoke authorization")}finally{A(null)}}},Ie=f==="mine"?e:s,Ke=f==="mine"?n:i,se={active:Ie.filter(N=>At(N,{revokedSet:F})==="active").length,pending:Ie.filter(N=>At(N,{revokedSet:F})==="pending").length,expired:Ie.filter(N=>At(N,{revokedSet:F})==="expired").length,revoked:Ie.filter(N=>At(N,{revokedSet:F})==="revoked").length},Ue=(()=>{const N=new Map;for(const E of Ie){if(At(E,{revokedSet:F})!==p)continue;const V=N.get(E.profile_id)??{count:0,review:!1};V.count+=1,E.deferred_commitment_domains.length>0&&(V.review=!0),N.set(E.profile_id,V)}return Array.from(N.entries()).map(([E,V])=>({profileId:E,...V})).sort((E,V)=>ze(E.profileId).localeCompare(ze(V.profileId)))})(),P=qv(Ie.filter(N=>{if(At(N,{revokedSet:F})!==p||w!==null&&N.profile_id!==w)return!1;if(j!==null){const E=N.deferred_commitment_domains.length>0;if(j==="review"&&!E||j==="auto"&&E)return!1}return!0}),F,I),b={revokedSet:F,expandedHash:_,gateCache:z,gateLoading:Y,copiedHash:q,revokingHash:H,copyingHash:U,profileConfigCache:M,mode:$e,activeDomain:de,group:X,groupId:Z,onExpand:Le,onCopyHash:ot,onCopy:De,onRevoke:ht,onExtend:T,highlightHash:I};return a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"page-header",style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",gap:"1rem",flexWrap:"wrap"},children:[a.jsxs("div",{children:[a.jsx("h1",{className:"page-title",children:"Authorizations"}),a.jsx("p",{className:"page-subtitle",children:"Active, pending, and expired agent authorizations."})]}),a.jsx("button",{className:"btn btn-primary",onClick:()=>k(!0),children:"+ New authorization"})]}),S&&a.jsx("div",{className:"modal-backdrop",onClick:()=>{k(!1),g.get("new")&&(g.delete("new"),y(g,{replace:!0}))},children:a.jsxs("div",{className:"modal",onClick:N=>N.stopPropagation(),style:{maxWidth:"960px",width:"90vw"},children:[a.jsxs("div",{className:"modal-header",children:[a.jsx("h2",{className:"modal-title",children:"New authorization"}),a.jsx("button",{className:"modal-close",onClick:()=>{k(!1),g.get("new")&&(g.delete("new"),y(g,{replace:!0}))},children:"×"})]}),a.jsxs("div",{className:"modal-body",children:[a.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."}),a.jsx(Uv,{onDismiss:()=>k(!1)})]})]})}),le&&a.jsxs("div",{className:"nav-tabs",style:{marginBottom:"0.5rem"},children:[a.jsx("button",{className:`nav-tab${f==="mine"?" active":""}`,onClick:()=>{m("mine"),x("active"),v(null),h(null),C(null)},children:"Mine"}),a.jsx("button",{className:`nav-tab${f==="team"?" active":""}`,onClick:()=>{m("team"),x("active"),v(null),h(null),C(null)},children:"Team"})]}),a.jsx("div",{className:"nav-tabs",children:["active","pending","expired","revoked"].map(N=>a.jsxs("button",{className:`nav-tab${p===N?" active":""}`,onClick:()=>{x(N),v(null),h(null)},children:[N.charAt(0).toUpperCase()+N.slice(1)," (",se[N],")"]},N))}),Ue.length>0&&a.jsxs("div",{style:{display:"flex",gap:"0.5rem",flexWrap:"wrap",alignItems:"center",marginTop:"-0.25rem",marginBottom:"1rem"},children:[Ue.map(N=>{const E=w===N.profileId;return a.jsx("button",{className:`btn btn-sm ${E?"btn-primary":"btn-secondary"}`,onClick:()=>v(E?null:N.profileId),children:ze(N.profileId)},N.profileId)}),a.jsx("span",{"aria-hidden":"true",style:{color:"var(--border)",fontSize:"1.1rem",padding:"0 0.25rem",userSelect:"none"},children:"|"}),["auto","review"].map(N=>{const E=j===N;return a.jsx("button",{className:`btn btn-sm ${E?"btn-primary":"btn-secondary"}`,onClick:()=>h(E?null:N),children:N==="auto"?"Auto":"Review"},N)})]}),Ke&&Ie.length===0?a.jsx("p",{style:{color:"var(--text-tertiary)"},children:"Loading..."}):P.length===0?a.jsx(Zf,{icon:"☰",title:"No authorizations",text:`No ${p} authorizations found.`}):a.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem"},children:P.map(N=>{const E=f==="team"?N:null,V=E!=null&&E.owner?E.owner.name??E.owner.email??E.owner.userId:void 0;return a.jsx(Zv,{item:N,newerProfile:pe(N.profile_id),ownerLabel:V,isAdmin:le,...b},N.authorization_id)})}),W&&a.jsx(Xv,{item:W,onClose:()=>T(null),onSuccess:()=>{T(null),te()}})]})}function tx(e){const t=e.indexOf("__");return t<0?{integrationId:"",toolName:e}:{integrationId:e.slice(0,t),toolName:e.slice(t+2)}}function nx(e,t){var c,d,f;const{integrationId:n,toolName:r}=tx(e.action),s=t.find(m=>m.id===n),o=(d=(c=s==null?void 0:s.toolGating)==null?void 0:c.overrides)==null?void 0:d[r];if(o!=null&&o.actionLabel)return o.actionLabel;const i=ze(e.profileId),l=(f=e.executionContext)==null?void 0:f.action_type;return typeof l=="string"&&l?`${i} · ${l}`:`${i} · ${r}`}function rx(e){const t=[];for(const[n,r]of Object.entries(e.executionContext??{})){if(!n.startsWith("allowed_"))continue;const s=String(r??"").trim();s&&t.push(s.split(",").map(o=>o.trim()).filter(Boolean).join(", "))}return t.join(" · ")}function sx(e){if(!e)return"";const t=[];for(const[n,r]of Object.entries(e)){if(n==="action_type")continue;const s=String(r??"").trim();if(!s)continue;const o=n.replace(/^allowed_/,"").replace(/_/g," ");t.push(`${o} ${s.split(",").map(i=>i.trim()).filter(Boolean).join(", ")}`)}return t.join(" · ")}function ax(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),s=[];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`,m=Object.keys(t??{}).filter(j=>j.endsWith(f)),p=(r&&m.find(j=>j.startsWith(`${r}_`)))??(m.length===1?m[0]:void 0),w=(p?/^(amount|spend)_/.test(p):!1)?d.amount:d.count,v=p?Number(t==null?void 0:t[p]):NaN;p&&Number.isFinite(v)?s.push(`${w} of ${v} ${c}`):s.push(`${d.count} ${d.count===1?"call":"calls"} ${c}`)}return s.join(" · ")}function ox(e){return typeof e.proposalId=="string"&&e.proposalId.length>0}function ix(e){const t=ze(e),n=e.split("@")[1];return n?`${t}@${n}`:t}function Tr({label:e,children:t}){return a.jsxs(a.Fragment,{children:[a.jsx("dt",{className:"receipt-row-label",children:e}),a.jsx("dd",{className:"receipt-row-value",children:t})]})}function lx({receipt:e,manifests:t,localAuth:n,localUnavailable:r,signature:s,grantTitle:o,ownerLabel:i,spUrl:l,formatDate:c,onOpenComplete:d}){var w;const f=rx(e),m=sx(n==null?void 0:n.context),p=ax(e,(n==null?void 0:n.bounds)??e.limits),x=n==null?void 0:n.intent;return a.jsxs("div",{className:"card",style:{marginBottom:0},children:[a.jsxs("div",{className:"receipt-head",children:[a.jsx("span",{className:"receipt-what",children:nx(e,t)}),a.jsx("span",{className:"receipt-tag",children:ox(e)?"review":"automatic"}),e.contentHash&&a.jsx("span",{className:"receipt-tag receipt-tag-bound",title:(w=e.contentBinding)!=null&&w.fields?`The receipt binds: ${e.contentBinding.fields.join(", ")}`:"This exact content was authorized",children:"content bound"}),a.jsx("span",{className:"auth-card-time",children:c(e.timestamp)})]}),f&&a.jsx("div",{className:"receipt-scope",children:f}),a.jsxs("dl",{className:"receipt-rows",children:[a.jsx(Tr,{label:"authorization",children:a.jsx("strong",{children:o||ix(e.profileId)})}),i&&a.jsx(Tr,{label:"owner",children:i}),m&&a.jsx(Tr,{label:"allowed",children:m}),p&&a.jsx(Tr,{label:"used",children:a.jsx("span",{className:"receipt-num",children:p})}),a.jsx(Tr,{label:"intent",children:x?a.jsx("span",{className:"receipt-intent",children:x}):a.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"})})]}),a.jsxs("div",{className:"receipt-foot",children:[s==="valid"&&a.jsx("span",{className:"receipt-verified",title:"Ed25519 signature checked on this device against the issuer key archived when the receipt was issued — no Authority Server involved.",children:"✓ Verified on this device"}),s==="invalid"&&a.jsx("span",{className:"receipt-tamper",title:"The stored receipt does not match what was signed.",children:"⚠ Signature check FAILED"}),a.jsx("button",{type:"button",className:"receipt-evidence-link",onClick:d,children:"Complete receipt"}),l&&a.jsxs("span",{className:"receipt-public",children:["redacted, shareable:"," ",a.jsx("a",{className:"receipt-link",href:`${l}/r/${e.id}`,target:"_blank",rel:"noreferrer",children:"public link ↗"})]})]}),a.jsxs("details",{className:"receipt-more",children:[a.jsx("summary",{children:"Raw"}),a.jsxs("div",{className:"receipt-kv",children:[a.jsxs("div",{children:["receipt · ",e.id]}),a.jsxs("div",{children:["action · ",e.action]}),a.jsxs("div",{children:["profile · ",e.profileId]}),e.authorizationId&&a.jsxs("div",{children:["authorization · ",e.authorizationId]}),Object.keys(e.executionContext??{}).length>0&&a.jsxs("div",{children:["context ·"," ",Object.entries(e.executionContext).map(([v,j])=>`${v}=${j}`).join(" · ")]}),(n==null?void 0:n.boundsHash)&&a.jsxs("div",{children:["bounds hash · ",n.boundsHash]}),(n==null?void 0:n.contextHash)&&a.jsxs("div",{children:["context hash · ",n.contextHash]}),e.contentHash&&a.jsxs("div",{children:["content · ",e.contentHash]}),e.proposalId&&a.jsxs("div",{children:["proposal · ",e.proposalId]}),a.jsxs("div",{children:["signature · ",e.signature]})]})]})]})}function cx({receipt:e,onClose:t}){const[n,r]=u.useState(null),[s,o]=u.useState(null),[i,l]=u.useState(null),[c,d]=u.useState(!0),[f,m]=u.useState(!1);u.useEffect(()=>{let j=!1;return d(!0),$.getArchivedReceipt(e.id).then(h=>{j||(r(h),o(h?"local":"authority-server"),l((h==null?void 0:h.signature)??null))}).catch(()=>{j||o("authority-server")}).finally(()=>{j||d(!1)}),()=>{j=!0}},[e.id]);const p=n?n.entry:{receipt:e},x=JSON.stringify(p,null,2);function w(){const j=URL.createObjectURL(new Blob([x],{type:"application/json"})),h=document.createElement("a");h.href=j,h.download=`suveren-receipt-${e.id.slice(0,8)}.json`,h.click(),URL.revokeObjectURL(j)}async function v(){try{await navigator.clipboard.writeText(x),m(!0),setTimeout(()=>m(!1),2e3)}catch{m(!1)}}return a.jsx("div",{className:"modal-backdrop",onClick:j=>j.target===j.currentTarget&&t(),children:a.jsxs("div",{className:"modal",style:{maxWidth:"44rem"},children:[a.jsxs("div",{className:"modal-header",children:[a.jsx("h3",{className:"modal-title",children:"Complete receipt"}),a.jsx("button",{className:"modal-close",onClick:t,"aria-label":"Close",children:"×"})]}),a.jsxs("div",{className:"modal-body",children:[i==="valid"&&a.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 receipt was issued."}),i==="invalid"&&a.jsx("p",{className:"receipt-tamper",style:{margin:"0 0 0.5rem",fontSize:"0.8rem"},children:"⚠ Signature check FAILED — the stored receipt does not match what was signed."}),a.jsx("p",{style:{fontSize:"0.8rem",color:"var(--text-muted)",margin:"0 0 0.75rem"},children:c?"Loading…":s==="local"?"Held on this device — the signed receipt, the attestation 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 receipt (it predates local archiving, or ran on another device). Shown from the Authority Server — complete and signed, but it needs the server to retrieve."}),a.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:x})]}),a.jsxs("div",{className:"modal-footer",children:[a.jsx("button",{className:"btn btn-primary btn-sm",onClick:w,children:"Download"}),a.jsx("button",{className:"btn btn-secondary btn-sm",onClick:v,children:f?"Copied":"Copy"})]})]})})}function ux(e){return new Date(e*1e3).toLocaleString()}function dx(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 fx(e,t){if(!t)return!0;const n=t.toLowerCase();return e.profileId.toLowerCase().includes(n)||ze(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 qc(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,s)=>s.timestamp-r.timestamp)}function px(){const{activeTeam:e,groupId:t}=Ae(),n=(e==null?void 0:e.isAdmin)===!0,[r,s]=u.useState("mine"),[o,i]=u.useState([]),[l,c]=u.useState([]),[d,f]=u.useState(""),[m,p]=u.useState(!0),[x,w]=u.useState({}),[v,j]=u.useState(new Set),[h,g]=u.useState(""),[y,S]=u.useState(new Set),[k,I]=u.useState(new Set),[R,_]=u.useState("all"),[C,z]=u.useState(!1),[D,Y]=u.useState(!1),[K,W]=u.useState(null),[T,q]=u.useState({}),[ee,F]=u.useState(!1),[L,H]=u.useState({}),[A,U]=u.useState({}),[O,G]=u.useState(null),[X,Z]=u.useState(null),[de,$e]=u.useState(!1),[Be,le]=u.useState(!1),M=u.useRef(""),J=u.useCallback(b=>r==="team"&&n&&t?$.listTeamReceiptsPage(t,{before:b,limit:200}):$.getMyReceiptsPage({before:b,limit:200}),[r,n,t]),te=u.useCallback(()=>{const b=r==="team"?`team:${t}`:"mine",N=M.current!==b;M.current=b,p(!0),le(!1),J().then(E=>{i(V=>N?E.receipts:qc(V,E.receipts)),Z(V=>N?E.nextBefore:V??E.nextBefore)}).catch(()=>{N&&i([]),le(!0)}).finally(()=>p(!1))},[J,r,t]),he=u.useCallback(()=>{!X||de||($e(!0),le(!1),J(X).then(b=>{i(N=>qc(N,b.receipts)),Z(b.nextBefore)}).catch(()=>le(!0)).finally(()=>$e(!1)))},[X,de,J]);Lt(te,12e4),u.useEffect(()=>{$.getIntegrationManifests().then(({manifests:b})=>c(b)).catch(()=>{}),fetch("/health").then(b=>b.json()).then(b=>{typeof b.spUrl=="string"&&f(b.spUrl.replace(/\/$/,""))}).catch(()=>{})},[]),u.useEffect(()=>{$.getLocalAuthorizations().then(({authorizations:b,signatures:N})=>{q(b),H(N),F(!1)}).catch(()=>{q({}),H({}),F(!0)}),$.getMyAttestations().then(b=>{const N={};for(const E of b)E.authorization_id&&E.title&&(N[E.authorization_id]=E.title);U(N)}).catch(()=>{})},[]),u.useEffect(()=>{r!=="team"||Object.keys(x).length>0||$.listUsers().then(b=>{const N={};for(const E of b)N[E.id]={name:E.name,email:E.email};w(N)}).catch(()=>{})},[r,x]);const pe=u.useMemo(()=>{const b=new Set;for(const N of o)b.add(ze(N.profileId));return[...b].sort()},[o]),Le=u.useMemo(()=>{const b=new Set;for(const N of o)b.add(N.action);return[...b].sort()},[o]),ot=u.useMemo(()=>{if(r!=="team")return[];const b=new Set;for(const N of o)N.userId&&b.add(N.userId);return[...b].map(N=>{var E;return{id:N,label:(E=x[N])!=null&&E.name?`${x[N].name} (${x[N].email})`:N}}).sort((N,E)=>N.label.localeCompare(E.label))},[r,o,x]),De=u.useMemo(()=>o.filter(b=>!(!fx(b,h)||y.size>0&&!y.has(ze(b.profileId))||k.size>0&&!k.has(b.action)||v.size>0&&b.userId&&!v.has(b.userId)||!dx(b,R))),[o,h,y,k,v,R]),ht=y.size>0||k.size>0||v.size>0||R!=="all";function Ie(b){S(N=>{const E=new Set(N);return E.has(b)?E.delete(b):E.add(b),E})}function Ke(b){I(N=>{const E=new Set(N);return E.has(b)?E.delete(b):E.add(b),E})}function se(b){j(N=>{const E=new Set(N);return E.has(b)?E.delete(b):E.add(b),E})}function Ue(){S(new Set),I(new Set),j(new Set),_("all"),g("")}async function P(){Y(!0),W(null);try{const{bundle:b,filename:N}=await $.fetchEvidenceBundle(),E=URL.createObjectURL(new Blob([JSON.stringify(b,null,2)],{type:"application/json"})),V=document.createElement("a");V.href=E,V.download=N,V.click(),URL.revokeObjectURL(E);const ne=b.sources??{};ne.authorityServer?ne.local||W(`Downloaded Authority Server history only — ${ne.localError??"local archive unavailable."}`):W(`Downloaded local evidence only — ${ne.asError??"Authority Server export unavailable."}`)}catch(b){W(`Export failed: ${b instanceof Error?b.message:String(b)}`)}finally{Y(!1)}}return a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"page-header",style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",gap:"1rem",flexWrap:"wrap"},children:[a.jsxs("div",{children:[a.jsx("h1",{className:"page-title",children:"Receipts"}),a.jsx("p",{className:"page-subtitle",children:"Execution history for agent actions."})]}),a.jsx("button",{className:"btn btn-secondary",onClick:P,disabled:D,children:D?"Preparing…":"Download evidence"})]}),K&&a.jsx("div",{style:{marginBottom:"1rem",color:"var(--text-tertiary)",fontSize:"0.875rem"},children:K}),n&&a.jsx("div",{style:{display:"flex",gap:"0.5rem",marginBottom:"1rem",borderBottom:"1px solid var(--border)"},children:["mine","team"].map(b=>a.jsx("button",{onClick:()=>s(b),className:"btn btn-ghost",style:{borderRadius:0,padding:"0.5rem 0.875rem",borderBottom:r===b?"2px solid var(--accent)":"2px solid transparent",color:r===b?"var(--text-primary)":"var(--text-tertiary)",fontWeight:r===b?600:500},children:b==="mine"?"Mine":"Team"},b))}),a.jsxs("div",{className:"search-filter-bar",children:[a.jsxs("div",{className:"search-input-wrap",children:[a.jsx("span",{className:"search-icon",children:"⌕"}),a.jsx("input",{type:"text",className:"form-input search-input",placeholder:"Search by profile, action, path, or hash\\u2026",value:h,onChange:b=>g(b.target.value)}),h&&a.jsx("button",{className:"search-clear",onClick:()=>g(""),children:"×"})]}),a.jsxs("button",{className:`btn btn-sm btn-secondary${C?" active":""}`,onClick:()=>z(!C),children:["Filters",ht?` (${y.size+k.size+(R!=="all"?1:0)})`:""]})]}),C&&a.jsxs("div",{className:"filter-panel",children:[pe.length>1&&a.jsxs("div",{className:"filter-section",children:[a.jsx("div",{className:"filter-label",children:"Profile"}),a.jsx("div",{className:"filter-chips",children:pe.map(b=>a.jsx("button",{className:`filter-chip${y.has(b)?" selected":""}`,onClick:()=>Ie(b),children:b},b))})]}),Le.length>1&&a.jsxs("div",{className:"filter-section",children:[a.jsx("div",{className:"filter-label",children:"Action"}),a.jsx("div",{className:"filter-chips",children:Le.map(b=>a.jsx("button",{className:`filter-chip${k.has(b)?" selected":""}`,onClick:()=>Ke(b),children:b},b))})]}),r==="team"&&ot.length>1&&a.jsxs("div",{className:"filter-section",children:[a.jsx("div",{className:"filter-label",children:"Owner"}),a.jsx("div",{className:"filter-chips",children:ot.map(b=>a.jsx("button",{className:`filter-chip${v.has(b.id)?" selected":""}`,onClick:()=>se(b.id),children:b.label},b.id))})]}),a.jsxs("div",{className:"filter-section",children:[a.jsx("div",{className:"filter-label",children:"Time range"}),a.jsx("div",{className:"filter-chips",children:[["1d","Today"],["7d","7 days"],["30d","30 days"],["all","All time"]].map(([b,N])=>a.jsx("button",{className:`filter-chip${R===b?" selected":""}`,onClick:()=>_(b),children:N},b))})]})]}),ht&&a.jsxs("div",{className:"active-filters",children:[[...y].map(b=>a.jsxs("span",{className:"active-chip",onClick:()=>Ie(b),children:[b," ",a.jsx("span",{className:"chip-remove",children:"×"})]},b)),[...k].map(b=>a.jsxs("span",{className:"active-chip",onClick:()=>Ke(b),children:[b," ",a.jsx("span",{className:"chip-remove",children:"×"})]},b)),[...v].map(b=>{const N=x[b],E=N?N.name:b;return a.jsxs("span",{className:"active-chip",onClick:()=>se(b),children:[E," ",a.jsx("span",{className:"chip-remove",children:"×"})]},b)}),R!=="all"&&a.jsxs("span",{className:"active-chip",onClick:()=>_("all"),children:[R==="1d"?"Today":R==="7d"?"7 days":"30 days"," ",a.jsx("span",{className:"chip-remove",children:"×"})]}),a.jsx("button",{className:"clear-filters",onClick:Ue,children:"Clear all"})]}),Be&&a.jsx("div",{className:"card",style:{borderColor:"var(--danger, #c0392b)",marginBottom:"0.75rem"},children:a.jsx("span",{style:{color:"var(--danger, #c0392b)",fontSize:"0.85rem"},children:"Couldn’t load receipts — your session may have expired. Try signing out and back in."})}),m&&o.length===0?a.jsx("p",{style:{color:"var(--text-tertiary)"},children:"Loading..."}):De.length===0?a.jsx(Zf,{icon:"⌕",title:o.length===0?"No receipts in the last 30 days":"No matching receipts",text:o.length===0?"Execution receipts appear here after an agent uses an authorized tool. Older receipts can be loaded below.":"Try adjusting your search or filters."}):a.jsxs(a.Fragment,{children:[a.jsx("div",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)",marginBottom:"0.75rem"},children:De.length===o.length?`${o.length} receipt${o.length!==1?"s":""}`:`${De.length} of ${o.length} receipts`}),a.jsx("div",{className:"timeline",children:De.map(b=>{const N=b.userId?x[b.userId]:void 0;return a.jsx("div",{className:"timeline-event",children:a.jsx(lx,{receipt:b,manifests:l,localAuth:b.authorizationId?T[b.authorizationId]:void 0,localUnavailable:ee,signature:L[b.id],grantTitle:b.authorizationId?A[b.authorizationId]:null,ownerLabel:r==="team"&&b.userId?N?`${N.name} (${N.email})`:b.userId:null,spUrl:d,formatDate:ux,onOpenComplete:()=>G(b)})},b.id)})})]}),O&&a.jsx(cx,{receipt:O,onClose:()=>G(null)}),X&&a.jsx("div",{style:{textAlign:"center",marginTop:"1rem"},children:a.jsx("button",{className:"btn btn-secondary btn-sm",onClick:he,disabled:de,children:de?"Loading…":"Load older"})})]})}const mx={darwin:"a macOS login item",win32:"a Windows scheduled task",linux:"a systemd user service"};function hx(){const[e,t]=u.useState(null),[n,r]=u.useState(!1),[s,o]=u.useState(null),i=u.useCallback(async()=>{try{t(await $.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 $.setAutostart(!e.installed)}catch(d){o(d instanceof Error?d.message:"Failed")}finally{try{t(await $.getAutostart()),o(null)}catch(d){o(d instanceof Error?d.message:"Could not re-read state")}r(!1)}}},[e,n,i]);if(!e)return a.jsxs("div",{className:"card",style:{padding:"1.5rem",marginTop:"2rem"},children:[a.jsx("h2",{style:{fontSize:"1rem",fontWeight:700,margin:0},children:"Keep Suveren running"}),a.jsx("p",{role:s?"alert":void 0,style:{margin:"0.5rem 0 0",fontSize:"0.9rem",color:"var(--text-secondary)"},children:s?`Could not read autostart state: ${s}`:"Checking…"})]});const c=mx[e.platform]??"a login service";return a.jsxs("div",{className:"card",style:{padding:"1.5rem",marginTop:"2rem"},children:[a.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",gap:"1rem"},children:[a.jsxs("div",{children:[a.jsx("h2",{style:{fontSize:"1rem",fontWeight:700,margin:0},children:"Keep Suveren running"}),a.jsx("p",{style:{color:"var(--text-secondary)",margin:"0.5rem 0 0",fontSize:"0.9rem"},children:e.supported?a.jsxs(a.Fragment,{children:["Starts automatically when you log in, and restarts if it crashes. Uses ",c," — no admin rights needed."]}):e.reason})]}),e.supported&&a.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&&a.jsxs("p",{style:{margin:"1rem 0 0",fontSize:"0.85rem",color:"var(--text-tertiary)"},children:["Status: ",a.jsx("strong",{children:e.installed?"On — starts from your next login":"Off"})]}),e.supported&&a.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 ",a.jsx("strong",{children:"locked"}),": you enter your API key once to unlock it, because nothing stored on this machine can unlock it for you."]}),s&&a.jsx("p",{role:"alert",style:{margin:"0.75rem 0 0",fontSize:"0.85rem",color:"var(--danger, #c00)"},children:s})]})}function gx(){const[e,t]=u.useState(null),[n,r]=u.useState(!1),[s,o]=u.useState(null),i=u.useCallback(async()=>{try{const c=await $.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 $.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?a.jsxs("div",{className:"card",style:{padding:"1.5rem",marginTop:"2rem"},children:[a.jsx("h2",{style:{fontSize:"1rem",fontWeight:700,margin:0},children:"Desktop notifications"}),a.jsx("p",{role:s?"alert":void 0,style:{margin:"0.5rem 0 0",fontSize:"0.9rem",color:"var(--text-secondary)"},children:s?`Could not read the setting: ${s}`:"Checking…"})]}):a.jsxs("div",{className:"card",style:{padding:"1.5rem",marginTop:"2rem"},children:[a.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",gap:"1rem"},children:[a.jsxs("div",{children:[a.jsx("h2",{style:{fontSize:"1rem",fontWeight:700,margin:0},children:"Desktop notifications"}),a.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."})]}),a.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"})]}),s&&a.jsx("p",{role:"alert",style:{margin:"0.75rem 0 0",fontSize:"0.85rem",color:"var(--danger)"},children:s})]})}const yx={npm:"Checking npm for new releases",docker:"Checking the container registry for new images",dev:"Git checkout — comparing against origin/main, not npm releases"};function vx(){const{version:e,latestVersion:t,updateAvailable:n,installMethod:r}=Cl();return e?a.jsxs("div",{className:"card",style:{padding:"1.5rem",marginTop:"2rem"},children:[a.jsx("h2",{style:{fontSize:"1rem",fontWeight:700,margin:0},children:"Version"}),a.jsxs("p",{style:{margin:"0.5rem 0 0",fontSize:"0.9rem",color:"var(--text-secondary)"},children:["Running ",a.jsx("strong",{children:e}),n&&t?a.jsxs(a.Fragment,{children:[" — ",a.jsx("strong",{children:t})," is available"]}):null]}),a.jsxs("p",{style:{margin:"0.5rem 0 0",fontSize:"0.85rem",color:"var(--text-tertiary)"},children:[yx[r]??"Update checking is unavailable",r==="dev"&&a.jsx(a.Fragment,{children:" — a development checkout is not told about published releases."})]})]}):null}const xx={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"]}};function wx(){const[e,t]=u.useState(""),[n,r]=u.useState("openrouter"),[s,o]=u.useState("openai-compatible"),[i,l]=u.useState("https://openrouter.ai/api/v1"),[c,d]=u.useState("google/gemma-4-31b-it"),[f,m]=u.useState(""),[p,x]=u.useState(!1),[w,v]=u.useState(!1),[j,h]=u.useState(!1),[g,y]=u.useState(null),[S,k]=u.useState([]),[I,R]=u.useState(!1),[_,C]=u.useState(null),[z,D]=u.useState(""),Y=u.useCallback(L=>{t(L),setTimeout(()=>t(""),3e3)},[]),K=u.useCallback(async(L,H,A)=>{R(!0),C(null);try{const U=await $.aiModels({provider:L,endpoint:H,...A?{apiKey:A}:{}});U.ok&&U.models.length>0?(k(U.models),C(`${U.models.length} models available`)):(k([]),C(U.message||"No models returned — using defaults"))}catch(U){k([]),C(U instanceof Error?U.message:"Failed to load models")}finally{R(!1)}},[]),W=u.useCallback(async()=>{try{const L=await $.getCredential("ai-config");if(x(L.configured),L.configured&&L.fields){const H=L.fields.provider||"openai-compatible",A=L.fields.endpoint||"";L.fields.provider&&o(H),L.fields.endpoint&&l(A),L.fields.model&&d(L.fields.model),A.includes("openai.com")?r("openai"):A.includes("groq.com")?r("groq"):A.includes("together.xyz")?r("together"):A.includes("openrouter.ai")?r("openrouter"):r("ollama"),A&&K(H,A)}}catch{}},[K]);u.useEffect(()=>{W()},[W]);const T=L=>{r(L),k([]),C(null),D("");const H=xx[L];H&&(o(H.provider),l(H.endpoint),d(""),K(H.provider,H.endpoint,f||void 0))},q=()=>K(s,i,f||void 0),ee=async()=>{v(!0);try{await $.setCredential("ai-config",{provider:s,endpoint:i,model:c,...f?{apiKey:f}:{}}),x(!0),Y("AI configuration saved!")}catch{Y("Failed to save AI config")}finally{v(!1)}},F=async()=>{h(!0),y(null);try{const L=await $.aiTest({provider:s,endpoint:i,model:c,...f?{apiKey:f}:{}});y(L.ok?`OK: ${L.message}`:`Failed: ${L.message}`)}catch(L){y(`Error: ${L instanceof Error?L.message:"Unknown"}`)}finally{h(!1)}};return a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"page-header",children:[a.jsx("h1",{className:"page-title",children:"AI Assistant"}),a.jsx("p",{className:"page-subtitle",children:"Advisory AI to help you think through intent when authorizing agents."})]}),e&&a.jsx("div",{className:"alert alert-success",children:e}),a.jsxs("div",{className:"card",children:[a.jsx("h3",{className:"card-title",children:"Configuration"}),a.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 authorizations. Keys are encrypted in your vault."}),p&&a.jsxs("div",{className:"status-banner status-banner-success",style:{marginBottom:"1rem",fontSize:"0.8rem"},children:[a.jsx("span",{className:"status-banner-icon",children:"✓"}),a.jsx("span",{className:"status-banner-text",children:"AI configured"})]}),a.jsxs("div",{className:"form-group",style:{marginBottom:"0.75rem"},children:[a.jsx("label",{className:"form-label",children:"Provider Preset"}),a.jsxs("select",{className:"form-input",value:n,onChange:L=>T(L.target.value),children:[a.jsx("option",{value:"openrouter",children:"OpenRouter (recommended)"}),a.jsx("option",{value:"ollama",children:"Ollama (local)"}),a.jsx("option",{value:"openai",children:"OpenAI"}),a.jsx("option",{value:"groq",children:"Groq"}),a.jsx("option",{value:"together",children:"Together"})]})]}),a.jsxs("div",{className:"form-group",style:{marginBottom:"0.75rem"},children:[a.jsxs("label",{className:"form-label",children:["API Key ",s==="ollama"?"(not needed for Ollama)":"(required to load models)"]}),a.jsx("input",{className:"form-input",type:"password",name:"ai-provider-api-key-credential-top",autoComplete:"new-password",value:f,onChange:L=>m(L.target.value),onBlur:()=>{f.trim()&&K(s,i,f.trim())},placeholder:p?"••••••••••••••••":"sk-... (not needed for Ollama)"}),a.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."})]}),a.jsxs("div",{className:"form-group",style:{marginBottom:"0.75rem"},children:[a.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[a.jsx("label",{className:"form-label",children:"Model"}),a.jsx("button",{type:"button",className:"btn btn-ghost",style:{fontSize:"0.75rem",padding:"0.125rem 0.5rem"},onClick:q,disabled:I,title:"Re-fetch the model list from the provider",children:I?"Loading…":"↻ Refresh"})]}),S.length===0?a.jsx("div",{className:"form-input",style:{display:"flex",alignItems:"center",minHeight:"2.5rem",color:"var(--text-secondary)",fontSize:"0.85rem"},children:I?"Loading models…":s==="ollama"?"Start Ollama locally, then ↻ Refresh to load models.":"Enter a valid API key above to load available models."}):(()=>{const L=S,H=L.includes(c),A=L.length>12,U=z.trim().toLowerCase();let O=U?L.filter(G=>G.toLowerCase().includes(U)):L;return H&&!O.includes(c)&&(O=[c,...O]),a.jsxs(a.Fragment,{children:[A&&a.jsx("input",{className:"form-input",value:z,onChange:G=>D(G.target.value),placeholder:"Filter models… (e.g. kimi)",style:{marginBottom:"0.375rem"}}),a.jsxs("select",{className:"form-input",value:H?c:"__unset__",onChange:G=>d(G.target.value==="__unset__"?"":G.target.value),children:[a.jsx("option",{value:"__unset__",disabled:!0,children:"Select a model…"}),O.map(G=>a.jsx("option",{value:G,children:G},G)),U&&O.length===0&&a.jsxs("option",{value:"__unset__",disabled:!0,children:["No models match “",z,"”"]})]})]})})(),_&&a.jsx("p",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",margin:"0.375rem 0 0"},children:_})]}),a.jsxs("div",{style:{display:"flex",gap:"0.5rem",alignItems:"center"},children:[a.jsx("button",{className:"btn btn-primary",onClick:ee,disabled:w||!c.trim(),title:c.trim()?void 0:"Select a model first",children:w?"Saving...":"Save & Encrypt"}),p&&a.jsx("button",{className:"btn btn-ghost",onClick:F,disabled:j,children:j?"Testing...":"Test Connection"})]}),g&&a.jsx("div",{className:`alert ${g.startsWith("OK")?"alert-success":"alert-error"}`,style:{marginTop:"0.75rem"},children:g})]}),a.jsx(Sx,{}),a.jsx(hx,{}),a.jsx(gx,{}),a.jsx(vx,{}),a.jsxs("div",{className:"card",style:{padding:"1.5rem",marginTop:"2rem"},children:[a.jsx("h2",{style:{fontSize:"1rem",fontWeight:700,marginBottom:"1rem"},children:"Security"}),a.jsxs("div",{style:{fontSize:"0.85rem",color:"var(--text-secondary)",lineHeight:1.7},children:[a.jsxs("div",{style:{marginBottom:"1rem"},children:[a.jsx("div",{style:{fontWeight:600,color:"var(--text-primary)",marginBottom:"0.375rem"},children:"What the gateway protects"}),a.jsxs("ul",{style:{margin:0,paddingLeft:"1.25rem"},children:[a.jsx("li",{children:"Every tool call verified against your authorization bounds"}),a.jsx("li",{children:"Credentials never exposed to agents through MCP"}),a.jsx("li",{children:"Every action produces a signed receipt"})]})]}),a.jsxs("div",{children:[a.jsx("div",{style:{fontWeight:600,color:"var(--text-primary)",marginBottom:"0.375rem"},children:"Your responsibility"}),a.jsxs("ul",{style:{margin:0,paddingLeft:"1.25rem"},children:[a.jsx("li",{children:"If your AI agent has full access to your computer, it could bypass the gateway"}),a.jsx("li",{children:"For best security, run agents in sandboxed environments"}),a.jsx("li",{children:"The gateway secures what agents do through tools — not what they do on your machine"})]})]})]})]})]})}function Sx(){const[e,t]=u.useState(null),[n,r]=u.useState({intent:"",context:""}),[s,o]=u.useState(null),[i,l]=u.useState(null),[c,d]=u.useState(null),[f,m]=u.useState(!1),p=u.useCallback(async()=>{if(!f)try{const v=await $.getAIPrompts();t(v),r({intent:v.intent.current,context:v.context.current}),m(!0)}catch(v){l(v instanceof Error?v.message:"Failed to load prompts")}},[f]),x=async v=>{if(e){o(v),l(null);try{const j=n[v],h=j.trim()===e[v].default.trim()?"":j;await $.setAIPrompt(v,h);const g=await $.getAIPrompts();t(g),r({intent:g.intent.current,context:g.context.current}),d(v),setTimeout(()=>d(null),2e3)}catch(j){l(j instanceof Error?j.message:"Save failed")}finally{o(null)}}},w=async v=>{if(confirm(`Revert ${v} prompt to the built-in default?`)){o(v),l(null);try{await $.setAIPrompt(v,"");const j=await $.getAIPrompts();t(j),r({intent:j.intent.current,context:j.context.current})}catch(j){l(j instanceof Error?j.message:"Revert failed")}finally{o(null)}}};return a.jsxs("details",{className:"card",style:{padding:"1.5rem",marginTop:"1rem"},onToggle:v=>{v.currentTarget.open&&p()},children:[a.jsx("summary",{style:{fontSize:"1rem",fontWeight:700,cursor:"pointer",listStyle:"revert",userSelect:"none"},children:"Advanced — AI assistant prompts"}),a.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-authorization) or Context (your standing-orders brief). Edit with care — changes apply on the next chat turn."}),i&&a.jsx("div",{className:"alert alert-error",style:{marginBottom:"0.75rem"},children:i}),!f&&!i&&a.jsx("p",{style:{color:"var(--text-muted)",fontSize:"0.85rem"},children:"Loading prompts…"}),e&&a.jsxs(a.Fragment,{children:[a.jsx(Zc,{kind:"intent",label:"Intent — per-authorization",description:"Used on the Intent gate when creating a new authorization.",state:e.intent,draft:n.intent,onChange:v=>r(j=>({...j,intent:v})),onSave:()=>x("intent"),onRevert:()=>w("intent"),saving:s==="intent",justSaved:c==="intent"}),a.jsx(Zc,{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:v=>r(j=>({...j,context:v})),onSave:()=>x("context"),onRevert:()=>w("context"),saving:s==="context",justSaved:c==="context"})]})]})}function Zc({kind:e,label:t,description:n,state:r,draft:s,onChange:o,onSave:i,onRevert:l,saving:c,justSaved:d}){const f=s!==r.current;return a.jsxs("section",{style:{marginBottom:"1.5rem"},children:[a.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"baseline",marginBottom:"0.25rem",gap:"1rem",flexWrap:"wrap"},children:[a.jsxs("div",{children:[a.jsx("div",{style:{fontWeight:600,fontSize:"0.9rem"},children:t}),a.jsx("div",{style:{fontSize:"0.78rem",color:"var(--text-secondary)"},children:n})]}),r.overridden&&a.jsx("span",{style:{fontSize:"0.7rem",color:"var(--accent)",fontWeight:600,textTransform:"uppercase",letterSpacing:"0.05em"},children:"Custom"})]}),a.jsx("textarea",{className:"form-textarea",value:s,onChange:m=>o(m.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`}),a.jsxs("div",{style:{display:"flex",gap:"0.5rem",alignItems:"center",marginTop:"0.5rem",flexWrap:"wrap"},children:[a.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:i,disabled:c||!f,children:c?"Saving…":"Save"}),r.overridden&&a.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&&a.jsx("span",{style:{fontSize:"0.78rem",color:"var(--success)"},children:"Saved"}),f&&!c&&!d&&a.jsx("span",{style:{fontSize:"0.78rem",color:"var(--text-muted)"},children:"Unsaved changes"})]}),a.jsxs("details",{style:{marginTop:"0.5rem"},children:[a.jsx("summary",{style:{fontSize:"0.78rem",color:"var(--text-muted)",cursor:"pointer"},children:"Show built-in default"}),a.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})]}),a.jsx("span",{style:{display:"none"},children:e})]})}function jx(e){return e.proposalId?"review":"automatic"}function eu(e,t,n={}){const r=n.status??"pending",s=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=jx(i);!s&&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 kx=["https://","http://"];function ep(e,t){return e!=null&&e.length?e.flatMap(n=>{const r=n.template.replace(/\{(\w+)\}/g,(s,o)=>{const i=t[o];return typeof i=="string"||typeof i=="number"?String(i):"\0"});return r.includes("\0")||/\{|\}/.test(r)?[]:kx.some(s=>r.toLowerCase().startsWith(s))?[{label:n.label,href:r,description:n.description}]:[]}):[]}function bx({profileId:e}){return a.jsx("span",{className:"profile-badge",children:ze(e)})}function tp(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),s=Math.floor(n%86400/3600),o=Math.floor(n%3600/60);let i;return r>0?i=`expires in ${r}d ${s}h`:s>0?i=`expires in ${s}h ${o}m`:i=`expires in ${Math.max(1,o)}m`,{label:i,urgent:n<2*3600,expired:!1}}const Cx={pending:"Pending",committed:"Approved",executed:"Executed",rejected:"Rejected",expired:"Expired"},Nx={pending:"status-pending",committed:"status-active",executed:"status-active",rejected:"status-revoked",expired:"status-expired"};function Ex(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 Tx(e){return e.split("__").pop()??e}function zx(e){const t=e.toLowerCase();return t.includes("delete")||t.includes("refund")||t.includes("cancel")||t.includes("revoke")}const Ix=new Set(["apiKey","api_key","accessToken","access_token","password","secret","signature","_imagePreview"]),Rx=/^(image|img|photo|picture|thumbnail)(_?url)?$/i;function Px(e,t){return typeof t!="string"?!1:/^data:image\//i.test(t)?!0:Rx.test(e)?/^https?:\/\//.test(t):/^https?:\/\/.+\.(jpe?g|png|gif|webp|svg|avif)(\?|$)/i.test(t)}function ji(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=>ji(t)).join(", ");try{return JSON.stringify(e,null,2)}catch{return String(e)}}function tu({item:e,onApprove:t,onReject:n,resolving:r,proposalLinks:s}){const o=e.kind==="proposal",i=o?e.proposal.status:"executed",l=o?e.proposal.tool:e.receipt.action,c=Tx(l),d=zx(l),f=o?e.proposal.toolArgs:null,m=o?e.proposal.executionContext:e.receipt.executionContext,p=o?null:e.receipt.cumulativeState,x=o?ep(s,e.proposal.toolArgs):[],w=f?Object.entries(f).filter(([j])=>!Ix.has(j)):[],v=Object.entries(m??{});return a.jsxs("div",{className:"card",children:[a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem",marginBottom:"0.75rem",flexWrap:"wrap"},children:[a.jsx(bx,{profileId:e.profileId}),a.jsx("code",{style:{fontSize:"0.85rem"},children:c}),e.commitmentMode==="automatic"&&a.jsx("span",{style:{fontSize:"0.7rem",color:"var(--text-tertiary)",textTransform:"uppercase",letterSpacing:"0.04em"},children:"autonomous"}),a.jsxs("span",{style:{marginLeft:"auto",display:"flex",alignItems:"center",gap:"0.5rem"},children:[o&&i==="pending"&&(()=>{const j=tp(e.proposal.expiresAt,Date.now());return a.jsx("span",{style:{fontSize:"0.72rem",color:j.urgent?"var(--warning)":"var(--text-tertiary)",fontWeight:j.urgent?600:400,whiteSpace:"nowrap"},children:j.label})})(),a.jsx("span",{className:`status-badge ${Nx[i]}`,children:Cx[i]}),a.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-tertiary)"},children:Ex(e.sortTimestamp)})]})]}),d&&a.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:[a.jsx("span",{children:"⚠"}),a.jsx("span",{children:"Irreversible action"})]}),o&&typeof(f==null?void 0:f._imagePreview)=="string"&&a.jsxs("div",{style:{marginBottom:"0.75rem"},children:[a.jsx("div",{style:{fontSize:"0.7rem",fontWeight:600,color:"var(--text-tertiary)",textTransform:"uppercase",letterSpacing:"0.04em",marginBottom:"0.35rem"},children:"Preview"}),a.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)"}})]}),x.length>0&&a.jsx("div",{style:{marginBottom:"0.75rem",display:"flex",gap:"0.5rem",flexWrap:"wrap"},children:x.map(j=>a.jsxs("a",{href:j.href,target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm",style:{textDecoration:"none"},title:j.description??j.href,children:[j.label," ↗"]},j.label))}),o&&w.length>0&&a.jsxs("div",{style:{marginBottom:"0.75rem"},children:[a.jsx("div",{style:{fontSize:"0.7rem",fontWeight:600,color:"var(--text-tertiary)",textTransform:"uppercase",letterSpacing:"0.04em",marginBottom:"0.35rem"},children:"Arguments"}),a.jsx("dl",{style:{display:"grid",gridTemplateColumns:"max-content 1fr",gap:"0.2rem 0.75rem",fontSize:"0.85rem",margin:0},children:w.map(([j,h])=>a.jsxs(u.Fragment,{children:[a.jsx("dt",{style:{color:"var(--text-tertiary)",whiteSpace:"nowrap",alignSelf:"start"},children:j}),a.jsx("dd",{style:{color:"var(--text-primary)",margin:0,wordBreak:"break-word",whiteSpace:"pre-wrap"},children:Px(j,h)?a.jsx("img",{src:h,alt:typeof(f==null?void 0:f.altText)=="string"?f.altText:j,style:{display:"block",maxWidth:"100%",maxHeight:"240px",borderRadius:"0.375rem",border:"1px solid var(--border)"},onError:g=>{const y=g.currentTarget,S=y.parentElement;if(!S)return;y.style.display="none";const k=document.createElement("span");k.textContent=h,k.style.color="var(--text-tertiary)",S.appendChild(k)}}):ji(h)})]},j))})]}),v.length>0&&a.jsx("div",{style:{marginBottom:"0.75rem",fontSize:"0.8rem",color:"var(--text-secondary)"},children:v.map(([j,h])=>`${j}=${ji(h)}`).join(" · ")}),p&&a.jsxs("div",{style:{fontSize:"0.75rem",color:"var(--text-tertiary)",marginBottom:"0.5rem"},children:["After this action · today: ",p.daily.count," action",p.daily.count===1?"":"s",p.daily.amount>0?`, ${p.daily.amount}`:""," · ","this month: ",p.monthly.count,p.monthly.amount>0?`, ${p.monthly.amount}`:""]}),o&&i==="pending"&&a.jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[a.jsx("button",{className:"btn btn-primary",onClick:()=>t==null?void 0:t(e.id),disabled:r,children:r?"Approving…":"Approve"}),a.jsx("button",{className:"btn btn-ghost",style:{color:"var(--danger)"},onClick:()=>n==null?void 0:n(e.id),disabled:r,children:"Reject"})]}),a.jsxs("div",{style:{marginTop:"0.5rem",fontSize:"0.7rem",color:"var(--text-tertiary)"},children:[o?"Proposal":"Receipt",": ",e.id]})]})}const _x=new Set(["apiKey","api_key","accessToken","access_token","password","secret","signature","_imagePreview"]);function ki(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=>ki(t)).join(", ");try{return JSON.stringify(e,null,2)}catch{return String(e)}}function Ax(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 $x({proposal:e,currentUserId:t,onAction:n,onMessage:r,proposalLinks:s}){const[o,i]=u.useState(!1),[l,c]=u.useState(!1),[d,f]=u.useState(null),[m,p]=u.useState(!1),[x,w]=u.useState(null),[v,j]=u.useState(!1),h=e.tool.split("__").pop()??e.tool,g=Object.entries(e.toolArgs).filter(([T])=>!_x.has(T)),y=Object.entries(e.executionContext),S=ep(s,e.toolArgs),k=e.pendingApprovers??[],I=e.approvedBy??{},R=Object.keys(I).length,_=k.filter(T=>!(T in I)).length,C=t in I,z=async()=>{if(d===null){p(!0),w(null);try{const T=await $.getAttestationIntent(e.authorizationId);if(!T){w("Intent not available or you are not an authorized approver.");return}const q=await $.decryptIntent({intentCiphertext:T.intentCiphertext,encryptedKey:T.encryptedKey,approverId:t});f(q)}catch(T){w(T instanceof Error?T.message:"Failed to decrypt intent")}finally{p(!1)}}},D=async()=>{v?j(!1):(j(!0),await z())},Y=async()=>{i(!0),r("");try{await $.approveProposal(e.id);try{if(d===null){const T=await $.getAttestationIntent(e.authorizationId);if(T){const q=await $.decryptIntent({intentCiphertext:T.intentCiphertext,encryptedKey:T.encryptedKey,approverId:t});f(q),await $.storeApprovedIntent(e.authorizationId,q)}}else await $.storeApprovedIntent(e.authorizationId,d)}catch{}r(`Approved. ${_-1>0?`${_-1} more approver(s) still needed.`:"All approvers signed off — action is ready to execute."}`),n()}catch(T){r(T instanceof Error?T.message:"Approval failed")}finally{i(!1)}},K=async()=>{const T=prompt("Rejection reason (optional):");if(T!==null){c(!0),r("");try{await $.rejectProposal(e.id,T||void 0),r("Action rejected."),n()}catch(q){r(q instanceof Error?q.message:"Rejection failed")}finally{c(!1)}}},W=o||l;return a.jsxs("div",{className:"card",children:[a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem",marginBottom:"0.5rem",flexWrap:"wrap"},children:[a.jsx("span",{style:{fontWeight:600,fontSize:"0.9rem"},children:ze(e.profileId)}),a.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"}),a.jsxs("span",{style:{marginLeft:"auto",display:"flex",alignItems:"center",gap:"0.5rem"},children:[(()=>{const T=tp(e.expiresAt,Date.now());return a.jsx("span",{style:{fontSize:"0.72rem",color:T.urgent?"var(--warning)":"var(--text-tertiary)",fontWeight:T.urgent?600:400,whiteSpace:"nowrap"},children:T.label})})(),a.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-tertiary)"},children:Ax(e.createdAt)})]})]}),a.jsxs("div",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)",marginBottom:"0.5rem"},children:[R," of ",k.length," approver",k.length===1?"":"s"," signed off",k.map(T=>{const q=T in I;return a.jsxs("span",{style:{marginLeft:"0.5rem",color:q?"var(--success, green)":"var(--text-tertiary)"},children:[q?"✓":"○"," ",T===t?"You":T]},T)})]}),a.jsxs("div",{style:{marginBottom:"0.5rem"},children:[a.jsx("div",{style:{fontSize:"0.7rem",fontWeight:600,color:"var(--text-tertiary)",textTransform:"uppercase",letterSpacing:"0.04em",marginBottom:"0.25rem"},children:"Proposed action"}),a.jsx("code",{style:{fontSize:"0.85rem"},children:h})]}),S.length>0&&a.jsx("div",{style:{marginBottom:"0.75rem",display:"flex",gap:"0.5rem",flexWrap:"wrap"},children:S.map(T=>a.jsxs("a",{href:T.href,target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm",style:{textDecoration:"none"},title:T.description??T.href,children:[T.label," ↗"]},T.label))}),g.length>0&&a.jsxs("div",{style:{marginBottom:"0.75rem"},children:[a.jsx("div",{style:{fontSize:"0.7rem",fontWeight:600,color:"var(--text-tertiary)",textTransform:"uppercase",letterSpacing:"0.04em",marginBottom:"0.25rem"},children:"Arguments"}),a.jsx("dl",{style:{display:"grid",gridTemplateColumns:"max-content 1fr",gap:"0.2rem 0.75rem",fontSize:"0.85rem",margin:0},children:g.map(([T,q])=>a.jsxs(u.Fragment,{children:[a.jsx("dt",{style:{color:"var(--text-tertiary)",whiteSpace:"nowrap",alignSelf:"start"},children:T}),a.jsx("dd",{style:{color:"var(--text-primary)",margin:0,wordBreak:"break-word",whiteSpace:"pre-wrap"},children:ki(q)})]},T))})]}),y.length>0&&a.jsx("div",{style:{fontSize:"0.8rem",color:"var(--text-secondary)",marginBottom:"0.5rem"},children:y.map(([T,q])=>`${T}=${ki(q)}`).join(" · ")}),a.jsxs("div",{style:{marginBottom:"0.75rem"},children:[a.jsxs("button",{className:"btn btn-ghost btn-sm",style:{padding:"0.2rem 0",fontSize:"0.75rem"},onClick:D,disabled:m,children:[v?"▲ Hide intent":"▼ Show intent",m&&" (decrypting...)"]}),v&&a.jsx("div",{style:{marginTop:"0.5rem",padding:"0.75rem",background:"var(--bg-main)",borderRadius:"0.375rem",border:"1px solid var(--border)"},children:x?a.jsx("p",{style:{color:"var(--danger)",fontSize:"0.8rem",margin:0},children:x}):d!==null?a.jsx("p",{style:{fontSize:"0.85rem",margin:0,whiteSpace:"pre-wrap",color:"var(--text-primary)"},children:d}):a.jsx("p",{style:{color:"var(--text-tertiary)",fontSize:"0.8rem",margin:0},children:"No intent available for this authority."})})]}),!C&&a.jsxs("div",{style:{display:"flex",gap:"0.5rem",marginTop:"0.25rem"},children:[a.jsx("button",{className:"btn btn-primary",onClick:Y,disabled:W,children:o?"Approving...":"Approve"}),a.jsx("button",{className:"btn btn-ghost",style:{color:"var(--danger)"},onClick:K,disabled:W,children:l?"Rejecting...":"Reject"})]}),C&&a.jsx("p",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)",marginTop:"0.25rem"},children:"You approved this action. Waiting on other approvers."}),a.jsxs("div",{style:{marginTop:"0.5rem",fontSize:"0.7rem",color:"var(--text-tertiary)"},children:["Proposal: ",e.id]})]})}function Lx(){const{domain:e,user:t}=Ae(),n=(t==null?void 0:t.id)??"",[r,s]=u.useState("awaiting-me"),[o,i]=u.useState([]),[l,c]=u.useState([]),[d,f]=u.useState(!0),[m,p]=u.useState(""),x=u.useCallback(async()=>{try{const M=await $.getProposalsForApprover();i(M)}catch{}finally{f(!1)}},[]);ue("proposal-added",x),ue("proposal-approved",x),ue("proposal-rejected",x),ue("proposal-resolved",x),Lt(x,3e4);const[w,v]=u.useState([]),j=u.useCallback(async()=>{try{const M=await $.getProposals(e||"owner");v(M)}catch{}},[e]);ue("proposal-added",j),ue("proposal-approved",j),ue("proposal-rejected",j),ue("proposal-resolved",j),Lt(j,3e4,e);const h=u.useMemo(()=>w.filter(M=>{var J;return M.status==="pending"&&(((J=M.pendingApprovers)==null?void 0:J.length)??0)===0}),[w]),g=u.useMemo(()=>eu(h,[],{status:"pending"}),[h]),[y,S]=u.useState([]),k=u.useCallback(async()=>{if(n)try{const J=(await $.getProposals(e||"owner")).filter(te=>te.status==="pending"&&te.pendingApprovers&&te.pendingApprovers.includes(n)&&te.approvedBy&&n in te.approvedBy);S(J)}catch{}},[n,e]);ue("proposal-approved",k),ue("proposal-rejected",k),Lt(k,3e4,`${n}:${e}`),u.useEffect(()=>{$.getIntegrationManifests().then(M=>c(M.manifests??[])).catch(()=>{})},[]);const I=M=>{var J;return(J=l.find(te=>te.id===M.split("__")[0]))==null?void 0:J.proposalLinks};u.useEffect(()=>{x(),j(),k()},[]);const[R,_]=u.useState([]),[C,z]=u.useState([]),[D,Y]=u.useState(!0),[K,W]=u.useState(null),[T,q]=u.useState(""),[ee,F]=u.useState("pending"),[L,H]=u.useState(null),[A,U]=u.useState(!1),O=u.useCallback(async()=>{try{const{proposals:M,receipts:J}=await $.getThread({domain:e,status:ee,sinceDays:7});_(M),z(J)}catch{}finally{Y(!1)}},[e,ee]);Lt(O,3e4,`${e}:${ee}`);const G=async(M,J)=>{W(M),q("");try{const te=e||"owner",he=await $.resolveProposal(M,J,te);q(J==="commit"?`Action approved. Status: ${he.status}`:"Action rejected."),await Promise.all([O(),j()])}catch(te){q(te instanceof Error?te.message:"Failed")}finally{W(null)}},X=u.useMemo(()=>{const M=new Set;for(const J of R)M.add(J.profileId);for(const J of C)M.add(J.profileId);return Array.from(M).sort()},[R,C]),Z=u.useMemo(()=>eu(R,C,{status:ee,profile:L??void 0,includeAutonomous:A}),[R,C,ee,L,A]),de=u.useCallback(()=>{x(),k()},[x,k]),$e=u.useMemo(()=>{const M=new Set,J=[];for(const te of y)M.has(te.id)||(M.add(te.id),J.push(te));return J.sort((te,he)=>he.createdAt-te.createdAt)},[y]),Be=o.length+g.length,le=$e.length;return a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"page-header",children:[a.jsx("h1",{className:"page-title",children:"Pending Approvals"}),a.jsx("p",{className:"page-subtitle",children:"Actions awaiting approval, plus recent activity from the last 7 days."})]}),a.jsxs("div",{className:"nav-tabs",style:{marginBottom:"1rem"},children:[a.jsxs("button",{className:`nav-tab${r==="awaiting-me"?" active":""}`,onClick:()=>s("awaiting-me"),children:["Awaiting me ",Be>0&&a.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:Be})]}),a.jsxs("button",{className:`nav-tab${r==="awaiting-others"?" active":""}`,onClick:()=>s("awaiting-others"),children:["Awaiting others ",le>0&&a.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:le})]}),a.jsx("button",{className:`nav-tab${r==="all"?" active":""}`,onClick:()=>{s("all"),O()},children:"All"})]}),r==="awaiting-me"&&a.jsx(a.Fragment,{children:d&&Be===0?a.jsx("p",{style:{color:"var(--text-tertiary)"},children:"Loading..."}):Be===0?a.jsxs("div",{className:"card",style:{textAlign:"center",padding:"2rem"},children:[a.jsx("p",{style:{color:"var(--text-tertiary)",marginBottom:"0.5rem"},children:"No actions awaiting your approval."}),a.jsx("p",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)"},children:"Review-mode actions and above-cap actions you must approve will appear here."})]}):a.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"1rem"},children:[(m||T)&&a.jsx("div",{className:"alert alert-success",children:m||T}),g.map(M=>a.jsx(tu,{proposalLinks:M.kind==="proposal"?I(M.proposal.tool):void 0,item:M,onApprove:J=>G(J,"commit"),onReject:J=>G(J,"reject"),resolving:K===M.id},M.id)),o.map(M=>a.jsx($x,{proposal:M,currentUserId:n,onAction:de,onMessage:p,proposalLinks:I(M.tool)},M.id))]})}),r==="awaiting-others"&&a.jsx(a.Fragment,{children:$e.length===0?a.jsxs("div",{className:"card",style:{textAlign:"center",padding:"2rem"},children:[a.jsx("p",{style:{color:"var(--text-tertiary)",marginBottom:"0.5rem"},children:"No actions waiting on others."}),a.jsx("p",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)"},children:"Actions you proposed or approved that are pending other approvers will appear here."})]}):a.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"1rem"},children:$e.map(M=>a.jsx(Fx,{proposal:M,currentUserId:n,onCancel:async()=>{try{await $.rejectProposal(M.id,"cancelled by creator"),k(),j()}catch(J){alert(J instanceof Error?J.message:"Cancel failed")}}},M.id))})}),r==="all"&&a.jsxs(a.Fragment,{children:[T&&a.jsx("div",{className:"alert alert-success",style:{marginBottom:"1rem"},children:T}),a.jsxs("div",{className:"filter-chips",style:{marginBottom:"1rem"},children:[a.jsx("button",{className:`filter-chip ${ee==="pending"?"selected":""}`,onClick:()=>F("pending"),children:"Pending"}),a.jsx("button",{className:`filter-chip ${ee==="all"?"selected":""}`,onClick:()=>F("all"),children:"All"}),X.length>0&&a.jsx("span",{style:{width:1,background:"var(--border)",alignSelf:"stretch",margin:"0 0.25rem"}}),X.map(M=>a.jsx("button",{className:`filter-chip ${L===M?"selected":""}`,onClick:()=>H(L===M?null:M),children:ze(M)},M)),ee==="all"&&a.jsxs(a.Fragment,{children:[a.jsx("span",{style:{width:1,background:"var(--border)",alignSelf:"stretch",margin:"0 0.25rem"}}),a.jsxs("button",{className:`filter-chip ${A?"selected":""}`,onClick:()=>U(!A),title:"Include actions executed without human review (automatic commitment mode)",children:[A?"✓ ":"","Autonomous actions"]})]})]}),D&&Z.length===0?a.jsx("p",{style:{color:"var(--text-tertiary)"},children:"Loading..."}):Z.length===0?a.jsxs("div",{className:"card",style:{textAlign:"center",padding:"2rem"},children:[a.jsx("p",{style:{color:"var(--text-tertiary)",marginBottom:"0.5rem"},children:ee==="pending"?"No actions awaiting your approval.":"Nothing here yet."}),a.jsx("p",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)"},children:ee==="pending"?"Your agents are operating within their authorizations. Switch to All to see recent activity.":"When an agent calls a gated tool, activity will appear here."})]}):a.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"1rem"},children:Z.map(M=>a.jsx(tu,{proposalLinks:M.kind==="proposal"?I(M.proposal.tool):void 0,item:M,onApprove:J=>G(J,"commit"),onReject:J=>G(J,"reject"),resolving:K===M.id},M.id))})]})]})}function Mx(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 Fx({proposal:e,currentUserId:t,onCancel:n}){var d;const[r,s]=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.")){s(!0);try{await n()}finally{s(!1)}}};return a.jsxs("div",{className:"card",children:[a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem",marginBottom:"0.5rem",flexWrap:"wrap"},children:[a.jsx("span",{style:{fontWeight:600,fontSize:"0.9rem"},children:ze(e.profileId)}),l&&a.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"}),a.jsx("span",{style:{marginLeft:"auto",fontSize:"0.75rem",color:"var(--text-tertiary)"},children:Mx(e.createdAt)})]}),a.jsx("div",{style:{fontSize:"0.85rem",color:"var(--text-secondary)",marginBottom:"0.5rem"},children:a.jsx("code",{children:e.tool.split("__").pop()??e.tool})}),l&&a.jsxs("div",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)",marginBottom:"0.5rem"},children:[o.map(f=>a.jsx("span",{style:{marginRight:"0.75rem",color:"var(--success, green)"},children:f===t?"You approved":`${f} approved`},f)),i.map(f=>a.jsxs("span",{style:{marginRight:"0.75rem",color:"var(--text-tertiary)"},children:["Waiting on ",f===t?"you":f]},f))]}),a.jsx("div",{style:{display:"flex",justifyContent:"flex-end",gap:"0.5rem",marginTop:"0.5rem"},children:a.jsx("button",{className:"btn btn-ghost btn-sm",style:{color:"var(--danger)"},onClick:c,disabled:r,children:r?"Cancelling...":"Cancel"})})]})}const Ox=`# Agent Brief
|
|
74
|
+
`}),m?a.jsx("p",{style:{color:"var(--text-tertiary)",fontSize:"0.9rem"},children:"Loading..."}):k.length===0?a.jsxs("div",{className:"card",style:{padding:"2rem",textAlign:"center"},children:[a.jsx("p",{style:{color:"var(--text-secondary)",fontSize:"0.9rem",marginBottom:"1rem"},children:"No integrations set up yet. Connect a service first."}),a.jsx(Qe,{to:"/integrations",className:"btn btn-primary btn-sm",onClick:()=>e==null?void 0:e(),children:"Go to Integrations"})]}):a.jsx("div",{className:"profile-grid",children:k.map(({manifest:C,profile:z,integration:D})=>{const Y=I(z.id),K=(D==null?void 0:D.running)===!0;return a.jsxs("div",{className:"card",style:K?void 0:{opacity:.7},children:[a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem",marginBottom:"0.125rem"},children:[a.jsx("h3",{className:"card-title",style:{margin:0},children:C.name}),Y?a.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"}):a.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"})]}),a.jsx("p",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)",marginBottom:"1rem",flex:1},children:C.description||z.description}),K?a.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>_(z.id,C),children:"Authorize"}):a.jsxs(Qe,{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 Wv={active:"Active",pending:"Pending",expired:"Expired",revoked:"Revoked"};function Hv({status:e,label:t}){return a.jsx("span",{className:`status-badge status-${e}`,children:t||Wv[e]})}function Vv({domain:e,attested:t}){const n=t===!0?"domain-attested":t===!1?"domain-missing":"";return a.jsx("span",{className:`domain-badge ${n}`,style:{fontSize:"0.75rem"},children:e})}const Cn=86400,_r=3600,Ls=60,Gv=30*Cn;function Kv(e){if(e<=0)return"Expired";if(e>90*Cn){const t=Math.floor(e/Gv);return`${t} ${t===1?"month":"months"} remaining`}if(e>7*Cn){const t=Math.floor(e/Cn);return`${t} ${t===1?"day":"days"} remaining`}if(e>=2*Cn){const t=Math.floor(e/Cn),n=Math.floor(e%Cn/_r);return`${t} ${t===1?"day":"days"} ${n}h remaining`}if(e>=2*_r){const t=Math.floor(e/_r),n=Math.floor(e%_r/Ls);return`${t}h ${String(n).padStart(2,"0")}m remaining`}if(e>=Ls){const t=Math.floor(e/Ls),n=Math.floor(e%Ls);return`${t}m ${String(n).padStart(2,"0")}s remaining`}return`${Math.floor(e)}s remaining`}function Yv({expiresAt:e}){const[t,n]=u.useState(()=>e-Date.now()/1e3),r=t<2*_r;u.useEffect(()=>{const o=setInterval(()=>n(e-Date.now()/1e3),r?1e3:6e4);return()=>clearInterval(o)},[e,r]);const s=t<300;return a.jsx("span",{className:`ttl-badge ${s?"ttl-warn":"ttl-ok"}`,children:Kv(t)})}function Zf({icon:e,title:t,text:n,children:r}){return a.jsxs("div",{className:"empty-state",children:[e&&a.jsx("div",{className:"empty-state-icon",children:e}),a.jsx("div",{className:"empty-state-title",children:t}),n&&a.jsx("div",{className:"empty-state-text",children:n}),r]})}function Qv(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 Jv=[{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 Xv({item:e,onClose:t,onSuccess:n}){var y;const{user:r,activeDomain:s,groupId:o}=Ae(),[i,l]=u.useState(null);u.useEffect(()=>{let S=!1;return $.getProfile(e.profile_id).then(k=>{var I;S||l(((I=k==null?void 0:k.ttl)==null?void 0:I.max)??null)}).catch(()=>{}),()=>{S=!0}},[e.profile_id]);const c=e.remaining_seconds??0,d=Jv.filter(S=>S.seconds>c&&(i===null||S.seconds<=i)),f=((y=d[0])==null?void 0:y.seconds)??2592e3,[m,p]=u.useState(f);u.useEffect(()=>{var S;if(i!==null&&m>i){const k=(S=d[d.length-1])==null?void 0:S.seconds;k&&p(k)}},[i]);const[x,w]=u.useState(!1),[v,j]=u.useState(""),h=Object.entries(e.frame).filter(([S])=>S!=="profile"&&S!=="path"),g=async()=>{var S;if(r){w(!0),j("");try{const k=e.authorization_id,I=await $.getGateContent(k);if(!I)throw new Error("Gate content not found locally. The MCP server may have restarted. Please re-authorize through the full wizard instead.");const R=await $.getProfile(e.profile_id),_=e.frame,C=I.context??{},z=e.attested_domains[0]||s||"owner",D=await Xs(_,R),Y=await Jf(C,R),[K,W]=await Promise.all([ba(I.gateContent.intent),ba(JSON.stringify({profile:e.profile_id,path:e.path,domain:z}))]);if(!o)throw new Error("No active group; cannot extend authorization.");const T=(((S=e.deferred_commitment_domains)==null?void 0:S.length)??0)>0?"review":"automatic",q=await $.attest({authorization_id:e.authorization_id,renew:!0,profile_id:e.profile_id,bounds:_,bounds_hash:D,context_hash:Y,domain:z,did:r.did,gate_content_hashes:{intent:K},execution_context_hash:W,group_id:o,commitment_mode:T,ttl:m});await $.pushGateContent(Xf(q,{boundsHash:D,contextHash:Y,context:C,path:e.path,gateContent:I.gateContent})),n()}catch(k){j(k instanceof Error?k.message:"Extension failed")}finally{w(!1)}}};return a.jsx("div",{className:"modal-backdrop",onClick:S=>S.target===S.currentTarget&&t(),children:a.jsxs("div",{className:"modal",children:[a.jsxs("div",{className:"modal-header",children:[a.jsx("h3",{className:"modal-title",children:"Extend Authorization"}),a.jsx("button",{className:"modal-close",onClick:t,children:"×"})]}),a.jsxs("div",{className:"modal-body",children:[a.jsxs("div",{style:{marginBottom:"1rem"},children:[a.jsxs("div",{style:{fontWeight:600,marginBottom:"0.25rem"},children:[ze(e.profile_id)," / ",e.path]}),h.length>0&&a.jsx("div",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)"},children:h.map(([S,k])=>`${S}=${k}`).join(" · ")})]}),a.jsxs("div",{style:{marginBottom:"1rem"},children:[a.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&&a.jsxs("div",{style:{fontSize:"0.75rem",color:"var(--text-tertiary)",marginBottom:"0.5rem"},children:["Currently valid for ",Qv(c),". Only longer durations are shown."]}),a.jsx("div",{style:{display:"flex",gap:"0.5rem",flexWrap:"wrap"},children:d.length===0?a.jsx("div",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)"},children:"This authorization is already on the longest available duration. Nothing to extend."}):d.map(S=>a.jsx("button",{className:`btn ${m===S.seconds?"btn-primary":"btn-secondary"}`,onClick:()=>p(S.seconds),style:{minWidth:"3.5rem"},children:S.label},S.seconds))})]}),a.jsx("div",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)",marginBottom:"0.5rem"},children:"Same bounds, context, and gate content will be re-attested with a new TTL (measured from now)."}),v&&a.jsx("div",{className:"error-message",children:v})]}),a.jsxs("div",{className:"modal-footer",children:[a.jsx("button",{className:"btn btn-secondary",onClick:t,disabled:x,children:"Cancel"}),a.jsx("button",{className:"btn btn-primary",onClick:g,disabled:x,children:x?"Extending...":"Extend"})]})]})})}function qv(e,t,n){return[...e].sort((r,s)=>{if(n){if(r.authorization_id===n&&s.authorization_id!==n)return-1;if(s.authorization_id===n&&r.authorization_id!==n)return 1}const o=At(r,{revokedSet:t}),i=At(s,{revokedSet:t}),l={active:0,pending:1,expired:2,revoked:3};return l[o]!==l[i]?l[o]-l[i]:new Date(s.created_at).getTime()-new Date(r.created_at).getTime()})}function Zv({item:e,newerProfile:t,revokedSet:n,expandedHash:r,gateCache:s,gateLoading:o,copiedHash:i,revokingHash:l,copyingHash:c,profileConfigCache:d,mode:f,ownerLabel:m,isAdmin:p,onExpand:x,onCopyHash:w,onCopy:v,onRevoke:j,onExtend:h,highlightHash:g}){var U;const y=At(e,{revokedSet:n}),S=r===e.authorization_id,k=s[e.authorization_id],I=y==="active"||y==="pending"||y==="expired",R=Object.entries(e.frame).filter(([O])=>O!=="profile"&&O!=="path"),_=d.get(e.profile_id)??null,C=(((U=_==null?void 0:_.approvers)==null?void 0:U.length)??0)>0,z=new Map;if(_!=null&&_.caps&&f==="team")for(const[O,G]of R){const X=_.caps[O];X!==void 0&&Number(G)>X&&z.set(O,{authorized:Number(G),cap:X})}const D=z.size>0,Y=e.approvers_frozen??[],K=(_==null?void 0:_.approvers)??[],W=f==="team"&&Y.length>0&&K.length>0&&(Y.length!==K.length||Y.some(O=>!K.includes(O))||K.some(O=>!Y.includes(O))),T=Array.from(z.entries()).map(([O,G])=>`${O}: ${G.authorized} (cap ${G.cap})`).join(", "),q=Array.from(z.entries()).map(([O,G])=>`${O}: ${G.authorized} → ${G.cap}`).join(", "),ee=D?C?z.size===1?`Above team cap: ${T} — actions require approval`:`Above team cap (${z.size}): ${T} — actions require approval`:z.size===1?`Reduced by hard cap: ${q}`:`Reduced by hard cap (${z.size}): ${q}`:"",F=D?C?"Above-cap actions under this authority 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 authorization to reissue within the cap.":void 0,L=ze(e.profile_id),H=t?a.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:[a.jsxs("strong",{style:{color:"var(--text-secondary)"},children:[L,"@",t.version," available"]}),t.whatsNew?a.jsxs(a.Fragment,{children:[" — ",t.whatsNew]}):null,a.jsx("br",{}),a.jsxs("span",{children:["This authority stays on ",e.profile_id.split("@")[1]??"its pinned version","; authorize again to move it."]})]}):null,A=g!=null&&e.authorization_id===g;return a.jsxs("div",{className:`card${A?" card-highlight":""}`,style:{marginBottom:0},children:[H,m&&a.jsxs("div",{style:{fontSize:"0.75rem",color:"var(--text-tertiary)",marginBottom:"0.375rem"},children:["Owner: ",a.jsx("span",{style:{color:"var(--text-secondary)",fontWeight:500},children:m})]}),a.jsxs("div",{className:"auth-card-header",children:[a.jsx("span",{style:{fontWeight:700,fontSize:"1rem",color:"var(--text-primary)",letterSpacing:"0.01em"},children:L}),e.title&&a.jsx("span",{style:{fontWeight:500,fontSize:"0.85rem",color:"var(--text-secondary)"},children:e.title}),a.jsx(Hv,{status:y}),y==="active"&&e.earliest_expiry&&a.jsx(Yv,{expiresAt:new Date(e.earliest_expiry).getTime()/1e3}),y==="expired"&&(()=>{const O=hy(e,y);return O?a.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-tertiary)"},title:`Expired ${new Date(O.iso).toLocaleString()}`,children:new Date(O.iso).toLocaleDateString(void 0,{month:"short",day:"numeric"})}):null})()]}),a.jsxs("div",{style:{display:"flex",gap:"0.5rem",flexWrap:"wrap",marginBottom:"0.5rem",alignItems:"center"},children:[e.required_domains.map(O=>a.jsx(Vv,{domain:O,attested:e.attested_domains.includes(O)},O)),e.deferred_commitment_domains.length>0&&a.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"}),D&&a.jsx("span",{title:F,style:{fontSize:"0.65rem",padding:"0.15rem 0.4rem",borderRadius:"0.25rem",background:C?"var(--accent-subtle)":"var(--danger-subtle)",color:C?"var(--accent)":"var(--danger)",fontWeight:600,cursor:"help"},children:ee}),W&&a.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:()=>v(e),disabled:c===e.authorization_id,title:"The approver list for this profile has changed since this authority was created. Copy to reissue with the current approvers.",children:c===e.authorization_id?"Copying...":"Approver list updated · Copy with new approvers"})]}),R.length>0&&a.jsx("div",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)"},children:R.map(([O,G],X)=>{const Z=z.get(O);return a.jsxs("span",{children:[X>0&&" · ",Z?C?a.jsxs("span",{title:`Team cap on ${O} is ${Z.cap}. Actions exceeding the cap require per-action approval. Bound remains authorized at ${Z.authorized}.`,children:[a.jsxs("span",{style:{color:"var(--text-tertiary)"},children:[O,"=",String(G)]}),a.jsxs("span",{style:{color:"var(--accent)",marginLeft:"0.25rem",fontWeight:600},children:["↑ approval at ",Z.cap]})]}):a.jsxs("span",{title:`Team cap on ${O} is ${Z.cap} with no approvers configured (hard cap). Authorized for ${Z.authorized}; effective ${Z.cap}.`,children:[a.jsxs("span",{style:{textDecoration:"line-through",color:"var(--text-tertiary)"},children:[O,"=",String(G)]}),a.jsxs("span",{style:{color:"var(--danger)",marginLeft:"0.25rem",fontWeight:600},children:["→"," ",Z.cap]})]}):a.jsxs("span",{children:[O,"=",String(G)]})]},O)})}),a.jsx("div",{style:{display:"flex",justifyContent:"flex-end",gap:"0.5rem",marginTop:"0.5rem"},children:a.jsx("button",{className:"btn btn-ghost btn-sm",onClick:()=>x(e),children:S?"▲ Hide Details":"▼ Details"})}),S&&a.jsxs("div",{style:{borderTop:"1px solid var(--border)",marginTop:"0.75rem",paddingTop:"0.75rem"},children:[R.length>0&&a.jsxs(a.Fragment,{children:[a.jsx("div",{style:{fontSize:"0.75rem",fontWeight:600,color:"var(--text-tertiary)",textTransform:"uppercase",letterSpacing:"0.04em",marginBottom:"0.25rem"},children:"Bounds"}),a.jsx("dl",{className:"review-grid",children:R.map(([O,G])=>a.jsxs("span",{style:{display:"contents"},children:[a.jsx("dt",{children:O}),a.jsx("dd",{children:String(G)})]},O))})]}),(k==null?void 0:k.context)&&Object.keys(k.context).length>0&&a.jsxs(a.Fragment,{children:[a.jsx("div",{style:{fontSize:"0.75rem",fontWeight:600,color:"var(--text-tertiary)",textTransform:"uppercase",letterSpacing:"0.04em",marginTop:"1rem",marginBottom:"0.25rem"},children:"Context"}),a.jsx("dl",{className:"review-grid",children:Object.entries(k.context).map(([O,G])=>a.jsxs("span",{style:{display:"contents"},children:[a.jsx("dt",{children:O}),a.jsx("dd",{title:String(G),children:qf(O,G,k.contextLabels)})]},O))})]}),a.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?a.jsx("p",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)"},children:"Loading gate content..."}):k?a.jsx("div",{className:"gate-content-block",children:a.jsx("div",{className:"gate-content-item",children:a.jsx("div",{className:"gate-content-text",children:k.gateContent.intent})})}):a.jsx("p",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)"},children:"Gate content not available."}),a.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()}`]}),a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem",marginTop:"0.25rem"},children:[a.jsx("span",{style:{fontSize:"0.7rem",color:"var(--text-tertiary)",fontFamily:"'SF Mono', Monaco, monospace",wordBreak:"break-all"},children:e.authorization_id}),a.jsx("button",{className:"btn btn-ghost btn-sm",style:{fontSize:"0.7rem",padding:"0.125rem 0.375rem"},onClick:()=>w(e.authorization_id),children:i===e.authorization_id?"copied":"copy"})]}),a.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:"0.5rem",marginTop:"0.75rem"},children:[!m&&a.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>v(e),disabled:c===e.authorization_id,title:"Start a new authorization pre-filled with these bounds, context, and intent",children:c===e.authorization_id?"Copying…":"⧉ Copy"}),!m&&(y==="active"||y==="pending")&&a.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>v(e,{asEdit:!0}),disabled:c===e.authorization_id,title:"Adjust intent, bounds, or scope: opens the ceremony pre-filled; signing the new authorization revokes this one",children:"✎ Edit"}),!m&&I&&a.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>h(e),children:"↻ Extend"}),m&&p&&y!=="revoked"?a.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>j(e.authorization_id,m,L),disabled:l===e.authorization_id,children:l===e.authorization_id?"Revoking…":"Revoke"}):!m&&(y==="active"||y==="pending")?a.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>j(e.authorization_id),disabled:l===e.authorization_id,children:l===e.authorization_id?"Revoking…":"Revoke"}):null]})]})]},e.authorization_id)}function ex(){const[e,t]=u.useState([]),[n,r]=u.useState(!0),[s,o]=u.useState([]),[i,l]=u.useState(!1),[c,d]=u.useState(new Map),[f,m]=u.useState("mine"),[p,x]=u.useState("active"),[w,v]=u.useState(null),[j,h]=u.useState(null),[g,y]=Af(),[S,k]=u.useState(()=>g.get("new")==="1"),[I,R]=u.useState(()=>g.get("highlight")),[_,C]=u.useState(null),[z,D]=u.useState({}),[Y,K]=u.useState(null),[W,T]=u.useState(null),[q,ee]=u.useState(null),[F,L]=u.useState(new Set),[H,A]=u.useState(null),[U,O]=u.useState(null),G=qt(),{group:X,groupId:Z,domain:de,mode:$e,activeTeam:Be}=Ae(),le=(Be==null?void 0:Be.isAdmin)===!0,[M,J]=u.useState(()=>new Map),te=u.useCallback(()=>{r(!0),$.getMyAttestations().then(t).catch(()=>{}).finally(()=>r(!1))},[]),he=u.useCallback(()=>{Z&&(l(!0),$.listTeamAuthorizations(Z).then(o).catch(()=>{}).finally(()=>l(!1)))},[Z]);ue("attestation-changed",()=>{te(),le&&Z&&he()}),u.useEffect(()=>{if(!I)return;g.get("highlight")&&(g.delete("highlight"),y(g,{replace:!0}));const N=window.setTimeout(()=>R(null),3e3);return()=>window.clearTimeout(N)},[]),Lt(te,3e5),u.useEffect(()=>{f==="team"&&le&&Z&&s.length===0&&!i&&he()},[f,le,Z,s.length,i,he]),u.useEffect(()=>{let N=!1;return $.listProfiles().then(E=>{if(N)return;const V=ie=>ie.replace(/@.*$/,"").split("/").pop()??ie,ne=ie=>ie.split("@")[1]??"",ce=new Map;for(const ie of E){const Ce=V(ie.id),Ze=ce.get(Ce);(!Ze||ne(ie.id).localeCompare(ne(Ze.id),void 0,{numeric:!0})>0)&&ce.set(Ce,ie)}d(ce)}).catch(()=>{}),()=>{N=!0}},[]);const pe=u.useCallback(N=>{const E=Ce=>Ce.replace(/@.*$/,"").split("/").pop()??Ce,V=Ce=>Ce.split("@")[1]??"",ne=c.get(E(N));if(!ne)return;const ce=V(N),ie=V(ne.id);if(!(!ce||!ie))return ie.localeCompare(ce,void 0,{numeric:!0})>0?ne:void 0},[c]);u.useEffect(()=>{if($e!=="team"||!Z)return;const N=f==="mine"?e:s;if(N.length===0)return;const E=[...new Set(N.map(V=>V.profile_id))].filter(V=>!M.has(V));if(E.length!==0){J(V=>{const ne=new Map(V);for(const ce of E)ne.set(ce,null);return ne});for(const V of E)$.getTeamProfileConfig(Z,V).then(ne=>{J(ce=>new Map(ce).set(V,ne))}).catch(()=>{})}},[e,s,f,Z,$e,M]);const Le=async N=>{if(_===N.authorization_id){C(null);return}C(N.authorization_id);const E=N.authorization_id;if(!(E in z)){K(N.authorization_id);try{const V=await $.getGateContent(E);D(ne=>({...ne,[E]:V}))}catch{D(V=>({...V,[E]:null}))}finally{K(null)}}},ot=N=>{navigator.clipboard.writeText(N).then(()=>{ee(N),setTimeout(()=>ee(null),2e3)})},De=async(N,E)=>{var V;if(!Z){alert("No active group; cannot copy authorization.");return}O(N.authorization_id);try{const ne=N.authorization_id;let ce=z[ne]??null;ne in z||(ce=await $.getGateContent(ne),D(On=>({...On,[ne]:ce})));const ie=Object.fromEntries(Object.entries(N.frame).filter(([On])=>On!=="profile"&&On!=="path")),Ce=(ce==null?void 0:ce.context)??{},Ze=((V=ce==null?void 0:ce.gateContent)==null?void 0:V.intent)??"",et=N.deferred_commitment_domains.length>0?"review":"automatic",Sn=N.attested_domains[0]||de||"owner",it=Date.parse(N.created_at),ae=N.earliest_expiry?Date.parse(N.earliest_expiry):NaN,Bt=Number.isFinite(it)&&Number.isFinite(ae)&&ae>it?Math.round((ae-it)/1e3):void 0;sessionStorage.setItem("agentAuth",JSON.stringify({profileId:N.profile_id,groupId:Z,groupName:(X==null?void 0:X.name)??null,domain:Sn})),sessionStorage.setItem("agentGate",JSON.stringify({bounds:ie,context:Ce,gateContent:{intent:Ze},templateMode:et,templateTtl:Bt})),E!=null&&E.asEdit?sessionStorage.setItem("agentEditReplaces",N.authorization_id):sessionStorage.removeItem("agentEditReplaces"),G("/agent/gate")}catch(ne){alert(ne instanceof Error?ne.message:"Failed to copy authorization")}finally{O(null)}},ht=async(N,E,V)=>{const ne=E&&V?`Revoke ${E}'s ${V} authorization? This cannot be undone.`:"Revoke this authorization? The agent will no longer be able to execute actions under this attestation.";if(confirm(ne)){A(N);try{await $.revokeAttestation(N),L(ce=>new Set(ce).add(N)),$.resyncGates().catch(()=>{}),E&&Z&&he()}catch(ce){alert(ce instanceof Error?ce.message:"Failed to revoke authorization")}finally{A(null)}}},Ie=f==="mine"?e:s,Ke=f==="mine"?n:i,se={active:Ie.filter(N=>At(N,{revokedSet:F})==="active").length,pending:Ie.filter(N=>At(N,{revokedSet:F})==="pending").length,expired:Ie.filter(N=>At(N,{revokedSet:F})==="expired").length,revoked:Ie.filter(N=>At(N,{revokedSet:F})==="revoked").length},Ue=(()=>{const N=new Map;for(const E of Ie){if(At(E,{revokedSet:F})!==p)continue;const V=N.get(E.profile_id)??{count:0,review:!1};V.count+=1,E.deferred_commitment_domains.length>0&&(V.review=!0),N.set(E.profile_id,V)}return Array.from(N.entries()).map(([E,V])=>({profileId:E,...V})).sort((E,V)=>ze(E.profileId).localeCompare(ze(V.profileId)))})(),P=qv(Ie.filter(N=>{if(At(N,{revokedSet:F})!==p||w!==null&&N.profile_id!==w)return!1;if(j!==null){const E=N.deferred_commitment_domains.length>0;if(j==="review"&&!E||j==="auto"&&E)return!1}return!0}),F,I),b={revokedSet:F,expandedHash:_,gateCache:z,gateLoading:Y,copiedHash:q,revokingHash:H,copyingHash:U,profileConfigCache:M,mode:$e,activeDomain:de,group:X,groupId:Z,onExpand:Le,onCopyHash:ot,onCopy:De,onRevoke:ht,onExtend:T,highlightHash:I};return a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"page-header",style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",gap:"1rem",flexWrap:"wrap"},children:[a.jsxs("div",{children:[a.jsx("h1",{className:"page-title",children:"Mandates"}),a.jsx("p",{className:"page-subtitle",children:"Active, pending, and expired agent authorizations."})]}),a.jsx("button",{className:"btn btn-primary",onClick:()=>k(!0),children:"+ New authorization"})]}),S&&a.jsx("div",{className:"modal-backdrop",onClick:()=>{k(!1),g.get("new")&&(g.delete("new"),y(g,{replace:!0}))},children:a.jsxs("div",{className:"modal",onClick:N=>N.stopPropagation(),style:{maxWidth:"960px",width:"90vw"},children:[a.jsxs("div",{className:"modal-header",children:[a.jsx("h2",{className:"modal-title",children:"New authorization"}),a.jsx("button",{className:"modal-close",onClick:()=>{k(!1),g.get("new")&&(g.delete("new"),y(g,{replace:!0}))},children:"×"})]}),a.jsxs("div",{className:"modal-body",children:[a.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."}),a.jsx(Uv,{onDismiss:()=>k(!1)})]})]})}),le&&a.jsxs("div",{className:"nav-tabs",style:{marginBottom:"0.5rem"},children:[a.jsx("button",{className:`nav-tab${f==="mine"?" active":""}`,onClick:()=>{m("mine"),x("active"),v(null),h(null),C(null)},children:"Mine"}),a.jsx("button",{className:`nav-tab${f==="team"?" active":""}`,onClick:()=>{m("team"),x("active"),v(null),h(null),C(null)},children:"Team"})]}),a.jsx("div",{className:"nav-tabs",children:["active","pending","expired","revoked"].map(N=>a.jsxs("button",{className:`nav-tab${p===N?" active":""}`,onClick:()=>{x(N),v(null),h(null)},children:[N.charAt(0).toUpperCase()+N.slice(1)," (",se[N],")"]},N))}),Ue.length>0&&a.jsxs("div",{style:{display:"flex",gap:"0.5rem",flexWrap:"wrap",alignItems:"center",marginTop:"-0.25rem",marginBottom:"1rem"},children:[Ue.map(N=>{const E=w===N.profileId;return a.jsx("button",{className:`btn btn-sm ${E?"btn-primary":"btn-secondary"}`,onClick:()=>v(E?null:N.profileId),children:ze(N.profileId)},N.profileId)}),a.jsx("span",{"aria-hidden":"true",style:{color:"var(--border)",fontSize:"1.1rem",padding:"0 0.25rem",userSelect:"none"},children:"|"}),["auto","review"].map(N=>{const E=j===N;return a.jsx("button",{className:`btn btn-sm ${E?"btn-primary":"btn-secondary"}`,onClick:()=>h(E?null:N),children:N==="auto"?"Auto":"Review"},N)})]}),Ke&&Ie.length===0?a.jsx("p",{style:{color:"var(--text-tertiary)"},children:"Loading..."}):P.length===0?a.jsx(Zf,{icon:"☰",title:"No authorizations",text:`No ${p} authorizations found.`}):a.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem"},children:P.map(N=>{const E=f==="team"?N:null,V=E!=null&&E.owner?E.owner.name??E.owner.email??E.owner.userId:void 0;return a.jsx(Zv,{item:N,newerProfile:pe(N.profile_id),ownerLabel:V,isAdmin:le,...b},N.authorization_id)})}),W&&a.jsx(Xv,{item:W,onClose:()=>T(null),onSuccess:()=>{T(null),te()}})]})}function tx(e){const t=e.indexOf("__");return t<0?{integrationId:"",toolName:e}:{integrationId:e.slice(0,t),toolName:e.slice(t+2)}}function nx(e,t){var c,d,f;const{integrationId:n,toolName:r}=tx(e.action),s=t.find(m=>m.id===n),o=(d=(c=s==null?void 0:s.toolGating)==null?void 0:c.overrides)==null?void 0:d[r];if(o!=null&&o.actionLabel)return o.actionLabel;const i=ze(e.profileId),l=(f=e.executionContext)==null?void 0:f.action_type;return typeof l=="string"&&l?`${i} · ${l}`:`${i} · ${r}`}function rx(e){const t=[];for(const[n,r]of Object.entries(e.executionContext??{})){if(!n.startsWith("allowed_"))continue;const s=String(r??"").trim();s&&t.push(s.split(",").map(o=>o.trim()).filter(Boolean).join(", "))}return t.join(" · ")}function sx(e){if(!e)return"";const t=[];for(const[n,r]of Object.entries(e)){if(n==="action_type")continue;const s=String(r??"").trim();if(!s)continue;const o=n.replace(/^allowed_/,"").replace(/_/g," ");t.push(`${o} ${s.split(",").map(i=>i.trim()).filter(Boolean).join(", ")}`)}return t.join(" · ")}function ax(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),s=[];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`,m=Object.keys(t??{}).filter(j=>j.endsWith(f)),p=(r&&m.find(j=>j.startsWith(`${r}_`)))??(m.length===1?m[0]:void 0),w=(p?/^(amount|spend)_/.test(p):!1)?d.amount:d.count,v=p?Number(t==null?void 0:t[p]):NaN;p&&Number.isFinite(v)?s.push(`${w} of ${v} ${c}`):s.push(`${d.count} ${d.count===1?"call":"calls"} ${c}`)}return s.join(" · ")}function ox(e){return typeof e.proposalId=="string"&&e.proposalId.length>0}function ix(e){const t=ze(e),n=e.split("@")[1];return n?`${t}@${n}`:t}function Tr({label:e,children:t}){return a.jsxs(a.Fragment,{children:[a.jsx("dt",{className:"receipt-row-label",children:e}),a.jsx("dd",{className:"receipt-row-value",children:t})]})}function lx({receipt:e,manifests:t,localAuth:n,localUnavailable:r,signature:s,grantTitle:o,ownerLabel:i,spUrl:l,formatDate:c,onOpenComplete:d}){var w;const f=rx(e),m=sx(n==null?void 0:n.context),p=ax(e,(n==null?void 0:n.bounds)??e.limits),x=n==null?void 0:n.intent;return a.jsxs("div",{className:"card",style:{marginBottom:0},children:[a.jsxs("div",{className:"receipt-head",children:[a.jsx("span",{className:"receipt-what",children:nx(e,t)}),a.jsx("span",{className:"receipt-tag",children:ox(e)?"review":"automatic"}),e.contentHash&&a.jsx("span",{className:"receipt-tag receipt-tag-bound",title:(w=e.contentBinding)!=null&&w.fields?`The receipt binds: ${e.contentBinding.fields.join(", ")}`:"This exact content was authorized",children:"content bound"}),a.jsx("span",{className:"auth-card-time",children:c(e.timestamp)})]}),f&&a.jsx("div",{className:"receipt-scope",children:f}),a.jsxs("dl",{className:"receipt-rows",children:[a.jsx(Tr,{label:"authorization",children:a.jsx("strong",{children:o||ix(e.profileId)})}),i&&a.jsx(Tr,{label:"owner",children:i}),m&&a.jsx(Tr,{label:"allowed",children:m}),p&&a.jsx(Tr,{label:"used",children:a.jsx("span",{className:"receipt-num",children:p})}),a.jsx(Tr,{label:"intent",children:x?a.jsx("span",{className:"receipt-intent",children:x}):a.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"})})]}),a.jsxs("div",{className:"receipt-foot",children:[s==="valid"&&a.jsx("span",{className:"receipt-verified",title:"Ed25519 signature checked on this device against the issuer key archived when the receipt was issued — no Authority Server involved.",children:"✓ Verified on this device"}),s==="invalid"&&a.jsx("span",{className:"receipt-tamper",title:"The stored receipt does not match what was signed.",children:"⚠ Signature check FAILED"}),a.jsx("button",{type:"button",className:"receipt-evidence-link",onClick:d,children:"Complete receipt"}),l&&a.jsxs("span",{className:"receipt-public",children:["redacted, shareable:"," ",a.jsx("a",{className:"receipt-link",href:`${l}/r/${e.id}`,target:"_blank",rel:"noreferrer",children:"public link ↗"})]})]}),a.jsxs("details",{className:"receipt-more",children:[a.jsx("summary",{children:"Raw"}),a.jsxs("div",{className:"receipt-kv",children:[a.jsxs("div",{children:["receipt · ",e.id]}),a.jsxs("div",{children:["action · ",e.action]}),a.jsxs("div",{children:["profile · ",e.profileId]}),e.authorizationId&&a.jsxs("div",{children:["authorization · ",e.authorizationId]}),Object.keys(e.executionContext??{}).length>0&&a.jsxs("div",{children:["context ·"," ",Object.entries(e.executionContext).map(([v,j])=>`${v}=${j}`).join(" · ")]}),(n==null?void 0:n.boundsHash)&&a.jsxs("div",{children:["bounds hash · ",n.boundsHash]}),(n==null?void 0:n.contextHash)&&a.jsxs("div",{children:["context hash · ",n.contextHash]}),e.contentHash&&a.jsxs("div",{children:["content · ",e.contentHash]}),e.proposalId&&a.jsxs("div",{children:["proposal · ",e.proposalId]}),a.jsxs("div",{children:["signature · ",e.signature]})]})]})]})}function cx({receipt:e,onClose:t}){const[n,r]=u.useState(null),[s,o]=u.useState(null),[i,l]=u.useState(null),[c,d]=u.useState(!0),[f,m]=u.useState(!1);u.useEffect(()=>{let j=!1;return d(!0),$.getArchivedReceipt(e.id).then(h=>{j||(r(h),o(h?"local":"authority-server"),l((h==null?void 0:h.signature)??null))}).catch(()=>{j||o("authority-server")}).finally(()=>{j||d(!1)}),()=>{j=!0}},[e.id]);const p=n?n.entry:{receipt:e},x=JSON.stringify(p,null,2);function w(){const j=URL.createObjectURL(new Blob([x],{type:"application/json"})),h=document.createElement("a");h.href=j,h.download=`suveren-receipt-${e.id.slice(0,8)}.json`,h.click(),URL.revokeObjectURL(j)}async function v(){try{await navigator.clipboard.writeText(x),m(!0),setTimeout(()=>m(!1),2e3)}catch{m(!1)}}return a.jsx("div",{className:"modal-backdrop",onClick:j=>j.target===j.currentTarget&&t(),children:a.jsxs("div",{className:"modal",style:{maxWidth:"44rem"},children:[a.jsxs("div",{className:"modal-header",children:[a.jsx("h3",{className:"modal-title",children:"Complete receipt"}),a.jsx("button",{className:"modal-close",onClick:t,"aria-label":"Close",children:"×"})]}),a.jsxs("div",{className:"modal-body",children:[i==="valid"&&a.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 receipt was issued."}),i==="invalid"&&a.jsx("p",{className:"receipt-tamper",style:{margin:"0 0 0.5rem",fontSize:"0.8rem"},children:"⚠ Signature check FAILED — the stored receipt does not match what was signed."}),a.jsx("p",{style:{fontSize:"0.8rem",color:"var(--text-muted)",margin:"0 0 0.75rem"},children:c?"Loading…":s==="local"?"Held on this device — the signed receipt, the attestation 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 receipt (it predates local archiving, or ran on another device). Shown from the Authority Server — complete and signed, but it needs the server to retrieve."}),a.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:x})]}),a.jsxs("div",{className:"modal-footer",children:[a.jsx("button",{className:"btn btn-primary btn-sm",onClick:w,children:"Download"}),a.jsx("button",{className:"btn btn-secondary btn-sm",onClick:v,children:f?"Copied":"Copy"})]})]})})}function ux(e){return new Date(e*1e3).toLocaleString()}function dx(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 fx(e,t){if(!t)return!0;const n=t.toLowerCase();return e.profileId.toLowerCase().includes(n)||ze(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 qc(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,s)=>s.timestamp-r.timestamp)}function px(){const{activeTeam:e,groupId:t}=Ae(),n=(e==null?void 0:e.isAdmin)===!0,[r,s]=u.useState("mine"),[o,i]=u.useState([]),[l,c]=u.useState([]),[d,f]=u.useState(""),[m,p]=u.useState(!0),[x,w]=u.useState({}),[v,j]=u.useState(new Set),[h,g]=u.useState(""),[y,S]=u.useState(new Set),[k,I]=u.useState(new Set),[R,_]=u.useState("all"),[C,z]=u.useState(!1),[D,Y]=u.useState(!1),[K,W]=u.useState(null),[T,q]=u.useState({}),[ee,F]=u.useState(!1),[L,H]=u.useState({}),[A,U]=u.useState({}),[O,G]=u.useState(null),[X,Z]=u.useState(null),[de,$e]=u.useState(!1),[Be,le]=u.useState(!1),M=u.useRef(""),J=u.useCallback(b=>r==="team"&&n&&t?$.listTeamReceiptsPage(t,{before:b,limit:200}):$.getMyReceiptsPage({before:b,limit:200}),[r,n,t]),te=u.useCallback(()=>{const b=r==="team"?`team:${t}`:"mine",N=M.current!==b;M.current=b,p(!0),le(!1),J().then(E=>{i(V=>N?E.receipts:qc(V,E.receipts)),Z(V=>N?E.nextBefore:V??E.nextBefore)}).catch(()=>{N&&i([]),le(!0)}).finally(()=>p(!1))},[J,r,t]),he=u.useCallback(()=>{!X||de||($e(!0),le(!1),J(X).then(b=>{i(N=>qc(N,b.receipts)),Z(b.nextBefore)}).catch(()=>le(!0)).finally(()=>$e(!1)))},[X,de,J]);Lt(te,12e4),u.useEffect(()=>{$.getIntegrationManifests().then(({manifests:b})=>c(b)).catch(()=>{}),fetch("/health").then(b=>b.json()).then(b=>{typeof b.spUrl=="string"&&f(b.spUrl.replace(/\/$/,""))}).catch(()=>{})},[]),u.useEffect(()=>{$.getLocalAuthorizations().then(({authorizations:b,signatures:N})=>{q(b),H(N),F(!1)}).catch(()=>{q({}),H({}),F(!0)}),$.getMyAttestations().then(b=>{const N={};for(const E of b)E.authorization_id&&E.title&&(N[E.authorization_id]=E.title);U(N)}).catch(()=>{})},[]),u.useEffect(()=>{r!=="team"||Object.keys(x).length>0||$.listUsers().then(b=>{const N={};for(const E of b)N[E.id]={name:E.name,email:E.email};w(N)}).catch(()=>{})},[r,x]);const pe=u.useMemo(()=>{const b=new Set;for(const N of o)b.add(ze(N.profileId));return[...b].sort()},[o]),Le=u.useMemo(()=>{const b=new Set;for(const N of o)b.add(N.action);return[...b].sort()},[o]),ot=u.useMemo(()=>{if(r!=="team")return[];const b=new Set;for(const N of o)N.userId&&b.add(N.userId);return[...b].map(N=>{var E;return{id:N,label:(E=x[N])!=null&&E.name?`${x[N].name} (${x[N].email})`:N}}).sort((N,E)=>N.label.localeCompare(E.label))},[r,o,x]),De=u.useMemo(()=>o.filter(b=>!(!fx(b,h)||y.size>0&&!y.has(ze(b.profileId))||k.size>0&&!k.has(b.action)||v.size>0&&b.userId&&!v.has(b.userId)||!dx(b,R))),[o,h,y,k,v,R]),ht=y.size>0||k.size>0||v.size>0||R!=="all";function Ie(b){S(N=>{const E=new Set(N);return E.has(b)?E.delete(b):E.add(b),E})}function Ke(b){I(N=>{const E=new Set(N);return E.has(b)?E.delete(b):E.add(b),E})}function se(b){j(N=>{const E=new Set(N);return E.has(b)?E.delete(b):E.add(b),E})}function Ue(){S(new Set),I(new Set),j(new Set),_("all"),g("")}async function P(){Y(!0),W(null);try{const{bundle:b,filename:N}=await $.fetchEvidenceBundle(),E=URL.createObjectURL(new Blob([JSON.stringify(b,null,2)],{type:"application/json"})),V=document.createElement("a");V.href=E,V.download=N,V.click(),URL.revokeObjectURL(E);const ne=b.sources??{};ne.authorityServer?ne.local||W(`Downloaded Authority Server history only — ${ne.localError??"local archive unavailable."}`):W(`Downloaded local evidence only — ${ne.asError??"Authority Server export unavailable."}`)}catch(b){W(`Export failed: ${b instanceof Error?b.message:String(b)}`)}finally{Y(!1)}}return a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"page-header",style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",gap:"1rem",flexWrap:"wrap"},children:[a.jsxs("div",{children:[a.jsx("h1",{className:"page-title",children:"Tickets"}),a.jsx("p",{className:"page-subtitle",children:"Execution history for agent actions."})]}),a.jsx("button",{className:"btn btn-secondary",onClick:P,disabled:D,children:D?"Preparing…":"Download evidence"})]}),K&&a.jsx("div",{style:{marginBottom:"1rem",color:"var(--text-tertiary)",fontSize:"0.875rem"},children:K}),n&&a.jsx("div",{style:{display:"flex",gap:"0.5rem",marginBottom:"1rem",borderBottom:"1px solid var(--border)"},children:["mine","team"].map(b=>a.jsx("button",{onClick:()=>s(b),className:"btn btn-ghost",style:{borderRadius:0,padding:"0.5rem 0.875rem",borderBottom:r===b?"2px solid var(--accent)":"2px solid transparent",color:r===b?"var(--text-primary)":"var(--text-tertiary)",fontWeight:r===b?600:500},children:b==="mine"?"Mine":"Team"},b))}),a.jsxs("div",{className:"search-filter-bar",children:[a.jsxs("div",{className:"search-input-wrap",children:[a.jsx("span",{className:"search-icon",children:"⌕"}),a.jsx("input",{type:"text",className:"form-input search-input",placeholder:"Search by profile, action, path, or hash\\u2026",value:h,onChange:b=>g(b.target.value)}),h&&a.jsx("button",{className:"search-clear",onClick:()=>g(""),children:"×"})]}),a.jsxs("button",{className:`btn btn-sm btn-secondary${C?" active":""}`,onClick:()=>z(!C),children:["Filters",ht?` (${y.size+k.size+(R!=="all"?1:0)})`:""]})]}),C&&a.jsxs("div",{className:"filter-panel",children:[pe.length>1&&a.jsxs("div",{className:"filter-section",children:[a.jsx("div",{className:"filter-label",children:"Profile"}),a.jsx("div",{className:"filter-chips",children:pe.map(b=>a.jsx("button",{className:`filter-chip${y.has(b)?" selected":""}`,onClick:()=>Ie(b),children:b},b))})]}),Le.length>1&&a.jsxs("div",{className:"filter-section",children:[a.jsx("div",{className:"filter-label",children:"Action"}),a.jsx("div",{className:"filter-chips",children:Le.map(b=>a.jsx("button",{className:`filter-chip${k.has(b)?" selected":""}`,onClick:()=>Ke(b),children:b},b))})]}),r==="team"&&ot.length>1&&a.jsxs("div",{className:"filter-section",children:[a.jsx("div",{className:"filter-label",children:"Owner"}),a.jsx("div",{className:"filter-chips",children:ot.map(b=>a.jsx("button",{className:`filter-chip${v.has(b.id)?" selected":""}`,onClick:()=>se(b.id),children:b.label},b.id))})]}),a.jsxs("div",{className:"filter-section",children:[a.jsx("div",{className:"filter-label",children:"Time range"}),a.jsx("div",{className:"filter-chips",children:[["1d","Today"],["7d","7 days"],["30d","30 days"],["all","All time"]].map(([b,N])=>a.jsx("button",{className:`filter-chip${R===b?" selected":""}`,onClick:()=>_(b),children:N},b))})]})]}),ht&&a.jsxs("div",{className:"active-filters",children:[[...y].map(b=>a.jsxs("span",{className:"active-chip",onClick:()=>Ie(b),children:[b," ",a.jsx("span",{className:"chip-remove",children:"×"})]},b)),[...k].map(b=>a.jsxs("span",{className:"active-chip",onClick:()=>Ke(b),children:[b," ",a.jsx("span",{className:"chip-remove",children:"×"})]},b)),[...v].map(b=>{const N=x[b],E=N?N.name:b;return a.jsxs("span",{className:"active-chip",onClick:()=>se(b),children:[E," ",a.jsx("span",{className:"chip-remove",children:"×"})]},b)}),R!=="all"&&a.jsxs("span",{className:"active-chip",onClick:()=>_("all"),children:[R==="1d"?"Today":R==="7d"?"7 days":"30 days"," ",a.jsx("span",{className:"chip-remove",children:"×"})]}),a.jsx("button",{className:"clear-filters",onClick:Ue,children:"Clear all"})]}),Be&&a.jsx("div",{className:"card",style:{borderColor:"var(--danger, #c0392b)",marginBottom:"0.75rem"},children:a.jsx("span",{style:{color:"var(--danger, #c0392b)",fontSize:"0.85rem"},children:"Couldn’t load receipts — your session may have expired. Try signing out and back in."})}),m&&o.length===0?a.jsx("p",{style:{color:"var(--text-tertiary)"},children:"Loading..."}):De.length===0?a.jsx(Zf,{icon:"⌕",title:o.length===0?"No receipts in the last 30 days":"No matching receipts",text:o.length===0?"Execution receipts appear here after an agent uses an authorized tool. Older receipts can be loaded below.":"Try adjusting your search or filters."}):a.jsxs(a.Fragment,{children:[a.jsx("div",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)",marginBottom:"0.75rem"},children:De.length===o.length?`${o.length} receipt${o.length!==1?"s":""}`:`${De.length} of ${o.length} receipts`}),a.jsx("div",{className:"timeline",children:De.map(b=>{const N=b.userId?x[b.userId]:void 0;return a.jsx("div",{className:"timeline-event",children:a.jsx(lx,{receipt:b,manifests:l,localAuth:b.authorizationId?T[b.authorizationId]:void 0,localUnavailable:ee,signature:L[b.id],grantTitle:b.authorizationId?A[b.authorizationId]:null,ownerLabel:r==="team"&&b.userId?N?`${N.name} (${N.email})`:b.userId:null,spUrl:d,formatDate:ux,onOpenComplete:()=>G(b)})},b.id)})})]}),O&&a.jsx(cx,{receipt:O,onClose:()=>G(null)}),X&&a.jsx("div",{style:{textAlign:"center",marginTop:"1rem"},children:a.jsx("button",{className:"btn btn-secondary btn-sm",onClick:he,disabled:de,children:de?"Loading…":"Load older"})})]})}const mx={darwin:"a macOS login item",win32:"a Windows scheduled task",linux:"a systemd user service"};function hx(){const[e,t]=u.useState(null),[n,r]=u.useState(!1),[s,o]=u.useState(null),i=u.useCallback(async()=>{try{t(await $.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 $.setAutostart(!e.installed)}catch(d){o(d instanceof Error?d.message:"Failed")}finally{try{t(await $.getAutostart()),o(null)}catch(d){o(d instanceof Error?d.message:"Could not re-read state")}r(!1)}}},[e,n,i]);if(!e)return a.jsxs("div",{className:"card",style:{padding:"1.5rem",marginTop:"2rem"},children:[a.jsx("h2",{style:{fontSize:"1rem",fontWeight:700,margin:0},children:"Keep Suveren running"}),a.jsx("p",{role:s?"alert":void 0,style:{margin:"0.5rem 0 0",fontSize:"0.9rem",color:"var(--text-secondary)"},children:s?`Could not read autostart state: ${s}`:"Checking…"})]});const c=mx[e.platform]??"a login service";return a.jsxs("div",{className:"card",style:{padding:"1.5rem",marginTop:"2rem"},children:[a.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",gap:"1rem"},children:[a.jsxs("div",{children:[a.jsx("h2",{style:{fontSize:"1rem",fontWeight:700,margin:0},children:"Keep Suveren running"}),a.jsx("p",{style:{color:"var(--text-secondary)",margin:"0.5rem 0 0",fontSize:"0.9rem"},children:e.supported?a.jsxs(a.Fragment,{children:["Starts automatically when you log in, and restarts if it crashes. Uses ",c," — no admin rights needed."]}):e.reason})]}),e.supported&&a.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&&a.jsxs("p",{style:{margin:"1rem 0 0",fontSize:"0.85rem",color:"var(--text-tertiary)"},children:["Status: ",a.jsx("strong",{children:e.installed?"On — starts from your next login":"Off"})]}),e.supported&&a.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 ",a.jsx("strong",{children:"locked"}),": you enter your API key once to unlock it, because nothing stored on this machine can unlock it for you."]}),s&&a.jsx("p",{role:"alert",style:{margin:"0.75rem 0 0",fontSize:"0.85rem",color:"var(--danger, #c00)"},children:s})]})}function gx(){const[e,t]=u.useState(null),[n,r]=u.useState(!1),[s,o]=u.useState(null),i=u.useCallback(async()=>{try{const c=await $.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 $.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?a.jsxs("div",{className:"card",style:{padding:"1.5rem",marginTop:"2rem"},children:[a.jsx("h2",{style:{fontSize:"1rem",fontWeight:700,margin:0},children:"Desktop notifications"}),a.jsx("p",{role:s?"alert":void 0,style:{margin:"0.5rem 0 0",fontSize:"0.9rem",color:"var(--text-secondary)"},children:s?`Could not read the setting: ${s}`:"Checking…"})]}):a.jsxs("div",{className:"card",style:{padding:"1.5rem",marginTop:"2rem"},children:[a.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",gap:"1rem"},children:[a.jsxs("div",{children:[a.jsx("h2",{style:{fontSize:"1rem",fontWeight:700,margin:0},children:"Desktop notifications"}),a.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."})]}),a.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"})]}),s&&a.jsx("p",{role:"alert",style:{margin:"0.75rem 0 0",fontSize:"0.85rem",color:"var(--danger)"},children:s})]})}const yx={npm:"Checking npm for new releases",docker:"Checking the container registry for new images",dev:"Git checkout — comparing against origin/main, not npm releases"};function vx(){const{version:e,latestVersion:t,updateAvailable:n,installMethod:r}=Cl();return e?a.jsxs("div",{className:"card",style:{padding:"1.5rem",marginTop:"2rem"},children:[a.jsx("h2",{style:{fontSize:"1rem",fontWeight:700,margin:0},children:"Version"}),a.jsxs("p",{style:{margin:"0.5rem 0 0",fontSize:"0.9rem",color:"var(--text-secondary)"},children:["Running ",a.jsx("strong",{children:e}),n&&t?a.jsxs(a.Fragment,{children:[" — ",a.jsx("strong",{children:t})," is available"]}):null]}),a.jsxs("p",{style:{margin:"0.5rem 0 0",fontSize:"0.85rem",color:"var(--text-tertiary)"},children:[yx[r]??"Update checking is unavailable",r==="dev"&&a.jsx(a.Fragment,{children:" — a development checkout is not told about published releases."})]})]}):null}const xx={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"]}};function wx(){const[e,t]=u.useState(""),[n,r]=u.useState("openrouter"),[s,o]=u.useState("openai-compatible"),[i,l]=u.useState("https://openrouter.ai/api/v1"),[c,d]=u.useState("google/gemma-4-31b-it"),[f,m]=u.useState(""),[p,x]=u.useState(!1),[w,v]=u.useState(!1),[j,h]=u.useState(!1),[g,y]=u.useState(null),[S,k]=u.useState([]),[I,R]=u.useState(!1),[_,C]=u.useState(null),[z,D]=u.useState(""),Y=u.useCallback(L=>{t(L),setTimeout(()=>t(""),3e3)},[]),K=u.useCallback(async(L,H,A)=>{R(!0),C(null);try{const U=await $.aiModels({provider:L,endpoint:H,...A?{apiKey:A}:{}});U.ok&&U.models.length>0?(k(U.models),C(`${U.models.length} models available`)):(k([]),C(U.message||"No models returned — using defaults"))}catch(U){k([]),C(U instanceof Error?U.message:"Failed to load models")}finally{R(!1)}},[]),W=u.useCallback(async()=>{try{const L=await $.getCredential("ai-config");if(x(L.configured),L.configured&&L.fields){const H=L.fields.provider||"openai-compatible",A=L.fields.endpoint||"";L.fields.provider&&o(H),L.fields.endpoint&&l(A),L.fields.model&&d(L.fields.model),A.includes("openai.com")?r("openai"):A.includes("groq.com")?r("groq"):A.includes("together.xyz")?r("together"):A.includes("openrouter.ai")?r("openrouter"):r("ollama"),A&&K(H,A)}}catch{}},[K]);u.useEffect(()=>{W()},[W]);const T=L=>{r(L),k([]),C(null),D("");const H=xx[L];H&&(o(H.provider),l(H.endpoint),d(""),K(H.provider,H.endpoint,f||void 0))},q=()=>K(s,i,f||void 0),ee=async()=>{v(!0);try{await $.setCredential("ai-config",{provider:s,endpoint:i,model:c,...f?{apiKey:f}:{}}),x(!0),Y("AI configuration saved!")}catch{Y("Failed to save AI config")}finally{v(!1)}},F=async()=>{h(!0),y(null);try{const L=await $.aiTest({provider:s,endpoint:i,model:c,...f?{apiKey:f}:{}});y(L.ok?`OK: ${L.message}`:`Failed: ${L.message}`)}catch(L){y(`Error: ${L instanceof Error?L.message:"Unknown"}`)}finally{h(!1)}};return a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"page-header",children:[a.jsx("h1",{className:"page-title",children:"AI Assistant"}),a.jsx("p",{className:"page-subtitle",children:"Advisory AI to help you think through intent when authorizing agents."})]}),e&&a.jsx("div",{className:"alert alert-success",children:e}),a.jsxs("div",{className:"card",children:[a.jsx("h3",{className:"card-title",children:"Configuration"}),a.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 authorizations. Keys are encrypted in your vault."}),p&&a.jsxs("div",{className:"status-banner status-banner-success",style:{marginBottom:"1rem",fontSize:"0.8rem"},children:[a.jsx("span",{className:"status-banner-icon",children:"✓"}),a.jsx("span",{className:"status-banner-text",children:"AI configured"})]}),a.jsxs("div",{className:"form-group",style:{marginBottom:"0.75rem"},children:[a.jsx("label",{className:"form-label",children:"Provider Preset"}),a.jsxs("select",{className:"form-input",value:n,onChange:L=>T(L.target.value),children:[a.jsx("option",{value:"openrouter",children:"OpenRouter (recommended)"}),a.jsx("option",{value:"ollama",children:"Ollama (local)"}),a.jsx("option",{value:"openai",children:"OpenAI"}),a.jsx("option",{value:"groq",children:"Groq"}),a.jsx("option",{value:"together",children:"Together"})]})]}),a.jsxs("div",{className:"form-group",style:{marginBottom:"0.75rem"},children:[a.jsxs("label",{className:"form-label",children:["API Key ",s==="ollama"?"(not needed for Ollama)":"(required to load models)"]}),a.jsx("input",{className:"form-input",type:"password",name:"ai-provider-api-key-credential-top",autoComplete:"new-password",value:f,onChange:L=>m(L.target.value),onBlur:()=>{f.trim()&&K(s,i,f.trim())},placeholder:p?"••••••••••••••••":"sk-... (not needed for Ollama)"}),a.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."})]}),a.jsxs("div",{className:"form-group",style:{marginBottom:"0.75rem"},children:[a.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[a.jsx("label",{className:"form-label",children:"Model"}),a.jsx("button",{type:"button",className:"btn btn-ghost",style:{fontSize:"0.75rem",padding:"0.125rem 0.5rem"},onClick:q,disabled:I,title:"Re-fetch the model list from the provider",children:I?"Loading…":"↻ Refresh"})]}),S.length===0?a.jsx("div",{className:"form-input",style:{display:"flex",alignItems:"center",minHeight:"2.5rem",color:"var(--text-secondary)",fontSize:"0.85rem"},children:I?"Loading models…":s==="ollama"?"Start Ollama locally, then ↻ Refresh to load models.":"Enter a valid API key above to load available models."}):(()=>{const L=S,H=L.includes(c),A=L.length>12,U=z.trim().toLowerCase();let O=U?L.filter(G=>G.toLowerCase().includes(U)):L;return H&&!O.includes(c)&&(O=[c,...O]),a.jsxs(a.Fragment,{children:[A&&a.jsx("input",{className:"form-input",value:z,onChange:G=>D(G.target.value),placeholder:"Filter models… (e.g. kimi)",style:{marginBottom:"0.375rem"}}),a.jsxs("select",{className:"form-input",value:H?c:"__unset__",onChange:G=>d(G.target.value==="__unset__"?"":G.target.value),children:[a.jsx("option",{value:"__unset__",disabled:!0,children:"Select a model…"}),O.map(G=>a.jsx("option",{value:G,children:G},G)),U&&O.length===0&&a.jsxs("option",{value:"__unset__",disabled:!0,children:["No models match “",z,"”"]})]})]})})(),_&&a.jsx("p",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",margin:"0.375rem 0 0"},children:_})]}),a.jsxs("div",{style:{display:"flex",gap:"0.5rem",alignItems:"center"},children:[a.jsx("button",{className:"btn btn-primary",onClick:ee,disabled:w||!c.trim(),title:c.trim()?void 0:"Select a model first",children:w?"Saving...":"Save & Encrypt"}),p&&a.jsx("button",{className:"btn btn-ghost",onClick:F,disabled:j,children:j?"Testing...":"Test Connection"})]}),g&&a.jsx("div",{className:`alert ${g.startsWith("OK")?"alert-success":"alert-error"}`,style:{marginTop:"0.75rem"},children:g})]}),a.jsx(Sx,{}),a.jsx(hx,{}),a.jsx(gx,{}),a.jsx(vx,{}),a.jsxs("div",{className:"card",style:{padding:"1.5rem",marginTop:"2rem"},children:[a.jsx("h2",{style:{fontSize:"1rem",fontWeight:700,marginBottom:"1rem"},children:"Security"}),a.jsxs("div",{style:{fontSize:"0.85rem",color:"var(--text-secondary)",lineHeight:1.7},children:[a.jsxs("div",{style:{marginBottom:"1rem"},children:[a.jsx("div",{style:{fontWeight:600,color:"var(--text-primary)",marginBottom:"0.375rem"},children:"What the gateway protects"}),a.jsxs("ul",{style:{margin:0,paddingLeft:"1.25rem"},children:[a.jsx("li",{children:"Every tool call verified against your authorization bounds"}),a.jsx("li",{children:"Credentials never exposed to agents through MCP"}),a.jsx("li",{children:"Every action produces a signed receipt"})]})]}),a.jsxs("div",{children:[a.jsx("div",{style:{fontWeight:600,color:"var(--text-primary)",marginBottom:"0.375rem"},children:"Your responsibility"}),a.jsxs("ul",{style:{margin:0,paddingLeft:"1.25rem"},children:[a.jsx("li",{children:"If your AI agent has full access to your computer, it could bypass the gateway"}),a.jsx("li",{children:"For best security, run agents in sandboxed environments"}),a.jsx("li",{children:"The gateway secures what agents do through tools — not what they do on your machine"})]})]})]})]})]})}function Sx(){const[e,t]=u.useState(null),[n,r]=u.useState({intent:"",context:""}),[s,o]=u.useState(null),[i,l]=u.useState(null),[c,d]=u.useState(null),[f,m]=u.useState(!1),p=u.useCallback(async()=>{if(!f)try{const v=await $.getAIPrompts();t(v),r({intent:v.intent.current,context:v.context.current}),m(!0)}catch(v){l(v instanceof Error?v.message:"Failed to load prompts")}},[f]),x=async v=>{if(e){o(v),l(null);try{const j=n[v],h=j.trim()===e[v].default.trim()?"":j;await $.setAIPrompt(v,h);const g=await $.getAIPrompts();t(g),r({intent:g.intent.current,context:g.context.current}),d(v),setTimeout(()=>d(null),2e3)}catch(j){l(j instanceof Error?j.message:"Save failed")}finally{o(null)}}},w=async v=>{if(confirm(`Revert ${v} prompt to the built-in default?`)){o(v),l(null);try{await $.setAIPrompt(v,"");const j=await $.getAIPrompts();t(j),r({intent:j.intent.current,context:j.context.current})}catch(j){l(j instanceof Error?j.message:"Revert failed")}finally{o(null)}}};return a.jsxs("details",{className:"card",style:{padding:"1.5rem",marginTop:"1rem"},onToggle:v=>{v.currentTarget.open&&p()},children:[a.jsx("summary",{style:{fontSize:"1rem",fontWeight:700,cursor:"pointer",listStyle:"revert",userSelect:"none"},children:"Advanced — AI assistant prompts"}),a.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-authorization) or Context (your standing-orders brief). Edit with care — changes apply on the next chat turn."}),i&&a.jsx("div",{className:"alert alert-error",style:{marginBottom:"0.75rem"},children:i}),!f&&!i&&a.jsx("p",{style:{color:"var(--text-muted)",fontSize:"0.85rem"},children:"Loading prompts…"}),e&&a.jsxs(a.Fragment,{children:[a.jsx(Zc,{kind:"intent",label:"Intent — per-authorization",description:"Used on the Intent gate when creating a new authorization.",state:e.intent,draft:n.intent,onChange:v=>r(j=>({...j,intent:v})),onSave:()=>x("intent"),onRevert:()=>w("intent"),saving:s==="intent",justSaved:c==="intent"}),a.jsx(Zc,{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:v=>r(j=>({...j,context:v})),onSave:()=>x("context"),onRevert:()=>w("context"),saving:s==="context",justSaved:c==="context"})]})]})}function Zc({kind:e,label:t,description:n,state:r,draft:s,onChange:o,onSave:i,onRevert:l,saving:c,justSaved:d}){const f=s!==r.current;return a.jsxs("section",{style:{marginBottom:"1.5rem"},children:[a.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"baseline",marginBottom:"0.25rem",gap:"1rem",flexWrap:"wrap"},children:[a.jsxs("div",{children:[a.jsx("div",{style:{fontWeight:600,fontSize:"0.9rem"},children:t}),a.jsx("div",{style:{fontSize:"0.78rem",color:"var(--text-secondary)"},children:n})]}),r.overridden&&a.jsx("span",{style:{fontSize:"0.7rem",color:"var(--accent)",fontWeight:600,textTransform:"uppercase",letterSpacing:"0.05em"},children:"Custom"})]}),a.jsx("textarea",{className:"form-textarea",value:s,onChange:m=>o(m.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`}),a.jsxs("div",{style:{display:"flex",gap:"0.5rem",alignItems:"center",marginTop:"0.5rem",flexWrap:"wrap"},children:[a.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:i,disabled:c||!f,children:c?"Saving…":"Save"}),r.overridden&&a.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&&a.jsx("span",{style:{fontSize:"0.78rem",color:"var(--success)"},children:"Saved"}),f&&!c&&!d&&a.jsx("span",{style:{fontSize:"0.78rem",color:"var(--text-muted)"},children:"Unsaved changes"})]}),a.jsxs("details",{style:{marginTop:"0.5rem"},children:[a.jsx("summary",{style:{fontSize:"0.78rem",color:"var(--text-muted)",cursor:"pointer"},children:"Show built-in default"}),a.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})]}),a.jsx("span",{style:{display:"none"},children:e})]})}function jx(e){return e.proposalId?"review":"automatic"}function eu(e,t,n={}){const r=n.status??"pending",s=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=jx(i);!s&&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 kx=["https://","http://"];function ep(e,t){return e!=null&&e.length?e.flatMap(n=>{const r=n.template.replace(/\{(\w+)\}/g,(s,o)=>{const i=t[o];return typeof i=="string"||typeof i=="number"?String(i):"\0"});return r.includes("\0")||/\{|\}/.test(r)?[]:kx.some(s=>r.toLowerCase().startsWith(s))?[{label:n.label,href:r,description:n.description}]:[]}):[]}function bx({profileId:e}){return a.jsx("span",{className:"profile-badge",children:ze(e)})}function tp(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),s=Math.floor(n%86400/3600),o=Math.floor(n%3600/60);let i;return r>0?i=`expires in ${r}d ${s}h`:s>0?i=`expires in ${s}h ${o}m`:i=`expires in ${Math.max(1,o)}m`,{label:i,urgent:n<2*3600,expired:!1}}const Cx={pending:"Pending",committed:"Approved",executed:"Executed",rejected:"Rejected",expired:"Expired"},Nx={pending:"status-pending",committed:"status-active",executed:"status-active",rejected:"status-revoked",expired:"status-expired"};function Ex(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 Tx(e){return e.split("__").pop()??e}function zx(e){const t=e.toLowerCase();return t.includes("delete")||t.includes("refund")||t.includes("cancel")||t.includes("revoke")}const Ix=new Set(["apiKey","api_key","accessToken","access_token","password","secret","signature","_imagePreview"]),Rx=/^(image|img|photo|picture|thumbnail)(_?url)?$/i;function Px(e,t){return typeof t!="string"?!1:/^data:image\//i.test(t)?!0:Rx.test(e)?/^https?:\/\//.test(t):/^https?:\/\/.+\.(jpe?g|png|gif|webp|svg|avif)(\?|$)/i.test(t)}function ji(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=>ji(t)).join(", ");try{return JSON.stringify(e,null,2)}catch{return String(e)}}function tu({item:e,onApprove:t,onReject:n,resolving:r,proposalLinks:s}){const o=e.kind==="proposal",i=o?e.proposal.status:"executed",l=o?e.proposal.tool:e.receipt.action,c=Tx(l),d=zx(l),f=o?e.proposal.toolArgs:null,m=o?e.proposal.executionContext:e.receipt.executionContext,p=o?null:e.receipt.cumulativeState,x=o?ep(s,e.proposal.toolArgs):[],w=f?Object.entries(f).filter(([j])=>!Ix.has(j)):[],v=Object.entries(m??{});return a.jsxs("div",{className:"card",children:[a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem",marginBottom:"0.75rem",flexWrap:"wrap"},children:[a.jsx(bx,{profileId:e.profileId}),a.jsx("code",{style:{fontSize:"0.85rem"},children:c}),e.commitmentMode==="automatic"&&a.jsx("span",{style:{fontSize:"0.7rem",color:"var(--text-tertiary)",textTransform:"uppercase",letterSpacing:"0.04em"},children:"autonomous"}),a.jsxs("span",{style:{marginLeft:"auto",display:"flex",alignItems:"center",gap:"0.5rem"},children:[o&&i==="pending"&&(()=>{const j=tp(e.proposal.expiresAt,Date.now());return a.jsx("span",{style:{fontSize:"0.72rem",color:j.urgent?"var(--warning)":"var(--text-tertiary)",fontWeight:j.urgent?600:400,whiteSpace:"nowrap"},children:j.label})})(),a.jsx("span",{className:`status-badge ${Nx[i]}`,children:Cx[i]}),a.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-tertiary)"},children:Ex(e.sortTimestamp)})]})]}),d&&a.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:[a.jsx("span",{children:"⚠"}),a.jsx("span",{children:"Irreversible action"})]}),o&&typeof(f==null?void 0:f._imagePreview)=="string"&&a.jsxs("div",{style:{marginBottom:"0.75rem"},children:[a.jsx("div",{style:{fontSize:"0.7rem",fontWeight:600,color:"var(--text-tertiary)",textTransform:"uppercase",letterSpacing:"0.04em",marginBottom:"0.35rem"},children:"Preview"}),a.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)"}})]}),x.length>0&&a.jsx("div",{style:{marginBottom:"0.75rem",display:"flex",gap:"0.5rem",flexWrap:"wrap"},children:x.map(j=>a.jsxs("a",{href:j.href,target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm",style:{textDecoration:"none"},title:j.description??j.href,children:[j.label," ↗"]},j.label))}),o&&w.length>0&&a.jsxs("div",{style:{marginBottom:"0.75rem"},children:[a.jsx("div",{style:{fontSize:"0.7rem",fontWeight:600,color:"var(--text-tertiary)",textTransform:"uppercase",letterSpacing:"0.04em",marginBottom:"0.35rem"},children:"Arguments"}),a.jsx("dl",{style:{display:"grid",gridTemplateColumns:"max-content 1fr",gap:"0.2rem 0.75rem",fontSize:"0.85rem",margin:0},children:w.map(([j,h])=>a.jsxs(u.Fragment,{children:[a.jsx("dt",{style:{color:"var(--text-tertiary)",whiteSpace:"nowrap",alignSelf:"start"},children:j}),a.jsx("dd",{style:{color:"var(--text-primary)",margin:0,wordBreak:"break-word",whiteSpace:"pre-wrap"},children:Px(j,h)?a.jsx("img",{src:h,alt:typeof(f==null?void 0:f.altText)=="string"?f.altText:j,style:{display:"block",maxWidth:"100%",maxHeight:"240px",borderRadius:"0.375rem",border:"1px solid var(--border)"},onError:g=>{const y=g.currentTarget,S=y.parentElement;if(!S)return;y.style.display="none";const k=document.createElement("span");k.textContent=h,k.style.color="var(--text-tertiary)",S.appendChild(k)}}):ji(h)})]},j))})]}),v.length>0&&a.jsx("div",{style:{marginBottom:"0.75rem",fontSize:"0.8rem",color:"var(--text-secondary)"},children:v.map(([j,h])=>`${j}=${ji(h)}`).join(" · ")}),p&&a.jsxs("div",{style:{fontSize:"0.75rem",color:"var(--text-tertiary)",marginBottom:"0.5rem"},children:["After this action · today: ",p.daily.count," action",p.daily.count===1?"":"s",p.daily.amount>0?`, ${p.daily.amount}`:""," · ","this month: ",p.monthly.count,p.monthly.amount>0?`, ${p.monthly.amount}`:""]}),o&&i==="pending"&&a.jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[a.jsx("button",{className:"btn btn-primary",onClick:()=>t==null?void 0:t(e.id),disabled:r,children:r?"Approving…":"Approve"}),a.jsx("button",{className:"btn btn-ghost",style:{color:"var(--danger)"},onClick:()=>n==null?void 0:n(e.id),disabled:r,children:"Reject"})]}),a.jsxs("div",{style:{marginTop:"0.5rem",fontSize:"0.7rem",color:"var(--text-tertiary)"},children:[o?"Proposal":"Receipt",": ",e.id]})]})}const _x=new Set(["apiKey","api_key","accessToken","access_token","password","secret","signature","_imagePreview"]);function ki(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=>ki(t)).join(", ");try{return JSON.stringify(e,null,2)}catch{return String(e)}}function Ax(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 $x({proposal:e,currentUserId:t,onAction:n,onMessage:r,proposalLinks:s}){const[o,i]=u.useState(!1),[l,c]=u.useState(!1),[d,f]=u.useState(null),[m,p]=u.useState(!1),[x,w]=u.useState(null),[v,j]=u.useState(!1),h=e.tool.split("__").pop()??e.tool,g=Object.entries(e.toolArgs).filter(([T])=>!_x.has(T)),y=Object.entries(e.executionContext),S=ep(s,e.toolArgs),k=e.pendingApprovers??[],I=e.approvedBy??{},R=Object.keys(I).length,_=k.filter(T=>!(T in I)).length,C=t in I,z=async()=>{if(d===null){p(!0),w(null);try{const T=await $.getAttestationIntent(e.authorizationId);if(!T){w("Intent not available or you are not an authorized approver.");return}const q=await $.decryptIntent({intentCiphertext:T.intentCiphertext,encryptedKey:T.encryptedKey,approverId:t});f(q)}catch(T){w(T instanceof Error?T.message:"Failed to decrypt intent")}finally{p(!1)}}},D=async()=>{v?j(!1):(j(!0),await z())},Y=async()=>{i(!0),r("");try{await $.approveProposal(e.id);try{if(d===null){const T=await $.getAttestationIntent(e.authorizationId);if(T){const q=await $.decryptIntent({intentCiphertext:T.intentCiphertext,encryptedKey:T.encryptedKey,approverId:t});f(q),await $.storeApprovedIntent(e.authorizationId,q)}}else await $.storeApprovedIntent(e.authorizationId,d)}catch{}r(`Approved. ${_-1>0?`${_-1} more approver(s) still needed.`:"All approvers signed off — action is ready to execute."}`),n()}catch(T){r(T instanceof Error?T.message:"Approval failed")}finally{i(!1)}},K=async()=>{const T=prompt("Rejection reason (optional):");if(T!==null){c(!0),r("");try{await $.rejectProposal(e.id,T||void 0),r("Action rejected."),n()}catch(q){r(q instanceof Error?q.message:"Rejection failed")}finally{c(!1)}}},W=o||l;return a.jsxs("div",{className:"card",children:[a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem",marginBottom:"0.5rem",flexWrap:"wrap"},children:[a.jsx("span",{style:{fontWeight:600,fontSize:"0.9rem"},children:ze(e.profileId)}),a.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"}),a.jsxs("span",{style:{marginLeft:"auto",display:"flex",alignItems:"center",gap:"0.5rem"},children:[(()=>{const T=tp(e.expiresAt,Date.now());return a.jsx("span",{style:{fontSize:"0.72rem",color:T.urgent?"var(--warning)":"var(--text-tertiary)",fontWeight:T.urgent?600:400,whiteSpace:"nowrap"},children:T.label})})(),a.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-tertiary)"},children:Ax(e.createdAt)})]})]}),a.jsxs("div",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)",marginBottom:"0.5rem"},children:[R," of ",k.length," approver",k.length===1?"":"s"," signed off",k.map(T=>{const q=T in I;return a.jsxs("span",{style:{marginLeft:"0.5rem",color:q?"var(--success, green)":"var(--text-tertiary)"},children:[q?"✓":"○"," ",T===t?"You":T]},T)})]}),a.jsxs("div",{style:{marginBottom:"0.5rem"},children:[a.jsx("div",{style:{fontSize:"0.7rem",fontWeight:600,color:"var(--text-tertiary)",textTransform:"uppercase",letterSpacing:"0.04em",marginBottom:"0.25rem"},children:"Proposed action"}),a.jsx("code",{style:{fontSize:"0.85rem"},children:h})]}),S.length>0&&a.jsx("div",{style:{marginBottom:"0.75rem",display:"flex",gap:"0.5rem",flexWrap:"wrap"},children:S.map(T=>a.jsxs("a",{href:T.href,target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm",style:{textDecoration:"none"},title:T.description??T.href,children:[T.label," ↗"]},T.label))}),g.length>0&&a.jsxs("div",{style:{marginBottom:"0.75rem"},children:[a.jsx("div",{style:{fontSize:"0.7rem",fontWeight:600,color:"var(--text-tertiary)",textTransform:"uppercase",letterSpacing:"0.04em",marginBottom:"0.25rem"},children:"Arguments"}),a.jsx("dl",{style:{display:"grid",gridTemplateColumns:"max-content 1fr",gap:"0.2rem 0.75rem",fontSize:"0.85rem",margin:0},children:g.map(([T,q])=>a.jsxs(u.Fragment,{children:[a.jsx("dt",{style:{color:"var(--text-tertiary)",whiteSpace:"nowrap",alignSelf:"start"},children:T}),a.jsx("dd",{style:{color:"var(--text-primary)",margin:0,wordBreak:"break-word",whiteSpace:"pre-wrap"},children:ki(q)})]},T))})]}),y.length>0&&a.jsx("div",{style:{fontSize:"0.8rem",color:"var(--text-secondary)",marginBottom:"0.5rem"},children:y.map(([T,q])=>`${T}=${ki(q)}`).join(" · ")}),a.jsxs("div",{style:{marginBottom:"0.75rem"},children:[a.jsxs("button",{className:"btn btn-ghost btn-sm",style:{padding:"0.2rem 0",fontSize:"0.75rem"},onClick:D,disabled:m,children:[v?"▲ Hide intent":"▼ Show intent",m&&" (decrypting...)"]}),v&&a.jsx("div",{style:{marginTop:"0.5rem",padding:"0.75rem",background:"var(--bg-main)",borderRadius:"0.375rem",border:"1px solid var(--border)"},children:x?a.jsx("p",{style:{color:"var(--danger)",fontSize:"0.8rem",margin:0},children:x}):d!==null?a.jsx("p",{style:{fontSize:"0.85rem",margin:0,whiteSpace:"pre-wrap",color:"var(--text-primary)"},children:d}):a.jsx("p",{style:{color:"var(--text-tertiary)",fontSize:"0.8rem",margin:0},children:"No intent available for this authority."})})]}),!C&&a.jsxs("div",{style:{display:"flex",gap:"0.5rem",marginTop:"0.25rem"},children:[a.jsx("button",{className:"btn btn-primary",onClick:Y,disabled:W,children:o?"Approving...":"Approve"}),a.jsx("button",{className:"btn btn-ghost",style:{color:"var(--danger)"},onClick:K,disabled:W,children:l?"Rejecting...":"Reject"})]}),C&&a.jsx("p",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)",marginTop:"0.25rem"},children:"You approved this action. Waiting on other approvers."}),a.jsxs("div",{style:{marginTop:"0.5rem",fontSize:"0.7rem",color:"var(--text-tertiary)"},children:["Proposal: ",e.id]})]})}function Lx(){const{domain:e,user:t}=Ae(),n=(t==null?void 0:t.id)??"",[r,s]=u.useState("awaiting-me"),[o,i]=u.useState([]),[l,c]=u.useState([]),[d,f]=u.useState(!0),[m,p]=u.useState(""),x=u.useCallback(async()=>{try{const M=await $.getProposalsForApprover();i(M)}catch{}finally{f(!1)}},[]);ue("proposal-added",x),ue("proposal-approved",x),ue("proposal-rejected",x),ue("proposal-resolved",x),Lt(x,3e4);const[w,v]=u.useState([]),j=u.useCallback(async()=>{try{const M=await $.getProposals(e||"owner");v(M)}catch{}},[e]);ue("proposal-added",j),ue("proposal-approved",j),ue("proposal-rejected",j),ue("proposal-resolved",j),Lt(j,3e4,e);const h=u.useMemo(()=>w.filter(M=>{var J;return M.status==="pending"&&(((J=M.pendingApprovers)==null?void 0:J.length)??0)===0}),[w]),g=u.useMemo(()=>eu(h,[],{status:"pending"}),[h]),[y,S]=u.useState([]),k=u.useCallback(async()=>{if(n)try{const J=(await $.getProposals(e||"owner")).filter(te=>te.status==="pending"&&te.pendingApprovers&&te.pendingApprovers.includes(n)&&te.approvedBy&&n in te.approvedBy);S(J)}catch{}},[n,e]);ue("proposal-approved",k),ue("proposal-rejected",k),Lt(k,3e4,`${n}:${e}`),u.useEffect(()=>{$.getIntegrationManifests().then(M=>c(M.manifests??[])).catch(()=>{})},[]);const I=M=>{var J;return(J=l.find(te=>te.id===M.split("__")[0]))==null?void 0:J.proposalLinks};u.useEffect(()=>{x(),j(),k()},[]);const[R,_]=u.useState([]),[C,z]=u.useState([]),[D,Y]=u.useState(!0),[K,W]=u.useState(null),[T,q]=u.useState(""),[ee,F]=u.useState("pending"),[L,H]=u.useState(null),[A,U]=u.useState(!1),O=u.useCallback(async()=>{try{const{proposals:M,receipts:J}=await $.getThread({domain:e,status:ee,sinceDays:7});_(M),z(J)}catch{}finally{Y(!1)}},[e,ee]);Lt(O,3e4,`${e}:${ee}`);const G=async(M,J)=>{W(M),q("");try{const te=e||"owner",he=await $.resolveProposal(M,J,te);q(J==="commit"?`Action approved. Status: ${he.status}`:"Action rejected."),await Promise.all([O(),j()])}catch(te){q(te instanceof Error?te.message:"Failed")}finally{W(null)}},X=u.useMemo(()=>{const M=new Set;for(const J of R)M.add(J.profileId);for(const J of C)M.add(J.profileId);return Array.from(M).sort()},[R,C]),Z=u.useMemo(()=>eu(R,C,{status:ee,profile:L??void 0,includeAutonomous:A}),[R,C,ee,L,A]),de=u.useCallback(()=>{x(),k()},[x,k]),$e=u.useMemo(()=>{const M=new Set,J=[];for(const te of y)M.has(te.id)||(M.add(te.id),J.push(te));return J.sort((te,he)=>he.createdAt-te.createdAt)},[y]),Be=o.length+g.length,le=$e.length;return a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"page-header",children:[a.jsx("h1",{className:"page-title",children:"Pending Approvals"}),a.jsx("p",{className:"page-subtitle",children:"Actions awaiting approval, plus recent activity from the last 7 days."})]}),a.jsxs("div",{className:"nav-tabs",style:{marginBottom:"1rem"},children:[a.jsxs("button",{className:`nav-tab${r==="awaiting-me"?" active":""}`,onClick:()=>s("awaiting-me"),children:["Awaiting me ",Be>0&&a.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:Be})]}),a.jsxs("button",{className:`nav-tab${r==="awaiting-others"?" active":""}`,onClick:()=>s("awaiting-others"),children:["Awaiting others ",le>0&&a.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:le})]}),a.jsx("button",{className:`nav-tab${r==="all"?" active":""}`,onClick:()=>{s("all"),O()},children:"All"})]}),r==="awaiting-me"&&a.jsx(a.Fragment,{children:d&&Be===0?a.jsx("p",{style:{color:"var(--text-tertiary)"},children:"Loading..."}):Be===0?a.jsxs("div",{className:"card",style:{textAlign:"center",padding:"2rem"},children:[a.jsx("p",{style:{color:"var(--text-tertiary)",marginBottom:"0.5rem"},children:"No actions awaiting your approval."}),a.jsx("p",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)"},children:"Review-mode actions and above-cap actions you must approve will appear here."})]}):a.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"1rem"},children:[(m||T)&&a.jsx("div",{className:"alert alert-success",children:m||T}),g.map(M=>a.jsx(tu,{proposalLinks:M.kind==="proposal"?I(M.proposal.tool):void 0,item:M,onApprove:J=>G(J,"commit"),onReject:J=>G(J,"reject"),resolving:K===M.id},M.id)),o.map(M=>a.jsx($x,{proposal:M,currentUserId:n,onAction:de,onMessage:p,proposalLinks:I(M.tool)},M.id))]})}),r==="awaiting-others"&&a.jsx(a.Fragment,{children:$e.length===0?a.jsxs("div",{className:"card",style:{textAlign:"center",padding:"2rem"},children:[a.jsx("p",{style:{color:"var(--text-tertiary)",marginBottom:"0.5rem"},children:"No actions waiting on others."}),a.jsx("p",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)"},children:"Actions you proposed or approved that are pending other approvers will appear here."})]}):a.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"1rem"},children:$e.map(M=>a.jsx(Fx,{proposal:M,currentUserId:n,onCancel:async()=>{try{await $.rejectProposal(M.id,"cancelled by creator"),k(),j()}catch(J){alert(J instanceof Error?J.message:"Cancel failed")}}},M.id))})}),r==="all"&&a.jsxs(a.Fragment,{children:[T&&a.jsx("div",{className:"alert alert-success",style:{marginBottom:"1rem"},children:T}),a.jsxs("div",{className:"filter-chips",style:{marginBottom:"1rem"},children:[a.jsx("button",{className:`filter-chip ${ee==="pending"?"selected":""}`,onClick:()=>F("pending"),children:"Pending"}),a.jsx("button",{className:`filter-chip ${ee==="all"?"selected":""}`,onClick:()=>F("all"),children:"All"}),X.length>0&&a.jsx("span",{style:{width:1,background:"var(--border)",alignSelf:"stretch",margin:"0 0.25rem"}}),X.map(M=>a.jsx("button",{className:`filter-chip ${L===M?"selected":""}`,onClick:()=>H(L===M?null:M),children:ze(M)},M)),ee==="all"&&a.jsxs(a.Fragment,{children:[a.jsx("span",{style:{width:1,background:"var(--border)",alignSelf:"stretch",margin:"0 0.25rem"}}),a.jsxs("button",{className:`filter-chip ${A?"selected":""}`,onClick:()=>U(!A),title:"Include actions executed without human review (automatic commitment mode)",children:[A?"✓ ":"","Autonomous actions"]})]})]}),D&&Z.length===0?a.jsx("p",{style:{color:"var(--text-tertiary)"},children:"Loading..."}):Z.length===0?a.jsxs("div",{className:"card",style:{textAlign:"center",padding:"2rem"},children:[a.jsx("p",{style:{color:"var(--text-tertiary)",marginBottom:"0.5rem"},children:ee==="pending"?"No actions awaiting your approval.":"Nothing here yet."}),a.jsx("p",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)"},children:ee==="pending"?"Your agents are operating within their authorizations. Switch to All to see recent activity.":"When an agent calls a gated tool, activity will appear here."})]}):a.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"1rem"},children:Z.map(M=>a.jsx(tu,{proposalLinks:M.kind==="proposal"?I(M.proposal.tool):void 0,item:M,onApprove:J=>G(J,"commit"),onReject:J=>G(J,"reject"),resolving:K===M.id},M.id))})]})]})}function Mx(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 Fx({proposal:e,currentUserId:t,onCancel:n}){var d;const[r,s]=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.")){s(!0);try{await n()}finally{s(!1)}}};return a.jsxs("div",{className:"card",children:[a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem",marginBottom:"0.5rem",flexWrap:"wrap"},children:[a.jsx("span",{style:{fontWeight:600,fontSize:"0.9rem"},children:ze(e.profileId)}),l&&a.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"}),a.jsx("span",{style:{marginLeft:"auto",fontSize:"0.75rem",color:"var(--text-tertiary)"},children:Mx(e.createdAt)})]}),a.jsx("div",{style:{fontSize:"0.85rem",color:"var(--text-secondary)",marginBottom:"0.5rem"},children:a.jsx("code",{children:e.tool.split("__").pop()??e.tool})}),l&&a.jsxs("div",{style:{fontSize:"0.8rem",color:"var(--text-tertiary)",marginBottom:"0.5rem"},children:[o.map(f=>a.jsx("span",{style:{marginRight:"0.75rem",color:"var(--success, green)"},children:f===t?"You approved":`${f} approved`},f)),i.map(f=>a.jsxs("span",{style:{marginRight:"0.75rem",color:"var(--text-tertiary)"},children:["Waiting on ",f===t?"you":f]},f))]}),a.jsx("div",{style:{display:"flex",justifyContent:"flex-end",gap:"0.5rem",marginTop:"0.5rem"},children:a.jsx("button",{className:"btn btn-ghost btn-sm",style:{color:"var(--danger)"},onClick:c,disabled:r,children:r?"Cancelling...":"Cancel"})})]})}const Ox=`# 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
|