@kya-os/mcp-i 1.6.0 → 1.6.1-canary.clientinfo.20251125183419

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.
@@ -1,2 +1,2 @@
1
1
  /*! For license information please see stdio.js.LICENSE.txt */
2
- (()=>{var e={202:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.IdpTokenResolver=void 0,t.IdpTokenResolver=class{config;constructor(e){this.config={tokenStorage:e.tokenStorage,oauthService:e.oauthService,logger:e.logger||(()=>{})}}async resolveTokenFromDid(e,t,r){const s=await this.config.tokenStorage.getToken(e,t,r);if(!s)return this.config.logger("[IdpTokenResolver] Token not found",{userDid:e.substring(0,20)+"...",provider:t,scopes:r}),null;const i=Date.now();if(s.expires_at<i){if(this.config.logger("[IdpTokenResolver] Token expired, attempting refresh",{userDid:e.substring(0,20)+"...",provider:t,expiresAt:new Date(s.expires_at).toISOString(),hasRefreshToken:!!s.refresh_token}),s.refresh_token){const i=await this.config.oauthService.refreshToken(t,s.refresh_token);return i?(await this.config.tokenStorage.storeToken(e,t,r,i),this.config.logger("[IdpTokenResolver] Token refreshed successfully",{userDid:e.substring(0,20)+"...",provider:t,expiresAt:new Date(i.expires_at).toISOString()}),i.access_token):(this.config.logger("[IdpTokenResolver] Token refresh failed",{userDid:e.substring(0,20)+"...",provider:t}),null)}return this.config.logger("[IdpTokenResolver] Token expired and no refresh token",{userDid:e.substring(0,20)+"...",provider:t}),null}return this.config.logger("[IdpTokenResolver] Token resolved successfully",{userDid:e.substring(0,20)+"...",provider:t,expiresAt:new Date(s.expires_at).toISOString()}),s.access_token}}},4901:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ToolProtectionServiceError=t.DelegationRequiredError=void 0;class r extends Error{toolName;requiredScopes;consentUrl;resumeToken;interceptedCall;constructor(e,t,r,s,i){super(`Delegation required for tool "${e}"`),this.toolName=e,this.requiredScopes=t,this.consentUrl=r,this.name="DelegationRequiredError",this.interceptedCall=s,this.resumeToken=i}}t.DelegationRequiredError=r;class s extends Error{cause;constructor(e,t){super(e),this.cause=t,this.name="ToolProtectionServiceError"}}t.ToolProtectionServiceError=s},6069:(e,t,r)=>{"use strict";var s=r(72916).MissingRef;e.exports=function e(t,r,i){var a=this;if("function"!=typeof this._opts.loadSchema)throw new Error("options.loadSchema should be a function");"function"==typeof r&&(i=r,r=void 0);var o=n(t).then(function(){var e=a._addSchema(t,void 0,r);return e.validate||c(e)});return i&&o.then(function(e){i(null,e)},i),o;function n(t){var r=t.$schema;return r&&!a.getSchema(r)?e.call(a,{$ref:r},!0):Promise.resolve()}function c(e){try{return a._compile(e)}catch(t){if(t instanceof s)return function(t){var s=t.missingSchema;if(d(s))throw new Error("Schema "+s+" is loaded but "+t.missingRef+" cannot be resolved");var i=a._loadingSchemas[s];return i||(i=a._loadingSchemas[s]=a._opts.loadSchema(s)).then(o,o),i.then(function(e){if(!d(s))return n(e).then(function(){d(s)||a.addSchema(e,s,void 0,r)})}).then(function(){return c(e)});function o(){delete a._loadingSchemas[s]}function d(e){return a._refs[e]||a._schemas[e]}}(t);throw t}}}},7318:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MemoryStatusListStorage=void 0,t.MemoryStatusListStorage=class{statusLists=new Map;indexCounters=new Map;async getStatusList(e){return this.statusLists.get(e)||null}async setStatusList(e,t){this.statusLists.set(e,t)}async allocateIndex(e){const t=this.indexCounters.get(e)||0,r=t;return this.indexCounters.set(e,t+1),r}getIndexCount(e){return this.indexCounters.get(e)||0}clear(){this.statusLists.clear(),this.indexCounters.clear()}getAllStatusListIds(){return Array.from(this.statusLists.keys())}}},9249:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ToolProtectionService=void 0;const s=r(85601);t.ToolProtectionService=class{config;cache;constructor(e,t){this.config=e,this.cache=t}getProjectId(){return this.config.projectId}async getStaleCache(e){if(!1===this.config.allowStaleCache)return null;if(!(this.cache instanceof s.InMemoryToolProtectionCache))return null;const t=this.cache.getStale(e);if(!t)return null;const r=this.cache.getExpiresAt(e);if(!r)return null;const i=Date.now(),a=this.config.maxStaleCacheAge??864e5;return i>r&&i-r<=a?(this.config.debug&&console.log("[ToolProtectionService] Using stale cache",{cacheKey:e,expiredAt:new Date(r).toISOString(),staleAgeMs:i-r,maxStaleAgeMs:a}),t):null}async getToolProtectionConfig(e){const t=this.config.projectId?`config:tool-protections:${this.config.projectId}`:`agent:${e}`,r=await this.cache.get(t);if(r){const s=this.config.cacheTtl??3e5,i=new Date(Date.now()+s).toISOString();return this.config.debug&&console.log("[ToolProtectionService] Cache hit",{source:"cache",cacheKey:t,agentDid:e.slice(0,20)+"...",projectId:this.config.projectId||"none",toolCount:Object.keys(r.toolProtections).length,protectedTools:Object.entries(r.toolProtections).filter(([e,t])=>t.requiresDelegation).map(([e])=>e),cacheTtlMs:s,cachedUntil:i}),r}this.config.debug&&console.log("[ToolProtectionService] Cache miss, fetching from API",{source:"api-fetch-start",cacheKey:t,agentDid:e.slice(0,20)+"...",projectId:this.config.projectId||"none",apiUrl:this.config.apiUrl,endpoint:this.config.projectId?`/api/v1/bouncer/projects/${this.config.projectId}/tool-protections`:`/api/v1/bouncer/config?agent_did=${e}`});try{const r=await this.fetchFromApi(e);this.config.debug&&console.log("[ToolProtectionService] API response received",{source:"api-fetch-complete",agentDid:e.slice(0,20)+"...",projectId:this.config.projectId||"none",responseKeys:Object.keys(r),dataKeys:r.data?Object.keys(r.data):[],rawToolProtections:r.data?.toolProtections||null,rawTools:r.data?.tools||null,responseMetadata:r.metadata||null});const s={};if(r.data.toolProtections)for(const[e,t]of Object.entries(r.data.toolProtections)){const r=t.requiresDelegation??t.requires_delegation??!1,i=t.requiredScopes??t.required_scopes??t.scopes??[],a=t.oauthProvider??t.oauth_provider??void 0,o=t.riskLevel??t.risk_level??void 0;s[e]={requiresDelegation:r,requiredScopes:i,...a&&{oauthProvider:a},...o&&{riskLevel:o}}}else if(r.data.tools)if(Array.isArray(r.data.tools))for(const e of r.data.tools){const t=e.name;if(!t){this.config.debug&&console.warn("[ToolProtectionService] Tool missing name in array format",e);continue}const r=e.requiresDelegation??e.requires_delegation??!1,i=e.requiredScopes??e.required_scopes??e.scopes??[],a=e.oauthProvider??e.oauth_provider??void 0,o=e.riskLevel??e.risk_level??void 0;s[t]={requiresDelegation:r,requiredScopes:i,...a&&{oauthProvider:a},...o&&{riskLevel:o}}}else for(const[e,t]of Object.entries(r.data.tools)){const r=t.requiresDelegation??t.requires_delegation??!1,i=t.requiredScopes??t.required_scopes??t.scopes??[],a=t.oauthProvider??t.oauth_provider??void 0,o=t.riskLevel??t.risk_level??void 0;s[e]={requiresDelegation:r,requiredScopes:i,...a&&{oauthProvider:a},...o&&{riskLevel:o}}}const i={...s};if(this.config.fallbackConfig?.toolProtections)for(const[e,t]of Object.entries(this.config.fallbackConfig.toolProtections)){if(!t||"object"!=typeof t||0===Object.keys(t).length){this.config.debug&&console.log("[ToolProtectionService] Skipping empty/invalid fallback config entry",{tool:e});continue}const r={requiresDelegation:t.requiresDelegation??!1,requiredScopes:t.requiredScopes??[]};i[e]=r,this.config.debug&&console.log("[ToolProtectionService] Overriding API config with local config",{tool:e,localConfig:r})}const a={toolProtections:i},o=this.config.cacheTtl??3e5,n=new Date(Date.now()+o);return await this.cache.set(t,a,o),console.log("[ToolProtectionService] Config loaded from API",{source:"api",toolCount:Object.keys(i).length,protectedTools:Object.entries(i).filter(([e,t])=>t.requiresDelegation).map(([e])=>e),agentDid:e.slice(0,20)+"...",projectId:this.config.projectId||"none",cacheTtlMs:o,cacheExpiresAt:n.toISOString()}),this.config.debug&&console.log("[ToolProtectionService] API fetch successful, config cached",{source:"cache-write",agentDid:e.slice(0,20)+"...",cacheKey:t,toolCount:Object.keys(i).length,tools:Object.entries(i).map(([e,t])=>({name:e,requiresDelegation:t.requiresDelegation,scopeCount:(t.requiredScopes||[]).length})),ttlMs:o,ttlMinutes:Math.round(o/6e4),expiresAt:n.toISOString(),expiresIn:`${Math.round(o/1e3)}s`}),a}catch(r){const s=r instanceof Error?r.message:String(r);if(s.includes("API key is missing or empty"))throw r;if(s.includes("Failed to fetch bouncer config:")&&(429!==r.status||!this.config.fallbackConfig))throw r;if(s.includes("Failed to parse API response:"))throw r;if(s.includes("API returned success: false"))throw r;this.config.debug&&console.error("[ToolProtectionService] API fetch failed",{agentDid:e.slice(0,20)+"...",error:s});const i=await this.getStaleCache(t);if(i)return console.warn("[ToolProtectionService] API fetch failed, using stale cache",{agentDid:e.slice(0,20)+"...",error:s,cacheKey:t}),i;if(this.config.fallbackConfig){console.warn("[ToolProtectionService] API fetch failed, using fallback config",{agentDid:e.slice(0,20)+"...",error:s});const r=this.config.cacheTtl??3e5;return await this.cache.set(t,this.config.fallbackConfig,r),this.config.fallbackConfig}if("deny-all"===(this.config.failSafeBehavior??"deny-all")){console.error("[ToolProtectionService] API fetch failed, no fallback, failing closed (deny-all)",{agentDid:e.slice(0,20)+"...",error:s,cacheKey:t});const r={toolProtections:{"*":{requiresDelegation:!0,requiredScopes:[]}}},i=this.config.cacheTtl??3e5;return await this.cache.set(t,r,i),r}{console.warn("[ToolProtectionService] API fetch failed, no fallback, failing open (allow-all)",{agentDid:e.slice(0,20)+"...",error:s,cacheKey:t});const r={toolProtections:{}},i=this.config.cacheTtl??3e5;return await this.cache.set(t,r,i),r}}}async checkToolProtection(e,t){const r=await this.getToolProtectionConfig(t);let s=r.toolProtections[e];return!s&&r.toolProtections["*"]&&(s=r.toolProtections["*"]),(this.config.debug||!s||s.requiresDelegation)&&console.log("[ToolProtectionService] Protection check",{tool:e,agentDid:t.slice(0,20)+"...",found:!!s,isWildcard:s===r.toolProtections["*"],requiresDelegation:s?.requiresDelegation??!1,availableTools:Object.keys(r.toolProtections)}),s&&s.requiresDelegation?s:null}async fetchFromApi(e){let t,r=!1;this.config.projectId?(t=`${this.config.apiUrl}/api/v1/bouncer/projects/${encodeURIComponent(this.config.projectId)}/tool-protections`,r=!0):t=`${this.config.apiUrl}/api/v1/bouncer/config?agent_did=${encodeURIComponent(e)}`;const s=this.config.apiKey?(()=>{const e=this.config.apiKey.split("_");return e.length>=2?`${e[0]}_${e[1]}...`:`${this.config.apiKey.substring(0,8)}...`})():"(empty)",i=this.config.apiKey?.length||0;if(this.config.debug&&console.log("[ToolProtectionService] Fetching from API:",t,{method:r?"projects/{projectId}/tool-protections (new)":"config?agent_did (old)",projectId:this.config.projectId||"none",apiKeyPresent:!!this.config.apiKey,apiKeyLength:i,apiKeyMasked:s}),!this.config.apiKey||""===this.config.apiKey.trim()){const e="API key is missing or empty";throw this.config.debug&&console.error("[ToolProtectionService]",e,{apiKeyPresent:!!this.config.apiKey,apiKeyLength:i}),new Error(`ToolProtectionService: ${e}. Check AGENTSHIELD_API_KEY in .dev.vars or wrangler.toml [vars]`)}const a={"Content-Type":"application/json"};r?(a["X-API-Key"]=this.config.apiKey,this.config.projectId&&(a["X-Project-Id"]=this.config.projectId)):a.Authorization=`Bearer ${this.config.apiKey}`;const o=await fetch(t,{method:"GET",headers:a});if(!o.ok){const e=await o.text().catch(()=>"Unknown error"),t=new Error(`Failed to fetch bouncer config: ${o.status} ${o.statusText} - ${e}`);throw t.status=o.status,t}let n;try{n=await o.json()}catch(e){throw new Error(`Failed to parse API response: ${e instanceof Error?e.message:String(e)}`)}if(!n.success)throw new Error("API returned success: false");return n}async clearCache(e){const t=this.config.projectId?`config:tool-protections:${this.config.projectId}`:`agent:${e}`;this.config.debug&&console.log("[ToolProtectionService] Clearing cache",{cacheKey:t,projectId:this.config.projectId||"none",agentDid:e.slice(0,20)+"..."}),await this.cache.delete(t)}async clearAndRefresh(e){const t=this.config.projectId?`config:tool-protections:${this.config.projectId}`:`agent:${e}`;console.log("[ToolProtectionService] clearAndRefresh starting",{cacheKey:t,projectId:this.config.projectId||"none",agentDid:e.slice(0,20)+"..."}),await this.cache.delete(t),console.log("[ToolProtectionService] Cache entry deleted",{cacheKey:t});try{const r=await this.fetchFromApi(e),s={};if(r.data.toolProtections)for(const[e,t]of Object.entries(r.data.toolProtections)){const r=t.requiresDelegation??t.requires_delegation??!1,i=t.requiredScopes??t.required_scopes??t.scopes??[],a=t.oauthProvider??t.oauth_provider??void 0,o=t.riskLevel??t.risk_level??void 0;s[e]={requiresDelegation:r,requiredScopes:i,...a&&{oauthProvider:a},...o&&{riskLevel:o}}}else if(r.data.tools)if(Array.isArray(r.data.tools))for(const e of r.data.tools){const t=e.name;if(!t)continue;const r=e.requiresDelegation??e.requires_delegation??!1,i=e.requiredScopes??e.required_scopes??e.scopes??[],a=e.oauthProvider??e.oauth_provider??void 0,o=e.riskLevel??e.risk_level??void 0;s[t]={requiresDelegation:r,requiredScopes:i,...a&&{oauthProvider:a},...o&&{riskLevel:o}}}else for(const[e,t]of Object.entries(r.data.tools)){const r=t.requiresDelegation??t.requires_delegation??!1,i=t.requiredScopes??t.required_scopes??t.scopes??[],a=t.oauthProvider??t.oauth_provider??void 0,o=t.riskLevel??t.risk_level??void 0;s[e]={requiresDelegation:r,requiredScopes:i,...a&&{oauthProvider:a},...o&&{riskLevel:o}}}const i={toolProtections:s},a=this.config.cacheTtl??3e5;return await this.cache.set(t,i,a),console.log("[ToolProtectionService] Fresh config fetched and cached",{cacheKey:t,toolCount:Object.keys(s).length,protectedTools:Object.entries(s).filter(([e,t])=>t.requiresDelegation).map(([e])=>e),source:"api"}),{config:i,cacheKey:t,source:"api"}}catch(e){return console.warn("[ToolProtectionService] API fetch failed during refresh, using fallback",{error:e instanceof Error?e.message:String(e),cacheKey:t}),{config:this.config.fallbackConfig||{toolProtections:{}},cacheKey:t,source:"fallback"}}}}},9717:(e,t,r)=>{"use strict";function s(e,t,r,s){var i=s?" !== ":" === ",a=s?" || ":" && ",o=s?"!":"",n=s?"":"!";switch(e){case"null":return t+i+"null";case"array":return o+"Array.isArray("+t+")";case"object":return"("+o+t+a+"typeof "+t+i+'"object"'+a+n+"Array.isArray("+t+"))";case"integer":return"(typeof "+t+i+'"number"'+a+n+"("+t+" % 1)"+a+t+i+t+(r?a+o+"isFinite("+t+")":"")+")";case"number":return"(typeof "+t+i+'"'+e+'"'+(r?a+o+"isFinite("+t+")":"")+")";default:return"typeof "+t+i+'"'+e+'"'}}e.exports={copy:function(e,t){for(var r in t=t||{},e)t[r]=e[r];return t},checkDataType:s,checkDataTypes:function(e,t,r){if(1===e.length)return s(e[0],t,r,!0);var i="",o=a(e);for(var n in o.array&&o.object&&(i=o.null?"(":"(!"+t+" || ",i+="typeof "+t+' !== "object")',delete o.null,delete o.array,delete o.object),o.number&&delete o.integer,o)i+=(i?" && ":"")+s(n,t,r,!0);return i},coerceToTypes:function(e,t){if(Array.isArray(t)){for(var r=[],s=0;s<t.length;s++){var a=t[s];(i[a]||"array"===e&&"array"===a)&&(r[r.length]=a)}if(r.length)return r}else{if(i[t])return[t];if("array"===e&&"array"===t)return["array"]}},toHash:a,getProperty:c,escapeQuotes:d,equal:r(67371),ucs2length:r(61812),varOccurences:function(e,t){t+="[^0-9]";var r=e.match(new RegExp(t,"g"));return r?r.length:0},varReplace:function(e,t,r){return t+="([^0-9])",r=r.replace(/\$/g,"$$$$"),e.replace(new RegExp(t,"g"),r+"$1")},schemaHasRules:function(e,t){if("boolean"==typeof e)return!e;for(var r in e)if(t[r])return!0},schemaHasRulesExcept:function(e,t,r){if("boolean"==typeof e)return!e&&"not"!=r;for(var s in e)if(s!=r&&t[s])return!0},schemaUnknownRules:function(e,t){if("boolean"!=typeof e)for(var r in e)if(!t[r])return r},toQuotedString:l,getPathExpr:function(e,t,r,s){return p(e,r?"'/' + "+t+(s?"":".replace(/~/g, '~0').replace(/\\//g, '~1')"):s?"'[' + "+t+" + ']'":"'[\\'' + "+t+" + '\\']'")},getPath:function(e,t,r){return p(e,l(r?"/"+f(t):c(t)))},getData:function(e,t,r){var s,i,a,o;if(""===e)return"rootData";if("/"==e[0]){if(!u.test(e))throw new Error("Invalid JSON-pointer: "+e);i=e,a="rootData"}else{if(!(o=e.match(h)))throw new Error("Invalid JSON-pointer: "+e);if(s=+o[1],"#"==(i=o[2])){if(s>=t)throw new Error("Cannot access property/index "+s+" levels up, current level is "+t);return r[t-s]}if(s>t)throw new Error("Cannot access data "+s+" levels up, current level is "+t);if(a="data"+(t-s||""),!i)return a}for(var n=a,d=i.split("/"),l=0;l<d.length;l++){var p=d[l];p&&(n+=" && "+(a+=c(g(p))))}return n},unescapeFragment:function(e){return g(decodeURIComponent(e))},unescapeJsonPointer:g,escapeFragment:function(e){return encodeURIComponent(f(e))},escapeJsonPointer:f};var i=a(["string","number","integer","boolean","null"]);function a(e){for(var t={},r=0;r<e.length;r++)t[e[r]]=!0;return t}var o=/^[a-z$_][a-z$_0-9]*$/i,n=/'|\\/g;function c(e){return"number"==typeof e?"["+e+"]":o.test(e)?"."+e:"['"+d(e)+"']"}function d(e){return e.replace(n,"\\$&").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\f/g,"\\f").replace(/\t/g,"\\t")}function l(e){return"'"+d(e)+"'"}var u=/^\/(?:[^~]|~0|~1)*$/,h=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function p(e,t){return'""'==e?t:(e+" + "+t).replace(/([^\\])' \+ '/g,"$1")}function f(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function g(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}},9931:e=>{"use strict";e.exports=function(e,t,r){var s=" ",i=e.level,a=e.dataLevel,o=e.schema[t],n=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,d=!e.opts.allErrors,l="data"+(a||""),u="errs__"+i,h=e.util.copy(e);h.level++;var p="valid"+h.level;if(s+="var "+u+" = errors;",e.opts.strictKeywords?"object"==typeof o&&Object.keys(o).length>0||!1===o:e.util.schemaHasRules(o,e.RULES.all)){h.schema=o,h.schemaPath=n,h.errSchemaPath=c;var f="key"+i,g="idx"+i,m="i"+i,v="' + "+f+" + '",y="data"+(h.dataLevel=e.dataLevel+1),_="dataProperties"+i,w=e.opts.ownProperties,b=e.baseId;w&&(s+=" var "+_+" = undefined; "),s+=w?" "+_+" = "+_+" || Object.keys("+l+"); for (var "+g+"=0; "+g+"<"+_+".length; "+g+"++) { var "+f+" = "+_+"["+g+"]; ":" for (var "+f+" in "+l+") { ",s+=" var startErrs"+i+" = errors; ";var S=f,P=e.compositeRule;e.compositeRule=h.compositeRule=!0;var E=e.validate(h);h.baseId=b,e.util.varOccurences(E,y)<2?s+=" "+e.util.varReplace(E,y,S)+" ":s+=" var "+y+" = "+S+"; "+E+" ",e.compositeRule=h.compositeRule=P,s+=" if (!"+p+") { for (var "+m+"=startErrs"+i+"; "+m+"<errors; "+m+"++) { vErrors["+m+"].propertyName = "+f+"; } var err = ",!1!==e.createErrors?(s+=" { keyword: 'propertyNames' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { propertyName: '"+v+"' } ",!1!==e.opts.messages&&(s+=" , message: 'property name \\'"+v+"\\' is invalid' "),e.opts.verbose&&(s+=" , schema: validate.schema"+n+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),s+=" } "):s+=" {} ",s+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&d&&(e.async?s+=" throw new ValidationError(vErrors); ":s+=" validate.errors = vErrors; return false; "),d&&(s+=" break; "),s+=" } }"}return d&&(s+=" if ("+u+" == errors) {"),s}},10985:(e,t,r)=>{"use strict";r.d(t,{S:()=>i});var s="$";function i(e,t){var r="",i=t&&t.include,a=t&&t.exclude;a&&"string"==typeof a&&(a=[a]),i&&i.sort();var o=new WeakMap,n=t&&t.allowCircular,c=t&&t.filterUndefined,d=t&&t.undefinedInArrayToNull;return function e(t,l){if(null===t||"object"!=typeof t||null!=t.toJSON)r+=JSON.stringify(t);else if(Array.isArray(t)){if(void 0!==(h=o.get(t))&&l.startsWith(h)){if(!n)throw new Error("Circular reference detected");return void(r+='"[Circular:'+h+']"')}o.set(t,l),r+="[";var u=!1;t.forEach(function(t,s){u&&(r+=","),u=!0,d&&void 0===t&&(t=null),e(t,l+"["+s+"]")}),r+="]"}else{var h;if(void 0!==(h=o.get(t))&&l.startsWith(h)){if(!n)throw new Error("Circular reference detected");return void(r+='"[Circular:'+h+']"')}o.set(t,l),r+="{";var p=!1,f=function(s){a&&a.includes(s)||(p&&(r+=","),p=!0,r+=JSON.stringify(s),r+=":",e(t[s],l+"."+s))};if(l===s&&i)i.forEach(function(e){t.hasOwnProperty(e)&&f(e)});else{var g=Object.keys(t);c&&(g=g.filter(function(e){return void 0!==t[e]})),g.sort(),g.forEach(function(e){f(e)})}r+="}"}}(e,s),r}},11300:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SCHEMA_REGISTRY=void 0,t.getAllSchemas=function(){return t.SCHEMA_REGISTRY},t.getSchemasByCategory=function(e){const r={vc:["verifiable-credential","verifiable-presentation","statuslist2021-credential","statuslist2021-credential-subject"],delegation:["delegation-credential","delegation-record","delegation-constraints","delegation-chain","delegation-creation-request","delegation-verification-result"],handshake:["handshake-request","session-context","nonce-cache-config","nonce-cache-entry"],proof:["detached-proof","proof-meta","proof","proof-w3c","audit-record","canonical-hashes"],registry:["registration-input","registration-result","agent-status","claim-token","delegation-request","delegation-response","registry-delegation","mirror-status","receipt"],runtime:["authorization-display","needs-authorization-error","runtime-error"],cli:["register-output"],tlkrc:["rotation-chain","rotation-event"],verifier:["verify-page"],"well-known":["well-known-agent"]}[e]||[];return t.SCHEMA_REGISTRY.filter(e=>r.includes(e.id))},t.getSchemaById=function(e){return t.SCHEMA_REGISTRY.find(t=>t.id===e)},t.getCriticalSchemas=function(){const e=["verifiable-credential","statuslist2021-credential","delegation-credential","delegation-record","delegation-constraints","detached-proof","proof-meta","handshake-request","session-context","audit-record"];return t.SCHEMA_REGISTRY.filter(t=>e.includes(t.id))},t.getSchemaStats=function(){const e={},s={};for(const i of t.SCHEMA_REGISTRY){const t=i.url.replace(r+"/","").split("/")[0]||"unknown";e[t]=(e[t]||0)+1,s[i.version]=(s[i.version]||0)+1}return{total:t.SCHEMA_REGISTRY.length,byCategory:e,byVersion:s}};const r="https://schemas.kya-os.ai/xmcp-i";t.SCHEMA_REGISTRY=[{id:"verifiable-credential",url:`${r}/vc/verifiable-credential.v1.0.0.json`,version:"1.0.0",type:"VerifiableCredential",description:"W3C Verifiable Credential Data Model"},{id:"verifiable-presentation",url:`${r}/vc/verifiable-presentation.v1.0.0.json`,version:"1.0.0",type:"VerifiablePresentation",description:"W3C Verifiable Presentation"},{id:"statuslist2021-credential",url:`${r}/vc/statuslist-2021-credential.v1.0.0.json`,version:"1.0.0",type:"StatusList2021Credential",description:"StatusList2021 Credential for efficient revocation"},{id:"statuslist2021-credential-subject",url:`${r}/vc/statuslist-2021-credential-subject.v1.0.0.json`,version:"1.0.0",type:"StatusList2021CredentialSubject",description:"StatusList2021 Credential Subject"},{id:"delegation-credential",url:`${r}/credentials/delegation/v1.0.0.json`,version:"1.0.0",type:"DelegationCredential",description:"W3C VC-based delegation credential"},{id:"delegation-record",url:`${r}/delegation/delegation-record.v1.0.0.json`,version:"1.0.0",type:"DelegationRecord",description:"Internal delegation record"},{id:"delegation-constraints",url:`${r}/delegation/constraints.v1.0.0.json`,version:"1.0.0",type:"DelegationConstraints",description:"CRISP constraints for delegations"},{id:"delegation-chain",url:`${r}/delegation/delegation-chain.v1.0.0.json`,version:"1.0.0",type:"DelegationChain",description:"Delegation chain for hierarchy tracking"},{id:"delegation-creation-request",url:`${r}/delegation/delegation-creation-request.v1.0.0.json`,version:"1.0.0",type:"DelegationCreationRequest",description:"Request to create a delegation"},{id:"delegation-verification-result",url:`${r}/delegation/delegation-verification-result.v1.0.0.json`,version:"1.0.0",type:"DelegationVerificationResult",description:"Result of delegation verification"},{id:"handshake-request",url:`${r}/handshake/handshake-request.v1.0.0.json`,version:"1.0.0",type:"HandshakeRequest",description:"MCP-I handshake request"},{id:"session-context",url:`${r}/handshake/session-context.v1.0.0.json`,version:"1.0.0",type:"SessionContext",description:"MCP-I session context"},{id:"nonce-cache-config",url:`${r}/handshake/nonce-cache-config.v1.0.0.json`,version:"1.0.0",type:"NonceCacheConfig",description:"Nonce cache configuration"},{id:"nonce-cache-entry",url:`${r}/handshake/nonce-cache-entry.v1.0.0.json`,version:"1.0.0",type:"NonceCacheEntry",description:"Nonce cache entry for replay protection"},{id:"detached-proof",url:`${r}/proof/detached-proof.v1.0.0.json`,version:"1.0.0",type:"DetachedProof",description:"MCP-I detached proof with JWS"},{id:"proof-meta",url:`${r}/proof/proof-meta.v1.0.0.json`,version:"1.0.0",type:"ProofMeta",description:"Metadata for MCP-I proofs"},{id:"proof",url:`${r}/proof/v1.0.0.json`,version:"1.0.0",type:"Proof",description:"Generic proof structure"},{id:"proof-w3c",url:`${r}/proof/w3c/v1.0.0.json`,version:"1.0.0",type:"W3CProof",description:"W3C-compliant proof"},{id:"audit-record",url:`${r}/proof/audit-record.v1.0.0.json`,version:"1.0.0",type:"AuditRecord",description:"Audit trail record"},{id:"canonical-hashes",url:`${r}/proof/canonical-hashes.v1.0.0.json`,version:"1.0.0",type:"CanonicalHashes",description:"Canonical hashes for proof generation"},{id:"registration-input",url:`${r}/registry/registration-input.v1.0.0.json`,version:"1.0.0",type:"RegistrationInput",description:"Agent registration input"},{id:"registration-result",url:`${r}/registry/registration-result.v1.0.0.json`,version:"1.0.0",type:"RegistrationResult",description:"Agent registration result"},{id:"agent-status",url:`${r}/registry/agent-status.v1.0.0.json`,version:"1.0.0",type:"AgentStatus",description:"Agent status information"},{id:"claim-token",url:`${r}/registry/claim-token.v1.0.0.json`,version:"1.0.0",type:"ClaimToken",description:"Token for claiming agent ownership"},{id:"delegation-request",url:`${r}/registry/delegation-request.v1.0.0.json`,version:"1.0.0",type:"DelegationRequest",description:"Registry delegation request"},{id:"delegation-response",url:`${r}/registry/delegation-response.v1.0.0.json`,version:"1.0.0",type:"DelegationResponse",description:"Registry delegation response"},{id:"registry-delegation",url:`${r}/registry/delegation.v1.0.0.json`,version:"1.0.0",type:"RegistryDelegation",description:"Registry delegation object"},{id:"mirror-status",url:`${r}/registry/mirror-status.v1.0.0.json`,version:"1.0.0",type:"MirrorStatus",description:"Registry mirror status"},{id:"receipt",url:`${r}/registry/receipt.v1.0.0.json`,version:"1.0.0",type:"Receipt",description:"Registry receipt"},{id:"authorization-display",url:`${r}/runtime/authorization-display.v1.0.0.json`,version:"1.0.0",type:"AuthorizationDisplay",description:"Authorization display information"},{id:"needs-authorization-error",url:`${r}/runtime/needs-authorization-error.v1.0.0.json`,version:"1.0.0",type:"NeedsAuthorizationError",description:"Error indicating authorization is needed"},{id:"runtime-error",url:`${r}/runtime/runtime-error.v1.0.0.json`,version:"1.0.0",type:"RuntimeError",description:"Generic runtime error"},{id:"register-output",url:`${r}/cli/register-output/v1.0.0.json`,version:"1.0.0",type:"RegisterOutput",description:"CLI registration output"},{id:"rotation-chain",url:`${r}/tlkrc/rotation-chain.v1.0.0.json`,version:"1.0.0",type:"RotationChain",description:"Key rotation chain"},{id:"rotation-event",url:`${r}/tlkrc/rotation-event.v1.0.0.json`,version:"1.0.0",type:"RotationEvent",description:"Key rotation event"},{id:"verify-page",url:`${r}/verifier/verify-page/v1.0.0.json`,version:"1.0.0",type:"VerifyPage",description:"Verifier page response"},{id:"well-known-agent",url:`${r}/well-known/agent/v1.0.0.json`,version:"1.0.0",type:"WellKnownAgent",description:"Agent well-known metadata"}]},12269:e=>{"use strict";e.exports=JSON.parse('{"$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":true,"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":true,"readOnly":{"type":"boolean","default":false},"examples":{"type":"array","items":true},"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":true},"maxItems":{"$ref":"#/definitions/nonNegativeInteger"},"minItems":{"$ref":"#/definitions/nonNegativeIntegerDefault0"},"uniqueItems":{"type":"boolean","default":false},"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":true,"enum":{"type":"array","items":true,"minItems":1,"uniqueItems":true},"type":{"anyOf":[{"$ref":"#/definitions/simpleTypes"},{"type":"array","items":{"$ref":"#/definitions/simpleTypes"},"minItems":1,"uniqueItems":true}]},"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":true}')},12857:e=>{"use strict";e.exports=function(e,t,r){var s,i,a=" ",o=e.level,n=e.dataLevel,c=e.schema[t],d=e.errSchemaPath+"/"+t,l=!e.opts.allErrors,u="data"+(n||""),h="valid"+o;if("#"==c||"#/"==c)e.isRoot?(s=e.async,i="validate"):(s=!0===e.root.schema.$async,i="root.refVal[0]");else{var p=e.resolveRef(e.baseId,c,e.isRoot);if(void 0===p){var f=e.MissingRefError.message(e.baseId,c);if("fail"==e.opts.missingRefs){e.logger.error(f),(y=y||[]).push(a),a="",!1!==e.createErrors?(a+=" { keyword: '$ref' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(d)+" , params: { ref: '"+e.util.escapeQuotes(c)+"' } ",!1!==e.opts.messages&&(a+=" , message: 'can\\'t resolve reference "+e.util.escapeQuotes(c)+"' "),e.opts.verbose&&(a+=" , schema: "+e.util.toQuotedString(c)+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ";var g=a;a=y.pop(),!e.compositeRule&&l?e.async?a+=" throw new ValidationError(["+g+"]); ":a+=" validate.errors = ["+g+"]; return false; ":a+=" var err = "+g+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",l&&(a+=" if (false) { ")}else{if("ignore"!=e.opts.missingRefs)throw new e.MissingRefError(e.baseId,c,f);e.logger.warn(f),l&&(a+=" if (true) { ")}}else if(p.inline){var m=e.util.copy(e);m.level++;var v="valid"+m.level;m.schema=p.schema,m.schemaPath="",m.errSchemaPath=c,a+=" "+e.validate(m).replace(/validate\.schema/g,p.code)+" ",l&&(a+=" if ("+v+") { ")}else s=!0===p.$async||e.async&&!1!==p.$async,i=p.code}if(i){var y;(y=y||[]).push(a),a="",e.opts.passContext?a+=" "+i+".call(this, ":a+=" "+i+"( ",a+=" "+u+", (dataPath || '')",'""'!=e.errorPath&&(a+=" + "+e.errorPath);var _=a+=" , "+(n?"data"+(n-1||""):"parentData")+" , "+(n?e.dataPathArr[n]:"parentDataProperty")+", rootData) ";if(a=y.pop(),s){if(!e.async)throw new Error("async schema referenced by sync schema");l&&(a+=" var "+h+"; "),a+=" try { await "+_+"; ",l&&(a+=" "+h+" = true; "),a+=" } catch (e) { if (!(e instanceof ValidationError)) throw e; if (vErrors === null) vErrors = e.errors; else vErrors = vErrors.concat(e.errors); errors = vErrors.length; ",l&&(a+=" "+h+" = false; "),a+=" } ",l&&(a+=" if ("+h+") { ")}else a+=" if (!"+_+") { if (vErrors === null) vErrors = "+i+".errors; else vErrors = vErrors.concat("+i+".errors); errors = vErrors.length; } ",l&&(a+=" else { ")}return a}},13215:e=>{"use strict";e.exports=JSON.parse('{"$schema":"http://json-schema.org/draft-07/schema#","$id":"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#","description":"Meta-schema for $data reference (JSON Schema extension proposal)","type":"object","required":["$data"],"properties":{"$data":{"type":"string","anyOf":[{"format":"relative-json-pointer"},{"format":"json-pointer"}]}},"additionalProperties":false}')},13441:e=>{"use strict";e.exports=function(e,t,r){var s=" ",i=e.level,a=e.dataLevel,o=e.schema[t],n=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,d=!e.opts.allErrors,l="data"+(a||""),u="errs__"+i,h=e.util.copy(e);h.level++;var p="valid"+h.level;if(e.opts.strictKeywords?"object"==typeof o&&Object.keys(o).length>0||!1===o:e.util.schemaHasRules(o,e.RULES.all)){h.schema=o,h.schemaPath=n,h.errSchemaPath=c,s+=" var "+u+" = errors; ";var f,g=e.compositeRule;e.compositeRule=h.compositeRule=!0,h.createErrors=!1,h.opts.allErrors&&(f=h.opts.allErrors,h.opts.allErrors=!1),s+=" "+e.validate(h)+" ",h.createErrors=!0,f&&(h.opts.allErrors=f),e.compositeRule=h.compositeRule=g,s+=" if ("+p+") { ";var m=m||[];m.push(s),s="",!1!==e.createErrors?(s+=" { keyword: 'not' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: {} ",!1!==e.opts.messages&&(s+=" , message: 'should NOT be valid' "),e.opts.verbose&&(s+=" , schema: validate.schema"+n+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),s+=" } "):s+=" {} ";var v=s;s=m.pop(),!e.compositeRule&&d?e.async?s+=" throw new ValidationError(["+v+"]); ":s+=" validate.errors = ["+v+"]; return false; ":s+=" var err = "+v+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+=" } else { errors = "+u+"; if (vErrors !== null) { if ("+u+") vErrors.length = "+u+"; else vErrors = null; } ",e.opts.allErrors&&(s+=" } ")}else s+=" var err = ",!1!==e.createErrors?(s+=" { keyword: 'not' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: {} ",!1!==e.opts.messages&&(s+=" , message: 'should NOT be valid' "),e.opts.verbose&&(s+=" , schema: validate.schema"+n+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),s+=" } "):s+=" {} ",s+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",d&&(s+=" if (false) { ");return s}},13749:function(e,t){!function(e){"use strict";function t(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];if(t.length>1){t[0]=t[0].slice(0,-1);for(var s=t.length-1,i=1;i<s;++i)t[i]=t[i].slice(1,-1);return t[s]=t[s].slice(1),t.join("")}return t[0]}function r(e){return"(?:"+e+")"}function s(e){return void 0===e?"undefined":null===e?"null":Object.prototype.toString.call(e).split(" ").pop().split("]").shift().toLowerCase()}function i(e){return e.toUpperCase()}function a(e){var s="[A-Za-z]",i="[0-9]",a=t(i,"[A-Fa-f]"),o=r(r("%[EFef]"+a+"%"+a+a+"%"+a+a)+"|"+r("%[89A-Fa-f]"+a+"%"+a+a)+"|"+r("%"+a+a)),n="[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]",c=t("[\\:\\/\\?\\#\\[\\]\\@]",n),d=e?"[\\uE000-\\uF8FF]":"[]",l=t(s,i,"[\\-\\.\\_\\~]",e?"[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]":"[]"),u=r(s+t(s,i,"[\\+\\-\\.]")+"*"),h=r(r(o+"|"+t(l,n,"[\\:]"))+"*"),p=(r(r("25[0-5]")+"|"+r("2[0-4]"+i)+"|"+r("1"+i+i)+"|"+r("[1-9]"+i)+"|"+i),r(r("25[0-5]")+"|"+r("2[0-4]"+i)+"|"+r("1"+i+i)+"|"+r("0?[1-9]"+i)+"|0?0?"+i)),f=r(p+"\\."+p+"\\."+p+"\\."+p),g=r(a+"{1,4}"),m=r(r(g+"\\:"+g)+"|"+f),v=r(r(g+"\\:")+"{6}"+m),y=r("\\:\\:"+r(g+"\\:")+"{5}"+m),_=r(r(g)+"?\\:\\:"+r(g+"\\:")+"{4}"+m),w=r(r(r(g+"\\:")+"{0,1}"+g)+"?\\:\\:"+r(g+"\\:")+"{3}"+m),b=r(r(r(g+"\\:")+"{0,2}"+g)+"?\\:\\:"+r(g+"\\:")+"{2}"+m),S=r(r(r(g+"\\:")+"{0,3}"+g)+"?\\:\\:"+g+"\\:"+m),P=r(r(r(g+"\\:")+"{0,4}"+g)+"?\\:\\:"+m),E=r(r(r(g+"\\:")+"{0,5}"+g)+"?\\:\\:"+g),I=r(r(r(g+"\\:")+"{0,6}"+g)+"?\\:\\:"),k=r([v,y,_,w,b,S,P,E,I].join("|")),C=r(r(l+"|"+o)+"+"),D=(r(k+"\\%25"+C),r(k+r("\\%25|\\%(?!"+a+"{2})")+C)),O=r("[vV]"+a+"+\\."+t(l,n,"[\\:]")+"+"),A=r("\\["+r(D+"|"+k+"|"+O)+"\\]"),x=r(r(o+"|"+t(l,n))+"*"),T=r(A+"|"+f+"(?!"+x+")|"+x),R=r(i+"*"),$=r(r(h+"@")+"?"+T+r("\\:"+R)+"?"),j=r(o+"|"+t(l,n,"[\\:\\@]")),N=r(j+"*"),M=r(j+"+"),F=r(r(o+"|"+t(l,n,"[\\@]"))+"+"),K=r(r("\\/"+N)+"*"),q=r("\\/"+r(M+K)+"?"),L=r(F+K),U=r(M+K),V="(?!"+j+")",H=(r(K+"|"+q+"|"+L+"|"+U+"|"+V),r(r(j+"|"+t("[\\/\\?]",d))+"*")),B=r(r(j+"|[\\/\\?]")+"*"),z=r(r("\\/\\/"+$+K)+"|"+q+"|"+U+"|"+V),J=r(u+"\\:"+z+r("\\?"+H)+"?"+r("\\#"+B)+"?"),W=r(r("\\/\\/"+$+K)+"|"+q+"|"+L+"|"+V),Z=r(W+r("\\?"+H)+"?"+r("\\#"+B)+"?");return r(J+"|"+Z),r(u+"\\:"+z+r("\\?"+H)+"?"),r(r("\\/\\/("+r("("+h+")@")+"?("+T+")"+r("\\:("+R+")")+"?)")+"?("+K+"|"+q+"|"+U+"|"+V+")"),r("\\?("+H+")"),r("\\#("+B+")"),r(r("\\/\\/("+r("("+h+")@")+"?("+T+")"+r("\\:("+R+")")+"?)")+"?("+K+"|"+q+"|"+L+"|"+V+")"),r("\\?("+H+")"),r("\\#("+B+")"),r(r("\\/\\/("+r("("+h+")@")+"?("+T+")"+r("\\:("+R+")")+"?)")+"?("+K+"|"+q+"|"+U+"|"+V+")"),r("\\?("+H+")"),r("\\#("+B+")"),r("("+h+")@"),r("\\:("+R+")"),{NOT_SCHEME:new RegExp(t("[^]",s,i,"[\\+\\-\\.]"),"g"),NOT_USERINFO:new RegExp(t("[^\\%\\:]",l,n),"g"),NOT_HOST:new RegExp(t("[^\\%\\[\\]\\:]",l,n),"g"),NOT_PATH:new RegExp(t("[^\\%\\/\\:\\@]",l,n),"g"),NOT_PATH_NOSCHEME:new RegExp(t("[^\\%\\/\\@]",l,n),"g"),NOT_QUERY:new RegExp(t("[^\\%]",l,n,"[\\:\\@\\/\\?]",d),"g"),NOT_FRAGMENT:new RegExp(t("[^\\%]",l,n,"[\\:\\@\\/\\?]"),"g"),ESCAPE:new RegExp(t("[^]",l,n),"g"),UNRESERVED:new RegExp(l,"g"),OTHER_CHARS:new RegExp(t("[^\\%]",l,c),"g"),PCT_ENCODED:new RegExp(o,"g"),IPV4ADDRESS:new RegExp("^("+f+")$"),IPV6ADDRESS:new RegExp("^\\[?("+k+")"+r(r("\\%25|\\%(?!"+a+"{2})")+"("+C+")")+"?\\]?$")}}var o=a(!1),n=a(!0),c=function(e,t){if(Array.isArray(e))return e;if(Symbol.iterator in Object(e))return function(e,t){var r=[],s=!0,i=!1,a=void 0;try{for(var o,n=e[Symbol.iterator]();!(s=(o=n.next()).done)&&(r.push(o.value),!t||r.length!==t);s=!0);}catch(e){i=!0,a=e}finally{try{!s&&n.return&&n.return()}finally{if(i)throw a}}return r}(e,t);throw new TypeError("Invalid attempt to destructure non-iterable instance")},d=2147483647,l=36,u=/^xn--/,h=/[^\0-\x7E]/,p=/[\x2E\u3002\uFF0E\uFF61]/g,f={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},g=Math.floor,m=String.fromCharCode;function v(e){throw new RangeError(f[e])}function y(e,t){var r=e.split("@"),s="";return r.length>1&&(s=r[0]+"@",e=r[1]),s+function(e,t){for(var r=[],s=e.length;s--;)r[s]=t(e[s]);return r}((e=e.replace(p,".")).split("."),t).join(".")}function _(e){for(var t=[],r=0,s=e.length;r<s;){var i=e.charCodeAt(r++);if(i>=55296&&i<=56319&&r<s){var a=e.charCodeAt(r++);56320==(64512&a)?t.push(((1023&i)<<10)+(1023&a)+65536):(t.push(i),r--)}else t.push(i)}return t}var w=function(e){return e-48<10?e-22:e-65<26?e-65:e-97<26?e-97:l},b=function(e,t){return e+22+75*(e<26)-((0!=t)<<5)},S=function(e,t,r){var s=0;for(e=r?g(e/700):e>>1,e+=g(e/t);e>455;s+=l)e=g(e/35);return g(s+36*e/(e+38))},P=function(e){var t=[],r=e.length,s=0,i=128,a=72,o=e.lastIndexOf("-");o<0&&(o=0);for(var n=0;n<o;++n)e.charCodeAt(n)>=128&&v("not-basic"),t.push(e.charCodeAt(n));for(var c=o>0?o+1:0;c<r;){for(var u=s,h=1,p=l;;p+=l){c>=r&&v("invalid-input");var f=w(e.charCodeAt(c++));(f>=l||f>g((d-s)/h))&&v("overflow"),s+=f*h;var m=p<=a?1:p>=a+26?26:p-a;if(f<m)break;var y=l-m;h>g(d/y)&&v("overflow"),h*=y}var _=t.length+1;a=S(s-u,_,0==u),g(s/_)>d-i&&v("overflow"),i+=g(s/_),s%=_,t.splice(s++,0,i)}return String.fromCodePoint.apply(String,t)},E=function(e){var t=[],r=(e=_(e)).length,s=128,i=0,a=72,o=!0,n=!1,c=void 0;try{for(var u,h=e[Symbol.iterator]();!(o=(u=h.next()).done);o=!0){var p=u.value;p<128&&t.push(m(p))}}catch(e){n=!0,c=e}finally{try{!o&&h.return&&h.return()}finally{if(n)throw c}}var f=t.length,y=f;for(f&&t.push("-");y<r;){var w=d,P=!0,E=!1,I=void 0;try{for(var k,C=e[Symbol.iterator]();!(P=(k=C.next()).done);P=!0){var D=k.value;D>=s&&D<w&&(w=D)}}catch(e){E=!0,I=e}finally{try{!P&&C.return&&C.return()}finally{if(E)throw I}}var O=y+1;w-s>g((d-i)/O)&&v("overflow"),i+=(w-s)*O,s=w;var A=!0,x=!1,T=void 0;try{for(var R,$=e[Symbol.iterator]();!(A=(R=$.next()).done);A=!0){var j=R.value;if(j<s&&++i>d&&v("overflow"),j==s){for(var N=i,M=l;;M+=l){var F=M<=a?1:M>=a+26?26:M-a;if(N<F)break;var K=N-F,q=l-F;t.push(m(b(F+K%q,0))),N=g(K/q)}t.push(m(b(N,0))),a=S(i,O,y==f),i=0,++y}}}catch(e){x=!0,T=e}finally{try{!A&&$.return&&$.return()}finally{if(x)throw T}}++i,++s}return t.join("")},I=function(e){return y(e,function(e){return h.test(e)?"xn--"+E(e):e})},k=function(e){return y(e,function(e){return u.test(e)?P(e.slice(4).toLowerCase()):e})},C={};function D(e){var t=e.charCodeAt(0);return t<16?"%0"+t.toString(16).toUpperCase():t<128?"%"+t.toString(16).toUpperCase():t<2048?"%"+(t>>6|192).toString(16).toUpperCase()+"%"+(63&t|128).toString(16).toUpperCase():"%"+(t>>12|224).toString(16).toUpperCase()+"%"+(t>>6&63|128).toString(16).toUpperCase()+"%"+(63&t|128).toString(16).toUpperCase()}function O(e){for(var t="",r=0,s=e.length;r<s;){var i=parseInt(e.substr(r+1,2),16);if(i<128)t+=String.fromCharCode(i),r+=3;else if(i>=194&&i<224){if(s-r>=6){var a=parseInt(e.substr(r+4,2),16);t+=String.fromCharCode((31&i)<<6|63&a)}else t+=e.substr(r,6);r+=6}else if(i>=224){if(s-r>=9){var o=parseInt(e.substr(r+4,2),16),n=parseInt(e.substr(r+7,2),16);t+=String.fromCharCode((15&i)<<12|(63&o)<<6|63&n)}else t+=e.substr(r,9);r+=9}else t+=e.substr(r,3),r+=3}return t}function A(e,t){function r(e){var r=O(e);return r.match(t.UNRESERVED)?r:e}return e.scheme&&(e.scheme=String(e.scheme).replace(t.PCT_ENCODED,r).toLowerCase().replace(t.NOT_SCHEME,"")),void 0!==e.userinfo&&(e.userinfo=String(e.userinfo).replace(t.PCT_ENCODED,r).replace(t.NOT_USERINFO,D).replace(t.PCT_ENCODED,i)),void 0!==e.host&&(e.host=String(e.host).replace(t.PCT_ENCODED,r).toLowerCase().replace(t.NOT_HOST,D).replace(t.PCT_ENCODED,i)),void 0!==e.path&&(e.path=String(e.path).replace(t.PCT_ENCODED,r).replace(e.scheme?t.NOT_PATH:t.NOT_PATH_NOSCHEME,D).replace(t.PCT_ENCODED,i)),void 0!==e.query&&(e.query=String(e.query).replace(t.PCT_ENCODED,r).replace(t.NOT_QUERY,D).replace(t.PCT_ENCODED,i)),void 0!==e.fragment&&(e.fragment=String(e.fragment).replace(t.PCT_ENCODED,r).replace(t.NOT_FRAGMENT,D).replace(t.PCT_ENCODED,i)),e}function x(e){return e.replace(/^0*(.*)/,"$1")||"0"}function T(e,t){var r=e.match(t.IPV4ADDRESS)||[],s=c(r,2)[1];return s?s.split(".").map(x).join("."):e}function R(e,t){var r=e.match(t.IPV6ADDRESS)||[],s=c(r,3),i=s[1],a=s[2];if(i){for(var o=i.toLowerCase().split("::").reverse(),n=c(o,2),d=n[0],l=n[1],u=l?l.split(":").map(x):[],h=d.split(":").map(x),p=t.IPV4ADDRESS.test(h[h.length-1]),f=p?7:8,g=h.length-f,m=Array(f),v=0;v<f;++v)m[v]=u[v]||h[g+v]||"";p&&(m[f-1]=T(m[f-1],t));var y=m.reduce(function(e,t,r){if(!t||"0"===t){var s=e[e.length-1];s&&s.index+s.length===r?s.length++:e.push({index:r,length:1})}return e},[]).sort(function(e,t){return t.length-e.length})[0],_=void 0;if(y&&y.length>1){var w=m.slice(0,y.index),b=m.slice(y.index+y.length);_=w.join(":")+"::"+b.join(":")}else _=m.join(":");return a&&(_+="%"+a),_}return e}var $=/^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i,j=void 0==="".match(/(){0}/)[1];function N(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r={},s=!1!==t.iri?n:o;"suffix"===t.reference&&(e=(t.scheme?t.scheme+":":"")+"//"+e);var i=e.match($);if(i){j?(r.scheme=i[1],r.userinfo=i[3],r.host=i[4],r.port=parseInt(i[5],10),r.path=i[6]||"",r.query=i[7],r.fragment=i[8],isNaN(r.port)&&(r.port=i[5])):(r.scheme=i[1]||void 0,r.userinfo=-1!==e.indexOf("@")?i[3]:void 0,r.host=-1!==e.indexOf("//")?i[4]:void 0,r.port=parseInt(i[5],10),r.path=i[6]||"",r.query=-1!==e.indexOf("?")?i[7]:void 0,r.fragment=-1!==e.indexOf("#")?i[8]:void 0,isNaN(r.port)&&(r.port=e.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/)?i[4]:void 0)),r.host&&(r.host=R(T(r.host,s),s)),void 0!==r.scheme||void 0!==r.userinfo||void 0!==r.host||void 0!==r.port||r.path||void 0!==r.query?void 0===r.scheme?r.reference="relative":void 0===r.fragment?r.reference="absolute":r.reference="uri":r.reference="same-document",t.reference&&"suffix"!==t.reference&&t.reference!==r.reference&&(r.error=r.error||"URI is not a "+t.reference+" reference.");var a=C[(t.scheme||r.scheme||"").toLowerCase()];if(t.unicodeSupport||a&&a.unicodeSupport)A(r,s);else{if(r.host&&(t.domainHost||a&&a.domainHost))try{r.host=I(r.host.replace(s.PCT_ENCODED,O).toLowerCase())}catch(e){r.error=r.error||"Host's domain name can not be converted to ASCII via punycode: "+e}A(r,o)}a&&a.parse&&a.parse(r,t)}else r.error=r.error||"URI can not be parsed.";return r}var M=/^\.\.?\//,F=/^\/\.(\/|$)/,K=/^\/\.\.(\/|$)/,q=/^\/?(?:.|\n)*?(?=\/|$)/;function L(e){for(var t=[];e.length;)if(e.match(M))e=e.replace(M,"");else if(e.match(F))e=e.replace(F,"/");else if(e.match(K))e=e.replace(K,"/"),t.pop();else if("."===e||".."===e)e="";else{var r=e.match(q);if(!r)throw new Error("Unexpected dot segment condition");var s=r[0];e=e.slice(s.length),t.push(s)}return t.join("")}function U(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=t.iri?n:o,s=[],i=C[(t.scheme||e.scheme||"").toLowerCase()];if(i&&i.serialize&&i.serialize(e,t),e.host)if(r.IPV6ADDRESS.test(e.host));else if(t.domainHost||i&&i.domainHost)try{e.host=t.iri?k(e.host):I(e.host.replace(r.PCT_ENCODED,O).toLowerCase())}catch(r){e.error=e.error||"Host's domain name can not be converted to "+(t.iri?"Unicode":"ASCII")+" via punycode: "+r}A(e,r),"suffix"!==t.reference&&e.scheme&&(s.push(e.scheme),s.push(":"));var a=function(e,t){var r=!1!==t.iri?n:o,s=[];return void 0!==e.userinfo&&(s.push(e.userinfo),s.push("@")),void 0!==e.host&&s.push(R(T(String(e.host),r),r).replace(r.IPV6ADDRESS,function(e,t,r){return"["+t+(r?"%25"+r:"")+"]"})),"number"!=typeof e.port&&"string"!=typeof e.port||(s.push(":"),s.push(String(e.port))),s.length?s.join(""):void 0}(e,t);if(void 0!==a&&("suffix"!==t.reference&&s.push("//"),s.push(a),e.path&&"/"!==e.path.charAt(0)&&s.push("/")),void 0!==e.path){var c=e.path;t.absolutePath||i&&i.absolutePath||(c=L(c)),void 0===a&&(c=c.replace(/^\/\//,"/%2F")),s.push(c)}return void 0!==e.query&&(s.push("?"),s.push(e.query)),void 0!==e.fragment&&(s.push("#"),s.push(e.fragment)),s.join("")}function V(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},s={};return arguments[3]||(e=N(U(e,r),r),t=N(U(t,r),r)),!(r=r||{}).tolerant&&t.scheme?(s.scheme=t.scheme,s.userinfo=t.userinfo,s.host=t.host,s.port=t.port,s.path=L(t.path||""),s.query=t.query):(void 0!==t.userinfo||void 0!==t.host||void 0!==t.port?(s.userinfo=t.userinfo,s.host=t.host,s.port=t.port,s.path=L(t.path||""),s.query=t.query):(t.path?("/"===t.path.charAt(0)?s.path=L(t.path):(void 0===e.userinfo&&void 0===e.host&&void 0===e.port||e.path?e.path?s.path=e.path.slice(0,e.path.lastIndexOf("/")+1)+t.path:s.path=t.path:s.path="/"+t.path,s.path=L(s.path)),s.query=t.query):(s.path=e.path,void 0!==t.query?s.query=t.query:s.query=e.query),s.userinfo=e.userinfo,s.host=e.host,s.port=e.port),s.scheme=e.scheme),s.fragment=t.fragment,s}function H(e,t){return e&&e.toString().replace(t&&t.iri?n.PCT_ENCODED:o.PCT_ENCODED,O)}var B={scheme:"http",domainHost:!0,parse:function(e,t){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e},serialize:function(e,t){var r="https"===String(e.scheme).toLowerCase();return e.port!==(r?443:80)&&""!==e.port||(e.port=void 0),e.path||(e.path="/"),e}},z={scheme:"https",domainHost:B.domainHost,parse:B.parse,serialize:B.serialize};function J(e){return"boolean"==typeof e.secure?e.secure:"wss"===String(e.scheme).toLowerCase()}var W={scheme:"ws",domainHost:!0,parse:function(e,t){var r=e;return r.secure=J(r),r.resourceName=(r.path||"/")+(r.query?"?"+r.query:""),r.path=void 0,r.query=void 0,r},serialize:function(e,t){if(e.port!==(J(e)?443:80)&&""!==e.port||(e.port=void 0),"boolean"==typeof e.secure&&(e.scheme=e.secure?"wss":"ws",e.secure=void 0),e.resourceName){var r=e.resourceName.split("?"),s=c(r,2),i=s[0],a=s[1];e.path=i&&"/"!==i?i:void 0,e.query=a,e.resourceName=void 0}return e.fragment=void 0,e}},Z={scheme:"wss",domainHost:W.domainHost,parse:W.parse,serialize:W.serialize},Q={},G="[A-Za-z0-9\\-\\.\\_\\~\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]",Y="[0-9A-Fa-f]",X=r(r("%[EFef]"+Y+"%"+Y+Y+"%"+Y+Y)+"|"+r("%[89A-Fa-f]"+Y+"%"+Y+Y)+"|"+r("%"+Y+Y)),ee=t("[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]",'[\\"\\\\]'),te=new RegExp(G,"g"),re=new RegExp(X,"g"),se=new RegExp(t("[^]","[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]","[\\.]",'[\\"]',ee),"g"),ie=new RegExp(t("[^]",G,"[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]"),"g"),ae=ie;function oe(e){var t=O(e);return t.match(te)?t:e}var ne={scheme:"mailto",parse:function(e,t){var r=e,s=r.to=r.path?r.path.split(","):[];if(r.path=void 0,r.query){for(var i=!1,a={},o=r.query.split("&"),n=0,c=o.length;n<c;++n){var d=o[n].split("=");switch(d[0]){case"to":for(var l=d[1].split(","),u=0,h=l.length;u<h;++u)s.push(l[u]);break;case"subject":r.subject=H(d[1],t);break;case"body":r.body=H(d[1],t);break;default:i=!0,a[H(d[0],t)]=H(d[1],t)}}i&&(r.headers=a)}r.query=void 0;for(var p=0,f=s.length;p<f;++p){var g=s[p].split("@");if(g[0]=H(g[0]),t.unicodeSupport)g[1]=H(g[1],t).toLowerCase();else try{g[1]=I(H(g[1],t).toLowerCase())}catch(e){r.error=r.error||"Email address's domain name can not be converted to ASCII via punycode: "+e}s[p]=g.join("@")}return r},serialize:function(e,t){var r,s=e,a=null!=(r=e.to)?r instanceof Array?r:"number"!=typeof r.length||r.split||r.setInterval||r.call?[r]:Array.prototype.slice.call(r):[];if(a){for(var o=0,n=a.length;o<n;++o){var c=String(a[o]),d=c.lastIndexOf("@"),l=c.slice(0,d).replace(re,oe).replace(re,i).replace(se,D),u=c.slice(d+1);try{u=t.iri?k(u):I(H(u,t).toLowerCase())}catch(e){s.error=s.error||"Email address's domain name can not be converted to "+(t.iri?"Unicode":"ASCII")+" via punycode: "+e}a[o]=l+"@"+u}s.path=a.join(",")}var h=e.headers=e.headers||{};e.subject&&(h.subject=e.subject),e.body&&(h.body=e.body);var p=[];for(var f in h)h[f]!==Q[f]&&p.push(f.replace(re,oe).replace(re,i).replace(ie,D)+"="+h[f].replace(re,oe).replace(re,i).replace(ae,D));return p.length&&(s.query=p.join("&")),s}},ce=/^([^\:]+)\:(.*)/,de={scheme:"urn",parse:function(e,t){var r=e.path&&e.path.match(ce),s=e;if(r){var i=t.scheme||s.scheme||"urn",a=r[1].toLowerCase(),o=r[2],n=i+":"+(t.nid||a),c=C[n];s.nid=a,s.nss=o,s.path=void 0,c&&(s=c.parse(s,t))}else s.error=s.error||"URN can not be parsed.";return s},serialize:function(e,t){var r=t.scheme||e.scheme||"urn",s=e.nid,i=r+":"+(t.nid||s),a=C[i];a&&(e=a.serialize(e,t));var o=e,n=e.nss;return o.path=(s||t.nid)+":"+n,o}},le=/^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/,ue={scheme:"urn:uuid",parse:function(e,t){var r=e;return r.uuid=r.nss,r.nss=void 0,t.tolerant||r.uuid&&r.uuid.match(le)||(r.error=r.error||"UUID is not valid."),r},serialize:function(e,t){var r=e;return r.nss=(e.uuid||"").toLowerCase(),r}};C[B.scheme]=B,C[z.scheme]=z,C[W.scheme]=W,C[Z.scheme]=Z,C[ne.scheme]=ne,C[de.scheme]=de,C[ue.scheme]=ue,e.SCHEMES=C,e.pctEncChar=D,e.pctDecChars=O,e.parse=N,e.removeDotSegments=L,e.serialize=U,e.resolveComponents=V,e.resolve=function(e,t,r){var s=function(e,t){var r=e;if(t)for(var s in t)r[s]=t[s];return r}({scheme:"null"},r);return U(V(N(e,s),N(t,s),s,!0),s)},e.normalize=function(e,t){return"string"==typeof e?e=U(N(e,t),t):"object"===s(e)&&(e=N(U(e,t),t)),e},e.equal=function(e,t,r){return"string"==typeof e?e=U(N(e,r),r):"object"===s(e)&&(e=U(e,r)),"string"==typeof t?t=U(N(t,r),r):"object"===s(t)&&(t=U(t,r)),e===t},e.escapeComponent=function(e,t){return e&&e.toString().replace(t&&t.iri?n.ESCAPE:o.ESCAPE,D)},e.unescapeComponent=H,Object.defineProperty(e,"__esModule",{value:!0})}(t)},14547:e=>{"use strict";e.exports=function(e,t,r){var s=" ",i=e.level,a=e.dataLevel,o=e.schema[t],n=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,d=!e.opts.allErrors,l="data"+(a||""),u="valid"+i,h="errs__"+i,p=e.util.copy(e),f="";p.level++;var g="valid"+p.level,m=o.every(function(t){return e.opts.strictKeywords?"object"==typeof t&&Object.keys(t).length>0||!1===t:e.util.schemaHasRules(t,e.RULES.all)});if(m){var v=p.baseId;s+=" var "+h+" = errors; var "+u+" = false; ";var y=e.compositeRule;e.compositeRule=p.compositeRule=!0;var _=o;if(_)for(var w,b=-1,S=_.length-1;b<S;)w=_[b+=1],p.schema=w,p.schemaPath=n+"["+b+"]",p.errSchemaPath=c+"/"+b,s+=" "+e.validate(p)+" ",p.baseId=v,s+=" "+u+" = "+u+" || "+g+"; if (!"+u+") { ",f+="}";e.compositeRule=p.compositeRule=y,s+=" "+f+" if (!"+u+") { var err = ",!1!==e.createErrors?(s+=" { keyword: 'anyOf' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: {} ",!1!==e.opts.messages&&(s+=" , message: 'should match some schema in anyOf' "),e.opts.verbose&&(s+=" , schema: validate.schema"+n+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),s+=" } "):s+=" {} ",s+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&d&&(e.async?s+=" throw new ValidationError(vErrors); ":s+=" validate.errors = vErrors; return false; "),s+=" } else { errors = "+h+"; if (vErrors !== null) { if ("+h+") vErrors.length = "+h+"; else vErrors = null; } ",e.opts.allErrors&&(s+=" } ")}else d&&(s+=" if (true) { ");return s}},16928:e=>{"use strict";e.exports=require("path")},17214:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OAUTH_CORS_HEADERS=t.PREFLIGHT_CORS_HEADERS=t.MCP_CORS_HEADERS=t.WELL_KNOWN_CORS_HEADERS=void 0,t.mergeCORSHeaders=function(e,r=t.WELL_KNOWN_CORS_HEADERS){return{...e,...r}},t.applyCORSHeaders=function(e,r=t.MCP_CORS_HEADERS){Object.entries(r).forEach(([t,r])=>{void 0!==r&&e.setHeader(t,r)})},t.WELL_KNOWN_CORS_HEADERS={"Access-Control-Allow-Origin":"*",Vary:"Origin"},t.MCP_CORS_HEADERS={"Access-Control-Allow-Origin":"*","Access-Control-Expose-Headers":"mcp-session-id",Vary:"Origin"},t.PREFLIGHT_CORS_HEADERS={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, mcp-session-id, mcp-protocol-version",Vary:"Origin"},t.OAUTH_CORS_HEADERS={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, Accept, mcp-protocol-version","Access-Control-Expose-Headers":"Content-Type",Vary:"Origin"}},20698:(e,t,r)=>{"use strict";var s=r(52004),i=r(9717).toHash;e.exports=function(){var e=[{type:"number",rules:[{maximum:["exclusiveMaximum"]},{minimum:["exclusiveMinimum"]},"multipleOf","format"]},{type:"string",rules:["maxLength","minLength","pattern","format"]},{type:"array",rules:["maxItems","minItems","items","contains","uniqueItems"]},{type:"object",rules:["maxProperties","minProperties","required","dependencies","propertyNames",{properties:["additionalProperties","patternProperties"]}]},{rules:["$ref","const","enum","not","anyOf","oneOf","allOf","if"]}],t=["type","$comment"];return e.all=i(t),e.types=i(["number","integer","string","array","object","boolean","null"]),e.forEach(function(r){r.rules=r.rules.map(function(r){var i;if("object"==typeof r){var a=Object.keys(r)[0];i=r[a],r=a,i.forEach(function(r){t.push(r),e.all[r]=!0})}return t.push(r),e.all[r]={keyword:r,code:s[r],implements:i}}),e.all.$comment={keyword:"$comment",code:s.$comment},r.type&&(e.types[r.type]=r)}),e.keywords=i(t.concat(["$schema","$id","id","$data","$async","title","description","default","definitions","examples","readOnly","writeOnly","contentMediaType","contentEncoding","additionalItems","then","else"])),e.custom={},e}},20812:(e,t,r)=>{"use strict";var s=r(9717);e.exports=function(e){s.copy(e,this)}},22853:(e,t,r)=>{"use strict";var s=r(40985),i=r(9717),a=r(72916),o=r(56039),n=r(25572),c=i.ucs2length,d=r(67371),l=a.Validation;function u(e,t,r){var s=p.call(this,e,t,r);return s>=0?{index:s,compiling:!0}:(s=this._compilations.length,this._compilations[s]={schema:e,root:t,baseId:r},{index:s,compiling:!1})}function h(e,t,r){var s=p.call(this,e,t,r);s>=0&&this._compilations.splice(s,1)}function p(e,t,r){for(var s=0;s<this._compilations.length;s++){var i=this._compilations[s];if(i.schema==e&&i.root==t&&i.baseId==r)return s}return-1}function f(e,t){return"var pattern"+e+" = new RegExp("+i.toQuotedString(t[e])+");"}function g(e){return"var default"+e+" = defaults["+e+"];"}function m(e,t){return void 0===t[e]?"":"var refVal"+e+" = refVal["+e+"];"}function v(e){return"var customRule"+e+" = customRules["+e+"];"}function y(e,t){if(!e.length)return"";for(var r="",s=0;s<e.length;s++)r+=t(s,e);return r}e.exports=function e(t,r,p,_){var w=this,b=this._opts,S=[void 0],P={},E=[],I={},k=[],C={},D=[];r=r||{schema:t,refVal:S,refs:P};var O=u.call(this,t,r,_),A=this._compilations[O.index];if(O.compiling)return A.callValidate=function e(){var t=A.validate,r=t.apply(this,arguments);return e.errors=t.errors,r};var x=this._formats,T=this.RULES;try{var R=j(t,r,p,_);A.validate=R;var $=A.callValidate;return $&&($.schema=R.schema,$.errors=null,$.refs=R.refs,$.refVal=R.refVal,$.root=R.root,$.$async=R.$async,b.sourceCode&&($.source=R.source)),R}finally{h.call(this,t,r,_)}function j(t,o,u,h){var p=!o||o&&o.schema==t;if(o.schema!=r.schema)return e.call(w,t,o,u,h);var _,I=!0===t.$async,C=n({isTop:!0,schema:t,isRoot:p,baseId:h,root:o,schemaPath:"",errSchemaPath:"#",errorPath:'""',MissingRefError:a.MissingRef,RULES:T,validate:n,util:i,resolve:s,resolveRef:N,usePattern:K,useDefault:q,useCustomRule:L,opts:b,formats:x,logger:w.logger,self:w});C=y(S,m)+y(E,f)+y(k,g)+y(D,v)+C,b.processCode&&(C=b.processCode(C,t));try{_=new Function("self","RULES","formats","root","refVal","defaults","customRules","equal","ucs2length","ValidationError",C)(w,T,x,r,S,k,D,d,c,l),S[0]=_}catch(e){throw w.logger.error("Error compiling schema, function code:",C),e}return _.schema=t,_.errors=null,_.refs=P,_.refVal=S,_.root=p?_:o,I&&(_.$async=!0),!0===b.sourceCode&&(_.source={code:C,patterns:E,defaults:k}),_}function N(t,i,a){i=s.url(t,i);var o,n,c=P[i];if(void 0!==c)return F(o=S[c],n="refVal["+c+"]");if(!a&&r.refs){var d=r.refs[i];if(void 0!==d)return F(o=r.refVal[d],n=M(i,o))}n=M(i);var l=s.call(w,j,r,i);if(void 0===l){var u=p&&p[i];u&&(l=s.inlineRef(u,b.inlineRefs)?u:e.call(w,u,r,p,t))}if(void 0!==l)return function(e,t){var r=P[e];S[r]=t}(i,l),F(l,n);!function(e){delete P[e]}(i)}function M(e,t){var r=S.length;return S[r]=t,P[e]=r,"refVal"+r}function F(e,t){return"object"==typeof e||"boolean"==typeof e?{code:t,schema:e,inline:!0}:{code:t,$async:e&&!!e.$async}}function K(e){var t=I[e];return void 0===t&&(t=I[e]=E.length,E[t]=e),"pattern"+t}function q(e){switch(typeof e){case"boolean":case"number":return""+e;case"string":return i.toQuotedString(e);case"object":if(null===e)return"null";var t=o(e),r=C[t];return void 0===r&&(r=C[t]=k.length,k[r]=e),"default"+r}}function L(e,t,r,s){if(!1!==w._opts.validateSchema){var i=e.definition.dependencies;if(i&&!i.every(function(e){return Object.prototype.hasOwnProperty.call(r,e)}))throw new Error("parent schema must have all required keywords: "+i.join(","));var a=e.definition.validateSchema;if(a&&!a(t)){var o="keyword schema is invalid: "+w.errorsText(a.errors);if("log"!=w._opts.validateSchema)throw new Error(o);w.logger.error(o)}}var n,c=e.definition.compile,d=e.definition.inline,l=e.definition.macro;if(c)n=c.call(w,t,r,s);else if(l)n=l.call(w,t,r,s),!1!==b.validateSchema&&w.validateSchema(n,!0);else if(d)n=d.call(w,s,e.keyword,t,r);else if(!(n=e.definition.validate))return;if(void 0===n)throw new Error('custom keyword "'+e.keyword+'"failed to compile');var u=D.length;return D[u]=n,{code:"customRule"+u,validate:n}}}},23137:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MCPIRuntimeBase=void 0;const s=r(4901),i=r(81296),a=r(82906),o=r(65067);t.MCPIRuntimeBase=class{crypto;clock;fetch;storage;nonceCache;identity;config;cachedIdentity;sessions=new Map;lastProof;userDidManager;interceptedCalls=new Map;cryptoService;proofVerifier;accessControlService;constructor(e){this.config=e,this.crypto=e.cryptoProvider,this.clock=e.clockProvider,this.fetch=e.fetchProvider,this.storage=e.storageProvider,this.nonceCache=e.nonceCacheProvider,this.identity=e.identityProvider,this.cryptoService=new i.CryptoService(this.crypto)}async initialize(){this.cachedIdentity=await this.identity.getIdentity(),this.config.identity?.generateUserDids&&(this.userDidManager=new o.UserDidManager({crypto:this.crypto,storage:this.config.identity?.userDidStorage?{get:async e=>await this.storage.get(`userDid:${e}`),set:async(e,t,r)=>{await this.storage.set(`userDid:${e}`,t)},delete:async e=>await this.storage.delete(`userDid:${e}`)}:void 0,useDidWeb:"persistent"===this.config.identity?.userDidStorage})),"initialize"in this.nonceCache&&"function"==typeof this.nonceCache.initialize&&await this.nonceCache.initialize(),this.config.audit?.enabled&&this.logAudit("runtime_initialized",{did:this.cachedIdentity.did,environment:this.config.environment||"development",userDidGeneration:this.config.identity?.generateUserDids?"enabled":"disabled"})}async getIdentity(){return this.cachedIdentity||(this.cachedIdentity=await this.identity.getIdentity()),this.cachedIdentity}async handleHandshake(e){const t=await this.getIdentity(),r=this.clock.now(),s=await this.generateSessionId();let i;if(this.userDidManager)try{const t=e.oauthIdentity;i=await this.userDidManager.getOrCreateUserDid(s,t),this.config.audit?.enabled&&console.log("[MCP-I] Generated user DID for session:",{userDid:i.substring(0,20)+"...",hasOAuth:!!t,provider:t?.provider})}catch(e){console.warn("[MCP-I] Failed to generate user DID:",e)}const a=e=>{if("string"!=typeof e)return;const t=e.trim();return t.length>0?t:void 0},o=a(e.clientProtocolVersion),n=e.clientCapabilities,c=e.clientInfo,d=c||"string"==typeof o||void 0!==n?{name:a(c?.name)??"unknown",title:a(c?.title),version:a(c?.version),platform:a(c?.platform),vendor:a(c?.vendor),persistentId:a(c?.persistentId),clientId:a(c?.clientId)??crypto.randomUUID(),protocolVersion:o,capabilities:n}:void 0,l={id:s,clientDid:e.clientDid||i,userDid:i,agentDid:e.agentDid,serverDid:t.did,audience:e.audience,createdAt:r,expiresAt:this.clock.calculateExpiry(60*(this.config.session?.ttlMinutes||30)),clientInfo:d};this.sessions.set(s,l);const u={sessionId:s,agentDid:t.did,timestamp:r,capabilities:["identity","proof","audit"],...i&&{userDid:i}},h=await this.signData(u);return{...u,signature:h}}async processToolCall(e,t,r,i){if(this.config.toolProtectionService){const r=await this.getIdentity();this.config.audit?.enabled&&console.log("[MCP-I] Checking tool protection:",{tool:e,agentDid:r.did.slice(0,20)+"...",hasDelegation:!(!i?.delegationToken&&!i?.consentProof)});const o=await this.config.toolProtectionService.checkToolProtection(e,r.did);if(o){if(!i?.delegationToken&&!i?.consentProof){const a={toolName:e,args:t,sessionId:i?.id||"unknown",timestamp:this.clock.now(),expiresAt:this.clock.calculateExpiry(1800)},n=this.generateResumeToken(a),c=this.buildConsentUrl(e,o.requiredScopes,i,n),d=new s.DelegationRequiredError(e,o.requiredScopes,c,a,n);throw this.interceptedCalls.set(n,a),this.cleanupExpiredInterceptedCalls(),this.config.audit?.enabled&&console.warn("[MCP-I] BLOCKED: Tool requires delegation but none provided",{tool:e,requiredScopes:o.requiredScopes,agentDid:r.did.slice(0,20)+"...",resumeToken:d.resumeToken,consentUrl:c}),d}const n=i?.delegationToken,c=i?.consentProof;if(this.accessControlService)try{this.config.audit?.enabled&&console.log("[MCP-I] 🔐 Verifying delegation token with AccessControlApiService",{tool:e,agentDid:r.did.slice(0,20)+"...",hasDelegationToken:!!n,hasConsentProof:!!c,requiredScopes:o.requiredScopes});const a={agent_did:r.did,scopes:o.requiredScopes};n?a.delegation_token=n:c&&(a.credential_jwt=c),a.timestamp=this.clock.now(),(i?.clientDid||i?.clientId)&&(a.client_info={origin:i?.serverOrigin,user_agent:i?.userAgent});const d=await this.accessControlService.verifyDelegation(a,{delegationToken:n||void 0,credentialJwt:c||void 0});if(!d.data.valid){const a=d.data.reason||"Delegation token invalid or expired",n=d.data.error;this.config.audit?.enabled&&console.error("[MCP-I] ❌ Delegation verification FAILED",{tool:e,agentDid:r.did.slice(0,20)+"...",reason:a,errorCode:n?.code,errorMessage:n?.message,requiredScopes:o.requiredScopes});const c={toolName:e,args:t,sessionId:i?.id||"unknown",timestamp:this.clock.now(),expiresAt:this.clock.calculateExpiry(1800)},l=this.generateResumeToken(c),u=this.buildConsentUrl(e,o.requiredScopes,i,l);throw this.interceptedCalls.set(l,c),this.cleanupExpiredInterceptedCalls(),new s.DelegationRequiredError(e,o.requiredScopes,u,c,l)}const l=d.data.credential,u=l?.user_identifier,h=i?.userDid;if(u&&h){if(u!==h){u.substring(0,20),h.substring(0,20),this.config.audit?.enabled&&console.error("[MCP-I] 🔒 SECURITY: User identifier validation FAILED",{tool:e,agentDid:r.did.slice(0,20)+"...",delegationUserIdentifier:u.substring(0,20)+"...",sessionUserDid:h.substring(0,20)+"...",sessionId:i?.id?.substring(0,20)+"...",reason:"user_identifier_mismatch",severity:"high"});const a={toolName:e,args:t,sessionId:i?.id||"unknown",timestamp:this.clock.now(),expiresAt:this.clock.calculateExpiry(1800)},n=this.generateResumeToken(a),c=this.buildConsentUrl(e,o.requiredScopes,i,n);throw this.interceptedCalls.set(n,a),this.cleanupExpiredInterceptedCalls(),new s.DelegationRequiredError(e,o.requiredScopes,c,a,n)}this.config.audit?.enabled&&console.log("[MCP-I] ✅ User identifier validation PASSED",{tool:e,agentDid:r.did.slice(0,20)+"...",userDid:h.substring(0,20)+"...",sessionId:i?.id?.substring(0,20)+"..."})}else u&&!h&&this.config.audit?.enabled&&console.warn("[MCP-I] ⚠️ Delegation has user_identifier but session missing userDid",{tool:e,agentDid:r.did.slice(0,20)+"...",delegationUserIdentifier:u.substring(0,20)+"...",sessionId:i?.id?.substring(0,20)+"..."});this.config.audit?.enabled&&console.log("[MCP-I] ✅ Delegation verification SUCCEEDED",{tool:e,agentDid:r.did.slice(0,20)+"...",delegationId:d.data.delegation_id,credentialScopes:d.data.credential?.scopes,requiredScopes:o.requiredScopes})}catch(n){if(n instanceof s.DelegationRequiredError)throw n;if(n instanceof a.AgentShieldAPIError){this.config.audit?.enabled&&console.error("[MCP-I] ❌ Delegation verification error (API failure)",{tool:e,agentDid:r.did.slice(0,20)+"...",errorCode:n.code,errorMessage:n.message,errorDetails:n.details});const a={toolName:e,args:t,sessionId:i?.id||"unknown",timestamp:this.clock.now(),expiresAt:this.clock.calculateExpiry(1800)},c=this.generateResumeToken(a),d=this.buildConsentUrl(e,o.requiredScopes,i,c);throw this.interceptedCalls.set(c,a),this.cleanupExpiredInterceptedCalls(),new s.DelegationRequiredError(e,o.requiredScopes,d,a,c)}this.config.audit?.enabled&&console.error("[MCP-I] ❌ Unexpected error during delegation verification",{tool:e,agentDid:r.did.slice(0,20)+"...",error:n.message||String(n),errorStack:n.stack});const c={toolName:e,args:t,sessionId:i?.id||"unknown",timestamp:this.clock.now(),expiresAt:this.clock.calculateExpiry(1800)},d=this.generateResumeToken(c),l=this.buildConsentUrl(e,o.requiredScopes,i,d);throw this.interceptedCalls.set(d,c),this.cleanupExpiredInterceptedCalls(),new s.DelegationRequiredError(e,o.requiredScopes,l,c,d)}else this.config.audit?.enabled&&console.warn("[MCP-I] ⚠️ Delegation token provided but AccessControlApiService not configured - skipping verification",{tool:e,agentDid:r.did.slice(0,20)+"...",hasDelegationToken:!!n,hasConsentProof:!!c})}else this.config.audit?.enabled&&console.log("[MCP-I] Tool protection check passed (no delegation required)",{tool:e,agentDid:r.did.slice(0,20)+"...",reason:"Tool not configured to require delegation"})}const o=await r(t),n=await this.createProof(o,i);return this.lastProof=n,this.config.audit?.enabled&&this.logAudit("tool_executed",{tool:e,sessionId:i?.id,timestamp:this.clock.now()}),o}async resumeToolCall(e,t,r){const s=this.interceptedCalls.get(e);if(!s)throw new Error(`Invalid or expired resume token: ${e}`);if(this.clock.hasExpired(s.expiresAt))throw this.interceptedCalls.delete(e),new Error(`Resume token expired: ${e}`);const i=this.sessions.get(s.sessionId);if(!i)throw new Error(`Session not found for intercepted call: ${s.sessionId}`);const a={...i,delegationToken:r},o=await this.processToolCall(s.toolName,s.args,t,a);return this.interceptedCalls.delete(e),o}generateResumeToken(e){const t=JSON.stringify({tool:e.toolName,args:e.args,sessionId:e.sessionId,timestamp:e.timestamp});let r=0;for(let e=0;e<t.length;e++)r=(r<<5)-r+t.charCodeAt(e),r&=r;return`resume_${Math.abs(r).toString(36)}_${Date.now().toString(36)}`}cleanupExpiredInterceptedCalls(){this.clock.now();for(const[e,t]of this.interceptedCalls.entries())this.clock.hasExpired(t.expiresAt)&&this.interceptedCalls.delete(e)}buildConsentUrl(e,t,r,s,i){const a=new URLSearchParams({tool:e,scopes:t.join(","),session_id:r?.id||"",agent_did:r?.agentDid||""});return i&&a.set("project_id",i),s&&a.set("resume_token",s),`https://kya.vouched.id/bouncer/consent?${a.toString()}`}async issueNonce(e){const t=await this.generateNonce(),r=this.sessions.get(e),s=r?.agentDid||(await this.getIdentity()).did;return await this.nonceCache.add(t,300,s),t}async createProof(e,t){const r=await this.getIdentity(),s=this.clock.now();let i;if(t?.nonce)i=t.nonce;else{i=await this.generateNonce();const e=t?.agentDid||r.did;await this.nonceCache.add(i,300,e)}const a={data:e,timestamp:s,nonce:i,did:r.did,sessionId:t?.id,audience:t?.audience},o=await this.signData(a);return{timestamp:s,nonce:i,did:r.did,signature:o,algorithm:"Ed25519",sessionId:t?.id,audience:t?.audience}}async verifyProof(e,t){if(!(e&&"object"==typeof e&&"jws"in e&&"meta"in e))return this.verifyProofLegacy(e,t);{const r=e,s=t;if(!this.proofVerifier)return console.warn("[MCPIRuntimeBase] ProofVerifier not available, using fallback verification"),this.verifyProofLegacy(e,t);try{const e=await this.fetch.resolveDID(r.meta.did),t=this.extractPublicKeyJwk(e,r.meta.kid);if(!t)return console.error("[MCPIRuntimeBase] Failed to extract public key JWK"),!1;const i=await this.proofVerifier.verifyProof(r,t);if(i.valid&&s){const e=this.proofVerifier.buildCanonicalPayload(r.meta);s.canonicalPayload=e}return i.valid}catch(e){return console.error("[MCPIRuntimeBase] Proof verification failed:",e),!1}}}async verifyProofLegacy(e,t){try{if(await this.nonceCache.has(t.nonce,t.did))return!1;if(!this.clock.isWithinSkew(t.timestamp,this.config.session?.timestampSkewSeconds||120))return!1;const r=await this.fetch.resolveDID(t.did),s=this.extractPublicKey(r),i={data:e,timestamp:t.timestamp,nonce:t.nonce,did:t.did,sessionId:t.sessionId},a=(new TextEncoder).encode(JSON.stringify(i)),o=this.base64ToBytes(t.signature),n=await this.crypto.verify(a,o,s);if(n){const e=60*(this.config.session?.ttlMinutes||30);await this.nonceCache.add(t.nonce,e,t.did)}return n}catch(e){return console.error("Proof verification failed:",e),!1}}async verifyProofJWS(e,t,r){if(!this.cryptoService)return console.error("[MCPIRuntimeBase] CryptoService not initialized"),!1;try{const s=void 0!==r?{detachedPayload:r}:void 0;return await this.cryptoService.verifyJWS(e,t,s)}catch(e){return console.error("[MCPIRuntimeBase] JWS verification failed:",e),!1}}async getCurrentSession(){for(const[e,t]of this.sessions)if(!this.clock.hasExpired(t.expiresAt))return t;return null}getLastProof(){return this.lastProof}createWellKnownHandler(e){return async t=>{const r=await this.getIdentity();if("/.well-known/did.json"===t){const e=this.createDIDDocument(r);return{status:200,headers:{"Content-Type":"application/did+json","Cache-Control":"production"===this.config.environment?"public, max-age=300":"no-store"},body:JSON.stringify(e,null,2)}}if("/.well-known/agent.json"===t){const t={id:r.did,capabilities:{"mcp-i":["handshake","signing","verification"]}};return(e?.serviceName||e?.serviceEndpoint)&&(t.metadata={...e?.serviceName&&{name:e.serviceName},...e?.serviceEndpoint&&{serviceEndpoint:e.serviceEndpoint}}),{status:200,headers:{"Content-Type":"application/json","Cache-Control":"production"===this.config.environment?"public, max-age=300":"no-store"},body:JSON.stringify(t,null,2)}}return"/.well-known/mcp-identity"===t?{did:r.did,publicKey:r.publicKey,serviceName:e?.serviceName||"MCP-I Service",serviceEndpoint:e?.serviceEndpoint||"https://example.com",timestamp:this.clock.now()}:null}}createDebugEndpoint(){return"production"===this.config.environment?null:async()=>{const e=await this.getIdentity(),t=await this.getCurrentSession();return{identity:{did:e.did,publicKey:e.publicKey},session:t,config:{environment:this.config.environment,timestampSkewSeconds:this.config.session?.timestampSkewSeconds,sessionTtlMinutes:this.config.session?.ttlMinutes},timestamp:this.clock.now()}}}getAuditLogger(){return{log:(e,t)=>this.logAudit(e,t)}}async rotateKeys(){const e=this.cachedIdentity?.did,t=await this.identity.rotateKeys();return this.cachedIdentity=t,this.config.audit?.enabled&&this.logAudit("keys_rotated",{oldDid:e,newDid:t.did,timestamp:this.clock.now()}),t}async signData(e){const t=await this.getIdentity(),r=(new TextEncoder).encode(JSON.stringify(e)),s=await this.crypto.sign(r,t.privateKey);return this.bytesToBase64(s)}async generateNonce(){const e=await this.crypto.randomBytes(32);return this.bytesToBase64(e)}async generateSessionId(){const e=await this.crypto.randomBytes(16);return this.bytesToHex(e)}logAudit(e,t){if(!this.config.audit?.enabled)return;const r={event:e,data:this.config.audit.includePayloads?t:void 0,timestamp:this.clock.now(),timestampFormatted:this.clock.format(this.clock.now())},s=JSON.stringify(r);this.config.audit.logFunction?this.config.audit.logFunction(s):console.log("[AUDIT]",s)}createDIDDocument(e){return{"@context":["https://www.w3.org/ns/did/v1"],id:e.did,verificationMethod:[{id:`${e.did}#key-1`,type:"Ed25519VerificationKey2020",controller:e.did,publicKeyBase64:e.publicKey}],authentication:[`${e.did}#key-1`],assertionMethod:[`${e.did}#key-1`]}}extractPublicKey(e){const t=e.verificationMethod?.[0];if(t?.publicKeyBase64)return t.publicKeyBase64;if(t?.publicKeyMultibase)return t.publicKeyMultibase;throw new Error("Public key not found in DID document")}extractPublicKeyJwk(e,t){const r=e.verificationMethod?.find(e=>{const r="Ed25519VerificationKey2020"===e.type||"JsonWebKey2020"===e.type,s=!t||e.id===t||e.id.endsWith(`#${t}`);return r&&s})||e.verificationMethod?.[0];if(r?.publicKeyJwk){const e=r.publicKeyJwk;if("OKP"===e.kty&&"Ed25519"===e.crv)return e}return r?.publicKeyMultibase?(console.warn("[MCPIRuntimeBase] Multibase to JWK conversion not fully implemented"),null):null}bytesToBase64(e){return Buffer.from(e).toString("base64")}base64ToBytes(e){return new Uint8Array(Buffer.from(e,"base64"))}bytesToHex(e){return Buffer.from(e).toString("hex")}}},24235:e=>{"use strict";e.exports=function(e,t,r){var s=" ",i=e.level,a=e.dataLevel,o=e.schema[t],n=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,d=!e.opts.allErrors,l="data"+(a||""),u="valid"+i,h="errs__"+i,p=e.util.copy(e);p.level++;var f="valid"+p.level,g="i"+i,m=p.dataLevel=e.dataLevel+1,v="data"+m,y=e.baseId,_=e.opts.strictKeywords?"object"==typeof o&&Object.keys(o).length>0||!1===o:e.util.schemaHasRules(o,e.RULES.all);if(s+="var "+h+" = errors;var "+u+";",_){var w=e.compositeRule;e.compositeRule=p.compositeRule=!0,p.schema=o,p.schemaPath=n,p.errSchemaPath=c,s+=" var "+f+" = false; for (var "+g+" = 0; "+g+" < "+l+".length; "+g+"++) { ",p.errorPath=e.util.getPathExpr(e.errorPath,g,e.opts.jsonPointers,!0);var b=l+"["+g+"]";p.dataPathArr[m]=g;var S=e.validate(p);p.baseId=y,e.util.varOccurences(S,v)<2?s+=" "+e.util.varReplace(S,v,b)+" ":s+=" var "+v+" = "+b+"; "+S+" ",s+=" if ("+f+") break; } ",e.compositeRule=p.compositeRule=w,s+=" if (!"+f+") {"}else s+=" if ("+l+".length == 0) {";var P=P||[];P.push(s),s="",!1!==e.createErrors?(s+=" { keyword: 'contains' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: {} ",!1!==e.opts.messages&&(s+=" , message: 'should contain a valid item' "),e.opts.verbose&&(s+=" , schema: validate.schema"+n+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),s+=" } "):s+=" {} ";var E=s;return s=P.pop(),!e.compositeRule&&d?e.async?s+=" throw new ValidationError(["+E+"]); ":s+=" validate.errors = ["+E+"]; return false; ":s+=" var err = "+E+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+=" } else { ",_&&(s+=" errors = "+h+"; if (vErrors !== null) { if ("+h+") vErrors.length = "+h+"; else vErrors = null; } "),e.opts.allErrors&&(s+=" } "),s}},24886:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CascadingRevocationManager=void 0,t.createCascadingRevocationManager=function(e,t){return new r(e,t)};class r{graph;statusList;constructor(e,t){this.graph=e,this.statusList=t}async revokeDelegation(e,t={}){const r=t.maxDepth||100,s=[],i=await this.graph.getNode(e);if(!i)throw new Error(`Delegation not found: ${e}`);const a=await this.graph.getDepth(e);if(a>r)throw new Error(`Delegation depth ${a} exceeds maximum ${r}`);const o=await this.revokeNode(i,!0,t.reason,t.dryRun);s.push(o),t.onRevoke&&await t.onRevoke(o);const n=await this.graph.getDescendants(e);for(const r of n){const i=await this.revokeNode(r,!1,`Cascaded from ${e}`,t.dryRun,e);s.push(i),t.onRevoke&&await t.onRevoke(i)}return s}async revokeNode(e,t,r,s,i){const a={delegationId:e.id,isRoot:t,parentId:i,timestamp:Date.now(),reason:r};if(s)return a;if(e.credentialStatusId){const t=this.parseCredentialStatus(e.credentialStatusId);t&&await this.statusList.updateStatus(t,!0)}return a}async restoreDelegation(e){const t=await this.graph.getNode(e);if(!t)throw new Error(`Delegation not found: ${e}`);const r={delegationId:t.id,isRoot:!0,timestamp:Date.now(),reason:"Restored"};if(t.credentialStatusId){const e=this.parseCredentialStatus(t.credentialStatusId);e&&await this.statusList.updateStatus(e,!1)}return r}async isRevoked(e){const t=await this.graph.getChain(e);for(const r of t.reverse())if(r.credentialStatusId){const t=this.parseCredentialStatus(r.credentialStatusId);if(t&&await this.statusList.checkStatus(t))return{revoked:!0,reason:r.id===e?"Directly revoked":"Ancestor revoked",revokedAncestor:r.id===e?void 0:r.id}}return{revoked:!1}}async getRevokedInSubtree(e){const t=await this.graph.getDescendants(e),r=[];(await this.isRevoked(e)).revoked&&r.push(e);for(const e of t)(await this.isRevoked(e.id)).revoked&&r.push(e.id);return r}parseCredentialStatus(e){const t=e.match(/^(.+)#(\d+)$/);if(!t)return null;const[,r,s]=t;return{id:e,type:"StatusList2021Entry",statusPurpose:"revocation",statusListIndex:parseInt(s,10).toString(),statusListCredential:r}}async validateDelegation(e){const t=await this.isRevoked(e);if(t.revoked)return{valid:!1,reason:t.revokedAncestor?`Ancestor ${t.revokedAncestor} is revoked`:"Delegation is revoked"};const r=await this.graph.validateChain(e);return r.valid?{valid:!0}:r}}t.CascadingRevocationManager=r},25572:e=>{"use strict";e.exports=function(e,t,r){var s="",i=!0===e.schema.$async,a=e.util.schemaHasRulesExcept(e.schema,e.RULES.all,"$ref"),o=e.self._getId(e.schema);if(e.opts.strictKeywords){var n=e.util.schemaUnknownRules(e.schema,e.RULES.keywords);if(n){var c="unknown keyword: "+n;if("log"!==e.opts.strictKeywords)throw new Error(c);e.logger.warn(c)}}if(e.isTop&&(s+=" var validate = ",i&&(e.async=!0,s+="async "),s+="function(data, dataPath, parentData, parentDataProperty, rootData) { 'use strict'; ",o&&(e.opts.sourceCode||e.opts.processCode)&&(s+=" /*# sourceURL="+o+" */ ")),"boolean"==typeof e.schema||!a&&!e.schema.$ref){t="false schema";var d=e.level,l=e.dataLevel,u=e.schema[t],h=e.schemaPath+e.util.getProperty(t),p=e.errSchemaPath+"/"+t,f=!e.opts.allErrors,g="data"+(l||""),m="valid"+d;if(!1===e.schema){e.isTop?f=!0:s+=" var "+m+" = false; ",(B=B||[]).push(s),s="",!1!==e.createErrors?(s+=" { keyword: 'false schema' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(p)+" , params: {} ",!1!==e.opts.messages&&(s+=" , message: 'boolean schema is false' "),e.opts.verbose&&(s+=" , schema: false , parentSchema: validate.schema"+e.schemaPath+" , data: "+g+" "),s+=" } "):s+=" {} ";var v=s;s=B.pop(),!e.compositeRule&&f?e.async?s+=" throw new ValidationError(["+v+"]); ":s+=" validate.errors = ["+v+"]; return false; ":s+=" var err = "+v+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}else e.isTop?s+=i?" return data; ":" validate.errors = null; return true; ":s+=" var "+m+" = true; ";return e.isTop&&(s+=" }; return validate; "),s}if(e.isTop){var y=e.isTop;if(d=e.level=0,l=e.dataLevel=0,g="data",e.rootId=e.resolve.fullPath(e.self._getId(e.root.schema)),e.baseId=e.baseId||e.rootId,delete e.isTop,e.dataPathArr=[""],void 0!==e.schema.default&&e.opts.useDefaults&&e.opts.strictDefaults){var _="default is ignored in the schema root";if("log"!==e.opts.strictDefaults)throw new Error(_);e.logger.warn(_)}s+=" var vErrors = null; ",s+=" var errors = 0; ",s+=" if (rootData === undefined) rootData = data; "}else{if(d=e.level,g="data"+((l=e.dataLevel)||""),o&&(e.baseId=e.resolve.url(e.baseId,o)),i&&!e.async)throw new Error("async schema in sync schema");s+=" var errs_"+d+" = errors;"}m="valid"+d,f=!e.opts.allErrors;var w="",b="",S=e.schema.type,P=Array.isArray(S);if(S&&e.opts.nullable&&!0===e.schema.nullable&&(P?-1==S.indexOf("null")&&(S=S.concat("null")):"null"!=S&&(S=[S,"null"],P=!0)),P&&1==S.length&&(S=S[0],P=!1),e.schema.$ref&&a){if("fail"==e.opts.extendRefs)throw new Error('$ref: validation keywords used in schema at path "'+e.errSchemaPath+'" (see option extendRefs)');!0!==e.opts.extendRefs&&(a=!1,e.logger.warn('$ref: keywords ignored in schema at path "'+e.errSchemaPath+'"'))}if(e.schema.$comment&&e.opts.$comment&&(s+=" "+e.RULES.all.$comment.code(e,"$comment")),S){if(e.opts.coerceTypes)var E=e.util.coerceToTypes(e.opts.coerceTypes,S);var I=e.RULES.types[S];if(E||P||!0===I||I&&!G(I)){h=e.schemaPath+".type",p=e.errSchemaPath+"/type",h=e.schemaPath+".type",p=e.errSchemaPath+"/type";var k=P?"checkDataTypes":"checkDataType";if(s+=" if ("+e.util[k](S,g,e.opts.strictNumbers,!0)+") { ",E){var C="dataType"+d,D="coerced"+d;s+=" var "+C+" = typeof "+g+"; var "+D+" = undefined; ","array"==e.opts.coerceTypes&&(s+=" if ("+C+" == 'object' && Array.isArray("+g+") && "+g+".length == 1) { "+g+" = "+g+"[0]; "+C+" = typeof "+g+"; if ("+e.util.checkDataType(e.schema.type,g,e.opts.strictNumbers)+") "+D+" = "+g+"; } "),s+=" if ("+D+" !== undefined) ; ";var O=E;if(O)for(var A,x=-1,T=O.length-1;x<T;)"string"==(A=O[x+=1])?s+=" else if ("+C+" == 'number' || "+C+" == 'boolean') "+D+" = '' + "+g+"; else if ("+g+" === null) "+D+" = ''; ":"number"==A||"integer"==A?(s+=" else if ("+C+" == 'boolean' || "+g+" === null || ("+C+" == 'string' && "+g+" && "+g+" == +"+g+" ","integer"==A&&(s+=" && !("+g+" % 1)"),s+=")) "+D+" = +"+g+"; "):"boolean"==A?s+=" else if ("+g+" === 'false' || "+g+" === 0 || "+g+" === null) "+D+" = false; else if ("+g+" === 'true' || "+g+" === 1) "+D+" = true; ":"null"==A?s+=" else if ("+g+" === '' || "+g+" === 0 || "+g+" === false) "+D+" = null; ":"array"==e.opts.coerceTypes&&"array"==A&&(s+=" else if ("+C+" == 'string' || "+C+" == 'number' || "+C+" == 'boolean' || "+g+" == null) "+D+" = ["+g+"]; ");s+=" else { ",(B=B||[]).push(s),s="",!1!==e.createErrors?(s+=" { keyword: 'type' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(p)+" , params: { type: '",s+=P?""+S.join(","):""+S,s+="' } ",!1!==e.opts.messages&&(s+=" , message: 'should be ",s+=P?""+S.join(","):""+S,s+="' "),e.opts.verbose&&(s+=" , schema: validate.schema"+h+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+g+" "),s+=" } "):s+=" {} ",v=s,s=B.pop(),!e.compositeRule&&f?e.async?s+=" throw new ValidationError(["+v+"]); ":s+=" validate.errors = ["+v+"]; return false; ":s+=" var err = "+v+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+=" } if ("+D+" !== undefined) { ";var R=l?"data"+(l-1||""):"parentData";s+=" "+g+" = "+D+"; ",l||(s+="if ("+R+" !== undefined)"),s+=" "+R+"["+(l?e.dataPathArr[l]:"parentDataProperty")+"] = "+D+"; } "}else(B=B||[]).push(s),s="",!1!==e.createErrors?(s+=" { keyword: 'type' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(p)+" , params: { type: '",s+=P?""+S.join(","):""+S,s+="' } ",!1!==e.opts.messages&&(s+=" , message: 'should be ",s+=P?""+S.join(","):""+S,s+="' "),e.opts.verbose&&(s+=" , schema: validate.schema"+h+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+g+" "),s+=" } "):s+=" {} ",v=s,s=B.pop(),!e.compositeRule&&f?e.async?s+=" throw new ValidationError(["+v+"]); ":s+=" validate.errors = ["+v+"]; return false; ":s+=" var err = "+v+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";s+=" } "}}if(e.schema.$ref&&!a)s+=" "+e.RULES.all.$ref.code(e,"$ref")+" ",f&&(s+=" } if (errors === ",s+=y?"0":"errs_"+d,s+=") { ",b+="}");else{var $=e.RULES;if($)for(var j=-1,N=$.length-1;j<N;)if(G(I=$[j+=1])){if(I.type&&(s+=" if ("+e.util.checkDataType(I.type,g,e.opts.strictNumbers)+") { "),e.opts.useDefaults)if("object"==I.type&&e.schema.properties){u=e.schema.properties;var M=Object.keys(u);if(M)for(var F,K=-1,q=M.length-1;K<q;)if(void 0!==(V=u[F=M[K+=1]]).default){var L=g+e.util.getProperty(F);if(e.compositeRule){if(e.opts.strictDefaults){if(_="default is ignored for: "+L,"log"!==e.opts.strictDefaults)throw new Error(_);e.logger.warn(_)}}else s+=" if ("+L+" === undefined ","empty"==e.opts.useDefaults&&(s+=" || "+L+" === null || "+L+" === '' "),s+=" ) "+L+" = ","shared"==e.opts.useDefaults?s+=" "+e.useDefault(V.default)+" ":s+=" "+JSON.stringify(V.default)+" ",s+="; "}}else if("array"==I.type&&Array.isArray(e.schema.items)){var U=e.schema.items;if(U){x=-1;for(var V,H=U.length-1;x<H;)if(void 0!==(V=U[x+=1]).default)if(L=g+"["+x+"]",e.compositeRule){if(e.opts.strictDefaults){if(_="default is ignored for: "+L,"log"!==e.opts.strictDefaults)throw new Error(_);e.logger.warn(_)}}else s+=" if ("+L+" === undefined ","empty"==e.opts.useDefaults&&(s+=" || "+L+" === null || "+L+" === '' "),s+=" ) "+L+" = ","shared"==e.opts.useDefaults?s+=" "+e.useDefault(V.default)+" ":s+=" "+JSON.stringify(V.default)+" ",s+="; "}}var B,z=I.rules;if(z)for(var J,W=-1,Z=z.length-1;W<Z;)if(Y(J=z[W+=1])){var Q=J.code(e,J.keyword,I.type);Q&&(s+=" "+Q+" ",f&&(w+="}"))}if(f&&(s+=" "+w+" ",w=""),I.type&&(s+=" } ",S&&S===I.type&&!E))s+=" else { ",h=e.schemaPath+".type",p=e.errSchemaPath+"/type",(B=B||[]).push(s),s="",!1!==e.createErrors?(s+=" { keyword: 'type' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(p)+" , params: { type: '",s+=P?""+S.join(","):""+S,s+="' } ",!1!==e.opts.messages&&(s+=" , message: 'should be ",s+=P?""+S.join(","):""+S,s+="' "),e.opts.verbose&&(s+=" , schema: validate.schema"+h+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+g+" "),s+=" } "):s+=" {} ",v=s,s=B.pop(),!e.compositeRule&&f?e.async?s+=" throw new ValidationError(["+v+"]); ":s+=" validate.errors = ["+v+"]; return false; ":s+=" var err = "+v+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+=" } ";f&&(s+=" if (errors === ",s+=y?"0":"errs_"+d,s+=") { ",b+="}")}}function G(e){for(var t=e.rules,r=0;r<t.length;r++)if(Y(t[r]))return!0}function Y(t){return void 0!==e.schema[t.keyword]||t.implements&&function(t){for(var r=t.implements,s=0;s<r.length;s++)if(void 0!==e.schema[r[s]])return!0}(t)}return f&&(s+=" "+b+" "),y?(i?(s+=" if (errors === 0) return data; ",s+=" else throw new ValidationError(vErrors); "):(s+=" validate.errors = vErrors; ",s+=" return errors === 0; "),s+=" }; return validate;"):s+=" var "+m+" = errors === errs_"+d+";",s}},27087:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.IdentityProvider=t.NonceCacheProvider=t.StorageProvider=t.FetchProvider=t.ClockProvider=t.CryptoProvider=void 0,t.CryptoProvider=class{},t.ClockProvider=class{},t.FetchProvider=class{},t.StorageProvider=class{},t.NonceCacheProvider=class{},t.IdentityProvider=class{}},27399:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OAuthRequiredError=void 0;class r extends Error{toolName;requiredScopes;provider;oauthUrl;resumeToken;userDid;sessionId;constructor(e){const{toolName:t,requiredScopes:r,provider:s,oauthUrl:i}=e;super(`OAuth required for tool "${t}" with provider "${s}". Required scopes: ${r.join(", ")}`),this.name="OAuthRequiredError",this.toolName=t,this.requiredScopes=r,this.provider=s,this.oauthUrl=i,this.resumeToken=e.resumeToken,this.userDid=e.userDid,this.sessionId=e.sessionId}}t.OAuthRequiredError=r},27713:e=>{"use strict";var t=e.exports=function(e,t,s){"function"==typeof t&&(s=t,t={}),r(t,"function"==typeof(s=t.cb||s)?s:s.pre||function(){},s.post||function(){},e,"",e)};function r(e,i,a,o,n,c,d,l,u,h){if(o&&"object"==typeof o&&!Array.isArray(o)){for(var p in i(o,n,c,d,l,u,h),o){var f=o[p];if(Array.isArray(f)){if(p in t.arrayKeywords)for(var g=0;g<f.length;g++)r(e,i,a,f[g],n+"/"+p+"/"+g,c,n,p,o,g)}else if(p in t.propsKeywords){if(f&&"object"==typeof f)for(var m in f)r(e,i,a,f[m],n+"/"+p+"/"+s(m),c,n,p,o,m)}else(p in t.keywords||e.allKeys&&!(p in t.skipKeywords))&&r(e,i,a,f,n+"/"+p,c,n,p,o)}a(o,n,c,d,l,u,h)}}function s(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}t.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0},t.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},t.propsKeywords={definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},t.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0}},28565:e=>{"use strict";var t=e.exports=function(){this._cache={}};t.prototype.put=function(e,t){this._cache[e]=t},t.prototype.get=function(e){return this._cache[e]},t.prototype.del=function(e){delete this._cache[e]},t.prototype.clear=function(){this._cache={}}},28717:e=>{"use strict";e.exports=require("@kya-os/contracts/proof")},30124:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BatchDelegationService=void 0,t.BatchDelegationService=class{providerResolver;toolProtectionService;constructor(e,t){this.providerResolver=e,this.toolProtectionService=t}async groupToolsByProvider(e,t,r){const s=new Map;for(const i of e){const e=await this.toolProtectionService.checkToolProtection(i,r);if(!e?.requiresDelegation)continue;let a;try{a=await this.providerResolver.resolveProvider(e,t)}catch(e){console.warn(`[BatchDelegation] Could not resolve provider for tool "${i}", skipping`,e instanceof Error?e.message:String(e));continue}s.has(a)||s.set(a,{provider:a,tools:[],scopes:[],riskLevel:"medium"});const o=s.get(a);o.tools.push(i);const n=new Set([...o.scopes,...e.requiredScopes||[]]);if(o.scopes=Array.from(n),e.riskLevel){const t={low:1,medium:2,high:3,critical:4},r=t[o.riskLevel]||1;(t[e.riskLevel]||1)>r&&(o.riskLevel="critical"===e.riskLevel?"high":e.riskLevel)}}return s}async getToolsForProvider(e,t,r){return[]}}},30845:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DelegationCredentialIssuer=void 0,t.createDelegationIssuer=function(e,t){return new a(e,t)};const s=r(62408),i=r(63969);class a{identity;signingFunction;constructor(e,t){this.identity=e,this.signingFunction=t}async issueDelegationCredential(e,t={}){let r=(0,s.wrapDelegationAsVC)(e,{id:t.id,issuanceDate:t.issuanceDate,expirationDate:t.expirationDate,credentialStatus:t.credentialStatus});if(t.additionalContexts&&t.additionalContexts.length>0){const e=r["@context"];r={...r,"@context":[...e,...t.additionalContexts]}}const i=this.canonicalizeVC(r),a=await this.signingFunction(i,this.identity.getDid(),this.identity.getKeyId());return{...r,proof:a}}async createAndIssueDelegation(e,t={}){const r=Date.now(),s={id:e.id,issuerDid:e.issuerDid,subjectDid:e.subjectDid,controller:e.controller,vcId:t.id||`urn:uuid:${e.id}`,parentId:e.parentId,constraints:e.constraints,signature:"",status:e.status||"active",createdAt:r,metadata:e.metadata};return this.issueDelegationCredential(s,t)}canonicalizeVC(e){return(0,i.canonicalizeJSON)(e)}getIssuerDid(){return this.identity.getDid()}getIssuerKeyId(){return this.identity.getKeyId()}}t.DelegationCredentialIssuer=a},32299:(e,t)=>{"use strict";function r(e){return`agent:${e}:delegation`}function s(e,t,r){return r?`delegation:user:${e}:agent:${t}:project:${r}`:`delegation:user:${e}:agent:${t}`}function i(e){return`session:${e}`}function a(e,t){return`userDid:oauth:${e}:${t}`}function o(e,t){return`oauth:${e}:${t}`}function n(e){return`verified:${e}`}function c(e){return`nonce:${e}`}Object.defineProperty(t,"__esModule",{value:!0}),t.STORAGE_KEYS=void 0,t.legacyDelegationKey=r,t.compositeDelegationKey=s,t.sessionKey=i,t.userDidKey=a,t.oauthIdentityKey=o,t.verificationCacheKey=n,t.nonceKey=c,t.migrateDelegationKeys=async function(e,t={}){const r={migrated:0,failed:0,migrations:[],errors:[]};try{const i=(await e.list("agent:")).filter(e=>e.match(/^agent:[^:]+:delegation$/));console.log(`Found ${i.length} legacy delegation keys to migrate`);for(const a of i)try{const i=a.match(/^agent:([^:]+):delegation$/);if(!i){r.errors.push({key:a,error:"Invalid legacy key format"}),r.failed++;continue}const o=i[1],n=await e.get(a);if(!n)continue;let c,d=null;const l=await e.list("session:");for(const t of l){const r=await e.get(t);if(r)try{const e=JSON.parse(r);if(e.userDid&&e.agentDid===o){d=e.userDid;const r=t.match(/^session:(.+)$/);r&&(c=r[1]);break}}catch{}}if(t.resolveUserDid){const e=await t.resolveUserDid(o,c);e&&(d=e)}if(!d){r.errors.push({key:a,error:"Cannot resolve userDid - skipping migration"}),r.failed++;continue}const u=s(d,o);t.dryRun?(r.migrations.push({oldKey:a,newKey:u}),r.migrated++):(await e.set(u,n),r.migrations.push({oldKey:a,newKey:u}),r.migrated++,t.deleteOldKeys&&await e.delete(a))}catch(e){r.errors.push({key:a,error:e instanceof Error?e.message:String(e)}),r.failed++}}catch(e){r.errors.push({key:"migration",error:e instanceof Error?e.message:String(e)})}return r},t.STORAGE_KEYS={userDid:a,oauthIdentity:o,delegation:s,session:i,legacyDelegation:r,verificationCache:n,nonce:c}},33728:e=>{"use strict";e.exports=function(e,t,r){var s=" ",i=e.level,a=e.dataLevel,o=e.schema[t],n=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,d=!e.opts.allErrors,l="data"+(a||""),u="valid"+i,h="errs__"+i,p=e.util.copy(e),f="";p.level++;var g="valid"+p.level,m="i"+i,v=p.dataLevel=e.dataLevel+1,y="data"+v,_=e.baseId;if(s+="var "+h+" = errors;var "+u+";",Array.isArray(o)){var w=e.schema.additionalItems;if(!1===w){s+=" "+u+" = "+l+".length <= "+o.length+"; ";var b=c;c=e.errSchemaPath+"/additionalItems",s+=" if (!"+u+") { ";var S=S||[];S.push(s),s="",!1!==e.createErrors?(s+=" { keyword: 'additionalItems' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { limit: "+o.length+" } ",!1!==e.opts.messages&&(s+=" , message: 'should NOT have more than "+o.length+" items' "),e.opts.verbose&&(s+=" , schema: false , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),s+=" } "):s+=" {} ";var P=s;s=S.pop(),!e.compositeRule&&d?e.async?s+=" throw new ValidationError(["+P+"]); ":s+=" validate.errors = ["+P+"]; return false; ":s+=" var err = "+P+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+=" } ",c=b,d&&(f+="}",s+=" else { ")}var E=o;if(E)for(var I,k=-1,C=E.length-1;k<C;)if(I=E[k+=1],e.opts.strictKeywords?"object"==typeof I&&Object.keys(I).length>0||!1===I:e.util.schemaHasRules(I,e.RULES.all)){s+=" "+g+" = true; if ("+l+".length > "+k+") { ";var D=l+"["+k+"]";p.schema=I,p.schemaPath=n+"["+k+"]",p.errSchemaPath=c+"/"+k,p.errorPath=e.util.getPathExpr(e.errorPath,k,e.opts.jsonPointers,!0),p.dataPathArr[v]=k;var O=e.validate(p);p.baseId=_,e.util.varOccurences(O,y)<2?s+=" "+e.util.varReplace(O,y,D)+" ":s+=" var "+y+" = "+D+"; "+O+" ",s+=" } ",d&&(s+=" if ("+g+") { ",f+="}")}"object"==typeof w&&(e.opts.strictKeywords?"object"==typeof w&&Object.keys(w).length>0||!1===w:e.util.schemaHasRules(w,e.RULES.all))&&(p.schema=w,p.schemaPath=e.schemaPath+".additionalItems",p.errSchemaPath=e.errSchemaPath+"/additionalItems",s+=" "+g+" = true; if ("+l+".length > "+o.length+") { for (var "+m+" = "+o.length+"; "+m+" < "+l+".length; "+m+"++) { ",p.errorPath=e.util.getPathExpr(e.errorPath,m,e.opts.jsonPointers,!0),D=l+"["+m+"]",p.dataPathArr[v]=m,O=e.validate(p),p.baseId=_,e.util.varOccurences(O,y)<2?s+=" "+e.util.varReplace(O,y,D)+" ":s+=" var "+y+" = "+D+"; "+O+" ",d&&(s+=" if (!"+g+") break; "),s+=" } } ",d&&(s+=" if ("+g+") { ",f+="}"))}else(e.opts.strictKeywords?"object"==typeof o&&Object.keys(o).length>0||!1===o:e.util.schemaHasRules(o,e.RULES.all))&&(p.schema=o,p.schemaPath=n,p.errSchemaPath=c,s+=" for (var "+m+" = 0; "+m+" < "+l+".length; "+m+"++) { ",p.errorPath=e.util.getPathExpr(e.errorPath,m,e.opts.jsonPointers,!0),D=l+"["+m+"]",p.dataPathArr[v]=m,O=e.validate(p),p.baseId=_,e.util.varOccurences(O,y)<2?s+=" "+e.util.varReplace(O,y,D)+" ":s+=" var "+y+" = "+D+"; "+O+" ",d&&(s+=" if (!"+g+") break; "),s+=" }");return d&&(s+=" "+f+" if ("+h+" == errors) {"),s}},36255:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AccessControlApiService=void 0;const s=r(82906),i=r(82906);function a(){return"undefined"!=typeof crypto&&crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).substring(2,15)}`}t.AccessControlApiService=class{config;metrics;constructor(e){const t=e.retryConfig||{};this.config={retryConfig:{maxRetries:t.maxRetries??3,initialDelayMs:t.initialDelayMs??100,maxDelayMs:t.maxDelayMs??5e3},logger:e.logger||(()=>{}),baseUrl:e.baseUrl,apiKey:e.apiKey,fetchProvider:e.fetchProvider,sleepProvider:e.sleepProvider||(e=>new Promise(t=>setTimeout(t,e)))},this.metrics={successCount:0,errorCount:0,retryCount:0}}async fetchConfig(e){return this.retryWithBackoff(async()=>{const t=a(),r=`${this.config.baseUrl}/api/v1/bouncer/config?agent_did=${encodeURIComponent(e.agentDid)}`;this.config.logger(`[AccessControl] Fetching config for agent: ${e.agentDid}`,{correlationId:t,url:r});const o=await this.config.fetchProvider.fetch(r,{method:"GET",headers:{Authorization:`Bearer ${this.config.apiKey}`,"Content-Type":"application/json","X-Request-ID":t}}),n=await o.text(),c=this.parseResponseJSON(o,n);o.ok||this.handleErrorResponse(o,c);const d=s.toolProtectionConfigAPIResponseSchema.safeParse(c);if(!d.success)throw new i.AgentShieldAPIError("invalid_response","Response validation failed",{zodErrors:d.error.errors});return this.config.logger("[AccessControl] Config fetched successfully",{correlationId:t,agentDid:e.agentDid}),d.data})}async verifyDelegation(e,t){return this.retryWithBackoff(async()=>{const r=a(),o=`${this.config.baseUrl}/api/v1/bouncer/delegations/verify`,n={agent_did:e.agent_did};void 0!==e.scopes&&(n.scopes=e.scopes),void 0!==e.credential_jwt?n.credential_jwt=e.credential_jwt:t?.credentialJwt&&(n.credential_jwt=t.credentialJwt),void 0!==e.delegation_token?n.delegation_token=e.delegation_token:t?.delegationToken&&(n.delegation_token=t.delegationToken),void 0!==e.timestamp&&(n.timestamp=e.timestamp),e.client_info&&(n.client_info=e.client_info);const c=Object.fromEntries(Object.entries(n).filter(([e,t])=>void 0!==t)),d=s.verifyDelegationRequestSchema.safeParse(c);if(!d.success&&(!d.error.errors.find(e=>e.path.includes("scopes")&&"Required"===e.message)||"scopes"in c))throw this.config.logger("[AccessControl] Validation failed:",{errors:d.error.errors,requestBody:n}),new i.AgentShieldAPIError("validation_error","Request validation failed",{zodErrors:d.error.errors});this.config.logger(`[AccessControl] Verifying delegation for agent: ${e.agent_did}`,{correlationId:r,url:o,hasScopes:(e.scopes?.length||0)>0});const l=await this.config.fetchProvider.fetch(o,{method:"POST",headers:{Authorization:`Bearer ${this.config.apiKey}`,"Content-Type":"application/json","X-Request-ID":r},body:JSON.stringify(c)}),u=await l.text(),h=this.parseResponseJSON(l,u);l.ok||this.handleErrorResponse(l,h);const p=s.verifyDelegationAPIResponseSchema.safeParse(h);if(!p.success)throw new i.AgentShieldAPIError("invalid_response","Response validation failed",{zodErrors:p.error.errors});return this.config.logger("[AccessControl] Delegation verified",{correlationId:r,agentDid:e.agent_did,valid:p.data.data.valid}),p.data})}async submitProofs(e){return this.retryWithBackoff(async()=>{const t=s.proofSubmissionRequestSchema.safeParse(e);if(!t.success){const r=JSON.stringify(t.error.errors,null,2);throw this.config.logger("[AccessControl] Proof submission validation failed:",{errors:t.error.errors,request:JSON.stringify(e,null,2)}),new i.AgentShieldAPIError("validation_error",`Request validation failed: ${r}`,{zodErrors:t.error.errors})}const r=t.data,o=a(),n=`${this.config.baseUrl}/api/v1/bouncer/proofs`;this.config.logger(`[AccessControl] Submitting ${e.proofs.length} proof(s)`,{correlationId:o,url:n,sessionId:e.session_id,delegationId:e.delegation_id});const c=await this.config.fetchProvider.fetch(n,{method:"POST",headers:{Authorization:`Bearer ${this.config.apiKey}`,"Content-Type":"application/json","X-Request-ID":o},body:JSON.stringify(r)}),d=await c.text();console.error("[AccessControl] 🔍 RAW API RESPONSE (before parsing):",{correlationId:o,status:c.status,statusText:c.statusText,headers:Object.fromEntries(c.headers.entries()),responseTextLength:d.length,responseTextPreview:d.substring(0,500),fullResponseText:d});const l=this.parseResponseJSON(c,d);if(console.error("[AccessControl] 🔍 PARSED RESPONSE DATA:",{correlationId:o,status:c.status,responseDataType:typeof l,responseDataKeys:Object.keys(l||{}),responseData:JSON.stringify(l,null,2)}),!c.ok){const t=l;if(t.error){const r=t.error.code||"api_error";if("all_proofs_rejected"===r&&400===c.status){const r=t.error.details,a={success:!1,accepted:0,rejected:r?.rejected||e.proofs.length,outcomes:{success:0,failed:0,blocked:0,error:r?.rejected||e.proofs.length},errors:r?.errors},o=s.proofSubmissionResponseSchema.safeParse(a);if(o.success)return o.data;throw new i.AgentShieldAPIError("invalid_response","Error response validation failed",{zodErrors:o.error.errors})}const a={...t.error.details||{},status:c.status};throw new i.AgentShieldAPIError(r,t.error.message||`API error: ${c.status}`,a)}let r="api_error";throw 400===c.status?r="validation_error":404===c.status&&(r=c.statusText.includes("delegation")?"delegation_not_found":"session_not_found"),new i.AgentShieldAPIError(r,`API request failed: ${c.status} ${c.statusText}`,{status:c.status,responseData:l})}const u=l,h={correlationId:o,hasSuccess:void 0!==u.success,hasData:void 0!==u.data,responseType:typeof l,responseKeys:Object.keys(l||{}),responseData:JSON.stringify(l,null,2).substring(0,2e3)};if(this.config.logger("[AccessControl] Raw response received",h),console.error("[AccessControl] Raw response received:",JSON.stringify(l,null,2)),void 0!==u.success&&u.data){let e;try{const t=u.data,r=JSON.parse(JSON.stringify(t));if("object"!=typeof r||null===r)throw new i.AgentShieldAPIError("invalid_response","Response data is not an object after cloning",{originalType:typeof t,clonedType:typeof r,clonedValue:r});e=r}catch(e){if(e instanceof i.AgentShieldAPIError)throw e;throw new i.AgentShieldAPIError("invalid_response","Failed to clone response data",{error:e instanceof Error?e.message:String(e),dataType:typeof u.data})}console.error("[AccessControl] 🔍 DATA OBJECT STRUCTURE (after deep clone):",{correlationId:o,dataKeys:Object.keys(e),hasAccepted:"accepted"in e,hasRejected:"rejected"in e,hasOutcomes:"outcomes"in e,hasErrors:"errors"in e,acceptedType:typeof e.accepted,acceptedValue:e.accepted,rejectedType:typeof e.rejected,rejectedValue:e.rejected,outcomesType:typeof e.outcomes,outcomesValue:e.outcomes,errorsType:typeof e.errors,errorsIsArray:Array.isArray(e.errors),fullData:JSON.stringify(e,null,2)});const t={success:!0===u.success,accepted:e.accepted,rejected:e.rejected};if("outcomes"in e&&void 0!==e.outcomes&&(t.outcomes=e.outcomes),"errors"in e&&void 0!==e.errors&&(t.errors=e.errors),console.error("[AccessControl] 🔍 VALIDATING DATA WITH SUCCESS:",{correlationId:o,dataWithSuccessKeys:Object.keys(t),hasSuccess:"success"in t,successValue:t.success,hasAccepted:"accepted"in t,acceptedValue:t.accepted,hasRejected:"rejected"in t,rejectedValue:t.rejected,hasOutcomes:"outcomes"in t,outcomesValue:t.outcomes,fullDataWithSuccess:JSON.stringify(t,null,2)}),"number"!=typeof t.accepted||"number"!=typeof t.rejected)throw console.error("[AccessControl] ❌ MISSING REQUIRED FIELDS AFTER CONSTRUCTION:",{correlationId:o,hasAccepted:"accepted"in t,acceptedType:typeof t.accepted,acceptedValue:t.accepted,hasRejected:"rejected"in t,rejectedType:typeof t.rejected,rejectedValue:t.rejected,dataWithSuccessKeys:Object.keys(t),fullDataWithSuccess:JSON.stringify(t,null,2),dataToValidateKeys:Object.keys(e),fullDataToValidate:JSON.stringify(e,null,2),originalResponseData:JSON.stringify(l,null,2)}),new i.AgentShieldAPIError("invalid_response","Response data missing required fields (accepted/rejected)",{responseData:l,dataToValidate:e,dataWithSuccess:t});const r=s.proofSubmissionResponseSchema.safeParse(t);if(r.success)return this.config.logger("[AccessControl] Proofs submitted successfully (wrapped)",{correlationId:o,accepted:r.data.accepted,rejected:r.data.rejected}),r.data;{const s={correlationId:o,zodErrors:r.error.errors,zodErrorDetails:JSON.stringify(r.error.errors,null,2),dataToValidate:JSON.stringify(e,null,2).substring(0,2e3),dataWithSuccess:JSON.stringify(t,null,2).substring(0,2e3),dataKeys:Object.keys(e),dataWithSuccessKeys:Object.keys(t),originalResponse:JSON.stringify(l,null,2).substring(0,2e3)};throw this.config.logger("[AccessControl] Wrapped response validation failed",s),console.error("[AccessControl] Wrapped response validation failed",s),console.error("[AccessControl] Original wrapped response:",JSON.stringify(l,null,2)),console.error(`[AccessControl] ❌ ZOD VALIDATION FAILED - ${r.error.errors.length} error(s):`),r.error.errors.forEach((e,t)=>{const r={path:e.path.join(".")||"(root)",message:e.message,code:e.code};"received"in e&&(r.received=e.received),"expected"in e&&(r.expected=e.expected),"input"in e&&(r.input=e.input),console.error(`[AccessControl] Error ${t+1}:`,JSON.stringify(r,null,2))}),console.error("[AccessControl] ❌ Full ZOD errors JSON:",JSON.stringify(r.error.errors,null,2)),new i.AgentShieldAPIError("invalid_response","Response validation failed",{zodErrors:r.error.errors,responseData:l})}}const p=s.proofSubmissionResponseSchema.safeParse(l);if(!p.success){const e={correlationId:o,zodErrors:p.error.errors,zodErrorDetails:JSON.stringify(p.error.errors,null,2),responseData:JSON.stringify(l,null,2),responseDataType:typeof l,responseKeys:Object.keys(l||{}),httpStatus:c.status,httpStatusText:c.statusText};throw this.config.logger("[AccessControl] Response validation failed",e),console.error("[AccessControl] Response validation failed",{zodErrors:p.error.errors,responseData:l}),console.error("[AccessControl] Response validation failed",e),console.error(`[AccessControl] ❌ ZOD VALIDATION FAILED (direct) - ${p.error.errors.length} error(s):`),p.error.errors.forEach((e,t)=>{const r={path:e.path.join(".")||"(root)",message:e.message,code:e.code};"received"in e&&(r.received=e.received),"expected"in e&&(r.expected=e.expected),"input"in e&&(r.input=e.input),console.error(`[AccessControl] Error ${t+1}:`,r)}),console.error("[AccessControl] ❌ Full ZOD errors JSON:",JSON.stringify(p.error.errors,null,2)),console.error("[AccessControl] ❌ ACTUAL RESPONSE DATA:",JSON.stringify(l,null,2)),new i.AgentShieldAPIError("invalid_response","Response validation failed",{zodErrors:p.error.errors,responseData:l})}return this.config.logger("[AccessControl] Proofs submitted successfully",{correlationId:o,accepted:p.data.accepted,rejected:p.data.rejected}),p.data})}getMetrics(){return{...this.metrics}}resetMetrics(){this.metrics={successCount:0,errorCount:0,retryCount:0}}async retryWithBackoff(e,t=0){try{const t=await e();return this.metrics.successCount++,t}catch(r){const s=this.isRetryableError(r),{maxRetries:i,initialDelayMs:a,maxDelayMs:o}=this.config.retryConfig;if(s&&t<i){const r=Math.min(a*Math.pow(2,t),o);return this.metrics.retryCount++,this.config.logger(`Retrying after ${r}ms (attempt ${t+1}/${i})`),await this.sleep(r),this.retryWithBackoff(e,t+1)}throw this.metrics.errorCount++,r}}isRetryableError(e){if(e instanceof TypeError&&e.message.includes("fetch"))return!0;if(e instanceof i.AgentShieldAPIError){if("server_error"===e.code)return!0;const t=e.details?.status;if(t&&t>=500&&t<600)return!0;if(429===t)return!0}if(e instanceof Error){const t=e.message.toLowerCase();if(t.includes("timeout")||t.includes("timed out"))return!0}return!1}sleep(e){return this.config.sleepProvider(e)}parseResponseJSON(e,t){try{return JSON.parse(t)}catch(r){if(!e.ok){const r=this.mapStatusToErrorCode(e.status);throw new i.AgentShieldAPIError(r,`API request failed: ${e.status} ${e.statusText}`,{status:e.status,responseText:t.substring(0,500)})}throw new i.AgentShieldAPIError("invalid_response",`Failed to parse response: ${r instanceof Error?r.message:String(r)}`,{responseText:t.substring(0,500)})}}mapStatusToErrorCode(e,t=""){return 400===e?"validation_error":401===e||403===e?"authentication_failed":404===e?"config_not_found":e>=500?"server_error":"api_error"}handleErrorResponse(e,t){const r=t;if(r.error){const t=r.error.code||"api_error",s={...r.error.details||{},status:e.status};throw new i.AgentShieldAPIError(t,r.error.message||`API error: ${e.status}`,s)}const s=this.mapStatusToErrorCode(e.status,e.statusText);throw new i.AgentShieldAPIError(s,`API request failed: ${e.status} ${e.statusText}`,{status:e.status,responseData:t})}}},36885:(e,t,r)=>{"use strict";var s=r(9717),i=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,a=[0,31,28,31,30,31,30,31,31,30,31,30,31],o=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,n=/^(?=.{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,c=/^(?:[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,d=/^(?:(?:[^\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,l=/^(?:(?:http[s\u017F]?|ftp):\/\/)(?:(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+(?::(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?@)?(?:(?!10(?:\.[0-9]{1,3}){3})(?!127(?:\.[0-9]{1,3}){3})(?!169\.254(?:\.[0-9]{1,3}){2})(?!192\.168(?:\.[0-9]{1,3}){2})(?!172\.(?:1[6-9]|2[0-9]|3[01])(?:\.[0-9]{1,3}){2})(?:[1-9][0-9]?|1[0-9][0-9]|2[01][0-9]|22[0-3])(?:\.(?:1?[0-9]{1,2}|2[0-4][0-9]|25[0-5])){2}(?:\.(?:[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-4]))|(?:(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)(?:\.(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)*(?:\.(?:(?:[a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]){2,})))(?::[0-9]{2,5})?(?:\/(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?$/i,u=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,h=/^(?:\/(?:[^~/]|~0|~1)*)*$/,p=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,f=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/;function g(e){return e="full"==e?"full":"fast",s.copy(g[e])}function m(e){var t=e.match(i);if(!t)return!1;var r=+t[1],s=+t[2],o=+t[3];return s>=1&&s<=12&&o>=1&&o<=(2==s&&function(e){return e%4==0&&(e%100!=0||e%400==0)}(r)?29:a[s])}function v(e,t){var r=e.match(o);if(!r)return!1;var s=r[1],i=r[2],a=r[3],n=r[5];return(s<=23&&i<=59&&a<=59||23==s&&59==i&&60==a)&&(!t||n)}e.exports=g,g.fast={date:/^\d\d\d\d-[0-1]\d-[0-3]\d$/,time:/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,"date-time":/^\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,uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,"uri-template":d,url:l,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,hostname:n,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,ipv6:/^\s*(?:(?:(?:[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}))|:)))(?:%.+)?\s*$/i,regex:b,uuid:u,"json-pointer":h,"json-pointer-uri-fragment":p,"relative-json-pointer":f},g.full={date:m,time:v,"date-time":function(e){var t=e.split(y);return 2==t.length&&m(t[0])&&v(t[1],!0)},uri:function(e){return _.test(e)&&c.test(e)},"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":d,url:l,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:n,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,ipv6:/^\s*(?:(?:(?:[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}))|:)))(?:%.+)?\s*$/i,regex:b,uuid:u,"json-pointer":h,"json-pointer-uri-fragment":p,"relative-json-pointer":f};var y=/t|\s/i,_=/\/|:/,w=/[^\\]\\Z/;function b(e){if(w.test(e))return!1;try{return new RegExp(e),!0}catch(e){return!1}}},37121:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SchemaVerifier=void 0,t.createSchemaVerifier=function(e){return new r(e)};class r{schemasBaseUrl="https://schemas.kya-os.ai";schemaCache=new Map;constructor(e){e?.schemasBaseUrl&&(this.schemasBaseUrl=e.schemasBaseUrl)}async verifySchema(e,t){const r=[],s=[],i=[];let a;try{a=await this.fetchSchema(e.url)}catch(t){return{schema:e,compliant:!1,compliancePercentage:0,fields:[],issues:[`Failed to fetch schema: ${t instanceof Error?t.message:"Unknown error"}`],warnings:[],timestamp:Date.now()}}const o=this.resolveRef(a,a),n=this.validateAgainstSchema(t,o,a,"");r.push(...n.fields);for(const e of r)"fail"===e.status?s.push(`${e.fieldPath}: ${e.reason}`):"warning"===e.status&&i.push(`${e.fieldPath}: ${e.reason}`);const c=r.filter(e=>e.required),d=c.filter(e=>"pass"===e.status).length,l=c.length>0?d/c.length*100:100;return{schema:e,compliant:0===s.length&&l>=95,compliancePercentage:l,fields:r,issues:s,warnings:i,timestamp:Date.now()}}async verifyAll(e,t){const r=[],s=[];for(const i of e){const e=t.get(i.id);if(!e){s.push(`No implementation found for schema: ${i.id}`);continue}const a=await this.verifySchema(i,e);r.push(a),a.compliant||s.push(`${i.id}: ${a.issues.join(", ")}`)}const i=r.filter(e=>e.compliant).length,a=e.length>0?i/e.length*100:0;return{totalSchemas:e.length,compliantSchemas:i,overallCompliance:a,schemaReports:r,criticalIssues:s,timestamp:Date.now()}}validateAgainstSchema(e,t,r,s){const i=[];if((t=this.resolveRef(t,r)).oneOf||t.anyOf||t.allOf)return this.validateUnion(e,t,r,s);if("object"===t.type&&t.properties){const a=t.required||[];for(const[o,n]of Object.entries(t.properties)){const t=s?`${s}.${o}`:o,c=e?.[o],d=a.includes(o),l=this.checkField(t,c,n,r,d);if(i.push(l),void 0!==c&&"object"===n.type){const e=this.validateAgainstSchema(c,n,r,t);i.push(...e.fields)}}}if("array"===t.type&&e&&Array.isArray(e)){const a=this.validateArray(e,t,r,s);i.push(...a.fields)}return{fields:i}}validateUnion(e,t,r,s){const i=[];if(t.anyOf||t.oneOf){const a=t.anyOf||t.oneOf;let o=!1;for(const t of a){const a=this.resolveRef(t,r);try{if(this.matchesSchema(e,a,r)){const t=this.validateAgainstSchema(e,a,r,s);i.push(...t.fields),o=!0;break}}catch(e){continue}}!o&&s&&i.push({fieldPath:s,present:void 0!==e,expectedType:"oneOf/anyOf options",actualType:typeof e,typeMatches:!1,required:!0,status:"fail",reason:"Value does not match any of the schema options"})}if(t.allOf)for(const a of t.allOf){const t=this.resolveRef(a,r),o=this.validateAgainstSchema(e,t,r,s);i.push(...o.fields)}return{fields:i}}matchesSchema(e,t,r){if((t=this.resolveRef(t,r)).type){const r=Array.isArray(e)?"array":typeof e;if("integer"===t.type&&"number"===r){if(!Number.isInteger(e))return!1}else if(t.type!==r)return!1}if(void 0!==t.const&&e!==t.const)return!1;if(t.enum&&!t.enum.includes(e))return!1;if(t.pattern&&"string"==typeof e&&!new RegExp(t.pattern).test(e))return!1;if("object"===t.type&&t.required)for(const r of t.required)if(!(r in e))return!1;return!0}validateArray(e,t,r,s){const i=[];if(void 0!==t.minItems&&e.length<t.minItems&&i.push({fieldPath:`${s}.length`,present:!0,expectedType:`array with minItems: ${t.minItems}`,actualType:`array with length: ${e.length}`,typeMatches:!1,required:!0,status:"fail",reason:`Array length ${e.length} is less than minItems ${t.minItems}`}),Array.isArray(t.items)){for(let a=0;a<t.items.length;a++){const o=t.items[a],n=e[a],c=`${s}[${a}]`;if(void 0!==n){const e=this.resolveRef(o,r),t=this.validateAgainstSchema(n,e,r,c);i.push(...t.fields)}}if(void 0!==t.additionalItems&&e.length>t.items.length)for(let a=t.items.length;a<e.length;a++){const o=e[a],n=`${s}[${a}]`,c=this.validateAgainstSchema(o,t.additionalItems,r,n);i.push(...c.fields)}}else if(t.items)for(let a=0;a<e.length;a++){const o=e[a],n=`${s}[${a}]`,c=this.resolveRef(t.items,r),d=this.validateAgainstSchema(o,c,r,n);i.push(...d.fields)}if(t.contains){const a=this.resolveRef(t.contains,r);e.some(e=>this.matchesSchema(e,a,r))||i.push({fieldPath:`${s}.contains`,present:!0,expectedType:"array containing matching item",actualType:"array without matching item",typeMatches:!1,required:!0,status:"fail",reason:'Array does not contain any item matching the "contains" schema'})}return{fields:i}}checkField(e,t,r,s,i){r=this.resolveRef(r,s);const a=void 0!==t,o=this.getActualType(t);let n="unknown";return r.type?n=r.type:r.anyOf?n="anyOf":r.oneOf?n="oneOf":r.allOf&&(n="allOf"),i&&!a?{fieldPath:e,present:a,expectedType:n,actualType:o,typeMatches:!1,required:i,status:"fail",reason:"Required field missing"}:i||a?this.matchesSchema(t,r,s)?{fieldPath:e,present:a,expectedType:n,actualType:o,typeMatches:!0,required:i,status:"pass"}:{fieldPath:e,present:a,expectedType:n,actualType:o,typeMatches:!1,required:i,status:"fail",reason:"Type/value mismatch"}:{fieldPath:e,present:a,expectedType:n,actualType:o,typeMatches:!0,required:i,status:"pass"}}getActualType(e){return null===e?"null":Array.isArray(e)?"array":"number"==typeof e&&Number.isInteger(e)?"integer":typeof e}resolveRef(e,t){if(!e.$ref)return e;const r=e.$ref;if(r.startsWith("#/definitions/")){const e=r.substring(14);if(t.definitions&&t.definitions[e])return t.definitions[e]}if(r.startsWith("#/$defs/")){const e=r.substring(8);if(t.$defs&&t.$defs[e])return t.$defs[e]}return"#"===r?t:e}async fetchSchema(e){if(this.schemaCache.has(e))return this.schemaCache.get(e);try{const t=await fetch(e);if(!t.ok)throw new Error(`HTTP ${t.status}: ${t.statusText}`);const r=await t.json();return this.schemaCache.set(e,r),r}catch(t){if(t instanceof Error)throw new Error(`Failed to fetch schema from ${e}: ${t.message}`);throw new Error(`Failed to fetch schema from ${e}: Unknown error`)}}generateReport(e){const t=[];t.push(`\n${"=".repeat(80)}`),t.push(`SCHEMA COMPLIANCE REPORT: ${e.schema.id}`),t.push(`${"=".repeat(80)}\n`),t.push(`Schema: ${e.schema.type} v${e.schema.version}`),t.push(`URL: ${e.schema.url}`),t.push("Status: "+(e.compliant?"✅ COMPLIANT":"❌ NON-COMPLIANT")),t.push(`Compliance: ${e.compliancePercentage.toFixed(1)}%\n`),e.issues.length>0&&(t.push(`\n🚨 ISSUES (${e.issues.length}):`),e.issues.forEach((e,r)=>{t.push(` ${r+1}. ${e}`)})),e.warnings.length>0&&(t.push(`\n⚠️ WARNINGS (${e.warnings.length}):`),e.warnings.forEach((e,r)=>{t.push(` ${r+1}. ${e}`)})),t.push("\n📊 FIELD DETAILS:\n");const r=e.fields.filter(e=>e.required),s=r.filter(e=>"pass"===e.status).length,i=r.filter(e=>"fail"===e.status).length,a=e.fields.filter(e=>"warning"===e.status).length;return t.push(` ✅ Pass: ${s}/${r.length} required fields`),t.push(` ❌ Fail: ${i}/${r.length} required fields`),t.push(` ⚠️ Warn: ${a} optional fields`),t.push(` 📝 Total: ${e.fields.length} fields checked\n`),t.push(`${"=".repeat(80)}\n`),t.join("\n")}generateFullReport(e){const t=[];return t.push(`\n${"=".repeat(80)}`),t.push("FULL SCHEMA COMPLIANCE REPORT"),t.push(`${"=".repeat(80)}\n`),t.push(`Total Schemas: ${e.totalSchemas}`),t.push(`Compliant: ${e.compliantSchemas}`),t.push("Non-Compliant: "+(e.totalSchemas-e.compliantSchemas)),t.push(`Overall Compliance: ${e.overallCompliance.toFixed(1)}%\n`),e.criticalIssues.length>0&&(t.push(`\n🚨 CRITICAL ISSUES (${e.criticalIssues.length}):`),e.criticalIssues.slice(0,10).forEach((e,r)=>{t.push(` ${r+1}. ${e}`)}),e.criticalIssues.length>10&&t.push(` ... and ${e.criticalIssues.length-10} more issues`)),t.push("\n📊 SCHEMA BREAKDOWN:\n"),e.schemaReports.forEach(e=>{const r=e.compliant?"✅":"❌",s=e.compliancePercentage.toFixed(1);t.push(` ${r} ${e.schema.id}: ${s}%`)}),t.push(`\n${"=".repeat(80)}\n`),t.join("\n")}}t.SchemaVerifier=r},40985:(e,t,r)=>{"use strict";var s=r(13749),i=r(67371),a=r(9717),o=r(20812),n=r(27713);function c(e,t,r){var s=this._refs[r];if("string"==typeof s){if(!this._refs[s])return c.call(this,e,t,s);s=this._refs[s]}if((s=s||this._schemas[r])instanceof o)return f(s.schema,this._opts.inlineRefs)?s.schema:s.validate||this._compile(s);var i,a,n,l=d.call(this,t,r);return l&&(i=l.schema,t=l.root,n=l.baseId),i instanceof o?a=i.validate||e.call(this,i.schema,t,void 0,n):void 0!==i&&(a=f(i,this._opts.inlineRefs)?i:e.call(this,i,t,void 0,n)),a}function d(e,t){var r=s.parse(t),i=y(r),a=v(this._getId(e.schema));if(0===Object.keys(e.schema).length||i!==a){var n=w(i),c=this._refs[n];if("string"==typeof c)return l.call(this,e,c,r);if(c instanceof o)c.validate||this._compile(c),e=c;else{if(!((c=this._schemas[n])instanceof o))return;if(c.validate||this._compile(c),n==w(t))return{schema:c,root:e,baseId:a};e=c}if(!e.schema)return;a=v(this._getId(e.schema))}return h.call(this,r,a,e.schema,e)}function l(e,t,r){var s=d.call(this,e,t);if(s){var i=s.schema,a=s.baseId;e=s.root;var o=this._getId(i);return o&&(a=b(a,o)),h.call(this,r,a,i,e)}}e.exports=c,c.normalizeId=w,c.fullPath=v,c.url=b,c.ids=function(e){var t=w(this._getId(e)),r={"":t},o={"":v(t,!1)},c={},d=this;return n(e,{allKeys:!0},function(e,t,n,l,u,h,p){if(""!==t){var f=d._getId(e),g=r[l],m=o[l]+"/"+u;if(void 0!==p&&(m+="/"+("number"==typeof p?p:a.escapeFragment(p))),"string"==typeof f){f=g=w(g?s.resolve(g,f):f);var v=d._refs[f];if("string"==typeof v&&(v=d._refs[v]),v&&v.schema){if(!i(e,v.schema))throw new Error('id "'+f+'" resolves to more than one schema')}else if(f!=w(m))if("#"==f[0]){if(c[f]&&!i(e,c[f]))throw new Error('id "'+f+'" resolves to more than one schema');c[f]=e}else d._refs[f]=m}r[t]=g,o[t]=m}}),c},c.inlineRef=f,c.schema=d;var u=a.toHash(["properties","patternProperties","enum","dependencies","definitions"]);function h(e,t,r,s){if(e.fragment=e.fragment||"","/"==e.fragment.slice(0,1)){for(var i=e.fragment.split("/"),o=1;o<i.length;o++){var n=i[o];if(n){if(void 0===(r=r[n=a.unescapeFragment(n)]))break;var c;if(!u[n]&&((c=this._getId(r))&&(t=b(t,c)),r.$ref)){var l=b(t,r.$ref),h=d.call(this,s,l);h&&(r=h.schema,s=h.root,t=h.baseId)}}}return void 0!==r&&r!==s.schema?{schema:r,root:s,baseId:t}:void 0}}var p=a.toHash(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum"]);function f(e,t){return!1!==t&&(void 0===t||!0===t?g(e):t?m(e)<=t:void 0)}function g(e){var t;if(Array.isArray(e)){for(var r=0;r<e.length;r++)if("object"==typeof(t=e[r])&&!g(t))return!1}else for(var s in e){if("$ref"==s)return!1;if("object"==typeof(t=e[s])&&!g(t))return!1}return!0}function m(e){var t,r=0;if(Array.isArray(e)){for(var s=0;s<e.length;s++)if("object"==typeof(t=e[s])&&(r+=m(t)),r==1/0)return 1/0}else for(var i in e){if("$ref"==i)return 1/0;if(p[i])r++;else if("object"==typeof(t=e[i])&&(r+=m(t)+1),r==1/0)return 1/0}return r}function v(e,t){return!1!==t&&(e=w(e)),y(s.parse(e))}function y(e){return s.serialize(e).split("#")[0]+"#"}var _=/#\/?$/;function w(e){return e?e.replace(_,""):""}function b(e,t){return t=w(t),s.resolve(e,t)}},41021:e=>{"use strict";e.exports=function(e,t,r){var s,i,a=" ",o=e.level,n=e.dataLevel,c=e.schema[t],d=e.schemaPath+e.util.getProperty(t),l=e.errSchemaPath+"/"+t,u=!e.opts.allErrors,h="data"+(n||""),p="valid"+o,f="errs__"+o,g=e.opts.$data&&c&&c.$data;g?(a+=" var schema"+o+" = "+e.util.getData(c.$data,n,e.dataPathArr)+"; ",i="schema"+o):i=c;var m,v,y,_,w,b=this,S="definition"+o,P=b.definition,E="";if(g&&P.$data){w="keywordValidate"+o;var I=P.validateSchema;a+=" var "+S+" = RULES.custom['"+t+"'].definition; var "+w+" = "+S+".validate;"}else{if(!(_=e.useCustomRule(b,c,e.schema,e)))return;i="validate.schema"+d,w=_.code,m=P.compile,v=P.inline,y=P.macro}var k=w+".errors",C="i"+o,D="ruleErr"+o,O=P.async;if(O&&!e.async)throw new Error("async keyword in sync schema");if(v||y||(a+=k+" = null;"),a+="var "+f+" = errors;var "+p+";",g&&P.$data&&(E+="}",a+=" if ("+i+" === undefined) { "+p+" = true; } else { ",I&&(E+="}",a+=" "+p+" = "+S+".validateSchema("+i+"); if ("+p+") { ")),v)P.statements?a+=" "+_.validate+" ":a+=" "+p+" = "+_.validate+"; ";else if(y){var A=e.util.copy(e);E="",A.level++;var x="valid"+A.level;A.schema=_.validate,A.schemaPath="";var T=e.compositeRule;e.compositeRule=A.compositeRule=!0;var R=e.validate(A).replace(/validate\.schema/g,w);e.compositeRule=A.compositeRule=T,a+=" "+R}else{(M=M||[]).push(a),a="",a+=" "+w+".call( ",e.opts.passContext?a+="this":a+="self",m||!1===P.schema?a+=" , "+h+" ":a+=" , "+i+" , "+h+" , validate.schema"+e.schemaPath+" ",a+=" , (dataPath || '')",'""'!=e.errorPath&&(a+=" + "+e.errorPath);var $=n?"data"+(n-1||""):"parentData",j=n?e.dataPathArr[n]:"parentDataProperty",N=a+=" , "+$+" , "+j+" , rootData ) ";a=M.pop(),!1===P.errors?(a+=" "+p+" = ",O&&(a+="await "),a+=N+"; "):a+=O?" var "+(k="customErrors"+o)+" = null; try { "+p+" = await "+N+"; } catch (e) { "+p+" = false; if (e instanceof ValidationError) "+k+" = e.errors; else throw e; } ":" "+k+" = null; "+p+" = "+N+"; "}if(P.modifying&&(a+=" if ("+$+") "+h+" = "+$+"["+j+"];"),a+=""+E,P.valid)u&&(a+=" if (true) { ");else{var M;a+=" if ( ",void 0===P.valid?(a+=" !",a+=y?""+x:""+p):a+=" "+!P.valid+" ",a+=") { ",s=b.keyword,(M=M||[]).push(a),a="",(M=M||[]).push(a),a="",!1!==e.createErrors?(a+=" { keyword: '"+(s||"custom")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: { keyword: '"+b.keyword+"' } ",!1!==e.opts.messages&&(a+=" , message: 'should pass \""+b.keyword+"\" keyword validation' "),e.opts.verbose&&(a+=" , schema: validate.schema"+d+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),a+=" } "):a+=" {} ";var F=a;a=M.pop(),!e.compositeRule&&u?e.async?a+=" throw new ValidationError(["+F+"]); ":a+=" validate.errors = ["+F+"]; return false; ":a+=" var err = "+F+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";var K=a;a=M.pop(),v?P.errors?"full"!=P.errors&&(a+=" for (var "+C+"="+f+"; "+C+"<errors; "+C+"++) { var "+D+" = vErrors["+C+"]; if ("+D+".dataPath === undefined) "+D+".dataPath = (dataPath || '') + "+e.errorPath+"; if ("+D+".schemaPath === undefined) { "+D+'.schemaPath = "'+l+'"; } ',e.opts.verbose&&(a+=" "+D+".schema = "+i+"; "+D+".data = "+h+"; "),a+=" } "):!1===P.errors?a+=" "+K+" ":(a+=" if ("+f+" == errors) { "+K+" } else { for (var "+C+"="+f+"; "+C+"<errors; "+C+"++) { var "+D+" = vErrors["+C+"]; if ("+D+".dataPath === undefined) "+D+".dataPath = (dataPath || '') + "+e.errorPath+"; if ("+D+".schemaPath === undefined) { "+D+'.schemaPath = "'+l+'"; } ',e.opts.verbose&&(a+=" "+D+".schema = "+i+"; "+D+".data = "+h+"; "),a+=" } } "):y?(a+=" var err = ",!1!==e.createErrors?(a+=" { keyword: '"+(s||"custom")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: { keyword: '"+b.keyword+"' } ",!1!==e.opts.messages&&(a+=" , message: 'should pass \""+b.keyword+"\" keyword validation' "),e.opts.verbose&&(a+=" , schema: validate.schema"+d+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),a+=" } "):a+=" {} ",a+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&u&&(e.async?a+=" throw new ValidationError(vErrors); ":a+=" validate.errors = vErrors; return false; ")):!1===P.errors?a+=" "+K+" ":(a+=" if (Array.isArray("+k+")) { if (vErrors === null) vErrors = "+k+"; else vErrors = vErrors.concat("+k+"); errors = vErrors.length; for (var "+C+"="+f+"; "+C+"<errors; "+C+"++) { var "+D+" = vErrors["+C+"]; if ("+D+".dataPath === undefined) "+D+".dataPath = (dataPath || '') + "+e.errorPath+"; "+D+'.schemaPath = "'+l+'"; ',e.opts.verbose&&(a+=" "+D+".schema = "+i+"; "+D+".data = "+h+"; "),a+=" } } else { "+K+" } "),a+=" } ",u&&(a+=" else { ")}return a}},42399:e=>{function t(e){return Promise.resolve().then(()=>{var t=new Error("Cannot find module '"+e+"'");throw t.code="MODULE_NOT_FOUND",t})}t.keys=()=>[],t.resolve=t,t.id=42399,e.exports=t},42769:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OAuthTokenRetrievalService=void 0,t.OAuthTokenRetrievalService=class{config;constructor(e){this.config={...e,logger:e.logger||(()=>{}),retryConfig:{maxRetries:3,retryDelay:1e3,retryBackoff:2,...e.retryConfig}}}async retrieveTokens(e,t){const r=`${this.config.baseUrl}/api/v1/bouncer/delegations/${e}/tokens`;this.config.logger("[OAuthTokenRetrievalService] Retrieving OAuth tokens",{delegationId:e,endpoint:r});let s=null,i=0;for(;i<=this.config.retryConfig.maxRetries;)try{const s=await this.config.fetchProvider(r,{method:"GET",headers:{Authorization:`Bearer ${t}`,Accept:"application/json"}});if(!s.ok){const t=await s.json().catch(()=>({}));if(404===s.status||401===s.status)return this.config.logger("[OAuthTokenRetrievalService] Tokens unavailable",{status:s.status,delegationId:e,error:t}),null;const r=t.error?.message||t.error||t.message||`HTTP ${s.status}`;throw new Error(`Token retrieval failed: ${r}`)}const i=await s.json();if(!i.success)return this.config.logger("[OAuthTokenRetrievalService] Token retrieval error response",{delegationId:e,error:i.error}),null;const a=this.mapToIdpTokens(i.data);return this.config.logger("[OAuthTokenRetrievalService] OAuth tokens retrieved successfully",{delegationId:e,expiresAt:new Date(a.expires_at).toISOString(),hasRefreshToken:!!a.refresh_token}),a}catch(t){if(s=t instanceof Error?t:new Error(String(t)),!(i<this.config.retryConfig.maxRetries))return this.config.logger("[OAuthTokenRetrievalService] Max retries exceeded",{delegationId:e,error:s.message,attempts:i+1}),null;{const e=this.config.retryConfig.retryDelay*Math.pow(this.config.retryConfig.retryBackoff,i);this.config.logger("[OAuthTokenRetrievalService] Retry attempt failed, retrying",{attempt:i+1,maxRetries:this.config.retryConfig.maxRetries,delay:e,error:s.message}),await new Promise(t=>setTimeout(t,e)),i++}}return null}mapToIdpTokens(e){let t;return t=e.oauth_expires_at?new Date(e.oauth_expires_at).getTime():e.oauth_expires_in?Date.now()+1e3*e.oauth_expires_in:Date.now()+36e5,{access_token:e.oauth_access_token,refresh_token:e.oauth_refresh_token||void 0,expires_in:e.oauth_expires_in||void 0,expires_at:t,token_type:e.oauth_token_type||"Bearer",scope:e.oauth_scope||void 0}}}},43528:(e,t,r)=>{"use strict";var s=/^[a-z_$][a-z0-9_$-]*$/i,i=r(41021),a=r(96150);e.exports={add:function(e,t){var r=this.RULES;if(r.keywords[e])throw new Error("Keyword "+e+" is already defined");if(!s.test(e))throw new Error("Keyword "+e+" is not a valid identifier");if(t){this.validateKeyword(t,!0);var a=t.type;if(Array.isArray(a))for(var o=0;o<a.length;o++)c(e,a[o],t);else c(e,a,t);var n=t.metaSchema;n&&(t.$data&&this._opts.$data&&(n={anyOf:[n,{$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"}]}),t.validateSchema=this.compile(n,!0))}function c(e,t,s){for(var a,o=0;o<r.length;o++){var n=r[o];if(n.type==t){a=n;break}}a||(a={type:t,rules:[]},r.push(a));var c={keyword:e,definition:s,custom:!0,code:i,implements:s.implements};a.rules.push(c),r.custom[e]=c}return r.keywords[e]=r.all[e]=!0,this},get:function(e){var t=this.RULES.custom[e];return t?t.definition:this.RULES.keywords[e]||!1},remove:function(e){var t=this.RULES;delete t.keywords[e],delete t.all[e],delete t.custom[e];for(var r=0;r<t.length;r++)for(var s=t[r].rules,i=0;i<s.length;i++)if(s[i].keyword==e){s.splice(i,1);break}return this},validate:function e(t,r){e.errors=null;var s=this._validateKeyword=this._validateKeyword||this.compile(a,!0);if(s(t))return!0;if(e.errors=s.errors,r)throw new Error("custom keyword definition is invalid: "+this.errorsText(s.errors));return!1}}},44413:e=>{"use strict";e.exports=function(e,t,r){var s=" ",i=e.schema[t],a=e.errSchemaPath+"/"+t,o=(e.opts.allErrors,e.util.toQuotedString(i));return!0===e.opts.$comment?s+=" console.log("+o+");":"function"==typeof e.opts.$comment&&(s+=" self._opts.$comment("+o+", "+e.util.toQuotedString(a)+", validate.root.schema);"),s}},44558:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MemoryDelegationGraphStorage=void 0,t.MemoryDelegationGraphStorage=class{nodes=new Map;async getNode(e){return this.nodes.get(e)||null}async setNode(e){this.nodes.set(e.id,e)}async getChildren(e){const t=this.nodes.get(e);return t?t.children.map(e=>this.nodes.get(e)).filter(e=>void 0!==e):[]}async getChain(e){const t=[];let r=e;for(;r;){const e=this.nodes.get(r);if(!e)break;t.unshift(e),r=e.parentId}return t}async getDescendants(e){const t=[],r=[e],s=new Set;for(;r.length>0;){const e=r.shift();if(s.has(e))continue;s.add(e);const i=this.nodes.get(e);if(i)for(const e of i.children)if(!s.has(e)){r.push(e);const s=this.nodes.get(e);s&&t.push(s)}}return t}async deleteNode(e){this.nodes.delete(e)}clear(){this.nodes.clear()}getAllNodeIds(){return Array.from(this.nodes.keys())}getStats(){const e=Array.from(this.nodes.values()),t=e.filter(e=>null===e.parentId).length,r=e.filter(e=>0===e.children.length).length;let s=0;for(const t of e){const e=this.getChainSync(t.id);s=Math.max(s,e.length-1)}return{totalNodes:e.length,rootNodes:t,leafNodes:r,maxDepth:s}}getChainSync(e){const t=[];let r=e;for(;r;){const e=this.nodes.get(r);if(!e)break;t.unshift(e),r=e.parentId}return t}}},45395:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProofVerifier=void 0;const s=r(81296),i=r(28717),a=r(51708),o=r(53683);t.ProofVerifier=class{cryptoService;clock;nonceCache;fetch;timestampSkewSeconds;nonceTtlSeconds;constructor(e){this.cryptoService=new s.CryptoService(e.cryptoProvider),this.clock=e.clockProvider,this.nonceCache=e.nonceCacheProvider,this.fetch=e.fetchProvider,this.timestampSkewSeconds=e.timestampSkewSeconds??120,this.nonceTtlSeconds=e.nonceTtlSeconds??300}async verifyProof(e,t){try{const r=await this.validateProofStructure(e);if(!r.valid)return r;const s=r.proof,i=await this.validateNonce(s.meta.nonce,s.meta.did);if(!i.valid)return i;const a=await this.validateTimestamp(s.meta.ts);if(!a.valid)return a;const o=this.buildCanonicalPayload(s.meta),n=(new TextEncoder).encode(o),c=await this.verifySignature(s.jws,t,n,s.meta.kid);return c.valid?(await this.addNonceToCache(s.meta.nonce,s.meta.did),{valid:!0}):c}catch(e){return{valid:!1,reason:"Proof verification error",errorCode:o.PROOF_VERIFICATION_ERROR_CODES.VERIFICATION_ERROR,error:e instanceof Error?e:new Error(String(e)),details:{errorMessage:e instanceof Error?e.message:String(e)}}}}async verifyProofDetached(e,t,r){try{const s=await this.validateProofStructure(e);if(!s.valid)return s;const i=s.proof,a=await this.validateNonce(i.meta.nonce,i.meta.did);if(!a.valid)return a;const o=await this.validateTimestamp(i.meta.ts);if(!o.valid)return o;const n=t instanceof Uint8Array?t:(new TextEncoder).encode(t),c=await this.verifySignature(i.jws,r,n,i.meta.kid);return c.valid?(await this.addNonceToCache(i.meta.nonce,i.meta.did),{valid:!0}):c}catch(e){return{valid:!1,reason:"Proof verification error",errorCode:o.PROOF_VERIFICATION_ERROR_CODES.VERIFICATION_ERROR,error:e instanceof Error?e:new Error(String(e)),details:{errorMessage:e instanceof Error?e.message:String(e)}}}}async validateProofStructure(e){const t=i.DetachedProofSchema.safeParse(e);return t.success?{valid:!0,proof:t.data}:{valid:!1,reason:"Invalid proof structure",errorCode:o.PROOF_VERIFICATION_ERROR_CODES.INVALID_PROOF_STRUCTURE,error:new Error(`Proof validation failed: ${t.error.message}`),details:{zodErrors:t.error.errors}}}async validateNonce(e,t){return await this.nonceCache.has(e,t)?{valid:!1,reason:"Nonce already used (replay attack detected)",errorCode:o.PROOF_VERIFICATION_ERROR_CODES.NONCE_REPLAY_DETECTED,details:{nonce:e,agentDid:t}}:{valid:!0}}async validateTimestamp(e){const t=1e3*e;return this.clock.isWithinSkew(t,this.timestampSkewSeconds)?{valid:!0}:{valid:!1,reason:`Timestamp out of skew window (skew: ${this.timestampSkewSeconds}s)`,errorCode:o.PROOF_VERIFICATION_ERROR_CODES.TIMESTAMP_SKEW_EXCEEDED,details:{timestamp:e,timestampMs:t,skewSeconds:this.timestampSkewSeconds,currentTime:this.clock.now()}}}async verifySignature(e,t,r,s){return await this.cryptoService.verifyJWS(e,t,{detachedPayload:r,expectedKid:s,alg:"EdDSA"})?{valid:!0}:{valid:!1,reason:"Invalid JWS signature",errorCode:o.PROOF_VERIFICATION_ERROR_CODES.INVALID_JWS_SIGNATURE,details:{jwsLength:e.length,expectedKid:s,actualKid:t.kid}}}async addNonceToCache(e,t){await this.nonceCache.add(e,this.nonceTtlSeconds,t)}async fetchPublicKeyFromDID(e,t){try{const r=await this.fetch.resolveDID(e);if(!r)throw new o.ProofVerificationError(o.PROOF_VERIFICATION_ERROR_CODES.DID_DOCUMENT_NOT_FOUND,`DID document not found: ${e}`,{did:e});if(!r.verificationMethod||0===r.verificationMethod.length)throw new o.ProofVerificationError(o.PROOF_VERIFICATION_ERROR_CODES.VERIFICATION_METHOD_NOT_FOUND,`No verification methods found in DID document: ${e}`,{did:e});let s;if(t){const i=t.startsWith("#")?t:`#${t}`;if(s=r.verificationMethod.find(t=>t.id===i||t.id===`${e}${i}`),!s)throw new o.ProofVerificationError(o.PROOF_VERIFICATION_ERROR_CODES.VERIFICATION_METHOD_NOT_FOUND,`Verification method not found for kid: ${t}`,{did:e,kid:t,availableKids:r.verificationMethod.map(e=>e.id)})}else s=r.verificationMethod[0];if(!s?.publicKeyJwk)throw new o.ProofVerificationError(o.PROOF_VERIFICATION_ERROR_CODES.PUBLIC_KEY_NOT_FOUND,"Public key JWK not found in verification method",{did:e,kid:t,verificationMethodId:s?.id});const i=s.publicKeyJwk;if("OKP"!==i.kty||"Ed25519"!==i.crv||!i.x)throw new o.ProofVerificationError(o.PROOF_VERIFICATION_ERROR_CODES.INVALID_JWK_FORMAT,`Unsupported key type or curve: kty=${i.kty}, crv=${i.crv}`,{did:e,kid:t,jwk:{kty:i.kty,crv:i.crv}});return i}catch(r){if(r instanceof o.ProofVerificationError)throw r;throw console.error("[ProofVerifier] Failed to fetch public key from DID:",r),new o.ProofVerificationError(o.PROOF_VERIFICATION_ERROR_CODES.DID_RESOLUTION_FAILED,`DID resolution failed: ${r instanceof Error?r.message:String(r)}`,{did:e,kid:t,originalError:r instanceof Error?r.message:String(r)})}}buildCanonicalPayload(e){const t={aud:e.audience,sub:e.did,iss:e.did,requestHash:e.requestHash,responseHash:e.responseHash,ts:e.ts,nonce:e.nonce,sessionId:e.sessionId,...e.scopeId&&{scopeId:e.scopeId},...e.delegationRef&&{delegationRef:e.delegationRef},...e.clientDid&&{clientDid:e.clientDid}};return(0,a.canonicalize)(t)}}},46079:e=>{"use strict";var t=["multipleOf","maximum","exclusiveMaximum","minimum","exclusiveMinimum","maxLength","minLength","pattern","additionalItems","maxItems","minItems","uniqueItems","maxProperties","minProperties","required","additionalProperties","enum","format","const"];e.exports=function(e,r){for(var s=0;s<r.length;s++){e=JSON.parse(JSON.stringify(e));var i,a=r[s].split("/"),o=e;for(i=1;i<a.length;i++)o=o[a[i]];for(i=0;i<t.length;i++){var n=t[i],c=o[n];c&&(o[n]={anyOf:[c,{$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"}]})}}return e}},46137:e=>{"use strict";e.exports=function(e,t,r){var s=" ",i=e.level,a=e.dataLevel,o=e.schema[t],n=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,d=!e.opts.allErrors,l="data"+(a||""),u="valid"+i,h="errs__"+i,p=e.util.copy(e),f="";p.level++;var g="valid"+p.level,m=p.baseId,v="prevValid"+i,y="passingSchemas"+i;s+="var "+h+" = errors , "+v+" = false , "+u+" = false , "+y+" = null; ";var _=e.compositeRule;e.compositeRule=p.compositeRule=!0;var w=o;if(w)for(var b,S=-1,P=w.length-1;S<P;)b=w[S+=1],(e.opts.strictKeywords?"object"==typeof b&&Object.keys(b).length>0||!1===b:e.util.schemaHasRules(b,e.RULES.all))?(p.schema=b,p.schemaPath=n+"["+S+"]",p.errSchemaPath=c+"/"+S,s+=" "+e.validate(p)+" ",p.baseId=m):s+=" var "+g+" = true; ",S&&(s+=" if ("+g+" && "+v+") { "+u+" = false; "+y+" = ["+y+", "+S+"]; } else { ",f+="}"),s+=" if ("+g+") { "+u+" = "+v+" = true; "+y+" = "+S+"; }";return e.compositeRule=p.compositeRule=_,s+=f+"if (!"+u+") { var err = ",!1!==e.createErrors?(s+=" { keyword: 'oneOf' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { passingSchemas: "+y+" } ",!1!==e.opts.messages&&(s+=" , message: 'should match exactly one schema in oneOf' "),e.opts.verbose&&(s+=" , schema: validate.schema"+n+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),s+=" } "):s+=" {} ",s+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&d&&(e.async?s+=" throw new ValidationError(vErrors); ":s+=" validate.errors = vErrors; return false; "),s+="} else { errors = "+h+"; if (vErrors !== null) { if ("+h+") vErrors.length = "+h+"; else vErrors = null; }",e.opts.allErrors&&(s+=" } "),s}},46610:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BitstringManager=void 0,t.isIndexSet=async function(e,t,s){const i=r.base64urlDecode(e),a=await s.decompress(i),o=Math.floor(t/8),n=t%8;return!(o>=a.length)&&!!(a[o]&1<<n)};class r{compressor;decompressor;bits;size;constructor(e,t,r){this.compressor=t,this.decompressor=r,this.size=e;const s=Math.ceil(e/8);this.bits=new Uint8Array(s)}setBit(e,t){if(e<0||e>=this.size)throw new Error(`Bit index ${e} out of range (0-${this.size-1})`);const r=Math.floor(e/8),s=e%8;t?this.bits[r]|=1<<s:this.bits[r]&=~(1<<s)}getBit(e){if(e<0||e>=this.size)throw new Error(`Bit index ${e} out of range (0-${this.size-1})`);const t=Math.floor(e/8),r=e%8;return!!(this.bits[t]&1<<r)}getSetBits(){const e=[];for(let t=0;t<this.size;t++)this.getBit(t)&&e.push(t);return e}async encode(){const e=await this.compressor.compress(this.bits);return this.base64urlEncode(e)}static async decode(e,t,s){const i=r.base64urlDecode(e),a=await s.decompress(i),o=8*a.length,n=new r(o,t,s);return n.bits=a,n}getRawBits(){return this.bits}getSize(){return this.size}base64urlEncode(e){return this.bytesToBase64(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}static base64urlDecode(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");for(;t.length%4!=0;)t+="=";return r.base64ToBytes(t)}bytesToBase64(e){const t=Array.from(e).map(e=>String.fromCharCode(e)).join("");return btoa(t)}static base64ToBytes(e){const t=atob(e),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r}static fromSetBits(e,t,s,i){const a=new r(e,s,i);for(const e of t)a.setBit(e,!0);return a}}t.BitstringManager=r},48021:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NoOpOAuthConfigCache=t.InMemoryOAuthConfigCache=void 0,t.InMemoryOAuthConfigCache=class{cache=new Map;async get(e){const t=this.cache.get(e);return t?Date.now()>t.expiresAt?(this.cache.delete(e),null):t.value:null}async set(e,t,r){if(r<=0)return;const s=Date.now()+r;this.cache.set(e,{value:t,expiresAt:s})}async clear(){this.cache.clear()}async delete(e){this.cache.delete(e)}},t.NoOpOAuthConfigCache=class{async get(e){return null}async set(e,t,r){}async clear(){}async delete(e){}}},48505:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MemoryIdentityProvider=t.MemoryNonceCacheProvider=t.MemoryStorageProvider=void 0;const s=r(27087);class i extends s.StorageProvider{store=new Map;async get(e){return this.store.get(e)??null}async set(e,t){this.store.set(e,t)}async delete(e){this.store.delete(e)}async exists(e){return this.store.has(e)}async list(e){const t=Array.from(this.store.keys());return e?t.filter(t=>t.startsWith(e)):t}}t.MemoryStorageProvider=i;class a extends s.NonceCacheProvider{nonces=new Map;async has(e,t){const r=t?`nonce:${t}:${e}`:`nonce:${e}`,s=this.nonces.get(r);return!(!s||Date.now()>s&&(this.nonces.delete(r),1))}async add(e,t,r){const s=r?`nonce:${r}:${e}`:`nonce:${e}`,i=Date.now()+1e3*t;this.nonces.set(s,i)}async cleanup(){const e=Date.now();for(const[t,r]of this.nonces)e>r&&this.nonces.delete(t)}async destroy(){this.nonces.clear()}}t.MemoryNonceCacheProvider=a;class o extends s.IdentityProvider{identity;cryptoProvider;constructor(e){super(),this.cryptoProvider=e}async getIdentity(){return this.identity||(this.identity=await this.generateIdentity()),this.identity}async saveIdentity(e){this.identity=e}async rotateKeys(){return this.identity=await this.generateIdentity(),this.identity}async deleteIdentity(){this.identity=void 0}async generateIdentity(){if(!this.cryptoProvider)throw new Error("Crypto provider required for identity generation");const e=await this.cryptoProvider.generateKeyPair(),t=this.generateDIDFromPublicKey(e.publicKey);return{did:t,kid:`${t}#key-1`,privateKey:e.privateKey,publicKey:e.publicKey,createdAt:(new Date).toISOString(),type:"development"}}generateDIDFromPublicKey(e){return`did:key:z${Buffer.from(e,"base64").toString("base64url").substring(0,32)}`}}t.MemoryIdentityProvider=o},49436:e=>{function t(e){return Promise.resolve().then(()=>{var t=new Error("Cannot find module '"+e+"'");throw t.code="MODULE_NOT_FOUND",t})}t.keys=()=>[],t.resolve=t,t.id=49436,e.exports=t},50399:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OAuthProviderRegistry=void 0,t.OAuthProviderRegistry=class{configService;validator;providers=new Map;constructor(e,t){this.configService=e,this.validator=t}async loadFromAgentShield(e){const t=await this.configService.getOAuthConfig(e);this.providers.clear();for(const[e,r]of Object.entries(t.providers))this.providers.set(e,r)}getProvider(e){return this.providers.get(e)||null}getAllProviders(){return Array.from(this.providers.values())}hasProvider(e){return this.providers.has(e)}getProviderNames(){return Array.from(this.providers.keys())}registerCustomProvider(e,t){this.validator&&this.validator.validate(t,e),this.providers.set(e,t)}getProviderWithParams(e){return this.getProvider(e)||null}}},51708:(e,t,r)=>{"use strict";r.r(t),r.d(t,{canonicalize:()=>s.d,canonicalizeEx:()=>a});var s=r(77753),i=r(10985);function a(e,t){return(0,i.S)(e,t)}},52004:(e,t,r)=>{"use strict";e.exports={$ref:r(12857),allOf:r(67578),anyOf:r(14547),$comment:r(44413),const:r(59087),contains:r(24235),dependencies:r(90083),enum:r(68307),format:r(95545),if:r(82917),items:r(33728),maximum:r(71346),minimum:r(71346),maxItems:r(80536),minItems:r(80536),maxLength:r(83010),minLength:r(83010),maxProperties:r(96111),minProperties:r(96111),multipleOf:r(58047),not:r(13441),oneOf:r(46137),pattern:r(96774),properties:r(86343),propertyNames:r(9931),required:r(91939),uniqueItems:r(57817),validate:r(25572)}},52643:e=>{function t(e){return Promise.resolve().then(()=>{var t=new Error("Cannot find module '"+e+"'");throw t.code="MODULE_NOT_FOUND",t})}t.keys=()=>[],t.resolve=t,t.id=52643,e.exports=t},53084:(e,t,r)=>{"use strict";var s=r(22853),i=r(40985),a=r(28565),o=r(20812),n=r(56039),c=r(36885),d=r(20698),l=r(46079),u=r(9717);e.exports=v,v.prototype.validate=function(e,t){var r;if("string"==typeof e){if(!(r=this.getSchema(e)))throw new Error('no schema with key or ref "'+e+'"')}else{var s=this._addSchema(e);r=s.validate||this._compile(s)}var i=r(t);return!0!==r.$async&&(this.errors=r.errors),i},v.prototype.compile=function(e,t){var r=this._addSchema(e,void 0,t);return r.validate||this._compile(r)},v.prototype.addSchema=function(e,t,r,s){if(Array.isArray(e)){for(var a=0;a<e.length;a++)this.addSchema(e[a],void 0,r,s);return this}var o=this._getId(e);if(void 0!==o&&"string"!=typeof o)throw new Error("schema id must be string");return P(this,t=i.normalizeId(t||o)),this._schemas[t]=this._addSchema(e,r,s,!0),this},v.prototype.addMetaSchema=function(e,t,r){return this.addSchema(e,t,r,!0),this},v.prototype.validateSchema=function(e,t){var r,s,i=e.$schema;if(void 0!==i&&"string"!=typeof i)throw new Error("$schema must be a string");if(!(i=i||this._opts.defaultMeta||(r=this,s=r._opts.meta,r._opts.defaultMeta="object"==typeof s?r._getId(s)||s:r.getSchema(f)?f:void 0,r._opts.defaultMeta)))return this.logger.warn("meta-schema not available"),this.errors=null,!0;var a=this.validate(i,e);if(!a&&t){var o="schema is invalid: "+this.errorsText();if("log"!=this._opts.validateSchema)throw new Error(o);this.logger.error(o)}return a},v.prototype.getSchema=function(e){var t=y(this,e);switch(typeof t){case"object":return t.validate||this._compile(t);case"string":return this.getSchema(t);case"undefined":return function(e,t){var r=i.schema.call(e,{schema:{}},t);if(r){var a=r.schema,n=r.root,c=r.baseId,d=s.call(e,a,n,void 0,c);return e._fragments[t]=new o({ref:t,fragment:!0,schema:a,root:n,baseId:c,validate:d}),d}}(this,e)}},v.prototype.removeSchema=function(e){if(e instanceof RegExp)return _(this,this._schemas,e),_(this,this._refs,e),this;switch(typeof e){case"undefined":return _(this,this._schemas),_(this,this._refs),this._cache.clear(),this;case"string":var t=y(this,e);return t&&this._cache.del(t.cacheKey),delete this._schemas[e],delete this._refs[e],this;case"object":var r=this._opts.serialize,s=r?r(e):e;this._cache.del(s);var a=this._getId(e);a&&(a=i.normalizeId(a),delete this._schemas[a],delete this._refs[a])}return this},v.prototype.addFormat=function(e,t){return"string"==typeof t&&(t=new RegExp(t)),this._formats[e]=t,this},v.prototype.errorsText=function(e,t){if(!(e=e||this.errors))return"No errors";for(var r=void 0===(t=t||{}).separator?", ":t.separator,s=void 0===t.dataVar?"data":t.dataVar,i="",a=0;a<e.length;a++){var o=e[a];o&&(i+=s+o.dataPath+" "+o.message+r)}return i.slice(0,-r.length)},v.prototype._addSchema=function(e,t,r,s){if("object"!=typeof e&&"boolean"!=typeof e)throw new Error("schema should be object or boolean");var a=this._opts.serialize,n=a?a(e):e,c=this._cache.get(n);if(c)return c;s=s||!1!==this._opts.addUsedSchema;var d=i.normalizeId(this._getId(e));d&&s&&P(this,d);var l,u=!1!==this._opts.validateSchema&&!t;u&&!(l=d&&d==i.normalizeId(e.$schema))&&this.validateSchema(e,!0);var h=i.ids.call(this,e),p=new o({id:d,schema:e,localRefs:h,cacheKey:n,meta:r});return"#"!=d[0]&&s&&(this._refs[d]=p),this._cache.put(n,p),u&&l&&this.validateSchema(e,!0),p},v.prototype._compile=function(e,t){if(e.compiling)return e.validate=a,a.schema=e.schema,a.errors=null,a.root=t||a,!0===e.schema.$async&&(a.$async=!0),a;var r,i;e.compiling=!0,e.meta&&(r=this._opts,this._opts=this._metaOpts);try{i=s.call(this,e.schema,t,e.localRefs)}catch(t){throw delete e.validate,t}finally{e.compiling=!1,e.meta&&(this._opts=r)}return e.validate=i,e.refs=i.refs,e.refVal=i.refVal,e.root=i.root,i;function a(){var t=e.validate,r=t.apply(this,arguments);return a.errors=t.errors,r}},v.prototype.compileAsync=r(6069);var h=r(43528);v.prototype.addKeyword=h.add,v.prototype.getKeyword=h.get,v.prototype.removeKeyword=h.remove,v.prototype.validateKeyword=h.validate;var p=r(72916);v.ValidationError=p.Validation,v.MissingRefError=p.MissingRef,v.$dataMetaSchema=l;var f="http://json-schema.org/draft-07/schema",g=["removeAdditional","useDefaults","coerceTypes","strictDefaults"],m=["/properties"];function v(e){if(!(this instanceof v))return new v(e);e=this._opts=u.copy(e)||{},function(e){var t=e._opts.logger;if(!1===t)e.logger={log:E,warn:E,error:E};else{if(void 0===t&&(t=console),!("object"==typeof t&&t.log&&t.warn&&t.error))throw new Error("logger must implement log, warn and error methods");e.logger=t}}(this),this._schemas={},this._refs={},this._fragments={},this._formats=c(e.format),this._cache=e.cache||new a,this._loadingSchemas={},this._compilations=[],this.RULES=d(),this._getId=function(e){switch(e.schemaId){case"auto":return S;case"id":return w;default:return b}}(e),e.loopRequired=e.loopRequired||1/0,"property"==e.errorDataPath&&(e._errorDataPathProperty=!0),void 0===e.serialize&&(e.serialize=n),this._metaOpts=function(e){for(var t=u.copy(e._opts),r=0;r<g.length;r++)delete t[g[r]];return t}(this),e.formats&&function(e){for(var t in e._opts.formats){var r=e._opts.formats[t];e.addFormat(t,r)}}(this),e.keywords&&function(e){for(var t in e._opts.keywords){var r=e._opts.keywords[t];e.addKeyword(t,r)}}(this),function(e){var t;if(e._opts.$data&&(t=r(13215),e.addMetaSchema(t,t.$id,!0)),!1!==e._opts.meta){var s=r(12269);e._opts.$data&&(s=l(s,m)),e.addMetaSchema(s,f,!0),e._refs["http://json-schema.org/schema"]=f}}(this),"object"==typeof e.meta&&this.addMetaSchema(e.meta),e.nullable&&this.addKeyword("nullable",{metaSchema:{type:"boolean"}}),function(e){var t=e._opts.schemas;if(t)if(Array.isArray(t))e.addSchema(t);else for(var r in t)e.addSchema(t[r],r)}(this)}function y(e,t){return t=i.normalizeId(t),e._schemas[t]||e._refs[t]||e._fragments[t]}function _(e,t,r){for(var s in t){var i=t[s];i.meta||r&&!r.test(s)||(e._cache.del(i.cacheKey),delete t[s])}}function w(e){return e.$id&&this.logger.warn("schema $id ignored",e.$id),e.id}function b(e){return e.id&&this.logger.warn("schema id ignored",e.id),e.$id}function S(e){if(e.$id&&e.id&&e.$id!=e.id)throw new Error("schema $id is different from id");return e.$id||e.id}function P(e,t){if(e._schemas[t]||e._refs[t])throw new Error('schema with key or id "'+t+'" already exists')}function E(){}},53683:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProofVerificationError=t.PROOF_VERIFICATION_ERROR_CODES=void 0,t.createProofVerificationError=function(e,t,s){return new r(e,t,s)},t.PROOF_VERIFICATION_ERROR_CODES={INVALID_PROOF_STRUCTURE:"INVALID_PROOF_STRUCTURE",MISSING_REQUIRED_FIELD:"MISSING_REQUIRED_FIELD",NONCE_REPLAY_DETECTED:"NONCE_REPLAY_DETECTED",TIMESTAMP_SKEW_EXCEEDED:"TIMESTAMP_SKEW_EXCEEDED",TIMESTAMP_INVALID:"TIMESTAMP_INVALID",INVALID_JWS_SIGNATURE:"INVALID_JWS_SIGNATURE",INVALID_JWS_FORMAT:"INVALID_JWS_FORMAT",INVALID_JWS_HEADER:"INVALID_JWS_HEADER",INVALID_JWS_PAYLOAD:"INVALID_JWS_PAYLOAD",INVALID_JWS_SIGNATURE_BASE64:"INVALID_JWS_SIGNATURE_BASE64",UNSUPPORTED_ALGORITHM:"UNSUPPORTED_ALGORITHM",INVALID_JWK_FORMAT:"INVALID_JWK_FORMAT",INVALID_JWK_KTY:"INVALID_JWK_KTY",INVALID_JWK_CRV:"INVALID_JWK_CRV",INVALID_JWK_X_FIELD:"INVALID_JWK_X_FIELD",INVALID_JWK_KEY_LENGTH:"INVALID_JWK_KEY_LENGTH",JWK_KID_MISMATCH:"JWK_KID_MISMATCH",DID_RESOLUTION_FAILED:"DID_RESOLUTION_FAILED",DID_DOCUMENT_NOT_FOUND:"DID_DOCUMENT_NOT_FOUND",VERIFICATION_METHOD_NOT_FOUND:"VERIFICATION_METHOD_NOT_FOUND",PUBLIC_KEY_NOT_FOUND:"PUBLIC_KEY_NOT_FOUND",UNSUPPORTED_DID_METHOD:"UNSUPPORTED_DID_METHOD",VERIFICATION_ERROR:"VERIFICATION_ERROR",INTERNAL_ERROR:"INTERNAL_ERROR"};class r extends Error{code;details;constructor(e,t,r){super(t),this.code=e,this.details=r,this.name="ProofVerificationError"}}t.ProofVerificationError=r},53871:function(e,t,r){"use strict";var s=this&&this.__createBinding||(Object.create?function(e,t,r,s){void 0===s&&(s=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,s,i)}:function(e,t,r,s){void 0===s&&(s=r),e[s]=t[r]}),i=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||s(t,e,r)};Object.defineProperty(t,"__esModule",{value:!0}),i(r(17214),t),i(r(98448),t),i(r(32299),t),i(r(75306),t)},55921:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DelegationGraphManager=void 0,t.createDelegationGraph=function(e){return new r(e)};class r{storage;constructor(e){this.storage=e}async registerDelegation(e){const t={id:e.id,parentId:e.parentId,children:[],issuerDid:e.issuerDid,subjectDid:e.subjectDid,credentialStatusId:e.credentialStatusId};return await this.storage.setNode(t),e.parentId&&await this.addChildToParent(e.parentId,e.id),t}async addChildToParent(e,t){const r=await this.storage.getNode(e);if(!r)throw new Error(`Parent delegation not found: ${e}`);r.children.includes(t)||(r.children.push(t),await this.storage.setNode(r))}async getNode(e){return this.storage.getNode(e)}async getChildren(e){return this.storage.getChildren(e)}async getDescendants(e){return this.storage.getDescendants(e)}async getChain(e){return this.storage.getChain(e)}async isAncestor(e,t){return(await this.getChain(t)).some(t=>t.id===e)}async getDepth(e){return(await this.getChain(e)).length-1}async validateChain(e){const t=await this.getChain(e);if(0===t.length)return{valid:!1,reason:"Delegation not found"};for(let e=1;e<t.length;e++){const r=t[e-1],s=t[e];if(s.issuerDid!==r.subjectDid)return{valid:!1,reason:`Invalid chain: ${s.id} issued by ${s.issuerDid} but parent ${r.id} subject is ${r.subjectDid}`};if(s.parentId!==r.id)return{valid:!1,reason:`Invalid chain: ${s.id} parentId=${s.parentId} but actual parent is ${r.id}`}}return{valid:!0}}async removeDelegation(e){const t=await this.storage.getNode(e);if(t){if(t.parentId){const r=await this.storage.getNode(t.parentId);r&&(r.children=r.children.filter(t=>t!==e),await this.storage.setNode(r))}await this.storage.deleteNode(e)}}}t.DelegationGraphManager=r},56039:e=>{"use strict";e.exports=function(e,t){t||(t={}),"function"==typeof t&&(t={cmp:t});var r,s="boolean"==typeof t.cycles&&t.cycles,i=t.cmp&&(r=t.cmp,function(e){return function(t,s){var i={key:t,value:e[t]},a={key:s,value:e[s]};return r(i,a)}}),a=[];return function e(t){if(t&&t.toJSON&&"function"==typeof t.toJSON&&(t=t.toJSON()),void 0!==t){if("number"==typeof t)return isFinite(t)?""+t:"null";if("object"!=typeof t)return JSON.stringify(t);var r,o;if(Array.isArray(t)){for(o="[",r=0;r<t.length;r++)r&&(o+=","),o+=e(t[r])||"null";return o+"]"}if(null===t)return"null";if(-1!==a.indexOf(t)){if(s)return JSON.stringify("__cycle__");throw new TypeError("Converting circular structure to JSON")}var n=a.push(t)-1,c=Object.keys(t).sort(i&&i(t));for(o="",r=0;r<c.length;r++){var d=c[r],l=e(t[d]);l&&(o&&(o+=","),o+=JSON.stringify(d)+":"+l)}return a.splice(n,1),"{"+o+"}"}}(e)}},57817:e=>{"use strict";e.exports=function(e,t,r){var s,i=" ",a=e.level,o=e.dataLevel,n=e.schema[t],c=e.schemaPath+e.util.getProperty(t),d=e.errSchemaPath+"/"+t,l=!e.opts.allErrors,u="data"+(o||""),h="valid"+a,p=e.opts.$data&&n&&n.$data;if(p?(i+=" var schema"+a+" = "+e.util.getData(n.$data,o,e.dataPathArr)+"; ",s="schema"+a):s=n,(n||p)&&!1!==e.opts.uniqueItems){p&&(i+=" var "+h+"; if ("+s+" === false || "+s+" === undefined) "+h+" = true; else if (typeof "+s+" != 'boolean') "+h+" = false; else { "),i+=" var i = "+u+".length , "+h+" = true , j; if (i > 1) { ";var f=e.schema.items&&e.schema.items.type,g=Array.isArray(f);if(!f||"object"==f||"array"==f||g&&(f.indexOf("object")>=0||f.indexOf("array")>=0))i+=" outer: for (;i--;) { for (j = i; j--;) { if (equal("+u+"[i], "+u+"[j])) { "+h+" = false; break outer; } } } ";else{i+=" var itemIndices = {}, item; for (;i--;) { var item = "+u+"[i]; ";var m="checkDataType"+(g?"s":"");i+=" if ("+e.util[m](f,"item",e.opts.strictNumbers,!0)+") continue; ",g&&(i+=" if (typeof item == 'string') item = '\"' + item; "),i+=" if (typeof itemIndices[item] == 'number') { "+h+" = false; j = itemIndices[item]; break; } itemIndices[item] = i; } "}i+=" } ",p&&(i+=" } "),i+=" if (!"+h+") { ";var v=v||[];v.push(i),i="",!1!==e.createErrors?(i+=" { keyword: 'uniqueItems' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(d)+" , params: { i: i, j: j } ",!1!==e.opts.messages&&(i+=" , message: 'should NOT have duplicate items (items ## ' + j + ' and ' + i + ' are identical)' "),e.opts.verbose&&(i+=" , schema: ",i+=p?"validate.schema"+c:""+n,i+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),i+=" } "):i+=" {} ";var y=i;i=v.pop(),!e.compositeRule&&l?e.async?i+=" throw new ValidationError(["+y+"]); ":i+=" validate.errors = ["+y+"]; return false; ":i+=" var err = "+y+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",i+=" } ",l&&(i+=" else { ")}else l&&(i+=" if (true) { ");return i}},58047:e=>{"use strict";e.exports=function(e,t,r){var s,i=" ",a=e.level,o=e.dataLevel,n=e.schema[t],c=e.schemaPath+e.util.getProperty(t),d=e.errSchemaPath+"/"+t,l=!e.opts.allErrors,u="data"+(o||""),h=e.opts.$data&&n&&n.$data;if(h?(i+=" var schema"+a+" = "+e.util.getData(n.$data,o,e.dataPathArr)+"; ",s="schema"+a):s=n,!h&&"number"!=typeof n)throw new Error(t+" must be number");i+="var division"+a+";if (",h&&(i+=" "+s+" !== undefined && ( typeof "+s+" != 'number' || "),i+=" (division"+a+" = "+u+" / "+s+", ",e.opts.multipleOfPrecision?i+=" Math.abs(Math.round(division"+a+") - division"+a+") > 1e-"+e.opts.multipleOfPrecision+" ":i+=" division"+a+" !== parseInt(division"+a+") ",i+=" ) ",h&&(i+=" ) "),i+=" ) { ";var p=p||[];p.push(i),i="",!1!==e.createErrors?(i+=" { keyword: 'multipleOf' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(d)+" , params: { multipleOf: "+s+" } ",!1!==e.opts.messages&&(i+=" , message: 'should be multiple of ",i+=h?"' + "+s:s+"'"),e.opts.verbose&&(i+=" , schema: ",i+=h?"validate.schema"+c:""+n,i+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),i+=" } "):i+=" {} ";var f=i;return i=p.pop(),!e.compositeRule&&l?e.async?i+=" throw new ValidationError(["+f+"]); ":i+=" validate.errors = ["+f+"]; return false; ":i+=" var err = "+f+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",i+="} ",l&&(i+=" else { "),i}},59087:e=>{"use strict";e.exports=function(e,t,r){var s=" ",i=e.level,a=e.dataLevel,o=e.schema[t],n=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,d=!e.opts.allErrors,l="data"+(a||""),u="valid"+i,h=e.opts.$data&&o&&o.$data;h&&(s+=" var schema"+i+" = "+e.util.getData(o.$data,a,e.dataPathArr)+"; "),h||(s+=" var schema"+i+" = validate.schema"+n+";"),s+="var "+u+" = equal("+l+", schema"+i+"); if (!"+u+") { ";var p=p||[];p.push(s),s="",!1!==e.createErrors?(s+=" { keyword: 'const' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { allowedValue: schema"+i+" } ",!1!==e.opts.messages&&(s+=" , message: 'should be equal to constant' "),e.opts.verbose&&(s+=" , schema: validate.schema"+n+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),s+=" } "):s+=" {} ";var f=s;return s=p.pop(),!e.compositeRule&&d?e.async?s+=" throw new ValidationError(["+f+"]); ":s+=" validate.errors = ["+f+"]; return false; ":s+=" var err = "+f+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+=" }",d&&(s+=" else { "),s}},61812:e=>{"use strict";e.exports=function(e){for(var t,r=0,s=e.length,i=0;i<s;)r++,(t=e.charCodeAt(i++))>=55296&&t<=56319&&i<s&&56320==(64512&(t=e.charCodeAt(i)))&&i++;return r}},62175:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OAuthService=void 0,t.OAuthService=class{config;constructor(e){this.config={configService:e.configService,fetchProvider:e.fetchProvider,agentShieldApiUrl:e.agentShieldApiUrl,agentShieldApiKey:e.agentShieldApiKey,projectId:e.projectId,logger:e.logger||(()=>{})}}async exchangeToken(e,t,r,s){const i=(await this.config.configService.getOAuthConfig(this.config.projectId)).providers[e];if(!i)throw new Error(`Provider "${e}" not configured for project "${this.config.projectId}"`);if(i.supportsPKCE&&!i.proxyMode){if(!r)throw new Error(`Provider "${e}" requires PKCE code_verifier for token exchange`);return this.exchangeTokenPKCE(i,t,r,s||"")}if(i.proxyMode)return this.exchangeTokenProxy(i,t,r,s||"");throw new Error(`Provider "${e}" configuration is invalid: must support PKCE or use proxy mode`)}async exchangeTokenPKCE(e,t,r,s){this.config.logger("[OAuthService] Exchanging token with PKCE",{provider:e.authorizationUrl,tokenUrl:e.tokenUrl});const i=await this.config.fetchProvider.fetch(e.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new URLSearchParams({grant_type:"authorization_code",code:t,redirect_uri:s,client_id:e.clientId,code_verifier:r}).toString()});if(!i.ok){const t=await i.text().catch(()=>"Unknown error");let r;try{r=JSON.parse(t)}catch{r={error:t}}const s=r.error_description||r.error||t;throw this.config.logger("[OAuthService] Token exchange failed",{status:i.status,error:s,provider:e.tokenUrl}),new Error(`Token exchange failed: ${s} (${i.status})`)}const a=await i.json();if(!a.access_token)throw new Error("Token response missing access_token");const o=a.expires_in||3600,n=Date.now()+1e3*o,c={access_token:a.access_token,refresh_token:a.refresh_token,expires_in:o,expires_at:n,token_type:a.token_type||"Bearer",scope:a.scope};return this.config.logger("[OAuthService] Token exchange successful",{provider:e.tokenUrl,expiresAt:new Date(n).toISOString(),hasRefreshToken:!!c.refresh_token}),c}async exchangeTokenProxy(e,t,r,s){const i=`${this.config.agentShieldApiUrl}/api/v1/oauth/token`;this.config.logger("[OAuthService] Exchanging token via proxy",{proxyUrl:i,provider:e.authorizationUrl,hasCodeVerifier:!!r,supportsPKCE:e.supportsPKCE});const a={grant_type:"authorization_code",code:t,redirect_uri:s||"",provider:e.authorizationUrl,project_id:this.config.projectId};e.supportsPKCE&&r&&(a.code_verifier=r);const o=await this.config.fetchProvider.fetch(i,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.agentShieldApiKey}`},body:JSON.stringify(a)});if(!o.ok){const e=await o.text().catch(()=>"Unknown error");let t;try{t=JSON.parse(e)}catch{t={error:e}}const r=t.error_description||t.error||e;throw this.config.logger("[OAuthService] Proxy token exchange failed",{status:o.status,error:r,proxyUrl:i}),new Error(`Proxy token exchange failed: ${r} (${o.status})`)}const n=await o.json(),c=n.data||n;if(!c.access_token)throw new Error("Proxy token response missing access_token");const d=c.expires_in||3600,l=Date.now()+1e3*d,u={access_token:c.access_token,refresh_token:c.refresh_token,expires_in:d,expires_at:l,token_type:c.token_type||"Bearer",scope:c.scope};return this.config.logger("[OAuthService] Proxy token exchange successful",{proxyUrl:i,expiresAt:new Date(l).toISOString(),hasRefreshToken:!!u.refresh_token}),u}async refreshToken(e,t){const r=(await this.config.configService.getOAuthConfig(this.config.projectId)).providers[e];return r?r.supportsPKCE&&!r.proxyMode?this.refreshTokenPKCE(r,t):r.proxyMode?this.refreshTokenProxy(r,t):null:(this.config.logger("[OAuthService] Provider not found for refresh",{provider:e}),null)}async refreshTokenPKCE(e,t){this.config.logger("[OAuthService] Refreshing token with PKCE",{provider:e.tokenUrl});try{const r=await this.config.fetchProvider.fetch(e.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:t,client_id:e.clientId}).toString()});if(!r.ok)return this.config.logger("[OAuthService] Token refresh failed",{status:r.status,provider:e.tokenUrl}),null;const s=await r.json();if(!s.access_token)return this.config.logger("[OAuthService] Token refresh response missing access_token"),null;const i=s.expires_in||3600,a=Date.now()+1e3*i,o={access_token:s.access_token,refresh_token:s.refresh_token||t,expires_in:i,expires_at:a,token_type:s.token_type||"Bearer",scope:s.scope};return this.config.logger("[OAuthService] Token refresh successful",{provider:e.tokenUrl,expiresAt:new Date(a).toISOString()}),o}catch(t){return this.config.logger("[OAuthService] Token refresh error",{error:t instanceof Error?t.message:String(t),provider:e.tokenUrl}),null}}async refreshTokenProxy(e,t){const r=`${this.config.agentShieldApiUrl}/api/v1/oauth/token`;this.config.logger("[OAuthService] Refreshing token via proxy",{proxyUrl:r,provider:e.authorizationUrl});try{const s=await this.config.fetchProvider.fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.agentShieldApiKey}`},body:JSON.stringify({grant_type:"refresh_token",refresh_token:t,provider:e.authorizationUrl,project_id:this.config.projectId})});if(!s.ok)return this.config.logger("[OAuthService] Proxy token refresh failed",{status:s.status,proxyUrl:r}),null;const i=await s.json(),a=i.data||i;if(!a.access_token)return this.config.logger("[OAuthService] Proxy token refresh response missing access_token"),null;const o=a.expires_in||3600,n=Date.now()+1e3*o,c={access_token:a.access_token,refresh_token:a.refresh_token||t,expires_in:o,expires_at:n,token_type:a.token_type||"Bearer",scope:a.scope};return this.config.logger("[OAuthService] Proxy token refresh successful",{proxyUrl:r,expiresAt:new Date(n).toISOString()}),c}catch(e){return this.config.logger("[OAuthService] Proxy token refresh error",{error:e instanceof Error?e.message:String(e),proxyUrl:r}),null}}}},62408:e=>{"use strict";e.exports=require("@kya-os/contracts")},63969:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.canonicalizeJSON=function e(t){if(null===t)return"null";if("boolean"==typeof t)return t.toString();if("number"==typeof t){if(!isFinite(t))throw new Error("Cannot canonicalize non-finite number");return JSON.stringify(t)}if("string"==typeof t)return JSON.stringify(t);if(Array.isArray(t))return"["+t.map(t=>e(t)).join(",")+"]";if("object"==typeof t)return"{"+Object.keys(t).sort().map(r=>{const s=e(t[r]);return JSON.stringify(r)+":"+s}).join(",")+"}";throw new Error("Cannot canonicalize type: "+typeof t)}},65067:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UserDidManager=void 0,t.UserDidManager=class{config;sessionDidCache=new Map;constructor(e){this.config=e}async getOrCreateUserDid(e,t){if(this.sessionDidCache.has(e))return this.sessionDidCache.get(e);if(t&&t.provider&&t.subject&&this.config.storage?.getByOAuth)try{const r=await this.config.storage.getByOAuth(t.provider,t.subject);if(r){if(console.log("[UserDidManager] Found persistent user DID from OAuth mapping:",{provider:t.provider,userDid:r.substring(0,20)+"..."}),this.sessionDidCache.set(e,r),this.config.storage)try{await this.config.storage.set(e,r,1800)}catch(e){console.warn("[UserDidManager] Failed to cache persistent DID in session storage:",e)}return r}}catch(e){console.warn("[UserDidManager] OAuth lookup failed, falling back to session storage:",e)}if(this.config.storage)try{const r=await this.config.storage.get(e);if(r){if(this.sessionDidCache.set(e,r),t&&t.provider&&t.subject&&this.config.storage.setByOAuth)try{await this.config.storage.setByOAuth(t.provider,t.subject,r,7776e3),console.log("[UserDidManager] Created persistent OAuth mapping for existing user DID:",{provider:t.provider,userDid:r.substring(0,20)+"..."})}catch(e){console.warn("[UserDidManager] Failed to create OAuth mapping:",e)}return r}}catch(e){console.warn("[UserDidManager] Storage.get failed, generating new DID:",e)}const r=await this.generateUserDid();if(this.sessionDidCache.set(e,r),this.config.storage)try{await this.config.storage.set(e,r,1800)}catch(e){console.warn("[UserDidManager] Storage.set failed, continuing with cached DID:",e)}if(t&&t.provider&&t.subject&&this.config.storage?.setByOAuth)try{await this.config.storage.setByOAuth(t.provider,t.subject,r,7776e3),console.log("[UserDidManager] Created persistent OAuth mapping for new user DID:",{provider:t.provider,userDid:r.substring(0,20)+"..."})}catch(e){console.warn("[UserDidManager] Failed to create OAuth mapping:",e)}return r}async generateUserDid(){this.config.useDidWeb&&this.config.didWebBaseUrl&&console.warn("[UserDidManager] did:web not yet implemented, using did:key");const e=await this.config.crypto.generateKeyPair(),t=this.base64ToBytes(e.publicKey);return this.generateDidKeyFromPublicKey(t)}generateDidKeyFromPublicKey(e){const t=new Uint8Array([237,1]),r=new Uint8Array(t.length+e.length);return r.set(t),r.set(e,t.length),`did:key:z${this.base58Encode(r)}`}base58Encode(e){let t=BigInt(0);for(let r=0;r<e.length;r++)t=t*BigInt(256)+BigInt(e[r]);let r="";for(;t>0;)r="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"[Number(t%BigInt(58))]+r,t/=BigInt(58);for(let t=0;t<e.length&&0===e[t];t++)r="1"+r;return r}base64ToBytes(e){if("undefined"!=typeof Buffer)return new Uint8Array(Buffer.from(e,"base64"));{const t=atob(e),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r}}async getUserDid(e){if(this.sessionDidCache.has(e))return this.sessionDidCache.get(e);if(this.config.storage){const t=await this.config.storage.get(e);if(t)return this.sessionDidCache.set(e,t),t}return null}async clearUserDid(e){if(this.sessionDidCache.delete(e),this.config.storage)try{await this.config.storage.delete(e)}catch(e){console.warn("[UserDidManager] Storage.delete failed, continuing:",e)}}clearCache(){this.sessionDidCache.clear()}}},67371:e=>{"use strict";e.exports=function e(t,r){if(t===r)return!0;if(t&&r&&"object"==typeof t&&"object"==typeof r){if(t.constructor!==r.constructor)return!1;var s,i,a;if(Array.isArray(t)){if((s=t.length)!=r.length)return!1;for(i=s;0!==i--;)if(!e(t[i],r[i]))return!1;return!0}if(t.constructor===RegExp)return t.source===r.source&&t.flags===r.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===r.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===r.toString();if((s=(a=Object.keys(t)).length)!==Object.keys(r).length)return!1;for(i=s;0!==i--;)if(!Object.prototype.hasOwnProperty.call(r,a[i]))return!1;for(i=s;0!==i--;){var o=a[i];if(!e(t[o],r[o]))return!1}return!0}return t!=t&&r!=r}},67578:e=>{"use strict";e.exports=function(e,t,r){var s=" ",i=e.schema[t],a=e.schemaPath+e.util.getProperty(t),o=e.errSchemaPath+"/"+t,n=!e.opts.allErrors,c=e.util.copy(e),d="";c.level++;var l="valid"+c.level,u=c.baseId,h=!0,p=i;if(p)for(var f,g=-1,m=p.length-1;g<m;)f=p[g+=1],(e.opts.strictKeywords?"object"==typeof f&&Object.keys(f).length>0||!1===f:e.util.schemaHasRules(f,e.RULES.all))&&(h=!1,c.schema=f,c.schemaPath=a+"["+g+"]",c.errSchemaPath=o+"/"+g,s+=" "+e.validate(c)+" ",c.baseId=u,n&&(s+=" if ("+l+") { ",d+="}"));return n&&(s+=h?" if (true) { ":" "+d.slice(0,-1)+" "),s}},68252:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProviderResolver=void 0,t.ProviderResolver=class{registry;configService;constructor(e,t){this.registry=e,this.configService=t}async resolveProvider(e,t){if(e.oauthProvider){if(0===this.registry.getProviderNames().length&&await this.registry.loadFromAgentShield(t),!this.registry.hasProvider(e.oauthProvider))throw new Error(`Provider "${e.oauthProvider}" not configured for project "${t}". Add provider in project settings.`);return e.oauthProvider}const r=this.inferProviderFromScopes(e.requiredScopes||[]);if(r&&(0===this.registry.getProviderNames().length&&await this.registry.loadFromAgentShield(t),this.registry.hasProvider(r)))return console.log(`[ProviderResolver] Inferred provider "${r}" from scopes`),r;if(await this.registry.loadFromAgentShield(t),this.registry.getAllProviders().length>0){const e=this.registry.getProviderNames()[0];return console.warn(`[ProviderResolver] Tool does not specify oauthProvider. Using first configured provider "${e}" as fallback. This is deprecated - configure oauthProvider in AgentShield dashboard for Phase 2+.`),e}throw new Error(`Tool requires OAuth but no provider could be resolved. Either specify oauthProvider in tool protection config, or configure at least one provider for project "${t}".`)}inferProviderFromScopes(e){if(!e||0===e.length)return null;const t=e.map(e=>e.split(":")[0].toLowerCase()),r={github:"github",google:"google",gmail:"google",calendar:"google",microsoft:"microsoft",outlook:"microsoft",slack:"slack",auth0:"auth0",okta:"okta"},s=new Set(t.map(e=>r[e]).filter(Boolean));return 1===s.size?Array.from(s)[0]:null}}},68307:e=>{"use strict";e.exports=function(e,t,r){var s=" ",i=e.level,a=e.dataLevel,o=e.schema[t],n=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,d=!e.opts.allErrors,l="data"+(a||""),u="valid"+i,h=e.opts.$data&&o&&o.$data;h&&(s+=" var schema"+i+" = "+e.util.getData(o.$data,a,e.dataPathArr)+"; ");var p="i"+i,f="schema"+i;h||(s+=" var "+f+" = validate.schema"+n+";"),s+="var "+u+";",h&&(s+=" if (schema"+i+" === undefined) "+u+" = true; else if (!Array.isArray(schema"+i+")) "+u+" = false; else {"),s+=u+" = false;for (var "+p+"=0; "+p+"<"+f+".length; "+p+"++) if (equal("+l+", "+f+"["+p+"])) { "+u+" = true; break; }",h&&(s+=" } "),s+=" if (!"+u+") { ";var g=g||[];g.push(s),s="",!1!==e.createErrors?(s+=" { keyword: 'enum' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { allowedValues: schema"+i+" } ",!1!==e.opts.messages&&(s+=" , message: 'should be equal to one of the allowed values' "),e.opts.verbose&&(s+=" , schema: validate.schema"+n+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),s+=" } "):s+=" {} ";var m=s;return s=g.pop(),!e.compositeRule&&d?e.async?s+=" throw new ValidationError(["+m+"]); ":s+=" validate.errors = ["+m+"]; return false; ":s+=" var err = "+m+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+=" }",d&&(s+=" else { "),s}},71346:e=>{"use strict";e.exports=function(e,t,r){var s,i=" ",a=e.level,o=e.dataLevel,n=e.schema[t],c=e.schemaPath+e.util.getProperty(t),d=e.errSchemaPath+"/"+t,l=!e.opts.allErrors,u="data"+(o||""),h=e.opts.$data&&n&&n.$data;h?(i+=" var schema"+a+" = "+e.util.getData(n.$data,o,e.dataPathArr)+"; ",s="schema"+a):s=n;var p="maximum"==t,f=p?"exclusiveMaximum":"exclusiveMinimum",g=e.schema[f],m=e.opts.$data&&g&&g.$data,v=p?"<":">",y=p?">":"<",_=void 0;if(!h&&"number"!=typeof n&&void 0!==n)throw new Error(t+" must be number");if(!m&&void 0!==g&&"number"!=typeof g&&"boolean"!=typeof g)throw new Error(f+" must be number or boolean");if(m){var w,b=e.util.getData(g.$data,o,e.dataPathArr),S="exclusive"+a,P="exclType"+a,E="exclIsNumber"+a,I="' + "+(C="op"+a)+" + '";i+=" var schemaExcl"+a+" = "+b+"; ",i+=" var "+S+"; var "+P+" = typeof "+(b="schemaExcl"+a)+"; if ("+P+" != 'boolean' && "+P+" != 'undefined' && "+P+" != 'number') { ",_=f,(w=w||[]).push(i),i="",!1!==e.createErrors?(i+=" { keyword: '"+(_||"_exclusiveLimit")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(d)+" , params: {} ",!1!==e.opts.messages&&(i+=" , message: '"+f+" should be boolean' "),e.opts.verbose&&(i+=" , schema: validate.schema"+c+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),i+=" } "):i+=" {} ";var k=i;i=w.pop(),!e.compositeRule&&l?e.async?i+=" throw new ValidationError(["+k+"]); ":i+=" validate.errors = ["+k+"]; return false; ":i+=" var err = "+k+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",i+=" } else if ( ",h&&(i+=" ("+s+" !== undefined && typeof "+s+" != 'number') || "),i+=" "+P+" == 'number' ? ( ("+S+" = "+s+" === undefined || "+b+" "+v+"= "+s+") ? "+u+" "+y+"= "+b+" : "+u+" "+y+" "+s+" ) : ( ("+S+" = "+b+" === true) ? "+u+" "+y+"= "+s+" : "+u+" "+y+" "+s+" ) || "+u+" !== "+u+") { var op"+a+" = "+S+" ? '"+v+"' : '"+v+"='; ",void 0===n&&(_=f,d=e.errSchemaPath+"/"+f,s=b,h=m)}else if(I=v,(E="number"==typeof g)&&h){var C="'"+I+"'";i+=" if ( ",h&&(i+=" ("+s+" !== undefined && typeof "+s+" != 'number') || "),i+=" ( "+s+" === undefined || "+g+" "+v+"= "+s+" ? "+u+" "+y+"= "+g+" : "+u+" "+y+" "+s+" ) || "+u+" !== "+u+") { "}else E&&void 0===n?(S=!0,_=f,d=e.errSchemaPath+"/"+f,s=g,y+="="):(E&&(s=Math[p?"min":"max"](g,n)),g===(!E||s)?(S=!0,_=f,d=e.errSchemaPath+"/"+f,y+="="):(S=!1,I+="=")),C="'"+I+"'",i+=" if ( ",h&&(i+=" ("+s+" !== undefined && typeof "+s+" != 'number') || "),i+=" "+u+" "+y+" "+s+" || "+u+" !== "+u+") { ";return _=_||t,(w=w||[]).push(i),i="",!1!==e.createErrors?(i+=" { keyword: '"+(_||"_limit")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(d)+" , params: { comparison: "+C+", limit: "+s+", exclusive: "+S+" } ",!1!==e.opts.messages&&(i+=" , message: 'should be "+I+" ",i+=h?"' + "+s:s+"'"),e.opts.verbose&&(i+=" , schema: ",i+=h?"validate.schema"+c:""+n,i+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),i+=" } "):i+=" {} ",k=i,i=w.pop(),!e.compositeRule&&l?e.async?i+=" throw new ValidationError(["+k+"]); ":i+=" validate.errors = ["+k+"]; return false; ":i+=" var err = "+k+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",i+=" } ",l&&(i+=" else { "),i}},72114:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ToolContextBuilder=void 0;const s=r(27399);t.ToolContextBuilder=class{config;constructor(e){this.config={tokenResolver:e.tokenResolver,configService:e.configService,providerResolver:e.providerResolver,projectId:e.projectId,logger:e.logger||(()=>{})}}async buildContext(e,t,r,i,a){if(!a?.requiredScopes?.length||!t)return;let o;try{o=await this.resolveProvider(a)}catch(r){return void this.config.logger("[ToolContextBuilder] Provider not resolved",{toolName:e,userDid:t.substring(0,20)+"...",error:r instanceof Error?r.message:String(r)})}const n=await this.config.tokenResolver.resolveTokenFromDid(t,o,a.requiredScopes);if(!n)throw this.config.logger("[ToolContextBuilder] Token not available, throwing OAuthRequiredError",{toolName:e,userDid:t.substring(0,20)+"...",provider:o,scopes:a.requiredScopes}),new s.OAuthRequiredError({toolName:e,requiredScopes:a.requiredScopes,provider:o,oauthUrl:"",userDid:t,sessionId:r});const c={idpToken:n,provider:o,scopes:a.requiredScopes,userDid:t,sessionId:r,delegationToken:i};return this.config.logger("[ToolContextBuilder] Context built successfully",{toolName:e,userDid:t.substring(0,20)+"...",provider:o,hasToken:!!n}),c}async resolveProvider(e){try{const t=await this.config.providerResolver.resolveProvider(e,this.config.projectId);return this.config.logger("[ToolContextBuilder] Provider resolved",{provider:t}),t}catch(e){throw this.config.logger("[ToolContextBuilder] Provider resolution failed",{error:e instanceof Error?e.message:String(e),projectId:this.config.projectId}),e}}}},72916:(e,t,r)=>{"use strict";var s=r(40985);function i(e,t,r){this.message=r||i.message(e,t),this.missingRef=s.url(e,t),this.missingSchema=s.normalizeId(s.fullPath(this.missingRef))}function a(e){return e.prototype=Object.create(Error.prototype),e.prototype.constructor=e,e}e.exports={Validation:a(function(e){this.message="validation failed",this.errors=e,this.ajv=this.validation=!0}),MissingRef:a(i)},i.message=function(e,t){return"can't resolve reference "+t+" from id "+e}},75306:(e,t)=>{"use strict";function r(e){return"string"==typeof e&&e.startsWith("did:")}function s(e){return e.trim()}function i(e){const t=e.split(":");return t[t.length-1]}Object.defineProperty(t,"__esModule",{value:!0}),t.isValidDid=r,t.getDidMethod=function(e){if(!r(e))return null;const t=e.match(/^did:([^:]+):/);return t?t[1]:null},t.normalizeDid=s,t.compareDids=function(e,t){return s(e)===s(t)},t.getServerDid=function(e){const t=e.identity.serverDid||e.identity.agentDid;if(!t)throw new Error("Server DID not configured");return t},t.extractAgentId=i,t.extractAgentSlug=function(e){return i(e)}},77311:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fetchRemoteConfig=t.ProviderRuntimeConfigBuilder=void 0,t.createProviderRuntimeConfig=function(e,t){return(new s).withProviders(e).withEnvironment(t?.environment||"development").withSession(t?.session||{}).withIdentity(t?.identity||{enabled:!1,environment:"development"}).withProofing(t?.proofing||{enabled:!1}).withDelegation(t?.delegation||{enabled:!1,verifier:{type:"memory"}}).withAudit(t?.audit||{enabled:!1}).withWellKnown(t?.wellKnown||{enabled:!0}).build()};class s{config={environment:"development"};withProviders(e){return Object.assign(this.config,e),this}withEnvironment(e){return this.config.environment=e,this}withSession(e){return this.config.session=e,this}withIdentity(e){return this.config.identity=e,this}withProofing(e){return this.config.proofing=e,this}withDelegation(e){return this.config.delegation=e,this}withToolProtectionService(e){return this.config.toolProtectionService=e,this}withToolProtection(e){return this.config.toolProtection=e,this}withAudit(e){return this.config.audit=e,this}withWellKnown(e){return this.config.wellKnown=e,this}build(){const e=["cryptoProvider","clockProvider","fetchProvider","storageProvider","nonceCacheProvider","identityProvider"];for(const t of e)if(!(t in this.config))throw new Error(`Missing required provider: ${t}`);return{environment:"development",session:{timestampSkewSeconds:120,ttlMinutes:30},...this.config}}}t.ProviderRuntimeConfigBuilder=s;var i=r(82811);Object.defineProperty(t,"fetchRemoteConfig",{enumerable:!0,get:function(){return i.fetchRemoteConfig}})},77460:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DelegationCredentialVerifier=void 0,t.createDelegationVerifier=function(e){return new i(e)};const s=r(62408);class i{didResolver;statusListResolver;signatureVerifier;cache=new Map;cacheTtl;constructor(e){this.didResolver=e?.didResolver,this.statusListResolver=e?.statusListResolver,this.signatureVerifier=e?.signatureVerifier,this.cacheTtl=e?.cacheTtl||6e4}async verifyDelegationCredential(e,t={}){const r=Date.now();if(!t.skipCache){const t=this.getFromCache(e.id||"");if(t)return{...t,cached:!0}}const s=Date.now(),i=this.validateBasicProperties(e),a=Date.now()-s;if(!i.valid)return{valid:!1,reason:i.reason,stage:"basic",metrics:{basicCheckMs:a,totalMs:Date.now()-r},checks:{basicValid:!1}};const o=t.skipSignature?Promise.resolve({valid:!0,durationMs:0}):this.verifySignature(e,t.didResolver||this.didResolver),n=!t.skipStatus&&e.credentialStatus?this.checkCredentialStatus(e.credentialStatus,t.statusListResolver||this.statusListResolver):Promise.resolve({valid:!0,durationMs:0}),[c,d]=await Promise.all([o,n]),l=c.durationMs||0,u=d.durationMs||0,h=i.valid&&c.valid&&d.valid,p={valid:h,reason:h?void 0:c.reason||d.reason||"Unknown failure",stage:"complete",metrics:{basicCheckMs:a,signatureCheckMs:l,statusCheckMs:u,totalMs:Date.now()-r},checks:{basicValid:i.valid,signatureValid:c.valid,statusValid:d.valid}};return p.valid&&e.id&&this.setInCache(e.id,p),p}validateBasicProperties(e){const t=(0,s.validateDelegationCredential)(e);if(!t.success)return{valid:!1,reason:`Schema validation failed: ${t.error.message}`};if((0,s.isDelegationCredentialExpired)(e))return{valid:!1,reason:"Delegation credential expired"};if((0,s.isDelegationCredentialNotYetValid)(e))return{valid:!1,reason:"Delegation credential not yet valid"};const r=e.credentialSubject.delegation;return"revoked"===r.status?{valid:!1,reason:"Delegation status is revoked"}:"expired"===r.status?{valid:!1,reason:"Delegation status is expired"}:r.issuerDid&&r.subjectDid?e.proof?{valid:!0}:{valid:!1,reason:"Missing proof"}:{valid:!1,reason:"Missing issuer or subject DID"}}async verifySignature(e,t){const r=Date.now();try{const s="string"==typeof e.issuer?e.issuer:e.issuer.id;if(!t||!this.signatureVerifier)return{valid:!0,reason:"No DID resolver or signature verifier available, skipping signature verification",durationMs:Date.now()-r};const i=await t.resolve(s);if(!i)return{valid:!1,reason:`Could not resolve issuer DID: ${s}`,durationMs:Date.now()-r};if(!e.proof)return{valid:!1,reason:"Proof is missing",durationMs:Date.now()-r};const a=e.proof.verificationMethod;if(!a)return{valid:!1,reason:"Proof missing verificationMethod",durationMs:Date.now()-r};const o=this.findVerificationMethod(i,a);if(!o)return{valid:!1,reason:`Verification method ${a} not found`,durationMs:Date.now()-r};const n=o.publicKeyJwk;if(!n)return{valid:!1,reason:"Verification method missing publicKeyJwk",durationMs:Date.now()-r};const c=await this.signatureVerifier(e,n);return{valid:c.valid,reason:c.reason,durationMs:Date.now()-r}}catch(e){return{valid:!1,reason:`Signature verification error: ${e instanceof Error?e.message:"Unknown error"}`,durationMs:Date.now()-r}}}async checkCredentialStatus(e,t){const r=Date.now();try{return t?await t.checkStatus(e)?{valid:!1,reason:`Credential revoked via StatusList2021 (${e.statusPurpose})`,durationMs:Date.now()-r}:{valid:!0,durationMs:Date.now()-r}:{valid:!0,reason:"No status list resolver available, skipping status check",durationMs:Date.now()-r}}catch(e){return{valid:!1,reason:`Status check error: ${e instanceof Error?e.message:"Unknown error"}`,durationMs:Date.now()-r}}}findVerificationMethod(e,t){return e.verificationMethod?.find(e=>e.id===t)}getFromCache(e){const t=this.cache.get(e);return t?Date.now()>t.expiresAt?(this.cache.delete(e),null):t.result:null}setInCache(e,t){this.cache.set(e,{result:t,expiresAt:Date.now()+this.cacheTtl})}clearCache(){this.cache.clear()}clearCacheEntry(e){this.cache.delete(e)}}t.DelegationCredentialVerifier=i},77753:(e,t,r)=>{"use strict";r.d(t,{d:()=>i});var s=r(10985);function i(e,t){return(0,s.S)(e,{allowCircular:t,filterUndefined:!0,undefinedInArrayToNull:!0})}},80536:e=>{"use strict";e.exports=function(e,t,r){var s,i=" ",a=e.level,o=e.dataLevel,n=e.schema[t],c=e.schemaPath+e.util.getProperty(t),d=e.errSchemaPath+"/"+t,l=!e.opts.allErrors,u="data"+(o||""),h=e.opts.$data&&n&&n.$data;if(h?(i+=" var schema"+a+" = "+e.util.getData(n.$data,o,e.dataPathArr)+"; ",s="schema"+a):s=n,!h&&"number"!=typeof n)throw new Error(t+" must be number");i+="if ( ",h&&(i+=" ("+s+" !== undefined && typeof "+s+" != 'number') || "),i+=" "+u+".length "+("maxItems"==t?">":"<")+" "+s+") { ";var p=t,f=f||[];f.push(i),i="",!1!==e.createErrors?(i+=" { keyword: '"+(p||"_limitItems")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(d)+" , params: { limit: "+s+" } ",!1!==e.opts.messages&&(i+=" , message: 'should NOT have ",i+="maxItems"==t?"more":"fewer",i+=" than ",i+=h?"' + "+s+" + '":""+n,i+=" items' "),e.opts.verbose&&(i+=" , schema: ",i+=h?"validate.schema"+c:""+n,i+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),i+=" } "):i+=" {} ";var g=i;return i=f.pop(),!e.compositeRule&&l?e.async?i+=" throw new ValidationError(["+g+"]); ":i+=" validate.errors = ["+g+"]; return false; ":i+=" var err = "+g+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",i+="} ",l&&(i+=" else { "),i}},81296:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CryptoService=void 0;const s=r(98448);t.CryptoService=class{cryptoProvider;constructor(e){this.cryptoProvider=e}async verifyEd25519(e,t,r){try{return!0===await this.cryptoProvider.verify(e,t,r)}catch(e){return console.error("[CryptoService] Ed25519 verification error:",e),!1}}parseJWS(e){const t=e.split(".");if(3!==t.length)throw new Error("Invalid JWS format: expected header.payload.signature");const[r,i,a]=t;let o,n,c;try{o=JSON.parse((0,s.base64urlDecodeToString)(r))}catch(e){throw new Error(`Invalid header base64: ${e instanceof Error?e.message:String(e)}`)}if(i)try{n=JSON.parse((0,s.base64urlDecodeToString)(i))}catch(e){throw new Error(`Invalid payload base64: ${e instanceof Error?e.message:String(e)}`)}try{c=(0,s.base64urlDecodeToBytes)(a)}catch(e){throw new Error(`Invalid signature base64: ${e instanceof Error?e.message:String(e)}`)}return{header:o,payload:n,signatureBytes:c,signingInput:`${r}.${i}`}}async verifyJWS(e,t,r){try{if(!this.isValidEd25519JWK(t))return console.error("[CryptoService] Invalid Ed25519 JWK format"),!1;if(r?.expectedKid&&t.kid!==r.expectedKid)return console.error("[CryptoService] Key ID mismatch"),!1;let i;try{i=this.parseJWS(e)}catch(t){if(void 0===r?.detachedPayload)return console.error("[CryptoService] Invalid JWS format:",t),!1;{const r=e.split(".");if(3!==r.length||""!==r[1])return console.error("[CryptoService] Invalid JWS format:",t),!1;try{const e=r[0],t=r[2];i={header:JSON.parse((0,s.base64urlDecodeToString)(e)),payload:void 0,signatureBytes:(0,s.base64urlDecodeToBytes)(t),signingInput:""}}catch{return console.error("[CryptoService] Invalid detached JWS format"),!1}}}const a=r?.alg||"EdDSA";if(i.header.alg!==a)return console.error(`[CryptoService] Unsupported algorithm: ${i.header.alg}, expected ${a}`),!1;let o,n,c;if(void 0!==r?.detachedPayload){const t=e.split(".")[0];let i;i=r.detachedPayload instanceof Uint8Array?(0,s.base64urlEncodeFromBytes)(r.detachedPayload):(0,s.base64urlEncodeFromBytes)((new TextEncoder).encode(r.detachedPayload)),o=`${t}.${i}`,n=(new TextEncoder).encode(o)}else{if(!i.signingInput)return console.error("[CryptoService] Missing signing input for compact JWS"),!1;o=i.signingInput,n=(new TextEncoder).encode(o)}try{c=this.jwkToBase64PublicKey(t)}catch(e){return console.error("[CryptoService] Failed to extract public key:",e),!1}return await this.verifyEd25519(n,i.signatureBytes,c)}catch(e){return console.error("[CryptoService] JWS verification error:",e),!1}}isValidEd25519JWK(e){return"object"==typeof e&&null!==e&&"kty"in e&&"OKP"===e.kty&&"crv"in e&&"Ed25519"===e.crv&&"x"in e&&"string"==typeof e.x&&e.x.length>0}jwkToBase64PublicKey(e){const t=(0,s.base64urlDecodeToBytes)(e.x);if(32!==t.length)throw new Error(`Invalid Ed25519 public key length: ${t.length}`);return(0,s.bytesToBase64)(t)}}},82811:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fetchRemoteConfig=async function(e,t){const{apiUrl:r,apiKey:i,projectId:a,agentDid:o,cacheTtl:n=3e5,fetchProvider:c}=e,d=a?`config:project:${a}`:o?`config:agent:${o}`:null;if(t&&d)try{const e=await t.get(d);if(e)try{const t=JSON.parse(e);if(t.expiresAt>Date.now())return t.config}catch{}}catch(e){console.warn("[RemoteConfig] Cache read failed:",e)}try{let e;if(a)e=`${r}${s.AGENTSHIELD_ENDPOINTS.CONFIG(a)}`;else{if(!o)return console.warn("[RemoteConfig] Neither projectId nor agentDid provided"),null;e=`${r}/api/v1/bouncer/config?agent_did=${encodeURIComponent(o)}`}const l=await c(e,{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"}});if(!l.ok)return console.warn(`[RemoteConfig] API returned ${l.status}: ${l.statusText}`),null;const u=await l.json(),h=u.config||u.data?.config||(u.success?u.data:null);if(!h)return console.warn("[RemoteConfig] No config found in API response"),null;if(t&&d)try{await t.set(d,JSON.stringify({config:h,expiresAt:Date.now()+n}),n)}catch(e){console.warn("[RemoteConfig] Cache write failed:",e)}return h}catch(e){return console.warn("[RemoteConfig] Failed to fetch config:",e),null}};const s=r(82906)},82906:e=>{"use strict";e.exports=require("@kya-os/contracts/agentshield-api")},82917:e=>{"use strict";e.exports=function(e,t,r){var s=" ",i=e.level,a=e.dataLevel,o=e.schema[t],n=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,d=!e.opts.allErrors,l="data"+(a||""),u="valid"+i,h="errs__"+i,p=e.util.copy(e);p.level++;var f="valid"+p.level,g=e.schema.then,m=e.schema.else,v=void 0!==g&&(e.opts.strictKeywords?"object"==typeof g&&Object.keys(g).length>0||!1===g:e.util.schemaHasRules(g,e.RULES.all)),y=void 0!==m&&(e.opts.strictKeywords?"object"==typeof m&&Object.keys(m).length>0||!1===m:e.util.schemaHasRules(m,e.RULES.all)),_=p.baseId;if(v||y){var w;p.createErrors=!1,p.schema=o,p.schemaPath=n,p.errSchemaPath=c,s+=" var "+h+" = errors; var "+u+" = true; ";var b=e.compositeRule;e.compositeRule=p.compositeRule=!0,s+=" "+e.validate(p)+" ",p.baseId=_,p.createErrors=!0,s+=" errors = "+h+"; if (vErrors !== null) { if ("+h+") vErrors.length = "+h+"; else vErrors = null; } ",e.compositeRule=p.compositeRule=b,v?(s+=" if ("+f+") { ",p.schema=e.schema.then,p.schemaPath=e.schemaPath+".then",p.errSchemaPath=e.errSchemaPath+"/then",s+=" "+e.validate(p)+" ",p.baseId=_,s+=" "+u+" = "+f+"; ",v&&y?s+=" var "+(w="ifClause"+i)+" = 'then'; ":w="'then'",s+=" } ",y&&(s+=" else { ")):s+=" if (!"+f+") { ",y&&(p.schema=e.schema.else,p.schemaPath=e.schemaPath+".else",p.errSchemaPath=e.errSchemaPath+"/else",s+=" "+e.validate(p)+" ",p.baseId=_,s+=" "+u+" = "+f+"; ",v&&y?s+=" var "+(w="ifClause"+i)+" = 'else'; ":w="'else'",s+=" } "),s+=" if (!"+u+") { var err = ",!1!==e.createErrors?(s+=" { keyword: 'if' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { failingKeyword: "+w+" } ",!1!==e.opts.messages&&(s+=" , message: 'should match \"' + "+w+" + '\" schema' "),e.opts.verbose&&(s+=" , schema: validate.schema"+n+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),s+=" } "):s+=" {} ",s+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&d&&(e.async?s+=" throw new ValidationError(vErrors); ":s+=" validate.errors = vErrors; return false; "),s+=" } ",d&&(s+=" else { ")}else d&&(s+=" if (true) { ");return s}},83010:e=>{"use strict";e.exports=function(e,t,r){var s,i=" ",a=e.level,o=e.dataLevel,n=e.schema[t],c=e.schemaPath+e.util.getProperty(t),d=e.errSchemaPath+"/"+t,l=!e.opts.allErrors,u="data"+(o||""),h=e.opts.$data&&n&&n.$data;if(h?(i+=" var schema"+a+" = "+e.util.getData(n.$data,o,e.dataPathArr)+"; ",s="schema"+a):s=n,!h&&"number"!=typeof n)throw new Error(t+" must be number");var p="maxLength"==t?">":"<";i+="if ( ",h&&(i+=" ("+s+" !== undefined && typeof "+s+" != 'number') || "),!1===e.opts.unicode?i+=" "+u+".length ":i+=" ucs2length("+u+") ",i+=" "+p+" "+s+") { ";var f=t,g=g||[];g.push(i),i="",!1!==e.createErrors?(i+=" { keyword: '"+(f||"_limitLength")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(d)+" , params: { limit: "+s+" } ",!1!==e.opts.messages&&(i+=" , message: 'should NOT be ",i+="maxLength"==t?"longer":"shorter",i+=" than ",i+=h?"' + "+s+" + '":""+n,i+=" characters' "),e.opts.verbose&&(i+=" , schema: ",i+=h?"validate.schema"+c:""+n,i+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),i+=" } "):i+=" {} ";var m=i;return i=g.pop(),!e.compositeRule&&l?e.async?i+=" throw new ValidationError(["+m+"]); ":i+=" validate.errors = ["+m+"]; return false; ":i+=" var err = "+m+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",i+="} ",l&&(i+=" else { "),i}},85601:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NoOpToolProtectionCache=t.InMemoryToolProtectionCache=void 0,t.InMemoryToolProtectionCache=class{cache=new Map;async get(e){const t=this.cache.get(e);return t?Date.now()>t.expiresAt?(this.cache.delete(e),null):t.value:null}async set(e,t,r){if(r<=0)return;const s=Date.now()+r;this.cache.set(e,{value:t,expiresAt:s})}async clear(){this.cache.clear()}async delete(e){this.cache.delete(e)}cleanup(){const e=Date.now();for(const[t,r]of this.cache.entries())e>r.expiresAt&&this.cache.delete(t)}getStale(e){const t=this.cache.get(e);return t?t.value:null}getExpiresAt(e){const t=this.cache.get(e);return t?t.expiresAt:null}},t.NoOpToolProtectionCache=class{async get(e){return null}async set(e,t,r){}async clear(){}async delete(e){}}},86343:e=>{"use strict";e.exports=function(e,t,r){var s=" ",i=e.level,a=e.dataLevel,o=e.schema[t],n=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,d=!e.opts.allErrors,l="data"+(a||""),u="errs__"+i,h=e.util.copy(e),p="";h.level++;var f="valid"+h.level,g="key"+i,m="idx"+i,v=h.dataLevel=e.dataLevel+1,y="data"+v,_="dataProperties"+i,w=Object.keys(o||{}).filter(R),b=e.schema.patternProperties||{},S=Object.keys(b).filter(R),P=e.schema.additionalProperties,E=w.length||S.length,I=!1===P,k="object"==typeof P&&Object.keys(P).length,C=e.opts.removeAdditional,D=I||k||C,O=e.opts.ownProperties,A=e.baseId,x=e.schema.required;if(x&&(!e.opts.$data||!x.$data)&&x.length<e.opts.loopRequired)var T=e.util.toHash(x);function R(e){return"__proto__"!==e}if(s+="var "+u+" = errors;var "+f+" = true;",O&&(s+=" var "+_+" = undefined;"),D){if(s+=O?" "+_+" = "+_+" || Object.keys("+l+"); for (var "+m+"=0; "+m+"<"+_+".length; "+m+"++) { var "+g+" = "+_+"["+m+"]; ":" for (var "+g+" in "+l+") { ",E){if(s+=" var isAdditional"+i+" = !(false ",w.length)if(w.length>8)s+=" || validate.schema"+n+".hasOwnProperty("+g+") ";else{var $=w;if($)for(var j=-1,N=$.length-1;j<N;)Z=$[j+=1],s+=" || "+g+" == "+e.util.toQuotedString(Z)+" "}if(S.length){var M=S;if(M)for(var F=-1,K=M.length-1;F<K;)ae=M[F+=1],s+=" || "+e.usePattern(ae)+".test("+g+") "}s+=" ); if (isAdditional"+i+") { "}if("all"==C)s+=" delete "+l+"["+g+"]; ";else{var q=e.errorPath,L="' + "+g+" + '";if(e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPathExpr(e.errorPath,g,e.opts.jsonPointers)),I)if(C)s+=" delete "+l+"["+g+"]; ";else{s+=" "+f+" = false; ";var U=c;c=e.errSchemaPath+"/additionalProperties",(re=re||[]).push(s),s="",!1!==e.createErrors?(s+=" { keyword: 'additionalProperties' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { additionalProperty: '"+L+"' } ",!1!==e.opts.messages&&(s+=" , message: '",e.opts._errorDataPathProperty?s+="is an invalid additional property":s+="should NOT have additional properties",s+="' "),e.opts.verbose&&(s+=" , schema: false , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),s+=" } "):s+=" {} ";var V=s;s=re.pop(),!e.compositeRule&&d?e.async?s+=" throw new ValidationError(["+V+"]); ":s+=" validate.errors = ["+V+"]; return false; ":s+=" var err = "+V+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",c=U,d&&(s+=" break; ")}else if(k)if("failing"==C){s+=" var "+u+" = errors; ";var H=e.compositeRule;e.compositeRule=h.compositeRule=!0,h.schema=P,h.schemaPath=e.schemaPath+".additionalProperties",h.errSchemaPath=e.errSchemaPath+"/additionalProperties",h.errorPath=e.opts._errorDataPathProperty?e.errorPath:e.util.getPathExpr(e.errorPath,g,e.opts.jsonPointers);var B=l+"["+g+"]";h.dataPathArr[v]=g;var z=e.validate(h);h.baseId=A,e.util.varOccurences(z,y)<2?s+=" "+e.util.varReplace(z,y,B)+" ":s+=" var "+y+" = "+B+"; "+z+" ",s+=" if (!"+f+") { errors = "+u+"; if (validate.errors !== null) { if (errors) validate.errors.length = errors; else validate.errors = null; } delete "+l+"["+g+"]; } ",e.compositeRule=h.compositeRule=H}else h.schema=P,h.schemaPath=e.schemaPath+".additionalProperties",h.errSchemaPath=e.errSchemaPath+"/additionalProperties",h.errorPath=e.opts._errorDataPathProperty?e.errorPath:e.util.getPathExpr(e.errorPath,g,e.opts.jsonPointers),B=l+"["+g+"]",h.dataPathArr[v]=g,z=e.validate(h),h.baseId=A,e.util.varOccurences(z,y)<2?s+=" "+e.util.varReplace(z,y,B)+" ":s+=" var "+y+" = "+B+"; "+z+" ",d&&(s+=" if (!"+f+") break; ");e.errorPath=q}E&&(s+=" } "),s+=" } ",d&&(s+=" if ("+f+") { ",p+="}")}var J=e.opts.useDefaults&&!e.compositeRule;if(w.length){var W=w;if(W)for(var Z,Q=-1,G=W.length-1;Q<G;){var Y=o[Z=W[Q+=1]];if(e.opts.strictKeywords?"object"==typeof Y&&Object.keys(Y).length>0||!1===Y:e.util.schemaHasRules(Y,e.RULES.all)){var X=e.util.getProperty(Z),ee=(B=l+X,J&&void 0!==Y.default);if(h.schema=Y,h.schemaPath=n+X,h.errSchemaPath=c+"/"+e.util.escapeFragment(Z),h.errorPath=e.util.getPath(e.errorPath,Z,e.opts.jsonPointers),h.dataPathArr[v]=e.util.toQuotedString(Z),z=e.validate(h),h.baseId=A,e.util.varOccurences(z,y)<2){z=e.util.varReplace(z,y,B);var te=B}else te=y,s+=" var "+y+" = "+B+"; ";if(ee)s+=" "+z+" ";else{if(T&&T[Z]){s+=" if ( "+te+" === undefined ",O&&(s+=" || ! Object.prototype.hasOwnProperty.call("+l+", '"+e.util.escapeQuotes(Z)+"') "),s+=") { "+f+" = false; ",q=e.errorPath,U=c;var re,se=e.util.escapeQuotes(Z);e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPath(q,Z,e.opts.jsonPointers)),c=e.errSchemaPath+"/required",(re=re||[]).push(s),s="",!1!==e.createErrors?(s+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { missingProperty: '"+se+"' } ",!1!==e.opts.messages&&(s+=" , message: '",e.opts._errorDataPathProperty?s+="is a required property":s+="should have required property \\'"+se+"\\'",s+="' "),e.opts.verbose&&(s+=" , schema: validate.schema"+n+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),s+=" } "):s+=" {} ",V=s,s=re.pop(),!e.compositeRule&&d?e.async?s+=" throw new ValidationError(["+V+"]); ":s+=" validate.errors = ["+V+"]; return false; ":s+=" var err = "+V+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",c=U,e.errorPath=q,s+=" } else { "}else d?(s+=" if ( "+te+" === undefined ",O&&(s+=" || ! Object.prototype.hasOwnProperty.call("+l+", '"+e.util.escapeQuotes(Z)+"') "),s+=") { "+f+" = true; } else { "):(s+=" if ("+te+" !== undefined ",O&&(s+=" && Object.prototype.hasOwnProperty.call("+l+", '"+e.util.escapeQuotes(Z)+"') "),s+=" ) { ");s+=" "+z+" } "}}d&&(s+=" if ("+f+") { ",p+="}")}}if(S.length){var ie=S;if(ie)for(var ae,oe=-1,ne=ie.length-1;oe<ne;)Y=b[ae=ie[oe+=1]],(e.opts.strictKeywords?"object"==typeof Y&&Object.keys(Y).length>0||!1===Y:e.util.schemaHasRules(Y,e.RULES.all))&&(h.schema=Y,h.schemaPath=e.schemaPath+".patternProperties"+e.util.getProperty(ae),h.errSchemaPath=e.errSchemaPath+"/patternProperties/"+e.util.escapeFragment(ae),s+=O?" "+_+" = "+_+" || Object.keys("+l+"); for (var "+m+"=0; "+m+"<"+_+".length; "+m+"++) { var "+g+" = "+_+"["+m+"]; ":" for (var "+g+" in "+l+") { ",s+=" if ("+e.usePattern(ae)+".test("+g+")) { ",h.errorPath=e.util.getPathExpr(e.errorPath,g,e.opts.jsonPointers),B=l+"["+g+"]",h.dataPathArr[v]=g,z=e.validate(h),h.baseId=A,e.util.varOccurences(z,y)<2?s+=" "+e.util.varReplace(z,y,B)+" ":s+=" var "+y+" = "+B+"; "+z+" ",d&&(s+=" if (!"+f+") break; "),s+=" } ",d&&(s+=" else "+f+" = true; "),s+=" } ",d&&(s+=" if ("+f+") { ",p+="}"))}return d&&(s+=" "+p+" if ("+u+" == errors) {"),s}},90083:e=>{"use strict";e.exports=function(e,t,r){var s=" ",i=e.level,a=e.dataLevel,o=e.schema[t],n=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,d=!e.opts.allErrors,l="data"+(a||""),u="errs__"+i,h=e.util.copy(e),p="";h.level++;var f="valid"+h.level,g={},m={},v=e.opts.ownProperties;for(b in o)if("__proto__"!=b){var y=o[b],_=Array.isArray(y)?m:g;_[b]=y}s+="var "+u+" = errors;";var w=e.errorPath;for(var b in s+="var missing"+i+";",m)if((_=m[b]).length){if(s+=" if ( "+l+e.util.getProperty(b)+" !== undefined ",v&&(s+=" && Object.prototype.hasOwnProperty.call("+l+", '"+e.util.escapeQuotes(b)+"') "),d){s+=" && ( ";var S=_;if(S)for(var P=-1,E=S.length-1;P<E;)A=S[P+=1],P&&(s+=" || "),s+=" ( ( "+($=l+(R=e.util.getProperty(A)))+" === undefined ",v&&(s+=" || ! Object.prototype.hasOwnProperty.call("+l+", '"+e.util.escapeQuotes(A)+"') "),s+=") && (missing"+i+" = "+e.util.toQuotedString(e.opts.jsonPointers?A:R)+") ) ";s+=")) { ";var I="missing"+i,k="' + "+I+" + '";e.opts._errorDataPathProperty&&(e.errorPath=e.opts.jsonPointers?e.util.getPathExpr(w,I,!0):w+" + "+I);var C=C||[];C.push(s),s="",!1!==e.createErrors?(s+=" { keyword: 'dependencies' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { property: '"+e.util.escapeQuotes(b)+"', missingProperty: '"+k+"', depsCount: "+_.length+", deps: '"+e.util.escapeQuotes(1==_.length?_[0]:_.join(", "))+"' } ",!1!==e.opts.messages&&(s+=" , message: 'should have ",1==_.length?s+="property "+e.util.escapeQuotes(_[0]):s+="properties "+e.util.escapeQuotes(_.join(", ")),s+=" when property "+e.util.escapeQuotes(b)+" is present' "),e.opts.verbose&&(s+=" , schema: validate.schema"+n+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),s+=" } "):s+=" {} ";var D=s;s=C.pop(),!e.compositeRule&&d?e.async?s+=" throw new ValidationError(["+D+"]); ":s+=" validate.errors = ["+D+"]; return false; ":s+=" var err = "+D+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}else{s+=" ) { ";var O=_;if(O)for(var A,x=-1,T=O.length-1;x<T;){A=O[x+=1];var R=e.util.getProperty(A),$=(k=e.util.escapeQuotes(A),l+R);e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPath(w,A,e.opts.jsonPointers)),s+=" if ( "+$+" === undefined ",v&&(s+=" || ! Object.prototype.hasOwnProperty.call("+l+", '"+e.util.escapeQuotes(A)+"') "),s+=") { var err = ",!1!==e.createErrors?(s+=" { keyword: 'dependencies' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { property: '"+e.util.escapeQuotes(b)+"', missingProperty: '"+k+"', depsCount: "+_.length+", deps: '"+e.util.escapeQuotes(1==_.length?_[0]:_.join(", "))+"' } ",!1!==e.opts.messages&&(s+=" , message: 'should have ",1==_.length?s+="property "+e.util.escapeQuotes(_[0]):s+="properties "+e.util.escapeQuotes(_.join(", ")),s+=" when property "+e.util.escapeQuotes(b)+" is present' "),e.opts.verbose&&(s+=" , schema: validate.schema"+n+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),s+=" } "):s+=" {} ",s+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } "}}s+=" } ",d&&(p+="}",s+=" else { ")}e.errorPath=w;var j=h.baseId;for(var b in g)y=g[b],(e.opts.strictKeywords?"object"==typeof y&&Object.keys(y).length>0||!1===y:e.util.schemaHasRules(y,e.RULES.all))&&(s+=" "+f+" = true; if ( "+l+e.util.getProperty(b)+" !== undefined ",v&&(s+=" && Object.prototype.hasOwnProperty.call("+l+", '"+e.util.escapeQuotes(b)+"') "),s+=") { ",h.schema=y,h.schemaPath=n+e.util.getProperty(b),h.errSchemaPath=c+"/"+e.util.escapeFragment(b),s+=" "+e.validate(h)+" ",h.baseId=j,s+=" } ",d&&(s+=" if ("+f+") { ",p+="}"));return d&&(s+=" "+p+" if ("+u+" == errors) {"),s}},91939:e=>{"use strict";e.exports=function(e,t,r){var s=" ",i=e.level,a=e.dataLevel,o=e.schema[t],n=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,d=!e.opts.allErrors,l="data"+(a||""),u="valid"+i,h=e.opts.$data&&o&&o.$data;h&&(s+=" var schema"+i+" = "+e.util.getData(o.$data,a,e.dataPathArr)+"; ");var p="schema"+i;if(!h)if(o.length<e.opts.loopRequired&&e.schema.properties&&Object.keys(e.schema.properties).length){var f=[],g=o;if(g)for(var m,v=-1,y=g.length-1;v<y;){m=g[v+=1];var _=e.schema.properties[m];_&&(e.opts.strictKeywords?"object"==typeof _&&Object.keys(_).length>0||!1===_:e.util.schemaHasRules(_,e.RULES.all))||(f[f.length]=m)}}else f=o;if(h||f.length){var w=e.errorPath,b=h||f.length>=e.opts.loopRequired,S=e.opts.ownProperties;if(d)if(s+=" var missing"+i+"; ",b){h||(s+=" var "+p+" = validate.schema"+n+"; ");var P="' + "+(O="schema"+i+"["+(C="i"+i)+"]")+" + '";e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPathExpr(w,O,e.opts.jsonPointers)),s+=" var "+u+" = true; ",h&&(s+=" if (schema"+i+" === undefined) "+u+" = true; else if (!Array.isArray(schema"+i+")) "+u+" = false; else {"),s+=" for (var "+C+" = 0; "+C+" < "+p+".length; "+C+"++) { "+u+" = "+l+"["+p+"["+C+"]] !== undefined ",S&&(s+=" && Object.prototype.hasOwnProperty.call("+l+", "+p+"["+C+"]) "),s+="; if (!"+u+") break; } ",h&&(s+=" } "),s+=" if (!"+u+") { ",(I=I||[]).push(s),s="",!1!==e.createErrors?(s+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { missingProperty: '"+P+"' } ",!1!==e.opts.messages&&(s+=" , message: '",e.opts._errorDataPathProperty?s+="is a required property":s+="should have required property \\'"+P+"\\'",s+="' "),e.opts.verbose&&(s+=" , schema: validate.schema"+n+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),s+=" } "):s+=" {} ";var E=s;s=I.pop(),!e.compositeRule&&d?e.async?s+=" throw new ValidationError(["+E+"]); ":s+=" validate.errors = ["+E+"]; return false; ":s+=" var err = "+E+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+=" } else { "}else{s+=" if ( ";var I,k=f;if(k)for(var C=-1,D=k.length-1;C<D;)x=k[C+=1],C&&(s+=" || "),s+=" ( ( "+(j=l+($=e.util.getProperty(x)))+" === undefined ",S&&(s+=" || ! Object.prototype.hasOwnProperty.call("+l+", '"+e.util.escapeQuotes(x)+"') "),s+=") && (missing"+i+" = "+e.util.toQuotedString(e.opts.jsonPointers?x:$)+") ) ";s+=") { ",P="' + "+(O="missing"+i)+" + '",e.opts._errorDataPathProperty&&(e.errorPath=e.opts.jsonPointers?e.util.getPathExpr(w,O,!0):w+" + "+O),(I=I||[]).push(s),s="",!1!==e.createErrors?(s+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { missingProperty: '"+P+"' } ",!1!==e.opts.messages&&(s+=" , message: '",e.opts._errorDataPathProperty?s+="is a required property":s+="should have required property \\'"+P+"\\'",s+="' "),e.opts.verbose&&(s+=" , schema: validate.schema"+n+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),s+=" } "):s+=" {} ",E=s,s=I.pop(),!e.compositeRule&&d?e.async?s+=" throw new ValidationError(["+E+"]); ":s+=" validate.errors = ["+E+"]; return false; ":s+=" var err = "+E+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+=" } else { "}else if(b){var O;h||(s+=" var "+p+" = validate.schema"+n+"; "),P="' + "+(O="schema"+i+"["+(C="i"+i)+"]")+" + '",e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPathExpr(w,O,e.opts.jsonPointers)),h&&(s+=" if ("+p+" && !Array.isArray("+p+")) { var err = ",!1!==e.createErrors?(s+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { missingProperty: '"+P+"' } ",!1!==e.opts.messages&&(s+=" , message: '",e.opts._errorDataPathProperty?s+="is a required property":s+="should have required property \\'"+P+"\\'",s+="' "),e.opts.verbose&&(s+=" , schema: validate.schema"+n+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),s+=" } "):s+=" {} ",s+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } else if ("+p+" !== undefined) { "),s+=" for (var "+C+" = 0; "+C+" < "+p+".length; "+C+"++) { if ("+l+"["+p+"["+C+"]] === undefined ",S&&(s+=" || ! Object.prototype.hasOwnProperty.call("+l+", "+p+"["+C+"]) "),s+=") { var err = ",!1!==e.createErrors?(s+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { missingProperty: '"+P+"' } ",!1!==e.opts.messages&&(s+=" , message: '",e.opts._errorDataPathProperty?s+="is a required property":s+="should have required property \\'"+P+"\\'",s+="' "),e.opts.verbose&&(s+=" , schema: validate.schema"+n+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),s+=" } "):s+=" {} ",s+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } } ",h&&(s+=" } ")}else{var A=f;if(A)for(var x,T=-1,R=A.length-1;T<R;){x=A[T+=1];var $=e.util.getProperty(x),j=(P=e.util.escapeQuotes(x),l+$);e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPath(w,x,e.opts.jsonPointers)),s+=" if ( "+j+" === undefined ",S&&(s+=" || ! Object.prototype.hasOwnProperty.call("+l+", '"+e.util.escapeQuotes(x)+"') "),s+=") { var err = ",!1!==e.createErrors?(s+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { missingProperty: '"+P+"' } ",!1!==e.opts.messages&&(s+=" , message: '",e.opts._errorDataPathProperty?s+="is a required property":s+="should have required property \\'"+P+"\\'",s+="' "),e.opts.verbose&&(s+=" , schema: validate.schema"+n+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),s+=" } "):s+=" {} ",s+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } "}}e.errorPath=w}else d&&(s+=" if (true) {");return s}},92182:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StorageKeyHelpers=void 0,t.createStorageProviders=async function(e){const t=!1!==e.fallbackToMemory;if(e.redisUrl)try{const t="redis",s=await r(52643)(t).catch(()=>null);if(!s)throw new Error("Redis package not available");const{createClient:i}=s,a=i({url:e.redisUrl,socket:{connectTimeout:5e3}});await a.connect(),await a.ping();return{storageProvider:new c(a),nonceCacheProvider:new d(a)}}catch(e){if(!t)throw e;console.warn("[StorageService] Failed to connect to Redis, falling back to memory:",e instanceof Error?e.message:String(e))}if(e.kvNamespace)try{const t=await async function(e){try{const t="@kya-os/mcp-i-cloudflare/providers/storage",{KVStorageProvider:s,KVNonceCacheProvider:i}=await r(42399)(t);return{storage:new s(e),nonceCache:new i(e)}}catch(e){throw new Error(`Failed to import Cloudflare storage providers: ${e instanceof Error?e.message:String(e)}`)}}(e.kvNamespace);return{storageProvider:t.storage,nonceCacheProvider:t.nonceCache}}catch(e){if(!t)throw e;console.warn("[StorageService] Failed to initialize KV, falling back to memory:",e instanceof Error?e.message:String(e))}if(e.durableObjectState)try{return{storageProvider:new o(e.durableObjectState),nonceCacheProvider:new n(e.durableObjectState)}}catch(e){if(!t)throw e;console.warn("[StorageService] Failed to initialize Durable Objects, falling back to memory:",e instanceof Error?e.message:String(e))}if(t)return{storageProvider:new i.MemoryStorageProvider,nonceCacheProvider:new i.MemoryNonceCacheProvider};throw new Error("No storage provider configured and fallbackToMemory is false")},t.migrateLegacyKeys=async function(e,t,r,s=100){let i=0;try{const a=await r.list(e);for(const e of a){const a=t(e);if(!a)continue;if(await r.exists(a))continue;const o=await r.get(e);o&&(await r.set(a,o),i++,i%s===0&&await new Promise(e=>setTimeout(e,0)))}}catch(e){throw console.error("[StorageService] Migration error:",e),e}return i};const s=r(27087),i=r(48505);class a{static buildDelegationKey(e,t,r){return`delegation:${e}:${t}:${r}`}static buildSessionKey(e){return`session:${e}`}static buildNonceKey(e,t){return`nonce:${e}:${t}`}static parseDelegationKey(e){if(!e.startsWith("delegation:"))return null;const t=e.slice(11),r=t.lastIndexOf(":");if(-1===r)return null;const s=t.slice(r+1);if(!s)return null;const i=t.slice(0,r),a=i.indexOf("did:");if(0!==a)return null;const o=i.indexOf(":",a+4);if(-1===o)return null;const n=i.indexOf("did:",o+1);if(-1===n)return null;const c=i.slice(0,n),d=i.slice(n),l=c.endsWith(":")?c.slice(0,-1):c;return l&&d?{userDid:l,agentDid:d,projectId:s}:null}}t.StorageKeyHelpers=a;class o extends s.StorageProvider{state;constructor(e){super(),this.state=e}async get(e){return await this.state.storage.get(e)??null}async set(e,t){await this.state.storage.put(e,t)}async delete(e){await this.state.storage.delete(e)}async exists(e){return void 0!==await this.state.storage.get(e)}async list(e){const t=await this.state.storage.list(e?{prefix:e}:void 0);return Array.from(t.keys())}}class n extends s.NonceCacheProvider{state;constructor(e){super(),this.state=e}async has(e,t){const r=t?a.buildNonceKey(t,e):`nonce:${e}`,s=await this.state.storage.get(r);if(!s)return!1;const i=parseInt(s,10);return Date.now()<i}async add(e,t,r){const s=r?a.buildNonceKey(r,e):`nonce:${e}`,i=Date.now()+1e3*t;await this.state.storage.put(s,i.toString())}async cleanup(){}async destroy(){}}class c extends s.StorageProvider{redis;constructor(e){super(),this.redis=e}async get(e){return await this.redis.get(e)}async set(e,t){await this.redis.set(e,t)}async delete(e){await this.redis.del(e)}async exists(e){return 1===await this.redis.exists(e)}async list(e){const t=e?`${e}*`:"*";return await this.redis.keys(t)}}class d extends s.NonceCacheProvider{redis;keyPrefix;constructor(e,t="nonce:"){super(),this.redis=e,this.keyPrefix=t}async has(e,t){const r=t?a.buildNonceKey(t,e):`${this.keyPrefix}${e}`;return 1===await this.redis.exists(r)}async add(e,t,r){const s=r?a.buildNonceKey(r,e):`${this.keyPrefix}${e}`;await this.redis.setEx(s,t,"1")}async cleanup(){}async destroy(){}}},94766:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProviderValidator=t.ProviderValidationError=void 0;const r=["response_type","client_id","redirect_uri","scope","state","code_challenge","code_challenge_method"];class s extends Error{field;constructor(e,t){super(e),this.field=t,this.name="ProviderValidationError"}}t.ProviderValidationError=s,t.ProviderValidator=class{validate(e,t){if(!e.clientId||0===e.clientId.trim().length)throw new s(`Provider "${t}" must have a clientId`,"clientId");if(!e.authorizationUrl||0===e.authorizationUrl.trim().length)throw new s(`Provider "${t}" must have an authorizationUrl`,"authorizationUrl");if(!e.tokenUrl||0===e.tokenUrl.trim().length)throw new s(`Provider "${t}" must have a tokenUrl`,"tokenUrl");if(this.validateUrl(e.authorizationUrl,t,"authorizationUrl"),this.validateUrl(e.tokenUrl,t,"tokenUrl"),e.userInfoUrl&&this.validateUrl(e.userInfoUrl,t,"userInfoUrl"),e.proxyMode&&!e.requiresClientSecret)throw new s(`Provider "${t}" with proxyMode=true must have requiresClientSecret=true`,"proxyMode");e.customParams&&this.validateCustomParams(e.customParams,t)}validateUrl(e,t,r){try{const i=new URL(e);if("http:"!==i.protocol&&"https:"!==i.protocol)throw new s(`Provider "${t}" ${r} must use HTTP or HTTPS protocol`,r)}catch(e){if(e instanceof s)throw e;throw new s(`Provider "${t}" ${r} is not a valid URL: ${e instanceof Error?e.message:String(e)}`,r)}}validateCustomParams(e,t){for(const[i,a]of Object.entries(e)){const e=i.toLowerCase();if(r.includes(e))throw new s(`Provider "${t}" custom parameter "${i}" conflicts with reserved OAuth parameter. Reserved parameters: ${r.join(", ")}`,`customParams.${i}`);if(!a||0===a.trim().length)throw new s(`Provider "${t}" custom parameter "${i}" has empty value`,`customParams.${i}`)}}async testProvider(e,t){try{const r=await t(e.authorizationUrl,{method:"HEAD",signal:AbortSignal.timeout(5e3)});return r.ok||405===r.status}catch(e){return!1}}}},95277:function(e,t,r){"use strict";var s=this&&this.__createBinding||(Object.create?function(e,t,r,s){void 0===s&&(s=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,s,i)}:function(e,t,r,s){void 0===s&&(s=r),e[s]=t[r]}),i=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||s(t,e,r)};Object.defineProperty(t,"__esModule",{value:!0}),t.SchemaVerifier=t.MemoryDelegationGraphStorage=t.MemoryStatusListStorage=t.createCascadingRevocationManager=t.CascadingRevocationManager=t.createDelegationGraph=t.DelegationGraphManager=t.isIndexSet=t.BitstringManager=t.createStatusListManager=t.StatusList2021Manager=t.createDelegationVerifier=t.DelegationCredentialVerifier=t.createDelegationIssuer=t.DelegationCredentialIssuer=t.OAuthRequiredError=t.DelegationRequiredError=t.NoOpToolProtectionCache=t.InMemoryToolProtectionCache=t.createProofVerificationError=t.PROOF_VERIFICATION_ERROR_CODES=t.ProofVerificationError=t.migrateLegacyKeys=t.StorageKeyHelpers=t.createStorageProviders=t.NoOpOAuthConfigCache=t.InMemoryOAuthConfigCache=t.BatchDelegationService=t.OAuthTokenRetrievalService=t.ProviderValidationError=t.ProviderValidator=t.ProviderResolver=t.OAuthProviderRegistry=t.ToolContextBuilder=t.OAuthService=t.OAuthConfigService=t.AccessControlApiService=t.ProofVerifier=t.CryptoService=t.ToolProtectionService=t.MCPIRuntimeBase=t.MemoryIdentityProvider=t.MemoryNonceCacheProvider=t.MemoryStorageProvider=t.IdentityProvider=t.NonceCacheProvider=t.StorageProvider=t.FetchProvider=t.ClockProvider=t.CryptoProvider=void 0,t.IdpTokenResolver=t.UserDidManager=t.fetchRemoteConfig=t.canonicalizeJSON=t.getSchemaStats=t.getCriticalSchemas=t.getSchemaById=t.getSchemasByCategory=t.getAllSchemas=t.SCHEMA_REGISTRY=t.createSchemaVerifier=void 0;var a=r(27087);Object.defineProperty(t,"CryptoProvider",{enumerable:!0,get:function(){return a.CryptoProvider}}),Object.defineProperty(t,"ClockProvider",{enumerable:!0,get:function(){return a.ClockProvider}}),Object.defineProperty(t,"FetchProvider",{enumerable:!0,get:function(){return a.FetchProvider}}),Object.defineProperty(t,"StorageProvider",{enumerable:!0,get:function(){return a.StorageProvider}}),Object.defineProperty(t,"NonceCacheProvider",{enumerable:!0,get:function(){return a.NonceCacheProvider}}),Object.defineProperty(t,"IdentityProvider",{enumerable:!0,get:function(){return a.IdentityProvider}});var o=r(48505);Object.defineProperty(t,"MemoryStorageProvider",{enumerable:!0,get:function(){return o.MemoryStorageProvider}}),Object.defineProperty(t,"MemoryNonceCacheProvider",{enumerable:!0,get:function(){return o.MemoryNonceCacheProvider}}),Object.defineProperty(t,"MemoryIdentityProvider",{enumerable:!0,get:function(){return o.MemoryIdentityProvider}});var n=r(23137);Object.defineProperty(t,"MCPIRuntimeBase",{enumerable:!0,get:function(){return n.MCPIRuntimeBase}}),i(r(53871),t);var c=r(9249);Object.defineProperty(t,"ToolProtectionService",{enumerable:!0,get:function(){return c.ToolProtectionService}});var d=r(81296);Object.defineProperty(t,"CryptoService",{enumerable:!0,get:function(){return d.CryptoService}});var l=r(45395);Object.defineProperty(t,"ProofVerifier",{enumerable:!0,get:function(){return l.ProofVerifier}});var u=r(36255);Object.defineProperty(t,"AccessControlApiService",{enumerable:!0,get:function(){return u.AccessControlApiService}});var h=r(97405);Object.defineProperty(t,"OAuthConfigService",{enumerable:!0,get:function(){return h.OAuthConfigService}});var p=r(62175);Object.defineProperty(t,"OAuthService",{enumerable:!0,get:function(){return p.OAuthService}});var f=r(72114);Object.defineProperty(t,"ToolContextBuilder",{enumerable:!0,get:function(){return f.ToolContextBuilder}});var g=r(50399);Object.defineProperty(t,"OAuthProviderRegistry",{enumerable:!0,get:function(){return g.OAuthProviderRegistry}});var m=r(68252);Object.defineProperty(t,"ProviderResolver",{enumerable:!0,get:function(){return m.ProviderResolver}});var v=r(94766);Object.defineProperty(t,"ProviderValidator",{enumerable:!0,get:function(){return v.ProviderValidator}}),Object.defineProperty(t,"ProviderValidationError",{enumerable:!0,get:function(){return v.ProviderValidationError}});var y=r(42769);Object.defineProperty(t,"OAuthTokenRetrievalService",{enumerable:!0,get:function(){return y.OAuthTokenRetrievalService}});var _=r(30124);Object.defineProperty(t,"BatchDelegationService",{enumerable:!0,get:function(){return _.BatchDelegationService}});var w=r(48021);Object.defineProperty(t,"InMemoryOAuthConfigCache",{enumerable:!0,get:function(){return w.InMemoryOAuthConfigCache}}),Object.defineProperty(t,"NoOpOAuthConfigCache",{enumerable:!0,get:function(){return w.NoOpOAuthConfigCache}});var b=r(92182);Object.defineProperty(t,"createStorageProviders",{enumerable:!0,get:function(){return b.createStorageProviders}}),Object.defineProperty(t,"StorageKeyHelpers",{enumerable:!0,get:function(){return b.StorageKeyHelpers}}),Object.defineProperty(t,"migrateLegacyKeys",{enumerable:!0,get:function(){return b.migrateLegacyKeys}});var S=r(53683);Object.defineProperty(t,"ProofVerificationError",{enumerable:!0,get:function(){return S.ProofVerificationError}}),Object.defineProperty(t,"PROOF_VERIFICATION_ERROR_CODES",{enumerable:!0,get:function(){return S.PROOF_VERIFICATION_ERROR_CODES}}),Object.defineProperty(t,"createProofVerificationError",{enumerable:!0,get:function(){return S.createProofVerificationError}});var P=r(85601);Object.defineProperty(t,"InMemoryToolProtectionCache",{enumerable:!0,get:function(){return P.InMemoryToolProtectionCache}}),Object.defineProperty(t,"NoOpToolProtectionCache",{enumerable:!0,get:function(){return P.NoOpToolProtectionCache}});var E=r(4901);Object.defineProperty(t,"DelegationRequiredError",{enumerable:!0,get:function(){return E.DelegationRequiredError}});var I=r(27399);Object.defineProperty(t,"OAuthRequiredError",{enumerable:!0,get:function(){return I.OAuthRequiredError}});var k=r(30845);Object.defineProperty(t,"DelegationCredentialIssuer",{enumerable:!0,get:function(){return k.DelegationCredentialIssuer}}),Object.defineProperty(t,"createDelegationIssuer",{enumerable:!0,get:function(){return k.createDelegationIssuer}});var C=r(77460);Object.defineProperty(t,"DelegationCredentialVerifier",{enumerable:!0,get:function(){return C.DelegationCredentialVerifier}}),Object.defineProperty(t,"createDelegationVerifier",{enumerable:!0,get:function(){return C.createDelegationVerifier}});var D=r(98358);Object.defineProperty(t,"StatusList2021Manager",{enumerable:!0,get:function(){return D.StatusList2021Manager}}),Object.defineProperty(t,"createStatusListManager",{enumerable:!0,get:function(){return D.createStatusListManager}});var O=r(46610);Object.defineProperty(t,"BitstringManager",{enumerable:!0,get:function(){return O.BitstringManager}}),Object.defineProperty(t,"isIndexSet",{enumerable:!0,get:function(){return O.isIndexSet}});var A=r(55921);Object.defineProperty(t,"DelegationGraphManager",{enumerable:!0,get:function(){return A.DelegationGraphManager}}),Object.defineProperty(t,"createDelegationGraph",{enumerable:!0,get:function(){return A.createDelegationGraph}});var x=r(24886);Object.defineProperty(t,"CascadingRevocationManager",{enumerable:!0,get:function(){return x.CascadingRevocationManager}}),Object.defineProperty(t,"createCascadingRevocationManager",{enumerable:!0,get:function(){return x.createCascadingRevocationManager}});var T=r(7318);Object.defineProperty(t,"MemoryStatusListStorage",{enumerable:!0,get:function(){return T.MemoryStatusListStorage}});var R=r(44558);Object.defineProperty(t,"MemoryDelegationGraphStorage",{enumerable:!0,get:function(){return R.MemoryDelegationGraphStorage}});var $=r(37121);Object.defineProperty(t,"SchemaVerifier",{enumerable:!0,get:function(){return $.SchemaVerifier}}),Object.defineProperty(t,"createSchemaVerifier",{enumerable:!0,get:function(){return $.createSchemaVerifier}});var j=r(11300);Object.defineProperty(t,"SCHEMA_REGISTRY",{enumerable:!0,get:function(){return j.SCHEMA_REGISTRY}}),Object.defineProperty(t,"getAllSchemas",{enumerable:!0,get:function(){return j.getAllSchemas}}),Object.defineProperty(t,"getSchemasByCategory",{enumerable:!0,get:function(){return j.getSchemasByCategory}}),Object.defineProperty(t,"getSchemaById",{enumerable:!0,get:function(){return j.getSchemaById}}),Object.defineProperty(t,"getCriticalSchemas",{enumerable:!0,get:function(){return j.getCriticalSchemas}}),Object.defineProperty(t,"getSchemaStats",{enumerable:!0,get:function(){return j.getSchemaStats}});var N=r(63969);Object.defineProperty(t,"canonicalizeJSON",{enumerable:!0,get:function(){return N.canonicalizeJSON}}),i(r(77311),t);var M=r(82811);Object.defineProperty(t,"fetchRemoteConfig",{enumerable:!0,get:function(){return M.fetchRemoteConfig}});var F=r(65067);Object.defineProperty(t,"UserDidManager",{enumerable:!0,get:function(){return F.UserDidManager}});var K=r(202);Object.defineProperty(t,"IdpTokenResolver",{enumerable:!0,get:function(){return K.IdpTokenResolver}})},95545:e=>{"use strict";e.exports=function(e,t,r){var s=" ",i=e.level,a=e.dataLevel,o=e.schema[t],n=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,d=!e.opts.allErrors,l="data"+(a||"");if(!1===e.opts.format)return d&&(s+=" if (true) { "),s;var u,h=e.opts.$data&&o&&o.$data;h?(s+=" var schema"+i+" = "+e.util.getData(o.$data,a,e.dataPathArr)+"; ",u="schema"+i):u=o;var p=e.opts.unknownFormats,f=Array.isArray(p);if(h)s+=" var "+(g="format"+i)+" = formats["+u+"]; var "+(m="isObject"+i)+" = typeof "+g+" == 'object' && !("+g+" instanceof RegExp) && "+g+".validate; var "+(v="formatType"+i)+" = "+m+" && "+g+".type || 'string'; if ("+m+") { ",e.async&&(s+=" var async"+i+" = "+g+".async; "),s+=" "+g+" = "+g+".validate; } if ( ",h&&(s+=" ("+u+" !== undefined && typeof "+u+" != 'string') || "),s+=" (","ignore"!=p&&(s+=" ("+u+" && !"+g+" ",f&&(s+=" && self._opts.unknownFormats.indexOf("+u+") == -1 "),s+=") || "),s+=" ("+g+" && "+v+" == '"+r+"' && !(typeof "+g+" == 'function' ? ",e.async?s+=" (async"+i+" ? await "+g+"("+l+") : "+g+"("+l+")) ":s+=" "+g+"("+l+") ",s+=" : "+g+".test("+l+"))))) {";else{var g;if(!(g=e.formats[o])){if("ignore"==p)return e.logger.warn('unknown format "'+o+'" ignored in schema at path "'+e.errSchemaPath+'"'),d&&(s+=" if (true) { "),s;if(f&&p.indexOf(o)>=0)return d&&(s+=" if (true) { "),s;throw new Error('unknown format "'+o+'" is used in schema at path "'+e.errSchemaPath+'"')}var m,v=(m="object"==typeof g&&!(g instanceof RegExp)&&g.validate)&&g.type||"string";if(m){var y=!0===g.async;g=g.validate}if(v!=r)return d&&(s+=" if (true) { "),s;if(y){if(!e.async)throw new Error("async format in sync schema");s+=" if (!(await "+(_="formats"+e.util.getProperty(o)+".validate")+"("+l+"))) { "}else{s+=" if (! ";var _="formats"+e.util.getProperty(o);m&&(_+=".validate"),s+="function"==typeof g?" "+_+"("+l+") ":" "+_+".test("+l+") ",s+=") { "}}var w=w||[];w.push(s),s="",!1!==e.createErrors?(s+=" { keyword: 'format' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { format: ",s+=h?""+u:""+e.util.toQuotedString(o),s+=" } ",!1!==e.opts.messages&&(s+=" , message: 'should match format \"",s+=h?"' + "+u+" + '":""+e.util.escapeQuotes(o),s+="\"' "),e.opts.verbose&&(s+=" , schema: ",s+=h?"validate.schema"+n:""+e.util.toQuotedString(o),s+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),s+=" } "):s+=" {} ";var b=s;return s=w.pop(),!e.compositeRule&&d?e.async?s+=" throw new ValidationError(["+b+"]); ":s+=" validate.errors = ["+b+"]; return false; ":s+=" var err = "+b+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+=" } ",d&&(s+=" else { "),s}},96111:e=>{"use strict";e.exports=function(e,t,r){var s,i=" ",a=e.level,o=e.dataLevel,n=e.schema[t],c=e.schemaPath+e.util.getProperty(t),d=e.errSchemaPath+"/"+t,l=!e.opts.allErrors,u="data"+(o||""),h=e.opts.$data&&n&&n.$data;if(h?(i+=" var schema"+a+" = "+e.util.getData(n.$data,o,e.dataPathArr)+"; ",s="schema"+a):s=n,!h&&"number"!=typeof n)throw new Error(t+" must be number");i+="if ( ",h&&(i+=" ("+s+" !== undefined && typeof "+s+" != 'number') || "),i+=" Object.keys("+u+").length "+("maxProperties"==t?">":"<")+" "+s+") { ";var p=t,f=f||[];f.push(i),i="",!1!==e.createErrors?(i+=" { keyword: '"+(p||"_limitProperties")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(d)+" , params: { limit: "+s+" } ",!1!==e.opts.messages&&(i+=" , message: 'should NOT have ",i+="maxProperties"==t?"more":"fewer",i+=" than ",i+=h?"' + "+s+" + '":""+n,i+=" properties' "),e.opts.verbose&&(i+=" , schema: ",i+=h?"validate.schema"+c:""+n,i+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),i+=" } "):i+=" {} ";var g=i;return i=f.pop(),!e.compositeRule&&l?e.async?i+=" throw new ValidationError(["+g+"]); ":i+=" validate.errors = ["+g+"]; return false; ":i+=" var err = "+g+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",i+="} ",l&&(i+=" else { "),i}},96150:(e,t,r)=>{"use strict";var s=r(12269);e.exports={$id:"https://github.com/ajv-validator/ajv/blob/master/lib/definition_schema.js",definitions:{simpleTypes:s.definitions.simpleTypes},type:"object",dependencies:{schema:["validate"],$data:["validate"],statements:["inline"],valid:{not:{required:["macro"]}}},properties:{type:s.properties.type,schema:{type:"boolean"},statements:{type:"boolean"},dependencies:{type:"array",items:{type:"string"}},metaSchema:{type:"object"},modifying:{type:"boolean"},valid:{type:"boolean"},$data:{type:"boolean"},async:{type:"boolean"},errors:{anyOf:[{type:"boolean"},{const:"full"}]}}}},96774:e=>{"use strict";e.exports=function(e,t,r){var s,i=" ",a=e.level,o=e.dataLevel,n=e.schema[t],c=e.schemaPath+e.util.getProperty(t),d=e.errSchemaPath+"/"+t,l=!e.opts.allErrors,u="data"+(o||""),h=e.opts.$data&&n&&n.$data;h?(i+=" var schema"+a+" = "+e.util.getData(n.$data,o,e.dataPathArr)+"; ",s="schema"+a):s=n,i+="if ( ",h&&(i+=" ("+s+" !== undefined && typeof "+s+" != 'string') || "),i+=" !"+(h?"(new RegExp("+s+"))":e.usePattern(n))+".test("+u+") ) { ";var p=p||[];p.push(i),i="",!1!==e.createErrors?(i+=" { keyword: 'pattern' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(d)+" , params: { pattern: ",i+=h?""+s:""+e.util.toQuotedString(n),i+=" } ",!1!==e.opts.messages&&(i+=" , message: 'should match pattern \"",i+=h?"' + "+s+" + '":""+e.util.escapeQuotes(n),i+="\"' "),e.opts.verbose&&(i+=" , schema: ",i+=h?"validate.schema"+c:""+e.util.toQuotedString(n),i+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),i+=" } "):i+=" {} ";var f=i;return i=p.pop(),!e.compositeRule&&l?e.async?i+=" throw new ValidationError(["+f+"]); ":i+=" validate.errors = ["+f+"]; return false; ":i+=" var err = "+f+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",i+="} ",l&&(i+=" else { "),i}},97405:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OAuthConfigService=void 0;const s=r(48021);t.OAuthConfigService=class{config;constructor(e){this.config={baseUrl:e.baseUrl,apiKey:e.apiKey,fetchProvider:e.fetchProvider,cacheTtl:e.cacheTtl??3e5,logger:e.logger||(()=>{}),cache:e.cache||new s.InMemoryOAuthConfigCache}}async getOAuthConfig(e){const t=await this.config.cache.get(e);if(t)return this.config.logger("[OAuthConfigService] Cache hit",{projectId:e}),t;const r=`${this.config.baseUrl}/api/v1/bouncer/projects/${encodeURIComponent(e)}/providers`;this.config.logger("[OAuthConfigService] Fetching config from API",{projectId:e,url:r});try{const t=await this.config.fetchProvider.fetch(r,{method:"GET",headers:{Authorization:`Bearer ${this.config.apiKey}`,"Content-Type":"application/json"}});if(!t.ok){const e=await t.text().catch(()=>"Unknown error");throw new Error(`Failed to fetch OAuth config: ${t.status} ${t.statusText} - ${e}`)}const s=await t.json();if(!s.success||!s.data)throw new Error("Invalid API response: missing success or data field");const i=s.data.providers||{};if("object"!=typeof i||Array.isArray(i))throw new Error("Invalid API response: providers must be an object, not an array");const a={providers:i};return await this.config.cache.set(e,a,this.config.cacheTtl),this.config.logger("[OAuthConfigService] Config fetched and cached",{projectId:e,providerCount:Object.keys(i).length,providers:Object.keys(i),expiresAt:new Date(Date.now()+this.config.cacheTtl).toISOString()}),a}catch(t){throw this.config.logger("[OAuthConfigService] API fetch failed",{projectId:e,error:t instanceof Error?t.message:String(t)}),t}}async clearCache(e){await this.config.cache.delete(e),this.config.logger("[OAuthConfigService] Cache cleared",{projectId:e})}async clearAllCache(){await this.config.cache.clear(),this.config.logger("[OAuthConfigService] All cache cleared")}}},98358:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StatusList2021Manager=void 0,t.createStatusListManager=function(e,t,r,s,i,o){return new a(e,t,r,s,i,o)};const s=r(46610),i=r(63969);class a{storage;identity;signingFunction;compressor;decompressor;statusListBaseUrl;defaultListSize;constructor(e,t,r,s,i,a){this.storage=e,this.identity=t,this.signingFunction=r,this.compressor=s,this.decompressor=i,this.statusListBaseUrl=a?.statusListBaseUrl||"https://status.example.com",this.defaultListSize=a?.defaultListSize||131072}async allocateStatusEntry(e){const t=`${this.statusListBaseUrl}/${e}/v1`,r=await this.storage.allocateIndex(t);return await this.ensureStatusListExists(t,e),{id:`${t}#${r}`,type:"StatusList2021Entry",statusPurpose:e,statusListIndex:r.toString(),statusListCredential:t}}async updateStatus(e,t){const{statusListCredential:r,statusListIndex:a}=e,o=await this.storage.getStatusList(r);if(!o)throw new Error(`Status list not found: ${r}`);const n=await s.BitstringManager.decode(o.credentialSubject.encodedList,this.compressor,this.decompressor),c=parseInt(a,10);n.setBit(c,t);const d=await n.encode(),l={...o,credentialSubject:{...o.credentialSubject,encodedList:d}},u={...l};delete u.proof;const h=(0,i.canonicalizeJSON)(u),p=await this.signingFunction(h,this.identity.getDid(),this.identity.getKeyId()),f={...l,proof:p};await this.storage.setStatusList(r,f)}async checkStatus(e){const{statusListCredential:t,statusListIndex:r}=e,i=await this.storage.getStatusList(t);if(!i)return!1;const a=await s.BitstringManager.decode(i.credentialSubject.encodedList,this.compressor,this.decompressor),o=parseInt(r,10);return a.getBit(o)}async getRevokedIndices(e){const t=await this.storage.getStatusList(e);return t?(await s.BitstringManager.decode(t.credentialSubject.encodedList,this.compressor,this.decompressor)).getSetBits():[]}async ensureStatusListExists(e,t){if(await this.storage.getStatusList(e))return;const r=new s.BitstringManager(this.defaultListSize,this.compressor,this.decompressor),a=await r.encode(),o={"@context":["https://www.w3.org/2018/credentials/v1","https://w3id.org/vc/status-list/2021/v1"],id:e,type:["VerifiableCredential","StatusList2021Credential"],issuer:this.identity.getDid(),issuanceDate:(new Date).toISOString(),credentialSubject:{id:`${e}#list`,type:"StatusList2021",statusPurpose:t,encodedList:a}},n=(0,i.canonicalizeJSON)(o),c=await this.signingFunction(n,this.identity.getDid(),this.identity.getKeyId()),d={...o,proof:c};await this.storage.setStatusList(e,d)}getStatusListBaseUrl(){return this.statusListBaseUrl}getDefaultListSize(){return this.defaultListSize}}t.StatusList2021Manager=a},98448:(e,t)=>{"use strict";function r(e){const t=e.length%4;return 0===t?e:e+"=".repeat((4-t)%4)}Object.defineProperty(t,"__esModule",{value:!0}),t.base64urlDecodeToString=function(e){const t=r(e).replace(/-/g,"+").replace(/_/g,"/");if("undefined"!=typeof atob)try{return atob(t)}catch(e){throw new Error(`Invalid base64url string: ${e instanceof Error?e.message:String(e)}`)}if(!/^[A-Za-z0-9+/]*={0,2}$/.test(t))throw new Error("Invalid base64url string: contains invalid characters");try{return Buffer.from(t,"base64").toString("utf-8")}catch(e){throw new Error(`Invalid base64url string: ${e instanceof Error?e.message:String(e)}`)}},t.base64urlDecodeToBytes=function(e){const t=r(e).replace(/-/g,"+").replace(/_/g,"/");if("undefined"!=typeof atob)try{const e=atob(t),r=new Uint8Array(e.length);for(let t=0;t<e.length;t++)r[t]=e.charCodeAt(t);return r}catch(e){throw new Error(`Invalid base64url string: ${e instanceof Error?e.message:String(e)}`)}return new Uint8Array(Buffer.from(t,"base64"))},t.base64urlEncodeFromString=function(e){return"undefined"!=typeof btoa?btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,""):Buffer.from(e,"utf-8").toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")},t.base64urlEncodeFromBytes=function(e){if("undefined"!=typeof btoa){const t=Array.from(e).map(e=>String.fromCharCode(e)).join("");return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}return Buffer.from(e).toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")},t.bytesToBase64=function(e){if("undefined"!=typeof btoa){const t=Array.from(e).map(e=>String.fromCharCode(e)).join("");return btoa(t)}return Buffer.from(e).toString("base64")},t.base64ToBytes=function(e){if("undefined"!=typeof atob){const t=atob(e),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r}return new Uint8Array(Buffer.from(e,"base64"))}}},t={};function r(s){var i=t[s];if(void 0!==i)return i.exports;var a=t[s]={exports:{}};return e[s].call(a.exports,a,a.exports,r),a.exports}r.d=(e,t)=>{for(var s in t)r.o(t,s)&&!r.o(e,s)&&Object.defineProperty(e,s,{enumerable:!0,get:t[s]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},(()=>{"use strict";const e=require("node:process");var t,s;!function(e){e.assertEqual=e=>{},e.assertIs=function(e){},e.assertNever=function(e){throw new Error},e.arrayToEnum=e=>{const t={};for(const r of e)t[r]=r;return t},e.getValidEnumValues=t=>{const r=e.objectKeys(t).filter(e=>"number"!=typeof t[t[e]]),s={};for(const e of r)s[e]=t[e];return e.objectValues(s)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{const t=[];for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.push(r);return t},e.find=(e,t)=>{for(const r of e)if(t(r))return r},e.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&Number.isFinite(e)&&Math.floor(e)===e,e.joinValues=function(e,t=" | "){return e.map(e=>"string"==typeof e?`'${e}'`:e).join(t)},e.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t}(t||(t={})),function(e){e.mergeShapes=(e,t)=>({...e,...t})}(s||(s={}));const i=t.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),a=e=>{switch(typeof e){case"undefined":return i.undefined;case"string":return i.string;case"number":return Number.isNaN(e)?i.nan:i.number;case"boolean":return i.boolean;case"function":return i.function;case"bigint":return i.bigint;case"symbol":return i.symbol;case"object":return Array.isArray(e)?i.array:null===e?i.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?i.promise:"undefined"!=typeof Map&&e instanceof Map?i.map:"undefined"!=typeof Set&&e instanceof Set?i.set:"undefined"!=typeof Date&&e instanceof Date?i.date:i.object;default:return i.unknown}},o=t.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class n extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(e){return e.message},r={_errors:[]},s=e=>{for(const i of e.issues)if("invalid_union"===i.code)i.unionErrors.map(s);else if("invalid_return_type"===i.code)s(i.returnTypeError);else if("invalid_arguments"===i.code)s(i.argumentsError);else if(0===i.path.length)r._errors.push(t(i));else{let e=r,s=0;for(;s<i.path.length;){const r=i.path[s];s===i.path.length-1?(e[r]=e[r]||{_errors:[]},e[r]._errors.push(t(i))):e[r]=e[r]||{_errors:[]},e=e[r],s++}}};return s(this),r}static assert(e){if(!(e instanceof n))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,t.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){const t={},r=[];for(const s of this.issues)if(s.path.length>0){const r=s.path[0];t[r]=t[r]||[],t[r].push(e(s))}else r.push(e(s));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}}n.create=e=>new n(e);const c=(e,r)=>{let s;switch(e.code){case o.invalid_type:s=e.received===i.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case o.invalid_literal:s=`Invalid literal value, expected ${JSON.stringify(e.expected,t.jsonStringifyReplacer)}`;break;case o.unrecognized_keys:s=`Unrecognized key(s) in object: ${t.joinValues(e.keys,", ")}`;break;case o.invalid_union:s="Invalid input";break;case o.invalid_union_discriminator:s=`Invalid discriminator value. Expected ${t.joinValues(e.options)}`;break;case o.invalid_enum_value:s=`Invalid enum value. Expected ${t.joinValues(e.options)}, received '${e.received}'`;break;case o.invalid_arguments:s="Invalid function arguments";break;case o.invalid_return_type:s="Invalid function return type";break;case o.invalid_date:s="Invalid date";break;case o.invalid_string:"object"==typeof e.validation?"includes"in e.validation?(s=`Invalid input: must include "${e.validation.includes}"`,"number"==typeof e.validation.position&&(s=`${s} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?s=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?s=`Invalid input: must end with "${e.validation.endsWith}"`:t.assertNever(e.validation):s="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case o.too_small:s="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:"number"===e.type||"bigint"===e.type?`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:"date"===e.type?`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:"Invalid input";break;case o.too_big:s="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"bigint"===e.type?`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"date"===e.type?`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:"Invalid input";break;case o.custom:s="Invalid input";break;case o.invalid_intersection_types:s="Intersection results could not be merged";break;case o.not_multiple_of:s=`Number must be a multiple of ${e.multipleOf}`;break;case o.not_finite:s="Number must be finite";break;default:s=r.defaultError,t.assertNever(e)}return{message:s}};let d=c;var l;!function(e){e.errToObj=e=>"string"==typeof e?{message:e}:e||{},e.toString=e=>"string"==typeof e?e:e?.message}(l||(l={}));function u(e,t){const r=d,s=(e=>{const{data:t,path:r,errorMaps:s,issueData:i}=e,a=[...r,...i.path||[]],o={...i,path:a};if(void 0!==i.message)return{...i,path:a,message:i.message};let n="";const c=s.filter(e=>!!e).slice().reverse();for(const e of c)n=e(o,{data:t,defaultError:n}).message;return{...i,path:a,message:n}})({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===c?void 0:c].filter(e=>!!e)});e.common.issues.push(s)}class h{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){const r=[];for(const s of t){if("aborted"===s.status)return p;"dirty"===s.status&&e.dirty(),r.push(s.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){const r=[];for(const e of t){const t=await e.key,s=await e.value;r.push({key:t,value:s})}return h.mergeObjectSync(e,r)}static mergeObjectSync(e,t){const r={};for(const s of t){const{key:t,value:i}=s;if("aborted"===t.status)return p;if("aborted"===i.status)return p;"dirty"===t.status&&e.dirty(),"dirty"===i.status&&e.dirty(),"__proto__"===t.value||void 0===i.value&&!s.alwaysSet||(r[t.value]=i.value)}return{status:e.value,value:r}}}const p=Object.freeze({status:"aborted"}),f=e=>({status:"dirty",value:e}),g=e=>({status:"valid",value:e}),m=e=>"aborted"===e.status,v=e=>"dirty"===e.status,y=e=>"valid"===e.status,_=e=>"undefined"!=typeof Promise&&e instanceof Promise;class w{constructor(e,t,r,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const b=(e,t)=>{if(y(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new n(e.common.issues);return this._error=t,this._error}}};function S(e){if(!e)return{};const{errorMap:t,invalid_type_error:r,required_error:s,description:i}=e;if(t&&(r||s))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');return t?{errorMap:t,description:i}:{errorMap:(t,i)=>{const{message:a}=e;return"invalid_enum_value"===t.code?{message:a??i.defaultError}:void 0===i.data?{message:a??s??i.defaultError}:"invalid_type"!==t.code?{message:i.defaultError}:{message:a??r??i.defaultError}},description:i}}class P{get description(){return this._def.description}_getType(e){return a(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:a(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new h,ctx:{common:e.parent.common,data:e.data,parsedType:a(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(_(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){const r={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:a(e)},s=this._parseSync({data:e,path:r.path,parent:r});return b(r,s)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:a(e)};if(!this["~standard"].async)try{const r=this._parseSync({data:e,path:[],parent:t});return y(r)?{value:r.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>y(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){const r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){const r={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:a(e)},s=this._parse({data:e,path:r.path,parent:r}),i=await(_(s)?s:Promise.resolve(s));return b(r,i)}refine(e,t){const r=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement((t,s)=>{const i=e(t),a=()=>s.addIssue({code:o.custom,...r(t)});return"undefined"!=typeof Promise&&i instanceof Promise?i.then(e=>!!e||(a(),!1)):!!i||(a(),!1)})}refinement(e,t){return this._refinement((r,s)=>!!e(r)||(s.addIssue("function"==typeof t?t(r,s):t),!1))}_refinement(e){return new Ee({schema:this,typeName:Re.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:e=>this["~validate"](e)}}optional(){return Ie.create(this,this._def)}nullable(){return ke.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return oe.create(this)}promise(){return Pe.create(this,this._def)}or(e){return de.create([this,e],this._def)}and(e){return pe.create(this,e,this._def)}transform(e){return new Ee({...S(this._def),schema:this,typeName:Re.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new Ce({...S(this._def),innerType:this,defaultValue:t,typeName:Re.ZodDefault})}brand(){return new Ae({typeName:Re.ZodBranded,type:this,...S(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new De({...S(this._def),innerType:this,catchValue:t,typeName:Re.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return xe.create(this,e)}readonly(){return Te.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const E=/^c[^\s-]{8,}$/i,I=/^[0-9a-z]+$/,k=/^[0-9A-HJKMNP-TV-Z]{26}$/i,C=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,D=/^[a-z0-9_-]{21}$/i,O=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,A=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,x=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let T;const R=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,$=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,j=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,N=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,M=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,F=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,K="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",q=new RegExp(`^${K}$`);function L(e){let t="[0-5]\\d";return e.precision?t=`${t}\\.\\d{${e.precision}}`:null==e.precision&&(t=`${t}(\\.\\d+)?`),`([01]\\d|2[0-3]):[0-5]\\d(:${t})${e.precision?"+":"?"}`}function U(e){return new RegExp(`^${L(e)}$`)}function V(e){let t=`${K}T${L(e)}`;const r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function H(e,t){return!("v4"!==t&&t||!R.test(e))||!("v6"!==t&&t||!j.test(e))}function B(e,t){if(!O.test(e))return!1;try{const[r]=e.split(".");if(!r)return!1;const s=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),i=JSON.parse(atob(s));return!("object"!=typeof i||null===i||"typ"in i&&"JWT"!==i?.typ||!i.alg||t&&i.alg!==t)}catch{return!1}}function z(e,t){return!("v4"!==t&&t||!$.test(e))||!("v6"!==t&&t||!N.test(e))}class J extends P{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==i.string){const t=this._getOrReturnCtx(e);return u(t,{code:o.invalid_type,expected:i.string,received:t.parsedType}),p}const r=new h;let s;for(const i of this._def.checks)if("min"===i.kind)e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),u(s,{code:o.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if("max"===i.kind)e.data.length>i.value&&(s=this._getOrReturnCtx(e,s),u(s,{code:o.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if("length"===i.kind){const t=e.data.length>i.value,a=e.data.length<i.value;(t||a)&&(s=this._getOrReturnCtx(e,s),t?u(s,{code:o.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):a&&u(s,{code:o.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if("email"===i.kind)x.test(e.data)||(s=this._getOrReturnCtx(e,s),u(s,{validation:"email",code:o.invalid_string,message:i.message}),r.dirty());else if("emoji"===i.kind)T||(T=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),T.test(e.data)||(s=this._getOrReturnCtx(e,s),u(s,{validation:"emoji",code:o.invalid_string,message:i.message}),r.dirty());else if("uuid"===i.kind)C.test(e.data)||(s=this._getOrReturnCtx(e,s),u(s,{validation:"uuid",code:o.invalid_string,message:i.message}),r.dirty());else if("nanoid"===i.kind)D.test(e.data)||(s=this._getOrReturnCtx(e,s),u(s,{validation:"nanoid",code:o.invalid_string,message:i.message}),r.dirty());else if("cuid"===i.kind)E.test(e.data)||(s=this._getOrReturnCtx(e,s),u(s,{validation:"cuid",code:o.invalid_string,message:i.message}),r.dirty());else if("cuid2"===i.kind)I.test(e.data)||(s=this._getOrReturnCtx(e,s),u(s,{validation:"cuid2",code:o.invalid_string,message:i.message}),r.dirty());else if("ulid"===i.kind)k.test(e.data)||(s=this._getOrReturnCtx(e,s),u(s,{validation:"ulid",code:o.invalid_string,message:i.message}),r.dirty());else if("url"===i.kind)try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),u(s,{validation:"url",code:o.invalid_string,message:i.message}),r.dirty()}else"regex"===i.kind?(i.regex.lastIndex=0,i.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),u(s,{validation:"regex",code:o.invalid_string,message:i.message}),r.dirty())):"trim"===i.kind?e.data=e.data.trim():"includes"===i.kind?e.data.includes(i.value,i.position)||(s=this._getOrReturnCtx(e,s),u(s,{code:o.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),r.dirty()):"toLowerCase"===i.kind?e.data=e.data.toLowerCase():"toUpperCase"===i.kind?e.data=e.data.toUpperCase():"startsWith"===i.kind?e.data.startsWith(i.value)||(s=this._getOrReturnCtx(e,s),u(s,{code:o.invalid_string,validation:{startsWith:i.value},message:i.message}),r.dirty()):"endsWith"===i.kind?e.data.endsWith(i.value)||(s=this._getOrReturnCtx(e,s),u(s,{code:o.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):"datetime"===i.kind?V(i).test(e.data)||(s=this._getOrReturnCtx(e,s),u(s,{code:o.invalid_string,validation:"datetime",message:i.message}),r.dirty()):"date"===i.kind?q.test(e.data)||(s=this._getOrReturnCtx(e,s),u(s,{code:o.invalid_string,validation:"date",message:i.message}),r.dirty()):"time"===i.kind?U(i).test(e.data)||(s=this._getOrReturnCtx(e,s),u(s,{code:o.invalid_string,validation:"time",message:i.message}),r.dirty()):"duration"===i.kind?A.test(e.data)||(s=this._getOrReturnCtx(e,s),u(s,{validation:"duration",code:o.invalid_string,message:i.message}),r.dirty()):"ip"===i.kind?H(e.data,i.version)||(s=this._getOrReturnCtx(e,s),u(s,{validation:"ip",code:o.invalid_string,message:i.message}),r.dirty()):"jwt"===i.kind?B(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),u(s,{validation:"jwt",code:o.invalid_string,message:i.message}),r.dirty()):"cidr"===i.kind?z(e.data,i.version)||(s=this._getOrReturnCtx(e,s),u(s,{validation:"cidr",code:o.invalid_string,message:i.message}),r.dirty()):"base64"===i.kind?M.test(e.data)||(s=this._getOrReturnCtx(e,s),u(s,{validation:"base64",code:o.invalid_string,message:i.message}),r.dirty()):"base64url"===i.kind?F.test(e.data)||(s=this._getOrReturnCtx(e,s),u(s,{validation:"base64url",code:o.invalid_string,message:i.message}),r.dirty()):t.assertNever(i);return{status:r.value,value:e.data}}_regex(e,t,r){return this.refinement(t=>e.test(t),{validation:t,code:o.invalid_string,...l.errToObj(r)})}_addCheck(e){return new J({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...l.errToObj(e)})}url(e){return this._addCheck({kind:"url",...l.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...l.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...l.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...l.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...l.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...l.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...l.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...l.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...l.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...l.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...l.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...l.errToObj(e)})}datetime(e){return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===e?.precision?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...l.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return"string"==typeof e?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:void 0===e?.precision?null:e?.precision,...l.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...l.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...l.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...l.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...l.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...l.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...l.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...l.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...l.errToObj(t)})}nonempty(e){return this.min(1,l.errToObj(e))}trim(){return new J({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new J({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new J({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>"datetime"===e.kind)}get isDate(){return!!this._def.checks.find(e=>"date"===e.kind)}get isTime(){return!!this._def.checks.find(e=>"time"===e.kind)}get isDuration(){return!!this._def.checks.find(e=>"duration"===e.kind)}get isEmail(){return!!this._def.checks.find(e=>"email"===e.kind)}get isURL(){return!!this._def.checks.find(e=>"url"===e.kind)}get isEmoji(){return!!this._def.checks.find(e=>"emoji"===e.kind)}get isUUID(){return!!this._def.checks.find(e=>"uuid"===e.kind)}get isNANOID(){return!!this._def.checks.find(e=>"nanoid"===e.kind)}get isCUID(){return!!this._def.checks.find(e=>"cuid"===e.kind)}get isCUID2(){return!!this._def.checks.find(e=>"cuid2"===e.kind)}get isULID(){return!!this._def.checks.find(e=>"ulid"===e.kind)}get isIP(){return!!this._def.checks.find(e=>"ip"===e.kind)}get isCIDR(){return!!this._def.checks.find(e=>"cidr"===e.kind)}get isBase64(){return!!this._def.checks.find(e=>"base64"===e.kind)}get isBase64url(){return!!this._def.checks.find(e=>"base64url"===e.kind)}get minLength(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}function W(e,t){const r=(e.toString().split(".")[1]||"").length,s=(t.toString().split(".")[1]||"").length,i=r>s?r:s;return Number.parseInt(e.toFixed(i).replace(".",""))%Number.parseInt(t.toFixed(i).replace(".",""))/10**i}J.create=e=>new J({checks:[],typeName:Re.ZodString,coerce:e?.coerce??!1,...S(e)});class Z extends P{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==i.number){const t=this._getOrReturnCtx(e);return u(t,{code:o.invalid_type,expected:i.number,received:t.parsedType}),p}let r;const s=new h;for(const i of this._def.checks)"int"===i.kind?t.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),u(r,{code:o.invalid_type,expected:"integer",received:"float",message:i.message}),s.dirty()):"min"===i.kind?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),u(r,{code:o.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):"max"===i.kind?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),u(r,{code:o.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):"multipleOf"===i.kind?0!==W(e.data,i.value)&&(r=this._getOrReturnCtx(e,r),u(r,{code:o.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):"finite"===i.kind?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),u(r,{code:o.not_finite,message:i.message}),s.dirty()):t.assertNever(i);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,l.toString(t))}gt(e,t){return this.setLimit("min",e,!1,l.toString(t))}lte(e,t){return this.setLimit("max",e,!0,l.toString(t))}lt(e,t){return this.setLimit("max",e,!1,l.toString(t))}setLimit(e,t,r,s){return new Z({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:l.toString(s)}]})}_addCheck(e){return new Z({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:l.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:l.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:l.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:l.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:l.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:l.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:l.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:l.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:l.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>"int"===e.kind||"multipleOf"===e.kind&&t.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const r of this._def.checks){if("finite"===r.kind||"int"===r.kind||"multipleOf"===r.kind)return!0;"min"===r.kind?(null===t||r.value>t)&&(t=r.value):"max"===r.kind&&(null===e||r.value<e)&&(e=r.value)}return Number.isFinite(t)&&Number.isFinite(e)}}Z.create=e=>new Z({checks:[],typeName:Re.ZodNumber,coerce:e?.coerce||!1,...S(e)});class Q extends P{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==i.bigint)return this._getInvalidInput(e);let r;const s=new h;for(const i of this._def.checks)"min"===i.kind?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),u(r,{code:o.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):"max"===i.kind?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),u(r,{code:o.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):"multipleOf"===i.kind?e.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),u(r,{code:o.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):t.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return u(t,{code:o.invalid_type,expected:i.bigint,received:t.parsedType}),p}gte(e,t){return this.setLimit("min",e,!0,l.toString(t))}gt(e,t){return this.setLimit("min",e,!1,l.toString(t))}lte(e,t){return this.setLimit("max",e,!0,l.toString(t))}lt(e,t){return this.setLimit("max",e,!1,l.toString(t))}setLimit(e,t,r,s){return new Q({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:l.toString(s)}]})}_addCheck(e){return new Q({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:l.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:l.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:l.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:l.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:l.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}Q.create=e=>new Q({checks:[],typeName:Re.ZodBigInt,coerce:e?.coerce??!1,...S(e)});class G extends P{_parse(e){if(this._def.coerce&&(e.data=Boolean(e.data)),this._getType(e)!==i.boolean){const t=this._getOrReturnCtx(e);return u(t,{code:o.invalid_type,expected:i.boolean,received:t.parsedType}),p}return g(e.data)}}G.create=e=>new G({typeName:Re.ZodBoolean,coerce:e?.coerce||!1,...S(e)});class Y extends P{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==i.date){const t=this._getOrReturnCtx(e);return u(t,{code:o.invalid_type,expected:i.date,received:t.parsedType}),p}if(Number.isNaN(e.data.getTime()))return u(this._getOrReturnCtx(e),{code:o.invalid_date}),p;const r=new h;let s;for(const i of this._def.checks)"min"===i.kind?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),u(s,{code:o.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),r.dirty()):"max"===i.kind?e.data.getTime()>i.value&&(s=this._getOrReturnCtx(e,s),u(s,{code:o.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):t.assertNever(i);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new Y({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:l.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:l.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}}Y.create=e=>new Y({checks:[],coerce:e?.coerce||!1,typeName:Re.ZodDate,...S(e)});class X extends P{_parse(e){if(this._getType(e)!==i.symbol){const t=this._getOrReturnCtx(e);return u(t,{code:o.invalid_type,expected:i.symbol,received:t.parsedType}),p}return g(e.data)}}X.create=e=>new X({typeName:Re.ZodSymbol,...S(e)});class ee extends P{_parse(e){if(this._getType(e)!==i.undefined){const t=this._getOrReturnCtx(e);return u(t,{code:o.invalid_type,expected:i.undefined,received:t.parsedType}),p}return g(e.data)}}ee.create=e=>new ee({typeName:Re.ZodUndefined,...S(e)});class te extends P{_parse(e){if(this._getType(e)!==i.null){const t=this._getOrReturnCtx(e);return u(t,{code:o.invalid_type,expected:i.null,received:t.parsedType}),p}return g(e.data)}}te.create=e=>new te({typeName:Re.ZodNull,...S(e)});class re extends P{constructor(){super(...arguments),this._any=!0}_parse(e){return g(e.data)}}re.create=e=>new re({typeName:Re.ZodAny,...S(e)});class se extends P{constructor(){super(...arguments),this._unknown=!0}_parse(e){return g(e.data)}}se.create=e=>new se({typeName:Re.ZodUnknown,...S(e)});class ie extends P{_parse(e){const t=this._getOrReturnCtx(e);return u(t,{code:o.invalid_type,expected:i.never,received:t.parsedType}),p}}ie.create=e=>new ie({typeName:Re.ZodNever,...S(e)});class ae extends P{_parse(e){if(this._getType(e)!==i.undefined){const t=this._getOrReturnCtx(e);return u(t,{code:o.invalid_type,expected:i.void,received:t.parsedType}),p}return g(e.data)}}ae.create=e=>new ae({typeName:Re.ZodVoid,...S(e)});class oe extends P{_parse(e){const{ctx:t,status:r}=this._processInputParams(e),s=this._def;if(t.parsedType!==i.array)return u(t,{code:o.invalid_type,expected:i.array,received:t.parsedType}),p;if(null!==s.exactLength){const e=t.data.length>s.exactLength.value,i=t.data.length<s.exactLength.value;(e||i)&&(u(t,{code:e?o.too_big:o.too_small,minimum:i?s.exactLength.value:void 0,maximum:e?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),r.dirty())}if(null!==s.minLength&&t.data.length<s.minLength.value&&(u(t,{code:o.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),null!==s.maxLength&&t.data.length>s.maxLength.value&&(u(t,{code:o.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map((e,r)=>s.type._parseAsync(new w(t,e,t.path,r)))).then(e=>h.mergeArray(r,e));const a=[...t.data].map((e,r)=>s.type._parseSync(new w(t,e,t.path,r)));return h.mergeArray(r,a)}get element(){return this._def.type}min(e,t){return new oe({...this._def,minLength:{value:e,message:l.toString(t)}})}max(e,t){return new oe({...this._def,maxLength:{value:e,message:l.toString(t)}})}length(e,t){return new oe({...this._def,exactLength:{value:e,message:l.toString(t)}})}nonempty(e){return this.min(1,e)}}function ne(e){if(e instanceof ce){const t={};for(const r in e.shape){const s=e.shape[r];t[r]=Ie.create(ne(s))}return new ce({...e._def,shape:()=>t})}return e instanceof oe?new oe({...e._def,type:ne(e.element)}):e instanceof Ie?Ie.create(ne(e.unwrap())):e instanceof ke?ke.create(ne(e.unwrap())):e instanceof fe?fe.create(e.items.map(e=>ne(e))):e}oe.create=(e,t)=>new oe({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Re.ZodArray,...S(t)});class ce extends P{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;const e=this._def.shape(),r=t.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==i.object){const t=this._getOrReturnCtx(e);return u(t,{code:o.invalid_type,expected:i.object,received:t.parsedType}),p}const{status:t,ctx:r}=this._processInputParams(e),{shape:s,keys:a}=this._getCached(),n=[];if(!(this._def.catchall instanceof ie&&"strip"===this._def.unknownKeys))for(const e in r.data)a.includes(e)||n.push(e);const c=[];for(const e of a){const t=s[e],i=r.data[e];c.push({key:{status:"valid",value:e},value:t._parse(new w(r,i,r.path,e)),alwaysSet:e in r.data})}if(this._def.catchall instanceof ie){const e=this._def.unknownKeys;if("passthrough"===e)for(const e of n)c.push({key:{status:"valid",value:e},value:{status:"valid",value:r.data[e]}});else if("strict"===e)n.length>0&&(u(r,{code:o.unrecognized_keys,keys:n}),t.dirty());else if("strip"!==e)throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const e=this._def.catchall;for(const t of n){const s=r.data[t];c.push({key:{status:"valid",value:t},value:e._parse(new w(r,s,r.path,t)),alwaysSet:t in r.data})}}return r.common.async?Promise.resolve().then(async()=>{const e=[];for(const t of c){const r=await t.key,s=await t.value;e.push({key:r,value:s,alwaysSet:t.alwaysSet})}return e}).then(e=>h.mergeObjectSync(t,e)):h.mergeObjectSync(t,c)}get shape(){return this._def.shape()}strict(e){return l.errToObj,new ce({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,r)=>{const s=this._def.errorMap?.(t,r).message??r.defaultError;return"unrecognized_keys"===t.code?{message:l.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new ce({...this._def,unknownKeys:"strip"})}passthrough(){return new ce({...this._def,unknownKeys:"passthrough"})}extend(e){return new ce({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new ce({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:Re.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new ce({...this._def,catchall:e})}pick(e){const r={};for(const s of t.objectKeys(e))e[s]&&this.shape[s]&&(r[s]=this.shape[s]);return new ce({...this._def,shape:()=>r})}omit(e){const r={};for(const s of t.objectKeys(this.shape))e[s]||(r[s]=this.shape[s]);return new ce({...this._def,shape:()=>r})}deepPartial(){return ne(this)}partial(e){const r={};for(const s of t.objectKeys(this.shape)){const t=this.shape[s];e&&!e[s]?r[s]=t:r[s]=t.optional()}return new ce({...this._def,shape:()=>r})}required(e){const r={};for(const s of t.objectKeys(this.shape))if(e&&!e[s])r[s]=this.shape[s];else{let e=this.shape[s];for(;e instanceof Ie;)e=e._def.innerType;r[s]=e}return new ce({...this._def,shape:()=>r})}keyof(){return we(t.objectKeys(this.shape))}}ce.create=(e,t)=>new ce({shape:()=>e,unknownKeys:"strip",catchall:ie.create(),typeName:Re.ZodObject,...S(t)}),ce.strictCreate=(e,t)=>new ce({shape:()=>e,unknownKeys:"strict",catchall:ie.create(),typeName:Re.ZodObject,...S(t)}),ce.lazycreate=(e,t)=>new ce({shape:e,unknownKeys:"strip",catchall:ie.create(),typeName:Re.ZodObject,...S(t)});class de extends P{_parse(e){const{ctx:t}=this._processInputParams(e),r=this._def.options;if(t.common.async)return Promise.all(r.map(async e=>{const r={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:r}),ctx:r}})).then(function(e){for(const t of e)if("valid"===t.result.status)return t.result;for(const r of e)if("dirty"===r.result.status)return t.common.issues.push(...r.ctx.common.issues),r.result;const r=e.map(e=>new n(e.ctx.common.issues));return u(t,{code:o.invalid_union,unionErrors:r}),p});{let e;const s=[];for(const i of r){const r={...t,common:{...t.common,issues:[]},parent:null},a=i._parseSync({data:t.data,path:t.path,parent:r});if("valid"===a.status)return a;"dirty"!==a.status||e||(e={result:a,ctx:r}),r.common.issues.length&&s.push(r.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const i=s.map(e=>new n(e));return u(t,{code:o.invalid_union,unionErrors:i}),p}}get options(){return this._def.options}}de.create=(e,t)=>new de({options:e,typeName:Re.ZodUnion,...S(t)});const le=e=>e instanceof ye?le(e.schema):e instanceof Ee?le(e.innerType()):e instanceof _e?[e.value]:e instanceof be?e.options:e instanceof Se?t.objectValues(e.enum):e instanceof Ce?le(e._def.innerType):e instanceof ee?[void 0]:e instanceof te?[null]:e instanceof Ie?[void 0,...le(e.unwrap())]:e instanceof ke?[null,...le(e.unwrap())]:e instanceof Ae||e instanceof Te?le(e.unwrap()):e instanceof De?le(e._def.innerType):[];class ue extends P{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==i.object)return u(t,{code:o.invalid_type,expected:i.object,received:t.parsedType}),p;const r=this.discriminator,s=t.data[r],a=this.optionsMap.get(s);return a?t.common.async?a._parseAsync({data:t.data,path:t.path,parent:t}):a._parseSync({data:t.data,path:t.path,parent:t}):(u(t,{code:o.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),p)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,r){const s=new Map;for(const r of t){const t=le(r.shape[e]);if(!t.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const i of t){if(s.has(i))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(i)}`);s.set(i,r)}}return new ue({typeName:Re.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:s,...S(r)})}}function he(e,r){const s=a(e),o=a(r);if(e===r)return{valid:!0,data:e};if(s===i.object&&o===i.object){const s=t.objectKeys(r),i=t.objectKeys(e).filter(e=>-1!==s.indexOf(e)),a={...e,...r};for(const t of i){const s=he(e[t],r[t]);if(!s.valid)return{valid:!1};a[t]=s.data}return{valid:!0,data:a}}if(s===i.array&&o===i.array){if(e.length!==r.length)return{valid:!1};const t=[];for(let s=0;s<e.length;s++){const i=he(e[s],r[s]);if(!i.valid)return{valid:!1};t.push(i.data)}return{valid:!0,data:t}}return s===i.date&&o===i.date&&+e===+r?{valid:!0,data:e}:{valid:!1}}class pe extends P{_parse(e){const{status:t,ctx:r}=this._processInputParams(e),s=(e,s)=>{if(m(e)||m(s))return p;const i=he(e.value,s.value);return i.valid?((v(e)||v(s))&&t.dirty(),{status:t.value,value:i.data}):(u(r,{code:o.invalid_intersection_types}),p)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([e,t])=>s(e,t)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}pe.create=(e,t,r)=>new pe({left:e,right:t,typeName:Re.ZodIntersection,...S(r)});class fe extends P{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==i.array)return u(r,{code:o.invalid_type,expected:i.array,received:r.parsedType}),p;if(r.data.length<this._def.items.length)return u(r,{code:o.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),p;!this._def.rest&&r.data.length>this._def.items.length&&(u(r,{code:o.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const s=[...r.data].map((e,t)=>{const s=this._def.items[t]||this._def.rest;return s?s._parse(new w(r,e,r.path,t)):null}).filter(e=>!!e);return r.common.async?Promise.all(s).then(e=>h.mergeArray(t,e)):h.mergeArray(t,s)}get items(){return this._def.items}rest(e){return new fe({...this._def,rest:e})}}fe.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new fe({items:e,typeName:Re.ZodTuple,rest:null,...S(t)})};class ge extends P{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==i.object)return u(r,{code:o.invalid_type,expected:i.object,received:r.parsedType}),p;const s=[],a=this._def.keyType,n=this._def.valueType;for(const e in r.data)s.push({key:a._parse(new w(r,e,r.path,e)),value:n._parse(new w(r,r.data[e],r.path,e)),alwaysSet:e in r.data});return r.common.async?h.mergeObjectAsync(t,s):h.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,r){return new ge(t instanceof P?{keyType:e,valueType:t,typeName:Re.ZodRecord,...S(r)}:{keyType:J.create(),valueType:e,typeName:Re.ZodRecord,...S(t)})}}class me extends P{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==i.map)return u(r,{code:o.invalid_type,expected:i.map,received:r.parsedType}),p;const s=this._def.keyType,a=this._def.valueType,n=[...r.data.entries()].map(([e,t],i)=>({key:s._parse(new w(r,e,r.path,[i,"key"])),value:a._parse(new w(r,t,r.path,[i,"value"]))}));if(r.common.async){const e=new Map;return Promise.resolve().then(async()=>{for(const r of n){const s=await r.key,i=await r.value;if("aborted"===s.status||"aborted"===i.status)return p;"dirty"!==s.status&&"dirty"!==i.status||t.dirty(),e.set(s.value,i.value)}return{status:t.value,value:e}})}{const e=new Map;for(const r of n){const s=r.key,i=r.value;if("aborted"===s.status||"aborted"===i.status)return p;"dirty"!==s.status&&"dirty"!==i.status||t.dirty(),e.set(s.value,i.value)}return{status:t.value,value:e}}}}me.create=(e,t,r)=>new me({valueType:t,keyType:e,typeName:Re.ZodMap,...S(r)});class ve extends P{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==i.set)return u(r,{code:o.invalid_type,expected:i.set,received:r.parsedType}),p;const s=this._def;null!==s.minSize&&r.data.size<s.minSize.value&&(u(r,{code:o.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),null!==s.maxSize&&r.data.size>s.maxSize.value&&(u(r,{code:o.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());const a=this._def.valueType;function n(e){const r=new Set;for(const s of e){if("aborted"===s.status)return p;"dirty"===s.status&&t.dirty(),r.add(s.value)}return{status:t.value,value:r}}const c=[...r.data.values()].map((e,t)=>a._parse(new w(r,e,r.path,t)));return r.common.async?Promise.all(c).then(e=>n(e)):n(c)}min(e,t){return new ve({...this._def,minSize:{value:e,message:l.toString(t)}})}max(e,t){return new ve({...this._def,maxSize:{value:e,message:l.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}ve.create=(e,t)=>new ve({valueType:e,minSize:null,maxSize:null,typeName:Re.ZodSet,...S(t)});class ye extends P{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}ye.create=(e,t)=>new ye({getter:e,typeName:Re.ZodLazy,...S(t)});class _e extends P{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return u(t,{received:t.data,code:o.invalid_literal,expected:this._def.value}),p}return{status:"valid",value:e.data}}get value(){return this._def.value}}function we(e,t){return new be({values:e,typeName:Re.ZodEnum,...S(t)})}_e.create=(e,t)=>new _e({value:e,typeName:Re.ZodLiteral,...S(t)});class be extends P{_parse(e){if("string"!=typeof e.data){const r=this._getOrReturnCtx(e),s=this._def.values;return u(r,{expected:t.joinValues(s),received:r.parsedType,code:o.invalid_type}),p}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),r=this._def.values;return u(t,{received:t.data,code:o.invalid_enum_value,options:r}),p}return g(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return be.create(e,{...this._def,...t})}exclude(e,t=this._def){return be.create(this.options.filter(t=>!e.includes(t)),{...this._def,...t})}}be.create=we;class Se extends P{_parse(e){const r=t.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(e);if(s.parsedType!==i.string&&s.parsedType!==i.number){const e=t.objectValues(r);return u(s,{expected:t.joinValues(e),received:s.parsedType,code:o.invalid_type}),p}if(this._cache||(this._cache=new Set(t.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const e=t.objectValues(r);return u(s,{received:s.data,code:o.invalid_enum_value,options:e}),p}return g(e.data)}get enum(){return this._def.values}}Se.create=(e,t)=>new Se({values:e,typeName:Re.ZodNativeEnum,...S(t)});class Pe extends P{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==i.promise&&!1===t.common.async)return u(t,{code:o.invalid_type,expected:i.promise,received:t.parsedType}),p;const r=t.parsedType===i.promise?t.data:Promise.resolve(t.data);return g(r.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}Pe.create=(e,t)=>new Pe({type:e,typeName:Re.ZodPromise,...S(t)});class Ee extends P{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Re.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:r,ctx:s}=this._processInputParams(e),i=this._def.effect||null,a={addIssue:e=>{u(s,e),e.fatal?r.abort():r.dirty()},get path(){return s.path}};if(a.addIssue=a.addIssue.bind(a),"preprocess"===i.type){const e=i.transform(s.data,a);if(s.common.async)return Promise.resolve(e).then(async e=>{if("aborted"===r.value)return p;const t=await this._def.schema._parseAsync({data:e,path:s.path,parent:s});return"aborted"===t.status?p:"dirty"===t.status||"dirty"===r.value?f(t.value):t});{if("aborted"===r.value)return p;const t=this._def.schema._parseSync({data:e,path:s.path,parent:s});return"aborted"===t.status?p:"dirty"===t.status||"dirty"===r.value?f(t.value):t}}if("refinement"===i.type){const e=e=>{const t=i.refinement(e,a);if(s.common.async)return Promise.resolve(t);if(t instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1===s.common.async){const t=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});return"aborted"===t.status?p:("dirty"===t.status&&r.dirty(),e(t.value),{status:r.value,value:t.value})}return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(t=>"aborted"===t.status?p:("dirty"===t.status&&r.dirty(),e(t.value).then(()=>({status:r.value,value:t.value}))))}if("transform"===i.type){if(!1===s.common.async){const e=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(!y(e))return p;const t=i.transform(e.value,a);if(t instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:t}}return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(e=>y(e)?Promise.resolve(i.transform(e.value,a)).then(e=>({status:r.value,value:e})):p)}t.assertNever(i)}}Ee.create=(e,t,r)=>new Ee({schema:e,typeName:Re.ZodEffects,effect:t,...S(r)}),Ee.createWithPreprocess=(e,t,r)=>new Ee({schema:t,effect:{type:"preprocess",transform:e},typeName:Re.ZodEffects,...S(r)});class Ie extends P{_parse(e){return this._getType(e)===i.undefined?g(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Ie.create=(e,t)=>new Ie({innerType:e,typeName:Re.ZodOptional,...S(t)});class ke extends P{_parse(e){return this._getType(e)===i.null?g(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ke.create=(e,t)=>new ke({innerType:e,typeName:Re.ZodNullable,...S(t)});class Ce extends P{_parse(e){const{ctx:t}=this._processInputParams(e);let r=t.data;return t.parsedType===i.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}Ce.create=(e,t)=>new Ce({innerType:e,typeName:Re.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...S(t)});class De extends P{_parse(e){const{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return _(s)?s.then(e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new n(r.common.issues)},input:r.data})})):{status:"valid",value:"valid"===s.status?s.value:this._def.catchValue({get error(){return new n(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}De.create=(e,t)=>new De({innerType:e,typeName:Re.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...S(t)});class Oe extends P{_parse(e){if(this._getType(e)!==i.nan){const t=this._getOrReturnCtx(e);return u(t,{code:o.invalid_type,expected:i.nan,received:t.parsedType}),p}return{status:"valid",value:e.data}}}Oe.create=e=>new Oe({typeName:Re.ZodNaN,...S(e)}),Symbol("zod_brand");class Ae extends P{_parse(e){const{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}}class xe extends P{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{const e=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?p:"dirty"===e.status?(t.dirty(),f(e.value)):this._def.out._parseAsync({data:e.value,path:r.path,parent:r})})();{const e=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?p:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:r.path,parent:r})}}static create(e,t){return new xe({in:e,out:t,typeName:Re.ZodPipeline})}}class Te extends P{_parse(e){const t=this._def.innerType._parse(e),r=e=>(y(e)&&(e.value=Object.freeze(e.value)),e);return _(t)?t.then(e=>r(e)):r(t)}unwrap(){return this._def.innerType}}var Re;Te.create=(e,t)=>new Te({innerType:e,typeName:Re.ZodReadonly,...S(t)}),ce.lazycreate,function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"}(Re||(Re={}));const $e=J.create,je=Z.create,Ne=(Oe.create,Q.create,G.create),Me=(Y.create,X.create,ee.create,te.create,re.create,se.create),Fe=(ie.create,ae.create,oe.create),Ke=ce.create,qe=(ce.strictCreate,de.create),Le=ue.create,Ue=(pe.create,fe.create,ge.create),Ve=(me.create,ve.create,ye.create,_e.create),He=be.create,Be=(Se.create,Pe.create,Ee.create,Ie.create),ze=(ke.create,Ee.createWithPreprocess,xe.create,"2025-06-18"),Je=[ze,"2025-03-26","2024-11-05","2024-10-07"],We="2.0",Ze=qe([$e(),je().int()]),Qe=$e(),Ge=Ke({progressToken:Be(Ze)}).passthrough(),Ye=Ke({_meta:Be(Ge)}).passthrough(),Xe=Ke({method:$e(),params:Be(Ye)}),et=Ke({_meta:Be(Ke({}).passthrough())}).passthrough(),tt=Ke({method:$e(),params:Be(et)}),rt=Ke({_meta:Be(Ke({}).passthrough())}).passthrough(),st=qe([$e(),je().int()]),it=Ke({jsonrpc:Ve(We),id:st}).merge(Xe).strict(),at=Ke({jsonrpc:Ve(We)}).merge(tt).strict(),ot=Ke({jsonrpc:Ve(We),id:st,result:rt}).strict(),nt=e=>ot.safeParse(e).success;var ct;!function(e){e[e.ConnectionClosed=-32e3]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError"}(ct||(ct={}));const dt=Ke({jsonrpc:Ve(We),id:st,error:Ke({code:je().int(),message:$e(),data:Be(Me())})}).strict(),lt=qe([it,at,ot,dt]),ut=rt.strict(),ht=tt.extend({method:Ve("notifications/cancelled"),params:et.extend({requestId:st,reason:$e().optional()})}),pt=Ke({src:$e(),mimeType:Be($e()),sizes:Be($e())}).passthrough(),ft=Ke({name:$e(),title:Be($e())}).passthrough(),gt=ft.extend({version:$e(),websiteUrl:Be($e()),icons:Be(Fe(pt))}),mt=Ke({experimental:Be(Ke({}).passthrough()),sampling:Be(Ke({}).passthrough()),elicitation:Be(Ke({}).passthrough()),roots:Be(Ke({listChanged:Be(Ne())}).passthrough())}).passthrough(),vt=Xe.extend({method:Ve("initialize"),params:Ye.extend({protocolVersion:$e(),capabilities:mt,clientInfo:gt})}),yt=Ke({experimental:Be(Ke({}).passthrough()),logging:Be(Ke({}).passthrough()),completions:Be(Ke({}).passthrough()),prompts:Be(Ke({listChanged:Be(Ne())}).passthrough()),resources:Be(Ke({subscribe:Be(Ne()),listChanged:Be(Ne())}).passthrough()),tools:Be(Ke({listChanged:Be(Ne())}).passthrough())}).passthrough(),_t=rt.extend({protocolVersion:$e(),capabilities:yt,serverInfo:gt,instructions:Be($e())}),wt=tt.extend({method:Ve("notifications/initialized")}),bt=Xe.extend({method:Ve("ping")}),St=Ke({progress:je(),total:Be(je()),message:Be($e())}).passthrough(),Pt=tt.extend({method:Ve("notifications/progress"),params:et.merge(St).extend({progressToken:Ze})}),Et=Xe.extend({params:Ye.extend({cursor:Be(Qe)}).optional()}),It=rt.extend({nextCursor:Be(Qe)}),kt=Ke({uri:$e(),mimeType:Be($e()),_meta:Be(Ke({}).passthrough())}).passthrough(),Ct=kt.extend({text:$e()}),Dt=$e().refine(e=>{try{return atob(e),!0}catch(e){return!1}},{message:"Invalid Base64 string"}),Ot=kt.extend({blob:Dt}),At=ft.extend({uri:$e(),description:Be($e()),mimeType:Be($e()),icons:Be(Fe(pt)),_meta:Be(Ke({}).passthrough())}),xt=ft.extend({uriTemplate:$e(),description:Be($e()),mimeType:Be($e()),_meta:Be(Ke({}).passthrough())}),Tt=Et.extend({method:Ve("resources/list")}),Rt=It.extend({resources:Fe(At)}),$t=Et.extend({method:Ve("resources/templates/list")}),jt=It.extend({resourceTemplates:Fe(xt)}),Nt=Xe.extend({method:Ve("resources/read"),params:Ye.extend({uri:$e()})}),Mt=rt.extend({contents:Fe(qe([Ct,Ot]))}),Ft=tt.extend({method:Ve("notifications/resources/list_changed")}),Kt=Xe.extend({method:Ve("resources/subscribe"),params:Ye.extend({uri:$e()})}),qt=Xe.extend({method:Ve("resources/unsubscribe"),params:Ye.extend({uri:$e()})}),Lt=tt.extend({method:Ve("notifications/resources/updated"),params:et.extend({uri:$e()})}),Ut=Ke({name:$e(),description:Be($e()),required:Be(Ne())}).passthrough(),Vt=ft.extend({description:Be($e()),arguments:Be(Fe(Ut)),icons:Be(Fe(pt)),_meta:Be(Ke({}).passthrough())}),Ht=Et.extend({method:Ve("prompts/list")}),Bt=It.extend({prompts:Fe(Vt)}),zt=Xe.extend({method:Ve("prompts/get"),params:Ye.extend({name:$e(),arguments:Be(Ue($e()))})}),Jt=Ke({type:Ve("text"),text:$e(),_meta:Be(Ke({}).passthrough())}).passthrough(),Wt=Ke({type:Ve("image"),data:Dt,mimeType:$e(),_meta:Be(Ke({}).passthrough())}).passthrough(),Zt=Ke({type:Ve("audio"),data:Dt,mimeType:$e(),_meta:Be(Ke({}).passthrough())}).passthrough(),Qt=Ke({type:Ve("resource"),resource:qe([Ct,Ot]),_meta:Be(Ke({}).passthrough())}).passthrough(),Gt=qe([Jt,Wt,Zt,At.extend({type:Ve("resource_link")}),Qt]),Yt=Ke({role:He(["user","assistant"]),content:Gt}).passthrough(),Xt=rt.extend({description:Be($e()),messages:Fe(Yt)}),er=tt.extend({method:Ve("notifications/prompts/list_changed")}),tr=Ke({title:Be($e()),readOnlyHint:Be(Ne()),destructiveHint:Be(Ne()),idempotentHint:Be(Ne()),openWorldHint:Be(Ne())}).passthrough(),rr=ft.extend({description:Be($e()),inputSchema:Ke({type:Ve("object"),properties:Be(Ke({}).passthrough()),required:Be(Fe($e()))}).passthrough(),outputSchema:Be(Ke({type:Ve("object"),properties:Be(Ke({}).passthrough()),required:Be(Fe($e()))}).passthrough()),annotations:Be(tr),icons:Be(Fe(pt)),_meta:Be(Ke({}).passthrough())}),sr=Et.extend({method:Ve("tools/list")}),ir=It.extend({tools:Fe(rr)}),ar=rt.extend({content:Fe(Gt).default([]),structuredContent:Ke({}).passthrough().optional(),isError:Be(Ne())}),or=(ar.or(rt.extend({toolResult:Me()})),Xe.extend({method:Ve("tools/call"),params:Ye.extend({name:$e(),arguments:Be(Ue(Me()))})})),nr=tt.extend({method:Ve("notifications/tools/list_changed")}),cr=He(["debug","info","notice","warning","error","critical","alert","emergency"]),dr=Xe.extend({method:Ve("logging/setLevel"),params:Ye.extend({level:cr})}),lr=tt.extend({method:Ve("notifications/message"),params:et.extend({level:cr,logger:Be($e()),data:Me()})}),ur=Ke({name:$e().optional()}).passthrough(),hr=Ke({hints:Be(Fe(ur)),costPriority:Be(je().min(0).max(1)),speedPriority:Be(je().min(0).max(1)),intelligencePriority:Be(je().min(0).max(1))}).passthrough(),pr=Ke({role:He(["user","assistant"]),content:qe([Jt,Wt,Zt])}).passthrough(),fr=Xe.extend({method:Ve("sampling/createMessage"),params:Ye.extend({messages:Fe(pr),systemPrompt:Be($e()),includeContext:Be(He(["none","thisServer","allServers"])),temperature:Be(je()),maxTokens:je().int(),stopSequences:Be(Fe($e())),metadata:Be(Ke({}).passthrough()),modelPreferences:Be(hr)})}),gr=rt.extend({model:$e(),stopReason:Be(He(["endTurn","stopSequence","maxTokens"]).or($e())),role:He(["user","assistant"]),content:Le("type",[Jt,Wt,Zt])}),mr=qe([Ke({type:Ve("boolean"),title:Be($e()),description:Be($e()),default:Be(Ne())}).passthrough(),Ke({type:Ve("string"),title:Be($e()),description:Be($e()),minLength:Be(je()),maxLength:Be(je()),format:Be(He(["email","uri","date","date-time"]))}).passthrough(),Ke({type:He(["number","integer"]),title:Be($e()),description:Be($e()),minimum:Be(je()),maximum:Be(je())}).passthrough(),Ke({type:Ve("string"),title:Be($e()),description:Be($e()),enum:Fe($e()),enumNames:Be(Fe($e()))}).passthrough()]),vr=Xe.extend({method:Ve("elicitation/create"),params:Ye.extend({message:$e(),requestedSchema:Ke({type:Ve("object"),properties:Ue($e(),mr),required:Be(Fe($e()))}).passthrough()})}),yr=rt.extend({action:He(["accept","decline","cancel"]),content:Be(Ue($e(),Me()))}),_r=Ke({type:Ve("ref/resource"),uri:$e()}).passthrough(),wr=Ke({type:Ve("ref/prompt"),name:$e()}).passthrough(),br=Xe.extend({method:Ve("completion/complete"),params:Ye.extend({ref:qe([wr,_r]),argument:Ke({name:$e(),value:$e()}).passthrough(),context:Be(Ke({arguments:Be(Ue($e(),$e()))}))})}),Sr=rt.extend({completion:Ke({values:Fe($e()).max(100),total:Be(je().int()),hasMore:Be(Ne())}).passthrough()}),Pr=Ke({uri:$e().startsWith("file://"),name:Be($e()),_meta:Be(Ke({}).passthrough())}).passthrough(),Er=Xe.extend({method:Ve("roots/list")}),Ir=rt.extend({roots:Fe(Pr)}),kr=tt.extend({method:Ve("notifications/roots/list_changed")});qe([bt,vt,br,dr,zt,Ht,Tt,$t,Nt,Kt,qt,or,sr]),qe([ht,Pt,wt,kr]),qe([ut,gr,yr,Ir]),qe([bt,fr,vr,Er]),qe([ht,Pt,lr,Lt,Ft,nr,er]),qe([ut,_t,Sr,Xt,Bt,Rt,jt,Mt,ar,ir]);class Cr extends Error{constructor(e,t,r){super(`MCP error ${e}: ${t}`),this.code=e,this.data=r,this.name="McpError"}}class Dr{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;const e=this._buffer.indexOf("\n");if(-1===e)return null;const t=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),function(e){return lt.parse(JSON.parse(e))}(t)}clear(){this._buffer=void 0}}class Or{constructor(t=e.stdin,r=e.stdout){this._stdin=t,this._stdout=r,this._readBuffer=new Dr,this._started=!1,this._ondata=e=>{this._readBuffer.append(e),this.processReadBuffer()},this._onerror=e=>{var t;null===(t=this.onerror)||void 0===t||t.call(this,e)}}async start(){if(this._started)throw new 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(var e,t;;)try{const t=this._readBuffer.readMessage();if(null===t)break;null===(e=this.onmessage)||void 0===e||e.call(this,t)}catch(e){null===(t=this.onerror)||void 0===t||t.call(this,e)}}async close(){var e;this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),0===this._stdin.listenerCount("data")&&this._stdin.pause(),this._readBuffer.clear(),null===(e=this.onclose)||void 0===e||e.call(this)}send(e){return new Promise(t=>{const r=function(e){return JSON.stringify(e)+"\n"}(e);this._stdout.write(r)?t():this._stdout.once("drain",t)})}}class Ar{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this.setNotificationHandler(ht,e=>{const t=this._requestHandlerAbortControllers.get(e.params.requestId);null==t||t.abort(e.params.reason)}),this.setNotificationHandler(Pt,e=>{this._onprogress(e)}),this.setRequestHandler(bt,e=>({}))}_setupTimeout(e,t,r,s,i=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(s,t),startTime:Date.now(),timeout:t,maxTotalTimeout:r,resetTimeoutOnProgress:i,onTimeout:s})}_resetTimeout(e){const t=this._timeoutInfo.get(e);if(!t)return!1;const r=Date.now()-t.startTime;if(t.maxTotalTimeout&&r>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),new Cr(ct.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:r});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){const t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){var t,r,s;this._transport=e;const i=null===(t=this.transport)||void 0===t?void 0:t.onclose;this._transport.onclose=()=>{null==i||i(),this._onclose()};const a=null===(r=this.transport)||void 0===r?void 0:r.onerror;this._transport.onerror=e=>{null==a||a(e),this._onerror(e)};const o=null===(s=this._transport)||void 0===s?void 0:s.onmessage;this._transport.onmessage=(e,t)=>{var r;null==o||o(e,t),nt(e)||(r=e,dt.safeParse(r).success)?this._onresponse(e):(e=>it.safeParse(e).success)(e)?this._onrequest(e,t):(e=>at.safeParse(e).success)(e)?this._onnotification(e):this._onerror(new Error(`Unknown message type: ${JSON.stringify(e)}`))},await this._transport.start()}_onclose(){var e;const t=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear(),this._transport=void 0,null===(e=this.onclose)||void 0===e||e.call(this);const r=new Cr(ct.ConnectionClosed,"Connection closed");for(const e of t.values())e(r)}_onerror(e){var t;null===(t=this.onerror)||void 0===t||t.call(this,e)}_onnotification(e){var t;const r=null!==(t=this._notificationHandlers.get(e.method))&&void 0!==t?t:this.fallbackNotificationHandler;void 0!==r&&Promise.resolve().then(()=>r(e)).catch(e=>this._onerror(new Error(`Uncaught error in notification handler: ${e}`)))}_onrequest(e,t){var r,s;const i=null!==(r=this._requestHandlers.get(e.method))&&void 0!==r?r:this.fallbackRequestHandler,a=this._transport;if(void 0===i)return void(null==a||a.send({jsonrpc:"2.0",id:e.id,error:{code:ct.MethodNotFound,message:"Method not found"}}).catch(e=>this._onerror(new Error(`Failed to send an error response: ${e}`))));const o=new AbortController;this._requestHandlerAbortControllers.set(e.id,o);const n={signal:o.signal,sessionId:null==a?void 0:a.sessionId,_meta:null===(s=e.params)||void 0===s?void 0:s._meta,sendNotification:t=>this.notification(t,{relatedRequestId:e.id}),sendRequest:(t,r,s)=>this.request(t,r,{...s,relatedRequestId:e.id}),authInfo:null==t?void 0:t.authInfo,requestId:e.id,requestInfo:null==t?void 0:t.requestInfo};Promise.resolve().then(()=>i(e,n)).then(t=>{if(!o.signal.aborted)return null==a?void 0:a.send({result:t,jsonrpc:"2.0",id:e.id})},t=>{var r;if(!o.signal.aborted)return null==a?void 0:a.send({jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(t.code)?t.code:ct.InternalError,message:null!==(r=t.message)&&void 0!==r?r:"Internal error"}})}).catch(e=>this._onerror(new Error(`Failed to send response: ${e}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){const{progressToken:t,...r}=e.params,s=Number(t),i=this._progressHandlers.get(s);if(!i)return void this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));const a=this._responseHandlers.get(s),o=this._timeoutInfo.get(s);if(o&&a&&o.resetTimeoutOnProgress)try{this._resetTimeout(s)}catch(e){return void a(e)}i(r)}_onresponse(e){const t=Number(e.id),r=this._responseHandlers.get(t);void 0!==r?(this._responseHandlers.delete(t),this._progressHandlers.delete(t),this._cleanupTimeout(t),nt(e)?r(e):r(new Cr(e.error.code,e.error.message,e.error.data))):this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`))}get transport(){return this._transport}async close(){var e;await(null===(e=this._transport)||void 0===e?void 0:e.close())}request(e,t,r){const{relatedRequestId:s,resumptionToken:i,onresumptiontoken:a}=null!=r?r:{};return new Promise((o,n)=>{var c,d,l,u,h,p;if(!this._transport)return void n(new Error("Not connected"));!0===(null===(c=this._options)||void 0===c?void 0:c.enforceStrictCapabilities)&&this.assertCapabilityForMethod(e.method),null===(d=null==r?void 0:r.signal)||void 0===d||d.throwIfAborted();const f=this._requestMessageId++,g={...e,jsonrpc:"2.0",id:f};(null==r?void 0:r.onprogress)&&(this._progressHandlers.set(f,r.onprogress),g.params={...e.params,_meta:{...(null===(l=e.params)||void 0===l?void 0:l._meta)||{},progressToken:f}});const m=e=>{var t;this._responseHandlers.delete(f),this._progressHandlers.delete(f),this._cleanupTimeout(f),null===(t=this._transport)||void 0===t||t.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:f,reason:String(e)}},{relatedRequestId:s,resumptionToken:i,onresumptiontoken:a}).catch(e=>this._onerror(new Error(`Failed to send cancellation: ${e}`))),n(e)};this._responseHandlers.set(f,e=>{var s;if(!(null===(s=null==r?void 0:r.signal)||void 0===s?void 0:s.aborted)){if(e instanceof Error)return n(e);try{const r=t.parse(e.result);o(r)}catch(e){n(e)}}}),null===(u=null==r?void 0:r.signal)||void 0===u||u.addEventListener("abort",()=>{var e;m(null===(e=null==r?void 0:r.signal)||void 0===e?void 0:e.reason)});const v=null!==(h=null==r?void 0:r.timeout)&&void 0!==h?h:6e4;this._setupTimeout(f,v,null==r?void 0:r.maxTotalTimeout,()=>m(new Cr(ct.RequestTimeout,"Request timed out",{timeout:v})),null!==(p=null==r?void 0:r.resetTimeoutOnProgress)&&void 0!==p&&p),this._transport.send(g,{relatedRequestId:s,resumptionToken:i,onresumptiontoken:a}).catch(e=>{this._cleanupTimeout(f),n(e)})})}async notification(e,t){var r,s;if(!this._transport)throw new Error("Not connected");if(this.assertNotificationCapability(e.method),(null!==(s=null===(r=this._options)||void 0===r?void 0:r.debouncedNotificationMethods)&&void 0!==s?s:[]).includes(e.method)&&!e.params&&!(null==t?void 0:t.relatedRequestId)){if(this._pendingDebouncedNotifications.has(e.method))return;return this._pendingDebouncedNotifications.add(e.method),void Promise.resolve().then(()=>{var r;if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;const s={...e,jsonrpc:"2.0"};null===(r=this._transport)||void 0===r||r.send(s,t).catch(e=>this._onerror(e))})}const i={...e,jsonrpc:"2.0"};await this._transport.send(i,t)}setRequestHandler(e,t){const r=e.shape.method.value;this.assertRequestHandlerCapability(r),this._requestHandlers.set(r,(r,s)=>Promise.resolve(t(e.parse(r),s)))}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t){this._notificationHandlers.set(e.shape.method.value,r=>Promise.resolve(t(e.parse(r))))}removeNotificationHandler(e){this._notificationHandlers.delete(e)}}var xr=r(53084);class Tr extends Ar{constructor(e,t){var r;super(t),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(cr.options.map((e,t)=>[e,t])),this.isMessageIgnored=(e,t)=>{const r=this._loggingLevels.get(t);return!!r&&this.LOG_LEVEL_SEVERITY.get(e)<this.LOG_LEVEL_SEVERITY.get(r)},this._capabilities=null!==(r=null==t?void 0:t.capabilities)&&void 0!==r?r:{},this._instructions=null==t?void 0:t.instructions,this.setRequestHandler(vt,e=>this._oninitialize(e)),this.setNotificationHandler(wt,()=>{var e;return null===(e=this.oninitialized)||void 0===e?void 0:e.call(this)}),this._capabilities.logging&&this.setRequestHandler(dr,async(e,t)=>{var r;const s=t.sessionId||(null===(r=t.requestInfo)||void 0===r?void 0:r.headers["mcp-session-id"])||void 0,{level:i}=e.params,a=cr.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");var t,r;this._capabilities=(t=this._capabilities,r=e,Object.entries(r).reduce((e,[t,r])=>(e[t]=r&&"object"==typeof r&&e[t]?{...e[t],...r}:r,e),{...t}))}assertCapabilityForMethod(e){var t,r,s;switch(e){case"sampling/createMessage":if(!(null===(t=this._clientCapabilities)||void 0===t?void 0:t.sampling))throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!(null===(r=this._clientCapabilities)||void 0===r?void 0:r.elicitation))throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!(null===(s=this._clientCapabilities)||void 0===s?void 0:s.roots))throw new Error(`Client does not support listing roots (required for ${e})`)}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`)}}assertRequestHandlerCapability(e){switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Server does not support sampling (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new 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 new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`)}}async _oninitialize(e){const t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:Je.includes(t)?t:ze,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"},ut)}async createMessage(e,t){return this.request({method:"sampling/createMessage",params:e},gr,t)}async elicitInput(e,t){const r=await this.request({method:"elicitation/create",params:e},yr,t);if("accept"===r.action&&r.content)try{const t=new xr,s=t.compile(e.requestedSchema);if(!s(r.content))throw new Cr(ct.InvalidParams,`Elicitation response content does not match requested schema: ${t.errorsText(s.errors)}`)}catch(e){if(e instanceof Cr)throw e;throw new Cr(ct.InternalError,`Error validating elicitation response: ${e}`)}return r}async listRoots(e,t){return this.request({method:"roots/list",params:e},Ir,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"})}}const Rr=require("crypto"),$r=require("node:crypto"),jr=require("node:buffer");const Nr=e=>jr.Buffer.from(e).toString("base64url"),Mr=require("node:util");class Fr extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(e,t){super(e,t),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}}class Kr extends Fr{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"}class qr extends Fr{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"}class Lr extends Fr{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"}Symbol.asyncIterator;const Ur=$r.webcrypto,Vr=e=>Mr.types.isCryptoKey(e),Hr=e=>Mr.types.isKeyObject(e);function Br(e,t,...r){if((r=r.filter(Boolean)).length>2){const t=r.pop();e+=`one of type ${r.join(", ")}, or ${t}.`}else 2===r.length?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return null==t?e+=` Received ${t}`:"function"==typeof t&&t.name?e+=` Received function ${t.name}`:"object"==typeof t&&null!=t&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}const zr=(e,...t)=>Br("Key must be ",e,...t);function Jr(e,t,...r){return Br(`Key for the ${e} algorithm must be `,t,...r)}const Wr=e=>Hr(e)||Vr(e),Zr=["KeyObject"];function Qr(e){if("object"!=typeof(t=e)||null===t||"[object Object]"!==Object.prototype.toString.call(e))return!1;var t;if(null===Object.getPrototypeOf(e))return!0;let r=e;for(;null!==Object.getPrototypeOf(r);)r=Object.getPrototypeOf(r);return Object.getPrototypeOf(e)===r}function Gr(e){return Qr(e)&&"string"==typeof e.kty}(globalThis.CryptoKey||Ur?.CryptoKey)&&Zr.push("CryptoKey"),new WeakMap;const Yr=(e,t)=>{let r;if(Vr(e))r=$r.KeyObject.from(e);else{if(!Hr(e)){if(Gr(e))return e.crv;throw new TypeError(zr(e,...Zr))}r=e}if("secret"===r.type)throw new TypeError('only "private" or "public" type keys can be used for this operation');switch(r.asymmetricKeyType){case"ed25519":case"ed448":return`Ed${r.asymmetricKeyType.slice(2)}`;case"x25519":case"x448":return`X${r.asymmetricKeyType.slice(1)}`;case"ec":{const e=r.asymmetricKeyDetails.namedCurve;return t?e:(e=>{switch(e){case"prime256v1":return"P-256";case"secp384r1":return"P-384";case"secp521r1":return"P-521";case"secp256k1":return"secp256k1";default:throw new Kr("Unsupported key curve for this operation")}})(e)}default:throw new TypeError("Invalid asymmetric key type for this operation")}},Xr=(e,t)=>{let r;try{r=e instanceof $r.KeyObject?e.asymmetricKeyDetails?.modulusLength:Buffer.from(e.n,"base64url").byteLength<<3}catch{}if("number"!=typeof r||r<2048)throw new TypeError(`${t} requires key modulusLength to be 2048 bits or larger`)},es=new Map([["ES256","P-256"],["ES256K","secp256k1"],["ES384","P-384"],["ES512","P-521"]]);function ts(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function rs(e,t){return e.name===t}function ss(e){return parseInt(e.name.slice(4),10)}function is(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!rs(e.algorithm,"HMAC"))throw ts("HMAC");const r=parseInt(t.slice(2),10);if(ss(e.algorithm.hash)!==r)throw ts(`SHA-${r}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!rs(e.algorithm,"RSASSA-PKCS1-v1_5"))throw ts("RSASSA-PKCS1-v1_5");const r=parseInt(t.slice(2),10);if(ss(e.algorithm.hash)!==r)throw ts(`SHA-${r}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!rs(e.algorithm,"RSA-PSS"))throw ts("RSA-PSS");const r=parseInt(t.slice(2),10);if(ss(e.algorithm.hash)!==r)throw ts(`SHA-${r}`,"algorithm.hash");break}case"EdDSA":if("Ed25519"!==e.algorithm.name&&"Ed448"!==e.algorithm.name)throw ts("Ed25519 or Ed448");break;case"Ed25519":if(!rs(e.algorithm,"Ed25519"))throw ts("Ed25519");break;case"ES256":case"ES384":case"ES512":{if(!rs(e.algorithm,"ECDSA"))throw ts("ECDSA");const r=function(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}(t);if(e.algorithm.namedCurve!==r)throw ts(r,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}!function(e,t){if(t.length&&!t.some(t=>e.usages.includes(t))){let e="CryptoKey does not support this operation, its usages must include ";if(t.length>2){const r=t.pop();e+=`one of ${t.join(", ")}, or ${r}.`}else 2===t.length?e+=`one of ${t[0]} or ${t[1]}.`:e+=`${t[0]}.`;throw new TypeError(e)}}(e,r)}const as=(0,Mr.promisify)($r.sign),os=new TextEncoder,ns=new TextDecoder;const cs=e=>e?.[Symbol.toStringTag],ds=(e,t,r)=>{if(void 0!==t.use&&"sig"!==t.use)throw new TypeError("Invalid key for this operation, when present its use must be sig");if(void 0!==t.key_ops&&!0!==t.key_ops.includes?.(r))throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${r}`);if(void 0!==t.alg&&t.alg!==e)throw new TypeError(`Invalid key for this operation, when present its alg must be ${e}`);return!0};function ls(e,t,r,s){t.startsWith("HS")||"dir"===t||t.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(t)?((e,t,r,s)=>{if(!(t instanceof Uint8Array)){if(s&&Gr(t)){if(function(e){return Gr(e)&&"oct"===e.kty&&"string"==typeof e.k}(t)&&ds(e,t,r))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!Wr(t))throw new TypeError(Jr(e,t,...Zr,"Uint8Array",s?"JSON Web Key":null));if("secret"!==t.type)throw new TypeError(`${cs(t)} instances for symmetric algorithms must be of type "secret"`)}})(t,r,s,e):((e,t,r,s)=>{if(s&&Gr(t))switch(r){case"sign":if(function(e){return"oct"!==e.kty&&"string"==typeof e.d}(t)&&ds(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(function(e){return"oct"!==e.kty&&void 0===e.d}(t)&&ds(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!Wr(t))throw new TypeError(Jr(e,t,...Zr,s?"JSON Web Key":null));if("secret"===t.type)throw new TypeError(`${cs(t)} instances for asymmetric algorithms must not be of type "secret"`);if("sign"===r&&"public"===t.type)throw new TypeError(`${cs(t)} instances for asymmetric algorithm signing must be of type "private"`);if("decrypt"===r&&"public"===t.type)throw new TypeError(`${cs(t)} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&"verify"===r&&"private"===t.type)throw new TypeError(`${cs(t)} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&"encrypt"===r&&"private"===t.type)throw new TypeError(`${cs(t)} instances for asymmetric algorithm encryption must be of type "public"`)})(t,r,s,e)}ls.bind(void 0,!1);const us=ls.bind(void 0,!0);class hs{_payload;_protectedHeader;_unprotectedHeader;constructor(e){if(!(e instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this._payload=e}setProtectedHeader(e){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=e,this}setUnprotectedHeader(e){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=e,this}async sign(e,t){if(!this._protectedHeader&&!this._unprotectedHeader)throw new qr("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!((...e)=>{const t=e.filter(Boolean);if(0===t.length||1===t.length)return!0;let r;for(const e of t){const t=Object.keys(e);if(r&&0!==r.size)for(const e of t){if(r.has(e))return!1;r.add(e)}else r=new Set(t)}return!0})(this._protectedHeader,this._unprotectedHeader))throw new qr("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const r={...this._protectedHeader,...this._unprotectedHeader};let s=!0;if(function(e,t,r,s,i){if(void 0!==i.crit&&void 0===s?.crit)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!s||void 0===s.crit)return new Set;if(!Array.isArray(s.crit)||0===s.crit.length||s.crit.some(e=>"string"!=typeof e||0===e.length))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let a;a=void 0!==r?new Map([...Object.entries(r),...t.entries()]):t;for(const t of s.crit){if(!a.has(t))throw new Kr(`Extension Header Parameter "${t}" is not recognized`);if(void 0===i[t])throw new e(`Extension Header Parameter "${t}" is missing`);if(a.get(t)&&void 0===s[t])throw new e(`Extension Header Parameter "${t}" MUST be integrity protected`)}return new Set(s.crit)}(qr,new Map([["b64",!0]]),t?.crit,this._protectedHeader,r).has("b64")&&(s=this._protectedHeader.b64,"boolean"!=typeof s))throw new qr('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:i}=r;if("string"!=typeof i||!i)throw new qr('JWS "alg" (Algorithm) Header Parameter missing or invalid');us(i,e,"sign");let a,o=this._payload;s&&(o=os.encode(Nr(o))),a=this._protectedHeader?os.encode(Nr(JSON.stringify(this._protectedHeader))):os.encode("");const n=function(...e){const t=e.reduce((e,{length:t})=>e+t,0),r=new Uint8Array(t);let s=0;for(const t of e)r.set(t,s),s+=t.length;return r}(a,os.encode("."),o),c=await(async(e,t,r)=>{const s=function(e,t){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(zr(t,...Zr));return(0,$r.createSecretKey)(t)}if(t instanceof $r.KeyObject)return t;if(Vr(t))return is(t,e,"sign"),$r.KeyObject.from(t);if(Gr(t))return e.startsWith("HS")?(0,$r.createSecretKey)(Buffer.from(t.k,"base64url")):t;throw new TypeError(zr(t,...Zr,"Uint8Array","JSON Web Key"))}(e,t);if(e.startsWith("HS")){const t=$r.createHmac(function(e){switch(e){case"HS256":return"sha256";case"HS384":return"sha384";case"HS512":return"sha512";default:throw new Kr(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}(e),s);return t.update(r),t.digest()}return as(function(e){switch(e){case"PS256":case"RS256":case"ES256":case"ES256K":return"sha256";case"PS384":case"RS384":case"ES384":return"sha384";case"PS512":case"RS512":case"ES512":return"sha512";case"Ed25519":case"EdDSA":return;default:throw new Kr(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}(e),r,function(e,t){let r,s,i,a;if(t instanceof $r.KeyObject)r=t.asymmetricKeyType,s=t.asymmetricKeyDetails;else switch(i=!0,t.kty){case"RSA":r="rsa";break;case"EC":r="ec";break;case"OKP":if("Ed25519"===t.crv){r="ed25519";break}if("Ed448"===t.crv){r="ed448";break}throw new TypeError("Invalid key for this operation, its crv must be Ed25519 or Ed448");default:throw new TypeError("Invalid key for this operation, its kty must be RSA, OKP, or EC")}switch(e){case"Ed25519":if("ed25519"!==r)throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ed25519");break;case"EdDSA":if(!["ed25519","ed448"].includes(r))throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ed25519 or ed448");break;case"RS256":case"RS384":case"RS512":if("rsa"!==r)throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa");Xr(t,e);break;case"PS256":case"PS384":case"PS512":if("rsa-pss"===r){const{hashAlgorithm:t,mgf1HashAlgorithm:r,saltLength:i}=s,a=parseInt(e.slice(-3),10);if(void 0!==t&&(t!==`sha${a}`||r!==t))throw new TypeError(`Invalid key for this operation, its RSA-PSS parameters do not meet the requirements of "alg" ${e}`);if(void 0!==i&&i>a>>3)throw new TypeError(`Invalid key for this operation, its RSA-PSS parameter saltLength does not meet the requirements of "alg" ${e}`)}else if("rsa"!==r)throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa or rsa-pss");Xr(t,e),a={padding:$r.constants.RSA_PKCS1_PSS_PADDING,saltLength:$r.constants.RSA_PSS_SALTLEN_DIGEST};break;case"ES256":case"ES256K":case"ES384":case"ES512":{if("ec"!==r)throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ec");const s=Yr(t),i=es.get(e);if(s!==i)throw new TypeError(`Invalid key curve for the algorithm, its curve must be ${i}, got ${s}`);a={dsaEncoding:"ieee-p1363"};break}default:throw new Kr(`alg ${e} is not supported either by JOSE or your javascript runtime`)}return i?{format:"jwk",key:t,...a}:a?{...a,key:t}:t}(e,s))})(i,e,n),d={signature:Nr(c),payload:""};return s&&(d.payload=ns.decode(o)),this._unprotectedHeader&&(d.header=this._unprotectedHeader),this._protectedHeader&&(d.protected=ns.decode(a)),d}}class ps{_flattened;constructor(e){this._flattened=new hs(e)}setProtectedHeader(e){return this._flattened.setProtectedHeader(e),this}async sign(e,t){const r=await this._flattened.sign(e,t);if(void 0===r.payload)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${r.protected}.${r.payload}.${r.signature}`}}const fs=e=>Math.floor(e.getTime()/1e3),gs=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,ms=e=>{const t=gs.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");const r=parseFloat(t[2]);let s;switch(t[3].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":s=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":s=Math.round(60*r);break;case"hour":case"hours":case"hr":case"hrs":case"h":s=Math.round(3600*r);break;case"day":case"days":case"d":s=Math.round(86400*r);break;case"week":case"weeks":case"w":s=Math.round(604800*r);break;default:s=Math.round(31557600*r)}return"-"===t[1]||"ago"===t[4]?-s:s};function vs(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}class ys{_payload;constructor(e={}){if(!Qr(e))throw new TypeError("JWT Claims Set MUST be an object");this._payload=e}setIssuer(e){return this._payload={...this._payload,iss:e},this}setSubject(e){return this._payload={...this._payload,sub:e},this}setAudience(e){return this._payload={...this._payload,aud:e},this}setJti(e){return this._payload={...this._payload,jti:e},this}setNotBefore(e){return"number"==typeof e?this._payload={...this._payload,nbf:vs("setNotBefore",e)}:e instanceof Date?this._payload={...this._payload,nbf:vs("setNotBefore",fs(e))}:this._payload={...this._payload,nbf:fs(new Date)+ms(e)},this}setExpirationTime(e){return"number"==typeof e?this._payload={...this._payload,exp:vs("setExpirationTime",e)}:e instanceof Date?this._payload={...this._payload,exp:vs("setExpirationTime",fs(e))}:this._payload={...this._payload,exp:fs(new Date)+ms(e)},this}setIssuedAt(e){return void 0===e?this._payload={...this._payload,iat:fs(new Date)}:e instanceof Date?this._payload={...this._payload,iat:vs("setIssuedAt",fs(e))}:this._payload="string"==typeof e?{...this._payload,iat:vs("setIssuedAt",fs(new Date)+ms(e))}:{...this._payload,iat:vs("setIssuedAt",e)},this}}class _s extends ys{_protectedHeader;setProtectedHeader(e){return this._protectedHeader=e,this}async sign(e,t){const r=new ps(os.encode(JSON.stringify(this._payload)));if(r.setProtectedHeader(this._protectedHeader),Array.isArray(this._protectedHeader?.crit)&&this._protectedHeader.crit.includes("b64")&&!1===this._protectedHeader.b64)throw new Lr("JWTs MUST NOT use unencoded payload");return r.sign(e,t)}}var ws=r(77753),bs=r(95277);const Ss=require("fs");var Ps=r(16928);class Es extends bs.CryptoProvider{async sign(e,t){const r=Buffer.from(t,"base64"),s=64===r.length?r.subarray(0,32):r,i=Buffer.concat([Buffer.from("302e020100300506032b657004220420","hex"),s]),a=Rr.createPrivateKey({key:i,format:"der",type:"pkcs8"}),o=Rr.sign(null,Buffer.from(e),a);return new Uint8Array(o)}async verify(e,t,r){try{const s=Buffer.from(r,"base64"),i=Buffer.concat([Buffer.from("302a300506032b6570032100","hex"),s]),a=Rr.createPublicKey({key:i,format:"der",type:"spki"});return Rr.verify(null,Buffer.from(e),a,Buffer.from(t))}catch{return!1}}async generateKeyPair(){const{publicKey:e,privateKey:t}=Rr.generateKeyPairSync("ed25519",{publicKeyEncoding:{type:"spki",format:"der"},privateKeyEncoding:{type:"pkcs8",format:"der"}}),r=t.subarray(16,48),s=e.subarray(12,44);return{privateKey:r.toString("base64"),publicKey:s.toString("base64")}}async hash(e){const t=Rr.createHash("sha256").update(Buffer.from(e)).digest();return new Uint8Array(t)}async randomBytes(e){return new Uint8Array(Rr.randomBytes(e))}}bs.StorageProvider,bs.IdentityProvider;class Is{async generateProof(e,t,r,s={}){const i=this.generateCanonicalHashes(e,t),a={did:this.identity.did,kid:this.identity.kid,ts:Math.floor(Date.now()/1e3),nonce:r.nonce,audience:r.audience,sessionId:r.sessionId,requestHash:i.requestHash,responseHash:i.responseHash,...s};return{jws:await this.generateJWS(a),meta:a}}generateCanonicalHashes(e,t){const r={method:e.method,...e.params&&{params:e.params}},s=t.data;return{requestHash:this.generateSHA256Hash(r),responseHash:this.generateSHA256Hash(s)}}generateSHA256Hash(e){const t=this.canonicalizeJSON(e);return`sha256:${(0,Rr.createHash)("sha256").update(t,"utf8").digest("hex")}`}canonicalizeJSON(e){return(0,ws.d)(e)}async generateJWS(e){try{const t=this.formatPrivateKeyAsPEM(this.identity.privateKey),r=await async function(e){if("string"!=typeof e||0!==e.indexOf("-----BEGIN PRIVATE KEY-----"))throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return t=e,(0,$r.createPrivateKey)({key:jr.Buffer.from(t.replace(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g,""),"base64"),type:"pkcs8",format:"der"});var t}(t),s={aud:e.audience,sub:e.did,iss:e.did,requestHash:e.requestHash,responseHash:e.responseHash,ts:e.ts,nonce:e.nonce,sessionId:e.sessionId,...e.scopeId&&{scopeId:e.scopeId},...e.delegationRef&&{delegationRef:e.delegationRef},...e.clientDid&&{clientDid:e.clientDid}};return await new _s(s).setProtectedHeader({alg:"EdDSA",kid:this.identity.kid}).sign(r)}catch(e){throw new Error(`Failed to generate JWS: ${e instanceof Error?e.message:"Unknown error"}`)}}formatPrivateKeyAsPEM(e){const t=Buffer.from(e,"base64"),r=Buffer.from([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]),s=Buffer.concat([r,t.subarray(0,32)]).toString("base64");return"-----BEGIN PRIVATE KEY-----\n"+(s.match(/.{1,64}/g)?.join("\n")||s)+"\n-----END PRIVATE KEY-----"}async verifyProof(e,t,r){try{const s=this.generateCanonicalHashes(t,r);if(e.meta.requestHash!==s.requestHash||e.meta.responseHash!==s.responseHash)return!1;const i=this.base64PublicKeyToJWK(this.identity.publicKey),a=new Es,o=new bs.CryptoService(a);return await o.verifyJWS(e.jws,i,{expectedKid:this.identity.kid,alg:"EdDSA"})}catch(e){return console.error("[ProofGenerator] Proof verification error:",e),!1}}base64PublicKeyToJWK(e){const t=Buffer.from(e,"base64");if(32!==t.length)throw new Error(`Invalid Ed25519 public key length: ${t.length}`);return{kty:"OKP",crv:"Ed25519",x:Buffer.from(t).toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,""),kid:this.identity.kid}}constructor(e){var t,r;r=void 0,(t="identity")in this?Object.defineProperty(this,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):this[t]=r,this.identity=e}}const ks=require("fs/promises"),Cs=(0,Mr.promisify)($r.generateKeyPair);function Ds(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}r(75306);class Os{async ensureIdentity(){return this.cachedIdentity||("development"===this.config.environment?this.cachedIdentity=await this.loadOrGenerateDevIdentity():this.cachedIdentity=await this.loadProdIdentity()),this.cachedIdentity}async loadOrGenerateDevIdentity(){const e=this.config.devIdentityPath;try{if((0,Ss.existsSync)(e)){const t=await(0,ks.readFile)(e,"utf-8"),r=JSON.parse(t);let s=r.kid||r.keyId;if(r.keyId&&!r.kid&&s.startsWith("key-")){s=this.generateMultibaseKid(r.publicKey);const e={did:r.did,kid:s,privateKey:r.privateKey,publicKey:r.publicKey,createdAt:r.createdAt,lastRotated:r.lastRotated};return await this.saveDevIdentity(e),console.error(`✅ Migrated identity to new multibase kid format: ${s}`),e}return{did:r.did,kid:s,privateKey:r.privateKey,publicKey:r.publicKey,createdAt:r.createdAt,lastRotated:r.lastRotated}}}catch(t){console.warn(`Warning: Could not load identity from ${e}, generating new one`,t instanceof Error?t.message:t)}return await this.generateDevIdentity()}async generateDevIdentity(){const e=await async function(e,t){return async function(e,t){switch(e){case"RS256":case"RS384":case"RS512":case"PS256":case"PS384":case"PS512":case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":case"RSA1_5":{const e=t?.modulusLength??2048;if("number"!=typeof e||e<2048)throw new Kr("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return await Cs("rsa",{modulusLength:e,publicExponent:65537})}case"ES256":return Cs("ec",{namedCurve:"P-256"});case"ES256K":return Cs("ec",{namedCurve:"secp256k1"});case"ES384":return Cs("ec",{namedCurve:"P-384"});case"ES512":return Cs("ec",{namedCurve:"P-521"});case"Ed25519":return Cs("ed25519");case"EdDSA":switch(t?.crv){case void 0:case"Ed25519":return Cs("ed25519");case"Ed448":return Cs("ed448");default:throw new Kr("Invalid or unsupported crv option provided, supported values are Ed25519 and Ed448")}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{const e=t?.crv??"P-256";switch(e){case void 0:case"P-256":case"P-384":case"P-521":return Cs("ec",{namedCurve:e});case"X25519":return Cs("x25519");case"X448":return Cs("x448");default:throw new Kr("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448")}}default:throw new Kr('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}}(e,t)}("EdDSA",{crv:"Ed25519"}),t=await async function(e){return(e=>{let t;if(Vr(e)){if(!e.extractable)throw new TypeError("CryptoKey is not extractable");t=$r.KeyObject.from(e)}else{if(!Hr(e)){if(e instanceof Uint8Array)return{kty:"oct",k:Nr(e)};throw new TypeError(zr(e,...Zr,"Uint8Array"))}t=e}if("secret"!==t.type&&!["rsa","ec","ed25519","x25519","ed448","x448"].includes(t.asymmetricKeyType))throw new Kr("Unsupported key asymmetricKeyType");return t.export({format:"jwk"})})(e)}(e.privateKey);if(!t.x||!t.d)throw new Error("Failed to generate Ed25519 keypair");const r=Buffer.from(t.d,"base64url").toString("base64"),s=Buffer.from(t.x,"base64url").toString("base64"),i=this.generateMultibaseKid(s),a={did:`did:web:localhost:3000:agents:${(0,Rr.createHash)("sha256").update(s).digest("hex").substring(0,8)}`,kid:i,privateKey:r,publicKey:s,createdAt:(new Date).toISOString()};return await this.saveDevIdentity(a),a}generateMultibaseKid(e){const t=Buffer.from(e,"base64"),r=Buffer.concat([Buffer.from([237,1]),t]);return`z${this.encodeBase58(r)}`}encodeBase58(e){let t=BigInt("0x"+e.toString("hex")),r="";for(;t>0n;)r="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"[Number(t%58n)]+r,t/=58n;for(let t=0;t<e.length&&0===e[t];t++)r="1"+r;return r}async saveDevIdentity(e){const t=this.config.devIdentityPath;await(0,ks.mkdir)((0,Ps.dirname)(t),{recursive:!0});const r={version:"1.0",did:e.did,kid:e.kid,privateKey:e.privateKey,publicKey:e.publicKey,createdAt:e.createdAt,lastRotated:e.lastRotated};await(0,ks.writeFile)(t,JSON.stringify(r,null,2),{mode:384}),console.error(`✅ Identity saved to ${t}`),console.error(` DID: ${e.did}`),console.error(` Key ID: ${e.kid}`)}async loadProdIdentity(){const e=["AGENT_PRIVATE_KEY","AGENT_KEY_ID","AGENT_DID","KYA_VOUCHED_API_KEY"],t=[],r={};for(const s of e){const e=process.env[s];e?r[s]=e:t.push(s)}if(t.length>0){const e=new Error(`Missing required environment variables for production identity: ${t.join(", ")}\nRequired variables:\n AGENT_PRIVATE_KEY - Base64-encoded Ed25519 private key\n AGENT_KEY_ID - Key identifier\n AGENT_DID - Agent DID\n KYA_VOUCHED_API_KEY - Know-That-AI API key`);throw e.code="XMCP_I_ENOIDENTITY",e}const s=Buffer.from(r.AGENT_PRIVATE_KEY,"base64"),i=(0,Rr.createHash)("sha256").update(s).digest("base64");return{did:r.AGENT_DID,kid:r.AGENT_KEY_ID,privateKey:r.AGENT_PRIVATE_KEY,publicKey:i,createdAt:(new Date).toISOString()}}async validateIdentity(e){try{return!!(e.did&&e.kid&&e.privateKey&&e.publicKey)&&!!e.did.startsWith("did:")&&(Buffer.from(e.privateKey,"base64"),Buffer.from(e.publicKey,"base64"),!0)}catch{return!1}}clearCache(){this.cachedIdentity=void 0}getConfig(){return{...this.config}}constructor(e={environment:"development"}){Ds(this,"config",void 0),Ds(this,"cachedIdentity",void 0);const t=r(16928);let s=e.devIdentityPath||".mcpi/identity.json";t.isAbsolute(s)||(s=t.resolve(process.cwd(),s)),this.config={privacyMode:!1,...e,devIdentityPath:s},this.config.debug&&console.error("[IdentityManager] Constructed with config:",{environment:this.config.environment,devIdentityPath:this.config.devIdentityPath})}}function As(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}new Os;const xs=new class{register(e,t){this.config.set(e,t),this.debug&&console.error(`[ToolProtectionRegistry] Registered protection for tool: ${e}`,t)}registerAll(e){for(const[t,r]of Object.entries(e))this.register(t,r)}get(e){return this.config.get(e)||null}requiresDelegation(e){const t=this.get(e);return t?.requiresDelegation||!1}getRequiredScopes(e){const t=this.get(e);return t?.requiredScopes||[]}setDelegationVerifier(e){this.delegationVerifier=e}setAuthConfig(e){this.authConfig=e}getDelegationVerifier(){return this.delegationVerifier}getAuthConfig(){return this.authConfig}setDebug(e){this.debug=e}setCurrentSession(e){this.currentSession=e}getCurrentSession(){return this.currentSession}getCurrentAgentDid(){return this.currentSession?.agentDid||null}clear(){this.config.clear(),this.delegationVerifier=null,this.authConfig=null,this.currentSession=null}getProtectedTools(){return Array.from(this.config.keys())}constructor(){As(this,"config",new Map),As(this,"delegationVerifier",null),As(this,"authConfig",null),As(this,"debug",!1),As(this,"currentSession",null)}},Ts=require("@kya-os/contracts/runtime");async function Rs(e,t,r,s){const i=await r.resumeTokenStore.create(e,t,{requestedAt:Date.now()}),a=Date.now()+(r.bouncer.resumeTokenTtl||6e5),o=new URL(r.bouncer.authorizationUrl);o.searchParams.set("agent_did",e),o.searchParams.set("scopes",t.join(",")),o.searchParams.set("resume_token",i);const n={title:"Authorization Required",hint:["link","qr"],authorizationCode:i.substring(0,8).toUpperCase(),qrUrl:`https://chart.googleapis.com/chart?cht=qr&chs=300x300&chl=${encodeURIComponent(o.toString())}`};return(0,Ts.createNeedsAuthorizationError)({message:s,authorizationUrl:o.toString(),resumeToken:i,expiresAt:a,scopes:t,display:n})}function $s(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}class js{async has(e,t){const r=t?`nonce:${t}:${e}`:e,s=this.cache.get(r);return!(!s||Date.now()>s.expiresAt&&(this.cache.delete(r),1))}async add(e,t,r){const s=r?`nonce:${r}:${e}`:e,i=this.cache.get(s);if(i&&Date.now()<=i.expiresAt)throw new Error(`Nonce ${e} already exists - potential replay attack`);const a=t<=0?Date.now()-1:Date.now()+1e3*t,o={sessionId:`mem_${Date.now()}_${Math.random().toString(36).substring(2)}`,expiresAt:a};this.cache.set(s,o)}async cleanup(){const e=Date.now(),t=[];for(const[r,s]of this.cache.entries())e>s.expiresAt&&t.push(r);for(const e of t)this.cache.delete(e)}getStats(){const e=Date.now();let t=0;for(const r of this.cache.values())e>r.expiresAt&&t++;return{size:this.cache.size,expired:t}}clear(){this.cache.clear()}destroy(){this.cleanupInterval&&(clearInterval(this.cleanupInterval),this.cleanupInterval=void 0),this.cache.clear()}constructor(e=6e4){$s(this,"cache",new Map),$s(this,"cleanupInterval",void 0),console.warn("⚠️ MemoryNonceCache is not suitable for multi-instance deployments. For production use with multiple instances, configure Redis, DynamoDB, or Cloudflare KV."),this.cleanupInterval=setInterval(()=>{this.cleanup().catch(console.error)},e)}}function Ns(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}class Ms{setServerDid(e){this.config.serverDid=e}async validateHandshake(e){try{const t=Math.floor(Date.now()/1e3),r=Math.abs(t-e.timestamp);if(r>this.config.timestampSkewSeconds)return{success:!1,error:{code:"XMCP_I_EHANDSHAKE",message:`Timestamp outside acceptable range (±${this.config.timestampSkewSeconds}s)`,remediation:`Check NTP sync on client and server. Current server time: ${t}, received: ${e.timestamp}, diff: ${r}s. Adjust XMCP_I_TS_SKEW_SEC if needed.`}};if(await this.config.nonceCache.has(e.nonce,e.agentDid))return{success:!1,error:{code:"XMCP_I_EHANDSHAKE",message:"Nonce already used (replay attack prevention)",remediation:"Generate a new unique nonce for each request"}};const s=60*this.config.sessionTtlMinutes+60;await this.config.nonceCache.add(e.nonce,s,e.agentDid);const i=this.generateSessionId(),a={sessionId:i,audience:e.audience,nonce:e.nonce,timestamp:e.timestamp,createdAt:t,lastActivity:t,ttlMinutes:this.config.sessionTtlMinutes,agentDid:e.agentDid,...this.config.serverDid&&{serverDid:this.config.serverDid}};return this.sessions.set(i,a),{success:!0,session:a}}catch(e){return{success:!1,error:{code:"XMCP_I_EHANDSHAKE",message:`Handshake validation failed: ${e instanceof Error?e.message:"Unknown error"}`}}}}async getSession(e){const t=this.sessions.get(e);if(!t)return null;const r=Math.floor(Date.now()/1e3);return r-t.lastActivity>60*t.ttlMinutes||this.config.absoluteSessionLifetime&&r-t.createdAt>60*this.config.absoluteSessionLifetime?(this.sessions.delete(e),null):(t.lastActivity=r,this.sessions.set(e,t),t)}generateSessionId(){return`sess_${Date.now().toString(36)}_${(0,Rr.randomBytes)(8).toString("hex")}`}static generateNonce(){return(0,Rr.randomBytes)(16).toString("base64url")}async cleanup(){const e=Math.floor(Date.now()/1e3);for(const[t,r]of this.sessions.entries()){let s=e-r.lastActivity>60*r.ttlMinutes;!s&&this.config.absoluteSessionLifetime&&(s=e-r.createdAt>60*this.config.absoluteSessionLifetime),s&&this.sessions.delete(t)}await this.config.nonceCache.cleanup()}getStats(){return{activeSessions:this.sessions.size,config:{timestampSkewSeconds:this.config.timestampSkewSeconds,sessionTtlMinutes:this.config.sessionTtlMinutes,absoluteSessionLifetime:this.config.absoluteSessionLifetime,cacheType:this.config.nonceCache.constructor.name}}}clearSessions(){this.sessions.clear()}constructor(e={}){Ns(this,"config",void 0),Ns(this,"sessions",new Map),this.config={timestampSkewSeconds:parseInt(process.env.XMCP_I_TS_SKEW_SEC||"120"),sessionTtlMinutes:parseInt(process.env.XMCP_I_SESSION_TTL_MIN||"30"),nonceCache:new js,...e},this.config.nonceCache instanceof js&&console.warn("Warning: Using MemoryNonceCache - not suitable for multi-instance deployments. Consider using Redis, DynamoDB, or Cloudflare KV for production.")}}new Ms;const Fs=new(require("async_hooks").AsyncLocalStorage);function Ks(){return(Fs.getStore()?.session)?.agentDid}function qs(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}class Ls{async submit(e){if(0===e.length)return;const t={delegation_id:null,session_id:e[0]?.meta?.sessionId||"unknown",proofs:e},r=await fetch(`${this.apiUrl}/api/v1/bouncer/proofs`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(t)});if(!r.ok){const e=await r.text().catch(()=>"Unable to read error body");throw new Error(`AgentShield proof submission failed: ${r.status} ${r.statusText}\n${e}`)}}constructor(e,t){qs(this,"name","AgentShield"),qs(this,"apiUrl",void 0),qs(this,"apiKey",void 0),this.apiUrl=e.replace(/\/$/,""),this.apiKey=t}}class Us{enqueue(e){this.closed?console.warn("[ProofBatchQueue] Queue is closed, dropping proof"):(this.queue.push(e),this.stats.queued++,this.config.debug&&console.log(`[ProofBatchQueue] Enqueued proof (queue size: ${this.queue.length})`),this.queue.length>=this.config.maxBatchSize&&this.flush())}async flush(){if(0===this.queue.length)return;const e=this.queue.splice(0,this.config.maxBatchSize);this.config.debug&&console.log(`[ProofBatchQueue] Flushing ${e.length} proofs to ${this.config.destinations.length} destinations`);for(const t of this.config.destinations){const r={proofs:e,destination:t,retryCount:0};this.submitBatch(r)}}async submitBatch(e){try{await e.destination.submit(e.proofs),this.stats.submitted+=e.proofs.length,this.stats.batchesSubmitted++,this.config.debug&&console.log(`[ProofBatchQueue] Successfully submitted ${e.proofs.length} proofs to ${e.destination.name}`)}catch(t){if(console.error(`[ProofBatchQueue] Failed to submit to ${e.destination.name}:`,t),e.retryCount<this.config.maxRetries){e.retryCount++;const t=Math.min(1e3*Math.pow(2,e.retryCount-1),16e3);e.nextRetryAt=Date.now()+t,this.pendingBatches.push(e),this.config.debug&&console.log(`[ProofBatchQueue] Scheduling retry ${e.retryCount}/${this.config.maxRetries} in ${t}ms`)}else this.stats.failed+=e.proofs.length,console.error(`[ProofBatchQueue] Max retries exceeded for ${e.destination.name}, dropping ${e.proofs.length} proofs`)}}startFlushTimer(){this.flushTimer=setInterval(()=>{this.queue.length>0&&this.flush()},this.config.flushIntervalMs),"function"==typeof this.flushTimer.unref&&this.flushTimer.unref()}startRetryTimer(){this.retryTimer=setInterval(()=>{const e=Date.now(),t=this.pendingBatches.filter(t=>t.nextRetryAt&&t.nextRetryAt<=e);if(t.length>0){this.pendingBatches=this.pendingBatches.filter(e=>!t.includes(e));for(const e of t)this.submitBatch(e)}},1e3),"function"==typeof this.retryTimer.unref&&this.retryTimer.unref()}async close(){this.closed=!0,this.flushTimer&&clearInterval(this.flushTimer),this.retryTimer&&clearInterval(this.retryTimer),await this.flush();const e=Date.now();for(;this.pendingBatches.length>0&&Date.now()-e<3e4;)await new Promise(e=>setTimeout(e,100));this.pendingBatches.length>0&&console.warn(`[ProofBatchQueue] Closing with ${this.pendingBatches.length} pending batches (timed out)`)}getStats(){return{...this.stats,queueSize:this.queue.length,pendingBatches:this.pendingBatches.length}}constructor(e){qs(this,"queue",[]),qs(this,"pendingBatches",[]),qs(this,"config",void 0),qs(this,"flushTimer",void 0),qs(this,"retryTimer",void 0),qs(this,"closed",!1),qs(this,"stats",{queued:0,submitted:0,failed:0,batchesSubmitted:0}),this.config={destinations:e.destinations,maxBatchSize:e.maxBatchSize||10,flushIntervalMs:e.flushIntervalMs||5e3,maxRetries:e.maxRetries||5,debug:e.debug||!1},this.startFlushTimer(),this.startRetryTimer()}}const Vs="undefined"!=typeof RUNTIME_CONFIG_PATH?RUNTIME_CONFIG_PATH:void 0,Hs=Vs?"string"==typeof Vs?JSON.parse(Vs):Vs:null;let Bs=null;async function zs(e,t,s){if("undefined"!=typeof global){if(global.__MCPI_HANDLERS_REGISTERED__)return s?.debug&&console.error("[MCPI] Handlers already registered, skipping duplicate registration"),e;global.__MCPI_HANDLERS_REGISTERED__=!0}s?.debug&&console.error("[MCPI] Registering handlers for the first time");const i=new Ms;let a=null;if(s?.enabled)try{a=new Os({environment:s.environment||"development",devIdentityPath:s.devIdentityPath,debug:s.debug});const e=await a.ensureIdentity();s.debug&&(console.error(`[MCPI] Identity enabled - DID: ${e.did}`),console.error(`[MCPI] Identity path: ${s.devIdentityPath||".mcpi/identity.json"}`))}catch(e){s?.debug&&console.error("[MCPI] Failed to initialize identity:",e)}await async function(e){if(Bs)return Bs;if(!Hs)return e&&console.error("[MCPI] No runtime config found - proof submission disabled"),null;try{e&&console.error("[MCPI] Loading runtime config from:",Hs);const t=await r(49436)(Hs),s="function"==typeof t.getRuntimeConfig?t.getRuntimeConfig():t.default;if(!s?.proofing?.enabled)return e&&console.error("[MCPI] Proofing is disabled in runtime config"),null;const i=s.proofing;if(!i.batchQueue?.destinations||0===i.batchQueue.destinations.length)return e&&console.error("[MCPI] No proof destinations configured"),null;const a=[];for(const t of i.batchQueue.destinations)"agentshield"===t.type&&(a.push(new Ls(t.apiUrl,t.apiKey)),e&&console.error(`[MCPI] Added AgentShield destination: ${t.apiUrl}`));return 0===a.length?(e&&console.error("[MCPI] No valid proof destinations configured"),null):(Bs=new Us({destinations:a,maxBatchSize:i.batchQueue.maxBatchSize||10,flushIntervalMs:i.batchQueue.flushIntervalMs||5e3,maxRetries:i.batchQueue.maxRetries||3,debug:i.batchQueue.debug||e}),e&&console.error(`[MCPI] ProofBatchQueue initialized (batch: ${i.batchQueue.maxBatchSize}, flush: ${i.batchQueue.flushIntervalMs}ms, destinations: ${a.length})`),Bs)}catch(t){return e&&console.error("[MCPI] Failed to initialize ProofBatchQueue:",t),null}}(s?.debug);const o=[],n=new Map;return t.forEach((e,t)=>{const r=function(e){return(e.split("/").pop()||e).replace(/\.[^/.]+$/,"")}(t),s={name:r,description:"No description provided"};let i={};const{default:a,metadata:c,schema:d}=e;"object"==typeof c&&null!==c&&Object.assign(s,c),function(e){if("object"!=typeof e||null===e)return!1;const t=e;return Object.entries(t).every(([e,t])=>"string"==typeof e&&"object"==typeof t&&null!==t&&"parse"in t&&"function"==typeof t.parse)}(d)?Object.assign(i,d):null!=d&&console.warn(`Invalid schema for tool "${s.name}" at ${t}. Expected Record<string, z.ZodType>`),void 0===s.annotations&&(s.annotations={}),void 0===s.annotations.title&&(s.annotations.title=s.name);const l={name:s.name,description:s.description,inputSchema:{type:"object",properties:Object.fromEntries(Object.entries(i).map(([e,t])=>[e,{type:"string"}]))}};o.push(l),n.set(s.name,a)}),s?.debug&&console.error("[MCPI] About to register handlers (tools/list, tools/call)"),e.setRequestHandler(sr,async e=>({tools:o})),e.setRequestHandler(or,async e=>{const t=e._meta?.sessionId;let r=null;return t&&(r=await i.getSession(t),!r&&s?.debug&&console.error(`[MCPI] Session not found or expired: ${t}`)),o={session:r||void 0,requestId:e._meta?.requestId,startTime:Date.now()},c=async()=>{const{name:t,arguments:r}=e.params,i=n.get(t);if(!i)return{content:[{type:"text",text:`Tool "${t}" not found`}],isError:!0};const o=xs.get(t);if(o?.requiresDelegation){const e=xs.getAuthConfig();if(!xs.getDelegationVerifier()||!e)return s?.debug&&console.error(`[MCPI] Tool "${t}" requires delegation but verifier not configured`),{content:[{type:"text",text:`❌ Tool "${t}" requires delegation verification, but the delegation system is not configured.\n\nTo fix this:\n1. Configure a delegation verifier:\n - MemoryDelegationVerifier (development/testing)\n - KVDelegationVerifier (production with KV store)\n - AgentShieldVerifier (production with AgentShield service)\n\n2. Enable delegation in your runtime config:\n const runtime = new MCPIRuntime({\n delegation: { enabled: true },\n // ... other config\n });\n\n3. Ensure the verifier is initialized before tool execution.\n\n📚 Documentation: https://docs.mcp-i.dev/delegation/setup`}],isError:!0};const r=Ks();if(!r)return s?.debug&&console.error(`[MCPI] Tool "${t}" requires delegation but no agent DID in session`),{content:[{type:"text",text:`❌ Tool "${t}" requires delegation, but no agent identity was found in the current session.\n\nThis usually means one of the following:\n\n1. **No handshake was performed**: The MCP client must send a handshake request before calling protected tools.\n Example handshake:\n {\n "agentDid": "did:key:z6Mk...",\n "nonce": "unique-value",\n "audience": "server-did",\n "timestamp": ${Date.now()}\n }\n\n2. **Handshake missing agentDid**: Ensure the handshake request includes the 'agentDid' field.\n\n3. **Session expired**: The session may have expired. Try performing a new handshake.\n\n4. **Request missing sessionId**: Ensure tool call requests include _meta.sessionId from the handshake response.\n\n📚 Learn more: https://docs.mcp-i.dev/delegation/handshake`}],isError:!0};s?.debug&&console.error(`[MCPI] Tool "${t}" requires delegation - verifying scopes: ${o.requiredScopes?.join(", ")}`);const i=await async function(e,t,r){const s=Date.now();let i,a;if(r.debug&&console.log(`[AuthHandshake] Verifying ${e} for scopes: ${t.join(", ")}`),r.kta&&void 0!==r.bouncer.minReputationScore)try{if(i=await async function(e,t){const r=t.apiUrl.replace(/\/$/,""),s={"Content-Type":"application/json"};t.apiKey&&(s["X-API-Key"]=t.apiKey);const i=await fetch(`${r}/api/v1/reputation/${encodeURIComponent(e)}`,{method:"GET",headers:s});if(!i.ok){if(404===i.status)return{agentDid:e,score:50,totalInteractions:0,successRate:0,riskLevel:"unknown",updatedAt:Date.now()};throw new Error(`KTA API error: ${i.status} ${i.statusText}`)}const a=await i.json();return{agentDid:a.agentDid||e,score:a.score||50,totalInteractions:a.totalInteractions||0,successRate:a.successRate||0,riskLevel:a.riskLevel||"unknown",updatedAt:a.updatedAt||Date.now()}}(e,r.kta),r.debug&&console.log(`[AuthHandshake] Reputation score: ${i.score}`),i.score<r.bouncer.minReputationScore)return r.debug&&console.log(`[AuthHandshake] Reputation ${i.score} < ${r.bouncer.minReputationScore}, requiring authorization`),{authorized:!1,authError:await Rs(e,t,r,"Agent reputation score below threshold"),reputation:i,reason:"Low reputation score"}}catch(e){console.warn("[AuthHandshake] Failed to check reputation:",e)}try{a=await r.delegationVerifier.verify(e,t)}catch(s){console.error("[AuthHandshake] Delegation verification failed:",s);const i=`Delegation verification error: ${s instanceof Error?s.message:"Unknown error"}`;return{authorized:!1,authError:await Rs(e,t,r,i),reason:i}}return a.valid&&a.delegation?(r.debug&&console.log(`[AuthHandshake] Delegation valid, authorized (${Date.now()-s}ms)`),{authorized:!0,delegation:a.delegation,reputation:i,reason:"Valid delegation found"}):(r.debug&&console.log(`[AuthHandshake] No delegation found, returning needs_authorization (${Date.now()-s}ms)`),{authorized:!1,authError:await Rs(e,t,r,a.reason||"No valid delegation found"),reputation:i,reason:a.reason||"No delegation"})}(r,o.requiredScopes||[],e);if(!i.authorized)return s?.debug&&console.error(`[MCPI] Tool "${t}" blocked - authorization required`),{content:[{type:"text",text:JSON.stringify({error:"needs_authorization",message:`Tool "${t}" requires user authorization`,authorizationUrl:i.authError?.authorizationUrl,resumeToken:i.authError?.resumeToken,scopes:i.authError?.scopes,display:i.authError?.display})}],isError:!0};s?.debug&&console.error(`[MCPI] Tool "${t}" authorized - executing handler`)}try{const e=await i(r||{}),o={content:[{type:"text",text:"string"==typeof e?e:JSON.stringify(e)}]};if(a)try{const i=await a.ensureIdentity(),n={method:t,params:r||{}},c={data:e},d=Math.floor(Date.now()/1e3),l={sessionId:`tool-${Date.now()}`,nonce:`${Date.now()}`,audience:"client",createdAt:d,timestamp:d,lastActivity:d,ttlMinutes:30};let u;const h=xs.get(t);u=h?.requiredScopes&&h.requiredScopes.length>0?h.requiredScopes[0]:`${t}:execute`,s?.debug&&console.error(`[MCPI] Proof scopeId for tool "${t}": ${u}`);const p=new Is(i),f=await p.generateProof(n,c,l,{scopeId:u,clientDid:l?.clientDid});if(s?.debug&&console.error(`[MCPI] Generated proof for tool "${t}" - DID: ${f.meta.did}`),Bs)try{Bs.enqueue(f),s?.debug&&console.error("[MCPI] Proof enqueued for submission to AgentShield")}catch(e){s?.debug&&console.error("[MCPI] Failed to enqueue proof:",e)}return{...o,_meta:{proof:f}}}catch(e){return s?.debug&&console.error(`[MCPI] Failed to generate proof for tool "${t}":`,e),o}return o}catch(e){return{content:[{type:"text",text:`Error executing tool "${t}": ${e instanceof Error?e.message:String(e)}`}],isError:!0}}},Fs.run(o,c);var o,c}),s?.debug&&console.error("[MCPI] Handlers registered successfully"),e}"undefined"!=typeof global&&(global.__MCPI_HANDLERS_REGISTERED__=global.__MCPI_HANDLERS_REGISTERED__||!1);const Js=INJECTED_TOOLS,Ws="undefined"!=typeof IDENTITY_CONFIG?IDENTITY_CONFIG:void 0,Zs=Ws?JSON.parse(Ws):void 0,Qs={name:"MCP Server",version:"0.0.1"},Gs={capabilities:{tools:{}}};function Ys(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}"undefined"!=typeof global&&(global.__MCPI_SERVER_CREATED__=global.__MCPI_SERVER_CREATED__||!1);class Xs{start(){try{this.mcpServer.connect(this.transport),this.debug&&console.error("[STDIO] MCP Server running with STDIO transport"),this.setupShutdownHandlers()}catch(e){this.debug&&console.error("[STDIO] Error starting STDIO transport:",e),process.exit(1)}}setupShutdownHandlers(){const e=()=>{this.debug&&console.error("[STDIO] Shutting down STDIO transport"),process.exit(0)};process.on("SIGINT",e),process.on("SIGTERM",e)}shutdown(){this.debug&&console.error("[STDIO] Shutting down STDIO transport"),process.exit(0)}constructor(e,t=!1){Ys(this,"mcpServer",void 0),Ys(this,"transport",void 0),Ys(this,"debug",void 0),this.mcpServer=e,this.transport=new Or,this.debug=t}}const ei=STDIO_CONFIG.debug||!1;(async function(){if(Zs?.debug&&console.error("[createServer] Starting server creation"),"undefined"!=typeof global&&global.__MCPI_SERVER_CREATED__&&(Zs?.debug&&console.error("[createServer] Server already exists, returning cached instance"),global.__MCPI_SERVER_INSTANCE__))return global.__MCPI_SERVER_INSTANCE__;Zs?.debug&&(console.error("[createServer] Creating new McpServer"),console.error("[createServer] SERVER_INFO constant:",JSON.stringify(Qs)),console.error("[createServer] SERVER_CAPABILITIES constant:",JSON.stringify(Gs)),console.error("[createServer] Calling: new McpServer(SERVER_INFO, SERVER_CAPABILITIES)"));const e=new Tr(Qs,Gs);if(Zs?.debug){console.error("[createServer] Server created successfully");const t=e;console.error("[createServer] Actual server._serverInfo:",JSON.stringify(t._serverInfo||"undefined")),console.error("[createServer] Actual server._capabilities:",JSON.stringify(t._capabilities||"undefined")),console.error("[createServer] Loading tools...")}const[t,r]=function(){const e=new Map,t=Object.keys(Js);return Zs?.debug&&console.error("[loadTools] Injected tool paths:",t),[t.map(t=>Js[t]().then(r=>{Zs?.debug&&console.error("[loadTools] Loaded tool from path:",t),e.set(t,r)})),e]}();await Promise.all(t),Zs?.debug&&console.error("[createServer] Tools loaded, configuring server");const s=await async function(e,t){return await zs(e,t,Zs),e}(e,r);return Zs?.debug&&console.error("[createServer] Server configured successfully"),"undefined"!=typeof global&&(global.__MCPI_SERVER_CREATED__=!0,global.__MCPI_SERVER_INSTANCE__=s),s})().then(e=>{new Xs(e,ei).start()})})()})();
2
+ (()=>{var e={202:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.IdpTokenResolver=void 0,t.IdpTokenResolver=class{config;constructor(e){this.config={tokenStorage:e.tokenStorage,oauthService:e.oauthService,logger:e.logger||(()=>{})}}async resolveTokenFromDid(e,t,r){const s=await this.config.tokenStorage.getToken(e,t,r);if(!s)return this.config.logger("[IdpTokenResolver] Token not found",{userDid:e.substring(0,20)+"...",provider:t,scopes:r}),null;const i=Date.now();if(s.expires_at<i){if(this.config.logger("[IdpTokenResolver] Token expired, attempting refresh",{userDid:e.substring(0,20)+"...",provider:t,expiresAt:new Date(s.expires_at).toISOString(),hasRefreshToken:!!s.refresh_token}),s.refresh_token){const i=await this.config.oauthService.refreshToken(t,s.refresh_token);return i?(await this.config.tokenStorage.storeToken(e,t,r,i),this.config.logger("[IdpTokenResolver] Token refreshed successfully",{userDid:e.substring(0,20)+"...",provider:t,expiresAt:new Date(i.expires_at).toISOString()}),i.access_token):(this.config.logger("[IdpTokenResolver] Token refresh failed",{userDid:e.substring(0,20)+"...",provider:t}),null)}return this.config.logger("[IdpTokenResolver] Token expired and no refresh token",{userDid:e.substring(0,20)+"...",provider:t}),null}return this.config.logger("[IdpTokenResolver] Token resolved successfully",{userDid:e.substring(0,20)+"...",provider:t,expiresAt:new Date(s.expires_at).toISOString()}),s.access_token}}},4901:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ToolProtectionServiceError=t.DelegationRequiredError=void 0;class r extends Error{toolName;requiredScopes;consentUrl;resumeToken;interceptedCall;constructor(e,t,r,s,i){super(`Delegation required for tool "${e}"`),this.toolName=e,this.requiredScopes=t,this.consentUrl=r,this.name="DelegationRequiredError",this.interceptedCall=s,this.resumeToken=i}}t.DelegationRequiredError=r;class s extends Error{cause;constructor(e,t){super(e),this.cause=t,this.name="ToolProtectionServiceError"}}t.ToolProtectionServiceError=s},6069:(e,t,r)=>{"use strict";var s=r(72916).MissingRef;e.exports=function e(t,r,i){var a=this;if("function"!=typeof this._opts.loadSchema)throw new Error("options.loadSchema should be a function");"function"==typeof r&&(i=r,r=void 0);var o=n(t).then(function(){var e=a._addSchema(t,void 0,r);return e.validate||c(e)});return i&&o.then(function(e){i(null,e)},i),o;function n(t){var r=t.$schema;return r&&!a.getSchema(r)?e.call(a,{$ref:r},!0):Promise.resolve()}function c(e){try{return a._compile(e)}catch(t){if(t instanceof s)return function(t){var s=t.missingSchema;if(d(s))throw new Error("Schema "+s+" is loaded but "+t.missingRef+" cannot be resolved");var i=a._loadingSchemas[s];return i||(i=a._loadingSchemas[s]=a._opts.loadSchema(s)).then(o,o),i.then(function(e){if(!d(s))return n(e).then(function(){d(s)||a.addSchema(e,s,void 0,r)})}).then(function(){return c(e)});function o(){delete a._loadingSchemas[s]}function d(e){return a._refs[e]||a._schemas[e]}}(t);throw t}}}},7318:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MemoryStatusListStorage=void 0,t.MemoryStatusListStorage=class{statusLists=new Map;indexCounters=new Map;async getStatusList(e){return this.statusLists.get(e)||null}async setStatusList(e,t){this.statusLists.set(e,t)}async allocateIndex(e){const t=this.indexCounters.get(e)||0,r=t;return this.indexCounters.set(e,t+1),r}getIndexCount(e){return this.indexCounters.get(e)||0}clear(){this.statusLists.clear(),this.indexCounters.clear()}getAllStatusListIds(){return Array.from(this.statusLists.keys())}}},9249:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ToolProtectionService=void 0;const s=r(85601);t.ToolProtectionService=class{config;cache;constructor(e,t){this.config=e,this.cache=t}getProjectId(){return this.config.projectId}async getStaleCache(e){if(!1===this.config.allowStaleCache)return null;if(!(this.cache instanceof s.InMemoryToolProtectionCache))return null;const t=this.cache.getStale(e);if(!t)return null;const r=this.cache.getExpiresAt(e);if(!r)return null;const i=Date.now(),a=this.config.maxStaleCacheAge??864e5;return i>r&&i-r<=a?(this.config.debug&&console.log("[ToolProtectionService] Using stale cache",{cacheKey:e,expiredAt:new Date(r).toISOString(),staleAgeMs:i-r,maxStaleAgeMs:a}),t):null}async getToolProtectionConfig(e){const t=this.config.projectId?`config:tool-protections:${this.config.projectId}`:`agent:${e}`,r=await this.cache.get(t);if(r){const s=this.config.cacheTtl??3e5,i=new Date(Date.now()+s).toISOString();return this.config.debug&&console.log("[ToolProtectionService] Cache hit",{source:"cache",cacheKey:t,agentDid:e.slice(0,20)+"...",projectId:this.config.projectId||"none",toolCount:Object.keys(r.toolProtections).length,protectedTools:Object.entries(r.toolProtections).filter(([e,t])=>t.requiresDelegation).map(([e])=>e),cacheTtlMs:s,cachedUntil:i}),r}this.config.debug&&console.log("[ToolProtectionService] Cache miss, fetching from API",{source:"api-fetch-start",cacheKey:t,agentDid:e.slice(0,20)+"...",projectId:this.config.projectId||"none",apiUrl:this.config.apiUrl,endpoint:this.config.projectId?`/api/v1/bouncer/projects/${this.config.projectId}/tool-protections`:`/api/v1/bouncer/config?agent_did=${e}`});try{const r=await this.fetchFromApi(e);this.config.debug&&console.log("[ToolProtectionService] API response received",{source:"api-fetch-complete",agentDid:e.slice(0,20)+"...",projectId:this.config.projectId||"none",responseKeys:Object.keys(r),dataKeys:r.data?Object.keys(r.data):[],rawToolProtections:r.data?.toolProtections||null,rawTools:r.data?.tools||null,responseMetadata:r.metadata||null});const s={};if(r.data.toolProtections)for(const[e,t]of Object.entries(r.data.toolProtections)){const r=t.requiresDelegation??t.requires_delegation??!1,i=t.requiredScopes??t.required_scopes??t.scopes??[],a=t.oauthProvider??t.oauth_provider??void 0,o=t.riskLevel??t.risk_level??void 0;s[e]={requiresDelegation:r,requiredScopes:i,...a&&{oauthProvider:a},...o&&{riskLevel:o}}}else if(r.data.tools)if(Array.isArray(r.data.tools))for(const e of r.data.tools){const t=e.name;if(!t){this.config.debug&&console.warn("[ToolProtectionService] Tool missing name in array format",e);continue}const r=e.requiresDelegation??e.requires_delegation??!1,i=e.requiredScopes??e.required_scopes??e.scopes??[],a=e.oauthProvider??e.oauth_provider??void 0,o=e.riskLevel??e.risk_level??void 0;s[t]={requiresDelegation:r,requiredScopes:i,...a&&{oauthProvider:a},...o&&{riskLevel:o}}}else for(const[e,t]of Object.entries(r.data.tools)){const r=t.requiresDelegation??t.requires_delegation??!1,i=t.requiredScopes??t.required_scopes??t.scopes??[],a=t.oauthProvider??t.oauth_provider??void 0,o=t.riskLevel??t.risk_level??void 0;s[e]={requiresDelegation:r,requiredScopes:i,...a&&{oauthProvider:a},...o&&{riskLevel:o}}}const i={...s};if(this.config.fallbackConfig?.toolProtections)for(const[e,t]of Object.entries(this.config.fallbackConfig.toolProtections)){if(!t||"object"!=typeof t||0===Object.keys(t).length){this.config.debug&&console.log("[ToolProtectionService] Skipping empty/invalid fallback config entry",{tool:e});continue}const r={requiresDelegation:t.requiresDelegation??!1,requiredScopes:t.requiredScopes??[]};i[e]=r,this.config.debug&&console.log("[ToolProtectionService] Overriding API config with local config",{tool:e,localConfig:r})}const a={toolProtections:i},o=this.config.cacheTtl??3e5,n=new Date(Date.now()+o);return await this.cache.set(t,a,o),console.log("[ToolProtectionService] Config loaded from API",{source:"api",toolCount:Object.keys(i).length,protectedTools:Object.entries(i).filter(([e,t])=>t.requiresDelegation).map(([e])=>e),agentDid:e.slice(0,20)+"...",projectId:this.config.projectId||"none",cacheTtlMs:o,cacheExpiresAt:n.toISOString()}),this.config.debug&&console.log("[ToolProtectionService] API fetch successful, config cached",{source:"cache-write",agentDid:e.slice(0,20)+"...",cacheKey:t,toolCount:Object.keys(i).length,tools:Object.entries(i).map(([e,t])=>({name:e,requiresDelegation:t.requiresDelegation,scopeCount:(t.requiredScopes||[]).length})),ttlMs:o,ttlMinutes:Math.round(o/6e4),expiresAt:n.toISOString(),expiresIn:`${Math.round(o/1e3)}s`}),a}catch(r){const s=r instanceof Error?r.message:String(r);if(s.includes("API key is missing or empty"))throw r;if(s.includes("Failed to fetch bouncer config:")&&(429!==r.status||!this.config.fallbackConfig))throw r;if(s.includes("Failed to parse API response:"))throw r;if(s.includes("API returned success: false"))throw r;this.config.debug&&console.error("[ToolProtectionService] API fetch failed",{agentDid:e.slice(0,20)+"...",error:s});const i=await this.getStaleCache(t);if(i)return console.warn("[ToolProtectionService] API fetch failed, using stale cache",{agentDid:e.slice(0,20)+"...",error:s,cacheKey:t}),i;if(this.config.fallbackConfig){console.warn("[ToolProtectionService] API fetch failed, using fallback config",{agentDid:e.slice(0,20)+"...",error:s});const r=this.config.cacheTtl??3e5;return await this.cache.set(t,this.config.fallbackConfig,r),this.config.fallbackConfig}if("deny-all"===(this.config.failSafeBehavior??"deny-all")){console.error("[ToolProtectionService] API fetch failed, no fallback, failing closed (deny-all)",{agentDid:e.slice(0,20)+"...",error:s,cacheKey:t});const r={toolProtections:{"*":{requiresDelegation:!0,requiredScopes:[]}}},i=this.config.cacheTtl??3e5;return await this.cache.set(t,r,i),r}{console.warn("[ToolProtectionService] API fetch failed, no fallback, failing open (allow-all)",{agentDid:e.slice(0,20)+"...",error:s,cacheKey:t});const r={toolProtections:{}},i=this.config.cacheTtl??3e5;return await this.cache.set(t,r,i),r}}}async checkToolProtection(e,t){const r=await this.getToolProtectionConfig(t);let s=r.toolProtections[e];return!s&&r.toolProtections["*"]&&(s=r.toolProtections["*"]),(this.config.debug||!s||s.requiresDelegation)&&console.log("[ToolProtectionService] Protection check",{tool:e,agentDid:t.slice(0,20)+"...",found:!!s,isWildcard:s===r.toolProtections["*"],requiresDelegation:s?.requiresDelegation??!1,availableTools:Object.keys(r.toolProtections)}),s&&s.requiresDelegation?s:null}async fetchFromApi(e){let t,r=!1;this.config.projectId?(t=`${this.config.apiUrl}/api/v1/bouncer/projects/${encodeURIComponent(this.config.projectId)}/tool-protections`,r=!0):t=`${this.config.apiUrl}/api/v1/bouncer/config?agent_did=${encodeURIComponent(e)}`;const s=this.config.apiKey?(()=>{const e=this.config.apiKey.split("_");return e.length>=2?`${e[0]}_${e[1]}...`:`${this.config.apiKey.substring(0,8)}...`})():"(empty)",i=this.config.apiKey?.length||0;if(this.config.debug&&console.log("[ToolProtectionService] Fetching from API:",t,{method:r?"projects/{projectId}/tool-protections (new)":"config?agent_did (old)",projectId:this.config.projectId||"none",apiKeyPresent:!!this.config.apiKey,apiKeyLength:i,apiKeyMasked:s}),!this.config.apiKey||""===this.config.apiKey.trim()){const e="API key is missing or empty";throw this.config.debug&&console.error("[ToolProtectionService]",e,{apiKeyPresent:!!this.config.apiKey,apiKeyLength:i}),new Error(`ToolProtectionService: ${e}. Check AGENTSHIELD_API_KEY in .dev.vars or wrangler.toml [vars]`)}const a={"Content-Type":"application/json"};r?(a["X-API-Key"]=this.config.apiKey,this.config.projectId&&(a["X-Project-Id"]=this.config.projectId)):a.Authorization=`Bearer ${this.config.apiKey}`;const o=await fetch(t,{method:"GET",headers:a});if(!o.ok){const e=await o.text().catch(()=>"Unknown error"),t=new Error(`Failed to fetch bouncer config: ${o.status} ${o.statusText} - ${e}`);throw t.status=o.status,t}let n;try{n=await o.json()}catch(e){throw new Error(`Failed to parse API response: ${e instanceof Error?e.message:String(e)}`)}if(!n.success)throw new Error("API returned success: false");return n}async clearCache(e){const t=this.config.projectId?`config:tool-protections:${this.config.projectId}`:`agent:${e}`;this.config.debug&&console.log("[ToolProtectionService] Clearing cache",{cacheKey:t,projectId:this.config.projectId||"none",agentDid:e.slice(0,20)+"..."}),await this.cache.delete(t)}async clearAndRefresh(e){const t=this.config.projectId?`config:tool-protections:${this.config.projectId}`:`agent:${e}`;console.log("[ToolProtectionService] clearAndRefresh starting",{cacheKey:t,projectId:this.config.projectId||"none",agentDid:e.slice(0,20)+"..."}),await this.cache.delete(t),console.log("[ToolProtectionService] Cache entry deleted",{cacheKey:t});try{const r=await this.fetchFromApi(e),s={};if(r.data.toolProtections)for(const[e,t]of Object.entries(r.data.toolProtections)){const r=t.requiresDelegation??t.requires_delegation??!1,i=t.requiredScopes??t.required_scopes??t.scopes??[],a=t.oauthProvider??t.oauth_provider??void 0,o=t.riskLevel??t.risk_level??void 0;s[e]={requiresDelegation:r,requiredScopes:i,...a&&{oauthProvider:a},...o&&{riskLevel:o}}}else if(r.data.tools)if(Array.isArray(r.data.tools))for(const e of r.data.tools){const t=e.name;if(!t)continue;const r=e.requiresDelegation??e.requires_delegation??!1,i=e.requiredScopes??e.required_scopes??e.scopes??[],a=e.oauthProvider??e.oauth_provider??void 0,o=e.riskLevel??e.risk_level??void 0;s[t]={requiresDelegation:r,requiredScopes:i,...a&&{oauthProvider:a},...o&&{riskLevel:o}}}else for(const[e,t]of Object.entries(r.data.tools)){const r=t.requiresDelegation??t.requires_delegation??!1,i=t.requiredScopes??t.required_scopes??t.scopes??[],a=t.oauthProvider??t.oauth_provider??void 0,o=t.riskLevel??t.risk_level??void 0;s[e]={requiresDelegation:r,requiredScopes:i,...a&&{oauthProvider:a},...o&&{riskLevel:o}}}const i={toolProtections:s},a=this.config.cacheTtl??3e5;return await this.cache.set(t,i,a),console.log("[ToolProtectionService] Fresh config fetched and cached",{cacheKey:t,toolCount:Object.keys(s).length,protectedTools:Object.entries(s).filter(([e,t])=>t.requiresDelegation).map(([e])=>e),source:"api"}),{config:i,cacheKey:t,source:"api"}}catch(e){return console.warn("[ToolProtectionService] API fetch failed during refresh, using fallback",{error:e instanceof Error?e.message:String(e),cacheKey:t}),{config:this.config.fallbackConfig||{toolProtections:{}},cacheKey:t,source:"fallback"}}}}},9717:(e,t,r)=>{"use strict";function s(e,t,r,s){var i=s?" !== ":" === ",a=s?" || ":" && ",o=s?"!":"",n=s?"":"!";switch(e){case"null":return t+i+"null";case"array":return o+"Array.isArray("+t+")";case"object":return"("+o+t+a+"typeof "+t+i+'"object"'+a+n+"Array.isArray("+t+"))";case"integer":return"(typeof "+t+i+'"number"'+a+n+"("+t+" % 1)"+a+t+i+t+(r?a+o+"isFinite("+t+")":"")+")";case"number":return"(typeof "+t+i+'"'+e+'"'+(r?a+o+"isFinite("+t+")":"")+")";default:return"typeof "+t+i+'"'+e+'"'}}e.exports={copy:function(e,t){for(var r in t=t||{},e)t[r]=e[r];return t},checkDataType:s,checkDataTypes:function(e,t,r){if(1===e.length)return s(e[0],t,r,!0);var i="",o=a(e);for(var n in o.array&&o.object&&(i=o.null?"(":"(!"+t+" || ",i+="typeof "+t+' !== "object")',delete o.null,delete o.array,delete o.object),o.number&&delete o.integer,o)i+=(i?" && ":"")+s(n,t,r,!0);return i},coerceToTypes:function(e,t){if(Array.isArray(t)){for(var r=[],s=0;s<t.length;s++){var a=t[s];(i[a]||"array"===e&&"array"===a)&&(r[r.length]=a)}if(r.length)return r}else{if(i[t])return[t];if("array"===e&&"array"===t)return["array"]}},toHash:a,getProperty:c,escapeQuotes:d,equal:r(67371),ucs2length:r(61812),varOccurences:function(e,t){t+="[^0-9]";var r=e.match(new RegExp(t,"g"));return r?r.length:0},varReplace:function(e,t,r){return t+="([^0-9])",r=r.replace(/\$/g,"$$$$"),e.replace(new RegExp(t,"g"),r+"$1")},schemaHasRules:function(e,t){if("boolean"==typeof e)return!e;for(var r in e)if(t[r])return!0},schemaHasRulesExcept:function(e,t,r){if("boolean"==typeof e)return!e&&"not"!=r;for(var s in e)if(s!=r&&t[s])return!0},schemaUnknownRules:function(e,t){if("boolean"!=typeof e)for(var r in e)if(!t[r])return r},toQuotedString:l,getPathExpr:function(e,t,r,s){return p(e,r?"'/' + "+t+(s?"":".replace(/~/g, '~0').replace(/\\//g, '~1')"):s?"'[' + "+t+" + ']'":"'[\\'' + "+t+" + '\\']'")},getPath:function(e,t,r){return p(e,l(r?"/"+f(t):c(t)))},getData:function(e,t,r){var s,i,a,o;if(""===e)return"rootData";if("/"==e[0]){if(!u.test(e))throw new Error("Invalid JSON-pointer: "+e);i=e,a="rootData"}else{if(!(o=e.match(h)))throw new Error("Invalid JSON-pointer: "+e);if(s=+o[1],"#"==(i=o[2])){if(s>=t)throw new Error("Cannot access property/index "+s+" levels up, current level is "+t);return r[t-s]}if(s>t)throw new Error("Cannot access data "+s+" levels up, current level is "+t);if(a="data"+(t-s||""),!i)return a}for(var n=a,d=i.split("/"),l=0;l<d.length;l++){var p=d[l];p&&(n+=" && "+(a+=c(g(p))))}return n},unescapeFragment:function(e){return g(decodeURIComponent(e))},unescapeJsonPointer:g,escapeFragment:function(e){return encodeURIComponent(f(e))},escapeJsonPointer:f};var i=a(["string","number","integer","boolean","null"]);function a(e){for(var t={},r=0;r<e.length;r++)t[e[r]]=!0;return t}var o=/^[a-z$_][a-z$_0-9]*$/i,n=/'|\\/g;function c(e){return"number"==typeof e?"["+e+"]":o.test(e)?"."+e:"['"+d(e)+"']"}function d(e){return e.replace(n,"\\$&").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\f/g,"\\f").replace(/\t/g,"\\t")}function l(e){return"'"+d(e)+"'"}var u=/^\/(?:[^~]|~0|~1)*$/,h=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function p(e,t){return'""'==e?t:(e+" + "+t).replace(/([^\\])' \+ '/g,"$1")}function f(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function g(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}},9931:e=>{"use strict";e.exports=function(e,t,r){var s=" ",i=e.level,a=e.dataLevel,o=e.schema[t],n=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,d=!e.opts.allErrors,l="data"+(a||""),u="errs__"+i,h=e.util.copy(e);h.level++;var p="valid"+h.level;if(s+="var "+u+" = errors;",e.opts.strictKeywords?"object"==typeof o&&Object.keys(o).length>0||!1===o:e.util.schemaHasRules(o,e.RULES.all)){h.schema=o,h.schemaPath=n,h.errSchemaPath=c;var f="key"+i,g="idx"+i,m="i"+i,v="' + "+f+" + '",y="data"+(h.dataLevel=e.dataLevel+1),_="dataProperties"+i,w=e.opts.ownProperties,b=e.baseId;w&&(s+=" var "+_+" = undefined; "),s+=w?" "+_+" = "+_+" || Object.keys("+l+"); for (var "+g+"=0; "+g+"<"+_+".length; "+g+"++) { var "+f+" = "+_+"["+g+"]; ":" for (var "+f+" in "+l+") { ",s+=" var startErrs"+i+" = errors; ";var S=f,P=e.compositeRule;e.compositeRule=h.compositeRule=!0;var E=e.validate(h);h.baseId=b,e.util.varOccurences(E,y)<2?s+=" "+e.util.varReplace(E,y,S)+" ":s+=" var "+y+" = "+S+"; "+E+" ",e.compositeRule=h.compositeRule=P,s+=" if (!"+p+") { for (var "+m+"=startErrs"+i+"; "+m+"<errors; "+m+"++) { vErrors["+m+"].propertyName = "+f+"; } var err = ",!1!==e.createErrors?(s+=" { keyword: 'propertyNames' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { propertyName: '"+v+"' } ",!1!==e.opts.messages&&(s+=" , message: 'property name \\'"+v+"\\' is invalid' "),e.opts.verbose&&(s+=" , schema: validate.schema"+n+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),s+=" } "):s+=" {} ",s+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&d&&(e.async?s+=" throw new ValidationError(vErrors); ":s+=" validate.errors = vErrors; return false; "),d&&(s+=" break; "),s+=" } }"}return d&&(s+=" if ("+u+" == errors) {"),s}},10985:(e,t,r)=>{"use strict";r.d(t,{S:()=>i});var s="$";function i(e,t){var r="",i=t&&t.include,a=t&&t.exclude;a&&"string"==typeof a&&(a=[a]),i&&i.sort();var o=new WeakMap,n=t&&t.allowCircular,c=t&&t.filterUndefined,d=t&&t.undefinedInArrayToNull;return function e(t,l){if(null===t||"object"!=typeof t||null!=t.toJSON)r+=JSON.stringify(t);else if(Array.isArray(t)){if(void 0!==(h=o.get(t))&&l.startsWith(h)){if(!n)throw new Error("Circular reference detected");return void(r+='"[Circular:'+h+']"')}o.set(t,l),r+="[";var u=!1;t.forEach(function(t,s){u&&(r+=","),u=!0,d&&void 0===t&&(t=null),e(t,l+"["+s+"]")}),r+="]"}else{var h;if(void 0!==(h=o.get(t))&&l.startsWith(h)){if(!n)throw new Error("Circular reference detected");return void(r+='"[Circular:'+h+']"')}o.set(t,l),r+="{";var p=!1,f=function(s){a&&a.includes(s)||(p&&(r+=","),p=!0,r+=JSON.stringify(s),r+=":",e(t[s],l+"."+s))};if(l===s&&i)i.forEach(function(e){t.hasOwnProperty(e)&&f(e)});else{var g=Object.keys(t);c&&(g=g.filter(function(e){return void 0!==t[e]})),g.sort(),g.forEach(function(e){f(e)})}r+="}"}}(e,s),r}},11300:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SCHEMA_REGISTRY=void 0,t.getAllSchemas=function(){return t.SCHEMA_REGISTRY},t.getSchemasByCategory=function(e){const r={vc:["verifiable-credential","verifiable-presentation","statuslist2021-credential","statuslist2021-credential-subject"],delegation:["delegation-credential","delegation-record","delegation-constraints","delegation-chain","delegation-creation-request","delegation-verification-result"],handshake:["handshake-request","session-context","nonce-cache-config","nonce-cache-entry"],proof:["detached-proof","proof-meta","proof","proof-w3c","audit-record","canonical-hashes"],registry:["registration-input","registration-result","agent-status","claim-token","delegation-request","delegation-response","registry-delegation","mirror-status","receipt"],runtime:["authorization-display","needs-authorization-error","runtime-error"],cli:["register-output"],tlkrc:["rotation-chain","rotation-event"],verifier:["verify-page"],"well-known":["well-known-agent"]}[e]||[];return t.SCHEMA_REGISTRY.filter(e=>r.includes(e.id))},t.getSchemaById=function(e){return t.SCHEMA_REGISTRY.find(t=>t.id===e)},t.getCriticalSchemas=function(){const e=["verifiable-credential","statuslist2021-credential","delegation-credential","delegation-record","delegation-constraints","detached-proof","proof-meta","handshake-request","session-context","audit-record"];return t.SCHEMA_REGISTRY.filter(t=>e.includes(t.id))},t.getSchemaStats=function(){const e={},s={};for(const i of t.SCHEMA_REGISTRY){const t=i.url.replace(r+"/","").split("/")[0]||"unknown";e[t]=(e[t]||0)+1,s[i.version]=(s[i.version]||0)+1}return{total:t.SCHEMA_REGISTRY.length,byCategory:e,byVersion:s}};const r="https://schemas.kya-os.ai/xmcp-i";t.SCHEMA_REGISTRY=[{id:"verifiable-credential",url:`${r}/vc/verifiable-credential.v1.0.0.json`,version:"1.0.0",type:"VerifiableCredential",description:"W3C Verifiable Credential Data Model"},{id:"verifiable-presentation",url:`${r}/vc/verifiable-presentation.v1.0.0.json`,version:"1.0.0",type:"VerifiablePresentation",description:"W3C Verifiable Presentation"},{id:"statuslist2021-credential",url:`${r}/vc/statuslist-2021-credential.v1.0.0.json`,version:"1.0.0",type:"StatusList2021Credential",description:"StatusList2021 Credential for efficient revocation"},{id:"statuslist2021-credential-subject",url:`${r}/vc/statuslist-2021-credential-subject.v1.0.0.json`,version:"1.0.0",type:"StatusList2021CredentialSubject",description:"StatusList2021 Credential Subject"},{id:"delegation-credential",url:`${r}/credentials/delegation/v1.0.0.json`,version:"1.0.0",type:"DelegationCredential",description:"W3C VC-based delegation credential"},{id:"delegation-record",url:`${r}/delegation/delegation-record.v1.0.0.json`,version:"1.0.0",type:"DelegationRecord",description:"Internal delegation record"},{id:"delegation-constraints",url:`${r}/delegation/constraints.v1.0.0.json`,version:"1.0.0",type:"DelegationConstraints",description:"CRISP constraints for delegations"},{id:"delegation-chain",url:`${r}/delegation/delegation-chain.v1.0.0.json`,version:"1.0.0",type:"DelegationChain",description:"Delegation chain for hierarchy tracking"},{id:"delegation-creation-request",url:`${r}/delegation/delegation-creation-request.v1.0.0.json`,version:"1.0.0",type:"DelegationCreationRequest",description:"Request to create a delegation"},{id:"delegation-verification-result",url:`${r}/delegation/delegation-verification-result.v1.0.0.json`,version:"1.0.0",type:"DelegationVerificationResult",description:"Result of delegation verification"},{id:"handshake-request",url:`${r}/handshake/handshake-request.v1.0.0.json`,version:"1.0.0",type:"HandshakeRequest",description:"MCP-I handshake request"},{id:"session-context",url:`${r}/handshake/session-context.v1.0.0.json`,version:"1.0.0",type:"SessionContext",description:"MCP-I session context"},{id:"nonce-cache-config",url:`${r}/handshake/nonce-cache-config.v1.0.0.json`,version:"1.0.0",type:"NonceCacheConfig",description:"Nonce cache configuration"},{id:"nonce-cache-entry",url:`${r}/handshake/nonce-cache-entry.v1.0.0.json`,version:"1.0.0",type:"NonceCacheEntry",description:"Nonce cache entry for replay protection"},{id:"detached-proof",url:`${r}/proof/detached-proof.v1.0.0.json`,version:"1.0.0",type:"DetachedProof",description:"MCP-I detached proof with JWS"},{id:"proof-meta",url:`${r}/proof/proof-meta.v1.0.0.json`,version:"1.0.0",type:"ProofMeta",description:"Metadata for MCP-I proofs"},{id:"proof",url:`${r}/proof/v1.0.0.json`,version:"1.0.0",type:"Proof",description:"Generic proof structure"},{id:"proof-w3c",url:`${r}/proof/w3c/v1.0.0.json`,version:"1.0.0",type:"W3CProof",description:"W3C-compliant proof"},{id:"audit-record",url:`${r}/proof/audit-record.v1.0.0.json`,version:"1.0.0",type:"AuditRecord",description:"Audit trail record"},{id:"canonical-hashes",url:`${r}/proof/canonical-hashes.v1.0.0.json`,version:"1.0.0",type:"CanonicalHashes",description:"Canonical hashes for proof generation"},{id:"registration-input",url:`${r}/registry/registration-input.v1.0.0.json`,version:"1.0.0",type:"RegistrationInput",description:"Agent registration input"},{id:"registration-result",url:`${r}/registry/registration-result.v1.0.0.json`,version:"1.0.0",type:"RegistrationResult",description:"Agent registration result"},{id:"agent-status",url:`${r}/registry/agent-status.v1.0.0.json`,version:"1.0.0",type:"AgentStatus",description:"Agent status information"},{id:"claim-token",url:`${r}/registry/claim-token.v1.0.0.json`,version:"1.0.0",type:"ClaimToken",description:"Token for claiming agent ownership"},{id:"delegation-request",url:`${r}/registry/delegation-request.v1.0.0.json`,version:"1.0.0",type:"DelegationRequest",description:"Registry delegation request"},{id:"delegation-response",url:`${r}/registry/delegation-response.v1.0.0.json`,version:"1.0.0",type:"DelegationResponse",description:"Registry delegation response"},{id:"registry-delegation",url:`${r}/registry/delegation.v1.0.0.json`,version:"1.0.0",type:"RegistryDelegation",description:"Registry delegation object"},{id:"mirror-status",url:`${r}/registry/mirror-status.v1.0.0.json`,version:"1.0.0",type:"MirrorStatus",description:"Registry mirror status"},{id:"receipt",url:`${r}/registry/receipt.v1.0.0.json`,version:"1.0.0",type:"Receipt",description:"Registry receipt"},{id:"authorization-display",url:`${r}/runtime/authorization-display.v1.0.0.json`,version:"1.0.0",type:"AuthorizationDisplay",description:"Authorization display information"},{id:"needs-authorization-error",url:`${r}/runtime/needs-authorization-error.v1.0.0.json`,version:"1.0.0",type:"NeedsAuthorizationError",description:"Error indicating authorization is needed"},{id:"runtime-error",url:`${r}/runtime/runtime-error.v1.0.0.json`,version:"1.0.0",type:"RuntimeError",description:"Generic runtime error"},{id:"register-output",url:`${r}/cli/register-output/v1.0.0.json`,version:"1.0.0",type:"RegisterOutput",description:"CLI registration output"},{id:"rotation-chain",url:`${r}/tlkrc/rotation-chain.v1.0.0.json`,version:"1.0.0",type:"RotationChain",description:"Key rotation chain"},{id:"rotation-event",url:`${r}/tlkrc/rotation-event.v1.0.0.json`,version:"1.0.0",type:"RotationEvent",description:"Key rotation event"},{id:"verify-page",url:`${r}/verifier/verify-page/v1.0.0.json`,version:"1.0.0",type:"VerifyPage",description:"Verifier page response"},{id:"well-known-agent",url:`${r}/well-known/agent/v1.0.0.json`,version:"1.0.0",type:"WellKnownAgent",description:"Agent well-known metadata"}]},12269:e=>{"use strict";e.exports=JSON.parse('{"$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":true,"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":true,"readOnly":{"type":"boolean","default":false},"examples":{"type":"array","items":true},"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":true},"maxItems":{"$ref":"#/definitions/nonNegativeInteger"},"minItems":{"$ref":"#/definitions/nonNegativeIntegerDefault0"},"uniqueItems":{"type":"boolean","default":false},"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":true,"enum":{"type":"array","items":true,"minItems":1,"uniqueItems":true},"type":{"anyOf":[{"$ref":"#/definitions/simpleTypes"},{"type":"array","items":{"$ref":"#/definitions/simpleTypes"},"minItems":1,"uniqueItems":true}]},"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":true}')},12857:e=>{"use strict";e.exports=function(e,t,r){var s,i,a=" ",o=e.level,n=e.dataLevel,c=e.schema[t],d=e.errSchemaPath+"/"+t,l=!e.opts.allErrors,u="data"+(n||""),h="valid"+o;if("#"==c||"#/"==c)e.isRoot?(s=e.async,i="validate"):(s=!0===e.root.schema.$async,i="root.refVal[0]");else{var p=e.resolveRef(e.baseId,c,e.isRoot);if(void 0===p){var f=e.MissingRefError.message(e.baseId,c);if("fail"==e.opts.missingRefs){e.logger.error(f),(y=y||[]).push(a),a="",!1!==e.createErrors?(a+=" { keyword: '$ref' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(d)+" , params: { ref: '"+e.util.escapeQuotes(c)+"' } ",!1!==e.opts.messages&&(a+=" , message: 'can\\'t resolve reference "+e.util.escapeQuotes(c)+"' "),e.opts.verbose&&(a+=" , schema: "+e.util.toQuotedString(c)+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ";var g=a;a=y.pop(),!e.compositeRule&&l?e.async?a+=" throw new ValidationError(["+g+"]); ":a+=" validate.errors = ["+g+"]; return false; ":a+=" var err = "+g+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",l&&(a+=" if (false) { ")}else{if("ignore"!=e.opts.missingRefs)throw new e.MissingRefError(e.baseId,c,f);e.logger.warn(f),l&&(a+=" if (true) { ")}}else if(p.inline){var m=e.util.copy(e);m.level++;var v="valid"+m.level;m.schema=p.schema,m.schemaPath="",m.errSchemaPath=c,a+=" "+e.validate(m).replace(/validate\.schema/g,p.code)+" ",l&&(a+=" if ("+v+") { ")}else s=!0===p.$async||e.async&&!1!==p.$async,i=p.code}if(i){var y;(y=y||[]).push(a),a="",e.opts.passContext?a+=" "+i+".call(this, ":a+=" "+i+"( ",a+=" "+u+", (dataPath || '')",'""'!=e.errorPath&&(a+=" + "+e.errorPath);var _=a+=" , "+(n?"data"+(n-1||""):"parentData")+" , "+(n?e.dataPathArr[n]:"parentDataProperty")+", rootData) ";if(a=y.pop(),s){if(!e.async)throw new Error("async schema referenced by sync schema");l&&(a+=" var "+h+"; "),a+=" try { await "+_+"; ",l&&(a+=" "+h+" = true; "),a+=" } catch (e) { if (!(e instanceof ValidationError)) throw e; if (vErrors === null) vErrors = e.errors; else vErrors = vErrors.concat(e.errors); errors = vErrors.length; ",l&&(a+=" "+h+" = false; "),a+=" } ",l&&(a+=" if ("+h+") { ")}else a+=" if (!"+_+") { if (vErrors === null) vErrors = "+i+".errors; else vErrors = vErrors.concat("+i+".errors); errors = vErrors.length; } ",l&&(a+=" else { ")}return a}},13215:e=>{"use strict";e.exports=JSON.parse('{"$schema":"http://json-schema.org/draft-07/schema#","$id":"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#","description":"Meta-schema for $data reference (JSON Schema extension proposal)","type":"object","required":["$data"],"properties":{"$data":{"type":"string","anyOf":[{"format":"relative-json-pointer"},{"format":"json-pointer"}]}},"additionalProperties":false}')},13441:e=>{"use strict";e.exports=function(e,t,r){var s=" ",i=e.level,a=e.dataLevel,o=e.schema[t],n=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,d=!e.opts.allErrors,l="data"+(a||""),u="errs__"+i,h=e.util.copy(e);h.level++;var p="valid"+h.level;if(e.opts.strictKeywords?"object"==typeof o&&Object.keys(o).length>0||!1===o:e.util.schemaHasRules(o,e.RULES.all)){h.schema=o,h.schemaPath=n,h.errSchemaPath=c,s+=" var "+u+" = errors; ";var f,g=e.compositeRule;e.compositeRule=h.compositeRule=!0,h.createErrors=!1,h.opts.allErrors&&(f=h.opts.allErrors,h.opts.allErrors=!1),s+=" "+e.validate(h)+" ",h.createErrors=!0,f&&(h.opts.allErrors=f),e.compositeRule=h.compositeRule=g,s+=" if ("+p+") { ";var m=m||[];m.push(s),s="",!1!==e.createErrors?(s+=" { keyword: 'not' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: {} ",!1!==e.opts.messages&&(s+=" , message: 'should NOT be valid' "),e.opts.verbose&&(s+=" , schema: validate.schema"+n+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),s+=" } "):s+=" {} ";var v=s;s=m.pop(),!e.compositeRule&&d?e.async?s+=" throw new ValidationError(["+v+"]); ":s+=" validate.errors = ["+v+"]; return false; ":s+=" var err = "+v+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+=" } else { errors = "+u+"; if (vErrors !== null) { if ("+u+") vErrors.length = "+u+"; else vErrors = null; } ",e.opts.allErrors&&(s+=" } ")}else s+=" var err = ",!1!==e.createErrors?(s+=" { keyword: 'not' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: {} ",!1!==e.opts.messages&&(s+=" , message: 'should NOT be valid' "),e.opts.verbose&&(s+=" , schema: validate.schema"+n+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),s+=" } "):s+=" {} ",s+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",d&&(s+=" if (false) { ");return s}},13749:function(e,t){!function(e){"use strict";function t(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];if(t.length>1){t[0]=t[0].slice(0,-1);for(var s=t.length-1,i=1;i<s;++i)t[i]=t[i].slice(1,-1);return t[s]=t[s].slice(1),t.join("")}return t[0]}function r(e){return"(?:"+e+")"}function s(e){return void 0===e?"undefined":null===e?"null":Object.prototype.toString.call(e).split(" ").pop().split("]").shift().toLowerCase()}function i(e){return e.toUpperCase()}function a(e){var s="[A-Za-z]",i="[0-9]",a=t(i,"[A-Fa-f]"),o=r(r("%[EFef]"+a+"%"+a+a+"%"+a+a)+"|"+r("%[89A-Fa-f]"+a+"%"+a+a)+"|"+r("%"+a+a)),n="[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]",c=t("[\\:\\/\\?\\#\\[\\]\\@]",n),d=e?"[\\uE000-\\uF8FF]":"[]",l=t(s,i,"[\\-\\.\\_\\~]",e?"[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]":"[]"),u=r(s+t(s,i,"[\\+\\-\\.]")+"*"),h=r(r(o+"|"+t(l,n,"[\\:]"))+"*"),p=(r(r("25[0-5]")+"|"+r("2[0-4]"+i)+"|"+r("1"+i+i)+"|"+r("[1-9]"+i)+"|"+i),r(r("25[0-5]")+"|"+r("2[0-4]"+i)+"|"+r("1"+i+i)+"|"+r("0?[1-9]"+i)+"|0?0?"+i)),f=r(p+"\\."+p+"\\."+p+"\\."+p),g=r(a+"{1,4}"),m=r(r(g+"\\:"+g)+"|"+f),v=r(r(g+"\\:")+"{6}"+m),y=r("\\:\\:"+r(g+"\\:")+"{5}"+m),_=r(r(g)+"?\\:\\:"+r(g+"\\:")+"{4}"+m),w=r(r(r(g+"\\:")+"{0,1}"+g)+"?\\:\\:"+r(g+"\\:")+"{3}"+m),b=r(r(r(g+"\\:")+"{0,2}"+g)+"?\\:\\:"+r(g+"\\:")+"{2}"+m),S=r(r(r(g+"\\:")+"{0,3}"+g)+"?\\:\\:"+g+"\\:"+m),P=r(r(r(g+"\\:")+"{0,4}"+g)+"?\\:\\:"+m),E=r(r(r(g+"\\:")+"{0,5}"+g)+"?\\:\\:"+g),I=r(r(r(g+"\\:")+"{0,6}"+g)+"?\\:\\:"),k=r([v,y,_,w,b,S,P,E,I].join("|")),C=r(r(l+"|"+o)+"+"),D=(r(k+"\\%25"+C),r(k+r("\\%25|\\%(?!"+a+"{2})")+C)),O=r("[vV]"+a+"+\\."+t(l,n,"[\\:]")+"+"),A=r("\\["+r(D+"|"+k+"|"+O)+"\\]"),x=r(r(o+"|"+t(l,n))+"*"),T=r(A+"|"+f+"(?!"+x+")|"+x),R=r(i+"*"),$=r(r(h+"@")+"?"+T+r("\\:"+R)+"?"),j=r(o+"|"+t(l,n,"[\\:\\@]")),N=r(j+"*"),M=r(j+"+"),F=r(r(o+"|"+t(l,n,"[\\@]"))+"+"),K=r(r("\\/"+N)+"*"),q=r("\\/"+r(M+K)+"?"),L=r(F+K),U=r(M+K),V="(?!"+j+")",H=(r(K+"|"+q+"|"+L+"|"+U+"|"+V),r(r(j+"|"+t("[\\/\\?]",d))+"*")),B=r(r(j+"|[\\/\\?]")+"*"),z=r(r("\\/\\/"+$+K)+"|"+q+"|"+U+"|"+V),J=r(u+"\\:"+z+r("\\?"+H)+"?"+r("\\#"+B)+"?"),W=r(r("\\/\\/"+$+K)+"|"+q+"|"+L+"|"+V),Z=r(W+r("\\?"+H)+"?"+r("\\#"+B)+"?");return r(J+"|"+Z),r(u+"\\:"+z+r("\\?"+H)+"?"),r(r("\\/\\/("+r("("+h+")@")+"?("+T+")"+r("\\:("+R+")")+"?)")+"?("+K+"|"+q+"|"+U+"|"+V+")"),r("\\?("+H+")"),r("\\#("+B+")"),r(r("\\/\\/("+r("("+h+")@")+"?("+T+")"+r("\\:("+R+")")+"?)")+"?("+K+"|"+q+"|"+L+"|"+V+")"),r("\\?("+H+")"),r("\\#("+B+")"),r(r("\\/\\/("+r("("+h+")@")+"?("+T+")"+r("\\:("+R+")")+"?)")+"?("+K+"|"+q+"|"+U+"|"+V+")"),r("\\?("+H+")"),r("\\#("+B+")"),r("("+h+")@"),r("\\:("+R+")"),{NOT_SCHEME:new RegExp(t("[^]",s,i,"[\\+\\-\\.]"),"g"),NOT_USERINFO:new RegExp(t("[^\\%\\:]",l,n),"g"),NOT_HOST:new RegExp(t("[^\\%\\[\\]\\:]",l,n),"g"),NOT_PATH:new RegExp(t("[^\\%\\/\\:\\@]",l,n),"g"),NOT_PATH_NOSCHEME:new RegExp(t("[^\\%\\/\\@]",l,n),"g"),NOT_QUERY:new RegExp(t("[^\\%]",l,n,"[\\:\\@\\/\\?]",d),"g"),NOT_FRAGMENT:new RegExp(t("[^\\%]",l,n,"[\\:\\@\\/\\?]"),"g"),ESCAPE:new RegExp(t("[^]",l,n),"g"),UNRESERVED:new RegExp(l,"g"),OTHER_CHARS:new RegExp(t("[^\\%]",l,c),"g"),PCT_ENCODED:new RegExp(o,"g"),IPV4ADDRESS:new RegExp("^("+f+")$"),IPV6ADDRESS:new RegExp("^\\[?("+k+")"+r(r("\\%25|\\%(?!"+a+"{2})")+"("+C+")")+"?\\]?$")}}var o=a(!1),n=a(!0),c=function(e,t){if(Array.isArray(e))return e;if(Symbol.iterator in Object(e))return function(e,t){var r=[],s=!0,i=!1,a=void 0;try{for(var o,n=e[Symbol.iterator]();!(s=(o=n.next()).done)&&(r.push(o.value),!t||r.length!==t);s=!0);}catch(e){i=!0,a=e}finally{try{!s&&n.return&&n.return()}finally{if(i)throw a}}return r}(e,t);throw new TypeError("Invalid attempt to destructure non-iterable instance")},d=2147483647,l=36,u=/^xn--/,h=/[^\0-\x7E]/,p=/[\x2E\u3002\uFF0E\uFF61]/g,f={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},g=Math.floor,m=String.fromCharCode;function v(e){throw new RangeError(f[e])}function y(e,t){var r=e.split("@"),s="";return r.length>1&&(s=r[0]+"@",e=r[1]),s+function(e,t){for(var r=[],s=e.length;s--;)r[s]=t(e[s]);return r}((e=e.replace(p,".")).split("."),t).join(".")}function _(e){for(var t=[],r=0,s=e.length;r<s;){var i=e.charCodeAt(r++);if(i>=55296&&i<=56319&&r<s){var a=e.charCodeAt(r++);56320==(64512&a)?t.push(((1023&i)<<10)+(1023&a)+65536):(t.push(i),r--)}else t.push(i)}return t}var w=function(e){return e-48<10?e-22:e-65<26?e-65:e-97<26?e-97:l},b=function(e,t){return e+22+75*(e<26)-((0!=t)<<5)},S=function(e,t,r){var s=0;for(e=r?g(e/700):e>>1,e+=g(e/t);e>455;s+=l)e=g(e/35);return g(s+36*e/(e+38))},P=function(e){var t=[],r=e.length,s=0,i=128,a=72,o=e.lastIndexOf("-");o<0&&(o=0);for(var n=0;n<o;++n)e.charCodeAt(n)>=128&&v("not-basic"),t.push(e.charCodeAt(n));for(var c=o>0?o+1:0;c<r;){for(var u=s,h=1,p=l;;p+=l){c>=r&&v("invalid-input");var f=w(e.charCodeAt(c++));(f>=l||f>g((d-s)/h))&&v("overflow"),s+=f*h;var m=p<=a?1:p>=a+26?26:p-a;if(f<m)break;var y=l-m;h>g(d/y)&&v("overflow"),h*=y}var _=t.length+1;a=S(s-u,_,0==u),g(s/_)>d-i&&v("overflow"),i+=g(s/_),s%=_,t.splice(s++,0,i)}return String.fromCodePoint.apply(String,t)},E=function(e){var t=[],r=(e=_(e)).length,s=128,i=0,a=72,o=!0,n=!1,c=void 0;try{for(var u,h=e[Symbol.iterator]();!(o=(u=h.next()).done);o=!0){var p=u.value;p<128&&t.push(m(p))}}catch(e){n=!0,c=e}finally{try{!o&&h.return&&h.return()}finally{if(n)throw c}}var f=t.length,y=f;for(f&&t.push("-");y<r;){var w=d,P=!0,E=!1,I=void 0;try{for(var k,C=e[Symbol.iterator]();!(P=(k=C.next()).done);P=!0){var D=k.value;D>=s&&D<w&&(w=D)}}catch(e){E=!0,I=e}finally{try{!P&&C.return&&C.return()}finally{if(E)throw I}}var O=y+1;w-s>g((d-i)/O)&&v("overflow"),i+=(w-s)*O,s=w;var A=!0,x=!1,T=void 0;try{for(var R,$=e[Symbol.iterator]();!(A=(R=$.next()).done);A=!0){var j=R.value;if(j<s&&++i>d&&v("overflow"),j==s){for(var N=i,M=l;;M+=l){var F=M<=a?1:M>=a+26?26:M-a;if(N<F)break;var K=N-F,q=l-F;t.push(m(b(F+K%q,0))),N=g(K/q)}t.push(m(b(N,0))),a=S(i,O,y==f),i=0,++y}}}catch(e){x=!0,T=e}finally{try{!A&&$.return&&$.return()}finally{if(x)throw T}}++i,++s}return t.join("")},I=function(e){return y(e,function(e){return h.test(e)?"xn--"+E(e):e})},k=function(e){return y(e,function(e){return u.test(e)?P(e.slice(4).toLowerCase()):e})},C={};function D(e){var t=e.charCodeAt(0);return t<16?"%0"+t.toString(16).toUpperCase():t<128?"%"+t.toString(16).toUpperCase():t<2048?"%"+(t>>6|192).toString(16).toUpperCase()+"%"+(63&t|128).toString(16).toUpperCase():"%"+(t>>12|224).toString(16).toUpperCase()+"%"+(t>>6&63|128).toString(16).toUpperCase()+"%"+(63&t|128).toString(16).toUpperCase()}function O(e){for(var t="",r=0,s=e.length;r<s;){var i=parseInt(e.substr(r+1,2),16);if(i<128)t+=String.fromCharCode(i),r+=3;else if(i>=194&&i<224){if(s-r>=6){var a=parseInt(e.substr(r+4,2),16);t+=String.fromCharCode((31&i)<<6|63&a)}else t+=e.substr(r,6);r+=6}else if(i>=224){if(s-r>=9){var o=parseInt(e.substr(r+4,2),16),n=parseInt(e.substr(r+7,2),16);t+=String.fromCharCode((15&i)<<12|(63&o)<<6|63&n)}else t+=e.substr(r,9);r+=9}else t+=e.substr(r,3),r+=3}return t}function A(e,t){function r(e){var r=O(e);return r.match(t.UNRESERVED)?r:e}return e.scheme&&(e.scheme=String(e.scheme).replace(t.PCT_ENCODED,r).toLowerCase().replace(t.NOT_SCHEME,"")),void 0!==e.userinfo&&(e.userinfo=String(e.userinfo).replace(t.PCT_ENCODED,r).replace(t.NOT_USERINFO,D).replace(t.PCT_ENCODED,i)),void 0!==e.host&&(e.host=String(e.host).replace(t.PCT_ENCODED,r).toLowerCase().replace(t.NOT_HOST,D).replace(t.PCT_ENCODED,i)),void 0!==e.path&&(e.path=String(e.path).replace(t.PCT_ENCODED,r).replace(e.scheme?t.NOT_PATH:t.NOT_PATH_NOSCHEME,D).replace(t.PCT_ENCODED,i)),void 0!==e.query&&(e.query=String(e.query).replace(t.PCT_ENCODED,r).replace(t.NOT_QUERY,D).replace(t.PCT_ENCODED,i)),void 0!==e.fragment&&(e.fragment=String(e.fragment).replace(t.PCT_ENCODED,r).replace(t.NOT_FRAGMENT,D).replace(t.PCT_ENCODED,i)),e}function x(e){return e.replace(/^0*(.*)/,"$1")||"0"}function T(e,t){var r=e.match(t.IPV4ADDRESS)||[],s=c(r,2)[1];return s?s.split(".").map(x).join("."):e}function R(e,t){var r=e.match(t.IPV6ADDRESS)||[],s=c(r,3),i=s[1],a=s[2];if(i){for(var o=i.toLowerCase().split("::").reverse(),n=c(o,2),d=n[0],l=n[1],u=l?l.split(":").map(x):[],h=d.split(":").map(x),p=t.IPV4ADDRESS.test(h[h.length-1]),f=p?7:8,g=h.length-f,m=Array(f),v=0;v<f;++v)m[v]=u[v]||h[g+v]||"";p&&(m[f-1]=T(m[f-1],t));var y=m.reduce(function(e,t,r){if(!t||"0"===t){var s=e[e.length-1];s&&s.index+s.length===r?s.length++:e.push({index:r,length:1})}return e},[]).sort(function(e,t){return t.length-e.length})[0],_=void 0;if(y&&y.length>1){var w=m.slice(0,y.index),b=m.slice(y.index+y.length);_=w.join(":")+"::"+b.join(":")}else _=m.join(":");return a&&(_+="%"+a),_}return e}var $=/^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i,j=void 0==="".match(/(){0}/)[1];function N(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r={},s=!1!==t.iri?n:o;"suffix"===t.reference&&(e=(t.scheme?t.scheme+":":"")+"//"+e);var i=e.match($);if(i){j?(r.scheme=i[1],r.userinfo=i[3],r.host=i[4],r.port=parseInt(i[5],10),r.path=i[6]||"",r.query=i[7],r.fragment=i[8],isNaN(r.port)&&(r.port=i[5])):(r.scheme=i[1]||void 0,r.userinfo=-1!==e.indexOf("@")?i[3]:void 0,r.host=-1!==e.indexOf("//")?i[4]:void 0,r.port=parseInt(i[5],10),r.path=i[6]||"",r.query=-1!==e.indexOf("?")?i[7]:void 0,r.fragment=-1!==e.indexOf("#")?i[8]:void 0,isNaN(r.port)&&(r.port=e.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/)?i[4]:void 0)),r.host&&(r.host=R(T(r.host,s),s)),void 0!==r.scheme||void 0!==r.userinfo||void 0!==r.host||void 0!==r.port||r.path||void 0!==r.query?void 0===r.scheme?r.reference="relative":void 0===r.fragment?r.reference="absolute":r.reference="uri":r.reference="same-document",t.reference&&"suffix"!==t.reference&&t.reference!==r.reference&&(r.error=r.error||"URI is not a "+t.reference+" reference.");var a=C[(t.scheme||r.scheme||"").toLowerCase()];if(t.unicodeSupport||a&&a.unicodeSupport)A(r,s);else{if(r.host&&(t.domainHost||a&&a.domainHost))try{r.host=I(r.host.replace(s.PCT_ENCODED,O).toLowerCase())}catch(e){r.error=r.error||"Host's domain name can not be converted to ASCII via punycode: "+e}A(r,o)}a&&a.parse&&a.parse(r,t)}else r.error=r.error||"URI can not be parsed.";return r}var M=/^\.\.?\//,F=/^\/\.(\/|$)/,K=/^\/\.\.(\/|$)/,q=/^\/?(?:.|\n)*?(?=\/|$)/;function L(e){for(var t=[];e.length;)if(e.match(M))e=e.replace(M,"");else if(e.match(F))e=e.replace(F,"/");else if(e.match(K))e=e.replace(K,"/"),t.pop();else if("."===e||".."===e)e="";else{var r=e.match(q);if(!r)throw new Error("Unexpected dot segment condition");var s=r[0];e=e.slice(s.length),t.push(s)}return t.join("")}function U(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=t.iri?n:o,s=[],i=C[(t.scheme||e.scheme||"").toLowerCase()];if(i&&i.serialize&&i.serialize(e,t),e.host)if(r.IPV6ADDRESS.test(e.host));else if(t.domainHost||i&&i.domainHost)try{e.host=t.iri?k(e.host):I(e.host.replace(r.PCT_ENCODED,O).toLowerCase())}catch(r){e.error=e.error||"Host's domain name can not be converted to "+(t.iri?"Unicode":"ASCII")+" via punycode: "+r}A(e,r),"suffix"!==t.reference&&e.scheme&&(s.push(e.scheme),s.push(":"));var a=function(e,t){var r=!1!==t.iri?n:o,s=[];return void 0!==e.userinfo&&(s.push(e.userinfo),s.push("@")),void 0!==e.host&&s.push(R(T(String(e.host),r),r).replace(r.IPV6ADDRESS,function(e,t,r){return"["+t+(r?"%25"+r:"")+"]"})),"number"!=typeof e.port&&"string"!=typeof e.port||(s.push(":"),s.push(String(e.port))),s.length?s.join(""):void 0}(e,t);if(void 0!==a&&("suffix"!==t.reference&&s.push("//"),s.push(a),e.path&&"/"!==e.path.charAt(0)&&s.push("/")),void 0!==e.path){var c=e.path;t.absolutePath||i&&i.absolutePath||(c=L(c)),void 0===a&&(c=c.replace(/^\/\//,"/%2F")),s.push(c)}return void 0!==e.query&&(s.push("?"),s.push(e.query)),void 0!==e.fragment&&(s.push("#"),s.push(e.fragment)),s.join("")}function V(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},s={};return arguments[3]||(e=N(U(e,r),r),t=N(U(t,r),r)),!(r=r||{}).tolerant&&t.scheme?(s.scheme=t.scheme,s.userinfo=t.userinfo,s.host=t.host,s.port=t.port,s.path=L(t.path||""),s.query=t.query):(void 0!==t.userinfo||void 0!==t.host||void 0!==t.port?(s.userinfo=t.userinfo,s.host=t.host,s.port=t.port,s.path=L(t.path||""),s.query=t.query):(t.path?("/"===t.path.charAt(0)?s.path=L(t.path):(void 0===e.userinfo&&void 0===e.host&&void 0===e.port||e.path?e.path?s.path=e.path.slice(0,e.path.lastIndexOf("/")+1)+t.path:s.path=t.path:s.path="/"+t.path,s.path=L(s.path)),s.query=t.query):(s.path=e.path,void 0!==t.query?s.query=t.query:s.query=e.query),s.userinfo=e.userinfo,s.host=e.host,s.port=e.port),s.scheme=e.scheme),s.fragment=t.fragment,s}function H(e,t){return e&&e.toString().replace(t&&t.iri?n.PCT_ENCODED:o.PCT_ENCODED,O)}var B={scheme:"http",domainHost:!0,parse:function(e,t){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e},serialize:function(e,t){var r="https"===String(e.scheme).toLowerCase();return e.port!==(r?443:80)&&""!==e.port||(e.port=void 0),e.path||(e.path="/"),e}},z={scheme:"https",domainHost:B.domainHost,parse:B.parse,serialize:B.serialize};function J(e){return"boolean"==typeof e.secure?e.secure:"wss"===String(e.scheme).toLowerCase()}var W={scheme:"ws",domainHost:!0,parse:function(e,t){var r=e;return r.secure=J(r),r.resourceName=(r.path||"/")+(r.query?"?"+r.query:""),r.path=void 0,r.query=void 0,r},serialize:function(e,t){if(e.port!==(J(e)?443:80)&&""!==e.port||(e.port=void 0),"boolean"==typeof e.secure&&(e.scheme=e.secure?"wss":"ws",e.secure=void 0),e.resourceName){var r=e.resourceName.split("?"),s=c(r,2),i=s[0],a=s[1];e.path=i&&"/"!==i?i:void 0,e.query=a,e.resourceName=void 0}return e.fragment=void 0,e}},Z={scheme:"wss",domainHost:W.domainHost,parse:W.parse,serialize:W.serialize},Q={},G="[A-Za-z0-9\\-\\.\\_\\~\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]",Y="[0-9A-Fa-f]",X=r(r("%[EFef]"+Y+"%"+Y+Y+"%"+Y+Y)+"|"+r("%[89A-Fa-f]"+Y+"%"+Y+Y)+"|"+r("%"+Y+Y)),ee=t("[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]",'[\\"\\\\]'),te=new RegExp(G,"g"),re=new RegExp(X,"g"),se=new RegExp(t("[^]","[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]","[\\.]",'[\\"]',ee),"g"),ie=new RegExp(t("[^]",G,"[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]"),"g"),ae=ie;function oe(e){var t=O(e);return t.match(te)?t:e}var ne={scheme:"mailto",parse:function(e,t){var r=e,s=r.to=r.path?r.path.split(","):[];if(r.path=void 0,r.query){for(var i=!1,a={},o=r.query.split("&"),n=0,c=o.length;n<c;++n){var d=o[n].split("=");switch(d[0]){case"to":for(var l=d[1].split(","),u=0,h=l.length;u<h;++u)s.push(l[u]);break;case"subject":r.subject=H(d[1],t);break;case"body":r.body=H(d[1],t);break;default:i=!0,a[H(d[0],t)]=H(d[1],t)}}i&&(r.headers=a)}r.query=void 0;for(var p=0,f=s.length;p<f;++p){var g=s[p].split("@");if(g[0]=H(g[0]),t.unicodeSupport)g[1]=H(g[1],t).toLowerCase();else try{g[1]=I(H(g[1],t).toLowerCase())}catch(e){r.error=r.error||"Email address's domain name can not be converted to ASCII via punycode: "+e}s[p]=g.join("@")}return r},serialize:function(e,t){var r,s=e,a=null!=(r=e.to)?r instanceof Array?r:"number"!=typeof r.length||r.split||r.setInterval||r.call?[r]:Array.prototype.slice.call(r):[];if(a){for(var o=0,n=a.length;o<n;++o){var c=String(a[o]),d=c.lastIndexOf("@"),l=c.slice(0,d).replace(re,oe).replace(re,i).replace(se,D),u=c.slice(d+1);try{u=t.iri?k(u):I(H(u,t).toLowerCase())}catch(e){s.error=s.error||"Email address's domain name can not be converted to "+(t.iri?"Unicode":"ASCII")+" via punycode: "+e}a[o]=l+"@"+u}s.path=a.join(",")}var h=e.headers=e.headers||{};e.subject&&(h.subject=e.subject),e.body&&(h.body=e.body);var p=[];for(var f in h)h[f]!==Q[f]&&p.push(f.replace(re,oe).replace(re,i).replace(ie,D)+"="+h[f].replace(re,oe).replace(re,i).replace(ae,D));return p.length&&(s.query=p.join("&")),s}},ce=/^([^\:]+)\:(.*)/,de={scheme:"urn",parse:function(e,t){var r=e.path&&e.path.match(ce),s=e;if(r){var i=t.scheme||s.scheme||"urn",a=r[1].toLowerCase(),o=r[2],n=i+":"+(t.nid||a),c=C[n];s.nid=a,s.nss=o,s.path=void 0,c&&(s=c.parse(s,t))}else s.error=s.error||"URN can not be parsed.";return s},serialize:function(e,t){var r=t.scheme||e.scheme||"urn",s=e.nid,i=r+":"+(t.nid||s),a=C[i];a&&(e=a.serialize(e,t));var o=e,n=e.nss;return o.path=(s||t.nid)+":"+n,o}},le=/^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/,ue={scheme:"urn:uuid",parse:function(e,t){var r=e;return r.uuid=r.nss,r.nss=void 0,t.tolerant||r.uuid&&r.uuid.match(le)||(r.error=r.error||"UUID is not valid."),r},serialize:function(e,t){var r=e;return r.nss=(e.uuid||"").toLowerCase(),r}};C[B.scheme]=B,C[z.scheme]=z,C[W.scheme]=W,C[Z.scheme]=Z,C[ne.scheme]=ne,C[de.scheme]=de,C[ue.scheme]=ue,e.SCHEMES=C,e.pctEncChar=D,e.pctDecChars=O,e.parse=N,e.removeDotSegments=L,e.serialize=U,e.resolveComponents=V,e.resolve=function(e,t,r){var s=function(e,t){var r=e;if(t)for(var s in t)r[s]=t[s];return r}({scheme:"null"},r);return U(V(N(e,s),N(t,s),s,!0),s)},e.normalize=function(e,t){return"string"==typeof e?e=U(N(e,t),t):"object"===s(e)&&(e=N(U(e,t),t)),e},e.equal=function(e,t,r){return"string"==typeof e?e=U(N(e,r),r):"object"===s(e)&&(e=U(e,r)),"string"==typeof t?t=U(N(t,r),r):"object"===s(t)&&(t=U(t,r)),e===t},e.escapeComponent=function(e,t){return e&&e.toString().replace(t&&t.iri?n.ESCAPE:o.ESCAPE,D)},e.unescapeComponent=H,Object.defineProperty(e,"__esModule",{value:!0})}(t)},14547:e=>{"use strict";e.exports=function(e,t,r){var s=" ",i=e.level,a=e.dataLevel,o=e.schema[t],n=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,d=!e.opts.allErrors,l="data"+(a||""),u="valid"+i,h="errs__"+i,p=e.util.copy(e),f="";p.level++;var g="valid"+p.level,m=o.every(function(t){return e.opts.strictKeywords?"object"==typeof t&&Object.keys(t).length>0||!1===t:e.util.schemaHasRules(t,e.RULES.all)});if(m){var v=p.baseId;s+=" var "+h+" = errors; var "+u+" = false; ";var y=e.compositeRule;e.compositeRule=p.compositeRule=!0;var _=o;if(_)for(var w,b=-1,S=_.length-1;b<S;)w=_[b+=1],p.schema=w,p.schemaPath=n+"["+b+"]",p.errSchemaPath=c+"/"+b,s+=" "+e.validate(p)+" ",p.baseId=v,s+=" "+u+" = "+u+" || "+g+"; if (!"+u+") { ",f+="}";e.compositeRule=p.compositeRule=y,s+=" "+f+" if (!"+u+") { var err = ",!1!==e.createErrors?(s+=" { keyword: 'anyOf' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: {} ",!1!==e.opts.messages&&(s+=" , message: 'should match some schema in anyOf' "),e.opts.verbose&&(s+=" , schema: validate.schema"+n+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),s+=" } "):s+=" {} ",s+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&d&&(e.async?s+=" throw new ValidationError(vErrors); ":s+=" validate.errors = vErrors; return false; "),s+=" } else { errors = "+h+"; if (vErrors !== null) { if ("+h+") vErrors.length = "+h+"; else vErrors = null; } ",e.opts.allErrors&&(s+=" } ")}else d&&(s+=" if (true) { ");return s}},16928:e=>{"use strict";e.exports=require("path")},17214:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OAUTH_CORS_HEADERS=t.PREFLIGHT_CORS_HEADERS=t.MCP_CORS_HEADERS=t.WELL_KNOWN_CORS_HEADERS=void 0,t.mergeCORSHeaders=function(e,r=t.WELL_KNOWN_CORS_HEADERS){return{...e,...r}},t.applyCORSHeaders=function(e,r=t.MCP_CORS_HEADERS){Object.entries(r).forEach(([t,r])=>{void 0!==r&&e.setHeader(t,r)})},t.WELL_KNOWN_CORS_HEADERS={"Access-Control-Allow-Origin":"*",Vary:"Origin"},t.MCP_CORS_HEADERS={"Access-Control-Allow-Origin":"*","Access-Control-Expose-Headers":"mcp-session-id",Vary:"Origin"},t.PREFLIGHT_CORS_HEADERS={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, mcp-session-id, mcp-protocol-version",Vary:"Origin"},t.OAUTH_CORS_HEADERS={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, Accept, mcp-protocol-version","Access-Control-Expose-Headers":"Content-Type",Vary:"Origin"}},20698:(e,t,r)=>{"use strict";var s=r(52004),i=r(9717).toHash;e.exports=function(){var e=[{type:"number",rules:[{maximum:["exclusiveMaximum"]},{minimum:["exclusiveMinimum"]},"multipleOf","format"]},{type:"string",rules:["maxLength","minLength","pattern","format"]},{type:"array",rules:["maxItems","minItems","items","contains","uniqueItems"]},{type:"object",rules:["maxProperties","minProperties","required","dependencies","propertyNames",{properties:["additionalProperties","patternProperties"]}]},{rules:["$ref","const","enum","not","anyOf","oneOf","allOf","if"]}],t=["type","$comment"];return e.all=i(t),e.types=i(["number","integer","string","array","object","boolean","null"]),e.forEach(function(r){r.rules=r.rules.map(function(r){var i;if("object"==typeof r){var a=Object.keys(r)[0];i=r[a],r=a,i.forEach(function(r){t.push(r),e.all[r]=!0})}return t.push(r),e.all[r]={keyword:r,code:s[r],implements:i}}),e.all.$comment={keyword:"$comment",code:s.$comment},r.type&&(e.types[r.type]=r)}),e.keywords=i(t.concat(["$schema","$id","id","$data","$async","title","description","default","definitions","examples","readOnly","writeOnly","contentMediaType","contentEncoding","additionalItems","then","else"])),e.custom={},e}},20812:(e,t,r)=>{"use strict";var s=r(9717);e.exports=function(e){s.copy(e,this)}},22853:(e,t,r)=>{"use strict";var s=r(40985),i=r(9717),a=r(72916),o=r(56039),n=r(25572),c=i.ucs2length,d=r(67371),l=a.Validation;function u(e,t,r){var s=p.call(this,e,t,r);return s>=0?{index:s,compiling:!0}:(s=this._compilations.length,this._compilations[s]={schema:e,root:t,baseId:r},{index:s,compiling:!1})}function h(e,t,r){var s=p.call(this,e,t,r);s>=0&&this._compilations.splice(s,1)}function p(e,t,r){for(var s=0;s<this._compilations.length;s++){var i=this._compilations[s];if(i.schema==e&&i.root==t&&i.baseId==r)return s}return-1}function f(e,t){return"var pattern"+e+" = new RegExp("+i.toQuotedString(t[e])+");"}function g(e){return"var default"+e+" = defaults["+e+"];"}function m(e,t){return void 0===t[e]?"":"var refVal"+e+" = refVal["+e+"];"}function v(e){return"var customRule"+e+" = customRules["+e+"];"}function y(e,t){if(!e.length)return"";for(var r="",s=0;s<e.length;s++)r+=t(s,e);return r}e.exports=function e(t,r,p,_){var w=this,b=this._opts,S=[void 0],P={},E=[],I={},k=[],C={},D=[];r=r||{schema:t,refVal:S,refs:P};var O=u.call(this,t,r,_),A=this._compilations[O.index];if(O.compiling)return A.callValidate=function e(){var t=A.validate,r=t.apply(this,arguments);return e.errors=t.errors,r};var x=this._formats,T=this.RULES;try{var R=j(t,r,p,_);A.validate=R;var $=A.callValidate;return $&&($.schema=R.schema,$.errors=null,$.refs=R.refs,$.refVal=R.refVal,$.root=R.root,$.$async=R.$async,b.sourceCode&&($.source=R.source)),R}finally{h.call(this,t,r,_)}function j(t,o,u,h){var p=!o||o&&o.schema==t;if(o.schema!=r.schema)return e.call(w,t,o,u,h);var _,I=!0===t.$async,C=n({isTop:!0,schema:t,isRoot:p,baseId:h,root:o,schemaPath:"",errSchemaPath:"#",errorPath:'""',MissingRefError:a.MissingRef,RULES:T,validate:n,util:i,resolve:s,resolveRef:N,usePattern:K,useDefault:q,useCustomRule:L,opts:b,formats:x,logger:w.logger,self:w});C=y(S,m)+y(E,f)+y(k,g)+y(D,v)+C,b.processCode&&(C=b.processCode(C,t));try{_=new Function("self","RULES","formats","root","refVal","defaults","customRules","equal","ucs2length","ValidationError",C)(w,T,x,r,S,k,D,d,c,l),S[0]=_}catch(e){throw w.logger.error("Error compiling schema, function code:",C),e}return _.schema=t,_.errors=null,_.refs=P,_.refVal=S,_.root=p?_:o,I&&(_.$async=!0),!0===b.sourceCode&&(_.source={code:C,patterns:E,defaults:k}),_}function N(t,i,a){i=s.url(t,i);var o,n,c=P[i];if(void 0!==c)return F(o=S[c],n="refVal["+c+"]");if(!a&&r.refs){var d=r.refs[i];if(void 0!==d)return F(o=r.refVal[d],n=M(i,o))}n=M(i);var l=s.call(w,j,r,i);if(void 0===l){var u=p&&p[i];u&&(l=s.inlineRef(u,b.inlineRefs)?u:e.call(w,u,r,p,t))}if(void 0!==l)return function(e,t){var r=P[e];S[r]=t}(i,l),F(l,n);!function(e){delete P[e]}(i)}function M(e,t){var r=S.length;return S[r]=t,P[e]=r,"refVal"+r}function F(e,t){return"object"==typeof e||"boolean"==typeof e?{code:t,schema:e,inline:!0}:{code:t,$async:e&&!!e.$async}}function K(e){var t=I[e];return void 0===t&&(t=I[e]=E.length,E[t]=e),"pattern"+t}function q(e){switch(typeof e){case"boolean":case"number":return""+e;case"string":return i.toQuotedString(e);case"object":if(null===e)return"null";var t=o(e),r=C[t];return void 0===r&&(r=C[t]=k.length,k[r]=e),"default"+r}}function L(e,t,r,s){if(!1!==w._opts.validateSchema){var i=e.definition.dependencies;if(i&&!i.every(function(e){return Object.prototype.hasOwnProperty.call(r,e)}))throw new Error("parent schema must have all required keywords: "+i.join(","));var a=e.definition.validateSchema;if(a&&!a(t)){var o="keyword schema is invalid: "+w.errorsText(a.errors);if("log"!=w._opts.validateSchema)throw new Error(o);w.logger.error(o)}}var n,c=e.definition.compile,d=e.definition.inline,l=e.definition.macro;if(c)n=c.call(w,t,r,s);else if(l)n=l.call(w,t,r,s),!1!==b.validateSchema&&w.validateSchema(n,!0);else if(d)n=d.call(w,s,e.keyword,t,r);else if(!(n=e.definition.validate))return;if(void 0===n)throw new Error('custom keyword "'+e.keyword+'"failed to compile');var u=D.length;return D[u]=n,{code:"customRule"+u,validate:n}}}},23137:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MCPIRuntimeBase=void 0;const s=r(4901),i=r(81296),a=r(82906),o=r(65067);t.MCPIRuntimeBase=class{crypto;clock;fetch;storage;nonceCache;identity;config;cachedIdentity;sessions=new Map;lastProof;userDidManager;interceptedCalls=new Map;cryptoService;proofVerifier;accessControlService;constructor(e){this.config=e,this.crypto=e.cryptoProvider,this.clock=e.clockProvider,this.fetch=e.fetchProvider,this.storage=e.storageProvider,this.nonceCache=e.nonceCacheProvider,this.identity=e.identityProvider,this.cryptoService=new i.CryptoService(this.crypto)}async initialize(){this.cachedIdentity=await this.identity.getIdentity(),this.config.identity?.generateUserDids&&(this.userDidManager=new o.UserDidManager({crypto:this.crypto,storage:this.config.identity?.userDidStorage?{get:async e=>await this.storage.get(`userDid:${e}`),set:async(e,t,r)=>{await this.storage.set(`userDid:${e}`,t)},delete:async e=>await this.storage.delete(`userDid:${e}`)}:void 0,useDidWeb:"persistent"===this.config.identity?.userDidStorage})),"initialize"in this.nonceCache&&"function"==typeof this.nonceCache.initialize&&await this.nonceCache.initialize(),this.config.audit?.enabled&&this.logAudit("runtime_initialized",{did:this.cachedIdentity.did,environment:this.config.environment||"development",userDidGeneration:this.config.identity?.generateUserDids?"enabled":"disabled"})}async getIdentity(){return this.cachedIdentity||(this.cachedIdentity=await this.identity.getIdentity()),this.cachedIdentity}async handleHandshake(e){const t=await this.getIdentity(),r=this.clock.now(),s=await this.generateSessionId();let i;if(this.userDidManager)try{const t=e.oauthIdentity;i=await this.userDidManager.getOrCreateUserDid(s,t),this.config.audit?.enabled&&console.log("[MCP-I] Generated user DID for session:",{userDid:i.substring(0,20)+"...",hasOAuth:!!t,provider:t?.provider})}catch(e){console.warn("[MCP-I] Failed to generate user DID:",e)}const a=e=>{if("string"!=typeof e)return;const t=e.trim();return t.length>0?t:void 0},o=a(e.clientProtocolVersion),n=e.clientCapabilities,c=e.clientInfo,d=c||"string"==typeof o||void 0!==n?{name:a(c?.name)??"unknown",title:a(c?.title),version:a(c?.version),platform:a(c?.platform),vendor:a(c?.vendor),persistentId:a(c?.persistentId),clientId:a(c?.clientId)??crypto.randomUUID(),protocolVersion:o,capabilities:n}:void 0,l={id:s,clientDid:e.clientDid||i,userDid:i,agentDid:e.agentDid,serverDid:t.did,audience:e.audience,createdAt:r,expiresAt:this.clock.calculateExpiry(60*(this.config.session?.ttlMinutes||30)),clientInfo:d};this.sessions.set(s,l);const u={sessionId:s,agentDid:t.did,timestamp:r,capabilities:["identity","proof","audit"],...i&&{userDid:i}},h=await this.signData(u);return{...u,signature:h}}async processToolCall(e,t,r,i){if(this.config.toolProtectionService){const r=await this.getIdentity();this.config.audit?.enabled&&console.log("[MCP-I] Checking tool protection:",{tool:e,agentDid:r.did.slice(0,20)+"...",hasDelegation:!(!i?.delegationToken&&!i?.consentProof)});const o=await this.config.toolProtectionService.checkToolProtection(e,r.did);if(o){if(!i?.delegationToken&&!i?.consentProof){const a={toolName:e,args:t,sessionId:i?.id||"unknown",timestamp:this.clock.now(),expiresAt:this.clock.calculateExpiry(1800)},n=this.generateResumeToken(a),c=this.buildConsentUrl(e,o.requiredScopes,i,n),d=new s.DelegationRequiredError(e,o.requiredScopes,c,a,n);throw this.interceptedCalls.set(n,a),this.cleanupExpiredInterceptedCalls(),this.config.audit?.enabled&&console.warn("[MCP-I] BLOCKED: Tool requires delegation but none provided",{tool:e,requiredScopes:o.requiredScopes,agentDid:r.did.slice(0,20)+"...",resumeToken:d.resumeToken,consentUrl:c}),d}const n=i?.delegationToken,c=i?.consentProof;if(this.accessControlService)try{this.config.audit?.enabled&&console.log("[MCP-I] 🔐 Verifying delegation token with AccessControlApiService",{tool:e,agentDid:r.did.slice(0,20)+"...",hasDelegationToken:!!n,hasConsentProof:!!c,requiredScopes:o.requiredScopes});const a={agent_did:r.did,scopes:o.requiredScopes};n?a.delegation_token=n:c&&(a.credential_jwt=c),a.timestamp=this.clock.now(),(i?.clientDid||i?.clientId)&&(a.client_info={origin:i?.serverOrigin,user_agent:i?.userAgent});const d=await this.accessControlService.verifyDelegation(a,{delegationToken:n||void 0,credentialJwt:c||void 0});if(!d.data.valid){const a=d.data.reason||"Delegation token invalid or expired",n=d.data.error;this.config.audit?.enabled&&console.error("[MCP-I] ❌ Delegation verification FAILED",{tool:e,agentDid:r.did.slice(0,20)+"...",reason:a,errorCode:n?.code,errorMessage:n?.message,requiredScopes:o.requiredScopes});const c={toolName:e,args:t,sessionId:i?.id||"unknown",timestamp:this.clock.now(),expiresAt:this.clock.calculateExpiry(1800)},l=this.generateResumeToken(c),u=this.buildConsentUrl(e,o.requiredScopes,i,l);throw this.interceptedCalls.set(l,c),this.cleanupExpiredInterceptedCalls(),new s.DelegationRequiredError(e,o.requiredScopes,u,c,l)}const l=d.data.credential,u=l?.user_identifier,h=i?.userDid;if(u&&h){if(u!==h){u.substring(0,20),h.substring(0,20),this.config.audit?.enabled&&console.error("[MCP-I] 🔒 SECURITY: User identifier validation FAILED",{tool:e,agentDid:r.did.slice(0,20)+"...",delegationUserIdentifier:u.substring(0,20)+"...",sessionUserDid:h.substring(0,20)+"...",sessionId:i?.id?.substring(0,20)+"...",reason:"user_identifier_mismatch",severity:"high"});const a={toolName:e,args:t,sessionId:i?.id||"unknown",timestamp:this.clock.now(),expiresAt:this.clock.calculateExpiry(1800)},n=this.generateResumeToken(a),c=this.buildConsentUrl(e,o.requiredScopes,i,n);throw this.interceptedCalls.set(n,a),this.cleanupExpiredInterceptedCalls(),new s.DelegationRequiredError(e,o.requiredScopes,c,a,n)}this.config.audit?.enabled&&console.log("[MCP-I] ✅ User identifier validation PASSED",{tool:e,agentDid:r.did.slice(0,20)+"...",userDid:h.substring(0,20)+"...",sessionId:i?.id?.substring(0,20)+"..."})}else u&&!h&&this.config.audit?.enabled&&console.warn("[MCP-I] ⚠️ Delegation has user_identifier but session missing userDid",{tool:e,agentDid:r.did.slice(0,20)+"...",delegationUserIdentifier:u.substring(0,20)+"...",sessionId:i?.id?.substring(0,20)+"..."});this.config.audit?.enabled&&console.log("[MCP-I] ✅ Delegation verification SUCCEEDED",{tool:e,agentDid:r.did.slice(0,20)+"...",delegationId:d.data.delegation_id,credentialScopes:d.data.credential?.scopes,requiredScopes:o.requiredScopes})}catch(n){if(n instanceof s.DelegationRequiredError)throw n;if(n instanceof a.AgentShieldAPIError){this.config.audit?.enabled&&console.error("[MCP-I] ❌ Delegation verification error (API failure)",{tool:e,agentDid:r.did.slice(0,20)+"...",errorCode:n.code,errorMessage:n.message,errorDetails:n.details});const a={toolName:e,args:t,sessionId:i?.id||"unknown",timestamp:this.clock.now(),expiresAt:this.clock.calculateExpiry(1800)},c=this.generateResumeToken(a),d=this.buildConsentUrl(e,o.requiredScopes,i,c);throw this.interceptedCalls.set(c,a),this.cleanupExpiredInterceptedCalls(),new s.DelegationRequiredError(e,o.requiredScopes,d,a,c)}this.config.audit?.enabled&&console.error("[MCP-I] ❌ Unexpected error during delegation verification",{tool:e,agentDid:r.did.slice(0,20)+"...",error:n.message||String(n),errorStack:n.stack});const c={toolName:e,args:t,sessionId:i?.id||"unknown",timestamp:this.clock.now(),expiresAt:this.clock.calculateExpiry(1800)},d=this.generateResumeToken(c),l=this.buildConsentUrl(e,o.requiredScopes,i,d);throw this.interceptedCalls.set(d,c),this.cleanupExpiredInterceptedCalls(),new s.DelegationRequiredError(e,o.requiredScopes,l,c,d)}else this.config.audit?.enabled&&console.warn("[MCP-I] ⚠️ Delegation token provided but AccessControlApiService not configured - skipping verification",{tool:e,agentDid:r.did.slice(0,20)+"...",hasDelegationToken:!!n,hasConsentProof:!!c})}else this.config.audit?.enabled&&console.log("[MCP-I] Tool protection check passed (no delegation required)",{tool:e,agentDid:r.did.slice(0,20)+"...",reason:"Tool not configured to require delegation"})}const o=await r(t),n=await this.createProof(o,i);return this.lastProof=n,this.config.audit?.enabled&&this.logAudit("tool_executed",{tool:e,sessionId:i?.id,timestamp:this.clock.now()}),o}async resumeToolCall(e,t,r){const s=this.interceptedCalls.get(e);if(!s)throw new Error(`Invalid or expired resume token: ${e}`);if(this.clock.hasExpired(s.expiresAt))throw this.interceptedCalls.delete(e),new Error(`Resume token expired: ${e}`);const i=this.sessions.get(s.sessionId);if(!i)throw new Error(`Session not found for intercepted call: ${s.sessionId}`);const a={...i,delegationToken:r},o=await this.processToolCall(s.toolName,s.args,t,a);return this.interceptedCalls.delete(e),o}generateResumeToken(e){const t=JSON.stringify({tool:e.toolName,args:e.args,sessionId:e.sessionId,timestamp:e.timestamp});let r=0;for(let e=0;e<t.length;e++)r=(r<<5)-r+t.charCodeAt(e),r&=r;return`resume_${Math.abs(r).toString(36)}_${Date.now().toString(36)}`}cleanupExpiredInterceptedCalls(){this.clock.now();for(const[e,t]of this.interceptedCalls.entries())this.clock.hasExpired(t.expiresAt)&&this.interceptedCalls.delete(e)}buildConsentUrl(e,t,r,s,i){const a=new URLSearchParams({tool:e,scopes:t.join(","),session_id:r?.id||"",agent_did:r?.agentDid||""});return i&&a.set("project_id",i),s&&a.set("resume_token",s),`https://kya.vouched.id/bouncer/consent?${a.toString()}`}async issueNonce(e){const t=await this.generateNonce(),r=this.sessions.get(e),s=r?.agentDid||(await this.getIdentity()).did;return await this.nonceCache.add(t,300,s),t}async createProof(e,t){const r=await this.getIdentity(),s=this.clock.now();let i;if(t?.nonce)i=t.nonce;else{i=await this.generateNonce();const e=t?.agentDid||r.did;await this.nonceCache.add(i,300,e)}const a={data:e,timestamp:s,nonce:i,did:r.did,sessionId:t?.id,audience:t?.audience},o=await this.signData(a);return{timestamp:s,nonce:i,did:r.did,signature:o,algorithm:"Ed25519",sessionId:t?.id,audience:t?.audience}}async verifyProof(e,t){if(!(e&&"object"==typeof e&&"jws"in e&&"meta"in e))return this.verifyProofLegacy(e,t);{const r=e,s=t;if(!this.proofVerifier)return console.warn("[MCPIRuntimeBase] ProofVerifier not available, using fallback verification"),this.verifyProofLegacy(e,t);try{const e=await this.fetch.resolveDID(r.meta.did),t=this.extractPublicKeyJwk(e,r.meta.kid);if(!t)return console.error("[MCPIRuntimeBase] Failed to extract public key JWK"),!1;const i=await this.proofVerifier.verifyProof(r,t);if(i.valid&&s){const e=this.proofVerifier.buildCanonicalPayload(r.meta);s.canonicalPayload=e}return i.valid}catch(e){return console.error("[MCPIRuntimeBase] Proof verification failed:",e),!1}}}async verifyProofLegacy(e,t){try{if(await this.nonceCache.has(t.nonce,t.did))return!1;if(!this.clock.isWithinSkew(t.timestamp,this.config.session?.timestampSkewSeconds||120))return!1;const r=await this.fetch.resolveDID(t.did),s=this.extractPublicKey(r),i={data:e,timestamp:t.timestamp,nonce:t.nonce,did:t.did,sessionId:t.sessionId},a=(new TextEncoder).encode(JSON.stringify(i)),o=this.base64ToBytes(t.signature),n=await this.crypto.verify(a,o,s);if(n){const e=60*(this.config.session?.ttlMinutes||30);await this.nonceCache.add(t.nonce,e,t.did)}return n}catch(e){return console.error("Proof verification failed:",e),!1}}async verifyProofJWS(e,t,r){if(!this.cryptoService)return console.error("[MCPIRuntimeBase] CryptoService not initialized"),!1;try{const s=void 0!==r?{detachedPayload:r}:void 0;return await this.cryptoService.verifyJWS(e,t,s)}catch(e){return console.error("[MCPIRuntimeBase] JWS verification failed:",e),!1}}async getCurrentSession(){for(const[e,t]of this.sessions)if(!this.clock.hasExpired(t.expiresAt))return t;return null}getLastProof(){return this.lastProof}createWellKnownHandler(e){return async t=>{const r=await this.getIdentity();if("/.well-known/did.json"===t){const e=this.createDIDDocument(r);return{status:200,headers:{"Content-Type":"application/did+json","Cache-Control":"production"===this.config.environment?"public, max-age=300":"no-store"},body:JSON.stringify(e,null,2)}}if("/.well-known/agent.json"===t){const t={id:r.did,capabilities:{"mcp-i":["handshake","signing","verification"]}};return(e?.serviceName||e?.serviceEndpoint)&&(t.metadata={...e?.serviceName&&{name:e.serviceName},...e?.serviceEndpoint&&{serviceEndpoint:e.serviceEndpoint}}),{status:200,headers:{"Content-Type":"application/json","Cache-Control":"production"===this.config.environment?"public, max-age=300":"no-store"},body:JSON.stringify(t,null,2)}}return"/.well-known/mcp-identity"===t?{did:r.did,publicKey:r.publicKey,serviceName:e?.serviceName||"MCP-I Service",serviceEndpoint:e?.serviceEndpoint||"https://example.com",timestamp:this.clock.now()}:null}}createDebugEndpoint(){return"production"===this.config.environment?null:async()=>{const e=await this.getIdentity(),t=await this.getCurrentSession();return{identity:{did:e.did,publicKey:e.publicKey},session:t,config:{environment:this.config.environment,timestampSkewSeconds:this.config.session?.timestampSkewSeconds,sessionTtlMinutes:this.config.session?.ttlMinutes},timestamp:this.clock.now()}}}getAuditLogger(){return{log:(e,t)=>this.logAudit(e,t)}}async rotateKeys(){const e=this.cachedIdentity?.did,t=await this.identity.rotateKeys();return this.cachedIdentity=t,this.config.audit?.enabled&&this.logAudit("keys_rotated",{oldDid:e,newDid:t.did,timestamp:this.clock.now()}),t}async signData(e){const t=await this.getIdentity(),r=(new TextEncoder).encode(JSON.stringify(e)),s=await this.crypto.sign(r,t.privateKey);return this.bytesToBase64(s)}async generateNonce(){const e=await this.crypto.randomBytes(32);return this.bytesToBase64(e)}async generateSessionId(){const e=await this.crypto.randomBytes(16);return this.bytesToHex(e)}logAudit(e,t){if(!this.config.audit?.enabled)return;const r={event:e,data:this.config.audit.includePayloads?t:void 0,timestamp:this.clock.now(),timestampFormatted:this.clock.format(this.clock.now())},s=JSON.stringify(r);this.config.audit.logFunction?this.config.audit.logFunction(s):console.log("[AUDIT]",s)}createDIDDocument(e){return{"@context":["https://www.w3.org/ns/did/v1"],id:e.did,verificationMethod:[{id:`${e.did}#key-1`,type:"Ed25519VerificationKey2020",controller:e.did,publicKeyBase64:e.publicKey}],authentication:[`${e.did}#key-1`],assertionMethod:[`${e.did}#key-1`]}}extractPublicKey(e){const t=e.verificationMethod?.[0];if(t?.publicKeyBase64)return t.publicKeyBase64;if(t?.publicKeyMultibase)return t.publicKeyMultibase;throw new Error("Public key not found in DID document")}extractPublicKeyJwk(e,t){const r=e.verificationMethod?.find(e=>{const r="Ed25519VerificationKey2020"===e.type||"JsonWebKey2020"===e.type,s=!t||e.id===t||e.id.endsWith(`#${t}`);return r&&s})||e.verificationMethod?.[0];if(r?.publicKeyJwk){const e=r.publicKeyJwk;if("OKP"===e.kty&&"Ed25519"===e.crv)return e}return r?.publicKeyMultibase?(console.warn("[MCPIRuntimeBase] Multibase to JWK conversion not fully implemented"),null):null}bytesToBase64(e){return Buffer.from(e).toString("base64")}base64ToBytes(e){return new Uint8Array(Buffer.from(e,"base64"))}bytesToHex(e){return Buffer.from(e).toString("hex")}}},24235:e=>{"use strict";e.exports=function(e,t,r){var s=" ",i=e.level,a=e.dataLevel,o=e.schema[t],n=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,d=!e.opts.allErrors,l="data"+(a||""),u="valid"+i,h="errs__"+i,p=e.util.copy(e);p.level++;var f="valid"+p.level,g="i"+i,m=p.dataLevel=e.dataLevel+1,v="data"+m,y=e.baseId,_=e.opts.strictKeywords?"object"==typeof o&&Object.keys(o).length>0||!1===o:e.util.schemaHasRules(o,e.RULES.all);if(s+="var "+h+" = errors;var "+u+";",_){var w=e.compositeRule;e.compositeRule=p.compositeRule=!0,p.schema=o,p.schemaPath=n,p.errSchemaPath=c,s+=" var "+f+" = false; for (var "+g+" = 0; "+g+" < "+l+".length; "+g+"++) { ",p.errorPath=e.util.getPathExpr(e.errorPath,g,e.opts.jsonPointers,!0);var b=l+"["+g+"]";p.dataPathArr[m]=g;var S=e.validate(p);p.baseId=y,e.util.varOccurences(S,v)<2?s+=" "+e.util.varReplace(S,v,b)+" ":s+=" var "+v+" = "+b+"; "+S+" ",s+=" if ("+f+") break; } ",e.compositeRule=p.compositeRule=w,s+=" if (!"+f+") {"}else s+=" if ("+l+".length == 0) {";var P=P||[];P.push(s),s="",!1!==e.createErrors?(s+=" { keyword: 'contains' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: {} ",!1!==e.opts.messages&&(s+=" , message: 'should contain a valid item' "),e.opts.verbose&&(s+=" , schema: validate.schema"+n+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),s+=" } "):s+=" {} ";var E=s;return s=P.pop(),!e.compositeRule&&d?e.async?s+=" throw new ValidationError(["+E+"]); ":s+=" validate.errors = ["+E+"]; return false; ":s+=" var err = "+E+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+=" } else { ",_&&(s+=" errors = "+h+"; if (vErrors !== null) { if ("+h+") vErrors.length = "+h+"; else vErrors = null; } "),e.opts.allErrors&&(s+=" } "),s}},24886:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CascadingRevocationManager=void 0,t.createCascadingRevocationManager=function(e,t){return new r(e,t)};class r{graph;statusList;constructor(e,t){this.graph=e,this.statusList=t}async revokeDelegation(e,t={}){const r=t.maxDepth||100,s=[],i=await this.graph.getNode(e);if(!i)throw new Error(`Delegation not found: ${e}`);const a=await this.graph.getDepth(e);if(a>r)throw new Error(`Delegation depth ${a} exceeds maximum ${r}`);const o=await this.revokeNode(i,!0,t.reason,t.dryRun);s.push(o),t.onRevoke&&await t.onRevoke(o);const n=await this.graph.getDescendants(e);for(const r of n){const i=await this.revokeNode(r,!1,`Cascaded from ${e}`,t.dryRun,e);s.push(i),t.onRevoke&&await t.onRevoke(i)}return s}async revokeNode(e,t,r,s,i){const a={delegationId:e.id,isRoot:t,parentId:i,timestamp:Date.now(),reason:r};if(s)return a;if(e.credentialStatusId){const t=this.parseCredentialStatus(e.credentialStatusId);t&&await this.statusList.updateStatus(t,!0)}return a}async restoreDelegation(e){const t=await this.graph.getNode(e);if(!t)throw new Error(`Delegation not found: ${e}`);const r={delegationId:t.id,isRoot:!0,timestamp:Date.now(),reason:"Restored"};if(t.credentialStatusId){const e=this.parseCredentialStatus(t.credentialStatusId);e&&await this.statusList.updateStatus(e,!1)}return r}async isRevoked(e){const t=await this.graph.getChain(e);for(const r of t.reverse())if(r.credentialStatusId){const t=this.parseCredentialStatus(r.credentialStatusId);if(t&&await this.statusList.checkStatus(t))return{revoked:!0,reason:r.id===e?"Directly revoked":"Ancestor revoked",revokedAncestor:r.id===e?void 0:r.id}}return{revoked:!1}}async getRevokedInSubtree(e){const t=await this.graph.getDescendants(e),r=[];(await this.isRevoked(e)).revoked&&r.push(e);for(const e of t)(await this.isRevoked(e.id)).revoked&&r.push(e.id);return r}parseCredentialStatus(e){const t=e.match(/^(.+)#(\d+)$/);if(!t)return null;const[,r,s]=t;return{id:e,type:"StatusList2021Entry",statusPurpose:"revocation",statusListIndex:parseInt(s,10).toString(),statusListCredential:r}}async validateDelegation(e){const t=await this.isRevoked(e);if(t.revoked)return{valid:!1,reason:t.revokedAncestor?`Ancestor ${t.revokedAncestor} is revoked`:"Delegation is revoked"};const r=await this.graph.validateChain(e);return r.valid?{valid:!0}:r}}t.CascadingRevocationManager=r},25572:e=>{"use strict";e.exports=function(e,t,r){var s="",i=!0===e.schema.$async,a=e.util.schemaHasRulesExcept(e.schema,e.RULES.all,"$ref"),o=e.self._getId(e.schema);if(e.opts.strictKeywords){var n=e.util.schemaUnknownRules(e.schema,e.RULES.keywords);if(n){var c="unknown keyword: "+n;if("log"!==e.opts.strictKeywords)throw new Error(c);e.logger.warn(c)}}if(e.isTop&&(s+=" var validate = ",i&&(e.async=!0,s+="async "),s+="function(data, dataPath, parentData, parentDataProperty, rootData) { 'use strict'; ",o&&(e.opts.sourceCode||e.opts.processCode)&&(s+=" /*# sourceURL="+o+" */ ")),"boolean"==typeof e.schema||!a&&!e.schema.$ref){t="false schema";var d=e.level,l=e.dataLevel,u=e.schema[t],h=e.schemaPath+e.util.getProperty(t),p=e.errSchemaPath+"/"+t,f=!e.opts.allErrors,g="data"+(l||""),m="valid"+d;if(!1===e.schema){e.isTop?f=!0:s+=" var "+m+" = false; ",(B=B||[]).push(s),s="",!1!==e.createErrors?(s+=" { keyword: 'false schema' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(p)+" , params: {} ",!1!==e.opts.messages&&(s+=" , message: 'boolean schema is false' "),e.opts.verbose&&(s+=" , schema: false , parentSchema: validate.schema"+e.schemaPath+" , data: "+g+" "),s+=" } "):s+=" {} ";var v=s;s=B.pop(),!e.compositeRule&&f?e.async?s+=" throw new ValidationError(["+v+"]); ":s+=" validate.errors = ["+v+"]; return false; ":s+=" var err = "+v+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}else e.isTop?s+=i?" return data; ":" validate.errors = null; return true; ":s+=" var "+m+" = true; ";return e.isTop&&(s+=" }; return validate; "),s}if(e.isTop){var y=e.isTop;if(d=e.level=0,l=e.dataLevel=0,g="data",e.rootId=e.resolve.fullPath(e.self._getId(e.root.schema)),e.baseId=e.baseId||e.rootId,delete e.isTop,e.dataPathArr=[""],void 0!==e.schema.default&&e.opts.useDefaults&&e.opts.strictDefaults){var _="default is ignored in the schema root";if("log"!==e.opts.strictDefaults)throw new Error(_);e.logger.warn(_)}s+=" var vErrors = null; ",s+=" var errors = 0; ",s+=" if (rootData === undefined) rootData = data; "}else{if(d=e.level,g="data"+((l=e.dataLevel)||""),o&&(e.baseId=e.resolve.url(e.baseId,o)),i&&!e.async)throw new Error("async schema in sync schema");s+=" var errs_"+d+" = errors;"}m="valid"+d,f=!e.opts.allErrors;var w="",b="",S=e.schema.type,P=Array.isArray(S);if(S&&e.opts.nullable&&!0===e.schema.nullable&&(P?-1==S.indexOf("null")&&(S=S.concat("null")):"null"!=S&&(S=[S,"null"],P=!0)),P&&1==S.length&&(S=S[0],P=!1),e.schema.$ref&&a){if("fail"==e.opts.extendRefs)throw new Error('$ref: validation keywords used in schema at path "'+e.errSchemaPath+'" (see option extendRefs)');!0!==e.opts.extendRefs&&(a=!1,e.logger.warn('$ref: keywords ignored in schema at path "'+e.errSchemaPath+'"'))}if(e.schema.$comment&&e.opts.$comment&&(s+=" "+e.RULES.all.$comment.code(e,"$comment")),S){if(e.opts.coerceTypes)var E=e.util.coerceToTypes(e.opts.coerceTypes,S);var I=e.RULES.types[S];if(E||P||!0===I||I&&!G(I)){h=e.schemaPath+".type",p=e.errSchemaPath+"/type",h=e.schemaPath+".type",p=e.errSchemaPath+"/type";var k=P?"checkDataTypes":"checkDataType";if(s+=" if ("+e.util[k](S,g,e.opts.strictNumbers,!0)+") { ",E){var C="dataType"+d,D="coerced"+d;s+=" var "+C+" = typeof "+g+"; var "+D+" = undefined; ","array"==e.opts.coerceTypes&&(s+=" if ("+C+" == 'object' && Array.isArray("+g+") && "+g+".length == 1) { "+g+" = "+g+"[0]; "+C+" = typeof "+g+"; if ("+e.util.checkDataType(e.schema.type,g,e.opts.strictNumbers)+") "+D+" = "+g+"; } "),s+=" if ("+D+" !== undefined) ; ";var O=E;if(O)for(var A,x=-1,T=O.length-1;x<T;)"string"==(A=O[x+=1])?s+=" else if ("+C+" == 'number' || "+C+" == 'boolean') "+D+" = '' + "+g+"; else if ("+g+" === null) "+D+" = ''; ":"number"==A||"integer"==A?(s+=" else if ("+C+" == 'boolean' || "+g+" === null || ("+C+" == 'string' && "+g+" && "+g+" == +"+g+" ","integer"==A&&(s+=" && !("+g+" % 1)"),s+=")) "+D+" = +"+g+"; "):"boolean"==A?s+=" else if ("+g+" === 'false' || "+g+" === 0 || "+g+" === null) "+D+" = false; else if ("+g+" === 'true' || "+g+" === 1) "+D+" = true; ":"null"==A?s+=" else if ("+g+" === '' || "+g+" === 0 || "+g+" === false) "+D+" = null; ":"array"==e.opts.coerceTypes&&"array"==A&&(s+=" else if ("+C+" == 'string' || "+C+" == 'number' || "+C+" == 'boolean' || "+g+" == null) "+D+" = ["+g+"]; ");s+=" else { ",(B=B||[]).push(s),s="",!1!==e.createErrors?(s+=" { keyword: 'type' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(p)+" , params: { type: '",s+=P?""+S.join(","):""+S,s+="' } ",!1!==e.opts.messages&&(s+=" , message: 'should be ",s+=P?""+S.join(","):""+S,s+="' "),e.opts.verbose&&(s+=" , schema: validate.schema"+h+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+g+" "),s+=" } "):s+=" {} ",v=s,s=B.pop(),!e.compositeRule&&f?e.async?s+=" throw new ValidationError(["+v+"]); ":s+=" validate.errors = ["+v+"]; return false; ":s+=" var err = "+v+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+=" } if ("+D+" !== undefined) { ";var R=l?"data"+(l-1||""):"parentData";s+=" "+g+" = "+D+"; ",l||(s+="if ("+R+" !== undefined)"),s+=" "+R+"["+(l?e.dataPathArr[l]:"parentDataProperty")+"] = "+D+"; } "}else(B=B||[]).push(s),s="",!1!==e.createErrors?(s+=" { keyword: 'type' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(p)+" , params: { type: '",s+=P?""+S.join(","):""+S,s+="' } ",!1!==e.opts.messages&&(s+=" , message: 'should be ",s+=P?""+S.join(","):""+S,s+="' "),e.opts.verbose&&(s+=" , schema: validate.schema"+h+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+g+" "),s+=" } "):s+=" {} ",v=s,s=B.pop(),!e.compositeRule&&f?e.async?s+=" throw new ValidationError(["+v+"]); ":s+=" validate.errors = ["+v+"]; return false; ":s+=" var err = "+v+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";s+=" } "}}if(e.schema.$ref&&!a)s+=" "+e.RULES.all.$ref.code(e,"$ref")+" ",f&&(s+=" } if (errors === ",s+=y?"0":"errs_"+d,s+=") { ",b+="}");else{var $=e.RULES;if($)for(var j=-1,N=$.length-1;j<N;)if(G(I=$[j+=1])){if(I.type&&(s+=" if ("+e.util.checkDataType(I.type,g,e.opts.strictNumbers)+") { "),e.opts.useDefaults)if("object"==I.type&&e.schema.properties){u=e.schema.properties;var M=Object.keys(u);if(M)for(var F,K=-1,q=M.length-1;K<q;)if(void 0!==(V=u[F=M[K+=1]]).default){var L=g+e.util.getProperty(F);if(e.compositeRule){if(e.opts.strictDefaults){if(_="default is ignored for: "+L,"log"!==e.opts.strictDefaults)throw new Error(_);e.logger.warn(_)}}else s+=" if ("+L+" === undefined ","empty"==e.opts.useDefaults&&(s+=" || "+L+" === null || "+L+" === '' "),s+=" ) "+L+" = ","shared"==e.opts.useDefaults?s+=" "+e.useDefault(V.default)+" ":s+=" "+JSON.stringify(V.default)+" ",s+="; "}}else if("array"==I.type&&Array.isArray(e.schema.items)){var U=e.schema.items;if(U){x=-1;for(var V,H=U.length-1;x<H;)if(void 0!==(V=U[x+=1]).default)if(L=g+"["+x+"]",e.compositeRule){if(e.opts.strictDefaults){if(_="default is ignored for: "+L,"log"!==e.opts.strictDefaults)throw new Error(_);e.logger.warn(_)}}else s+=" if ("+L+" === undefined ","empty"==e.opts.useDefaults&&(s+=" || "+L+" === null || "+L+" === '' "),s+=" ) "+L+" = ","shared"==e.opts.useDefaults?s+=" "+e.useDefault(V.default)+" ":s+=" "+JSON.stringify(V.default)+" ",s+="; "}}var B,z=I.rules;if(z)for(var J,W=-1,Z=z.length-1;W<Z;)if(Y(J=z[W+=1])){var Q=J.code(e,J.keyword,I.type);Q&&(s+=" "+Q+" ",f&&(w+="}"))}if(f&&(s+=" "+w+" ",w=""),I.type&&(s+=" } ",S&&S===I.type&&!E))s+=" else { ",h=e.schemaPath+".type",p=e.errSchemaPath+"/type",(B=B||[]).push(s),s="",!1!==e.createErrors?(s+=" { keyword: 'type' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(p)+" , params: { type: '",s+=P?""+S.join(","):""+S,s+="' } ",!1!==e.opts.messages&&(s+=" , message: 'should be ",s+=P?""+S.join(","):""+S,s+="' "),e.opts.verbose&&(s+=" , schema: validate.schema"+h+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+g+" "),s+=" } "):s+=" {} ",v=s,s=B.pop(),!e.compositeRule&&f?e.async?s+=" throw new ValidationError(["+v+"]); ":s+=" validate.errors = ["+v+"]; return false; ":s+=" var err = "+v+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+=" } ";f&&(s+=" if (errors === ",s+=y?"0":"errs_"+d,s+=") { ",b+="}")}}function G(e){for(var t=e.rules,r=0;r<t.length;r++)if(Y(t[r]))return!0}function Y(t){return void 0!==e.schema[t.keyword]||t.implements&&function(t){for(var r=t.implements,s=0;s<r.length;s++)if(void 0!==e.schema[r[s]])return!0}(t)}return f&&(s+=" "+b+" "),y?(i?(s+=" if (errors === 0) return data; ",s+=" else throw new ValidationError(vErrors); "):(s+=" validate.errors = vErrors; ",s+=" return errors === 0; "),s+=" }; return validate;"):s+=" var "+m+" = errors === errs_"+d+";",s}},27087:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.IdentityProvider=t.NonceCacheProvider=t.StorageProvider=t.FetchProvider=t.ClockProvider=t.CryptoProvider=void 0,t.CryptoProvider=class{},t.ClockProvider=class{},t.FetchProvider=class{},t.StorageProvider=class{},t.NonceCacheProvider=class{},t.IdentityProvider=class{}},27399:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OAuthRequiredError=void 0;class r extends Error{toolName;requiredScopes;provider;oauthUrl;resumeToken;userDid;sessionId;constructor(e){const{toolName:t,requiredScopes:r,provider:s,oauthUrl:i}=e;super(`OAuth required for tool "${t}" with provider "${s}". Required scopes: ${r.join(", ")}`),this.name="OAuthRequiredError",this.toolName=t,this.requiredScopes=r,this.provider=s,this.oauthUrl=i,this.resumeToken=e.resumeToken,this.userDid=e.userDid,this.sessionId=e.sessionId}}t.OAuthRequiredError=r},27713:e=>{"use strict";var t=e.exports=function(e,t,s){"function"==typeof t&&(s=t,t={}),r(t,"function"==typeof(s=t.cb||s)?s:s.pre||function(){},s.post||function(){},e,"",e)};function r(e,i,a,o,n,c,d,l,u,h){if(o&&"object"==typeof o&&!Array.isArray(o)){for(var p in i(o,n,c,d,l,u,h),o){var f=o[p];if(Array.isArray(f)){if(p in t.arrayKeywords)for(var g=0;g<f.length;g++)r(e,i,a,f[g],n+"/"+p+"/"+g,c,n,p,o,g)}else if(p in t.propsKeywords){if(f&&"object"==typeof f)for(var m in f)r(e,i,a,f[m],n+"/"+p+"/"+s(m),c,n,p,o,m)}else(p in t.keywords||e.allKeys&&!(p in t.skipKeywords))&&r(e,i,a,f,n+"/"+p,c,n,p,o)}a(o,n,c,d,l,u,h)}}function s(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}t.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0},t.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},t.propsKeywords={definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},t.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0}},28565:e=>{"use strict";var t=e.exports=function(){this._cache={}};t.prototype.put=function(e,t){this._cache[e]=t},t.prototype.get=function(e){return this._cache[e]},t.prototype.del=function(e){delete this._cache[e]},t.prototype.clear=function(){this._cache={}}},28717:e=>{"use strict";e.exports=require("@kya-os/contracts/proof")},30124:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BatchDelegationService=void 0,t.BatchDelegationService=class{providerResolver;toolProtectionService;constructor(e,t){this.providerResolver=e,this.toolProtectionService=t}async groupToolsByProvider(e,t,r){const s=new Map;for(const i of e){const e=await this.toolProtectionService.checkToolProtection(i,r);if(!e?.requiresDelegation)continue;let a;try{a=await this.providerResolver.resolveProvider(e,t)}catch(e){console.warn(`[BatchDelegation] Could not resolve provider for tool "${i}", skipping`,e instanceof Error?e.message:String(e));continue}s.has(a)||s.set(a,{provider:a,tools:[],scopes:[],riskLevel:"medium"});const o=s.get(a);o.tools.push(i);const n=new Set([...o.scopes,...e.requiredScopes||[]]);if(o.scopes=Array.from(n),e.riskLevel){const t={low:1,medium:2,high:3,critical:4},r=t[o.riskLevel]||1;(t[e.riskLevel]||1)>r&&(o.riskLevel="critical"===e.riskLevel?"high":e.riskLevel)}}return s}async getToolsForProvider(e,t,r){return[]}}},30845:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DelegationCredentialIssuer=void 0,t.createDelegationIssuer=function(e,t){return new a(e,t)};const s=r(62408),i=r(63969);class a{identity;signingFunction;constructor(e,t){this.identity=e,this.signingFunction=t}async issueDelegationCredential(e,t={}){let r=(0,s.wrapDelegationAsVC)(e,{id:t.id,issuanceDate:t.issuanceDate,expirationDate:t.expirationDate,credentialStatus:t.credentialStatus});if(t.additionalContexts&&t.additionalContexts.length>0){const e=r["@context"];r={...r,"@context":[...e,...t.additionalContexts]}}const i=this.canonicalizeVC(r),a=await this.signingFunction(i,this.identity.getDid(),this.identity.getKeyId());return{...r,proof:a}}async createAndIssueDelegation(e,t={}){const r=Date.now(),s={id:e.id,issuerDid:e.issuerDid,subjectDid:e.subjectDid,controller:e.controller,vcId:t.id||`urn:uuid:${e.id}`,parentId:e.parentId,constraints:e.constraints,signature:"",status:e.status||"active",createdAt:r,metadata:e.metadata};return this.issueDelegationCredential(s,t)}canonicalizeVC(e){return(0,i.canonicalizeJSON)(e)}getIssuerDid(){return this.identity.getDid()}getIssuerKeyId(){return this.identity.getKeyId()}}t.DelegationCredentialIssuer=a},32299:(e,t)=>{"use strict";function r(e){return`agent:${e}:delegation`}function s(e,t,r){return r?`delegation:user:${e}:agent:${t}:project:${r}`:`delegation:user:${e}:agent:${t}`}function i(e){return`session:${e}`}function a(e,t){return`userDid:oauth:${e}:${t}`}function o(e,t){return`oauth:${e}:${t}`}function n(e){return`verified:${e}`}function c(e){return`nonce:${e}`}Object.defineProperty(t,"__esModule",{value:!0}),t.STORAGE_KEYS=void 0,t.legacyDelegationKey=r,t.compositeDelegationKey=s,t.sessionKey=i,t.userDidKey=a,t.oauthIdentityKey=o,t.verificationCacheKey=n,t.nonceKey=c,t.migrateDelegationKeys=async function(e,t={}){const r={migrated:0,failed:0,migrations:[],errors:[]};try{const i=(await e.list("agent:")).filter(e=>e.match(/^agent:[^:]+:delegation$/));console.log(`Found ${i.length} legacy delegation keys to migrate`);for(const a of i)try{const i=a.match(/^agent:([^:]+):delegation$/);if(!i){r.errors.push({key:a,error:"Invalid legacy key format"}),r.failed++;continue}const o=i[1],n=await e.get(a);if(!n)continue;let c,d=null;const l=await e.list("session:");for(const t of l){const r=await e.get(t);if(r)try{const e=JSON.parse(r);if(e.userDid&&e.agentDid===o){d=e.userDid;const r=t.match(/^session:(.+)$/);r&&(c=r[1]);break}}catch{}}if(t.resolveUserDid){const e=await t.resolveUserDid(o,c);e&&(d=e)}if(!d){r.errors.push({key:a,error:"Cannot resolve userDid - skipping migration"}),r.failed++;continue}const u=s(d,o);t.dryRun?(r.migrations.push({oldKey:a,newKey:u}),r.migrated++):(await e.set(u,n),r.migrations.push({oldKey:a,newKey:u}),r.migrated++,t.deleteOldKeys&&await e.delete(a))}catch(e){r.errors.push({key:a,error:e instanceof Error?e.message:String(e)}),r.failed++}}catch(e){r.errors.push({key:"migration",error:e instanceof Error?e.message:String(e)})}return r},t.STORAGE_KEYS={userDid:a,oauthIdentity:o,delegation:s,session:i,legacyDelegation:r,verificationCache:n,nonce:c}},33728:e=>{"use strict";e.exports=function(e,t,r){var s=" ",i=e.level,a=e.dataLevel,o=e.schema[t],n=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,d=!e.opts.allErrors,l="data"+(a||""),u="valid"+i,h="errs__"+i,p=e.util.copy(e),f="";p.level++;var g="valid"+p.level,m="i"+i,v=p.dataLevel=e.dataLevel+1,y="data"+v,_=e.baseId;if(s+="var "+h+" = errors;var "+u+";",Array.isArray(o)){var w=e.schema.additionalItems;if(!1===w){s+=" "+u+" = "+l+".length <= "+o.length+"; ";var b=c;c=e.errSchemaPath+"/additionalItems",s+=" if (!"+u+") { ";var S=S||[];S.push(s),s="",!1!==e.createErrors?(s+=" { keyword: 'additionalItems' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { limit: "+o.length+" } ",!1!==e.opts.messages&&(s+=" , message: 'should NOT have more than "+o.length+" items' "),e.opts.verbose&&(s+=" , schema: false , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),s+=" } "):s+=" {} ";var P=s;s=S.pop(),!e.compositeRule&&d?e.async?s+=" throw new ValidationError(["+P+"]); ":s+=" validate.errors = ["+P+"]; return false; ":s+=" var err = "+P+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+=" } ",c=b,d&&(f+="}",s+=" else { ")}var E=o;if(E)for(var I,k=-1,C=E.length-1;k<C;)if(I=E[k+=1],e.opts.strictKeywords?"object"==typeof I&&Object.keys(I).length>0||!1===I:e.util.schemaHasRules(I,e.RULES.all)){s+=" "+g+" = true; if ("+l+".length > "+k+") { ";var D=l+"["+k+"]";p.schema=I,p.schemaPath=n+"["+k+"]",p.errSchemaPath=c+"/"+k,p.errorPath=e.util.getPathExpr(e.errorPath,k,e.opts.jsonPointers,!0),p.dataPathArr[v]=k;var O=e.validate(p);p.baseId=_,e.util.varOccurences(O,y)<2?s+=" "+e.util.varReplace(O,y,D)+" ":s+=" var "+y+" = "+D+"; "+O+" ",s+=" } ",d&&(s+=" if ("+g+") { ",f+="}")}"object"==typeof w&&(e.opts.strictKeywords?"object"==typeof w&&Object.keys(w).length>0||!1===w:e.util.schemaHasRules(w,e.RULES.all))&&(p.schema=w,p.schemaPath=e.schemaPath+".additionalItems",p.errSchemaPath=e.errSchemaPath+"/additionalItems",s+=" "+g+" = true; if ("+l+".length > "+o.length+") { for (var "+m+" = "+o.length+"; "+m+" < "+l+".length; "+m+"++) { ",p.errorPath=e.util.getPathExpr(e.errorPath,m,e.opts.jsonPointers,!0),D=l+"["+m+"]",p.dataPathArr[v]=m,O=e.validate(p),p.baseId=_,e.util.varOccurences(O,y)<2?s+=" "+e.util.varReplace(O,y,D)+" ":s+=" var "+y+" = "+D+"; "+O+" ",d&&(s+=" if (!"+g+") break; "),s+=" } } ",d&&(s+=" if ("+g+") { ",f+="}"))}else(e.opts.strictKeywords?"object"==typeof o&&Object.keys(o).length>0||!1===o:e.util.schemaHasRules(o,e.RULES.all))&&(p.schema=o,p.schemaPath=n,p.errSchemaPath=c,s+=" for (var "+m+" = 0; "+m+" < "+l+".length; "+m+"++) { ",p.errorPath=e.util.getPathExpr(e.errorPath,m,e.opts.jsonPointers,!0),D=l+"["+m+"]",p.dataPathArr[v]=m,O=e.validate(p),p.baseId=_,e.util.varOccurences(O,y)<2?s+=" "+e.util.varReplace(O,y,D)+" ":s+=" var "+y+" = "+D+"; "+O+" ",d&&(s+=" if (!"+g+") break; "),s+=" }");return d&&(s+=" "+f+" if ("+h+" == errors) {"),s}},36255:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AccessControlApiService=void 0;const s=r(82906),i=r(82906);function a(){return"undefined"!=typeof crypto&&crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).substring(2,15)}`}t.AccessControlApiService=class{config;metrics;constructor(e){const t=e.retryConfig||{};this.config={retryConfig:{maxRetries:t.maxRetries??3,initialDelayMs:t.initialDelayMs??100,maxDelayMs:t.maxDelayMs??5e3},logger:e.logger||(()=>{}),baseUrl:e.baseUrl,apiKey:e.apiKey,fetchProvider:e.fetchProvider,sleepProvider:e.sleepProvider||(e=>new Promise(t=>setTimeout(t,e)))},this.metrics={successCount:0,errorCount:0,retryCount:0}}async fetchConfig(e){return this.retryWithBackoff(async()=>{const t=a(),r=`${this.config.baseUrl}/api/v1/bouncer/config?agent_did=${encodeURIComponent(e.agentDid)}`;this.config.logger(`[AccessControl] Fetching config for agent: ${e.agentDid}`,{correlationId:t,url:r});const o=await this.config.fetchProvider.fetch(r,{method:"GET",headers:{Authorization:`Bearer ${this.config.apiKey}`,"Content-Type":"application/json","X-Request-ID":t}}),n=await o.text(),c=this.parseResponseJSON(o,n);o.ok||this.handleErrorResponse(o,c);const d=s.toolProtectionConfigAPIResponseSchema.safeParse(c);if(!d.success)throw new i.AgentShieldAPIError("invalid_response","Response validation failed",{zodErrors:d.error.errors});return this.config.logger("[AccessControl] Config fetched successfully",{correlationId:t,agentDid:e.agentDid}),d.data})}async verifyDelegation(e,t){return this.retryWithBackoff(async()=>{const r=a(),o=`${this.config.baseUrl}/api/v1/bouncer/delegations/verify`,n={agent_did:e.agent_did};void 0!==e.scopes&&(n.scopes=e.scopes),void 0!==e.credential_jwt?n.credential_jwt=e.credential_jwt:t?.credentialJwt&&(n.credential_jwt=t.credentialJwt),void 0!==e.delegation_token?n.delegation_token=e.delegation_token:t?.delegationToken&&(n.delegation_token=t.delegationToken),void 0!==e.timestamp&&(n.timestamp=e.timestamp),e.client_info&&(n.client_info=e.client_info);const c=Object.fromEntries(Object.entries(n).filter(([e,t])=>void 0!==t)),d=s.verifyDelegationRequestSchema.safeParse(c);if(!d.success&&(!d.error.errors.find(e=>e.path.includes("scopes")&&"Required"===e.message)||"scopes"in c))throw this.config.logger("[AccessControl] Validation failed:",{errors:d.error.errors,requestBody:n}),new i.AgentShieldAPIError("validation_error","Request validation failed",{zodErrors:d.error.errors});this.config.logger(`[AccessControl] Verifying delegation for agent: ${e.agent_did}`,{correlationId:r,url:o,hasScopes:(e.scopes?.length||0)>0});const l=await this.config.fetchProvider.fetch(o,{method:"POST",headers:{Authorization:`Bearer ${this.config.apiKey}`,"Content-Type":"application/json","X-Request-ID":r},body:JSON.stringify(c)}),u=await l.text(),h=this.parseResponseJSON(l,u);l.ok||this.handleErrorResponse(l,h);const p=s.verifyDelegationAPIResponseSchema.safeParse(h);if(!p.success)throw new i.AgentShieldAPIError("invalid_response","Response validation failed",{zodErrors:p.error.errors});return this.config.logger("[AccessControl] Delegation verified",{correlationId:r,agentDid:e.agent_did,valid:p.data.data.valid}),p.data})}async submitProofs(e){return this.retryWithBackoff(async()=>{const t=s.proofSubmissionRequestSchema.safeParse(e);if(!t.success){const r=JSON.stringify(t.error.errors,null,2);throw this.config.logger("[AccessControl] Proof submission validation failed:",{errors:t.error.errors,request:JSON.stringify(e,null,2)}),new i.AgentShieldAPIError("validation_error",`Request validation failed: ${r}`,{zodErrors:t.error.errors})}const r=t.data,o=a(),n=`${this.config.baseUrl}/api/v1/bouncer/proofs`;this.config.logger(`[AccessControl] Submitting ${e.proofs.length} proof(s)`,{correlationId:o,url:n,sessionId:e.session_id,delegationId:e.delegation_id});const c=await this.config.fetchProvider.fetch(n,{method:"POST",headers:{Authorization:`Bearer ${this.config.apiKey}`,"Content-Type":"application/json","X-Request-ID":o},body:JSON.stringify(r)}),d=await c.text();console.error("[AccessControl] 🔍 RAW API RESPONSE (before parsing):",{correlationId:o,status:c.status,statusText:c.statusText,headers:Object.fromEntries(c.headers.entries()),responseTextLength:d.length,responseTextPreview:d.substring(0,500),fullResponseText:d});const l=this.parseResponseJSON(c,d);if(console.error("[AccessControl] 🔍 PARSED RESPONSE DATA:",{correlationId:o,status:c.status,responseDataType:typeof l,responseDataKeys:Object.keys(l||{}),responseData:JSON.stringify(l,null,2)}),!c.ok){const t=l;if(t.error){const r=t.error.code||"api_error";if("all_proofs_rejected"===r&&400===c.status){const r=t.error.details,a={success:!1,accepted:0,rejected:r?.rejected||e.proofs.length,outcomes:{success:0,failed:0,blocked:0,error:r?.rejected||e.proofs.length},errors:r?.errors},o=s.proofSubmissionResponseSchema.safeParse(a);if(o.success)return o.data;throw new i.AgentShieldAPIError("invalid_response","Error response validation failed",{zodErrors:o.error.errors})}const a={...t.error.details||{},status:c.status};throw new i.AgentShieldAPIError(r,t.error.message||`API error: ${c.status}`,a)}let r="api_error";throw 400===c.status?r="validation_error":404===c.status&&(r=c.statusText.includes("delegation")?"delegation_not_found":"session_not_found"),new i.AgentShieldAPIError(r,`API request failed: ${c.status} ${c.statusText}`,{status:c.status,responseData:l})}const u=l,h={correlationId:o,hasSuccess:void 0!==u.success,hasData:void 0!==u.data,responseType:typeof l,responseKeys:Object.keys(l||{}),responseData:JSON.stringify(l,null,2).substring(0,2e3)};if(this.config.logger("[AccessControl] Raw response received",h),console.error("[AccessControl] Raw response received:",JSON.stringify(l,null,2)),void 0!==u.success&&u.data){let e;try{const t=u.data,r=JSON.parse(JSON.stringify(t));if("object"!=typeof r||null===r)throw new i.AgentShieldAPIError("invalid_response","Response data is not an object after cloning",{originalType:typeof t,clonedType:typeof r,clonedValue:r});e=r}catch(e){if(e instanceof i.AgentShieldAPIError)throw e;throw new i.AgentShieldAPIError("invalid_response","Failed to clone response data",{error:e instanceof Error?e.message:String(e),dataType:typeof u.data})}console.error("[AccessControl] 🔍 DATA OBJECT STRUCTURE (after deep clone):",{correlationId:o,dataKeys:Object.keys(e),hasAccepted:"accepted"in e,hasRejected:"rejected"in e,hasOutcomes:"outcomes"in e,hasErrors:"errors"in e,acceptedType:typeof e.accepted,acceptedValue:e.accepted,rejectedType:typeof e.rejected,rejectedValue:e.rejected,outcomesType:typeof e.outcomes,outcomesValue:e.outcomes,errorsType:typeof e.errors,errorsIsArray:Array.isArray(e.errors),fullData:JSON.stringify(e,null,2)});const t={success:!0===u.success,accepted:e.accepted,rejected:e.rejected};if("outcomes"in e&&void 0!==e.outcomes&&(t.outcomes=e.outcomes),"errors"in e&&void 0!==e.errors&&(t.errors=e.errors),console.error("[AccessControl] 🔍 VALIDATING DATA WITH SUCCESS:",{correlationId:o,dataWithSuccessKeys:Object.keys(t),hasSuccess:"success"in t,successValue:t.success,hasAccepted:"accepted"in t,acceptedValue:t.accepted,hasRejected:"rejected"in t,rejectedValue:t.rejected,hasOutcomes:"outcomes"in t,outcomesValue:t.outcomes,fullDataWithSuccess:JSON.stringify(t,null,2)}),"number"!=typeof t.accepted||"number"!=typeof t.rejected)throw console.error("[AccessControl] ❌ MISSING REQUIRED FIELDS AFTER CONSTRUCTION:",{correlationId:o,hasAccepted:"accepted"in t,acceptedType:typeof t.accepted,acceptedValue:t.accepted,hasRejected:"rejected"in t,rejectedType:typeof t.rejected,rejectedValue:t.rejected,dataWithSuccessKeys:Object.keys(t),fullDataWithSuccess:JSON.stringify(t,null,2),dataToValidateKeys:Object.keys(e),fullDataToValidate:JSON.stringify(e,null,2),originalResponseData:JSON.stringify(l,null,2)}),new i.AgentShieldAPIError("invalid_response","Response data missing required fields (accepted/rejected)",{responseData:l,dataToValidate:e,dataWithSuccess:t});const r=s.proofSubmissionResponseSchema.safeParse(t);if(r.success)return this.config.logger("[AccessControl] Proofs submitted successfully (wrapped)",{correlationId:o,accepted:r.data.accepted,rejected:r.data.rejected}),r.data;{const s={correlationId:o,zodErrors:r.error.errors,zodErrorDetails:JSON.stringify(r.error.errors,null,2),dataToValidate:JSON.stringify(e,null,2).substring(0,2e3),dataWithSuccess:JSON.stringify(t,null,2).substring(0,2e3),dataKeys:Object.keys(e),dataWithSuccessKeys:Object.keys(t),originalResponse:JSON.stringify(l,null,2).substring(0,2e3)};throw this.config.logger("[AccessControl] Wrapped response validation failed",s),console.error("[AccessControl] Wrapped response validation failed",s),console.error("[AccessControl] Original wrapped response:",JSON.stringify(l,null,2)),console.error(`[AccessControl] ❌ ZOD VALIDATION FAILED - ${r.error.errors.length} error(s):`),r.error.errors.forEach((e,t)=>{const r={path:e.path.join(".")||"(root)",message:e.message,code:e.code};"received"in e&&(r.received=e.received),"expected"in e&&(r.expected=e.expected),"input"in e&&(r.input=e.input),console.error(`[AccessControl] Error ${t+1}:`,JSON.stringify(r,null,2))}),console.error("[AccessControl] ❌ Full ZOD errors JSON:",JSON.stringify(r.error.errors,null,2)),new i.AgentShieldAPIError("invalid_response","Response validation failed",{zodErrors:r.error.errors,responseData:l})}}const p=s.proofSubmissionResponseSchema.safeParse(l);if(!p.success){const e={correlationId:o,zodErrors:p.error.errors,zodErrorDetails:JSON.stringify(p.error.errors,null,2),responseData:JSON.stringify(l,null,2),responseDataType:typeof l,responseKeys:Object.keys(l||{}),httpStatus:c.status,httpStatusText:c.statusText};throw this.config.logger("[AccessControl] Response validation failed",e),console.error("[AccessControl] Response validation failed",{zodErrors:p.error.errors,responseData:l}),console.error("[AccessControl] Response validation failed",e),console.error(`[AccessControl] ❌ ZOD VALIDATION FAILED (direct) - ${p.error.errors.length} error(s):`),p.error.errors.forEach((e,t)=>{const r={path:e.path.join(".")||"(root)",message:e.message,code:e.code};"received"in e&&(r.received=e.received),"expected"in e&&(r.expected=e.expected),"input"in e&&(r.input=e.input),console.error(`[AccessControl] Error ${t+1}:`,r)}),console.error("[AccessControl] ❌ Full ZOD errors JSON:",JSON.stringify(p.error.errors,null,2)),console.error("[AccessControl] ❌ ACTUAL RESPONSE DATA:",JSON.stringify(l,null,2)),new i.AgentShieldAPIError("invalid_response","Response validation failed",{zodErrors:p.error.errors,responseData:l})}return this.config.logger("[AccessControl] Proofs submitted successfully",{correlationId:o,accepted:p.data.accepted,rejected:p.data.rejected}),p.data})}getMetrics(){return{...this.metrics}}resetMetrics(){this.metrics={successCount:0,errorCount:0,retryCount:0}}async retryWithBackoff(e,t=0){try{const t=await e();return this.metrics.successCount++,t}catch(r){const s=this.isRetryableError(r),{maxRetries:i,initialDelayMs:a,maxDelayMs:o}=this.config.retryConfig;if(s&&t<i){const r=Math.min(a*Math.pow(2,t),o);return this.metrics.retryCount++,this.config.logger(`Retrying after ${r}ms (attempt ${t+1}/${i})`),await this.sleep(r),this.retryWithBackoff(e,t+1)}throw this.metrics.errorCount++,r}}isRetryableError(e){if(e instanceof TypeError&&e.message.includes("fetch"))return!0;if(e instanceof i.AgentShieldAPIError){if("server_error"===e.code)return!0;const t=e.details?.status;if(t&&t>=500&&t<600)return!0;if(429===t)return!0}if(e instanceof Error){const t=e.message.toLowerCase();if(t.includes("timeout")||t.includes("timed out"))return!0}return!1}sleep(e){return this.config.sleepProvider(e)}parseResponseJSON(e,t){try{return JSON.parse(t)}catch(r){if(!e.ok){const r=this.mapStatusToErrorCode(e.status);throw new i.AgentShieldAPIError(r,`API request failed: ${e.status} ${e.statusText}`,{status:e.status,responseText:t.substring(0,500)})}throw new i.AgentShieldAPIError("invalid_response",`Failed to parse response: ${r instanceof Error?r.message:String(r)}`,{responseText:t.substring(0,500)})}}mapStatusToErrorCode(e,t=""){return 400===e?"validation_error":401===e||403===e?"authentication_failed":404===e?"config_not_found":e>=500?"server_error":"api_error"}handleErrorResponse(e,t){const r=t;if(r.error){const t=r.error.code||"api_error",s={...r.error.details||{},status:e.status};throw new i.AgentShieldAPIError(t,r.error.message||`API error: ${e.status}`,s)}const s=this.mapStatusToErrorCode(e.status,e.statusText);throw new i.AgentShieldAPIError(s,`API request failed: ${e.status} ${e.statusText}`,{status:e.status,responseData:t})}}},36885:(e,t,r)=>{"use strict";var s=r(9717),i=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,a=[0,31,28,31,30,31,30,31,31,30,31,30,31],o=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,n=/^(?=.{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,c=/^(?:[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,d=/^(?:(?:[^\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,l=/^(?:(?:http[s\u017F]?|ftp):\/\/)(?:(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+(?::(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?@)?(?:(?!10(?:\.[0-9]{1,3}){3})(?!127(?:\.[0-9]{1,3}){3})(?!169\.254(?:\.[0-9]{1,3}){2})(?!192\.168(?:\.[0-9]{1,3}){2})(?!172\.(?:1[6-9]|2[0-9]|3[01])(?:\.[0-9]{1,3}){2})(?:[1-9][0-9]?|1[0-9][0-9]|2[01][0-9]|22[0-3])(?:\.(?:1?[0-9]{1,2}|2[0-4][0-9]|25[0-5])){2}(?:\.(?:[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-4]))|(?:(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)(?:\.(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)*(?:\.(?:(?:[a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]){2,})))(?::[0-9]{2,5})?(?:\/(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?$/i,u=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,h=/^(?:\/(?:[^~/]|~0|~1)*)*$/,p=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,f=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/;function g(e){return e="full"==e?"full":"fast",s.copy(g[e])}function m(e){var t=e.match(i);if(!t)return!1;var r=+t[1],s=+t[2],o=+t[3];return s>=1&&s<=12&&o>=1&&o<=(2==s&&function(e){return e%4==0&&(e%100!=0||e%400==0)}(r)?29:a[s])}function v(e,t){var r=e.match(o);if(!r)return!1;var s=r[1],i=r[2],a=r[3],n=r[5];return(s<=23&&i<=59&&a<=59||23==s&&59==i&&60==a)&&(!t||n)}e.exports=g,g.fast={date:/^\d\d\d\d-[0-1]\d-[0-3]\d$/,time:/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,"date-time":/^\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,uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,"uri-template":d,url:l,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,hostname:n,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,ipv6:/^\s*(?:(?:(?:[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}))|:)))(?:%.+)?\s*$/i,regex:b,uuid:u,"json-pointer":h,"json-pointer-uri-fragment":p,"relative-json-pointer":f},g.full={date:m,time:v,"date-time":function(e){var t=e.split(y);return 2==t.length&&m(t[0])&&v(t[1],!0)},uri:function(e){return _.test(e)&&c.test(e)},"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":d,url:l,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:n,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,ipv6:/^\s*(?:(?:(?:[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}))|:)))(?:%.+)?\s*$/i,regex:b,uuid:u,"json-pointer":h,"json-pointer-uri-fragment":p,"relative-json-pointer":f};var y=/t|\s/i,_=/\/|:/,w=/[^\\]\\Z/;function b(e){if(w.test(e))return!1;try{return new RegExp(e),!0}catch(e){return!1}}},37121:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SchemaVerifier=void 0,t.createSchemaVerifier=function(e){return new r(e)};class r{schemasBaseUrl="https://schemas.kya-os.ai";schemaCache=new Map;constructor(e){e?.schemasBaseUrl&&(this.schemasBaseUrl=e.schemasBaseUrl)}async verifySchema(e,t){const r=[],s=[],i=[];let a;try{a=await this.fetchSchema(e.url)}catch(t){return{schema:e,compliant:!1,compliancePercentage:0,fields:[],issues:[`Failed to fetch schema: ${t instanceof Error?t.message:"Unknown error"}`],warnings:[],timestamp:Date.now()}}const o=this.resolveRef(a,a),n=this.validateAgainstSchema(t,o,a,"");r.push(...n.fields);for(const e of r)"fail"===e.status?s.push(`${e.fieldPath}: ${e.reason}`):"warning"===e.status&&i.push(`${e.fieldPath}: ${e.reason}`);const c=r.filter(e=>e.required),d=c.filter(e=>"pass"===e.status).length,l=c.length>0?d/c.length*100:100;return{schema:e,compliant:0===s.length&&l>=95,compliancePercentage:l,fields:r,issues:s,warnings:i,timestamp:Date.now()}}async verifyAll(e,t){const r=[],s=[];for(const i of e){const e=t.get(i.id);if(!e){s.push(`No implementation found for schema: ${i.id}`);continue}const a=await this.verifySchema(i,e);r.push(a),a.compliant||s.push(`${i.id}: ${a.issues.join(", ")}`)}const i=r.filter(e=>e.compliant).length,a=e.length>0?i/e.length*100:0;return{totalSchemas:e.length,compliantSchemas:i,overallCompliance:a,schemaReports:r,criticalIssues:s,timestamp:Date.now()}}validateAgainstSchema(e,t,r,s){const i=[];if((t=this.resolveRef(t,r)).oneOf||t.anyOf||t.allOf)return this.validateUnion(e,t,r,s);if("object"===t.type&&t.properties){const a=t.required||[];for(const[o,n]of Object.entries(t.properties)){const t=s?`${s}.${o}`:o,c=e?.[o],d=a.includes(o),l=this.checkField(t,c,n,r,d);if(i.push(l),void 0!==c&&"object"===n.type){const e=this.validateAgainstSchema(c,n,r,t);i.push(...e.fields)}}}if("array"===t.type&&e&&Array.isArray(e)){const a=this.validateArray(e,t,r,s);i.push(...a.fields)}return{fields:i}}validateUnion(e,t,r,s){const i=[];if(t.anyOf||t.oneOf){const a=t.anyOf||t.oneOf;let o=!1;for(const t of a){const a=this.resolveRef(t,r);try{if(this.matchesSchema(e,a,r)){const t=this.validateAgainstSchema(e,a,r,s);i.push(...t.fields),o=!0;break}}catch(e){continue}}!o&&s&&i.push({fieldPath:s,present:void 0!==e,expectedType:"oneOf/anyOf options",actualType:typeof e,typeMatches:!1,required:!0,status:"fail",reason:"Value does not match any of the schema options"})}if(t.allOf)for(const a of t.allOf){const t=this.resolveRef(a,r),o=this.validateAgainstSchema(e,t,r,s);i.push(...o.fields)}return{fields:i}}matchesSchema(e,t,r){if((t=this.resolveRef(t,r)).type){const r=Array.isArray(e)?"array":typeof e;if("integer"===t.type&&"number"===r){if(!Number.isInteger(e))return!1}else if(t.type!==r)return!1}if(void 0!==t.const&&e!==t.const)return!1;if(t.enum&&!t.enum.includes(e))return!1;if(t.pattern&&"string"==typeof e&&!new RegExp(t.pattern).test(e))return!1;if("object"===t.type&&t.required)for(const r of t.required)if(!(r in e))return!1;return!0}validateArray(e,t,r,s){const i=[];if(void 0!==t.minItems&&e.length<t.minItems&&i.push({fieldPath:`${s}.length`,present:!0,expectedType:`array with minItems: ${t.minItems}`,actualType:`array with length: ${e.length}`,typeMatches:!1,required:!0,status:"fail",reason:`Array length ${e.length} is less than minItems ${t.minItems}`}),Array.isArray(t.items)){for(let a=0;a<t.items.length;a++){const o=t.items[a],n=e[a],c=`${s}[${a}]`;if(void 0!==n){const e=this.resolveRef(o,r),t=this.validateAgainstSchema(n,e,r,c);i.push(...t.fields)}}if(void 0!==t.additionalItems&&e.length>t.items.length)for(let a=t.items.length;a<e.length;a++){const o=e[a],n=`${s}[${a}]`,c=this.validateAgainstSchema(o,t.additionalItems,r,n);i.push(...c.fields)}}else if(t.items)for(let a=0;a<e.length;a++){const o=e[a],n=`${s}[${a}]`,c=this.resolveRef(t.items,r),d=this.validateAgainstSchema(o,c,r,n);i.push(...d.fields)}if(t.contains){const a=this.resolveRef(t.contains,r);e.some(e=>this.matchesSchema(e,a,r))||i.push({fieldPath:`${s}.contains`,present:!0,expectedType:"array containing matching item",actualType:"array without matching item",typeMatches:!1,required:!0,status:"fail",reason:'Array does not contain any item matching the "contains" schema'})}return{fields:i}}checkField(e,t,r,s,i){r=this.resolveRef(r,s);const a=void 0!==t,o=this.getActualType(t);let n="unknown";return r.type?n=r.type:r.anyOf?n="anyOf":r.oneOf?n="oneOf":r.allOf&&(n="allOf"),i&&!a?{fieldPath:e,present:a,expectedType:n,actualType:o,typeMatches:!1,required:i,status:"fail",reason:"Required field missing"}:i||a?this.matchesSchema(t,r,s)?{fieldPath:e,present:a,expectedType:n,actualType:o,typeMatches:!0,required:i,status:"pass"}:{fieldPath:e,present:a,expectedType:n,actualType:o,typeMatches:!1,required:i,status:"fail",reason:"Type/value mismatch"}:{fieldPath:e,present:a,expectedType:n,actualType:o,typeMatches:!0,required:i,status:"pass"}}getActualType(e){return null===e?"null":Array.isArray(e)?"array":"number"==typeof e&&Number.isInteger(e)?"integer":typeof e}resolveRef(e,t){if(!e.$ref)return e;const r=e.$ref;if(r.startsWith("#/definitions/")){const e=r.substring(14);if(t.definitions&&t.definitions[e])return t.definitions[e]}if(r.startsWith("#/$defs/")){const e=r.substring(8);if(t.$defs&&t.$defs[e])return t.$defs[e]}return"#"===r?t:e}async fetchSchema(e){if(this.schemaCache.has(e))return this.schemaCache.get(e);try{const t=await fetch(e);if(!t.ok)throw new Error(`HTTP ${t.status}: ${t.statusText}`);const r=await t.json();return this.schemaCache.set(e,r),r}catch(t){if(t instanceof Error)throw new Error(`Failed to fetch schema from ${e}: ${t.message}`);throw new Error(`Failed to fetch schema from ${e}: Unknown error`)}}generateReport(e){const t=[];t.push(`\n${"=".repeat(80)}`),t.push(`SCHEMA COMPLIANCE REPORT: ${e.schema.id}`),t.push(`${"=".repeat(80)}\n`),t.push(`Schema: ${e.schema.type} v${e.schema.version}`),t.push(`URL: ${e.schema.url}`),t.push("Status: "+(e.compliant?"✅ COMPLIANT":"❌ NON-COMPLIANT")),t.push(`Compliance: ${e.compliancePercentage.toFixed(1)}%\n`),e.issues.length>0&&(t.push(`\n🚨 ISSUES (${e.issues.length}):`),e.issues.forEach((e,r)=>{t.push(` ${r+1}. ${e}`)})),e.warnings.length>0&&(t.push(`\n⚠️ WARNINGS (${e.warnings.length}):`),e.warnings.forEach((e,r)=>{t.push(` ${r+1}. ${e}`)})),t.push("\n📊 FIELD DETAILS:\n");const r=e.fields.filter(e=>e.required),s=r.filter(e=>"pass"===e.status).length,i=r.filter(e=>"fail"===e.status).length,a=e.fields.filter(e=>"warning"===e.status).length;return t.push(` ✅ Pass: ${s}/${r.length} required fields`),t.push(` ❌ Fail: ${i}/${r.length} required fields`),t.push(` ⚠️ Warn: ${a} optional fields`),t.push(` 📝 Total: ${e.fields.length} fields checked\n`),t.push(`${"=".repeat(80)}\n`),t.join("\n")}generateFullReport(e){const t=[];return t.push(`\n${"=".repeat(80)}`),t.push("FULL SCHEMA COMPLIANCE REPORT"),t.push(`${"=".repeat(80)}\n`),t.push(`Total Schemas: ${e.totalSchemas}`),t.push(`Compliant: ${e.compliantSchemas}`),t.push("Non-Compliant: "+(e.totalSchemas-e.compliantSchemas)),t.push(`Overall Compliance: ${e.overallCompliance.toFixed(1)}%\n`),e.criticalIssues.length>0&&(t.push(`\n🚨 CRITICAL ISSUES (${e.criticalIssues.length}):`),e.criticalIssues.slice(0,10).forEach((e,r)=>{t.push(` ${r+1}. ${e}`)}),e.criticalIssues.length>10&&t.push(` ... and ${e.criticalIssues.length-10} more issues`)),t.push("\n📊 SCHEMA BREAKDOWN:\n"),e.schemaReports.forEach(e=>{const r=e.compliant?"✅":"❌",s=e.compliancePercentage.toFixed(1);t.push(` ${r} ${e.schema.id}: ${s}%`)}),t.push(`\n${"=".repeat(80)}\n`),t.join("\n")}}t.SchemaVerifier=r},40985:(e,t,r)=>{"use strict";var s=r(13749),i=r(67371),a=r(9717),o=r(20812),n=r(27713);function c(e,t,r){var s=this._refs[r];if("string"==typeof s){if(!this._refs[s])return c.call(this,e,t,s);s=this._refs[s]}if((s=s||this._schemas[r])instanceof o)return f(s.schema,this._opts.inlineRefs)?s.schema:s.validate||this._compile(s);var i,a,n,l=d.call(this,t,r);return l&&(i=l.schema,t=l.root,n=l.baseId),i instanceof o?a=i.validate||e.call(this,i.schema,t,void 0,n):void 0!==i&&(a=f(i,this._opts.inlineRefs)?i:e.call(this,i,t,void 0,n)),a}function d(e,t){var r=s.parse(t),i=y(r),a=v(this._getId(e.schema));if(0===Object.keys(e.schema).length||i!==a){var n=w(i),c=this._refs[n];if("string"==typeof c)return l.call(this,e,c,r);if(c instanceof o)c.validate||this._compile(c),e=c;else{if(!((c=this._schemas[n])instanceof o))return;if(c.validate||this._compile(c),n==w(t))return{schema:c,root:e,baseId:a};e=c}if(!e.schema)return;a=v(this._getId(e.schema))}return h.call(this,r,a,e.schema,e)}function l(e,t,r){var s=d.call(this,e,t);if(s){var i=s.schema,a=s.baseId;e=s.root;var o=this._getId(i);return o&&(a=b(a,o)),h.call(this,r,a,i,e)}}e.exports=c,c.normalizeId=w,c.fullPath=v,c.url=b,c.ids=function(e){var t=w(this._getId(e)),r={"":t},o={"":v(t,!1)},c={},d=this;return n(e,{allKeys:!0},function(e,t,n,l,u,h,p){if(""!==t){var f=d._getId(e),g=r[l],m=o[l]+"/"+u;if(void 0!==p&&(m+="/"+("number"==typeof p?p:a.escapeFragment(p))),"string"==typeof f){f=g=w(g?s.resolve(g,f):f);var v=d._refs[f];if("string"==typeof v&&(v=d._refs[v]),v&&v.schema){if(!i(e,v.schema))throw new Error('id "'+f+'" resolves to more than one schema')}else if(f!=w(m))if("#"==f[0]){if(c[f]&&!i(e,c[f]))throw new Error('id "'+f+'" resolves to more than one schema');c[f]=e}else d._refs[f]=m}r[t]=g,o[t]=m}}),c},c.inlineRef=f,c.schema=d;var u=a.toHash(["properties","patternProperties","enum","dependencies","definitions"]);function h(e,t,r,s){if(e.fragment=e.fragment||"","/"==e.fragment.slice(0,1)){for(var i=e.fragment.split("/"),o=1;o<i.length;o++){var n=i[o];if(n){if(void 0===(r=r[n=a.unescapeFragment(n)]))break;var c;if(!u[n]&&((c=this._getId(r))&&(t=b(t,c)),r.$ref)){var l=b(t,r.$ref),h=d.call(this,s,l);h&&(r=h.schema,s=h.root,t=h.baseId)}}}return void 0!==r&&r!==s.schema?{schema:r,root:s,baseId:t}:void 0}}var p=a.toHash(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum"]);function f(e,t){return!1!==t&&(void 0===t||!0===t?g(e):t?m(e)<=t:void 0)}function g(e){var t;if(Array.isArray(e)){for(var r=0;r<e.length;r++)if("object"==typeof(t=e[r])&&!g(t))return!1}else for(var s in e){if("$ref"==s)return!1;if("object"==typeof(t=e[s])&&!g(t))return!1}return!0}function m(e){var t,r=0;if(Array.isArray(e)){for(var s=0;s<e.length;s++)if("object"==typeof(t=e[s])&&(r+=m(t)),r==1/0)return 1/0}else for(var i in e){if("$ref"==i)return 1/0;if(p[i])r++;else if("object"==typeof(t=e[i])&&(r+=m(t)+1),r==1/0)return 1/0}return r}function v(e,t){return!1!==t&&(e=w(e)),y(s.parse(e))}function y(e){return s.serialize(e).split("#")[0]+"#"}var _=/#\/?$/;function w(e){return e?e.replace(_,""):""}function b(e,t){return t=w(t),s.resolve(e,t)}},41021:e=>{"use strict";e.exports=function(e,t,r){var s,i,a=" ",o=e.level,n=e.dataLevel,c=e.schema[t],d=e.schemaPath+e.util.getProperty(t),l=e.errSchemaPath+"/"+t,u=!e.opts.allErrors,h="data"+(n||""),p="valid"+o,f="errs__"+o,g=e.opts.$data&&c&&c.$data;g?(a+=" var schema"+o+" = "+e.util.getData(c.$data,n,e.dataPathArr)+"; ",i="schema"+o):i=c;var m,v,y,_,w,b=this,S="definition"+o,P=b.definition,E="";if(g&&P.$data){w="keywordValidate"+o;var I=P.validateSchema;a+=" var "+S+" = RULES.custom['"+t+"'].definition; var "+w+" = "+S+".validate;"}else{if(!(_=e.useCustomRule(b,c,e.schema,e)))return;i="validate.schema"+d,w=_.code,m=P.compile,v=P.inline,y=P.macro}var k=w+".errors",C="i"+o,D="ruleErr"+o,O=P.async;if(O&&!e.async)throw new Error("async keyword in sync schema");if(v||y||(a+=k+" = null;"),a+="var "+f+" = errors;var "+p+";",g&&P.$data&&(E+="}",a+=" if ("+i+" === undefined) { "+p+" = true; } else { ",I&&(E+="}",a+=" "+p+" = "+S+".validateSchema("+i+"); if ("+p+") { ")),v)P.statements?a+=" "+_.validate+" ":a+=" "+p+" = "+_.validate+"; ";else if(y){var A=e.util.copy(e);E="",A.level++;var x="valid"+A.level;A.schema=_.validate,A.schemaPath="";var T=e.compositeRule;e.compositeRule=A.compositeRule=!0;var R=e.validate(A).replace(/validate\.schema/g,w);e.compositeRule=A.compositeRule=T,a+=" "+R}else{(M=M||[]).push(a),a="",a+=" "+w+".call( ",e.opts.passContext?a+="this":a+="self",m||!1===P.schema?a+=" , "+h+" ":a+=" , "+i+" , "+h+" , validate.schema"+e.schemaPath+" ",a+=" , (dataPath || '')",'""'!=e.errorPath&&(a+=" + "+e.errorPath);var $=n?"data"+(n-1||""):"parentData",j=n?e.dataPathArr[n]:"parentDataProperty",N=a+=" , "+$+" , "+j+" , rootData ) ";a=M.pop(),!1===P.errors?(a+=" "+p+" = ",O&&(a+="await "),a+=N+"; "):a+=O?" var "+(k="customErrors"+o)+" = null; try { "+p+" = await "+N+"; } catch (e) { "+p+" = false; if (e instanceof ValidationError) "+k+" = e.errors; else throw e; } ":" "+k+" = null; "+p+" = "+N+"; "}if(P.modifying&&(a+=" if ("+$+") "+h+" = "+$+"["+j+"];"),a+=""+E,P.valid)u&&(a+=" if (true) { ");else{var M;a+=" if ( ",void 0===P.valid?(a+=" !",a+=y?""+x:""+p):a+=" "+!P.valid+" ",a+=") { ",s=b.keyword,(M=M||[]).push(a),a="",(M=M||[]).push(a),a="",!1!==e.createErrors?(a+=" { keyword: '"+(s||"custom")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: { keyword: '"+b.keyword+"' } ",!1!==e.opts.messages&&(a+=" , message: 'should pass \""+b.keyword+"\" keyword validation' "),e.opts.verbose&&(a+=" , schema: validate.schema"+d+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),a+=" } "):a+=" {} ";var F=a;a=M.pop(),!e.compositeRule&&u?e.async?a+=" throw new ValidationError(["+F+"]); ":a+=" validate.errors = ["+F+"]; return false; ":a+=" var err = "+F+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";var K=a;a=M.pop(),v?P.errors?"full"!=P.errors&&(a+=" for (var "+C+"="+f+"; "+C+"<errors; "+C+"++) { var "+D+" = vErrors["+C+"]; if ("+D+".dataPath === undefined) "+D+".dataPath = (dataPath || '') + "+e.errorPath+"; if ("+D+".schemaPath === undefined) { "+D+'.schemaPath = "'+l+'"; } ',e.opts.verbose&&(a+=" "+D+".schema = "+i+"; "+D+".data = "+h+"; "),a+=" } "):!1===P.errors?a+=" "+K+" ":(a+=" if ("+f+" == errors) { "+K+" } else { for (var "+C+"="+f+"; "+C+"<errors; "+C+"++) { var "+D+" = vErrors["+C+"]; if ("+D+".dataPath === undefined) "+D+".dataPath = (dataPath || '') + "+e.errorPath+"; if ("+D+".schemaPath === undefined) { "+D+'.schemaPath = "'+l+'"; } ',e.opts.verbose&&(a+=" "+D+".schema = "+i+"; "+D+".data = "+h+"; "),a+=" } } "):y?(a+=" var err = ",!1!==e.createErrors?(a+=" { keyword: '"+(s||"custom")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: { keyword: '"+b.keyword+"' } ",!1!==e.opts.messages&&(a+=" , message: 'should pass \""+b.keyword+"\" keyword validation' "),e.opts.verbose&&(a+=" , schema: validate.schema"+d+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),a+=" } "):a+=" {} ",a+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&u&&(e.async?a+=" throw new ValidationError(vErrors); ":a+=" validate.errors = vErrors; return false; ")):!1===P.errors?a+=" "+K+" ":(a+=" if (Array.isArray("+k+")) { if (vErrors === null) vErrors = "+k+"; else vErrors = vErrors.concat("+k+"); errors = vErrors.length; for (var "+C+"="+f+"; "+C+"<errors; "+C+"++) { var "+D+" = vErrors["+C+"]; if ("+D+".dataPath === undefined) "+D+".dataPath = (dataPath || '') + "+e.errorPath+"; "+D+'.schemaPath = "'+l+'"; ',e.opts.verbose&&(a+=" "+D+".schema = "+i+"; "+D+".data = "+h+"; "),a+=" } } else { "+K+" } "),a+=" } ",u&&(a+=" else { ")}return a}},42399:e=>{function t(e){return Promise.resolve().then(()=>{var t=new Error("Cannot find module '"+e+"'");throw t.code="MODULE_NOT_FOUND",t})}t.keys=()=>[],t.resolve=t,t.id=42399,e.exports=t},42769:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OAuthTokenRetrievalService=void 0,t.OAuthTokenRetrievalService=class{config;constructor(e){this.config={...e,logger:e.logger||(()=>{}),retryConfig:{maxRetries:3,retryDelay:1e3,retryBackoff:2,...e.retryConfig}}}async retrieveTokens(e,t){const r=`${this.config.baseUrl}/api/v1/bouncer/delegations/${e}/tokens`;this.config.logger("[OAuthTokenRetrievalService] Retrieving OAuth tokens",{delegationId:e,endpoint:r});let s=null,i=0;for(;i<=this.config.retryConfig.maxRetries;)try{const s=await this.config.fetchProvider(r,{method:"GET",headers:{Authorization:`Bearer ${t}`,Accept:"application/json"}});if(!s.ok){const t=await s.json().catch(()=>({}));if(404===s.status||401===s.status)return this.config.logger("[OAuthTokenRetrievalService] Tokens unavailable",{status:s.status,delegationId:e,error:t}),null;const r=t.error?.message||t.error||t.message||`HTTP ${s.status}`;throw new Error(`Token retrieval failed: ${r}`)}const i=await s.json();if(!i.success)return this.config.logger("[OAuthTokenRetrievalService] Token retrieval error response",{delegationId:e,error:i.error}),null;const a=this.mapToIdpTokens(i.data);return this.config.logger("[OAuthTokenRetrievalService] OAuth tokens retrieved successfully",{delegationId:e,expiresAt:new Date(a.expires_at).toISOString(),hasRefreshToken:!!a.refresh_token}),a}catch(t){if(s=t instanceof Error?t:new Error(String(t)),!(i<this.config.retryConfig.maxRetries))return this.config.logger("[OAuthTokenRetrievalService] Max retries exceeded",{delegationId:e,error:s.message,attempts:i+1}),null;{const e=this.config.retryConfig.retryDelay*Math.pow(this.config.retryConfig.retryBackoff,i);this.config.logger("[OAuthTokenRetrievalService] Retry attempt failed, retrying",{attempt:i+1,maxRetries:this.config.retryConfig.maxRetries,delay:e,error:s.message}),await new Promise(t=>setTimeout(t,e)),i++}}return null}mapToIdpTokens(e){let t;return t=e.oauth_expires_at?new Date(e.oauth_expires_at).getTime():e.oauth_expires_in?Date.now()+1e3*e.oauth_expires_in:Date.now()+36e5,{access_token:e.oauth_access_token,refresh_token:e.oauth_refresh_token||void 0,expires_in:e.oauth_expires_in||void 0,expires_at:t,token_type:e.oauth_token_type||"Bearer",scope:e.oauth_scope||void 0}}}},43528:(e,t,r)=>{"use strict";var s=/^[a-z_$][a-z0-9_$-]*$/i,i=r(41021),a=r(96150);e.exports={add:function(e,t){var r=this.RULES;if(r.keywords[e])throw new Error("Keyword "+e+" is already defined");if(!s.test(e))throw new Error("Keyword "+e+" is not a valid identifier");if(t){this.validateKeyword(t,!0);var a=t.type;if(Array.isArray(a))for(var o=0;o<a.length;o++)c(e,a[o],t);else c(e,a,t);var n=t.metaSchema;n&&(t.$data&&this._opts.$data&&(n={anyOf:[n,{$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"}]}),t.validateSchema=this.compile(n,!0))}function c(e,t,s){for(var a,o=0;o<r.length;o++){var n=r[o];if(n.type==t){a=n;break}}a||(a={type:t,rules:[]},r.push(a));var c={keyword:e,definition:s,custom:!0,code:i,implements:s.implements};a.rules.push(c),r.custom[e]=c}return r.keywords[e]=r.all[e]=!0,this},get:function(e){var t=this.RULES.custom[e];return t?t.definition:this.RULES.keywords[e]||!1},remove:function(e){var t=this.RULES;delete t.keywords[e],delete t.all[e],delete t.custom[e];for(var r=0;r<t.length;r++)for(var s=t[r].rules,i=0;i<s.length;i++)if(s[i].keyword==e){s.splice(i,1);break}return this},validate:function e(t,r){e.errors=null;var s=this._validateKeyword=this._validateKeyword||this.compile(a,!0);if(s(t))return!0;if(e.errors=s.errors,r)throw new Error("custom keyword definition is invalid: "+this.errorsText(s.errors));return!1}}},44413:e=>{"use strict";e.exports=function(e,t,r){var s=" ",i=e.schema[t],a=e.errSchemaPath+"/"+t,o=(e.opts.allErrors,e.util.toQuotedString(i));return!0===e.opts.$comment?s+=" console.log("+o+");":"function"==typeof e.opts.$comment&&(s+=" self._opts.$comment("+o+", "+e.util.toQuotedString(a)+", validate.root.schema);"),s}},44558:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MemoryDelegationGraphStorage=void 0,t.MemoryDelegationGraphStorage=class{nodes=new Map;async getNode(e){return this.nodes.get(e)||null}async setNode(e){this.nodes.set(e.id,e)}async getChildren(e){const t=this.nodes.get(e);return t?t.children.map(e=>this.nodes.get(e)).filter(e=>void 0!==e):[]}async getChain(e){const t=[];let r=e;for(;r;){const e=this.nodes.get(r);if(!e)break;t.unshift(e),r=e.parentId}return t}async getDescendants(e){const t=[],r=[e],s=new Set;for(;r.length>0;){const e=r.shift();if(s.has(e))continue;s.add(e);const i=this.nodes.get(e);if(i)for(const e of i.children)if(!s.has(e)){r.push(e);const s=this.nodes.get(e);s&&t.push(s)}}return t}async deleteNode(e){this.nodes.delete(e)}clear(){this.nodes.clear()}getAllNodeIds(){return Array.from(this.nodes.keys())}getStats(){const e=Array.from(this.nodes.values()),t=e.filter(e=>null===e.parentId).length,r=e.filter(e=>0===e.children.length).length;let s=0;for(const t of e){const e=this.getChainSync(t.id);s=Math.max(s,e.length-1)}return{totalNodes:e.length,rootNodes:t,leafNodes:r,maxDepth:s}}getChainSync(e){const t=[];let r=e;for(;r;){const e=this.nodes.get(r);if(!e)break;t.unshift(e),r=e.parentId}return t}}},45395:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProofVerifier=void 0;const s=r(81296),i=r(28717),a=r(51708),o=r(53683);t.ProofVerifier=class{cryptoService;clock;nonceCache;fetch;timestampSkewSeconds;nonceTtlSeconds;constructor(e){this.cryptoService=new s.CryptoService(e.cryptoProvider),this.clock=e.clockProvider,this.nonceCache=e.nonceCacheProvider,this.fetch=e.fetchProvider,this.timestampSkewSeconds=e.timestampSkewSeconds??120,this.nonceTtlSeconds=e.nonceTtlSeconds??300}async verifyProof(e,t){try{const r=await this.validateProofStructure(e);if(!r.valid)return r;const s=r.proof,i=await this.validateNonce(s.meta.nonce,s.meta.did);if(!i.valid)return i;const a=await this.validateTimestamp(s.meta.ts);if(!a.valid)return a;const o=this.buildCanonicalPayload(s.meta),n=(new TextEncoder).encode(o),c=await this.verifySignature(s.jws,t,n,s.meta.kid);return c.valid?(await this.addNonceToCache(s.meta.nonce,s.meta.did),{valid:!0}):c}catch(e){return{valid:!1,reason:"Proof verification error",errorCode:o.PROOF_VERIFICATION_ERROR_CODES.VERIFICATION_ERROR,error:e instanceof Error?e:new Error(String(e)),details:{errorMessage:e instanceof Error?e.message:String(e)}}}}async verifyProofDetached(e,t,r){try{const s=await this.validateProofStructure(e);if(!s.valid)return s;const i=s.proof,a=await this.validateNonce(i.meta.nonce,i.meta.did);if(!a.valid)return a;const o=await this.validateTimestamp(i.meta.ts);if(!o.valid)return o;const n=t instanceof Uint8Array?t:(new TextEncoder).encode(t),c=await this.verifySignature(i.jws,r,n,i.meta.kid);return c.valid?(await this.addNonceToCache(i.meta.nonce,i.meta.did),{valid:!0}):c}catch(e){return{valid:!1,reason:"Proof verification error",errorCode:o.PROOF_VERIFICATION_ERROR_CODES.VERIFICATION_ERROR,error:e instanceof Error?e:new Error(String(e)),details:{errorMessage:e instanceof Error?e.message:String(e)}}}}async validateProofStructure(e){const t=i.DetachedProofSchema.safeParse(e);return t.success?{valid:!0,proof:t.data}:{valid:!1,reason:"Invalid proof structure",errorCode:o.PROOF_VERIFICATION_ERROR_CODES.INVALID_PROOF_STRUCTURE,error:new Error(`Proof validation failed: ${t.error.message}`),details:{zodErrors:t.error.errors}}}async validateNonce(e,t){return await this.nonceCache.has(e,t)?{valid:!1,reason:"Nonce already used (replay attack detected)",errorCode:o.PROOF_VERIFICATION_ERROR_CODES.NONCE_REPLAY_DETECTED,details:{nonce:e,agentDid:t}}:{valid:!0}}async validateTimestamp(e){const t=1e3*e;return this.clock.isWithinSkew(t,this.timestampSkewSeconds)?{valid:!0}:{valid:!1,reason:`Timestamp out of skew window (skew: ${this.timestampSkewSeconds}s)`,errorCode:o.PROOF_VERIFICATION_ERROR_CODES.TIMESTAMP_SKEW_EXCEEDED,details:{timestamp:e,timestampMs:t,skewSeconds:this.timestampSkewSeconds,currentTime:this.clock.now()}}}async verifySignature(e,t,r,s){return await this.cryptoService.verifyJWS(e,t,{detachedPayload:r,expectedKid:s,alg:"EdDSA"})?{valid:!0}:{valid:!1,reason:"Invalid JWS signature",errorCode:o.PROOF_VERIFICATION_ERROR_CODES.INVALID_JWS_SIGNATURE,details:{jwsLength:e.length,expectedKid:s,actualKid:t.kid}}}async addNonceToCache(e,t){await this.nonceCache.add(e,this.nonceTtlSeconds,t)}async fetchPublicKeyFromDID(e,t){try{const r=await this.fetch.resolveDID(e);if(!r)throw new o.ProofVerificationError(o.PROOF_VERIFICATION_ERROR_CODES.DID_DOCUMENT_NOT_FOUND,`DID document not found: ${e}`,{did:e});if(!r.verificationMethod||0===r.verificationMethod.length)throw new o.ProofVerificationError(o.PROOF_VERIFICATION_ERROR_CODES.VERIFICATION_METHOD_NOT_FOUND,`No verification methods found in DID document: ${e}`,{did:e});let s;if(t){const i=t.startsWith("#")?t:`#${t}`;if(s=r.verificationMethod.find(t=>t.id===i||t.id===`${e}${i}`),!s)throw new o.ProofVerificationError(o.PROOF_VERIFICATION_ERROR_CODES.VERIFICATION_METHOD_NOT_FOUND,`Verification method not found for kid: ${t}`,{did:e,kid:t,availableKids:r.verificationMethod.map(e=>e.id)})}else s=r.verificationMethod[0];if(!s?.publicKeyJwk)throw new o.ProofVerificationError(o.PROOF_VERIFICATION_ERROR_CODES.PUBLIC_KEY_NOT_FOUND,"Public key JWK not found in verification method",{did:e,kid:t,verificationMethodId:s?.id});const i=s.publicKeyJwk;if("OKP"!==i.kty||"Ed25519"!==i.crv||!i.x)throw new o.ProofVerificationError(o.PROOF_VERIFICATION_ERROR_CODES.INVALID_JWK_FORMAT,`Unsupported key type or curve: kty=${i.kty}, crv=${i.crv}`,{did:e,kid:t,jwk:{kty:i.kty,crv:i.crv}});return i}catch(r){if(r instanceof o.ProofVerificationError)throw r;throw console.error("[ProofVerifier] Failed to fetch public key from DID:",r),new o.ProofVerificationError(o.PROOF_VERIFICATION_ERROR_CODES.DID_RESOLUTION_FAILED,`DID resolution failed: ${r instanceof Error?r.message:String(r)}`,{did:e,kid:t,originalError:r instanceof Error?r.message:String(r)})}}buildCanonicalPayload(e){const t={aud:e.audience,sub:e.did,iss:e.did,requestHash:e.requestHash,responseHash:e.responseHash,ts:e.ts,nonce:e.nonce,sessionId:e.sessionId,...e.scopeId&&{scopeId:e.scopeId},...e.delegationRef&&{delegationRef:e.delegationRef},...e.clientDid&&{clientDid:e.clientDid}};return(0,a.canonicalize)(t)}}},46079:e=>{"use strict";var t=["multipleOf","maximum","exclusiveMaximum","minimum","exclusiveMinimum","maxLength","minLength","pattern","additionalItems","maxItems","minItems","uniqueItems","maxProperties","minProperties","required","additionalProperties","enum","format","const"];e.exports=function(e,r){for(var s=0;s<r.length;s++){e=JSON.parse(JSON.stringify(e));var i,a=r[s].split("/"),o=e;for(i=1;i<a.length;i++)o=o[a[i]];for(i=0;i<t.length;i++){var n=t[i],c=o[n];c&&(o[n]={anyOf:[c,{$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"}]})}}return e}},46137:e=>{"use strict";e.exports=function(e,t,r){var s=" ",i=e.level,a=e.dataLevel,o=e.schema[t],n=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,d=!e.opts.allErrors,l="data"+(a||""),u="valid"+i,h="errs__"+i,p=e.util.copy(e),f="";p.level++;var g="valid"+p.level,m=p.baseId,v="prevValid"+i,y="passingSchemas"+i;s+="var "+h+" = errors , "+v+" = false , "+u+" = false , "+y+" = null; ";var _=e.compositeRule;e.compositeRule=p.compositeRule=!0;var w=o;if(w)for(var b,S=-1,P=w.length-1;S<P;)b=w[S+=1],(e.opts.strictKeywords?"object"==typeof b&&Object.keys(b).length>0||!1===b:e.util.schemaHasRules(b,e.RULES.all))?(p.schema=b,p.schemaPath=n+"["+S+"]",p.errSchemaPath=c+"/"+S,s+=" "+e.validate(p)+" ",p.baseId=m):s+=" var "+g+" = true; ",S&&(s+=" if ("+g+" && "+v+") { "+u+" = false; "+y+" = ["+y+", "+S+"]; } else { ",f+="}"),s+=" if ("+g+") { "+u+" = "+v+" = true; "+y+" = "+S+"; }";return e.compositeRule=p.compositeRule=_,s+=f+"if (!"+u+") { var err = ",!1!==e.createErrors?(s+=" { keyword: 'oneOf' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { passingSchemas: "+y+" } ",!1!==e.opts.messages&&(s+=" , message: 'should match exactly one schema in oneOf' "),e.opts.verbose&&(s+=" , schema: validate.schema"+n+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),s+=" } "):s+=" {} ",s+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&d&&(e.async?s+=" throw new ValidationError(vErrors); ":s+=" validate.errors = vErrors; return false; "),s+="} else { errors = "+h+"; if (vErrors !== null) { if ("+h+") vErrors.length = "+h+"; else vErrors = null; }",e.opts.allErrors&&(s+=" } "),s}},46610:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BitstringManager=void 0,t.isIndexSet=async function(e,t,s){const i=r.base64urlDecode(e),a=await s.decompress(i),o=Math.floor(t/8),n=t%8;return!(o>=a.length)&&!!(a[o]&1<<n)};class r{compressor;decompressor;bits;size;constructor(e,t,r){this.compressor=t,this.decompressor=r,this.size=e;const s=Math.ceil(e/8);this.bits=new Uint8Array(s)}setBit(e,t){if(e<0||e>=this.size)throw new Error(`Bit index ${e} out of range (0-${this.size-1})`);const r=Math.floor(e/8),s=e%8;t?this.bits[r]|=1<<s:this.bits[r]&=~(1<<s)}getBit(e){if(e<0||e>=this.size)throw new Error(`Bit index ${e} out of range (0-${this.size-1})`);const t=Math.floor(e/8),r=e%8;return!!(this.bits[t]&1<<r)}getSetBits(){const e=[];for(let t=0;t<this.size;t++)this.getBit(t)&&e.push(t);return e}async encode(){const e=await this.compressor.compress(this.bits);return this.base64urlEncode(e)}static async decode(e,t,s){const i=r.base64urlDecode(e),a=await s.decompress(i),o=8*a.length,n=new r(o,t,s);return n.bits=a,n}getRawBits(){return this.bits}getSize(){return this.size}base64urlEncode(e){return this.bytesToBase64(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}static base64urlDecode(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");for(;t.length%4!=0;)t+="=";return r.base64ToBytes(t)}bytesToBase64(e){const t=Array.from(e).map(e=>String.fromCharCode(e)).join("");return btoa(t)}static base64ToBytes(e){const t=atob(e),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r}static fromSetBits(e,t,s,i){const a=new r(e,s,i);for(const e of t)a.setBit(e,!0);return a}}t.BitstringManager=r},48021:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NoOpOAuthConfigCache=t.InMemoryOAuthConfigCache=void 0,t.InMemoryOAuthConfigCache=class{cache=new Map;async get(e){const t=this.cache.get(e);return t?Date.now()>t.expiresAt?(this.cache.delete(e),null):t.value:null}async set(e,t,r){if(r<=0)return;const s=Date.now()+r;this.cache.set(e,{value:t,expiresAt:s})}async clear(){this.cache.clear()}async delete(e){this.cache.delete(e)}},t.NoOpOAuthConfigCache=class{async get(e){return null}async set(e,t,r){}async clear(){}async delete(e){}}},48505:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MemoryIdentityProvider=t.MemoryNonceCacheProvider=t.MemoryStorageProvider=void 0;const s=r(27087);class i extends s.StorageProvider{store=new Map;async get(e){return this.store.get(e)??null}async set(e,t){this.store.set(e,t)}async delete(e){this.store.delete(e)}async exists(e){return this.store.has(e)}async list(e){const t=Array.from(this.store.keys());return e?t.filter(t=>t.startsWith(e)):t}}t.MemoryStorageProvider=i;class a extends s.NonceCacheProvider{nonces=new Map;async has(e,t){const r=t?`nonce:${t}:${e}`:`nonce:${e}`,s=this.nonces.get(r);return!(!s||Date.now()>s&&(this.nonces.delete(r),1))}async add(e,t,r){const s=r?`nonce:${r}:${e}`:`nonce:${e}`,i=Date.now()+1e3*t;this.nonces.set(s,i)}async cleanup(){const e=Date.now();for(const[t,r]of this.nonces)e>r&&this.nonces.delete(t)}async destroy(){this.nonces.clear()}}t.MemoryNonceCacheProvider=a;class o extends s.IdentityProvider{identity;cryptoProvider;constructor(e){super(),this.cryptoProvider=e}async getIdentity(){return this.identity||(this.identity=await this.generateIdentity()),this.identity}async saveIdentity(e){this.identity=e}async rotateKeys(){return this.identity=await this.generateIdentity(),this.identity}async deleteIdentity(){this.identity=void 0}async generateIdentity(){if(!this.cryptoProvider)throw new Error("Crypto provider required for identity generation");const e=await this.cryptoProvider.generateKeyPair(),t=this.generateDIDFromPublicKey(e.publicKey);return{did:t,kid:`${t}#key-1`,privateKey:e.privateKey,publicKey:e.publicKey,createdAt:(new Date).toISOString(),type:"development"}}generateDIDFromPublicKey(e){return`did:key:z${Buffer.from(e,"base64").toString("base64url").substring(0,32)}`}}t.MemoryIdentityProvider=o},49436:e=>{function t(e){return Promise.resolve().then(()=>{var t=new Error("Cannot find module '"+e+"'");throw t.code="MODULE_NOT_FOUND",t})}t.keys=()=>[],t.resolve=t,t.id=49436,e.exports=t},50399:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OAuthProviderRegistry=void 0,t.OAuthProviderRegistry=class{configService;validator;providers=new Map;constructor(e,t){this.configService=e,this.validator=t}async loadFromAgentShield(e){const t=await this.configService.getOAuthConfig(e);this.providers.clear();for(const[e,r]of Object.entries(t.providers))this.providers.set(e,r)}getProvider(e){return this.providers.get(e)||null}getAllProviders(){return Array.from(this.providers.values())}hasProvider(e){return this.providers.has(e)}getProviderNames(){return Array.from(this.providers.keys())}registerCustomProvider(e,t){this.validator&&this.validator.validate(t,e),this.providers.set(e,t)}getProviderWithParams(e){return this.getProvider(e)||null}}},51708:(e,t,r)=>{"use strict";r.r(t),r.d(t,{canonicalize:()=>s.d,canonicalizeEx:()=>a});var s=r(77753),i=r(10985);function a(e,t){return(0,i.S)(e,t)}},52004:(e,t,r)=>{"use strict";e.exports={$ref:r(12857),allOf:r(67578),anyOf:r(14547),$comment:r(44413),const:r(59087),contains:r(24235),dependencies:r(90083),enum:r(68307),format:r(95545),if:r(82917),items:r(33728),maximum:r(71346),minimum:r(71346),maxItems:r(80536),minItems:r(80536),maxLength:r(83010),minLength:r(83010),maxProperties:r(96111),minProperties:r(96111),multipleOf:r(58047),not:r(13441),oneOf:r(46137),pattern:r(96774),properties:r(86343),propertyNames:r(9931),required:r(91939),uniqueItems:r(57817),validate:r(25572)}},52643:e=>{function t(e){return Promise.resolve().then(()=>{var t=new Error("Cannot find module '"+e+"'");throw t.code="MODULE_NOT_FOUND",t})}t.keys=()=>[],t.resolve=t,t.id=52643,e.exports=t},53084:(e,t,r)=>{"use strict";var s=r(22853),i=r(40985),a=r(28565),o=r(20812),n=r(56039),c=r(36885),d=r(20698),l=r(46079),u=r(9717);e.exports=v,v.prototype.validate=function(e,t){var r;if("string"==typeof e){if(!(r=this.getSchema(e)))throw new Error('no schema with key or ref "'+e+'"')}else{var s=this._addSchema(e);r=s.validate||this._compile(s)}var i=r(t);return!0!==r.$async&&(this.errors=r.errors),i},v.prototype.compile=function(e,t){var r=this._addSchema(e,void 0,t);return r.validate||this._compile(r)},v.prototype.addSchema=function(e,t,r,s){if(Array.isArray(e)){for(var a=0;a<e.length;a++)this.addSchema(e[a],void 0,r,s);return this}var o=this._getId(e);if(void 0!==o&&"string"!=typeof o)throw new Error("schema id must be string");return P(this,t=i.normalizeId(t||o)),this._schemas[t]=this._addSchema(e,r,s,!0),this},v.prototype.addMetaSchema=function(e,t,r){return this.addSchema(e,t,r,!0),this},v.prototype.validateSchema=function(e,t){var r,s,i=e.$schema;if(void 0!==i&&"string"!=typeof i)throw new Error("$schema must be a string");if(!(i=i||this._opts.defaultMeta||(r=this,s=r._opts.meta,r._opts.defaultMeta="object"==typeof s?r._getId(s)||s:r.getSchema(f)?f:void 0,r._opts.defaultMeta)))return this.logger.warn("meta-schema not available"),this.errors=null,!0;var a=this.validate(i,e);if(!a&&t){var o="schema is invalid: "+this.errorsText();if("log"!=this._opts.validateSchema)throw new Error(o);this.logger.error(o)}return a},v.prototype.getSchema=function(e){var t=y(this,e);switch(typeof t){case"object":return t.validate||this._compile(t);case"string":return this.getSchema(t);case"undefined":return function(e,t){var r=i.schema.call(e,{schema:{}},t);if(r){var a=r.schema,n=r.root,c=r.baseId,d=s.call(e,a,n,void 0,c);return e._fragments[t]=new o({ref:t,fragment:!0,schema:a,root:n,baseId:c,validate:d}),d}}(this,e)}},v.prototype.removeSchema=function(e){if(e instanceof RegExp)return _(this,this._schemas,e),_(this,this._refs,e),this;switch(typeof e){case"undefined":return _(this,this._schemas),_(this,this._refs),this._cache.clear(),this;case"string":var t=y(this,e);return t&&this._cache.del(t.cacheKey),delete this._schemas[e],delete this._refs[e],this;case"object":var r=this._opts.serialize,s=r?r(e):e;this._cache.del(s);var a=this._getId(e);a&&(a=i.normalizeId(a),delete this._schemas[a],delete this._refs[a])}return this},v.prototype.addFormat=function(e,t){return"string"==typeof t&&(t=new RegExp(t)),this._formats[e]=t,this},v.prototype.errorsText=function(e,t){if(!(e=e||this.errors))return"No errors";for(var r=void 0===(t=t||{}).separator?", ":t.separator,s=void 0===t.dataVar?"data":t.dataVar,i="",a=0;a<e.length;a++){var o=e[a];o&&(i+=s+o.dataPath+" "+o.message+r)}return i.slice(0,-r.length)},v.prototype._addSchema=function(e,t,r,s){if("object"!=typeof e&&"boolean"!=typeof e)throw new Error("schema should be object or boolean");var a=this._opts.serialize,n=a?a(e):e,c=this._cache.get(n);if(c)return c;s=s||!1!==this._opts.addUsedSchema;var d=i.normalizeId(this._getId(e));d&&s&&P(this,d);var l,u=!1!==this._opts.validateSchema&&!t;u&&!(l=d&&d==i.normalizeId(e.$schema))&&this.validateSchema(e,!0);var h=i.ids.call(this,e),p=new o({id:d,schema:e,localRefs:h,cacheKey:n,meta:r});return"#"!=d[0]&&s&&(this._refs[d]=p),this._cache.put(n,p),u&&l&&this.validateSchema(e,!0),p},v.prototype._compile=function(e,t){if(e.compiling)return e.validate=a,a.schema=e.schema,a.errors=null,a.root=t||a,!0===e.schema.$async&&(a.$async=!0),a;var r,i;e.compiling=!0,e.meta&&(r=this._opts,this._opts=this._metaOpts);try{i=s.call(this,e.schema,t,e.localRefs)}catch(t){throw delete e.validate,t}finally{e.compiling=!1,e.meta&&(this._opts=r)}return e.validate=i,e.refs=i.refs,e.refVal=i.refVal,e.root=i.root,i;function a(){var t=e.validate,r=t.apply(this,arguments);return a.errors=t.errors,r}},v.prototype.compileAsync=r(6069);var h=r(43528);v.prototype.addKeyword=h.add,v.prototype.getKeyword=h.get,v.prototype.removeKeyword=h.remove,v.prototype.validateKeyword=h.validate;var p=r(72916);v.ValidationError=p.Validation,v.MissingRefError=p.MissingRef,v.$dataMetaSchema=l;var f="http://json-schema.org/draft-07/schema",g=["removeAdditional","useDefaults","coerceTypes","strictDefaults"],m=["/properties"];function v(e){if(!(this instanceof v))return new v(e);e=this._opts=u.copy(e)||{},function(e){var t=e._opts.logger;if(!1===t)e.logger={log:E,warn:E,error:E};else{if(void 0===t&&(t=console),!("object"==typeof t&&t.log&&t.warn&&t.error))throw new Error("logger must implement log, warn and error methods");e.logger=t}}(this),this._schemas={},this._refs={},this._fragments={},this._formats=c(e.format),this._cache=e.cache||new a,this._loadingSchemas={},this._compilations=[],this.RULES=d(),this._getId=function(e){switch(e.schemaId){case"auto":return S;case"id":return w;default:return b}}(e),e.loopRequired=e.loopRequired||1/0,"property"==e.errorDataPath&&(e._errorDataPathProperty=!0),void 0===e.serialize&&(e.serialize=n),this._metaOpts=function(e){for(var t=u.copy(e._opts),r=0;r<g.length;r++)delete t[g[r]];return t}(this),e.formats&&function(e){for(var t in e._opts.formats){var r=e._opts.formats[t];e.addFormat(t,r)}}(this),e.keywords&&function(e){for(var t in e._opts.keywords){var r=e._opts.keywords[t];e.addKeyword(t,r)}}(this),function(e){var t;if(e._opts.$data&&(t=r(13215),e.addMetaSchema(t,t.$id,!0)),!1!==e._opts.meta){var s=r(12269);e._opts.$data&&(s=l(s,m)),e.addMetaSchema(s,f,!0),e._refs["http://json-schema.org/schema"]=f}}(this),"object"==typeof e.meta&&this.addMetaSchema(e.meta),e.nullable&&this.addKeyword("nullable",{metaSchema:{type:"boolean"}}),function(e){var t=e._opts.schemas;if(t)if(Array.isArray(t))e.addSchema(t);else for(var r in t)e.addSchema(t[r],r)}(this)}function y(e,t){return t=i.normalizeId(t),e._schemas[t]||e._refs[t]||e._fragments[t]}function _(e,t,r){for(var s in t){var i=t[s];i.meta||r&&!r.test(s)||(e._cache.del(i.cacheKey),delete t[s])}}function w(e){return e.$id&&this.logger.warn("schema $id ignored",e.$id),e.id}function b(e){return e.id&&this.logger.warn("schema id ignored",e.id),e.$id}function S(e){if(e.$id&&e.id&&e.$id!=e.id)throw new Error("schema $id is different from id");return e.$id||e.id}function P(e,t){if(e._schemas[t]||e._refs[t])throw new Error('schema with key or id "'+t+'" already exists')}function E(){}},53683:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProofVerificationError=t.PROOF_VERIFICATION_ERROR_CODES=void 0,t.createProofVerificationError=function(e,t,s){return new r(e,t,s)},t.PROOF_VERIFICATION_ERROR_CODES={INVALID_PROOF_STRUCTURE:"INVALID_PROOF_STRUCTURE",MISSING_REQUIRED_FIELD:"MISSING_REQUIRED_FIELD",NONCE_REPLAY_DETECTED:"NONCE_REPLAY_DETECTED",TIMESTAMP_SKEW_EXCEEDED:"TIMESTAMP_SKEW_EXCEEDED",TIMESTAMP_INVALID:"TIMESTAMP_INVALID",INVALID_JWS_SIGNATURE:"INVALID_JWS_SIGNATURE",INVALID_JWS_FORMAT:"INVALID_JWS_FORMAT",INVALID_JWS_HEADER:"INVALID_JWS_HEADER",INVALID_JWS_PAYLOAD:"INVALID_JWS_PAYLOAD",INVALID_JWS_SIGNATURE_BASE64:"INVALID_JWS_SIGNATURE_BASE64",UNSUPPORTED_ALGORITHM:"UNSUPPORTED_ALGORITHM",INVALID_JWK_FORMAT:"INVALID_JWK_FORMAT",INVALID_JWK_KTY:"INVALID_JWK_KTY",INVALID_JWK_CRV:"INVALID_JWK_CRV",INVALID_JWK_X_FIELD:"INVALID_JWK_X_FIELD",INVALID_JWK_KEY_LENGTH:"INVALID_JWK_KEY_LENGTH",JWK_KID_MISMATCH:"JWK_KID_MISMATCH",DID_RESOLUTION_FAILED:"DID_RESOLUTION_FAILED",DID_DOCUMENT_NOT_FOUND:"DID_DOCUMENT_NOT_FOUND",VERIFICATION_METHOD_NOT_FOUND:"VERIFICATION_METHOD_NOT_FOUND",PUBLIC_KEY_NOT_FOUND:"PUBLIC_KEY_NOT_FOUND",UNSUPPORTED_DID_METHOD:"UNSUPPORTED_DID_METHOD",VERIFICATION_ERROR:"VERIFICATION_ERROR",INTERNAL_ERROR:"INTERNAL_ERROR"};class r extends Error{code;details;constructor(e,t,r){super(t),this.code=e,this.details=r,this.name="ProofVerificationError"}}t.ProofVerificationError=r},53871:function(e,t,r){"use strict";var s=this&&this.__createBinding||(Object.create?function(e,t,r,s){void 0===s&&(s=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,s,i)}:function(e,t,r,s){void 0===s&&(s=r),e[s]=t[r]}),i=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||s(t,e,r)};Object.defineProperty(t,"__esModule",{value:!0}),i(r(17214),t),i(r(98448),t),i(r(32299),t),i(r(75306),t)},55921:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DelegationGraphManager=void 0,t.createDelegationGraph=function(e){return new r(e)};class r{storage;constructor(e){this.storage=e}async registerDelegation(e){const t={id:e.id,parentId:e.parentId,children:[],issuerDid:e.issuerDid,subjectDid:e.subjectDid,credentialStatusId:e.credentialStatusId};return await this.storage.setNode(t),e.parentId&&await this.addChildToParent(e.parentId,e.id),t}async addChildToParent(e,t){const r=await this.storage.getNode(e);if(!r)throw new Error(`Parent delegation not found: ${e}`);r.children.includes(t)||(r.children.push(t),await this.storage.setNode(r))}async getNode(e){return this.storage.getNode(e)}async getChildren(e){return this.storage.getChildren(e)}async getDescendants(e){return this.storage.getDescendants(e)}async getChain(e){return this.storage.getChain(e)}async isAncestor(e,t){return(await this.getChain(t)).some(t=>t.id===e)}async getDepth(e){return(await this.getChain(e)).length-1}async validateChain(e){const t=await this.getChain(e);if(0===t.length)return{valid:!1,reason:"Delegation not found"};for(let e=1;e<t.length;e++){const r=t[e-1],s=t[e];if(s.issuerDid!==r.subjectDid)return{valid:!1,reason:`Invalid chain: ${s.id} issued by ${s.issuerDid} but parent ${r.id} subject is ${r.subjectDid}`};if(s.parentId!==r.id)return{valid:!1,reason:`Invalid chain: ${s.id} parentId=${s.parentId} but actual parent is ${r.id}`}}return{valid:!0}}async removeDelegation(e){const t=await this.storage.getNode(e);if(t){if(t.parentId){const r=await this.storage.getNode(t.parentId);r&&(r.children=r.children.filter(t=>t!==e),await this.storage.setNode(r))}await this.storage.deleteNode(e)}}}t.DelegationGraphManager=r},56039:e=>{"use strict";e.exports=function(e,t){t||(t={}),"function"==typeof t&&(t={cmp:t});var r,s="boolean"==typeof t.cycles&&t.cycles,i=t.cmp&&(r=t.cmp,function(e){return function(t,s){var i={key:t,value:e[t]},a={key:s,value:e[s]};return r(i,a)}}),a=[];return function e(t){if(t&&t.toJSON&&"function"==typeof t.toJSON&&(t=t.toJSON()),void 0!==t){if("number"==typeof t)return isFinite(t)?""+t:"null";if("object"!=typeof t)return JSON.stringify(t);var r,o;if(Array.isArray(t)){for(o="[",r=0;r<t.length;r++)r&&(o+=","),o+=e(t[r])||"null";return o+"]"}if(null===t)return"null";if(-1!==a.indexOf(t)){if(s)return JSON.stringify("__cycle__");throw new TypeError("Converting circular structure to JSON")}var n=a.push(t)-1,c=Object.keys(t).sort(i&&i(t));for(o="",r=0;r<c.length;r++){var d=c[r],l=e(t[d]);l&&(o&&(o+=","),o+=JSON.stringify(d)+":"+l)}return a.splice(n,1),"{"+o+"}"}}(e)}},57817:e=>{"use strict";e.exports=function(e,t,r){var s,i=" ",a=e.level,o=e.dataLevel,n=e.schema[t],c=e.schemaPath+e.util.getProperty(t),d=e.errSchemaPath+"/"+t,l=!e.opts.allErrors,u="data"+(o||""),h="valid"+a,p=e.opts.$data&&n&&n.$data;if(p?(i+=" var schema"+a+" = "+e.util.getData(n.$data,o,e.dataPathArr)+"; ",s="schema"+a):s=n,(n||p)&&!1!==e.opts.uniqueItems){p&&(i+=" var "+h+"; if ("+s+" === false || "+s+" === undefined) "+h+" = true; else if (typeof "+s+" != 'boolean') "+h+" = false; else { "),i+=" var i = "+u+".length , "+h+" = true , j; if (i > 1) { ";var f=e.schema.items&&e.schema.items.type,g=Array.isArray(f);if(!f||"object"==f||"array"==f||g&&(f.indexOf("object")>=0||f.indexOf("array")>=0))i+=" outer: for (;i--;) { for (j = i; j--;) { if (equal("+u+"[i], "+u+"[j])) { "+h+" = false; break outer; } } } ";else{i+=" var itemIndices = {}, item; for (;i--;) { var item = "+u+"[i]; ";var m="checkDataType"+(g?"s":"");i+=" if ("+e.util[m](f,"item",e.opts.strictNumbers,!0)+") continue; ",g&&(i+=" if (typeof item == 'string') item = '\"' + item; "),i+=" if (typeof itemIndices[item] == 'number') { "+h+" = false; j = itemIndices[item]; break; } itemIndices[item] = i; } "}i+=" } ",p&&(i+=" } "),i+=" if (!"+h+") { ";var v=v||[];v.push(i),i="",!1!==e.createErrors?(i+=" { keyword: 'uniqueItems' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(d)+" , params: { i: i, j: j } ",!1!==e.opts.messages&&(i+=" , message: 'should NOT have duplicate items (items ## ' + j + ' and ' + i + ' are identical)' "),e.opts.verbose&&(i+=" , schema: ",i+=p?"validate.schema"+c:""+n,i+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),i+=" } "):i+=" {} ";var y=i;i=v.pop(),!e.compositeRule&&l?e.async?i+=" throw new ValidationError(["+y+"]); ":i+=" validate.errors = ["+y+"]; return false; ":i+=" var err = "+y+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",i+=" } ",l&&(i+=" else { ")}else l&&(i+=" if (true) { ");return i}},58047:e=>{"use strict";e.exports=function(e,t,r){var s,i=" ",a=e.level,o=e.dataLevel,n=e.schema[t],c=e.schemaPath+e.util.getProperty(t),d=e.errSchemaPath+"/"+t,l=!e.opts.allErrors,u="data"+(o||""),h=e.opts.$data&&n&&n.$data;if(h?(i+=" var schema"+a+" = "+e.util.getData(n.$data,o,e.dataPathArr)+"; ",s="schema"+a):s=n,!h&&"number"!=typeof n)throw new Error(t+" must be number");i+="var division"+a+";if (",h&&(i+=" "+s+" !== undefined && ( typeof "+s+" != 'number' || "),i+=" (division"+a+" = "+u+" / "+s+", ",e.opts.multipleOfPrecision?i+=" Math.abs(Math.round(division"+a+") - division"+a+") > 1e-"+e.opts.multipleOfPrecision+" ":i+=" division"+a+" !== parseInt(division"+a+") ",i+=" ) ",h&&(i+=" ) "),i+=" ) { ";var p=p||[];p.push(i),i="",!1!==e.createErrors?(i+=" { keyword: 'multipleOf' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(d)+" , params: { multipleOf: "+s+" } ",!1!==e.opts.messages&&(i+=" , message: 'should be multiple of ",i+=h?"' + "+s:s+"'"),e.opts.verbose&&(i+=" , schema: ",i+=h?"validate.schema"+c:""+n,i+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),i+=" } "):i+=" {} ";var f=i;return i=p.pop(),!e.compositeRule&&l?e.async?i+=" throw new ValidationError(["+f+"]); ":i+=" validate.errors = ["+f+"]; return false; ":i+=" var err = "+f+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",i+="} ",l&&(i+=" else { "),i}},59087:e=>{"use strict";e.exports=function(e,t,r){var s=" ",i=e.level,a=e.dataLevel,o=e.schema[t],n=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,d=!e.opts.allErrors,l="data"+(a||""),u="valid"+i,h=e.opts.$data&&o&&o.$data;h&&(s+=" var schema"+i+" = "+e.util.getData(o.$data,a,e.dataPathArr)+"; "),h||(s+=" var schema"+i+" = validate.schema"+n+";"),s+="var "+u+" = equal("+l+", schema"+i+"); if (!"+u+") { ";var p=p||[];p.push(s),s="",!1!==e.createErrors?(s+=" { keyword: 'const' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { allowedValue: schema"+i+" } ",!1!==e.opts.messages&&(s+=" , message: 'should be equal to constant' "),e.opts.verbose&&(s+=" , schema: validate.schema"+n+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),s+=" } "):s+=" {} ";var f=s;return s=p.pop(),!e.compositeRule&&d?e.async?s+=" throw new ValidationError(["+f+"]); ":s+=" validate.errors = ["+f+"]; return false; ":s+=" var err = "+f+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+=" }",d&&(s+=" else { "),s}},61812:e=>{"use strict";e.exports=function(e){for(var t,r=0,s=e.length,i=0;i<s;)r++,(t=e.charCodeAt(i++))>=55296&&t<=56319&&i<s&&56320==(64512&(t=e.charCodeAt(i)))&&i++;return r}},62175:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OAuthService=void 0,t.OAuthService=class{config;constructor(e){this.config={configService:e.configService,fetchProvider:e.fetchProvider,agentShieldApiUrl:e.agentShieldApiUrl,agentShieldApiKey:e.agentShieldApiKey,projectId:e.projectId,logger:e.logger||(()=>{})}}async exchangeToken(e,t,r,s){const i=(await this.config.configService.getOAuthConfig(this.config.projectId)).providers[e];if(!i)throw new Error(`Provider "${e}" not configured for project "${this.config.projectId}"`);if(i.supportsPKCE&&!i.proxyMode){if(!r)throw new Error(`Provider "${e}" requires PKCE code_verifier for token exchange`);return this.exchangeTokenPKCE(i,t,r,s||"")}if(i.proxyMode)return this.exchangeTokenProxy(i,t,r,s||"");throw new Error(`Provider "${e}" configuration is invalid: must support PKCE or use proxy mode`)}async exchangeTokenPKCE(e,t,r,s){this.config.logger("[OAuthService] Exchanging token with PKCE",{provider:e.authorizationUrl,tokenUrl:e.tokenUrl});const i=await this.config.fetchProvider.fetch(e.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new URLSearchParams({grant_type:"authorization_code",code:t,redirect_uri:s,client_id:e.clientId,code_verifier:r}).toString()});if(!i.ok){const t=await i.text().catch(()=>"Unknown error");let r;try{r=JSON.parse(t)}catch{r={error:t}}const s=r.error_description||r.error||t;throw this.config.logger("[OAuthService] Token exchange failed",{status:i.status,error:s,provider:e.tokenUrl}),new Error(`Token exchange failed: ${s} (${i.status})`)}const a=await i.json();if(!a.access_token)throw new Error("Token response missing access_token");const o=a.expires_in||3600,n=Date.now()+1e3*o,c={access_token:a.access_token,refresh_token:a.refresh_token,expires_in:o,expires_at:n,token_type:a.token_type||"Bearer",scope:a.scope};return this.config.logger("[OAuthService] Token exchange successful",{provider:e.tokenUrl,expiresAt:new Date(n).toISOString(),hasRefreshToken:!!c.refresh_token}),c}async exchangeTokenProxy(e,t,r,s){const i=`${this.config.agentShieldApiUrl}/api/v1/oauth/token`;this.config.logger("[OAuthService] Exchanging token via proxy",{proxyUrl:i,provider:e.authorizationUrl,hasCodeVerifier:!!r,supportsPKCE:e.supportsPKCE});const a={grant_type:"authorization_code",code:t,redirect_uri:s||"",provider:e.authorizationUrl,project_id:this.config.projectId};e.supportsPKCE&&r&&(a.code_verifier=r);const o=await this.config.fetchProvider.fetch(i,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.agentShieldApiKey}`},body:JSON.stringify(a)});if(!o.ok){const e=await o.text().catch(()=>"Unknown error");let t;try{t=JSON.parse(e)}catch{t={error:e}}const r=t.error_description||t.error||e;throw this.config.logger("[OAuthService] Proxy token exchange failed",{status:o.status,error:r,proxyUrl:i}),new Error(`Proxy token exchange failed: ${r} (${o.status})`)}const n=await o.json(),c=n.data||n;if(!c.access_token)throw new Error("Proxy token response missing access_token");const d=c.expires_in||3600,l=Date.now()+1e3*d,u={access_token:c.access_token,refresh_token:c.refresh_token,expires_in:d,expires_at:l,token_type:c.token_type||"Bearer",scope:c.scope};return this.config.logger("[OAuthService] Proxy token exchange successful",{proxyUrl:i,expiresAt:new Date(l).toISOString(),hasRefreshToken:!!u.refresh_token}),u}async refreshToken(e,t){const r=(await this.config.configService.getOAuthConfig(this.config.projectId)).providers[e];return r?r.supportsPKCE&&!r.proxyMode?this.refreshTokenPKCE(r,t):r.proxyMode?this.refreshTokenProxy(r,t):null:(this.config.logger("[OAuthService] Provider not found for refresh",{provider:e}),null)}async refreshTokenPKCE(e,t){this.config.logger("[OAuthService] Refreshing token with PKCE",{provider:e.tokenUrl});try{const r=await this.config.fetchProvider.fetch(e.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:t,client_id:e.clientId}).toString()});if(!r.ok)return this.config.logger("[OAuthService] Token refresh failed",{status:r.status,provider:e.tokenUrl}),null;const s=await r.json();if(!s.access_token)return this.config.logger("[OAuthService] Token refresh response missing access_token"),null;const i=s.expires_in||3600,a=Date.now()+1e3*i,o={access_token:s.access_token,refresh_token:s.refresh_token||t,expires_in:i,expires_at:a,token_type:s.token_type||"Bearer",scope:s.scope};return this.config.logger("[OAuthService] Token refresh successful",{provider:e.tokenUrl,expiresAt:new Date(a).toISOString()}),o}catch(t){return this.config.logger("[OAuthService] Token refresh error",{error:t instanceof Error?t.message:String(t),provider:e.tokenUrl}),null}}async refreshTokenProxy(e,t){const r=`${this.config.agentShieldApiUrl}/api/v1/oauth/token`;this.config.logger("[OAuthService] Refreshing token via proxy",{proxyUrl:r,provider:e.authorizationUrl});try{const s=await this.config.fetchProvider.fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.agentShieldApiKey}`},body:JSON.stringify({grant_type:"refresh_token",refresh_token:t,provider:e.authorizationUrl,project_id:this.config.projectId})});if(!s.ok)return this.config.logger("[OAuthService] Proxy token refresh failed",{status:s.status,proxyUrl:r}),null;const i=await s.json(),a=i.data||i;if(!a.access_token)return this.config.logger("[OAuthService] Proxy token refresh response missing access_token"),null;const o=a.expires_in||3600,n=Date.now()+1e3*o,c={access_token:a.access_token,refresh_token:a.refresh_token||t,expires_in:o,expires_at:n,token_type:a.token_type||"Bearer",scope:a.scope};return this.config.logger("[OAuthService] Proxy token refresh successful",{proxyUrl:r,expiresAt:new Date(n).toISOString()}),c}catch(e){return this.config.logger("[OAuthService] Proxy token refresh error",{error:e instanceof Error?e.message:String(e),proxyUrl:r}),null}}}},62408:e=>{"use strict";e.exports=require("@kya-os/contracts")},63969:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.canonicalizeJSON=function e(t){if(null===t)return"null";if("boolean"==typeof t)return t.toString();if("number"==typeof t){if(!isFinite(t))throw new Error("Cannot canonicalize non-finite number");return JSON.stringify(t)}if("string"==typeof t)return JSON.stringify(t);if(Array.isArray(t))return"["+t.map(t=>e(t)).join(",")+"]";if("object"==typeof t)return"{"+Object.keys(t).sort().map(r=>{const s=e(t[r]);return JSON.stringify(r)+":"+s}).join(",")+"}";throw new Error("Cannot canonicalize type: "+typeof t)}},65067:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UserDidManager=void 0,t.UserDidManager=class{config;sessionDidCache=new Map;constructor(e){this.config=e}async getOrCreateUserDid(e,t){if(this.sessionDidCache.has(e))return this.sessionDidCache.get(e);if(t&&t.provider&&t.subject&&this.config.storage?.getByOAuth)try{const r=await this.config.storage.getByOAuth(t.provider,t.subject);if(r){if(console.log("[UserDidManager] Found persistent user DID from OAuth mapping:",{provider:t.provider,userDid:r.substring(0,20)+"..."}),this.sessionDidCache.set(e,r),this.config.storage)try{await this.config.storage.set(e,r,1800)}catch(e){console.warn("[UserDidManager] Failed to cache persistent DID in session storage:",e)}return r}}catch(e){console.warn("[UserDidManager] OAuth lookup failed, falling back to session storage:",e)}if(this.config.storage)try{const r=await this.config.storage.get(e);if(r){if(this.sessionDidCache.set(e,r),t&&t.provider&&t.subject&&this.config.storage.setByOAuth)try{await this.config.storage.setByOAuth(t.provider,t.subject,r,7776e3),console.log("[UserDidManager] Created persistent OAuth mapping for existing user DID:",{provider:t.provider,userDid:r.substring(0,20)+"..."})}catch(e){console.warn("[UserDidManager] Failed to create OAuth mapping:",e)}return r}}catch(e){console.warn("[UserDidManager] Storage.get failed, generating new DID:",e)}const r=await this.generateUserDid();if(this.sessionDidCache.set(e,r),this.config.storage)try{await this.config.storage.set(e,r,1800)}catch(e){console.warn("[UserDidManager] Storage.set failed, continuing with cached DID:",e)}if(t&&t.provider&&t.subject&&this.config.storage?.setByOAuth)try{await this.config.storage.setByOAuth(t.provider,t.subject,r,7776e3),console.log("[UserDidManager] Created persistent OAuth mapping for new user DID:",{provider:t.provider,userDid:r.substring(0,20)+"..."})}catch(e){console.warn("[UserDidManager] Failed to create OAuth mapping:",e)}return r}async generateUserDid(){this.config.useDidWeb&&this.config.didWebBaseUrl&&console.warn("[UserDidManager] did:web not yet implemented, using did:key");const e=await this.config.crypto.generateKeyPair(),t=this.base64ToBytes(e.publicKey);return this.generateDidKeyFromPublicKey(t)}generateDidKeyFromPublicKey(e){const t=new Uint8Array([237,1]),r=new Uint8Array(t.length+e.length);return r.set(t),r.set(e,t.length),`did:key:z${this.base58Encode(r)}`}base58Encode(e){let t=BigInt(0);for(let r=0;r<e.length;r++)t=t*BigInt(256)+BigInt(e[r]);let r="";for(;t>0;)r="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"[Number(t%BigInt(58))]+r,t/=BigInt(58);for(let t=0;t<e.length&&0===e[t];t++)r="1"+r;return r}base64ToBytes(e){if("undefined"!=typeof Buffer)return new Uint8Array(Buffer.from(e,"base64"));{const t=atob(e),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r}}async getUserDid(e){if(this.sessionDidCache.has(e))return this.sessionDidCache.get(e);if(this.config.storage){const t=await this.config.storage.get(e);if(t)return this.sessionDidCache.set(e,t),t}return null}async clearUserDid(e){if(this.sessionDidCache.delete(e),this.config.storage)try{await this.config.storage.delete(e)}catch(e){console.warn("[UserDidManager] Storage.delete failed, continuing:",e)}}clearCache(){this.sessionDidCache.clear()}}},67371:e=>{"use strict";e.exports=function e(t,r){if(t===r)return!0;if(t&&r&&"object"==typeof t&&"object"==typeof r){if(t.constructor!==r.constructor)return!1;var s,i,a;if(Array.isArray(t)){if((s=t.length)!=r.length)return!1;for(i=s;0!==i--;)if(!e(t[i],r[i]))return!1;return!0}if(t.constructor===RegExp)return t.source===r.source&&t.flags===r.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===r.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===r.toString();if((s=(a=Object.keys(t)).length)!==Object.keys(r).length)return!1;for(i=s;0!==i--;)if(!Object.prototype.hasOwnProperty.call(r,a[i]))return!1;for(i=s;0!==i--;){var o=a[i];if(!e(t[o],r[o]))return!1}return!0}return t!=t&&r!=r}},67578:e=>{"use strict";e.exports=function(e,t,r){var s=" ",i=e.schema[t],a=e.schemaPath+e.util.getProperty(t),o=e.errSchemaPath+"/"+t,n=!e.opts.allErrors,c=e.util.copy(e),d="";c.level++;var l="valid"+c.level,u=c.baseId,h=!0,p=i;if(p)for(var f,g=-1,m=p.length-1;g<m;)f=p[g+=1],(e.opts.strictKeywords?"object"==typeof f&&Object.keys(f).length>0||!1===f:e.util.schemaHasRules(f,e.RULES.all))&&(h=!1,c.schema=f,c.schemaPath=a+"["+g+"]",c.errSchemaPath=o+"/"+g,s+=" "+e.validate(c)+" ",c.baseId=u,n&&(s+=" if ("+l+") { ",d+="}"));return n&&(s+=h?" if (true) { ":" "+d.slice(0,-1)+" "),s}},68252:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProviderResolver=void 0,t.ProviderResolver=class{registry;configService;constructor(e,t){this.registry=e,this.configService=t}async resolveProvider(e,t){if(e.oauthProvider){if(0===this.registry.getProviderNames().length&&await this.registry.loadFromAgentShield(t),!this.registry.hasProvider(e.oauthProvider))throw new Error(`Provider "${e.oauthProvider}" not configured for project "${t}". Add provider in project settings.`);return e.oauthProvider}const r=this.inferProviderFromScopes(e.requiredScopes||[]);if(r&&(0===this.registry.getProviderNames().length&&await this.registry.loadFromAgentShield(t),this.registry.hasProvider(r)))return console.log(`[ProviderResolver] Inferred provider "${r}" from scopes`),r;if(await this.registry.loadFromAgentShield(t),this.registry.getAllProviders().length>0){const e=this.registry.getProviderNames()[0];return console.warn(`[ProviderResolver] Tool does not specify oauthProvider. Using first configured provider "${e}" as fallback. This is deprecated - configure oauthProvider in AgentShield dashboard for Phase 2+.`),e}throw new Error(`Tool requires OAuth but no provider could be resolved. Either specify oauthProvider in tool protection config, or configure at least one provider for project "${t}".`)}inferProviderFromScopes(e){if(!e||0===e.length)return null;const t=e.map(e=>e.split(":")[0].toLowerCase()),r={github:"github",google:"google",gmail:"google",calendar:"google",microsoft:"microsoft",outlook:"microsoft",slack:"slack",auth0:"auth0",okta:"okta"},s=new Set(t.map(e=>r[e]).filter(Boolean));return 1===s.size?Array.from(s)[0]:null}}},68307:e=>{"use strict";e.exports=function(e,t,r){var s=" ",i=e.level,a=e.dataLevel,o=e.schema[t],n=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,d=!e.opts.allErrors,l="data"+(a||""),u="valid"+i,h=e.opts.$data&&o&&o.$data;h&&(s+=" var schema"+i+" = "+e.util.getData(o.$data,a,e.dataPathArr)+"; ");var p="i"+i,f="schema"+i;h||(s+=" var "+f+" = validate.schema"+n+";"),s+="var "+u+";",h&&(s+=" if (schema"+i+" === undefined) "+u+" = true; else if (!Array.isArray(schema"+i+")) "+u+" = false; else {"),s+=u+" = false;for (var "+p+"=0; "+p+"<"+f+".length; "+p+"++) if (equal("+l+", "+f+"["+p+"])) { "+u+" = true; break; }",h&&(s+=" } "),s+=" if (!"+u+") { ";var g=g||[];g.push(s),s="",!1!==e.createErrors?(s+=" { keyword: 'enum' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { allowedValues: schema"+i+" } ",!1!==e.opts.messages&&(s+=" , message: 'should be equal to one of the allowed values' "),e.opts.verbose&&(s+=" , schema: validate.schema"+n+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),s+=" } "):s+=" {} ";var m=s;return s=g.pop(),!e.compositeRule&&d?e.async?s+=" throw new ValidationError(["+m+"]); ":s+=" validate.errors = ["+m+"]; return false; ":s+=" var err = "+m+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+=" }",d&&(s+=" else { "),s}},71346:e=>{"use strict";e.exports=function(e,t,r){var s,i=" ",a=e.level,o=e.dataLevel,n=e.schema[t],c=e.schemaPath+e.util.getProperty(t),d=e.errSchemaPath+"/"+t,l=!e.opts.allErrors,u="data"+(o||""),h=e.opts.$data&&n&&n.$data;h?(i+=" var schema"+a+" = "+e.util.getData(n.$data,o,e.dataPathArr)+"; ",s="schema"+a):s=n;var p="maximum"==t,f=p?"exclusiveMaximum":"exclusiveMinimum",g=e.schema[f],m=e.opts.$data&&g&&g.$data,v=p?"<":">",y=p?">":"<",_=void 0;if(!h&&"number"!=typeof n&&void 0!==n)throw new Error(t+" must be number");if(!m&&void 0!==g&&"number"!=typeof g&&"boolean"!=typeof g)throw new Error(f+" must be number or boolean");if(m){var w,b=e.util.getData(g.$data,o,e.dataPathArr),S="exclusive"+a,P="exclType"+a,E="exclIsNumber"+a,I="' + "+(C="op"+a)+" + '";i+=" var schemaExcl"+a+" = "+b+"; ",i+=" var "+S+"; var "+P+" = typeof "+(b="schemaExcl"+a)+"; if ("+P+" != 'boolean' && "+P+" != 'undefined' && "+P+" != 'number') { ",_=f,(w=w||[]).push(i),i="",!1!==e.createErrors?(i+=" { keyword: '"+(_||"_exclusiveLimit")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(d)+" , params: {} ",!1!==e.opts.messages&&(i+=" , message: '"+f+" should be boolean' "),e.opts.verbose&&(i+=" , schema: validate.schema"+c+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),i+=" } "):i+=" {} ";var k=i;i=w.pop(),!e.compositeRule&&l?e.async?i+=" throw new ValidationError(["+k+"]); ":i+=" validate.errors = ["+k+"]; return false; ":i+=" var err = "+k+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",i+=" } else if ( ",h&&(i+=" ("+s+" !== undefined && typeof "+s+" != 'number') || "),i+=" "+P+" == 'number' ? ( ("+S+" = "+s+" === undefined || "+b+" "+v+"= "+s+") ? "+u+" "+y+"= "+b+" : "+u+" "+y+" "+s+" ) : ( ("+S+" = "+b+" === true) ? "+u+" "+y+"= "+s+" : "+u+" "+y+" "+s+" ) || "+u+" !== "+u+") { var op"+a+" = "+S+" ? '"+v+"' : '"+v+"='; ",void 0===n&&(_=f,d=e.errSchemaPath+"/"+f,s=b,h=m)}else if(I=v,(E="number"==typeof g)&&h){var C="'"+I+"'";i+=" if ( ",h&&(i+=" ("+s+" !== undefined && typeof "+s+" != 'number') || "),i+=" ( "+s+" === undefined || "+g+" "+v+"= "+s+" ? "+u+" "+y+"= "+g+" : "+u+" "+y+" "+s+" ) || "+u+" !== "+u+") { "}else E&&void 0===n?(S=!0,_=f,d=e.errSchemaPath+"/"+f,s=g,y+="="):(E&&(s=Math[p?"min":"max"](g,n)),g===(!E||s)?(S=!0,_=f,d=e.errSchemaPath+"/"+f,y+="="):(S=!1,I+="=")),C="'"+I+"'",i+=" if ( ",h&&(i+=" ("+s+" !== undefined && typeof "+s+" != 'number') || "),i+=" "+u+" "+y+" "+s+" || "+u+" !== "+u+") { ";return _=_||t,(w=w||[]).push(i),i="",!1!==e.createErrors?(i+=" { keyword: '"+(_||"_limit")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(d)+" , params: { comparison: "+C+", limit: "+s+", exclusive: "+S+" } ",!1!==e.opts.messages&&(i+=" , message: 'should be "+I+" ",i+=h?"' + "+s:s+"'"),e.opts.verbose&&(i+=" , schema: ",i+=h?"validate.schema"+c:""+n,i+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),i+=" } "):i+=" {} ",k=i,i=w.pop(),!e.compositeRule&&l?e.async?i+=" throw new ValidationError(["+k+"]); ":i+=" validate.errors = ["+k+"]; return false; ":i+=" var err = "+k+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",i+=" } ",l&&(i+=" else { "),i}},72114:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ToolContextBuilder=void 0;const s=r(27399);t.ToolContextBuilder=class{config;constructor(e){this.config={tokenResolver:e.tokenResolver,configService:e.configService,providerResolver:e.providerResolver,projectId:e.projectId,logger:e.logger||(()=>{})}}async buildContext(e,t,r,i,a){if(!a?.requiredScopes?.length||!t)return;let o;try{o=await this.resolveProvider(a)}catch(r){return void this.config.logger("[ToolContextBuilder] Provider not resolved",{toolName:e,userDid:t.substring(0,20)+"...",error:r instanceof Error?r.message:String(r)})}const n=await this.config.tokenResolver.resolveTokenFromDid(t,o,a.requiredScopes);if(!n)throw this.config.logger("[ToolContextBuilder] Token not available, throwing OAuthRequiredError",{toolName:e,userDid:t.substring(0,20)+"...",provider:o,scopes:a.requiredScopes}),new s.OAuthRequiredError({toolName:e,requiredScopes:a.requiredScopes,provider:o,oauthUrl:"",userDid:t,sessionId:r});const c={idpToken:n,provider:o,scopes:a.requiredScopes,userDid:t,sessionId:r,delegationToken:i};return this.config.logger("[ToolContextBuilder] Context built successfully",{toolName:e,userDid:t.substring(0,20)+"...",provider:o,hasToken:!!n}),c}async resolveProvider(e){try{const t=await this.config.providerResolver.resolveProvider(e,this.config.projectId);return this.config.logger("[ToolContextBuilder] Provider resolved",{provider:t}),t}catch(e){throw this.config.logger("[ToolContextBuilder] Provider resolution failed",{error:e instanceof Error?e.message:String(e),projectId:this.config.projectId}),e}}}},72916:(e,t,r)=>{"use strict";var s=r(40985);function i(e,t,r){this.message=r||i.message(e,t),this.missingRef=s.url(e,t),this.missingSchema=s.normalizeId(s.fullPath(this.missingRef))}function a(e){return e.prototype=Object.create(Error.prototype),e.prototype.constructor=e,e}e.exports={Validation:a(function(e){this.message="validation failed",this.errors=e,this.ajv=this.validation=!0}),MissingRef:a(i)},i.message=function(e,t){return"can't resolve reference "+t+" from id "+e}},75306:(e,t)=>{"use strict";function r(e){return"string"==typeof e&&e.startsWith("did:")}function s(e){return e.trim()}function i(e){const t=e.split(":");return t[t.length-1]}Object.defineProperty(t,"__esModule",{value:!0}),t.isValidDid=r,t.getDidMethod=function(e){if(!r(e))return null;const t=e.match(/^did:([^:]+):/);return t?t[1]:null},t.normalizeDid=s,t.compareDids=function(e,t){return s(e)===s(t)},t.getServerDid=function(e){const t=e.identity.serverDid||e.identity.agentDid;if(!t)throw new Error("Server DID not configured");return t},t.extractAgentId=i,t.extractAgentSlug=function(e){return i(e)}},77311:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fetchRemoteConfig=t.ProviderRuntimeConfigBuilder=void 0,t.createProviderRuntimeConfig=function(e,t){return(new s).withProviders(e).withEnvironment(t?.environment||"development").withSession(t?.session||{}).withIdentity(t?.identity||{enabled:!1,environment:"development"}).withProofing(t?.proofing||{enabled:!1}).withDelegation(t?.delegation||{enabled:!1,verifier:{type:"memory"}}).withAudit(t?.audit||{enabled:!1}).withWellKnown(t?.wellKnown||{enabled:!0}).build()};class s{config={environment:"development"};withProviders(e){return Object.assign(this.config,e),this}withEnvironment(e){return this.config.environment=e,this}withSession(e){return this.config.session=e,this}withIdentity(e){return this.config.identity=e,this}withProofing(e){return this.config.proofing=e,this}withDelegation(e){return this.config.delegation=e,this}withToolProtectionService(e){return this.config.toolProtectionService=e,this}withToolProtection(e){return this.config.toolProtection=e,this}withAudit(e){return this.config.audit=e,this}withWellKnown(e){return this.config.wellKnown=e,this}build(){const e=["cryptoProvider","clockProvider","fetchProvider","storageProvider","nonceCacheProvider","identityProvider"];for(const t of e)if(!(t in this.config))throw new Error(`Missing required provider: ${t}`);return{environment:"development",session:{timestampSkewSeconds:120,ttlMinutes:30},...this.config}}}t.ProviderRuntimeConfigBuilder=s;var i=r(82811);Object.defineProperty(t,"fetchRemoteConfig",{enumerable:!0,get:function(){return i.fetchRemoteConfig}})},77460:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DelegationCredentialVerifier=void 0,t.createDelegationVerifier=function(e){return new i(e)};const s=r(62408);class i{didResolver;statusListResolver;signatureVerifier;cache=new Map;cacheTtl;constructor(e){this.didResolver=e?.didResolver,this.statusListResolver=e?.statusListResolver,this.signatureVerifier=e?.signatureVerifier,this.cacheTtl=e?.cacheTtl||6e4}async verifyDelegationCredential(e,t={}){const r=Date.now();if(!t.skipCache){const t=this.getFromCache(e.id||"");if(t)return{...t,cached:!0}}const s=Date.now(),i=this.validateBasicProperties(e),a=Date.now()-s;if(!i.valid)return{valid:!1,reason:i.reason,stage:"basic",metrics:{basicCheckMs:a,totalMs:Date.now()-r},checks:{basicValid:!1}};const o=t.skipSignature?Promise.resolve({valid:!0,durationMs:0}):this.verifySignature(e,t.didResolver||this.didResolver),n=!t.skipStatus&&e.credentialStatus?this.checkCredentialStatus(e.credentialStatus,t.statusListResolver||this.statusListResolver):Promise.resolve({valid:!0,durationMs:0}),[c,d]=await Promise.all([o,n]),l=c.durationMs||0,u=d.durationMs||0,h=i.valid&&c.valid&&d.valid,p={valid:h,reason:h?void 0:c.reason||d.reason||"Unknown failure",stage:"complete",metrics:{basicCheckMs:a,signatureCheckMs:l,statusCheckMs:u,totalMs:Date.now()-r},checks:{basicValid:i.valid,signatureValid:c.valid,statusValid:d.valid}};return p.valid&&e.id&&this.setInCache(e.id,p),p}validateBasicProperties(e){const t=(0,s.validateDelegationCredential)(e);if(!t.success)return{valid:!1,reason:`Schema validation failed: ${t.error.message}`};if((0,s.isDelegationCredentialExpired)(e))return{valid:!1,reason:"Delegation credential expired"};if((0,s.isDelegationCredentialNotYetValid)(e))return{valid:!1,reason:"Delegation credential not yet valid"};const r=e.credentialSubject.delegation;return"revoked"===r.status?{valid:!1,reason:"Delegation status is revoked"}:"expired"===r.status?{valid:!1,reason:"Delegation status is expired"}:r.issuerDid&&r.subjectDid?e.proof?{valid:!0}:{valid:!1,reason:"Missing proof"}:{valid:!1,reason:"Missing issuer or subject DID"}}async verifySignature(e,t){const r=Date.now();try{const s="string"==typeof e.issuer?e.issuer:e.issuer.id;if(!t||!this.signatureVerifier)return{valid:!0,reason:"No DID resolver or signature verifier available, skipping signature verification",durationMs:Date.now()-r};const i=await t.resolve(s);if(!i)return{valid:!1,reason:`Could not resolve issuer DID: ${s}`,durationMs:Date.now()-r};if(!e.proof)return{valid:!1,reason:"Proof is missing",durationMs:Date.now()-r};const a=e.proof.verificationMethod;if(!a)return{valid:!1,reason:"Proof missing verificationMethod",durationMs:Date.now()-r};const o=this.findVerificationMethod(i,a);if(!o)return{valid:!1,reason:`Verification method ${a} not found`,durationMs:Date.now()-r};const n=o.publicKeyJwk;if(!n)return{valid:!1,reason:"Verification method missing publicKeyJwk",durationMs:Date.now()-r};const c=await this.signatureVerifier(e,n);return{valid:c.valid,reason:c.reason,durationMs:Date.now()-r}}catch(e){return{valid:!1,reason:`Signature verification error: ${e instanceof Error?e.message:"Unknown error"}`,durationMs:Date.now()-r}}}async checkCredentialStatus(e,t){const r=Date.now();try{return t?await t.checkStatus(e)?{valid:!1,reason:`Credential revoked via StatusList2021 (${e.statusPurpose})`,durationMs:Date.now()-r}:{valid:!0,durationMs:Date.now()-r}:{valid:!0,reason:"No status list resolver available, skipping status check",durationMs:Date.now()-r}}catch(e){return{valid:!1,reason:`Status check error: ${e instanceof Error?e.message:"Unknown error"}`,durationMs:Date.now()-r}}}findVerificationMethod(e,t){return e.verificationMethod?.find(e=>e.id===t)}getFromCache(e){const t=this.cache.get(e);return t?Date.now()>t.expiresAt?(this.cache.delete(e),null):t.result:null}setInCache(e,t){this.cache.set(e,{result:t,expiresAt:Date.now()+this.cacheTtl})}clearCache(){this.cache.clear()}clearCacheEntry(e){this.cache.delete(e)}}t.DelegationCredentialVerifier=i},77753:(e,t,r)=>{"use strict";r.d(t,{d:()=>i});var s=r(10985);function i(e,t){return(0,s.S)(e,{allowCircular:t,filterUndefined:!0,undefinedInArrayToNull:!0})}},80536:e=>{"use strict";e.exports=function(e,t,r){var s,i=" ",a=e.level,o=e.dataLevel,n=e.schema[t],c=e.schemaPath+e.util.getProperty(t),d=e.errSchemaPath+"/"+t,l=!e.opts.allErrors,u="data"+(o||""),h=e.opts.$data&&n&&n.$data;if(h?(i+=" var schema"+a+" = "+e.util.getData(n.$data,o,e.dataPathArr)+"; ",s="schema"+a):s=n,!h&&"number"!=typeof n)throw new Error(t+" must be number");i+="if ( ",h&&(i+=" ("+s+" !== undefined && typeof "+s+" != 'number') || "),i+=" "+u+".length "+("maxItems"==t?">":"<")+" "+s+") { ";var p=t,f=f||[];f.push(i),i="",!1!==e.createErrors?(i+=" { keyword: '"+(p||"_limitItems")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(d)+" , params: { limit: "+s+" } ",!1!==e.opts.messages&&(i+=" , message: 'should NOT have ",i+="maxItems"==t?"more":"fewer",i+=" than ",i+=h?"' + "+s+" + '":""+n,i+=" items' "),e.opts.verbose&&(i+=" , schema: ",i+=h?"validate.schema"+c:""+n,i+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),i+=" } "):i+=" {} ";var g=i;return i=f.pop(),!e.compositeRule&&l?e.async?i+=" throw new ValidationError(["+g+"]); ":i+=" validate.errors = ["+g+"]; return false; ":i+=" var err = "+g+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",i+="} ",l&&(i+=" else { "),i}},81296:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CryptoService=void 0;const s=r(98448);t.CryptoService=class{cryptoProvider;constructor(e){this.cryptoProvider=e}async verifyEd25519(e,t,r){try{return!0===await this.cryptoProvider.verify(e,t,r)}catch(e){return console.error("[CryptoService] Ed25519 verification error:",e),!1}}parseJWS(e){const t=e.split(".");if(3!==t.length)throw new Error("Invalid JWS format: expected header.payload.signature");const[r,i,a]=t;let o,n,c;try{o=JSON.parse((0,s.base64urlDecodeToString)(r))}catch(e){throw new Error(`Invalid header base64: ${e instanceof Error?e.message:String(e)}`)}if(i)try{n=JSON.parse((0,s.base64urlDecodeToString)(i))}catch(e){throw new Error(`Invalid payload base64: ${e instanceof Error?e.message:String(e)}`)}try{c=(0,s.base64urlDecodeToBytes)(a)}catch(e){throw new Error(`Invalid signature base64: ${e instanceof Error?e.message:String(e)}`)}return{header:o,payload:n,signatureBytes:c,signingInput:`${r}.${i}`}}async verifyJWS(e,t,r){try{if(!this.isValidEd25519JWK(t))return console.error("[CryptoService] Invalid Ed25519 JWK format"),!1;if(r?.expectedKid&&t.kid!==r.expectedKid)return console.error("[CryptoService] Key ID mismatch"),!1;let i;try{i=this.parseJWS(e)}catch(t){if(void 0===r?.detachedPayload)return console.error("[CryptoService] Invalid JWS format:",t),!1;{const r=e.split(".");if(3!==r.length||""!==r[1])return console.error("[CryptoService] Invalid JWS format:",t),!1;try{const e=r[0],t=r[2];i={header:JSON.parse((0,s.base64urlDecodeToString)(e)),payload:void 0,signatureBytes:(0,s.base64urlDecodeToBytes)(t),signingInput:""}}catch{return console.error("[CryptoService] Invalid detached JWS format"),!1}}}const a=r?.alg||"EdDSA";if(i.header.alg!==a)return console.error(`[CryptoService] Unsupported algorithm: ${i.header.alg}, expected ${a}`),!1;let o,n,c;if(void 0!==r?.detachedPayload){const t=e.split(".")[0];let i;i=r.detachedPayload instanceof Uint8Array?(0,s.base64urlEncodeFromBytes)(r.detachedPayload):(0,s.base64urlEncodeFromBytes)((new TextEncoder).encode(r.detachedPayload)),o=`${t}.${i}`,n=(new TextEncoder).encode(o)}else{if(!i.signingInput)return console.error("[CryptoService] Missing signing input for compact JWS"),!1;o=i.signingInput,n=(new TextEncoder).encode(o)}try{c=this.jwkToBase64PublicKey(t)}catch(e){return console.error("[CryptoService] Failed to extract public key:",e),!1}return await this.verifyEd25519(n,i.signatureBytes,c)}catch(e){return console.error("[CryptoService] JWS verification error:",e),!1}}isValidEd25519JWK(e){return"object"==typeof e&&null!==e&&"kty"in e&&"OKP"===e.kty&&"crv"in e&&"Ed25519"===e.crv&&"x"in e&&"string"==typeof e.x&&e.x.length>0}jwkToBase64PublicKey(e){const t=(0,s.base64urlDecodeToBytes)(e.x);if(32!==t.length)throw new Error(`Invalid Ed25519 public key length: ${t.length}`);return(0,s.bytesToBase64)(t)}}},82811:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fetchRemoteConfig=async function(e,t){const{apiUrl:r,apiKey:i,projectId:a,agentDid:o,cacheTtl:n=3e5,fetchProvider:c}=e,d=a?`config:project:${a}`:o?`config:agent:${o}`:null;if(t&&d)try{const e=await t.get(d);if(e)try{const t=JSON.parse(e);if(t.expiresAt>Date.now())return t.config}catch{}}catch(e){console.warn("[RemoteConfig] Cache read failed:",e)}try{let e;if(a)e=`${r}${s.AGENTSHIELD_ENDPOINTS.CONFIG(a)}`;else{if(!o)return console.warn("[RemoteConfig] Neither projectId nor agentDid provided"),null;e=`${r}/api/v1/bouncer/config?agent_did=${encodeURIComponent(o)}`}const l=await c(e,{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"}});if(!l.ok)return console.warn(`[RemoteConfig] API returned ${l.status}: ${l.statusText}`),null;const u=await l.json(),h=u.config||u.data?.config||(u.success?u.data:null);if(!h)return console.warn("[RemoteConfig] No config found in API response"),null;if(t&&d)try{await t.set(d,JSON.stringify({config:h,expiresAt:Date.now()+n}),n)}catch(e){console.warn("[RemoteConfig] Cache write failed:",e)}return h}catch(e){return console.warn("[RemoteConfig] Failed to fetch config:",e),null}};const s=r(82906)},82906:e=>{"use strict";e.exports=require("@kya-os/contracts/agentshield-api")},82917:e=>{"use strict";e.exports=function(e,t,r){var s=" ",i=e.level,a=e.dataLevel,o=e.schema[t],n=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,d=!e.opts.allErrors,l="data"+(a||""),u="valid"+i,h="errs__"+i,p=e.util.copy(e);p.level++;var f="valid"+p.level,g=e.schema.then,m=e.schema.else,v=void 0!==g&&(e.opts.strictKeywords?"object"==typeof g&&Object.keys(g).length>0||!1===g:e.util.schemaHasRules(g,e.RULES.all)),y=void 0!==m&&(e.opts.strictKeywords?"object"==typeof m&&Object.keys(m).length>0||!1===m:e.util.schemaHasRules(m,e.RULES.all)),_=p.baseId;if(v||y){var w;p.createErrors=!1,p.schema=o,p.schemaPath=n,p.errSchemaPath=c,s+=" var "+h+" = errors; var "+u+" = true; ";var b=e.compositeRule;e.compositeRule=p.compositeRule=!0,s+=" "+e.validate(p)+" ",p.baseId=_,p.createErrors=!0,s+=" errors = "+h+"; if (vErrors !== null) { if ("+h+") vErrors.length = "+h+"; else vErrors = null; } ",e.compositeRule=p.compositeRule=b,v?(s+=" if ("+f+") { ",p.schema=e.schema.then,p.schemaPath=e.schemaPath+".then",p.errSchemaPath=e.errSchemaPath+"/then",s+=" "+e.validate(p)+" ",p.baseId=_,s+=" "+u+" = "+f+"; ",v&&y?s+=" var "+(w="ifClause"+i)+" = 'then'; ":w="'then'",s+=" } ",y&&(s+=" else { ")):s+=" if (!"+f+") { ",y&&(p.schema=e.schema.else,p.schemaPath=e.schemaPath+".else",p.errSchemaPath=e.errSchemaPath+"/else",s+=" "+e.validate(p)+" ",p.baseId=_,s+=" "+u+" = "+f+"; ",v&&y?s+=" var "+(w="ifClause"+i)+" = 'else'; ":w="'else'",s+=" } "),s+=" if (!"+u+") { var err = ",!1!==e.createErrors?(s+=" { keyword: 'if' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { failingKeyword: "+w+" } ",!1!==e.opts.messages&&(s+=" , message: 'should match \"' + "+w+" + '\" schema' "),e.opts.verbose&&(s+=" , schema: validate.schema"+n+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),s+=" } "):s+=" {} ",s+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&d&&(e.async?s+=" throw new ValidationError(vErrors); ":s+=" validate.errors = vErrors; return false; "),s+=" } ",d&&(s+=" else { ")}else d&&(s+=" if (true) { ");return s}},83010:e=>{"use strict";e.exports=function(e,t,r){var s,i=" ",a=e.level,o=e.dataLevel,n=e.schema[t],c=e.schemaPath+e.util.getProperty(t),d=e.errSchemaPath+"/"+t,l=!e.opts.allErrors,u="data"+(o||""),h=e.opts.$data&&n&&n.$data;if(h?(i+=" var schema"+a+" = "+e.util.getData(n.$data,o,e.dataPathArr)+"; ",s="schema"+a):s=n,!h&&"number"!=typeof n)throw new Error(t+" must be number");var p="maxLength"==t?">":"<";i+="if ( ",h&&(i+=" ("+s+" !== undefined && typeof "+s+" != 'number') || "),!1===e.opts.unicode?i+=" "+u+".length ":i+=" ucs2length("+u+") ",i+=" "+p+" "+s+") { ";var f=t,g=g||[];g.push(i),i="",!1!==e.createErrors?(i+=" { keyword: '"+(f||"_limitLength")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(d)+" , params: { limit: "+s+" } ",!1!==e.opts.messages&&(i+=" , message: 'should NOT be ",i+="maxLength"==t?"longer":"shorter",i+=" than ",i+=h?"' + "+s+" + '":""+n,i+=" characters' "),e.opts.verbose&&(i+=" , schema: ",i+=h?"validate.schema"+c:""+n,i+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),i+=" } "):i+=" {} ";var m=i;return i=g.pop(),!e.compositeRule&&l?e.async?i+=" throw new ValidationError(["+m+"]); ":i+=" validate.errors = ["+m+"]; return false; ":i+=" var err = "+m+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",i+="} ",l&&(i+=" else { "),i}},85601:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NoOpToolProtectionCache=t.InMemoryToolProtectionCache=void 0,t.InMemoryToolProtectionCache=class{cache=new Map;async get(e){const t=this.cache.get(e);return t?Date.now()>t.expiresAt?(this.cache.delete(e),null):t.value:null}async set(e,t,r){if(r<=0)return;const s=Date.now()+r;this.cache.set(e,{value:t,expiresAt:s})}async clear(){this.cache.clear()}async delete(e){this.cache.delete(e)}cleanup(){const e=Date.now();for(const[t,r]of this.cache.entries())e>r.expiresAt&&this.cache.delete(t)}getStale(e){const t=this.cache.get(e);return t?t.value:null}getExpiresAt(e){const t=this.cache.get(e);return t?t.expiresAt:null}},t.NoOpToolProtectionCache=class{async get(e){return null}async set(e,t,r){}async clear(){}async delete(e){}}},86343:e=>{"use strict";e.exports=function(e,t,r){var s=" ",i=e.level,a=e.dataLevel,o=e.schema[t],n=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,d=!e.opts.allErrors,l="data"+(a||""),u="errs__"+i,h=e.util.copy(e),p="";h.level++;var f="valid"+h.level,g="key"+i,m="idx"+i,v=h.dataLevel=e.dataLevel+1,y="data"+v,_="dataProperties"+i,w=Object.keys(o||{}).filter(R),b=e.schema.patternProperties||{},S=Object.keys(b).filter(R),P=e.schema.additionalProperties,E=w.length||S.length,I=!1===P,k="object"==typeof P&&Object.keys(P).length,C=e.opts.removeAdditional,D=I||k||C,O=e.opts.ownProperties,A=e.baseId,x=e.schema.required;if(x&&(!e.opts.$data||!x.$data)&&x.length<e.opts.loopRequired)var T=e.util.toHash(x);function R(e){return"__proto__"!==e}if(s+="var "+u+" = errors;var "+f+" = true;",O&&(s+=" var "+_+" = undefined;"),D){if(s+=O?" "+_+" = "+_+" || Object.keys("+l+"); for (var "+m+"=0; "+m+"<"+_+".length; "+m+"++) { var "+g+" = "+_+"["+m+"]; ":" for (var "+g+" in "+l+") { ",E){if(s+=" var isAdditional"+i+" = !(false ",w.length)if(w.length>8)s+=" || validate.schema"+n+".hasOwnProperty("+g+") ";else{var $=w;if($)for(var j=-1,N=$.length-1;j<N;)Z=$[j+=1],s+=" || "+g+" == "+e.util.toQuotedString(Z)+" "}if(S.length){var M=S;if(M)for(var F=-1,K=M.length-1;F<K;)ae=M[F+=1],s+=" || "+e.usePattern(ae)+".test("+g+") "}s+=" ); if (isAdditional"+i+") { "}if("all"==C)s+=" delete "+l+"["+g+"]; ";else{var q=e.errorPath,L="' + "+g+" + '";if(e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPathExpr(e.errorPath,g,e.opts.jsonPointers)),I)if(C)s+=" delete "+l+"["+g+"]; ";else{s+=" "+f+" = false; ";var U=c;c=e.errSchemaPath+"/additionalProperties",(re=re||[]).push(s),s="",!1!==e.createErrors?(s+=" { keyword: 'additionalProperties' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { additionalProperty: '"+L+"' } ",!1!==e.opts.messages&&(s+=" , message: '",e.opts._errorDataPathProperty?s+="is an invalid additional property":s+="should NOT have additional properties",s+="' "),e.opts.verbose&&(s+=" , schema: false , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),s+=" } "):s+=" {} ";var V=s;s=re.pop(),!e.compositeRule&&d?e.async?s+=" throw new ValidationError(["+V+"]); ":s+=" validate.errors = ["+V+"]; return false; ":s+=" var err = "+V+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",c=U,d&&(s+=" break; ")}else if(k)if("failing"==C){s+=" var "+u+" = errors; ";var H=e.compositeRule;e.compositeRule=h.compositeRule=!0,h.schema=P,h.schemaPath=e.schemaPath+".additionalProperties",h.errSchemaPath=e.errSchemaPath+"/additionalProperties",h.errorPath=e.opts._errorDataPathProperty?e.errorPath:e.util.getPathExpr(e.errorPath,g,e.opts.jsonPointers);var B=l+"["+g+"]";h.dataPathArr[v]=g;var z=e.validate(h);h.baseId=A,e.util.varOccurences(z,y)<2?s+=" "+e.util.varReplace(z,y,B)+" ":s+=" var "+y+" = "+B+"; "+z+" ",s+=" if (!"+f+") { errors = "+u+"; if (validate.errors !== null) { if (errors) validate.errors.length = errors; else validate.errors = null; } delete "+l+"["+g+"]; } ",e.compositeRule=h.compositeRule=H}else h.schema=P,h.schemaPath=e.schemaPath+".additionalProperties",h.errSchemaPath=e.errSchemaPath+"/additionalProperties",h.errorPath=e.opts._errorDataPathProperty?e.errorPath:e.util.getPathExpr(e.errorPath,g,e.opts.jsonPointers),B=l+"["+g+"]",h.dataPathArr[v]=g,z=e.validate(h),h.baseId=A,e.util.varOccurences(z,y)<2?s+=" "+e.util.varReplace(z,y,B)+" ":s+=" var "+y+" = "+B+"; "+z+" ",d&&(s+=" if (!"+f+") break; ");e.errorPath=q}E&&(s+=" } "),s+=" } ",d&&(s+=" if ("+f+") { ",p+="}")}var J=e.opts.useDefaults&&!e.compositeRule;if(w.length){var W=w;if(W)for(var Z,Q=-1,G=W.length-1;Q<G;){var Y=o[Z=W[Q+=1]];if(e.opts.strictKeywords?"object"==typeof Y&&Object.keys(Y).length>0||!1===Y:e.util.schemaHasRules(Y,e.RULES.all)){var X=e.util.getProperty(Z),ee=(B=l+X,J&&void 0!==Y.default);if(h.schema=Y,h.schemaPath=n+X,h.errSchemaPath=c+"/"+e.util.escapeFragment(Z),h.errorPath=e.util.getPath(e.errorPath,Z,e.opts.jsonPointers),h.dataPathArr[v]=e.util.toQuotedString(Z),z=e.validate(h),h.baseId=A,e.util.varOccurences(z,y)<2){z=e.util.varReplace(z,y,B);var te=B}else te=y,s+=" var "+y+" = "+B+"; ";if(ee)s+=" "+z+" ";else{if(T&&T[Z]){s+=" if ( "+te+" === undefined ",O&&(s+=" || ! Object.prototype.hasOwnProperty.call("+l+", '"+e.util.escapeQuotes(Z)+"') "),s+=") { "+f+" = false; ",q=e.errorPath,U=c;var re,se=e.util.escapeQuotes(Z);e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPath(q,Z,e.opts.jsonPointers)),c=e.errSchemaPath+"/required",(re=re||[]).push(s),s="",!1!==e.createErrors?(s+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { missingProperty: '"+se+"' } ",!1!==e.opts.messages&&(s+=" , message: '",e.opts._errorDataPathProperty?s+="is a required property":s+="should have required property \\'"+se+"\\'",s+="' "),e.opts.verbose&&(s+=" , schema: validate.schema"+n+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),s+=" } "):s+=" {} ",V=s,s=re.pop(),!e.compositeRule&&d?e.async?s+=" throw new ValidationError(["+V+"]); ":s+=" validate.errors = ["+V+"]; return false; ":s+=" var err = "+V+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",c=U,e.errorPath=q,s+=" } else { "}else d?(s+=" if ( "+te+" === undefined ",O&&(s+=" || ! Object.prototype.hasOwnProperty.call("+l+", '"+e.util.escapeQuotes(Z)+"') "),s+=") { "+f+" = true; } else { "):(s+=" if ("+te+" !== undefined ",O&&(s+=" && Object.prototype.hasOwnProperty.call("+l+", '"+e.util.escapeQuotes(Z)+"') "),s+=" ) { ");s+=" "+z+" } "}}d&&(s+=" if ("+f+") { ",p+="}")}}if(S.length){var ie=S;if(ie)for(var ae,oe=-1,ne=ie.length-1;oe<ne;)Y=b[ae=ie[oe+=1]],(e.opts.strictKeywords?"object"==typeof Y&&Object.keys(Y).length>0||!1===Y:e.util.schemaHasRules(Y,e.RULES.all))&&(h.schema=Y,h.schemaPath=e.schemaPath+".patternProperties"+e.util.getProperty(ae),h.errSchemaPath=e.errSchemaPath+"/patternProperties/"+e.util.escapeFragment(ae),s+=O?" "+_+" = "+_+" || Object.keys("+l+"); for (var "+m+"=0; "+m+"<"+_+".length; "+m+"++) { var "+g+" = "+_+"["+m+"]; ":" for (var "+g+" in "+l+") { ",s+=" if ("+e.usePattern(ae)+".test("+g+")) { ",h.errorPath=e.util.getPathExpr(e.errorPath,g,e.opts.jsonPointers),B=l+"["+g+"]",h.dataPathArr[v]=g,z=e.validate(h),h.baseId=A,e.util.varOccurences(z,y)<2?s+=" "+e.util.varReplace(z,y,B)+" ":s+=" var "+y+" = "+B+"; "+z+" ",d&&(s+=" if (!"+f+") break; "),s+=" } ",d&&(s+=" else "+f+" = true; "),s+=" } ",d&&(s+=" if ("+f+") { ",p+="}"))}return d&&(s+=" "+p+" if ("+u+" == errors) {"),s}},90083:e=>{"use strict";e.exports=function(e,t,r){var s=" ",i=e.level,a=e.dataLevel,o=e.schema[t],n=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,d=!e.opts.allErrors,l="data"+(a||""),u="errs__"+i,h=e.util.copy(e),p="";h.level++;var f="valid"+h.level,g={},m={},v=e.opts.ownProperties;for(b in o)if("__proto__"!=b){var y=o[b],_=Array.isArray(y)?m:g;_[b]=y}s+="var "+u+" = errors;";var w=e.errorPath;for(var b in s+="var missing"+i+";",m)if((_=m[b]).length){if(s+=" if ( "+l+e.util.getProperty(b)+" !== undefined ",v&&(s+=" && Object.prototype.hasOwnProperty.call("+l+", '"+e.util.escapeQuotes(b)+"') "),d){s+=" && ( ";var S=_;if(S)for(var P=-1,E=S.length-1;P<E;)A=S[P+=1],P&&(s+=" || "),s+=" ( ( "+($=l+(R=e.util.getProperty(A)))+" === undefined ",v&&(s+=" || ! Object.prototype.hasOwnProperty.call("+l+", '"+e.util.escapeQuotes(A)+"') "),s+=") && (missing"+i+" = "+e.util.toQuotedString(e.opts.jsonPointers?A:R)+") ) ";s+=")) { ";var I="missing"+i,k="' + "+I+" + '";e.opts._errorDataPathProperty&&(e.errorPath=e.opts.jsonPointers?e.util.getPathExpr(w,I,!0):w+" + "+I);var C=C||[];C.push(s),s="",!1!==e.createErrors?(s+=" { keyword: 'dependencies' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { property: '"+e.util.escapeQuotes(b)+"', missingProperty: '"+k+"', depsCount: "+_.length+", deps: '"+e.util.escapeQuotes(1==_.length?_[0]:_.join(", "))+"' } ",!1!==e.opts.messages&&(s+=" , message: 'should have ",1==_.length?s+="property "+e.util.escapeQuotes(_[0]):s+="properties "+e.util.escapeQuotes(_.join(", ")),s+=" when property "+e.util.escapeQuotes(b)+" is present' "),e.opts.verbose&&(s+=" , schema: validate.schema"+n+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),s+=" } "):s+=" {} ";var D=s;s=C.pop(),!e.compositeRule&&d?e.async?s+=" throw new ValidationError(["+D+"]); ":s+=" validate.errors = ["+D+"]; return false; ":s+=" var err = "+D+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}else{s+=" ) { ";var O=_;if(O)for(var A,x=-1,T=O.length-1;x<T;){A=O[x+=1];var R=e.util.getProperty(A),$=(k=e.util.escapeQuotes(A),l+R);e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPath(w,A,e.opts.jsonPointers)),s+=" if ( "+$+" === undefined ",v&&(s+=" || ! Object.prototype.hasOwnProperty.call("+l+", '"+e.util.escapeQuotes(A)+"') "),s+=") { var err = ",!1!==e.createErrors?(s+=" { keyword: 'dependencies' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { property: '"+e.util.escapeQuotes(b)+"', missingProperty: '"+k+"', depsCount: "+_.length+", deps: '"+e.util.escapeQuotes(1==_.length?_[0]:_.join(", "))+"' } ",!1!==e.opts.messages&&(s+=" , message: 'should have ",1==_.length?s+="property "+e.util.escapeQuotes(_[0]):s+="properties "+e.util.escapeQuotes(_.join(", ")),s+=" when property "+e.util.escapeQuotes(b)+" is present' "),e.opts.verbose&&(s+=" , schema: validate.schema"+n+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),s+=" } "):s+=" {} ",s+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } "}}s+=" } ",d&&(p+="}",s+=" else { ")}e.errorPath=w;var j=h.baseId;for(var b in g)y=g[b],(e.opts.strictKeywords?"object"==typeof y&&Object.keys(y).length>0||!1===y:e.util.schemaHasRules(y,e.RULES.all))&&(s+=" "+f+" = true; if ( "+l+e.util.getProperty(b)+" !== undefined ",v&&(s+=" && Object.prototype.hasOwnProperty.call("+l+", '"+e.util.escapeQuotes(b)+"') "),s+=") { ",h.schema=y,h.schemaPath=n+e.util.getProperty(b),h.errSchemaPath=c+"/"+e.util.escapeFragment(b),s+=" "+e.validate(h)+" ",h.baseId=j,s+=" } ",d&&(s+=" if ("+f+") { ",p+="}"));return d&&(s+=" "+p+" if ("+u+" == errors) {"),s}},91939:e=>{"use strict";e.exports=function(e,t,r){var s=" ",i=e.level,a=e.dataLevel,o=e.schema[t],n=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,d=!e.opts.allErrors,l="data"+(a||""),u="valid"+i,h=e.opts.$data&&o&&o.$data;h&&(s+=" var schema"+i+" = "+e.util.getData(o.$data,a,e.dataPathArr)+"; ");var p="schema"+i;if(!h)if(o.length<e.opts.loopRequired&&e.schema.properties&&Object.keys(e.schema.properties).length){var f=[],g=o;if(g)for(var m,v=-1,y=g.length-1;v<y;){m=g[v+=1];var _=e.schema.properties[m];_&&(e.opts.strictKeywords?"object"==typeof _&&Object.keys(_).length>0||!1===_:e.util.schemaHasRules(_,e.RULES.all))||(f[f.length]=m)}}else f=o;if(h||f.length){var w=e.errorPath,b=h||f.length>=e.opts.loopRequired,S=e.opts.ownProperties;if(d)if(s+=" var missing"+i+"; ",b){h||(s+=" var "+p+" = validate.schema"+n+"; ");var P="' + "+(O="schema"+i+"["+(C="i"+i)+"]")+" + '";e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPathExpr(w,O,e.opts.jsonPointers)),s+=" var "+u+" = true; ",h&&(s+=" if (schema"+i+" === undefined) "+u+" = true; else if (!Array.isArray(schema"+i+")) "+u+" = false; else {"),s+=" for (var "+C+" = 0; "+C+" < "+p+".length; "+C+"++) { "+u+" = "+l+"["+p+"["+C+"]] !== undefined ",S&&(s+=" && Object.prototype.hasOwnProperty.call("+l+", "+p+"["+C+"]) "),s+="; if (!"+u+") break; } ",h&&(s+=" } "),s+=" if (!"+u+") { ",(I=I||[]).push(s),s="",!1!==e.createErrors?(s+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { missingProperty: '"+P+"' } ",!1!==e.opts.messages&&(s+=" , message: '",e.opts._errorDataPathProperty?s+="is a required property":s+="should have required property \\'"+P+"\\'",s+="' "),e.opts.verbose&&(s+=" , schema: validate.schema"+n+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),s+=" } "):s+=" {} ";var E=s;s=I.pop(),!e.compositeRule&&d?e.async?s+=" throw new ValidationError(["+E+"]); ":s+=" validate.errors = ["+E+"]; return false; ":s+=" var err = "+E+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+=" } else { "}else{s+=" if ( ";var I,k=f;if(k)for(var C=-1,D=k.length-1;C<D;)x=k[C+=1],C&&(s+=" || "),s+=" ( ( "+(j=l+($=e.util.getProperty(x)))+" === undefined ",S&&(s+=" || ! Object.prototype.hasOwnProperty.call("+l+", '"+e.util.escapeQuotes(x)+"') "),s+=") && (missing"+i+" = "+e.util.toQuotedString(e.opts.jsonPointers?x:$)+") ) ";s+=") { ",P="' + "+(O="missing"+i)+" + '",e.opts._errorDataPathProperty&&(e.errorPath=e.opts.jsonPointers?e.util.getPathExpr(w,O,!0):w+" + "+O),(I=I||[]).push(s),s="",!1!==e.createErrors?(s+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { missingProperty: '"+P+"' } ",!1!==e.opts.messages&&(s+=" , message: '",e.opts._errorDataPathProperty?s+="is a required property":s+="should have required property \\'"+P+"\\'",s+="' "),e.opts.verbose&&(s+=" , schema: validate.schema"+n+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),s+=" } "):s+=" {} ",E=s,s=I.pop(),!e.compositeRule&&d?e.async?s+=" throw new ValidationError(["+E+"]); ":s+=" validate.errors = ["+E+"]; return false; ":s+=" var err = "+E+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+=" } else { "}else if(b){var O;h||(s+=" var "+p+" = validate.schema"+n+"; "),P="' + "+(O="schema"+i+"["+(C="i"+i)+"]")+" + '",e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPathExpr(w,O,e.opts.jsonPointers)),h&&(s+=" if ("+p+" && !Array.isArray("+p+")) { var err = ",!1!==e.createErrors?(s+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { missingProperty: '"+P+"' } ",!1!==e.opts.messages&&(s+=" , message: '",e.opts._errorDataPathProperty?s+="is a required property":s+="should have required property \\'"+P+"\\'",s+="' "),e.opts.verbose&&(s+=" , schema: validate.schema"+n+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),s+=" } "):s+=" {} ",s+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } else if ("+p+" !== undefined) { "),s+=" for (var "+C+" = 0; "+C+" < "+p+".length; "+C+"++) { if ("+l+"["+p+"["+C+"]] === undefined ",S&&(s+=" || ! Object.prototype.hasOwnProperty.call("+l+", "+p+"["+C+"]) "),s+=") { var err = ",!1!==e.createErrors?(s+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { missingProperty: '"+P+"' } ",!1!==e.opts.messages&&(s+=" , message: '",e.opts._errorDataPathProperty?s+="is a required property":s+="should have required property \\'"+P+"\\'",s+="' "),e.opts.verbose&&(s+=" , schema: validate.schema"+n+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),s+=" } "):s+=" {} ",s+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } } ",h&&(s+=" } ")}else{var A=f;if(A)for(var x,T=-1,R=A.length-1;T<R;){x=A[T+=1];var $=e.util.getProperty(x),j=(P=e.util.escapeQuotes(x),l+$);e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPath(w,x,e.opts.jsonPointers)),s+=" if ( "+j+" === undefined ",S&&(s+=" || ! Object.prototype.hasOwnProperty.call("+l+", '"+e.util.escapeQuotes(x)+"') "),s+=") { var err = ",!1!==e.createErrors?(s+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { missingProperty: '"+P+"' } ",!1!==e.opts.messages&&(s+=" , message: '",e.opts._errorDataPathProperty?s+="is a required property":s+="should have required property \\'"+P+"\\'",s+="' "),e.opts.verbose&&(s+=" , schema: validate.schema"+n+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),s+=" } "):s+=" {} ",s+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } "}}e.errorPath=w}else d&&(s+=" if (true) {");return s}},92182:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StorageKeyHelpers=void 0,t.createStorageProviders=async function(e){const t=!1!==e.fallbackToMemory;if(e.redisUrl)try{const t="redis",s=await r(52643)(t).catch(()=>null);if(!s)throw new Error("Redis package not available");const{createClient:i}=s,a=i({url:e.redisUrl,socket:{connectTimeout:5e3}});await a.connect(),await a.ping();return{storageProvider:new c(a),nonceCacheProvider:new d(a)}}catch(e){if(!t)throw e;console.warn("[StorageService] Failed to connect to Redis, falling back to memory:",e instanceof Error?e.message:String(e))}if(e.kvNamespace)try{const t=await async function(e){try{const t="@kya-os/mcp-i-cloudflare/providers/storage",{KVStorageProvider:s,KVNonceCacheProvider:i}=await r(42399)(t);return{storage:new s(e),nonceCache:new i(e)}}catch(e){throw new Error(`Failed to import Cloudflare storage providers: ${e instanceof Error?e.message:String(e)}`)}}(e.kvNamespace);return{storageProvider:t.storage,nonceCacheProvider:t.nonceCache}}catch(e){if(!t)throw e;console.warn("[StorageService] Failed to initialize KV, falling back to memory:",e instanceof Error?e.message:String(e))}if(e.durableObjectState)try{return{storageProvider:new o(e.durableObjectState),nonceCacheProvider:new n(e.durableObjectState)}}catch(e){if(!t)throw e;console.warn("[StorageService] Failed to initialize Durable Objects, falling back to memory:",e instanceof Error?e.message:String(e))}if(t)return{storageProvider:new i.MemoryStorageProvider,nonceCacheProvider:new i.MemoryNonceCacheProvider};throw new Error("No storage provider configured and fallbackToMemory is false")},t.migrateLegacyKeys=async function(e,t,r,s=100){let i=0;try{const a=await r.list(e);for(const e of a){const a=t(e);if(!a)continue;if(await r.exists(a))continue;const o=await r.get(e);o&&(await r.set(a,o),i++,i%s===0&&await new Promise(e=>setTimeout(e,0)))}}catch(e){throw console.error("[StorageService] Migration error:",e),e}return i};const s=r(27087),i=r(48505);class a{static buildDelegationKey(e,t,r){return`delegation:${e}:${t}:${r}`}static buildSessionKey(e){return`session:${e}`}static buildNonceKey(e,t){return`nonce:${e}:${t}`}static parseDelegationKey(e){if(!e.startsWith("delegation:"))return null;const t=e.slice(11),r=t.lastIndexOf(":");if(-1===r)return null;const s=t.slice(r+1);if(!s)return null;const i=t.slice(0,r),a=i.indexOf("did:");if(0!==a)return null;const o=i.indexOf(":",a+4);if(-1===o)return null;const n=i.indexOf("did:",o+1);if(-1===n)return null;const c=i.slice(0,n),d=i.slice(n),l=c.endsWith(":")?c.slice(0,-1):c;return l&&d?{userDid:l,agentDid:d,projectId:s}:null}}t.StorageKeyHelpers=a;class o extends s.StorageProvider{state;constructor(e){super(),this.state=e}async get(e){return await this.state.storage.get(e)??null}async set(e,t){await this.state.storage.put(e,t)}async delete(e){await this.state.storage.delete(e)}async exists(e){return void 0!==await this.state.storage.get(e)}async list(e){const t=await this.state.storage.list(e?{prefix:e}:void 0);return Array.from(t.keys())}}class n extends s.NonceCacheProvider{state;constructor(e){super(),this.state=e}async has(e,t){const r=t?a.buildNonceKey(t,e):`nonce:${e}`,s=await this.state.storage.get(r);if(!s)return!1;const i=parseInt(s,10);return Date.now()<i}async add(e,t,r){const s=r?a.buildNonceKey(r,e):`nonce:${e}`,i=Date.now()+1e3*t;await this.state.storage.put(s,i.toString())}async cleanup(){}async destroy(){}}class c extends s.StorageProvider{redis;constructor(e){super(),this.redis=e}async get(e){return await this.redis.get(e)}async set(e,t){await this.redis.set(e,t)}async delete(e){await this.redis.del(e)}async exists(e){return 1===await this.redis.exists(e)}async list(e){const t=e?`${e}*`:"*";return await this.redis.keys(t)}}class d extends s.NonceCacheProvider{redis;keyPrefix;constructor(e,t="nonce:"){super(),this.redis=e,this.keyPrefix=t}async has(e,t){const r=t?a.buildNonceKey(t,e):`${this.keyPrefix}${e}`;return 1===await this.redis.exists(r)}async add(e,t,r){const s=r?a.buildNonceKey(r,e):`${this.keyPrefix}${e}`;await this.redis.setEx(s,t,"1")}async cleanup(){}async destroy(){}}},94766:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProviderValidator=t.ProviderValidationError=void 0;const r=["response_type","client_id","redirect_uri","scope","state","code_challenge","code_challenge_method"];class s extends Error{field;constructor(e,t){super(e),this.field=t,this.name="ProviderValidationError"}}t.ProviderValidationError=s,t.ProviderValidator=class{validate(e,t){if(!e.clientId||0===e.clientId.trim().length)throw new s(`Provider "${t}" must have a clientId`,"clientId");if(!e.authorizationUrl||0===e.authorizationUrl.trim().length)throw new s(`Provider "${t}" must have an authorizationUrl`,"authorizationUrl");if(!e.tokenUrl||0===e.tokenUrl.trim().length)throw new s(`Provider "${t}" must have a tokenUrl`,"tokenUrl");if(this.validateUrl(e.authorizationUrl,t,"authorizationUrl"),this.validateUrl(e.tokenUrl,t,"tokenUrl"),e.userInfoUrl&&this.validateUrl(e.userInfoUrl,t,"userInfoUrl"),e.proxyMode&&!e.requiresClientSecret)throw new s(`Provider "${t}" with proxyMode=true must have requiresClientSecret=true`,"proxyMode");e.customParams&&this.validateCustomParams(e.customParams,t)}validateUrl(e,t,r){try{const i=new URL(e);if("http:"!==i.protocol&&"https:"!==i.protocol)throw new s(`Provider "${t}" ${r} must use HTTP or HTTPS protocol`,r)}catch(e){if(e instanceof s)throw e;throw new s(`Provider "${t}" ${r} is not a valid URL: ${e instanceof Error?e.message:String(e)}`,r)}}validateCustomParams(e,t){for(const[i,a]of Object.entries(e)){const e=i.toLowerCase();if(r.includes(e))throw new s(`Provider "${t}" custom parameter "${i}" conflicts with reserved OAuth parameter. Reserved parameters: ${r.join(", ")}`,`customParams.${i}`);if(!a||0===a.trim().length)throw new s(`Provider "${t}" custom parameter "${i}" has empty value`,`customParams.${i}`)}}async testProvider(e,t){try{const r=await t(e.authorizationUrl,{method:"HEAD",signal:AbortSignal.timeout(5e3)});return r.ok||405===r.status}catch(e){return!1}}}},95277:function(e,t,r){"use strict";var s=this&&this.__createBinding||(Object.create?function(e,t,r,s){void 0===s&&(s=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,s,i)}:function(e,t,r,s){void 0===s&&(s=r),e[s]=t[r]}),i=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||s(t,e,r)};Object.defineProperty(t,"__esModule",{value:!0}),t.SchemaVerifier=t.MemoryDelegationGraphStorage=t.MemoryStatusListStorage=t.createCascadingRevocationManager=t.CascadingRevocationManager=t.createDelegationGraph=t.DelegationGraphManager=t.isIndexSet=t.BitstringManager=t.createStatusListManager=t.StatusList2021Manager=t.createDelegationVerifier=t.DelegationCredentialVerifier=t.createDelegationIssuer=t.DelegationCredentialIssuer=t.OAuthRequiredError=t.DelegationRequiredError=t.NoOpToolProtectionCache=t.InMemoryToolProtectionCache=t.createProofVerificationError=t.PROOF_VERIFICATION_ERROR_CODES=t.ProofVerificationError=t.migrateLegacyKeys=t.StorageKeyHelpers=t.createStorageProviders=t.NoOpOAuthConfigCache=t.InMemoryOAuthConfigCache=t.BatchDelegationService=t.OAuthTokenRetrievalService=t.ProviderValidationError=t.ProviderValidator=t.ProviderResolver=t.OAuthProviderRegistry=t.ToolContextBuilder=t.OAuthService=t.OAuthConfigService=t.AccessControlApiService=t.ProofVerifier=t.CryptoService=t.ToolProtectionService=t.MCPIRuntimeBase=t.MemoryIdentityProvider=t.MemoryNonceCacheProvider=t.MemoryStorageProvider=t.IdentityProvider=t.NonceCacheProvider=t.StorageProvider=t.FetchProvider=t.ClockProvider=t.CryptoProvider=void 0,t.IdpTokenResolver=t.UserDidManager=t.fetchRemoteConfig=t.canonicalizeJSON=t.getSchemaStats=t.getCriticalSchemas=t.getSchemaById=t.getSchemasByCategory=t.getAllSchemas=t.SCHEMA_REGISTRY=t.createSchemaVerifier=void 0;var a=r(27087);Object.defineProperty(t,"CryptoProvider",{enumerable:!0,get:function(){return a.CryptoProvider}}),Object.defineProperty(t,"ClockProvider",{enumerable:!0,get:function(){return a.ClockProvider}}),Object.defineProperty(t,"FetchProvider",{enumerable:!0,get:function(){return a.FetchProvider}}),Object.defineProperty(t,"StorageProvider",{enumerable:!0,get:function(){return a.StorageProvider}}),Object.defineProperty(t,"NonceCacheProvider",{enumerable:!0,get:function(){return a.NonceCacheProvider}}),Object.defineProperty(t,"IdentityProvider",{enumerable:!0,get:function(){return a.IdentityProvider}});var o=r(48505);Object.defineProperty(t,"MemoryStorageProvider",{enumerable:!0,get:function(){return o.MemoryStorageProvider}}),Object.defineProperty(t,"MemoryNonceCacheProvider",{enumerable:!0,get:function(){return o.MemoryNonceCacheProvider}}),Object.defineProperty(t,"MemoryIdentityProvider",{enumerable:!0,get:function(){return o.MemoryIdentityProvider}});var n=r(23137);Object.defineProperty(t,"MCPIRuntimeBase",{enumerable:!0,get:function(){return n.MCPIRuntimeBase}}),i(r(53871),t);var c=r(9249);Object.defineProperty(t,"ToolProtectionService",{enumerable:!0,get:function(){return c.ToolProtectionService}});var d=r(81296);Object.defineProperty(t,"CryptoService",{enumerable:!0,get:function(){return d.CryptoService}});var l=r(45395);Object.defineProperty(t,"ProofVerifier",{enumerable:!0,get:function(){return l.ProofVerifier}});var u=r(36255);Object.defineProperty(t,"AccessControlApiService",{enumerable:!0,get:function(){return u.AccessControlApiService}});var h=r(97405);Object.defineProperty(t,"OAuthConfigService",{enumerable:!0,get:function(){return h.OAuthConfigService}});var p=r(62175);Object.defineProperty(t,"OAuthService",{enumerable:!0,get:function(){return p.OAuthService}});var f=r(72114);Object.defineProperty(t,"ToolContextBuilder",{enumerable:!0,get:function(){return f.ToolContextBuilder}});var g=r(50399);Object.defineProperty(t,"OAuthProviderRegistry",{enumerable:!0,get:function(){return g.OAuthProviderRegistry}});var m=r(68252);Object.defineProperty(t,"ProviderResolver",{enumerable:!0,get:function(){return m.ProviderResolver}});var v=r(94766);Object.defineProperty(t,"ProviderValidator",{enumerable:!0,get:function(){return v.ProviderValidator}}),Object.defineProperty(t,"ProviderValidationError",{enumerable:!0,get:function(){return v.ProviderValidationError}});var y=r(42769);Object.defineProperty(t,"OAuthTokenRetrievalService",{enumerable:!0,get:function(){return y.OAuthTokenRetrievalService}});var _=r(30124);Object.defineProperty(t,"BatchDelegationService",{enumerable:!0,get:function(){return _.BatchDelegationService}});var w=r(48021);Object.defineProperty(t,"InMemoryOAuthConfigCache",{enumerable:!0,get:function(){return w.InMemoryOAuthConfigCache}}),Object.defineProperty(t,"NoOpOAuthConfigCache",{enumerable:!0,get:function(){return w.NoOpOAuthConfigCache}});var b=r(92182);Object.defineProperty(t,"createStorageProviders",{enumerable:!0,get:function(){return b.createStorageProviders}}),Object.defineProperty(t,"StorageKeyHelpers",{enumerable:!0,get:function(){return b.StorageKeyHelpers}}),Object.defineProperty(t,"migrateLegacyKeys",{enumerable:!0,get:function(){return b.migrateLegacyKeys}});var S=r(53683);Object.defineProperty(t,"ProofVerificationError",{enumerable:!0,get:function(){return S.ProofVerificationError}}),Object.defineProperty(t,"PROOF_VERIFICATION_ERROR_CODES",{enumerable:!0,get:function(){return S.PROOF_VERIFICATION_ERROR_CODES}}),Object.defineProperty(t,"createProofVerificationError",{enumerable:!0,get:function(){return S.createProofVerificationError}});var P=r(85601);Object.defineProperty(t,"InMemoryToolProtectionCache",{enumerable:!0,get:function(){return P.InMemoryToolProtectionCache}}),Object.defineProperty(t,"NoOpToolProtectionCache",{enumerable:!0,get:function(){return P.NoOpToolProtectionCache}});var E=r(4901);Object.defineProperty(t,"DelegationRequiredError",{enumerable:!0,get:function(){return E.DelegationRequiredError}});var I=r(27399);Object.defineProperty(t,"OAuthRequiredError",{enumerable:!0,get:function(){return I.OAuthRequiredError}});var k=r(30845);Object.defineProperty(t,"DelegationCredentialIssuer",{enumerable:!0,get:function(){return k.DelegationCredentialIssuer}}),Object.defineProperty(t,"createDelegationIssuer",{enumerable:!0,get:function(){return k.createDelegationIssuer}});var C=r(77460);Object.defineProperty(t,"DelegationCredentialVerifier",{enumerable:!0,get:function(){return C.DelegationCredentialVerifier}}),Object.defineProperty(t,"createDelegationVerifier",{enumerable:!0,get:function(){return C.createDelegationVerifier}});var D=r(98358);Object.defineProperty(t,"StatusList2021Manager",{enumerable:!0,get:function(){return D.StatusList2021Manager}}),Object.defineProperty(t,"createStatusListManager",{enumerable:!0,get:function(){return D.createStatusListManager}});var O=r(46610);Object.defineProperty(t,"BitstringManager",{enumerable:!0,get:function(){return O.BitstringManager}}),Object.defineProperty(t,"isIndexSet",{enumerable:!0,get:function(){return O.isIndexSet}});var A=r(55921);Object.defineProperty(t,"DelegationGraphManager",{enumerable:!0,get:function(){return A.DelegationGraphManager}}),Object.defineProperty(t,"createDelegationGraph",{enumerable:!0,get:function(){return A.createDelegationGraph}});var x=r(24886);Object.defineProperty(t,"CascadingRevocationManager",{enumerable:!0,get:function(){return x.CascadingRevocationManager}}),Object.defineProperty(t,"createCascadingRevocationManager",{enumerable:!0,get:function(){return x.createCascadingRevocationManager}});var T=r(7318);Object.defineProperty(t,"MemoryStatusListStorage",{enumerable:!0,get:function(){return T.MemoryStatusListStorage}});var R=r(44558);Object.defineProperty(t,"MemoryDelegationGraphStorage",{enumerable:!0,get:function(){return R.MemoryDelegationGraphStorage}});var $=r(37121);Object.defineProperty(t,"SchemaVerifier",{enumerable:!0,get:function(){return $.SchemaVerifier}}),Object.defineProperty(t,"createSchemaVerifier",{enumerable:!0,get:function(){return $.createSchemaVerifier}});var j=r(11300);Object.defineProperty(t,"SCHEMA_REGISTRY",{enumerable:!0,get:function(){return j.SCHEMA_REGISTRY}}),Object.defineProperty(t,"getAllSchemas",{enumerable:!0,get:function(){return j.getAllSchemas}}),Object.defineProperty(t,"getSchemasByCategory",{enumerable:!0,get:function(){return j.getSchemasByCategory}}),Object.defineProperty(t,"getSchemaById",{enumerable:!0,get:function(){return j.getSchemaById}}),Object.defineProperty(t,"getCriticalSchemas",{enumerable:!0,get:function(){return j.getCriticalSchemas}}),Object.defineProperty(t,"getSchemaStats",{enumerable:!0,get:function(){return j.getSchemaStats}});var N=r(63969);Object.defineProperty(t,"canonicalizeJSON",{enumerable:!0,get:function(){return N.canonicalizeJSON}}),i(r(77311),t);var M=r(82811);Object.defineProperty(t,"fetchRemoteConfig",{enumerable:!0,get:function(){return M.fetchRemoteConfig}});var F=r(65067);Object.defineProperty(t,"UserDidManager",{enumerable:!0,get:function(){return F.UserDidManager}});var K=r(202);Object.defineProperty(t,"IdpTokenResolver",{enumerable:!0,get:function(){return K.IdpTokenResolver}})},95545:e=>{"use strict";e.exports=function(e,t,r){var s=" ",i=e.level,a=e.dataLevel,o=e.schema[t],n=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,d=!e.opts.allErrors,l="data"+(a||"");if(!1===e.opts.format)return d&&(s+=" if (true) { "),s;var u,h=e.opts.$data&&o&&o.$data;h?(s+=" var schema"+i+" = "+e.util.getData(o.$data,a,e.dataPathArr)+"; ",u="schema"+i):u=o;var p=e.opts.unknownFormats,f=Array.isArray(p);if(h)s+=" var "+(g="format"+i)+" = formats["+u+"]; var "+(m="isObject"+i)+" = typeof "+g+" == 'object' && !("+g+" instanceof RegExp) && "+g+".validate; var "+(v="formatType"+i)+" = "+m+" && "+g+".type || 'string'; if ("+m+") { ",e.async&&(s+=" var async"+i+" = "+g+".async; "),s+=" "+g+" = "+g+".validate; } if ( ",h&&(s+=" ("+u+" !== undefined && typeof "+u+" != 'string') || "),s+=" (","ignore"!=p&&(s+=" ("+u+" && !"+g+" ",f&&(s+=" && self._opts.unknownFormats.indexOf("+u+") == -1 "),s+=") || "),s+=" ("+g+" && "+v+" == '"+r+"' && !(typeof "+g+" == 'function' ? ",e.async?s+=" (async"+i+" ? await "+g+"("+l+") : "+g+"("+l+")) ":s+=" "+g+"("+l+") ",s+=" : "+g+".test("+l+"))))) {";else{var g;if(!(g=e.formats[o])){if("ignore"==p)return e.logger.warn('unknown format "'+o+'" ignored in schema at path "'+e.errSchemaPath+'"'),d&&(s+=" if (true) { "),s;if(f&&p.indexOf(o)>=0)return d&&(s+=" if (true) { "),s;throw new Error('unknown format "'+o+'" is used in schema at path "'+e.errSchemaPath+'"')}var m,v=(m="object"==typeof g&&!(g instanceof RegExp)&&g.validate)&&g.type||"string";if(m){var y=!0===g.async;g=g.validate}if(v!=r)return d&&(s+=" if (true) { "),s;if(y){if(!e.async)throw new Error("async format in sync schema");s+=" if (!(await "+(_="formats"+e.util.getProperty(o)+".validate")+"("+l+"))) { "}else{s+=" if (! ";var _="formats"+e.util.getProperty(o);m&&(_+=".validate"),s+="function"==typeof g?" "+_+"("+l+") ":" "+_+".test("+l+") ",s+=") { "}}var w=w||[];w.push(s),s="",!1!==e.createErrors?(s+=" { keyword: 'format' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { format: ",s+=h?""+u:""+e.util.toQuotedString(o),s+=" } ",!1!==e.opts.messages&&(s+=" , message: 'should match format \"",s+=h?"' + "+u+" + '":""+e.util.escapeQuotes(o),s+="\"' "),e.opts.verbose&&(s+=" , schema: ",s+=h?"validate.schema"+n:""+e.util.toQuotedString(o),s+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),s+=" } "):s+=" {} ";var b=s;return s=w.pop(),!e.compositeRule&&d?e.async?s+=" throw new ValidationError(["+b+"]); ":s+=" validate.errors = ["+b+"]; return false; ":s+=" var err = "+b+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+=" } ",d&&(s+=" else { "),s}},96111:e=>{"use strict";e.exports=function(e,t,r){var s,i=" ",a=e.level,o=e.dataLevel,n=e.schema[t],c=e.schemaPath+e.util.getProperty(t),d=e.errSchemaPath+"/"+t,l=!e.opts.allErrors,u="data"+(o||""),h=e.opts.$data&&n&&n.$data;if(h?(i+=" var schema"+a+" = "+e.util.getData(n.$data,o,e.dataPathArr)+"; ",s="schema"+a):s=n,!h&&"number"!=typeof n)throw new Error(t+" must be number");i+="if ( ",h&&(i+=" ("+s+" !== undefined && typeof "+s+" != 'number') || "),i+=" Object.keys("+u+").length "+("maxProperties"==t?">":"<")+" "+s+") { ";var p=t,f=f||[];f.push(i),i="",!1!==e.createErrors?(i+=" { keyword: '"+(p||"_limitProperties")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(d)+" , params: { limit: "+s+" } ",!1!==e.opts.messages&&(i+=" , message: 'should NOT have ",i+="maxProperties"==t?"more":"fewer",i+=" than ",i+=h?"' + "+s+" + '":""+n,i+=" properties' "),e.opts.verbose&&(i+=" , schema: ",i+=h?"validate.schema"+c:""+n,i+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),i+=" } "):i+=" {} ";var g=i;return i=f.pop(),!e.compositeRule&&l?e.async?i+=" throw new ValidationError(["+g+"]); ":i+=" validate.errors = ["+g+"]; return false; ":i+=" var err = "+g+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",i+="} ",l&&(i+=" else { "),i}},96150:(e,t,r)=>{"use strict";var s=r(12269);e.exports={$id:"https://github.com/ajv-validator/ajv/blob/master/lib/definition_schema.js",definitions:{simpleTypes:s.definitions.simpleTypes},type:"object",dependencies:{schema:["validate"],$data:["validate"],statements:["inline"],valid:{not:{required:["macro"]}}},properties:{type:s.properties.type,schema:{type:"boolean"},statements:{type:"boolean"},dependencies:{type:"array",items:{type:"string"}},metaSchema:{type:"object"},modifying:{type:"boolean"},valid:{type:"boolean"},$data:{type:"boolean"},async:{type:"boolean"},errors:{anyOf:[{type:"boolean"},{const:"full"}]}}}},96774:e=>{"use strict";e.exports=function(e,t,r){var s,i=" ",a=e.level,o=e.dataLevel,n=e.schema[t],c=e.schemaPath+e.util.getProperty(t),d=e.errSchemaPath+"/"+t,l=!e.opts.allErrors,u="data"+(o||""),h=e.opts.$data&&n&&n.$data;h?(i+=" var schema"+a+" = "+e.util.getData(n.$data,o,e.dataPathArr)+"; ",s="schema"+a):s=n,i+="if ( ",h&&(i+=" ("+s+" !== undefined && typeof "+s+" != 'string') || "),i+=" !"+(h?"(new RegExp("+s+"))":e.usePattern(n))+".test("+u+") ) { ";var p=p||[];p.push(i),i="",!1!==e.createErrors?(i+=" { keyword: 'pattern' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(d)+" , params: { pattern: ",i+=h?""+s:""+e.util.toQuotedString(n),i+=" } ",!1!==e.opts.messages&&(i+=" , message: 'should match pattern \"",i+=h?"' + "+s+" + '":""+e.util.escapeQuotes(n),i+="\"' "),e.opts.verbose&&(i+=" , schema: ",i+=h?"validate.schema"+c:""+e.util.toQuotedString(n),i+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),i+=" } "):i+=" {} ";var f=i;return i=p.pop(),!e.compositeRule&&l?e.async?i+=" throw new ValidationError(["+f+"]); ":i+=" validate.errors = ["+f+"]; return false; ":i+=" var err = "+f+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",i+="} ",l&&(i+=" else { "),i}},97405:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OAuthConfigService=void 0;const s=r(48021);t.OAuthConfigService=class{config;constructor(e){this.config={baseUrl:e.baseUrl,apiKey:e.apiKey,fetchProvider:e.fetchProvider,cacheTtl:e.cacheTtl??3e5,logger:e.logger||(()=>{}),cache:e.cache||new s.InMemoryOAuthConfigCache}}async getOAuthConfig(e){const t=await this.config.cache.get(e);if(t)return this.config.logger("[OAuthConfigService] Cache hit",{projectId:e}),t;const r=`${this.config.baseUrl}/api/v1/bouncer/projects/${encodeURIComponent(e)}/providers`;this.config.logger("[OAuthConfigService] Fetching config from API",{projectId:e,url:r});try{const t=await this.config.fetchProvider.fetch(r,{method:"GET",headers:{Authorization:`Bearer ${this.config.apiKey}`,"Content-Type":"application/json"}});if(!t.ok){const e=await t.text().catch(()=>"Unknown error");throw new Error(`Failed to fetch OAuth config: ${t.status} ${t.statusText} - ${e}`)}const s=await t.json();if(!s.success||!s.data)throw new Error("Invalid API response: missing success or data field");const i=s.data.providers||{};if("object"!=typeof i||Array.isArray(i))throw new Error("Invalid API response: providers must be an object, not an array");const a={providers:i};return await this.config.cache.set(e,a,this.config.cacheTtl),this.config.logger("[OAuthConfigService] Config fetched and cached",{projectId:e,providerCount:Object.keys(i).length,providers:Object.keys(i),expiresAt:new Date(Date.now()+this.config.cacheTtl).toISOString()}),a}catch(t){throw this.config.logger("[OAuthConfigService] API fetch failed",{projectId:e,error:t instanceof Error?t.message:String(t)}),t}}async clearCache(e){await this.config.cache.delete(e),this.config.logger("[OAuthConfigService] Cache cleared",{projectId:e})}async clearAllCache(){await this.config.cache.clear(),this.config.logger("[OAuthConfigService] All cache cleared")}}},98358:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StatusList2021Manager=void 0,t.createStatusListManager=function(e,t,r,s,i,o){return new a(e,t,r,s,i,o)};const s=r(46610),i=r(63969);class a{storage;identity;signingFunction;compressor;decompressor;statusListBaseUrl;defaultListSize;constructor(e,t,r,s,i,a){this.storage=e,this.identity=t,this.signingFunction=r,this.compressor=s,this.decompressor=i,this.statusListBaseUrl=a?.statusListBaseUrl||"https://status.example.com",this.defaultListSize=a?.defaultListSize||131072}async allocateStatusEntry(e){const t=`${this.statusListBaseUrl}/${e}/v1`,r=await this.storage.allocateIndex(t);return await this.ensureStatusListExists(t,e),{id:`${t}#${r}`,type:"StatusList2021Entry",statusPurpose:e,statusListIndex:r.toString(),statusListCredential:t}}async updateStatus(e,t){const{statusListCredential:r,statusListIndex:a}=e,o=await this.storage.getStatusList(r);if(!o)throw new Error(`Status list not found: ${r}`);const n=await s.BitstringManager.decode(o.credentialSubject.encodedList,this.compressor,this.decompressor),c=parseInt(a,10);n.setBit(c,t);const d=await n.encode(),l={...o,credentialSubject:{...o.credentialSubject,encodedList:d}},u={...l};delete u.proof;const h=(0,i.canonicalizeJSON)(u),p=await this.signingFunction(h,this.identity.getDid(),this.identity.getKeyId()),f={...l,proof:p};await this.storage.setStatusList(r,f)}async checkStatus(e){const{statusListCredential:t,statusListIndex:r}=e,i=await this.storage.getStatusList(t);if(!i)return!1;const a=await s.BitstringManager.decode(i.credentialSubject.encodedList,this.compressor,this.decompressor),o=parseInt(r,10);return a.getBit(o)}async getRevokedIndices(e){const t=await this.storage.getStatusList(e);return t?(await s.BitstringManager.decode(t.credentialSubject.encodedList,this.compressor,this.decompressor)).getSetBits():[]}async ensureStatusListExists(e,t){if(await this.storage.getStatusList(e))return;const r=new s.BitstringManager(this.defaultListSize,this.compressor,this.decompressor),a=await r.encode(),o={"@context":["https://www.w3.org/2018/credentials/v1","https://w3id.org/vc/status-list/2021/v1"],id:e,type:["VerifiableCredential","StatusList2021Credential"],issuer:this.identity.getDid(),issuanceDate:(new Date).toISOString(),credentialSubject:{id:`${e}#list`,type:"StatusList2021",statusPurpose:t,encodedList:a}},n=(0,i.canonicalizeJSON)(o),c=await this.signingFunction(n,this.identity.getDid(),this.identity.getKeyId()),d={...o,proof:c};await this.storage.setStatusList(e,d)}getStatusListBaseUrl(){return this.statusListBaseUrl}getDefaultListSize(){return this.defaultListSize}}t.StatusList2021Manager=a},98448:(e,t)=>{"use strict";function r(e){const t=e.length%4;return 0===t?e:e+"=".repeat((4-t)%4)}Object.defineProperty(t,"__esModule",{value:!0}),t.base64urlDecodeToString=function(e){const t=r(e).replace(/-/g,"+").replace(/_/g,"/");if("undefined"!=typeof atob)try{return atob(t)}catch(e){throw new Error(`Invalid base64url string: ${e instanceof Error?e.message:String(e)}`)}if(!/^[A-Za-z0-9+/]*={0,2}$/.test(t))throw new Error("Invalid base64url string: contains invalid characters");try{return Buffer.from(t,"base64").toString("utf-8")}catch(e){throw new Error(`Invalid base64url string: ${e instanceof Error?e.message:String(e)}`)}},t.base64urlDecodeToBytes=function(e){const t=r(e).replace(/-/g,"+").replace(/_/g,"/");if("undefined"!=typeof atob)try{const e=atob(t),r=new Uint8Array(e.length);for(let t=0;t<e.length;t++)r[t]=e.charCodeAt(t);return r}catch(e){throw new Error(`Invalid base64url string: ${e instanceof Error?e.message:String(e)}`)}return new Uint8Array(Buffer.from(t,"base64"))},t.base64urlEncodeFromString=function(e){return"undefined"!=typeof btoa?btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,""):Buffer.from(e,"utf-8").toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")},t.base64urlEncodeFromBytes=function(e){if("undefined"!=typeof btoa){const t=Array.from(e).map(e=>String.fromCharCode(e)).join("");return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}return Buffer.from(e).toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")},t.bytesToBase64=function(e){if("undefined"!=typeof btoa){const t=Array.from(e).map(e=>String.fromCharCode(e)).join("");return btoa(t)}return Buffer.from(e).toString("base64")},t.base64ToBytes=function(e){if("undefined"!=typeof atob){const t=atob(e),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r}return new Uint8Array(Buffer.from(e,"base64"))}}},t={};function r(s){var i=t[s];if(void 0!==i)return i.exports;var a=t[s]={exports:{}};return e[s].call(a.exports,a,a.exports,r),a.exports}r.d=(e,t)=>{for(var s in t)r.o(t,s)&&!r.o(e,s)&&Object.defineProperty(e,s,{enumerable:!0,get:t[s]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},(()=>{"use strict";const e=require("node:process");var t,s;!function(e){e.assertEqual=e=>{},e.assertIs=function(e){},e.assertNever=function(e){throw new Error},e.arrayToEnum=e=>{const t={};for(const r of e)t[r]=r;return t},e.getValidEnumValues=t=>{const r=e.objectKeys(t).filter(e=>"number"!=typeof t[t[e]]),s={};for(const e of r)s[e]=t[e];return e.objectValues(s)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{const t=[];for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.push(r);return t},e.find=(e,t)=>{for(const r of e)if(t(r))return r},e.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&Number.isFinite(e)&&Math.floor(e)===e,e.joinValues=function(e,t=" | "){return e.map(e=>"string"==typeof e?`'${e}'`:e).join(t)},e.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t}(t||(t={})),function(e){e.mergeShapes=(e,t)=>({...e,...t})}(s||(s={}));const i=t.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),a=e=>{switch(typeof e){case"undefined":return i.undefined;case"string":return i.string;case"number":return Number.isNaN(e)?i.nan:i.number;case"boolean":return i.boolean;case"function":return i.function;case"bigint":return i.bigint;case"symbol":return i.symbol;case"object":return Array.isArray(e)?i.array:null===e?i.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?i.promise:"undefined"!=typeof Map&&e instanceof Map?i.map:"undefined"!=typeof Set&&e instanceof Set?i.set:"undefined"!=typeof Date&&e instanceof Date?i.date:i.object;default:return i.unknown}},o=t.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class n extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(e){return e.message},r={_errors:[]},s=e=>{for(const i of e.issues)if("invalid_union"===i.code)i.unionErrors.map(s);else if("invalid_return_type"===i.code)s(i.returnTypeError);else if("invalid_arguments"===i.code)s(i.argumentsError);else if(0===i.path.length)r._errors.push(t(i));else{let e=r,s=0;for(;s<i.path.length;){const r=i.path[s];s===i.path.length-1?(e[r]=e[r]||{_errors:[]},e[r]._errors.push(t(i))):e[r]=e[r]||{_errors:[]},e=e[r],s++}}};return s(this),r}static assert(e){if(!(e instanceof n))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,t.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){const t={},r=[];for(const s of this.issues)if(s.path.length>0){const r=s.path[0];t[r]=t[r]||[],t[r].push(e(s))}else r.push(e(s));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}}n.create=e=>new n(e);const c=(e,r)=>{let s;switch(e.code){case o.invalid_type:s=e.received===i.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case o.invalid_literal:s=`Invalid literal value, expected ${JSON.stringify(e.expected,t.jsonStringifyReplacer)}`;break;case o.unrecognized_keys:s=`Unrecognized key(s) in object: ${t.joinValues(e.keys,", ")}`;break;case o.invalid_union:s="Invalid input";break;case o.invalid_union_discriminator:s=`Invalid discriminator value. Expected ${t.joinValues(e.options)}`;break;case o.invalid_enum_value:s=`Invalid enum value. Expected ${t.joinValues(e.options)}, received '${e.received}'`;break;case o.invalid_arguments:s="Invalid function arguments";break;case o.invalid_return_type:s="Invalid function return type";break;case o.invalid_date:s="Invalid date";break;case o.invalid_string:"object"==typeof e.validation?"includes"in e.validation?(s=`Invalid input: must include "${e.validation.includes}"`,"number"==typeof e.validation.position&&(s=`${s} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?s=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?s=`Invalid input: must end with "${e.validation.endsWith}"`:t.assertNever(e.validation):s="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case o.too_small:s="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:"number"===e.type||"bigint"===e.type?`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:"date"===e.type?`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:"Invalid input";break;case o.too_big:s="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"bigint"===e.type?`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"date"===e.type?`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:"Invalid input";break;case o.custom:s="Invalid input";break;case o.invalid_intersection_types:s="Intersection results could not be merged";break;case o.not_multiple_of:s=`Number must be a multiple of ${e.multipleOf}`;break;case o.not_finite:s="Number must be finite";break;default:s=r.defaultError,t.assertNever(e)}return{message:s}};let d=c;var l;!function(e){e.errToObj=e=>"string"==typeof e?{message:e}:e||{},e.toString=e=>"string"==typeof e?e:e?.message}(l||(l={}));function u(e,t){const r=d,s=(e=>{const{data:t,path:r,errorMaps:s,issueData:i}=e,a=[...r,...i.path||[]],o={...i,path:a};if(void 0!==i.message)return{...i,path:a,message:i.message};let n="";const c=s.filter(e=>!!e).slice().reverse();for(const e of c)n=e(o,{data:t,defaultError:n}).message;return{...i,path:a,message:n}})({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===c?void 0:c].filter(e=>!!e)});e.common.issues.push(s)}class h{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){const r=[];for(const s of t){if("aborted"===s.status)return p;"dirty"===s.status&&e.dirty(),r.push(s.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){const r=[];for(const e of t){const t=await e.key,s=await e.value;r.push({key:t,value:s})}return h.mergeObjectSync(e,r)}static mergeObjectSync(e,t){const r={};for(const s of t){const{key:t,value:i}=s;if("aborted"===t.status)return p;if("aborted"===i.status)return p;"dirty"===t.status&&e.dirty(),"dirty"===i.status&&e.dirty(),"__proto__"===t.value||void 0===i.value&&!s.alwaysSet||(r[t.value]=i.value)}return{status:e.value,value:r}}}const p=Object.freeze({status:"aborted"}),f=e=>({status:"dirty",value:e}),g=e=>({status:"valid",value:e}),m=e=>"aborted"===e.status,v=e=>"dirty"===e.status,y=e=>"valid"===e.status,_=e=>"undefined"!=typeof Promise&&e instanceof Promise;class w{constructor(e,t,r,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const b=(e,t)=>{if(y(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new n(e.common.issues);return this._error=t,this._error}}};function S(e){if(!e)return{};const{errorMap:t,invalid_type_error:r,required_error:s,description:i}=e;if(t&&(r||s))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');return t?{errorMap:t,description:i}:{errorMap:(t,i)=>{const{message:a}=e;return"invalid_enum_value"===t.code?{message:a??i.defaultError}:void 0===i.data?{message:a??s??i.defaultError}:"invalid_type"!==t.code?{message:i.defaultError}:{message:a??r??i.defaultError}},description:i}}class P{get description(){return this._def.description}_getType(e){return a(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:a(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new h,ctx:{common:e.parent.common,data:e.data,parsedType:a(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(_(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){const r={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:a(e)},s=this._parseSync({data:e,path:r.path,parent:r});return b(r,s)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:a(e)};if(!this["~standard"].async)try{const r=this._parseSync({data:e,path:[],parent:t});return y(r)?{value:r.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>y(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){const r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){const r={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:a(e)},s=this._parse({data:e,path:r.path,parent:r}),i=await(_(s)?s:Promise.resolve(s));return b(r,i)}refine(e,t){const r=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement((t,s)=>{const i=e(t),a=()=>s.addIssue({code:o.custom,...r(t)});return"undefined"!=typeof Promise&&i instanceof Promise?i.then(e=>!!e||(a(),!1)):!!i||(a(),!1)})}refinement(e,t){return this._refinement((r,s)=>!!e(r)||(s.addIssue("function"==typeof t?t(r,s):t),!1))}_refinement(e){return new Ee({schema:this,typeName:Re.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:e=>this["~validate"](e)}}optional(){return Ie.create(this,this._def)}nullable(){return ke.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return oe.create(this)}promise(){return Pe.create(this,this._def)}or(e){return de.create([this,e],this._def)}and(e){return pe.create(this,e,this._def)}transform(e){return new Ee({...S(this._def),schema:this,typeName:Re.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new Ce({...S(this._def),innerType:this,defaultValue:t,typeName:Re.ZodDefault})}brand(){return new Ae({typeName:Re.ZodBranded,type:this,...S(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new De({...S(this._def),innerType:this,catchValue:t,typeName:Re.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return xe.create(this,e)}readonly(){return Te.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const E=/^c[^\s-]{8,}$/i,I=/^[0-9a-z]+$/,k=/^[0-9A-HJKMNP-TV-Z]{26}$/i,C=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,D=/^[a-z0-9_-]{21}$/i,O=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,A=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,x=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let T;const R=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,$=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,j=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,N=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,M=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,F=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,K="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",q=new RegExp(`^${K}$`);function L(e){let t="[0-5]\\d";return e.precision?t=`${t}\\.\\d{${e.precision}}`:null==e.precision&&(t=`${t}(\\.\\d+)?`),`([01]\\d|2[0-3]):[0-5]\\d(:${t})${e.precision?"+":"?"}`}function U(e){return new RegExp(`^${L(e)}$`)}function V(e){let t=`${K}T${L(e)}`;const r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function H(e,t){return!("v4"!==t&&t||!R.test(e))||!("v6"!==t&&t||!j.test(e))}function B(e,t){if(!O.test(e))return!1;try{const[r]=e.split(".");if(!r)return!1;const s=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),i=JSON.parse(atob(s));return!("object"!=typeof i||null===i||"typ"in i&&"JWT"!==i?.typ||!i.alg||t&&i.alg!==t)}catch{return!1}}function z(e,t){return!("v4"!==t&&t||!$.test(e))||!("v6"!==t&&t||!N.test(e))}class J extends P{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==i.string){const t=this._getOrReturnCtx(e);return u(t,{code:o.invalid_type,expected:i.string,received:t.parsedType}),p}const r=new h;let s;for(const i of this._def.checks)if("min"===i.kind)e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),u(s,{code:o.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if("max"===i.kind)e.data.length>i.value&&(s=this._getOrReturnCtx(e,s),u(s,{code:o.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if("length"===i.kind){const t=e.data.length>i.value,a=e.data.length<i.value;(t||a)&&(s=this._getOrReturnCtx(e,s),t?u(s,{code:o.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):a&&u(s,{code:o.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if("email"===i.kind)x.test(e.data)||(s=this._getOrReturnCtx(e,s),u(s,{validation:"email",code:o.invalid_string,message:i.message}),r.dirty());else if("emoji"===i.kind)T||(T=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),T.test(e.data)||(s=this._getOrReturnCtx(e,s),u(s,{validation:"emoji",code:o.invalid_string,message:i.message}),r.dirty());else if("uuid"===i.kind)C.test(e.data)||(s=this._getOrReturnCtx(e,s),u(s,{validation:"uuid",code:o.invalid_string,message:i.message}),r.dirty());else if("nanoid"===i.kind)D.test(e.data)||(s=this._getOrReturnCtx(e,s),u(s,{validation:"nanoid",code:o.invalid_string,message:i.message}),r.dirty());else if("cuid"===i.kind)E.test(e.data)||(s=this._getOrReturnCtx(e,s),u(s,{validation:"cuid",code:o.invalid_string,message:i.message}),r.dirty());else if("cuid2"===i.kind)I.test(e.data)||(s=this._getOrReturnCtx(e,s),u(s,{validation:"cuid2",code:o.invalid_string,message:i.message}),r.dirty());else if("ulid"===i.kind)k.test(e.data)||(s=this._getOrReturnCtx(e,s),u(s,{validation:"ulid",code:o.invalid_string,message:i.message}),r.dirty());else if("url"===i.kind)try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),u(s,{validation:"url",code:o.invalid_string,message:i.message}),r.dirty()}else"regex"===i.kind?(i.regex.lastIndex=0,i.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),u(s,{validation:"regex",code:o.invalid_string,message:i.message}),r.dirty())):"trim"===i.kind?e.data=e.data.trim():"includes"===i.kind?e.data.includes(i.value,i.position)||(s=this._getOrReturnCtx(e,s),u(s,{code:o.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),r.dirty()):"toLowerCase"===i.kind?e.data=e.data.toLowerCase():"toUpperCase"===i.kind?e.data=e.data.toUpperCase():"startsWith"===i.kind?e.data.startsWith(i.value)||(s=this._getOrReturnCtx(e,s),u(s,{code:o.invalid_string,validation:{startsWith:i.value},message:i.message}),r.dirty()):"endsWith"===i.kind?e.data.endsWith(i.value)||(s=this._getOrReturnCtx(e,s),u(s,{code:o.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):"datetime"===i.kind?V(i).test(e.data)||(s=this._getOrReturnCtx(e,s),u(s,{code:o.invalid_string,validation:"datetime",message:i.message}),r.dirty()):"date"===i.kind?q.test(e.data)||(s=this._getOrReturnCtx(e,s),u(s,{code:o.invalid_string,validation:"date",message:i.message}),r.dirty()):"time"===i.kind?U(i).test(e.data)||(s=this._getOrReturnCtx(e,s),u(s,{code:o.invalid_string,validation:"time",message:i.message}),r.dirty()):"duration"===i.kind?A.test(e.data)||(s=this._getOrReturnCtx(e,s),u(s,{validation:"duration",code:o.invalid_string,message:i.message}),r.dirty()):"ip"===i.kind?H(e.data,i.version)||(s=this._getOrReturnCtx(e,s),u(s,{validation:"ip",code:o.invalid_string,message:i.message}),r.dirty()):"jwt"===i.kind?B(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),u(s,{validation:"jwt",code:o.invalid_string,message:i.message}),r.dirty()):"cidr"===i.kind?z(e.data,i.version)||(s=this._getOrReturnCtx(e,s),u(s,{validation:"cidr",code:o.invalid_string,message:i.message}),r.dirty()):"base64"===i.kind?M.test(e.data)||(s=this._getOrReturnCtx(e,s),u(s,{validation:"base64",code:o.invalid_string,message:i.message}),r.dirty()):"base64url"===i.kind?F.test(e.data)||(s=this._getOrReturnCtx(e,s),u(s,{validation:"base64url",code:o.invalid_string,message:i.message}),r.dirty()):t.assertNever(i);return{status:r.value,value:e.data}}_regex(e,t,r){return this.refinement(t=>e.test(t),{validation:t,code:o.invalid_string,...l.errToObj(r)})}_addCheck(e){return new J({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...l.errToObj(e)})}url(e){return this._addCheck({kind:"url",...l.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...l.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...l.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...l.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...l.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...l.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...l.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...l.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...l.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...l.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...l.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...l.errToObj(e)})}datetime(e){return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===e?.precision?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...l.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return"string"==typeof e?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:void 0===e?.precision?null:e?.precision,...l.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...l.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...l.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...l.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...l.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...l.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...l.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...l.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...l.errToObj(t)})}nonempty(e){return this.min(1,l.errToObj(e))}trim(){return new J({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new J({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new J({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>"datetime"===e.kind)}get isDate(){return!!this._def.checks.find(e=>"date"===e.kind)}get isTime(){return!!this._def.checks.find(e=>"time"===e.kind)}get isDuration(){return!!this._def.checks.find(e=>"duration"===e.kind)}get isEmail(){return!!this._def.checks.find(e=>"email"===e.kind)}get isURL(){return!!this._def.checks.find(e=>"url"===e.kind)}get isEmoji(){return!!this._def.checks.find(e=>"emoji"===e.kind)}get isUUID(){return!!this._def.checks.find(e=>"uuid"===e.kind)}get isNANOID(){return!!this._def.checks.find(e=>"nanoid"===e.kind)}get isCUID(){return!!this._def.checks.find(e=>"cuid"===e.kind)}get isCUID2(){return!!this._def.checks.find(e=>"cuid2"===e.kind)}get isULID(){return!!this._def.checks.find(e=>"ulid"===e.kind)}get isIP(){return!!this._def.checks.find(e=>"ip"===e.kind)}get isCIDR(){return!!this._def.checks.find(e=>"cidr"===e.kind)}get isBase64(){return!!this._def.checks.find(e=>"base64"===e.kind)}get isBase64url(){return!!this._def.checks.find(e=>"base64url"===e.kind)}get minLength(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}function W(e,t){const r=(e.toString().split(".")[1]||"").length,s=(t.toString().split(".")[1]||"").length,i=r>s?r:s;return Number.parseInt(e.toFixed(i).replace(".",""))%Number.parseInt(t.toFixed(i).replace(".",""))/10**i}J.create=e=>new J({checks:[],typeName:Re.ZodString,coerce:e?.coerce??!1,...S(e)});class Z extends P{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==i.number){const t=this._getOrReturnCtx(e);return u(t,{code:o.invalid_type,expected:i.number,received:t.parsedType}),p}let r;const s=new h;for(const i of this._def.checks)"int"===i.kind?t.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),u(r,{code:o.invalid_type,expected:"integer",received:"float",message:i.message}),s.dirty()):"min"===i.kind?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),u(r,{code:o.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):"max"===i.kind?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),u(r,{code:o.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):"multipleOf"===i.kind?0!==W(e.data,i.value)&&(r=this._getOrReturnCtx(e,r),u(r,{code:o.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):"finite"===i.kind?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),u(r,{code:o.not_finite,message:i.message}),s.dirty()):t.assertNever(i);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,l.toString(t))}gt(e,t){return this.setLimit("min",e,!1,l.toString(t))}lte(e,t){return this.setLimit("max",e,!0,l.toString(t))}lt(e,t){return this.setLimit("max",e,!1,l.toString(t))}setLimit(e,t,r,s){return new Z({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:l.toString(s)}]})}_addCheck(e){return new Z({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:l.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:l.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:l.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:l.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:l.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:l.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:l.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:l.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:l.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>"int"===e.kind||"multipleOf"===e.kind&&t.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const r of this._def.checks){if("finite"===r.kind||"int"===r.kind||"multipleOf"===r.kind)return!0;"min"===r.kind?(null===t||r.value>t)&&(t=r.value):"max"===r.kind&&(null===e||r.value<e)&&(e=r.value)}return Number.isFinite(t)&&Number.isFinite(e)}}Z.create=e=>new Z({checks:[],typeName:Re.ZodNumber,coerce:e?.coerce||!1,...S(e)});class Q extends P{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==i.bigint)return this._getInvalidInput(e);let r;const s=new h;for(const i of this._def.checks)"min"===i.kind?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),u(r,{code:o.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):"max"===i.kind?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),u(r,{code:o.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):"multipleOf"===i.kind?e.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),u(r,{code:o.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):t.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return u(t,{code:o.invalid_type,expected:i.bigint,received:t.parsedType}),p}gte(e,t){return this.setLimit("min",e,!0,l.toString(t))}gt(e,t){return this.setLimit("min",e,!1,l.toString(t))}lte(e,t){return this.setLimit("max",e,!0,l.toString(t))}lt(e,t){return this.setLimit("max",e,!1,l.toString(t))}setLimit(e,t,r,s){return new Q({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:l.toString(s)}]})}_addCheck(e){return new Q({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:l.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:l.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:l.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:l.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:l.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}Q.create=e=>new Q({checks:[],typeName:Re.ZodBigInt,coerce:e?.coerce??!1,...S(e)});class G extends P{_parse(e){if(this._def.coerce&&(e.data=Boolean(e.data)),this._getType(e)!==i.boolean){const t=this._getOrReturnCtx(e);return u(t,{code:o.invalid_type,expected:i.boolean,received:t.parsedType}),p}return g(e.data)}}G.create=e=>new G({typeName:Re.ZodBoolean,coerce:e?.coerce||!1,...S(e)});class Y extends P{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==i.date){const t=this._getOrReturnCtx(e);return u(t,{code:o.invalid_type,expected:i.date,received:t.parsedType}),p}if(Number.isNaN(e.data.getTime()))return u(this._getOrReturnCtx(e),{code:o.invalid_date}),p;const r=new h;let s;for(const i of this._def.checks)"min"===i.kind?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),u(s,{code:o.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),r.dirty()):"max"===i.kind?e.data.getTime()>i.value&&(s=this._getOrReturnCtx(e,s),u(s,{code:o.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):t.assertNever(i);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new Y({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:l.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:l.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}}Y.create=e=>new Y({checks:[],coerce:e?.coerce||!1,typeName:Re.ZodDate,...S(e)});class X extends P{_parse(e){if(this._getType(e)!==i.symbol){const t=this._getOrReturnCtx(e);return u(t,{code:o.invalid_type,expected:i.symbol,received:t.parsedType}),p}return g(e.data)}}X.create=e=>new X({typeName:Re.ZodSymbol,...S(e)});class ee extends P{_parse(e){if(this._getType(e)!==i.undefined){const t=this._getOrReturnCtx(e);return u(t,{code:o.invalid_type,expected:i.undefined,received:t.parsedType}),p}return g(e.data)}}ee.create=e=>new ee({typeName:Re.ZodUndefined,...S(e)});class te extends P{_parse(e){if(this._getType(e)!==i.null){const t=this._getOrReturnCtx(e);return u(t,{code:o.invalid_type,expected:i.null,received:t.parsedType}),p}return g(e.data)}}te.create=e=>new te({typeName:Re.ZodNull,...S(e)});class re extends P{constructor(){super(...arguments),this._any=!0}_parse(e){return g(e.data)}}re.create=e=>new re({typeName:Re.ZodAny,...S(e)});class se extends P{constructor(){super(...arguments),this._unknown=!0}_parse(e){return g(e.data)}}se.create=e=>new se({typeName:Re.ZodUnknown,...S(e)});class ie extends P{_parse(e){const t=this._getOrReturnCtx(e);return u(t,{code:o.invalid_type,expected:i.never,received:t.parsedType}),p}}ie.create=e=>new ie({typeName:Re.ZodNever,...S(e)});class ae extends P{_parse(e){if(this._getType(e)!==i.undefined){const t=this._getOrReturnCtx(e);return u(t,{code:o.invalid_type,expected:i.void,received:t.parsedType}),p}return g(e.data)}}ae.create=e=>new ae({typeName:Re.ZodVoid,...S(e)});class oe extends P{_parse(e){const{ctx:t,status:r}=this._processInputParams(e),s=this._def;if(t.parsedType!==i.array)return u(t,{code:o.invalid_type,expected:i.array,received:t.parsedType}),p;if(null!==s.exactLength){const e=t.data.length>s.exactLength.value,i=t.data.length<s.exactLength.value;(e||i)&&(u(t,{code:e?o.too_big:o.too_small,minimum:i?s.exactLength.value:void 0,maximum:e?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),r.dirty())}if(null!==s.minLength&&t.data.length<s.minLength.value&&(u(t,{code:o.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),null!==s.maxLength&&t.data.length>s.maxLength.value&&(u(t,{code:o.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map((e,r)=>s.type._parseAsync(new w(t,e,t.path,r)))).then(e=>h.mergeArray(r,e));const a=[...t.data].map((e,r)=>s.type._parseSync(new w(t,e,t.path,r)));return h.mergeArray(r,a)}get element(){return this._def.type}min(e,t){return new oe({...this._def,minLength:{value:e,message:l.toString(t)}})}max(e,t){return new oe({...this._def,maxLength:{value:e,message:l.toString(t)}})}length(e,t){return new oe({...this._def,exactLength:{value:e,message:l.toString(t)}})}nonempty(e){return this.min(1,e)}}function ne(e){if(e instanceof ce){const t={};for(const r in e.shape){const s=e.shape[r];t[r]=Ie.create(ne(s))}return new ce({...e._def,shape:()=>t})}return e instanceof oe?new oe({...e._def,type:ne(e.element)}):e instanceof Ie?Ie.create(ne(e.unwrap())):e instanceof ke?ke.create(ne(e.unwrap())):e instanceof fe?fe.create(e.items.map(e=>ne(e))):e}oe.create=(e,t)=>new oe({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Re.ZodArray,...S(t)});class ce extends P{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;const e=this._def.shape(),r=t.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==i.object){const t=this._getOrReturnCtx(e);return u(t,{code:o.invalid_type,expected:i.object,received:t.parsedType}),p}const{status:t,ctx:r}=this._processInputParams(e),{shape:s,keys:a}=this._getCached(),n=[];if(!(this._def.catchall instanceof ie&&"strip"===this._def.unknownKeys))for(const e in r.data)a.includes(e)||n.push(e);const c=[];for(const e of a){const t=s[e],i=r.data[e];c.push({key:{status:"valid",value:e},value:t._parse(new w(r,i,r.path,e)),alwaysSet:e in r.data})}if(this._def.catchall instanceof ie){const e=this._def.unknownKeys;if("passthrough"===e)for(const e of n)c.push({key:{status:"valid",value:e},value:{status:"valid",value:r.data[e]}});else if("strict"===e)n.length>0&&(u(r,{code:o.unrecognized_keys,keys:n}),t.dirty());else if("strip"!==e)throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const e=this._def.catchall;for(const t of n){const s=r.data[t];c.push({key:{status:"valid",value:t},value:e._parse(new w(r,s,r.path,t)),alwaysSet:t in r.data})}}return r.common.async?Promise.resolve().then(async()=>{const e=[];for(const t of c){const r=await t.key,s=await t.value;e.push({key:r,value:s,alwaysSet:t.alwaysSet})}return e}).then(e=>h.mergeObjectSync(t,e)):h.mergeObjectSync(t,c)}get shape(){return this._def.shape()}strict(e){return l.errToObj,new ce({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,r)=>{const s=this._def.errorMap?.(t,r).message??r.defaultError;return"unrecognized_keys"===t.code?{message:l.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new ce({...this._def,unknownKeys:"strip"})}passthrough(){return new ce({...this._def,unknownKeys:"passthrough"})}extend(e){return new ce({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new ce({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:Re.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new ce({...this._def,catchall:e})}pick(e){const r={};for(const s of t.objectKeys(e))e[s]&&this.shape[s]&&(r[s]=this.shape[s]);return new ce({...this._def,shape:()=>r})}omit(e){const r={};for(const s of t.objectKeys(this.shape))e[s]||(r[s]=this.shape[s]);return new ce({...this._def,shape:()=>r})}deepPartial(){return ne(this)}partial(e){const r={};for(const s of t.objectKeys(this.shape)){const t=this.shape[s];e&&!e[s]?r[s]=t:r[s]=t.optional()}return new ce({...this._def,shape:()=>r})}required(e){const r={};for(const s of t.objectKeys(this.shape))if(e&&!e[s])r[s]=this.shape[s];else{let e=this.shape[s];for(;e instanceof Ie;)e=e._def.innerType;r[s]=e}return new ce({...this._def,shape:()=>r})}keyof(){return we(t.objectKeys(this.shape))}}ce.create=(e,t)=>new ce({shape:()=>e,unknownKeys:"strip",catchall:ie.create(),typeName:Re.ZodObject,...S(t)}),ce.strictCreate=(e,t)=>new ce({shape:()=>e,unknownKeys:"strict",catchall:ie.create(),typeName:Re.ZodObject,...S(t)}),ce.lazycreate=(e,t)=>new ce({shape:e,unknownKeys:"strip",catchall:ie.create(),typeName:Re.ZodObject,...S(t)});class de extends P{_parse(e){const{ctx:t}=this._processInputParams(e),r=this._def.options;if(t.common.async)return Promise.all(r.map(async e=>{const r={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:r}),ctx:r}})).then(function(e){for(const t of e)if("valid"===t.result.status)return t.result;for(const r of e)if("dirty"===r.result.status)return t.common.issues.push(...r.ctx.common.issues),r.result;const r=e.map(e=>new n(e.ctx.common.issues));return u(t,{code:o.invalid_union,unionErrors:r}),p});{let e;const s=[];for(const i of r){const r={...t,common:{...t.common,issues:[]},parent:null},a=i._parseSync({data:t.data,path:t.path,parent:r});if("valid"===a.status)return a;"dirty"!==a.status||e||(e={result:a,ctx:r}),r.common.issues.length&&s.push(r.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const i=s.map(e=>new n(e));return u(t,{code:o.invalid_union,unionErrors:i}),p}}get options(){return this._def.options}}de.create=(e,t)=>new de({options:e,typeName:Re.ZodUnion,...S(t)});const le=e=>e instanceof ye?le(e.schema):e instanceof Ee?le(e.innerType()):e instanceof _e?[e.value]:e instanceof be?e.options:e instanceof Se?t.objectValues(e.enum):e instanceof Ce?le(e._def.innerType):e instanceof ee?[void 0]:e instanceof te?[null]:e instanceof Ie?[void 0,...le(e.unwrap())]:e instanceof ke?[null,...le(e.unwrap())]:e instanceof Ae||e instanceof Te?le(e.unwrap()):e instanceof De?le(e._def.innerType):[];class ue extends P{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==i.object)return u(t,{code:o.invalid_type,expected:i.object,received:t.parsedType}),p;const r=this.discriminator,s=t.data[r],a=this.optionsMap.get(s);return a?t.common.async?a._parseAsync({data:t.data,path:t.path,parent:t}):a._parseSync({data:t.data,path:t.path,parent:t}):(u(t,{code:o.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),p)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,r){const s=new Map;for(const r of t){const t=le(r.shape[e]);if(!t.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const i of t){if(s.has(i))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(i)}`);s.set(i,r)}}return new ue({typeName:Re.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:s,...S(r)})}}function he(e,r){const s=a(e),o=a(r);if(e===r)return{valid:!0,data:e};if(s===i.object&&o===i.object){const s=t.objectKeys(r),i=t.objectKeys(e).filter(e=>-1!==s.indexOf(e)),a={...e,...r};for(const t of i){const s=he(e[t],r[t]);if(!s.valid)return{valid:!1};a[t]=s.data}return{valid:!0,data:a}}if(s===i.array&&o===i.array){if(e.length!==r.length)return{valid:!1};const t=[];for(let s=0;s<e.length;s++){const i=he(e[s],r[s]);if(!i.valid)return{valid:!1};t.push(i.data)}return{valid:!0,data:t}}return s===i.date&&o===i.date&&+e===+r?{valid:!0,data:e}:{valid:!1}}class pe extends P{_parse(e){const{status:t,ctx:r}=this._processInputParams(e),s=(e,s)=>{if(m(e)||m(s))return p;const i=he(e.value,s.value);return i.valid?((v(e)||v(s))&&t.dirty(),{status:t.value,value:i.data}):(u(r,{code:o.invalid_intersection_types}),p)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([e,t])=>s(e,t)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}pe.create=(e,t,r)=>new pe({left:e,right:t,typeName:Re.ZodIntersection,...S(r)});class fe extends P{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==i.array)return u(r,{code:o.invalid_type,expected:i.array,received:r.parsedType}),p;if(r.data.length<this._def.items.length)return u(r,{code:o.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),p;!this._def.rest&&r.data.length>this._def.items.length&&(u(r,{code:o.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const s=[...r.data].map((e,t)=>{const s=this._def.items[t]||this._def.rest;return s?s._parse(new w(r,e,r.path,t)):null}).filter(e=>!!e);return r.common.async?Promise.all(s).then(e=>h.mergeArray(t,e)):h.mergeArray(t,s)}get items(){return this._def.items}rest(e){return new fe({...this._def,rest:e})}}fe.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new fe({items:e,typeName:Re.ZodTuple,rest:null,...S(t)})};class ge extends P{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==i.object)return u(r,{code:o.invalid_type,expected:i.object,received:r.parsedType}),p;const s=[],a=this._def.keyType,n=this._def.valueType;for(const e in r.data)s.push({key:a._parse(new w(r,e,r.path,e)),value:n._parse(new w(r,r.data[e],r.path,e)),alwaysSet:e in r.data});return r.common.async?h.mergeObjectAsync(t,s):h.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,r){return new ge(t instanceof P?{keyType:e,valueType:t,typeName:Re.ZodRecord,...S(r)}:{keyType:J.create(),valueType:e,typeName:Re.ZodRecord,...S(t)})}}class me extends P{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==i.map)return u(r,{code:o.invalid_type,expected:i.map,received:r.parsedType}),p;const s=this._def.keyType,a=this._def.valueType,n=[...r.data.entries()].map(([e,t],i)=>({key:s._parse(new w(r,e,r.path,[i,"key"])),value:a._parse(new w(r,t,r.path,[i,"value"]))}));if(r.common.async){const e=new Map;return Promise.resolve().then(async()=>{for(const r of n){const s=await r.key,i=await r.value;if("aborted"===s.status||"aborted"===i.status)return p;"dirty"!==s.status&&"dirty"!==i.status||t.dirty(),e.set(s.value,i.value)}return{status:t.value,value:e}})}{const e=new Map;for(const r of n){const s=r.key,i=r.value;if("aborted"===s.status||"aborted"===i.status)return p;"dirty"!==s.status&&"dirty"!==i.status||t.dirty(),e.set(s.value,i.value)}return{status:t.value,value:e}}}}me.create=(e,t,r)=>new me({valueType:t,keyType:e,typeName:Re.ZodMap,...S(r)});class ve extends P{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==i.set)return u(r,{code:o.invalid_type,expected:i.set,received:r.parsedType}),p;const s=this._def;null!==s.minSize&&r.data.size<s.minSize.value&&(u(r,{code:o.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),null!==s.maxSize&&r.data.size>s.maxSize.value&&(u(r,{code:o.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());const a=this._def.valueType;function n(e){const r=new Set;for(const s of e){if("aborted"===s.status)return p;"dirty"===s.status&&t.dirty(),r.add(s.value)}return{status:t.value,value:r}}const c=[...r.data.values()].map((e,t)=>a._parse(new w(r,e,r.path,t)));return r.common.async?Promise.all(c).then(e=>n(e)):n(c)}min(e,t){return new ve({...this._def,minSize:{value:e,message:l.toString(t)}})}max(e,t){return new ve({...this._def,maxSize:{value:e,message:l.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}ve.create=(e,t)=>new ve({valueType:e,minSize:null,maxSize:null,typeName:Re.ZodSet,...S(t)});class ye extends P{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}ye.create=(e,t)=>new ye({getter:e,typeName:Re.ZodLazy,...S(t)});class _e extends P{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return u(t,{received:t.data,code:o.invalid_literal,expected:this._def.value}),p}return{status:"valid",value:e.data}}get value(){return this._def.value}}function we(e,t){return new be({values:e,typeName:Re.ZodEnum,...S(t)})}_e.create=(e,t)=>new _e({value:e,typeName:Re.ZodLiteral,...S(t)});class be extends P{_parse(e){if("string"!=typeof e.data){const r=this._getOrReturnCtx(e),s=this._def.values;return u(r,{expected:t.joinValues(s),received:r.parsedType,code:o.invalid_type}),p}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),r=this._def.values;return u(t,{received:t.data,code:o.invalid_enum_value,options:r}),p}return g(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return be.create(e,{...this._def,...t})}exclude(e,t=this._def){return be.create(this.options.filter(t=>!e.includes(t)),{...this._def,...t})}}be.create=we;class Se extends P{_parse(e){const r=t.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(e);if(s.parsedType!==i.string&&s.parsedType!==i.number){const e=t.objectValues(r);return u(s,{expected:t.joinValues(e),received:s.parsedType,code:o.invalid_type}),p}if(this._cache||(this._cache=new Set(t.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const e=t.objectValues(r);return u(s,{received:s.data,code:o.invalid_enum_value,options:e}),p}return g(e.data)}get enum(){return this._def.values}}Se.create=(e,t)=>new Se({values:e,typeName:Re.ZodNativeEnum,...S(t)});class Pe extends P{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==i.promise&&!1===t.common.async)return u(t,{code:o.invalid_type,expected:i.promise,received:t.parsedType}),p;const r=t.parsedType===i.promise?t.data:Promise.resolve(t.data);return g(r.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}Pe.create=(e,t)=>new Pe({type:e,typeName:Re.ZodPromise,...S(t)});class Ee extends P{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Re.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:r,ctx:s}=this._processInputParams(e),i=this._def.effect||null,a={addIssue:e=>{u(s,e),e.fatal?r.abort():r.dirty()},get path(){return s.path}};if(a.addIssue=a.addIssue.bind(a),"preprocess"===i.type){const e=i.transform(s.data,a);if(s.common.async)return Promise.resolve(e).then(async e=>{if("aborted"===r.value)return p;const t=await this._def.schema._parseAsync({data:e,path:s.path,parent:s});return"aborted"===t.status?p:"dirty"===t.status||"dirty"===r.value?f(t.value):t});{if("aborted"===r.value)return p;const t=this._def.schema._parseSync({data:e,path:s.path,parent:s});return"aborted"===t.status?p:"dirty"===t.status||"dirty"===r.value?f(t.value):t}}if("refinement"===i.type){const e=e=>{const t=i.refinement(e,a);if(s.common.async)return Promise.resolve(t);if(t instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1===s.common.async){const t=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});return"aborted"===t.status?p:("dirty"===t.status&&r.dirty(),e(t.value),{status:r.value,value:t.value})}return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(t=>"aborted"===t.status?p:("dirty"===t.status&&r.dirty(),e(t.value).then(()=>({status:r.value,value:t.value}))))}if("transform"===i.type){if(!1===s.common.async){const e=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(!y(e))return p;const t=i.transform(e.value,a);if(t instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:t}}return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(e=>y(e)?Promise.resolve(i.transform(e.value,a)).then(e=>({status:r.value,value:e})):p)}t.assertNever(i)}}Ee.create=(e,t,r)=>new Ee({schema:e,typeName:Re.ZodEffects,effect:t,...S(r)}),Ee.createWithPreprocess=(e,t,r)=>new Ee({schema:t,effect:{type:"preprocess",transform:e},typeName:Re.ZodEffects,...S(r)});class Ie extends P{_parse(e){return this._getType(e)===i.undefined?g(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Ie.create=(e,t)=>new Ie({innerType:e,typeName:Re.ZodOptional,...S(t)});class ke extends P{_parse(e){return this._getType(e)===i.null?g(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ke.create=(e,t)=>new ke({innerType:e,typeName:Re.ZodNullable,...S(t)});class Ce extends P{_parse(e){const{ctx:t}=this._processInputParams(e);let r=t.data;return t.parsedType===i.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}Ce.create=(e,t)=>new Ce({innerType:e,typeName:Re.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...S(t)});class De extends P{_parse(e){const{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return _(s)?s.then(e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new n(r.common.issues)},input:r.data})})):{status:"valid",value:"valid"===s.status?s.value:this._def.catchValue({get error(){return new n(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}De.create=(e,t)=>new De({innerType:e,typeName:Re.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...S(t)});class Oe extends P{_parse(e){if(this._getType(e)!==i.nan){const t=this._getOrReturnCtx(e);return u(t,{code:o.invalid_type,expected:i.nan,received:t.parsedType}),p}return{status:"valid",value:e.data}}}Oe.create=e=>new Oe({typeName:Re.ZodNaN,...S(e)}),Symbol("zod_brand");class Ae extends P{_parse(e){const{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}}class xe extends P{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{const e=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?p:"dirty"===e.status?(t.dirty(),f(e.value)):this._def.out._parseAsync({data:e.value,path:r.path,parent:r})})();{const e=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?p:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:r.path,parent:r})}}static create(e,t){return new xe({in:e,out:t,typeName:Re.ZodPipeline})}}class Te extends P{_parse(e){const t=this._def.innerType._parse(e),r=e=>(y(e)&&(e.value=Object.freeze(e.value)),e);return _(t)?t.then(e=>r(e)):r(t)}unwrap(){return this._def.innerType}}var Re;Te.create=(e,t)=>new Te({innerType:e,typeName:Re.ZodReadonly,...S(t)}),ce.lazycreate,function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"}(Re||(Re={}));const $e=J.create,je=Z.create,Ne=(Oe.create,Q.create,G.create),Me=(Y.create,X.create,ee.create,te.create,re.create,se.create),Fe=(ie.create,ae.create,oe.create),Ke=ce.create,qe=(ce.strictCreate,de.create),Le=ue.create,Ue=(pe.create,fe.create,ge.create),Ve=(me.create,ve.create,ye.create,_e.create),He=be.create,Be=(Se.create,Pe.create,Ee.create,Ie.create),ze=(ke.create,Ee.createWithPreprocess,xe.create,"2025-06-18"),Je=[ze,"2025-03-26","2024-11-05","2024-10-07"],We="2.0",Ze=qe([$e(),je().int()]),Qe=$e(),Ge=Ke({progressToken:Be(Ze)}).passthrough(),Ye=Ke({_meta:Be(Ge)}).passthrough(),Xe=Ke({method:$e(),params:Be(Ye)}),et=Ke({_meta:Be(Ke({}).passthrough())}).passthrough(),tt=Ke({method:$e(),params:Be(et)}),rt=Ke({_meta:Be(Ke({}).passthrough())}).passthrough(),st=qe([$e(),je().int()]),it=Ke({jsonrpc:Ve(We),id:st}).merge(Xe).strict(),at=Ke({jsonrpc:Ve(We)}).merge(tt).strict(),ot=Ke({jsonrpc:Ve(We),id:st,result:rt}).strict(),nt=e=>ot.safeParse(e).success;var ct;!function(e){e[e.ConnectionClosed=-32e3]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError"}(ct||(ct={}));const dt=Ke({jsonrpc:Ve(We),id:st,error:Ke({code:je().int(),message:$e(),data:Be(Me())})}).strict(),lt=qe([it,at,ot,dt]),ut=rt.strict(),ht=tt.extend({method:Ve("notifications/cancelled"),params:et.extend({requestId:st,reason:$e().optional()})}),pt=Ke({src:$e(),mimeType:Be($e()),sizes:Be($e())}).passthrough(),ft=Ke({name:$e(),title:Be($e())}).passthrough(),gt=ft.extend({version:$e(),websiteUrl:Be($e()),icons:Be(Fe(pt))}),mt=Ke({experimental:Be(Ke({}).passthrough()),sampling:Be(Ke({}).passthrough()),elicitation:Be(Ke({}).passthrough()),roots:Be(Ke({listChanged:Be(Ne())}).passthrough())}).passthrough(),vt=Xe.extend({method:Ve("initialize"),params:Ye.extend({protocolVersion:$e(),capabilities:mt,clientInfo:gt})}),yt=Ke({experimental:Be(Ke({}).passthrough()),logging:Be(Ke({}).passthrough()),completions:Be(Ke({}).passthrough()),prompts:Be(Ke({listChanged:Be(Ne())}).passthrough()),resources:Be(Ke({subscribe:Be(Ne()),listChanged:Be(Ne())}).passthrough()),tools:Be(Ke({listChanged:Be(Ne())}).passthrough())}).passthrough(),_t=rt.extend({protocolVersion:$e(),capabilities:yt,serverInfo:gt,instructions:Be($e())}),wt=tt.extend({method:Ve("notifications/initialized")}),bt=Xe.extend({method:Ve("ping")}),St=Ke({progress:je(),total:Be(je()),message:Be($e())}).passthrough(),Pt=tt.extend({method:Ve("notifications/progress"),params:et.merge(St).extend({progressToken:Ze})}),Et=Xe.extend({params:Ye.extend({cursor:Be(Qe)}).optional()}),It=rt.extend({nextCursor:Be(Qe)}),kt=Ke({uri:$e(),mimeType:Be($e()),_meta:Be(Ke({}).passthrough())}).passthrough(),Ct=kt.extend({text:$e()}),Dt=$e().refine(e=>{try{return atob(e),!0}catch(e){return!1}},{message:"Invalid Base64 string"}),Ot=kt.extend({blob:Dt}),At=ft.extend({uri:$e(),description:Be($e()),mimeType:Be($e()),icons:Be(Fe(pt)),_meta:Be(Ke({}).passthrough())}),xt=ft.extend({uriTemplate:$e(),description:Be($e()),mimeType:Be($e()),_meta:Be(Ke({}).passthrough())}),Tt=Et.extend({method:Ve("resources/list")}),Rt=It.extend({resources:Fe(At)}),$t=Et.extend({method:Ve("resources/templates/list")}),jt=It.extend({resourceTemplates:Fe(xt)}),Nt=Xe.extend({method:Ve("resources/read"),params:Ye.extend({uri:$e()})}),Mt=rt.extend({contents:Fe(qe([Ct,Ot]))}),Ft=tt.extend({method:Ve("notifications/resources/list_changed")}),Kt=Xe.extend({method:Ve("resources/subscribe"),params:Ye.extend({uri:$e()})}),qt=Xe.extend({method:Ve("resources/unsubscribe"),params:Ye.extend({uri:$e()})}),Lt=tt.extend({method:Ve("notifications/resources/updated"),params:et.extend({uri:$e()})}),Ut=Ke({name:$e(),description:Be($e()),required:Be(Ne())}).passthrough(),Vt=ft.extend({description:Be($e()),arguments:Be(Fe(Ut)),icons:Be(Fe(pt)),_meta:Be(Ke({}).passthrough())}),Ht=Et.extend({method:Ve("prompts/list")}),Bt=It.extend({prompts:Fe(Vt)}),zt=Xe.extend({method:Ve("prompts/get"),params:Ye.extend({name:$e(),arguments:Be(Ue($e()))})}),Jt=Ke({type:Ve("text"),text:$e(),_meta:Be(Ke({}).passthrough())}).passthrough(),Wt=Ke({type:Ve("image"),data:Dt,mimeType:$e(),_meta:Be(Ke({}).passthrough())}).passthrough(),Zt=Ke({type:Ve("audio"),data:Dt,mimeType:$e(),_meta:Be(Ke({}).passthrough())}).passthrough(),Qt=Ke({type:Ve("resource"),resource:qe([Ct,Ot]),_meta:Be(Ke({}).passthrough())}).passthrough(),Gt=qe([Jt,Wt,Zt,At.extend({type:Ve("resource_link")}),Qt]),Yt=Ke({role:He(["user","assistant"]),content:Gt}).passthrough(),Xt=rt.extend({description:Be($e()),messages:Fe(Yt)}),er=tt.extend({method:Ve("notifications/prompts/list_changed")}),tr=Ke({title:Be($e()),readOnlyHint:Be(Ne()),destructiveHint:Be(Ne()),idempotentHint:Be(Ne()),openWorldHint:Be(Ne())}).passthrough(),rr=ft.extend({description:Be($e()),inputSchema:Ke({type:Ve("object"),properties:Be(Ke({}).passthrough()),required:Be(Fe($e()))}).passthrough(),outputSchema:Be(Ke({type:Ve("object"),properties:Be(Ke({}).passthrough()),required:Be(Fe($e()))}).passthrough()),annotations:Be(tr),icons:Be(Fe(pt)),_meta:Be(Ke({}).passthrough())}),sr=Et.extend({method:Ve("tools/list")}),ir=It.extend({tools:Fe(rr)}),ar=rt.extend({content:Fe(Gt).default([]),structuredContent:Ke({}).passthrough().optional(),isError:Be(Ne())}),or=(ar.or(rt.extend({toolResult:Me()})),Xe.extend({method:Ve("tools/call"),params:Ye.extend({name:$e(),arguments:Be(Ue(Me()))})})),nr=tt.extend({method:Ve("notifications/tools/list_changed")}),cr=He(["debug","info","notice","warning","error","critical","alert","emergency"]),dr=Xe.extend({method:Ve("logging/setLevel"),params:Ye.extend({level:cr})}),lr=tt.extend({method:Ve("notifications/message"),params:et.extend({level:cr,logger:Be($e()),data:Me()})}),ur=Ke({name:$e().optional()}).passthrough(),hr=Ke({hints:Be(Fe(ur)),costPriority:Be(je().min(0).max(1)),speedPriority:Be(je().min(0).max(1)),intelligencePriority:Be(je().min(0).max(1))}).passthrough(),pr=Ke({role:He(["user","assistant"]),content:qe([Jt,Wt,Zt])}).passthrough(),fr=Xe.extend({method:Ve("sampling/createMessage"),params:Ye.extend({messages:Fe(pr),systemPrompt:Be($e()),includeContext:Be(He(["none","thisServer","allServers"])),temperature:Be(je()),maxTokens:je().int(),stopSequences:Be(Fe($e())),metadata:Be(Ke({}).passthrough()),modelPreferences:Be(hr)})}),gr=rt.extend({model:$e(),stopReason:Be(He(["endTurn","stopSequence","maxTokens"]).or($e())),role:He(["user","assistant"]),content:Le("type",[Jt,Wt,Zt])}),mr=qe([Ke({type:Ve("boolean"),title:Be($e()),description:Be($e()),default:Be(Ne())}).passthrough(),Ke({type:Ve("string"),title:Be($e()),description:Be($e()),minLength:Be(je()),maxLength:Be(je()),format:Be(He(["email","uri","date","date-time"]))}).passthrough(),Ke({type:He(["number","integer"]),title:Be($e()),description:Be($e()),minimum:Be(je()),maximum:Be(je())}).passthrough(),Ke({type:Ve("string"),title:Be($e()),description:Be($e()),enum:Fe($e()),enumNames:Be(Fe($e()))}).passthrough()]),vr=Xe.extend({method:Ve("elicitation/create"),params:Ye.extend({message:$e(),requestedSchema:Ke({type:Ve("object"),properties:Ue($e(),mr),required:Be(Fe($e()))}).passthrough()})}),yr=rt.extend({action:He(["accept","decline","cancel"]),content:Be(Ue($e(),Me()))}),_r=Ke({type:Ve("ref/resource"),uri:$e()}).passthrough(),wr=Ke({type:Ve("ref/prompt"),name:$e()}).passthrough(),br=Xe.extend({method:Ve("completion/complete"),params:Ye.extend({ref:qe([wr,_r]),argument:Ke({name:$e(),value:$e()}).passthrough(),context:Be(Ke({arguments:Be(Ue($e(),$e()))}))})}),Sr=rt.extend({completion:Ke({values:Fe($e()).max(100),total:Be(je().int()),hasMore:Be(Ne())}).passthrough()}),Pr=Ke({uri:$e().startsWith("file://"),name:Be($e()),_meta:Be(Ke({}).passthrough())}).passthrough(),Er=Xe.extend({method:Ve("roots/list")}),Ir=rt.extend({roots:Fe(Pr)}),kr=tt.extend({method:Ve("notifications/roots/list_changed")});qe([bt,vt,br,dr,zt,Ht,Tt,$t,Nt,Kt,qt,or,sr]),qe([ht,Pt,wt,kr]),qe([ut,gr,yr,Ir]),qe([bt,fr,vr,Er]),qe([ht,Pt,lr,Lt,Ft,nr,er]),qe([ut,_t,Sr,Xt,Bt,Rt,jt,Mt,ar,ir]);class Cr extends Error{constructor(e,t,r){super(`MCP error ${e}: ${t}`),this.code=e,this.data=r,this.name="McpError"}}class Dr{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;const e=this._buffer.indexOf("\n");if(-1===e)return null;const t=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),function(e){return lt.parse(JSON.parse(e))}(t)}clear(){this._buffer=void 0}}class Or{constructor(t=e.stdin,r=e.stdout){this._stdin=t,this._stdout=r,this._readBuffer=new Dr,this._started=!1,this._ondata=e=>{this._readBuffer.append(e),this.processReadBuffer()},this._onerror=e=>{var t;null===(t=this.onerror)||void 0===t||t.call(this,e)}}async start(){if(this._started)throw new 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(var e,t;;)try{const t=this._readBuffer.readMessage();if(null===t)break;null===(e=this.onmessage)||void 0===e||e.call(this,t)}catch(e){null===(t=this.onerror)||void 0===t||t.call(this,e)}}async close(){var e;this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),0===this._stdin.listenerCount("data")&&this._stdin.pause(),this._readBuffer.clear(),null===(e=this.onclose)||void 0===e||e.call(this)}send(e){return new Promise(t=>{const r=function(e){return JSON.stringify(e)+"\n"}(e);this._stdout.write(r)?t():this._stdout.once("drain",t)})}}class Ar{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this.setNotificationHandler(ht,e=>{const t=this._requestHandlerAbortControllers.get(e.params.requestId);null==t||t.abort(e.params.reason)}),this.setNotificationHandler(Pt,e=>{this._onprogress(e)}),this.setRequestHandler(bt,e=>({}))}_setupTimeout(e,t,r,s,i=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(s,t),startTime:Date.now(),timeout:t,maxTotalTimeout:r,resetTimeoutOnProgress:i,onTimeout:s})}_resetTimeout(e){const t=this._timeoutInfo.get(e);if(!t)return!1;const r=Date.now()-t.startTime;if(t.maxTotalTimeout&&r>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),new Cr(ct.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:r});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){const t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){var t,r,s;this._transport=e;const i=null===(t=this.transport)||void 0===t?void 0:t.onclose;this._transport.onclose=()=>{null==i||i(),this._onclose()};const a=null===(r=this.transport)||void 0===r?void 0:r.onerror;this._transport.onerror=e=>{null==a||a(e),this._onerror(e)};const o=null===(s=this._transport)||void 0===s?void 0:s.onmessage;this._transport.onmessage=(e,t)=>{var r;null==o||o(e,t),nt(e)||(r=e,dt.safeParse(r).success)?this._onresponse(e):(e=>it.safeParse(e).success)(e)?this._onrequest(e,t):(e=>at.safeParse(e).success)(e)?this._onnotification(e):this._onerror(new Error(`Unknown message type: ${JSON.stringify(e)}`))},await this._transport.start()}_onclose(){var e;const t=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear(),this._transport=void 0,null===(e=this.onclose)||void 0===e||e.call(this);const r=new Cr(ct.ConnectionClosed,"Connection closed");for(const e of t.values())e(r)}_onerror(e){var t;null===(t=this.onerror)||void 0===t||t.call(this,e)}_onnotification(e){var t;const r=null!==(t=this._notificationHandlers.get(e.method))&&void 0!==t?t:this.fallbackNotificationHandler;void 0!==r&&Promise.resolve().then(()=>r(e)).catch(e=>this._onerror(new Error(`Uncaught error in notification handler: ${e}`)))}_onrequest(e,t){var r,s;const i=null!==(r=this._requestHandlers.get(e.method))&&void 0!==r?r:this.fallbackRequestHandler,a=this._transport;if(void 0===i)return void(null==a||a.send({jsonrpc:"2.0",id:e.id,error:{code:ct.MethodNotFound,message:"Method not found"}}).catch(e=>this._onerror(new Error(`Failed to send an error response: ${e}`))));const o=new AbortController;this._requestHandlerAbortControllers.set(e.id,o);const n={signal:o.signal,sessionId:null==a?void 0:a.sessionId,_meta:null===(s=e.params)||void 0===s?void 0:s._meta,sendNotification:t=>this.notification(t,{relatedRequestId:e.id}),sendRequest:(t,r,s)=>this.request(t,r,{...s,relatedRequestId:e.id}),authInfo:null==t?void 0:t.authInfo,requestId:e.id,requestInfo:null==t?void 0:t.requestInfo};Promise.resolve().then(()=>i(e,n)).then(t=>{if(!o.signal.aborted)return null==a?void 0:a.send({result:t,jsonrpc:"2.0",id:e.id})},t=>{var r;if(!o.signal.aborted)return null==a?void 0:a.send({jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(t.code)?t.code:ct.InternalError,message:null!==(r=t.message)&&void 0!==r?r:"Internal error"}})}).catch(e=>this._onerror(new Error(`Failed to send response: ${e}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){const{progressToken:t,...r}=e.params,s=Number(t),i=this._progressHandlers.get(s);if(!i)return void this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));const a=this._responseHandlers.get(s),o=this._timeoutInfo.get(s);if(o&&a&&o.resetTimeoutOnProgress)try{this._resetTimeout(s)}catch(e){return void a(e)}i(r)}_onresponse(e){const t=Number(e.id),r=this._responseHandlers.get(t);void 0!==r?(this._responseHandlers.delete(t),this._progressHandlers.delete(t),this._cleanupTimeout(t),nt(e)?r(e):r(new Cr(e.error.code,e.error.message,e.error.data))):this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`))}get transport(){return this._transport}async close(){var e;await(null===(e=this._transport)||void 0===e?void 0:e.close())}request(e,t,r){const{relatedRequestId:s,resumptionToken:i,onresumptiontoken:a}=null!=r?r:{};return new Promise((o,n)=>{var c,d,l,u,h,p;if(!this._transport)return void n(new Error("Not connected"));!0===(null===(c=this._options)||void 0===c?void 0:c.enforceStrictCapabilities)&&this.assertCapabilityForMethod(e.method),null===(d=null==r?void 0:r.signal)||void 0===d||d.throwIfAborted();const f=this._requestMessageId++,g={...e,jsonrpc:"2.0",id:f};(null==r?void 0:r.onprogress)&&(this._progressHandlers.set(f,r.onprogress),g.params={...e.params,_meta:{...(null===(l=e.params)||void 0===l?void 0:l._meta)||{},progressToken:f}});const m=e=>{var t;this._responseHandlers.delete(f),this._progressHandlers.delete(f),this._cleanupTimeout(f),null===(t=this._transport)||void 0===t||t.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:f,reason:String(e)}},{relatedRequestId:s,resumptionToken:i,onresumptiontoken:a}).catch(e=>this._onerror(new Error(`Failed to send cancellation: ${e}`))),n(e)};this._responseHandlers.set(f,e=>{var s;if(!(null===(s=null==r?void 0:r.signal)||void 0===s?void 0:s.aborted)){if(e instanceof Error)return n(e);try{const r=t.parse(e.result);o(r)}catch(e){n(e)}}}),null===(u=null==r?void 0:r.signal)||void 0===u||u.addEventListener("abort",()=>{var e;m(null===(e=null==r?void 0:r.signal)||void 0===e?void 0:e.reason)});const v=null!==(h=null==r?void 0:r.timeout)&&void 0!==h?h:6e4;this._setupTimeout(f,v,null==r?void 0:r.maxTotalTimeout,()=>m(new Cr(ct.RequestTimeout,"Request timed out",{timeout:v})),null!==(p=null==r?void 0:r.resetTimeoutOnProgress)&&void 0!==p&&p),this._transport.send(g,{relatedRequestId:s,resumptionToken:i,onresumptiontoken:a}).catch(e=>{this._cleanupTimeout(f),n(e)})})}async notification(e,t){var r,s;if(!this._transport)throw new Error("Not connected");if(this.assertNotificationCapability(e.method),(null!==(s=null===(r=this._options)||void 0===r?void 0:r.debouncedNotificationMethods)&&void 0!==s?s:[]).includes(e.method)&&!e.params&&!(null==t?void 0:t.relatedRequestId)){if(this._pendingDebouncedNotifications.has(e.method))return;return this._pendingDebouncedNotifications.add(e.method),void Promise.resolve().then(()=>{var r;if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;const s={...e,jsonrpc:"2.0"};null===(r=this._transport)||void 0===r||r.send(s,t).catch(e=>this._onerror(e))})}const i={...e,jsonrpc:"2.0"};await this._transport.send(i,t)}setRequestHandler(e,t){const r=e.shape.method.value;this.assertRequestHandlerCapability(r),this._requestHandlers.set(r,(r,s)=>Promise.resolve(t(e.parse(r),s)))}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t){this._notificationHandlers.set(e.shape.method.value,r=>Promise.resolve(t(e.parse(r))))}removeNotificationHandler(e){this._notificationHandlers.delete(e)}}var xr=r(53084);class Tr extends Ar{constructor(e,t){var r;super(t),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(cr.options.map((e,t)=>[e,t])),this.isMessageIgnored=(e,t)=>{const r=this._loggingLevels.get(t);return!!r&&this.LOG_LEVEL_SEVERITY.get(e)<this.LOG_LEVEL_SEVERITY.get(r)},this._capabilities=null!==(r=null==t?void 0:t.capabilities)&&void 0!==r?r:{},this._instructions=null==t?void 0:t.instructions,this.setRequestHandler(vt,e=>this._oninitialize(e)),this.setNotificationHandler(wt,()=>{var e;return null===(e=this.oninitialized)||void 0===e?void 0:e.call(this)}),this._capabilities.logging&&this.setRequestHandler(dr,async(e,t)=>{var r;const s=t.sessionId||(null===(r=t.requestInfo)||void 0===r?void 0:r.headers["mcp-session-id"])||void 0,{level:i}=e.params,a=cr.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");var t,r;this._capabilities=(t=this._capabilities,r=e,Object.entries(r).reduce((e,[t,r])=>(e[t]=r&&"object"==typeof r&&e[t]?{...e[t],...r}:r,e),{...t}))}assertCapabilityForMethod(e){var t,r,s;switch(e){case"sampling/createMessage":if(!(null===(t=this._clientCapabilities)||void 0===t?void 0:t.sampling))throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!(null===(r=this._clientCapabilities)||void 0===r?void 0:r.elicitation))throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!(null===(s=this._clientCapabilities)||void 0===s?void 0:s.roots))throw new Error(`Client does not support listing roots (required for ${e})`)}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`)}}assertRequestHandlerCapability(e){switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Server does not support sampling (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new 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 new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`)}}async _oninitialize(e){const t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:Je.includes(t)?t:ze,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"},ut)}async createMessage(e,t){return this.request({method:"sampling/createMessage",params:e},gr,t)}async elicitInput(e,t){const r=await this.request({method:"elicitation/create",params:e},yr,t);if("accept"===r.action&&r.content)try{const t=new xr,s=t.compile(e.requestedSchema);if(!s(r.content))throw new Cr(ct.InvalidParams,`Elicitation response content does not match requested schema: ${t.errorsText(s.errors)}`)}catch(e){if(e instanceof Cr)throw e;throw new Cr(ct.InternalError,`Error validating elicitation response: ${e}`)}return r}async listRoots(e,t){return this.request({method:"roots/list",params:e},Ir,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"})}}const Rr=require("crypto"),$r=require("node:crypto"),jr=require("node:buffer");const Nr=e=>jr.Buffer.from(e).toString("base64url"),Mr=require("node:util");class Fr extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(e,t){super(e,t),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}}class Kr extends Fr{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"}class qr extends Fr{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"}class Lr extends Fr{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"}Symbol.asyncIterator;const Ur=$r.webcrypto,Vr=e=>Mr.types.isCryptoKey(e),Hr=e=>Mr.types.isKeyObject(e);function Br(e,t,...r){if((r=r.filter(Boolean)).length>2){const t=r.pop();e+=`one of type ${r.join(", ")}, or ${t}.`}else 2===r.length?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return null==t?e+=` Received ${t}`:"function"==typeof t&&t.name?e+=` Received function ${t.name}`:"object"==typeof t&&null!=t&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}const zr=(e,...t)=>Br("Key must be ",e,...t);function Jr(e,t,...r){return Br(`Key for the ${e} algorithm must be `,t,...r)}const Wr=e=>Hr(e)||Vr(e),Zr=["KeyObject"];function Qr(e){if("object"!=typeof(t=e)||null===t||"[object Object]"!==Object.prototype.toString.call(e))return!1;var t;if(null===Object.getPrototypeOf(e))return!0;let r=e;for(;null!==Object.getPrototypeOf(r);)r=Object.getPrototypeOf(r);return Object.getPrototypeOf(e)===r}function Gr(e){return Qr(e)&&"string"==typeof e.kty}(globalThis.CryptoKey||Ur?.CryptoKey)&&Zr.push("CryptoKey"),new WeakMap;const Yr=(e,t)=>{let r;if(Vr(e))r=$r.KeyObject.from(e);else{if(!Hr(e)){if(Gr(e))return e.crv;throw new TypeError(zr(e,...Zr))}r=e}if("secret"===r.type)throw new TypeError('only "private" or "public" type keys can be used for this operation');switch(r.asymmetricKeyType){case"ed25519":case"ed448":return`Ed${r.asymmetricKeyType.slice(2)}`;case"x25519":case"x448":return`X${r.asymmetricKeyType.slice(1)}`;case"ec":{const e=r.asymmetricKeyDetails.namedCurve;return t?e:(e=>{switch(e){case"prime256v1":return"P-256";case"secp384r1":return"P-384";case"secp521r1":return"P-521";case"secp256k1":return"secp256k1";default:throw new Kr("Unsupported key curve for this operation")}})(e)}default:throw new TypeError("Invalid asymmetric key type for this operation")}},Xr=(e,t)=>{let r;try{r=e instanceof $r.KeyObject?e.asymmetricKeyDetails?.modulusLength:Buffer.from(e.n,"base64url").byteLength<<3}catch{}if("number"!=typeof r||r<2048)throw new TypeError(`${t} requires key modulusLength to be 2048 bits or larger`)},es=new Map([["ES256","P-256"],["ES256K","secp256k1"],["ES384","P-384"],["ES512","P-521"]]);function ts(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function rs(e,t){return e.name===t}function ss(e){return parseInt(e.name.slice(4),10)}function is(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!rs(e.algorithm,"HMAC"))throw ts("HMAC");const r=parseInt(t.slice(2),10);if(ss(e.algorithm.hash)!==r)throw ts(`SHA-${r}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!rs(e.algorithm,"RSASSA-PKCS1-v1_5"))throw ts("RSASSA-PKCS1-v1_5");const r=parseInt(t.slice(2),10);if(ss(e.algorithm.hash)!==r)throw ts(`SHA-${r}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!rs(e.algorithm,"RSA-PSS"))throw ts("RSA-PSS");const r=parseInt(t.slice(2),10);if(ss(e.algorithm.hash)!==r)throw ts(`SHA-${r}`,"algorithm.hash");break}case"EdDSA":if("Ed25519"!==e.algorithm.name&&"Ed448"!==e.algorithm.name)throw ts("Ed25519 or Ed448");break;case"Ed25519":if(!rs(e.algorithm,"Ed25519"))throw ts("Ed25519");break;case"ES256":case"ES384":case"ES512":{if(!rs(e.algorithm,"ECDSA"))throw ts("ECDSA");const r=function(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}(t);if(e.algorithm.namedCurve!==r)throw ts(r,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}!function(e,t){if(t.length&&!t.some(t=>e.usages.includes(t))){let e="CryptoKey does not support this operation, its usages must include ";if(t.length>2){const r=t.pop();e+=`one of ${t.join(", ")}, or ${r}.`}else 2===t.length?e+=`one of ${t[0]} or ${t[1]}.`:e+=`${t[0]}.`;throw new TypeError(e)}}(e,r)}const as=(0,Mr.promisify)($r.sign),os=new TextEncoder,ns=new TextDecoder;const cs=e=>e?.[Symbol.toStringTag],ds=(e,t,r)=>{if(void 0!==t.use&&"sig"!==t.use)throw new TypeError("Invalid key for this operation, when present its use must be sig");if(void 0!==t.key_ops&&!0!==t.key_ops.includes?.(r))throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${r}`);if(void 0!==t.alg&&t.alg!==e)throw new TypeError(`Invalid key for this operation, when present its alg must be ${e}`);return!0};function ls(e,t,r,s){t.startsWith("HS")||"dir"===t||t.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(t)?((e,t,r,s)=>{if(!(t instanceof Uint8Array)){if(s&&Gr(t)){if(function(e){return Gr(e)&&"oct"===e.kty&&"string"==typeof e.k}(t)&&ds(e,t,r))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!Wr(t))throw new TypeError(Jr(e,t,...Zr,"Uint8Array",s?"JSON Web Key":null));if("secret"!==t.type)throw new TypeError(`${cs(t)} instances for symmetric algorithms must be of type "secret"`)}})(t,r,s,e):((e,t,r,s)=>{if(s&&Gr(t))switch(r){case"sign":if(function(e){return"oct"!==e.kty&&"string"==typeof e.d}(t)&&ds(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(function(e){return"oct"!==e.kty&&void 0===e.d}(t)&&ds(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!Wr(t))throw new TypeError(Jr(e,t,...Zr,s?"JSON Web Key":null));if("secret"===t.type)throw new TypeError(`${cs(t)} instances for asymmetric algorithms must not be of type "secret"`);if("sign"===r&&"public"===t.type)throw new TypeError(`${cs(t)} instances for asymmetric algorithm signing must be of type "private"`);if("decrypt"===r&&"public"===t.type)throw new TypeError(`${cs(t)} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&"verify"===r&&"private"===t.type)throw new TypeError(`${cs(t)} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&"encrypt"===r&&"private"===t.type)throw new TypeError(`${cs(t)} instances for asymmetric algorithm encryption must be of type "public"`)})(t,r,s,e)}ls.bind(void 0,!1);const us=ls.bind(void 0,!0);class hs{_payload;_protectedHeader;_unprotectedHeader;constructor(e){if(!(e instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this._payload=e}setProtectedHeader(e){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=e,this}setUnprotectedHeader(e){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=e,this}async sign(e,t){if(!this._protectedHeader&&!this._unprotectedHeader)throw new qr("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!((...e)=>{const t=e.filter(Boolean);if(0===t.length||1===t.length)return!0;let r;for(const e of t){const t=Object.keys(e);if(r&&0!==r.size)for(const e of t){if(r.has(e))return!1;r.add(e)}else r=new Set(t)}return!0})(this._protectedHeader,this._unprotectedHeader))throw new qr("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const r={...this._protectedHeader,...this._unprotectedHeader};let s=!0;if(function(e,t,r,s,i){if(void 0!==i.crit&&void 0===s?.crit)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!s||void 0===s.crit)return new Set;if(!Array.isArray(s.crit)||0===s.crit.length||s.crit.some(e=>"string"!=typeof e||0===e.length))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let a;a=void 0!==r?new Map([...Object.entries(r),...t.entries()]):t;for(const t of s.crit){if(!a.has(t))throw new Kr(`Extension Header Parameter "${t}" is not recognized`);if(void 0===i[t])throw new e(`Extension Header Parameter "${t}" is missing`);if(a.get(t)&&void 0===s[t])throw new e(`Extension Header Parameter "${t}" MUST be integrity protected`)}return new Set(s.crit)}(qr,new Map([["b64",!0]]),t?.crit,this._protectedHeader,r).has("b64")&&(s=this._protectedHeader.b64,"boolean"!=typeof s))throw new qr('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:i}=r;if("string"!=typeof i||!i)throw new qr('JWS "alg" (Algorithm) Header Parameter missing or invalid');us(i,e,"sign");let a,o=this._payload;s&&(o=os.encode(Nr(o))),a=this._protectedHeader?os.encode(Nr(JSON.stringify(this._protectedHeader))):os.encode("");const n=function(...e){const t=e.reduce((e,{length:t})=>e+t,0),r=new Uint8Array(t);let s=0;for(const t of e)r.set(t,s),s+=t.length;return r}(a,os.encode("."),o),c=await(async(e,t,r)=>{const s=function(e,t){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(zr(t,...Zr));return(0,$r.createSecretKey)(t)}if(t instanceof $r.KeyObject)return t;if(Vr(t))return is(t,e,"sign"),$r.KeyObject.from(t);if(Gr(t))return e.startsWith("HS")?(0,$r.createSecretKey)(Buffer.from(t.k,"base64url")):t;throw new TypeError(zr(t,...Zr,"Uint8Array","JSON Web Key"))}(e,t);if(e.startsWith("HS")){const t=$r.createHmac(function(e){switch(e){case"HS256":return"sha256";case"HS384":return"sha384";case"HS512":return"sha512";default:throw new Kr(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}(e),s);return t.update(r),t.digest()}return as(function(e){switch(e){case"PS256":case"RS256":case"ES256":case"ES256K":return"sha256";case"PS384":case"RS384":case"ES384":return"sha384";case"PS512":case"RS512":case"ES512":return"sha512";case"Ed25519":case"EdDSA":return;default:throw new Kr(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}(e),r,function(e,t){let r,s,i,a;if(t instanceof $r.KeyObject)r=t.asymmetricKeyType,s=t.asymmetricKeyDetails;else switch(i=!0,t.kty){case"RSA":r="rsa";break;case"EC":r="ec";break;case"OKP":if("Ed25519"===t.crv){r="ed25519";break}if("Ed448"===t.crv){r="ed448";break}throw new TypeError("Invalid key for this operation, its crv must be Ed25519 or Ed448");default:throw new TypeError("Invalid key for this operation, its kty must be RSA, OKP, or EC")}switch(e){case"Ed25519":if("ed25519"!==r)throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ed25519");break;case"EdDSA":if(!["ed25519","ed448"].includes(r))throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ed25519 or ed448");break;case"RS256":case"RS384":case"RS512":if("rsa"!==r)throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa");Xr(t,e);break;case"PS256":case"PS384":case"PS512":if("rsa-pss"===r){const{hashAlgorithm:t,mgf1HashAlgorithm:r,saltLength:i}=s,a=parseInt(e.slice(-3),10);if(void 0!==t&&(t!==`sha${a}`||r!==t))throw new TypeError(`Invalid key for this operation, its RSA-PSS parameters do not meet the requirements of "alg" ${e}`);if(void 0!==i&&i>a>>3)throw new TypeError(`Invalid key for this operation, its RSA-PSS parameter saltLength does not meet the requirements of "alg" ${e}`)}else if("rsa"!==r)throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa or rsa-pss");Xr(t,e),a={padding:$r.constants.RSA_PKCS1_PSS_PADDING,saltLength:$r.constants.RSA_PSS_SALTLEN_DIGEST};break;case"ES256":case"ES256K":case"ES384":case"ES512":{if("ec"!==r)throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ec");const s=Yr(t),i=es.get(e);if(s!==i)throw new TypeError(`Invalid key curve for the algorithm, its curve must be ${i}, got ${s}`);a={dsaEncoding:"ieee-p1363"};break}default:throw new Kr(`alg ${e} is not supported either by JOSE or your javascript runtime`)}return i?{format:"jwk",key:t,...a}:a?{...a,key:t}:t}(e,s))})(i,e,n),d={signature:Nr(c),payload:""};return s&&(d.payload=ns.decode(o)),this._unprotectedHeader&&(d.header=this._unprotectedHeader),this._protectedHeader&&(d.protected=ns.decode(a)),d}}class ps{_flattened;constructor(e){this._flattened=new hs(e)}setProtectedHeader(e){return this._flattened.setProtectedHeader(e),this}async sign(e,t){const r=await this._flattened.sign(e,t);if(void 0===r.payload)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${r.protected}.${r.payload}.${r.signature}`}}const fs=e=>Math.floor(e.getTime()/1e3),gs=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,ms=e=>{const t=gs.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");const r=parseFloat(t[2]);let s;switch(t[3].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":s=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":s=Math.round(60*r);break;case"hour":case"hours":case"hr":case"hrs":case"h":s=Math.round(3600*r);break;case"day":case"days":case"d":s=Math.round(86400*r);break;case"week":case"weeks":case"w":s=Math.round(604800*r);break;default:s=Math.round(31557600*r)}return"-"===t[1]||"ago"===t[4]?-s:s};function vs(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}class ys{_payload;constructor(e={}){if(!Qr(e))throw new TypeError("JWT Claims Set MUST be an object");this._payload=e}setIssuer(e){return this._payload={...this._payload,iss:e},this}setSubject(e){return this._payload={...this._payload,sub:e},this}setAudience(e){return this._payload={...this._payload,aud:e},this}setJti(e){return this._payload={...this._payload,jti:e},this}setNotBefore(e){return"number"==typeof e?this._payload={...this._payload,nbf:vs("setNotBefore",e)}:e instanceof Date?this._payload={...this._payload,nbf:vs("setNotBefore",fs(e))}:this._payload={...this._payload,nbf:fs(new Date)+ms(e)},this}setExpirationTime(e){return"number"==typeof e?this._payload={...this._payload,exp:vs("setExpirationTime",e)}:e instanceof Date?this._payload={...this._payload,exp:vs("setExpirationTime",fs(e))}:this._payload={...this._payload,exp:fs(new Date)+ms(e)},this}setIssuedAt(e){return void 0===e?this._payload={...this._payload,iat:fs(new Date)}:e instanceof Date?this._payload={...this._payload,iat:vs("setIssuedAt",fs(e))}:this._payload="string"==typeof e?{...this._payload,iat:vs("setIssuedAt",fs(new Date)+ms(e))}:{...this._payload,iat:vs("setIssuedAt",e)},this}}class _s extends ys{_protectedHeader;setProtectedHeader(e){return this._protectedHeader=e,this}async sign(e,t){const r=new ps(os.encode(JSON.stringify(this._payload)));if(r.setProtectedHeader(this._protectedHeader),Array.isArray(this._protectedHeader?.crit)&&this._protectedHeader.crit.includes("b64")&&!1===this._protectedHeader.b64)throw new Lr("JWTs MUST NOT use unencoded payload");return r.sign(e,t)}}var ws=r(77753),bs=r(95277);const Ss=require("fs");var Ps=r(16928);class Es extends bs.CryptoProvider{async sign(e,t){const r=Buffer.from(t,"base64"),s=64===r.length?r.subarray(0,32):r,i=Buffer.concat([Buffer.from("302e020100300506032b657004220420","hex"),s]),a=Rr.createPrivateKey({key:i,format:"der",type:"pkcs8"}),o=Rr.sign(null,Buffer.from(e),a);return new Uint8Array(o)}async verify(e,t,r){try{const s=Buffer.from(r,"base64"),i=Buffer.concat([Buffer.from("302a300506032b6570032100","hex"),s]),a=Rr.createPublicKey({key:i,format:"der",type:"spki"});return Rr.verify(null,Buffer.from(e),a,Buffer.from(t))}catch{return!1}}async generateKeyPair(){const{publicKey:e,privateKey:t}=Rr.generateKeyPairSync("ed25519",{publicKeyEncoding:{type:"spki",format:"der"},privateKeyEncoding:{type:"pkcs8",format:"der"}}),r=t.subarray(16,48),s=e.subarray(12,44);return{privateKey:r.toString("base64"),publicKey:s.toString("base64")}}async hash(e){const t=Rr.createHash("sha256").update(Buffer.from(e)).digest();return new Uint8Array(t)}async randomBytes(e){return new Uint8Array(Rr.randomBytes(e))}}bs.StorageProvider,bs.IdentityProvider;class Is{async generateProof(e,t,r,s={}){const i=this.generateCanonicalHashes(e,t),a={did:this.identity.did,kid:this.identity.kid,ts:Math.floor(Date.now()/1e3),nonce:r.nonce,audience:r.audience,sessionId:r.sessionId,requestHash:i.requestHash,responseHash:i.responseHash,...s};return{jws:await this.generateJWS(a),meta:a}}generateCanonicalHashes(e,t){const r={method:e.method,...e.params&&{params:e.params}},s=t.data;return{requestHash:this.generateSHA256Hash(r),responseHash:this.generateSHA256Hash(s)}}generateSHA256Hash(e){const t=this.canonicalizeJSON(e);return`sha256:${(0,Rr.createHash)("sha256").update(t,"utf8").digest("hex")}`}canonicalizeJSON(e){return(0,ws.d)(e)}async generateJWS(e){try{const t=this.formatPrivateKeyAsPEM(this.identity.privateKey),r=await async function(e){if("string"!=typeof e||0!==e.indexOf("-----BEGIN PRIVATE KEY-----"))throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return t=e,(0,$r.createPrivateKey)({key:jr.Buffer.from(t.replace(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g,""),"base64"),type:"pkcs8",format:"der"});var t}(t),s={aud:e.audience,sub:e.did,iss:e.did,requestHash:e.requestHash,responseHash:e.responseHash,ts:e.ts,nonce:e.nonce,sessionId:e.sessionId,...e.scopeId&&{scopeId:e.scopeId},...e.delegationRef&&{delegationRef:e.delegationRef},...e.clientDid&&{clientDid:e.clientDid}};return await new _s(s).setProtectedHeader({alg:"EdDSA",kid:this.identity.kid}).sign(r)}catch(e){throw new Error(`Failed to generate JWS: ${e instanceof Error?e.message:"Unknown error"}`)}}formatPrivateKeyAsPEM(e){const t=Buffer.from(e,"base64"),r=Buffer.from([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]),s=Buffer.concat([r,t.subarray(0,32)]).toString("base64");return"-----BEGIN PRIVATE KEY-----\n"+(s.match(/.{1,64}/g)?.join("\n")||s)+"\n-----END PRIVATE KEY-----"}async verifyProof(e,t,r){try{const s=this.generateCanonicalHashes(t,r);if(e.meta.requestHash!==s.requestHash||e.meta.responseHash!==s.responseHash)return!1;const i=this.base64PublicKeyToJWK(this.identity.publicKey),a=new Es,o=new bs.CryptoService(a);return await o.verifyJWS(e.jws,i,{expectedKid:this.identity.kid,alg:"EdDSA"})}catch(e){return console.error("[ProofGenerator] Proof verification error:",e),!1}}base64PublicKeyToJWK(e){const t=Buffer.from(e,"base64");if(32!==t.length)throw new Error(`Invalid Ed25519 public key length: ${t.length}`);return{kty:"OKP",crv:"Ed25519",x:Buffer.from(t).toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,""),kid:this.identity.kid}}constructor(e){var t,r;r=void 0,(t="identity")in this?Object.defineProperty(this,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):this[t]=r,this.identity=e}}const ks=require("fs/promises"),Cs=(0,Mr.promisify)($r.generateKeyPair);function Ds(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}r(75306);class Os{async ensureIdentity(){return this.cachedIdentity||("development"===this.config.environment?this.cachedIdentity=await this.loadOrGenerateDevIdentity():this.cachedIdentity=await this.loadProdIdentity()),this.cachedIdentity}async loadOrGenerateDevIdentity(){const e=this.config.devIdentityPath;try{if((0,Ss.existsSync)(e)){const t=await(0,ks.readFile)(e,"utf-8"),r=JSON.parse(t);let s=r.kid||r.keyId;if(r.keyId&&!r.kid&&s.startsWith("key-")){s=this.generateMultibaseKid(r.publicKey);const e={did:r.did,kid:s,privateKey:r.privateKey,publicKey:r.publicKey,createdAt:r.createdAt,lastRotated:r.lastRotated};return await this.saveDevIdentity(e),console.error(`✅ Migrated identity to new multibase kid format: ${s}`),e}return{did:r.did,kid:s,privateKey:r.privateKey,publicKey:r.publicKey,createdAt:r.createdAt,lastRotated:r.lastRotated}}}catch(t){console.warn(`Warning: Could not load identity from ${e}, generating new one`,t instanceof Error?t.message:t)}return await this.generateDevIdentity()}async generateDevIdentity(){const e=await async function(e,t){return async function(e,t){switch(e){case"RS256":case"RS384":case"RS512":case"PS256":case"PS384":case"PS512":case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":case"RSA1_5":{const e=t?.modulusLength??2048;if("number"!=typeof e||e<2048)throw new Kr("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return await Cs("rsa",{modulusLength:e,publicExponent:65537})}case"ES256":return Cs("ec",{namedCurve:"P-256"});case"ES256K":return Cs("ec",{namedCurve:"secp256k1"});case"ES384":return Cs("ec",{namedCurve:"P-384"});case"ES512":return Cs("ec",{namedCurve:"P-521"});case"Ed25519":return Cs("ed25519");case"EdDSA":switch(t?.crv){case void 0:case"Ed25519":return Cs("ed25519");case"Ed448":return Cs("ed448");default:throw new Kr("Invalid or unsupported crv option provided, supported values are Ed25519 and Ed448")}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{const e=t?.crv??"P-256";switch(e){case void 0:case"P-256":case"P-384":case"P-521":return Cs("ec",{namedCurve:e});case"X25519":return Cs("x25519");case"X448":return Cs("x448");default:throw new Kr("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448")}}default:throw new Kr('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}}(e,t)}("EdDSA",{crv:"Ed25519"}),t=await async function(e){return(e=>{let t;if(Vr(e)){if(!e.extractable)throw new TypeError("CryptoKey is not extractable");t=$r.KeyObject.from(e)}else{if(!Hr(e)){if(e instanceof Uint8Array)return{kty:"oct",k:Nr(e)};throw new TypeError(zr(e,...Zr,"Uint8Array"))}t=e}if("secret"!==t.type&&!["rsa","ec","ed25519","x25519","ed448","x448"].includes(t.asymmetricKeyType))throw new Kr("Unsupported key asymmetricKeyType");return t.export({format:"jwk"})})(e)}(e.privateKey);if(!t.x||!t.d)throw new Error("Failed to generate Ed25519 keypair");const r=Buffer.from(t.d,"base64url").toString("base64"),s=Buffer.from(t.x,"base64url").toString("base64"),i=this.generateMultibaseKid(s),a={did:`did:web:localhost:3000:agents:${(0,Rr.createHash)("sha256").update(s).digest("hex").substring(0,8)}`,kid:i,privateKey:r,publicKey:s,createdAt:(new Date).toISOString()};return await this.saveDevIdentity(a),a}generateMultibaseKid(e){const t=Buffer.from(e,"base64"),r=Buffer.concat([Buffer.from([237,1]),t]);return`z${this.encodeBase58(r)}`}encodeBase58(e){let t=BigInt("0x"+e.toString("hex")),r="";for(;t>0n;)r="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"[Number(t%58n)]+r,t/=58n;for(let t=0;t<e.length&&0===e[t];t++)r="1"+r;return r}async saveDevIdentity(e){const t=this.config.devIdentityPath;await(0,ks.mkdir)((0,Ps.dirname)(t),{recursive:!0});const r={version:"1.0",did:e.did,kid:e.kid,privateKey:e.privateKey,publicKey:e.publicKey,createdAt:e.createdAt,lastRotated:e.lastRotated};await(0,ks.writeFile)(t,JSON.stringify(r,null,2),{mode:384}),console.error(`✅ Identity saved to ${t}`),console.error(` DID: ${e.did}`),console.error(` Key ID: ${e.kid}`)}async loadProdIdentity(){const e=["AGENT_PRIVATE_KEY","AGENT_KEY_ID","AGENT_DID","KYA_VOUCHED_API_KEY"],t=[],r={};for(const s of e){const e=process.env[s];e?r[s]=e:t.push(s)}if(t.length>0){const e=new Error(`Missing required environment variables for production identity: ${t.join(", ")}\nRequired variables:\n AGENT_PRIVATE_KEY - Base64-encoded Ed25519 private key\n AGENT_KEY_ID - Key identifier\n AGENT_DID - Agent DID\n KYA_VOUCHED_API_KEY - Know-That-AI API key`);throw e.code="XMCP_I_ENOIDENTITY",e}const s=Buffer.from(r.AGENT_PRIVATE_KEY,"base64"),i=(0,Rr.createHash)("sha256").update(s).digest("base64");return{did:r.AGENT_DID,kid:r.AGENT_KEY_ID,privateKey:r.AGENT_PRIVATE_KEY,publicKey:i,createdAt:(new Date).toISOString()}}async validateIdentity(e){try{return!!(e.did&&e.kid&&e.privateKey&&e.publicKey)&&!!e.did.startsWith("did:")&&(Buffer.from(e.privateKey,"base64"),Buffer.from(e.publicKey,"base64"),!0)}catch{return!1}}clearCache(){this.cachedIdentity=void 0}getConfig(){return{...this.config}}constructor(e={environment:"development"}){Ds(this,"config",void 0),Ds(this,"cachedIdentity",void 0);const t=r(16928);let s=e.devIdentityPath||".mcpi/identity.json";t.isAbsolute(s)||(s=t.resolve(process.cwd(),s)),this.config={privacyMode:!1,...e,devIdentityPath:s},this.config.debug&&console.error("[IdentityManager] Constructed with config:",{environment:this.config.environment,devIdentityPath:this.config.devIdentityPath})}}function As(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}new Os;const xs=new class{register(e,t){this.config.set(e,t),this.debug&&console.error(`[ToolProtectionRegistry] Registered protection for tool: ${e}`,t)}registerAll(e){for(const[t,r]of Object.entries(e))this.register(t,r)}get(e){return this.config.get(e)||null}requiresDelegation(e){const t=this.get(e);return t?.requiresDelegation||!1}getRequiredScopes(e){const t=this.get(e);return t?.requiredScopes||[]}setDelegationVerifier(e){this.delegationVerifier=e}setAuthConfig(e){this.authConfig=e}getDelegationVerifier(){return this.delegationVerifier}getAuthConfig(){return this.authConfig}setDebug(e){this.debug=e}setCurrentSession(e){this.currentSession=e}getCurrentSession(){return this.currentSession}getCurrentAgentDid(){return this.currentSession?.agentDid||null}clear(){this.config.clear(),this.delegationVerifier=null,this.authConfig=null,this.currentSession=null}getProtectedTools(){return Array.from(this.config.keys())}constructor(){As(this,"config",new Map),As(this,"delegationVerifier",null),As(this,"authConfig",null),As(this,"debug",!1),As(this,"currentSession",null)}},Ts=require("@kya-os/contracts/runtime");async function Rs(e,t,r,s){const i=await r.resumeTokenStore.create(e,t,{requestedAt:Date.now()}),a=Date.now()+(r.bouncer.resumeTokenTtl||6e5),o=new URL(r.bouncer.authorizationUrl);o.searchParams.set("agent_did",e),o.searchParams.set("scopes",t.join(",")),o.searchParams.set("resume_token",i);const n={title:"Authorization Required",hint:["link","qr"],authorizationCode:i.substring(0,8).toUpperCase(),qrUrl:`https://chart.googleapis.com/chart?cht=qr&chs=300x300&chl=${encodeURIComponent(o.toString())}`};return(0,Ts.createNeedsAuthorizationError)({message:s,authorizationUrl:o.toString(),resumeToken:i,expiresAt:a,scopes:t,display:n})}function $s(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}class js{async has(e,t){const r=t?`nonce:${t}:${e}`:e,s=this.cache.get(r);return!(!s||Date.now()>s.expiresAt&&(this.cache.delete(r),1))}async add(e,t,r){const s=r?`nonce:${r}:${e}`:e,i=this.cache.get(s);if(i&&Date.now()<=i.expiresAt)throw new Error(`Nonce ${e} already exists - potential replay attack`);const a=t<=0?Date.now()-1:Date.now()+1e3*t,o={sessionId:`mem_${Date.now()}_${Math.random().toString(36).substring(2)}`,expiresAt:a};this.cache.set(s,o)}async cleanup(){const e=Date.now(),t=[];for(const[r,s]of this.cache.entries())e>s.expiresAt&&t.push(r);for(const e of t)this.cache.delete(e)}getStats(){const e=Date.now();let t=0;for(const r of this.cache.values())e>r.expiresAt&&t++;return{size:this.cache.size,expired:t}}clear(){this.cache.clear()}destroy(){this.cleanupInterval&&(clearInterval(this.cleanupInterval),this.cleanupInterval=void 0),this.cache.clear()}constructor(e=6e4){$s(this,"cache",new Map),$s(this,"cleanupInterval",void 0),console.warn("⚠️ MemoryNonceCache is not suitable for multi-instance deployments. For production use with multiple instances, configure Redis, DynamoDB, or Cloudflare KV."),this.cleanupInterval=setInterval(()=>{this.cleanup().catch(console.error)},e)}}function Ns(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}class Ms{setServerDid(e){this.config.serverDid=e}async validateHandshake(e){try{const t=Math.floor(Date.now()/1e3),r=Math.abs(t-e.timestamp);if(r>this.config.timestampSkewSeconds)return{success:!1,error:{code:"XMCP_I_EHANDSHAKE",message:`Timestamp outside acceptable range (±${this.config.timestampSkewSeconds}s)`,remediation:`Check NTP sync on client and server. Current server time: ${t}, received: ${e.timestamp}, diff: ${r}s. Adjust XMCP_I_TS_SKEW_SEC if needed.`}};if(await this.config.nonceCache.has(e.nonce,e.agentDid))return{success:!1,error:{code:"XMCP_I_EHANDSHAKE",message:"Nonce already used (replay attack prevention)",remediation:"Generate a new unique nonce for each request"}};const s=60*this.config.sessionTtlMinutes+60;await this.config.nonceCache.add(e.nonce,s,e.agentDid);const i=this.generateSessionId(),a=this.buildClientInfo(e),o={sessionId:i,audience:e.audience,nonce:e.nonce,timestamp:e.timestamp,createdAt:t,lastActivity:t,ttlMinutes:this.config.sessionTtlMinutes,agentDid:e.agentDid,...this.config.serverDid&&{serverDid:this.config.serverDid},...a&&{clientInfo:a}};return this.sessions.set(i,o),{success:!0,session:o}}catch(e){return{success:!1,error:{code:"XMCP_I_EHANDSHAKE",message:`Handshake validation failed: ${e instanceof Error?e.message:"Unknown error"}`}}}}async getSession(e){const t=this.sessions.get(e);if(!t)return null;const r=Math.floor(Date.now()/1e3);return r-t.lastActivity>60*t.ttlMinutes||this.config.absoluteSessionLifetime&&r-t.createdAt>60*this.config.absoluteSessionLifetime?(this.sessions.delete(e),null):(t.lastActivity=r,this.sessions.set(e,t),t)}generateSessionId(){return`sess_${Date.now().toString(36)}_${(0,Rr.randomBytes)(8).toString("hex")}`}generateClientId(){return`client_${(0,Rr.randomBytes)(6).toString("hex")}`}normalizeClientInfoString(e){if("string"!=typeof e)return;const t=e.trim();return t.length>0?t:void 0}buildClientInfo(e){if(!e.clientInfo&&"string"!=typeof e.clientProtocolVersion&&void 0===e.clientCapabilities)return;const t=e.clientInfo;return{name:this.normalizeClientInfoString(t?.name)??"unknown",title:this.normalizeClientInfoString(t?.title),version:this.normalizeClientInfoString(t?.version),platform:this.normalizeClientInfoString(t?.platform),vendor:this.normalizeClientInfoString(t?.vendor),persistentId:this.normalizeClientInfoString(t?.persistentId),clientId:this.normalizeClientInfoString(t?.clientId)??this.generateClientId(),protocolVersion:this.normalizeClientInfoString(e.clientProtocolVersion),capabilities:e.clientCapabilities}}static generateNonce(){return(0,Rr.randomBytes)(16).toString("base64url")}async cleanup(){const e=Math.floor(Date.now()/1e3);for(const[t,r]of this.sessions.entries()){let s=e-r.lastActivity>60*r.ttlMinutes;!s&&this.config.absoluteSessionLifetime&&(s=e-r.createdAt>60*this.config.absoluteSessionLifetime),s&&this.sessions.delete(t)}await this.config.nonceCache.cleanup()}getStats(){return{activeSessions:this.sessions.size,config:{timestampSkewSeconds:this.config.timestampSkewSeconds,sessionTtlMinutes:this.config.sessionTtlMinutes,absoluteSessionLifetime:this.config.absoluteSessionLifetime,cacheType:this.config.nonceCache.constructor.name}}}clearSessions(){this.sessions.clear()}constructor(e={}){Ns(this,"config",void 0),Ns(this,"sessions",new Map),this.config={timestampSkewSeconds:parseInt(process.env.XMCP_I_TS_SKEW_SEC||"120"),sessionTtlMinutes:parseInt(process.env.XMCP_I_SESSION_TTL_MIN||"30"),nonceCache:new js,...e},this.config.nonceCache instanceof js&&console.warn("Warning: Using MemoryNonceCache - not suitable for multi-instance deployments. Consider using Redis, DynamoDB, or Cloudflare KV for production.")}}new Ms;const Fs=new(require("async_hooks").AsyncLocalStorage);function Ks(){return(Fs.getStore()?.session)?.agentDid}function qs(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}class Ls{async submit(e){if(0===e.length)return;const t={delegation_id:null,session_id:e[0]?.meta?.sessionId||"unknown",proofs:e},r=await fetch(`${this.apiUrl}/api/v1/bouncer/proofs`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(t)});if(!r.ok){const e=await r.text().catch(()=>"Unable to read error body");throw new Error(`AgentShield proof submission failed: ${r.status} ${r.statusText}\n${e}`)}}constructor(e,t){qs(this,"name","AgentShield"),qs(this,"apiUrl",void 0),qs(this,"apiKey",void 0),this.apiUrl=e.replace(/\/$/,""),this.apiKey=t}}class Us{enqueue(e){this.closed?console.warn("[ProofBatchQueue] Queue is closed, dropping proof"):(this.queue.push(e),this.stats.queued++,this.config.debug&&console.log(`[ProofBatchQueue] Enqueued proof (queue size: ${this.queue.length})`),this.queue.length>=this.config.maxBatchSize&&this.flush())}async flush(){if(0===this.queue.length)return;const e=this.queue.splice(0,this.config.maxBatchSize);this.config.debug&&console.log(`[ProofBatchQueue] Flushing ${e.length} proofs to ${this.config.destinations.length} destinations`);for(const t of this.config.destinations){const r={proofs:e,destination:t,retryCount:0};this.submitBatch(r)}}async submitBatch(e){try{await e.destination.submit(e.proofs),this.stats.submitted+=e.proofs.length,this.stats.batchesSubmitted++,this.config.debug&&console.log(`[ProofBatchQueue] Successfully submitted ${e.proofs.length} proofs to ${e.destination.name}`)}catch(t){if(console.error(`[ProofBatchQueue] Failed to submit to ${e.destination.name}:`,t),e.retryCount<this.config.maxRetries){e.retryCount++;const t=Math.min(1e3*Math.pow(2,e.retryCount-1),16e3);e.nextRetryAt=Date.now()+t,this.pendingBatches.push(e),this.config.debug&&console.log(`[ProofBatchQueue] Scheduling retry ${e.retryCount}/${this.config.maxRetries} in ${t}ms`)}else this.stats.failed+=e.proofs.length,console.error(`[ProofBatchQueue] Max retries exceeded for ${e.destination.name}, dropping ${e.proofs.length} proofs`)}}startFlushTimer(){this.flushTimer=setInterval(()=>{this.queue.length>0&&this.flush()},this.config.flushIntervalMs),"function"==typeof this.flushTimer.unref&&this.flushTimer.unref()}startRetryTimer(){this.retryTimer=setInterval(()=>{const e=Date.now(),t=this.pendingBatches.filter(t=>t.nextRetryAt&&t.nextRetryAt<=e);if(t.length>0){this.pendingBatches=this.pendingBatches.filter(e=>!t.includes(e));for(const e of t)this.submitBatch(e)}},1e3),"function"==typeof this.retryTimer.unref&&this.retryTimer.unref()}async close(){this.closed=!0,this.flushTimer&&clearInterval(this.flushTimer),this.retryTimer&&clearInterval(this.retryTimer),await this.flush();const e=Date.now();for(;this.pendingBatches.length>0&&Date.now()-e<3e4;)await new Promise(e=>setTimeout(e,100));this.pendingBatches.length>0&&console.warn(`[ProofBatchQueue] Closing with ${this.pendingBatches.length} pending batches (timed out)`)}getStats(){return{...this.stats,queueSize:this.queue.length,pendingBatches:this.pendingBatches.length}}constructor(e){qs(this,"queue",[]),qs(this,"pendingBatches",[]),qs(this,"config",void 0),qs(this,"flushTimer",void 0),qs(this,"retryTimer",void 0),qs(this,"closed",!1),qs(this,"stats",{queued:0,submitted:0,failed:0,batchesSubmitted:0}),this.config={destinations:e.destinations,maxBatchSize:e.maxBatchSize||10,flushIntervalMs:e.flushIntervalMs||5e3,maxRetries:e.maxRetries||5,debug:e.debug||!1},this.startFlushTimer(),this.startRetryTimer()}}const Vs="undefined"!=typeof RUNTIME_CONFIG_PATH?RUNTIME_CONFIG_PATH:void 0,Hs=Vs?"string"==typeof Vs?JSON.parse(Vs):Vs:null;let Bs=null;async function zs(e,t,s){if("undefined"!=typeof global){if(global.__MCPI_HANDLERS_REGISTERED__)return s?.debug&&console.error("[MCPI] Handlers already registered, skipping duplicate registration"),e;global.__MCPI_HANDLERS_REGISTERED__=!0}s?.debug&&console.error("[MCPI] Registering handlers for the first time");const i=new Ms;let a=null;if(s?.enabled)try{a=new Os({environment:s.environment||"development",devIdentityPath:s.devIdentityPath,debug:s.debug});const e=await a.ensureIdentity();s.debug&&(console.error(`[MCPI] Identity enabled - DID: ${e.did}`),console.error(`[MCPI] Identity path: ${s.devIdentityPath||".mcpi/identity.json"}`))}catch(e){s?.debug&&console.error("[MCPI] Failed to initialize identity:",e),a=null}await async function(e){if(Bs)return Bs;if(!Hs)return e&&console.error("[MCPI] No runtime config found - proof submission disabled"),null;try{e&&console.error("[MCPI] Loading runtime config from:",Hs);const t=await r(49436)(Hs),s="function"==typeof t.getRuntimeConfig?t.getRuntimeConfig():t.default;if(!s?.proofing?.enabled)return e&&console.error("[MCPI] Proofing is disabled in runtime config"),null;const i=s.proofing;if(!i.batchQueue?.destinations||0===i.batchQueue.destinations.length)return e&&console.error("[MCPI] No proof destinations configured"),null;const a=[];for(const t of i.batchQueue.destinations)"agentshield"===t.type&&(a.push(new Ls(t.apiUrl,t.apiKey)),e&&console.error(`[MCPI] Added AgentShield destination: ${t.apiUrl}`));return 0===a.length?(e&&console.error("[MCPI] No valid proof destinations configured"),null):(Bs=new Us({destinations:a,maxBatchSize:i.batchQueue.maxBatchSize||10,flushIntervalMs:i.batchQueue.flushIntervalMs||5e3,maxRetries:i.batchQueue.maxRetries||3,debug:i.batchQueue.debug||e}),e&&console.error(`[MCPI] ProofBatchQueue initialized (batch: ${i.batchQueue.maxBatchSize}, flush: ${i.batchQueue.flushIntervalMs}ms, destinations: ${a.length})`),Bs)}catch(t){return e&&console.error("[MCPI] Failed to initialize ProofBatchQueue:",t),null}}(s?.debug);const o=[],n=new Map;if(t.forEach((e,t)=>{const r=function(e){return(e.split("/").pop()||e).replace(/\.[^/.]+$/,"")}(t),s={name:r,description:"No description provided"};let i={};const{default:a,metadata:c,schema:d}=e;"object"==typeof c&&null!==c&&Object.assign(s,c),function(e){if("object"!=typeof e||null===e)return!1;const t=e;return Object.entries(t).every(([e,t])=>"string"==typeof e&&"object"==typeof t&&null!==t&&"parse"in t&&"function"==typeof t.parse)}(d)?Object.assign(i,d):null!=d&&console.warn(`Invalid schema for tool "${s.name}" at ${t}. Expected Record<string, z.ZodType>`),void 0===s.annotations&&(s.annotations={}),void 0===s.annotations.title&&(s.annotations.title=s.name);const l={name:s.name,description:s.description,inputSchema:{type:"object",properties:Object.fromEntries(Object.entries(i).map(([e,t])=>[e,{type:"string"}]))}};o.push(l),n.set(s.name,a)}),s?.debug&&console.error("[MCPI] About to register handlers (tools/list, tools/call, handshake)"),a)try{const e=await a.ensureIdentity();i.setServerDid(e.did)}catch(e){s?.debug&&console.error("[MCPI] Failed to set server DID on session manager:",e),a=null}return o.push({name:"_mcpi_handshake",description:"Internal MCP-I handshake tool for session establishment. Clients should call this before protected tools.",inputSchema:{type:"object",properties:{nonce:{type:"string",description:"Unique nonce for replay prevention"},audience:{type:"string",description:"Target audience (server DID or URL)"},timestamp:{type:"number",description:"Unix timestamp in seconds"},agentDid:{type:"string",description:"Agent DID for delegation verification (optional)"},clientInfo:{type:"object",description:"MCP client metadata (optional)",properties:{name:{type:"string"},version:{type:"string"},platform:{type:"string"},vendor:{type:"string"}}},clientProtocolVersion:{type:"string",description:"MCP protocol version (optional)"},clientCapabilities:{type:"object",description:"MCP client capabilities (optional)",additionalProperties:!0}},required:["nonce","audience","timestamp"]}}),n.set("_mcpi_handshake",async e=>{const t=[];if((!e.nonce||"string"==typeof e.nonce&&0===e.nonce.trim().length)&&t.push("nonce"),(!e.audience||"string"==typeof e.audience&&0===e.audience.trim().length)&&t.push("audience"),void 0===e.timestamp||null===e.timestamp||"number"!=typeof e.timestamp||e.timestamp<=0||!Number.isInteger(e.timestamp)){if(void 0!==e.timestamp&&null!==e.timestamp)return{success:!1,error:{code:"XMCP_I_EHANDSHAKE",message:"Invalid timestamp: must be a positive integer (Unix timestamp in seconds)",details:{received:typeof e.timestamp,value:e.timestamp}}};t.push("timestamp")}if(t.length>0)return{success:!1,error:{code:"XMCP_I_EHANDSHAKE",message:`Missing required field(s): ${t.join(", ")}`,details:{missingFields:t,requiredFields:["nonce","audience","timestamp"]}}};const r=e.timestamp,a={nonce:String(e.nonce).trim(),audience:String(e.audience).trim(),timestamp:r,agentDid:"string"==typeof e.agentDid&&e.agentDid.trim().length>0?e.agentDid.trim():void 0,clientInfo:"object"==typeof e.clientInfo&&null!==e.clientInfo?e.clientInfo:void 0,clientProtocolVersion:"string"==typeof e.clientProtocolVersion&&e.clientProtocolVersion.trim().length>0?e.clientProtocolVersion.trim():void 0,clientCapabilities:"object"==typeof e.clientCapabilities&&null!==e.clientCapabilities?e.clientCapabilities:void 0};if(!("object"==typeof(o=a)&&null!==o&&"string"==typeof o.nonce&&o.nonce.length>0&&"string"==typeof o.audience&&o.audience.length>0&&"number"==typeof o.timestamp&&o.timestamp>0&&Number.isInteger(o.timestamp)))return{success:!1,error:{code:"XMCP_I_EHANDSHAKE",message:"Invalid handshake request format. Required: nonce, audience, timestamp"}};var o;const n=await i.validateHandshake(a);return s?.debug&&n.success&&n.session?.clientInfo&&console.error("[MCPI] Client connected:",{name:n.session.clientInfo.name,version:n.session.clientInfo.version,platform:n.session.clientInfo.platform,vendor:n.session.clientInfo.vendor,clientId:n.session.clientInfo.clientId}),n.success&&n.session?{success:!0,sessionId:n.session.sessionId,serverDid:n.session.serverDid,ttlMinutes:n.session.ttlMinutes,...n.session.clientInfo&&{clientInfo:n.session.clientInfo}}:{success:!1,error:n.error}}),e.setRequestHandler(sr,async e=>({tools:o})),e.setRequestHandler(or,async e=>{const t=e._meta?.sessionId;let r=null;return t&&(r=await i.getSession(t),!r&&s?.debug&&console.error(`[MCPI] Session not found or expired: ${t}`)),o={session:r||void 0,requestId:e._meta?.requestId,startTime:Date.now()},c=async()=>{const{name:t,arguments:i}=e.params,o=n.get(t);if(!o)return{content:[{type:"text",text:`Tool "${t}" not found`}],isError:!0};const c=xs.get(t);if(c?.requiresDelegation){const e=xs.getAuthConfig();if(!xs.getDelegationVerifier()||!e)return s?.debug&&console.error(`[MCPI] Tool "${t}" requires delegation but verifier not configured`),{content:[{type:"text",text:`❌ Tool "${t}" requires delegation verification, but the delegation system is not configured.\n\nTo fix this:\n1. Configure a delegation verifier:\n - MemoryDelegationVerifier (development/testing)\n - KVDelegationVerifier (production with KV store)\n - AgentShieldVerifier (production with AgentShield service)\n\n2. Enable delegation in your runtime config:\n const runtime = new MCPIRuntime({\n delegation: { enabled: true },\n // ... other config\n });\n\n3. Ensure the verifier is initialized before tool execution.\n\n📚 Documentation: https://docs.mcp-i.dev/delegation/setup`}],isError:!0};const r=Ks();if(!r)return s?.debug&&console.error(`[MCPI] Tool "${t}" requires delegation but no agent DID in session`),{content:[{type:"text",text:`❌ Tool "${t}" requires delegation, but no agent identity was found in the current session.\n\nThis usually means one of the following:\n\n1. **No handshake was performed**: The MCP client must send a handshake request before calling protected tools.\n Example handshake:\n {\n "agentDid": "did:key:z6Mk...",\n "nonce": "unique-value",\n "audience": "server-did",\n "timestamp": ${Math.floor(Date.now()/1e3)}\n }\n\n2. **Handshake missing agentDid**: Ensure the handshake request includes the 'agentDid' field.\n\n3. **Session expired**: The session may have expired. Try performing a new handshake.\n\n4. **Request missing sessionId**: Ensure tool call requests include _meta.sessionId from the handshake response.\n\n📚 Learn more: https://docs.mcp-i.dev/delegation/handshake`}],isError:!0};s?.debug&&console.error(`[MCPI] Tool "${t}" requires delegation - verifying scopes: ${c.requiredScopes?.join(", ")}`);const i=await async function(e,t,r){const s=Date.now();let i,a;if(r.debug&&console.log(`[AuthHandshake] Verifying ${e} for scopes: ${t.join(", ")}`),r.kta&&void 0!==r.bouncer.minReputationScore)try{if(i=await async function(e,t){const r=t.apiUrl.replace(/\/$/,""),s={"Content-Type":"application/json"};t.apiKey&&(s["X-API-Key"]=t.apiKey);const i=await fetch(`${r}/api/v1/reputation/${encodeURIComponent(e)}`,{method:"GET",headers:s});if(!i.ok){if(404===i.status)return{agentDid:e,score:50,totalInteractions:0,successRate:0,riskLevel:"unknown",updatedAt:Date.now()};throw new Error(`KTA API error: ${i.status} ${i.statusText}`)}const a=await i.json();return{agentDid:a.agentDid||e,score:a.score||50,totalInteractions:a.totalInteractions||0,successRate:a.successRate||0,riskLevel:a.riskLevel||"unknown",updatedAt:a.updatedAt||Date.now()}}(e,r.kta),r.debug&&console.log(`[AuthHandshake] Reputation score: ${i.score}`),i.score<r.bouncer.minReputationScore)return r.debug&&console.log(`[AuthHandshake] Reputation ${i.score} < ${r.bouncer.minReputationScore}, requiring authorization`),{authorized:!1,authError:await Rs(e,t,r,"Agent reputation score below threshold"),reputation:i,reason:"Low reputation score"}}catch(e){console.warn("[AuthHandshake] Failed to check reputation:",e)}try{a=await r.delegationVerifier.verify(e,t)}catch(s){console.error("[AuthHandshake] Delegation verification failed:",s);const i=`Delegation verification error: ${s instanceof Error?s.message:"Unknown error"}`;return{authorized:!1,authError:await Rs(e,t,r,i),reason:i}}return a.valid&&a.delegation?(r.debug&&console.log(`[AuthHandshake] Delegation valid, authorized (${Date.now()-s}ms)`),{authorized:!0,delegation:a.delegation,reputation:i,reason:"Valid delegation found"}):(r.debug&&console.log(`[AuthHandshake] No delegation found, returning needs_authorization (${Date.now()-s}ms)`),{authorized:!1,authError:await Rs(e,t,r,a.reason||"No valid delegation found"),reputation:i,reason:a.reason||"No delegation"})}(r,c.requiredScopes||[],e);if(!i.authorized)return s?.debug&&console.error(`[MCPI] Tool "${t}" blocked - authorization required`),{content:[{type:"text",text:JSON.stringify({error:"needs_authorization",message:`Tool "${t}" requires user authorization`,authorizationUrl:i.authError?.authorizationUrl,resumeToken:i.authError?.resumeToken,scopes:i.authError?.scopes,display:i.authError?.display})}],isError:!0};s?.debug&&console.error(`[MCPI] Tool "${t}" authorized - executing handler`)}try{const e=await o(i||{}),n={content:[{type:"text",text:"string"==typeof e?e:JSON.stringify(e)}]};if(a)try{const o=await a.ensureIdentity(),c={method:t,params:i||{}},d={data:e},l=Math.floor(Date.now()/1e3),u=r??{sessionId:`tool-${Date.now()}`,nonce:`${Date.now()}`,audience:"client",createdAt:l,timestamp:l,lastActivity:l,ttlMinutes:30};let h;const p=xs.get(t);h=p?.requiredScopes&&p.requiredScopes.length>0?p.requiredScopes[0]:`${t}:execute`,s?.debug&&console.error(`[MCPI] Proof scopeId for tool "${t}": ${h}`);const f=new Is(o),g=await f.generateProof(c,d,u,{scopeId:h,clientDid:r?.clientDid});if(s?.debug&&console.error(`[MCPI] Generated proof for tool "${t}" - DID: ${g.meta.did}`),Bs)try{Bs.enqueue(g),s?.debug&&console.error("[MCPI] Proof enqueued for submission to AgentShield")}catch(e){s?.debug&&console.error("[MCPI] Failed to enqueue proof:",e)}return{...n,_meta:{proof:g}}}catch(e){return s?.debug&&console.error(`[MCPI] Failed to generate proof for tool "${t}":`,e),n}return n}catch(e){return{content:[{type:"text",text:`Error executing tool "${t}": ${e instanceof Error?e.message:String(e)}`}],isError:!0}}},Fs.run(o,c);var o,c}),s?.debug&&console.error("[MCPI] Handlers registered successfully"),e}"undefined"!=typeof global&&(global.__MCPI_HANDLERS_REGISTERED__=global.__MCPI_HANDLERS_REGISTERED__||!1);const Js=INJECTED_TOOLS,Ws="undefined"!=typeof IDENTITY_CONFIG?IDENTITY_CONFIG:void 0,Zs=Ws?JSON.parse(Ws):void 0,Qs={name:"MCP Server",version:"0.0.1"},Gs={capabilities:{tools:{}}};function Ys(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}"undefined"!=typeof global&&(global.__MCPI_SERVER_CREATED__=global.__MCPI_SERVER_CREATED__||!1);class Xs{start(){try{this.mcpServer.connect(this.transport),this.debug&&console.error("[STDIO] MCP Server running with STDIO transport"),this.setupShutdownHandlers()}catch(e){this.debug&&console.error("[STDIO] Error starting STDIO transport:",e),process.exit(1)}}setupShutdownHandlers(){const e=()=>{this.debug&&console.error("[STDIO] Shutting down STDIO transport"),process.exit(0)};process.on("SIGINT",e),process.on("SIGTERM",e)}shutdown(){this.debug&&console.error("[STDIO] Shutting down STDIO transport"),process.exit(0)}constructor(e,t=!1){Ys(this,"mcpServer",void 0),Ys(this,"transport",void 0),Ys(this,"debug",void 0),this.mcpServer=e,this.transport=new Or,this.debug=t}}const ei=STDIO_CONFIG.debug||!1;(async function(){if(Zs?.debug&&console.error("[createServer] Starting server creation"),"undefined"!=typeof global&&global.__MCPI_SERVER_CREATED__&&(Zs?.debug&&console.error("[createServer] Server already exists, returning cached instance"),global.__MCPI_SERVER_INSTANCE__))return global.__MCPI_SERVER_INSTANCE__;Zs?.debug&&(console.error("[createServer] Creating new McpServer"),console.error("[createServer] SERVER_INFO constant:",JSON.stringify(Qs)),console.error("[createServer] SERVER_CAPABILITIES constant:",JSON.stringify(Gs)),console.error("[createServer] Calling: new McpServer(SERVER_INFO, SERVER_CAPABILITIES)"));const e=new Tr(Qs,Gs);if(Zs?.debug){console.error("[createServer] Server created successfully");const t=e;console.error("[createServer] Actual server._serverInfo:",JSON.stringify(t._serverInfo||"undefined")),console.error("[createServer] Actual server._capabilities:",JSON.stringify(t._capabilities||"undefined")),console.error("[createServer] Loading tools...")}const[t,r]=function(){const e=new Map,t=Object.keys(Js);return Zs?.debug&&console.error("[loadTools] Injected tool paths:",t),[t.map(t=>Js[t]().then(r=>{Zs?.debug&&console.error("[loadTools] Loaded tool from path:",t),e.set(t,r)})),e]}();await Promise.all(t),Zs?.debug&&console.error("[createServer] Tools loaded, configuring server");const s=await async function(e,t){return await zs(e,t,Zs),e}(e,r);return Zs?.debug&&console.error("[createServer] Server configured successfully"),"undefined"!=typeof global&&(global.__MCPI_SERVER_CREATED__=!0,global.__MCPI_SERVER_INSTANCE__=s),s})().then(e=>{new Xs(e,ei).start()})})()})();