@kya-os/mcp-i
Version:
The TypeScript MCP framework with identity features built-in
1 lines • 220 kB
JavaScript
"use strict";exports.id=365,exports.ids=[365],exports.modules={17365:(e,t,i)=>{i.r(t),i.d(t,{ANON_NONCE_TTL_MS:()=>S,AUDIT_ASSURANCE_PROFILES:()=>on,AUDIT_BUNDLE_INTEGRITY_SUITE:()=>fr,AUDIT_BUNDLE_MANIFEST_SCHEMA_ID:()=>pr,AUDIT_BUNDLE_MEDIA_TYPES:()=>Xn,AUDIT_CHECKPOINT_INTEGRITY_SUITE:()=>hr,AUDIT_CHECKPOINT_SCHEMA_ID:()=>lr,AUDIT_DIGEST_DOMAINS:()=>gn,AUDIT_ENTRY_SCHEMA_ID:()=>cr,AUDIT_ERROR_CODES:()=>wn,AUDIT_EVENT_SCHEMA_ID:()=>ar,AUDIT_EVENT_TYPES:()=>or,AUDIT_INTEGRITY_SUITE:()=>ur,AUDIT_REASON_CODES:()=>Bn,AUDIT_RECEIPT_SCHEMA_ID:()=>dr,AUTH_NONCE_TTL_MS:()=>w,AuditArtifactVerifier:()=>Gn,AuditCheckpointBuilder:()=>Un,AuditCheckpointCoordinator:()=>Hn,AuditLogProvider:()=>ir,AuditMirrorService:()=>po,AuditProjectionWorker:()=>Vn,AuditProtocolError:()=>Sn,AuditRecorderService:()=>vo,AuditReplayBundleExporter:()=>ro,AuditTrailService:()=>lo,BitstringManager:()=>qe,CascadingRevocationManager:()=>Ye,ClockProvider:()=>xi,CompactJwsAuditSignatureVerifier:()=>un,CompactJwsAuditSigner:()=>ln,CryptoProvider:()=>Li,CryptoProviderAuditHasher:()=>dn,DEFAULT_CLOCK_SKEW_SECONDS:()=>bi,DEFAULT_SESSION_TTL_MINUTES:()=>v,DEFAULT_TIMESTAMP_SKEW_SECONDS:()=>I,DELEGATION_CREDENTIAL_CONTEXT:()=>h,DefaultPolicyEngine:()=>Vo,DelegationCredentialIssuer:()=>H,DelegationCredentialVerifier:()=>He,DelegationGraphManager:()=>Ke,DidWebResolver:()=>ai,ED25519_KEY_SIZE:()=>jt,ED25519_PKCS8_DER_HEADER:()=>Ut,ED25519_SPKI_DER_HEADER_LENGTH:()=>Ht,FetchProvider:()=>Mi,GrantStore:()=>Oo,HOLDER_BINDING_ERROR:()=>Xt,IdentityProvider:()=>Hi,KYA_OS_ERROR_CODES:()=>r,KYA_OS_PROOF_META_KEY:()=>Kt,LEGACY_PROOF_META_KEY:()=>$t,LegacyAuditSinkAdapter:()=>ko,LocalAuditRecorderClient:()=>So,MAX_CLOCK_SKEW_SECONDS:()=>Ci,MIN_CLOCK_SKEW_SECONDS:()=>_i,McpAuditEventAdapter:()=>Ro,MemoryAuditCheckpointObserver:()=>bo,MemoryAuditCheckpointStore:()=>zn,MemoryAuditEvidenceProvider:()=>An,MemoryAuditJournal:()=>wo,MemoryAuditLogProvider:()=>rr,MemoryAuditOutbox:()=>Co,MemoryAuditProjectionProvider:()=>$n,MemoryAuditSourceState:()=>To,MemoryDelegationGraphStorage:()=>ii,MemoryGrantStore:()=>Po,MemoryIdentityProvider:()=>$i,MemoryNonceCacheProvider:()=>Ki,MemoryPendingFlowStore:()=>xo,MemoryResumeTokenStore:()=>vi,MemorySessionStore:()=>Bi,MemoryStatusListStorage:()=>ti,MemoryStorageProvider:()=>ji,MemorySupportingAnchorProvider:()=>_o,NONCE_LENGTH_BYTES:()=>E,NodeCryptoProvider:()=>Xi,NonceCacheProvider:()=>Ui,NoopAuditLogProvider:()=>nr,NoopFetchProvider:()=>er,OUTBOUND_HEADER_NAMES:()=>xt,PROOF_VERIFICATION_ERROR_CODES:()=>Si,PendingFlowStore:()=>Lo,ProofGenerator:()=>Bt,ProofVerificationError:()=>Di,ProofVerifier:()=>Ti,Rfc9162MerkleTree:()=>Rn,RiskClassifier:()=>jo,RuntimeFetchProvider:()=>Qi,SENSITIVE_VERBS:()=>Uo,SessionManager:()=>qi,SessionStore:()=>Vi,StatusList2021Manager:()=>Ge,StorageProvider:()=>zi,SystemClockProvider:()=>Zi,WebCryptoEvidenceEncryptor:()=>Dn,assertAuditCapabilities:()=>sn,assertHolderBinding:()=>Qt,auditAnchorReceiptSchema:()=>Pr,auditBundleConsistencyProofSchema:()=>zr,auditBundleInclusionProofSchema:()=>Mr,auditBundleManifestCoreSchema:()=>jr,auditCheckpointCoreSchema:()=>kr,auditEntryCoreSchema:()=>Cr,auditMerkleConsistencyProofSchema:()=>xr,auditMerkleInclusionProofSchema:()=>Lr,auditObservationReceiptSchema:()=>Or,auditProducerEventSchema:()=>_r,auditRecorderReceiptCoreSchema:()=>Tr,auditReplayBundleSchema:()=>$r,auditVerificationPolicySchema:()=>qr,base58Decode:()=>ht,base58Encode:()=>lt,base64ToBytes:()=>u,base64urlDecodeToBytes:()=>s,base64urlEncodeFromBytes:()=>c,buildAuditRecord:()=>tr,buildAuditRecorderReceiptCore:()=>mn,buildChainString:()=>ct,buildDelegationProofJWT:()=>at,buildDidResolverRegistry:()=>mi,buildDidWebDocument:()=>li,buildOutboundDelegationHeaders:()=>Mt,buildPolicyRequest:()=>qo,bytesToBase64:()=>d,canonicalizeJSON:()=>x,collectAuditEvidenceManifest:()=>yn,collectAuditEvidenceRefs:()=>fn,compareDids:()=>mt,completeVCJWT:()=>z,createAuditTrail:()=>ho,createCascadingRevocationManager:()=>Xe,createDefaultConsoleLogger:()=>_t,createDelegationGraph:()=>$e,createDelegationIssuer:()=>j,createDelegationVerifier:()=>je,createDidKeyResolver:()=>Pt,createDidWebResolver:()=>ci,createHandshakeRequest:()=>Fi,createKyaOsError:()=>n,createKyaOsMiddleware:()=>ts,createLocalAuditRecorder:()=>Do,createNeedsApprovalError:()=>b,createNeedsAuthorizationError:()=>D,createProofResponse:()=>qt,createProofVerificationError:()=>Ai,createStatusListManager:()=>Je,createUnsignedVCJWT:()=>M,didKeyFragment:()=>At,didWebToUrl:()=>si,digestAuditEntry:()=>In,digestAuditEvent:()=>vn,digestAuditEvidenceManifest:()=>En,digestSchema:()=>vr,evidenceRefSchema:()=>wr,extractAgentId:()=>It,extractAgentSlug:()=>Et,extractCanonicalData:()=>Ft,extractDelegationFromVC:()=>f,extractProofFromMeta:()=>Pi,extractPublicKeyFromDidKey:()=>Rt,generateDidKeyFromBase64:()=>Dt,generateDidKeyFromBytes:()=>St,generateIdentity:()=>is,generateRequestProof:()=>Yt,getDidMethod:()=>gt,getServerDid:()=>vt,hasSensitiveScopes:()=>wi,hashAuditValue:()=>hn,isDelegationCredentialExpired:()=>g,isDelegationCredentialNotYetValid:()=>y,isDidWeb:()=>ni,isEd25519DidKey:()=>Nt,isHolderBindingApplicable:()=>Zt,isIndexSet:()=>We,isKyaOsControlArg:()=>Gt,isNeedsApprovalError:()=>_,isNeedsAuthorizationError:()=>A,isReservedMcpMetaKey:()=>Ri,isValidBase58:()=>pt,isValidDid:()=>ft,logger:()=>Ct,matchScope:()=>Yo,mergeAuditDimensions:()=>Jn,normalizeDid:()=>yt,parseAuditBundleManifestCore:()=>tn,parseAuditCheckpointCore:()=>Zr,parseAuditEntryCore:()=>Jr,parseAuditObservationReceipt:()=>en,parseAuditProducerEvent:()=>Gr,parseAuditRecorderReceiptCore:()=>Xr,parseAuditReplayBundle:()=>rn,parseAuditVerificationPolicy:()=>nn,parseDidWeb:()=>oi,parseSignedAuditCheckpoint:()=>Qr,parseSignedAuditEntry:()=>Yr,parseVCJWT:()=>U,partyRefSchema:()=>Sr,publicKeyToJwk:()=>Ot,resolveDidKeySync:()=>Lt,scopeSatisfies:()=>Xo,signedAuditCheckpointSchema:()=>Nr,signedAuditEntrySchema:()=>Rr,signerRefSchema:()=>Er,toHolderBindingRequest:()=>Jt,validateDelegationCredential:()=>m,validateDetachedProof:()=>T,validateHandshakeFormat:()=>Wi,validateMetaStructure:()=>Oi,verifyApprovalQuorum:()=>Bo,verifyAuditBundle:()=>uo,verifyDelegationAudience:()=>Ze,verifyDidLinkage:()=>pi,verifyOrHints:()=>Ii,withKyaOs:()=>rs,wrapDelegationAsVC:()=>p});const r={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 n(e,t,i){return i?{code:e,message:t,details:i}:{code:e,message:t}}function o(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 i=0;i<e.length;i++)t[i]=e.charCodeAt(i);return(new TextDecoder).decode(t)}return e}throw new Error("Neither Buffer nor atob is available")}function s(e){const t=l(e).replace(/-/g,"+").replace(/_/g,"/");if("undefined"!=typeof atob){const e=atob(t),i=new Uint8Array(e.length);for(let t=0;t<e.length;t++)i[t]=e.charCodeAt(t);return i}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),i=Array.from(t).map(e=>String.fromCharCode(e)).join("");return btoa(i).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 i=(4-t.length%4)%4;if(t+="=".repeat(i),"undefined"!=typeof atob){const e=atob(t),i=new Uint8Array(e.length);for(let t=0;t<e.length;t++)i[t]=e.charCodeAt(t);return i}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 p(e,t){const i=(new Date).toISOString(),r=e.constraints.notAfter?new Date(1e3*e.constraints.notAfter).toISOString():t?.expirationDate;let n=t?.issuanceDate||i;!t?.issuanceDate&&e.createdAt&&(n=new Date(e.createdAt).toISOString());const o=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:n,...void 0!==r&&{expirationDate:r},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},...o&&o.length>0&&{scopes:o},...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 f(e){const t=e?.credentialSubject?.delegation;if(!t||"object"!=typeof t)throw new Error("extractDelegationFromVC: credential is missing credentialSubject.delegation");let i="";if(e.proof){const t=e.proof;i=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:i,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 i=t.credentialSubject;if(!i||"object"!=typeof i)return{success:!1,error:{message:"Missing credentialSubject"}};if(!i.id||"string"!=typeof i.id)return{success:!1,error:{message:"credentialSubject.id missing"}};const r=i.delegation;return r&&"object"==typeof r?r.id&&r.issuerDid&&r.subjectDid&&r.constraints?{success:!0,data:e}:{success:!1,error:{message:"delegation fields missing"}}:{success:!1,error:{message:"credentialSubject.delegation missing"}}}const v=30,I=120,E=16,w=12e4,S=6e4;function D(e){return{error:"needs_authorization",...e}}function A(e){return"object"==typeof e&&null!==e&&"needs_authorization"===e.error}function b(e){return{error:"needs_approval",...e}}function _(e){return"object"==typeof e&&null!==e&&"needs_approval"===e.error}const C=/^sha256:[a-f0-9]{64}$/;function T(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 i=t.meta;if(!i||"object"!=typeof i)return{success:!1,error:{message:"meta must be an object"}};const r=i,n=["did","kid","nonce","audience","sessionId"];for(const e of n)if("string"!=typeof r[e]||r[e].length<1)return{success:!1,error:{message:`meta.${e} must be a non-empty string`}};if("number"!=typeof r.ts||!Number.isInteger(r.ts)||r.ts<=0)return{success:!1,error:{message:"meta.ts must be a positive integer"}};if("string"!=typeof r.requestHash||!C.test(r.requestHash))return{success:!1,error:{message:"meta.requestHash must match sha256:<64 hex chars>"}};if(void 0!==r.responseHash&&("string"!=typeof r.responseHash||!C.test(r.responseHash)))return{success:!1,error:{message:"meta.responseHash must match sha256:<64 hex chars> when present"}};const o=["scopeId","delegationRef","clientDid","reason"];for(const e of o)if(void 0!==r[e]&&"string"!=typeof r[e])return{success:!1,error:{message:`meta.${e} must be a string if present`}};return void 0===r.outcome||["allowed","denied","step_up_required","needs_authorization"].includes(r.outcome)?{success:!0,data:e}:{success:!1,error:{message:"meta.outcome must be one of allowed | denied | step_up_required | needs_authorization"}}}var k=i(77753);const N=new TextEncoder;function R(e){for(let t=0;t<e.length;t+=1){const i=e.charCodeAt(t);if(i>=55296&&i<=56319){const i=e.charCodeAt(t+1);if(t+1>=e.length||i<56320||i>57343)return!0;t+=1}else if(i>=56320&&i<=57343)return!0}return!1}function O(e,t="$",i=new WeakSet){if(null!==e&&"boolean"!=typeof e)if("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("object"!=typeof e)throw new TypeError(`Cannot canonicalize unsupported value at ${t}`);if(i.has(e))throw new TypeError(`Cannot canonicalize cyclic reference at ${t}`);i.add(e);try{if(Array.isArray(e)){for(let r=0;r<e.length;r+=1){if(!(r in e))throw new TypeError(`Cannot canonicalize sparse array element at ${t}[${r}]`);O(e[r],`${t}[${r}]`,i)}return}const r=Object.getPrototypeOf(e);if(r!==Object.prototype&&null!==r)throw new TypeError(`Cannot canonicalize non-plain object at ${t}`);for(const r of Reflect.ownKeys(e)){if("symbol"==typeof r)throw new TypeError(`Cannot canonicalize symbol-keyed property at ${t}`);if(R(r))throw new TypeError(`Cannot canonicalize object key with lone surrogate at ${t}`);const n=Object.getOwnPropertyDescriptor(e,r);if(n?.enumerable){if(!("value"in n))throw new TypeError(`Cannot canonicalize accessor property at ${t}.${r}`);O(n.value,`${t}.${r}`,i)}}}finally{i.delete(e)}}else{if(!Number.isFinite(e))throw new TypeError(`Cannot canonicalize non-finite number at ${t}: ${e}`);if(Number.isInteger(e)&&!Number.isSafeInteger(e))throw new TypeError(`Cannot canonicalize unsafe integer at ${t}: ${e}`)}else if(R(e))throw new TypeError(`Cannot canonicalize string with lone surrogate at ${t}`)}function P(e){return O(e),(0,k.d)(e)}function L(e){return N.encode(P(e))}function x(e){return P(e)}function M(e,t={}){const i={alg:"EdDSA",typ:"JWT"};t.keyId&&(i.kid=t.keyId);const r="string"==typeof e.issuer?e.issuer:e.issuer?.id,n=e.credentialSubject?.id;let o,s;e.expirationDate&&"string"==typeof e.expirationDate&&(o=Math.floor(new Date(e.expirationDate).getTime()/1e3)),e.issuanceDate&&"string"==typeof e.issuanceDate&&(s=Math.floor(new Date(e.issuanceDate).getTime()/1e3));const c={...e};delete c.proof;const d={iss:r,vc:c};n&&(d.sub=n),o&&(d.exp=o),s&&(d.iat=s),e.id&&"string"==typeof e.id&&(d.jti=e.id);const u=a(JSON.stringify(i)),l=a(JSON.stringify(d));return{header:i,payload:d,encodedHeader:u,encodedPayload:l,signingInput:`${u}.${l}`}}function z(e,t){return`${e}.${t}`}function U(e){const t=e.split(".");if(3!==t.length)return null;try{const e=o(t[0]),i=o(t[1]);return{header:JSON.parse(e),payload:JSON.parse(i),signature:t[2],signingInput:`${t[0]}.${t[1]}`}}catch{return null}}class H{identity;signingFunction;constructor(e,t){this.identity=e,this.signingFunction=t}async issueDelegationCredential(e,t={}){let i=p(e,{id:t.id,issuanceDate:t.issuanceDate,expirationDate:t.expirationDate,credentialStatus:t.credentialStatus});if(t.additionalContexts&&t.additionalContexts.length>0){const e=i["@context"];i={...i,"@context":[...e,...t.additionalContexts]}}const r=this.canonicalizeVC(i),n=await this.signingFunction(r,this.identity.getDid(),this.identity.getKeyId());return{...i,proof:n}}async createAndIssueDelegation(e,t={}){const i=Date.now(),r={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:i,metadata:e.metadata};return this.issueDelegationCredential(r,t)}canonicalizeVC(e){return x(e)}getIssuerDid(){return this.identity.getDid()}getIssuerKeyId(){return this.identity.getKeyId()}}function j(e,t){return new H(e,t)}const K=["id","delegation"];function $(e,t={}){const i=m(e);if(!i.success)return{valid:!1,reason:`Schema validation failed: ${i.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 r=e.credentialSubject.delegation;if("revoked"===r.status)return{valid:!1,reason:"Delegation status is revoked"};if("expired"===r.status)return{valid:!1,reason:"Delegation status is expired"};if(!r.issuerDid||!r.subjectDid)return{valid:!1,reason:"Missing issuer or subject DID"};if((t.requireEmbeddedProof??1)&&!e.proof)return{valid:!1,reason:"Missing proof"};const n=function(e){const t=Object.keys(e.credentialSubject).filter(e=>!K.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 n.valid?{valid:!0}:n}async function V(e,t){const i=Date.now();try{return t?await t.checkStatus(e)?{valid:!1,reason:`Credential revoked via StatusList2021 (${e.statusPurpose})`,outcome:"revoked",durationMs:Date.now()-i}:{valid:!0,durationMs:Date.now()-i}:{valid:!1,reason:"Credential has credentialStatus but no status list resolver is configured — cannot verify revocation status",outcome:"status_unresolvable",durationMs:Date.now()-i}}catch(e){return{valid:!1,reason:`Status check error: ${e instanceof Error?e.message:"Unknown error"}`,outcome:"status_unresolvable",durationMs:Date.now()-i}}}const B=new TextEncoder,q=new TextDecoder;function F(...e){const t=e.reduce((e,{length:t})=>e+t,0),i=new Uint8Array(t);let r=0;for(const t of e)i.set(t,r),r+=t.length;return i}function W(e){const t=new Uint8Array(e.length);for(let i=0;i<e.length;i++){const r=e.charCodeAt(i);if(r>127)throw new TypeError("non-ASCII string encountered in encode()");t[i]=r}return t}function G(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e);const t=atob(e),i=new Uint8Array(t.length);for(let e=0;e<t.length;e++)i[e]=t.charCodeAt(e);return i}function J(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64("string"==typeof e?e:q.decode(e),{alphabet:"base64url"});let t=e;t instanceof Uint8Array&&(t=q.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/");try{return G(t)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}}function Y(e){let t=e;return"string"==typeof t&&(t=B.encode(t)),Uint8Array.prototype.toBase64?t.toBase64({alphabet:"base64url",omitPadding:!0}):function(e){if(Uint8Array.prototype.toBase64)return e.toBase64();const t=[];for(let i=0;i<e.length;i+=32768)t.push(String.fromCharCode.apply(null,e.subarray(i,i+32768)));return btoa(t.join(""))}(t).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}class X 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 Z extends X{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"}class Q extends X{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"}class ee extends X{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"}class te extends X{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"}Symbol.asyncIterator;class ie extends X{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(e="signature verification failed",t){super(e,t)}}const re=(e,t)=>{if(e.byteLength!==t.length)return!1;for(let i=0;i<e.byteLength;i++)if(e[i]!==t[i])return!1;return!0},ne=e=>{const t=e.data[e.pos++];if(128&t){const i=127&t;let r=0;for(let t=0;t<i;t++)r=r<<8|e.data[e.pos++];return r}return t},oe=(e,t,i)=>{if(e.data[e.pos++]!==t)throw new Error(i)},se=(e,t)=>{const i=e.data.subarray(e.pos,e.pos+t);return e.pos+=t,i},ae=(e,t,i)=>{const r=((e,t)=>G(e.replace(t,"")))(e,/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g);let n=i;return t?.startsWith?.("ECDH-ES")&&(n||={},n.getNamedCurve=e=>{const t={data:e,pos:0};return function(e){oe(e,48,"Invalid PKCS#8 structure"),ne(e),oe(e,2,"Expected version field");const t=ne(e);e.pos+=t,oe(e,48,"Expected algorithm identifier");ne(e);e.pos}(t),(e=>{const t=(e=>{oe(e,6,"Expected algorithm OID");const t=ne(e);return se(e,t)})(e);if(re(t,[43,101,110]))return"X25519";if(!re(t,[42,134,72,206,61,2,1]))throw new Error("Unsupported key algorithm");oe(e,6,"Expected curve OID");const i=ne(e),r=se(e,i);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(re(r,t))return e;throw new Error("Unsupported named curve")})(t)}),(async(e,t,i,r)=>{let n,o;const s="spki"===e,a=()=>s?["verify"]:["sign"];switch(i){case"PS256":case"PS384":case"PS512":n={name:"RSA-PSS",hash:`SHA-${i.slice(-3)}`},o=a();break;case"RS256":case"RS384":case"RS512":n={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${i.slice(-3)}`},o=a();break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":n={name:"RSA-OAEP",hash:`SHA-${parseInt(i.slice(-3),10)||1}`},o=s?["encrypt","wrapKey"]:["decrypt","unwrapKey"];break;case"ES256":case"ES384":case"ES512":n={name:"ECDSA",namedCurve:{ES256:"P-256",ES384:"P-384",ES512:"P-521"}[i]},o=a();break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":try{const e=r.getNamedCurve(t);n="X25519"===e?{name:"X25519"}:{name:"ECDH",namedCurve:e}}catch(e){throw new Q("Invalid or unsupported key format")}o=s?[]:["deriveBits"];break;case"Ed25519":case"EdDSA":n={name:"Ed25519"},o=a();break;case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":n={name:i},o=a();break;default:throw new Q('Invalid or unsupported "alg" (Algorithm) value')}return crypto.subtle.importKey(e,t,n,r?.extractable??!!s,o)})("pkcs8",r,t,n)},ce='Invalid or unsupported JWK "alg" (Algorithm) Parameter value';async function de(e){if(!e.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:t,keyUsages:i}=function(e){let t,i;switch(e.kty){case"AKP":switch(e.alg){case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":t={name:e.alg},i=e.priv?["sign"]:["verify"];break;default:throw new Q(ce)}break;case"RSA":switch(e.alg){case"PS256":case"PS384":case"PS512":t={name:"RSA-PSS",hash:`SHA-${e.alg.slice(-3)}`},i=e.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":t={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.alg.slice(-3)}`},i=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}`},i=e.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new Q(ce)}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]},i=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},i=e.d?["deriveBits"]:[];break;default:throw new Q(ce)}break;case"OKP":switch(e.alg){case"Ed25519":case"EdDSA":t={name:"Ed25519"},i=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:e.crv},i=e.d?["deriveBits"]:[];break;default:throw new Q(ce)}break;default:throw new Q('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:i}}(e),r={...e};return"AKP"!==r.kty&&delete r.alg,delete r.use,crypto.subtle.importKey("jwk",r,t,e.ext??(!e.d&&!e.priv),e.key_ops??i)}const ue=e=>"object"==typeof e&&null!==e;function le(e){if(!ue(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 he(...e){const t=e.filter(Boolean);if(0===t.length||1===t.length)return!0;let i;for(const e of t){const t=Object.keys(e);if(i&&0!==i.size)for(const e of t){if(i.has(e))return!1;i.add(e)}else i=new Set(t)}return!0}const pe=e=>le(e)&&"string"==typeof e.kty;async function fe(e,t,i){if(!le(e))throw new TypeError("JWK must be an object");let r;switch(t??=e.alg,r??=i?.extractable??e.ext,e.kty){case"oct":if("string"!=typeof e.k||!e.k)throw new TypeError('missing "k" (Key Value) Parameter value');return J(e.k);case"RSA":if("oth"in e&&void 0!==e.oth)throw new Q('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');return de({...e,alg:t,ext:r});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 de({...e,ext:r});case"EC":case"OKP":return de({...e,alg:t,ext:r});default:throw new Q('Unsupported "kty" (Key Type) Parameter value')}}const ge=(e,t="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`),ye=(e,t)=>e.name===t;function me(e,t){var i;if(i=e.hash,parseInt(i.name.slice(4),10)!==t)throw ge(`SHA-${t}`,"algorithm.hash")}function ve(e,t,i){switch(t){case"HS256":case"HS384":case"HS512":if(!ye(e.algorithm,"HMAC"))throw ge("HMAC");me(e.algorithm,parseInt(t.slice(2),10));break;case"RS256":case"RS384":case"RS512":if(!ye(e.algorithm,"RSASSA-PKCS1-v1_5"))throw ge("RSASSA-PKCS1-v1_5");me(e.algorithm,parseInt(t.slice(2),10));break;case"PS256":case"PS384":case"PS512":if(!ye(e.algorithm,"RSA-PSS"))throw ge("RSA-PSS");me(e.algorithm,parseInt(t.slice(2),10));break;case"Ed25519":case"EdDSA":if(!ye(e.algorithm,"Ed25519"))throw ge("Ed25519");break;case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":if(!ye(e.algorithm,t))throw ge(t);break;case"ES256":case"ES384":case"ES512":{if(!ye(e.algorithm,"ECDSA"))throw ge("ECDSA");const i=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!==i)throw ge(i,"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,i)}function Ie(e,t,...i){if((i=i.filter(Boolean)).length>2){const t=i.pop();e+=`one of type ${i.join(", ")}, or ${t}.`}else 2===i.length?e+=`one of type ${i[0]} or ${i[1]}.`:e+=`of type ${i[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 Ee=(e,t,...i)=>Ie(`Key for the ${e} algorithm must be `,t,...i);function we(e,t){if(e.startsWith("RS")||e.startsWith("PS")){const{modulusLength:i}=t.algorithm;if("number"!=typeof i||i<2048)throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}}function Se(e,t){const i=`SHA-${e.slice(-3)}`;switch(e){case"HS256":case"HS384":case"HS512":return{hash:i,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:i,name:"RSA-PSS",saltLength:parseInt(e.slice(-3),10)>>3};case"RS256":case"RS384":case"RS512":return{hash:i,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:i,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 Q(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}async function De(e,t,i){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(Ie("Key must be ",t,"CryptoKey","KeyObject","JSON Web Key"));return crypto.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[i])}return ve(t,e,i),t}function Ae(e,t){if(e)throw new TypeError(`${t} can only be called once`)}function be(e,t,i){try{return J(e)}catch{throw new i(`Failed to base64url decode the ${t}`)}}Symbol();const _e=e=>{if("CryptoKey"===e?.[Symbol.toStringTag])return!0;try{return e instanceof CryptoKey}catch{return!1}},Ce=e=>"KeyObject"===e?.[Symbol.toStringTag],Te=e=>_e(e)||Ce(e),ke=e=>e?.[Symbol.toStringTag],Ne=(e,t,i)=>{if(void 0!==t.use){let e;switch(i){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 r;switch(!0){case"sign"===i||"verify"===i:case"dir"===e:case e.includes("CBC-HS"):r=i;break;case e.startsWith("PBES2"):r="deriveBits";break;case/^A\d{3}(?:GCM)?(?:KW)?$/.test(e):r=!e.includes("GCM")&&e.endsWith("KW")?"encrypt"===i?"wrapKey":"unwrapKey":i;break;case"encrypt"===i&&e.startsWith("RSA"):r="wrapKey";break;case"decrypt"===i:r=e.startsWith("RSA")?"unwrapKey":"deriveBits"}if(r&&!1===t.key_ops?.includes?.(r))throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${r}" when present`)}return!0};function Re(e,t,i){switch(e.substring(0,2)){case"A1":case"A2":case"di":case"HS":case"PB":((e,t,i)=>{if(!(t instanceof Uint8Array)){if(pe(t)){if((e=>"oct"===e.kty&&"string"==typeof e.k)(t)&&Ne(e,t,i))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(!Te(t))throw new TypeError(Ee(e,t,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"));if("secret"!==t.type)throw new TypeError(`${ke(t)} instances for symmetric algorithms must be of type "secret"`)}})(e,t,i);break;default:((e,t,i)=>{if(pe(t))switch(i){case"decrypt":case"sign":if((e=>"oct"!==e.kty&&("AKP"===e.kty&&"string"==typeof e.priv||"string"==typeof e.d))(t)&&Ne(e,t,i))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)&&Ne(e,t,i))return;throw new TypeError("JSON Web Key for this operation must be a public JWK")}if(!Te(t))throw new TypeError(Ee(e,t,"CryptoKey","KeyObject","JSON Web Key"));if("secret"===t.type)throw new TypeError(`${ke(t)} instances for asymmetric algorithms must not be of type "secret"`);if("public"===t.type)switch(i){case"sign":throw new TypeError(`${ke(t)} instances for asymmetric algorithm signing must be of type "private"`);case"decrypt":throw new TypeError(`${ke(t)} instances for asymmetric algorithm decryption must be of type "private"`)}if("private"===t.type)switch(i){case"verify":throw new TypeError(`${ke(t)} instances for asymmetric algorithm verifying must be of type "public"`);case"encrypt":throw new TypeError(`${ke(t)} instances for asymmetric algorithm encryption must be of type "public"`)}})(e,t,i)}}function Oe(e,t,i,r,n){if(void 0!==n.crit&&void 0===r?.crit)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!r||void 0===r.crit)return new Set;if(!Array.isArray(r.crit)||0===r.crit.length||r.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 o;o=void 0!==i?new Map([...Object.entries(i),...t.entries()]):t;for(const t of r.crit){if(!o.has(t))throw new Q(`Extension Header Parameter "${t}" is not recognized`);if(void 0===n[t])throw new e(`Extension Header Parameter "${t}" is missing`);if(o.get(t)&&void 0===r[t])throw new e(`Extension Header Parameter "${t}" MUST be integrity protected`)}return new Set(r.crit)}const Pe="given KeyObject instance cannot be used for this algorithm";let Le;const xe=async(e,t,i,r=!1)=>{Le||=new WeakMap;let n=Le.get(e);if(n?.[i])return n[i];const o=await de({...t,alg:i});return r&&Object.freeze(e),n?n[i]=o:Le.set(e,{[i]:o}),o};async function Me(e,t){if(e instanceof Uint8Array)return e;if(_e(e))return e;if(Ce(e)){if("secret"===e.type)return e.export();if("toCryptoKey"in e&&"function"==typeof e.toCryptoKey)try{return((e,t)=>{Le||=new WeakMap;let i=Le.get(e);if(i?.[t])return i[t];const r="public"===e.type,n=!!r;let o;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)}o=e.toCryptoKey(e.asymmetricKeyType,n,r?[]:["deriveBits"])}if("ed25519"===e.asymmetricKeyType){if("EdDSA"!==t&&"Ed25519"!==t)throw new TypeError(Pe);o=e.toCryptoKey(e.asymmetricKeyType,n,[r?"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);o=e.toCryptoKey(e.asymmetricKeyType,n,[r?"verify":"sign"])}if("rsa"===e.asymmetricKeyType){let i;switch(t){case"RSA-OAEP":i="SHA-1";break;case"RS256":case"PS256":case"RSA-OAEP-256":i="SHA-256";break;case"RS384":case"PS384":case"RSA-OAEP-384":i="SHA-384";break;case"RS512":case"PS512":case"RSA-OAEP-512":i="SHA-512";break;default:throw new TypeError(Pe)}if(t.startsWith("RSA-OAEP"))return e.toCryptoKey({name:"RSA-OAEP",hash:i},n,r?["encrypt"]:["decrypt"]);o=e.toCryptoKey({name:t.startsWith("PS")?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:i},n,[r?"verify":"sign"])}if("ec"===e.asymmetricKeyType){const i=new Map([["prime256v1","P-256"],["secp384r1","P-384"],["secp521r1","P-521"]]).get(e.asymmetricKeyDetails?.namedCurve);if(!i)throw new TypeError(Pe);const s={ES256:"P-256",ES384:"P-384",ES512:"P-521"};s[t]&&i===s[t]&&(o=e.toCryptoKey({name:"ECDSA",namedCurve:i},n,[r?"verify":"sign"])),t.startsWith("ECDH-ES")&&(o=e.toCryptoKey({name:"ECDH",namedCurve:i},n,r?[]:["deriveBits"]))}if(!o)throw new TypeError(Pe);return i?i[t]=o:Le.set(e,{[t]:o}),o})(e,t)}catch(e){if(e instanceof TypeError)throw e}let i=e.export({format:"jwk"});return xe(e,i,t)}if(pe(e))return e.k?J(e.k):xe(e,e,t,!0);throw new Error("unreachable")}async function ze(e,t,i){if(e instanceof Uint8Array&&(e=q.decode(e)),"string"!=typeof e)throw new ee("Compact JWS must be a string or Uint8Array");const{0:r,1:n,2:o,length:s}=e.split(".");if(3!==s)throw new ee("Invalid Compact JWS");const a=await async function(e,t,i){if(!le(e))throw new ee("Flattened JWS must be an object");if(void 0===e.protected&&void 0===e.header)throw new ee('Flattened JWS must have either of the "protected" or "header" members');if(void 0!==e.protected&&"string"!=typeof e.protected)throw new ee("JWS Protected Header incorrect type");if(void 0===e.payload)throw new ee("JWS Payload missing");if("string"!=typeof e.signature)throw new ee("JWS Signature missing or incorrect type");if(void 0!==e.header&&!le(e.header))throw new ee("JWS Unprotected Header incorrect type");let r={};if(e.protected)try{const t=J(e.protected);r=JSON.parse(q.decode(t))}catch{throw new ee("JWS Protected Header is invalid")}if(!he(r,e.header))throw new ee("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const n={...r,...e.header};let o=!0;if(Oe(ee,new Map([["b64",!0]]),i?.crit,r,n).has("b64")&&(o=r.b64,"boolean"!=typeof o))throw new ee('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:s}=n;if("string"!=typeof s||!s)throw new ee('JWS "alg" (Algorithm) Header Parameter missing or invalid');const a=i&&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,i.algorithms);if(a&&!a.has(s))throw new Z('"alg" (Algorithm) Header Parameter value not allowed');if(o){if("string"!=typeof e.payload)throw new ee("JWS Payload must be a string")}else if("string"!=typeof e.payload&&!(e.payload instanceof Uint8Array))throw new ee("JWS Payload must be a string or an Uint8Array instance");let c=!1;"function"==typeof t&&(t=await t(r,e),c=!0),Re(s,t,"verify");const d=F(void 0!==e.protected?W(e.protected):new Uint8Array,W("."),"string"==typeof e.payload?o?W(e.payload):B.encode(e.payload):e.payload),u=be(e.signature,"signature",ee),l=await Me(t,s),h=await async function(e,t,i,r){const n=await De(e,t,"verify");we(e,n);const o=Se(e,n.algorithm);try{return await crypto.subtle.verify(o,n,i,r)}catch{return!1}}(s,l,u,d);if(!h)throw new ie;let p;p=o?be(e.payload,"payload",ee):"string"==typeof e.payload?B.encode(e.payload):e.payload;const f={payload:p};return void 0!==e.protected&&(f.protectedHeader=r),void 0!==e.header&&(f.unprotectedHeader=e.header),c?{...f,key:l}:f}({payload:n,protected:r,signature:o},t,i),c={payload:a.payload,protectedHeader:a.protectedHeader};return"function"==typeof t?{...c,key:a.key}:c}function Ue(e,t,i){return{valid:!1,reason:e,stage:"basic",metrics:void 0!==i?{basicCheckMs:i,totalMs:Date.now()-t}:{totalMs:Date.now()-t},checks:{basicValid:!1}}}class He{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 i=Date.now(),r=this.cacheKeyForCredential("di",e,t);if(null!==r){const e=this.getFromCache(r);if(e)return{...e,cached:!0}}const n=Date.now(),o=$(e),s=Date.now()-n;if(!o.valid)return{valid:!1,reason:o.reason,stage:"basic",metrics:{basicCheckMs:s,totalMs:Date.now()-i},checks:{basicValid:!1}};const a=t.skipSignature?Promise.resolve({valid:!0,durationMs:0}):async function(e,t,i){const r=Date.now();try{const n="string"==typeof e.issuer?e.issuer:e.issuer.id;if(!t||!i)return{valid:!1,reason:"No DID resolver or signature verifier configured — signature cannot be verified",durationMs:Date.now()-r};const o=await t.resolve(n);if(!o)return{valid:!1,reason:`Could not resolve issuer DID: ${n}`,durationMs:Date.now()-r};if(!e.proof)return{valid:!1,reason:"Proof is missing",durationMs:Date.now()-r};const s=e.proof.verificationMethod;if(!s)return{valid:!1,reason:"Proof missing verificationMethod",durationMs:Date.now()-r};const a=function(e,t){return e.verificationMethod?.find(e=>e.id===t)}(o,s);if(!a)return{valid:!1,reason:`Verification method ${s} not found`,durationMs:Date.now()-r};const c=a.publicKeyJwk;if(!c)return{valid:!1,reason:"Verification method missing publicKeyJwk",durationMs:Date.now()-r};const d=await i(e,c);return{valid:d.valid,reason:d.reason,durationMs:Date.now()-r}}catch(e){return{valid:!1,reason:`Signature verification error: ${e instanceof Error?e.message:"Unknown error"}`,durationMs:Date.now()-r}}}(e,t.didResolver||this.didResolver,this.signatureVerifier),c=!t.skipStatus&&e.credentialStatus?V(e.credentialStatus,t.statusListResolver||this.statusListResolver):Promise.resolve({valid:!0,durationMs:0});return this.finalizeVerification(a,c,s,i,r)}async verifyDelegationJwt(e,t={}){const i=Date.now(),r=function(e,t){const i=U(e);if(!i)return{failure:Ue("Not a valid VC-JWT (parse failed)",t)};const r=Date.now(),n=i.payload.vc,o=$(n,{requireEmbeddedProof:!1}),s=Date.now()-r;return o.valid?function(e){const t=e.issuer;return"string"==typeof t?t:t&&"object"==typeof t&&"string"==typeof t.id?t.id:void 0}(n)!==i.payload.iss?{failure:Ue("Credential `issuer` does not match the JWT `iss` (the verified signer)",t,s)}:{vc:n,issuerDid:i.payload.iss,kid:i.header.kid,basicCheckMs:s}:{failure:Ue(o.reason,t,s)}}(e,i);if("failure"in r)return r.failure;const{vc:n,issuerDid:o,kid:s,basicCheckMs:a}=r,c=this.cacheKeyForJwt(e,n,t);if(null!==c){const e=this.getFromCache(c);if(e)return{...e,cached:!0}}const d=t.skipSignature?Promise.resolve({valid:!0,durationMs:0}):async function(e,t,i,r){const n=Date.now(),o=(e,t)=>({valid:e,reason:t,durationMs:Date.now()-n});if(!r)return o(!1,"No DID resolver configured — signature cannot be verified");const s=await r.resolve(t);if(!s)return o(!1,`Could not resolve issuer DID: ${t}`);const a=function(e,t){return t?e.find(e=>e.id===t):e[0]}(s.verificationMethod??[],i);if(!a)return o(!1,i?`Verification method ${i} not found in DID Document`:"DID Document has no verification method");if(!a.publicKeyJwk)return o(!1,"Verification method missing publicKeyJwk");try{const t=await fe(a.publicKeyJwk,"EdDSA");return await ze(e,t,{algorithms:["EdDSA"]}),o(!0)}catch(e){return o(!1,`JWT envelope signature is not valid: ${function(e){return e instanceof Error?e.message:String(e)}(e)}`)}}(e,o,s,t.didResolver||this.didResolver),u=!t.skipStatus&&n.credentialStatus?V(n.credentialStatus,t.statusListResolver||this.statusListResolver):Promise.resolve({valid:!0,durationMs:0});return this.finalizeVerification(d,u,a,i,c)}async finalizeVerification(e,t,i,r,n){const[o,s]=await Promise.all([e,t]),a=function(e,t,i,r){const n=e.valid&&t.valid;return{valid:n,reason:n?void 0:e.reason||t.reason||"Unknown failure",statusOutcome:t.outcome,stage:"complete",metrics:{basicCheckMs:i,signatureCheckMs:e.durationMs||0,statusCheckMs:t.durationMs||0,totalMs:Date.now()-r},checks:{basicValid:!0,signatureValid:e.valid,statusValid:t.valid}}}(o,s,i,r);return a.valid&&null!==n&&this.setInCache(n,a),a}cacheKeyForCredential(e,t,i){if(!this.cacheAllowed(i))return null;try{return`${e}\0${t.id??""}\0${this.verificationProfile(i)}\0${P(t)}`}catch{return null}}cacheKeyForJwt(e,t,i){return this.cacheAllowed(i)?`jwt\0${t.id??""}\0${this.verificationProfile(i)}\0${e}`:null}cacheAllowed(e){return!e.skipCache&&void 0===e.didResolver&&void 0===e.statusListResolver}verificationProfile(e){return`signature:${e.skipSignature?"skip":"verify"}|status:${e.skipStatus?"skip":"verify"}`}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){const t=`di\0${e}\0`,i=`jwt\0${e}\0`;for(const e of[...this.cache.keys()]){if(!e.startsWith(t)&&!e.startsWith(i))continue;this.cache.delete(e);const r=this.cacheInsertionOrder.indexOf(e);-1!==r&&this.cacheInsertionOrder.splice(r,1)}}}function je(e){return new He(e)}class Ke{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};if(e.parentId&&!await this.storage.getNode(e.parentId))throw new Error(`Parent delegation not found: ${e.parentId}`);if("registerNodeAtomic"in(i=this.storage)&&"function"==typeof i.registerNodeAtomic)await this.storage.registerNodeAtomic(t);else if(await this.storage.setNode(t),e.parentId)try{await this.addChildToParent(e.parentId,e.id)}catch(t){try{await this.storage.deleteNode(e.id)}catch(e){throw new AggregateError([t,e],"Delegation registration failed and its non-atomic rollback also failed",{cause:t})}throw t}var i;return t}async addChildToParent(e,t){const i=await this.storage.getNode(e);if(!i)throw new Error(`Parent delegation not found: ${e}`);i.children.includes(t)||(i.children.push(t),await this.storage.setNode(i))}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 i=t[e-1],r=t[e];if(r.issuerDid!==i.subjectDid)return{valid:!1,reason:`Invalid chain: ${r.id} issued by ${r.issuerDid} but parent ${i.id} subject is ${i.subjectDid}`};if(r.parentId!==i.id)return{valid:!1,reason:`Invalid chain: ${r.id} parentId=${r.parentId} but actual parent is ${i.id}`}}return{valid:!0}}async removeDelegation(e){const t=await this.storage.getNode(e);if(t){if(t.parentId){const i=await this.storage.getNode(t.parentId);i&&(i.children=i.children.filter(t=>t!==e),await this.storage.setNode(i))}await this.storage.deleteNode(e)}}}function $e(e){return new Ke(e)}const Ve=16777216,Be="u";class qe{compressor;bits;size;constructor(e,t,i){this.compressor=t,this.size=e;const r=Math.ceil(e/8);this.bits=new Uint8Array(r)}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 i=Math.floor(e/8),r=e%8;t?this.bits[i]|=128>>r:this.bits[i]&=255^128>>r}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),i=e%8;return!!(this.bits[t]&128>>i)}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 Be+this.base64urlEncode(e)}static async decode(e,t,i){const r=await Fe(e,i),n=8*r.length,o=new qe(n,t,i);return o.bits=r,o}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,i,r){const n=new qe(e,i,r);for(const e of t)n.setBit(e,!0);return n}}async function Fe(e,t){const i=await t.decompress(function(e){let t=(e[0]===Be?e.slice(1):e).replace(/-/g,"+").replace(/_/g,"/");t+="=".repeat((4-t.length%4)%4);const i=atob(t),r=new Uint8Array(i.length);for(let e=0;e<i.length;e++)r[e]=i.charCodeAt(e);return r}(e));if(i.length>Ve)throw new Error(`Status list too large: ${i.length} bytes exceeds ${Ve}`);return i}async function We(e,t,i){const r=await Fe(e,i),n=Math.floor(t/8),o=t%8;if(!Number.isInteger(t)||t<0||n>=r.length)throw new Error(`Bit index ${t} out of range for the status list`);return!!(r[n]&128>>o)}class Ge{storage;identity;signingFunction;compressor;decompressor;statusListBaseUrl;defaultListSize;updateLocks=new Map;constructor(e,t,i,r,n,o){this.storage=e,this.identity=t,this.signingFunction=i,this.compressor=r,this.decompressor=n,this.statusListBaseUrl=o?.statusListBaseUrl||"https://status.example.com",this.defaultListSize=o?.defaultListSize||131072}async allocateStatusEntry(e){const t=`${this.statusListBaseUrl}/${e}/v1`,i=await this.storage.allocateIndex(t);return await this.ensureStatusListExists(t,e),{id:`${t}#${i}`,type:"StatusList2021Entry",statusPurpose:e,statusListIndex:i.toString(),statusListCredential:t}}async updateStatus(e,t){const{statusListCredential:i}=e,r=(this.updateLocks.get(i)??Promise.resolve()).then(()=>this.doUpdateStatus(e,t));this.updateLocks.set(i,r.catch(()=>{})),await r}async doUpdateStatus(e,t){const{statusListCredential:i,statusListIndex:r}=e,n=await this.storage.getStatusList(i);if(!n)throw new Error(`Status list not found: ${i}`);const o=await qe.decode(n.credentialSubject.encodedList,this.compressor,this.decompressor),s=parseInt(r,10);o.setBit(s,t);const a=await o.encode(),c={...n,credentialSubject:{...n.credentialSubject,encodedList:a}},d={...c};delete d.proof;const u=x(d),l=await this.signingFunction(u,this.identity.getDid(),this.identity.getKeyId()),h={...c,proof:l};await this.storage.setStatusList(i,h)}async checkStatus(e){const{statusListCredential:t,statusListIndex:i}=e,r=await this.storage.getStatusList(t);if(!r)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}"`)}(r.credentialSubject.statusPurpose,e.statusPurpose);const n=await qe.decode(r.credentialSubject.encodedList,this.compressor,this.decompressor);if(!/^[0-9]+$/.test(i))throw new Error(`Invalid statusListIndex "${i}" — must be a canonical non-negative decimal`);const o=Number(i);if(!Number.isSafeInteger(o))throw new Error(`statusListIndex "${i}" exceeds the safe integer range`);return n.getBit(o)}async getRevokedIndices(e){const t=await this.storage.getStatusList(e);return t?(await qe.decode(t.credentialSubject.encodedList,this.compressor,this.decompressor)).getSetBits():[]}async ensureStatusListExists(e,t){if(await this.storage.getStatusList(e))return;const i=new qe(this.defaultListSize,this.compressor,this.decompressor),r=await i.encode(),n={"@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:r}},o=x(n),s=await this.signingFunction(o,this.identity.getDid(),this.identity.getKeyId()),a={...n,proof:s};await this.storage.setStatusList(e,a)}getStatusListBaseUrl(){return this.statusListBaseUrl}getDefaultListSize(){return this.defaultListSize}}function Je(e,t,i,r,n,o){return new Ge(e,t,i,r,n,o)}class Ye{graph;statusList;constructor(e,t){this.graph=e,this.statusList=t}async revokeDelegation(e,t={}){const i=t.maxDepth||100,r=[],n=await this.graph.getNode(e);if(!n)throw new Error(`Delegation not found: ${e}`);const o=await this.graph.getDepth(e);if(o>i)throw new Error(`Delegation depth ${o} exceeds maximum ${i}`);const s=await this.revokeNode(n,!0,t.reason,t.dryRun);r.push(s),t.onRevoke&&await t.onRevoke(s);const a=await this.graph.getDescendants(e);for(const i of a){const n=await this.revokeNode(i,!1,`Cascaded from ${e}`,t.dryRun,e);r.push(n),t.onRevoke&&await t.onRevoke(n)}return r}async revokeNode(e,t,i,r,n){const o={delegationId:e.id,isRoot:t,parentId:n,timestamp:Date.now(),reason:i};if(r)return o;if(e.credentialStatusId){const t=this.parseCredentialStatus(e.credentialStatusId);t&&await this.statusList.updateStatus(t,!0)}return o}async restoreDelegation(e){const t=await this.graph.getNode(e);if(!t)throw new Error(`Delegation not found: ${e}`);const i={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 i}async isRevoked(e){const t=await this.graph.getChain(e);for(const i of t)if(i.credentialStatusId){const t=this.parseCredentialStatus(i.credentialStatusId);if(t&&await this.statusList.checkStatus(t))return{revoked:!0,reason:i.id===e?"Directly revoked":"Ancestor revoked",revokedAncestor:i.id===e?void 0:i.id}}return{revoked:!1}}async getRevokedInSubtree(e){const t=await this.graph.getDescendants(e),i=[];(await this.isRevoked(e)).revoked&&i.push(e);for(const e of t)(await this.isRevoked(e.id)).revoked&&i.push(e.id);return i}parseCredentialStatus(e){const t=e.match(/^(.+)#(\d+)$/);if(!t)return null;const[,i,r]=t;return{id:e,type:"StatusList2021Entry",statusPurpose:"revocation",statusListIndex:parseInt(r,10).toString(),statusListCredential:i}}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 i=await this.graph.validateChain(e);return i.valid?{valid:!0}:i}}function Xe(e,t){return new Ye(e,t)}function Ze(e,t){if(!e.constraints.audience)return!0;const i=e.constraints.audience;return"string"==typeof i?i===t:i.includes(t)}class Qe{#e;#t;#i;constructor(e){if(!(e instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this.#e=e}setProtectedHeader(e){return Ae(this.#t,"setProtectedHeader"),this.#t=e,this}setUnprotectedHeader(e){return Ae(this.#i,"setUnprotectedHeader"),this.#i=e,this}async sign(e,t){if(!this.#t&&!this.#i)throw new ee("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!he(this.#t,this.#i))throw new ee("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const i={...this.#t,...this.#i};let r=!0;if(Oe(ee,new Map([["b64",!0]]),t?.crit,this.#t,i).has("b64")&&(r=this.#t.b64,"boolean"!=typeof r))throw new ee('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:n}=i;if("string"!=typeof n||!n)throw new ee('JWS "alg" (Algorithm) Header Parameter missing or invalid');let o,s,a,c;Re(n,e,"sign"),r?(o=Y(this.#e),s=W(o)):(s=this.#e,o=""),this.#t?(a=Y(JSON.stringify(this.#t)),c=W(a)):(a="",c=new Uint8Array);const d=F(c,W("."),s),u=await Me(e,n),l=await async function(e,t,i){const r=await De(e,t,"sign");we(e,r);const n=await crypto.subtle.sign(Se(e,r.algorithm),r,i);return new Uint8Array(n)}(n,u,d),h={signature:Y(l),payload:o};return this.#i&&(h.header=this.#i),this.#t&&(h.protected=a),h}}class et{#r;constructor(e){this.#r=new Qe(e)}setProtectedHeader(e){return this.#r.setProtectedHeader(e),this}async sign(e,t){const i=await this.#r.sign(e,t);if(void 0===i.payload)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${i.protected}.${i.payload}.${i.signature}`}}const tt=e=>Math.floor(e.getTime()/1e3),it=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;function rt(e){const t=it.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");const i=parseFloat(t[2]);let r;switch(t[3].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":r=Math.round(i);break;case"minute":case"minutes":case"min":case"mins":case"m":r=Math.round(60*i);break;case"hour":case"hours":case"hr":case"hrs":case"h":r=Math.round(3600*i);break;case"day":case"days":case"d":r=Math.round(86400*i);break;case"week":case"weeks":case"w":r=Math.round(604800*i);break;default:r=Math.round(31557600*i)}return"-"===t[1]||"ago"===t[4]?-r:r}function nt(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}class ot{#e;constructor(e){if(!le(e))throw new TypeError("JWT Claims Set MUST be an object");this.#e=structuredClone(e)}data(){return B.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=nt("setNotBefore",e):e instanceof Date?this.#e.nbf=nt("setNotBefore",tt(e)):this.#e.nbf=tt(new Date)+rt(e)}set exp(e){"number"==typeof e?this.#e.exp=nt("setExpirationTime",e):e instanceof Date?this.#e.exp=nt("setExpirationTime",tt(e)):this.#e.exp=tt(new Date)+rt(e)}set iat(e){void 0===e?this.#e.iat=tt(new Date):e instanceof Date?this.#e.iat=nt("setIssuedAt",tt(e)):this.#e.iat=nt("setIssuedAt","string"==typeof e?tt(new Date)+rt(e):e)}}class st{#t;#n;constructor(e={}){this.#n=new ot(e)}setIssuer(e){return this.#n.iss=e,this}setSubject(e){return this.#n.sub=e,this}setAudience(e){return this.#n.aud=e,this}setJti(e){return this.#n.jti=e,this}setNotBefore(e){return this.#n.nbf=e,this}setExpirationTime(e){return this.#n.exp=e,this}setIssuedAt(e){return this.#n.iat=e,this}setProtectedHeader(e){return this.#t=e,this}async sign(e,t){const i=new et(this.#n.data());if(i.setProtectedHeader(this.#t),Array.isArray(this.#t?.crit)&&this.#t.crit.includes("b64")&&!1===this.#t.b64)throw new te("JWTs MUST NOT use unencoded payload");return i.sign(e,t)}}async function at(e){const{agentDid:t,userDid:i,delegationId:r,delegationChain:n,scopes:o,privateKeyJwk:s,kid:a,targetHostname:c}=e,d=await fe(s,"EdDSA"),u=Math.floor(Date.now()/1e3),l=u+60;return await new st({delegation_id:r,delegation_chain:n,scope:o.join(",")}).setProtectedHeader({alg:"EdDSA",kid:a}).setIssuer(t).setSubject(i).setJti(crypto.randomUUID()).setAudience(c).setIssuedAt(u).setExpirationTime(l).sign(d)}function ct(e){return e.id||e.vcId?e.vcId?`${e.vcId}>${e.id}`:e.id:""}const dt="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",ut=new Map;for(let e=0;e<dt.length;e++){const t=dt[e];void 0!==t&&ut.set(t,e)}function lt(e){if(0===e.length)return"";let t=BigInt(0);for(let i=0;i<e.length;i++){const r=e[i];void 0!==r&&(t=t*BigInt(256)+BigInt(r))}let i="";for(;t>0;)i=dt[Number(t%BigInt(58))]+i,t/=BigInt(58);for(let t=0;t<e.length&&0===e[t];t++)i="1"+i;return i}function ht(e){if(0===e.length)return new Uint8Array(0);let t=BigInt(0);for(const i of e){const e=ut.get(i);if(void 0===e)throw new Error(`Invalid base58 character: ${i}`);t=t*BigInt(58)+BigInt(e)}const i=[];for(;t>0;)i.unshift(Number(t%BigInt(256))),t/=BigInt(256);let r=0;for(const t of e){if("1"!==t)break;r++}const n=new Uint8Array(r+i.length);return n.set(i,r),n}function pt(e){if(0===e.length)return!0;for(const t of e)if(!ut.has(t))return!1;return!0}function ft(e){return"string"==typeof e&&e.startsWith("did:")}function gt(e){if(!ft(e))return null;const t=e.match(/^did:([^:]+):/);return t?.[1]??null}function yt(e){return e.trim()}function mt(e,t){return yt(e)===yt(t)}function vt(e){const t=e.identity.serverDid||e.identity.agentDid;if(!t)throw new Error("Server DID not configured");return t}function It(e){const t=e.split(":");return t[t.length-1]??e}function Et(e){return It(e)}const wt=new Uint8Array([237,1]);function St(e){const t=new Uint8Array(wt.length+e.length);return t.set(wt),t.set(e,wt.length),`did:key:z${lt(t)}`}function Dt(e){return St(Uint8Array.from(atob(e),e=>e.charCodeAt(0)))}function At(e){return e.startsWith("did:key:")?e.slice(8):"keys-1"}const bt={debug:10,info:20,warn:30,error:40};function _t(){let e="info",t=!1;function i(i,...r){if(function(t){return bt[t]>=bt[e]}(i))if(t)console.error(...r);else switch(i){case"debug":"function"==typeof console.debug?console.debug(...r):console.log(...r);break;case"info":"function"==typeof console.info?console.info(...r):console.log(...r);break;case"warn":"function"==typeof console.warn?console.warn(...r):console.error(...r);break;case"error":console.error(...r)}}return{configure(i={}){i.level&&(e=i.level),!0===i.forceStderr?t=!0:!1===i.forceStderr?t=!1:"stdio"===i.transport?t=!0:"sse"!==i.transport&&"http"!==i.transport||(t=!1)},debug:(...e)=>i("debug",...e),info:(...e)=>i("info",...e),warn:(...e)=>i("warn",...e),error:(...e)=>i("error",...e)}}const Ct=_t(),Tt=new Uint8Array([237,1]),kt=32;function Nt(e){return e.startsWith("did:key:z6Mk")}function Rt(e){if(!e.startsWith("did:key:z"))return null;try{const t=ht(e.replace("did:key:","").slice(1));return t.length<Tt.length+kt||t[0]!==Tt[0]||t[1]!==Tt[1]?null:t.slice(Tt.length)}catch(e){return Ct.debug("Failed to extract public key from did:key",e),null}}function Ot(e){return{kty:"OKP",crv:"Ed25519",x:c(e)}}function Pt(){return{resolve:async e=>{if(!Nt(e))return null;const t=Rt(e);if(!t)return null;const i=Ot(t),r=e.replace("did:key:",""),n=At(e);return{id:e,verificationMethod:[{id:`${e}#${n}`,type:"Ed25519VerificationKey2020",controller:e,publicKeyJwk:i,publicKeyMultibase:r}],authentication:[`${e}#${n}`],assertionMethod:[`${e}#${n}`]}}}}function Lt(e){if(!Nt(e))return null;const t=Rt(e);if(!t)return null;const i=Ot(t),r=e.replace("did:key:",""),n=At(e);return{id:e,verificationMethod:[{id:`${e}#${n}`,type:"Ed25519VerificationKey2020",controller:e,publicKeyJwk:i,publicKeyMultibase:r}],authentication:[`${e}#${n}`],assertionMethod:[`${e}#${n}`]}}const xt={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 Mt(e){const{session:t,delegation:i,serverIdentity:r,targetUrl:n}=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(!i.vcId)throw new Error("Delegation must have vcId for outbound delegation");const o=function(e){try{return new URL(e).hostname}catch{return Ct.warn("Failed to parse target URL, using as-is",{url:e}),e}}(n),s=function(e,t){const i=u(e),r=64===i.length?i.subarray(0,32):i;if(!Nt(t))throw new Error(`Server DID must be did:key with Ed25519: ${t}`);const n=Rt(t);if(!n)throw new Error(`Failed to extract public key from DID: ${t}`);return{kty:"OKP",crv:"Ed25519",x:c(n),d:c(r)}}(r.privateKey,r.did),a=await at({agentDid:r.did,userDid:t.agentDid,delegationId:i.id,delegationChain:i.vcId,scopes:["delegation:propagate"],privateKeyJwk:s,kid:r.kid,targetHostname:o});return Ct.debug("Built outbound delegation headers",{agentDid:t.agentDid,delegationChain:i.vcId,sessionId:t.sessionId,targetHostname:o}),{"KYA-OS-Agent-DID":t.agentDid,"KYA-OS-Delegation-Chain":i.vcId,"KYA-OS-Session-Id":t.sessionId,"KYA-OS-Delegation-Proof":a}}class zt{cryptoProvider;constructor(e){this.cryptoProvider=e}async verifyEd25519(e,t,i){try{return!0===await this.cryptoProvider.verify(e,t,i)}catch(e){return Ct.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[i,r,n]=t;let a,c,d;try{a=JSON.parse(o(i))}catch(e){throw new Error(`Invalid header base64: ${e instanceof Error?e.message:String(e)}`)}if(r)try{c=JSON.parse(o(r))}catch(e){throw new Error(`Invalid payload base64: ${e instanceof Error?e.message:String(e)}`)}try{d=s(n)}catch(e){throw new Error(`Invalid signature base64: ${e instanceof Error?e.message:String(e)}`)}return{header:a,payload:c,signatureBytes:d,signingInput:`${i}.${r}`}}async verifyJWS(e,t,i){try{if(!this.isValidEd25519JWK(t))return Ct.error("[CryptoService] Invalid Ed25519 JWK format"),!1;if(i?.expectedKid&&t.kid!==i.expectedKid)return Ct.error("[CryptoService] Key ID mismatch"),!1;let r;try{r=this.parseJWS(e)}catch(t){if(void 0===i?.detachedPayload)return Ct.error("[CryptoService] Invalid JWS format:",t),!1;{const i=e.split(".");if(3!==i.length||""!==i[1])return Ct.error("[CryptoService] Invalid JWS format:",t),!1;try{const e=i[0],t=i[2];r={header:JSON.parse(o(e)),payload:void 0,signatureBytes:s(t),signingInput:""}}catch{return Ct.error("[CryptoService] Invalid detached JWS format"),!1}}}const n=i?.alg||"EdDSA";if(r.header.alg!==n)return Ct.error(`[CryptoService] Unsupported algorithm: ${r.header.alg}, expected ${n}`),!1;if(void 0!==i?.expectedKid&&r.header.kid!==i.expectedKid)return Ct.error("[CryptoService] Protected JWS key ID mismatch"),!1;let a,d;if(void 0!==i?.detachedPayload){const t=e.split(".")[0];let r;r=i.detachedPayload instanceof Uint8Array?c(i.detachedPayload):c((new TextEncoder).encode(i.detachedPayload)),a=(new TextEncoder).encode(`${t}.${r}`)}else{if(!r.signingInput)return Ct.error("[CryptoService] Missing signing input for compact JWS"),!1;a=(new TextEncoder).encode(r.signingInput)}try{d=this.jwkToBase64PublicKey(t)}catch(e){return Ct.error("[CryptoService] Failed to extract public key:",e),!1}return await this.verifyEd25519(a,r.signatureBytes,d)}catch(e){return Ct.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=s(e.x);if(32!==t.length)throw new Error(`Invalid Ed25519 public key length: ${t.length}`);return d(t)}}const Ut=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]),Ht=12,jt=32,Kt="org.kya-os/proof",$t="proof";async function Vt(e,t,i){const r={method:e.method,...e.params?{params:e.params}:{}},n=await i(L(r));return void 0===t?{requestHash:n}:{requestHash:n,responseHash:await i(L(t.data))}}class Bt{identity;cryptoProvider;constructor(e,t){this.identity=e,this.cryptoProvider=t}async generateProof(e,t,i,r={}){const n=await this.generateCanonicalHashes(e,t),o=c(await this.cryptoProvider.randomBytes(16)),s={did:this.identity.did,kid:this.identity.kid,ts:Math.floor(Date.now()/1e3),nonce:o,audience:i.audience,sessionId:i.sessionId,requestHash:n.requestHash,...void 0!==n.responseHash?{responseHash:n.responseHash}:{},...r};return{jws:await this.generateJWS(s),meta:s}}async hashRequest(e){return(await this.generateCanonicalHashes(e)).requestHash}async generateCanonicalHashes(e,t){return Vt(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 ae(e,"EdDSA",void 0)}(this.formatPrivateKeyAsPEM(e)):e}async generateJWS(e){try{const t=await this.resolveSigningKey(),i=P({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}}),r=(new TextEncoder).encode(i);return await new et(r).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,jt),i=new Uint8Array(Ut.length+t.length);i.set(Ut),i.set(t,Ut.length);const r=d(i);return"-----BEGIN PRIVATE KEY-----\n"+(r.match(/.{1,64}/g)?.join("\n")??r)+"\n-----END PRIVATE KEY-----"}async verifyProof(e,t,i){try{const r=await this.generateCanonicalHashes(t,i);if(e.meta.requestHash!==r.requestHash)return!1;if(void 0!==e.meta.responseHash&&(void 0===r.responseHash||e.meta.responseHash!==r.responseHash))return!1;const n=this.base64PublicKeyToJWK(this.identity.publicKey);return new zt(this.cryptoProvider).verifyJWS(e.jws,n,{expectedKid:this.identity.kid,alg:"EdDSA"})}catch{return!1}}base64PublicKeyToJWK(e){const t=u(e);if(t.length!==jt)throw new Error(`Invalid Ed25519 public key length: ${t.length}`);return{kty:"OKP",crv:"Ed25519",x:c(t),kid:this.identity.kid}}}async function qt(e,t,i,r,n,o={}){const s={data:t},a=new Bt(i,n),c=await a.generateProof(e,s,r,o);return s.meta={proof:c},s}function Ft(e,t){return{request:{method:e.method,...e.params?{params:e.params}:{}},response:t.data}}const Wt="_kyaos";function Gt(e){return e.startsWith(Wt)}function Jt(e,t){const i={};for(const[e,r]of Object.entries(t))Gt(e)||(i[e]=r);return{method:e,params:i}}async function Yt(e){const{identity:t,crypto:i,toolName:r,args:n,audience:o,sessionId:s}=e,a=new Bt(t,i),d=Jt(r,n),u=c(await i.randomBytes(16)),l=Math.floor(Date.now()/1e3);return a.generateProof(d,void 0,{sessionId:s??"",audience:o,nonce:u,timestamp:l,createdAt:l,lastActivity:l,ttlMinutes:30,identityState:"anonymous"})}const Xt="holder_binding_failed";function Zt(e){return null!==Rt(e)}async function Qt(e){const{proof:t,subjectDid:i,request:r,response:n,expectedAudience:o,proofVerifier:s}=e,a=Rt(i);if(!a)return{status:"not_applicable",reason:`Holder binding (phase 1) covers did:key subjects only; "${gt(i)??"unknown"}" is deferred to cnf-based binding`};if("object"!=typeof t?.meta||null===t.meta)return{status:"unbound",errorCode:Xt,reason:"Malformed proof: missing meta"};if(t.meta.did!==i)return{status:"unbound",errorCode:Xt,reason:"Proof subject does not match the delegation subject"};if(void 0!==o&&!(Array.isArray(o)?o:[o]).includes(t.meta.audience))return{status:"unbound",errorCode:Xt,reason:"Proof audience does not match this server",cause:"audience_mismatch"};const c=Ot(a);c.kid=`${i}#${At(i)}`;const d=await s.verifyProof(t,c,{request:r,...void 0!==n?{response:n}:{}});return d.valid?{status:"bound"}:{status:"unbound",errorCode:Xt,reason:"Request proof is not bound to the delegation subject",...void 0!==d.errorCode?{cause:d.errorCode}:{}}}function ei(e){return structuredClone(e)}class ti{statusLists=new Map;versions=new Map;indexCounters=new Map;async getStatusList(e){const t=this.statusLists.get(e);return void 0===t?null:ei(t)}async setStatusList(e,t){const i=ei(t);this.statusLists.set(e,i);const r=this.versions.get(e)??[];r.push(i),this.versions.set(e,r)}async allocateIndex(e){const t=this.indexCounters.get(e)||0,i=t;return this.indexCounters.set(e,t+1),i}getIndexCount(e){return this.indexCounters.get(e)||0}async getStatusListVersion(e,t){if(!Number.isSafeInteger(t)||t<1)return null;const i=this.versions.get(e)?.[t-1];return void 0===i?null:ei(i)}async getStatusListVersionCount(e){return this.versions.get(e)?.length??0}clear(){this.statusLists.clear(),this.versions.clear(),this.indexCounters.clear()}getAllStatusListIds(){return Array.from(this.statusLists.keys())}}class ii{nodes=new Map;async getNode(e){return this.nodes.get(e)||null}async setNode(e){this.nodes.set(e.id,e)}async registerNodeAtomic(e){const t=null===e.parentId?null:this.nodes.get(e.parentId);if(null!==e.parentId&&void 0===t)throw new Error(`Parent delegation not found: ${e.parentId}`);const i={...e,children:[...e.children]};if(null!=t){const i={...t,children:t.children.includes(e.id)?[...t.children]:[...t.children,e.id]};this.nodes.set(i.id,i)}this.nodes.set(i.id,i)}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 i=e;for(;i;){const e=this.nodes.get(i);if(!e)break;t.unshift(e),i=e.parentId}return t}async getDescendants(e){const t=[],i=[e],r=new Set;for(;i.length>0;){const e=i.shift();if(r.has(e))continue;r.add(e);const n=this.nodes.get(e);if(n)for(const e of n.children)if(!r.has(e)){i.push(e);const r=this.nodes.get(e);r&&t.push(r)}}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,i=e.filter(e=>0===e.children.length).length;let r=0;for(const t of e){const e=this.getChainSync(t.id);r=Math.max(r,e.length-1)}return{totalNodes:e.length,rootNodes:t,leafNodes:i,maxDepth:r}}getChainSync(e){const t=[];let i=e;for(;i;){const e=this.nodes.get(i);if(!e)break;t.unshift(e),i=e.parentId}return t}}function ri(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 ni(e){return e.startsWith("did:web:")}function oi(e){if(!ni(e))return null;const t=e.slice(8);if(0===t.length)return null;const i=t.split(":"),r=decodeURIComponent(i[0]);return 0===r.length?null:{domain:r,path:i.slice(1).map(e=>decodeURIComponent(e))}}function si(e){const t=oi(e);if(!t)return null;const{domain:i,path:r}=t;let n=`https://${i}`;return 0===r.length?n+="/.well-known/did.json":n+="/"+r.join("/")+"/did.json",n}class ai{fetchProvider;cache;cacheTtl;constructor(e,t){this.fetchProvider=e,this.cache=new Map,this.cacheTtl=t?.cacheTtl??3e5}async resolve(e){if(!ni(e))return null;const t=this.cache.get(e);if(t&&Date.now()<t.expiresAt)return t.document;const i=si(e);if(!i)return Ct.warn(`[DidWebResolver] Invalid did:web format: ${e}`),null;try{const t=await this.fetchProvider.fetch(i);if(!t.ok)return Ct.warn(`[DidWebResolver] HTTP ${t.status} fetching ${i}`),null;let r;try{r=await t.json()}catch{return Ct.warn(`[DidWebResolver] Invalid JSON from ${i}`),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(!ri(e))return!1}return!0}(r)?r.id!==e?(Ct.warn(`[DidWebResolver] DID Document id mismatch: expected ${e}, got ${r.id}`),null):(this.cache.set(e,{document:r,expiresAt:Date.now()+this.cacheTtl}),r):(Ct.warn(`[DidWebResolver] Invalid DID Document structure from ${i}`),null)}catch(t){return Ct.warn(`[DidWebResolver] Error resolving ${e}: ${t instanceof Error?t.message:"Unknown error"}`),null}}clearCache(){this.cache.clear()}clearCacheEntry(e){this.cache.delete(e)}}function ci(e,t){return new ai(e,t)}const di=new Uint8Array([237,1]),ui=["https://www.w3.org/ns/did/v1","https://w3id.org/security/suites/ed25519-2020/v1"];function li(e,t){const i=Array.isArray(e)?e:[e],r=i[0];if(!r)throw new Error("buildDidWebDocument: at least one identity is required");const n=r.did;if(!ni(n))throw new Error(`buildDidWebDocument: identity.did must be a did:web DID (got "${n}")`);const o=i.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 i=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:Ot(i),publicKeyMultibase:hi(i)}}(e,n)),s=o.map(e=>e.id);if(new Set(s).size!==s.length)throw new Error("buildDidWebDocument: every key needs a unique verification-method id (kid); got a duplicate");return{"@context":t?.additionalContexts?.length?[...ui,...t.additionalContexts]:[...ui],id:n,...t?.alsoKnownAs?.length?{alsoKnownAs:[...t.alsoKnownAs]}:{},verificationMethod:o,authentication:s,assertionMethod:s}}function hi(e){const t=new Uint8Array(di.length+e.length);return t.set(di),t.set(e,di.length),`z${lt(t)}`}function pi(e){const t=e.requireBidirectional??!0,i=gi(e.primaryDid),r=gi(e.secondaryDid),n=e.primaryDidDocument,o=e.secondaryDidDocument,s={primaryReferencesSecondary:!1,secondaryReferencesPrimary:!1,primaryDocumentMatches:!1,secondaryDocumentMatches:!1};return yi(n)?yi(o)?(s.primaryDocumentMatches=gi(n.id)===i,s.secondaryDocumentMatches=gi(o.id)===r,s.primaryDocumentMatches&&s.secondaryDocumentMatches?(s.primaryReferencesSecondary=fi(n,r),s.secondaryReferencesPrimary=fi(o,i),t?s.primaryReferencesSecondary&&s.secondaryReferencesPrimary?{valid:!0,checks:s}:{valid:!1,reason:"Bidirectional alsoKnownAs linkage is not present",checks:s}:s.primaryReferencesSecondary||s.secondaryReferencesPrimary?{valid:!0,checks:s}:{valid:!1,reason:"No alsoKnownAs linkage is present",checks:s}):{valid:!1,reason:"DID Document id does not match expected DID",checks:s}):{valid:!1,reason:"Secondary DID Document is missing or malformed",checks:s}:{valid:!1,reason:"Primary DID Document is missing or malformed",checks:s}}function fi(e,t){return(e.alsoKnownAs??[]).some(e=>gi(e)===t)}function gi(e){return e.trim()}function yi(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 mi(e,t){const i={};if(!e)return i;for(const[r,n]of Object.entries(e))/^[a-z0-9]+$/.test(r)&&("function"!=typeof n?i[r]=n:t&&(i[r]=n(t)));return i}class vi{tokens=new Map;ttl;constructor(e=6e5){this.ttl=e}async create(e,t,i){const r=new Uint8Array(16);globalThis.crypto.getRandomValues(r);const n=`rt_${Array.from(r).map(e=>e.toString(16).padStart(2,"0")).join("")}`,o=Date.now();return this.tokens.set(n,{agentDid:e,scopes:t,createdAt:o,expiresAt:o+this.ttl,metadata:i,fulfilled:!1}),n}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 Ii(e,t,i){const r=Date.now();let n,o;if(i.debug&&Ct.debug(`[AuthHandshake] Verifying ${e} for scopes: ${t.join(", ")}`),i.reputationService&&void 0!==i.authorization.minReputationScore){const r=i.authorization.unknownAgentPolicy??"require-consent";try{n=await async function(e,t){const i=t.apiUrl.replace(/\/$/,""),r={"Content-Type":"application/json"};let n;if(t.apiKey&&(r["X-API-Key"]=t.apiKey),n="v2"===t.apiFormat?await fetch(`${i}/v1/reputation/${encodeURIComponent(e)}`,{method:"POST",headers:r,body:JSON.stringify({include_details:!1})}):await fetch(`${i}/api/v1/reputation/${encodeURIComponent(e)}`,{method:"GET",headers:r}),!n.ok){if(404===n.status)return{agentDid:e,score:null,totalInteractions:0,successRate:0,riskLevel:"unknown",updatedAt:Date.now()};throw new Error(`Reputation API error: ${n.status} ${n.statusText}`)}const o=await n.json(),s=o.score??0,a=(o.level??o.riskLevel??"unknown").toLowerCase(),c="low"===a||"medium"===a||"high"===a?a:"unknown";return{agentDid:o.agent_did??o.agentDid??e,score:s,totalInteractions:o.totalInteractions??0,successRate:o.successRate??0,riskLevel:c,updatedAt:o.calculatedAt?new Date(o.calculatedAt).getTime():o.updatedAt??Date.now()}}(e,i.reputationService)}catch(t){Ct.error("[AuthHandshake] Reputation service unreachable, treating agent as unknown:",t),n={agentDid:e,score:null,totalInteractions:0,successRate:0,riskLevel:"unknown",updatedAt:Date.now()}}if(i.debug&&Ct.debug(`[AuthHandshake] Reputation score: ${n.score}`),null===n.score){if("deny"===r)return{authorized:!1,authError:await Ei(e,t,i,"Unknown agent denied by policy"),reputation:n,reason:"Unknown agent — policy: deny"};if("require-consent"===r)return{authorized:!1,authError:await Ei(e,t,i,"Unknown agent requires consent"),reputation:n,reason:"Unknown agent — policy: require-consent"};i.debug&&Ct.debug("[AuthHandshake] Unknown agent allowed by policy, skipping reputation gate")}if(null!==n.score&&n.score<i.authorization.minReputationScore)return i.debug&&Ct.debug(`[AuthHandshake] Reputation ${n.score} < ${i.authorization.minReputationScore}, requiring authorization`),{authorized:!1,authError:await Ei(e,t,i,"Agent reputation score below threshold"),reputation:n,reason:"Low reputation score"}}try{o=await i.delegationVerifier.verify(e,t)}catch(r){Ct.error("[AuthHandshake] Delegation verification failed:",r);const n=`Delegation verification error: ${r instanceof Error?r.message:"Unknown error"}`;return{authorized:!1,authError:await Ei(e,t,i,n),reason:n}}return o.valid&&o.delegation?(i.debug&&Ct.debug(`[AuthHandshake] Delegation valid, authorized (${Date.now()-r}ms)`),{authorized:!0,delegation:o.delegation,credential:o.credential,reputation:n,reason:"Valid delegation found"}):(i.debug&&Ct.debug(`[AuthHandshake] No delegation found, returning needs_authorization (${Date.now()-r}ms)`),{authorized:!1,authError:await Ei(e,t,i,o.reason??"No valid delegation found"),reputation:n,reason:o.reason??"No delegation"})}async function Ei(e,t,i,r){const n=await i.resumeTokenStore.create(e,t,{requestedAt:Date.now()}),o=Date.now()+(i.authorization.resumeTokenTtl??6e5),s=new URL(i.authorization.authorizationUrl);s.searchParams.set("agent_did",e),s.searchParams.set("scopes",t.join(",")),s.searchParams.set("resume_token",n);const a={title:"Authorization Required",hint:["link","qr"],authorizationCode:n.substring(0,8).toUpperCase(),qrUrl:`https://api.qrserver.com/v1/create-qr-code/?data=${encodeURIComponent(s.toString())}`};return D({message:r,authorizationUrl:s.toString(),resumeToken:n,expiresAt:o,scopes:t,display:a})}function wi(e){const t=["write","delete","admin","payment","transfer","execute","modify"];return e.some(e=>t.some(t=>e.toLowerCase().includes(t)))}const Si={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 Di extends Error{code;details;constructor(e,t,i){super(t),this.code=e,this.details=i,this.name="ProofVerificationError"}}function Ai(e,t,i){return new Di(e,t,i)}const bi=120,_i=30,Ci=600;class Ti{cryptoService;clock;nonceCache;fetch;timestampSkewSeconds;nonceTtlSeconds;cryptoProvider;constructor(e){this.cryptoService=new zt(e.cryptoProvider),this.cryptoProvider=e.cryptoProvider,this.clock=e.clockProvider,this.nonceCache=e.nonceCacheProvider,this.fetch=e.fetchProvider,this.timestampSkewSeconds=e.timestampSkewSeconds??bi,this.nonceTtlSeconds=e.nonceTtlSeconds??300}setTimestampSkew(e){"number"==typeof e&&Number.isFinite(e)&&(this.timestampSkewSeconds=Math.max(_i,Math.min(Ci,Math.floor(e))))}getTimestampSkew(){return this.timestampSkewSeconds}async verifyProof(e,t,i){try{const r=await this.validateProofStructure(e);if(!r.valid)return r;const n=r.proof,o=this.buildCanonicalPayload(n.meta),s=(new TextEncoder).encode(o);return await this.runVerificationPipeline(n,t,s,i)}catch(e){return this.handleVerificationError(e)}}async verifyProofArtifact(e,t,i){try{const r=await this.validateProofStructure(e);if(!r.valid)return r;const n=r.proof,o=(new TextEncoder).encode(this.buildCanonicalPayload(n.meta)),s=await this.verifySignature(n.jws,t,o,n.meta.kid);return s.valid?void 0!==i?this.validateContentBinding(n,i):{valid:!0}:s}catch(e){return this.handleVerificationError(e)}}async verifyProofDetached(e,t,i){try{const r=t instanceof Uint8Array?t:(new TextEncoder).encode(t);return await this.runVerificationPipeline(e,i,r)}catch(e){return this.handleVerificationError(e)}}async runVerificationPipeline(e,t,i,r){const n=await this.validateProofStructure(e);if(!n.valid)return n;const o=n.proof,s=await this.validateNonce(o.meta.nonce,o.meta.did);if(!s.valid)return s;const a=await this.validateTimestamp(o.meta.ts);if(!a.valid)return a;const c=await this.verifySignature(o.jws,t,i,o.meta.kid);if(!c.valid)return c;if(void 0!==r){const e=await this.validateContentBinding(o,r);if(!e.valid)return e}return await this.addNonceToCache(o.meta.nonce,o.meta.did),{valid:!0}}async validateContentBinding(e,t){const{requestHash:i,responseHash:r}=await Vt(t.request,t.response,e=>this.cryptoProvider.hash(e));if(e.meta.requestHash!==i)return{valid:!1,reason:"Request hash mismatch: the proof does not bind the request you supplied",errorCode:Si.CONTENT_BINDING_MISMATCH};const n=void 0!==e.meta.responseHash;return n!==(void 0!==t.response)?{valid:!1,reason:n?"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:Si.CONTENT_BINDING_MISMATCH}:n&&e.meta.responseHash!==r?{valid:!1,reason:"Response hash mismatch: received content differs from what the server signed (possible substitution / MITM)",errorCode:Si.CONTENT_BINDING_MISMATCH}:{valid:!0}}handleVerificationError(e){return{valid:!1,reason:"Proof verification error",errorCode:Si.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=T(e);return t.success?{valid:!0,proof:t.data}:{valid:!1,reason:"Invalid proof structure",errorCode:Si.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:Si.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:Si.TIMESTAMP_SKEW_EXCEEDED,details:{timestamp:e,timestampMs:t,skewSeconds:this.timestampSkewSeconds,currentTime:this.clock.now()}}}async verifySignature(e,t,i,r){return await this.cryptoService.verifyJWS(e,t,{detachedPayload:i,expectedKid:r,alg:"EdDSA"})?{valid:!0}:{valid:!1,reason:"Invalid JWS signature",errorCode:Si.INVALID_JWS_SIGNATURE,details:{jwsLength:e.length,expectedKid:r,actualKid:t.kid}}}async addNonceToCache(e,t){await this.nonceCache.add(e,this.nonceTtlSeconds,t)}async fetchPublicKeyFromDID(e,t){try{const i=await this.fetch.resolveDID(e);if(!i)throw new Di(Si.DID_DOCUMENT_NOT_FOUND,`DID document not found: ${e}`,{did:e});const r=i;if(!r.verificationMethod||0===r.verificationMethod.length)throw new Di(Si.VERIFICATION_METHOD_NOT_FOUND,`No verification methods found in DID document: ${e}`,{did:e});let n;if(t){const i=t.startsWith("#")?t:`#${t}`;if(n=r.verificationMethod.find(t=>t.id===i||t.id===`${e}${i}`),!n)throw new Di(Si.VERIFICATION_METHOD_NOT_FOUND,`Verification method not found for kid: ${t}`,{did:e,kid:t,availableKids:r.verificationMethod.map(e=>e.id)})}else n=r.verificationMethod[0];if(!n?.publicKeyJwk)throw new Di(Si.PUBLIC_KEY_NOT_FOUND,"Public key JWK not found in verification method",{did:e,kid:t,verificationMethodId:n?.id});const o=n.publicKeyJwk;if("OKP"!==o.kty||"Ed25519"!==o.crv||!o.x)throw new Di(Si.INVALID_JWK_FORMAT,`Unsupported key type or curve: kty=${o.kty}, crv=${o.crv}`,{did:e,kid:t,jwk:{kty:o.kty,crv:o.crv}});const s=o;return!s.kid&&n.id&&(s.kid=n.id),s}catch(i){if(i instanceof Di)throw i;throw Ct.error("[ProofVerifier] Failed to fetch public key from DID",{error:i}),new Di(Si.DID_RESOLUTION_FAILED,`DID resolution failed: ${i instanceof Error?i.message:String(i)}`,{did:e,kid:t,originalError:i instanceof Error?i.message:String(i)})}}buildCanonicalPayload(e){return P({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}})}}const ki=["io.modelcontextprotocol/"],Ni=["traceparent","tracestate","baggage"];function Ri(e){return Ni.includes(e)||ki.some(t=>e.startsWith(t))}function Oi(e,t="strict"){const i=Object.keys(e).filter(e=>e!==Kt&&e!==$t);return"allow-extensions"===t&&i.length>0?{valid:!0,extraKeys:i}:{valid:!0}}function Pi(e,t="strict"){const i=e[Kt]??e[$t];if(!i)return{success:!1,reason:"_meta does not contain a proof",errorCode:Si.MISSING_REQUIRED_FIELD};Oi(e,t);const r=T(i);return r.success?{success:!0,proof:r.data}:{success:!1,reason:r.error?.message??"Invalid proof structure",errorCode:Si.INVALID_PROOF_STRUCTURE}}class Li{}class xi{}class Mi{}class zi{}class Ui{}class Hi{}class ji extends zi{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 Ki extends Ui{nonces=new Map;async has(e,t){const i=t?`nonce:${t}:${e}`:`nonce:${e}`,r=this.nonces.get(i);return!(!r||Date.now()>r&&(this.nonces.delete(i),1))}async add(e,t,i){const r=i?`nonce:${i}:${e}`:`nonce:${e}`,n=Date.now()+1e3*t;this.nonces.set(r,n)}async cleanup(){const e=Date.now();for(const[t,i]of this.nonces)e>i&&this.nonces.delete(t)}async destroy(){this.nonces.clear()}}class $i extends Hi{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}#${At(t)}`,privateKey:e.privateKey,publicKey:e.publicKey,createdAt:(new Date).toISOString(),type:"development"}}generateDIDFromPublicKey(e){return Dt(e)}}class Vi{}class Bi extends Vi{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 qi{config;cryptoProvider;sessionStore;constructor(e,t={}){this.cryptoProvider=e,this.sessionStore=t.sessionStore??new Bi({maxSessions:t.maxSessions??1e4}),this.config={timestampSkewSeconds:t.timestampSkewSeconds??120,sessionTtlMinutes:t.sessionTtlMinutes??30,nonceCache:t.nonceCache??new Ki,metaPolicy:t.metaPolicy??"strict",...void 0!==t.absoluteSessionLifetime&&{absoluteSessionLifetime:t.absoluteSessionLifetime},...void 0!==t.serverDid&&{serverDid:t.serverDid}},this.config.nonceCache instanceof Ki&&Ct.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),i=Math.abs(t-e.timestamp);if(i>this.config.timestampSkewSeconds)return{success:!1,error:{code:r.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: ${i}s. Adjust timestampSkewSeconds if needed.`}};if(this.config.serverDid&&e.audience!==this.config.serverDid)return{success:!1,error:{code:r.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:r.nonce_replay,message:"Nonce already used (replay attack prevention)",remediation:"Generate a new unique nonce for each request"}};const n=e.agentDid?w:S,o=Math.ceil(n/1e3);await this.config.nonceCache.add(e.nonce,o,e.agentDid);const s=await this.generateSessionId(),a=await this.buildClientInfo(e),c={sessionId:s,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(s,c),{success:!0,session:c}}catch(e){return{success:!1,error:{code:r.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 i=Math.floor(Date.now()/1e3);return i-t.lastActivity>60*t.ttlMinutes||void 0!==this.config.absoluteSessionLifetime&&i-t.createdAt>60*this.config.absoluteSessionLifetime?(await this.sessionStore.delete(e),null):(t.lastActivity=i,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 i=0;i<e.length;i++)t+=String.fromCharCode(e[i]);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}async cleanup(){const e=Math.floor(Date.now()/1e3);for(const[t,i]of await this.sessionStore.entries()){let r=e-i.lastActivity>60*i.ttlMinutes;r||void 0===this.config.absoluteSessionLifetime||(r=e-i.createdAt>60*this.config.absoluteSessionLifetime),r&&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 Fi(e){return{nonce:qi.generateNonce(),audience:e,timestamp:Math.floor(Date.now()/1e3)}}function Wi(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 Gi=i(77598);const Ji=Buffer.from("302e020100300506032b657004220420","hex"),Yi=Buffer.from("302a300506032b6570032100","hex");class Xi extends Li{async sign(e,t){const i=Buffer.from(t,"base64"),r=64===i.length?i.subarray(0,32):i,n=(0,Gi.createPrivateKey)({key:Buffer.concat([Ji,r]),format:"der",type:"pkcs8"});return new Uint8Array((0,Gi.sign)(null,Buffer.from(e),n))}async verify(e,t,i){try{const r=(0,Gi.createPublicKey)({key:Buffer.concat([Yi,Buffer.from(i,"base64")]),format:"der",type:"spki"});return(0,Gi.verify)(null,Buffer.from(e),r,Buffer.from(t))}catch{return!1}}async generateKeyPair(){const{publicKey:e,privateKey:t}=(0,Gi.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,Gi.createHash)("sha256").update(Buffer.from(e)).digest("hex")}`}async randomBytes(e){return new Uint8Array((0,Gi.randomBytes)(e))}}class Zi extends xi{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 Qi extends Mi{didKeyResolver=Pt();didWebResolver;didResolvers;allowPrivateNetworkHosts;constructor(e){super(),this.allowPrivateNetworkHosts=e?.allowPrivateNetworkHosts??!1,this.didResolvers=mi(e?.didResolvers,this)}async resolveDID(e){const t=gt(e),i=t?this.didResolvers[t]:void 0;if(i)try{const t=await i.resolve(e);if(t)return t}catch{return null}return e.startsWith("did:key:")?this.didKeyResolver.resolve(e):ni(e)?this.isBlockedTarget(si(e))?null:(this.didWebResolver||(this.didWebResolver=ci(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 i=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 i=t.credentialSubject;if("object"!=typeof i||null===i)return!1;const r=i;return"StatusList2021"===r.type&&"string"==typeof r.encodedList}(i)?i: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 i=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(t);if(!i)return!1;const r=Number(i[1]),n=Number(i[2]);return 127===r||10===r||0===r||169===r&&254===n||192===r&&168===n||172===r&&n>=16&&n<=31}(t)}}class er extends Mi{async resolveDID(e){return null}async fetchStatusList(e){return null}async fetchDelegationChain(e){return[]}async fetch(e,t){throw new Error("fetch unavailable")}}function tr(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 ir{}class rr extends ir{records=[];events=[];loggedSessions=new Set;async logAuditRecord(e){const t=e.session.sessionId;this.loggedSessions.has(t)||(this.loggedSessions.add(t),this.records.push(tr(e)))}async logEvent(e){this.events.push(e)}}class nr extends ir{async logAuditRecord(e){}async logEvent(e){}}const or=["session.established","session.rejected","session.expired","session.replay_rejected","tool.call.started","tool.call.completed","tool.call.failed","tool.call.denied","tool.call.challenged","proof.generated","proof.verified","proof.rejected","delegation.issued","delegation.verified","delegation.rejected","delegation.revoked","delegation.cascade_revoked","delegation.outbound_attached","authorization.evaluated","authorization.approved","authorization.denied","authorization.step_up_required","grant.used","consent.requested","consent.approved","consent.denied","credential.required","credential.verified","credential.failed","key.rotated","policy.changed","configuration.changed","integrity_suite.transitioned","ledger.epoch.started","ledger.epoch.transitioned","checkpoint.created","checkpoint.anchored","checkpoint.anchor_failed","evidence.disposed","projection.reconciled","audit.source_high_water","audit.accessed","audit.exported","legal_hold.applied","retention.executed"];var sr=i(11569);const ar="https://schema.kya-os.org/v1/protocol/audit/event/v1.0.0",cr="https://schema.kya-os.org/v1/protocol/audit/entry/v1.0.0",dr="https://schema.kya-os.org/v1/protocol/audit/receipt/v1.0.0",ur="KYA-AUDIT-JCS-SHA256-JWS-2026",lr="https://schema.kya-os.org/v1/protocol/audit/checkpoint/v1.0.0",hr="KYA-AUDIT-RFC9162-SHA256-JWS-2026",pr="https://schema.kya-os.org/v1/protocol/audit/bundle-manifest/v1.0.0",fr="KYA-AUDIT-BUNDLE-JCS-SHA256-JWS-2026",gr=256,yr=4096,mr=sr.z.string().max(20).regex(/^(0|[1-9][0-9]*)$/),vr=sr.z.string().regex(/^sha256:[a-f0-9]{64}$/),Ir=sr.z.string().min(5).max(2048).regex(/^did:[^\r\n]+$/),Er=sr.z.object({did:Ir,kid:sr.z.string().min(1).max(2304),alg:sr.z.enum(["EdDSA","ES256"])}).strict(),wr=sr.z.object({objectId:sr.z.string().min(1).max(gr),ciphertextDigest:vr,plaintextCommitment:vr.optional(),mediaType:sr.z.string().min(1).max(gr),size:mr,encryption:sr.z.object({suite:sr.z.literal("A256GCM"),keyId:sr.z.string().min(1).max(gr),nonce:sr.z.string().min(1).max(gr),aadDigest:vr}).strict()}).strict(),Sr=sr.z.discriminatedUnion("kind",[sr.z.object({kind:sr.z.literal("public_did"),did:Ir}).strict(),sr.z.object({kind:sr.z.literal("pairwise_did"),did:Ir}).strict(),sr.z.object({kind:sr.z.literal("keyed_commitment"),value:vr,keyId:sr.z.string().min(1).max(gr)}).strict(),sr.z.object({kind:sr.z.literal("evidence_ref"),ref:wr}).strict()]),Dr=[sr.z.object({family:sr.z.literal("session"),phase:sr.z.enum(["established","rejected","expired","replay_rejected"]),reasonCode:sr.z.string().min(1).max(128).optional()}).strict(),sr.z.object({family:sr.z.literal("tool"),phase:sr.z.enum(["started","completed","failed","denied","challenged"]),attempt:mr,idempotencyRef:sr.z.string().min(1).max(gr).optional()}).strict(),sr.z.object({family:sr.z.literal("proof"),phase:sr.z.enum(["generated","verified","rejected"]),proofDigest:vr.optional(),verificationCode:sr.z.string().min(1).max(128).optional()}).strict(),sr.z.object({family:sr.z.literal("delegation"),phase:sr.z.enum(["issued","verified","rejected","revoked","cascade_revoked","outbound_attached"]),delegationRef:sr.z.string().min(1).max(gr),parentRef:sr.z.string().min(1).max(gr).optional(),statusEvidence:sr.z.array(wr).max(256).optional()}).strict(),sr.z.object({family:sr.z.literal("authorization"),phase:sr.z.enum(["evaluated","approved","denied","step_up_required","grant_used"]),policyDigest:vr.optional(),grantRef:sr.z.string().min(1).max(gr).optional()}).strict(),sr.z.object({family:sr.z.literal("consent"),phase:sr.z.enum(["requested","approved","denied","credential_required","credential_verified","credential_failed"]),consentRef:sr.z.string().min(1).max(gr).optional()}).strict(),sr.z.object({family:sr.z.literal("key"),phase:sr.z.enum(["rotated","policy_changed","configuration_changed","integrity_suite_transitioned"]),previousSigner:Er.optional(),nextSigner:Er.optional(),configurationDigest:vr.optional()}).strict(),sr.z.object({family:sr.z.literal("ledger"),phase:sr.z.enum(["epoch_started","epoch_transitioned","checkpoint_created","checkpoint_anchored","checkpoint_anchor_failed","evidence_disposed","projection_reconciled"]),checkpointDigest:vr.optional(),previousEpochId:sr.z.string().min(1).max(gr).optional(),previousTerminalCheckpointDigest:vr.optional(),successorEpochIds:sr.z.array(sr.z.string().min(1).max(gr)).max(256).optional(),targetEvidenceRef:wr.optional()}).strict(),sr.z.object({family:sr.z.literal("administration"),phase:sr.z.enum(["source_high_water","accessed","exported","legal_hold_applied","retention_executed"]),purpose:sr.z.string().min(1).max(gr).optional(),sourceSequence:mr.optional(),selectionDigest:vr.optional()}).strict()],Ar=sr.z.discriminatedUnion("family",Dr),br=sr.z.object({source:sr.z.enum(["delegation","grant","anonymous","policy"]),decision:sr.z.enum(["allowed","denied","step_up_required","needs_authorization"]),scopeId:sr.z.string().min(1).max(gr).optional(),delegationRef:sr.z.string().min(1).max(gr).optional(),delegationCredentialDigest:vr.optional(),delegationChainDigests:sr.z.array(vr).max(256).optional(),statusEvidence:sr.z.array(wr).max(256).optional(),grantRef:sr.z.string().min(1).max(gr).optional(),policyId:sr.z.string().min(1).max(gr).optional(),policyVersion:sr.z.string().min(1).max(gr).optional(),policyDigest:vr.optional(),verificationCode:sr.z.string().min(1).max(128).optional()}).strict(),_r=sr.z.object({schema:sr.z.literal(ar),eventId:sr.z.string().min(1).max(256),eventType:sr.z.enum(or),eventVersion:sr.z.literal("1.0.0"),binding:sr.z.string().max(gr).regex(/^urn:kya-os:audit-binding:[a-z0-9][a-z0-9._:-]*$/),occurredAt:sr.z.number().int().nonnegative(),tenantRef:Sr,source:sr.z.object({producer:Sr,sourceId:sr.z.string().min(1).max(256),sourceSequence:mr.optional(),previousSourceEventDigest:vr.optional()}).strict(),correlationId:sr.z.string().min(1).max(256).optional(),causationId:sr.z.string().min(1).max(256).optional(),trace:sr.z.object({traceId:sr.z.string().regex(/^[a-f0-9]{32}$/).optional(),spanId:sr.z.string().regex(/^[a-f0-9]{16}$/).optional()}).strict().optional(),session:sr.z.object({ref:Sr,handshakeNonceCommitment:vr.optional()}).strict().optional(),actor:Sr.optional(),responsibleParty:Sr.optional(),resource:Sr.optional(),action:sr.z.object({category:sr.z.string().min(1).max(128),name:sr.z.string().min(1).max(256).optional(),detailRef:wr.optional()}).strict(),outcome:sr.z.enum(["succeeded","failed","denied","challenged","unknown"]),reason:sr.z.object({code:sr.z.string().min(1).max(128),detailRef:wr.optional()}).strict().optional(),authorization:br.optional(),proof:wr.optional(),evidence:sr.z.array(wr).max(256),details:Ar,privacy:sr.z.object({classification:sr.z.enum(["public","internal","confidential","restricted"]),retentionClass:sr.z.string().min(1).max(128),legalHold:sr.z.string().min(1).max(256).optional()}).strict()}).strict().superRefine((e,t)=>{var i;e.details.family!==((i=e.eventType).startsWith("session.")?"session":i.startsWith("tool.")?"tool":i.startsWith("proof.")?"proof":i.startsWith("delegation.")?"delegation":i.startsWith("authorization.")||"grant.used"===i?"authorization":i.startsWith("consent.")||i.startsWith("credential.")?"consent":i.startsWith("key.")||i.startsWith("policy.")||i.startsWith("configuration.")||i.startsWith("integrity_suite.")?"key":i.startsWith("ledger.")||i.startsWith("checkpoint.")||i.startsWith("evidence.")||i.startsWith("projection.")?"ledger":"administration")&&t.addIssue({code:"custom",path:["details","family"],message:`Event detail family ${e.details.family} does not match ${e.eventType}`})}),Cr=sr.z.object({schema:sr.z.literal(cr),ledgerId:sr.z.string().min(1).max(256),ledgerEpochId:sr.z.string().min(1).max(256),sequence:mr,previousEntryDigest:vr.nullable(),recordedAt:sr.z.number().int().nonnegative(),recorder:Er,eventDigest:vr,event:_r,evidenceManifestDigest:vr,integritySuite:sr.z.literal(ur)}).strict(),Tr=sr.z.object({schema:sr.z.literal(dr),ledgerId:sr.z.string().min(1).max(256),ledgerEpochId:sr.z.string().min(1).max(256),sequence:mr,eventId:sr.z.string().min(1).max(256),entryDigest:vr,previousEntryDigest:vr.nullable(),recordedAt:sr.z.number().int().nonnegative(),recorder:Er,integritySuite:sr.z.literal(ur)}).strict(),kr=sr.z.object({schema:sr.z.literal(lr),checkpointId:sr.z.string().min(1).max(512),ledgerId:sr.z.string().min(1).max(256),ledgerEpochId:sr.z.string().min(1).max(256),treeSize:mr,firstSequence:mr,lastSequence:mr,rootDigest:vr,headEntryDigest:vr,previousCheckpointDigest:vr.nullable(),createdAt:sr.z.number().int().nonnegative(),issuer:Er,integritySuite:sr.z.literal(hr)}).strict().superRefine((e,t)=>{(0n===BigInt(e.treeSize)||BigInt(e.lastSequence)<BigInt(e.firstSequence))&&t.addIssue({code:"custom",message:"Checkpoint range must be non-empty and ordered"})}),Nr=sr.z.object({core:kr,checkpointDigest:vr,jws:sr.z.string().min(1).max(yr)}).strict(),Rr=sr.z.object({core:Cr,eventDigest:vr,entryDigest:vr,recorderReceipt:sr.z.object({core:Tr,jws:sr.z.string().min(1).max(yr)}).strict()}).strict(),Or=sr.z.object({core:sr.z.object({schema:sr.z.literal("https://schema.kya-os.org/v1/protocol/audit/observation/v1.0.0"),observerId:sr.z.string().min(1).max(256),observer:Er,ledgerId:sr.z.string().min(1).max(256),ledgerEpochId:sr.z.string().min(1).max(256),checkpointDigest:vr,treeSize:mr,observedAt:sr.z.number().int().nonnegative(),previousObservationDigest:vr.nullable()}).strict(),observationDigest:vr,jws:sr.z.string().min(1).max(yr)}).strict(),Pr=sr.z.object({schema:sr.z.literal("https://schema.kya-os.org/v1/protocol/audit/anchor-receipt/v1.0.0"),kind:sr.z.enum(["worm","rfc3161","scitt"]),providerId:sr.z.string().min(1).max(256),checkpointDigest:vr,issuedAt:sr.z.number().int().nonnegative(),receiptData:sr.z.string().min(1).max(65536).optional()}).strict(),Lr=sr.z.object({leafIndex:mr,treeSize:mr,auditPath:sr.z.array(vr)}).strict(),xr=sr.z.object({oldTreeSize:mr,newTreeSize:mr,auditPath:sr.z.array(vr)}).strict(),Mr=sr.z.object({ledgerId:sr.z.string().min(1).max(256),ledgerEpochId:sr.z.string().min(1).max(256),sequence:mr,entryDigest:vr,checkpointDigest:vr,proof:Lr}).strict(),zr=sr.z.object({ledgerId:sr.z.string().min(1).max(256),ledgerEpochId:sr.z.string().min(1).max(256),oldCheckpointDigest:vr,newCheckpointDigest:vr,proof:xr}).strict(),Ur=sr.z.object({ledgerId:sr.z.string().min(1).max(256),ledgerEpochId:sr.z.string().min(1).max(256),firstSequence:mr,lastSequence:mr,expectedHeadDigest:vr,checkpointTreeSizes:sr.z.array(mr).max(256)}).strict().superRefine((e,t)=>{BigInt(e.lastSequence)<BigInt(e.firstSequence)&&t.addIssue({code:"custom",message:"Bundle selection range is reversed"})}),Hr=sr.z.object({path:sr.z.string().min(1).max(1024),mediaType:sr.z.string().min(1).max(256),disposition:sr.z.enum(["included","redacted","disposed","unavailable","policy_excluded"]),digest:vr.optional(),size:mr.optional(),reasonCode:sr.z.string().min(1).max(128).optional()}).strict().superRefine((e,t)=>{"included"===e.disposition?void 0!==e.digest&&void 0!==e.size&&void 0===e.reasonCode||t.addIssue({code:"custom",message:"Included inventory requires digest/size only"}):void 0!==e.reasonCode&&void 0===e.digest&&void 0===e.size||t.addIssue({code:"custom",message:"Excluded inventory requires only a reason code"})}),jr=sr.z.object({schema:sr.z.literal(pr),bundleId:sr.z.string().min(1).max(256),formatVersion:sr.z.literal("1.0.0"),selections:sr.z.array(Ur).min(1),exporter:Er,purpose:sr.z.string().min(1).max(256),exportedAt:sr.z.number().int().nonnegative(),verificationPolicyDigest:vr,inventory:sr.z.array(Hr).max(1e4),integritySuite:sr.z.literal(fr)}).strict().superRefine((e,t)=>{const i=e.inventory.map(e=>e.path);new Set(i).size!==i.length&&t.addIssue({code:"custom",path:["inventory"],message:"Inventory paths must be unique"})}),Kr=Hr.extend({content:sr.z.unknown().optional()}).strict().superRefine((e,t)=>{const i=Object.prototype.hasOwnProperty.call(e,"content");if(("included"===e.disposition?!i:i)&&t.addIssue({code:"custom",path:["content"],message:"included"===e.disposition?"Included component content is required":"Excluded component content is forbidden"}),i)try{O(e.content)}catch(e){t.addIssue({code:"custom",path:["content"],message:e instanceof Error?e.message:"Content is not canonical JSON"})}}),$r=sr.z.object({manifest:sr.z.object({core:jr,manifestDigest:vr,jws:sr.z.string().min(1).max(yr)}).strict(),components:sr.z.array(Kr)}).strict();function Vr(e){return new Set(e).size===e.length}const Br=sr.z.object({signer:Er,validFrom:sr.z.number().int().nonnegative().optional(),validUntil:sr.z.number().int().nonnegative().optional(),validFromCheckpoint:vr.optional(),validUntilCheckpoint:vr.optional()}).strict().superRefine((e,t)=>{void 0!==e.validFrom&&void 0!==e.validUntil&&e.validFrom>e.validUntil&&t.addIssue({code:"custom",message:"Key validity interval is reversed"})}),qr=sr.z.object({policyId:sr.z.string().min(1).max(256),trustedLedgerEpochs:sr.z.array(sr.z.object({ledgerId:sr.z.string().min(1).max(256),ledgerEpochId:sr.z.string().min(1).max(256),recorderKeys:sr.z.array(Br).min(1),validFromCheckpoint:vr.optional(),validUntilCheckpoint:vr.optional()}).strict()),trustedObservers:sr.z.array(Br),trustedSupportingAnchors:sr.z.array(sr.z.object({kind:sr.z.enum(["worm","rfc3161","scitt"]),providerId:sr.z.string().min(1).max(256),validFrom:sr.z.number().int().nonnegative().optional(),validUntil:sr.z.number().int().nonnegative().optional()}).strict()).optional(),authorizedExporters:sr.z.array(sr.z.object({signerKeys:sr.z.array(Br).min(1),allowedLedgerIds:sr.z.array(sr.z.string().min(1).max(256)).min(1).refine(Vr,"Allowed ledger IDs must be unique"),allowedPurposes:sr.z.array(sr.z.string().min(1).max(256)).min(1).refine(Vr,"Allowed purposes must be unique")}).strict()),acceptedIntegritySuites:sr.z.array(sr.z.string().min(1).max(128)).min(1).refine(Vr,"Accepted integrity suites must be unique"),acceptedAlgorithms:sr.z.array(sr.z.enum(["EdDSA","ES256"])).min(1).refine(Vr,"Accepted algorithms must be unique"),keyRevocationMode:sr.z.enum(["as_observed","current","both"]),requiredCheckpointFreshnessMs:sr.z.number().int().nonnegative().optional(),requiredAuditProfile:sr.z.enum(["AAP-0","AAP-1","AAP-2","AAP-3","AAP-4"]).optional()}).strict();function Fr(e,t=new WeakSet){if("object"!=typeof e||null===e||Object.isFrozen(e))return e;if(t.has(e))return e;t.add(e);for(const i of Object.values(e))Fr(i,t);return Object.freeze(e)}function Wr(e){return Fr(structuredClone(e))}function Gr(e){return Wr(_r.parse(e))}function Jr(e){return Wr(Cr.parse(e))}function Yr(e){return Wr(Rr.parse(e))}function Xr(e){return Wr(Tr.parse(e))}function Zr(e){return Wr(kr.parse(e))}function Qr(e){return Wr(Nr.parse(e))}function en(e){return Wr(Or.parse(e))}function tn(e){return Wr(jr.parse(e))}function rn(e){return Wr($r.parse(e))}function nn(e){return Wr(qr.parse(e))}const on=Object.freeze({"AAP-0":{name:"None",claim:"No audit assurance"},"AAP-1":{name:"Recorded",claim:"Structured capture of delivered instrumented events"},"AAP-2":{name:"Chained",claim:"Ordered tamper-evident accepted history for a declared scope"},"AAP-3":{name:"Transparent",claim:"Efficient inclusion, consistency, and declared source-gap evidence"},"AAP-4":{name:"Observed",claim:"Conflicting observed views are detectable relative to independently known checkpoints"}});function sn(e){const t=Number(e.profile.slice(-1));if(0!==t){if("none"===e.recorderTopology||"none"===e.journalDurability)throw new Error(`${e.profile} requires an audit recorder or verified mirror`);if(t>=2){if("durable"!==e.journalDurability)throw new Error(`${e.profile} requires a durable journal`);if(!e.atomicAppend)throw new Error(`${e.profile} requires atomic append`);if("best-effort"===e.delivery)throw new Error(`${e.profile} cannot use best-effort delivery`)}if(t>=3&&(!e.merkleCheckpoints||!e.sourceHighWater))throw new Error(`${e.profile} requires Merkle checkpoints and source high-water evidence`);if(t>=4){if(!e.independentObservation)throw new Error("AAP-4 requires independent observation with authenticated comparison/gossip");if(0===e.supportingAnchors.length)throw new Error("AAP-4 requires at least one supporting checkpoint receipt")}}}const an=new TextEncoder,cn=/^sha256:[a-f0-9]{64}$/;class dn{crypto;constructor(e){this.crypto=e}async sha256(e){const t=await this.crypto.hash(e);if(!cn.test(t))throw new TypeError("Audit hasher must return sha256:<lowercase-hex>");return t}}class un{keys;constructor(e){this.keys=e}async verify(e,t,i){try{if(!i.kid.startsWith(`${i.did}#`))return!1;const r=await this.keys.resolve(i);if(null===r)return!1;const n=await ze(t,r,{algorithms:[i.alg]});return n.protectedHeader.alg===i.alg&&n.protectedHeader.kid===i.kid&&n.payload.length===e.length&&n.payload.every((t,i)=>t===e[i])}catch{return!1}}}class ln{ref;privateKey;constructor(e,t){this.ref=e,this.privateKey=t}async sign(e){return new et(e).setProtectedHeader({alg:this.ref.alg,kid:this.ref.kid}).sign(this.privateKey)}}async function hn(e,t,i){if(0===t.length||t.includes("\0"))throw new TypeError("Audit digest domain must be non-empty and cannot contain NUL");const r=an.encode(`${t}\0`),n=L(i),o=new Uint8Array(r.length+n.length);return o.set(r),o.set(n,r.length),e.sha256(o)}function pn(e){return"evidence_ref"===e?.kind?[e.ref]:[]}function fn(e){const t="delegation"===e.details.family?e.details.statusEvidence??[]:"ledger"===e.details.family&&void 0!==e.details.targetEvidenceRef?[e.details.targetEvidenceRef]:[];return[...pn(e.tenantRef),...pn(e.source.producer),...pn(e.session?.ref),...pn(e.actor),...pn(e.responsibleParty),...pn(e.resource),...void 0===e.proof?[]:[e.proof],...e.evidence,...void 0===e.action.detailRef?[]:[e.action.detailRef],...void 0===e.reason?.detailRef?[]:[e.reason.detailRef],...e.authorization?.statusEvidence??[],...t]}const gn=Object.freeze({event:"org.kya-os.audit.event.v1",entry:"org.kya-os.audit.entry.v1",evidenceManifest:"org.kya-os.audit.evidence-manifest.v1",idempotency:"org.kya-os.audit.idempotency.v1",checkpoint:"org.kya-os.audit.checkpoint.v1",observation:"org.kya-os.audit.observation.v1",bundleManifest:"org.kya-os.audit.bundle-manifest.v1",bundleComponent:"org.kya-os.audit.bundle-component.v1"});function yn(e){return{refs:fn(e)}}function mn(e,t){return{schema:"https://schema.kya-os.org/v1/protocol/audit/receipt/v1.0.0",ledgerId:e.ledgerId,ledgerEpochId:e.ledgerEpochId,sequence:e.sequence,eventId:e.event.eventId,entryDigest:t,previousEntryDigest:e.previousEntryDigest,recordedAt:e.recordedAt,recorder:e.recorder,integritySuite:"KYA-AUDIT-JCS-SHA256-JWS-2026"}}async function vn(e,t){return hn(e,gn.event,t)}async function In(e,t){return hn(e,gn.entry,t)}async function En(e,t){return hn(e,gn.evidenceManifest,yn(t))}const wn={INVALID_EVENT:"AUDIT_INVALID_EVENT",LEDGER_MISMATCH:"AUDIT_LEDGER_MISMATCH",EPOCH_MISMATCH:"AUDIT_EPOCH_MISMATCH",EVENT_ID_CONFLICT:"AUDIT_EVENT_ID_CONFLICT",APPEND_CONFLICT_EXHAUSTED:"AUDIT_APPEND_CONFLICT_EXHAUSTED",JOURNAL_FAILURE:"AUDIT_JOURNAL_FAILURE",EVIDENCE_FAILURE:"AUDIT_EVIDENCE_FAILURE",EVIDENCE_INTEGRITY:"AUDIT_EVIDENCE_INTEGRITY",EVIDENCE_LEGAL_HOLD:"AUDIT_EVIDENCE_LEGAL_HOLD",EVIDENCE_ACCESS_DENIED:"AUDIT_EVIDENCE_ACCESS_DENIED",CHECKPOINT_INVALID:"AUDIT_CHECKPOINT_INVALID",CHECKPOINT_ROLLBACK:"AUDIT_CHECKPOINT_ROLLBACK",CHECKPOINT_CONFLICT:"AUDIT_CHECKPOINT_CONFLICT",CHECKPOINT_PUBLICATION_FAILED:"AUDIT_CHECKPOINT_PUBLICATION_FAILED",PROJECTION_CONFLICT:"AUDIT_PROJECTION_CONFLICT",MIRROR_VERIFICATION_FAILED:"AUDIT_MIRROR_VERIFICATION_FAILED",MIRROR_CONTINUITY_FAILED:"AUDIT_MIRROR_CONTINUITY_FAILED",MIRROR_OUT_OF_ORDER:"AUDIT_MIRROR_OUT_OF_ORDER",UNAUTHORIZED_SUBMISSION:"AUDIT_UNAUTHORIZED_SUBMISSION",INVALID_CONFIGURATION:"AUDIT_INVALID_CONFIGURATION"};class Sn extends Error{code;details;constructor(e,t,i,r){super(t,r),this.code=e,this.details=i,this.name="AuditProtocolError"}}class Dn{config;constructor(e){this.config=e}async encrypt(e){if("AES-GCM"!==e.key.algorithm.name)throw new TypeError("Evidence encryption key must use AES-GCM");if(0===e.aad.byteLength)throw new TypeError("Evidence encryption requires entity-scoped authenticated data");const t=await this.config.randomBytes(12),i=await this.config.randomBytes(16),r=await this.config.crypto.subtle.encrypt({name:"AES-GCM",iv:bn(t),additionalData:bn(e.aad),tagLength:128},e.key,bn(e.plaintext)),n=new Uint8Array(r),o=await this.config.hasher.sha256(n),s=await this.config.hasher.sha256(e.aad),a={objectId:`evi_${c(i)}`,ciphertextDigest:o,...e.plaintextCommitment?{plaintextCommitment:e.plaintextCommitment}:{},mediaType:e.mediaType,size:String(n.byteLength),encryption:{suite:"A256GCM",keyId:e.keyId,nonce:c(t),aadDigest:s}};return{ref:Object.freeze(a),ciphertext:n}}async decrypt(e,t,i){if(0===i.byteLength)throw new TypeError("Evidence decryption requires entity-scoped authenticated data");const r=await this.config.hasher.sha256(e.ciphertext),n=await this.config.hasher.sha256(i);if(r!==e.ref.ciphertextDigest||n!==e.ref.encryption.aadDigest)throw new Sn(wn.EVIDENCE_INTEGRITY,"Evidence ciphertext or authenticated metadata digest does not match");try{const r=await this.config.crypto.subtle.decrypt({name:"AES-GCM",iv:bn(s(e.ref.encryption.nonce)),additionalData:bn(i),tagLength:128},t,bn(e.ciphertext));return new Uint8Array(r)}catch(e){throw new Sn(wn.EVIDENCE_INTEGRITY,"Evidence AEAD verification failed",void 0,{cause:e})}}}class An{hasher;options;states=new Map;constructor(e,t={}){this.hasher=e,this.options=t}async putIfAbsent(e){if(await this.hasher.sha256(e.ciphertext)!==e.ref.ciphertextDigest||String(e.ciphertext.byteLength)!==e.ref.size)throw new Sn(wn.EVIDENCE_INTEGRITY,"Evidence bytes do not match their ciphertext digest or size");const t=this.states.get(e.ref.objectId);if(void 0!==t){if(t.ref.ciphertextDigest!==e.ref.ciphertextDigest||null===t.ciphertext||!function(e,t){if(e.byteLength!==t.byteLength)return!1;let i=0;for(let r=0;r<e.byteLength;r+=1)i|=e[r]^t[r];return 0===i}(t.ciphertext,e.ciphertext))throw new Sn(wn.EVIDENCE_INTEGRITY,"Opaque evidence object ID collision");return t.ref}return this.states.set(e.ref.objectId,{ref:e.ref,ciphertext:new Uint8Array(e.ciphertext),holds:new Set}),e.ref}async has(e){return null!==this.states.get(e.objectId)?.ciphertext&&this.states.has(e.objectId)}async get(e,t){if(void 0!==this.options.authorizeAccess&&!await this.options.authorizeAccess({ref:e,context:t}))throw await(this.options.onAccess?.({ref:e,context:t,result:"denied"})),new Sn(wn.EVIDENCE_ACCESS_DENIED,"Evidence access policy denied this actor and purpose");const i=this.states.get(e.objectId),r=void 0===i?"missing":null===i.ciphertext?"disposed":"found";return await(this.options.onAccess?.({ref:e,context:t,result:r})),null===i?.ciphertext||void 0===i?null:new Uint8Array(i.ciphertext)}async applyRetention(e){const t=this.states.get(e.ref.objectId);if(void 0===t)return{ref:e.ref,state:"missing"};if("legal_hold"===e.kind)return t.holds.add(e.holdId),{ref:t.ref,state:"held"};if("release_hold"===e.kind)return t.holds.delete(e.holdId),{ref:t.ref,state:null===t.ciphertext?"disposed":t.holds.size>0?"held":"retained"};if(t.holds.size>0)throw new Sn(wn.EVIDENCE_LEGAL_HOLD,"Evidence cannot be disposed while a legal hold is active",{holdIds:[...t.holds]});return t.ciphertext=null,{ref:t.ref,state:"disposed"}}}function bn(e){return Uint8Array.from(e).buffer}const _n=/^sha256:([a-f0-9]{64})$/;function Cn(e){const t=_n.exec(e);if(null===t)throw new TypeError("Expected sha256:<lowercase-hex> digest");const i=t[1],r=new Uint8Array(32);for(let e=0;e<r.length;e+=1)r[e]=Number.parseInt(i.slice(2*e,2*e+2),16);return r}function Tn(...e){const t=new Uint8Array(e.reduce((e,t)=>e+t.length,0));let i=0;for(const r of e)t.set(r,i),i+=r.length;return t}function kn(e){let t=1;for(;2*t<e;)t*=2;return t}function Nn(e,t){if(!Number.isSafeInteger(e)||e<0)throw new RangeError(`${t} must be a non-negative safe integer`)}class Rn{hasher;constructor(e){this.hasher=e}async leafHash(e){return this.hasher.sha256(Tn(Uint8Array.of(0),Cn(e)))}async nodeHash(e,t){return this.hasher.sha256(Tn(Uint8Array.of(1),Cn(e),Cn(t)))}async root(e){if(0===e.length)return this.hasher.sha256(new Uint8Array);if(1===e.length)return this.leafHash(e[0]);const t=kn(e.length),[i,r]=await Promise.all([this.root(e.slice(0,t)),this.root(e.slice(t))]);return this.nodeHash(i,r)}async inclusionProof(e,t){if(Nn(t,"Leaf index"),0===e.length||t>=e.length)throw new RangeError("Leaf index must identify a leaf in the tree");return this.buildInclusionProof(e,t)}async buildInclusionProof(e,t){if(1===e.length)return[];const i=kn(e.length);if(t<i){const[r,n]=await Promise.all([this.buildInclusionProof(e.slice(0,i),t),this.root(e.slice(i))]);return[...r,n]}const[r,n]=await Promise.all([this.buildInclusionProof(e.slice(i),t-i),this.root(e.slice(0,i))]);return[...r,n]}async verifyInclusion(e){try{if(Nn(e.leafIndex,"Leaf index"),Nn(e.treeSize,"Tree size"),0===e.treeSize||e.leafIndex>=e.treeSize)return!1;let t=e.leafIndex,i=e.treeSize-1,r=await this.leafHash(e.leaf);for(const n of e.auditPath){if(0===i)return!1;if(1&~t&&t!==i)r=await this.nodeHash(r,n);else for(r=await this.nodeHash(n,r);!(1&t)&&0!==t;)t=Math.floor(t/2),i=Math.floor(i/2);t=Math.floor(t/2),i=Math.floor(i/2)}return 0===i&&r===e.root}catch{return!1}}async consistencyProof(e,t){if(Nn(t,"Old tree size"),0===t||t>e.length)throw new RangeError("Old tree size must be between 1 and the new tree size");return t===e.length?[]:this.buildConsistencyProof(t,e,!0)}async buildConsistencyProof(e,t,i){if(e===t.length)return i?[]:[await this.root(t)];const r=kn(t.length);if(e<=r){const[n,o]=await Promise.all([this.buildConsistencyProof(e,t.slice(0,r),i),this.root(t.slice(r))]);return[...n,o]}const[n,o]=await Promise.all([this.buildConsistencyProof(e-r,t.slice(r),!1),this.root(t.slice(0,r))]);return[...n,o]}async verifyConsistency(e){try{if(Nn(e.oldSize,"Old tree size"),Nn(e.newSize,"New tree size"),0===e.oldSize||e.oldSize>e.newSize)return!1;if(e.oldSize===e.newSize)return 0===e.auditPath.length&&e.oldRoot===e.newRoot;let t=e.oldSize-1,i=e.newSize-1;for(;!(1&~t);)t=Math.floor(t/2),i=Math.floor(i/2);let r,n,o=0;if(0===t)r=e.oldRoot,n=e.oldRoot;else{const t=e.auditPath[o++];if(void 0===t)return!1;r=t,n=t}for(;o<e.auditPath.length;o+=1){if(0===i)return!1;const s=e.auditPath[o];if(1&~t&&t!==i)n=await this.nodeHash(n,s);else for(r=await this.nodeHash(s,r),n=await this.nodeHash(s,n);!(1&t)&&0!==t;)t=Math.floor(t/2),i=Math.floor(i/2);t=Math.floor(t/2),i=Math.floor(i/2)}return 0===i&&r===e.oldRoot&&n===e.newRoot}catch{return!1}}}function On(e){return`${e.ledgerId}\0${e.ledgerEpochId}`}function Pn(e,t){return`${On(e)}\0${t}`}function Ln(e,t){if(!/^(0|[1-9][0-9]*)$/.test(e))throw new Sn(wn.CHECKPOINT_INVALID,`${t} must be a canonical non-negative decimal string`);return BigInt(e)}function xn(e,t){if(e>BigInt(Number.MAX_SAFE_INTEGER))throw new Sn(wn.CHECKPOINT_INVALID,`${t} exceeds this implementation's safe in-memory proof range`);return Number(e)}function Mn(e){if("object"!=typeof e||null===e||Object.isFrozen(e))return e;for(const t of Object.values(e))Mn(t);return Object.freeze(e)}class zn{checkpoints=new Map;latest=new Map;async getLatest(e){return this.latest.get(On(e))??null}async getByTreeSize(e,t){return this.checkpoints.get(Pn(e,t))??null}async putIfAbsent(e){const t=e.core,i=Pn(t,e.core.treeSize),r=this.checkpoints.get(i);if(void 0!==r)return r.checkpointDigest===e.checkpointDigest?{kind:"existing",checkpoint:r}:{kind:"conflict",checkpoint:r};const n=Mn(e);this.checkpoints.set(i,n);const o=this.latest.get(On(t));return(void 0===o||BigInt(o.core.treeSize)<BigInt(e.core.treeSize))&&this.latest.set(On(t),n),{kind:"inserted",checkpoint:n}}}class Un{options;tree;clock;constructor(e){this.options=e,this.tree=new Rn(e.hasher),this.clock=e.clock??Date}async createCheckpoint(e){const t=await this.snapshotAtHead(e);if(0===t.length)throw new Sn(wn.CHECKPOINT_INVALID,"Cannot checkpoint an empty audit epoch");const i=String(t.length),r=await this.options.store.getLatest(e);if(null!==r){const e=Ln(r.core.treeSize,"Previous tree size");if(e>BigInt(t.length))throw new Sn(wn.CHECKPOINT_ROLLBACK,"Journal tree size is behind the latest signed checkpoint");if(e===BigInt(t.length)){const e=await this.tree.root(t.map(e=>e.entryDigest));if(r.core.rootDigest!==e||r.core.headEntryDigest!==t[t.length-1].entryDigest)throw new Sn(wn.CHECKPOINT_CONFLICT,"Journal content forked at the latest checkpointed tree size");return r}}const n=t[0],o=t[t.length-1],s=Zr({schema:"https://schema.kya-os.org/v1/protocol/audit/checkpoint/v1.0.0",checkpointId:`checkpoint:${e.ledgerId}:${e.ledgerEpochId}:${i}`,...e,treeSize:i,firstSequence:n.core.sequence,lastSequence:o.core.sequence,rootDigest:await this.tree.root(t.map(e=>e.entryDigest)),headEntryDigest:o.entryDigest,previousCheckpointDigest:r?.checkpointDigest??null,createdAt:this.clock.now(),issuer:this.options.signer.ref,integritySuite:"KYA-AUDIT-RFC9162-SHA256-JWS-2026"}),a=Mn({core:s,checkpointDigest:await hn(this.options.hasher,gn.checkpoint,s),jws:await this.options.signer.sign(L(s))}),c=await this.options.store.putIfAbsent(a);if("conflict"===c.kind)throw new Sn(wn.CHECKPOINT_CONFLICT,"A different checkpoint already exists at this tree size",{treeSize:i});return"inserted"===c.kind&&await(this.options.onCheckpointCreated?.(c.checkpoint)),c.checkpoint}async inclusionProof(e,t,i){this.assertCheckpointLedger(e,i);const r=await this.entriesForCheckpoint(e,i),n=r.findIndex(e=>e.core.sequence===t);if(n<0)throw new Sn(wn.CHECKPOINT_INVALID,"Sequence is not included in the checkpoint",{sequence:t,treeSize:i.core.treeSize});return Mn({leafIndex:String(n),treeSize:i.core.treeSize,auditPath:await this.tree.inclusionProof(r.map(e=>e.entryDigest),n)})}async consistencyProof(e,t,i){this.assertCheckpointLedger(e,i);const r=await this.entriesForCheckpoint(e,i),n=xn(Ln(t,"Old tree size"),"Old tree size");return Mn({oldTreeSize:t,newTreeSize:i.core.treeSize,auditPath:await this.tree.consistencyProof(r.map(e=>e.entryDigest),n)})}async rootForRange(e,t){const i=xn(Ln(t,"Tree size"),"Tree size");if(0===i)return this.tree.root([]);const r=await this.readEntries(e,i);if(r.length!==i)throw new Sn(wn.CHECKPOINT_INVALID,"Journal does not contain the requested tree range",{treeSize:t});return this.tree.root(r.map(e=>e.entryDigest))}async verifyInclusion(e,t,i){return i.treeSize===t.core.treeSize&&this.tree.verifyInclusion({leaf:e,leafIndex:xn(Ln(i.leafIndex,"Leaf index"),"Leaf index"),treeSize:xn(Ln(i.treeSize,"Tree size"),"Tree size"),root:t.core.rootDigest,auditPath:i.auditPath})}async verifyConsistency(e){return e.proof.oldTreeSize===e.oldTreeSize&&e.proof.newTreeSize===e.checkpoint.core.treeSize&&this.tree.verifyConsistency({oldSize:xn(Ln(e.oldTreeSize,"Old tree size"),"Old tree size"),newSize:xn(Ln(e.checkpoint.core.treeSize,"New tree size"),"New tree size"),oldRoot:e.oldRoot,newRoot:e.checkpoint.core.rootDigest,auditPath:e.proof.auditPath})}async snapshotAtHead(e){const t=await this.options.journal.getHead(e);if(null===t)return[];const i=xn(Ln(t.sequence,"Journal head sequence")+1n,"Journal tree size"),r=await this.readEntries(e,i),n=r[r.length-1];if(r.length!==i||n?.entryDigest!==t.entryDigest)throw new Sn(wn.JOURNAL_FAILURE,"Journal could not provide a stable range through its reported head");return r}async entriesForCheckpoint(e,t){const i=xn(Ln(t.core.treeSize,"Checkpoint tree size"),"Checkpoint tree size"),r=await this.readEntries(e,i);if(r.length!==i||r[r.length-1]?.entryDigest!==t.core.headEntryDigest)throw new Sn(wn.CHECKPOINT_INVALID,"Journal range does not match the signed checkpoint head");return r}async readEntries(e,t){const i=[];for await(const r of this.options.journal.readRange({...e,limit:t})){if(BigInt(r.core.sequence)!==BigInt(i.length))throw new Sn(wn.JOURNAL_FAILURE,"Audit journal range is not contiguous from sequence zero");i.push(r)}return i}assertCheckpointLedger(e,t){if(t.core.ledgerId!==e.ledgerId||t.core.ledgerEpochId!==e.ledgerEpochId)throw new Sn(wn.LEDGER_MISMATCH,"Checkpoint belongs to a different ledger or epoch")}}class Hn{options;observers;anchors;maxAttempts;constructor(e){if(this.options=e,this.observers=e.observers??[],this.anchors=e.anchors??[],this.maxAttempts=e.maxPublishAttempts??1,!Number.isSafeInteger(this.maxAttempts)||this.maxAttempts<1)throw new Sn(wn.INVALID_CONFIGURATION,"Checkpoint publication attempts must be a positive safe integer");const t=e.requirements;if(void 0!==t&&(!Number.isSafeInteger(t.minimumObservers)||t.minimumObservers<0))throw new Sn(wn.INVALID_CONFIGURATION,"Minimum checkpoint observers must be a non-negative safe integer")}async createAndPublish(e){const t=await this.options.checkpoints.createCheckpoint(e),i=[],r=[],n=[];await Promise.all(this.observers.map(async(e,r)=>{const o=await this.publishWithRetry("observer",r,()=>e.publish(t));o.ok?i.push(o.value):n.push(o.failure)})),await Promise.all(this.anchors.map(async(e,i)=>{const o=await this.publishWithRetry("anchor",i,()=>e.publish(t),e.kind);o.ok?r.push(o.value):n.push(o.failure)})),i.sort((e,t)=>e.core.observerId.localeCompare(t.core.observerId)),r.sort((e,t)=>e.kind.localeCompare(t.kind)||e.providerId.localeCompare(t.providerId)),n.sort((e,t)=>e.role.localeCompare(t.role)||e.providerIndex-t.providerIndex);const o={checkpoint:t,observations:i,anchors:r,failures:n};return this.assertRequirements(o),await(this.options.onPublished?.(o)),o}async publishWithRetry(e,t,i,r){let n;for(let o=1;o<=this.maxAttempts;o+=1)try{return{ok:!0,value:await i()}}catch(i){if(n=i,o<this.maxAttempts)try{await(this.options.backoff?.({role:e,providerIndex:t,attempt:o,error:i}))}catch(n){return{ok:!1,failure:{role:e,providerIndex:t,...void 0===r?{}:{kind:r},attempts:o,error:new AggregateError([i,n],"Checkpoint publication backoff failed")}}}}return{ok:!1,failure:{role:e,providerIndex:t,...void 0===r?{}:{kind:r},attempts:this.maxAttempts,error:n}}}assertRequirements(e){const t=this.options.requirements;if(void 0===t)return;const i=[...new Set(t.requiredAnchorKinds)].filter(t=>!e.anchors.some(e=>e.kind===t));if(e.observations.length<t.minimumObservers||i.length>0)throw new Sn(wn.CHECKPOINT_PUBLICATION_FAILED,"Signed checkpoint did not obtain the required external publication evidence",{checkpointDigest:e.checkpoint.checkpointDigest,requiredObservers:t.minimumObservers,publishedObservers:e.observations.length,missingAnchorKinds:i,failedProviders:e.failures.map(({role:e,providerIndex:t,kind:i,attempts:r})=>({role:e,providerIndex:t,...void 0===i?{}:{kind:i},attempts:r}))})}}function jn(e,t){return`${e}\0${t.ledgerId}\0${t.ledgerEpochId}`}function Kn(e){const t=e.core.event;return Object.freeze({ledgerId:e.core.ledgerId,ledgerEpochId:e.core.ledgerEpochId,sequence:e.core.sequence,entryDigest:e.entryDigest,eventId:t.eventId,eventType:t.eventType,occurredAt:t.occurredAt,recordedAt:e.core.recordedAt,outcome:t.outcome,...void 0===t.correlationId?{}:{correlationId:t.correlationId},...void 0===t.causationId?{}:{causationId:t.causationId},chainStatus:"chained"})}class $n{capabilities={durability:"ephemeral",atomicOffset:!0};offsets=new Map;records=new Map;async getOffset(e,t){const i=this.offsets.get(jn(e,t));return void 0===i?null:{...i}}async compareAndApply(e){const t=jn(e.projectionId,e.ledger),i=this.offsets.get(t)??null,r=this.records.get(t)?.find(t=>t.sequence===e.entry.core.sequence);if(void 0!==r)return r.entryDigest===e.entry.entryDigest?{kind:"duplicate"}:{kind:"conflict",actualOffset:i};if(n=i,o=e.expectedOffset,!(null===n||null===o?n===o:n.sequence===o.sequence&&n.entryDigest===o.entryDigest))return{kind:"conflict",actualOffset:i};var n,o;const s=null===i?0n:BigInt(i.sequence)+1n;if(BigInt(e.entry.core.sequence)!==s)return{kind:"conflict",actualOffset:i};const a=this.records.get(t)??[];return a.push(Object.freeze({...e.record})),this.records.set(t,a),this.offsets.set(t,{sequence:e.entry.core.sequence,entryDigest:e.entry.entryDigest}),{kind:"applied"}}async reset(e,t){const i=jn(e,t);this.offsets.delete(i),this.records.delete(i)}async read(e,t){return(this.records.get(jn(e,t))??[]).map(e=>({...e}))}corruptOffsetForTesting(e,t,i){this.offsets.set(jn(e,t),{...i})}}class Vn{options;constructor(e){if(this.options=e,!e.projectionId)throw new Sn(wn.INVALID_CONFIGURATION,"Projection ID is required")}async synchronize(e){let t=await this.options.projections.getOffset(this.options.projectionId,e),i=0,r=0;for await(const n of this.options.journal.readRange({...e,...null===t?{}:{afterSequence:t.sequence}})){const o=await this.options.projections.compareAndApply({projectionId:this.options.projectionId,ledger:e,expectedOffset:t,entry:n,record:Kn(n)});if("conflict"===o.kind)throw new Sn(wn.PROJECTION_CONFLICT,"Projection offset conflicted with the ordered ledger",{sequence:n.core.sequence,expectedOffset:t,actualOffset:o.actualOffset});"applied"===o.kind?i+=1:r+=1,t={sequence:n.core.sequence,entryDigest:n.entryDigest}}return{applied:i,duplicates:r}}async rebuild(e){return await this.options.projections.reset(this.options.projectionId,e),this.synchronize(e)}async reconcile(e){const[t,i]=await Promise.all([this.options.journal.getHead(e),this.options.projections.getOffset(this.options.projectionId,e)]);let r;return r=null===t&&null===i?"empty":null!==t&&null===i?"pending":null===t||null===i?"gap_detected":t.sequence===i.sequence?t.entryDigest===i.entryDigest?"verified":"gap_detected":BigInt(i.sequence)<BigInt(t.sequence)?"pending":"gap_detected",{status:r,journalHead:t,projectionHead:i}}}const Bn=Object.freeze({NOT_EVALUATED:"AUDIT_NOT_EVALUATED",SCHEMA_INVALID:"AUDIT_SCHEMA_INVALID",UNSUPPORTED_SUITE:"AUDIT_UNSUPPORTED_SUITE",UNSUPPORTED_ALGORITHM:"AUDIT_UNSUPPORTED_ALGORITHM",UNTRUSTED_RECORDER:"AUDIT_UNTRUSTED_RECORDER",SIGNATURE_INVALID:"AUDIT_SIGNATURE_INVALID",EVENT_DIGEST_MISMATCH:"AUDIT_EVENT_DIGEST_MISMATCH",EVIDENCE_MANIFEST_DIGEST_MISMATCH:"AUDIT_EVIDENCE_MANIFEST_DIGEST_MISMATCH",ENTRY_DIGEST_MISMATCH:"AUDIT_ENTRY_DIGEST_MISMATCH",RECEIPT_MISMATCH:"AUDIT_RECEIPT_MISMATCH",LEDGER_SCOPE_MISMATCH:"AUDIT_LEDGER_SCOPE_MISMATCH",SEQUENCE_GAP:"AUDIT_SEQUENCE_GAP",PREDECESSOR_MISMATCH:"AUDIT_PREDECESSOR_MISMATCH",GENESIS_INVALID:"AUDIT_GENESIS_INVALID",CHECKPOINT_MISSING:"AUDIT_CHECKPOINT_MISSING",CHECKPOINT_DIGEST_MISMATCH:"AUDIT_CHECKPOINT_DIGEST_MISMATCH",CHECKPOINT_SIGNATURE_INVALID:"AUDIT_CHECKPOINT_SIGNATURE_INVALID",CHECKPOINT_ROOT_MISMATCH:"AUDIT_CHECKPOINT_ROOT_MISMATCH",CHECKPOINT_RANGE_MISMATCH:"AUDIT_CHECKPOINT_RANGE_MISMATCH",CHECKPOINT_CHAIN_MISMATCH:"AUDIT_CHECKPOINT_CHAIN_MISMATCH",CHECKPOINT_FORK_DETECTED:"AUDIT_CHECKPOINT_FORK_DETECTED",MERKLE_PROOF_INVALID:"AUDIT_MERKLE_PROOF_INVALID",OBSERVER_EVIDENCE_MISSING:"AUDIT_OBSERVER_EVIDENCE_MISSING",OBSERVATION_DIGEST_MISMATCH:"AUDIT_OBSERVATION_DIGEST_MISMATCH",OBSERVATION_SIGNATURE_INVALID:"AUDIT_OBSERVATION_SIGNATURE_INVALID",OBSERVATION_SCOPE_MISMATCH:"AUDIT_OBSERVATION_SCOPE_MISMATCH",UNTRUSTED_OBSERVER:"AUDIT_UNTRUSTED_OBSERVER",OBSERVATION_STALE:"AUDIT_OBSERVATION_STALE",OBSERVATION_CHAIN_MISMATCH:"AUDIT_OBSERVATION_CHAIN_MISMATCH",UNTRUSTED_SUPPORTING_ANCHOR:"AUDIT_UNTRUSTED_SUPPORTING_ANCHOR",SUPPORTING_ANCHOR_INVALID:"AUDIT_SUPPORTING_ANCHOR_INVALID",AUTHORIZATION_EVIDENCE_MISSING:"AUDIT_AUTHORIZATION_EVIDENCE_MISSING",AUTHORIZATION_COLLATERAL_NOT_VERIFIED:"AUDIT_AUTHORIZATION_COLLATERAL_NOT_VERIFIED",CURRENT_AUTHORIZATION_NOT_EVALUATED:"AUDIT_CURRENT_AUTHORIZATION_NOT_EVALUATED",BUNDLE_SCHEMA_INVALID:"AUDIT_BUNDLE_SCHEMA_INVALID",BUNDLE_MANIFEST_DIGEST_MISMATCH:"AUDIT_BUNDLE_MANIFEST_DIGEST_MISMATCH",BUNDLE_SIGNATURE_INVALID:"AUDIT_BUNDLE_SIGNATURE_INVALID",BUNDLE_EXPORTER_UNAUTHORIZED:"AUDIT_BUNDLE_EXPORTER_UNAUTHORIZED",BUNDLE_INVENTORY_MISMATCH:"AUDIT_BUNDLE_INVENTORY_MISMATCH",BUNDLE_COMPONENT_DIGEST_MISMATCH:"AUDIT_BUNDLE_COMPONENT_DIGEST_MISMATCH",BUNDLE_SELECTION_INCOMPLETE:"AUDIT_BUNDLE_SELECTION_INCOMPLETE",VERIFICATION_POLICY_MISMATCH:"AUDIT_VERIFICATION_POLICY_MISMATCH",VERIFICATION_POLICY_INVALID:"AUDIT_VERIFICATION_POLICY_INVALID",EXPLICITLY_REDACTED:"AUDIT_EXPLICITLY_REDACTED",EXPLICITLY_DISPOSED:"AUDIT_EXPLICITLY_DISPOSED",EXPLICITLY_UNAVAILABLE:"AUDIT_EXPLICITLY_UNAVAILABLE"});function qn(e,t=[]){return{verdict:e,reasonCodes:[...new Set(t)].sort()}}function Fn(e,t){return e.did===t.did&&e.kid===t.kid&&e.alg===t.alg}function Wn(e,t){return(void 0===e.validFrom||t>=e.validFrom)&&(void 0===e.validUntil||t<=e.validUntil)}class Gn{options;constructor(e){this.options=e}async verifyEntries(e,t){if(!qr.safeParse(t).success)return function(e){const t="object"==typeof e&&null!==e&&"string"==typeof e.policyId?e.policyId:"invalid-policy",i=qn("invalid",[Bn.VERIFICATION_POLICY_INVALID]);return{schema:"https://schema.kya-os.org/v1/protocol/audit/verification-report/v1.0.0",policyId:t,cryptographicIntegrity:i,chainIntegrity:i,checkpointIntegrity:i,anchorIntegrity:i,scopeEvidenceCompleteness:i,authorizedAsObserved:qn("indeterminate",[Bn.NOT_EVALUATED]),currentAuthorization:qn("indeterminate",[Bn.NOT_EVALUATED])}}(t);const i=t,r=new Set,n=new Set,o=[];0===e.length&&n.add(Bn.BUNDLE_SELECTION_INCOMPLETE);for(const t of e){const e=Rr.safeParse(t);if(!e.success){r.add(Bn.SCHEMA_INVALID),n.add(Bn.SCHEMA_INVALID);continue}const s=e.data,a=o.length;await this.verifyEntry(s,i,r),this.verifyChainPosition(s,o[a-1],a,n),o.push(s)}const s=o.some(e=>void 0!==e.core.event.authorization),[a,c]=void 0===this.options.authorization?[qn("indeterminate",[s?Bn.AUTHORIZATION_COLLATERAL_NOT_VERIFIED:Bn.AUTHORIZATION_EVIDENCE_MISSING]),qn("indeterminate",[Bn.CURRENT_AUTHORIZATION_NOT_EVALUATED])]:await Promise.all([this.options.authorization.verifyAsObserved(o,i),this.options.authorization.verifyCurrent(o,i)]);return{schema:"https://schema.kya-os.org/v1/protocol/audit/verification-report/v1.0.0",policyId:i.policyId,...void 0===this.options.verifiedAt?{}:{verifiedAt:this.options.verifiedAt()},cryptographicIntegrity:qn(0===r.size&&e.length>0?"valid":"invalid",r),chainIntegrity:qn(0===n.size&&e.length>0?"valid":"invalid",n),checkpointIntegrity:qn("indeterminate",[Bn.CHECKPOINT_MISSING]),anchorIntegrity:qn("indeterminate",[Bn.OBSERVER_EVIDENCE_MISSING]),scopeEvidenceCompleteness:qn(e.length>0?"indeterminate":"invalid",[Bn.NOT_EVALUATED]),authorizedAsObserved:a,currentAuthorization:c}}async verifyCheckpoint(e,t,i){const r=new Set;if(!qr.safeParse(i).success)return qn("invalid",[Bn.VERIFICATION_POLICY_INVALID]);const n=Nr.safeParse(e);if(!n.success)return qn("invalid",[Bn.SCHEMA_INVALID]);const o=n.data,s=o.core;i.acceptedIntegritySuites.includes(s.integritySuite)||r.add(Bn.UNSUPPORTED_SUITE),i.acceptedAlgorithms.includes(s.issuer.alg)||r.add(Bn.UNSUPPORTED_ALGORITHM);const a=i.trustedLedgerEpochs.find(e=>e.ledgerId===s.ledgerId&&e.ledgerEpochId===s.ledgerEpochId);a?.recorderKeys.some(e=>Fn(e.signer,s.issuer)&&Wn(e,s.createdAt))||r.add(Bn.UNTRUSTED_RECORDER),await hn(this.options.hasher,gn.checkpoint,s)!==o.checkpointDigest&&r.add(Bn.CHECKPOINT_DIGEST_MISMATCH),await this.options.signatures.verify(L(s),o.jws,s.issuer)||r.add(Bn.CHECKPOINT_SIGNATURE_INVALID);const c=Number(s.treeSize),d=t[0],u=t[t.length-1];return!Number.isSafeInteger(c)||c!==t.length||d?.core.sequence!==s.firstSequence||u?.core.sequence!==s.lastSequence||u?.entryDigest!==s.headEntryDigest||t.some(e=>e.core.ledgerId!==s.ledgerId||e.core.ledgerEpochId!==s.ledgerEpochId)?r.add(Bn.CHECKPOINT_RANGE_MISMATCH):await new Rn(this.options.hasher).root(t.map(e=>e.entryDigest))!==s.rootDigest&&r.add(Bn.CHECKPOINT_ROOT_MISMATCH),qn(0===r.size?"valid":"invalid",r)}async verifyObservation(e,t,i){const r=new Set;let n=!1;if(!qr.safeParse(i).success)return qn("invalid",[Bn.VERIFICATION_POLICY_INVALID]);const o=Nr.safeParse(e),s=Or.safeParse(t);if(!o.success||!s.success)return qn("invalid",[Bn.SCHEMA_INVALID]);const a=o.data,c=s.data,d=c.core;if("https://schema.kya-os.org/v1/protocol/audit/observation/v1.0.0"!==d.schema&&r.add(Bn.SCHEMA_INVALID),d.ledgerId===a.core.ledgerId&&d.ledgerEpochId===a.core.ledgerEpochId&&d.checkpointDigest===a.checkpointDigest&&d.treeSize===a.core.treeSize||r.add(Bn.OBSERVATION_SCOPE_MISMATCH),i.acceptedAlgorithms.includes(d.observer.alg)||r.add(Bn.UNSUPPORTED_ALGORITHM),i.trustedObservers.some(e=>Fn(e.signer,d.observer)&&Wn(e,d.observedAt))||r.add(Bn.UNTRUSTED_OBSERVER),void 0!==i.requiredCheckpointFreshnessMs){const e=this.options.verifiedAt?.();void 0===e?(r.add(Bn.NOT_EVALUATED),n=!0):e-d.observedAt>i.requiredCheckpointFreshnessMs&&r.add(Bn.OBSERVATION_STALE)}await hn(this.options.hasher,gn.observation,d)!==c.observationDigest&&r.add(Bn.OBSERVATION_DIGEST_MISMATCH),await this.options.signatures.verify(L(d),c.jws,d.observer)||r.add(Bn.OBSERVATION_SIGNATURE_INVALID);const u=n&&[...r].every(e=>e===Bn.NOT_EVALUATED);return qn(0===r.size?"valid":u?"indeterminate":"invalid",r)}async verifyEntry(e,t,i){t.acceptedIntegritySuites.includes(e.core.integritySuite)||i.add(Bn.UNSUPPORTED_SUITE),t.acceptedAlgorithms.includes(e.core.recorder.alg)||i.add(Bn.UNSUPPORTED_ALGORITHM);const r=t.trustedLedgerEpochs.find(t=>t.ledgerId===e.core.ledgerId&&t.ledgerEpochId===e.core.ledgerEpochId),n=r?.recorderKeys.find(t=>Fn(t.signer,e.core.recorder)&&Wn(t,e.core.recordedAt));void 0===n&&i.add(Bn.UNTRUSTED_RECORDER);const o=await vn(this.options.hasher,e.core.event);o===e.core.eventDigest&&o===e.eventDigest||i.add(Bn.EVENT_DIGEST_MISMATCH),await En(this.options.hasher,e.core.event)!==e.core.evidenceManifestDigest&&i.add(Bn.EVIDENCE_MANIFEST_DIGEST_MISMATCH),await In(this.options.hasher,e.core)!==e.entryDigest&&i.add(Bn.ENTRY_DIGEST_MISMATCH),function(e,t){try{return P(e)===P(t)}catch{return!1}}(mn(e.core,e.entryDigest),e.recorderReceipt.core)||i.add(Bn.RECEIPT_MISMATCH),await this.options.signatures.verify(L(e.recorderReceipt.core),e.recorderReceipt.jws,e.core.recorder)||i.add(Bn.SIGNATURE_INVALID)}verifyChainPosition(e,t,i,r){if(void 0!==t){e.core.ledgerId===t.core.ledgerId&&e.core.ledgerEpochId===t.core.ledgerEpochId||r.add(Bn.LEDGER_SCOPE_MISMATCH);try{BigInt(e.core.sequence)!==BigInt(t.core.sequence)+1n&&r.add(Bn.SEQUENCE_GAP)}catch{r.add(Bn.SEQUENCE_GAP)}e.core.previousEntryDigest!==t.entryDigest&&r.add(Bn.PREDECESSOR_MISMATCH)}else"0"===e.core.sequence?null===e.core.previousEntryDigest&&"ledger.epoch.started"===e.core.event.eventType||r.add(Bn.GENESIS_INVALID):0===i&&null===e.core.previousEntryDigest&&r.add(Bn.PREDECESSOR_MISMATCH)}}function Jn(...e){return 0===e.length?qn("indeterminate",[Bn.NOT_EVALUATED]):qn(e.some(e=>"invalid"===e.verdict)?"invalid":e.every(e=>"valid"===e.verdict)?"valid":"indeterminate",e.flatMap(e=>e.reasonCodes))}const Yn="https://schema.kya-os.org/v1/protocol/audit/bundle-manifest/v1.0.0",Xn=Object.freeze({entries:"application/vnd.kya-os.audit.entries.v1+json",checkpoints:"application/vnd.kya-os.audit.checkpoints.v1+json",inclusionProofs:"application/vnd.kya-os.audit.inclusion-proofs.v1+json",consistencyProofs:"application/vnd.kya-os.audit.consistency-proofs.v1+json",observations:"application/vnd.kya-os.audit.observations.v1+json",anchors:"application/vnd.kya-os.audit.anchors.v1+json",verificationReport:"application/vnd.kya-os.audit.verification-report.v1+json"});function Zn(e){if("object"!=typeof e||null===e||Object.isFrozen(e))return e;for(const t of Object.values(e))Zn(t);return Object.freeze(e)}function Qn(e){return JSON.parse(P(e))}function eo(e){if(0===e.length||e.startsWith("/")||e.includes("\\")||e.split("/").some(e=>""===e||"."===e||".."===e))throw new TypeError("Bundle component path must be a safe canonical relative path")}function to(e,t){return(void 0===e.validFrom||t>=e.validFrom)&&(void 0===e.validUntil||t<=e.validUntil)}function io(e,t=[]){return{verdict:e,reasonCodes:[...new Set(t)].sort()}}class ro{options;constructor(e){this.options=e}async export(e){if(!e.bundleId||!e.purpose)throw new TypeError("Bundle ID and export purpose are required");const t=new Set,i=[...e.components].sort((e,t)=>e.path.localeCompare(t.path)),r=[];for(const e of i){if(eo(e.path),t.has(e.path))throw new TypeError(`Duplicate bundle component path: ${e.path}`);if(t.add(e.path),"included"===e.disposition){const t=Qn(e.content),i=L(t);r.push({path:e.path,mediaType:e.mediaType,disposition:"included",digest:await this.options.hasher.sha256(i),size:String(i.length),content:t})}else{if(!e.reasonCode)throw new TypeError("Excluded bundle items require a reason code");r.push({path:e.path,mediaType:e.mediaType,disposition:e.disposition,reasonCode:e.reasonCode})}}const n=r.map(e=>no(e)),o=tn({schema:Yn,bundleId:e.bundleId,formatVersion:"1.0.0",selections:Qn([...e.selections]),exporter:this.options.signer.ref,purpose:e.purpose,exportedAt:this.options.clock.now(),verificationPolicyDigest:e.verificationPolicyDigest,inventory:n,integritySuite:"KYA-AUDIT-BUNDLE-JCS-SHA256-JWS-2026"});return Zn({manifest:{core:o,manifestDigest:await hn(this.options.hasher,gn.bundleManifest,o),jws:await this.options.signer.sign(L(o))},components:r})}}function no(e){return{path:e.path,mediaType:e.mediaType,disposition:e.disposition,...void 0===e.digest?{}:{digest:e.digest},...void 0===e.size?{}:{size:e.size},...void 0===e.reasonCode?{}:{reasonCode:e.reasonCode}}}function oo(e,t){const i=[];for(const r of e.components)"included"===r.disposition&&r.mediaType===t&&Array.isArray(r.content)&&i.push(...r.content);return i}function so(e){return`${e.ledgerId}\0${e.ledgerEpochId}`}function ao(e,t){const i=BigInt(e),r=BigInt(t);return i<r?-1:i>r?1:0}function co(e,t,i){const r=new Set;for(const i of e){const e=t.filter(e=>e.core.ledgerId===i.ledgerId&&e.core.ledgerEpochId===i.ledgerEpochId),n=new Map;let o=!1;for(const t of e)n.has(t.core.sequence)?o=!0:n.set(t.core.sequence,t);const s=[...n.values()].sort((e,t)=>{const i=BigInt(e.core.sequence),r=BigInt(t.core.sequence);return i<r?-1:i>r?1:0});let a;try{a=BigInt(i.lastSequence)-BigInt(i.firstSequence)+1n}catch{r.add(Bn.BUNDLE_SELECTION_INCOMPLETE);continue}let c=!0;for(let e=1;e<s.length;e+=1)if(BigInt(s[e].core.sequence)!==BigInt(s[e-1].core.sequence)+1n){c=!1;break}(o||!c||a<1n||a!==BigInt(s.length)||s[0]?.core.sequence!==i.firstSequence||s[s.length-1]?.core.sequence!==i.lastSequence||s[s.length-1]?.entryDigest!==i.expectedHeadDigest)&&r.add(Bn.BUNDLE_SELECTION_INCOMPLETE)}for(const e of i)"redacted"===e.disposition&&r.add(Bn.EXPLICITLY_REDACTED),"disposed"===e.disposition&&r.add(Bn.EXPLICITLY_DISPOSED),"unavailable"===e.disposition&&r.add(Bn.EXPLICITLY_UNAVAILABLE);return r.has(Bn.BUNDLE_SELECTION_INCOMPLETE)?io("invalid",r):0===r.size?io("valid"):io("indeterminate",r)}async function uo(e,t,i){if(!qr.safeParse(t).success){const e="string"==typeof t?.policyId?t.policyId:"invalid-policy",i=io("invalid",[Bn.VERIFICATION_POLICY_INVALID]);return{schema:"https://schema.kya-os.org/v1/protocol/audit/verification-report/v1.0.0",policyId:e,cryptographicIntegrity:i,chainIntegrity:i,checkpointIntegrity:i,anchorIntegrity:i,scopeEvidenceCompleteness:i,authorizedAsObserved:io("indeterminate",[Bn.NOT_EVALUATED]),currentAuthorization:io("indeterminate",[Bn.NOT_EVALUATED])}}if(!$r.safeParse(e).success)return function(e){return{schema:"https://schema.kya-os.org/v1/protocol/audit/verification-report/v1.0.0",policyId:e.policyId,cryptographicIntegrity:io("invalid",[Bn.BUNDLE_SCHEMA_INVALID]),chainIntegrity:io("invalid",[Bn.BUNDLE_SCHEMA_INVALID]),checkpointIntegrity:io("indeterminate",[Bn.CHECKPOINT_MISSING]),anchorIntegrity:io("indeterminate",[Bn.OBSERVER_EVIDENCE_MISSING]),scopeEvidenceCompleteness:io("invalid",[Bn.BUNDLE_SCHEMA_INVALID]),authorizedAsObserved:io("indeterminate",[Bn.AUTHORIZATION_COLLATERAL_NOT_VERIFIED]),currentAuthorization:io("indeterminate",[Bn.CURRENT_AUTHORIZATION_NOT_EVALUATED])}}(t);const r=e,n=new Set,o=r.manifest.core;if(o?.schema===Yn&&"1.0.0"===o.formatVersion||n.add(Bn.BUNDLE_SCHEMA_INVALID),t.acceptedIntegritySuites.includes(o?.integritySuite??"")||n.add(Bn.UNSUPPORTED_SUITE),void 0!==o&&t.acceptedAlgorithms.includes(o.exporter.alg)||n.add(Bn.UNSUPPORTED_ALGORITHM),void 0!==o&&function(e,t){return t.authorizedExporters.some(t=>t.allowedPurposes.includes(e.purpose)&&e.selections.every(e=>t.allowedLedgerIds.includes(e.ledgerId))&&t.signerKeys.some(t=>{return i=t.signer,r=e.exporter,i.did===r.did&&i.kid===r.kid&&i.alg===r.alg&&to(t,e.exportedAt);var i,r}))}(o,t)||n.add(Bn.BUNDLE_EXPORTER_UNAUTHORIZED),void 0!==o){const[e,s]=await Promise.all([hn(i.hasher,gn.bundleManifest,o),hn(i.hasher,"org.kya-os.audit.verification-policy.v1",t)]);e!==r.manifest.manifestDigest&&n.add(Bn.BUNDLE_MANIFEST_DIGEST_MISMATCH),s!==o.verificationPolicyDigest&&n.add(Bn.VERIFICATION_POLICY_MISMATCH),await i.signatures.verify(L(o),r.manifest.jws,o.exporter)||n.add(Bn.BUNDLE_SIGNATURE_INVALID);const a=new Map(o.inventory.map(e=>[e.path,e])),c=new Map(r.components.map(e=>[e.path,e]));a.size===o.inventory.length&&c.size===r.components.length&&a.size===c.size||n.add(Bn.BUNDLE_INVENTORY_MISMATCH);for(const[e,t]of a){const r=c.get(e);if(void 0!==r&&P(t)===P(no(r))){try{eo(e)}catch{n.add(Bn.BUNDLE_SCHEMA_INVALID)}if("included"===r.disposition){if(void 0===r.content){n.add(Bn.BUNDLE_INVENTORY_MISMATCH);continue}const e=L(r.content);r.size===String(e.length)&&r.digest===await i.hasher.sha256(e)||n.add(Bn.BUNDLE_COMPONENT_DIGEST_MISMATCH)}else void 0===r.content&&void 0!==r.reasonCode||n.add(Bn.BUNDLE_INVENTORY_MISMATCH)}else n.add(Bn.BUNDLE_INVENTORY_MISMATCH)}}const s=oo(r,Xn.entries),a=oo(r,Xn.checkpoints),c=oo(r,Xn.observations),d=oo(r,Xn.anchors),u=i.artifacts??new Gn(i),l=await async function(e,t,i){const r=new Map,n=[];for(const t of e){if(!Rr.safeParse(t).success){n.push(t);continue}const e=t,i=so(e.core),o=r.get(i)??[];o.push(e),r.set(i,o)}const o=await Promise.all([...[...r.values()].map(e=>i.verifyEntries(e,t)),...0===n.length?[]:[i.verifyEntries(n,t)]]);return 0===o.length?i.verifyEntries([],t):{...o[0],cryptographicIntegrity:Jn(...o.map(e=>e.cryptographicIntegrity)),chainIntegrity:Jn(...o.map(e=>e.chainIntegrity)),checkpointIntegrity:Jn(...o.map(e=>e.checkpointIntegrity)),anchorIntegrity:Jn(...o.map(e=>e.anchorIntegrity)),scopeEvidenceCompleteness:Jn(...o.map(e=>e.scopeEvidenceCompleteness)),authorizedAsObserved:Jn(...o.map(e=>e.authorizedAsObserved)),currentAuthorization:Jn(...o.map(e=>e.currentAuthorization))}}(s,t,u),h=s.filter(e=>Rr.safeParse(e).success),p=a.filter(e=>Nr.safeParse(e).success);let f=l.checkpointIntegrity;if(a.length>0){const e=[];for(const i of a){if(!Nr.safeParse(i).success){e.push(io("invalid",[Bn.SCHEMA_INVALID]));continue}const r=i,n=h.filter(e=>e.core.ledgerId===r.core.ledgerId&&e.core.ledgerEpochId===r.core.ledgerEpochId&&BigInt(e.core.sequence)<BigInt(r.core.treeSize));e.push(await u.verifyCheckpoint(r,n,t))}f=Jn(...e,function(e,t,i){const r=new Set,n=new Map;for(const t of e){const e=so(t.core),i=n.get(e)??[];i.push(t),n.set(e,i)}for(const e of n.values()){e.sort((e,t)=>{const i=BigInt(e.core.treeSize),r=BigInt(t.core.treeSize);return i<r?-1:i>r?1:0});for(let t=1;t<e.length;t+=1){const i=e[t-1],n=e[t];n.core.treeSize===i.core.treeSize?r.add(Bn.CHECKPOINT_FORK_DETECTED):n.core.previousCheckpointDigest!==i.checkpointDigest&&r.add(Bn.CHECKPOINT_CHAIN_MISMATCH)}}for(const e of i){const t=(n.get(so(e))??[]).map(e=>e.core.treeSize).sort(ao),i=[...e.checkpointTreeSizes].sort(ao);P(t)!==P(i)&&r.add(Bn.CHECKPOINT_MISSING)}for(const n of t){if("0"!==n.core.sequence||"ledger.epoch.started"!==n.core.event.eventType||"ledger"!==n.core.event.details.family)continue;const t=n.core.event.details;void 0!==t.previousEpochId&&void 0!==t.previousTerminalCheckpointDigest&&i.some(e=>e.ledgerId===n.core.ledgerId&&e.ledgerEpochId===t.previousEpochId)&&!e.some(e=>e.core.ledgerId===n.core.ledgerId&&e.core.ledgerEpochId===t.previousEpochId&&e.checkpointDigest===t.previousTerminalCheckpointDigest)&&r.add(Bn.CHECKPOINT_CHAIN_MISMATCH)}return io(0===r.size?"valid":"invalid",r)}(p,h,o.selections),await async function(e,t,i,r){const n=new Set,o=new Rn(r),s=oo(e,Xn.inclusionProofs);for(const e of s){if(!Mr.safeParse(e).success){n.add(Bn.SCHEMA_INVALID);continue}const r=e,s=i.find(e=>e.checkpointDigest===r.checkpointDigest&&e.core.ledgerId===r.ledgerId&&e.core.ledgerEpochId===r.ledgerEpochId),a=t.find(e=>e.entryDigest===r.entryDigest&&e.core.sequence===r.sequence&&e.core.ledgerId===r.ledgerId&&e.core.ledgerEpochId===r.ledgerEpochId),c=Number(r.proof.leafIndex),d=Number(r.proof.treeSize);void 0!==s&&void 0!==a&&r.proof.treeSize===s.core.treeSize&&r.proof.leafIndex===r.sequence&&await o.verifyInclusion({leaf:r.entryDigest,leafIndex:c,treeSize:d,root:s.core.rootDigest,auditPath:r.proof.auditPath})||n.add(Bn.MERKLE_PROOF_INVALID)}const a=oo(e,Xn.consistencyProofs);for(const e of a){if(!zr.safeParse(e).success){n.add(Bn.SCHEMA_INVALID);continue}const t=e,r=i.find(e=>e.checkpointDigest===t.oldCheckpointDigest&&e.core.ledgerId===t.ledgerId&&e.core.ledgerEpochId===t.ledgerEpochId),s=i.find(e=>e.checkpointDigest===t.newCheckpointDigest&&e.core.ledgerId===t.ledgerId&&e.core.ledgerEpochId===t.ledgerEpochId);void 0!==r&&void 0!==s&&t.proof.oldTreeSize===r.core.treeSize&&t.proof.newTreeSize===s.core.treeSize&&await o.verifyConsistency({oldSize:Number(t.proof.oldTreeSize),newSize:Number(t.proof.newTreeSize),oldRoot:r.core.rootDigest,newRoot:s.core.rootDigest,auditPath:t.proof.auditPath})||n.add(Bn.MERKLE_PROOF_INVALID)}return io(0===n.size?"valid":"invalid",n)}(r,h,p,i.hasher))}else o.selections.some(e=>e.checkpointTreeSizes.length>0)&&(f=io("invalid",[Bn.CHECKPOINT_MISSING]));let g=l.anchorIntegrity;if(c.length>0){const e=[];for(const i of c){if(!Or.safeParse(i).success){e.push(io("invalid",[Bn.SCHEMA_INVALID]));continue}const r=i,n=p.find(e=>e.checkpointDigest===r.core.checkpointDigest);e.push(void 0===n?io("invalid",[Bn.OBSERVATION_SCOPE_MISMATCH]):await u.verifyObservation(n,r,t))}const i=c.filter(e=>Or.safeParse(e).success);g=Jn(...e,function(e){const t=new Set,i=new Map;for(const t of e){const e=`${so(t.core)}\0${t.core.observerId}`,r=i.get(e)??[];r.push(t),i.set(e,r)}for(const e of i.values()){e.sort((e,t)=>e.core.observedAt-t.core.observedAt||ao(e.core.treeSize,t.core.treeSize));for(let i=1;i<e.length;i+=1)e[i].core.previousObservationDigest!==e[i-1].observationDigest&&t.add(Bn.OBSERVATION_CHAIN_MISMATCH)}return io(0===t.size?"valid":"invalid",t)}(i))}d.length>0&&(g=Jn(g,await async function(e,t,i,r){const n=new Set;let o=!1;for(const s of e){if(!Pr.safeParse(s).success){n.add(Bn.SCHEMA_INVALID);continue}const e=s,a=t.find(t=>t.checkpointDigest===e.checkpointDigest);(i.trustedSupportingAnchors?.some(t=>t.kind===e.kind&&t.providerId===e.providerId&&to(t,e.issuedAt))??!1)||n.add(Bn.UNTRUSTED_SUPPORTING_ANCHOR),void 0===a?n.add(Bn.SUPPORTING_ANCHOR_INVALID):void 0===r?(n.add(Bn.NOT_EVALUATED),o=!0):await r(a,e)||n.add(Bn.SUPPORTING_ANCHOR_INVALID)}return io([...n].some(e=>e!==Bn.NOT_EVALUATED)?"invalid":o?"indeterminate":"valid",n)}(d,p,t,i.verifySupportingAnchor)));const y=io(0===n.size?"valid":"invalid",n);return{...l,cryptographicIntegrity:Jn(y,l.cryptographicIntegrity),checkpointIntegrity:f,anchorIntegrity:g,scopeEvidenceCompleteness:co(o?.selections??[],h,r.components.filter(e=>"included"!==e.disposition))}}class lo{configuration;idCounter=0n;sourceState;sourceConstructionTail=Promise.resolve();get auditProfile(){return this.configuration.capabilities?.profile??"AAP-0"}get capabilities(){return this.configuration.capabilities}constructor(e){if("buffered"===e.delivery&&"durable"!==e.outbox?.capabilities.durability)throw new Sn(wn.INVALID_CONFIGURATION,"Buffered audit delivery requires a durable outbox provider");if(void 0!==e.capabilities){if(e.capabilities.delivery!==e.delivery)throw new Sn(wn.INVALID_CONFIGURATION,"Advertised audit delivery does not match the trail delivery mode");if(sn(e.capabilities),e.capabilities.sourceHighWater&&"durable"!==e.sourceState.capabilities.durability)throw new Sn(wn.INVALID_CONFIGURATION,"Advertised source high-water support requires durable source state")}this.configuration=Object.freeze({...e}),this.sourceState=e.sourceState}async record(e,t={}){const i=e.eventId??this.nextEventId(),r=t.encryptedEvidence??[],n="buffered"===this.configuration.delivery,{event:o,submission:s}=await this.withSourceConstruction(async()=>{const t=await this.buildAndLinkEvent(e,i);this.assertEvidenceIsReferenced(t,r);const o=Object.freeze({ledgerId:this.configuration.ledgerId,...n||void 0===this.configuration.expectedLedgerEpochId?{}:{expectedLedgerEpochId:this.configuration.expectedLedgerEpochId},producerEvent:t,encryptedEvidence:Object.freeze([...r])});return n&&await this.configuration.outbox.enqueue(Object.freeze({eventId:t.eventId,submission:o,enqueuedAt:this.configuration.clock.now(),attempts:0})),{event:t,submission:o}});if(n)return{status:"pending",event:o};let a;try{a=await this.submitAndValidate(s)}catch(e){if(this.configuration.onDeliveryFailure?.(e,o),"required"===this.configuration.delivery)throw e;return{status:"failed",event:o,error:e}}try{await this.sourceState.markReceipted(this.configuration.sourceId,o.source.sourceSequence,a.entryDigest)}catch(e){this.configuration.onSourceStateFailure?.(e,o)}return{status:"recorded",event:o,entry:a}}async flush(e){if("buffered"!==this.configuration.delivery)return{delivered:0,failed:0};let t=0,i=0;const r=new Set;for await(const n of this.configuration.outbox.pending(e)){const e=n.submission.producerEvent.source.sourceId;if(!r.has(e))try{const i=await this.submitAndValidate(n.submission);try{await this.sourceState.markReceipted(e,n.submission.producerEvent.source.sourceSequence,i.entryDigest)}catch(e){this.configuration.onSourceStateFailure?.(e,n.submission.producerEvent)}await this.configuration.outbox.markDelivered(n.eventId),t+=1}catch(t){await this.configuration.outbox.markFailed(n.eventId,t),this.configuration.onDeliveryFailure?.(t,n.submission.producerEvent),r.add(e),i+=1}}return{delivered:t,failed:i}}async getSourceState(){return this.sourceState.getState(this.configuration.sourceId)}async recordSourceHighWater(e={}){const t=await this.getSourceState();return this.record({...void 0===e.eventId?{}:{eventId:e.eventId},eventType:"audit.source_high_water",action:{category:"audit.source_high_water"},outcome:"succeeded",evidence:[],details:{family:"administration",phase:"source_high_water",sourceSequence:t.highestEmitted}})}async withSourceConstruction(e){const t=this.sourceConstructionTail;let i;this.sourceConstructionTail=new Promise(e=>{i=e}),await t;try{return await e()}finally{i()}}async buildAndLinkEvent(e,t){const i=await this.sourceState.claimEvent(this.configuration.sourceId,t),r=this.buildEvent(e,t,i),n=await vn(this.configuration.hasher,r);return await this.sourceState.markEmitted(this.configuration.sourceId,t,i.sequence,n),r}buildEvent(e,t,i){return Gr({...e,schema:"https://schema.kya-os.org/v1/protocol/audit/event/v1.0.0",eventId:t,eventVersion:"1.0.0",binding:this.configuration.binding,occurredAt:e.occurredAt??this.configuration.clock.now(),tenantRef:this.configuration.tenantRef,source:{producer:this.configuration.producer,sourceId:this.configuration.sourceId,sourceSequence:i.sequence,...void 0===i.previousSourceEventDigest?{}:{previousSourceEventDigest:i.previousSourceEventDigest}},privacy:e.privacy??this.configuration.privacy})}nextEventId(){return void 0!==this.configuration.eventIdFactory?this.configuration.eventIdFactory():(this.idCounter+=1n,`audit_${this.configuration.clock.now()}_${this.idCounter}`)}assertEvidenceIsReferenced(e,t){const i=new Map(fn(e).map(e=>[e.objectId,e])),r=new Set;for(const e of t){const t=i.get(e.ref.objectId);if(r.has(e.ref.objectId)||void 0===t||P(t)!==P(e.ref))throw new Sn(wn.EVIDENCE_FAILURE,"Encrypted evidence must exactly match one unique reference in the frozen event",{objectId:e.ref.objectId});r.add(e.ref.objectId)}}async submitAndValidate(e){const t=await this.configuration.recorder.submit(e),i=await vn(this.configuration.hasher,e.producerEvent);if(t.core.ledgerId!==e.ledgerId||t.eventDigest!==i||t.core.eventDigest!==i||P(t.core.event)!==P(e.producerEvent))throw new Sn(wn.JOURNAL_FAILURE,"Recorder response does not bind the submitted frozen producer event");return t}}function ho(e){return new lo(e)}class po{options;constructor(e){this.options=e}async ingest(e){if(e.core.ledgerId!==this.options.ledger.ledgerId||e.core.ledgerEpochId!==this.options.ledger.ledgerEpochId)throw new Sn(wn.LEDGER_MISMATCH,"Mirror entry belongs to a different ledger epoch");const t=await this.options.verifier.verifyEntries([e],this.options.verificationPolicy);if("valid"!==t.cryptographicIntegrity.verdict)throw new Sn(wn.MIRROR_VERIFICATION_FAILED,"Mirror rejected an entry that failed historical artifact verification",{reasonCodes:t.cryptographicIntegrity.reasonCodes});const i=await hn(this.options.hasher,"org.kya-os.audit.mirror-idempotency.v1",{ledgerId:e.core.ledgerId,entryDigest:e.entryDigest}),r=await this.options.journal.getByIdempotencyKey(e.core.ledgerId,i);if(null!==r)return r.entryDigest!==e.entryDigest&&this.continuityFailure(),r;const n=await this.options.journal.getHead(this.options.ledger),o=BigInt(e.core.sequence);if(null===n&&o>0n||null!==n&&o>BigInt(n.sequence)+1n)throw new Sn(wn.MIRROR_OUT_OF_ORDER,"Mirror entry arrived before its predecessor and may be retried",{sequence:e.core.sequence,observedHeadSequence:n?.sequence??null});(null===n?"0"===e.core.sequence&&null===e.core.previousEntryDigest:o===BigInt(n.sequence)+1n&&e.core.previousEntryDigest===n.entryDigest)||this.continuityFailure();const s=await this.options.journal.compareAndAppend({ledger:this.options.ledger,expectedHead:n,entry:e,idempotencyKey:i});if("appended"===s.kind||"duplicate"===s.kind)return s.entry;const a=await this.options.journal.getByIdempotencyKey(e.core.ledgerId,i);if(a?.entryDigest===e.entryDigest)return a;this.continuityFailure()}continuityFailure(){throw new Sn(wn.MIRROR_CONTINUITY_FAILED,"Mirror entry does not exactly extend the observed recorder chain")}}function fo(e){if("object"!=typeof e||null===e||Object.isFrozen(e))return e;for(const t of Object.values(e))fo(t);return Object.freeze(e)}function go(e,t){return null===e||null===t?e===t:e.entryDigest===t.entryDigest&&e.sequence===t.sequence}function yo(e,t){return P(e)===P(t)}function mo(e,t,i){return void 0!==t?yo(t,i):("public_did"===i.kind||"pairwise_did"===i.kind)&&i.did===e}class vo{config;maxAppendConflicts;initialization;constructor(e){if(this.config=e,void 0===e.previousEpochId!=(void 0===e.previousTerminalCheckpointDigest))throw new Sn(wn.INVALID_CONFIGURATION,"Previous epoch ID and terminal checkpoint digest must be supplied together");if(void 0!==e.previousEpochId&&void 0===e.epochTransitionGuard)throw new Sn(wn.INVALID_CONFIGURATION,"Epoch transitions require an authoritative verify-and-seal guard");this.maxAppendConflicts=e.maxAppendConflicts??256}async submitAuthenticated(e,t){this.validateSubmissionEnvelope(e,t);const i=Gr(e.producerEvent);if(this.validateEventAuthority(i,t),void 0!==this.config.authorizer&&!await this.config.authorizer.authorize({submission:e,context:t}))throw new Sn(wn.UNAUTHORIZED_SUBMISSION,"Audit producer is not authorized for this ledger");const r=await this.identifyEvent(i,t),n=await this.config.journal.getByIdempotencyKey(this.config.ledgerId,r.idempotencyKey);if(null!==n)return this.resolveDuplicate(n,r.eventDigest);if(void 0!==e.expectedLedgerEpochId&&e.expectedLedgerEpochId!==this.config.ledgerEpochId)throw new Sn(wn.EPOCH_MISMATCH,"Wrong audit ledger epoch");await this.ensureInitialized(),await this.persistSubmittedEvidence(e.encryptedEvidence,i);try{return await this.appendEvent(i,t,!1,r)}catch(t){throw await this.disposeUncommittedEvidence(e.encryptedEvidence,r),t}}async disposeUncommittedEvidence(e,t){if(0!==e.length&&void 0!==this.config.evidence)try{if(null!==await this.config.journal.getByIdempotencyKey(this.config.ledgerId,t.idempotencyKey))return;for(const t of e)await this.config.evidence.applyRetention({kind:"dispose",ref:t.ref,authorizedBy:"audit-recorder",reason:"append_failed_uncommitted"})}catch{}}validateSubmissionEnvelope(e,t){if(!t.producerAuthority||!t.tenantAuthority)throw new Sn(wn.UNAUTHORIZED_SUBMISSION,"Authenticated producer and tenant authority are required");if(e.ledgerId!==this.config.ledgerId)throw new Sn(wn.LEDGER_MISMATCH,"Wrong audit ledger")}validateEventAuthority(e,t){if(!mo(t.producerAuthority,t.producerRef,e.source.producer))throw new Sn(wn.UNAUTHORIZED_SUBMISSION,"Event producer does not match the authenticated producer authority");if(!yo(e.tenantRef,this.config.tenantRef)||!mo(t.tenantAuthority,t.tenantRef,e.tenantRef))throw new Sn(wn.UNAUTHORIZED_SUBMISSION,"Event tenant does not match the authenticated tenant authority")}async persistSubmittedEvidence(e,t){if(0!==e.length){if(void 0===this.config.evidence)throw new Sn(wn.EVIDENCE_FAILURE,"Encrypted evidence was submitted but no evidence provider is configured");try{const i=new Map(fn(t).map(e=>[e.objectId,e])),r=new Set;for(const t of e){const e=i.get(t.ref.objectId);if(r.has(t.ref.objectId)||void 0===e||P(e)!==P(t.ref))throw new Sn(wn.EVIDENCE_FAILURE,"Submitted evidence does not exactly match a unique frozen event reference",{objectId:t.ref.objectId});r.add(t.ref.objectId),await this.config.evidence.putIfAbsent(t)}}catch(e){if(e instanceof Sn&&e.code===wn.EVIDENCE_FAILURE)throw e;throw new Sn(wn.EVIDENCE_FAILURE,"Required evidence could not be persisted",void 0,{cause:e})}}}async ensureInitialized(){const e=this.ledgerRef();if(null!==await this.config.journal.getHead(e)){const t=this.config.journal.readRange({...e,limit:1});for await(const e of t)return this.validateExistingGenesis(e);throw new Sn(wn.JOURNAL_FAILURE,"Ledger head exists without genesis")}if(void 0!==this.config.previousEpochId&&!await this.config.epochTransitionGuard.verifyAndSeal({ledgerId:this.config.ledgerId,previousEpochId:this.config.previousEpochId,nextEpochId:this.config.ledgerEpochId,previousTerminalCheckpointDigest:this.config.previousTerminalCheckpointDigest}))throw new Sn(wn.INVALID_CONFIGURATION,"Predecessor checkpoint could not be verified and sealed");return this.initialization??=this.appendEvent(this.genesisEvent(),{producerAuthority:this.config.signer.ref.did,tenantAuthority:"audit-recorder",producerRef:{kind:"public_did",did:this.config.signer.ref.did},tenantRef:this.config.tenantRef},!0).finally(()=>{this.initialization=void 0}),this.initialization}validateExistingGenesis(e){try{const r=Yr(e),n=r.core.event.details;if("0"!==r.core.sequence||null!==r.core.previousEntryDigest||r.core.ledgerId!==this.config.ledgerId||r.core.ledgerEpochId!==this.config.ledgerEpochId||(t=r.core.recorder,i=this.config.signer.ref,t.did!==i.did||t.kid!==i.kid||t.alg!==i.alg)||"ledger.epoch.started"!==r.core.event.eventType||r.core.event.binding!==this.config.binding||r.core.event.source.sourceId!==this.config.sourceId||"public_did"!==r.core.event.source.producer.kind||r.core.event.source.producer.did!==this.config.signer.ref.did||!yo(r.core.event.tenantRef,this.config.tenantRef)||"ledger"!==n.family||"epoch_started"!==n.phase||n.previousEpochId!==this.config.previousEpochId||n.previousTerminalCheckpointDigest!==this.config.previousTerminalCheckpointDigest)throw new Error("Genesis does not match recorder epoch configuration");return r}catch(e){throw new Sn(wn.JOURNAL_FAILURE,"Existing ledger genesis does not match the authoritative recorder configuration",void 0,{cause:e})}var t,i}genesisEvent(){return Gr({schema:ar,eventId:`genesis:${this.config.ledgerId}:${this.config.ledgerEpochId}`,eventType:"ledger.epoch.started",eventVersion:"1.0.0",binding:this.config.binding,occurredAt:this.config.clock.now(),tenantRef:this.config.tenantRef,source:{producer:{kind:"public_did",did:this.config.signer.ref.did},sourceId:this.config.sourceId,sourceSequence:"0"},resource:{kind:"public_did",did:this.config.signer.ref.did},action:{category:"ledger.epoch"},outcome:"succeeded",evidence:[],details:{family:"ledger",phase:"epoch_started",...this.config.previousEpochId?{previousEpochId:this.config.previousEpochId,previousTerminalCheckpointDigest:this.config.previousTerminalCheckpointDigest}:{}},privacy:{classification:"internal",retentionClass:"integrity-ledger"}})}async appendEvent(e,t,i=!1,r){const{eventDigest:n,idempotencyKey:o}=r??await this.identifyEvent(e,t),s=await this.config.journal.getByIdempotencyKey(this.config.ledgerId,o);if(null!==s)return i?this.validateExistingGenesis(s):this.resolveDuplicate(s,n);const a=this.ledgerRef();for(let t=0;t<=this.maxAppendConflicts;t+=1){const t=await this.config.journal.getHead(a);if(i&&null!==t){const e=await this.config.journal.getByIdempotencyKey(this.config.ledgerId,o);if(null!==e)return this.validateExistingGenesis(e)}const r=await this.buildCandidate(e,n,t,i);let s;try{s=await this.config.journal.compareAndAppend({ledger:a,expectedHead:t,entry:r,idempotencyKey:o})}catch(e){throw new Sn(wn.JOURNAL_FAILURE,"Audit journal append failed",void 0,{cause:e})}if("appended"===s.kind||"duplicate"===s.kind)return"duplicate"===s.kind?this.resolveDuplicate(s.entry,n):s.entry;if("idempotency_conflict"===s.kind)return this.resolveDuplicate(s.existing,n);if(go(t,s.actualHead))throw new Sn(wn.JOURNAL_FAILURE,"Audit journal reported a head conflict without advancing its head")}throw new Sn(wn.APPEND_CONFLICT_EXHAUSTED,"Audit append conflict retry budget exhausted")}async identifyEvent(e,t){return{eventDigest:await vn(this.config.hasher,e),idempotencyKey:await hn(this.config.hasher,gn.idempotency,{ledgerId:this.config.ledgerId,producerAuthority:t.producerAuthority,sourceId:e.source.sourceId,eventId:e.eventId})}}resolveDuplicate(e,t){if(e.eventDigest!==t)throw new Sn(wn.EVENT_ID_CONFLICT,"Authenticated producer event identity was reused with different content",{eventId:e.core.event.eventId});return e}async buildCandidate(e,t,i,r){const n=null===i?"0":(BigInt(i.sequence)+1n).toString();if(r!==("0"===n))throw new Sn(wn.JOURNAL_FAILURE,r?"Genesis must be the first epoch entry":"Producer event cannot replace genesis");const o=this.config.clock.now(),s=await En(this.config.hasher,e),a=Jr({schema:cr,ledgerId:this.config.ledgerId,ledgerEpochId:this.config.ledgerEpochId,sequence:n,previousEntryDigest:i?.entryDigest??null,recordedAt:o,recorder:this.config.signer.ref,eventDigest:t,event:e,evidenceManifestDigest:s,integritySuite:ur}),c=await In(this.config.hasher,a),d=mn(a,c);return fo({core:a,eventDigest:t,entryDigest:c,recorderReceipt:{core:d,jws:await this.config.signer.sign(L(d))}})}ledgerRef(){return{ledgerId:this.config.ledgerId,ledgerEpochId:this.config.ledgerEpochId}}}function Io(e){return`${e.ledgerId}\0${e.ledgerEpochId}`}function Eo(e,t){return`${e}\0${t}`}class wo{capabilities={durability:"ephemeral",atomicAppend:!0,orderedRead:!0};entriesByLedger=new Map;entriesByIdempotency=new Map;heads=new Map;async getHead(e){return this.heads.get(Io(e))??null}async getByIdempotencyKey(e,t){return this.entriesByIdempotency.get(Eo(e,t))??null}async compareAndAppend(e){const t=Eo(e.ledger.ledgerId,e.idempotencyKey),i=this.entriesByIdempotency.get(t);if(void 0!==i)return i.eventDigest===e.entry.eventDigest?{kind:"duplicate",entry:i}:{kind:"idempotency_conflict",existing:i};const r=Io(e.ledger),n=this.heads.get(r)??null;if(s=n,!(null===(o=e.expectedHead)||null===s?o===s:o.ledgerId===s.ledgerId&&o.ledgerEpochId===s.ledgerEpochId&&o.sequence===s.sequence&&o.entryDigest===s.entryDigest))return{kind:"head_conflict",actualHead:n};var o,s;const a=this.entriesByLedger.get(r)??[];return a.push(e.entry),this.entriesByLedger.set(r,a),this.entriesByIdempotency.set(t,e.entry),this.heads.set(r,{ledgerId:e.ledger.ledgerId,ledgerEpochId:e.ledger.ledgerEpochId,sequence:e.entry.core.sequence,entryDigest:e.entry.entryDigest}),{kind:"appended",entry:e.entry}}async*readRange(e){const t=await this.snapshot(e),i=void 0===e.afterSequence?null:BigInt(e.afterSequence);let r=0;for(const n of t)if(!(null!==i&&BigInt(n.core.sequence)<=i)){if(void 0!==e.limit&&r>=e.limit)return;r+=1,yield n}}async snapshot(e){return[...this.entriesByLedger.get(Io(e))??[]]}}class So{recorder;context;constructor(e,t){this.recorder=e,this.context=t}async submit(e){return this.recorder.submitAuthenticated(e,await this.context())}}function Do(e,t){return new So(new vo(e),t)}function Ao(e){return`${e.ledgerId}\0${e.ledgerEpochId}`}class bo{config;capability="independent-observer";observations=new Map;publicationTails=new Map;constructor(e){this.config=e}async publish(e){const t=Ao({ledgerId:e.core.ledgerId,ledgerEpochId:e.core.ledgerEpochId}),i=this.publicationTails.get(t)??Promise.resolve();let r;const n=new Promise(e=>{r=e}),o=i.then(()=>n);this.publicationTails.set(t,o),await i;try{return await this.publishSerialized(e)}finally{r(),this.publicationTails.get(t)===o&&this.publicationTails.delete(t)}}async publishSerialized(e){if(!await this.config.verifyCheckpoint(e))throw new Sn(wn.CHECKPOINT_INVALID,"Observer rejected an invalid checkpoint");const t={ledgerId:e.core.ledgerId,ledgerEpochId:e.core.ledgerEpochId},i=this.observations.get(Ao(t));if(void 0!==i){const t=BigInt(i.checkpoint.core.treeSize),r=BigInt(e.core.treeSize);if(r<t)throw new Sn(wn.CHECKPOINT_ROLLBACK,"Observed checkpoint tree size moved backwards");if(r===t){if(e.core.rootDigest!==i.checkpoint.core.rootDigest||e.checkpointDigest!==i.checkpoint.checkpointDigest)throw new Sn(wn.CHECKPOINT_CONFLICT,"Conflicting checkpoint roots were observed at the same tree size");return i.receipt}if(!await this.config.verifyConsistency(i.checkpoint,e))throw new Sn(wn.CHECKPOINT_CONFLICT,"Checkpoint does not consistently extend the previously observed tree")}const r={schema:"https://schema.kya-os.org/v1/protocol/audit/observation/v1.0.0",observerId:this.config.observerId,observer:this.config.signer.ref,ledgerId:e.core.ledgerId,ledgerEpochId:e.core.ledgerEpochId,checkpointDigest:e.checkpointDigest,treeSize:e.core.treeSize,observedAt:this.config.clock.now(),previousObservationDigest:i?.receipt.observationDigest??null},n=await hn(this.config.hasher,gn.observation,r),o=Object.freeze({core:Object.freeze(r),observationDigest:n,jws:await this.config.signer.sign(L(r))});return this.observations.set(Ao(t),{checkpoint:e,receipt:o}),o}async latest(e){return this.observations.get(Ao(e))??null}async verifyObservation(e,t){const i=await this.latest({ledgerId:e.core.ledgerId,ledgerEpochId:e.core.ledgerEpochId});return i?.checkpoint.checkpointDigest===e.checkpointDigest&&i.receipt.observationDigest===t.observationDigest}}class _o{config;capability="supporting-anchor";kind;constructor(e){this.config=e,this.kind=e.kind}async publish(e){return Object.freeze({schema:"https://schema.kya-os.org/v1/protocol/audit/anchor-receipt/v1.0.0",kind:this.config.kind,providerId:this.config.providerId,checkpointDigest:e.checkpointDigest,issuedAt:this.config.clock.now()})}async verify(e,t){return t.kind===this.config.kind&&t.providerId===this.config.providerId&&t.checkpointDigest===e.checkpointDigest}}class Co{capabilities={durability:"ephemeral",fifoPerSource:!0};items=new Map;async enqueue(e){const t=this.items.get(e.eventId);var i,r;if(void 0===t)this.items.set(e.eventId,e);else if(i=t.submission,r=e.submission,i.ledgerId!==r.ledgerId||i.expectedLedgerEpochId!==r.expectedLedgerEpochId||P(i.producerEvent)!==P(r.producerEvent)||i.encryptedEvidence.length!==r.encryptedEvidence.length||!i.encryptedEvidence.every((e,t)=>{const i=r.encryptedEvidence[t];if(void 0===i||P(e.ref)!==P(i.ref)||e.ciphertext.byteLength!==i.ciphertext.byteLength)return!1;let n=0;for(let t=0;t<e.ciphertext.byteLength;t+=1)n|=e.ciphertext[t]^i.ciphertext[t];return 0===n}))throw new Error(`Audit outbox event identity collision: ${e.eventId}`)}async*pending(e=Number.MAX_SAFE_INTEGER){let t=0;for(const i of[...this.items.values()]){if(t>=e)return;t+=1,yield i}}async markDelivered(e){this.items.delete(e)}async markFailed(e){const t=this.items.get(e);void 0!==t&&this.items.set(e,{...t,attempts:t.attempts+1})}}class To{capabilities={durability:"ephemeral",atomicClaim:!0};states=new Map;async claimEvent(e,t){const i=this.state(e),r=i.claims.get(t);if(void 0!==r)return{sequence:r.sequence.toString(),...void 0===r.previousSourceEventDigest?{}:{previousSourceEventDigest:r.previousSourceEventDigest}};i.next+=1n;const n=i.eventDigests.get(i.next-1n),o={sequence:i.next,...void 0===n?{}:{previousSourceEventDigest:n}};return i.claims.set(t,o),{sequence:o.sequence.toString(),...void 0===o.previousSourceEventDigest?{}:{previousSourceEventDigest:o.previousSourceEventDigest}}}async markEmitted(e,t,i,r){const n=this.state(e),o=BigInt(i),s=n.claims.get(t);if(s?.sequence!==o)throw new RangeError("Unknown source event claim");const a=n.eventDigests.get(o);if(void 0!==a&&a!==r)throw new Error(`Source event identity collision: ${t}`);n.eventDigests.set(o,r)}async markReceipted(e,t){const i=BigInt(t),r=this.state(e);if(i<1n||i>r.next)throw new RangeError("Unknown source sequence");if(!(i<=r.receiptedWatermark)){for(r.receipted.add(i);r.receipted.delete(r.receiptedWatermark+1n);)r.receiptedWatermark+=1n;for(const[e,t]of r.claims)t.sequence<r.receiptedWatermark&&r.claims.delete(e);for(const e of r.eventDigests.keys())e<r.receiptedWatermark&&r.eventDigests.delete(e)}}async getState(e){const t=this.state(e),i=[];for(let e=t.receiptedWatermark+1n;e<=t.next;e+=1n)t.receipted.has(e)||i.push(e.toString());return{sourceId:e,highestEmitted:t.next.toString(),highestReceipted:t.receiptedWatermark.toString(),pendingSequences:i}}state(e){const t=this.states.get(e);if(void 0!==t)return t;const i={next:0n,receiptedWatermark:0n,receipted:new Set,claims:new Map,eventDigests:new Map};return this.states.set(e,i),i}}class ko extends ir{trail;options;capability="legacy-capture";constructor(e,t={}){super(),this.trail=e,this.options=t}async logAuditRecord(e){const t="yes"===e.verified;await this.trail.record({eventType:t?"proof.verified":"proof.rejected",actor:{kind:this.options.identityKind??"public_did",did:e.identity.did},resource:{kind:this.options.resourceKind??"public_did",did:e.session.audience},action:{category:"legacy.audit-record"},outcome:t?"succeeded":"failed",...t?{}:{reason:{code:"LEGACY_VERIFICATION_FAILED"}},...void 0===e.scopeId?{}:{authorization:{source:"policy",decision:t?"allowed":"denied",scopeId:e.scopeId}},evidence:[],details:{family:"proof",phase:t?"verified":"rejected",verificationCode:t?"LEGACY_VERIFIED_CLAIM":"LEGACY_REJECTED_CLAIM"}})}async logEvent(e){const t={eventType:"configuration.changed",actor:{kind:this.options.identityKind??"public_did",did:e.identity.did},resource:{kind:this.options.resourceKind??"public_did",did:e.session.audience},action:{category:"legacy.event"},outcome:"unknown",reason:{code:"LEGACY_EVENT_CAPTURE"},evidence:[],details:{family:"key",phase:"configuration_changed"}};await this.trail.record(t)}}function No(e,t=256){return e.slice(0,t)}class Ro{trail;options;constructor(e,t={}){this.trail=e,this.options=t}async session(e,t){await this.trail.record({eventType:`session.${e}`,...this.context(t.context),action:{category:"session"},outcome:t.succeeded?"succeeded":"failed",...void 0===t.reasonCode?{}:{reason:{code:t.reasonCode}},evidence:[],details:{family:"session",phase:e,...void 0===t.reasonCode?{}:{reasonCode:t.reasonCode}}})}async tool(e,t){await this.trail.record({eventType:`tool.call.${e}`,...this.context(t.context),action:{category:"tool.call",...this.options.includeToolNames?{name:No(t.toolName)}:{}},outcome:t.outcome,...void 0===t.reasonCode?{}:{reason:{code:t.reasonCode}},evidence:[],details:{family:"tool",phase:e,attempt:t.attempt??"1"}})}async proof(e,t){await this.trail.record({eventType:`proof.${e}`,...this.context(t.context),action:{category:"proof"},outcome:t.outcome,evidence:[],details:{family:"proof",phase:e,...void 0===t.proofDigest?{}:{proofDigest:t.proofDigest},...void 0===t.verificationCode?{}:{verificationCode:t.verificationCode}}})}async authorization(e,t){const i="grant_used"===e?"grant.used":`authorization.${e}`;await this.trail.record({eventType:i,...this.context(t.context),action:{category:"authorization"},outcome:t.outcome,...void 0===t.reasonCode?{}:{reason:{code:t.reasonCode}},evidence:[],details:{family:"authorization",phase:e,...void 0===t.policyDigest?{}:{policyDigest:t.policyDigest},...void 0===t.grantRef?{}:{grantRef:No(t.grantRef)}}})}async delegation(e,t){await this.trail.record({eventType:`delegation.${e}`,...this.context(t.context),action:{category:"delegation"},outcome:t.outcome,...void 0===t.reasonCode?{}:{reason:{code:t.reasonCode}},evidence:[],details:{family:"delegation",phase:e,delegationRef:No(t.delegationRef),...void 0===t.parentRef?{}:{parentRef:No(t.parentRef)}}})}async consent(e,t){const i=e.startsWith("credential_")?`credential.${e.slice(11)}`:`consent.${e}`;await this.trail.record({eventType:i,...this.context(t.context),action:{category:"consent"},outcome:t.outcome,...void 0===t.reasonCode?{}:{reason:{code:t.reasonCode}},evidence:[],details:{family:"consent",phase:e,...void 0===t.consentRef?{}:{consentRef:No(t.consentRef)}}})}async key(e,t){await this.trail.record({eventType:{rotated:"key.rotated",policy_changed:"policy.changed",configuration_changed:"configuration.changed",integrity_suite_transitioned:"integrity_suite.transitioned"}[e],...this.context(t.context),action:{category:"configuration"},outcome:t.outcome,...void 0===t.reasonCode?{}:{reason:{code:t.reasonCode}},evidence:[],details:{family:"key",phase:e,...void 0===t.previousSigner?{}:{previousSigner:t.previousSigner},...void 0===t.nextSigner?{}:{nextSigner:t.nextSigner},...void 0===t.configurationDigest?{}:{configurationDigest:t.configurationDigest}}})}async ledger(e,t){await this.trail.record({eventType:{epoch_started:"ledger.epoch.started",epoch_transitioned:"ledger.epoch.transitioned",checkpoint_created:"checkpoint.created",checkpoint_anchored:"checkpoint.anchored",checkpoint_anchor_failed:"checkpoint.anchor_failed",evidence_disposed:"evidence.disposed",projection_reconciled:"projection.reconciled"}[e],...this.context(t.context),action:{category:"audit.ledger"},outcome:t.outcome,...void 0===t.reasonCode?{}:{reason:{code:t.reasonCode}},evidence:[],details:{family:"ledger",phase:e,...void 0===t.checkpointDigest?{}:{checkpointDigest:t.checkpointDigest},...void 0===t.previousEpochId?{}:{previousEpochId:t.previousEpochId},...void 0===t.previousTerminalCheckpointDigest?{}:{previousTerminalCheckpointDigest:t.previousTerminalCheckpointDigest},...void 0===t.successorEpochIds?{}:{successorEpochIds:t.successorEpochIds}}})}async administration(e,t){await this.trail.record({eventType:{source_high_water:"audit.source_high_water",accessed:"audit.accessed",exported:"audit.exported",legal_hold_applied:"legal_hold.applied",retention_executed:"retention.executed"}[e],...this.context(t.context),action:{category:"audit.administration"},outcome:t.outcome,...void 0===t.reasonCode?{}:{reason:{code:t.reasonCode}},evidence:[],details:{family:"administration",phase:e,...void 0===t.purpose?{}:{purpose:t.purpose},...void 0===t.sourceSequence?{}:{sourceSequence:t.sourceSequence},...void 0===t.selectionDigest?{}:{selectionDigest:t.selectionDigest}}})}context(e){return void 0===e?{}:{...void 0===e.actor?{}:{actor:e.actor},...void 0===e.responsibleParty?{}:{responsibleParty:e.responsibleParty},...void 0===e.authorization?{}:{authorization:e.authorization},...void 0===e.correlationId?{}:{correlationId:e.correlationId},...void 0===e.causationId?{}:{causationId:e.causationId}}}}class Oo{}class Po extends Oo{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(i=>i.agentDid===e&&this.coversScopes(i,t))}async getBySession(e,t){return this.activeGrants().filter(i=>i.sessionId===e&&this.coversScopes(i,t))}async getById(e){const t=this.grants.get(e);return t?{...t}:void 0}async revoke(e,t){const i=this.grants.get(e);i&&(i.status="revoked",void 0!==t&&(i.revocationReason=t))}async cleanup(){const e=this.now();for(const[t,i]of this.grants)void 0!==i.expiresAt&&i.expiresAt<=e&&this.grants.delete(t)}activeGrants(){const e=this.now(),t=[];for(const i of this.grants.values())"revoked"!==i.status&&(void 0!==i.expiresAt&&i.expiresAt<=e||t.push({...i}));return t}coversScopes(e,t){return!t||0===t.length||t.every(t=>e.scopes.includes(t))}}class Lo{}class xo extends Lo{pending=new Map;now;constructor(e={}){super(),this.now=e.now??(()=>Date.now())}async put(e,t,i){this.pending.set(e,{flow:{...t},expiresAt:this.now()+i})}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,i]of this.pending)i.expiresAt<=e&&this.pending.delete(t)}}function Mo(e){const t=new Set;for(const i of e.credentialSubject.delegation.scopes??[])t.add(i);for(const i of e.credentialSubject.delegation.constraints?.scopes??[])t.add(i);return Array.from(t)}function zo(e,t){const i=Mo(e),r=Mo(t),n=t.credentialSubject.delegation,o=e=>`${e.matcher}\0${e.resource}`,s=new Set((e.credentialSubject.delegation.constraints.crisp?.scopes??[]).map(o)),a=(n.constraints.crisp?.scopes??[]).filter(e=>!s.has(o(e)));if(a.length>0)return{valid:!1,reason:`Delegation ${n.id} introduces crisp scope matcher(s) absent from parent ${e.credentialSubject.delegation.id}: ${a.map(e=>`${e.matcher}:${e.resource}`).join(", ")}`};if(0===i.length)return{valid:!0};if(0===r.length)return{valid:!1,reason:`Delegation ${n.id} omits scopes required to prove attenuation from parent ${e.credentialSubject.delegation.id}`};const c=new Set(i),d=r.filter(e=>!c.has(e));return d.length>0?{valid:!1,reason:`Delegation ${n.id} widens scopes beyond parent ${e.credentialSubject.delegation.id}: ${d.join(", ")}`}:{valid:!0}}const Uo=["delete","drop","destroy","remove","terminate","transfer","payment","admin","execute","modify","write","rotate","revoke"],Ho=["read","get","list","describe","search","query"];class jo{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 i=Ko(e.toolName),r=function(e){const t=Ko(e);return t.includes("prod")||t.includes("production")}(e.namespace);let n;return n=i.some(e=>Uo.includes(e))?{reversibility:"irreversible",blastRadius:r?"environment":"resource",severity:r?"catastrophic":"high"}:i.some(e=>Ho.includes(e))?{reversibility:"reversible",blastRadius:"record",severity:"low"}:{reversibility:"unknown",blastRadius:"unknown",severity:"unknown"},{...n,...$o(t)}}}function Ko(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 $o(e){if(!e)return{};const t={};for(const[i,r]of Object.entries(e))void 0!==r&&(t[i]=r);return t}class Vo{cfg;constructor(e={}){this.cfg=e}async evaluate(e){const{severity:t,reversibility:i,scopeMatched:r,humanApprovals:n}=e.context;if(!r)return{decision:"deny",reason:"scope_not_matched"};if("unknown"===t||"unknown"===i)return{decision:"deny",reason:"unclassified_high_risk"};if("irreversible"===i||"catastrophic"===t||"high"===t){const e=this.cfg.stepUpQuorum??1;return n.length>=e?{decision:"allow"}:{decision:"step_up",quorum:{n:e,approvers:this.cfg.stepUpApprovers??[]},reason:"destructive_action_requires_approval"}}return{decision:"allow"}}}async function Bo(e,t,i,r){if(i.n<=0)return{satisfied:!1,reason:"invalid_quorum:n<=0"};const n=new Set;for(const o of e)"approve"===o.decision&&o.requestHash===t&&(i.approvers.length>0&&!i.approvers.includes(o.approverDid)||await r(o)&&n.add(o.approverDid));return n.size>=i.n?{satisfied:!0}:{satisfied:!1,reason:`quorum_not_met:${n.size}/${i.n}`}}function qo(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 Fo(e,t=256){const i="string"==typeof e?e:String(e);let r="";for(const e of i){const t=e.codePointAt(0)??0;r+=t<=31||t>=127&&t<=159?"�":e}return r.length>t?`${r.slice(0,t)}…`:r}const Wo=256,Go=256,Jo=/\([^()]*[+*?{][^()]*\)\s*[+*{]/;function Yo(e,t,i){switch(t){case"exact":return e===i;case"prefix":{const t=e.endsWith("*")?e.slice(0,-1):e;return 0!==t.length&&i.startsWith(t)}case"regex":if(e.length>Wo||i.length>Go)return!1;if(Jo.test(e))return!1;try{return new RegExp(`^(?:${e})$`).test(i)}catch{return!1}default:return!1}}function Xo(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 i of function(e){return e?.credentialSubject?.delegation?.constraints?.crisp?.scopes??[]}(t))if(Yo(i.resource,i.matcher,e))return{satisfied:!0,usedNonExactMatcher:"exact"!==i.matcher};return{satisfied:!1,usedNonExactMatcher:!1}}const Zo=256;function Qo(e){try{if("object"!=typeof e||null===e)return"unknown";const t=e,i=t.id;if("string"==typeof i&&i.length>0)return i.slice(0,Zo);const r=t.credentialSubject;if("object"!=typeof r||null===r)return"unknown";const n=r.delegation;if("object"!=typeof n||null===n)return"unknown";const o=n.id;return"string"==typeof o&&o.length>0?o.slice(0,Zo):"unknown"}catch{return"unknown"}}const es=["handshake","identity","reputation"];function ts(e,t){if(e.audit&&e.auditLog)throw new TypeError("Configure either audit or legacy auditLog, not both");if(void 0!==e.audit&&!1!==e.audit)if(void 0!==e.audit.capabilities){if(sn(e.audit.capabilities),void 0!==e.audit.auditProfile&&e.audit.auditProfile!==e.audit.capabilities.profile)throw new TypeError("Audit profile must match the validated capability profile")}else if(void 0!==e.audit.auditProfile&&"AAP-0"!==e.audit.auditProfile)throw new TypeError("Audit profiles above AAP-0 require validated capabilities");const i={did:e.identity.did,kid:e.identity.kid,privateKey:e.identity.privateKey,publicKey:e.identity.publicKey},n=e.nonceCache??new Ki,o=new qi(t,{...e.session,serverDid:i.did,nonceCache:n}),a=new Bt(i,t),u=e.delegation,l=e.auditLog??new nr,h=void 0!==e.audit&&!1!==e.audit?new Ro(e.audit,{includeToolNames:e.audit.includeToolNames??!1}):void 0,p=e.emitLegacyProofKey??!0,g=e.grantStore??new Po;e.grantStore||Ct.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 y=u?.holderBinding??"off",m={identity:i,config:e,cryptoProvider:t,sessionManager:o,proofGenerator:a,auditLog:l,audit:h,grantStore:g,delegationConfig:u,holderBindingMode:y,holderBindingVerifier:"off"===y?void 0:new Ti({cryptoProvider:t,clockProvider:new Zi,nonceCacheProvider:n,fetchProvider:u?.fetchProvider??("function"==typeof globalThis.fetch?new Qi:new er)}),emitLegacyProofKey:p},v=function(e){const{identity:t,config:i,cryptoProvider:n,sessionManager:o,proofGenerator:s,auditLog:a,audit:d,emitLegacyProofKey:u}=e,l=new WeakSet,h="org.kya-os/audit",p=async(e,t,i)=>{try{return await t(),!0}catch(t){return Ct.error(`[kya-os] ${e}`,{...void 0===i?{}:{tool:i},error:t instanceof Error?t.message:String(t)}),!1}},f=(e,t,i)=>{const r={...e._meta??{}};return i&&(delete r[Kt],delete r[$t]),r[h]={..."object"==typeof r[h]&&null!==r[h]?r[h]:{},status:"degraded",reason:t},e._meta=r,e.isError=!0,e},g=e=>({content:[{type:"text",text:JSON.stringify({success:!1,error:{code:"audit_delivery_failed",message:e}})}],isError:!0,_meta:{[h]:{status:"degraded",reason:e}}}),y=e=>void 0===e?void 0:{...void 0===e.actor?{}:{actor:e.actor},...void 0===e.responsibleParty?{}:{responsibleParty:e.responsibleParty},...void 0===e.authorization?{}:{authorization:e.authorization},...void 0===e.correlationId?{}:{correlationId:e.correlationId},...void 0===e.causationId?{}:{causationId:e.causationId}},m=(e,t)=>({...e,[Kt]:t,...u?{[$t]:t}:{}});let v;async function I(){if(v&&await o.getSession(v))return o.getStats().activeSessions<=1?v:void Ct.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(!i.autoSession)return;const e=c(await n.randomBytes(16)),r=Math.floor(Date.now()/1e3),s=await o.validateHandshake({nonce:e,audience:t.did,timestamp:r});return s.success&&s.session?(v=s.session.sessionId,v):void 0}return{handleHandshake:async function(e){if(!Wi(e))return await p("Failed to record rejected session audit event",()=>d?.session("rejected",{succeeded:!1,reasonCode:r.handshake_failed})),{content:[{type:"text",text:JSON.stringify({success:!1,error:{code:r.handshake_failed,message:"Invalid handshake format: requires nonce (string), audience (string), and timestamp (positive integer)"}})}],isError:!0};const i=await o.validateHandshake(e),n=i.success?"established":i.error?.code===r.nonce_replay?"replay_rejected":"rejected",s=await p(`Failed to record ${n} session audit event`,()=>d?.session(n,{succeeded:i.success,...void 0===i.error?{}:{reasonCode:i.error.code}}));return i.success&&!s?{content:g("Required session audit delivery failed after handshake validation").content,isError:!0}:(i.success&&i.session&&(v=i.session.sessionId),{content:[{type:"text",text:JSON.stringify({success:i.success,...i.session&&{sessionId:i.session.sessionId,serverDid:t.did,serverKid:t.kid},...i.error&&{error:i.error}})}],...i.error&&{isError:!0}})},ensureSession:I,wrapWithProof:function(e,i){return async(r,n,c)=>{if(!await p("Required tool intent audit delivery failed",()=>d?.tool("started",{toolName:e,outcome:"unknown",context:y(c)}),e))return g("Required intent audit delivery failed before tool execution");let u;try{u=await i(r,n,c)}catch(t){throw await p("Failed to record thrown tool outcome; preserving original handler error",()=>d?.tool("failed",{toolName:e,outcome:"failed",reasonCode:"HANDLER_THROWN",context:y(c)}),e),t}if(u.isError)return(e=>{if(l.has(e))return!0;const t=e._meta,i=t?.[h];return"object"==typeof i&&null!==i&&!0===i.terminal})(u)||await p("Failed to record error tool outcome",()=>d?.tool("failed",{toolName:e,outcome:"failed",reasonCode:"HANDLER_ERROR_RESULT",context:y(c)}),e)||f(u,"Required terminal audit delivery failed for an error response",!1),u;const v=n??await I();if(!v)return await p("Failed to record unavailable proof session",()=>d?.proof("rejected",{outcome:"failed",verificationCode:"PROOF_SESSION_UNAVAILABLE",context:y(c)}),e)&&await p("Failed to record completed tool outcome",()=>d?.tool("completed",{toolName:e,outcome:"succeeded",context:y(c)}),e)?u:f(u,"Required terminal audit delivery failed after tool completion",!0);const E=await o.getSession(v);if(!E)return await p("Failed to record missing proof session",()=>d?.proof("rejected",{outcome:"failed",verificationCode:"PROOF_SESSION_NOT_FOUND",context:y(c)}),e)&&await p("Failed to record completed tool outcome",()=>d?.tool("completed",{toolName:e,outcome:"succeeded",context:y(c)}),e)?u:f(u,"Required terminal audit delivery failed after tool completion",!0);try{const i={method:e,params:r},n={data:u.content},o=await s.generateProof(i,n,E,{scopeId:c?.scopeId});if(u._meta=m({},o),!await p("Required generated-proof audit delivery failed",()=>d?.proof("generated",{outcome:"succeeded",context:y(c)}),e)||!await p("Required completed-tool audit delivery failed",()=>d?.tool("completed",{toolName:e,outcome:"succeeded",context:y(c)}),e))return f(u,"Required terminal audit delivery failed after tool completion",!0);try{await a.logAuditRecord({identity:{did:t.did,kid:t.kid},session:{sessionId:E.sessionId,audience:E.audience},requestHash:o.meta.requestHash,responseHash:o.meta.responseHash,verified:"yes",scopeId:o.meta.scopeId})}catch(t){Ct.error("[kya-os] Audit log failed",{tool:e,error:t instanceof Error?t.message:String(t)})}}catch(t){Ct.error("[kya-os] Proof generation failed",{tool:e,error:t instanceof Error?t.message:String(t)}),u._meta={proofError:"Proof generation failed — response is unproven"},await p("Failed to record proof-generation rejection",()=>d?.proof("rejected",{outcome:"failed",verificationCode:"PROOF_GENERATION_FAILED",context:y(c)}),e)||f(u,"Required proof-failure audit delivery failed after tool completion",!0)}return u}},attachOutcomeProof:async(e,t,i,r,n,a="denied",c,u)=>{const g="denied"===a?"denied":"step_up_required",y="needs_authorization"===a?"NEEDS_AUTHORIZATION":"step_up_required"===a?"STEP_UP_REQUIRED":"AUTHORIZATION_DENIED",v=await p("Failed to record authorization outcome",()=>d?.authorization(g,{outcome:"denied"===a?"denied":"challenged",reasonCode:y}),t)&&await p("Failed to record terminal authorization tool outcome",()=>d?.tool("denied"===a?"denied":"challenged",{toolName:t,outcome:"denied"===a?"denied":"challenged",reasonCode:y}),t);l.add(e),e._meta={...e._meta??{},[h]:{terminal:!0,outcome:a,...v?{}:{status:"degraded",reason:"Required terminal audit delivery failed for authorization outcome"}}};try{const l=r??await I();if(!l)return e;const h=await o.getSession(l);if(!h)return e;let g;if(void 0!==c)g=c;else{g={};for(const[e,t]of Object.entries(i))"_kyaos_delegation"!==e&&(g[e]=t)}const y={method:t,params:g},E=void 0!==u?{data:u}:void 0,w=await s.generateProof(y,E,h,{outcome:a,reason:Fo(n)});e._meta=m(e._meta??{},w),v&&(await p("Failed to record generated outcome proof",()=>d?.proof("generated",{outcome:"succeeded"}),t)||f(e,"Required proof audit delivery failed for authorization outcome",!1))}catch(e){Ct.error("[kya-os] Outcome proof generation failed",{tool:t,error:e instanceof Error?e.message:String(e)}),v&&await p("Failed to record outcome-proof rejection",()=>d?.proof("rejected",{outcome:"failed",verificationCode:"OUTCOME_PROOF_GENERATION_FAILED"}),t)}return e}}}(m),I=function(e,t){const{identity:i,config:n,sessionManager:o}=e,{handleHandshake:s}=t;return{handleKyaOs:async function(e){const t="string"==typeof e.action?e.action:void 0;switch(t){case"handshake":return s(e);case"identity":return async function(){const e=void 0!==n.audit&&!1!==n.audit?{enabled:!0,profile:n.audit.capabilities?.profile??n.audit.auditProfile??"AAP-0",...void 0===n.audit.capabilities?{}:{capabilities:n.audit.capabilities}}:{enabled:!1,profile:"AAP-0"};return{content:[{type:"text",text:JSON.stringify({did:i.did,kid:i.kid,name:n.identity.agentName??i.did,capabilities:["handshake","signing","verification"],protocolVersion:"1.0.0",clockSkewSeconds:o.getStats().config.timestampSkewSeconds,auditAssurance:e})}]}}();case"reputation":return{content:[{type:"text",text:JSON.stringify({success:!1,error:{code:r.runtime_error,message:'action: "reputation" is not yet implemented.'}})}],isError:!0};default:return{content:[{type:"text",text:JSON.stringify({success:!1,error:{code:r.invalid_request,message:`Unknown _kyaos action: "${t??"(missing)"}". Valid actions: ${es.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:[...es],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"]}}}}(m,{handleHandshake:v.handleHandshake}),{resolveExistingGrant:E,bindGrantOnSuccess:w}=function(e){const{identity:t,cryptoProvider:i,grantStore:r,holderBindingMode:n,holderBindingVerifier:o}=e;async function s(e,t,r){const n=`${e}|${t??""}|${[...r].sort().join(",")}`;return`grant_${(await i.hash((new TextEncoder).encode(n))).replace(/^sha256:/,"")}`}return{resolveExistingGrant:async function(e,i,n,s){const a=await async function(e,i,n,s){if(!o)return;const a=i._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&&Zt(u)&&"bound"===(await Qt({proof:d,subjectDid:u,request:Jt(e,i),expectedAudience:t.did,proofVerifier:o})).status?(await r.getByAgent(u,[s])).find(e=>void 0===e.sessionId||e.sessionId===n):void 0}(e,i,n,s);if(a)return a;if(n){const[e]=await r.getBySession(n,[s]);if(e)return e}},bindGrantOnSuccess:async function(e,t,i,o,a){try{const c=e.credentialSubject?.id;if(!c)return;if("off"===n&&void 0===o)return void Ct.debug(`[kya-os] Skipping an unresolvable session-less grant for scope "${a}" (holderBinding 'off', no sessionId).`);let d;try{d=Mo(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),p={id:await s(c,o,u),agentDid:c,...void 0!==l?{userDid:l}:{},scopes:u,...void 0!==o?{sessionId:o}:{},authorization:{type:"delegation"},...i&&"string"==typeof t?{credentialJwt:t}:{},issuedAt:Date.now(),...void 0!==h?{expiresAt:h}:{},status:"active"};await r.bind(p)}catch(e){Ct.error("[kya-os] Grant bind failed",{scope:a,error:e instanceof Error?e.message:String(e)})}}}}(m),{wrapWithDelegation:S}=function(e,t){const{identity:i,holderBindingMode:n,holderBindingVerifier:o,audit:a,cryptoProvider:c}=e,{attachOutcomeProof:u,resolveExistingGrant:l,bindGrantOnSuccess:h}=t,{validateDelegationChain:p,buildDelegationErrorResponse:g,buildNeedsAuthorizationChallenge:y}=function(e){const{identity:t,cryptoProvider:i,delegationConfig:r}=e,n=Pt(),o=r?.fetchProvider??("function"==typeof globalThis.fetch?new Qi:void 0),a=o?ci(o):void 0,c=mi(r?.didResolvers,o),u=new He({didResolver:{async resolve(e){const t=r?.didResolver;if(t){const i=await t.resolve(e);if(i)return i}const i=gt(e),o=i?c[i]:void 0;if(o)try{const t=await o.resolve(e);if(t)return t}catch{return null}return e.startsWith("did:key:")?n.resolve(e):e.startsWith("did:web:")?a?.resolve(e)??null:null}},signatureVerifier:async(e,t)=>{const r=e.proof;if(!r)return{valid:!1,reason:"Missing proof"};const n=r.proofValue;if(!n)return{valid:!1,reason:"Missing proofValue in proof"};const o=e,a={};for(const[e,t]of Object.entries(o))"proof"!==e&&(a[e]=t);const c=x(a),u=(new TextEncoder).encode(c),l=s(n),h=t;if(!h.x)return{valid:!1,reason:"No x field in publicKeyJwk"};const p=d(s(h.x)),f=await i.verify(u,l,p);return{valid:f,reason:f?void 0:"Signature verification failed"}},statusListResolver:r?.statusListResolver});return{validateDelegationChain:(e,i)=>async function(e,t,i){const r=e?.credentialSubject?.delegation;if(!r||"object"!=typeof r||!r.constraints||"object"!=typeof r.constraints)return{valid:!1,reason:"Malformed delegation credential: missing credentialSubject.delegation or its constraints"};const n=f(e);let o=[e];if(n.parentId){if(!t.resolveDelegationChain)return{valid:!1,reason:`Delegation ${n.id} references parent ${n.parentId} but no resolveDelegationChain handler is configured`};let i;try{i=await t.resolveDelegationChain(e)}catch(e){return{valid:!1,reason:`Failed to resolve delegation chain: ${e instanceof Error?e.message:"Unknown error"}`}}if(0===i.length)return{valid:!1,reason:`Delegation ${n.id} references parent ${n.parentId} but the resolved chain is empty`};const r=i.findIndex(e=>e.credentialSubject.delegation.id===n.id);if(-1!==r&&r!==i.length-1)return{valid:!1,reason:`Resolved delegation chain for ${n.id} must end with the leaf credential`};o=-1===r?[...i,e]:i}const s=new Set;let a,c;for(const e of o){const r=f(e);if(s.has(r.id))return{valid:!1,reason:`Delegation chain contains a circular reference at ${r.id}`};if(s.add(r.id),e.credentialStatus&&!t.statusListConfigured)return{valid:!1,reason:`Delegation ${r.id} has credentialStatus but no statusListResolver is configured`};const n=await t.verifier.verifyDelegationCredential(e,{...i?.skipSignature?{skipSignature:!0}:{}});if(!n.valid)return{valid:!1,reason:`Delegation ${r.id} invalid: ${n.reason}`};if(!Ze(r,t.serverDid))return{valid:!1,reason:`Delegation ${r.id} audience does not include server DID ${t.serverDid}`};if(r.parentId&&!r.constraints.audience)return{valid:!1,reason:`Delegation ${r.id} is a re-delegation (parentId: ${r.parentId}) but has no audience constraint. Re-delegations MUST include an audience constraint (KYA-OS §11.6)`};if(!a||!c){if(r.parentId)return{valid:!1,reason:`Resolved delegation chain is incomplete: root delegation ${r.id} still references parent ${r.parentId}`};a=r,c=e;continue}if(r.parentId!==a.id)return{valid:!1,reason:`Delegation ${r.id} references parent ${r.parentId} but expected ${a.id}`};if(r.issuerDid!==a.subjectDid)return{valid:!1,reason:`Delegation ${r.id} issued by ${r.issuerDid} but parent subject is ${a.subjectDid}`};const o=zo(c,e);if(!o.valid)return o;a=r,c=e}const d=f(o[o.length-1]);if(d.id!==n.id)return{valid:!1,reason:`Resolved delegation chain ended at ${d.id} instead of leaf ${n.id}`};if(t.revocationChecker){const e=await t.revocationChecker.isRevoked(n.id);if(e.revoked)return{valid:!1,reason:e.revokedAncestor?`Delegation ${n.id} is revoked via ancestor ${e.revokedAncestor}`:`Delegation ${n.id} is revoked${e.reason?`: ${e.reason}`:""}`}}return{valid:!0}}(e,{serverDid:t.did,verifier:u,resolveDelegationChain:r?.resolveDelegationChain,statusListConfigured:!!r?.statusListResolver,revocationChecker:r?.revocationChecker},i),buildDelegationErrorResponse:(e,t)=>({content:[{type:"text",text:JSON.stringify({error:e,reason:Fo(t)})}],isError:!0}),buildNeedsAuthorizationChallenge:async function(e,t){const r=await i.randomBytes(16),n=Array.from(r).map(e=>e.toString(16).padStart(2,"0")).join(""),o=[n.slice(0,8),n.slice(8,12),n.slice(12,16),n.slice(16,20),n.slice(20)].join("-"),s=Math.floor(Date.now()/1e3)+300,a=D({message:`Tool "${e}" requires delegation with scope: ${t.scopeId}`,authorizationUrl:t.consentUrl,resumeToken:o,expiresAt:s,scopes:[t.scopeId]}),c=[{type:"text",text:JSON.stringify(a)}];let d=c;if(t.formatChallenge)try{d=t.formatChallenge(a)}catch(t){Ct.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,s){return async(d,f)=>{const m=d._kyaos_delegation;if(null==m){const i=await l(e,d,f,t.scopeId);if(i){const r={};for(const[e,t]of Object.entries(d))Gt(e)||(r[e]=t);Ct.debug(`[kya-os] Grant resolved for "${e}" (scope "${t.scopeId}") — no re-paste required`);const n={scopeId:t.scopeId,actor:{kind:"pairwise_did",did:i.agentDid},...i.userDid?.startsWith("did:")?{responsibleParty:{kind:"pairwise_did",did:i.userDid}}:{},authorization:{source:"grant",decision:"allowed",scopeId:t.scopeId,grantRef:i.id,verificationCode:"DURABLE_GRANT_RESOLVED"}};return await(a?.authorization("grant_used",{outcome:"succeeded",grantRef:i.id,context:n})),s(r,f,n)}const{challengeContent:r,message:n}=await y(e,t);return u({content:r},e,d,f,n,"needs_authorization",void 0,r)}let v,I=!1;if("string"==typeof m){const t=U(m);if(!t||!t.payload.vc)return u(g(r.delegation_invalid,"Invalid VC-JWT format"),e,d,f,"Invalid VC-JWT format");v=t.payload.vc,v.proof||(v={...v,proof:{type:"JwtProof2020",jwt:m}}),I=!0}else v=m;const E=await(async()=>{try{return await p(v,{skipSignature:I})}catch(t){return Ct.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(!E.valid){const t=E.reason??"Unknown delegation validation error";try{await(a?.delegation("rejected",{delegationRef:Qo(v),outcome:"failed",reasonCode:"DELEGATION_VERIFICATION_FAILED"}))}catch(t){Ct.error("[kya-os] Failed to record rejected delegation audit event",{tool:e,error:t instanceof Error?t.message:String(t)})}return Ct.warn(`[kya-os] Delegation verification failed for "${e}": ${Fo(t)}`),u(g(r.delegation_invalid,t),e,d,f,t)}if("off"!==n&&o){const t=v.credentialSubject?.id;if(t&&Zt(t)){const s=d._kyaos_proof;if(void 0===s){const t="Holder-of-key proof (_kyaos_proof) is required for this delegation subject";if(Ct.warn(`[kya-os] Holder binding: "${e}" called without _kyaos_proof`),"enforce"===n)return u(g(r.holder_binding_failed,t),e,d,f,t)}else{let a=s;if("string"==typeof s)try{a=JSON.parse(s)}catch{a={}}const c=await Qt({proof:a,subjectDid:t,request:Jt(e,d),expectedAudience:i.did,proofVerifier:o});if("bound"!==c.status){const t=c.reason??"Holder-of-key proof did not bind the delegation subject";if(Ct.warn(`[kya-os] Holder binding ${c.status} for "${e}": ${Fo(t)}`),"enforce"===n)return u(g(r.holder_binding_failed,t),e,d,f,t)}}}else t&&Ct.warn(`[kya-os] Holder binding: subject "${t}" is not did:key; deferring to cnf binding (phase 2)`)}const w=Xo(t.scopeId,v);if(w.usedNonExactMatcher&&Ct.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.`),!w.satisfied){const i=`Required scope "${t.scopeId}" not in delegation scopes`;return Ct.warn(`[kya-os] Delegation missing required scope "${t.scopeId}" for "${e}"`),u(g(r.insufficient_scope,i),e,d,f,i)}const S=I?(new TextEncoder).encode(m):L(v),D=await c.hash(S),A=v.id??v.credentialSubject.delegation.id,b={kind:"pairwise_did",did:v.credentialSubject.id},_=v.credentialSubject.delegation.controller,C={source:"delegation",decision:"allowed",scopeId:t.scopeId,delegationRef:A,delegationCredentialDigest:D,verificationCode:"DELEGATION_CHAIN_VALID"},T={scopeId:t.scopeId,actor:b,..._?.startsWith("did:")?{responsibleParty:{kind:"pairwise_did",did:_}}:{},authorization:C};await(a?.delegation("verified",{delegationRef:A,outcome:"succeeded",parentRef:v.credentialSubject.delegation.parentId,context:T})),await(a?.authorization("approved",{outcome:"succeeded",context:T}));const k={};for(const[e,t]of Object.entries(d))Gt(e)||(k[e]=t);return await h(v,m,I,f,t.scopeId),Ct.debug(`[kya-os] Delegation verified for "${e}", scope "${t.scopeId}"`),s(k,f,T)}}}}(m,{attachOutcomeProof:v.attachOutcomeProof,resolveExistingGrant:E,bindGrantOnSuccess:w}),{withPolicyGate:A}=function(e,t){const{proofGenerator:i,audit:n}=e,{attachOutcomeProof:o}=t,s=new jo,a=new Vo;return{withPolicyGate:function(e,t,c={}){const d=c.engine??a,u=c.classifier??s,l=c.approvalsArgKey??"_kyaos_approvals",h=c.isValidApprovalSignature??(async()=>!1);return async(s,a,p)=>{const f={};for(const[e,t]of Object.entries(s))Gt(e)||e===l||(f[e]=t);const g=c.resolveNamespace?.(s)??e,y=u.classify({toolName:e,namespace:g}),m=function(e){if(!e||"object"!=typeof e)return{agentDid:"unknown",delegatedScopes:[]};try{const t=e,i=t.credentialSubject,r=i?.delegation?.subjectDid??i?.id??"unknown",n=i?.delegation?.controller;let o=[];try{o=Mo(t)}catch{o=[]}return{agentDid:r,...n?{responsibleParty:n}:{},delegatedScopes:o}}catch{return{agentDid:"unknown",delegatedScopes:[]}}}(s._kyaos_delegation),v=qo({principal:{agentDid:m.agentDid,...m.responsibleParty?{responsibleParty:m.responsibleParty}:{}},action:{toolName:e},resource:{namespace:g},delegatedScopes:m.delegatedScopes,scopeMatched:c.scopeMatched??!1,risk:y}),I=await d.evaluate(v),E=void 0===p?void 0:{...void 0===p.actor?{}:{actor:p.actor},...void 0===p.responsibleParty?{}:{responsibleParty:p.responsibleParty},...void 0===p.authorization?{}:{authorization:p.authorization}};if(await(n?.authorization("evaluated",{outcome:"allow"===I.decision?"succeeded":"deny"===I.decision?"denied":"challenged",reasonCode:"allow"===I.decision?void 0:"deny"===I.decision?"POLICY_DENIED":"POLICY_STEP_UP",context:E})),"allow"===I.decision)return await(n?.authorization("approved",{outcome:"succeeded",context:E})),t(f,a,p);if("deny"===I.decision){const t={content:[{type:"text",text:JSON.stringify({error:r.policy_denied,reason:Fo(I.reason)})}],isError:!0};return o(t,e,s,a,I.reason,"denied",f)}const w=await i.hashRequest({method:e,params:f}),S=Array.isArray(s[l])?s[l]:[];if((await Bo(S,w,I.quorum,h)).satisfied)return await(n?.authorization("approved",{outcome:"succeeded",context:E})),t(f,a,p);const D=b({message:`Tool "${e}" requires ${I.quorum.n}-of-N approval before it may proceed (${Fo(I.reason)}).`,resumeToken:`step_up:${w}`,expiresAt:Math.floor(Date.now()/1e3)+300,requestHash:w,quorum:I.quorum}),A={content:[{type:"text",text:JSON.stringify(D)}],isError:!0};return o(A,e,s,a,I.reason,"step_up_required",f)}}}}(m,{attachOutcomeProof:v.attachOutcomeProof});return{identity:e.identity,sessionManager:o,proofGenerator:a,kyaOsTool:I.kyaOsTool,handshakeTool:I.handshakeTool,handleKyaOs:I.handleKyaOs,handleHandshake:v.handleHandshake,wrapWithProof:v.wrapWithProof,wrapWithDelegation:S,withPolicyGate:A}}async function is(e){const t=await e.generateKeyPair(),i=Dt(t.publicKey);return{did:i,kid:`${i}#${At(i)}`,privateKey:t.privateKey,publicKey:t.publicKey}}async function rs(e,t){const i=ts({identity:t.identity??await is(t.crypto),session:t.session,delegation:t.delegation,autoSession:t.autoSession??!0,...void 0!==t.audit?{audit:t.audit}:{},...void 0!==t.auditLog?{auditLog:t.auditLog}:{},...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:sr.z.enum(es).describe("Protocol operation to perform"),nonce:sr.z.string().optional().describe("Client-generated unique nonce (handshake)"),audience:sr.z.string().optional().describe("Intended audience (handshake)"),timestamp:sr.z.number().optional().describe("Unix epoch seconds (handshake)"),agentDid:sr.z.string().optional().describe("Client agent DID (handshake, optional)")}},async e=>{const t=await i.handleKyaOs(e);return{...t,content:t.content.map(e=>({...e,type:"text"}))}}),!1!==t.proofAllTools){const r=["_kyaos","_kyaos_handshake",...t.excludeTools??[]],n=e.connect.bind(e);e.connect=e=>n(function(e,t,i=["_kyaos","_kyaos_handshake"]){const r=new Map,n={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(i){const n=i.id,o=void 0!==n?r.get(n):void 0;if(o){r.delete(n);try{const e=i.result;if(e){const r=async()=>({...e}),n=t.wrapWithProof(o.toolName,r),s=await n(o.args);e.isError||void 0===s._meta||(i={...i,result:s})}}catch(e){Ct.error("[kya-os-transport] Proof injection failed",{tool:o.toolName,error:e instanceof Error?e.message:String(e)});const t=i.result;t&&(t._meta={proofError:"Proof generation failed — response is unproven"},i={...i,result:t})}}return e.send(i)}},o=e.start.bind(e);return n.start=async()=>{await o();const t=e.onmessage;e.onmessage=e=>{if("tools/call"===e.method&&void 0!==e.id){const t=e.params,n=t?.name;n&&!i.includes(n)&&r.set(e.id,{toolName:n,args:t?.arguments??{}})}t?.(e)}},n}(e,i,r))}return i}}};