diff --git a/agent-gateway/cmd/agent-gateway/root.go b/agent-gateway/cmd/agent-gateway/root.go index e8c0ebb1..7e89b139 100644 --- a/agent-gateway/cmd/agent-gateway/root.go +++ b/agent-gateway/cmd/agent-gateway/root.go @@ -247,7 +247,7 @@ func executeServe(command *cobra.Command, dataDir, authority string, allowedHost } runtime, err := newComposition(composition.Options{ Ownership: ownership, TrafficBudget: budget, - Store: store, InstallationID: identity.InstallationID, CallbackURL: "http://" + httpboundary.LocalAuthority(authority) + "/oauth/callback", + Store: store, InstallationID: identity.InstallationID, CallbackURL: origin + "/oauth/callback", Clock: dependencies.clock, Entropy: dependencies.entropy, Invalidate: eventHub.Publish, Ready: ready.Load, Diagnostics: dependencies.diagnostics, DiagnosticProcessID: dependencies.diagnostics.ProcessID(), diff --git a/agent-gateway/docs/design/downstream-servers.md b/agent-gateway/docs/design/downstream-servers.md index 3d9a0807..51eef7a2 100644 --- a/agent-gateway/docs/design/downstream-servers.md +++ b/agent-gateway/docs/design/downstream-servers.md @@ -188,7 +188,7 @@ The registered-resource origin and explicitly trusted origins may resolve to res A static registration is local and binds the exact graph issuer/resource, configured client ID, exact callback URI, and an explicitly metadata-supported token endpoint authentication method. Dynamic registration requires the advertised role endpoint and no reusable exact unexpired authority. -It sends one unauthenticated bounded RFC 7591 native-client JSON request with the exact callback, code response, code/refresh grants, and one method selected Basic → Post → None; it never probes or retries. Publication accepts only bounded extensible JSON at `201` whose client ID, sole callback, response/grant support, returned method, and secret/expiry shape match. +It sends one unauthenticated bounded RFC 7591 JSON request with application type `web` for the configured external HTTPS callback or `native` for local HTTP loopback, the exact callback, code response, code/refresh grants, and one method selected Basic → Post → None; it never probes or retries. Provider-specific registration acceptance remains outside this protocol support. Publication accepts only bounded extensible JSON at `201` whose client ID, sole callback, response/grant support, returned method, and secret/expiry shape match. Confidential results require a nonempty secret; an omitted expiry or expiry `0` means non-expiring, while any nonzero expiry must be strictly future. They atomically publish the registration row, `oauth_client` credential revision/handle, keyring authority, and verified candidate generation in one marker-armed transaction. @@ -200,7 +200,9 @@ Stale desired/registration/client/flow or drain results are orphan cleanup only; Foreground flow creation first commits one safe `preparing` record under the global-16/per-server-one bound, then performs discovery/registration outside SQLite admission. Independent 32-byte state and verifier material, S256 challenge, exact graph/registration/revision binding, endpoint snapshot, and sorted requested scopes remain in one process-local registry. -Optional `callback_uri` selects one exact HTTP `localhost` or canonical numeric-loopback URI with an explicit nonzero port and canonical path. Query, fragment, userinfo, wildcard/remote/alias hosts, encoded paths, and ambiguous spellings are rejected. `localhost` binds numeric `127.0.0.1`, never a resolved or wildcard address. Omission retains the main numeric-loopback `/oauth/callback`; that exact URI reuses the existing listener. Registration, authorization, and exchange retain identical redirect bytes. +With a configured external HTTPS origin, omission of `callback_uri` selects that exact origin plus `/oauth/callback`. Explicit remote overrides must equal those bytes, including scheme, authority, port and path; they reuse the main Gateway listener and never acquire a public listener. The main HTTP boundary admits only the configured external Host for callbacks, rejects encoded paths and bodies, and rejects forwarding headers rather than deriving authority from them. API create/transport replacement validates selection against the configured origin; flow preparation rechecks before discovery/registration so persisted configuration cannot bypass a changed serving origin. Registration, authorization and token exchange retain the same exact redirect bytes. + +Without external origin, optional `callback_uri` selects one exact HTTP `localhost` or canonical numeric-loopback URI with an explicit nonzero port and canonical path. Query, fragment, userinfo, wildcard/remote/alias hosts, encoded paths, and ambiguous spellings are rejected. `localhost` binds numeric `127.0.0.1`, never a resolved or wildcard address. Omission retains the main numeric-loopback `/oauth/callback`; that exact URI reuses the existing listener. Registration, authorization, and exchange retain identical redirect bytes. Composition owns temporary callback-only listener acquisition before URL publication. A conflicting port fails without fallback. Each listener admits only its exact method, path, and authority, rejects forwarding headers and request bodies, and delegates to the shared one-time state/PKCE/issuer/fence/token owner. State presented on the wrong callback or another flow's listener is not consumed. The existing global flow bound limits outstanding listener owners and accepted connections, while the independent callback-work bound limits exchanges. Header/body/write deadlines and shutdown are finite. No MCP, health, administration, assets, redirects, main allowed-host, or alternate browser-origin authority is added. Terminal, cancellation, expiry, supersession, shutdown, and late preparation paths release owned listeners; drain waits for their connections outside unrelated locks. diff --git a/agent-gateway/docs/operators/remote-serving.md b/agent-gateway/docs/operators/remote-serving.md index e3daa85b..04751509 100644 --- a/agent-gateway/docs/operators/remote-serving.md +++ b/agent-gateway/docs/operators/remote-serving.md @@ -23,9 +23,17 @@ Replace the example with your canonical public HTTPS origin: lowercase DNS hostn This contract needs no vendor-specific headers or trusted-proxy CIDR discovery. The configured origin automatically permits its exact public Host and is the only trusted browser Origin. Session cookies are Secure, HttpOnly, host-only and SameSite=Strict; CSRF and separate administrator/agent credentials remain mandatory. Repeatable `--allowed-host internal.example` permits authenticated direct MCP/API access at internal aliases without granting browser Origin trust. Forwarding headers cannot add aliases. +## Remote browser OAuth + +With `--external-origin https://gateway.example`, upstream OAuth defaults to the exact redirect `https://gateway.example/oauth/callback`. Route that path through the same proxy and main Gateway listener; no additional public callback listener or SSH tunnel is needed. Registration, browser authorization and token exchange use identical redirect bytes. An explicit per-server `callback_uri` in remote mode must equal this configured origin plus `/oauth/callback`, including a nondefault port; different hosts, ports, paths and local-loopback overrides are rejected. Forwarding headers never select callback authority. + +Register that exact URI with your provider when using a configured client. Dynamic registration advertises a `web` application for HTTPS callbacks (`native` remains the local-loopback behavior); provider support for registration, redirect policy and token authentication still varies. Public HTTPS callback support is not universal provider compatibility. Start authorization from the Servers UI, follow the provider page, then return to Gateway to inspect the flow. A canceled, expired, completed or interrupted flow cannot be replayed; after restart start a new flow rather than revisiting the old page. See [upstream OAuth configuration](upstream-servers.md#oauth-compatibility-settings). + +Keep proxy callback URLs/query strings out of access logs and error pages: they carry one-time authorization material. Disable callback caching and retries. Gateway's callback responses are fixed and nonreflecting; its HTTPS issuer/token endpoint and upstream address policies remain unchanged. Source fixtures use an isolated HTTPS provider and reverse proxy, not a real provider, installed proxy or container qualification. + ## Local access and protocol separation -For wildcard binds, local health probes use `http://127.0.0.1:8210/livez` or `/readyz`, and a local CLI (including one invoked through `docker exec` in an operator-managed container) uses the same loopback endpoint and protected administrator bearer file. Use `--address http://127.0.0.1:` for a custom port. This narrow internal access accepts no Origin or Cookie header and cannot sign in or serve the browser. A specific non-loopback bind does not also listen on loopback. Remote HTTPS CLI and external OAuth callbacks are not delivered by this configuration. +For wildcard binds, local health probes use `http://127.0.0.1:8210/livez` or `/readyz`, and a local CLI (including one invoked through `docker exec` in an operator-managed container) uses the same loopback endpoint and protected administrator bearer file. Use `--address http://127.0.0.1:` for a custom port. This narrow internal access accepts no Origin or Cookie header and cannot sign in or serve the browser. A specific non-loopback bind does not also listen on loopback. Remote HTTPS CLI is not delivered by this configuration; local CLI through `docker exec` remains sufficient. HTTP/Git forwarding is a **separate direct listener**, not a website route. Enable it explicitly with e.g. `--http-proxy-listen 0.0.0.0:8212` instead of the opt-out above, after [client/CA setup](http-proxy.md); protect the unencrypted client-to-proxy hop. Wildcard listeners conservatively reserve their ports against outgoing proxy requests. Container image/runtime qualification and live Debian/proxy adoption require separate evidence; source tests do not qualify them. diff --git a/agent-gateway/docs/operators/upstream-servers.md b/agent-gateway/docs/operators/upstream-servers.md index 90e10565..30454bb8 100644 --- a/agent-gateway/docs/operators/upstream-servers.md +++ b/agent-gateway/docs/operators/upstream-servers.md @@ -117,7 +117,7 @@ These headers apply only to this server's MCP requests (all protocol modes, init Server create files, complete transport replacements in server update files, and the web form's **Advanced OAuth settings** accept three optional fields under `transport.authentication`: -- `callback_uri`: the exact HTTP loopback redirect registered with the provider, including explicit port and canonical path. `localhost`, canonical IPv4 loopback, and `[::1]` are accepted; remote names, wildcard addresses, credentials, query, fragment, encoded paths, and ambiguous spellings are rejected. Omission uses the main numeric-loopback `/oauth/callback` listener. +- `callback_uri`: omit for Gateway's default `/oauth/callback`. With `--external-origin`, the default uses that exact HTTPS origin, and an explicit override must equal that origin plus `/oauth/callback` byte-for-byte. No other host, port, path or loopback override is accepted in remote mode. Without external origin, supported overrides remain exact HTTP loopback redirects with an explicit port and canonical path: `localhost`, canonical IPv4 loopback, and `[::1]`. Credentials, query, fragment, encoded paths, wildcard addresses and ambiguous spellings are rejected. Configuration saves check the current serving origin, and flow creation rechecks it before provider work (including after a serving-origin change). - `auth_server_metadata_url`: an exact canonical HTTPS metadata location with a path and optional bounded query. This changes the fetch location for authorization and refresh, never issuer identity or protected-resource authority. Invalid metadata fails without fallback. Existing TLS, address, trusted-origin, no-redirect, size, and deadline controls still apply. - `scopes`: initial scope tokens replacing resource-metadata defaults. Tokens are deduplicated and sorted, bounded to 64 entries, 256 bytes each, and 8192 bytes including separators. `[]` explicitly sends an empty scope value; omission uses metadata defaults. `request_offline_access` separately adds `offline_access` only when advertised. Token responses may narrow, never expand the requested set; later expansion requires a new foreground authorization, without tool-call replay. @@ -149,7 +149,9 @@ This disabled synthetic example illustrates all three settings together; its met Save as a JSON file and use `agent-gateway mcp server create --file PATH`. For updates, put the complete `transport` object under `transport` in the patch file and use `agent-gateway mcp server update SERVER_ID --file PATH --yes`. -Registration, browser authorization, and code exchange use identical redirect bytes. Gateway acquires a separate numeric-loopback, callback-only listener before exposing the authorization URL. A port collision—including another Broker or flow—fails without random-port fallback: stop the conflicting listener and start a new flow. The default callback URI reuses the main callback route. Additional listeners never expose MCP, administration, health, or assets, and main `--allowed-host` configuration neither registers nor admits them. Listeners close on terminal state, cancellation, expiry, supersession, shutdown, and rejected late preparation. Configuration changes fence stale flows and incompatible token authority. Restart never resumes listeners or authorization pages. +Registration, browser authorization, and code exchange use identical redirect bytes. HTTPS callbacks use the existing main listener through the [remote-serving proxy contract](remote-serving.md#remote-browser-oauth), never a new public listener. Dynamic registration sends application type `web` for HTTPS and `native` for HTTP loopback; a provider may still require manual client registration or impose additional redirect/client-authentication restrictions. This support does not qualify any particular provider. + +For a nondefault local callback, Gateway acquires a separate numeric-loopback, callback-only listener before exposing the authorization URL. A port collision—including another Broker or flow—fails without random-port fallback: stop the conflicting listener and start a new flow. The default callback URI reuses the main callback route. Additional listeners never expose MCP, administration, health, or assets, and main `--allowed-host` configuration neither registers nor admits them. Listeners close on terminal state, cancellation, expiry, supersession, shutdown, and rejected late preparation. Configuration changes fence stale flows and incompatible token authority. Restart never resumes listeners or authorization pages. Deterministic fixtures are not live Slack qualification. Use actual provider configuration and credentials only under separately authorized live testing. @@ -214,7 +216,7 @@ agent-gateway mcp server auth-flow start SERVER_ID --etag ETAG --open Flow start requires a prepared controlling terminal in human and JSON modes. It publishes the one-time authorization URL only to that sink; safe metadata goes to ordinary output. `--open` opens the validated URL explicitly without a referrer. Gateway does not retain or reconstruct a lost URL and never retries flow creation automatically. -The OAuth callback remains Gateway-owned, on its main origin by default or the configured callback-only loopback listener, never the frontend development origin. Flow state is process-local where sensitive and bounded where durable; restart interrupts nonterminal work. To cancel an eligible flow after reading its current state: +The OAuth callback remains Gateway-owned, on its configured external HTTPS origin or local main origin by default, or the configured callback-only loopback listener in local mode, never the frontend development origin. Flow state is process-local where sensitive and bounded where durable; restart interrupts nonterminal work. To cancel an eligible flow after reading its current state: ```bash agent-gateway mcp server auth-flow cancel SERVER_ID FLOW_ID diff --git a/agent-gateway/internal/api/remote_callback_test.go b/agent-gateway/internal/api/remote_callback_test.go new file mode 100644 index 00000000..0a790a0a --- /dev/null +++ b/agent-gateway/internal/api/remote_callback_test.go @@ -0,0 +1,32 @@ +package api + +import ( + "testing" + + "github.com/averycrespi/agent-tools/agent-gateway/internal/contract" + "github.com/stretchr/testify/require" +) + +func TestConfiguredCallbackSelection(t *testing.T) { + for _, test := range []struct { + origin, callback string + valid bool + }{ + {"https://gateway.example:8443", "https://gateway.example:8443/oauth/callback", true}, + {"https://gateway.example:8443", "https://gateway.example/oauth/callback", false}, + {"https://gateway.example:8443", "https://other.example:8443/oauth/callback", false}, + {"https://gateway.example:8443", "https://gateway.example:8443/other", false}, + {"https://gateway.example:8443", "http://localhost:3118/callback", false}, + {"http://127.0.0.1:8210", "https://gateway.example:8443/oauth/callback", false}, + {"http://127.0.0.1:8210", "http://localhost:3118/callback", true}, + } { + handler := New(Options{Origin: test.origin}) + transport := contract.StreamableHTTPTransport{Authentication: contract.OAuthAuthentication{CallbackURI: &test.callback}} + err := handler.validateCallbackSelection(transport) + if test.valid { + require.NoError(t, err) + } else { + require.Error(t, err) + } + } +} diff --git a/agent-gateway/internal/api/servers.go b/agent-gateway/internal/api/servers.go index caa0864b..91de4d11 100644 --- a/agent-gateway/internal/api/servers.go +++ b/agent-gateway/internal/api/servers.go @@ -27,6 +27,18 @@ type ServerService interface { ListOperations(context.Context, string, *serverdomain.SnapshotCursor, int) (serverdomain.OperationPage, error) } +func (handler *Handler) validateCallbackSelection(transport contract.Transport) error { + httpTransport, ok := transport.(contract.StreamableHTTPTransport) + if !ok { + return nil + } + authentication, ok := httpTransport.Authentication.(contract.OAuthAuthentication) + if ok && authentication.CallbackURI != nil && !contract.ValidOAuthCallbackSelection(handler.origin+"/oauth/callback", *authentication.CallbackURI) { + return serverdomain.NewConfigurationError(contract.ServerConfigurationFieldCallbackURI, contract.ServerConfigurationRuleCanonicalURL) + } + return nil +} + type OperationStateProvider func(context.Context, string) serverdomain.OperationTriggerState type rawServerCreate struct { @@ -100,6 +112,10 @@ func (handler *Handler) createServer(writer http.ResponseWriter, request *http.R writeServerConfigurationError(writer, err) return } + if err := handler.validateCallbackSelection(transport); err != nil { + writeServerConfigurationError(writer, err) + return + } key, ok := idempotencyKey(writer, request) if !ok { return @@ -178,6 +194,10 @@ func (handler *Handler) patchServer(writer http.ResponseWriter, request *http.Re writeServerConfigurationError(writer, err) return } + if err := handler.validateCallbackSelection(transport); err != nil { + writeServerConfigurationError(writer, err) + return + } patch.Transport = transport } result, err := handler.servers.Patch(request.Context(), serverID, revision, patch) diff --git a/agent-gateway/internal/api/static/app.js b/agent-gateway/internal/api/static/app.js index 9e28e1e4..c09ebec9 100644 --- a/agent-gateway/internal/api/static/app.js +++ b/agent-gateway/internal/api/static/app.js @@ -1,3 +1,3 @@ (function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var e,t,n,r,i,a,o,s,c,l,u,d,f,p,m={},h=[],g=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,_=Array.isArray;function v(e,t){for(var n in t)e[n]=t[n];return e}function y(e){e&&e.parentNode&&e.parentNode.removeChild(e)}function b(t,n,r){var i,a,o,s={};for(o in n)o==`key`?i=n[o]:o==`ref`?a=n[o]:s[o]=n[o];if(arguments.length>2&&(s.children=arguments.length>3?e.call(arguments,2):r),typeof t==`function`&&t.defaultProps!=null)for(o in t.defaultProps)s[o]===void 0&&(s[o]=t.defaultProps[o]);return x(t,s,i,a,null)}function x(e,r,i,a,o){var s={type:e,props:r,key:i,ref:a,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:o??++n,__i:-1,__u:0};return o==null&&t.vnode!=null&&t.vnode(s),s}function S(e){return e.children}function C(e,t){this.props=e,this.context=t}function w(e,t){if(t==null)return e.__?w(e.__,e.__i+1):null;for(var n;tt&&r.sort(o),e=r.shift(),t=r.length,T(e)}finally{r.length=O.__r=0}}function k(e,t,n,r,i,a,o,s,c,l,u){var d,f,p,g,_,v,y=r&&r.__k||h,b=t.length;for(c=A(n,t,y,c,b),d=0;d0?o=e.__k[a]=x(o.type,o.props,o.key,o.ref?o.ref:null,o.__v):e.__k[a]=o,c=a+f,o.__=e,o.__b=e.__b+1,s=null,(l=o.__i=M(o,n,c,d))!=-1&&(d--,(s=n[l])&&(s.__u|=2)),s==null||s.__v==null?(l==-1&&(i>u?f--:ic?f--:f++,o.__u|=4))):e.__k[a]=null;if(d)for(a=0;a+!!u){for(i=n-1,a=n+1;i>=0||a=0?i--:a++])!=null&&!(2&l.__u)&&s==l.key&&c==l.type)return o}return-1}function N(e,t,n){t[0]==`-`?e.setProperty(t,n??``):e[t]=n==null?``:typeof n!=`number`||g.test(t)?n:n+`px`}function ee(e,t,n,r,i){var a,o;n:if(t==`style`){if(typeof n==`string`)e.style.cssText=n;else{if(typeof r==`string`&&(e.style.cssText=r=``),r)for(t in r)n&&t in n||N(e.style,t,``);if(n)for(t in n)r&&n[t]==r[t]||N(e.style,t,n[t])}}else if(t[0]==`o`&&t[1]==`n`)a=t!=(t=t.replace(u,`$1`)),o=t.toLowerCase(),t=o in e||t==`onFocusOut`||t==`onFocusIn`?o.slice(2):t.slice(2),e.l||={},e.l[t+a]=n,n?r?n[l]=r[l]:(n[l]=d,e.addEventListener(t,a?p:f,a)):e.removeEventListener(t,a?p:f,a);else{if(i==`http://www.w3.org/2000/svg`)t=t.replace(/xlink(H|:h)/,`h`).replace(/sName$/,`s`);else if(t!=`width`&&t!=`height`&&t!=`href`&&t!=`list`&&t!=`form`&&t!=`tabIndex`&&t!=`download`&&t!=`rowSpan`&&t!=`colSpan`&&t!=`role`&&t!=`popover`&&t in e)try{e[t]=n??``;break n}catch{}typeof n==`function`||(n==null||!1===n&&t[4]!=`-`?e.removeAttribute(t):e.setAttribute(t,t==`popover`&&n==1?``:n))}}function P(e){return function(n){if(this.l){var r=this.l[n.type+e];if(n[c]==null)n[c]=d++;else if(n[c]0?e:_(e)?e.map(I):e.constructor===void 0?v({},e):null}function re(n,r,i,a,o,s,c,l,u){var d,f,p,h,g,v,b,x=i.props||m,S=r.props,C=r.type;if(C==`svg`?o=`http://www.w3.org/2000/svg`:C==`math`?o=`http://www.w3.org/1998/Math/MathML`:o||=`http://www.w3.org/1999/xhtml`,s!=null){for(d=0;d=n.__.length&&n.__.push({}),n.__[e]}function z(e){return de=1,be(Ae,e)}function be(e,t,n){var r=ye(ce++,2);if(r.t=e,!r.__c&&(r.__=[n?n(t):Ae(void 0,t),function(e){var t=r.__N?r.__N[0]:r.__[0],n=r.t(t,e);t!==n&&(r.__N=[n,r.__[1]],r.__c.setState({}))}],r.__c=L,!L.__f)){var i=function(e,t,n){if(!r.__c.__H)return!0;var i=!1,o=r.__c.props!==e;if(r.__c.__H.__.some(function(e){if(e.__N){i=!0;var t=e.__[0];e.__=e.__N,e.__N=void 0,t!==e.__[0]&&(o=!0)}}),a){var s=a.call(this,e,t,n);return i?s||o:s}return!i||o};L.__f=!0;var a=L.shouldComponentUpdate,o=L.componentWillUpdate;L.componentWillUpdate=function(e,t,n){if(this.__e){var r=a;a=void 0,i(e,t,n),a=r}o&&o.call(this,e,t,n)},L.shouldComponentUpdate=i}return r.__N||r.__}function B(e,t){var n=ye(ce++,3);!R.__s&&ke(n.__H,t)&&(n.__=e,n.u=t,L.__H.__h.push(n))}function xe(e,t){var n=ye(ce++,4);!R.__s&&ke(n.__H,t)&&(n.__=e,n.u=t,L.__h.push(n))}function V(e){return de=5,Se(function(){return{current:e}},[])}function Se(e,t){var n=ye(ce++,7);return ke(n.__H,t)&&(n.__=e(),n.__H=t,n.__h=e),n.__}function Ce(e,t){return de=8,Se(function(){return e},t)}function we(){for(var e;e=fe.shift();){var t=e.__H;if(e.__P&&t)try{t.__h.some(De),t.__h.some(Oe),t.__h=[]}catch(n){t.__h=[],R.__e(n,e.__v)}}}R.__b=function(e){L=null,pe&&pe(e)},R.__=function(e,t){e&&t.__k&&t.__k.__m&&(e.__m=t.__k.__m),ve&&ve(e,t)},R.__r=function(e){me&&me(e),ce=0;var t=(L=e.__c).__H;t&&(le===L?(t.__h=[],L.__h=[],t.__.some(function(e){e.__N&&(e.__=e.__N),e.u=e.__N=void 0})):(t.__h.some(De),t.__h.some(Oe),t.__h=[],ce=0)),le=L},R.diffed=function(e){he&&he(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(fe.push(t)!==1&&ue===R.requestAnimationFrame||((ue=R.requestAnimationFrame)||Ee)(we)),t.__H.__.some(function(e){e.u&&=(e.__H=e.u,void 0)})),le=L=null},R.__c=function(e,t){t.some(function(e){try{e.__h.some(De),e.__h=e.__h.filter(function(e){return!e.__||Oe(e)})}catch(n){t.some(function(e){e.__h&&=[]}),t=[],R.__e(n,e.__v)}}),ge&&ge(e,t)},R.unmount=function(e){_e&&_e(e);var t,n=e.__c;n&&n.__H&&(n.__H.__.some(function(e){try{De(e)}catch(e){t=e}}),n.__H=void 0,t&&R.__e(t,n.__v))};var Te=typeof requestAnimationFrame==`function`;function Ee(e){var t,n=function(){clearTimeout(r),Te&&cancelAnimationFrame(t),setTimeout(e)},r=setTimeout(n,35);Te&&(t=requestAnimationFrame(n))}function De(e){var t=L,n=e.__c;typeof n==`function`&&(e.__c=void 0,n()),L=t}function Oe(e){var t=L;e.__c=e.__(),L=t}function ke(e,t){return!e||e.length!==t.length||t.some(function(t,n){return t!==e[n]})}function Ae(e,t){return typeof t==`function`?t(e):t}var je=[`15m`,`1h`,`24h`],Me=[`success`,`other`,`reported_success`,`failed`,`denied`,`rejected`,`unknown`,`incomplete`,`reported_partial`];function Ne(e,t){if(!e||typeof e!=`object`||Array.isArray(e)||Object.keys(e).sort().join(`,`)!==[...t].sort().join(`,`))throw Error(`Invalid protocol summary`);return e}function Pe(e){return/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{9}Z$/.test(e)&&Number.isFinite(Date.parse(e))&&new Date(e).toISOString()===e.slice(0,23)+`Z`}function Fe(e){return BigInt(Date.parse(e))*1000000n+BigInt(e.slice(23,29))}function Ie(e){let t=e.filter_from,n=e.filter_until;return t===void 0&&n===void 0||t!==void 0&&n!==void 0&&Pe(t)&&Pe(n)&&te+BigInt(n[t]),0n)!==BigInt(n.total))throw Error(`Inconsistent activity total`)}}return e}function Re(e,t){let n=e===`mcp`?`mcp/invocations`:`${e}/traffic`,r=new URLSearchParams({filter_from:t.from,filter_until:t.until});return e===`http`&&r.set(`filter_type`,`request`),`#/${n}?${r}`}function ze(e){let t=Ne(e,[`items`,`next_cursor`,`total_count`,`offset`]);if(!Array.isArray(t.items)||t.items.length>1||t.offset!==0||typeof t.total_count!=`number`||!Number.isSafeInteger(t.total_count)||t.total_count1?typeof t.next_cursor!=`string`||!t.next_cursor:t.next_cursor!==null))throw Error(`Invalid inventory count`);return t.total_count}var Be={operation:[`read_discovery`,`read`,`push_discovery`,`probe`,`push`,`invalid`],admission:[`allowed`,`blocked`],transport:[`not_dispatched`,`unknown`,`prestart_failure`,`complete`,`incomplete`],report:[`not_a_push`,`unknown`,`reported_success`,`reported_failure`,`reported_partial`]};function Ve(e){return Ie(e)&&Object.entries(e).every(([e,t])=>e===`filter_from`||e===`filter_until`?!0:e===`filter_repository`?t.length>0&&new TextEncoder().encode(t).length<=256&&!/[\p{Cc}\p{Cf}]/u.test(t):e.startsWith(`filter_`)&&Be[e.slice(7)]?.includes(t)===!0)}function He(e){let t=JSON.parse(e),n=e=>{let t=!1,n=!1,r=0;for(let i of e)n?n=!1:t&&i===`\\`?n=!0:i===`"`?t=!t:!t&&i===`:`&&r++;return r};if(n(e)!==n(JSON.stringify(t)))throw Error(`Duplicate audit JSON member`);return t}var Ue={admin_credential:[`initialize`,`create`,`revoke`,`rotate`,`reset`],admin_session:[`sign_in`,`logout`],backup:[`create`,`delete`,`restore`],server:[`create`,`update`,`delete`,`reconcile`],server_credential:[`replace`,`disconnect`,`invalidate`],http_credential:[`create`,`update`,`rotate`,`delete`,`invalidate`],http_grant:[`create`,`update`,`delete`],http_default:[`update`],git_repository:[`create`,`update`,`delete`],git_grant:[`create`,`update`,`delete`],git_credential:[`create`,`update`,`rotate`,`delete`,`invalidate`],git_profile:[`update`],operation:[`request`,`activate`,`reload`,`retry`,`refresh_catalog`,`credential_replace`,`disable`,`delete`,`disconnect_credentials`,`schedule`,`start`,`finish`,`recover`],oauth:[`create`,`prepare`,`authorize`,`register`,`publish_registration`,`invalidate_registration`,`await_callback`,`begin_exchange`,`exchange`,`refresh`,`install`,`finish`,`cancel`,`expire`,`supersede`,`recover`,`revoke`],catalog:[`refresh`,`commit`,`publish`,`retire`,`invalidate`,`fence`,`withdraw`],keyring:[`setup`,`rotate`,`stage`,`write`,`commit`,`activate`,`fence`,`delete`,`cleanup`],principal:[`create`,`update`],agent_credential:[`issue`,`revoke`,`invalidate`],grant:[`create`,`update`,`delete`],grant_request:[`approve`,`reject`],storage:[`migrate`,`recover`,`verify`]},We=[`operator`,`system`,`offline_maintenance`],Ge=[`pending`,`succeeded`,`rejected`,`failed`,`unknown`],Ke=[`http_credential`,`http_grant`,`http_default`,`git_repository`,`git_grant`,`git_credential`,`installation`,`admin_credential`,`backup`,`server`,`operation`,`auth_flow`,`principal`,`agent_credential`,`grant`,`grant_request`,`descriptor`],qe=`configuration_invalid.resource_limit.connectivity.tls_failed.protocol_unsupported.protocol_invalid.authentication_rejected.credential_absent.keyring_absent.keyring_locked.keyring_interaction_required.keyring_unavailable.keyring_unsupported.oauth_rejected.oauth_expired.registration_expired.process_exited.output_limit.stop_unconfirmed.catalog_invalid.catalog_limit.catalog_stale.superseded.cancelled.interrupted.revocation_failed.revocation_unsupported.cleanup_pending`.split(`.`),Je=`malformed_request.invalid_json.invalid_cursor.invalid_idempotency_key.encrypted_backup_unsupported.ambiguous_credentials.invalid_oauth_state.authentication_required.credential_domain_mismatch.forbidden_origin.csrf_failed.not_found.method_not_allowed.conflict.idempotency_conflict.body_too_large.unsupported_media_type.misdirected_request.resource_limit.storage_unavailable.keyring_unavailable.shutting_down.invalid_server_configuration.invalid_operation.namespace_unavailable.operation_conflict.oauth_flow_active.oauth_callback_unavailable.stale_cursor.audit_history_replaced.history_unavailable.history_busy.stale_revision.precondition_required.downstream_unavailable.invalid_principal.invalid_grant.stale_grant_revision.grant_precondition_required.stale_principal_revision.principal_precondition_required.authorization_unavailable.invalid_grant_request.grant_request_conflict.stale_grant_request_revision.grant_request_precondition_required.admin_rotation_conflict.stale_admin_authority.admin_authority_precondition_required`.split(`.`),Ye=/^[0-7][0-9A-HJKMNP-TV-Z]{25}$/,Xe=[`actor_type`,`credential_id`,`category`,`action`,`target_type`,`target_id`,`target`,`outcome`,`correlation_id`,`from`,`until`];function Ze(e,t=``){switch(e){case`actor_type`:return We;case`category`:return Object.keys(Ue).sort();case`action`:return t===``?[...new Set(Object.values(Ue).flat())].sort():Ue[t];case`target_type`:return Ke;case`outcome`:return Ge;default:return}}function Qe(e){if(typeof e!=`string`||!/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{9}Z$/.test(e)||e<`1970`||!Number.isFinite(Date.parse(e))||new Date(e).toISOString()!==e.slice(0,23)+`Z`)throw Error(`Invalid audit timestamp`);return e}function $e(e){try{for(let[t,n]of Object.entries(e)){if(!t.startsWith(`filter_`)||!Xe.includes(t.slice(7))||n===``)return!1;let r=t.slice(7),i=Ze(r,e.filter_category);if(i!==void 0&&!i.includes(n)||[`credential_id`,`target_id`,`correlation_id`].includes(r)&&!Ye.test(n)||r===`target`&&(new TextEncoder().encode(n).length>256||/[\p{Cc}\p{Cf}\p{Cs}]/u.test(n)))return!1;(r===`from`||r===`until`)&&Qe(n)}let t=e.filter_from,n=e.filter_until;if(t===void 0!=(n===void 0))return!1;if(t!==void 0&&n!==void 0){let e=e=>BigInt(Date.parse(e.slice(0,19)+`Z`))*1000000n+BigInt(e.slice(20,29)),r=e(n)-e(t);if(r<=0n||r>366n*86400n*1000000000n)return!1}return!0}catch{return!1}}function et(e,t){if(typeof e!=`object`||!e||Array.isArray(e)||Object.keys(e).sort().join(`,`)!==[...t].sort().join(`,`))throw Error(`Invalid audit response`);return e}function tt(e,t){if(typeof e!=`string`||!t.test(e))throw Error(`Invalid audit response`);return e}function nt(e,t){if(typeof e!=`string`||!t.includes(e))throw Error(`Invalid audit response`);return e}function rt(e){let t=tt(e,/^[1-9][0-9]{0,18}$/);if(BigInt(t)>9223372036854775807n)throw Error(`Invalid audit sequence`);return t}function it(e){if(e===null)return null;let t=et(e,[`id`,`fingerprint`]);return{id:tt(t.id,Ye),fingerprint:tt(t.fingerprint,/^[0-9a-f]{16}$/)}}function at(e){let t=et(e,[`generation`,`oldest_retained`,`pruned`]);if(typeof t.pruned!=`boolean`||t.oldest_retained===null&&t.pruned)throw Error(`Invalid audit history`);let n=t.oldest_retained===null?null:et(t.oldest_retained,[`id`,`sequence`,`timestamp`]);return{generation:tt(t.generation,/^[0-9a-f]{64}$/),pruned:t.pruned,oldest_retained:n===null?null:{id:tt(n.id,Ye),sequence:rt(n.sequence),timestamp:Qe(n.timestamp)}}}function ot(e,t=!1){let n=et(e,[`id`,`sequence`,`timestamp`,`category`,`action`,`phase`,`outcome`,`actor`,`initiator`,`correlation_id`,`target`,...t?[`detail`]:[]]);if(new TextEncoder().encode(JSON.stringify(n)).byteLength>2048)throw Error(`Audit event too large`);let r=et(n.actor,[`type`,`credential`]),i=et(n.target,[`type`,`id`]),a=nt(r.type,We),o=it(r.credential),s=it(n.initiator);if(a===`operator`!=(o!==null)||s!==null&&a!==`system`)throw Error(`Invalid audit attribution`);let c=nt(n.category,Object.keys(Ue)),l=nt(n.phase,[`attempt`,`outcome`]),u=nt(n.outcome,Ge);if(l===`attempt`!=(u===`pending`))throw Error(`Invalid audit outcome`);let d={id:tt(n.id,Ye),sequence:rt(n.sequence),timestamp:Qe(n.timestamp),category:c,action:nt(n.action,Ue[c]),phase:l,outcome:u,actor:{type:a,credential:o},initiator:s,correlation_id:tt(n.correlation_id,Ye),target:{type:nt(i.type,Ke),id:tt(i.id,Ye)}};if(!t)return d;let f=et(n.detail,[`reason`,`problem`]),p=f.reason===null?null:nt(f.reason,qe),m=f.problem===null?null:nt(f.problem,Je);if(l===`attempt`&&(p!==null||m!==null))throw Error(`Invalid audit attempt`);return{...d,detail:{reason:p,problem:m}}}function st(e){return typeof e==`object`&&e&&`target_recognition`in e?[`target_recognition`]:[]}function ct(e,t){if(e===void 0)return;if(!Array.isArray(e)||e.length>100)throw Error(`Invalid target recognition`);let n=new Map(t.map(e=>[`${e.target.type}/${e.target.id}`,e.target])),r=new Map;for(let t of e){let e=et(t,[`target`,`display_name`]),i=et(e.target,[`type`,`id`]),a=`${nt(i.type,Ke)}/${tt(i.id,Ye)}`;if(!n.has(a)||r.has(a)||e.display_name!==null&&(typeof e.display_name!=`string`||!e.display_name||new TextEncoder().encode(e.display_name).length>256||/\p{Cc}/u.test(e.display_name)))throw Error(`Invalid target recognition`);r.set(a,e.display_name)}if(r.size!==n.size)throw Error(`Incomplete target recognition`);for(let e of t){let t=r.get(`${e.target.type}/${e.target.id}`);t&&(e.currentTargetName=t)}}function lt(e){let t=et(e,[`items`,`next_cursor`,`history`,...st(e)]);if(!Array.isArray(t.items)||t.items.length>100)throw Error(`Invalid audit page`);let n=t.items.map(e=>ot(e)),r=t.next_cursor===null?null:tt(t.next_cursor,/^[\x21-\x7e]{1,2048}$/),i=at(t.history);if(r!==null&&n.length===0)throw Error(`Empty audit continuation`);for(let e=0;e0&&BigInt(n[e].sequence)>=BigInt(n[e-1].sequence))throw Error(`Invalid audit ordering`);return ct(t.target_recognition,n),{items:n,next_cursor:r,history:i}}function ut(e){let t=et(e,[`event`,`history`,...st(e)]),n=ot(t.event,!0),r=at(t.history);if(r.oldest_retained===null||BigInt(n.sequence)e===`filter_from`||e===`filter_until`?!0:[`filter_tool`,`filter_principal`].includes(e)?new TextEncoder().encode(t).byteLength<=256&&!/[\p{Cc}\p{Cf}]/u.test(t):e===`filter_decision`||e===`filter_outcome`?dt[e===`filter_decision`?`decision`:`outcome`].some(([e])=>e===t):!1)}var pt=/^[0-7][0-9A-HJKMNP-TV-Z]{25}$/;function mt(e){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`HTTP policy data unavailable.`);return e}function ht(e,t){let n=mt(e);if(Object.keys(n).sort().join()!==t.sort().join())throw Error(`HTTP policy data unavailable.`);return n}function gt(e){return typeof e==`string`&&/^[1-9][0-9]{0,18}$/.test(e)&&(e.length<19||e<=`9223372036854775807`)}function _t(e){if(typeof e!=`string`)return;let t=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.(\d{9})Z$/.exec(e);if(t===null)return;let n=e.slice(0,19),r=Date.parse(n+`Z`);if(!(!Number.isFinite(r)||new Date(r).toISOString().slice(0,19)!==n))return n+(t[1]??``).padEnd(9,`0`)}function vt(e){let t=e.slice(4),n=t.lastIndexOf(`-`),r=n<0?[]:Array.from(t.slice(0,n),e=>e.charCodeAt(0)),i=n<0?0:n+1,a=128,o=0,s=72,c=2147483647;for(;i=t.length)return!1;let r=t.charCodeAt(i++),a=r>=97&&r<=122?r-97:r>=48&&r<=57?r-22:36;if(a>=36||a>Math.floor((c-o)/n))return!1;o+=a*n;let l=e<=s?1:e>=s+26?26:e-s;if(aMath.floor(c/(36-l)))return!1;n*=36-l}let l=r.length+1,u=Math.floor((o-e)/(e===0?700:2));u+=Math.floor(u/l);let d=0;for(;u>455;)u=Math.floor(u/35),d+=36;if(s=d+Math.floor(36*u/(u+38)),a+=Math.floor(o/l),a>1114111||a>=55296&&a<=57343)return!1;o%=l,r.splice(o,0,a),o++}if(!r.some(e=>e>=128))return!1;let l=String.fromCodePoint(...r),u=new TextEncoder().encode(l);if(u[0]===45||u.at(-1)===45||u.length>4&&u[2]===45&&u[3]===45)return!1;try{return new URL(`http://${l}/`).hostname===e}catch{return!1}}function yt(e){if(typeof e!=`string`)return!1;let t=e.startsWith(`*.`),n=t?e.slice(2):e;if(n.length===0||n.length>253)return!1;try{if(n.includes(`:`)){let e=new URL(`http://[${n}]/`).hostname;return!t&&e===`[${n}]`&&!/^\[::ffff:[0-9a-f]+:[0-9a-f]+\]$/.test(e)}return new URL(`http://${n}/`).hostname===n?/^\d+\.\d+\.\d+\.\d+$/.test(n)?!t:(!t||n.includes(`.`))&&n.split(`.`).every(e=>e.length<=63&&(e.slice(2,4)!==`--`||e.startsWith(`xn--`)&&vt(e))&&/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(e))&&!/^(?:\d+|0x[0-9a-f]*)$/.test(n.split(`.`).at(-1)):!1}catch{return!1}}function bt(e){let t=mt(e),n=String(t.type),r=n===`allow_requests`||n===`block_requests`,i=n===`allow_requests`||n===`allow_tunnel`;if(ht(t,[`version`,`type`,r?`request`:`destination`,...i?[`allow_private`]:[],...Object.hasOwn(t,`credential_id`)?[`credential_id`]:[]]),t.version!==1||![`block_destination`,`allow_tunnel`,`block_requests`,`allow_requests`].includes(n)||i&&typeof t.allow_private!=`boolean`||Object.hasOwn(t,`credential_id`)&&(n!==`allow_requests`||typeof t.credential_id!=`string`||!pt.test(t.credential_id))||new TextEncoder().encode(JSON.stringify(t)).length>16384)throw Error(`Invalid HTTP policy.`);let a=r?ht(t.request,[`origin`,`methods`,`path`]):void 0,o=ht(a?.origin??t.destination,r?[`scheme`,`host`,`port`]:[`host`,`port`]);if(!yt(o.host)||typeof o.port!=`number`||!Number.isInteger(o.port)||o.port<1||o.port>65535||r&&![`http`,`https`].includes(String(o.scheme))||t.credential_id!==void 0&&o.scheme!==`https`)throw Error(`Invalid destination.`);if(a!==void 0){let e=mt(a.methods);if(e.any===!0)ht(e,[`any`]);else if(ht(e,[`values`]),!Array.isArray(e.values)||e.values.length===0||e.values.length>32||e.values.some((e,t,n)=>typeof e!=`string`||e.length>32||e===`CONNECT`||!/^[!#$%&'*+.^_`|~0-9A-Z-]+$/.test(e)||t>0&&n[t-1]>=e))throw Error(`Invalid methods.`);let t=mt(a.path);if(t.kind===`any`)ht(t,[`kind`]);else if(ht(t,[`kind`,`value`]),![`exact`,`segment_prefix`].includes(String(t.kind))||typeof t.value!=`string`||t.value.length>4096||!t.value.startsWith(`/`)||!/^[A-Za-z0-9/._~@-]+$/.test(t.value)||t.value.includes(`//`)||t.value.split(`/`).some(e=>e===`.`||e===`..`)||t.kind===`segment_prefix`&&t.value!==`/`&&t.value.endsWith(`/`))throw Error(`Invalid path.`)}}function xt(e){let t=ht(e,[`id`,`principal_id`,`description`,`revision`,`policy`,`expires_at`,`state`,`created_at`,`updated_at`]);if(typeof t.id!=`string`||!pt.test(t.id)||typeof t.principal_id!=`string`||!pt.test(t.principal_id)||!gt(t.revision)||![`active`,`expired`].includes(String(t.state)))throw Error(`HTTP policy data unavailable.`);if(t.description!==null&&(typeof t.description!=`string`||new TextEncoder().encode(t.description).length<1||new TextEncoder().encode(t.description).length>256||/[\u0000-\u001f\u007f-\u009f\uD800-\uDFFF]/u.test(t.description)||/^\p{White_Space}|\p{White_Space}$/u.test(t.description)))throw Error(`Invalid description.`);bt(t.policy);let n=_t(t.created_at),r=_t(t.updated_at);if(n===void 0||r===void 0||rObject.hasOwn(i,e))]),i.version!==1||typeof i.allowed!=`boolean`)throw Error(`Invalid decision.`);for(let e of[`policy_revision`,`default_revision`])if(!Number.isSafeInteger(i[e])||Number(i[e])<1)throw Error(`Invalid revision.`);for(let e of[`principal`,...a.filter(e=>Object.hasOwn(i,e))]){let t=ht(i[e],[`id`,`revision`]);if(typeof t.id!=`string`||!pt.test(t.id)||!Number.isSafeInteger(t.revision)||Number(t.revision)<1)throw Error(`Invalid decision reference.`)}if(mt(i.principal).id!==t||!n!=(i.transport===`request`))throw Error(`Invalid preview identity.`);let o=e=>i[e]!==void 0;if(o(`credential`)!==o(`credential_grant`)||o(`conflict_credential`)!==o(`conflict_grant`)||o(`credential`)&&(i.transport!==`request`||!o(`grant`)))throw Error(`Invalid credential evidence.`);if(o(`conflict_credential`)&&(!o(`credential`)||mt(i.credential).id===mt(i.conflict_credential).id||String(mt(i.credential_grant).id)>=String(mt(i.conflict_grant).id)))throw Error(`Invalid conflict evidence.`);let s=!o(`private_grant`)&&!o(`credential`)&&!o(`conflict_credential`),c=!1;switch(i.reason){case`destination_block`:c=!i.allowed&&o(`grant`)&&s&&[`none`,`request`].includes(String(i.transport));break;case`request_block`:c=!i.allowed&&o(`grant`)&&s&&i.transport===`request`;break;case`intercept_required`:c=!i.allowed&&!o(`grant`)&&s&&i.transport===`intercept`;break;case`tunnel_allow`:c=i.allowed&&o(`grant`)&&!o(`credential`)&&i.transport===`tunnel`;break;case`request_allow`:c=i.allowed&&o(`grant`)&&!o(`conflict_credential`)&&i.transport===`request`;break;case`principal_default`:c=i.allowed===(r===`allow`)&&!o(`grant`)&&s&&i.transport===`request`;break;case`credential_conflict`:c=!i.allowed&&o(`grant`)&&o(`conflict_credential`)&&i.transport===`request`;break;case`credential_unavailable`:c=!i.allowed&&o(`grant`)&&o(`credential`)&&!o(`conflict_credential`)&&i.transport===`request`;break;case`address_forbidden`:case`private_permission_required`:c=!i.allowed&&!o(`conflict_credential`)&&(i.reason!==`private_permission_required`||!o(`private_grant`))&&(i.transport===`tunnel`?o(`grant`)&&!o(`credential`):i.transport===`request`&&(o(`grant`)||r===`allow`&&s))}if(!c)throw Error(`Invalid HTTP decision.`);return i}var wt={type:[`request`,`connect`,`invalid`],decision:[`allow`,`block`,`intercept`,`invalid`],outcome:[`not_dispatched`,`interception_selected`,`outcome_unknown`,`succeeded`,`prestart_failure`,`upstream_failure`]};function Tt(e){return Ie(e)&&Object.entries(e).every(([e,t])=>{if(e===`filter_from`||e===`filter_until`)return!0;if(e===`filter_principal_id`||e===`filter_connect_id`)return pt.test(t);if(e===`filter_destination`||e===`filter_principal`)return new TextEncoder().encode(t).byteLength<=256&&!/[\p{Cc}\p{Cf}]/u.test(t);let n=wt[e.slice(7)];return e.startsWith(`filter_`)&&n!==void 0&&n.includes(t)})}function Et(e){if(typeof e!=`string`||!pt.test(e))throw Error(`Invalid HTTP traffic identity.`);return e}function Dt(e){if(typeof e!=`string`||_t(e)===void 0)throw Error(`Invalid HTTP traffic time.`);return e}function Ot(e,t=0){if(!Number.isSafeInteger(e)||Number(e)65535)throw Error(`Invalid HTTP traffic destination.`);if(n&&(t.scheme!==`http`&&t.scheme!==`https`||typeof t.method!=`string`||!/^[A-Z0-9!#$%&'*+.^_`|~-]{1,32}$/.test(t.method)||t.method===`CONNECT`))throw Error(`Invalid HTTP request evidence.`);return t}var Mt={headers:{invalid_headers:`Invalid headers`,trailers_unsupported:`Trailers are not supported`,upgrade_unsupported:`Protocol upgrades are not supported`,inner_proxy_authorization:`Proxy credentials inside CONNECT`},request_form:{connect_body:`CONNECT must not carry a body`,nested_connect:`Nested CONNECT is not supported`,origin_form_required:`Origin-form request required inside CONNECT`,absolute_http_required:`Absolute-form HTTP request required`},target:{invalid_request_target:`Request target failed validation`,invalid_connect_target:`CONNECT target failed validation`,invalid_target_syntax:`Invalid request target syntax`,target_too_long:`Request target exceeds byte limit`,forbidden_path:`Forbidden path construct`,authority_mismatch:`Request authority mismatch`}};function Nt(e){return e===void 0?`Rejection details unavailable`:Mt[e.stage]?.[e.reason]??`Rejection details unavailable`}function Pt(e){let t=ht(e,[`stage`,`reason`]);if(typeof t.stage!=`string`||typeof t.reason!=`string`||!Object.hasOwn(Mt,t.stage)||!Object.hasOwn(Mt[t.stage],t.reason))throw Error(`Invalid rejection evidence.`);return t}function Ft(e,t,n){let r=ht(e,[`id`,`host`,`port`]),i=jt({host:r.host,port:r.port});if(Et(r.id)===t||n!==null&&(n.scheme!==`https`||n.host!==i.host||n.port!==i.port))throw Error(`Invalid CONNECT context.`);return r}function It(e,t){let n=mt(e);return t.filter(e=>Object.hasOwn(n,e))}var Lt=[`exchange`,`upstream_read`,`downstream_write`,`downstream_flush`,`deadline`,`response_headers`,`complete`];function Rt(e,t){let n=ht(e,[`stage`,`condition`,...It(e,[`context`])]);if(kt(n.stage,Lt),kt(n.condition,[`clean`,`cancelled`,`timeout`,`failure`]),n.context!==void 0&&kt(n.context,[`cancelled`,`timeout`]),n.condition===`clean`?t!==`succeeded`||![`complete`,`response_headers`].includes(String(n.stage))||n.context!==void 0:t!==`outcome_unknown`||n.stage===`complete`)throw Error(`Inconsistent HTTP termination evidence.`);return n}function zt(e,t){return e===!1?`Missing terminal evidence`:t===void 0?`Termination details unavailable`:t.condition===`clean`?t.stage===`response_headers`?`Headers prepared (HEAD)`:`Clean HTTP transfer`:`Incomplete HTTP transfer`}function Bt(e){let t=ht(e,[`items`,`next_cursor`]);if(!Array.isArray(t.items)||t.items.length>100||t.next_cursor!==null&&(typeof t.next_cursor!=`string`||t.next_cursor.length>512||!/^[A-Za-z0-9_-]+$/.test(t.next_cursor)))throw Error(`Invalid HTTP traffic page.`);let n=new Set;return{items:t.items.map(e=>{let t=ht(e,[`id`,`admitted_at`,`principal_id`,`target`,`type`,`decision`,`outcome`,...It(e,[`rejection`,`connect`,`response_source`,`completion_recorded`,`termination`])]),r={id:Et(t.id),admitted_at:Dt(t.admitted_at),principal_id:Et(t.principal_id),target:jt(t.target),type:kt(t.type,wt.type),decision:kt(t.decision,wt.decision),outcome:kt(t.outcome,wt.outcome)};if(r.type===`invalid`?r.target!==null||r.decision!==`invalid`||r.outcome!==`not_dispatched`:r.target===null||r.decision===`invalid`||r.type===`request`!=(r.target.scheme!==void 0)||!Vt(r.decision,r.outcome)||r.type===`request`&&r.decision===`intercept`)throw Error(`Inconsistent HTTP summary.`);if(t.rejection!==void 0&&(r.rejection=Pt(t.rejection),r.type!==`invalid`))throw Error(`Invalid rejection class.`);if(t.connect!==void 0&&(r.connect=Ft(t.connect,r.id,r.target)),t.response_source!==void 0&&(r.response_source=kt(t.response_source,[`gateway`,`upstream`])),r.rejection!==void 0&&r.response_source!==`gateway`)throw Error(`Invalid rejection source.`);if(t.completion_recorded!==void 0){if(typeof t.completion_recorded!=`boolean`||t.completion_recorded&&r.decision!==`allow`)throw Error(`Invalid HTTP completion presence.`);r.completion_recorded=t.completion_recorded}if(t.termination!==void 0){if(r.type!==`request`||r.decision!==`allow`||r.completion_recorded!==!0)throw Error(`Invalid HTTP termination presence.`);r.termination=Rt(t.termination,r.outcome);let e=r.termination;if((e.stage===`exchange`?r.response_source!==`gateway`:r.response_source!==`upstream`)||e.stage===`response_headers`&&r.target?.method!==`HEAD`||e.stage===`complete`&&r.target?.method===`HEAD`)throw Error(`Invalid HTTP termination boundary.`)}if(n.has(r.id))throw Error(`Duplicate HTTP traffic record.`);return n.add(r.id),r}),nextCursor:t.next_cursor}}function Vt(e,t){return e===`intercept`?t===`interception_selected`||t===`not_dispatched`:e===`block`?t===`not_dispatched`:t!==`not_dispatched`&&t!==`interception_selected`}function Ht(e){return e.decision===`intercept`?`interception_selected`:e.outcome}function Ut(e,t){return e===`intercept`?`Interception selected`:t===`connect`&&e===`allow`?`Opaque tunnel allowed`:t===`connect`&&e===`block`?`CONNECT denied`:e[0].toUpperCase()+e.slice(1)}var Wt=`Inner requests are authorized separately. Selection does not prove CONNECT acceptance, TLS establishment, upstream dispatch, request completion or connection closure.`;function Gt(e){let t=ht(e,[`admission`,`completion`]),n=ht(t.admission,[`id`,`admitted_at`,`principal`,`agent_credential`,`credential_fingerprint`,`class`,`default`,`target`,`evaluated_at`,`decision`,`grants`,`material`,...It(t.admission,[`rejection`,`connect`])]);Et(n.id),Dt(n.admitted_at),Dt(n.evaluated_at);let r=At(n.principal);if(At(n.agent_credential),String(n.evaluated_at)4)throw Error(`Invalid HTTP evidence.`);let i=jt(n.target);if(n.rejection!==void 0&&(Pt(n.rejection),n.class!==`invalid_request`))throw Error(`Invalid rejection class.`);if(n.connect!==void 0&&Ft(n.connect,String(n.id),i),n.class===`invalid_request`){if(n.default!==``||i!==null||n.decision!==null||n.grants.length!==0||n.material!==null||t.completion!==null)throw Error(`Invalid unparsed evidence.`)}else{if(n.class!==`evaluated`||i===null||![`allow`,`block`].includes(String(n.default)))throw Error(`Invalid HTTP admission.`);let e=Ct(n.decision,r.id,i.scheme===void 0,n.default);if(At(e.principal).revision!==r.revision)throw Error(`Invalid principal revision.`);let a=new Map;for(let t of[`grant`,`private_grant`,`credential_grant`,`conflict_grant`])if(e[t]!==void 0){let n=At(e[t]);if(a.has(n.id)&&a.get(n.id)!==n.revision)throw Error(`Conflicting grant revisions.`);a.set(n.id,n.revision)}if(a.size!==n.grants.length)throw Error(`Invalid grant evidence.`);let o=``;for(let e of n.grants){let t=ht(e,[`reference`,`policy`]),n=At(t.reference);if(n.id<=o||a.get(n.id)!==n.revision)throw Error(`Invalid grant reference.`);o=n.id,bt(t.policy)}if(n.material!==null){let t=ht(n.material,[`credential`,`generation`]),r=At(t.credential),i=At(e.credential);if(!e.allowed||r.id!==i.id||r.revision!==i.revision||typeof t.generation!=`string`||!/^[1-9][0-9]{0,18}$/.test(t.generation))throw Error(`Invalid material evidence.`)}if(e.allowed&&e.credential!==void 0&&n.material===null)throw Error(`Missing material evidence.`);if(t.completion!==null){let r=mt(t.completion);if(ht(r,[`completed_at`,`outcome`,`bytes_sent`,`bytes_received`,`duration_ms`,...It(r,[`status`,`response_source`,`gateway_status`,`termination`])]),!e.allowed||Dt(r.completed_at)599||e.transport!==`request`))throw Error(`Invalid HTTP status.`);if(r.response_source!==void 0&&kt(r.response_source,[`gateway`,`upstream`]),r.gateway_status!==void 0&&(r.response_source!==`gateway`||Ot(r.gateway_status,400)>599))throw Error(`Invalid Gateway response.`);if(r.response_source===`gateway`&&(r.gateway_status===void 0||r.status!==void 0))throw Error(`Invalid response source.`);if(r.response_source===`upstream`&&r.status===void 0)throw Error(`Missing upstream status.`);if(r.outcome===`prestart_failure`&&(r.status!==void 0||r.bytes_sent!==0||r.bytes_received!==0))throw Error(`Invalid prestart evidence.`)}}return{admission:n,completion:t.completion===null?null:mt(t.completion)}}function Kt(e){if(e===null)return`Not parsed`;let t=e.host.includes(`:`)?`[${e.host}]`:e.host;return e.scheme===void 0?`CONNECT ${t}:${e.port}`:`${e.method} ${e.scheme}://${t}:${e.port}`}var qt={overview:`overview`,servers:`mcp/servers`,catalog:`mcp/tools`,principals:`agents`,"git-routing":`git/routing`,"git-repositories":`git/repositories`,"git-grants":`git/grants`,"git-credentials":`git/credentials`,"git-traffic":`git/traffic`,"http-credentials":`http/credentials`,"http-grants":`http/grants`,"http-traffic":`http/traffic`,grants:`mcp/grants`,requests:`mcp/access-requests`,invocations:`mcp/invocations`,audit:`audit-log`,system:`system`,"sign-in":`sign-in`},Jt=/^[0-7][0-9A-HJKMNP-TV-Z]{25}$/,Yt=new Set([`status`,`tools`,`operations`,`authentication`,`settings`]),Xt=new Set([`status`,`resource-limits`,`needs-attention`,`admin-credentials`,`backups`]);function Zt(e){return Jt.test(e)}function Qt(e){if(e===``)return{};let t=Object.create(null);for(let n of e.split(`&`)){if(n===``||n.indexOf(`=`)<=0)return;let e=n.indexOf(`=`);if(e!==n.lastIndexOf(`=`))return;let r,i;try{r=decodeURIComponent(n.slice(0,e)),i=decodeURIComponent(n.slice(e+1))}catch{return}if(i===``||Object.hasOwn(t,r)||Object.hasOwn(Object.prototype,r))return;t[r]=i}return t}function $t(e,t){return/^filter_[a-z][a-z0-9_-]*$/.test(e)&&new TextEncoder().encode(t).byteLength<=256&&!/[\p{Cc}\p{Cf}]/u.test(t)}function en(e,t){for(let[n,r]of Object.entries(e))if(!Object.hasOwn(t,n)||!t[n](r))return!1;return!0}function tn(e,t){let n=t===`principals`?[`filter_name`]:[`filter_identity`,`filter_principal`,`filter_target`,`filter_server`,`filter_scope`],r=t===`principals`?{filter_state:[`active`,`disabled`],filter_visibility:[`requestable`,`allowed-only`,`all`],filter_http_default:[`block`,`allow`],sort:[`name`,`id`,`state`,`visibility`]}:{filter_effect:[`allow`,`deny`],filter_state:[`active`,`expired`],sort:[`id`,`description`,`principal`,`target`,`server`,`scope`,`effect`,`state`]};return r.direction=[`ascending`,`descending`],e.direction!==void 0&&e.sort===void 0?!1:Object.entries(e).every(([e,t])=>n.includes(e)?$t(e,t):r[e]?.includes(t)===!0)}function nn(e,t){let n=t===`git-repositories`?[`name`,`destination`,`credential`]:t===`git-credentials`?[`name`,`origin`]:[`identity`,`repository`,`principal`],r={direction:[`ascending`,`descending`],sort:t===`git-repositories`?[`id`,`name`,`destination`,`credential`]:t===`git-credentials`?[`id`,`name`,`origin`,`status`]:[`id`,`description`,`repository`,`principal`,`state`]};return t===`git-credentials`&&(r.filter_status=[`configured`,`unavailable`]),t===`git-grants`&&(r.filter_state=[`active`,`expired`]),(e.direction===void 0||e.sort!==void 0)&&Object.entries(e).every(([e,t])=>n.some(t=>e===`filter_${t}`)?$t(e,t):r[e]?.includes(t)===!0)}function rn(e){let t={queue:[`all`],filter_state:[`pending`,`approved`,`rejected`,`cancelled`],filter_scope:[`tool`,`server`],sort:[`request`,`principal`,`target`,`state`,`submitted`],direction:[`ascending`,`descending`]};return e.direction!==void 0&&e.sort===void 0||e.queue!==`all`&&e.filter_state!==void 0?!1:Object.entries(e).every(([e,n])=>[`filter_request`,`filter_principal`,`filter_target`].includes(e)?$t(e,n):t[e]?.includes(n)===!0)}function an(e,t){let n=t===`servers`?[`filter_name`,`filter_namespace`]:t===`catalog`?[`filter_tool`,`filter_server`]:[`filter_tool`],r={direction:[`ascending`,`descending`],sort:t===`servers`?[`name`,`id`,`namespace`,`status`,`tools`]:t===`catalog`?[`tool`,`server`]:[`tool`,`status`,`last-seen`],filter_status:t===`servers`?[`Ready`,`Connecting`,`Authorization required`,`Authentication unavailable`,`Capacity saturated`,`Disabled`,`Deleted`,`Needs attention`]:t===`catalog`?[`available`,`issue`]:[`available`,`retired`]};return t===`descriptors`&&(r.tab=[`tools`]),e.direction!==void 0&&e.sort===void 0?!1:Object.entries(e).every(([e,t])=>n.includes(e)?$t(e,t)&&$t(e,t.normalize(`NFKC`).toLowerCase()):r[e]?.includes(t)===!0)}function on(e){let t={tab:[`operations`],sort:[`action`,`status`,`created`,`started`,`outcome`],direction:[`ascending`,`descending`],filter_action:[`activate`,`reload`,`retry`,`refresh_catalog`,`credential_replace`,`disable`,`delete`,`disconnect_credentials`],filter_status:[`scheduled`,`running`,`succeeded`,`failed`,`cancelled`,`superseded`,`interrupted`]};return(e.direction===void 0||e.sort!==void 0)&&Object.entries(e).every(([e,n])=>t[e]?.includes(n)===!0)}function sn(e,t,n){return{destination:e,segments:t,query:n}}function H(e){if(e.length<3||e.length>2048||!e.startsWith(`#/`))return;for(let t=0;t126)return}let t=e.indexOf(`?`);if(t!==-1&&t!==e.lastIndexOf(`?`))return;let n=e.slice(2,t===-1?void 0:t),r=n===`principals`||n.startsWith(`principals/`)?`agents${n.slice(10)}`:n;if(r.includes(`%`))return;let i=t===-1?``:e.slice(t+1);if(t!==-1&&i===``||r===``||r.endsWith(`/`)||r.split(`/`).some(e=>e===``))return;let a=Object.keys(qt).find(e=>r===qt[e]||r.startsWith(`${qt[e]}/`));if(a===void 0)return;let o=[a,...r.slice(qt[a].length).split(`/`).slice(1)],s=Qt(i);if(s===void 0)return;let c=Object.keys(s).length===0,[l,u,d,f]=o;if(o.length===1){if((l===`overview`||l===`sign-in`||l===`git-routing`)&&c||l===`catalog`&&an(s,`catalog`))return sn(l,o,s);if(l===`servers`&&an(s,`servers`))return sn(`servers`,o,s)}if(l===`servers`&&(o.length===2&&u===`new`&&c||o.length===2&&u!==void 0&&Zt(u)&&(s.tab===`tools`?an(s,`descriptors`):s.tab===`operations`?on(s):en(s,{tab:e=>Yt.has(e)}))||o.length===4&&u!==void 0&&Zt(u)&&f!==void 0&&Zt(f)&&c&&(d===`operations`||d===`auth-flows`||d===`descriptors`)))return sn(`servers`,o,s);if((l===`git-repositories`||l===`git-grants`||l===`git-credentials`||l===`git-traffic`)&&(l===`git-traffic`?Ve(s):u===`new`?c:nn(s,l))&&(o.length===1||o.length===2&&u!==void 0&&(Zt(u)||u===`new`&&l!==`git-traffic`)))return sn(l,o,s);if(l===`http-traffic`&&Tt(s)&&(o.length===1||o.length===2&&u!==void 0&&Zt(u)))return sn(`http-traffic`,o,s);if(l===`http-grants`&&(o.length===1&&(s.direction===void 0||s.sort!==void 0)&&en(s,{principal_id:Zt,filter_identity:e=>$t(`filter_identity`,e),filter_principal:e=>$t(`filter_principal`,e),filter_target:e=>$t(`filter_target`,e),filter_type:e=>[`block_destination`,`allow_tunnel`,`block_requests`,`allow_requests`].includes(e),filter_state:e=>[`active`,`expired`].includes(e),sort:e=>[`id`,`description`,`principal`,`target`,`effect`,`state`].includes(e),direction:e=>[`ascending`,`descending`].includes(e)})||o.length===2&&u!==void 0&&(u===`new`||u===`test-access`||Zt(u))&&c))return sn(`http-grants`,o,s);if(l===`http-credentials`&&(s.direction===void 0||s.sort!==void 0)&&(u===`new`?c:en(s,{filter_name:e=>$t(`filter_name`,e),filter_boundary:e=>$t(`filter_boundary`,e),filter_recipe:e=>$t(`filter_recipe`,e),filter_status:e=>[`configured`,`unavailable`].includes(e),sort:e=>[`name`,`boundary`,`recipe`,`status`].includes(e),direction:e=>[`ascending`,`descending`].includes(e)}))&&(o.length===1||o.length===2&&u!==void 0&&(u===`new`||Zt(u))))return sn(`http-credentials`,o,s);if(l===`principals`){if(o.length===1&&tn(s,`principals`))return s.sort===`visibility`&&(s.sort=`name`,s.direction=`ascending`),sn(`principals`,o,s);if(o.length===2&&u===`new`&&c||o.length===2&&u!==void 0&&Zt(u)&&c)return sn(`principals`,o,s)}if(l===`grants`&&(o.length===1&&tn(s,`grants`)||o.length===2&&u===`new`&&en(s,{principal_id:Zt,server_id:Zt})||o.length===2&&u!==void 0&&Zt(u)&&c))return sn(`grants`,o,s);if(l===`requests`&&(o.length===1&&rn(s)||o.length===2&&u!==void 0&&Zt(u)&&c))return sn(`requests`,o,s);if(l===`audit`){let e=Object.fromEntries(Object.entries(s).filter(([e])=>![`filter_from`,`filter_until`,`filter_credential_id`,`filter_target_id`].includes(e)));if(s.filter_target_id&&!e.filter_target&&(e.filter_target=s.filter_target_id),o.length===1&&$e(s)||o.length===2&&u!==void 0&&Zt(u)&&$e(s))return sn(`audit`,o,e)}if(l===`invocations`&&(o.length===1&&ft(s)||o.length===2&&u!==void 0&&Zt(u)&&ft(s)))return sn(`invocations`,o,s);if(l===`system`&&(o.length===1&&en(s,{tab:e=>Xt.has(e)})||o.length===3&&(u===`backups`||u===`admin-credentials`)&&o[2]===`new`&&c))return sn(`system`,o,s)}var cn={"grants/new":[`principal_id`,`server_id`],servers:[`sort`,`direction`],catalog:[`sort`,`direction`],principals:[`sort`,`direction`],grants:[`sort`,`direction`],"http-grants":[`principal_id`,`sort`,`direction`],"http-credentials":[`sort`,`direction`],"git-repositories":[`sort`,`direction`],"git-credentials":[`sort`,`direction`],"git-grants":[`sort`,`direction`],requests:[`queue`,`sort`,`direction`]};function ln(e){let t=e.segments.join(`/`),n={...e.query};t.startsWith(`servers/`)&&n.tab===`status`&&delete n.tab,t===`system`&&n.tab===`status`&&delete n.tab;let r=cn[t]??([`http-credentials`,`git-repositories`,`git-credentials`,`git-grants`].includes(e.destination)?cn[e.destination]:void 0)??(n.tab===`tools`||n.tab===`operations`?[`tab`,`sort`,`direction`]:Object.hasOwn(n,`tab`)?[`tab`]:[]),i=[...r,...Object.keys(n).filter(e=>e.startsWith(`filter_`)&&!r.includes(e)).sort()].filter(e=>Object.hasOwn(n,e)).map(e=>`${encodeURIComponent(e)}=${encodeURIComponent(n[e])}`);return`#/${[qt[e.destination],...e.segments.slice(1)].join(`/`)}${i.length===0?``:`?${i.join(`&`)}`}`}function un(e,t){let n=H(e);if(n!==void 0)return{location:n,canonicalFragment:ln(n),invalid:!1};let r=t?`#/overview`:`#/sign-in`,i=H(r);if(i===void 0)throw Error(`fixed location is invalid`);return{location:i,canonicalFragment:r,invalid:!0}}function dn(e){let t=e?`#/overview`:`#/sign-in`;window.history.replaceState(null,``,t)}function fn(e){let t=un(window.location.hash,e);return window.location.hash!==t.canonicalFragment&&window.history.replaceState(null,``,t.canonicalFragment),t}var pn=0;Array.isArray;function U(e,n,r,i,a,o){n||={};var s,c,l=n;if(`ref`in l)for(c in l={},n)c==`ref`?s=n[c]:l[c]=n[c];var u={type:e,props:l,key:r,ref:s,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--pn,__i:-1,__u:0,__source:a,__self:o};if(typeof e==`function`&&(s=e.defaultProps))for(c in s)l[c]===void 0&&(l[c]=s[c]);return t.vnode&&t.vnode(u),u}function mn(e,t){let n=V(t);n.current=t,B(()=>{let t=setTimeout(()=>n.current(e),300);return()=>clearTimeout(t)},[e])}function hn({count:e,singular:t,plural:n,matching:r,stale:i}){return U(`output`,{class:`table-filter-summary`,"aria-live":`polite`,children:[e,` `,r?`matching `:``,e===1?t:n,` loaded`,i?` (stale)`:``]})}function gn(e){return/\p{Cc}/u.test(e)}function W(e){return e.replaceAll(`_`,` `).replaceAll(`-`,` `).replace(/^./,e=>e.toLocaleUpperCase())}function _n(e){switch(e.code){case`invalid_principal`:return`The agent is invalid.`;case`stale_principal_revision`:return`The agent revision is stale.`;case`principal_precondition_required`:return`The current agent revision is required.`;default:return e.title}}function G({state:e,children:t,testID:n}){return U(`span`,{class:`status-label ${e}`,"data-state":e,"data-testid":n,children:t})}function vn({value:e,current:t=!0}){return U(G,{state:t?e===void 0||[`idle`,`disabled`,`inactive`,`not_required`,`retired`,`deleted`].includes(e)?`neutral`:[`ready`,`active`,`current`,`succeeded`].includes(e)?`current`:[`starting`,`activating`,`refreshing`,`running`,`scheduled`].includes(e)?`loading`:e===`failed`||e===`faulted`?`error`:`warning`:`stale`,children:e===void 0?`Not reported`:e.charAt(0).toUpperCase()+e.slice(1).replaceAll(`_`,` `)})}function K({state:e,title:t,children:n}){let r=e===`error`||e===`unavailable`;return U(`section`,{class:`state-notice ${e}`,role:r?`alert`:`status`,"aria-live":r?`assertive`:`polite`,"aria-atomic":`true`,children:[U(G,{state:e,children:t}),n!==void 0&&U(`div`,{class:`state-detail`,children:n})]})}function yn({value:e,label:t=`JSON value`}){let n;try{n=JSON.stringify(e,null,2)??`null`}catch{n=`Unable to display this JSON value.`}return U(`pre`,{class:`inert-json`,"aria-label":t,tabindex:0,children:U(`code`,{children:n})})}function bn({caption:e,children:t,layout:n=`comparison`}){return U(`div`,{class:`table-region table-${n}`,role:`region`,"aria-label":e,tabindex:0,onFocusCapture:e=>{if(e.target instanceof HTMLElement&&e.target!==e.currentTarget&&e.currentTarget.querySelector(`.column-actions`)!==null){let t=e.currentTarget.querySelector(`th.column-actions`),n=t!==null&&getComputedStyle(t).position===`sticky`?t.getBoundingClientRect().width:0;e.currentTarget.style.scrollPaddingRight=`${n}px`,e.target.scrollIntoView({block:`nearest`,inline:`nearest`})}},children:U(`table`,{children:[U(`caption`,{class:`visually-hidden`,children:e}),t]})})}function xn({label:e,beforeLabel:t,afterLabel:n,rows:r,fullWidth:i=!1}){return U(`dl`,{class:`detail-comparison${i?` comparison-wide`:``}`,"aria-label":e,children:r.map(e=>U(`div`,{class:`comparison-field`,children:[U(`dt`,{children:[e.label,e.changed&&U(`span`,{class:`comparison-change`,children:`Changed`})]}),U(`dd`,{children:[U(`div`,{class:`comparison-value`,children:[U(`span`,{class:`comparison-label`,children:t}),U(`div`,{children:e.before})]}),U(`div`,{class:`comparison-value`,children:[U(`span`,{class:`comparison-label`,children:n}),U(`div`,{children:e.after})]})]})]},e.label))})}function q({primary:e,secondary:t}){return U(S,{children:[U(`span`,{class:`table-primary`,children:e}),t!==void 0&&U(`span`,{class:`table-identifier`,children:t})]})}function Sn(e){return e.normalize(`NFKD`).replace(/\p{M}/gu,``).toLocaleLowerCase()}function Cn(e,t){if(Math.abs(e.length-t.length)>1)return!1;if(e===t)return!0;let n=0,r=0,i=0;for(;n1)return!1;e.length===t.length&&e[n]===t[r+1]&&e[n+1]===t[r]?(n+=2,r+=2):e.length>t.length?n+=1:(t.length>e.length||(n+=1),r+=1)}return i+(e.length-n)+(t.length-r)<=1}function wn(e,t){let n=Sn(e);return Sn(t).split(/\s+/u).filter(Boolean).every(e=>n.includes(e)?!0:e.length<4||/\d/u.test(e)?!1:n.split(/[^\p{L}\p{N}]+/u).filter(Boolean).some(t=>Cn(t,e)))}function Tn(e){let t=H(window.location.hash);return t===void 0?{}:Object.fromEntries(e.flatMap(e=>{let n=t.query[`filter_${e.key}`];return n===void 0?[]:[[e.key,n]]}))}function En(e,t){let n=H(window.location.hash);if(n===void 0)return;let r={...n.query},i=`filter_${e}`;t.trim()===``?delete r[i]:r[i]=t;let a=ln({...n,query:r});H(a)!==void 0&&window.history.replaceState(null,``,a)}function Dn({caption:e,items:t,columns:n,rowKey:r,rowTestID:i,filters:a=[],initialSort:o,emptyTitle:s=`No results`,hasMore:c=!1,loadingMore:l=!1,onLoadMore:u,loadMoreLabel:d=`Load more`,itemNames:f={singular:`item`,plural:`items`},remote:p,rowHeaderKey:m,layout:h=`resource`,additionalSorts:g=[],loadedSubset:_=!1,historySummary:v=!1,historyMatching:y=!1,localStale:b=!1,localLoading:x=!1,summaryExtra:S}){let[C,w]=z(()=>Tn(a)),[T,E]=z(o),D=p?.filterValues??C,O=p===void 0?T:p.sort;B(()=>{if(p!==void 0)return;let e=()=>w(Tn(a));return window.addEventListener(`hashchange`,e),()=>window.removeEventListener(`hashchange`,e)},[a,p]);let k=[...n.filter(e=>e.sortValue!==void 0),...g],A=Se(()=>{if(p!==void 0)return t;let e=t.filter(e=>a.every(t=>{let n=D[t.key]?.trim()??``;if(n===``)return!0;let r=t.value(e);return t.type===`text`?(t.literalValues?.(e).some(e=>e.includes(n))??!1)||wn(r,n):r===n}));if(O===void 0)return e;let n=k.find(e=>e.key===O.key);return n?.sortValue===void 0?e:e.sort((e,t)=>{let r=n.sortValue(e),i=n.sortValue(t),a=typeof r==`number`&&typeof i==`number`?r-i:String(r).localeCompare(String(i));return O.direction===`ascending`?a:-a})},[n,g,D,a,t,O,p]),j=e=>{if(p!==void 0){p.changeSort(e);return}E(t=>({key:e,direction:t?.key===e&&t.direction===`ascending`?`descending`:`ascending`}))},M=Object.values(D).some(e=>e.trim()!==``)||(p?.contextFilters.length??0)>0,N=t=>p!==void 0&&U(`div`,{class:`collection-pagination`,children:[U(`nav`,{class:`inline-actions`,"aria-label":`${e} pagination ${t}`,children:[U(`button`,{type:`button`,disabled:!p.hasPrevious,onClick:p.previous,children:`Previous`}),U(`button`,{type:`button`,disabled:!p.hasNext,onClick:p.next,children:`Next`})]}),U(`span`,{class:`table-filter-summary`,role:t===`top`?`status`:void 0,"aria-live":t===`top`?`polite`:void 0,children:p.status===`loading`?`Loading…`:p.status===`error`?`Unavailable`:p.totalCount===void 0?A.length===0?`No ${M?`matching `:``}${f.plural}`:`Showing ${A.length} ${M?`matching `:``}${A.length===1?f.singular:f.plural}`:p.totalCount===0?`No ${M?`matching `:``}${f.plural}`:`Showing ${p.offset+1}–${p.offset+A.length} of ${p.totalCount} ${M?`matching `:``}${p.totalCount===1?f.singular:f.plural}`})]});return U(`div`,{class:`collection-table`,"aria-busy":p?.status===`loading`?`true`:void 0,children:[a.length>0&&U(`div`,{class:p===void 0?`table-filters`:`table-filters collection-query-filters`,role:`group`,"aria-label":`${e} filters`,children:[U(`span`,{class:`table-filters-label`,children:`Filter:`}),a.map(e=>e.type===`text`?U(`input`,{type:`search`,"aria-label":e.label,placeholder:e.placeholder??e.label,value:D[e.key]??``,onInput:t=>{let n=t.currentTarget.value;if(p!==void 0){p.changeFilter(e.key,n);return}En(e.key,n),w(t=>({...t,[e.key]:n}))}},e.key):U(`select`,{"aria-label":e.label,value:D[e.key]??``,onChange:t=>{let n=t.currentTarget.value;if(p!==void 0){p.changeFilter(e.key,n);return}En(e.key,n),w(t=>({...t,[e.key]:n}))},children:[U(`option`,{value:``,children:[e.label,`: any`]}),e.options.map(e=>U(`option`,{value:e.value,children:e.label},e.value))]},e.key)),U(`button`,{class:`text-button`,type:`button`,disabled:!M,onClick:()=>{if(p!==void 0){p.resetFilters();return}for(let e of a)En(e.key,``);w({})},children:`Reset`}),p===void 0&&!v&&U(`output`,{class:`table-filter-summary`,"aria-live":`polite`,children:[`Showing `,A.length,` of `,t.length,c?` loaded`:``,b?` (last-known)`:``]})]}),p!==void 0&&p.contextFilters.length>0&&U(`div`,{class:`table-filters`,role:`group`,"aria-label":`${e} context filters`,children:p.contextFilters.map(e=>U(`button`,{type:`button`,onClick:()=>p.clearContextFilter(e.key),children:[e.label,`:`,` `,U(`span`,{class:`technical-value`,children:e.value}),` ×`]}))}),p?.stale&&U(K,{state:`stale`,title:`Last-known results`,children:U(`p`,{children:`These rows are stale. The current range is unavailable until Refresh succeeds.`})}),p?.notice!==void 0&&U(K,{state:`warning`,title:p.notice}),p?.error!==void 0&&U(K,{state:`error`,title:p.error}),N(`top`),_&&U(`p`,{class:`table-query-scope`,children:`Filters and sorting apply to loaded rows only.`}),k.length>0&&U(`div`,{class:`table-sort-controls`,role:`group`,"aria-label":`${e} sorting`,children:[U(`label`,{children:[`Sort by`,` `,U(`select`,{"aria-label":`${e} sort column`,value:O?.key??``,onChange:e=>j(e.currentTarget.value),children:[(O===void 0||!n.some(e=>e.key===O.key&&e.sortValue!==void 0))&&U(`option`,{value:O?.key??``,disabled:!0,children:O===void 0?`Default order`:`Custom order (from URL)`}),n.filter(e=>e.sortValue!==void 0).map(e=>U(`option`,{value:e.key,children:e.label},e.key))]})]}),U(`button`,{type:`button`,disabled:O===void 0,onClick:()=>O!==void 0&&j(O.key),"aria-label":`${e} sort direction`,children:O?.direction===`descending`?`Descending ↓`:`Ascending ↑`})]}),U(bn,{caption:e,layout:h,children:[U(`colgroup`,{children:n.map(e=>U(`col`,{class:`column-${e.role}`},e.key))}),U(`thead`,{children:U(`tr`,{children:n.map(e=>U(`th`,{scope:`col`,class:`column-${e.role} ${e.class??``}`,"aria-sort":O?.key===e.key?O.direction:void 0,children:[e.sortValue!==void 0&&U(`span`,{class:`table-narrow-heading`,children:e.label}),e.sortValue===void 0?e.label:U(`button`,{class:`sort-button`,type:`button`,onClick:()=>j(e.key),children:[U(`span`,{children:e.label}),U(`span`,{class:`sort-indicator`,"aria-hidden":`true`,children:O?.key===e.key?O.direction===`ascending`?`↑`:`↓`:`↕`})]})]},e.key))})}),U(`tbody`,{children:A.map(e=>U(`tr`,{"data-testid":i,children:n.map(t=>t.key===m?U(`th`,{scope:`row`,class:`column-${t.role} ${t.class??``}`,"data-label":t.label,children:t.render(e)},t.key):U(`td`,{class:`column-${t.role} ${t.class??``}`,"data-label":t.label,children:t.render(e)},t.key))},r(e)))})]}),p?.status===`loading`&&A.length===0&&U(K,{state:`loading`,title:`Loading ${e.toLowerCase()}`}),A.length===0&&!b&&!x&&(p===void 0||p.status===`current`)&&U(K,{state:`empty`,title:p!==void 0&&M?`No matching ${f.plural}`:s}),N(`bottom`),(v||S!==void 0||c&&u!==void 0)&&U(`div`,{class:`collection-pagination`,children:[c&&u!==void 0&&U(`button`,{type:`button`,disabled:l,onClick:u,children:l?`Loading…`:d}),v&&!x&&U(hn,{count:A.length,singular:f.singular,plural:f.plural,matching:M||y,stale:b}),S]})]})}function On({attributes:e,checked:t,disabled:n=!1,enabledLabel:r=`Enabled`,disabledLabel:i=`Disabled`,showState:a=!0,testID:o,onChange:s}){return U(`span`,{class:`binary-toggle`,children:[U(`input`,{...e,"data-testid":o,type:`checkbox`,role:`switch`,checked:t,disabled:n,onChange:e=>s(e.currentTarget.checked)}),U(`span`,{"aria-hidden":`true`,class:`binary-toggle-track`}),a&&U(`span`,{class:`binary-toggle-state`,children:t?r:i})]})}function kn({attributes:e,label:t,value:n,options:r,disabled:i=!1,placeholder:a,testID:o,onChange:s}){let c=V(null),l=V(null),[u,d]=z(!1),[f,p]=z(),m=r.filter(e=>e.value.toLowerCase().includes(n.toLowerCase())),h=m.findIndex(e=>e.value===f),g=u&&!i,_=`${e.id}-options`,v=()=>{d(!1),p(void 0)},y=e=>{s(e),c.current?.focus(),v()};return xe(()=>{g&&h>=0&&l.current?.children[h]?.scrollIntoView({block:`nearest`})},[g,h,f]),U(`div`,{class:`suggestion-input`,onFocusOut:e=>{e.currentTarget.contains(e.relatedTarget)||v()},children:[U(`input`,{...e,ref:c,"data-testid":o,role:`combobox`,"aria-autocomplete":`list`,"aria-expanded":g,"aria-controls":g?_:void 0,"aria-activedescendant":g&&h>=0?`${_}-${h}`:void 0,autocomplete:`off`,value:n,placeholder:a,disabled:i,onFocus:()=>d(!0),onInput:e=>{s(e.currentTarget.value),p(void 0),d(!0)},onKeyDown:e=>{if(!e.isComposing){if(e.key===`ArrowDown`||e.key===`ArrowUp`){e.preventDefault(),d(!0);let t=!g||h<0?e.key===`ArrowDown`?0:m.length-1:(h+(e.key===`ArrowDown`?1:-1)+m.length)%m.length;p(m[t]?.value)}else g&&e.key===`Enter`?(e.preventDefault(),h>=0?y(m[h].value):v()):g&&e.key===`Escape`?(e.preventDefault(),e.stopPropagation(),v()):e.key===`Tab`&&v()}}}),U(`button`,{class:`suggestion-toggle`,type:`button`,tabindex:-1,"aria-label":`Show suggestions for ${t}`,"aria-expanded":g,"aria-controls":g?_:void 0,disabled:i,onMouseDown:e=>e.preventDefault(),onClick:()=>{c.current?.focus(),p(void 0),d(!g)},children:U(`span`,{"aria-hidden":`true`,children:`▾`})}),g&&U(`div`,{class:`suggestion-panel`,"data-empty":m.length===0,children:[U(`ul`,{id:_,ref:l,role:`listbox`,"aria-label":`${t} suggestions`,children:m.map((e,t)=>U(`li`,{id:`${_}-${t}`,role:`option`,"aria-selected":t===h,"data-value":e.value,onMouseDown:e=>e.preventDefault(),onClick:()=>y(e.value),children:[U(`span`,{children:e.value}),e.detail&&U(`small`,{children:e.detail})]},e.value))}),m.length===0&&U(`p`,{children:`No suggestions. Enter a custom value.`})]})]})}function J({id:e,label:t,hint:n,error:r,optional:i=!1,required:a=!1,children:o}){let s=[n===void 0?void 0:`${e}-hint`,r===void 0?void 0:`${e}-error`].filter(e=>e!==void 0).join(` `),c={id:e};return a&&(c.required=!0),s!==``&&(c[`aria-describedby`]=s),r!==void 0&&(c[`aria-invalid`]=!0),U(`div`,{class:`form-field`,children:[U(`label`,{for:e,children:[t,i&&U(`span`,{class:`optional-label`,children:` (optional)`})]}),n!==void 0&&U(`span`,{class:`field-hint`,id:`${e}-hint`,children:n}),o(c),r!==void 0&&U(`span`,{class:`field-error`,id:`${e}-error`,role:`alert`,children:r})]})}function An({id:e,open:t,title:n,consequence:r,expected:i,value:a,confirmLabel:o,returnFocus:s,onValue:c,onConfirm:l,onCancel:u}){let d=V(null);return B(()=>{let e=d.current;e!==null&&(t&&!e.open&&e.showModal(),!t&&e.open&&e.close())},[t]),U(`dialog`,{ref:d,class:`confirmation-dialog`,"aria-labelledby":`${e}-title`,"aria-describedby":`${e}-consequence`,onCancel:e=>{e.preventDefault(),u()},onClose:()=>s.current?.focus(),children:U(`form`,{method:`dialog`,children:[U(`h2`,{id:`${e}-title`,children:n}),U(`div`,{id:`${e}-consequence`,class:`dialog-consequence`,children:r}),U(J,{id:`${e}-value`,label:`Type ${i} to confirm`,hint:`The immutable namespace must match exactly.`,children:t=>U(`input`,{...t,"data-testid":`${e}-value`,value:a,autoComplete:`off`,spellcheck:!1,onInput:e=>c(e.currentTarget.value)})}),U(`div`,{class:`dialog-actions`,children:[U(`button`,{type:`button`,"data-testid":`${e}-cancel`,onClick:u,children:`Cancel`}),U(`button`,{class:`danger-action`,type:`button`,"data-testid":`${e}-submit`,disabled:a!==i,onClick:l,children:o})]})]})})}function jn({id:e,open:t,title:n,consequence:r,confirmLabel:i,destructive:a=!1,returnFocus:o,onConfirm:s,onCancel:c}){let l=V(null);return B(()=>{let e=l.current;e!==null&&(t&&!e.open&&e.showModal(),!t&&e.open&&e.close())},[t]),U(`dialog`,{ref:l,class:`confirmation-dialog`,"aria-labelledby":`${e}-title`,"aria-describedby":`${e}-consequence`,onCancel:e=>{e.preventDefault(),c()},onClose:()=>{o.current?.focus()},children:U(`form`,{method:`dialog`,children:[U(`h2`,{id:`${e}-title`,children:n}),U(`div`,{id:`${e}-consequence`,class:`dialog-consequence`,children:r}),U(`div`,{class:`dialog-actions`,children:[U(`button`,{type:`button`,"data-testid":`${e}-cancel`,onClick:c,children:`Cancel`}),U(`button`,{class:a?`danger-action`:`primary-action`,type:`button`,"data-testid":`${e}-submit`,onClick:()=>{l.current?.close(),s()},children:i})]})]})})}var Mn=`application/json`,Nn=`application/problem+json`;function Pn(e,t){return Object.keys(e).sort().join(`,`)===[...t].sort().join(`,`)}function Fn(e){return typeof e==`string`&&e.length<=64&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/.test(e)&&!Number.isNaN(Date.parse(e))}function In(e){if(!(typeof e!=`object`||!e||Array.isArray(e)||!Pn(e,[`absolute_expires_at`,`csrf_token`,`idle_expires_at`])||!(`csrf_token`in e)||typeof e.csrf_token!=`string`||!/^[A-Za-z0-9_-]{43}$/.test(e.csrf_token)||!(`idle_expires_at`in e)||!Fn(e.idle_expires_at)||!(`absolute_expires_at`in e)||!Fn(e.absolute_expires_at)||Date.parse(e.idle_expires_at)>Date.parse(e.absolute_expires_at)))return{csrfToken:e.csrf_token,idleExpiresAt:e.idle_expires_at,absoluteExpiresAt:e.absolute_expires_at}}var Ln=new Set(`configuration,namespace,display_name,enabled,transport,transport.kind,transport.executable,transport.arguments,transport.working_directory,transport.environment,transport.secret_environment,transport.url,transport.protocol_mode,transport.headers,transport.authentication,transport.authentication.mode,transport.authentication.trusted_origins,transport.authentication.request_offline_access,transport.authentication.callback_uri,transport.authentication.auth_server_metadata_url,transport.authentication.scopes,transport.authentication.registration,transport.authentication.registration.mode,transport.authentication.registration.issuer,transport.authentication.registration.client_id,transport.authentication.registration.token_endpoint_auth_method`.split(`,`)),Rn=new Set([`invalid`,`required`,`maximum`,`unique`,`disjoint`,`canonical_absolute_path`,`canonical_url`,`transport_policy`]);function zn(e){if(!(typeof e!=`object`||!e||Array.isArray(e)||!Pn(e,[`field`,`rule`])||!(`field`in e)||typeof e.field!=`string`||!Ln.has(e.field)||!(`rule`in e)||typeof e.rule!=`string`||!Rn.has(e.rule)))return{field:e.field,rule:e.rule}}function Bn(e){if(!(typeof e!=`object`||!e||Array.isArray(e)||!(`status`in e)||!Number.isInteger(e.status)||typeof e.status!=`number`||e.status<400||e.status>599||!(`code`in e)||typeof e.code!=`string`||!/^[a-z][a-z0-9_]{0,63}$/.test(e.code)||!(`title`in e)||typeof e.title!=`string`||e.title.length===0||e.title.length>256)){if(e.code===`invalid_server_configuration`){if(Pn(e,[`code`,`status`,`title`]))return{status:e.status,code:e.code,title:e.title};if(!Pn(e,[`code`,`context`,`status`,`title`]))return;let t=`context`in e?zn(e.context):void 0;return t===void 0?void 0:{status:e.status,code:e.code,title:e.title,context:t}}if(Pn(e,[`code`,`status`,`title`]))return{status:e.status,code:e.code,title:e.title}}}async function Vn(e){try{return await e.json()}catch{return}}function Hn(e){return e.headers.get(`Content-Type`)??``}var Un=class{request;lifecycle=`bootstrapping`;epoch=0;session;message;started=!1;recovery;listeners=new Set;clearProtectedState=new Set;controllers=new Set;timers=new Set;constructor(e=fetch){this.request=e.bind(globalThis)}snapshot(){return this.message===void 0?{lifecycle:this.lifecycle,epoch:this.epoch}:{lifecycle:this.lifecycle,epoch:this.epoch,message:this.message}}subscribe(e){return this.listeners.add(e),e(this.snapshot()),()=>this.listeners.delete(e)}registerProtectedState(e){return this.clearProtectedState.add(e),()=>this.clearProtectedState.delete(e)}start(){this.started||(this.started=!0,this.bootstrap(!1))}async exchange(e){if(this.lifecycle!==`signed_out`||e.length===0)return!1;this.message=void 0,this.emit();let t=e;try{let e=await this.request(`/api/v2/admin-sessions`,{method:`POST`,headers:{Authorization:`Bearer ${t}`,"Content-Type":`application/json`},body:`{}`,credentials:`same-origin`,redirect:`error`});if(t=``,e.status===201&&Hn(e)===Mn){let t=In(await Vn(e));if(t!==void 0)return this.authenticate(t),!0}else await this.readProblem(e);return this.message=`Sign-in failed. Check the credential and try again.`,this.emit(),!1}catch{return t=``,this.message=`Sign-in could not be completed.`,this.emit(),!1}finally{t=``,e=``}}async logout(){if(this.lifecycle!==`authenticated`||this.session===void 0)return;let e=this.session.csrfToken;this.advanceEpoch(`signed_out`);try{let t=await this.request(`/api/v2/admin-sessions/current`,{method:`DELETE`,headers:{"Content-Type":`application/json`,"X-CSRF-Token":e},body:`{}`,credentials:`same-origin`,redirect:`error`});t.status!==204&&(await this.readProblem(t),this.message=`The local session was cleared, but logout was not confirmed.`,this.emit())}catch{this.message=`The local session was cleared, but logout was not confirmed.`,this.emit()}}async runProtected(e){if(this.lifecycle!==`authenticated`||this.session===void 0)return;let t=this.epoch,n=new AbortController;this.controllers.add(n);let r=()=>this.lifecycle===`authenticated`&&this.epoch===t;try{let i=await e({epoch:t,csrfToken:this.session.csrfToken,signal:n.signal,isCurrent:r,sessionLost:async e=>e.status!==401&&(e.status!==403||await this.problemCode(e)!==`csrf_failed`)?!1:(await this.recoverAfterSessionLoss(t),!0)});return r()?i:void 0}catch(e){if(n.signal.aborted||!r())return;throw e}finally{this.controllers.delete(n)}}scheduleProtected(e,t){if(this.lifecycle!==`authenticated`)return()=>{};let n=this.epoch,r=setTimeout(()=>{this.timers.delete(r),this.lifecycle===`authenticated`&&this.epoch===n&&e()},t);return this.timers.add(r),()=>{clearTimeout(r),this.timers.delete(r)}}recoverAfterSessionLoss(e=this.epoch){if(this.recovery!==void 0)return this.recovery;if(e!==this.epoch)return Promise.resolve();this.advanceEpoch(`reauthenticating`);let t=this.bootstrap(!0).finally(()=>{this.recovery===t&&(this.recovery=void 0)});return this.recovery=t,t}async bootstrap(e){try{let t=await this.request(`/api/v2/admin-sessions/current`,{method:`POST`,headers:{"Content-Type":`application/json`},body:`{}`,credentials:`same-origin`,redirect:`error`});if(t.status===200&&Hn(t)===Mn){let e=In(await Vn(t));if(e!==void 0){this.authenticate(e);return}}else{let e=await this.readProblem(t);if(t.status===401&&e?.code===`authentication_required`){this.setSignedOut(void 0);return}}this.setSignedOut(e?`The session could not be recovered. Sign in again.`:`The session response was invalid. Sign in again.`)}catch{this.setSignedOut(`The session could not be restored. Sign in again.`)}}authenticate(e){this.advanceEpoch(`authenticated`),this.session=e,this.message=void 0,this.emit()}setSignedOut(e){this.session=void 0,this.lifecycle=`signed_out`,this.message=e,this.emit()}advanceEpoch(e){this.epoch+=1,this.lifecycle=e,this.session=void 0,this.message=void 0;for(let e of this.controllers)e.abort();this.controllers.clear();for(let e of this.timers)clearTimeout(e);this.timers.clear();for(let e of this.clearProtectedState)e();this.emit()}async readProblem(e){if(Hn(e)!==Nn)return;let t=Bn(await Vn(e));return t?.status===e.status?t:void 0}async problemCode(e){return(await this.readProblem(e))?.code}emit(){let e=this.snapshot();for(let t of this.listeners)t(e)}};function Wn({query:e}){return e.filter_from&&e.filter_until?U(`p`,{class:`history-window`,children:[`Admission window: `,U(Y,{value:e.filter_from,compact:!0}),` to`,` `,U(Y,{value:e.filter_until,compact:!0}),` (end exclusive)`]}):null}function Gn(e){let t=new Date(e);return Number.isFinite(t.getTime())?new Intl.DateTimeFormat(void 0,{dateStyle:`medium`,timeStyle:`medium`}).format(t):e}function Y({value:e,fallback:t=`—`,compact:n=!1}){if(e==null)return U(S,{children:t});let r=new Date(e);if(!Number.isFinite(r.getTime()))return U(`time`,{dateTime:e,children:e});if(n)return U(`time`,{dateTime:e,title:e,"aria-label":`${Gn(e)} (${e})`,children:new Intl.DateTimeFormat(void 0,{dateStyle:`short`,timeStyle:`short`}).format(r)});let i=new Intl.DateTimeFormat(void 0,{dateStyle:`medium`,timeStyle:`medium`}).formatToParts(r),a=i.findIndex(e=>e.type===`hour`||e.type===`dayPeriod`),o=i[a-1]?.type===`literal`?a-1:a;return U(`time`,{dateTime:e,title:e,class:`user-time`,children:[U(`span`,{class:`user-time-date`,children:i.slice(0,o).map(e=>e.value).join(``)}),U(`span`,{class:`user-time-separator`,children:i.slice(o,a).map(e=>e.value).join(``)}),U(`span`,{class:`user-time-clock`,children:i.slice(a).map(e=>e.value).join(``)})]})}var Kn=class extends Error{},qn=(e=``)=>({key:e,items:[],next:null,loaded:!1,loading:!1,error:!1}),Jn=class{value=qn();cursor=null;listeners=new Set;views;id;constructor(e,t,n,r,i){this.views=t,this.id=n,t.registerPanel({id:n,matches:e=>{let t=H(e);return t?.destination===r&&t.segments.length===2},invalidations:[],shouldRefresh:e=>[`navigation`,`manual`,`panel`].includes(e),read:async e=>{this.value.key!==e.viewKey&&(this.value=qn(e.viewKey),this.cursor=null);let t=e.reason===`panel`?this.cursor:null;this.cursor=null,this.value={...this.value,loading:!0},this.emit();try{let n=this.value,r=await i(e,t,n.generation);if(r.items.length>50)throw Error(`Related page exceeds limit`);if(this.value.generation&&r.generation!==this.value.generation)return{...qn(e.viewKey),error:!0,notice:`History changed. Refresh the page before reading related evidence.`};let a=t?[...n.items,...r.items]:r.items,o=a.length>500||a.length===500&&r.next!==null;return{...r,key:e.viewKey,items:a.slice(0,500),next:o?null:r.next,...o?{notice:`Showing the first 500 related records. Refresh to restart at the newest evidence.`}:{},loaded:!0,loading:!1,error:!1}}catch(t){if(e.signal.aborted)throw t;return t instanceof Kn?{...qn(e.viewKey),error:!0,notice:`History changed. Reload this detail page to restart related history.`}:{...this.value,loading:!1,error:!0}}},publish:e=>{this.value=e,this.emit()}}),e.registerProtectedState(()=>{this.cursor=null,this.value=qn(),this.emit()})}snapshot(){return this.value}subscribe(e){return this.listeners.add(e),e(this.value),()=>this.listeners.delete(e)}refresh(){this.value.loading||(this.cursor=null,this.views.refreshPanel(this.id))}more(){this.value.loading||!this.value.next||this.value.items.length>=500||(this.cursor=this.value.next,this.views.refreshPanel(this.id))}emit(){for(let e of this.listeners)e(this.value)}},Yn=`Audit history may have been replaced by restore. Newer local events may have been discarded. Previous-history state was discarded; these histories must not be combined.`,Xn={server:[`mcp/servers`,`servers`],principal:[`principals`,`principals`],grant:[`mcp/grants`,`grants`],grant_request:[`mcp/grant-requests`,`requests`],http_credential:[`http/credentials`,`http-credentials`],http_grant:[`http/grants`,`http-grants`],git_repository:[`git/repositories`,`git-repositories`],git_credential:[`git/credentials`,`git-credentials`],git_grant:[`git/grants`,`git-grants`]};function Zn(e){return W(e)}function Qn(e){return e===`principal`?`Agent`:W(e)}function $n({item:e,href:t}){let n=e.currentTargetName||e.target.id;return U(q,{primary:t?U(`a`,{href:t,children:n}):n,secondary:e.currentTargetName?e.target.id:void 0})}function er(e){let t=Xn[e.target.type];return e.currentTargetName&&t&&(e.target.type!==`server`||e.target.id!==`00000000000000000000000000`)?`#/${qt[t[1]]}/${e.target.id}`:void 0}function tr(e){return e===`succeeded`?`current`:e===`failed`?`error`:e===`pending`||e===`rejected`?`neutral`:`warning`}var nr=`Showing the latest entries. Older results could not be continued.`;function rr(e=``){return{viewKey:e,live:!0,paused:!1,items:[],nextCursor:null,history:void 0,item:void 0,missing:!1,loadingOlder:!1,olderError:!1,notice:void 0,targetLink:void 0,targetUnavailable:!1}}async function ir(e,t){let n=await fetch(t,{method:`GET`,headers:{Accept:`application/json`,"X-CSRF-Token":e.csrfToken},credentials:`same-origin`,redirect:`error`,signal:e.signal});if(await e.sessionLost(n))throw Error(`Session lost`);return n}async function ar(e,t=262144){let n=e.body?.getReader();if(n===void 0)throw Error(`Audit body missing`);let r=new TextDecoder(`utf-8`,{fatal:!0}),i=0,a=``;try{for(;;){let e=await n.read();if(e.done)break;if(i+=e.value.byteLength,i>t)throw Error(`Audit response too large`);a+=r.decode(e.value,{stream:!0})}return He(a+r.decode())}finally{await n.cancel().catch(()=>void 0),n.releaseLock()}}async function or(e,t){let n=await ir(e,t);if(n.status===200&&n.headers.get(`Content-Type`)===`application/json`)return{value:await ar(n),problem:void 0};if(n.headers.get(`Content-Type`)===`application/problem+json`){let e=Bn(await ar(n,65536));if(e?.status===n.status&&(n.status===409&&[`stale_cursor`,`audit_history_replaced`].includes(e.code)||n.status===404&&e?.code===`not_found`))return{value:void 0,problem:e.code}}throw Error(`Audit read unavailable`)}function sr(e,t,n){let r=new URLSearchParams({limit:`50`});for(let[t,n]of Object.entries(e))r.set(t.slice(7),n);return t!==null&&r.set(`cursor`,t),n!==void 0&&r.set(`generation`,n),`/api/v2/audit-events?${r.toString()}`}var cr=class{views;related;value=rr();serial=0;olderPosition=!1;listeners=new Set;continuation=null;knownGeneration;unavailableTargets=new Set;constructor(e,t){this.views=t,this.related=new Jn(e,t,`audit-related`,`audit`,async(e,t,n)=>{let r=H(e.viewKey).segments[1],i=n??this.knownGeneration,a=await or(e,`/api/v2/audit-events/${r}${i?`?generation=${i}`:``}`);if(a.problem===`audit_history_replaced`)throw new Kn;if(a.problem)throw Error(`Related history unavailable`);let o=ut(a.value);if(o.event.id!==r)throw Error(`Mismatched parent`);let s=await or(e,sr({filter_correlation_id:o.event.correlation_id},t,o.history.generation));if(s.problem)throw new Kn;let c=lt(s.value);if(c.history.generation!==o.history.generation)throw new Kn;if(c.items.some(e=>e.correlation_id!==o.event.correlation_id))throw Error(`Mismatched correlation`);return{items:[...c.items],next:c.next_cursor,generation:c.history.generation}}),t.registerPanel({id:`audit`,matches:e=>H(e)?.destination===`audit`,invalidations:[],pollMilliseconds:3e4,shouldRefresh:e=>![`invalidation`,`reconnect`,`poll`].includes(e)||H(this.views.snapshot().viewKey)?.segments.length===2||this.value.live&&!this.value.paused,read:async e=>{let t=this.serial,n=this.continuation;try{return{result:await this.read(e),serial:t}}catch(r){if(n!==null&&!e.signal.aborted&&this.value.viewKey===e.viewKey&&this.value.nextCursor===n)return{result:{...this.value,loadingOlder:!1,olderError:!0},serial:t};throw r}},publish:({result:e,serial:t})=>{t===this.serial&&(e.history!==void 0&&e.history.generation!==this.knownGeneration&&this.unavailableTargets.clear(),this.value=e,this.knownGeneration=e.history?.generation??this.knownGeneration,this.emit())}}),e.registerProtectedState(()=>{this.serial++,this.olderPosition=!1,this.value=rr(),this.continuation=null,this.knownGeneration=void 0,this.unavailableTargets.clear(),this.emit()})}listTarget(e){let t=Xn[e.target.type],n=`${e.target.type}/${e.target.id}`;if(!(t===void 0||!e.currentTargetName||this.unavailableTargets.has(n)||this.value.items.some(t=>t.target.type===e.target.type&&t.target.id===e.target.id&&t.action===`delete`&&t.outcome===`succeeded`)))return er(e)}snapshot(){return this.value}subscribe(e){return this.listeners.add(e),e(this.value),()=>this.listeners.delete(e)}setLive(e){this.views.cancelPanelRead(`audit`),this.serial++,this.continuation=null,this.value={...this.value,live:e,loadingOlder:!1},this.emit(),(this.value.history===void 0||e&&!this.value.paused)&&this.resume()}resume(){this.serial++,this.olderPosition=!1,this.continuation=null,this.value={...this.value,paused:!1,loadingOlder:!1,notice:void 0},this.emit(),this.views.refreshPanel(`audit`)}async loadOlder(){if(this.value.loadingOlder||this.value.items.length>=500||this.views.snapshot().panels.audit?.refreshing||this.views.snapshot().panels.audit?.status===`error`||this.value.nextCursor===null||this.views.snapshot().viewKey!==this.value.viewKey)return;this.continuation=this.value.nextCursor,this.value={...this.value,paused:!0,loadingOlder:!0,olderError:!1},this.emit();let e=this.value.viewKey,t=this.views.refreshPanel(`audit`),n=this.views.snapshot().generation;try{await t}finally{this.value.viewKey===e&&this.views.snapshot().generation===n&&(this.value={...this.value,loadingOlder:!1},this.emit())}}discard(e,t){e.signal.aborted||this.views.snapshot().viewKey!==e.viewKey||(this.olderPosition=!1,this.value={...rr(e.viewKey),live:this.value.live,paused:this.value.paused,notice:t},this.emit())}async read(e){let t=H(e.viewKey);if(t?.destination!==`audit`)throw Error(`Invalid audit location`);e.viewKey!==this.value.viewKey&&(this.value={...rr(e.viewKey),live:this.value.live,paused:this.value.paused},this.continuation=null,this.emit());let n=this.value,r=this.knownGeneration,i=t.segments[1];if(i!==void 0){let t=await or(e,`/api/v2/audit-events/${i}${r===void 0?``:`?generation=${r}`}`);if(t.problem===`audit_history_replaced`)return this.discard(e,Yn),{...rr(e.viewKey),live:n.live,paused:n.paused,notice:Yn};if(t.problem===`not_found`)return{...rr(e.viewKey),live:n.live,paused:n.paused,missing:!0};if(t.problem!==void 0)throw Error(`Audit item unavailable`);let a=ut(t.value);if(a.event.id!==i)throw Error(`Audit identity mismatch`);if(r!==void 0&&r!==a.history.generation)return{...rr(e.viewKey),live:n.live,paused:n.paused,notice:Yn};let o={...rr(e.viewKey),live:n.live,paused:n.paused,history:a.history,item:a.event};return!e.signal.aborted&&this.views.snapshot().viewKey===e.viewKey&&(this.value=o,this.knownGeneration=a.history.generation,this.emit()),{...o,...await this.target(e,a.event)}}let a=e.reason===`panel`?this.continuation:null;this.continuation=null;let o=await or(e,sr(t.query,a,r)),s=a!==null,c=!s&&this.olderPosition?nr:n.notice;if((o.problem===`audit_history_replaced`||a!==null&&o.problem===`stale_cursor`)&&(c=o.problem===`audit_history_replaced`?Yn:nr,this.discard(e,c),o=await or(e,sr(t.query,null)),s=!1),o.problem!==void 0)throw Error(`Audit page unavailable`);let l=lt(o.value);if(r!==void 0&&l.history.generation!==r&&(s=!1,c=Yn),s&&(n.history?.generation!==l.history.generation||n.history.oldest_retained?.sequence!==l.history.oldest_retained?.sequence||n.items.length+l.items.length>500))throw Error(`Audit continuation mismatch`);if(s&&n.items.length>0&&l.items.length>0&&BigInt(n.items.at(-1).sequence)<=BigInt(l.items[0].sequence))throw Error(`Audit continuation order mismatch`);return!e.signal.aborted&&this.views.snapshot().viewKey===e.viewKey&&(this.olderPosition=s),{...rr(e.viewKey),live:n.live,paused:n.paused,items:s?[...n.items,...l.items]:l.items,nextCursor:l.next_cursor,history:l.history,notice:c}}async target(e,t){let n=Xn[t.target.type],r=`${t.target.type}/${t.target.id}`,i=()=>{!e.signal.aborted&&this.views.snapshot().viewKey===e.viewKey&&this.unavailableTargets.add(r)};if(n===void 0)return{targetLink:void 0,targetUnavailable:!1};try{let a=await ir(e,`/api/v2/${n[0]}/${t.target.id}`);if(a.status===404)return i(),{targetLink:void 0,targetUnavailable:!1};if(a.status!==200||a.headers.get(`Content-Type`)!==`application/json`)throw Error(`Target unavailable`);let o=await ar(a,4194304);if(typeof o!=`object`||!o||!(`id`in o)||o.id!==t.target.id)throw Error(`Target identity mismatch`);return`deleted_at`in o&&o.deleted_at!==null?(i(),{targetLink:void 0,targetUnavailable:!1}):(!e.signal.aborted&&this.views.snapshot().viewKey===e.viewKey&&this.unavailableTargets.delete(r),{targetLink:`#/${qt[n[1]]}/${t.target.id}`,targetUnavailable:!1})}catch{return i(),{targetLink:void 0,targetUnavailable:!0}}}emit(){for(let e of this.listeners)e(this.value)}};function lr({value:e}){return e===null?U(S,{children:`None recorded`}):U(S,{children:[e.id,` · fingerprint `,e.fingerprint]})}function ur({value:e}){return U(`section`,{class:`panel domain-panel audit-history`,"aria-label":`Audit retention and continuity`,children:[U(`div`,{class:`panel-heading`,children:[U(`h2`,{children:`Retained history`}),U(G,{state:e.pruned?`warning`:`current`,children:e.pruned?`Older events pruned`:`No pruning recorded`})]}),U(`p`,{children:`Only the newest 65,536 events are retained. Restore may replace local history and discard newer events; this is not a permanent or complete record.`}),U(`details`,{children:[U(`summary`,{children:`Retention details`}),U(`dl`,{class:`detail-facts`,children:[U(`div`,{children:[U(`dt`,{children:`Oldest retained boundary`}),U(`dd`,{children:e.oldest_retained===null?`None — history is empty`:U(S,{children:[U(Y,{value:e.oldest_retained.timestamp}),` · sequence `,e.oldest_retained.sequence,U(`br`,{}),e.oldest_retained.id]})})]}),U(`div`,{children:[U(`dt`,{children:`History generation`}),U(`dd`,{children:e.generation})]})]})]})]})}var dr=e=>e===`category`?`Event`:e===`actor_type`?`Performer`:W(e).replace(/\bid\b/g,`ID`),fr=[`target`];function pr(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==``))}function mr({resolved:e,navigate:t}){let[n,r]=z({...e.location.query}),i=V(e.location.query),a=V();xe(()=>{i.current=e.location.query,a.current!==e.canonicalFragment&&r({...e.location.query}),a.current=void 0},[e.canonicalFragment]);let o=n=>{let r=pr({...i.current,...n}),o=ln({...e.location,query:r});!$e(r)||H(o)===void 0||o===ln({...e.location,query:i.current})||(i.current=r,a.current=o,t(o))};mn(n,e=>{let t={};for(let n of fr){let r=`filter_${n}`,i=e[r]??``;$e(pr({[r]:i}))&&(t[r]=i)}o(t)});let s={};for(let e of fr){let t=n[`filter_${e}`]??``;$e(pr({[`filter_${e}`]:t}))||(s[e]=`Use at most 256 UTF-8 bytes without control characters.`)}let c=ln({...e.location,query:pr(n)})!==ln({...e.location,query:i.current}),l=()=>{r({}),i.current={},a.current=`#/audit-log`,t(`#/audit-log`)},u=e=>{let t=`filter_${e}`,a=Ze(e,n.filter_category),c=dr(e),l=i.current[t]??``,u=[(n[t]??``)===l?``:`Current results: ${l===``?`Any`:l}.`].filter(Boolean).join(` `);return U(J,{id:`audit-${e}`,label:c,...u===``?{}:{hint:u},...s[e]===void 0?{}:{error:s[e]},children:i=>a===void 0?U(`input`,{...i,type:`text`,placeholder:`Name or ID`,value:n[t]??``,maxLength:256,onInput:e=>r({...n,[t]:e.currentTarget.value})}):U(`select`,{...i,value:n[t]??``,onChange:i=>{let a={[t]:i.currentTarget.value};e===`category`&&!Ze(`action`,a[t])?.includes(n.filter_action??``)&&(a.filter_action=``),r({...n,...a}),o(a)},children:[U(`option`,{value:``,children:[c,`: any`]}),a.map(e=>U(`option`,{value:e,children:e===`principal`?`Agent`:W(e)},e))]})},e)};return U(`form`,{class:`audit-filters`,"aria-label":`Filter audit history`,onSubmit:e=>e.preventDefault(),children:[e.location.query.filter_correlation_id&&U(`div`,{class:`inline-actions`,children:[`Related events:`,` `,U(`code`,{children:e.location.query.filter_correlation_id}),U(`button`,{type:`button`,onClick:()=>{r({...n,filter_correlation_id:``}),o({filter_correlation_id:``})},children:`Remove correlation filter`})]}),U(`div`,{class:`table-filters collection-query-filters audit-filter-grid`,children:[U(J,{id:`audit-event`,label:`Event`,children:e=>U(`select`,{...e,value:n.filter_category?`${n.filter_category}.${n.filter_action||`*`}`:n.filter_action?`*.${n.filter_action}`:``,onChange:e=>{let[t=``,i=``]=e.currentTarget.value.split(`.`),a={filter_category:t===`*`?``:t,filter_action:i===`*`?``:i};r({...n,...a}),o(a)},children:[U(`option`,{value:``,children:`Event: any`}),Object.entries(Ue).toSorted(([e],[t])=>e.localeCompare(t)).map(([e,t])=>U(`optgroup`,{label:W(e),children:[U(`option`,{value:`${e}.*`,children:[e,` · All actions`]}),t.map(t=>U(`option`,{value:`${e}.${t}`,children:[e,`.`,t]}))]})),U(`optgroup`,{label:`Action across categories`,children:Ze(`action`).map(e=>U(`option`,{value:`*.${e}`,children:[`Any category · `,e]}))})]})}),u(`actor_type`),u(`target_type`),u(`target`),u(`outcome`),U(`button`,{type:`button`,disabled:Object.keys(pr(n)).length===0&&Object.keys(i.current).length===0,onClick:l,children:`Reset`})]}),c&&U(`p`,{role:`status`,children:[`Draft changes are not yet applied.`,` `,Object.keys(s).length>0?`Check the marked fields; valid independent changes still apply.`:`Text filters apply after a short pause.`]})]})}function hr({controller:e,resolved:t,view:n,selected:r,targetHref:i}){let[a,o]=z(e.snapshot());B(()=>e.subscribe(o),[e]);let s=a.key===n.viewKey?a:void 0;return U(`section`,{"aria-label":`Related events`,class:`panel domain-panel related-history`,children:[U(`div`,{class:`panel-heading`,children:[U(`h2`,{children:`Related events`}),U(`button`,{type:`button`,disabled:s?.loading,onClick:()=>e.refresh(),children:`Refresh related events`})]}),s?.error&&U(K,{state:`error`,title:`Related events unavailable`,children:`Previously loaded events may be stale. Refresh to try again.`}),s?.notice&&U(K,{state:`warning`,title:s.notice}),!s?.loaded&&!s?.error&&U(K,{state:`loading`,title:`Loading related events…`}),s?.loaded&&U(Dn,{caption:`Related control-plane events`,layout:`activity`,rowHeaderKey:`event`,rowKey:e=>e.id,items:(s.items.some(e=>e.id===r.id)?s.items:[...s.items,r]).toSorted((e,t)=>BigInt(e.sequence)>BigInt(t.sequence)?-1:+(BigInt(e.sequence)U(Y,{value:e.timestamp})},{key:`event`,label:`Event`,role:`identity`,render:e=>U(q,{primary:U(S,{children:[U(`a`,{"aria-current":e.id===t.location.segments[1]?`page`:void 0,href:ln({...t.location,segments:[`audit`,e.id]}),children:[e.category,`.`,e.action]}),e.id===t.location.segments[1]&&U(`div`,{class:`audit-selected`,children:`Selected event`})]}),secondary:e.id})},{key:`actor`,label:`Performer`,role:`text`,render:e=>W(e.actor.type)},{key:`target-type`,label:`Target type`,role:`text`,render:e=>Qn(e.target.type)},{key:`target`,label:`Target`,role:`relation`,render:e=>U($n,{item:e,href:i(e)})},{key:`outcome`,label:`Outcome`,role:`status`,render:e=>U(G,{state:tr(e.outcome),children:Zn(e.outcome)})}]}),U(`div`,{class:`collection-pagination`,children:[s?.next&&s.items.length<500&&U(`button`,{type:`button`,disabled:s.loading,onClick:()=>e.more(),children:`Load older events`}),s?.loaded&&U(S,{children:[U(hn,{count:s.items.length,singular:`event`,plural:`events`,matching:!1,stale:s.error}),!s.items.some(e=>e.id===r.id)&&U(`span`,{class:`table-filter-summary`,children:`Plus the selected event`})]})]})]})}function gr({controller:e,resolved:t,view:n,navigate:r}){let[i,a]=z(e.snapshot());B(()=>e.subscribe(a),[e]);let o=i.viewKey===t.canonicalFragment?i:rr(t.canonicalFragment),s=n.panels.audit,c=t.location.segments[1]!==void 0;return U(`div`,{class:`domain-view audit-view`,"data-testid":`audit-view`,children:[c?U(S,{children:[U(`nav`,{class:`detail-navigation`,"aria-label":`Audit navigation`,children:U(`a`,{href:ln({...t.location,segments:[`audit`]}),children:`Back to Audit Log`})}),U(`header`,{class:`detail-context`,"data-testid":`detail-context`,children:[U(`div`,{class:`detail-context-heading`,children:[U(`h1`,{tabindex:-1,children:o.item?`${W(o.item.action)} ${o.item.category===`principal`?`agent`:o.item.category.replaceAll(`_`,` `)}`:`Audit event`}),o.item!==void 0&&U(G,{state:tr(o.item.outcome),children:Zn(o.item.outcome)})]}),U(`p`,{class:`technical-value`,children:t.location.segments[1]})]})]}):null,!c&&U(`div`,{class:`collection-toolbar live-collection-toolbar`,children:[U(`label`,{for:`audit-live-mode`,children:`Live mode`}),U(On,{attributes:{id:`audit-live-mode`},checked:o.live,showState:!1,onChange:t=>e.setLive(t)}),o.paused&&U(S,{children:[o.live&&U(G,{state:`warning`,children:`Live paused while viewing older results`}),U(`button`,{type:`button`,onClick:()=>e.resume(),children:o.live?`Resume live`:`Return to newest`})]})]}),o.notice!==void 0&&U(K,{state:`warning`,title:`Audit history changed`,children:U(`p`,{children:o.notice})}),s?.status===`error`&&U(K,{state:`error`,title:`Audit read unavailable`,children:U(`p`,{children:[o.items.length>0||o.item!==void 0?`Previously loaded evidence is stale and may be partial. `:``,`Use Refresh to try again.`]})}),c?o.item===void 0?o.missing?U(K,{state:`unavailable`,title:`Audit event not retained`,children:U(`p`,{children:`A missing event does not prove the action never occurred.`})}):o.notice===Yn?U(K,{state:`unavailable`,title:`Previous-history detail discarded`,children:U(`p`,{children:`Return to audit history to view the latest entries.`})}):s?.status===`error`?null:U(K,{state:`loading`,title:`Loading audit event`}):U(S,{children:[U(`section`,{class:`detail-section`,"aria-label":`Audit event detail`,children:[U(`div`,{class:`panel-heading`,children:U(`h2`,{children:`Event details`})}),U(`dl`,{class:`detail-facts`,children:[U(`div`,{children:[U(`dt`,{children:`Event`}),U(`dd`,{children:[o.item.category,`.`,o.item.action]})]}),U(`div`,{children:[U(`dt`,{children:`Correlation ID`}),U(`dd`,{class:`technical-value`,children:o.item.correlation_id})]}),U(`div`,{children:[U(`dt`,{children:`Timestamp`}),U(`dd`,{children:U(Y,{value:o.item.timestamp})})]}),U(`div`,{children:[U(`dt`,{children:`Performer`}),U(`dd`,{children:[W(o.item.actor.type),o.item.actor.credential!==null&&U(S,{children:[U(`br`,{}),U(lr,{value:o.item.actor.credential})]})]})]}),U(`div`,{children:[U(`dt`,{children:`Initiating credential`}),U(`dd`,{children:U(lr,{value:o.item.initiator})})]}),U(`div`,{children:[U(`dt`,{children:`Target type`}),U(`dd`,{children:Qn(o.item.target.type)})]}),U(`div`,{children:[U(`dt`,{children:`Target`}),U(`dd`,{children:U($n,{item:o.item,href:o.targetLink})})]})]}),(o.item.detail.reason!==null||o.item.detail.problem!==null)&&U(S,{children:[U(`h3`,{children:`Recorded diagnostics`}),U(`dl`,{class:`detail-facts`,children:[o.item.detail.reason!==null&&U(`div`,{children:[U(`dt`,{children:`Reason`}),U(`dd`,{children:o.item.detail.reason})]}),o.item.detail.problem!==null&&U(`div`,{children:[U(`dt`,{children:`Problem`}),U(`dd`,{children:o.item.detail.problem})]})]})]}),[`pending`,`unknown`].includes(o.item.outcome)&&U(`p`,{children:[o.item.outcome===`pending`?`The action was attempted; its outcome is unconfirmed. Pending does not mean it is still executing.`:`The outcome is unconfirmed.`,` `,`This event does not establish success, rollback, or safe replay.`]}),o.targetUnavailable&&U(K,{state:`warning`,title:`Current target unavailable`,children:U(`p`,{children:`Audit evidence remains available. The resource link could not be verified.`})})]}),U(hr,{controller:e.related,targetHref:t=>e.listTarget(t),selected:o.item,resolved:t,view:n})]}):U(`section`,{class:`panel domain-panel`,"aria-label":`Audit history`,children:[U(mr,{resolved:t,navigate:r}),o.history===void 0&&s?.status!==`error`?U(K,{state:`loading`,title:`Loading audit history`}):o.history!==void 0&&o.items.length===0&&s?.status!==`error`?U(K,{state:`empty`,title:Object.keys(t.location.query).length>0?`No matching audit events`:`No audit events yet`,children:Object.keys(t.location.query).length>0?U(`button`,{type:`button`,onClick:()=>r(`#/audit-log`),children:`Reset`}):U(`p`,{children:`Retained history is bounded; this does not establish that no earlier actions occurred.`})}):o.items.length>0?U(Dn,{caption:`Control-plane audit history`,layout:`activity`,rowHeaderKey:`event`,items:o.items,rowKey:e=>e.id,rowTestID:`audit-row`,columns:[{key:`time`,label:`Time`,role:`time`,render:e=>U(Y,{value:e.timestamp})},{key:`event`,label:`Event`,role:`identity`,render:e=>U(q,{primary:U(`a`,{href:ln({...t.location,segments:[`audit`,e.id]}),children:[e.category,`.`,e.action]}),secondary:e.id})},{key:`actor`,label:`Performer`,role:`relation`,render:e=>W(e.actor.type)},{key:`target-type`,label:`Target type`,role:`text`,render:e=>Qn(e.target.type)},{key:`target`,label:`Target`,role:`relation`,render:t=>U($n,{item:t,href:e.listTarget(t)})},{key:`outcome`,label:`Outcome`,role:`status`,render:e=>U(G,{state:tr(e.outcome),children:Zn(e.outcome)})}],hasMore:o.nextCursor!==null&&o.items.length<500&&s?.status!==`error`,loadingMore:o.loadingOlder,onLoadMore:()=>void e.loadOlder(),loadMoreLabel:`Load older events`,historySummary:!0,summaryExtra:s?.status!==`error`&&!o.olderError?U(`span`,{children:o.nextCursor===null?`No older events`:o.items.length>=500?`Load limit reached. Narrow the filters or return to newest.`:``}):void 0,historyMatching:Object.keys(t.location.query).length>0,itemNames:{singular:`event`,plural:`events`},localStale:s?.status===`error`||o.olderError}):null,o.history!==void 0&&o.items.length===0&&U(hn,{count:0,singular:`event`,plural:`events`,matching:Object.keys(t.location.query).length>0,stale:s?.status===`error`}),o.olderError&&U(`p`,{role:`alert`,children:`Older audit results unavailable. Loaded rows were retained; use Load older events to retry.`})]}),!c&&o.history!==void 0&&U(ur,{value:o.history})]})}function _r(e){return typeof e==`object`&&e&&Object.prototype.hasOwnProperty.call(e,`read_only`)?[`read_only`]:[]}function vr(e){if(`read_only`in e&&typeof e.read_only!=`boolean`)throw Error(`invalid response`);return e.read_only===!0}function yr(e){return e?`,"read_only":true`:``}function br(e){if(e===void 0)return null;if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`invalid response`);let t=e;if(Object.keys(t).sort().join(`,`)!==`process_id,upstream_ref`||typeof t.process_id!=`string`||!/^[0-9a-f]{32}$/.test(t.process_id)||typeof t.upstream_ref!=`string`||!/^[1-9]\d{0,19}$/.test(t.upstream_ref)||BigInt(t.upstream_ref)>18446744073709551615n)throw Error(`invalid response`);return{processID:t.process_id,upstreamRef:t.upstream_ref}}var xr;function Sr(e){xr=e}function Cr(e){let t=V(Symbol(`unsaved-changes`));if(xr===void 0)throw Error(`navigation guard is unavailable`);let n=xr;return xe(()=>(n.setDirty(t.current,e),()=>n.setDirty(t.current,!1)),[e,n]),n.navigate}var wr=new Set([`admin_credentials`,`system_status`,`backups`,`servers`,`server_operations`,`server_auth_flows`,`catalog`,`authorization`,`grant_requests`,`http_credentials`,`invocations`]),Tr=/^[0-7][0-9A-HJKMNP-TV-Z]{25}$/,Er=250;function Dr(){return{isVisible:()=>typeof document>`u`||document.visibilityState===`visible`,subscribe:e=>typeof document>`u`?()=>{}:(document.addEventListener(`visibilitychange`,e),()=>document.removeEventListener(`visibilitychange`,e))}}function Or(e,t){return Object.keys(e).sort().join(`,`)===[...t].sort().join(`,`)}function kr(e){if(!(typeof e!=`object`||!e||Array.isArray(e)||!Or(e,[`kind`,`resource_id`])||!(`kind`in e)||typeof e.kind!=`string`||!wr.has(e.kind)||!(`resource_id`in e)||e.resource_id!==null&&(typeof e.resource_id!=`string`||!Tr.test(e.resource_id))))return{kind:e.kind,resourceID:e.resource_id}}function Ar(e,t){let n=new AbortController,r=()=>n.abort();return e.aborted||t.aborted?n.abort():(e.addEventListener(`abort`,r,{once:!0}),t.addEventListener(`abort`,r,{once:!0})),{signal:n.signal,release:()=>{e.removeEventListener(`abort`,r),t.removeEventListener(`abort`,r)}}}var jr=class extends Error{};async function Mr(e,t,n,r,i){return e.runProtected(async e=>{let a=await fetch(t,{credentials:`same-origin`,redirect:`error`,signal:AbortSignal.any([r,e.signal]),headers:{Accept:`application/json`,"X-CSRF-Token":e.csrfToken}});if(await e.sessionLost(a))return;let o=a.headers.get(`Content-Type`);if(o!==`application/json`&&o!==`application/problem+json`)throw Error(`Collection data is unavailable.`);let s=await a.json();if(!a.ok)throw a.status===409&&Bn(s)?.code===`stale_cursor`?new jr:Error(`Collection data is unavailable.`);if(i!==void 0)return i(s);if(typeof s!=`object`||!s||!Or(s,[`items`,`next_cursor`,`total_count`,`offset`])||!(`items`in s)||!Array.isArray(s.items)||s.items.length>50||!(`total_count`in s)||typeof s.total_count!=`number`||!Number.isSafeInteger(s.total_count)||s.total_count<0||!(`offset`in s)||typeof s.offset!=`number`||!Number.isSafeInteger(s.offset)||s.offset<0||s.offset>s.total_count-s.items.length||s.items.length===0&&(s.total_count!==0||s.offset!==0)||!(`next_cursor`in s)||s.next_cursor!==null&&(typeof s.next_cursor!=`string`||s.next_cursor.length===0||s.next_cursor.length>512)||s.next_cursor!==null!=s.offset+s.items.lengthe.registerProtectedState(()=>{f.current+=1,l({key:``,cursors:[null],index:0}),h({key:``,cursor:null,status:`loading`}),_(void 0)}),[e]),xe(()=>{let r=++f.current,i=new AbortController;if(n.viewKey!==t.canonicalFragment)return()=>i.abort();_(void 0),l(e=>e.key===s?e:{key:s,cursors:[null],index:0}),h(e=>({key:s,cursor:d,status:`loading`,page:e.key===s&&e.cursor===d?e.page:void 0}));let a=()=>f.current===r&&!i.signal.aborted&&e.snapshot().epoch===o;return p.current(t.location.query,d,i.signal).then(e=>{a()&&e!==void 0&&h({key:s,cursor:d,page:e,status:`current`})}).catch(e=>{if(a()){if(e instanceof jr&&d!==null){h({key:s,cursor:null,status:`loading`}),l({key:s,cursors:[null],index:0,notice:`The previous page expired or changed. Restarted at the first page.`});return}h(t=>({key:s,cursor:d,page:!(e instanceof jr)&&t.key===s&&t.cursor===d?t.page:void 0,status:`error`,error:`Collection data is unavailable. Use Refresh to try again.`}))}}),()=>{i.abort(),f.current+=1}},[e,s,d,n.generation,n.viewKey]);let v=m.key===s&&m.cursor===d,y=g===void 0?v&&n.viewKey===t.canonicalFragment?m.status:`loading`:`error`,b=v?m.page:void 0,x=t.location.query,S=x.sort===void 0?a:{key:x.sort,direction:x.direction===`descending`?`descending`:`ascending`},C=e=>{let n=ln({...t.location,query:e});if(H(n)===void 0){_(`Filters must contain at most 256 UTF-8 bytes each, no control characters, and fit the location limit.`);return}_(void 0),i(n)},w=Object.fromEntries(Object.entries(x).filter(([e])=>e.startsWith(`filter_`)).map(([e,t])=>[e.slice(7),t])),T=y===`current`;return{items:b?.items??[],controls:{filterValues:w,sort:S,status:y,stale:v&&m.status===`error`&&b!==void 0,contextFilters:x.principal_id===void 0?[]:[{key:`principal_id`,label:`Exact agent ID`,value:x.principal_id}],clearContextFilter:e=>{let t={...x};delete t[e],C(t)},error:g??(v?m.error:void 0),notice:u.notice,totalCount:b?.totalCount,offset:b?.offset??0,hasPrevious:T&&u.index>0,hasNext:T&&b?.nextCursor!=null,previous:()=>{T&&u.index>0&&l({...u,index:u.index-1})},next:()=>{T&&b?.nextCursor!=null&&l({...u,cursors:[...u.cursors.slice(0,u.index+1),b.nextCursor],index:u.index+1})},changeFilter:(e,n)=>{let r=H(window.location.hash),i={...r?.destination===t.location.destination&&r.query.tab===t.location.query.tab&&r.segments.join(`/`)===t.location.segments.join(`/`)?r.query:x};n.trim()===``?delete i[`filter_${e}`]:i[`filter_${e}`]=n,C(i)},changeSort:e=>C({...x,sort:e,direction:S?.key===e&&S.direction===`ascending`?`descending`:`ascending`}),resetFilters:()=>C(Object.fromEntries(Object.entries(x).filter(([e])=>!e.startsWith(`filter_`)&&e!==`principal_id`)))}}}var Pr=class{session;request;visibility;reconnectMilliseconds;listeners=new Set;panels=new Map;panelState=new Map;panelGenerations=new Map;readControllers=new Map;pollTimers=new Map;pendingInvalidations=new Set;unsubscribeVisibility;unregisterProtectedState;viewKey=`#/sign-in`;generation=0;freshness=`reconnecting`;active=!1;streamConnected=!1;streamController;reconnectTimer;invalidationTimer;constructor(e,t={}){this.session=e,this.request=(t.request??fetch).bind(globalThis),this.visibility=t.visibility??Dr(),this.reconnectMilliseconds=t.reconnectMilliseconds??1e3,this.unsubscribeVisibility=this.visibility.subscribe(()=>this.visibilityChanged()),this.unregisterProtectedState=this.session.registerProtectedState(()=>this.reset())}snapshot(){return{viewKey:this.viewKey,generation:this.generation,freshness:this.freshness,panels:Object.fromEntries(this.panelState)}}subscribe(e){return this.listeners.add(e),e(this.snapshot()),()=>this.listeners.delete(e)}registerPanel(e){if(this.panels.has(e.id))throw Error(`duplicate view panel`);let t=e;return this.panels.set(e.id,t),this.panelState.set(e.id,{status:`loading`,hasValue:!1}),this.active&&e.matches(this.viewKey)&&this.refresh([e.id]),()=>{this.panels.delete(e.id),this.panelState.delete(e.id),this.panelGenerations.delete(e.id),this.abortRead(e.id),this.clearPolls();for(let e of this.visiblePanels())this.schedulePoll(e);this.emit()}}activate(e){if(!this.active){this.active=!0,this.viewKey=e,this.abortReads(),this.clearPolls(),this.markVisiblePanelsLoading(),this.connect();return}this.navigate(e),this.connect()}navigate(e){(this.viewKey!==e||this.generation===0)&&(this.viewKey=e,this.abortReads(),this.clearPolls(),this.markVisiblePanelsLoading(),this.active?this.refresh(void 0,`navigation`):this.emit())}manualRefresh(){this.active&&this.refresh(void 0,`manual`)}refreshPanel(e){return this.active?this.refresh([e],`panel`):Promise.resolve()}invalidate(e){if(!this.active)return;let t=!1;for(let n of this.visiblePanels())n.invalidations.includes(e.kind)&&(n.onInvalidation?.(e)??!0)&&(this.pendingInvalidations.add(n.id),t=!0);!t&&this.panels.size===0&&(t=!0),!(!t||this.invalidationTimer!==void 0)&&(this.invalidationTimer=setTimeout(()=>{this.invalidationTimer=void 0;let e=[...this.pendingInvalidations];this.pendingInvalidations.clear(),this.refresh(e,`invalidation`)},Er))}cancelPanelRead(e){this.abortRead(e),this.panelGenerations.set(e,(this.panelGenerations.get(e)??0)+1);let t=this.panelState.get(e);t&&this.panelState.set(e,{...t,refreshing:!1}),this.emit()}close(){this.active=!1,this.reset(),this.unsubscribeVisibility(),this.unregisterProtectedState(),this.listeners.clear()}async refresh(e,t=`navigation`){if(!this.active)return;let n=(e===void 0?this.visiblePanels():e.map(e=>this.panels.get(e)).filter(e=>e!==void 0&&e.matches(this.viewKey))).filter(e=>e.shouldRefresh?.(t)??!0),r=this.generation+1;this.generation=r;let i=this.viewKey;for(let e of n){this.abortRead(e.id),this.panelGenerations.set(e.id,r);let t=this.panelState.get(e.id);this.panelState.set(e.id,{status:t?.hasValue===!0?this.streamConnected?`current`:`stale`:`loading`,hasValue:t?.hasValue===!0,refreshing:!0})}if(this.freshness=this.streamConnected?`current`:`reconnecting`,this.emit(),n.length===0){this.streamConnected&&(this.freshness=`current`),this.emit();return}await Promise.all(n.map(e=>this.readPanel(e,i,r,t))),this.current(i,r)&&this.streamConnected&&(this.freshness=`current`,this.emit())}async readPanel(e,t,n,r){let i=new AbortController;this.readControllers.set(e.id,i);try{let a=await this.session.runProtected(async a=>{let o=Ar(a.signal,i.signal);try{return await e.read({...a,signal:o.signal,viewKey:t,generation:n,reason:r})}finally{o.release()}});if(a===void 0||!this.panelCurrent(e.id,t,n))return;e.publish(a),this.panelState.set(e.id,{status:this.streamConnected?`current`:`stale`,hasValue:!0})}catch{if(!i.signal.aborted&&this.panelCurrent(e.id,t,n)){let t=this.panelState.get(e.id);this.panelState.set(e.id,{status:`error`,hasValue:t?.hasValue===!0})}}finally{this.readControllers.get(e.id)===i&&this.readControllers.delete(e.id),this.panelCurrent(e.id,t,n)&&(this.schedulePoll(e),this.emit())}}connect(){if(!this.active||this.streamController!==void 0||this.session.snapshot().lifecycle!==`authenticated`)return;this.reconnectTimer?.(),this.reconnectTimer=void 0,this.streamConnected=!1,this.freshness=`reconnecting`,this.markVisiblePanelsStale(),this.emit();let e=new AbortController;this.streamController=e,this.session.runProtected(async t=>{let n=Ar(t.signal,e.signal);try{let e=await this.request(`/api/v2/events`,{method:`POST`,headers:{"Content-Type":`application/json`,"X-CSRF-Token":t.csrfToken},body:`{}`,credentials:`same-origin`,redirect:`error`,signal:n.signal});if(await t.sessionLost(e))return;if(e.status!==200||e.headers.get(`Content-Type`)!==`text/event-stream`||e.body===null)throw Error(`event stream rejected`);this.streamConnected=!0,this.refresh(void 0,`reconnect`),await this.consumeEvents(e.body,n.signal)}finally{n.release()}}).catch(()=>void 0).finally(()=>{this.streamController===e&&(this.streamController=void 0,this.streamConnected=!1,!(!this.active||this.session.snapshot().lifecycle!==`authenticated`)&&(this.freshness=`reconnecting`,this.markVisiblePanelsStale(),this.emit(),this.reconnectTimer=this.session.scheduleProtected(()=>this.connect(),this.reconnectMilliseconds)))})}async consumeEvents(e,t){let n=e.getReader(),r=new TextDecoder(`utf-8`,{fatal:!0}),i=``,a=``,o=``;try{for(;!t.aborted;){let e=await n.read();if(e.done)return;if(i+=r.decode(e.value,{stream:!0}),i.length>65536)throw Error(`event frame too large`);for(;;){let e=i.indexOf(` -`);if(e===-1)break;let t=i.slice(0,e).replace(/\r$/,``);if(i=i.slice(e+1),t===``){if(a===`invalidate`&&o!==``){let e;try{e=JSON.parse(o)}catch{throw Error(`invalid event JSON`)}let t=kr(e);if(t===void 0)throw Error(`invalid event`);this.invalidate(t)}a=``,o=``}else if(t.startsWith(`event: `))a=t.slice(7);else if(t.startsWith(`data: `)){if(o!==``)throw Error(`duplicate event data`);o=t.slice(6)}else if(!t.startsWith(`:`))throw Error(`invalid event field`)}}}finally{await n.cancel().catch(()=>void 0),n.releaseLock()}}visiblePanels(){return[...this.panels.values()].filter(e=>e.matches(this.viewKey))}current(e,t){return this.active&&this.viewKey===e&&this.generation===t}panelCurrent(e,t,n){return this.active&&this.viewKey===t&&this.panelGenerations.get(e)===n}schedulePoll(e){let t=e.pollMilliseconds;if(!this.active||t===void 0||t<=0||this.pollTimers.has(t)||!e.matches(this.viewKey)||e.shouldPoll?.()===!1||!this.visibility.isVisible())return;let n=setTimeout(()=>{if(this.pollTimers.delete(t),!this.visibility.isVisible())return;let e=this.visiblePanels().filter(e=>e.pollMilliseconds===t&&e.shouldPoll?.()!==!1).map(e=>e.id);e.length>0&&this.refresh(e,`poll`)},t);this.pollTimers.set(t,n)}visibilityChanged(){if(!this.visibility.isVisible()){this.clearPolls();return}for(let e of this.visiblePanels())this.schedulePoll(e)}markVisiblePanelsStale(){for(let e of this.visiblePanels()){let t=this.panelState.get(e.id);this.panelState.set(e.id,{status:t?.hasValue===!0?`stale`:`loading`,hasValue:t?.hasValue===!0})}}markVisiblePanelsLoading(){for(let e of this.visiblePanels())e.scope!==`session`&&this.panelState.set(e.id,{status:`loading`,hasValue:!1})}abortRead(e){this.readControllers.get(e)?.abort(),this.readControllers.delete(e)}abortReads(){for(let e of this.readControllers.values())e.abort();this.readControllers.clear()}clearPolls(){for(let e of this.pollTimers.values())clearTimeout(e);this.pollTimers.clear()}reset(){this.active=!1,this.streamController?.abort(),this.streamController=void 0,this.streamConnected=!1,this.abortReads(),this.clearPolls(),this.reconnectTimer?.(),this.reconnectTimer=void 0,this.invalidationTimer!==void 0&&clearTimeout(this.invalidationTimer),this.invalidationTimer=void 0,this.pendingInvalidations.clear(),this.freshness=`reconnecting`;for(let e of this.panelState.keys())this.panelState.set(e,{status:`loading`,hasValue:!1});this.emit()}emit(){let e=this.snapshot();for(let t of this.listeners)t(e)}},Fr=/^[0-7][0-9A-HJKMNP-TV-Z]{25}$/,Ir=[`preparing`,`awaiting_callback`,`exchanging`,`succeeded`,`failed`,`expired`,`cancelled`,`superseded`,`interrupted`],Lr=[`metadata_discovery`,`client_registration`,`authorization_request`,`callback_validation`,`token_exchange`,`credential_installation`],Rr=new Set(`configuration_invalid.resource_limit.connectivity.tls_failed.protocol_unsupported.protocol_invalid.authentication_rejected.credential_absent.keyring_absent.keyring_locked.keyring_interaction_required.keyring_unavailable.keyring_unsupported.oauth_rejected.oauth_expired.registration_expired.process_exited.output_limit.stop_unconfirmed.catalog_invalid.catalog_limit.catalog_stale.superseded.cancelled.interrupted.revocation_failed.revocation_unsupported.cleanup_pending`.split(`.`));function zr(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`invalid auth flow response`);let n=e;if(Object.keys(n).sort().join(`,`)!==[...t].sort().join(`,`))throw Error(`invalid auth flow response`);return n}function Br(e){if(typeof e!=`string`)throw Error(`invalid auth flow response`);return e}function Vr(e){let t=Br(e);if(!Fr.test(t))throw Error(`invalid auth flow response`);return t}function Hr(e){let t=Br(e);if(!/^(?:0|[1-9][0-9]*)$/.test(t))throw Error(`invalid auth flow response`);return t}function Ur(e){if(e===null)return null;let t=Br(e);if(!Rr.has(t))throw Error(`invalid auth flow response`);return t}function Wr(e){if(e===null)return null;let t=zr(e,[`correlation_id`,`stage`,`reason`,`http_status`]),n=Br(t.stage),r=Ur(t.reason),i=t.http_status;if(!Lr.includes(n)||r===null||i!==null&&(!Number.isInteger(i)||typeof i!=`number`||i<100||i>599))throw Error(`invalid auth flow response`);return{correlationID:Vr(t.correlation_id),stage:n,reason:r,httpStatus:i}}function Gr(e){if(e!==null&&typeof e!=`string`)throw Error(`invalid auth flow response`);return e}function Kr(e){let t=Gr(e);if(t!==null&&(t.length===0||t.length>4096))throw Error(`invalid auth flow response`);return t}function qr(e){let t=Br(e);if(!Ir.includes(t))throw Error(`invalid auth flow response`);return t}function Jr(e){let t=zr(e,[`id`,`server_id`,`state`,`target_desired_revision`,`registration_revision`,`created_at`,`expires_at`,`finished_at`,`reason`,`diagnostic`]);return{id:Vr(t.id),serverID:Vr(t.server_id),state:qr(t.state),targetDesiredRevision:Hr(t.target_desired_revision),registrationRevision:Hr(t.registration_revision),createdAt:Br(t.created_at),expiresAt:Br(t.expires_at),finishedAt:Gr(t.finished_at),reason:Ur(t.reason),diagnostic:Wr(t.diagnostic)}}function Yr(e){let t=zr(e,[`items`,`next_cursor`]);if(!Array.isArray(t.items))throw Error(`invalid auth flow response`);return{items:t.items.map(Jr),nextCursor:Kr(t.next_cursor)}}async function Xr(e){let t=new Uint8Array(await e.arrayBuffer());if(t.byteLength>4194304)throw Error(`auth flow response too large`);let n=zr(JSON.parse(new TextDecoder(`utf-8`,{fatal:!0}).decode(t)),[`flow`,`authorization_url`]),r=Br(n.authorization_url);if(r.length===0||r.length>8192)throw Error(`invalid auth flow response`);return{flow:Jr(n.flow),authorizationURL:r}}function Zr(e){return![`preparing`,`awaiting_callback`,`exchanging`].includes(e.state)}function Qr(e){return e.state===`preparing`||e.state===`awaiting_callback`}function $r(e){if(e.desiredState===`deleted`||typeof e.transport!=`object`||e.transport===null)return!1;let t=e.transport;if(t.kind!==`streamable_http`)return!1;let n=t.authentication;return typeof n==`object`&&!!n&&!Array.isArray(n)&&n.mode===`oauth`}function ei(e){let t=e.replaceAll(`_`,` `);return t.startsWith(`oauth`)?`OAuth${t.slice(5)}`:t.charAt(0).toLocaleUpperCase()+t.slice(1)}function ti(e){return Zr(e)?e.state===`succeeded`?`current`:e.state===`failed`?`error`:e.state===`interrupted`?`warning`:`neutral`:`loading`}function ni({serverID:e,items:t,hasMore:n,loadingMore:r,onLoadMore:i,stale:a,loading:o}){return U(Dn,{caption:`OAuth activity`,layout:`activity`,rowHeaderKey:`action`,loadedSubset:!0,historySummary:!0,localStale:a,localLoading:o,itemNames:{singular:`flow`,plural:`flows`},emptyTitle:`No retained OAuth flows`,hasMore:n,loadingMore:r,onLoadMore:i,loadMoreLabel:`Load more flows`,items:t,rowKey:e=>e.id,rowTestID:`auth-flow-row`,filters:[{key:`status`,label:`Status`,type:`select`,value:e=>e.state,options:[{value:`preparing`,label:`Preparing`},{value:`awaiting_callback`,label:`Awaiting callback`},{value:`exchanging`,label:`Exchanging`},{value:`succeeded`,label:`Succeeded`},{value:`failed`,label:`Failed`},{value:`cancelled`,label:`Cancelled`},{value:`interrupted`,label:`Interrupted`},{value:`expired`,label:`Expired`},{value:`superseded`,label:`Superseded`}]}],initialSort:{key:`created`,direction:`descending`},columns:[{key:`created`,label:`Created`,role:`time`,sortValue:e=>e.createdAt,render:e=>U(Y,{value:e.createdAt})},{key:`action`,label:`Flow`,role:`identity`,render:t=>U(q,{primary:U(`a`,{href:`#/mcp/servers/${e}/auth-flows/${t.id}`,children:`OAuth authorization`}),secondary:t.id})},{key:`status`,label:`Status`,role:`status`,sortValue:e=>e.state,render:e=>U(G,{state:ti(e),children:ei(e.state)})},{key:`outcome`,label:`Reason`,role:`text`,sortValue:e=>e.reason??``,render:e=>e.reason===null?`—`:ei(e.reason)}]})}function ri({mutations:e,sinks:t,server:n,etag:r,readVersion:i,exchangeActive:a}){let[o]=z(()=>e.create()),[s,c]=z(()=>o.snapshot()),[l,u]=z(),[d,f]=z();B(()=>o.subscribe(c),[o]),B(()=>()=>o.close(),[o]);let p=async(e,t)=>{let n=await e;if(n.kind===`acknowledged`){t.publish(n.value.authorizationURL)===`lost`&&u(`The authorization URL could not be displayed. Start a new flow from current state.`),o.abandon();return}if(n.kind===`uncertain`){t.lose();return}t.cancel(),n.kind===`rejected`&&n.requiresRefresh&&f(i)},m=()=>{u(void 0);let e=t.prepareOAuth(`Authorize server OAuth flow`);if(e===void 0){u(`The one-time authorization URL display is unavailable. No flow was started.`);return}o.begin({route:`/api/v2/mcp/servers/${n.id}/oauth-flows`,method:`POST`,body:`{}`,precondition:r,requiresPrecondition:!0,idempotency:`none`,successStatuses:[201],decode:async e=>{let t=await Xr(e);if(t.flow.serverID!==n.id||t.flow.state!==`awaiting_callback`||t.flow.targetDesiredRevision!==n.desiredRevision||t.flow.registrationRevision!==n.oauthClientRevision||t.flow.finishedAt!==null||t.flow.reason!==null)throw Error(`invalid auth flow creation response`);return t}}),p(o.submit(),e)},h=d!==void 0&&i<=d,g=s.state===`submitting`||s.availability===`storage_latched`||h,_=n.credentialState===`ready`,v=n.transport?.authentication?.registration,y=v?.mode===`static`&&(v.token_endpoint_auth_method===`client_secret_basic`||v.token_endpoint_auth_method===`client_secret_post`)&&n.oauthClientRevision===`0`;return U(`section`,{class:`panel domain-panel`,"aria-labelledby":`auth-flow-start-title`,children:[U(`div`,{class:`panel-heading`,children:U(`div`,{children:U(`h2`,{id:`auth-flow-start-title`,children:`OAuth authorization`})})}),U(`p`,{children:`Continue authorization in a new browser page. The one-time URL is cleared when it is dismissed, opened, or you leave this page.`}),$r(n)&&!a&&U(`p`,{children:`Starting again invalidates any previous pending authorization link.`}),y&&U(`p`,{class:`bounded-note`,id:`oauth-client-prerequisite`,children:`Add the client secret above before authorizing.`}),$r(n)&&!a?U(`button`,{type:`button`,class:_?void 0:`primary-action`,"data-testid":`start-auth-flow`,disabled:g||y,"aria-describedby":y?`oauth-client-prerequisite`:void 0,onClick:m,children:_?`Reauthorize server`:`Authorize server`}):U(K,{state:a?`loading`:`empty`,title:a?`Authorization in progress`:`OAuth is unavailable`,children:!a&&U(`p`,{children:`This server is not configured for OAuth.`})}),s.problem!==void 0&&U(K,{state:`error`,title:s.problem.title,children:s.requiresRefresh&&U(`p`,{children:`A fresh server and flow snapshot was requested. Review it before starting a new flow.`})}),s.state===`uncertain`&&U(K,{state:`warning`,title:`Flow start outcome unknown`,children:U(`p`,{children:`Inspect refreshed flow history before starting again. This start cannot be replayed.`})}),h&&U(`p`,{class:`session-message`,role:`status`,children:`Waiting for a newer authoritative server snapshot.`}),l!==void 0&&U(`p`,{class:`session-message`,role:`status`,children:l})]})}function ii({mutations:e,flow:t,onRefresh:n}){let[r]=z(()=>e.create()),[i,a]=z(()=>r.snapshot()),o=V(null);B(()=>r.subscribe(a),[r]),B(()=>()=>r.close(),[r]);let s=async e=>{(await e).kind===`acknowledged`&&(r.abandon(),n())};return Qr(t)?U(`section`,{class:`panel domain-panel`,"aria-labelledby":`auth-flow-cancel-title`,children:[U(`div`,{class:`panel-heading`,children:U(`div`,{children:U(`h2`,{id:`auth-flow-cancel-title`,children:`Cancel this OAuth flow`})})}),U(`button`,{ref:o,type:`button`,"data-testid":`cancel-auth-flow`,disabled:i.state===`submitting`||i.availability===`storage_latched`,onClick:()=>{r.begin({route:`/api/v2/mcp/servers/${t.serverID}/oauth-flows/${t.id}`,method:`DELETE`,body:`{}`,precondition:null,requiresPrecondition:!1,idempotency:`none`,successStatuses:[204],decode:async()=>void 0}),r.confirm()},children:`Review cancellation`}),i.problem!==void 0&&U(K,{state:`error`,title:i.problem.title}),i.state===`uncertain`&&U(K,{state:`warning`,title:`Cancellation outcome unknown`,children:U(`p`,{children:`Refresh this flow. Do not infer cancellation or replay the request.`})}),U(jn,{id:`auth-flow-cancel-confirm`,open:i.state===`confirming`,title:`Cancel this OAuth flow?`,consequence:`Cancellation invalidates the current callback state. An authorization page already opened may no longer complete, while an exchange already in progress cannot be cancelled.`,confirmLabel:`Cancel OAuth flow`,returnFocus:o,onCancel:()=>r.abandon(),onConfirm:()=>void s(r.submit())})]}):null}function ai({mutations:e,sinks:t,server:n,etag:r,readVersion:i,flows:a,flow:o,nextCursor:s,loadingMore:c,restarted:l,onLoadMore:u,onRefresh:d,mode:f=`full`,stale:p=!1,loading:m=!1}){return o===void 0?f===`action`?$r(n)?U(ri,{mutations:e,sinks:t,server:n,etag:r,readVersion:i,exchangeActive:a.some(e=>e.state===`exchanging`)}):null:U(S,{children:[U(`section`,{class:`panel domain-panel`,"aria-labelledby":`auth-flow-list-title`,"data-testid":`auth-flow-list`,children:[U(`div`,{class:`panel-heading`,children:U(`div`,{children:U(`h2`,{id:`auth-flow-list-title`,children:`OAuth activity`})})}),l&&U(K,{state:`stale`,title:`Flow history changed`,children:U(`p`,{children:`Showing the first page. Previous results could not be continued.`})}),m&&U(K,{state:`loading`,title:`Loading OAuth activity`}),p&&U(K,{state:`error`,title:`OAuth activity unavailable`,children:`Loaded flows are last-known. Use Load more flows to retry continuation, or Refresh to restart.`}),U(ni,{stale:p,loading:m,serverID:n.id,items:a,hasMore:s!==null,loadingMore:c,onLoadMore:u})]}),f===`full`&&U(ri,{mutations:e,sinks:t,server:n,etag:r,readVersion:i,exchangeActive:a.some(e=>e.state===`exchanging`)})]}):U(S,{children:[U(`div`,{"data-testid":`auth-flow-detail`,children:[U(`nav`,{class:`detail-navigation`,"aria-label":`OAuth flow navigation`,children:U(`a`,{href:`#/mcp/servers/${n.id}?tab=authentication`,children:`Back to server authentication`})}),U(`header`,{class:`detail-context`,"data-testid":`detail-context`,children:[U(`div`,{class:`detail-context-heading`,children:[U(`h1`,{id:`auth-flow-detail-title`,tabindex:-1,children:`Authorize server with OAuth`}),U(G,{state:ti(o),children:ei(o.state)})]}),U(`p`,{class:`technical-value`,children:o.id})]}),U(`section`,{class:`detail-section`,"aria-labelledby":`auth-flow-facts-title`,children:[U(`h3`,{id:`auth-flow-facts-title`,children:`Flow details`}),p&&U(K,{state:`error`,title:`OAuth flow unavailable`,children:`These flow details are last-known. Refresh to retry the read.`}),U(`dl`,{class:`detail-list`,children:[U(`div`,{children:[U(`dt`,{children:`Created`}),U(`dd`,{children:U(Y,{value:o.createdAt})})]}),U(`div`,{children:[U(`dt`,{children:`Expires`}),U(`dd`,{children:U(Y,{value:o.expiresAt})})]}),U(`div`,{children:[U(`dt`,{children:`Finished`}),U(`dd`,{children:U(Y,{value:o.finishedAt,fallback:Zr(o)?`Not recorded`:`In progress`})})]}),o.reason!==null&&U(`div`,{children:[U(`dt`,{children:`Reason`}),U(`dd`,{children:ei(o.reason)})]})]}),o.diagnostic!==null&&U(`details`,{children:[U(`summary`,{children:`Diagnostic details`}),U(`dl`,{class:`detail-list`,children:[U(`div`,{children:[U(`dt`,{children:`Stage`}),U(`dd`,{children:ei(o.diagnostic.stage)})]}),U(`div`,{children:[U(`dt`,{children:`Reason`}),U(`dd`,{children:ei(o.diagnostic.reason)})]}),o.diagnostic.httpStatus!==null&&U(`div`,{children:[U(`dt`,{children:`HTTP status`}),U(`dd`,{children:o.diagnostic.httpStatus})]}),U(`div`,{children:[U(`dt`,{children:`Correlation`}),U(`dd`,{children:o.diagnostic.correlationID})]})]})]})]})]}),U(ii,{mutations:e,flow:o,onRefresh:d})]})}var oi=/^[0-7][0-9A-HJKMNP-TV-Z]{25}$/,si=[`activate`,`reload`,`retry`,`refresh_catalog`,`credential_replace`,`disable`,`delete`,`disconnect_credentials`],ci=[`scheduled`,`running`,`succeeded`,`failed`,`cancelled`,`superseded`,`interrupted`],li=new Set(`configuration_invalid.resource_limit.connectivity.tls_failed.protocol_unsupported.protocol_invalid.authentication_rejected.credential_absent.keyring_absent.keyring_locked.keyring_interaction_required.keyring_unavailable.keyring_unsupported.oauth_rejected.oauth_expired.registration_expired.process_exited.output_limit.stop_unconfirmed.catalog_invalid.catalog_limit.catalog_stale.superseded.cancelled.interrupted.revocation_failed.revocation_unsupported.cleanup_pending`.split(`.`));function ui(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`invalid operation response`);let n=e;if(Object.keys(n).sort().join(`,`)!==[...t].sort().join(`,`))throw Error(`invalid operation response`);return n}function di(e){if(typeof e!=`string`)throw Error(`invalid operation response`);return e}function fi(e){if(e!==null&&typeof e!=`string`)throw Error(`invalid operation response`);return e}function pi(e){let t=di(e);if(!oi.test(t))throw Error(`invalid operation response`);return t}function mi(e,t){let n=di(e);if(!t.includes(n))throw Error(`invalid operation response`);return n}function hi(e){let t=fi(e);if(t!==null&&(t.length===0||t.length>512))throw Error(`invalid operation response`);return t}function gi(e){let t=ui(e,[`items`,`has_more`]);if(!Array.isArray(t.items)||t.items.length>2||typeof t.has_more!=`boolean`||t.has_more&&t.items.length!==2)throw Error(`invalid active operation response`);let n=t.items.map(_i);if(n.some(bi))throw Error(`invalid active operation response`);return{items:n,hasMore:t.has_more,nextCursor:null}}function _i(e){let t=ui(e,[`id`,`server_id`,`kind`,`target_desired_revision`,`target_credential_revisions`,`state`,`reason`,`created_at`,`started_at`,`finished_at`]),n=ui(t.target_credential_revisions,[`static_credential`,`oauth_client`,`oauth_tokens`]),r=fi(t.reason);if(r!==null&&!li.has(r))throw Error(`invalid operation response`);return{id:pi(t.id),serverID:pi(t.server_id),kind:mi(t.kind,si),targetDesiredRevision:di(t.target_desired_revision),targetStaticRevision:di(n.static_credential),targetOAuthClientRevision:di(n.oauth_client),targetOAuthTokensRevision:di(n.oauth_tokens),state:mi(t.state,ci),reason:r,createdAt:di(t.created_at),startedAt:fi(t.started_at),finishedAt:fi(t.finished_at)}}function vi(e){let t=ui(e,[`items`,`next_cursor`]);if(!Array.isArray(t.items))throw Error(`invalid operation response`);return{items:t.items.map(_i),nextCursor:hi(t.next_cursor)}}async function yi(e){if(e.headers.get(`Content-Type`)!==`application/json`)throw Error(`invalid operation response`);let t=await e.text();if(new TextEncoder().encode(t).byteLength>1048576)throw Error(`invalid operation response`);return _i(ui(JSON.parse(t),[`operation`]).operation)}function bi(e){return e.state!==`scheduled`&&e.state!==`running`}function xi(e){let t,n=document.createElement(`a`);try{return t=URL.createObjectURL(e),n.href=t,n.download=`agent-gateway-traffic-${new Date().toISOString().replaceAll(`:`,`-`)}.json`,n.hidden=!0,document.body.append(n),n.click(),!0}catch{return!1}finally{n.remove(),t!==void 0&&URL.revokeObjectURL(t)}}async function Si(e,t){let n=e;try{return await t(n),n=``,`copied`}catch{return n=``,`failed`}finally{n=``}}function Ci(e,t){let n=t(e,`_blank`,`noopener,noreferrer`);if(n===null)return`blocked`;try{n.opener=null}catch{}return`opened`}var wi=/^mgw_(?:admin|agent)_[A-Za-z0-9_-]{43}$/,Ti=/^127\.(?:0|[1-9][0-9]{0,2})\.(?:0|[1-9][0-9]{0,2})\.(?:0|[1-9][0-9]{0,2})$/,Ei=8192;function Di(e){if(e.length===0||new TextEncoder().encode(e).byteLength>Ei)return!1;let t;try{t=new URL(e)}catch{return!1}return t.href!==e||t.username!==``||t.password!==``||t.hash!==``?!1:t.protocol===`https:`?!0:t.protocol!==`http:`||!Ti.test(t.hostname)?!1:t.hostname.split(`.`).every(e=>Number(e)<=255)}var Oi=class{input;release;constructor(e){this.release=e}attach(e){this.input=e,e.value=``}detach(e){this.input===e&&(e.value=``,this.input=void 0)}read(){return this.input?.value??``}clear(){this.input!==void 0&&(this.input.value=``)}close(){this.clear(),this.input=void 0,this.release(this)}},ki=class{session;unregisterProtectedState;oneTimePresenter;oauthPresenter;writeOnlyValues=new Set;generation=0;active;constructor(e){this.session=e,this.unregisterProtectedState=e.registerProtectedState(()=>this.clear())}registerOneTimePresenter(e){return this.oneTimePresenter?.clear(),this.oneTimePresenter=e,()=>{this.oneTimePresenter===e&&(e.clear(),this.oneTimePresenter=void 0,this.active?.kind===`one_time`&&this.invalidate())}}registerOAuthPresenter(e){return this.oauthPresenter?.clear(),this.oauthPresenter=e,()=>{this.oauthPresenter===e&&(e.clear(),this.oauthPresenter=void 0,this.active?.kind===`oauth`&&this.invalidate())}}createWriteOnly(){let e=new Oi(e=>this.writeOnlyValues.delete(e));return this.writeOnlyValues.add(e),e}prepareOneTime(e){let t=this.session.snapshot(),n=this.oneTimePresenter;if(t.lifecycle!==`authenticated`||n===void 0||e.length===0||e.length>160)return;this.clear();let r=++this.generation;if(this.active={kind:`one_time`,generation:r,epoch:t.epoch},!n.prepare(e,r)){n.clear(),this.invalidate();return}return this.preparedOneTime(r,t.epoch)}prepareOAuth(e){let t=this.session.snapshot(),n=this.oauthPresenter;if(t.lifecycle!==`authenticated`||n===void 0||e.length===0||e.length>160)return;this.clear();let r=++this.generation;if(this.active={kind:`oauth`,generation:r,epoch:t.epoch},!n.prepare(e,r)){n.clear(),this.invalidate();return}return this.preparedOAuth(r,t.epoch)}isCurrent(e){let t=this.session.snapshot();return this.active?.generation===e&&this.active.epoch===t.epoch&&t.lifecycle===`authenticated`}dismiss(e){this.isCurrent(e)&&this.clear()}clearForNavigation(){this.clear()}close(){this.unregisterProtectedState(),this.clear();for(let e of[...this.writeOnlyValues])e.close()}preparedOneTime(e,t){let n=!1;return Object.freeze({publish:r=>n||(n=!0,!this.matches(`one_time`,e,t))?`lost`:!wi.test(r)||!this.oneTimePresenter?.publish(r,e)?(this.oneTimePresenter?.lose(e),`lost`):`published`,lose:()=>{n||(n=!0,this.matches(`one_time`,e,t)&&this.oneTimePresenter?.lose(e))},cancel:()=>{n||(n=!0,this.matches(`one_time`,e,t)&&this.clear())}})}preparedOAuth(e,t){let n=!1;return Object.freeze({publish:r=>n||(n=!0,!this.matches(`oauth`,e,t))?`lost`:!Di(r)||!this.oauthPresenter?.publish(r,e)?(this.oauthPresenter?.lose(e),`lost`):`published`,lose:()=>{n||(n=!0,this.matches(`oauth`,e,t)&&this.oauthPresenter?.lose(e))},cancel:()=>{n||(n=!0,this.matches(`oauth`,e,t)&&this.clear())}})}matches(e,t,n){return this.active?.kind===e&&this.active.generation===t&&this.active.epoch===n&&this.isCurrent(t)}clear(){this.oneTimePresenter?.clear(),this.oauthPresenter?.clear();for(let e of this.writeOnlyValues)e.clear();this.invalidate()}invalidate(){this.generation+=1,this.active=void 0}};function Ai(){let e=window.getSelection();e!==null&&e.removeAllRanges()}function ji({value:e,label:t,testID:n}){let[r,i]=z(`idle`),a=V(0);B(()=>{a.current+=1,i(`idle`)},[e]);let o=async()=>{let t=++a.current,n=await Si(e,e=>navigator.clipboard.writeText(e));a.current===t&&i(n)};return U(`div`,{class:`copyable-value`,children:[U(`code`,{"data-testid":n,children:e}),U(`button`,{class:`text-button`,type:`button`,"aria-label":`Copy ${t}`,onClick:()=>void o(),children:`Copy`}),U(`span`,{class:`copyable-value-status`,role:`status`,"aria-live":`polite`,children:[r===`copied`&&`${Mi(t)} copied.`,r===`failed`&&`Could not copy ${t}.`]})]})}function Mi(e){return`${e.charAt(0).toUpperCase()}${e.slice(1)}`}function Ni({value:e,id:t,label:n,hint:r,multiline:i=!1,placeholder:a,onInput:o}){let s=V(null),c=V(null);return xe(()=>{let t=i?c.current:s.current;if(t!==null)return e.attach(t),()=>e.detach(t)},[i,e]),U(J,{id:t,label:n,hint:r,required:!0,children:e=>i?U(`textarea`,{...e,ref:c,placeholder:a,rows:5,autocomplete:`off`,autocapitalize:`none`,spellcheck:!1,onInput:e=>o?.(e.currentTarget.value)}):U(`input`,{...e,ref:s,placeholder:a,type:`password`,autocomplete:`off`,autocapitalize:`none`,spellcheck:!1,onInput:e=>o?.(e.currentTarget.value)})})}function Pi({coordinator:e}){let t=V(null),[n,r]=z(0),[i,a]=z(``),[o,s]=z(``),[c,l]=z(`awaiting`),[u,d]=z(`idle`);B(()=>e.registerOneTimePresenter({prepare:(e,n)=>{let i=t.current;if(i===null||i.open)return!1;r(n),a(e),s(``),d(`idle`),l(`awaiting`);try{return i.showModal(),!0}catch{return!1}},publish:(n,r)=>t.current?.open!==!0||!e.isCurrent(r)?!1:(s(n),d(`idle`),l(`display`),!0),lose:t=>{e.isCurrent(t)&&(s(``),d(`idle`),l(`lost`),Ai())},clear:()=>{s(``),a(``),d(`idle`),l(`awaiting`),Ai(),t.current?.open&&t.current.close()}}),[e]);let f=async()=>{if(c!==`display`||o===``)return;let t=await Si(o,e=>navigator.clipboard.writeText(e));e.isCurrent(n)&&d(t)};return U(`dialog`,{ref:t,class:`sensitive-dialog`,"aria-labelledby":`one-time-display-title`,"aria-describedby":`one-time-display-warning`,onCancel:t=>{t.preventDefault(),e.dismiss(n)},children:[U(`h2`,{id:`one-time-display-title`,children:i||`One-time bearer`}),U(`p`,{id:`one-time-display-warning`,class:`sensitive-warning`,children:`This bearer cannot be recovered or shown again. Copying leaves it in the operating-system clipboard until you overwrite it; this application cannot revoke clipboard contents.`}),c===`awaiting`&&U(G,{state:`loading`,children:`Waiting for the response`}),c===`lost`&&U(G,{state:`unavailable`,children:`No bearer can be displayed. Inspect current state before another explicit action.`}),c===`display`&&U(`div`,{class:`one-time-value`,"data-testid":`one-time-value`,children:U(`code`,{children:o})}),U(`div`,{class:`sink-status`,role:`status`,"aria-live":`polite`,"aria-atomic":`true`,children:[u===`copied`&&`Copied to the operating-system clipboard.`,u===`failed`&&`Clipboard copy failed. The bearer was not echoed.`]}),U(`div`,{class:`dialog-actions`,children:[U(`button`,{type:`button`,onClick:()=>e.dismiss(n),children:`Dismiss and clear`}),c===`display`&&U(`button`,{class:`primary-action`,type:`button`,"data-testid":`copy-one-time-value`,onClick:()=>void f(),children:`Copy bearer`})]})]})}function Fi({coordinator:e}){let t=V(null),[n,r]=z(0),[i,a]=z(``),[o,s]=z(``),[c,l]=z(`awaiting`),[u,d]=z(!1),[f,p]=z(`idle`);B(()=>e.registerOAuthPresenter({prepare:(e,n)=>{let i=t.current;if(i===null||i.open)return!1;r(n),a(e),s(``),d(!1),p(`idle`),l(`awaiting`);try{return i.showModal(),!0}catch{return!1}},publish:(n,r)=>t.current?.open!==!0||!e.isCurrent(r)?!1:(s(n),d(!1),p(`idle`),l(`display`),!0),lose:t=>{e.isCurrent(t)&&(s(``),d(!1),p(`idle`),l(`lost`),Ai())},clear:()=>{s(``),a(``),d(!1),p(`idle`),l(`awaiting`),Ai(),t.current?.open&&t.current.close()}}),[e]);let m=()=>{if(c===`display`&&o!==``){if(Ci(o,()=>window.open(o,`_blank`,`noopener,noreferrer`))===`blocked`){d(!0),p(`idle`);return}s(``),Ai(),e.dismiss(n)}},h=async()=>{if(c!==`display`||o===``)return;let t=await Si(o,e=>navigator.clipboard.writeText(e));e.isCurrent(n)&&p(t)};return U(`dialog`,{ref:t,class:`sensitive-dialog`,"aria-labelledby":`oauth-display-title`,"aria-describedby":`oauth-display-warning`,onCancel:t=>{t.preventDefault(),e.dismiss(n)},children:[U(`h2`,{id:`oauth-display-title`,children:i||`Authorization URL`}),U(`p`,{id:`oauth-display-warning`,class:`sensitive-warning`,children:`Open this URL only when you are ready to continue authorization. It is kept only in this dialog and is cleared on dismissal or navigation.`}),c===`awaiting`&&U(G,{state:`loading`,children:`Waiting for the response`}),c===`lost`&&U(G,{state:`unavailable`,children:`No authorization URL can be displayed. Start a new flow from current state.`}),c===`display`&&U(`div`,{class:`one-time-url`,"data-testid":`one-time-oauth-url`,children:U(`code`,{children:o})}),U(`div`,{class:`sink-status`,role:`status`,"aria-live":`polite`,"aria-atomic":`true`,children:[u&&`The browser blocked the new page. The URL remains available in this dialog. Copying leaves it in the operating-system clipboard until you overwrite it.`,f===`copied`&&` Copied to the operating-system clipboard.`,f===`failed`&&` Clipboard copy failed.`]}),U(`div`,{class:`dialog-actions`,children:[U(`button`,{type:`button`,onClick:()=>e.dismiss(n),children:`Dismiss and clear`}),c===`display`&&u&&U(`button`,{type:`button`,"data-testid":`copy-oauth-url`,onClick:()=>void h(),children:`Copy URL`}),c===`display`&&U(`button`,{class:`primary-action`,type:`button`,"data-testid":`open-oauth-url`,onClick:m,children:`Open authorization page`})]})]})}function Ii({coordinator:e}){return U(S,{children:[U(Pi,{coordinator:e}),U(Fi,{coordinator:e})]})}function Li(e){if(e.desiredState===`deleted`||e.transport===null)return;let t=e.transport;if(t.kind===`stdio`){let n=t.secret_environment,r=[...new Set(Object.values(n))].sort();return r.length===0?void 0:{kind:`static_credential`,slots:r,expectedRevision:e.staticRevision}}let n=t.authentication??{};if(n.mode===`bearer`)return{kind:`static_credential`,slots:[`bearer`],expectedRevision:e.staticRevision};if(n.mode!==`oauth`)return;let r=n.registration??{};return r.mode===`static`&&(r.token_endpoint_auth_method===`client_secret_basic`||r.token_endpoint_auth_method===`client_secret_post`)?{kind:`oauth_client`,slots:[`client_secret`],expectedRevision:e.oauthClientRevision}:void 0}function Ri(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`invalid credential replacement response`);let n=e;if(Object.keys(n).sort().join(`,`)!==[...t].sort().join(`,`))throw Error(`invalid credential replacement response`);return n}async function zi(e){if(e.headers.get(`Content-Type`)!==`application/json`)throw Error(`invalid credential replacement response`);let t=await e.text();if(new TextEncoder().encode(t).byteLength>1048576)throw Error(`invalid credential replacement response`);let n=Ri(JSON.parse(t),[`server_id`,`kind`,`credential_revision`,`operation`]),r=_i(n.operation);if(typeof n.server_id!=`string`||r.serverID!==n.server_id||n.kind!==`static_credential`&&n.kind!==`oauth_client`||typeof n.credential_revision!=`string`||!/^(?:0|[1-9][0-9]*)$/.test(n.credential_revision)||r.kind!==`credential_replace`)throw Error(`invalid credential replacement response`);return{serverID:n.server_id,kind:n.kind,credentialRevision:n.credential_revision,operation:r}}function Bi({mutations:e,sinks:t,server:n,etag:r,readVersion:i,shape:a,onRefresh:o}){let[s]=z(()=>a.slots.map(e=>({slot:e,value:t.createWriteOnly()}))),[c]=z(()=>e.create()),[l,u]=z(()=>c.snapshot()),[d,f]=z(!1),[p,m]=z(),[h,g]=z(),[_,v]=z(),[y,b]=z(!1),x=V(null),C=Cr(y);B(()=>c.subscribe(u),[c]),B(()=>()=>{c.close();for(let e of s)e.value.close()},[c,s]);let w=()=>{b(s.some(({slot:e})=>{let t=document.getElementById(`credential-slot-${e}`);return(t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement)&&t.value!==``}))},T=()=>{for(let e of s)e.value.clear();b(!1)},E=async e=>{let t=await e;t.kind===`acknowledged`?(v(void 0),g(`Credential revision ${t.value.credentialRevision} was published; operation ${t.value.operation.id} was scheduled.`),c.abandon(),C(`#/mcp/servers/${n.id}/operations/${t.value.operation.id}`,!0)):(t.kind===`rejected`&&t.requiresRefresh||t.kind===`uncertain`)&&(v(i),o())},D=()=>{if(m(void 0),g(void 0),s.map(({slot:e})=>{let t=document.getElementById(`credential-slot-${e}`);return[e,t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement?t.value:``]}).some(([,e])=>e.length===0)){T(),m(`Enter every credential again; the fields were cleared.`);return}f(!0)},O=()=>{f(!1);let e=Object.fromEntries(s.map(({slot:e})=>{let t=document.getElementById(`credential-slot-${e}`);return[e,t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement?t.value:``]})),t=a.kind===`static_credential`?JSON.stringify({kind:a.kind,expected_revision:a.expectedRevision,values:e}):JSON.stringify({kind:a.kind,expected_revision:a.expectedRevision,client_secret:e.client_secret}),i={route:`/api/v2/mcp/servers/${n.id}/credential-replacements`,method:`POST`,body:t,precondition:r,requiresPrecondition:!0,idempotency:`none`,successStatuses:[202],uncertainProblemCodes:[`keyring_unavailable`],decode:async e=>{let t=await zi(e);if(t.serverID!==n.id||t.kind!==a.kind)throw Error(`invalid credential replacement response`);return t}};c.begin(i);let o=c.submit();T(),E(o)},k=_!==void 0&&i<=_,A=l.state===`submitting`||l.availability===`storage_latched`||k;return U(S,{children:[U(`form`,{"data-testid":`credential-replacement-form`,children:[s.map(({slot:e,value:t})=>U(Ni,{value:t,id:`credential-slot-${e}`,label:a.kind===`oauth_client`?`OAuth client secret`:n.transport.kind===`streamable_http`?`Bearer token`:`Secret slot ${e}`,placeholder:a.kind===`oauth_client`?`Enter OAuth client secret`:n.transport.kind===`streamable_http`?`Enter bearer token`:`Enter secret value`,hint:`Write-only. This value is cleared immediately after submission and is never returned by the Gateway.`,onInput:w},e)),p!==void 0&&U(K,{state:`error`,title:`Credential input required`,children:U(`p`,{children:p})}),l.problem!==void 0&&U(K,{state:`error`,title:l.problem.title,children:l.requiresRefresh&&U(`p`,{children:`A fresh server snapshot was requested. Re-enter credentials only after reviewing current revisions and operation history.`})}),l.state===`uncertain`&&U(K,{state:`warning`,title:`Replacement outcome unknown`,children:U(`p`,{children:`The credential or operation may have been published. No replay is available. Inspect the refreshed server and operation history before making a new decision.`})}),k&&U(`p`,{class:`session-message`,role:`status`,children:`Waiting for a newer authoritative server snapshot.`}),h!==void 0&&U(`p`,{class:`session-message`,role:`status`,children:h}),U(`button`,{ref:x,class:`danger-action form-submit-action`,type:`button`,"data-testid":`credential-replacement-submit`,disabled:A,onClick:D,children:`Review credential replacement`})]}),U(jn,{id:`credential-replacement-confirm`,open:d,title:`Replace current server authority?`,consequence:`Replacement withdraws current routing and may interrupt calls. Calls already handed downstream can have unknown outcomes. A native keyring operation may require OS interaction, fail, or outlive cancellation.`,confirmLabel:`Replace credential`,destructive:!0,returnFocus:x,onCancel:()=>{f(!1),T()},onConfirm:O})]})}function Vi(e){let t=`${e.shape.kind}:${e.shape.slots.join(`,`)}`,[n,r]=z(t);return B(()=>{n!==t&&r(t)},[n,t]),n===t?U(Bi,{...e}):null}function Hi(e){if(e.transport===null)return{heading:`Authentication`,description:`No active transport is configured.`,status:`Unavailable`,warning:!0};let t=e.transport,n=t.authentication??{},r=`Authentication`,i;if(t.kind===`stdio`){let e=t.secret_environment??{};Object.keys(e).length>0&&(r=`Local secrets`,i=`Replace the write-only values used by this local server.`)}else n.mode===`bearer`?(r=`Bearer token`,i=`Replace the write-only bearer token used for this server.`):n.mode===`oauth`&&(r=`OAuth client credentials`,i=`This client secret identifies your OAuth application. You must also authorize Gateway below to access the server.`);let a=[`absent`,`reauthentication_required`,`locked`,`interaction_required`,`unavailable`,`unsupported`].includes(e.credentialState);return{heading:r,description:i,status:i===void 0?`Not required`:a?`Action required`:`Configured`,warning:a}}function Ui({mutations:e,sinks:t,server:n,etag:r,readVersion:i,onRefresh:a}){let o=Li(n),s=Hi(n);return s.heading===`OAuth client credentials`&&o===void 0?null:U(`section`,{class:`panel domain-panel`,"aria-labelledby":`server-credentials-title`,"data-testid":`server-credentials`,children:[U(`div`,{class:`panel-heading`,children:[U(`div`,{children:U(`h2`,{id:`server-credentials-title`,children:s.heading})}),o?.kind===`oauth_client`?n.oauthClientRevision===`0`&&U(G,{state:`warning`,children:`Client secret required`}):U(G,{state:s.warning?`warning`:`current`,children:s.status})]}),s.description!==void 0&&U(`p`,{children:s.description}),o!==void 0&&U(Vi,{mutations:e,sinks:t,server:n,etag:r,readVersion:i,shape:o,onRefresh:a})]})}async function Wi(e,t){if(e.headers.get(`Content-Type`)!==`application/json`)throw Error(`invalid server deletion response`);let n=new Uint8Array(await e.arrayBuffer());if(n.byteLength>1048576)throw Error(`invalid server deletion response`);let r=JSON.parse(new TextDecoder(`utf-8`,{fatal:!0}).decode(n));if(typeof r!=`object`||!r||Array.isArray(r))throw Error(`invalid server deletion response`);let i=r;if(Object.keys(i).sort().join(`,`)!==`operation,server`)throw Error(`invalid server deletion response`);let a=t(i.server),o=_i(i.operation),s=e.headers.get(`ETag`);if(a.desiredState!==`deleted`||a.transport!==null||o.serverID!==a.id||o.kind!==`delete`||s!==`"server-${a.id}-${a.desiredRevision}"`)throw Error(`invalid server deletion response`);return{server:a,operation:o}}function Gi({mutations:e,server:t,etag:n,readVersion:r,decodeServerValue:i}){let[a]=z(()=>e.create()),[o,s]=z(()=>a.snapshot()),[c,l]=z(``),[u,d]=z(),f=V(null);if(B(()=>a.subscribe(s),[a]),B(()=>()=>a.close(),[a]),t.desiredState===`deleted`)return null;let p=u!==void 0&&r<=u,m=o.state===`submitting`||o.availability===`storage_latched`||p,h=async e=>{l(``);let n=await e;n.kind===`acknowledged`?(a.abandon(),window.location.hash=`#/mcp/servers/${t.id}/operations/${n.value.operation.id}`):n.kind===`rejected`&&n.requiresRefresh&&d(r)};return U(`section`,{class:`panel domain-panel`,"aria-labelledby":`server-destructive-title`,"data-testid":`server-destructive-actions`,children:[U(`div`,{class:`panel-heading`,children:U(`div`,{children:U(`h2`,{id:`server-destructive-title`,children:`Delete server`})})}),U(`p`,{children:`Permanent deletion tombstones this server identity, withdraws routing, and uses best-effort remote revocation for affected credentials.`}),U(`button`,{ref:f,class:`danger-action`,type:`button`,"data-testid":`delete-server`,disabled:m,onClick:()=>{l(``),a.begin({route:`/api/v2/mcp/servers/${t.id}`,method:`DELETE`,body:`{}`,precondition:n,requiresPrecondition:!0,idempotency:`none`,successStatuses:[200,202],decode:e=>Wi(e,i)}),a.confirm()},children:`Review permanent deletion`}),p&&U(`p`,{class:`session-message`,role:`status`,children:`Waiting for a newer authoritative server snapshot.`}),o.problem!==void 0&&U(K,{state:`error`,title:o.problem.title}),o.state===`uncertain`&&U(K,{state:`warning`,title:`Deletion outcome unknown`,children:U(`p`,{children:`Refresh the permanent server identity and operation history. Do not replay, force deletion, or infer remote cleanup.`})}),U(An,{id:`server-delete-confirm`,open:o.state===`confirming`,title:`Permanently delete this server?`,consequence:U(`p`,{children:`This tombstones the permanent identity and immutable namespace, withdraws routing, invalidates local authority, and attempts remote revocation only on a best-effort basis. Cleanup may remain pending. There is no force or authority-restoration path.`}),expected:t.namespace,value:c,confirmLabel:`Permanently delete server`,returnFocus:f,onValue:l,onCancel:()=>{l(``),a.abandon()},onConfirm:()=>void h(a.submit())})]})}function Ki(e){if(e.length>8192)return!1;let t=/^https:\/\/([a-z0-9.-]+)(?::([0-9]+))?$/.exec(e);if(t===null||t[0]!==e)return!1;let n=t[1],r=t[2];if(n.length>253||n.split(`.`).some(e=>e.length>63||!/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(e))||r!==void 0&&(Number(r)<1||Number(r)>65535||Number(r)===443))return!1;let i=n.split(`.`);return!(i.length===4&&i.every(e=>/^(0|[1-9][0-9]{0,2})$/.test(e)&&Number(e)<=255))}var qi=class extends Error{field;itemID;constructor(e,t,n){super(t),this.field=e,this.itemID=n}},Ji=/^[a-z][a-z0-9_-]{0,31}$/,Yi=/^[a-z][a-z0-9_]{0,63}$/,Xi=/^\/(?:[^\0]*)$/,Zi=0,Qi={auto:`Automatic (recommended)`,modern:`Current only — 2026-07-28`,legacy:`Legacy only — 2025-11-25`},$i={none:`Public client — no client secret`,client_secret_basic:`Client secret in HTTP Basic`,client_secret_post:`Client secret in request body`};function ea(e){return Xi.test(e)?e===`/`||e.endsWith(`/`)===!1&&e.slice(1).split(`/`).every(e=>e!==``&&e!==`.`&&e!==`..`):!1}function ta(e){let t={configuration:`Server configuration`,namespace:`Namespace`,display_name:`Display name`,enabled:`Initial state`,transport:`Connection`,"transport.kind":`Connection type`,"transport.executable":`Executable`,"transport.arguments":`Arguments`,"transport.working_directory":`Working directory`,"transport.environment":`Environment`,"transport.secret_environment":`Secret environment bindings`,"transport.headers":`Custom HTTP headers`,"transport.url":`HTTP endpoint`,"transport.protocol_mode":`Protocol mode`,"transport.authentication":`Authentication`,"transport.authentication.mode":`Authentication mode`,"transport.authentication.trusted_origins":`Trusted origins`,"transport.authentication.request_offline_access":`Offline access policy`,"transport.authentication.callback_uri":`Callback URI`,"transport.authentication.auth_server_metadata_url":`Authorization metadata URL`,"transport.authentication.scopes":`Initial scopes`,"transport.authentication.registration":`OAuth registration`,"transport.authentication.registration.mode":`OAuth registration mode`,"transport.authentication.registration.issuer":`OAuth issuer`,"transport.authentication.registration.client_id":`OAuth client ID`,"transport.authentication.registration.token_endpoint_auth_method":`Token endpoint authentication method`}[e.field]??`Server configuration`;switch(e.rule){case`required`:return`${t} is required.`;case`maximum`:return`${t} exceeds its maximum size or item count.`;case`unique`:return`${t} must not contain duplicates.`;case`disjoint`:return`${t} conflicts with another configuration source.`;case`canonical_absolute_path`:return`${t} must be an absolute canonical path without a trailing slash, empty segment, ".", or ".." segment.`;case`canonical_url`:return e.field===`transport.authentication.callback_uri`?`Callback URI must be an exact HTTP loopback URL with an explicit port and path, without credentials, query, fragment, or encoded path.`:e.field===`transport.authentication.auth_server_metadata_url`?`Authorization metadata URL must be an exact canonical HTTPS URL with a path and without credentials or fragment. A bounded query is allowed.`:`${t} must be a canonical URL without credentials, a query, fragment, uppercase hostname, or default port.`;case`transport_policy`:return`${t} does not satisfy the selected transport security policy.`;default:return`${t} is invalid.`}}function na(e){return Zi+=1,`${e}-${Zi}`}function ra(e,t){return t.map(t=>({id:na(e),value:t}))}function ia(e,t){return Object.entries(t).map(([t,n])=>({id:na(e),name:t,value:n}))}function aa(e,t){let n=Object.create(null);for(let r of e){if(r.name===``)throw Error(`${t} names cannot be empty.`);if(Object.hasOwn(n,r.name))throw Error(`${t} names must be unique.`);n[r.name]=r.value}return n}function oa(){return{namespace:``,displayName:``,enabled:!1,transportKind:``,executable:``,arguments:[],workingDirectory:``,environment:[],secretEnvironment:[],url:``,headers:[],protocolMode:`auto`,authMode:``,registrationMode:`dynamic`,issuer:``,clientID:``,tokenEndpointAuthMethod:`none`,trustedOrigins:[],requestOfflineAccess:!1,callbackURI:``,authServerMetadataURL:``,explicitScopes:!1,scopes:[]}}function sa(e){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`Expected a JSON object.`);return e}function ca(e){if(Array.isArray(e))return`[${e.map(ca).join(`,`)}]`;if(typeof e==`object`&&e){let t=e;return`{${Object.keys(t).sort().map(e=>`${JSON.stringify(e)}:${ca(t[e])}`).join(`,`)}}`}return JSON.stringify(e)}function la(e){let t=sa(e);if(t.kind!==`streamable_http`)return ca(t);let n=sa(t.authentication);return n.mode===`oauth`?ca({...t,authentication:{...n,trusted_origins:[...n.trusted_origins].sort()}}):ca(t)}function ua(e){let t=Object.create(null),n=new Set,r=new Set(`authorization.authentication-info.www-authenticate.cookie.cookie2.set-cookie.set-cookie2.api-key.x-api-key.x-auth-token.x-access-token.x-authorization.host.connection.keep-alive.te.trailer.transfer-encoding.upgrade.expect.forwarded.via.x-real-ip.x-original-url.x-rewrite-url.x-http-method-override.origin.referer.accept.user-agent.range.cache-control.pragma.max-forwards.date`.split(`.`)),i=0;if(e.length>16)throw new qi(`headers`,`Use at most 16 custom HTTP headers.`);for(let[a,o]of e.entries()){let e=o.name.toLowerCase(),s=`Header ${a+1}`;if(!/^[!#$%&'*+.^_`|~0-9a-z-]{1,128}$/i.test(o.name))throw new qi(`headers`,`${s}: enter an HTTP token name of 1–128 ASCII bytes, without spaces or a colon.`);if(n.has(e))throw new qi(`headers`,`${s}: names must be unique regardless of letter case.`);if(r.has(e)||/^(mcp-|proxy-|sec-|x-forwarded-|content-|accept-|if-)/.test(e))throw new qi(`headers`,`${s}: this name is reserved for authentication, routing, HTTP, or MCP protocol control. Use Authentication for credentials.`);if(!/^[\x20-\x7e]{0,4096}$/.test(o.value)||o.value.trim()!==o.value)throw new qi(`headers`,`${s}: use at most 4096 printable ASCII bytes, without leading/trailing spaces, tabs, or line breaks. Empty values are allowed.`);n.add(e),i+=o.name.length+o.value.length,t[o.name]=o.value}if(i>8192)throw new qi(`headers`,`Custom header names and values together must not exceed 8192 bytes.`);return t}function da(e){if(e.transportKind===``)throw Error(`Choose how Gateway connects to this server.`);if(e.transportKind===`stdio`){let t=e.arguments.map(e=>e.value),n=aa(e.environment,`Environment variable`),r=aa(e.secretEnvironment,`Secret environment binding`);if(!ea(e.executable))throw Error(`Executable must be an absolute canonical path without a trailing slash, empty segment, ".", or ".." segment.`);if(!ea(e.workingDirectory))throw Error(`Working directory must be an absolute canonical path without a trailing slash, empty segment, ".", or ".." segment.`);if(t.length>64)throw Error(`At most 64 arguments are allowed.`);if(Object.keys(n).length>32)throw Error(`At most 32 ordinary environment entries are allowed.`);if(Object.keys(r).length>16)throw Error(`At most 16 secret environment slots are allowed.`);for(let[e,t]of Object.entries(r)){if(!Yi.test(t))throw Error(`Secret environment ${e} must name a keyring slot.`);if(Object.hasOwn(n,e))throw Error(`${e} cannot be both ordinary and secret environment.`)}return{kind:`stdio`,executable:e.executable,arguments:t,working_directory:e.workingDirectory,environment:n,secret_environment:r}}if(e.authMode===``)throw Error(`Choose how Gateway authenticates to this server.`);let t=e.url.trim();if(t===``)throw new qi(`url`,`Enter an HTTP endpoint.`);let n;try{n=new URL(t)}catch{throw new qi(`url`,`HTTP URL must be absolute.`)}if(n.protocol!==`http:`&&n.protocol!==`https:`)throw new qi(`url`,`HTTP endpoint must use http or https.`);if(n.username!==``||n.password!==``||n.search!==``||n.hash!==``)throw new qi(`url`,`HTTP URL cannot contain credentials, query, or fragment.`);let r;if(e.authMode===`none`||e.authMode===`bearer`)r={mode:e.authMode};else{let t=[],n=new Set;for(let r of e.trustedOrigins){let e=r.value.trim();if(e===``)throw new qi(`origin`,`Enter an OAuth network origin.`,r.id);if(!Ki(e))throw new qi(`origin`,`Use a lowercase DNS origin without an IP address, path, or default port.`,r.id);if(n.has(e))throw new qi(`origin`,`OAuth network origins must be unique.`,r.id);n.add(e),t.push(e)}let i=e.issuer.trim();if(i!==``){let e;try{e=new URL(i)}catch{throw new qi(`issuer`,`OAuth issuer must be an absolute HTTPS URL.`)}if(e.protocol!==`https:`||e.username!==``||e.password!==``||e.search!==``||e.hash!==``)throw new qi(`issuer`,`OAuth issuer must be an HTTPS URL without credentials, query, or fragment.`)}let a=e.clientID.trim();if(e.registrationMode===`static`&&a.length===0)throw new qi(`clientID`,`Enter the OAuth client ID.`);let o=e.callbackURI;if(o!==``){let e=/^http:\/\/(localhost|127(?:\.[0-9]{1,3}){3}|\[::1\]):([1-9][0-9]{0,4})(\/[^?#%\\\s]*)$/.exec(o);if(e===null||Number(e[2])>65535||!ea(e[3]??``)||new URL(o).pathname!==e[3]||e[1]?.startsWith(`127.`)&&e[1].split(`.`).some(e=>Number(e)>255||String(Number(e))!==e)||new TextEncoder().encode(o).byteLength>8192)throw new qi(`callbackURI`,`Use an exact HTTP localhost or numeric-loopback URI with an explicit port and canonical path, such as http://localhost:3118/callback. No credentials, query, fragment, or encoded path.`)}let s=e.authServerMetadataURL;if(s!==``){let e;try{e=new URL(s)}catch{throw new qi(`authServerMetadataURL`,`Enter an absolute HTTPS metadata URL.`)}if(e.protocol!==`https:`||e.username!==``||e.password!==``||s.includes(`#`)||e.href!==s||new TextEncoder().encode(s).byteLength>8192||!ea(e.pathname))throw new qi(`authServerMetadataURL`,`Use the exact canonical HTTPS metadata URL with a path, without credentials or fragment. A bounded query is allowed.`)}let c=e.scopes.map(e=>e.value);if(e.explicitScopes&&(c.length>64||c.some(e=>!/^[\x21\x23-\x5b\x5d-\x7e]{1,256}$/.test(e))||[...new Set(c)].join(` `).length>8192))throw new qi(`scopes`,`Enter one scope per row, without spaces, quotes, or backslashes. Remove unused rows. Use at most 64 ASCII scopes (256 bytes each, 8192 bytes total).`);r={mode:`oauth`,registration:e.registrationMode===`static`?{mode:`static`,issuer:i===``?null:i,client_id:a,token_endpoint_auth_method:e.tokenEndpointAuthMethod}:{mode:`dynamic`,issuer:i===``?null:i},trusted_origins:t,request_offline_access:e.requestOfflineAccess,...o===``?{}:{callback_uri:o},...s===``?{}:{auth_server_metadata_url:s},...e.explicitScopes?{scopes:[...new Set(c)].sort()}:{}}}return{kind:`streamable_http`,url:t,protocol_mode:e.protocolMode,...e.headers.length===0?{}:{headers:ua(e.headers)},authentication:r}}function fa(e){let t=oa();t.namespace=e.namespace,t.displayName=e.displayName,t.enabled=e.desiredState===`enabled`;let n=e.transport;if(n.kind===`stdio`)return t.transportKind=`stdio`,t.executable=n.executable,t.arguments=ra(`argument`,n.arguments),t.workingDirectory=n.working_directory,t.environment=ia(`environment`,n.environment),t.secretEnvironment=ia(`secret-environment`,n.secret_environment),t;t.transportKind=`streamable_http`,t.url=n.url,t.headers=ia(`header`,n.headers??{}),t.protocolMode=n.protocol_mode;let r=n.authentication;if(t.authMode=r.mode,t.authMode!==`oauth`)return t;let i=r.registration;return t.registrationMode=i.mode,t.issuer=i.issuer??``,t.clientID=i.client_id??``,t.tokenEndpointAuthMethod=i.token_endpoint_auth_method??`none`,t.trustedOrigins=ra(`oauth-origin`,r.trusted_origins),t.requestOfflineAccess=r.request_offline_access,t.callbackURI=r.callback_uri??``,t.authServerMetadataURL=r.auth_server_metadata_url??``,t.explicitScopes=r.scopes!==void 0,t.scopes=ra(`scope`,r.scopes??[]),t}function pa(e){return e===null?null:_i(e).id}async function ma(e,t){if(e.headers.get(`Content-Type`)!==`application/json`)throw Error(`invalid mutation response`);let n=await e.text();if(new TextEncoder().encode(n).byteLength>1048576)throw Error(`invalid mutation response`);let r=sa(JSON.parse(n));if(Object.keys(r).sort().join(`,`)!==`operation,server`)throw Error(`invalid mutation response`);let i=t(r.server),a=e.headers.get(`ETag`);if(a!==`"server-${i.id}-${i.desiredRevision}"`)throw Error(`invalid mutation response`);return{server:i,operationID:pa(r.operation),etag:a}}function ha({id:e,label:t,hint:n,itemLabel:r,addLabel:i,items:a,disabled:o,placeholder:s,errors:c={},error:l,onChange:u}){return U(`fieldset`,{class:`collection-field`,id:e,"aria-describedby":l===void 0?`${e}-hint`:`${e}-hint ${e}-error`,"aria-invalid":l!==void 0||void 0,children:[U(`legend`,{children:[t,U(`span`,{class:`optional-label`,children:` (optional)`})]}),U(`p`,{class:`field-hint`,id:`${e}-hint`,children:n}),l!==void 0&&U(`span`,{class:`field-error`,id:`${e}-error`,role:`alert`,children:l}),a.map((t,n)=>U(`div`,{class:`collection-row`,children:[U(`label`,{class:`visually-hidden`,for:`${e}-${t.id}`,children:[r,` `,n+1]}),U(`input`,{id:`${e}-${t.id}`,"data-testid":e,value:t.value,placeholder:s,disabled:o,"aria-invalid":c[t.id]===void 0&&l===void 0?void 0:!0,"aria-describedby":[`${e}-hint`,...l===void 0?[]:[`${e}-error`],...c[t.id]===void 0?[]:[`${e}-${t.id}-error`]].join(` `),onInput:e=>u(a.map(n=>n.id===t.id?{...n,value:e.currentTarget.value}:n))}),U(`button`,{type:`button`,disabled:o,"aria-label":`Remove ${r.toLowerCase()} ${n+1}`,onClick:()=>u(a.filter(e=>e.id!==t.id)),children:`Remove`}),c[t.id]!==void 0&&U(`span`,{class:`field-error collection-error`,id:`${e}-${t.id}-error`,role:`alert`,children:c[t.id]})]},t.id)),U(`button`,{type:`button`,class:`quiet-action`,"data-testid":`${e}-add`,disabled:o,onClick:()=>u([...a,{id:na(e),value:``}]),children:i})]})}function ga({id:e,label:t,hint:n,nameLabel:r,valueLabel:i,addLabel:a,valueRequired:o=!0,error:s,items:c,disabled:l,onChange:u}){return U(`fieldset`,{class:`collection-field`,"aria-describedby":s===void 0?`${e}-hint`:`${e}-hint ${e}-error`,"aria-invalid":s!==void 0||void 0,children:[U(`legend`,{children:[t,U(`span`,{class:`optional-label`,children:` (optional)`})]}),U(`p`,{class:`field-hint`,id:`${e}-hint`,children:n}),s!==void 0&&U(`span`,{class:`field-error`,id:`${e}-error`,role:`alert`,children:s}),c.map((n,a)=>U(`div`,{class:`collection-row collection-pair`,children:[U(`label`,{class:`visually-hidden`,for:`${e}-${n.id}-name`,children:[r,` `,a+1]}),U(`input`,{id:`${e}-${n.id}-name`,"data-testid":`${e}-name`,value:n.name,required:!0,placeholder:r,disabled:l,onInput:e=>u(c.map(t=>t.id===n.id?{...t,name:e.currentTarget.value}:t))}),U(`label`,{class:`visually-hidden`,for:`${e}-${n.id}-value`,children:[i,` `,a+1]}),U(`input`,{id:`${e}-${n.id}-value`,"data-testid":`${e}-value`,value:n.value,required:o,placeholder:i,disabled:l,onInput:e=>u(c.map(t=>t.id===n.id?{...t,value:e.currentTarget.value}:t))}),U(`button`,{type:`button`,disabled:l,"aria-label":`Remove ${t.toLowerCase()} row ${a+1}`,onClick:()=>u(c.filter(e=>e.id!==n.id)),children:`Remove`})]},n.id)),U(`button`,{type:`button`,class:`quiet-action`,"data-testid":`${e}-add`,disabled:l,onClick:()=>u([...c,{id:na(e),name:``,value:``}]),children:a})]})}function _a({draft:e,setDraft:t,disabled:n,namespaceLocked:r,urlError:i,issuerError:a,clientIDError:o,originErrors:s,compatibilityErrors:c,configurationError:l,clearFieldError:u}){let[d,f]=z(()=>e.issuer!==``||e.callbackURI!==``||e.authServerMetadataURL!==``||e.explicitScopes||e.trustedOrigins.length>0||e.requestOfflineAccess);B(()=>{let e=l?.field;(a!==void 0||Object.keys(c).some(e=>e!==`headers`)||Object.keys(s).length>0||e!==void 0&&[`transport.authentication.registration.issuer`,`transport.authentication.callback_uri`,`transport.authentication.auth_server_metadata_url`,`transport.authentication.scopes`,`transport.authentication.trusted_origins`,`transport.authentication.request_offline_access`].includes(e))&&f(!0)},[a,c,s,l]);let p=(n,r)=>t({...e,[n]:r});return U(S,{children:[U(`p`,{class:`form-convention`,children:`All fields are required unless marked optional.`}),U(J,{id:`server-namespace`,label:`Namespace`,hint:`Namespace cannot be changed after creation. It prefixes this server's tool names. Use 1–32 lowercase letters, digits, underscores, or hyphens, starting with a letter; mcp_gateway is reserved.`,required:!0,children:t=>U(`input`,{...t,placeholder:`example_tools`,value:e.namespace,disabled:n,readOnly:r,onInput:e=>p(`namespace`,e.currentTarget.value)})}),U(J,{id:`server-display-name`,label:`Display name`,hint:`A recognizable name for this server in Gateway. You can change it later.`,required:!0,children:t=>U(`input`,{...t,placeholder:`Example Tools`,value:e.displayName,disabled:n,onInput:e=>p(`displayName`,e.currentTarget.value)})}),U(J,{id:`server-enabled`,label:`Server enabled`,hint:`When enabled, Gateway will try to connect when you save this server. Leave disabled to finish configuring credentials first.`,children:t=>U(On,{attributes:t,checked:e.enabled,disabled:n,testID:`server-enabled`,onChange:e=>p(`enabled`,e)})}),U(`fieldset`,{class:`choice-field`,children:[U(`legend`,{children:`Connection method`}),U(`label`,{children:[U(`input`,{id:`server-transport-stdio`,name:`server-transport-kind`,type:`radio`,value:`stdio`,checked:e.transportKind===`stdio`,disabled:n,required:!0,onChange:()=>p(`transportKind`,`stdio`)}),U(`span`,{children:[U(`strong`,{children:`Local process (stdio)`}),U(`small`,{children:`Gateway launches a local executable.`})]})]}),U(`label`,{children:[U(`input`,{id:`server-transport-http`,name:`server-transport-kind`,type:`radio`,value:`streamable_http`,checked:e.transportKind===`streamable_http`,disabled:n,required:!0,onChange:()=>p(`transportKind`,`streamable_http`)}),U(`span`,{children:[U(`strong`,{children:`HTTP endpoint`}),U(`small`,{children:`Gateway connects to a Streamable HTTP server.`})]})]})]}),e.transportKind===`stdio`&&U(S,{children:[U(`p`,{class:`bounded-note`,children:`Gateway runs this executable directly as its operating-system user. It is not sandboxed.`}),U(J,{id:`server-executable`,label:`Executable`,hint:`Enter the full path to the executable on the Gateway host. Shell expressions such as ~ and $HOME are not expanded.`,required:!0,children:t=>U(`input`,{...t,placeholder:`/usr/local/bin/example-mcp-server`,value:e.executable,disabled:n,onInput:e=>p(`executable`,e.currentTarget.value)})}),U(J,{id:`server-working-directory`,label:`Working directory`,hint:`Enter the full path to the directory the process should run in, on the Gateway host.`,required:!0,children:t=>U(`input`,{...t,placeholder:`/opt/example-mcp-server`,value:e.workingDirectory,disabled:n,onInput:e=>p(`workingDirectory`,e.currentTarget.value)})}),U(ha,{id:`server-argument`,label:`Arguments`,hint:`Add one command-line argument per row, in order. Values are passed as written, without shell expansion or shell quoting.`,itemLabel:`Argument`,addLabel:`Add argument`,placeholder:`--verbose`,items:e.arguments,disabled:n,onChange:e=>p(`arguments`,e)}),U(ga,{id:`server-environment`,label:`Environment variables`,addLabel:`Add variable`,hint:`Add non-secret environment variables for the process. Use Secret environment bindings for passwords and tokens.`,nameLabel:`Variable name`,valueLabel:`Value`,valueRequired:!1,items:e.environment,disabled:n,onChange:e=>p(`environment`,e)}),U(ga,{id:`server-secret-environment`,label:`Secret environment bindings`,addLabel:`Add binding`,hint:r?`Map each environment variable to a credential slot name, not a secret value. Manage the matching secret under Authentication.`:`Map each environment variable to a credential slot name, not a secret value. After creating the server, add the matching secret under Authentication.`,nameLabel:`Environment variable`,valueLabel:`Credential slot`,items:e.secretEnvironment,disabled:n,onChange:e=>p(`secretEnvironment`,e)})]}),e.transportKind===`streamable_http`&&U(S,{children:[U(J,{id:`server-url`,label:`HTTP endpoint`,hint:`Enter the server's full MCP endpoint URL, including its path. Do not include credentials, a query string, or a fragment.`,...i===void 0?{}:{error:i},required:!0,children:t=>U(`input`,{...t,placeholder:`https://mcp.example.invalid/mcp`,value:e.url,disabled:n,onInput:e=>{u(`url`),p(`url`,e.currentTarget.value)}})}),U(ga,{id:`server-header`,label:`Custom HTTP headers`,hint:`Non-secret values only. Headers are stored in plaintext and visible to administrators. Never enter tokens, API keys, passwords, or cookies.`,nameLabel:`Header name`,valueLabel:`Header value`,addLabel:`Add header`,valueRequired:!1,items:e.headers,disabled:n,...c.headers===void 0?{}:{error:c.headers},onChange:e=>{u(`headers`),p(`headers`,e)}}),U(J,{id:`server-protocol-mode`,label:`Protocol preference`,hint:`Keep Automatic unless the provider requires a specific version. It tries the current protocol and uses legacy only if the server explicitly reports that the current version is unsupported.`,required:!0,children:t=>U(`select`,{...t,value:e.protocolMode,disabled:n,onChange:e=>p(`protocolMode`,e.currentTarget.value),children:[U(`option`,{value:`auto`,children:Qi.auto}),U(`option`,{value:`modern`,children:Qi.modern}),U(`option`,{value:`legacy`,children:Qi.legacy})]})}),U(`fieldset`,{class:`choice-field`,children:[U(`legend`,{children:`Authentication`}),U(`p`,{class:`field-hint`,children:`Choose the authentication method required by the server. Tokens and client secrets are managed separately and stored in the operating-system keyring, not in this form.`}),[[`none`,`No authentication`],[`bearer`,`Bearer token`],[`oauth`,`OAuth`]].map(([t,r])=>U(`label`,{children:[U(`input`,{id:`server-auth-${t}`,name:`server-auth-mode`,type:`radio`,value:t,checked:e.authMode===t,disabled:n,required:!0,onChange:()=>p(`authMode`,t)}),U(`span`,{children:r})]},t))]}),e.authMode===`bearer`&&U(`p`,{class:`bounded-note`,children:[r?`Manage this server's bearer token under Authentication.`:`After creating the server, add its bearer token under Authentication.`,` `,`Gateway stores it in the keyring and sends it in the Authorization header.`]}),e.authMode===`oauth`&&U(S,{children:[U(`p`,{class:`bounded-note`,children:[r?`Start or manage OAuth authorization under Authentication.`:`After creating the server, open Authentication to authorize Gateway with the provider.`,` `,`Gateway stores access and refresh tokens in the keyring.`]}),U(J,{id:`server-registration-mode`,label:`OAuth client registration`,hint:e.registrationMode===`dynamic`?`Gateway registers a client when you start authorization. The provider must support automatic client registration.`:`Use an OAuth application you have already registered with the provider. Enter its client details below.`,required:!0,children:t=>U(`select`,{...t,value:e.registrationMode,disabled:n,onChange:e=>p(`registrationMode`,e.currentTarget.value),children:[U(`option`,{value:`dynamic`,children:`Register Gateway automatically`}),U(`option`,{value:`static`,children:`Use an existing OAuth client`})]})}),e.registrationMode===`static`&&U(S,{children:[U(J,{id:`server-client-id`,label:`Client ID`,hint:`Enter the client ID assigned when you registered your OAuth application with the provider. This is not the client secret.`,...o===void 0?{}:{error:o},required:!0,children:t=>U(`input`,{...t,placeholder:`example-gateway-client`,value:e.clientID,disabled:n,onInput:e=>{u(`clientID`),p(`clientID`,e.currentTarget.value)}})}),U(J,{id:`server-token-auth`,label:`Token endpoint authentication`,hint:`Choose the method configured for your OAuth application. For either client-secret method, add the secret separately under Authentication.`,required:!0,children:t=>U(`select`,{...t,value:e.tokenEndpointAuthMethod,disabled:n,onChange:e=>p(`tokenEndpointAuthMethod`,e.currentTarget.value),children:[U(`option`,{value:`none`,children:$i.none}),U(`option`,{value:`client_secret_basic`,children:$i.client_secret_basic}),U(`option`,{value:`client_secret_post`,children:$i.client_secret_post})]})})]}),U(`details`,{class:`form-disclosure`,open:d,onToggle:e=>f(e.currentTarget.open),children:[U(`summary`,{children:d?`Hide advanced OAuth settings`:`Show advanced OAuth settings`}),U(J,{id:`server-issuer`,label:`OAuth issuer URL`,hint:`Enter the exact HTTPS issuer URL from your provider's OAuth documentation, not its authorization or token endpoint. You can leave this blank if the MCP server advertises exactly one issuer with the same scheme, hostname, and port as its HTTP endpoint.`,...a===void 0?{}:{error:a},optional:!0,children:t=>U(`input`,{...t,placeholder:`https://auth.example.invalid`,value:e.issuer,disabled:n,onInput:e=>{u(`issuer`),p(`issuer`,e.currentTarget.value)}})}),U(J,{id:`server-callback-uri`,label:`Callback URI`,optional:!0,hint:`Leave blank to use Gateway's default callback. To use a different callback, enter the exact HTTP loopback redirect URL registered with your provider, including port and path. That port must be free; Gateway listens there only during authorization.`,...c.callbackURI===void 0?{}:{error:c.callbackURI},children:t=>U(`input`,{...t,value:e.callbackURI,disabled:n,placeholder:`http://localhost:3118/callback`,onInput:e=>{u(`callbackURI`),p(`callbackURI`,e.currentTarget.value)}})}),U(J,{id:`server-auth-metadata-url`,label:`Authorization metadata URL`,optional:!0,hint:`Leave blank for standard OAuth discovery. Set this only if your provider specifies a different HTTPS metadata URL. It does not change the issuer; if this URL fails, Gateway will not try another location.`,...c.authServerMetadataURL===void 0?{}:{error:c.authServerMetadataURL},children:t=>U(`input`,{...t,placeholder:`https://auth.example.invalid/.well-known/oauth-authorization-server`,value:e.authServerMetadataURL,disabled:n,onInput:e=>{u(`authServerMetadataURL`),p(`authServerMetadataURL`,e.currentTarget.value)}})}),U(`label`,{class:`checkbox-field`,for:`server-explicit-scopes`,children:[U(`input`,{id:`server-explicit-scopes`,type:`checkbox`,checked:e.explicitScopes,disabled:n,onChange:e=>p(`explicitScopes`,e.currentTarget.checked)}),U(`span`,{children:[U(`strong`,{children:`Configure initial scopes explicitly`}),U(`small`,{children:`Leave off to use the MCP server's advertised defaults. Turn on to choose scopes below; an empty list requests no initial scopes. Offline access is controlled separately.`})]})]}),e.explicitScopes&&U(ha,{id:`server-initial-scopes`,label:`Initial scopes`,hint:`Add scope names from your provider's documentation, one per row. These replace the server's defaults; duplicates are removed. Adding permissions later requires authorizing the server again.`,itemLabel:`Scope`,addLabel:`Add scope`,placeholder:`read:tools`,items:e.scopes,disabled:n,...c.scopes===void 0?{}:{error:c.scopes},onChange:e=>{u(`scopes`),p(`scopes`,e)}}),U(ha,{id:`server-oauth-origin`,label:`Additional OAuth origins allowed on restricted networks`,hint:`Allow OAuth connections to additional private-network or loopback hosts. Enter each HTTPS origin (scheme, hostname, and optional port), without a path. The MCP server's origin is already allowed. This does not relax TLS checks or browser access rules.`,itemLabel:`OAuth origin`,addLabel:`Add OAuth origin`,placeholder:`https://auth.example.invalid`,items:e.trustedOrigins,disabled:n,errors:s,onChange:e=>{u(`origin`),p(`trustedOrigins`,e)}}),U(`label`,{class:`checkbox-field`,for:`server-offline-access`,children:[U(`input`,{id:`server-offline-access`,type:`checkbox`,checked:e.requestOfflineAccess,disabled:n,onChange:e=>p(`requestOfflineAccess`,e.currentTarget.checked)}),U(`span`,{children:[U(`strong`,{children:`Request offline access when supported`}),U(`small`,{children:`Ask for offline_access so Gateway can refresh access without another sign-in. Gateway requests it only if the provider advertises support; a refresh token is not guaranteed.`})]})]})]})]})]})]})}function va({draft:e}){let t=e.transportKind===`stdio`?`Local process — ${e.executable}`:`HTTP — ${e.url.trim()}`,n=e.transportKind===`stdio`?`Not applicable`:e.authMode===`none`?`No authentication`:e.authMode===`bearer`?`Bearer token`:`OAuth`,r=e=>e.length===0?`None`:e.map(e=>e.value).join(`, `),i=(e,t)=>e.length===0?`None`:e.map(e=>`${e.name}${t}${e.value}`).join(`, `);return U(`div`,{"data-testid":`server-creation-review`,children:[U(`h3`,{children:`Identity`}),U(`dl`,{class:`review-list`,children:[U(`div`,{children:[U(`dt`,{children:`Namespace`}),U(`dd`,{children:e.namespace})]}),U(`div`,{children:[U(`dt`,{children:`Display name`}),U(`dd`,{children:e.displayName})]}),U(`div`,{children:[U(`dt`,{children:`Initial state`}),U(`dd`,{children:e.enabled?`Enabled`:`Disabled`})]})]}),U(`h3`,{children:`Connection`}),U(`dl`,{class:`review-list`,"data-testid":`server-connection-review`,children:[U(`div`,{children:[U(`dt`,{children:`Connection`}),U(`dd`,{children:t})]}),e.transportKind===`stdio`?U(S,{children:[U(`div`,{children:[U(`dt`,{children:`Working directory`}),U(`dd`,{children:e.workingDirectory})]}),U(`div`,{children:[U(`dt`,{children:`Arguments`}),U(`dd`,{children:r(e.arguments)})]}),U(`div`,{children:[U(`dt`,{children:`Environment`}),U(`dd`,{children:i(e.environment,`=`)})]}),U(`div`,{children:[U(`dt`,{children:`Secret bindings`}),U(`dd`,{children:i(e.secretEnvironment,` → `)})]})]}):U(S,{children:[U(`div`,{children:[U(`dt`,{children:`Protocol`}),U(`dd`,{children:Qi[e.protocolMode]})]}),U(`div`,{children:[U(`dt`,{children:`Custom HTTP headers (plaintext)`}),U(`dd`,{children:i(e.headers,`: `)})]})]})]}),e.transportKind!==`stdio`&&U(S,{children:[U(`h3`,{children:`Authentication`}),U(`dl`,{class:`review-list`,"data-testid":`server-authentication-review`,children:[U(`div`,{children:[U(`dt`,{children:`Authentication`}),U(`dd`,{children:n})]}),e.authMode===`oauth`&&U(S,{children:[U(`div`,{children:[U(`dt`,{children:`OAuth registration`}),U(`dd`,{children:e.registrationMode===`dynamic`?`Register Gateway automatically`:`Existing client ${e.clientID.trim()} (${$i[e.tokenEndpointAuthMethod]})`})]}),U(`div`,{children:[U(`dt`,{children:`OAuth issuer`}),U(`dd`,{children:e.issuer.trim()===``?`Discover from same-origin metadata`:e.issuer.trim()})]}),U(`div`,{children:[U(`dt`,{children:`OAuth network origins`}),U(`dd`,{children:r(e.trustedOrigins.map(e=>({...e,value:e.value.trim()})))})]}),U(`div`,{children:[U(`dt`,{children:`Callback URI`}),U(`dd`,{children:e.callbackURI===``?`Gateway main callback`:e.callbackURI})]}),U(`div`,{children:[U(`dt`,{children:`Authorization metadata URL`}),U(`dd`,{children:e.authServerMetadataURL===``?`Standard discovery`:e.authServerMetadataURL})]}),U(`div`,{children:[U(`dt`,{children:`Initial scopes`}),U(`dd`,{children:e.explicitScopes?e.scopes.length===0?`No initial scopes (explicit)`:[...new Set(e.scopes.map(e=>e.value))].sort().join(` `):`Server-advertised defaults`})]}),U(`div`,{children:[U(`dt`,{children:`Offline access`}),U(`dd`,{children:e.requestOfflineAccess?`Request when advertised`:`Do not request`})]})]})]})]}),U(`p`,{children:`The namespace is permanent. If enabled, Gateway will try to connect after the server is created.`})]})}function ya({mutations:e,server:t,etag:n,onRefresh:r,notify:i,decodeServerValue:a}){let o=t===void 0,s=V(o?oa():fa(t)),[c,l]=z(s.current),[u,d]=z(),[f,p]=z(),[m,h]=z(),[g,_]=z(),[v,y]=z({}),[b,x]=z({}),[C,w]=z(),[T,E]=z(),[D]=z(()=>e.create()),[O,k]=z(()=>D.snapshot()),A=V(null),j=e=>ca({display_name:e.displayName,enabled:e.enabled,transport:la(da(e))}),M=(()=>{try{return j(c)!==j(s.current)}catch{return ca(c)!==ca(s.current)}})(),N=Cr(M);B(()=>D.subscribe(k),[D]),B(()=>()=>D.close(),[D]),B(()=>{if(t===void 0)return;let e=fa(t);s.current=e,l(e)},[t?.id]);let ee=async e=>{let t=await e;t.kind===`acknowledged`?(E(void 0),w(void 0),i(o?`Server created.`:t.value.operationID===null?`Server settings saved.`:`Server settings saved; applying changes.`),D.abandon(),s.current=c,l({...c}),o?N(`#/mcp/servers/${t.value.server.id}`,!0):(r(),N(t.value.operationID===null?`#/mcp/servers/${t.value.server.id}`:`#/mcp/servers/${t.value.server.id}/operations/${t.value.operationID}`,!0))):t.kind===`rejected`&&t.requiresRefresh&&!o&&E(n)},P=e=>{e===`url`?p(void 0):e===`issuer`?h(void 0):e===`clientID`?_(void 0):e===`origin`?y({}):x({})},te=()=>{d(void 0),p(void 0),h(void 0),_(void 0),y({}),x({}),w(void 0);try{if(!Ji.test(c.namespace)||c.namespace===`mcp_gateway`)throw Error(`Namespace must be a permitted lowercase routing identity.`);if(c.displayName.length===0||new TextEncoder().encode(c.displayName).byteLength>256)throw Error(`Display name must contain 1–256 UTF-8 bytes.`);let e=da(c);if(o)return{behavioral:!0,spec:{route:`/api/v2/mcp/servers`,method:`POST`,body:JSON.stringify({namespace:c.namespace,display_name:c.displayName,enabled:c.enabled,transport:e}),precondition:null,requiresPrecondition:!1,idempotency:`server_create`,successStatuses:[200,201],decode:e=>ma(e,a)}};if(n===void 0)throw Error(`Refresh the current server revision before editing.`);let r=c.enabled!==(t.desiredState===`enabled`)||la(e)!==la(t.transport),i=r?{display_name:c.displayName,enabled:c.enabled,transport:e}:{display_name:c.displayName};return{behavioral:r,spec:{route:`/api/v2/mcp/servers/${t.id}`,method:`PATCH`,body:JSON.stringify(i),precondition:n,requiresPrecondition:!0,idempotency:`none`,successStatuses:[200],decode:e=>ma(e,a)}}}catch(e){let t=e instanceof Error?e.message:`Invalid server configuration.`;e instanceof qi?e.field===`url`?p(t):e.field===`issuer`?h(t):e.field===`clientID`?_(t):e.itemID===void 0?x({[e.field]:t}):y({[e.itemID]:t}):d(t);return}},F=()=>{let e=te();e!==void 0&&(D.begin(e.spec),e.behavioral?D.confirm():ee(D.submit()))},ne=!o&&T!==void 0&&T===n,I=O.state===`submitting`||O.availability===`storage_latched`||ne,re=U(S,{children:[U(`form`,{onSubmit:e=>{e.preventDefault(),F()},"data-testid":`server-editor`,children:[U(_a,{draft:c,setDraft:l,disabled:I,namespaceLocked:!o,urlError:f,issuerError:m,clientIDError:g,originErrors:v,compatibilityErrors:b,configurationError:O.problem?.context,clearFieldError:P}),u!==void 0&&U(K,{state:`error`,title:`Check server configuration`,children:U(`p`,{children:u})}),O.problem!==void 0&&U(K,{state:`error`,title:O.problem.title,children:[O.problem.context!==void 0&&U(`p`,{children:ta(O.problem.context)}),O.requiresRefresh&&!o&&U(`p`,{children:`A current server reload was requested. Your safe nonsecret draft is preserved; review it after the reload succeeds.`})]}),ne&&U(`p`,{class:`session-message`,role:`status`,children:`Waiting for a refreshed server revision before another submission.`}),O.state===`uncertain`&&U(K,{state:`warning`,title:`Mutation outcome unknown`,children:U(`p`,{children:O.canReplay?`The same create may be replayed explicitly with its retained in-memory idempotency key.`:`Inspect the authoritative server record before making another change.`})}),C!==void 0&&U(`p`,{class:`session-message`,role:`status`,children:C}),O.availability===`storage_latched`&&U(K,{state:`unavailable`,title:`Mutations closed by storage latch`}),U(`button`,{ref:A,class:`${o?`create-action`:`primary-action`} form-submit-action`,type:`submit`,disabled:I||!o&&!M||O.state===`uncertain`,"data-testid":`server-editor-submit`,children:o?`Review and create`:`Save settings`}),O.canReplay&&U(`button`,{type:`button`,"data-testid":`server-create-replay`,onClick:()=>void ee(D.replay()),children:`Replay this same create`})]}),U(jn,{id:`server-change-confirm`,open:O.state===`confirming`,title:o?`Review server`:`Apply behavioral server change?`,consequence:o?U(va,{draft:c}):`Changing desired state or transport interrupts current server routing and schedules reconciliation.`,confirmLabel:o?`Create server`:`Apply behavioral change`,destructive:!o,returnFocus:A,onCancel:()=>D.abandon(),onConfirm:()=>void ee(D.submit())})]});return o?U(`section`,{class:`panel domain-panel`,"aria-labelledby":`server-editor-title`,children:[U(`div`,{class:`panel-heading`,children:U(`div`,{children:U(`h2`,{id:`server-editor-title`,children:`Create MCP Server`})})}),re]}):U(`section`,{class:`panel domain-panel`,"aria-labelledby":`server-editor-title`,children:[U(`div`,{class:`panel-heading`,children:U(`h2`,{id:`server-editor-title`,children:`Edit server`})}),re]})}function ba(e,t){if(t!==void 0&&!bi(t))return t.kind===`refresh_catalog`&&t.targetDesiredRevision===e.desiredRevision?[`refresh_catalog`]:[];let n=[];return e.desiredState===`enabled`&&(e.runtimeState===`inactive`||e.runtimeState===`active`)&&n.push(`reload`),(e.desiredState===`enabled`&&[`retry_wait`,`degraded`,`authentication_required`].includes(e.runtimeState)||e.credentialState===`cleanup_pending`||(e.desiredState===`disabled`||e.desiredState===`deleted`)&&e.runtimeReason===`stop_unconfirmed`)&&n.push(`retry`),e.desiredState===`enabled`&&e.runtimeState===`active`&&(e.activeState===`current`||e.activeState===`stale`)&&n.push(`refresh_catalog`),e.desiredState!==`deleted`&&(e.staticRevision!==`0`||e.oauthClientRevision!==`0`||e.oauthTokensRevision!==`0`)&&n.push(`disconnect_credentials`),n}function xa(e){switch(e){case`activate`:return`Connect server`;case`reload`:return`Reload server`;case`retry`:return`Retry server operation`;case`refresh_catalog`:return`Refresh tools`;case`credential_replace`:return`Replace credential`;case`disable`:return`Disable server`;case`delete`:return`Delete server`;case`disconnect_credentials`:return`Disconnect credentials`}}function Sa(e){let t=e.replaceAll(`_`,` `);return t.charAt(0).toLocaleUpperCase()+t.slice(1)}function Ca(e){return bi(e)?e.state===`succeeded`?`current`:e.state===`failed`?`error`:e.state===`interrupted`?`warning`:`neutral`:`loading`}function wa(e){return e===`reload`||e===`disconnect_credentials`}function Ta(e){return e===`reload`?`Reload withdraws current routing while the server restarts. Calls already handed downstream may have unknown outcomes.`:`Disconnect invalidates local credential authority and withdraws affected routing. Remote revocation is best effort and is not guaranteed.`}function Ea({serverID:e,items:t,controls:n}){return U(Dn,{caption:`Server activity`,layout:`activity`,rowHeaderKey:`action`,additionalSorts:[{key:`started`,label:`Started (created if queued)`,sortValue:e=>e.startedAt??e.createdAt}],remote:n,itemNames:{singular:`operation`,plural:`operations`},emptyTitle:`No retained operations`,items:t,rowKey:e=>e.id,rowTestID:`operation-row`,filters:[{key:`action`,label:`Operation`,type:`select`,value:e=>e.kind,options:[{value:`activate`,label:`Connect server`},{value:`reload`,label:`Reload server`},{value:`retry`,label:`Retry server operation`},{value:`refresh_catalog`,label:`Refresh tools`},{value:`credential_replace`,label:`Replace credential`},{value:`disable`,label:`Disable server`},{value:`delete`,label:`Delete server`},{value:`disconnect_credentials`,label:`Disconnect credentials`}]},{key:`status`,label:`Status`,type:`select`,value:e=>e.state,options:[{value:`scheduled`,label:`Scheduled`},{value:`running`,label:`Running`},{value:`succeeded`,label:`Succeeded`},{value:`failed`,label:`Failed`},{value:`interrupted`,label:`Interrupted`},{value:`cancelled`,label:`Cancelled`},{value:`superseded`,label:`Superseded`}]}],initialSort:{key:`created`,direction:`descending`},columns:[{key:`created`,label:`Created`,role:`time`,sortValue:e=>e.createdAt,render:e=>U(Y,{value:e.createdAt})},{key:`action`,label:`Operation`,role:`identity`,sortValue:e=>xa(e.kind),render:t=>U(q,{primary:U(`a`,{href:`#/mcp/servers/${e}/operations/${t.id}`,children:xa(t.kind)}),secondary:t.id})},{key:`status`,label:`Status`,role:`status`,sortValue:e=>e.state,render:e=>U(G,{state:Ca(e),children:Sa(e.state)})},{key:`outcome`,label:`Reason`,role:`text`,sortValue:e=>e.reason??``,render:e=>e.reason===null?`—`:Sa(e.reason)}]})}function Da({mutations:e,server:t,etag:n,readVersion:r,activeOperation:i,activeCurrent:a,activeRefreshing:o,multipleActive:s}){let[c]=z(()=>e.create()),[l,u]=z(()=>c.snapshot()),[d,f]=z(),[p,m]=z(),[h,g]=z(),_=V(null);B(()=>c.subscribe(u),[c]),B(()=>()=>c.close(),[c]);let v=e=>({route:`/api/v2/mcp/servers/${t.id}/operations`,method:`POST`,body:JSON.stringify({kind:e}),precondition:n,requiresPrecondition:!0,idempotency:`operation_start`,successStatuses:[200,202],decode:yi}),y=async e=>{let n=await e;n.kind===`acknowledged`?(m(void 0),g(`Operation ${n.value.id} was accepted.`),c.abandon(),window.location.hash=`#/mcp/servers/${t.id}/operations/${n.value.id}`):n.kind===`rejected`&&n.requiresRefresh&&m(r)},b=(e,t)=>{_.current=t,f(e),g(void 0),c.begin(v(e)),wa(e)?c.confirm():y(c.submit())},x=p!==void 0&&r<=p,S=!a||l.state===`submitting`||l.availability===`storage_latched`||x,C=s?[]:ba(t,i);return U(`section`,{class:`panel domain-panel`,"aria-labelledby":`operation-start-title`,"aria-busy":o?`true`:void 0,children:[U(`div`,{class:`panel-heading`,children:U(`div`,{children:U(`h2`,{id:`operation-start-title`,children:`Available actions`})})}),i!==void 0&&U(K,{state:`warning`,title:a||o?`Active server work`:`Last observed active work`,children:U(`p`,{children:[U(`a`,{"data-testid":`active-operation-link`,href:`#/mcp/servers/${t.id}/operations/${i.id}`,children:[xa(i.kind),` — `,Sa(i.state)]}),s?` and additional active work`:``,`. This work may block new actions.`]})}),!a&&!o&&U(K,{state:`loading`,title:`Active-work status is not current`,children:`Actions require a successful authoritative refresh.`}),C.length===0?U(K,{state:`empty`,title:`No actions are currently available`}):U(`div`,{class:`action-list`,children:C.map(e=>U(`button`,{class:e===`disconnect_credentials`?`danger-action`:`safe-action`,type:`button`,"data-testid":`start-operation-${e}`,disabled:S,onClick:t=>b(e,t.currentTarget),children:xa(e)},e))}),l.problem!==void 0&&U(K,{state:`error`,title:l.problem.title,children:l.requiresRefresh&&U(`p`,{children:`A fresh server and operation snapshot was requested. Review the selected operation before starting a new intent.`})}),p!==void 0&&!x&&(a||o)&&U(`p`,{class:`session-message`,role:`status`,children:i===void 0?`Refreshed state: no active operation remains. Review available actions before starting a new intent.`:`Refreshed state: active work is identified above.`}),x&&U(`p`,{class:`session-message`,role:`status`,children:`Waiting for a newer authoritative operation snapshot.`}),l.state===`uncertain`&&U(K,{state:`warning`,title:`Operation start outcome unknown`,children:U(`p`,{children:`Inspect operation history before using Replay this same operation start.`})}),l.canReplay&&U(`button`,{type:`button`,"data-testid":`operation-start-replay`,onClick:()=>void y(c.replay()),children:`Replay this same operation start`}),h!==void 0&&U(`p`,{class:`session-message`,role:`status`,children:h}),d!==void 0&&U(jn,{id:`operation-start-confirm`,open:l.state===`confirming`,title:`${xa(d)}?`,consequence:Ta(d),confirmLabel:xa(d),destructive:d===`disconnect_credentials`,returnFocus:_,onCancel:()=>c.abandon(),onConfirm:()=>void y(c.submit())})]})}function Oa({mutations:e,server:t,etag:n,readVersion:r,operations:i,operation:a,activeCurrent:o=!1,activeRefreshing:s=!1,multipleActive:c=!1,history:l}){return a===void 0?U(S,{children:[U(Da,{mutations:e,server:t,etag:n,readVersion:r,activeOperation:i.find(e=>!bi(e)),activeCurrent:o,activeRefreshing:s,multipleActive:c}),l!==void 0&&U(`section`,{class:`panel domain-panel`,"aria-labelledby":`operation-list-title`,"data-testid":`operation-list`,children:[U(`div`,{class:`panel-heading`,children:U(`div`,{children:U(`h2`,{id:`operation-list-title`,children:`Operation history`})})}),l]})]}):U(`div`,{"data-testid":`operation-detail`,children:[U(`nav`,{class:`detail-navigation`,"aria-label":`Operation navigation`,children:U(`a`,{href:`#/mcp/servers/${t.id}?tab=operations`,children:`Back to server operations`})}),U(`header`,{class:`detail-context`,"data-testid":`detail-context`,children:[U(`div`,{class:`detail-context-heading`,children:[U(`h1`,{id:`operation-detail-title`,tabindex:-1,children:xa(a.kind)}),U(G,{state:Ca(a),children:Sa(a.state)})]}),U(`p`,{class:`technical-value`,children:a.id})]}),U(`section`,{class:`detail-section`,"aria-labelledby":`operation-facts-title`,children:[U(`h3`,{id:`operation-facts-title`,children:`Operation details`}),U(`dl`,{class:`detail-list`,children:[U(`div`,{children:[U(`dt`,{children:`Created`}),U(`dd`,{children:U(Y,{value:a.createdAt})})]}),U(`div`,{children:[U(`dt`,{children:`Started`}),U(`dd`,{children:U(Y,{value:a.startedAt,fallback:`Not started`})})]}),U(`div`,{children:[U(`dt`,{children:`Finished`}),U(`dd`,{children:U(Y,{value:a.finishedAt,fallback:bi(a)?`Not recorded`:`In progress`})})]}),a.reason!==null&&U(`div`,{children:[U(`dt`,{children:`Reason`}),U(`dd`,{children:Sa(a.reason)})]})]})]})]})}var ka=/^[0-7][0-9A-HJKMNP-TV-Z]{25}$/;function Aa(e){let t=H(e);if(t?.destination===`catalog`)return`catalog`;if(t?.destination===`servers`){if(t.segments.length===1)return`servers`;if(t.segments.length===2&&t.query.tab===`tools`)return`descriptors`}}function ja(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`invalid response`);let n=e;if(Object.keys(n).sort().join(`,`)!==[...t].sort().join(`,`))throw Error(`invalid response`);return n}function Ma(e,t,n){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`invalid response`);let r=e,i=Object.keys(r);if(t.some(e=>!Object.hasOwn(r,e))||i.some(e=>!t.includes(e)&&!n.includes(e)))throw Error(`invalid response`);return r}function X(e){if(typeof e!=`string`)throw Error(`invalid response`);return e}function Na(e){if(e!==null&&typeof e!=`string`)throw Error(`invalid response`);return e}function Pa(e){if(typeof e!=`boolean`)throw Error(`invalid response`);return e}function Fa(e){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<0)throw Error(`invalid response`);return e}function Ia(e){let t=X(e);if(!ka.test(t))throw Error(`invalid response`);return t}function La(e,t){let n=X(e);if(!t.includes(n))throw Error(`invalid response`);return n}function Ra(e){if(!Array.isArray(e))throw Error(`invalid response`);return e}function za(e){let t=Na(e);if(t!==null&&(t.length===0||t.length>4096))throw Error(`invalid response`);return t}function Ba(e){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`invalid response`);return e}function Va(e){let t=ja(e,[`in_use`,`limit`,`saturated`]);return{inUse:Fa(t.in_use),limit:Fa(t.limit),saturated:Pa(t.saturated)}}function Ha(e){if(e===null)return null;let t=e;if(La(t.kind,[`stdio`,`streamable_http`])===`stdio`){let t=ja(e,[`kind`,`executable`,`arguments`,`working_directory`,`environment`,`secret_environment`]);X(t.executable),X(t.working_directory),Ra(t.arguments).forEach(X);for(let e of[t.environment,t.secret_environment]){let t=Ma(e,[],Object.keys(e));Object.values(t).forEach(X)}return e}let n=ja(e,[`kind`,`url`,`protocol_mode`,`authentication`,...Object.hasOwn(t,`headers`)?[`headers`]:[]]);if(n.headers!==void 0){let e=n.headers;if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`invalid HTTP headers`);let t=Ma(e,[],Object.keys(e));Object.values(t).forEach(X)}X(n.url),La(n.protocol_mode,[`modern`,`legacy`,`auto`]);let r=n.authentication,i=La(r.mode,[`none`,`bearer`,`oauth`]);if(i===`none`||i===`bearer`)return ja(n.authentication,[`mode`]),e;let a=ja(n.authentication,[`mode`,`registration`,`trusted_origins`,`request_offline_access`,...[`callback_uri`,`auth_server_metadata_url`,`scopes`].filter(e=>Object.hasOwn(r,e))]);a.callback_uri!==void 0&&X(a.callback_uri),a.auth_server_metadata_url!==void 0&&X(a.auth_server_metadata_url),a.scopes!==void 0&&Ra(a.scopes).forEach(X),Ra(a.trusted_origins).forEach(X),Pa(a.request_offline_access);let o=a.registration;if(La(o.mode,[`static`,`dynamic`])===`dynamic`)Na(ja(a.registration,[`mode`,`issuer`]).issuer);else{let e=ja(a.registration,[`mode`,`issuer`,`client_id`,`token_endpoint_auth_method`]);Na(e.issuer),X(e.client_id),La(e.token_endpoint_auth_method,[`none`,`client_secret_basic`,`client_secret_post`])}return e}var Ua=`configuration_invalid.resource_limit.connectivity.tls_failed.protocol_unsupported.protocol_invalid.authentication_rejected.credential_absent.keyring_absent.keyring_locked.keyring_interaction_required.keyring_unavailable.keyring_unsupported.oauth_rejected.oauth_expired.registration_expired.process_exited.output_limit.stop_unconfirmed.catalog_invalid.catalog_limit.catalog_stale.superseded.cancelled.interrupted.revocation_failed.revocation_unsupported.cleanup_pending`.split(`.`);function Wa(e){let t=ja(e,[`id`,`namespace`,`display_name`,`desired_state`,`desired_revision`,`transport`,`credential_revisions`,`credential_state`,`runtime`,`catalog`,`created_at`,`updated_at`,`deleted_at`]),n=ja(t.credential_revisions,[`static_credential`,`oauth_client`,`oauth_tokens`]),r=Ma(t.runtime,[`state`,`reason`,`runtime_id`,`reconciliation`,`dispatch`],[`diagnostic_correlation`]),i=Na(r.reason);i!==null&&La(i,Ua);let a=ja(t.catalog,[`durable_state`,`active_state`,`durable_revision`,`active_revision`,`durable_tool_count`,`active_tool_count`,`last_success_at`,`traversal`]);return{id:Ia(t.id),namespace:X(t.namespace),displayName:X(t.display_name),desiredState:La(t.desired_state,[`enabled`,`disabled`,`deleted`]),desiredRevision:X(t.desired_revision),transport:Ha(t.transport),staticRevision:X(n.static_credential),oauthClientRevision:X(n.oauth_client),oauthTokensRevision:X(n.oauth_tokens),credentialState:La(t.credential_state,[`not_required`,`ready`,`absent`,`locked`,`interaction_required`,`unavailable`,`unsupported`,`refreshing`,`reauthentication_required`,`disconnecting`,`cleanup_pending`]),runtimeState:La(r.state,[`inactive`,`activating`,`active`,`stopping`,`retry_wait`,`degraded`,`authentication_required`,`deleted`]),runtimeReason:i,runtimeID:Na(r.runtime_id),diagnosticCorrelation:br(r.diagnostic_correlation),reconciliation:Va(r.reconciliation),dispatch:Va(r.dispatch),durableState:La(a.durable_state,[`empty`,`current`,`stale`,`unavailable`,`retired`]),activeState:La(a.active_state,[`absent`,`refreshing`,`current`,`stale`,`unavailable`]),durableRevision:Na(a.durable_revision),activeRevision:Na(a.active_revision),durableToolCount:Fa(a.durable_tool_count),activeToolCount:Fa(a.active_tool_count),lastSuccessAt:Na(a.last_success_at),traversal:Va(a.traversal),createdAt:X(t.created_at),updatedAt:X(t.updated_at),deletedAt:Na(t.deleted_at)}}function Ga(e){let t=ja(e,[`items`,`next_cursor`]);return{items:Ra(t.items).map(Wa),nextCursor:za(t.next_cursor)}}function Ka(e,t=!1){let n=[`id`,`server_id`,`upstream_name`,`external_name`,`descriptor`,`fingerprint`,`catalog_revision`,`first_seen_at`,`last_seen_at`,`retired_at`];t&&n.push(`server_display_name`,`server_catalog_state`);let r=ja(e,n),i=Ma(r.descriptor,[`name`,`inputSchema`,`annotations`],[`title`,`description`,`outputSchema`]);X(i.name),i.title!==void 0&&X(i.title),i.description!==void 0&&X(i.description),Ba(i.inputSchema),i.outputSchema!==void 0&&Ba(i.outputSchema);let a=ja(i.annotations,[`title`,`readOnlyHint`,`destructiveHint`,`idempotentHint`,`openWorldHint`]);Na(a.title);for(let e of[`readOnlyHint`,`destructiveHint`,`idempotentHint`,`openWorldHint`])Pa(a[e]);let o={id:Ia(r.id),serverID:Ia(r.server_id),upstreamName:X(r.upstream_name),externalName:X(r.external_name),descriptor:r.descriptor,fingerprint:X(r.fingerprint),catalogRevision:X(r.catalog_revision),firstSeenAt:X(r.first_seen_at),lastSeenAt:X(r.last_seen_at),retiredAt:Na(r.retired_at)};return t?{...o,serverDisplayName:X(r.server_display_name),serverCatalogState:La(r.server_catalog_state,[`refreshing`,`current`,`stale`,`unavailable`])}:o}function qa(e){return Ka(e)}function Ja(e){let t=ja(e,[`items`,`next_cursor`]);return{items:Ra(t.items).map(e=>Ka(e)),nextCursor:za(t.next_cursor)}}function Ya(e){let t=ja(e,[`catalog`,`items`,`next_cursor`]),n=ja(t.catalog,[`active_state`,`active_generation`,`changed_at`,`issue_count`]);return{catalog:{activeState:La(n.active_state,[`empty`,`current`,`degraded`]),activeGeneration:X(n.active_generation),changedAt:Na(n.changed_at),issueCount:Fa(n.issue_count)},page:{items:Ra(t.items).map(e=>Ka(e,!0)),nextCursor:za(t.next_cursor)}}}async function Xa(e,t){let n=await fetch(t,{method:`GET`,headers:{"X-CSRF-Token":e.csrfToken},credentials:`same-origin`,redirect:`error`,signal:e.signal});if(await e.sessionLost(n))throw Error(`session lost`);return n}async function Za(e){if(e.status!==200||e.headers.get(`Content-Type`)!==`application/json`)throw Error(`read failed`);let t=await e.text();if(new TextEncoder().encode(t).byteLength>4194304)throw Error(`response too large`);return JSON.parse(t)}async function Qa(e){if(e.status!==409||e.headers.get(`Content-Type`)!==`application/problem+json`)return!1;let t=await e.text();if(new TextEncoder().encode(t).byteLength>65536)return!1;try{let e=ja(JSON.parse(t),[`status`,`code`,`title`]);return e.status===409&&X(e.code)===`stale_cursor`&&X(e.title).length>0}catch{return!1}}function $a(e=``){return{viewKey:e,servers:[],serverNext:null,server:void 0,serverETag:void 0,descriptors:[],descriptorNext:null,descriptor:void 0,catalog:void 0,catalogItems:[],catalogNext:null,operations:[],operationNext:null,activeMore:!1,operation:void 0,authFlows:[],authFlowNext:null,authFlow:void 0,readVersion:0,loadingMore:!1,restarted:!1}}function eo(e,t,n){let r=new URLSearchParams;if(r.set(`limit`,`50`),n!==null&&r.set(`cursor`,n),e===`servers`)return`/api/v2/mcp/servers?${r.toString()}`;if(e===`catalog`)return`/api/v2/mcp/catalog?${r.toString()}`;if(e===`operations`){let e=to(t);if(e===void 0)throw Error(`invalid server activity location`);return`/api/v2/mcp/servers/${e}/operations?projection=active`}if(e===`authFlows`){let e=/^#\/mcp\/servers\/([0-7][0-9A-HJKMNP-TV-Z]{25})\?tab=(?:operations|authentication|status)$/.exec(t);if(e===null)throw Error(`invalid server history location`);return`/api/v2/mcp/servers/${e[1]}/oauth-flows?${r.toString()}`}let i=/^#\/mcp\/servers\/([0-7][0-9A-HJKMNP-TV-Z]{25})\?tab=tools$/.exec(t);if(i===null)throw Error(`invalid descriptor location`);return`/api/v2/mcp/servers/${i[1]}/descriptors?${r.toString()}`}function to(e){return/^#\/mcp\/servers\/([0-7][0-9A-HJKMNP-TV-Z]{25})(?:[/?]|$)/.exec(e)?.[1]}function no(e){return Aa(e)===`catalog`?`catalog-reads`:Aa(e)===`descriptors`?`server-descriptor-reads`:/\?tab=operations(?:&|$)|\/operations\//.test(e)?`server-operation-reads`:/\/auth-flows\//.test(e)?`server-oauth-reads`:/\?tab=tools$|\/descriptors\//.test(e)?`server-descriptor-reads`:`server-overview-reads`}var ro=class{views;listeners=new Set;value=$a();continuation;continuationPending=!1;constructor(e,t){this.views=t;let n=(e,n,r,i=!1)=>t.registerPanel({id:e,matches:n,invalidations:r,...i?{pollMilliseconds:2e3,shouldPoll:()=>this.value.operation!==void 0&&!bi(this.value.operation)||this.value.authFlow!==void 0&&!Zr(this.value.authFlow)||this.value.authFlows.some(e=>!Zr(e))||this.value.operations.some(e=>!bi(e))}:{},read:t=>this.read(t,e===`server-operation-reads`?`operations`:e===`server-oauth-reads`?`authFlows`:e===`server-descriptor-reads`?`descriptors`:void 0),publish:e=>this.publish(e)});n(`server-overview-reads`,e=>Aa(e)===`servers`||/^#\/mcp\/servers\/[0-7][0-9A-HJKMNP-TV-Z]{25}(?:\?tab=(?:authentication|settings|status))?$/.test(e),[`servers`,`catalog`]),n(`server-operation-reads`,e=>/^#\/mcp\/servers\/[0-7][0-9A-HJKMNP-TV-Z]{25}\?tab=operations(?:&|$)/.test(e)||/^#\/mcp\/servers\/[0-7][0-9A-HJKMNP-TV-Z]{25}\/operations\/[0-7][0-9A-HJKMNP-TV-Z]{25}$/.test(e),[`servers`,`server_operations`,`catalog`],!0),n(`server-oauth-reads`,e=>/^#\/mcp\/servers\/[0-7][0-9A-HJKMNP-TV-Z]{25}\?tab=authentication$/.test(e)||/^#\/mcp\/servers\/[0-7][0-9A-HJKMNP-TV-Z]{25}\/auth-flows\/[0-7][0-9A-HJKMNP-TV-Z]{25}$/.test(e),[`servers`,`server_auth_flows`,`catalog`],!0),n(`server-descriptor-reads`,e=>Aa(e)===`descriptors`||/^#\/mcp\/servers\/[0-7][0-9A-HJKMNP-TV-Z]{25}\/descriptors\/[0-7][0-9A-HJKMNP-TV-Z]{25}$/.test(e),[`catalog`]),n(`catalog-reads`,e=>Aa(e)===`catalog`,[`catalog`]),e.registerProtectedState(()=>{this.continuation=void 0,this.continuationPending=!1,this.value=$a(),this.emit()})}snapshot(){return this.value}subscribe(e){return this.listeners.add(e),e(this.value),()=>this.listeners.delete(e)}async loadMore(e){let t=e===`servers`?this.value.serverNext:e===`descriptors`?this.value.descriptorNext:e===`operations`?this.value.operationNext:e===`authFlows`?this.value.authFlowNext:this.value.catalogNext;if(!(this.continuationPending||t===null)){this.continuationPending=!0,this.continuation={kind:e,cursor:t},this.value={...this.value,loadingMore:!0},this.emit();try{await this.views.refreshPanel(e===`authFlows`?`server-oauth-reads`:e===`operations`?`server-operation-reads`:no(this.value.viewKey))}finally{this.continuationPending=!1,this.value={...this.value,loadingMore:!1},this.emit()}}}async read(e,t){if(e.viewKey!==this.value.viewKey){this.continuation=void 0;let t=to(e.viewKey),n=t!==void 0&&this.value.server?.id===t?this.value.server:void 0;this.value={...$a(e.viewKey),server:n},this.emit()}let n=Aa(e.viewKey);if(n===`servers`||n===`catalog`)return{kind:`collection`,viewKey:e.viewKey};if(n===`descriptors`){let t=await Xa(e,`/api/v2/mcp/servers/${to(e.viewKey)}`),n=Wa(await Za(t)),r=t.headers.get(`ETag`);if(r!==`"server-${n.id}-${n.desiredRevision}"`)throw Error(`invalid server ETag`);return{kind:`server`,viewKey:e.viewKey,server:n,etag:r}}let r=/^#\/mcp\/servers\/([0-7][0-9A-HJKMNP-TV-Z]{25})\/auth-flows\/([0-7][0-9A-HJKMNP-TV-Z]{25})$/.exec(e.viewKey);if(r!==null){let[t,n]=await Promise.all([Xa(e,`/api/v2/mcp/servers/${r[1]}`),Xa(e,`/api/v2/mcp/servers/${r[1]}/oauth-flows/${r[2]}`)]),i=Wa(await Za(t)),a=t.headers.get(`ETag`);if(a!==`"server-${i.id}-${i.desiredRevision}"`)throw Error(`invalid server ETag`);let o=Jr(await Za(n));if(o.serverID!==r[1]||o.id!==r[2])throw Error(`auth flow route mismatch`);return{kind:`authFlow`,viewKey:e.viewKey,server:i,etag:a,flow:o}}let i=/^#\/mcp\/servers\/([0-7][0-9A-HJKMNP-TV-Z]{25})\/operations\/([0-7][0-9A-HJKMNP-TV-Z]{25})$/.exec(e.viewKey);if(i!==null){let[t,n]=await Promise.all([Xa(e,`/api/v2/mcp/servers/${i[1]}`),Xa(e,`/api/v2/mcp/servers/${i[1]}/operations/${i[2]}`)]),r=Wa(await Za(t)),a=t.headers.get(`ETag`);if(a!==`"server-${r.id}-${r.desiredRevision}"`)throw Error(`invalid server ETag`);let o=_i(await Za(n));if(o.serverID!==i[1]||o.id!==i[2])throw Error(`operation route mismatch`);return{kind:`operation`,viewKey:e.viewKey,server:r,etag:a,operation:o}}let a=/^#\/mcp\/servers\/([0-7][0-9A-HJKMNP-TV-Z]{25})\/descriptors\/([0-7][0-9A-HJKMNP-TV-Z]{25})$/.exec(e.viewKey);if(a!==null){let[t,n]=await Promise.all([Xa(e,`/api/v2/mcp/servers/${a[1]}`),Xa(e,`/api/v2/mcp/servers/${a[1]}/descriptors/${a[2]}`)]),r=Wa(await Za(t)),i=t.headers.get(`ETag`);if(i!==`"server-${r.id}-${r.desiredRevision}"`)throw Error(`invalid server ETag`);return{kind:`descriptor`,viewKey:e.viewKey,server:r,etag:i,descriptor:Ka(await Za(n))}}let o=/^#\/mcp\/servers\/([0-7][0-9A-HJKMNP-TV-Z]{25})(?:\?tab=(?:authentication|settings|status))?$/.exec(e.viewKey);if(o!==null&&t===void 0){let t=await Xa(e,`/api/v2/mcp/servers/${o[1]}`),n=Wa(await Za(t)),r=t.headers.get(`ETag`);if(r!==`"server-${n.id}-${n.desiredRevision}"`)throw Error(`invalid server ETag`);return{kind:`server`,viewKey:e.viewKey,server:n,etag:r}}let s=t??(e.viewKey===`#/mcp/servers`?`servers`:e.viewKey===`#/mcp/tools`?`catalog`:`descriptors`),c=this.continuation;this.continuation=void 0;let l=c?.kind===s?c.cursor:null,u=s===`operations`||s===`authFlows`||s===`descriptors`?Xa(e,`/api/v2/mcp/servers/${H(e.viewKey).segments[1]}`):void 0,[d,f]=await Promise.all([Xa(e,eo(s,e.viewKey,l)),u??Promise.resolve(void 0)]),p=!1;if(l!==null&&await Qa(d)&&(p=!0,s===`authFlows`&&!e.signal.aborted&&this.value.viewKey===e.viewKey&&(this.value={...this.value,authFlows:[],authFlowNext:null,restarted:!0},this.emit()),d=await Xa(e,eo(s,e.viewKey,null))),s===`servers`)return{kind:s,viewKey:e.viewKey,page:Ga(await Za(d)),append:l!==null&&!p,restarted:p};if(s===`descriptors`){if(f===void 0)throw Error(`missing server descriptor response`);let t=Wa(await Za(f)),n=f.headers.get(`ETag`);if(n!==`"server-${t.id}-${t.desiredRevision}"`)throw Error(`invalid server ETag`);return{kind:s,viewKey:e.viewKey,server:t,etag:n,page:Ja(await Za(d)),append:l!==null&&!p,restarted:p}}if(s===`operations`||s===`authFlows`){if(f===void 0)throw Error(`missing server history response`);let t=Wa(await Za(f)),n=f.headers.get(`ETag`);if(n!==`"server-${t.id}-${t.desiredRevision}"`)throw Error(`invalid server ETag`);if(s===`operations`){!e.signal.aborted&&this.value.viewKey===e.viewKey&&(this.value={...this.value,server:t,serverETag:n},this.emit());let r=gi(await Za(d));if(r.items.some(e=>e.serverID!==t.id))throw Error(`invalid active operation server`);return{kind:s,viewKey:e.viewKey,server:t,etag:n,page:r,append:!1,restarted:!1}}return{kind:s,viewKey:e.viewKey,server:t,etag:n,page:Yr(await Za(d)),append:l!==null&&!p,restarted:p}}let m=Ya(await Za(d));return{kind:s,viewKey:e.viewKey,catalog:m.catalog,page:m.page,append:l!==null&&!p,restarted:p}}publish(e){e.kind!==`collection`&&(this.value=e.kind===`server`?{...this.value,server:e.server,serverETag:e.etag,readVersion:this.value.readVersion+1,restarted:!1}:e.kind===`operation`?{...this.value,server:e.server,serverETag:e.etag,operation:e.operation,readVersion:this.value.readVersion+1,restarted:!1}:e.kind===`operations`?{...this.value,server:e.server,serverETag:e.etag,operations:e.append?[...this.value.operations,...e.page.items]:e.page.items,operationNext:e.page.nextCursor,activeMore:e.page.hasMore,readVersion:this.value.readVersion+1,restarted:e.restarted}:e.kind===`authFlow`?{...this.value,server:e.server,serverETag:e.etag,authFlow:e.flow,readVersion:this.value.readVersion+1,restarted:!1}:e.kind===`authFlows`?{...this.value,server:e.server,serverETag:e.etag,authFlows:e.append?[...this.value.authFlows,...e.page.items]:e.page.items,authFlowNext:e.page.nextCursor,readVersion:this.value.readVersion+1,restarted:e.restarted}:e.kind===`descriptor`?{...this.value,server:e.server,serverETag:e.etag,descriptor:e.descriptor,readVersion:this.value.readVersion+1,restarted:!1}:e.kind===`servers`?{...this.value,servers:e.append?[...this.value.servers,...e.page.items]:e.page.items,serverNext:e.page.nextCursor,restarted:e.restarted}:e.kind===`descriptors`?{...this.value,server:e.server,serverETag:e.etag,descriptors:e.append?[...this.value.descriptors,...e.page.items]:e.page.items,descriptorNext:e.page.nextCursor,readVersion:this.value.readVersion+1,restarted:e.restarted}:{...this.value,catalog:e.catalog,catalogItems:e.append?[...this.value.catalogItems,...e.page.items]:e.page.items,catalogNext:e.page.nextCursor,restarted:e.restarted},this.emit())}emit(){for(let e of this.listeners)e(this.value)}};function io({panel:e,children:t}){return e?.status===`error`&&e.hasValue!==!0?U(K,{state:`error`,title:`Read unavailable`}):e===void 0||e.status===`loading`&&!e.hasValue?U(K,{state:`loading`,title:`Loading authoritative data`}):U(S,{children:[e.status!==`current`&&e.hasValue&&U(K,{state:`stale`,title:`Last known data — refresh unavailable`}),t]})}function ao({serverID:e,current:t}){return U(`nav`,{class:`subnav`,"aria-label":`Server sections`,children:[[`status`,`Status`,`#/mcp/servers/${e}`],[`tools`,`Tools`,`#/mcp/servers/${e}?tab=tools`],[`operations`,`Operations`,`#/mcp/servers/${e}?tab=operations`],[`authentication`,`Authentication`,`#/mcp/servers/${e}?tab=authentication`],[`settings`,`Settings`,`#/mcp/servers/${e}?tab=settings`]].map(([e,n,r])=>U(`a`,{href:r,"aria-current":t===e?`page`:void 0,children:n},e))})}function oo(e){if(typeof e.transport!=`object`||e.transport===null)return!1;let t=e.transport;if(t.kind!==`streamable_http`)return!1;let n=t.authentication;return typeof n==`object`&&!!n&&!Array.isArray(n)&&n.mode===`oauth`}function so(e){let t=`#/mcp/servers/${e.id}`;if(e.desiredState===`deleted`)return{label:`Deleted`,state:`neutral`};if(e.desiredState===`disabled`)return{label:`Disabled`,state:`neutral`,action:`Configure`,href:`${t}?tab=settings`};if(e.runtimeState===`authentication_required`||e.credentialState===`absent`||e.credentialState===`reauthentication_required`)return{label:`Authorization required`,state:`warning`,action:oo(e)?`Authorize server`:`Manage credentials`,href:`${t}?tab=authentication`};if(e.credentialState===`locked`||e.credentialState===`interaction_required`||e.credentialState===`unavailable`||e.credentialState===`unsupported`)return{label:`Authentication unavailable`,state:`warning`,action:`Manage credentials`,href:`${t}?tab=authentication`};if(e.credentialState===`cleanup_pending`)return{label:`Cleanup needs attention`,state:`warning`,action:`View operations`,href:`${t}?tab=operations`};if(e.runtimeState===`activating`||e.runtimeState===`retry_wait`||e.credentialState===`refreshing`||e.credentialState===`disconnecting`)return{label:`Connecting`,state:`loading`,action:`View operations`,href:`${t}?tab=operations`};let n=e.reconciliation.saturated||e.dispatch.saturated||e.traversal.saturated;return e.runtimeState===`active`&&e.activeState===`current`&&(e.credentialState===`ready`||e.credentialState===`not_required`)&&!n?{label:`Ready`,state:`current`}:e.runtimeState===`active`?e.activeState===`current`?{label:`Capacity saturated`,state:`warning`,action:`View status`,href:t}:{label:`Needs attention`,state:`warning`,action:`View tools`,href:`${t}?tab=tools`}:{label:`Needs attention`,state:`warning`,action:`View operations`,href:`${t}?tab=operations`}}function co(e,t){return e.label===`Authorization required`?e.action===`Authorize server`?`Authorize this server to restore authenticated access.`:`Provide valid credentials to restore authenticated access.`:e.label===`Authentication unavailable`?`Credential storage requires operator attention before authentication can succeed.`:e.label===`Disabled`?`This server will not connect until it is enabled.`:e.label===`Connecting`?`The gateway is establishing or cleaning up the server connection.`:e.label===`Deleted`?`This server is retained as historical evidence.`:e.label===`Capacity saturated`?`One or more server capacity limits are saturated.`:t.runtimeReason===null?`The catalog is ${W(t.activeState)}.`:`Runtime reported ${W(t.runtimeReason)}.`}function lo({server:e,serverID:t,current:n,fresh:r,compact:i=!1}){if(e===void 0)return null;if(i)return U(S,{children:[U(`p`,{class:`secondary-text`,children:[`Server: `,U(`a`,{href:`#/mcp/servers/${t}`,children:e.displayName})]}),U(ao,{serverID:t,current:n})]});let a=so(e);return U(S,{children:[U(`nav`,{class:`detail-navigation`,"aria-label":`Server navigation`,children:U(`a`,{href:`#/mcp/servers`,children:`Back to MCP Servers`})}),U(`header`,{class:`server-context`,"data-testid":`server-context`,children:[U(`div`,{class:`server-context-heading`,children:[U(`h1`,{tabindex:-1,children:e.displayName}),U(G,{state:r?a.state:`stale`,children:r?a.label:`Last known · ${a.label}`})]}),U(`p`,{class:`technical-value`,children:U(`code`,{"data-testid":`server-id`,children:e.id})})]}),U(ao,{serverID:t,current:n})]})}function uo({items:e,controls:t}){return U(Dn,{caption:`Servers`,rowHeaderKey:`name`,additionalSorts:[{key:`id`,label:`Server ID`,sortValue:e=>e.id}],remote:t,itemNames:{singular:`server`,plural:`servers`},items:e,rowKey:e=>e.id,initialSort:{key:`name`,direction:`ascending`},rowTestID:`server-row`,filters:[{key:`name`,label:`Name or ID`,type:`text`,value:e=>e.displayName,literalValues:e=>[e.id]},{key:`namespace`,label:`Namespace`,type:`text`,value:e=>e.namespace},{key:`status`,label:`Status`,type:`select`,value:e=>so(e).label,options:[{value:`Ready`,label:`Ready`},{value:`Connecting`,label:`Connecting`},{value:`Authorization required`,label:`Authorization required`},{value:`Authentication unavailable`,label:`Authentication unavailable`},{value:`Capacity saturated`,label:`Capacity saturated`},{value:`Disabled`,label:`Disabled`},{value:`Deleted`,label:`Deleted`},{value:`Needs attention`,label:`Needs attention`}]}],emptyTitle:`No servers`,columns:[{key:`name`,label:`Server`,role:`identity`,sortValue:e=>e.displayName,render:e=>U(q,{primary:U(`a`,{href:`#/mcp/servers/${e.id}`,children:e.displayName}),secondary:e.id})},{key:`namespace`,label:`Namespace`,role:`text`,sortValue:e=>e.namespace,render:e=>e.namespace},{key:`status`,label:`Status`,role:`status`,sortValue:e=>so(e).label,render:e=>{let n=so(e);return U(G,{state:t.stale?`stale`:n.state,children:t.stale?`Last known · ${n.label}`:n.label})}},{key:`tools`,label:`Active tools`,role:`count`,sortValue:e=>e.activeToolCount,render:e=>e.activeToolCount}]})}function fo(e){return typeof e.type==`string`?e.type:Array.isArray(e.type)?e.type.filter(e=>typeof e==`string`).join(` or `):`value`}function po(e){let t=[];typeof e.format==`string`&&t.push(`Format: ${e.format}`),Array.isArray(e.enum)&&t.push(`Allowed: ${e.enum.map(String).join(`, `)}`),Object.hasOwn(e,`const`)&&t.push(`Constant: ${String(e.const)}`),Object.hasOwn(e,`default`)&&t.push(`Default: ${String(e.default)}`);for(let[n,r]of[[`minimum`,`Minimum`],[`maximum`,`Maximum`],[`minLength`,`Minimum length`],[`maxLength`,`Maximum length`],[`pattern`,`Pattern`]])(typeof e[n]==`string`||typeof e[n]==`number`)&&t.push(`${r}: ${String(e[n])}`);return t}function mo({value:e,depth:t=0}){if(typeof e!=`object`||!e||Array.isArray(e))return U(`span`,{class:`schema-constraint`,children:e===!0?`Any value`:e===!1?`No value`:`Invalid schema`});let n=e,r=typeof n.properties==`object`&&n.properties!==null&&!Array.isArray(n.properties)?n.properties:{},i=new Set(Array.isArray(n.required)?n.required.filter(e=>typeof e==`string`):[]),a=po(n),o=[`oneOf`,`anyOf`,`allOf`].map(e=>[e,n[e]]).filter(e=>Array.isArray(e[1]));return U(S,{children:[typeof n.description==`string`&&U(`p`,{children:n.description}),a.map(e=>U(`span`,{class:`schema-constraint`,children:e},e)),Object.keys(r).length>0&&U(`dl`,{class:`schema-fields`,children:Object.entries(r).map(([e,n])=>{let r=n;return U(`div`,{children:[U(`dt`,{children:[U(`code`,{children:e}),U(`span`,{children:fo(r)}),i.has(e)&&U(`strong`,{children:`Required`})]}),U(`dd`,{children:U(mo,{value:r,depth:t+1})})]},e)})}),t<5&&typeof n.items==`object`&&n.items!==null&&U(`div`,{class:`schema-nested`,children:[U(`strong`,{children:`Items`}),U(mo,{value:n.items,depth:t+1})]}),t<5&&o.map(([e,n])=>U(`div`,{class:`schema-nested`,children:[U(`strong`,{children:e}),n.map((e,n)=>U(`div`,{children:[U(`span`,{class:`schema-constraint`,children:[`Option `,n+1]}),U(mo,{value:e,depth:t+1})]},n))]},e)),typeof n.$ref==`string`&&U(`span`,{class:`schema-constraint`,children:[`Reference: `,n.$ref]})]})}function ho({label:e,value:t}){let n=t,r=`${e.toLowerCase().replace(` `,`-`)}-title`;return U(`section`,{class:`tool-schema`,"aria-labelledby":r,children:[U(`div`,{class:`tool-schema-heading`,children:[U(`h3`,{id:r,children:e}),U(`span`,{children:fo(n)})]}),U(mo,{value:n})]})}function go({items:e,controls:t}){return U(Dn,{caption:`Available tools`,rowHeaderKey:`tool`,remote:t,itemNames:{singular:`tool`,plural:`tools`},emptyTitle:`No catalog tools`,items:e,rowKey:e=>e.id,initialSort:{key:`tool`,direction:`ascending`},rowTestID:`catalog-row`,filters:[{key:`tool`,label:`Tool`,type:`text`,value:e=>e.externalName,literalValues:e=>[e.id]},{key:`server`,label:`Server`,type:`text`,value:e=>e.serverDisplayName,literalValues:e=>[e.serverID]},{key:`status`,label:`Status`,type:`select`,value:e=>e.serverCatalogState===`current`?`available`:`issue`,options:[{value:`available`,label:`Available`},{value:`issue`,label:`Catalog issue`}]}],columns:[{key:`tool`,label:`Tool`,role:`identity`,sortValue:e=>e.externalName,render:e=>U(q,{primary:U(`a`,{href:`#/mcp/servers/${e.serverID}/descriptors/${e.id}`,"data-tool-name":e.upstreamName,children:e.externalName}),secondary:e.id})},{key:`server`,label:`Server`,role:`relation`,sortValue:e=>e.serverDisplayName,render:e=>U(q,{primary:U(`a`,{href:`#/mcp/servers/${e.serverID}?tab=tools`,children:e.serverDisplayName||e.serverID}),secondary:e.serverID})},{key:`status`,label:`Status`,role:`status`,render:e=>{let n=e.serverCatalogState===`current`;return U(G,{state:t.stale?`stale`:n?`current`:`warning`,children:[t.stale?`Last known · `:``,n?`Available`:`Catalog issue`]})}}]})}function _o({items:e,controls:t}){return U(Dn,{caption:`Server tools`,rowHeaderKey:`tool`,remote:t,itemNames:{singular:`tool`,plural:`tools`},emptyTitle:`No server tools`,items:e,rowKey:e=>e.id,rowTestID:`descriptor-row`,filters:[{key:`tool`,label:`Tool`,type:`text`,value:e=>e.externalName,literalValues:e=>[e.id]},{key:`status`,label:`Status`,type:`select`,value:e=>e.retiredAt===null?`available`:`retired`,options:[{value:`available`,label:`Available`},{value:`retired`,label:`Retired`}]}],initialSort:{key:`last-seen`,direction:`descending`},columns:[{key:`tool`,label:`Tool`,role:`identity`,sortValue:e=>e.externalName,render:e=>U(q,{primary:U(`a`,{href:`#/mcp/servers/${e.serverID}/descriptors/${e.id}`,"data-tool-name":e.upstreamName,children:e.externalName})})},{key:`status`,label:`Status`,role:`status`,sortValue:e=>e.retiredAt===null?`available`:`retired`,render:e=>U(G,{state:t.stale?`stale`:e.retiredAt===null?`current`:`neutral`,children:[t.stale?`Last known · `:``,e.retiredAt===null?`Available`:`Retired`]})},{key:`last-seen`,label:`Last seen`,role:`time`,sortValue:e=>e.lastSeenAt,render:e=>U(Y,{value:e.lastSeenAt})}]})}function vo({session:e,resolved:t,view:n,kind:r,decodePage:i,render:a}){let o=Cr(!1),s=r===`operations`?{key:`created`,direction:`descending`}:r===`descriptors`?{key:`last-seen`,direction:`descending`}:{key:r===`servers`?`name`:`tool`,direction:`ascending`},{items:c,controls:l}=Nr(e,t,n,(n,a,o)=>{let c=new URLSearchParams({limit:`50`,sort:n.sort??s.key,direction:n.direction??(n.sort===void 0?s.direction:`ascending`)});for(let[e,t]of Object.entries(n))e.startsWith(`filter_`)&&c.set(e.slice(7),r===`servers`&&e===`filter_status`?t.toLowerCase().replaceAll(` `,`_`):t);a!==null&&c.set(`cursor`,a);let l=r===`descriptors`||r===`operations`?`/api/v2/mcp/servers/${t.location.segments[1]}/${r}`:`/api/v2/mcp/${r}`;return r===`operations`?Mr(e,`${l}?${c}`,e=>{let n=_i(e);if(n.serverID!==t.location.segments[1])throw Error(`Invalid operation server.`);return n},o):Mr(e,`${l}?${c}`,void 0,o,e=>{let t=i(e);if(t.items.length>50||t.nextCursor!==null&&t.nextCursor.length>512)throw Error(`Invalid collection response.`);return{...t,totalCount:void 0,offset:0}})},o,s);return U(S,{children:a(c,l)})}function yo({session:e,resolved:t,controller:n,view:r,destination:i,mutations:a,sinks:o,onRefresh:s,notify:c}){let[l,u]=z(n.snapshot());B(()=>n.subscribe(u),[n]);let d=r.panels[no(r.viewKey)],f=r.panels[`server-overview-reads`],p=r.panels[`server-operation-reads`],m=r.panels[`server-oauth-reads`],h=/^#\/mcp\/servers\/([0-7][0-9A-HJKMNP-TV-Z]{25})\?tab=authentication$/.exec(r.viewKey),g=/^#\/mcp\/servers\/([0-7][0-9A-HJKMNP-TV-Z]{25})\/auth-flows\/[0-7][0-9A-HJKMNP-TV-Z]{25}$/.exec(r.viewKey),_=/^#\/mcp\/servers\/([0-7][0-9A-HJKMNP-TV-Z]{25})\?tab=operations(?:&|$)/.exec(r.viewKey),v=/^#\/mcp\/servers\/([0-7][0-9A-HJKMNP-TV-Z]{25})\/operations\/[0-7][0-9A-HJKMNP-TV-Z]{25}$/.exec(r.viewKey),y=/^#\/mcp\/servers\/([0-7][0-9A-HJKMNP-TV-Z]{25})\?tab=settings$/.exec(r.viewKey),b=/^#\/mcp\/servers\/([0-7][0-9A-HJKMNP-TV-Z]{25})\?tab=status$/.exec(r.viewKey),x=/^#\/mcp\/servers\/([0-7][0-9A-HJKMNP-TV-Z]{25})\/descriptors\/[0-7][0-9A-HJKMNP-TV-Z]{25}$/.exec(r.viewKey),C=/^#\/mcp\/servers\/([0-7][0-9A-HJKMNP-TV-Z]{25})$/.exec(r.viewKey),w=Aa(r.viewKey)===`descriptors`?to(r.viewKey):void 0,T=/^#\/mcp\/servers\/([0-7][0-9A-HJKMNP-TV-Z]{25})\?tab=([^&]+)$/.exec(r.viewKey),E=b?.[1]??C?.[1];if(r.viewKey===`#/mcp/servers/new`)return U(`div`,{class:`domain-view`,"data-testid":`server-create-view`,children:[U(`a`,{href:`#/mcp/servers`,children:`Back to server inventory`}),U(ya,{mutations:a,onRefresh:s,notify:c,decodeServerValue:Wa})]});if(i===`catalog`)return U(`div`,{class:`domain-view`,"data-testid":`catalog-view`,children:U(`section`,{class:`panel domain-panel`,"aria-labelledby":`page-title`,children:U(vo,{session:e,resolved:t,view:r,kind:`catalog`,decodePage:e=>Ya(e).page,render:(e,t)=>U(go,{items:e,controls:t})})})});if(Aa(r.viewKey)===`servers`)return U(`div`,{class:`domain-view`,"data-testid":`servers-view`,children:[U(`div`,{class:`collection-toolbar`,children:U(`a`,{class:`button-link create-action`,href:`#/mcp/servers/new`,"data-testid":`server-create-link`,children:`Create server`})}),U(`section`,{class:`panel domain-panel`,"aria-labelledby":`page-title`,children:U(vo,{session:e,resolved:t,view:r,kind:`servers`,decodePage:Ga,render:(e,t)=>U(uo,{items:e,controls:t})})})]});if(h!==null)return U(`div`,{class:`domain-view`,"data-testid":`server-authentication-view`,children:[U(lo,{server:l.server,serverID:h[1],fresh:f?.status===`current`,current:`authentication`}),U(io,{panel:f,children:l.server!==void 0&&l.serverETag!==void 0&&U(Ui,{mutations:a,sinks:o,server:l.server,etag:l.serverETag,readVersion:l.readVersion,onRefresh:s})}),U(io,{panel:m,children:l.server!==void 0&&l.serverETag!==void 0&&U(ai,{mutations:a,sinks:o,server:l.server,etag:l.serverETag,readVersion:l.readVersion,flows:l.authFlows,flow:void 0,nextCursor:l.authFlowNext,loadingMore:l.loadingMore,restarted:l.restarted,onLoadMore:()=>void n.loadMore(`authFlows`),onRefresh:s,mode:`action`,stale:m?.status===`error`})}),l.server!==void 0&&l.serverETag!==void 0&&U(ai,{mutations:a,sinks:o,server:l.server,etag:l.serverETag,readVersion:l.readVersion,flows:l.authFlows,flow:void 0,nextCursor:l.authFlowNext,loadingMore:l.loadingMore,restarted:l.restarted,onLoadMore:()=>void n.loadMore(`authFlows`),onRefresh:s,mode:`history`,stale:m?.status===`error`,loading:m===void 0||m.status===`loading`&&!m.hasValue})]});if(g!==null){let e=g[1];return U(`div`,{class:`domain-view`,"data-testid":`server-auth-flows-view`,children:[U(lo,{server:l.server,serverID:e,fresh:d?.status===`current`,current:`authentication`,compact:!0}),U(io,{panel:d,children:l.server!==void 0&&l.serverETag!==void 0&&U(ai,{mutations:a,sinks:o,server:l.server,etag:l.serverETag,readVersion:l.readVersion,flows:l.authFlows,flow:l.authFlow,stale:d?.status===`error`,nextCursor:l.authFlowNext,loadingMore:l.loadingMore,restarted:l.restarted,onLoadMore:()=>void n.loadMore(`authFlows`),onRefresh:s})})]})}return _===null?v===null?x===null?w===void 0?y===null?E===void 0?T===null?U(K,{state:`unavailable`,title:`Server workflow not yet available`}):U(`div`,{class:`domain-view`,children:[U(lo,{server:l.server,serverID:T[1],fresh:d?.status===`current`,current:T[2]}),U(K,{state:`unavailable`,title:`Workflow not yet available`})]}):U(`div`,{class:`domain-view`,"data-testid":`server-status-view`,children:[U(lo,{server:l.server,serverID:E,fresh:d?.status===`current`,current:`status`}),U(`section`,{class:`detail-section operator-status-view`,"aria-labelledby":`server-status-title`,children:[U(`div`,{class:`panel-heading`,children:U(`h2`,{id:`server-status-title`,children:`Server status`})}),U(io,{panel:d,children:l.server!==void 0&&(()=>{let e=l.server,t=so(e),n=[[`Reconciliation`,e.reconciliation],[`Dispatch`,e.dispatch],[`Catalog traversal`,e.traversal]].filter(([,e])=>e.saturated),r=t.action!==void 0;return U(`div`,{class:`operator-status-stack`,children:[(r||n.length>0||e.desiredState===`deleted`)&&U(`section`,{class:`operator-status-section`,"aria-labelledby":`server-issues-title`,"data-testid":`server-status-issues`,children:[U(`div`,{class:`operator-status-section-heading`,children:U(`h3`,{id:`server-issues-title`,children:`Needs attention`})}),e.desiredState===`deleted`&&U(K,{state:`unavailable`,title:`Deleted`,children:[U(`p`,{children:co(t,e)}),e.deletedAt!==null&&U(`p`,{children:[`Deleted `,U(Y,{value:e.deletedAt})]})]}),r&&U(K,{state:t.state===`current`?`warning`:t.state,title:t.label,children:[U(`p`,{children:co(t,e)}),t.href!==void 0&&t.href!==`#/mcp/servers/${e.id}`&&U(`a`,{href:t.href,children:t.action})]}),n.map(([e,t])=>U(K,{state:`warning`,title:`${e} capacity is saturated`,children:U(`p`,{children:[t.inUse,` of `,t.limit,` slots are in use. New work cannot be admitted until capacity is released.`]})},e))]}),U(`section`,{class:`operator-status-section`,"aria-labelledby":`server-operational-title`,"data-testid":`server-status-operational`,children:[U(`h3`,{id:`server-operational-title`,children:`Operational state`}),U(`dl`,{class:`operator-status-grid`,children:[U(`div`,{children:[U(`dt`,{children:`Runtime`}),U(`dd`,{children:[U(vn,{value:e.runtimeState,current:d?.status===`current`}),U(`span`,{children:[`Desired `,W(e.desiredState)]}),e.runtimeReason!==null&&U(`span`,{children:[`Reason: `,W(e.runtimeReason)]})]})]}),U(`div`,{children:[U(`dt`,{children:`Authentication`}),U(`dd`,{children:[U(vn,{value:e.credentialState,current:d?.status===`current`}),t.href!==`#/mcp/servers/${e.id}?tab=authentication`&&U(`a`,{href:`#/mcp/servers/${e.id}?tab=authentication`,children:`Manage authentication`})]})]}),U(`div`,{children:[U(`dt`,{children:`Catalog`}),U(`dd`,{children:[U(vn,{value:e.activeState,current:d?.status===`current`}),U(`span`,{children:[e.activeToolCount,` active ·`,` `,e.durableToolCount,` durable tools`]}),U(`span`,{children:[`Last successful refresh`,` `,U(Y,{value:e.lastSuccessAt})]}),U(`a`,{href:`#/mcp/servers/${e.id}?tab=tools`,children:`View tools`})]})]})]})]}),U(`section`,{class:`operator-status-details`,"aria-labelledby":`server-technical-details-title`,"data-testid":`server-status-details`,children:[U(`h3`,{id:`server-technical-details-title`,children:`Technical details`}),U(`dl`,{class:`technical-details-grid`,children:[U(`div`,{children:[U(`dt`,{children:`Namespace`}),U(`dd`,{children:e.namespace})]}),U(`div`,{class:`technical-details-wide`,children:[U(`dt`,{children:`Diagnostic correlation`}),U(`dd`,{"data-testid":`server-diagnostic-correlation`,children:e.diagnosticCorrelation?U(S,{children:[U(`span`,{children:[`Process:`,` `,e.diagnosticCorrelation.processID]}),U(`br`,{}),U(`span`,{children:[`Upstream reference:`,` `,e.diagnosticCorrelation.upstreamRef]}),U(`p`,{class:`muted`,children:`Match both values to stderr from this Gateway process. References do not survive restart.`})]}):`Unavailable — no current diagnostic reference`})]}),U(`div`,{class:`technical-details-wide`,children:[U(`dt`,{children:`Runtime ID`}),U(`dd`,{children:e.runtimeID===null?`—`:U(ji,{value:e.runtimeID,label:`runtime ID`})})]}),U(`div`,{children:[U(`dt`,{children:`Desired revision`}),U(`dd`,{children:e.desiredRevision})]}),U(`div`,{children:[U(`dt`,{children:`Static credential revision`}),U(`dd`,{children:e.staticRevision})]}),U(`div`,{children:[U(`dt`,{children:`OAuth client revision`}),U(`dd`,{children:e.oauthClientRevision})]}),U(`div`,{children:[U(`dt`,{children:`OAuth token revision`}),U(`dd`,{children:e.oauthTokensRevision})]}),U(`div`,{children:[U(`dt`,{children:`Durable catalog revision`}),U(`dd`,{children:e.durableRevision??`—`})]}),U(`div`,{children:[U(`dt`,{children:`Active catalog revision`}),U(`dd`,{children:e.activeRevision??`—`})]}),U(`div`,{children:[U(`dt`,{children:`Created`}),U(`dd`,{children:U(Y,{value:e.createdAt})})]}),U(`div`,{children:[U(`dt`,{children:`Updated`}),U(`dd`,{children:U(Y,{value:e.updatedAt})})]})]})]})]})})()})]})]}):U(`div`,{class:`domain-view`,"data-testid":`server-settings-view`,children:[U(lo,{server:l.server,serverID:y[1],fresh:d?.status===`current`,current:`settings`}),U(io,{panel:d,children:[l.server!==void 0&&l.serverETag!==void 0&&l.server.desiredState!==`deleted`&&U(S,{children:[U(ya,{mutations:a,server:l.server,etag:l.serverETag,onRefresh:s,notify:c,decodeServerValue:Wa}),U(Gi,{mutations:a,server:l.server,etag:l.serverETag,readVersion:l.readVersion,decodeServerValue:Wa})]}),l.server?.desiredState===`deleted`&&U(K,{state:`unavailable`,title:`Server deleted`})]})]}):U(`div`,{class:`domain-view`,"data-testid":`descriptor-list`,children:[U(lo,{server:l.server,serverID:w,fresh:f?.status===`current`,current:`tools`}),U(`section`,{class:`panel domain-panel`,"aria-labelledby":`descriptor-list-title`,children:[U(`div`,{class:`panel-heading`,children:[U(`h2`,{id:`descriptor-list-title`,children:`Tools`}),U(`a`,{href:`#/mcp/tools`,children:`All available tools`})]}),U(vo,{session:e,resolved:t,view:r,kind:`descriptors`,decodePage:Ja,render:(e,t)=>U(_o,{items:e,controls:t})})]})]}):U(`div`,{class:`domain-view`,"data-testid":`descriptor-detail`,children:U(io,{panel:d,children:l.descriptor!==void 0&&(()=>{let e=l.descriptor,t=e.descriptor,n=t.annotations;return U(S,{children:[U(`nav`,{class:`detail-navigation`,"aria-label":`Tool navigation`,children:[U(`a`,{href:`#/mcp/servers/${e.serverID}?tab=tools`,children:`Back to server tools`}),U(`a`,{href:`#/mcp/tools`,children:`All MCP tools`})]}),U(`header`,{class:`detail-context`,"data-testid":`detail-context`,children:U(`div`,{class:`detail-context-heading tool-heading`,children:[U(`div`,{children:[U(`h1`,{id:`descriptor-detail-title`,tabindex:-1,children:e.externalName}),U(`p`,{class:`technical-value`,children:e.id})]}),U(G,{state:d?.status===`current`?e.retiredAt===null?`current`:`neutral`:`stale`,children:e.retiredAt===null?`Available`:`Retired`})]})}),e.retiredAt!==null&&U(`p`,{children:`Historical evidence; not callable`}),U(`section`,{class:`detail-section`,"aria-labelledby":`tool-evidence-title`,children:[U(`h2`,{id:`tool-evidence-title`,children:`Tool details`}),U(`dl`,{class:`tool-metadata`,children:[U(`div`,{children:[U(`dt`,{children:`Server`}),U(`dd`,{children:U(q,{primary:U(`a`,{href:`#/mcp/servers/${e.serverID}`,children:l.server?.displayName??`Server ${e.serverID}`}),secondary:e.serverID})})]}),typeof t.description==`string`&&U(`div`,{children:[U(`dt`,{children:`Description`}),U(`dd`,{children:t.description})]})]}),U(`h3`,{children:`Catalog evidence`}),U(`dl`,{class:`tool-metadata`,children:[U(`div`,{children:[U(`dt`,{children:`Catalog revision`}),U(`dd`,{children:e.catalogRevision})]}),U(`div`,{children:[U(`dt`,{children:`First seen`}),U(`dd`,{children:U(Y,{value:e.firstSeenAt})})]}),U(`div`,{children:[U(`dt`,{children:`Last seen`}),U(`dd`,{children:U(Y,{value:e.lastSeenAt})})]}),U(`div`,{children:[U(`dt`,{children:`Retired`}),U(`dd`,{children:U(Y,{value:e.retiredAt,fallback:`No`})})]})]}),U(`h3`,{id:`server-hints-title`,class:`detail-group`,children:`Server hints`}),U(`div`,{class:`tool-annotations`,"aria-labelledby":`server-hints-title`,children:[U(`span`,{children:n.readOnlyHint?`Read only`:`May write`}),U(`span`,{children:n.destructiveHint?`Destructive`:`Non-destructive`}),U(`span`,{children:n.idempotentHint?`Idempotent`:`Not idempotent`}),U(`span`,{children:n.openWorldHint?`External access`:`Closed world`})]})]}),U(`section`,{class:`detail-section`,children:[U(`h3`,{children:`Schema summary`}),U(`div`,{class:`tool-schema-grid`,children:[U(ho,{label:`Input schema`,value:t.inputSchema}),t.outputSchema!==void 0&&U(ho,{label:`Output schema`,value:t.outputSchema})]})]})]})})()})}):U(`div`,{class:`domain-view`,"data-testid":`server-operations-view`,children:U(io,{panel:d,children:l.server!==void 0&&l.serverETag!==void 0&&U(Oa,{mutations:a,server:l.server,etag:l.serverETag,readVersion:l.readVersion,operations:l.operations,operation:l.operation})})}):U(`div`,{class:`domain-view`,"data-testid":`server-activity-view`,children:[U(lo,{server:l.server,serverID:_[1],fresh:f?.status===`current`,current:`operations`}),p?.status===`error`&&U(K,{state:`error`,title:`Active operations unavailable`,children:`Operation starts are disabled. History remains independently readable.`}),l.server!==void 0&&l.serverETag!==void 0&&U(Oa,{mutations:a,server:l.server,etag:l.serverETag,readVersion:l.readVersion,operations:l.operations,operation:void 0,activeCurrent:p?.status===`current`&&p.refreshing!==!0,activeRefreshing:p?.refreshing===!0,multipleActive:l.activeMore||l.operations.length>1}),U(`section`,{class:`panel domain-panel`,"aria-labelledby":`operation-list-title`,"data-testid":`operation-list`,children:[U(`div`,{class:`panel-heading`,children:U(`h2`,{id:`operation-list-title`,children:`Operation history`})}),U(vo,{session:e,resolved:t,view:r,kind:`operations`,decodePage:vi,render:(e,t)=>U(Ea,{serverID:_[1],items:e,controls:t})})]})]})}var bo=/^[0-7][0-9A-HJKMNP-TV-Z]{25}$/;function xo(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:void 0}function So(e){return e.replaceAll(`~`,`~0`).replaceAll(`/`,`~1`)}var Co=new Set([`$id`,`$schema`,`default`,`deprecated`,`description`,`examples`,`readOnly`,`title`,`writeOnly`]);function wo(e,t){let n=new Set([...Co,...t]);return Object.keys(e).some(e=>!n.has(e))}function To(e){let t=xo(xo(e)?.inputSchema),n=[],r=t===void 0,i=(e,t,a)=>{if(a>16||n.length>=256){r=!0;return}let o=xo(e.properties);if((e.type!==`object`||o===void 0||wo(e,[`type`,`properties`,`required`,`additionalProperties`,`minProperties`,`maxProperties`])||e.additionalProperties!==!1)&&(r=!0),e.type===`object`&&o!==void 0)for(let[e,s]of Object.entries(o)){if(n.length>=256){r=!0;break}let o=xo(s);if(o===void 0){r=!0;continue}let c=[...t,e];if(o.type===`object`){i(o,c,a+1);continue}wo(o,[`type`,`enum`])&&(r=!0);let l=o.type===`integer`||o.type===`number`?`number`:o.type===`null`||o.type===`boolean`||o.type===`string`?o.type:void 0;if(l===void 0){r=!0;continue}o.enum!==void 0&&!Array.isArray(o.enum)&&(r=!0);let u=Array.isArray(o.enum)?o.enum:[],d=u.filter(e=>l===`null`?e===null:l===`number`?typeof e==`number`:typeof e===l).map(e=>e===null?`null`:String(e));d.length!==u.length&&(r=!0);let f=`/${c.map(So).join(`/`)}`;if(new TextEncoder().encode(f).length>256){r=!0;continue}n.push({pointer:f,type:l,description:typeof o.description==`string`?o.description:null,values:d,regexAvailable:l===`string`})}};return t!==void 0&&i(t,[],0),{fields:n,unsupported:r}}function Eo(e){if(typeof e!=`string`)throw Error(`invalid response`);return e}function Do(e){let t=xo(e);if(t===void 0||Object.keys(t).sort().join(`,`)!==`items,next_cursor`||!Array.isArray(t.items)||t.items.length>100||t.next_cursor!==null&&(typeof t.next_cursor!=`string`||t.next_cursor===``||new TextEncoder().encode(t.next_cursor).length>512))throw Error(`invalid response`);return{items:t.items.map(e=>{let t=xo(e);if(t===void 0||Object.keys(t).sort().join(`,`)!==`catalog_revision,external_name,id,server_id,upstream_name`)throw Error(`invalid response`);let n=Eo(t.id),r=Eo(t.server_id);if(!bo.test(n)||!bo.test(r))throw Error(`invalid response`);return{id:n,serverID:r,upstreamName:Eo(t.upstream_name),externalName:Eo(t.external_name),catalogRevision:Eo(t.catalog_revision)}}),nextCursor:t.next_cursor}}function Oo(e,t){return t===void 0?e:AbortSignal.any([e,t])}async function ko(e,t,n){return!bo.test(t)||t===`00000000000000000000000000`?[]:e.runProtected(async e=>{let r=[],i=null,a=!1,o=new Set;for(;;){let s=new URLSearchParams({limit:`50`,status:`available`,projection:`summary`});i!==null&&s.set(`cursor`,i);let c=await fetch(`/api/v2/mcp/servers/${t}/descriptors?${s}`,{credentials:`same-origin`,redirect:`error`,signal:Oo(e.signal,n),headers:{Accept:`application/json`,"X-CSRF-Token":e.csrfToken}});if(await e.sessionLost(c))return;if(c.status===409&&i!==null&&!a){r.length=0,i=null,o.clear(),a=!0;continue}if(!c.ok||c.headers.get(`Content-Type`)!==`application/json`)throw Error(`Catalog tools are unavailable.`);let l=Do(await c.json());if(l.items.some(e=>e.serverID!==t))throw Error(`Catalog pagination returned the wrong server.`);if(r.length+l.items.length>256)throw Error(`Catalog tools exceed the supported limit.`);if(r.push(...l.items),l.nextCursor===null)return r;if(o.has(l.nextCursor)||r.length>=256)throw Error(`Catalog pagination is invalid.`);o.add(l.nextCursor),i=l.nextCursor}})}async function Ao(e,t,n){if(!(!bo.test(t.serverID)||!bo.test(t.id)))return e.runProtected(async e=>{let r=await fetch(`/api/v2/mcp/servers/${t.serverID}/descriptors/${t.id}`,{credentials:`same-origin`,redirect:`error`,signal:Oo(e.signal,n),headers:{Accept:`application/json`,"X-CSRF-Token":e.csrfToken}});if(await e.sessionLost(r))return;if(!r.ok||r.headers.get(`Content-Type`)!==`application/json`)throw Error(`The selected tool schema is unavailable.`);let i=qa(await r.json());if(i.id!==t.id||i.serverID!==t.serverID||i.upstreamName!==t.upstreamName||i.externalName!==t.externalName||i.retiredAt!==null)throw Error(`The selected tool schema is no longer current.`);return i})}function jo({status:e,testID:t}){return U(`span`,{class:`matcher-status`,"data-recognition":e.toLowerCase(),"data-testid":t,role:`status`,"aria-live":`polite`,"aria-atomic":`true`,children:e})}var Mo=/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/;function No(e){return e.startsWith(`/`)&&new TextEncoder().encode(e).length<=256&&!/~(?:[^01]|$)/.test(e)}function Po(e){if(e===null)return 0;let t=e;return Object.keys(t.equals??{}).length+Object.keys(t.regex??{}).length}function Fo(e){if(e.length===0)return`null`;let t=t=>e.filter(e=>e.operator===t).map(e=>{let n;if(t===`regex`)n=JSON.stringify(e.value);else if(e.type===`null`)n=`null`;else if(e.type===`boolean`){if(e.value!==`true`&&e.value!==`false`)throw Error(`Boolean values must be true or false.`);n=e.value}else if(e.type===`number`){if(!Mo.test(e.value))throw Error(`Number values must use valid JSON number syntax.`);n=e.value}else n=JSON.stringify(e.value);return`${JSON.stringify(e.pointer)}:${n}`}),n=t(`equals`),r=t(`regex`);return`{"version":2${n.length===0?``:`,"equals":{${n.join(`,`)}}`},"regex":{${r.join(`,`)}}}`}function Io({idPrefix:e,testPrefix:t,addTestID:n,atoms:r,suggestions:i,schemaState:a=`unavailable`,disabled:o=!1,onChange:s}){let c=(e,t)=>s(r.map((n,r)=>r===e?{...n,...t}:n)),l=(i?.fields??[]).map(e=>({value:e.pointer,detail:`${e.type}${e.values.length===0?``:` · ${e.values.join(`, `)}`}${e.description===null?``:` · ${e.description}`}`}));return U(`div`,{class:`matcher-editor`,children:[r.map((n,u)=>{let d=i?.fields.find(e=>e.pointer===n.pointer),f=n.operator===`regex`,p=n.pointer===``?`Choose field`:i===void 0?a===`loading`?`Loading…`:`Unavailable`:d===void 0?`Unknown`:`Known`,m=d!==void 0&&d.type!==(f?`string`:n.type)?f?`Schema suggests ${d.type}; only string runtime values can match. No coercion.`:`Schema suggests ${d.type}; your ${n.type} type is retained.`:``,h=`${e}-guidance-${u}`,g=m?h:void 0,_=`${e}-values-${u}`,v=!f&&d?.type===n.type?d.values:[];return U(`div`,{class:`matcher-row`,"data-testid":`${t}-atom`,children:[U(J,{id:`${e}-pointer-${u}`,label:`JSON pointer`,children:e=>U(kn,{attributes:{...e,...g?{"aria-describedby":g}:{}},label:`JSON pointer ${u+1}`,testID:`${t}-pointer`,value:n.pointer,options:l,placeholder:`/repository`,disabled:o,onChange:e=>{let t=i?.fields.find(t=>t.pointer===e);c(u,{pointer:e,...!n.explicitType&&n.value===``&&t!==void 0?{type:t.type}:{}})}})}),U(jo,{status:p,testID:`${t}-status`}),U(J,{id:`${e}-operator-${u}`,label:`Operator`,children:e=>U(`select`,{...e,"aria-describedby":g,"data-testid":`${t}-operator`,value:n.operator,disabled:o,onChange:e=>c(u,{operator:e.currentTarget.value,value:``}),children:[U(`option`,{value:`equals`,children:`EQUALS`}),U(`option`,{value:`regex`,children:`MATCHES`})]})}),U(J,{id:`${e}-type-${u}`,label:`Scalar type`,children:e=>U(`select`,{...e,"aria-describedby":g,"data-testid":`${t}-type`,value:f?`string`:n.type,disabled:o||f,onChange:e=>c(u,{type:e.currentTarget.value,explicitType:!0}),children:[U(`option`,{value:`null`,children:`Null`}),U(`option`,{value:`boolean`,children:`Boolean`}),U(`option`,{value:`string`,children:`String`}),U(`option`,{value:`number`,children:`Number`})]})}),U(J,{id:`${e}-value-${u}`,label:f?`Full-string RE2 pattern`:`Scalar value`,children:e=>!f&&n.type===`boolean`?U(`select`,{...e,"aria-describedby":g,"data-testid":`${t}-value`,value:n.value,disabled:o,onChange:e=>c(u,{value:e.currentTarget.value}),children:[U(`option`,{value:``,children:`Choose a boolean`}),U(`option`,{value:`true`,children:`true`}),U(`option`,{value:`false`,children:`false`})]}):!f&&n.type===`null`?U(`input`,{...e,"aria-describedby":g,value:`null`,disabled:!0}):U(`input`,{...e,"aria-describedby":g,"data-testid":`${t}-value`,value:n.value,placeholder:f?`example-[a-z0-9-]+`:n.type===`number`?`42`:`example-project`,list:_,autocomplete:`off`,disabled:o,onInput:e=>c(u,{value:e.currentTarget.value})})}),U(`datalist`,{id:_,children:v.map(e=>U(`option`,{value:e},e))}),U(`button`,{class:`matcher-remove`,type:`button`,"aria-label":`Remove condition ${u+1}`,disabled:o,onClick:()=>s(r.filter((e,t)=>t!==u)),children:`Remove condition`}),m&&U(`p`,{id:h,class:`field-hint matcher-guidance`,role:`status`,children:m})]},u)}),U(`button`,{"data-testid":n??`${t}-add`,type:`button`,disabled:o||r.length>=16,onClick:()=>s([...r,{operator:`equals`,pointer:``,type:`string`,value:``}]),children:`Add condition`})]})}function Lo(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`Matcher validation returned an invalid response.`);let n=e;if(Object.keys(n).sort().join(`,`)!==[...t].sort().join(`,`))throw Error(`Matcher validation returned an invalid response.`);return n}function Ro(e){if(typeof e!=`string`)throw Error(`Matcher validation returned an invalid response.`);return e}function zo(e){return{Accept:`application/json`,"Content-Type":`application/json`,"X-CSRF-Token":e.csrfToken}}async function Bo(e,t){return e.runProtected(async e=>{let n=await fetch(`/api/v2/mcp/grant-constraints/validate`,{method:`POST`,credentials:`same-origin`,redirect:`error`,signal:e.signal,headers:zo(e),body:`{"constraint":${t}}`});if(await e.sessionLost(n))return;if(n.status!==200||n.headers.get(`Content-Type`)!==`application/json`)throw Error(`Matcher validation is unavailable.`);let r=Lo(await n.json(),[`valid`,`diagnostics`]);if(typeof r.valid!=`boolean`||!Array.isArray(r.diagnostics))throw Error(`Matcher validation returned an invalid response.`);if(r.valid){if(r.diagnostics.length!==0)throw Error(`Matcher validation returned an invalid response.`);return null}if(r.diagnostics.length!==1)throw Error(`Matcher validation returned an invalid response.`);let i=Lo(r.diagnostics[0],[`field`,`message`]);return`${Ro(i.field)}: ${Ro(i.message)}`})}var Vo=/^[0-7][0-9A-HJKMNP-TV-Z]{25}$/,Ho=/^(0|[1-9][0-9]*)$/;function Uo(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`invalid response`);let n=e;if(Object.keys(n).sort().join(`,`)!==[...t].sort().join(`,`))throw Error(`invalid response`);return n}function Wo(e){if(typeof e!=`string`)throw Error(`invalid response`);return e}function Go(e){let t=Wo(e);if(!Vo.test(t))throw Error(`invalid response`);return t}function Ko(e){let t=Wo(e);if(!Ho.test(t))throw Error(`invalid response`);return t}function qo(e,t){let n=Wo(e);if(!t.includes(n))throw Error(`invalid response`);return n}function Jo(e){let t=Uo(e,[`id`,`display_name`,`state`,`visibility`,`http_default`,`revision`,`credential_revision`,`credential`,`created_at`,`updated_at`]),n=t.credential===null?null:Uo(t.credential,[`id`,`fingerprint`,`revision`,`created_at`]);return{id:Go(t.id),displayName:Wo(t.display_name),state:qo(t.state,[`active`,`disabled`]),visibility:qo(t.visibility,[`requestable`,`allowed-only`,`all`]),httpDefault:qo(t.http_default,[`allow`,`block`]),revision:Ko(t.revision),credentialRevision:Ko(t.credential_revision),credential:n===null?null:{id:Go(n.id),fingerprint:Wo(n.fingerprint),revision:Ko(n.revision),createdAt:Wo(n.created_at)},hasCredential:n!==null,createdAt:Wo(t.created_at),updatedAt:Wo(t.updated_at)}}function Yo(e){let t=Uo(e,[`principal`,`default_grant`]),n=Uo(t.default_grant,[`id`,`description`,`revision`,`principal_id`,`effect`,`server_id`,`upstream_name`,`constraint`,`expires_at`,`state`,`created_at`]),r=Jo(t.principal);if(n.description!==`Default Gateway access`||Ko(n.revision)!==`1`||Go(n.principal_id)!==r.id||n.effect!==`allow`||n.server_id!==`00000000000000000000000000`||n.upstream_name!==null||n.constraint!==null||n.expires_at!==null||n.state!==`active`)throw Error(`invalid response`);return{principal:r,defaultGrantID:Go(n.id)}}function Xo(e){return{Accept:`application/json`,"X-CSRF-Token":e.csrfToken}}async function Zo(e,t){return e.runProtected(async e=>{let n=await fetch(t,{credentials:`same-origin`,redirect:`error`,signal:e.signal,headers:Xo(e)});if(!await e.sessionLost(n)){if(n.headers.get(`Content-Type`)!==`application/json`&&n.headers.get(`Content-Type`)!==`application/problem+json`)throw Error(`Agent data is unavailable.`);return{value:await n.json(),response:n}}})}async function Qo(e){let t=[],n=null,r=!1;for(;;){let i=await Zo(e,`/api/v2/principals?limit=50${n===null?``:`&cursor=${encodeURIComponent(n)}`}`);if(i===void 0)return[];if(i.response.status===409&&n!==null&&!r){t.length=0,n=null,r=!0;continue}if(!i.response.ok)throw Error(`Agent data is unavailable.`);let a=Uo(i.value,[`items`,`next_cursor`,`total_count`,`offset`]);if(!Array.isArray(a.items))throw Error(`invalid response`);if(t.push(...a.items.map(Jo)),a.next_cursor===null)return t;if(n=Wo(a.next_cursor),n.length===0||n.length>4096)throw Error(`invalid response`)}}var $o=class{listeners=new Set;principals=new Map;constructor(e,t){t.registerPanel({id:`principal-directory`,matches:e=>e===`#/overview`||[`invocations`,`http-traffic`].includes(H(e)?.destination??``),invalidations:[`authorization`],read:()=>Qo(e),publish:e=>{this.principals=new Map(e.map(e=>[e.id,e.displayName])),this.emit()}}),e.registerProtectedState(()=>{this.principals=new Map,this.emit()})}snapshot(){return this.principals}subscribe(e){return this.listeners.add(e),e(this.principals),()=>this.listeners.delete(e)}emit(){for(let e of this.listeners)e(this.principals)}};async function es(e,t){let n=await Zo(e,`/api/v2/principals/${t}`);if(n===void 0)return;if(!n.response.ok)throw Error(`Agent data is unavailable.`);let r=Jo(n.value),i=n.response.headers.get(`ETag`);if(r.id!==t||i!==`"principal-${t}-${r.revision}"`)throw Error(`The current agent revision is unavailable.`);return{principal:r,etag:i}}async function ts(e){if(e.headers.get(`Content-Type`)!==`application/json`)throw Error(`invalid response`);let t=Jo(await e.json());if(e.headers.get(`ETag`)!==`"principal-${t.id}-${t.revision}"`)throw Error(`invalid agent revision`);return t}async function ns(e){if(e.headers.get(`Content-Type`)!==`application/json`)throw Error(`invalid response`);let t=Uo(await e.json(),[`principal`,`bearer`]),n=Wo(t.bearer);if(!/^mgw_agent_[A-Za-z0-9_-]{43}$/.test(n))throw Error(`invalid response`);return{principal:Jo(t.principal),bearer:n}}async function rs(e){if(e.headers.get(`Content-Type`)!==`application/json`)throw Error(`invalid response`);return Yo(await e.json())}function is(e){return e===`allow`?`Allow requests`:`Block requests`}function as(e){return e===`requestable`?`Requestable`:e===`allowed-only`?`Allowed tools only`:`All tools`}function os({mutations:e,detail:t,onRefresh:n,notify:r,readUnavailable:i=!1}){let a=t===void 0,o=t?.principal,s=V({displayName:o?.displayName??``,state:o?.state??`active`,visibility:o?.visibility??`requestable`,httpDefault:o?.httpDefault??`block`}),[c,l]=z(s.current.displayName),[u,d]=z(s.current.state),[f,p]=z(s.current.visibility),[m,h]=z(s.current.httpDefault),[g,_]=z(t?.etag),[v,y]=z(),[b,x]=z(),[C]=z(()=>e.create()),[w,T]=z(()=>C.snapshot()),E=V(null),D=JSON.stringify({displayName:c,state:u,visibility:f,httpDefault:m})!==JSON.stringify(s.current),O=!a&&(i||g!==t?.etag),k=Cr(D);B(()=>C.subscribe(T),[C]),B(()=>()=>C.close(),[C]),B(()=>{o===void 0||D||w.state===`uncertain`||w.requiresRefresh||(s.current={displayName:o.displayName,state:o.state,visibility:o.visibility,httpDefault:o.httpDefault},l(o.displayName),d(o.state),p(o.visibility),h(o.httpDefault),_(t?.etag))},[o?.id,t?.etag]);let A=async e=>{let t=await e;if(t.kind===`acknowledged`){C.abandon();let e=`principal`in t.value?t.value.principal:t.value;s.current={displayName:e.displayName,state:e.state,visibility:e.visibility,httpDefault:e.httpDefault},l(e.displayName),d(e.state),p(e.visibility),h(e.httpDefault),_(`"principal-${e.id}-${e.revision}"`),a?(r(`Agent created.`),k(`#/agents/${e.id}`,!0)):(x(`Agent settings saved.`),n())}},j=()=>{if(y(void 0),x(void 0),c.length===0||new TextEncoder().encode(c).length>256){y(`Display name must contain 1–256 UTF-8 bytes.`);return}if(a)return{authority:!1,spec:{route:`/api/v2/principals`,method:`POST`,body:JSON.stringify({display_name:c,visibility:f,http_default:m}),precondition:null,requiresPrecondition:!1,idempotency:`none`,successStatuses:[201],decode:rs}};if(t===void 0||O||w.state===`uncertain`||w.requiresRefresh)return;let e=t.principal,n=s.current,r={};if(c!==n.displayName&&(r.display_name=c),u!==n.state&&(r.state=u),f!==n.visibility&&(r.visibility=f),m!==n.httpDefault&&(r.http_default=m),Object.keys(r).length===0){y(`Change at least one agent field.`);return}return{authority:r.state!==void 0||r.http_default!==void 0,spec:{route:`/api/v2/principals/${e.id}`,method:`PATCH`,body:JSON.stringify(r),precondition:g??null,requiresPrecondition:!0,idempotency:`none`,successStatuses:[200],decode:async t=>{let n=await ts(t);if(n.id!==e.id)throw Error(`invalid agent identity`);return n}}}},M=()=>{let e=j();e!==void 0&&(C.begin(e.spec),a||e.authority?C.confirm():A(C.submit()))},N=w.state===`submitting`||w.state===`confirming`||w.availability===`storage_latched`;return U(`section`,{class:`panel domain-panel`,"aria-labelledby":`principal-editor-title`,children:[U(`div`,{class:`panel-heading`,children:U(`div`,{children:U(`h2`,{id:`principal-editor-title`,children:a?`Agent configuration`:`Edit agent`})})}),a&&U(S,{children:[U(`p`,{children:`Creating an agent also adds the ordinary Default Gateway access grant for Gateway's six fixed MCP self-service tools, not downstream tools or future protocols.`}),U(`p`,{class:`bounded-note`,children:`Gateway generates the agent ID as a permanent identity. The display name and MCP discovery visibility can be changed later.`})]}),U(`form`,{id:`principal-editor-form`,"data-testid":`principal-editor`,onSubmit:e=>{e.preventDefault(),M()},children:[U(J,{id:`principal-display-name`,label:`Display name`,required:!0,children:e=>U(`input`,{...e,"data-testid":`principal-display-name`,placeholder:`Research assistant`,value:c,disabled:N,onInput:e=>l(e.currentTarget.value),required:!0})}),!a&&U(J,{id:`principal-state`,label:`Agent enabled`,hint:`Disabling immediately removes current credential authority.`,children:e=>U(On,{attributes:e,checked:u===`active`,disabled:N,testID:`principal-state`,onChange:e=>d(e?`active`:`disabled`)})}),U(J,{id:`principal-visibility`,label:`MCP discovery visibility`,hint:`Discovery visibility grants no access; MCP grants remain authoritative.`,children:e=>U(`select`,{...e,"data-testid":`principal-visibility`,value:f,disabled:N,onChange:e=>p(e.currentTarget.value),children:[U(`option`,{value:`requestable`,children:`Requestable`}),U(`option`,{value:`allowed-only`,children:`Allowed tools only`}),U(`option`,{value:`all`,children:`All tools`})]})}),U(J,{id:`principal-http-default`,label:`HTTP default`,hint:`Default allow supplies no credential, tunnel permission or local/private access.`,children:e=>U(`select`,{...e,value:m,disabled:N,onChange:e=>h(e.currentTarget.value),children:[U(`option`,{value:`block`,children:`Block requests`}),U(`option`,{value:`allow`,children:`Allow requests`})]})})]}),(O||w.requiresRefresh||w.state===`uncertain`)&&t!==void 0&&U(K,{state:`warning`,title:`Review current agent settings`,children:[U(`p`,{children:`Your draft is preserved. Last loaded settings:`}),U(`dl`,{class:`detail-facts`,children:[U(`div`,{children:[U(`dt`,{children:`Display name`}),U(`dd`,{children:t.principal.displayName})]}),U(`div`,{children:[U(`dt`,{children:`Agent enabled`}),U(`dd`,{children:t.principal.state===`active`?`Enabled`:`Disabled`})]}),U(`div`,{children:[U(`dt`,{children:`MCP discovery visibility`}),U(`dd`,{children:as(t.principal.visibility)})]}),U(`div`,{children:[U(`dt`,{children:`HTTP default`}),U(`dd`,{children:is(t.principal.httpDefault)})]}),U(`div`,{children:[U(`dt`,{children:`Revision`}),U(`dd`,{children:t.principal.revision})]})]}),U(`div`,{class:`form-actions`,children:[U(`button`,{type:`button`,onClick:n,children:`Refresh current settings`}),w.state!==`uncertain`&&U(`button`,{type:`button`,disabled:i,onClick:()=>{let e=t.principal,n=s.current;c===n.displayName&&l(e.displayName),u===n.state&&d(e.state),f===n.visibility&&p(e.visibility),m===n.httpDefault&&h(e.httpDefault),s.current={displayName:e.displayName,state:e.state,visibility:e.visibility,httpDefault:e.httpDefault},_(t.etag),C.abandon()},children:`Use reviewed revision; keep draft`}),w.state===`uncertain`&&U(`button`,{type:`button`,disabled:i,onClick:()=>{let e=t.principal;s.current={displayName:e.displayName,state:e.state,visibility:e.visibility,httpDefault:e.httpDefault},l(e.displayName),d(e.state),p(e.visibility),h(e.httpDefault),_(t.etag),C.abandon(),x(void 0)},children:`Discard uncertain draft; use current settings`})]})]}),v!==void 0&&U(K,{state:`error`,title:`Check agent configuration`,children:U(`p`,{children:v})}),w.problem!==void 0&&U(K,{state:`error`,title:_n(w.problem),children:w.requiresRefresh&&U(`p`,{children:`Review current settings and the preserved draft before accepting a refreshed revision.`})}),w.state===`uncertain`&&U(K,{state:`warning`,title:`Agent outcome is unknown`,children:U(`p`,{children:`Do not replay this non-idempotent change. Refresh the agent and authorization state to investigate.`})}),b!==void 0&&U(K,{state:`empty`,title:b}),U(`button`,{ref:E,class:`${a?`create-action`:`primary-action`} form-submit-action`,"data-testid":`principal-editor-submit`,form:`principal-editor-form`,type:`submit`,disabled:N||!a&&!D||O||w.requiresRefresh||w.state===`uncertain`,children:w.state===`submitting`?`Submitting…`:a?`Review and create`:`Save agent`}),U(jn,{id:`principal-change-confirm`,open:w.state===`confirming`,title:a?`Review agent`:`Review agent changes`,consequence:a?U(`div`,{class:`review-stack`,children:[U(`p`,{children:`Review this permanent identity and its initial MCP self-service access before creating it. Discovery visibility grants no access; MCP grants remain authoritative.`}),U(`dl`,{class:`detail-facts`,children:[U(`div`,{children:[U(`dt`,{children:`Display name`}),U(`dd`,{children:c})]}),U(`div`,{children:[U(`dt`,{children:`MCP discovery visibility`}),U(`dd`,{children:as(f)})]}),U(`div`,{children:[U(`dt`,{children:`HTTP default`}),U(`dd`,{children:is(m)})]}),U(`div`,{children:[U(`dt`,{children:`Initial MCP self-service access`}),U(`dd`,{children:`Default Gateway access — an ordinary grant for Gateway's six fixed MCP self-service tools, not downstream tools or future protocols.`})]})]})]}):U(`div`,{class:`review-stack`,children:[U(`dl`,{class:`detail-facts`,children:[c!==s.current.displayName&&U(`div`,{children:[U(`dt`,{children:`Display name`}),U(`dd`,{children:c})]}),u!==s.current.state&&U(`div`,{children:[U(`dt`,{children:`Agent enabled`}),U(`dd`,{children:u===`active`?`Enabled`:`Disabled`})]}),f!==s.current.visibility&&U(`div`,{children:[U(`dt`,{children:`MCP discovery visibility`}),U(`dd`,{children:as(f)})]}),m!==s.current.httpDefault&&U(`div`,{children:[U(`dt`,{children:`HTTP default`}),U(`dd`,{children:is(m)})]})]}),u!==s.current.state&&U(`p`,{children:u===`disabled`?`Disabling revokes current agent authority and interrupts credential-bound sessions and streams.`:`Re-enabling does not restore revoked credentials or removed MCP self-service access.`}),m!==s.current.httpDefault&&U(`p`,{children:`Explicit blocks still win. Default allow supplies no credential, tunnel permission or local/private access.`})]}),confirmLabel:a?`Create agent`:`Save agent changes`,destructive:!a&&u===`disabled`,returnFocus:E,onCancel:()=>C.abandon(),onConfirm:()=>void A(C.submit())})]})}function ss({mutations:e,sinks:t,detail:n,onRefresh:r}){let i=n.principal,[a]=z(()=>e.create()),[o,s]=z(()=>a.snapshot()),[c,l]=z(`issue`),[u,d]=z(),[f,p]=z(),[m,h]=z(),g=V(null),_=V(null);B(()=>a.subscribe(s),[a]),B(()=>()=>a.close(),[a]),B(()=>()=>u?.cancel(),[u]);let v=()=>{h(void 0);let e={route:`/api/v2/principals/${i.id}/credential`,method:`POST`,body:`{}`,precondition:n.etag,requiresPrecondition:!0,idempotency:`none`,successStatuses:[201],decode:ns};l(i.hasCredential?`rotate`:`issue`),d(void 0),a.begin(e),a.confirm()},y=()=>{h(void 0);let e={route:`/api/v2/principals/${i.id}/credential`,method:`DELETE`,body:`{}`,precondition:n.etag,requiresPrecondition:!0,idempotency:`none`,successStatuses:[200],decode:ts};l(`revoke`),d(void 0),a.begin(e),a.confirm()},b=()=>{u?.cancel(),d(void 0),a.abandon()},x=async()=>{let e=u;if(c!==`revoke`&&e===void 0&&(e=t.prepareOneTime(`${i.hasCredential?`Replacement`:`New`} agent bearer for ${i.displayName}`),e===void 0)){h(`The protected one-time display could not be prepared. No credential was changed.`),a.abandon();return}let o=await a.submit();if(o.kind===`acknowledged`){if(p(void 0),c!==`revoke`){if(!(`bearer`in o.value))throw Error(`invalid response`);let t=e?.publish(o.value.bearer)??`lost`;h(t===`published`?`The one-time agent bearer is ready. It cannot be revealed again.`:c===`rotate`?`The replacement may now be current and the prior bearer may already be invalid. Review agent metadata, then explicitly rotate or revoke the lost current credential. Do not replay the operation.`:`A current credential may now occupy the slot, but its bearer was lost and cannot be recovered. Review agent metadata, then explicitly rotate or revoke it. Do not replay issue.`)}else h(`Agent credential revoked. Prior authority no longer authenticates.`);d(void 0),a.abandon(),r();return}o.kind===`rejected`&&o.requiresRefresh&&(p(n.etag),r()),c!==`revoke`&&(o.kind===`uncertain`?e?.lose():e?.cancel()),d(void 0)},S=i.state!==`active`||o.state===`submitting`||o.availability===`storage_latched`||f===n.etag;return U(`section`,{class:`detail-section`,"aria-labelledby":`principal-credential-title`,"data-testid":`principal-credential-actions`,children:[U(`div`,{class:`panel-heading`,children:[U(`div`,{children:U(`h2`,{id:`principal-credential-title`,children:`Agent credential`})}),U(G,{state:i.hasCredential?`current`:`empty`,children:i.hasCredential?`Issued`:`Not issued`})]}),U(`p`,{children:`Only one agent credential may be active at a time. Rotating it replaces the current credential.`}),i.credential!==null&&U(`dl`,{class:`detail-facts`,children:[U(`div`,{children:[U(`dt`,{children:`Credential ID`}),U(`dd`,{class:`technical-value`,children:i.credential.id})]}),U(`div`,{children:[U(`dt`,{children:`Fingerprint`}),U(`dd`,{class:`technical-value`,children:i.credential.fingerprint})]}),U(`div`,{children:[U(`dt`,{children:`Issued`}),U(`dd`,{children:U(Y,{value:i.credential.createdAt})})]}),U(`div`,{children:[U(`dt`,{children:`Credential revision`}),U(`dd`,{children:i.credential.revision})]})]}),i.state!==`active`&&U(K,{state:`unavailable`,title:`Agent is disabled`,children:U(`p`,{children:`Re-enable the agent before issuing agent authority.`})}),o.problem!==void 0&&U(K,{state:`error`,title:_n(o.problem),children:o.requiresRefresh&&U(`p`,{children:`Refresh the agent and review its current authority before trying a new action.`})}),o.state===`uncertain`&&U(K,{state:`warning`,title:`Credential outcome is unknown`,children:U(`p`,{children:c===`rotate`?`Do not replay. The replacement may be current and the prior bearer may already be invalid. Refresh the agent, then explicitly rotate or revoke the observed current credential.`:c===`issue`?`Do not replay issue. A current credential may occupy the slot while its bearer is permanently lost. Refresh the agent, then explicitly rotate or revoke the observed credential.`:`Do not replay revoke. Authority may already be revoked. Refresh the agent before another explicit action.`})}),m!==void 0&&U(K,{state:`empty`,title:m}),U(`div`,{class:`inline-actions`,children:[U(`button`,{ref:g,class:i.hasCredential?`danger-action`:`create-action`,"data-testid":`principal-credential-issue`,type:`button`,disabled:S,onClick:v,children:i.hasCredential?`Rotate credential`:`Issue credential`}),i.hasCredential&&U(`button`,{ref:_,class:`danger-action`,"data-testid":`principal-credential-revoke`,type:`button`,disabled:S,onClick:y,children:`Revoke credential`})]}),U(jn,{id:`principal-credential-confirm`,open:o.state===`confirming`,title:c===`rotate`?`Rotate agent credential?`:c===`issue`?`Issue agent credential?`:`Revoke agent credential?`,consequence:c===`rotate`?U(`p`,{children:`Rotating immediately replaces current agent authority. The new bearer is displayed once.`}):c===`issue`?U(`p`,{children:`The new bearer is displayed once and becomes this agent's current authority.`}):U(`p`,{children:`The current bearer, authenticated sessions, and streams stop authorizing this agent.`}),confirmLabel:c===`rotate`?`Rotate credential`:c===`issue`?`Issue credential`:`Revoke credential`,destructive:c===`revoke`,returnFocus:c===`revoke`?_:g,onCancel:b,onConfirm:()=>void x()})]})}function cs({session:e,mutations:t,sinks:n,resolved:r,view:i,onRefresh:a,notify:o}){let s=r.location.segments,c=s[1]===`new`,l=s.length===2&&!c?s[1]:void 0,[u,d]=z(),[f,p]=z();if(B(()=>{let t=!0;return p(void 0),c||l===void 0||l!==void 0&&(d(e=>e?.principal.id===l?e:void 0),es(e,l).then(e=>{t&&e!==void 0&&d(e)}).catch(e=>{t&&p(e instanceof Error?e.message:`Agent data is unavailable.`)})),()=>{t=!1}},[r.canonicalFragment,i.generation]),c)return U(`div`,{class:`domain-view`,"data-testid":`principal-create-view`,children:U(os,{mutations:t,onRefresh:a,notify:o})});if(l!==void 0&&f!==void 0&&u?.principal.id!==l)return U(K,{state:`error`,title:`Agent data unavailable`,children:U(`p`,{children:f})});if(l!==void 0){if(u?.principal.id!==l)return U(K,{state:`loading`,title:`Loading agent`});let e=u.principal;return U(`div`,{class:`domain-view`,"data-testid":`principal-detail`,children:[f!==void 0&&U(K,{state:`error`,title:`Current agent data unavailable`,children:U(`p`,{children:[f,` Your draft is preserved; refresh before saving.`]})}),U(`nav`,{class:`detail-navigation`,"aria-label":`Agent navigation`,children:U(`a`,{href:`#/agents`,children:`Back to agents`})}),U(`header`,{class:`detail-context`,"data-testid":`detail-context`,children:[U(`div`,{class:`detail-context-heading`,children:[U(`div`,{children:U(`h1`,{id:`principal-page-title`,tabindex:-1,children:e.displayName})}),U(G,{state:e.state===`active`?`current`:`neutral`,children:e.state===`active`?`Active`:`Disabled`})]}),U(`p`,{class:`technical-value`,children:e.id})]}),U(`section`,{class:`detail-section`,"aria-labelledby":`principal-title`,children:[U(`div`,{class:`panel-heading`,children:U(`h2`,{id:`principal-title`,children:`Agent details`})}),U(`h3`,{children:`Access defaults`}),U(`dl`,{class:`detail-facts`,children:[U(`div`,{children:[U(`dt`,{children:`MCP discovery visibility`}),U(`dd`,{children:as(e.visibility)})]}),U(`div`,{children:[U(`dt`,{children:`HTTP default`}),U(`dd`,{children:is(e.httpDefault)})]})]}),U(`h3`,{children:`Metadata`}),U(`dl`,{class:`detail-facts`,children:[U(`div`,{children:[U(`dt`,{children:`Agent revision`}),U(`dd`,{children:e.revision})]}),U(`div`,{children:[U(`dt`,{children:`Updated`}),U(`dd`,{children:U(Y,{value:e.updatedAt})})]})]})]}),U(os,{mutations:t,detail:u,readUnavailable:f!==void 0,onRefresh:a,notify:o},e.id),U(ss,{mutations:t,sinks:n,detail:u,onRefresh:a})]})}return U(ls,{session:e,resolved:r,view:i})}function ls({session:e,resolved:t,view:n}){let{items:r,controls:i}=Nr(e,t,n,(t,n,r)=>{let i=new URLSearchParams({limit:`50`,sort:t.sort??`name`,direction:t.direction??`ascending`});for(let e of[`name`,`state`,`visibility`,`http_default`]){let n=t[`filter_${e}`];n!==void 0&&i.set(e,n)}return n!==null&&i.set(`cursor`,n),Mr(e,`/api/v2/principals?${i}`,Jo,r)},Cr(!1),{key:`name`,direction:`ascending`});return U(`div`,{class:`domain-view`,"data-testid":`principals-view`,children:[U(`div`,{class:`collection-toolbar`,children:U(`a`,{class:`button-link create-action`,href:`#/agents/new`,"data-testid":`principal-create-link`,children:`Create agent`})}),U(`section`,{class:`panel domain-panel`,"aria-labelledby":`page-title`,children:U(Dn,{caption:`Agent identities`,rowHeaderKey:`name`,additionalSorts:[{key:`id`,label:`Agent ID`,sortValue:e=>e.id}],remote:i,itemNames:{singular:`agent`,plural:`agents`},emptyTitle:`No agents`,items:r,rowKey:e=>e.id,initialSort:{key:`name`,direction:`ascending`},rowTestID:`principal-row`,filters:[{key:`name`,label:`Name or ID`,type:`text`,value:e=>e.displayName,literalValues:e=>[e.id]},{key:`state`,label:`Status`,type:`select`,value:e=>e.state,options:[{value:`active`,label:`Active`},{value:`disabled`,label:`Disabled`}]},{key:`visibility`,label:`MCP discovery visibility`,type:`select`,value:e=>e.visibility,options:[{value:`requestable`,label:`Requestable`},{value:`allowed-only`,label:`Allowed tools only`},{value:`all`,label:`All tools`}]},{key:`http_default`,label:`HTTP default`,type:`select`,value:e=>e.httpDefault,options:[{value:`block`,label:`Block requests`},{value:`allow`,label:`Allow requests`}]}],columns:[{key:`name`,label:`Agent`,role:`identity`,sortValue:e=>e.displayName,render:e=>U(q,{primary:U(`a`,{href:`#/agents/${e.id}`,children:e.displayName}),secondary:e.id})},{key:`state`,label:`Status`,role:`status`,sortValue:e=>e.state,render:e=>U(G,{state:e.state===`active`?`current`:`neutral`,children:e.state===`active`?`Active`:`Disabled`})},{key:`visibility`,label:`MCP discovery visibility`,role:`status`,render:e=>as(e.visibility)},{key:`http-default`,label:`HTTP default`,role:`status`,render:e=>is(e.httpDefault)}]})})]})}var us=/^[0-7][0-9A-HJKMNP-TV-Z]{25}$/;function ds(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`invalid response`);let n=e;if(Object.keys(n).sort().join(`,`)!==[...t].sort().join(`,`))throw Error(`invalid response`);return n}function fs(e){if(typeof e!=`string`)throw Error(`invalid response`);return e}function ps(e){let t=fs(e);if(!us.test(t))throw Error(`invalid response`);return t}function ms(e){let t=ds(e,[..._r(e),`id`,`description`,`revision`,`principal_id`,`effect`,`server_id`,`upstream_name`,`constraint`,`expires_at`,`state`,`created_at`]),n=vr(t);if(n&&(t.effect!==`allow`||t.upstream_name!==null||t.constraint!==null)||t.effect!==`allow`&&t.effect!==`deny`||t.state!==`active`&&t.state!==`expired`||t.upstream_name!==null&&typeof t.upstream_name!=`string`||t.expires_at!==null&&typeof t.expires_at!=`string`||t.constraint!==null&&(typeof t.constraint!=`object`||Array.isArray(t.constraint)))throw Error(`invalid response`);return{readOnly:n,id:ps(t.id),description:t.description===null?null:fs(t.description),revision:fs(t.revision),principalID:ps(t.principal_id),effect:t.effect,serverID:ps(t.server_id),upstreamName:t.upstream_name,constraint:t.constraint,expiresAt:t.expires_at,state:t.state,createdAt:fs(t.created_at)}}function hs(e){return{Accept:`application/json`,"X-CSRF-Token":e.csrfToken}}async function gs(e,t){return e.runProtected(async e=>{let n=await fetch(t,{credentials:`same-origin`,redirect:`error`,signal:e.signal,headers:hs(e)});if(await e.sessionLost(n))return;let r=n.headers.get(`Content-Type`);if(r!==`application/json`&&r!==`application/problem+json`)throw Error(`Grant data is unavailable.`);return{response:n,value:await n.json()}})}async function _s(e){let t=[],n=null;for(;;){let r=new URLSearchParams({limit:`50`});n!==null&&r.set(`cursor`,n);let i=await gs(e,`/api/v2/mcp/servers?${r}`);if(i===void 0)return[];if(!i.response.ok)throw Error(`Server data is unavailable.`);let a=ds(i.value,[`items`,`next_cursor`]);if(!Array.isArray(a.items))throw Error(`invalid response`);if(t.push(...a.items.map(Wa)),a.next_cursor===null)return t;n=fs(a.next_cursor)}}async function vs(e){let t=[],n=null,r=!1;for(;;){let i=new URLSearchParams({limit:`50`});n!==null&&i.set(`cursor`,n);let a=await gs(e,`/api/v2/mcp/grants?${i}`);if(a===void 0)return[];if(a.response.status===409&&n!==null&&!r){t.length=0,n=null,r=!0;continue}if(!a.response.ok)throw Error(`Grant data is unavailable.`);let o=ds(a.value,[`items`,`next_cursor`,`total_count`,`offset`]);if(!Array.isArray(o.items))throw Error(`invalid response`);if(t.push(...o.items.map(e=>{let t=ds(e,[`grant`,`principal_display_name`,`server_display_name`]);return fs(t.principal_display_name),fs(t.server_display_name),ms(t.grant)})),o.next_cursor===null)return t;if(n=fs(o.next_cursor),n.length===0||n.length>4096)throw Error(`invalid response`)}}async function ys(e,t){let n=await gs(e,`/api/v2/mcp/grants/${t}`);if(n!==void 0){if(!n.response.ok)throw Error(`Grant data is unavailable.`);return ms(n.value)}}async function bs(e){if(e.headers.get(`Content-Type`)!==`application/json`)throw Error(`invalid response`);return ms(await e.json())}function xs({session:e,mutations:t,query:n,principals:r,servers:i}){let a=V({description:``,principalID:n.principal_id??``,effect:`allow`,readOnly:!1,serverID:n.server_id??``,scope:`server`,upstreamName:``,expiresAt:``,atoms:[]}),[o,s]=z(a.current.description),[c,l]=z(a.current.principalID),[u,d]=z(a.current.effect),[f,p]=z(!1),[m,h]=z(a.current.serverID),[g,_]=z(a.current.scope),[v,y]=z(``),[b,x]=z(),[S,C]=z(),[w,T]=z(!1),[E,D]=z(!1),[O,k]=z(``),[A,j]=z([]),[M,N]=z(),[ee,P]=z(!1),[te,F]=z(!1),ne=V(null),[I]=z(()=>t.create()),[re,ie]=z(()=>I.snapshot()),ae=b?.find(e=>e.serverID===m&&e.upstreamName===v),oe=S===void 0||S.serverID!==m||S.upstreamName!==v||S.id!==ae?.id?void 0:To(S.descriptor),se=us.test(m)?v===``?`Choose a tool`:w?`Unavailable`:b===void 0?`Loading…`:ae===void 0?`Unknown`:`Known`:`Select a server`,ce=us.test(m)?w?`Catalog unavailable. Manual entry is still available.`:ae===void 0?null:E?`Schema unavailable. Manual conditions are still available.`:oe===void 0?`Loading schema…`:null:null,L=(()=>{try{return`{"description":${o===``?`null`:JSON.stringify(o)},"principal_id":${JSON.stringify(c)},"effect":${JSON.stringify(u)},"server_id":${JSON.stringify(m)},"upstream_name":${g===`server`?`null`:JSON.stringify(v)},"constraint":${Fo(A)},"expires_at":${O===``?`null`:JSON.stringify(new Date(O).toISOString())}${yr(f)}}`}catch{return`Complete the policy to review its serialized form.`}})(),le=JSON.stringify({description:o,principalID:c,effect:u,readOnly:f,serverID:m,scope:g,upstreamName:v,expiresAt:O,atoms:A}),ue=V(le);ue.current=le;let de=Cr(le!==JSON.stringify(a.current));B(()=>I.subscribe(ie),[I]),B(()=>()=>I.close(),[I]),B(()=>{let t=new AbortController;return T(!1),x(void 0),g!==`tool`||!us.test(m)||ko(e,m,t.signal).then(e=>{!t.signal.aborted&&e!==void 0&&x(e)}).catch(()=>{t.signal.aborted||T(!0)}),()=>t.abort()},[g,m,e]),B(()=>{let t=new AbortController;return D(!1),C(void 0),ae===void 0||Ao(e,ae,t.signal).then(e=>{!t.signal.aborted&&e!==void 0&&C(e)}).catch(()=>{t.signal.aborted||D(!0)}),()=>t.abort()},[ae,m,e]);let fe=async()=>{let t=ue.current;N(void 0);try{if(o.length>0&&(o.trim()!==o||new TextEncoder().encode(o).length>256))throw Error(`Description must be at most 256 bytes without surrounding whitespace.`);if(gn(o))throw Error(`Description cannot contain control characters.`);if(!us.test(c)||!us.test(m))throw Error(`Agent and server IDs must be complete Gateway IDs.`);if(f&&(g!==`server`||u!==`allow`))throw Error(`Read-only access requires server-wide ALLOW scope.`);if(g===`tool`&&v.length===0)throw Error(`Exact-tool scope requires an upstream tool name.`);if(g===`server`&&A.length!==0)throw Error(`Server-wide grants cannot have argument conditions.`);if(A.length>16)throw Error(`At most 16 matcher atoms are allowed.`);if(A.some(e=>!No(e.pointer)))throw Error(`Each atom requires a valid RFC 6901 JSON pointer.`);if(new Set(A.map(e=>`${e.operator}:${e.pointer}`)).size!==A.length)throw Error(`Pointers must be unique within each operator.`);if(A.some(e=>e.operator===`regex`&&new TextEncoder().encode(e.value).length>1024))throw Error(`RE2 patterns must be at most 1024 bytes.`);if(!document.getElementById(`grant-expiry`).validity.valid)throw Error(`Choose a complete expiry date and time, or clear it for no expiry.`);if(O!==``&&(Number.isNaN(Date.parse(O))||Date.parse(O)<=Date.now()))throw Error(`Choose an expiry date and time in the future.`);let n=Fo(A);if(n!==`null`){F(!0);let r=await Bo(e,n);if(r===void 0||ue.current!==t)return;if(r!==null)throw Error(r)}let r={route:`/api/v2/mcp/grants`,method:`POST`,body:`{"description":${o===``?`null`:JSON.stringify(o)},"principal_id":${JSON.stringify(c)},"effect":${JSON.stringify(u)},"server_id":${JSON.stringify(m)},"upstream_name":${g===`server`?`null`:JSON.stringify(v)},"constraint":${n},"expires_at":${O===``?`null`:JSON.stringify(new Date(O).toISOString())}${yr(f)}}`,precondition:null,requiresPrecondition:!1,idempotency:`none`,successStatuses:[201],decode:async e=>{let t=await bs(e);if(t.readOnly!==f)throw Error(`invalid response`);return t}};I.begin(r),P(!0)}catch(e){N(e instanceof Error?e.message:`Invalid grant.`)}finally{F(!1)}},R=te||re.state===`submitting`||re.availability===`storage_latched`;return U(`div`,{class:`domain-view`,"data-testid":`grant-create-view`,children:U(`section`,{class:`panel domain-panel`,"aria-labelledby":`grant-create-title`,children:[U(`div`,{class:`panel-heading`,children:U(`div`,{children:U(`h2`,{id:`grant-create-title`,children:`Create MCP Grant`})})}),U(`p`,{class:`bounded-note`,children:`The effect, target, scope, conditions, and expiry cannot be edited after creation. You can update the optional description later.`}),U(`form`,{onSubmit:e=>{e.preventDefault(),fe()},children:[U(J,{id:`grant-description`,label:`Description`,optional:!0,children:e=>U(`input`,{...e,"data-testid":`grant-description`,placeholder:`Example tool access policy`,value:o,maxlength:256,onInput:e=>s(e.currentTarget.value)})}),U(J,{id:`grant-principal`,label:`Agent`,required:!0,children:e=>U(`select`,{...e,"data-testid":`grant-principal`,value:c,onChange:e=>l(e.currentTarget.value),required:!0,children:[U(`option`,{value:``,children:`Choose an agent`}),r.map(e=>U(`option`,{value:e.id,children:[e.displayName,` — `,e.id,e.state===`disabled`?` (Disabled)`:``]},e.id))]})}),U(J,{id:`grant-effect`,label:`Effect`,children:e=>U(`select`,{...e,"data-testid":`grant-effect`,value:u,onChange:e=>{d(e.currentTarget.value),e.currentTarget.value!==`allow`&&p(!1)},children:[U(`option`,{value:`allow`,children:`ALLOW`}),U(`option`,{value:`deny`,children:`DENY`})]})}),U(J,{id:`grant-server`,label:`Server or Gateway scope`,required:!0,children:e=>U(`select`,{...e,"data-testid":`grant-server`,value:m,onChange:e=>h(e.currentTarget.value),required:!0,children:[U(`option`,{value:``,children:`Choose a server`}),U(`option`,{value:`00000000000000000000000000`,children:`Gateway self-service tools`}),i.filter(e=>e.desiredState!==`deleted`).map(e=>U(`option`,{value:e.id,children:[e.displayName,` — `,e.id,e.desiredState===`disabled`?` (Disabled)`:``]},e.id))]})}),U(J,{id:`grant-scope`,label:`Scope`,children:e=>U(`select`,{...e,"data-testid":`grant-scope`,value:g,onChange:e=>{let t=e.currentTarget.value;_(t),t===`tool`&&p(!1),t===`server`&&j([])},children:[U(`option`,{value:`server`,children:`Entire server`}),U(`option`,{value:`tool`,children:`Exact upstream tool`})]})}),g===`server`&&u===`allow`&&U(`div`,{children:U(J,{id:`grant-read-only`,label:`Allowed tools`,...f?{hint:`Includes current and future tools marked readOnlyHint=true. The Gateway does not verify that these tools are read-only; they may still change data.`}:{},children:e=>U(`select`,{...e,"data-testid":`grant-read-only`,value:f?`read-only`:`all`,onChange:e=>p(e.currentTarget.value===`read-only`),children:[U(`option`,{value:`all`,children:`All tools`}),U(`option`,{value:`read-only`,children:`Only tools marked read-only`})]})})}),g===`tool`&&U(`div`,{children:[U(J,{id:`grant-upstream`,label:`Tool name`,hint:`Choose a tool or enter an exact name.`,required:!0,children:e=>U(`div`,{class:`matcher-tool-input`,children:[U(`span`,{"data-testid":`grant-namespace`,children:[i.find(e=>e.id===m)?.namespace??(m===`00000000000000000000000000`?`mcp_gateway`:`Choose a server`),` `,`.`]}),U(kn,{attributes:e,label:`Tool name`,testID:`grant-upstream`,placeholder:`lookup`,value:v,options:(b??[]).filter(e=>e.serverID===m).map(e=>({value:e.upstreamName})),onChange:y}),U(jo,{status:se,testID:`grant-tool-recognition`})]})}),ce&&U(`p`,{class:`bounded-note`,role:`status`,"data-testid":`grant-tool-posture`,children:ce})]}),g===`tool`&&U(`section`,{class:`subpanel`,"aria-labelledby":`constraint-title`,children:[U(`h3`,{id:`constraint-title`,children:`Conditions — All must match`}),U(`p`,{class:`field-hint`,children:`Choose suggested fields or enter custom JSON pointers.`}),oe?.unsupported&&U(`p`,{class:`bounded-note`,"data-testid":`matcher-schema-posture`,children:`Some schema fields cannot be suggested. Custom pointers are still available.`}),U(Io,{idPrefix:`constraint`,testPrefix:`constraint`,addTestID:`add-constraint-atom`,atoms:A,suggestions:oe,schemaState:us.test(m)&&!w&&(b===void 0||ae!==void 0&&!E&&oe===void 0)?`loading`:`unavailable`,onChange:e=>{N(void 0),j(e)}})]}),U(J,{id:`grant-expiry`,label:`Expires`,hint:`Choose a future date and time in your local timezone. Leave blank for no expiry.`,optional:!0,children:e=>U(`input`,{...e,"data-testid":`grant-expiry`,type:`datetime-local`,step:`1`,value:O,onInput:e=>k(e.currentTarget.value)})}),M!==void 0&&U(K,{state:`error`,title:`Check grant configuration`,children:U(`p`,{children:M})}),re.problem!==void 0&&U(K,{state:`error`,title:_n(re.problem)}),re.state===`uncertain`&&U(K,{state:`warning`,title:`Grant outcome is unknown`,children:U(`p`,{children:`Do not replay this non-idempotent creation. Refresh the filtered grant list to investigate.`})}),U(`button`,{ref:ne,class:`create-action form-submit-action`,"data-testid":`grant-create-submit`,type:`submit`,disabled:R,children:te?`Validating matcher…`:re.state===`submitting`?`Creating…`:`Review and create`})]}),U(jn,{id:`grant-create-confirm`,open:ee,title:`Review grant`,consequence:U(`div`,{class:`review-stack`,children:[U(`p`,{children:`This creates one immutable authorization policy. Every matcher atom is required (AND), and any matching DENY takes precedence over ALLOW.`}),f&&U(`p`,{children:`Includes current and future tools marked readOnlyHint=true. The Gateway does not verify that these tools are read-only; they may still change data.`}),A.length===0&&U(K,{state:`warning`,title:`Unconstrained access matches every argument object`}),U(`h3`,{children:`Identity and authority`}),U(`dl`,{class:`detail-facts`,children:[U(`div`,{children:[U(`dt`,{children:`Description`}),U(`dd`,{children:o})]}),U(`div`,{children:[U(`dt`,{children:`Agent`}),U(`dd`,{children:[r.find(e=>e.id===c)?.displayName??`Unknown agent`,` `,`· `,c]})]}),U(`div`,{children:[U(`dt`,{children:`Effect`}),U(`dd`,{children:u===`allow`?`Allow`:`Deny`})]}),U(`div`,{children:[U(`dt`,{children:`Server and literal tool`}),U(`dd`,{children:[i.find(e=>e.id===m)?.displayName??`Gateway self-service tools`,` `,`· `,m,g===`tool`?` · ${v}`:f?` · Read-only tools`:` · All tools`]})]}),U(`div`,{children:[U(`dt`,{children:`Catalog posture`}),U(`dd`,{children:g===`server`?`Not applicable to server-wide authority`:w?`Unavailable — literal manual name`:ae===void 0||S===void 0||E?`No verified current descriptor — literal manual name`:`Current durable descriptor · catalog revision ${S.catalogRevision}`})]}),U(`div`,{children:[U(`dt`,{children:`Expires`}),U(`dd`,{children:O===``?`No expiry`:U(Y,{value:Number.isFinite(Date.parse(O))?new Date(O).toISOString():O})})]}),U(`div`,{children:[U(`dt`,{children:`Constraint`}),U(`dd`,{children:A.length===0?`None`:`v2 · ${A.filter(e=>e.operator===`equals`).length} equality · ${A.filter(e=>e.operator===`regex`).length} regex`})]})]}),U(`div`,{children:[U(`strong`,{children:`Read-only serialized policy`}),U(`textarea`,{class:`inert-json matcher-policy-review`,"data-testid":`grant-review-policy`,"aria-label":`Read-only serialized policy`,readOnly:!0,rows:8,value:L})]})]}),confirmLabel:`Create grant`,returnFocus:ne,onCancel:()=>{P(!1),I.abandon()},onConfirm:()=>{P(!1),I.submit().then(e=>{e.kind===`acknowledged`&&de(`#/mcp/grants/${e.value.id}`,!0)})}})]})})}function Ss({mutations:e,grant:t,onAcknowledged:n}){let[r,i]=z(t.description??``),[a,o]=z(),[s]=z(()=>e.create()),[c,l]=z(()=>s.snapshot());B(()=>s.subscribe(l),[s]),B(()=>()=>s.close(),[s]);let u=async()=>{if(o(void 0),r.length>0&&(r.trim()!==r||new TextEncoder().encode(r).length>256||gn(r))){o(`Description must be at most 256 bytes without surrounding whitespace or control characters.`);return}if(r===(t.description??``)){o(`Change the description before saving.`);return}s.begin({route:`/api/v2/mcp/grants/${t.id}`,method:`PATCH`,body:JSON.stringify({description:r===``?null:r}),precondition:`"grant-${t.id}-${t.revision}"`,requiresPrecondition:!0,idempotency:`none`,successStatuses:[200],decode:bs});let e=await s.submit();e.kind===`acknowledged`&&n(e.value)};return U(`section`,{class:`panel domain-panel`,"aria-labelledby":`grant-description-title`,children:[U(`div`,{class:`panel-heading`,children:U(`div`,{children:U(`h2`,{id:`grant-description-title`,children:`Edit grant description`})})}),U(`form`,{onSubmit:e=>{e.preventDefault(),u()},children:[U(J,{id:`grant-description-edit`,label:`Description`,optional:!0,children:e=>U(`input`,{...e,value:r,maxlength:256,onInput:e=>i(e.currentTarget.value)})}),a!==void 0&&U(K,{state:`error`,title:`Description not saved`,children:U(`p`,{children:a})}),c.state===`rejected`&&U(K,{state:`error`,title:`Description not saved`,children:U(`p`,{children:c.problem===void 0?`Refresh the grant before trying again.`:_n(c.problem)})}),c.state===`uncertain`&&U(K,{state:`warning`,title:`Save outcome unknown`,children:U(`p`,{children:`Refresh the grant to inspect its description before taking another action.`})}),U(`button`,{class:`primary-action form-submit-action`,type:`submit`,disabled:r===(t.description??``)||c.state===`submitting`||c.state===`uncertain`||c.availability===`storage_latched`,children:c.state===`submitting`?`Saving…`:`Save description`})]})]})}function Cs({session:e,mutations:t,grant:n}){let[r]=z(()=>t.create()),[i,a]=z(()=>r.snapshot()),[o,s]=z(!1),[c,l]=z(`create_first`),[u,d]=z(n.effect===`allow`?`deny`:`allow`),[f,p]=z(`configure`),[m,h]=z(),[g,_]=z(`delete`),[v,y]=z(!1),[b,x]=z(),C=V(null),w=!n.readOnly&&n.effect===`allow`&&n.serverID===`00000000000000000000000000`&&n.upstreamName===null&&n.constraint===null&&n.expiresAt===null;B(()=>r.subscribe(a),[r]),B(()=>()=>r.close(),[r]);let T=()=>{let e=n.readOnly&&u===`allow`;return{route:`/api/v2/mcp/grants`,method:`POST`,body:JSON.stringify({description:n.description,principal_id:n.principalID,effect:u,...e?{read_only:!0}:{},server_id:n.serverID,upstream_name:n.upstreamName,constraint:null,expires_at:null}),precondition:null,requiresPrecondition:!1,idempotency:`none`,successStatuses:[201],decode:async t=>{let n=await bs(t);if(n.readOnly!==e)throw Error(`invalid response`);return{kind:`created`,grant:n}}}},E=()=>({route:`/api/v2/mcp/grants/${n.id}`,method:`DELETE`,body:null,precondition:null,requiresPrecondition:!1,idempotency:`none`,successStatuses:[204],decode:async()=>({kind:`deleted`})}),D=e=>{x(void 0),_(e),r.begin(e===`create`?T():E()),y(!0)},O=()=>vs(e),k=async()=>{y(!1);let e=await r.submit();if(e.kind!==`acknowledged`)return;if(await O(),r.abandon(),!o){window.location.hash=`#/mcp/grants`;return}if(f===`configure`){e.value.kind===`created`?(h(e.value.grant.id),p(`delete_second`),x(`Replacement grant created; original grant not yet deleted.`)):(p(`create_second`),x(`Original grant deleted; replacement not yet created.`));return}let t=e.value.kind===`created`?e.value.grant.id:m;window.location.hash=t===void 0?`#/mcp/grants`:`#/mcp/grants/${t}`},A=()=>{y(!1),r.abandon()},j=()=>{s(!1),p(`configure`),h(void 0),x(void 0)},M=i.state===`submitting`||i.availability===`storage_latched`;return U(`section`,{class:`panel domain-panel`,"aria-labelledby":`grant-actions-title`,"data-testid":`grant-actions`,children:[U(`div`,{class:`panel-heading`,children:U(`div`,{children:U(`h2`,{id:`grant-actions-title`,children:`Delete or replace this grant`})})}),w&&U(K,{state:`neutral`,title:`Replacement shortcut unavailable`,children:U(`p`,{children:`This shortcut does not replace default-shaped grants.`})}),n.state===`expired`&&U(K,{state:`warning`,title:`Expired grant still consumes capacity`,children:U(`p`,{children:`Deletion releases its retained grant slot; expiry does not delete evidence.`})}),i.problem!==void 0&&U(K,{state:`error`,title:_n(i.problem),children:U(`p`,{children:`No later replacement step was submitted.`})}),i.state===`uncertain`&&U(K,{state:`warning`,title:`Grant mutation outcome is unknown`,children:U(`p`,{children:`Do not replay and do not submit the later replacement step. Refresh policy to investigate.`})}),b!==void 0&&U(K,{state:`warning`,title:b}),o?U(`div`,{"data-testid":`grant-correction`,children:[n.readOnly&&U(`p`,{children:`Replacement ALLOW retains read-only server access. Replacement DENY applies to all tools on this server.`}),f===`configure`&&U(S,{children:[U(J,{id:`correction-order`,label:`Replacement order`,children:e=>U(`select`,{...e,"data-testid":`correction-order`,value:c,onChange:e=>l(e.currentTarget.value),children:[U(`option`,{value:`create_first`,children:`Create first`}),U(`option`,{value:`delete_first`,children:`Delete first`})]})}),U(J,{id:`correction-effect`,label:`Replacement effect`,children:e=>U(`select`,{...e,"data-testid":`correction-effect`,value:u,onChange:e=>d(e.currentTarget.value),children:[U(`option`,{value:`allow`,children:`Allow`}),U(`option`,{value:`deny`,children:`Deny`})]})}),U(`p`,{children:`The replacement keeps the same agent and scope, is unconstrained, and is permanent. Use Create grant for any other policy shape.`})]}),U(`div`,{class:`inline-actions`,children:[U(`button`,{ref:C,"data-testid":`grant-correction-step`,type:`button`,disabled:M,onClick:()=>D(f===`create_second`||f===`configure`&&c===`create_first`?`create`:`delete`),children:f===`configure`?`Confirm step one`:`Confirm step two`}),f===`configure`&&U(`button`,{type:`button`,onClick:j,children:`Cancel replacement`})]})]}):U(`div`,{class:`inline-actions`,children:[U(`button`,{ref:C,"data-testid":`grant-delete`,class:`danger-action`,type:`button`,disabled:M,onClick:()=>D(`delete`),children:`Delete grant`}),U(`button`,{class:`danger-action`,"data-testid":`grant-correct`,type:`button`,disabled:M||n.constraint!==null||n.expiresAt!==null||w,onClick:()=>s(!0),children:`Replace grant`})]}),U(jn,{id:`grant-action-confirm`,open:v,title:g===`create`?`Create replacement grant?`:`Delete grant?`,consequence:U(`p`,{children:g===`create`?`This creates one independent immutable policy record. It does not delete or modify the current grant.${n.readOnly?u===`allow`?` The replacement ALLOW retains read-only server access.`:` The replacement DENY applies to all tools on this server.`:``}`:`This permanently removes this policy record. Remaining grants still apply, with matching Deny taking precedence. No replacement or later step is automatic.`}),confirmLabel:g===`create`?`Create replacement`:`Delete grant`,destructive:g===`delete`,returnFocus:C,onCancel:A,onConfirm:()=>void k()})]})}function ws({session:e,mutations:t,resolved:n,view:r}){let i=n.location.segments,a=i[1]===`new`,o=i.length===2&&!a?i[1]:void 0,[s,c]=z(),[l,u]=z(),[d,f]=z(),[p,m]=z();if(B(()=>{if(!a&&o===void 0)return;let t=!0;return Promise.all([Qo(e),_s(e)]).then(([e,n])=>{t&&(u(e),f(n))}).catch(e=>{t&&m(e instanceof Error?e.message:`Grant references are unavailable.`)}),()=>{t=!1}},[r.generation]),B(()=>{let t=!0;return m(void 0),a||o===void 0||o!==void 0&&(c(e=>e?.id===o?e:void 0),ys(e,o).then(e=>{t&&e!==void 0&&c(e)}).catch(e=>{t&&m(e instanceof Error?e.message:`Grant data is unavailable.`)})),()=>{t=!1}},[n.canonicalFragment,r.generation]),a)return p!==void 0&&(l===void 0||d===void 0)?U(K,{state:`error`,title:`Grant options unavailable`,children:U(`p`,{children:p})}):l===void 0||d===void 0?U(K,{state:`loading`,title:`Loading grant options`}):U(xs,{session:e,mutations:t,query:n.location.query,principals:l,servers:d});if(o!==void 0&&p!==void 0)return U(K,{state:`error`,title:`Grant data unavailable`,children:U(`p`,{children:p})});if(o!==void 0){if(s?.id!==o||l===void 0||d===void 0)return U(K,{state:`loading`,title:`Loading grant`});let n=l.find(e=>e.id===s.principalID),r=d.find(e=>e.id===s.serverID);return U(`div`,{class:`domain-view`,"data-testid":`grant-detail`,children:[U(`nav`,{class:`detail-navigation`,"aria-label":`Grant navigation`,children:U(`a`,{href:`#/mcp/grants`,children:`Back to MCP Grants`})}),U(`header`,{class:`detail-context`,"data-testid":`detail-context`,children:[U(`div`,{class:`detail-context-heading`,children:[U(`h1`,{id:`grant-page-title`,tabindex:-1,children:s.description||`Unnamed MCP grant`}),U(G,{state:s.state===`active`?`current`:`neutral`,children:s.state===`active`?`Active`:`Expired`})]}),U(`p`,{class:`technical-value`,children:s.id})]}),U(`section`,{class:`detail-section`,"aria-labelledby":`grant-title`,children:[U(`div`,{class:`panel-heading`,children:U(`h2`,{id:`grant-title`,children:`Grant details`})}),U(`h3`,{children:`Policy and relationships`}),U(`dl`,{class:`detail-facts`,children:[U(`div`,{children:[U(`dt`,{children:`Effect`}),U(`dd`,{children:s.effect===`allow`?`Allow`:`Deny`})]}),U(`div`,{children:[U(`dt`,{children:`Description`}),U(`dd`,{children:s.description??`—`})]}),U(`div`,{children:[U(`dt`,{children:`Agent`}),U(`dd`,{children:U(`a`,{href:`#/agents/${s.principalID}`,children:n?.displayName??`Agent ${s.principalID}`})})]}),U(`div`,{children:[U(`dt`,{children:`Server`}),U(`dd`,{children:s.serverID===`00000000000000000000000000`?`Gateway self-service tools`:U(`a`,{href:`#/mcp/servers/${s.serverID}?tab=tools`,children:r?.displayName??`Server ${s.serverID}`})})]}),U(`div`,{children:[U(`dt`,{children:`Scope`}),U(`dd`,{children:[s.upstreamName===null?s.readOnly?`Entire server — read-only tools`:`Entire server — all tools`:`Exact tool ${s.upstreamName}`,s.readOnly&&U(`p`,{children:`Includes current and future tools marked readOnlyHint=true. The Gateway does not verify that these tools are read-only; they may still change data.`})]})]})]}),U(`h3`,{children:`Timing`}),U(`dl`,{class:`detail-facts`,children:[U(`div`,{children:[U(`dt`,{children:`Expires`}),U(`dd`,{children:U(Y,{value:s.expiresAt,fallback:`No expiry`})})]}),U(`div`,{children:[U(`dt`,{children:`Created`}),U(`dd`,{children:U(Y,{value:s.createdAt})})]})]}),s.constraint!==null&&U(`section`,{class:`detail-group`,"aria-label":`Constraint evidence`,children:[U(`h3`,{children:`Constraint evidence`}),U(yn,{value:s.constraint,label:`Grant constraint`})]})]}),U(Ss,{mutations:t,grant:s,onAcknowledged:c},`${s.id}-${s.revision}`),U(Cs,{session:e,mutations:t,grant:s},s.id)]})}return U(Es,{session:e,resolved:n,view:r})}function Ts(e){return e.upstreamName??(e.readOnly?`Read-only tools`:`All tools`)}function Es({session:e,resolved:t,view:n}){let{items:r,controls:i}=Nr(e,t,n,(t,n,r)=>{let i=new URLSearchParams({limit:`50`,sort:t.sort??`description`,direction:t.direction??`ascending`});for(let e of[`identity`,`principal`,`target`,`server`,`scope`,`effect`,`state`]){let n=t[`filter_${e}`];n!==void 0&&i.set(e,n)}return n!==null&&i.set(`cursor`,n),Mr(e,`/api/v2/mcp/grants?${i}`,e=>{let t=typeof e==`object`&&!!e&&Object.hasOwn(e,`tool_id`),n=ds(e,[`grant`,`principal_display_name`,`server_display_name`,...t?[`tool_id`]:[]]);return{...ms(n.grant),principalDisplayName:fs(n.principal_display_name),serverDisplayName:fs(n.server_display_name),toolID:t?ps(n.tool_id):void 0}},r)},Cr(!1),{key:`description`,direction:`ascending`}),a=new Map(r.map(e=>[e.principalID,e.principalDisplayName]));return U(`div`,{class:`domain-view`,"data-testid":`grants-view`,children:[U(`div`,{class:`collection-toolbar`,children:U(`a`,{class:`button-link create-action`,href:`#/mcp/grants/new`,"data-testid":`grant-create-link`,children:`Create grant`})}),U(`section`,{class:`panel domain-panel`,"aria-labelledby":`page-title`,children:U(Dn,{caption:`Grant policy records`,rowHeaderKey:`description`,initialSort:{key:`description`,direction:`ascending`},additionalSorts:[{key:`id`,label:`Grant ID`,sortValue:e=>e.id},{key:`target`,label:`Server`,sortValue:e=>e.serverDisplayName}],remote:i,itemNames:{singular:`grant`,plural:`grants`},emptyTitle:`No grants`,items:r,rowKey:e=>e.id,rowTestID:`grant-row`,filters:[{key:`identity`,label:`Description or ID`,type:`text`,value:e=>e.description??``,literalValues:e=>[e.id]},{key:`principal`,label:`Agent`,type:`text`,value:e=>a.get(e.principalID)??``,literalValues:e=>[e.principalID]},...t.location.query.filter_target===void 0?[]:[{key:`target`,label:`Server or tool (legacy)`,type:`text`,value:e=>`${e.serverDisplayName} ${e.upstreamName??`Entire server`}`,literalValues:e=>[e.serverID]}],{key:`server`,label:`Server`,type:`text`,value:e=>e.serverDisplayName,literalValues:e=>[e.serverID]},{key:`scope`,label:`Scope`,type:`text`,value:Ts,literalValues:e=>e.toolID?[e.toolID]:[]},{key:`effect`,label:`Effect`,type:`select`,value:e=>e.effect,options:[{value:`allow`,label:`Allow`},{value:`deny`,label:`Deny`}]},{key:`state`,label:`Status`,type:`select`,value:e=>e.state,options:[{value:`active`,label:`Active`},{value:`expired`,label:`Expired`}]}],columns:[{key:`description`,label:`Grant`,role:`identity`,sortValue:e=>e.description??``,render:e=>U(q,{primary:U(`a`,{href:`#/mcp/grants/${e.id}`,children:e.description??`Unnamed grant`}),secondary:e.id})},{key:`principal`,label:`Agent`,role:`relation`,sortValue:e=>a.get(e.principalID)??e.principalID,render:e=>U(q,{primary:U(`a`,{href:`#/agents/${e.principalID}`,children:e.principalDisplayName||e.principalID}),secondary:e.principalID})},{key:`server`,label:`Server`,role:`relation`,sortValue:e=>e.serverDisplayName,render:e=>e.serverID===`00000000000000000000000000`?U(q,{primary:`Gateway self-service tools`,secondary:e.serverID}):U(q,{primary:U(`a`,{href:`#/mcp/servers/${e.serverID}?tab=tools`,children:e.serverDisplayName||e.serverID}),secondary:e.serverID})},{key:`scope`,label:`Scope`,role:`relation`,sortValue:Ts,render:e=>e.toolID&&e.upstreamName!==null&&e.serverID!==`00000000000000000000000000`?U(`a`,{href:`#/mcp/servers/${e.serverID}/descriptors/${e.toolID}`,children:Ts(e)}):Ts(e)},{key:`effect`,label:`Effect`,role:`status`,sortValue:e=>e.effect,render:e=>U(`strong`,{children:e.effect===`allow`?`Allow`:`Deny`})},{key:`state`,label:`Status`,role:`status`,sortValue:e=>e.state,render:e=>U(G,{state:e.state===`active`?`current`:`neutral`,children:e.state===`active`?`Active`:`Expired`})},{key:`constraints`,label:`Conditions`,role:`count`,render:e=>Po(e.constraint)},{key:`expiry`,label:`Expires`,role:`time`,render:e=>U(Y,{value:e.expiresAt,fallback:`No expiry`})}]})})]})}function Ds(e,t){if(typeof e!=`object`||!e||Array.isArray(e)||Object.keys(e).sort().join(`,`)!==t.sort().join(`,`))throw Error(`invalid invocation recognition`);return e}function Os(e,t){if(typeof e!=`string`||!t&&e.length===0||new TextEncoder().encode(e).byteLength>256)throw Error(`invalid invocation recognition`);return e}function ks(e,t){if(typeof e!=`string`||!/^[0-7][0-9A-HJKMNP-TV-Z]{25}$/.test(e)||e!==t)throw Error(`invalid invocation recognition identity`);return e}function As(e,t,n){if(e===void 0)return;let r=Ds(e,[`server`,`grant`]),i=r.server===null?null:Ds(r.server,[`server_id`,`display_name`]),a=r.grant===null?null:Ds(r.grant,[`grant_id`,`description`]);return{server:i===null?null:{serverID:ks(i.server_id,t),displayName:Os(i.display_name,!1)},grant:a===null?null:{grantID:ks(a.grant_id,n),description:Os(a.description,!0)}}}function js(e){return e===`succeeded`?`current`:e===`outcome_unknown`?`warning`:e===`deny`||e===`block`?`neutral`:`error`}function Ms({decision:e}){return U(G,{state:e===`allow`?`current`:`neutral`,children:e===void 0?`Not evaluated`:W(e)})}var Ns=/^[0-7][0-9A-HJKMNP-TV-Z]{25}$/;function Ps(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`invalid response`);let n=e;if(Object.keys(n).sort().join(`,`)!==[...t].sort().join(`,`))throw Error(`invalid response`);return n}function Fs(e){if(typeof e!=`string`)throw Error(`invalid response`);return e}function Is(e){if(e!==null&&typeof e!=`string`)throw Error(`invalid response`);return e}function Ls(e){let t=Fs(e);if(!Ns.test(t))throw Error(`invalid response`);return t}function Rs(e,t){let n=Fs(e);if(!t.includes(n))throw Error(`invalid response`);return n}function zs(e){if(!Array.isArray(e))throw Error(`invalid response`);return e}function Bs(e){let t=Is(e);if(t!==null&&(t.length===0||t.length>512))throw Error(`invalid response`);return t}var Vs={models_result:[`$`,`$.models`,`$.models.[]`,`$.models.[].name`,`$.models.[].description`,`$.models.[].release_date`],evaluate_result:[`$`,`$.model`,`$.answers`,`$.answers.*`,`$.answers.*.type`,`$.answers.*.choice`,`$.answers.*.confidence`,`$.answers.*.probabilities`,`$.answers.*.probabilities.*`,`$.answers.*.score`,`$.answers.*.legend`,`$.answers.*.legend.*`,`$.answers.*.noul`,`$.usage`,`$.usage.input_tokens`,`$.usage.output_tokens`]};function Hs(e){let t=Ps(e,[`schema`,`version`,`violations`,`truncated`]),n=Rs(t.schema,[`models_result`,`evaluate_result`]);if(t.version!==1||typeof t.truncated!=`boolean`||!Array.isArray(t.violations)||t.violations.length<1||t.violations.length>3)throw Error(`invalid response`);let r=t.violations.map(e=>{let t=typeof e==`object`&&!!e&&`code`in e&&e.code===`type`,r=Ps(e,[`code`,`path`,`rule`,...t?[`expected`,`observed`]:[]]),i=Rs(r.code,[`missing`,`type`,`invalid_date`,`correspondence`,`constraint`]),a=Rs(r.path,Vs[n]),o={code:i,path:a,rule:Rs(r.rule,{missing:[`required`],type:[`type`],invalid_date:[`date`],correspondence:[`correspondence`],constraint:[`schema`,`oneOf`,`additionalProperties`,`minLength`,`minItems`,`maxItems`,`minProperties`,`minimum`,`maximum`,`const`,`pattern`]}[i])};if(i===`invalid_date`&&a!==`$.models.[].release_date`||i===`correspondence`&&a!==`$.answers`)throw Error(`invalid response`);if(t){let e=[`null`,`boolean`,`object`,`array`,`number`,`string`,`integer`];o.expected=Rs(r.expected,[...e,`null|string|array|object`]),o.observed=Rs(r.observed,e)}return o}),i=r.map(e=>JSON.stringify(e));if(i.some((e,t)=>t>0&&e<=i[t-1]))throw Error(`invalid response`);return{schema:n,version:1,violations:r,truncated:t.truncated}}function Us(e){switch(e){case`missing`:return`Required field is missing`;case`type`:return`Wrong value type`;case`invalid_date`:return`Invalid release date; expected YYYY-MM-DD or RFC 3339 timestamp`;case`correspondence`:return`Answers do not correspond to the submitted questions`;default:return`Response does not satisfy the schema rule`}}function Ws(e){let t=(e,t,n)=>{let r=[...t];if(typeof e==`object`&&e)for(let t of n)t in e&&r.push(t);return Ps(e,r)},n=t(e,[`gateway_observed`],[`server_reported`]),r=Ps(n.gateway_observed,[`source`,`reason`]),i={gateway_observed:{source:Rs(r.source,[`transport`,`protocol`,`tool`,`result_validation`]),reason:Rs(r.reason,[`prestart`,`handoff_uncertain`,`invalid_response`,`rpc_error`,`reported_error`,`result_shape`])}};if(`server_reported`in n){let e=t(n.server_reported,[`version`,`category`,`phase`],[`http_status`,`retry_after_seconds`,`validation`]);if(e.version!==1&&e.version!==2)throw Error(`invalid response`);i.server_reported={version:e.version,category:Rs(e.category,[`authentication`,`rate_limit`,`timeout`,`canceled`,`transport`,`json_decode`,`response_contract`,`response_limit`,`validation`,`capacity`,`overload`,`redirect_rejected`,`upstream`]),phase:Rs(e.phase,[`admission`,`exchange`,`response_status`,`response_decode`,`response_validation`])};for(let t of[`http_status`,`retry_after_seconds`]){if(!(t in e))continue;let n=e[t],r=t===`http_status`?100:0,a=t===`http_status`?599:86400;if(typeof n!=`number`||!Number.isInteger(n)||na)throw Error(`invalid response`);i.server_reported[t]=n}if(e.version===2){if(e.category!==`response_contract`||e.phase!==`response_validation`||`http_status`in e||`retry_after_seconds`in e||(i.server_reported.validation=Hs(e.validation),JSON.stringify(i.server_reported).length>400))throw Error(`invalid response`)}else if(`validation`in e)throw Error(`invalid response`)}return i}function Gs(e){if(e===null)return null;let t=Ps(e,[`kind`,`server_id`,`tool_id`,`upstream_name`,`descriptor_revision`,`descriptor_fingerprint`]);return{kind:Rs(t.kind,[`downstream`,`gateway`]),serverID:Ls(t.server_id),toolID:Ls(t.tool_id),upstreamName:Fs(t.upstream_name),descriptorRevision:Fs(t.descriptor_revision),descriptorFingerprint:Fs(t.descriptor_fingerprint)}}function Ks(e){if(e===null)return null;let t=Ps(e,[`decision`,`revision`,`evaluated_at`,`grant_id`]),n=Is(t.grant_id);return n!==null&&Ls(n),{decision:Rs(t.decision,[`allow`,`deny`,`block`]),revision:Fs(t.revision),evaluatedAt:Fs(t.evaluated_at),grantID:n}}function qs(e,t=!1){let n=[`id`,`principal_id`,`credential_id`,`credential_fingerprint`,`credential_revision`,`admitted_at`,`admission_class`,`requested_name`,`target`,`authorization`,`outcome`];t&&(n.push(`redacted_arguments`),typeof e==`object`&&e&&`recognition`in e&&n.push(`recognition`),typeof e==`object`&&e&&`diagnostics`in e&&n.push(`diagnostics`));let r=Ps(e,n),i=Ps(r.outcome,[`class`,`basis`,`completed_at`]),a={id:Ls(r.id),principalID:Ls(r.principal_id),credentialID:Ls(r.credential_id),credentialFingerprint:Fs(r.credential_fingerprint),credentialRevision:Fs(r.credential_revision),admittedAt:Fs(r.admitted_at),admissionClass:Rs(r.admission_class,[`invalid_params`,`unknown_tool`,`invalid_arguments`,`authorization_unavailable`,`evaluated`]),requestedName:Is(r.requested_name),target:Gs(r.target),authorization:Ks(r.authorization),outcome:Rs(i.class,[`invalid_params`,`unknown_tool`,`invalid_arguments`,`authorization_unavailable`,`deny`,`block`,`prestart_failure`,`succeeded`,`downstream_failure`,`outcome_unknown`]),basis:Rs(i.basis,[`admission`,`policy`,`terminal`,`missing_terminal`]),completedAt:Is(i.completed_at)};if(t){a.redactedArguments=r.redacted_arguments;let e=As(r.recognition,a.target?.kind===`downstream`?a.target.serverID:void 0,a.authorization?.grantID??void 0);e!==void 0&&(a.recognition=e),`diagnostics`in r&&(a.diagnostics=Ws(r.diagnostics))}return a}function Js(e){let t=Ps(e,[`items`,`next_cursor`]),n=zs(t.items).map(e=>qs(e));if(n.length>50||new Set(n.map(e=>e.id)).size!==n.length||n.length===0&&t.next_cursor!==null)throw Error(`Invalid invocation page`);return{items:n,nextCursor:Bs(t.next_cursor)}}function Ys(e){let t=qs(e,!0);if(!(`redactedArguments`in t))throw Error(`invalid response`);return t}async function Xs(e,t){let n=await fetch(t,{method:`GET`,headers:{"X-CSRF-Token":e.csrfToken},credentials:`same-origin`,redirect:`error`,signal:e.signal});if(await e.sessionLost(n))throw Error(`session lost`);return n}async function Zs(e){if(e.status!==200||e.headers.get(`Content-Type`)!==`application/json`)throw Error(`read failed`);let t=await e.text();if(new TextEncoder().encode(t).byteLength>4194304)throw Error(`response too large`);return JSON.parse(t)}async function Qs(e,t){if(e.status!==t||e.headers.get(`Content-Type`)!==`application/problem+json`)return;let n=await e.text();if(!(new TextEncoder().encode(n).byteLength>65536))try{let e=Ps(JSON.parse(n),[`status`,`code`,`title`]);return e.status!==t||Fs(e.title).length===0?void 0:Fs(e.code)}catch{return}}function $s(e,t){let n=new URLSearchParams({limit:`50`});for(let[t,r]of Object.entries(e))n.set(t.slice(7),r);return(e.filter_tool||e.filter_principal)&&n.set(`search_locale`,Intl.DateTimeFormat().resolvedOptions().locale),t!==null&&n.set(`cursor`,t),`/api/v2/mcp/invocations?${n.toString()}`}var ec=class{views;listeners=new Set;value={viewKey:``,live:!0,paused:!1,successful:!1,refreshError:!1,olderError:!1,notice:void 0,updatesAvailable:!1,items:[],nextCursor:null,item:void 0,missing:!1,loadingOlder:!1};continuation=null;continuationPending=!1;serial=0;continuationSerial=0;constructor(e,t){this.views=t,t.registerPanel({id:`invocations`,matches:e=>H(e)?.destination===`invocations`,invalidations:[`invocations`,`authorization`,`servers`],shouldRefresh:e=>![`invalidation`,`reconnect`,`poll`].includes(e)||H(this.views.snapshot().viewKey)?.segments.length===2||this.value.live&&!this.value.paused,onInvalidation:()=>H(this.views.snapshot().viewKey)?.segments.length===2||this.value.live&&!this.value.paused?!0:(this.value.updatesAvailable||(this.value={...this.value,updatesAvailable:!0},this.emit()),!1),read:e=>this.read(e),publish:e=>this.publish(e)}),e.registerProtectedState(()=>{this.continuation=null,this.continuationPending=!1,this.serial+=1,this.continuationSerial+=1,this.value={viewKey:``,live:!0,paused:!1,successful:!1,refreshError:!1,olderError:!1,notice:void 0,updatesAvailable:!1,items:[],nextCursor:null,item:void 0,missing:!1,loadingOlder:!1},this.emit()})}snapshot(){return this.value}subscribe(e){return this.listeners.add(e),e(this.value),()=>this.listeners.delete(e)}setLive(e){this.views.cancelPanelRead(`invocations`),this.serial+=1,this.continuation=null,this.value={...this.value,live:e,loadingOlder:!1},this.emit(),(!this.value.successful||e&&!this.value.paused)&&(this.continuation=null,this.views.refreshPanel(`invocations`))}resume(){this.serial+=1,this.value={...this.value,paused:!1},this.emit(),this.refresh()}refresh(){this.continuation=null,this.views.refreshPanel(`invocations`)}async loadOlder(){if(this.continuationPending||this.value.items.length>=500||this.value.refreshError||this.value.nextCursor===null||this.views.snapshot().viewKey!==this.value.viewKey||this.views.snapshot().panels.invocations?.refreshing===!0)return;this.serial+=1;let e=++this.continuationSerial;this.continuationPending=!0,this.continuation=this.value.nextCursor,this.value={...this.value,paused:!0,loadingOlder:!0,olderError:!1},this.emit();try{await this.views.refreshPanel(`invocations`)}finally{e===this.continuationSerial&&(this.continuationPending=!1,this.value={...this.value,loadingOlder:!1},this.emit())}}async read(e){let t=H(e.viewKey);if(t?.destination!==`invocations`)throw Error(`Invalid invocation location`);e.viewKey!==this.value.viewKey&&(this.serial+=1,this.continuationSerial+=1,this.continuationPending=!1,this.continuation=null,this.value={viewKey:e.viewKey,live:this.value.live,paused:this.value.paused,successful:!1,refreshError:!1,olderError:!1,notice:this.value.paused&&t.segments.length===1?`Showing the latest entries. Older results could not be continued.`:void 0,updatesAvailable:!1,items:[],nextCursor:null,item:void 0,missing:!1,loadingOlder:!1},this.emit());let n=t.segments[1];if(n!==void 0){let t=await Xs(e,`/api/v2/mcp/invocations/${n}`);return await Qs(t,404)===`not_found`?{kind:`missing`,viewKey:e.viewKey}:{kind:`item`,viewKey:e.viewKey,item:Ys(await Zs(t))}}let r=e.reason===`panel`?this.continuation:null;this.continuation=null;let i=this.serial,a=[`invalidation`,`reconnect`,`poll`].includes(e.reason??`navigation`),o=r!==null;try{let n=await Xs(e,$s(t.query,r));if(o&&await Qs(n,409)===`stale_cursor`){if(e.signal.aborted)throw Error(`Superseded`);o=!1,this.value={...this.value,items:[],nextCursor:null,successful:!1,notice:`Showing the latest entries. Older results could not be continued.`},this.emit(),n=await Xs(e,$s(t.query,null))}let s=Js(await Zs(n));if(o&&(this.value.items.length+s.items.length>500||s.items.some(e=>this.value.items.some(t=>t.id===e.id))))throw Error(`Invalid continuation`);return{kind:`list`,viewKey:e.viewKey,page:s,append:o,automatic:a,serial:i}}catch(t){if(e.signal.aborted)throw t;return{kind:`failure`,viewKey:e.viewKey,append:o,automatic:a,serial:i}}}publish(e){if(!((e.kind===`list`||e.kind===`failure`)&&e.automatic&&(e.serial!==this.serial||!this.value.live||this.value.paused))){if(e.kind===`failure`){this.value={...this.value,loadingOlder:!1,olderError:e.append,refreshError:!e.append},this.emit();return}this.value=e.kind===`missing`?{...this.value,viewKey:e.viewKey,item:void 0,missing:!0}:e.kind===`item`?{...this.value,viewKey:e.viewKey,item:e.item,missing:!1}:{...this.value,viewKey:e.viewKey,items:e.append?[...this.value.items,...e.page.items]:e.page.items,nextCursor:e.page.nextCursor,successful:!0,refreshError:!1,olderError:!1,item:void 0,missing:!1,updatesAvailable:!1},this.emit()}}emit(){for(let e of this.listeners)e(this.value)}};function tc(e,t){return t??(e===null?`Not resolved`:e.kind===`gateway`?`mcp_gateway.${e.upstreamName}`:e.upstreamName)}function nc({item:e,principalNames:t}){return U(S,{children:[U(`h3`,{children:`Authorization and relationships`}),U(`dl`,{class:`detail-facts`,children:[U(`div`,{children:[U(`dt`,{children:`Agent`}),U(`dd`,{children:U(q,{primary:U(`a`,{href:`#/agents/${e.principalID}`,children:t.get(e.principalID)??e.principalID}),secondary:e.principalID})})]}),U(`div`,{children:[U(`dt`,{children:`Tool`}),U(`dd`,{children:U(q,{primary:e.target?.kind===`downstream`?U(`a`,{href:`#/mcp/servers/${e.target.serverID}/descriptors/${e.target.toolID}`,children:tc(e.target,e.requestedName)}):tc(e.target,e.requestedName),secondary:e.target?.kind===`downstream`?e.target.toolID:void 0})})]}),U(`div`,{children:[U(`dt`,{children:`Authorization decision`}),U(`dd`,{children:U(Ms,{decision:e.authorization?.decision})})]}),e.authorization?.grantID!==null&&e.authorization?.grantID!==void 0&&U(`div`,{children:[U(`dt`,{children:`Grant`}),U(`dd`,{children:U(q,{primary:U(`a`,{href:`#/mcp/grants/${e.authorization.grantID}`,children:e.recognition?.grant?e.recognition.grant.description||`Unnamed grant`:e.authorization.grantID}),secondary:e.authorization.grantID})})]}),e.target?.kind===`downstream`&&U(`div`,{children:[U(`dt`,{children:`Server`}),U(`dd`,{children:U(q,{primary:U(`a`,{href:`#/mcp/servers/${e.target.serverID}`,children:e.recognition?.server?.displayName??e.target.serverID}),secondary:e.target.serverID})})]})]}),U(`h3`,{children:`Timing`}),U(`dl`,{class:`detail-facts`,children:[U(`div`,{children:[U(`dt`,{children:`Admitted`}),U(`dd`,{children:U(Y,{value:e.admittedAt})})]}),U(`div`,{children:[U(`dt`,{children:`Completed`}),U(`dd`,{children:U(Y,{value:e.completedAt,fallback:`No terminal timestamp retained`})})]}),U(`div`,{children:[U(`dt`,{children:`Outcome basis`}),U(`dd`,{children:W(e.basis)})]})]}),U(`h3`,{children:`Admission-time credential`}),U(`dl`,{class:`detail-facts`,children:[U(`div`,{children:[U(`dt`,{children:`Credential ID`}),U(`dd`,{class:`technical-value`,children:e.credentialID})]}),U(`div`,{children:[U(`dt`,{children:`Credential revision`}),U(`dd`,{children:e.credentialRevision})]}),U(`div`,{children:[U(`dt`,{children:`Fingerprint`}),U(`dd`,{class:`technical-value`,children:e.credentialFingerprint})]})]})]})}function rc({controller:e,principals:t,view:n,navigate:r}){let[i,a]=z(e.snapshot()),[o,s]=z(t.snapshot());B(()=>e.subscribe(a),[e]),B(()=>t.subscribe(s),[t]);let c=n.panels.invocations,l=H(n.viewKey),u=l?.segments.length===2,d=l?.query??{},f=ln({destination:`invocations`,segments:[`invocations`],query:d}),p=i.viewKey===n.viewKey?i:{...i,items:[],item:void 0,successful:!1,missing:!1,refreshError:!1,olderError:!1,notice:void 0,nextCursor:null};return u?U(S,{children:[U(`nav`,{class:`detail-navigation`,"aria-label":`Invocation navigation`,children:U(`a`,{href:f,children:`Back to MCP Invocations`})}),U(lc,{snapshot:p,panel:c,principalNames:o})]}):U(`div`,{class:`invocations-view`,"data-testid":`invocations-view`,children:U(ic,{snapshot:p,panel:c,query:d,navigate:r,resume:()=>e.resume(),refresh:()=>e.refresh(),setLive:t=>e.setLive(t),loadOlder:()=>void e.loadOlder(),principalNames:o})})}function ic({snapshot:e,panel:t,setLive:n,loadOlder:r,principalNames:i,query:a,navigate:o,resume:s,refresh:c}){return U(`section`,{class:`panel domain-panel`,"aria-label":`Invocations`,children:[U(`div`,{class:`collection-toolbar live-collection-toolbar`,children:[U(`label`,{for:`invocation-live-mode`,children:`Live mode`}),U(On,{attributes:{id:`invocation-live-mode`},checked:e.live,showState:!1,onChange:n}),e.updatesAvailable&&U(G,{state:`warning`,children:`Updates available`})]}),U(oc,{query:a,navigate:o}),e.paused&&U(`div`,{class:`inline-actions`,children:[e.live&&U(G,{state:`warning`,children:`Live paused while viewing older results`}),U(`button`,{type:`button`,onClick:s,children:e.live?`Resume live`:`Return to newest`})]}),e.notice&&U(K,{state:`warning`,title:e.notice}),e.refreshError&&U(K,{state:`error`,title:e.successful?`Refresh failed; shown results are stale`:`Invocation list unavailable`,children:U(`button`,{type:`button`,onClick:c,children:`Retry refresh`})}),!e.successful&&!e.refreshError?U(K,{state:`loading`,title:`Loading invocations`}):e.items.length===0?e.successful&&!e.refreshError&&U(K,{state:`empty`,title:Object.keys(a).length?`No matching invocations`:`No retained invocations`}):U(Dn,{caption:`Invocation history`,layout:`activity`,rowHeaderKey:`tool`,items:e.items,rowKey:e=>e.id,rowTestID:`invocation-row`,columns:[{key:`admitted`,label:`Admitted`,role:`time`,render:e=>U(Y,{value:e.admittedAt})},{key:`tool`,label:`Invocation`,role:`identity`,render:e=>U(q,{primary:U(`a`,{href:ln({destination:`invocations`,segments:[`invocations`,e.id],query:a}),children:tc(e.target,e.requestedName)}),secondary:e.id})},{key:`principal`,label:`Agent`,role:`relation`,render:e=>U(q,{primary:U(`a`,{href:`#/agents/${e.principalID}`,children:i.get(e.principalID)??e.principalID}),secondary:e.principalID})},{key:`decision`,label:`Authorization`,role:`status`,render:e=>U(Ms,{decision:e.authorization?.decision})},{key:`outcome`,label:`Outcome`,role:`status`,render:e=>U(G,{state:js(e.outcome),children:e.outcome===`invalid_params`?`Invalid parameters`:W(e.outcome)})}]}),U(`div`,{class:`history-continuation`,children:[e.successful&&!e.refreshError&&!e.olderError&&U(`span`,{children:e.nextCursor===null?`No older invocations`:e.items.length>=500?`Load limit reached. Narrow the filters or return to newest.`:``}),e.successful&&U(hn,{count:e.items.length,singular:`invocation`,plural:`invocations`,matching:Object.keys(a).length>0,stale:e.refreshError}),e.nextCursor!==null&&e.items.length<500&&!e.refreshError&&U(`div`,{class:`inline-actions`,children:[U(`button`,{type:`button`,onClick:r,disabled:e.loadingOlder||t?.refreshing===!0,children:`Load older invocations`}),e.olderError&&U(`span`,{role:`alert`,children:`Older results unavailable. Loaded rows were retained; use Load older invocations to retry.`})]})]})]})}function ac({name:e,value:t,change:n,reportDraft:r}){let[i,a]=z(t);return xe(()=>a(t),[t]),mn(i,e=>{e!==t&&n(e)}),U(`input`,{type:`search`,"aria-label":e,placeholder:e,value:i,onInput:e=>{a(e.currentTarget.value),r(e.currentTarget.value)}})}function oc({query:e,navigate:t}){let[n,r]=z(),[i,a]=z(0),[o,s]=z({});xe(()=>{s(t=>({...t,tool:e.filter_tool??``}))},[e.filter_tool]),xe(()=>{s(t=>({...t,principal:e.filter_principal??``}))},[e.filter_principal]);let c=e=>{let n=ln({destination:`invocations`,segments:[`invocations`],query:e});if(!H(n)){r(`Filters must fit 256 UTF-8 bytes each and contain no control characters.`);return}r(void 0),t(n)},l=(t,n)=>{let r={...e};n.trim()===``?delete r[`filter_${t}`]:r[`filter_${t}`]=n,c(r)};return U(S,{children:[U(Wn,{query:e}),U(`div`,{class:`table-filters collection-query-filters`,role:`group`,"aria-label":`Invocation history filters`,children:[[`tool`,`principal`].map(t=>U(ac,{name:t===`principal`?`Agent`:W(t),value:e[`filter_${t}`]??``,change:e=>l(t,e),reportDraft:e=>s(n=>({...n,[t]:e}))},`${t}:${i}`)),[`decision`,`outcome`].map(t=>U(`select`,{"aria-label":t===`decision`?`Authorization`:`Outcome`,value:e[`filter_${t}`]??``,onChange:e=>l(t,e.currentTarget.value),children:[U(`option`,{value:``,children:[t===`decision`?`Authorization`:`Outcome`,`: any`]}),dt[t].map(([e,t])=>U(`option`,{value:e,children:t}))]},t)),U(`button`,{type:`button`,disabled:!Object.values(e).some(Boolean)&&!Object.values(o).some(Boolean),onClick:()=>{a(i+1),s({}),c({})},children:`Reset`})]}),n&&U(K,{state:`error`,title:n})]})}function sc({value:e}){let t=typeof e==`object`&&!!e&&!Array.isArray(e)&&Object.keys(e).length===0;return U(`section`,{class:`panel domain-panel argument-capture`,"aria-labelledby":`invocation-argument-capture-title`,"data-testid":`invocation-argument-capture`,children:[U(`div`,{class:`panel-heading`,children:U(`h2`,{id:`invocation-argument-capture-title`,children:[`Captured arguments`,t&&` · Empty`]})}),t?null:e===null?U(`p`,{children:`No argument capture was retained.`}):e===`[TRUNCATED]`?U(`p`,{children:`The redacted capture exceeded 8 KiB; argument content was not retained.`}):U(yn,{value:e,label:`Retained invocation argument capture`})]})}function cc({diagnostics:e}){let t=e.gateway_observed,n=e.server_reported,r=n?.validation;return U(`section`,{class:`panel domain-panel failure-diagnostics`,"aria-labelledby":`failure-diagnostics-title`,"data-testid":`failure-diagnostics`,children:[U(`div`,{class:`panel-heading`,children:[U(`h2`,{id:`failure-diagnostics-title`,children:`Failure diagnostics`}),U(`span`,{class:`diagnostic-source`,children:[`Gateway observed · `,W(t.source),`:`,` `,W(t.reason)]})]}),n&&U(`div`,{class:`diagnostic-report`,"aria-label":`Server reported (unverified)`,children:[U(`div`,{class:`diagnostic-report-heading`,children:[U(`h3`,{children:r?`Response validation failed`:W(n.category)}),U(`span`,{class:`diagnostic-source`,children:`Server reported (unverified)`})]}),r&&U(S,{children:[U(`ul`,{class:`diagnostic-violations`,children:r.violations.map(e=>U(`li`,{children:[U(`strong`,{children:Us(e.code)}),U(`code`,{children:e.path}),e.expected&&U(`span`,{children:[`Expected `,e.expected,`; observed `,e.observed,`.`]})]},`${e.code}:${e.path}:${e.rule}`))}),r.truncated&&U(`p`,{children:`Additional validation violations omitted.`})]}),n.http_status!==void 0&&U(`p`,{children:[`HTTP status: `,n.http_status]}),n.retry_after_seconds!==void 0&&U(`p`,{children:[`Retry guidance: `,n.retry_after_seconds,` seconds`]}),U(`details`,{children:[U(`summary`,{children:`Technical details`}),U(`p`,{children:[W(n.category),` · `,W(n.phase),` `,`· Diagnostic version `,n.version]}),r&&U(S,{children:[U(`p`,{children:[`Schema: `,U(`code`,{children:r.schema}),` v`,r.version]}),U(`ul`,{children:r.violations.map(e=>U(`li`,{children:[U(`code`,{children:e.path}),` · Rule: `,U(`code`,{children:e.rule}),` · Code: `,U(`code`,{children:e.code})]},`${e.code}:${e.path}:${e.rule}`))}),U(`p`,{children:`Array positions and dynamic keys are masked.`})]})]})]}),t.reason!==`prestart`&&U(`p`,{class:`diagnostic-retry`,children:`The tool may have executed. Retrying could duplicate effects.`})]})}function lc({snapshot:e,panel:t,principalNames:n}){if(e.missing)return U(K,{state:`unavailable`,title:`Invocation evidence is no longer retained`,children:U(`p`,{"data-testid":`invocation-missing`,children:`A missing or evicted item does not prove it never existed or never executed. It is not safe-to-retry evidence.`})});if(e.item===void 0)return t?.status===`error`?U(K,{state:`error`,title:`Invocation detail unavailable`}):U(K,{state:`loading`,title:`Loading invocation detail`});let r=e.item;return U(`div`,{class:`domain-view`,"data-testid":`invocation-detail`,children:[U(`header`,{class:`detail-context`,"data-testid":`detail-context`,children:[U(`div`,{class:`detail-context-heading`,children:[U(`h1`,{id:`invocation-page-title`,tabindex:-1,children:tc(r.target,r.requestedName)||`MCP invocation`}),U(G,{state:js(r.outcome),children:r.outcome===`invalid_params`?`Invalid parameters`:W(r.outcome)})]}),U(`p`,{class:`technical-value`,children:r.id})]}),U(`section`,{class:`detail-section`,"aria-labelledby":`invocation-detail-title`,children:[U(`div`,{class:`panel-heading`,children:U(`h2`,{id:`invocation-detail-title`,children:`Invocation details`})}),U(nc,{item:r,principalNames:n}),r.basis===`missing_terminal`&&U(K,{state:`warning`,title:`Audit completion is unknown`,children:[U(`p`,{children:`Missing terminal evidence does not prove nonexecution and is not safe-to-retry evidence. Gateway does not automatically replay invocations; an explicit caller retry can duplicate an effect.`}),r.target?.kind===`gateway`&&U(`p`,{children:`This is a Gateway-owned local target. Missing terminal evidence is not proof of downstream handoff.`})]})]}),r.diagnostics&&U(cc,{diagnostics:r.diagnostics}),U(sc,{value:r.redactedArguments})]})}var uc=`[0-7][0-9A-HJKMNP-TV-Z]{25}`,dc={backup_create:/^\/api\/v2\/backups$/,server_create:/^\/api\/v2\/mcp\/servers$/,operation_start:RegExp(`^/api/v2/mcp/servers/${uc}/operations$`)},fc=[/^PATCH \/api\/v2\/git\/routing-profile$/,RegExp(`^(?:PATCH|DELETE) /api/v2/git/(?:repositories|grants|credentials)/${uc}$`),RegExp(`^POST /api/v2/git/credentials/${uc}/rotate$`),RegExp(`^(?:PATCH|DELETE) /api/v2/http/grants/${uc}$`),RegExp(`^(?:PATCH|DELETE) /api/v2/http/credentials/${uc}$`),RegExp(`^POST /api/v2/http/credentials/${uc}/rotate$`),RegExp(`^PATCH /api/v2/mcp/servers/${uc}$`),RegExp(`^DELETE /api/v2/mcp/servers/${uc}$`),RegExp(`^POST /api/v2/mcp/servers/${uc}/operations$`),RegExp(`^POST /api/v2/mcp/servers/${uc}/credential-replacements$`),RegExp(`^POST /api/v2/mcp/servers/${uc}/oauth-flows$`),RegExp(`^PATCH /api/v2/principals/${uc}$`),RegExp(`^PATCH /api/v2/mcp/grants/${uc}$`),RegExp(`^(?:POST|DELETE) /api/v2/principals/${uc}/credential$`),RegExp(`^POST /api/v2/mcp/grant-requests/${uc}/(?:approve|reject)$`)],pc=/^"[\x21\x23-\x7e]{1,255}"$/,mc=/^\/api\/v2\/[A-Za-z0-9_/-]{1,512}$/,hc=RegExp(`^(?:/api/v2/mcp/servers/${uc}/credential-replacements|/api/v2/(?:http|git)/credentials(?:/${uc}/rotate)?)$`),gc=RegExp(`^/api/v2/mcp/grant-requests/${uc}/approve$`),_c=1048576;function vc(){let e=crypto.getRandomValues(new Uint8Array(16));return`mgw-web-${Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``)}`}function yc(e){try{return JSON.stringify(JSON.parse(e))===e}catch{return!1}}function bc(e){if(e.method!==`POST`||e.body===null||e.route!==`/api/v2/mcp/grants`&&!gc.test(e.route))return!1;try{return JSON.parse(e.body),!0}catch{return!1}}function xc(e){let t=Object.entries(dc).find(([,t])=>t.test(e.route))?.[0],n=fc.some(t=>t.test(`${e.method} ${e.route}`));if(!mc.test(e.route)||e.body!==null&&(new TextEncoder().encode(e.body).byteLength>_c||!yc(e.body)&&!bc(e))||e.requiresPrecondition!==n||n!==(e.precondition!==null)||e.precondition!==null&&!pc.test(e.precondition)||e.successStatuses.length===0||e.successStatuses.some(e=>!Number.isInteger(e)||e<200||e>299)||t!==(e.idempotency===`none`?void 0:e.idempotency)||e.idempotency!==`none`&&(e.method!==`POST`||e.body===null)||e.idempotency===`operation_start`&&e.precondition===null||(e.idempotency===`backup_create`||e.idempotency===`server_create`)&&e.precondition!==null||(e.uncertainProblemCodes?.length??0)!==0&&(!hc.test(e.route)||e.uncertainProblemCodes?.length!==1||e.uncertainProblemCodes[0]!==`keyring_unavailable`))throw Error(`invalid mutation specification`)}function Sc(e){return JSON.stringify([e.route,e.method,e.body,e.precondition,e.idempotency,[...e.successStatuses],[...e.uncertainProblemCodes??[]]])}async function Cc(e){if(e.headers.get(`Content-Type`)!==`application/problem+json`)return;let t;try{t=await e.json()}catch{return}let n=Bn(t);return n?.status===e.status?n:void 0}var wc=class{session;request;refreshCurrent;createKey;controllers=new Set;listeners=new Set;unregisterProtectedState;availability=`enabled`;constructor(e,t={}){this.session=e,this.request=(t.request??fetch).bind(globalThis),this.refreshCurrent=t.refreshCurrent??(()=>{}),this.createKey=t.key??vc,this.unregisterProtectedState=this.session.registerProtectedState(()=>{for(let e of this.controllers)e.resetForEpoch()})}snapshot(){return this.availability}subscribe(e){return this.listeners.add(e),e(this.availability),()=>this.listeners.delete(e)}create(){let e=new Tc(this);return this.controllers.add(e),e}setStorageLatched(e){let t=e?`storage_latched`:`enabled`;if(this.availability!==t){this.availability=t;for(let e of this.listeners)e(t);for(let e of this.controllers)e.availabilityChanged()}}close(){this.unregisterProtectedState();for(let e of[...this.controllers])e.close();this.controllers.clear(),this.listeners.clear()}available(){return this.availability===`enabled`}release(e){this.controllers.delete(e)}key(){let e=this.createKey();if(!/^[\x21-\x7e]{1,128}$/.test(e))throw Error(`invalid idempotency key`);return e}refresh(){this.refreshCurrent()}async execute(e,t){return await this.session.runProtected(async n=>this.requestMutation(n,e,t))??{outcome:{kind:`discarded`},storageLatched:!1}}async requestMutation(e,t,n){let r={"Content-Type":`application/json`,"X-CSRF-Token":e.csrfToken};t.precondition!==null&&(r[`If-Match`]=t.precondition),n!==void 0&&(r[`Idempotency-Key`]=n);let i;try{i=await this.request(t.route,{method:t.method,headers:r,body:t.body,credentials:`same-origin`,redirect:`error`,signal:e.signal})}catch{return{outcome:{kind:`uncertain`,canReplay:n!==void 0},storageLatched:!1}}if(await e.sessionLost(i))return{outcome:{kind:`discarded`},storageLatched:!1};if(t.successStatuses.includes(i.status))try{return{outcome:{kind:`acknowledged`,value:await t.decode(i)},storageLatched:!1}}catch{return{outcome:{kind:`uncertain`,canReplay:n!==void 0},storageLatched:!1}}let a=await Cc(i);return a===void 0||t.uncertainProblemCodes?.includes(a.code)===!0?{outcome:{kind:`uncertain`,canReplay:n!==void 0},storageLatched:!1}:a.code===`storage_unavailable`?{outcome:{kind:`uncertain`,canReplay:n!==void 0},storageLatched:!0}:{outcome:{kind:`rejected`,problem:a,requiresRefresh:i.status===409||i.status===412||i.status===428},storageLatched:!1}}},Tc=class{coordinator;listeners=new Set;state=`editing`;spec;recovery;problem;requiresRefresh=!1;version=0;inFlight;closed=!1;constructor(e){this.coordinator=e}snapshot(){let e={state:this.state,availability:this.coordinator.snapshot(),canReplay:this.state===`uncertain`&&this.recovery!==void 0&&this.coordinator.available(),requiresRefresh:this.requiresRefresh};return this.problem!==void 0&&(e.problem=this.problem),e}subscribe(e){return this.listeners.add(e),e(this.snapshot()),()=>this.listeners.delete(e)}begin(e){if(this.closed)throw Error(`mutation is closed`);if(this.state===`submitting`)throw Error(`mutation is submitting`);let t={...e,successStatuses:[...e.successStatuses],...e.uncertainProblemCodes===void 0?{}:{uncertainProblemCodes:[...e.uncertainProblemCodes]}};xc(t),this.version+=1,this.spec=t,this.recovery=t.idempotency===`none`?void 0:{key:this.coordinator.key(),spec:t,fingerprint:Sc(t)},this.problem=void 0,this.requiresRefresh=!1,this.state=`editing`,this.emit()}confirm(){if(this.state!==`editing`)throw Error(`mutation is not editable`);this.state=`confirming`,this.emit()}submit(){return this.inFlight===void 0?this.spec===void 0||this.state!==`editing`&&this.state!==`confirming`?Promise.resolve({kind:`discarded`}):this.start(!1):this.inFlight}replay(){return this.inFlight===void 0?this.state!==`uncertain`||this.recovery===void 0||!this.coordinator.available()||Sc(this.recovery.spec)!==this.recovery.fingerprint?Promise.resolve({kind:`discarded`}):(this.spec=this.recovery.spec,this.start(!0)):this.inFlight}abandon(){if(this.state===`submitting`)throw Error(`mutation is submitting`);this.version+=1,this.spec=void 0,this.recovery=void 0,this.problem=void 0,this.requiresRefresh=!1,this.state=`editing`,this.emit()}resetForEpoch(){this.closed||(this.version+=1,this.spec=void 0,this.recovery=void 0,this.problem=void 0,this.requiresRefresh=!1,this.state=`editing`,this.inFlight=void 0,this.emit())}availabilityChanged(){this.emit()}close(){this.closed||(this.resetForEpoch(),this.closed=!0,this.listeners.clear(),this.coordinator.release(this))}start(e){if(!this.coordinator.available()||this.spec===void 0)return Promise.resolve({kind:`discarded`});let t=this.version,n=this.spec,r=this.recovery?.key;this.state=`submitting`,this.problem=void 0,this.requiresRefresh=!1,this.emit();let i=this.coordinator.execute(n,r).then(n=>{if(t!==this.version)return{kind:`discarded`};n.storageLatched&&this.coordinator.setStorageLatched(!0);let r=n.outcome;return r.kind===`acknowledged`?(this.state=`acknowledged`,this.spec=void 0,this.recovery=void 0):r.kind===`rejected`?(this.state=`rejected`,this.spec=void 0,this.problem=r.problem,this.requiresRefresh=r.requiresRefresh,this.recovery=void 0,r.requiresRefresh&&this.coordinator.refresh()):r.kind===`uncertain`?(this.state=`uncertain`,r.canReplay||(this.spec=void 0,this.recovery=void 0)):(this.state=`editing`,this.recovery=void 0),e&&r.kind===`uncertain`&&(this.state=`uncertain`),this.emit(),r}).finally(()=>{this.inFlight===i&&(this.inFlight=void 0)});return this.inFlight=i,i}emit(){let e=this.snapshot();for(let t of this.listeners)t(e)}},Ec=/^[0-7][0-9A-HJKMNP-TV-Z]{25}$/,Dc=/^[1-9][0-9]*$/;function Z(){throw Error(`Git data is unavailable.`)}function Oc(e,t,n=[]){if(!e||typeof e!=`object`||Array.isArray(e))return Z();let r=e;return t.some(e=>!Object.hasOwn(r,e))||Object.keys(r).some(e=>!t.includes(e)&&!n.includes(e))?Z():r}function kc(e,t=4096){return typeof e==`string`&&new TextEncoder().encode(e).length<=t&&!/[\p{Cc}\p{Cf}]/u.test(e)}function Ac(e){return typeof e==`string`&&Ec.test(e)}function jc(e){return typeof e==`string`&&Dc.test(e)}function Mc(e){return typeof e==`string`&&Number.isFinite(Date.parse(e))}function Nc(e,t){let n=[`id`,`revision`,`created_at`,`updated_at`],r=e===`repositories`?[`name`,`url`,`aliases`,`credential_id`,`alias_revision`]:e===`credentials`?[`name`,`origin`,`recipe`,`available`,`referencing_repositories`]:[`principal_id`,`repository_id`,`description`,`policy`,`expires_at`,`state`],i=Oc(t,[...n,...r]);if(!Ac(i.id)||!jc(i.revision)||!Mc(i.created_at)||!Mc(i.updated_at)||e!==`grants`&&(!kc(i.name,256)||i.name.length===0))return Z();if(e===`repositories`){if(!kc(i.url)||!i.url.startsWith(`https://`)||!jc(i.alias_revision)||!(i.credential_id===null||Ac(i.credential_id))||!Array.isArray(i.aliases)||i.aliases.length>4||i.aliases.some(e=>!kc(e)||!e.startsWith(`https://`)))return Z()}else if(e===`credentials`){let e=Oc(i.recipe,[`header`,`prefix`]);if(!kc(i.origin)||!i.origin.startsWith(`https://`)||!kc(e.header,128)||!kc(e.prefix,128)||typeof i.available!=`boolean`||!Array.isArray(i.referencing_repositories)||i.referencing_repositories.length>256)return Z();for(let e of i.referencing_repositories)if(!Ac(Oc(e,[`id`]).id))return Z()}else{if(!Ac(i.principal_id)||!Ac(i.repository_id)||!(i.description===null||kc(i.description,1024))||!(i.expires_at===null||Mc(i.expires_at))||![`active`,`expired`].includes(String(i.state)))return Z();let e=Oc(i.policy,[`version`,`read`,`refs`]);if(e.version!==1||typeof e.read!=`boolean`||!Array.isArray(e.refs)||e.refs.length>128||e.refs.length>0&&!e.read)return Z();for(let t of e.refs){let e=Oc(t,[`ref`,`actions`]),n=Oc(e.ref,[`kind`,`value`]);if(![`exact`,`prefix`].includes(String(n.kind))||!kc(n.value,1024)||!Array.isArray(e.actions)||e.actions.length===0||e.actions.length>3||e.actions.some(e=>![`create`,`update`,`delete`].includes(String(e))))return Z()}}return t}function Pc(e,t){return`"git-${e===`repositories`?`repository`:e===`credentials`?`credential`:`grant`}-${t.id}-${t.revision}"`}async function Fc(e,t){if(t.headers.get(`Content-Type`)!==`application/json`)return Z();let n=await t.text();if(n.length>1048576)return Z();let r=Nc(e,JSON.parse(n));return t.headers.get(`ETag`)===Pc(e,r)?r:Z()}function Ic(e,t=!1){let n=Oc(e,[`id`,`revision`]);t&&n.id===``&&n.revision===``||(!Ac(n.id)||!jc(n.revision))&&Z()}function Lc(e){let t=Oc(e,[`items`,`next_cursor`]);if(!Array.isArray(t.items)||t.items.length>50||t.next_cursor!==null&&(typeof t.next_cursor!=`string`||t.next_cursor.length>512||!/^[A-Za-z0-9_-]+$/.test(t.next_cursor)))return Z();let n=t.items.map(Rc);return new Set(n.map(e=>e.admission.id)).size!==n.length||n.length===0&&t.next_cursor!==null?Z():{items:n,nextCursor:t.next_cursor,totalCount:void 0,offset:0}}function Rc(e){let t=Oc(e,[`admission`,`completion`]),n=Oc(t.admission,[`id`,`admitted_at`,`evaluated_at`,`principal`,`agent_credential`,`repository`,`alias_revision`,`profile_revision`,`authorization_revision`,`operation`,`commands`,`allowed`],[`policy`,`material`,`private_grant`,`rejection`,`denial`,`ref_evidence`]);if(!Ac(n.id)||!Mc(n.admitted_at)||!Mc(n.evaluated_at)||!jc(n.profile_revision)||!jc(n.authorization_revision)||typeof n.allowed!=`boolean`||!Number.isInteger(n.commands)||Number(n.commands)<0||Number(n.commands)>128||![`read`,`read_discovery`,`push`,`push_discovery`,`probe`,`invalid`].includes(String(n.operation))||Date.parse(String(n.evaluated_at))0||n.operation===`invalid`!=(n.rejection!==void 0)||(n.rejection!==void 0||n.denial!==void 0)&&n.allowed||n.operation!==`invalid`&&!jc(n.alias_revision)||n.operation===`invalid`&&(n.alias_revision!==``||n.policy!==void 0||n.material!==void 0||n.private_grant!==void 0)||(Ic(n.principal),Ic(n.agent_credential),Ic(n.repository,n.operation===`invalid`),n.rejection!==void 0&&![`unsupported`,`repository_unavailable`,`destination_unavailable`].includes(String(n.rejection)))||n.denial!==void 0&&n.denial!==`credential_unavailable`)return Z();if(n.policy!==void 0){let e=Oc(n.policy,[`repository_name`,`repository_url`,`grants`,`grant_count`,`creates`,`updates`,`deletes`]);if(!kc(e.repository_name,256)||!kc(e.repository_url)||!Array.isArray(e.grants)||e.grants.length>4)return Z();e.grants.forEach(e=>Ic(e));for(let t of[`grant_count`,`creates`,`updates`,`deletes`])if(!Number.isInteger(e[t])||Number(e[t])<0)return Z();if(Number(e.grant_count)4096||Number(e.creates)+Number(e.updates)+Number(e.deletes)!==n.commands||new Set(e.grants.map(e=>e.id)).size!==e.grants.length)return Z()}if(n.ref_evidence!==void 0){let e=Oc(n.ref_evidence,[`state`,`refs`]),t=JSON.stringify(e).replace(/[<>&]/g,e=>`\\u${e.charCodeAt(0).toString(16).padStart(4,`0`)}`);if(n.operation!==`push`||![`complete`,`truncated`].includes(String(e.state))||!Array.isArray(e.refs)||e.refs.length>8||e.refs.length>Number(n.commands)||e.state===`complete`!=(e.refs.length===n.commands)||new TextEncoder().encode(t).length>1536)return Z();let r=new Set,i={create:0,update:0,delete:0};for(let t of e.refs){let e=Oc(t,[`name`,`action`]);if(typeof e.name!=`string`||!Bc(e.name)||r.has(e.name)||![`create`,`update`,`delete`].includes(String(e.action)))return Z();r.add(e.name),i[e.action]++}if(n.policy!==void 0){let e=n.policy;if(i.create>e.creates||i.update>e.updates||i.delete>e.deletes)return Z()}}if(n.material!==void 0){let e=Oc(n.material,[`credential`,`generation`]);if(Ic(e.credential),!jc(e.generation)||!n.allowed)return Z()}if(n.private_grant!==void 0){let e=Oc(n.private_grant,[`id`,`revision`]);if(!Ac(e.id)||!Number.isSafeInteger(e.revision)||Number(e.revision)<1)return Z()}if(t.completion!==null){let e=Oc(t.completion,[`completed_at`,`outcome`,`bytes_sent`,`bytes_received`,`duration_ms`,`transfer_complete`],[`status`,`reported_result`,`failure`,`ref_outcomes`]);if(!n.allowed||!Mc(e.completed_at)||Date.parse(String(e.completed_at))599)||e.transfer_complete&&e.status===void 0||e.outcome===`nonmutation`&&(!e.transfer_complete||n.operation===`push`)||e.outcome===`prestart_failure`&&(e.status!==void 0||e.bytes_sent!==0||e.bytes_received!==0||e.transfer_complete)||e.failure!==void 0&&e.outcome!==`prestart_failure`||e.reported_result!==void 0&&(![`reported_success`,`reported_partial`,`reported_failure`].includes(String(e.reported_result))||n.operation!==`push`||e.status!==200||!e.transfer_complete))return Z();if(e.ref_outcomes!==void 0){let t=n.ref_evidence;if(!t||!Array.isArray(e.ref_outcomes)||e.ref_outcomes.length===0||e.ref_outcomes.length!==t.refs.length||e.reported_result===void 0||e.outcome!==`outcome_unknown`||e.ref_outcomes.some(e=>e!==`ok`&&e!==`ng`))return Z();let r=e.ref_outcomes.filter(e=>e===`ok`).length;if(e.reported_result===`reported_success`&&r!==e.ref_outcomes.length||e.reported_result===`reported_failure`&&r!==0||t.state===`complete`&&e.reported_result===`reported_partial`&&(r===0||r===e.ref_outcomes.length))return Z()}if(e.failure!==void 0&&![`credential_unavailable`,`authorization_unavailable`].includes(String(e.failure)))return Z()}return e}var zc={read:`Read`,read_discovery:`Read discovery`,push:`Push`,push_discovery:`Push discovery`,probe:`Push probe`,invalid:`Unsupported exchange`,unsupported:`Unsupported Git request`,repository_unavailable:`Repository unavailable`,destination_unavailable:`Destination unavailable`,credential_unavailable:`Credential unavailable`,authorization_unavailable:`Authorization unavailable`,reported_success:`Reported success`,reported_failure:`Reported failure`,reported_partial:`Reported partial success`};function Bc(e){return e.length<=1024&&e.startsWith(`refs/`)&&e.split(`/`).length>=3&&!e.includes(`..`)&&!e.includes(`@{`)&&!e.endsWith(`.`)&&!/[\x00-\x20\x7f-\uffff~^:?*\[\\\\]/.test(e)&&e.split(`/`).every(e=>e!==``&&!e.startsWith(`.`)&&!e.endsWith(`.lock`))}function Vc(e){let t=e.admission,n=e.completion;return t.allowed?n?n.outcome===`prestart_failure`||(n.status??0)>=400?`Failed`:n.transfer_complete?t.operation===`push`?n.reported_result?zc[n.reported_result]:`Unknown`:(n.status??0)>=200&&(n.status??0)<300?`HTTP success`:`Unknown`:`Incomplete`:`Unknown`:`Denied`}function Hc(e){let t=e.admission,n=e.completion;return{admission:t.allowed?`Allowed`:zc[t.rejection??t.denial??``]??`Blocked`,transport:t.allowed?n?.outcome===`prestart_failure`?zc[n.failure??``]??`Not started`:n===null?`Unknown`:n.transfer_complete?`Complete`:`Incomplete`:`Not dispatched`,report:t.operation===`push`?n?.reported_result?zc[n.reported_result]:`Unknown`:`Not a push`}}function Uc(e){if(e.length>4096||!/^[\x21-\x7e]+$/.test(e)||!/^https:\/\/[^/?#%@\\\s]+$/.test(e))throw Error(`Enter an HTTPS origin without a path, credentials, query or fragment.`);let t;try{t=new URL(e)}catch{throw Error(`Enter an exact HTTPS host and a valid port.`)}if(!t.hostname||t.port===`0`||t.hostname.includes(`*`))throw Error(`Enter an exact HTTPS host and a valid port.`);return`https://${t.hostname}:${t.port||`443`}`}function Wc(e,t){try{let n=/^https:\/\/([^/?#@%\\\s]+)(\/[A-Za-z0-9._~/-]+)$/.exec(e);if(e.length>4096||!n||n[2].slice(1).split(`/`).some(e=>e===``||e===`.`||e===`..`))return;let r=new URL(e);return t.origins.includes(Uc(`https://${r.host}`))}catch{return}}function Gc(e){if(e.length>256)throw Error(`Use at most 256 origins.`);let t=e.map(Uc).sort();if(new Set(t).size!==t.length)throw Error(`Each HTTPS origin must be unique.`);return t}function Kc(e){let t=Oc(e,[`origins`,`revision`,`active`]);if(typeof t.active!=`boolean`||typeof t.revision!=`string`||!/^[1-9][0-9]*$/.test(t.revision)||BigInt(t.revision)>9223372036854775807n||!Array.isArray(t.origins)||t.origins.some(e=>typeof e!=`string`)||JSON.stringify(Gc(t.origins))!==JSON.stringify(t.origins))throw Error(`Git routing profile is unavailable.`);return e}function qc(e){return`"git-profile-routing-${e.revision}"`}async function Jc(e){if(e.headers.get(`Content-Type`)!==`application/json`)throw Error(`Git routing profile is unavailable.`);let t=await e.text();if(t.length>1048576)throw Error(`Git routing profile is unavailable.`);let n=Kc(JSON.parse(t));if(e.headers.get(`ETag`)!==qc(n))throw Error(`Git routing revision is unavailable.`);return n}function Yc(e,t){if(!e||typeof e!=`object`||Array.isArray(e)||Object.keys(e).sort().join()!==t.sort().join())throw Error(`invalid observation health`);return e}function Xc(e){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<0)throw Error(`invalid observation count`);return e}function Zc(e){if(typeof e!=`boolean`)throw Error(`invalid observation flag`);return e}function Qc(e){if(typeof e!=`string`||e.length>128)throw Error(`invalid observation text`);return e}function $c(e,t){let n=Qc(e);if(!t.includes(n))throw Error(`invalid observation state`);return n}function el(e){let t=Yc(e,[`state`,`bytes`]),n=$c(t.state,[`available`,`absent`,`unavailable`]);if(n===`available`!=(t.bytes!==null))throw Error(`invalid measurement availability`);return{state:n,bytes:t.bytes===null?null:Xc(t.bytes)}}var tl=[`delivery`,`database_measurement`,`wal_measurement`,`free_space_measurement`,`pressure_reason`,`accounting_available`];function nl(e){if(!tl.some(t=>t in e))return;let t=Yc(e.delivery,[`accepted`,`acknowledged`,`discarded`,`queue_records`,`queue_bytes`,`completion_records`,`queue_record_limit`,`queue_byte_limit`]);return{delivery:{accepted:Xc(t.accepted),acknowledged:Xc(t.acknowledged),discarded:Xc(t.discarded),queue_records:Xc(t.queue_records),queue_bytes:Xc(t.queue_bytes),completion_records:Xc(t.completion_records),queue_record_limit:Xc(t.queue_record_limit),queue_byte_limit:Xc(t.queue_byte_limit)},database_measurement:el(e.database_measurement),wal_measurement:el(e.wal_measurement),free_space_measurement:el(e.free_space_measurement),pressure_reason:$c(e.pressure_reason,[`none`,`queue_capacity`,`checkpoint_reader`,`checkpoint_unavailable`,`budget_reservation`,`measurement_unavailable`,`low_space`,`history_unavailable`]),accounting_available:Zc(e.accounting_available)}}var rl=[`health`,`last_acknowledged`,`incident`],il=[`unknown`,`permission`,`ownership`,`missing`,`integrity`,`full`,`io`,`locked`,`deadline`,`capacity`],al=[`opening`,`validation`,`reservation`,`begin`,`statement`,`commit`,`rollback`,`acknowledgment`,`read`],ol=[`healthy`,`degraded`,`recovering`,`operator_action_required`,`recovered`,`disabled`,`opening`,`unavailable`];function sl(e,t=!1){let n=Qc(e);if(t&&n===``)return n;if(!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,9})?Z$/.test(n)||!Number.isFinite(Date.parse(n)))throw Error(`invalid incident timestamp`);return n}function cl(e){if(!rl.some(t=>t in e))return;let t=$c(e.health,ol),n=sl(e.last_acknowledged,!0);if(e.incident===null)return{health:t,lastAcknowledged:n,incident:null};let r=Yc(e.incident,[`first_failure`,`cause`,`stage`,`settlement`,`recovery`,`recovery_cause`,`recovery_stage`,`sqlite_code`,`affected`,`discarded`]),i=Xc(r.sqlite_code);if(i>65535)throw Error(`invalid SQLite code`);return{health:t,lastAcknowledged:n,incident:{firstFailure:sl(r.first_failure),cause:$c(r.cause,il),stage:$c(r.stage,al),recoveryCause:$c(r.recovery_cause,il),recoveryStage:$c(r.recovery_stage,al),settlement:$c(r.settlement,[`not_started`,`rolled_back`,`committed`,`uncertain`]),recovery:$c(r.recovery,[`degraded`,`recovering`,`operator_action_required`,`recovered`]),sqliteCode:i,affected:Xc(r.affected),discarded:Xc(r.discarded)}}}function ll(e){let t=e.incident;return t?t.recovery===`recovered`?`Recording resumed; discarded history was not reconstructed.`:t.recovery===`degraded`?`Validation passed; awaiting a new acknowledged observation.`:t.settlement===`uncertain`&&t.recovery===`recovering`?`Wait for owned settlement and safe validation. Do not replay missing history.`:t.recovery===`recovering`?`Waiting for bounded storage revalidation. Serving remains independent.`:[`permission`,`ownership`].includes(t.recoveryCause)?`Inspect history ownership and permissions; do not change them while serving.`:t.recoveryCause===`integrity`?`Preserve history files; use a separately qualified stopped recovery plan.`:[`full`,`capacity`].includes(t.recoveryCause)?`Inspect disk capacity and the traffic budget. Do not delete live database or WAL files.`:t.recoveryCause===`missing`?`Inspect the selected history generation; do not create a replacement.`:`Inspect filesystem availability. Missing history never authorizes replay.`:``}function ul(e){if(e===void 0)return;let t=Yc(e,[`state`,`epoch`,`accepted`,`written`,`dropped`,`invalid`,`write_failures`,`queue_records`,`queue_bytes`,`queue_limit`,`writing`,`last_successful_write`,`overflow`]);return{state:$c(t.state,[`ready`,`writing`,`pressure`,`failed`,`unavailable`]),epoch:Qc(t.epoch),accepted:Xc(t.accepted),written:Xc(t.written),dropped:Xc(t.dropped),invalid:Xc(t.invalid),write_failures:Xc(t.write_failures),queue_records:Xc(t.queue_records),queue_bytes:Xc(t.queue_bytes),queue_limit:Xc(t.queue_limit),writing:Zc(t.writing),last_successful_write:t.last_successful_write===null?null:Qc(t.last_successful_write),overflow:Zc(t.overflow)}}function dl(e){if(e===void 0)return;let t=Yc(e,[`epoch`,`started_at`,`coverage`,`overflow`,`protocols`]),n=(e,t)=>{if(!Array.isArray(e)||e.length!==t)throw Error(`invalid observation vector`);return e.map(Xc)};if(!Array.isArray(t.protocols)||t.protocols.length!==4)throw Error(`invalid observation protocols`);return{epoch:Qc(t.epoch),started_at:Qc(t.started_at),coverage:$c(t.coverage,[`owner_boundaries`,`unavailable`]),overflow:Zc(t.overflow),protocols:t.protocols.map((e,t)=>{let r=Yc(e,[`protocol`,`requests`,`executions`,`results`,`git_reports`,`latency`]);if(!Array.isArray(r.latency)||r.latency.length!==3)throw Error(`invalid observation stages`);return{protocol:$c(r.protocol,[[`mcp`,`http`,`connect`,`git`][t]]),requests:Xc(r.requests),executions:Xc(r.executions),results:n(r.results,5),git_reports:n(r.git_reports,3),latency:r.latency.map(e=>n(e,6))}})}}function fl(e){return e?.state===`available`?`${e.bytes.toLocaleString()} bytes`:e?.state===`absent`?`Absent`:`Unavailable`}function pl(e){if(e.desired===`enabled`){if(e.runtime===`authentication_required`)return`Authentication required`;if(e.runtime===`degraded`){if(e.reason===`configuration_invalid`)return`Configuration invalid`;if(e.reason===`protocol_unsupported`)return`Protocol unsupported`;if(e.reason===`stop_unconfirmed`)return`Process stop unconfirmed`}if(![`activating`,`retry_wait`,`stopping`].includes(e.runtime)&&[`absent`,`locked`,`interaction_required`,`unavailable`,`unsupported`,`reauthentication_required`,`cleanup_pending`].includes(e.credential))return`Credentials ${e.credential.replaceAll(`_`,` `)}`}}function ml(e,t){let n=e=>t.panels[`overview-${e}`]?.status===`current`,r=[],i=n(`status`)?e.status:void 0;if(i?.latched&&r.push({id:`control-storage`,label:`Control storage recovery required`,explanation:`Changes are blocked. Review the stopped-process recovery procedure in System status.`,href:`#/system`}),i?.traffic?.recovery?.health===`operator_action_required`&&r.push({id:`traffic-recording`,label:`Traffic recording needs attention`,explanation:`Recording requires operator action. Inspect traffic storage recovery in System status.`,href:`#/system`}),n(`servers`)){let t=new Set;for(let n of[...e.servers?.items??[]].sort((e,t)=>e.idt.id))){let e=pl(n);!e||t.has(n.id)||(t.add(n.id),r.push({id:n.id,label:n.name||`MCP server ${n.id}`,explanation:e,href:`#/mcp/servers/${n.id}`}))}}n(`requests`)&&e.requests&&e.requests.total>0&&r.push({id:`pending-requests`,label:`${e.requests.total.toLocaleString()} pending MCP ${e.requests.total===1?`request`:`requests`}`,explanation:`Review pending access requests.`,href:`#/mcp/access-requests`});let a=!!(i?.traffic?.recovery&&n(`servers`)&&e.servers?.complete&&n(`requests`)&&e.requests),o=[`status`,`servers`,`requests`].map(e=>t.panels[`overview-${e}`]);return{items:r,complete:a,notice:a?void 0:o.some(e=>e?.status===`error`)?`Attention data unavailable; list may be incomplete.`:o.some(e=>e?.status===`stale`)?`Attention data stale; current list is unknown.`:o.some(e=>!e||e.status===`loading`)?`Loading attention data…`:`Attention data incomplete; more items may need attention.`}}var hl=/^[0-7][0-9A-HJKMNP-TV-Z]{25}$/,gl=`http_regular.http_control_auth.http_admin.http_health.mcp_work.mcp_streams.admin_sessions.legacy_sessions.event_streams.backup_work.backup_records.admin_credentials.idempotency_records.keyring_candidates.keyring_work.database_bytes.server_identities.servers.downstream_runtimes.server_reconciliations.catalog_traversals.oauth_flows.oauth_callback_work.server_idempotency_records.active_tools.durable_tool_identities.downstream_dispatch.principals.grants.grant_requests.grant_request_evidence_bytes`.split(`.`);function Q(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`invalid response`);let n=e;if(Object.keys(n).sort().join(`,`)!==[...t].sort().join(`,`))throw Error(`invalid response`);return n}function $(e){if(typeof e!=`string`)throw Error(`invalid response`);return e}function _l(e){if(e!==null&&typeof e!=`string`)throw Error(`invalid response`);return e}function vl(e){if(typeof e!=`boolean`)throw Error(`invalid response`);return e}function yl(e){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<0)throw Error(`invalid response`);return e}function bl(e){let t=$(e);if(!hl.test(t))throw Error(`invalid response`);return t}function xl(e){if(!Array.isArray(e))throw Error(`invalid response`);return e}function Sl(e){let t=_l(e);if(t!==null&&(t.length===0||t.length>4096))throw Error(`invalid response`);return t}function Cl(e,t){let n=$(e);if(!t.includes(n))throw Error(`invalid response`);return n}function wl(e,t){let n=Q(e,[`in_use`,`limit`,`saturated`]);return{name:t,inUse:yl(n.in_use),limit:yl(n.limit),saturated:vl(n.saturated)}}function Tl(e){let t=typeof e==`object`&&!!e&&`traffic`in e,n=typeof e==`object`&&!!e&&`http_proxy`in e,r=typeof e==`object`&&!!e&&`endpoints`in e,i=Q(e,[...typeof e==`object`&&e?[`diagnostics`,`observations`].filter(t=>t in e):[],...r?[`endpoints`]:[],...n?[`http_proxy`]:[],...t?[`traffic`]:[],`process`,`sqlite`,`keyring`,`limits`,`backup`,`protocols`]),a;if(r){let e=Q(i.endpoints,[`authority`,`api`,`mcp`]);a={authority:$(e.authority),api:Cl(e.api,[`starting`,`ready`,`read_only`,`draining`]),mcp:Cl(e.mcp,[`starting`,`ready`,`disabled`,`unavailable`,`draining`])}}let o;if(t){let e=i.traffic&&typeof i.traffic==`object`&&`delivery`in i.traffic?tl:[],t=i.traffic&&typeof i.traffic==`object`&&`health`in i.traffic?rl:[],n=Q(i.traffic,[...t,...e,`state`,`ready`,`faulted`,`pressure`,`budget_bytes`,`database_bytes`,`wal_bytes`,`quota_refusals`,`pruned_records`,`generation`,`rolling_history`,`unknown_completion_possible`]);if(!vl(n.rolling_history)||!vl(n.unknown_completion_possible))throw Error(`invalid traffic history semantics`);o={health:nl(n),recovery:cl(n),state:Cl(n.state,[`opening`,`ready`,`unavailable`,`faulted`,`disabled`]),ready:vl(n.ready),faulted:vl(n.faulted),pressure:vl(n.pressure),budgetBytes:yl(n.budget_bytes),databaseBytes:yl(n.database_bytes),walBytes:yl(n.wal_bytes),quotaRefusals:yl(n.quota_refusals),prunedRecords:yl(n.pruned_records),generation:$(n.generation)}}let s;if(n){let e=i.http_proxy,t=typeof e==`object`&&!!e&&`authority`in e,n=Q(e,[`enabled`,`ready`,`ca_ready`,`connections`,`work`,`active_streams`,`active_tunnels`,...t?[`authority`]:[]]);s={enabled:vl(n.enabled),ready:vl(n.ready),caReady:vl(n.ca_ready),...t?{authority:$(n.authority)}:{},connections:wl(n.connections,`http_regular`),work:wl(n.work,`http_regular`),activeStreams:yl(n.active_streams),activeTunnels:yl(n.active_tunnels)}}let c=Q(i.process,[`state`,`ready`,`started_at`]),l=Q(i.sqlite,[`state`,`schema_version`,`revision`,`latched`]),u=Q(i.keyring,[`capability`]),d=Q(i.limits,gl),f=Q(i.backup,[`state`,`last_completed_at`]),p=Q(i.protocols,[`modern`,`legacy`,`agent_auth`]);return{diagnostics:ul(i.diagnostics),observations:dl(i.observations),...a?{endpoints:a}:{},...o?{traffic:o}:{},...s?{httpProxy:s}:{},processState:Cl(c.state,[`uninitialized`,`starting`,`ready`,`storage_failed`,`draining`]),ready:vl(c.ready),startedAt:$(c.started_at),sqliteState:Cl(l.state,[`uninitialized`,`ready`,`latched`]),schemaVersion:$(l.schema_version),revision:$(l.revision),latched:vl(l.latched),keyring:Cl(u.capability,[`ready`,`absent`,`locked`,`interaction_required`,`unavailable`,`unsupported`]),limits:gl.map(e=>wl(d[e],e)),backupState:Cl(f.state,[`idle`,`creating`,`unavailable`]),lastBackupAt:_l(f.last_completed_at),modernProtocol:$(p.modern),legacyProtocol:$(p.legacy),agentAuth:Cl(p.agent_auth,[`deny_all`,`principal_credentials`])}}function El(e){return wl(e,`http_regular`)}function Dl(e){let t=Q(e,Object.keys(e));if(Cl(t.kind,[`stdio`,`streamable_http`])===`stdio`){let t=Q(e,[`kind`,`executable`,`arguments`,`working_directory`,`environment`,`secret_environment`]);$(t.executable),$(t.working_directory),xl(t.arguments).forEach($);for(let e of[t.environment,t.secret_environment]){let t=Q(e,Object.keys(e));Object.values(t).forEach($)}return}let n=Q(e,[`kind`,`url`,`protocol_mode`,`authentication`,...Object.hasOwn(t,`headers`)?[`headers`]:[]]);if(n.headers!==void 0){let e=n.headers;if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`invalid HTTP headers`);let t=Q(e,Object.keys(e));Object.values(t).forEach($)}$(n.url),Cl(n.protocol_mode,[`modern`,`legacy`,`auto`]);let r=Q(n.authentication,Object.keys(n.authentication)),i=Cl(r.mode,[`none`,`bearer`,`oauth`]);if(i===`none`||i===`bearer`){Q(n.authentication,[`mode`]);return}let a=Q(n.authentication,[`mode`,`registration`,`trusted_origins`,`request_offline_access`,...[`callback_uri`,`auth_server_metadata_url`,`scopes`].filter(e=>Object.hasOwn(r,e))]);if(a.callback_uri!==void 0&&$(a.callback_uri),a.auth_server_metadata_url!==void 0&&$(a.auth_server_metadata_url),a.scopes!==void 0&&xl(a.scopes).forEach($),xl(a.trusted_origins).forEach($),vl(a.request_offline_access),Cl(Q(a.registration,Object.keys(a.registration)).mode,[`static`,`dynamic`])===`dynamic`)_l(Q(a.registration,[`mode`,`issuer`]).issuer);else{let e=Q(a.registration,[`mode`,`issuer`,`client_id`,`token_endpoint_auth_method`]);_l(e.issuer),$(e.client_id),$(e.token_endpoint_auth_method)}}function Ol(e){let t=Q(e,[`id`,`namespace`,`display_name`,`desired_state`,`desired_revision`,`transport`,`credential_revisions`,`credential_state`,`runtime`,`catalog`,`created_at`,`updated_at`,`deleted_at`]),n=bl(t.id);$(t.namespace),$(t.desired_revision);let r=Cl(t.desired_state,[`enabled`,`disabled`,`deleted`]);if(r===`deleted`){if(t.transport!==null)throw Error(`invalid response`)}else Dl(t.transport);let i=Q(t.credential_revisions,[`static_credential`,`oauth_client`,`oauth_tokens`]);Object.values(i).forEach($);let a=Cl(t.credential_state,[`not_required`,`ready`,`absent`,`locked`,`interaction_required`,`unavailable`,`unsupported`,`refreshing`,`reauthentication_required`,`disconnecting`,`cleanup_pending`]),o=typeof t.runtime==`object`&&t.runtime!==null&&`diagnostic_correlation`in t.runtime,s=Q(t.runtime,[`state`,`reason`,`runtime_id`,`reconciliation`,`dispatch`,...o?[`diagnostic_correlation`]:[]]);br(s.diagnostic_correlation);let c=Cl(s.state,[`inactive`,`activating`,`active`,`stopping`,`retry_wait`,`degraded`,`authentication_required`,`deleted`]),l=_l(s.reason);_l(s.runtime_id);let u=El(s.reconciliation),d=El(s.dispatch),f=Q(t.catalog,[`durable_state`,`active_state`,`durable_revision`,`active_revision`,`durable_tool_count`,`active_tool_count`,`last_success_at`,`traversal`]);Cl(f.durable_state,[`empty`,`current`,`stale`,`unavailable`,`retired`]);let p=Cl(f.active_state,[`absent`,`refreshing`,`current`,`stale`,`unavailable`]);_l(f.durable_revision),_l(f.active_revision),yl(f.durable_tool_count);let m=yl(f.active_tool_count);_l(f.last_success_at);let h=El(f.traversal);$(t.created_at),$(t.updated_at),_l(t.deleted_at);let g=u.saturated||d.saturated||h.saturated,_=r===`enabled`&&(c!==`active`||a!==`ready`&&a!==`not_required`||p!==`current`||g);return{id:n,name:$(t.display_name),desired:r,runtime:c,reason:l,credential:a,catalog:p,activeToolCount:m,attention:_,saturated:g}}function kl(e){let t=Q(e,[`items`,`next_cursor`]);return{items:xl(t.items).map(Ol),next:Sl(t.next_cursor)}}function Al(e){let t=Q(e,[..._r(e),`scope`,`target`,`constraint`,`duration_seconds`,`future_tools_acknowledged`]);Cl(t.scope,[`tool`,`server`]);let n=$(t.target);if(_l(t.duration_seconds),vl(t.future_tools_acknowledged),vr(t)&&(t.scope!==`server`||t.constraint!==null||t.future_tools_acknowledged!==!0)||t.constraint!==null&&(typeof t.constraint!=`object`||Array.isArray(t.constraint)))throw Error(`invalid response`);return n}function jl(e){let t=Q(e,[`items`,`next_cursor`,`total_count`,`offset`]),n=yl(t.total_count);if(yl(t.offset)!==0)throw Error(`invalid queue offset`);let r=Sl(t.next_cursor),i=xl(t.items).map(e=>{let t=Q(e,[`request`,`principal_display_name`,`server_display_name`,`resolved_server_id`,`resolved_upstream_name`]),n=$(t.principal_display_name),r=$(t.server_display_name);bl(t.resolved_server_id),t.resolved_upstream_name!==null&&$(t.resolved_upstream_name);let i=Q(t.request,[`id`,`principal_id`,`state`,`revision`,`requested_policy`,`approved_policy`,`approved_grant_id`,`rejection_reason`,`created_at`,`updated_at`,`closed_at`]);if(Cl(i.state,[`pending`]),$(i.revision),i.approved_policy!==null||i.approved_grant_id!==null||i.rejection_reason!==null||i.closed_at!==null)throw Error(`invalid response`);return $(i.updated_at),{id:bl(i.id),principalID:bl(i.principal_id),principalName:n,serverName:r,target:Al(i.requested_policy),createdAt:$(i.created_at)}});if(i.length!==Math.min(n,5)||r===null!=(i.length===n)||new Set(i.map(e=>e.id)).size!==i.length)throw Error(`invalid queue coverage`);return{items:i,total:n,complete:r===null}}async function Ml(e){if(e.status!==200||e.headers.get(`Content-Type`)!==`application/json`)throw Error(`read failed`);let t=await e.text();if(new TextEncoder().encode(t).byteLength>4194304)throw Error(`response too large`);return JSON.parse(t)}async function Nl(e,t){let n=await fetch(t,{method:`GET`,headers:{"X-CSRF-Token":e.csrfToken},credentials:`same-origin`,redirect:`error`,signal:e.signal});if(await e.sessionLost(n))throw Error(`session lost`);return n}async function Pl(e){if(e.status!==409||e.headers.get(`Content-Type`)!==`application/problem+json`)return!1;let t=await e.text();if(new TextEncoder().encode(t).byteLength>65536)return!1;let n;try{n=JSON.parse(t)}catch{return!1}try{let e=Q(n,[`status`,`code`,`title`]);return yl(e.status)===409&&$(e.code)===`stale_cursor`&&$(e.title).length>0}catch{return!1}}async function Fl(e){let t=[],n=null,r=!1,i=new Set;for(let a=0;a<32;a+=1){let a=await Nl(e,`/api/v2/mcp/servers?limit=50${n===null?``:`&cursor=${encodeURIComponent(n)}`}`);if(n!==null&&!r&&await Pl(a)){t=[],n=null,r=!0,i.clear();continue}if(a.status!==200){if(t.length>0)return{items:t,complete:!1,restarted:r};throw Error(`server read failed`)}let o=kl(await Ml(a));if(t.push(...o.items.filter(e=>e.desired!==`deleted`)),n=o.next,n===null)return{items:t,complete:!0,restarted:r};if(i.has(n))throw Error(`repeated cursor`);i.add(n)}return{items:t,complete:!1,restarted:r}}var Il=class{views;listeners=new Set;value={};constructor(e,t,n){this.views=t;let r=e=>e===`#/overview`,i=e=>r(e)||e===`#/system?tab=needs-attention`;t.registerPanel({id:`overview-status`,matches:i,invalidations:[`system_status`],read:async e=>Tl(await Ml(await Nl(e,`/api/v2/system-status`))),publish:e=>{this.value={...this.value,status:e},n(e.latched),this.emit()}}),t.registerPanel({id:`overview-servers`,matches:i,invalidations:[`servers`,`catalog`],read:Fl,publish:e=>{this.value={...this.value,servers:e},this.emit()}}),t.registerPanel({id:`overview-requests`,matches:i,invalidations:[`grant_requests`],read:async e=>jl(await Ml(await Nl(e,`/api/v2/mcp/grant-requests?limit=5&state=pending&sort=submitted&direction=ascending`))),publish:e=>{this.value={...this.value,requests:e},this.emit()}}),t.registerPanel({id:`overview-activity`,matches:r,invalidations:[`system_status`,`invocations`],read:async e=>{let t=this.value.window??`1h`,n=Le(await Ml(await Nl(e,`/api/v2/protocol-activity?window=${t}`)));if(n.window!==t)throw Error(`Activity window mismatch`);return n},publish:e=>{this.value={...this.value,activity:e},this.emit()}});for(let[e,n]of Object.entries({httpCredentials:`http/credentials`,httpGrants:`http/grants`,gitCredentials:`git/credentials`,gitRepositories:`git/repositories`,gitGrants:`git/grants`,mcpGrants:`mcp/grants`,routing:`git/routing-profile`}))t.registerPanel({id:`overview-${e}`,matches:r,invalidations:[`authorization`,`http_credentials`,`system_status`],read:async t=>e===`routing`?(await Jc(await Nl(t,`/api/v2/${n}`))).origins.length:ze(await Ml(await Nl(t,`/api/v2/${n}?limit=1`))),publish:t=>{this.value={...this.value,inventory:{...this.value.inventory,[e]:t}},this.emit()}});e.registerProtectedState(()=>{this.value={},n(!1),this.emit()})}setWindow(e){if(!je.includes(e)||e===(this.value.window??`1h`))return;let{activity:t,...n}=this.value;this.value={...n,window:e},this.emit(),this.views.refreshPanel(`overview-activity`)}snapshot(){return this.value}subscribe(e){return this.listeners.add(e),e(this.value),()=>this.listeners.delete(e)}emit(){for(let e of this.listeners)e(this.value)}};function Ll({id:e,title:t,panel:n,children:r}){let i=n?.status??`loading`,a=e===`overview-material`||e===`overview-capacity`;return U(`section`,{class:`panel overview-panel`,"data-testid":e,"data-panel-status":i,"aria-labelledby":`${e}-title`,children:[U(`div`,{class:`panel-heading`,children:[U(`div`,{children:U(`h2`,{id:`${e}-title`,children:t})}),U(G,{state:i===`error`?`error`:i,children:W(i)})]}),n?.hasValue===!0&&i!==`current`&&U(`p`,{class:`overview-evidence`,role:e===`overview-material`||e===`overview-capacity`?void 0:`status`,children:[i===`error`?`Refresh failed.`:`Data stale.`,` Showing the last read; current state is unknown.`]}),i===`error`&&n?.hasValue!==!0?a?U(`p`,{children:`System read unavailable.`}):U(K,{state:`error`,title:`Read unavailable`,children:U(`p`,{children:`Refresh after checking Gateway availability.`})}):i===`loading`&&n?.hasValue!==!0?a?U(`p`,{children:`Loading system data`}):U(K,{state:`loading`,title:`Loading current data`}):r]})}function Rl({label:e,value:t,current:n}){return U(`div`,{children:[U(`dt`,{children:e}),U(`dd`,{children:U(G,{state:!n||t===void 0||t===`disabled`?`neutral`:t===`ready`?`current`:t===`starting`||t===`draining`?`warning`:`unavailable`,children:t===void 0?`Not reported`:W(t)})})]})}function zl({controller:e,view:t,preview:n=!1}){let[r,i]=z(e.snapshot());B(()=>e.subscribe(i),[e]);let{items:a,complete:o,notice:s}=ml(r,t);return U(`section`,{class:`panel ${n?`overview-panel attention-preview`:`attention-detail`}`,"data-testid":`needs-attention`,"aria-labelledby":`needs-attention-title`,children:[U(`h2`,{id:`needs-attention-title`,children:`Needs attention`}),s&&U(`p`,{class:`overview-evidence`,role:`status`,children:s}),o&&a.length===0&&U(`p`,{children:`Nothing needs attention`}),U(`ul`,{class:`attention-list`,"data-testid":`overview-requests`,"data-panel-status":t.panels[`overview-requests`]?.status??`loading`,children:(n?a.slice(0,3):a).map(e=>U(`li`,{children:[U(`a`,{href:e.href,children:e.label}),!n&&U(`p`,{children:e.explanation})]},e.id))}),n&&U(`footer`,{children:[U(`a`,{href:`#/system?tab=needs-attention`,children:`View all`}),o&&a.length>3&&U(`span`,{children:[a.length-3,` more`]})]})]})}function Bl({controller:e,view:t}){let[n,r]=z(e.snapshot());B(()=>e.subscribe(r),[e]);let i=e=>t.panels[e],a=n.status,o=n.servers?.items.length??0,s=n.servers?.items.reduce((e,t)=>e+BigInt(t.activeToolCount),0n)??0,c=e=>i(e)?.status===`current`,l=(e,t,r,a=n.inventory?.[e],o=!0,s=`overview-${e}`)=>U(`div`,{children:[U(`dt`,{children:U(`a`,{href:r,children:t})}),U(`dd`,{children:a===void 0?i(s)?.status===`error`?`Unavailable`:`Loading…`:o?U(S,{children:[a.toLocaleString(),!c(s)&&U(`span`,{class:`overview-evidence`,children:` · stale`})]}):`Incomplete`})]}),u=e=>{let t=n.activity;if(!t)return U(`p`,{children:i(`overview-activity`)?.status===`error`?`Recent activity unavailable`:`Loading recent activity…`});if(!t.counts)return U(`p`,{class:`overview-evidence`,children:`Recent history unavailable`});let r=t.counts[e];return U(`div`,{class:`protocol-activity`,children:[U(`dl`,{class:`overview-facts`,children:U(`div`,{children:[U(`dt`,{children:U(`a`,{href:Re(e,t),children:e===`http`?`Requests`:e===`git`?`Operations`:`Invocations`})}),U(`dd`,{children:r.total.toLocaleString()})]})}),!c(`overview-activity`)&&U(`p`,{class:`overview-context`,children:`Stale; current counts unknown`})]})};return U(`div`,{class:`overview`,"data-testid":`overview-grid`,children:[U(Ll,{id:`overview-status`,title:`Gateway status`,panel:i(`overview-status`),children:a!==void 0&&U(`div`,{class:`overview-stack`,children:[U(`dl`,{class:`overview-facts`,children:[U(Rl,{label:`Process`,value:a.ready?`ready`:a.processState,current:c(`overview-status`)}),U(Rl,{label:`Administration API`,value:a.endpoints?.api,current:c(`overview-status`)}),U(Rl,{label:`MCP ingress`,value:a.endpoints?.mcp,current:c(`overview-status`)}),U(Rl,{label:`HTTP proxy`,value:a.httpProxy?a.httpProxy.enabled?a.httpProxy.ready?`ready`:`not_ready`:`disabled`:void 0,current:c(`overview-status`)})]}),!a.ready&&U(K,{state:`warning`,title:`Process ${W(a.processState).toLowerCase()} · not ready`,children:U(`p`,{children:[`Gateway is not ready to accept work.`,` `,U(`a`,{href:`#/system`,children:`Inspect System`})]})})]})}),U(Ll,{id:`overview-material`,title:`Storage and security`,panel:i(`overview-status`),children:a!==void 0&&U(`div`,{class:`overview-stack`,children:[U(`dl`,{class:`overview-facts`,children:[U(`div`,{children:[U(`dt`,{children:`Control storage`}),U(`dd`,{children:U(vn,{value:a.latched?`recovery_required`:a.sqliteState,current:c(`overview-status`)})})]}),U(`div`,{children:[U(`dt`,{children:`Traffic storage`}),U(`dd`,{children:U(vn,{value:a.traffic?a.traffic.state===`ready`&&a.traffic.pressure?`storage_pressure`:a.traffic.state:void 0,current:c(`overview-status`)})})]}),U(`div`,{children:[U(`dt`,{children:`Credential storage`}),U(`dd`,{children:U(vn,{value:a.keyring,current:c(`overview-status`)})})]}),U(`div`,{children:[U(`dt`,{children:`Interception CA loaded`}),U(`dd`,{children:U(G,{state:c(`overview-status`)?`neutral`:`stale`,children:a.httpProxy?a.httpProxy.caReady?`Yes`:`No`:`Not reported`})})]}),U(`div`,{children:[U(`dt`,{children:`Backup activity`}),U(`dd`,{children:U(vn,{value:a.backupState,current:c(`overview-status`)})})]}),U(`div`,{children:[U(`dt`,{children:`Last backup`}),U(`dd`,{class:`overview-backup-time`,children:U(Y,{value:a.lastBackupAt,fallback:`No completion reported`,compact:!0})})]})]}),(a.latched||a.sqliteState!==`ready`)&&U(K,{state:`error`,title:a.latched?`Recovery required`:`Control storage ${a.sqliteState}`,children:U(`p`,{children:[a.latched?`Changes cannot be saved.`:`Storage is not ready.`,` `,U(`a`,{href:`#/system`,children:`Inspect storage status`})]})}),a.keyring!==`ready`&&U(K,{state:`warning`,title:`Credential storage: ${W(a.keyring).toLowerCase()}`,children:U(`p`,{children:[`Startup capability is not a live credential check.`,` `,U(`a`,{href:`#/system`,children:`Inspect keyring status`})]})})]})}),U(zl,{controller:e,view:t,preview:!0}),U(`div`,{class:`protocol-toolbar`,children:[U(`h2`,{children:`Protocol activity`}),U(`label`,{children:[`Recent activity`,` `,U(`select`,{"aria-label":`Recent activity window`,value:n.window??`1h`,onChange:t=>e.setWindow(t.currentTarget.value),children:je.map(e=>U(`option`,{value:e,children:e},e))})]})]}),U(`section`,{class:`panel overview-panel protocol-card`,"aria-labelledby":`overview-http-title`,children:[U(`h2`,{id:`overview-http-title`,children:`HTTP`}),U(`dl`,{class:`overview-facts protocol-inventory`,children:[l(`httpCredentials`,`Credentials`,`#/http/credentials`),l(`httpGrants`,`Grants`,`#/http/grants`)]}),u(`http`)]}),U(`section`,{class:`panel overview-panel protocol-card`,"aria-labelledby":`overview-git-title`,children:[U(`h2`,{id:`overview-git-title`,children:`Git`}),U(`dl`,{class:`overview-facts protocol-inventory`,children:[l(`routing`,`Routing origins`,`#/git/routing`),l(`gitCredentials`,`Credentials`,`#/git/credentials`),l(`gitRepositories`,`Repositories`,`#/git/repositories`),l(`gitGrants`,`Grants`,`#/git/grants`)]}),u(`git`)]}),U(`section`,{class:`panel overview-panel protocol-card`,"data-testid":`overview-mcp`,"aria-labelledby":`overview-mcp-title`,children:[U(`h2`,{id:`overview-mcp-title`,children:`MCP`}),U(`dl`,{class:`overview-facts protocol-inventory`,"data-testid":`overview-servers`,"data-panel-status":i(`overview-servers`)?.status??`loading`,children:[l(`servers`,`Servers`,`#/mcp/servers`,n.servers?o:void 0,n.servers?.complete,`overview-servers`),l(`tools`,`Tools`,`#/mcp/tools`,n.servers?s:void 0,n.servers?.complete,`overview-servers`),l(`mcpGrants`,`Grants`,`#/mcp/grants`)]}),u(`mcp`)]})]})}function Vl(e){if(!/^https:\/\/[^/?#%@\\\s]+\/[A-Za-z0-9._~/-]+$/.test(e))return e;let t=e.slice(e.indexOf(`/`,8));if(t.slice(1).split(`/`).some(e=>!e||e===`.`||e===`..`))return e;try{let n=new URL(e);return n.port===`0`?e:`https://${n.hostname}:${n.port||`443`}${t}`}catch{return e}}function Hl(e){if(!e)return``;let t=new Date(e);return new Date(t.getTime()-t.getTimezoneOffset()*6e4).toISOString().slice(0,16)}function Ul(e,t){if(e===Hl(t))return t??null;if(!e)return null;let n=Date.parse(e);return Number.isNaN(n)?e:new Date(n).toISOString().replace(/\.000Z$/,`Z`)}function Wl(e){try{let t=new URL(e);if(t.protocol!==`https:`||t.username||t.password||t.search||t.hash||t.pathname===`/`||t.pathname.endsWith(`/`)||/[%?#\\\\]/.test(e)||!t.pathname.slice(1).split(`/`).every(e=>/^[A-Za-z0-9._~-]+$/.test(e)))return null;let n=t.pathname.endsWith(`.git`)?t.pathname.slice(0,-4):`${t.pathname}.git`;return!n||n.endsWith(`/`)?null:(t.pathname=n,t.href)}catch{return null}}function Gl(e,t){let n=e=>{try{return new URL(e).href}catch{return e}},r=t.map(n);return!r.includes(n(e))&&new Set(r).size===r.length}async function Kl(e,t,n,r,i){let a=[],o=null;for(let s=0;sr||s.offset!==a.length)throw Error(`Choices unavailable`);if(a.push(...s.items),a.length>r||new Set(a.map(e=>e.id)).size!==a.length)throw Error(`Invalid choices`);if(s.nextCursor===null)return a;o=s.nextCursor}throw Error(`Choice limit exceeded`)}function ql(e,t,n){let[r,i]=z({generation:-1,agents:[],repositories:[],credentials:[],loading:!0,error:!1});return B(()=>{let r=new AbortController;return i(e=>({...e,loading:!0})),Promise.all([n===`grants`?Kl(e,`/api/v2/principals`,e=>{let t=Jo(e);return{id:t.id,name:t.displayName}},128,r.signal):[],n===`repositories`?[]:Kl(e,`/api/v2/git/repositories`,e=>Nc(`repositories`,e),256,r.signal),n===`repositories`?Kl(e,`/api/v2/git/credentials`,e=>Nc(`credentials`,e),256,r.signal):[]]).then(([e,n,a])=>{r.signal.aborted||i({generation:t,agents:e,repositories:n,credentials:a,loading:!1,error:!1})}).catch(()=>{r.signal.aborted||i(e=>({...e,generation:t,loading:!1,error:!0}))}),()=>r.abort()},[e,t,n]),r.generation===t?r:{...r,loading:!0}}function Jl(e,t){return`${e.name||`Unnamed resource`}${t.filter(t=>t.name===e.name).length>1?` · ${e.id}`:``}`}function Yl(e,t){try{return e.available===!0&&e.origin!==void 0&&new URL(t).origin===new URL(e.origin).origin}catch{return!1}}function Xl(e,t,n){let[r,i]=z({generation:-1,loading:!0,error:!1});return B(()=>{if(!n)return;let r=!0;return e.runProtected(async e=>{let n=await fetch(`/api/v2/git/routing-profile`,{credentials:`same-origin`,redirect:`error`,signal:e.signal,headers:{Accept:`application/json`,"X-CSRF-Token":e.csrfToken}});if(await e.sessionLost(n))return;if(!n.ok)throw Error(`Routing unavailable`);let a=await Jc(n);r&&i({generation:t,profile:a,loading:!1,error:!1})}).catch(()=>{r&&i(e=>({...e,generation:t,loading:!1,error:!0}))}),()=>{r=!1}},[e,t,n]),n&&r.generation===t?r:{...r,loading:!0}}function Zl({source:e,destination:t,contextual:n=!1}){let r=`neutral`,i;if(e.loading)r=`loading`,i=`Checking routing`;else if(e.error||!e.profile)r=e.profile?`stale`:`warning`,i=e.profile?`Routing stale`:`Routing unknown`;else if(!e.profile.active)i=`Routing inactive`;else{let a=Wc(t,e.profile);if(a===void 0)r=`warning`,i=`Routing unknown`;else if(a){if(!n)return null;i=`Origin enabled`}else r=`warning`,i=`Not routed`}return U(`div`,{class:`git-routing-coverage`,children:[U(G,{state:r,children:i}),n&&U(`p`,{children:[i===`Not routed`?`Repository origin is not enabled in Git routing. `:``,U(`a`,{href:`#/git/routing`,children:`Git routing`}),` · Coverage does not establish grants, credential readiness or access.`]})]})}var Ql=e=>e===`repositories`?`repository`:e===`credentials`?`credential`:`grant`,$l=e=>e.name??e.description??`Unnamed Git grant`;function eu(e,t,n){let[r,i]=z(),[a,o]=z(!1),[s,c]=z(!1);return B(()=>{let r=!0;if(o(!1),c(t!==void 0),t!==void 0)return e.session.runProtected(async e=>{let a=await fetch(t,{credentials:`same-origin`,redirect:`error`,signal:e.signal,headers:{Accept:`application/json`,"X-CSRF-Token":e.csrfToken}});if(await e.sessionLost(a))return;if(!a.ok)throw Error(`Read unavailable`);let o=await n(a);r&&(i(o),c(!1))}).catch(()=>{r&&(o(!0),c(!1))}),()=>{r=!1}},[t,e.view.generation]),{value:r,error:a,loading:s}}function tu(e){let{kind:t}=e,n=e.resolved.location.segments[1],r=ql(e.session,e.view.generation,t),i=Xl(e.session,e.view.generation,t===`repositories`&&e.view.viewKey===e.resolved.canonicalFragment),[a,o]=z(),{value:s,error:c,loading:l}=eu(e,n&&n!==`new`?`/api/v2/git/${t}/${n}`:void 0,async e=>{let r=await Fc(t,e);if(r.id!==n)throw Error(`Identity unavailable`);return r});return n===void 0?U(ru,{...e,choices:r,coverage:i}):n===`new`?U(ou,{...e,choices:r,coverage:i,mode:`create`}):s?U(`div`,{class:`domain-view`,children:[U(`nav`,{class:`detail-navigation`,"aria-label":`Git resource navigation`,children:U(`a`,{href:ln({...e.resolved.location,segments:[e.resolved.location.destination]}),children:[`Back to Git `,t]})}),U(`header`,{class:`detail-context`,"data-testid":`detail-context`,children:[U(`div`,{class:`detail-context-heading`,children:[U(`h1`,{tabindex:-1,children:$l(s)}),t===`credentials`?U(G,{state:c?`stale`:s.available?`current`:`warning`,children:s.available?`Configured`:`Unavailable`}):t===`grants`?U(G,{state:c?`stale`:s.state===`active`?`current`:`neutral`,children:s.state===`active`?`Active`:`Expired`}):null]}),U(`p`,{class:`technical-value`,children:s.id})]}),c&&U(K,{state:`error`,title:`Git resource refresh unavailable`,children:`Saved facts may be stale. Refresh before making changes.`}),U(`section`,{class:`detail-section`,children:[U(`h2`,{children:`${Ql(t)[0].toUpperCase()}${Ql(t).slice(1)} details`}),U(`dl`,{class:`detail-facts`,children:[t===`repositories`&&U(S,{children:[U(`div`,{children:[U(`dt`,{children:`Canonical destination`}),U(`dd`,{children:s.url})]}),U(`div`,{children:[U(`dt`,{children:`Origin enabled`}),U(`dd`,{children:i.loading||i.error||!i.profile||Wc(s.url,i.profile)===void 0?`Unavailable`:i.profile.active&&Wc(s.url,i.profile)?`Yes`:`No`})]}),U(`div`,{children:[U(`dt`,{children:`Explicit aliases`}),U(`dd`,{children:s.aliases?.length?s.aliases.map(e=>U(`p`,{children:e},e)):`None`})]}),U(`div`,{children:[U(`dt`,{children:`Git credential`}),U(`dd`,{children:s.credential_id?U(nu,{id:s.credential_id,kind:`credentials`,choices:r}):`None`})]})]}),t===`grants`&&U(S,{children:[U(`div`,{children:[U(`dt`,{children:`Agent`}),U(`dd`,{children:U(nu,{id:s.principal_id,kind:`agents`,choices:r})})]}),U(`div`,{children:[U(`dt`,{children:`Repository`}),U(`dd`,{children:U(nu,{id:s.repository_id,kind:`repositories`,choices:r})})]}),U(`div`,{children:[U(`dt`,{children:`Read`}),U(`dd`,{children:s.policy?.read?`Allowed`:`Blocked`})]}),U(`div`,{children:[U(`dt`,{children:`Expires`}),U(`dd`,{children:U(Y,{value:s.expires_at,fallback:`No expiry`})})]})]}),t===`credentials`&&U(S,{children:[U(`div`,{children:[U(`dt`,{children:`HTTPS origin`}),U(`dd`,{children:s.origin})]}),U(`div`,{children:[U(`dt`,{children:`Header recipe`}),U(`dd`,{children:[s.recipe?.header,`: `,s.recipe?.prefix,`[secret]`]})]}),U(`div`,{children:[U(`dt`,{children:`Referencing repositories`}),U(`dd`,{children:s.referencing_repositories?.length?s.referencing_repositories.map(e=>U(`p`,{children:U(nu,{id:e.id,kind:`repositories`,choices:r})},e.id)):`None`})]})]})]}),t===`grants`&&(s.policy?.refs.length?U(`ul`,{children:s.policy?.refs.map(e=>U(`li`,{children:[U(`span`,{class:`technical-value`,children:e.ref.value}),` (`,e.ref.kind,`): `,e.actions.join(`, `)]},`${e.ref.kind}:${e.ref.value}`))}):U(`p`,{children:`No push permissions`})),U(`h3`,{children:`Metadata`}),U(`dl`,{class:`detail-facts`,children:U(`div`,{children:[U(`dt`,{children:`Revision`}),U(`dd`,{children:s.revision})]})})]}),U(ou,{...e,choices:r,resource:s,mode:`edit`,unavailable:c||l,acknowledgment:a,onAcknowledged:o}),t===`credentials`&&U(ou,{...e,choices:r,resource:s,mode:`rotate`,unavailable:c||l,acknowledgment:a,onAcknowledged:o}),U(ou,{...e,choices:r,resource:s,mode:`delete`,unavailable:c||l,acknowledgment:a})]}):U(K,{state:c?`error`:`loading`,title:c?`Git resource unavailable`:`Loading Git resource`})}function nu({id:e,kind:t,choices:n}){let r=n[t].find(t=>t.id===e)?.name;return U(q,{primary:U(`a`,{href:t===`agents`?`#/agents/${e}`:`#/git/${t}/${e}`,children:[r||(n.loading?`Loading relationship`:`Resource unavailable`),r&&n.error?` · Last known`:``]}),secondary:e})}function ru(e){let t=Cr(!1),{kind:n}=e,{items:r,controls:i}=Nr(e.session,e.resolved,e.view,(t,r,i)=>{let a=new URLSearchParams({limit:`50`,sort:t.sort??(n===`grants`?`description`:`name`),direction:t.direction??`ascending`});for(let e of n===`repositories`?[`name`,`destination`,`credential`]:n===`credentials`?[`name`,`origin`,`status`]:[`identity`,`repository`,`principal`,`state`]){let n=t[`filter_${e}`];n!==void 0&&a.set(e,n)}return r!==null&&a.set(`cursor`,r),Mr(e.session,`/api/v2/git/${n}?${a}`,e=>Nc(n,e),i)},t,{key:n===`grants`?`description`:`name`,direction:`ascending`});return U(`div`,{class:`domain-view`,children:[U(`div`,{class:`collection-toolbar`,children:U(`a`,{class:`button-link create-action`,href:`#/git/${n}/new`,children:[`Create `,Ql(n)]})}),U(`section`,{class:`panel domain-panel`,children:U(Dn,{caption:`Git ${n}`,rowHeaderKey:n===`grants`?`description`:`name`,remote:i,itemNames:{singular:Ql(n),plural:n},emptyTitle:`No Git ${n}`,items:r,rowKey:e=>e.id,filters:[{key:n===`grants`?`identity`:`name`,label:n===`grants`?`Description or ID`:`Name or ID`,type:`text`,value:e=>e.name??e.description??``,literalValues:e=>[e.id]},...n===`grants`?[{key:`repository`,label:`Repository`,type:`text`,value:t=>e.choices.repositories.find(e=>e.id===t.repository_id)?.name??``,literalValues:e=>[e.repository_id]},{key:`principal`,label:`Agent`,type:`text`,value:t=>e.choices.agents.find(e=>e.id===t.principal_id)?.name??``,literalValues:e=>[e.principal_id]},{key:`state`,label:`Status`,type:`select`,value:e=>e.state,options:[{value:`active`,label:`Active`},{value:`expired`,label:`Expired`}]}]:n===`repositories`?[{key:`destination`,label:`Destination`,type:`text`,value:e=>e.url,placeholder:`Literal destination substring`},{key:`credential`,label:`Git credential`,type:`text`,value:t=>e.choices.credentials.find(e=>e.id===t.credential_id)?.name??``,literalValues:e=>[e.credential_id??``]}]:[{key:`origin`,label:`HTTPS origin`,type:`text`,value:e=>e.origin,placeholder:`Destination`},{key:`status`,label:`Status`,type:`select`,value:e=>e.available?`configured`:`unavailable`,options:[{value:`configured`,label:`Configured`},{value:`unavailable`,label:`Unavailable`}]}]],additionalSorts:[{key:`id`,label:`ID`,sortValue:e=>e.id}],initialSort:{key:n===`grants`?`description`:`name`,direction:`ascending`},columns:[{key:n===`grants`?`description`:`name`,sortValue:e=>$l(e),label:n===`repositories`?`Repository`:n===`credentials`?`Credential`:`Grant`,role:`identity`,render:t=>U(q,{primary:U(`a`,{href:ln({...e.resolved.location,segments:[e.resolved.location.destination,t.id]}),children:$l(t)}),secondary:t.id})},{key:n===`grants`?`repository`:n===`credentials`?`origin`:`destination`,sortValue:t=>t.url??t.origin??e.choices.repositories.find(e=>e.id===t.repository_id)?.name??t.repository_id,label:n===`grants`?`Repository`:`Destination`,role:`relation`,render:t=>n===`grants`?U(nu,{id:t.repository_id,kind:`repositories`,choices:e.choices}):U(S,{children:[t.url??t.origin,n===`repositories`&&U(Zl,{source:e.coverage,destination:t.url})]})},...n===`grants`?[{key:`principal`,sortValue:t=>e.choices.agents.find(e=>e.id===t.principal_id)?.name??t.principal_id,label:`Agent`,role:`relation`,render:t=>U(nu,{id:t.principal_id,kind:`agents`,choices:e.choices})}]:[],{key:n===`repositories`?`credential`:n===`grants`?`state`:`status`,sortValue:t=>n===`repositories`?e.choices.credentials.find(e=>e.id===t.credential_id)?.name??t.credential_id??``:n===`grants`?t.state:t.available?`configured`:`unavailable`,label:n===`repositories`?`Git credential`:`Status`,role:n===`repositories`?`relation`:`status`,render:t=>n===`repositories`?t.credential_id?U(nu,{id:t.credential_id,kind:`credentials`,choices:e.choices}):`None`:U(G,{state:n===`credentials`?t.available?`current`:`warning`:t.state===`active`?`current`:`neutral`,children:n===`credentials`?t.available?`Configured`:`Unavailable`:t.state===`active`?`Active`:`Expired`})}]})})]})}function iu(e){return{name:e?.name??``,url:e?.url??``,aliases:e?.aliases??[],credential:e?.credential_id??``,principal:e?.principal_id??``,repository:e?.repository_id??``,description:e?.description??``,read:e?.policy?.read??!0,refs:e?.policy?.refs??[],expires:e?.expires_at??``,origin:e?.origin??``,header:e?.recipe?.header??`Authorization`,prefix:e?.recipe?.prefix??`Bearer `}}function au(e){return JSON.stringify({...e,url:Vl(e.url),aliases:e.aliases.map(Vl).sort(),origin:Vl(`${e.origin}/repository`).replace(/\/repository$/,``),header:e.header.toLowerCase(),refs:e.refs.map(e=>({...e,actions:[...e.actions].sort()})).sort((e,t)=>`${e.ref.kind}:${e.ref.value}`.localeCompare(`${t.ref.kind}:${t.ref.value}`))})}function ou({kind:e,choices:t,resource:n,mode:r,unavailable:i=!1,coverage:a,acknowledgment:o,onAcknowledged:s,...c}){let[l,u]=z(()=>iu(n)),[d,f]=z(()=>iu(n)),[p,m]=z(!1),h=r===`create`||r===`edit`,g=e===`credentials`&&(r===`create`||r===`rotate`),_=h&&au(d)!==au(l)||p,v=V(!1),[y,b]=z(n?Pc(e,n):null),[x,C]=z(!1),[w,T]=z(),[E]=z(()=>c.sinks.createWriteOnly()),[D]=z(()=>c.mutations.create()),[O,k]=z(()=>D.snapshot()),A=V(null),j=Cr(_),M=`git-secret-${r}`;B(()=>D.subscribe(k),[D]),B(()=>()=>{D.close(),E.close()},[D,E]);let N=n!==void 0&&y!==Pc(e,n),ee=V(),P=r===`delete`&&e===`credentials`&&(n?.referencing_repositories?.length??0)>0,te=P||i||N||O.state===`submitting`||O.state===`uncertain`||O.availability===`storage_latched`;B(()=>{if(!(!n||i||!o||o.to!==Pc(e,n)||ee.current===o.to)&&(ee.current=o.to,!_&&!x&&O.state===`editing`&&o.from===y)){b(o.to);let e=iu(n);u(e),f(e)}},[n,i,_,x,O.state,o,y,e]);let F=()=>{E.clear(),m(!1)},ne=r===`rotate`?`Rotate secret`:`${r===`create`?`Create Git`:r===`edit`?`Edit`:`Delete`} ${Ql(e)}`,I=(t,n)=>{t===`aliases`&&(v.current=!0),f(i=>{if(t===`url`&&e===`repositories`&&r===`create`&&!v.current){let e=Wl(String(n));return{...i,url:String(n),aliases:e?[e]:[]}}return{...i,[t]:n}})},re=(e,t,n=!0,i=!1,a,o)=>U(J,{id:`git-${e}-${r}`,label:t,...o===void 0?{}:{hint:o},children:t=>U(`input`,{...t,required:n,readOnly:i,placeholder:a,value:d[e],onInput:t=>I(e,t.currentTarget.value)})}),ie=()=>e===`repositories`?{name:d.name,url:d.url,aliases:d.aliases,credential_id:d.credential||null}:e===`credentials`?{name:d.name,origin:d.origin,recipe:{header:d.header,prefix:d.prefix}}:{principal_id:d.principal,repository_id:d.repository,description:d.description||null,policy:{version:1,read:d.read,refs:d.refs},expires_at:d.expires||null},ae=()=>{if(h){if(e!==`grants`&&(d.name.trim()===``||new TextEncoder().encode(d.name).length>256))return`Enter a name of at most 256 bytes.`;if(e===`repositories`&&(!d.url.startsWith(`https://`)||d.aliases.some(e=>!e.startsWith(`https://`))||d.credential!==``&&!Ec.test(d.credential)))return`Use HTTPS destinations and a valid optional Git credential ID.`;if(e===`repositories`&&!Gl(d.url,d.aliases))return`Aliases must be distinct from each other and the canonical destination.`;if(e===`grants`&&(!Ec.test(d.principal)||!Ec.test(d.repository)))return`Enter valid agent and repository IDs.`;if((e===`repositories`||e===`grants`&&r===`create`)&&(t.loading||t.error))return`Refresh resource choices before reviewing.`;if(e===`repositories`&&d.credential!==``&&!t.credentials.some(e=>e.id===d.credential&&Yl(e,d.url)))return`Select an available credential for this HTTPS origin, or choose None.`;if(e===`grants`&&r===`create`&&(!t.agents.some(e=>e.id===d.principal)||!t.repositories.some(e=>e.id===d.repository)))return`Select an existing agent and repository.`;if(e===`grants`&&d.refs.length>0&&!d.read)return`Push permissions require read access.`;if(e===`grants`&&d.refs.some(e=>!e.ref.value.startsWith(`refs/`)||e.actions.length===0))return`Each ref rule needs a refs/ selector and at least one operation.`}if(g){let e=document.getElementById(M);if(!(e instanceof HTMLInputElement)||!e.value||!/^[\x20-\x7e]+$/.test(e.value)||e.value.length+d.prefix.length>4096)return`Enter a nonempty printable secret; secret and prefix must fit 4096 characters.`}},oe=()=>{if(te||r===`edit`&&!_)return;let e=ae();T(e),e?F():C(!0)},se=()=>{if(C(!1),te){F(),T(`Current facts changed or are unavailable. Review them before confirming a new action.`);return}let t=ae();if(t){T(t),F();return}let i=document.getElementById(M),a=i instanceof HTMLInputElement?i.value:``,o=r===`rotate`?{secret:a}:r===`delete`?{}:g?{...ie(),secret:a}:ie();try{D.begin({route:`/api/v2/git/${e}${n?`/${n.id}`:``}${r===`rotate`?`/rotate`:``}`,method:r===`delete`?`DELETE`:r===`edit`?`PATCH`:`POST`,body:r===`delete`&&e!==`credentials`?null:JSON.stringify(o),precondition:y,requiresPrecondition:n!==void 0,idempotency:`none`,successStatuses:[r===`create`?201:r===`delete`?204:200],...g?{uncertainProblemCodes:[`keyring_unavailable`]}:{},decode:async t=>r===`delete`?null:Fc(e,t)});let t=D.submit();F(),t.then(t=>{if(t.kind===`acknowledged`){if(D.abandon(),r===`delete`)j(`#/git/${e}`,!0);else if(r===`create`&&t.value)j(`#/git/${e}/${t.value.id}`,!0);else{if(t.value){let n=Pc(e,t.value);y&&s?.({from:y,to:n}),b(n);let r=iu(t.value);u(r),f(r)}c.onRefresh()}}else(t.kind===`uncertain`||t.kind===`rejected`&&t.requiresRefresh)&&c.onRefresh()})}catch{F(),T(`Change could not be prepared. Refresh and review current metadata before making a new decision.`)}};return U(`section`,{class:`panel domain-panel`,children:[U(`div`,{class:`panel-heading`,children:U(`h2`,{children:r===`create`?`${e===`repositories`?`Repository`:e===`grants`?`Grant`:`Credential`} configuration`:ne})}),U(`form`,{onSubmit:e=>{e.preventDefault(),oe()},children:U(`fieldset`,{class:`git-mutation-fields`,disabled:O.state===`submitting`||O.state===`uncertain`,children:[h&&e!==`grants`&&re(`name`,`Name`,!0,!1,e===`repositories`?`Project repository`:`Project Git credential`),h&&e===`repositories`&&U(S,{children:[re(`url`,`Canonical HTTPS destination`,!0,n!==void 0,`https://git.example.com/team/project`),U(`section`,{class:`git-list-editor`,"aria-label":`Repository aliases`,children:[U(`h3`,{children:`Aliases`}),d.aliases.map((e,t)=>U(`div`,{class:`form-row`,children:[U(J,{id:`git-alias-${t}`,label:`Alias ${t+1}`,children:n=>U(`input`,{...n,required:!0,placeholder:`Same destination with .git added or removed`,value:e,onInput:e=>I(`aliases`,d.aliases.map((n,r)=>t===r?e.currentTarget.value:n))})}),U(`button`,{type:`button`,onClick:()=>I(`aliases`,d.aliases.filter((e,n)=>t!==n)),children:[`Remove alias `,t+1]})]},t)),U(`button`,{type:`button`,disabled:d.aliases.length>=4,onClick:()=>I(`aliases`,[...d.aliases,``]),children:`Add alias`})]}),U(J,{id:`git-credential-${r}`,label:`Git credential`,...d.credential?{hint:d.credential}:{},children:e=>U(`select`,{...e,value:d.credential,onChange:e=>I(`credential`,e.currentTarget.value),children:[U(`option`,{value:``,children:`None — public repository`}),d.credential&&!t.credentials.some(e=>e.id===d.credential&&Yl(e,d.url))&&U(`option`,{value:d.credential,disabled:!0,children:[t.credentials.find(e=>e.id===d.credential)?.name||d.credential,` `,`· Unavailable or incompatible`]}),t.credentials.filter(e=>Yl(e,d.url)).map(e=>U(`option`,{value:e.id,children:Jl(e,t.credentials)},e.id))]})})]}),h&&e===`credentials`&&U(S,{children:[re(`origin`,`HTTPS origin`,!0,!1,`https://git.example.com`),re(`header`,`Header name`,!0,!1,`Authorization`),re(`prefix`,`Fixed prefix (optional)`,!1,!1,`Bearer `,`Include any space needed between the prefix and secret. Leave blank for no prefix.`)]}),h&&e===`grants`&&U(S,{children:[[`principal`,`repository`].map(e=>{let i=e===`principal`?t.agents:t.repositories,a=e===`principal`?`Agent`:`Repository`;return U(J,{id:`git-${e}-${r}`,label:a,...d[e]?{hint:d[e]}:{},children:r=>n===void 0?U(`select`,{...r,required:!0,disabled:t.loading||t.error,value:d[e],onChange:t=>I(e,t.currentTarget.value),children:[U(`option`,{value:``,children:t.loading?`Loading ${a.toLowerCase()}s`:t.error?`${a} choices unavailable`:i.length?`Select ${a.toLowerCase()}`:`No ${a.toLowerCase()}s configured`}),d[e]&&!i.some(t=>t.id===d[e])&&U(`option`,{value:d[e],children:[d[e],` · Unavailable`]}),i.map(e=>U(`option`,{value:e.id,children:Jl(e,i)},e.id))]}):U(`input`,{...r,readOnly:!0,value:i.find(t=>t.id===d[e])?.name??d[e]})})}),re(`description`,`Description (optional)`,!1,!1,`Project repository access policy`),U(J,{id:`git-read-${r}`,label:`Read repository`,children:e=>U(On,{attributes:e,checked:d.read,onChange:e=>{I(`read`,e),e||I(`refs`,[])}})}),U(`section`,{class:`git-list-editor`,"aria-label":`Push permissions`,children:[U(`h3`,{children:`Push permissions`}),d.refs.map((e,t)=>U(`fieldset`,{children:[U(`legend`,{children:[`Ref rule `,t+1]}),U(J,{id:`git-rule-kind-${t}`,label:`Match`,children:n=>U(`select`,{...n,value:e.ref.kind,onChange:e=>I(`refs`,d.refs.map((n,r)=>t===r?{...n,ref:{...n.ref,kind:e.currentTarget.value}}:n)),children:[U(`option`,{value:`exact`,children:`Exact ref`}),U(`option`,{value:`prefix`,children:`Namespace prefix ending in /`})]})}),U(J,{id:`git-rule-ref-${t}`,label:`Ref selector`,children:n=>U(`input`,{...n,required:!0,placeholder:e.ref.kind===`exact`?`refs/heads/main`:`refs/heads/`,value:e.ref.value,onInput:e=>I(`refs`,d.refs.map((n,r)=>t===r?{...n,ref:{...n.ref,value:e.currentTarget.value}}:n))})}),U(`div`,{class:`push-permissions-row`,children:[`create`,`update`,`delete`].map(n=>U(J,{id:`git-rule-${t}-${n}`,label:n[0].toUpperCase()+n.slice(1),children:r=>U(On,{attributes:r,checked:e.actions.includes(n),onChange:e=>I(`refs`,d.refs.map((r,i)=>t===i?{...r,actions:e?[...r.actions,n]:r.actions.filter(e=>e!==n)}:r))})}))}),U(`button`,{type:`button`,onClick:()=>I(`refs`,d.refs.filter((e,n)=>t!==n)),children:[`Remove ref rule `,t+1]})]},t)),U(`button`,{type:`button`,disabled:d.refs.length>=128,onClick:()=>{I(`read`,!0),I(`refs`,[...d.refs,{ref:{kind:`exact`,value:``},actions:[`update`]}])},children:`Add push rule`})]}),U(J,{id:`git-expires-${r}`,label:`Expiry (optional)`,children:e=>U(`input`,{...e,type:`datetime-local`,value:d.expires?su(d.expires):``,onInput:e=>I(`expires`,Ul(e.currentTarget.value,l.expires)??``)})})]}),g&&U(Ni,{id:M,value:E,label:`Secret`,placeholder:`Enter secret value`,hint:`Write-only. Cleared on submission or cancellation.`,onInput:e=>m(e.length>0)}),h&&(e===`repositories`||e===`grants`)&&t.error&&U(K,{state:`error`,title:`Resource choices unavailable`,children:`Refresh to load choices. Your draft is retained.`}),w&&U(K,{state:`error`,title:`Check Git configuration`,children:U(`p`,{children:[w,g?` Enter the secret again; it was cleared.`:``]})}),N&&U(K,{state:`warning`,title:`Revision changed`,children:[U(`p`,{children:`This resource changed since this form was prepared. Compare the current facts above with your draft. Use reviewed revision keeps your draft and uses that revision for your next confirmation; it does not save, rotate, delete, or retry anything.`}),U(`button`,{type:`button`,disabled:i||O.state===`uncertain`,onClick:()=>{b(Pc(e,n)),u(iu(n)),D.abandon()},children:`Use reviewed revision`})]}),O.problem&&U(K,{state:`error`,title:O.problem.title}),O.state===`uncertain`&&U(K,{state:`warning`,title:`Change outcome unknown`,children:`Inspect current metadata before deciding on another operation. No automatic retry.`}),P&&U(K,{state:`warning`,title:`Credential is referenced`,children:[U(`p`,{children:`Remove credential references from repositories before deleting this credential. Deleted repositories retain their references; deleting a repository does not release them.`}),U(`ul`,{children:n?.referencing_repositories?.map(e=>U(`li`,{children:U(nu,{id:e.id,kind:`repositories`,choices:t})},e.id))})]}),U(`div`,{class:`form-actions`,children:[_&&U(`button`,{type:`button`,disabled:i||O.state===`submitting`||O.state===`uncertain`,onClick:()=>{let t=iu(n);f(t),u(t),b(n?Pc(e,n):null),F(),T(void 0),D.abandon()},children:`Discard changes`}),U(`button`,{ref:A,type:`submit`,class:`${r===`delete`?`danger-action`:r===`create`?`create-action`:r===`edit`?`primary-action`:``} form-submit-action`,disabled:te||r===`edit`&&!_,children:r===`create`?`Review and create`:r===`edit`?`Review changes`:r===`rotate`?`Review rotation`:`Review deletion`})]})]})}),U(jn,{id:`git-confirm-${e}-${r}`,open:x,title:ne,consequence:r===`delete`?`Retire this resource. Referenced resources cannot be deleted; historical traffic is unchanged.`:r===`rotate`?`Replace protected material. A failed cutover can leave the credential unavailable; there is no fallback to the old secret.`:U(`div`,{class:`confirmation-details`,children:[U(`dl`,{class:`detail-facts`,children:[e!==`grants`&&U(`div`,{children:[U(`dt`,{children:`Name`}),U(`dd`,{children:d.name})]}),e===`repositories`&&U(S,{children:[U(`div`,{children:[U(`dt`,{children:`Immutable destination`}),U(`dd`,{children:[d.url,a&&U(Zl,{source:a,destination:d.url,contextual:!0})]})]}),U(`div`,{children:[U(`dt`,{children:`Aliases`}),U(`dd`,{children:d.aliases.length?d.aliases.join(`, `):`None`})]}),U(`div`,{children:[U(`dt`,{children:`Git credential`}),U(`dd`,{children:d.credential?U(nu,{id:d.credential,kind:`credentials`,choices:t}):`None — public repository`})]})]}),e===`credentials`&&U(S,{children:[U(`div`,{children:[U(`dt`,{children:`HTTPS origin`}),U(`dd`,{children:d.origin})]}),U(`div`,{children:[U(`dt`,{children:`Header recipe`}),U(`dd`,{children:[d.header,`: `,d.prefix,`[secret]`]})]})]}),e===`grants`&&U(S,{children:[U(`div`,{children:[U(`dt`,{children:`Agent`}),U(`dd`,{children:U(nu,{id:d.principal,kind:`agents`,choices:t})})]}),U(`div`,{children:[U(`dt`,{children:`Repository`}),U(`dd`,{children:U(nu,{id:d.repository,kind:`repositories`,choices:t})})]}),U(`div`,{children:[U(`dt`,{children:`Read repository`}),U(`dd`,{children:d.read?`Allowed`:`Blocked`})]}),U(`div`,{children:[U(`dt`,{children:`Expiry`}),U(`dd`,{children:U(Y,{value:d.expires||null,fallback:`No expiry`})})]})]})]}),e===`grants`&&U(`ul`,{children:d.refs.map((e,t)=>U(`li`,{children:[e.ref.kind,`:`,` `,U(`span`,{class:`technical-value`,children:e.ref.value}),` —`,` `,e.actions.join(`, `)]},t))})]}),confirmLabel:ne,destructive:r!==`create`,returnFocus:A,onCancel:()=>{C(!1),F()},onConfirm:se})]})}function su(e){let t=new Date(e);if(!Number.isFinite(t.getTime()))return``;let n=e=>String(e).padStart(2,`0`);return`${t.getFullYear()}-${n(t.getMonth()+1)}-${n(t.getDate())}T${n(t.getHours())}:${n(t.getMinutes())}`}function cu(e){let t=e.resolved.location.segments[1],n=ql(e.session,e.view.generation,`traffic`),{value:r,error:i}=eu(e,t?`/api/v2/git/traffic/${t}`:void 0,async e=>{if(e.headers.get(`Content-Type`)!==`application/json`)throw Error(`Unavailable`);let n=await e.text();if(n.length>16384)throw Error(`Unavailable`);let r=Rc(JSON.parse(n));if(r.admission.id!==t)throw Error(`Unavailable`);return r});if(!t)return U(uu,{...e,repositories:n});if(!r)return U(K,{state:i?`error`:`loading`,title:i?`Git traffic unavailable`:`Loading Git traffic`});let a=r.admission,o=r.completion,s=Hc(r);return U(`div`,{class:`domain-view`,children:[U(`nav`,{class:`detail-navigation`,"aria-label":`Git traffic navigation`,children:U(`a`,{href:ln({...e.resolved.location,segments:[`git-traffic`]}),children:`Back to Git traffic`})}),U(`header`,{class:`detail-context`,"data-testid":`detail-context`,children:[U(`div`,{class:`detail-context-heading`,children:[U(`h1`,{tabindex:-1,children:[zc[a.operation],a.policy?.repository_name?` — ${a.policy.repository_name}`:``]}),U(G,{state:i?`stale`:a.allowed?[`HTTP success`,`Reported success`].includes(Vc(r))?`current`:`warning`:`neutral`,children:Vc(r)})]}),U(`p`,{class:`technical-value`,children:a.id})]}),i&&U(K,{state:`warning`,title:`Git traffic refresh unavailable`}),U(`section`,{class:`detail-section`,children:[U(`h2`,{children:`Recorded exchange`}),U(`dl`,{class:`detail-facts`,children:[U(`div`,{children:[U(`dt`,{children:`Admitted`}),U(`dd`,{children:U(Y,{value:a.admitted_at})})]}),U(`div`,{children:[U(`dt`,{children:`Repository`}),U(`dd`,{children:U(lu,{item:r,choices:n})})]}),a.policy&&U(`div`,{children:[U(`dt`,{children:`Canonical destination at admission`}),U(`dd`,{children:a.policy.repository_url})]}),U(`div`,{children:[U(`dt`,{children:`Operation`}),U(`dd`,{children:zc[a.operation]})]}),U(`div`,{children:[U(`dt`,{children:`Admission`}),U(`dd`,{children:s.admission})]}),U(`div`,{children:[U(`dt`,{children:`Transport`}),U(`dd`,{children:s.transport})]}),U(`div`,{children:[U(`dt`,{children:`Upstream report`}),U(`dd`,{children:s.report})]}),U(`div`,{children:[U(`dt`,{children:`Command count`}),U(`dd`,{children:a.commands})]}),a.policy&&U(`div`,{children:[U(`dt`,{children:`Create / update / delete commands`}),U(`dd`,{children:[a.policy.creates,` / `,a.policy.updates,` / `,a.policy.deletes]})]}),o&&U(S,{children:[U(`div`,{children:[U(`dt`,{children:`HTTP status`}),U(`dd`,{children:o.status??`None`})]}),U(`div`,{children:[U(`dt`,{children:`Bytes sent / received`}),U(`dd`,{children:[o.bytes_sent,` / `,o.bytes_received]})]})]})]}),a.operation===`push`?U(`p`,{children:`Upstream reports are not independently verified repository effects. Reconcile an uncertain push with the remote before deciding on another operation.`}):U(`p`,{children:`Transport completion does not prove a valid local checkout. Discovery and probes are not completed pushes.`}),a.operation===`push`&&U(`section`,{"aria-label":`Targeted refs`,children:[U(`h2`,{children:`Targeted refs`}),a.ref_evidence?U(S,{children:[U(`p`,{children:[a.ref_evidence.refs.length,` of `,a.commands,` requested refs retained`,a.ref_evidence.state===`truncated`?`; truncated — omitted refs and their outcomes are unavailable.`:`.`]}),U(`div`,{class:`table-region table-resource`,role:`region`,"aria-label":`Targeted ref evidence`,tabindex:0,children:U(`table`,{children:[U(`caption`,{children:`Requested operations and upstream claims`}),U(`thead`,{children:U(`tr`,{children:[U(`th`,{scope:`col`,children:`Ref`}),U(`th`,{scope:`col`,children:`Requested action`}),U(`th`,{scope:`col`,children:`Upstream outcome`})]})}),U(`tbody`,{children:a.ref_evidence.refs.map((e,t)=>U(`tr`,{children:[U(`th`,{scope:`row`,"data-label":`Ref`,children:U(`span`,{class:`technical-value`,children:e.name})}),U(`td`,{"data-label":`Requested action`,children:W(e.action)}),U(`td`,{"data-label":`Upstream outcome`,children:a.allowed?o?.ref_outcomes?.[t]===`ok`?`Reported success`:o?.ref_outcomes?.[t]===`ng`?`Reported failure`:`Unknown`:`Not dispatched`})]},e.name))})]})})]}):U(`p`,{children:`Ref evidence unavailable (legacy record).`})]}),U(`details`,{children:[U(`summary`,{children:`Admission-time policy references`}),U(`dl`,{class:`detail-facts`,children:[U(`div`,{children:[U(`dt`,{children:`Repository`}),U(`dd`,{children:[a.repository.id||`Unavailable`,` · revision`,` `,a.repository.revision||`Unavailable`]})]}),U(`div`,{children:[U(`dt`,{children:`Agent`}),U(`dd`,{children:[a.principal.id,` · revision `,a.principal.revision]})]}),U(`div`,{children:[U(`dt`,{children:`Authorization revision`}),U(`dd`,{children:a.authorization_revision})]}),U(`div`,{children:[U(`dt`,{children:`Alias revision`}),U(`dd`,{children:a.alias_revision||`Unavailable`})]}),U(`div`,{children:[U(`dt`,{children:`Routing profile revision`}),U(`dd`,{children:a.profile_revision})]}),U(`div`,{children:[U(`dt`,{children:`Agent credential`}),U(`dd`,{children:[a.agent_credential.id,` · revision `,a.agent_credential.revision]})]}),a.material&&U(`div`,{children:[U(`dt`,{children:`Git credential at admission`}),U(`dd`,{children:[a.material.credential.id,` · revision`,` `,a.material.credential.revision,` · generation`,` `,a.material.generation]})]}),a.private_grant&&U(`div`,{children:[U(`dt`,{children:`Private destination permission`}),U(`dd`,{children:[a.private_grant.id,` · revision `,a.private_grant.revision]})]})]}),a.policy&&U(S,{children:[U(`p`,{children:[a.policy.grants.length,` of `,a.policy.grant_count,` applicable grant references retained`]}),U(`ul`,{children:a.policy.grants.map(e=>U(`li`,{children:[e.id,` · revision `,e.revision]},e.id))})]})]})]})]})}function lu({item:e,choices:t}){let n=e.admission.repository.id,r=e.admission.policy?.repository_name||n||`Unavailable`;return U(q,{primary:!t.loading&&!t.error&&t.repositories.some(e=>e.id===n)?U(`a`,{href:`#/git/repositories/${n}`,children:r}):r,secondary:n||void 0})}function uu(e){let t=Cr(!1),[n,r]=z(e.controller.snapshot());B(()=>e.controller.subscribe(r),[e.controller]);let i=e.resolved.location.query,[a,o]=z({...i}),[s,c]=z(!1),l=e=>{let n=Object.fromEntries(Object.entries(e).filter(([,e])=>e!==``));if(!Ve(n)){c(!0);return}c(!1),JSON.stringify(n)!==JSON.stringify(i)&&t(ln({destination:`git-traffic`,segments:[`git-traffic`],query:n}))};mn(a,l);let u=n.key===e.view.viewKey?n.items:[],d=e.view.panels[`git-traffic`]?.refreshing===!0,f=n.error||e.view.panels[`git-traffic`]?.status===`error`;return U(`section`,{class:`panel domain-panel`,children:[U(`div`,{class:`collection-toolbar live-collection-toolbar`,children:[U(`label`,{for:`git-traffic-live-mode`,children:`Live mode`}),U(On,{attributes:{id:`git-traffic-live-mode`},checked:n.live,showState:!1,onChange:t=>e.controller.setLive(t)})]}),U(Wn,{query:i}),U(`div`,{class:`table-filters collection-query-filters`,role:`group`,"aria-label":`Git traffic filters`,children:[Object.entries(Be).map(([e,t])=>U(S,{children:[e===`admission`&&U(`input`,{type:`search`,"aria-label":`Repo name or ID`,placeholder:`Repo name or ID`,value:a.filter_repository??``,onInput:e=>o({...a,filter_repository:e.currentTarget.value})}),U(`select`,{"aria-label":e===`report`?`Upstream report`:W(e),value:a[`filter_${e}`]??``,onChange:t=>{let n={...a,[`filter_${e}`]:t.currentTarget.value};o(n),l(n)},children:[U(`option`,{value:``,children:[e===`report`?`Upstream report`:W(e),`: any`]}),t.map(e=>U(`option`,{value:e,children:zc[e]??W(e)}))]})]})),U(`button`,{type:`button`,disabled:!Object.values(a).some(Boolean)&&!Object.values(i).some(Boolean),onClick:()=>{o({}),l({})},children:`Reset`})]}),s&&U(K,{state:`error`,title:`Invalid repository search`}),n.paused&&U(`div`,{class:`inline-actions`,children:[n.live&&U(G,{state:`warning`,children:`Live paused while viewing older results`}),U(`button`,{type:`button`,onClick:()=>e.controller.resume(),children:n.live?`Resume live`:`Return to newest`})]}),n.notice&&U(K,{state:`warning`,title:n.notice}),n.olderError&&U(K,{state:`error`,title:`Older exchanges unavailable`,children:`Loaded exchanges are unchanged. Try Load older exchanges again.`}),f&&U(K,{state:`error`,title:`Git traffic unavailable`,children:`Previously loaded exchanges may be stale.`}),!n.loaded&&!f&&U(K,{state:`loading`,title:`Loading Git traffic`}),U(Dn,{caption:`Git traffic`,rowHeaderKey:`exchange`,layout:`activity`,localStale:f,localLoading:!n.loaded&&!f,historySummary:!0,historyMatching:Object.keys(i).length>0,summaryExtra:n.loaded&&!f?U(`span`,{children:n.next===null?`No older exchanges`:u.length>=500?`Load limit reached. Narrow the filters or return to newest.`:``}):void 0,hasMore:n.next!==null&&u.length<500&&!f,loadingMore:d||n.loadingOlder,loadMoreLabel:`Load older exchanges`,onLoadMore:()=>void e.controller.older(),itemNames:{singular:`exchange`,plural:`exchanges`},emptyTitle:`No Git traffic`,items:u,rowKey:e=>e.admission.id,filters:[],columns:[{key:`admitted`,label:`Admitted`,role:`time`,render:e=>U(Y,{value:e.admission.admitted_at})},{key:`exchange`,label:`Operation`,role:`identity`,render:t=>U(q,{primary:U(`a`,{href:ln({...e.resolved.location,segments:[`git-traffic`,t.admission.id]}),children:zc[t.admission.operation]}),secondary:t.admission.id})},{key:`repository`,label:`Repository`,role:`relation`,render:t=>U(lu,{item:t,choices:e.repositories})},{key:`outcome`,label:`Outcome`,role:`status`,render:e=>U(G,{state:[`HTTP success`,`Reported success`].includes(Vc(e))?`current`:`warning`,children:Vc(e)})},{key:`admission`,label:`Admission`,role:`status`,render:e=>U(G,{state:`neutral`,children:Hc(e).admission})},{key:`transport`,label:`Transport`,role:`status`,render:e=>Hc(e).transport},{key:`report`,label:`Upstream report`,role:`status`,render:e=>Hc(e).report}]})]})}var du=`Showing the latest entries. Older results could not be continued.`,fu=()=>({key:``,items:[],next:null,live:!0,paused:!1,loaded:!1,error:!1,olderError:!1,loadingOlder:!1,notice:``}),pu=class{value=fu();serial=0;olderPosition=!1;continuation=null;listeners=new Set;views;constructor(e,t){this.views=t,t.registerPanel({id:`git-traffic`,matches:e=>{let t=H(e);return t?.destination===`git-traffic`&&t.segments.length===1},invalidations:[`system_status`],shouldRefresh:e=>![`invalidation`,`reconnect`,`poll`].includes(e)||this.value.live&&!this.value.paused,read:e=>this.read(e),publish:e=>{e.serial===this.serial&&(this.value=e.value,this.emit())}}),e.registerProtectedState(()=>{this.serial++,this.olderPosition=!1,this.continuation=null,this.value=fu(),this.emit()})}snapshot(){return this.value}subscribe(e){return this.listeners.add(e),e(this.value),()=>{this.listeners.delete(e)}}emit(){for(let e of this.listeners)e(this.value)}setLive(e){this.views.cancelPanelRead(`git-traffic`),this.serial++,this.value={...this.value,live:e,loadingOlder:!1},this.continuation=null,this.emit(),(!this.value.loaded||e&&!this.value.paused)&&this.resume()}resume(){this.serial++,this.olderPosition=!1,this.continuation=null,this.value={...this.value,paused:!1,loadingOlder:!1,notice:``},this.emit(),this.views.refreshPanel(`git-traffic`)}async older(){this.value.error||this.value.loadingOlder||this.value.next===null||this.value.items.length>=500||this.value.key!==this.views.snapshot().viewKey||this.views.snapshot().panels[`git-traffic`]?.refreshing||(this.continuation=this.value.next,this.value={...this.value,paused:!0,loadingOlder:!0,olderError:!1},this.emit(),await this.views.refreshPanel(`git-traffic`))}async read(e){let t=H(e.viewKey);this.value.key!==e.viewKey&&(this.serial++,this.continuation=null,this.value={...fu(),key:e.viewKey,live:this.value.live,paused:this.value.paused},this.emit());let n=this.serial,r=this.value,i=e.reason===`panel`?this.continuation:null;this.continuation=null;let a=()=>!e.signal.aborted&&n===this.serial&&e.viewKey===this.views.snapshot().viewKey,o=async n=>{let r=new URLSearchParams({limit:`50`});for(let[e,n]of Object.entries(t.query))r.set(e.slice(7),n);t.query.filter_repository&&r.set(`search_locale`,Intl.DateTimeFormat().resolvedOptions().locale),n&&r.set(`cursor`,n);let i=await fetch(`/api/v2/git/traffic?${r}`,{credentials:`same-origin`,redirect:`error`,signal:e.signal,headers:{Accept:`application/json`,"X-CSRF-Token":e.csrfToken}});if(await e.sessionLost(i)||!a())throw Error(`Superseded`);let o=await i.text();if(o.length>1048576||!a())throw Error(`Unavailable`);let s=JSON.parse(o);if(i.status===409&&i.headers.get(`Content-Type`)===`application/problem+json`&&Bn(s)?.code===`stale_cursor`)return null;if(!i.ok||i.headers.get(`Content-Type`)!==`application/json`)throw Error(`Unavailable`);return Lc(s)},s=i!==null,c=!s&&this.olderPosition?du:r.notice;try{let e=await o(i);if(e===null&&s&&(s=!1,c=du+` Git history changed; previous results were discarded.`,this.olderPosition=!1,this.value={...r,items:[],next:null,loaded:!1,notice:c},this.emit(),e=await o(null)),e===null||!a())throw Error(`Unavailable`);if(s&&(r.items.length+e.items.length>500||e.items.some(e=>r.items.some(t=>t.admission.id===e.admission.id))))throw Error(`Repeated evidence`);return this.olderPosition=s,{serial:n,value:{...this.value,items:s?[...r.items,...e.items]:e.items,next:e.nextCursor,loaded:!0,error:!1,olderError:!1,loadingOlder:!1,notice:c}}}catch(e){if(!a())throw e;return{serial:n,value:{...this.value,error:!s,olderError:s,loadingOlder:!1}}}}},mu=`/api/v2/git/routing-profile`;function hu({values:e}){return e.length?U(`ul`,{children:e.map(e=>U(`li`,{class:`technical-value`,children:e},e))}):U(`span`,{children:`No origins enabled`})}function gu(e){let[t,n]=z(),[r,i]=z(!0),[a,o]=z(!1),s=V(0);return B(()=>{let t=++s.current;return i(!0),e.session.runProtected(async e=>{let r=await fetch(mu,{credentials:`same-origin`,redirect:`error`,signal:e.signal,headers:{Accept:`application/json`,"X-CSRF-Token":e.csrfToken}});if(await e.sessionLost(r))return;if(!r.ok)throw Error(`Read unavailable`);let i=await Jc(r);t===s.current&&(n(i),o(!1))}).catch(()=>{t===s.current&&o(!0)}).finally(()=>{t===s.current&&i(!1)}),()=>{s.current++}},[e.session,e.view.generation]),t?U(`div`,{class:`domain-view`,children:[a&&U(K,{state:`error`,title:`Git routing refresh unavailable`,children:`Saved facts may be stale. Refresh before making changes.`}),U(`section`,{class:`detail-section`,"aria-labelledby":`git-routing-details`,children:[U(`h2`,{id:`git-routing-details`,children:`Routing profile`}),U(`dl`,{class:`detail-facts`,children:[U(`div`,{children:[U(`dt`,{children:`Enforcement`}),U(`dd`,{children:U(G,{state:a?`stale`:t.active?`current`:`neutral`,children:[a?`Last known: `:``,t.active?`Active`:`Inactive`]})})]}),U(`div`,{children:[U(`dt`,{children:`Enabled origins`}),U(`dd`,{children:U(hu,{values:t.origins})})]}),U(`div`,{children:[U(`dt`,{children:`Revision`}),U(`dd`,{children:t.revision})]})]})]}),U(_u,{...e,profile:t,unavailable:r||a,onSaved:t=>{s.current++,n(t),o(!1),e.onRefresh()}})]}):U(K,{state:a?`error`:`loading`,title:a?`Git routing unavailable`:`Loading Git routing`,children:a&&`Refresh to load the routing profile.`})}function _u({profile:e,unavailable:t,onSaved:n,...r}){let[i,a]=z(e.origins),[o,s]=z(qc(e)),[c,l]=z(e.origins),u=(()=>{try{return JSON.stringify(Gc(i))!==JSON.stringify(Gc(c))}catch{return!0}})(),[d,f]=z(),[p,m]=z(),[h,g]=z(!1),[_]=z(()=>r.mutations.create()),[v,y]=z(()=>_.snapshot()),b=V(null);Cr(u),B(()=>_.subscribe(y),[_]),B(()=>()=>_.close(),[_]);let x=o!==qc(e)||v.requiresRefresh,C=v.state===`submitting`||v.state===`uncertain`,w=t||x||C||v.availability===`storage_latched`,T=e=>{a(e),g(!1),m(void 0)},E=()=>{if(!(w||!u))try{f(Gc(i)),m(void 0)}catch(e){m(e instanceof Error?e.message:`Check HTTPS origins.`)}};return U(`section`,{class:`panel domain-panel`,children:[U(`div`,{class:`panel-heading`,children:U(`h2`,{children:`Edit routing`})}),U(`p`,{children:`Enabled origins use Git repository permissions and credentials for smart HTTPS Git requests. Other origins remain under HTTP policy.`}),h&&U(`p`,{role:`status`,children:`Routing saved`}),U(`form`,{onSubmit:e=>{e.preventDefault(),E()},children:U(`fieldset`,{class:`git-mutation-fields`,disabled:C,children:[U(`div`,{class:`git-list-editor`,children:[U(`h3`,{children:`HTTPS origins`}),i.length===0&&U(`p`,{children:`No origins enabled`}),i.map((e,t)=>U(`div`,{class:`form-row`,children:[U(J,{id:`git-routing-origin-${t}`,label:`Origin ${t+1}`,children:n=>U(`input`,{...n,required:!0,value:e,placeholder:`https://github.com`,onInput:e=>T(i.map((n,r)=>r===t?e.currentTarget.value:n))})}),U(`button`,{type:`button`,"aria-label":`Remove origin ${t+1}`,onClick:()=>T(i.filter((e,n)=>n!==t)),children:`Remove`})]},t)),U(`button`,{type:`button`,disabled:i.length>=256,onClick:()=>T([...i,``]),children:`Add origin`})]}),p&&U(K,{state:`error`,title:`Check HTTPS origins`,children:p}),x&&U(K,{state:`warning`,title:`Review current revision`,children:[U(`p`,{children:`Compare the saved origins above with your retained draft before continuing.`}),U(`button`,{type:`button`,disabled:t||C,onClick:()=>{s(qc(e)),l(e.origins),_.abandon()},children:`Use reviewed revision`})]}),v.problem&&U(K,{state:`error`,title:v.problem.title}),v.state===`uncertain`&&U(K,{state:`warning`,title:`Change outcome unknown`,children:`Inspect current routing before deciding on another operation. No automatic retry.`}),v.availability===`storage_latched`&&U(K,{state:`warning`,title:`Changes unavailable`,children:`Gateway storage is latched.`}),U(`div`,{class:`form-actions`,children:U(`button`,{ref:b,type:`submit`,class:`primary-action form-submit-action`,disabled:w||!u,children:`Review changes`})})]})}),U(jn,{id:`git-routing-confirm`,open:d!==void 0,title:`Update Git routing`,confirmLabel:`Save routing`,returnFocus:b,onCancel:()=>f(void 0),onConfirm:()=>{let e=d;if(f(void 0),!(!e||w))try{_.begin({route:mu,method:`PATCH`,body:JSON.stringify({origins:e}),precondition:o,requiresPrecondition:!0,idempotency:`none`,successStatuses:[200],decode:Jc}),_.submit().then(e=>{e.kind===`acknowledged`?(a(e.value.origins),s(qc(e.value)),l(e.value.origins),g(!0),_.abandon(),n(e.value)):(e.kind===`uncertain`||e.kind===`rejected`&&e.requiresRefresh)&&r.onRefresh()})}catch{m(`Refresh and review the current routing profile before making a new decision.`)}},consequence:U(S,{children:[U(xn,{label:`Routing changes`,beforeLabel:`Current`,afterLabel:`Proposed`,rows:[{label:`Enabled origins`,before:U(hu,{values:e.origins}),after:U(hu,{values:d??[]}),changed:JSON.stringify(e.origins)!==JSON.stringify(d)}]}),U(`p`,{children:`This replaces the enabled-origin list for subsequent requests. Enabled origins refuse opaque tunnels; repository grants are still required. Removing an origin returns it to HTTP policy.`}),w&&U(K,{state:`warning`,title:`Refresh and review before saving`})]})})]})}var vu=/^[0-7][0-9A-HJKMNP-TV-Z]{25}$/;function yu(e,t){if(typeof e!=`object`||!e||Array.isArray(e)||Object.keys(e).sort().join()!==t.sort().join())throw Error(`HTTP credential data is unavailable.`);return e}function bu(e){let t=yu(e,[`id`,`name`,`boundary`,`recipe`,`revision`,`available`,`referencing_grants`,`created_at`,`updated_at`]),n=yu(t.boundary,[`host`,`port`,`allow_wildcard`]),r=yu(t.recipe,[`header`,`prefix`]);if(typeof t.id!=`string`||!vu.test(t.id)||typeof t.name!=`string`||t.name.length===0||new TextEncoder().encode(t.name).length>256||typeof t.revision!=`string`||!/^[1-9][0-9]*$/.test(t.revision)||typeof t.available!=`boolean`||typeof n.host!=`string`||n.host.length===0||n.host.length>255||typeof n.port!=`number`||!Number.isInteger(n.port)||n.port<1||n.port>65535||typeof n.allow_wildcard!=`boolean`||typeof r.header!=`string`||!/^[!#$%&'*+.^_`|~0-9A-Za-z-]{1,128}$/.test(r.header)||typeof r.prefix!=`string`||!/^[\x20-\x7e]{0,128}$/.test(r.prefix)||!Array.isArray(t.referencing_grants)||t.referencing_grants.length>4096||typeof t.created_at!=`string`||!Number.isFinite(Date.parse(t.created_at))||typeof t.updated_at!=`string`||!Number.isFinite(Date.parse(t.updated_at)))throw Error(`HTTP credential data is unavailable.`);for(let e of t.referencing_grants){let t=yu(e,[`id`]);if(typeof t.id!=`string`||!vu.test(t.id))throw Error(`Invalid credential reference.`)}return e}async function xu(e){if(e.headers.get(`Content-Type`)!==`application/json`)throw Error(`HTTP credential data is unavailable.`);let t=await e.text();if(t.length>1048576)throw Error(`HTTP credential data is unavailable.`);let n=bu(JSON.parse(t));if(e.headers.get(`ETag`)!==Su(n))throw Error(`HTTP credential revision is unavailable.`);return n}function Su(e){return`"http-credential-${e.id}-${e.revision}"`}function Cu(e){let t=e.resolved.location.segments[1],[n,r]=z(),[i,a]=z(),[o,s]=z(!1),[c,l]=z(!1);return B(()=>{let n=!0;if(s(!1),l(!0),t!==void 0&&t!==`new`)return r(e=>e?.id===t?e:void 0),e.session.runProtected(async e=>{let i=await fetch(`/api/v2/http/credentials/${t}`,{credentials:`same-origin`,redirect:`error`,signal:e.signal,headers:{Accept:`application/json`,"X-CSRF-Token":e.csrfToken}});if(await e.sessionLost(i))return;if(!i.ok)throw Error(`HTTP credential data is unavailable.`);let a=await xu(i);if(a.id!==t)throw Error(`Invalid credential identity.`);n&&r(a)}).catch(()=>{n&&s(!0)}).finally(()=>{n&&l(!1)}),()=>{n=!1}},[t,e.view.generation]),t===void 0?U(wu,{...e}):t===`new`?U(Tu,{...e,mode:`create`}):o&&n?.id!==t?U(K,{state:`error`,title:`HTTP credential data unavailable`,children:U(`p`,{children:`Refresh to load the credential.`})}):n?.id===t?U(`div`,{class:`domain-view`,children:[o&&U(K,{state:`error`,title:`Current HTTP credential data unavailable`,children:U(`p`,{children:`Your safe draft is preserved. Refresh before reviewing the current revision.`})}),U(`nav`,{class:`detail-navigation`,"aria-label":`HTTP credential navigation`,children:U(`a`,{href:ln({destination:`http-credentials`,segments:[`http-credentials`],query:e.resolved.location.query}),children:`Back to HTTP credentials`})}),U(`header`,{class:`detail-context`,"data-testid":`detail-context`,children:[U(`div`,{class:`detail-context-heading`,children:[U(`h1`,{tabindex:-1,children:n.name}),U(G,{state:n.available?`current`:`warning`,children:n.available?`Configured`:`Unavailable`})]}),U(`p`,{class:`technical-value`,children:n.id})]}),U(`section`,{class:`detail-section`,"aria-labelledby":`credential-details-title`,children:[U(`div`,{class:`panel-heading`,children:U(`h2`,{id:`credential-details-title`,children:`Credential details`})}),U(`h3`,{children:`HTTPS scope and recipe`}),U(`dl`,{class:`detail-facts`,children:[U(`div`,{children:[U(`dt`,{children:`HTTPS boundary`}),U(`dd`,{children:[n.boundary.host,`:`,n.boundary.port]})]}),U(`div`,{children:[U(`dt`,{children:`Wildcard hosts`}),U(`dd`,{children:n.boundary.allow_wildcard?`Allowed within boundary`:`Exact host only`})]}),U(`div`,{children:[U(`dt`,{children:`Header recipe`}),U(`dd`,{children:[n.recipe.header,`: `,n.recipe.prefix,U(`span`,{class:`secondary-text`,children:`[secret]`})]})]})]}),U(`h3`,{children:`Referencing grants`}),n.referencing_grants.length===0?U(`p`,{children:`No referencing grants`}):U(`ul`,{children:n.referencing_grants.map(e=>U(`li`,{class:`technical-value`,children:U(`a`,{href:`#/http/grants/${e.id}`,children:e.id})},e.id))}),U(`h3`,{children:`Metadata`}),U(`dl`,{class:`detail-facts`,children:U(`div`,{children:[U(`dt`,{children:`Revision`}),U(`dd`,{children:n.revision})]})})]}),b(Tu,{...e,key:`${n.id}-edit`,acknowledgment:i,onAcknowledged:a,credential:n,mode:`edit`,unavailable:o||c}),b(Tu,{...e,key:`${n.id}-rotate`,acknowledgment:i,onAcknowledged:a,credential:n,mode:`rotate`,unavailable:o||c}),b(Tu,{...e,key:`${n.id}-delete`,acknowledgment:i,onAcknowledged:a,credential:n,mode:`delete`,unavailable:o||c})]}):U(K,{state:`loading`,title:`Loading HTTP credential`})}function wu(e){let t=Cr(!1),{items:n,controls:r}=Nr(e.session,e.resolved,e.view,(t,n,r)=>{let i=new URLSearchParams({limit:`50`,sort:t.sort??`name`,direction:t.direction??`ascending`});for(let e of[`name`,`boundary`,`recipe`,`status`]){let n=t[`filter_${e}`];n!==void 0&&i.set(e,n)}return n!==null&&i.set(`cursor`,n),Mr(e.session,`/api/v2/http/credentials?${i}`,bu,r)},t,{key:`name`,direction:`ascending`});return U(`div`,{class:`domain-view`,children:[U(`div`,{class:`collection-toolbar`,children:U(`a`,{class:`button-link create-action`,href:`#/http/credentials/new`,children:`Create credential`})}),U(`section`,{class:`panel domain-panel`,children:U(Dn,{caption:`HTTP credentials`,rowHeaderKey:`name`,remote:r,itemNames:{singular:`credential`,plural:`credentials`},emptyTitle:`No HTTP credentials`,items:n,rowKey:e=>e.id,initialSort:{key:`name`,direction:`ascending`},filters:[{key:`name`,label:`Name or ID`,type:`text`,value:e=>e.name,literalValues:e=>[e.id]},{key:`boundary`,label:`HTTPS boundary`,type:`text`,value:e=>`${e.boundary.host}:${e.boundary.port}`},{key:`recipe`,label:`Header recipe`,type:`text`,value:e=>`${e.recipe.header} ${e.recipe.prefix}`},{key:`status`,label:`Status`,type:`select`,value:e=>e.available?`configured`:`unavailable`,options:[{value:`configured`,label:`Configured`},{value:`unavailable`,label:`Unavailable`}]}],columns:[{key:`name`,label:`Credential`,role:`identity`,sortValue:e=>e.name,render:t=>U(q,{primary:U(`a`,{href:ln({destination:`http-credentials`,segments:[`http-credentials`,t.id],query:e.resolved.location.query}),children:t.name}),secondary:t.id})},{key:`boundary`,label:`HTTPS boundary`,role:`relation`,sortValue:e=>`${e.boundary.host}:${e.boundary.port}`,render:e=>U(S,{children:[e.boundary.host,`:`,e.boundary.port]})},{key:`recipe`,label:`Header recipe`,role:`identity`,sortValue:e=>`${e.recipe.header} ${e.recipe.prefix}`,render:e=>U(S,{children:[e.recipe.header,`: `,e.recipe.prefix,`[secret]`]})},{key:`status`,label:`Status`,role:`status`,sortValue:e=>e.available?`configured`:`unavailable`,render:e=>U(G,{state:e.available?`current`:`warning`,children:e.available?`Configured`:`Unavailable`})}]})})]})}function Tu({mutations:e,sinks:t,credential:n,mode:r,onRefresh:i,view:a,unavailable:o=!1,acknowledgment:s,onAcknowledged:c}){let[l,u]=z(n?.name??``),[d,f]=z(n?.boundary.host??``),[p,m]=z(String(n?.boundary.port??443)),[h,g]=z(n?.boundary.allow_wildcard??!1),[_,v]=z(n?.recipe.header??`Authorization`),[y,b]=z(n?.recipe.prefix??`Bearer `),[x]=z(()=>t.createWriteOnly()),[C]=z(()=>e.create()),[w,T]=z(()=>C.snapshot()),[E,D]=z(!1),[O,k]=z(!1),[A,j]=z(n),M=A===void 0||JSON.stringify({name:l,host:d.toLowerCase(),port:p,wildcard:h,header:_.toLowerCase(),prefix:y})!==JSON.stringify({name:A.name,host:A.boundary.host.toLowerCase(),port:String(A.boundary.port),wildcard:A.boundary.allow_wildcard,header:A.recipe.header.toLowerCase(),prefix:A.recipe.prefix}),N=r===`edit`?M:O,[ee,P]=z(),[te,F]=z(),[ne,I]=z(!1),[re,ie]=z(()=>n===void 0?null:Su(n)),ae=V();B(()=>{if(!(n===void 0||o||re===Su(n))){if(re!==Su(n)){if(s?.from!==re||s.to!==Su(n)||ae.current===s.to)return;ae.current=s.to}N||ne||E||w.state!==`editing`||(j(n),ie(Su(n)),u(n.name),f(n.boundary.host),m(String(n.boundary.port)),g(n.boundary.allow_wildcard),v(n.recipe.header),b(n.recipe.prefix))}},[n,N,ne,E,w.state,s,re,o]);let oe=V(null),se=Cr(N),ce=`http-credential-secret-${r}`;B(()=>C.subscribe(T),[C]),B(()=>()=>{C.close(),x.close()},[C,x]);let L=r===`create`||r===`edit`,le=r===`create`||r===`rotate`,ue=r===`edit`&&(n?.referencing_grants.length??0)>0,de=n!==void 0&&re!==Su(n),fe=o||de||ne||w.state===`submitting`||w.state===`uncertain`||w.availability===`storage_latched`||te!==void 0&&a.generation<=te||r===`delete`&&(n?.referencing_grants.length??0)>0,R=r===`create`?`Create HTTP credential`:r===`edit`?`Edit credential`:r===`rotate`?`Rotate secret`:`Delete credential`,pe=()=>{x.clear(),k(!1)},me=()=>{if(L){if(l.trim()===``||new TextEncoder().encode(l).byteLength>256)return`Name must be nonempty and at most 256 bytes.`;if(d===``||new TextEncoder().encode(d.startsWith(`*.`)?d.slice(2):d).byteLength>253)return`HTTPS destination host must be nonempty and at most 253 bytes, excluding *.`;if(!/^[1-9][0-9]*$/.test(p)||Number(p)>65535)return`Port must be a whole number from 1 to 65535.`;if(!/^[!#$%&'*+.^_`|~0-9A-Za-z-]{1,128}$/.test(_))return`Header name must contain 1–128 HTTP token characters.`;if(!/^[\x20-\x7e]{0,128}$/.test(y))return`Fixed prefix must contain at most 128 printable ASCII characters.`}if(le){let e=document.getElementById(ce);if(!(e instanceof HTMLInputElement)||e.value===``)return`Secret must be nonempty.`;if(e.value.length+y.length>4096)return`Secret and fixed prefix must total at most 4096 characters.`;if(!/^[\x20-\x7e]+$/.test(e.value))return`Secret must contain only printable ASCII characters.`}},he=e=>{x.clear(),P(le?`${e} Enter the secret again; it was cleared.`:e)},ge=()=>{if(fe||r===`edit`&&!N)return;let e=me();P(void 0),e===void 0?D(!0):he(e)};return U(`section`,{class:`panel domain-panel`,"aria-labelledby":`http-credential-title-${r}`,children:[U(`div`,{class:`panel-heading`,children:U(`h2`,{id:`http-credential-title-${r}`,children:r===`create`?`Credential configuration`:R})}),U(`form`,{onSubmit:e=>{e.preventDefault(),ge()},onInput:()=>k(!0),children:U(`fieldset`,{class:`credential-fields`,disabled:w.state===`submitting`||w.state===`uncertain`||w.availability===`storage_latched`,children:[L&&U(S,{children:[U(J,{id:`http-name-${r}`,label:`Name`,children:e=>U(`input`,{...e,required:!0,placeholder:`Example API credential`,value:l,onInput:e=>u(e.currentTarget.value)})}),U(J,{id:`http-host-${r}`,label:`HTTPS destination host`,children:e=>U(`input`,{...e,required:!0,placeholder:`api.example.com`,value:d,onInput:e=>f(e.currentTarget.value)})}),U(J,{id:`http-port-${r}`,label:`Port`,children:e=>U(`input`,{...e,required:!0,type:`number`,min:`1`,max:`65535`,placeholder:`443`,value:p,onInput:e=>m(e.currentTarget.value)})}),U(J,{id:`http-wildcard-${r}`,label:`Allow the explicit *. subdomain boundary`,children:e=>U(On,{attributes:e,checked:h,onChange:g})}),ue&&U(`p`,{children:`Header recipe is fixed while referenced.`}),U(J,{id:`http-header-${r}`,label:`Header name`,children:e=>U(`input`,{...e,required:!0,readOnly:ue,placeholder:`Authorization`,value:_,onInput:e=>v(e.currentTarget.value)})}),U(J,{id:`http-prefix-${r}`,label:`Fixed prefix (optional)`,hint:`Include any space needed between the prefix and secret. Leave blank for no prefix.`,children:e=>U(`input`,{...e,readOnly:ue,placeholder:`Bearer `,value:y,onInput:e=>b(e.currentTarget.value)})})]}),le&&U(Ni,{id:ce,value:x,label:`Secret`,placeholder:`Enter secret value`,hint:`Write-only. Cleared after submission; stored values cannot be revealed.`}),r===`delete`&&(n?.referencing_grants.length??0)>0&&U(K,{state:`warning`,title:`Credential is referenced`,children:`Remove referencing grants before deleting this credential.`}),ee!==void 0&&U(K,{state:`error`,title:`Check credential fields`,children:U(`p`,{children:ee})}),(ne||de)&&U(K,{state:`warning`,title:`Review current credential revision`,children:[U(`p`,{children:`Compare the current facts above with your retained draft before applying it.`}),U(`button`,{type:`button`,disabled:o||n===void 0||te!==void 0&&a.generation<=te,onClick:()=>{n!==void 0&&(ie(Su(n)),j(n),I(!1),C.abandon())},children:`Use reviewed revision; keep draft`})]}),w.problem!==void 0&&U(K,{state:`error`,title:w.problem.title}),w.state===`uncertain`&&U(K,{state:`warning`,title:`Credential change outcome unknown`,children:U(`p`,{children:`Inspect current metadata before making a new decision. No replay is available.`})}),U(`button`,{ref:oe,type:`submit`,class:r===`delete`?`danger-action form-submit-action`:`${r===`create`?`create-action `:r===`edit`?`primary-action `:``}form-submit-action`,disabled:fe||r===`edit`&&!N,children:r===`create`?`Review and create`:`Review ${r===`edit`?`changes`:r===`rotate`?`rotation`:`deletion`}`})]})}),U(jn,{id:`http-credential-confirm-${r}`,open:E,title:R,consequence:L?U(`div`,{class:`review-stack`,children:[U(`dl`,{class:`detail-facts`,children:[U(`div`,{children:[U(`dt`,{children:`Name`}),U(`dd`,{children:l})]}),U(`div`,{children:[U(`dt`,{children:`HTTPS boundary`}),U(`dd`,{children:[d,`:`,p]})]}),U(`div`,{children:[U(`dt`,{children:`Wildcard hosts`}),U(`dd`,{children:h?`Allowed within boundary`:`Exact host only`})]}),U(`div`,{children:[U(`dt`,{children:`Header`}),U(`dd`,{children:_})]}),U(`div`,{children:[U(`dt`,{children:`Prefix`}),U(`dd`,{children:y===``?`None`:U(`code`,{children:y})})]}),U(`div`,{children:[U(`dt`,{children:`Secret material`}),U(`dd`,{children:r===`create`?`Write-only; not displayed`:`Unchanged`})]})]}),U(`p`,{children:`Replace the named header using this recipe. Every referencing grant must remain contained.`})]}):r===`delete`?`Permanently retire this unreferenced credential. Stored material cannot be restored from a backup.`:`Once replacement starts, failure may leave this credential unavailable; replacement does not fall back to the old secret.`,confirmLabel:R,destructive:r!==`create`,returnFocus:oe,onCancel:()=>{D(!1),x.clear()},onConfirm:()=>{if(D(!1),fe){he(`Current credential state cannot authorize this change. Refresh and review again.`);return}let e=me();if(e!==void 0){he(e);return}let t=document.getElementById(ce),o=t instanceof HTMLInputElement?t.value:``,s={name:l,boundary:{host:d,port:Number(p),allow_wildcard:h},recipe:{header:_,prefix:y}},u=r===`create`?{...s,secret:o}:r===`edit`?s:r===`rotate`?{secret:o}:{},f=`/api/v2/http/credentials${n===void 0?``:`/${n.id}`}${r===`rotate`?`/rotate`:``}`;try{C.begin({route:f,method:r===`delete`?`DELETE`:r===`edit`?`PATCH`:`POST`,body:JSON.stringify(u),precondition:re,requiresPrecondition:n!==void 0,idempotency:`none`,successStatuses:[r===`create`?201:r===`delete`?204:200],...le?{uncertainProblemCodes:[`keyring_unavailable`]}:{},decode:async e=>r===`delete`?null:xu(e)})}catch{pe(),P(le?`Credential change could not be prepared. Enter the secret again; it was cleared.`:`Credential change could not be prepared. Refresh before reviewing again.`);return}let m=C.submit();r===`edit`?x.clear():pe(),m.then(e=>{e.kind===`acknowledged`?(k(!1),e.value&&(re&&c?.({from:re,to:Su(e.value)}),j(e.value),ie(Su(e.value))),I(!1),C.abandon(),r===`delete`?se(`#/http/credentials`,!0):r===`create`&&e.value!==null?se(`#/http/credentials/${e.value.id}`,!0):i()):(e.kind===`uncertain`||e.kind===`rejected`&&e.requiresRefresh)&&(F(a.generation),r===`edit`&&e.kind===`rejected`&&I(!0),i())})}})]})}var Eu={block_destination:`Block destination`,allow_tunnel:`Allow tunnel`,block_requests:`Block requests`,allow_requests:`Allow requests`};async function Du(e){if(e.headers.get(`Content-Type`)!==`application/json`)throw Error(`HTTP policy data unavailable.`);let t=await e.text();if(t.length>1048576)throw Error(`HTTP policy data unavailable.`);return He(t)}async function Ou(e,t,n){return e.runProtected(async e=>{let r=await fetch(t,{credentials:`same-origin`,redirect:`error`,signal:e.signal,headers:{Accept:`application/json`,"X-CSRF-Token":e.csrfToken}});if(!await e.sessionLost(r)){if(!r.ok)throw Error(`HTTP policy data unavailable.`);return n(await Du(r),r)}})}async function ku(e){let t=[],n=null;for(let r=0;r<3;r++){let r=await Ou(e,`/api/v2/http/credentials?limit=100${n===null?``:`&cursor=`+encodeURIComponent(n)}`,e=>{let t=ht(e,[`items`,`next_cursor`,`total_count`,`offset`]);if(!Array.isArray(t.items)||t.items.length>100||t.next_cursor!==null&&(typeof t.next_cursor!=`string`||t.next_cursor.length>512))throw Error(`Invalid credential choices.`);return{items:t.items.map(bu),next:t.next_cursor}});if(r===void 0)throw Error(`Credential choices unavailable.`);if(t.push(...r.items),t.length>256||new Set(t.map(e=>e.id)).size!==t.length)throw Error(`Invalid credential choices.`);if(r.next===null)return t;n=r.next}throw Error(`Credential choice limit exceeded.`)}function Au(e){return`"http-grant-${e.id}-${e.revision}"`}async function ju(e){let t=xt(await Du(e));if(e.headers.get(`ETag`)!==Au(t))throw Error(`Invalid HTTP grant revision.`);return t}function Mu(e){return e.destination??e.request.origin}function Nu(e){let t=Mu(e),n=e.request;return[{label:`Type`,value:Eu[e.type]},{label:`Destination`,value:`${n===void 0?``:n.origin.scheme+`://`}${t.host}:${t.port}`},{label:`Methods`,value:n===void 0?`Not applicable`:n.methods.any?`Any method`:n.methods.values.join(`, `)},{label:`Path`,value:n===void 0?`Not applicable`:n.path.kind===`any`?`Any path`:n.path.kind===`exact`?n.path.value:n.path.value+` and descendants`},{label:`Local/private access`,value:e.type===`allow_requests`||e.type===`allow_tunnel`?e.allow_private?`Enabled`:`Disabled`:`Not applicable`},{label:`Credential`,value:e.type===`allow_requests`?e.credential_id??`No credential`:`Not applicable`,href:e.credential_id===void 0?void 0:`#/http/credentials/${e.credential_id}`}]}function Pu({policy:e,credentialName:t}){return U(S,{children:Nu(e).map(n=>U(`div`,{children:[U(`dt`,{children:n.label}),U(`dd`,{children:n.href===void 0?n.value:U(S,{children:[U(`a`,{href:n.href,children:n.label===`Credential`?t??n.value:n.value}),n.label===`Credential`&&t!==void 0&&U(`span`,{class:`table-identifier`,children:e.credential_id})]})})]},n.label))})}function Fu({current:e,proposed:t,principals:n}){let r=e=>[{label:`Description`,value:e.description||`Unnamed HTTP grant`},{label:`Agent`,value:e.principal_id,content:U(q,{primary:n.find(t=>t.id===e.principal_id)?.displayName??`Agent unavailable`,secondary:e.principal_id})},...Nu(e.policy).map(e=>({...e,content:e.href===void 0?e.value:U(`a`,{href:e.href,children:e.value})})),{label:`Expires`,value:e.expires_at,content:U(Y,{value:e.expires_at,fallback:`No expiry`})}],i=r(e);return U(xn,{label:`Current versus proposed grant`,beforeLabel:`Current`,afterLabel:`Proposed`,rows:r(t).map((e,t)=>({label:e.label,before:`content`in i[t]?i[t].content:i[t].value,after:`content`in e?e.content:e.value,changed:i[t].value!==e.value}))})}function Iu(e,t){let[n,r]=z([]),[i,a]=z([]),[o,s]=z(!1),[c,l]=z(!0);return B(()=>{if(!t)return;let n=!0;return l(!0),Promise.all([Qo(e.session),ku(e.session)]).then(([e,t])=>{n&&(r(e),a(t),s(!1))}).catch(()=>{n&&(r([]),a([]),s(!0))}).finally(()=>{n&&l(!1)}),()=>{n=!1}},[t,e.view.generation]),{principals:n,credentials:i,loadError:o,loading:c}}function Lu(e){let[t]=z(()=>e.mutations.create()),[n,r]=z(()=>t.snapshot()),[i,a]=z(),[o,s]=z(!1);return B(()=>t.subscribe(r),[t]),B(()=>()=>t.close(),[t]),{blocked:n.state===`submitting`||n.state===`uncertain`||n.availability===`storage_latched`||i!==void 0&&e.view.generation<=i,submit:async(n,r)=>{try{t.begin(n);let i=await t.submit();i.kind===`acknowledged`?(t.abandon(),r(i.value)):(i.kind===`uncertain`||i.kind===`rejected`&&i.requiresRefresh)&&(a(e.view.generation),i.kind===`rejected`&&s(!0),e.onRefresh())}catch{a(e.view.generation),e.onRefresh()}},state:n,reviewRequired:o,review:()=>{s(!1),t.abandon()}}}function Ru({state:e}){return e.state===`uncertain`?U(K,{state:`error`,title:`Outcome uncertain`,children:U(`p`,{children:`Inspect current policy. Do not replay this change.`})}):e.state===`rejected`?U(K,{state:`error`,title:`Change not applied`,children:[U(`p`,{children:e.problem?.title??`Check the proposed policy.`}),e.requiresRefresh&&U(`p`,{children:`Inspect refreshed policy before reviewing again.`})]}):null}function zu(e){let t=e.resolved.location.segments[1],[n,r]=z(),[i,a]=z(!1),[o,s]=z(!0),[c,l]=z(0),[u,d]=z(!1),f=V(null),p=Iu(e,t!==void 0&&t!==`test-access`),m=()=>{l(e=>e+1),f.current?.focus()};if(B(()=>{let n=!0;if(s(!0),t!==void 0&&t!==`new`&&t!==`test-access`)return Ou(e.session,`/api/v2/http/grants/${t}`,(e,n)=>{let r=xt(e);if(r.id!==t||n.headers.get(`ETag`)!==Au(r))throw Error(`HTTP grant revision unavailable.`);return r}).then(e=>{n&&e?.id===t&&(r(e),a(!1))}).catch(()=>{n&&a(!0)}).finally(()=>{n&&s(!1)}),()=>{n=!1}},[t,e.view.generation]),t===void 0)return U(Bu,{...e});if(t===`test-access`)return U(Hu,{...e});if(t===`new`)return U(Vu,{...e,choices:p});if(i&&n?.id!==t)return U(K,{state:`error`,title:`HTTP grant unavailable`,children:U(`p`,{children:`Refresh to inspect current policy.`})});if(n?.id!==t)return U(K,{state:`loading`,title:`Loading HTTP grant`});let h=p.credentials.find(e=>e.id===n.policy.credential_id)?.available;return U(`div`,{class:`domain-view`,children:[U(`nav`,{class:`detail-navigation`,"aria-label":`HTTP grant navigation`,children:U(`a`,{href:`#/http/grants`,children:`Back to HTTP grants`})}),U(`header`,{class:`detail-context`,"data-testid":`detail-context`,children:[U(`div`,{class:`detail-context-heading`,children:[U(`h1`,{ref:f,tabindex:-1,children:n.description||`Unnamed HTTP grant`}),U(G,{state:n.state===`active`?`current`:`neutral`,children:n.state===`active`?`Active`:`Expired`})]}),U(`p`,{class:`technical-value`,children:n.id})]}),i&&U(K,{state:`stale`,title:u?`Grant saved; refresh unavailable`:`Grant details are stale`,children:U(`p`,{children:[u?`Showing last acknowledged values.`:`Showing last loaded values.`,` `,`Refresh to inspect current policy before editing.`]})}),U(`section`,{class:`detail-section`,"aria-labelledby":`http-grant-details-title`,children:[U(`div`,{class:`panel-heading`,children:U(`h2`,{id:`http-grant-details-title`,children:`Grant details`})}),U(`h3`,{children:`Policy and relationships`}),U(`dl`,{class:`detail-facts`,children:[U(`div`,{children:[U(`dt`,{children:`Agent`}),U(`dd`,{children:U(q,{primary:U(`a`,{href:`#/agents/${n.principal_id}`,children:p.principals.find(e=>e.id===n.principal_id)?.displayName??(p.loading?`Loading agent`:`Agent unavailable`)}),secondary:n.principal_id})})]}),U(Pu,{policy:n.policy,credentialName:p.credentials.find(e=>e.id===n.policy.credential_id)?.name}),n.policy.credential_id!==void 0&&U(`div`,{children:[U(`dt`,{children:`Credential material`}),U(`dd`,{children:p.loading?`Loading`:h===void 0?`Unknown`:h?`Available`:`Unavailable`})]})]}),U(`h3`,{children:`Timing`}),U(`dl`,{class:`detail-facts`,children:[U(`div`,{children:[U(`dt`,{children:`Expires`}),U(`dd`,{children:U(Y,{value:n.expires_at,fallback:`No expiry`})})]}),U(`div`,{children:[U(`dt`,{children:`Created`}),U(`dd`,{children:U(Y,{value:n.created_at})})]})]})]}),b(Vu,{...e,key:`${n.id}:${c}`,grant:n,choices:p,unavailable:i||o,onCancel:m,onSaved:t=>{r(t),d(!0),m(),f.current?.focus(),e.notify(`Grant saved`),e.onRefresh()}})]})}function Bu(e){let t=Cr(!1),{items:n,controls:r}=Nr(e.session,e.resolved,e.view,(t,n,r)=>{let i=new URLSearchParams({limit:`50`,sort:t.sort??`description`,direction:t.direction??`ascending`});for(let e of[`identity`,`principal`,`target`,`type`,`state`]){let n=t[`filter_${e}`];n!==void 0&&i.set(e,n)}return t.principal_id!==void 0&&i.set(`principal_id`,t.principal_id),n!==null&&i.set(`cursor`,n),Mr(e.session,`/api/v2/http/grants?${i}`,e=>{let t=mt(e);if(Object.keys(t).sort().join()!==`grant,principal_display_name`||typeof t.principal_display_name!=`string`)throw Error(`Invalid grant row.`);return{grant:xt(t.grant),principal_display_name:t.principal_display_name}},r)},t,{key:`description`,direction:`ascending`});return U(`div`,{class:`domain-view`,children:[U(`div`,{class:`collection-toolbar`,children:[U(`a`,{class:`button-link create-action`,href:`#/http/grants/new`,children:`Create grant`}),U(`a`,{class:`button-link`,href:`#/http/grants/test-access`,children:`Test access`})]}),U(`section`,{class:`panel domain-panel`,children:U(Dn,{caption:`HTTP grants`,rowHeaderKey:`description`,additionalSorts:[{key:`id`,label:`Grant ID`,sortValue:e=>e.grant.id}],remote:r,initialSort:{key:`description`,direction:`ascending`},itemNames:{singular:`grant`,plural:`grants`},emptyTitle:`No HTTP grants`,items:n,rowKey:e=>e.grant.id,filters:[{key:`identity`,label:`Description or ID`,type:`text`,value:e=>e.grant.description??``,literalValues:e=>[e.grant.id]},{key:`principal`,label:`Agent`,type:`text`,value:e=>e.principal_display_name,literalValues:e=>[e.grant.principal_id]},{key:`target`,label:`Destination host`,type:`text`,value:e=>Mu(e.grant.policy).host},{key:`type`,label:`Type`,type:`select`,value:e=>e.grant.policy.type,options:Object.entries(Eu).map(([e,t])=>({value:e,label:t}))},{key:`state`,label:`Status`,type:`select`,value:e=>e.grant.state,options:[{value:`active`,label:`Active`},{value:`expired`,label:`Expired`}]}],columns:[{key:`description`,label:`Grant`,role:`identity`,sortValue:e=>e.grant.description??``,render:e=>U(q,{primary:U(`a`,{href:`#/http/grants/${e.grant.id}`,children:e.grant.description??`Unnamed grant`}),secondary:e.grant.id})},{key:`principal`,label:`Agent`,role:`relation`,sortValue:e=>e.principal_display_name,render:e=>U(q,{primary:U(`a`,{href:`#/agents/${e.grant.principal_id}`,children:e.principal_display_name||e.grant.principal_id}),secondary:e.grant.principal_id})},{key:`target`,label:`Destination`,role:`relation`,sortValue:e=>Mu(e.grant.policy).host,render:e=>U(S,{children:[Mu(e.grant.policy).host,`:`,Mu(e.grant.policy).port]})},{key:`effect`,label:`Type`,role:`status`,sortValue:e=>e.grant.policy.type,render:e=>Eu[e.grant.policy.type]},{key:`state`,label:`Status`,role:`status`,sortValue:e=>e.grant.state,render:e=>U(G,{state:e.grant.state===`active`?`current`:`neutral`,children:e.grant.state===`active`?`Active`:`Expired`})},{key:`expiry`,label:`Expires`,role:`time`,render:e=>U(Y,{value:e.grant.expires_at,fallback:`No expiry`})}]})})]})}function Vu(e){let t=e.grant,n=t?.policy,r=n?.request,{principals:i,credentials:a,loadError:o,loading:s}=e.choices,[c,l]=z(t?.principal_id??``),[u,d]=z(t?.description??``),[f,p]=z(n?.type??`allow_requests`),[m,h]=z(n===void 0?``:Mu(n).host),[g,_]=z(String(n===void 0?443:Mu(n).port)),[v,y]=z(r?.origin.scheme??`https`),[b,x]=z(r?.methods.values??[]),[C,w]=z(r?.path.kind??`any`),[T,E]=z(r?.path.value??``),[D,O]=z(n?.allow_private??!1),[k,A]=z(n?.credential_id??``),[j,M]=z(t),[N,ee]=z(Hl(t?.expires_at)),[P,te]=z(),[F,ne]=z(!1),I=V(null),re=V(null),ie=V(null),ae=V(null),[oe,se]=z(!1),[ce,L]=z(t===void 0?null:Au(t)),le=V(null),ue=Lu(e),de=f===`allow_requests`||f===`block_requests`,fe=f===`allow_requests`||f===`allow_tunnel`,R=a.filter(e=>v===`https`&&e.boundary.port===Number(g)&&(e.boundary.host===m.toLowerCase()||e.boundary.host.startsWith(`*.`)&&m.toLowerCase().endsWith(e.boundary.host.slice(1)))),pe={version:1,type:f,...de?{request:{origin:{scheme:v,host:m,port:Number(g)},methods:b.length===0?{any:!0}:{values:b},path:C===`any`?{kind:C}:{kind:C,value:T}}}:{destination:{host:m,port:Number(g)}},...fe?{allow_private:D}:{},...f===`allow_requests`&&k!==``?{credential_id:k}:{}},me=Ul(N,j?.expires_at),he=e=>JSON.stringify({version:e.version,type:e.type,allow_private:e.allow_private,credential_id:e.credential_id,...e.request?{request:{origin:{scheme:e.request.origin.scheme,host:e.request.origin.host.toLowerCase(),port:e.request.origin.port},path:{kind:e.request.path.kind,value:e.request.path.value},methods:e.request.methods.any?{any:!0}:{values:[...e.request.methods.values??[]].sort()}}}:{},...e.destination?{destination:{host:e.destination.host.toLowerCase(),port:e.destination.port}}:{}}),ge=j===void 0||!/^[1-9][0-9]*$/.test(g)||c!==j.principal_id||(u||null)!==j.description||me!==j.expires_at||he(pe)!==he(j.policy),_e=Cr(ge),ve=t!==void 0&&(ce!==Au(t)||ue.reviewRequired),ye=()=>{let n=P===`delete`;if(te(void 0),ue.blocked||ve||e.unavailable||!n&&(o||s))return;let r=n?null:JSON.stringify({principal_id:c,description:u||null,policy:pe,expires_at:me});ue.submit({route:`/api/v2/http/grants${t===void 0?``:`/`+t.id}`,method:n?`DELETE`:t===void 0?`POST`:`PATCH`,body:r,precondition:ce,requiresPrecondition:t!==void 0,idempotency:`none`,successStatuses:[n?204:t===void 0?201:200],decode:async e=>{if(n)return null;let r=await ju(e);if(r.principal_id!==c||t!==void 0&&r.id!==t.id)throw Error(`HTTP grant identity unavailable.`);return r}},n=>{n!==null&&M(n),n===null?_e(`#/http/grants`,!0):t===void 0?_e(`#/http/grants/${n.id}`,!0):e.onSaved?.(n)})};return U(`section`,{id:`http-grant-editor`,class:`panel domain-panel`,"aria-labelledby":`http-grant-editor-title`,children:[U(`div`,{class:`panel-heading`,children:U(`h2`,{id:`http-grant-editor-title`,children:t===void 0?`Grant configuration`:`Edit grant`})}),o&&U(K,{state:`error`,title:`Agent or credential choices unavailable`}),ve&&U(K,{state:`warning`,title:`Policy changed`,children:[U(`p`,{children:`Inspect the current policy above before applying this draft.`}),U(`button`,{type:`button`,disabled:ue.blocked||e.unavailable,onClick:()=>{L(Au(t)),M(t),ue.review()},children:`Use current revision`})]}),U(`form`,{onSubmit:e=>{e.preventDefault();let t=pt.test(c)&&new TextEncoder().encode(u).length<=256&&m.length<=253&&/^[1-9][0-9]*$/.test(g)&&Number(g)<=65535&&(!de||C===`any`||T.startsWith(`/`))&&(N===``||Date.parse(N)>Date.now())&&(f!==`allow_requests`||k===``||R.some(e=>e.id===k));se(!t),t&&(ie.current=le.current,te(`save`))},children:[U(`div`,{role:`group`,"aria-label":`Agent and description`,children:[U(J,{id:`http-grant-principal`,label:`Agent`,...c?{hint:c}:{},children:e=>t===void 0?U(`select`,{...e,required:!0,value:c,onChange:e=>l(e.currentTarget.value),children:[U(`option`,{value:``,children:`Select agent`}),t!==void 0&&!i.some(e=>e.id===c)&&U(`option`,{value:c,children:[`Agent unavailable · `,c]}),i.map(e=>U(`option`,{value:e.id,children:[e.displayName,i.filter(t=>t.displayName===e.displayName).length>1?` · ${e.id}`:``]},e.id))]}):U(`input`,{...e,readOnly:!0,value:i.find(e=>e.id===c)?.displayName??c})}),U(J,{id:`http-grant-description`,label:`Description (optional)`,children:e=>U(`input`,{...e,ref:ae,placeholder:`Example API policy`,maxLength:256,value:u,onInput:e=>d(e.currentTarget.value)})})]}),U(`div`,{class:`form-section`,role:`group`,"aria-label":`Destination and matching`,children:[U(J,{id:`http-grant-type`,label:`Grant type`,children:e=>U(`select`,{...e,value:f,onChange:e=>p(e.currentTarget.value),children:Object.entries(Eu).map(([e,t])=>U(`option`,{value:e,children:t}))})}),f===`allow_tunnel`&&U(K,{state:`warning`,title:`Opaque tunnel bypass`,children:U(`p`,{children:`Allows encrypted traffic without request method/path checks or credential injection. Request blocks do not apply inside this tunnel.`})}),de&&U(J,{id:`http-grant-scheme`,label:`Scheme`,children:e=>U(`select`,{...e,value:v,onChange:e=>{y(e.currentTarget.value),A(``)},children:[U(`option`,{value:`https`,children:`HTTPS`}),U(`option`,{value:`http`,children:`HTTP`})]})}),U(J,{id:`http-grant-host`,label:`Destination host`,hint:`Exact host, or *.example.com for every subdomain excluding the apex.`,children:e=>U(`input`,{...e,required:!0,maxLength:255,placeholder:`api.example.com`,value:m,onInput:e=>h(e.currentTarget.value)})}),U(J,{id:`http-grant-port`,label:`Port`,children:e=>U(`input`,{...e,required:!0,type:`number`,min:1,max:65535,placeholder:`443`,value:g,onInput:e=>_(e.currentTarget.value)})}),de&&U(S,{children:[U(`fieldset`,{class:`collection-field`,children:[U(`legend`,{children:`Methods`}),U(`p`,{children:b.length===0?`Any method`:`Only the listed methods`}),b.map((e,t)=>U(`div`,{class:`form-actions`,children:[U(`input`,{"aria-label":`Method ${t+1}`,required:!0,maxLength:32,pattern:"[A-Z0-9!#$%&'*+.^_`\\|~\\-]+",placeholder:`GET`,value:e,onInput:e=>x(b.map((n,r)=>r===t?e.currentTarget.value:n))}),U(`button`,{type:`button`,onClick:()=>{x(b.filter((e,n)=>n!==t))},children:`Remove method`})]})),U(`button`,{type:`button`,disabled:b.length>=32,onClick:()=>{x([...b,`GET`])},children:`Add method`})]}),U(J,{id:`http-grant-path-kind`,label:`Path match`,children:e=>U(`select`,{...e,value:C,onChange:e=>w(e.currentTarget.value),children:[U(`option`,{value:`any`,children:`Any path`}),U(`option`,{value:`exact`,children:`Exact path`}),U(`option`,{value:`segment_prefix`,children:`Path and descendants`})]})}),C!==`any`&&U(J,{id:`http-grant-path`,label:`Path`,hint:`Slash, literal @ and unreserved characters only; query, header and body matching are not supported.`,children:e=>U(`input`,{...e,required:!0,maxLength:4096,placeholder:`/v1/resources`,value:T,onInput:e=>E(e.currentTarget.value)})})]})]}),U(`div`,{class:`form-section`,role:`group`,"aria-label":`Permissions and expiry`,children:[f===`allow_requests`&&U(J,{id:`http-grant-credential`,label:`Credential (optional)`,hint:k||`Only HTTPS credentials covering this entire destination are eligible.`,children:e=>U(`select`,{...e,value:k,onChange:e=>A(e.currentTarget.value),children:[U(`option`,{value:``,children:`No credential`}),k!==``&&!R.some(e=>e.id===k)&&U(`option`,{value:k,children:[`Unavailable credential · `,k]}),R.map(e=>U(`option`,{value:e.id,children:[e.name,a.filter(t=>t.name===e.name).length>1?` · ${e.id}`:``,e.available?``:` — unavailable`]}))]})}),fe&&U(`label`,{class:`checkbox-field`,for:`http-grant-private`,children:[U(`input`,{id:`http-grant-private`,type:`checkbox`,checked:D,"aria-describedby":`http-grant-private-hint`,onChange:e=>O(e.currentTarget.checked)}),U(`span`,{children:[U(`strong`,{children:`Allow local/private destinations`}),U(`small`,{id:`http-grant-private-hint`,children:`Permits loopback and private networks within this grant. Metadata, link-local and Gateway endpoints remain forbidden.`})]})]}),U(J,{id:`http-grant-expiry`,label:`Expires (optional)`,children:e=>U(`input`,{...e,type:`datetime-local`,value:N,onInput:e=>ee(e.currentTarget.value)})})]}),oe&&U(K,{state:`error`,title:`Check the proposed policy`,children:U(`p`,{children:`Use a valid agent, destination, future expiry and compatible credential.`})}),U(Ru,{state:ue.state}),U(`div`,{class:`form-actions`,children:[U(`button`,{ref:le,class:`${t===void 0?`create-action`:`primary-action`} form-submit-action`,disabled:ue.blocked||ve||o||s||e.unavailable||t!==void 0&&!ge,children:ue.state.state===`submitting`?`Applying grant…`:t===void 0?`Review and create`:`Review changes`}),t!==void 0&&U(S,{children:U(`button`,{ref:I,type:`button`,disabled:ue.blocked,onClick:()=>ge?ne(!0):e.onCancel?.(),children:`Cancel`})})]})]}),t!==void 0&&U(`section`,{class:`detail-group`,"aria-label":`Delete grant`,children:[U(`h3`,{children:`Delete grant`}),U(`button`,{ref:re,type:`button`,class:`danger-action`,disabled:ue.blocked||ve||e.unavailable,onClick:()=>{ie.current=re.current,te(`delete`)},children:`Delete grant`})]}),U(jn,{id:`http-grant-discard`,open:F,title:`Discard grant changes?`,consequence:`Your unsaved changes will be lost.`,confirmLabel:`Discard changes`,returnFocus:I,onCancel:()=>ne(!1),onConfirm:()=>e.onCancel?.()}),U(jn,{id:`http-grant-confirm`,open:P!==void 0,title:P===`delete`?`Delete HTTP grant`:`Apply HTTP grant`,consequence:P===`delete`?`Remove this grant. Other grants and the agent default still apply.`:U(S,{children:[t===void 0?U(`section`,{"aria-label":`Proposed grant`,children:[U(`h3`,{children:`Proposed grant`}),U(`dl`,{class:`detail-facts`,children:[U(`div`,{children:[U(`dt`,{children:`Description`}),U(`dd`,{children:u||`Unnamed HTTP grant`})]}),U(`div`,{children:[U(`dt`,{children:`Agent`}),U(`dd`,{children:[i.find(e=>e.id===c)?.displayName??`Agent`,` `,`· `,c]})]}),U(Pu,{policy:pe}),U(`div`,{children:[U(`dt`,{children:`Expires`}),U(`dd`,{children:U(Y,{value:me,fallback:`No expiry`})})]})]})]}):U(Fu,{current:t,proposed:{description:u,principal_id:c,policy:pe,expires_at:me},principals:i}),pe.type===`allow_tunnel`&&U(`p`,{children:`Opaque tunnel bypass: request method/path checks and credential injection do not apply inside this tunnel.`}),pe.allow_private&&U(`p`,{children:`Permits local/private destinations within this grant.`}),pe.credential_id!==void 0&&U(`p`,{children:`The selected credential will be injected into matching HTTPS requests.`})]}),confirmLabel:P===`delete`?`Delete grant`:`Apply grant`,destructive:P===`delete`,returnFocus:ie,onCancel:()=>te(void 0),onConfirm:ye})]})}function Hu(e){let[t,n]=z([]),[r,i]=z(``),[a,o]=z(!1),[s,c]=z(``),[l,u]=z(`GET`),[d,f]=z(``),[p,m]=z(``),[h,g]=z(`443`),[_,v]=z(),[y,b]=z(!1),[x,C]=z(!1),w=V(0);return B(()=>{let t=!0;return Qo(e.session).then(e=>{t&&n(e)}).catch(()=>{t&&b(!0)}),()=>{t=!1,w.current++}},[]),U(`section`,{class:`panel domain-panel`,children:[U(`p`,{children:`Policy only. No request is sent. Network, TLS and secret material are unverified; this result is not future admission authority.`}),U(`form`,{onInput:()=>{w.current++,v(void 0)},onSubmit:t=>{t.preventDefault();let n=++w.current;C(!0),b(!1),v(void 0),e.session.runProtected(async e=>{let t=JSON.stringify({principal_id:r,...a?{connect:{host:p,port:Number(h)}}:{url:s,method:l===`custom`?d:l}}),i=await fetch(`/api/v2/http/access-preview`,{method:`POST`,credentials:`same-origin`,redirect:`error`,signal:e.signal,headers:{"Content-Type":`application/json`,"X-CSRF-Token":e.csrfToken},body:t});if(await e.sessionLost(i))return;if(!i.ok)throw Error(`Preview unavailable.`);let o=St(await Du(i),r,a);w.current===n&&v(o)}).catch(()=>{w.current===n&&b(!0)}).finally(()=>C(!1))},children:[U(J,{id:`preview-principal`,label:`Agent`,...r?{hint:r}:{},children:e=>U(`select`,{...e,required:!0,value:r,onChange:e=>i(e.currentTarget.value),children:[U(`option`,{value:``,children:`Select agent`}),t.map(e=>U(`option`,{value:e.id,children:[e.displayName,t.filter(t=>t.displayName===e.displayName).length>1?` · ${e.id}`:``]}))]})}),U(J,{id:`preview-kind`,label:`Access type`,children:e=>U(`select`,{...e,value:a?`connect`:`request`,onChange:e=>o(e.currentTarget.value===`connect`),children:[U(`option`,{value:`request`,children:`HTTP request`}),U(`option`,{value:`connect`,children:`CONNECT destination`})]})}),a?U(S,{children:[U(J,{id:`preview-host`,label:`Host`,children:e=>U(`input`,{...e,required:!0,maxLength:253,value:p,onInput:e=>m(e.currentTarget.value)})}),U(J,{id:`preview-port`,label:`Port`,children:e=>U(`input`,{...e,required:!0,type:`number`,min:1,max:65535,value:h,onInput:e=>g(e.currentTarget.value)})})]}):U(S,{children:[U(J,{id:`preview-url`,label:`URL`,children:e=>U(`input`,{...e,required:!0,type:`url`,maxLength:8192,placeholder:`https://api.example.com/v1/resource`,value:s,onInput:e=>c(e.currentTarget.value)})}),U(J,{id:`preview-method`,label:`Method`,children:e=>U(`select`,{...e,value:l,onChange:e=>u(e.currentTarget.value),children:[[`GET`,`HEAD`,`POST`,`PUT`,`PATCH`,`DELETE`,`OPTIONS`,`TRACE`].map(e=>U(`option`,{value:e,children:e})),U(`option`,{value:`custom`,children:`Custom`})]})}),l===`custom`&&U(J,{id:`preview-custom-method`,label:`Custom method`,hint:`Use an uppercase HTTP method token. For CONNECT, select CONNECT destination above.`,children:e=>U(`input`,{...e,required:!0,maxLength:32,pattern:"(?!CONNECT$)[A-Z0-9!#$%&'*+.^_`\\|~\\-]+",value:d,onInput:e=>f(e.currentTarget.value)})})]}),U(`button`,{class:`form-submit-action`,disabled:x,children:`Test access`})]}),y&&U(K,{state:`error`,title:`Access preview unavailable`,children:U(`p`,{children:`Check the coordinates and current agent state.`})}),_!==void 0&&U(Uu,{result:_})]})}function Uu({result:e}){let t=mt(e.decision);return U(`section`,{class:`detail-group`,"aria-live":`polite`,children:[U(`h3`,{children:{destination_block:`Blocked by a destination grant`,request_block:`Blocked by a request grant`,request_allow:`Allowed by request policy`,principal_default:`Agent default: ${is(e.default)}`,tunnel_allow:`Opaque tunnel allowed; request policy and injection bypassed`,intercept_required:`Interception required; each decrypted request needs its own evaluation`,credential_conflict:`Blocked: matching grants require different credentials`,credential_unavailable:`Blocked: selected credential has no available material binding`,address_forbidden:`Blocked: destination address is forbidden`,private_permission_required:`Blocked: a matching local/private allow is required`}[String(t.reason)]??`Policy result unavailable`}),U(`dl`,{class:`detail-facts`,children:[U(`div`,{children:[U(`dt`,{children:`Policy revision`}),U(`dd`,{children:String(t.policy_revision)})]}),U(`div`,{children:[U(`dt`,{children:`HTTP default`}),U(`dd`,{children:is(e.default)})]}),U(`div`,{children:[U(`dt`,{children:`Default revision`}),U(`dd`,{children:String(t.default_revision)})]}),U(`div`,{children:[U(`dt`,{children:`Transport`}),U(`dd`,{children:String(t.transport)})]}),U(`div`,{children:[U(`dt`,{children:`Local/private permission`}),U(`dd`,{children:t.private_grant===void 0?`Explicit matching allow required`:`Matching permission present`})]}),U(`div`,{children:[U(`dt`,{children:`Agent`}),U(`dd`,{children:[U(`a`,{href:`#/agents/${String(mt(t.principal).id)}`,children:String(mt(t.principal).id)}),` `,`· revision `,String(mt(t.principal).revision)]})]}),[`grant`,`private_grant`,`credential`,`credential_grant`,`conflict_credential`,`conflict_grant`].map(e=>{if(t[e]===void 0)return null;let n=mt(t[e]);return typeof n.id!=`string`||!pt.test(n.id)?null:U(`div`,{children:[U(`dt`,{children:{grant:`Deciding grant`,private_grant:`Local/private grant`,credential:`Credential`,credential_grant:`Credential grant`,conflict_credential:`Conflicting credential`,conflict_grant:`Conflicting grant`}[e]}),U(`dd`,{children:[U(`a`,{href:`#/http/${e.includes(`credential`)&&!e.includes(`grant`)?`credentials`:`grants`}/${n.id}`,children:n.id}),` `,`· revision `,String(n.revision)]})]})})]})]})}var Wu=()=>({key:``,items:[],next:null,item:void 0,live:!0,paused:!1,loaded:!1,error:!1,olderError:!1,missing:!1,notice:``,loadingOlder:!1});async function Gu(e,t){let n=await fetch(t,{headers:{"X-CSRF-Token":e.csrfToken},credentials:`same-origin`,redirect:`error`,signal:e.signal});if(await e.sessionLost(n))throw Error(`Session lost.`);return n}async function Ku(e){if(e.status!==200||e.headers.get(`Content-Type`)!==`application/json`)throw Error(`HTTP traffic unavailable.`);let t=await e.text();if(new TextEncoder().encode(t).byteLength>1048576)throw Error(`HTTP traffic response exceeds limit.`);return He(t)}async function qu(e){if(e.status!==409||e.headers.get(`Content-Type`)!==`application/problem+json`)return!1;let t=await e.text();if(t.length>4096)return!1;let n=He(t);return typeof n==`object`&&!!n&&`code`in n&&n.code===`stale_cursor`}function Ju(e,t){let n=new URLSearchParams({limit:`50`});for(let[t,r]of Object.entries(e))n.set(t.slice(7),r);return e.filter_principal&&n.set(`search_locale`,Intl.DateTimeFormat().resolvedOptions().locale),t!==null&&n.set(`cursor`,t),`/api/v2/http/traffic?${n}`}var Yu=class{views;related;value=Wu();serial=0;continuation=null;listeners=new Set;constructor(e,t){this.views=t,this.related=new Jn(e,t,`http-related`,`http-traffic`,async(e,t)=>{let n=H(e.viewKey).segments[1],r=Gt(await Ku(await Gu(e,`/api/v2/http/traffic/${n}`)));if(r.admission.id!==n)throw Error(`Mismatched parent`);if(r.admission.decision?.transport!==`intercept`)return{items:[],next:null};let i=await Gu(e,Ju({filter_connect_id:n},t));if(await qu(i))throw new Kn;let a=Bt(await Ku(i));if(a.items.some(e=>e.connect?.id!==n))throw Error(`Mismatched connection`);return{items:a.items,next:a.nextCursor}}),t.registerPanel({id:`http-traffic`,matches:e=>H(e)?.destination===`http-traffic`,invalidations:[`system_status`],shouldRefresh:e=>![`invalidation`,`reconnect`,`poll`].includes(e)||H(this.views.snapshot().viewKey)?.segments.length===2||this.value.live&&!this.value.paused,read:e=>this.read(e),publish:e=>this.publish(e)}),e.registerProtectedState(()=>{this.serial++,this.continuation=null,this.value=Wu(),this.emit()})}snapshot(){return this.value}subscribe(e){return this.listeners.add(e),e(this.value),()=>this.listeners.delete(e)}setLive(e){this.views.cancelPanelRead(`http-traffic`),this.serial++,this.continuation=null,this.value={...this.value,live:e,loadingOlder:!1},this.emit(),(!this.value.loaded||e&&!this.value.paused)&&this.refresh()}refresh(){this.continuation=null,this.views.refreshPanel(`http-traffic`)}resume(){this.serial++,this.value={...this.value,paused:!1},this.emit(),this.refresh()}async older(){if(this.value.loadingOlder||this.value.error||this.value.next===null||this.value.items.length>=500||this.value.key!==this.views.snapshot().viewKey||this.views.snapshot().panels[`http-traffic`]?.refreshing)return;this.serial++;let e=this.serial;this.continuation=this.value.next,this.value={...this.value,paused:!0,loadingOlder:!0,olderError:!1},this.emit();try{await this.views.refreshPanel(`http-traffic`)}finally{e===this.serial&&(this.value={...this.value,loadingOlder:!1},this.emit())}}async read(e){let t=H(e.viewKey);if(t?.destination!==`http-traffic`)throw Error(`Invalid HTTP traffic location.`);this.value.key!==e.viewKey&&(this.serial++,this.continuation=null,this.value={...Wu(),key:e.viewKey,live:this.value.live,paused:this.value.paused,notice:this.value.paused&&t.segments.length===1?`Showing the latest entries. Older results could not be continued.`:``},this.emit());let n={key:e.viewKey,serial:this.serial,automatic:[`invalidation`,`reconnect`,`poll`].includes(e.reason??``)},r=t.segments[1];if(r!==void 0){let t=await Gu(e,`/api/v2/http/traffic/${r}`);if(t.status===404)return{...n,kind:`missing`};let i=Gt(await Ku(t));if(i.admission.id!==r)throw Error(`Mismatched HTTP traffic identity.`);return{...n,kind:`item`,item:i}}let i=e.reason===`panel`?this.continuation:null;this.continuation=null;let a=i!==null;try{let r=await Gu(e,Ju(t.query,i));if(a&&await qu(r)){if(e.signal.aborted)throw Error(`Superseded.`);a=!1,this.value={...this.value,items:[],next:null,loaded:!1,notice:`Showing the latest entries. Older results could not be continued.`},this.emit(),r=await Gu(e,Ju(t.query,null))}let o=Bt(await Ku(r));if(o.items.length>50)throw Error(`Invalid HTTP page size.`);if(a&&(this.value.items.length+o.items.length>500||o.items.some(e=>this.value.items.some(t=>t.id===e.id))))throw Error(`Repeated HTTP traffic evidence.`);return{...n,kind:`page`,page:o,append:a}}catch(t){if(e.signal.aborted)throw t;return{...n,kind:`failure`,append:a}}}publish(e){e.key!==this.value.key||e.automatic&&(e.serial!==this.serial||!this.value.live||this.value.paused)&&e.kind!==`item`&&e.kind!==`missing`||(this.value=e.kind===`page`?{...this.value,items:e.append?[...this.value.items,...e.page.items]:e.page.items,next:e.page.nextCursor,loaded:!0,error:!1,olderError:!1,loadingOlder:!1}:e.kind===`item`?{...this.value,item:e.item,error:!1,missing:!1}:e.kind===`missing`?{...this.value,item:void 0,missing:!0}:{...this.value,error:!e.append,olderError:e.append,loadingOlder:!1},this.emit())}emit(){for(let e of this.listeners)e(this.value)}};function Xu({controller:e,principals:t,view:n,navigate:r}){let[i,a]=z(e.snapshot()),[o,s]=z(t.snapshot());B(()=>e.subscribe(a),[e]),B(()=>t.subscribe(s),[t]);let c=H(n.viewKey),l=c?.query??{},u=i.key===n.viewKey?i:{...Wu(),live:i.live,paused:i.paused},d=e=>ln({destination:`http-traffic`,segments:e===void 0?[`http-traffic`]:[`http-traffic`,e],query:l}),f=n.panels[`http-traffic`];return c?.segments.length===2?U(`div`,{class:`domain-view`,children:[U(`nav`,{class:`detail-navigation`,"aria-label":`HTTP traffic navigation`,children:U(`a`,{href:d(),children:`Back to HTTP traffic`})}),U(`header`,{class:`detail-context`,"data-testid":`detail-context`,children:[U(`div`,{class:`detail-context-heading`,children:[U(`h1`,{id:`http-traffic-page-title`,tabindex:-1,children:u.item?.admission.target?u.item.admission.target.scheme?`HTTP request`:`CONNECT exchange`:`HTTP traffic`}),u.item&&U(ed,{item:u.item,stale:f?.status===`error`})]}),U(`div`,{class:`copyable-value`,children:U(`code`,{children:c.segments[1]})})]}),u.missing?U(K,{state:`empty`,title:`Traffic record unavailable`,children:`It may have been pruned. Missing evidence does not prove nonexecution.`}):u.item===void 0?U(K,{state:f?.status===`error`?`error`:`loading`,title:f?.status===`error`?`HTTP traffic unavailable`:`Loading HTTP traffic…`}):U(S,{children:[f?.status===`error`&&U(K,{state:`error`,title:`Refresh failed. This evidence may be stale.`}),U(td,{item:u.item,link:d}),u.item.admission.decision?.transport===`intercept`&&U(Qu,{controller:e.related,view:n,link:d})]})]}):U(`section`,{class:`panel domain-panel`,"aria-label":`HTTP traffic history`,"data-testid":`http-traffic-view`,children:[U(`div`,{class:`collection-toolbar live-collection-toolbar`,children:[U(`label`,{for:`http-traffic-live-mode`,children:`Live mode`}),U(On,{attributes:{id:`http-traffic-live-mode`},checked:u.live,showState:!1,onChange:t=>e.setLive(t)})]}),U(Zu,{query:l,navigate:r}),u.paused&&U(`div`,{class:`inline-actions`,children:[u.live&&U(G,{state:`warning`,children:`Live paused while viewing older results`}),U(`button`,{type:`button`,onClick:()=>e.resume(),children:u.live?`Resume live`:`Return to newest`})]}),u.notice&&U(K,{state:`warning`,title:u.notice}),(u.error||f?.status===`error`)&&U(K,{state:`error`,title:`HTTP traffic unavailable`,children:`Previously loaded traffic may be stale.`}),u.loaded?U(S,{children:[U(Dn,{caption:`HTTP traffic records`,localStale:u.error||u.olderError||f?.status===`error`,layout:`activity`,rowHeaderKey:`destination`,rowKey:e=>e.id,items:u.items,itemNames:{singular:`traffic record`,plural:`traffic records`},emptyTitle:Object.keys(l).length?`No matching HTTP traffic`:`No HTTP traffic yet`,columns:[{key:`admitted`,role:`time`,label:`Admitted`,render:e=>U(Y,{value:e.admitted_at})},{key:`destination`,role:`identity`,label:`Destination`,render:e=>U(q,{primary:U(`a`,{href:d(e.id),children:Kt(e.target)}),secondary:e.id})},{key:`principal`,role:`relation`,label:`Agent`,render:e=>U(q,{primary:U(`a`,{href:`#/agents/${e.principal_id}`,children:o.get(e.principal_id)??`Agent`}),secondary:e.principal_id})},{key:`type`,role:`status`,label:`Type`,render:e=>W(e.type)},{key:`decision`,role:`text`,label:`Decision`,render:e=>U(S,{children:[U(G,{state:e.decision===`allow`?`current`:`neutral`,children:Ut(e.decision,e.type)}),e.type===`invalid`&&e.rejection!==void 0&&U(`div`,{children:Nt(e.rejection)})]})},{key:`outcome`,role:`status`,label:`Outcome`,render:e=>U(S,{children:[U(G,{state:Ht(e)===`succeeded`?`current`:Ht(e)===`outcome_unknown`?`warning`:[`not_dispatched`,`interception_selected`].includes(Ht(e))?`neutral`:`error`,children:e.decision===`intercept`?`—`:W(Ht(e))}),e.type===`request`&&e.decision===`allow`&&U(`div`,{children:zt(e.completion_recorded,e.termination)})]})}]}),U(`div`,{class:`history-continuation`,children:[u.loaded&&u.next===null&&!u.error&&!u.olderError&&f?.status!==`error`&&U(`span`,{children:`No older HTTP traffic records`}),u.loaded&&U(hn,{count:u.items.length,singular:`HTTP traffic record`,plural:`HTTP traffic records`,matching:Object.keys(l).length>0,stale:u.error||f?.status===`error`}),u.next!==null&&u.items.length<500&&!u.error&&f?.status!==`error`&&U(`button`,{type:`button`,disabled:u.loadingOlder,onClick:()=>void e.older(),children:u.loadingOlder?`Loading…`:`Load older HTTP traffic records`})]}),u.olderError&&U(K,{state:`error`,title:`Older traffic unavailable`,children:`Loaded records are retained. Use Load older HTTP traffic records to try this read again.`}),u.items.length>=500&&U(`p`,{children:`500 records loaded. Narrow the filters or return to newest.`})]}):!u.error&&f?.status!==`error`?U(K,{state:`loading`,title:`Loading HTTP traffic…`}):null]})}function Zu({query:e,navigate:t}){let[n,r]=z({...e}),[i,a]=z(!1);B(()=>{r({...e}),a(!1)},[JSON.stringify(e)]);let o=n=>{let r=Object.fromEntries(Object.entries(n).filter(([,e])=>e!==``));if(!Tt(r)){a(!0);return}a(!1),JSON.stringify(r)!==JSON.stringify(e)&&t(ln({destination:`http-traffic`,segments:[`http-traffic`],query:r}))};return mn(n,o),U(S,{children:[U(Wn,{query:e}),U(`div`,{class:`table-filters collection-query-filters`,role:`group`,"aria-label":`HTTP traffic filters`,children:[[[`destination`,`Destination host`],[`principal`,`Agent`]].map(([e,t])=>U(`input`,{type:`search`,"aria-label":t,placeholder:t,value:n[`filter_${e}`]??``,onInput:t=>r({...n,[`filter_${e}`]:t.currentTarget.value})})),Object.entries(wt).map(([e,t])=>U(`select`,{"aria-label":W(e),value:n[`filter_${e}`]??``,onChange:t=>{let i={...n,[`filter_${e}`]:t.currentTarget.value};r(i),o(i)},children:[U(`option`,{value:``,children:[W(e),`: any`]}),t.map(t=>U(`option`,{value:t,children:e===`decision`&&t===`intercept`?`Interception selected`:W(t)}))]})),U(`button`,{type:`button`,disabled:!Object.values(n).some(Boolean)&&!Object.values(e).some(Boolean),onClick:()=>{r({}),o({})},children:`Reset`})]}),(e.filter_connect_id||e.filter_principal_id)&&U(`div`,{class:`table-filters`,role:`group`,"aria-label":`HTTP traffic context filters`,children:[e.filter_connect_id&&U(`span`,{class:`inline-actions`,children:[`Related to CONNECT`,` `,U(`a`,{href:ln({destination:`http-traffic`,segments:[`http-traffic`,e.filter_connect_id],query:{}}),children:U(`code`,{children:e.filter_connect_id})}),U(`button`,{type:`button`,onClick:()=>{let e={...n};delete e.filter_connect_id,r(e),o(e)},children:`Remove connection filter`})]}),e.filter_principal_id&&U(`span`,{class:`inline-actions`,children:[`Exact agent ID: `,U(`code`,{children:e.filter_principal_id}),U(`button`,{type:`button`,onClick:()=>{let e={...n};delete e.filter_principal_id,r(e),o(e)},children:`Remove exact agent filter`})]})]}),i&&U(K,{state:`error`,title:`Use searches of at most 256 UTF-8 bytes without control characters.`})]})}function Qu({controller:e,view:t,link:n}){let[r,i]=z(e.snapshot());B(()=>e.subscribe(i),[e]);let a=r.key===t.viewKey?r:void 0;return U(`section`,{class:`panel domain-panel`,"aria-label":`Requests on this connection`,children:[U(`div`,{class:`panel-heading`,children:[U(`h2`,{children:`Requests on this connection`}),U(`button`,{type:`button`,disabled:a?.loading,onClick:()=>e.refresh(),children:`Refresh requests`})]}),a?.notice&&U(K,{state:`warning`,title:a.notice}),a?.error&&U(K,{state:`error`,title:`Related requests unavailable`,children:`Previously loaded requests may be stale. Refresh to try again.`}),!a?.loaded&&!a?.error&&U(K,{state:`loading`,title:`Loading related requests…`}),a?.loaded&&U(Dn,{caption:`Related HTTP requests`,layout:`activity`,rowHeaderKey:`request`,rowKey:e=>e.id,items:a.items,emptyTitle:`No related requests recorded`,localStale:a.error,columns:[{key:`time`,label:`Admitted`,role:`time`,render:e=>U(Y,{value:e.admitted_at})},{key:`request`,label:`Request`,role:`identity`,render:e=>U(q,{primary:U(`a`,{href:n(e.id),children:Kt(e.target)}),secondary:e.id})},{key:`decision`,label:`Decision`,role:`status`,render:e=>U(G,{state:e.decision===`allow`?`current`:`neutral`,children:Ut(e.decision,e.type)})},{key:`outcome`,label:`Outcome`,role:`status`,render:e=>U(G,{state:Ht(e)===`succeeded`?`current`:Ht(e)===`outcome_unknown`?`warning`:[`not_dispatched`,`interception_selected`].includes(Ht(e))?`neutral`:`error`,children:e.decision===`intercept`?`—`:W(Ht(e))})}]}),U(`div`,{class:`collection-pagination`,children:[a?.loaded&&U(hn,{count:a.items.length,singular:`request`,plural:`requests`,matching:!1,stale:a.error}),a?.next&&a.items.length<500&&U(`button`,{type:`button`,disabled:a.loading,onClick:()=>e.more(),children:`Load older requests`})]})]})}function $u(e){return e===`gateway`?`Gateway`:e===`upstream`?`Upstream`:`Unavailable`}function ed({item:e,stale:t}){let n=e.admission.decision,r=n?.transport===`intercept`?`interception_selected`:e.completion?.outcome?String(e.completion.outcome):n?.allowed?`outcome_unknown`:`not_dispatched`;return U(G,{state:t?`stale`:r===`succeeded`?`current`:r===`outcome_unknown`?`warning`:[`not_dispatched`,`interception_selected`].includes(r)?`neutral`:`error`,children:W(r)})}function td({item:e,link:t}){let n=e.admission,r=n.decision,i=e.completion,a=i?.termination,o=n.rejection,s=n.connect,c=r?.transport===`intercept`&&r?.reason===`intercept_required`,l=n.target!==null&&n.target.scheme===void 0;return U(S,{children:[U(`section`,{class:`detail-section`,children:[U(`h2`,{children:`Admission`}),U(`dl`,{class:`detail-facts`,children:[U(`div`,{children:[U(`dt`,{children:`Destination`}),U(`dd`,{children:Kt(n.target)})]}),U(`div`,{children:[U(`dt`,{children:`Admitted`}),U(`dd`,{children:U(Y,{value:String(n.admitted_at)})})]}),U(`div`,{children:[U(`dt`,{children:`Decision time`}),U(`dd`,{children:U(Y,{value:String(n.evaluated_at)})})]}),U(`div`,{children:[U(`dt`,{children:`Reason`}),U(`dd`,{children:r===null?Nt(o):c?`Interception selected`:l?r.allowed?`Opaque tunnel allowed`:`CONNECT denied`:W(String(r.reason))})]}),U(`div`,{children:[U(`dt`,{children:`Transport`}),U(`dd`,{children:r===null?`None`:W(String(r.transport))})]})]}),o!==void 0&&U(`details`,{children:[U(`summary`,{children:`Rejection codes`}),U(`p`,{children:[o.stage,` · `,o.reason]})]}),!l&&U(`dl`,{class:`detail-facts`,children:[U(`div`,{children:[U(`dt`,{children:`Connection`}),U(`dd`,{children:s===void 0?`Unavailable`:U(`a`,{href:t(s.id),children:[`CONNECT `,s.host,`:`,s.port,` ·`,` `,U(`code`,{children:s.id})]})})]}),s!==void 0&&U(`div`,{children:[U(`dt`,{children:`Destination inherited from CONNECT`}),U(`dd`,{children:Kt({host:s.host,port:s.port})})]})]}),s!==void 0&&U(`p`,{children:`Connection context does not validate the inner request target.`}),r?.transport===`tunnel`&&U(`p`,{children:`Opaque tunnel: inner HTTP requests are not visible.`})]}),U(`section`,{class:`detail-section`,children:[U(`h2`,{children:`Outcome`}),U(`dl`,{class:`detail-facts`,children:U(`div`,{children:[U(`dt`,{children:`Response source`}),U(`dd`,{children:$u(o===void 0?i?.response_source:`gateway`)})]})}),o!==void 0&&U(`p`,{children:`Gateway rejection. Response delivery is not recorded.`}),i===null?U(K,{state:r?.allowed?`warning`:`neutral`,title:c?`Interception selected`:r?.allowed?`Unknown outcome`:l?`CONNECT denied`:`Not dispatched`,children:c?Wt:r?.allowed?`Missing terminal evidence does not prove nonexecution or safe retry.`:void 0}):U(`dl`,{class:`detail-facts`,children:Object.entries(i).filter(([e])=>e!==`response_source`&&e!==`termination`).map(([e,t])=>U(`div`,{children:[U(`dt`,{children:W(e)}),U(`dd`,{children:e===`completed_at`?U(Y,{value:String(t)}):W(String(t))})]}))}),!l&&r?.allowed&&U(`dl`,{class:`detail-facts`,children:[U(`div`,{children:[U(`dt`,{children:`HTTP transfer`}),U(`dd`,{children:zt(i!==null,a)})]}),a!==void 0&&U(S,{children:[U(`div`,{children:[U(`dt`,{children:`Observed stage`}),U(`dd`,{children:W(a.stage)})]}),U(`div`,{children:[U(`dt`,{children:`Observed condition`}),U(`dd`,{children:W(a.condition)})]}),a.context!==void 0&&U(`div`,{children:[U(`dt`,{children:`Request context`}),U(`dd`,{children:W(a.context)})]})]})]}),a!==void 0&&U(`details`,{children:[U(`summary`,{children:`Transfer evidence limits`}),U(`p`,{children:`HTTP transfer evidence does not establish application success or who initiated cancellation.`})]}),!l&&i?.outcome===`outcome_unknown`&&U(`p`,{children:`The request may have taken effect. Retrying may repeat effects.`})]}),U(`section`,{class:`detail-section`,children:[U(`h2`,{children:`Admission-time authority`}),U(`dl`,{class:`detail-facts`,children:[[[`Agent`,n.principal],[`Agent credential`,n.agent_credential]].map(([e,t])=>{let n=t;return U(`div`,{children:[U(`dt`,{children:String(e)}),U(`dd`,{children:[U(`code`,{children:n.id}),` · revision `,n.revision]})]})}),r!==null&&U(S,{children:[U(`div`,{children:[U(`dt`,{children:`Policy revision`}),U(`dd`,{children:String(r.policy_revision)})]}),U(`div`,{children:[U(`dt`,{children:`Default`}),U(`dd`,{children:[W(String(n.default)),` · revision`,` `,String(r.default_revision)]})]})]})]}),U(`details`,{children:[U(`summary`,{children:`Exact authority references`}),U(yn,{value:{decision:n.decision,material:n.material},label:`Admission-time references`})]}),U(`details`,{children:[U(`summary`,{children:`Matched policy selectors`}),U(yn,{value:n.grants,label:`Recorded policy selectors`})]})]})]})}var nd=/^[0-7][0-9A-HJKMNP-TV-Z]{25}$/,rd={days:86400,hours:3600,minutes:60,seconds:1};function id(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`invalid response`);let n=e;if(Object.keys(n).sort().join(`,`)!==[...t].sort().join(`,`))throw Error(`invalid response`);return n}function ad(e){if(typeof e!=`string`)throw Error(`invalid response`);return e}function od(e){if(e!==null&&typeof e!=`string`)throw Error(`invalid response`);return e}function sd(e){let t=ad(e);if(!nd.test(t))throw Error(`invalid response`);return t}function cd(e){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`invalid response`);return e}function ld(e,t){let n=ad(e);if(!t.includes(n))throw Error(`invalid response`);return n}function ud(e,t){return e===null?null:ld(e,t)}function dd(e){let t=id(e,[..._r(e),`scope`,`target`,`constraint`,`duration_seconds`,`future_tools_acknowledged`]);if(t.constraint!==null&&(typeof t.constraint!=`object`||Array.isArray(t.constraint))||typeof t.future_tools_acknowledged!=`boolean`)throw Error(`invalid response`);let n=vr(t);if(n&&(t.scope!==`server`||t.constraint!==null||t.future_tools_acknowledged!==!0))throw Error(`invalid response`);return{readOnly:n,scope:ld(t.scope,[`tool`,`server`]),target:ad(t.target),constraint:t.constraint,durationSeconds:od(t.duration_seconds),futureToolsAcknowledged:t.future_tools_acknowledged}}var fd=[`id`,`principal_id`,`state`,`revision`,`requested_policy`,`approved_policy`,`approved_grant_id`,`rejection_reason`,`created_at`,`updated_at`,`closed_at`];function pd(e){let t=id(e,fd),n=od(t.approved_grant_id);if(n!==null&&!nd.test(n))throw Error(`invalid response`);return{id:sd(t.id),principalID:sd(t.principal_id),state:ld(t.state,[`pending`,`approved`,`rejected`,`cancelled`]),revision:ad(t.revision),requestedPolicy:dd(t.requested_policy),approvedPolicy:t.approved_policy===null?null:dd(t.approved_policy),approvedGrantID:n,rejectionReason:od(t.rejection_reason),createdAt:ad(t.created_at),updatedAt:ad(t.updated_at),closedAt:od(t.closed_at)}}function md(e){let t=id(e,[`server_id`,`tool_id`,`namespace`,`upstream_name`,`external_name`,`catalog_revision`,`fingerprint`,`durable_state`,`descriptor`,`captured_at`]);return{serverID:sd(t.server_id),toolID:sd(t.tool_id),namespace:ad(t.namespace),upstreamName:ad(t.upstream_name),externalName:ad(t.external_name),catalogRevision:ad(t.catalog_revision),fingerprint:ad(t.fingerprint),durableState:ld(t.durable_state,[`current`,`retired`]),descriptor:cd(t.descriptor),capturedAt:ad(t.captured_at)}}function hd(e){let t=id(e,[`scope`,`target_state`,`active_state`,`durable_state`,`catalog_revision`,`fingerprint`,`descriptor`]);return{scope:ld(t.scope,[`tool`,`server`]),targetState:ld(t.target_state,[`extant`,`deleted`]),activeState:ud(t.active_state,[`current`,`stale`,`absent`,`unavailable`]),durableState:ud(t.durable_state,[`current`,`retired`,`absent`]),catalogRevision:od(t.catalog_revision),fingerprint:od(t.fingerprint),descriptor:t.descriptor===null?null:cd(t.descriptor)}}function gd(e,t,n){let r=id(e,[...fd,`resolved_server_id`,`resolved_upstream_name`,`submitted_evidence`,`approved_evidence`,`current_target`]),i=pd(Object.fromEntries(fd.map(e=>[e,r[e]]))),a=od(r.resolved_upstream_name);return{...i,submittedConstraintSource:xd(n),approvedConstraintSource:xd(n,`approved_policy`),approvedPolicySource:i.approvedPolicy===null?null:bd(n,`approved_policy`),resolvedServerID:sd(r.resolved_server_id),resolvedUpstreamName:a,submittedEvidence:r.submitted_evidence===null?null:md(r.submitted_evidence),approvedEvidence:r.approved_evidence===null?null:md(r.approved_evidence),currentTarget:hd(r.current_target),etag:t}}function _d(e){return{Accept:`application/json`,"X-CSRF-Token":e.csrfToken}}function vd(e,t){if(e[t]!==`"`)throw Error(`invalid response`);for(let n=t+1;n{let n=await fetch(t,{credentials:`same-origin`,redirect:`error`,signal:e.signal,headers:_d(e)});if(await e.sessionLost(n))return;let r=n.headers.get(`Content-Type`);if(r!==`application/json`&&r!==`application/problem+json`)throw Error(`Request data is unavailable.`);let i=await n.text();return{response:n,value:JSON.parse(i),source:i}})}function Cd(e){let t=id(e,[`request`,`principal_display_name`,`server_display_name`,`resolved_server_id`,`resolved_upstream_name`]);return{...pd(t.request),principalName:ad(t.principal_display_name),serverName:ad(t.server_display_name),serverID:sd(t.resolved_server_id),upstreamName:od(t.resolved_upstream_name)}}function wd(e,t,n,r){let i=new URLSearchParams({limit:`50`,sort:t.sort??`submitted`,direction:t.direction??(t.sort===void 0&&t.queue===`all`?`descending`:`ascending`)});for(let e of[`request`,`principal`,`target`,`scope`,`state`]){let n=t[`filter_${e}`];n!==void 0&&i.set(e,n)}return t.queue!==`all`&&i.set(`state`,`pending`),n!==null&&i.set(`cursor`,n),Mr(e,`/api/v2/mcp/grant-requests?${i}`,Cd,r)}async function Td(e,t){let n=await Sd(e,`/api/v2/mcp/grant-requests/${t}`);if(n===void 0)return;if(!n.response.ok)throw Error(`Request data is unavailable.`);let r=n.response.headers.get(`ETag`);if(r===null||r!==`"grant-request-${t}-${n.value.revision}"`)throw Error(`The current request revision is unavailable.`);return gd(n.value,r,n.source)}function Ed(e){if(e===null)return`No expiry`;for(let[t,n]of Object.entries(rd))if(Number(e)%n===0){let r=Number(e)/n;return`${r} ${r===1?t.slice(0,-1):t}`}return`${e} seconds`}function Dd({source:e,locked:t=!1}){if(e===null||e===``)return U(`p`,{children:`No argument restrictions`});try{let n=Pd(JSON.parse(e));return U(`div`,{children:[U(`ul`,{class:`request-conditions`,children:[`equals`,`regex`].flatMap(r=>Object.keys(n[r]).map(n=>U(`li`,{children:[t&&U(`strong`,{children:`Locked · `}),U(`code`,{children:n}),` `,r===`equals`?`equals`:`matches`,` `,U(`code`,{children:bd(bd(e,r),n)})]})))}),U(`details`,{children:[U(`summary`,{children:`Exact condition source`}),U(`textarea`,{"aria-label":`Exact condition source`,"data-testid":t?`approval-submitted-constraint`:void 0,class:`inert-json`,readOnly:!0,value:e})]})]})}catch{return U(K,{state:`error`,title:`Conditions unavailable`})}}function Od({policy:e,source:t,definition:n}){return U(`div`,{class:`request-access-summary`,children:[e.readOnly&&U(`p`,{children:`Includes current and future tools marked readOnlyHint=true. The Gateway does not verify that these tools are read-only; they may still change data.`}),U(`dl`,{class:`detail-facts`,children:[U(`div`,{children:[U(`dt`,{children:`Duration`}),U(`dd`,{children:[Ed(e.durationSeconds),e.durationSeconds!==null&&` from approval`]})]}),U(`div`,{children:[U(`dt`,{children:`Tool definition`}),U(`dd`,{children:n})]})]}),U(`section`,{"aria-label":`Conditions`,children:[U(`h3`,{children:`Conditions`}),U(Dd,{source:t})]})]})}function kd(e){let t=e.approvedPolicy??e.requestedPolicy,n=e.currentTarget.targetState===`deleted`?`The requested server has been deleted. `:e.currentTarget.durableState===`retired`?`Only a historical tool definition is available. `:e.currentTarget.activeState===`unavailable`?`The current tool definition is unavailable. `:``;if(t.scope===`server`)return`${n}Not applicable to server-wide authority`;let r=e.approvedPolicy!==null&&e.requestedPolicy.scope===`server`,i=r?e.approvedEvidence:e.submittedEvidence,a=r?`approval`:`submission`,o=r?`approved`:`submitted`,s=r?`${t.target} — `:``;return i===null||e.currentTarget.fingerprint===null||e.currentTarget.descriptor===null?`${n}${s}Comparison unavailable — missing tool definition`:n+s+(i.fingerprint===e.currentTarget.fingerprint?`Unchanged since ${a}`:`Changed since ${a} — inspect ${o} and current definitions`)}function Ad(e){return e.readOnly?`Read-only server tools`:e.scope===`server`?`All tools`:`Exact tool`}function jd(e){return U(`dl`,{class:`detail-facts`,children:[U(`div`,{children:[U(`dt`,{children:`Scope`}),U(`dd`,{children:[W(e.scope),` — `,Ad(e)]})]}),U(`div`,{children:[U(`dt`,{children:`Target`}),U(`dd`,{children:e.target})]}),U(`div`,{children:[U(`dt`,{children:`Duration`}),U(`dd`,{children:Ed(e.durationSeconds)})]}),U(`div`,{children:[U(`dt`,{children:`Future tools acknowledged`}),U(`dd`,{children:e.futureToolsAcknowledged?`Yes`:`No`})]})]})}function Md(e,t){let n=e=>[{label:`Access`,value:Ad(e)},{label:`Scope`,value:W(e.scope)},{label:`Tools`,value:e.target},{label:`Duration`,value:Ed(e.durationSeconds)},{label:`Future tools acknowledged`,value:e.futureToolsAcknowledged?`Yes`:`No`}],r=n(e);return U(xn,{label:`Requested versus approved authority`,beforeLabel:`Requested`,afterLabel:`Approved`,rows:n(t).map((e,t)=>({label:e.label,before:r[t].value,after:e.value,changed:r[t].value!==e.value}))})}function Nd({evidence:e,label:t}){return e===null?U(K,{state:`empty`,title:`${t}: no descriptor evidence`}):U(`section`,{class:`detail-group`,children:[U(`h3`,{children:[t,`: immutable descriptor evidence`]}),U(`p`,{children:e.durableState===`retired`?`Retired historical evidence; it is not proof of a callable tool.`:`Current when captured; current target comparison remains authoritative for present state.`}),U(`dl`,{class:`detail-facts`,children:[U(`div`,{children:[U(`dt`,{children:`Namespace / tool`}),U(`dd`,{children:[e.namespace,` / `,e.upstreamName]})]}),U(`div`,{children:[U(`dt`,{children:`Catalog revision`}),U(`dd`,{children:e.catalogRevision})]}),U(`div`,{children:[U(`dt`,{children:`Fingerprint`}),U(`dd`,{class:`technical-value`,children:e.fingerprint})]}),U(`div`,{children:[U(`dt`,{children:`Captured`}),U(`dd`,{children:U(Y,{value:e.capturedAt})})]})]}),U(`a`,{href:`#/mcp/servers/${e.serverID}/descriptors/${e.toolID}`,children:`Open retained descriptor`}),U(yn,{value:e.descriptor,label:`${t} normalized descriptor`})]})}function Pd(e){let t=cd(e),n=Object.keys(t),r=n.length===1&&n[0]===`equals`?1:t.version===2&&n.every(e=>[`version`,`equals`,`regex`].includes(e))&&(t.equals!==void 0||t.regex!==void 0)?2:void 0;if(r===void 0)throw Error(`invalid constraint`);let i=t.equals===void 0?{}:cd(t.equals),a=t.regex===void 0?{}:cd(t.regex),o=Object.keys(i).length+Object.keys(a).length;if(o<1||o>16||Object.values(i).some(e=>typeof e==`object`&&!!e)||Object.values(a).some(e=>typeof e!=`string`))throw Error(`invalid constraint`);return{version:r,equals:i,regex:a}}function Fd(e){if(e===void 0)return``;let t=e.trim();if(!t.startsWith(`{`)||!t.endsWith(`}`))throw Error(`invalid constraint`);return t.slice(1,-1).trim()}function Id(e,t){if(t===``)return e===null?``:Pd(JSON.parse(e)).version===2?e:`{"version":2,"equals":${bd(e,`equals`)}}`;let n;try{n=JSON.parse(t)}catch{throw Error(`Additional matcher atoms must be valid JSON.`)}let r=Pd(n);if(e===null)return t;if(r.version!==2)throw Error(`Additional matcher atoms must use version 2.`);let i=Pd(JSON.parse(e));for(let e of[`equals`,`regex`])if(Object.keys(r[e]).some(t=>Object.hasOwn(i[e],t)))throw Error(`Additional matcher atoms cannot replace a submitted operator and pointer.`);let a=`{"version":2,${[`equals`,`regex`].map(n=>{let r=[Fd(bd(e,n)),Fd(bd(t,n))].filter(e=>e!==``);return r.length===0?``:`${JSON.stringify(n)}:{${r.join(`,`)}}`}).filter(e=>e!==``).join(`,`)}}`;return Pd(JSON.parse(a)),a}function Ld({session:e,mutations:t,detail:n,onRefresh:r,onAcknowledged:i,onUncertain:a,principalName:o,serverName:s,readAvailable:c}){let l=n.requestedPolicy,[u]=z(()=>t.create()),[d,f]=z(()=>u.snapshot()),[p,m]=z(`approve`),[h,g]=z(!1),[_,v]=z(!1),[y,b]=z(!1),x=V(`not_approved`),C=V(),w=V(null),[T,E]=z(``),[D,O]=z(l.scope),[k,A]=z(l.readOnly),[j,M]=z(l.target),[N,ee]=z(),[P,te]=z(),[F,ne]=z(!1),[I,re]=z(!1),[ie,ae]=z([]),oe=Object.keys(rd).find(e=>l.durationSeconds!==null&&Number(l.durationSeconds)%rd[e]===0)??`minutes`,[se,ce]=z(oe),[L,le]=z(l.durationSeconds===null?``:String(Number(l.durationSeconds)/rd[oe])),ue=se===`seconds`?`60`:`1`,de=Number(ue)*rd[se]<=Math.min(2592e3,Number(l.durationSeconds??2592e3)),fe=L===``?``:String(Number(L)*rd[se]),[R,pe]=z(`not_approved`),me=V({description:``,scope:l.scope,readOnly:l.readOnly,target:l.target,additionalAtoms:[],duration:l.durationSeconds??``,reason:`not_approved`}),he=JSON.stringify({description:T,scope:D,readOnly:k,target:j,additionalAtoms:ie,duration:fe,reason:R}),ge=V(he);ge.current=he,Cr(he!==JSON.stringify(me.current));let[_e,ve]=z(),[ye,be]=z(!1),[xe,Se]=z(),[Ce,we]=z(!1),Te=V(null),Ee=V(null);B(()=>u.subscribe(f),[u]),B(()=>()=>u.close(),[u]);let De=l.scope===`server`&&D===`tool`;B(()=>{let t=new AbortController;return ne(!1),ee(void 0),De&&ko(e,n.resolvedServerID,t.signal).then(e=>{!t.signal.aborted&&e!==void 0&&ee(e)}).catch(()=>{t.signal.aborted||ne(!0)}),()=>t.abort()},[n.resolvedServerID,De,e]);let Oe=async e=>{if(e.headers.get(`Content-Type`)!==`application/json`)throw Error(`invalid response`);let t=await e.text(),n=JSON.parse(t),r=e.headers.get(`ETag`);if(r===null)throw Error(`invalid response`);return gd(n,r,t)},ke=N?.find(e=>e.externalName===j);B(()=>{let t=new AbortController;return re(!1),te(void 0),!De||ke===void 0||Ao(e,ke,t.signal).then(e=>{!t.signal.aborted&&e!==void 0&&te(e)}).catch(()=>{t.signal.aborted||re(!0)}),()=>t.abort()},[n.resolvedServerID,De,ke,e]);let Ae=De?P===void 0||P.serverID!==n.resolvedServerID||P.externalName!==j||P.id!==ke?.id?void 0:To(P.descriptor):n.currentTarget.descriptor===null?void 0:To(n.currentTarget.descriptor),je=j===``?`Choose a tool`:F?`Unavailable`:N===void 0?`Loading…`:ke===void 0?`Unknown`:`Known`,Me=F?`Catalog unavailable. Manual entry is still available.`:ke===void 0?null:I?`Schema unavailable. Manual conditions are still available.`:Ae===void 0?`Loading schema…`:null,Ne=()=>ie.length===0?``:Fo(ie),Pe=()=>{if(l.readOnly&&(!k||D!==`server`))throw Error(`A read-only server request must retain read-only server scope.`);if(k&&D!==`server`)throw Error(`Read-only access requires server scope.`);if(l.scope===`tool`&&(D!==`tool`||j!==l.target))throw Error(`A tool request cannot change scope or target.`);if(l.scope===`server`&&D===`server`&&j!==l.target)throw Error(`A server approval cannot broaden to another target.`);if(j.length===0)throw Error(`Approval target is required.`);if(l.scope===`server`&&D===`tool`&&!j.startsWith(`${l.target}.`))throw Error(`Choose a tool on the requested server.`);let e;try{e=Id(n.submittedConstraintSource,Ne())}catch(e){throw e instanceof Error&&e.message.startsWith(`Additional `)?e:Error(`Constraint must use the supported matcher shape.`)}let t=e===``?null:JSON.parse(e);if(D===`server`&&t!==null)throw Error(`Server approval cannot include a constraint.`);let r=document.getElementById(`approval-duration`);if(r!==null&&!r.validity.valid)throw Error(`Enter a positive whole-number duration and choose its unit.`);if(fe!==``){if(!/^[1-9][0-9]*$/.test(L)||!/^[1-9][0-9]*$/.test(fe))throw Error(`Enter a positive whole-number duration and choose its unit.`);let e=Number(fe);if(e<60||e>2592e3)throw Error(`Duration must be between 1 minute and 30 days.`);if(l.durationSeconds!==null&&BigInt(fe)>BigInt(l.durationSeconds))throw Error(`Approval cannot extend the submitted duration.`)}else if(l.durationSeconds!==null)throw Error(`A temporary request cannot become permanent.`);return{scope:D,readOnly:k,target:j,constraint:t,durationSeconds:fe===``?null:fe,futureToolsAcknowledged:D===`server`}},Fe,Ie=(()=>{try{return Id(n.submittedConstraintSource,Ne())}catch(e){return Fe=e instanceof Error?e.message:`Invalid conditions`,``}})(),Le=`{"description":${T===``?`null`:JSON.stringify(T)},"approved_policy":{"scope":${JSON.stringify(D)},"target":${JSON.stringify(j)},"constraint":${Ie===``?`null`:Ie},"duration_seconds":${fe===``?`null`:JSON.stringify(fe)},"future_tools_acknowledged":${String(D===`server`)}${yr(k)}}}`,Re=async(t,r=!1)=>{let i=ge.current;m(t),v(r),ve(void 0);try{let a;if(t===`approve`){if(T.length>0&&(T.trim()!==T||new TextEncoder().encode(T).length>256))throw Error(`Grant description must be at most 256 bytes without surrounding whitespace.`);if(gn(T))throw Error(`Grant description cannot contain control characters.`);let t=r?l:Pe(),o=Id(n.submittedConstraintSource,r?``:Ne());if(o!==``){be(!0);let t=await Bo(e,o);if(t===void 0||ge.current!==i)return;if(t!==null)throw Error(t)}let s=o===``?`null`:o;a=`{"description":${T===``?`null`:JSON.stringify(T)},"approved_policy":{"scope":${JSON.stringify(t.scope)},"target":${JSON.stringify(t.target)},"constraint":${s},"duration_seconds":${t.durationSeconds===null?`null`:JSON.stringify(t.durationSeconds)},"future_tools_acknowledged":${String(t.futureToolsAcknowledged)}${yr(t.readOnly)}}}`}else a=JSON.stringify({reason:R});let o={route:`/api/v2/mcp/grant-requests/${n.id}/${t}`,method:`POST`,body:a,precondition:n.etag,requiresPrecondition:!0,idempotency:`none`,successStatuses:[200],decode:async e=>{let n=await Oe(e);if(t===`approve`&&(n.approvedPolicy===null||n.approvedPolicy.readOnly!==(r?l.readOnly:k)))throw Error(`invalid response`);return n}};C.current=i,u.begin(o),b(!1),t===`reject`?await ze():we(!0)}catch(e){ve(e instanceof Error?e.message:`Invalid adjudication.`)}finally{be(!1)}},ze=async()=>{if(we(!1),!c||C.current!==ge.current){u.abandon(),ve(`The draft changed. Review the current draft again.`);return}let e=await u.submit();e.kind===`acknowledged`?(Se(void 0),me.current={description:T,scope:D,readOnly:k,target:j,additionalAtoms:ie,duration:fe,reason:R},i(e.value),u.abandon(),r()):e.kind===`uncertain`?a():e.kind===`rejected`&&e.requiresRefresh&&(Se(n.etag),r())},Be=()=>{we(!1),p===`reject`&&pe(x.current),u.abandon()},Ve=!c||ye||d.state===`submitting`||d.state===`uncertain`||d.availability===`storage_latched`||xe===n.etag;if(n.state!==`pending`)return U(K,{state:`empty`,title:`Request adjudication is closed`,children:U(`p`,{children:`Terminal requests cannot be approved or rejected again.`})});let He=_?l:{scope:D,readOnly:k,target:j,constraint:Ie===``?null:JSON.parse(Ie),durationSeconds:fe===``?null:fe,futureToolsAcknowledged:D===`server`},Ue=l.scope===`server`&&He.scope===`tool`,We=P?.serverID===n.resolvedServerID&&P.externalName===He.target&&P.id===ke?.id?P:void 0,Ge=_?Id(n.submittedConstraintSource,``):Ie,Ke=k!==l.readOnly||D!==l.scope||j!==l.target||ie.length>0||fe!==(l.durationSeconds??``),qe=!_&&Ke;return U(`section`,{class:`panel domain-panel`,"aria-labelledby":`request-actions-title`,"data-testid":`request-actions`,children:[U(`div`,{class:`panel-heading`,children:U(`div`,{children:U(`h2`,{id:`request-actions-title`,children:`Choose a decision`})})}),U(`p`,{children:`Approval does not execute or retry a call.`}),U(J,{id:`approval-description`,label:`Grant description`,optional:!0,children:e=>U(`input`,{...e,"data-testid":`approval-description`,placeholder:`Allow requested tool access`,value:T,maxlength:256,disabled:Ve,onInput:e=>E(e.currentTarget.value)})}),U(`div`,{class:`form-actions`,children:[U(`button`,{ref:w,class:`primary-action`,type:`button`,disabled:Ve,onClick:()=>void Re(`approve`,!0),children:`Approve as requested`}),U(`button`,{type:`button`,class:`secondary request-customize-toggle`,disabled:Ve,"aria-expanded":h,"aria-controls":`request-customization`,onClick:()=>g(!h),children:[U(`span`,{"aria-hidden":`true`,children:h?`▾`:`▸`}),` `,h?`Hide customization`:`Customize approval`]}),!h&&Ke&&U(`span`,{class:`request-draft-note`,children:`Custom approval edited`}),U(`button`,{ref:Ee,"data-testid":`request-reject`,type:`button`,class:`danger-action`,disabled:Ve,onClick:()=>{x.current=R,m(`reject`),b(!0)},children:`Reject request`})]}),_e!==void 0&&U(K,{state:`error`,title:`Check decision`,children:U(`p`,{children:_e})}),h&&U(`section`,{id:`request-customization`,class:`form-section`,"aria-label":`Customize approval`,children:[U(`h3`,{children:`Tools`}),U(J,{id:`approval-scope`,label:`Approved scope`,children:e=>U(`select`,{...e,"data-testid":`approval-scope`,value:D,disabled:l.scope===`tool`||l.readOnly||Ve,onChange:e=>{let t=e.currentTarget.value;O(t),t===`tool`&&A(!1),t===`server`&&(M(l.target),ae([]))},children:[U(`option`,{value:`server`,children:`Server`}),U(`option`,{value:`tool`,children:`Exact tool`})]})}),D===`server`&&U(`div`,{children:[U(J,{id:`approval-read-only`,label:`Allowed tools`,...k?{hint:`Includes current and future tools marked readOnlyHint=true. The Gateway does not verify that these tools are read-only; they may still change data.`}:{},children:e=>U(`select`,{...e,"data-testid":`approval-read-only`,value:k?`read-only`:`all`,disabled:l.readOnly||Ve,onChange:e=>A(e.currentTarget.value===`read-only`),children:[U(`option`,{value:`all`,children:`All tools`}),U(`option`,{value:`read-only`,children:`Only tools marked read-only`})]})}),l.readOnly&&U(`p`,{children:`The requested read-only server restriction cannot be removed or narrowed to an exact tool.`})]}),U(J,{id:`approval-target`,label:`Approved target`,children:e=>De?U(`div`,{class:`matcher-tool-input`,children:[U(kn,{attributes:e,label:`Approved target`,testID:`approval-target`,placeholder:`${l.target}.lookup`,value:j,options:(N??[]).filter(e=>e.serverID===n.resolvedServerID).map(e=>({value:e.externalName})),disabled:Ve,onChange:M}),U(jo,{status:je,testID:`approval-tool-recognition`})]}):U(`input`,{...e,"data-testid":`approval-target`,value:j,disabled:!0})}),De&&Me&&U(`p`,{class:`bounded-note`,role:`status`,"data-testid":`approval-tool-posture`,children:Me}),U(`h3`,{children:`Conditions`}),D===`tool`&&U(S,{children:[U(Dd,{source:n.submittedConstraintSource,locked:!0}),U(`div`,{"aria-labelledby":`approval-additional-matchers-title`,children:[U(`h3`,{id:`approval-additional-matchers-title`,children:[`Additional conditions — All must match`,U(`span`,{class:`optional-label`,children:` (optional)`})]}),U(`p`,{class:`field-hint`,children:`Add rules without changing the submitted policy.`}),Ae?.unsupported&&U(`p`,{class:`bounded-note`,"data-testid":`approval-matcher-schema-posture`,children:`Some schema fields cannot be suggested. Custom pointers are still available.`}),U(Io,{idPrefix:`approval-additional`,testPrefix:`approval-additional`,atoms:ie,suggestions:Ae,schemaState:De&&!F&&(N===void 0||ke!==void 0&&!I&&Ae===void 0)?`loading`:`unavailable`,disabled:Ve,onChange:e=>{ve(void 0),ae(e)}})]})]}),U(`h3`,{children:`Duration`}),U(J,{id:`approval-duration`,label:`Approved duration`,hint:(l.durationSeconds===null?`Enter a whole number and choose its unit, from 1 minute to 30 days. Leave blank for no expiry.`:`Enter a whole number and choose its unit, from 1 minute to 30 days. The duration cannot exceed the request; temporary access cannot become permanent.`)+(de?``:` Choose a smaller unit; no positive whole number in this unit fits the requested duration.`),optional:l.durationSeconds===null,children:e=>U(`div`,{class:`duration-controls`,children:[U(`input`,{...e,type:`number`,min:`1`,step:`1`,"data-testid":`approval-duration`,placeholder:de?ue:void 0,value:L,disabled:Ve,onInput:e=>le(e.currentTarget.value)}),U(`select`,{"aria-label":`Approved duration unit`,"data-testid":`approval-duration-unit`,value:se,disabled:Ve,onChange:e=>ce(e.currentTarget.value),children:[U(`option`,{value:`minutes`,children:`Minutes`}),U(`option`,{value:`hours`,children:`Hours`}),U(`option`,{value:`days`,children:`Days`}),U(`option`,{value:`seconds`,children:`Seconds`})]})]})}),U(`section`,{class:`subpanel`,"aria-label":`Approval preview`,children:[U(`h3`,{children:`Approval preview`}),!Ke&&U(`p`,{children:`No changes to requested access.`}),U(`div`,{class:`approval-preview`,children:[U(`div`,{class:`preview-head`,"aria-hidden":`true`,children:[U(`span`,{children:`Field`}),U(`span`,{children:`Requested`}),U(`span`,{children:`Proposed approval`})]}),U(`div`,{class:D!==l.scope||j!==l.target||k!==l.readOnly?`preview-row changed`:`preview-row`,children:[U(`strong`,{children:`Tools`}),U(`div`,{children:[U(`span`,{class:`preview-label`,children:`Requested`}),l.scope===`server`?Ad(l):l.target]}),U(`div`,{children:[U(`span`,{class:`preview-label`,children:`Proposed approval`}),D===`server`?k?`Read-only server tools`:`All tools`:j]})]}),U(`div`,{class:fe===(l.durationSeconds??``)?`preview-row`:`preview-row changed`,children:[U(`strong`,{children:`Duration`}),U(`div`,{children:[U(`span`,{class:`preview-label`,children:`Requested`}),Ed(l.durationSeconds)]}),U(`div`,{children:[U(`span`,{class:`preview-label`,children:`Proposed approval`}),Ed(fe===``?null:fe)]})]}),U(`div`,{class:ie.length>0?`preview-row changed`:`preview-row`,children:[U(`strong`,{children:`Conditions`}),U(`div`,{children:[U(`span`,{class:`preview-label`,children:`Requested`}),U(Dd,{source:n.submittedConstraintSource})]}),U(`div`,{children:[U(`span`,{class:`preview-label`,children:`Proposed approval`}),Fe===void 0?U(Dd,{source:Ie}):U(K,{state:`error`,title:`Correct invalid conditions before approval`})]})]})]})]}),U(`div`,{class:`form-actions`,children:U(`button`,{ref:Te,"data-testid":`request-approve`,class:`primary-action`,type:`button`,disabled:Ve,onClick:()=>void Re(`approve`),children:ye?`Validating matcher…`:Ke?`Approve as narrowed`:`Approve as requested`})})]}),U(jn,{id:`request-rejection`,open:y,title:`Reject request`,confirmLabel:`Reject request`,destructive:!0,returnFocus:Ee,onCancel:()=>{pe(x.current),b(!1)},onConfirm:()=>void Re(`reject`),consequence:U(`div`,{children:[U(`p`,{children:`Rejection closes this request and creates no grant. It does not revoke existing access or create a DENY.`}),U(J,{id:`rejection-reason`,label:`Rejection reason`,children:e=>U(`select`,{...e,"data-testid":`rejection-reason`,value:R,disabled:Ve,onChange:e=>pe(e.currentTarget.value),children:[U(`option`,{value:`not_approved`,children:`Not approved`}),U(`option`,{value:`existing_access`,children:`Existing access`}),U(`option`,{value:`scope_too_broad`,children:`Scope too broad`}),U(`option`,{value:`policy_conflict`,children:`Policy conflict`})]})})]})}),d.problem!==void 0&&U(K,{state:`error`,title:_n(d.problem),children:d.requiresRefresh&&U(`p`,{children:`Refresh the request and review its state before taking another action.`})}),d.state===`uncertain`&&U(K,{state:`warning`,title:`Adjudication outcome is unknown`,children:U(`p`,{children:`Do not retry or replay. Refresh the request and grant history to investigate possible atomic commit.`})}),U(jn,{id:`request-adjudication-confirm`,open:Ce,title:p===`approve`?qe?`Approve as narrowed?`:`Approve as requested?`:`Reject request?`,consequence:p===`approve`?U(`div`,{class:`review-stack request-confirmation`,children:[U(`p`,{children:`Creates one allow grant and closes this request. It does not run a tool.`}),U(`dl`,{class:`detail-facts`,children:[U(`div`,{children:[U(`dt`,{children:`Agent`}),U(`dd`,{children:o})]}),U(`div`,{children:[U(`dt`,{children:`Approved target`}),U(`dd`,{children:s})]}),U(`div`,{children:[U(`dt`,{children:`Tools`}),U(`dd`,{children:He.scope===`tool`?He.target:Ad(He)})]}),T!==``&&U(`div`,{children:[U(`dt`,{children:`Description`}),U(`dd`,{children:T})]})]}),U(Od,{policy:He,source:Ge,definition:Ue?`Narrowed to one tool — no submitted definition to compare. ${F||I||We===void 0?`Current definition unavailable; using the literal tool name.`:`Current definition available.`}`:kd(n)}),U(`p`,{children:`All conditions must match. Matching deny grants still take precedence.`}),U(`details`,{children:[U(`summary`,{children:`Exact identifiers and serialized policy`}),U(`dl`,{class:`detail-facts`,children:[U(`div`,{children:[U(`dt`,{children:`Agent ID`}),U(`dd`,{class:`technical-value`,children:n.principalID})]}),U(`div`,{children:[U(`dt`,{children:`Server ID`}),U(`dd`,{class:`technical-value`,children:n.resolvedServerID})]})]}),U(`strong`,{children:`Read-only serialized policy`}),U(`textarea`,{class:`inert-json matcher-policy-review`,"aria-label":`Read-only serialized policy`,"data-testid":`approval-review-policy`,readOnly:!0,rows:8,value:_?`{"description":${JSON.stringify(T===``?null:T)},"approved_policy":{"scope":${JSON.stringify(l.scope)},"target":${JSON.stringify(l.target)},"constraint":${Ge===``?`null`:Ge},"duration_seconds":${JSON.stringify(l.durationSeconds)},"future_tools_acknowledged":${String(l.futureToolsAcknowledged)}${yr(l.readOnly)}}}`:Le})]})]}):U(`p`,{children:[`Rejection atomically closes the request with reason`,` `,W(R),`; it creates no grant, does not revoke existing access, and does not create a DENY.`]}),confirmLabel:p===`approve`?qe?`Approve as narrowed`:`Approve as requested`:`Reject request`,destructive:p===`reject`,returnFocus:p===`approve`?_?w:Te:Ee,onCancel:Be,onConfirm:()=>void ze()})]})}function Rd({session:e,mutations:t,resolved:n,view:r,onRefresh:i}){let a=n.location.segments.length===2?n.location.segments[1]:void 0,[o,s]=z(),[c,l]=z(),[u,d]=z(),f=V({location:{destination:`requests`,segments:[`requests`],query:{}},canonicalFragment:`#/mcp/access-requests`,invalid:!1});a===void 0&&(f.current=n);let p=Cr(!1),{items:m,controls:h}=Nr(e,f.current,r,(t,n,r)=>wd(e,t,n,r),p,{key:`submitted`,direction:f.current.location.query.queue===`all`?`descending`:`ascending`}),[g,_]=z(),[v,y]=z();if(B(()=>{let t=!0;if(l(void 0),a!==void 0){s(e=>e?.id===a?e:void 0),Td(e,a).then(e=>{t&&e!==void 0&&s(e)}).catch(e=>{t&&l(e instanceof Error?e.message:`Request data is unavailable.`)});let n=new AbortController;wd(e,{queue:`all`,filter_request:a},null,n.signal).then(e=>{t&&_(e?.items.find(e=>e.id===a))}).catch(()=>{t&&_(void 0)}),wd(e,{},null,n.signal).then(e=>{t&&y(e?.items.find(e=>e.id!==a)?.id)}).catch(()=>{t&&y(void 0)})}return()=>{t=!1}},[n.canonicalFragment,r.generation]),c!==void 0&&(o===void 0||o.id!==a))return U(K,{state:`error`,title:`Request data unavailable`,children:U(`p`,{children:c})});if(a!==void 0){if(o===void 0||o.id!==a)return U(K,{state:`loading`,title:`Loading request`});let n=g?.id===o.id?g.principalName:`Agent ${o.principalID}`,r=g?.id===o.id?g.serverName:`Server ${o.resolvedServerID}`,l=o.submittedEvidence!==null&&o.currentTarget.fingerprint!==null&&o.submittedEvidence.fingerprint!==o.currentTarget.fingerprint;return U(`div`,{class:`domain-view`,"data-testid":`request-detail`,"data-request-id":o.id,children:[U(`nav`,{class:`detail-navigation`,"aria-label":`Request navigation`,children:[U(`a`,{href:f.current.canonicalFragment,children:[`Back to`,` `,f.current.location.query.queue===`all`?`all`:`pending`,` `,`requests`]}),o.state!==`pending`&&v!==void 0&&U(`a`,{href:`#/mcp/access-requests/${v}`,children:`Review next`}),o.state!==`pending`&&v===void 0&&U(`span`,{children:`No next pending request available. Return to the queue to refresh.`})]}),U(`header`,{class:`detail-context`,"data-testid":`detail-context`,children:[U(`div`,{class:`detail-context-heading`,children:[U(`h1`,{id:`request-page-title`,tabindex:-1,children:o.state===`pending`?`Review MCP Access Request`:`${W(o.state)} MCP Access Request`}),U(G,{state:o.state===`pending`?`warning`:o.state===`approved`?`current`:`neutral`,children:W(o.state)})]}),U(`p`,{class:`technical-value`,children:o.id})]}),U(`section`,{class:`detail-section`,"aria-labelledby":`request-title`,children:[U(`div`,{class:`panel-heading`,children:U(`h2`,{id:`request-title`,children:`Request details`})}),U(`dl`,{class:`detail-facts`,children:[U(`div`,{children:[U(`dt`,{children:`Agent`}),U(`dd`,{children:U(`a`,{href:`#/agents/${o.principalID}`,children:n})})]}),U(`div`,{children:[U(`dt`,{children:`Submitted`}),U(`dd`,{children:U(Y,{value:o.createdAt})})]}),U(`div`,{children:[U(`dt`,{children:`Requested target`}),U(`dd`,{children:U(`a`,{href:`#/mcp/servers/${o.resolvedServerID}?tab=tools`,children:r})})]}),U(`div`,{children:[U(`dt`,{children:`Tools`}),U(`dd`,{children:o.resolvedUpstreamName??Ad(o.requestedPolicy)})]})]}),U(Od,{policy:o.requestedPolicy,source:o.submittedConstraintSource,definition:kd(o)}),c!==void 0&&U(K,{state:`error`,title:`Request refresh failed`,children:U(`p`,{children:[c,` Displayed evidence may be stale; refresh before deciding.`]})}),u===o.id&&U(K,{state:`warning`,title:`Adjudication outcome is unknown`,children:U(`p`,{children:`Do not resubmit. Inspect refreshed request and grant history; no success or rollback was confirmed.`})})]}),o.state===`pending`&&u!==o.id&&U(Ld,{session:e,mutations:t,detail:o,onRefresh:i,onAcknowledged:s,onUncertain:()=>d(o.id),principalName:n,serverName:r,readAvailable:c===void 0},`${o.id}:${o.etag}`),o.state!==`pending`&&U(`section`,{class:`detail-section`,"aria-labelledby":`approved-policy-title`,children:[U(`h2`,{id:`approved-policy-title`,children:[W(o.state),` decision`]}),o.approvedGrantID!==null&&U(`dl`,{class:`detail-facts`,children:U(`div`,{children:[U(`dt`,{children:`Created grant`}),U(`dd`,{children:U(`a`,{href:`#/mcp/grants/${o.approvedGrantID}`,children:o.approvedGrantID})})]})}),U(K,{state:`empty`,title:`Request adjudication is closed`,children:U(`p`,{children:`Terminal requests cannot be approved or rejected again.`})}),o.approvedPolicy===null?U(`p`,{children:[o.state===`cancelled`?`The requesting agent cancelled this request.`:`This request was rejected.`,` `,`This decision created no grant and did not revoke existing access or create a DENY.`]}):U(S,{children:[U(`section`,{class:`detail-group`,"aria-label":`Requested versus approved`,children:[U(`h3`,{children:`Requested versus Approved`}),Md(o.requestedPolicy,o.approvedPolicy),U(xn,{label:`Requested versus approved conditions`,fullWidth:!0,beforeLabel:`Requested`,afterLabel:`Approved`,rows:[{label:`Conditions`,before:U(Dd,{source:o.submittedConstraintSource}),after:U(Dd,{source:o.approvedConstraintSource}),changed:o.submittedConstraintSource!==o.approvedConstraintSource}]})]}),U(`details`,{children:[U(`summary`,{children:`Approved serialized policy`}),U(`pre`,{class:`inert-json`,tabindex:0,"aria-label":`Approved policy`,children:o.approvedPolicySource})]})]}),o.approvedEvidence!==null&&U(`details`,{children:[U(`summary`,{children:`Approved descriptor evidence`}),U(Nd,{evidence:o.approvedEvidence,label:`Approved`})]}),o.rejectionReason!==null&&U(`p`,{children:[`Closed rejection reason: `,o.rejectionReason]})]}),U(`details`,{class:`detail-section`,children:[U(`summary`,{children:`Technical identifiers and immutable evidence`}),U(`dl`,{class:`detail-facts`,children:[U(`div`,{children:[U(`dt`,{children:`Agent ID`}),U(`dd`,{children:o.principalID})]}),U(`div`,{children:[U(`dt`,{children:`Server ID`}),U(`dd`,{children:o.resolvedServerID})]}),U(`div`,{children:[U(`dt`,{children:`Revision / ETag`}),U(`dd`,{children:o.etag})]})]}),U(`p`,{children:`Tool descriptions and schemas are untrusted inert evidence, not instructions or proof of callable authority.`}),U(`section`,{class:`detail-group`,"aria-labelledby":`submitted-policy-title`,children:[U(`h2`,{id:`submitted-policy-title`,children:`Submitted policy and evidence — immutable`}),jd(o.requestedPolicy),o.requestedPolicy.constraint!==null&&U(yn,{value:o.requestedPolicy.constraint,label:`Submitted constraint`}),U(Nd,{evidence:o.submittedEvidence,label:`Submitted`})]}),U(`section`,{class:`detail-group`,"aria-labelledby":`current-target-title`,children:[U(`h2`,{id:`current-target-title`,children:`Current target comparison — read-time`}),U(`p`,{children:`Current comparison does not rewrite immutable submitted evidence or the request revision.`}),U(`dl`,{class:`detail-facts`,children:[U(`div`,{children:[U(`dt`,{children:`Target`}),U(`dd`,{children:W(o.currentTarget.targetState)})]}),U(`div`,{children:[U(`dt`,{children:`Active descriptor`}),U(`dd`,{children:o.currentTarget.activeState===null?`Not applicable`:W(o.currentTarget.activeState)})]}),U(`div`,{children:[U(`dt`,{children:`Durable descriptor`}),U(`dd`,{children:o.currentTarget.durableState===null?`Not applicable`:W(o.currentTarget.durableState)})]}),U(`div`,{children:[U(`dt`,{children:`Current fingerprint`}),U(`dd`,{children:o.currentTarget.fingerprint??`Absent`})]})]}),l&&U(K,{state:`warning`,title:`Descriptor fingerprint changed`,children:U(`p`,{children:`The current descriptor differs from submitted evidence. Active current does not mean it matches the submission.`})}),o.currentTarget.durableState===`retired`&&U(K,{state:`warning`,title:`Current comparison is retired historical evidence`,children:U(`p`,{children:`Retained evidence is not callable authority.`})}),o.currentTarget.durableState===`absent`&&U(K,{state:`unavailable`,title:`Current descriptor is absent`}),o.currentTarget.descriptor!==null&&U(yn,{value:o.currentTarget.descriptor,label:`Current normalized descriptor`})]})]})]})}let b=n.location.query.queue===`all`;return U(`div`,{class:`domain-view`,"data-testid":`requests-view`,children:U(`section`,{class:`panel domain-panel`,"aria-label":`Grant requests`,children:[U(`nav`,{class:`subnav request-queue-tabs`,"aria-label":`Request queues`,children:[U(`a`,{href:`#/mcp/access-requests`,"aria-current":b?void 0:`page`,children:`Pending`}),U(`a`,{href:`#/mcp/access-requests?queue=all`,"aria-current":b?`page`:void 0,children:`All requests`})]}),U(Dn,{caption:`Grant request summaries`,rowHeaderKey:`request`,items:m,rowKey:e=>e.id,rowTestID:`request-row`,emptyTitle:b?`No requests`:`No pending requests`,remote:h,itemNames:{singular:`request`,plural:`requests`},filters:[{key:`request`,label:`Request ID`,type:`text`,value:()=>``,literalValues:e=>[e.id]},{key:`principal`,label:`Agent`,type:`text`,value:e=>e.principalName,literalValues:e=>[e.principalID]},{key:`target`,label:`Target`,type:`text`,value:e=>e.requestedPolicy.target},{key:`scope`,label:`Scope`,type:`select`,value:e=>e.requestedPolicy.scope,options:[{value:`tool`,label:`Tool`},{value:`server`,label:`Server`}]},...b?[{key:`state`,label:`Status`,type:`select`,value:e=>e.state,options:[{value:`pending`,label:`Pending`},{value:`approved`,label:`Approved`},{value:`rejected`,label:`Rejected`},{value:`cancelled`,label:`Cancelled`}]}]:[]],columns:[{key:`submitted`,label:`Submitted`,role:`time`,render:e=>U(Y,{value:e.createdAt}),sortValue:e=>e.createdAt},{key:`request`,label:`Request`,role:`identity`,render:e=>U(q,{primary:U(`a`,{href:`#/mcp/access-requests/${e.id}`,children:`Access request`}),secondary:e.id}),sortValue:e=>e.id},{key:`principal`,label:`Agent`,role:`relation`,render:e=>U(`a`,{href:`#/agents/${e.principalID}`,children:e.principalName}),sortValue:e=>e.principalName},{key:`target`,label:`Target`,role:`relation`,render:e=>U(`a`,{href:`#/mcp/servers/${e.serverID}?tab=tools`,title:e.requestedPolicy.target,children:[e.serverName,` ·`,` `,e.upstreamName??(e.requestedPolicy.readOnly?`Read-only tools`:`All tools`)]}),sortValue:e=>e.requestedPolicy.target},{key:`state`,label:`Status`,role:`status`,render:e=>U(G,{state:e.state===`pending`?`warning`:e.state===`approved`?`current`:`neutral`,children:W(e.state)}),sortValue:e=>e.state},{key:`duration`,label:`Requested duration`,role:`measure`,render:e=>Ed(e.requestedPolicy.durationSeconds)},{key:`constraints`,label:`Conditions`,role:`count`,render:e=>Po(e.requestedPolicy.constraint===null?null:Pd(e.requestedPolicy.constraint))},{key:`decision`,label:`Actions`,role:`actions`,render:e=>U(`a`,{class:`button-link${e.state===`pending`?` primary-action`:``}`,href:`#/mcp/access-requests/${e.id}`,children:e.state===`pending`?`Review`:`View decision`})}]})]})})}var zd=`sidebar-pending-requests`,Bd=class{total;constructor(e,t){e.registerProtectedState(()=>{this.total=void 0}),t.registerPanel({id:zd,scope:`session`,matches:e=>e!==`#/sign-in`,invalidations:[`grant_requests`],pollMilliseconds:3e4,read:async({signal:t})=>{let n=await Mr(e,`/api/v2/mcp/grant-requests?state=pending&limit=1`,()=>null,t);if(n?.totalCount===void 0)throw Error(`Pending request count is unavailable.`);return n.totalCount},publish:e=>{this.total=e}})}presentation(e){let t=e.panels[zd];return this.total===void 0||t?.hasValue!==!0?{label:t?.status===`error`?`Requests, pending count unavailable`:`Requests, pending count loading`,badge:`?`}:t.status===`error`||t.status===`stale`?{label:`Requests, pending count unavailable; last known ${this.total} pending`,badge:`?`}:{label:`Requests, ${this.total} pending${t.refreshing?` (refreshing)`:``}`,badge:this.total===0?null:String(this.total)}}},Vd={bytes:67108864,milliseconds:12e4,pages:4096},Hd=class extends Error{},Ud=()=>new Hd(`History coverage could not be verified. No file was downloaded.`),Wd=/^(0|[1-9][0-9]{0,18})$/,Gd=/^[0-7][0-9A-HJKMNP-TV-Z]{25}$/;function Kd(e){if(typeof e!=`string`||!Wd.test(e))throw Ud();let t=BigInt(e);if(t>9223372036854775807n)throw Ud();return t}function qd(e,t,n){let r=JSON.parse(e);if(typeof r!=`object`||!r||Array.isArray(r)||r.format!==1||typeof r.generation!=`string`||!Gd.test(r.generation)||typeof r.installation_id!=`string`||!Gd.test(r.installation_id)||r.complete_traffic_audit!==!1||!Array.isArray(r.records)||r.records.length>256||typeof r.retained!=`number`||!Number.isSafeInteger(r.retained)||r.retained64||!Number.isFinite(Date.parse(r.captured_at))||Kd(r.after_sequence)!==t)throw Ud();let i=Kd(r.high_water),a=Kd(r.pruning),o=Kd(r.next_sequence);if(i-a!==BigInt(r.retained))throw Ud();let s=t;for(let e of r.records){if(typeof e!=`object`||!e||Array.isArray(e))throw Ud();let t=Kd(e.sequence),r=e.protocol;if(t<=s||t>(n??i)||![`mcp`,`http`,`git`].includes(r)||e[r]===null||typeof e[r]!=`object`||Array.isArray(e[r])||[`mcp`,`http`,`git`].some(t=>t!==r&&t in e))throw Ud();s=t}if(o!==s||r.truncated&&o===t)throw Ud();return{generation:r.generation,installation:r.installation_id,high:i,pruning:a,retained:r.retained,next:o,truncated:r.truncated,count:r.records.length,captured:r.captured_at}}async function Jd(e,t,n,r,i){let a=r===void 0?``:`?after_sequence=${n}&through_sequence=${r}&limit=256`,o=await fetch(`/api/v2/history/export${a}`,{method:`GET`,credentials:`same-origin`,cache:`no-store`,redirect:`error`,headers:{"X-CSRF-Token":e},signal:AbortSignal.any([t,AbortSignal.timeout(5e3)])});if(await i?.(o))throw Ud();if(!o.ok||o.headers.get(`Content-Type`)!==`application/json`||o.body===null)throw new Hd(`Traffic history is unavailable. No file was downloaded. Backup controls remain independent.`);let s=o.body.getReader(),c=new TextDecoder(`utf-8`,{fatal:!0}),l=0,u=``;try{for(;;){t.throwIfAborted();let e=await s.read();if(e.done)break;if(l+=e.value.byteLength,l>921600)throw new Hd(`A history response exceeds its safe bound. No file was downloaded.`);u+=c.decode(e.value,{stream:!0})}u+=c.decode()}catch(e){throw await s.cancel().catch(()=>{}),e}finally{s.releaseLock()}return{raw:u,bytes:l}}async function Yd(e,t,n=()=>{},r){let i=AbortSignal.any([t,AbortSignal.timeout(Vd.milliseconds)]),a=[],o,s=0n,c=0,l=0,u=0n;try{for(let t=0;tVd.bytes)throw new Hd(`Traffic history exceeds the 64 MiB browser limit. No file was downloaded. Use the documented bounded CLI export procedure.`);if(c+=d.count,c>o.retained)throw Ud();if(a.push(t.raw),n({records:c,pages:a.length,bytes:l}),s=d.next,!d.truncated){if(c!==o.retained||c>0&&s!==o.high)throw Ud();let e=JSON.stringify({initial_high_water:String(o.high),final_high_water:String(u),initial_pruning:String(o.pruning),initial_retained:o.retained,returned_records:c,page_count:a.length,started_at:o.captured,finished_at:d.captured,retained_boundary_traversed:!0,atomic_snapshot:!1,new_records_excluded:u>o.high,completion_changes:`Each page observes its own read transaction; late completions on earlier pages are not refreshed. Missing completion remains unknown.`});return i.throwIfAborted(),{blob:new Blob([`{"format":"agent-gateway-retained-traffic-v1","complete_traffic_audit":false,"coverage":${e},"pages":[`,...a.flatMap((e,t)=>t===0?[e]:[`,`,e]),`]} +`);if(e===-1)break;let t=i.slice(0,e).replace(/\r$/,``);if(i=i.slice(e+1),t===``){if(a===`invalidate`&&o!==``){let e;try{e=JSON.parse(o)}catch{throw Error(`invalid event JSON`)}let t=kr(e);if(t===void 0)throw Error(`invalid event`);this.invalidate(t)}a=``,o=``}else if(t.startsWith(`event: `))a=t.slice(7);else if(t.startsWith(`data: `)){if(o!==``)throw Error(`duplicate event data`);o=t.slice(6)}else if(!t.startsWith(`:`))throw Error(`invalid event field`)}}}finally{await n.cancel().catch(()=>void 0),n.releaseLock()}}visiblePanels(){return[...this.panels.values()].filter(e=>e.matches(this.viewKey))}current(e,t){return this.active&&this.viewKey===e&&this.generation===t}panelCurrent(e,t,n){return this.active&&this.viewKey===t&&this.panelGenerations.get(e)===n}schedulePoll(e){let t=e.pollMilliseconds;if(!this.active||t===void 0||t<=0||this.pollTimers.has(t)||!e.matches(this.viewKey)||e.shouldPoll?.()===!1||!this.visibility.isVisible())return;let n=setTimeout(()=>{if(this.pollTimers.delete(t),!this.visibility.isVisible())return;let e=this.visiblePanels().filter(e=>e.pollMilliseconds===t&&e.shouldPoll?.()!==!1).map(e=>e.id);e.length>0&&this.refresh(e,`poll`)},t);this.pollTimers.set(t,n)}visibilityChanged(){if(!this.visibility.isVisible()){this.clearPolls();return}for(let e of this.visiblePanels())this.schedulePoll(e)}markVisiblePanelsStale(){for(let e of this.visiblePanels()){let t=this.panelState.get(e.id);this.panelState.set(e.id,{status:t?.hasValue===!0?`stale`:`loading`,hasValue:t?.hasValue===!0})}}markVisiblePanelsLoading(){for(let e of this.visiblePanels())e.scope!==`session`&&this.panelState.set(e.id,{status:`loading`,hasValue:!1})}abortRead(e){this.readControllers.get(e)?.abort(),this.readControllers.delete(e)}abortReads(){for(let e of this.readControllers.values())e.abort();this.readControllers.clear()}clearPolls(){for(let e of this.pollTimers.values())clearTimeout(e);this.pollTimers.clear()}reset(){this.active=!1,this.streamController?.abort(),this.streamController=void 0,this.streamConnected=!1,this.abortReads(),this.clearPolls(),this.reconnectTimer?.(),this.reconnectTimer=void 0,this.invalidationTimer!==void 0&&clearTimeout(this.invalidationTimer),this.invalidationTimer=void 0,this.pendingInvalidations.clear(),this.freshness=`reconnecting`;for(let e of this.panelState.keys())this.panelState.set(e,{status:`loading`,hasValue:!1});this.emit()}emit(){let e=this.snapshot();for(let t of this.listeners)t(e)}},Fr=/^[0-7][0-9A-HJKMNP-TV-Z]{25}$/,Ir=[`preparing`,`awaiting_callback`,`exchanging`,`succeeded`,`failed`,`expired`,`cancelled`,`superseded`,`interrupted`],Lr=[`metadata_discovery`,`client_registration`,`authorization_request`,`callback_validation`,`token_exchange`,`credential_installation`],Rr=new Set(`configuration_invalid.resource_limit.connectivity.tls_failed.protocol_unsupported.protocol_invalid.authentication_rejected.credential_absent.keyring_absent.keyring_locked.keyring_interaction_required.keyring_unavailable.keyring_unsupported.oauth_rejected.oauth_expired.registration_expired.process_exited.output_limit.stop_unconfirmed.catalog_invalid.catalog_limit.catalog_stale.superseded.cancelled.interrupted.revocation_failed.revocation_unsupported.cleanup_pending`.split(`.`));function zr(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`invalid auth flow response`);let n=e;if(Object.keys(n).sort().join(`,`)!==[...t].sort().join(`,`))throw Error(`invalid auth flow response`);return n}function Br(e){if(typeof e!=`string`)throw Error(`invalid auth flow response`);return e}function Vr(e){let t=Br(e);if(!Fr.test(t))throw Error(`invalid auth flow response`);return t}function Hr(e){let t=Br(e);if(!/^(?:0|[1-9][0-9]*)$/.test(t))throw Error(`invalid auth flow response`);return t}function Ur(e){if(e===null)return null;let t=Br(e);if(!Rr.has(t))throw Error(`invalid auth flow response`);return t}function Wr(e){if(e===null)return null;let t=zr(e,[`correlation_id`,`stage`,`reason`,`http_status`]),n=Br(t.stage),r=Ur(t.reason),i=t.http_status;if(!Lr.includes(n)||r===null||i!==null&&(!Number.isInteger(i)||typeof i!=`number`||i<100||i>599))throw Error(`invalid auth flow response`);return{correlationID:Vr(t.correlation_id),stage:n,reason:r,httpStatus:i}}function Gr(e){if(e!==null&&typeof e!=`string`)throw Error(`invalid auth flow response`);return e}function Kr(e){let t=Gr(e);if(t!==null&&(t.length===0||t.length>4096))throw Error(`invalid auth flow response`);return t}function qr(e){let t=Br(e);if(!Ir.includes(t))throw Error(`invalid auth flow response`);return t}function Jr(e){let t=zr(e,[`id`,`server_id`,`state`,`target_desired_revision`,`registration_revision`,`created_at`,`expires_at`,`finished_at`,`reason`,`diagnostic`]);return{id:Vr(t.id),serverID:Vr(t.server_id),state:qr(t.state),targetDesiredRevision:Hr(t.target_desired_revision),registrationRevision:Hr(t.registration_revision),createdAt:Br(t.created_at),expiresAt:Br(t.expires_at),finishedAt:Gr(t.finished_at),reason:Ur(t.reason),diagnostic:Wr(t.diagnostic)}}function Yr(e){let t=zr(e,[`items`,`next_cursor`]);if(!Array.isArray(t.items))throw Error(`invalid auth flow response`);return{items:t.items.map(Jr),nextCursor:Kr(t.next_cursor)}}async function Xr(e){let t=new Uint8Array(await e.arrayBuffer());if(t.byteLength>4194304)throw Error(`auth flow response too large`);let n=zr(JSON.parse(new TextDecoder(`utf-8`,{fatal:!0}).decode(t)),[`flow`,`authorization_url`]),r=Br(n.authorization_url);if(r.length===0||r.length>8192)throw Error(`invalid auth flow response`);return{flow:Jr(n.flow),authorizationURL:r}}function Zr(e){return![`preparing`,`awaiting_callback`,`exchanging`].includes(e.state)}function Qr(e){return e.state===`preparing`||e.state===`awaiting_callback`}function $r(e){if(e.desiredState===`deleted`||typeof e.transport!=`object`||e.transport===null)return!1;let t=e.transport;if(t.kind!==`streamable_http`)return!1;let n=t.authentication;return typeof n==`object`&&!!n&&!Array.isArray(n)&&n.mode===`oauth`}function ei(e){let t=e.replaceAll(`_`,` `);return t.startsWith(`oauth`)?`OAuth${t.slice(5)}`:t.charAt(0).toLocaleUpperCase()+t.slice(1)}function ti(e){return Zr(e)?e.state===`succeeded`?`current`:e.state===`failed`?`error`:e.state===`interrupted`?`warning`:`neutral`:`loading`}function ni({serverID:e,items:t,hasMore:n,loadingMore:r,onLoadMore:i,stale:a,loading:o}){return U(Dn,{caption:`OAuth activity`,layout:`activity`,rowHeaderKey:`action`,loadedSubset:!0,historySummary:!0,localStale:a,localLoading:o,itemNames:{singular:`flow`,plural:`flows`},emptyTitle:`No retained OAuth flows`,hasMore:n,loadingMore:r,onLoadMore:i,loadMoreLabel:`Load more flows`,items:t,rowKey:e=>e.id,rowTestID:`auth-flow-row`,filters:[{key:`status`,label:`Status`,type:`select`,value:e=>e.state,options:[{value:`preparing`,label:`Preparing`},{value:`awaiting_callback`,label:`Awaiting callback`},{value:`exchanging`,label:`Exchanging`},{value:`succeeded`,label:`Succeeded`},{value:`failed`,label:`Failed`},{value:`cancelled`,label:`Cancelled`},{value:`interrupted`,label:`Interrupted`},{value:`expired`,label:`Expired`},{value:`superseded`,label:`Superseded`}]}],initialSort:{key:`created`,direction:`descending`},columns:[{key:`created`,label:`Created`,role:`time`,sortValue:e=>e.createdAt,render:e=>U(Y,{value:e.createdAt})},{key:`action`,label:`Flow`,role:`identity`,render:t=>U(q,{primary:U(`a`,{href:`#/mcp/servers/${e}/auth-flows/${t.id}`,children:`OAuth authorization`}),secondary:t.id})},{key:`status`,label:`Status`,role:`status`,sortValue:e=>e.state,render:e=>U(G,{state:ti(e),children:ei(e.state)})},{key:`outcome`,label:`Reason`,role:`text`,sortValue:e=>e.reason??``,render:e=>e.reason===null?`—`:ei(e.reason)}]})}function ri({mutations:e,sinks:t,server:n,etag:r,readVersion:i,exchangeActive:a}){let[o]=z(()=>e.create()),[s,c]=z(()=>o.snapshot()),[l,u]=z(),[d,f]=z();B(()=>o.subscribe(c),[o]),B(()=>()=>o.close(),[o]);let p=async(e,t)=>{let n=await e;if(n.kind===`acknowledged`){t.publish(n.value.authorizationURL)===`lost`&&u(`The authorization URL could not be displayed. Start a new flow from current state.`),o.abandon();return}if(n.kind===`uncertain`){t.lose();return}t.cancel(),n.kind===`rejected`&&n.requiresRefresh&&f(i)},m=()=>{u(void 0);let e=t.prepareOAuth(`Authorize server OAuth flow`);if(e===void 0){u(`The one-time authorization URL display is unavailable. No flow was started.`);return}o.begin({route:`/api/v2/mcp/servers/${n.id}/oauth-flows`,method:`POST`,body:`{}`,precondition:r,requiresPrecondition:!0,idempotency:`none`,successStatuses:[201],decode:async e=>{let t=await Xr(e);if(t.flow.serverID!==n.id||t.flow.state!==`awaiting_callback`||t.flow.targetDesiredRevision!==n.desiredRevision||t.flow.registrationRevision!==n.oauthClientRevision||t.flow.finishedAt!==null||t.flow.reason!==null)throw Error(`invalid auth flow creation response`);return t}}),p(o.submit(),e)},h=d!==void 0&&i<=d,g=s.state===`submitting`||s.availability===`storage_latched`||h,_=n.credentialState===`ready`,v=n.transport?.authentication?.registration,y=v?.mode===`static`&&(v.token_endpoint_auth_method===`client_secret_basic`||v.token_endpoint_auth_method===`client_secret_post`)&&n.oauthClientRevision===`0`;return U(`section`,{class:`panel domain-panel`,"aria-labelledby":`auth-flow-start-title`,children:[U(`div`,{class:`panel-heading`,children:U(`div`,{children:U(`h2`,{id:`auth-flow-start-title`,children:`OAuth authorization`})})}),U(`p`,{children:`Continue authorization in a new browser page. The one-time URL is cleared when it is dismissed, opened, or you leave this page.`}),$r(n)&&!a&&U(`p`,{children:`Starting again invalidates any previous pending authorization link.`}),y&&U(`p`,{class:`bounded-note`,id:`oauth-client-prerequisite`,children:`Add the client secret above before authorizing.`}),$r(n)&&!a?U(`button`,{type:`button`,class:_?void 0:`primary-action`,"data-testid":`start-auth-flow`,disabled:g||y,"aria-describedby":y?`oauth-client-prerequisite`:void 0,onClick:m,children:_?`Reauthorize server`:`Authorize server`}):U(K,{state:a?`loading`:`empty`,title:a?`Authorization in progress`:`OAuth is unavailable`,children:!a&&U(`p`,{children:`This server is not configured for OAuth.`})}),s.problem!==void 0&&U(K,{state:`error`,title:s.problem.title,children:s.requiresRefresh&&U(`p`,{children:`A fresh server and flow snapshot was requested. Review it before starting a new flow.`})}),s.state===`uncertain`&&U(K,{state:`warning`,title:`Flow start outcome unknown`,children:U(`p`,{children:`Inspect refreshed flow history before starting again. This start cannot be replayed.`})}),h&&U(`p`,{class:`session-message`,role:`status`,children:`Waiting for a newer authoritative server snapshot.`}),l!==void 0&&U(`p`,{class:`session-message`,role:`status`,children:l})]})}function ii({mutations:e,flow:t,onRefresh:n}){let[r]=z(()=>e.create()),[i,a]=z(()=>r.snapshot()),o=V(null);B(()=>r.subscribe(a),[r]),B(()=>()=>r.close(),[r]);let s=async e=>{(await e).kind===`acknowledged`&&(r.abandon(),n())};return Qr(t)?U(`section`,{class:`panel domain-panel`,"aria-labelledby":`auth-flow-cancel-title`,children:[U(`div`,{class:`panel-heading`,children:U(`div`,{children:U(`h2`,{id:`auth-flow-cancel-title`,children:`Cancel this OAuth flow`})})}),U(`button`,{ref:o,type:`button`,"data-testid":`cancel-auth-flow`,disabled:i.state===`submitting`||i.availability===`storage_latched`,onClick:()=>{r.begin({route:`/api/v2/mcp/servers/${t.serverID}/oauth-flows/${t.id}`,method:`DELETE`,body:`{}`,precondition:null,requiresPrecondition:!1,idempotency:`none`,successStatuses:[204],decode:async()=>void 0}),r.confirm()},children:`Review cancellation`}),i.problem!==void 0&&U(K,{state:`error`,title:i.problem.title}),i.state===`uncertain`&&U(K,{state:`warning`,title:`Cancellation outcome unknown`,children:U(`p`,{children:`Refresh this flow. Do not infer cancellation or replay the request.`})}),U(jn,{id:`auth-flow-cancel-confirm`,open:i.state===`confirming`,title:`Cancel this OAuth flow?`,consequence:`Cancellation invalidates the current callback state. An authorization page already opened may no longer complete, while an exchange already in progress cannot be cancelled.`,confirmLabel:`Cancel OAuth flow`,returnFocus:o,onCancel:()=>r.abandon(),onConfirm:()=>void s(r.submit())})]}):null}function ai({mutations:e,sinks:t,server:n,etag:r,readVersion:i,flows:a,flow:o,nextCursor:s,loadingMore:c,restarted:l,onLoadMore:u,onRefresh:d,mode:f=`full`,stale:p=!1,loading:m=!1}){return o===void 0?f===`action`?$r(n)?U(ri,{mutations:e,sinks:t,server:n,etag:r,readVersion:i,exchangeActive:a.some(e=>e.state===`exchanging`)}):null:U(S,{children:[U(`section`,{class:`panel domain-panel`,"aria-labelledby":`auth-flow-list-title`,"data-testid":`auth-flow-list`,children:[U(`div`,{class:`panel-heading`,children:U(`div`,{children:U(`h2`,{id:`auth-flow-list-title`,children:`OAuth activity`})})}),l&&U(K,{state:`stale`,title:`Flow history changed`,children:U(`p`,{children:`Showing the first page. Previous results could not be continued.`})}),m&&U(K,{state:`loading`,title:`Loading OAuth activity`}),p&&U(K,{state:`error`,title:`OAuth activity unavailable`,children:`Loaded flows are last-known. Use Load more flows to retry continuation, or Refresh to restart.`}),U(ni,{stale:p,loading:m,serverID:n.id,items:a,hasMore:s!==null,loadingMore:c,onLoadMore:u})]}),f===`full`&&U(ri,{mutations:e,sinks:t,server:n,etag:r,readVersion:i,exchangeActive:a.some(e=>e.state===`exchanging`)})]}):U(S,{children:[U(`div`,{"data-testid":`auth-flow-detail`,children:[U(`nav`,{class:`detail-navigation`,"aria-label":`OAuth flow navigation`,children:U(`a`,{href:`#/mcp/servers/${n.id}?tab=authentication`,children:`Back to server authentication`})}),U(`header`,{class:`detail-context`,"data-testid":`detail-context`,children:[U(`div`,{class:`detail-context-heading`,children:[U(`h1`,{id:`auth-flow-detail-title`,tabindex:-1,children:`Authorize server with OAuth`}),U(G,{state:ti(o),children:ei(o.state)})]}),U(`p`,{class:`technical-value`,children:o.id})]}),U(`section`,{class:`detail-section`,"aria-labelledby":`auth-flow-facts-title`,children:[U(`h3`,{id:`auth-flow-facts-title`,children:`Flow details`}),p&&U(K,{state:`error`,title:`OAuth flow unavailable`,children:`These flow details are last-known. Refresh to retry the read.`}),U(`dl`,{class:`detail-list`,children:[U(`div`,{children:[U(`dt`,{children:`Created`}),U(`dd`,{children:U(Y,{value:o.createdAt})})]}),U(`div`,{children:[U(`dt`,{children:`Expires`}),U(`dd`,{children:U(Y,{value:o.expiresAt})})]}),U(`div`,{children:[U(`dt`,{children:`Finished`}),U(`dd`,{children:U(Y,{value:o.finishedAt,fallback:Zr(o)?`Not recorded`:`In progress`})})]}),o.reason!==null&&U(`div`,{children:[U(`dt`,{children:`Reason`}),U(`dd`,{children:ei(o.reason)})]})]}),o.diagnostic!==null&&U(`details`,{children:[U(`summary`,{children:`Diagnostic details`}),U(`dl`,{class:`detail-list`,children:[U(`div`,{children:[U(`dt`,{children:`Stage`}),U(`dd`,{children:ei(o.diagnostic.stage)})]}),U(`div`,{children:[U(`dt`,{children:`Reason`}),U(`dd`,{children:ei(o.diagnostic.reason)})]}),o.diagnostic.httpStatus!==null&&U(`div`,{children:[U(`dt`,{children:`HTTP status`}),U(`dd`,{children:o.diagnostic.httpStatus})]}),U(`div`,{children:[U(`dt`,{children:`Correlation`}),U(`dd`,{children:o.diagnostic.correlationID})]})]})]})]})]}),U(ii,{mutations:e,flow:o,onRefresh:d})]})}var oi=/^[0-7][0-9A-HJKMNP-TV-Z]{25}$/,si=[`activate`,`reload`,`retry`,`refresh_catalog`,`credential_replace`,`disable`,`delete`,`disconnect_credentials`],ci=[`scheduled`,`running`,`succeeded`,`failed`,`cancelled`,`superseded`,`interrupted`],li=new Set(`configuration_invalid.resource_limit.connectivity.tls_failed.protocol_unsupported.protocol_invalid.authentication_rejected.credential_absent.keyring_absent.keyring_locked.keyring_interaction_required.keyring_unavailable.keyring_unsupported.oauth_rejected.oauth_expired.registration_expired.process_exited.output_limit.stop_unconfirmed.catalog_invalid.catalog_limit.catalog_stale.superseded.cancelled.interrupted.revocation_failed.revocation_unsupported.cleanup_pending`.split(`.`));function ui(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`invalid operation response`);let n=e;if(Object.keys(n).sort().join(`,`)!==[...t].sort().join(`,`))throw Error(`invalid operation response`);return n}function di(e){if(typeof e!=`string`)throw Error(`invalid operation response`);return e}function fi(e){if(e!==null&&typeof e!=`string`)throw Error(`invalid operation response`);return e}function pi(e){let t=di(e);if(!oi.test(t))throw Error(`invalid operation response`);return t}function mi(e,t){let n=di(e);if(!t.includes(n))throw Error(`invalid operation response`);return n}function hi(e){let t=fi(e);if(t!==null&&(t.length===0||t.length>512))throw Error(`invalid operation response`);return t}function gi(e){let t=ui(e,[`items`,`has_more`]);if(!Array.isArray(t.items)||t.items.length>2||typeof t.has_more!=`boolean`||t.has_more&&t.items.length!==2)throw Error(`invalid active operation response`);let n=t.items.map(_i);if(n.some(bi))throw Error(`invalid active operation response`);return{items:n,hasMore:t.has_more,nextCursor:null}}function _i(e){let t=ui(e,[`id`,`server_id`,`kind`,`target_desired_revision`,`target_credential_revisions`,`state`,`reason`,`created_at`,`started_at`,`finished_at`]),n=ui(t.target_credential_revisions,[`static_credential`,`oauth_client`,`oauth_tokens`]),r=fi(t.reason);if(r!==null&&!li.has(r))throw Error(`invalid operation response`);return{id:pi(t.id),serverID:pi(t.server_id),kind:mi(t.kind,si),targetDesiredRevision:di(t.target_desired_revision),targetStaticRevision:di(n.static_credential),targetOAuthClientRevision:di(n.oauth_client),targetOAuthTokensRevision:di(n.oauth_tokens),state:mi(t.state,ci),reason:r,createdAt:di(t.created_at),startedAt:fi(t.started_at),finishedAt:fi(t.finished_at)}}function vi(e){let t=ui(e,[`items`,`next_cursor`]);if(!Array.isArray(t.items))throw Error(`invalid operation response`);return{items:t.items.map(_i),nextCursor:hi(t.next_cursor)}}async function yi(e){if(e.headers.get(`Content-Type`)!==`application/json`)throw Error(`invalid operation response`);let t=await e.text();if(new TextEncoder().encode(t).byteLength>1048576)throw Error(`invalid operation response`);return _i(ui(JSON.parse(t),[`operation`]).operation)}function bi(e){return e.state!==`scheduled`&&e.state!==`running`}function xi(e){let t,n=document.createElement(`a`);try{return t=URL.createObjectURL(e),n.href=t,n.download=`agent-gateway-traffic-${new Date().toISOString().replaceAll(`:`,`-`)}.json`,n.hidden=!0,document.body.append(n),n.click(),!0}catch{return!1}finally{n.remove(),t!==void 0&&URL.revokeObjectURL(t)}}async function Si(e,t){let n=e;try{return await t(n),n=``,`copied`}catch{return n=``,`failed`}finally{n=``}}function Ci(e,t){let n=t(e,`_blank`,`noopener,noreferrer`);if(n===null)return`blocked`;try{n.opener=null}catch{}return`opened`}var wi=/^mgw_(?:admin|agent)_[A-Za-z0-9_-]{43}$/,Ti=/^127\.(?:0|[1-9][0-9]{0,2})\.(?:0|[1-9][0-9]{0,2})\.(?:0|[1-9][0-9]{0,2})$/,Ei=8192;function Di(e){if(e.length===0||new TextEncoder().encode(e).byteLength>Ei)return!1;let t;try{t=new URL(e)}catch{return!1}return t.href!==e||t.username!==``||t.password!==``||t.hash!==``?!1:t.protocol===`https:`?!0:t.protocol!==`http:`||!Ti.test(t.hostname)?!1:t.hostname.split(`.`).every(e=>Number(e)<=255)}var Oi=class{input;release;constructor(e){this.release=e}attach(e){this.input=e,e.value=``}detach(e){this.input===e&&(e.value=``,this.input=void 0)}read(){return this.input?.value??``}clear(){this.input!==void 0&&(this.input.value=``)}close(){this.clear(),this.input=void 0,this.release(this)}},ki=class{session;unregisterProtectedState;oneTimePresenter;oauthPresenter;writeOnlyValues=new Set;generation=0;active;constructor(e){this.session=e,this.unregisterProtectedState=e.registerProtectedState(()=>this.clear())}registerOneTimePresenter(e){return this.oneTimePresenter?.clear(),this.oneTimePresenter=e,()=>{this.oneTimePresenter===e&&(e.clear(),this.oneTimePresenter=void 0,this.active?.kind===`one_time`&&this.invalidate())}}registerOAuthPresenter(e){return this.oauthPresenter?.clear(),this.oauthPresenter=e,()=>{this.oauthPresenter===e&&(e.clear(),this.oauthPresenter=void 0,this.active?.kind===`oauth`&&this.invalidate())}}createWriteOnly(){let e=new Oi(e=>this.writeOnlyValues.delete(e));return this.writeOnlyValues.add(e),e}prepareOneTime(e){let t=this.session.snapshot(),n=this.oneTimePresenter;if(t.lifecycle!==`authenticated`||n===void 0||e.length===0||e.length>160)return;this.clear();let r=++this.generation;if(this.active={kind:`one_time`,generation:r,epoch:t.epoch},!n.prepare(e,r)){n.clear(),this.invalidate();return}return this.preparedOneTime(r,t.epoch)}prepareOAuth(e){let t=this.session.snapshot(),n=this.oauthPresenter;if(t.lifecycle!==`authenticated`||n===void 0||e.length===0||e.length>160)return;this.clear();let r=++this.generation;if(this.active={kind:`oauth`,generation:r,epoch:t.epoch},!n.prepare(e,r)){n.clear(),this.invalidate();return}return this.preparedOAuth(r,t.epoch)}isCurrent(e){let t=this.session.snapshot();return this.active?.generation===e&&this.active.epoch===t.epoch&&t.lifecycle===`authenticated`}dismiss(e){this.isCurrent(e)&&this.clear()}clearForNavigation(){this.clear()}close(){this.unregisterProtectedState(),this.clear();for(let e of[...this.writeOnlyValues])e.close()}preparedOneTime(e,t){let n=!1;return Object.freeze({publish:r=>n||(n=!0,!this.matches(`one_time`,e,t))?`lost`:!wi.test(r)||!this.oneTimePresenter?.publish(r,e)?(this.oneTimePresenter?.lose(e),`lost`):`published`,lose:()=>{n||(n=!0,this.matches(`one_time`,e,t)&&this.oneTimePresenter?.lose(e))},cancel:()=>{n||(n=!0,this.matches(`one_time`,e,t)&&this.clear())}})}preparedOAuth(e,t){let n=!1;return Object.freeze({publish:r=>n||(n=!0,!this.matches(`oauth`,e,t))?`lost`:!Di(r)||!this.oauthPresenter?.publish(r,e)?(this.oauthPresenter?.lose(e),`lost`):`published`,lose:()=>{n||(n=!0,this.matches(`oauth`,e,t)&&this.oauthPresenter?.lose(e))},cancel:()=>{n||(n=!0,this.matches(`oauth`,e,t)&&this.clear())}})}matches(e,t,n){return this.active?.kind===e&&this.active.generation===t&&this.active.epoch===n&&this.isCurrent(t)}clear(){this.oneTimePresenter?.clear(),this.oauthPresenter?.clear();for(let e of this.writeOnlyValues)e.clear();this.invalidate()}invalidate(){this.generation+=1,this.active=void 0}};function Ai(){let e=window.getSelection();e!==null&&e.removeAllRanges()}function ji({value:e,label:t,testID:n}){let[r,i]=z(`idle`),a=V(0);B(()=>{a.current+=1,i(`idle`)},[e]);let o=async()=>{let t=++a.current,n=await Si(e,e=>navigator.clipboard.writeText(e));a.current===t&&i(n)};return U(`div`,{class:`copyable-value`,children:[U(`code`,{"data-testid":n,children:e}),U(`button`,{class:`text-button`,type:`button`,"aria-label":`Copy ${t}`,onClick:()=>void o(),children:`Copy`}),U(`span`,{class:`copyable-value-status`,role:`status`,"aria-live":`polite`,children:[r===`copied`&&`${Mi(t)} copied.`,r===`failed`&&`Could not copy ${t}.`]})]})}function Mi(e){return`${e.charAt(0).toUpperCase()}${e.slice(1)}`}function Ni({value:e,id:t,label:n,hint:r,multiline:i=!1,placeholder:a,onInput:o}){let s=V(null),c=V(null);return xe(()=>{let t=i?c.current:s.current;if(t!==null)return e.attach(t),()=>e.detach(t)},[i,e]),U(J,{id:t,label:n,hint:r,required:!0,children:e=>i?U(`textarea`,{...e,ref:c,placeholder:a,rows:5,autocomplete:`off`,autocapitalize:`none`,spellcheck:!1,onInput:e=>o?.(e.currentTarget.value)}):U(`input`,{...e,ref:s,placeholder:a,type:`password`,autocomplete:`off`,autocapitalize:`none`,spellcheck:!1,onInput:e=>o?.(e.currentTarget.value)})})}function Pi({coordinator:e}){let t=V(null),[n,r]=z(0),[i,a]=z(``),[o,s]=z(``),[c,l]=z(`awaiting`),[u,d]=z(`idle`);B(()=>e.registerOneTimePresenter({prepare:(e,n)=>{let i=t.current;if(i===null||i.open)return!1;r(n),a(e),s(``),d(`idle`),l(`awaiting`);try{return i.showModal(),!0}catch{return!1}},publish:(n,r)=>t.current?.open!==!0||!e.isCurrent(r)?!1:(s(n),d(`idle`),l(`display`),!0),lose:t=>{e.isCurrent(t)&&(s(``),d(`idle`),l(`lost`),Ai())},clear:()=>{s(``),a(``),d(`idle`),l(`awaiting`),Ai(),t.current?.open&&t.current.close()}}),[e]);let f=async()=>{if(c!==`display`||o===``)return;let t=await Si(o,e=>navigator.clipboard.writeText(e));e.isCurrent(n)&&d(t)};return U(`dialog`,{ref:t,class:`sensitive-dialog`,"aria-labelledby":`one-time-display-title`,"aria-describedby":`one-time-display-warning`,onCancel:t=>{t.preventDefault(),e.dismiss(n)},children:[U(`h2`,{id:`one-time-display-title`,children:i||`One-time bearer`}),U(`p`,{id:`one-time-display-warning`,class:`sensitive-warning`,children:`This bearer cannot be recovered or shown again. Copying leaves it in the operating-system clipboard until you overwrite it; this application cannot revoke clipboard contents.`}),c===`awaiting`&&U(G,{state:`loading`,children:`Waiting for the response`}),c===`lost`&&U(G,{state:`unavailable`,children:`No bearer can be displayed. Inspect current state before another explicit action.`}),c===`display`&&U(`div`,{class:`one-time-value`,"data-testid":`one-time-value`,children:U(`code`,{children:o})}),U(`div`,{class:`sink-status`,role:`status`,"aria-live":`polite`,"aria-atomic":`true`,children:[u===`copied`&&`Copied to the operating-system clipboard.`,u===`failed`&&`Clipboard copy failed. The bearer was not echoed.`]}),U(`div`,{class:`dialog-actions`,children:[U(`button`,{type:`button`,onClick:()=>e.dismiss(n),children:`Dismiss and clear`}),c===`display`&&U(`button`,{class:`primary-action`,type:`button`,"data-testid":`copy-one-time-value`,onClick:()=>void f(),children:`Copy bearer`})]})]})}function Fi({coordinator:e}){let t=V(null),[n,r]=z(0),[i,a]=z(``),[o,s]=z(``),[c,l]=z(`awaiting`),[u,d]=z(!1),[f,p]=z(`idle`);B(()=>e.registerOAuthPresenter({prepare:(e,n)=>{let i=t.current;if(i===null||i.open)return!1;r(n),a(e),s(``),d(!1),p(`idle`),l(`awaiting`);try{return i.showModal(),!0}catch{return!1}},publish:(n,r)=>t.current?.open!==!0||!e.isCurrent(r)?!1:(s(n),d(!1),p(`idle`),l(`display`),!0),lose:t=>{e.isCurrent(t)&&(s(``),d(!1),p(`idle`),l(`lost`),Ai())},clear:()=>{s(``),a(``),d(!1),p(`idle`),l(`awaiting`),Ai(),t.current?.open&&t.current.close()}}),[e]);let m=()=>{if(c===`display`&&o!==``){if(Ci(o,()=>window.open(o,`_blank`,`noopener,noreferrer`))===`blocked`){d(!0),p(`idle`);return}s(``),Ai(),e.dismiss(n)}},h=async()=>{if(c!==`display`||o===``)return;let t=await Si(o,e=>navigator.clipboard.writeText(e));e.isCurrent(n)&&p(t)};return U(`dialog`,{ref:t,class:`sensitive-dialog`,"aria-labelledby":`oauth-display-title`,"aria-describedby":`oauth-display-warning`,onCancel:t=>{t.preventDefault(),e.dismiss(n)},children:[U(`h2`,{id:`oauth-display-title`,children:i||`Authorization URL`}),U(`p`,{id:`oauth-display-warning`,class:`sensitive-warning`,children:`Open this URL only when you are ready to continue authorization. It is kept only in this dialog and is cleared on dismissal or navigation.`}),c===`awaiting`&&U(G,{state:`loading`,children:`Waiting for the response`}),c===`lost`&&U(G,{state:`unavailable`,children:`No authorization URL can be displayed. Start a new flow from current state.`}),c===`display`&&U(`div`,{class:`one-time-url`,"data-testid":`one-time-oauth-url`,children:U(`code`,{children:o})}),U(`div`,{class:`sink-status`,role:`status`,"aria-live":`polite`,"aria-atomic":`true`,children:[u&&`The browser blocked the new page. The URL remains available in this dialog. Copying leaves it in the operating-system clipboard until you overwrite it.`,f===`copied`&&` Copied to the operating-system clipboard.`,f===`failed`&&` Clipboard copy failed.`]}),U(`div`,{class:`dialog-actions`,children:[U(`button`,{type:`button`,onClick:()=>e.dismiss(n),children:`Dismiss and clear`}),c===`display`&&u&&U(`button`,{type:`button`,"data-testid":`copy-oauth-url`,onClick:()=>void h(),children:`Copy URL`}),c===`display`&&U(`button`,{class:`primary-action`,type:`button`,"data-testid":`open-oauth-url`,onClick:m,children:`Open authorization page`})]})]})}function Ii({coordinator:e}){return U(S,{children:[U(Pi,{coordinator:e}),U(Fi,{coordinator:e})]})}function Li(e){if(e.desiredState===`deleted`||e.transport===null)return;let t=e.transport;if(t.kind===`stdio`){let n=t.secret_environment,r=[...new Set(Object.values(n))].sort();return r.length===0?void 0:{kind:`static_credential`,slots:r,expectedRevision:e.staticRevision}}let n=t.authentication??{};if(n.mode===`bearer`)return{kind:`static_credential`,slots:[`bearer`],expectedRevision:e.staticRevision};if(n.mode!==`oauth`)return;let r=n.registration??{};return r.mode===`static`&&(r.token_endpoint_auth_method===`client_secret_basic`||r.token_endpoint_auth_method===`client_secret_post`)?{kind:`oauth_client`,slots:[`client_secret`],expectedRevision:e.oauthClientRevision}:void 0}function Ri(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`invalid credential replacement response`);let n=e;if(Object.keys(n).sort().join(`,`)!==[...t].sort().join(`,`))throw Error(`invalid credential replacement response`);return n}async function zi(e){if(e.headers.get(`Content-Type`)!==`application/json`)throw Error(`invalid credential replacement response`);let t=await e.text();if(new TextEncoder().encode(t).byteLength>1048576)throw Error(`invalid credential replacement response`);let n=Ri(JSON.parse(t),[`server_id`,`kind`,`credential_revision`,`operation`]),r=_i(n.operation);if(typeof n.server_id!=`string`||r.serverID!==n.server_id||n.kind!==`static_credential`&&n.kind!==`oauth_client`||typeof n.credential_revision!=`string`||!/^(?:0|[1-9][0-9]*)$/.test(n.credential_revision)||r.kind!==`credential_replace`)throw Error(`invalid credential replacement response`);return{serverID:n.server_id,kind:n.kind,credentialRevision:n.credential_revision,operation:r}}function Bi({mutations:e,sinks:t,server:n,etag:r,readVersion:i,shape:a,onRefresh:o}){let[s]=z(()=>a.slots.map(e=>({slot:e,value:t.createWriteOnly()}))),[c]=z(()=>e.create()),[l,u]=z(()=>c.snapshot()),[d,f]=z(!1),[p,m]=z(),[h,g]=z(),[_,v]=z(),[y,b]=z(!1),x=V(null),C=Cr(y);B(()=>c.subscribe(u),[c]),B(()=>()=>{c.close();for(let e of s)e.value.close()},[c,s]);let w=()=>{b(s.some(({slot:e})=>{let t=document.getElementById(`credential-slot-${e}`);return(t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement)&&t.value!==``}))},T=()=>{for(let e of s)e.value.clear();b(!1)},E=async e=>{let t=await e;t.kind===`acknowledged`?(v(void 0),g(`Credential revision ${t.value.credentialRevision} was published; operation ${t.value.operation.id} was scheduled.`),c.abandon(),C(`#/mcp/servers/${n.id}/operations/${t.value.operation.id}`,!0)):(t.kind===`rejected`&&t.requiresRefresh||t.kind===`uncertain`)&&(v(i),o())},D=()=>{if(m(void 0),g(void 0),s.map(({slot:e})=>{let t=document.getElementById(`credential-slot-${e}`);return[e,t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement?t.value:``]}).some(([,e])=>e.length===0)){T(),m(`Enter every credential again; the fields were cleared.`);return}f(!0)},O=()=>{f(!1);let e=Object.fromEntries(s.map(({slot:e})=>{let t=document.getElementById(`credential-slot-${e}`);return[e,t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement?t.value:``]})),t=a.kind===`static_credential`?JSON.stringify({kind:a.kind,expected_revision:a.expectedRevision,values:e}):JSON.stringify({kind:a.kind,expected_revision:a.expectedRevision,client_secret:e.client_secret}),i={route:`/api/v2/mcp/servers/${n.id}/credential-replacements`,method:`POST`,body:t,precondition:r,requiresPrecondition:!0,idempotency:`none`,successStatuses:[202],uncertainProblemCodes:[`keyring_unavailable`],decode:async e=>{let t=await zi(e);if(t.serverID!==n.id||t.kind!==a.kind)throw Error(`invalid credential replacement response`);return t}};c.begin(i);let o=c.submit();T(),E(o)},k=_!==void 0&&i<=_,A=l.state===`submitting`||l.availability===`storage_latched`||k;return U(S,{children:[U(`form`,{"data-testid":`credential-replacement-form`,children:[s.map(({slot:e,value:t})=>U(Ni,{value:t,id:`credential-slot-${e}`,label:a.kind===`oauth_client`?`OAuth client secret`:n.transport.kind===`streamable_http`?`Bearer token`:`Secret slot ${e}`,placeholder:a.kind===`oauth_client`?`Enter OAuth client secret`:n.transport.kind===`streamable_http`?`Enter bearer token`:`Enter secret value`,hint:`Write-only. This value is cleared immediately after submission and is never returned by the Gateway.`,onInput:w},e)),p!==void 0&&U(K,{state:`error`,title:`Credential input required`,children:U(`p`,{children:p})}),l.problem!==void 0&&U(K,{state:`error`,title:l.problem.title,children:l.requiresRefresh&&U(`p`,{children:`A fresh server snapshot was requested. Re-enter credentials only after reviewing current revisions and operation history.`})}),l.state===`uncertain`&&U(K,{state:`warning`,title:`Replacement outcome unknown`,children:U(`p`,{children:`The credential or operation may have been published. No replay is available. Inspect the refreshed server and operation history before making a new decision.`})}),k&&U(`p`,{class:`session-message`,role:`status`,children:`Waiting for a newer authoritative server snapshot.`}),h!==void 0&&U(`p`,{class:`session-message`,role:`status`,children:h}),U(`button`,{ref:x,class:`danger-action form-submit-action`,type:`button`,"data-testid":`credential-replacement-submit`,disabled:A,onClick:D,children:`Review credential replacement`})]}),U(jn,{id:`credential-replacement-confirm`,open:d,title:`Replace current server authority?`,consequence:`Replacement withdraws current routing and may interrupt calls. Calls already handed downstream can have unknown outcomes. A native keyring operation may require OS interaction, fail, or outlive cancellation.`,confirmLabel:`Replace credential`,destructive:!0,returnFocus:x,onCancel:()=>{f(!1),T()},onConfirm:O})]})}function Vi(e){let t=`${e.shape.kind}:${e.shape.slots.join(`,`)}`,[n,r]=z(t);return B(()=>{n!==t&&r(t)},[n,t]),n===t?U(Bi,{...e}):null}function Hi(e){if(e.transport===null)return{heading:`Authentication`,description:`No active transport is configured.`,status:`Unavailable`,warning:!0};let t=e.transport,n=t.authentication??{},r=`Authentication`,i;if(t.kind===`stdio`){let e=t.secret_environment??{};Object.keys(e).length>0&&(r=`Local secrets`,i=`Replace the write-only values used by this local server.`)}else n.mode===`bearer`?(r=`Bearer token`,i=`Replace the write-only bearer token used for this server.`):n.mode===`oauth`&&(r=`OAuth client credentials`,i=`This client secret identifies your OAuth application. You must also authorize Gateway below to access the server.`);let a=[`absent`,`reauthentication_required`,`locked`,`interaction_required`,`unavailable`,`unsupported`].includes(e.credentialState);return{heading:r,description:i,status:i===void 0?`Not required`:a?`Action required`:`Configured`,warning:a}}function Ui({mutations:e,sinks:t,server:n,etag:r,readVersion:i,onRefresh:a}){let o=Li(n),s=Hi(n);return s.heading===`OAuth client credentials`&&o===void 0?null:U(`section`,{class:`panel domain-panel`,"aria-labelledby":`server-credentials-title`,"data-testid":`server-credentials`,children:[U(`div`,{class:`panel-heading`,children:[U(`div`,{children:U(`h2`,{id:`server-credentials-title`,children:s.heading})}),o?.kind===`oauth_client`?n.oauthClientRevision===`0`&&U(G,{state:`warning`,children:`Client secret required`}):U(G,{state:s.warning?`warning`:`current`,children:s.status})]}),s.description!==void 0&&U(`p`,{children:s.description}),o!==void 0&&U(Vi,{mutations:e,sinks:t,server:n,etag:r,readVersion:i,shape:o,onRefresh:a})]})}async function Wi(e,t){if(e.headers.get(`Content-Type`)!==`application/json`)throw Error(`invalid server deletion response`);let n=new Uint8Array(await e.arrayBuffer());if(n.byteLength>1048576)throw Error(`invalid server deletion response`);let r=JSON.parse(new TextDecoder(`utf-8`,{fatal:!0}).decode(n));if(typeof r!=`object`||!r||Array.isArray(r))throw Error(`invalid server deletion response`);let i=r;if(Object.keys(i).sort().join(`,`)!==`operation,server`)throw Error(`invalid server deletion response`);let a=t(i.server),o=_i(i.operation),s=e.headers.get(`ETag`);if(a.desiredState!==`deleted`||a.transport!==null||o.serverID!==a.id||o.kind!==`delete`||s!==`"server-${a.id}-${a.desiredRevision}"`)throw Error(`invalid server deletion response`);return{server:a,operation:o}}function Gi({mutations:e,server:t,etag:n,readVersion:r,decodeServerValue:i}){let[a]=z(()=>e.create()),[o,s]=z(()=>a.snapshot()),[c,l]=z(``),[u,d]=z(),f=V(null);if(B(()=>a.subscribe(s),[a]),B(()=>()=>a.close(),[a]),t.desiredState===`deleted`)return null;let p=u!==void 0&&r<=u,m=o.state===`submitting`||o.availability===`storage_latched`||p,h=async e=>{l(``);let n=await e;n.kind===`acknowledged`?(a.abandon(),window.location.hash=`#/mcp/servers/${t.id}/operations/${n.value.operation.id}`):n.kind===`rejected`&&n.requiresRefresh&&d(r)};return U(`section`,{class:`panel domain-panel`,"aria-labelledby":`server-destructive-title`,"data-testid":`server-destructive-actions`,children:[U(`div`,{class:`panel-heading`,children:U(`div`,{children:U(`h2`,{id:`server-destructive-title`,children:`Delete server`})})}),U(`p`,{children:`Permanent deletion tombstones this server identity, withdraws routing, and uses best-effort remote revocation for affected credentials.`}),U(`button`,{ref:f,class:`danger-action`,type:`button`,"data-testid":`delete-server`,disabled:m,onClick:()=>{l(``),a.begin({route:`/api/v2/mcp/servers/${t.id}`,method:`DELETE`,body:`{}`,precondition:n,requiresPrecondition:!0,idempotency:`none`,successStatuses:[200,202],decode:e=>Wi(e,i)}),a.confirm()},children:`Review permanent deletion`}),p&&U(`p`,{class:`session-message`,role:`status`,children:`Waiting for a newer authoritative server snapshot.`}),o.problem!==void 0&&U(K,{state:`error`,title:o.problem.title}),o.state===`uncertain`&&U(K,{state:`warning`,title:`Deletion outcome unknown`,children:U(`p`,{children:`Refresh the permanent server identity and operation history. Do not replay, force deletion, or infer remote cleanup.`})}),U(An,{id:`server-delete-confirm`,open:o.state===`confirming`,title:`Permanently delete this server?`,consequence:U(`p`,{children:`This tombstones the permanent identity and immutable namespace, withdraws routing, invalidates local authority, and attempts remote revocation only on a best-effort basis. Cleanup may remain pending. There is no force or authority-restoration path.`}),expected:t.namespace,value:c,confirmLabel:`Permanently delete server`,returnFocus:f,onValue:l,onCancel:()=>{l(``),a.abandon()},onConfirm:()=>void h(a.submit())})]})}function Ki(e){if(e.length>8192)return!1;let t=/^https:\/\/([a-z0-9.-]+)(?::([0-9]+))?$/.exec(e);if(t===null||t[0]!==e)return!1;let n=t[1],r=t[2];if(n.length>253||n.split(`.`).some(e=>e.length>63||!/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(e))||r!==void 0&&(Number(r)<1||Number(r)>65535||Number(r)===443))return!1;let i=n.split(`.`);return!(i.length===4&&i.every(e=>/^(0|[1-9][0-9]{0,2})$/.test(e)&&Number(e)<=255))}var qi=class extends Error{field;itemID;constructor(e,t,n){super(t),this.field=e,this.itemID=n}},Ji=/^[a-z][a-z0-9_-]{0,31}$/,Yi=/^[a-z][a-z0-9_]{0,63}$/,Xi=/^\/(?:[^\0]*)$/,Zi=0,Qi={auto:`Automatic (recommended)`,modern:`Current only — 2026-07-28`,legacy:`Legacy only — 2025-11-25`},$i={none:`Public client — no client secret`,client_secret_basic:`Client secret in HTTP Basic`,client_secret_post:`Client secret in request body`};function ea(e){return Xi.test(e)?e===`/`||e.endsWith(`/`)===!1&&e.slice(1).split(`/`).every(e=>e!==``&&e!==`.`&&e!==`..`):!1}function ta(e){let t={configuration:`Server configuration`,namespace:`Namespace`,display_name:`Display name`,enabled:`Initial state`,transport:`Connection`,"transport.kind":`Connection type`,"transport.executable":`Executable`,"transport.arguments":`Arguments`,"transport.working_directory":`Working directory`,"transport.environment":`Environment`,"transport.secret_environment":`Secret environment bindings`,"transport.headers":`Custom HTTP headers`,"transport.url":`HTTP endpoint`,"transport.protocol_mode":`Protocol mode`,"transport.authentication":`Authentication`,"transport.authentication.mode":`Authentication mode`,"transport.authentication.trusted_origins":`Trusted origins`,"transport.authentication.request_offline_access":`Offline access policy`,"transport.authentication.callback_uri":`Callback URI`,"transport.authentication.auth_server_metadata_url":`Authorization metadata URL`,"transport.authentication.scopes":`Initial scopes`,"transport.authentication.registration":`OAuth registration`,"transport.authentication.registration.mode":`OAuth registration mode`,"transport.authentication.registration.issuer":`OAuth issuer`,"transport.authentication.registration.client_id":`OAuth client ID`,"transport.authentication.registration.token_endpoint_auth_method":`Token endpoint authentication method`}[e.field]??`Server configuration`;switch(e.rule){case`required`:return`${t} is required.`;case`maximum`:return`${t} exceeds its maximum size or item count.`;case`unique`:return`${t} must not contain duplicates.`;case`disjoint`:return`${t} conflicts with another configuration source.`;case`canonical_absolute_path`:return`${t} must be an absolute canonical path without a trailing slash, empty segment, ".", or ".." segment.`;case`canonical_url`:return e.field===`transport.authentication.callback_uri`?`Callback URI must match Gateway's configured HTTPS origin and /oauth/callback, or use an HTTP loopback URL with an explicit port and path in local mode.`:e.field===`transport.authentication.auth_server_metadata_url`?`Authorization metadata URL must be an exact canonical HTTPS URL with a path and without credentials or fragment. A bounded query is allowed.`:`${t} must be a canonical URL without credentials, a query, fragment, uppercase hostname, or default port.`;case`transport_policy`:return`${t} does not satisfy the selected transport security policy.`;default:return`${t} is invalid.`}}function na(e){return Zi+=1,`${e}-${Zi}`}function ra(e,t){return t.map(t=>({id:na(e),value:t}))}function ia(e,t){return Object.entries(t).map(([t,n])=>({id:na(e),name:t,value:n}))}function aa(e,t){let n=Object.create(null);for(let r of e){if(r.name===``)throw Error(`${t} names cannot be empty.`);if(Object.hasOwn(n,r.name))throw Error(`${t} names must be unique.`);n[r.name]=r.value}return n}function oa(){return{namespace:``,displayName:``,enabled:!1,transportKind:``,executable:``,arguments:[],workingDirectory:``,environment:[],secretEnvironment:[],url:``,headers:[],protocolMode:`auto`,authMode:``,registrationMode:`dynamic`,issuer:``,clientID:``,tokenEndpointAuthMethod:`none`,trustedOrigins:[],requestOfflineAccess:!1,callbackURI:``,authServerMetadataURL:``,explicitScopes:!1,scopes:[]}}function sa(e){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`Expected a JSON object.`);return e}function ca(e){if(Array.isArray(e))return`[${e.map(ca).join(`,`)}]`;if(typeof e==`object`&&e){let t=e;return`{${Object.keys(t).sort().map(e=>`${JSON.stringify(e)}:${ca(t[e])}`).join(`,`)}}`}return JSON.stringify(e)}function la(e){let t=sa(e);if(t.kind!==`streamable_http`)return ca(t);let n=sa(t.authentication);return n.mode===`oauth`?ca({...t,authentication:{...n,trusted_origins:[...n.trusted_origins].sort()}}):ca(t)}function ua(e){let t=Object.create(null),n=new Set,r=new Set(`authorization.authentication-info.www-authenticate.cookie.cookie2.set-cookie.set-cookie2.api-key.x-api-key.x-auth-token.x-access-token.x-authorization.host.connection.keep-alive.te.trailer.transfer-encoding.upgrade.expect.forwarded.via.x-real-ip.x-original-url.x-rewrite-url.x-http-method-override.origin.referer.accept.user-agent.range.cache-control.pragma.max-forwards.date`.split(`.`)),i=0;if(e.length>16)throw new qi(`headers`,`Use at most 16 custom HTTP headers.`);for(let[a,o]of e.entries()){let e=o.name.toLowerCase(),s=`Header ${a+1}`;if(!/^[!#$%&'*+.^_`|~0-9a-z-]{1,128}$/i.test(o.name))throw new qi(`headers`,`${s}: enter an HTTP token name of 1–128 ASCII bytes, without spaces or a colon.`);if(n.has(e))throw new qi(`headers`,`${s}: names must be unique regardless of letter case.`);if(r.has(e)||/^(mcp-|proxy-|sec-|x-forwarded-|content-|accept-|if-)/.test(e))throw new qi(`headers`,`${s}: this name is reserved for authentication, routing, HTTP, or MCP protocol control. Use Authentication for credentials.`);if(!/^[\x20-\x7e]{0,4096}$/.test(o.value)||o.value.trim()!==o.value)throw new qi(`headers`,`${s}: use at most 4096 printable ASCII bytes, without leading/trailing spaces, tabs, or line breaks. Empty values are allowed.`);n.add(e),i+=o.name.length+o.value.length,t[o.name]=o.value}if(i>8192)throw new qi(`headers`,`Custom header names and values together must not exceed 8192 bytes.`);return t}function da(e){if(e.transportKind===``)throw Error(`Choose how Gateway connects to this server.`);if(e.transportKind===`stdio`){let t=e.arguments.map(e=>e.value),n=aa(e.environment,`Environment variable`),r=aa(e.secretEnvironment,`Secret environment binding`);if(!ea(e.executable))throw Error(`Executable must be an absolute canonical path without a trailing slash, empty segment, ".", or ".." segment.`);if(!ea(e.workingDirectory))throw Error(`Working directory must be an absolute canonical path without a trailing slash, empty segment, ".", or ".." segment.`);if(t.length>64)throw Error(`At most 64 arguments are allowed.`);if(Object.keys(n).length>32)throw Error(`At most 32 ordinary environment entries are allowed.`);if(Object.keys(r).length>16)throw Error(`At most 16 secret environment slots are allowed.`);for(let[e,t]of Object.entries(r)){if(!Yi.test(t))throw Error(`Secret environment ${e} must name a keyring slot.`);if(Object.hasOwn(n,e))throw Error(`${e} cannot be both ordinary and secret environment.`)}return{kind:`stdio`,executable:e.executable,arguments:t,working_directory:e.workingDirectory,environment:n,secret_environment:r}}if(e.authMode===``)throw Error(`Choose how Gateway authenticates to this server.`);let t=e.url.trim();if(t===``)throw new qi(`url`,`Enter an HTTP endpoint.`);let n;try{n=new URL(t)}catch{throw new qi(`url`,`HTTP URL must be absolute.`)}if(n.protocol!==`http:`&&n.protocol!==`https:`)throw new qi(`url`,`HTTP endpoint must use http or https.`);if(n.username!==``||n.password!==``||n.search!==``||n.hash!==``)throw new qi(`url`,`HTTP URL cannot contain credentials, query, or fragment.`);let r;if(e.authMode===`none`||e.authMode===`bearer`)r={mode:e.authMode};else{let t=[],n=new Set;for(let r of e.trustedOrigins){let e=r.value.trim();if(e===``)throw new qi(`origin`,`Enter an OAuth network origin.`,r.id);if(!Ki(e))throw new qi(`origin`,`Use a lowercase DNS origin without an IP address, path, or default port.`,r.id);if(n.has(e))throw new qi(`origin`,`OAuth network origins must be unique.`,r.id);n.add(e),t.push(e)}let i=e.issuer.trim();if(i!==``){let e;try{e=new URL(i)}catch{throw new qi(`issuer`,`OAuth issuer must be an absolute HTTPS URL.`)}if(e.protocol!==`https:`||e.username!==``||e.password!==``||e.search!==``||e.hash!==``)throw new qi(`issuer`,`OAuth issuer must be an HTTPS URL without credentials, query, or fragment.`)}let a=e.clientID.trim();if(e.registrationMode===`static`&&a.length===0)throw new qi(`clientID`,`Enter the OAuth client ID.`);let o=e.callbackURI;if(o.startsWith(`https://`)){let e;try{e=new URL(o)}catch{}if(e===void 0||e.href!==o||e.username!==``||e.password!==``||e.pathname!==`/oauth/callback`||e.search!==``||e.hash!==``||/[?#%\\\\\s]/.test(o)||new TextEncoder().encode(o).byteLength>8192)throw new qi(`callbackURI`,`Use Gateway's exact configured HTTPS origin followed by /oauth/callback, or leave blank for the default.`)}else if(o!==``){let e=/^http:\/\/(localhost|127(?:\.[0-9]{1,3}){3}|\[::1\]):([1-9][0-9]{0,4})(\/[^?#%\\\s]*)$/.exec(o);if(e===null||Number(e[2])>65535||!ea(e[3]??``)||new URL(o).pathname!==e[3]||e[1]?.startsWith(`127.`)&&e[1].split(`.`).some(e=>Number(e)>255||String(Number(e))!==e)||new TextEncoder().encode(o).byteLength>8192)throw new qi(`callbackURI`,`Use Gateway's exact configured HTTPS origin followed by /oauth/callback. In local mode, use an exact HTTP loopback URI with an explicit port and canonical path.`)}let s=e.authServerMetadataURL;if(s!==``){let e;try{e=new URL(s)}catch{throw new qi(`authServerMetadataURL`,`Enter an absolute HTTPS metadata URL.`)}if(e.protocol!==`https:`||e.username!==``||e.password!==``||s.includes(`#`)||e.href!==s||new TextEncoder().encode(s).byteLength>8192||!ea(e.pathname))throw new qi(`authServerMetadataURL`,`Use the exact canonical HTTPS metadata URL with a path, without credentials or fragment. A bounded query is allowed.`)}let c=e.scopes.map(e=>e.value);if(e.explicitScopes&&(c.length>64||c.some(e=>!/^[\x21\x23-\x5b\x5d-\x7e]{1,256}$/.test(e))||[...new Set(c)].join(` `).length>8192))throw new qi(`scopes`,`Enter one scope per row, without spaces, quotes, or backslashes. Remove unused rows. Use at most 64 ASCII scopes (256 bytes each, 8192 bytes total).`);r={mode:`oauth`,registration:e.registrationMode===`static`?{mode:`static`,issuer:i===``?null:i,client_id:a,token_endpoint_auth_method:e.tokenEndpointAuthMethod}:{mode:`dynamic`,issuer:i===``?null:i},trusted_origins:t,request_offline_access:e.requestOfflineAccess,...o===``?{}:{callback_uri:o},...s===``?{}:{auth_server_metadata_url:s},...e.explicitScopes?{scopes:[...new Set(c)].sort()}:{}}}return{kind:`streamable_http`,url:t,protocol_mode:e.protocolMode,...e.headers.length===0?{}:{headers:ua(e.headers)},authentication:r}}function fa(e){let t=oa();t.namespace=e.namespace,t.displayName=e.displayName,t.enabled=e.desiredState===`enabled`;let n=e.transport;if(n.kind===`stdio`)return t.transportKind=`stdio`,t.executable=n.executable,t.arguments=ra(`argument`,n.arguments),t.workingDirectory=n.working_directory,t.environment=ia(`environment`,n.environment),t.secretEnvironment=ia(`secret-environment`,n.secret_environment),t;t.transportKind=`streamable_http`,t.url=n.url,t.headers=ia(`header`,n.headers??{}),t.protocolMode=n.protocol_mode;let r=n.authentication;if(t.authMode=r.mode,t.authMode!==`oauth`)return t;let i=r.registration;return t.registrationMode=i.mode,t.issuer=i.issuer??``,t.clientID=i.client_id??``,t.tokenEndpointAuthMethod=i.token_endpoint_auth_method??`none`,t.trustedOrigins=ra(`oauth-origin`,r.trusted_origins),t.requestOfflineAccess=r.request_offline_access,t.callbackURI=r.callback_uri??``,t.authServerMetadataURL=r.auth_server_metadata_url??``,t.explicitScopes=r.scopes!==void 0,t.scopes=ra(`scope`,r.scopes??[]),t}function pa(e){return e===null?null:_i(e).id}async function ma(e,t){if(e.headers.get(`Content-Type`)!==`application/json`)throw Error(`invalid mutation response`);let n=await e.text();if(new TextEncoder().encode(n).byteLength>1048576)throw Error(`invalid mutation response`);let r=sa(JSON.parse(n));if(Object.keys(r).sort().join(`,`)!==`operation,server`)throw Error(`invalid mutation response`);let i=t(r.server),a=e.headers.get(`ETag`);if(a!==`"server-${i.id}-${i.desiredRevision}"`)throw Error(`invalid mutation response`);return{server:i,operationID:pa(r.operation),etag:a}}function ha({id:e,label:t,hint:n,itemLabel:r,addLabel:i,items:a,disabled:o,placeholder:s,errors:c={},error:l,onChange:u}){return U(`fieldset`,{class:`collection-field`,id:e,"aria-describedby":l===void 0?`${e}-hint`:`${e}-hint ${e}-error`,"aria-invalid":l!==void 0||void 0,children:[U(`legend`,{children:[t,U(`span`,{class:`optional-label`,children:` (optional)`})]}),U(`p`,{class:`field-hint`,id:`${e}-hint`,children:n}),l!==void 0&&U(`span`,{class:`field-error`,id:`${e}-error`,role:`alert`,children:l}),a.map((t,n)=>U(`div`,{class:`collection-row`,children:[U(`label`,{class:`visually-hidden`,for:`${e}-${t.id}`,children:[r,` `,n+1]}),U(`input`,{id:`${e}-${t.id}`,"data-testid":e,value:t.value,placeholder:s,disabled:o,"aria-invalid":c[t.id]===void 0&&l===void 0?void 0:!0,"aria-describedby":[`${e}-hint`,...l===void 0?[]:[`${e}-error`],...c[t.id]===void 0?[]:[`${e}-${t.id}-error`]].join(` `),onInput:e=>u(a.map(n=>n.id===t.id?{...n,value:e.currentTarget.value}:n))}),U(`button`,{type:`button`,disabled:o,"aria-label":`Remove ${r.toLowerCase()} ${n+1}`,onClick:()=>u(a.filter(e=>e.id!==t.id)),children:`Remove`}),c[t.id]!==void 0&&U(`span`,{class:`field-error collection-error`,id:`${e}-${t.id}-error`,role:`alert`,children:c[t.id]})]},t.id)),U(`button`,{type:`button`,class:`quiet-action`,"data-testid":`${e}-add`,disabled:o,onClick:()=>u([...a,{id:na(e),value:``}]),children:i})]})}function ga({id:e,label:t,hint:n,nameLabel:r,valueLabel:i,addLabel:a,valueRequired:o=!0,error:s,items:c,disabled:l,onChange:u}){return U(`fieldset`,{class:`collection-field`,"aria-describedby":s===void 0?`${e}-hint`:`${e}-hint ${e}-error`,"aria-invalid":s!==void 0||void 0,children:[U(`legend`,{children:[t,U(`span`,{class:`optional-label`,children:` (optional)`})]}),U(`p`,{class:`field-hint`,id:`${e}-hint`,children:n}),s!==void 0&&U(`span`,{class:`field-error`,id:`${e}-error`,role:`alert`,children:s}),c.map((n,a)=>U(`div`,{class:`collection-row collection-pair`,children:[U(`label`,{class:`visually-hidden`,for:`${e}-${n.id}-name`,children:[r,` `,a+1]}),U(`input`,{id:`${e}-${n.id}-name`,"data-testid":`${e}-name`,value:n.name,required:!0,placeholder:r,disabled:l,onInput:e=>u(c.map(t=>t.id===n.id?{...t,name:e.currentTarget.value}:t))}),U(`label`,{class:`visually-hidden`,for:`${e}-${n.id}-value`,children:[i,` `,a+1]}),U(`input`,{id:`${e}-${n.id}-value`,"data-testid":`${e}-value`,value:n.value,required:o,placeholder:i,disabled:l,onInput:e=>u(c.map(t=>t.id===n.id?{...t,value:e.currentTarget.value}:t))}),U(`button`,{type:`button`,disabled:l,"aria-label":`Remove ${t.toLowerCase()} row ${a+1}`,onClick:()=>u(c.filter(e=>e.id!==n.id)),children:`Remove`})]},n.id)),U(`button`,{type:`button`,class:`quiet-action`,"data-testid":`${e}-add`,disabled:l,onClick:()=>u([...c,{id:na(e),name:``,value:``}]),children:a})]})}function _a({draft:e,setDraft:t,disabled:n,namespaceLocked:r,urlError:i,issuerError:a,clientIDError:o,originErrors:s,compatibilityErrors:c,configurationError:l,clearFieldError:u}){let[d,f]=z(()=>e.issuer!==``||e.callbackURI!==``||e.authServerMetadataURL!==``||e.explicitScopes||e.trustedOrigins.length>0||e.requestOfflineAccess);B(()=>{let e=l?.field;(a!==void 0||Object.keys(c).some(e=>e!==`headers`)||Object.keys(s).length>0||e!==void 0&&[`transport.authentication.registration.issuer`,`transport.authentication.callback_uri`,`transport.authentication.auth_server_metadata_url`,`transport.authentication.scopes`,`transport.authentication.trusted_origins`,`transport.authentication.request_offline_access`].includes(e))&&f(!0)},[a,c,s,l]);let p=(n,r)=>t({...e,[n]:r});return U(S,{children:[U(`p`,{class:`form-convention`,children:`All fields are required unless marked optional.`}),U(J,{id:`server-namespace`,label:`Namespace`,hint:`Namespace cannot be changed after creation. It prefixes this server's tool names. Use 1–32 lowercase letters, digits, underscores, or hyphens, starting with a letter; mcp_gateway is reserved.`,required:!0,children:t=>U(`input`,{...t,placeholder:`example_tools`,value:e.namespace,disabled:n,readOnly:r,onInput:e=>p(`namespace`,e.currentTarget.value)})}),U(J,{id:`server-display-name`,label:`Display name`,hint:`A recognizable name for this server in Gateway. You can change it later.`,required:!0,children:t=>U(`input`,{...t,placeholder:`Example Tools`,value:e.displayName,disabled:n,onInput:e=>p(`displayName`,e.currentTarget.value)})}),U(J,{id:`server-enabled`,label:`Server enabled`,hint:`When enabled, Gateway will try to connect when you save this server. Leave disabled to finish configuring credentials first.`,children:t=>U(On,{attributes:t,checked:e.enabled,disabled:n,testID:`server-enabled`,onChange:e=>p(`enabled`,e)})}),U(`fieldset`,{class:`choice-field`,children:[U(`legend`,{children:`Connection method`}),U(`label`,{children:[U(`input`,{id:`server-transport-stdio`,name:`server-transport-kind`,type:`radio`,value:`stdio`,checked:e.transportKind===`stdio`,disabled:n,required:!0,onChange:()=>p(`transportKind`,`stdio`)}),U(`span`,{children:[U(`strong`,{children:`Local process (stdio)`}),U(`small`,{children:`Gateway launches a local executable.`})]})]}),U(`label`,{children:[U(`input`,{id:`server-transport-http`,name:`server-transport-kind`,type:`radio`,value:`streamable_http`,checked:e.transportKind===`streamable_http`,disabled:n,required:!0,onChange:()=>p(`transportKind`,`streamable_http`)}),U(`span`,{children:[U(`strong`,{children:`HTTP endpoint`}),U(`small`,{children:`Gateway connects to a Streamable HTTP server.`})]})]})]}),e.transportKind===`stdio`&&U(S,{children:[U(`p`,{class:`bounded-note`,children:`Gateway runs this executable directly as its operating-system user. It is not sandboxed.`}),U(J,{id:`server-executable`,label:`Executable`,hint:`Enter the full path to the executable on the Gateway host. Shell expressions such as ~ and $HOME are not expanded.`,required:!0,children:t=>U(`input`,{...t,placeholder:`/usr/local/bin/example-mcp-server`,value:e.executable,disabled:n,onInput:e=>p(`executable`,e.currentTarget.value)})}),U(J,{id:`server-working-directory`,label:`Working directory`,hint:`Enter the full path to the directory the process should run in, on the Gateway host.`,required:!0,children:t=>U(`input`,{...t,placeholder:`/opt/example-mcp-server`,value:e.workingDirectory,disabled:n,onInput:e=>p(`workingDirectory`,e.currentTarget.value)})}),U(ha,{id:`server-argument`,label:`Arguments`,hint:`Add one command-line argument per row, in order. Values are passed as written, without shell expansion or shell quoting.`,itemLabel:`Argument`,addLabel:`Add argument`,placeholder:`--verbose`,items:e.arguments,disabled:n,onChange:e=>p(`arguments`,e)}),U(ga,{id:`server-environment`,label:`Environment variables`,addLabel:`Add variable`,hint:`Add non-secret environment variables for the process. Use Secret environment bindings for passwords and tokens.`,nameLabel:`Variable name`,valueLabel:`Value`,valueRequired:!1,items:e.environment,disabled:n,onChange:e=>p(`environment`,e)}),U(ga,{id:`server-secret-environment`,label:`Secret environment bindings`,addLabel:`Add binding`,hint:r?`Map each environment variable to a credential slot name, not a secret value. Manage the matching secret under Authentication.`:`Map each environment variable to a credential slot name, not a secret value. After creating the server, add the matching secret under Authentication.`,nameLabel:`Environment variable`,valueLabel:`Credential slot`,items:e.secretEnvironment,disabled:n,onChange:e=>p(`secretEnvironment`,e)})]}),e.transportKind===`streamable_http`&&U(S,{children:[U(J,{id:`server-url`,label:`HTTP endpoint`,hint:`Enter the server's full MCP endpoint URL, including its path. Do not include credentials, a query string, or a fragment.`,...i===void 0?{}:{error:i},required:!0,children:t=>U(`input`,{...t,placeholder:`https://mcp.example.invalid/mcp`,value:e.url,disabled:n,onInput:e=>{u(`url`),p(`url`,e.currentTarget.value)}})}),U(ga,{id:`server-header`,label:`Custom HTTP headers`,hint:`Non-secret values only. Headers are stored in plaintext and visible to administrators. Never enter tokens, API keys, passwords, or cookies.`,nameLabel:`Header name`,valueLabel:`Header value`,addLabel:`Add header`,valueRequired:!1,items:e.headers,disabled:n,...c.headers===void 0?{}:{error:c.headers},onChange:e=>{u(`headers`),p(`headers`,e)}}),U(J,{id:`server-protocol-mode`,label:`Protocol preference`,hint:`Keep Automatic unless the provider requires a specific version. It tries the current protocol and uses legacy only if the server explicitly reports that the current version is unsupported.`,required:!0,children:t=>U(`select`,{...t,value:e.protocolMode,disabled:n,onChange:e=>p(`protocolMode`,e.currentTarget.value),children:[U(`option`,{value:`auto`,children:Qi.auto}),U(`option`,{value:`modern`,children:Qi.modern}),U(`option`,{value:`legacy`,children:Qi.legacy})]})}),U(`fieldset`,{class:`choice-field`,children:[U(`legend`,{children:`Authentication`}),U(`p`,{class:`field-hint`,children:`Choose the authentication method required by the server. Tokens and client secrets are managed separately and stored in the operating-system keyring, not in this form.`}),[[`none`,`No authentication`],[`bearer`,`Bearer token`],[`oauth`,`OAuth`]].map(([t,r])=>U(`label`,{children:[U(`input`,{id:`server-auth-${t}`,name:`server-auth-mode`,type:`radio`,value:t,checked:e.authMode===t,disabled:n,required:!0,onChange:()=>p(`authMode`,t)}),U(`span`,{children:r})]},t))]}),e.authMode===`bearer`&&U(`p`,{class:`bounded-note`,children:[r?`Manage this server's bearer token under Authentication.`:`After creating the server, add its bearer token under Authentication.`,` `,`Gateway stores it in the keyring and sends it in the Authorization header.`]}),e.authMode===`oauth`&&U(S,{children:[U(`p`,{class:`bounded-note`,children:[r?`Start or manage OAuth authorization under Authentication.`:`After creating the server, open Authentication to authorize Gateway with the provider.`,` `,`Gateway stores access and refresh tokens in the keyring.`]}),U(J,{id:`server-registration-mode`,label:`OAuth client registration`,hint:e.registrationMode===`dynamic`?`Gateway registers a client when you start authorization. The provider must support automatic client registration.`:`Use an OAuth application you have already registered with the provider. Enter its client details below.`,required:!0,children:t=>U(`select`,{...t,value:e.registrationMode,disabled:n,onChange:e=>p(`registrationMode`,e.currentTarget.value),children:[U(`option`,{value:`dynamic`,children:`Register Gateway automatically`}),U(`option`,{value:`static`,children:`Use an existing OAuth client`})]})}),e.registrationMode===`static`&&U(S,{children:[U(J,{id:`server-client-id`,label:`Client ID`,hint:`Enter the client ID assigned when you registered your OAuth application with the provider. This is not the client secret.`,...o===void 0?{}:{error:o},required:!0,children:t=>U(`input`,{...t,placeholder:`example-gateway-client`,value:e.clientID,disabled:n,onInput:e=>{u(`clientID`),p(`clientID`,e.currentTarget.value)}})}),U(J,{id:`server-token-auth`,label:`Token endpoint authentication`,hint:`Choose the method configured for your OAuth application. For either client-secret method, add the secret separately under Authentication.`,required:!0,children:t=>U(`select`,{...t,value:e.tokenEndpointAuthMethod,disabled:n,onChange:e=>p(`tokenEndpointAuthMethod`,e.currentTarget.value),children:[U(`option`,{value:`none`,children:$i.none}),U(`option`,{value:`client_secret_basic`,children:$i.client_secret_basic}),U(`option`,{value:`client_secret_post`,children:$i.client_secret_post})]})})]}),U(`details`,{class:`form-disclosure`,open:d,onToggle:e=>f(e.currentTarget.open),children:[U(`summary`,{children:d?`Hide advanced OAuth settings`:`Show advanced OAuth settings`}),U(J,{id:`server-issuer`,label:`OAuth issuer URL`,hint:`Enter the exact HTTPS issuer URL from your provider's OAuth documentation, not its authorization or token endpoint. You can leave this blank if the MCP server advertises exactly one issuer with the same scheme, hostname, and port as its HTTP endpoint.`,...a===void 0?{}:{error:a},optional:!0,children:t=>U(`input`,{...t,placeholder:`https://auth.example.invalid`,value:e.issuer,disabled:n,onInput:e=>{u(`issuer`),p(`issuer`,e.currentTarget.value)}})}),U(J,{id:`server-callback-uri`,label:`Callback URI`,optional:!0,hint:`Leave blank for Gateway's default callback. Remote mode requires the exact configured HTTPS origin followed by /oauth/callback. Local mode also supports an HTTP loopback redirect with an explicit free port and path.`,...c.callbackURI===void 0?{}:{error:c.callbackURI},children:t=>U(`input`,{...t,value:e.callbackURI,disabled:n,placeholder:`http://localhost:3118/callback`,onInput:e=>{u(`callbackURI`),p(`callbackURI`,e.currentTarget.value)}})}),U(J,{id:`server-auth-metadata-url`,label:`Authorization metadata URL`,optional:!0,hint:`Leave blank for standard OAuth discovery. Set this only if your provider specifies a different HTTPS metadata URL. It does not change the issuer; if this URL fails, Gateway will not try another location.`,...c.authServerMetadataURL===void 0?{}:{error:c.authServerMetadataURL},children:t=>U(`input`,{...t,placeholder:`https://auth.example.invalid/.well-known/oauth-authorization-server`,value:e.authServerMetadataURL,disabled:n,onInput:e=>{u(`authServerMetadataURL`),p(`authServerMetadataURL`,e.currentTarget.value)}})}),U(`label`,{class:`checkbox-field`,for:`server-explicit-scopes`,children:[U(`input`,{id:`server-explicit-scopes`,type:`checkbox`,checked:e.explicitScopes,disabled:n,onChange:e=>p(`explicitScopes`,e.currentTarget.checked)}),U(`span`,{children:[U(`strong`,{children:`Configure initial scopes explicitly`}),U(`small`,{children:`Leave off to use the MCP server's advertised defaults. Turn on to choose scopes below; an empty list requests no initial scopes. Offline access is controlled separately.`})]})]}),e.explicitScopes&&U(ha,{id:`server-initial-scopes`,label:`Initial scopes`,hint:`Add scope names from your provider's documentation, one per row. These replace the server's defaults; duplicates are removed. Adding permissions later requires authorizing the server again.`,itemLabel:`Scope`,addLabel:`Add scope`,placeholder:`read:tools`,items:e.scopes,disabled:n,...c.scopes===void 0?{}:{error:c.scopes},onChange:e=>{u(`scopes`),p(`scopes`,e)}}),U(ha,{id:`server-oauth-origin`,label:`Additional OAuth origins allowed on restricted networks`,hint:`Allow OAuth connections to additional private-network or loopback hosts. Enter each HTTPS origin (scheme, hostname, and optional port), without a path. The MCP server's origin is already allowed. This does not relax TLS checks or browser access rules.`,itemLabel:`OAuth origin`,addLabel:`Add OAuth origin`,placeholder:`https://auth.example.invalid`,items:e.trustedOrigins,disabled:n,errors:s,onChange:e=>{u(`origin`),p(`trustedOrigins`,e)}}),U(`label`,{class:`checkbox-field`,for:`server-offline-access`,children:[U(`input`,{id:`server-offline-access`,type:`checkbox`,checked:e.requestOfflineAccess,disabled:n,onChange:e=>p(`requestOfflineAccess`,e.currentTarget.checked)}),U(`span`,{children:[U(`strong`,{children:`Request offline access when supported`}),U(`small`,{children:`Ask for offline_access so Gateway can refresh access without another sign-in. Gateway requests it only if the provider advertises support; a refresh token is not guaranteed.`})]})]})]})]})]})]})}function va({draft:e}){let t=e.transportKind===`stdio`?`Local process — ${e.executable}`:`HTTP — ${e.url.trim()}`,n=e.transportKind===`stdio`?`Not applicable`:e.authMode===`none`?`No authentication`:e.authMode===`bearer`?`Bearer token`:`OAuth`,r=e=>e.length===0?`None`:e.map(e=>e.value).join(`, `),i=(e,t)=>e.length===0?`None`:e.map(e=>`${e.name}${t}${e.value}`).join(`, `);return U(`div`,{"data-testid":`server-creation-review`,children:[U(`h3`,{children:`Identity`}),U(`dl`,{class:`review-list`,children:[U(`div`,{children:[U(`dt`,{children:`Namespace`}),U(`dd`,{children:e.namespace})]}),U(`div`,{children:[U(`dt`,{children:`Display name`}),U(`dd`,{children:e.displayName})]}),U(`div`,{children:[U(`dt`,{children:`Initial state`}),U(`dd`,{children:e.enabled?`Enabled`:`Disabled`})]})]}),U(`h3`,{children:`Connection`}),U(`dl`,{class:`review-list`,"data-testid":`server-connection-review`,children:[U(`div`,{children:[U(`dt`,{children:`Connection`}),U(`dd`,{children:t})]}),e.transportKind===`stdio`?U(S,{children:[U(`div`,{children:[U(`dt`,{children:`Working directory`}),U(`dd`,{children:e.workingDirectory})]}),U(`div`,{children:[U(`dt`,{children:`Arguments`}),U(`dd`,{children:r(e.arguments)})]}),U(`div`,{children:[U(`dt`,{children:`Environment`}),U(`dd`,{children:i(e.environment,`=`)})]}),U(`div`,{children:[U(`dt`,{children:`Secret bindings`}),U(`dd`,{children:i(e.secretEnvironment,` → `)})]})]}):U(S,{children:[U(`div`,{children:[U(`dt`,{children:`Protocol`}),U(`dd`,{children:Qi[e.protocolMode]})]}),U(`div`,{children:[U(`dt`,{children:`Custom HTTP headers (plaintext)`}),U(`dd`,{children:i(e.headers,`: `)})]})]})]}),e.transportKind!==`stdio`&&U(S,{children:[U(`h3`,{children:`Authentication`}),U(`dl`,{class:`review-list`,"data-testid":`server-authentication-review`,children:[U(`div`,{children:[U(`dt`,{children:`Authentication`}),U(`dd`,{children:n})]}),e.authMode===`oauth`&&U(S,{children:[U(`div`,{children:[U(`dt`,{children:`OAuth registration`}),U(`dd`,{children:e.registrationMode===`dynamic`?`Register Gateway automatically`:`Existing client ${e.clientID.trim()} (${$i[e.tokenEndpointAuthMethod]})`})]}),U(`div`,{children:[U(`dt`,{children:`OAuth issuer`}),U(`dd`,{children:e.issuer.trim()===``?`Discover from same-origin metadata`:e.issuer.trim()})]}),U(`div`,{children:[U(`dt`,{children:`OAuth network origins`}),U(`dd`,{children:r(e.trustedOrigins.map(e=>({...e,value:e.value.trim()})))})]}),U(`div`,{children:[U(`dt`,{children:`Callback URI`}),U(`dd`,{children:e.callbackURI===``?`Gateway main callback`:e.callbackURI})]}),U(`div`,{children:[U(`dt`,{children:`Authorization metadata URL`}),U(`dd`,{children:e.authServerMetadataURL===``?`Standard discovery`:e.authServerMetadataURL})]}),U(`div`,{children:[U(`dt`,{children:`Initial scopes`}),U(`dd`,{children:e.explicitScopes?e.scopes.length===0?`No initial scopes (explicit)`:[...new Set(e.scopes.map(e=>e.value))].sort().join(` `):`Server-advertised defaults`})]}),U(`div`,{children:[U(`dt`,{children:`Offline access`}),U(`dd`,{children:e.requestOfflineAccess?`Request when advertised`:`Do not request`})]})]})]})]}),U(`p`,{children:`The namespace is permanent. If enabled, Gateway will try to connect after the server is created.`})]})}function ya({mutations:e,server:t,etag:n,onRefresh:r,notify:i,decodeServerValue:a}){let o=t===void 0,s=V(o?oa():fa(t)),[c,l]=z(s.current),[u,d]=z(),[f,p]=z(),[m,h]=z(),[g,_]=z(),[v,y]=z({}),[b,x]=z({}),[C,w]=z(),[T,E]=z(),[D]=z(()=>e.create()),[O,k]=z(()=>D.snapshot()),A=V(null),j=e=>ca({display_name:e.displayName,enabled:e.enabled,transport:la(da(e))}),M=(()=>{try{return j(c)!==j(s.current)}catch{return ca(c)!==ca(s.current)}})(),N=Cr(M);B(()=>D.subscribe(k),[D]),B(()=>()=>D.close(),[D]),B(()=>{if(t===void 0)return;let e=fa(t);s.current=e,l(e)},[t?.id]);let ee=async e=>{let t=await e;t.kind===`acknowledged`?(E(void 0),w(void 0),i(o?`Server created.`:t.value.operationID===null?`Server settings saved.`:`Server settings saved; applying changes.`),D.abandon(),s.current=c,l({...c}),o?N(`#/mcp/servers/${t.value.server.id}`,!0):(r(),N(t.value.operationID===null?`#/mcp/servers/${t.value.server.id}`:`#/mcp/servers/${t.value.server.id}/operations/${t.value.operationID}`,!0))):t.kind===`rejected`&&t.requiresRefresh&&!o&&E(n)},P=e=>{e===`url`?p(void 0):e===`issuer`?h(void 0):e===`clientID`?_(void 0):e===`origin`?y({}):x({})},te=()=>{d(void 0),p(void 0),h(void 0),_(void 0),y({}),x({}),w(void 0);try{if(!Ji.test(c.namespace)||c.namespace===`mcp_gateway`)throw Error(`Namespace must be a permitted lowercase routing identity.`);if(c.displayName.length===0||new TextEncoder().encode(c.displayName).byteLength>256)throw Error(`Display name must contain 1–256 UTF-8 bytes.`);let e=da(c);if(o)return{behavioral:!0,spec:{route:`/api/v2/mcp/servers`,method:`POST`,body:JSON.stringify({namespace:c.namespace,display_name:c.displayName,enabled:c.enabled,transport:e}),precondition:null,requiresPrecondition:!1,idempotency:`server_create`,successStatuses:[200,201],decode:e=>ma(e,a)}};if(n===void 0)throw Error(`Refresh the current server revision before editing.`);let r=c.enabled!==(t.desiredState===`enabled`)||la(e)!==la(t.transport),i=r?{display_name:c.displayName,enabled:c.enabled,transport:e}:{display_name:c.displayName};return{behavioral:r,spec:{route:`/api/v2/mcp/servers/${t.id}`,method:`PATCH`,body:JSON.stringify(i),precondition:n,requiresPrecondition:!0,idempotency:`none`,successStatuses:[200],decode:e=>ma(e,a)}}}catch(e){let t=e instanceof Error?e.message:`Invalid server configuration.`;e instanceof qi?e.field===`url`?p(t):e.field===`issuer`?h(t):e.field===`clientID`?_(t):e.itemID===void 0?x({[e.field]:t}):y({[e.itemID]:t}):d(t);return}},F=()=>{let e=te();e!==void 0&&(D.begin(e.spec),e.behavioral?D.confirm():ee(D.submit()))},ne=!o&&T!==void 0&&T===n,I=O.state===`submitting`||O.availability===`storage_latched`||ne,re=U(S,{children:[U(`form`,{onSubmit:e=>{e.preventDefault(),F()},"data-testid":`server-editor`,children:[U(_a,{draft:c,setDraft:l,disabled:I,namespaceLocked:!o,urlError:f,issuerError:m,clientIDError:g,originErrors:v,compatibilityErrors:b,configurationError:O.problem?.context,clearFieldError:P}),u!==void 0&&U(K,{state:`error`,title:`Check server configuration`,children:U(`p`,{children:u})}),O.problem!==void 0&&U(K,{state:`error`,title:O.problem.title,children:[O.problem.context!==void 0&&U(`p`,{children:ta(O.problem.context)}),O.requiresRefresh&&!o&&U(`p`,{children:`A current server reload was requested. Your safe nonsecret draft is preserved; review it after the reload succeeds.`})]}),ne&&U(`p`,{class:`session-message`,role:`status`,children:`Waiting for a refreshed server revision before another submission.`}),O.state===`uncertain`&&U(K,{state:`warning`,title:`Mutation outcome unknown`,children:U(`p`,{children:O.canReplay?`The same create may be replayed explicitly with its retained in-memory idempotency key.`:`Inspect the authoritative server record before making another change.`})}),C!==void 0&&U(`p`,{class:`session-message`,role:`status`,children:C}),O.availability===`storage_latched`&&U(K,{state:`unavailable`,title:`Mutations closed by storage latch`}),U(`button`,{ref:A,class:`${o?`create-action`:`primary-action`} form-submit-action`,type:`submit`,disabled:I||!o&&!M||O.state===`uncertain`,"data-testid":`server-editor-submit`,children:o?`Review and create`:`Save settings`}),O.canReplay&&U(`button`,{type:`button`,"data-testid":`server-create-replay`,onClick:()=>void ee(D.replay()),children:`Replay this same create`})]}),U(jn,{id:`server-change-confirm`,open:O.state===`confirming`,title:o?`Review server`:`Apply behavioral server change?`,consequence:o?U(va,{draft:c}):`Changing desired state or transport interrupts current server routing and schedules reconciliation.`,confirmLabel:o?`Create server`:`Apply behavioral change`,destructive:!o,returnFocus:A,onCancel:()=>D.abandon(),onConfirm:()=>void ee(D.submit())})]});return o?U(`section`,{class:`panel domain-panel`,"aria-labelledby":`server-editor-title`,children:[U(`div`,{class:`panel-heading`,children:U(`div`,{children:U(`h2`,{id:`server-editor-title`,children:`Create MCP Server`})})}),re]}):U(`section`,{class:`panel domain-panel`,"aria-labelledby":`server-editor-title`,children:[U(`div`,{class:`panel-heading`,children:U(`h2`,{id:`server-editor-title`,children:`Edit server`})}),re]})}function ba(e,t){if(t!==void 0&&!bi(t))return t.kind===`refresh_catalog`&&t.targetDesiredRevision===e.desiredRevision?[`refresh_catalog`]:[];let n=[];return e.desiredState===`enabled`&&(e.runtimeState===`inactive`||e.runtimeState===`active`)&&n.push(`reload`),(e.desiredState===`enabled`&&[`retry_wait`,`degraded`,`authentication_required`].includes(e.runtimeState)||e.credentialState===`cleanup_pending`||(e.desiredState===`disabled`||e.desiredState===`deleted`)&&e.runtimeReason===`stop_unconfirmed`)&&n.push(`retry`),e.desiredState===`enabled`&&e.runtimeState===`active`&&(e.activeState===`current`||e.activeState===`stale`)&&n.push(`refresh_catalog`),e.desiredState!==`deleted`&&(e.staticRevision!==`0`||e.oauthClientRevision!==`0`||e.oauthTokensRevision!==`0`)&&n.push(`disconnect_credentials`),n}function xa(e){switch(e){case`activate`:return`Connect server`;case`reload`:return`Reload server`;case`retry`:return`Retry server operation`;case`refresh_catalog`:return`Refresh tools`;case`credential_replace`:return`Replace credential`;case`disable`:return`Disable server`;case`delete`:return`Delete server`;case`disconnect_credentials`:return`Disconnect credentials`}}function Sa(e){let t=e.replaceAll(`_`,` `);return t.charAt(0).toLocaleUpperCase()+t.slice(1)}function Ca(e){return bi(e)?e.state===`succeeded`?`current`:e.state===`failed`?`error`:e.state===`interrupted`?`warning`:`neutral`:`loading`}function wa(e){return e===`reload`||e===`disconnect_credentials`}function Ta(e){return e===`reload`?`Reload withdraws current routing while the server restarts. Calls already handed downstream may have unknown outcomes.`:`Disconnect invalidates local credential authority and withdraws affected routing. Remote revocation is best effort and is not guaranteed.`}function Ea({serverID:e,items:t,controls:n}){return U(Dn,{caption:`Server activity`,layout:`activity`,rowHeaderKey:`action`,additionalSorts:[{key:`started`,label:`Started (created if queued)`,sortValue:e=>e.startedAt??e.createdAt}],remote:n,itemNames:{singular:`operation`,plural:`operations`},emptyTitle:`No retained operations`,items:t,rowKey:e=>e.id,rowTestID:`operation-row`,filters:[{key:`action`,label:`Operation`,type:`select`,value:e=>e.kind,options:[{value:`activate`,label:`Connect server`},{value:`reload`,label:`Reload server`},{value:`retry`,label:`Retry server operation`},{value:`refresh_catalog`,label:`Refresh tools`},{value:`credential_replace`,label:`Replace credential`},{value:`disable`,label:`Disable server`},{value:`delete`,label:`Delete server`},{value:`disconnect_credentials`,label:`Disconnect credentials`}]},{key:`status`,label:`Status`,type:`select`,value:e=>e.state,options:[{value:`scheduled`,label:`Scheduled`},{value:`running`,label:`Running`},{value:`succeeded`,label:`Succeeded`},{value:`failed`,label:`Failed`},{value:`interrupted`,label:`Interrupted`},{value:`cancelled`,label:`Cancelled`},{value:`superseded`,label:`Superseded`}]}],initialSort:{key:`created`,direction:`descending`},columns:[{key:`created`,label:`Created`,role:`time`,sortValue:e=>e.createdAt,render:e=>U(Y,{value:e.createdAt})},{key:`action`,label:`Operation`,role:`identity`,sortValue:e=>xa(e.kind),render:t=>U(q,{primary:U(`a`,{href:`#/mcp/servers/${e}/operations/${t.id}`,children:xa(t.kind)}),secondary:t.id})},{key:`status`,label:`Status`,role:`status`,sortValue:e=>e.state,render:e=>U(G,{state:Ca(e),children:Sa(e.state)})},{key:`outcome`,label:`Reason`,role:`text`,sortValue:e=>e.reason??``,render:e=>e.reason===null?`—`:Sa(e.reason)}]})}function Da({mutations:e,server:t,etag:n,readVersion:r,activeOperation:i,activeCurrent:a,activeRefreshing:o,multipleActive:s}){let[c]=z(()=>e.create()),[l,u]=z(()=>c.snapshot()),[d,f]=z(),[p,m]=z(),[h,g]=z(),_=V(null);B(()=>c.subscribe(u),[c]),B(()=>()=>c.close(),[c]);let v=e=>({route:`/api/v2/mcp/servers/${t.id}/operations`,method:`POST`,body:JSON.stringify({kind:e}),precondition:n,requiresPrecondition:!0,idempotency:`operation_start`,successStatuses:[200,202],decode:yi}),y=async e=>{let n=await e;n.kind===`acknowledged`?(m(void 0),g(`Operation ${n.value.id} was accepted.`),c.abandon(),window.location.hash=`#/mcp/servers/${t.id}/operations/${n.value.id}`):n.kind===`rejected`&&n.requiresRefresh&&m(r)},b=(e,t)=>{_.current=t,f(e),g(void 0),c.begin(v(e)),wa(e)?c.confirm():y(c.submit())},x=p!==void 0&&r<=p,S=!a||l.state===`submitting`||l.availability===`storage_latched`||x,C=s?[]:ba(t,i);return U(`section`,{class:`panel domain-panel`,"aria-labelledby":`operation-start-title`,"aria-busy":o?`true`:void 0,children:[U(`div`,{class:`panel-heading`,children:U(`div`,{children:U(`h2`,{id:`operation-start-title`,children:`Available actions`})})}),i!==void 0&&U(K,{state:`warning`,title:a||o?`Active server work`:`Last observed active work`,children:U(`p`,{children:[U(`a`,{"data-testid":`active-operation-link`,href:`#/mcp/servers/${t.id}/operations/${i.id}`,children:[xa(i.kind),` — `,Sa(i.state)]}),s?` and additional active work`:``,`. This work may block new actions.`]})}),!a&&!o&&U(K,{state:`loading`,title:`Active-work status is not current`,children:`Actions require a successful authoritative refresh.`}),C.length===0?U(K,{state:`empty`,title:`No actions are currently available`}):U(`div`,{class:`action-list`,children:C.map(e=>U(`button`,{class:e===`disconnect_credentials`?`danger-action`:`safe-action`,type:`button`,"data-testid":`start-operation-${e}`,disabled:S,onClick:t=>b(e,t.currentTarget),children:xa(e)},e))}),l.problem!==void 0&&U(K,{state:`error`,title:l.problem.title,children:l.requiresRefresh&&U(`p`,{children:`A fresh server and operation snapshot was requested. Review the selected operation before starting a new intent.`})}),p!==void 0&&!x&&(a||o)&&U(`p`,{class:`session-message`,role:`status`,children:i===void 0?`Refreshed state: no active operation remains. Review available actions before starting a new intent.`:`Refreshed state: active work is identified above.`}),x&&U(`p`,{class:`session-message`,role:`status`,children:`Waiting for a newer authoritative operation snapshot.`}),l.state===`uncertain`&&U(K,{state:`warning`,title:`Operation start outcome unknown`,children:U(`p`,{children:`Inspect operation history before using Replay this same operation start.`})}),l.canReplay&&U(`button`,{type:`button`,"data-testid":`operation-start-replay`,onClick:()=>void y(c.replay()),children:`Replay this same operation start`}),h!==void 0&&U(`p`,{class:`session-message`,role:`status`,children:h}),d!==void 0&&U(jn,{id:`operation-start-confirm`,open:l.state===`confirming`,title:`${xa(d)}?`,consequence:Ta(d),confirmLabel:xa(d),destructive:d===`disconnect_credentials`,returnFocus:_,onCancel:()=>c.abandon(),onConfirm:()=>void y(c.submit())})]})}function Oa({mutations:e,server:t,etag:n,readVersion:r,operations:i,operation:a,activeCurrent:o=!1,activeRefreshing:s=!1,multipleActive:c=!1,history:l}){return a===void 0?U(S,{children:[U(Da,{mutations:e,server:t,etag:n,readVersion:r,activeOperation:i.find(e=>!bi(e)),activeCurrent:o,activeRefreshing:s,multipleActive:c}),l!==void 0&&U(`section`,{class:`panel domain-panel`,"aria-labelledby":`operation-list-title`,"data-testid":`operation-list`,children:[U(`div`,{class:`panel-heading`,children:U(`div`,{children:U(`h2`,{id:`operation-list-title`,children:`Operation history`})})}),l]})]}):U(`div`,{"data-testid":`operation-detail`,children:[U(`nav`,{class:`detail-navigation`,"aria-label":`Operation navigation`,children:U(`a`,{href:`#/mcp/servers/${t.id}?tab=operations`,children:`Back to server operations`})}),U(`header`,{class:`detail-context`,"data-testid":`detail-context`,children:[U(`div`,{class:`detail-context-heading`,children:[U(`h1`,{id:`operation-detail-title`,tabindex:-1,children:xa(a.kind)}),U(G,{state:Ca(a),children:Sa(a.state)})]}),U(`p`,{class:`technical-value`,children:a.id})]}),U(`section`,{class:`detail-section`,"aria-labelledby":`operation-facts-title`,children:[U(`h3`,{id:`operation-facts-title`,children:`Operation details`}),U(`dl`,{class:`detail-list`,children:[U(`div`,{children:[U(`dt`,{children:`Created`}),U(`dd`,{children:U(Y,{value:a.createdAt})})]}),U(`div`,{children:[U(`dt`,{children:`Started`}),U(`dd`,{children:U(Y,{value:a.startedAt,fallback:`Not started`})})]}),U(`div`,{children:[U(`dt`,{children:`Finished`}),U(`dd`,{children:U(Y,{value:a.finishedAt,fallback:bi(a)?`Not recorded`:`In progress`})})]}),a.reason!==null&&U(`div`,{children:[U(`dt`,{children:`Reason`}),U(`dd`,{children:Sa(a.reason)})]})]})]})]})}var ka=/^[0-7][0-9A-HJKMNP-TV-Z]{25}$/;function Aa(e){let t=H(e);if(t?.destination===`catalog`)return`catalog`;if(t?.destination===`servers`){if(t.segments.length===1)return`servers`;if(t.segments.length===2&&t.query.tab===`tools`)return`descriptors`}}function ja(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`invalid response`);let n=e;if(Object.keys(n).sort().join(`,`)!==[...t].sort().join(`,`))throw Error(`invalid response`);return n}function Ma(e,t,n){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`invalid response`);let r=e,i=Object.keys(r);if(t.some(e=>!Object.hasOwn(r,e))||i.some(e=>!t.includes(e)&&!n.includes(e)))throw Error(`invalid response`);return r}function X(e){if(typeof e!=`string`)throw Error(`invalid response`);return e}function Na(e){if(e!==null&&typeof e!=`string`)throw Error(`invalid response`);return e}function Pa(e){if(typeof e!=`boolean`)throw Error(`invalid response`);return e}function Fa(e){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<0)throw Error(`invalid response`);return e}function Ia(e){let t=X(e);if(!ka.test(t))throw Error(`invalid response`);return t}function La(e,t){let n=X(e);if(!t.includes(n))throw Error(`invalid response`);return n}function Ra(e){if(!Array.isArray(e))throw Error(`invalid response`);return e}function za(e){let t=Na(e);if(t!==null&&(t.length===0||t.length>4096))throw Error(`invalid response`);return t}function Ba(e){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`invalid response`);return e}function Va(e){let t=ja(e,[`in_use`,`limit`,`saturated`]);return{inUse:Fa(t.in_use),limit:Fa(t.limit),saturated:Pa(t.saturated)}}function Ha(e){if(e===null)return null;let t=e;if(La(t.kind,[`stdio`,`streamable_http`])===`stdio`){let t=ja(e,[`kind`,`executable`,`arguments`,`working_directory`,`environment`,`secret_environment`]);X(t.executable),X(t.working_directory),Ra(t.arguments).forEach(X);for(let e of[t.environment,t.secret_environment]){let t=Ma(e,[],Object.keys(e));Object.values(t).forEach(X)}return e}let n=ja(e,[`kind`,`url`,`protocol_mode`,`authentication`,...Object.hasOwn(t,`headers`)?[`headers`]:[]]);if(n.headers!==void 0){let e=n.headers;if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`invalid HTTP headers`);let t=Ma(e,[],Object.keys(e));Object.values(t).forEach(X)}X(n.url),La(n.protocol_mode,[`modern`,`legacy`,`auto`]);let r=n.authentication,i=La(r.mode,[`none`,`bearer`,`oauth`]);if(i===`none`||i===`bearer`)return ja(n.authentication,[`mode`]),e;let a=ja(n.authentication,[`mode`,`registration`,`trusted_origins`,`request_offline_access`,...[`callback_uri`,`auth_server_metadata_url`,`scopes`].filter(e=>Object.hasOwn(r,e))]);a.callback_uri!==void 0&&X(a.callback_uri),a.auth_server_metadata_url!==void 0&&X(a.auth_server_metadata_url),a.scopes!==void 0&&Ra(a.scopes).forEach(X),Ra(a.trusted_origins).forEach(X),Pa(a.request_offline_access);let o=a.registration;if(La(o.mode,[`static`,`dynamic`])===`dynamic`)Na(ja(a.registration,[`mode`,`issuer`]).issuer);else{let e=ja(a.registration,[`mode`,`issuer`,`client_id`,`token_endpoint_auth_method`]);Na(e.issuer),X(e.client_id),La(e.token_endpoint_auth_method,[`none`,`client_secret_basic`,`client_secret_post`])}return e}var Ua=`configuration_invalid.resource_limit.connectivity.tls_failed.protocol_unsupported.protocol_invalid.authentication_rejected.credential_absent.keyring_absent.keyring_locked.keyring_interaction_required.keyring_unavailable.keyring_unsupported.oauth_rejected.oauth_expired.registration_expired.process_exited.output_limit.stop_unconfirmed.catalog_invalid.catalog_limit.catalog_stale.superseded.cancelled.interrupted.revocation_failed.revocation_unsupported.cleanup_pending`.split(`.`);function Wa(e){let t=ja(e,[`id`,`namespace`,`display_name`,`desired_state`,`desired_revision`,`transport`,`credential_revisions`,`credential_state`,`runtime`,`catalog`,`created_at`,`updated_at`,`deleted_at`]),n=ja(t.credential_revisions,[`static_credential`,`oauth_client`,`oauth_tokens`]),r=Ma(t.runtime,[`state`,`reason`,`runtime_id`,`reconciliation`,`dispatch`],[`diagnostic_correlation`]),i=Na(r.reason);i!==null&&La(i,Ua);let a=ja(t.catalog,[`durable_state`,`active_state`,`durable_revision`,`active_revision`,`durable_tool_count`,`active_tool_count`,`last_success_at`,`traversal`]);return{id:Ia(t.id),namespace:X(t.namespace),displayName:X(t.display_name),desiredState:La(t.desired_state,[`enabled`,`disabled`,`deleted`]),desiredRevision:X(t.desired_revision),transport:Ha(t.transport),staticRevision:X(n.static_credential),oauthClientRevision:X(n.oauth_client),oauthTokensRevision:X(n.oauth_tokens),credentialState:La(t.credential_state,[`not_required`,`ready`,`absent`,`locked`,`interaction_required`,`unavailable`,`unsupported`,`refreshing`,`reauthentication_required`,`disconnecting`,`cleanup_pending`]),runtimeState:La(r.state,[`inactive`,`activating`,`active`,`stopping`,`retry_wait`,`degraded`,`authentication_required`,`deleted`]),runtimeReason:i,runtimeID:Na(r.runtime_id),diagnosticCorrelation:br(r.diagnostic_correlation),reconciliation:Va(r.reconciliation),dispatch:Va(r.dispatch),durableState:La(a.durable_state,[`empty`,`current`,`stale`,`unavailable`,`retired`]),activeState:La(a.active_state,[`absent`,`refreshing`,`current`,`stale`,`unavailable`]),durableRevision:Na(a.durable_revision),activeRevision:Na(a.active_revision),durableToolCount:Fa(a.durable_tool_count),activeToolCount:Fa(a.active_tool_count),lastSuccessAt:Na(a.last_success_at),traversal:Va(a.traversal),createdAt:X(t.created_at),updatedAt:X(t.updated_at),deletedAt:Na(t.deleted_at)}}function Ga(e){let t=ja(e,[`items`,`next_cursor`]);return{items:Ra(t.items).map(Wa),nextCursor:za(t.next_cursor)}}function Ka(e,t=!1){let n=[`id`,`server_id`,`upstream_name`,`external_name`,`descriptor`,`fingerprint`,`catalog_revision`,`first_seen_at`,`last_seen_at`,`retired_at`];t&&n.push(`server_display_name`,`server_catalog_state`);let r=ja(e,n),i=Ma(r.descriptor,[`name`,`inputSchema`,`annotations`],[`title`,`description`,`outputSchema`]);X(i.name),i.title!==void 0&&X(i.title),i.description!==void 0&&X(i.description),Ba(i.inputSchema),i.outputSchema!==void 0&&Ba(i.outputSchema);let a=ja(i.annotations,[`title`,`readOnlyHint`,`destructiveHint`,`idempotentHint`,`openWorldHint`]);Na(a.title);for(let e of[`readOnlyHint`,`destructiveHint`,`idempotentHint`,`openWorldHint`])Pa(a[e]);let o={id:Ia(r.id),serverID:Ia(r.server_id),upstreamName:X(r.upstream_name),externalName:X(r.external_name),descriptor:r.descriptor,fingerprint:X(r.fingerprint),catalogRevision:X(r.catalog_revision),firstSeenAt:X(r.first_seen_at),lastSeenAt:X(r.last_seen_at),retiredAt:Na(r.retired_at)};return t?{...o,serverDisplayName:X(r.server_display_name),serverCatalogState:La(r.server_catalog_state,[`refreshing`,`current`,`stale`,`unavailable`])}:o}function qa(e){return Ka(e)}function Ja(e){let t=ja(e,[`items`,`next_cursor`]);return{items:Ra(t.items).map(e=>Ka(e)),nextCursor:za(t.next_cursor)}}function Ya(e){let t=ja(e,[`catalog`,`items`,`next_cursor`]),n=ja(t.catalog,[`active_state`,`active_generation`,`changed_at`,`issue_count`]);return{catalog:{activeState:La(n.active_state,[`empty`,`current`,`degraded`]),activeGeneration:X(n.active_generation),changedAt:Na(n.changed_at),issueCount:Fa(n.issue_count)},page:{items:Ra(t.items).map(e=>Ka(e,!0)),nextCursor:za(t.next_cursor)}}}async function Xa(e,t){let n=await fetch(t,{method:`GET`,headers:{"X-CSRF-Token":e.csrfToken},credentials:`same-origin`,redirect:`error`,signal:e.signal});if(await e.sessionLost(n))throw Error(`session lost`);return n}async function Za(e){if(e.status!==200||e.headers.get(`Content-Type`)!==`application/json`)throw Error(`read failed`);let t=await e.text();if(new TextEncoder().encode(t).byteLength>4194304)throw Error(`response too large`);return JSON.parse(t)}async function Qa(e){if(e.status!==409||e.headers.get(`Content-Type`)!==`application/problem+json`)return!1;let t=await e.text();if(new TextEncoder().encode(t).byteLength>65536)return!1;try{let e=ja(JSON.parse(t),[`status`,`code`,`title`]);return e.status===409&&X(e.code)===`stale_cursor`&&X(e.title).length>0}catch{return!1}}function $a(e=``){return{viewKey:e,servers:[],serverNext:null,server:void 0,serverETag:void 0,descriptors:[],descriptorNext:null,descriptor:void 0,catalog:void 0,catalogItems:[],catalogNext:null,operations:[],operationNext:null,activeMore:!1,operation:void 0,authFlows:[],authFlowNext:null,authFlow:void 0,readVersion:0,loadingMore:!1,restarted:!1}}function eo(e,t,n){let r=new URLSearchParams;if(r.set(`limit`,`50`),n!==null&&r.set(`cursor`,n),e===`servers`)return`/api/v2/mcp/servers?${r.toString()}`;if(e===`catalog`)return`/api/v2/mcp/catalog?${r.toString()}`;if(e===`operations`){let e=to(t);if(e===void 0)throw Error(`invalid server activity location`);return`/api/v2/mcp/servers/${e}/operations?projection=active`}if(e===`authFlows`){let e=/^#\/mcp\/servers\/([0-7][0-9A-HJKMNP-TV-Z]{25})\?tab=(?:operations|authentication|status)$/.exec(t);if(e===null)throw Error(`invalid server history location`);return`/api/v2/mcp/servers/${e[1]}/oauth-flows?${r.toString()}`}let i=/^#\/mcp\/servers\/([0-7][0-9A-HJKMNP-TV-Z]{25})\?tab=tools$/.exec(t);if(i===null)throw Error(`invalid descriptor location`);return`/api/v2/mcp/servers/${i[1]}/descriptors?${r.toString()}`}function to(e){return/^#\/mcp\/servers\/([0-7][0-9A-HJKMNP-TV-Z]{25})(?:[/?]|$)/.exec(e)?.[1]}function no(e){return Aa(e)===`catalog`?`catalog-reads`:Aa(e)===`descriptors`?`server-descriptor-reads`:/\?tab=operations(?:&|$)|\/operations\//.test(e)?`server-operation-reads`:/\/auth-flows\//.test(e)?`server-oauth-reads`:/\?tab=tools$|\/descriptors\//.test(e)?`server-descriptor-reads`:`server-overview-reads`}var ro=class{views;listeners=new Set;value=$a();continuation;continuationPending=!1;constructor(e,t){this.views=t;let n=(e,n,r,i=!1)=>t.registerPanel({id:e,matches:n,invalidations:r,...i?{pollMilliseconds:2e3,shouldPoll:()=>this.value.operation!==void 0&&!bi(this.value.operation)||this.value.authFlow!==void 0&&!Zr(this.value.authFlow)||this.value.authFlows.some(e=>!Zr(e))||this.value.operations.some(e=>!bi(e))}:{},read:t=>this.read(t,e===`server-operation-reads`?`operations`:e===`server-oauth-reads`?`authFlows`:e===`server-descriptor-reads`?`descriptors`:void 0),publish:e=>this.publish(e)});n(`server-overview-reads`,e=>Aa(e)===`servers`||/^#\/mcp\/servers\/[0-7][0-9A-HJKMNP-TV-Z]{25}(?:\?tab=(?:authentication|settings|status))?$/.test(e),[`servers`,`catalog`]),n(`server-operation-reads`,e=>/^#\/mcp\/servers\/[0-7][0-9A-HJKMNP-TV-Z]{25}\?tab=operations(?:&|$)/.test(e)||/^#\/mcp\/servers\/[0-7][0-9A-HJKMNP-TV-Z]{25}\/operations\/[0-7][0-9A-HJKMNP-TV-Z]{25}$/.test(e),[`servers`,`server_operations`,`catalog`],!0),n(`server-oauth-reads`,e=>/^#\/mcp\/servers\/[0-7][0-9A-HJKMNP-TV-Z]{25}\?tab=authentication$/.test(e)||/^#\/mcp\/servers\/[0-7][0-9A-HJKMNP-TV-Z]{25}\/auth-flows\/[0-7][0-9A-HJKMNP-TV-Z]{25}$/.test(e),[`servers`,`server_auth_flows`,`catalog`],!0),n(`server-descriptor-reads`,e=>Aa(e)===`descriptors`||/^#\/mcp\/servers\/[0-7][0-9A-HJKMNP-TV-Z]{25}\/descriptors\/[0-7][0-9A-HJKMNP-TV-Z]{25}$/.test(e),[`catalog`]),n(`catalog-reads`,e=>Aa(e)===`catalog`,[`catalog`]),e.registerProtectedState(()=>{this.continuation=void 0,this.continuationPending=!1,this.value=$a(),this.emit()})}snapshot(){return this.value}subscribe(e){return this.listeners.add(e),e(this.value),()=>this.listeners.delete(e)}async loadMore(e){let t=e===`servers`?this.value.serverNext:e===`descriptors`?this.value.descriptorNext:e===`operations`?this.value.operationNext:e===`authFlows`?this.value.authFlowNext:this.value.catalogNext;if(!(this.continuationPending||t===null)){this.continuationPending=!0,this.continuation={kind:e,cursor:t},this.value={...this.value,loadingMore:!0},this.emit();try{await this.views.refreshPanel(e===`authFlows`?`server-oauth-reads`:e===`operations`?`server-operation-reads`:no(this.value.viewKey))}finally{this.continuationPending=!1,this.value={...this.value,loadingMore:!1},this.emit()}}}async read(e,t){if(e.viewKey!==this.value.viewKey){this.continuation=void 0;let t=to(e.viewKey),n=t!==void 0&&this.value.server?.id===t?this.value.server:void 0;this.value={...$a(e.viewKey),server:n},this.emit()}let n=Aa(e.viewKey);if(n===`servers`||n===`catalog`)return{kind:`collection`,viewKey:e.viewKey};if(n===`descriptors`){let t=await Xa(e,`/api/v2/mcp/servers/${to(e.viewKey)}`),n=Wa(await Za(t)),r=t.headers.get(`ETag`);if(r!==`"server-${n.id}-${n.desiredRevision}"`)throw Error(`invalid server ETag`);return{kind:`server`,viewKey:e.viewKey,server:n,etag:r}}let r=/^#\/mcp\/servers\/([0-7][0-9A-HJKMNP-TV-Z]{25})\/auth-flows\/([0-7][0-9A-HJKMNP-TV-Z]{25})$/.exec(e.viewKey);if(r!==null){let[t,n]=await Promise.all([Xa(e,`/api/v2/mcp/servers/${r[1]}`),Xa(e,`/api/v2/mcp/servers/${r[1]}/oauth-flows/${r[2]}`)]),i=Wa(await Za(t)),a=t.headers.get(`ETag`);if(a!==`"server-${i.id}-${i.desiredRevision}"`)throw Error(`invalid server ETag`);let o=Jr(await Za(n));if(o.serverID!==r[1]||o.id!==r[2])throw Error(`auth flow route mismatch`);return{kind:`authFlow`,viewKey:e.viewKey,server:i,etag:a,flow:o}}let i=/^#\/mcp\/servers\/([0-7][0-9A-HJKMNP-TV-Z]{25})\/operations\/([0-7][0-9A-HJKMNP-TV-Z]{25})$/.exec(e.viewKey);if(i!==null){let[t,n]=await Promise.all([Xa(e,`/api/v2/mcp/servers/${i[1]}`),Xa(e,`/api/v2/mcp/servers/${i[1]}/operations/${i[2]}`)]),r=Wa(await Za(t)),a=t.headers.get(`ETag`);if(a!==`"server-${r.id}-${r.desiredRevision}"`)throw Error(`invalid server ETag`);let o=_i(await Za(n));if(o.serverID!==i[1]||o.id!==i[2])throw Error(`operation route mismatch`);return{kind:`operation`,viewKey:e.viewKey,server:r,etag:a,operation:o}}let a=/^#\/mcp\/servers\/([0-7][0-9A-HJKMNP-TV-Z]{25})\/descriptors\/([0-7][0-9A-HJKMNP-TV-Z]{25})$/.exec(e.viewKey);if(a!==null){let[t,n]=await Promise.all([Xa(e,`/api/v2/mcp/servers/${a[1]}`),Xa(e,`/api/v2/mcp/servers/${a[1]}/descriptors/${a[2]}`)]),r=Wa(await Za(t)),i=t.headers.get(`ETag`);if(i!==`"server-${r.id}-${r.desiredRevision}"`)throw Error(`invalid server ETag`);return{kind:`descriptor`,viewKey:e.viewKey,server:r,etag:i,descriptor:Ka(await Za(n))}}let o=/^#\/mcp\/servers\/([0-7][0-9A-HJKMNP-TV-Z]{25})(?:\?tab=(?:authentication|settings|status))?$/.exec(e.viewKey);if(o!==null&&t===void 0){let t=await Xa(e,`/api/v2/mcp/servers/${o[1]}`),n=Wa(await Za(t)),r=t.headers.get(`ETag`);if(r!==`"server-${n.id}-${n.desiredRevision}"`)throw Error(`invalid server ETag`);return{kind:`server`,viewKey:e.viewKey,server:n,etag:r}}let s=t??(e.viewKey===`#/mcp/servers`?`servers`:e.viewKey===`#/mcp/tools`?`catalog`:`descriptors`),c=this.continuation;this.continuation=void 0;let l=c?.kind===s?c.cursor:null,u=s===`operations`||s===`authFlows`||s===`descriptors`?Xa(e,`/api/v2/mcp/servers/${H(e.viewKey).segments[1]}`):void 0,[d,f]=await Promise.all([Xa(e,eo(s,e.viewKey,l)),u??Promise.resolve(void 0)]),p=!1;if(l!==null&&await Qa(d)&&(p=!0,s===`authFlows`&&!e.signal.aborted&&this.value.viewKey===e.viewKey&&(this.value={...this.value,authFlows:[],authFlowNext:null,restarted:!0},this.emit()),d=await Xa(e,eo(s,e.viewKey,null))),s===`servers`)return{kind:s,viewKey:e.viewKey,page:Ga(await Za(d)),append:l!==null&&!p,restarted:p};if(s===`descriptors`){if(f===void 0)throw Error(`missing server descriptor response`);let t=Wa(await Za(f)),n=f.headers.get(`ETag`);if(n!==`"server-${t.id}-${t.desiredRevision}"`)throw Error(`invalid server ETag`);return{kind:s,viewKey:e.viewKey,server:t,etag:n,page:Ja(await Za(d)),append:l!==null&&!p,restarted:p}}if(s===`operations`||s===`authFlows`){if(f===void 0)throw Error(`missing server history response`);let t=Wa(await Za(f)),n=f.headers.get(`ETag`);if(n!==`"server-${t.id}-${t.desiredRevision}"`)throw Error(`invalid server ETag`);if(s===`operations`){!e.signal.aborted&&this.value.viewKey===e.viewKey&&(this.value={...this.value,server:t,serverETag:n},this.emit());let r=gi(await Za(d));if(r.items.some(e=>e.serverID!==t.id))throw Error(`invalid active operation server`);return{kind:s,viewKey:e.viewKey,server:t,etag:n,page:r,append:!1,restarted:!1}}return{kind:s,viewKey:e.viewKey,server:t,etag:n,page:Yr(await Za(d)),append:l!==null&&!p,restarted:p}}let m=Ya(await Za(d));return{kind:s,viewKey:e.viewKey,catalog:m.catalog,page:m.page,append:l!==null&&!p,restarted:p}}publish(e){e.kind!==`collection`&&(this.value=e.kind===`server`?{...this.value,server:e.server,serverETag:e.etag,readVersion:this.value.readVersion+1,restarted:!1}:e.kind===`operation`?{...this.value,server:e.server,serverETag:e.etag,operation:e.operation,readVersion:this.value.readVersion+1,restarted:!1}:e.kind===`operations`?{...this.value,server:e.server,serverETag:e.etag,operations:e.append?[...this.value.operations,...e.page.items]:e.page.items,operationNext:e.page.nextCursor,activeMore:e.page.hasMore,readVersion:this.value.readVersion+1,restarted:e.restarted}:e.kind===`authFlow`?{...this.value,server:e.server,serverETag:e.etag,authFlow:e.flow,readVersion:this.value.readVersion+1,restarted:!1}:e.kind===`authFlows`?{...this.value,server:e.server,serverETag:e.etag,authFlows:e.append?[...this.value.authFlows,...e.page.items]:e.page.items,authFlowNext:e.page.nextCursor,readVersion:this.value.readVersion+1,restarted:e.restarted}:e.kind===`descriptor`?{...this.value,server:e.server,serverETag:e.etag,descriptor:e.descriptor,readVersion:this.value.readVersion+1,restarted:!1}:e.kind===`servers`?{...this.value,servers:e.append?[...this.value.servers,...e.page.items]:e.page.items,serverNext:e.page.nextCursor,restarted:e.restarted}:e.kind===`descriptors`?{...this.value,server:e.server,serverETag:e.etag,descriptors:e.append?[...this.value.descriptors,...e.page.items]:e.page.items,descriptorNext:e.page.nextCursor,readVersion:this.value.readVersion+1,restarted:e.restarted}:{...this.value,catalog:e.catalog,catalogItems:e.append?[...this.value.catalogItems,...e.page.items]:e.page.items,catalogNext:e.page.nextCursor,restarted:e.restarted},this.emit())}emit(){for(let e of this.listeners)e(this.value)}};function io({panel:e,children:t}){return e?.status===`error`&&e.hasValue!==!0?U(K,{state:`error`,title:`Read unavailable`}):e===void 0||e.status===`loading`&&!e.hasValue?U(K,{state:`loading`,title:`Loading authoritative data`}):U(S,{children:[e.status!==`current`&&e.hasValue&&U(K,{state:`stale`,title:`Last known data — refresh unavailable`}),t]})}function ao({serverID:e,current:t}){return U(`nav`,{class:`subnav`,"aria-label":`Server sections`,children:[[`status`,`Status`,`#/mcp/servers/${e}`],[`tools`,`Tools`,`#/mcp/servers/${e}?tab=tools`],[`operations`,`Operations`,`#/mcp/servers/${e}?tab=operations`],[`authentication`,`Authentication`,`#/mcp/servers/${e}?tab=authentication`],[`settings`,`Settings`,`#/mcp/servers/${e}?tab=settings`]].map(([e,n,r])=>U(`a`,{href:r,"aria-current":t===e?`page`:void 0,children:n},e))})}function oo(e){if(typeof e.transport!=`object`||e.transport===null)return!1;let t=e.transport;if(t.kind!==`streamable_http`)return!1;let n=t.authentication;return typeof n==`object`&&!!n&&!Array.isArray(n)&&n.mode===`oauth`}function so(e){let t=`#/mcp/servers/${e.id}`;if(e.desiredState===`deleted`)return{label:`Deleted`,state:`neutral`};if(e.desiredState===`disabled`)return{label:`Disabled`,state:`neutral`,action:`Configure`,href:`${t}?tab=settings`};if(e.runtimeState===`authentication_required`||e.credentialState===`absent`||e.credentialState===`reauthentication_required`)return{label:`Authorization required`,state:`warning`,action:oo(e)?`Authorize server`:`Manage credentials`,href:`${t}?tab=authentication`};if(e.credentialState===`locked`||e.credentialState===`interaction_required`||e.credentialState===`unavailable`||e.credentialState===`unsupported`)return{label:`Authentication unavailable`,state:`warning`,action:`Manage credentials`,href:`${t}?tab=authentication`};if(e.credentialState===`cleanup_pending`)return{label:`Cleanup needs attention`,state:`warning`,action:`View operations`,href:`${t}?tab=operations`};if(e.runtimeState===`activating`||e.runtimeState===`retry_wait`||e.credentialState===`refreshing`||e.credentialState===`disconnecting`)return{label:`Connecting`,state:`loading`,action:`View operations`,href:`${t}?tab=operations`};let n=e.reconciliation.saturated||e.dispatch.saturated||e.traversal.saturated;return e.runtimeState===`active`&&e.activeState===`current`&&(e.credentialState===`ready`||e.credentialState===`not_required`)&&!n?{label:`Ready`,state:`current`}:e.runtimeState===`active`?e.activeState===`current`?{label:`Capacity saturated`,state:`warning`,action:`View status`,href:t}:{label:`Needs attention`,state:`warning`,action:`View tools`,href:`${t}?tab=tools`}:{label:`Needs attention`,state:`warning`,action:`View operations`,href:`${t}?tab=operations`}}function co(e,t){return e.label===`Authorization required`?e.action===`Authorize server`?`Authorize this server to restore authenticated access.`:`Provide valid credentials to restore authenticated access.`:e.label===`Authentication unavailable`?`Credential storage requires operator attention before authentication can succeed.`:e.label===`Disabled`?`This server will not connect until it is enabled.`:e.label===`Connecting`?`The gateway is establishing or cleaning up the server connection.`:e.label===`Deleted`?`This server is retained as historical evidence.`:e.label===`Capacity saturated`?`One or more server capacity limits are saturated.`:t.runtimeReason===null?`The catalog is ${W(t.activeState)}.`:`Runtime reported ${W(t.runtimeReason)}.`}function lo({server:e,serverID:t,current:n,fresh:r,compact:i=!1}){if(e===void 0)return null;if(i)return U(S,{children:[U(`p`,{class:`secondary-text`,children:[`Server: `,U(`a`,{href:`#/mcp/servers/${t}`,children:e.displayName})]}),U(ao,{serverID:t,current:n})]});let a=so(e);return U(S,{children:[U(`nav`,{class:`detail-navigation`,"aria-label":`Server navigation`,children:U(`a`,{href:`#/mcp/servers`,children:`Back to MCP Servers`})}),U(`header`,{class:`server-context`,"data-testid":`server-context`,children:[U(`div`,{class:`server-context-heading`,children:[U(`h1`,{tabindex:-1,children:e.displayName}),U(G,{state:r?a.state:`stale`,children:r?a.label:`Last known · ${a.label}`})]}),U(`p`,{class:`technical-value`,children:U(`code`,{"data-testid":`server-id`,children:e.id})})]}),U(ao,{serverID:t,current:n})]})}function uo({items:e,controls:t}){return U(Dn,{caption:`Servers`,rowHeaderKey:`name`,additionalSorts:[{key:`id`,label:`Server ID`,sortValue:e=>e.id}],remote:t,itemNames:{singular:`server`,plural:`servers`},items:e,rowKey:e=>e.id,initialSort:{key:`name`,direction:`ascending`},rowTestID:`server-row`,filters:[{key:`name`,label:`Name or ID`,type:`text`,value:e=>e.displayName,literalValues:e=>[e.id]},{key:`namespace`,label:`Namespace`,type:`text`,value:e=>e.namespace},{key:`status`,label:`Status`,type:`select`,value:e=>so(e).label,options:[{value:`Ready`,label:`Ready`},{value:`Connecting`,label:`Connecting`},{value:`Authorization required`,label:`Authorization required`},{value:`Authentication unavailable`,label:`Authentication unavailable`},{value:`Capacity saturated`,label:`Capacity saturated`},{value:`Disabled`,label:`Disabled`},{value:`Deleted`,label:`Deleted`},{value:`Needs attention`,label:`Needs attention`}]}],emptyTitle:`No servers`,columns:[{key:`name`,label:`Server`,role:`identity`,sortValue:e=>e.displayName,render:e=>U(q,{primary:U(`a`,{href:`#/mcp/servers/${e.id}`,children:e.displayName}),secondary:e.id})},{key:`namespace`,label:`Namespace`,role:`text`,sortValue:e=>e.namespace,render:e=>e.namespace},{key:`status`,label:`Status`,role:`status`,sortValue:e=>so(e).label,render:e=>{let n=so(e);return U(G,{state:t.stale?`stale`:n.state,children:t.stale?`Last known · ${n.label}`:n.label})}},{key:`tools`,label:`Active tools`,role:`count`,sortValue:e=>e.activeToolCount,render:e=>e.activeToolCount}]})}function fo(e){return typeof e.type==`string`?e.type:Array.isArray(e.type)?e.type.filter(e=>typeof e==`string`).join(` or `):`value`}function po(e){let t=[];typeof e.format==`string`&&t.push(`Format: ${e.format}`),Array.isArray(e.enum)&&t.push(`Allowed: ${e.enum.map(String).join(`, `)}`),Object.hasOwn(e,`const`)&&t.push(`Constant: ${String(e.const)}`),Object.hasOwn(e,`default`)&&t.push(`Default: ${String(e.default)}`);for(let[n,r]of[[`minimum`,`Minimum`],[`maximum`,`Maximum`],[`minLength`,`Minimum length`],[`maxLength`,`Maximum length`],[`pattern`,`Pattern`]])(typeof e[n]==`string`||typeof e[n]==`number`)&&t.push(`${r}: ${String(e[n])}`);return t}function mo({value:e,depth:t=0}){if(typeof e!=`object`||!e||Array.isArray(e))return U(`span`,{class:`schema-constraint`,children:e===!0?`Any value`:e===!1?`No value`:`Invalid schema`});let n=e,r=typeof n.properties==`object`&&n.properties!==null&&!Array.isArray(n.properties)?n.properties:{},i=new Set(Array.isArray(n.required)?n.required.filter(e=>typeof e==`string`):[]),a=po(n),o=[`oneOf`,`anyOf`,`allOf`].map(e=>[e,n[e]]).filter(e=>Array.isArray(e[1]));return U(S,{children:[typeof n.description==`string`&&U(`p`,{children:n.description}),a.map(e=>U(`span`,{class:`schema-constraint`,children:e},e)),Object.keys(r).length>0&&U(`dl`,{class:`schema-fields`,children:Object.entries(r).map(([e,n])=>{let r=n;return U(`div`,{children:[U(`dt`,{children:[U(`code`,{children:e}),U(`span`,{children:fo(r)}),i.has(e)&&U(`strong`,{children:`Required`})]}),U(`dd`,{children:U(mo,{value:r,depth:t+1})})]},e)})}),t<5&&typeof n.items==`object`&&n.items!==null&&U(`div`,{class:`schema-nested`,children:[U(`strong`,{children:`Items`}),U(mo,{value:n.items,depth:t+1})]}),t<5&&o.map(([e,n])=>U(`div`,{class:`schema-nested`,children:[U(`strong`,{children:e}),n.map((e,n)=>U(`div`,{children:[U(`span`,{class:`schema-constraint`,children:[`Option `,n+1]}),U(mo,{value:e,depth:t+1})]},n))]},e)),typeof n.$ref==`string`&&U(`span`,{class:`schema-constraint`,children:[`Reference: `,n.$ref]})]})}function ho({label:e,value:t}){let n=t,r=`${e.toLowerCase().replace(` `,`-`)}-title`;return U(`section`,{class:`tool-schema`,"aria-labelledby":r,children:[U(`div`,{class:`tool-schema-heading`,children:[U(`h3`,{id:r,children:e}),U(`span`,{children:fo(n)})]}),U(mo,{value:n})]})}function go({items:e,controls:t}){return U(Dn,{caption:`Available tools`,rowHeaderKey:`tool`,remote:t,itemNames:{singular:`tool`,plural:`tools`},emptyTitle:`No catalog tools`,items:e,rowKey:e=>e.id,initialSort:{key:`tool`,direction:`ascending`},rowTestID:`catalog-row`,filters:[{key:`tool`,label:`Tool`,type:`text`,value:e=>e.externalName,literalValues:e=>[e.id]},{key:`server`,label:`Server`,type:`text`,value:e=>e.serverDisplayName,literalValues:e=>[e.serverID]},{key:`status`,label:`Status`,type:`select`,value:e=>e.serverCatalogState===`current`?`available`:`issue`,options:[{value:`available`,label:`Available`},{value:`issue`,label:`Catalog issue`}]}],columns:[{key:`tool`,label:`Tool`,role:`identity`,sortValue:e=>e.externalName,render:e=>U(q,{primary:U(`a`,{href:`#/mcp/servers/${e.serverID}/descriptors/${e.id}`,"data-tool-name":e.upstreamName,children:e.externalName}),secondary:e.id})},{key:`server`,label:`Server`,role:`relation`,sortValue:e=>e.serverDisplayName,render:e=>U(q,{primary:U(`a`,{href:`#/mcp/servers/${e.serverID}?tab=tools`,children:e.serverDisplayName||e.serverID}),secondary:e.serverID})},{key:`status`,label:`Status`,role:`status`,render:e=>{let n=e.serverCatalogState===`current`;return U(G,{state:t.stale?`stale`:n?`current`:`warning`,children:[t.stale?`Last known · `:``,n?`Available`:`Catalog issue`]})}}]})}function _o({items:e,controls:t}){return U(Dn,{caption:`Server tools`,rowHeaderKey:`tool`,remote:t,itemNames:{singular:`tool`,plural:`tools`},emptyTitle:`No server tools`,items:e,rowKey:e=>e.id,rowTestID:`descriptor-row`,filters:[{key:`tool`,label:`Tool`,type:`text`,value:e=>e.externalName,literalValues:e=>[e.id]},{key:`status`,label:`Status`,type:`select`,value:e=>e.retiredAt===null?`available`:`retired`,options:[{value:`available`,label:`Available`},{value:`retired`,label:`Retired`}]}],initialSort:{key:`last-seen`,direction:`descending`},columns:[{key:`tool`,label:`Tool`,role:`identity`,sortValue:e=>e.externalName,render:e=>U(q,{primary:U(`a`,{href:`#/mcp/servers/${e.serverID}/descriptors/${e.id}`,"data-tool-name":e.upstreamName,children:e.externalName})})},{key:`status`,label:`Status`,role:`status`,sortValue:e=>e.retiredAt===null?`available`:`retired`,render:e=>U(G,{state:t.stale?`stale`:e.retiredAt===null?`current`:`neutral`,children:[t.stale?`Last known · `:``,e.retiredAt===null?`Available`:`Retired`]})},{key:`last-seen`,label:`Last seen`,role:`time`,sortValue:e=>e.lastSeenAt,render:e=>U(Y,{value:e.lastSeenAt})}]})}function vo({session:e,resolved:t,view:n,kind:r,decodePage:i,render:a}){let o=Cr(!1),s=r===`operations`?{key:`created`,direction:`descending`}:r===`descriptors`?{key:`last-seen`,direction:`descending`}:{key:r===`servers`?`name`:`tool`,direction:`ascending`},{items:c,controls:l}=Nr(e,t,n,(n,a,o)=>{let c=new URLSearchParams({limit:`50`,sort:n.sort??s.key,direction:n.direction??(n.sort===void 0?s.direction:`ascending`)});for(let[e,t]of Object.entries(n))e.startsWith(`filter_`)&&c.set(e.slice(7),r===`servers`&&e===`filter_status`?t.toLowerCase().replaceAll(` `,`_`):t);a!==null&&c.set(`cursor`,a);let l=r===`descriptors`||r===`operations`?`/api/v2/mcp/servers/${t.location.segments[1]}/${r}`:`/api/v2/mcp/${r}`;return r===`operations`?Mr(e,`${l}?${c}`,e=>{let n=_i(e);if(n.serverID!==t.location.segments[1])throw Error(`Invalid operation server.`);return n},o):Mr(e,`${l}?${c}`,void 0,o,e=>{let t=i(e);if(t.items.length>50||t.nextCursor!==null&&t.nextCursor.length>512)throw Error(`Invalid collection response.`);return{...t,totalCount:void 0,offset:0}})},o,s);return U(S,{children:a(c,l)})}function yo({session:e,resolved:t,controller:n,view:r,destination:i,mutations:a,sinks:o,onRefresh:s,notify:c}){let[l,u]=z(n.snapshot());B(()=>n.subscribe(u),[n]);let d=r.panels[no(r.viewKey)],f=r.panels[`server-overview-reads`],p=r.panels[`server-operation-reads`],m=r.panels[`server-oauth-reads`],h=/^#\/mcp\/servers\/([0-7][0-9A-HJKMNP-TV-Z]{25})\?tab=authentication$/.exec(r.viewKey),g=/^#\/mcp\/servers\/([0-7][0-9A-HJKMNP-TV-Z]{25})\/auth-flows\/[0-7][0-9A-HJKMNP-TV-Z]{25}$/.exec(r.viewKey),_=/^#\/mcp\/servers\/([0-7][0-9A-HJKMNP-TV-Z]{25})\?tab=operations(?:&|$)/.exec(r.viewKey),v=/^#\/mcp\/servers\/([0-7][0-9A-HJKMNP-TV-Z]{25})\/operations\/[0-7][0-9A-HJKMNP-TV-Z]{25}$/.exec(r.viewKey),y=/^#\/mcp\/servers\/([0-7][0-9A-HJKMNP-TV-Z]{25})\?tab=settings$/.exec(r.viewKey),b=/^#\/mcp\/servers\/([0-7][0-9A-HJKMNP-TV-Z]{25})\?tab=status$/.exec(r.viewKey),x=/^#\/mcp\/servers\/([0-7][0-9A-HJKMNP-TV-Z]{25})\/descriptors\/[0-7][0-9A-HJKMNP-TV-Z]{25}$/.exec(r.viewKey),C=/^#\/mcp\/servers\/([0-7][0-9A-HJKMNP-TV-Z]{25})$/.exec(r.viewKey),w=Aa(r.viewKey)===`descriptors`?to(r.viewKey):void 0,T=/^#\/mcp\/servers\/([0-7][0-9A-HJKMNP-TV-Z]{25})\?tab=([^&]+)$/.exec(r.viewKey),E=b?.[1]??C?.[1];if(r.viewKey===`#/mcp/servers/new`)return U(`div`,{class:`domain-view`,"data-testid":`server-create-view`,children:[U(`a`,{href:`#/mcp/servers`,children:`Back to server inventory`}),U(ya,{mutations:a,onRefresh:s,notify:c,decodeServerValue:Wa})]});if(i===`catalog`)return U(`div`,{class:`domain-view`,"data-testid":`catalog-view`,children:U(`section`,{class:`panel domain-panel`,"aria-labelledby":`page-title`,children:U(vo,{session:e,resolved:t,view:r,kind:`catalog`,decodePage:e=>Ya(e).page,render:(e,t)=>U(go,{items:e,controls:t})})})});if(Aa(r.viewKey)===`servers`)return U(`div`,{class:`domain-view`,"data-testid":`servers-view`,children:[U(`div`,{class:`collection-toolbar`,children:U(`a`,{class:`button-link create-action`,href:`#/mcp/servers/new`,"data-testid":`server-create-link`,children:`Create server`})}),U(`section`,{class:`panel domain-panel`,"aria-labelledby":`page-title`,children:U(vo,{session:e,resolved:t,view:r,kind:`servers`,decodePage:Ga,render:(e,t)=>U(uo,{items:e,controls:t})})})]});if(h!==null)return U(`div`,{class:`domain-view`,"data-testid":`server-authentication-view`,children:[U(lo,{server:l.server,serverID:h[1],fresh:f?.status===`current`,current:`authentication`}),U(io,{panel:f,children:l.server!==void 0&&l.serverETag!==void 0&&U(Ui,{mutations:a,sinks:o,server:l.server,etag:l.serverETag,readVersion:l.readVersion,onRefresh:s})}),U(io,{panel:m,children:l.server!==void 0&&l.serverETag!==void 0&&U(ai,{mutations:a,sinks:o,server:l.server,etag:l.serverETag,readVersion:l.readVersion,flows:l.authFlows,flow:void 0,nextCursor:l.authFlowNext,loadingMore:l.loadingMore,restarted:l.restarted,onLoadMore:()=>void n.loadMore(`authFlows`),onRefresh:s,mode:`action`,stale:m?.status===`error`})}),l.server!==void 0&&l.serverETag!==void 0&&U(ai,{mutations:a,sinks:o,server:l.server,etag:l.serverETag,readVersion:l.readVersion,flows:l.authFlows,flow:void 0,nextCursor:l.authFlowNext,loadingMore:l.loadingMore,restarted:l.restarted,onLoadMore:()=>void n.loadMore(`authFlows`),onRefresh:s,mode:`history`,stale:m?.status===`error`,loading:m===void 0||m.status===`loading`&&!m.hasValue})]});if(g!==null){let e=g[1];return U(`div`,{class:`domain-view`,"data-testid":`server-auth-flows-view`,children:[U(lo,{server:l.server,serverID:e,fresh:d?.status===`current`,current:`authentication`,compact:!0}),U(io,{panel:d,children:l.server!==void 0&&l.serverETag!==void 0&&U(ai,{mutations:a,sinks:o,server:l.server,etag:l.serverETag,readVersion:l.readVersion,flows:l.authFlows,flow:l.authFlow,stale:d?.status===`error`,nextCursor:l.authFlowNext,loadingMore:l.loadingMore,restarted:l.restarted,onLoadMore:()=>void n.loadMore(`authFlows`),onRefresh:s})})]})}return _===null?v===null?x===null?w===void 0?y===null?E===void 0?T===null?U(K,{state:`unavailable`,title:`Server workflow not yet available`}):U(`div`,{class:`domain-view`,children:[U(lo,{server:l.server,serverID:T[1],fresh:d?.status===`current`,current:T[2]}),U(K,{state:`unavailable`,title:`Workflow not yet available`})]}):U(`div`,{class:`domain-view`,"data-testid":`server-status-view`,children:[U(lo,{server:l.server,serverID:E,fresh:d?.status===`current`,current:`status`}),U(`section`,{class:`detail-section operator-status-view`,"aria-labelledby":`server-status-title`,children:[U(`div`,{class:`panel-heading`,children:U(`h2`,{id:`server-status-title`,children:`Server status`})}),U(io,{panel:d,children:l.server!==void 0&&(()=>{let e=l.server,t=so(e),n=[[`Reconciliation`,e.reconciliation],[`Dispatch`,e.dispatch],[`Catalog traversal`,e.traversal]].filter(([,e])=>e.saturated),r=t.action!==void 0;return U(`div`,{class:`operator-status-stack`,children:[(r||n.length>0||e.desiredState===`deleted`)&&U(`section`,{class:`operator-status-section`,"aria-labelledby":`server-issues-title`,"data-testid":`server-status-issues`,children:[U(`div`,{class:`operator-status-section-heading`,children:U(`h3`,{id:`server-issues-title`,children:`Needs attention`})}),e.desiredState===`deleted`&&U(K,{state:`unavailable`,title:`Deleted`,children:[U(`p`,{children:co(t,e)}),e.deletedAt!==null&&U(`p`,{children:[`Deleted `,U(Y,{value:e.deletedAt})]})]}),r&&U(K,{state:t.state===`current`?`warning`:t.state,title:t.label,children:[U(`p`,{children:co(t,e)}),t.href!==void 0&&t.href!==`#/mcp/servers/${e.id}`&&U(`a`,{href:t.href,children:t.action})]}),n.map(([e,t])=>U(K,{state:`warning`,title:`${e} capacity is saturated`,children:U(`p`,{children:[t.inUse,` of `,t.limit,` slots are in use. New work cannot be admitted until capacity is released.`]})},e))]}),U(`section`,{class:`operator-status-section`,"aria-labelledby":`server-operational-title`,"data-testid":`server-status-operational`,children:[U(`h3`,{id:`server-operational-title`,children:`Operational state`}),U(`dl`,{class:`operator-status-grid`,children:[U(`div`,{children:[U(`dt`,{children:`Runtime`}),U(`dd`,{children:[U(vn,{value:e.runtimeState,current:d?.status===`current`}),U(`span`,{children:[`Desired `,W(e.desiredState)]}),e.runtimeReason!==null&&U(`span`,{children:[`Reason: `,W(e.runtimeReason)]})]})]}),U(`div`,{children:[U(`dt`,{children:`Authentication`}),U(`dd`,{children:[U(vn,{value:e.credentialState,current:d?.status===`current`}),t.href!==`#/mcp/servers/${e.id}?tab=authentication`&&U(`a`,{href:`#/mcp/servers/${e.id}?tab=authentication`,children:`Manage authentication`})]})]}),U(`div`,{children:[U(`dt`,{children:`Catalog`}),U(`dd`,{children:[U(vn,{value:e.activeState,current:d?.status===`current`}),U(`span`,{children:[e.activeToolCount,` active ·`,` `,e.durableToolCount,` durable tools`]}),U(`span`,{children:[`Last successful refresh`,` `,U(Y,{value:e.lastSuccessAt})]}),U(`a`,{href:`#/mcp/servers/${e.id}?tab=tools`,children:`View tools`})]})]})]})]}),U(`section`,{class:`operator-status-details`,"aria-labelledby":`server-technical-details-title`,"data-testid":`server-status-details`,children:[U(`h3`,{id:`server-technical-details-title`,children:`Technical details`}),U(`dl`,{class:`technical-details-grid`,children:[U(`div`,{children:[U(`dt`,{children:`Namespace`}),U(`dd`,{children:e.namespace})]}),U(`div`,{class:`technical-details-wide`,children:[U(`dt`,{children:`Diagnostic correlation`}),U(`dd`,{"data-testid":`server-diagnostic-correlation`,children:e.diagnosticCorrelation?U(S,{children:[U(`span`,{children:[`Process:`,` `,e.diagnosticCorrelation.processID]}),U(`br`,{}),U(`span`,{children:[`Upstream reference:`,` `,e.diagnosticCorrelation.upstreamRef]}),U(`p`,{class:`muted`,children:`Match both values to stderr from this Gateway process. References do not survive restart.`})]}):`Unavailable — no current diagnostic reference`})]}),U(`div`,{class:`technical-details-wide`,children:[U(`dt`,{children:`Runtime ID`}),U(`dd`,{children:e.runtimeID===null?`—`:U(ji,{value:e.runtimeID,label:`runtime ID`})})]}),U(`div`,{children:[U(`dt`,{children:`Desired revision`}),U(`dd`,{children:e.desiredRevision})]}),U(`div`,{children:[U(`dt`,{children:`Static credential revision`}),U(`dd`,{children:e.staticRevision})]}),U(`div`,{children:[U(`dt`,{children:`OAuth client revision`}),U(`dd`,{children:e.oauthClientRevision})]}),U(`div`,{children:[U(`dt`,{children:`OAuth token revision`}),U(`dd`,{children:e.oauthTokensRevision})]}),U(`div`,{children:[U(`dt`,{children:`Durable catalog revision`}),U(`dd`,{children:e.durableRevision??`—`})]}),U(`div`,{children:[U(`dt`,{children:`Active catalog revision`}),U(`dd`,{children:e.activeRevision??`—`})]}),U(`div`,{children:[U(`dt`,{children:`Created`}),U(`dd`,{children:U(Y,{value:e.createdAt})})]}),U(`div`,{children:[U(`dt`,{children:`Updated`}),U(`dd`,{children:U(Y,{value:e.updatedAt})})]})]})]})]})})()})]})]}):U(`div`,{class:`domain-view`,"data-testid":`server-settings-view`,children:[U(lo,{server:l.server,serverID:y[1],fresh:d?.status===`current`,current:`settings`}),U(io,{panel:d,children:[l.server!==void 0&&l.serverETag!==void 0&&l.server.desiredState!==`deleted`&&U(S,{children:[U(ya,{mutations:a,server:l.server,etag:l.serverETag,onRefresh:s,notify:c,decodeServerValue:Wa}),U(Gi,{mutations:a,server:l.server,etag:l.serverETag,readVersion:l.readVersion,decodeServerValue:Wa})]}),l.server?.desiredState===`deleted`&&U(K,{state:`unavailable`,title:`Server deleted`})]})]}):U(`div`,{class:`domain-view`,"data-testid":`descriptor-list`,children:[U(lo,{server:l.server,serverID:w,fresh:f?.status===`current`,current:`tools`}),U(`section`,{class:`panel domain-panel`,"aria-labelledby":`descriptor-list-title`,children:[U(`div`,{class:`panel-heading`,children:[U(`h2`,{id:`descriptor-list-title`,children:`Tools`}),U(`a`,{href:`#/mcp/tools`,children:`All available tools`})]}),U(vo,{session:e,resolved:t,view:r,kind:`descriptors`,decodePage:Ja,render:(e,t)=>U(_o,{items:e,controls:t})})]})]}):U(`div`,{class:`domain-view`,"data-testid":`descriptor-detail`,children:U(io,{panel:d,children:l.descriptor!==void 0&&(()=>{let e=l.descriptor,t=e.descriptor,n=t.annotations;return U(S,{children:[U(`nav`,{class:`detail-navigation`,"aria-label":`Tool navigation`,children:[U(`a`,{href:`#/mcp/servers/${e.serverID}?tab=tools`,children:`Back to server tools`}),U(`a`,{href:`#/mcp/tools`,children:`All MCP tools`})]}),U(`header`,{class:`detail-context`,"data-testid":`detail-context`,children:U(`div`,{class:`detail-context-heading tool-heading`,children:[U(`div`,{children:[U(`h1`,{id:`descriptor-detail-title`,tabindex:-1,children:e.externalName}),U(`p`,{class:`technical-value`,children:e.id})]}),U(G,{state:d?.status===`current`?e.retiredAt===null?`current`:`neutral`:`stale`,children:e.retiredAt===null?`Available`:`Retired`})]})}),e.retiredAt!==null&&U(`p`,{children:`Historical evidence; not callable`}),U(`section`,{class:`detail-section`,"aria-labelledby":`tool-evidence-title`,children:[U(`h2`,{id:`tool-evidence-title`,children:`Tool details`}),U(`dl`,{class:`tool-metadata`,children:[U(`div`,{children:[U(`dt`,{children:`Server`}),U(`dd`,{children:U(q,{primary:U(`a`,{href:`#/mcp/servers/${e.serverID}`,children:l.server?.displayName??`Server ${e.serverID}`}),secondary:e.serverID})})]}),typeof t.description==`string`&&U(`div`,{children:[U(`dt`,{children:`Description`}),U(`dd`,{children:t.description})]})]}),U(`h3`,{children:`Catalog evidence`}),U(`dl`,{class:`tool-metadata`,children:[U(`div`,{children:[U(`dt`,{children:`Catalog revision`}),U(`dd`,{children:e.catalogRevision})]}),U(`div`,{children:[U(`dt`,{children:`First seen`}),U(`dd`,{children:U(Y,{value:e.firstSeenAt})})]}),U(`div`,{children:[U(`dt`,{children:`Last seen`}),U(`dd`,{children:U(Y,{value:e.lastSeenAt})})]}),U(`div`,{children:[U(`dt`,{children:`Retired`}),U(`dd`,{children:U(Y,{value:e.retiredAt,fallback:`No`})})]})]}),U(`h3`,{id:`server-hints-title`,class:`detail-group`,children:`Server hints`}),U(`div`,{class:`tool-annotations`,"aria-labelledby":`server-hints-title`,children:[U(`span`,{children:n.readOnlyHint?`Read only`:`May write`}),U(`span`,{children:n.destructiveHint?`Destructive`:`Non-destructive`}),U(`span`,{children:n.idempotentHint?`Idempotent`:`Not idempotent`}),U(`span`,{children:n.openWorldHint?`External access`:`Closed world`})]})]}),U(`section`,{class:`detail-section`,children:[U(`h3`,{children:`Schema summary`}),U(`div`,{class:`tool-schema-grid`,children:[U(ho,{label:`Input schema`,value:t.inputSchema}),t.outputSchema!==void 0&&U(ho,{label:`Output schema`,value:t.outputSchema})]})]})]})})()})}):U(`div`,{class:`domain-view`,"data-testid":`server-operations-view`,children:U(io,{panel:d,children:l.server!==void 0&&l.serverETag!==void 0&&U(Oa,{mutations:a,server:l.server,etag:l.serverETag,readVersion:l.readVersion,operations:l.operations,operation:l.operation})})}):U(`div`,{class:`domain-view`,"data-testid":`server-activity-view`,children:[U(lo,{server:l.server,serverID:_[1],fresh:f?.status===`current`,current:`operations`}),p?.status===`error`&&U(K,{state:`error`,title:`Active operations unavailable`,children:`Operation starts are disabled. History remains independently readable.`}),l.server!==void 0&&l.serverETag!==void 0&&U(Oa,{mutations:a,server:l.server,etag:l.serverETag,readVersion:l.readVersion,operations:l.operations,operation:void 0,activeCurrent:p?.status===`current`&&p.refreshing!==!0,activeRefreshing:p?.refreshing===!0,multipleActive:l.activeMore||l.operations.length>1}),U(`section`,{class:`panel domain-panel`,"aria-labelledby":`operation-list-title`,"data-testid":`operation-list`,children:[U(`div`,{class:`panel-heading`,children:U(`h2`,{id:`operation-list-title`,children:`Operation history`})}),U(vo,{session:e,resolved:t,view:r,kind:`operations`,decodePage:vi,render:(e,t)=>U(Ea,{serverID:_[1],items:e,controls:t})})]})]})}var bo=/^[0-7][0-9A-HJKMNP-TV-Z]{25}$/;function xo(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:void 0}function So(e){return e.replaceAll(`~`,`~0`).replaceAll(`/`,`~1`)}var Co=new Set([`$id`,`$schema`,`default`,`deprecated`,`description`,`examples`,`readOnly`,`title`,`writeOnly`]);function wo(e,t){let n=new Set([...Co,...t]);return Object.keys(e).some(e=>!n.has(e))}function To(e){let t=xo(xo(e)?.inputSchema),n=[],r=t===void 0,i=(e,t,a)=>{if(a>16||n.length>=256){r=!0;return}let o=xo(e.properties);if((e.type!==`object`||o===void 0||wo(e,[`type`,`properties`,`required`,`additionalProperties`,`minProperties`,`maxProperties`])||e.additionalProperties!==!1)&&(r=!0),e.type===`object`&&o!==void 0)for(let[e,s]of Object.entries(o)){if(n.length>=256){r=!0;break}let o=xo(s);if(o===void 0){r=!0;continue}let c=[...t,e];if(o.type===`object`){i(o,c,a+1);continue}wo(o,[`type`,`enum`])&&(r=!0);let l=o.type===`integer`||o.type===`number`?`number`:o.type===`null`||o.type===`boolean`||o.type===`string`?o.type:void 0;if(l===void 0){r=!0;continue}o.enum!==void 0&&!Array.isArray(o.enum)&&(r=!0);let u=Array.isArray(o.enum)?o.enum:[],d=u.filter(e=>l===`null`?e===null:l===`number`?typeof e==`number`:typeof e===l).map(e=>e===null?`null`:String(e));d.length!==u.length&&(r=!0);let f=`/${c.map(So).join(`/`)}`;if(new TextEncoder().encode(f).length>256){r=!0;continue}n.push({pointer:f,type:l,description:typeof o.description==`string`?o.description:null,values:d,regexAvailable:l===`string`})}};return t!==void 0&&i(t,[],0),{fields:n,unsupported:r}}function Eo(e){if(typeof e!=`string`)throw Error(`invalid response`);return e}function Do(e){let t=xo(e);if(t===void 0||Object.keys(t).sort().join(`,`)!==`items,next_cursor`||!Array.isArray(t.items)||t.items.length>100||t.next_cursor!==null&&(typeof t.next_cursor!=`string`||t.next_cursor===``||new TextEncoder().encode(t.next_cursor).length>512))throw Error(`invalid response`);return{items:t.items.map(e=>{let t=xo(e);if(t===void 0||Object.keys(t).sort().join(`,`)!==`catalog_revision,external_name,id,server_id,upstream_name`)throw Error(`invalid response`);let n=Eo(t.id),r=Eo(t.server_id);if(!bo.test(n)||!bo.test(r))throw Error(`invalid response`);return{id:n,serverID:r,upstreamName:Eo(t.upstream_name),externalName:Eo(t.external_name),catalogRevision:Eo(t.catalog_revision)}}),nextCursor:t.next_cursor}}function Oo(e,t){return t===void 0?e:AbortSignal.any([e,t])}async function ko(e,t,n){return!bo.test(t)||t===`00000000000000000000000000`?[]:e.runProtected(async e=>{let r=[],i=null,a=!1,o=new Set;for(;;){let s=new URLSearchParams({limit:`50`,status:`available`,projection:`summary`});i!==null&&s.set(`cursor`,i);let c=await fetch(`/api/v2/mcp/servers/${t}/descriptors?${s}`,{credentials:`same-origin`,redirect:`error`,signal:Oo(e.signal,n),headers:{Accept:`application/json`,"X-CSRF-Token":e.csrfToken}});if(await e.sessionLost(c))return;if(c.status===409&&i!==null&&!a){r.length=0,i=null,o.clear(),a=!0;continue}if(!c.ok||c.headers.get(`Content-Type`)!==`application/json`)throw Error(`Catalog tools are unavailable.`);let l=Do(await c.json());if(l.items.some(e=>e.serverID!==t))throw Error(`Catalog pagination returned the wrong server.`);if(r.length+l.items.length>256)throw Error(`Catalog tools exceed the supported limit.`);if(r.push(...l.items),l.nextCursor===null)return r;if(o.has(l.nextCursor)||r.length>=256)throw Error(`Catalog pagination is invalid.`);o.add(l.nextCursor),i=l.nextCursor}})}async function Ao(e,t,n){if(!(!bo.test(t.serverID)||!bo.test(t.id)))return e.runProtected(async e=>{let r=await fetch(`/api/v2/mcp/servers/${t.serverID}/descriptors/${t.id}`,{credentials:`same-origin`,redirect:`error`,signal:Oo(e.signal,n),headers:{Accept:`application/json`,"X-CSRF-Token":e.csrfToken}});if(await e.sessionLost(r))return;if(!r.ok||r.headers.get(`Content-Type`)!==`application/json`)throw Error(`The selected tool schema is unavailable.`);let i=qa(await r.json());if(i.id!==t.id||i.serverID!==t.serverID||i.upstreamName!==t.upstreamName||i.externalName!==t.externalName||i.retiredAt!==null)throw Error(`The selected tool schema is no longer current.`);return i})}function jo({status:e,testID:t}){return U(`span`,{class:`matcher-status`,"data-recognition":e.toLowerCase(),"data-testid":t,role:`status`,"aria-live":`polite`,"aria-atomic":`true`,children:e})}var Mo=/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/;function No(e){return e.startsWith(`/`)&&new TextEncoder().encode(e).length<=256&&!/~(?:[^01]|$)/.test(e)}function Po(e){if(e===null)return 0;let t=e;return Object.keys(t.equals??{}).length+Object.keys(t.regex??{}).length}function Fo(e){if(e.length===0)return`null`;let t=t=>e.filter(e=>e.operator===t).map(e=>{let n;if(t===`regex`)n=JSON.stringify(e.value);else if(e.type===`null`)n=`null`;else if(e.type===`boolean`){if(e.value!==`true`&&e.value!==`false`)throw Error(`Boolean values must be true or false.`);n=e.value}else if(e.type===`number`){if(!Mo.test(e.value))throw Error(`Number values must use valid JSON number syntax.`);n=e.value}else n=JSON.stringify(e.value);return`${JSON.stringify(e.pointer)}:${n}`}),n=t(`equals`),r=t(`regex`);return`{"version":2${n.length===0?``:`,"equals":{${n.join(`,`)}}`},"regex":{${r.join(`,`)}}}`}function Io({idPrefix:e,testPrefix:t,addTestID:n,atoms:r,suggestions:i,schemaState:a=`unavailable`,disabled:o=!1,onChange:s}){let c=(e,t)=>s(r.map((n,r)=>r===e?{...n,...t}:n)),l=(i?.fields??[]).map(e=>({value:e.pointer,detail:`${e.type}${e.values.length===0?``:` · ${e.values.join(`, `)}`}${e.description===null?``:` · ${e.description}`}`}));return U(`div`,{class:`matcher-editor`,children:[r.map((n,u)=>{let d=i?.fields.find(e=>e.pointer===n.pointer),f=n.operator===`regex`,p=n.pointer===``?`Choose field`:i===void 0?a===`loading`?`Loading…`:`Unavailable`:d===void 0?`Unknown`:`Known`,m=d!==void 0&&d.type!==(f?`string`:n.type)?f?`Schema suggests ${d.type}; only string runtime values can match. No coercion.`:`Schema suggests ${d.type}; your ${n.type} type is retained.`:``,h=`${e}-guidance-${u}`,g=m?h:void 0,_=`${e}-values-${u}`,v=!f&&d?.type===n.type?d.values:[];return U(`div`,{class:`matcher-row`,"data-testid":`${t}-atom`,children:[U(J,{id:`${e}-pointer-${u}`,label:`JSON pointer`,children:e=>U(kn,{attributes:{...e,...g?{"aria-describedby":g}:{}},label:`JSON pointer ${u+1}`,testID:`${t}-pointer`,value:n.pointer,options:l,placeholder:`/repository`,disabled:o,onChange:e=>{let t=i?.fields.find(t=>t.pointer===e);c(u,{pointer:e,...!n.explicitType&&n.value===``&&t!==void 0?{type:t.type}:{}})}})}),U(jo,{status:p,testID:`${t}-status`}),U(J,{id:`${e}-operator-${u}`,label:`Operator`,children:e=>U(`select`,{...e,"aria-describedby":g,"data-testid":`${t}-operator`,value:n.operator,disabled:o,onChange:e=>c(u,{operator:e.currentTarget.value,value:``}),children:[U(`option`,{value:`equals`,children:`EQUALS`}),U(`option`,{value:`regex`,children:`MATCHES`})]})}),U(J,{id:`${e}-type-${u}`,label:`Scalar type`,children:e=>U(`select`,{...e,"aria-describedby":g,"data-testid":`${t}-type`,value:f?`string`:n.type,disabled:o||f,onChange:e=>c(u,{type:e.currentTarget.value,explicitType:!0}),children:[U(`option`,{value:`null`,children:`Null`}),U(`option`,{value:`boolean`,children:`Boolean`}),U(`option`,{value:`string`,children:`String`}),U(`option`,{value:`number`,children:`Number`})]})}),U(J,{id:`${e}-value-${u}`,label:f?`Full-string RE2 pattern`:`Scalar value`,children:e=>!f&&n.type===`boolean`?U(`select`,{...e,"aria-describedby":g,"data-testid":`${t}-value`,value:n.value,disabled:o,onChange:e=>c(u,{value:e.currentTarget.value}),children:[U(`option`,{value:``,children:`Choose a boolean`}),U(`option`,{value:`true`,children:`true`}),U(`option`,{value:`false`,children:`false`})]}):!f&&n.type===`null`?U(`input`,{...e,"aria-describedby":g,value:`null`,disabled:!0}):U(`input`,{...e,"aria-describedby":g,"data-testid":`${t}-value`,value:n.value,placeholder:f?`example-[a-z0-9-]+`:n.type===`number`?`42`:`example-project`,list:_,autocomplete:`off`,disabled:o,onInput:e=>c(u,{value:e.currentTarget.value})})}),U(`datalist`,{id:_,children:v.map(e=>U(`option`,{value:e},e))}),U(`button`,{class:`matcher-remove`,type:`button`,"aria-label":`Remove condition ${u+1}`,disabled:o,onClick:()=>s(r.filter((e,t)=>t!==u)),children:`Remove condition`}),m&&U(`p`,{id:h,class:`field-hint matcher-guidance`,role:`status`,children:m})]},u)}),U(`button`,{"data-testid":n??`${t}-add`,type:`button`,disabled:o||r.length>=16,onClick:()=>s([...r,{operator:`equals`,pointer:``,type:`string`,value:``}]),children:`Add condition`})]})}function Lo(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`Matcher validation returned an invalid response.`);let n=e;if(Object.keys(n).sort().join(`,`)!==[...t].sort().join(`,`))throw Error(`Matcher validation returned an invalid response.`);return n}function Ro(e){if(typeof e!=`string`)throw Error(`Matcher validation returned an invalid response.`);return e}function zo(e){return{Accept:`application/json`,"Content-Type":`application/json`,"X-CSRF-Token":e.csrfToken}}async function Bo(e,t){return e.runProtected(async e=>{let n=await fetch(`/api/v2/mcp/grant-constraints/validate`,{method:`POST`,credentials:`same-origin`,redirect:`error`,signal:e.signal,headers:zo(e),body:`{"constraint":${t}}`});if(await e.sessionLost(n))return;if(n.status!==200||n.headers.get(`Content-Type`)!==`application/json`)throw Error(`Matcher validation is unavailable.`);let r=Lo(await n.json(),[`valid`,`diagnostics`]);if(typeof r.valid!=`boolean`||!Array.isArray(r.diagnostics))throw Error(`Matcher validation returned an invalid response.`);if(r.valid){if(r.diagnostics.length!==0)throw Error(`Matcher validation returned an invalid response.`);return null}if(r.diagnostics.length!==1)throw Error(`Matcher validation returned an invalid response.`);let i=Lo(r.diagnostics[0],[`field`,`message`]);return`${Ro(i.field)}: ${Ro(i.message)}`})}var Vo=/^[0-7][0-9A-HJKMNP-TV-Z]{25}$/,Ho=/^(0|[1-9][0-9]*)$/;function Uo(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`invalid response`);let n=e;if(Object.keys(n).sort().join(`,`)!==[...t].sort().join(`,`))throw Error(`invalid response`);return n}function Wo(e){if(typeof e!=`string`)throw Error(`invalid response`);return e}function Go(e){let t=Wo(e);if(!Vo.test(t))throw Error(`invalid response`);return t}function Ko(e){let t=Wo(e);if(!Ho.test(t))throw Error(`invalid response`);return t}function qo(e,t){let n=Wo(e);if(!t.includes(n))throw Error(`invalid response`);return n}function Jo(e){let t=Uo(e,[`id`,`display_name`,`state`,`visibility`,`http_default`,`revision`,`credential_revision`,`credential`,`created_at`,`updated_at`]),n=t.credential===null?null:Uo(t.credential,[`id`,`fingerprint`,`revision`,`created_at`]);return{id:Go(t.id),displayName:Wo(t.display_name),state:qo(t.state,[`active`,`disabled`]),visibility:qo(t.visibility,[`requestable`,`allowed-only`,`all`]),httpDefault:qo(t.http_default,[`allow`,`block`]),revision:Ko(t.revision),credentialRevision:Ko(t.credential_revision),credential:n===null?null:{id:Go(n.id),fingerprint:Wo(n.fingerprint),revision:Ko(n.revision),createdAt:Wo(n.created_at)},hasCredential:n!==null,createdAt:Wo(t.created_at),updatedAt:Wo(t.updated_at)}}function Yo(e){let t=Uo(e,[`principal`,`default_grant`]),n=Uo(t.default_grant,[`id`,`description`,`revision`,`principal_id`,`effect`,`server_id`,`upstream_name`,`constraint`,`expires_at`,`state`,`created_at`]),r=Jo(t.principal);if(n.description!==`Default Gateway access`||Ko(n.revision)!==`1`||Go(n.principal_id)!==r.id||n.effect!==`allow`||n.server_id!==`00000000000000000000000000`||n.upstream_name!==null||n.constraint!==null||n.expires_at!==null||n.state!==`active`)throw Error(`invalid response`);return{principal:r,defaultGrantID:Go(n.id)}}function Xo(e){return{Accept:`application/json`,"X-CSRF-Token":e.csrfToken}}async function Zo(e,t){return e.runProtected(async e=>{let n=await fetch(t,{credentials:`same-origin`,redirect:`error`,signal:e.signal,headers:Xo(e)});if(!await e.sessionLost(n)){if(n.headers.get(`Content-Type`)!==`application/json`&&n.headers.get(`Content-Type`)!==`application/problem+json`)throw Error(`Agent data is unavailable.`);return{value:await n.json(),response:n}}})}async function Qo(e){let t=[],n=null,r=!1;for(;;){let i=await Zo(e,`/api/v2/principals?limit=50${n===null?``:`&cursor=${encodeURIComponent(n)}`}`);if(i===void 0)return[];if(i.response.status===409&&n!==null&&!r){t.length=0,n=null,r=!0;continue}if(!i.response.ok)throw Error(`Agent data is unavailable.`);let a=Uo(i.value,[`items`,`next_cursor`,`total_count`,`offset`]);if(!Array.isArray(a.items))throw Error(`invalid response`);if(t.push(...a.items.map(Jo)),a.next_cursor===null)return t;if(n=Wo(a.next_cursor),n.length===0||n.length>4096)throw Error(`invalid response`)}}var $o=class{listeners=new Set;principals=new Map;constructor(e,t){t.registerPanel({id:`principal-directory`,matches:e=>e===`#/overview`||[`invocations`,`http-traffic`].includes(H(e)?.destination??``),invalidations:[`authorization`],read:()=>Qo(e),publish:e=>{this.principals=new Map(e.map(e=>[e.id,e.displayName])),this.emit()}}),e.registerProtectedState(()=>{this.principals=new Map,this.emit()})}snapshot(){return this.principals}subscribe(e){return this.listeners.add(e),e(this.principals),()=>this.listeners.delete(e)}emit(){for(let e of this.listeners)e(this.principals)}};async function es(e,t){let n=await Zo(e,`/api/v2/principals/${t}`);if(n===void 0)return;if(!n.response.ok)throw Error(`Agent data is unavailable.`);let r=Jo(n.value),i=n.response.headers.get(`ETag`);if(r.id!==t||i!==`"principal-${t}-${r.revision}"`)throw Error(`The current agent revision is unavailable.`);return{principal:r,etag:i}}async function ts(e){if(e.headers.get(`Content-Type`)!==`application/json`)throw Error(`invalid response`);let t=Jo(await e.json());if(e.headers.get(`ETag`)!==`"principal-${t.id}-${t.revision}"`)throw Error(`invalid agent revision`);return t}async function ns(e){if(e.headers.get(`Content-Type`)!==`application/json`)throw Error(`invalid response`);let t=Uo(await e.json(),[`principal`,`bearer`]),n=Wo(t.bearer);if(!/^mgw_agent_[A-Za-z0-9_-]{43}$/.test(n))throw Error(`invalid response`);return{principal:Jo(t.principal),bearer:n}}async function rs(e){if(e.headers.get(`Content-Type`)!==`application/json`)throw Error(`invalid response`);return Yo(await e.json())}function is(e){return e===`allow`?`Allow requests`:`Block requests`}function as(e){return e===`requestable`?`Requestable`:e===`allowed-only`?`Allowed tools only`:`All tools`}function os({mutations:e,detail:t,onRefresh:n,notify:r,readUnavailable:i=!1}){let a=t===void 0,o=t?.principal,s=V({displayName:o?.displayName??``,state:o?.state??`active`,visibility:o?.visibility??`requestable`,httpDefault:o?.httpDefault??`block`}),[c,l]=z(s.current.displayName),[u,d]=z(s.current.state),[f,p]=z(s.current.visibility),[m,h]=z(s.current.httpDefault),[g,_]=z(t?.etag),[v,y]=z(),[b,x]=z(),[C]=z(()=>e.create()),[w,T]=z(()=>C.snapshot()),E=V(null),D=JSON.stringify({displayName:c,state:u,visibility:f,httpDefault:m})!==JSON.stringify(s.current),O=!a&&(i||g!==t?.etag),k=Cr(D);B(()=>C.subscribe(T),[C]),B(()=>()=>C.close(),[C]),B(()=>{o===void 0||D||w.state===`uncertain`||w.requiresRefresh||(s.current={displayName:o.displayName,state:o.state,visibility:o.visibility,httpDefault:o.httpDefault},l(o.displayName),d(o.state),p(o.visibility),h(o.httpDefault),_(t?.etag))},[o?.id,t?.etag]);let A=async e=>{let t=await e;if(t.kind===`acknowledged`){C.abandon();let e=`principal`in t.value?t.value.principal:t.value;s.current={displayName:e.displayName,state:e.state,visibility:e.visibility,httpDefault:e.httpDefault},l(e.displayName),d(e.state),p(e.visibility),h(e.httpDefault),_(`"principal-${e.id}-${e.revision}"`),a?(r(`Agent created.`),k(`#/agents/${e.id}`,!0)):(x(`Agent settings saved.`),n())}},j=()=>{if(y(void 0),x(void 0),c.length===0||new TextEncoder().encode(c).length>256){y(`Display name must contain 1–256 UTF-8 bytes.`);return}if(a)return{authority:!1,spec:{route:`/api/v2/principals`,method:`POST`,body:JSON.stringify({display_name:c,visibility:f,http_default:m}),precondition:null,requiresPrecondition:!1,idempotency:`none`,successStatuses:[201],decode:rs}};if(t===void 0||O||w.state===`uncertain`||w.requiresRefresh)return;let e=t.principal,n=s.current,r={};if(c!==n.displayName&&(r.display_name=c),u!==n.state&&(r.state=u),f!==n.visibility&&(r.visibility=f),m!==n.httpDefault&&(r.http_default=m),Object.keys(r).length===0){y(`Change at least one agent field.`);return}return{authority:r.state!==void 0||r.http_default!==void 0,spec:{route:`/api/v2/principals/${e.id}`,method:`PATCH`,body:JSON.stringify(r),precondition:g??null,requiresPrecondition:!0,idempotency:`none`,successStatuses:[200],decode:async t=>{let n=await ts(t);if(n.id!==e.id)throw Error(`invalid agent identity`);return n}}}},M=()=>{let e=j();e!==void 0&&(C.begin(e.spec),a||e.authority?C.confirm():A(C.submit()))},N=w.state===`submitting`||w.state===`confirming`||w.availability===`storage_latched`;return U(`section`,{class:`panel domain-panel`,"aria-labelledby":`principal-editor-title`,children:[U(`div`,{class:`panel-heading`,children:U(`div`,{children:U(`h2`,{id:`principal-editor-title`,children:a?`Agent configuration`:`Edit agent`})})}),a&&U(S,{children:[U(`p`,{children:`Creating an agent also adds the ordinary Default Gateway access grant for Gateway's six fixed MCP self-service tools, not downstream tools or future protocols.`}),U(`p`,{class:`bounded-note`,children:`Gateway generates the agent ID as a permanent identity. The display name and MCP discovery visibility can be changed later.`})]}),U(`form`,{id:`principal-editor-form`,"data-testid":`principal-editor`,onSubmit:e=>{e.preventDefault(),M()},children:[U(J,{id:`principal-display-name`,label:`Display name`,required:!0,children:e=>U(`input`,{...e,"data-testid":`principal-display-name`,placeholder:`Research assistant`,value:c,disabled:N,onInput:e=>l(e.currentTarget.value),required:!0})}),!a&&U(J,{id:`principal-state`,label:`Agent enabled`,hint:`Disabling immediately removes current credential authority.`,children:e=>U(On,{attributes:e,checked:u===`active`,disabled:N,testID:`principal-state`,onChange:e=>d(e?`active`:`disabled`)})}),U(J,{id:`principal-visibility`,label:`MCP discovery visibility`,hint:`Discovery visibility grants no access; MCP grants remain authoritative.`,children:e=>U(`select`,{...e,"data-testid":`principal-visibility`,value:f,disabled:N,onChange:e=>p(e.currentTarget.value),children:[U(`option`,{value:`requestable`,children:`Requestable`}),U(`option`,{value:`allowed-only`,children:`Allowed tools only`}),U(`option`,{value:`all`,children:`All tools`})]})}),U(J,{id:`principal-http-default`,label:`HTTP default`,hint:`Default allow supplies no credential, tunnel permission or local/private access.`,children:e=>U(`select`,{...e,value:m,disabled:N,onChange:e=>h(e.currentTarget.value),children:[U(`option`,{value:`block`,children:`Block requests`}),U(`option`,{value:`allow`,children:`Allow requests`})]})})]}),(O||w.requiresRefresh||w.state===`uncertain`)&&t!==void 0&&U(K,{state:`warning`,title:`Review current agent settings`,children:[U(`p`,{children:`Your draft is preserved. Last loaded settings:`}),U(`dl`,{class:`detail-facts`,children:[U(`div`,{children:[U(`dt`,{children:`Display name`}),U(`dd`,{children:t.principal.displayName})]}),U(`div`,{children:[U(`dt`,{children:`Agent enabled`}),U(`dd`,{children:t.principal.state===`active`?`Enabled`:`Disabled`})]}),U(`div`,{children:[U(`dt`,{children:`MCP discovery visibility`}),U(`dd`,{children:as(t.principal.visibility)})]}),U(`div`,{children:[U(`dt`,{children:`HTTP default`}),U(`dd`,{children:is(t.principal.httpDefault)})]}),U(`div`,{children:[U(`dt`,{children:`Revision`}),U(`dd`,{children:t.principal.revision})]})]}),U(`div`,{class:`form-actions`,children:[U(`button`,{type:`button`,onClick:n,children:`Refresh current settings`}),w.state!==`uncertain`&&U(`button`,{type:`button`,disabled:i,onClick:()=>{let e=t.principal,n=s.current;c===n.displayName&&l(e.displayName),u===n.state&&d(e.state),f===n.visibility&&p(e.visibility),m===n.httpDefault&&h(e.httpDefault),s.current={displayName:e.displayName,state:e.state,visibility:e.visibility,httpDefault:e.httpDefault},_(t.etag),C.abandon()},children:`Use reviewed revision; keep draft`}),w.state===`uncertain`&&U(`button`,{type:`button`,disabled:i,onClick:()=>{let e=t.principal;s.current={displayName:e.displayName,state:e.state,visibility:e.visibility,httpDefault:e.httpDefault},l(e.displayName),d(e.state),p(e.visibility),h(e.httpDefault),_(t.etag),C.abandon(),x(void 0)},children:`Discard uncertain draft; use current settings`})]})]}),v!==void 0&&U(K,{state:`error`,title:`Check agent configuration`,children:U(`p`,{children:v})}),w.problem!==void 0&&U(K,{state:`error`,title:_n(w.problem),children:w.requiresRefresh&&U(`p`,{children:`Review current settings and the preserved draft before accepting a refreshed revision.`})}),w.state===`uncertain`&&U(K,{state:`warning`,title:`Agent outcome is unknown`,children:U(`p`,{children:`Do not replay this non-idempotent change. Refresh the agent and authorization state to investigate.`})}),b!==void 0&&U(K,{state:`empty`,title:b}),U(`button`,{ref:E,class:`${a?`create-action`:`primary-action`} form-submit-action`,"data-testid":`principal-editor-submit`,form:`principal-editor-form`,type:`submit`,disabled:N||!a&&!D||O||w.requiresRefresh||w.state===`uncertain`,children:w.state===`submitting`?`Submitting…`:a?`Review and create`:`Save agent`}),U(jn,{id:`principal-change-confirm`,open:w.state===`confirming`,title:a?`Review agent`:`Review agent changes`,consequence:a?U(`div`,{class:`review-stack`,children:[U(`p`,{children:`Review this permanent identity and its initial MCP self-service access before creating it. Discovery visibility grants no access; MCP grants remain authoritative.`}),U(`dl`,{class:`detail-facts`,children:[U(`div`,{children:[U(`dt`,{children:`Display name`}),U(`dd`,{children:c})]}),U(`div`,{children:[U(`dt`,{children:`MCP discovery visibility`}),U(`dd`,{children:as(f)})]}),U(`div`,{children:[U(`dt`,{children:`HTTP default`}),U(`dd`,{children:is(m)})]}),U(`div`,{children:[U(`dt`,{children:`Initial MCP self-service access`}),U(`dd`,{children:`Default Gateway access — an ordinary grant for Gateway's six fixed MCP self-service tools, not downstream tools or future protocols.`})]})]})]}):U(`div`,{class:`review-stack`,children:[U(`dl`,{class:`detail-facts`,children:[c!==s.current.displayName&&U(`div`,{children:[U(`dt`,{children:`Display name`}),U(`dd`,{children:c})]}),u!==s.current.state&&U(`div`,{children:[U(`dt`,{children:`Agent enabled`}),U(`dd`,{children:u===`active`?`Enabled`:`Disabled`})]}),f!==s.current.visibility&&U(`div`,{children:[U(`dt`,{children:`MCP discovery visibility`}),U(`dd`,{children:as(f)})]}),m!==s.current.httpDefault&&U(`div`,{children:[U(`dt`,{children:`HTTP default`}),U(`dd`,{children:is(m)})]})]}),u!==s.current.state&&U(`p`,{children:u===`disabled`?`Disabling revokes current agent authority and interrupts credential-bound sessions and streams.`:`Re-enabling does not restore revoked credentials or removed MCP self-service access.`}),m!==s.current.httpDefault&&U(`p`,{children:`Explicit blocks still win. Default allow supplies no credential, tunnel permission or local/private access.`})]}),confirmLabel:a?`Create agent`:`Save agent changes`,destructive:!a&&u===`disabled`,returnFocus:E,onCancel:()=>C.abandon(),onConfirm:()=>void A(C.submit())})]})}function ss({mutations:e,sinks:t,detail:n,onRefresh:r}){let i=n.principal,[a]=z(()=>e.create()),[o,s]=z(()=>a.snapshot()),[c,l]=z(`issue`),[u,d]=z(),[f,p]=z(),[m,h]=z(),g=V(null),_=V(null);B(()=>a.subscribe(s),[a]),B(()=>()=>a.close(),[a]),B(()=>()=>u?.cancel(),[u]);let v=()=>{h(void 0);let e={route:`/api/v2/principals/${i.id}/credential`,method:`POST`,body:`{}`,precondition:n.etag,requiresPrecondition:!0,idempotency:`none`,successStatuses:[201],decode:ns};l(i.hasCredential?`rotate`:`issue`),d(void 0),a.begin(e),a.confirm()},y=()=>{h(void 0);let e={route:`/api/v2/principals/${i.id}/credential`,method:`DELETE`,body:`{}`,precondition:n.etag,requiresPrecondition:!0,idempotency:`none`,successStatuses:[200],decode:ts};l(`revoke`),d(void 0),a.begin(e),a.confirm()},b=()=>{u?.cancel(),d(void 0),a.abandon()},x=async()=>{let e=u;if(c!==`revoke`&&e===void 0&&(e=t.prepareOneTime(`${i.hasCredential?`Replacement`:`New`} agent bearer for ${i.displayName}`),e===void 0)){h(`The protected one-time display could not be prepared. No credential was changed.`),a.abandon();return}let o=await a.submit();if(o.kind===`acknowledged`){if(p(void 0),c!==`revoke`){if(!(`bearer`in o.value))throw Error(`invalid response`);let t=e?.publish(o.value.bearer)??`lost`;h(t===`published`?`The one-time agent bearer is ready. It cannot be revealed again.`:c===`rotate`?`The replacement may now be current and the prior bearer may already be invalid. Review agent metadata, then explicitly rotate or revoke the lost current credential. Do not replay the operation.`:`A current credential may now occupy the slot, but its bearer was lost and cannot be recovered. Review agent metadata, then explicitly rotate or revoke it. Do not replay issue.`)}else h(`Agent credential revoked. Prior authority no longer authenticates.`);d(void 0),a.abandon(),r();return}o.kind===`rejected`&&o.requiresRefresh&&(p(n.etag),r()),c!==`revoke`&&(o.kind===`uncertain`?e?.lose():e?.cancel()),d(void 0)},S=i.state!==`active`||o.state===`submitting`||o.availability===`storage_latched`||f===n.etag;return U(`section`,{class:`detail-section`,"aria-labelledby":`principal-credential-title`,"data-testid":`principal-credential-actions`,children:[U(`div`,{class:`panel-heading`,children:[U(`div`,{children:U(`h2`,{id:`principal-credential-title`,children:`Agent credential`})}),U(G,{state:i.hasCredential?`current`:`empty`,children:i.hasCredential?`Issued`:`Not issued`})]}),U(`p`,{children:`Only one agent credential may be active at a time. Rotating it replaces the current credential.`}),i.credential!==null&&U(`dl`,{class:`detail-facts`,children:[U(`div`,{children:[U(`dt`,{children:`Credential ID`}),U(`dd`,{class:`technical-value`,children:i.credential.id})]}),U(`div`,{children:[U(`dt`,{children:`Fingerprint`}),U(`dd`,{class:`technical-value`,children:i.credential.fingerprint})]}),U(`div`,{children:[U(`dt`,{children:`Issued`}),U(`dd`,{children:U(Y,{value:i.credential.createdAt})})]}),U(`div`,{children:[U(`dt`,{children:`Credential revision`}),U(`dd`,{children:i.credential.revision})]})]}),i.state!==`active`&&U(K,{state:`unavailable`,title:`Agent is disabled`,children:U(`p`,{children:`Re-enable the agent before issuing agent authority.`})}),o.problem!==void 0&&U(K,{state:`error`,title:_n(o.problem),children:o.requiresRefresh&&U(`p`,{children:`Refresh the agent and review its current authority before trying a new action.`})}),o.state===`uncertain`&&U(K,{state:`warning`,title:`Credential outcome is unknown`,children:U(`p`,{children:c===`rotate`?`Do not replay. The replacement may be current and the prior bearer may already be invalid. Refresh the agent, then explicitly rotate or revoke the observed current credential.`:c===`issue`?`Do not replay issue. A current credential may occupy the slot while its bearer is permanently lost. Refresh the agent, then explicitly rotate or revoke the observed credential.`:`Do not replay revoke. Authority may already be revoked. Refresh the agent before another explicit action.`})}),m!==void 0&&U(K,{state:`empty`,title:m}),U(`div`,{class:`inline-actions`,children:[U(`button`,{ref:g,class:i.hasCredential?`danger-action`:`create-action`,"data-testid":`principal-credential-issue`,type:`button`,disabled:S,onClick:v,children:i.hasCredential?`Rotate credential`:`Issue credential`}),i.hasCredential&&U(`button`,{ref:_,class:`danger-action`,"data-testid":`principal-credential-revoke`,type:`button`,disabled:S,onClick:y,children:`Revoke credential`})]}),U(jn,{id:`principal-credential-confirm`,open:o.state===`confirming`,title:c===`rotate`?`Rotate agent credential?`:c===`issue`?`Issue agent credential?`:`Revoke agent credential?`,consequence:c===`rotate`?U(`p`,{children:`Rotating immediately replaces current agent authority. The new bearer is displayed once.`}):c===`issue`?U(`p`,{children:`The new bearer is displayed once and becomes this agent's current authority.`}):U(`p`,{children:`The current bearer, authenticated sessions, and streams stop authorizing this agent.`}),confirmLabel:c===`rotate`?`Rotate credential`:c===`issue`?`Issue credential`:`Revoke credential`,destructive:c===`revoke`,returnFocus:c===`revoke`?_:g,onCancel:b,onConfirm:()=>void x()})]})}function cs({session:e,mutations:t,sinks:n,resolved:r,view:i,onRefresh:a,notify:o}){let s=r.location.segments,c=s[1]===`new`,l=s.length===2&&!c?s[1]:void 0,[u,d]=z(),[f,p]=z();if(B(()=>{let t=!0;return p(void 0),c||l===void 0||l!==void 0&&(d(e=>e?.principal.id===l?e:void 0),es(e,l).then(e=>{t&&e!==void 0&&d(e)}).catch(e=>{t&&p(e instanceof Error?e.message:`Agent data is unavailable.`)})),()=>{t=!1}},[r.canonicalFragment,i.generation]),c)return U(`div`,{class:`domain-view`,"data-testid":`principal-create-view`,children:U(os,{mutations:t,onRefresh:a,notify:o})});if(l!==void 0&&f!==void 0&&u?.principal.id!==l)return U(K,{state:`error`,title:`Agent data unavailable`,children:U(`p`,{children:f})});if(l!==void 0){if(u?.principal.id!==l)return U(K,{state:`loading`,title:`Loading agent`});let e=u.principal;return U(`div`,{class:`domain-view`,"data-testid":`principal-detail`,children:[f!==void 0&&U(K,{state:`error`,title:`Current agent data unavailable`,children:U(`p`,{children:[f,` Your draft is preserved; refresh before saving.`]})}),U(`nav`,{class:`detail-navigation`,"aria-label":`Agent navigation`,children:U(`a`,{href:`#/agents`,children:`Back to agents`})}),U(`header`,{class:`detail-context`,"data-testid":`detail-context`,children:[U(`div`,{class:`detail-context-heading`,children:[U(`div`,{children:U(`h1`,{id:`principal-page-title`,tabindex:-1,children:e.displayName})}),U(G,{state:e.state===`active`?`current`:`neutral`,children:e.state===`active`?`Active`:`Disabled`})]}),U(`p`,{class:`technical-value`,children:e.id})]}),U(`section`,{class:`detail-section`,"aria-labelledby":`principal-title`,children:[U(`div`,{class:`panel-heading`,children:U(`h2`,{id:`principal-title`,children:`Agent details`})}),U(`h3`,{children:`Access defaults`}),U(`dl`,{class:`detail-facts`,children:[U(`div`,{children:[U(`dt`,{children:`MCP discovery visibility`}),U(`dd`,{children:as(e.visibility)})]}),U(`div`,{children:[U(`dt`,{children:`HTTP default`}),U(`dd`,{children:is(e.httpDefault)})]})]}),U(`h3`,{children:`Metadata`}),U(`dl`,{class:`detail-facts`,children:[U(`div`,{children:[U(`dt`,{children:`Agent revision`}),U(`dd`,{children:e.revision})]}),U(`div`,{children:[U(`dt`,{children:`Updated`}),U(`dd`,{children:U(Y,{value:e.updatedAt})})]})]})]}),U(os,{mutations:t,detail:u,readUnavailable:f!==void 0,onRefresh:a,notify:o},e.id),U(ss,{mutations:t,sinks:n,detail:u,onRefresh:a})]})}return U(ls,{session:e,resolved:r,view:i})}function ls({session:e,resolved:t,view:n}){let{items:r,controls:i}=Nr(e,t,n,(t,n,r)=>{let i=new URLSearchParams({limit:`50`,sort:t.sort??`name`,direction:t.direction??`ascending`});for(let e of[`name`,`state`,`visibility`,`http_default`]){let n=t[`filter_${e}`];n!==void 0&&i.set(e,n)}return n!==null&&i.set(`cursor`,n),Mr(e,`/api/v2/principals?${i}`,Jo,r)},Cr(!1),{key:`name`,direction:`ascending`});return U(`div`,{class:`domain-view`,"data-testid":`principals-view`,children:[U(`div`,{class:`collection-toolbar`,children:U(`a`,{class:`button-link create-action`,href:`#/agents/new`,"data-testid":`principal-create-link`,children:`Create agent`})}),U(`section`,{class:`panel domain-panel`,"aria-labelledby":`page-title`,children:U(Dn,{caption:`Agent identities`,rowHeaderKey:`name`,additionalSorts:[{key:`id`,label:`Agent ID`,sortValue:e=>e.id}],remote:i,itemNames:{singular:`agent`,plural:`agents`},emptyTitle:`No agents`,items:r,rowKey:e=>e.id,initialSort:{key:`name`,direction:`ascending`},rowTestID:`principal-row`,filters:[{key:`name`,label:`Name or ID`,type:`text`,value:e=>e.displayName,literalValues:e=>[e.id]},{key:`state`,label:`Status`,type:`select`,value:e=>e.state,options:[{value:`active`,label:`Active`},{value:`disabled`,label:`Disabled`}]},{key:`visibility`,label:`MCP discovery visibility`,type:`select`,value:e=>e.visibility,options:[{value:`requestable`,label:`Requestable`},{value:`allowed-only`,label:`Allowed tools only`},{value:`all`,label:`All tools`}]},{key:`http_default`,label:`HTTP default`,type:`select`,value:e=>e.httpDefault,options:[{value:`block`,label:`Block requests`},{value:`allow`,label:`Allow requests`}]}],columns:[{key:`name`,label:`Agent`,role:`identity`,sortValue:e=>e.displayName,render:e=>U(q,{primary:U(`a`,{href:`#/agents/${e.id}`,children:e.displayName}),secondary:e.id})},{key:`state`,label:`Status`,role:`status`,sortValue:e=>e.state,render:e=>U(G,{state:e.state===`active`?`current`:`neutral`,children:e.state===`active`?`Active`:`Disabled`})},{key:`visibility`,label:`MCP discovery visibility`,role:`status`,render:e=>as(e.visibility)},{key:`http-default`,label:`HTTP default`,role:`status`,render:e=>is(e.httpDefault)}]})})]})}var us=/^[0-7][0-9A-HJKMNP-TV-Z]{25}$/;function ds(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`invalid response`);let n=e;if(Object.keys(n).sort().join(`,`)!==[...t].sort().join(`,`))throw Error(`invalid response`);return n}function fs(e){if(typeof e!=`string`)throw Error(`invalid response`);return e}function ps(e){let t=fs(e);if(!us.test(t))throw Error(`invalid response`);return t}function ms(e){let t=ds(e,[..._r(e),`id`,`description`,`revision`,`principal_id`,`effect`,`server_id`,`upstream_name`,`constraint`,`expires_at`,`state`,`created_at`]),n=vr(t);if(n&&(t.effect!==`allow`||t.upstream_name!==null||t.constraint!==null)||t.effect!==`allow`&&t.effect!==`deny`||t.state!==`active`&&t.state!==`expired`||t.upstream_name!==null&&typeof t.upstream_name!=`string`||t.expires_at!==null&&typeof t.expires_at!=`string`||t.constraint!==null&&(typeof t.constraint!=`object`||Array.isArray(t.constraint)))throw Error(`invalid response`);return{readOnly:n,id:ps(t.id),description:t.description===null?null:fs(t.description),revision:fs(t.revision),principalID:ps(t.principal_id),effect:t.effect,serverID:ps(t.server_id),upstreamName:t.upstream_name,constraint:t.constraint,expiresAt:t.expires_at,state:t.state,createdAt:fs(t.created_at)}}function hs(e){return{Accept:`application/json`,"X-CSRF-Token":e.csrfToken}}async function gs(e,t){return e.runProtected(async e=>{let n=await fetch(t,{credentials:`same-origin`,redirect:`error`,signal:e.signal,headers:hs(e)});if(await e.sessionLost(n))return;let r=n.headers.get(`Content-Type`);if(r!==`application/json`&&r!==`application/problem+json`)throw Error(`Grant data is unavailable.`);return{response:n,value:await n.json()}})}async function _s(e){let t=[],n=null;for(;;){let r=new URLSearchParams({limit:`50`});n!==null&&r.set(`cursor`,n);let i=await gs(e,`/api/v2/mcp/servers?${r}`);if(i===void 0)return[];if(!i.response.ok)throw Error(`Server data is unavailable.`);let a=ds(i.value,[`items`,`next_cursor`]);if(!Array.isArray(a.items))throw Error(`invalid response`);if(t.push(...a.items.map(Wa)),a.next_cursor===null)return t;n=fs(a.next_cursor)}}async function vs(e){let t=[],n=null,r=!1;for(;;){let i=new URLSearchParams({limit:`50`});n!==null&&i.set(`cursor`,n);let a=await gs(e,`/api/v2/mcp/grants?${i}`);if(a===void 0)return[];if(a.response.status===409&&n!==null&&!r){t.length=0,n=null,r=!0;continue}if(!a.response.ok)throw Error(`Grant data is unavailable.`);let o=ds(a.value,[`items`,`next_cursor`,`total_count`,`offset`]);if(!Array.isArray(o.items))throw Error(`invalid response`);if(t.push(...o.items.map(e=>{let t=ds(e,[`grant`,`principal_display_name`,`server_display_name`]);return fs(t.principal_display_name),fs(t.server_display_name),ms(t.grant)})),o.next_cursor===null)return t;if(n=fs(o.next_cursor),n.length===0||n.length>4096)throw Error(`invalid response`)}}async function ys(e,t){let n=await gs(e,`/api/v2/mcp/grants/${t}`);if(n!==void 0){if(!n.response.ok)throw Error(`Grant data is unavailable.`);return ms(n.value)}}async function bs(e){if(e.headers.get(`Content-Type`)!==`application/json`)throw Error(`invalid response`);return ms(await e.json())}function xs({session:e,mutations:t,query:n,principals:r,servers:i}){let a=V({description:``,principalID:n.principal_id??``,effect:`allow`,readOnly:!1,serverID:n.server_id??``,scope:`server`,upstreamName:``,expiresAt:``,atoms:[]}),[o,s]=z(a.current.description),[c,l]=z(a.current.principalID),[u,d]=z(a.current.effect),[f,p]=z(!1),[m,h]=z(a.current.serverID),[g,_]=z(a.current.scope),[v,y]=z(``),[b,x]=z(),[S,C]=z(),[w,T]=z(!1),[E,D]=z(!1),[O,k]=z(``),[A,j]=z([]),[M,N]=z(),[ee,P]=z(!1),[te,F]=z(!1),ne=V(null),[I]=z(()=>t.create()),[re,ie]=z(()=>I.snapshot()),ae=b?.find(e=>e.serverID===m&&e.upstreamName===v),oe=S===void 0||S.serverID!==m||S.upstreamName!==v||S.id!==ae?.id?void 0:To(S.descriptor),se=us.test(m)?v===``?`Choose a tool`:w?`Unavailable`:b===void 0?`Loading…`:ae===void 0?`Unknown`:`Known`:`Select a server`,ce=us.test(m)?w?`Catalog unavailable. Manual entry is still available.`:ae===void 0?null:E?`Schema unavailable. Manual conditions are still available.`:oe===void 0?`Loading schema…`:null:null,L=(()=>{try{return`{"description":${o===``?`null`:JSON.stringify(o)},"principal_id":${JSON.stringify(c)},"effect":${JSON.stringify(u)},"server_id":${JSON.stringify(m)},"upstream_name":${g===`server`?`null`:JSON.stringify(v)},"constraint":${Fo(A)},"expires_at":${O===``?`null`:JSON.stringify(new Date(O).toISOString())}${yr(f)}}`}catch{return`Complete the policy to review its serialized form.`}})(),le=JSON.stringify({description:o,principalID:c,effect:u,readOnly:f,serverID:m,scope:g,upstreamName:v,expiresAt:O,atoms:A}),ue=V(le);ue.current=le;let de=Cr(le!==JSON.stringify(a.current));B(()=>I.subscribe(ie),[I]),B(()=>()=>I.close(),[I]),B(()=>{let t=new AbortController;return T(!1),x(void 0),g!==`tool`||!us.test(m)||ko(e,m,t.signal).then(e=>{!t.signal.aborted&&e!==void 0&&x(e)}).catch(()=>{t.signal.aborted||T(!0)}),()=>t.abort()},[g,m,e]),B(()=>{let t=new AbortController;return D(!1),C(void 0),ae===void 0||Ao(e,ae,t.signal).then(e=>{!t.signal.aborted&&e!==void 0&&C(e)}).catch(()=>{t.signal.aborted||D(!0)}),()=>t.abort()},[ae,m,e]);let fe=async()=>{let t=ue.current;N(void 0);try{if(o.length>0&&(o.trim()!==o||new TextEncoder().encode(o).length>256))throw Error(`Description must be at most 256 bytes without surrounding whitespace.`);if(gn(o))throw Error(`Description cannot contain control characters.`);if(!us.test(c)||!us.test(m))throw Error(`Agent and server IDs must be complete Gateway IDs.`);if(f&&(g!==`server`||u!==`allow`))throw Error(`Read-only access requires server-wide ALLOW scope.`);if(g===`tool`&&v.length===0)throw Error(`Exact-tool scope requires an upstream tool name.`);if(g===`server`&&A.length!==0)throw Error(`Server-wide grants cannot have argument conditions.`);if(A.length>16)throw Error(`At most 16 matcher atoms are allowed.`);if(A.some(e=>!No(e.pointer)))throw Error(`Each atom requires a valid RFC 6901 JSON pointer.`);if(new Set(A.map(e=>`${e.operator}:${e.pointer}`)).size!==A.length)throw Error(`Pointers must be unique within each operator.`);if(A.some(e=>e.operator===`regex`&&new TextEncoder().encode(e.value).length>1024))throw Error(`RE2 patterns must be at most 1024 bytes.`);if(!document.getElementById(`grant-expiry`).validity.valid)throw Error(`Choose a complete expiry date and time, or clear it for no expiry.`);if(O!==``&&(Number.isNaN(Date.parse(O))||Date.parse(O)<=Date.now()))throw Error(`Choose an expiry date and time in the future.`);let n=Fo(A);if(n!==`null`){F(!0);let r=await Bo(e,n);if(r===void 0||ue.current!==t)return;if(r!==null)throw Error(r)}let r={route:`/api/v2/mcp/grants`,method:`POST`,body:`{"description":${o===``?`null`:JSON.stringify(o)},"principal_id":${JSON.stringify(c)},"effect":${JSON.stringify(u)},"server_id":${JSON.stringify(m)},"upstream_name":${g===`server`?`null`:JSON.stringify(v)},"constraint":${n},"expires_at":${O===``?`null`:JSON.stringify(new Date(O).toISOString())}${yr(f)}}`,precondition:null,requiresPrecondition:!1,idempotency:`none`,successStatuses:[201],decode:async e=>{let t=await bs(e);if(t.readOnly!==f)throw Error(`invalid response`);return t}};I.begin(r),P(!0)}catch(e){N(e instanceof Error?e.message:`Invalid grant.`)}finally{F(!1)}},R=te||re.state===`submitting`||re.availability===`storage_latched`;return U(`div`,{class:`domain-view`,"data-testid":`grant-create-view`,children:U(`section`,{class:`panel domain-panel`,"aria-labelledby":`grant-create-title`,children:[U(`div`,{class:`panel-heading`,children:U(`div`,{children:U(`h2`,{id:`grant-create-title`,children:`Create MCP Grant`})})}),U(`p`,{class:`bounded-note`,children:`The effect, target, scope, conditions, and expiry cannot be edited after creation. You can update the optional description later.`}),U(`form`,{onSubmit:e=>{e.preventDefault(),fe()},children:[U(J,{id:`grant-description`,label:`Description`,optional:!0,children:e=>U(`input`,{...e,"data-testid":`grant-description`,placeholder:`Example tool access policy`,value:o,maxlength:256,onInput:e=>s(e.currentTarget.value)})}),U(J,{id:`grant-principal`,label:`Agent`,required:!0,children:e=>U(`select`,{...e,"data-testid":`grant-principal`,value:c,onChange:e=>l(e.currentTarget.value),required:!0,children:[U(`option`,{value:``,children:`Choose an agent`}),r.map(e=>U(`option`,{value:e.id,children:[e.displayName,` — `,e.id,e.state===`disabled`?` (Disabled)`:``]},e.id))]})}),U(J,{id:`grant-effect`,label:`Effect`,children:e=>U(`select`,{...e,"data-testid":`grant-effect`,value:u,onChange:e=>{d(e.currentTarget.value),e.currentTarget.value!==`allow`&&p(!1)},children:[U(`option`,{value:`allow`,children:`ALLOW`}),U(`option`,{value:`deny`,children:`DENY`})]})}),U(J,{id:`grant-server`,label:`Server or Gateway scope`,required:!0,children:e=>U(`select`,{...e,"data-testid":`grant-server`,value:m,onChange:e=>h(e.currentTarget.value),required:!0,children:[U(`option`,{value:``,children:`Choose a server`}),U(`option`,{value:`00000000000000000000000000`,children:`Gateway self-service tools`}),i.filter(e=>e.desiredState!==`deleted`).map(e=>U(`option`,{value:e.id,children:[e.displayName,` — `,e.id,e.desiredState===`disabled`?` (Disabled)`:``]},e.id))]})}),U(J,{id:`grant-scope`,label:`Scope`,children:e=>U(`select`,{...e,"data-testid":`grant-scope`,value:g,onChange:e=>{let t=e.currentTarget.value;_(t),t===`tool`&&p(!1),t===`server`&&j([])},children:[U(`option`,{value:`server`,children:`Entire server`}),U(`option`,{value:`tool`,children:`Exact upstream tool`})]})}),g===`server`&&u===`allow`&&U(`div`,{children:U(J,{id:`grant-read-only`,label:`Allowed tools`,...f?{hint:`Includes current and future tools marked readOnlyHint=true. The Gateway does not verify that these tools are read-only; they may still change data.`}:{},children:e=>U(`select`,{...e,"data-testid":`grant-read-only`,value:f?`read-only`:`all`,onChange:e=>p(e.currentTarget.value===`read-only`),children:[U(`option`,{value:`all`,children:`All tools`}),U(`option`,{value:`read-only`,children:`Only tools marked read-only`})]})})}),g===`tool`&&U(`div`,{children:[U(J,{id:`grant-upstream`,label:`Tool name`,hint:`Choose a tool or enter an exact name.`,required:!0,children:e=>U(`div`,{class:`matcher-tool-input`,children:[U(`span`,{"data-testid":`grant-namespace`,children:[i.find(e=>e.id===m)?.namespace??(m===`00000000000000000000000000`?`mcp_gateway`:`Choose a server`),` `,`.`]}),U(kn,{attributes:e,label:`Tool name`,testID:`grant-upstream`,placeholder:`lookup`,value:v,options:(b??[]).filter(e=>e.serverID===m).map(e=>({value:e.upstreamName})),onChange:y}),U(jo,{status:se,testID:`grant-tool-recognition`})]})}),ce&&U(`p`,{class:`bounded-note`,role:`status`,"data-testid":`grant-tool-posture`,children:ce})]}),g===`tool`&&U(`section`,{class:`subpanel`,"aria-labelledby":`constraint-title`,children:[U(`h3`,{id:`constraint-title`,children:`Conditions — All must match`}),U(`p`,{class:`field-hint`,children:`Choose suggested fields or enter custom JSON pointers.`}),oe?.unsupported&&U(`p`,{class:`bounded-note`,"data-testid":`matcher-schema-posture`,children:`Some schema fields cannot be suggested. Custom pointers are still available.`}),U(Io,{idPrefix:`constraint`,testPrefix:`constraint`,addTestID:`add-constraint-atom`,atoms:A,suggestions:oe,schemaState:us.test(m)&&!w&&(b===void 0||ae!==void 0&&!E&&oe===void 0)?`loading`:`unavailable`,onChange:e=>{N(void 0),j(e)}})]}),U(J,{id:`grant-expiry`,label:`Expires`,hint:`Choose a future date and time in your local timezone. Leave blank for no expiry.`,optional:!0,children:e=>U(`input`,{...e,"data-testid":`grant-expiry`,type:`datetime-local`,step:`1`,value:O,onInput:e=>k(e.currentTarget.value)})}),M!==void 0&&U(K,{state:`error`,title:`Check grant configuration`,children:U(`p`,{children:M})}),re.problem!==void 0&&U(K,{state:`error`,title:_n(re.problem)}),re.state===`uncertain`&&U(K,{state:`warning`,title:`Grant outcome is unknown`,children:U(`p`,{children:`Do not replay this non-idempotent creation. Refresh the filtered grant list to investigate.`})}),U(`button`,{ref:ne,class:`create-action form-submit-action`,"data-testid":`grant-create-submit`,type:`submit`,disabled:R,children:te?`Validating matcher…`:re.state===`submitting`?`Creating…`:`Review and create`})]}),U(jn,{id:`grant-create-confirm`,open:ee,title:`Review grant`,consequence:U(`div`,{class:`review-stack`,children:[U(`p`,{children:`This creates one immutable authorization policy. Every matcher atom is required (AND), and any matching DENY takes precedence over ALLOW.`}),f&&U(`p`,{children:`Includes current and future tools marked readOnlyHint=true. The Gateway does not verify that these tools are read-only; they may still change data.`}),A.length===0&&U(K,{state:`warning`,title:`Unconstrained access matches every argument object`}),U(`h3`,{children:`Identity and authority`}),U(`dl`,{class:`detail-facts`,children:[U(`div`,{children:[U(`dt`,{children:`Description`}),U(`dd`,{children:o})]}),U(`div`,{children:[U(`dt`,{children:`Agent`}),U(`dd`,{children:[r.find(e=>e.id===c)?.displayName??`Unknown agent`,` `,`· `,c]})]}),U(`div`,{children:[U(`dt`,{children:`Effect`}),U(`dd`,{children:u===`allow`?`Allow`:`Deny`})]}),U(`div`,{children:[U(`dt`,{children:`Server and literal tool`}),U(`dd`,{children:[i.find(e=>e.id===m)?.displayName??`Gateway self-service tools`,` `,`· `,m,g===`tool`?` · ${v}`:f?` · Read-only tools`:` · All tools`]})]}),U(`div`,{children:[U(`dt`,{children:`Catalog posture`}),U(`dd`,{children:g===`server`?`Not applicable to server-wide authority`:w?`Unavailable — literal manual name`:ae===void 0||S===void 0||E?`No verified current descriptor — literal manual name`:`Current durable descriptor · catalog revision ${S.catalogRevision}`})]}),U(`div`,{children:[U(`dt`,{children:`Expires`}),U(`dd`,{children:O===``?`No expiry`:U(Y,{value:Number.isFinite(Date.parse(O))?new Date(O).toISOString():O})})]}),U(`div`,{children:[U(`dt`,{children:`Constraint`}),U(`dd`,{children:A.length===0?`None`:`v2 · ${A.filter(e=>e.operator===`equals`).length} equality · ${A.filter(e=>e.operator===`regex`).length} regex`})]})]}),U(`div`,{children:[U(`strong`,{children:`Read-only serialized policy`}),U(`textarea`,{class:`inert-json matcher-policy-review`,"data-testid":`grant-review-policy`,"aria-label":`Read-only serialized policy`,readOnly:!0,rows:8,value:L})]})]}),confirmLabel:`Create grant`,returnFocus:ne,onCancel:()=>{P(!1),I.abandon()},onConfirm:()=>{P(!1),I.submit().then(e=>{e.kind===`acknowledged`&&de(`#/mcp/grants/${e.value.id}`,!0)})}})]})})}function Ss({mutations:e,grant:t,onAcknowledged:n}){let[r,i]=z(t.description??``),[a,o]=z(),[s]=z(()=>e.create()),[c,l]=z(()=>s.snapshot());B(()=>s.subscribe(l),[s]),B(()=>()=>s.close(),[s]);let u=async()=>{if(o(void 0),r.length>0&&(r.trim()!==r||new TextEncoder().encode(r).length>256||gn(r))){o(`Description must be at most 256 bytes without surrounding whitespace or control characters.`);return}if(r===(t.description??``)){o(`Change the description before saving.`);return}s.begin({route:`/api/v2/mcp/grants/${t.id}`,method:`PATCH`,body:JSON.stringify({description:r===``?null:r}),precondition:`"grant-${t.id}-${t.revision}"`,requiresPrecondition:!0,idempotency:`none`,successStatuses:[200],decode:bs});let e=await s.submit();e.kind===`acknowledged`&&n(e.value)};return U(`section`,{class:`panel domain-panel`,"aria-labelledby":`grant-description-title`,children:[U(`div`,{class:`panel-heading`,children:U(`div`,{children:U(`h2`,{id:`grant-description-title`,children:`Edit grant description`})})}),U(`form`,{onSubmit:e=>{e.preventDefault(),u()},children:[U(J,{id:`grant-description-edit`,label:`Description`,optional:!0,children:e=>U(`input`,{...e,value:r,maxlength:256,onInput:e=>i(e.currentTarget.value)})}),a!==void 0&&U(K,{state:`error`,title:`Description not saved`,children:U(`p`,{children:a})}),c.state===`rejected`&&U(K,{state:`error`,title:`Description not saved`,children:U(`p`,{children:c.problem===void 0?`Refresh the grant before trying again.`:_n(c.problem)})}),c.state===`uncertain`&&U(K,{state:`warning`,title:`Save outcome unknown`,children:U(`p`,{children:`Refresh the grant to inspect its description before taking another action.`})}),U(`button`,{class:`primary-action form-submit-action`,type:`submit`,disabled:r===(t.description??``)||c.state===`submitting`||c.state===`uncertain`||c.availability===`storage_latched`,children:c.state===`submitting`?`Saving…`:`Save description`})]})]})}function Cs({session:e,mutations:t,grant:n}){let[r]=z(()=>t.create()),[i,a]=z(()=>r.snapshot()),[o,s]=z(!1),[c,l]=z(`create_first`),[u,d]=z(n.effect===`allow`?`deny`:`allow`),[f,p]=z(`configure`),[m,h]=z(),[g,_]=z(`delete`),[v,y]=z(!1),[b,x]=z(),C=V(null),w=!n.readOnly&&n.effect===`allow`&&n.serverID===`00000000000000000000000000`&&n.upstreamName===null&&n.constraint===null&&n.expiresAt===null;B(()=>r.subscribe(a),[r]),B(()=>()=>r.close(),[r]);let T=()=>{let e=n.readOnly&&u===`allow`;return{route:`/api/v2/mcp/grants`,method:`POST`,body:JSON.stringify({description:n.description,principal_id:n.principalID,effect:u,...e?{read_only:!0}:{},server_id:n.serverID,upstream_name:n.upstreamName,constraint:null,expires_at:null}),precondition:null,requiresPrecondition:!1,idempotency:`none`,successStatuses:[201],decode:async t=>{let n=await bs(t);if(n.readOnly!==e)throw Error(`invalid response`);return{kind:`created`,grant:n}}}},E=()=>({route:`/api/v2/mcp/grants/${n.id}`,method:`DELETE`,body:null,precondition:null,requiresPrecondition:!1,idempotency:`none`,successStatuses:[204],decode:async()=>({kind:`deleted`})}),D=e=>{x(void 0),_(e),r.begin(e===`create`?T():E()),y(!0)},O=()=>vs(e),k=async()=>{y(!1);let e=await r.submit();if(e.kind!==`acknowledged`)return;if(await O(),r.abandon(),!o){window.location.hash=`#/mcp/grants`;return}if(f===`configure`){e.value.kind===`created`?(h(e.value.grant.id),p(`delete_second`),x(`Replacement grant created; original grant not yet deleted.`)):(p(`create_second`),x(`Original grant deleted; replacement not yet created.`));return}let t=e.value.kind===`created`?e.value.grant.id:m;window.location.hash=t===void 0?`#/mcp/grants`:`#/mcp/grants/${t}`},A=()=>{y(!1),r.abandon()},j=()=>{s(!1),p(`configure`),h(void 0),x(void 0)},M=i.state===`submitting`||i.availability===`storage_latched`;return U(`section`,{class:`panel domain-panel`,"aria-labelledby":`grant-actions-title`,"data-testid":`grant-actions`,children:[U(`div`,{class:`panel-heading`,children:U(`div`,{children:U(`h2`,{id:`grant-actions-title`,children:`Delete or replace this grant`})})}),w&&U(K,{state:`neutral`,title:`Replacement shortcut unavailable`,children:U(`p`,{children:`This shortcut does not replace default-shaped grants.`})}),n.state===`expired`&&U(K,{state:`warning`,title:`Expired grant still consumes capacity`,children:U(`p`,{children:`Deletion releases its retained grant slot; expiry does not delete evidence.`})}),i.problem!==void 0&&U(K,{state:`error`,title:_n(i.problem),children:U(`p`,{children:`No later replacement step was submitted.`})}),i.state===`uncertain`&&U(K,{state:`warning`,title:`Grant mutation outcome is unknown`,children:U(`p`,{children:`Do not replay and do not submit the later replacement step. Refresh policy to investigate.`})}),b!==void 0&&U(K,{state:`warning`,title:b}),o?U(`div`,{"data-testid":`grant-correction`,children:[n.readOnly&&U(`p`,{children:`Replacement ALLOW retains read-only server access. Replacement DENY applies to all tools on this server.`}),f===`configure`&&U(S,{children:[U(J,{id:`correction-order`,label:`Replacement order`,children:e=>U(`select`,{...e,"data-testid":`correction-order`,value:c,onChange:e=>l(e.currentTarget.value),children:[U(`option`,{value:`create_first`,children:`Create first`}),U(`option`,{value:`delete_first`,children:`Delete first`})]})}),U(J,{id:`correction-effect`,label:`Replacement effect`,children:e=>U(`select`,{...e,"data-testid":`correction-effect`,value:u,onChange:e=>d(e.currentTarget.value),children:[U(`option`,{value:`allow`,children:`Allow`}),U(`option`,{value:`deny`,children:`Deny`})]})}),U(`p`,{children:`The replacement keeps the same agent and scope, is unconstrained, and is permanent. Use Create grant for any other policy shape.`})]}),U(`div`,{class:`inline-actions`,children:[U(`button`,{ref:C,"data-testid":`grant-correction-step`,type:`button`,disabled:M,onClick:()=>D(f===`create_second`||f===`configure`&&c===`create_first`?`create`:`delete`),children:f===`configure`?`Confirm step one`:`Confirm step two`}),f===`configure`&&U(`button`,{type:`button`,onClick:j,children:`Cancel replacement`})]})]}):U(`div`,{class:`inline-actions`,children:[U(`button`,{ref:C,"data-testid":`grant-delete`,class:`danger-action`,type:`button`,disabled:M,onClick:()=>D(`delete`),children:`Delete grant`}),U(`button`,{class:`danger-action`,"data-testid":`grant-correct`,type:`button`,disabled:M||n.constraint!==null||n.expiresAt!==null||w,onClick:()=>s(!0),children:`Replace grant`})]}),U(jn,{id:`grant-action-confirm`,open:v,title:g===`create`?`Create replacement grant?`:`Delete grant?`,consequence:U(`p`,{children:g===`create`?`This creates one independent immutable policy record. It does not delete or modify the current grant.${n.readOnly?u===`allow`?` The replacement ALLOW retains read-only server access.`:` The replacement DENY applies to all tools on this server.`:``}`:`This permanently removes this policy record. Remaining grants still apply, with matching Deny taking precedence. No replacement or later step is automatic.`}),confirmLabel:g===`create`?`Create replacement`:`Delete grant`,destructive:g===`delete`,returnFocus:C,onCancel:A,onConfirm:()=>void k()})]})}function ws({session:e,mutations:t,resolved:n,view:r}){let i=n.location.segments,a=i[1]===`new`,o=i.length===2&&!a?i[1]:void 0,[s,c]=z(),[l,u]=z(),[d,f]=z(),[p,m]=z();if(B(()=>{if(!a&&o===void 0)return;let t=!0;return Promise.all([Qo(e),_s(e)]).then(([e,n])=>{t&&(u(e),f(n))}).catch(e=>{t&&m(e instanceof Error?e.message:`Grant references are unavailable.`)}),()=>{t=!1}},[r.generation]),B(()=>{let t=!0;return m(void 0),a||o===void 0||o!==void 0&&(c(e=>e?.id===o?e:void 0),ys(e,o).then(e=>{t&&e!==void 0&&c(e)}).catch(e=>{t&&m(e instanceof Error?e.message:`Grant data is unavailable.`)})),()=>{t=!1}},[n.canonicalFragment,r.generation]),a)return p!==void 0&&(l===void 0||d===void 0)?U(K,{state:`error`,title:`Grant options unavailable`,children:U(`p`,{children:p})}):l===void 0||d===void 0?U(K,{state:`loading`,title:`Loading grant options`}):U(xs,{session:e,mutations:t,query:n.location.query,principals:l,servers:d});if(o!==void 0&&p!==void 0)return U(K,{state:`error`,title:`Grant data unavailable`,children:U(`p`,{children:p})});if(o!==void 0){if(s?.id!==o||l===void 0||d===void 0)return U(K,{state:`loading`,title:`Loading grant`});let n=l.find(e=>e.id===s.principalID),r=d.find(e=>e.id===s.serverID);return U(`div`,{class:`domain-view`,"data-testid":`grant-detail`,children:[U(`nav`,{class:`detail-navigation`,"aria-label":`Grant navigation`,children:U(`a`,{href:`#/mcp/grants`,children:`Back to MCP Grants`})}),U(`header`,{class:`detail-context`,"data-testid":`detail-context`,children:[U(`div`,{class:`detail-context-heading`,children:[U(`h1`,{id:`grant-page-title`,tabindex:-1,children:s.description||`Unnamed MCP grant`}),U(G,{state:s.state===`active`?`current`:`neutral`,children:s.state===`active`?`Active`:`Expired`})]}),U(`p`,{class:`technical-value`,children:s.id})]}),U(`section`,{class:`detail-section`,"aria-labelledby":`grant-title`,children:[U(`div`,{class:`panel-heading`,children:U(`h2`,{id:`grant-title`,children:`Grant details`})}),U(`h3`,{children:`Policy and relationships`}),U(`dl`,{class:`detail-facts`,children:[U(`div`,{children:[U(`dt`,{children:`Effect`}),U(`dd`,{children:s.effect===`allow`?`Allow`:`Deny`})]}),U(`div`,{children:[U(`dt`,{children:`Description`}),U(`dd`,{children:s.description??`—`})]}),U(`div`,{children:[U(`dt`,{children:`Agent`}),U(`dd`,{children:U(`a`,{href:`#/agents/${s.principalID}`,children:n?.displayName??`Agent ${s.principalID}`})})]}),U(`div`,{children:[U(`dt`,{children:`Server`}),U(`dd`,{children:s.serverID===`00000000000000000000000000`?`Gateway self-service tools`:U(`a`,{href:`#/mcp/servers/${s.serverID}?tab=tools`,children:r?.displayName??`Server ${s.serverID}`})})]}),U(`div`,{children:[U(`dt`,{children:`Scope`}),U(`dd`,{children:[s.upstreamName===null?s.readOnly?`Entire server — read-only tools`:`Entire server — all tools`:`Exact tool ${s.upstreamName}`,s.readOnly&&U(`p`,{children:`Includes current and future tools marked readOnlyHint=true. The Gateway does not verify that these tools are read-only; they may still change data.`})]})]})]}),U(`h3`,{children:`Timing`}),U(`dl`,{class:`detail-facts`,children:[U(`div`,{children:[U(`dt`,{children:`Expires`}),U(`dd`,{children:U(Y,{value:s.expiresAt,fallback:`No expiry`})})]}),U(`div`,{children:[U(`dt`,{children:`Created`}),U(`dd`,{children:U(Y,{value:s.createdAt})})]})]}),s.constraint!==null&&U(`section`,{class:`detail-group`,"aria-label":`Constraint evidence`,children:[U(`h3`,{children:`Constraint evidence`}),U(yn,{value:s.constraint,label:`Grant constraint`})]})]}),U(Ss,{mutations:t,grant:s,onAcknowledged:c},`${s.id}-${s.revision}`),U(Cs,{session:e,mutations:t,grant:s},s.id)]})}return U(Es,{session:e,resolved:n,view:r})}function Ts(e){return e.upstreamName??(e.readOnly?`Read-only tools`:`All tools`)}function Es({session:e,resolved:t,view:n}){let{items:r,controls:i}=Nr(e,t,n,(t,n,r)=>{let i=new URLSearchParams({limit:`50`,sort:t.sort??`description`,direction:t.direction??`ascending`});for(let e of[`identity`,`principal`,`target`,`server`,`scope`,`effect`,`state`]){let n=t[`filter_${e}`];n!==void 0&&i.set(e,n)}return n!==null&&i.set(`cursor`,n),Mr(e,`/api/v2/mcp/grants?${i}`,e=>{let t=typeof e==`object`&&!!e&&Object.hasOwn(e,`tool_id`),n=ds(e,[`grant`,`principal_display_name`,`server_display_name`,...t?[`tool_id`]:[]]);return{...ms(n.grant),principalDisplayName:fs(n.principal_display_name),serverDisplayName:fs(n.server_display_name),toolID:t?ps(n.tool_id):void 0}},r)},Cr(!1),{key:`description`,direction:`ascending`}),a=new Map(r.map(e=>[e.principalID,e.principalDisplayName]));return U(`div`,{class:`domain-view`,"data-testid":`grants-view`,children:[U(`div`,{class:`collection-toolbar`,children:U(`a`,{class:`button-link create-action`,href:`#/mcp/grants/new`,"data-testid":`grant-create-link`,children:`Create grant`})}),U(`section`,{class:`panel domain-panel`,"aria-labelledby":`page-title`,children:U(Dn,{caption:`Grant policy records`,rowHeaderKey:`description`,initialSort:{key:`description`,direction:`ascending`},additionalSorts:[{key:`id`,label:`Grant ID`,sortValue:e=>e.id},{key:`target`,label:`Server`,sortValue:e=>e.serverDisplayName}],remote:i,itemNames:{singular:`grant`,plural:`grants`},emptyTitle:`No grants`,items:r,rowKey:e=>e.id,rowTestID:`grant-row`,filters:[{key:`identity`,label:`Description or ID`,type:`text`,value:e=>e.description??``,literalValues:e=>[e.id]},{key:`principal`,label:`Agent`,type:`text`,value:e=>a.get(e.principalID)??``,literalValues:e=>[e.principalID]},...t.location.query.filter_target===void 0?[]:[{key:`target`,label:`Server or tool (legacy)`,type:`text`,value:e=>`${e.serverDisplayName} ${e.upstreamName??`Entire server`}`,literalValues:e=>[e.serverID]}],{key:`server`,label:`Server`,type:`text`,value:e=>e.serverDisplayName,literalValues:e=>[e.serverID]},{key:`scope`,label:`Scope`,type:`text`,value:Ts,literalValues:e=>e.toolID?[e.toolID]:[]},{key:`effect`,label:`Effect`,type:`select`,value:e=>e.effect,options:[{value:`allow`,label:`Allow`},{value:`deny`,label:`Deny`}]},{key:`state`,label:`Status`,type:`select`,value:e=>e.state,options:[{value:`active`,label:`Active`},{value:`expired`,label:`Expired`}]}],columns:[{key:`description`,label:`Grant`,role:`identity`,sortValue:e=>e.description??``,render:e=>U(q,{primary:U(`a`,{href:`#/mcp/grants/${e.id}`,children:e.description??`Unnamed grant`}),secondary:e.id})},{key:`principal`,label:`Agent`,role:`relation`,sortValue:e=>a.get(e.principalID)??e.principalID,render:e=>U(q,{primary:U(`a`,{href:`#/agents/${e.principalID}`,children:e.principalDisplayName||e.principalID}),secondary:e.principalID})},{key:`server`,label:`Server`,role:`relation`,sortValue:e=>e.serverDisplayName,render:e=>e.serverID===`00000000000000000000000000`?U(q,{primary:`Gateway self-service tools`,secondary:e.serverID}):U(q,{primary:U(`a`,{href:`#/mcp/servers/${e.serverID}?tab=tools`,children:e.serverDisplayName||e.serverID}),secondary:e.serverID})},{key:`scope`,label:`Scope`,role:`relation`,sortValue:Ts,render:e=>e.toolID&&e.upstreamName!==null&&e.serverID!==`00000000000000000000000000`?U(`a`,{href:`#/mcp/servers/${e.serverID}/descriptors/${e.toolID}`,children:Ts(e)}):Ts(e)},{key:`effect`,label:`Effect`,role:`status`,sortValue:e=>e.effect,render:e=>U(`strong`,{children:e.effect===`allow`?`Allow`:`Deny`})},{key:`state`,label:`Status`,role:`status`,sortValue:e=>e.state,render:e=>U(G,{state:e.state===`active`?`current`:`neutral`,children:e.state===`active`?`Active`:`Expired`})},{key:`constraints`,label:`Conditions`,role:`count`,render:e=>Po(e.constraint)},{key:`expiry`,label:`Expires`,role:`time`,render:e=>U(Y,{value:e.expiresAt,fallback:`No expiry`})}]})})]})}function Ds(e,t){if(typeof e!=`object`||!e||Array.isArray(e)||Object.keys(e).sort().join(`,`)!==t.sort().join(`,`))throw Error(`invalid invocation recognition`);return e}function Os(e,t){if(typeof e!=`string`||!t&&e.length===0||new TextEncoder().encode(e).byteLength>256)throw Error(`invalid invocation recognition`);return e}function ks(e,t){if(typeof e!=`string`||!/^[0-7][0-9A-HJKMNP-TV-Z]{25}$/.test(e)||e!==t)throw Error(`invalid invocation recognition identity`);return e}function As(e,t,n){if(e===void 0)return;let r=Ds(e,[`server`,`grant`]),i=r.server===null?null:Ds(r.server,[`server_id`,`display_name`]),a=r.grant===null?null:Ds(r.grant,[`grant_id`,`description`]);return{server:i===null?null:{serverID:ks(i.server_id,t),displayName:Os(i.display_name,!1)},grant:a===null?null:{grantID:ks(a.grant_id,n),description:Os(a.description,!0)}}}function js(e){return e===`succeeded`?`current`:e===`outcome_unknown`?`warning`:e===`deny`||e===`block`?`neutral`:`error`}function Ms({decision:e}){return U(G,{state:e===`allow`?`current`:`neutral`,children:e===void 0?`Not evaluated`:W(e)})}var Ns=/^[0-7][0-9A-HJKMNP-TV-Z]{25}$/;function Ps(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`invalid response`);let n=e;if(Object.keys(n).sort().join(`,`)!==[...t].sort().join(`,`))throw Error(`invalid response`);return n}function Fs(e){if(typeof e!=`string`)throw Error(`invalid response`);return e}function Is(e){if(e!==null&&typeof e!=`string`)throw Error(`invalid response`);return e}function Ls(e){let t=Fs(e);if(!Ns.test(t))throw Error(`invalid response`);return t}function Rs(e,t){let n=Fs(e);if(!t.includes(n))throw Error(`invalid response`);return n}function zs(e){if(!Array.isArray(e))throw Error(`invalid response`);return e}function Bs(e){let t=Is(e);if(t!==null&&(t.length===0||t.length>512))throw Error(`invalid response`);return t}var Vs={models_result:[`$`,`$.models`,`$.models.[]`,`$.models.[].name`,`$.models.[].description`,`$.models.[].release_date`],evaluate_result:[`$`,`$.model`,`$.answers`,`$.answers.*`,`$.answers.*.type`,`$.answers.*.choice`,`$.answers.*.confidence`,`$.answers.*.probabilities`,`$.answers.*.probabilities.*`,`$.answers.*.score`,`$.answers.*.legend`,`$.answers.*.legend.*`,`$.answers.*.noul`,`$.usage`,`$.usage.input_tokens`,`$.usage.output_tokens`]};function Hs(e){let t=Ps(e,[`schema`,`version`,`violations`,`truncated`]),n=Rs(t.schema,[`models_result`,`evaluate_result`]);if(t.version!==1||typeof t.truncated!=`boolean`||!Array.isArray(t.violations)||t.violations.length<1||t.violations.length>3)throw Error(`invalid response`);let r=t.violations.map(e=>{let t=typeof e==`object`&&!!e&&`code`in e&&e.code===`type`,r=Ps(e,[`code`,`path`,`rule`,...t?[`expected`,`observed`]:[]]),i=Rs(r.code,[`missing`,`type`,`invalid_date`,`correspondence`,`constraint`]),a=Rs(r.path,Vs[n]),o={code:i,path:a,rule:Rs(r.rule,{missing:[`required`],type:[`type`],invalid_date:[`date`],correspondence:[`correspondence`],constraint:[`schema`,`oneOf`,`additionalProperties`,`minLength`,`minItems`,`maxItems`,`minProperties`,`minimum`,`maximum`,`const`,`pattern`]}[i])};if(i===`invalid_date`&&a!==`$.models.[].release_date`||i===`correspondence`&&a!==`$.answers`)throw Error(`invalid response`);if(t){let e=[`null`,`boolean`,`object`,`array`,`number`,`string`,`integer`];o.expected=Rs(r.expected,[...e,`null|string|array|object`]),o.observed=Rs(r.observed,e)}return o}),i=r.map(e=>JSON.stringify(e));if(i.some((e,t)=>t>0&&e<=i[t-1]))throw Error(`invalid response`);return{schema:n,version:1,violations:r,truncated:t.truncated}}function Us(e){switch(e){case`missing`:return`Required field is missing`;case`type`:return`Wrong value type`;case`invalid_date`:return`Invalid release date; expected YYYY-MM-DD or RFC 3339 timestamp`;case`correspondence`:return`Answers do not correspond to the submitted questions`;default:return`Response does not satisfy the schema rule`}}function Ws(e){let t=(e,t,n)=>{let r=[...t];if(typeof e==`object`&&e)for(let t of n)t in e&&r.push(t);return Ps(e,r)},n=t(e,[`gateway_observed`],[`server_reported`]),r=Ps(n.gateway_observed,[`source`,`reason`]),i={gateway_observed:{source:Rs(r.source,[`transport`,`protocol`,`tool`,`result_validation`]),reason:Rs(r.reason,[`prestart`,`handoff_uncertain`,`invalid_response`,`rpc_error`,`reported_error`,`result_shape`])}};if(`server_reported`in n){let e=t(n.server_reported,[`version`,`category`,`phase`],[`http_status`,`retry_after_seconds`,`validation`]);if(e.version!==1&&e.version!==2)throw Error(`invalid response`);i.server_reported={version:e.version,category:Rs(e.category,[`authentication`,`rate_limit`,`timeout`,`canceled`,`transport`,`json_decode`,`response_contract`,`response_limit`,`validation`,`capacity`,`overload`,`redirect_rejected`,`upstream`]),phase:Rs(e.phase,[`admission`,`exchange`,`response_status`,`response_decode`,`response_validation`])};for(let t of[`http_status`,`retry_after_seconds`]){if(!(t in e))continue;let n=e[t],r=t===`http_status`?100:0,a=t===`http_status`?599:86400;if(typeof n!=`number`||!Number.isInteger(n)||na)throw Error(`invalid response`);i.server_reported[t]=n}if(e.version===2){if(e.category!==`response_contract`||e.phase!==`response_validation`||`http_status`in e||`retry_after_seconds`in e||(i.server_reported.validation=Hs(e.validation),JSON.stringify(i.server_reported).length>400))throw Error(`invalid response`)}else if(`validation`in e)throw Error(`invalid response`)}return i}function Gs(e){if(e===null)return null;let t=Ps(e,[`kind`,`server_id`,`tool_id`,`upstream_name`,`descriptor_revision`,`descriptor_fingerprint`]);return{kind:Rs(t.kind,[`downstream`,`gateway`]),serverID:Ls(t.server_id),toolID:Ls(t.tool_id),upstreamName:Fs(t.upstream_name),descriptorRevision:Fs(t.descriptor_revision),descriptorFingerprint:Fs(t.descriptor_fingerprint)}}function Ks(e){if(e===null)return null;let t=Ps(e,[`decision`,`revision`,`evaluated_at`,`grant_id`]),n=Is(t.grant_id);return n!==null&&Ls(n),{decision:Rs(t.decision,[`allow`,`deny`,`block`]),revision:Fs(t.revision),evaluatedAt:Fs(t.evaluated_at),grantID:n}}function qs(e,t=!1){let n=[`id`,`principal_id`,`credential_id`,`credential_fingerprint`,`credential_revision`,`admitted_at`,`admission_class`,`requested_name`,`target`,`authorization`,`outcome`];t&&(n.push(`redacted_arguments`),typeof e==`object`&&e&&`recognition`in e&&n.push(`recognition`),typeof e==`object`&&e&&`diagnostics`in e&&n.push(`diagnostics`));let r=Ps(e,n),i=Ps(r.outcome,[`class`,`basis`,`completed_at`]),a={id:Ls(r.id),principalID:Ls(r.principal_id),credentialID:Ls(r.credential_id),credentialFingerprint:Fs(r.credential_fingerprint),credentialRevision:Fs(r.credential_revision),admittedAt:Fs(r.admitted_at),admissionClass:Rs(r.admission_class,[`invalid_params`,`unknown_tool`,`invalid_arguments`,`authorization_unavailable`,`evaluated`]),requestedName:Is(r.requested_name),target:Gs(r.target),authorization:Ks(r.authorization),outcome:Rs(i.class,[`invalid_params`,`unknown_tool`,`invalid_arguments`,`authorization_unavailable`,`deny`,`block`,`prestart_failure`,`succeeded`,`downstream_failure`,`outcome_unknown`]),basis:Rs(i.basis,[`admission`,`policy`,`terminal`,`missing_terminal`]),completedAt:Is(i.completed_at)};if(t){a.redactedArguments=r.redacted_arguments;let e=As(r.recognition,a.target?.kind===`downstream`?a.target.serverID:void 0,a.authorization?.grantID??void 0);e!==void 0&&(a.recognition=e),`diagnostics`in r&&(a.diagnostics=Ws(r.diagnostics))}return a}function Js(e){let t=Ps(e,[`items`,`next_cursor`]),n=zs(t.items).map(e=>qs(e));if(n.length>50||new Set(n.map(e=>e.id)).size!==n.length||n.length===0&&t.next_cursor!==null)throw Error(`Invalid invocation page`);return{items:n,nextCursor:Bs(t.next_cursor)}}function Ys(e){let t=qs(e,!0);if(!(`redactedArguments`in t))throw Error(`invalid response`);return t}async function Xs(e,t){let n=await fetch(t,{method:`GET`,headers:{"X-CSRF-Token":e.csrfToken},credentials:`same-origin`,redirect:`error`,signal:e.signal});if(await e.sessionLost(n))throw Error(`session lost`);return n}async function Zs(e){if(e.status!==200||e.headers.get(`Content-Type`)!==`application/json`)throw Error(`read failed`);let t=await e.text();if(new TextEncoder().encode(t).byteLength>4194304)throw Error(`response too large`);return JSON.parse(t)}async function Qs(e,t){if(e.status!==t||e.headers.get(`Content-Type`)!==`application/problem+json`)return;let n=await e.text();if(!(new TextEncoder().encode(n).byteLength>65536))try{let e=Ps(JSON.parse(n),[`status`,`code`,`title`]);return e.status!==t||Fs(e.title).length===0?void 0:Fs(e.code)}catch{return}}function $s(e,t){let n=new URLSearchParams({limit:`50`});for(let[t,r]of Object.entries(e))n.set(t.slice(7),r);return(e.filter_tool||e.filter_principal)&&n.set(`search_locale`,Intl.DateTimeFormat().resolvedOptions().locale),t!==null&&n.set(`cursor`,t),`/api/v2/mcp/invocations?${n.toString()}`}var ec=class{views;listeners=new Set;value={viewKey:``,live:!0,paused:!1,successful:!1,refreshError:!1,olderError:!1,notice:void 0,updatesAvailable:!1,items:[],nextCursor:null,item:void 0,missing:!1,loadingOlder:!1};continuation=null;continuationPending=!1;serial=0;continuationSerial=0;constructor(e,t){this.views=t,t.registerPanel({id:`invocations`,matches:e=>H(e)?.destination===`invocations`,invalidations:[`invocations`,`authorization`,`servers`],shouldRefresh:e=>![`invalidation`,`reconnect`,`poll`].includes(e)||H(this.views.snapshot().viewKey)?.segments.length===2||this.value.live&&!this.value.paused,onInvalidation:()=>H(this.views.snapshot().viewKey)?.segments.length===2||this.value.live&&!this.value.paused?!0:(this.value.updatesAvailable||(this.value={...this.value,updatesAvailable:!0},this.emit()),!1),read:e=>this.read(e),publish:e=>this.publish(e)}),e.registerProtectedState(()=>{this.continuation=null,this.continuationPending=!1,this.serial+=1,this.continuationSerial+=1,this.value={viewKey:``,live:!0,paused:!1,successful:!1,refreshError:!1,olderError:!1,notice:void 0,updatesAvailable:!1,items:[],nextCursor:null,item:void 0,missing:!1,loadingOlder:!1},this.emit()})}snapshot(){return this.value}subscribe(e){return this.listeners.add(e),e(this.value),()=>this.listeners.delete(e)}setLive(e){this.views.cancelPanelRead(`invocations`),this.serial+=1,this.continuation=null,this.value={...this.value,live:e,loadingOlder:!1},this.emit(),(!this.value.successful||e&&!this.value.paused)&&(this.continuation=null,this.views.refreshPanel(`invocations`))}resume(){this.serial+=1,this.value={...this.value,paused:!1},this.emit(),this.refresh()}refresh(){this.continuation=null,this.views.refreshPanel(`invocations`)}async loadOlder(){if(this.continuationPending||this.value.items.length>=500||this.value.refreshError||this.value.nextCursor===null||this.views.snapshot().viewKey!==this.value.viewKey||this.views.snapshot().panels.invocations?.refreshing===!0)return;this.serial+=1;let e=++this.continuationSerial;this.continuationPending=!0,this.continuation=this.value.nextCursor,this.value={...this.value,paused:!0,loadingOlder:!0,olderError:!1},this.emit();try{await this.views.refreshPanel(`invocations`)}finally{e===this.continuationSerial&&(this.continuationPending=!1,this.value={...this.value,loadingOlder:!1},this.emit())}}async read(e){let t=H(e.viewKey);if(t?.destination!==`invocations`)throw Error(`Invalid invocation location`);e.viewKey!==this.value.viewKey&&(this.serial+=1,this.continuationSerial+=1,this.continuationPending=!1,this.continuation=null,this.value={viewKey:e.viewKey,live:this.value.live,paused:this.value.paused,successful:!1,refreshError:!1,olderError:!1,notice:this.value.paused&&t.segments.length===1?`Showing the latest entries. Older results could not be continued.`:void 0,updatesAvailable:!1,items:[],nextCursor:null,item:void 0,missing:!1,loadingOlder:!1},this.emit());let n=t.segments[1];if(n!==void 0){let t=await Xs(e,`/api/v2/mcp/invocations/${n}`);return await Qs(t,404)===`not_found`?{kind:`missing`,viewKey:e.viewKey}:{kind:`item`,viewKey:e.viewKey,item:Ys(await Zs(t))}}let r=e.reason===`panel`?this.continuation:null;this.continuation=null;let i=this.serial,a=[`invalidation`,`reconnect`,`poll`].includes(e.reason??`navigation`),o=r!==null;try{let n=await Xs(e,$s(t.query,r));if(o&&await Qs(n,409)===`stale_cursor`){if(e.signal.aborted)throw Error(`Superseded`);o=!1,this.value={...this.value,items:[],nextCursor:null,successful:!1,notice:`Showing the latest entries. Older results could not be continued.`},this.emit(),n=await Xs(e,$s(t.query,null))}let s=Js(await Zs(n));if(o&&(this.value.items.length+s.items.length>500||s.items.some(e=>this.value.items.some(t=>t.id===e.id))))throw Error(`Invalid continuation`);return{kind:`list`,viewKey:e.viewKey,page:s,append:o,automatic:a,serial:i}}catch(t){if(e.signal.aborted)throw t;return{kind:`failure`,viewKey:e.viewKey,append:o,automatic:a,serial:i}}}publish(e){if(!((e.kind===`list`||e.kind===`failure`)&&e.automatic&&(e.serial!==this.serial||!this.value.live||this.value.paused))){if(e.kind===`failure`){this.value={...this.value,loadingOlder:!1,olderError:e.append,refreshError:!e.append},this.emit();return}this.value=e.kind===`missing`?{...this.value,viewKey:e.viewKey,item:void 0,missing:!0}:e.kind===`item`?{...this.value,viewKey:e.viewKey,item:e.item,missing:!1}:{...this.value,viewKey:e.viewKey,items:e.append?[...this.value.items,...e.page.items]:e.page.items,nextCursor:e.page.nextCursor,successful:!0,refreshError:!1,olderError:!1,item:void 0,missing:!1,updatesAvailable:!1},this.emit()}}emit(){for(let e of this.listeners)e(this.value)}};function tc(e,t){return t??(e===null?`Not resolved`:e.kind===`gateway`?`mcp_gateway.${e.upstreamName}`:e.upstreamName)}function nc({item:e,principalNames:t}){return U(S,{children:[U(`h3`,{children:`Authorization and relationships`}),U(`dl`,{class:`detail-facts`,children:[U(`div`,{children:[U(`dt`,{children:`Agent`}),U(`dd`,{children:U(q,{primary:U(`a`,{href:`#/agents/${e.principalID}`,children:t.get(e.principalID)??e.principalID}),secondary:e.principalID})})]}),U(`div`,{children:[U(`dt`,{children:`Tool`}),U(`dd`,{children:U(q,{primary:e.target?.kind===`downstream`?U(`a`,{href:`#/mcp/servers/${e.target.serverID}/descriptors/${e.target.toolID}`,children:tc(e.target,e.requestedName)}):tc(e.target,e.requestedName),secondary:e.target?.kind===`downstream`?e.target.toolID:void 0})})]}),U(`div`,{children:[U(`dt`,{children:`Authorization decision`}),U(`dd`,{children:U(Ms,{decision:e.authorization?.decision})})]}),e.authorization?.grantID!==null&&e.authorization?.grantID!==void 0&&U(`div`,{children:[U(`dt`,{children:`Grant`}),U(`dd`,{children:U(q,{primary:U(`a`,{href:`#/mcp/grants/${e.authorization.grantID}`,children:e.recognition?.grant?e.recognition.grant.description||`Unnamed grant`:e.authorization.grantID}),secondary:e.authorization.grantID})})]}),e.target?.kind===`downstream`&&U(`div`,{children:[U(`dt`,{children:`Server`}),U(`dd`,{children:U(q,{primary:U(`a`,{href:`#/mcp/servers/${e.target.serverID}`,children:e.recognition?.server?.displayName??e.target.serverID}),secondary:e.target.serverID})})]})]}),U(`h3`,{children:`Timing`}),U(`dl`,{class:`detail-facts`,children:[U(`div`,{children:[U(`dt`,{children:`Admitted`}),U(`dd`,{children:U(Y,{value:e.admittedAt})})]}),U(`div`,{children:[U(`dt`,{children:`Completed`}),U(`dd`,{children:U(Y,{value:e.completedAt,fallback:`No terminal timestamp retained`})})]}),U(`div`,{children:[U(`dt`,{children:`Outcome basis`}),U(`dd`,{children:W(e.basis)})]})]}),U(`h3`,{children:`Admission-time credential`}),U(`dl`,{class:`detail-facts`,children:[U(`div`,{children:[U(`dt`,{children:`Credential ID`}),U(`dd`,{class:`technical-value`,children:e.credentialID})]}),U(`div`,{children:[U(`dt`,{children:`Credential revision`}),U(`dd`,{children:e.credentialRevision})]}),U(`div`,{children:[U(`dt`,{children:`Fingerprint`}),U(`dd`,{class:`technical-value`,children:e.credentialFingerprint})]})]})]})}function rc({controller:e,principals:t,view:n,navigate:r}){let[i,a]=z(e.snapshot()),[o,s]=z(t.snapshot());B(()=>e.subscribe(a),[e]),B(()=>t.subscribe(s),[t]);let c=n.panels.invocations,l=H(n.viewKey),u=l?.segments.length===2,d=l?.query??{},f=ln({destination:`invocations`,segments:[`invocations`],query:d}),p=i.viewKey===n.viewKey?i:{...i,items:[],item:void 0,successful:!1,missing:!1,refreshError:!1,olderError:!1,notice:void 0,nextCursor:null};return u?U(S,{children:[U(`nav`,{class:`detail-navigation`,"aria-label":`Invocation navigation`,children:U(`a`,{href:f,children:`Back to MCP Invocations`})}),U(lc,{snapshot:p,panel:c,principalNames:o})]}):U(`div`,{class:`invocations-view`,"data-testid":`invocations-view`,children:U(ic,{snapshot:p,panel:c,query:d,navigate:r,resume:()=>e.resume(),refresh:()=>e.refresh(),setLive:t=>e.setLive(t),loadOlder:()=>void e.loadOlder(),principalNames:o})})}function ic({snapshot:e,panel:t,setLive:n,loadOlder:r,principalNames:i,query:a,navigate:o,resume:s,refresh:c}){return U(`section`,{class:`panel domain-panel`,"aria-label":`Invocations`,children:[U(`div`,{class:`collection-toolbar live-collection-toolbar`,children:[U(`label`,{for:`invocation-live-mode`,children:`Live mode`}),U(On,{attributes:{id:`invocation-live-mode`},checked:e.live,showState:!1,onChange:n}),e.updatesAvailable&&U(G,{state:`warning`,children:`Updates available`})]}),U(oc,{query:a,navigate:o}),e.paused&&U(`div`,{class:`inline-actions`,children:[e.live&&U(G,{state:`warning`,children:`Live paused while viewing older results`}),U(`button`,{type:`button`,onClick:s,children:e.live?`Resume live`:`Return to newest`})]}),e.notice&&U(K,{state:`warning`,title:e.notice}),e.refreshError&&U(K,{state:`error`,title:e.successful?`Refresh failed; shown results are stale`:`Invocation list unavailable`,children:U(`button`,{type:`button`,onClick:c,children:`Retry refresh`})}),!e.successful&&!e.refreshError?U(K,{state:`loading`,title:`Loading invocations`}):e.items.length===0?e.successful&&!e.refreshError&&U(K,{state:`empty`,title:Object.keys(a).length?`No matching invocations`:`No retained invocations`}):U(Dn,{caption:`Invocation history`,layout:`activity`,rowHeaderKey:`tool`,items:e.items,rowKey:e=>e.id,rowTestID:`invocation-row`,columns:[{key:`admitted`,label:`Admitted`,role:`time`,render:e=>U(Y,{value:e.admittedAt})},{key:`tool`,label:`Invocation`,role:`identity`,render:e=>U(q,{primary:U(`a`,{href:ln({destination:`invocations`,segments:[`invocations`,e.id],query:a}),children:tc(e.target,e.requestedName)}),secondary:e.id})},{key:`principal`,label:`Agent`,role:`relation`,render:e=>U(q,{primary:U(`a`,{href:`#/agents/${e.principalID}`,children:i.get(e.principalID)??e.principalID}),secondary:e.principalID})},{key:`decision`,label:`Authorization`,role:`status`,render:e=>U(Ms,{decision:e.authorization?.decision})},{key:`outcome`,label:`Outcome`,role:`status`,render:e=>U(G,{state:js(e.outcome),children:e.outcome===`invalid_params`?`Invalid parameters`:W(e.outcome)})}]}),U(`div`,{class:`history-continuation`,children:[e.successful&&!e.refreshError&&!e.olderError&&U(`span`,{children:e.nextCursor===null?`No older invocations`:e.items.length>=500?`Load limit reached. Narrow the filters or return to newest.`:``}),e.successful&&U(hn,{count:e.items.length,singular:`invocation`,plural:`invocations`,matching:Object.keys(a).length>0,stale:e.refreshError}),e.nextCursor!==null&&e.items.length<500&&!e.refreshError&&U(`div`,{class:`inline-actions`,children:[U(`button`,{type:`button`,onClick:r,disabled:e.loadingOlder||t?.refreshing===!0,children:`Load older invocations`}),e.olderError&&U(`span`,{role:`alert`,children:`Older results unavailable. Loaded rows were retained; use Load older invocations to retry.`})]})]})]})}function ac({name:e,value:t,change:n,reportDraft:r}){let[i,a]=z(t);return xe(()=>a(t),[t]),mn(i,e=>{e!==t&&n(e)}),U(`input`,{type:`search`,"aria-label":e,placeholder:e,value:i,onInput:e=>{a(e.currentTarget.value),r(e.currentTarget.value)}})}function oc({query:e,navigate:t}){let[n,r]=z(),[i,a]=z(0),[o,s]=z({});xe(()=>{s(t=>({...t,tool:e.filter_tool??``}))},[e.filter_tool]),xe(()=>{s(t=>({...t,principal:e.filter_principal??``}))},[e.filter_principal]);let c=e=>{let n=ln({destination:`invocations`,segments:[`invocations`],query:e});if(!H(n)){r(`Filters must fit 256 UTF-8 bytes each and contain no control characters.`);return}r(void 0),t(n)},l=(t,n)=>{let r={...e};n.trim()===``?delete r[`filter_${t}`]:r[`filter_${t}`]=n,c(r)};return U(S,{children:[U(Wn,{query:e}),U(`div`,{class:`table-filters collection-query-filters`,role:`group`,"aria-label":`Invocation history filters`,children:[[`tool`,`principal`].map(t=>U(ac,{name:t===`principal`?`Agent`:W(t),value:e[`filter_${t}`]??``,change:e=>l(t,e),reportDraft:e=>s(n=>({...n,[t]:e}))},`${t}:${i}`)),[`decision`,`outcome`].map(t=>U(`select`,{"aria-label":t===`decision`?`Authorization`:`Outcome`,value:e[`filter_${t}`]??``,onChange:e=>l(t,e.currentTarget.value),children:[U(`option`,{value:``,children:[t===`decision`?`Authorization`:`Outcome`,`: any`]}),dt[t].map(([e,t])=>U(`option`,{value:e,children:t}))]},t)),U(`button`,{type:`button`,disabled:!Object.values(e).some(Boolean)&&!Object.values(o).some(Boolean),onClick:()=>{a(i+1),s({}),c({})},children:`Reset`})]}),n&&U(K,{state:`error`,title:n})]})}function sc({value:e}){let t=typeof e==`object`&&!!e&&!Array.isArray(e)&&Object.keys(e).length===0;return U(`section`,{class:`panel domain-panel argument-capture`,"aria-labelledby":`invocation-argument-capture-title`,"data-testid":`invocation-argument-capture`,children:[U(`div`,{class:`panel-heading`,children:U(`h2`,{id:`invocation-argument-capture-title`,children:[`Captured arguments`,t&&` · Empty`]})}),t?null:e===null?U(`p`,{children:`No argument capture was retained.`}):e===`[TRUNCATED]`?U(`p`,{children:`The redacted capture exceeded 8 KiB; argument content was not retained.`}):U(yn,{value:e,label:`Retained invocation argument capture`})]})}function cc({diagnostics:e}){let t=e.gateway_observed,n=e.server_reported,r=n?.validation;return U(`section`,{class:`panel domain-panel failure-diagnostics`,"aria-labelledby":`failure-diagnostics-title`,"data-testid":`failure-diagnostics`,children:[U(`div`,{class:`panel-heading`,children:[U(`h2`,{id:`failure-diagnostics-title`,children:`Failure diagnostics`}),U(`span`,{class:`diagnostic-source`,children:[`Gateway observed · `,W(t.source),`:`,` `,W(t.reason)]})]}),n&&U(`div`,{class:`diagnostic-report`,"aria-label":`Server reported (unverified)`,children:[U(`div`,{class:`diagnostic-report-heading`,children:[U(`h3`,{children:r?`Response validation failed`:W(n.category)}),U(`span`,{class:`diagnostic-source`,children:`Server reported (unverified)`})]}),r&&U(S,{children:[U(`ul`,{class:`diagnostic-violations`,children:r.violations.map(e=>U(`li`,{children:[U(`strong`,{children:Us(e.code)}),U(`code`,{children:e.path}),e.expected&&U(`span`,{children:[`Expected `,e.expected,`; observed `,e.observed,`.`]})]},`${e.code}:${e.path}:${e.rule}`))}),r.truncated&&U(`p`,{children:`Additional validation violations omitted.`})]}),n.http_status!==void 0&&U(`p`,{children:[`HTTP status: `,n.http_status]}),n.retry_after_seconds!==void 0&&U(`p`,{children:[`Retry guidance: `,n.retry_after_seconds,` seconds`]}),U(`details`,{children:[U(`summary`,{children:`Technical details`}),U(`p`,{children:[W(n.category),` · `,W(n.phase),` `,`· Diagnostic version `,n.version]}),r&&U(S,{children:[U(`p`,{children:[`Schema: `,U(`code`,{children:r.schema}),` v`,r.version]}),U(`ul`,{children:r.violations.map(e=>U(`li`,{children:[U(`code`,{children:e.path}),` · Rule: `,U(`code`,{children:e.rule}),` · Code: `,U(`code`,{children:e.code})]},`${e.code}:${e.path}:${e.rule}`))}),U(`p`,{children:`Array positions and dynamic keys are masked.`})]})]})]}),t.reason!==`prestart`&&U(`p`,{class:`diagnostic-retry`,children:`The tool may have executed. Retrying could duplicate effects.`})]})}function lc({snapshot:e,panel:t,principalNames:n}){if(e.missing)return U(K,{state:`unavailable`,title:`Invocation evidence is no longer retained`,children:U(`p`,{"data-testid":`invocation-missing`,children:`A missing or evicted item does not prove it never existed or never executed. It is not safe-to-retry evidence.`})});if(e.item===void 0)return t?.status===`error`?U(K,{state:`error`,title:`Invocation detail unavailable`}):U(K,{state:`loading`,title:`Loading invocation detail`});let r=e.item;return U(`div`,{class:`domain-view`,"data-testid":`invocation-detail`,children:[U(`header`,{class:`detail-context`,"data-testid":`detail-context`,children:[U(`div`,{class:`detail-context-heading`,children:[U(`h1`,{id:`invocation-page-title`,tabindex:-1,children:tc(r.target,r.requestedName)||`MCP invocation`}),U(G,{state:js(r.outcome),children:r.outcome===`invalid_params`?`Invalid parameters`:W(r.outcome)})]}),U(`p`,{class:`technical-value`,children:r.id})]}),U(`section`,{class:`detail-section`,"aria-labelledby":`invocation-detail-title`,children:[U(`div`,{class:`panel-heading`,children:U(`h2`,{id:`invocation-detail-title`,children:`Invocation details`})}),U(nc,{item:r,principalNames:n}),r.basis===`missing_terminal`&&U(K,{state:`warning`,title:`Audit completion is unknown`,children:[U(`p`,{children:`Missing terminal evidence does not prove nonexecution and is not safe-to-retry evidence. Gateway does not automatically replay invocations; an explicit caller retry can duplicate an effect.`}),r.target?.kind===`gateway`&&U(`p`,{children:`This is a Gateway-owned local target. Missing terminal evidence is not proof of downstream handoff.`})]})]}),r.diagnostics&&U(cc,{diagnostics:r.diagnostics}),U(sc,{value:r.redactedArguments})]})}var uc=`[0-7][0-9A-HJKMNP-TV-Z]{25}`,dc={backup_create:/^\/api\/v2\/backups$/,server_create:/^\/api\/v2\/mcp\/servers$/,operation_start:RegExp(`^/api/v2/mcp/servers/${uc}/operations$`)},fc=[/^PATCH \/api\/v2\/git\/routing-profile$/,RegExp(`^(?:PATCH|DELETE) /api/v2/git/(?:repositories|grants|credentials)/${uc}$`),RegExp(`^POST /api/v2/git/credentials/${uc}/rotate$`),RegExp(`^(?:PATCH|DELETE) /api/v2/http/grants/${uc}$`),RegExp(`^(?:PATCH|DELETE) /api/v2/http/credentials/${uc}$`),RegExp(`^POST /api/v2/http/credentials/${uc}/rotate$`),RegExp(`^PATCH /api/v2/mcp/servers/${uc}$`),RegExp(`^DELETE /api/v2/mcp/servers/${uc}$`),RegExp(`^POST /api/v2/mcp/servers/${uc}/operations$`),RegExp(`^POST /api/v2/mcp/servers/${uc}/credential-replacements$`),RegExp(`^POST /api/v2/mcp/servers/${uc}/oauth-flows$`),RegExp(`^PATCH /api/v2/principals/${uc}$`),RegExp(`^PATCH /api/v2/mcp/grants/${uc}$`),RegExp(`^(?:POST|DELETE) /api/v2/principals/${uc}/credential$`),RegExp(`^POST /api/v2/mcp/grant-requests/${uc}/(?:approve|reject)$`)],pc=/^"[\x21\x23-\x7e]{1,255}"$/,mc=/^\/api\/v2\/[A-Za-z0-9_/-]{1,512}$/,hc=RegExp(`^(?:/api/v2/mcp/servers/${uc}/credential-replacements|/api/v2/(?:http|git)/credentials(?:/${uc}/rotate)?)$`),gc=RegExp(`^/api/v2/mcp/grant-requests/${uc}/approve$`),_c=1048576;function vc(){let e=crypto.getRandomValues(new Uint8Array(16));return`mgw-web-${Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``)}`}function yc(e){try{return JSON.stringify(JSON.parse(e))===e}catch{return!1}}function bc(e){if(e.method!==`POST`||e.body===null||e.route!==`/api/v2/mcp/grants`&&!gc.test(e.route))return!1;try{return JSON.parse(e.body),!0}catch{return!1}}function xc(e){let t=Object.entries(dc).find(([,t])=>t.test(e.route))?.[0],n=fc.some(t=>t.test(`${e.method} ${e.route}`));if(!mc.test(e.route)||e.body!==null&&(new TextEncoder().encode(e.body).byteLength>_c||!yc(e.body)&&!bc(e))||e.requiresPrecondition!==n||n!==(e.precondition!==null)||e.precondition!==null&&!pc.test(e.precondition)||e.successStatuses.length===0||e.successStatuses.some(e=>!Number.isInteger(e)||e<200||e>299)||t!==(e.idempotency===`none`?void 0:e.idempotency)||e.idempotency!==`none`&&(e.method!==`POST`||e.body===null)||e.idempotency===`operation_start`&&e.precondition===null||(e.idempotency===`backup_create`||e.idempotency===`server_create`)&&e.precondition!==null||(e.uncertainProblemCodes?.length??0)!==0&&(!hc.test(e.route)||e.uncertainProblemCodes?.length!==1||e.uncertainProblemCodes[0]!==`keyring_unavailable`))throw Error(`invalid mutation specification`)}function Sc(e){return JSON.stringify([e.route,e.method,e.body,e.precondition,e.idempotency,[...e.successStatuses],[...e.uncertainProblemCodes??[]]])}async function Cc(e){if(e.headers.get(`Content-Type`)!==`application/problem+json`)return;let t;try{t=await e.json()}catch{return}let n=Bn(t);return n?.status===e.status?n:void 0}var wc=class{session;request;refreshCurrent;createKey;controllers=new Set;listeners=new Set;unregisterProtectedState;availability=`enabled`;constructor(e,t={}){this.session=e,this.request=(t.request??fetch).bind(globalThis),this.refreshCurrent=t.refreshCurrent??(()=>{}),this.createKey=t.key??vc,this.unregisterProtectedState=this.session.registerProtectedState(()=>{for(let e of this.controllers)e.resetForEpoch()})}snapshot(){return this.availability}subscribe(e){return this.listeners.add(e),e(this.availability),()=>this.listeners.delete(e)}create(){let e=new Tc(this);return this.controllers.add(e),e}setStorageLatched(e){let t=e?`storage_latched`:`enabled`;if(this.availability!==t){this.availability=t;for(let e of this.listeners)e(t);for(let e of this.controllers)e.availabilityChanged()}}close(){this.unregisterProtectedState();for(let e of[...this.controllers])e.close();this.controllers.clear(),this.listeners.clear()}available(){return this.availability===`enabled`}release(e){this.controllers.delete(e)}key(){let e=this.createKey();if(!/^[\x21-\x7e]{1,128}$/.test(e))throw Error(`invalid idempotency key`);return e}refresh(){this.refreshCurrent()}async execute(e,t){return await this.session.runProtected(async n=>this.requestMutation(n,e,t))??{outcome:{kind:`discarded`},storageLatched:!1}}async requestMutation(e,t,n){let r={"Content-Type":`application/json`,"X-CSRF-Token":e.csrfToken};t.precondition!==null&&(r[`If-Match`]=t.precondition),n!==void 0&&(r[`Idempotency-Key`]=n);let i;try{i=await this.request(t.route,{method:t.method,headers:r,body:t.body,credentials:`same-origin`,redirect:`error`,signal:e.signal})}catch{return{outcome:{kind:`uncertain`,canReplay:n!==void 0},storageLatched:!1}}if(await e.sessionLost(i))return{outcome:{kind:`discarded`},storageLatched:!1};if(t.successStatuses.includes(i.status))try{return{outcome:{kind:`acknowledged`,value:await t.decode(i)},storageLatched:!1}}catch{return{outcome:{kind:`uncertain`,canReplay:n!==void 0},storageLatched:!1}}let a=await Cc(i);return a===void 0||t.uncertainProblemCodes?.includes(a.code)===!0?{outcome:{kind:`uncertain`,canReplay:n!==void 0},storageLatched:!1}:a.code===`storage_unavailable`?{outcome:{kind:`uncertain`,canReplay:n!==void 0},storageLatched:!0}:{outcome:{kind:`rejected`,problem:a,requiresRefresh:i.status===409||i.status===412||i.status===428},storageLatched:!1}}},Tc=class{coordinator;listeners=new Set;state=`editing`;spec;recovery;problem;requiresRefresh=!1;version=0;inFlight;closed=!1;constructor(e){this.coordinator=e}snapshot(){let e={state:this.state,availability:this.coordinator.snapshot(),canReplay:this.state===`uncertain`&&this.recovery!==void 0&&this.coordinator.available(),requiresRefresh:this.requiresRefresh};return this.problem!==void 0&&(e.problem=this.problem),e}subscribe(e){return this.listeners.add(e),e(this.snapshot()),()=>this.listeners.delete(e)}begin(e){if(this.closed)throw Error(`mutation is closed`);if(this.state===`submitting`)throw Error(`mutation is submitting`);let t={...e,successStatuses:[...e.successStatuses],...e.uncertainProblemCodes===void 0?{}:{uncertainProblemCodes:[...e.uncertainProblemCodes]}};xc(t),this.version+=1,this.spec=t,this.recovery=t.idempotency===`none`?void 0:{key:this.coordinator.key(),spec:t,fingerprint:Sc(t)},this.problem=void 0,this.requiresRefresh=!1,this.state=`editing`,this.emit()}confirm(){if(this.state!==`editing`)throw Error(`mutation is not editable`);this.state=`confirming`,this.emit()}submit(){return this.inFlight===void 0?this.spec===void 0||this.state!==`editing`&&this.state!==`confirming`?Promise.resolve({kind:`discarded`}):this.start(!1):this.inFlight}replay(){return this.inFlight===void 0?this.state!==`uncertain`||this.recovery===void 0||!this.coordinator.available()||Sc(this.recovery.spec)!==this.recovery.fingerprint?Promise.resolve({kind:`discarded`}):(this.spec=this.recovery.spec,this.start(!0)):this.inFlight}abandon(){if(this.state===`submitting`)throw Error(`mutation is submitting`);this.version+=1,this.spec=void 0,this.recovery=void 0,this.problem=void 0,this.requiresRefresh=!1,this.state=`editing`,this.emit()}resetForEpoch(){this.closed||(this.version+=1,this.spec=void 0,this.recovery=void 0,this.problem=void 0,this.requiresRefresh=!1,this.state=`editing`,this.inFlight=void 0,this.emit())}availabilityChanged(){this.emit()}close(){this.closed||(this.resetForEpoch(),this.closed=!0,this.listeners.clear(),this.coordinator.release(this))}start(e){if(!this.coordinator.available()||this.spec===void 0)return Promise.resolve({kind:`discarded`});let t=this.version,n=this.spec,r=this.recovery?.key;this.state=`submitting`,this.problem=void 0,this.requiresRefresh=!1,this.emit();let i=this.coordinator.execute(n,r).then(n=>{if(t!==this.version)return{kind:`discarded`};n.storageLatched&&this.coordinator.setStorageLatched(!0);let r=n.outcome;return r.kind===`acknowledged`?(this.state=`acknowledged`,this.spec=void 0,this.recovery=void 0):r.kind===`rejected`?(this.state=`rejected`,this.spec=void 0,this.problem=r.problem,this.requiresRefresh=r.requiresRefresh,this.recovery=void 0,r.requiresRefresh&&this.coordinator.refresh()):r.kind===`uncertain`?(this.state=`uncertain`,r.canReplay||(this.spec=void 0,this.recovery=void 0)):(this.state=`editing`,this.recovery=void 0),e&&r.kind===`uncertain`&&(this.state=`uncertain`),this.emit(),r}).finally(()=>{this.inFlight===i&&(this.inFlight=void 0)});return this.inFlight=i,i}emit(){let e=this.snapshot();for(let t of this.listeners)t(e)}},Ec=/^[0-7][0-9A-HJKMNP-TV-Z]{25}$/,Dc=/^[1-9][0-9]*$/;function Z(){throw Error(`Git data is unavailable.`)}function Oc(e,t,n=[]){if(!e||typeof e!=`object`||Array.isArray(e))return Z();let r=e;return t.some(e=>!Object.hasOwn(r,e))||Object.keys(r).some(e=>!t.includes(e)&&!n.includes(e))?Z():r}function kc(e,t=4096){return typeof e==`string`&&new TextEncoder().encode(e).length<=t&&!/[\p{Cc}\p{Cf}]/u.test(e)}function Ac(e){return typeof e==`string`&&Ec.test(e)}function jc(e){return typeof e==`string`&&Dc.test(e)}function Mc(e){return typeof e==`string`&&Number.isFinite(Date.parse(e))}function Nc(e,t){let n=[`id`,`revision`,`created_at`,`updated_at`],r=e===`repositories`?[`name`,`url`,`aliases`,`credential_id`,`alias_revision`]:e===`credentials`?[`name`,`origin`,`recipe`,`available`,`referencing_repositories`]:[`principal_id`,`repository_id`,`description`,`policy`,`expires_at`,`state`],i=Oc(t,[...n,...r]);if(!Ac(i.id)||!jc(i.revision)||!Mc(i.created_at)||!Mc(i.updated_at)||e!==`grants`&&(!kc(i.name,256)||i.name.length===0))return Z();if(e===`repositories`){if(!kc(i.url)||!i.url.startsWith(`https://`)||!jc(i.alias_revision)||!(i.credential_id===null||Ac(i.credential_id))||!Array.isArray(i.aliases)||i.aliases.length>4||i.aliases.some(e=>!kc(e)||!e.startsWith(`https://`)))return Z()}else if(e===`credentials`){let e=Oc(i.recipe,[`header`,`prefix`]);if(!kc(i.origin)||!i.origin.startsWith(`https://`)||!kc(e.header,128)||!kc(e.prefix,128)||typeof i.available!=`boolean`||!Array.isArray(i.referencing_repositories)||i.referencing_repositories.length>256)return Z();for(let e of i.referencing_repositories)if(!Ac(Oc(e,[`id`]).id))return Z()}else{if(!Ac(i.principal_id)||!Ac(i.repository_id)||!(i.description===null||kc(i.description,1024))||!(i.expires_at===null||Mc(i.expires_at))||![`active`,`expired`].includes(String(i.state)))return Z();let e=Oc(i.policy,[`version`,`read`,`refs`]);if(e.version!==1||typeof e.read!=`boolean`||!Array.isArray(e.refs)||e.refs.length>128||e.refs.length>0&&!e.read)return Z();for(let t of e.refs){let e=Oc(t,[`ref`,`actions`]),n=Oc(e.ref,[`kind`,`value`]);if(![`exact`,`prefix`].includes(String(n.kind))||!kc(n.value,1024)||!Array.isArray(e.actions)||e.actions.length===0||e.actions.length>3||e.actions.some(e=>![`create`,`update`,`delete`].includes(String(e))))return Z()}}return t}function Pc(e,t){return`"git-${e===`repositories`?`repository`:e===`credentials`?`credential`:`grant`}-${t.id}-${t.revision}"`}async function Fc(e,t){if(t.headers.get(`Content-Type`)!==`application/json`)return Z();let n=await t.text();if(n.length>1048576)return Z();let r=Nc(e,JSON.parse(n));return t.headers.get(`ETag`)===Pc(e,r)?r:Z()}function Ic(e,t=!1){let n=Oc(e,[`id`,`revision`]);t&&n.id===``&&n.revision===``||(!Ac(n.id)||!jc(n.revision))&&Z()}function Lc(e){let t=Oc(e,[`items`,`next_cursor`]);if(!Array.isArray(t.items)||t.items.length>50||t.next_cursor!==null&&(typeof t.next_cursor!=`string`||t.next_cursor.length>512||!/^[A-Za-z0-9_-]+$/.test(t.next_cursor)))return Z();let n=t.items.map(Rc);return new Set(n.map(e=>e.admission.id)).size!==n.length||n.length===0&&t.next_cursor!==null?Z():{items:n,nextCursor:t.next_cursor,totalCount:void 0,offset:0}}function Rc(e){let t=Oc(e,[`admission`,`completion`]),n=Oc(t.admission,[`id`,`admitted_at`,`evaluated_at`,`principal`,`agent_credential`,`repository`,`alias_revision`,`profile_revision`,`authorization_revision`,`operation`,`commands`,`allowed`],[`policy`,`material`,`private_grant`,`rejection`,`denial`,`ref_evidence`]);if(!Ac(n.id)||!Mc(n.admitted_at)||!Mc(n.evaluated_at)||!jc(n.profile_revision)||!jc(n.authorization_revision)||typeof n.allowed!=`boolean`||!Number.isInteger(n.commands)||Number(n.commands)<0||Number(n.commands)>128||![`read`,`read_discovery`,`push`,`push_discovery`,`probe`,`invalid`].includes(String(n.operation))||Date.parse(String(n.evaluated_at))0||n.operation===`invalid`!=(n.rejection!==void 0)||(n.rejection!==void 0||n.denial!==void 0)&&n.allowed||n.operation!==`invalid`&&!jc(n.alias_revision)||n.operation===`invalid`&&(n.alias_revision!==``||n.policy!==void 0||n.material!==void 0||n.private_grant!==void 0)||(Ic(n.principal),Ic(n.agent_credential),Ic(n.repository,n.operation===`invalid`),n.rejection!==void 0&&![`unsupported`,`repository_unavailable`,`destination_unavailable`].includes(String(n.rejection)))||n.denial!==void 0&&n.denial!==`credential_unavailable`)return Z();if(n.policy!==void 0){let e=Oc(n.policy,[`repository_name`,`repository_url`,`grants`,`grant_count`,`creates`,`updates`,`deletes`]);if(!kc(e.repository_name,256)||!kc(e.repository_url)||!Array.isArray(e.grants)||e.grants.length>4)return Z();e.grants.forEach(e=>Ic(e));for(let t of[`grant_count`,`creates`,`updates`,`deletes`])if(!Number.isInteger(e[t])||Number(e[t])<0)return Z();if(Number(e.grant_count)4096||Number(e.creates)+Number(e.updates)+Number(e.deletes)!==n.commands||new Set(e.grants.map(e=>e.id)).size!==e.grants.length)return Z()}if(n.ref_evidence!==void 0){let e=Oc(n.ref_evidence,[`state`,`refs`]),t=JSON.stringify(e).replace(/[<>&]/g,e=>`\\u${e.charCodeAt(0).toString(16).padStart(4,`0`)}`);if(n.operation!==`push`||![`complete`,`truncated`].includes(String(e.state))||!Array.isArray(e.refs)||e.refs.length>8||e.refs.length>Number(n.commands)||e.state===`complete`!=(e.refs.length===n.commands)||new TextEncoder().encode(t).length>1536)return Z();let r=new Set,i={create:0,update:0,delete:0};for(let t of e.refs){let e=Oc(t,[`name`,`action`]);if(typeof e.name!=`string`||!Bc(e.name)||r.has(e.name)||![`create`,`update`,`delete`].includes(String(e.action)))return Z();r.add(e.name),i[e.action]++}if(n.policy!==void 0){let e=n.policy;if(i.create>e.creates||i.update>e.updates||i.delete>e.deletes)return Z()}}if(n.material!==void 0){let e=Oc(n.material,[`credential`,`generation`]);if(Ic(e.credential),!jc(e.generation)||!n.allowed)return Z()}if(n.private_grant!==void 0){let e=Oc(n.private_grant,[`id`,`revision`]);if(!Ac(e.id)||!Number.isSafeInteger(e.revision)||Number(e.revision)<1)return Z()}if(t.completion!==null){let e=Oc(t.completion,[`completed_at`,`outcome`,`bytes_sent`,`bytes_received`,`duration_ms`,`transfer_complete`],[`status`,`reported_result`,`failure`,`ref_outcomes`]);if(!n.allowed||!Mc(e.completed_at)||Date.parse(String(e.completed_at))599)||e.transfer_complete&&e.status===void 0||e.outcome===`nonmutation`&&(!e.transfer_complete||n.operation===`push`)||e.outcome===`prestart_failure`&&(e.status!==void 0||e.bytes_sent!==0||e.bytes_received!==0||e.transfer_complete)||e.failure!==void 0&&e.outcome!==`prestart_failure`||e.reported_result!==void 0&&(![`reported_success`,`reported_partial`,`reported_failure`].includes(String(e.reported_result))||n.operation!==`push`||e.status!==200||!e.transfer_complete))return Z();if(e.ref_outcomes!==void 0){let t=n.ref_evidence;if(!t||!Array.isArray(e.ref_outcomes)||e.ref_outcomes.length===0||e.ref_outcomes.length!==t.refs.length||e.reported_result===void 0||e.outcome!==`outcome_unknown`||e.ref_outcomes.some(e=>e!==`ok`&&e!==`ng`))return Z();let r=e.ref_outcomes.filter(e=>e===`ok`).length;if(e.reported_result===`reported_success`&&r!==e.ref_outcomes.length||e.reported_result===`reported_failure`&&r!==0||t.state===`complete`&&e.reported_result===`reported_partial`&&(r===0||r===e.ref_outcomes.length))return Z()}if(e.failure!==void 0&&![`credential_unavailable`,`authorization_unavailable`].includes(String(e.failure)))return Z()}return e}var zc={read:`Read`,read_discovery:`Read discovery`,push:`Push`,push_discovery:`Push discovery`,probe:`Push probe`,invalid:`Unsupported exchange`,unsupported:`Unsupported Git request`,repository_unavailable:`Repository unavailable`,destination_unavailable:`Destination unavailable`,credential_unavailable:`Credential unavailable`,authorization_unavailable:`Authorization unavailable`,reported_success:`Reported success`,reported_failure:`Reported failure`,reported_partial:`Reported partial success`};function Bc(e){return e.length<=1024&&e.startsWith(`refs/`)&&e.split(`/`).length>=3&&!e.includes(`..`)&&!e.includes(`@{`)&&!e.endsWith(`.`)&&!/[\x00-\x20\x7f-\uffff~^:?*\[\\\\]/.test(e)&&e.split(`/`).every(e=>e!==``&&!e.startsWith(`.`)&&!e.endsWith(`.lock`))}function Vc(e){let t=e.admission,n=e.completion;return t.allowed?n?n.outcome===`prestart_failure`||(n.status??0)>=400?`Failed`:n.transfer_complete?t.operation===`push`?n.reported_result?zc[n.reported_result]:`Unknown`:(n.status??0)>=200&&(n.status??0)<300?`HTTP success`:`Unknown`:`Incomplete`:`Unknown`:`Denied`}function Hc(e){let t=e.admission,n=e.completion;return{admission:t.allowed?`Allowed`:zc[t.rejection??t.denial??``]??`Blocked`,transport:t.allowed?n?.outcome===`prestart_failure`?zc[n.failure??``]??`Not started`:n===null?`Unknown`:n.transfer_complete?`Complete`:`Incomplete`:`Not dispatched`,report:t.operation===`push`?n?.reported_result?zc[n.reported_result]:`Unknown`:`Not a push`}}function Uc(e){if(e.length>4096||!/^[\x21-\x7e]+$/.test(e)||!/^https:\/\/[^/?#%@\\\s]+$/.test(e))throw Error(`Enter an HTTPS origin without a path, credentials, query or fragment.`);let t;try{t=new URL(e)}catch{throw Error(`Enter an exact HTTPS host and a valid port.`)}if(!t.hostname||t.port===`0`||t.hostname.includes(`*`))throw Error(`Enter an exact HTTPS host and a valid port.`);return`https://${t.hostname}:${t.port||`443`}`}function Wc(e,t){try{let n=/^https:\/\/([^/?#@%\\\s]+)(\/[A-Za-z0-9._~/-]+)$/.exec(e);if(e.length>4096||!n||n[2].slice(1).split(`/`).some(e=>e===``||e===`.`||e===`..`))return;let r=new URL(e);return t.origins.includes(Uc(`https://${r.host}`))}catch{return}}function Gc(e){if(e.length>256)throw Error(`Use at most 256 origins.`);let t=e.map(Uc).sort();if(new Set(t).size!==t.length)throw Error(`Each HTTPS origin must be unique.`);return t}function Kc(e){let t=Oc(e,[`origins`,`revision`,`active`]);if(typeof t.active!=`boolean`||typeof t.revision!=`string`||!/^[1-9][0-9]*$/.test(t.revision)||BigInt(t.revision)>9223372036854775807n||!Array.isArray(t.origins)||t.origins.some(e=>typeof e!=`string`)||JSON.stringify(Gc(t.origins))!==JSON.stringify(t.origins))throw Error(`Git routing profile is unavailable.`);return e}function qc(e){return`"git-profile-routing-${e.revision}"`}async function Jc(e){if(e.headers.get(`Content-Type`)!==`application/json`)throw Error(`Git routing profile is unavailable.`);let t=await e.text();if(t.length>1048576)throw Error(`Git routing profile is unavailable.`);let n=Kc(JSON.parse(t));if(e.headers.get(`ETag`)!==qc(n))throw Error(`Git routing revision is unavailable.`);return n}function Yc(e,t){if(!e||typeof e!=`object`||Array.isArray(e)||Object.keys(e).sort().join()!==t.sort().join())throw Error(`invalid observation health`);return e}function Xc(e){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<0)throw Error(`invalid observation count`);return e}function Zc(e){if(typeof e!=`boolean`)throw Error(`invalid observation flag`);return e}function Qc(e){if(typeof e!=`string`||e.length>128)throw Error(`invalid observation text`);return e}function $c(e,t){let n=Qc(e);if(!t.includes(n))throw Error(`invalid observation state`);return n}function el(e){let t=Yc(e,[`state`,`bytes`]),n=$c(t.state,[`available`,`absent`,`unavailable`]);if(n===`available`!=(t.bytes!==null))throw Error(`invalid measurement availability`);return{state:n,bytes:t.bytes===null?null:Xc(t.bytes)}}var tl=[`delivery`,`database_measurement`,`wal_measurement`,`free_space_measurement`,`pressure_reason`,`accounting_available`];function nl(e){if(!tl.some(t=>t in e))return;let t=Yc(e.delivery,[`accepted`,`acknowledged`,`discarded`,`queue_records`,`queue_bytes`,`completion_records`,`queue_record_limit`,`queue_byte_limit`]);return{delivery:{accepted:Xc(t.accepted),acknowledged:Xc(t.acknowledged),discarded:Xc(t.discarded),queue_records:Xc(t.queue_records),queue_bytes:Xc(t.queue_bytes),completion_records:Xc(t.completion_records),queue_record_limit:Xc(t.queue_record_limit),queue_byte_limit:Xc(t.queue_byte_limit)},database_measurement:el(e.database_measurement),wal_measurement:el(e.wal_measurement),free_space_measurement:el(e.free_space_measurement),pressure_reason:$c(e.pressure_reason,[`none`,`queue_capacity`,`checkpoint_reader`,`checkpoint_unavailable`,`budget_reservation`,`measurement_unavailable`,`low_space`,`history_unavailable`]),accounting_available:Zc(e.accounting_available)}}var rl=[`health`,`last_acknowledged`,`incident`],il=[`unknown`,`permission`,`ownership`,`missing`,`integrity`,`full`,`io`,`locked`,`deadline`,`capacity`],al=[`opening`,`validation`,`reservation`,`begin`,`statement`,`commit`,`rollback`,`acknowledgment`,`read`],ol=[`healthy`,`degraded`,`recovering`,`operator_action_required`,`recovered`,`disabled`,`opening`,`unavailable`];function sl(e,t=!1){let n=Qc(e);if(t&&n===``)return n;if(!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,9})?Z$/.test(n)||!Number.isFinite(Date.parse(n)))throw Error(`invalid incident timestamp`);return n}function cl(e){if(!rl.some(t=>t in e))return;let t=$c(e.health,ol),n=sl(e.last_acknowledged,!0);if(e.incident===null)return{health:t,lastAcknowledged:n,incident:null};let r=Yc(e.incident,[`first_failure`,`cause`,`stage`,`settlement`,`recovery`,`recovery_cause`,`recovery_stage`,`sqlite_code`,`affected`,`discarded`]),i=Xc(r.sqlite_code);if(i>65535)throw Error(`invalid SQLite code`);return{health:t,lastAcknowledged:n,incident:{firstFailure:sl(r.first_failure),cause:$c(r.cause,il),stage:$c(r.stage,al),recoveryCause:$c(r.recovery_cause,il),recoveryStage:$c(r.recovery_stage,al),settlement:$c(r.settlement,[`not_started`,`rolled_back`,`committed`,`uncertain`]),recovery:$c(r.recovery,[`degraded`,`recovering`,`operator_action_required`,`recovered`]),sqliteCode:i,affected:Xc(r.affected),discarded:Xc(r.discarded)}}}function ll(e){let t=e.incident;return t?t.recovery===`recovered`?`Recording resumed; discarded history was not reconstructed.`:t.recovery===`degraded`?`Validation passed; awaiting a new acknowledged observation.`:t.settlement===`uncertain`&&t.recovery===`recovering`?`Wait for owned settlement and safe validation. Do not replay missing history.`:t.recovery===`recovering`?`Waiting for bounded storage revalidation. Serving remains independent.`:[`permission`,`ownership`].includes(t.recoveryCause)?`Inspect history ownership and permissions; do not change them while serving.`:t.recoveryCause===`integrity`?`Preserve history files; use a separately qualified stopped recovery plan.`:[`full`,`capacity`].includes(t.recoveryCause)?`Inspect disk capacity and the traffic budget. Do not delete live database or WAL files.`:t.recoveryCause===`missing`?`Inspect the selected history generation; do not create a replacement.`:`Inspect filesystem availability. Missing history never authorizes replay.`:``}function ul(e){if(e===void 0)return;let t=Yc(e,[`state`,`epoch`,`accepted`,`written`,`dropped`,`invalid`,`write_failures`,`queue_records`,`queue_bytes`,`queue_limit`,`writing`,`last_successful_write`,`overflow`]);return{state:$c(t.state,[`ready`,`writing`,`pressure`,`failed`,`unavailable`]),epoch:Qc(t.epoch),accepted:Xc(t.accepted),written:Xc(t.written),dropped:Xc(t.dropped),invalid:Xc(t.invalid),write_failures:Xc(t.write_failures),queue_records:Xc(t.queue_records),queue_bytes:Xc(t.queue_bytes),queue_limit:Xc(t.queue_limit),writing:Zc(t.writing),last_successful_write:t.last_successful_write===null?null:Qc(t.last_successful_write),overflow:Zc(t.overflow)}}function dl(e){if(e===void 0)return;let t=Yc(e,[`epoch`,`started_at`,`coverage`,`overflow`,`protocols`]),n=(e,t)=>{if(!Array.isArray(e)||e.length!==t)throw Error(`invalid observation vector`);return e.map(Xc)};if(!Array.isArray(t.protocols)||t.protocols.length!==4)throw Error(`invalid observation protocols`);return{epoch:Qc(t.epoch),started_at:Qc(t.started_at),coverage:$c(t.coverage,[`owner_boundaries`,`unavailable`]),overflow:Zc(t.overflow),protocols:t.protocols.map((e,t)=>{let r=Yc(e,[`protocol`,`requests`,`executions`,`results`,`git_reports`,`latency`]);if(!Array.isArray(r.latency)||r.latency.length!==3)throw Error(`invalid observation stages`);return{protocol:$c(r.protocol,[[`mcp`,`http`,`connect`,`git`][t]]),requests:Xc(r.requests),executions:Xc(r.executions),results:n(r.results,5),git_reports:n(r.git_reports,3),latency:r.latency.map(e=>n(e,6))}})}}function fl(e){return e?.state===`available`?`${e.bytes.toLocaleString()} bytes`:e?.state===`absent`?`Absent`:`Unavailable`}function pl(e){if(e.desired===`enabled`){if(e.runtime===`authentication_required`)return`Authentication required`;if(e.runtime===`degraded`){if(e.reason===`configuration_invalid`)return`Configuration invalid`;if(e.reason===`protocol_unsupported`)return`Protocol unsupported`;if(e.reason===`stop_unconfirmed`)return`Process stop unconfirmed`}if(![`activating`,`retry_wait`,`stopping`].includes(e.runtime)&&[`absent`,`locked`,`interaction_required`,`unavailable`,`unsupported`,`reauthentication_required`,`cleanup_pending`].includes(e.credential))return`Credentials ${e.credential.replaceAll(`_`,` `)}`}}function ml(e,t){let n=e=>t.panels[`overview-${e}`]?.status===`current`,r=[],i=n(`status`)?e.status:void 0;if(i?.latched&&r.push({id:`control-storage`,label:`Control storage recovery required`,explanation:`Changes are blocked. Review the stopped-process recovery procedure in System status.`,href:`#/system`}),i?.traffic?.recovery?.health===`operator_action_required`&&r.push({id:`traffic-recording`,label:`Traffic recording needs attention`,explanation:`Recording requires operator action. Inspect traffic storage recovery in System status.`,href:`#/system`}),n(`servers`)){let t=new Set;for(let n of[...e.servers?.items??[]].sort((e,t)=>e.idt.id))){let e=pl(n);!e||t.has(n.id)||(t.add(n.id),r.push({id:n.id,label:n.name||`MCP server ${n.id}`,explanation:e,href:`#/mcp/servers/${n.id}`}))}}n(`requests`)&&e.requests&&e.requests.total>0&&r.push({id:`pending-requests`,label:`${e.requests.total.toLocaleString()} pending MCP ${e.requests.total===1?`request`:`requests`}`,explanation:`Review pending access requests.`,href:`#/mcp/access-requests`});let a=!!(i?.traffic?.recovery&&n(`servers`)&&e.servers?.complete&&n(`requests`)&&e.requests),o=[`status`,`servers`,`requests`].map(e=>t.panels[`overview-${e}`]);return{items:r,complete:a,notice:a?void 0:o.some(e=>e?.status===`error`)?`Attention data unavailable; list may be incomplete.`:o.some(e=>e?.status===`stale`)?`Attention data stale; current list is unknown.`:o.some(e=>!e||e.status===`loading`)?`Loading attention data…`:`Attention data incomplete; more items may need attention.`}}var hl=/^[0-7][0-9A-HJKMNP-TV-Z]{25}$/,gl=`http_regular.http_control_auth.http_admin.http_health.mcp_work.mcp_streams.admin_sessions.legacy_sessions.event_streams.backup_work.backup_records.admin_credentials.idempotency_records.keyring_candidates.keyring_work.database_bytes.server_identities.servers.downstream_runtimes.server_reconciliations.catalog_traversals.oauth_flows.oauth_callback_work.server_idempotency_records.active_tools.durable_tool_identities.downstream_dispatch.principals.grants.grant_requests.grant_request_evidence_bytes`.split(`.`);function Q(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`invalid response`);let n=e;if(Object.keys(n).sort().join(`,`)!==[...t].sort().join(`,`))throw Error(`invalid response`);return n}function $(e){if(typeof e!=`string`)throw Error(`invalid response`);return e}function _l(e){if(e!==null&&typeof e!=`string`)throw Error(`invalid response`);return e}function vl(e){if(typeof e!=`boolean`)throw Error(`invalid response`);return e}function yl(e){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<0)throw Error(`invalid response`);return e}function bl(e){let t=$(e);if(!hl.test(t))throw Error(`invalid response`);return t}function xl(e){if(!Array.isArray(e))throw Error(`invalid response`);return e}function Sl(e){let t=_l(e);if(t!==null&&(t.length===0||t.length>4096))throw Error(`invalid response`);return t}function Cl(e,t){let n=$(e);if(!t.includes(n))throw Error(`invalid response`);return n}function wl(e,t){let n=Q(e,[`in_use`,`limit`,`saturated`]);return{name:t,inUse:yl(n.in_use),limit:yl(n.limit),saturated:vl(n.saturated)}}function Tl(e){let t=typeof e==`object`&&!!e&&`traffic`in e,n=typeof e==`object`&&!!e&&`http_proxy`in e,r=typeof e==`object`&&!!e&&`endpoints`in e,i=Q(e,[...typeof e==`object`&&e?[`diagnostics`,`observations`].filter(t=>t in e):[],...r?[`endpoints`]:[],...n?[`http_proxy`]:[],...t?[`traffic`]:[],`process`,`sqlite`,`keyring`,`limits`,`backup`,`protocols`]),a;if(r){let e=Q(i.endpoints,[`authority`,`api`,`mcp`]);a={authority:$(e.authority),api:Cl(e.api,[`starting`,`ready`,`read_only`,`draining`]),mcp:Cl(e.mcp,[`starting`,`ready`,`disabled`,`unavailable`,`draining`])}}let o;if(t){let e=i.traffic&&typeof i.traffic==`object`&&`delivery`in i.traffic?tl:[],t=i.traffic&&typeof i.traffic==`object`&&`health`in i.traffic?rl:[],n=Q(i.traffic,[...t,...e,`state`,`ready`,`faulted`,`pressure`,`budget_bytes`,`database_bytes`,`wal_bytes`,`quota_refusals`,`pruned_records`,`generation`,`rolling_history`,`unknown_completion_possible`]);if(!vl(n.rolling_history)||!vl(n.unknown_completion_possible))throw Error(`invalid traffic history semantics`);o={health:nl(n),recovery:cl(n),state:Cl(n.state,[`opening`,`ready`,`unavailable`,`faulted`,`disabled`]),ready:vl(n.ready),faulted:vl(n.faulted),pressure:vl(n.pressure),budgetBytes:yl(n.budget_bytes),databaseBytes:yl(n.database_bytes),walBytes:yl(n.wal_bytes),quotaRefusals:yl(n.quota_refusals),prunedRecords:yl(n.pruned_records),generation:$(n.generation)}}let s;if(n){let e=i.http_proxy,t=typeof e==`object`&&!!e&&`authority`in e,n=Q(e,[`enabled`,`ready`,`ca_ready`,`connections`,`work`,`active_streams`,`active_tunnels`,...t?[`authority`]:[]]);s={enabled:vl(n.enabled),ready:vl(n.ready),caReady:vl(n.ca_ready),...t?{authority:$(n.authority)}:{},connections:wl(n.connections,`http_regular`),work:wl(n.work,`http_regular`),activeStreams:yl(n.active_streams),activeTunnels:yl(n.active_tunnels)}}let c=Q(i.process,[`state`,`ready`,`started_at`]),l=Q(i.sqlite,[`state`,`schema_version`,`revision`,`latched`]),u=Q(i.keyring,[`capability`]),d=Q(i.limits,gl),f=Q(i.backup,[`state`,`last_completed_at`]),p=Q(i.protocols,[`modern`,`legacy`,`agent_auth`]);return{diagnostics:ul(i.diagnostics),observations:dl(i.observations),...a?{endpoints:a}:{},...o?{traffic:o}:{},...s?{httpProxy:s}:{},processState:Cl(c.state,[`uninitialized`,`starting`,`ready`,`storage_failed`,`draining`]),ready:vl(c.ready),startedAt:$(c.started_at),sqliteState:Cl(l.state,[`uninitialized`,`ready`,`latched`]),schemaVersion:$(l.schema_version),revision:$(l.revision),latched:vl(l.latched),keyring:Cl(u.capability,[`ready`,`absent`,`locked`,`interaction_required`,`unavailable`,`unsupported`]),limits:gl.map(e=>wl(d[e],e)),backupState:Cl(f.state,[`idle`,`creating`,`unavailable`]),lastBackupAt:_l(f.last_completed_at),modernProtocol:$(p.modern),legacyProtocol:$(p.legacy),agentAuth:Cl(p.agent_auth,[`deny_all`,`principal_credentials`])}}function El(e){return wl(e,`http_regular`)}function Dl(e){let t=Q(e,Object.keys(e));if(Cl(t.kind,[`stdio`,`streamable_http`])===`stdio`){let t=Q(e,[`kind`,`executable`,`arguments`,`working_directory`,`environment`,`secret_environment`]);$(t.executable),$(t.working_directory),xl(t.arguments).forEach($);for(let e of[t.environment,t.secret_environment]){let t=Q(e,Object.keys(e));Object.values(t).forEach($)}return}let n=Q(e,[`kind`,`url`,`protocol_mode`,`authentication`,...Object.hasOwn(t,`headers`)?[`headers`]:[]]);if(n.headers!==void 0){let e=n.headers;if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`invalid HTTP headers`);let t=Q(e,Object.keys(e));Object.values(t).forEach($)}$(n.url),Cl(n.protocol_mode,[`modern`,`legacy`,`auto`]);let r=Q(n.authentication,Object.keys(n.authentication)),i=Cl(r.mode,[`none`,`bearer`,`oauth`]);if(i===`none`||i===`bearer`){Q(n.authentication,[`mode`]);return}let a=Q(n.authentication,[`mode`,`registration`,`trusted_origins`,`request_offline_access`,...[`callback_uri`,`auth_server_metadata_url`,`scopes`].filter(e=>Object.hasOwn(r,e))]);if(a.callback_uri!==void 0&&$(a.callback_uri),a.auth_server_metadata_url!==void 0&&$(a.auth_server_metadata_url),a.scopes!==void 0&&xl(a.scopes).forEach($),xl(a.trusted_origins).forEach($),vl(a.request_offline_access),Cl(Q(a.registration,Object.keys(a.registration)).mode,[`static`,`dynamic`])===`dynamic`)_l(Q(a.registration,[`mode`,`issuer`]).issuer);else{let e=Q(a.registration,[`mode`,`issuer`,`client_id`,`token_endpoint_auth_method`]);_l(e.issuer),$(e.client_id),$(e.token_endpoint_auth_method)}}function Ol(e){let t=Q(e,[`id`,`namespace`,`display_name`,`desired_state`,`desired_revision`,`transport`,`credential_revisions`,`credential_state`,`runtime`,`catalog`,`created_at`,`updated_at`,`deleted_at`]),n=bl(t.id);$(t.namespace),$(t.desired_revision);let r=Cl(t.desired_state,[`enabled`,`disabled`,`deleted`]);if(r===`deleted`){if(t.transport!==null)throw Error(`invalid response`)}else Dl(t.transport);let i=Q(t.credential_revisions,[`static_credential`,`oauth_client`,`oauth_tokens`]);Object.values(i).forEach($);let a=Cl(t.credential_state,[`not_required`,`ready`,`absent`,`locked`,`interaction_required`,`unavailable`,`unsupported`,`refreshing`,`reauthentication_required`,`disconnecting`,`cleanup_pending`]),o=typeof t.runtime==`object`&&t.runtime!==null&&`diagnostic_correlation`in t.runtime,s=Q(t.runtime,[`state`,`reason`,`runtime_id`,`reconciliation`,`dispatch`,...o?[`diagnostic_correlation`]:[]]);br(s.diagnostic_correlation);let c=Cl(s.state,[`inactive`,`activating`,`active`,`stopping`,`retry_wait`,`degraded`,`authentication_required`,`deleted`]),l=_l(s.reason);_l(s.runtime_id);let u=El(s.reconciliation),d=El(s.dispatch),f=Q(t.catalog,[`durable_state`,`active_state`,`durable_revision`,`active_revision`,`durable_tool_count`,`active_tool_count`,`last_success_at`,`traversal`]);Cl(f.durable_state,[`empty`,`current`,`stale`,`unavailable`,`retired`]);let p=Cl(f.active_state,[`absent`,`refreshing`,`current`,`stale`,`unavailable`]);_l(f.durable_revision),_l(f.active_revision),yl(f.durable_tool_count);let m=yl(f.active_tool_count);_l(f.last_success_at);let h=El(f.traversal);$(t.created_at),$(t.updated_at),_l(t.deleted_at);let g=u.saturated||d.saturated||h.saturated,_=r===`enabled`&&(c!==`active`||a!==`ready`&&a!==`not_required`||p!==`current`||g);return{id:n,name:$(t.display_name),desired:r,runtime:c,reason:l,credential:a,catalog:p,activeToolCount:m,attention:_,saturated:g}}function kl(e){let t=Q(e,[`items`,`next_cursor`]);return{items:xl(t.items).map(Ol),next:Sl(t.next_cursor)}}function Al(e){let t=Q(e,[..._r(e),`scope`,`target`,`constraint`,`duration_seconds`,`future_tools_acknowledged`]);Cl(t.scope,[`tool`,`server`]);let n=$(t.target);if(_l(t.duration_seconds),vl(t.future_tools_acknowledged),vr(t)&&(t.scope!==`server`||t.constraint!==null||t.future_tools_acknowledged!==!0)||t.constraint!==null&&(typeof t.constraint!=`object`||Array.isArray(t.constraint)))throw Error(`invalid response`);return n}function jl(e){let t=Q(e,[`items`,`next_cursor`,`total_count`,`offset`]),n=yl(t.total_count);if(yl(t.offset)!==0)throw Error(`invalid queue offset`);let r=Sl(t.next_cursor),i=xl(t.items).map(e=>{let t=Q(e,[`request`,`principal_display_name`,`server_display_name`,`resolved_server_id`,`resolved_upstream_name`]),n=$(t.principal_display_name),r=$(t.server_display_name);bl(t.resolved_server_id),t.resolved_upstream_name!==null&&$(t.resolved_upstream_name);let i=Q(t.request,[`id`,`principal_id`,`state`,`revision`,`requested_policy`,`approved_policy`,`approved_grant_id`,`rejection_reason`,`created_at`,`updated_at`,`closed_at`]);if(Cl(i.state,[`pending`]),$(i.revision),i.approved_policy!==null||i.approved_grant_id!==null||i.rejection_reason!==null||i.closed_at!==null)throw Error(`invalid response`);return $(i.updated_at),{id:bl(i.id),principalID:bl(i.principal_id),principalName:n,serverName:r,target:Al(i.requested_policy),createdAt:$(i.created_at)}});if(i.length!==Math.min(n,5)||r===null!=(i.length===n)||new Set(i.map(e=>e.id)).size!==i.length)throw Error(`invalid queue coverage`);return{items:i,total:n,complete:r===null}}async function Ml(e){if(e.status!==200||e.headers.get(`Content-Type`)!==`application/json`)throw Error(`read failed`);let t=await e.text();if(new TextEncoder().encode(t).byteLength>4194304)throw Error(`response too large`);return JSON.parse(t)}async function Nl(e,t){let n=await fetch(t,{method:`GET`,headers:{"X-CSRF-Token":e.csrfToken},credentials:`same-origin`,redirect:`error`,signal:e.signal});if(await e.sessionLost(n))throw Error(`session lost`);return n}async function Pl(e){if(e.status!==409||e.headers.get(`Content-Type`)!==`application/problem+json`)return!1;let t=await e.text();if(new TextEncoder().encode(t).byteLength>65536)return!1;let n;try{n=JSON.parse(t)}catch{return!1}try{let e=Q(n,[`status`,`code`,`title`]);return yl(e.status)===409&&$(e.code)===`stale_cursor`&&$(e.title).length>0}catch{return!1}}async function Fl(e){let t=[],n=null,r=!1,i=new Set;for(let a=0;a<32;a+=1){let a=await Nl(e,`/api/v2/mcp/servers?limit=50${n===null?``:`&cursor=${encodeURIComponent(n)}`}`);if(n!==null&&!r&&await Pl(a)){t=[],n=null,r=!0,i.clear();continue}if(a.status!==200){if(t.length>0)return{items:t,complete:!1,restarted:r};throw Error(`server read failed`)}let o=kl(await Ml(a));if(t.push(...o.items.filter(e=>e.desired!==`deleted`)),n=o.next,n===null)return{items:t,complete:!0,restarted:r};if(i.has(n))throw Error(`repeated cursor`);i.add(n)}return{items:t,complete:!1,restarted:r}}var Il=class{views;listeners=new Set;value={};constructor(e,t,n){this.views=t;let r=e=>e===`#/overview`,i=e=>r(e)||e===`#/system?tab=needs-attention`;t.registerPanel({id:`overview-status`,matches:i,invalidations:[`system_status`],read:async e=>Tl(await Ml(await Nl(e,`/api/v2/system-status`))),publish:e=>{this.value={...this.value,status:e},n(e.latched),this.emit()}}),t.registerPanel({id:`overview-servers`,matches:i,invalidations:[`servers`,`catalog`],read:Fl,publish:e=>{this.value={...this.value,servers:e},this.emit()}}),t.registerPanel({id:`overview-requests`,matches:i,invalidations:[`grant_requests`],read:async e=>jl(await Ml(await Nl(e,`/api/v2/mcp/grant-requests?limit=5&state=pending&sort=submitted&direction=ascending`))),publish:e=>{this.value={...this.value,requests:e},this.emit()}}),t.registerPanel({id:`overview-activity`,matches:r,invalidations:[`system_status`,`invocations`],read:async e=>{let t=this.value.window??`1h`,n=Le(await Ml(await Nl(e,`/api/v2/protocol-activity?window=${t}`)));if(n.window!==t)throw Error(`Activity window mismatch`);return n},publish:e=>{this.value={...this.value,activity:e},this.emit()}});for(let[e,n]of Object.entries({httpCredentials:`http/credentials`,httpGrants:`http/grants`,gitCredentials:`git/credentials`,gitRepositories:`git/repositories`,gitGrants:`git/grants`,mcpGrants:`mcp/grants`,routing:`git/routing-profile`}))t.registerPanel({id:`overview-${e}`,matches:r,invalidations:[`authorization`,`http_credentials`,`system_status`],read:async t=>e===`routing`?(await Jc(await Nl(t,`/api/v2/${n}`))).origins.length:ze(await Ml(await Nl(t,`/api/v2/${n}?limit=1`))),publish:t=>{this.value={...this.value,inventory:{...this.value.inventory,[e]:t}},this.emit()}});e.registerProtectedState(()=>{this.value={},n(!1),this.emit()})}setWindow(e){if(!je.includes(e)||e===(this.value.window??`1h`))return;let{activity:t,...n}=this.value;this.value={...n,window:e},this.emit(),this.views.refreshPanel(`overview-activity`)}snapshot(){return this.value}subscribe(e){return this.listeners.add(e),e(this.value),()=>this.listeners.delete(e)}emit(){for(let e of this.listeners)e(this.value)}};function Ll({id:e,title:t,panel:n,children:r}){let i=n?.status??`loading`,a=e===`overview-material`||e===`overview-capacity`;return U(`section`,{class:`panel overview-panel`,"data-testid":e,"data-panel-status":i,"aria-labelledby":`${e}-title`,children:[U(`div`,{class:`panel-heading`,children:[U(`div`,{children:U(`h2`,{id:`${e}-title`,children:t})}),U(G,{state:i===`error`?`error`:i,children:W(i)})]}),n?.hasValue===!0&&i!==`current`&&U(`p`,{class:`overview-evidence`,role:e===`overview-material`||e===`overview-capacity`?void 0:`status`,children:[i===`error`?`Refresh failed.`:`Data stale.`,` Showing the last read; current state is unknown.`]}),i===`error`&&n?.hasValue!==!0?a?U(`p`,{children:`System read unavailable.`}):U(K,{state:`error`,title:`Read unavailable`,children:U(`p`,{children:`Refresh after checking Gateway availability.`})}):i===`loading`&&n?.hasValue!==!0?a?U(`p`,{children:`Loading system data`}):U(K,{state:`loading`,title:`Loading current data`}):r]})}function Rl({label:e,value:t,current:n}){return U(`div`,{children:[U(`dt`,{children:e}),U(`dd`,{children:U(G,{state:!n||t===void 0||t===`disabled`?`neutral`:t===`ready`?`current`:t===`starting`||t===`draining`?`warning`:`unavailable`,children:t===void 0?`Not reported`:W(t)})})]})}function zl({controller:e,view:t,preview:n=!1}){let[r,i]=z(e.snapshot());B(()=>e.subscribe(i),[e]);let{items:a,complete:o,notice:s}=ml(r,t);return U(`section`,{class:`panel ${n?`overview-panel attention-preview`:`attention-detail`}`,"data-testid":`needs-attention`,"aria-labelledby":`needs-attention-title`,children:[U(`h2`,{id:`needs-attention-title`,children:`Needs attention`}),s&&U(`p`,{class:`overview-evidence`,role:`status`,children:s}),o&&a.length===0&&U(`p`,{children:`Nothing needs attention`}),U(`ul`,{class:`attention-list`,"data-testid":`overview-requests`,"data-panel-status":t.panels[`overview-requests`]?.status??`loading`,children:(n?a.slice(0,3):a).map(e=>U(`li`,{children:[U(`a`,{href:e.href,children:e.label}),!n&&U(`p`,{children:e.explanation})]},e.id))}),n&&U(`footer`,{children:[U(`a`,{href:`#/system?tab=needs-attention`,children:`View all`}),o&&a.length>3&&U(`span`,{children:[a.length-3,` more`]})]})]})}function Bl({controller:e,view:t}){let[n,r]=z(e.snapshot());B(()=>e.subscribe(r),[e]);let i=e=>t.panels[e],a=n.status,o=n.servers?.items.length??0,s=n.servers?.items.reduce((e,t)=>e+BigInt(t.activeToolCount),0n)??0,c=e=>i(e)?.status===`current`,l=(e,t,r,a=n.inventory?.[e],o=!0,s=`overview-${e}`)=>U(`div`,{children:[U(`dt`,{children:U(`a`,{href:r,children:t})}),U(`dd`,{children:a===void 0?i(s)?.status===`error`?`Unavailable`:`Loading…`:o?U(S,{children:[a.toLocaleString(),!c(s)&&U(`span`,{class:`overview-evidence`,children:` · stale`})]}):`Incomplete`})]}),u=e=>{let t=n.activity;if(!t)return U(`p`,{children:i(`overview-activity`)?.status===`error`?`Recent activity unavailable`:`Loading recent activity…`});if(!t.counts)return U(`p`,{class:`overview-evidence`,children:`Recent history unavailable`});let r=t.counts[e];return U(`div`,{class:`protocol-activity`,children:[U(`dl`,{class:`overview-facts`,children:U(`div`,{children:[U(`dt`,{children:U(`a`,{href:Re(e,t),children:e===`http`?`Requests`:e===`git`?`Operations`:`Invocations`})}),U(`dd`,{children:r.total.toLocaleString()})]})}),!c(`overview-activity`)&&U(`p`,{class:`overview-context`,children:`Stale; current counts unknown`})]})};return U(`div`,{class:`overview`,"data-testid":`overview-grid`,children:[U(Ll,{id:`overview-status`,title:`Gateway status`,panel:i(`overview-status`),children:a!==void 0&&U(`div`,{class:`overview-stack`,children:[U(`dl`,{class:`overview-facts`,children:[U(Rl,{label:`Process`,value:a.ready?`ready`:a.processState,current:c(`overview-status`)}),U(Rl,{label:`Administration API`,value:a.endpoints?.api,current:c(`overview-status`)}),U(Rl,{label:`MCP ingress`,value:a.endpoints?.mcp,current:c(`overview-status`)}),U(Rl,{label:`HTTP proxy`,value:a.httpProxy?a.httpProxy.enabled?a.httpProxy.ready?`ready`:`not_ready`:`disabled`:void 0,current:c(`overview-status`)})]}),!a.ready&&U(K,{state:`warning`,title:`Process ${W(a.processState).toLowerCase()} · not ready`,children:U(`p`,{children:[`Gateway is not ready to accept work.`,` `,U(`a`,{href:`#/system`,children:`Inspect System`})]})})]})}),U(Ll,{id:`overview-material`,title:`Storage and security`,panel:i(`overview-status`),children:a!==void 0&&U(`div`,{class:`overview-stack`,children:[U(`dl`,{class:`overview-facts`,children:[U(`div`,{children:[U(`dt`,{children:`Control storage`}),U(`dd`,{children:U(vn,{value:a.latched?`recovery_required`:a.sqliteState,current:c(`overview-status`)})})]}),U(`div`,{children:[U(`dt`,{children:`Traffic storage`}),U(`dd`,{children:U(vn,{value:a.traffic?a.traffic.state===`ready`&&a.traffic.pressure?`storage_pressure`:a.traffic.state:void 0,current:c(`overview-status`)})})]}),U(`div`,{children:[U(`dt`,{children:`Credential storage`}),U(`dd`,{children:U(vn,{value:a.keyring,current:c(`overview-status`)})})]}),U(`div`,{children:[U(`dt`,{children:`Interception CA loaded`}),U(`dd`,{children:U(G,{state:c(`overview-status`)?`neutral`:`stale`,children:a.httpProxy?a.httpProxy.caReady?`Yes`:`No`:`Not reported`})})]}),U(`div`,{children:[U(`dt`,{children:`Backup activity`}),U(`dd`,{children:U(vn,{value:a.backupState,current:c(`overview-status`)})})]}),U(`div`,{children:[U(`dt`,{children:`Last backup`}),U(`dd`,{class:`overview-backup-time`,children:U(Y,{value:a.lastBackupAt,fallback:`No completion reported`,compact:!0})})]})]}),(a.latched||a.sqliteState!==`ready`)&&U(K,{state:`error`,title:a.latched?`Recovery required`:`Control storage ${a.sqliteState}`,children:U(`p`,{children:[a.latched?`Changes cannot be saved.`:`Storage is not ready.`,` `,U(`a`,{href:`#/system`,children:`Inspect storage status`})]})}),a.keyring!==`ready`&&U(K,{state:`warning`,title:`Credential storage: ${W(a.keyring).toLowerCase()}`,children:U(`p`,{children:[`Startup capability is not a live credential check.`,` `,U(`a`,{href:`#/system`,children:`Inspect keyring status`})]})})]})}),U(zl,{controller:e,view:t,preview:!0}),U(`div`,{class:`protocol-toolbar`,children:[U(`h2`,{children:`Protocol activity`}),U(`label`,{children:[`Recent activity`,` `,U(`select`,{"aria-label":`Recent activity window`,value:n.window??`1h`,onChange:t=>e.setWindow(t.currentTarget.value),children:je.map(e=>U(`option`,{value:e,children:e},e))})]})]}),U(`section`,{class:`panel overview-panel protocol-card`,"aria-labelledby":`overview-http-title`,children:[U(`h2`,{id:`overview-http-title`,children:`HTTP`}),U(`dl`,{class:`overview-facts protocol-inventory`,children:[l(`httpCredentials`,`Credentials`,`#/http/credentials`),l(`httpGrants`,`Grants`,`#/http/grants`)]}),u(`http`)]}),U(`section`,{class:`panel overview-panel protocol-card`,"aria-labelledby":`overview-git-title`,children:[U(`h2`,{id:`overview-git-title`,children:`Git`}),U(`dl`,{class:`overview-facts protocol-inventory`,children:[l(`routing`,`Routing origins`,`#/git/routing`),l(`gitCredentials`,`Credentials`,`#/git/credentials`),l(`gitRepositories`,`Repositories`,`#/git/repositories`),l(`gitGrants`,`Grants`,`#/git/grants`)]}),u(`git`)]}),U(`section`,{class:`panel overview-panel protocol-card`,"data-testid":`overview-mcp`,"aria-labelledby":`overview-mcp-title`,children:[U(`h2`,{id:`overview-mcp-title`,children:`MCP`}),U(`dl`,{class:`overview-facts protocol-inventory`,"data-testid":`overview-servers`,"data-panel-status":i(`overview-servers`)?.status??`loading`,children:[l(`servers`,`Servers`,`#/mcp/servers`,n.servers?o:void 0,n.servers?.complete,`overview-servers`),l(`tools`,`Tools`,`#/mcp/tools`,n.servers?s:void 0,n.servers?.complete,`overview-servers`),l(`mcpGrants`,`Grants`,`#/mcp/grants`)]}),u(`mcp`)]})]})}function Vl(e){if(!/^https:\/\/[^/?#%@\\\s]+\/[A-Za-z0-9._~/-]+$/.test(e))return e;let t=e.slice(e.indexOf(`/`,8));if(t.slice(1).split(`/`).some(e=>!e||e===`.`||e===`..`))return e;try{let n=new URL(e);return n.port===`0`?e:`https://${n.hostname}:${n.port||`443`}${t}`}catch{return e}}function Hl(e){if(!e)return``;let t=new Date(e);return new Date(t.getTime()-t.getTimezoneOffset()*6e4).toISOString().slice(0,16)}function Ul(e,t){if(e===Hl(t))return t??null;if(!e)return null;let n=Date.parse(e);return Number.isNaN(n)?e:new Date(n).toISOString().replace(/\.000Z$/,`Z`)}function Wl(e){try{let t=new URL(e);if(t.protocol!==`https:`||t.username||t.password||t.search||t.hash||t.pathname===`/`||t.pathname.endsWith(`/`)||/[%?#\\\\]/.test(e)||!t.pathname.slice(1).split(`/`).every(e=>/^[A-Za-z0-9._~-]+$/.test(e)))return null;let n=t.pathname.endsWith(`.git`)?t.pathname.slice(0,-4):`${t.pathname}.git`;return!n||n.endsWith(`/`)?null:(t.pathname=n,t.href)}catch{return null}}function Gl(e,t){let n=e=>{try{return new URL(e).href}catch{return e}},r=t.map(n);return!r.includes(n(e))&&new Set(r).size===r.length}async function Kl(e,t,n,r,i){let a=[],o=null;for(let s=0;sr||s.offset!==a.length)throw Error(`Choices unavailable`);if(a.push(...s.items),a.length>r||new Set(a.map(e=>e.id)).size!==a.length)throw Error(`Invalid choices`);if(s.nextCursor===null)return a;o=s.nextCursor}throw Error(`Choice limit exceeded`)}function ql(e,t,n){let[r,i]=z({generation:-1,agents:[],repositories:[],credentials:[],loading:!0,error:!1});return B(()=>{let r=new AbortController;return i(e=>({...e,loading:!0})),Promise.all([n===`grants`?Kl(e,`/api/v2/principals`,e=>{let t=Jo(e);return{id:t.id,name:t.displayName}},128,r.signal):[],n===`repositories`?[]:Kl(e,`/api/v2/git/repositories`,e=>Nc(`repositories`,e),256,r.signal),n===`repositories`?Kl(e,`/api/v2/git/credentials`,e=>Nc(`credentials`,e),256,r.signal):[]]).then(([e,n,a])=>{r.signal.aborted||i({generation:t,agents:e,repositories:n,credentials:a,loading:!1,error:!1})}).catch(()=>{r.signal.aborted||i(e=>({...e,generation:t,loading:!1,error:!0}))}),()=>r.abort()},[e,t,n]),r.generation===t?r:{...r,loading:!0}}function Jl(e,t){return`${e.name||`Unnamed resource`}${t.filter(t=>t.name===e.name).length>1?` · ${e.id}`:``}`}function Yl(e,t){try{return e.available===!0&&e.origin!==void 0&&new URL(t).origin===new URL(e.origin).origin}catch{return!1}}function Xl(e,t,n){let[r,i]=z({generation:-1,loading:!0,error:!1});return B(()=>{if(!n)return;let r=!0;return e.runProtected(async e=>{let n=await fetch(`/api/v2/git/routing-profile`,{credentials:`same-origin`,redirect:`error`,signal:e.signal,headers:{Accept:`application/json`,"X-CSRF-Token":e.csrfToken}});if(await e.sessionLost(n))return;if(!n.ok)throw Error(`Routing unavailable`);let a=await Jc(n);r&&i({generation:t,profile:a,loading:!1,error:!1})}).catch(()=>{r&&i(e=>({...e,generation:t,loading:!1,error:!0}))}),()=>{r=!1}},[e,t,n]),n&&r.generation===t?r:{...r,loading:!0}}function Zl({source:e,destination:t,contextual:n=!1}){let r=`neutral`,i;if(e.loading)r=`loading`,i=`Checking routing`;else if(e.error||!e.profile)r=e.profile?`stale`:`warning`,i=e.profile?`Routing stale`:`Routing unknown`;else if(!e.profile.active)i=`Routing inactive`;else{let a=Wc(t,e.profile);if(a===void 0)r=`warning`,i=`Routing unknown`;else if(a){if(!n)return null;i=`Origin enabled`}else r=`warning`,i=`Not routed`}return U(`div`,{class:`git-routing-coverage`,children:[U(G,{state:r,children:i}),n&&U(`p`,{children:[i===`Not routed`?`Repository origin is not enabled in Git routing. `:``,U(`a`,{href:`#/git/routing`,children:`Git routing`}),` · Coverage does not establish grants, credential readiness or access.`]})]})}var Ql=e=>e===`repositories`?`repository`:e===`credentials`?`credential`:`grant`,$l=e=>e.name??e.description??`Unnamed Git grant`;function eu(e,t,n){let[r,i]=z(),[a,o]=z(!1),[s,c]=z(!1);return B(()=>{let r=!0;if(o(!1),c(t!==void 0),t!==void 0)return e.session.runProtected(async e=>{let a=await fetch(t,{credentials:`same-origin`,redirect:`error`,signal:e.signal,headers:{Accept:`application/json`,"X-CSRF-Token":e.csrfToken}});if(await e.sessionLost(a))return;if(!a.ok)throw Error(`Read unavailable`);let o=await n(a);r&&(i(o),c(!1))}).catch(()=>{r&&(o(!0),c(!1))}),()=>{r=!1}},[t,e.view.generation]),{value:r,error:a,loading:s}}function tu(e){let{kind:t}=e,n=e.resolved.location.segments[1],r=ql(e.session,e.view.generation,t),i=Xl(e.session,e.view.generation,t===`repositories`&&e.view.viewKey===e.resolved.canonicalFragment),[a,o]=z(),{value:s,error:c,loading:l}=eu(e,n&&n!==`new`?`/api/v2/git/${t}/${n}`:void 0,async e=>{let r=await Fc(t,e);if(r.id!==n)throw Error(`Identity unavailable`);return r});return n===void 0?U(ru,{...e,choices:r,coverage:i}):n===`new`?U(ou,{...e,choices:r,coverage:i,mode:`create`}):s?U(`div`,{class:`domain-view`,children:[U(`nav`,{class:`detail-navigation`,"aria-label":`Git resource navigation`,children:U(`a`,{href:ln({...e.resolved.location,segments:[e.resolved.location.destination]}),children:[`Back to Git `,t]})}),U(`header`,{class:`detail-context`,"data-testid":`detail-context`,children:[U(`div`,{class:`detail-context-heading`,children:[U(`h1`,{tabindex:-1,children:$l(s)}),t===`credentials`?U(G,{state:c?`stale`:s.available?`current`:`warning`,children:s.available?`Configured`:`Unavailable`}):t===`grants`?U(G,{state:c?`stale`:s.state===`active`?`current`:`neutral`,children:s.state===`active`?`Active`:`Expired`}):null]}),U(`p`,{class:`technical-value`,children:s.id})]}),c&&U(K,{state:`error`,title:`Git resource refresh unavailable`,children:`Saved facts may be stale. Refresh before making changes.`}),U(`section`,{class:`detail-section`,children:[U(`h2`,{children:`${Ql(t)[0].toUpperCase()}${Ql(t).slice(1)} details`}),U(`dl`,{class:`detail-facts`,children:[t===`repositories`&&U(S,{children:[U(`div`,{children:[U(`dt`,{children:`Canonical destination`}),U(`dd`,{children:s.url})]}),U(`div`,{children:[U(`dt`,{children:`Origin enabled`}),U(`dd`,{children:i.loading||i.error||!i.profile||Wc(s.url,i.profile)===void 0?`Unavailable`:i.profile.active&&Wc(s.url,i.profile)?`Yes`:`No`})]}),U(`div`,{children:[U(`dt`,{children:`Explicit aliases`}),U(`dd`,{children:s.aliases?.length?s.aliases.map(e=>U(`p`,{children:e},e)):`None`})]}),U(`div`,{children:[U(`dt`,{children:`Git credential`}),U(`dd`,{children:s.credential_id?U(nu,{id:s.credential_id,kind:`credentials`,choices:r}):`None`})]})]}),t===`grants`&&U(S,{children:[U(`div`,{children:[U(`dt`,{children:`Agent`}),U(`dd`,{children:U(nu,{id:s.principal_id,kind:`agents`,choices:r})})]}),U(`div`,{children:[U(`dt`,{children:`Repository`}),U(`dd`,{children:U(nu,{id:s.repository_id,kind:`repositories`,choices:r})})]}),U(`div`,{children:[U(`dt`,{children:`Read`}),U(`dd`,{children:s.policy?.read?`Allowed`:`Blocked`})]}),U(`div`,{children:[U(`dt`,{children:`Expires`}),U(`dd`,{children:U(Y,{value:s.expires_at,fallback:`No expiry`})})]})]}),t===`credentials`&&U(S,{children:[U(`div`,{children:[U(`dt`,{children:`HTTPS origin`}),U(`dd`,{children:s.origin})]}),U(`div`,{children:[U(`dt`,{children:`Header recipe`}),U(`dd`,{children:[s.recipe?.header,`: `,s.recipe?.prefix,`[secret]`]})]}),U(`div`,{children:[U(`dt`,{children:`Referencing repositories`}),U(`dd`,{children:s.referencing_repositories?.length?s.referencing_repositories.map(e=>U(`p`,{children:U(nu,{id:e.id,kind:`repositories`,choices:r})},e.id)):`None`})]})]})]}),t===`grants`&&(s.policy?.refs.length?U(`ul`,{children:s.policy?.refs.map(e=>U(`li`,{children:[U(`span`,{class:`technical-value`,children:e.ref.value}),` (`,e.ref.kind,`): `,e.actions.join(`, `)]},`${e.ref.kind}:${e.ref.value}`))}):U(`p`,{children:`No push permissions`})),U(`h3`,{children:`Metadata`}),U(`dl`,{class:`detail-facts`,children:U(`div`,{children:[U(`dt`,{children:`Revision`}),U(`dd`,{children:s.revision})]})})]}),U(ou,{...e,choices:r,resource:s,mode:`edit`,unavailable:c||l,acknowledgment:a,onAcknowledged:o}),t===`credentials`&&U(ou,{...e,choices:r,resource:s,mode:`rotate`,unavailable:c||l,acknowledgment:a,onAcknowledged:o}),U(ou,{...e,choices:r,resource:s,mode:`delete`,unavailable:c||l,acknowledgment:a})]}):U(K,{state:c?`error`:`loading`,title:c?`Git resource unavailable`:`Loading Git resource`})}function nu({id:e,kind:t,choices:n}){let r=n[t].find(t=>t.id===e)?.name;return U(q,{primary:U(`a`,{href:t===`agents`?`#/agents/${e}`:`#/git/${t}/${e}`,children:[r||(n.loading?`Loading relationship`:`Resource unavailable`),r&&n.error?` · Last known`:``]}),secondary:e})}function ru(e){let t=Cr(!1),{kind:n}=e,{items:r,controls:i}=Nr(e.session,e.resolved,e.view,(t,r,i)=>{let a=new URLSearchParams({limit:`50`,sort:t.sort??(n===`grants`?`description`:`name`),direction:t.direction??`ascending`});for(let e of n===`repositories`?[`name`,`destination`,`credential`]:n===`credentials`?[`name`,`origin`,`status`]:[`identity`,`repository`,`principal`,`state`]){let n=t[`filter_${e}`];n!==void 0&&a.set(e,n)}return r!==null&&a.set(`cursor`,r),Mr(e.session,`/api/v2/git/${n}?${a}`,e=>Nc(n,e),i)},t,{key:n===`grants`?`description`:`name`,direction:`ascending`});return U(`div`,{class:`domain-view`,children:[U(`div`,{class:`collection-toolbar`,children:U(`a`,{class:`button-link create-action`,href:`#/git/${n}/new`,children:[`Create `,Ql(n)]})}),U(`section`,{class:`panel domain-panel`,children:U(Dn,{caption:`Git ${n}`,rowHeaderKey:n===`grants`?`description`:`name`,remote:i,itemNames:{singular:Ql(n),plural:n},emptyTitle:`No Git ${n}`,items:r,rowKey:e=>e.id,filters:[{key:n===`grants`?`identity`:`name`,label:n===`grants`?`Description or ID`:`Name or ID`,type:`text`,value:e=>e.name??e.description??``,literalValues:e=>[e.id]},...n===`grants`?[{key:`repository`,label:`Repository`,type:`text`,value:t=>e.choices.repositories.find(e=>e.id===t.repository_id)?.name??``,literalValues:e=>[e.repository_id]},{key:`principal`,label:`Agent`,type:`text`,value:t=>e.choices.agents.find(e=>e.id===t.principal_id)?.name??``,literalValues:e=>[e.principal_id]},{key:`state`,label:`Status`,type:`select`,value:e=>e.state,options:[{value:`active`,label:`Active`},{value:`expired`,label:`Expired`}]}]:n===`repositories`?[{key:`destination`,label:`Destination`,type:`text`,value:e=>e.url,placeholder:`Literal destination substring`},{key:`credential`,label:`Git credential`,type:`text`,value:t=>e.choices.credentials.find(e=>e.id===t.credential_id)?.name??``,literalValues:e=>[e.credential_id??``]}]:[{key:`origin`,label:`HTTPS origin`,type:`text`,value:e=>e.origin,placeholder:`Destination`},{key:`status`,label:`Status`,type:`select`,value:e=>e.available?`configured`:`unavailable`,options:[{value:`configured`,label:`Configured`},{value:`unavailable`,label:`Unavailable`}]}]],additionalSorts:[{key:`id`,label:`ID`,sortValue:e=>e.id}],initialSort:{key:n===`grants`?`description`:`name`,direction:`ascending`},columns:[{key:n===`grants`?`description`:`name`,sortValue:e=>$l(e),label:n===`repositories`?`Repository`:n===`credentials`?`Credential`:`Grant`,role:`identity`,render:t=>U(q,{primary:U(`a`,{href:ln({...e.resolved.location,segments:[e.resolved.location.destination,t.id]}),children:$l(t)}),secondary:t.id})},{key:n===`grants`?`repository`:n===`credentials`?`origin`:`destination`,sortValue:t=>t.url??t.origin??e.choices.repositories.find(e=>e.id===t.repository_id)?.name??t.repository_id,label:n===`grants`?`Repository`:`Destination`,role:`relation`,render:t=>n===`grants`?U(nu,{id:t.repository_id,kind:`repositories`,choices:e.choices}):U(S,{children:[t.url??t.origin,n===`repositories`&&U(Zl,{source:e.coverage,destination:t.url})]})},...n===`grants`?[{key:`principal`,sortValue:t=>e.choices.agents.find(e=>e.id===t.principal_id)?.name??t.principal_id,label:`Agent`,role:`relation`,render:t=>U(nu,{id:t.principal_id,kind:`agents`,choices:e.choices})}]:[],{key:n===`repositories`?`credential`:n===`grants`?`state`:`status`,sortValue:t=>n===`repositories`?e.choices.credentials.find(e=>e.id===t.credential_id)?.name??t.credential_id??``:n===`grants`?t.state:t.available?`configured`:`unavailable`,label:n===`repositories`?`Git credential`:`Status`,role:n===`repositories`?`relation`:`status`,render:t=>n===`repositories`?t.credential_id?U(nu,{id:t.credential_id,kind:`credentials`,choices:e.choices}):`None`:U(G,{state:n===`credentials`?t.available?`current`:`warning`:t.state===`active`?`current`:`neutral`,children:n===`credentials`?t.available?`Configured`:`Unavailable`:t.state===`active`?`Active`:`Expired`})}]})})]})}function iu(e){return{name:e?.name??``,url:e?.url??``,aliases:e?.aliases??[],credential:e?.credential_id??``,principal:e?.principal_id??``,repository:e?.repository_id??``,description:e?.description??``,read:e?.policy?.read??!0,refs:e?.policy?.refs??[],expires:e?.expires_at??``,origin:e?.origin??``,header:e?.recipe?.header??`Authorization`,prefix:e?.recipe?.prefix??`Bearer `}}function au(e){return JSON.stringify({...e,url:Vl(e.url),aliases:e.aliases.map(Vl).sort(),origin:Vl(`${e.origin}/repository`).replace(/\/repository$/,``),header:e.header.toLowerCase(),refs:e.refs.map(e=>({...e,actions:[...e.actions].sort()})).sort((e,t)=>`${e.ref.kind}:${e.ref.value}`.localeCompare(`${t.ref.kind}:${t.ref.value}`))})}function ou({kind:e,choices:t,resource:n,mode:r,unavailable:i=!1,coverage:a,acknowledgment:o,onAcknowledged:s,...c}){let[l,u]=z(()=>iu(n)),[d,f]=z(()=>iu(n)),[p,m]=z(!1),h=r===`create`||r===`edit`,g=e===`credentials`&&(r===`create`||r===`rotate`),_=h&&au(d)!==au(l)||p,v=V(!1),[y,b]=z(n?Pc(e,n):null),[x,C]=z(!1),[w,T]=z(),[E]=z(()=>c.sinks.createWriteOnly()),[D]=z(()=>c.mutations.create()),[O,k]=z(()=>D.snapshot()),A=V(null),j=Cr(_),M=`git-secret-${r}`;B(()=>D.subscribe(k),[D]),B(()=>()=>{D.close(),E.close()},[D,E]);let N=n!==void 0&&y!==Pc(e,n),ee=V(),P=r===`delete`&&e===`credentials`&&(n?.referencing_repositories?.length??0)>0,te=P||i||N||O.state===`submitting`||O.state===`uncertain`||O.availability===`storage_latched`;B(()=>{if(!(!n||i||!o||o.to!==Pc(e,n)||ee.current===o.to)&&(ee.current=o.to,!_&&!x&&O.state===`editing`&&o.from===y)){b(o.to);let e=iu(n);u(e),f(e)}},[n,i,_,x,O.state,o,y,e]);let F=()=>{E.clear(),m(!1)},ne=r===`rotate`?`Rotate secret`:`${r===`create`?`Create Git`:r===`edit`?`Edit`:`Delete`} ${Ql(e)}`,I=(t,n)=>{t===`aliases`&&(v.current=!0),f(i=>{if(t===`url`&&e===`repositories`&&r===`create`&&!v.current){let e=Wl(String(n));return{...i,url:String(n),aliases:e?[e]:[]}}return{...i,[t]:n}})},re=(e,t,n=!0,i=!1,a,o)=>U(J,{id:`git-${e}-${r}`,label:t,...o===void 0?{}:{hint:o},children:t=>U(`input`,{...t,required:n,readOnly:i,placeholder:a,value:d[e],onInput:t=>I(e,t.currentTarget.value)})}),ie=()=>e===`repositories`?{name:d.name,url:d.url,aliases:d.aliases,credential_id:d.credential||null}:e===`credentials`?{name:d.name,origin:d.origin,recipe:{header:d.header,prefix:d.prefix}}:{principal_id:d.principal,repository_id:d.repository,description:d.description||null,policy:{version:1,read:d.read,refs:d.refs},expires_at:d.expires||null},ae=()=>{if(h){if(e!==`grants`&&(d.name.trim()===``||new TextEncoder().encode(d.name).length>256))return`Enter a name of at most 256 bytes.`;if(e===`repositories`&&(!d.url.startsWith(`https://`)||d.aliases.some(e=>!e.startsWith(`https://`))||d.credential!==``&&!Ec.test(d.credential)))return`Use HTTPS destinations and a valid optional Git credential ID.`;if(e===`repositories`&&!Gl(d.url,d.aliases))return`Aliases must be distinct from each other and the canonical destination.`;if(e===`grants`&&(!Ec.test(d.principal)||!Ec.test(d.repository)))return`Enter valid agent and repository IDs.`;if((e===`repositories`||e===`grants`&&r===`create`)&&(t.loading||t.error))return`Refresh resource choices before reviewing.`;if(e===`repositories`&&d.credential!==``&&!t.credentials.some(e=>e.id===d.credential&&Yl(e,d.url)))return`Select an available credential for this HTTPS origin, or choose None.`;if(e===`grants`&&r===`create`&&(!t.agents.some(e=>e.id===d.principal)||!t.repositories.some(e=>e.id===d.repository)))return`Select an existing agent and repository.`;if(e===`grants`&&d.refs.length>0&&!d.read)return`Push permissions require read access.`;if(e===`grants`&&d.refs.some(e=>!e.ref.value.startsWith(`refs/`)||e.actions.length===0))return`Each ref rule needs a refs/ selector and at least one operation.`}if(g){let e=document.getElementById(M);if(!(e instanceof HTMLInputElement)||!e.value||!/^[\x20-\x7e]+$/.test(e.value)||e.value.length+d.prefix.length>4096)return`Enter a nonempty printable secret; secret and prefix must fit 4096 characters.`}},oe=()=>{if(te||r===`edit`&&!_)return;let e=ae();T(e),e?F():C(!0)},se=()=>{if(C(!1),te){F(),T(`Current facts changed or are unavailable. Review them before confirming a new action.`);return}let t=ae();if(t){T(t),F();return}let i=document.getElementById(M),a=i instanceof HTMLInputElement?i.value:``,o=r===`rotate`?{secret:a}:r===`delete`?{}:g?{...ie(),secret:a}:ie();try{D.begin({route:`/api/v2/git/${e}${n?`/${n.id}`:``}${r===`rotate`?`/rotate`:``}`,method:r===`delete`?`DELETE`:r===`edit`?`PATCH`:`POST`,body:r===`delete`&&e!==`credentials`?null:JSON.stringify(o),precondition:y,requiresPrecondition:n!==void 0,idempotency:`none`,successStatuses:[r===`create`?201:r===`delete`?204:200],...g?{uncertainProblemCodes:[`keyring_unavailable`]}:{},decode:async t=>r===`delete`?null:Fc(e,t)});let t=D.submit();F(),t.then(t=>{if(t.kind===`acknowledged`){if(D.abandon(),r===`delete`)j(`#/git/${e}`,!0);else if(r===`create`&&t.value)j(`#/git/${e}/${t.value.id}`,!0);else{if(t.value){let n=Pc(e,t.value);y&&s?.({from:y,to:n}),b(n);let r=iu(t.value);u(r),f(r)}c.onRefresh()}}else(t.kind===`uncertain`||t.kind===`rejected`&&t.requiresRefresh)&&c.onRefresh()})}catch{F(),T(`Change could not be prepared. Refresh and review current metadata before making a new decision.`)}};return U(`section`,{class:`panel domain-panel`,children:[U(`div`,{class:`panel-heading`,children:U(`h2`,{children:r===`create`?`${e===`repositories`?`Repository`:e===`grants`?`Grant`:`Credential`} configuration`:ne})}),U(`form`,{onSubmit:e=>{e.preventDefault(),oe()},children:U(`fieldset`,{class:`git-mutation-fields`,disabled:O.state===`submitting`||O.state===`uncertain`,children:[h&&e!==`grants`&&re(`name`,`Name`,!0,!1,e===`repositories`?`Project repository`:`Project Git credential`),h&&e===`repositories`&&U(S,{children:[re(`url`,`Canonical HTTPS destination`,!0,n!==void 0,`https://git.example.com/team/project`),U(`section`,{class:`git-list-editor`,"aria-label":`Repository aliases`,children:[U(`h3`,{children:`Aliases`}),d.aliases.map((e,t)=>U(`div`,{class:`form-row`,children:[U(J,{id:`git-alias-${t}`,label:`Alias ${t+1}`,children:n=>U(`input`,{...n,required:!0,placeholder:`Same destination with .git added or removed`,value:e,onInput:e=>I(`aliases`,d.aliases.map((n,r)=>t===r?e.currentTarget.value:n))})}),U(`button`,{type:`button`,onClick:()=>I(`aliases`,d.aliases.filter((e,n)=>t!==n)),children:[`Remove alias `,t+1]})]},t)),U(`button`,{type:`button`,disabled:d.aliases.length>=4,onClick:()=>I(`aliases`,[...d.aliases,``]),children:`Add alias`})]}),U(J,{id:`git-credential-${r}`,label:`Git credential`,...d.credential?{hint:d.credential}:{},children:e=>U(`select`,{...e,value:d.credential,onChange:e=>I(`credential`,e.currentTarget.value),children:[U(`option`,{value:``,children:`None — public repository`}),d.credential&&!t.credentials.some(e=>e.id===d.credential&&Yl(e,d.url))&&U(`option`,{value:d.credential,disabled:!0,children:[t.credentials.find(e=>e.id===d.credential)?.name||d.credential,` `,`· Unavailable or incompatible`]}),t.credentials.filter(e=>Yl(e,d.url)).map(e=>U(`option`,{value:e.id,children:Jl(e,t.credentials)},e.id))]})})]}),h&&e===`credentials`&&U(S,{children:[re(`origin`,`HTTPS origin`,!0,!1,`https://git.example.com`),re(`header`,`Header name`,!0,!1,`Authorization`),re(`prefix`,`Fixed prefix (optional)`,!1,!1,`Bearer `,`Include any space needed between the prefix and secret. Leave blank for no prefix.`)]}),h&&e===`grants`&&U(S,{children:[[`principal`,`repository`].map(e=>{let i=e===`principal`?t.agents:t.repositories,a=e===`principal`?`Agent`:`Repository`;return U(J,{id:`git-${e}-${r}`,label:a,...d[e]?{hint:d[e]}:{},children:r=>n===void 0?U(`select`,{...r,required:!0,disabled:t.loading||t.error,value:d[e],onChange:t=>I(e,t.currentTarget.value),children:[U(`option`,{value:``,children:t.loading?`Loading ${a.toLowerCase()}s`:t.error?`${a} choices unavailable`:i.length?`Select ${a.toLowerCase()}`:`No ${a.toLowerCase()}s configured`}),d[e]&&!i.some(t=>t.id===d[e])&&U(`option`,{value:d[e],children:[d[e],` · Unavailable`]}),i.map(e=>U(`option`,{value:e.id,children:Jl(e,i)},e.id))]}):U(`input`,{...r,readOnly:!0,value:i.find(t=>t.id===d[e])?.name??d[e]})})}),re(`description`,`Description (optional)`,!1,!1,`Project repository access policy`),U(J,{id:`git-read-${r}`,label:`Read repository`,children:e=>U(On,{attributes:e,checked:d.read,onChange:e=>{I(`read`,e),e||I(`refs`,[])}})}),U(`section`,{class:`git-list-editor`,"aria-label":`Push permissions`,children:[U(`h3`,{children:`Push permissions`}),d.refs.map((e,t)=>U(`fieldset`,{children:[U(`legend`,{children:[`Ref rule `,t+1]}),U(J,{id:`git-rule-kind-${t}`,label:`Match`,children:n=>U(`select`,{...n,value:e.ref.kind,onChange:e=>I(`refs`,d.refs.map((n,r)=>t===r?{...n,ref:{...n.ref,kind:e.currentTarget.value}}:n)),children:[U(`option`,{value:`exact`,children:`Exact ref`}),U(`option`,{value:`prefix`,children:`Namespace prefix ending in /`})]})}),U(J,{id:`git-rule-ref-${t}`,label:`Ref selector`,children:n=>U(`input`,{...n,required:!0,placeholder:e.ref.kind===`exact`?`refs/heads/main`:`refs/heads/`,value:e.ref.value,onInput:e=>I(`refs`,d.refs.map((n,r)=>t===r?{...n,ref:{...n.ref,value:e.currentTarget.value}}:n))})}),U(`div`,{class:`push-permissions-row`,children:[`create`,`update`,`delete`].map(n=>U(J,{id:`git-rule-${t}-${n}`,label:n[0].toUpperCase()+n.slice(1),children:r=>U(On,{attributes:r,checked:e.actions.includes(n),onChange:e=>I(`refs`,d.refs.map((r,i)=>t===i?{...r,actions:e?[...r.actions,n]:r.actions.filter(e=>e!==n)}:r))})}))}),U(`button`,{type:`button`,onClick:()=>I(`refs`,d.refs.filter((e,n)=>t!==n)),children:[`Remove ref rule `,t+1]})]},t)),U(`button`,{type:`button`,disabled:d.refs.length>=128,onClick:()=>{I(`read`,!0),I(`refs`,[...d.refs,{ref:{kind:`exact`,value:``},actions:[`update`]}])},children:`Add push rule`})]}),U(J,{id:`git-expires-${r}`,label:`Expiry (optional)`,children:e=>U(`input`,{...e,type:`datetime-local`,value:d.expires?su(d.expires):``,onInput:e=>I(`expires`,Ul(e.currentTarget.value,l.expires)??``)})})]}),g&&U(Ni,{id:M,value:E,label:`Secret`,placeholder:`Enter secret value`,hint:`Write-only. Cleared on submission or cancellation.`,onInput:e=>m(e.length>0)}),h&&(e===`repositories`||e===`grants`)&&t.error&&U(K,{state:`error`,title:`Resource choices unavailable`,children:`Refresh to load choices. Your draft is retained.`}),w&&U(K,{state:`error`,title:`Check Git configuration`,children:U(`p`,{children:[w,g?` Enter the secret again; it was cleared.`:``]})}),N&&U(K,{state:`warning`,title:`Revision changed`,children:[U(`p`,{children:`This resource changed since this form was prepared. Compare the current facts above with your draft. Use reviewed revision keeps your draft and uses that revision for your next confirmation; it does not save, rotate, delete, or retry anything.`}),U(`button`,{type:`button`,disabled:i||O.state===`uncertain`,onClick:()=>{b(Pc(e,n)),u(iu(n)),D.abandon()},children:`Use reviewed revision`})]}),O.problem&&U(K,{state:`error`,title:O.problem.title}),O.state===`uncertain`&&U(K,{state:`warning`,title:`Change outcome unknown`,children:`Inspect current metadata before deciding on another operation. No automatic retry.`}),P&&U(K,{state:`warning`,title:`Credential is referenced`,children:[U(`p`,{children:`Remove credential references from repositories before deleting this credential. Deleted repositories retain their references; deleting a repository does not release them.`}),U(`ul`,{children:n?.referencing_repositories?.map(e=>U(`li`,{children:U(nu,{id:e.id,kind:`repositories`,choices:t})},e.id))})]}),U(`div`,{class:`form-actions`,children:[_&&U(`button`,{type:`button`,disabled:i||O.state===`submitting`||O.state===`uncertain`,onClick:()=>{let t=iu(n);f(t),u(t),b(n?Pc(e,n):null),F(),T(void 0),D.abandon()},children:`Discard changes`}),U(`button`,{ref:A,type:`submit`,class:`${r===`delete`?`danger-action`:r===`create`?`create-action`:r===`edit`?`primary-action`:``} form-submit-action`,disabled:te||r===`edit`&&!_,children:r===`create`?`Review and create`:r===`edit`?`Review changes`:r===`rotate`?`Review rotation`:`Review deletion`})]})]})}),U(jn,{id:`git-confirm-${e}-${r}`,open:x,title:ne,consequence:r===`delete`?`Retire this resource. Referenced resources cannot be deleted; historical traffic is unchanged.`:r===`rotate`?`Replace protected material. A failed cutover can leave the credential unavailable; there is no fallback to the old secret.`:U(`div`,{class:`confirmation-details`,children:[U(`dl`,{class:`detail-facts`,children:[e!==`grants`&&U(`div`,{children:[U(`dt`,{children:`Name`}),U(`dd`,{children:d.name})]}),e===`repositories`&&U(S,{children:[U(`div`,{children:[U(`dt`,{children:`Immutable destination`}),U(`dd`,{children:[d.url,a&&U(Zl,{source:a,destination:d.url,contextual:!0})]})]}),U(`div`,{children:[U(`dt`,{children:`Aliases`}),U(`dd`,{children:d.aliases.length?d.aliases.join(`, `):`None`})]}),U(`div`,{children:[U(`dt`,{children:`Git credential`}),U(`dd`,{children:d.credential?U(nu,{id:d.credential,kind:`credentials`,choices:t}):`None — public repository`})]})]}),e===`credentials`&&U(S,{children:[U(`div`,{children:[U(`dt`,{children:`HTTPS origin`}),U(`dd`,{children:d.origin})]}),U(`div`,{children:[U(`dt`,{children:`Header recipe`}),U(`dd`,{children:[d.header,`: `,d.prefix,`[secret]`]})]})]}),e===`grants`&&U(S,{children:[U(`div`,{children:[U(`dt`,{children:`Agent`}),U(`dd`,{children:U(nu,{id:d.principal,kind:`agents`,choices:t})})]}),U(`div`,{children:[U(`dt`,{children:`Repository`}),U(`dd`,{children:U(nu,{id:d.repository,kind:`repositories`,choices:t})})]}),U(`div`,{children:[U(`dt`,{children:`Read repository`}),U(`dd`,{children:d.read?`Allowed`:`Blocked`})]}),U(`div`,{children:[U(`dt`,{children:`Expiry`}),U(`dd`,{children:U(Y,{value:d.expires||null,fallback:`No expiry`})})]})]})]}),e===`grants`&&U(`ul`,{children:d.refs.map((e,t)=>U(`li`,{children:[e.ref.kind,`:`,` `,U(`span`,{class:`technical-value`,children:e.ref.value}),` —`,` `,e.actions.join(`, `)]},t))})]}),confirmLabel:ne,destructive:r!==`create`,returnFocus:A,onCancel:()=>{C(!1),F()},onConfirm:se})]})}function su(e){let t=new Date(e);if(!Number.isFinite(t.getTime()))return``;let n=e=>String(e).padStart(2,`0`);return`${t.getFullYear()}-${n(t.getMonth()+1)}-${n(t.getDate())}T${n(t.getHours())}:${n(t.getMinutes())}`}function cu(e){let t=e.resolved.location.segments[1],n=ql(e.session,e.view.generation,`traffic`),{value:r,error:i}=eu(e,t?`/api/v2/git/traffic/${t}`:void 0,async e=>{if(e.headers.get(`Content-Type`)!==`application/json`)throw Error(`Unavailable`);let n=await e.text();if(n.length>16384)throw Error(`Unavailable`);let r=Rc(JSON.parse(n));if(r.admission.id!==t)throw Error(`Unavailable`);return r});if(!t)return U(uu,{...e,repositories:n});if(!r)return U(K,{state:i?`error`:`loading`,title:i?`Git traffic unavailable`:`Loading Git traffic`});let a=r.admission,o=r.completion,s=Hc(r);return U(`div`,{class:`domain-view`,children:[U(`nav`,{class:`detail-navigation`,"aria-label":`Git traffic navigation`,children:U(`a`,{href:ln({...e.resolved.location,segments:[`git-traffic`]}),children:`Back to Git traffic`})}),U(`header`,{class:`detail-context`,"data-testid":`detail-context`,children:[U(`div`,{class:`detail-context-heading`,children:[U(`h1`,{tabindex:-1,children:[zc[a.operation],a.policy?.repository_name?` — ${a.policy.repository_name}`:``]}),U(G,{state:i?`stale`:a.allowed?[`HTTP success`,`Reported success`].includes(Vc(r))?`current`:`warning`:`neutral`,children:Vc(r)})]}),U(`p`,{class:`technical-value`,children:a.id})]}),i&&U(K,{state:`warning`,title:`Git traffic refresh unavailable`}),U(`section`,{class:`detail-section`,children:[U(`h2`,{children:`Recorded exchange`}),U(`dl`,{class:`detail-facts`,children:[U(`div`,{children:[U(`dt`,{children:`Admitted`}),U(`dd`,{children:U(Y,{value:a.admitted_at})})]}),U(`div`,{children:[U(`dt`,{children:`Repository`}),U(`dd`,{children:U(lu,{item:r,choices:n})})]}),a.policy&&U(`div`,{children:[U(`dt`,{children:`Canonical destination at admission`}),U(`dd`,{children:a.policy.repository_url})]}),U(`div`,{children:[U(`dt`,{children:`Operation`}),U(`dd`,{children:zc[a.operation]})]}),U(`div`,{children:[U(`dt`,{children:`Admission`}),U(`dd`,{children:s.admission})]}),U(`div`,{children:[U(`dt`,{children:`Transport`}),U(`dd`,{children:s.transport})]}),U(`div`,{children:[U(`dt`,{children:`Upstream report`}),U(`dd`,{children:s.report})]}),U(`div`,{children:[U(`dt`,{children:`Command count`}),U(`dd`,{children:a.commands})]}),a.policy&&U(`div`,{children:[U(`dt`,{children:`Create / update / delete commands`}),U(`dd`,{children:[a.policy.creates,` / `,a.policy.updates,` / `,a.policy.deletes]})]}),o&&U(S,{children:[U(`div`,{children:[U(`dt`,{children:`HTTP status`}),U(`dd`,{children:o.status??`None`})]}),U(`div`,{children:[U(`dt`,{children:`Bytes sent / received`}),U(`dd`,{children:[o.bytes_sent,` / `,o.bytes_received]})]})]})]}),a.operation===`push`?U(`p`,{children:`Upstream reports are not independently verified repository effects. Reconcile an uncertain push with the remote before deciding on another operation.`}):U(`p`,{children:`Transport completion does not prove a valid local checkout. Discovery and probes are not completed pushes.`}),a.operation===`push`&&U(`section`,{"aria-label":`Targeted refs`,children:[U(`h2`,{children:`Targeted refs`}),a.ref_evidence?U(S,{children:[U(`p`,{children:[a.ref_evidence.refs.length,` of `,a.commands,` requested refs retained`,a.ref_evidence.state===`truncated`?`; truncated — omitted refs and their outcomes are unavailable.`:`.`]}),U(`div`,{class:`table-region table-resource`,role:`region`,"aria-label":`Targeted ref evidence`,tabindex:0,children:U(`table`,{children:[U(`caption`,{children:`Requested operations and upstream claims`}),U(`thead`,{children:U(`tr`,{children:[U(`th`,{scope:`col`,children:`Ref`}),U(`th`,{scope:`col`,children:`Requested action`}),U(`th`,{scope:`col`,children:`Upstream outcome`})]})}),U(`tbody`,{children:a.ref_evidence.refs.map((e,t)=>U(`tr`,{children:[U(`th`,{scope:`row`,"data-label":`Ref`,children:U(`span`,{class:`technical-value`,children:e.name})}),U(`td`,{"data-label":`Requested action`,children:W(e.action)}),U(`td`,{"data-label":`Upstream outcome`,children:a.allowed?o?.ref_outcomes?.[t]===`ok`?`Reported success`:o?.ref_outcomes?.[t]===`ng`?`Reported failure`:`Unknown`:`Not dispatched`})]},e.name))})]})})]}):U(`p`,{children:`Ref evidence unavailable (legacy record).`})]}),U(`details`,{children:[U(`summary`,{children:`Admission-time policy references`}),U(`dl`,{class:`detail-facts`,children:[U(`div`,{children:[U(`dt`,{children:`Repository`}),U(`dd`,{children:[a.repository.id||`Unavailable`,` · revision`,` `,a.repository.revision||`Unavailable`]})]}),U(`div`,{children:[U(`dt`,{children:`Agent`}),U(`dd`,{children:[a.principal.id,` · revision `,a.principal.revision]})]}),U(`div`,{children:[U(`dt`,{children:`Authorization revision`}),U(`dd`,{children:a.authorization_revision})]}),U(`div`,{children:[U(`dt`,{children:`Alias revision`}),U(`dd`,{children:a.alias_revision||`Unavailable`})]}),U(`div`,{children:[U(`dt`,{children:`Routing profile revision`}),U(`dd`,{children:a.profile_revision})]}),U(`div`,{children:[U(`dt`,{children:`Agent credential`}),U(`dd`,{children:[a.agent_credential.id,` · revision `,a.agent_credential.revision]})]}),a.material&&U(`div`,{children:[U(`dt`,{children:`Git credential at admission`}),U(`dd`,{children:[a.material.credential.id,` · revision`,` `,a.material.credential.revision,` · generation`,` `,a.material.generation]})]}),a.private_grant&&U(`div`,{children:[U(`dt`,{children:`Private destination permission`}),U(`dd`,{children:[a.private_grant.id,` · revision `,a.private_grant.revision]})]})]}),a.policy&&U(S,{children:[U(`p`,{children:[a.policy.grants.length,` of `,a.policy.grant_count,` applicable grant references retained`]}),U(`ul`,{children:a.policy.grants.map(e=>U(`li`,{children:[e.id,` · revision `,e.revision]},e.id))})]})]})]})]})}function lu({item:e,choices:t}){let n=e.admission.repository.id,r=e.admission.policy?.repository_name||n||`Unavailable`;return U(q,{primary:!t.loading&&!t.error&&t.repositories.some(e=>e.id===n)?U(`a`,{href:`#/git/repositories/${n}`,children:r}):r,secondary:n||void 0})}function uu(e){let t=Cr(!1),[n,r]=z(e.controller.snapshot());B(()=>e.controller.subscribe(r),[e.controller]);let i=e.resolved.location.query,[a,o]=z({...i}),[s,c]=z(!1),l=e=>{let n=Object.fromEntries(Object.entries(e).filter(([,e])=>e!==``));if(!Ve(n)){c(!0);return}c(!1),JSON.stringify(n)!==JSON.stringify(i)&&t(ln({destination:`git-traffic`,segments:[`git-traffic`],query:n}))};mn(a,l);let u=n.key===e.view.viewKey?n.items:[],d=e.view.panels[`git-traffic`]?.refreshing===!0,f=n.error||e.view.panels[`git-traffic`]?.status===`error`;return U(`section`,{class:`panel domain-panel`,children:[U(`div`,{class:`collection-toolbar live-collection-toolbar`,children:[U(`label`,{for:`git-traffic-live-mode`,children:`Live mode`}),U(On,{attributes:{id:`git-traffic-live-mode`},checked:n.live,showState:!1,onChange:t=>e.controller.setLive(t)})]}),U(Wn,{query:i}),U(`div`,{class:`table-filters collection-query-filters`,role:`group`,"aria-label":`Git traffic filters`,children:[Object.entries(Be).map(([e,t])=>U(S,{children:[e===`admission`&&U(`input`,{type:`search`,"aria-label":`Repo name or ID`,placeholder:`Repo name or ID`,value:a.filter_repository??``,onInput:e=>o({...a,filter_repository:e.currentTarget.value})}),U(`select`,{"aria-label":e===`report`?`Upstream report`:W(e),value:a[`filter_${e}`]??``,onChange:t=>{let n={...a,[`filter_${e}`]:t.currentTarget.value};o(n),l(n)},children:[U(`option`,{value:``,children:[e===`report`?`Upstream report`:W(e),`: any`]}),t.map(e=>U(`option`,{value:e,children:zc[e]??W(e)}))]})]})),U(`button`,{type:`button`,disabled:!Object.values(a).some(Boolean)&&!Object.values(i).some(Boolean),onClick:()=>{o({}),l({})},children:`Reset`})]}),s&&U(K,{state:`error`,title:`Invalid repository search`}),n.paused&&U(`div`,{class:`inline-actions`,children:[n.live&&U(G,{state:`warning`,children:`Live paused while viewing older results`}),U(`button`,{type:`button`,onClick:()=>e.controller.resume(),children:n.live?`Resume live`:`Return to newest`})]}),n.notice&&U(K,{state:`warning`,title:n.notice}),n.olderError&&U(K,{state:`error`,title:`Older exchanges unavailable`,children:`Loaded exchanges are unchanged. Try Load older exchanges again.`}),f&&U(K,{state:`error`,title:`Git traffic unavailable`,children:`Previously loaded exchanges may be stale.`}),!n.loaded&&!f&&U(K,{state:`loading`,title:`Loading Git traffic`}),U(Dn,{caption:`Git traffic`,rowHeaderKey:`exchange`,layout:`activity`,localStale:f,localLoading:!n.loaded&&!f,historySummary:!0,historyMatching:Object.keys(i).length>0,summaryExtra:n.loaded&&!f?U(`span`,{children:n.next===null?`No older exchanges`:u.length>=500?`Load limit reached. Narrow the filters or return to newest.`:``}):void 0,hasMore:n.next!==null&&u.length<500&&!f,loadingMore:d||n.loadingOlder,loadMoreLabel:`Load older exchanges`,onLoadMore:()=>void e.controller.older(),itemNames:{singular:`exchange`,plural:`exchanges`},emptyTitle:`No Git traffic`,items:u,rowKey:e=>e.admission.id,filters:[],columns:[{key:`admitted`,label:`Admitted`,role:`time`,render:e=>U(Y,{value:e.admission.admitted_at})},{key:`exchange`,label:`Operation`,role:`identity`,render:t=>U(q,{primary:U(`a`,{href:ln({...e.resolved.location,segments:[`git-traffic`,t.admission.id]}),children:zc[t.admission.operation]}),secondary:t.admission.id})},{key:`repository`,label:`Repository`,role:`relation`,render:t=>U(lu,{item:t,choices:e.repositories})},{key:`outcome`,label:`Outcome`,role:`status`,render:e=>U(G,{state:[`HTTP success`,`Reported success`].includes(Vc(e))?`current`:`warning`,children:Vc(e)})},{key:`admission`,label:`Admission`,role:`status`,render:e=>U(G,{state:`neutral`,children:Hc(e).admission})},{key:`transport`,label:`Transport`,role:`status`,render:e=>Hc(e).transport},{key:`report`,label:`Upstream report`,role:`status`,render:e=>Hc(e).report}]})]})}var du=`Showing the latest entries. Older results could not be continued.`,fu=()=>({key:``,items:[],next:null,live:!0,paused:!1,loaded:!1,error:!1,olderError:!1,loadingOlder:!1,notice:``}),pu=class{value=fu();serial=0;olderPosition=!1;continuation=null;listeners=new Set;views;constructor(e,t){this.views=t,t.registerPanel({id:`git-traffic`,matches:e=>{let t=H(e);return t?.destination===`git-traffic`&&t.segments.length===1},invalidations:[`system_status`],shouldRefresh:e=>![`invalidation`,`reconnect`,`poll`].includes(e)||this.value.live&&!this.value.paused,read:e=>this.read(e),publish:e=>{e.serial===this.serial&&(this.value=e.value,this.emit())}}),e.registerProtectedState(()=>{this.serial++,this.olderPosition=!1,this.continuation=null,this.value=fu(),this.emit()})}snapshot(){return this.value}subscribe(e){return this.listeners.add(e),e(this.value),()=>{this.listeners.delete(e)}}emit(){for(let e of this.listeners)e(this.value)}setLive(e){this.views.cancelPanelRead(`git-traffic`),this.serial++,this.value={...this.value,live:e,loadingOlder:!1},this.continuation=null,this.emit(),(!this.value.loaded||e&&!this.value.paused)&&this.resume()}resume(){this.serial++,this.olderPosition=!1,this.continuation=null,this.value={...this.value,paused:!1,loadingOlder:!1,notice:``},this.emit(),this.views.refreshPanel(`git-traffic`)}async older(){this.value.error||this.value.loadingOlder||this.value.next===null||this.value.items.length>=500||this.value.key!==this.views.snapshot().viewKey||this.views.snapshot().panels[`git-traffic`]?.refreshing||(this.continuation=this.value.next,this.value={...this.value,paused:!0,loadingOlder:!0,olderError:!1},this.emit(),await this.views.refreshPanel(`git-traffic`))}async read(e){let t=H(e.viewKey);this.value.key!==e.viewKey&&(this.serial++,this.continuation=null,this.value={...fu(),key:e.viewKey,live:this.value.live,paused:this.value.paused},this.emit());let n=this.serial,r=this.value,i=e.reason===`panel`?this.continuation:null;this.continuation=null;let a=()=>!e.signal.aborted&&n===this.serial&&e.viewKey===this.views.snapshot().viewKey,o=async n=>{let r=new URLSearchParams({limit:`50`});for(let[e,n]of Object.entries(t.query))r.set(e.slice(7),n);t.query.filter_repository&&r.set(`search_locale`,Intl.DateTimeFormat().resolvedOptions().locale),n&&r.set(`cursor`,n);let i=await fetch(`/api/v2/git/traffic?${r}`,{credentials:`same-origin`,redirect:`error`,signal:e.signal,headers:{Accept:`application/json`,"X-CSRF-Token":e.csrfToken}});if(await e.sessionLost(i)||!a())throw Error(`Superseded`);let o=await i.text();if(o.length>1048576||!a())throw Error(`Unavailable`);let s=JSON.parse(o);if(i.status===409&&i.headers.get(`Content-Type`)===`application/problem+json`&&Bn(s)?.code===`stale_cursor`)return null;if(!i.ok||i.headers.get(`Content-Type`)!==`application/json`)throw Error(`Unavailable`);return Lc(s)},s=i!==null,c=!s&&this.olderPosition?du:r.notice;try{let e=await o(i);if(e===null&&s&&(s=!1,c=du+` Git history changed; previous results were discarded.`,this.olderPosition=!1,this.value={...r,items:[],next:null,loaded:!1,notice:c},this.emit(),e=await o(null)),e===null||!a())throw Error(`Unavailable`);if(s&&(r.items.length+e.items.length>500||e.items.some(e=>r.items.some(t=>t.admission.id===e.admission.id))))throw Error(`Repeated evidence`);return this.olderPosition=s,{serial:n,value:{...this.value,items:s?[...r.items,...e.items]:e.items,next:e.nextCursor,loaded:!0,error:!1,olderError:!1,loadingOlder:!1,notice:c}}}catch(e){if(!a())throw e;return{serial:n,value:{...this.value,error:!s,olderError:s,loadingOlder:!1}}}}},mu=`/api/v2/git/routing-profile`;function hu({values:e}){return e.length?U(`ul`,{children:e.map(e=>U(`li`,{class:`technical-value`,children:e},e))}):U(`span`,{children:`No origins enabled`})}function gu(e){let[t,n]=z(),[r,i]=z(!0),[a,o]=z(!1),s=V(0);return B(()=>{let t=++s.current;return i(!0),e.session.runProtected(async e=>{let r=await fetch(mu,{credentials:`same-origin`,redirect:`error`,signal:e.signal,headers:{Accept:`application/json`,"X-CSRF-Token":e.csrfToken}});if(await e.sessionLost(r))return;if(!r.ok)throw Error(`Read unavailable`);let i=await Jc(r);t===s.current&&(n(i),o(!1))}).catch(()=>{t===s.current&&o(!0)}).finally(()=>{t===s.current&&i(!1)}),()=>{s.current++}},[e.session,e.view.generation]),t?U(`div`,{class:`domain-view`,children:[a&&U(K,{state:`error`,title:`Git routing refresh unavailable`,children:`Saved facts may be stale. Refresh before making changes.`}),U(`section`,{class:`detail-section`,"aria-labelledby":`git-routing-details`,children:[U(`h2`,{id:`git-routing-details`,children:`Routing profile`}),U(`dl`,{class:`detail-facts`,children:[U(`div`,{children:[U(`dt`,{children:`Enforcement`}),U(`dd`,{children:U(G,{state:a?`stale`:t.active?`current`:`neutral`,children:[a?`Last known: `:``,t.active?`Active`:`Inactive`]})})]}),U(`div`,{children:[U(`dt`,{children:`Enabled origins`}),U(`dd`,{children:U(hu,{values:t.origins})})]}),U(`div`,{children:[U(`dt`,{children:`Revision`}),U(`dd`,{children:t.revision})]})]})]}),U(_u,{...e,profile:t,unavailable:r||a,onSaved:t=>{s.current++,n(t),o(!1),e.onRefresh()}})]}):U(K,{state:a?`error`:`loading`,title:a?`Git routing unavailable`:`Loading Git routing`,children:a&&`Refresh to load the routing profile.`})}function _u({profile:e,unavailable:t,onSaved:n,...r}){let[i,a]=z(e.origins),[o,s]=z(qc(e)),[c,l]=z(e.origins),u=(()=>{try{return JSON.stringify(Gc(i))!==JSON.stringify(Gc(c))}catch{return!0}})(),[d,f]=z(),[p,m]=z(),[h,g]=z(!1),[_]=z(()=>r.mutations.create()),[v,y]=z(()=>_.snapshot()),b=V(null);Cr(u),B(()=>_.subscribe(y),[_]),B(()=>()=>_.close(),[_]);let x=o!==qc(e)||v.requiresRefresh,C=v.state===`submitting`||v.state===`uncertain`,w=t||x||C||v.availability===`storage_latched`,T=e=>{a(e),g(!1),m(void 0)},E=()=>{if(!(w||!u))try{f(Gc(i)),m(void 0)}catch(e){m(e instanceof Error?e.message:`Check HTTPS origins.`)}};return U(`section`,{class:`panel domain-panel`,children:[U(`div`,{class:`panel-heading`,children:U(`h2`,{children:`Edit routing`})}),U(`p`,{children:`Enabled origins use Git repository permissions and credentials for smart HTTPS Git requests. Other origins remain under HTTP policy.`}),h&&U(`p`,{role:`status`,children:`Routing saved`}),U(`form`,{onSubmit:e=>{e.preventDefault(),E()},children:U(`fieldset`,{class:`git-mutation-fields`,disabled:C,children:[U(`div`,{class:`git-list-editor`,children:[U(`h3`,{children:`HTTPS origins`}),i.length===0&&U(`p`,{children:`No origins enabled`}),i.map((e,t)=>U(`div`,{class:`form-row`,children:[U(J,{id:`git-routing-origin-${t}`,label:`Origin ${t+1}`,children:n=>U(`input`,{...n,required:!0,value:e,placeholder:`https://github.com`,onInput:e=>T(i.map((n,r)=>r===t?e.currentTarget.value:n))})}),U(`button`,{type:`button`,"aria-label":`Remove origin ${t+1}`,onClick:()=>T(i.filter((e,n)=>n!==t)),children:`Remove`})]},t)),U(`button`,{type:`button`,disabled:i.length>=256,onClick:()=>T([...i,``]),children:`Add origin`})]}),p&&U(K,{state:`error`,title:`Check HTTPS origins`,children:p}),x&&U(K,{state:`warning`,title:`Review current revision`,children:[U(`p`,{children:`Compare the saved origins above with your retained draft before continuing.`}),U(`button`,{type:`button`,disabled:t||C,onClick:()=>{s(qc(e)),l(e.origins),_.abandon()},children:`Use reviewed revision`})]}),v.problem&&U(K,{state:`error`,title:v.problem.title}),v.state===`uncertain`&&U(K,{state:`warning`,title:`Change outcome unknown`,children:`Inspect current routing before deciding on another operation. No automatic retry.`}),v.availability===`storage_latched`&&U(K,{state:`warning`,title:`Changes unavailable`,children:`Gateway storage is latched.`}),U(`div`,{class:`form-actions`,children:U(`button`,{ref:b,type:`submit`,class:`primary-action form-submit-action`,disabled:w||!u,children:`Review changes`})})]})}),U(jn,{id:`git-routing-confirm`,open:d!==void 0,title:`Update Git routing`,confirmLabel:`Save routing`,returnFocus:b,onCancel:()=>f(void 0),onConfirm:()=>{let e=d;if(f(void 0),!(!e||w))try{_.begin({route:mu,method:`PATCH`,body:JSON.stringify({origins:e}),precondition:o,requiresPrecondition:!0,idempotency:`none`,successStatuses:[200],decode:Jc}),_.submit().then(e=>{e.kind===`acknowledged`?(a(e.value.origins),s(qc(e.value)),l(e.value.origins),g(!0),_.abandon(),n(e.value)):(e.kind===`uncertain`||e.kind===`rejected`&&e.requiresRefresh)&&r.onRefresh()})}catch{m(`Refresh and review the current routing profile before making a new decision.`)}},consequence:U(S,{children:[U(xn,{label:`Routing changes`,beforeLabel:`Current`,afterLabel:`Proposed`,rows:[{label:`Enabled origins`,before:U(hu,{values:e.origins}),after:U(hu,{values:d??[]}),changed:JSON.stringify(e.origins)!==JSON.stringify(d)}]}),U(`p`,{children:`This replaces the enabled-origin list for subsequent requests. Enabled origins refuse opaque tunnels; repository grants are still required. Removing an origin returns it to HTTP policy.`}),w&&U(K,{state:`warning`,title:`Refresh and review before saving`})]})})]})}var vu=/^[0-7][0-9A-HJKMNP-TV-Z]{25}$/;function yu(e,t){if(typeof e!=`object`||!e||Array.isArray(e)||Object.keys(e).sort().join()!==t.sort().join())throw Error(`HTTP credential data is unavailable.`);return e}function bu(e){let t=yu(e,[`id`,`name`,`boundary`,`recipe`,`revision`,`available`,`referencing_grants`,`created_at`,`updated_at`]),n=yu(t.boundary,[`host`,`port`,`allow_wildcard`]),r=yu(t.recipe,[`header`,`prefix`]);if(typeof t.id!=`string`||!vu.test(t.id)||typeof t.name!=`string`||t.name.length===0||new TextEncoder().encode(t.name).length>256||typeof t.revision!=`string`||!/^[1-9][0-9]*$/.test(t.revision)||typeof t.available!=`boolean`||typeof n.host!=`string`||n.host.length===0||n.host.length>255||typeof n.port!=`number`||!Number.isInteger(n.port)||n.port<1||n.port>65535||typeof n.allow_wildcard!=`boolean`||typeof r.header!=`string`||!/^[!#$%&'*+.^_`|~0-9A-Za-z-]{1,128}$/.test(r.header)||typeof r.prefix!=`string`||!/^[\x20-\x7e]{0,128}$/.test(r.prefix)||!Array.isArray(t.referencing_grants)||t.referencing_grants.length>4096||typeof t.created_at!=`string`||!Number.isFinite(Date.parse(t.created_at))||typeof t.updated_at!=`string`||!Number.isFinite(Date.parse(t.updated_at)))throw Error(`HTTP credential data is unavailable.`);for(let e of t.referencing_grants){let t=yu(e,[`id`]);if(typeof t.id!=`string`||!vu.test(t.id))throw Error(`Invalid credential reference.`)}return e}async function xu(e){if(e.headers.get(`Content-Type`)!==`application/json`)throw Error(`HTTP credential data is unavailable.`);let t=await e.text();if(t.length>1048576)throw Error(`HTTP credential data is unavailable.`);let n=bu(JSON.parse(t));if(e.headers.get(`ETag`)!==Su(n))throw Error(`HTTP credential revision is unavailable.`);return n}function Su(e){return`"http-credential-${e.id}-${e.revision}"`}function Cu(e){let t=e.resolved.location.segments[1],[n,r]=z(),[i,a]=z(),[o,s]=z(!1),[c,l]=z(!1);return B(()=>{let n=!0;if(s(!1),l(!0),t!==void 0&&t!==`new`)return r(e=>e?.id===t?e:void 0),e.session.runProtected(async e=>{let i=await fetch(`/api/v2/http/credentials/${t}`,{credentials:`same-origin`,redirect:`error`,signal:e.signal,headers:{Accept:`application/json`,"X-CSRF-Token":e.csrfToken}});if(await e.sessionLost(i))return;if(!i.ok)throw Error(`HTTP credential data is unavailable.`);let a=await xu(i);if(a.id!==t)throw Error(`Invalid credential identity.`);n&&r(a)}).catch(()=>{n&&s(!0)}).finally(()=>{n&&l(!1)}),()=>{n=!1}},[t,e.view.generation]),t===void 0?U(wu,{...e}):t===`new`?U(Tu,{...e,mode:`create`}):o&&n?.id!==t?U(K,{state:`error`,title:`HTTP credential data unavailable`,children:U(`p`,{children:`Refresh to load the credential.`})}):n?.id===t?U(`div`,{class:`domain-view`,children:[o&&U(K,{state:`error`,title:`Current HTTP credential data unavailable`,children:U(`p`,{children:`Your safe draft is preserved. Refresh before reviewing the current revision.`})}),U(`nav`,{class:`detail-navigation`,"aria-label":`HTTP credential navigation`,children:U(`a`,{href:ln({destination:`http-credentials`,segments:[`http-credentials`],query:e.resolved.location.query}),children:`Back to HTTP credentials`})}),U(`header`,{class:`detail-context`,"data-testid":`detail-context`,children:[U(`div`,{class:`detail-context-heading`,children:[U(`h1`,{tabindex:-1,children:n.name}),U(G,{state:n.available?`current`:`warning`,children:n.available?`Configured`:`Unavailable`})]}),U(`p`,{class:`technical-value`,children:n.id})]}),U(`section`,{class:`detail-section`,"aria-labelledby":`credential-details-title`,children:[U(`div`,{class:`panel-heading`,children:U(`h2`,{id:`credential-details-title`,children:`Credential details`})}),U(`h3`,{children:`HTTPS scope and recipe`}),U(`dl`,{class:`detail-facts`,children:[U(`div`,{children:[U(`dt`,{children:`HTTPS boundary`}),U(`dd`,{children:[n.boundary.host,`:`,n.boundary.port]})]}),U(`div`,{children:[U(`dt`,{children:`Wildcard hosts`}),U(`dd`,{children:n.boundary.allow_wildcard?`Allowed within boundary`:`Exact host only`})]}),U(`div`,{children:[U(`dt`,{children:`Header recipe`}),U(`dd`,{children:[n.recipe.header,`: `,n.recipe.prefix,U(`span`,{class:`secondary-text`,children:`[secret]`})]})]})]}),U(`h3`,{children:`Referencing grants`}),n.referencing_grants.length===0?U(`p`,{children:`No referencing grants`}):U(`ul`,{children:n.referencing_grants.map(e=>U(`li`,{class:`technical-value`,children:U(`a`,{href:`#/http/grants/${e.id}`,children:e.id})},e.id))}),U(`h3`,{children:`Metadata`}),U(`dl`,{class:`detail-facts`,children:U(`div`,{children:[U(`dt`,{children:`Revision`}),U(`dd`,{children:n.revision})]})})]}),b(Tu,{...e,key:`${n.id}-edit`,acknowledgment:i,onAcknowledged:a,credential:n,mode:`edit`,unavailable:o||c}),b(Tu,{...e,key:`${n.id}-rotate`,acknowledgment:i,onAcknowledged:a,credential:n,mode:`rotate`,unavailable:o||c}),b(Tu,{...e,key:`${n.id}-delete`,acknowledgment:i,onAcknowledged:a,credential:n,mode:`delete`,unavailable:o||c})]}):U(K,{state:`loading`,title:`Loading HTTP credential`})}function wu(e){let t=Cr(!1),{items:n,controls:r}=Nr(e.session,e.resolved,e.view,(t,n,r)=>{let i=new URLSearchParams({limit:`50`,sort:t.sort??`name`,direction:t.direction??`ascending`});for(let e of[`name`,`boundary`,`recipe`,`status`]){let n=t[`filter_${e}`];n!==void 0&&i.set(e,n)}return n!==null&&i.set(`cursor`,n),Mr(e.session,`/api/v2/http/credentials?${i}`,bu,r)},t,{key:`name`,direction:`ascending`});return U(`div`,{class:`domain-view`,children:[U(`div`,{class:`collection-toolbar`,children:U(`a`,{class:`button-link create-action`,href:`#/http/credentials/new`,children:`Create credential`})}),U(`section`,{class:`panel domain-panel`,children:U(Dn,{caption:`HTTP credentials`,rowHeaderKey:`name`,remote:r,itemNames:{singular:`credential`,plural:`credentials`},emptyTitle:`No HTTP credentials`,items:n,rowKey:e=>e.id,initialSort:{key:`name`,direction:`ascending`},filters:[{key:`name`,label:`Name or ID`,type:`text`,value:e=>e.name,literalValues:e=>[e.id]},{key:`boundary`,label:`HTTPS boundary`,type:`text`,value:e=>`${e.boundary.host}:${e.boundary.port}`},{key:`recipe`,label:`Header recipe`,type:`text`,value:e=>`${e.recipe.header} ${e.recipe.prefix}`},{key:`status`,label:`Status`,type:`select`,value:e=>e.available?`configured`:`unavailable`,options:[{value:`configured`,label:`Configured`},{value:`unavailable`,label:`Unavailable`}]}],columns:[{key:`name`,label:`Credential`,role:`identity`,sortValue:e=>e.name,render:t=>U(q,{primary:U(`a`,{href:ln({destination:`http-credentials`,segments:[`http-credentials`,t.id],query:e.resolved.location.query}),children:t.name}),secondary:t.id})},{key:`boundary`,label:`HTTPS boundary`,role:`relation`,sortValue:e=>`${e.boundary.host}:${e.boundary.port}`,render:e=>U(S,{children:[e.boundary.host,`:`,e.boundary.port]})},{key:`recipe`,label:`Header recipe`,role:`identity`,sortValue:e=>`${e.recipe.header} ${e.recipe.prefix}`,render:e=>U(S,{children:[e.recipe.header,`: `,e.recipe.prefix,`[secret]`]})},{key:`status`,label:`Status`,role:`status`,sortValue:e=>e.available?`configured`:`unavailable`,render:e=>U(G,{state:e.available?`current`:`warning`,children:e.available?`Configured`:`Unavailable`})}]})})]})}function Tu({mutations:e,sinks:t,credential:n,mode:r,onRefresh:i,view:a,unavailable:o=!1,acknowledgment:s,onAcknowledged:c}){let[l,u]=z(n?.name??``),[d,f]=z(n?.boundary.host??``),[p,m]=z(String(n?.boundary.port??443)),[h,g]=z(n?.boundary.allow_wildcard??!1),[_,v]=z(n?.recipe.header??`Authorization`),[y,b]=z(n?.recipe.prefix??`Bearer `),[x]=z(()=>t.createWriteOnly()),[C]=z(()=>e.create()),[w,T]=z(()=>C.snapshot()),[E,D]=z(!1),[O,k]=z(!1),[A,j]=z(n),M=A===void 0||JSON.stringify({name:l,host:d.toLowerCase(),port:p,wildcard:h,header:_.toLowerCase(),prefix:y})!==JSON.stringify({name:A.name,host:A.boundary.host.toLowerCase(),port:String(A.boundary.port),wildcard:A.boundary.allow_wildcard,header:A.recipe.header.toLowerCase(),prefix:A.recipe.prefix}),N=r===`edit`?M:O,[ee,P]=z(),[te,F]=z(),[ne,I]=z(!1),[re,ie]=z(()=>n===void 0?null:Su(n)),ae=V();B(()=>{if(!(n===void 0||o||re===Su(n))){if(re!==Su(n)){if(s?.from!==re||s.to!==Su(n)||ae.current===s.to)return;ae.current=s.to}N||ne||E||w.state!==`editing`||(j(n),ie(Su(n)),u(n.name),f(n.boundary.host),m(String(n.boundary.port)),g(n.boundary.allow_wildcard),v(n.recipe.header),b(n.recipe.prefix))}},[n,N,ne,E,w.state,s,re,o]);let oe=V(null),se=Cr(N),ce=`http-credential-secret-${r}`;B(()=>C.subscribe(T),[C]),B(()=>()=>{C.close(),x.close()},[C,x]);let L=r===`create`||r===`edit`,le=r===`create`||r===`rotate`,ue=r===`edit`&&(n?.referencing_grants.length??0)>0,de=n!==void 0&&re!==Su(n),fe=o||de||ne||w.state===`submitting`||w.state===`uncertain`||w.availability===`storage_latched`||te!==void 0&&a.generation<=te||r===`delete`&&(n?.referencing_grants.length??0)>0,R=r===`create`?`Create HTTP credential`:r===`edit`?`Edit credential`:r===`rotate`?`Rotate secret`:`Delete credential`,pe=()=>{x.clear(),k(!1)},me=()=>{if(L){if(l.trim()===``||new TextEncoder().encode(l).byteLength>256)return`Name must be nonempty and at most 256 bytes.`;if(d===``||new TextEncoder().encode(d.startsWith(`*.`)?d.slice(2):d).byteLength>253)return`HTTPS destination host must be nonempty and at most 253 bytes, excluding *.`;if(!/^[1-9][0-9]*$/.test(p)||Number(p)>65535)return`Port must be a whole number from 1 to 65535.`;if(!/^[!#$%&'*+.^_`|~0-9A-Za-z-]{1,128}$/.test(_))return`Header name must contain 1–128 HTTP token characters.`;if(!/^[\x20-\x7e]{0,128}$/.test(y))return`Fixed prefix must contain at most 128 printable ASCII characters.`}if(le){let e=document.getElementById(ce);if(!(e instanceof HTMLInputElement)||e.value===``)return`Secret must be nonempty.`;if(e.value.length+y.length>4096)return`Secret and fixed prefix must total at most 4096 characters.`;if(!/^[\x20-\x7e]+$/.test(e.value))return`Secret must contain only printable ASCII characters.`}},he=e=>{x.clear(),P(le?`${e} Enter the secret again; it was cleared.`:e)},ge=()=>{if(fe||r===`edit`&&!N)return;let e=me();P(void 0),e===void 0?D(!0):he(e)};return U(`section`,{class:`panel domain-panel`,"aria-labelledby":`http-credential-title-${r}`,children:[U(`div`,{class:`panel-heading`,children:U(`h2`,{id:`http-credential-title-${r}`,children:r===`create`?`Credential configuration`:R})}),U(`form`,{onSubmit:e=>{e.preventDefault(),ge()},onInput:()=>k(!0),children:U(`fieldset`,{class:`credential-fields`,disabled:w.state===`submitting`||w.state===`uncertain`||w.availability===`storage_latched`,children:[L&&U(S,{children:[U(J,{id:`http-name-${r}`,label:`Name`,children:e=>U(`input`,{...e,required:!0,placeholder:`Example API credential`,value:l,onInput:e=>u(e.currentTarget.value)})}),U(J,{id:`http-host-${r}`,label:`HTTPS destination host`,children:e=>U(`input`,{...e,required:!0,placeholder:`api.example.com`,value:d,onInput:e=>f(e.currentTarget.value)})}),U(J,{id:`http-port-${r}`,label:`Port`,children:e=>U(`input`,{...e,required:!0,type:`number`,min:`1`,max:`65535`,placeholder:`443`,value:p,onInput:e=>m(e.currentTarget.value)})}),U(J,{id:`http-wildcard-${r}`,label:`Allow the explicit *. subdomain boundary`,children:e=>U(On,{attributes:e,checked:h,onChange:g})}),ue&&U(`p`,{children:`Header recipe is fixed while referenced.`}),U(J,{id:`http-header-${r}`,label:`Header name`,children:e=>U(`input`,{...e,required:!0,readOnly:ue,placeholder:`Authorization`,value:_,onInput:e=>v(e.currentTarget.value)})}),U(J,{id:`http-prefix-${r}`,label:`Fixed prefix (optional)`,hint:`Include any space needed between the prefix and secret. Leave blank for no prefix.`,children:e=>U(`input`,{...e,readOnly:ue,placeholder:`Bearer `,value:y,onInput:e=>b(e.currentTarget.value)})})]}),le&&U(Ni,{id:ce,value:x,label:`Secret`,placeholder:`Enter secret value`,hint:`Write-only. Cleared after submission; stored values cannot be revealed.`}),r===`delete`&&(n?.referencing_grants.length??0)>0&&U(K,{state:`warning`,title:`Credential is referenced`,children:`Remove referencing grants before deleting this credential.`}),ee!==void 0&&U(K,{state:`error`,title:`Check credential fields`,children:U(`p`,{children:ee})}),(ne||de)&&U(K,{state:`warning`,title:`Review current credential revision`,children:[U(`p`,{children:`Compare the current facts above with your retained draft before applying it.`}),U(`button`,{type:`button`,disabled:o||n===void 0||te!==void 0&&a.generation<=te,onClick:()=>{n!==void 0&&(ie(Su(n)),j(n),I(!1),C.abandon())},children:`Use reviewed revision; keep draft`})]}),w.problem!==void 0&&U(K,{state:`error`,title:w.problem.title}),w.state===`uncertain`&&U(K,{state:`warning`,title:`Credential change outcome unknown`,children:U(`p`,{children:`Inspect current metadata before making a new decision. No replay is available.`})}),U(`button`,{ref:oe,type:`submit`,class:r===`delete`?`danger-action form-submit-action`:`${r===`create`?`create-action `:r===`edit`?`primary-action `:``}form-submit-action`,disabled:fe||r===`edit`&&!N,children:r===`create`?`Review and create`:`Review ${r===`edit`?`changes`:r===`rotate`?`rotation`:`deletion`}`})]})}),U(jn,{id:`http-credential-confirm-${r}`,open:E,title:R,consequence:L?U(`div`,{class:`review-stack`,children:[U(`dl`,{class:`detail-facts`,children:[U(`div`,{children:[U(`dt`,{children:`Name`}),U(`dd`,{children:l})]}),U(`div`,{children:[U(`dt`,{children:`HTTPS boundary`}),U(`dd`,{children:[d,`:`,p]})]}),U(`div`,{children:[U(`dt`,{children:`Wildcard hosts`}),U(`dd`,{children:h?`Allowed within boundary`:`Exact host only`})]}),U(`div`,{children:[U(`dt`,{children:`Header`}),U(`dd`,{children:_})]}),U(`div`,{children:[U(`dt`,{children:`Prefix`}),U(`dd`,{children:y===``?`None`:U(`code`,{children:y})})]}),U(`div`,{children:[U(`dt`,{children:`Secret material`}),U(`dd`,{children:r===`create`?`Write-only; not displayed`:`Unchanged`})]})]}),U(`p`,{children:`Replace the named header using this recipe. Every referencing grant must remain contained.`})]}):r===`delete`?`Permanently retire this unreferenced credential. Stored material cannot be restored from a backup.`:`Once replacement starts, failure may leave this credential unavailable; replacement does not fall back to the old secret.`,confirmLabel:R,destructive:r!==`create`,returnFocus:oe,onCancel:()=>{D(!1),x.clear()},onConfirm:()=>{if(D(!1),fe){he(`Current credential state cannot authorize this change. Refresh and review again.`);return}let e=me();if(e!==void 0){he(e);return}let t=document.getElementById(ce),o=t instanceof HTMLInputElement?t.value:``,s={name:l,boundary:{host:d,port:Number(p),allow_wildcard:h},recipe:{header:_,prefix:y}},u=r===`create`?{...s,secret:o}:r===`edit`?s:r===`rotate`?{secret:o}:{},f=`/api/v2/http/credentials${n===void 0?``:`/${n.id}`}${r===`rotate`?`/rotate`:``}`;try{C.begin({route:f,method:r===`delete`?`DELETE`:r===`edit`?`PATCH`:`POST`,body:JSON.stringify(u),precondition:re,requiresPrecondition:n!==void 0,idempotency:`none`,successStatuses:[r===`create`?201:r===`delete`?204:200],...le?{uncertainProblemCodes:[`keyring_unavailable`]}:{},decode:async e=>r===`delete`?null:xu(e)})}catch{pe(),P(le?`Credential change could not be prepared. Enter the secret again; it was cleared.`:`Credential change could not be prepared. Refresh before reviewing again.`);return}let m=C.submit();r===`edit`?x.clear():pe(),m.then(e=>{e.kind===`acknowledged`?(k(!1),e.value&&(re&&c?.({from:re,to:Su(e.value)}),j(e.value),ie(Su(e.value))),I(!1),C.abandon(),r===`delete`?se(`#/http/credentials`,!0):r===`create`&&e.value!==null?se(`#/http/credentials/${e.value.id}`,!0):i()):(e.kind===`uncertain`||e.kind===`rejected`&&e.requiresRefresh)&&(F(a.generation),r===`edit`&&e.kind===`rejected`&&I(!0),i())})}})]})}var Eu={block_destination:`Block destination`,allow_tunnel:`Allow tunnel`,block_requests:`Block requests`,allow_requests:`Allow requests`};async function Du(e){if(e.headers.get(`Content-Type`)!==`application/json`)throw Error(`HTTP policy data unavailable.`);let t=await e.text();if(t.length>1048576)throw Error(`HTTP policy data unavailable.`);return He(t)}async function Ou(e,t,n){return e.runProtected(async e=>{let r=await fetch(t,{credentials:`same-origin`,redirect:`error`,signal:e.signal,headers:{Accept:`application/json`,"X-CSRF-Token":e.csrfToken}});if(!await e.sessionLost(r)){if(!r.ok)throw Error(`HTTP policy data unavailable.`);return n(await Du(r),r)}})}async function ku(e){let t=[],n=null;for(let r=0;r<3;r++){let r=await Ou(e,`/api/v2/http/credentials?limit=100${n===null?``:`&cursor=`+encodeURIComponent(n)}`,e=>{let t=ht(e,[`items`,`next_cursor`,`total_count`,`offset`]);if(!Array.isArray(t.items)||t.items.length>100||t.next_cursor!==null&&(typeof t.next_cursor!=`string`||t.next_cursor.length>512))throw Error(`Invalid credential choices.`);return{items:t.items.map(bu),next:t.next_cursor}});if(r===void 0)throw Error(`Credential choices unavailable.`);if(t.push(...r.items),t.length>256||new Set(t.map(e=>e.id)).size!==t.length)throw Error(`Invalid credential choices.`);if(r.next===null)return t;n=r.next}throw Error(`Credential choice limit exceeded.`)}function Au(e){return`"http-grant-${e.id}-${e.revision}"`}async function ju(e){let t=xt(await Du(e));if(e.headers.get(`ETag`)!==Au(t))throw Error(`Invalid HTTP grant revision.`);return t}function Mu(e){return e.destination??e.request.origin}function Nu(e){let t=Mu(e),n=e.request;return[{label:`Type`,value:Eu[e.type]},{label:`Destination`,value:`${n===void 0?``:n.origin.scheme+`://`}${t.host}:${t.port}`},{label:`Methods`,value:n===void 0?`Not applicable`:n.methods.any?`Any method`:n.methods.values.join(`, `)},{label:`Path`,value:n===void 0?`Not applicable`:n.path.kind===`any`?`Any path`:n.path.kind===`exact`?n.path.value:n.path.value+` and descendants`},{label:`Local/private access`,value:e.type===`allow_requests`||e.type===`allow_tunnel`?e.allow_private?`Enabled`:`Disabled`:`Not applicable`},{label:`Credential`,value:e.type===`allow_requests`?e.credential_id??`No credential`:`Not applicable`,href:e.credential_id===void 0?void 0:`#/http/credentials/${e.credential_id}`}]}function Pu({policy:e,credentialName:t}){return U(S,{children:Nu(e).map(n=>U(`div`,{children:[U(`dt`,{children:n.label}),U(`dd`,{children:n.href===void 0?n.value:U(S,{children:[U(`a`,{href:n.href,children:n.label===`Credential`?t??n.value:n.value}),n.label===`Credential`&&t!==void 0&&U(`span`,{class:`table-identifier`,children:e.credential_id})]})})]},n.label))})}function Fu({current:e,proposed:t,principals:n}){let r=e=>[{label:`Description`,value:e.description||`Unnamed HTTP grant`},{label:`Agent`,value:e.principal_id,content:U(q,{primary:n.find(t=>t.id===e.principal_id)?.displayName??`Agent unavailable`,secondary:e.principal_id})},...Nu(e.policy).map(e=>({...e,content:e.href===void 0?e.value:U(`a`,{href:e.href,children:e.value})})),{label:`Expires`,value:e.expires_at,content:U(Y,{value:e.expires_at,fallback:`No expiry`})}],i=r(e);return U(xn,{label:`Current versus proposed grant`,beforeLabel:`Current`,afterLabel:`Proposed`,rows:r(t).map((e,t)=>({label:e.label,before:`content`in i[t]?i[t].content:i[t].value,after:`content`in e?e.content:e.value,changed:i[t].value!==e.value}))})}function Iu(e,t){let[n,r]=z([]),[i,a]=z([]),[o,s]=z(!1),[c,l]=z(!0);return B(()=>{if(!t)return;let n=!0;return l(!0),Promise.all([Qo(e.session),ku(e.session)]).then(([e,t])=>{n&&(r(e),a(t),s(!1))}).catch(()=>{n&&(r([]),a([]),s(!0))}).finally(()=>{n&&l(!1)}),()=>{n=!1}},[t,e.view.generation]),{principals:n,credentials:i,loadError:o,loading:c}}function Lu(e){let[t]=z(()=>e.mutations.create()),[n,r]=z(()=>t.snapshot()),[i,a]=z(),[o,s]=z(!1);return B(()=>t.subscribe(r),[t]),B(()=>()=>t.close(),[t]),{blocked:n.state===`submitting`||n.state===`uncertain`||n.availability===`storage_latched`||i!==void 0&&e.view.generation<=i,submit:async(n,r)=>{try{t.begin(n);let i=await t.submit();i.kind===`acknowledged`?(t.abandon(),r(i.value)):(i.kind===`uncertain`||i.kind===`rejected`&&i.requiresRefresh)&&(a(e.view.generation),i.kind===`rejected`&&s(!0),e.onRefresh())}catch{a(e.view.generation),e.onRefresh()}},state:n,reviewRequired:o,review:()=>{s(!1),t.abandon()}}}function Ru({state:e}){return e.state===`uncertain`?U(K,{state:`error`,title:`Outcome uncertain`,children:U(`p`,{children:`Inspect current policy. Do not replay this change.`})}):e.state===`rejected`?U(K,{state:`error`,title:`Change not applied`,children:[U(`p`,{children:e.problem?.title??`Check the proposed policy.`}),e.requiresRefresh&&U(`p`,{children:`Inspect refreshed policy before reviewing again.`})]}):null}function zu(e){let t=e.resolved.location.segments[1],[n,r]=z(),[i,a]=z(!1),[o,s]=z(!0),[c,l]=z(0),[u,d]=z(!1),f=V(null),p=Iu(e,t!==void 0&&t!==`test-access`),m=()=>{l(e=>e+1),f.current?.focus()};if(B(()=>{let n=!0;if(s(!0),t!==void 0&&t!==`new`&&t!==`test-access`)return Ou(e.session,`/api/v2/http/grants/${t}`,(e,n)=>{let r=xt(e);if(r.id!==t||n.headers.get(`ETag`)!==Au(r))throw Error(`HTTP grant revision unavailable.`);return r}).then(e=>{n&&e?.id===t&&(r(e),a(!1))}).catch(()=>{n&&a(!0)}).finally(()=>{n&&s(!1)}),()=>{n=!1}},[t,e.view.generation]),t===void 0)return U(Bu,{...e});if(t===`test-access`)return U(Hu,{...e});if(t===`new`)return U(Vu,{...e,choices:p});if(i&&n?.id!==t)return U(K,{state:`error`,title:`HTTP grant unavailable`,children:U(`p`,{children:`Refresh to inspect current policy.`})});if(n?.id!==t)return U(K,{state:`loading`,title:`Loading HTTP grant`});let h=p.credentials.find(e=>e.id===n.policy.credential_id)?.available;return U(`div`,{class:`domain-view`,children:[U(`nav`,{class:`detail-navigation`,"aria-label":`HTTP grant navigation`,children:U(`a`,{href:`#/http/grants`,children:`Back to HTTP grants`})}),U(`header`,{class:`detail-context`,"data-testid":`detail-context`,children:[U(`div`,{class:`detail-context-heading`,children:[U(`h1`,{ref:f,tabindex:-1,children:n.description||`Unnamed HTTP grant`}),U(G,{state:n.state===`active`?`current`:`neutral`,children:n.state===`active`?`Active`:`Expired`})]}),U(`p`,{class:`technical-value`,children:n.id})]}),i&&U(K,{state:`stale`,title:u?`Grant saved; refresh unavailable`:`Grant details are stale`,children:U(`p`,{children:[u?`Showing last acknowledged values.`:`Showing last loaded values.`,` `,`Refresh to inspect current policy before editing.`]})}),U(`section`,{class:`detail-section`,"aria-labelledby":`http-grant-details-title`,children:[U(`div`,{class:`panel-heading`,children:U(`h2`,{id:`http-grant-details-title`,children:`Grant details`})}),U(`h3`,{children:`Policy and relationships`}),U(`dl`,{class:`detail-facts`,children:[U(`div`,{children:[U(`dt`,{children:`Agent`}),U(`dd`,{children:U(q,{primary:U(`a`,{href:`#/agents/${n.principal_id}`,children:p.principals.find(e=>e.id===n.principal_id)?.displayName??(p.loading?`Loading agent`:`Agent unavailable`)}),secondary:n.principal_id})})]}),U(Pu,{policy:n.policy,credentialName:p.credentials.find(e=>e.id===n.policy.credential_id)?.name}),n.policy.credential_id!==void 0&&U(`div`,{children:[U(`dt`,{children:`Credential material`}),U(`dd`,{children:p.loading?`Loading`:h===void 0?`Unknown`:h?`Available`:`Unavailable`})]})]}),U(`h3`,{children:`Timing`}),U(`dl`,{class:`detail-facts`,children:[U(`div`,{children:[U(`dt`,{children:`Expires`}),U(`dd`,{children:U(Y,{value:n.expires_at,fallback:`No expiry`})})]}),U(`div`,{children:[U(`dt`,{children:`Created`}),U(`dd`,{children:U(Y,{value:n.created_at})})]})]})]}),b(Vu,{...e,key:`${n.id}:${c}`,grant:n,choices:p,unavailable:i||o,onCancel:m,onSaved:t=>{r(t),d(!0),m(),f.current?.focus(),e.notify(`Grant saved`),e.onRefresh()}})]})}function Bu(e){let t=Cr(!1),{items:n,controls:r}=Nr(e.session,e.resolved,e.view,(t,n,r)=>{let i=new URLSearchParams({limit:`50`,sort:t.sort??`description`,direction:t.direction??`ascending`});for(let e of[`identity`,`principal`,`target`,`type`,`state`]){let n=t[`filter_${e}`];n!==void 0&&i.set(e,n)}return t.principal_id!==void 0&&i.set(`principal_id`,t.principal_id),n!==null&&i.set(`cursor`,n),Mr(e.session,`/api/v2/http/grants?${i}`,e=>{let t=mt(e);if(Object.keys(t).sort().join()!==`grant,principal_display_name`||typeof t.principal_display_name!=`string`)throw Error(`Invalid grant row.`);return{grant:xt(t.grant),principal_display_name:t.principal_display_name}},r)},t,{key:`description`,direction:`ascending`});return U(`div`,{class:`domain-view`,children:[U(`div`,{class:`collection-toolbar`,children:[U(`a`,{class:`button-link create-action`,href:`#/http/grants/new`,children:`Create grant`}),U(`a`,{class:`button-link`,href:`#/http/grants/test-access`,children:`Test access`})]}),U(`section`,{class:`panel domain-panel`,children:U(Dn,{caption:`HTTP grants`,rowHeaderKey:`description`,additionalSorts:[{key:`id`,label:`Grant ID`,sortValue:e=>e.grant.id}],remote:r,initialSort:{key:`description`,direction:`ascending`},itemNames:{singular:`grant`,plural:`grants`},emptyTitle:`No HTTP grants`,items:n,rowKey:e=>e.grant.id,filters:[{key:`identity`,label:`Description or ID`,type:`text`,value:e=>e.grant.description??``,literalValues:e=>[e.grant.id]},{key:`principal`,label:`Agent`,type:`text`,value:e=>e.principal_display_name,literalValues:e=>[e.grant.principal_id]},{key:`target`,label:`Destination host`,type:`text`,value:e=>Mu(e.grant.policy).host},{key:`type`,label:`Type`,type:`select`,value:e=>e.grant.policy.type,options:Object.entries(Eu).map(([e,t])=>({value:e,label:t}))},{key:`state`,label:`Status`,type:`select`,value:e=>e.grant.state,options:[{value:`active`,label:`Active`},{value:`expired`,label:`Expired`}]}],columns:[{key:`description`,label:`Grant`,role:`identity`,sortValue:e=>e.grant.description??``,render:e=>U(q,{primary:U(`a`,{href:`#/http/grants/${e.grant.id}`,children:e.grant.description??`Unnamed grant`}),secondary:e.grant.id})},{key:`principal`,label:`Agent`,role:`relation`,sortValue:e=>e.principal_display_name,render:e=>U(q,{primary:U(`a`,{href:`#/agents/${e.grant.principal_id}`,children:e.principal_display_name||e.grant.principal_id}),secondary:e.grant.principal_id})},{key:`target`,label:`Destination`,role:`relation`,sortValue:e=>Mu(e.grant.policy).host,render:e=>U(S,{children:[Mu(e.grant.policy).host,`:`,Mu(e.grant.policy).port]})},{key:`effect`,label:`Type`,role:`status`,sortValue:e=>e.grant.policy.type,render:e=>Eu[e.grant.policy.type]},{key:`state`,label:`Status`,role:`status`,sortValue:e=>e.grant.state,render:e=>U(G,{state:e.grant.state===`active`?`current`:`neutral`,children:e.grant.state===`active`?`Active`:`Expired`})},{key:`expiry`,label:`Expires`,role:`time`,render:e=>U(Y,{value:e.grant.expires_at,fallback:`No expiry`})}]})})]})}function Vu(e){let t=e.grant,n=t?.policy,r=n?.request,{principals:i,credentials:a,loadError:o,loading:s}=e.choices,[c,l]=z(t?.principal_id??``),[u,d]=z(t?.description??``),[f,p]=z(n?.type??`allow_requests`),[m,h]=z(n===void 0?``:Mu(n).host),[g,_]=z(String(n===void 0?443:Mu(n).port)),[v,y]=z(r?.origin.scheme??`https`),[b,x]=z(r?.methods.values??[]),[C,w]=z(r?.path.kind??`any`),[T,E]=z(r?.path.value??``),[D,O]=z(n?.allow_private??!1),[k,A]=z(n?.credential_id??``),[j,M]=z(t),[N,ee]=z(Hl(t?.expires_at)),[P,te]=z(),[F,ne]=z(!1),I=V(null),re=V(null),ie=V(null),ae=V(null),[oe,se]=z(!1),[ce,L]=z(t===void 0?null:Au(t)),le=V(null),ue=Lu(e),de=f===`allow_requests`||f===`block_requests`,fe=f===`allow_requests`||f===`allow_tunnel`,R=a.filter(e=>v===`https`&&e.boundary.port===Number(g)&&(e.boundary.host===m.toLowerCase()||e.boundary.host.startsWith(`*.`)&&m.toLowerCase().endsWith(e.boundary.host.slice(1)))),pe={version:1,type:f,...de?{request:{origin:{scheme:v,host:m,port:Number(g)},methods:b.length===0?{any:!0}:{values:b},path:C===`any`?{kind:C}:{kind:C,value:T}}}:{destination:{host:m,port:Number(g)}},...fe?{allow_private:D}:{},...f===`allow_requests`&&k!==``?{credential_id:k}:{}},me=Ul(N,j?.expires_at),he=e=>JSON.stringify({version:e.version,type:e.type,allow_private:e.allow_private,credential_id:e.credential_id,...e.request?{request:{origin:{scheme:e.request.origin.scheme,host:e.request.origin.host.toLowerCase(),port:e.request.origin.port},path:{kind:e.request.path.kind,value:e.request.path.value},methods:e.request.methods.any?{any:!0}:{values:[...e.request.methods.values??[]].sort()}}}:{},...e.destination?{destination:{host:e.destination.host.toLowerCase(),port:e.destination.port}}:{}}),ge=j===void 0||!/^[1-9][0-9]*$/.test(g)||c!==j.principal_id||(u||null)!==j.description||me!==j.expires_at||he(pe)!==he(j.policy),_e=Cr(ge),ve=t!==void 0&&(ce!==Au(t)||ue.reviewRequired),ye=()=>{let n=P===`delete`;if(te(void 0),ue.blocked||ve||e.unavailable||!n&&(o||s))return;let r=n?null:JSON.stringify({principal_id:c,description:u||null,policy:pe,expires_at:me});ue.submit({route:`/api/v2/http/grants${t===void 0?``:`/`+t.id}`,method:n?`DELETE`:t===void 0?`POST`:`PATCH`,body:r,precondition:ce,requiresPrecondition:t!==void 0,idempotency:`none`,successStatuses:[n?204:t===void 0?201:200],decode:async e=>{if(n)return null;let r=await ju(e);if(r.principal_id!==c||t!==void 0&&r.id!==t.id)throw Error(`HTTP grant identity unavailable.`);return r}},n=>{n!==null&&M(n),n===null?_e(`#/http/grants`,!0):t===void 0?_e(`#/http/grants/${n.id}`,!0):e.onSaved?.(n)})};return U(`section`,{id:`http-grant-editor`,class:`panel domain-panel`,"aria-labelledby":`http-grant-editor-title`,children:[U(`div`,{class:`panel-heading`,children:U(`h2`,{id:`http-grant-editor-title`,children:t===void 0?`Grant configuration`:`Edit grant`})}),o&&U(K,{state:`error`,title:`Agent or credential choices unavailable`}),ve&&U(K,{state:`warning`,title:`Policy changed`,children:[U(`p`,{children:`Inspect the current policy above before applying this draft.`}),U(`button`,{type:`button`,disabled:ue.blocked||e.unavailable,onClick:()=>{L(Au(t)),M(t),ue.review()},children:`Use current revision`})]}),U(`form`,{onSubmit:e=>{e.preventDefault();let t=pt.test(c)&&new TextEncoder().encode(u).length<=256&&m.length<=253&&/^[1-9][0-9]*$/.test(g)&&Number(g)<=65535&&(!de||C===`any`||T.startsWith(`/`))&&(N===``||Date.parse(N)>Date.now())&&(f!==`allow_requests`||k===``||R.some(e=>e.id===k));se(!t),t&&(ie.current=le.current,te(`save`))},children:[U(`div`,{role:`group`,"aria-label":`Agent and description`,children:[U(J,{id:`http-grant-principal`,label:`Agent`,...c?{hint:c}:{},children:e=>t===void 0?U(`select`,{...e,required:!0,value:c,onChange:e=>l(e.currentTarget.value),children:[U(`option`,{value:``,children:`Select agent`}),t!==void 0&&!i.some(e=>e.id===c)&&U(`option`,{value:c,children:[`Agent unavailable · `,c]}),i.map(e=>U(`option`,{value:e.id,children:[e.displayName,i.filter(t=>t.displayName===e.displayName).length>1?` · ${e.id}`:``]},e.id))]}):U(`input`,{...e,readOnly:!0,value:i.find(e=>e.id===c)?.displayName??c})}),U(J,{id:`http-grant-description`,label:`Description (optional)`,children:e=>U(`input`,{...e,ref:ae,placeholder:`Example API policy`,maxLength:256,value:u,onInput:e=>d(e.currentTarget.value)})})]}),U(`div`,{class:`form-section`,role:`group`,"aria-label":`Destination and matching`,children:[U(J,{id:`http-grant-type`,label:`Grant type`,children:e=>U(`select`,{...e,value:f,onChange:e=>p(e.currentTarget.value),children:Object.entries(Eu).map(([e,t])=>U(`option`,{value:e,children:t}))})}),f===`allow_tunnel`&&U(K,{state:`warning`,title:`Opaque tunnel bypass`,children:U(`p`,{children:`Allows encrypted traffic without request method/path checks or credential injection. Request blocks do not apply inside this tunnel.`})}),de&&U(J,{id:`http-grant-scheme`,label:`Scheme`,children:e=>U(`select`,{...e,value:v,onChange:e=>{y(e.currentTarget.value),A(``)},children:[U(`option`,{value:`https`,children:`HTTPS`}),U(`option`,{value:`http`,children:`HTTP`})]})}),U(J,{id:`http-grant-host`,label:`Destination host`,hint:`Exact host, or *.example.com for every subdomain excluding the apex.`,children:e=>U(`input`,{...e,required:!0,maxLength:255,placeholder:`api.example.com`,value:m,onInput:e=>h(e.currentTarget.value)})}),U(J,{id:`http-grant-port`,label:`Port`,children:e=>U(`input`,{...e,required:!0,type:`number`,min:1,max:65535,placeholder:`443`,value:g,onInput:e=>_(e.currentTarget.value)})}),de&&U(S,{children:[U(`fieldset`,{class:`collection-field`,children:[U(`legend`,{children:`Methods`}),U(`p`,{children:b.length===0?`Any method`:`Only the listed methods`}),b.map((e,t)=>U(`div`,{class:`form-actions`,children:[U(`input`,{"aria-label":`Method ${t+1}`,required:!0,maxLength:32,pattern:"[A-Z0-9!#$%&'*+.^_`\\|~\\-]+",placeholder:`GET`,value:e,onInput:e=>x(b.map((n,r)=>r===t?e.currentTarget.value:n))}),U(`button`,{type:`button`,onClick:()=>{x(b.filter((e,n)=>n!==t))},children:`Remove method`})]})),U(`button`,{type:`button`,disabled:b.length>=32,onClick:()=>{x([...b,`GET`])},children:`Add method`})]}),U(J,{id:`http-grant-path-kind`,label:`Path match`,children:e=>U(`select`,{...e,value:C,onChange:e=>w(e.currentTarget.value),children:[U(`option`,{value:`any`,children:`Any path`}),U(`option`,{value:`exact`,children:`Exact path`}),U(`option`,{value:`segment_prefix`,children:`Path and descendants`})]})}),C!==`any`&&U(J,{id:`http-grant-path`,label:`Path`,hint:`Slash, literal @ and unreserved characters only; query, header and body matching are not supported.`,children:e=>U(`input`,{...e,required:!0,maxLength:4096,placeholder:`/v1/resources`,value:T,onInput:e=>E(e.currentTarget.value)})})]})]}),U(`div`,{class:`form-section`,role:`group`,"aria-label":`Permissions and expiry`,children:[f===`allow_requests`&&U(J,{id:`http-grant-credential`,label:`Credential (optional)`,hint:k||`Only HTTPS credentials covering this entire destination are eligible.`,children:e=>U(`select`,{...e,value:k,onChange:e=>A(e.currentTarget.value),children:[U(`option`,{value:``,children:`No credential`}),k!==``&&!R.some(e=>e.id===k)&&U(`option`,{value:k,children:[`Unavailable credential · `,k]}),R.map(e=>U(`option`,{value:e.id,children:[e.name,a.filter(t=>t.name===e.name).length>1?` · ${e.id}`:``,e.available?``:` — unavailable`]}))]})}),fe&&U(`label`,{class:`checkbox-field`,for:`http-grant-private`,children:[U(`input`,{id:`http-grant-private`,type:`checkbox`,checked:D,"aria-describedby":`http-grant-private-hint`,onChange:e=>O(e.currentTarget.checked)}),U(`span`,{children:[U(`strong`,{children:`Allow local/private destinations`}),U(`small`,{id:`http-grant-private-hint`,children:`Permits loopback and private networks within this grant. Metadata, link-local and Gateway endpoints remain forbidden.`})]})]}),U(J,{id:`http-grant-expiry`,label:`Expires (optional)`,children:e=>U(`input`,{...e,type:`datetime-local`,value:N,onInput:e=>ee(e.currentTarget.value)})})]}),oe&&U(K,{state:`error`,title:`Check the proposed policy`,children:U(`p`,{children:`Use a valid agent, destination, future expiry and compatible credential.`})}),U(Ru,{state:ue.state}),U(`div`,{class:`form-actions`,children:[U(`button`,{ref:le,class:`${t===void 0?`create-action`:`primary-action`} form-submit-action`,disabled:ue.blocked||ve||o||s||e.unavailable||t!==void 0&&!ge,children:ue.state.state===`submitting`?`Applying grant…`:t===void 0?`Review and create`:`Review changes`}),t!==void 0&&U(S,{children:U(`button`,{ref:I,type:`button`,disabled:ue.blocked,onClick:()=>ge?ne(!0):e.onCancel?.(),children:`Cancel`})})]})]}),t!==void 0&&U(`section`,{class:`detail-group`,"aria-label":`Delete grant`,children:[U(`h3`,{children:`Delete grant`}),U(`button`,{ref:re,type:`button`,class:`danger-action`,disabled:ue.blocked||ve||e.unavailable,onClick:()=>{ie.current=re.current,te(`delete`)},children:`Delete grant`})]}),U(jn,{id:`http-grant-discard`,open:F,title:`Discard grant changes?`,consequence:`Your unsaved changes will be lost.`,confirmLabel:`Discard changes`,returnFocus:I,onCancel:()=>ne(!1),onConfirm:()=>e.onCancel?.()}),U(jn,{id:`http-grant-confirm`,open:P!==void 0,title:P===`delete`?`Delete HTTP grant`:`Apply HTTP grant`,consequence:P===`delete`?`Remove this grant. Other grants and the agent default still apply.`:U(S,{children:[t===void 0?U(`section`,{"aria-label":`Proposed grant`,children:[U(`h3`,{children:`Proposed grant`}),U(`dl`,{class:`detail-facts`,children:[U(`div`,{children:[U(`dt`,{children:`Description`}),U(`dd`,{children:u||`Unnamed HTTP grant`})]}),U(`div`,{children:[U(`dt`,{children:`Agent`}),U(`dd`,{children:[i.find(e=>e.id===c)?.displayName??`Agent`,` `,`· `,c]})]}),U(Pu,{policy:pe}),U(`div`,{children:[U(`dt`,{children:`Expires`}),U(`dd`,{children:U(Y,{value:me,fallback:`No expiry`})})]})]})]}):U(Fu,{current:t,proposed:{description:u,principal_id:c,policy:pe,expires_at:me},principals:i}),pe.type===`allow_tunnel`&&U(`p`,{children:`Opaque tunnel bypass: request method/path checks and credential injection do not apply inside this tunnel.`}),pe.allow_private&&U(`p`,{children:`Permits local/private destinations within this grant.`}),pe.credential_id!==void 0&&U(`p`,{children:`The selected credential will be injected into matching HTTPS requests.`})]}),confirmLabel:P===`delete`?`Delete grant`:`Apply grant`,destructive:P===`delete`,returnFocus:ie,onCancel:()=>te(void 0),onConfirm:ye})]})}function Hu(e){let[t,n]=z([]),[r,i]=z(``),[a,o]=z(!1),[s,c]=z(``),[l,u]=z(`GET`),[d,f]=z(``),[p,m]=z(``),[h,g]=z(`443`),[_,v]=z(),[y,b]=z(!1),[x,C]=z(!1),w=V(0);return B(()=>{let t=!0;return Qo(e.session).then(e=>{t&&n(e)}).catch(()=>{t&&b(!0)}),()=>{t=!1,w.current++}},[]),U(`section`,{class:`panel domain-panel`,children:[U(`p`,{children:`Policy only. No request is sent. Network, TLS and secret material are unverified; this result is not future admission authority.`}),U(`form`,{onInput:()=>{w.current++,v(void 0)},onSubmit:t=>{t.preventDefault();let n=++w.current;C(!0),b(!1),v(void 0),e.session.runProtected(async e=>{let t=JSON.stringify({principal_id:r,...a?{connect:{host:p,port:Number(h)}}:{url:s,method:l===`custom`?d:l}}),i=await fetch(`/api/v2/http/access-preview`,{method:`POST`,credentials:`same-origin`,redirect:`error`,signal:e.signal,headers:{"Content-Type":`application/json`,"X-CSRF-Token":e.csrfToken},body:t});if(await e.sessionLost(i))return;if(!i.ok)throw Error(`Preview unavailable.`);let o=St(await Du(i),r,a);w.current===n&&v(o)}).catch(()=>{w.current===n&&b(!0)}).finally(()=>C(!1))},children:[U(J,{id:`preview-principal`,label:`Agent`,...r?{hint:r}:{},children:e=>U(`select`,{...e,required:!0,value:r,onChange:e=>i(e.currentTarget.value),children:[U(`option`,{value:``,children:`Select agent`}),t.map(e=>U(`option`,{value:e.id,children:[e.displayName,t.filter(t=>t.displayName===e.displayName).length>1?` · ${e.id}`:``]}))]})}),U(J,{id:`preview-kind`,label:`Access type`,children:e=>U(`select`,{...e,value:a?`connect`:`request`,onChange:e=>o(e.currentTarget.value===`connect`),children:[U(`option`,{value:`request`,children:`HTTP request`}),U(`option`,{value:`connect`,children:`CONNECT destination`})]})}),a?U(S,{children:[U(J,{id:`preview-host`,label:`Host`,children:e=>U(`input`,{...e,required:!0,maxLength:253,value:p,onInput:e=>m(e.currentTarget.value)})}),U(J,{id:`preview-port`,label:`Port`,children:e=>U(`input`,{...e,required:!0,type:`number`,min:1,max:65535,value:h,onInput:e=>g(e.currentTarget.value)})})]}):U(S,{children:[U(J,{id:`preview-url`,label:`URL`,children:e=>U(`input`,{...e,required:!0,type:`url`,maxLength:8192,placeholder:`https://api.example.com/v1/resource`,value:s,onInput:e=>c(e.currentTarget.value)})}),U(J,{id:`preview-method`,label:`Method`,children:e=>U(`select`,{...e,value:l,onChange:e=>u(e.currentTarget.value),children:[[`GET`,`HEAD`,`POST`,`PUT`,`PATCH`,`DELETE`,`OPTIONS`,`TRACE`].map(e=>U(`option`,{value:e,children:e})),U(`option`,{value:`custom`,children:`Custom`})]})}),l===`custom`&&U(J,{id:`preview-custom-method`,label:`Custom method`,hint:`Use an uppercase HTTP method token. For CONNECT, select CONNECT destination above.`,children:e=>U(`input`,{...e,required:!0,maxLength:32,pattern:"(?!CONNECT$)[A-Z0-9!#$%&'*+.^_`\\|~\\-]+",value:d,onInput:e=>f(e.currentTarget.value)})})]}),U(`button`,{class:`form-submit-action`,disabled:x,children:`Test access`})]}),y&&U(K,{state:`error`,title:`Access preview unavailable`,children:U(`p`,{children:`Check the coordinates and current agent state.`})}),_!==void 0&&U(Uu,{result:_})]})}function Uu({result:e}){let t=mt(e.decision);return U(`section`,{class:`detail-group`,"aria-live":`polite`,children:[U(`h3`,{children:{destination_block:`Blocked by a destination grant`,request_block:`Blocked by a request grant`,request_allow:`Allowed by request policy`,principal_default:`Agent default: ${is(e.default)}`,tunnel_allow:`Opaque tunnel allowed; request policy and injection bypassed`,intercept_required:`Interception required; each decrypted request needs its own evaluation`,credential_conflict:`Blocked: matching grants require different credentials`,credential_unavailable:`Blocked: selected credential has no available material binding`,address_forbidden:`Blocked: destination address is forbidden`,private_permission_required:`Blocked: a matching local/private allow is required`}[String(t.reason)]??`Policy result unavailable`}),U(`dl`,{class:`detail-facts`,children:[U(`div`,{children:[U(`dt`,{children:`Policy revision`}),U(`dd`,{children:String(t.policy_revision)})]}),U(`div`,{children:[U(`dt`,{children:`HTTP default`}),U(`dd`,{children:is(e.default)})]}),U(`div`,{children:[U(`dt`,{children:`Default revision`}),U(`dd`,{children:String(t.default_revision)})]}),U(`div`,{children:[U(`dt`,{children:`Transport`}),U(`dd`,{children:String(t.transport)})]}),U(`div`,{children:[U(`dt`,{children:`Local/private permission`}),U(`dd`,{children:t.private_grant===void 0?`Explicit matching allow required`:`Matching permission present`})]}),U(`div`,{children:[U(`dt`,{children:`Agent`}),U(`dd`,{children:[U(`a`,{href:`#/agents/${String(mt(t.principal).id)}`,children:String(mt(t.principal).id)}),` `,`· revision `,String(mt(t.principal).revision)]})]}),[`grant`,`private_grant`,`credential`,`credential_grant`,`conflict_credential`,`conflict_grant`].map(e=>{if(t[e]===void 0)return null;let n=mt(t[e]);return typeof n.id!=`string`||!pt.test(n.id)?null:U(`div`,{children:[U(`dt`,{children:{grant:`Deciding grant`,private_grant:`Local/private grant`,credential:`Credential`,credential_grant:`Credential grant`,conflict_credential:`Conflicting credential`,conflict_grant:`Conflicting grant`}[e]}),U(`dd`,{children:[U(`a`,{href:`#/http/${e.includes(`credential`)&&!e.includes(`grant`)?`credentials`:`grants`}/${n.id}`,children:n.id}),` `,`· revision `,String(n.revision)]})]})})]})]})}var Wu=()=>({key:``,items:[],next:null,item:void 0,live:!0,paused:!1,loaded:!1,error:!1,olderError:!1,missing:!1,notice:``,loadingOlder:!1});async function Gu(e,t){let n=await fetch(t,{headers:{"X-CSRF-Token":e.csrfToken},credentials:`same-origin`,redirect:`error`,signal:e.signal});if(await e.sessionLost(n))throw Error(`Session lost.`);return n}async function Ku(e){if(e.status!==200||e.headers.get(`Content-Type`)!==`application/json`)throw Error(`HTTP traffic unavailable.`);let t=await e.text();if(new TextEncoder().encode(t).byteLength>1048576)throw Error(`HTTP traffic response exceeds limit.`);return He(t)}async function qu(e){if(e.status!==409||e.headers.get(`Content-Type`)!==`application/problem+json`)return!1;let t=await e.text();if(t.length>4096)return!1;let n=He(t);return typeof n==`object`&&!!n&&`code`in n&&n.code===`stale_cursor`}function Ju(e,t){let n=new URLSearchParams({limit:`50`});for(let[t,r]of Object.entries(e))n.set(t.slice(7),r);return e.filter_principal&&n.set(`search_locale`,Intl.DateTimeFormat().resolvedOptions().locale),t!==null&&n.set(`cursor`,t),`/api/v2/http/traffic?${n}`}var Yu=class{views;related;value=Wu();serial=0;continuation=null;listeners=new Set;constructor(e,t){this.views=t,this.related=new Jn(e,t,`http-related`,`http-traffic`,async(e,t)=>{let n=H(e.viewKey).segments[1],r=Gt(await Ku(await Gu(e,`/api/v2/http/traffic/${n}`)));if(r.admission.id!==n)throw Error(`Mismatched parent`);if(r.admission.decision?.transport!==`intercept`)return{items:[],next:null};let i=await Gu(e,Ju({filter_connect_id:n},t));if(await qu(i))throw new Kn;let a=Bt(await Ku(i));if(a.items.some(e=>e.connect?.id!==n))throw Error(`Mismatched connection`);return{items:a.items,next:a.nextCursor}}),t.registerPanel({id:`http-traffic`,matches:e=>H(e)?.destination===`http-traffic`,invalidations:[`system_status`],shouldRefresh:e=>![`invalidation`,`reconnect`,`poll`].includes(e)||H(this.views.snapshot().viewKey)?.segments.length===2||this.value.live&&!this.value.paused,read:e=>this.read(e),publish:e=>this.publish(e)}),e.registerProtectedState(()=>{this.serial++,this.continuation=null,this.value=Wu(),this.emit()})}snapshot(){return this.value}subscribe(e){return this.listeners.add(e),e(this.value),()=>this.listeners.delete(e)}setLive(e){this.views.cancelPanelRead(`http-traffic`),this.serial++,this.continuation=null,this.value={...this.value,live:e,loadingOlder:!1},this.emit(),(!this.value.loaded||e&&!this.value.paused)&&this.refresh()}refresh(){this.continuation=null,this.views.refreshPanel(`http-traffic`)}resume(){this.serial++,this.value={...this.value,paused:!1},this.emit(),this.refresh()}async older(){if(this.value.loadingOlder||this.value.error||this.value.next===null||this.value.items.length>=500||this.value.key!==this.views.snapshot().viewKey||this.views.snapshot().panels[`http-traffic`]?.refreshing)return;this.serial++;let e=this.serial;this.continuation=this.value.next,this.value={...this.value,paused:!0,loadingOlder:!0,olderError:!1},this.emit();try{await this.views.refreshPanel(`http-traffic`)}finally{e===this.serial&&(this.value={...this.value,loadingOlder:!1},this.emit())}}async read(e){let t=H(e.viewKey);if(t?.destination!==`http-traffic`)throw Error(`Invalid HTTP traffic location.`);this.value.key!==e.viewKey&&(this.serial++,this.continuation=null,this.value={...Wu(),key:e.viewKey,live:this.value.live,paused:this.value.paused,notice:this.value.paused&&t.segments.length===1?`Showing the latest entries. Older results could not be continued.`:``},this.emit());let n={key:e.viewKey,serial:this.serial,automatic:[`invalidation`,`reconnect`,`poll`].includes(e.reason??``)},r=t.segments[1];if(r!==void 0){let t=await Gu(e,`/api/v2/http/traffic/${r}`);if(t.status===404)return{...n,kind:`missing`};let i=Gt(await Ku(t));if(i.admission.id!==r)throw Error(`Mismatched HTTP traffic identity.`);return{...n,kind:`item`,item:i}}let i=e.reason===`panel`?this.continuation:null;this.continuation=null;let a=i!==null;try{let r=await Gu(e,Ju(t.query,i));if(a&&await qu(r)){if(e.signal.aborted)throw Error(`Superseded.`);a=!1,this.value={...this.value,items:[],next:null,loaded:!1,notice:`Showing the latest entries. Older results could not be continued.`},this.emit(),r=await Gu(e,Ju(t.query,null))}let o=Bt(await Ku(r));if(o.items.length>50)throw Error(`Invalid HTTP page size.`);if(a&&(this.value.items.length+o.items.length>500||o.items.some(e=>this.value.items.some(t=>t.id===e.id))))throw Error(`Repeated HTTP traffic evidence.`);return{...n,kind:`page`,page:o,append:a}}catch(t){if(e.signal.aborted)throw t;return{...n,kind:`failure`,append:a}}}publish(e){e.key!==this.value.key||e.automatic&&(e.serial!==this.serial||!this.value.live||this.value.paused)&&e.kind!==`item`&&e.kind!==`missing`||(this.value=e.kind===`page`?{...this.value,items:e.append?[...this.value.items,...e.page.items]:e.page.items,next:e.page.nextCursor,loaded:!0,error:!1,olderError:!1,loadingOlder:!1}:e.kind===`item`?{...this.value,item:e.item,error:!1,missing:!1}:e.kind===`missing`?{...this.value,item:void 0,missing:!0}:{...this.value,error:!e.append,olderError:e.append,loadingOlder:!1},this.emit())}emit(){for(let e of this.listeners)e(this.value)}};function Xu({controller:e,principals:t,view:n,navigate:r}){let[i,a]=z(e.snapshot()),[o,s]=z(t.snapshot());B(()=>e.subscribe(a),[e]),B(()=>t.subscribe(s),[t]);let c=H(n.viewKey),l=c?.query??{},u=i.key===n.viewKey?i:{...Wu(),live:i.live,paused:i.paused},d=e=>ln({destination:`http-traffic`,segments:e===void 0?[`http-traffic`]:[`http-traffic`,e],query:l}),f=n.panels[`http-traffic`];return c?.segments.length===2?U(`div`,{class:`domain-view`,children:[U(`nav`,{class:`detail-navigation`,"aria-label":`HTTP traffic navigation`,children:U(`a`,{href:d(),children:`Back to HTTP traffic`})}),U(`header`,{class:`detail-context`,"data-testid":`detail-context`,children:[U(`div`,{class:`detail-context-heading`,children:[U(`h1`,{id:`http-traffic-page-title`,tabindex:-1,children:u.item?.admission.target?u.item.admission.target.scheme?`HTTP request`:`CONNECT exchange`:`HTTP traffic`}),u.item&&U(ed,{item:u.item,stale:f?.status===`error`})]}),U(`div`,{class:`copyable-value`,children:U(`code`,{children:c.segments[1]})})]}),u.missing?U(K,{state:`empty`,title:`Traffic record unavailable`,children:`It may have been pruned. Missing evidence does not prove nonexecution.`}):u.item===void 0?U(K,{state:f?.status===`error`?`error`:`loading`,title:f?.status===`error`?`HTTP traffic unavailable`:`Loading HTTP traffic…`}):U(S,{children:[f?.status===`error`&&U(K,{state:`error`,title:`Refresh failed. This evidence may be stale.`}),U(td,{item:u.item,link:d}),u.item.admission.decision?.transport===`intercept`&&U(Qu,{controller:e.related,view:n,link:d})]})]}):U(`section`,{class:`panel domain-panel`,"aria-label":`HTTP traffic history`,"data-testid":`http-traffic-view`,children:[U(`div`,{class:`collection-toolbar live-collection-toolbar`,children:[U(`label`,{for:`http-traffic-live-mode`,children:`Live mode`}),U(On,{attributes:{id:`http-traffic-live-mode`},checked:u.live,showState:!1,onChange:t=>e.setLive(t)})]}),U(Zu,{query:l,navigate:r}),u.paused&&U(`div`,{class:`inline-actions`,children:[u.live&&U(G,{state:`warning`,children:`Live paused while viewing older results`}),U(`button`,{type:`button`,onClick:()=>e.resume(),children:u.live?`Resume live`:`Return to newest`})]}),u.notice&&U(K,{state:`warning`,title:u.notice}),(u.error||f?.status===`error`)&&U(K,{state:`error`,title:`HTTP traffic unavailable`,children:`Previously loaded traffic may be stale.`}),u.loaded?U(S,{children:[U(Dn,{caption:`HTTP traffic records`,localStale:u.error||u.olderError||f?.status===`error`,layout:`activity`,rowHeaderKey:`destination`,rowKey:e=>e.id,items:u.items,itemNames:{singular:`traffic record`,plural:`traffic records`},emptyTitle:Object.keys(l).length?`No matching HTTP traffic`:`No HTTP traffic yet`,columns:[{key:`admitted`,role:`time`,label:`Admitted`,render:e=>U(Y,{value:e.admitted_at})},{key:`destination`,role:`identity`,label:`Destination`,render:e=>U(q,{primary:U(`a`,{href:d(e.id),children:Kt(e.target)}),secondary:e.id})},{key:`principal`,role:`relation`,label:`Agent`,render:e=>U(q,{primary:U(`a`,{href:`#/agents/${e.principal_id}`,children:o.get(e.principal_id)??`Agent`}),secondary:e.principal_id})},{key:`type`,role:`status`,label:`Type`,render:e=>W(e.type)},{key:`decision`,role:`text`,label:`Decision`,render:e=>U(S,{children:[U(G,{state:e.decision===`allow`?`current`:`neutral`,children:Ut(e.decision,e.type)}),e.type===`invalid`&&e.rejection!==void 0&&U(`div`,{children:Nt(e.rejection)})]})},{key:`outcome`,role:`status`,label:`Outcome`,render:e=>U(S,{children:[U(G,{state:Ht(e)===`succeeded`?`current`:Ht(e)===`outcome_unknown`?`warning`:[`not_dispatched`,`interception_selected`].includes(Ht(e))?`neutral`:`error`,children:e.decision===`intercept`?`—`:W(Ht(e))}),e.type===`request`&&e.decision===`allow`&&U(`div`,{children:zt(e.completion_recorded,e.termination)})]})}]}),U(`div`,{class:`history-continuation`,children:[u.loaded&&u.next===null&&!u.error&&!u.olderError&&f?.status!==`error`&&U(`span`,{children:`No older HTTP traffic records`}),u.loaded&&U(hn,{count:u.items.length,singular:`HTTP traffic record`,plural:`HTTP traffic records`,matching:Object.keys(l).length>0,stale:u.error||f?.status===`error`}),u.next!==null&&u.items.length<500&&!u.error&&f?.status!==`error`&&U(`button`,{type:`button`,disabled:u.loadingOlder,onClick:()=>void e.older(),children:u.loadingOlder?`Loading…`:`Load older HTTP traffic records`})]}),u.olderError&&U(K,{state:`error`,title:`Older traffic unavailable`,children:`Loaded records are retained. Use Load older HTTP traffic records to try this read again.`}),u.items.length>=500&&U(`p`,{children:`500 records loaded. Narrow the filters or return to newest.`})]}):!u.error&&f?.status!==`error`?U(K,{state:`loading`,title:`Loading HTTP traffic…`}):null]})}function Zu({query:e,navigate:t}){let[n,r]=z({...e}),[i,a]=z(!1);B(()=>{r({...e}),a(!1)},[JSON.stringify(e)]);let o=n=>{let r=Object.fromEntries(Object.entries(n).filter(([,e])=>e!==``));if(!Tt(r)){a(!0);return}a(!1),JSON.stringify(r)!==JSON.stringify(e)&&t(ln({destination:`http-traffic`,segments:[`http-traffic`],query:r}))};return mn(n,o),U(S,{children:[U(Wn,{query:e}),U(`div`,{class:`table-filters collection-query-filters`,role:`group`,"aria-label":`HTTP traffic filters`,children:[[[`destination`,`Destination host`],[`principal`,`Agent`]].map(([e,t])=>U(`input`,{type:`search`,"aria-label":t,placeholder:t,value:n[`filter_${e}`]??``,onInput:t=>r({...n,[`filter_${e}`]:t.currentTarget.value})})),Object.entries(wt).map(([e,t])=>U(`select`,{"aria-label":W(e),value:n[`filter_${e}`]??``,onChange:t=>{let i={...n,[`filter_${e}`]:t.currentTarget.value};r(i),o(i)},children:[U(`option`,{value:``,children:[W(e),`: any`]}),t.map(t=>U(`option`,{value:t,children:e===`decision`&&t===`intercept`?`Interception selected`:W(t)}))]})),U(`button`,{type:`button`,disabled:!Object.values(n).some(Boolean)&&!Object.values(e).some(Boolean),onClick:()=>{r({}),o({})},children:`Reset`})]}),(e.filter_connect_id||e.filter_principal_id)&&U(`div`,{class:`table-filters`,role:`group`,"aria-label":`HTTP traffic context filters`,children:[e.filter_connect_id&&U(`span`,{class:`inline-actions`,children:[`Related to CONNECT`,` `,U(`a`,{href:ln({destination:`http-traffic`,segments:[`http-traffic`,e.filter_connect_id],query:{}}),children:U(`code`,{children:e.filter_connect_id})}),U(`button`,{type:`button`,onClick:()=>{let e={...n};delete e.filter_connect_id,r(e),o(e)},children:`Remove connection filter`})]}),e.filter_principal_id&&U(`span`,{class:`inline-actions`,children:[`Exact agent ID: `,U(`code`,{children:e.filter_principal_id}),U(`button`,{type:`button`,onClick:()=>{let e={...n};delete e.filter_principal_id,r(e),o(e)},children:`Remove exact agent filter`})]})]}),i&&U(K,{state:`error`,title:`Use searches of at most 256 UTF-8 bytes without control characters.`})]})}function Qu({controller:e,view:t,link:n}){let[r,i]=z(e.snapshot());B(()=>e.subscribe(i),[e]);let a=r.key===t.viewKey?r:void 0;return U(`section`,{class:`panel domain-panel`,"aria-label":`Requests on this connection`,children:[U(`div`,{class:`panel-heading`,children:[U(`h2`,{children:`Requests on this connection`}),U(`button`,{type:`button`,disabled:a?.loading,onClick:()=>e.refresh(),children:`Refresh requests`})]}),a?.notice&&U(K,{state:`warning`,title:a.notice}),a?.error&&U(K,{state:`error`,title:`Related requests unavailable`,children:`Previously loaded requests may be stale. Refresh to try again.`}),!a?.loaded&&!a?.error&&U(K,{state:`loading`,title:`Loading related requests…`}),a?.loaded&&U(Dn,{caption:`Related HTTP requests`,layout:`activity`,rowHeaderKey:`request`,rowKey:e=>e.id,items:a.items,emptyTitle:`No related requests recorded`,localStale:a.error,columns:[{key:`time`,label:`Admitted`,role:`time`,render:e=>U(Y,{value:e.admitted_at})},{key:`request`,label:`Request`,role:`identity`,render:e=>U(q,{primary:U(`a`,{href:n(e.id),children:Kt(e.target)}),secondary:e.id})},{key:`decision`,label:`Decision`,role:`status`,render:e=>U(G,{state:e.decision===`allow`?`current`:`neutral`,children:Ut(e.decision,e.type)})},{key:`outcome`,label:`Outcome`,role:`status`,render:e=>U(G,{state:Ht(e)===`succeeded`?`current`:Ht(e)===`outcome_unknown`?`warning`:[`not_dispatched`,`interception_selected`].includes(Ht(e))?`neutral`:`error`,children:e.decision===`intercept`?`—`:W(Ht(e))})}]}),U(`div`,{class:`collection-pagination`,children:[a?.loaded&&U(hn,{count:a.items.length,singular:`request`,plural:`requests`,matching:!1,stale:a.error}),a?.next&&a.items.length<500&&U(`button`,{type:`button`,disabled:a.loading,onClick:()=>e.more(),children:`Load older requests`})]})]})}function $u(e){return e===`gateway`?`Gateway`:e===`upstream`?`Upstream`:`Unavailable`}function ed({item:e,stale:t}){let n=e.admission.decision,r=n?.transport===`intercept`?`interception_selected`:e.completion?.outcome?String(e.completion.outcome):n?.allowed?`outcome_unknown`:`not_dispatched`;return U(G,{state:t?`stale`:r===`succeeded`?`current`:r===`outcome_unknown`?`warning`:[`not_dispatched`,`interception_selected`].includes(r)?`neutral`:`error`,children:W(r)})}function td({item:e,link:t}){let n=e.admission,r=n.decision,i=e.completion,a=i?.termination,o=n.rejection,s=n.connect,c=r?.transport===`intercept`&&r?.reason===`intercept_required`,l=n.target!==null&&n.target.scheme===void 0;return U(S,{children:[U(`section`,{class:`detail-section`,children:[U(`h2`,{children:`Admission`}),U(`dl`,{class:`detail-facts`,children:[U(`div`,{children:[U(`dt`,{children:`Destination`}),U(`dd`,{children:Kt(n.target)})]}),U(`div`,{children:[U(`dt`,{children:`Admitted`}),U(`dd`,{children:U(Y,{value:String(n.admitted_at)})})]}),U(`div`,{children:[U(`dt`,{children:`Decision time`}),U(`dd`,{children:U(Y,{value:String(n.evaluated_at)})})]}),U(`div`,{children:[U(`dt`,{children:`Reason`}),U(`dd`,{children:r===null?Nt(o):c?`Interception selected`:l?r.allowed?`Opaque tunnel allowed`:`CONNECT denied`:W(String(r.reason))})]}),U(`div`,{children:[U(`dt`,{children:`Transport`}),U(`dd`,{children:r===null?`None`:W(String(r.transport))})]})]}),o!==void 0&&U(`details`,{children:[U(`summary`,{children:`Rejection codes`}),U(`p`,{children:[o.stage,` · `,o.reason]})]}),!l&&U(`dl`,{class:`detail-facts`,children:[U(`div`,{children:[U(`dt`,{children:`Connection`}),U(`dd`,{children:s===void 0?`Unavailable`:U(`a`,{href:t(s.id),children:[`CONNECT `,s.host,`:`,s.port,` ·`,` `,U(`code`,{children:s.id})]})})]}),s!==void 0&&U(`div`,{children:[U(`dt`,{children:`Destination inherited from CONNECT`}),U(`dd`,{children:Kt({host:s.host,port:s.port})})]})]}),s!==void 0&&U(`p`,{children:`Connection context does not validate the inner request target.`}),r?.transport===`tunnel`&&U(`p`,{children:`Opaque tunnel: inner HTTP requests are not visible.`})]}),U(`section`,{class:`detail-section`,children:[U(`h2`,{children:`Outcome`}),U(`dl`,{class:`detail-facts`,children:U(`div`,{children:[U(`dt`,{children:`Response source`}),U(`dd`,{children:$u(o===void 0?i?.response_source:`gateway`)})]})}),o!==void 0&&U(`p`,{children:`Gateway rejection. Response delivery is not recorded.`}),i===null?U(K,{state:r?.allowed?`warning`:`neutral`,title:c?`Interception selected`:r?.allowed?`Unknown outcome`:l?`CONNECT denied`:`Not dispatched`,children:c?Wt:r?.allowed?`Missing terminal evidence does not prove nonexecution or safe retry.`:void 0}):U(`dl`,{class:`detail-facts`,children:Object.entries(i).filter(([e])=>e!==`response_source`&&e!==`termination`).map(([e,t])=>U(`div`,{children:[U(`dt`,{children:W(e)}),U(`dd`,{children:e===`completed_at`?U(Y,{value:String(t)}):W(String(t))})]}))}),!l&&r?.allowed&&U(`dl`,{class:`detail-facts`,children:[U(`div`,{children:[U(`dt`,{children:`HTTP transfer`}),U(`dd`,{children:zt(i!==null,a)})]}),a!==void 0&&U(S,{children:[U(`div`,{children:[U(`dt`,{children:`Observed stage`}),U(`dd`,{children:W(a.stage)})]}),U(`div`,{children:[U(`dt`,{children:`Observed condition`}),U(`dd`,{children:W(a.condition)})]}),a.context!==void 0&&U(`div`,{children:[U(`dt`,{children:`Request context`}),U(`dd`,{children:W(a.context)})]})]})]}),a!==void 0&&U(`details`,{children:[U(`summary`,{children:`Transfer evidence limits`}),U(`p`,{children:`HTTP transfer evidence does not establish application success or who initiated cancellation.`})]}),!l&&i?.outcome===`outcome_unknown`&&U(`p`,{children:`The request may have taken effect. Retrying may repeat effects.`})]}),U(`section`,{class:`detail-section`,children:[U(`h2`,{children:`Admission-time authority`}),U(`dl`,{class:`detail-facts`,children:[[[`Agent`,n.principal],[`Agent credential`,n.agent_credential]].map(([e,t])=>{let n=t;return U(`div`,{children:[U(`dt`,{children:String(e)}),U(`dd`,{children:[U(`code`,{children:n.id}),` · revision `,n.revision]})]})}),r!==null&&U(S,{children:[U(`div`,{children:[U(`dt`,{children:`Policy revision`}),U(`dd`,{children:String(r.policy_revision)})]}),U(`div`,{children:[U(`dt`,{children:`Default`}),U(`dd`,{children:[W(String(n.default)),` · revision`,` `,String(r.default_revision)]})]})]})]}),U(`details`,{children:[U(`summary`,{children:`Exact authority references`}),U(yn,{value:{decision:n.decision,material:n.material},label:`Admission-time references`})]}),U(`details`,{children:[U(`summary`,{children:`Matched policy selectors`}),U(yn,{value:n.grants,label:`Recorded policy selectors`})]})]})]})}var nd=/^[0-7][0-9A-HJKMNP-TV-Z]{25}$/,rd={days:86400,hours:3600,minutes:60,seconds:1};function id(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`invalid response`);let n=e;if(Object.keys(n).sort().join(`,`)!==[...t].sort().join(`,`))throw Error(`invalid response`);return n}function ad(e){if(typeof e!=`string`)throw Error(`invalid response`);return e}function od(e){if(e!==null&&typeof e!=`string`)throw Error(`invalid response`);return e}function sd(e){let t=ad(e);if(!nd.test(t))throw Error(`invalid response`);return t}function cd(e){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`invalid response`);return e}function ld(e,t){let n=ad(e);if(!t.includes(n))throw Error(`invalid response`);return n}function ud(e,t){return e===null?null:ld(e,t)}function dd(e){let t=id(e,[..._r(e),`scope`,`target`,`constraint`,`duration_seconds`,`future_tools_acknowledged`]);if(t.constraint!==null&&(typeof t.constraint!=`object`||Array.isArray(t.constraint))||typeof t.future_tools_acknowledged!=`boolean`)throw Error(`invalid response`);let n=vr(t);if(n&&(t.scope!==`server`||t.constraint!==null||t.future_tools_acknowledged!==!0))throw Error(`invalid response`);return{readOnly:n,scope:ld(t.scope,[`tool`,`server`]),target:ad(t.target),constraint:t.constraint,durationSeconds:od(t.duration_seconds),futureToolsAcknowledged:t.future_tools_acknowledged}}var fd=[`id`,`principal_id`,`state`,`revision`,`requested_policy`,`approved_policy`,`approved_grant_id`,`rejection_reason`,`created_at`,`updated_at`,`closed_at`];function pd(e){let t=id(e,fd),n=od(t.approved_grant_id);if(n!==null&&!nd.test(n))throw Error(`invalid response`);return{id:sd(t.id),principalID:sd(t.principal_id),state:ld(t.state,[`pending`,`approved`,`rejected`,`cancelled`]),revision:ad(t.revision),requestedPolicy:dd(t.requested_policy),approvedPolicy:t.approved_policy===null?null:dd(t.approved_policy),approvedGrantID:n,rejectionReason:od(t.rejection_reason),createdAt:ad(t.created_at),updatedAt:ad(t.updated_at),closedAt:od(t.closed_at)}}function md(e){let t=id(e,[`server_id`,`tool_id`,`namespace`,`upstream_name`,`external_name`,`catalog_revision`,`fingerprint`,`durable_state`,`descriptor`,`captured_at`]);return{serverID:sd(t.server_id),toolID:sd(t.tool_id),namespace:ad(t.namespace),upstreamName:ad(t.upstream_name),externalName:ad(t.external_name),catalogRevision:ad(t.catalog_revision),fingerprint:ad(t.fingerprint),durableState:ld(t.durable_state,[`current`,`retired`]),descriptor:cd(t.descriptor),capturedAt:ad(t.captured_at)}}function hd(e){let t=id(e,[`scope`,`target_state`,`active_state`,`durable_state`,`catalog_revision`,`fingerprint`,`descriptor`]);return{scope:ld(t.scope,[`tool`,`server`]),targetState:ld(t.target_state,[`extant`,`deleted`]),activeState:ud(t.active_state,[`current`,`stale`,`absent`,`unavailable`]),durableState:ud(t.durable_state,[`current`,`retired`,`absent`]),catalogRevision:od(t.catalog_revision),fingerprint:od(t.fingerprint),descriptor:t.descriptor===null?null:cd(t.descriptor)}}function gd(e,t,n){let r=id(e,[...fd,`resolved_server_id`,`resolved_upstream_name`,`submitted_evidence`,`approved_evidence`,`current_target`]),i=pd(Object.fromEntries(fd.map(e=>[e,r[e]]))),a=od(r.resolved_upstream_name);return{...i,submittedConstraintSource:xd(n),approvedConstraintSource:xd(n,`approved_policy`),approvedPolicySource:i.approvedPolicy===null?null:bd(n,`approved_policy`),resolvedServerID:sd(r.resolved_server_id),resolvedUpstreamName:a,submittedEvidence:r.submitted_evidence===null?null:md(r.submitted_evidence),approvedEvidence:r.approved_evidence===null?null:md(r.approved_evidence),currentTarget:hd(r.current_target),etag:t}}function _d(e){return{Accept:`application/json`,"X-CSRF-Token":e.csrfToken}}function vd(e,t){if(e[t]!==`"`)throw Error(`invalid response`);for(let n=t+1;n{let n=await fetch(t,{credentials:`same-origin`,redirect:`error`,signal:e.signal,headers:_d(e)});if(await e.sessionLost(n))return;let r=n.headers.get(`Content-Type`);if(r!==`application/json`&&r!==`application/problem+json`)throw Error(`Request data is unavailable.`);let i=await n.text();return{response:n,value:JSON.parse(i),source:i}})}function Cd(e){let t=id(e,[`request`,`principal_display_name`,`server_display_name`,`resolved_server_id`,`resolved_upstream_name`]);return{...pd(t.request),principalName:ad(t.principal_display_name),serverName:ad(t.server_display_name),serverID:sd(t.resolved_server_id),upstreamName:od(t.resolved_upstream_name)}}function wd(e,t,n,r){let i=new URLSearchParams({limit:`50`,sort:t.sort??`submitted`,direction:t.direction??(t.sort===void 0&&t.queue===`all`?`descending`:`ascending`)});for(let e of[`request`,`principal`,`target`,`scope`,`state`]){let n=t[`filter_${e}`];n!==void 0&&i.set(e,n)}return t.queue!==`all`&&i.set(`state`,`pending`),n!==null&&i.set(`cursor`,n),Mr(e,`/api/v2/mcp/grant-requests?${i}`,Cd,r)}async function Td(e,t){let n=await Sd(e,`/api/v2/mcp/grant-requests/${t}`);if(n===void 0)return;if(!n.response.ok)throw Error(`Request data is unavailable.`);let r=n.response.headers.get(`ETag`);if(r===null||r!==`"grant-request-${t}-${n.value.revision}"`)throw Error(`The current request revision is unavailable.`);return gd(n.value,r,n.source)}function Ed(e){if(e===null)return`No expiry`;for(let[t,n]of Object.entries(rd))if(Number(e)%n===0){let r=Number(e)/n;return`${r} ${r===1?t.slice(0,-1):t}`}return`${e} seconds`}function Dd({source:e,locked:t=!1}){if(e===null||e===``)return U(`p`,{children:`No argument restrictions`});try{let n=Pd(JSON.parse(e));return U(`div`,{children:[U(`ul`,{class:`request-conditions`,children:[`equals`,`regex`].flatMap(r=>Object.keys(n[r]).map(n=>U(`li`,{children:[t&&U(`strong`,{children:`Locked · `}),U(`code`,{children:n}),` `,r===`equals`?`equals`:`matches`,` `,U(`code`,{children:bd(bd(e,r),n)})]})))}),U(`details`,{children:[U(`summary`,{children:`Exact condition source`}),U(`textarea`,{"aria-label":`Exact condition source`,"data-testid":t?`approval-submitted-constraint`:void 0,class:`inert-json`,readOnly:!0,value:e})]})]})}catch{return U(K,{state:`error`,title:`Conditions unavailable`})}}function Od({policy:e,source:t,definition:n}){return U(`div`,{class:`request-access-summary`,children:[e.readOnly&&U(`p`,{children:`Includes current and future tools marked readOnlyHint=true. The Gateway does not verify that these tools are read-only; they may still change data.`}),U(`dl`,{class:`detail-facts`,children:[U(`div`,{children:[U(`dt`,{children:`Duration`}),U(`dd`,{children:[Ed(e.durationSeconds),e.durationSeconds!==null&&` from approval`]})]}),U(`div`,{children:[U(`dt`,{children:`Tool definition`}),U(`dd`,{children:n})]})]}),U(`section`,{"aria-label":`Conditions`,children:[U(`h3`,{children:`Conditions`}),U(Dd,{source:t})]})]})}function kd(e){let t=e.approvedPolicy??e.requestedPolicy,n=e.currentTarget.targetState===`deleted`?`The requested server has been deleted. `:e.currentTarget.durableState===`retired`?`Only a historical tool definition is available. `:e.currentTarget.activeState===`unavailable`?`The current tool definition is unavailable. `:``;if(t.scope===`server`)return`${n}Not applicable to server-wide authority`;let r=e.approvedPolicy!==null&&e.requestedPolicy.scope===`server`,i=r?e.approvedEvidence:e.submittedEvidence,a=r?`approval`:`submission`,o=r?`approved`:`submitted`,s=r?`${t.target} — `:``;return i===null||e.currentTarget.fingerprint===null||e.currentTarget.descriptor===null?`${n}${s}Comparison unavailable — missing tool definition`:n+s+(i.fingerprint===e.currentTarget.fingerprint?`Unchanged since ${a}`:`Changed since ${a} — inspect ${o} and current definitions`)}function Ad(e){return e.readOnly?`Read-only server tools`:e.scope===`server`?`All tools`:`Exact tool`}function jd(e){return U(`dl`,{class:`detail-facts`,children:[U(`div`,{children:[U(`dt`,{children:`Scope`}),U(`dd`,{children:[W(e.scope),` — `,Ad(e)]})]}),U(`div`,{children:[U(`dt`,{children:`Target`}),U(`dd`,{children:e.target})]}),U(`div`,{children:[U(`dt`,{children:`Duration`}),U(`dd`,{children:Ed(e.durationSeconds)})]}),U(`div`,{children:[U(`dt`,{children:`Future tools acknowledged`}),U(`dd`,{children:e.futureToolsAcknowledged?`Yes`:`No`})]})]})}function Md(e,t){let n=e=>[{label:`Access`,value:Ad(e)},{label:`Scope`,value:W(e.scope)},{label:`Tools`,value:e.target},{label:`Duration`,value:Ed(e.durationSeconds)},{label:`Future tools acknowledged`,value:e.futureToolsAcknowledged?`Yes`:`No`}],r=n(e);return U(xn,{label:`Requested versus approved authority`,beforeLabel:`Requested`,afterLabel:`Approved`,rows:n(t).map((e,t)=>({label:e.label,before:r[t].value,after:e.value,changed:r[t].value!==e.value}))})}function Nd({evidence:e,label:t}){return e===null?U(K,{state:`empty`,title:`${t}: no descriptor evidence`}):U(`section`,{class:`detail-group`,children:[U(`h3`,{children:[t,`: immutable descriptor evidence`]}),U(`p`,{children:e.durableState===`retired`?`Retired historical evidence; it is not proof of a callable tool.`:`Current when captured; current target comparison remains authoritative for present state.`}),U(`dl`,{class:`detail-facts`,children:[U(`div`,{children:[U(`dt`,{children:`Namespace / tool`}),U(`dd`,{children:[e.namespace,` / `,e.upstreamName]})]}),U(`div`,{children:[U(`dt`,{children:`Catalog revision`}),U(`dd`,{children:e.catalogRevision})]}),U(`div`,{children:[U(`dt`,{children:`Fingerprint`}),U(`dd`,{class:`technical-value`,children:e.fingerprint})]}),U(`div`,{children:[U(`dt`,{children:`Captured`}),U(`dd`,{children:U(Y,{value:e.capturedAt})})]})]}),U(`a`,{href:`#/mcp/servers/${e.serverID}/descriptors/${e.toolID}`,children:`Open retained descriptor`}),U(yn,{value:e.descriptor,label:`${t} normalized descriptor`})]})}function Pd(e){let t=cd(e),n=Object.keys(t),r=n.length===1&&n[0]===`equals`?1:t.version===2&&n.every(e=>[`version`,`equals`,`regex`].includes(e))&&(t.equals!==void 0||t.regex!==void 0)?2:void 0;if(r===void 0)throw Error(`invalid constraint`);let i=t.equals===void 0?{}:cd(t.equals),a=t.regex===void 0?{}:cd(t.regex),o=Object.keys(i).length+Object.keys(a).length;if(o<1||o>16||Object.values(i).some(e=>typeof e==`object`&&!!e)||Object.values(a).some(e=>typeof e!=`string`))throw Error(`invalid constraint`);return{version:r,equals:i,regex:a}}function Fd(e){if(e===void 0)return``;let t=e.trim();if(!t.startsWith(`{`)||!t.endsWith(`}`))throw Error(`invalid constraint`);return t.slice(1,-1).trim()}function Id(e,t){if(t===``)return e===null?``:Pd(JSON.parse(e)).version===2?e:`{"version":2,"equals":${bd(e,`equals`)}}`;let n;try{n=JSON.parse(t)}catch{throw Error(`Additional matcher atoms must be valid JSON.`)}let r=Pd(n);if(e===null)return t;if(r.version!==2)throw Error(`Additional matcher atoms must use version 2.`);let i=Pd(JSON.parse(e));for(let e of[`equals`,`regex`])if(Object.keys(r[e]).some(t=>Object.hasOwn(i[e],t)))throw Error(`Additional matcher atoms cannot replace a submitted operator and pointer.`);let a=`{"version":2,${[`equals`,`regex`].map(n=>{let r=[Fd(bd(e,n)),Fd(bd(t,n))].filter(e=>e!==``);return r.length===0?``:`${JSON.stringify(n)}:{${r.join(`,`)}}`}).filter(e=>e!==``).join(`,`)}}`;return Pd(JSON.parse(a)),a}function Ld({session:e,mutations:t,detail:n,onRefresh:r,onAcknowledged:i,onUncertain:a,principalName:o,serverName:s,readAvailable:c}){let l=n.requestedPolicy,[u]=z(()=>t.create()),[d,f]=z(()=>u.snapshot()),[p,m]=z(`approve`),[h,g]=z(!1),[_,v]=z(!1),[y,b]=z(!1),x=V(`not_approved`),C=V(),w=V(null),[T,E]=z(``),[D,O]=z(l.scope),[k,A]=z(l.readOnly),[j,M]=z(l.target),[N,ee]=z(),[P,te]=z(),[F,ne]=z(!1),[I,re]=z(!1),[ie,ae]=z([]),oe=Object.keys(rd).find(e=>l.durationSeconds!==null&&Number(l.durationSeconds)%rd[e]===0)??`minutes`,[se,ce]=z(oe),[L,le]=z(l.durationSeconds===null?``:String(Number(l.durationSeconds)/rd[oe])),ue=se===`seconds`?`60`:`1`,de=Number(ue)*rd[se]<=Math.min(2592e3,Number(l.durationSeconds??2592e3)),fe=L===``?``:String(Number(L)*rd[se]),[R,pe]=z(`not_approved`),me=V({description:``,scope:l.scope,readOnly:l.readOnly,target:l.target,additionalAtoms:[],duration:l.durationSeconds??``,reason:`not_approved`}),he=JSON.stringify({description:T,scope:D,readOnly:k,target:j,additionalAtoms:ie,duration:fe,reason:R}),ge=V(he);ge.current=he,Cr(he!==JSON.stringify(me.current));let[_e,ve]=z(),[ye,be]=z(!1),[xe,Se]=z(),[Ce,we]=z(!1),Te=V(null),Ee=V(null);B(()=>u.subscribe(f),[u]),B(()=>()=>u.close(),[u]);let De=l.scope===`server`&&D===`tool`;B(()=>{let t=new AbortController;return ne(!1),ee(void 0),De&&ko(e,n.resolvedServerID,t.signal).then(e=>{!t.signal.aborted&&e!==void 0&&ee(e)}).catch(()=>{t.signal.aborted||ne(!0)}),()=>t.abort()},[n.resolvedServerID,De,e]);let Oe=async e=>{if(e.headers.get(`Content-Type`)!==`application/json`)throw Error(`invalid response`);let t=await e.text(),n=JSON.parse(t),r=e.headers.get(`ETag`);if(r===null)throw Error(`invalid response`);return gd(n,r,t)},ke=N?.find(e=>e.externalName===j);B(()=>{let t=new AbortController;return re(!1),te(void 0),!De||ke===void 0||Ao(e,ke,t.signal).then(e=>{!t.signal.aborted&&e!==void 0&&te(e)}).catch(()=>{t.signal.aborted||re(!0)}),()=>t.abort()},[n.resolvedServerID,De,ke,e]);let Ae=De?P===void 0||P.serverID!==n.resolvedServerID||P.externalName!==j||P.id!==ke?.id?void 0:To(P.descriptor):n.currentTarget.descriptor===null?void 0:To(n.currentTarget.descriptor),je=j===``?`Choose a tool`:F?`Unavailable`:N===void 0?`Loading…`:ke===void 0?`Unknown`:`Known`,Me=F?`Catalog unavailable. Manual entry is still available.`:ke===void 0?null:I?`Schema unavailable. Manual conditions are still available.`:Ae===void 0?`Loading schema…`:null,Ne=()=>ie.length===0?``:Fo(ie),Pe=()=>{if(l.readOnly&&(!k||D!==`server`))throw Error(`A read-only server request must retain read-only server scope.`);if(k&&D!==`server`)throw Error(`Read-only access requires server scope.`);if(l.scope===`tool`&&(D!==`tool`||j!==l.target))throw Error(`A tool request cannot change scope or target.`);if(l.scope===`server`&&D===`server`&&j!==l.target)throw Error(`A server approval cannot broaden to another target.`);if(j.length===0)throw Error(`Approval target is required.`);if(l.scope===`server`&&D===`tool`&&!j.startsWith(`${l.target}.`))throw Error(`Choose a tool on the requested server.`);let e;try{e=Id(n.submittedConstraintSource,Ne())}catch(e){throw e instanceof Error&&e.message.startsWith(`Additional `)?e:Error(`Constraint must use the supported matcher shape.`)}let t=e===``?null:JSON.parse(e);if(D===`server`&&t!==null)throw Error(`Server approval cannot include a constraint.`);let r=document.getElementById(`approval-duration`);if(r!==null&&!r.validity.valid)throw Error(`Enter a positive whole-number duration and choose its unit.`);if(fe!==``){if(!/^[1-9][0-9]*$/.test(L)||!/^[1-9][0-9]*$/.test(fe))throw Error(`Enter a positive whole-number duration and choose its unit.`);let e=Number(fe);if(e<60||e>2592e3)throw Error(`Duration must be between 1 minute and 30 days.`);if(l.durationSeconds!==null&&BigInt(fe)>BigInt(l.durationSeconds))throw Error(`Approval cannot extend the submitted duration.`)}else if(l.durationSeconds!==null)throw Error(`A temporary request cannot become permanent.`);return{scope:D,readOnly:k,target:j,constraint:t,durationSeconds:fe===``?null:fe,futureToolsAcknowledged:D===`server`}},Fe,Ie=(()=>{try{return Id(n.submittedConstraintSource,Ne())}catch(e){return Fe=e instanceof Error?e.message:`Invalid conditions`,``}})(),Le=`{"description":${T===``?`null`:JSON.stringify(T)},"approved_policy":{"scope":${JSON.stringify(D)},"target":${JSON.stringify(j)},"constraint":${Ie===``?`null`:Ie},"duration_seconds":${fe===``?`null`:JSON.stringify(fe)},"future_tools_acknowledged":${String(D===`server`)}${yr(k)}}}`,Re=async(t,r=!1)=>{let i=ge.current;m(t),v(r),ve(void 0);try{let a;if(t===`approve`){if(T.length>0&&(T.trim()!==T||new TextEncoder().encode(T).length>256))throw Error(`Grant description must be at most 256 bytes without surrounding whitespace.`);if(gn(T))throw Error(`Grant description cannot contain control characters.`);let t=r?l:Pe(),o=Id(n.submittedConstraintSource,r?``:Ne());if(o!==``){be(!0);let t=await Bo(e,o);if(t===void 0||ge.current!==i)return;if(t!==null)throw Error(t)}let s=o===``?`null`:o;a=`{"description":${T===``?`null`:JSON.stringify(T)},"approved_policy":{"scope":${JSON.stringify(t.scope)},"target":${JSON.stringify(t.target)},"constraint":${s},"duration_seconds":${t.durationSeconds===null?`null`:JSON.stringify(t.durationSeconds)},"future_tools_acknowledged":${String(t.futureToolsAcknowledged)}${yr(t.readOnly)}}}`}else a=JSON.stringify({reason:R});let o={route:`/api/v2/mcp/grant-requests/${n.id}/${t}`,method:`POST`,body:a,precondition:n.etag,requiresPrecondition:!0,idempotency:`none`,successStatuses:[200],decode:async e=>{let n=await Oe(e);if(t===`approve`&&(n.approvedPolicy===null||n.approvedPolicy.readOnly!==(r?l.readOnly:k)))throw Error(`invalid response`);return n}};C.current=i,u.begin(o),b(!1),t===`reject`?await ze():we(!0)}catch(e){ve(e instanceof Error?e.message:`Invalid adjudication.`)}finally{be(!1)}},ze=async()=>{if(we(!1),!c||C.current!==ge.current){u.abandon(),ve(`The draft changed. Review the current draft again.`);return}let e=await u.submit();e.kind===`acknowledged`?(Se(void 0),me.current={description:T,scope:D,readOnly:k,target:j,additionalAtoms:ie,duration:fe,reason:R},i(e.value),u.abandon(),r()):e.kind===`uncertain`?a():e.kind===`rejected`&&e.requiresRefresh&&(Se(n.etag),r())},Be=()=>{we(!1),p===`reject`&&pe(x.current),u.abandon()},Ve=!c||ye||d.state===`submitting`||d.state===`uncertain`||d.availability===`storage_latched`||xe===n.etag;if(n.state!==`pending`)return U(K,{state:`empty`,title:`Request adjudication is closed`,children:U(`p`,{children:`Terminal requests cannot be approved or rejected again.`})});let He=_?l:{scope:D,readOnly:k,target:j,constraint:Ie===``?null:JSON.parse(Ie),durationSeconds:fe===``?null:fe,futureToolsAcknowledged:D===`server`},Ue=l.scope===`server`&&He.scope===`tool`,We=P?.serverID===n.resolvedServerID&&P.externalName===He.target&&P.id===ke?.id?P:void 0,Ge=_?Id(n.submittedConstraintSource,``):Ie,Ke=k!==l.readOnly||D!==l.scope||j!==l.target||ie.length>0||fe!==(l.durationSeconds??``),qe=!_&&Ke;return U(`section`,{class:`panel domain-panel`,"aria-labelledby":`request-actions-title`,"data-testid":`request-actions`,children:[U(`div`,{class:`panel-heading`,children:U(`div`,{children:U(`h2`,{id:`request-actions-title`,children:`Choose a decision`})})}),U(`p`,{children:`Approval does not execute or retry a call.`}),U(J,{id:`approval-description`,label:`Grant description`,optional:!0,children:e=>U(`input`,{...e,"data-testid":`approval-description`,placeholder:`Allow requested tool access`,value:T,maxlength:256,disabled:Ve,onInput:e=>E(e.currentTarget.value)})}),U(`div`,{class:`form-actions`,children:[U(`button`,{ref:w,class:`primary-action`,type:`button`,disabled:Ve,onClick:()=>void Re(`approve`,!0),children:`Approve as requested`}),U(`button`,{type:`button`,class:`secondary request-customize-toggle`,disabled:Ve,"aria-expanded":h,"aria-controls":`request-customization`,onClick:()=>g(!h),children:[U(`span`,{"aria-hidden":`true`,children:h?`▾`:`▸`}),` `,h?`Hide customization`:`Customize approval`]}),!h&&Ke&&U(`span`,{class:`request-draft-note`,children:`Custom approval edited`}),U(`button`,{ref:Ee,"data-testid":`request-reject`,type:`button`,class:`danger-action`,disabled:Ve,onClick:()=>{x.current=R,m(`reject`),b(!0)},children:`Reject request`})]}),_e!==void 0&&U(K,{state:`error`,title:`Check decision`,children:U(`p`,{children:_e})}),h&&U(`section`,{id:`request-customization`,class:`form-section`,"aria-label":`Customize approval`,children:[U(`h3`,{children:`Tools`}),U(J,{id:`approval-scope`,label:`Approved scope`,children:e=>U(`select`,{...e,"data-testid":`approval-scope`,value:D,disabled:l.scope===`tool`||l.readOnly||Ve,onChange:e=>{let t=e.currentTarget.value;O(t),t===`tool`&&A(!1),t===`server`&&(M(l.target),ae([]))},children:[U(`option`,{value:`server`,children:`Server`}),U(`option`,{value:`tool`,children:`Exact tool`})]})}),D===`server`&&U(`div`,{children:[U(J,{id:`approval-read-only`,label:`Allowed tools`,...k?{hint:`Includes current and future tools marked readOnlyHint=true. The Gateway does not verify that these tools are read-only; they may still change data.`}:{},children:e=>U(`select`,{...e,"data-testid":`approval-read-only`,value:k?`read-only`:`all`,disabled:l.readOnly||Ve,onChange:e=>A(e.currentTarget.value===`read-only`),children:[U(`option`,{value:`all`,children:`All tools`}),U(`option`,{value:`read-only`,children:`Only tools marked read-only`})]})}),l.readOnly&&U(`p`,{children:`The requested read-only server restriction cannot be removed or narrowed to an exact tool.`})]}),U(J,{id:`approval-target`,label:`Approved target`,children:e=>De?U(`div`,{class:`matcher-tool-input`,children:[U(kn,{attributes:e,label:`Approved target`,testID:`approval-target`,placeholder:`${l.target}.lookup`,value:j,options:(N??[]).filter(e=>e.serverID===n.resolvedServerID).map(e=>({value:e.externalName})),disabled:Ve,onChange:M}),U(jo,{status:je,testID:`approval-tool-recognition`})]}):U(`input`,{...e,"data-testid":`approval-target`,value:j,disabled:!0})}),De&&Me&&U(`p`,{class:`bounded-note`,role:`status`,"data-testid":`approval-tool-posture`,children:Me}),U(`h3`,{children:`Conditions`}),D===`tool`&&U(S,{children:[U(Dd,{source:n.submittedConstraintSource,locked:!0}),U(`div`,{"aria-labelledby":`approval-additional-matchers-title`,children:[U(`h3`,{id:`approval-additional-matchers-title`,children:[`Additional conditions — All must match`,U(`span`,{class:`optional-label`,children:` (optional)`})]}),U(`p`,{class:`field-hint`,children:`Add rules without changing the submitted policy.`}),Ae?.unsupported&&U(`p`,{class:`bounded-note`,"data-testid":`approval-matcher-schema-posture`,children:`Some schema fields cannot be suggested. Custom pointers are still available.`}),U(Io,{idPrefix:`approval-additional`,testPrefix:`approval-additional`,atoms:ie,suggestions:Ae,schemaState:De&&!F&&(N===void 0||ke!==void 0&&!I&&Ae===void 0)?`loading`:`unavailable`,disabled:Ve,onChange:e=>{ve(void 0),ae(e)}})]})]}),U(`h3`,{children:`Duration`}),U(J,{id:`approval-duration`,label:`Approved duration`,hint:(l.durationSeconds===null?`Enter a whole number and choose its unit, from 1 minute to 30 days. Leave blank for no expiry.`:`Enter a whole number and choose its unit, from 1 minute to 30 days. The duration cannot exceed the request; temporary access cannot become permanent.`)+(de?``:` Choose a smaller unit; no positive whole number in this unit fits the requested duration.`),optional:l.durationSeconds===null,children:e=>U(`div`,{class:`duration-controls`,children:[U(`input`,{...e,type:`number`,min:`1`,step:`1`,"data-testid":`approval-duration`,placeholder:de?ue:void 0,value:L,disabled:Ve,onInput:e=>le(e.currentTarget.value)}),U(`select`,{"aria-label":`Approved duration unit`,"data-testid":`approval-duration-unit`,value:se,disabled:Ve,onChange:e=>ce(e.currentTarget.value),children:[U(`option`,{value:`minutes`,children:`Minutes`}),U(`option`,{value:`hours`,children:`Hours`}),U(`option`,{value:`days`,children:`Days`}),U(`option`,{value:`seconds`,children:`Seconds`})]})]})}),U(`section`,{class:`subpanel`,"aria-label":`Approval preview`,children:[U(`h3`,{children:`Approval preview`}),!Ke&&U(`p`,{children:`No changes to requested access.`}),U(`div`,{class:`approval-preview`,children:[U(`div`,{class:`preview-head`,"aria-hidden":`true`,children:[U(`span`,{children:`Field`}),U(`span`,{children:`Requested`}),U(`span`,{children:`Proposed approval`})]}),U(`div`,{class:D!==l.scope||j!==l.target||k!==l.readOnly?`preview-row changed`:`preview-row`,children:[U(`strong`,{children:`Tools`}),U(`div`,{children:[U(`span`,{class:`preview-label`,children:`Requested`}),l.scope===`server`?Ad(l):l.target]}),U(`div`,{children:[U(`span`,{class:`preview-label`,children:`Proposed approval`}),D===`server`?k?`Read-only server tools`:`All tools`:j]})]}),U(`div`,{class:fe===(l.durationSeconds??``)?`preview-row`:`preview-row changed`,children:[U(`strong`,{children:`Duration`}),U(`div`,{children:[U(`span`,{class:`preview-label`,children:`Requested`}),Ed(l.durationSeconds)]}),U(`div`,{children:[U(`span`,{class:`preview-label`,children:`Proposed approval`}),Ed(fe===``?null:fe)]})]}),U(`div`,{class:ie.length>0?`preview-row changed`:`preview-row`,children:[U(`strong`,{children:`Conditions`}),U(`div`,{children:[U(`span`,{class:`preview-label`,children:`Requested`}),U(Dd,{source:n.submittedConstraintSource})]}),U(`div`,{children:[U(`span`,{class:`preview-label`,children:`Proposed approval`}),Fe===void 0?U(Dd,{source:Ie}):U(K,{state:`error`,title:`Correct invalid conditions before approval`})]})]})]})]}),U(`div`,{class:`form-actions`,children:U(`button`,{ref:Te,"data-testid":`request-approve`,class:`primary-action`,type:`button`,disabled:Ve,onClick:()=>void Re(`approve`),children:ye?`Validating matcher…`:Ke?`Approve as narrowed`:`Approve as requested`})})]}),U(jn,{id:`request-rejection`,open:y,title:`Reject request`,confirmLabel:`Reject request`,destructive:!0,returnFocus:Ee,onCancel:()=>{pe(x.current),b(!1)},onConfirm:()=>void Re(`reject`),consequence:U(`div`,{children:[U(`p`,{children:`Rejection closes this request and creates no grant. It does not revoke existing access or create a DENY.`}),U(J,{id:`rejection-reason`,label:`Rejection reason`,children:e=>U(`select`,{...e,"data-testid":`rejection-reason`,value:R,disabled:Ve,onChange:e=>pe(e.currentTarget.value),children:[U(`option`,{value:`not_approved`,children:`Not approved`}),U(`option`,{value:`existing_access`,children:`Existing access`}),U(`option`,{value:`scope_too_broad`,children:`Scope too broad`}),U(`option`,{value:`policy_conflict`,children:`Policy conflict`})]})})]})}),d.problem!==void 0&&U(K,{state:`error`,title:_n(d.problem),children:d.requiresRefresh&&U(`p`,{children:`Refresh the request and review its state before taking another action.`})}),d.state===`uncertain`&&U(K,{state:`warning`,title:`Adjudication outcome is unknown`,children:U(`p`,{children:`Do not retry or replay. Refresh the request and grant history to investigate possible atomic commit.`})}),U(jn,{id:`request-adjudication-confirm`,open:Ce,title:p===`approve`?qe?`Approve as narrowed?`:`Approve as requested?`:`Reject request?`,consequence:p===`approve`?U(`div`,{class:`review-stack request-confirmation`,children:[U(`p`,{children:`Creates one allow grant and closes this request. It does not run a tool.`}),U(`dl`,{class:`detail-facts`,children:[U(`div`,{children:[U(`dt`,{children:`Agent`}),U(`dd`,{children:o})]}),U(`div`,{children:[U(`dt`,{children:`Approved target`}),U(`dd`,{children:s})]}),U(`div`,{children:[U(`dt`,{children:`Tools`}),U(`dd`,{children:He.scope===`tool`?He.target:Ad(He)})]}),T!==``&&U(`div`,{children:[U(`dt`,{children:`Description`}),U(`dd`,{children:T})]})]}),U(Od,{policy:He,source:Ge,definition:Ue?`Narrowed to one tool — no submitted definition to compare. ${F||I||We===void 0?`Current definition unavailable; using the literal tool name.`:`Current definition available.`}`:kd(n)}),U(`p`,{children:`All conditions must match. Matching deny grants still take precedence.`}),U(`details`,{children:[U(`summary`,{children:`Exact identifiers and serialized policy`}),U(`dl`,{class:`detail-facts`,children:[U(`div`,{children:[U(`dt`,{children:`Agent ID`}),U(`dd`,{class:`technical-value`,children:n.principalID})]}),U(`div`,{children:[U(`dt`,{children:`Server ID`}),U(`dd`,{class:`technical-value`,children:n.resolvedServerID})]})]}),U(`strong`,{children:`Read-only serialized policy`}),U(`textarea`,{class:`inert-json matcher-policy-review`,"aria-label":`Read-only serialized policy`,"data-testid":`approval-review-policy`,readOnly:!0,rows:8,value:_?`{"description":${JSON.stringify(T===``?null:T)},"approved_policy":{"scope":${JSON.stringify(l.scope)},"target":${JSON.stringify(l.target)},"constraint":${Ge===``?`null`:Ge},"duration_seconds":${JSON.stringify(l.durationSeconds)},"future_tools_acknowledged":${String(l.futureToolsAcknowledged)}${yr(l.readOnly)}}}`:Le})]})]}):U(`p`,{children:[`Rejection atomically closes the request with reason`,` `,W(R),`; it creates no grant, does not revoke existing access, and does not create a DENY.`]}),confirmLabel:p===`approve`?qe?`Approve as narrowed`:`Approve as requested`:`Reject request`,destructive:p===`reject`,returnFocus:p===`approve`?_?w:Te:Ee,onCancel:Be,onConfirm:()=>void ze()})]})}function Rd({session:e,mutations:t,resolved:n,view:r,onRefresh:i}){let a=n.location.segments.length===2?n.location.segments[1]:void 0,[o,s]=z(),[c,l]=z(),[u,d]=z(),f=V({location:{destination:`requests`,segments:[`requests`],query:{}},canonicalFragment:`#/mcp/access-requests`,invalid:!1});a===void 0&&(f.current=n);let p=Cr(!1),{items:m,controls:h}=Nr(e,f.current,r,(t,n,r)=>wd(e,t,n,r),p,{key:`submitted`,direction:f.current.location.query.queue===`all`?`descending`:`ascending`}),[g,_]=z(),[v,y]=z();if(B(()=>{let t=!0;if(l(void 0),a!==void 0){s(e=>e?.id===a?e:void 0),Td(e,a).then(e=>{t&&e!==void 0&&s(e)}).catch(e=>{t&&l(e instanceof Error?e.message:`Request data is unavailable.`)});let n=new AbortController;wd(e,{queue:`all`,filter_request:a},null,n.signal).then(e=>{t&&_(e?.items.find(e=>e.id===a))}).catch(()=>{t&&_(void 0)}),wd(e,{},null,n.signal).then(e=>{t&&y(e?.items.find(e=>e.id!==a)?.id)}).catch(()=>{t&&y(void 0)})}return()=>{t=!1}},[n.canonicalFragment,r.generation]),c!==void 0&&(o===void 0||o.id!==a))return U(K,{state:`error`,title:`Request data unavailable`,children:U(`p`,{children:c})});if(a!==void 0){if(o===void 0||o.id!==a)return U(K,{state:`loading`,title:`Loading request`});let n=g?.id===o.id?g.principalName:`Agent ${o.principalID}`,r=g?.id===o.id?g.serverName:`Server ${o.resolvedServerID}`,l=o.submittedEvidence!==null&&o.currentTarget.fingerprint!==null&&o.submittedEvidence.fingerprint!==o.currentTarget.fingerprint;return U(`div`,{class:`domain-view`,"data-testid":`request-detail`,"data-request-id":o.id,children:[U(`nav`,{class:`detail-navigation`,"aria-label":`Request navigation`,children:[U(`a`,{href:f.current.canonicalFragment,children:[`Back to`,` `,f.current.location.query.queue===`all`?`all`:`pending`,` `,`requests`]}),o.state!==`pending`&&v!==void 0&&U(`a`,{href:`#/mcp/access-requests/${v}`,children:`Review next`}),o.state!==`pending`&&v===void 0&&U(`span`,{children:`No next pending request available. Return to the queue to refresh.`})]}),U(`header`,{class:`detail-context`,"data-testid":`detail-context`,children:[U(`div`,{class:`detail-context-heading`,children:[U(`h1`,{id:`request-page-title`,tabindex:-1,children:o.state===`pending`?`Review MCP Access Request`:`${W(o.state)} MCP Access Request`}),U(G,{state:o.state===`pending`?`warning`:o.state===`approved`?`current`:`neutral`,children:W(o.state)})]}),U(`p`,{class:`technical-value`,children:o.id})]}),U(`section`,{class:`detail-section`,"aria-labelledby":`request-title`,children:[U(`div`,{class:`panel-heading`,children:U(`h2`,{id:`request-title`,children:`Request details`})}),U(`dl`,{class:`detail-facts`,children:[U(`div`,{children:[U(`dt`,{children:`Agent`}),U(`dd`,{children:U(`a`,{href:`#/agents/${o.principalID}`,children:n})})]}),U(`div`,{children:[U(`dt`,{children:`Submitted`}),U(`dd`,{children:U(Y,{value:o.createdAt})})]}),U(`div`,{children:[U(`dt`,{children:`Requested target`}),U(`dd`,{children:U(`a`,{href:`#/mcp/servers/${o.resolvedServerID}?tab=tools`,children:r})})]}),U(`div`,{children:[U(`dt`,{children:`Tools`}),U(`dd`,{children:o.resolvedUpstreamName??Ad(o.requestedPolicy)})]})]}),U(Od,{policy:o.requestedPolicy,source:o.submittedConstraintSource,definition:kd(o)}),c!==void 0&&U(K,{state:`error`,title:`Request refresh failed`,children:U(`p`,{children:[c,` Displayed evidence may be stale; refresh before deciding.`]})}),u===o.id&&U(K,{state:`warning`,title:`Adjudication outcome is unknown`,children:U(`p`,{children:`Do not resubmit. Inspect refreshed request and grant history; no success or rollback was confirmed.`})})]}),o.state===`pending`&&u!==o.id&&U(Ld,{session:e,mutations:t,detail:o,onRefresh:i,onAcknowledged:s,onUncertain:()=>d(o.id),principalName:n,serverName:r,readAvailable:c===void 0},`${o.id}:${o.etag}`),o.state!==`pending`&&U(`section`,{class:`detail-section`,"aria-labelledby":`approved-policy-title`,children:[U(`h2`,{id:`approved-policy-title`,children:[W(o.state),` decision`]}),o.approvedGrantID!==null&&U(`dl`,{class:`detail-facts`,children:U(`div`,{children:[U(`dt`,{children:`Created grant`}),U(`dd`,{children:U(`a`,{href:`#/mcp/grants/${o.approvedGrantID}`,children:o.approvedGrantID})})]})}),U(K,{state:`empty`,title:`Request adjudication is closed`,children:U(`p`,{children:`Terminal requests cannot be approved or rejected again.`})}),o.approvedPolicy===null?U(`p`,{children:[o.state===`cancelled`?`The requesting agent cancelled this request.`:`This request was rejected.`,` `,`This decision created no grant and did not revoke existing access or create a DENY.`]}):U(S,{children:[U(`section`,{class:`detail-group`,"aria-label":`Requested versus approved`,children:[U(`h3`,{children:`Requested versus Approved`}),Md(o.requestedPolicy,o.approvedPolicy),U(xn,{label:`Requested versus approved conditions`,fullWidth:!0,beforeLabel:`Requested`,afterLabel:`Approved`,rows:[{label:`Conditions`,before:U(Dd,{source:o.submittedConstraintSource}),after:U(Dd,{source:o.approvedConstraintSource}),changed:o.submittedConstraintSource!==o.approvedConstraintSource}]})]}),U(`details`,{children:[U(`summary`,{children:`Approved serialized policy`}),U(`pre`,{class:`inert-json`,tabindex:0,"aria-label":`Approved policy`,children:o.approvedPolicySource})]})]}),o.approvedEvidence!==null&&U(`details`,{children:[U(`summary`,{children:`Approved descriptor evidence`}),U(Nd,{evidence:o.approvedEvidence,label:`Approved`})]}),o.rejectionReason!==null&&U(`p`,{children:[`Closed rejection reason: `,o.rejectionReason]})]}),U(`details`,{class:`detail-section`,children:[U(`summary`,{children:`Technical identifiers and immutable evidence`}),U(`dl`,{class:`detail-facts`,children:[U(`div`,{children:[U(`dt`,{children:`Agent ID`}),U(`dd`,{children:o.principalID})]}),U(`div`,{children:[U(`dt`,{children:`Server ID`}),U(`dd`,{children:o.resolvedServerID})]}),U(`div`,{children:[U(`dt`,{children:`Revision / ETag`}),U(`dd`,{children:o.etag})]})]}),U(`p`,{children:`Tool descriptions and schemas are untrusted inert evidence, not instructions or proof of callable authority.`}),U(`section`,{class:`detail-group`,"aria-labelledby":`submitted-policy-title`,children:[U(`h2`,{id:`submitted-policy-title`,children:`Submitted policy and evidence — immutable`}),jd(o.requestedPolicy),o.requestedPolicy.constraint!==null&&U(yn,{value:o.requestedPolicy.constraint,label:`Submitted constraint`}),U(Nd,{evidence:o.submittedEvidence,label:`Submitted`})]}),U(`section`,{class:`detail-group`,"aria-labelledby":`current-target-title`,children:[U(`h2`,{id:`current-target-title`,children:`Current target comparison — read-time`}),U(`p`,{children:`Current comparison does not rewrite immutable submitted evidence or the request revision.`}),U(`dl`,{class:`detail-facts`,children:[U(`div`,{children:[U(`dt`,{children:`Target`}),U(`dd`,{children:W(o.currentTarget.targetState)})]}),U(`div`,{children:[U(`dt`,{children:`Active descriptor`}),U(`dd`,{children:o.currentTarget.activeState===null?`Not applicable`:W(o.currentTarget.activeState)})]}),U(`div`,{children:[U(`dt`,{children:`Durable descriptor`}),U(`dd`,{children:o.currentTarget.durableState===null?`Not applicable`:W(o.currentTarget.durableState)})]}),U(`div`,{children:[U(`dt`,{children:`Current fingerprint`}),U(`dd`,{children:o.currentTarget.fingerprint??`Absent`})]})]}),l&&U(K,{state:`warning`,title:`Descriptor fingerprint changed`,children:U(`p`,{children:`The current descriptor differs from submitted evidence. Active current does not mean it matches the submission.`})}),o.currentTarget.durableState===`retired`&&U(K,{state:`warning`,title:`Current comparison is retired historical evidence`,children:U(`p`,{children:`Retained evidence is not callable authority.`})}),o.currentTarget.durableState===`absent`&&U(K,{state:`unavailable`,title:`Current descriptor is absent`}),o.currentTarget.descriptor!==null&&U(yn,{value:o.currentTarget.descriptor,label:`Current normalized descriptor`})]})]})]})}let b=n.location.query.queue===`all`;return U(`div`,{class:`domain-view`,"data-testid":`requests-view`,children:U(`section`,{class:`panel domain-panel`,"aria-label":`Grant requests`,children:[U(`nav`,{class:`subnav request-queue-tabs`,"aria-label":`Request queues`,children:[U(`a`,{href:`#/mcp/access-requests`,"aria-current":b?void 0:`page`,children:`Pending`}),U(`a`,{href:`#/mcp/access-requests?queue=all`,"aria-current":b?`page`:void 0,children:`All requests`})]}),U(Dn,{caption:`Grant request summaries`,rowHeaderKey:`request`,items:m,rowKey:e=>e.id,rowTestID:`request-row`,emptyTitle:b?`No requests`:`No pending requests`,remote:h,itemNames:{singular:`request`,plural:`requests`},filters:[{key:`request`,label:`Request ID`,type:`text`,value:()=>``,literalValues:e=>[e.id]},{key:`principal`,label:`Agent`,type:`text`,value:e=>e.principalName,literalValues:e=>[e.principalID]},{key:`target`,label:`Target`,type:`text`,value:e=>e.requestedPolicy.target},{key:`scope`,label:`Scope`,type:`select`,value:e=>e.requestedPolicy.scope,options:[{value:`tool`,label:`Tool`},{value:`server`,label:`Server`}]},...b?[{key:`state`,label:`Status`,type:`select`,value:e=>e.state,options:[{value:`pending`,label:`Pending`},{value:`approved`,label:`Approved`},{value:`rejected`,label:`Rejected`},{value:`cancelled`,label:`Cancelled`}]}]:[]],columns:[{key:`submitted`,label:`Submitted`,role:`time`,render:e=>U(Y,{value:e.createdAt}),sortValue:e=>e.createdAt},{key:`request`,label:`Request`,role:`identity`,render:e=>U(q,{primary:U(`a`,{href:`#/mcp/access-requests/${e.id}`,children:`Access request`}),secondary:e.id}),sortValue:e=>e.id},{key:`principal`,label:`Agent`,role:`relation`,render:e=>U(`a`,{href:`#/agents/${e.principalID}`,children:e.principalName}),sortValue:e=>e.principalName},{key:`target`,label:`Target`,role:`relation`,render:e=>U(`a`,{href:`#/mcp/servers/${e.serverID}?tab=tools`,title:e.requestedPolicy.target,children:[e.serverName,` ·`,` `,e.upstreamName??(e.requestedPolicy.readOnly?`Read-only tools`:`All tools`)]}),sortValue:e=>e.requestedPolicy.target},{key:`state`,label:`Status`,role:`status`,render:e=>U(G,{state:e.state===`pending`?`warning`:e.state===`approved`?`current`:`neutral`,children:W(e.state)}),sortValue:e=>e.state},{key:`duration`,label:`Requested duration`,role:`measure`,render:e=>Ed(e.requestedPolicy.durationSeconds)},{key:`constraints`,label:`Conditions`,role:`count`,render:e=>Po(e.requestedPolicy.constraint===null?null:Pd(e.requestedPolicy.constraint))},{key:`decision`,label:`Actions`,role:`actions`,render:e=>U(`a`,{class:`button-link${e.state===`pending`?` primary-action`:``}`,href:`#/mcp/access-requests/${e.id}`,children:e.state===`pending`?`Review`:`View decision`})}]})]})})}var zd=`sidebar-pending-requests`,Bd=class{total;constructor(e,t){e.registerProtectedState(()=>{this.total=void 0}),t.registerPanel({id:zd,scope:`session`,matches:e=>e!==`#/sign-in`,invalidations:[`grant_requests`],pollMilliseconds:3e4,read:async({signal:t})=>{let n=await Mr(e,`/api/v2/mcp/grant-requests?state=pending&limit=1`,()=>null,t);if(n?.totalCount===void 0)throw Error(`Pending request count is unavailable.`);return n.totalCount},publish:e=>{this.total=e}})}presentation(e){let t=e.panels[zd];return this.total===void 0||t?.hasValue!==!0?{label:t?.status===`error`?`Requests, pending count unavailable`:`Requests, pending count loading`,badge:`?`}:t.status===`error`||t.status===`stale`?{label:`Requests, pending count unavailable; last known ${this.total} pending`,badge:`?`}:{label:`Requests, ${this.total} pending${t.refreshing?` (refreshing)`:``}`,badge:this.total===0?null:String(this.total)}}},Vd={bytes:67108864,milliseconds:12e4,pages:4096},Hd=class extends Error{},Ud=()=>new Hd(`History coverage could not be verified. No file was downloaded.`),Wd=/^(0|[1-9][0-9]{0,18})$/,Gd=/^[0-7][0-9A-HJKMNP-TV-Z]{25}$/;function Kd(e){if(typeof e!=`string`||!Wd.test(e))throw Ud();let t=BigInt(e);if(t>9223372036854775807n)throw Ud();return t}function qd(e,t,n){let r=JSON.parse(e);if(typeof r!=`object`||!r||Array.isArray(r)||r.format!==1||typeof r.generation!=`string`||!Gd.test(r.generation)||typeof r.installation_id!=`string`||!Gd.test(r.installation_id)||r.complete_traffic_audit!==!1||!Array.isArray(r.records)||r.records.length>256||typeof r.retained!=`number`||!Number.isSafeInteger(r.retained)||r.retained64||!Number.isFinite(Date.parse(r.captured_at))||Kd(r.after_sequence)!==t)throw Ud();let i=Kd(r.high_water),a=Kd(r.pruning),o=Kd(r.next_sequence);if(i-a!==BigInt(r.retained))throw Ud();let s=t;for(let e of r.records){if(typeof e!=`object`||!e||Array.isArray(e))throw Ud();let t=Kd(e.sequence),r=e.protocol;if(t<=s||t>(n??i)||![`mcp`,`http`,`git`].includes(r)||e[r]===null||typeof e[r]!=`object`||Array.isArray(e[r])||[`mcp`,`http`,`git`].some(t=>t!==r&&t in e))throw Ud();s=t}if(o!==s||r.truncated&&o===t)throw Ud();return{generation:r.generation,installation:r.installation_id,high:i,pruning:a,retained:r.retained,next:o,truncated:r.truncated,count:r.records.length,captured:r.captured_at}}async function Jd(e,t,n,r,i){let a=r===void 0?``:`?after_sequence=${n}&through_sequence=${r}&limit=256`,o=await fetch(`/api/v2/history/export${a}`,{method:`GET`,credentials:`same-origin`,cache:`no-store`,redirect:`error`,headers:{"X-CSRF-Token":e},signal:AbortSignal.any([t,AbortSignal.timeout(5e3)])});if(await i?.(o))throw Ud();if(!o.ok||o.headers.get(`Content-Type`)!==`application/json`||o.body===null)throw new Hd(`Traffic history is unavailable. No file was downloaded. Backup controls remain independent.`);let s=o.body.getReader(),c=new TextDecoder(`utf-8`,{fatal:!0}),l=0,u=``;try{for(;;){t.throwIfAborted();let e=await s.read();if(e.done)break;if(l+=e.value.byteLength,l>921600)throw new Hd(`A history response exceeds its safe bound. No file was downloaded.`);u+=c.decode(e.value,{stream:!0})}u+=c.decode()}catch(e){throw await s.cancel().catch(()=>{}),e}finally{s.releaseLock()}return{raw:u,bytes:l}}async function Yd(e,t,n=()=>{},r){let i=AbortSignal.any([t,AbortSignal.timeout(Vd.milliseconds)]),a=[],o,s=0n,c=0,l=0,u=0n;try{for(let t=0;tVd.bytes)throw new Hd(`Traffic history exceeds the 64 MiB browser limit. No file was downloaded. Use the documented bounded CLI export procedure.`);if(c+=d.count,c>o.retained)throw Ud();if(a.push(t.raw),n({records:c,pages:a.length,bytes:l}),s=d.next,!d.truncated){if(c!==o.retained||c>0&&s!==o.high)throw Ud();let e=JSON.stringify({initial_high_water:String(o.high),final_high_water:String(u),initial_pruning:String(o.pruning),initial_retained:o.retained,returned_records:c,page_count:a.length,started_at:o.captured,finished_at:d.captured,retained_boundary_traversed:!0,atomic_snapshot:!1,new_records_excluded:u>o.high,completion_changes:`Each page observes its own read transaction; late completions on earlier pages are not refreshed. Missing completion remains unknown.`});return i.throwIfAborted(),{blob:new Blob([`{"format":"agent-gateway-retained-traffic-v1","complete_traffic_audit":false,"coverage":${e},"pages":[`,...a.flatMap((e,t)=>t===0?[e]:[`,`,e]),`]} `],{type:`application/json`}),records:c,pages:a.length,bytes:l,newRecords:u>o.high}}if(s>=o.high)throw Ud()}throw new Hd(`Traffic history exceeds the browser page limit. No file was downloaded. Use the documented bounded CLI export procedure.`)}finally{a.length=0}}function Xd(e,t){if(t===0)return`N/A`;let n=BigInt(e)*1000n,r=BigInt(t),i=n/r;n%r*2n>=r&&(i+=1n),e=1000n&&(i=999n);let a=i%10n;return`${i/10n}${a===0n?``:`.${a}`}%`}function Zd(e){let t=[`B`,`KiB`,`MiB`,`GiB`,`TiB`,`PiB`],n=e===0?0:Math.min(Math.floor(Math.log(e)/Math.log(1024)),t.length-1);return`${(e/1024**n).toLocaleString(void 0,{maximumFractionDigits:1})} ${t[n]}`}var Qd=/^[0-7][0-9A-HJKMNP-TV-Z]{25}$/;function $d(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`invalid response`);let n=e,r=Object.keys(n).sort(),i=[...t].sort();if(r.length!==i.length||r.some((e,t)=>e!==i[t]))throw Error(`invalid response`);return n}function ef(e){if(typeof e!=`string`)throw Error(`invalid response`);return e}function tf(e){let t=$d(e,[`id`,`fingerprint`,`created_at`,`expires_at`,`non_expiring`,`status`,`revision`]),n=ef(t.id),r=ef(t.fingerprint),i=ef(t.status);if(!Qd.test(n)||!/^[0-9a-f]{16}$/.test(r)||i!==`active`&&i!==`revoked`&&i!==`expired`||typeof t.non_expiring!=`boolean`||t.expires_at!==null&&typeof t.expires_at!=`string`)throw Error(`invalid response`);return{id:n,fingerprint:r,createdAt:ef(t.created_at),expiresAt:t.expires_at,nonExpiring:t.non_expiring,status:i,revision:ef(t.revision)}}function nf(e){let t=$d(e,[`id`,`fingerprint`,`created_at`,`expires_at`,`non_expiring`,`status`,`revision`,`bearer`]),n=tf(Object.fromEntries(Object.entries(t).filter(([e])=>e!==`bearer`))),r=ef(t.bearer);if(!/^mgw_admin_[A-Za-z0-9_-]{43}$/.test(r))throw Error(`invalid response`);return{...n,bearer:r}}function rf(e){let t=typeof e==`object`&&e&&`history`in e?[`history`]:[],n=$d(e,[...t,`id`,`created_at`,`installation_id`,`schema_version`,`source_revision`,`size_bytes`,`sha256`]),r=ef(n.id),i=ef(n.sha256);if(!Qd.test(r)||!/^[0-9a-f]{64}$/.test(i)||t.length>0&&n.history!==`omitted`||typeof n.size_bytes!=`number`||!Number.isSafeInteger(n.size_bytes)||n.size_bytes<0)throw Error(`invalid response`);return{id:r,createdAt:ef(n.created_at),installationID:ef(n.installation_id),schemaVersion:ef(n.schema_version),sourceRevision:ef(n.source_revision),sizeBytes:n.size_bytes,history:n.history===`omitted`?`omitted`:`legacy`,sha256:i}}async function af(e,t){let n=[],r=null,i=!1;for(;;){let a=new URLSearchParams({limit:`100`});r!==null&&a.set(`cursor`,r);let o=await fetch(`/api/v2/admin-credentials?${a}`,{method:`GET`,headers:{"X-CSRF-Token":e},credentials:`same-origin`,redirect:`error`,signal:t});if(o.status===409&&r!==null&&!i){n.length=0,r=null,i=!0;continue}if(o.status!==200||o.headers.get(`Content-Type`)!==`application/json`)throw Error(`admin credential read failed`);let s=$d(await o.json(),[`items`,`next_cursor`]);if(!Array.isArray(s.items))throw Error(`invalid response`);if(n.push(...s.items.map(tf)),s.next_cursor===null)return n;r=ef(s.next_cursor)}}async function of(e,t){let n=[],r=null,i=!1;for(;;){let a=new URLSearchParams({limit:`100`});r!==null&&a.set(`cursor`,r);let o=await fetch(`/api/v2/backups?${a}`,{method:`GET`,headers:{"X-CSRF-Token":e},credentials:`same-origin`,redirect:`error`,signal:t});if(o.status===409&&r!==null&&!i){n.length=0,r=null,i=!0;continue}if(o.status!==200||o.headers.get(`Content-Type`)!==`application/json`)throw Error(`backup read failed`);let s=$d(await o.json(),[`items`,`next_cursor`]);if(!Array.isArray(s.items))throw Error(`invalid response`);if(n.push(...s.items.map(rf)),s.next_cursor===null)return n;r=ef(s.next_cursor)}}async function sf(e,t){return fetch(`/api/v2/system-status`,{method:`GET`,headers:{"X-CSRF-Token":e},credentials:`same-origin`,redirect:`error`,signal:t})}async function cf(e){if(e.status!==200||e.headers.get(`Content-Type`)!==`application/json`)throw Error(`system status read failed`);let t=await e.text();if(new TextEncoder().encode(t).byteLength>1048576)throw Error(`system status read failed`);return JSON.parse(t)}function lf(e){if(e===`#/system/backups/new`)return`backups`;if(e===`#/system/admin-credentials/new`)return`admin-credentials`;let t=e.indexOf(`?`);if(t===-1)return`status`;let n=new URLSearchParams(e.slice(t+1)).get(`tab`);return n===`resource-limits`||n===`needs-attention`||n===`admin-credentials`||n===`backups`?n:`status`}var uf=class{listeners=new Set;credentialListeners=new Set;backupListeners=new Set;value;credentials;backups;history;historyListeners=new Set;views;constructor(e,t,n){this.views=t,t.registerPanel({id:`history-export`,matches:e=>e===`#/system?tab=backups`,invalidations:[],shouldRefresh:e=>e===`panel`,read:async e=>{try{return await Yd(e.csrfToken,e.signal,t=>{!e.signal.aborted&&e.isCurrent()&&this.setHistory({...t,kind:`reading`})},e.sessionLost)}catch(t){throw!e.signal.aborted&&e.isCurrent()&&this.setHistory({records:0,pages:0,bytes:0,kind:`error`,message:t instanceof Hd?t.message:`History export did not finish within its safe limits. No file was downloaded. Try again or use the documented bounded CLI export procedure.`}),t}},publish:e=>{let t=xi(e.blob);this.setHistory({records:e.records,pages:e.pages,bytes:e.bytes,kind:t?`complete`:`error`,message:t?`Download prepared for ${e.records.toLocaleString()} retained records across ${e.pages} ${e.pages===1?`page`:`pages`}.${e.newRecords?` New arrivals were excluded.`:``} Pages are separate reads; late completions may differ.`:`The browser download could not be started. No file was downloaded.`})}}),t.registerPanel({id:`mutation-latch`,matches:()=>!0,invalidations:[`system_status`],read:async e=>Tl(await cf(await sf(e.csrfToken,e.signal))),publish:e=>n(e.latched)}),t.registerPanel({id:`backups`,matches:e=>lf(e)===`backups`,invalidations:[`backups`],read:async e=>of(e.csrfToken,e.signal),publish:e=>{this.backups=e,this.emitBackups()}}),t.registerPanel({id:`admin-credentials`,matches:e=>lf(e)===`admin-credentials`,invalidations:[`admin_credentials`],read:async e=>af(e.csrfToken,e.signal),publish:e=>{this.credentials=e,this.emitCredentials()}}),t.registerPanel({id:`system-status`,matches:e=>{if(H(e)?.destination!==`system`)return!1;let t=lf(e);return t===`status`||t===`resource-limits`},invalidations:[`system_status`],read:async e=>Tl(await cf(await sf(e.csrfToken,e.signal))),publish:e=>{this.value=e,n(e.latched),this.emit()}}),e.registerProtectedState(()=>{this.value=void 0,this.credentials=void 0,this.backups=void 0,this.history=void 0;for(let e of this.historyListeners)e(void 0);n(!1),this.emit(),this.emitCredentials(),this.emitBackups()})}snapshot(){return this.value}subscribe(e){return this.listeners.add(e),e(this.value),()=>this.listeners.delete(e)}credentialSnapshot(){return this.credentials}subscribeCredentials(e){return this.credentialListeners.add(e),e(this.credentials),()=>this.credentialListeners.delete(e)}exportHistory(){this.history?.kind!==`reading`&&(this.setHistory({kind:`reading`,records:0,pages:0,bytes:0}),this.views.refreshPanel(`history-export`))}cancelHistory(){this.views.cancelPanelRead(`history-export`),this.setHistory(void 0)}setHistory(e){this.history=e;for(let t of this.historyListeners)t(e)}subscribeHistory(e){return this.historyListeners.add(e),e(this.history),()=>this.historyListeners.delete(e)}backupSnapshot(){return this.backups}subscribeBackups(e){return this.backupListeners.add(e),e(this.backups),()=>this.backupListeners.delete(e)}emitBackups(){for(let e of this.backupListeners)e(this.backups)}emitCredentials(){for(let e of this.credentialListeners)e(this.credentials)}emit(){for(let e of this.listeners)e(this.value)}};function df(e){return e.saturated?`warning`:`current`}function ff(){return`Check Gateway access to the encrypted credential database and its master-key file. Status records startup capability only, not a live credential check.`}function pf({current:e}){return U(`nav`,{class:`subnav`,"aria-label":`System sections`,children:[[`status`,`Status`,`#/system`],[`resource-limits`,`Resource limits`,`#/system?tab=resource-limits`],[`needs-attention`,`Needs attention`,`#/system?tab=needs-attention`],[`admin-credentials`,`Admin credentials`,`#/system?tab=admin-credentials`],[`backups`,`Backups`,`#/system?tab=backups`]].map(([t,n,r])=>U(`a`,{href:r,"aria-current":e===t?`page`:void 0,children:n},t))})}function mf({status:e,view:t}){let n=t.panels[`system-status`],r=n?.status??`loading`,i=e?.limits.filter(e=>e.saturated)??[],a=e!==void 0&&e.ready&&!e.latched&&e.keyring===`ready`&&(!e.endpoints||e.endpoints.api===`ready`&&e.endpoints.mcp===`ready`)&&(!e.httpProxy?.enabled||e.httpProxy.ready)&&i.length===0;return U(`section`,{class:`operator-status-view system-status-view`,"aria-label":`System status`,"data-testid":`system-status-panel`,"data-panel-status":r,children:[e!==void 0&&(r===`error`||r===`stale`)&&U(K,{state:`stale`,title:r===`error`?`Refresh failed — last known status`:`Last known status`}),r===`error`&&e===void 0?U(K,{state:`error`,title:`System status unavailable`,children:U(`p`,{children:`Check Gateway availability, then refresh this authoritative read.`})}):r===`loading`&&n?.hasValue!==!0||e===void 0?U(K,{state:`loading`,title:`Loading system status`}):U(`div`,{class:`operator-status-stack`,children:[!a&&U(`section`,{class:`operator-status-section`,"aria-labelledby":`system-issues-title`,"data-testid":`system-status-issues`,children:[U(`div`,{class:`operator-status-section-heading`,children:[U(`h3`,{id:`system-issues-title`,children:`Needs attention`}),!a&&U(`span`,{children:`Operator action may be required`})]}),e.endpoints&&(e.endpoints.api!==`ready`||e.endpoints.mcp!==`ready`)&&U(K,{state:`warning`,title:`Gateway endpoints need attention`,children:U(`p`,{children:`Review Gateway API and MCP endpoint admission states below.`})}),!e.ready&&U(K,{state:`warning`,title:`Gateway is not ready`,children:U(`p`,{children:[`The process is `,W(e.processState),`. Review the remaining health checks before restoring traffic.`]})}),e.latched&&U(K,{state:`error`,title:`Storage mutations are unavailable`,children:U(`p`,{children:`Reads can remain available, but only the documented stopped-process recovery procedure can clear this condition.`})}),e.httpProxy?.enabled&&!e.httpProxy.ready&&U(K,{state:`warning`,title:`HTTP proxy is unavailable`,children:U(`p`,{children:`Check authority, the loaded CA and lifecycle state. Client trust must be configured separately.`})}),e.keyring!==`ready`&&U(K,{state:`warning`,title:`Credential storage needs attention`,children:U(`p`,{children:ff()})}),i.length>0&&U(K,{state:`warning`,title:`${i.length} resource ${i.length===1?`limit is`:`limits are`} saturated`,children:U(`p`,{children:`New work using saturated capacity cannot be admitted.`})})]}),U(`section`,{class:`detail-section`,"aria-labelledby":`system-status-title`,"data-testid":`system-status-operational`,children:[U(`h3`,{id:`system-status-title`,children:`Gateway status`}),U(`dl`,{class:`operator-status-grid`,children:[U(`div`,{children:[U(`dt`,{children:`Process`}),U(`dd`,{children:[U(vn,{value:e.processState,current:r===`current`}),!e.ready&&U(`span`,{children:`Not ready`}),U(`span`,{children:[`Started `,U(Y,{value:e.startedAt})]})]})]}),U(`div`,{children:[U(`dt`,{children:`Administration API`}),U(`dd`,{children:[U(vn,{value:e.endpoints?.api,current:r===`current`}),e.endpoints&&U(`span`,{children:e.endpoints.authority}),e.endpoints?.api===`read_only`&&U(`span`,{children:`Inspection remains available; control mutations are blocked.`})]})]}),U(`div`,{children:[U(`dt`,{children:`MCP ingress`}),U(`dd`,{children:[U(vn,{value:e.endpoints?.mcp,current:r===`current`}),e.endpoints&&U(`span`,{children:[e.endpoints.authority,`/mcp`]}),e.endpoints?.mcp===`unavailable`&&U(`span`,{children:`New dispatch is blocked by control authority or lifecycle state.`}),(e.endpoints?.mcp===`disabled`||e.agentAuth===`deny_all`)&&U(`span`,{children:`Agent authentication is disabled.`})]})]}),e.httpProxy&&U(`div`,{children:[U(`dt`,{children:`HTTP proxy`}),U(`dd`,{children:[U(vn,{value:e.httpProxy.enabled?e.httpProxy.ready?`ready`:`unavailable`:`disabled`,current:r===`current`}),e.httpProxy.enabled&&U(S,{children:[U(`span`,{children:e.httpProxy.authority}),U(`span`,{children:[e.httpProxy.activeStreams,` active requests/streams · `,e.httpProxy.activeTunnels,` `,`opaque tunnels`]})]})]})]})]})]}),U(`section`,{class:`detail-section`,"aria-labelledby":`system-material-title`,"data-testid":`system-status-material`,children:[U(`h3`,{id:`system-material-title`,children:`Storage and security`}),U(`dl`,{class:`operator-status-grid`,children:[U(`div`,{children:[U(`dt`,{children:`Control storage`}),U(`dd`,{children:[U(vn,{value:e.latched?`recovery_required`:e.sqliteState,current:r===`current`}),U(`span`,{children:[`Mutation admission `,e.latched?`closed`:`open`]})]})]}),e.traffic&&U(`div`,{children:[U(`dt`,{children:`Traffic storage`}),U(`dd`,{children:[U(vn,{value:e.traffic.state,current:r===`current`}),U(`span`,{children:e.traffic.pressure?`Capacity pressure`:e.traffic.health?.database_measurement.state===`available`&&e.traffic.health?.wal_measurement.state!==`unavailable`&&e.traffic.health?.free_space_measurement.state===`available`?`No measured pressure`:`Capacity unavailable`}),U(`dl`,{class:`detail-facts storage-details`,children:[U(`div`,{children:[U(`dt`,{children:`Database`}),U(`dd`,{children:fl(e.traffic.health?.database_measurement)})]}),U(`div`,{children:[U(`dt`,{children:`WAL`}),U(`dd`,{children:fl(e.traffic.health?.wal_measurement)})]}),U(`div`,{children:[U(`dt`,{children:`Free space`}),U(`dd`,{children:fl(e.traffic.health?.free_space_measurement)})]}),U(`div`,{children:[U(`dt`,{children:`Budget`}),U(`dd`,{children:Zd(e.traffic.budgetBytes)})]}),U(`div`,{children:[U(`dt`,{children:`Pruned records`}),U(`dd`,{children:e.traffic.health?.accounting_available?e.traffic.prunedRecords.toLocaleString():`Unavailable`})]})]}),e.traffic.recovery&&U(S,{children:[U(`dl`,{class:`detail-facts storage-details`,children:[U(`div`,{children:[U(`dt`,{children:`Recording`}),U(`dd`,{children:W(e.traffic.recovery.health)})]}),U(`div`,{children:[U(`dt`,{children:`Last acknowledged`}),U(`dd`,{children:e.traffic.recovery.lastAcknowledged?U(Y,{value:e.traffic.recovery.lastAcknowledged}):`Not observed`})]})]}),e.traffic.recovery.incident&&U(S,{children:[U(`dl`,{class:`detail-facts storage-details`,children:[U(`div`,{children:[U(`dt`,{children:`Incident`}),U(`dd`,{children:[W(e.traffic.recovery.incident.cause),` `,`·`,` `,W(e.traffic.recovery.incident.stage),` `,`·`,` `,W(e.traffic.recovery.incident.settlement)]})]}),(e.traffic.recovery.incident.recoveryCause!==e.traffic.recovery.incident.cause||e.traffic.recovery.incident.recoveryStage!==e.traffic.recovery.incident.stage)&&U(`div`,{children:[U(`dt`,{children:`Recovery blocker`}),U(`dd`,{children:[W(e.traffic.recovery.incident.recoveryCause),` `,`·`,` `,W(e.traffic.recovery.incident.recoveryStage)]})]}),U(`div`,{children:[U(`dt`,{children:`First failure`}),U(`dd`,{children:U(Y,{value:e.traffic.recovery.incident.firstFailure})})]}),U(`div`,{children:[U(`dt`,{children:`Affected submissions`}),U(`dd`,{children:[e.traffic.recovery.incident.affected,` `,`affected ·`,` `,e.traffic.recovery.incident.discarded,` `,`discarded submissions`]})]}),e.traffic.recovery.incident.sqliteCode>0&&U(`div`,{children:[U(`dt`,{children:`SQLite code`}),U(`dd`,{children:e.traffic.recovery.incident.sqliteCode})]})]}),U(`span`,{children:ll(e.traffic.recovery)})]})]}),e.traffic.health&&U(S,{children:[e.traffic.health.pressure_reason!==`none`&&U(`dl`,{class:`detail-facts storage-details`,children:U(`div`,{children:[U(`dt`,{children:`Pressure reason`}),U(`dd`,{children:W(e.traffic.health.pressure_reason)})]})}),U(`dl`,{class:`detail-facts storage-details`,children:[U(`div`,{children:[U(`dt`,{children:`Submissions`}),U(`dd`,{children:[e.traffic.health.delivery.accepted,` accepted · `,e.traffic.health.delivery.acknowledged,` `,`acknowledged ·`,` `,e.traffic.health.delivery.discarded,` `,`discarded`]})]}),U(`div`,{children:[U(`dt`,{children:`Queue records`}),U(`dd`,{children:[e.traffic.health.delivery.queue_records,` /`,` `,e.traffic.health.delivery.queue_record_limit]})]}),U(`div`,{children:[U(`dt`,{children:`Queue bytes`}),U(`dd`,{children:[e.traffic.health.delivery.queue_bytes,` /`,` `,e.traffic.health.delivery.queue_byte_limit]})]}),U(`div`,{children:[U(`dt`,{children:`Completions`}),U(`dd`,{children:e.traffic.health.delivery.completion_records})]})]})]})]})]}),U(`div`,{children:[U(`dt`,{children:`Diagnostic delivery`}),U(`dd`,{children:[U(vn,{value:e.diagnostics?.state,current:r===`current`}),e.diagnostics&&U(S,{children:[U(`dl`,{class:`detail-facts storage-details`,children:[U(`div`,{children:[U(`dt`,{children:`Submissions`}),U(`dd`,{children:[e.diagnostics.accepted,` accepted ·`,` `,e.diagnostics.written,` written ·`,` `,e.diagnostics.dropped,` dropped ·`,` `,e.diagnostics.invalid,` invalid`]})]}),U(`div`,{children:[U(`dt`,{children:`Queue records`}),U(`dd`,{children:[e.diagnostics.queue_records,` /`,` `,e.diagnostics.queue_limit]})]}),U(`div`,{children:[U(`dt`,{children:`Reserved bytes`}),U(`dd`,{children:e.diagnostics.queue_bytes})]}),U(`div`,{children:[U(`dt`,{children:`Write outstanding`}),U(`dd`,{children:e.diagnostics.writing?`Yes`:`No`})]}),U(`div`,{children:[U(`dt`,{children:`Write failures`}),U(`dd`,{children:e.diagnostics.write_failures})]}),U(`div`,{children:[U(`dt`,{children:`Last successful write`}),U(`dd`,{children:e.diagnostics.last_successful_write?U(Y,{value:e.diagnostics.last_successful_write}):`Not observed`})]})]}),[`failed`,`pressure`,`unavailable`].includes(e.diagnostics.state)&&U(`span`,{children:`Inspect the configured stderr destination; do not replay requests.`})]})]})]}),U(`div`,{children:[U(`dt`,{children:`Credential storage`}),U(`dd`,{children:U(vn,{value:e.keyring,current:r===`current`})})]}),U(`div`,{children:[U(`dt`,{children:`Interception CA loaded`}),U(`dd`,{children:[U(G,{state:r===`current`?`neutral`:`stale`,children:e.httpProxy?e.httpProxy.caReady?`Yes`:`No`:`Not reported`}),U(`span`,{children:`Client trust is configured separately.`})]})]}),U(`div`,{children:[U(`dt`,{children:`Backup activity`}),U(`dd`,{children:U(vn,{value:e.backupState,current:r===`current`})})]}),U(`div`,{children:[U(`dt`,{children:`Last backup`}),U(`dd`,{children:U(Y,{value:e.lastBackupAt,fallback:`No completion reported`,compact:!0})})]})]})]}),U(`section`,{class:`detail-section`,"aria-labelledby":`system-activity-title`,"data-testid":`system-request-activity`,children:[U(`h3`,{id:`system-activity-title`,children:`Request activity`}),!e.observations||e.observations.coverage===`unavailable`?U(`p`,{children:`Tracking unavailable`}):U(S,{children:[U(`p`,{class:`overview-context`,children:[e.observations.started_at===e.startedAt?`Since restart`:U(S,{children:[`Since`,` `,U(Y,{value:e.observations.started_at,compact:!0})]}),e.observations.overflow?` · Counters saturated`:``]}),U(`p`,{class:`overview-context`,children:`HTTP includes Git; CONNECT is separate. Rows are not additive.`}),U(bn,{caption:`Request activity`,children:[U(`thead`,{children:U(`tr`,{children:[U(`th`,{scope:`col`,class:`activity-protocol`,children:`Protocol`}),[`Requests`,`Execution pipelines`,`Succeeded`,`Prestart failures`,`Failed`,`Unknown`,`Nonmutating`].map(e=>U(`th`,{scope:`col`,class:`column-count`,children:e},e))]})}),U(`tbody`,{children:[`mcp`,`http`,`connect`,`git`].map(t=>{let n=e.observations.protocols.find(e=>e.protocol===t);return U(`tr`,{children:[U(`th`,{scope:`row`,class:`activity-protocol`,children:t===`git`?`Git`:t.toUpperCase()}),(n?[n.requests,n.executions,...n.results]:Array(7).fill(`Unavailable`)).map((e,t)=>U(`td`,{class:`column-count`,children:e},t))]},t)})})]})]})]}),U(`section`,{class:`detail-section`,"aria-labelledby":`system-technical-details-title`,"data-testid":`system-status-details`,children:[U(`h3`,{id:`system-technical-details-title`,children:`Technical details`}),U(`dl`,{class:`technical-details-grid`,children:[U(`div`,{children:[U(`dt`,{children:`Schema`}),U(`dd`,{children:e.schemaVersion})]}),U(`div`,{children:[U(`dt`,{children:`Revision`}),U(`dd`,{children:e.revision})]}),U(`div`,{children:[U(`dt`,{children:`Modern protocol`}),U(`dd`,{children:e.modernProtocol})]}),U(`div`,{children:[U(`dt`,{children:`Legacy protocol`}),U(`dd`,{children:e.legacyProtocol})]})]})]})]})]})}function hf({status:e,view:t}){let n=t.panels[`system-status`];if(e===void 0)return n?.status===`error`?U(K,{state:`error`,title:`Resource limits unavailable`}):U(K,{state:`loading`,title:`Loading resource limits`});let r=[...e.limits].sort((e,t)=>e.saturated===t.saturated?e.name.localeCompare(t.name):e.saturated?-1:1);return U(`section`,{class:`panel domain-panel`,"aria-labelledby":`system-limits-title`,"data-testid":`system-limits-view`,"data-panel-status":n?.status??`loading`,children:[U(`div`,{class:`panel-heading`,children:[U(`div`,{children:U(`h2`,{id:`system-limits-title`,children:`Resource limits`})}),n?.status===`current`&&U(G,{state:r.some(e=>e.saturated)?`warning`:`current`,children:r.some(e=>e.saturated)?`Attention needed`:`Available`})]}),(n?.status===`error`||n?.status===`stale`)&&U(K,{state:`stale`,title:n.status===`error`?`Refresh failed — last known limits`:`Last known limits`}),U(bn,{caption:`Gateway resource occupancy and hard limits`,children:[U(`thead`,{children:U(`tr`,{children:[U(`th`,{scope:`col`,children:`Resource`}),U(`th`,{scope:`col`,class:`column-count`,children:`In use`}),U(`th`,{scope:`col`,class:`column-count`,children:`Limit`}),U(`th`,{scope:`col`,class:`column-count`,children:`Used (%)`}),U(`th`,{scope:`col`,class:`column-status`,children:`Status`})]})}),U(`tbody`,{children:r.map(e=>U(`tr`,{"data-testid":`system-limit-row`,children:[U(`th`,{class:`system-limit-name`,scope:`row`,children:e.name===`principals`?`Agents`:e.name}),U(`td`,{class:`column-count`,children:e.inUse}),U(`td`,{class:`column-count`,children:e.limit}),U(`td`,{class:`column-count`,children:Xd(e.inUse,e.limit)}),U(`td`,{class:`column-status`,children:U(G,{state:df(e),children:e.saturated?`Saturated`:`Available`})})]},e.name))})]})]})}function gf({backups:e,controller:t,view:n,mutations:r,onRefresh:i,createMode:a}){let[o]=z(()=>r.create()),[s,c]=z(()=>o.snapshot()),[l,u]=z(),[d,f]=z(!1);B(()=>t.subscribeHistory(u),[t]),B(()=>()=>t.cancelHistory(),[t,a]);let[p,m]=z(),[h,g]=z(),_=V(null),v=V(null);B(()=>o.subscribe(c),[o]),B(()=>()=>o.close(),[o]);let y=n.panels.backups,b=y?.status??`loading`,x=s.state===`submitting`||s.availability===`storage_latched`,C=async e=>{if(e.headers.get(`Content-Type`)!==`application/json`)throw Error(`invalid response`);return rf(await e.json())},w=async e=>{if(e.status!==204)throw Error(`invalid response`)},T=async e=>{e.kind===`acknowledged`&&(g(e.value===void 0?`Backup deleted. Restore remains a stopped-process CLI operation.`:`Backup ${e.value.id} is durably published.`),o.abandon(),e.value!==void 0&&(window.location.hash=`#/system?tab=backups`),i())},E=()=>{g(void 0);let e={route:`/api/v2/backups`,method:`POST`,body:`{}`,precondition:null,requiresPrecondition:!1,idempotency:`backup_create`,successStatuses:[200,201],decode:C};o.begin(e),o.confirm()},D=()=>void o.submit().then(T),O=e=>{g(void 0),m(e);let t={route:`/api/v2/backups/${e.id}`,method:`DELETE`,body:`{}`,precondition:null,requiresPrecondition:!1,idempotency:`none`,successStatuses:[204],decode:w};o.begin(t),o.confirm()},k=()=>{m(void 0),o.abandon()},A=async()=>{m(void 0),await T(await o.submit())};return a?U(`section`,{class:`panel domain-panel`,"aria-labelledby":`backup-create-title`,"data-testid":`backup-create-view`,children:[U(`div`,{class:`panel-heading`,children:U(`div`,{children:U(`h2`,{id:`backup-create-title`,children:`Create backup`})})}),U(`p`,{children:`Security backups are immutable owner-only artifacts containing configuration, authority and administrative audit. Traffic history is omitted. Restore invalidates credentials and disables history capture; it remains a stopped-process operation.`}),s.availability===`storage_latched`&&U(K,{state:`error`,title:`Storage mutation is closed`}),s.problem!==void 0&&U(K,{state:`error`,title:s.problem.title}),s.state===`uncertain`&&U(K,{state:`warning`,title:`Backup outcome is unknown`,children:[U(`p`,{children:`Nothing is replayed automatically. Return to backup inventory and inspect current records before acting again.`}),s.canReplay&&U(`button`,{"data-testid":`backup-replay`,type:`button`,onClick:()=>void o.replay().then(T),children:`Replay this same backup create`})]}),U(`div`,{class:`form-actions`,children:[U(`a`,{class:`button-link`,href:`#/system?tab=backups`,children:`Cancel`}),U(`button`,{ref:_,class:`create-action`,"data-testid":`backup-review-create`,type:`button`,disabled:x,onClick:E,children:`Review and create`})]}),U(jn,{id:`backup-create-confirm`,open:s.state===`confirming`,title:`Review backup`,consequence:`Create one security-only recovery artifact. Optional traffic history is omitted. Restore remains a separate stopped-process operation.`,confirmLabel:`Create backup`,returnFocus:_,onCancel:()=>o.abandon(),onConfirm:D})]}):U(S,{children:[U(`section`,{class:`panel domain-panel`,"aria-labelledby":`backups-title`,"data-testid":`backups-view`,children:[U(`div`,{class:`panel-heading`,children:[U(`div`,{children:[U(`h2`,{id:`backups-title`,children:`Control-plane backups`}),U(`p`,{children:`Recovery artifacts for configuration, grants, credentials and administrative audit. New backups omit traffic history.`})]}),b!==`current`&&U(G,{state:b,children:W(b)})]}),U(`div`,{class:`collection-toolbar collection-toolbar-after-copy`,children:U(`a`,{class:`button-link create-action`,"data-testid":`backup-create`,href:`#/system/backups/new`,children:`Create backup`})}),s.availability===`storage_latched`&&U(K,{state:`error`,title:`Storage mutation is closed`,children:U(`p`,{children:`Reads remain available. Use stopped verification and recovery guidance; navigation cannot clear the latch.`})}),s.problem!==void 0&&U(K,{state:`error`,title:s.problem.title}),s.state===`uncertain`&&U(K,{state:`warning`,title:`Backup outcome is unknown`,children:[U(`p`,{children:`Refresh backups before taking another action.`}),s.canReplay&&U(`button`,{"data-testid":`backup-replay`,type:`button`,onClick:()=>void o.replay().then(T),children:`Replay this same backup create`})]}),h!==void 0&&U(K,{state:`empty`,title:h}),b===`error`&&e!==void 0&&U(K,{state:`stale`,title:`Last-known backups`,children:`The inventory and count are stale. Use Refresh to try again.`}),b===`error`&&e===void 0?U(K,{state:`error`,title:`Backups unavailable`}):b===`loading`&&y?.hasValue!==!0||e===void 0?U(K,{state:`loading`,title:`Loading backups`}):U(Dn,{caption:`Published backup artifacts`,emptyTitle:`No backups`,localStale:b===`error`,summaryExtra:U(`output`,{class:`table-filter-summary`,children:[e.length,` `,e.length===1?`backup`:`backups`,b===`error`?` (last-known)`:``]}),rowHeaderKey:`backup`,items:e,rowKey:e=>e.id,rowTestID:`backup-row`,initialSort:{key:`created`,direction:`descending`},columns:[{key:`backup`,label:`Backup`,role:`identity`,render:e=>U(q,{primary:e.history===`omitted`?`Security backup · history omitted`:`Legacy backup`,secondary:e.id})},{key:`source`,label:`Source`,role:`text`,render:e=>U(S,{children:[`Schema `,e.schemaVersion,U(`span`,{class:`table-secondary`,children:[`Revision `,e.sourceRevision]})]})},{key:`size`,label:`Size`,role:`measure`,sortValue:e=>e.sizeBytes,render:e=>`${e.sizeBytes.toLocaleString()} bytes`},{key:`created`,label:`Created`,role:`time`,sortValue:e=>e.createdAt,render:e=>U(Y,{value:e.createdAt})},{key:`actions`,label:`Actions`,role:`actions`,render:e=>U(`div`,{class:`inline-actions`,children:U(`button`,{class:`danger-action`,"data-testid":`backup-delete`,type:`button`,disabled:x,onClick:t=>{v.current=t.currentTarget,O(e)},children:`Delete`})})}]}),U(jn,{id:`backup-delete-confirm`,open:p!==void 0&&s.state===`confirming`,title:`Delete backup artifact?`,consequence:U(`p`,{children:[`Backup `,p?.id,` is permanently removed. This does not restore, reset, or change the running database.`]}),confirmLabel:`Delete backup`,destructive:!0,returnFocus:v,onCancel:k,onConfirm:()=>void A()})]}),U(`section`,{class:`panel domain-panel`,"aria-labelledby":`history-export-title`,"data-testid":`history-export`,children:[U(`h2`,{id:`history-export-title`,children:`Traffic history export`}),U(`p`,{children:`Download retained MCP, HTTP and Git records, separate from recovery backups. Not an atomic snapshot or a complete traffic audit; missing records never prove nonexecution.`}),U(`div`,{class:`form-actions history-export-actions`,children:[U(`button`,{type:`button`,class:`primary-action`,disabled:l?.kind===`reading`,onClick:()=>{f(!1),t.exportHistory()},children:`Download JSON`}),l?.kind===`reading`&&U(`button`,{type:`button`,onClick:()=>{t.cancelHistory(),f(!0)},children:`Cancel export`})]}),U(`div`,{class:`history-export-status`,role:`status`,"aria-live":`polite`,children:[l?.kind===`reading`&&U(`p`,{children:[`Reading history: `,l.records.toLocaleString(),` records ·`,` `,l.pages,` `,l.pages===1?`page`:`pages`,` ·`,` `,l.bytes.toLocaleString(),` bytes received`]}),d&&U(`p`,{children:`Export cancelled. No file was downloaded.`}),l?.kind===`complete`&&U(`p`,{children:l.message})]}),l?.kind===`error`&&U(K,{state:`error`,title:`History export stopped`,children:l.message}),U(`p`,{class:`muted`,children:`Browser limit: 64 MiB, 2 minutes, 4,096 pages. Larger exports require the bounded CLI procedure in the backup and recovery guide. No partial file is saved. Downloaded history can contain identifying data; store it privately.`})]})]})}function _f({credentials:e,view:t,mutations:n,sinks:r,onRefresh:i,createMode:a}){let[o]=z(()=>n.create()),[s,c]=z(()=>o.snapshot()),[l,u]=z(``),[d,f]=z(),[p,m]=z(`create`),[h,g]=z(),[_,v]=z(),[y,b]=z();Cr(l!==``);let x=V(null),C=V(null);B(()=>o.subscribe(c),[o]),B(()=>()=>o.close(),[o]),B(()=>()=>d?.cancel(),[d]);let w=t.panels[`admin-credentials`],T=w?.status??`loading`,E=e?.filter(e=>e.status===`active`&&e.nonExpiring).length??0,D=s.state===`submitting`||s.availability===`storage_latched`,O=async e=>{if(e.headers.get(`Content-Type`)!==`application/json`)throw Error(`invalid response`);return nf(await e.json())},k=async e=>{if(e.status!==204)throw Error(`invalid response`)},A=()=>{if(v(void 0),b(void 0),!document.getElementById(`admin-credential-expiry`).validity.valid){b(`Choose a complete expiry date and time, or clear it for a non-expiring credential.`);return}let e=null;if(l!==``){let t=Date.parse(l),n=t-Date.now();if(!Number.isFinite(t)||n<3e5||n>31536e6){b(`Choose an expiry from 5 minutes through 365 days in the future.`);return}e=new Date(t).toISOString()}m(`create`),f(void 0);let t={route:`/api/v2/admin-credentials`,method:`POST`,body:JSON.stringify({expires_at:e}),precondition:null,requiresPrecondition:!1,idempotency:`none`,successStatuses:[201],decode:O};o.begin(t),o.confirm()},j=async()=>{let e=r.prepareOneTime(`New administrator bearer`);if(e===void 0){v(`The protected one-time display could not be prepared. No credential was created.`),o.abandon();return}let t=await o.submit();if(t.kind===`acknowledged`&&t.value!==void 0){let n=e.publish(t.value.bearer);v(n===`published`?`The one-time administrator bearer is ready. It cannot be revealed again.`:`The created credential may be active, but its bearer was lost and cannot be recovered. Review credential metadata and explicitly revoke it if unusable before creating a deliberate replacement. Nothing was replayed.`),f(void 0),u(``),o.abandon(),i();return}t.kind===`uncertain`?e.lose():e.cancel(),f(void 0)},M=e=>{v(void 0),m(`revoke`),g(e);let t={route:`/api/v2/admin-credentials/${e.id}`,method:`DELETE`,body:`{}`,precondition:null,requiresPrecondition:!1,idempotency:`none`,successStatuses:[204],decode:k};o.begin(t),o.confirm()},N=()=>{g(void 0),o.abandon()},ee=async()=>{let e=await o.submit();g(void 0),e.kind===`acknowledged`&&(v(`Administrator credential revoked. Every child browser session authenticated by it is closed.`),o.abandon(),i())};return a?U(`section`,{class:`panel domain-panel`,"aria-labelledby":`admin-credential-create-title`,"data-testid":`admin-credential-create-view`,children:[U(`div`,{class:`panel-heading`,children:U(`div`,{children:U(`h2`,{id:`admin-credential-create-title`,children:`Create admin credential`})})}),U(`p`,{children:`Gateway creates a permanent credential identity and displays its bearer once. The expiry cannot be changed after creation.`}),U(J,{id:`admin-credential-expiry`,label:`Expires`,hint:`Choose a date and time in your local timezone, from 5 minutes through 365 days ahead. Leave blank for a non-expiring credential.`,optional:!0,...y===void 0?{}:{error:y},children:e=>U(`input`,{...e,"data-testid":`admin-credential-expiry`,type:`datetime-local`,step:`1`,value:l,disabled:D,onInput:e=>{u(e.currentTarget.value),b(void 0)}})}),s.problem!==void 0&&U(K,{state:`error`,title:s.problem.title}),_!==void 0&&U(K,{state:`empty`,title:_}),s.state===`uncertain`&&U(K,{state:`warning`,title:`Credential outcome is unknown`,children:U(`p`,{children:`Do not replay. The credential may be active while its bearer is permanently lost. Refresh metadata, then explicitly revoke an unusable credential before creating a deliberate replacement.`})}),U(`div`,{class:`form-actions`,children:[U(`a`,{class:`button-link`,href:`#/system?tab=admin-credentials`,children:`Cancel`}),U(`button`,{ref:x,class:`create-action`,"data-testid":`admin-credential-create`,type:`button`,disabled:D,onClick:A,children:`Review and create`})]}),U(jn,{id:`admin-credential-create-confirm`,open:s.state===`confirming`&&p===`create`,title:`Review admin credential`,consequence:U(`div`,{class:`review-stack`,children:[U(`p`,{children:`Create one administrator authority whose bearer is displayed once.`}),U(`dl`,{class:`detail-facts`,children:U(`div`,{children:[U(`dt`,{children:`Expires`}),U(`dd`,{children:l===``?`No expiry`:U(Y,{value:Number.isFinite(Date.parse(l))?new Date(l).toISOString():l})})]})})]}),confirmLabel:`Create admin credential`,returnFocus:x,onCancel:()=>o.abandon(),onConfirm:()=>void j()})]}):U(`section`,{class:`panel domain-panel`,"aria-labelledby":`admin-credentials-title`,"data-testid":`admin-credentials-view`,"data-panel-status":T,children:[U(`div`,{class:`panel-heading`,children:[U(`div`,{children:U(`h2`,{id:`admin-credentials-title`,children:`Admin credentials`})}),T!==`current`&&U(G,{state:T,children:W(T)})]}),U(`div`,{class:`collection-toolbar collection-toolbar-after-copy`,children:U(`a`,{class:`button-link create-action`,"data-testid":`admin-credential-create`,href:`#/system/admin-credentials/new`,children:`Create admin credential`})}),s.problem!==void 0&&U(K,{state:`error`,title:s.problem.title,children:U(`p`,{children:`No force or silent overwrite path is available.`})}),s.state===`uncertain`&&U(K,{state:`warning`,title:`Credential outcome is unknown`,children:U(`p`,{children:p===`create`?`Do not replay. The credential may be active while its bearer is permanently lost. Refresh metadata, then explicitly revoke an unusable credential before creating a deliberate replacement.`:`Do not replay revoke. The credential may already be revoked and child sessions may already be closed. Refresh metadata before another explicit action.`})}),_!==void 0&&U(K,{state:`empty`,title:_}),T===`error`&&e!==void 0&&U(K,{state:`stale`,title:`Last-known administrator credentials`,children:`The inventory and count are stale. Use Refresh to try again.`}),T===`error`&&e===void 0?U(K,{state:`error`,title:`Administrator credentials unavailable`}):T===`loading`&&w?.hasValue!==!0||e===void 0?U(K,{state:`loading`,title:`Loading administrator credentials`}):U(Dn,{caption:`Admin credentials`,emptyTitle:`No administrator credentials`,localStale:T===`error`,rowHeaderKey:`fingerprint`,initialSort:{key:`created`,direction:`descending`},additionalSorts:[{key:`id`,label:`Credential ID`,sortValue:e=>e.id}],items:[...e].sort((e,t)=>t.createdAt.localeCompare(e.createdAt)),rowKey:e=>e.id,rowTestID:`admin-credential-row`,filters:[{key:`identity`,label:`Fingerprint or ID`,type:`text`,value:()=>``,literalValues:e=>[e.fingerprint,e.id]},{key:`status`,label:`Status`,type:`select`,value:e=>e.status,options:[{value:`active`,label:`Active`},{value:`revoked`,label:`Revoked`},{value:`expired`,label:`Expired`}]}],columns:[{key:`fingerprint`,label:`Credential`,role:`identity`,render:e=>U(q,{primary:U(`code`,{children:e.fingerprint}),secondary:e.id}),sortValue:e=>e.fingerprint},{key:`status`,label:`Status`,role:`status`,render:e=>U(G,{state:e.status===`active`?`current`:`neutral`,children:W(e.status)}),sortValue:e=>e.status},{key:`created`,label:`Created`,role:`time`,render:e=>U(Y,{value:e.createdAt}),sortValue:e=>e.createdAt},{key:`expires`,label:`Expires`,role:`time`,render:e=>U(Y,{value:e.expiresAt,fallback:`No expiry`}),sortValue:e=>e.expiresAt??``},{key:`actions`,label:`Actions`,role:`actions`,render:e=>{let t=e.status===`active`&&e.nonExpiring&&E<=1;return e.status===`active`?U(S,{children:[U(`button`,{class:`danger-action`,"data-testid":`admin-credential-revoke`,type:`button`,disabled:D||t,"aria-describedby":t?`protected-revoke-${e.id}`:void 0,onClick:t=>{C.current=t.currentTarget,M(e)},children:`Revoke`}),t&&U(`p`,{id:`protected-revoke-${e.id}`,class:`table-secondary table-action-guidance`,children:`The last active non-expiring administrator credential cannot be revoked.`})]}):`—`}}]}),U(jn,{id:`admin-credential-revoke-confirm`,open:h!==void 0&&s.state===`confirming`,title:`Revoke administrator credential?`,consequence:U(`p`,{children:[`Credential `,h?.fingerprint,` stops authenticating and all of its child browser sessions close. This cannot be forced or undone.`]}),confirmLabel:`Revoke administrator credential`,destructive:!0,returnFocus:C,onCancel:N,onConfirm:()=>void ee()})]})}function vf({controller:e,overview:t,session:n,mutations:r,sinks:i,view:a,onRefresh:o}){let[s,c]=z(e.snapshot()),[l,u]=z(e.credentialSnapshot()),[d,f]=z(e.backupSnapshot());B(()=>e.subscribe(c),[e]),B(()=>e.subscribeCredentials(u),[e]),B(()=>e.subscribeBackups(f),[e]);let p=lf(a.viewKey);return U(`div`,{class:`system-view`,"data-testid":`system-view`,children:[U(pf,{current:p}),p===`status`?U(mf,{status:s,view:a}):p===`resource-limits`?U(hf,{status:s,view:a}):p===`needs-attention`?U(zl,{controller:t,view:a}):p===`admin-credentials`?U(_f,{credentials:l,view:a,mutations:r,sinks:i,onRefresh:o,createMode:a.viewKey===`#/system/admin-credentials/new`}):p===`backups`?U(gf,{backups:d,controller:e,view:a,mutations:r,onRefresh:o,createMode:a.viewKey===`#/system/backups/new`}):U(`section`,{class:`panel`,"aria-labelledby":`system-later-title`,children:[U(`div`,{class:`panel-heading`,children:[U(`div`,{children:U(`h2`,{id:`system-later-title`,children:`Workflow not yet available`})}),U(G,{state:`unavailable`,children:`Unavailable`})]}),U(`p`,{children:`This System workflow is reserved for a later delivery slice.`})]})]})}var yf=class{message;listeners=new Set;timer;subscribe(e){return this.listeners.add(e),e(this.message),()=>this.listeners.delete(e)}show(e){let t=e.trim();t.length===0||t.length>160||(this.timer!==void 0&&clearTimeout(this.timer),this.message=t,this.emit(),this.timer=setTimeout(()=>this.clear(),5e3))}clear(){this.timer!==void 0&&clearTimeout(this.timer),this.timer=void 0,this.message!==void 0&&(this.message=void 0,this.emit())}emit(){for(let e of this.listeners)e(this.message)}};function bf({coordinator:e}){let[t,n]=z();return B(()=>e.subscribe(n),[e]),t===void 0?null:U(`div`,{class:`toast`,role:`status`,"aria-live":`polite`,"data-testid":`toast`,children:[U(`span`,{children:t}),U(`button`,{type:`button`,"aria-label":`Dismiss notification`,onClick:()=>e.clear(),children:`×`})]})}var xf=`agent_gateway_theme`,Sf=`mcp_gateway_theme`,Cf=`(prefers-color-scheme: dark)`;function wf(e){return e===`system`||e===`light`||e===`dark`}function Tf(){try{let e=window.localStorage.getItem(xf);if(wf(e))return Ef(e),e;let t=window.localStorage.getItem(Sf);if(wf(t))return Ef(t),t;e!==null&&window.localStorage.removeItem(xf)}catch{return`system`}return`system`}function Ef(e){try{window.localStorage.setItem(xf,e),window.localStorage.removeItem(Sf)}catch{}}function Df(e){return e===`system`?window.matchMedia(Cf).matches?`dark`:`light`:e}function Of(e){document.documentElement.dataset.theme=Df(e),document.documentElement.dataset.themePreference=e}function kf(e,t){if(e!==`system`)return()=>{};let n=window.matchMedia(Cf);return n.addEventListener(`change`,t),()=>n.removeEventListener(`change`,t)}var Af=[{destinations:[`overview`,`principals`,`audit`,`system`]},{label:`HTTP`,destinations:[`http-credentials`,`http-grants`,`http-traffic`]},{label:`Git`,destinations:[`git-routing`,`git-credentials`,`git-repositories`,`git-grants`,`git-traffic`]},{label:`MCP`,destinations:[`servers`,`catalog`,`grants`,`requests`,`invocations`]}],jf={overview:`Overview`,servers:`Servers`,catalog:`Tools`,principals:`Agents`,"git-routing":`Routing`,"git-repositories":`Repositories`,"git-grants":`Grants`,"git-credentials":`Credentials`,"git-traffic":`Traffic`,"http-credentials":`Credentials`,"http-grants":`Grants`,"http-traffic":`Traffic`,grants:`Grants`,requests:`Access requests`,invocations:`Invocations`,audit:`Audit Log`,system:`System`,"sign-in":`Sign in`},Mf={...jf,"git-routing":`Git Routing`,"git-repositories":`Git Repositories`,"git-grants":`Git Grants`,"git-credentials":`Git Credentials`,"git-traffic":`Git Traffic`,"http-credentials":`HTTP Credentials`,"http-grants":`HTTP Grants`,"http-traffic":`HTTP Traffic`,servers:`MCP Servers`,catalog:`MCP Tools`,grants:`MCP Grants`,requests:`MCP Access Requests`,invocations:`MCP Invocations`},Nf=fn(!1),Pf=Tf(),Ff=new Un,If=new ki(Ff),Lf=new yf,Rf=new Pr(Ff),zf=new Bd(Ff,Rf),Bf=new wc(Ff,{refreshCurrent:()=>Rf.manualRefresh()}),Vf=new Il(Ff,Rf,e=>Bf.setStorageLatched(e)),Hf=new cr(Ff,Rf),Uf=new ec(Ff,Rf),Wf=new Yu(Ff,Rf),Gf=new pu(Ff,Rf),Kf=new $o(Ff,Rf),qf=new uf(Ff,Rf,e=>Bf.setStorageLatched(e)),Jf=new ro(Ff,Rf),Yf=(e,t,n)=>Rf.registerPanel({id:e,matches:t,invalidations:n,read:async()=>null,publish:()=>void 0});Yf(`git-invalidation`,e=>/^#\/git\/(?:routing|repositories|grants|credentials)(?:[/?]|$)/.test(e)||/^#\/git\/traffic\//.test(e),[`authorization`,`system_status`]),Yf(`http-policy-invalidation`,e=>/^#\/http\/grants(?:[/?]|$)/.test(e),[`authorization`,`http_credentials`]),Yf(`http-credential-invalidation`,e=>/^#\/http\/credentials(?:[/?]|$)/.test(e),[`http_credentials`]),Yf(`principal-invalidation`,e=>/^#\/agents(?:[/?]|$)/.test(e),[`authorization`]),Yf(`grant-invalidation`,e=>/^#\/mcp\/grants(?:[/?]|$)/.test(e),[`authorization`,`servers`]),Yf(`request-list-invalidation`,e=>e===`#/mcp/access-requests`||e.startsWith(`#/mcp/access-requests?`),[`grant_requests`]),Yf(`request-detail-invalidation`,e=>/^#\/mcp\/access-requests\/[0-7][0-9A-HJKMNP-TV-Z]{25}$/.test(e),[`grant_requests`,`servers`,`catalog`]),Of(Pf);function Xf({snapshot:e,onAuthenticated:t}){let n=V(null),[r,i]=z(!1);return U(`section`,{class:`panel sign-in-panel`,"aria-labelledby":`sign-in-title`,children:[U(`div`,{class:`panel-heading`,children:U(`h2`,{id:`sign-in-title`,children:`Administrator access`})}),U(`form`,{autocomplete:`off`,onSubmit:async e=>{e.preventDefault();let a=n.current;if(a===null||a.value.length===0||r)return;let o=a.value;a.value=``,i(!0);let s=Ff.exchange(o);o=``;let c=await s;a.value=``,i(!1),c?t():a.focus()},children:[U(J,{id:`admin-bearer`,label:`Administrator bearer`,hint:`Cleared after handoff and never saved.`,required:!0,children:t=>U(`input`,{...t,ref:n,"data-testid":`admin-bearer-input`,type:`password`,autocomplete:`off`,autocapitalize:`none`,spellcheck:!1,disabled:r||e.lifecycle!==`signed_out`,required:!0})}),U(`button`,{class:`primary-action form-submit-action`,"data-testid":`sign-in-submit`,type:`submit`,disabled:r||e.lifecycle!==`signed_out`,children:r?`Signing in…`:`Sign in`})]}),e.message!==void 0&&U(`p`,{class:`session-message`,role:`alert`,"data-testid":`session-message`,children:e.message})]})}function Zf({lifecycle:e}){let t=e===`bootstrapping`;return U(K,{state:t?`loading`:`unavailable`,title:t?`Restoring session`:`Session lost`,children:U(`p`,{children:t?`Checking for current local browser authority.`:`Discarding prior authority and checking once for a current session.`})})}function Qf(){let[e,t]=z(Ff.snapshot()),[n,r]=z(Nf),[i,a]=z(Rf.snapshot()),[o,s]=z(Bf.snapshot()),[c,l]=z(Pf),[u,d]=z(!1),[f,p]=z(!1),[m,h]=z(),g=V(e.lifecycle),_=V(Nf.canonicalFragment),v=V(!1),y=V(new Set),b=V(null),x=V(null),S=V(null),C=V(null),w=V(!1),T=V(),E=Ce((e,t)=>{(t?!y.current.has(e):y.current.has(e))&&(t?y.current.add(e):y.current.delete(e))},[]),D=Ce((e,t=!1)=>{if(e!==window.location.hash){if(!t&&y.current.size!==0){h(e);return}v.current=t,window.location.hash=e}},[]);Sr(Se(()=>({setDirty:E,navigate:D}),[D,E])),B(()=>{let e=Ff.subscribe(t);return Ff.start(),e},[]),B(()=>Rf.subscribe(a),[]),B(()=>Bf.subscribe(s),[]),B(()=>{let t=e.lifecycle===`authenticated`,n=g.current;t&&(window.location.hash===`#/sign-in`||window.location.hash===``)?dn(!0):e.lifecycle===`signed_out`&&(n===`authenticated`||n===`reauthenticating`||n===`bootstrapping`)&&dn(!1),g.current=e.lifecycle;let i=fn(t);_.current=i.canonicalFragment,r(e=>({...i,invalid:e.invalid||i.invalid})),t&&Rf.activate(i.canonicalFragment)},[e.lifecycle,e.epoch]),B(()=>{let t=()=>{if(v.current)v.current=!1;else if(y.current.size!==0&&window.location.hash!==_.current&&!window.confirm(`Leave this page? Unsaved changes will be discarded.`)){window.history.pushState(null,``,_.current);return}If.clearForNavigation();let t=fn(e.lifecycle===`authenticated`);_.current=t.canonicalFragment,r(t),e.lifecycle===`authenticated`&&Rf.navigate(t.canonicalFragment)};return window.addEventListener(`hashchange`,t),()=>window.removeEventListener(`hashchange`,t)},[e.lifecycle]),B(()=>{let e=e=>{y.current.size!==0&&(e.preventDefault(),e.returnValue=``)};return window.addEventListener(`beforeunload`,e),()=>window.removeEventListener(`beforeunload`,e)},[]),B(()=>(Of(c),kf(c,()=>Of(c))),[c]),B(()=>{let t=n.location.destination===`servers`&&n.location.segments[1]!==void 0&&n.location.segments[1]!==`new`?n.location.segments[1]:void 0,r=n.location.destination===`principals`&&n.location.segments[1]!==void 0&&n.location.segments[1]!==`new`?n.location.segments[1]:void 0,i=n.location.destination===`invocations`||n.location.destination===`http-traffic`?n.location.segments[1]:void 0,a=n.location.destination===`grants`&&n.location.segments[1]!==`new`?n.location.segments[1]:void 0,o=n.location.destination===`requests`?n.location.segments[1]:void 0,s=n.location.destination===`audit`?n.location.segments[1]:void 0,c=[`http-credentials`,`http-grants`,`git-repositories`,`git-credentials`,`git-grants`,`git-traffic`].includes(n.location.destination)&&n.location.segments[1]!==`new`&&n.location.segments[1]!==`test-access`?n.location.segments[1]:void 0,l=t===void 0?void 0:n.location.segments[3],u=r??i??a??o??s??c,f=t===void 0?u===void 0?n.location.destination:`${n.location.destination}:${u}`:`server:${t}:${l??``}`,m;if(e.lifecycle===`authenticated`&&T.current!==f){if(T.current=f,t===void 0&&u===void 0)b.current?.focus();else{let e=()=>{let e=document.querySelector(l===void 0?t===void 0?`[data-testid="detail-context"] h1`:`[data-testid="server-context"] h1`:`[data-testid="detail-context"] h1`);return e?.focus(),e!==null};e()||(m=new MutationObserver(()=>{e()&&m?.disconnect()}),m.observe(document.body,{childList:!0,subtree:!0}))}}else e.lifecycle===`signed_out`&&w.current&&(w.current=!1,T.current=void 0,b.current?.focus());return e.lifecycle!==`authenticated`&&(T.current=void 0,d(!1),p(!1),Lf.clear()),()=>m?.disconnect()},[n.canonicalFragment,e.lifecycle]);let O=e=>{Ef(e),l(e)},k=n.location.destination,A=k===`servers`&&n.location.segments[1]!==void 0&&n.location.segments[1]!==`new`,j=k===`principals`&&n.location.segments[1]!==void 0&&n.location.segments[1]!==`new`,M=k===`invocations`&&n.location.segments[1]!==void 0,N=k===`grants`&&n.location.segments[1]!==void 0&&n.location.segments[1]!==`new`,ee=k===`requests`&&n.location.segments[1]!==void 0,P=(k===`git-repositories`||k===`git-grants`||k===`git-credentials`||k===`git-traffic`||k===`http-credentials`||k===`http-grants`||k===`http-traffic`)&&n.location.segments[1]!==void 0&&n.location.segments[1]!==`new`&&n.location.segments[1]!==`test-access`||A||j||M||N||ee||k===`audit`&&n.location.segments[1]!==void 0,te=k.startsWith(`git-`)&&n.location.segments[1]===`new`?`Create Git ${k===`git-repositories`?`repository`:k===`git-credentials`?`credential`:`grant`}`:k===`http-grants`&&n.location.segments[1]===`new`?`Create HTTP grant`:k===`http-grants`&&n.location.segments[1]===`test-access`?`Test HTTP access`:k===`http-credentials`&&n.location.segments[1]===`new`?`Create HTTP credential`:k===`servers`&&n.location.segments[1]!==void 0?n.canonicalFragment===`#/mcp/servers/new`?`Create MCP Server`:`MCP Server details`:k===`principals`&&n.canonicalFragment===`#/agents/new`?`Create agent`:k===`grants`&&n.canonicalFragment.startsWith(`#/mcp/grants/new`)?`Create MCP Grant`:n.canonicalFragment===`#/system/backups/new`?`Create backup`:n.canonicalFragment===`#/system/admin-credentials/new`?`Create admin credential`:Mf[k],F=e.lifecycle===`authenticated`,ne=zf.presentation(i);return U(`div`,{class:`shell ${F?`authenticated`:`signed-out`}`,"data-testid":`gateway-shell`,"data-session-lifecycle":e.lifecycle,"data-view-generation":i.generation,"data-freshness":i.freshness,"data-mutation-availability":o,onClickCapture:e=>{if(e.button!==0||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey)return;let t=e.target;if(!(t instanceof Element))return;let n=t.closest(`a`),r=n?.getAttribute(`href`);n===null||r==null||!r.startsWith(`#/`)||n.target!==``||(e.preventDefault(),C.current=n,D(r))},onKeyDown:e=>{!u||e.key!==`Escape`||(e.preventDefault(),d(!1),x.current?.focus())},children:[U(`a`,{class:`skip-link`,href:`#main-content`,onClick:e=>{e.preventDefault(),b.current?.focus()},children:`Skip to main content`}),U(`div`,{class:`visually-hidden`,role:`status`,"aria-live":`polite`,"aria-atomic":`true`,"data-testid":`shell-announcement`,children:F?`${te}. Data ${i.freshness}.`:`${te}. Authentication required.`}),U(`header`,{class:`masthead`,children:[U(`a`,{class:`wordmark`,href:`#/overview`,"aria-label":`Agent Gateway overview`,children:[U(`img`,{"aria-hidden":`true`,class:`mark`,src:`/assets/favicon.svg`,alt:``}),U(`span`,{children:`Agent Gateway`})]}),U(`div`,{class:`masthead-controls`,children:[F&&U(`button`,{ref:x,class:`navigation-toggle`,"data-testid":`navigation-toggle`,type:`button`,"aria-expanded":u,"aria-controls":`primary-navigation`,onClick:()=>d(e=>!e),children:[U(`span`,{"aria-hidden":`true`,children:`≡`}),`Menu`]}),F&&U(`div`,{class:`freshness-control`,children:[i.freshness!==`current`&&U(G,{state:i.freshness,children:i.freshness===`stale`?`Stale`:`Reconnecting`}),U(`button`,{class:`quiet-action`,"data-testid":`manual-refresh`,type:`button`,"aria-label":`Refresh current view`,onClick:()=>Rf.manualRefresh(),children:[U(`span`,{"aria-hidden":`true`,children:`↻`}),U(`span`,{class:`refresh-label`,children:`Refresh`})]})]}),U(`label`,{class:`theme-control`,children:[U(`span`,{class:`visually-hidden`,children:`Theme`}),U(`select`,{"data-testid":`theme-preference`,"aria-label":`Theme preference`,value:c,onChange:e=>O(e.currentTarget.value),children:[U(`option`,{value:`system`,children:`System`}),U(`option`,{value:`light`,children:`Light`}),U(`option`,{value:`dark`,children:`Dark`})]})]}),F&&U(`button`,{ref:S,class:`quiet-action`,"data-testid":`logout`,type:`button`,onClick:()=>p(!0),children:`Sign out`})]})]}),F&&U(`aside`,{id:`primary-navigation`,class:`rail ${u?`open`:``}`,"aria-label":`Primary navigation`,children:U(`nav`,{"aria-label":`Primary`,children:Af.map(e=>U(`div`,{class:`navigation-group`,role:e.label?`group`:void 0,"aria-label":e.label,children:[e.label&&U(`span`,{class:`navigation-group-label`,"aria-hidden":`true`,children:e.label}),U(`div`,{class:`navigation-links`,children:e.destinations.map(e=>{let t=k===e;return U(`a`,{class:t?`active`:void 0,href:`#/${qt[e]}`,"aria-current":t?`page`:void 0,"aria-label":e===`requests`?ne.label:void 0,title:e===`requests`?ne.label:void 0,onClick:()=>d(!1),children:[e===`requests`?`Requests`:jf[e],e===`requests`&&ne.badge!==null&&U(`span`,{class:`request-count`,"aria-hidden":`true`,"data-testid":`pending-request-count`,children:ne.badge})]},e)})})]},e.label??e.destinations[0]))})}),U(`main`,{id:`main-content`,class:`workspace`,tabindex:-1,children:[n.invalid&&U(`p`,{class:`location-notice`,role:`status`,"data-testid":`location-notice`,children:`The requested location was invalid. A safe location was restored.`}),U(`section`,{class:`intro`,"aria-labelledby":F&&j?void 0:`page-title`,children:[F&&P?U(`span`,{ref:e=>{b.current=e},id:`page-title`,class:`visually-hidden`,tabindex:-1,children:A?`MCP Server details`:j?`Agent details`:M?`MCP Invocation details`:N?`MCP Grant details`:ee?`MCP Access Request details`:k===`http-credentials`?`HTTP Credential details`:k===`http-grants`?`HTTP Grant details`:k===`http-traffic`?`HTTP Traffic details`:k===`git-repositories`?`Git Repository details`:k===`git-credentials`?`Git Credential details`:k===`git-grants`?`Git Grant details`:k===`git-traffic`?`Git Traffic details`:`Audit event details`}):U(`h1`,{ref:e=>{b.current=e},id:`page-title`,class:F&&A?`visually-hidden`:void 0,tabindex:-1,children:F?te:`Sign in`}),U(`div`,{class:`visually-hidden`,children:U(G,{state:F?`current`:`unavailable`,testID:`authentication-status`,children:F?`Authenticated`:`Authentication required`})})]}),e.lifecycle===`bootstrapping`||e.lifecycle===`reauthenticating`?U(Zf,{lifecycle:e.lifecycle}):F?k===`overview`?U(Bl,{controller:Vf,principals:Kf,view:i}):k===`audit`?U(gr,{controller:Hf,resolved:n,view:i,navigate:D}):k===`http-traffic`?U(Xu,{controller:Wf,principals:Kf,view:i,navigate:D}):k===`invocations`?U(rc,{controller:Uf,principals:Kf,view:i,navigate:D}):k===`system`?U(vf,{controller:qf,overview:Vf,session:Ff,mutations:Bf,sinks:If,view:i,onRefresh:()=>Rf.manualRefresh()}):k===`requests`?U(Rd,{session:Ff,mutations:Bf,resolved:n,view:i,onRefresh:()=>Rf.manualRefresh()}):k===`git-routing`?U(gu,{session:Ff,mutations:Bf,view:i,onRefresh:()=>Rf.manualRefresh()}):k===`git-traffic`?U(cu,{controller:Gf,session:Ff,mutations:Bf,sinks:If,resolved:n,view:i,onRefresh:()=>Rf.manualRefresh()},n.canonicalFragment):k===`git-repositories`||k===`git-grants`||k===`git-credentials`?U(tu,{kind:k===`git-repositories`?`repositories`:k===`git-grants`?`grants`:`credentials`,session:Ff,mutations:Bf,sinks:If,resolved:n,view:i,onRefresh:()=>Rf.manualRefresh()},n.canonicalFragment):k===`http-grants`?U(zu,{session:Ff,mutations:Bf,resolved:n,view:i,onRefresh:()=>Rf.manualRefresh(),notify:e=>e===void 0?Lf.clear():Lf.show(e)},n.location.segments.join(`/`)):k===`http-credentials`?U(Cu,{session:Ff,mutations:Bf,sinks:If,resolved:n,view:i,onRefresh:()=>Rf.manualRefresh()},n.location.segments.join(`/`)):k===`principals`?U(cs,{session:Ff,mutations:Bf,sinks:If,resolved:n,view:i,onRefresh:()=>Rf.manualRefresh(),notify:e=>Lf.show(e)}):k===`grants`?U(ws,{session:Ff,mutations:Bf,resolved:n,view:i},n.location.segments.join(`/`)):k===`servers`||k===`catalog`?U(yo,{session:Ff,resolved:n,controller:Jf,view:i,destination:k,mutations:Bf,sinks:If,onRefresh:()=>Rf.manualRefresh(),notify:e=>Lf.show(e)}):U(`section`,{class:`panel`,"aria-labelledby":`foundation-title`,children:[U(`div`,{class:`panel-heading`,children:[U(`div`,{children:U(`h2`,{id:`foundation-title`,children:`Session established`})}),U(`span`,{class:`classification`,children:`IN MEMORY`})]}),U(`p`,{children:`Protected views bind to this location and authentication epoch. Prior requests and scheduled work cannot update the current session.`})]}):U(Xf,{snapshot:e,onAuthenticated:()=>r(fn(!0))})]}),U(Ii,{coordinator:If}),U(bf,{coordinator:Lf}),U(jn,{id:`unsaved-changes`,open:m!==void 0,title:`Discard unsaved changes?`,consequence:`Your changes on this page have not been saved.`,confirmLabel:`Discard and leave`,destructive:!0,returnFocus:C,onCancel:()=>h(void 0),onConfirm:()=>{let e=m;h(void 0),e!==void 0&&D(e,!0)}}),U(jn,{id:`logout-confirmation`,open:f,title:`Sign out of this browser session?`,consequence:U(`p`,{children:`The current local session will end. No Gateway configuration or other administrator session is changed.`}),confirmLabel:`Sign out`,returnFocus:S,onCancel:()=>p(!1),onConfirm:()=>{w.current=!0,p(!1),Ff.logout()}})]})}se(U(Qf,{}),document.getElementById(`app`)); \ No newline at end of file diff --git a/agent-gateway/internal/contract/oauth_configuration.go b/agent-gateway/internal/contract/oauth_configuration.go index 650911ce..c51afe26 100644 --- a/agent-gateway/internal/contract/oauth_configuration.go +++ b/agent-gateway/internal/contract/oauth_configuration.go @@ -13,12 +13,20 @@ import ( var ErrOAuthConfiguration = errors.New("OAuth configuration is invalid") +// ParseOAuthCallbackURI validates syntax only. HTTPS callbacks have no bind +// address and must additionally match the configured main callback exactly. func ParseOAuthCallbackURI(raw string) (*url.URL, string, error) { maximum, _ := FixedLimitByName("oauth_url_bytes") parsed, err := url.Parse(raw) - if err != nil || raw == "" || int64(len(raw)) > maximum.Maximum || parsed.Scheme != "http" || parsed.Opaque != "" || parsed.User != nil || strings.ContainsAny(raw, "?#%\\") || parsed.String() != raw || parsed.Path == "" || !strings.HasPrefix(parsed.Path, "/") || path.Clean(parsed.Path) != parsed.Path { + if err != nil || raw == "" || int64(len(raw)) > maximum.Maximum || (parsed.Scheme != "http" && parsed.Scheme != "https") || parsed.Opaque != "" || parsed.User != nil || strings.ContainsAny(raw, "?#%\\") || parsed.String() != raw || parsed.Path == "" || !strings.HasPrefix(parsed.Path, "/") || path.Clean(parsed.Path) != parsed.Path { return nil, "", ErrOAuthConfiguration } + if parsed.Scheme == "https" { + if parsed.Path != "/oauth/callback" || !validHTTPSCallbackAuthority(parsed) { + return nil, "", ErrOAuthConfiguration + } + return parsed, "", nil + } port, err := strconv.ParseUint(parsed.Port(), 10, 16) if err != nil || port == 0 || strconv.FormatUint(port, 10) != parsed.Port() { return nil, "", ErrOAuthConfiguration @@ -39,6 +47,40 @@ func ParseOAuthCallbackURI(raw string) (*url.URL, string, error) { return parsed, net.JoinHostPort(bind, parsed.Port()), nil } +func validHTTPSCallbackAuthority(parsed *url.URL) bool { + host := parsed.Hostname() + canonical, ok := NormalizeHostname(host) + if address, err := netip.ParseAddr(host); err == nil && address.Zone() == "" && !address.IsUnspecified() && !address.IsMulticast() && address.String() == host { + canonical, ok = address.String(), true + if address.Is6() { + canonical = "[" + canonical + "]" + } + } else if canonical != host { + ok = false + } + if port := parsed.Port(); port != "" { + value, err := strconv.ParseUint(port, 10, 16) + if err != nil || value == 0 || value == 443 || strconv.FormatUint(value, 10) != port { + return false + } + canonical += ":" + port + } + return ok && parsed.Host == canonical +} + +// ValidOAuthCallbackSelection binds HTTPS to configured authority, never to +// request headers. Local mode retains its callback-only loopback listeners. +func ValidOAuthCallbackSelection(main, selected string) bool { + parsed, _, err := ParseOAuthCallbackURI(selected) + if err != nil { + return false + } + if strings.HasPrefix(main, "https://") || parsed.Scheme == "https" { + return selected == main + } + return true +} + func NormalizeOAuthScopes(values []string) ([]string, error) { count, _ := FixedLimitByName("oauth_scope_count") tokenBytes, _ := FixedLimitByName("oauth_scope_token_bytes") diff --git a/agent-gateway/internal/contract/oauth_configuration_test.go b/agent-gateway/internal/contract/oauth_configuration_test.go index c7286fdd..ebf9b1d6 100644 --- a/agent-gateway/internal/contract/oauth_configuration_test.go +++ b/agent-gateway/internal/contract/oauth_configuration_test.go @@ -8,9 +8,12 @@ import ( func TestOAuthCallbackURI(t *testing.T) { for raw, bind := range map[string]string{ - "http://localhost:3118/callback": "127.0.0.1:3118", - "http://127.0.0.1:8210/oauth/callback": "127.0.0.1:8210", - "http://[::1]:3118/callback": "[::1]:3118", + "http://localhost:3118/callback": "127.0.0.1:3118", + "http://127.0.0.1:8210/oauth/callback": "127.0.0.1:8210", + "http://[::1]:3118/callback": "[::1]:3118", + "https://gateway.example/oauth/callback": "", + "https://127.0.0.1:8443/oauth/callback": "", + "https://[::1]:8443/oauth/callback": "", } { parsed, actual, err := ParseOAuthCallbackURI(raw) if err != nil || actual != bind || parsed.String() != raw { @@ -18,6 +21,11 @@ func TestOAuthCallbackURI(t *testing.T) { } } for _, raw := range []string{ + "https://gateway.example:443/oauth/callback", "https://gateway.example:/oauth/callback", + "https://GATEWAY.example/oauth/callback", "https://gateway.example/other", + "https://gateway.example/oauth/%63allback", "https://gateway.example/oauth/callback?", + "https://gateway.example/oauth/callback#", "https://user@gateway.example/oauth/callback", + "https://0.0.0.0/oauth/callback", "https://[::]/oauth/callback", "", "https://localhost:3118/callback", "http://localhost/callback", "http://localhost:0/callback", "http://localhost:65536/callback", "http://localhost:03118/callback", "http://localhost:3118", "http://user@localhost:3118/callback", "http://localhost:3118/callback?", "http://localhost:3118/callback#", @@ -33,6 +41,26 @@ func TestOAuthCallbackURI(t *testing.T) { } } +func TestOAuthCallbackSelection(t *testing.T) { + const external = "https://gateway.example:8443/oauth/callback" + const local = "http://127.0.0.1:8210/oauth/callback" + for _, test := range []struct { + main, selected string + valid bool + }{ + {external, external, true}, {local, local, true}, + {local, "http://localhost:3118/callback", true}, + {external, local, false}, {local, external, false}, + {external, "https://other.example:8443/oauth/callback", false}, + {external, "https://gateway.example/oauth/callback", false}, + {external, "https://gateway.example:8443/other", false}, + } { + if got := ValidOAuthCallbackSelection(test.main, test.selected); got != test.valid { + t.Errorf("selection %q -> %q = %v", test.main, test.selected, got) + } + } +} + func TestNormalizeOAuthScopes(t *testing.T) { original := []string{"z", "a", "z"} got, err := NormalizeOAuthScopes(original) diff --git a/agent-gateway/internal/httpboundary/boundary.go b/agent-gateway/internal/httpboundary/boundary.go index 9393aa27..b3ff3194 100644 --- a/agent-gateway/internal/httpboundary/boundary.go +++ b/agent-gateway/internal/httpboundary/boundary.go @@ -273,6 +273,11 @@ func (boundary *Boundary) validateEarly(request *http.Request) contract.ProblemC if !boundary.acceptsRequestHost(request) { return contract.ProblemMisdirectedRequest } + if request.URL.Path == "/oauth/callback" { + if request.URL.RawPath != "" || request.ContentLength != 0 || len(request.TransferEncoding) != 0 { + return contract.ProblemMalformedRequest + } + } count, total := 0, 0 for name, values := range request.Header { lower := strings.ToLower(name) diff --git a/agent-gateway/internal/httpboundary/remote_callback_test.go b/agent-gateway/internal/httpboundary/remote_callback_test.go new file mode 100644 index 00000000..a06672b5 --- /dev/null +++ b/agent-gateway/internal/httpboundary/remote_callback_test.go @@ -0,0 +1,43 @@ +package httpboundary + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestExternalCallbackRejectsWrongAuthorityPathAndBodyBeforeDispatch(t *testing.T) { + calls := 0 + boundary, err := New(Options{Authority: "0.0.0.0:8210", ExternalOrigin: "https://gateway.example:8443", AllowedHosts: []string{"inside.example"}, Next: http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { calls++; w.WriteHeader(204) })}) + require.NoError(t, err) + for _, test := range []struct { + host, path, body, header string + status int + }{ + {"gateway.example:8443", "/oauth/callback?state=fixture", "", "", 204}, + {"gateway.example", "/oauth/callback", "", "", 421}, + {"gateway.example:8444", "/oauth/callback", "", "", 421}, + {"127.0.0.1:8210", "/oauth/callback", "", "", 421}, + {"inside.example", "/oauth/callback", "", "", 421}, + {"gateway.example:8443", "/oauth/%63allback", "", "", 400}, + {"gateway.example:8443", "/oauth/callback", "body", "", 400}, + {"gateway.example:8443", "/oauth/callback", "", "Forwarded", 400}, + {"gateway.example:8443", "/oauth/callback", "", "X-Forwarded-Host", 400}, + } { + request := httptest.NewRequest("GET", test.path, strings.NewReader(test.body)) + request.Host = test.host + if test.header != "" { + request.Header.Set(test.header, "gateway.example:8443") + } + before := calls + response := httptest.NewRecorder() + boundary.ServeHTTP(response, request) + require.Equal(t, test.status, response.Code) + if test.status != 204 { + require.Equal(t, before, calls) + } + } +} diff --git a/agent-gateway/internal/oauth/flows.go b/agent-gateway/internal/oauth/flows.go index e6a7f62e..0677c132 100644 --- a/agent-gateway/internal/oauth/flows.go +++ b/agent-gateway/internal/oauth/flows.go @@ -291,6 +291,13 @@ func (service *FlowService) Create(ctx context.Context, request FlowRequest) (cr } }() configuration := prepared.Configuration + callbackURL := service.callbackURL + if configuration.Authentication.CallbackURI != nil { + callbackURL = *configuration.Authentication.CallbackURI + } + if !contract.ValidOAuthCallbackSelection(service.callbackURL, callbackURL) { + return service.fail(ctx, prepared.Flow.ID, servers.NewConfigurationError(contract.ServerConfigurationFieldCallbackURI, contract.ServerConfigurationRuleCanonicalURL), contract.OAuthDiagnosticAuthorizationRequest) + } registrationConfig := configuration.Authentication.Registration var desiredIssuer *string switch registration := registrationConfig.(type) { @@ -306,10 +313,6 @@ func (service *FlowService) Create(ctx context.Context, request FlowRequest) (cr if err != nil { return service.fail(ctx, prepared.Flow.ID, err, contract.OAuthDiagnosticMetadataDiscovery) } - callbackURL := service.callbackURL - if configuration.Authentication.CallbackURI != nil { - callbackURL = *configuration.Authentication.CallbackURI - } if callbackURL != service.callbackURL { expires, parseErr := time.Parse(time.RFC3339Nano, prepared.Flow.ExpiresAt) if service.listeners == nil || parseErr != nil { diff --git a/agent-gateway/internal/oauth/registration.go b/agent-gateway/internal/oauth/registration.go index e7e7e309..2f1b0cc7 100644 --- a/agent-gateway/internal/oauth/registration.go +++ b/agent-gateway/internal/oauth/registration.go @@ -6,6 +6,7 @@ import ( "errors" "net/http" "strconv" + "strings" "time" "unicode/utf8" @@ -169,8 +170,12 @@ func (registrar *Registrar) registerDynamic(ctx context.Context, request Registr if !ok { return servers.OAuthRegistrationAuthority{}, ErrRegistrationRejected } + applicationType := "native" + if strings.HasPrefix(request.CallbackURL, "https://") { + applicationType = "web" + } payload, err := json.Marshal(dynamicRequest{ - ApplicationType: "native", RedirectURIs: []string{request.CallbackURL}, ResponseTypes: []string{"code"}, + ApplicationType: applicationType, RedirectURIs: []string{request.CallbackURL}, ResponseTypes: []string{"code"}, GrantTypes: []string{"authorization_code", "refresh_token"}, TokenEndpointAuthMethod: method, }) if err != nil { diff --git a/agent-gateway/internal/oauth/remote_callback_test.go b/agent-gateway/internal/oauth/remote_callback_test.go new file mode 100644 index 00000000..9d1a4c76 --- /dev/null +++ b/agent-gateway/internal/oauth/remote_callback_test.go @@ -0,0 +1,73 @@ +package oauth + +import ( + "context" + "net/http" + "net/url" + "testing" + "time" + + "github.com/averycrespi/agent-tools/agent-gateway/internal/contract" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestRemoteCallbackSelectionBeforeRegistrationAndListenerAcquisition(t *testing.T) { + const main = "https://gateway.example:8443/oauth/callback" + for _, selected := range []string{"", main, "https://other.example/oauth/callback", "https://gateway.example/oauth/callback", "http://localhost:3118/callback"} { + t.Run(selected, func(t *testing.T) { + created := flowCreateResult(contract.DynamicOAuthRegistration{Mode: contract.RegistrationDynamic}) + if selected != "" { + created.Configuration.Authentication.CallbackURI = &selected + } + store := &flowStoreFake{created: created} + registration := flowRegistration() + registration.CallbackURL = main + registrar := &flowRegistrarFake{registration: registration} + service := newFlowService(store, flowResolverFake{graph: Graph{Resource: created.Configuration.Resource, Issuer: registration.Issuer, AuthorizationEndpoint: "https://issuer.example/authorize"}}, registrar, zeroReader{}, main, func() time.Time { return flowTime }) + service.listeners = callbackAcquireFunc(func(context.Context, string, string, time.Time) (func(), error) { + t.Fatal("remote flow acquired a public listener") + return nil, nil + }) + flow, err := service.Create(t.Context(), FlowRequest{ServerID: created.Flow.ServerID, ExpectedDesiredRevision: "1"}) + if selected == "" || selected == main { + require.NoError(t, err) + parsed, err := url.Parse(flow.AuthorizationURL) + require.NoError(t, err) + assert.Equal(t, main, parsed.Query().Get("redirect_uri")) + assert.Equal(t, 1, registrar.calls) + } else { + require.Error(t, err) + assert.Empty(t, flow.AuthorizationURL) + assert.Zero(t, registrar.calls) + assert.Empty(t, service.byState) + } + service.Shutdown() + }) + } +} + +func TestRemoteCallbackBindsAuthorityAndPreservesSingleExchange(t *testing.T) { + const main = "https://gateway.example:8443/oauth/callback" + store := &callbackFlowStore{flowStoreFake: flowStoreFake{created: flowCreateResult(contract.DynamicOAuthRegistration{Mode: contract.RegistrationDynamic})}} + requester := &tokenRequester{status: 200, header: http.Header{"Content-Type": {contract.MediaTypeJSON}}, body: []byte(`{"access_token":"fixture-token","token_type":"Bearer"}`)} + service := callbackService(store, requester, new(tokenSecrets)) + service.callbackURL = main + bundle := callbackBundle("remote-state", false, contract.TokenEndpointAuthNone) + bundle.registration.CallbackURL = main + service.byState[bundle.state] = bundle + query := "state=remote-state&code=fixture-code" + for _, uri := range []string{"https://other.example:8443/oauth/callback", "https://gateway.example/oauth/callback", "https://gateway.example:8443/other", "http://127.0.0.1:8210/oauth/callback"} { + assert.Equal(t, CallbackInvalid, service.HandleCallbackAt(t.Context(), query, uri, "").Outcome) + assert.Contains(t, service.byState, bundle.state) + assert.Empty(t, requester.requests) + } + require.Equal(t, CallbackSucceeded, service.HandleCallback(t.Context(), query).Outcome) + require.Len(t, requester.requests, 1) + form, err := url.ParseQuery(string(requester.requests[0].body)) + require.NoError(t, err) + assert.Equal(t, main, form.Get("redirect_uri")) + assert.Equal(t, CallbackInvalid, service.HandleCallback(t.Context(), query).Outcome) + assert.Len(t, requester.requests, 1) + service.Shutdown() +} diff --git a/agent-gateway/test/e2e/remote_oauth_test.go b/agent-gateway/test/e2e/remote_oauth_test.go new file mode 100644 index 00000000..7ddc75ef --- /dev/null +++ b/agent-gateway/test/e2e/remote_oauth_test.go @@ -0,0 +1,315 @@ +//go:build e2e + +package e2e + +import ( + "context" + "crypto/rand" + "crypto/sha256" + "encoding/base64" + "encoding/json" + "encoding/pem" + "io" + "net" + "net/http" + "net/http/httptest" + "net/http/httputil" + "net/netip" + "net/url" + "os" + "path/filepath" + "strings" + "sync" + "sync/atomic" + "syscall" + "testing" + "time" + + "github.com/averycrespi/agent-tools/agent-gateway/internal/contract" + "github.com/averycrespi/agent-tools/agent-gateway/internal/keyring" + "github.com/averycrespi/agent-tools/agent-gateway/internal/oauth" + gatewaypaths "github.com/averycrespi/agent-tools/agent-gateway/internal/paths" + "github.com/averycrespi/agent-tools/agent-gateway/internal/remote" + "github.com/averycrespi/agent-tools/agent-gateway/internal/storage" + "github.com/averycrespi/agent-tools/agent-gateway/internal/testutil" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestRemoteHTTPSOAuthThroughReverseProxy(t *testing.T) { + var issuer, callback string + var exchanges, calls atomic.Int64 + var mu sync.Mutex + challenges := map[string]string{} + provider := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", contract.MediaTypeJSON) + switch r.URL.Path { + case "/.well-known/oauth-protected-resource/mcp": + _ = json.NewEncoder(w).Encode(map[string]any{"resource": issuer + "/mcp", "authorization_servers": []string{issuer}}) + case "/.well-known/oauth-authorization-server": + _ = json.NewEncoder(w).Encode(map[string]any{"issuer": issuer, "authorization_endpoint": issuer + "/authorize", "token_endpoint": issuer + "/token", "registration_endpoint": issuer + "/register", "response_types_supported": []string{"code"}, "grant_types_supported": []string{"authorization_code", "refresh_token"}, "code_challenge_methods_supported": []string{"S256"}, "token_endpoint_auth_methods_supported": []string{"none"}, "authorization_response_iss_parameter_supported": true}) + case "/register": + var input struct { + Redirects []string `json:"redirect_uris"` + Application string `json:"application_type"` + } + if json.NewDecoder(io.LimitReader(r.Body, 16384)).Decode(&input) != nil || len(input.Redirects) != 1 || input.Redirects[0] != callback || input.Application != "web" { + w.WriteHeader(400) + return + } + w.WriteHeader(201) + _ = json.NewEncoder(w).Encode(map[string]any{"client_id": "remote-fixture", "redirect_uris": []string{callback}, "response_types": []string{"code"}, "grant_types": []string{"authorization_code", "refresh_token"}, "token_endpoint_auth_method": "none"}) + case "/authorize": + q := r.URL.Query() + if q.Get("redirect_uri") != callback || q.Get("resource") != issuer+"/mcp" || q.Get("client_id") != "remote-fixture" || q.Get("response_type") != "code" || q.Get("code_challenge_method") != "S256" || q.Get("state") == "" || q.Get("code_challenge") == "" { + w.WriteHeader(400) + return + } + code := "synthetic-code-" + q.Get("state") + mu.Lock() + challenges[code] = q.Get("code_challenge") + mu.Unlock() + w.Header().Set("Location", callback+"?"+url.Values{"state": {q.Get("state")}, "code": {code}, "iss": {issuer}}.Encode()) + w.WriteHeader(302) + case "/token": + if r.Method != "POST" || r.ParseForm() != nil { + w.WriteHeader(400) + return + } + digest := sha256.Sum256([]byte(r.Form.Get("code_verifier"))) + mu.Lock() + challenge, ok := challenges[r.Form.Get("code")] + delete(challenges, r.Form.Get("code")) + mu.Unlock() + if !ok || challenge != base64.RawURLEncoding.EncodeToString(digest[:]) || r.Form.Get("redirect_uri") != callback || r.Form.Get("resource") != issuer+"/mcp" || r.Form.Get("client_id") != "remote-fixture" || r.Form.Get("grant_type") != "authorization_code" { + w.WriteHeader(400) + return + } + exchanges.Add(1) + _ = json.NewEncoder(w).Encode(map[string]any{"access_token": "synthetic-remote-access", "refresh_token": "synthetic-remote-refresh", "token_type": "Bearer", "expires_in": 3600}) + case "/mcp": + if r.Header.Get("Authorization") != "Bearer synthetic-remote-access" { + w.WriteHeader(401) + return + } + var request struct { + ID uint64 `json:"id"` + Method string `json:"method"` + } + if json.NewDecoder(io.LimitReader(r.Body, 16384)).Decode(&request) != nil { + w.WriteHeader(400) + return + } + switch request.Method { + case "server/discover": + _, _ = io.WriteString(w, rpcResult(request.ID, `{"ttlMs":0,"cacheScope":"public","supportedVersions":["2026-07-28"],"capabilities":{}}`)) + case "tools/list": + _, _ = io.WriteString(w, rpcResult(request.ID, `{"tools":[{"name":"echo","inputSchema":{"type":"object"}}]}`)) + case "tools/call": + calls.Add(1) + _, _ = io.WriteString(w, rpcResult(request.ID, `{"content":[{"type":"text","text":"remote OAuth works"}]}`)) + default: + w.WriteHeader(400) + } + default: + w.WriteHeader(404) + } + })) + defer provider.Close() + issuer = provider.URL + certificate := filepath.Join(t.TempDir(), "fixture-ca.pem") + require.NoError(t, os.WriteFile(certificate, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: provider.Certificate().Raw}), 0600)) + t.Setenv("SSL_CERT_FILE", certificate) + harness := newGatewayHarness(t) + backend, err := url.Parse("http://" + harness.authority) + require.NoError(t, err) + transport := http.DefaultTransport.(*http.Transport).Clone() + transport.Proxy = nil + defer transport.CloseIdleConnections() + proxy := httptest.NewTLSServer(&httputil.ReverseProxy{Transport: transport, Rewrite: func(r *httputil.ProxyRequest) { r.SetURL(backend); r.Out.Host = r.In.Host }}) + defer proxy.Close() + callback = proxy.URL + "/oauth/callback" + harness.serveArgs = append(harness.serveArgs, "--external-origin", proxy.URL) + harness.Start() + browser := proxy.Client() + browser.Timeout = 3 * time.Second + browser.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse } + providerBrowser := provider.Client() + providerBrowser.Timeout = 3 * time.Second + providerBrowser.CheckRedirect = browser.CheckRedirect + auth := map[string]any{"mode": "oauth", "registration": map[string]any{"mode": "dynamic", "issuer": nil}, "trusted_origins": []string{}, "request_offline_access": false} + upstream := map[string]any{"kind": "streamable_http", "url": issuer + "/mcp", "protocol_mode": "modern", "authentication": auth} + definition := map[string]any{"namespace": "remote-oauth", "display_name": "Remote OAuth fixture", "enabled": false, "transport": upstream} + encoded, err := json.Marshal(definition) + require.NoError(t, err) + var created stdioCreation + response := harness.AdminJSON("POST", "/api/v2/mcp/servers", string(encoded), map[string]string{"Idempotency-Key": "remote-oauth"}, &created) + require.Equal(t, 201, response.StatusCode) + etag := response.Header.Get("ETag") + readResponseBody(t, response) + serverPath := "/api/v2/mcp/servers/" + created.Server.ID + flowPath := serverPath + "/oauth-flows" + // Exact configured callback is the only remote override. Reject before any + // provider work, rather than redirecting to an arbitrary origin or listener. + for _, bad := range []string{"https://other.example/oauth/callback", proxy.URL + "/wrong", "http://localhost:3118/callback"} { + auth["callback_uri"] = bad + body, marshalErr := json.Marshal(map[string]any{"transport": upstream}) + require.NoError(t, marshalErr) + response = harness.AdminJSON("PATCH", serverPath, string(body), map[string]string{"If-Match": etag}, nil) + require.Equal(t, 400, response.StatusCode) + readResponseBody(t, response) + } + delete(auth, "callback_uri") + settle := func() { + t.Helper() + require.Eventually(t, func() bool { + var server struct { + Runtime contract.ServerRuntime `json:"runtime"` + } + response := harness.AdminJSON("GET", serverPath, "", nil, &server) + readResponseBody(t, response) + return server.Runtime.Reconciliation.InUse == 0 + }, 5*time.Second, 10*time.Millisecond) + } + start := func() contract.AuthFlowCreation { + t.Helper() + settle() + var flow contract.AuthFlowCreation + response := harness.AdminJSON("POST", flowPath, `{}`, map[string]string{"If-Match": etag}, &flow) + require.Equal(t, 201, response.StatusCode) + readResponseBody(t, response) + return flow + } + authorize := func(flow contract.AuthFlowCreation) string { + t.Helper() + response, err := providerBrowser.Get(flow.AuthorizationURL) + require.NoError(t, err) + require.Equal(t, 302, response.StatusCode) + location := response.Header.Get("Location") + readResponseBody(t, response) + require.True(t, strings.HasPrefix(location, callback+"?")) + return location + } + visit := func(location string, status int) { + t.Helper() + response, err := browser.Get(location) + require.NoError(t, err) + require.Equal(t, status, response.StatusCode) + body := readResponseBody(t, response) + for _, secret := range []string{"synthetic-code-", "synthetic-remote-access", "synthetic-remote-refresh"} { + assert.NotContains(t, string(body), secret) + } + } + flow := start() + redirect := authorize(flow) + parsed, err := url.Parse(redirect) + require.NoError(t, err) + // Wrong callback authority/path, forwarding metadata and encoded paths must + // not consume valid state; the subsequent exact callback still completes. + for _, test := range []struct{ host, path, header string }{ + {"other.example", parsed.RequestURI(), ""}, + {"", strings.Replace(parsed.RequestURI(), "/oauth/callback", "/wrong", 1), ""}, + {"", strings.Replace(parsed.RequestURI(), "/oauth/callback", "/oauth/%63allback", 1), ""}, + {"", parsed.RequestURI(), "Forwarded"}, + {"", parsed.RequestURI(), "X-Forwarded-Host"}, + } { + // Send directly to test Gateway's rejection (ReverseProxy strips forwarding + // fields by contract, so it cannot be used to inject this negative case). + req, requestErr := http.NewRequestWithContext(t.Context(), "GET", backend.String()+test.path, nil) + require.NoError(t, requestErr) + req.Host = parsed.Host + if test.host != "" { + req.Host = test.host + } + if test.header != "" { + req.Header.Set(test.header, "untrusted.example") + } + response, err = harness.client.Do(req) + require.NoError(t, err) + require.GreaterOrEqual(t, response.StatusCode, 400) + readResponseBody(t, response) + } + q := parsed.Query() + q.Set("state", "unknown-state") + visit(callback+"?"+q.Encode(), 400) + assert.Zero(t, exchanges.Load()) + visit(redirect, 200) + visit(redirect, 400) + require.EqualValues(t, 1, exchanges.Load()) + var completed contract.ServerAuthFlow + response = harness.AdminJSON("GET", flowPath+"/"+flow.Flow.ID, "", nil, &completed) + readResponseBody(t, response) + require.Equal(t, contract.AuthFlowSucceeded, completed.FlowState) + // Cancel and restart invalidate process-local state without code exchange. + canceled := start() + canceledRedirect := authorize(canceled) + response = harness.AdminJSON("DELETE", flowPath+"/"+canceled.Flow.ID, `{}`, nil, nil) + require.Equal(t, 204, response.StatusCode) + readResponseBody(t, response) + visit(canceledRedirect, 400) + mismatched := start() + wrongIssuer := authorize(mismatched) + wrong, err := url.Parse(wrongIssuer) + require.NoError(t, err) + q = wrong.Query() + q.Set("iss", "https://wrong.example") + wrong.RawQuery = q.Encode() + visit(wrong.String(), 400) + visit(wrongIssuer, 400) + interrupted := start() + interruptedRedirect := authorize(interrupted) + harness.Stop(syscall.SIGTERM) + harness.Start() + visit(interruptedRedirect, 400) + response = harness.AdminJSON("GET", flowPath+"/"+interrupted.Flow.ID, "", nil, &completed) + readResponseBody(t, response) + require.Equal(t, contract.AuthFlowInterrupted, completed.FlowState) + require.EqualValues(t, 1, exchanges.Load(), "invalid callbacks must not replay exchange") + stopped := harness.Stop(syscall.SIGTERM) + for _, secret := range []string{"synthetic-code-", "synthetic-remote-access", "synthetic-remote-refresh"} { + assert.NotContains(t, string(stopped.Stderr), secret) + assert.NotContains(t, string(stopped.Stdout), secret) + } + // Read the actual installed encrypted generation under stopped ownership. + // The production MCP policy still refuses private HTTPS upstream addresses; + // a test-only resolver/dial pair routes a validated public address to this + // isolated TLS fixture without changing production policy (TOOLS-137). + owner, err := gatewaypaths.AcquireStoppedExisting(harness.root) + require.NoError(t, err) + defer func() { require.NoError(t, owner.Close()) }() + store, err := storage.Open(t.Context(), owner) + require.NoError(t, err) + defer func() { require.NoError(t, store.Close()) }() + identity, err := store.Identity(t.Context()) + require.NoError(t, err) + providerStore, err := keyring.NewProvider(identity.InstallationID) + require.NoError(t, err) + require.NoError(t, providerStore.UseDatabaseCustody(t.Context(), owner, store)) + coordinator := keyring.NewCoordinator(providerStore, store, testutil.NewFakeClock(time.Now()), rand.Reader) + namespace, err := keyring.NewNamespace(identity.InstallationID, created.Server.ID, keyring.RecordOAuthTokens) + require.NoError(t, err) + contents, _, err := coordinator.ReadActive(t.Context(), namespace) + require.NoError(t, err) + defer clear(contents) + generation, err := oauth.DecodeTokenGeneration(contents) + require.NoError(t, err) + require.Equal(t, issuer+"/mcp", generation.Resource) + endpoint, err := remote.Parse(issuer+"/mcp", remote.Policy{}) + require.NoError(t, err) + factory := remote.New(remote.Options{Resolver: remoteOAuthFixtureResolver{}, DialContext: func(ctx context.Context, network, address string) (net.Conn, error) { + require.Equal(t, "8.8.8.8", strings.Split(address, ":")[0]) + dialer := net.Dialer{Timeout: time.Second} + return dialer.DialContext(ctx, network, provider.Listener.Addr().String()) + }}) + result, err := factory.Exchange(t.Context(), remote.Request{Endpoint: endpoint, Method: "POST", Header: http.Header{"Authorization": {"Bearer " + generation.AccessToken}, "Content-Type": {contract.MediaTypeJSON}}, Body: []byte(`{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"echo","arguments":{}}}`), MaxBody: 16384}) + require.NoError(t, err) + require.Equal(t, 200, result.StatusCode) + require.Contains(t, string(result.Body), "remote OAuth works") + require.EqualValues(t, 1, calls.Load()) +} + +type remoteOAuthFixtureResolver struct{} + +func (remoteOAuthFixtureResolver) LookupNetIP(context.Context, string, string) ([]netip.Addr, error) { + return []netip.Addr{netip.MustParseAddr("8.8.8.8")}, nil +} diff --git a/agent-gateway/web/src/server-editor.tsx b/agent-gateway/web/src/server-editor.tsx index 078810ec..5d8b69a1 100644 --- a/agent-gateway/web/src/server-editor.tsx +++ b/agent-gateway/web/src/server-editor.tsx @@ -158,7 +158,7 @@ function serverConfigurationContextMessage( return `${label} must be an absolute canonical path without a trailing slash, empty segment, ".", or ".." segment.`; case "canonical_url": if (context.field === "transport.authentication.callback_uri") - return "Callback URI must be an exact HTTP loopback URL with an explicit port and path, without credentials, query, fragment, or encoded path."; + return "Callback URI must match Gateway's configured HTTPS origin and /oauth/callback, or use an HTTP loopback URL with an explicit port and path in local mode."; if (context.field === "transport.authentication.auth_server_metadata_url") return "Authorization metadata URL must be an exact canonical HTTPS URL with a path and without credentials or fragment. A bounded query is allowed."; return `${label} must be a canonical URL without credentials, a query, fragment, uppercase hostname, or default port.`; @@ -461,7 +461,29 @@ function transportFromDraft(draft: Draft): unknown { if (draft.registrationMode === "static" && clientID.length === 0) throw new DraftValidationError("clientID", "Enter the OAuth client ID."); const callbackURI = draft.callbackURI; - if (callbackURI !== "") { + if (callbackURI.startsWith("https://")) { + let parsed: URL | undefined; + try { + parsed = new URL(callbackURI); + } catch { + // The field error below covers invalid URL syntax. + } + if ( + parsed === undefined || + parsed.href !== callbackURI || + parsed.username !== "" || + parsed.password !== "" || + parsed.pathname !== "/oauth/callback" || + parsed.search !== "" || + parsed.hash !== "" || + /[?#%\\\\\s]/.test(callbackURI) || + new TextEncoder().encode(callbackURI).byteLength > 8192 + ) + throw new DraftValidationError( + "callbackURI", + "Use Gateway's exact configured HTTPS origin followed by /oauth/callback, or leave blank for the default.", + ); + } else if (callbackURI !== "") { const match = /^http:\/\/(localhost|127(?:\.[0-9]{1,3}){3}|\[::1\]):([1-9][0-9]{0,4})(\/[^?#%\\\s]*)$/.exec( callbackURI, @@ -481,7 +503,7 @@ function transportFromDraft(draft: Draft): unknown { ) throw new DraftValidationError( "callbackURI", - "Use an exact HTTP localhost or numeric-loopback URI with an explicit port and canonical path, such as http://localhost:3118/callback. No credentials, query, fragment, or encoded path.", + "Use Gateway's exact configured HTTPS origin followed by /oauth/callback. In local mode, use an exact HTTP loopback URI with an explicit port and canonical path.", ); } const metadataURL = draft.authServerMetadataURL; @@ -1313,7 +1335,7 @@ function EditorForm({ id="server-callback-uri" label="Callback URI" optional - hint="Leave blank to use Gateway's default callback. To use a different callback, enter the exact HTTP loopback redirect URL registered with your provider, including port and path. That port must be free; Gateway listens there only during authorization." + hint="Leave blank for Gateway's default callback. Remote mode requires the exact configured HTTPS origin followed by /oauth/callback. Local mode also supports an HTTP loopback redirect with an explicit free port and path." {...(compatibilityErrors.callbackURI === undefined ? {} : { error: compatibilityErrors.callbackURI })} diff --git a/agent-gateway/web/tests/browser/server-scenarios.ts b/agent-gateway/web/tests/browser/server-scenarios.ts index 6009e843..5d235ed5 100644 --- a/agent-gateway/web/tests/browser/server-scenarios.ts +++ b/agent-gateway/web/tests/browser/server-scenarios.ts @@ -1406,6 +1406,20 @@ async function assertOAuthScopeEditing( if (submitted.length !== previous + 1) fail("OAuth scope edit did not submit exactly once"); }; + const callback = page.locator("#server-callback-uri"); + await callback.fill("https://gateway.example/other"); + await save.click(); + await expect(page.getByRole("dialog")).toHaveCount(0); + await expect( + page.getByText( + "Use Gateway's exact configured HTTPS origin followed by /oauth/callback, or leave blank for the default.", + { exact: true }, + ), + ).toBeVisible(); + expect(submitted).toHaveLength(0); + await capture(page, "settings-oauth-remote-invalid"); + await callback.fill("https://gateway.example:8443/oauth/callback"); + await capture(page, "settings-oauth-remote-configured", true); await page.getByRole("button", { name: "Add scope", exact: true }).click(); await scopeRows.nth(1).fill("fixture.write"); await page.getByRole("button", { name: "Add scope", exact: true }).click(); @@ -1420,6 +1434,10 @@ async function assertOAuthScopeEditing( '["fixture.read","fixture.write"]' ) fail("scope rows were not normalized in the actual update request"); + expect(submitted.at(-1)?.callback_uri).toBe( + "https://gateway.example:8443/oauth/callback", + ); + await callback.fill(""); await capture(page, "settings-oauth-validation"); for (let index = 3; index > 0; index -= 1) await page @@ -1428,6 +1446,7 @@ async function assertOAuthScopeEditing( await submit(); if (JSON.stringify(submitted.at(-1)?.scopes) !== "[]") fail("explicit empty scopes were not serialized as an empty list"); + expect(Object.hasOwn(submitted.at(-1) ?? {}, "callback_uri")).toBe(false); await capture(page, "settings-oauth-empty-scopes"); await page.getByRole("button", { name: "Add scope", exact: true }).click(); await scopeRows.fill("fixture.inactive"); diff --git a/agent-gateway/web/tests/frontend/inventory.json b/agent-gateway/web/tests/frontend/inventory.json index 9d53757f..0d48436d 100644 --- a/agent-gateway/web/tests/frontend/inventory.json +++ b/agent-gateway/web/tests/frontend/inventory.json @@ -22,7 +22,7 @@ "server-auth-flows.tsx": "927c5a263705fc0e84454da2e1d88397c5e8cafa1331964bd73946e4e8730b2c", "server-credentials.tsx": "284d44979ead9450dcd7e1fcdb7131f0a647273920fa35ca30fd039a6bfe8927", "server-destructive.tsx": "e791c5576ee662f6d982dc9ea4e7c7d53e1efb533b21e8547c3f6c7b6b0c42b1", - "server-editor.tsx": "f5c4cc85d61b7bc2beba7a7abf90bc9eb0b705e212bb656e5f2f1e375e4ce88e", + "server-editor.tsx": "f9ffac20a390a1494300a5121ba053ad2b959c12c84a47cec4f72692ec9f24d1", "server-operations.tsx": "dc01f29c84a8dfe25ba904fc8fccdca0ed8055c986cf7fad6b1ca421d80925be", "server-reads.tsx": "3172119ad0338f15f2a927f4dbd1ce7395384212fc3a9f4b128d1c8165c8fc97", "sinks-ui.tsx": "909c10148e7213c91e1b435be7a0805d3b899a0464b51ff47053bda244880406", @@ -547,6 +547,8 @@ "settings-unavailable": "standard", "settings-stale": "standard", "settings-oauth-configured": "reflow", + "settings-oauth-remote-invalid": "standard", + "settings-oauth-remote-configured": "reflow", "settings-oauth-review-1": "standard", "settings-oauth-review-2": "standard", "settings-oauth-review-3": "standard",