@kya-os/mcp-i 1.11.1 → 1.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -7
- package/dist/365.js +1 -0
- package/dist/runtime/160.js +1 -0
- package/dist/runtime/adapter-express.js +3 -3
- package/dist/runtime/adapter-nextjs.js +3 -3
- package/dist/runtime/http.js +3 -3
- package/dist/runtime/index.d.ts +1 -2
- package/dist/runtime/index.js +3 -10
- package/dist/runtime/mcpi-runtime-wrapper.js +1 -8
- package/dist/runtime/mcpi-runtime.d.ts +4 -12
- package/dist/runtime/mcpi-runtime.js +38 -31
- package/dist/runtime/stdio.js +3 -3
- package/dist/runtime/utils/time.d.ts +1 -1
- package/dist/runtime/utils/time.js +1 -1
- package/package.json +5 -5
- package/dist/342.js +0 -1
- package/dist/runtime/337.js +0 -1
- package/dist/runtime/audit.d.ts +0 -430
- package/dist/runtime/audit.js +0 -439
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kya-os/mcp-i",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.12.0",
|
|
4
4
|
"description": "The TypeScript MCP framework with identity features built-in",
|
|
5
5
|
"type": "commonjs",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -63,9 +63,9 @@
|
|
|
63
63
|
"model-context-protocol"
|
|
64
64
|
],
|
|
65
65
|
"dependencies": {
|
|
66
|
-
"@kya-os/contracts": "^1.
|
|
67
|
-
"@kya-os/mcp-i-core": "^1.
|
|
68
|
-
"@kya-os/mcp-i-runtime": "^1.
|
|
66
|
+
"@kya-os/contracts": "^1.10.0",
|
|
67
|
+
"@kya-os/mcp-i-core": "^1.9.0",
|
|
68
|
+
"@kya-os/mcp-i-runtime": "^1.2.0",
|
|
69
69
|
"@modelcontextprotocol/sdk": "^1.11.4",
|
|
70
70
|
"@swc/core": "^1.15.11",
|
|
71
71
|
"@types/express": "^5.0.6",
|
|
@@ -103,7 +103,7 @@
|
|
|
103
103
|
"@modelcontextprotocol/inspector": "^0.20.0"
|
|
104
104
|
},
|
|
105
105
|
"devDependencies": {
|
|
106
|
-
"@kya-os/mcp": "
|
|
106
|
+
"@kya-os/mcp": "1.11.0",
|
|
107
107
|
"@aws-sdk/client-dynamodb": "^3.992.0",
|
|
108
108
|
"@types/content-type": "^1.1.9",
|
|
109
109
|
"@types/fs-extra": "^11.0.4",
|
package/dist/342.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
"use strict";exports.id=342,exports.ids=[342],exports.modules={99342:(e,t,r)=>{r.r(t),r.d(t,{ANON_NONCE_TTL_MS:()=>D,AUTH_NONCE_TTL_MS:()=>b,AuditLogProvider:()=>Xr,BitstringManager:()=>We,CascadingRevocationManager:()=>ze,ClockProvider:()=>Tr,CryptoProvider:()=>Pr,DEFAULT_CLOCK_SKEW_SECONDS:()=>Sr,DEFAULT_SESSION_TTL_MINUTES:()=>w,DEFAULT_TIMESTAMP_SKEW_SECONDS:()=>v,DELEGATION_CREDENTIAL_CONTEXT:()=>h,DefaultPolicyEngine:()=>hn,DelegationCredentialIssuer:()=>K,DelegationCredentialVerifier:()=>Ke,DelegationGraphManager:()=>Me,DidWebResolver:()=>rr,ED25519_KEY_SIZE:()=>xt,ED25519_PKCS8_DER_HEADER:()=>Ot,ED25519_SPKI_DER_HEADER_LENGTH:()=>Kt,FetchProvider:()=>Rr,GrantStore:()=>en,HOLDER_BINDING_ERROR:()=>Ft,IdentityProvider:()=>Or,KYA_OS_ERROR_CODES:()=>n,KYA_OS_PROOF_META_KEY:()=>Mt,LEGACY_PROOF_META_KEY:()=>Ht,MAX_CLOCK_SKEW_SECONDS:()=>Dr,MIN_CLOCK_SKEW_SECONDS:()=>br,MemoryAuditLogProvider:()=>Qr,MemoryDelegationGraphStorage:()=>Xt,MemoryGrantStore:()=>tn,MemoryIdentityProvider:()=>Mr,MemoryNonceCacheProvider:()=>xr,MemoryPendingFlowStore:()=>nn,MemoryResumeTokenStore:()=>fr,MemorySessionStore:()=>Lr,MemoryStatusListStorage:()=>Yt,MemoryStorageProvider:()=>Kr,NONCE_LENGTH_BYTES:()=>S,NodeCryptoProvider:()=>zr,NonceCacheProvider:()=>Nr,NoopAuditLogProvider:()=>Zr,NoopFetchProvider:()=>Gr,OUTBOUND_HEADER_NAMES:()=>Rt,PROOF_VERIFICATION_ERROR_CODES:()=>mr,PendingFlowStore:()=>rn,ProofGenerator:()=>jt,ProofVerificationError:()=>wr,ProofVerifier:()=>Er,RiskClassifier:()=>dn,RuntimeFetchProvider:()=>qr,SENSITIVE_VERBS:()=>an,SessionManager:()=>jr,SessionStore:()=>Hr,StatusList2021Manager:()=>Be,StorageProvider:()=>$r,SystemClockProvider:()=>Fr,assertHolderBinding:()=>Gt,base58Decode:()=>ct,base58Encode:()=>at,base64ToBytes:()=>u,base64urlDecodeToBytes:()=>o,base64urlEncodeFromBytes:()=>c,buildAuditRecord:()=>Yr,buildChainString:()=>it,buildDelegationProofJWT:()=>nt,buildDidResolverRegistry:()=>hr,buildDidWebDocument:()=>or,buildOutboundDelegationHeaders:()=>$t,buildPolicyRequest:()=>pn,bytesToBase64:()=>d,canonicalizeJSON:()=>T,compareDids:()=>ft,completeVCJWT:()=>N,createCascadingRevocationManager:()=>Fe,createDefaultConsoleLogger:()=>Dt,createDelegationGraph:()=>He,createDelegationIssuer:()=>x,createDelegationVerifier:()=>xe,createDidKeyResolver:()=>Pt,createDidWebResolver:()=>nr,createHandshakeRequest:()=>Wr,createKyaOsError:()=>i,createKyaOsMiddleware:()=>Dn,createNeedsApprovalError:()=>A,createNeedsAuthorizationError:()=>E,createProofResponse:()=>Wt,createProofVerificationError:()=>vr,createStatusListManager:()=>Ve,createUnsignedVCJWT:()=>$,didKeyFragment:()=>St,didWebToUrl:()=>tr,extractAgentId:()=>gt,extractAgentSlug:()=>yt,extractCanonicalData:()=>Ut,extractDelegationFromVC:()=>p,extractProofFromMeta:()=>Cr,extractPublicKeyFromDidKey:()=>_t,generateDidKeyFromBase64:()=>vt,generateDidKeyFromBytes:()=>wt,generateIdentity:()=>In,generateRequestProof:()=>zt,getDidMethod:()=>lt,getServerDid:()=>pt,hasSensitiveScopes:()=>yr,isDelegationCredentialExpired:()=>g,isDelegationCredentialNotYetValid:()=>y,isDidWeb:()=>Zt,isEd25519DidKey:()=>kt,isHolderBindingApplicable:()=>qt,isIndexSet:()=>Je,isKyaOsControlArg:()=>Bt,isNeedsApprovalError:()=>k,isNeedsAuthorizationError:()=>I,isReservedMcpMetaKey:()=>kr,isValidBase58:()=>dt,isValidDid:()=>ut,logger:()=>Et,matchScope:()=>vn,normalizeDid:()=>ht,parseDidWeb:()=>er,parseVCJWT:()=>O,publicKeyToJwk:()=>Ct,resolveDidKeySync:()=>Tt,scopeSatisfies:()=>Sn,toHolderBindingRequest:()=>Vt,validateDelegationCredential:()=>m,validateDetachedProof:()=>C,validateHandshakeFormat:()=>Ur,validateMetaStructure:()=>_r,verifyApprovalQuorum:()=>fn,verifyDelegationAudience:()=>qe,verifyDidLinkage:()=>cr,verifyOrHints:()=>pr,withKyaOs:()=>An,wrapDelegationAsVC:()=>f});const n={invalid_proof:"invalid_proof",invalid_jws:"invalid_jws",nonce_replay:"nonce_replay",timestamp_skew:"timestamp_skew",did_not_found:"did_not_found",invalid_public_key:"invalid_public_key",handshake_failed:"handshake_failed",session_expired:"session_expired",invalid_request:"invalid_request",needs_authorization:"needs_authorization",insufficient_scope:"insufficient_scope",policy_denied:"policy_denied",delegation_expired:"delegation_expired",delegation_not_yet_valid:"delegation_not_yet_valid",delegation_revoked:"delegation_revoked",delegation_invalid:"delegation_invalid",holder_binding_failed:"holder_binding_failed",budget_exceeded:"budget_exceeded",rate_limit_exceeded:"rate_limit_exceeded",invalid_token:"invalid_token",token_expired:"token_expired",mirror_pending:"mirror_pending",claim_failed:"claim_failed",configuration_error:"configuration_error",runtime_error:"runtime_error"};function i(e,t,r){return r?{code:e,message:t,details:r}:{code:e,message:t}}function s(e){const t=l(e).replace(/-/g,"+").replace(/_/g,"/");if("undefined"!=typeof Buffer){if(!/^[A-Za-z0-9+/]*={0,2}$/.test(t))throw new Error("Invalid base64url string: contains invalid characters");return Buffer.from(t,"base64").toString("utf-8")}if("undefined"!=typeof atob){const e=atob(t);if("undefined"!=typeof TextDecoder){const t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return(new TextDecoder).decode(t)}return e}throw new Error("Neither Buffer nor atob is available")}function o(e){const t=l(e).replace(/-/g,"+").replace(/_/g,"/");if("undefined"!=typeof atob){const e=atob(t),r=new Uint8Array(e.length);for(let t=0;t<e.length;t++)r[t]=e.charCodeAt(t);return r}return new Uint8Array(Buffer.from(t,"base64"))}function a(e){if("undefined"!=typeof Buffer)return Buffer.from(e,"utf-8").toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"");if("undefined"!=typeof btoa){const t=(new TextEncoder).encode(e),r=Array.from(t).map(e=>String.fromCharCode(e)).join("");return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}throw new Error("Neither Buffer nor btoa is available")}function c(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,"")}function d(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")}function u(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");const r=(4-t.length%4)%4;if(t+="=".repeat(r),"undefined"!=typeof atob){const e=atob(t),r=new Uint8Array(e.length);for(let t=0;t<e.length;t++)r[t]=e.charCodeAt(t);return r}return new Uint8Array(Buffer.from(t,"base64"))}function l(e){const t=e.length%4;return 0===t?e:e+"=".repeat((4-t)%4)}const h="https://schema.kya-os.org/v1/protocol/delegation/context/v1.0.0";function f(e,t){const r=(new Date).toISOString(),n=e.constraints.notAfter?new Date(1e3*e.constraints.notAfter).toISOString():t?.expirationDate;let i=t?.issuanceDate||r;!t?.issuanceDate&&e.createdAt&&(i=new Date(e.createdAt).toISOString());const s=t?.scopes||e.constraints.scopes;return{"@context":["https://www.w3.org/2018/credentials/v1",h],id:t?.id||e.vcId||`urn:uuid:${e.id}`,type:["VerifiableCredential","DelegationCredential"],issuer:e.issuerDid,issuanceDate:i,...void 0!==n&&{expirationDate:n},credentialSubject:{id:e.subjectDid,delegation:{id:e.id,issuerDid:e.issuerDid,subjectDid:e.subjectDid,...t?.userDid&&{userDid:t.userDid},...t?.userIdentifier&&{userIdentifier:t.userIdentifier},...t?.sessionId&&{sessionId:t.sessionId},...s&&s.length>0&&{scopes:s},...void 0!==e.controller&&{controller:e.controller},...void 0!==e.parentId&&{parentId:e.parentId},constraints:e.constraints,status:e.status,...void 0!==e.createdAt&&{createdAt:e.createdAt},...void 0!==e.metadata&&{metadata:e.metadata}}},...void 0!==t?.credentialStatus&&{credentialStatus:t.credentialStatus}}}function p(e){const t=e?.credentialSubject?.delegation;if(!t||"object"!=typeof t)throw new Error("extractDelegationFromVC: credential is missing credentialSubject.delegation");let r="";if(e.proof){const t=e.proof;r=t.proofValue||t.jws||t.signatureValue||""}return{id:t.id,issuerDid:t.issuerDid,subjectDid:t.subjectDid,controller:t.controller,vcId:e.id||`vc:${t.id}`,parentId:t.parentId,constraints:t.constraints,signature:r,status:t.status,createdAt:t.createdAt,revokedAt:void 0,revokedReason:void 0,metadata:t.metadata}}function g(e){if(e.expirationDate&&new Date(e.expirationDate)<new Date)return!0;const t=e.credentialSubject.delegation;return!!(t.constraints.notAfter&&Math.floor(Date.now()/1e3)>t.constraints.notAfter)}function y(e){const t=e.credentialSubject.delegation;return!!(t.constraints.notBefore&&Math.floor(Date.now()/1e3)<t.constraints.notBefore)}function m(e){if(!e||"object"!=typeof e)return{success:!1,error:{message:"Not an object"}};const t=e;if(!Array.isArray(t["@context"])||0===t["@context"].length)return{success:!1,error:{message:"Missing or invalid @context"}};if("https://www.w3.org/2018/credentials/v1"!==t["@context"][0])return{success:!1,error:{message:"First @context must be W3C VC context"}};if(!Array.isArray(t.type))return{success:!1,error:{message:"Missing type array"}};if(!t.type.includes("VerifiableCredential")||!t.type.includes("DelegationCredential"))return{success:!1,error:{message:"type must include VerifiableCredential and DelegationCredential"}};if(!t.issuer||"string"!=typeof t.issuer&&"object"!=typeof t.issuer)return{success:!1,error:{message:"Missing or invalid issuer"}};if(!t.issuanceDate||"string"!=typeof t.issuanceDate)return{success:!1,error:{message:"Missing issuanceDate"}};const r=t.credentialSubject;if(!r||"object"!=typeof r)return{success:!1,error:{message:"Missing credentialSubject"}};if(!r.id||"string"!=typeof r.id)return{success:!1,error:{message:"credentialSubject.id missing"}};const n=r.delegation;return n&&"object"==typeof n?n.id&&n.issuerDid&&n.subjectDid&&n.constraints?{success:!0,data:e}:{success:!1,error:{message:"delegation fields missing"}}:{success:!1,error:{message:"credentialSubject.delegation missing"}}}const w=30,v=120,S=16,b=12e4,D=6e4;function E(e){return{error:"needs_authorization",...e}}function I(e){return"object"==typeof e&&null!==e&&"needs_authorization"===e.error}function A(e){return{error:"needs_approval",...e}}function k(e){return"object"==typeof e&&null!==e&&"needs_approval"===e.error}const _=/^sha256:[a-f0-9]{64}$/;function C(e){if(!e||"object"!=typeof e)return{success:!1,error:{message:"Not an object"}};const t=e;if("string"!=typeof t.jws||t.jws.length<1)return{success:!1,error:{message:"jws must be a non-empty string"}};const r=t.meta;if(!r||"object"!=typeof r)return{success:!1,error:{message:"meta must be an object"}};const n=r,i=["did","kid","nonce","audience","sessionId"];for(const e of i)if("string"!=typeof n[e]||n[e].length<1)return{success:!1,error:{message:`meta.${e} must be a non-empty string`}};if("number"!=typeof n.ts||!Number.isInteger(n.ts)||n.ts<=0)return{success:!1,error:{message:"meta.ts must be a positive integer"}};if("string"!=typeof n.requestHash||!_.test(n.requestHash))return{success:!1,error:{message:"meta.requestHash must match sha256:<64 hex chars>"}};if(void 0!==n.responseHash&&("string"!=typeof n.responseHash||!_.test(n.responseHash)))return{success:!1,error:{message:"meta.responseHash must match sha256:<64 hex chars> when present"}};const s=["scopeId","delegationRef","clientDid","reason"];for(const e of s)if(void 0!==n[e]&&"string"!=typeof n[e])return{success:!1,error:{message:`meta.${e} must be a string if present`}};return void 0===n.outcome||["allowed","denied","step_up_required","needs_authorization"].includes(n.outcome)?{success:!0,data:e}:{success:!1,error:{message:"meta.outcome must be one of allowed | denied | step_up_required | needs_authorization"}}}var P=r(77753);function T(e){return R(e),(0,P.d)(e)}function R(e,t="$"){if(null!==e&&"boolean"!=typeof e&&"string"!=typeof e)if("number"!=typeof e){if(void 0===e)throw new TypeError(`Cannot canonicalize undefined at ${t}`);if("function"==typeof e)throw new TypeError(`Cannot canonicalize function at ${t}`);if("symbol"==typeof e)throw new TypeError(`Cannot canonicalize symbol at ${t}`);if("bigint"==typeof e)throw new TypeError(`Cannot canonicalize bigint at ${t}`);if(Array.isArray(e))for(let r=0;r<e.length;r++)R(e[r],`${t}[${r}]`);else if("object"!=typeof e);else for(const[r,n]of Object.entries(e))R(n,`${t}.${r}`)}else if(!Number.isFinite(e))throw new TypeError(`Cannot canonicalize non-finite number at ${t}: ${e}`)}function $(e,t={}){const r={alg:"EdDSA",typ:"JWT"};t.keyId&&(r.kid=t.keyId);const n="string"==typeof e.issuer?e.issuer:e.issuer?.id,i=e.credentialSubject?.id;let s,o;e.expirationDate&&"string"==typeof e.expirationDate&&(s=Math.floor(new Date(e.expirationDate).getTime()/1e3)),e.issuanceDate&&"string"==typeof e.issuanceDate&&(o=Math.floor(new Date(e.issuanceDate).getTime()/1e3));const c={...e};delete c.proof;const d={iss:n,vc:c};i&&(d.sub=i),s&&(d.exp=s),o&&(d.iat=o),e.id&&"string"==typeof e.id&&(d.jti=e.id);const u=a(JSON.stringify(r)),l=a(JSON.stringify(d));return{header:r,payload:d,encodedHeader:u,encodedPayload:l,signingInput:`${u}.${l}`}}function N(e,t){return`${e}.${t}`}function O(e){const t=e.split(".");if(3!==t.length)return null;try{const e=s(t[0]),r=s(t[1]);return{header:JSON.parse(e),payload:JSON.parse(r),signature:t[2],signingInput:`${t[0]}.${t[1]}`}}catch{return null}}class K{identity;signingFunction;constructor(e,t){this.identity=e,this.signingFunction=t}async issueDelegationCredential(e,t={}){let r=f(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 n=this.canonicalizeVC(r),i=await this.signingFunction(n,this.identity.getDid(),this.identity.getKeyId());return{...r,proof:i}}async createAndIssueDelegation(e,t={}){const r=Date.now(),n={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(n,t)}canonicalizeVC(e){return T(e)}getIssuerDid(){return this.identity.getDid()}getIssuerKeyId(){return this.identity.getKeyId()}}function x(e,t){return new K(e,t)}const M=["id","delegation"];function H(e,t={}){const r=m(e);if(!r.success)return{valid:!1,reason:`Schema validation failed: ${r.error?.message}`};if(g(e))return{valid:!1,reason:"Delegation credential expired"};if(y(e))return{valid:!1,reason:"Delegation credential not yet valid"};const n=e.credentialSubject.delegation;if("revoked"===n.status)return{valid:!1,reason:"Delegation status is revoked"};if("expired"===n.status)return{valid:!1,reason:"Delegation status is expired"};if(!n.issuerDid||!n.subjectDid)return{valid:!1,reason:"Missing issuer or subject DID"};if((t.requireEmbeddedProof??1)&&!e.proof)return{valid:!1,reason:"Missing proof"};const i=function(e){const t=Object.keys(e.credentialSubject).filter(e=>!M.includes(e));return 0===t.length?{valid:!0}:{valid:!1,reason:`credentialSubject contains non-delegation field(s): ${t.join(", ")}. A DelegationCredential subject MUST carry only 'id' and 'delegation' (KYA-OS §11.6).`}}(e);return i.valid?{valid:!0}:i}async function L(e,t){const r=Date.now();try{return t?await t.checkStatus(e)?{valid:!1,reason:`Credential revoked via StatusList2021 (${e.statusPurpose})`,outcome:"revoked",durationMs:Date.now()-r}:{valid:!0,durationMs:Date.now()-r}:{valid:!1,reason:"Credential has credentialStatus but no status list resolver is configured — cannot verify revocation status",outcome:"status_unresolvable",durationMs:Date.now()-r}}catch(e){return{valid:!1,reason:`Status check error: ${e instanceof Error?e.message:"Unknown error"}`,outcome:"status_unresolvable",durationMs:Date.now()-r}}}const j=new TextEncoder,W=new TextDecoder;function U(...e){const t=e.reduce((e,{length:t})=>e+t,0),r=new Uint8Array(t);let n=0;for(const t of e)r.set(t,n),n+=t.length;return r}function J(e){const t=new Uint8Array(e.length);for(let r=0;r<e.length;r++){const n=e.charCodeAt(r);if(n>127)throw new TypeError("non-ASCII string encountered in encode()");t[r]=n}return t}function B(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(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}function V(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64("string"==typeof e?e:W.decode(e),{alphabet:"base64url"});let t=e;t instanceof Uint8Array&&(t=W.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/");try{return B(t)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}}function z(e){let t=e;return"string"==typeof t&&(t=j.encode(t)),Uint8Array.prototype.toBase64?t.toBase64({alphabet:"base64url",omitPadding:!0}):function(e){if(Uint8Array.prototype.toBase64)return e.toBase64();const t=[];for(let r=0;r<e.length;r+=32768)t.push(String.fromCharCode.apply(null,e.subarray(r,r+32768)));return btoa(t.join(""))}(t).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}class F 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 q extends F{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"}class G extends F{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"}class Y extends F{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"}class X extends F{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"}Symbol.asyncIterator;class Q extends F{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(e="signature verification failed",t){super(e,t)}}const Z=(e,t)=>{if(e.byteLength!==t.length)return!1;for(let r=0;r<e.byteLength;r++)if(e[r]!==t[r])return!1;return!0},ee=e=>{const t=e.data[e.pos++];if(128&t){const r=127&t;let n=0;for(let t=0;t<r;t++)n=n<<8|e.data[e.pos++];return n}return t},te=(e,t,r)=>{if(e.data[e.pos++]!==t)throw new Error(r)},re=(e,t)=>{const r=e.data.subarray(e.pos,e.pos+t);return e.pos+=t,r},ne=(e,t,r)=>{const n=((e,t)=>B(e.replace(t,"")))(e,/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g);let i=r;return t?.startsWith?.("ECDH-ES")&&(i||={},i.getNamedCurve=e=>{const t={data:e,pos:0};return function(e){te(e,48,"Invalid PKCS#8 structure"),ee(e),te(e,2,"Expected version field");const t=ee(e);e.pos+=t,te(e,48,"Expected algorithm identifier");ee(e);e.pos}(t),(e=>{const t=(e=>{te(e,6,"Expected algorithm OID");const t=ee(e);return re(e,t)})(e);if(Z(t,[43,101,110]))return"X25519";if(!Z(t,[42,134,72,206,61,2,1]))throw new Error("Unsupported key algorithm");te(e,6,"Expected curve OID");const r=ee(e),n=re(e,r);for(const{name:e,oid:t}of[{name:"P-256",oid:[42,134,72,206,61,3,1,7]},{name:"P-384",oid:[43,129,4,0,34]},{name:"P-521",oid:[43,129,4,0,35]}])if(Z(n,t))return e;throw new Error("Unsupported named curve")})(t)}),(async(e,t,r,n)=>{let i,s;const o="spki"===e,a=()=>o?["verify"]:["sign"];switch(r){case"PS256":case"PS384":case"PS512":i={name:"RSA-PSS",hash:`SHA-${r.slice(-3)}`},s=a();break;case"RS256":case"RS384":case"RS512":i={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${r.slice(-3)}`},s=a();break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":i={name:"RSA-OAEP",hash:`SHA-${parseInt(r.slice(-3),10)||1}`},s=o?["encrypt","wrapKey"]:["decrypt","unwrapKey"];break;case"ES256":case"ES384":case"ES512":i={name:"ECDSA",namedCurve:{ES256:"P-256",ES384:"P-384",ES512:"P-521"}[r]},s=a();break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":try{const e=n.getNamedCurve(t);i="X25519"===e?{name:"X25519"}:{name:"ECDH",namedCurve:e}}catch(e){throw new G("Invalid or unsupported key format")}s=o?[]:["deriveBits"];break;case"Ed25519":case"EdDSA":i={name:"Ed25519"},s=a();break;case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":i={name:r},s=a();break;default:throw new G('Invalid or unsupported "alg" (Algorithm) value')}return crypto.subtle.importKey(e,t,i,n?.extractable??!!o,s)})("pkcs8",n,t,i)},ie='Invalid or unsupported JWK "alg" (Algorithm) Parameter value';async function se(e){if(!e.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:t,keyUsages:r}=function(e){let t,r;switch(e.kty){case"AKP":switch(e.alg){case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":t={name:e.alg},r=e.priv?["sign"]:["verify"];break;default:throw new G(ie)}break;case"RSA":switch(e.alg){case"PS256":case"PS384":case"PS512":t={name:"RSA-PSS",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":t={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":t={name:"RSA-OAEP",hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},r=e.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new G(ie)}break;case"EC":switch(e.alg){case"ES256":case"ES384":case"ES512":t={name:"ECDSA",namedCurve:{ES256:"P-256",ES384:"P-384",ES512:"P-521"}[e.alg]},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:"ECDH",namedCurve:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new G(ie)}break;case"OKP":switch(e.alg){case"Ed25519":case"EdDSA":t={name:"Ed25519"},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new G(ie)}break;default:throw new G('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:r}}(e),n={...e};return"AKP"!==n.kty&&delete n.alg,delete n.use,crypto.subtle.importKey("jwk",n,t,e.ext??(!e.d&&!e.priv),e.key_ops??r)}const oe=e=>"object"==typeof e&&null!==e;function ae(e){if(!oe(e)||"[object Object]"!==Object.prototype.toString.call(e))return!1;if(null===Object.getPrototypeOf(e))return!0;let t=e;for(;null!==Object.getPrototypeOf(t);)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function ce(...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}const de=e=>ae(e)&&"string"==typeof e.kty;async function ue(e,t,r){if(!ae(e))throw new TypeError("JWK must be an object");let n;switch(t??=e.alg,n??=r?.extractable??e.ext,e.kty){case"oct":if("string"!=typeof e.k||!e.k)throw new TypeError('missing "k" (Key Value) Parameter value');return V(e.k);case"RSA":if("oth"in e&&void 0!==e.oth)throw new G('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');return se({...e,alg:t,ext:n});case"AKP":if("string"!=typeof e.alg||!e.alg)throw new TypeError('missing "alg" (Algorithm) Parameter value');if(void 0!==t&&t!==e.alg)throw new TypeError("JWK alg and alg option value mismatch");return se({...e,ext:n});case"EC":case"OKP":return se({...e,alg:t,ext:n});default:throw new G('Unsupported "kty" (Key Type) Parameter value')}}const le=(e,t="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`),he=(e,t)=>e.name===t;function fe(e,t){var r;if(r=e.hash,parseInt(r.name.slice(4),10)!==t)throw le(`SHA-${t}`,"algorithm.hash")}function pe(e,t,r){switch(t){case"HS256":case"HS384":case"HS512":if(!he(e.algorithm,"HMAC"))throw le("HMAC");fe(e.algorithm,parseInt(t.slice(2),10));break;case"RS256":case"RS384":case"RS512":if(!he(e.algorithm,"RSASSA-PKCS1-v1_5"))throw le("RSASSA-PKCS1-v1_5");fe(e.algorithm,parseInt(t.slice(2),10));break;case"PS256":case"PS384":case"PS512":if(!he(e.algorithm,"RSA-PSS"))throw le("RSA-PSS");fe(e.algorithm,parseInt(t.slice(2),10));break;case"Ed25519":case"EdDSA":if(!he(e.algorithm,"Ed25519"))throw le("Ed25519");break;case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":if(!he(e.algorithm,t))throw le(t);break;case"ES256":case"ES384":case"ES512":{if(!he(e.algorithm,"ECDSA"))throw le("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 le(r,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}!function(e,t){if(t&&!e.usages.includes(t))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}(e,r)}function ge(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 ye=(e,t,...r)=>ge(`Key for the ${e} algorithm must be `,t,...r);function me(e,t){if(e.startsWith("RS")||e.startsWith("PS")){const{modulusLength:r}=t.algorithm;if("number"!=typeof r||r<2048)throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}}function we(e,t){const r=`SHA-${e.slice(-3)}`;switch(e){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:parseInt(e.slice(-3),10)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:t.namedCurve};case"Ed25519":case"EdDSA":return{name:"Ed25519"};case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":return{name:e};default:throw new G(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}async function ve(e,t,r){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(ge("Key must be ",t,"CryptoKey","KeyObject","JSON Web Key"));return crypto.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}return pe(t,e,r),t}function Se(e,t){if(e)throw new TypeError(`${t} can only be called once`)}function be(e,t,r){try{return V(e)}catch{throw new r(`Failed to base64url decode the ${t}`)}}Symbol();const De=e=>{if("CryptoKey"===e?.[Symbol.toStringTag])return!0;try{return e instanceof CryptoKey}catch{return!1}},Ee=e=>"KeyObject"===e?.[Symbol.toStringTag],Ie=e=>De(e)||Ee(e),Ae=e=>e?.[Symbol.toStringTag],ke=(e,t,r)=>{if(void 0!==t.use){let e;switch(r){case"sign":case"verify":e="sig";break;case"encrypt":case"decrypt":e="enc"}if(t.use!==e)throw new TypeError(`Invalid key for this operation, its "use" must be "${e}" when present`)}if(void 0!==t.alg&&t.alg!==e)throw new TypeError(`Invalid key for this operation, its "alg" must be "${e}" when present`);if(Array.isArray(t.key_ops)){let n;switch(!0){case"sign"===r||"verify"===r:case"dir"===e:case e.includes("CBC-HS"):n=r;break;case e.startsWith("PBES2"):n="deriveBits";break;case/^A\d{3}(?:GCM)?(?:KW)?$/.test(e):n=!e.includes("GCM")&&e.endsWith("KW")?"encrypt"===r?"wrapKey":"unwrapKey":r;break;case"encrypt"===r&&e.startsWith("RSA"):n="wrapKey";break;case"decrypt"===r:n=e.startsWith("RSA")?"unwrapKey":"deriveBits"}if(n&&!1===t.key_ops?.includes?.(n))throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${n}" when present`)}return!0};function _e(e,t,r){switch(e.substring(0,2)){case"A1":case"A2":case"di":case"HS":case"PB":((e,t,r)=>{if(!(t instanceof Uint8Array)){if(de(t)){if((e=>"oct"===e.kty&&"string"==typeof e.k)(t)&&ke(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(!Ie(t))throw new TypeError(ye(e,t,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"));if("secret"!==t.type)throw new TypeError(`${Ae(t)} instances for symmetric algorithms must be of type "secret"`)}})(e,t,r);break;default:((e,t,r)=>{if(de(t))switch(r){case"decrypt":case"sign":if((e=>"oct"!==e.kty&&("AKP"===e.kty&&"string"==typeof e.priv||"string"==typeof e.d))(t)&&ke(e,t,r))return;throw new TypeError("JSON Web Key for this operation must be a private JWK");case"encrypt":case"verify":if((e=>"oct"!==e.kty&&void 0===e.d&&void 0===e.priv)(t)&&ke(e,t,r))return;throw new TypeError("JSON Web Key for this operation must be a public JWK")}if(!Ie(t))throw new TypeError(ye(e,t,"CryptoKey","KeyObject","JSON Web Key"));if("secret"===t.type)throw new TypeError(`${Ae(t)} instances for asymmetric algorithms must not be of type "secret"`);if("public"===t.type)switch(r){case"sign":throw new TypeError(`${Ae(t)} instances for asymmetric algorithm signing must be of type "private"`);case"decrypt":throw new TypeError(`${Ae(t)} instances for asymmetric algorithm decryption must be of type "private"`)}if("private"===t.type)switch(r){case"verify":throw new TypeError(`${Ae(t)} instances for asymmetric algorithm verifying must be of type "public"`);case"encrypt":throw new TypeError(`${Ae(t)} instances for asymmetric algorithm encryption must be of type "public"`)}})(e,t,r)}}function Ce(e,t,r,n,i){if(void 0!==i.crit&&void 0===n?.crit)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||void 0===n.crit)return new Set;if(!Array.isArray(n.crit)||0===n.crit.length||n.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 s;s=void 0!==r?new Map([...Object.entries(r),...t.entries()]):t;for(const t of n.crit){if(!s.has(t))throw new G(`Extension Header Parameter "${t}" is not recognized`);if(void 0===i[t])throw new e(`Extension Header Parameter "${t}" is missing`);if(s.get(t)&&void 0===n[t])throw new e(`Extension Header Parameter "${t}" MUST be integrity protected`)}return new Set(n.crit)}const Pe="given KeyObject instance cannot be used for this algorithm";let Te;const Re=async(e,t,r,n=!1)=>{Te||=new WeakMap;let i=Te.get(e);if(i?.[r])return i[r];const s=await se({...t,alg:r});return n&&Object.freeze(e),i?i[r]=s:Te.set(e,{[r]:s}),s};async function $e(e,t){if(e instanceof Uint8Array)return e;if(De(e))return e;if(Ee(e)){if("secret"===e.type)return e.export();if("toCryptoKey"in e&&"function"==typeof e.toCryptoKey)try{return((e,t)=>{Te||=new WeakMap;let r=Te.get(e);if(r?.[t])return r[t];const n="public"===e.type,i=!!n;let s;if("x25519"===e.asymmetricKeyType){switch(t){case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":break;default:throw new TypeError(Pe)}s=e.toCryptoKey(e.asymmetricKeyType,i,n?[]:["deriveBits"])}if("ed25519"===e.asymmetricKeyType){if("EdDSA"!==t&&"Ed25519"!==t)throw new TypeError(Pe);s=e.toCryptoKey(e.asymmetricKeyType,i,[n?"verify":"sign"])}switch(e.asymmetricKeyType){case"ml-dsa-44":case"ml-dsa-65":case"ml-dsa-87":if(t!==e.asymmetricKeyType.toUpperCase())throw new TypeError(Pe);s=e.toCryptoKey(e.asymmetricKeyType,i,[n?"verify":"sign"])}if("rsa"===e.asymmetricKeyType){let r;switch(t){case"RSA-OAEP":r="SHA-1";break;case"RS256":case"PS256":case"RSA-OAEP-256":r="SHA-256";break;case"RS384":case"PS384":case"RSA-OAEP-384":r="SHA-384";break;case"RS512":case"PS512":case"RSA-OAEP-512":r="SHA-512";break;default:throw new TypeError(Pe)}if(t.startsWith("RSA-OAEP"))return e.toCryptoKey({name:"RSA-OAEP",hash:r},i,n?["encrypt"]:["decrypt"]);s=e.toCryptoKey({name:t.startsWith("PS")?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:r},i,[n?"verify":"sign"])}if("ec"===e.asymmetricKeyType){const r=new Map([["prime256v1","P-256"],["secp384r1","P-384"],["secp521r1","P-521"]]).get(e.asymmetricKeyDetails?.namedCurve);if(!r)throw new TypeError(Pe);const o={ES256:"P-256",ES384:"P-384",ES512:"P-521"};o[t]&&r===o[t]&&(s=e.toCryptoKey({name:"ECDSA",namedCurve:r},i,[n?"verify":"sign"])),t.startsWith("ECDH-ES")&&(s=e.toCryptoKey({name:"ECDH",namedCurve:r},i,n?[]:["deriveBits"]))}if(!s)throw new TypeError(Pe);return r?r[t]=s:Te.set(e,{[t]:s}),s})(e,t)}catch(e){if(e instanceof TypeError)throw e}let r=e.export({format:"jwk"});return Re(e,r,t)}if(de(e))return e.k?V(e.k):Re(e,e,t,!0);throw new Error("unreachable")}function Ne(e,t,r){return{valid:!1,reason:e,stage:"basic",metrics:void 0!==r?{basicCheckMs:r,totalMs:Date.now()-t}:{totalMs:Date.now()-t},checks:{basicValid:!1}}}async function Oe(e,t,r,n){const i=Date.now(),s=(e,t)=>({valid:e,reason:t,durationMs:Date.now()-i});if(!n)return s(!1,"No DID resolver configured — signature cannot be verified");const o=await n.resolve(t);if(!o)return s(!1,`Could not resolve issuer DID: ${t}`);const a=function(e,t){return t?e.find(e=>e.id===t):e[0]}(o.verificationMethod??[],r);if(!a)return s(!1,r?`Verification method ${r} not found in DID Document`:"DID Document has no verification method");if(!a.publicKeyJwk)return s(!1,"Verification method missing publicKeyJwk");try{const t=await ue(a.publicKeyJwk,"EdDSA");return await async function(e,t){if(e instanceof Uint8Array&&(e=W.decode(e)),"string"!=typeof e)throw new Y("Compact JWS must be a string or Uint8Array");const{0:r,1:n,2:i,length:s}=e.split(".");if(3!==s)throw new Y("Invalid Compact JWS");const o=await async function(e,t,r){if(!ae(e))throw new Y("Flattened JWS must be an object");if(void 0===e.protected&&void 0===e.header)throw new Y('Flattened JWS must have either of the "protected" or "header" members');if(void 0!==e.protected&&"string"!=typeof e.protected)throw new Y("JWS Protected Header incorrect type");if(void 0===e.payload)throw new Y("JWS Payload missing");if("string"!=typeof e.signature)throw new Y("JWS Signature missing or incorrect type");if(void 0!==e.header&&!ae(e.header))throw new Y("JWS Unprotected Header incorrect type");let n={};if(e.protected)try{const t=V(e.protected);n=JSON.parse(W.decode(t))}catch{throw new Y("JWS Protected Header is invalid")}if(!ce(n,e.header))throw new Y("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const i={...n,...e.header};let s=!0;if(Ce(Y,new Map([["b64",!0]]),r?.crit,n,i).has("b64")&&(s=n.b64,"boolean"!=typeof s))throw new Y('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:o}=i;if("string"!=typeof o||!o)throw new Y('JWS "alg" (Algorithm) Header Parameter missing or invalid');const a=r&&function(e,t){if(void 0!==t&&(!Array.isArray(t)||t.some(e=>"string"!=typeof e)))throw new TypeError('"algorithms" option must be an array of strings');if(t)return new Set(t)}(0,r.algorithms);if(a&&!a.has(o))throw new q('"alg" (Algorithm) Header Parameter value not allowed');if(s){if("string"!=typeof e.payload)throw new Y("JWS Payload must be a string")}else if("string"!=typeof e.payload&&!(e.payload instanceof Uint8Array))throw new Y("JWS Payload must be a string or an Uint8Array instance");let c=!1;"function"==typeof t&&(t=await t(n,e),c=!0),_e(o,t,"verify");const d=U(void 0!==e.protected?J(e.protected):new Uint8Array,J("."),"string"==typeof e.payload?s?J(e.payload):j.encode(e.payload):e.payload),u=be(e.signature,"signature",Y),l=await $e(t,o),h=await async function(e,t,r,n){const i=await ve(e,t,"verify");me(e,i);const s=we(e,i.algorithm);try{return await crypto.subtle.verify(s,i,r,n)}catch{return!1}}(o,l,u,d);if(!h)throw new Q;let f;f=s?be(e.payload,"payload",Y):"string"==typeof e.payload?j.encode(e.payload):e.payload;const p={payload:f};return void 0!==e.protected&&(p.protectedHeader=n),void 0!==e.header&&(p.unprotectedHeader=e.header),c?{...p,key:l}:p}({payload:n,protected:r,signature:i},t,{algorithms:["EdDSA"]}),a={payload:o.payload,protectedHeader:o.protectedHeader};return"function"==typeof t?{...a,key:o.key}:a}(e,t),s(!0)}catch(e){return s(!1,`JWT envelope signature is not valid: ${function(e){return e instanceof Error?e.message:String(e)}(e)}`)}}class Ke{didResolver;statusListResolver;signatureVerifier;cache=new Map;cacheInsertionOrder=[];cacheTtl;maxCacheSize;constructor(e){this.didResolver=e?.didResolver,this.statusListResolver=e?.statusListResolver,this.signatureVerifier=e?.signatureVerifier,this.cacheTtl=e?.cacheTtl||6e4,this.maxCacheSize=e?.maxCacheSize??1e3}async verifyDelegationCredential(e,t={}){const r=Date.now();if(!t.skipCache){const t=this.getFromCache(e.id||"");if(t)return{...t,cached:!0}}const n=Date.now(),i=H(e),s=Date.now()-n;if(!i.valid)return{valid:!1,reason:i.reason,stage:"basic",metrics:{basicCheckMs:s,totalMs:Date.now()-r},checks:{basicValid:!1}};const o=t.skipSignature?Promise.resolve({valid:!0,durationMs:0}):async function(e,t,r){const n=Date.now();try{const i="string"==typeof e.issuer?e.issuer:e.issuer.id;if(!t||!r)return{valid:!1,reason:"No DID resolver or signature verifier configured — signature cannot be verified",durationMs:Date.now()-n};const s=await t.resolve(i);if(!s)return{valid:!1,reason:`Could not resolve issuer DID: ${i}`,durationMs:Date.now()-n};if(!e.proof)return{valid:!1,reason:"Proof is missing",durationMs:Date.now()-n};const o=e.proof.verificationMethod;if(!o)return{valid:!1,reason:"Proof missing verificationMethod",durationMs:Date.now()-n};const a=function(e,t){return e.verificationMethod?.find(e=>e.id===t)}(s,o);if(!a)return{valid:!1,reason:`Verification method ${o} not found`,durationMs:Date.now()-n};const c=a.publicKeyJwk;if(!c)return{valid:!1,reason:"Verification method missing publicKeyJwk",durationMs:Date.now()-n};const d=await r(e,c);return{valid:d.valid,reason:d.reason,durationMs:Date.now()-n}}catch(e){return{valid:!1,reason:`Signature verification error: ${e instanceof Error?e.message:"Unknown error"}`,durationMs:Date.now()-n}}}(e,t.didResolver||this.didResolver,this.signatureVerifier),a=!t.skipStatus&&e.credentialStatus?L(e.credentialStatus,t.statusListResolver||this.statusListResolver):Promise.resolve({valid:!0,durationMs:0});return this.finalizeVerification(e,o,a,s,r)}async verifyDelegationJwt(e,t={}){const r=Date.now(),n=function(e,t){const r=O(e);if(!r)return{failure:Ne("Not a valid VC-JWT (parse failed)",t)};const n=Date.now(),i=r.payload.vc,s=H(i,{requireEmbeddedProof:!1}),o=Date.now()-n;return s.valid?function(e){const t=e.issuer;return"string"==typeof t?t:t&&"object"==typeof t&&"string"==typeof t.id?t.id:void 0}(i)!==r.payload.iss?{failure:Ne("Credential `issuer` does not match the JWT `iss` (the verified signer)",t,o)}:{vc:i,issuerDid:r.payload.iss,kid:r.header.kid,basicCheckMs:o}:{failure:Ne(s.reason,t,o)}}(e,r);if("failure"in n)return n.failure;const{vc:i,issuerDid:s,kid:o,basicCheckMs:a}=n;if(!t.skipCache){const e=this.getFromCache(i.id||"");if(e)return{...e,cached:!0}}const c=t.skipSignature?Promise.resolve({valid:!0,durationMs:0}):Oe(e,s,o,t.didResolver||this.didResolver),d=!t.skipStatus&&i.credentialStatus?L(i.credentialStatus,t.statusListResolver||this.statusListResolver):Promise.resolve({valid:!0,durationMs:0});return this.finalizeVerification(i,c,d,a,r)}async finalizeVerification(e,t,r,n,i){const[s,o]=await Promise.all([t,r]),a=function(e,t,r,n){const i=e.valid&&t.valid;return{valid:i,reason:i?void 0:e.reason||t.reason||"Unknown failure",statusOutcome:t.outcome,stage:"complete",metrics:{basicCheckMs:r,signatureCheckMs:e.durationMs||0,statusCheckMs:t.durationMs||0,totalMs:Date.now()-n},checks:{basicValid:!0,signatureValid:e.valid,statusValid:t.valid}}}(s,o,n,i);return a.valid&&e.id&&this.setInCache(e.id,a),a}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){for(;this.cache.size>=this.maxCacheSize&&this.cacheInsertionOrder.length>0;){const e=this.cacheInsertionOrder.shift();e&&this.cache.delete(e)}this.cache.set(e,{result:t,expiresAt:Date.now()+this.cacheTtl}),this.cacheInsertionOrder.push(e)}clearCache(){this.cache.clear(),this.cacheInsertionOrder=[]}clearCacheEntry(e){this.cache.delete(e);const t=this.cacheInsertionOrder.indexOf(e);-1!==t&&this.cacheInsertionOrder.splice(t,1)}}function xe(e){return new Ke(e)}class Me{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],n=t[e];if(n.issuerDid!==r.subjectDid)return{valid:!1,reason:`Invalid chain: ${n.id} issued by ${n.issuerDid} but parent ${r.id} subject is ${r.subjectDid}`};if(n.parentId!==r.id)return{valid:!1,reason:`Invalid chain: ${n.id} parentId=${n.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)}}}function He(e){return new Me(e)}const Le=16777216,je="u";class We{compressor;bits;size;constructor(e,t,r){this.compressor=t,this.size=e;const n=Math.ceil(e/8);this.bits=new Uint8Array(n)}setBit(e,t){if(!Number.isInteger(e)||e<0||e>=this.size)throw new Error(`Bit index ${e} out of range (0-${this.size-1})`);const r=Math.floor(e/8),n=e%8;t?this.bits[r]|=128>>n:this.bits[r]&=255^128>>n}getBit(e){if(!Number.isInteger(e)||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]&128>>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 je+this.base64urlEncode(e)}static async decode(e,t,r){const n=await Ue(e,r),i=8*n.length,s=new We(i,t,r);return s.bits=n,s}getRawBits(){return this.bits}getSize(){return this.size}base64urlEncode(e){return this.bytesToBase64(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}bytesToBase64(e){const t=Array.from(e).map(e=>String.fromCharCode(e)).join("");return btoa(t)}static fromSetBits(e,t,r,n){const i=new We(e,r,n);for(const e of t)i.setBit(e,!0);return i}}async function Ue(e,t){const r=await t.decompress(function(e){let t=(e[0]===je?e.slice(1):e).replace(/-/g,"+").replace(/_/g,"/");t+="=".repeat((4-t.length%4)%4);const r=atob(t),n=new Uint8Array(r.length);for(let e=0;e<r.length;e++)n[e]=r.charCodeAt(e);return n}(e));if(r.length>Le)throw new Error(`Status list too large: ${r.length} bytes exceeds ${Le}`);return r}async function Je(e,t,r){const n=await Ue(e,r),i=Math.floor(t/8),s=t%8;if(!Number.isInteger(t)||t<0||i>=n.length)throw new Error(`Bit index ${t} out of range for the status list`);return!!(n[i]&128>>s)}class Be{storage;identity;signingFunction;compressor;decompressor;statusListBaseUrl;defaultListSize;updateLocks=new Map;constructor(e,t,r,n,i,s){this.storage=e,this.identity=t,this.signingFunction=r,this.compressor=n,this.decompressor=i,this.statusListBaseUrl=s?.statusListBaseUrl||"https://status.example.com",this.defaultListSize=s?.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}=e,n=(this.updateLocks.get(r)??Promise.resolve()).then(()=>this.doUpdateStatus(e,t));this.updateLocks.set(r,n.catch(()=>{})),await n}async doUpdateStatus(e,t){const{statusListCredential:r,statusListIndex:n}=e,i=await this.storage.getStatusList(r);if(!i)throw new Error(`Status list not found: ${r}`);const s=await We.decode(i.credentialSubject.encodedList,this.compressor,this.decompressor),o=parseInt(n,10);s.setBit(o,t);const a=await s.encode(),c={...i,credentialSubject:{...i.credentialSubject,encodedList:a}},d={...c};delete d.proof;const u=T(d),l=await this.signingFunction(u,this.identity.getDid(),this.identity.getKeyId()),h={...c,proof:l};await this.storage.setStatusList(r,h)}async checkStatus(e){const{statusListCredential:t,statusListIndex:r}=e,n=await this.storage.getStatusList(t);if(!n)throw new Error(`Status list not found: ${t} — cannot determine revocation status`);!function(e,t){if("string"!=typeof e)throw new Error(`status list has no statusPurpose (expected "${t}") — fail-closed`);if(e!==t)throw new Error(`status list statusPurpose mismatch: "${e}" ≠ "${t}"`)}(n.credentialSubject.statusPurpose,e.statusPurpose);const i=await We.decode(n.credentialSubject.encodedList,this.compressor,this.decompressor);if(!/^[0-9]+$/.test(r))throw new Error(`Invalid statusListIndex "${r}" — must be a canonical non-negative decimal`);const s=Number(r);if(!Number.isSafeInteger(s))throw new Error(`statusListIndex "${r}" exceeds the safe integer range`);return i.getBit(s)}async getRevokedIndices(e){const t=await this.storage.getStatusList(e);return t?(await We.decode(t.credentialSubject.encodedList,this.compressor,this.decompressor)).getSetBits():[]}async ensureStatusListExists(e,t){if(await this.storage.getStatusList(e))return;const r=new We(this.defaultListSize,this.compressor,this.decompressor),n=await r.encode(),i={"@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:n}},s=T(i),o=await this.signingFunction(s,this.identity.getDid(),this.identity.getKeyId()),a={...i,proof:o};await this.storage.setStatusList(e,a)}getStatusListBaseUrl(){return this.statusListBaseUrl}getDefaultListSize(){return this.defaultListSize}}function Ve(e,t,r,n,i,s){return new Be(e,t,r,n,i,s)}class ze{graph;statusList;constructor(e,t){this.graph=e,this.statusList=t}async revokeDelegation(e,t={}){const r=t.maxDepth||100,n=[],i=await this.graph.getNode(e);if(!i)throw new Error(`Delegation not found: ${e}`);const s=await this.graph.getDepth(e);if(s>r)throw new Error(`Delegation depth ${s} exceeds maximum ${r}`);const o=await this.revokeNode(i,!0,t.reason,t.dryRun);n.push(o),t.onRevoke&&await t.onRevoke(o);const a=await this.graph.getDescendants(e);for(const r of a){const i=await this.revokeNode(r,!1,`Cascaded from ${e}`,t.dryRun,e);n.push(i),t.onRevoke&&await t.onRevoke(i)}return n}async revokeNode(e,t,r,n,i){const s={delegationId:e.id,isRoot:t,parentId:i,timestamp:Date.now(),reason:r};if(n)return s;if(e.credentialStatusId){const t=this.parseCredentialStatus(e.credentialStatusId);t&&await this.statusList.updateStatus(t,!0)}return s}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)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,n]=t;return{id:e,type:"StatusList2021Entry",statusPurpose:"revocation",statusListIndex:parseInt(n,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}}function Fe(e,t){return new ze(e,t)}function qe(e,t){if(!e.constraints.audience)return!0;const r=e.constraints.audience;return"string"==typeof r?r===t:r.includes(t)}class Ge{#e;#t;#r;constructor(e){if(!(e instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this.#e=e}setProtectedHeader(e){return Se(this.#t,"setProtectedHeader"),this.#t=e,this}setUnprotectedHeader(e){return Se(this.#r,"setUnprotectedHeader"),this.#r=e,this}async sign(e,t){if(!this.#t&&!this.#r)throw new Y("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!ce(this.#t,this.#r))throw new Y("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const r={...this.#t,...this.#r};let n=!0;if(Ce(Y,new Map([["b64",!0]]),t?.crit,this.#t,r).has("b64")&&(n=this.#t.b64,"boolean"!=typeof n))throw new Y('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:i}=r;if("string"!=typeof i||!i)throw new Y('JWS "alg" (Algorithm) Header Parameter missing or invalid');let s,o,a,c;_e(i,e,"sign"),n?(s=z(this.#e),o=J(s)):(o=this.#e,s=""),this.#t?(a=z(JSON.stringify(this.#t)),c=J(a)):(a="",c=new Uint8Array);const d=U(c,J("."),o),u=await $e(e,i),l=await async function(e,t,r){const n=await ve(e,t,"sign");me(e,n);const i=await crypto.subtle.sign(we(e,n.algorithm),n,r);return new Uint8Array(i)}(i,u,d),h={signature:z(l),payload:s};return this.#r&&(h.header=this.#r),this.#t&&(h.protected=a),h}}class Ye{#n;constructor(e){this.#n=new Ge(e)}setProtectedHeader(e){return this.#n.setProtectedHeader(e),this}async sign(e,t){const r=await this.#n.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 Xe=e=>Math.floor(e.getTime()/1e3),Qe=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;function Ze(e){const t=Qe.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");const r=parseFloat(t[2]);let n;switch(t[3].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":n=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":n=Math.round(60*r);break;case"hour":case"hours":case"hr":case"hrs":case"h":n=Math.round(3600*r);break;case"day":case"days":case"d":n=Math.round(86400*r);break;case"week":case"weeks":case"w":n=Math.round(604800*r);break;default:n=Math.round(31557600*r)}return"-"===t[1]||"ago"===t[4]?-n:n}function et(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}class tt{#e;constructor(e){if(!ae(e))throw new TypeError("JWT Claims Set MUST be an object");this.#e=structuredClone(e)}data(){return j.encode(JSON.stringify(this.#e))}get iss(){return this.#e.iss}set iss(e){this.#e.iss=e}get sub(){return this.#e.sub}set sub(e){this.#e.sub=e}get aud(){return this.#e.aud}set aud(e){this.#e.aud=e}set jti(e){this.#e.jti=e}set nbf(e){"number"==typeof e?this.#e.nbf=et("setNotBefore",e):e instanceof Date?this.#e.nbf=et("setNotBefore",Xe(e)):this.#e.nbf=Xe(new Date)+Ze(e)}set exp(e){"number"==typeof e?this.#e.exp=et("setExpirationTime",e):e instanceof Date?this.#e.exp=et("setExpirationTime",Xe(e)):this.#e.exp=Xe(new Date)+Ze(e)}set iat(e){void 0===e?this.#e.iat=Xe(new Date):e instanceof Date?this.#e.iat=et("setIssuedAt",Xe(e)):this.#e.iat=et("setIssuedAt","string"==typeof e?Xe(new Date)+Ze(e):e)}}class rt{#t;#i;constructor(e={}){this.#i=new tt(e)}setIssuer(e){return this.#i.iss=e,this}setSubject(e){return this.#i.sub=e,this}setAudience(e){return this.#i.aud=e,this}setJti(e){return this.#i.jti=e,this}setNotBefore(e){return this.#i.nbf=e,this}setExpirationTime(e){return this.#i.exp=e,this}setIssuedAt(e){return this.#i.iat=e,this}setProtectedHeader(e){return this.#t=e,this}async sign(e,t){const r=new Ye(this.#i.data());if(r.setProtectedHeader(this.#t),Array.isArray(this.#t?.crit)&&this.#t.crit.includes("b64")&&!1===this.#t.b64)throw new X("JWTs MUST NOT use unencoded payload");return r.sign(e,t)}}async function nt(e){const{agentDid:t,userDid:r,delegationId:n,delegationChain:i,scopes:s,privateKeyJwk:o,kid:a,targetHostname:c}=e,d=await ue(o,"EdDSA"),u=Math.floor(Date.now()/1e3),l=u+60;return await new rt({delegation_id:n,delegation_chain:i,scope:s.join(",")}).setProtectedHeader({alg:"EdDSA",kid:a}).setIssuer(t).setSubject(r).setJti(crypto.randomUUID()).setAudience(c).setIssuedAt(u).setExpirationTime(l).sign(d)}function it(e){return e.id||e.vcId?e.vcId?`${e.vcId}>${e.id}`:e.id:""}const st="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",ot=new Map;for(let e=0;e<st.length;e++){const t=st[e];void 0!==t&&ot.set(t,e)}function at(e){if(0===e.length)return"";let t=BigInt(0);for(let r=0;r<e.length;r++){const n=e[r];void 0!==n&&(t=t*BigInt(256)+BigInt(n))}let r="";for(;t>0;)r=st[Number(t%BigInt(58))]+r,t/=BigInt(58);for(let t=0;t<e.length&&0===e[t];t++)r="1"+r;return r}function ct(e){if(0===e.length)return new Uint8Array(0);let t=BigInt(0);for(const r of e){const e=ot.get(r);if(void 0===e)throw new Error(`Invalid base58 character: ${r}`);t=t*BigInt(58)+BigInt(e)}const r=[];for(;t>0;)r.unshift(Number(t%BigInt(256))),t/=BigInt(256);let n=0;for(const t of e){if("1"!==t)break;n++}const i=new Uint8Array(n+r.length);return i.set(r,n),i}function dt(e){if(0===e.length)return!0;for(const t of e)if(!ot.has(t))return!1;return!0}function ut(e){return"string"==typeof e&&e.startsWith("did:")}function lt(e){if(!ut(e))return null;const t=e.match(/^did:([^:]+):/);return t?.[1]??null}function ht(e){return e.trim()}function ft(e,t){return ht(e)===ht(t)}function pt(e){const t=e.identity.serverDid||e.identity.agentDid;if(!t)throw new Error("Server DID not configured");return t}function gt(e){const t=e.split(":");return t[t.length-1]??e}function yt(e){return gt(e)}const mt=new Uint8Array([237,1]);function wt(e){const t=new Uint8Array(mt.length+e.length);return t.set(mt),t.set(e,mt.length),`did:key:z${at(t)}`}function vt(e){return wt(Uint8Array.from(atob(e),e=>e.charCodeAt(0)))}function St(e){return e.startsWith("did:key:")?e.slice(8):"keys-1"}const bt={debug:10,info:20,warn:30,error:40};function Dt(){let e="info",t=!1;function r(r,...n){if(function(t){return bt[t]>=bt[e]}(r))if(t)console.error(...n);else switch(r){case"debug":"function"==typeof console.debug?console.debug(...n):console.log(...n);break;case"info":"function"==typeof console.info?console.info(...n):console.log(...n);break;case"warn":"function"==typeof console.warn?console.warn(...n):console.error(...n);break;case"error":console.error(...n)}}return{configure(r={}){r.level&&(e=r.level),!0===r.forceStderr?t=!0:!1===r.forceStderr?t=!1:"stdio"===r.transport?t=!0:"sse"!==r.transport&&"http"!==r.transport||(t=!1)},debug:(...e)=>r("debug",...e),info:(...e)=>r("info",...e),warn:(...e)=>r("warn",...e),error:(...e)=>r("error",...e)}}const Et=Dt(),It=new Uint8Array([237,1]),At=32;function kt(e){return e.startsWith("did:key:z6Mk")}function _t(e){if(!e.startsWith("did:key:z"))return null;try{const t=ct(e.replace("did:key:","").slice(1));return t.length<It.length+At||t[0]!==It[0]||t[1]!==It[1]?null:t.slice(It.length)}catch(e){return Et.debug("Failed to extract public key from did:key",e),null}}function Ct(e){return{kty:"OKP",crv:"Ed25519",x:c(e)}}function Pt(){return{resolve:async e=>{if(!kt(e))return null;const t=_t(e);if(!t)return null;const r=Ct(t),n=e.replace("did:key:",""),i=St(e);return{id:e,verificationMethod:[{id:`${e}#${i}`,type:"Ed25519VerificationKey2020",controller:e,publicKeyJwk:r,publicKeyMultibase:n}],authentication:[`${e}#${i}`],assertionMethod:[`${e}#${i}`]}}}}function Tt(e){if(!kt(e))return null;const t=_t(e);if(!t)return null;const r=Ct(t),n=e.replace("did:key:",""),i=St(e);return{id:e,verificationMethod:[{id:`${e}#${i}`,type:"Ed25519VerificationKey2020",controller:e,publicKeyJwk:r,publicKeyMultibase:n}],authentication:[`${e}#${i}`],assertionMethod:[`${e}#${i}`]}}const Rt={AGENT_DID:"KYA-OS-Agent-DID",DELEGATION_CHAIN:"KYA-OS-Delegation-Chain",SESSION_ID:"KYA-OS-Session-Id",DELEGATION_PROOF:"KYA-OS-Delegation-Proof"};async function $t(e){const{session:t,delegation:r,serverIdentity:n,targetUrl:i}=e;if(!t.agentDid)throw new Error("Session must have agentDid for outbound delegation");if(!t.sessionId)throw new Error("Session must have sessionId for outbound delegation");if(!r.vcId)throw new Error("Delegation must have vcId for outbound delegation");const s=function(e){try{return new URL(e).hostname}catch{return Et.warn("Failed to parse target URL, using as-is",{url:e}),e}}(i),o=function(e,t){const r=u(e),n=64===r.length?r.subarray(0,32):r;if(!kt(t))throw new Error(`Server DID must be did:key with Ed25519: ${t}`);const i=_t(t);if(!i)throw new Error(`Failed to extract public key from DID: ${t}`);return{kty:"OKP",crv:"Ed25519",x:c(i),d:c(n)}}(n.privateKey,n.did),a=await nt({agentDid:n.did,userDid:t.agentDid,delegationId:r.id,delegationChain:r.vcId,scopes:["delegation:propagate"],privateKeyJwk:o,kid:n.kid,targetHostname:s});return Et.debug("Built outbound delegation headers",{agentDid:t.agentDid,delegationChain:r.vcId,sessionId:t.sessionId,targetHostname:s}),{"KYA-OS-Agent-DID":t.agentDid,"KYA-OS-Delegation-Chain":r.vcId,"KYA-OS-Session-Id":t.sessionId,"KYA-OS-Delegation-Proof":a}}class Nt{cryptoProvider;constructor(e){this.cryptoProvider=e}async verifyEd25519(e,t,r){try{return!0===await this.cryptoProvider.verify(e,t,r)}catch(e){return Et.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,n,i]=t;let a,c,d;try{a=JSON.parse(s(r))}catch(e){throw new Error(`Invalid header base64: ${e instanceof Error?e.message:String(e)}`)}if(n)try{c=JSON.parse(s(n))}catch(e){throw new Error(`Invalid payload base64: ${e instanceof Error?e.message:String(e)}`)}try{d=o(i)}catch(e){throw new Error(`Invalid signature base64: ${e instanceof Error?e.message:String(e)}`)}return{header:a,payload:c,signatureBytes:d,signingInput:`${r}.${n}`}}async verifyJWS(e,t,r){try{if(!this.isValidEd25519JWK(t))return Et.error("[CryptoService] Invalid Ed25519 JWK format"),!1;if(r?.expectedKid&&t.kid!==r.expectedKid)return Et.error("[CryptoService] Key ID mismatch"),!1;let n;try{n=this.parseJWS(e)}catch(t){if(void 0===r?.detachedPayload)return Et.error("[CryptoService] Invalid JWS format:",t),!1;{const r=e.split(".");if(3!==r.length||""!==r[1])return Et.error("[CryptoService] Invalid JWS format:",t),!1;try{const e=r[0],t=r[2];n={header:JSON.parse(s(e)),payload:void 0,signatureBytes:o(t),signingInput:""}}catch{return Et.error("[CryptoService] Invalid detached JWS format"),!1}}}const i=r?.alg||"EdDSA";if(n.header.alg!==i)return Et.error(`[CryptoService] Unsupported algorithm: ${n.header.alg}, expected ${i}`),!1;let a,d;if(void 0!==r?.detachedPayload){const t=e.split(".")[0];let n;n=r.detachedPayload instanceof Uint8Array?c(r.detachedPayload):c((new TextEncoder).encode(r.detachedPayload)),a=(new TextEncoder).encode(`${t}.${n}`)}else{if(!n.signingInput)return Et.error("[CryptoService] Missing signing input for compact JWS"),!1;a=(new TextEncoder).encode(n.signingInput)}try{d=this.jwkToBase64PublicKey(t)}catch(e){return Et.error("[CryptoService] Failed to extract public key:",e),!1}return await this.verifyEd25519(a,n.signatureBytes,d)}catch(e){return Et.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=o(e.x);if(32!==t.length)throw new Error(`Invalid Ed25519 public key length: ${t.length}`);return d(t)}}const Ot=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]),Kt=12,xt=32,Mt="org.kya-os/proof",Ht="proof";async function Lt(e,t,r){const n={method:e.method,...e.params?{params:e.params}:{}},i=await r((new TextEncoder).encode((0,P.d)(n)));return void 0===t?{requestHash:i}:{requestHash:i,responseHash:await r((new TextEncoder).encode((0,P.d)(t.data)))}}class jt{identity;cryptoProvider;constructor(e,t){this.identity=e,this.cryptoProvider=t}async generateProof(e,t,r,n={}){const i=await this.generateCanonicalHashes(e,t),s={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,...void 0!==i.responseHash?{responseHash:i.responseHash}:{},...n};return{jws:await this.generateJWS(s),meta:s}}async hashRequest(e){return(await this.generateCanonicalHashes(e)).requestHash}async generateCanonicalHashes(e,t){return Lt(e,t,e=>this.cryptoProvider.hash(e))}async resolveSigningKey(){const e=this.identity.privateKey;return"string"==typeof e?async function(e){if("string"!=typeof e||0!==e.indexOf("-----BEGIN PRIVATE KEY-----"))throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return ne(e,"EdDSA",void 0)}(this.formatPrivateKeyAsPEM(e)):e}async generateJWS(e){try{const t=await this.resolveSigningKey(),r={aud:e.audience,sub:e.did,iss:e.did,requestHash:e.requestHash,...void 0!==e.responseHash&&{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},...e.outcome&&{outcome:e.outcome},...e.reason&&{reason:e.reason}},n=(0,P.d)(r),i=(new TextEncoder).encode(n);return await new Ye(i).setProtectedHeader({alg:"EdDSA",kid:this.identity.kid}).sign(t)}catch(e){throw new Error(`Failed to generate JWS: ${e instanceof Error?e.message:"Unknown error"}`)}}formatPrivateKeyAsPEM(e){const t=u(e).subarray(0,xt),r=new Uint8Array(Ot.length+t.length);r.set(Ot),r.set(t,Ot.length);const n=d(r);return"-----BEGIN PRIVATE KEY-----\n"+(n.match(/.{1,64}/g)?.join("\n")??n)+"\n-----END PRIVATE KEY-----"}async verifyProof(e,t,r){try{const n=await this.generateCanonicalHashes(t,r);if(e.meta.requestHash!==n.requestHash)return!1;if(void 0!==e.meta.responseHash&&(void 0===n.responseHash||e.meta.responseHash!==n.responseHash))return!1;const i=this.base64PublicKeyToJWK(this.identity.publicKey);return new Nt(this.cryptoProvider).verifyJWS(e.jws,i,{expectedKid:this.identity.kid,alg:"EdDSA"})}catch{return!1}}base64PublicKeyToJWK(e){const t=u(e);if(t.length!==xt)throw new Error(`Invalid Ed25519 public key length: ${t.length}`);return{kty:"OKP",crv:"Ed25519",x:c(t),kid:this.identity.kid}}}async function Wt(e,t,r,n,i,s={}){const o={data:t},a=new jt(r,i),c=await a.generateProof(e,o,n,s);return o.meta={proof:c},o}function Ut(e,t){return{request:{method:e.method,...e.params?{params:e.params}:{}},response:t.data}}const Jt="_kyaos";function Bt(e){return e.startsWith(Jt)}function Vt(e,t){const r={};for(const[e,n]of Object.entries(t))Bt(e)||(r[e]=n);return{method:e,params:r}}async function zt(e){const{identity:t,crypto:r,toolName:n,args:i,audience:s,sessionId:o}=e,a=new jt(t,r),d=Vt(n,i),u=c(await r.randomBytes(16)),l=Math.floor(Date.now()/1e3);return a.generateProof(d,void 0,{sessionId:o??"",audience:s,nonce:u,timestamp:l,createdAt:l,lastActivity:l,ttlMinutes:30,identityState:"anonymous"})}const Ft="holder_binding_failed";function qt(e){return null!==_t(e)}async function Gt(e){const{proof:t,subjectDid:r,request:n,response:i,expectedAudience:s,proofVerifier:o}=e,a=_t(r);if(!a)return{status:"not_applicable",reason:`Holder binding (phase 1) covers did:key subjects only; "${lt(r)??"unknown"}" is deferred to cnf-based binding`};if("object"!=typeof t?.meta||null===t.meta)return{status:"unbound",errorCode:Ft,reason:"Malformed proof: missing meta"};if(t.meta.did!==r)return{status:"unbound",errorCode:Ft,reason:"Proof subject does not match the delegation subject"};if(void 0!==s&&!(Array.isArray(s)?s:[s]).includes(t.meta.audience))return{status:"unbound",errorCode:Ft,reason:"Proof audience does not match this server",cause:"audience_mismatch"};const c=Ct(a);c.kid=`${r}#${St(r)}`;const d=await o.verifyProof(t,c,{request:n,...void 0!==i?{response:i}:{}});return d.valid?{status:"bound"}:{status:"unbound",errorCode:Ft,reason:"Request proof is not bound to the delegation subject",...void 0!==d.errorCode?{cause:d.errorCode}:{}}}class Yt{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())}}class Xt{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],n=new Set;for(;r.length>0;){const e=r.shift();if(n.has(e))continue;n.add(e);const i=this.nodes.get(e);if(i)for(const e of i.children)if(!n.has(e)){r.push(e);const n=this.nodes.get(e);n&&t.push(n)}}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 n=0;for(const t of e){const e=this.getChainSync(t.id);n=Math.max(n,e.length-1)}return{totalNodes:e.length,rootNodes:t,leafNodes:r,maxDepth:n}}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}}function Qt(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.id&&0!==t.id.length&&"string"==typeof t.type&&0!==t.type.length&&"string"==typeof t.controller&&0!==t.controller.length}function Zt(e){return e.startsWith("did:web:")}function er(e){if(!Zt(e))return null;const t=e.slice(8);if(0===t.length)return null;const r=t.split(":"),n=decodeURIComponent(r[0]);return 0===n.length?null:{domain:n,path:r.slice(1).map(e=>decodeURIComponent(e))}}function tr(e){const t=er(e);if(!t)return null;const{domain:r,path:n}=t;let i=`https://${r}`;return 0===n.length?i+="/.well-known/did.json":i+="/"+n.join("/")+"/did.json",i}class rr{fetchProvider;cache;cacheTtl;constructor(e,t){this.fetchProvider=e,this.cache=new Map,this.cacheTtl=t?.cacheTtl??3e5}async resolve(e){if(!Zt(e))return null;const t=this.cache.get(e);if(t&&Date.now()<t.expiresAt)return t.document;const r=tr(e);if(!r)return Et.warn(`[DidWebResolver] Invalid did:web format: ${e}`),null;try{const t=await this.fetchProvider.fetch(r);if(!t.ok)return Et.warn(`[DidWebResolver] HTTP ${t.status} fetching ${r}`),null;let n;try{n=await t.json()}catch{return Et.warn(`[DidWebResolver] Invalid JSON from ${r}`),null}return function(e){if("object"!=typeof e||null===e)return!1;const t=e;if("string"!=typeof t.id||0===t.id.length)return!1;if(void 0!==t.verificationMethod){if(!Array.isArray(t.verificationMethod))return!1;for(const e of t.verificationMethod)if(!Qt(e))return!1}return!0}(n)?n.id!==e?(Et.warn(`[DidWebResolver] DID Document id mismatch: expected ${e}, got ${n.id}`),null):(this.cache.set(e,{document:n,expiresAt:Date.now()+this.cacheTtl}),n):(Et.warn(`[DidWebResolver] Invalid DID Document structure from ${r}`),null)}catch(t){return Et.warn(`[DidWebResolver] Error resolving ${e}: ${t instanceof Error?t.message:"Unknown error"}`),null}}clearCache(){this.cache.clear()}clearCacheEntry(e){this.cache.delete(e)}}function nr(e,t){return new rr(e,t)}const ir=new Uint8Array([237,1]),sr=["https://www.w3.org/ns/did/v1","https://w3id.org/security/suites/ed25519-2020/v1"];function or(e,t){const r=Array.isArray(e)?e:[e],n=r[0];if(!n)throw new Error("buildDidWebDocument: at least one identity is required");const i=n.did;if(!Zt(i))throw new Error(`buildDidWebDocument: identity.did must be a did:web DID (got "${i}")`);const s=r.map(e=>function(e,t){if(e.did!==t)throw new Error(`buildDidWebDocument: all identities must share one DID; got "${e.did}" alongside "${t}"`);if(!e.kid.startsWith(`${t}#`))throw new Error(`buildDidWebDocument: identity.kid "${e.kid}" does not reference identity.did "${t}"`);const r=function(e){const t=u(e);if(32!==t.length)throw new Error(`buildDidWebDocument: expected 32-byte Ed25519 public key, got ${t.length} bytes after base64 decode`);return t}(e.publicKey);return{id:e.kid,type:"Ed25519VerificationKey2020",controller:t,publicKeyJwk:Ct(r),publicKeyMultibase:ar(r)}}(e,i)),o=s.map(e=>e.id);if(new Set(o).size!==o.length)throw new Error("buildDidWebDocument: every key needs a unique verification-method id (kid); got a duplicate");return{"@context":t?.additionalContexts?.length?[...sr,...t.additionalContexts]:[...sr],id:i,...t?.alsoKnownAs?.length?{alsoKnownAs:[...t.alsoKnownAs]}:{},verificationMethod:s,authentication:o,assertionMethod:o}}function ar(e){const t=new Uint8Array(ir.length+e.length);return t.set(ir),t.set(e,ir.length),`z${at(t)}`}function cr(e){const t=e.requireBidirectional??!0,r=ur(e.primaryDid),n=ur(e.secondaryDid),i=e.primaryDidDocument,s=e.secondaryDidDocument,o={primaryReferencesSecondary:!1,secondaryReferencesPrimary:!1,primaryDocumentMatches:!1,secondaryDocumentMatches:!1};return lr(i)?lr(s)?(o.primaryDocumentMatches=ur(i.id)===r,o.secondaryDocumentMatches=ur(s.id)===n,o.primaryDocumentMatches&&o.secondaryDocumentMatches?(o.primaryReferencesSecondary=dr(i,n),o.secondaryReferencesPrimary=dr(s,r),t?o.primaryReferencesSecondary&&o.secondaryReferencesPrimary?{valid:!0,checks:o}:{valid:!1,reason:"Bidirectional alsoKnownAs linkage is not present",checks:o}:o.primaryReferencesSecondary||o.secondaryReferencesPrimary?{valid:!0,checks:o}:{valid:!1,reason:"No alsoKnownAs linkage is present",checks:o}):{valid:!1,reason:"DID Document id does not match expected DID",checks:o}):{valid:!1,reason:"Secondary DID Document is missing or malformed",checks:o}:{valid:!1,reason:"Primary DID Document is missing or malformed",checks:o}}function dr(e,t){return(e.alsoKnownAs??[]).some(e=>ur(e)===t)}function ur(e){return e.trim()}function lr(e){return!!function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}(e)&&"string"==typeof e.id&&0!==e.id.trim().length&&(void 0===e.alsoKnownAs||Array.isArray(e.alsoKnownAs)&&e.alsoKnownAs.every(e=>"string"==typeof e))}function hr(e,t){const r={};if(!e)return r;for(const[n,i]of Object.entries(e))/^[a-z0-9]+$/.test(n)&&("function"!=typeof i?r[n]=i:t&&(r[n]=i(t)));return r}class fr{tokens=new Map;ttl;constructor(e=6e5){this.ttl=e}async create(e,t,r){const n=new Uint8Array(16);globalThis.crypto.getRandomValues(n);const i=`rt_${Array.from(n).map(e=>e.toString(16).padStart(2,"0")).join("")}`,s=Date.now();return this.tokens.set(i,{agentDid:e,scopes:t,createdAt:s,expiresAt:s+this.ttl,metadata:r,fulfilled:!1}),i}async get(e){const t=this.tokens.get(e);return t?Date.now()>t.expiresAt?(this.tokens.delete(e),null):t.fulfilled?null:{agentDid:t.agentDid,scopes:t.scopes,createdAt:t.createdAt,expiresAt:t.expiresAt,metadata:t.metadata}:null}async fulfill(e){const t=this.tokens.get(e);t&&(t.fulfilled=!0)}clear(){this.tokens.clear()}}async function pr(e,t,r){const n=Date.now();let i,s;if(r.debug&&Et.debug(`[AuthHandshake] Verifying ${e} for scopes: ${t.join(", ")}`),r.reputationService&&void 0!==r.authorization.minReputationScore){const n=r.authorization.unknownAgentPolicy??"require-consent";try{i=await async function(e,t){const r=t.apiUrl.replace(/\/$/,""),n={"Content-Type":"application/json"};let i;if(t.apiKey&&(n["X-API-Key"]=t.apiKey),i="v2"===t.apiFormat?await fetch(`${r}/v1/reputation/${encodeURIComponent(e)}`,{method:"POST",headers:n,body:JSON.stringify({include_details:!1})}):await fetch(`${r}/api/v1/reputation/${encodeURIComponent(e)}`,{method:"GET",headers:n}),!i.ok){if(404===i.status)return{agentDid:e,score:null,totalInteractions:0,successRate:0,riskLevel:"unknown",updatedAt:Date.now()};throw new Error(`Reputation API error: ${i.status} ${i.statusText}`)}const s=await i.json(),o=s.score??0,a=(s.level??s.riskLevel??"unknown").toLowerCase(),c="low"===a||"medium"===a||"high"===a?a:"unknown";return{agentDid:s.agent_did??s.agentDid??e,score:o,totalInteractions:s.totalInteractions??0,successRate:s.successRate??0,riskLevel:c,updatedAt:s.calculatedAt?new Date(s.calculatedAt).getTime():s.updatedAt??Date.now()}}(e,r.reputationService)}catch(t){Et.error("[AuthHandshake] Reputation service unreachable, treating agent as unknown:",t),i={agentDid:e,score:null,totalInteractions:0,successRate:0,riskLevel:"unknown",updatedAt:Date.now()}}if(r.debug&&Et.debug(`[AuthHandshake] Reputation score: ${i.score}`),null===i.score){if("deny"===n)return{authorized:!1,authError:await gr(e,t,r,"Unknown agent denied by policy"),reputation:i,reason:"Unknown agent — policy: deny"};if("require-consent"===n)return{authorized:!1,authError:await gr(e,t,r,"Unknown agent requires consent"),reputation:i,reason:"Unknown agent — policy: require-consent"};r.debug&&Et.debug("[AuthHandshake] Unknown agent allowed by policy, skipping reputation gate")}if(null!==i.score&&i.score<r.authorization.minReputationScore)return r.debug&&Et.debug(`[AuthHandshake] Reputation ${i.score} < ${r.authorization.minReputationScore}, requiring authorization`),{authorized:!1,authError:await gr(e,t,r,"Agent reputation score below threshold"),reputation:i,reason:"Low reputation score"}}try{s=await r.delegationVerifier.verify(e,t)}catch(n){Et.error("[AuthHandshake] Delegation verification failed:",n);const i=`Delegation verification error: ${n instanceof Error?n.message:"Unknown error"}`;return{authorized:!1,authError:await gr(e,t,r,i),reason:i}}return s.valid&&s.delegation?(r.debug&&Et.debug(`[AuthHandshake] Delegation valid, authorized (${Date.now()-n}ms)`),{authorized:!0,delegation:s.delegation,credential:s.credential,reputation:i,reason:"Valid delegation found"}):(r.debug&&Et.debug(`[AuthHandshake] No delegation found, returning needs_authorization (${Date.now()-n}ms)`),{authorized:!1,authError:await gr(e,t,r,s.reason??"No valid delegation found"),reputation:i,reason:s.reason??"No delegation"})}async function gr(e,t,r,n){const i=await r.resumeTokenStore.create(e,t,{requestedAt:Date.now()}),s=Date.now()+(r.authorization.resumeTokenTtl??6e5),o=new URL(r.authorization.authorizationUrl);o.searchParams.set("agent_did",e),o.searchParams.set("scopes",t.join(",")),o.searchParams.set("resume_token",i);const a={title:"Authorization Required",hint:["link","qr"],authorizationCode:i.substring(0,8).toUpperCase(),qrUrl:`https://api.qrserver.com/v1/create-qr-code/?data=${encodeURIComponent(o.toString())}`};return E({message:n,authorizationUrl:o.toString(),resumeToken:i,expiresAt:s,scopes:t,display:a})}function yr(e){const t=["write","delete","admin","payment","transfer","execute","modify"];return e.some(e=>t.some(t=>e.toLowerCase().includes(t)))}const mr={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",CONTENT_BINDING_MISMATCH:"CONTENT_BINDING_MISMATCH",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",META_POLICY_VIOLATION:"META_POLICY_VIOLATION",VERIFICATION_ERROR:"VERIFICATION_ERROR",INTERNAL_ERROR:"INTERNAL_ERROR"};class wr extends Error{code;details;constructor(e,t,r){super(t),this.code=e,this.details=r,this.name="ProofVerificationError"}}function vr(e,t,r){return new wr(e,t,r)}const Sr=120,br=30,Dr=600;class Er{cryptoService;clock;nonceCache;fetch;timestampSkewSeconds;nonceTtlSeconds;cryptoProvider;constructor(e){this.cryptoService=new Nt(e.cryptoProvider),this.cryptoProvider=e.cryptoProvider,this.clock=e.clockProvider,this.nonceCache=e.nonceCacheProvider,this.fetch=e.fetchProvider,this.timestampSkewSeconds=e.timestampSkewSeconds??Sr,this.nonceTtlSeconds=e.nonceTtlSeconds??300}setTimestampSkew(e){"number"==typeof e&&Number.isFinite(e)&&(this.timestampSkewSeconds=Math.max(br,Math.min(Dr,Math.floor(e))))}getTimestampSkew(){return this.timestampSkewSeconds}async verifyProof(e,t,r){try{const n=this.buildCanonicalPayload(e.meta),i=(new TextEncoder).encode(n);return await this.runVerificationPipeline(e,t,i,r)}catch(e){return this.handleVerificationError(e)}}async verifyProofDetached(e,t,r){try{const n=t instanceof Uint8Array?t:(new TextEncoder).encode(t);return await this.runVerificationPipeline(e,r,n)}catch(e){return this.handleVerificationError(e)}}async runVerificationPipeline(e,t,r,n){const i=await this.validateProofStructure(e);if(!i.valid)return i;const s=i.proof,o=await this.validateNonce(s.meta.nonce,s.meta.did);if(!o.valid)return o;const a=await this.validateTimestamp(s.meta.ts);if(!a.valid)return a;const c=await this.verifySignature(s.jws,t,r,s.meta.kid);if(!c.valid)return c;if(void 0!==n){const e=await this.validateContentBinding(s,n);if(!e.valid)return e}return await this.addNonceToCache(s.meta.nonce,s.meta.did),{valid:!0}}async validateContentBinding(e,t){const{requestHash:r,responseHash:n}=await Lt(t.request,t.response,e=>this.cryptoProvider.hash(e));if(e.meta.requestHash!==r)return{valid:!1,reason:"Request hash mismatch: the proof does not bind the request you supplied",errorCode:mr.CONTENT_BINDING_MISMATCH};const i=void 0!==e.meta.responseHash;return i!==(void 0!==t.response)?{valid:!1,reason:i?"Proof binds a response (responseHash present) but no response was supplied to verify against — pass expected.response":"A response was supplied but the proof binds none — content/proof mismatch",errorCode:mr.CONTENT_BINDING_MISMATCH}:i&&e.meta.responseHash!==n?{valid:!1,reason:"Response hash mismatch: received content differs from what the server signed (possible substitution / MITM)",errorCode:mr.CONTENT_BINDING_MISMATCH}:{valid:!0}}handleVerificationError(e){return{valid:!1,reason:"Proof verification error",errorCode:mr.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=C(e);return t.success?{valid:!0,proof:t.data}:{valid:!1,reason:"Invalid proof structure",errorCode:mr.INVALID_PROOF_STRUCTURE,error:new Error(`Proof validation failed: ${t.error?.message}`),details:{validationError:t.error?.message}}}async validateNonce(e,t){return await this.nonceCache.has(e,t)?{valid:!1,reason:"Nonce already used (replay attack detected)",errorCode:mr.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:mr.TIMESTAMP_SKEW_EXCEEDED,details:{timestamp:e,timestampMs:t,skewSeconds:this.timestampSkewSeconds,currentTime:this.clock.now()}}}async verifySignature(e,t,r,n){return await this.cryptoService.verifyJWS(e,t,{detachedPayload:r,expectedKid:n,alg:"EdDSA"})?{valid:!0}:{valid:!1,reason:"Invalid JWS signature",errorCode:mr.INVALID_JWS_SIGNATURE,details:{jwsLength:e.length,expectedKid:n,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 wr(mr.DID_DOCUMENT_NOT_FOUND,`DID document not found: ${e}`,{did:e});const n=r;if(!n.verificationMethod||0===n.verificationMethod.length)throw new wr(mr.VERIFICATION_METHOD_NOT_FOUND,`No verification methods found in DID document: ${e}`,{did:e});let i;if(t){const r=t.startsWith("#")?t:`#${t}`;if(i=n.verificationMethod.find(t=>t.id===r||t.id===`${e}${r}`),!i)throw new wr(mr.VERIFICATION_METHOD_NOT_FOUND,`Verification method not found for kid: ${t}`,{did:e,kid:t,availableKids:n.verificationMethod.map(e=>e.id)})}else i=n.verificationMethod[0];if(!i?.publicKeyJwk)throw new wr(mr.PUBLIC_KEY_NOT_FOUND,"Public key JWK not found in verification method",{did:e,kid:t,verificationMethodId:i?.id});const s=i.publicKeyJwk;if("OKP"!==s.kty||"Ed25519"!==s.crv||!s.x)throw new wr(mr.INVALID_JWK_FORMAT,`Unsupported key type or curve: kty=${s.kty}, crv=${s.crv}`,{did:e,kid:t,jwk:{kty:s.kty,crv:s.crv}});const o=s;return!o.kid&&i.id&&(o.kid=i.id),o}catch(r){if(r instanceof wr)throw r;throw Et.error("[ProofVerifier] Failed to fetch public key from DID",{error:r}),new wr(mr.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,...void 0!==e.responseHash&&{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},...e.outcome&&{outcome:e.outcome},...e.reason&&{reason:e.reason}};return(0,P.d)(t)}}const Ir=["io.modelcontextprotocol/"],Ar=["traceparent","tracestate","baggage"];function kr(e){return Ar.includes(e)||Ir.some(t=>e.startsWith(t))}function _r(e,t="strict"){const r=Object.keys(e).filter(e=>e!==Mt&&e!==Ht);return"allow-extensions"===t&&r.length>0?{valid:!0,extraKeys:r}:{valid:!0}}function Cr(e,t="strict"){const r=e[Mt]??e[Ht];if(!r)return{success:!1,reason:"_meta does not contain a proof",errorCode:mr.MISSING_REQUIRED_FIELD};_r(e,t);const n=C(r);return n.success?{success:!0,proof:n.data}:{success:!1,reason:n.error?.message??"Invalid proof structure",errorCode:mr.INVALID_PROOF_STRUCTURE}}class Pr{}class Tr{}class Rr{}class $r{}class Nr{}class Or{}class Kr extends $r{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}}class xr extends Nr{nonces=new Map;async has(e,t){const r=t?`nonce:${t}:${e}`:`nonce:${e}`,n=this.nonces.get(r);return!(!n||Date.now()>n&&(this.nonces.delete(r),1))}async add(e,t,r){const n=r?`nonce:${r}:${e}`:`nonce:${e}`,i=Date.now()+1e3*t;this.nonces.set(n,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()}}class Mr extends Or{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}#${St(t)}`,privateKey:e.privateKey,publicKey:e.publicKey,createdAt:(new Date).toISOString(),type:"development"}}generateDIDFromPublicKey(e){return vt(e)}}class Hr{}class Lr extends Hr{sessions=new Map;insertionOrder=[];maxSessions;constructor(e={}){super(),this.maxSessions=e.maxSessions??1e4}async get(e){return this.sessions.get(e)}async set(e,t){this.sessions.has(e)||(this.evictIfNeeded(),this.insertionOrder.push(e)),this.sessions.set(e,t)}async delete(e){this.sessions.delete(e)}async entries(){return[...this.sessions.entries()]}async cleanup(){this.insertionOrder=this.insertionOrder.filter(e=>this.sessions.has(e))}async clear(){this.sessions.clear(),this.insertionOrder=[]}size(){return this.sessions.size}evictIfNeeded(){for(;this.sessions.size>=this.maxSessions&&this.insertionOrder.length>0;){const e=this.insertionOrder.shift();void 0!==e&&this.sessions.delete(e)}}}class jr{config;cryptoProvider;sessionStore;constructor(e,t={}){this.cryptoProvider=e,this.sessionStore=t.sessionStore??new Lr({maxSessions:t.maxSessions??1e4}),this.config={timestampSkewSeconds:t.timestampSkewSeconds??120,sessionTtlMinutes:t.sessionTtlMinutes??30,nonceCache:t.nonceCache??new xr,metaPolicy:t.metaPolicy??"strict",...void 0!==t.absoluteSessionLifetime&&{absoluteSessionLifetime:t.absoluteSessionLifetime},...void 0!==t.serverDid&&{serverDid:t.serverDid}},this.config.nonceCache instanceof xr&&Et.warn("[SessionManager] Using MemoryNonceCacheProvider — not suitable for multi-instance deployments. Use Redis, DynamoDB, or Cloudflare KV for production.")}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:n.handshake_failed,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 timestampSkewSeconds if needed.`}};if(this.config.serverDid&&e.audience!==this.config.serverDid)return{success:!1,error:{code:n.handshake_failed,message:`Audience mismatch: expected ${this.config.serverDid}, got ${e.audience}`}};if(await this.config.nonceCache.has(e.nonce,e.agentDid))return{success:!1,error:{code:n.handshake_failed,message:"Nonce already used (replay attack prevention)",remediation:"Generate a new unique nonce for each request"}};const i=e.agentDid?b:D,s=Math.ceil(i/1e3);await this.config.nonceCache.add(e.nonce,s,e.agentDid);const o=await this.generateSessionId(),a=await this.buildClientInfo(e),c={sessionId:o,audience:e.audience,nonce:e.nonce,timestamp:e.timestamp,createdAt:t,lastActivity:t,ttlMinutes:this.config.sessionTtlMinutes,identityState:"anonymous",metaPolicy:this.config.metaPolicy,agentDid:e.agentDid,...this.config.serverDid&&{serverDid:this.config.serverDid},...a&&{clientInfo:a}};return await this.sessionStore.set(o,c),{success:!0,session:c}}catch(e){return{success:!1,error:{code:n.handshake_failed,message:`Handshake validation failed: ${e instanceof Error?e.message:"Unknown error"}`}}}}async getSession(e){const t=await this.sessionStore.get(e);if(!t)return null;const r=Math.floor(Date.now()/1e3);return r-t.lastActivity>60*t.ttlMinutes||void 0!==this.config.absoluteSessionLifetime&&r-t.createdAt>60*this.config.absoluteSessionLifetime?(await this.sessionStore.delete(e),null):(t.lastActivity=r,await this.sessionStore.set(e,t),t)}async generateSessionId(){const e=await this.cryptoProvider.randomBytes(16);e[6]=15&e[6]|64,e[8]=63&e[8]|128;const t=Array.from(e).map(e=>e.toString(16).padStart(2,"0")).join("");return`kyaos_${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20,32)}`}async generateClientId(){const e=await this.cryptoProvider.randomBytes(6);return`client_${Array.from(e).map(e=>e.toString(16).padStart(2,"0")).join("")}`}normalizeClientInfoString(e){if("string"!=typeof e)return;const t=e.trim();return t.length>0?t:void 0}async 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)??await this.generateClientId(),protocolVersion:this.normalizeClientInfoString(e.clientProtocolVersion),capabilities:e.clientCapabilities}}static generateNonce(){const e=new Uint8Array(16);globalThis.crypto.getRandomValues(e);let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}async cleanup(){const e=Math.floor(Date.now()/1e3);for(const[t,r]of await this.sessionStore.entries()){let n=e-r.lastActivity>60*r.ttlMinutes;n||void 0===this.config.absoluteSessionLifetime||(n=e-r.createdAt>60*this.config.absoluteSessionLifetime),n&&await this.sessionStore.delete(t)}await this.sessionStore.cleanup(),await this.config.nonceCache.cleanup()}getStats(){return{activeSessions:this.sessionStore.size(),config:{timestampSkewSeconds:this.config.timestampSkewSeconds,sessionTtlMinutes:this.config.sessionTtlMinutes,absoluteSessionLifetime:this.config.absoluteSessionLifetime,cacheType:this.config.nonceCache.constructor.name}}}async clearSessions(){await this.sessionStore.clear()}}function Wr(e){return{nonce:jr.generateNonce(),audience:e,timestamp:Math.floor(Date.now()/1e3)}}function Ur(e){return"object"==typeof e&&null!==e&&"string"==typeof e.nonce&&e.nonce.length>0&&"string"==typeof e.audience&&e.audience.length>0&&"number"==typeof e.timestamp&&e.timestamp>0&&Number.isInteger(e.timestamp)}var Jr=r(77598);const Br=Buffer.from("302e020100300506032b657004220420","hex"),Vr=Buffer.from("302a300506032b6570032100","hex");class zr extends Pr{async sign(e,t){const r=Buffer.from(t,"base64"),n=64===r.length?r.subarray(0,32):r,i=(0,Jr.createPrivateKey)({key:Buffer.concat([Br,n]),format:"der",type:"pkcs8"});return new Uint8Array((0,Jr.sign)(null,Buffer.from(e),i))}async verify(e,t,r){try{const n=(0,Jr.createPublicKey)({key:Buffer.concat([Vr,Buffer.from(r,"base64")]),format:"der",type:"spki"});return(0,Jr.verify)(null,Buffer.from(e),n,Buffer.from(t))}catch{return!1}}async generateKeyPair(){const{publicKey:e,privateKey:t}=(0,Jr.generateKeyPairSync)("ed25519",{publicKeyEncoding:{type:"spki",format:"der"},privateKeyEncoding:{type:"pkcs8",format:"der"}});return{privateKey:t.subarray(16,48).toString("base64"),publicKey:e.subarray(12,44).toString("base64")}}async hash(e){return`sha256:${(0,Jr.createHash)("sha256").update(Buffer.from(e)).digest("hex")}`}async randomBytes(e){return new Uint8Array((0,Jr.randomBytes)(e))}}class Fr extends Tr{now(){return Date.now()}isWithinSkew(e,t){return Math.abs(Date.now()-e)<=1e3*t}hasExpired(e){return Date.now()>e}calculateExpiry(e){return Date.now()+1e3*e}format(e){return new Date(e).toISOString()}}class qr extends Rr{didKeyResolver=Pt();didWebResolver;didResolvers;allowPrivateNetworkHosts;constructor(e){super(),this.allowPrivateNetworkHosts=e?.allowPrivateNetworkHosts??!1,this.didResolvers=hr(e?.didResolvers,this)}async resolveDID(e){const t=lt(e),r=t?this.didResolvers[t]:void 0;if(r)try{const t=await r.resolve(e);if(t)return t}catch{return null}return e.startsWith("did:key:")?this.didKeyResolver.resolve(e):Zt(e)?this.isBlockedTarget(tr(e))?null:(this.didWebResolver||(this.didWebResolver=nr(this)),this.didWebResolver.resolve(e)):null}async fetchStatusList(e){if(this.isBlockedTarget(e))return null;try{const t=await this.fetch(e);if(!t.ok)return null;const r=await t.json();return function(e){if("object"!=typeof e||null===e)return!1;const t=e;if(!Array.isArray(t.type)||!t.type.includes("StatusList2021Credential"))return!1;const r=t.credentialSubject;if("object"!=typeof r||null===r)return!1;const n=r;return"StatusList2021"===n.type&&"string"==typeof n.encodedList}(r)?r:null}catch{return null}}async fetchDelegationChain(e){return[]}async fetch(e,t){if("function"!=typeof globalThis.fetch)throw new Error("Global fetch is not available in this runtime");return globalThis.fetch(e,t)}isBlockedTarget(e){if(this.allowPrivateNetworkHosts||null===e)return!1;let t;try{t=new URL(e).hostname}catch{return!1}return function(e){let t=e.toLowerCase();if(t.startsWith("[")&&t.endsWith("]")&&(t=t.slice(1,-1)),t.includes(":"))return"::1"===t||"::"===t||t.startsWith("fe80:")||t.startsWith("fc")||t.startsWith("fd");const r=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(t);if(!r)return!1;const n=Number(r[1]),i=Number(r[2]);return 127===n||10===n||0===n||169===n&&254===i||192===n&&168===i||172===n&&i>=16&&i<=31}(t)}}class Gr extends Rr{async resolveDID(e){return null}async fetchStatusList(e){return null}async fetchDelegationChain(e){return[]}async fetch(e,t){throw new Error("fetch unavailable")}}function Yr(e){return{version:"audit.v1",ts:Date.now(),session:e.session.sessionId,audience:e.session.audience,did:e.identity.did,kid:e.identity.kid,reqHash:e.requestHash,resHash:e.responseHash??"-",verified:e.verified,scope:e.scopeId??"-"}}class Xr{}class Qr extends Xr{records=[];events=[];loggedSessions=new Set;async logAuditRecord(e){const t=e.session.sessionId;this.loggedSessions.has(t)||(this.loggedSessions.add(t),this.records.push(Yr(e)))}async logEvent(e){this.events.push(e)}}class Zr extends Xr{async logAuditRecord(e){}async logEvent(e){}}class en{}class tn extends en{grants=new Map;now;constructor(e={}){super(),this.now=e.now??(()=>Date.now())}async bind(e){this.grants.set(e.id,{...e})}async getByAgent(e,t){return this.activeGrants().filter(r=>r.agentDid===e&&this.coversScopes(r,t))}async getBySession(e,t){return this.activeGrants().filter(r=>r.sessionId===e&&this.coversScopes(r,t))}async getById(e){const t=this.grants.get(e);return t?{...t}:void 0}async revoke(e,t){const r=this.grants.get(e);r&&(r.status="revoked",void 0!==t&&(r.revocationReason=t))}async cleanup(){const e=this.now();for(const[t,r]of this.grants)void 0!==r.expiresAt&&r.expiresAt<=e&&this.grants.delete(t)}activeGrants(){const e=this.now(),t=[];for(const r of this.grants.values())"revoked"!==r.status&&(void 0!==r.expiresAt&&r.expiresAt<=e||t.push({...r}));return t}coversScopes(e,t){return!t||0===t.length||t.every(t=>e.scopes.includes(t))}}class rn{}class nn extends rn{pending=new Map;now;constructor(e={}){super(),this.now=e.now??(()=>Date.now())}async put(e,t,r){this.pending.set(e,{flow:{...t},expiresAt:this.now()+r})}async get(e){const t=this.pending.get(e);if(t){if(!(t.expiresAt<=this.now()))return{...t.flow};this.pending.delete(e)}}async consume(e){const t=this.pending.get(e);if(t&&(this.pending.delete(e),!(t.expiresAt<=this.now())))return{...t.flow}}async delete(e){this.pending.delete(e)}async cleanup(){const e=this.now();for(const[t,r]of this.pending)r.expiresAt<=e&&this.pending.delete(t)}}function sn(e){const t=new Set;for(const r of e.credentialSubject.delegation.scopes??[])t.add(r);for(const r of e.credentialSubject.delegation.constraints?.scopes??[])t.add(r);return Array.from(t)}function on(e,t){const r=sn(e),n=sn(t),i=t.credentialSubject.delegation,s=e=>`${e.matcher}\0${e.resource}`,o=new Set((e.credentialSubject.delegation.constraints.crisp?.scopes??[]).map(s)),a=(i.constraints.crisp?.scopes??[]).filter(e=>!o.has(s(e)));if(a.length>0)return{valid:!1,reason:`Delegation ${i.id} introduces crisp scope matcher(s) absent from parent ${e.credentialSubject.delegation.id}: ${a.map(e=>`${e.matcher}:${e.resource}`).join(", ")}`};if(0===r.length)return{valid:!0};if(0===n.length)return{valid:!1,reason:`Delegation ${i.id} omits scopes required to prove attenuation from parent ${e.credentialSubject.delegation.id}`};const c=new Set(r),d=n.filter(e=>!c.has(e));return d.length>0?{valid:!1,reason:`Delegation ${i.id} widens scopes beyond parent ${e.credentialSubject.delegation.id}: ${d.join(", ")}`}:{valid:!0}}const an=["delete","drop","destroy","remove","terminate","transfer","payment","admin","execute","modify","write","rotate","revoke"],cn=["read","get","list","describe","search","query"];class dn{options;constructor(e={}){this.options=e}classify(e){const t=this.options.hints?.[e.toolName];if(t?.reversibility&&t.blastRadius&&t.severity)return{reversibility:t.reversibility,blastRadius:t.blastRadius,severity:t.severity};const r=un(e.toolName),n=function(e){const t=un(e);return t.includes("prod")||t.includes("production")}(e.namespace);let i;return i=r.some(e=>an.includes(e))?{reversibility:"irreversible",blastRadius:n?"environment":"resource",severity:n?"catastrophic":"high"}:r.some(e=>cn.includes(e))?{reversibility:"reversible",blastRadius:"record",severity:"low"}:{reversibility:"unknown",blastRadius:"unknown",severity:"unknown"},{...i,...ln(t)}}}function un(e){return e.split(/[.:/_\-\s]+/).flatMap(e=>e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/\s+/)).map(e=>e.toLowerCase()).filter(Boolean)}function ln(e){if(!e)return{};const t={};for(const[r,n]of Object.entries(e))void 0!==n&&(t[r]=n);return t}class hn{cfg;constructor(e={}){this.cfg=e}async evaluate(e){const{severity:t,reversibility:r,scopeMatched:n,humanApprovals:i}=e.context;if(!n)return{decision:"deny",reason:"scope_not_matched"};if("unknown"===t||"unknown"===r)return{decision:"deny",reason:"unclassified_high_risk"};if("irreversible"===r||"catastrophic"===t||"high"===t){const e=this.cfg.stepUpQuorum??1;return i.length>=e?{decision:"allow"}:{decision:"step_up",quorum:{n:e,approvers:this.cfg.stepUpApprovers??[]},reason:"destructive_action_requires_approval"}}return{decision:"allow"}}}async function fn(e,t,r,n){if(r.n<=0)return{satisfied:!1,reason:"invalid_quorum:n<=0"};const i=new Set;for(const s of e)"approve"===s.decision&&s.requestHash===t&&(r.approvers.length>0&&!r.approvers.includes(s.approverDid)||await n(s)&&i.add(s.approverDid));return i.size>=r.n?{satisfied:!0}:{satisfied:!1,reason:`quorum_not_met:${i.size}/${r.n}`}}function pn(e){return{principal:{agentDid:e.principal.agentDid,...e.principal.responsibleParty?{responsibleParty:e.principal.responsibleParty}:{}},action:{toolName:e.action.toolName},resource:{namespace:e.resource.namespace},context:{delegatedScopes:e.delegatedScopes,scopeMatched:e.scopeMatched,humanApprovals:e.humanApprovals??[],...e.risk,...void 0!==e.budgetRemaining?{budgetRemaining:e.budgetRemaining}:{}}}}function gn(e,t=256){const r="string"==typeof e?e:String(e);let n="";for(const e of r){const t=e.codePointAt(0)??0;n+=t<=31||t>=127&&t<=159?"�":e}return n.length>t?`${n.slice(0,t)}…`:n}const yn=256,mn=256,wn=/\([^()]*[+*?{][^()]*\)\s*[+*{]/;function vn(e,t,r){switch(t){case"exact":return e===r;case"prefix":{const t=e.endsWith("*")?e.slice(0,-1):e;return 0!==t.length&&r.startsWith(t)}case"regex":if(e.length>yn||r.length>mn)return!1;if(wn.test(e))return!1;try{return new RegExp(`^(?:${e})$`).test(r)}catch{return!1}default:return!1}}function Sn(e,t){if(function(e){const t=e?.credentialSubject?.delegation;return[...t?.scopes??[],...t?.constraints?.scopes??[]]}(t).includes(e))return{satisfied:!0,usedNonExactMatcher:!1};for(const r of function(e){return e?.credentialSubject?.delegation?.constraints?.crisp?.scopes??[]}(t))if(vn(r.resource,r.matcher,e))return{satisfied:!0,usedNonExactMatcher:"exact"!==r.matcher};return{satisfied:!1,usedNonExactMatcher:!1}}const bn=["handshake","identity","reputation"];function Dn(e,t){const r={did:e.identity.did,kid:e.identity.kid,privateKey:e.identity.privateKey,publicKey:e.identity.publicKey},i=e.nonceCache??new xr,s=new jr(t,{...e.session,serverDid:r.did,nonceCache:i}),a=new jt(r,t),u=e.delegation,l=e.auditLog??new Zr,h=e.emitLegacyProofKey??!0,f=e.grantStore??new tn;e.grantStore||Et.warn("[kya-os] Using MemoryGrantStore — grants are lost on restart and not shared across instances. Inject a Redis / Durable Object / DB-backed GrantStore via config.grantStore for production / multi-instance use.");const g=u?.holderBinding??"off",y={identity:r,config:e,cryptoProvider:t,sessionManager:s,proofGenerator:a,auditLog:l,grantStore:f,delegationConfig:u,holderBindingMode:g,holderBindingVerifier:"off"===g?void 0:new Er({cryptoProvider:t,clockProvider:new Fr,nonceCacheProvider:i,fetchProvider:u?.fetchProvider??("function"==typeof globalThis.fetch?new qr:new Gr)}),emitLegacyProofKey:h},m=function(e){const{identity:t,config:r,cryptoProvider:i,sessionManager:s,proofGenerator:o,auditLog:a,emitLegacyProofKey:d}=e,u=(e,t)=>({...e,[Mt]:t,...d?{[Ht]:t}:{}});let l;async function h(){if(l&&await s.getSession(l))return s.getStats().activeSessions<=1?l:void Et.warn("[kya-os] Multiple sessions active and no sessionId threaded; skipping proof attribution to avoid signing with another client's session. Thread the sessionId (the auto-proof path is single-session only).");if(!r.autoSession)return;const e=c(await i.randomBytes(16)),n=Math.floor(Date.now()/1e3),o=await s.validateHandshake({nonce:e,audience:t.did,timestamp:n});return o.success&&o.session?(l=o.session.sessionId,l):void 0}return{handleHandshake:async function(e){if(!Ur(e))return{content:[{type:"text",text:JSON.stringify({success:!1,error:{code:n.handshake_failed,message:"Invalid handshake format: requires nonce (string), audience (string), and timestamp (positive integer)"}})}],isError:!0};const r=await s.validateHandshake(e);return r.success&&r.session&&(l=r.session.sessionId),{content:[{type:"text",text:JSON.stringify({success:r.success,...r.session&&{sessionId:r.session.sessionId,serverDid:t.did,serverKid:t.kid},...r.error&&{error:r.error}})}],...r.error&&{isError:!0}}},ensureSession:h,wrapWithProof:function(e,r){return async(n,i,c)=>{const d=await r(n,i,c);if(d.isError)return d;const l=i??await h();if(!l)return d;const f=await s.getSession(l);if(!f)return d;try{const r={method:e,params:n},i={data:d.content},s=await o.generateProof(r,i,f,{scopeId:c?.scopeId});d._meta=u({},s);try{await a.logAuditRecord({identity:{did:t.did,kid:t.kid},session:{sessionId:f.sessionId,audience:f.audience},requestHash:s.meta.requestHash,responseHash:s.meta.responseHash,verified:"yes",scopeId:s.meta.scopeId})}catch(t){Et.error("[kya-os] Audit log failed",{tool:e,error:t instanceof Error?t.message:String(t)})}}catch(t){Et.error("[kya-os] Proof generation failed",{tool:e,error:t instanceof Error?t.message:String(t)}),d._meta={proofError:"Proof generation failed — response is unproven"}}return d}},attachOutcomeProof:async(e,t,r,n,i,a="denied",c,d)=>{try{const l=n??await h();if(!l)return e;const f=await s.getSession(l);if(!f)return e;let p;if(void 0!==c)p=c;else{p={};for(const[e,t]of Object.entries(r))"_kyaos_delegation"!==e&&(p[e]=t)}const g={method:t,params:p},y=void 0!==d?{data:d}:void 0,m=await o.generateProof(g,y,f,{outcome:a,reason:gn(i)});e._meta=u(e._meta??{},m)}catch(e){Et.error("[kya-os] Outcome proof generation failed",{tool:t,error:e instanceof Error?e.message:String(e)})}return e}}}(y),w=function(e,t){const{identity:r,config:i,sessionManager:s}=e,{handleHandshake:o}=t;return{handleKyaOs:async function(e){const t="string"==typeof e.action?e.action:void 0;switch(t){case"handshake":return o(e);case"identity":return async function(){return{content:[{type:"text",text:JSON.stringify({did:r.did,kid:r.kid,name:i.identity.agentName??r.did,capabilities:["handshake","signing","verification"],protocolVersion:"1.0.0",clockSkewSeconds:s.getStats().config.timestampSkewSeconds})}]}}();case"reputation":return{content:[{type:"text",text:JSON.stringify({success:!1,error:{code:n.runtime_error,message:'action: "reputation" is not yet implemented.'}})}],isError:!0};default:return{content:[{type:"text",text:JSON.stringify({success:!1,error:{code:n.invalid_request,message:`Unknown _kyaos action: "${t??"(missing)"}". Valid actions: ${bn.join(", ")}`}})}],isError:!0}}},handshakeTool:{name:"_kyaos_handshake",description:"KYA-OS identity handshake — establishes a cryptographic session",inputSchema:{type:"object",properties:{nonce:{type:"string",description:"Client-generated unique nonce"},audience:{type:"string",description:"Intended audience (server DID or URL)"},timestamp:{type:"number",description:"Unix epoch seconds"},agentDid:{type:"string",description:"Client agent DID (optional)"}},required:["nonce","audience","timestamp"]}},kyaOsTool:{name:"_kyaos",description:"KYA-OS protocol — identity verification, session handshake, and server metadata",inputSchema:{type:"object",properties:{action:{type:"string",enum:[...bn],description:"Protocol operation to perform"},nonce:{type:"string",description:"Client-generated unique nonce"},audience:{type:"string",description:"Intended audience (server DID or URL)"},timestamp:{type:"number",description:"Unix epoch seconds"},agentDid:{type:"string",description:"Client agent DID (optional)"}},required:["action"]}}}}(y,{handleHandshake:m.handleHandshake}),{resolveExistingGrant:v,bindGrantOnSuccess:S}=function(e){const{identity:t,cryptoProvider:r,grantStore:n,holderBindingMode:i,holderBindingVerifier:s}=e;async function o(e,t,n){const i=`${e}|${t??""}|${[...n].sort().join(",")}`;return`grant_${(await r.hash((new TextEncoder).encode(i))).replace(/^sha256:/,"")}`}return{resolveExistingGrant:async function(e,r,i,o){const a=await async function(e,r,i,o){if(!s)return;const a=r._kyaos_proof;if(void 0===a)return;let c=a;if("string"==typeof a)try{c=JSON.parse(a)}catch{return}const d=c,u=d?.meta?.did;return"string"==typeof u&&qt(u)&&"bound"===(await Gt({proof:d,subjectDid:u,request:Vt(e,r),expectedAudience:t.did,proofVerifier:s})).status?(await n.getByAgent(u,[o])).find(e=>void 0===e.sessionId||e.sessionId===i):void 0}(e,r,i,o);if(a)return a;if(i){const[e]=await n.getBySession(i,[o]);if(e)return e}},bindGrantOnSuccess:async function(e,t,r,s,a){try{const c=e.credentialSubject?.id;if(!c)return;if("off"===i&&void 0===s)return void Et.debug(`[kya-os] Skipping an unresolvable session-less grant for scope "${a}" (holderBinding 'off', no sessionId).`);let d;try{d=sn(e)}catch{d=[]}const u=Array.from(new Set([a,...d])),l=e.credentialSubject?.delegation?.controller,h=function(e){if(e.expirationDate){const t=Date.parse(e.expirationDate);if(!Number.isNaN(t))return t}const t=e.credentialSubject?.delegation?.constraints?.notAfter;if("number"==typeof t)return 1e3*t}(e),f={id:await o(c,s,u),agentDid:c,...void 0!==l?{userDid:l}:{},scopes:u,...void 0!==s?{sessionId:s}:{},authorization:{type:"delegation"},...r&&"string"==typeof t?{credentialJwt:t}:{},issuedAt:Date.now(),...void 0!==h?{expiresAt:h}:{},status:"active"};await n.bind(f)}catch(e){Et.error("[kya-os] Grant bind failed",{scope:a,error:e instanceof Error?e.message:String(e)})}}}}(y),{wrapWithDelegation:b}=function(e,t){const{identity:r,holderBindingMode:i,holderBindingVerifier:s}=e,{attachOutcomeProof:a,resolveExistingGrant:c,bindGrantOnSuccess:u}=t,{validateDelegationChain:l,buildDelegationErrorResponse:h,buildNeedsAuthorizationChallenge:f}=function(e){const{identity:t,cryptoProvider:r,delegationConfig:n}=e,i=Pt(),s=n?.fetchProvider??("function"==typeof globalThis.fetch?new qr:void 0),a=s?nr(s):void 0,c=hr(n?.didResolvers,s),u=new Ke({didResolver:{async resolve(e){const t=n?.didResolver;if(t){const r=await t.resolve(e);if(r)return r}const r=lt(e),s=r?c[r]:void 0;if(s)try{const t=await s.resolve(e);if(t)return t}catch{return null}return e.startsWith("did:key:")?i.resolve(e):e.startsWith("did:web:")?a?.resolve(e)??null:null}},signatureVerifier:async(e,t)=>{const n=e.proof;if(!n)return{valid:!1,reason:"Missing proof"};const i=n.proofValue;if(!i)return{valid:!1,reason:"Missing proofValue in proof"};const s=e,a={};for(const[e,t]of Object.entries(s))"proof"!==e&&(a[e]=t);const c=T(a),u=(new TextEncoder).encode(c),l=o(i),h=t;if(!h.x)return{valid:!1,reason:"No x field in publicKeyJwk"};const f=d(o(h.x)),p=await r.verify(u,l,f);return{valid:p,reason:p?void 0:"Signature verification failed"}},statusListResolver:n?.statusListResolver});return{validateDelegationChain:(e,r)=>async function(e,t,r){const n=e?.credentialSubject?.delegation;if(!n||"object"!=typeof n||!n.constraints||"object"!=typeof n.constraints)return{valid:!1,reason:"Malformed delegation credential: missing credentialSubject.delegation or its constraints"};const i=p(e);let s=[e];if(i.parentId){if(!t.resolveDelegationChain)return{valid:!1,reason:`Delegation ${i.id} references parent ${i.parentId} but no resolveDelegationChain handler is configured`};let r;try{r=await t.resolveDelegationChain(e)}catch(e){return{valid:!1,reason:`Failed to resolve delegation chain: ${e instanceof Error?e.message:"Unknown error"}`}}if(0===r.length)return{valid:!1,reason:`Delegation ${i.id} references parent ${i.parentId} but the resolved chain is empty`};const n=r.findIndex(e=>e.credentialSubject.delegation.id===i.id);if(-1!==n&&n!==r.length-1)return{valid:!1,reason:`Resolved delegation chain for ${i.id} must end with the leaf credential`};s=-1===n?[...r,e]:r}const o=new Set;let a,c;for(const e of s){const n=p(e);if(o.has(n.id))return{valid:!1,reason:`Delegation chain contains a circular reference at ${n.id}`};if(o.add(n.id),e.credentialStatus&&!t.statusListConfigured)return{valid:!1,reason:`Delegation ${n.id} has credentialStatus but no statusListResolver is configured`};const i=await t.verifier.verifyDelegationCredential(e,{...r?.skipSignature?{skipSignature:!0}:{}});if(!i.valid)return{valid:!1,reason:`Delegation ${n.id} invalid: ${i.reason}`};if(!qe(n,t.serverDid))return{valid:!1,reason:`Delegation ${n.id} audience does not include server DID ${t.serverDid}`};if(n.parentId&&!n.constraints.audience)return{valid:!1,reason:`Delegation ${n.id} is a re-delegation (parentId: ${n.parentId}) but has no audience constraint. Re-delegations MUST include an audience constraint (KYA-OS §11.6)`};if(!a||!c){if(n.parentId)return{valid:!1,reason:`Resolved delegation chain is incomplete: root delegation ${n.id} still references parent ${n.parentId}`};a=n,c=e;continue}if(n.parentId!==a.id)return{valid:!1,reason:`Delegation ${n.id} references parent ${n.parentId} but expected ${a.id}`};if(n.issuerDid!==a.subjectDid)return{valid:!1,reason:`Delegation ${n.id} issued by ${n.issuerDid} but parent subject is ${a.subjectDid}`};const s=on(c,e);if(!s.valid)return s;a=n,c=e}const d=p(s[s.length-1]);if(d.id!==i.id)return{valid:!1,reason:`Resolved delegation chain ended at ${d.id} instead of leaf ${i.id}`};if(t.revocationChecker){const e=await t.revocationChecker.isRevoked(i.id);if(e.revoked)return{valid:!1,reason:e.revokedAncestor?`Delegation ${i.id} is revoked via ancestor ${e.revokedAncestor}`:`Delegation ${i.id} is revoked${e.reason?`: ${e.reason}`:""}`}}return{valid:!0}}(e,{serverDid:t.did,verifier:u,resolveDelegationChain:n?.resolveDelegationChain,statusListConfigured:!!n?.statusListResolver,revocationChecker:n?.revocationChecker},r),buildDelegationErrorResponse:(e,t)=>({content:[{type:"text",text:JSON.stringify({error:e,reason:gn(t)})}],isError:!0}),buildNeedsAuthorizationChallenge:async function(e,t){const n=await r.randomBytes(16),i=Array.from(n).map(e=>e.toString(16).padStart(2,"0")).join(""),s=[i.slice(0,8),i.slice(8,12),i.slice(12,16),i.slice(16,20),i.slice(20)].join("-"),o=Math.floor(Date.now()/1e3)+300,a=E({message:`Tool "${e}" requires delegation with scope: ${t.scopeId}`,authorizationUrl:t.consentUrl,resumeToken:s,expiresAt:o,scopes:[t.scopeId]}),c=[{type:"text",text:JSON.stringify(a)}];let d=c;if(t.formatChallenge)try{d=t.formatChallenge(a)}catch(t){Et.error("[kya-os] formatChallenge threw; using the default challenge",{tool:e,error:t instanceof Error?t.message:String(t)}),d=c}return{challengeContent:d,message:a.message}}}}(e);return{wrapWithDelegation:function(e,t,o){return async(d,p)=>{const g=d._kyaos_delegation;if(null==g){if(await c(e,d,p,t.scopeId)){const r={};for(const[e,t]of Object.entries(d))Bt(e)||(r[e]=t);return Et.debug(`[kya-os] Grant resolved for "${e}" (scope "${t.scopeId}") — no re-paste required`),o(r,p,{scopeId:t.scopeId})}const{challengeContent:r,message:n}=await f(e,t);return a({content:r},e,d,p,n,"needs_authorization",void 0,r)}let y,m=!1;if("string"==typeof g){const t=O(g);if(!t||!t.payload.vc)return a(h(n.delegation_invalid,"Invalid VC-JWT format"),e,d,p,"Invalid VC-JWT format");y=t.payload.vc,y.proof||(y={...y,proof:{type:"JwtProof2020",jwt:g}}),m=!0}else y=g;const w=await(async()=>{try{return await l(y,{skipSignature:m})}catch(t){return Et.error("[kya-os] Unexpected error verifying delegation",{tool:e,error:t instanceof Error?t.message:String(t),stack:t instanceof Error?t.stack:void 0}),{valid:!1,reason:"Delegation credential could not be verified"}}})();if(!w.valid){const t=w.reason??"Unknown delegation validation error";return Et.warn(`[kya-os] Delegation verification failed for "${e}": ${gn(t)}`),a(h(n.delegation_invalid,t),e,d,p,t)}if("off"!==i&&s){const t=y.credentialSubject?.id;if(t&&qt(t)){const o=d._kyaos_proof;if(void 0===o){const t="Holder-of-key proof (_kyaos_proof) is required for this delegation subject";if(Et.warn(`[kya-os] Holder binding: "${e}" called without _kyaos_proof`),"enforce"===i)return a(h(n.holder_binding_failed,t),e,d,p,t)}else{let c=o;if("string"==typeof o)try{c=JSON.parse(o)}catch{c={}}const u=await Gt({proof:c,subjectDid:t,request:Vt(e,d),expectedAudience:r.did,proofVerifier:s});if("bound"!==u.status){const t=u.reason??"Holder-of-key proof did not bind the delegation subject";if(Et.warn(`[kya-os] Holder binding ${u.status} for "${e}": ${gn(t)}`),"enforce"===i)return a(h(n.holder_binding_failed,t),e,d,p,t)}}}else t&&Et.warn(`[kya-os] Holder binding: subject "${t}" is not did:key; deferring to cnf binding (phase 2)`)}const v=Sn(t.scopeId,y);if(v.usedNonExactMatcher&&Et.warn(`[kya-os] Scope "${t.scopeId}" for "${e}" granted via a non-exact (prefix/regex) matcher. Verify this is intended — non-exact matchers widen authority.`),!v.satisfied){const r=`Required scope "${t.scopeId}" not in delegation scopes`;return Et.warn(`[kya-os] Delegation missing required scope "${t.scopeId}" for "${e}"`),a(h(n.insufficient_scope,r),e,d,p,r)}const S={};for(const[e,t]of Object.entries(d))Bt(e)||(S[e]=t);return await u(y,g,m,p,t.scopeId),Et.debug(`[kya-os] Delegation verified for "${e}", scope "${t.scopeId}"`),o(S,p,{scopeId:t.scopeId})}}}}(y,{attachOutcomeProof:m.attachOutcomeProof,resolveExistingGrant:v,bindGrantOnSuccess:S}),{withPolicyGate:D}=function(e,t){const{proofGenerator:r}=e,{attachOutcomeProof:i}=t,s=new dn,o=new hn;return{withPolicyGate:function(e,t,a={}){const c=a.engine??o,d=a.classifier??s,u=a.approvalsArgKey??"_kyaos_approvals",l=a.isValidApprovalSignature??(async()=>!1);return async(s,o)=>{const h={};for(const[e,t]of Object.entries(s))Bt(e)||e===u||(h[e]=t);const f=a.resolveNamespace?.(s)??e,p=d.classify({toolName:e,namespace:f}),g=function(e){if(!e||"object"!=typeof e)return{agentDid:"unknown",delegatedScopes:[]};try{const t=e,r=t.credentialSubject,n=r?.delegation?.subjectDid??r?.id??"unknown",i=r?.delegation?.controller;let s=[];try{s=sn(t)}catch{s=[]}return{agentDid:n,...i?{responsibleParty:i}:{},delegatedScopes:s}}catch{return{agentDid:"unknown",delegatedScopes:[]}}}(s._kyaos_delegation),y=pn({principal:{agentDid:g.agentDid,...g.responsibleParty?{responsibleParty:g.responsibleParty}:{}},action:{toolName:e},resource:{namespace:f},delegatedScopes:g.delegatedScopes,scopeMatched:a.scopeMatched??!1,risk:p}),m=await c.evaluate(y);if("allow"===m.decision)return t(h,o);if("deny"===m.decision){const t={content:[{type:"text",text:JSON.stringify({error:n.policy_denied,reason:gn(m.reason)})}],isError:!0};return i(t,e,s,o,m.reason,"denied",h)}const w=await r.hashRequest({method:e,params:h}),v=Array.isArray(s[u])?s[u]:[];if((await fn(v,w,m.quorum,l)).satisfied)return t(h,o);const S=A({message:`Tool "${e}" requires ${m.quorum.n}-of-N approval before it may proceed (${gn(m.reason)}).`,resumeToken:`step_up:${w}`,expiresAt:Math.floor(Date.now()/1e3)+300,requestHash:w,quorum:m.quorum}),b={content:[{type:"text",text:JSON.stringify(S)}],isError:!0};return i(b,e,s,o,m.reason,"step_up_required",h)}}}}(y,{attachOutcomeProof:m.attachOutcomeProof});return{identity:e.identity,sessionManager:s,proofGenerator:a,kyaOsTool:w.kyaOsTool,handshakeTool:w.handshakeTool,handleKyaOs:w.handleKyaOs,handleHandshake:m.handleHandshake,wrapWithProof:m.wrapWithProof,wrapWithDelegation:b,withPolicyGate:D}}var En=r(11569);async function In(e){const t=await e.generateKeyPair(),r=vt(t.publicKey);return{did:r,kid:`${r}#${St(r)}`,privateKey:t.privateKey,publicKey:t.publicKey}}async function An(e,t){const r=Dn({identity:t.identity??await In(t.crypto),session:t.session,delegation:t.delegation,autoSession:t.autoSession??!0,...t.grantStore?{grantStore:t.grantStore}:{},...void 0!==t.emitLegacyProofKey?{emitLegacyProofKey:t.emitLegacyProofKey}:{}},t.crypto);if("tool"===(t.handshakeExposure??"tool")&&e.registerTool("_kyaos",{description:"KYA-OS protocol — identity verification, session handshake, and server metadata",annotations:{title:"KYA-OS Protocol",readOnlyHint:!0},inputSchema:{action:En.z.enum(bn).describe("Protocol operation to perform"),nonce:En.z.string().optional().describe("Client-generated unique nonce (handshake)"),audience:En.z.string().optional().describe("Intended audience (handshake)"),timestamp:En.z.number().optional().describe("Unix epoch seconds (handshake)"),agentDid:En.z.string().optional().describe("Client agent DID (handshake, optional)")}},async e=>{const t=await r.handleKyaOs(e);return{...t,content:t.content.map(e=>({...e,type:"text"}))}}),!1!==t.proofAllTools){const n=["_kyaos","_kyaos_handshake",...t.excludeTools??[]],i=e.connect.bind(e);e.connect=e=>i(function(e,t,r=["_kyaos","_kyaos_handshake"]){const n=new Map,i={start:()=>e.start(),close:()=>e.close(),set onmessage(t){e.onmessage=t},get onmessage(){return e.onmessage},set onclose(t){e.onclose=t},get onclose(){return e.onclose},set onerror(t){e.onerror=t},get onerror(){return e.onerror},async send(r){const i=r.id,s=void 0!==i?n.get(i):void 0;if(s){n.delete(i);try{const e=r.result;if(e&&!e.isError){const n=async()=>e,i=t.wrapWithProof(s.toolName,n),o=await i(s.args);void 0!==o._meta&&(r={...r,result:o})}}catch(e){Et.error("[kya-os-transport] Proof injection failed",{tool:s.toolName,error:e instanceof Error?e.message:String(e)});const t=r.result;t&&(t._meta={proofError:"Proof generation failed — response is unproven"},r={...r,result:t})}}return e.send(r)}},s=e.start.bind(e);return i.start=async()=>{await s();const t=e.onmessage;e.onmessage=e=>{if("tools/call"===e.method&&void 0!==e.id){const t=e.params,i=t?.name;i&&!r.includes(i)&&n.set(e.id,{toolName:i,args:t?.arguments??{}})}t?.(e)}},i}(e,r,n))}return r}}};
|