@kya-os/mcp-i 1.12.2 → 1.12.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/958.js +1 -0
- package/dist/runtime/215.js +1 -0
- package/dist/runtime/adapter-express.js +3 -3
- package/dist/runtime/adapter-nextjs.js +3 -3
- package/dist/runtime/http.js +3 -3
- package/dist/runtime/mcpi-runtime.js +62 -61
- package/dist/runtime/stdio.js +3 -3
- package/dist/test/examples/test-usage-example.d.ts +8 -8
- package/package.json +2 -2
- package/dist/365.js +0 -1
- package/dist/runtime/160.js +0 -1
package/dist/958.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";exports.id=958,exports.ids=[958],exports.modules={98958:(e,t,i)=>{i.r(t),i.d(t,{ANON_NONCE_TTL_MS:()=>D,AUDIT_ASSURANCE_PROFILES:()=>qn,AUDIT_BUNDLE_INTEGRITY_SUITE:()=>Qr,AUDIT_BUNDLE_MANIFEST_SCHEMA_ID:()=>Zr,AUDIT_BUNDLE_MEDIA_TYPES:()=>Mo,AUDIT_CHECKPOINT_INTEGRITY_SUITE:()=>Xr,AUDIT_CHECKPOINT_SCHEMA_ID:()=>Yr,AUDIT_CONSISTENCY_PROOF_REQUEST_SCHEMA_ID:()=>gs,AUDIT_CONSISTENCY_PROOF_RESPONSE_SCHEMA_ID:()=>ys,AUDIT_DIGEST_DOMAINS:()=>eo,AUDIT_ENTRY_SCHEMA_ID:()=>Wr,AUDIT_ERROR_CODES:()=>so,AUDIT_EVENT_SCHEMA_ID:()=>Fr,AUDIT_EVENT_TYPES:()=>qr,AUDIT_HEAD_REQUEST_SCHEMA_ID:()=>ds,AUDIT_HEAD_RESPONSE_SCHEMA_ID:()=>us,AUDIT_INCLUSION_PROOF_REQUEST_SCHEMA_ID:()=>ps,AUDIT_INCLUSION_PROOF_RESPONSE_SCHEMA_ID:()=>fs,AUDIT_INTEGRITY_SUITE:()=>Jr,AUDIT_LIST_ENTRIES_REQUEST_SCHEMA_ID:()=>ls,AUDIT_LIST_ENTRIES_RESPONSE_SCHEMA_ID:()=>hs,AUDIT_REASON_CODES:()=>No,AUDIT_RECEIPT_SCHEMA_ID:()=>Gr,AUTH_NONCE_TTL_MS:()=>A,AuditArtifactVerifier:()=>zo,AuditCheckpointBuilder:()=>Do,AuditCheckpointCoordinator:()=>_o,AuditLogProvider:()=>Kr,AuditMirrorService:()=>Zo,AuditProjectionWorker:()=>ko,AuditProtocolError:()=>ao,AuditRecorderService:()=>rs,AuditReplayBundleExporter:()=>Vo,AuditTrailService:()=>Yo,BitstringManager:()=>Gt,CascadingRevocationManager:()=>Zt,ClockProvider:()=>Er,CompactJwsAuditSignatureVerifier:()=>Jn,CompactJwsAuditSigner:()=>Yn,CryptoProvider:()=>Ir,CryptoProviderAuditHasher:()=>Gn,DEFAULT_CLOCK_SKEW_SECONDS:()=>ur,DEFAULT_EXEMPT_METHODS:()=>Ic,DEFAULT_EXTENSION_SETTINGS:()=>cc,DEFAULT_READ_ENTRIES_LIMIT:()=>ns,DEFAULT_SESSION_TTL_MINUTES:()=>E,DEFAULT_TIMESTAMP_SKEW_SECONDS:()=>w,DELEGATION_CREDENTIAL_CONTEXT:()=>h,DefaultPolicyEngine:()=>_a,DelegationCredentialIssuer:()=>V,DelegationCredentialVerifier:()=>Kt,DelegationGraphManager:()=>Vt,DidWebResolver:()=>Bi,ED25519_KEY_SIZE:()=>Si,ED25519_PKCS8_DER_HEADER:()=>Ei,ED25519_SPKI_DER_HEADER_LENGTH:()=>wi,EXTENSION_NOT_DECLARED_REASON:()=>nc,ExtensionSettingsSchema:()=>ac,FetchProvider:()=>wr,GrantStore:()=>fa,HOLDER_BINDING_ERROR:()=>xi,IdentityProvider:()=>Dr,KYA_OS_DOMAIN_ERROR_CODE:()=>yc,KYA_OS_ERROR_CODES:()=>r,KYA_OS_EXTENSION_ID:()=>tc,KYA_OS_PROOF_META_KEY:()=>Ai,LEGACY_NAMESPACED_PROOF_META_KEY:()=>Di,LEGACY_PROOF_META_KEY:()=>_i,LegacyAuditSinkAdapter:()=>la,LocalAuditReadService:()=>as,LocalAuditRecorderClient:()=>na,MAX_CLOCK_SKEW_SECONDS:()=>hr,MAX_READ_ENTRIES_LIMIT:()=>os,MCP_CLIENT_CAPABILITIES_META_KEY:()=>ic,MIN_CLOCK_SKEW_SECONDS:()=>lr,MISSING_REQUIRED_CLIENT_CAPABILITY_CODE:()=>rc,McpAuditEventAdapter:()=>pa,MemoryAuditCheckpointObserver:()=>aa,MemoryAuditCheckpointStore:()=>Ao,MemoryAuditEvidenceProvider:()=>uo,MemoryAuditJournal:()=>Gs,MemoryAuditLogProvider:()=>$r,MemoryAuditOutbox:()=>da,MemoryAuditProjectionProvider:()=>To,MemoryAuditSourceState:()=>ua,MemoryDelegationGraphStorage:()=>ji,MemoryGrantStore:()=>ga,MemoryIdentityProvider:()=>Cr,MemoryNonceCacheProvider:()=>br,MemoryPendingFlowStore:()=>va,MemoryResumeTokenStore:()=>rr,MemorySessionStore:()=>kr,MemoryStatusListStorage:()=>Hi,MemoryStorageProvider:()=>_r,MemorySupportingAnchorProvider:()=>ca,NONCE_LENGTH_BYTES:()=>S,NodeCryptoProvider:()=>Lr,NonceCacheProvider:()=>Ar,NoopAuditLogProvider:()=>Vr,NoopFetchProvider:()=>Hr,OUTBOUND_HEADER_NAMES:()=>yi,PROOF_VERIFICATION_ERROR_CODES:()=>ar,PendingFlowStore:()=>ya,ProofGenerator:()=>Ti,ProofVerificationError:()=>cr,ProofVerifier:()=>pr,RESPONSE_PROOF_PROFILE_BODY:()=>_,RESPONSE_PROOF_PROFILE_ENVELOPE:()=>b,Rfc9162MerkleTree:()=>vo,RiskClassifier:()=>Sa,RuntimeFetchProvider:()=>Ur,SENSITIVE_VERBS:()=>Ea,SessionManager:()=>Nr,SessionStore:()=>Tr,StatusList2021Manager:()=>Yt,StorageProvider:()=>Sr,SystemClockProvider:()=>Mr,WebCryptoEvidenceEncryptor:()=>co,assertAuditCapabilities:()=>Bn,assertHolderBinding:()=>Mi,auditAnchorReceiptSchema:()=>In,auditBundleConsistencyProofSchema:()=>An,auditBundleInclusionProofSchema:()=>Sn,auditBundleManifestCoreSchema:()=>bn,auditCheckpointCoreSchema:()=>gn,auditConsistencyProofRequestSchema:()=>bs,auditConsistencyProofResponseSchema:()=>Cs,auditEntryCoreSchema:()=>pn,auditHeadRequestSchema:()=>Es,auditHeadResponseSchema:()=>ws,auditHeadSchema:()=>ms,auditInclusionProofRequestSchema:()=>Ds,auditInclusionProofResponseSchema:()=>_s,auditListEntriesRequestSchema:()=>Ss,auditListEntriesResponseSchema:()=>As,auditMerkleConsistencyProofSchema:()=>wn,auditMerkleInclusionProofSchema:()=>En,auditObservationReceiptSchema:()=>mn,auditProducerEventSchema:()=>hn,auditRecorderReceiptCoreSchema:()=>fn,auditReplayBundleSchema:()=>Tn,auditVerificationPolicySchema:()=>Rn,base58Decode:()=>G,base58Encode:()=>W,base64ToBytes:()=>u,base64urlDecodeToBytes:()=>s,base64urlEncodeFromBytes:()=>c,buildAuditRecord:()=>jr,buildAuditRecorderReceiptCore:()=>io,buildChainString:()=>gi,buildDelegationProofJWT:()=>fi,buildDidResolverRegistry:()=>ir,buildDidWebDocument:()=>Ji,buildExtensionSettings:()=>lc,buildExtensionsEntry:()=>hc,buildOutboundDelegationHeaders:()=>vi,buildPolicyRequest:()=>Ca,buildProofJwsPayload:()=>Ci,bytesToBase64:()=>d,canonicalizeJSON:()=>H,collectAuditEvidenceManifest:()=>to,collectAuditEvidenceRefs:()=>Qn,compareDids:()=>Q,completeVCJWT:()=>K,computeCanonicalHashes:()=>bi,createAuditTrail:()=>Xo,createCascadingRevocationManager:()=>Qt,createDefaultConsoleLogger:()=>ce,createDelegationGraph:()=>qt,createDelegationIssuer:()=>q,createDelegationVerifier:()=>$t,createDidKeyResolver:()=>ge,createDidWebResolver:()=>Fi,createHandshakeRequest:()=>Rr,createInMemoryReferenceRecorder:()=>ra,createKyaOsError:()=>n,createKyaOsMiddleware:()=>Ua,createLocalAuditReadService:()=>cs,createLocalAuditRecorder:()=>oa,createNeedsApprovalError:()=>k,createNeedsAuthorizationError:()=>C,createProofResponse:()=>ki,createProofVerificationError:()=>dr,createStatusListManager:()=>Xt,createUnsignedVCJWT:()=>j,decimalStringSchema:()=>rn,didKeyFragment:()=>se,didWebToUrl:()=>qi,digestAuditEntry:()=>no,digestAuditEvent:()=>ro,digestAuditEvidenceManifest:()=>oo,digestSchema:()=>nn,evidenceRefSchema:()=>an,extractAgentId:()=>te,extractAgentSlug:()=>ie,extractCanonicalData:()=>Ni,extractDelegationFromVC:()=>y,extractProofFromMeta:()=>mr,extractPublicKeyFromDidKey:()=>pe,generateDidKeyFromBase64:()=>oe,generateDidKeyFromBytes:()=>ne,generateIdentity:()=>Ha,generateRequestProof:()=>zi,getDidMethod:()=>X,getServerDid:()=>ee,hasSensitiveScopes:()=>sr,hashAuditValue:()=>Xn,isDelegationCredentialExpired:()=>v,isDelegationCredentialNotYetValid:()=>m,isDidWeb:()=>$i,isEd25519DidKey:()=>he,isHolderBindingApplicable:()=>Li,isIndexSet:()=>Jt,isKyaOsControlArg:()=>Oi,isNeedsApprovalError:()=>N,isNeedsAuthorizationError:()=>T,isReservedMcpMetaKey:()=>yr,isValidBase58:()=>J,isValidDid:()=>Y,logger:()=>de,matchScope:()=>Oa,mergeAuditDimensions:()=>xo,missingRequiredCapabilityError:()=>wc,normalizeDid:()=>Z,parseAuditBundleManifestCore:()=>Kn,parseAuditCheckpointCore:()=>Un,parseAuditConsistencyProofRequest:()=>zs,parseAuditConsistencyProofResponse:()=>xs,parseAuditEntryCore:()=>xn,parseAuditHeadRequest:()=>Ts,parseAuditHeadResponse:()=>ks,parseAuditInclusionProofRequest:()=>Os,parseAuditInclusionProofResponse:()=>Ps,parseAuditListEntriesRequest:()=>Ns,parseAuditListEntriesResponse:()=>Rs,parseAuditObservationReceipt:()=>jn,parseAuditProducerEvent:()=>zn,parseAuditRecorderReceiptCore:()=>Mn,parseAuditReplayBundle:()=>$n,parseAuditVerificationPolicy:()=>Vn,parseDidWeb:()=>Vi,parseExtensionSettings:()=>dc,parseSignedAuditCheckpoint:()=>Hn,parseSignedAuditEntry:()=>Ln,parseVCJWT:()=>$,partyRefSchema:()=>cn,proofGateToJsonRpcError:()=>Dc,publicKeyToJwk:()=>fe,readExtensionDeclaration:()=>fc,requireExtension:()=>Ec,resolveDidKeySync:()=>ye,resolveExtensionSettings:()=>uc,sampleAuditEvent:()=>ia,scopeSatisfies:()=>Pa,signedAuditCheckpointSchema:()=>yn,signedAuditEntrySchema:()=>vn,signerRefSchema:()=>sn,toAuditConsistencyProofResponse:()=>Hs,toAuditHeadResponse:()=>Ls,toAuditInclusionProofResponse:()=>Us,toAuditListEntriesResponse:()=>Ms,toHolderBindingRequest:()=>Pi,validateDelegationCredential:()=>I,validateDetachedProof:()=>O,validateHandshakeFormat:()=>Or,validateMetaStructure:()=>vr,verifyApprovalQuorum:()=>ba,verifyAuditBundle:()=>Jo,verifyDelegationAudience:()=>ei,verifyDidLinkage:()=>Zi,verifyOrHints:()=>nr,withKyaOs:()=>ja,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?.proofValue;return"string"==typeof t?t:""}const g=new Set(["Ed25519Signature2020","DataIntegrityProof"]);function y(e){const t=e?.credentialSubject?.delegation;if(!t||"object"!=typeof t)throw new Error("extractDelegationFromVC: credential is missing credentialSubject.delegation");const i=f(e.proof);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 v(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 m(e){const t=e.credentialSubject.delegation;return!!(t.constraints.notBefore&&Math.floor(Date.now()/1e3)<t.constraints.notBefore)}function I(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 E=30,w=120,S=16,A=12e4,D=6e4,_="org.kya-os/response-proof.body",b="org.kya-os/response-proof.envelope";function C(e){return{error:"needs_authorization",...e}}function T(e){return"object"==typeof e&&null!==e&&"needs_authorization"===e.error}function k(e){return{error:"needs_approval",...e}}function N(e){return"object"==typeof e&&null!==e&&"needs_approval"===e.error}const R=/^sha256:[a-f0-9]{64}$/;function O(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||!R.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||!R.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)?void 0!==r.prf&&r.prf!==b?{success:!1,error:{message:`meta.prf must be "${b}" when present (unknown response-proof profiles are rejected fail-closed)`}}:{success:!0,data:e}:{success:!1,error:{message:"meta.outcome must be one of allowed | denied | step_up_required | needs_authorization"}}}var P=i(77753);const z=new TextEncoder;function x(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 L(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}]`);L(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(x(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}`);L(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(x(e))throw new TypeError(`Cannot canonicalize string with lone surrogate at ${t}`)}function M(e){return L(e),(0,P.d)(e)}function U(e){return z.encode(M(e))}function H(e){return M(e)}function j(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 K(e,t){return`${e}.${t}`}function $(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 V{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 H(e)}getIssuerDid(){return this.identity.getDid()}getIssuerKeyId(){return this.identity.getKeyId()}}function q(e,t){return new V(e,t)}const B="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",F=new Map;for(let e=0;e<B.length;e++){const t=B[e];void 0!==t&&F.set(t,e)}function W(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=B[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 G(e){if(0===e.length)return new Uint8Array(0);let t=BigInt(0);for(const i of e){const e=F.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 J(e){if(0===e.length)return!0;for(const t of e)if(!F.has(t))return!1;return!0}function Y(e){return"string"==typeof e&&e.startsWith("did:")}function X(e){if(!Y(e))return null;const t=e.match(/^did:([^:]+):/);return t?.[1]??null}function Z(e){return e.trim()}function Q(e,t){return Z(e)===Z(t)}function ee(e){const t=e.identity.serverDid||e.identity.agentDid;if(!t)throw new Error("Server DID not configured");return t}function te(e){const t=e.split(":");return t[t.length-1]??e}function ie(e){return te(e)}const re=new Uint8Array([237,1]);function ne(e){const t=new Uint8Array(re.length+e.length);return t.set(re),t.set(e,re.length),`did:key:z${W(t)}`}function oe(e){return ne(Uint8Array.from(atob(e),e=>e.charCodeAt(0)))}function se(e){return e.startsWith("did:key:")?e.slice(8):"keys-1"}const ae={debug:10,info:20,warn:30,error:40};function ce(){let e="info",t=!1;function i(i,...r){if(function(t){return ae[t]>=ae[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 de=ce(),ue=new Uint8Array([237,1]),le=32;function he(e){return e.startsWith("did:key:z6Mk")}function pe(e){if(!e.startsWith("did:key:z"))return null;try{const t=G(e.replace("did:key:","").slice(1));return t.length<ue.length+le||t[0]!==ue[0]||t[1]!==ue[1]?null:t.slice(ue.length)}catch(e){return de.debug("Failed to extract public key from did:key",e),null}}function fe(e){return{kty:"OKP",crv:"Ed25519",x:c(e)}}function ge(){return{resolve:async e=>{if(!he(e))return null;const t=pe(e);if(!t)return null;const i=fe(t),r=e.replace("did:key:",""),n=se(e);return{id:e,verificationMethod:[{id:`${e}#${n}`,type:"Ed25519VerificationKey2020",controller:e,publicKeyJwk:i,publicKeyMultibase:r}],authentication:[`${e}#${n}`],assertionMethod:[`${e}#${n}`]}}}}function ye(e){if(!he(e))return null;const t=pe(e);if(!t)return null;const i=fe(t),r=e.replace("did:key:",""),n=se(e);return{id:e,verificationMethod:[{id:`${e}#${n}`,type:"Ed25519VerificationKey2020",controller:e,publicKeyJwk:i,publicKeyMultibase:r}],authentication:[`${e}#${n}`],assertionMethod:[`${e}#${n}`]}}function ve(e){if(e.publicKeyJwk)return e.publicKeyJwk;const t=function(e){try{if(e.publicKeyMultibase?.startsWith("z")){const t=G(e.publicKeyMultibase.slice(1)),i=t.length===le+ue.length&&t[0]===ue[0]&&t[1]===ue[1]?t.slice(ue.length):t;return i.length===le?i:void 0}if(e.publicKeyBase58){const t=G(e.publicKeyBase58);return t.length===le?t:void 0}}catch{return}}(e);return t?fe(t):void 0}const me=["id","delegation"];function Ie(e,t={}){const i=I(e);if(!i.success)return{valid:!1,reason:`Schema validation failed: ${i.error?.message}`};if(v(e))return{valid:!1,reason:"Delegation credential expired"};if(m(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=>!me.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 Ee(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 we=new TextEncoder,Se=new TextDecoder,Ae=new TextDecoder("utf-8",{fatal:!0});function De(...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 _e(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 be(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}const Ce="The input to be decoded is not correctly encoded.";function Te(e){if(Uint8Array.fromBase64)try{return Uint8Array.fromBase64("string"==typeof e?e:Se.decode(e),{alphabet:"base64url"})}catch(e){throw new TypeError(Ce,{cause:e})}let t=e;if(t instanceof Uint8Array&&(t=Se.decode(t)),t.includes("+")||t.includes("/"))throw new TypeError(Ce);t=t.replace(/-/g,"+").replace(/_/g,"/");try{return be(t)}catch{throw new TypeError(Ce)}}function ke(e){let t=e;return"string"==typeof t&&(t=we.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 Ne 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 Re extends Ne{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"}class Oe extends Ne{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"}class Pe extends Ne{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"}class ze extends Ne{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"}Symbol.asyncIterator;class xe extends Ne{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(e="signature verification failed",t){super(e,t)}}function Le(e){const t={__proto__:null};for(const i in e)t[i]={...e[i],alg:i};return t}const Me=[["verify"],["sign"]];function Ue(e){const t={name:"HMAC",hash:`SHA-${e}`};return{kty:["oct"],secret:!0,subtle:t,signing:t,usages:Me}}function He(e,t){const i={name:t?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:`SHA-${e}`};return{kty:["RSA"],subtle:i,signing:t?{...i,saltLength:t}:i,usages:Me,minRsaBits:2048}}function je(e,t){return{kty:["EC"],crv:e,subtle:{name:"ECDSA",namedCurve:e},signing:{name:"ECDSA",hash:`SHA-${t}`},usages:Me}}function Ke(){const e={name:"Ed25519"};return{kty:["OKP"],crv:"Ed25519",subtle:e,signing:e,usages:Me}}function $e(e){const t={name:`ML-DSA-${e}`};return{kty:["AKP"],subtle:t,signing:t,usages:Me}}const Ve=Le({HS256:Ue(256),HS384:Ue(384),HS512:Ue(512),RS256:He(256),RS384:He(384),RS512:He(512),PS256:He(256,32),PS384:He(384,48),PS512:He(512,64),ES256:je("P-256",256),ES384:je("P-384",384),ES512:je("P-521",512),EdDSA:Ke(),Ed25519:Ke(),"ML-DSA-44":$e(44),"ML-DSA-65":$e(65),"ML-DSA-87":$e(87)});function qe(e){const t="string"==typeof e?Ve[e]:void 0;if(!t)throw new Oe(`alg ${e} is not supported either by JOSE or your javascript runtime`);return t}const Be=[["encrypt","wrapKey"],["decrypt","unwrapKey"]],Fe=[[],["deriveBits"]],We=[[],[]];function Ge(e){return{kty:["RSA"],mode:"key-encryption",subtle:{name:"RSA-OAEP",hash:`SHA-${e}`},usages:Be,ops:["wrapKey","unwrapKey"]}}function Je(e){return{kty:["EC","OKP"],mode:e,subtle:{name:"ECDH"},resolve:({kty:e,crv:t,asymmetricKeyType:i})=>{if("X25519"===t||"x25519"===i)return{name:"X25519"};if("OKP"===e)throw new Oe('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');return{name:"ECDH",namedCurve:t}},usages:Fe,ops:[void 0,"deriveBits"]}}function Ye(e,t=!1){return{kty:["oct"],mode:"key-wrapping",secret:!0,subtle:{name:t?"AES-GCM":"AES-KW",length:e},usages:We,ops:t?["encrypt","decrypt"]:["wrapKey","unwrapKey"]}}function Xe(){return{kty:["oct"],mode:"key-wrapping",secret:!0,subtle:{name:"PBKDF2"},usages:We,ops:["deriveBits","deriveBits"]}}const Ze=Le({dir:{kty:["oct"],mode:"direct-encryption",secret:!0,subtle:{name:"AES-GCM"},usages:We,ops:["encrypt","decrypt"]},"RSA-OAEP":Ge(1),"RSA-OAEP-256":Ge(256),"RSA-OAEP-384":Ge(384),"RSA-OAEP-512":Ge(512),"ECDH-ES":Je("direct-key-agreement"),"ECDH-ES+A128KW":Je("key-agreement-with-key-wrapping"),"ECDH-ES+A192KW":Je("key-agreement-with-key-wrapping"),"ECDH-ES+A256KW":Je("key-agreement-with-key-wrapping"),A128KW:Ye(128),A192KW:Ye(192),A256KW:Ye(256),A128GCMKW:Ye(128,!0),A192GCMKW:Ye(192,!0),A256GCMKW:Ye(256,!0),"PBES2-HS256+A128KW":Xe(),"PBES2-HS384+A192KW":Xe(),"PBES2-HS512+A256KW":Xe()}),Qe=["encrypt","decrypt"];function et(e,t=!1){return{kty:["oct"],secret:!0,subtle:{name:t?"AES-CBC":"AES-GCM",length:e},usages:We,ops:Qe,cekBits:e,ivBits:t?128:96,cbc:t}}Le({A128GCM:et(128),A192GCM:et(192),A256GCM:et(256),"A128CBC-HS256":et(256,!0),"A192CBC-HS384":et(384,!0),"A256CBC-HS512":et(512,!0)});const tt='"alg" (Algorithm)';function it(e='JWK "alg" (Algorithm) Parameter'){throw new Oe(`Invalid or unsupported ${e} value`)}function rt(e,t){return("string"==typeof e?Ve[e]??Ze[e]:void 0)??it(t)}function nt(e){if(void 0!==e&&"boolean"!=typeof e)throw new TypeError('"extractable" option must be a boolean');return e}const ot=(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},st=e=>{const t=e.data[e.pos++];if(void 0===t)throw new Error("Unexpected end of ASN.1 input");return t},at=e=>{const t=st(e);if(128&t){const i=127&t;let r=0;for(let t=0;t<i;t++)r=r<<8|st(e);return r}return t},ct=(e,t,i)=>{if(st(e)!==t)throw new Error(i)},dt=(e,t)=>{if(t<0||e.pos+t>e.data.length)throw new Error("Unexpected end of ASN.1 input");const i=e.data.subarray(e.pos,e.pos+t);return e.pos+=t,i},ut=e=>{const t=(e=>{ct(e,6,"Expected algorithm OID");const t=at(e);return dt(e,t)})(e);if(ot(t,[43,101,110]))return"X25519";if(!ot(t,[42,134,72,206,61,2,1]))throw new Error("Unsupported key algorithm");ct(e,6,"Expected curve OID");const i=at(e),r=dt(e,i);if(ot(r,[42,134,72,206,61,3,1,7]))return"P-256";if(ot(r,[43,129,4,0,34]))return"P-384";if(ot(r,[43,129,4,0,35]))return"P-521";throw new Error("Unsupported named curve")};async function lt(e,t){if(!e.kty.includes(t.kty))throw new Oe('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');const i=e.resolve?.({kty:t.kty,crv:t.crv})??e.subtle,r=!(!t.d&&!t.priv),n={...t};return"AKP"!==n.kty&&delete n.alg,delete n.use,crypto.subtle.importKey("jwk",n,i,t.ext??!r,t.key_ops??e.usages[r?1:0])}function ht(e){if("object"!=typeof e||null===e||"[object Object]"!==Object.prototype.toString.call(e))return!1;const t=Object.getPrototypeOf(e);return null===t||null===Object.getPrototypeOf(t)}function pt(e){const t=function(e){return{__proto__:null,...e}}(e);if(void 0!==t.ext&&"boolean"!=typeof t.ext)throw new TypeError('"ext" (Extractable) Parameter must be a boolean');if(void 0!==t.key_ops){const e=t.key_ops,i=Array.isArray(e)?[...e]:void 0;if(!i||i.some(e=>"string"!=typeof e)||new Set(i).size!==i.length)throw new TypeError('"key_ops" (Key Operations) Parameter must be an array of unique strings');t.key_ops=i}return t}async function ft(e,t,i){if("string"!=typeof e||0!==e.indexOf("-----BEGIN PRIVATE KEY-----"))throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return((e,t,i)=>{const r=((e,t)=>be(e.replace(t,"")))(e,/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g);return(async(e,t,i,r)=>{const n=nt(r?.extractable),o=rt(i,tt);o.secret&&it(tt);const s="spki"===e;let a;if(o.resolve)try{const i={data:t,pos:0};(function(e,t){if(ct(e,48,`Invalid ${"spki"===t?"SPKI":"PKCS#8"} structure`),at(e),"pkcs8"===t){ct(e,2,"Expected version field");const t=at(e);e.pos+=t}ct(e,48,"Expected algorithm identifier"),at(e)})(i,e),a=o.resolve({crv:ut(i)})}catch{throw new Oe("Invalid or unsupported key format")}else a=o.subtle;return crypto.subtle.importKey(e,t,a,n??s,o.usages[s?0:1])})("pkcs8",r,t,i)})(e,t,i)}async function gt(e,t,i){if(!ht(e))throw new TypeError("JWK must be an object");const r=pt(e),n=nt(i?.extractable),{alg:o}=r;t??=o;const s=n??r.ext;if("oct"!==r.kty&&!t)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');switch(r.kty){case"oct":if("string"!=typeof r.k)throw new TypeError('missing "k" (Key Value) Parameter value');return Te(r.k);case"AKP":if("string"!=typeof o||!o)throw new TypeError('missing "alg" (Algorithm) Parameter value');if(t!==o)throw new TypeError("JWK alg and alg option value mismatch");return lt(rt(t),{...r,ext:s});case"RSA":case"EC":case"OKP":return lt(rt(t),{...r,alg:t,ext:s});default:throw new Oe('Unsupported "kty" (Key Type) Parameter value')}}const yt=(e,t="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`);async function vt(e,t,i){return t instanceof Uint8Array?crypto.subtle.importKey("raw",t,e.subtle,!1,[i]):(function(e,t,i){const r=e.algorithm;if(r.name!==t.name)throw yt(t.name);if(t.hash&&r.hash?.name!==t.hash)throw yt(t.hash,"algorithm.hash");if(t.namedCurve&&r.namedCurve!==t.namedCurve)throw yt(t.namedCurve,"algorithm.namedCurve");if(void 0!==t.length&&r.length!==t.length)throw yt(t.length,"algorithm.length");!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)}(t,e.subtle,i),e.minRsaBits&&function(e,t){const{modulusLength:i}=t.algorithm;if("number"!=typeof i||i<2048)throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}(e.alg,t),t)}function mt(e,t){if(void 0!==e)throw new TypeError(`${t} can only be called once`)}function It(e,t,i){try{return Te(e)}catch{throw new i(`Failed to base64url decode the ${t}`)}}const Et={__proto__:null,b64:!0};function wt(e,t){if(void 0!==t&&(!Array.isArray(t)||t.some(e=>"string"!=typeof e)))throw new TypeError(`"${e}" option must be an array of strings`);if(t)return new Set(t)}function St(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[];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');const o=void 0===i?t:{__proto__:null,...i,...t};for(const t of r.crit){if(!(t in o))throw new Oe(`Extension Header Parameter "${t}" is not recognized`);if(!Object.hasOwn(n,t)||void 0===n[t])throw new e(`Extension Header Parameter "${t}" is missing`);if(o[t]&&(!Object.hasOwn(r,t)||void 0===r[t]))throw new e(`Extension Header Parameter "${t}" MUST be integrity protected`)}return r.crit}function At(e,t){if(t.includes("b64")){const t=e.b64;if("boolean"!=typeof t)throw new Pe('The "b64" (base64url-encode payload) Header Parameter must be a boolean');return t}return!0}const Dt=(e,t,...i)=>function(e,t,...i){if(i.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}(`Key for the ${e} algorithm must be `,t,...i),_t=e=>{if("CryptoKey"===e?.[Symbol.toStringTag])return!0;try{return e instanceof CryptoKey}catch{return!1}},bt=e=>e[Symbol.toStringTag];function Ct(e,t,i){const{alg:r,secret:n}=e,o="decrypt"===i||"sign"===i;if(n&&t instanceof Uint8Array)return[Tt,t];if(ht(t)){const s=pt(t);if("string"!=typeof s.kty)throw new TypeError(n?Dt(r,t,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"):Dt(r,t,"CryptoKey","KeyObject","JSON Web Key"));if(!(n?"oct"===s.kty&&"string"==typeof s.k:"oct"!==s.kty&&(o?"AKP"===s.kty&&"string"==typeof s.priv||"string"==typeof s.d:void 0===s.d&&void 0===s.priv)))throw new TypeError(n?'JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present':`JSON Web Key for this operation must be a ${o?"private":"public"} JWK`);return((e,t,i)=>{const{alg:r}=e;if(void 0!==t.use){const e="sign"===i||"verify"===i?"sig":"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!==r)throw new TypeError(`Invalid key for this operation, its "alg" must be "${r}" when present`);if(Array.isArray(t.key_ops)){const r="encrypt"===i||"decrypt"===i?e.ops?.["encrypt"===i?0:1]:i;if(r&&!t.key_ops.includes(r))throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${r}" when present`)}})(e,s,i),[Rt,t,s]}if(!(e=>_t(e)||(e=>"KeyObject"===e?.[Symbol.toStringTag])(e))(t))throw new TypeError(n?Dt(r,t,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"):Dt(r,t,"CryptoKey","KeyObject","JSON Web Key"));if(n){if("secret"!==t.type)throw new TypeError(`${bt(t)} instances for symmetric algorithms must be of type "secret"`)}else{if("secret"===t.type)throw new TypeError(`${bt(t)} instances for asymmetric algorithms must not be of type "secret"`);const e=o?"private":"public";if(("public"===t.type||"private"===t.type)&&t.type!==e){const r="sign"===i?"signing":"verify"===i?"verifying":`${i.slice(0,-1)}tion`;throw new TypeError(`${bt(t)} instances for asymmetric algorithm ${r} must be of type "${e}"`)}}return _t(t)?[kt,t]:[Nt,t]}const Tt=0,kt=1,Nt=2,Rt=3;let Ot;const Pt={__proto__:null,prime256v1:"P-256",secp384r1:"P-384",secp521r1:"P-521"};function zt(e,t,i){Ot||=new WeakMap;const r=Ot.get(e);return i&&(r?r[t]=i:Ot.set(e,{[t]:i})),i??r?.[t]}const xt=async(e,t,i)=>zt(e,i.alg)??zt(e,i.alg,await lt(i,{...t,alg:i.alg}));async function Lt(e,t,i){const r=Ct(e,t,i);switch(r[0]){case Tt:case kt:return r[1];case Rt:{const t=r[1],i=r[2];if("oct"===i.kty)return Te(i.k);if(!Object.isFrozen(t)){const{key_ops:e}=t;Array.isArray(e)&&Object.freeze(e),Object.freeze(t)}return xt(t,i,e)}case Nt:{const t=r[1];return"secret"===t.type?t.export():"toCryptoKey"in t&&"function"==typeof t.toCryptoKey?((e,t)=>{const i=zt(e,t.alg);if(i)return i;const r="public"===e.type,n=t.usages[r?0:1],{asymmetricKeyType:o}=e,s=Pt[e.asymmetricKeyDetails?.namedCurve],a=t.resolve?.({crv:s,asymmetricKeyType:o})??t.subtle;return zt(e,t.alg,e.toCryptoKey(a,r,n))})(t,e):xt(t,t.export({format:"jwk"}),e)}}}async function Mt(e,t,i){if(e instanceof Uint8Array&&(e=Se.decode(e)),"string"!=typeof e)throw new Pe("Compact JWS must be a string or Uint8Array");const{0:r,1:n,2:o,length:s}=e.split(".");if(3!==s)throw new Pe("Invalid Compact JWS");const a={payload:n,protected:r,signature:o},c=function(e,t=(void 0===e?{}:function(e,t,i){let r;try{r=JSON.parse(Ae.decode(Te(e)))}catch{throw new t(i)}if(!ht(r))throw new t(i);return r}(e,Pe,"JWS Protected Header is invalid"))){return t}(r),[d,u]=function(e,t,i){const r=At(e,St(Pe,Et,i[1],e,t)),n=t.alg;if("string"!=typeof n||!n)throw new Pe('JWS "alg" (Algorithm) Header Parameter missing or invalid');if(i[0]&&!i[0].has(n))throw new Re('"alg" (Algorithm) Header Parameter value not allowed');return[r,n]}(c,c,t),l=d?n:function(e){try{return _e(e)}catch{throw new Pe("JWS Compact Serialization payload must use only ASCII characters")}}(n);return async function(e,t,i,r,n,o,s){let a=!1;"function"==typeof i&&(i=await i(n,e),a=!0);const c="string"==typeof s,d=qe(o),u=De(void 0!==r?_e(r):new Uint8Array,_e("."),c?t[2]??=function(e,t,i){try{return _e(e)}catch{throw new i("The payload is not a valid base64url string")}}(s,0,Pe):s),l=It(e.signature,"signature",Pe),h=await Lt(d,i,"verify");if(!await async function(e,t,i,r){const n=await vt(e,t,"verify");try{return await crypto.subtle.verify(e.signing,n,i,r)}catch{return!1}}(d,h,l,u))throw new xe;return[c?It(s,"payload",Pe):s,n,c,h,a]}(a,t,i,r,c,u,l)}async function Ut(e,t,i){const r=await Mt(e,function(e){return[e&&wt("algorithms",e.algorithms),e?.crit]}(i),t),n={payload:r[0],protectedHeader:r[1]};return"function"==typeof t?{...n,key:r[3]}:n}function Ht(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 jt{options;entries=new Map;insertionOrder=[];constructor(e){this.options=e}get(e){const t=this.entries.get(e);if(t){if(!(Date.now()>t.expiresAt))return t.value;this.delete(e)}}set(e,t){if(!(this.options.ttlMs<=0||this.options.maxEntries<=0)){for(this.entries.has(e)&&this.delete(e);this.entries.size>=this.options.maxEntries&&this.insertionOrder.length>0;){const e=this.insertionOrder.shift();e&&this.entries.delete(e)}this.entries.set(e,{value:t,expiresAt:Date.now()+this.options.ttlMs}),this.insertionOrder.push(e)}}delete(e){this.entries.delete(e);const t=this.insertionOrder.indexOf(e);-1!==t&&this.insertionOrder.splice(t,1)}deleteWhere(e){for(const t of[...this.entries.keys()])e(t)&&this.delete(t)}clear(){this.entries.clear(),this.insertionOrder=[]}}class Kt{didResolver;statusListResolver;signatureVerifier;cache;constructor(e){this.didResolver=e?.didResolver,this.statusListResolver=e?.statusListResolver,this.signatureVerifier=e?.signatureVerifier,this.cache=new jt({ttlMs:e?.cacheTtl??6e4,maxEntries:e?.maxCacheSize??1e3})}async verifyDelegationCredential(e,t={}){const i=Date.now(),r=this.cacheKeyForCredential("di",e,t),n=Date.now(),o=Ie(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=this.cachedSignature(r,()=>t.skipSignature?Promise.resolve({valid:!0,durationMs:0}):async function(e,t,i){const r=Date.now();try{const o="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};if(e.proof&&("string"!=typeof(n=e.proof.type)||!g.has(n)))return{valid:!1,reason:`Unsupported credential proof.type: ${String(e.proof.type)}`,durationMs:Date.now()-r};const s=await t.resolve(o);if(!s)return{valid:!1,reason:`Could not resolve issuer DID: ${o}`,durationMs:Date.now()-r};if(!e.proof)return{valid:!1,reason:"Proof is missing",durationMs:Date.now()-r};const a=e.proof.verificationMethod;if(!a)return{valid:!1,reason:"Proof missing verificationMethod",durationMs:Date.now()-r};const c=function(e,t){return e.verificationMethod?.find(e=>e.id===t)}(s,a);if(!c)return{valid:!1,reason:`Verification method ${a} not found`,durationMs:Date.now()-r};const d=ve(c);if(!d)return{valid:!1,reason:"Verification method has no usable public key (publicKeyJwk / publicKeyMultibase / publicKeyBase58)",durationMs:Date.now()-r};const u=await i(e,d);return{valid:u.valid,reason:u.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}}var n}(e,t.didResolver||this.didResolver,this.signatureVerifier)),c=!t.skipStatus&&e.credentialStatus?Ee(e.credentialStatus,t.statusListResolver||this.statusListResolver):Promise.resolve({valid:!0,durationMs:0});return this.finalizeVerification(a,c,s,i)}async verifyDelegationJwt(e,t={}){const i=Date.now(),r=function(e,t){const i=$(e);if(!i)return{failure:Ht("Not a valid VC-JWT (parse failed)",t)};const r=Date.now(),n=i.payload.vc,o=Ie(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:Ht("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:Ht(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),d=this.cachedSignature(c,()=>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");const c=ve(a);if(!c)return o(!1,"Verification method has no usable public key (publicKeyJwk / publicKeyMultibase / publicKeyBase58)");try{const t=await gt(c,"EdDSA");return await Ut(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?Ee(n.credentialStatus,t.statusListResolver||this.statusListResolver):Promise.resolve({valid:!0,durationMs:0});return this.finalizeVerification(d,u,a,i)}async cachedSignature(e,t){if(null!==e){const t=this.cache.get(e);if(t)return{result:{...t,durationMs:0},cached:!0}}const i=await t();return i.valid&&null!==e&&this.cache.set(e,i),{result:i,cached:!1}}async finalizeVerification(e,t,i,r){const[n,o]=await Promise.all([e,t]),s=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}}}(n.result,o,i,r);return n.cached&&(s.cached=!0),s}cacheKeyForCredential(e,t,i){if(!this.cacheAllowed(i))return null;try{return`${e}\0${t.id??""}\0${M(t)}`}catch{return null}}cacheKeyForJwt(e,t,i){return this.cacheAllowed(i)?`jwt\0${t.id??""}\0${e}`:null}cacheAllowed(e){return!e.skipCache&&!e.skipSignature&&void 0===e.didResolver&&void 0===e.statusListResolver}clearCache(){this.cache.clear()}clearCacheEntry(e){const t=`di\0${e}\0`,i=`jwt\0${e}\0`;this.cache.deleteWhere(e=>e.startsWith(t)||e.startsWith(i))}}function $t(e){return new Kt(e)}class Vt{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 qt(e){return new Vt(e)}const Bt=16777216,Ft="u";async function Wt(e,t){const i=e[0]===Ft?e.slice(1):e,r=await t(s(i));if(r.length>Bt)throw new Error(`Status list too large: ${r.length} bytes exceeds ${Bt}`);return r instanceof Uint8Array?r:new Uint8Array(r)}class Gt{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 Ft+this.base64urlEncode(e)}static async decode(e,t,i){const r=await Wt(e,e=>i.decompress(e)),n=8*r.length,o=new Gt(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 Gt(e,i,r);for(const e of t)n.setBit(e,!0);return n}}async function Jt(e,t,i){return function(e,t){const i=Number.isInteger(t)&&t>=0?e[Math.floor(t/8)]:void 0;if(void 0===i)throw new Error(`Bit index ${t} out of range for the status list`);return!!(i&128>>t%8)}(await Wt(e,e=>i.decompress(e)),t)}class Yt{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 Gt.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=H(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 Gt.decode(r.credentialSubject.encodedList,this.compressor,this.decompressor),o=function(e){if(!/^[0-9]+$/.test(e))throw new Error(`Invalid statusListIndex "${e}" — must be a canonical non-negative decimal`);const t=Number(e);if(!Number.isSafeInteger(t))throw new Error(`statusListIndex "${e}" exceeds the safe integer range`);return t}(i);return n.getBit(o)}async getRevokedIndices(e){const t=await this.storage.getStatusList(e);return t?(await Gt.decode(t.credentialSubject.encodedList,this.compressor,this.decompressor)).getSetBits():[]}async ensureStatusListExists(e,t){if(await this.storage.getStatusList(e))return;const i=new Gt(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=H(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 Xt(e,t,i,r,n,o){return new Yt(e,t,i,r,n,o)}class Zt{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 Qt(e,t){return new Zt(e,t)}function ei(e,t){if(!e.constraints.audience)return!0;const i=e.constraints.audience;return"string"==typeof i?i===t:i.includes(t)}async function ti(e,t,i,r,n){const[o,s]=function(e){if(void 0===e)return[void 0,""];const t=function(e,t){let i,r;try{i=JSON.stringify(t),r=JSON.parse(i)}catch(t){throw new e("JOSE Header is not valid JSON",{cause:t})}if(!ht(r))throw new e("JOSE Header is not a JSON object");return[r,i]}(Pe,e);return[t[0],ke(t[1])]}(t);if(!o)throw new Pe("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");(function(e,t,i){return function(e,t){const{crit:i}=t??{};if(Array.isArray(i)&&new Set(i).size!==i.length)throw new e('"crit" (Critical) Header Parameter MUST NOT contain duplicate values')}(Pe,e),At(e,St(Pe,Et,i,e,t))})(o,o,i)||n();const a=function(e){const t=e.alg;if("string"!=typeof t||!t)throw new Pe('JWS "alg" (Algorithm) Header Parameter missing or invalid');return qe(t)}(o),c=ke(e);return`${s}.${c}.${await async function(e,t,i,r){const n=De(_e(e),_e("."),t),o=await Lt(i,r,"sign");return ke(await async function(e,t,i){const r=await vt(e,t,"sign"),n=await crypto.subtle.sign(e.signing,r,i);return new Uint8Array(n)}(i,o,n))}(s,_e(c),a,r)}`}const ii=e=>Math.floor(e.getTime()/1e3),ri={s:1,m:60,h:3600,d:86400,w:604800,y:31557600},ni=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;function oi(){throw new TypeError("Invalid time period format")}function si(e){"string"!=typeof e&&oi();const t=ni.exec(e);(!t||t[4]&&t[1])&&oi();const i=parseFloat(t[2]),r=Math.round(i*ri[t[3][0].toLowerCase()]);return Number.isFinite(r)||oi(),"-"===t[1]||"ago"===t[4]?-r:r}function ai(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}function ci(e,t){if("string"!=typeof t)throw new TypeError(`"${e}" claim must be a string`)}function di(e,t){return"number"==typeof e?ai(t,e):e instanceof Date?ai(t,ii(e)):ii(new Date)+si(e)}let ui;function li(e){return ui.get(e)}const hi=class{constructor(e={}){if(!ht(e))throw new TypeError("JWT Claims Set MUST be an object");(ui||=new WeakMap).set(this,structuredClone(e))}setIssuer(e){return ci("iss",e),li(this).iss=e,this}setSubject(e){return ci("sub",e),li(this).sub=e,this}setAudience(e){return function(e){if("string"!=typeof e&&(!Array.isArray(e)||Array.from(e).some(e=>"string"!=typeof e)))throw new TypeError('"aud" claim must be a string or an array of strings')}(e),li(this).aud=e,this}setJti(e){return ci("jti",e),li(this).jti=e,this}setNotBefore(e){return li(this).nbf=di(e,"setNotBefore"),this}setExpirationTime(e){return li(this).exp=di(e,"setExpirationTime"),this}setIssuedAt(e){return li(this).iat=void 0===e?ii(new Date):"string"==typeof e?ai("setIssuedAt",ii(new Date)+si(e)):di(e,"setIssuedAt"),this}};class pi extends hi{#e;setProtectedHeader(e){return mt(this.#e,"setProtectedHeader"),this.#e=e,this}async sign(e,t){return ti(function(e){const t=li(e);for(const e of["iat","nbf","exp"]){const i=t[e];if("number"==typeof i&&!Number.isFinite(i))throw new TypeError(`"${e}" claim must be a finite number`)}return we.encode(JSON.stringify(t))}(this),this.#e,t?.crit,e,()=>{throw new ze("JWTs MUST NOT use unencoded payload")})}}async function fi(e){const{agentDid:t,userDid:i,delegationId:r,delegationChain:n,scopes:o,privateKeyJwk:s,kid:a,targetHostname:c}=e,d=await gt(s,"EdDSA"),u=Math.floor(Date.now()/1e3),l=u+60;return await new pi({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 gi(e){return e.id||e.vcId?e.vcId?`${e.vcId}>${e.id}`:e.id:""}const yi={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 vi(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 de.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(!he(t))throw new Error(`Server DID must be did:key with Ed25519: ${t}`);const n=pe(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 fi({agentDid:r.did,userDid:t.agentDid,delegationId:i.id,delegationChain:i.vcId,scopes:["delegation:propagate"],privateKeyJwk:s,kid:r.kid,targetHostname:o});return de.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 mi{#t;#e;constructor(e){if(!(e instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this.#t=e}setProtectedHeader(e){return mt(this.#e,"setProtectedHeader"),this.#e=e,this}async sign(e,t){return ti(this.#t,this.#e,t?.crit,e,()=>{throw new TypeError("use the flattened module for creating JWS with b64: false")})}}class Ii{cryptoProvider;constructor(e){this.cryptoProvider=e}async verifyEd25519(e,t,i){try{return!0===await this.cryptoProvider.verify(e,t,i)}catch(e){return de.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 de.error("[CryptoService] Invalid Ed25519 JWK format"),!1;if(i?.expectedKid&&t.kid!==i.expectedKid)return de.error("[CryptoService] Key ID mismatch"),!1;let r;try{r=this.parseJWS(e)}catch(t){if(void 0===i?.detachedPayload)return de.error("[CryptoService] Invalid JWS format:",t),!1;{const i=e.split(".");if(3!==i.length||""!==i[1])return de.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 de.error("[CryptoService] Invalid detached JWS format"),!1}}}const n=i?.alg||"EdDSA";if(r.header.alg!==n)return de.error(`[CryptoService] Unsupported algorithm: ${r.header.alg}, expected ${n}`),!1;if(void 0!==i?.expectedKid&&r.header.kid!==i.expectedKid)return de.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 de.error("[CryptoService] Missing signing input for compact JWS"),!1;a=(new TextEncoder).encode(r.signingInput)}try{d=this.jwkToBase64PublicKey(t)}catch(e){return de.error("[CryptoService] Failed to extract public key:",e),!1}return await this.verifyEd25519(a,r.signatureBytes,d)}catch(e){return de.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 Ei=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]),wi=12,Si=32,Ai="org.kya-os/response-proof",Di="org.kya-os/proof",_i="proof";async function bi(e,t,i,r=_){const n={method:e.method,...e.params?{params:e.params}:{}},o=await i(U(n));if(void 0===t)return{requestHash:o};const s=await i(U(function(e,t){if(t!==b||null===e||"object"!=typeof e||Array.isArray(e))return e;const i={};for(const[t,r]of Object.entries(e))"_meta"!==t&&(i[t]=r);return i}(t.data,r)));return{requestHash:o,responseHash:s}}function Ci(e){return{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},...e.prf&&{prf:e.prf}}}class Ti{identity;cryptoProvider;constructor(e,t){this.identity=e,this.cryptoProvider=t}async generateProof(e,t,i,r={}){const{profile:n=_,...o}=r;Reflect.deleteProperty(o,"prf");const s=await this.generateCanonicalHashes(e,t,n),a=c(await this.cryptoProvider.randomBytes(16)),d={did:this.identity.did,kid:this.identity.kid,ts:Math.floor(Date.now()/1e3),nonce:a,audience:i.audience,sessionId:i.sessionId,requestHash:s.requestHash,...void 0!==s.responseHash?{responseHash:s.responseHash}:{},...n===b?{prf:b}:{},...o};return{jws:await this.generateJWS(d),meta:d}}async hashRequest(e){return(await this.generateCanonicalHashes(e)).requestHash}async generateCanonicalHashes(e,t,i){return bi(e,t,e=>this.cryptoProvider.hash(e),i)}async resolveSigningKey(){const e=this.identity.privateKey;return"string"==typeof e?ft(this.formatPrivateKeyAsPEM(e),"EdDSA"):e}async generateJWS(e){try{const t=await this.resolveSigningKey(),i=M(Ci(e)),r=(new TextEncoder).encode(i);return await new mi(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,Si),i=new Uint8Array(Ei.length+t.length);i.set(Ei),i.set(t,Ei.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,e.meta.prf??_);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 Ii(this.cryptoProvider).verifyJWS(e.jws,n,{expectedKid:this.identity.kid,alg:"EdDSA"})}catch{return!1}}base64PublicKeyToJWK(e){const t=u(e);if(t.length!==Si)throw new Error(`Invalid Ed25519 public key length: ${t.length}`);return{kty:"OKP",crv:"Ed25519",x:c(t),kid:this.identity.kid}}}async function ki(e,t,i,r,n,o={}){const s={data:t},a=new Ti(i,n),c=await a.generateProof(e,s,r,o);return s.meta={proof:c},s}function Ni(e,t){return{request:{method:e.method,...e.params?{params:e.params}:{}},response:t.data}}const Ri="_kyaos";function Oi(e){return e.startsWith(Ri)}function Pi(e,t){const i={};for(const[e,r]of Object.entries(t))Oi(e)||(i[e]=r);return{method:e,params:i}}async function zi(e){const{identity:t,crypto:i,toolName:r,args:n,audience:o,sessionId:s}=e,a=new Ti(t,i),d=Pi(r,n),u=c(await i.randomBytes(16)),l=Math.floor(Date.now()/1e3),h=s??`req-${c(await i.randomBytes(9))}`;return a.generateProof(d,void 0,{sessionId:h,audience:o,nonce:u,timestamp:l,createdAt:l,lastActivity:l,ttlMinutes:30,identityState:"anonymous"})}const xi="holder_binding_failed";function Li(e){return null!==pe(e)}async function Mi(e){const{proof:t,subjectDid:i,request:r,response:n,expectedAudience:o,proofVerifier:s}=e,a=pe(i);if(!a)return{status:"not_applicable",reason:`Holder binding (phase 1) covers did:key subjects only; "${X(i)??"unknown"}" is deferred to cnf-based binding`};if("object"!=typeof t?.meta||null===t.meta)return{status:"unbound",errorCode:xi,reason:"Malformed proof: missing meta"};if(t.meta.did!==i)return{status:"unbound",errorCode:xi,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:xi,reason:"Proof audience does not match this server",cause:"audience_mismatch"};const c=fe(a);c.kid=`${i}#${se(i)}`;const d=await s.verifyProof(t,c,{request:r,...void 0!==n?{response:n}:{}});return d.valid?{status:"bound"}:{status:"unbound",errorCode:xi,reason:"Request proof is not bound to the delegation subject",...void 0!==d.errorCode?{cause:d.errorCode}:{}}}function Ui(e){return structuredClone(e)}class Hi{statusLists=new Map;versions=new Map;indexCounters=new Map;async getStatusList(e){const t=this.statusLists.get(e);return void 0===t?null:Ui(t)}async setStatusList(e,t){const i=Ui(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:Ui(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 ji{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 Ki(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 $i(e){return e.startsWith("did:web:")}function Vi(e){if(!$i(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 qi(e){const t=Vi(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 Bi{fetchProvider;cache;cacheTtl;constructor(e,t){this.fetchProvider=e,this.cache=new Map,this.cacheTtl=t?.cacheTtl??3e5}async resolve(e){if(!$i(e))return null;const t=this.cache.get(e);if(t&&Date.now()<t.expiresAt)return t.document;const i=qi(e);if(!i)return de.warn(`[DidWebResolver] Invalid did:web format: ${e}`),null;try{const t=await this.fetchProvider.fetch(i);if(!t.ok)return de.warn(`[DidWebResolver] HTTP ${t.status} fetching ${i}`),null;let r;try{r=await t.json()}catch{return de.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(!Ki(e))return!1}return!0}(r)?r.id!==e?(de.warn(`[DidWebResolver] DID Document id mismatch: expected ${e}, got ${r.id}`),null):(this.cache.set(e,{document:r,expiresAt:Date.now()+this.cacheTtl}),r):(de.warn(`[DidWebResolver] Invalid DID Document structure from ${i}`),null)}catch(t){return de.warn(`[DidWebResolver] Error resolving ${e}: ${t instanceof Error?t.message:"Unknown error"}`),null}}clearCache(){this.cache.clear()}clearCacheEntry(e){this.cache.delete(e)}}function Fi(e,t){return new Bi(e,t)}const Wi=new Uint8Array([237,1]),Gi=["https://www.w3.org/ns/did/v1","https://w3id.org/security/suites/ed25519-2020/v1"];function Ji(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(!$i(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:fe(i),publicKeyMultibase:Yi(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?[...Gi,...t.additionalContexts]:[...Gi],id:n,...t?.alsoKnownAs?.length?{alsoKnownAs:[...t.alsoKnownAs]}:{},verificationMethod:o,authentication:s,assertionMethod:s}}function Yi(e){const t=new Uint8Array(Wi.length+e.length);return t.set(Wi),t.set(e,Wi.length),`z${W(t)}`}function Xi(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Zi(e){const t=e.requireBidirectional??!0,i=er(e.primaryDid),r=er(e.secondaryDid),n=e.primaryDidDocument,o=e.secondaryDidDocument,s={primaryReferencesSecondary:!1,secondaryReferencesPrimary:!1,primaryDocumentMatches:!1,secondaryDocumentMatches:!1};return tr(n)?tr(o)?(s.primaryDocumentMatches=er(n.id)===i,s.secondaryDocumentMatches=er(o.id)===r,s.primaryDocumentMatches&&s.secondaryDocumentMatches?(s.primaryReferencesSecondary=Qi(n,r),s.secondaryReferencesPrimary=Qi(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 Qi(e,t){return(e.alsoKnownAs??[]).some(e=>er(e)===t)}function er(e){return e.trim()}function tr(e){return!!Xi(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 ir(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 rr{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 nr(e,t,i){const r=Date.now();let n,o;if(i.debug&&de.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){de.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&&de.debug(`[AuthHandshake] Reputation score: ${n.score}`),null===n.score){if("deny"===r)return{authorized:!1,authError:await or(e,t,i,"Unknown agent denied by policy"),reputation:n,reason:"Unknown agent — policy: deny"};if("require-consent"===r)return{authorized:!1,authError:await or(e,t,i,"Unknown agent requires consent"),reputation:n,reason:"Unknown agent — policy: require-consent"};i.debug&&de.debug("[AuthHandshake] Unknown agent allowed by policy, skipping reputation gate")}if(null!==n.score&&n.score<i.authorization.minReputationScore)return i.debug&&de.debug(`[AuthHandshake] Reputation ${n.score} < ${i.authorization.minReputationScore}, requiring authorization`),{authorized:!1,authError:await or(e,t,i,"Agent reputation score below threshold"),reputation:n,reason:"Low reputation score"}}try{o=await i.delegationVerifier.verify(e,t)}catch(r){de.error("[AuthHandshake] Delegation verification failed:",r);const n=`Delegation verification error: ${r instanceof Error?r.message:"Unknown error"}`;return{authorized:!1,authError:await or(e,t,i,n),reason:n}}return o.valid&&o.delegation?(i.debug&&de.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&&de.debug(`[AuthHandshake] No delegation found, returning needs_authorization (${Date.now()-r}ms)`),{authorized:!1,authError:await or(e,t,i,o.reason??"No valid delegation found"),reputation:n,reason:o.reason??"No delegation"})}async function or(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 C({message:r,authorizationUrl:s.toString(),resumeToken:n,expiresAt:o,scopes:t,display:a})}function sr(e){const t=["write","delete","admin","payment","transfer","execute","modify"];return e.some(e=>t.some(t=>e.toLowerCase().includes(t)))}const ar={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 cr extends Error{code;details;constructor(e,t,i){super(t),this.code=e,this.details=i,this.name="ProofVerificationError"}}function dr(e,t,i){return new cr(e,t,i)}const ur=120,lr=30,hr=600;class pr{cryptoService;clock;nonceCache;fetch;timestampSkewSeconds;nonceTtlSeconds;cryptoProvider;constructor(e){this.cryptoService=new Ii(e.cryptoProvider),this.cryptoProvider=e.cryptoProvider,this.clock=e.clockProvider,this.nonceCache=e.nonceCacheProvider,this.fetch=e.fetchProvider,this.timestampSkewSeconds=e.timestampSkewSeconds??ur,this.nonceTtlSeconds=e.nonceTtlSeconds??300}setTimestampSkew(e){"number"==typeof e&&Number.isFinite(e)&&(this.timestampSkewSeconds=Math.max(lr,Math.min(hr,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 bi(t.request,t.response,e=>this.cryptoProvider.hash(e),e.meta.prf??_);if(e.meta.requestHash!==i)return{valid:!1,reason:"Request hash mismatch: the proof does not bind the request you supplied",errorCode:ar.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:ar.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:ar.CONTENT_BINDING_MISMATCH}:{valid:!0}}handleVerificationError(e){return{valid:!1,reason:"Proof verification error",errorCode:ar.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=O(e);return t.success?{valid:!0,proof:t.data}:{valid:!1,reason:"Invalid proof structure",errorCode:ar.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:ar.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:ar.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:ar.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 cr(ar.DID_DOCUMENT_NOT_FOUND,`DID document not found: ${e}`,{did:e});const r=i;if(!r.verificationMethod||0===r.verificationMethod.length)throw new cr(ar.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 cr(ar.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 cr(ar.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 cr(ar.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 cr)throw i;throw de.error("[ProofVerifier] Failed to fetch public key from DID",{error:i}),new cr(ar.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 M(Ci(e))}}const fr=["io.modelcontextprotocol/"],gr=["traceparent","tracestate","baggage"];function yr(e){return gr.includes(e)||fr.some(t=>e.startsWith(t))}function vr(e,t="strict"){const i=Object.keys(e).filter(e=>e!==Ai&&e!==Di&&e!==_i);return"allow-extensions"===t&&i.length>0?{valid:!0,extraKeys:i}:{valid:!0}}function mr(e,t="strict"){const i=e[Ai]??e[Di]??e[_i];if(!i)return{success:!1,reason:"_meta does not contain a proof",errorCode:ar.MISSING_REQUIRED_FIELD};vr(e,t);const r=O(i);return r.success?{success:!0,proof:r.data}:{success:!1,reason:r.error?.message??"Invalid proof structure",errorCode:ar.INVALID_PROOF_STRUCTURE}}class Ir{}class Er{}class wr{}class Sr{}class Ar{}class Dr{}class _r extends Sr{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 br extends Ar{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 Cr extends Dr{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}#${se(t)}`,privateKey:e.privateKey,publicKey:e.publicKey,createdAt:(new Date).toISOString(),type:"development"}}generateDIDFromPublicKey(e){return oe(e)}}class Tr{}class kr extends Tr{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 Nr{config;cryptoProvider;sessionStore;constructor(e,t={}){this.cryptoProvider=e,this.sessionStore=t.sessionStore??new kr({maxSessions:t.maxSessions??1e4}),this.config={timestampSkewSeconds:t.timestampSkewSeconds??120,sessionTtlMinutes:t.sessionTtlMinutes??30,nonceCache:t.nonceCache??new br,metaPolicy:t.metaPolicy??"strict",...void 0!==t.absoluteSessionLifetime&&{absoluteSessionLifetime:t.absoluteSessionLifetime},...void 0!==t.serverDid&&{serverDid:t.serverDid}},this.config.nonceCache instanceof br&&de.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?A:D,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 Rr(e){return{nonce:Nr.generateNonce(),audience:e,timestamp:Math.floor(Date.now()/1e3)}}function Or(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 Pr=i(77598);const zr=Buffer.from("302e020100300506032b657004220420","hex"),xr=Buffer.from("302a300506032b6570032100","hex");class Lr extends Ir{async sign(e,t){const i=Buffer.from(t,"base64"),r=64===i.length?i.subarray(0,32):i,n=(0,Pr.createPrivateKey)({key:Buffer.concat([zr,r]),format:"der",type:"pkcs8"});return new Uint8Array((0,Pr.sign)(null,Buffer.from(e),n))}async verify(e,t,i){try{const r=(0,Pr.createPublicKey)({key:Buffer.concat([xr,Buffer.from(i,"base64")]),format:"der",type:"spki"});return(0,Pr.verify)(null,Buffer.from(e),r,Buffer.from(t))}catch{return!1}}async generateKeyPair(){const{publicKey:e,privateKey:t}=(0,Pr.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,Pr.createHash)("sha256").update(Buffer.from(e)).digest("hex")}`}async randomBytes(e){return new Uint8Array((0,Pr.randomBytes)(e))}}class Mr extends Er{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 Ur extends wr{didKeyResolver=ge();didWebResolver;didResolvers;allowPrivateNetworkHosts;constructor(e){super(),this.allowPrivateNetworkHosts=e?.allowPrivateNetworkHosts??!1,this.didResolvers=ir(e?.didResolvers,this)}async resolveDID(e){const t=X(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):$i(e)?this.isBlockedTarget(qi(e))?null:(this.didWebResolver||(this.didWebResolver=Fi(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 Hr extends wr{async resolveDID(e){return null}async fetchStatusList(e){return null}async fetchDelegationChain(e){return[]}async fetch(e,t){throw new Error("fetch unavailable")}}function jr(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 Kr{}class $r extends Kr{records=[];events=[];loggedSessions=new Set;async logAuditRecord(e){const t=e.session.sessionId;this.loggedSessions.has(t)||(this.loggedSessions.add(t),this.records.push(jr(e)))}async logEvent(e){this.events.push(e)}}class Vr extends Kr{async logAuditRecord(e){}async logEvent(e){}}const qr=["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 Br=i(11569);const Fr="https://schema.kya-os.org/v1/protocol/audit/event/v1.0.0",Wr="https://schema.kya-os.org/v1/protocol/audit/entry/v1.0.0",Gr="https://schema.kya-os.org/v1/protocol/audit/receipt/v1.0.0",Jr="KYA-AUDIT-JCS-SHA256-JWS-2026",Yr="https://schema.kya-os.org/v1/protocol/audit/checkpoint/v1.0.0",Xr="KYA-AUDIT-RFC9162-SHA256-JWS-2026",Zr="https://schema.kya-os.org/v1/protocol/audit/bundle-manifest/v1.0.0",Qr="KYA-AUDIT-BUNDLE-JCS-SHA256-JWS-2026",en=256,tn=4096,rn=Br.z.string().max(20).regex(/^(0|[1-9][0-9]*)$/),nn=Br.z.string().regex(/^sha256:[a-f0-9]{64}$/),on=Br.z.string().min(5).max(2048).regex(/^did:[^\r\n]+$/),sn=Br.z.object({did:on,kid:Br.z.string().min(1).max(2304),alg:Br.z.enum(["EdDSA","ES256"])}).strict(),an=Br.z.object({objectId:Br.z.string().min(1).max(en),ciphertextDigest:nn,plaintextCommitment:nn.optional(),mediaType:Br.z.string().min(1).max(en),size:rn,encryption:Br.z.object({suite:Br.z.literal("A256GCM"),keyId:Br.z.string().min(1).max(en),nonce:Br.z.string().min(1).max(en),aadDigest:nn}).strict()}).strict(),cn=Br.z.discriminatedUnion("kind",[Br.z.object({kind:Br.z.literal("public_did"),did:on}).strict(),Br.z.object({kind:Br.z.literal("pairwise_did"),did:on}).strict(),Br.z.object({kind:Br.z.literal("keyed_commitment"),value:nn,keyId:Br.z.string().min(1).max(en)}).strict(),Br.z.object({kind:Br.z.literal("evidence_ref"),ref:an}).strict()]),dn=[Br.z.object({family:Br.z.literal("session"),phase:Br.z.enum(["established","rejected","expired","replay_rejected"]),reasonCode:Br.z.string().min(1).max(128).optional()}).strict(),Br.z.object({family:Br.z.literal("tool"),phase:Br.z.enum(["started","completed","failed","denied","challenged"]),attempt:rn,idempotencyRef:Br.z.string().min(1).max(en).optional()}).strict(),Br.z.object({family:Br.z.literal("proof"),phase:Br.z.enum(["generated","verified","rejected"]),proofDigest:nn.optional(),verificationCode:Br.z.string().min(1).max(128).optional()}).strict(),Br.z.object({family:Br.z.literal("delegation"),phase:Br.z.enum(["issued","verified","rejected","revoked","cascade_revoked","outbound_attached"]),delegationRef:Br.z.string().min(1).max(en),parentRef:Br.z.string().min(1).max(en).optional(),statusEvidence:Br.z.array(an).max(256).optional()}).strict(),Br.z.object({family:Br.z.literal("authorization"),phase:Br.z.enum(["evaluated","approved","denied","step_up_required","grant_used"]),policyDigest:nn.optional(),grantRef:Br.z.string().min(1).max(en).optional()}).strict(),Br.z.object({family:Br.z.literal("consent"),phase:Br.z.enum(["requested","approved","denied","credential_required","credential_verified","credential_failed"]),consentRef:Br.z.string().min(1).max(en).optional()}).strict(),Br.z.object({family:Br.z.literal("key"),phase:Br.z.enum(["rotated","policy_changed","configuration_changed","integrity_suite_transitioned"]),previousSigner:sn.optional(),nextSigner:sn.optional(),configurationDigest:nn.optional()}).strict(),Br.z.object({family:Br.z.literal("ledger"),phase:Br.z.enum(["epoch_started","epoch_transitioned","checkpoint_created","checkpoint_anchored","checkpoint_anchor_failed","evidence_disposed","projection_reconciled"]),checkpointDigest:nn.optional(),previousEpochId:Br.z.string().min(1).max(en).optional(),previousTerminalCheckpointDigest:nn.optional(),successorEpochIds:Br.z.array(Br.z.string().min(1).max(en)).max(256).optional(),targetEvidenceRef:an.optional()}).strict(),Br.z.object({family:Br.z.literal("administration"),phase:Br.z.enum(["source_high_water","accessed","exported","legal_hold_applied","retention_executed"]),purpose:Br.z.string().min(1).max(en).optional(),sourceSequence:rn.optional(),selectionDigest:nn.optional()}).strict()],un=Br.z.discriminatedUnion("family",dn),ln=Br.z.object({source:Br.z.enum(["delegation","grant","anonymous","policy"]),decision:Br.z.enum(["allowed","denied","step_up_required","needs_authorization"]),scopeId:Br.z.string().min(1).max(en).optional(),delegationRef:Br.z.string().min(1).max(en).optional(),delegationCredentialDigest:nn.optional(),delegationChainDigests:Br.z.array(nn).max(256).optional(),statusEvidence:Br.z.array(an).max(256).optional(),grantRef:Br.z.string().min(1).max(en).optional(),policyId:Br.z.string().min(1).max(en).optional(),policyVersion:Br.z.string().min(1).max(en).optional(),policyDigest:nn.optional(),verificationCode:Br.z.string().min(1).max(128).optional()}).strict(),hn=Br.z.object({schema:Br.z.literal(Fr),eventId:Br.z.string().min(1).max(256),eventType:Br.z.enum(qr),eventVersion:Br.z.literal("1.0.0"),binding:Br.z.string().max(en).regex(/^urn:kya-os:audit-binding:[a-z0-9][a-z0-9._:-]*$/),occurredAt:Br.z.number().int().nonnegative(),tenantRef:cn,source:Br.z.object({producer:cn,sourceId:Br.z.string().min(1).max(256),sourceSequence:rn.optional(),previousSourceEventDigest:nn.optional()}).strict(),correlationId:Br.z.string().min(1).max(256).optional(),causationId:Br.z.string().min(1).max(256).optional(),trace:Br.z.object({traceId:Br.z.string().regex(/^[a-f0-9]{32}$/).optional(),spanId:Br.z.string().regex(/^[a-f0-9]{16}$/).optional()}).strict().optional(),session:Br.z.object({ref:cn,handshakeNonceCommitment:nn.optional()}).strict().optional(),actor:cn.optional(),responsibleParty:cn.optional(),resource:cn.optional(),action:Br.z.object({category:Br.z.string().min(1).max(128),name:Br.z.string().min(1).max(256).optional(),detailRef:an.optional()}).strict(),outcome:Br.z.enum(["succeeded","failed","denied","challenged","unknown"]),reason:Br.z.object({code:Br.z.string().min(1).max(128),detailRef:an.optional()}).strict().optional(),authorization:ln.optional(),proof:an.optional(),evidence:Br.z.array(an).max(256),details:un,privacy:Br.z.object({classification:Br.z.enum(["public","internal","confidential","restricted"]),retentionClass:Br.z.string().min(1).max(128),legalHold:Br.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}`})}),pn=Br.z.object({schema:Br.z.literal(Wr),ledgerId:Br.z.string().min(1).max(256),ledgerEpochId:Br.z.string().min(1).max(256),sequence:rn,previousEntryDigest:nn.nullable(),recordedAt:Br.z.number().int().nonnegative(),recorder:sn,eventDigest:nn,event:hn,evidenceManifestDigest:nn,integritySuite:Br.z.literal(Jr)}).strict(),fn=Br.z.object({schema:Br.z.literal(Gr),ledgerId:Br.z.string().min(1).max(256),ledgerEpochId:Br.z.string().min(1).max(256),sequence:rn,eventId:Br.z.string().min(1).max(256),entryDigest:nn,previousEntryDigest:nn.nullable(),recordedAt:Br.z.number().int().nonnegative(),recorder:sn,integritySuite:Br.z.literal(Jr)}).strict(),gn=Br.z.object({schema:Br.z.literal(Yr),checkpointId:Br.z.string().min(1).max(512),ledgerId:Br.z.string().min(1).max(256),ledgerEpochId:Br.z.string().min(1).max(256),treeSize:rn,firstSequence:rn,lastSequence:rn,rootDigest:nn,headEntryDigest:nn,previousCheckpointDigest:nn.nullable(),createdAt:Br.z.number().int().nonnegative(),issuer:sn,integritySuite:Br.z.literal(Xr)}).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"})}),yn=Br.z.object({core:gn,checkpointDigest:nn,jws:Br.z.string().min(1).max(tn)}).strict(),vn=Br.z.object({core:pn,eventDigest:nn,entryDigest:nn,recorderReceipt:Br.z.object({core:fn,jws:Br.z.string().min(1).max(tn)}).strict()}).strict(),mn=Br.z.object({core:Br.z.object({schema:Br.z.literal("https://schema.kya-os.org/v1/protocol/audit/observation/v1.0.0"),observerId:Br.z.string().min(1).max(256),observer:sn,ledgerId:Br.z.string().min(1).max(256),ledgerEpochId:Br.z.string().min(1).max(256),checkpointDigest:nn,treeSize:rn,observedAt:Br.z.number().int().nonnegative(),previousObservationDigest:nn.nullable()}).strict(),observationDigest:nn,jws:Br.z.string().min(1).max(tn)}).strict(),In=Br.z.object({schema:Br.z.literal("https://schema.kya-os.org/v1/protocol/audit/anchor-receipt/v1.0.0"),kind:Br.z.enum(["worm","rfc3161","scitt"]),providerId:Br.z.string().min(1).max(256),checkpointDigest:nn,issuedAt:Br.z.number().int().nonnegative(),receiptData:Br.z.string().min(1).max(65536).optional()}).strict(),En=Br.z.object({leafIndex:rn,treeSize:rn,auditPath:Br.z.array(nn)}).strict(),wn=Br.z.object({oldTreeSize:rn,newTreeSize:rn,auditPath:Br.z.array(nn)}).strict(),Sn=Br.z.object({ledgerId:Br.z.string().min(1).max(256),ledgerEpochId:Br.z.string().min(1).max(256),sequence:rn,entryDigest:nn,checkpointDigest:nn,proof:En}).strict(),An=Br.z.object({ledgerId:Br.z.string().min(1).max(256),ledgerEpochId:Br.z.string().min(1).max(256),oldCheckpointDigest:nn,newCheckpointDigest:nn,proof:wn}).strict(),Dn=Br.z.object({ledgerId:Br.z.string().min(1).max(256),ledgerEpochId:Br.z.string().min(1).max(256),firstSequence:rn,lastSequence:rn,expectedHeadDigest:nn,checkpointTreeSizes:Br.z.array(rn).max(256)}).strict().superRefine((e,t)=>{BigInt(e.lastSequence)<BigInt(e.firstSequence)&&t.addIssue({code:"custom",message:"Bundle selection range is reversed"})}),_n=Br.z.object({path:Br.z.string().min(1).max(1024),mediaType:Br.z.string().min(1).max(256),disposition:Br.z.enum(["included","redacted","disposed","unavailable","policy_excluded"]),digest:nn.optional(),size:rn.optional(),reasonCode:Br.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"})}),bn=Br.z.object({schema:Br.z.literal(Zr),bundleId:Br.z.string().min(1).max(256),formatVersion:Br.z.literal("1.0.0"),selections:Br.z.array(Dn).min(1),exporter:sn,purpose:Br.z.string().min(1).max(256),exportedAt:Br.z.number().int().nonnegative(),verificationPolicyDigest:nn,inventory:Br.z.array(_n).max(1e4),integritySuite:Br.z.literal(Qr)}).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"})}),Cn=_n.extend({content:Br.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{L(e.content)}catch(e){t.addIssue({code:"custom",path:["content"],message:e instanceof Error?e.message:"Content is not canonical JSON"})}}),Tn=Br.z.object({manifest:Br.z.object({core:bn,manifestDigest:nn,jws:Br.z.string().min(1).max(tn)}).strict(),components:Br.z.array(Cn)}).strict();function kn(e){return new Set(e).size===e.length}const Nn=Br.z.object({signer:sn,validFrom:Br.z.number().int().nonnegative().optional(),validUntil:Br.z.number().int().nonnegative().optional(),validFromCheckpoint:nn.optional(),validUntilCheckpoint:nn.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"})}),Rn=Br.z.object({policyId:Br.z.string().min(1).max(256),trustedLedgerEpochs:Br.z.array(Br.z.object({ledgerId:Br.z.string().min(1).max(256),ledgerEpochId:Br.z.string().min(1).max(256),recorderKeys:Br.z.array(Nn).min(1),validFromCheckpoint:nn.optional(),validUntilCheckpoint:nn.optional()}).strict()),trustedObservers:Br.z.array(Nn),trustedSupportingAnchors:Br.z.array(Br.z.object({kind:Br.z.enum(["worm","rfc3161","scitt"]),providerId:Br.z.string().min(1).max(256),validFrom:Br.z.number().int().nonnegative().optional(),validUntil:Br.z.number().int().nonnegative().optional()}).strict()).optional(),authorizedExporters:Br.z.array(Br.z.object({signerKeys:Br.z.array(Nn).min(1),allowedLedgerIds:Br.z.array(Br.z.string().min(1).max(256)).min(1).refine(kn,"Allowed ledger IDs must be unique"),allowedPurposes:Br.z.array(Br.z.string().min(1).max(256)).min(1).refine(kn,"Allowed purposes must be unique")}).strict()),acceptedIntegritySuites:Br.z.array(Br.z.string().min(1).max(128)).min(1).refine(kn,"Accepted integrity suites must be unique"),acceptedAlgorithms:Br.z.array(Br.z.enum(["EdDSA","ES256"])).min(1).refine(kn,"Accepted algorithms must be unique"),keyRevocationMode:Br.z.enum(["as_observed","current","both"]),requiredCheckpointFreshnessMs:Br.z.number().int().nonnegative().optional(),requiredAuditProfile:Br.z.enum(["AAP-0","AAP-1","AAP-2","AAP-3","AAP-4"]).optional()}).strict();function On(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))On(i,t);return Object.freeze(e)}function Pn(e){return On(structuredClone(e))}function zn(e){return Pn(hn.parse(e))}function xn(e){return Pn(pn.parse(e))}function Ln(e){return Pn(vn.parse(e))}function Mn(e){return Pn(fn.parse(e))}function Un(e){return Pn(gn.parse(e))}function Hn(e){return Pn(yn.parse(e))}function jn(e){return Pn(mn.parse(e))}function Kn(e){return Pn(bn.parse(e))}function $n(e){return Pn(Tn.parse(e))}function Vn(e){return Pn(Rn.parse(e))}const qn=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 Bn(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 Fn=new TextEncoder,Wn=/^sha256:[a-f0-9]{64}$/;class Gn{crypto;constructor(e){this.crypto=e}async sha256(e){const t=await this.crypto.hash(e);if(!Wn.test(t))throw new TypeError("Audit hasher must return sha256:<lowercase-hex>");return t}}class Jn{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 Ut(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 Yn{ref;privateKey;constructor(e,t){this.ref=e,this.privateKey=t}async sign(e){return new mi(e).setProtectedHeader({alg:this.ref.alg,kid:this.ref.kid}).sign(this.privateKey)}}async function Xn(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=Fn.encode(`${t}\0`),n=U(i),o=new Uint8Array(r.length+n.length);return o.set(r),o.set(n,r.length),e.sha256(o)}function Zn(e){return"evidence_ref"===e?.kind?[e.ref]:[]}function Qn(e){const t="delegation"===e.details.family?e.details.statusEvidence??[]:"ledger"===e.details.family&&void 0!==e.details.targetEvidenceRef?[e.details.targetEvidenceRef]:[];return[...Zn(e.tenantRef),...Zn(e.source.producer),...Zn(e.session?.ref),...Zn(e.actor),...Zn(e.responsibleParty),...Zn(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 eo=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 to(e){return{refs:Qn(e)}}function io(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 ro(e,t){return Xn(e,eo.event,t)}async function no(e,t){return Xn(e,eo.entry,t)}async function oo(e,t){return Xn(e,eo.evidenceManifest,to(t))}const so={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 ao extends Error{code;details;constructor(e,t,i,r){super(t,r),this.code=e,this.details=i,this.name="AuditProtocolError"}}class co{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:lo(t),additionalData:lo(e.aad),tagLength:128},e.key,lo(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 ao(so.EVIDENCE_INTEGRITY,"Evidence ciphertext or authenticated metadata digest does not match");try{const r=await this.config.crypto.subtle.decrypt({name:"AES-GCM",iv:lo(s(e.ref.encryption.nonce)),additionalData:lo(i),tagLength:128},t,lo(e.ciphertext));return new Uint8Array(r)}catch(e){throw new ao(so.EVIDENCE_INTEGRITY,"Evidence AEAD verification failed",void 0,{cause:e})}}}class uo{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 ao(so.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 ao(so.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 ao(so.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 ao(so.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 lo(e){return Uint8Array.from(e).buffer}const ho=/^sha256:([a-f0-9]{64})$/;function po(e){const t=ho.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 fo(...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 go(e){let t=1;for(;2*t<e;)t*=2;return t}function yo(e,t){if(!Number.isSafeInteger(e)||e<0)throw new RangeError(`${t} must be a non-negative safe integer`)}class vo{hasher;constructor(e){this.hasher=e}async leafHash(e){return this.hasher.sha256(fo(Uint8Array.of(0),po(e)))}async nodeHash(e,t){return this.hasher.sha256(fo(Uint8Array.of(1),po(e),po(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=go(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(yo(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=go(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(yo(e.leafIndex,"Leaf index"),yo(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(yo(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=go(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(yo(e.oldSize,"Old tree size"),yo(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 mo(e){return`${e.ledgerId}\0${e.ledgerEpochId}`}function Io(e,t){return`${mo(e)}\0${t}`}function Eo(e,t){if(!/^(0|[1-9][0-9]*)$/.test(e))throw new ao(so.CHECKPOINT_INVALID,`${t} must be a canonical non-negative decimal string`);return BigInt(e)}function wo(e,t){if(e>BigInt(Number.MAX_SAFE_INTEGER))throw new ao(so.CHECKPOINT_INVALID,`${t} exceeds this implementation's safe in-memory proof range`);return Number(e)}function So(e){if("object"!=typeof e||null===e||Object.isFrozen(e))return e;for(const t of Object.values(e))So(t);return Object.freeze(e)}class Ao{checkpoints=new Map;latest=new Map;async getLatest(e){return this.latest.get(mo(e))??null}async getByTreeSize(e,t){return this.checkpoints.get(Io(e,t))??null}async putIfAbsent(e){const t=e.core,i=Io(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=So(e);this.checkpoints.set(i,n);const o=this.latest.get(mo(t));return(void 0===o||BigInt(o.core.treeSize)<BigInt(e.core.treeSize))&&this.latest.set(mo(t),n),{kind:"inserted",checkpoint:n}}}class Do{options;tree;clock;constructor(e){this.options=e,this.tree=new vo(e.hasher),this.clock=e.clock??Date}async createCheckpoint(e){const t=await this.snapshotAtHead(e);if(0===t.length)throw new ao(so.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=Eo(r.core.treeSize,"Previous tree size");if(e>BigInt(t.length))throw new ao(so.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 ao(so.CHECKPOINT_CONFLICT,"Journal content forked at the latest checkpointed tree size");return r}}const n=t[0],o=t[t.length-1],s=Un({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=So({core:s,checkpointDigest:await Xn(this.options.hasher,eo.checkpoint,s),jws:await this.options.signer.sign(U(s))}),c=await this.options.store.putIfAbsent(a);if("conflict"===c.kind)throw new ao(so.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 ao(so.CHECKPOINT_INVALID,"Sequence is not included in the checkpoint",{sequence:t,treeSize:i.core.treeSize});return So({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=wo(Eo(t,"Old tree size"),"Old tree size");return So({oldTreeSize:t,newTreeSize:i.core.treeSize,auditPath:await this.tree.consistencyProof(r.map(e=>e.entryDigest),n)})}async rootForRange(e,t){const i=wo(Eo(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 ao(so.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:wo(Eo(i.leafIndex,"Leaf index"),"Leaf index"),treeSize:wo(Eo(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:wo(Eo(e.oldTreeSize,"Old tree size"),"Old tree size"),newSize:wo(Eo(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=wo(Eo(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 ao(so.JOURNAL_FAILURE,"Journal could not provide a stable range through its reported head");return r}async entriesForCheckpoint(e,t){const i=wo(Eo(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 ao(so.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 ao(so.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 ao(so.LEDGER_MISMATCH,"Checkpoint belongs to a different ledger or epoch")}}class _o{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 ao(so.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 ao(so.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 ao(so.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 bo(e,t){return`${e}\0${t.ledgerId}\0${t.ledgerEpochId}`}function Co(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 To{capabilities={durability:"ephemeral",atomicOffset:!0};offsets=new Map;records=new Map;async getOffset(e,t){const i=this.offsets.get(bo(e,t));return void 0===i?null:{...i}}async compareAndApply(e){const t=bo(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=bo(e,t);this.offsets.delete(i),this.records.delete(i)}async read(e,t){return(this.records.get(bo(e,t))??[]).map(e=>({...e}))}corruptOffsetForTesting(e,t,i){this.offsets.set(bo(e,t),{...i})}}class ko{options;constructor(e){if(this.options=e,!e.projectionId)throw new ao(so.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:Co(n)});if("conflict"===o.kind)throw new ao(so.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 No=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 Ro(e,t=[]){return{verdict:e,reasonCodes:[...new Set(t)].sort()}}function Oo(e,t){return e.did===t.did&&e.kid===t.kid&&e.alg===t.alg}function Po(e,t){return(void 0===e.validFrom||t>=e.validFrom)&&(void 0===e.validUntil||t<=e.validUntil)}class zo{options;constructor(e){this.options=e}async verifyEntries(e,t){if(!Rn.safeParse(t).success)return function(e){const t="object"==typeof e&&null!==e&&"string"==typeof e.policyId?e.policyId:"invalid-policy",i=Ro("invalid",[No.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:Ro("indeterminate",[No.NOT_EVALUATED]),currentAuthorization:Ro("indeterminate",[No.NOT_EVALUATED])}}(t);const i=t,r=new Set,n=new Set,o=[];0===e.length&&n.add(No.BUNDLE_SELECTION_INCOMPLETE);for(const t of e){const e=vn.safeParse(t);if(!e.success){r.add(No.SCHEMA_INVALID),n.add(No.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?[Ro("indeterminate",[s?No.AUTHORIZATION_COLLATERAL_NOT_VERIFIED:No.AUTHORIZATION_EVIDENCE_MISSING]),Ro("indeterminate",[No.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:Ro(0===r.size&&e.length>0?"valid":"invalid",r),chainIntegrity:Ro(0===n.size&&e.length>0?"valid":"invalid",n),checkpointIntegrity:Ro("indeterminate",[No.CHECKPOINT_MISSING]),anchorIntegrity:Ro("indeterminate",[No.OBSERVER_EVIDENCE_MISSING]),scopeEvidenceCompleteness:Ro(e.length>0?"indeterminate":"invalid",[No.NOT_EVALUATED]),authorizedAsObserved:a,currentAuthorization:c}}async verifyCheckpoint(e,t,i){const r=new Set;if(!Rn.safeParse(i).success)return Ro("invalid",[No.VERIFICATION_POLICY_INVALID]);const n=yn.safeParse(e);if(!n.success)return Ro("invalid",[No.SCHEMA_INVALID]);const o=n.data,s=o.core;i.acceptedIntegritySuites.includes(s.integritySuite)||r.add(No.UNSUPPORTED_SUITE),i.acceptedAlgorithms.includes(s.issuer.alg)||r.add(No.UNSUPPORTED_ALGORITHM);const a=i.trustedLedgerEpochs.find(e=>e.ledgerId===s.ledgerId&&e.ledgerEpochId===s.ledgerEpochId);a?.recorderKeys.some(e=>Oo(e.signer,s.issuer)&&Po(e,s.createdAt))||r.add(No.UNTRUSTED_RECORDER),await Xn(this.options.hasher,eo.checkpoint,s)!==o.checkpointDigest&&r.add(No.CHECKPOINT_DIGEST_MISMATCH),await this.options.signatures.verify(U(s),o.jws,s.issuer)||r.add(No.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(No.CHECKPOINT_RANGE_MISMATCH):await new vo(this.options.hasher).root(t.map(e=>e.entryDigest))!==s.rootDigest&&r.add(No.CHECKPOINT_ROOT_MISMATCH),Ro(0===r.size?"valid":"invalid",r)}async verifyObservation(e,t,i){const r=new Set;let n=!1;if(!Rn.safeParse(i).success)return Ro("invalid",[No.VERIFICATION_POLICY_INVALID]);const o=yn.safeParse(e),s=mn.safeParse(t);if(!o.success||!s.success)return Ro("invalid",[No.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(No.SCHEMA_INVALID),d.ledgerId===a.core.ledgerId&&d.ledgerEpochId===a.core.ledgerEpochId&&d.checkpointDigest===a.checkpointDigest&&d.treeSize===a.core.treeSize||r.add(No.OBSERVATION_SCOPE_MISMATCH),i.acceptedAlgorithms.includes(d.observer.alg)||r.add(No.UNSUPPORTED_ALGORITHM),i.trustedObservers.some(e=>Oo(e.signer,d.observer)&&Po(e,d.observedAt))||r.add(No.UNTRUSTED_OBSERVER),void 0!==i.requiredCheckpointFreshnessMs){const e=this.options.verifiedAt?.();void 0===e?(r.add(No.NOT_EVALUATED),n=!0):e-d.observedAt>i.requiredCheckpointFreshnessMs&&r.add(No.OBSERVATION_STALE)}await Xn(this.options.hasher,eo.observation,d)!==c.observationDigest&&r.add(No.OBSERVATION_DIGEST_MISMATCH),await this.options.signatures.verify(U(d),c.jws,d.observer)||r.add(No.OBSERVATION_SIGNATURE_INVALID);const u=n&&[...r].every(e=>e===No.NOT_EVALUATED);return Ro(0===r.size?"valid":u?"indeterminate":"invalid",r)}async verifyEntry(e,t,i){t.acceptedIntegritySuites.includes(e.core.integritySuite)||i.add(No.UNSUPPORTED_SUITE),t.acceptedAlgorithms.includes(e.core.recorder.alg)||i.add(No.UNSUPPORTED_ALGORITHM);const r=t.trustedLedgerEpochs.find(t=>t.ledgerId===e.core.ledgerId&&t.ledgerEpochId===e.core.ledgerEpochId),n=r?.recorderKeys.find(t=>Oo(t.signer,e.core.recorder)&&Po(t,e.core.recordedAt));void 0===n&&i.add(No.UNTRUSTED_RECORDER);const o=await ro(this.options.hasher,e.core.event);o===e.core.eventDigest&&o===e.eventDigest||i.add(No.EVENT_DIGEST_MISMATCH),await oo(this.options.hasher,e.core.event)!==e.core.evidenceManifestDigest&&i.add(No.EVIDENCE_MANIFEST_DIGEST_MISMATCH),await no(this.options.hasher,e.core)!==e.entryDigest&&i.add(No.ENTRY_DIGEST_MISMATCH),function(e,t){try{return M(e)===M(t)}catch{return!1}}(io(e.core,e.entryDigest),e.recorderReceipt.core)||i.add(No.RECEIPT_MISMATCH),await this.options.signatures.verify(U(e.recorderReceipt.core),e.recorderReceipt.jws,e.core.recorder)||i.add(No.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(No.LEDGER_SCOPE_MISMATCH);try{BigInt(e.core.sequence)!==BigInt(t.core.sequence)+1n&&r.add(No.SEQUENCE_GAP)}catch{r.add(No.SEQUENCE_GAP)}e.core.previousEntryDigest!==t.entryDigest&&r.add(No.PREDECESSOR_MISMATCH)}else"0"===e.core.sequence?null===e.core.previousEntryDigest&&"ledger.epoch.started"===e.core.event.eventType||r.add(No.GENESIS_INVALID):0===i&&null===e.core.previousEntryDigest&&r.add(No.PREDECESSOR_MISMATCH)}}function xo(...e){return 0===e.length?Ro("indeterminate",[No.NOT_EVALUATED]):Ro(e.some(e=>"invalid"===e.verdict)?"invalid":e.every(e=>"valid"===e.verdict)?"valid":"indeterminate",e.flatMap(e=>e.reasonCodes))}const Lo="https://schema.kya-os.org/v1/protocol/audit/bundle-manifest/v1.0.0",Mo=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 Uo(e){if("object"!=typeof e||null===e||Object.isFrozen(e))return e;for(const t of Object.values(e))Uo(t);return Object.freeze(e)}function Ho(e){return JSON.parse(M(e))}function jo(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 Ko(e,t){return(void 0===e.validFrom||t>=e.validFrom)&&(void 0===e.validUntil||t<=e.validUntil)}function $o(e,t=[]){return{verdict:e,reasonCodes:[...new Set(t)].sort()}}class Vo{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(jo(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=Ho(e.content),i=U(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=>qo(e)),o=Kn({schema:Lo,bundleId:e.bundleId,formatVersion:"1.0.0",selections:Ho([...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 Uo({manifest:{core:o,manifestDigest:await Xn(this.options.hasher,eo.bundleManifest,o),jws:await this.options.signer.sign(U(o))},components:r})}}function qo(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 Bo(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 Fo(e){return`${e.ledgerId}\0${e.ledgerEpochId}`}function Wo(e,t){const i=BigInt(e),r=BigInt(t);return i<r?-1:i>r?1:0}function Go(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(No.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(No.BUNDLE_SELECTION_INCOMPLETE)}for(const e of i)"redacted"===e.disposition&&r.add(No.EXPLICITLY_REDACTED),"disposed"===e.disposition&&r.add(No.EXPLICITLY_DISPOSED),"unavailable"===e.disposition&&r.add(No.EXPLICITLY_UNAVAILABLE);return r.has(No.BUNDLE_SELECTION_INCOMPLETE)?$o("invalid",r):0===r.size?$o("valid"):$o("indeterminate",r)}async function Jo(e,t,i){if(!Rn.safeParse(t).success){const e="string"==typeof t?.policyId?t.policyId:"invalid-policy",i=$o("invalid",[No.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:$o("indeterminate",[No.NOT_EVALUATED]),currentAuthorization:$o("indeterminate",[No.NOT_EVALUATED])}}if(!Tn.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:$o("invalid",[No.BUNDLE_SCHEMA_INVALID]),chainIntegrity:$o("invalid",[No.BUNDLE_SCHEMA_INVALID]),checkpointIntegrity:$o("indeterminate",[No.CHECKPOINT_MISSING]),anchorIntegrity:$o("indeterminate",[No.OBSERVER_EVIDENCE_MISSING]),scopeEvidenceCompleteness:$o("invalid",[No.BUNDLE_SCHEMA_INVALID]),authorizedAsObserved:$o("indeterminate",[No.AUTHORIZATION_COLLATERAL_NOT_VERIFIED]),currentAuthorization:$o("indeterminate",[No.CURRENT_AUTHORIZATION_NOT_EVALUATED])}}(t);const r=e,n=new Set,o=r.manifest.core;if(o?.schema===Lo&&"1.0.0"===o.formatVersion||n.add(No.BUNDLE_SCHEMA_INVALID),t.acceptedIntegritySuites.includes(o?.integritySuite??"")||n.add(No.UNSUPPORTED_SUITE),void 0!==o&&t.acceptedAlgorithms.includes(o.exporter.alg)||n.add(No.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&&Ko(t,e.exportedAt);var i,r}))}(o,t)||n.add(No.BUNDLE_EXPORTER_UNAUTHORIZED),void 0!==o){const[e,s]=await Promise.all([Xn(i.hasher,eo.bundleManifest,o),Xn(i.hasher,"org.kya-os.audit.verification-policy.v1",t)]);e!==r.manifest.manifestDigest&&n.add(No.BUNDLE_MANIFEST_DIGEST_MISMATCH),s!==o.verificationPolicyDigest&&n.add(No.VERIFICATION_POLICY_MISMATCH),await i.signatures.verify(U(o),r.manifest.jws,o.exporter)||n.add(No.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(No.BUNDLE_INVENTORY_MISMATCH);for(const[e,t]of a){const r=c.get(e);if(void 0!==r&&M(t)===M(qo(r))){try{jo(e)}catch{n.add(No.BUNDLE_SCHEMA_INVALID)}if("included"===r.disposition){if(void 0===r.content){n.add(No.BUNDLE_INVENTORY_MISMATCH);continue}const e=U(r.content);r.size===String(e.length)&&r.digest===await i.hasher.sha256(e)||n.add(No.BUNDLE_COMPONENT_DIGEST_MISMATCH)}else void 0===r.content&&void 0!==r.reasonCode||n.add(No.BUNDLE_INVENTORY_MISMATCH)}else n.add(No.BUNDLE_INVENTORY_MISMATCH)}}const s=Bo(r,Mo.entries),a=Bo(r,Mo.checkpoints),c=Bo(r,Mo.observations),d=Bo(r,Mo.anchors),u=i.artifacts??new zo(i),l=await async function(e,t,i){const r=new Map,n=[];for(const t of e){if(!vn.safeParse(t).success){n.push(t);continue}const e=t,i=Fo(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:xo(...o.map(e=>e.cryptographicIntegrity)),chainIntegrity:xo(...o.map(e=>e.chainIntegrity)),checkpointIntegrity:xo(...o.map(e=>e.checkpointIntegrity)),anchorIntegrity:xo(...o.map(e=>e.anchorIntegrity)),scopeEvidenceCompleteness:xo(...o.map(e=>e.scopeEvidenceCompleteness)),authorizedAsObserved:xo(...o.map(e=>e.authorizedAsObserved)),currentAuthorization:xo(...o.map(e=>e.currentAuthorization))}}(s,t,u),h=s.filter(e=>vn.safeParse(e).success),p=a.filter(e=>yn.safeParse(e).success);let f=l.checkpointIntegrity;if(a.length>0){const e=[];for(const i of a){if(!yn.safeParse(i).success){e.push($o("invalid",[No.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=xo(...e,function(e,t,i){const r=new Set,n=new Map;for(const t of e){const e=Fo(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(No.CHECKPOINT_FORK_DETECTED):n.core.previousCheckpointDigest!==i.checkpointDigest&&r.add(No.CHECKPOINT_CHAIN_MISMATCH)}}for(const e of i){const t=(n.get(Fo(e))??[]).map(e=>e.core.treeSize).sort(Wo),i=[...e.checkpointTreeSizes].sort(Wo);M(t)!==M(i)&&r.add(No.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(No.CHECKPOINT_CHAIN_MISMATCH)}return $o(0===r.size?"valid":"invalid",r)}(p,h,o.selections),await async function(e,t,i,r){const n=new Set,o=new vo(r),s=Bo(e,Mo.inclusionProofs);for(const e of s){if(!Sn.safeParse(e).success){n.add(No.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(No.MERKLE_PROOF_INVALID)}const a=Bo(e,Mo.consistencyProofs);for(const e of a){if(!An.safeParse(e).success){n.add(No.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(No.MERKLE_PROOF_INVALID)}return $o(0===n.size?"valid":"invalid",n)}(r,h,p,i.hasher))}else o.selections.some(e=>e.checkpointTreeSizes.length>0)&&(f=$o("invalid",[No.CHECKPOINT_MISSING]));let g=l.anchorIntegrity;if(c.length>0){const e=[];for(const i of c){if(!mn.safeParse(i).success){e.push($o("invalid",[No.SCHEMA_INVALID]));continue}const r=i,n=p.find(e=>e.checkpointDigest===r.core.checkpointDigest);e.push(void 0===n?$o("invalid",[No.OBSERVATION_SCOPE_MISMATCH]):await u.verifyObservation(n,r,t))}const i=c.filter(e=>mn.safeParse(e).success);g=xo(...e,function(e){const t=new Set,i=new Map;for(const t of e){const e=`${Fo(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||Wo(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(No.OBSERVATION_CHAIN_MISMATCH)}return $o(0===t.size?"valid":"invalid",t)}(i))}d.length>0&&(g=xo(g,await async function(e,t,i,r){const n=new Set;let o=!1;for(const s of e){if(!In.safeParse(s).success){n.add(No.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&&Ko(t,e.issuedAt))??!1)||n.add(No.UNTRUSTED_SUPPORTING_ANCHOR),void 0===a?n.add(No.SUPPORTING_ANCHOR_INVALID):void 0===r?(n.add(No.NOT_EVALUATED),o=!0):await r(a,e)||n.add(No.SUPPORTING_ANCHOR_INVALID)}return $o([...n].some(e=>e!==No.NOT_EVALUATED)?"invalid":o?"indeterminate":"valid",n)}(d,p,t,i.verifySupportingAnchor)));const y=$o(0===n.size?"valid":"invalid",n);return{...l,cryptographicIntegrity:xo(y,l.cryptographicIntegrity),checkpointIntegrity:f,anchorIntegrity:g,scopeEvidenceCompleteness:Go(o?.selections??[],h,r.components.filter(e=>"included"!==e.disposition))}}class Yo{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 ao(so.INVALID_CONFIGURATION,"Buffered audit delivery requires a durable outbox provider");if(void 0!==e.capabilities){if(e.capabilities.delivery!==e.delivery)throw new ao(so.INVALID_CONFIGURATION,"Advertised audit delivery does not match the trail delivery mode");if(Bn(e.capabilities),e.capabilities.sourceHighWater&&"durable"!==e.sourceState.capabilities.durability)throw new ao(so.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 ro(this.configuration.hasher,r);return await this.sourceState.markEmitted(this.configuration.sourceId,t,i.sequence,n),r}buildEvent(e,t,i){return zn({...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(Qn(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||M(t)!==M(e.ref))throw new ao(so.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 ro(this.configuration.hasher,e.producerEvent);if(t.core.ledgerId!==e.ledgerId||t.eventDigest!==i||t.core.eventDigest!==i||M(t.core.event)!==M(e.producerEvent))throw new ao(so.JOURNAL_FAILURE,"Recorder response does not bind the submitted frozen producer event");return t}}function Xo(e){return new Yo(e)}class Zo{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 ao(so.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 ao(so.MIRROR_VERIFICATION_FAILED,"Mirror rejected an entry that failed historical artifact verification",{reasonCodes:t.cryptographicIntegrity.reasonCodes});const i=await Xn(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 ao(so.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 ao(so.MIRROR_CONTINUITY_FAILED,"Mirror entry does not exactly extend the observed recorder chain")}}function Qo(e){if("object"!=typeof e||null===e||Object.isFrozen(e))return e;for(const t of Object.values(e))Qo(t);return Object.freeze(e)}function es(e,t){return null===e||null===t?e===t:e.entryDigest===t.entryDigest&&e.sequence===t.sequence}function ts(e,t){return M(e)===M(t)}function is(e,t,i){return void 0!==t?ts(t,i):("public_did"===i.kind||"pairwise_did"===i.kind)&&i.did===e}class rs{config;maxAppendConflicts;initialization;constructor(e){if(this.config=e,void 0===e.previousEpochId!=(void 0===e.previousTerminalCheckpointDigest))throw new ao(so.INVALID_CONFIGURATION,"Previous epoch ID and terminal checkpoint digest must be supplied together");if(void 0!==e.previousEpochId&&void 0===e.epochTransitionGuard)throw new ao(so.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=zn(e.producerEvent);if(this.validateEventAuthority(i,t),void 0!==this.config.authorizer&&!await this.config.authorizer.authorize({submission:e,context:t}))throw new ao(so.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 ao(so.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 ao(so.UNAUTHORIZED_SUBMISSION,"Authenticated producer and tenant authority are required");if(e.ledgerId!==this.config.ledgerId)throw new ao(so.LEDGER_MISMATCH,"Wrong audit ledger")}validateEventAuthority(e,t){if(!is(t.producerAuthority,t.producerRef,e.source.producer))throw new ao(so.UNAUTHORIZED_SUBMISSION,"Event producer does not match the authenticated producer authority");if(!ts(e.tenantRef,this.config.tenantRef)||!is(t.tenantAuthority,t.tenantRef,e.tenantRef))throw new ao(so.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 ao(so.EVIDENCE_FAILURE,"Encrypted evidence was submitted but no evidence provider is configured");try{const i=new Map(Qn(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||M(e)!==M(t.ref))throw new ao(so.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 ao&&e.code===so.EVIDENCE_FAILURE)throw e;throw new ao(so.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 ao(so.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 ao(so.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=Ln(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||!ts(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 ao(so.JOURNAL_FAILURE,"Existing ledger genesis does not match the authoritative recorder configuration",void 0,{cause:e})}var t,i}genesisEvent(){return zn({schema:Fr,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 ao(so.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(es(t,s.actualHead))throw new ao(so.JOURNAL_FAILURE,"Audit journal reported a head conflict without advancing its head")}throw new ao(so.APPEND_CONFLICT_EXHAUSTED,"Audit append conflict retry budget exhausted")}async identifyEvent(e,t){return{eventDigest:await ro(this.config.hasher,e),idempotencyKey:await Xn(this.config.hasher,eo.idempotency,{ledgerId:this.config.ledgerId,producerAuthority:t.producerAuthority,sourceId:e.source.sourceId,eventId:e.eventId})}}resolveDuplicate(e,t){if(e.eventDigest!==t)throw new ao(so.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 ao(so.JOURNAL_FAILURE,r?"Genesis must be the first epoch entry":"Producer event cannot replace genesis");const o=this.config.clock.now(),s=await oo(this.config.hasher,e),a=xn({schema:Wr,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:Jr}),c=await no(this.config.hasher,a),d=io(a,c);return Qo({core:a,eventDigest:t,entryDigest:c,recorderReceipt:{core:d,jws:await this.config.signer.sign(U(d))}})}ledgerRef(){return{ledgerId:this.config.ledgerId,ledgerEpochId:this.config.ledgerEpochId}}}const ns=100,os=1e3;function ss(e){return{ledgerId:e.ledgerId,ledgerEpochId:e.ledgerEpochId}}class as{journal;checkpoints;constructor(e){this.journal=e.journal,this.checkpoints=e.checkpoints}getHead(e){return this.journal.getHead(ss(e))}async listEntries(e){const t=function(e){return void 0!==e&&Number.isFinite(e)?Math.max(1,Math.min(os,Math.trunc(e))):ns}(e.limit),i=ss(e),r=[];for await(const n of this.journal.readRange({...i,...void 0===e.afterSequence?{}:{afterSequence:e.afterSequence},limit:t+1}))if(r.push(n),r.length>t)break;const n=r.length>t,o=n?r.slice(0,t):r,s=n?o[o.length-1].core.sequence:null;return{entries:o,head:await this.journal.getHead(i),nextAfterSequence:s}}async getLatestCheckpoint(e){return this.requireCheckpoints().store.getLatest(ss(e))}async getInclusionProof(e){const t=this.requireCheckpoints(),i=ss(e),r=await this.requireLatestCheckpoint(t,i),n=await this.entryAtSequence(i,e.sequence),o=await t.builder.inclusionProof(i,e.sequence,r);return Object.freeze({ledgerId:i.ledgerId,ledgerEpochId:i.ledgerEpochId,sequence:e.sequence,entryDigest:n.entryDigest,checkpointDigest:r.checkpointDigest,proof:o})}async getConsistencyProof(e){const t=this.requireCheckpoints(),i=ss(e),r=await this.requireLatestCheckpoint(t,i),n=await t.store.getByTreeSize(i,e.oldTreeSize);if(null===n)throw new ao(so.CHECKPOINT_INVALID,"No signed checkpoint exists at the requested old tree size",{oldTreeSize:e.oldTreeSize});const o=await t.builder.consistencyProof(i,e.oldTreeSize,r);return Object.freeze({ledgerId:i.ledgerId,ledgerEpochId:i.ledgerEpochId,oldCheckpointDigest:n.checkpointDigest,newCheckpointDigest:r.checkpointDigest,proof:o})}requireCheckpoints(){if(void 0===this.checkpoints)throw new ao(so.INVALID_CONFIGURATION,"This read service was built without checkpoint access; proofs are unavailable");return this.checkpoints}async requireLatestCheckpoint(e,t){const i=await e.store.getLatest(t);if(null===i)throw new ao(so.CHECKPOINT_INVALID,"No signed checkpoint exists for this ledger yet",{ledgerId:t.ledgerId});return i}async entryAtSequence(e,t){const i=function(e,t){if(!/^(0|[1-9][0-9]*)$/.test(e))throw new ao(so.CHECKPOINT_INVALID,`${t} must be a canonical non-negative decimal string`,{[t]:e});return BigInt(e)}(t,"sequence"),r=i>1n?String(i-1n):void 0;for await(const i of this.journal.readRange({...e,...void 0===r?{}:{afterSequence:r},limit:1})){if(i.core.sequence===t)return i;break}throw new ao(so.CHECKPOINT_INVALID,"No entry exists at the requested sequence",{sequence:t})}}function cs(e){return new as(e)}const ds="https://schema.kya-os.org/v1/protocol/audit/head-request/v1.0.0",us="https://schema.kya-os.org/v1/protocol/audit/head-response/v1.0.0",ls="https://schema.kya-os.org/v1/protocol/audit/list-entries-request/v1.0.0",hs="https://schema.kya-os.org/v1/protocol/audit/list-entries-response/v1.0.0",ps="https://schema.kya-os.org/v1/protocol/audit/inclusion-proof-request/v1.0.0",fs="https://schema.kya-os.org/v1/protocol/audit/inclusion-proof-response/v1.0.0",gs="https://schema.kya-os.org/v1/protocol/audit/consistency-proof-request/v1.0.0",ys="https://schema.kya-os.org/v1/protocol/audit/consistency-proof-response/v1.0.0",vs=Br.z.object({ledgerId:Br.z.string().min(1).max(256),ledgerEpochId:Br.z.string().min(1).max(256)}).strict(),ms=Br.z.object({ledgerId:Br.z.string().min(1).max(256),ledgerEpochId:Br.z.string().min(1).max(256),sequence:rn,entryDigest:nn}).strict();function Is(e){if("object"!=typeof e||null===e||Object.isFrozen(e))return e;for(const t of Object.values(e))Is(t);return Object.freeze(e)}const Es=Br.z.object({schema:Br.z.literal(ds),ledger:vs}).strict(),ws=Br.z.object({schema:Br.z.literal(us),head:ms.nullable()}).strict(),Ss=Br.z.object({schema:Br.z.literal(ls),ledger:vs,afterSequence:rn.optional(),limit:Br.z.number().int().positive().max(os).optional()}).strict(),As=Br.z.object({schema:Br.z.literal(hs),entries:Br.z.array(vn),head:ms.nullable(),nextAfterSequence:rn.nullable()}).strict(),Ds=Br.z.object({schema:Br.z.literal(ps),ledger:vs,sequence:rn}).strict(),_s=Br.z.object({schema:Br.z.literal(fs),proof:Sn}).strict(),bs=Br.z.object({schema:Br.z.literal(gs),ledger:vs,oldTreeSize:rn}).strict(),Cs=Br.z.object({schema:Br.z.literal(ys),proof:An}).strict();function Ts(e){return Is(Es.parse(e))}function ks(e){return Is(ws.parse(e))}function Ns(e){return Is(Ss.parse(e))}function Rs(e){return Is(As.parse(e))}function Os(e){return Is(Ds.parse(e))}function Ps(e){return Is(_s.parse(e))}function zs(e){return Is(bs.parse(e))}function xs(e){return Is(Cs.parse(e))}function Ls(e){return{schema:us,head:e}}function Ms(e){return{schema:hs,entries:e.entries,head:e.head,nextAfterSequence:e.nextAfterSequence}}function Us(e){return{schema:fs,proof:e}}function Hs(e){return{schema:ys,proof:e}}function js(e){const t=e?.modulusLength??2048;if("number"!=typeof t||!Number.isInteger(t)||t<2048)throw new Oe("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return t}const Ks="Ed25519",$s=Uint8Array.from([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]);function Vs(){if("undefined"==typeof crypto||!crypto.subtle)throw new Error("WebCryptoProvider: WebCrypto (crypto.subtle) is unavailable in this runtime");return crypto}function qs(e){return e.slice()}class Bs extends Ir{async sign(e,t){const i=u(t),r=64===i.length?i.subarray(0,32):i,n=new Uint8Array($s.length+r.length);n.set($s,0),n.set(r,$s.length);const o=await Vs().subtle.importKey("pkcs8",n,{name:Ks},!1,["sign"]),s=await Vs().subtle.sign({name:Ks},o,qs(e));return new Uint8Array(s)}async verify(e,t,i){try{const r=u(i),n=await Vs().subtle.importKey("raw",qs(r),{name:Ks},!1,["verify"]);return await Vs().subtle.verify({name:Ks},n,qs(t),qs(e))}catch{return!1}}async generateKeyPair(){const e=await Vs().subtle.generateKey({name:Ks},!0,["sign","verify"]);if(!function(e){return"privateKey"in e&&"publicKey"in e}(e))throw new Error("WebCryptoProvider: expected an Ed25519 key pair from generateKey");const t=new Uint8Array(await Vs().subtle.exportKey("raw",e.publicKey));return{privateKey:d(new Uint8Array(await Vs().subtle.exportKey("pkcs8",e.privateKey)).subarray($s.length,$s.length+32)),publicKey:d(t)}}async hash(e){return`sha256:${function(e){let t="";for(const i of e)t+=i.toString(16).padStart(2,"0");return t}(new Uint8Array(await Vs().subtle.digest("SHA-256",qs(e))))}`}async randomBytes(e){return Vs().getRandomValues(new Uint8Array(e))}}function Fs(e){return`${e.ledgerId}\0${e.ledgerEpochId}`}function Ws(e,t){return`${e}\0${t}`}class Gs{capabilities={durability:"ephemeral",atomicAppend:!0,orderedRead:!0};entriesByLedger=new Map;entriesByIdempotency=new Map;heads=new Map;async getHead(e){return this.heads.get(Fs(e))??null}async getByIdempotencyKey(e,t){return this.entriesByIdempotency.get(Ws(e,t))??null}async compareAndAppend(e){const t=Ws(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=Fs(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(Fs(e))??[]]}}const Js="kya:reference:audit:primary",Ys="epoch_1",Xs="urn:kya-os:audit-binding:mcp:2025-11-25",Zs="did:key:zReferenceProducer",Qs="reference-recorder",ea="reference-tenant",ta={kind:"keyed_commitment",value:`sha256:${"a".repeat(64)}`,keyId:"reference-tenant-key"};function ia(e,t={}){return{schema:Fr,eventId:`evt_${e}`,eventType:"tool.call.completed",eventVersion:"1.0.0",binding:Xs,occurredAt:175e10+e,tenantRef:ta,source:{producer:{kind:"pairwise_did",did:Zs},sourceId:Qs,sourceSequence:String(e)},action:{category:"tool.call",name:"orders.create"},outcome:"succeeded",evidence:[],details:{family:"tool",phase:"completed",attempt:"1"},privacy:{classification:"internal",retentionClass:"audit-365d"},...t}}async function ra(e={}){const t={ledgerId:e.ledgerId??Js,ledgerEpochId:e.ledgerEpochId??Ys},{publicKey:i,privateKey:r}=await async function(e,t){const i=nt(t?.extractable),r=rt(e,tt);let n;if(r.secret&&it(tt),r.resolve){const e=t?.crv??"P-256";switch(e){case"P-256":case"P-384":case"P-521":n={name:"ECDH",namedCurve:e};break;case"X25519":n={name:"X25519"};break;default:throw new Oe("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, and X25519")}}else{if(void 0!==r.crv&&void 0!==t?.crv&&t.crv!==r.crv)throw new Oe(`Invalid or unsupported crv option provided, the only supported value for ${e} is ${r.crv}`);n="RSA"===r.kty[0]?{...r.subtle,publicExponent:Uint8Array.of(1,0,1),modulusLength:js(t)}:r.subtle}return crypto.subtle.generateKey(n,i??!1,[...r.usages[1],...r.usages[0]])}("EdDSA",{extractable:!1}),n={did:"did:key:zReferenceRecorder",kid:"did:key:zReferenceRecorder#0",alg:"EdDSA"},o={resolve:async e=>e.kid===n.kid?i:null},s=new Gn(new Bs),a=new Yn(n,r),c=new Gs,d=e.clock??{now:()=>Date.now()},u=new rs({ledgerId:t.ledgerId,ledgerEpochId:t.ledgerEpochId,tenantRef:ta,binding:Xs,sourceId:Qs,journal:c,signer:a,hasher:s,clock:d}),l=new Ao,h=new Do({journal:c,store:l,signer:a,hasher:s,clock:d}),p=new as({journal:c,checkpoints:{builder:h,store:l}}),f=new zo({hasher:s,signatures:new Jn(o)});return{ledger:t,signerRef:n,read:p,checkpoints:{builder:h,store:l},verifier:f,verificationPolicy:{policyId:"policy:reference-recorder",trustedLedgerEpochs:[{ledgerId:t.ledgerId,ledgerEpochId:t.ledgerEpochId,recorderKeys:[{signer:n}]}],trustedObservers:[],authorizedExporters:[],acceptedIntegritySuites:["KYA-AUDIT-JCS-SHA256-JWS-2026","KYA-AUDIT-RFC9162-SHA256-JWS-2026"],acceptedAlgorithms:["EdDSA"],keyRevocationMode:"as_observed"},submit:async e=>u.submitAuthenticated({ledgerId:t.ledgerId,producerEvent:e,encryptedEvidence:[]},{producerAuthority:Zs,tenantAuthority:ea,tenantRef:ta}),checkpoint:async()=>h.createCheckpoint(t)}}class na{recorder;context;constructor(e,t){this.recorder=e,this.context=t}async submit(e){return this.recorder.submitAuthenticated(e,await this.context())}}function oa(e,t){return new na(new rs(e),t)}function sa(e){return`${e.ledgerId}\0${e.ledgerEpochId}`}class aa{config;capability="independent-observer";observations=new Map;publicationTails=new Map;constructor(e){this.config=e}async publish(e){const t=sa({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 ao(so.CHECKPOINT_INVALID,"Observer rejected an invalid checkpoint");const t={ledgerId:e.core.ledgerId,ledgerEpochId:e.core.ledgerEpochId},i=this.observations.get(sa(t));if(void 0!==i){const t=BigInt(i.checkpoint.core.treeSize),r=BigInt(e.core.treeSize);if(r<t)throw new ao(so.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 ao(so.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 ao(so.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 Xn(this.config.hasher,eo.observation,r),o=Object.freeze({core:Object.freeze(r),observationDigest:n,jws:await this.config.signer.sign(U(r))});return this.observations.set(sa(t),{checkpoint:e,receipt:o}),o}async latest(e){return this.observations.get(sa(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 ca{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 da{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||M(i.producerEvent)!==M(r.producerEvent)||i.encryptedEvidence.length!==r.encryptedEvidence.length||!i.encryptedEvidence.every((e,t)=>{const i=r.encryptedEvidence[t];if(void 0===i||M(e.ref)!==M(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 ua{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 la extends Kr{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 ha(e,t=256){return e.slice(0,t)}class pa{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:ha(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:ha(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:ha(t.delegationRef),...void 0===t.parentRef?{}:{parentRef:ha(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:ha(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 fa{}class ga extends fa{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 ya{}class va extends ya{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 ma(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 Ia(e,t){const i=ma(e),r=ma(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 Ea=["delete","drop","destroy","remove","terminate","transfer","payment","admin","execute","modify","write","rotate","revoke"],wa=["read","get","list","describe","search","query"];class Sa{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=Aa(e.toolName),r=function(e){const t=Aa(e);return t.includes("prod")||t.includes("production")}(e.namespace);let n;return n=i.some(e=>Ea.includes(e))?{reversibility:"irreversible",blastRadius:r?"environment":"resource",severity:r?"catastrophic":"high"}:i.some(e=>wa.includes(e))?{reversibility:"reversible",blastRadius:"record",severity:"low"}:{reversibility:"unknown",blastRadius:"unknown",severity:"unknown"},{...n,...Da(t)}}}function Aa(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 Da(e){if(!e)return{};const t={};for(const[i,r]of Object.entries(e))void 0!==r&&(t[i]=r);return t}class _a{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 ba(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 Ca(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 Ta(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 ka=256,Na=256,Ra=/\([^()]*[+*?{][^()]*\)\s*[+*{]/;function Oa(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>ka||i.length>Na)return!1;if(Ra.test(e))return!1;try{return new RegExp(`^(?:${e})$`).test(i)}catch{return!1}default:return!1}}function Pa(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(Oa(i.resource,i.matcher,e))return{satisfied:!0,usedNonExactMatcher:"exact"!==i.matcher};return{satisfied:!1,usedNonExactMatcher:!1}}function za(e){const{identity:t,cryptoProvider:i,delegationConfig:r}=e,n=ge(),o=r?.fetchProvider??("function"==typeof globalThis.fetch?new Ur:void 0),a=o?Fi(o):void 0,c=ir(r?.didResolvers,o),u=new Kt({didResolver:{async resolve(e){const t=r?.didResolver;if(t){const i=await t.resolve(e);if(i)return i}const i=X(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=f(r);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=H(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)),g=await i.verify(u,l,p);return{valid:g,reason:g?void 0:"Signature verification failed"}},statusListResolver:r?.statusListResolver,cacheTtl:r?.verificationCache?.ttlMs,maxCacheSize:r?.verificationCache?.maxEntries});return{verifyDelegation:async function(e){let i,n,o=!1;if("string"==typeof e){const t=$(e);if(!t||!t.payload.vc)return{valid:!1,reason:"Invalid VC-JWT format"};const r=await u.verifyDelegationJwt(e,{skipStatus:!0});if(!r.valid)return{valid:!1,reason:r.reason??"VC-JWT envelope signature is not valid",vc:t.payload.vc};i=t.payload.vc,i.proof||(i={...i,proof:{type:"JwtProof2020",jwt:e}}),o=!0}else i=e;try{n=await(s=i,a={skipSignature:o},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=y(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=y(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(!ei(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=Ia(c,e);if(!o.valid)return o;a=r,c=e}const d=y(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}}(s,{serverDid:t.did,verifier:u,resolveDelegationChain:r?.resolveDelegationChain,statusListConfigured:!!r?.statusListResolver,revocationChecker:r?.revocationChecker},a))}catch(e){de.error("[kya-os] Unexpected error verifying delegation",{error:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0}),n={valid:!1,reason:"Delegation credential could not be verified"}}var s,a;return n.valid?{valid:!0,vc:i,isJwt:o}:{valid:!1,reason:n.reason??"Unknown delegation validation error",vc:i}},buildDelegationErrorResponse:(e,t)=>({content:[{type:"text",text:JSON.stringify({error:e,reason:Ta(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=C({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){de.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}}}}const xa=256;function La(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,xa);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,xa):"unknown"}catch{return"unknown"}}const Ma=["handshake","identity","reputation"];function Ua(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(Bn(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 br,o=new Nr(t,{...e.session,serverDid:i.did,nonceCache:n}),s=new Ti(i,t),a=e.delegation,d=e.auditLog??new Vr,u=void 0!==e.audit&&!1!==e.audit?new pa(e.audit,{includeToolNames:e.audit.includeToolNames??!1}):void 0,l=e.emitLegacyProofKey??!0,h=e.responseProofProfile??_,p=e.grantStore??new ga;e.grantStore||de.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 f=a?.holderBinding??"off",g={identity:i,config:e,cryptoProvider:t,sessionManager:o,proofGenerator:s,auditLog:d,audit:u,grantStore:p,delegationConfig:a,holderBindingMode:f,holderBindingVerifier:"off"===f?void 0:new pr({cryptoProvider:t,clockProvider:new Mr,nonceCacheProvider:n,fetchProvider:a?.fetchProvider??("function"==typeof globalThis.fetch?new Ur:new Hr)}),emitLegacyProofKey:l,responseProofProfile:h},y=function(e){const{identity:t,config:i,cryptoProvider:n,sessionManager:o,proofGenerator:s,auditLog:a,audit:d,emitLegacyProofKey:u,responseProofProfile:l}=e,h=l===b,p=new WeakSet,f="org.kya-os/audit",g=async(e,t,i)=>{try{return await t(),!0}catch(t){return de.error(`[kya-os] ${e}`,{...void 0===i?{}:{tool:i},error:t instanceof Error?t.message:String(t)}),!1}},y=(e,t,i)=>{const r={...e._meta??{}};return i&&(delete r[Ai],delete r[_i]),r[f]={..."object"==typeof r[f]&&null!==r[f]?r[f]:{},status:"degraded",reason:t},e._meta=r,e.isError=!0,e},v=e=>({content:[{type:"text",text:JSON.stringify({success:!1,error:{code:"audit_delivery_failed",message:e}})}],isError:!0,_meta:{[f]:{status:"degraded",reason:e}}}),m=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}},I=(e,t)=>({...e,[Ai]:t,...u?{[_i]:t}:{}});let E;async function w(){if(E&&await o.getSession(E))return o.getStats().activeSessions<=1?E:void de.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?(E=s.session.sessionId,E):void 0}return{handleHandshake:async function(e){if(!Or(e))return await g("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 g(`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:v("Required session audit delivery failed after handshake validation").content,isError:!0}:(i.success&&i.session&&(E=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:w,wrapWithProof:function(e,i){return async(r,n,c)=>{if(!await g("Required tool intent audit delivery failed",()=>d?.tool("started",{toolName:e,outcome:"unknown",context:m(c)}),e))return v("Required intent audit delivery failed before tool execution");let u;try{u=await i(r,n,c)}catch(t){throw await g("Failed to record thrown tool outcome; preserving original handler error",()=>d?.tool("failed",{toolName:e,outcome:"failed",reasonCode:"HANDLER_THROWN",context:m(c)}),e),t}if(u.isError)return(e=>{if(p.has(e))return!0;const t=e._meta,i=t?.[f];return"object"==typeof i&&null!==i&&!0===i.terminal})(u)||await g("Failed to record error tool outcome",()=>d?.tool("failed",{toolName:e,outcome:"failed",reasonCode:"HANDLER_ERROR_RESULT",context:m(c)}),e)||y(u,"Required terminal audit delivery failed for an error response",!1),u;const E=n??await w();if(!E)return await g("Failed to record unavailable proof session",()=>d?.proof("rejected",{outcome:"failed",verificationCode:"PROOF_SESSION_UNAVAILABLE",context:m(c)}),e)&&await g("Failed to record completed tool outcome",()=>d?.tool("completed",{toolName:e,outcome:"succeeded",context:m(c)}),e)?u:y(u,"Required terminal audit delivery failed after tool completion",!0);const S=await o.getSession(E);if(!S)return await g("Failed to record missing proof session",()=>d?.proof("rejected",{outcome:"failed",verificationCode:"PROOF_SESSION_NOT_FOUND",context:m(c)}),e)&&await g("Failed to record completed tool outcome",()=>d?.tool("completed",{toolName:e,outcome:"succeeded",context:m(c)}),e)?u:y(u,"Required terminal audit delivery failed after tool completion",!0);try{const i={method:e,params:r},n={data:h?u:u.content},o=await s.generateProof(i,n,S,{scopeId:c?.scopeId,profile:l});if(u._meta=I({},o),!await g("Required generated-proof audit delivery failed",()=>d?.proof("generated",{outcome:"succeeded",context:m(c)}),e)||!await g("Required completed-tool audit delivery failed",()=>d?.tool("completed",{toolName:e,outcome:"succeeded",context:m(c)}),e))return y(u,"Required terminal audit delivery failed after tool completion",!0);try{await a.logAuditRecord({identity:{did:t.did,kid:t.kid},session:{sessionId:S.sessionId,audience:S.audience},requestHash:o.meta.requestHash,responseHash:o.meta.responseHash,verified:"yes",scopeId:o.meta.scopeId})}catch(t){de.error("[kya-os] Audit log failed",{tool:e,error:t instanceof Error?t.message:String(t)})}}catch(t){de.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 g("Failed to record proof-generation rejection",()=>d?.proof("rejected",{outcome:"failed",verificationCode:"PROOF_GENERATION_FAILED",context:m(c)}),e)||y(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 v="denied"===a?"denied":"step_up_required",m="needs_authorization"===a?"NEEDS_AUTHORIZATION":"step_up_required"===a?"STEP_UP_REQUIRED":"AUTHORIZATION_DENIED",E=await g("Failed to record authorization outcome",()=>d?.authorization(v,{outcome:"denied"===a?"denied":"challenged",reasonCode:m}),t)&&await g("Failed to record terminal authorization tool outcome",()=>d?.tool("denied"===a?"denied":"challenged",{toolName:t,outcome:"denied"===a?"denied":"challenged",reasonCode:m}),t);p.add(e),e._meta={...e._meta??{},[f]:{terminal:!0,outcome:a,...E?{}:{status:"degraded",reason:"Required terminal audit delivery failed for authorization outcome"}}};try{const p=r??await w();if(!p)return e;const f=await o.getSession(p);if(!f)return e;let v;if(void 0!==c)v=c;else{v={};for(const[e,t]of Object.entries(i))"_kyaos_delegation"!==e&&(v[e]=t)}const m={method:t,params:v},S=void 0!==u?{data:h?e:u}:void 0,A=await s.generateProof(m,S,f,{outcome:a,reason:Ta(n),profile:l});e._meta=I(e._meta??{},A),E&&(await g("Failed to record generated outcome proof",()=>d?.proof("generated",{outcome:"succeeded"}),t)||y(e,"Required proof audit delivery failed for authorization outcome",h))}catch(e){de.error("[kya-os] Outcome proof generation failed",{tool:t,error:e instanceof Error?e.message:String(e)}),E&&await g("Failed to record outcome-proof rejection",()=>d?.proof("rejected",{outcome:"failed",verificationCode:"OUTCOME_PROOF_GENERATION_FAILED"}),t)}return e}}}(g),v=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: ${Ma.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:[...Ma],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"]}}}}(g,{handleHandshake:y.handleHandshake}),{resolveExistingGrant:m,bindGrantOnSuccess:I}=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&&Li(u)&&"bound"===(await Mi({proof:d,subjectDid:u,request:Pi(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 de.debug(`[kya-os] Skipping an unresolvable session-less grant for scope "${a}" (holderBinding 'off', no sessionId).`);let d;try{d=ma(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){de.error("[kya-os] Grant bind failed",{scope:a,error:e instanceof Error?e.message:String(e)})}}}}(g),{wrapWithDelegation:E}=function(e,t){const{identity:i,holderBindingMode:n,holderBindingVerifier:o,audit:s,cryptoProvider:a}=e,{attachOutcomeProof:c,resolveExistingGrant:d,bindGrantOnSuccess:u}=t,{verifyDelegation:l,buildDelegationErrorResponse:h,buildNeedsAuthorizationChallenge:p}=za(e);return{wrapWithDelegation:function(e,t,f){return async(g,y)=>{const v=g._kyaos_delegation;if(null==v){const i=await d(e,g,y,t.scopeId);if(i){const r={};for(const[e,t]of Object.entries(g))Oi(e)||(r[e]=t);de.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(s?.authorization("grant_used",{outcome:"succeeded",grantRef:i.id,context:n})),f(r,y,n)}const{challengeContent:r,message:n}=await p(e,t);return c({content:r},e,g,y,n,"needs_authorization",void 0,r)}const m=await l(v);if(!m.valid){try{await(s?.delegation("rejected",{delegationRef:La(m.vc),outcome:"failed",reasonCode:"DELEGATION_VERIFICATION_FAILED"}))}catch(t){de.error("[kya-os] Failed to record rejected delegation audit event",{tool:e,error:t instanceof Error?t.message:String(t)})}return de.warn(`[kya-os] Delegation verification failed for "${e}": ${Ta(m.reason)}`),c(h(r.delegation_invalid,m.reason),e,g,y,m.reason)}const{vc:I,isJwt:E}=m;if("off"!==n&&o){const t=I.credentialSubject?.id;if(t&&Li(t)){const s=g._kyaos_proof;if(void 0===s){const t="Holder-of-key proof (_kyaos_proof) is required for this delegation subject";if(de.warn(`[kya-os] Holder binding: "${e}" called without _kyaos_proof`),"enforce"===n)return c(h(r.holder_binding_failed,t),e,g,y,t)}else{let a=s;if("string"==typeof s)try{a=JSON.parse(s)}catch{a={}}const d=await Mi({proof:a,subjectDid:t,request:Pi(e,g),expectedAudience:i.did,proofVerifier:o});if("bound"!==d.status){const t=d.reason??"Holder-of-key proof did not bind the delegation subject";if(de.warn(`[kya-os] Holder binding ${d.status} for "${e}": ${Ta(t)}`),"enforce"===n)return c(h(r.holder_binding_failed,t),e,g,y,t)}}}else t&&de.warn(`[kya-os] Holder binding: subject "${t}" is not did:key; deferring to cnf binding (phase 2)`)}const w=Pa(t.scopeId,I);if(w.usedNonExactMatcher&&de.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 de.warn(`[kya-os] Delegation missing required scope "${t.scopeId}" for "${e}"`),c(h(r.insufficient_scope,i),e,g,y,i)}const S=E?(new TextEncoder).encode(v):U(I),A=await a.hash(S),D=I.id??I.credentialSubject.delegation.id,_={kind:"pairwise_did",did:I.credentialSubject.id},b=I.credentialSubject.delegation.controller,C={source:"delegation",decision:"allowed",scopeId:t.scopeId,delegationRef:D,delegationCredentialDigest:A,verificationCode:"DELEGATION_CHAIN_VALID"},T={scopeId:t.scopeId,actor:_,...b?.startsWith("did:")?{responsibleParty:{kind:"pairwise_did",did:b}}:{},authorization:C};await(s?.delegation("verified",{delegationRef:D,outcome:"succeeded",parentRef:I.credentialSubject.delegation.parentId,context:T})),await(s?.authorization("approved",{outcome:"succeeded",context:T}));const k={};for(const[e,t]of Object.entries(g))Oi(e)||(k[e]=t);return await u(I,v,E,y,t.scopeId),de.debug(`[kya-os] Delegation verified for "${e}", scope "${t.scopeId}"`),f(k,y,T)}}}}(g,{attachOutcomeProof:y.attachOutcomeProof,resolveExistingGrant:m,bindGrantOnSuccess:I}),{withPolicyGate:w}=function(e,t){const{proofGenerator:i,audit:n}=e,{attachOutcomeProof:o}=t,s=new Sa,a=new _a;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))Oi(e)||e===l||(f[e]=t);const g=c.resolveNamespace?.(s)??e,y=u.classify({toolName:e,namespace:g}),v=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=ma(t)}catch{o=[]}return{agentDid:r,...n?{responsibleParty:n}:{},delegatedScopes:o}}catch{return{agentDid:"unknown",delegatedScopes:[]}}}(s._kyaos_delegation),m=Ca({principal:{agentDid:v.agentDid,...v.responsibleParty?{responsibleParty:v.responsibleParty}:{}},action:{toolName:e},resource:{namespace:g},delegatedScopes:v.delegatedScopes,scopeMatched:c.scopeMatched??!1,risk:y}),I=await d.evaluate(m),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:Ta(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 ba(S,w,I.quorum,h)).satisfied)return await(n?.authorization("approved",{outcome:"succeeded",context:E})),t(f,a,p);const A=k({message:`Tool "${e}" requires ${I.quorum.n}-of-N approval before it may proceed (${Ta(I.reason)}).`,resumeToken:`step_up:${w}`,expiresAt:Math.floor(Date.now()/1e3)+300,requestHash:w,quorum:I.quorum}),D={content:[{type:"text",text:JSON.stringify(A)}],isError:!0};return o(D,e,s,a,I.reason,"step_up_required",f)}}}}(g,{attachOutcomeProof:y.attachOutcomeProof});return{identity:e.identity,sessionManager:o,proofGenerator:s,kyaOsTool:v.kyaOsTool,handshakeTool:v.handshakeTool,handleKyaOs:v.handleKyaOs,handleHandshake:y.handleHandshake,wrapWithProof:y.wrapWithProof,wrapWithDelegation:E,withPolicyGate:w}}async function Ha(e){const t=await e.generateKeyPair(),i=oe(t.publicKey);return{did:i,kid:`${i}#${se(i)}`,privateKey:t.privateKey,publicKey:t.publicKey}}async function ja(e,t){const i=Ua({identity:t.identity??await Ha(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:Br.z.enum(Ma).describe("Protocol operation to perform"),nonce:Br.z.string().optional().describe("Client-generated unique nonce (handshake)"),audience:Br.z.string().optional().describe("Intended audience (handshake)"),timestamp:Br.z.number().optional().describe("Unix epoch seconds (handshake)"),agentDid:Br.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){de.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}const Ka=Br.z.string().regex(/^did:(key|web):.+$/,"must be a did:key or did:web DID"),$a=Br.z.enum(["mcp","agent","client","verifier","human"]),Va=Br.z.enum(["L1","L2","L3"]),qa=Br.z.object({kty:Br.z.literal("OKP"),crv:Br.z.literal("Ed25519"),x:Br.z.string(),kid:Br.z.string().optional(),use:Br.z.string().optional()}).strict(),Ba=Br.z.object({kty:Br.z.literal("EC"),crv:Br.z.literal("P-256"),x:Br.z.string(),y:Br.z.string(),kid:Br.z.string().optional(),use:Br.z.string().optional()}).strict(),Fa=(Br.z.union([qa,Ba]),Br.z.union([Br.z.string(),Br.z.record(Br.z.string(),Br.z.unknown())])),Wa=Br.z.object({vc:Fa}),Ga=Br.z.object({name:Br.z.string().min(1),attestations:Br.z.array(Wa).min(1)}).strict(),Ja=Br.z.union([Br.z.string().min(1),Ga]),Ya=Br.z.object({type:Br.z.enum(["IdentityVerification","CapabilityAttestation"]),vc:Fa,subject:Ka.optional(),issuer:Ka.optional()}).strict(),Xa="org.kya-os/proof.v1",Za=Br.z.union([Br.z.literal(Xa),Br.z.literal("org.kya-os/proof@1")]),Qa=Br.z.object({clientId:Br.z.string().min(1),jwksUri:Br.z.string().min(1)}).strict(),ec=Br.z.object({statusListCredential:Br.z.string().min(1),statusListIndex:Br.z.string().regex(/^[0-9]+$/,"statusListIndex must be a canonical non-negative decimal")}).strict();Br.z.object({id:Ka,entityType:$a,name:Br.z.string().min(1),kid:Br.z.string().optional(),publicKeyJwk:qa.optional(),createdAt:Br.z.string().optional(),capabilities:Br.z.array(Ja).optional(),conformanceLevel:Va.optional(),responsibleParty:Ka.optional(),principal:Ka.optional(),delegationRef:Br.z.string().optional(),attestations:Br.z.array(Ya).optional(),didDocument:Br.z.string().optional(),proofProfile:Za.optional(),cimd:Qa.optional(),revocation:ec.optional()}).strict();const tc="org.kya-os/decentralized-authority",ic="io.modelcontextprotocol/clientCapabilities",rc=-32021,nc="extension_not_declared",oc="malformed_declaration",sc=e=>new Set(e).size===e.length,ac=Br.z.object({version:Br.z.string().regex(/^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/,"version must be a semver string").optional(),proofProfiles:Br.z.array(Br.z.string().min(1)).min(1).refine(sc,"proofProfiles must be unique").optional(),didMethods:Br.z.array(Br.z.string().regex(/^did:[a-z0-9]+$/,'didMethods entries look like "did:web"')).min(1).refine(sc,"didMethods must be unique").optional(),required:Br.z.boolean().optional()}),cc={version:"1.0.0",proofProfiles:[Xa],didMethods:["did:key","did:web"],required:!1};function dc(e){const t=ac.safeParse(e);return t.success?t.data:void 0}function uc(e={}){return{version:e.version??cc.version,proofProfiles:e.proofProfiles??[...cc.proofProfiles],didMethods:e.didMethods??[...cc.didMethods],required:e.required??cc.required}}function lc(e={}){const t=ac.safeParse(e);if(!t.success)throw new Error(`invalid ${tc} settings: ${t.error.message}`);return t.data}function hc(e={},t=tc){return{[t]:lc(e)}}function pc(e){const t=e.extensionId??tc,i=gc(Xi(r=e.meta)?r[ic]:void 0,t);var r;if(i.present){const e=dc(i.value);return void 0===e?{status:"malformed",carriage:"stateless"}:{status:"declared",declaration:{settings:e,carriage:"stateless"}}}const n=gc(e.initializeCapabilities,t);if(n.present){const e=dc(n.value);return void 0===e?{status:"malformed",carriage:"initialize"}:{status:"declared",declaration:{settings:e,carriage:"initialize"}}}return{status:"absent"}}function fc(e){const t=pc(e);return"declared"===t.status?t.declaration:void 0}function gc(e,t){if(!Xi(e))return{present:!1};const i=e.extensions;return Xi(i)&&Object.prototype.hasOwnProperty.call(i,t)?{present:!0,value:i[t]}:{present:!1}}const yc=-31e3,vc=-32099,mc=-32020,Ic=["server/discover","ping"];function Ec(e={},t={}){const i=uc(lc(e)),r=t.extensionId??tc,n=t.exemptMethods??Ic;return e=>{const t=pc({...e,extensionId:r});return"declared"===t.status?{ok:!0,declaration:t.declaration}:i.required?void 0!==e.method&&n.includes(e.method)?{ok:!0}:"malformed"===t.status?{ok:!1,error:Ac(r)}:{ok:!1,error:wc(r)}:{ok:!0}}}function wc(e=tc){return{code:rc,message:`Missing required client capability: ${e}`,data:{requiredCapabilities:{extensions:{[e]:{}}},reason:nc,extension:e}}}const Sc=-32602;function Ac(e=tc){return{code:Sc,message:`Invalid params: the ${e} settings declaration is present but malformed`,data:{reason:oc,extension:e}}}function Dc(e,t={}){if(void 0!==t.code&&t.code>=vc&&t.code<=mc)throw new Error(`JSON-RPC code ${t.code} is inside the MCP-reserved range (${vc}..${mc}); KYA-OS domain errors use implementation-defined codes (SPEC-MCP-EXTENSION.md §5.1)`);return{code:t.code??yc,message:e.message,data:{reason:e.code,profile:t.profile??Xa,...e.reasons&&e.reasons.length>0?{reasons:[...e.reasons]}:{}}}}}};
|