@onyxsecurity/mcp-gateway 1.0.138 → 1.0.140

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (26) hide show
  1. package/dist/bin/mcp-gateway.js +2 -2
  2. package/dist/{cli-DWpHxCK6.js → cli-Cj_W_Rxw.js} +2 -2
  3. package/dist/{cli-DWpHxCK6.js.map → cli-Cj_W_Rxw.js.map} +1 -1
  4. package/dist/{env-CkHa0WcM.js → env-CvPQLLkW.js} +1 -1
  5. package/dist/{env-DJNvBCH9.js → env-DKEqpop9.js} +2 -2
  6. package/dist/{env-DJNvBCH9.js.map → env-DKEqpop9.js.map} +1 -1
  7. package/dist/index.js +1 -1
  8. package/dist/{logger-BjLVc61x.js → logger-jKh1IKjp.js} +2 -2
  9. package/dist/{logger-BjLVc61x.js.map → logger-jKh1IKjp.js.map} +1 -1
  10. package/dist/{main-DrKclq2L.js → main-CsDKLUsa.js} +2 -2
  11. package/dist/{main-DrKclq2L.js.map → main-CsDKLUsa.js.map} +1 -1
  12. package/dist/oauthProvidersClient-DEQn3MwK.js +1 -0
  13. package/dist/{oauthProvidersClient-tKUY6rDu.js → oauthProvidersClient-T6ZhWZr8.js} +2 -2
  14. package/dist/{oauthProvidersClient-tKUY6rDu.js.map → oauthProvidersClient-T6ZhWZr8.js.map} +1 -1
  15. package/dist/{providers-BaFl5rAa.js → providers-CR3DqjRH.js} +2 -2
  16. package/dist/{providers-BaFl5rAa.js.map → providers-CR3DqjRH.js.map} +1 -1
  17. package/dist/secretstore-B7UBzLo4.js +3 -0
  18. package/dist/secretstore-B7UBzLo4.js.map +1 -0
  19. package/dist/{stdio-BD8z2niv.js → stdio-DDsYWNYz.js} +2 -2
  20. package/dist/{stdio-BD8z2niv.js.map → stdio-DDsYWNYz.js.map} +1 -1
  21. package/dist/{transportDetection-A7929-Uq.js → transportDetection-D45i4vIF.js} +2 -2
  22. package/dist/{transportDetection-A7929-Uq.js.map → transportDetection-D45i4vIF.js.map} +1 -1
  23. package/package.json +1 -1
  24. package/dist/oauthProvidersClient-MnnqkcZR.js +0 -1
  25. package/dist/secretstore-R8UMzO0o.js +0 -2
  26. package/dist/secretstore-R8UMzO0o.js.map +0 -1
@@ -0,0 +1 @@
1
+ import"./env-DKEqpop9.js";import"./logger-jKh1IKjp.js";import"./providers-CR3DqjRH.js";import{fetchOAuthProviders as e,initializeOAuthProviders as t}from"./oauthProvidersClient-T6ZhWZr8.js";export{t as initializeOAuthProviders};
@@ -1,2 +1,2 @@
1
- import{logger as e}from"./logger-BjLVc61x.js";import{setOAuthProviders as t}from"./providers-BaFl5rAa.js";async function n(e){let t=new URL(e.url),n=t.hostname===`localhost`||t.hostname===`127.0.0.1`||t.hostname===`::1`||t.hostname===`[::1]`;if(t.protocol!==`https:`&&!n)throw Error(`OAuth providers URL must use HTTPS, got ${t.protocol}`);let r=new AbortController,i=setTimeout(()=>r.abort(),e.timeoutMs);try{let t=await fetch(e.url,{headers:{Accept:`application/json`,apikey:e.apiKey},method:`GET`,signal:r.signal});if(!t.ok)throw Error(`OAuth providers service returned ${t.status}: ${t.statusText}`);let n=await t.json();return Array.isArray(n.providers)?n.providers:[]}catch(t){throw t instanceof Error&&t.name===`AbortError`?Error(`OAuth providers fetch timed out after ${e.timeoutMs}ms`):t}finally{clearTimeout(i)}}async function r(r){if(!r.enabled||!r.url||!r.apiKey){t([]),e.debug(`OAuth providers fetch disabled (missing URL or API key); skipping`);return}try{let i=await n({apiKey:r.apiKey,timeoutMs:r.timeoutMs,url:r.url});t(i),e.info(`OAuth providers loaded`,{count:i.length,ids:i.map(e=>e.id)})}catch(n){t([]),e.warn(`OAuth providers fetch failed; falling back to DCR`,{error:String(n),url:r.url})}}export{n as fetchOAuthProviders,r as initializeOAuthProviders};
2
- //# sourceMappingURL=oauthProvidersClient-tKUY6rDu.js.map
1
+ import{logger as e}from"./logger-jKh1IKjp.js";import{setOAuthProviders as t}from"./providers-CR3DqjRH.js";async function n(e){let t=new URL(e.url),n=t.hostname===`localhost`||t.hostname===`127.0.0.1`||t.hostname===`::1`||t.hostname===`[::1]`;if(t.protocol!==`https:`&&!n)throw Error(`OAuth providers URL must use HTTPS, got ${t.protocol}`);let r=new AbortController,i=setTimeout(()=>r.abort(),e.timeoutMs);try{let t=await fetch(e.url,{headers:{Accept:`application/json`,apikey:e.apiKey},method:`GET`,signal:r.signal});if(!t.ok)throw Error(`OAuth providers service returned ${t.status}: ${t.statusText}`);let n=await t.json();return Array.isArray(n.providers)?n.providers:[]}catch(t){throw t instanceof Error&&t.name===`AbortError`?Error(`OAuth providers fetch timed out after ${e.timeoutMs}ms`):t}finally{clearTimeout(i)}}async function r(r){if(!r.enabled||!r.url||!r.apiKey){t([]),e.debug(`OAuth providers fetch disabled (missing URL or API key); skipping`);return}try{let i=await n({apiKey:r.apiKey,timeoutMs:r.timeoutMs,url:r.url});t(i),e.info(`OAuth providers loaded`,{count:i.length,ids:i.map(e=>e.id)})}catch(n){t([]),e.warn(`OAuth providers fetch failed; falling back to DCR`,{error:String(n),url:r.url})}}export{n as fetchOAuthProviders,r as initializeOAuthProviders};
2
+ //# sourceMappingURL=oauthProvidersClient-T6ZhWZr8.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"oauthProvidersClient-tKUY6rDu.js","names":[],"sources":["../src/auth/oauthProvidersClient.ts"],"sourcesContent":["import type { OAuthProviderConfig } from \"../config/config.js\";\n\nimport { logger } from \"../lib/logger.js\";\nimport { setOAuthProviders } from \"./providers.js\";\n\nexport interface InitializeOAuthProvidersConfig {\n apiKey: string | undefined;\n enabled: boolean;\n timeoutMs: number;\n url: null | string;\n}\n\nexport interface OAuthProvidersClientConfig {\n apiKey: string;\n timeoutMs: number;\n url: string;\n}\n\ninterface OAuthProvidersResponse {\n providers?: OAuthProviderConfig[];\n}\n\n/**\n * Fetches the OAuth provider list from the web extension service.\n *\n * The endpoint is gated by Kong's key-auth plugin, which validates the\n * `apikey` header and forwards a per-tenant `x-consumer-username` header\n * (e.g. `mcp-gateway@<tenantUUID>`) to the backend.\n *\n * Throws on network error, timeout, or non-2xx response. Callers are\n * expected to handle errors and decide on a fallback (initializeOAuthProviders\n * fails open by emptying the in-memory provider list, which causes the OAuth\n * flow to fall through to Dynamic Client Registration).\n */\nexport async function fetchOAuthProviders(\n cfg: OAuthProvidersClientConfig\n): Promise<OAuthProviderConfig[]> {\n // Reject non-HTTPS URLs before sending the API key over the wire.\n // Loopback addresses are allowed for local development against a non-TLS\n // stub: \"localhost\", IPv4 (127.0.0.1), and IPv6 (::1). Node returns the\n // bracketed form (\"[::1]\") for IPv6 hosts in URL.hostname, so match both.\n const parsed = new URL(cfg.url);\n const isLocal =\n parsed.hostname === \"localhost\" ||\n parsed.hostname === \"127.0.0.1\" ||\n parsed.hostname === \"::1\" ||\n parsed.hostname === \"[::1]\";\n if (parsed.protocol !== \"https:\" && !isLocal) {\n throw new Error(`OAuth providers URL must use HTTPS, got ${parsed.protocol}`);\n }\n\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), cfg.timeoutMs);\n\n try {\n const response = await fetch(cfg.url, {\n // GET with no body — Accept signals the desired response format,\n // Content-Type would be misleading.\n headers: {\n Accept: \"application/json\",\n apikey: cfg.apiKey,\n },\n method: \"GET\",\n signal: controller.signal,\n });\n\n if (!response.ok) {\n throw new Error(`OAuth providers service returned ${response.status}: ${response.statusText}`);\n }\n\n const body = (await response.json()) as OAuthProvidersResponse;\n return Array.isArray(body.providers) ? body.providers : [];\n } catch (error) {\n if (error instanceof Error && error.name === \"AbortError\") {\n throw new Error(`OAuth providers fetch timed out after ${cfg.timeoutMs}ms`);\n }\n throw error;\n } finally {\n clearTimeout(timer);\n }\n}\n\n/**\n * Initializes the in-memory OAuth provider store at gateway startup.\n *\n * On a successful fetch, populates the store with the providers returned by\n * the web extension service. On any failure (disabled config, network error,\n * timeout, malformed body), empties the store and logs a warning. The OAuth\n * flow at oauthFlow.ts then falls through to Dynamic Client Registration,\n * matching the gateway's \"fail-safe by default\" convention.\n */\nexport async function initializeOAuthProviders(cfg: InitializeOAuthProvidersConfig): Promise<void> {\n if (!cfg.enabled || !cfg.url || !cfg.apiKey) {\n setOAuthProviders([]);\n logger.debug(\"OAuth providers fetch disabled (missing URL or API key); skipping\");\n return;\n }\n\n try {\n const providers = await fetchOAuthProviders({\n apiKey: cfg.apiKey,\n timeoutMs: cfg.timeoutMs,\n url: cfg.url,\n });\n setOAuthProviders(providers);\n logger.info(\"OAuth providers loaded\", {\n count: providers.length,\n ids: providers.map((p) => p.id),\n });\n } catch (error) {\n setOAuthProviders([]);\n logger.warn(\"OAuth providers fetch failed; falling back to DCR\", {\n error: String(error),\n url: cfg.url,\n });\n }\n}\n"],"mappings":"0GAkCA,eAAsB,EACpB,EACgC,CAKhC,IAAM,EAAS,IAAI,IAAI,EAAI,IAAI,CACzB,EACJ,EAAO,WAAa,aACpB,EAAO,WAAa,aACpB,EAAO,WAAa,OACpB,EAAO,WAAa,QACtB,GAAI,EAAO,WAAa,UAAY,CAAC,EACnC,MAAU,MAAM,2CAA2C,EAAO,WAAW,CAG/E,IAAM,EAAa,IAAI,gBACjB,EAAQ,eAAiB,EAAW,OAAO,CAAE,EAAI,UAAU,CAEjE,GAAI,CACF,IAAM,EAAW,MAAM,MAAM,EAAI,IAAK,CAGpC,QAAS,CACP,OAAQ,mBACR,OAAQ,EAAI,OACb,CACD,OAAQ,MACR,OAAQ,EAAW,OACpB,CAAC,CAEF,GAAI,CAAC,EAAS,GACZ,MAAU,MAAM,oCAAoC,EAAS,OAAO,IAAI,EAAS,aAAa,CAGhG,IAAM,EAAQ,MAAM,EAAS,MAAM,CACnC,OAAO,MAAM,QAAQ,EAAK,UAAU,CAAG,EAAK,UAAY,EAAE,OACnD,EAAO,CAId,MAHI,aAAiB,OAAS,EAAM,OAAS,aACjC,MAAM,yCAAyC,EAAI,UAAU,IAAI,CAEvE,SACE,CACR,aAAa,EAAM,EAavB,eAAsB,EAAyB,EAAoD,CACjG,GAAI,CAAC,EAAI,SAAW,CAAC,EAAI,KAAO,CAAC,EAAI,OAAQ,CAC3C,EAAkB,EAAE,CAAC,CACrB,EAAO,MAAM,oEAAoE,CACjF,OAGF,GAAI,CACF,IAAM,EAAY,MAAM,EAAoB,CAC1C,OAAQ,EAAI,OACZ,UAAW,EAAI,UACf,IAAK,EAAI,IACV,CAAC,CACF,EAAkB,EAAU,CAC5B,EAAO,KAAK,yBAA0B,CACpC,MAAO,EAAU,OACjB,IAAK,EAAU,IAAK,GAAM,EAAE,GAAG,CAChC,CAAC,OACK,EAAO,CACd,EAAkB,EAAE,CAAC,CACrB,EAAO,KAAK,oDAAqD,CAC/D,MAAO,OAAO,EAAM,CACpB,IAAK,EAAI,IACV,CAAC"}
1
+ {"version":3,"file":"oauthProvidersClient-T6ZhWZr8.js","names":[],"sources":["../src/auth/oauthProvidersClient.ts"],"sourcesContent":["import type { OAuthProviderConfig } from \"../config/config.js\";\n\nimport { logger } from \"../lib/logger.js\";\nimport { setOAuthProviders } from \"./providers.js\";\n\nexport interface InitializeOAuthProvidersConfig {\n apiKey: string | undefined;\n enabled: boolean;\n timeoutMs: number;\n url: null | string;\n}\n\nexport interface OAuthProvidersClientConfig {\n apiKey: string;\n timeoutMs: number;\n url: string;\n}\n\ninterface OAuthProvidersResponse {\n providers?: OAuthProviderConfig[];\n}\n\n/**\n * Fetches the OAuth provider list from the web extension service.\n *\n * The endpoint is gated by Kong's key-auth plugin, which validates the\n * `apikey` header and forwards a per-tenant `x-consumer-username` header\n * (e.g. `mcp-gateway@<tenantUUID>`) to the backend.\n *\n * Throws on network error, timeout, or non-2xx response. Callers are\n * expected to handle errors and decide on a fallback (initializeOAuthProviders\n * fails open by emptying the in-memory provider list, which causes the OAuth\n * flow to fall through to Dynamic Client Registration).\n */\nexport async function fetchOAuthProviders(\n cfg: OAuthProvidersClientConfig\n): Promise<OAuthProviderConfig[]> {\n // Reject non-HTTPS URLs before sending the API key over the wire.\n // Loopback addresses are allowed for local development against a non-TLS\n // stub: \"localhost\", IPv4 (127.0.0.1), and IPv6 (::1). Node returns the\n // bracketed form (\"[::1]\") for IPv6 hosts in URL.hostname, so match both.\n const parsed = new URL(cfg.url);\n const isLocal =\n parsed.hostname === \"localhost\" ||\n parsed.hostname === \"127.0.0.1\" ||\n parsed.hostname === \"::1\" ||\n parsed.hostname === \"[::1]\";\n if (parsed.protocol !== \"https:\" && !isLocal) {\n throw new Error(`OAuth providers URL must use HTTPS, got ${parsed.protocol}`);\n }\n\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), cfg.timeoutMs);\n\n try {\n const response = await fetch(cfg.url, {\n // GET with no body — Accept signals the desired response format,\n // Content-Type would be misleading.\n headers: {\n Accept: \"application/json\",\n apikey: cfg.apiKey,\n },\n method: \"GET\",\n signal: controller.signal,\n });\n\n if (!response.ok) {\n throw new Error(`OAuth providers service returned ${response.status}: ${response.statusText}`);\n }\n\n const body = (await response.json()) as OAuthProvidersResponse;\n return Array.isArray(body.providers) ? body.providers : [];\n } catch (error) {\n if (error instanceof Error && error.name === \"AbortError\") {\n throw new Error(`OAuth providers fetch timed out after ${cfg.timeoutMs}ms`);\n }\n throw error;\n } finally {\n clearTimeout(timer);\n }\n}\n\n/**\n * Initializes the in-memory OAuth provider store at gateway startup.\n *\n * On a successful fetch, populates the store with the providers returned by\n * the web extension service. On any failure (disabled config, network error,\n * timeout, malformed body), empties the store and logs a warning. The OAuth\n * flow at oauthFlow.ts then falls through to Dynamic Client Registration,\n * matching the gateway's \"fail-safe by default\" convention.\n */\nexport async function initializeOAuthProviders(cfg: InitializeOAuthProvidersConfig): Promise<void> {\n if (!cfg.enabled || !cfg.url || !cfg.apiKey) {\n setOAuthProviders([]);\n logger.debug(\"OAuth providers fetch disabled (missing URL or API key); skipping\");\n return;\n }\n\n try {\n const providers = await fetchOAuthProviders({\n apiKey: cfg.apiKey,\n timeoutMs: cfg.timeoutMs,\n url: cfg.url,\n });\n setOAuthProviders(providers);\n logger.info(\"OAuth providers loaded\", {\n count: providers.length,\n ids: providers.map((p) => p.id),\n });\n } catch (error) {\n setOAuthProviders([]);\n logger.warn(\"OAuth providers fetch failed; falling back to DCR\", {\n error: String(error),\n url: cfg.url,\n });\n }\n}\n"],"mappings":"0GAkCA,eAAsB,EACpB,EACgC,CAKhC,IAAM,EAAS,IAAI,IAAI,EAAI,IAAI,CACzB,EACJ,EAAO,WAAa,aACpB,EAAO,WAAa,aACpB,EAAO,WAAa,OACpB,EAAO,WAAa,QACtB,GAAI,EAAO,WAAa,UAAY,CAAC,EACnC,MAAU,MAAM,2CAA2C,EAAO,WAAW,CAG/E,IAAM,EAAa,IAAI,gBACjB,EAAQ,eAAiB,EAAW,OAAO,CAAE,EAAI,UAAU,CAEjE,GAAI,CACF,IAAM,EAAW,MAAM,MAAM,EAAI,IAAK,CAGpC,QAAS,CACP,OAAQ,mBACR,OAAQ,EAAI,OACb,CACD,OAAQ,MACR,OAAQ,EAAW,OACpB,CAAC,CAEF,GAAI,CAAC,EAAS,GACZ,MAAU,MAAM,oCAAoC,EAAS,OAAO,IAAI,EAAS,aAAa,CAGhG,IAAM,EAAQ,MAAM,EAAS,MAAM,CACnC,OAAO,MAAM,QAAQ,EAAK,UAAU,CAAG,EAAK,UAAY,EAAE,OACnD,EAAO,CAId,MAHI,aAAiB,OAAS,EAAM,OAAS,aACjC,MAAM,yCAAyC,EAAI,UAAU,IAAI,CAEvE,SACE,CACR,aAAa,EAAM,EAavB,eAAsB,EAAyB,EAAoD,CACjG,GAAI,CAAC,EAAI,SAAW,CAAC,EAAI,KAAO,CAAC,EAAI,OAAQ,CAC3C,EAAkB,EAAE,CAAC,CACrB,EAAO,MAAM,oEAAoE,CACjF,OAGF,GAAI,CACF,IAAM,EAAY,MAAM,EAAoB,CAC1C,OAAQ,EAAI,OACZ,UAAW,EAAI,UACf,IAAK,EAAI,IACV,CAAC,CACF,EAAkB,EAAU,CAC5B,EAAO,KAAK,yBAA0B,CACpC,MAAO,EAAU,OACjB,IAAK,EAAU,IAAK,GAAM,EAAE,GAAG,CAChC,CAAC,OACK,EAAO,CACd,EAAkB,EAAE,CAAC,CACrB,EAAO,KAAK,oDAAqD,CAC/D,MAAO,OAAO,EAAM,CACpB,IAAK,EAAI,IACV,CAAC"}
@@ -1,2 +1,2 @@
1
- import{logger as e}from"./logger-BjLVc61x.js";let t=[];function n(n){let r=typeof n==`string`?new URL(n):n,o=r.hostname.toLowerCase();for(let n of t)for(let t of n.urlPatterns){let r=t.toLowerCase();if(a(o,r))return e.debug(`Found matching OAuth provider for URL`,{hostname:o,pattern:t,providerId:n.id,providerName:n.name}),i(n)}e.debug(`No pre-configured OAuth provider found for URL`,{hostname:o,serverUrl:r.toString()})}function r(e){t=e.map(i)}function i(e){return{...e,scopes:e.scopes?[...e.scopes]:void 0,urlPatterns:[...e.urlPatterns]}}function a(e,t){return!!(e===t||e.endsWith(`.${t}`))}export{n as findProviderForUrl,r as setOAuthProviders};
2
- //# sourceMappingURL=providers-BaFl5rAa.js.map
1
+ import{logger as e}from"./logger-jKh1IKjp.js";let t=[];function n(n){let r=typeof n==`string`?new URL(n):n,o=r.hostname.toLowerCase();for(let n of t)for(let t of n.urlPatterns){let r=t.toLowerCase();if(a(o,r))return e.debug(`Found matching OAuth provider for URL`,{hostname:o,pattern:t,providerId:n.id,providerName:n.name}),i(n)}e.debug(`No pre-configured OAuth provider found for URL`,{hostname:o,serverUrl:r.toString()})}function r(e){t=e.map(i)}function i(e){return{...e,scopes:e.scopes?[...e.scopes]:void 0,urlPatterns:[...e.urlPatterns]}}function a(e,t){return!!(e===t||e.endsWith(`.${t}`))}export{n as findProviderForUrl,r as setOAuthProviders};
2
+ //# sourceMappingURL=providers-CR3DqjRH.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"providers-BaFl5rAa.js","names":["oauthProviders: OAuthProviderConfig[]"],"sources":["../src/auth/providers.ts"],"sourcesContent":["import type { OAuthProviderConfig } from \"../config/config.js\";\n\nimport { logger } from \"../lib/logger.js\";\n\n// Mutable store. Populated by setOAuthProviders() during startup once the\n// gateway has fetched provider config from the web extension service.\n// Pre-startup or when the fetch fails, the array stays empty and OAuth flows\n// fall through to Dynamic Client Registration via oauthFlow.ts.\nlet oauthProviders: OAuthProviderConfig[] = [];\n\n/**\n * Finds a pre-configured OAuth provider that matches the given server URL.\n *\n * @param serverUrl The MCP server URL to match against provider URL patterns\n * @returns The matching provider config, or undefined if no match found\n */\nexport function findProviderForUrl(serverUrl: string | URL): OAuthProviderConfig | undefined {\n const serverUrlObj = typeof serverUrl === \"string\" ? new URL(serverUrl) : serverUrl;\n const hostname = serverUrlObj.hostname.toLowerCase();\n\n for (const provider of oauthProviders) {\n for (const pattern of provider.urlPatterns) {\n // Pattern can be a hostname or a hostname with path prefix\n const patternLower = pattern.toLowerCase();\n\n // Check if pattern matches hostname (with or without subdomains)\n if (matchesHostname(hostname, patternLower)) {\n logger.debug(\"Found matching OAuth provider for URL\", {\n hostname,\n pattern,\n providerId: provider.id,\n providerName: provider.name,\n });\n // Return a defensive clone — callers in oauthFlow.ts must not be\n // able to corrupt the in-memory store via the returned reference.\n return cloneProvider(provider);\n }\n }\n }\n\n logger.debug(\"No pre-configured OAuth provider found for URL\", {\n hostname,\n serverUrl: serverUrlObj.toString(),\n });\n return undefined;\n}\n\n/**\n * Gets a provider by its ID.\n *\n * @param providerId The provider ID (e.g., \"github\")\n * @returns The provider config, or undefined if not found\n */\nexport function getProviderById(providerId: string): OAuthProviderConfig | undefined {\n const found = oauthProviders.find((p) => p.id === providerId);\n return found ? cloneProvider(found) : undefined;\n}\n\n/**\n * Lists all configured OAuth providers.\n * Useful for debugging and admin interfaces.\n *\n * @returns Array of provider summaries (without secrets)\n */\nexport function listProviders(): Array<{\n hasClientSecret: boolean;\n id: string;\n name: string;\n urlPatterns: string[];\n}> {\n return oauthProviders.map((p) => ({\n hasClientSecret: !!p.clientSecret,\n id: p.id,\n name: p.name,\n urlPatterns: [...p.urlPatterns],\n }));\n}\n\n/**\n * Replaces the in-memory OAuth provider list. Called once at gateway startup\n * after fetching from the web extension service. Pass an empty array to clear.\n *\n * Stores defensive shallow copies of each provider so that callers cannot\n * mutate the in-memory store via the references they passed in. The\n * urlPatterns array is also cloned for the same reason.\n */\nexport function setOAuthProviders(providers: OAuthProviderConfig[]): void {\n oauthProviders = providers.map(cloneProvider);\n}\n\n// cloneProvider returns a defensive shallow copy with array fields cloned,\n// so callers can read and even mutate the result without corrupting the\n// in-memory store. Used on every read path (findProviderForUrl,\n// getProviderById) to match the write-side contract in setOAuthProviders.\nfunction cloneProvider(p: OAuthProviderConfig): OAuthProviderConfig {\n return {\n ...p,\n scopes: p.scopes ? [...p.scopes] : undefined,\n urlPatterns: [...p.urlPatterns],\n };\n}\n\n/**\n * Checks if a hostname matches a pattern.\n * Supports exact matches and subdomain matches.\n *\n * @param hostname The hostname to check (e.g., \"api.github.com\")\n * @param pattern The pattern to match against (e.g., \"github.com\")\n * @returns true if the hostname matches the pattern\n */\nfunction matchesHostname(hostname: string, pattern: string): boolean {\n // Exact match\n if (hostname === pattern) {\n return true;\n }\n\n // Subdomain match: hostname ends with \".pattern\"\n // e.g., \"api.github.com\" matches \"github.com\"\n if (hostname.endsWith(`.${pattern}`)) {\n return true;\n }\n\n return false;\n}\n"],"mappings":"8CAQA,IAAIA,EAAwC,EAAE,CAQ9C,SAAgB,EAAmB,EAA0D,CAC3F,IAAM,EAAe,OAAO,GAAc,SAAW,IAAI,IAAI,EAAU,CAAG,EACpE,EAAW,EAAa,SAAS,aAAa,CAEpD,IAAK,IAAM,KAAY,EACrB,IAAK,IAAM,KAAW,EAAS,YAAa,CAE1C,IAAM,EAAe,EAAQ,aAAa,CAG1C,GAAI,EAAgB,EAAU,EAAa,CASzC,OARA,EAAO,MAAM,wCAAyC,CACpD,WACA,UACA,WAAY,EAAS,GACrB,aAAc,EAAS,KACxB,CAAC,CAGK,EAAc,EAAS,CAKpC,EAAO,MAAM,iDAAkD,CAC7D,WACA,UAAW,EAAa,UAAU,CACnC,CAAC,CA2CJ,SAAgB,EAAkB,EAAwC,CACxE,EAAiB,EAAU,IAAI,EAAc,CAO/C,SAAS,EAAc,EAA6C,CAClE,MAAO,CACL,GAAG,EACH,OAAQ,EAAE,OAAS,CAAC,GAAG,EAAE,OAAO,CAAG,IAAA,GACnC,YAAa,CAAC,GAAG,EAAE,YAAY,CAChC,CAWH,SAAS,EAAgB,EAAkB,EAA0B,CAYnE,MAJA,GANI,IAAa,GAMb,EAAS,SAAS,IAAI,IAAU"}
1
+ {"version":3,"file":"providers-CR3DqjRH.js","names":["oauthProviders: OAuthProviderConfig[]"],"sources":["../src/auth/providers.ts"],"sourcesContent":["import type { OAuthProviderConfig } from \"../config/config.js\";\n\nimport { logger } from \"../lib/logger.js\";\n\n// Mutable store. Populated by setOAuthProviders() during startup once the\n// gateway has fetched provider config from the web extension service.\n// Pre-startup or when the fetch fails, the array stays empty and OAuth flows\n// fall through to Dynamic Client Registration via oauthFlow.ts.\nlet oauthProviders: OAuthProviderConfig[] = [];\n\n/**\n * Finds a pre-configured OAuth provider that matches the given server URL.\n *\n * @param serverUrl The MCP server URL to match against provider URL patterns\n * @returns The matching provider config, or undefined if no match found\n */\nexport function findProviderForUrl(serverUrl: string | URL): OAuthProviderConfig | undefined {\n const serverUrlObj = typeof serverUrl === \"string\" ? new URL(serverUrl) : serverUrl;\n const hostname = serverUrlObj.hostname.toLowerCase();\n\n for (const provider of oauthProviders) {\n for (const pattern of provider.urlPatterns) {\n // Pattern can be a hostname or a hostname with path prefix\n const patternLower = pattern.toLowerCase();\n\n // Check if pattern matches hostname (with or without subdomains)\n if (matchesHostname(hostname, patternLower)) {\n logger.debug(\"Found matching OAuth provider for URL\", {\n hostname,\n pattern,\n providerId: provider.id,\n providerName: provider.name,\n });\n // Return a defensive clone — callers in oauthFlow.ts must not be\n // able to corrupt the in-memory store via the returned reference.\n return cloneProvider(provider);\n }\n }\n }\n\n logger.debug(\"No pre-configured OAuth provider found for URL\", {\n hostname,\n serverUrl: serverUrlObj.toString(),\n });\n return undefined;\n}\n\n/**\n * Gets a provider by its ID.\n *\n * @param providerId The provider ID (e.g., \"github\")\n * @returns The provider config, or undefined if not found\n */\nexport function getProviderById(providerId: string): OAuthProviderConfig | undefined {\n const found = oauthProviders.find((p) => p.id === providerId);\n return found ? cloneProvider(found) : undefined;\n}\n\n/**\n * Lists all configured OAuth providers.\n * Useful for debugging and admin interfaces.\n *\n * @returns Array of provider summaries (without secrets)\n */\nexport function listProviders(): Array<{\n hasClientSecret: boolean;\n id: string;\n name: string;\n urlPatterns: string[];\n}> {\n return oauthProviders.map((p) => ({\n hasClientSecret: !!p.clientSecret,\n id: p.id,\n name: p.name,\n urlPatterns: [...p.urlPatterns],\n }));\n}\n\n/**\n * Replaces the in-memory OAuth provider list. Called once at gateway startup\n * after fetching from the web extension service. Pass an empty array to clear.\n *\n * Stores defensive shallow copies of each provider so that callers cannot\n * mutate the in-memory store via the references they passed in. The\n * urlPatterns array is also cloned for the same reason.\n */\nexport function setOAuthProviders(providers: OAuthProviderConfig[]): void {\n oauthProviders = providers.map(cloneProvider);\n}\n\n// cloneProvider returns a defensive shallow copy with array fields cloned,\n// so callers can read and even mutate the result without corrupting the\n// in-memory store. Used on every read path (findProviderForUrl,\n// getProviderById) to match the write-side contract in setOAuthProviders.\nfunction cloneProvider(p: OAuthProviderConfig): OAuthProviderConfig {\n return {\n ...p,\n scopes: p.scopes ? [...p.scopes] : undefined,\n urlPatterns: [...p.urlPatterns],\n };\n}\n\n/**\n * Checks if a hostname matches a pattern.\n * Supports exact matches and subdomain matches.\n *\n * @param hostname The hostname to check (e.g., \"api.github.com\")\n * @param pattern The pattern to match against (e.g., \"github.com\")\n * @returns true if the hostname matches the pattern\n */\nfunction matchesHostname(hostname: string, pattern: string): boolean {\n // Exact match\n if (hostname === pattern) {\n return true;\n }\n\n // Subdomain match: hostname ends with \".pattern\"\n // e.g., \"api.github.com\" matches \"github.com\"\n if (hostname.endsWith(`.${pattern}`)) {\n return true;\n }\n\n return false;\n}\n"],"mappings":"8CAQA,IAAIA,EAAwC,EAAE,CAQ9C,SAAgB,EAAmB,EAA0D,CAC3F,IAAM,EAAe,OAAO,GAAc,SAAW,IAAI,IAAI,EAAU,CAAG,EACpE,EAAW,EAAa,SAAS,aAAa,CAEpD,IAAK,IAAM,KAAY,EACrB,IAAK,IAAM,KAAW,EAAS,YAAa,CAE1C,IAAM,EAAe,EAAQ,aAAa,CAG1C,GAAI,EAAgB,EAAU,EAAa,CASzC,OARA,EAAO,MAAM,wCAAyC,CACpD,WACA,UACA,WAAY,EAAS,GACrB,aAAc,EAAS,KACxB,CAAC,CAGK,EAAc,EAAS,CAKpC,EAAO,MAAM,iDAAkD,CAC7D,WACA,UAAW,EAAa,UAAU,CACnC,CAAC,CA2CJ,SAAgB,EAAkB,EAAwC,CACxE,EAAiB,EAAU,IAAI,EAAc,CAO/C,SAAS,EAAc,EAA6C,CAClE,MAAO,CACL,GAAG,EACH,OAAQ,EAAE,OAAS,CAAC,GAAG,EAAE,OAAO,CAAG,IAAA,GACnC,YAAa,CAAC,GAAG,EAAE,YAAY,CAChC,CAWH,SAAS,EAAgB,EAAkB,EAA0B,CAYnE,MAJA,GANI,IAAa,GAMb,EAAS,SAAS,IAAI,IAAU"}
@@ -0,0 +1,3 @@
1
+ import{homedir as e}from"node:os";import{join as t}from"node:path";import{env as n,platform as r}from"node:process";import{clearTimeout as i,setTimeout as a}from"node:timers";import{execFile as o}from"node:child_process";const s=`onyx-mcp-gateway`,c=`default`,l=`/Library/Keychains/System.keychain`,u=2e3;async function d(e){return r===`darwin`?g(e):r===`win32`?v(e):_(e)}const f=Symbol(`keychain-probe-timeout`);function p(e){let r=n.LOCALAPPDATA??t(n.USERPROFILE??`C:\\`,`AppData`,`Local`);return t(r,`Onyx`,`mcp-gateway`,`${e}.bin`)}function m(e){let r=n.ProgramData??`C:\\ProgramData`;return t(r,`Onyx`,`mcp-gateway`,`${e}.bin`)}async function h(e,t={}){let n=t.getSecretFn??d,r=t.timeoutMs??15e3,o,s=new Promise(e=>{o=a(()=>e(f),r),o.unref?.()});try{let t=await Promise.race([n(e),s]);return t===f?{key:null,source:`timeout`}:t?{key:t,source:`keychain`}:{key:null,source:`missing`}}catch{return{key:null,source:`error`}}finally{o!==void 0&&i(o)}}async function g(e){try{let t=await b(),n=[];for(let r of t){let t=await T(e,r);t!==null&&n.push({keychain:r,mdat:t})}n.sort((e,t)=>t.mdat-e.mdat);for(let{keychain:t}of n){let n=await w(e,t);if(n!==null)return n}return await w(e,l)??await w(e,null)}catch{return null}}async function _(e){try{return(await x(e)).getPassword()}catch{return null}}async function v(e){let{stat:t}=await import(`node:fs/promises`),n=[{path:m(e),scope:`LocalMachine`},{path:p(e),scope:`CurrentUser`}],r=[];for(let e of n)try{let n=await t(e.path);r.push({mtimeMs:n.mtimeMs,path:e.path,scope:e.scope})}catch{}r.sort((e,t)=>t.mtimeMs-e.mtimeMs);for(let e of r){let t=await C(e.path,e.scope);if(t!==null)return t}return null}function y(){return new Promise(e=>{o(`/usr/bin/security`,[`list-keychains`,`-d`,`user`],{encoding:`utf8`,killSignal:`SIGKILL`,timeout:u},(t,n)=>{if(t){e([]);return}let r=String(n).split(`
2
+ `).map(e=>e.trim().replace(/^"|"$/g,``)).filter(e=>e!==``);e(r)})})}async function b(){let n=await y();return n.length===0?[l,t(e(),`Library`,`Keychains`,`login.keychain-db`)]:[l,...n.filter(e=>e!==l)]}async function x(e){let{Entry:t}=await import(`@napi-rs/keyring`);return new t(s,e)}function S(e){let t=/"mdat"<timedate>=0x[0-9a-fA-F]*\s+"(\d{14})Z/.exec(e);if(t===null)return null;let n=t[1];return Date.UTC(Number(n.slice(0,4)),Number(n.slice(4,6))-1,Number(n.slice(6,8)),Number(n.slice(8,10)),Number(n.slice(10,12)),Number(n.slice(12,14)))}async function C(e,t){let{readFile:n}=await import(`node:fs/promises`),r;try{r=await n(e)}catch{return null}let{Dpapi:i}=await import(`@primno/dpapi`);try{let e=i.unprotectData(new Uint8Array(r),null,t),n=Buffer.from(e).toString(`utf8`);return n===``?null:n}catch{return null}}function w(e,t){return new Promise(n=>{let r=[`find-generic-password`,`-s`,s,`-a`,e,`-w`];t!==null&&r.push(t),o(`/usr/bin/security`,r,{encoding:`utf8`,killSignal:`SIGKILL`,timeout:u},(e,t)=>{if(e){n(null);return}let r=String(t).trim();n(r===``?null:r)})})}function T(e,t){return new Promise(n=>{o(`/usr/bin/security`,[`find-generic-password`,`-s`,s,`-a`,e,t],{encoding:`utf8`,killSignal:`SIGKILL`,timeout:u},(e,t)=>{if(e){n(null);return}n(S(String(t)))})})}export{c as ACCOUNT_DEFAULT,h as resolveApiKeyFromStore};
3
+ //# sourceMappingURL=secretstore-B7UBzLo4.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"secretstore-B7UBzLo4.js","names":["platform","timer: NodeJS.Timeout | undefined","dated: { keychain: string; mdat: number }[]","candidates: { path: string; scope: \"CurrentUser\" | \"LocalMachine\" }[]","present: { mtimeMs: number; path: string; scope: \"CurrentUser\" | \"LocalMachine\" }[]","blob: Buffer"],"sources":["../src/lib/secretstore.ts"],"sourcesContent":["// Cross-platform keychain reader for the MCP Gateway.\n//\n// The scanner picks the store by privilege at install time: a privileged\n// (root/SYSTEM/MDM) install writes a MACHINE-SCOPED, boot-available store (so\n// it resolves even when no user is logged in); a regular-user install writes\n// that user's own per-user store. Because both stores can hold an entry, the\n// gateway picks whichever holds the most recently modified entry (the machine\n// store wins a tie), rather than a fixed machine-first order. The read paths:\n//\n// macOS: shells out to /usr/bin/security (async execFile). A privileged install\n// writes the allow-all (`-A`) entry to the System keychain\n// (/Library/Keychains/System.keychain); a regular-user install writes the\n// login keychain. Both can hold an entry — a machine install then a user\n// install, or a re-install into the other store — so the reader picks the\n// entry with the LATEST modification date rather than a fixed order, so a\n// stale key never shadows a fresher one. It reads each candidate keychain's\n// \"mdat\" attribute (System first, then the user search list from\n// `security list-keychains -d user`), takes the newest (a tie keeps System,\n// which is probed first), and reads the value from that keychain explicitly.\n// If no candidate exposes a parseable mdat it falls back to the legacy read\n// (System explicitly, then the default search list) so a present entry never\n// regresses to null. Same `security` caller on both ends ⇒ no per-binary ACL\n// prompt for the entry the scanner wrote.\n//\n// The `-A` ACL governs app access, not the keychain's locked state, so a\n// locked login keychain (or an ACL re-evaluated after the node binary\n// changed) can still pop a SecurityAgent dialog and BLOCK — and a coding-agent\n// subprocess can't dismiss it. The read is therefore hard-bounded with\n// killSignal \"SIGKILL\" (PRDCT-6680): the prior execFileSync timeout used the\n// default SIGTERM, which `security` ignores while blocked, so it never fired.\n//\n// Linux: uses @napi-rs/keyring (libsecret) with the default (service, user)\n// constructor; libsecret stores by attribute set, not by TargetName, so\n// the default constructor finds entries the scanner wrote via go-keyring.\n// (No machine-scoped store on Linux — the scanner always uses the per-user\n// path.)\n//\n// Windows: reads a DPAPI blob (@primno/dpapi). A privileged/SYSTEM install\n// writes the machine blob under %ProgramData% (LocalMachine scope — the path\n// that works for pre-login installs); a regular-user install writes the\n// per-user blob under %LOCALAPPDATA% (CurrentUser scope). Both can exist, so\n// the reader picks by the newest file mtime rather than a fixed order (a tie\n// keeps the machine blob) and decrypts in that order, falling through to the\n// next blob if one fails to decrypt. The scanner no longer writes the per-user\n// Credential Manager, so it isn't consulted.\n//\n// - macOS/Windows machine stores are unlocked at boot — no session, no prompt.\n// - the per-user stores (login keychain / CurrentUser blob) are readable by\n// the gateway running as that same user.\n// - Linux libsecret with an unlocked login keyring (the normal\n// desktop state) — silent. Locked / headless boxes return an error\n// which we treat as miss and fall through to env.\n//\n// All public functions are best-effort. On any error — missing backend,\n// timeout, malformed binding — getSecret returns null and the gateway\n// falls back to process.env (legacy behavior).\n//\n// Async API rationale: the @napi-rs/keyring native binding (Linux only) is\n// loaded via `await import(...)` so a missing prebuild on musl/alpine/headless\n// turns into a swallowed `catch` inside getSecretNative rather than a\n// module-load crash. Using `createRequire` for the same lazy-load worked\n// at runtime but was opaque to vitest's `vi.mock` (which only intercepts\n// ESM resolution), so the Linux test path resolved the real binding and\n// missed the mock. Dynamic ESM imports are interceptable on both runtime\n// and test paths.\n\nimport { execFile } from \"node:child_process\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { env, platform } from \"node:process\";\nimport { clearTimeout, setTimeout } from \"node:timers\";\n\nimport type { KeychainOutcomeSource } from \"./keychainOutcome.js\";\n\n/** Keychain service name. MUST match scanner/internal/secretstore Service. */\nexport const SERVICE = \"onyx-mcp-gateway\";\n\n/** Single-tenant account name; multi-tenant on the same host is future work. */\nexport const ACCOUNT_DEFAULT = \"default\";\n\n/**\n * macOS machine-scoped keychain. The scanner writes the gateway key here (with\n * an allow-all ACL) so it is readable with no interactive-login dependency. We\n * pass this path explicitly rather than relying on the default search list, so\n * a customized search list can't hide the entry.\n */\nconst MAC_SYSTEM_KEYCHAIN = \"/Library/Keychains/System.keychain\";\n\n/** Hard cap on a single security/Entry call so a hung backend never wedges startup. */\nconst READ_TIMEOUT_MS = 2_000;\n\n/**\n * Overall deadline for resolveApiKeyFromStore — a backstop so credential\n * resolution can never wedge gateway startup even if a per-call cap doesn't\n * fire. Sized for the macOS worst case, which is now several sequential\n * `security` calls rather than two: `list-keychains`, one `mdat` probe per\n * candidate keychain, and the value read (or the two-step legacy fallback) —\n * each capped at READ_TIMEOUT_MS. If more than one candidate keychain is locked\n * and hits its SIGKILL timeout, the old 5s ceiling could elapse before a present\n * key is returned, making resolveApiKeyFromStore report `timeout` and the\n * gateway start degraded. This backstop must exceed that worst case; waiting a\n * few extra seconds in the (pathological) all-hang case is strictly better than\n * dropping a resolvable key.\n */\nexport const KEYCHAIN_PROBE_TIMEOUT_MS = 15_000;\n\n/**\n * getMachineBlobSecret reads the machine-scoped DPAPI blob a privileged install\n * writes under %ProgramData% (LocalMachine scope, readable by every user).\n */\nexport async function getMachineBlobSecret(account: string): Promise<null | string> {\n\treturn readDpapiBlob(programDataBlobPath(account), \"LocalMachine\");\n}\n\n/**\n * Look up the password under (SERVICE, account). Returns null on miss, on\n * any backend error, or if the underlying keychain access fails. Never\n * throws.\n */\nexport async function getSecret(account: string): Promise<null | string> {\n\tif (platform === \"darwin\") {\n\t\t// macOS: machine-scoped System keychain (where the scanner writes).\n\t\treturn getSecretMac(account);\n\t}\n\tif (platform === \"win32\") {\n\t\t// The scanner writes a privileged install to the machine blob\n\t\t// (%ProgramData%, LocalMachine) and a regular-user install to the\n\t\t// per-user blob (%LOCALAPPDATA%, CurrentUser). Pick the newest blob by\n\t\t// mtime (a tie keeps the machine blob) so a stale entry never shadows a\n\t\t// fresher one. The scanner no longer writes the per-user Credential\n\t\t// Manager, so it isn't consulted.\n\t\treturn getSecretWindows(account);\n\t}\n\t// Linux: per-user libsecret vault. No machine-scoped store exists, so the\n\t// scanner keeps the per-user path and we read it via @napi-rs/keyring.\n\treturn getSecretNative(account);\n}\n\n/** Sentinel for the overall-deadline race in resolveApiKeyFromStore. */\nconst PROBE_TIMEOUT = Symbol(\"keychain-probe-timeout\");\n\n/**\n * Outcome of resolving the scanner api-key from the OS secret store, classified\n * for the keychain_outcome telemetry. `error` is defensive (getSecret is\n * best-effort and shouldn't throw); `timeout` is the backstop for a probe that\n * blocked past KEYCHAIN_PROBE_TIMEOUT_MS.\n */\nexport interface ApiKeyResolution {\n\tkey: null | string;\n\tsource: Extract<KeychainOutcomeSource, \"error\" | \"keychain\" | \"missing\" | \"timeout\">;\n}\n\n/**\n * getUserBlobSecret reads the per-user DPAPI blob a regular-user install writes\n * under %LOCALAPPDATA% (CurrentUser scope, readable only by that user).\n */\nexport async function getUserBlobSecret(account: string): Promise<null | string> {\n\treturn readDpapiBlob(localAppDataBlobPath(account), \"CurrentUser\");\n}\n\n/**\n * localAppDataBlobPath is the absolute path of the Windows per-user DPAPI blob a\n * regular-user install writes. MUST match scanner/internal/secretstore\n * userBlobPath: %LOCALAPPDATA%\\Onyx\\mcp-gateway\\<account>.bin.\n */\nexport function localAppDataBlobPath(account: string): string {\n\tconst base = env.LOCALAPPDATA ?? join(env.USERPROFILE ?? \"C:\\\\\", \"AppData\", \"Local\");\n\treturn join(base, \"Onyx\", \"mcp-gateway\", `${account}.bin`);\n}\n\n/**\n * programDataBlobPath is the absolute path of the Windows machine-scoped DPAPI\n * blob a privileged install writes. MUST match scanner/internal/secretstore\n * programDataBlobPath: %ProgramData%\\Onyx\\mcp-gateway\\<account>.bin.\n */\nexport function programDataBlobPath(account: string): string {\n\tconst base = env.ProgramData ?? \"C:\\\\ProgramData\";\n\treturn join(base, \"Onyx\", \"mcp-gateway\", `${account}.bin`);\n}\n\n/**\n * Resolve the scanner api-key from the OS secret store, bounded by an overall\n * hard deadline so the credential probe is GUARANTEED non-blocking — the gateway\n * must never hang on credential resolution before the MCP handshake (PRDCT-6680).\n *\n * Never throws. `opts` is for tests: `getSecretFn` injects a fake reader and\n * `timeoutMs` shrinks the deadline.\n */\nexport async function resolveApiKeyFromStore(\n\taccount: string,\n\topts: { getSecretFn?: (account: string) => Promise<null | string>; timeoutMs?: number } = {},\n): Promise<ApiKeyResolution> {\n\tconst getSecretFn = opts.getSecretFn ?? getSecret;\n\tconst timeoutMs = opts.timeoutMs ?? KEYCHAIN_PROBE_TIMEOUT_MS;\n\n\tlet timer: NodeJS.Timeout | undefined;\n\tconst deadline = new Promise<typeof PROBE_TIMEOUT>((resolve) => {\n\t\ttimer = setTimeout(() => resolve(PROBE_TIMEOUT), timeoutMs);\n\t\t// Don't keep the event loop alive just for this backstop timer.\n\t\ttimer.unref?.();\n\t});\n\n\ttry {\n\t\tconst result = await Promise.race([getSecretFn(account), deadline]);\n\t\tif (result === PROBE_TIMEOUT) {\n\t\t\treturn { key: null, source: \"timeout\" };\n\t\t}\n\t\tif (result) {\n\t\t\treturn { key: result, source: \"keychain\" };\n\t\t}\n\t\treturn { key: null, source: \"missing\" };\n\t} catch {\n\t\treturn { key: null, source: \"error\" };\n\t} finally {\n\t\tif (timer !== undefined) {\n\t\t\tclearTimeout(timer);\n\t\t}\n\t}\n}\n\n/**\n * getSecretMac reads the gateway key from the macOS keychain, preferring the\n * entry with the newest modification date across the candidate keychains — so a\n * stale entry in one store never shadows a fresher one written later to another.\n * Candidates are the System keychain FIRST, then the user's search list\n * (`security list-keychains -d user`, System removed). For each candidate we\n * read the entry's \"mdat\" attribute; the newest wins (a tie keeps System, which\n * is iterated first, via a strict \"newer than\" comparison). The value is then\n * read from the winning keychain. If no candidate exposes a parseable mdat but a\n * value is present, fall back to the legacy read (System explicitly, then the\n * default search list) so a present entry never regresses to null. Never throws.\n */\nasync function getSecretMac(account: string): Promise<null | string> {\n\ttry {\n\t\tconst candidates = await macKeychainCandidates();\n\t\tconst dated: { keychain: string; mdat: number }[] = [];\n\t\tfor (const keychain of candidates) {\n\t\t\tconst mdat = await readSecurityModDate(account, keychain);\n\t\t\tif (mdat !== null) {\n\t\t\t\tdated.push({ keychain, mdat });\n\t\t\t}\n\t\t}\n\t\t// Newest first. Array.sort is stable, so an mdat tie keeps the\n\t\t// earlier-iterated candidate — System is listed first, so a tie resolves\n\t\t// to System.keychain.\n\t\tdated.sort((a, b) => b.mdat - a.mdat);\n\t\t// Try newest-first, falling through to the next-newest candidate on a\n\t\t// value-read miss/failure (a transient SIGKILL timeout, or the keychain\n\t\t// re-locking between the mdat probe and the value read) so a readable\n\t\t// older entry is never abandoned. Mirrors getSecretWindows and honors the\n\t\t// never-lose-a-present-key guarantee.\n\t\tfor (const { keychain } of dated) {\n\t\t\tconst value = await readSecurityKeychain(account, keychain);\n\t\t\tif (value !== null) {\n\t\t\t\treturn value;\n\t\t\t}\n\t\t}\n\t\t// No candidate exposed a parseable mdat, or every value read missed. Fall\n\t\t// back to the legacy read so a present-but-unparseable entry never\n\t\t// regresses to null: System explicitly first, then the default search\n\t\t// list (which covers the login keychain).\n\t\treturn (\n\t\t\t(await readSecurityKeychain(account, MAC_SYSTEM_KEYCHAIN)) ??\n\t\t\t(await readSecurityKeychain(account, null))\n\t\t);\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nasync function getSecretNative(account: string): Promise<null | string> {\n\ttry {\n\t\tconst entry = await nativeEntry(account);\n\t\treturn entry.getPassword();\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/**\n * getSecretWindows reads the gateway key from the newest Windows DPAPI blob. A\n * privileged install writes the machine blob (%ProgramData%, LocalMachine); a\n * regular-user install writes the per-user blob (%LOCALAPPDATA%, CurrentUser).\n * Both can exist, so pick by newest file mtime rather than a fixed order and\n * decrypt in that order — a decrypt failure falls through to the next blob. An\n * mtime tie resolves to the machine blob (listed first, with a stable, strict\n * comparison). Returns null when neither blob exists. A present blob whose native\n * binding fails to load still propagates (readDpapiBlob's intentional throw).\n */\nasync function getSecretWindows(account: string): Promise<null | string> {\n\tconst { stat } = await import(\"node:fs/promises\");\n\tconst candidates: { path: string; scope: \"CurrentUser\" | \"LocalMachine\" }[] = [\n\t\t{ path: programDataBlobPath(account), scope: \"LocalMachine\" },\n\t\t{ path: localAppDataBlobPath(account), scope: \"CurrentUser\" },\n\t];\n\tconst present: { mtimeMs: number; path: string; scope: \"CurrentUser\" | \"LocalMachine\" }[] = [];\n\tfor (const candidate of candidates) {\n\t\ttry {\n\t\t\tconst info = await stat(candidate.path);\n\t\t\tpresent.push({ mtimeMs: info.mtimeMs, path: candidate.path, scope: candidate.scope });\n\t\t} catch {\n\t\t\t// Blob absent at this scope — an expected miss; skip it.\n\t\t}\n\t}\n\t// Newest mtime first. The sort is stable and the comparison strict, so an\n\t// mtime tie keeps the machine blob (candidates[0]) ahead of the user blob.\n\tpresent.sort((a, b) => b.mtimeMs - a.mtimeMs);\n\tfor (const candidate of present) {\n\t\tconst value = await readDpapiBlob(candidate.path, candidate.scope);\n\t\tif (value !== null) {\n\t\t\treturn value;\n\t\t}\n\t}\n\treturn null;\n}\n\n// listUserKeychains returns the user's keychain search list from\n// `security list-keychains -d user`, one absolute path per line with the\n// surrounding quotes stripped. Same execFile hard-bound options as the reads\n// (SIGKILL + numeric timeout). Never rejects: resolves [] on error/timeout so\n// getSecretMac can fall back to the login keychain.\nfunction listUserKeychains(): Promise<string[]> {\n\treturn new Promise((resolve) => {\n\t\texecFile(\n\t\t\t\"/usr/bin/security\",\n\t\t\t[\"list-keychains\", \"-d\", \"user\"],\n\t\t\t{ encoding: \"utf8\", killSignal: \"SIGKILL\", timeout: READ_TIMEOUT_MS },\n\t\t\t(error, stdout) => {\n\t\t\t\tif (error) {\n\t\t\t\t\tresolve([]);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst keychains = String(stdout)\n\t\t\t\t\t.split(\"\\n\")\n\t\t\t\t\t.map((line) => line.trim().replace(/^\"|\"$/g, \"\"))\n\t\t\t\t\t.filter((line) => line !== \"\");\n\t\t\t\tresolve(keychains);\n\t\t\t},\n\t\t);\n\t});\n}\n\n/**\n * macKeychainCandidates lists the keychains to probe for the gateway key, System\n * FIRST (so an mdat tie resolves to it) then the user's search list with System\n * removed. If `security list-keychains -d user` fails or is empty, fall back to\n * [System, login] using the login keychain under the user's home.\n */\nasync function macKeychainCandidates(): Promise<string[]> {\n\tconst userKeychains = await listUserKeychains();\n\tif (userKeychains.length === 0) {\n\t\treturn [MAC_SYSTEM_KEYCHAIN, join(homedir(), \"Library\", \"Keychains\", \"login.keychain-db\")];\n\t}\n\treturn [MAC_SYSTEM_KEYCHAIN, ...userKeychains.filter((keychain) => keychain !== MAC_SYSTEM_KEYCHAIN)];\n}\n\n/**\n * Build an @napi-rs/keyring Entry for the Linux libsecret read. libsecret\n * matches by attribute set (service + user), so the default constructor finds\n * entries the scanner wrote via go-keyring. Linux is the only caller: darwin\n * shells to /usr/bin/security and Windows reads the machine DPAPI blob, so\n * neither loads the native binding. The dynamic `import` is lazy so a missing\n * prebuild on musl/alpine/headless becomes a swallowed exception inside\n * getSecretNative rather than a module-load crash. Using `await import(...)`\n * (rather than createRequire) makes the load interceptable by vitest's\n * `vi.mock` on the Linux test path.\n */\nasync function nativeEntry(account: string) {\n\tconst { Entry } = await import(\"@napi-rs/keyring\");\n\treturn new Entry(SERVICE, account);\n}\n\n/**\n * parseMdatEpochMs extracts the \"mdat\" (modification-date) attribute from a\n * `security find-generic-password` attribute dump and returns it as epoch ms.\n * The line looks like: \"mdat\"<timedate>=0x... \"YYYYMMDDHHMMSSZ\\000\"\n * The quoted 14-digit stamp (plus the trailing Z) is parsed as UTC. Returns null\n * when no mdat attribute is present.\n */\nfunction parseMdatEpochMs(dump: string): null | number {\n\tconst match = /\"mdat\"<timedate>=0x[0-9a-fA-F]*\\s+\"(\\d{14})Z/.exec(dump);\n\tif (match === null) {\n\t\treturn null;\n\t}\n\tconst stamp = match[1];\n\treturn Date.UTC(\n\t\tNumber(stamp.slice(0, 4)),\n\t\tNumber(stamp.slice(4, 6)) - 1,\n\t\tNumber(stamp.slice(6, 8)),\n\t\tNumber(stamp.slice(8, 10)),\n\t\tNumber(stamp.slice(10, 12)),\n\t\tNumber(stamp.slice(12, 14)),\n\t);\n}\n\n/**\n * readDpapiBlob reads a Windows DPAPI blob from `path` and decrypts it with the\n * given scope. The @primno/dpapi import is lazy so a missing prebuild never\n * crashes startup (mirrors the @napi-rs/keyring lazy import).\n *\n * Two failure modes are deliberately NOT treated the same:\n * - No blob at `path`: a legitimate, expected miss (nothing was ever written\n * at this scope, or this install doesn't use it). Swallowed to null.\n * - Blob present but the @primno/dpapi native binding fails to load: this\n * means the scanner DID write a secret here but the gateway binary can't\n * read it back — e.g. a cross-compiled Windows binary missing the addon's\n * prebuilt .node (a real packaging defect, not an absent-secret case).\n * Left to propagate, so resolveApiKeyFromStore's outcome=\"error\" telemetry\n * surfaces it distinctly instead of blending into the generic \"missing\"\n * bucket every no-secret endpoint already reports.\n * A decrypt failure once the binding loaded (wrong scope, corrupt blob) is\n * still swallowed to null — that's an expected miss, not a packaging defect.\n */\nasync function readDpapiBlob(\n\tpath: string,\n\tscope: \"CurrentUser\" | \"LocalMachine\",\n): Promise<null | string> {\n\tconst { readFile } = await import(\"node:fs/promises\");\n\tlet blob: Buffer;\n\ttry {\n\t\tblob = await readFile(path);\n\t} catch {\n\t\treturn null;\n\t}\n\n\tconst { Dpapi } = await import(\"@primno/dpapi\");\n\ttry {\n\t\tconst decrypted = Dpapi.unprotectData(new Uint8Array(blob), null, scope);\n\t\tconst value = Buffer.from(decrypted).toString(\"utf8\");\n\t\treturn value === \"\" ? null : value;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n// readSecurityKeychain runs `security find-generic-password -w` asynchronously,\n// reading the explicit `keychain` path when given or the default search list\n// when null. Never rejects — resolves null on miss/error/timeout so the caller\n// can fall through. Hard-bounded with killSignal \"SIGKILL\" (see the header).\nfunction readSecurityKeychain(account: string, keychain: null | string): Promise<null | string> {\n\treturn new Promise((resolve) => {\n\t\tconst args = [\"find-generic-password\", \"-s\", SERVICE, \"-a\", account, \"-w\"];\n\t\tif (keychain !== null) {\n\t\t\targs.push(keychain);\n\t\t}\n\t\texecFile(\n\t\t\t\"/usr/bin/security\",\n\t\t\targs,\n\t\t\t{ encoding: \"utf8\", killSignal: \"SIGKILL\", timeout: READ_TIMEOUT_MS },\n\t\t\t(error, stdout) => {\n\t\t\t\tif (error) {\n\t\t\t\t\t// miss, security CLI error, or SIGKILL'd timeout — all a miss.\n\t\t\t\t\tresolve(null);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst trimmed = String(stdout).trim();\n\t\t\t\tresolve(trimmed === \"\" ? null : trimmed);\n\t\t\t},\n\t\t);\n\t});\n}\n\n// readSecurityModDate runs `security find-generic-password` WITHOUT -w against\n// `keychain` and parses the entry's \"mdat\" (modification-date) attribute into a\n// comparable epoch-ms value. Mirrors readSecurityKeychain's execFile options\n// (SIGKILL + numeric timeout — see the header). Never rejects: resolves null on\n// miss, error, timeout, or an attribute dump with no parseable mdat.\nfunction readSecurityModDate(account: string, keychain: string): Promise<null | number> {\n\treturn new Promise((resolve) => {\n\t\texecFile(\n\t\t\t\"/usr/bin/security\",\n\t\t\t[\"find-generic-password\", \"-s\", SERVICE, \"-a\", account, keychain],\n\t\t\t{ encoding: \"utf8\", killSignal: \"SIGKILL\", timeout: READ_TIMEOUT_MS },\n\t\t\t(error, stdout) => {\n\t\t\t\tif (error) {\n\t\t\t\t\t// miss, security CLI error, or SIGKILL'd timeout — all a miss.\n\t\t\t\t\tresolve(null);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tresolve(parseMdatEpochMs(String(stdout)));\n\t\t\t},\n\t\t);\n\t});\n}\n"],"mappings":"6NA2EA,MAAa,EAAU,mBAGV,EAAkB,UAQzB,EAAsB,qCAGtB,EAAkB,IA8BxB,eAAsB,EAAU,EAAyC,CAgBxE,OAfIA,IAAa,SAET,EAAa,EAAQ,CAEzBA,IAAa,QAOT,EAAiB,EAAQ,CAI1B,EAAgB,EAAQ,CAIhC,MAAM,EAAgB,OAAO,yBAAyB,CA0BtD,SAAgB,EAAqB,EAAyB,CAC7D,IAAM,EAAO,EAAI,cAAgB,EAAK,EAAI,aAAe,OAAQ,UAAW,QAAQ,CACpF,OAAO,EAAK,EAAM,OAAQ,cAAe,GAAG,EAAQ,MAAM,CAQ3D,SAAgB,EAAoB,EAAyB,CAC5D,IAAM,EAAO,EAAI,aAAe,kBAChC,OAAO,EAAK,EAAM,OAAQ,cAAe,GAAG,EAAQ,MAAM,CAW3D,eAAsB,EACrB,EACA,EAA0F,EAAE,CAChE,CAC5B,IAAM,EAAc,EAAK,aAAe,EAClC,EAAY,EAAK,WAAa,KAEhCC,EACE,EAAW,IAAI,QAA+B,GAAY,CAC/D,EAAQ,MAAiB,EAAQ,EAAc,CAAE,EAAU,CAE3D,EAAM,SAAS,EACd,CAEF,GAAI,CACH,IAAM,EAAS,MAAM,QAAQ,KAAK,CAAC,EAAY,EAAQ,CAAE,EAAS,CAAC,CAOnE,OANI,IAAW,EACP,CAAE,IAAK,KAAM,OAAQ,UAAW,CAEpC,EACI,CAAE,IAAK,EAAQ,OAAQ,WAAY,CAEpC,CAAE,IAAK,KAAM,OAAQ,UAAW,MAChC,CACP,MAAO,CAAE,IAAK,KAAM,OAAQ,QAAS,QAC5B,CACL,IAAU,IAAA,IACb,EAAa,EAAM,EAiBtB,eAAe,EAAa,EAAyC,CACpE,GAAI,CACH,IAAM,EAAa,MAAM,GAAuB,CAC1CC,EAA8C,EAAE,CACtD,IAAK,IAAM,KAAY,EAAY,CAClC,IAAM,EAAO,MAAM,EAAoB,EAAS,EAAS,CACrD,IAAS,MACZ,EAAM,KAAK,CAAE,WAAU,OAAM,CAAC,CAMhC,EAAM,MAAM,EAAG,IAAM,EAAE,KAAO,EAAE,KAAK,CAMrC,IAAK,GAAM,CAAE,cAAc,EAAO,CACjC,IAAM,EAAQ,MAAM,EAAqB,EAAS,EAAS,CAC3D,GAAI,IAAU,KACb,OAAO,EAOT,OACE,MAAM,EAAqB,EAAS,EAAoB,EACxD,MAAM,EAAqB,EAAS,KAAK,MAEpC,CACP,OAAO,MAIT,eAAe,EAAgB,EAAyC,CACvE,GAAI,CAEH,OADc,MAAM,EAAY,EAAQ,EAC3B,aAAa,MACnB,CACP,OAAO,MAcT,eAAe,EAAiB,EAAyC,CACxE,GAAM,CAAE,QAAS,MAAM,OAAO,oBACxBC,EAAwE,CAC7E,CAAE,KAAM,EAAoB,EAAQ,CAAE,MAAO,eAAgB,CAC7D,CAAE,KAAM,EAAqB,EAAQ,CAAE,MAAO,cAAe,CAC7D,CACKC,EAAsF,EAAE,CAC9F,IAAK,IAAM,KAAa,EACvB,GAAI,CACH,IAAM,EAAO,MAAM,EAAK,EAAU,KAAK,CACvC,EAAQ,KAAK,CAAE,QAAS,EAAK,QAAS,KAAM,EAAU,KAAM,MAAO,EAAU,MAAO,CAAC,MAC9E,EAMT,EAAQ,MAAM,EAAG,IAAM,EAAE,QAAU,EAAE,QAAQ,CAC7C,IAAK,IAAM,KAAa,EAAS,CAChC,IAAM,EAAQ,MAAM,EAAc,EAAU,KAAM,EAAU,MAAM,CAClE,GAAI,IAAU,KACb,OAAO,EAGT,OAAO,KAQR,SAAS,GAAuC,CAC/C,OAAO,IAAI,QAAS,GAAY,CAC/B,EACC,oBACA,CAAC,iBAAkB,KAAM,OAAO,CAChC,CAAE,SAAU,OAAQ,WAAY,UAAW,QAAS,EAAiB,EACpE,EAAO,IAAW,CAClB,GAAI,EAAO,CACV,EAAQ,EAAE,CAAC,CACX,OAED,IAAM,EAAY,OAAO,EAAO,CAC9B,MAAM;EAAK,CACX,IAAK,GAAS,EAAK,MAAM,CAAC,QAAQ,SAAU,GAAG,CAAC,CAChD,OAAQ,GAAS,IAAS,GAAG,CAC/B,EAAQ,EAAU,EAEnB,EACA,CASH,eAAe,GAA2C,CACzD,IAAM,EAAgB,MAAM,GAAmB,CAI/C,OAHI,EAAc,SAAW,EACrB,CAAC,EAAqB,EAAK,GAAS,CAAE,UAAW,YAAa,oBAAoB,CAAC,CAEpF,CAAC,EAAqB,GAAG,EAAc,OAAQ,GAAa,IAAa,EAAoB,CAAC,CActG,eAAe,EAAY,EAAiB,CAC3C,GAAM,CAAE,SAAU,MAAM,OAAO,oBAC/B,OAAO,IAAI,EAAM,EAAS,EAAQ,CAUnC,SAAS,EAAiB,EAA6B,CACtD,IAAM,EAAQ,+CAA+C,KAAK,EAAK,CACvE,GAAI,IAAU,KACb,OAAO,KAER,IAAM,EAAQ,EAAM,GACpB,OAAO,KAAK,IACX,OAAO,EAAM,MAAM,EAAG,EAAE,CAAC,CACzB,OAAO,EAAM,MAAM,EAAG,EAAE,CAAC,CAAG,EAC5B,OAAO,EAAM,MAAM,EAAG,EAAE,CAAC,CACzB,OAAO,EAAM,MAAM,EAAG,GAAG,CAAC,CAC1B,OAAO,EAAM,MAAM,GAAI,GAAG,CAAC,CAC3B,OAAO,EAAM,MAAM,GAAI,GAAG,CAAC,CAC3B,CAqBF,eAAe,EACd,EACA,EACyB,CACzB,GAAM,CAAE,YAAa,MAAM,OAAO,oBAC9BC,EACJ,GAAI,CACH,EAAO,MAAM,EAAS,EAAK,MACpB,CACP,OAAO,KAGR,GAAM,CAAE,SAAU,MAAM,OAAO,iBAC/B,GAAI,CACH,IAAM,EAAY,EAAM,cAAc,IAAI,WAAW,EAAK,CAAE,KAAM,EAAM,CAClE,EAAQ,OAAO,KAAK,EAAU,CAAC,SAAS,OAAO,CACrD,OAAO,IAAU,GAAK,KAAO,OACtB,CACP,OAAO,MAQT,SAAS,EAAqB,EAAiB,EAAiD,CAC/F,OAAO,IAAI,QAAS,GAAY,CAC/B,IAAM,EAAO,CAAC,wBAAyB,KAAM,EAAS,KAAM,EAAS,KAAK,CACtE,IAAa,MAChB,EAAK,KAAK,EAAS,CAEpB,EACC,oBACA,EACA,CAAE,SAAU,OAAQ,WAAY,UAAW,QAAS,EAAiB,EACpE,EAAO,IAAW,CAClB,GAAI,EAAO,CAEV,EAAQ,KAAK,CACb,OAED,IAAM,EAAU,OAAO,EAAO,CAAC,MAAM,CACrC,EAAQ,IAAY,GAAK,KAAO,EAAQ,EAEzC,EACA,CAQH,SAAS,EAAoB,EAAiB,EAA0C,CACvF,OAAO,IAAI,QAAS,GAAY,CAC/B,EACC,oBACA,CAAC,wBAAyB,KAAM,EAAS,KAAM,EAAS,EAAS,CACjE,CAAE,SAAU,OAAQ,WAAY,UAAW,QAAS,EAAiB,EACpE,EAAO,IAAW,CAClB,GAAI,EAAO,CAEV,EAAQ,KAAK,CACb,OAED,EAAQ,EAAiB,OAAO,EAAO,CAAC,CAAC,EAE1C,EACA"}
@@ -1,4 +1,4 @@
1
- import{__commonJSMin as e,__require as t,__toESM as n}from"./chunk-CrDKVgUD.js";import{CallToolRequestSchema as r,CallToolResultSchema as i,CancelTaskRequestSchema as a,CancelTaskResultSchema as o,CancelledNotificationSchema as s,CompleteRequestSchema as c,CompleteResultSchema as l,CreateMessageRequestSchema as u,CreateMessageResultSchema as d,CreateMessageResultWithToolsSchema as f,CreateTaskResultSchema as p,DEFAULT_NEGOTIATED_PROTOCOL_VERSION as m,ElicitRequestSchema as h,ElicitResultSchema as g,EmptyResultSchema as _,ErrorCode as v,GetPromptRequestSchema as y,GetPromptResultSchema as b,GetTaskPayloadRequestSchema as x,GetTaskRequestSchema as S,GetTaskResultSchema as C,InitializeRequestSchema as w,InitializeResultSchema as T,InitializedNotificationSchema as E,JSONRPCMessageSchema as D,LATEST_PROTOCOL_VERSION as O,ListChangedOptionsBaseSchema as k,ListPromptsRequestSchema as A,ListPromptsResultSchema as ee,ListResourceTemplatesRequestSchema as te,ListResourceTemplatesResultSchema as ne,ListResourcesRequestSchema as j,ListResourcesResultSchema as re,ListRootsResultSchema as ie,ListTasksRequestSchema as M,ListTasksResultSchema as ae,ListToolsRequestSchema as oe,ListToolsResultSchema as se,LoggingLevelSchema as ce,LoggingMessageNotificationSchema as le,McpError as N,PingRequestSchema as ue,ProgressNotificationSchema as de,PromptListChangedNotificationSchema as fe,RELATED_TASK_META_KEY as P,ReadResourceRequestSchema as pe,ReadResourceResultSchema as me,ResourceListChangedNotificationSchema as he,ResourceUpdatedNotificationSchema as ge,SUPPORTED_PROTOCOL_VERSIONS as _e,SetLevelRequestSchema as ve,SubscribeRequestSchema as ye,TaskStatusNotificationSchema as be,ToolListChangedNotificationSchema as xe,UnsubscribeRequestSchema as Se,isInitializeRequest as Ce,isJSONRPCErrorResponse as we,isJSONRPCNotification as Te,isJSONRPCRequest as F,isJSONRPCResultResponse as I,isTaskAugmentedRequestParams as Ee,safeParse as De}from"./normalizeUrl-BrUSzVK4.js";import{SESSION_ID as Oe,config as ke}from"./env-DJNvBCH9.js";import{extractTraceIdFromHeaders as Ae,gatewayCorrelationId as je,logger as L,require_inherits as Me,runWithTraceContextAsync as Ne}from"./logger-BjLVc61x.js";import Pe,{randomUUID as Fe}from"crypto";import{homedir as Ie,hostname as Le,userInfo as Re}from"node:os";import{join as ze}from"node:path";import{randomUUID as Be}from"node:crypto";import{existsSync as Ve,readFileSync as He}from"node:fs";import{Readable as Ue}from"stream";import We from"ps-list";import{deflateSync as Ge}from"node:zlib";import{URL as Ke}from"node:url";import{Http2ServerRequest as qe,constants as Je}from"http2";import Ye from"node:http";import Xe from"node:process";var Ze=class{counter=0;events=new Map;async replayEventsAfter(e,{send:t}){if(!e||!this.events.has(e))return``;let n=this.getStreamIdFromEventId(e);if(!n)return``;let r=!1,i=[...this.events.entries()].sort((e,t)=>e[0].localeCompare(t[0]));for(let[a,{message:o,streamId:s}]of i){if(s!==n)continue;if(a===e){r=!0;continue}r&&await t(a,o)}return n}async storeEvent(e,t){let n=this.generateEventId(e);return this.events.set(n,{message:t,streamId:e}),n}generateEventId(e){let t=(++this.counter).toString().padStart(12,`0`);return`${e}_${Date.now()}_${t}_${Math.random().toString(36).substring(2,10)}`}getStreamIdFromEventId(e){let t=e.split(`_`);return t.length<4?``:t.slice(0,-3).join(`_`)}},Qe=class extends Error{extra;tags;constructor(e,t,n={},r={}){super(t),this.name=e,this.tags=n,this.extra=r}},$e=class extends Qe{constructor(e,t=`access_denied`,n={}){super(`AccessControlBlockError`,e,{feature:`access_control`,module:`security`,operation:`block`},{reason:t,...n}),this.reason=t}},et=class extends Qe{constructor(e,t,n={}){super(`ConfigurationError`,e,{feature:`configuration`,module:`cli`,operation:`validate`},{configKey:t,...n})}},tt=class extends Qe{constructor(e,t,n,r={},i){super(`ProxyConnectionError`,e,{feature:`connection`,module:`proxy`,operation:`connect`,transport:n||`unknown`},{url:t?(()=>{try{return new URL(t).origin}catch{return t}})():void 0,...r}),i!==void 0&&(this.cause=i)}};const nt=ke.clientAppName;let rt=null;const it=async()=>(rt||=await import(`systeminformation`),rt);function at(e){return typeof e==`string`&&e!==``&&e.includes(`@`)}function ot(){try{let e=ut();if(!Ve(e))return null;let t=He(e,`utf-8`),n=!1;for(let e of t.split(`
1
+ import{__commonJSMin as e,__require as t,__toESM as n}from"./chunk-CrDKVgUD.js";import{CallToolRequestSchema as r,CallToolResultSchema as i,CancelTaskRequestSchema as a,CancelTaskResultSchema as o,CancelledNotificationSchema as s,CompleteRequestSchema as c,CompleteResultSchema as l,CreateMessageRequestSchema as u,CreateMessageResultSchema as d,CreateMessageResultWithToolsSchema as f,CreateTaskResultSchema as p,DEFAULT_NEGOTIATED_PROTOCOL_VERSION as m,ElicitRequestSchema as h,ElicitResultSchema as g,EmptyResultSchema as _,ErrorCode as v,GetPromptRequestSchema as y,GetPromptResultSchema as b,GetTaskPayloadRequestSchema as x,GetTaskRequestSchema as S,GetTaskResultSchema as C,InitializeRequestSchema as w,InitializeResultSchema as T,InitializedNotificationSchema as E,JSONRPCMessageSchema as D,LATEST_PROTOCOL_VERSION as O,ListChangedOptionsBaseSchema as k,ListPromptsRequestSchema as A,ListPromptsResultSchema as ee,ListResourceTemplatesRequestSchema as te,ListResourceTemplatesResultSchema as ne,ListResourcesRequestSchema as j,ListResourcesResultSchema as re,ListRootsResultSchema as ie,ListTasksRequestSchema as M,ListTasksResultSchema as ae,ListToolsRequestSchema as oe,ListToolsResultSchema as se,LoggingLevelSchema as ce,LoggingMessageNotificationSchema as le,McpError as N,PingRequestSchema as ue,ProgressNotificationSchema as de,PromptListChangedNotificationSchema as fe,RELATED_TASK_META_KEY as P,ReadResourceRequestSchema as pe,ReadResourceResultSchema as me,ResourceListChangedNotificationSchema as he,ResourceUpdatedNotificationSchema as ge,SUPPORTED_PROTOCOL_VERSIONS as _e,SetLevelRequestSchema as ve,SubscribeRequestSchema as ye,TaskStatusNotificationSchema as be,ToolListChangedNotificationSchema as xe,UnsubscribeRequestSchema as Se,isInitializeRequest as Ce,isJSONRPCErrorResponse as we,isJSONRPCNotification as Te,isJSONRPCRequest as F,isJSONRPCResultResponse as I,isTaskAugmentedRequestParams as Ee,safeParse as De}from"./normalizeUrl-BrUSzVK4.js";import{SESSION_ID as Oe,config as ke}from"./env-DKEqpop9.js";import{extractTraceIdFromHeaders as Ae,gatewayCorrelationId as je,logger as L,require_inherits as Me,runWithTraceContextAsync as Ne}from"./logger-jKh1IKjp.js";import Pe,{randomUUID as Fe}from"crypto";import{homedir as Ie,hostname as Le,userInfo as Re}from"node:os";import{join as ze}from"node:path";import{randomUUID as Be}from"node:crypto";import{existsSync as Ve,readFileSync as He}from"node:fs";import{Readable as Ue}from"stream";import We from"ps-list";import{deflateSync as Ge}from"node:zlib";import{URL as Ke}from"node:url";import{Http2ServerRequest as qe,constants as Je}from"http2";import Ye from"node:http";import Xe from"node:process";var Ze=class{counter=0;events=new Map;async replayEventsAfter(e,{send:t}){if(!e||!this.events.has(e))return``;let n=this.getStreamIdFromEventId(e);if(!n)return``;let r=!1,i=[...this.events.entries()].sort((e,t)=>e[0].localeCompare(t[0]));for(let[a,{message:o,streamId:s}]of i){if(s!==n)continue;if(a===e){r=!0;continue}r&&await t(a,o)}return n}async storeEvent(e,t){let n=this.generateEventId(e);return this.events.set(n,{message:t,streamId:e}),n}generateEventId(e){let t=(++this.counter).toString().padStart(12,`0`);return`${e}_${Date.now()}_${t}_${Math.random().toString(36).substring(2,10)}`}getStreamIdFromEventId(e){let t=e.split(`_`);return t.length<4?``:t.slice(0,-3).join(`_`)}},Qe=class extends Error{extra;tags;constructor(e,t,n={},r={}){super(t),this.name=e,this.tags=n,this.extra=r}},$e=class extends Qe{constructor(e,t=`access_denied`,n={}){super(`AccessControlBlockError`,e,{feature:`access_control`,module:`security`,operation:`block`},{reason:t,...n}),this.reason=t}},et=class extends Qe{constructor(e,t,n={}){super(`ConfigurationError`,e,{feature:`configuration`,module:`cli`,operation:`validate`},{configKey:t,...n})}},tt=class extends Qe{constructor(e,t,n,r={},i){super(`ProxyConnectionError`,e,{feature:`connection`,module:`proxy`,operation:`connect`,transport:n||`unknown`},{url:t?(()=>{try{return new URL(t).origin}catch{return t}})():void 0,...r}),i!==void 0&&(this.cause=i)}};const nt=ke.clientAppName;let rt=null;const it=async()=>(rt||=await import(`systeminformation`),rt);function at(e){return typeof e==`string`&&e!==``&&e.includes(`@`)}function ot(){try{let e=ut();if(!Ve(e))return null;let t=He(e,`utf-8`),n=!1;for(let e of t.split(`
2
2
  `)){let t=e.trim();if(t.startsWith(`#`)||t.startsWith(`;`))continue;if(t.startsWith(`[`)){n=t.toLowerCase()===`[user]`;continue}if(n){let e=t.match(/^email\s*=\s*(.+)/i);if(e)return e[1].replace(/\s+[#;].*$/,``).trim()||null}}return null}catch{return null}}function st(){return ze(Ie(),`.claude.json`)}function ct(){return ze(Ie(),`.codex`,`auth.json`)}function lt(){try{return Le()}catch{return`unknown-device`}}function ut(){return ze(Ie(),`.gitconfig`)}async function dt(e){try{return(await We()).find(t=>t.pid===e)?.name||`unknown`}catch{return`unknown`}}async function ft(){try{let e=(await(await it()).system()).serial;return e&&e!==``&&e!==`0`&&!e.toLowerCase().includes(`to be filled`)?e:void 0}catch{return}}function pt(){try{let e=ht()?.oauthAccount?.emailAddress;if(at(e))return e;let t=gt();if(at(t))return t;let n=ot();return at(n)?n:void 0}catch{return}}function mt(){try{let e=Re();if(e.username)return e.username;throw Error(`userInfo() returned empty username`)}catch{return process.env.USER||process.env.USERNAME||process.env.LOGNAME}}function ht(){try{let e=st();if(!Ve(e))return null;let t=He(e,`utf-8`);return JSON.parse(t)}catch{return null}}function gt(){try{let e=ct();if(!Ve(e))return null;let t=He(e,`utf-8`),n=JSON.parse(t)?.tokens?.id_token;if(!n)return null;let r=n.split(`.`);if(r.length!==3)return null;let i=Buffer.from(r[1],`base64url`).toString(`utf-8`);return JSON.parse(i).email||null}catch{return null}}const _t=()=>{if(!Ve(`/.dockerenv`))return null;try{let e=He(ze(Ie(),`.onyx`,`container-context.json`),`utf8`),t=JSON.parse(e);return t.container_id?t:null}catch{return null}},vt=e=>{let t=process.env.ONYX_DOCKER_CONTAINER_ID,n=t?null:_t(),r=t||n?.container_id;return r?{...e,containerRuntime:process.env.ONYX_CONTAINER_RUNTIME||void 0,deviceName:process.env.ONYX_HOST_DEVICE_NAME||n?.host_device_name||e.deviceName,dockerContainerId:r,dockerContainerName:process.env.ONYX_DOCKER_CONTAINER_NAME||n?.container_name||void 0,dockerImage:process.env.ONYX_DOCKER_IMAGE||n?.image||void 0,dockerImageId:process.env.ONYX_DOCKER_IMAGE_ID||n?.image_id||void 0,inDockerContainer:!0,systemSerialNumber:process.env.ONYX_HOST_SERIAL_NUMBER||n?.host_serial_number||e.systemSerialNumber}:e},yt=async()=>{let e=process.pid,t=process.ppid;try{let n=lt(),[r,i]=await Promise.all([ft(),dt(t)]),a=pt(),o=mt();return vt({clientAppName:nt||`unknown`,deviceName:n,email:a,gatewayVersion:ke.appVersion,parentProcessId:t,parentProcessName:i,processId:e,systemSerialNumber:r,username:o})}catch{return vt({clientAppName:nt||`unknown`,deviceName:`unknown-device`,email:void 0,gatewayVersion:ke.appVersion,parentProcessId:t,parentProcessName:`unknown`,processId:e,systemSerialNumber:void 0,username:void 0})}},bt=`[REDACTED]`,xt=new Set([`api_key`,`api-key`,`apikey`,`authorization`,`bearer`,`credential`,`credentials`,`header`,`headers`,`key`,`pass`,`passwd`,`password`,`pwd`,`secret`,`token`]);function St(e){let t=[],n=!1;for(let r of e){if(n){t.push(bt),n=!1;continue}if(r.startsWith(`-H`)&&r.length>2&&!r.startsWith(`--`)&&r[2]!==`=`){t.push(`-H`+bt);continue}let e=Ct(r);if(e!==null&&wt(e))if(r.includes(`=`)){let e=r.indexOf(`=`);t.push(r.slice(0,e+1)+bt)}else t.push(r),n=!0;else t.push(r)}return t}function Ct(e){if(!e.startsWith(`-`))return null;let t=e.replace(/^-{1,2}/,``),n=t.indexOf(`=`);return n>=0?t.slice(0,n):t}function wt(e){return e===`H`?!0:xt.has(e.toLowerCase())}const Tt=`onyx.security`;function Et(e){if(!e)return e;let t;try{t=new URL(e)}catch{return e}if(!t.host||t.pathname===``||t.pathname===`/`)return e;let n=t.hostname.toLowerCase().replace(/\.$/,``);if(n!==Tt&&!n.endsWith(`.${Tt}`))return e;let r=t.pathname.split(`/`),i=r.findIndex(e=>e.length>0);if(i===-1)return e;r[i]=`[REDACTED]`;let a=r.join(`/`);return`${t.protocol}//${t.host}${a}${t.search}${t.hash}`}function Dt(e){let t=Ge(JSON.stringify(e));return Buffer.from(t).toString(`base64url`)}var Ot=class{clientAppName;clientInfoBase64;sessionData;get scannerConfig(){return{apiKey:this.config.scanApiKey,enabled:this.config.scanEnabled,failOpen:this.config.scanFailOpen,headers:this.config.scanHeaders,timeoutMs:this.config.scanTimeoutMs,url:this.config.scanUrl}}config;constructor(e,t){this.config=e,this.sessionData=t,this.clientAppName=t.clientAppName||``,this.clientInfoBase64=this.getClientInfoBase64()}async evaluate(e){let t={action:`allow`};if(this.isScanEnabled())try{if(t=await this.scan({data:e.data,id:e.id,method:e.method,originalRequestId:e.originalRequestId,timestamp:e.timestamp,type:e.type}),L.info(`Scan result`,{action:t.action,id:e.id,method:e.method,originalRequestId:e.originalRequestId}),t.action===`block`)return L.warn(`Request blocked by security policy`),t}catch(t){if(L.error(`Scanning failed`,{error:t,method:e.method,requestType:e.type,scannerUrl:this.config.scanUrl}),!this.config.scanFailOpen)return L.warn(`Scanning service unavailable, blocking traffic (fail-closed)`),{action:`block`};L.warn(`Scanning service unavailable, allowing traffic (fail-open)`)}return t}isEnabled(){return this.isScanEnabled()}isScanEnabled(){return this.config.scanEnabled&&!!this.config.scanUrl}async scan(e){if(!this.isScanEnabled())return{action:`allow`};let t={data:e.data,id:e.id,metadata:this.sessionData,method:e.method,originalRequestId:e.originalRequestId,type:e.type};L.info(`Scanning traffic`,{id:e.id,method:e.method,originalRequestId:e.originalRequestId,type:e.type});let n=await this.sendScanRequest(t);return L.info(`Scan result`,{action:n.action,blockReason:n.block_reason,hasModifiedData:!!n.modified_data,id:e.id,originalRequestId:e.originalRequestId}),n}updateConfig(e){this.config={...this.config,...e}}getClientInfoBase64(){return Dt(this.sessionData)}async sendScanRequest(e){let t=new AbortController,n=setTimeout(()=>t.abort(),this.config.scanTimeoutMs);try{let n=`${this.config.scanUrl}/${this.config.scanApiKey}/mcp/${this.clientInfoBase64}`,r={data:e.data,id:e.id,metadata:e.metadata,method:e.method,sessionId:Oe,...e.originalRequestId&&{original_request_id:String(e.originalRequestId)},type:e.type},i=await fetch(n,{body:JSON.stringify(r),headers:{"Content-Type":`application/json`,...this.config.scanHeaders},method:`POST`,signal:t.signal});if(!i.ok)throw Error(`Sanitization service returned ${i.status}: ${i.statusText}`);let a=await i.json();if(!a.action||![`allow`,`block`,`modify`].includes(a.action))throw Error(`Invalid scan response format: action="${a.action}"`);return a}catch(e){throw e instanceof Error&&e.name===`AbortError`?Error(`Scan request timed out after ${this.config.scanTimeoutMs}ms`):e}finally{clearTimeout(n)}}};let kt=null;const At=async e=>{let t=await yt(),n=e.cliArgs.proxyType,r=n===`stdio`?{...e.cliArgs,args:St(e.cliArgs.args)}:e.cliArgs,i={...t,proxyType:n,remoteCliArgs:n===`remote`?r:void 0,stdioCliArgs:n===`stdio`?r:void 0},a=n===`remote`?{...i,remoteCliArgs:{...r,url:Et(r.url)}}:i;return L.setSessionData(a),kt=new Ot(e,i),kt},jt=()=>kt,Mt=e=>{if(e.maxTotalTimeoutMs<0)throw Error(`maxTotalTimeoutMs must be >= 0 (0 disables the cap), got ${e.maxTotalTimeoutMs}`);let t={resetTimeoutOnProgress:e.resetTimeoutOnProgress,timeout:e.timeoutMs};return e.maxTotalTimeoutMs>0&&(t.maxTotalTimeout=e.maxTotalTimeoutMs),t},Nt=new class{counts=new Map;lastLogTime=Date.now();logIntervalMs=6e4;increment(e){this.counts.set(e,(this.counts.get(e)||0)+1),this.maybeLog()}logAndReset(){if(this.counts.size===0)return;let e=(Array.from(this.counts.values()).reduce((e,t)=>e+t,0));L.info(`Requests intercepted`,{byMethod:Object.fromEntries(this.counts),eventType:`mcp_requests_intercepted`,totalCount:e}),this.counts.clear(),this.lastLogTime=Date.now()}maybeLog(){Date.now()-this.lastLogTime>=this.logIntervalMs&&this.logAndReset()}},Pt=()=>{Nt.logAndReset()},Ft=e=>e.length>1&&e[1]&&typeof e[1]==`object`&&`requestId`in e[1]?e[1].requestId:void 0,R=(e,t,n,r)=>async(...i)=>{Nt.increment(e);let a=jt(),o=e,s=i[0],c=Fe(),l=Ft(i)?.toString();s&&typeof s==`object`&&`method`in s&&typeof s.method==`string`&&(o=s.method);let u=async(e,t,n)=>{try{if(!a?.isEnabled()&&!a?.isScanEnabled())return;let r;try{r=await a.evaluate({data:t,id:c,method:o,originalRequestId:l,timestamp:new Date().toISOString(),type:e})}catch(t){if(L.error(`${e} evaluation failed, applying fail-safe`,{error:t}),a?.isScanEnabled()&&!a.scannerConfig?.failOpen)throw Error(`Security scanning service unavailable`);return}if(L.info(`${e} scan result`,{action:r.action,id:c,method:o,...e===`request`&&{originalRequestId:l}}),r.action===`block`||r.action===`modify`){let t=r.action===`block`?`blocked`:`modified`,i=r.action===`block`&&e===`request`?`warn`:`log`;if(r.modified_data){if(r.action===`block`){let n=`${e} ${t} by security policy${e===`request`?`, returning error response`:``}`;return i===`warn`?L.warn(n):L.info(n),r.modified_data}if(n){let a=`${e} ${t} by security policy`;i===`warn`?L.warn(a):L.info(a),n(r.modified_data);return}return r.modified_data}L.warn(`${r.action} action without modified_data, allowing original ${e}`)}return}catch(t){if(L.error(`Unexpected error during ${e} processing`,{error:t}),e===`request`&&t instanceof Error&&t.message===`Security scanning service unavailable`)throw t;return}},d;try{d=await u(`request`,s,e=>{i[0]=e})}catch(n){if(n instanceof Error&&n.message===`Security scanning service unavailable`)throw L.error(`Security scanning unavailable (fail-closed)`,{error:n.message,handlerName:e,operation:t}),n;L.error(`Unexpected error during request processing, continuing`,{error:n,handlerName:e,operation:t})}if(d!==void 0)return d;if(r&&!await r.isAllowed()){let n=r.getBlockReason();throw L.warn(`MCP server blocked by access control`,{handlerName:e,operation:t,reason:n}),new $e(n,`policy_block`)}try{let e=await n(...i);try{if(e){let t=await u(`response`,e);if(t!==void 0)return t}}catch(e){L.error(`Error during response processing, returning original result`,{error:e})}return e}catch(n){if(n instanceof $e)throw L.info(`Request blocked by access control`,{error:n.message,handlerName:e,operation:t,reason:n.reason}),n;try{await u(`error`,{error:n instanceof Error?n.message:String(n),stack:n instanceof Error?n.stack:void 0})}catch(e){L.warn(`Failed to evaluate error`,{evalError:e})}throw L.error(`Handler error in ${e}`,{argsCount:i.length,errorMessage:n instanceof Error?n.message:String(n),operation:t}),n}},It=async({authorizer:e,client:t,forwarding:n=ke.toolCall,server:i,serverCapabilities:a})=>{let o=Mt(n);a?.logging&&(i.setNotificationHandler(le,R(`notifications/message`,`server-to-client`,async e=>t.notification(e),e)),t.setNotificationHandler(le,R(`notifications/message`,`client-to-server`,async e=>i.notification(e),e))),a?.prompts&&(i.setRequestHandler(y,R(`prompts/get`,`get`,async e=>t.getPrompt(e.params,o),e)),i.setRequestHandler(A,R(`prompts/list`,`list`,async e=>t.listPrompts(e.params,o),e))),a?.resources&&(i.setRequestHandler(j,R(`resources/list`,`list`,async e=>t.listResources(e.params,o),e)),i.setRequestHandler(te,R(`resources/templates/list`,`list`,async e=>t.listResourceTemplates(e.params,o),e)),i.setRequestHandler(pe,R(`resources/read`,`read`,async e=>t.readResource(e.params,o),e)),a?.resources.subscribe&&(i.setNotificationHandler(ge,R(`notifications/resources/updated`,`notify`,async e=>t.notification(e),e)),i.setRequestHandler(ye,R(`resources/subscribe`,`subscribe`,async e=>t.subscribeResource(e.params,o),e)),i.setRequestHandler(Se,R(`resources/unsubscribe`,`unsubscribe`,async e=>t.unsubscribeResource(e.params,o),e)))),a?.tools&&(i.setRequestHandler(r,R(`tools/call`,`call`,async(e,n)=>{let r=n._meta?.progressToken,i=r===void 0?void 0:e=>{n.sendNotification({method:`notifications/progress`,params:{...e,progressToken:r}}).catch(e=>{L.warn(`Failed to forward progress notification to client`,{error:e})})};return t.callTool(e.params,void 0,{...o,onprogress:i})},e)),i.setRequestHandler(oe,R(`tools/list`,`list`,async e=>t.listTools(e.params,o),e))),a?.completions&&i.setRequestHandler(c,R(`completion/complete`,`complete`,async e=>t.complete(e.params,o),e))};var Lt=e(((exports,t)=>{t.exports=o,t.exports.format=s,t.exports.parse=c;var n=/\B(?=(\d{3})+(?!\d))/g,r=/(?:\.0*|(\.[^0]+)0+)$/,i={b:1,kb:1024,mb:1<<20,gb:1<<30,tb:1024**4,pb:1024**5},a=/^((-|\+)?(\d+(?:\.\d+)?)) *(kb|mb|gb|tb|pb)$/i;function o(e,t){return typeof e==`string`?c(e):typeof e==`number`?s(e,t):null}function s(e,t){if(!Number.isFinite(e))return null;var a=Math.abs(e),o=t&&t.thousandsSeparator||``,s=t&&t.unitSeparator||``,c=t&&t.decimalPlaces!==void 0?t.decimalPlaces:2,l=!!(t&&t.fixedDecimals),u=t&&t.unit||``;(!u||!i[u.toLowerCase()])&&(u=a>=i.pb?`PB`:a>=i.tb?`TB`:a>=i.gb?`GB`:a>=i.mb?`MB`:a>=i.kb?`KB`:`B`);var d=(e/i[u.toLowerCase()]).toFixed(c);return l||(d=d.replace(r,`$1`)),o&&(d=d.split(`.`).map(function(e,t){return t===0?e.replace(n,o):e}).join(`.`)),d+s+u}function c(e){if(typeof e==`number`&&!isNaN(e))return e;if(typeof e!=`string`)return null;var t=a.exec(e),n,r=`b`;return t?(n=parseFloat(t[1]),r=t[4].toLowerCase()):(n=parseInt(e,10),r=`b`),isNaN(n)?null:Math.floor(i[r]*n)}})),Rt=e(((exports,n)=>{
3
3
  /*!
4
4
  * depd
@@ -28,4 +28,4 @@ return fn.apply(this, arguments)
28
28
  deps: ${r}}`};let i={keyword:`dependencies`,type:`object`,schemaType:`object`,error:exports.error,code(e){let[t,n]=a(e);o(e,t),s(e,n)}};function a({schema:e}){let t={},n={};for(let r in e){if(r===`__proto__`)continue;let i=Array.isArray(e[r])?t:n;i[r]=e[r]}return[t,n]}function o(e,n=e.schema){let{gen:i,data:a,it:o}=e;if(Object.keys(n).length===0)return;let s=i.let(`missing`);for(let c in n){let l=n[c];if(l.length===0)continue;let u=(0,r.propertyInData)(i,a,c,o.opts.ownProperties);e.setParams({property:c,depsCount:l.length,deps:l.join(`, `)}),o.allErrors?i.if(u,()=>{for(let t of l)(0,r.checkReportMissingProp)(e,t)}):(i.if((0,t._)`${u} && (${(0,r.checkMissingProp)(e,l,s)})`),(0,r.reportMissingProp)(e,s),i.else())}}exports.validatePropertyDeps=o;function s(e,t=e.schema){let{gen:i,data:a,keyword:o,it:s}=e,c=i.name(`valid`);for(let l in t){if((0,n.alwaysValidSchema)(s,t[l]))continue;i.if((0,r.propertyInData)(i,a,l,s.opts.ownProperties),()=>{let t=e.subschema({keyword:o,schemaProp:l},c);e.mergeValidEvaluated(t,c)},()=>i.var(c,!0)),e.ok(c)}}exports.validateSchemaDeps=s,exports.default=i})),ri=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0});let t=X(),n=Z();exports.default={keyword:`propertyNames`,type:`object`,schemaType:[`object`,`boolean`],error:{message:`property name must be valid`,params:({params:e})=>(0,t._)`{propertyName: ${e.propertyName}}`},code(e){let{gen:r,schema:i,data:a,it:o}=e;if((0,n.alwaysValidSchema)(o,i))return;let s=r.name(`valid`);r.forIn(`key`,a,n=>{e.setParams({propertyName:n}),e.subschema({keyword:`propertyNames`,data:n,dataTypes:[`string`],propertyName:n,compositeRule:!0},s),r.if((0,t.not)(s),()=>{e.error(!0),o.allErrors||r.break()})}),e.ok(s)}}})),ii=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0});let t=$(),n=X(),r=Q(),i=Z();exports.default={keyword:`additionalProperties`,type:[`object`],schemaType:[`boolean`,`object`],allowUndefined:!0,trackErrors:!0,error:{message:`must NOT have additional properties`,params:({params:e})=>(0,n._)`{additionalProperty: ${e.additionalProperty}}`},code(e){let{gen:a,schema:o,parentSchema:s,data:c,errsCount:l,it:u}=e;if(!l)throw Error(`ajv implementation error`);let{allErrors:d,opts:f}=u;if(u.props=!0,f.removeAdditional!==`all`&&(0,i.alwaysValidSchema)(u,o))return;let p=(0,t.allSchemaProperties)(s.properties),m=(0,t.allSchemaProperties)(s.patternProperties);h(),e.ok((0,n._)`${l} === ${r.default.errors}`);function h(){a.forIn(`key`,c,e=>{!p.length&&!m.length?v(e):a.if(g(e),()=>v(e))})}function g(r){let o;if(p.length>8){let e=(0,i.schemaRefOrVal)(u,s.properties,`properties`);o=(0,t.isOwnProperty)(a,e,r)}else o=p.length?(0,n.or)(...p.map(e=>(0,n._)`${r} === ${e}`)):n.nil;return m.length&&(o=(0,n.or)(o,...m.map(i=>(0,n._)`${(0,t.usePattern)(e,i)}.test(${r})`))),(0,n.not)(o)}function _(e){a.code((0,n._)`delete ${c}[${e}]`)}function v(t){if(f.removeAdditional===`all`||f.removeAdditional&&o===!1){_(t);return}if(o===!1){e.setParams({additionalProperty:t}),e.error(),d||a.break();return}if(typeof o==`object`&&!(0,i.alwaysValidSchema)(u,o)){let r=a.name(`valid`);f.removeAdditional===`failing`?(y(t,r,!1),a.if((0,n.not)(r),()=>{e.reset(),_(t)})):(y(t,r),d||a.if((0,n.not)(r),()=>a.break()))}}function y(t,n,r){let a={keyword:`additionalProperties`,dataProp:t,dataPropType:i.Type.Str};r===!1&&Object.assign(a,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(a,n)}}}})),ai=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0});let t=Tr(),n=$(),r=Z(),i=ii();exports.default={keyword:`properties`,type:`object`,schemaType:`object`,code(e){let{gen:a,schema:o,parentSchema:s,data:c,it:l}=e;l.opts.removeAdditional===`all`&&s.additionalProperties===void 0&&i.default.code(new t.KeywordCxt(l,i.default,`additionalProperties`));let u=(0,n.allSchemaProperties)(o);for(let e of u)l.definedProperties.add(e);l.opts.unevaluated&&u.length&&l.props!==!0&&(l.props=r.mergeEvaluated.props(a,(0,r.toHash)(u),l.props));let d=u.filter(e=>!(0,r.alwaysValidSchema)(l,o[e]));if(d.length===0)return;let f=a.name(`valid`);for(let t of d)p(t)?m(t):(a.if((0,n.propertyInData)(a,c,t,l.opts.ownProperties)),m(t),l.allErrors||a.else().var(f,!0),a.endIf()),e.it.definedProperties.add(t),e.ok(f);function p(e){return l.opts.useDefaults&&!l.compositeRule&&o[e].default!==void 0}function m(t){e.subschema({keyword:`properties`,schemaProp:t,dataProp:t},f)}}}})),oi=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0});let t=$(),n=X(),r=Z(),i=Z();exports.default={keyword:`patternProperties`,type:`object`,schemaType:`object`,code(e){let{gen:a,schema:o,data:s,parentSchema:c,it:l}=e,{opts:u}=l,d=(0,t.allSchemaProperties)(o),f=d.filter(e=>(0,r.alwaysValidSchema)(l,o[e]));if(d.length===0||f.length===d.length&&(!l.opts.unevaluated||l.props===!0))return;let p=u.strictSchema&&!u.allowMatchingProperties&&c.properties,m=a.name(`valid`);l.props!==!0&&!(l.props instanceof n.Name)&&(l.props=(0,i.evaluatedPropsToName)(a,l.props));let{props:h}=l;g();function g(){for(let e of d)p&&_(e),l.allErrors?v(e):(a.var(m,!0),v(e),a.if(m))}function _(e){for(let t in p)new RegExp(e).test(t)&&(0,r.checkStrictMode)(l,`property ${t} matches pattern ${e} (use allowMatchingProperties)`)}function v(r){a.forIn(`key`,s,o=>{a.if((0,n._)`${(0,t.usePattern)(e,r)}.test(${o})`,()=>{let t=f.includes(r);t||e.subschema({keyword:`patternProperties`,schemaProp:r,dataProp:o,dataPropType:i.Type.Str},m),l.opts.unevaluated&&h!==!0?a.assign((0,n._)`${h}[${o}]`,!0):!t&&!l.allErrors&&a.if((0,n.not)(m),()=>a.break())})})}}}})),si=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0});let t=Z();exports.default={keyword:`not`,schemaType:[`object`,`boolean`],trackErrors:!0,code(e){let{gen:n,schema:r,it:i}=e;if((0,t.alwaysValidSchema)(i,r)){e.fail();return}let a=n.name(`valid`);e.subschema({keyword:`not`,compositeRule:!0,createErrors:!1,allErrors:!1},a),e.failResult(a,()=>e.reset(),()=>e.error())},error:{message:`must NOT be valid`}}})),ci=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0}),exports.default={keyword:`anyOf`,schemaType:`array`,trackErrors:!0,code:$().validateUnion,error:{message:`must match a schema in anyOf`}}})),li=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0});let t=X(),n=Z();exports.default={keyword:`oneOf`,schemaType:`array`,trackErrors:!0,error:{message:`must match exactly one schema in oneOf`,params:({params:e})=>(0,t._)`{passingSchemas: ${e.passing}}`},code(e){let{gen:r,schema:i,parentSchema:a,it:o}=e;if(!Array.isArray(i))throw Error(`ajv implementation error`);if(o.opts.discriminator&&a.discriminator)return;let s=i,c=r.let(`valid`,!1),l=r.let(`passing`,null),u=r.name(`_valid`);e.setParams({passing:l}),r.block(d),e.result(c,()=>e.reset(),()=>e.error(!0));function d(){s.forEach((i,a)=>{let s;(0,n.alwaysValidSchema)(o,i)?r.var(u,!0):s=e.subschema({keyword:`oneOf`,schemaProp:a,compositeRule:!0},u),a>0&&r.if((0,t._)`${u} && ${c}`).assign(c,!1).assign(l,(0,t._)`[${l}, ${a}]`).else(),r.if(u,()=>{r.assign(c,!0),r.assign(l,a),s&&e.mergeEvaluated(s,t.Name)})})}}}})),ui=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0});let t=Z();exports.default={keyword:`allOf`,schemaType:`array`,code(e){let{gen:n,schema:r,it:i}=e;if(!Array.isArray(r))throw Error(`ajv implementation error`);let a=n.name(`valid`);r.forEach((n,r)=>{if((0,t.alwaysValidSchema)(i,n))return;let o=e.subschema({keyword:`allOf`,schemaProp:r},a);e.ok(a),e.mergeEvaluated(o)})}}})),di=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0});let t=X(),n=Z(),r={keyword:`if`,schemaType:[`object`,`boolean`],trackErrors:!0,error:{message:({params:e})=>(0,t.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,t._)`{failingKeyword: ${e.ifClause}}`},code(e){let{gen:r,parentSchema:a,it:o}=e;a.then===void 0&&a.else===void 0&&(0,n.checkStrictMode)(o,`"if" without "then" and "else" is ignored`);let s=i(o,`then`),c=i(o,`else`);if(!s&&!c)return;let l=r.let(`valid`,!0),u=r.name(`_valid`);if(d(),e.reset(),s&&c){let t=r.let(`ifClause`);e.setParams({ifClause:t}),r.if(u,f(`then`,t),f(`else`,t))}else s?r.if(u,f(`then`)):r.if((0,t.not)(u),f(`else`));e.pass(l,()=>e.error(!0));function d(){let t=e.subschema({keyword:`if`,compositeRule:!0,createErrors:!1,allErrors:!1},u);e.mergeEvaluated(t)}function f(n,i){return()=>{let a=e.subschema({keyword:n},u);r.assign(l,u),e.mergeValidEvaluated(a,l),i?r.assign(i,(0,t._)`${n}`):e.setParams({ifClause:n})}}}};function i(e,t){let r=e.schema[t];return r!==void 0&&!(0,n.alwaysValidSchema)(e,r)}exports.default=r})),fi=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0});let t=Z();exports.default={keyword:[`then`,`else`],schemaType:[`object`,`boolean`],code({keyword:e,parentSchema:n,it:r}){n.if===void 0&&(0,t.checkStrictMode)(r,`"${e}" without "if" is ignored`)}}})),pi=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0});let t=Zr(),n=$r(),r=Qr(),i=ei(),a=ti(),o=ni(),s=ri(),c=ii(),l=ai(),u=oi(),d=si(),f=ci(),p=li(),m=ui(),h=di(),g=fi();function _(e=!1){let _=[d.default,f.default,p.default,m.default,h.default,g.default,s.default,c.default,o.default,l.default,u.default];return e?_.push(n.default,i.default):_.push(t.default,r.default),_.push(a.default),_}exports.default=_})),mi=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0});let t=X();exports.default={keyword:`format`,type:[`number`,`string`],schemaType:`string`,$data:!0,error:{message:({schemaCode:e})=>(0,t.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,t._)`{format: ${e}}`},code(e,n){let{gen:r,data:i,$data:a,schema:o,schemaCode:s,it:c}=e,{opts:l,errSchemaPath:u,schemaEnv:d,self:f}=c;if(!l.validateFormats)return;a?p():m();function p(){let a=r.scopeValue(`formats`,{ref:f.formats,code:l.code.formats}),o=r.const(`fDef`,(0,t._)`${a}[${s}]`),c=r.let(`fType`),u=r.let(`format`);r.if((0,t._)`typeof ${o} == "object" && !(${o} instanceof RegExp)`,()=>r.assign(c,(0,t._)`${o}.type || "string"`).assign(u,(0,t._)`${o}.validate`),()=>r.assign(c,(0,t._)`"string"`).assign(u,o)),e.fail$data((0,t.or)(p(),m()));function p(){return l.strictSchema===!1?t.nil:(0,t._)`${s} && !${u}`}function m(){let e=d.$async?(0,t._)`(${o}.async ? await ${u}(${i}) : ${u}(${i}))`:(0,t._)`${u}(${i})`,r=(0,t._)`(typeof ${u} == "function" ? ${e} : ${u}.test(${i}))`;return(0,t._)`${u} && ${u} !== true && ${c} === ${n} && !${r}`}}function m(){let a=f.formats[o];if(!a){m();return}if(a===!0)return;let[s,c,p]=h(a);s===n&&e.pass(g());function m(){if(l.strictSchema===!1){f.logger.warn(e());return}throw Error(e());function e(){return`unknown format "${o}" ignored in schema at path "${u}"`}}function h(e){let n=e instanceof RegExp?(0,t.regexpCode)(e):l.code.formats?(0,t._)`${l.code.formats}${(0,t.getProperty)(o)}`:void 0,i=r.scopeValue(`formats`,{key:o,ref:e,code:n});return typeof e==`object`&&!(e instanceof RegExp)?[e.type||`string`,e.validate,(0,t._)`${i}.validate`]:[`string`,e,i]}function g(){if(typeof a==`object`&&!(a instanceof RegExp)&&a.async){if(!d.$async)throw Error(`async format in sync schema`);return(0,t._)`await ${p}(${i})`}return typeof c==`function`?(0,t._)`${p}(${i})`:(0,t._)`${p}.test(${i})`}}}}})),hi=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0}),exports.default=[mi().default]})),gi=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0}),exports.metadataVocabulary=[`title`,`description`,`default`,`deprecated`,`readOnly`,`writeOnly`,`examples`],exports.contentVocabulary=[`contentMediaType`,`contentEncoding`,`contentSchema`]})),_i=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0});let t=Lr(),n=Xr(),r=pi(),i=hi(),a=gi();exports.default=[t.default,n.default,(0,r.default)(),i.default,a.metadataVocabulary,a.contentVocabulary]})),vi=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0});var t;(function(e){e.Tag=`tag`,e.Mapping=`mapping`})(t||(exports.DiscrError=t={}))})),yi=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0});let t=X(),n=vi(),r=Or(),i=Dr(),a=Z();exports.default={keyword:`discriminator`,type:`object`,schemaType:`object`,error:{message:({params:{discrError:e,tagName:t}})=>e===n.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:n,tagName:r}})=>(0,t._)`{error: ${e}, tag: ${r}, tagValue: ${n}}`},code(e){let{gen:o,data:s,schema:c,parentSchema:l,it:u}=e,{oneOf:d}=l;if(!u.opts.discriminator)throw Error(`discriminator: requires discriminator option`);let f=c.propertyName;if(typeof f!=`string`)throw Error(`discriminator: requires propertyName`);if(c.mapping)throw Error(`discriminator: mapping is not supported`);if(!d)throw Error(`discriminator: requires oneOf keyword`);let p=o.let(`valid`,!1),m=o.const(`tag`,(0,t._)`${s}${(0,t.getProperty)(f)}`);o.if((0,t._)`typeof ${m} == "string"`,()=>h(),()=>e.error(!1,{discrError:n.DiscrError.Tag,tag:m,tagName:f})),e.ok(p);function h(){let r=_();for(let e in o.if(!1),r)o.elseIf((0,t._)`${m} === ${e}`),o.assign(p,g(r[e]));o.else(),e.error(!1,{discrError:n.DiscrError.Mapping,tag:m,tagName:f}),o.endIf()}function g(n){let r=o.name(`valid`),i=e.subschema({keyword:`oneOf`,schemaProp:n},r);return e.mergeEvaluated(i,t.Name),r}function _(){let e={},t=o(l),n=!0;for(let e=0;e<d.length;e++){let c=d[e];if(c?.$ref&&!(0,a.schemaHasRulesButRef)(c,u.self.RULES)){let e=c.$ref;if(c=r.resolveRef.call(u.self,u.schemaEnv.root,u.baseId,e),c instanceof r.SchemaEnv&&(c=c.schema),c===void 0)throw new i.default(u.opts.uriResolver,u.baseId,e)}let l=c?.properties?.[f];if(typeof l!=`object`)throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${f}"`);n&&=t||o(c),s(l,e)}if(!n)throw Error(`discriminator: "${f}" must be required`);return e;function o({required:e}){return Array.isArray(e)&&e.includes(f)}function s(e,t){if(e.const)c(e.const,t);else if(e.enum)for(let n of e.enum)c(n,t);else throw Error(`discriminator: "properties/${f}" must have "const" or "enum"`)}function c(t,n){if(typeof t!=`string`||t in e)throw Error(`discriminator: "${f}" values must be unique strings`);e[t]=n}}}}})),bi=e(((exports,t)=>{t.exports={$schema:`http://json-schema.org/draft-07/schema#`,$id:`http://json-schema.org/draft-07/schema#`,title:`Core schema meta-schema`,definitions:{schemaArray:{type:`array`,minItems:1,items:{$ref:`#`}},nonNegativeInteger:{type:`integer`,minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:`#/definitions/nonNegativeInteger`},{default:0}]},simpleTypes:{enum:[`array`,`boolean`,`integer`,`null`,`number`,`object`,`string`]},stringArray:{type:`array`,items:{type:`string`},uniqueItems:!0,default:[]}},type:[`object`,`boolean`],properties:{$id:{type:`string`,format:`uri-reference`},$schema:{type:`string`,format:`uri`},$ref:{type:`string`,format:`uri-reference`},$comment:{type:`string`},title:{type:`string`},description:{type:`string`},default:!0,readOnly:{type:`boolean`,default:!1},examples:{type:`array`,items:!0},multipleOf:{type:`number`,exclusiveMinimum:0},maximum:{type:`number`},exclusiveMaximum:{type:`number`},minimum:{type:`number`},exclusiveMinimum:{type:`number`},maxLength:{$ref:`#/definitions/nonNegativeInteger`},minLength:{$ref:`#/definitions/nonNegativeIntegerDefault0`},pattern:{type:`string`,format:`regex`},additionalItems:{$ref:`#`},items:{anyOf:[{$ref:`#`},{$ref:`#/definitions/schemaArray`}],default:!0},maxItems:{$ref:`#/definitions/nonNegativeInteger`},minItems:{$ref:`#/definitions/nonNegativeIntegerDefault0`},uniqueItems:{type:`boolean`,default:!1},contains:{$ref:`#`},maxProperties:{$ref:`#/definitions/nonNegativeInteger`},minProperties:{$ref:`#/definitions/nonNegativeIntegerDefault0`},required:{$ref:`#/definitions/stringArray`},additionalProperties:{$ref:`#`},definitions:{type:`object`,additionalProperties:{$ref:`#`},default:{}},properties:{type:`object`,additionalProperties:{$ref:`#`},default:{}},patternProperties:{type:`object`,additionalProperties:{$ref:`#`},propertyNames:{format:`regex`},default:{}},dependencies:{type:`object`,additionalProperties:{anyOf:[{$ref:`#`},{$ref:`#/definitions/stringArray`}]}},propertyNames:{$ref:`#`},const:!0,enum:{type:`array`,items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:`#/definitions/simpleTypes`},{type:`array`,items:{$ref:`#/definitions/simpleTypes`},minItems:1,uniqueItems:!0}]},format:{type:`string`},contentMediaType:{type:`string`},contentEncoding:{type:`string`},if:{$ref:`#`},then:{$ref:`#`},else:{$ref:`#`},allOf:{$ref:`#/definitions/schemaArray`},anyOf:{$ref:`#/definitions/schemaArray`},oneOf:{$ref:`#/definitions/schemaArray`},not:{$ref:`#`}},default:!0}})),xi=e(((exports,t)=>{Object.defineProperty(exports,`__esModule`,{value:!0}),exports.MissingRefError=exports.ValidationError=exports.CodeGen=exports.Name=exports.nil=exports.stringify=exports.str=exports._=exports.KeywordCxt=exports.Ajv=void 0;let n=Pr(),r=_i(),i=yi(),a=bi(),o=[`/properties`],s=`http://json-schema.org/draft-07/schema`;var c=class extends n.default{_addVocabularies(){super._addVocabularies(),r.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(i.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(a,o):a;this.addMetaSchema(e,s,!1),this.refs[`http://json-schema.org/schema`]=s}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(s)?s:void 0)}};exports.Ajv=c,t.exports=exports=c,t.exports.Ajv=c,Object.defineProperty(exports,`__esModule`,{value:!0}),exports.default=c;var l=Tr();Object.defineProperty(exports,`KeywordCxt`,{enumerable:!0,get:function(){return l.KeywordCxt}});var u=X();Object.defineProperty(exports,`_`,{enumerable:!0,get:function(){return u._}}),Object.defineProperty(exports,`str`,{enumerable:!0,get:function(){return u.str}}),Object.defineProperty(exports,`stringify`,{enumerable:!0,get:function(){return u.stringify}}),Object.defineProperty(exports,`nil`,{enumerable:!0,get:function(){return u.nil}}),Object.defineProperty(exports,`Name`,{enumerable:!0,get:function(){return u.Name}}),Object.defineProperty(exports,`CodeGen`,{enumerable:!0,get:function(){return u.CodeGen}});var d=Er();Object.defineProperty(exports,`ValidationError`,{enumerable:!0,get:function(){return d.default}});var f=Dr();Object.defineProperty(exports,`MissingRefError`,{enumerable:!0,get:function(){return f.default}})})),Si=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0}),exports.formatNames=exports.fastFormats=exports.fullFormats=void 0;function t(e,t){return{validate:e,compare:t}}exports.fullFormats={date:t(a,o),time:t(c(!0),l),"date-time":t(f(!0),p),"iso-time":t(c(),u),"iso-date-time":t(f(),m),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:_,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:E,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:y,int32:{type:`number`,validate:S},int64:{type:`number`,validate:C},float:{type:`number`,validate:w},double:{type:`number`,validate:w},password:!0,binary:!0},exports.fastFormats={...exports.fullFormats,date:t(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,o),time:t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,l),"date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,p),"iso-time":t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,u),"iso-date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,m),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i},exports.formatNames=Object.keys(exports.fullFormats);function n(e){return e%4==0&&(e%100!=0||e%400==0)}let r=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,i=[0,31,28,31,30,31,30,31,31,30,31,30,31];function a(e){let t=r.exec(e);if(!t)return!1;let a=+t[1],o=+t[2],s=+t[3];return o>=1&&o<=12&&s>=1&&s<=(o===2&&n(a)?29:i[o])}function o(e,t){if(e&&t)return e>t?1:e<t?-1:0}let s=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function c(e){return function(t){let n=s.exec(t);if(!n)return!1;let r=+n[1],i=+n[2],a=+n[3],o=n[4],c=n[5]===`-`?-1:1,l=+(n[6]||0),u=+(n[7]||0);if(l>23||u>59||e&&!o)return!1;if(r<=23&&i<=59&&a<60)return!0;let d=i-u*c,f=r-l*c-(d<0?1:0);return(f===23||f===-1)&&(d===59||d===-1)&&a<61}}function l(e,t){if(!(e&&t))return;let n=new Date(`2020-01-01T`+e).valueOf(),r=new Date(`2020-01-01T`+t).valueOf();if(n&&r)return n-r}function u(e,t){if(!(e&&t))return;let n=s.exec(e),r=s.exec(t);if(n&&r)return e=n[1]+n[2]+n[3],t=r[1]+r[2]+r[3],e>t?1:e<t?-1:0}let d=/t|\s/i;function f(e){let t=c(e);return function(e){let n=e.split(d);return n.length===2&&a(n[0])&&t(n[1])}}function p(e,t){if(!(e&&t))return;let n=new Date(e).valueOf(),r=new Date(t).valueOf();if(n&&r)return n-r}function m(e,t){if(!(e&&t))return;let[n,r]=e.split(d),[i,a]=t.split(d),s=o(n,i);if(s!==void 0)return s||l(r,a)}let h=/\/|:/,g=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function _(e){return h.test(e)&&g.test(e)}let v=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function y(e){return v.lastIndex=0,v.test(e)}let b=-(2**31),x=2**31-1;function S(e){return Number.isInteger(e)&&e<=x&&e>=b}function C(e){return Number.isInteger(e)}function w(){return!0}let T=/[^\\]\\Z/;function E(e){if(T.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}})),Ci=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0}),exports.formatLimitDefinition=void 0;let t=xi(),n=X(),r=n.operators,i={formatMaximum:{okStr:`<=`,ok:r.LTE,fail:r.GT},formatMinimum:{okStr:`>=`,ok:r.GTE,fail:r.LT},formatExclusiveMaximum:{okStr:`<`,ok:r.LT,fail:r.GTE},formatExclusiveMinimum:{okStr:`>`,ok:r.GT,fail:r.LTE}};exports.formatLimitDefinition={keyword:Object.keys(i),type:`string`,schemaType:`string`,$data:!0,error:{message:({keyword:e,schemaCode:t})=>(0,n.str)`should be ${i[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,n._)`{comparison: ${i[e].okStr}, limit: ${t}}`},code(e){let{gen:r,data:a,schemaCode:o,keyword:s,it:c}=e,{opts:l,self:u}=c;if(!l.validateFormats)return;let d=new t.KeywordCxt(c,u.RULES.all.format.definition,`format`);d.$data?f():p();function f(){let t=r.scopeValue(`formats`,{ref:u.formats,code:l.code.formats}),i=r.const(`fmt`,(0,n._)`${t}[${d.schemaCode}]`);e.fail$data((0,n.or)((0,n._)`typeof ${i} != "object"`,(0,n._)`${i} instanceof RegExp`,(0,n._)`typeof ${i}.compare != "function"`,m(i)))}function p(){let t=d.schema,i=u.formats[t];if(!i||i===!0)return;if(typeof i!=`object`||i instanceof RegExp||typeof i.compare!=`function`)throw Error(`"${s}": format "${t}" does not define "compare" function`);let a=r.scopeValue(`formats`,{key:t,ref:i,code:l.code.formats?(0,n._)`${l.code.formats}${(0,n.getProperty)(t)}`:void 0});e.fail$data(m(a))}function m(e){return(0,n._)`${e}.compare(${a}, ${o}) ${i[s].fail} 0`}},dependencies:[`format`]},exports.default=t=>(t.addKeyword(exports.formatLimitDefinition),t)})),wi=e(((exports,t)=>{Object.defineProperty(exports,`__esModule`,{value:!0});let n=Si(),r=Ci(),i=X(),a=new i.Name(`fullFormats`),o=new i.Name(`fastFormats`),s=(e,t={keywords:!0})=>{if(Array.isArray(t))return c(e,t,n.fullFormats,a),e;let[i,s]=t.mode===`fast`?[n.fastFormats,o]:[n.fullFormats,a],l=t.formats||n.formatNames;return c(e,l,i,s),t.keywords&&(0,r.default)(e),e};s.get=(e,t=`full`)=>{let r=(t===`fast`?n.fastFormats:n.fullFormats)[e];if(!r)throw Error(`Unknown format "${e}"`);return r};function c(e,t,n,r){var a;(a=e.opts.code).formats??(a.formats=(0,i._)`require("ajv-formats/dist/formats").${r}`);for(let r of t)e.addFormat(r,n[r])}t.exports=exports=s,Object.defineProperty(exports,`__esModule`,{value:!0}),exports.default=s})),Ti=n(xi(),1),Ei=n(wi(),1);function Di(){let e=new Ti.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,Ei.default)(e),e}var Oi=class{constructor(e){this._ajv=e??Di()}getValidator(e){let t=`$id`in e&&typeof e.$id==`string`?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return e=>t(e)?{valid:!0,data:e,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(t.errors)}}},ki=class{constructor(e){this._client=e}async*callToolStream(e,t=i,n){let r=this._client,a={...n,task:n?.task??(r.isToolTask(e.name)?{}:void 0)},o=r.requestStream({method:`tools/call`,params:e},t,a),s=r.getToolOutputValidator(e.name);for await(let t of o){if(t.type===`result`&&s){let n=t.result;if(!n.structuredContent&&!n.isError){yield{type:`error`,error:new N(v.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`)};return}if(n.structuredContent)try{let e=s(n.structuredContent);if(!e.valid){yield{type:`error`,error:new N(v.InvalidParams,`Structured content does not match the tool's output schema: ${e.errorMessage}`)};return}}catch(e){if(e instanceof N){yield{type:`error`,error:e};return}yield{type:`error`,error:new N(v.InvalidParams,`Failed to validate structured content: ${e instanceof Error?e.message:String(e)}`)};return}}yield t}}async getTask(e,t){return this._client.getTask({taskId:e},t)}async getTaskResult(e,t,n){return this._client.getTaskResult({taskId:e},t,n)}async listTasks(e,t){return this._client.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._client.cancelTask({taskId:e},t)}requestStream(e,t,n){return this._client.requestStream(e,t,n)}};function Ai(e,t,n){if(!e)throw Error(`${n} does not support task creation (required for ${t})`);switch(t){case`tools/call`:if(!e.tools?.call)throw Error(`${n} does not support task creation for tools/call (required for ${t})`);break;default:break}}function ji(e,t,n){if(!e)throw Error(`${n} does not support task creation (required for ${t})`);switch(t){case`sampling/createMessage`:if(!e.sampling?.createMessage)throw Error(`${n} does not support task creation for sampling/createMessage (required for ${t})`);break;case`elicitation/create`:if(!e.elicitation?.create)throw Error(`${n} does not support task creation for elicitation/create (required for ${t})`);break;default:break}}function Mi(e,t){if(!(!e||typeof t!=`object`||!t)){if(e.type===`object`&&e.properties&&typeof e.properties==`object`){let n=t,r=e.properties;for(let e of Object.keys(r)){let t=r[e];n[e]===void 0&&Object.prototype.hasOwnProperty.call(t,`default`)&&(n[e]=t.default),n[e]!==void 0&&Mi(t,n[e])}}if(Array.isArray(e.anyOf))for(let n of e.anyOf)typeof n!=`boolean`&&Mi(n,t);if(Array.isArray(e.oneOf))for(let n of e.oneOf)typeof n!=`boolean`&&Mi(n,t)}}function Ni(e){if(!e)return{supportsFormMode:!1,supportsUrlMode:!1};let t=e.form!==void 0,n=e.url!==void 0;return{supportsFormMode:t||!t&&!n,supportsUrlMode:n}}var Pi=class extends lr{constructor(e,t){super(t),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._cachedKnownTaskTools=new Set,this._cachedRequiredTaskTools=new Set,this._listChangedDebounceTimers=new Map,this._capabilities=t?.capabilities??{},this._jsonSchemaValidator=t?.jsonSchemaValidator??new Oi,t?.listChanged&&(this._pendingListChangedConfig=t.listChanged)}_setupListChangedHandlers(e){e.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler(`tools`,xe,e.tools,async()=>(await this.listTools()).tools),e.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler(`prompts`,fe,e.prompts,async()=>(await this.listPrompts()).prompts),e.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler(`resources`,he,e.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||={tasks:new ki(this)},this._experimental}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after connecting to transport`);this._capabilities=dr(this._capabilities,e)}setRequestHandler(e,t){let n=ar(e)?.method;if(!n)throw Error(`Schema is missing a method literal`);let r;if(q(n)){let e=n;r=e._zod?.def?.value??e.value}else{let e=n;r=e._def?.value??e.value}if(typeof r!=`string`)throw Error(`Schema method literal must be a string`);let i=r;return i===`elicitation/create`?super.setRequestHandler(e,async(e,n)=>{let r=J(h,e);if(!r.success){let e=r.error instanceof Error?r.error.message:String(r.error);throw new N(v.InvalidParams,`Invalid elicitation request: ${e}`)}let{params:i}=r.data;i.mode=i.mode??`form`;let{supportsFormMode:a,supportsUrlMode:o}=Ni(this._capabilities.elicitation);if(i.mode===`form`&&!a)throw new N(v.InvalidParams,`Client does not support form-mode elicitation requests`);if(i.mode===`url`&&!o)throw new N(v.InvalidParams,`Client does not support URL-mode elicitation requests`);let s=await Promise.resolve(t(e,n));if(i.task){let e=J(p,s);if(!e.success){let t=e.error instanceof Error?e.error.message:String(e.error);throw new N(v.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}let c=J(g,s);if(!c.success){let e=c.error instanceof Error?c.error.message:String(c.error);throw new N(v.InvalidParams,`Invalid elicitation result: ${e}`)}let l=c.data,u=i.mode===`form`?i.requestedSchema:void 0;if(i.mode===`form`&&l.action===`accept`&&l.content&&u&&this._capabilities.elicitation?.form?.applyDefaults)try{Mi(u,l.content)}catch{}return l}):i===`sampling/createMessage`?super.setRequestHandler(e,async(e,n)=>{let r=J(u,e);if(!r.success){let e=r.error instanceof Error?r.error.message:String(r.error);throw new N(v.InvalidParams,`Invalid sampling request: ${e}`)}let{params:i}=r.data,a=await Promise.resolve(t(e,n));if(i.task){let e=J(p,a);if(!e.success){let t=e.error instanceof Error?e.error.message:String(e.error);throw new N(v.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}let o=i.tools||i.toolChoice?f:d,s=J(o,a);if(!s.success){let e=s.error instanceof Error?s.error.message:String(s.error);throw new N(v.InvalidParams,`Invalid sampling result: ${e}`)}return s.data}):super.setRequestHandler(e,t)}assertCapability(e,t){if(!this._serverCapabilities?.[e])throw Error(`Server does not support ${e} (required for ${t})`)}async connect(e,t){if(await super.connect(e),e.sessionId===void 0)try{let n=await this.request({method:`initialize`,params:{protocolVersion:O,capabilities:this._capabilities,clientInfo:this._clientInfo}},T,t);if(n===void 0)throw Error(`Server sent invalid initialize result: ${n}`);if(!_e.includes(n.protocolVersion))throw Error(`Server's protocol version is not supported: ${n.protocolVersion}`);this._serverCapabilities=n.capabilities,this._serverVersion=n.serverInfo,e.setProtocolVersion&&e.setProtocolVersion(n.protocolVersion),this._instructions=n.instructions,await this.notification({method:`notifications/initialized`}),this._pendingListChangedConfig&&=(this._setupListChangedHandlers(this._pendingListChangedConfig),void 0)}catch(e){throw this.close(),e}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){switch(e){case`logging/setLevel`:if(!this._serverCapabilities?.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`prompts/get`:case`prompts/list`:if(!this._serverCapabilities?.prompts)throw Error(`Server does not support prompts (required for ${e})`);break;case`resources/list`:case`resources/templates/list`:case`resources/read`:case`resources/subscribe`:case`resources/unsubscribe`:if(!this._serverCapabilities?.resources)throw Error(`Server does not support resources (required for ${e})`);if(e===`resources/subscribe`&&!this._serverCapabilities.resources.subscribe)throw Error(`Server does not support resource subscriptions (required for ${e})`);break;case`tools/call`:case`tools/list`:if(!this._serverCapabilities?.tools)throw Error(`Server does not support tools (required for ${e})`);break;case`completion/complete`:if(!this._serverCapabilities?.completions)throw Error(`Server does not support completions (required for ${e})`);break;case`initialize`:break;case`ping`:break}}assertNotificationCapability(e){switch(e){case`notifications/roots/list_changed`:if(!this._capabilities.roots?.listChanged)throw Error(`Client does not support roots list changed notifications (required for ${e})`);break;case`notifications/initialized`:break;case`notifications/cancelled`:break;case`notifications/progress`:break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case`sampling/createMessage`:if(!this._capabilities.sampling)throw Error(`Client does not support sampling capability (required for ${e})`);break;case`elicitation/create`:if(!this._capabilities.elicitation)throw Error(`Client does not support elicitation capability (required for ${e})`);break;case`roots/list`:if(!this._capabilities.roots)throw Error(`Client does not support roots capability (required for ${e})`);break;case`tasks/get`:case`tasks/list`:case`tasks/result`:case`tasks/cancel`:if(!this._capabilities.tasks)throw Error(`Client does not support tasks capability (required for ${e})`);break;case`ping`:break}}assertTaskCapability(e){Ai(this._serverCapabilities?.tasks?.requests,e,`Server`)}assertTaskHandlerCapability(e){this._capabilities&&ji(this._capabilities.tasks?.requests,e,`Client`)}async ping(e){return this.request({method:`ping`},_,e)}async complete(e,t){return this.request({method:`completion/complete`,params:e},l,t)}async setLoggingLevel(e,t){return this.request({method:`logging/setLevel`,params:{level:e}},_,t)}async getPrompt(e,t){return this.request({method:`prompts/get`,params:e},b,t)}async listPrompts(e,t){return this.request({method:`prompts/list`,params:e},ee,t)}async listResources(e,t){return this.request({method:`resources/list`,params:e},re,t)}async listResourceTemplates(e,t){return this.request({method:`resources/templates/list`,params:e},ne,t)}async readResource(e,t){return this.request({method:`resources/read`,params:e},me,t)}async subscribeResource(e,t){return this.request({method:`resources/subscribe`,params:e},_,t)}async unsubscribeResource(e,t){return this.request({method:`resources/unsubscribe`,params:e},_,t)}async callTool(e,t=i,n){if(this.isToolTaskRequired(e.name))throw new N(v.InvalidRequest,`Tool "${e.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);let r=await this.request({method:`tools/call`,params:e},t,n),a=this.getToolOutputValidator(e.name);if(a){if(!r.structuredContent&&!r.isError)throw new N(v.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(r.structuredContent)try{let e=a(r.structuredContent);if(!e.valid)throw new N(v.InvalidParams,`Structured content does not match the tool's output schema: ${e.errorMessage}`)}catch(e){throw e instanceof N?e:new N(v.InvalidParams,`Failed to validate structured content: ${e instanceof Error?e.message:String(e)}`)}}return r}isToolTask(e){return this._serverCapabilities?.tasks?.requests?.tools?.call?this._cachedKnownTaskTools.has(e):!1}isToolTaskRequired(e){return this._cachedRequiredTaskTools.has(e)}cacheToolMetadata(e){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(let t of e){if(t.outputSchema){let e=this._jsonSchemaValidator.getValidator(t.outputSchema);this._cachedToolOutputValidators.set(t.name,e)}let e=t.execution?.taskSupport;(e===`required`||e===`optional`)&&this._cachedKnownTaskTools.add(t.name),e===`required`&&this._cachedRequiredTaskTools.add(t.name)}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,t){let n=await this.request({method:`tools/list`,params:e},se,t);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(e,t,n,r){let i=k.safeParse(n);if(!i.success)throw Error(`Invalid ${e} listChanged options: ${i.error.message}`);if(typeof n.onChanged!=`function`)throw Error(`Invalid ${e} listChanged options: onChanged must be a function`);let{autoRefresh:a,debounceMs:o}=i.data,{onChanged:s}=n,c=async()=>{if(!a){s(null,null);return}try{let e=await r();s(null,e)}catch(e){let t=e instanceof Error?e:Error(String(e));s(t,null)}};this.setNotificationHandler(t,()=>{if(o){let t=this._listChangedDebounceTimers.get(e);t&&clearTimeout(t);let n=setTimeout(c,o);this._listChangedDebounceTimers.set(e,n)}else c()})}async sendRootsListChanged(){return this.notification({method:`notifications/roots/list_changed`})}},Fi=class{constructor(e){this._server=e}requestStream(e,t,n){return this._server.requestStream(e,t,n)}async getTask(e,t){return this._server.getTask({taskId:e},t)}async getTaskResult(e,t,n){return this._server.getTaskResult({taskId:e},t,n)}async listTasks(e,t){return this._server.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._server.cancelTask({taskId:e},t)}},Ii=class extends lr{constructor(e,t){super(t),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(ce.options.map((e,t)=>[e,t])),this.isMessageIgnored=(e,t)=>{let n=this._loggingLevels.get(t);return n?this.LOG_LEVEL_SEVERITY.get(e)<this.LOG_LEVEL_SEVERITY.get(n):!1},this._capabilities=t?.capabilities??{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new Oi,this.setRequestHandler(w,e=>this._oninitialize(e)),this.setNotificationHandler(E,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(ve,async(e,t)=>{let n=t.sessionId||t.requestInfo?.headers[`mcp-session-id`]||void 0,{level:r}=e.params,i=ce.safeParse(r);return i.success&&this._loggingLevels.set(n,i.data),{}})}get experimental(){return this._experimental||={tasks:new Fi(this)},this._experimental}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after connecting to transport`);this._capabilities=dr(this._capabilities,e)}setRequestHandler(e,t){let n=ar(e)?.method;if(!n)throw Error(`Schema is missing a method literal`);let a;if(q(n)){let e=n;a=e._zod?.def?.value??e.value}else{let e=n;a=e._def?.value??e.value}if(typeof a!=`string`)throw Error(`Schema method literal must be a string`);return a===`tools/call`?super.setRequestHandler(e,async(e,n)=>{let a=J(r,e);if(!a.success){let e=a.error instanceof Error?a.error.message:String(a.error);throw new N(v.InvalidParams,`Invalid tools/call request: ${e}`)}let{params:o}=a.data,s=await Promise.resolve(t(e,n));if(o.task){let e=J(p,s);if(!e.success){let t=e.error instanceof Error?e.error.message:String(e.error);throw new N(v.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}let c=J(i,s);if(!c.success){let e=c.error instanceof Error?c.error.message:String(c.error);throw new N(v.InvalidParams,`Invalid tools/call result: ${e}`)}return c.data}):super.setRequestHandler(e,t)}assertCapabilityForMethod(e){switch(e){case`sampling/createMessage`:if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${e})`);break;case`elicitation/create`:if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${e})`);break;case`roots/list`:if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${e})`);break;case`ping`:break}}assertNotificationCapability(e){switch(e){case`notifications/message`:if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`notifications/resources/updated`:case`notifications/resources/list_changed`:if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${e})`);break;case`notifications/tools/list_changed`:if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case`notifications/prompts/list_changed`:if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case`notifications/elicitation/complete`:if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${e})`);break;case`notifications/cancelled`:break;case`notifications/progress`:break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case`completion/complete`:if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${e})`);break;case`logging/setLevel`:if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`prompts/get`:case`prompts/list`:if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${e})`);break;case`resources/list`:case`resources/templates/list`:case`resources/read`:if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${e})`);break;case`tools/call`:case`tools/list`:if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${e})`);break;case`tasks/get`:case`tasks/list`:case`tasks/result`:case`tasks/cancel`:if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${e})`);break;case`ping`:case`initialize`:break}}assertTaskCapability(e){ji(this._clientCapabilities?.tasks?.requests,e,`Client`)}assertTaskHandlerCapability(e){this._capabilities&&Ai(this._capabilities.tasks?.requests,e,`Server`)}async _oninitialize(e){let t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:_e.includes(t)?t:O,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:`ping`},_)}async createMessage(e,t){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw Error(`Client does not support sampling tools capability.`);if(e.messages.length>0){let t=e.messages[e.messages.length-1],n=Array.isArray(t.content)?t.content:[t.content],r=n.some(e=>e.type===`tool_result`),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],o=a.some(e=>e.type===`tool_use`);if(r){if(n.some(e=>e.type!==`tool_result`))throw Error(`The last message must contain only tool_result content if any is present`);if(!o)throw Error(`tool_result blocks are not matching any tool_use from the previous message`)}if(o){let e=new Set(a.filter(e=>e.type===`tool_use`).map(e=>e.id)),t=new Set(n.filter(e=>e.type===`tool_result`).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw Error(`ids of tool_result blocks and tool_use blocks from previous message do not match`)}}return e.tools?this.request({method:`sampling/createMessage`,params:e},f,t):this.request({method:`sampling/createMessage`,params:e},d,t)}async elicitInput(e,t){switch(e.mode??`form`){case`url`:{if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support url elicitation.`);let n=e;return this.request({method:`elicitation/create`,params:n},g,t)}case`form`:{if(!this._clientCapabilities?.elicitation?.form)throw Error(`Client does not support form elicitation.`);let n=e.mode===`form`?e:{...e,mode:`form`},r=await this.request({method:`elicitation/create`,params:n},g,t);if(r.action===`accept`&&r.content&&n.requestedSchema)try{let e=this._jsonSchemaValidator.getValidator(n.requestedSchema)(r.content);if(!e.valid)throw new N(v.InvalidParams,`Elicitation response content does not match requested schema: ${e.errorMessage}`)}catch(e){throw e instanceof N?e:new N(v.InternalError,`Error validating elicitation response: ${e instanceof Error?e.message:String(e)}`)}return r}}}createElicitationCompletionNotifier(e,t){if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for notifications/elicitation/complete)`);return()=>this.notification({method:`notifications/elicitation/complete`,params:{elicitationId:e}},t)}async listRoots(e,t){return this.request({method:`roots/list`,params:e},ie,t)}async sendLoggingMessage(e,t){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,t))return this.notification({method:`notifications/message`,params:e})}async sendResourceUpdated(e){return this.notification({method:`notifications/resources/updated`,params:e})}async sendResourceListChanged(){return this.notification({method:`notifications/resources/list_changed`})}async sendToolListChanged(){return this.notification({method:`notifications/tools/list_changed`})}async sendPromptListChanged(){return this.notification({method:`notifications/prompts/list_changed`})}},Li=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
29
29
  `);if(e===-1)return null;let t=this._buffer.toString(`utf8`,0,e).replace(/\r$/,``);return this._buffer=this._buffer.subarray(e+1),Ri(t)}clear(){this._buffer=void 0}};function Ri(e){return D.parse(JSON.parse(e))}function zi(e){return JSON.stringify(e)+`
30
30
  `}var Bi=class{constructor(e=Xe.stdin,t=Xe.stdout){this._stdin=e,this._stdout=t,this._readBuffer=new Li,this._started=!1,this._ondata=e=>{this._readBuffer.append(e),this.processReadBuffer()},this._onerror=e=>{this.onerror?.(e)}}async start(){if(this._started)throw Error(`StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.`);this._started=!0,this._stdin.on(`data`,this._ondata),this._stdin.on(`error`,this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off(`data`,this._ondata),this._stdin.off(`error`,this._onerror),this._stdin.listenerCount(`data`)===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(t=>{let n=zi(e);this._stdout.write(n)?t():this._stdout.once(`drain`,t)})}};export{$e as AccessControlBlockError,Pi as Client,et as ConfigurationError,Ze as InMemoryEventStore,tt as ProxyConnectionError,Li as ReadBuffer,Ii as Server,Bi as StdioServerTransport,Dt as compressClientInfo,yt as getSessionData,At as initializeTrafficMirror,Pt as logRequestCounts,It as proxyServer,St as redactCliArgs,zi as serializeMessage,ir as startHTTPServer};
31
- //# sourceMappingURL=stdio-BD8z2niv.js.map
31
+ //# sourceMappingURL=stdio-DDsYWNYz.js.map