@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
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";exports.id=215,exports.ids=[215],exports.modules={12215:(e,t,n)=>{n.r(t),n.d(t,{ANON_NONCE_TTL_MS:()=>S,AUDIT_ASSURANCE_PROFILES:()=>Ru,AUDIT_BUNDLE_INTEGRITY_SUITE:()=>Vd,AUDIT_BUNDLE_MANIFEST_SCHEMA_ID:()=>Kd,AUDIT_BUNDLE_MEDIA_TYPES:()=>Sl,AUDIT_CHECKPOINT_INTEGRITY_SUITE:()=>Hd,AUDIT_CHECKPOINT_SCHEMA_ID:()=>jd,AUDIT_CONSISTENCY_PROOF_REQUEST_SCHEMA_ID:()=>np,AUDIT_CONSISTENCY_PROOF_RESPONSE_SCHEMA_ID:()=>rp,AUDIT_DIGEST_DOMAINS:()=>Ku,AUDIT_ENTRY_SCHEMA_ID:()=>Md,AUDIT_ERROR_CODES:()=>Wu,AUDIT_EVENT_SCHEMA_ID:()=>$d,AUDIT_EVENT_TYPES:()=>qr,AUDIT_HEAD_REQUEST_SCHEMA_ID:()=>Zl,AUDIT_HEAD_RESPONSE_SCHEMA_ID:()=>Yl,AUDIT_INCLUSION_PROOF_REQUEST_SCHEMA_ID:()=>ep,AUDIT_INCLUSION_PROOF_RESPONSE_SCHEMA_ID:()=>tp,AUDIT_INTEGRITY_SUITE:()=>Ud,AUDIT_LIST_ENTRIES_REQUEST_SCHEMA_ID:()=>Xl,AUDIT_LIST_ENTRIES_RESPONSE_SCHEMA_ID:()=>Ql,AUDIT_REASON_CODES:()=>ml,AUDIT_RECEIPT_SCHEMA_ID:()=>Ld,AUTH_NONCE_TTL_MS:()=>b,AuditArtifactVerifier:()=>_l,AuditCheckpointBuilder:()=>ll,AuditCheckpointCoordinator:()=>pl,AuditLogProvider:()=>Kr,AuditMirrorService:()=>Ul,AuditProjectionWorker:()=>yl,AuditProtocolError:()=>Gu,AuditRecorderService:()=>Fl,AuditReplayBundleExporter:()=>Ol,AuditTrailService:()=>Ml,BitstringManager:()=>Wt,CascadingRevocationManager:()=>Xt,ClockProvider:()=>_r,CompactJwsAuditSignatureVerifier:()=>Mu,CompactJwsAuditSigner:()=>Lu,CryptoProvider:()=>wr,CryptoProviderAuditHasher:()=>$u,DEFAULT_CLOCK_SKEW_SECONDS:()=>lr,DEFAULT_EXEMPT_METHODS:()=>dh,DEFAULT_EXTENSION_SETTINGS:()=>Xf,DEFAULT_READ_ENTRIES_LIMIT:()=>ql,DEFAULT_SESSION_TTL_MINUTES:()=>w,DEFAULT_TIMESTAMP_SKEW_SECONDS:()=>_,DELEGATION_CREDENTIAL_CONTEXT:()=>p,DefaultPolicyEngine:()=>ff,DelegationCredentialIssuer:()=>V,DelegationCredentialVerifier:()=>Ht,DelegationGraphManager:()=>Vt,DidWebResolver:()=>Bn,ED25519_KEY_SIZE:()=>bn,ED25519_PKCS8_DER_HEADER:()=>_n,ED25519_SPKI_DER_HEADER_LENGTH:()=>En,EXTENSION_NOT_DECLARED_REASON:()=>Wf,ExtensionSettingsSchema:()=>Yf,FetchProvider:()=>Er,GrantStore:()=>tf,HOLDER_BINDING_ERROR:()=>$n,IdentityProvider:()=>Ar,KYA_OS_DOMAIN_ERROR_CODE:()=>sh,KYA_OS_ERROR_CODES:()=>r,KYA_OS_EXTENSION_ID:()=>qf,KYA_OS_PROOF_META_KEY:()=>Sn,LEGACY_NAMESPACED_PROOF_META_KEY:()=>An,LEGACY_PROOF_META_KEY:()=>Dn,LegacyAuditSinkAdapter:()=>Xp,LocalAuditReadService:()=>Wl,LocalAuditRecorderClient:()=>qp,MAX_CLOCK_SKEW_SECONDS:()=>fr,MAX_READ_ENTRIES_LIMIT:()=>Bl,MCP_CLIENT_CAPABILITIES_META_KEY:()=>Bf,MIN_CLOCK_SKEW_SECONDS:()=>pr,MISSING_REQUIRED_CLIENT_CAPABILITY_CODE:()=>Jf,McpAuditEventAdapter:()=>ef,MemoryAuditCheckpointObserver:()=>Wp,MemoryAuditCheckpointStore:()=>ul,MemoryAuditEvidenceProvider:()=>Yu,MemoryAuditJournal:()=>zp,MemoryAuditLogProvider:()=>Vr,MemoryAuditOutbox:()=>Zp,MemoryAuditProjectionProvider:()=>gl,MemoryAuditSourceState:()=>Yp,MemoryDelegationGraphStorage:()=>Hn,MemoryGrantStore:()=>nf,MemoryIdentityProvider:()=>Tr,MemoryNonceCacheProvider:()=>kr,MemoryPendingFlowStore:()=>of,MemoryResumeTokenStore:()=>ir,MemorySessionStore:()=>Or,MemoryStatusListStorage:()=>jn,MemoryStorageProvider:()=>Dr,MemorySupportingAnchorProvider:()=>Gp,NONCE_LENGTH_BYTES:()=>E,NodeCryptoProvider:()=>Mr,NonceCacheProvider:()=>Sr,NoopAuditLogProvider:()=>Fr,NoopFetchProvider:()=>jr,OUTBOUND_HEADER_NAMES:()=>mn,PROOF_VERIFICATION_ERROR_CODES:()=>cr,PendingFlowStore:()=>rf,ProofGenerator:()=>Cn,ProofVerificationError:()=>dr,ProofVerifier:()=>hr,RESPONSE_PROOF_PROFILE_BODY:()=>A,RESPONSE_PROOF_PROFILE_ENVELOPE:()=>D,Rfc9162MerkleTree:()=>il,RiskClassifier:()=>uf,RuntimeFetchProvider:()=>Ur,SENSITIVE_VERBS:()=>cf,SessionManager:()=>Nr,SessionStore:()=>Cr,StatusList2021Manager:()=>Zt,StorageProvider:()=>br,SystemClockProvider:()=>Lr,WebCryptoEvidenceEncryptor:()=>Zu,assertAuditCapabilities:()=>Pu,assertHolderBinding:()=>Ln,auditAnchorReceiptSchema:()=>au,auditBundleConsistencyProofSchema:()=>lu,auditBundleInclusionProofSchema:()=>uu,auditBundleManifestCoreSchema:()=>hu,auditCheckpointCoreSchema:()=>ru,auditConsistencyProofRequestSchema:()=>fp,auditConsistencyProofResponseSchema:()=>hp,auditEntryCoreSchema:()=>tu,auditHeadRequestSchema:()=>ap,auditHeadResponseSchema:()=>cp,auditHeadSchema:()=>op,auditInclusionProofRequestSchema:()=>lp,auditInclusionProofResponseSchema:()=>pp,auditListEntriesRequestSchema:()=>dp,auditListEntriesResponseSchema:()=>up,auditMerkleConsistencyProofSchema:()=>du,auditMerkleInclusionProofSchema:()=>cu,auditObservationReceiptSchema:()=>su,auditProducerEventSchema:()=>eu,auditRecorderReceiptCoreSchema:()=>nu,auditReplayBundleSchema:()=>yu,auditVerificationPolicySchema:()=>Iu,base58Decode:()=>W,base58Encode:()=>J,base64ToBytes:()=>u,base64urlDecodeToBytes:()=>s,base64urlEncodeFromBytes:()=>c,buildAuditRecord:()=>Hr,buildAuditRecorderReceiptCore:()=>Fu,buildChainString:()=>yn,buildDelegationProofJWT:()=>gn,buildDidResolverRegistry:()=>rr,buildDidWebDocument:()=>Zn,buildExtensionSettings:()=>th,buildExtensionsEntry:()=>nh,buildOutboundDelegationHeaders:()=>vn,buildPolicyRequest:()=>gf,buildProofJwsPayload:()=>Tn,bytesToBase64:()=>d,canonicalizeJSON:()=>U,collectAuditEvidenceManifest:()=>Vu,collectAuditEvidenceRefs:()=>Hu,compareDids:()=>Q,completeVCJWT:()=>H,computeCanonicalHashes:()=>kn,createAuditTrail:()=>Ll,createCascadingRevocationManager:()=>Qt,createDefaultConsoleLogger:()=>ce,createDelegationGraph:()=>Ft,createDelegationIssuer:()=>F,createDelegationVerifier:()=>Kt,createDidKeyResolver:()=>ge,createDidWebResolver:()=>Jn,createHandshakeRequest:()=>Rr,createInMemoryReferenceRecorder:()=>Fp,createKyaOsError:()=>i,createKyaOsMiddleware:()=>Df,createLocalAuditReadService:()=>Gl,createLocalAuditRecorder:()=>Bp,createNeedsApprovalError:()=>C,createNeedsAuthorizationError:()=>k,createProofResponse:()=>On,createProofVerificationError:()=>ur,createStatusListManager:()=>Yt,createUnsignedVCJWT:()=>j,decimalStringSchema:()=>Bd,didKeyFragment:()=>se,didWebToUrl:()=>qn,digestAuditEntry:()=>Bu,digestAuditEvent:()=>qu,digestAuditEvidenceManifest:()=>Ju,digestSchema:()=>Jd,evidenceRefSchema:()=>Zd,extractAgentId:()=>te,extractAgentSlug:()=>ne,extractCanonicalData:()=>Nn,extractDelegationFromVC:()=>y,extractProofFromMeta:()=>Ir,extractPublicKeyFromDidKey:()=>fe,generateDidKeyFromBase64:()=>oe,generateDidKeyFromBytes:()=>ie,generateIdentity:()=>kf,generateRequestProof:()=>zn,getDidMethod:()=>Y,getServerDid:()=>ee,hasSensitiveScopes:()=>ar,hashAuditValue:()=>Uu,isDelegationCredentialExpired:()=>m,isDelegationCredentialNotYetValid:()=>v,isDidWeb:()=>Vn,isEd25519DidKey:()=>pe,isHolderBindingApplicable:()=>Mn,isIndexSet:()=>Gt,isKyaOsControlArg:()=>Pn,isNeedsApprovalError:()=>O,isNeedsAuthorizationError:()=>T,isReservedMcpMetaKey:()=>mr,isValidBase58:()=>G,isValidDid:()=>Z,logger:()=>de,matchScope:()=>wf,mergeAuditDimensions:()=>El,missingRequiredCapabilityError:()=>lh,normalizeDid:()=>X,parseAuditBundleManifestCore:()=>Cu,parseAuditCheckpointCore:()=>Du,parseAuditConsistencyProofRequest:()=>_p,parseAuditConsistencyProofResponse:()=>Ep,parseAuditEntryCore:()=>bu,parseAuditHeadRequest:()=>gp,parseAuditHeadResponse:()=>yp,parseAuditInclusionProofRequest:()=>Ip,parseAuditInclusionProofResponse:()=>wp,parseAuditListEntriesRequest:()=>mp,parseAuditListEntriesResponse:()=>vp,parseAuditObservationReceipt:()=>Tu,parseAuditProducerEvent:()=>Eu,parseAuditRecorderReceiptCore:()=>Au,parseAuditReplayBundle:()=>Ou,parseAuditVerificationPolicy:()=>Nu,parseDidWeb:()=>Fn,parseExtensionSettings:()=>Qf,parseSignedAuditCheckpoint:()=>ku,parseSignedAuditEntry:()=>Su,parseVCJWT:()=>K,partyRefSchema:()=>Yd,proofGateToJsonRpcError:()=>hh,publicKeyToJwk:()=>he,readExtensionDeclaration:()=>ih,requireExtension:()=>uh,resolveDidKeySync:()=>ye,resolveExtensionSettings:()=>eh,sampleAuditEvent:()=>Vp,scopeSatisfies:()=>_f,signedAuditCheckpointSchema:()=>iu,signedAuditEntrySchema:()=>ou,signerRefSchema:()=>Gd,toAuditConsistencyProofResponse:()=>Dp,toAuditHeadResponse:()=>bp,toAuditInclusionProofResponse:()=>Ap,toAuditListEntriesResponse:()=>Sp,toHolderBindingRequest:()=>xn,validateDelegationCredential:()=>I,validateDetachedProof:()=>R,validateHandshakeFormat:()=>Pr,validateMetaStructure:()=>vr,verifyApprovalQuorum:()=>hf,verifyAuditBundle:()=>$l,verifyDelegationAudience:()=>en,verifyDidLinkage:()=>Qn,verifyOrHints:()=>or,withKyaOs:()=>Tf,wrapDelegationAsVC:()=>f});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 i(e,t,n){return n?{code:e,message:t,details:n}:{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 n=0;n<e.length;n++)t[n]=e.charCodeAt(n);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),n=new Uint8Array(e.length);for(let t=0;t<e.length;t++)n[t]=e.charCodeAt(t);return n}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),n=Array.from(t).map(e=>String.fromCharCode(e)).join("");return btoa(n).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 n=(4-t.length%4)%4;if(t+="=".repeat(n),"undefined"!=typeof atob){const e=atob(t),n=new Uint8Array(e.length);for(let t=0;t<e.length;t++)n[t]=e.charCodeAt(t);return n}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 p="https://schema.kya-os.org/v1/protocol/delegation/context/v1.0.0";function f(e,t){const n=(new Date).toISOString(),r=e.constraints.notAfter?new Date(1e3*e.constraints.notAfter).toISOString():t?.expirationDate;let i=t?.issuanceDate||n;!t?.issuanceDate&&e.createdAt&&(i=new Date(e.createdAt).toISOString());const o=t?.scopes||e.constraints.scopes;return{"@context":["https://www.w3.org/2018/credentials/v1",p],id:t?.id||e.vcId||`urn:uuid:${e.id}`,type:["VerifiableCredential","DelegationCredential"],issuer:e.issuerDid,issuanceDate:i,...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 h(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 n=h(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:n,status:t.status,createdAt:t.createdAt,revokedAt:void 0,revokedReason:void 0,metadata:t.metadata}}function m(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 v(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 n=t.credentialSubject;if(!n||"object"!=typeof n)return{success:!1,error:{message:"Missing credentialSubject"}};if(!n.id||"string"!=typeof n.id)return{success:!1,error:{message:"credentialSubject.id missing"}};const r=n.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 w=30,_=120,E=16,b=12e4,S=6e4,A="org.kya-os/response-proof.body",D="org.kya-os/response-proof.envelope";function k(e){return{error:"needs_authorization",...e}}function T(e){return"object"==typeof e&&null!==e&&"needs_authorization"===e.error}function C(e){return{error:"needs_approval",...e}}function O(e){return"object"==typeof e&&null!==e&&"needs_approval"===e.error}const N=/^sha256:[a-f0-9]{64}$/;function R(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 n=t.meta;if(!n||"object"!=typeof n)return{success:!1,error:{message:"meta must be an object"}};const r=n,i=["did","kid","nonce","audience","sessionId"];for(const e of i)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||!N.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||!N.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!==D?{success:!1,error:{message:`meta.prf must be "${D}" 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=n(77753);const x=new TextEncoder;function z(e){for(let t=0;t<e.length;t+=1){const n=e.charCodeAt(t);if(n>=55296&&n<=56319){const n=e.charCodeAt(t+1);if(t+1>=e.length||n<56320||n>57343)return!0;t+=1}else if(n>=56320&&n<=57343)return!0}return!1}function $(e,t="$",n=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(n.has(e))throw new TypeError(`Cannot canonicalize cyclic reference at ${t}`);n.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}]`);$(e[r],`${t}[${r}]`,n)}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(z(r))throw new TypeError(`Cannot canonicalize object key with lone surrogate at ${t}`);const i=Object.getOwnPropertyDescriptor(e,r);if(i?.enumerable){if(!("value"in i))throw new TypeError(`Cannot canonicalize accessor property at ${t}.${r}`);$(i.value,`${t}.${r}`,n)}}}finally{n.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(z(e))throw new TypeError(`Cannot canonicalize string with lone surrogate at ${t}`)}function M(e){return $(e),(0,P.d)(e)}function L(e){return x.encode(M(e))}function U(e){return M(e)}function j(e,t={}){const n={alg:"EdDSA",typ:"JWT"};t.keyId&&(n.kid=t.keyId);const r="string"==typeof e.issuer?e.issuer:e.issuer?.id,i=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};i&&(d.sub=i),o&&(d.exp=o),s&&(d.iat=s),e.id&&"string"==typeof e.id&&(d.jti=e.id);const u=a(JSON.stringify(n)),l=a(JSON.stringify(d));return{header:n,payload:d,encodedHeader:u,encodedPayload:l,signingInput:`${u}.${l}`}}function H(e,t){return`${e}.${t}`}function K(e){const t=e.split(".");if(3!==t.length)return null;try{const e=o(t[0]),n=o(t[1]);return{header:JSON.parse(e),payload:JSON.parse(n),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 n=f(e,{id:t.id,issuanceDate:t.issuanceDate,expirationDate:t.expirationDate,credentialStatus:t.credentialStatus});if(t.additionalContexts&&t.additionalContexts.length>0){const e=n["@context"];n={...n,"@context":[...e,...t.additionalContexts]}}const r=this.canonicalizeVC(n),i=await this.signingFunction(r,this.identity.getDid(),this.identity.getKeyId());return{...n,proof:i}}async createAndIssueDelegation(e,t={}){const n=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:n,metadata:e.metadata};return this.issueDelegationCredential(r,t)}canonicalizeVC(e){return U(e)}getIssuerDid(){return this.identity.getDid()}getIssuerKeyId(){return this.identity.getKeyId()}}function F(e,t){return new V(e,t)}const q="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",B=new Map;for(let e=0;e<q.length;e++){const t=q[e];void 0!==t&&B.set(t,e)}function J(e){if(0===e.length)return"";let t=BigInt(0);for(let n=0;n<e.length;n++){const r=e[n];void 0!==r&&(t=t*BigInt(256)+BigInt(r))}let n="";for(;t>0;)n=q[Number(t%BigInt(58))]+n,t/=BigInt(58);for(let t=0;t<e.length&&0===e[t];t++)n="1"+n;return n}function W(e){if(0===e.length)return new Uint8Array(0);let t=BigInt(0);for(const n of e){const e=B.get(n);if(void 0===e)throw new Error(`Invalid base58 character: ${n}`);t=t*BigInt(58)+BigInt(e)}const n=[];for(;t>0;)n.unshift(Number(t%BigInt(256))),t/=BigInt(256);let r=0;for(const t of e){if("1"!==t)break;r++}const i=new Uint8Array(r+n.length);return i.set(n,r),i}function G(e){if(0===e.length)return!0;for(const t of e)if(!B.has(t))return!1;return!0}function Z(e){return"string"==typeof e&&e.startsWith("did:")}function Y(e){if(!Z(e))return null;const t=e.match(/^did:([^:]+):/);return t?.[1]??null}function X(e){return e.trim()}function Q(e,t){return X(e)===X(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 ne(e){return te(e)}const re=new Uint8Array([237,1]);function ie(e){const t=new Uint8Array(re.length+e.length);return t.set(re),t.set(e,re.length),`did:key:z${J(t)}`}function oe(e){return ie(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 n(n,...r){if(function(t){return ae[t]>=ae[e]}(n))if(t)console.error(...r);else switch(n){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(n={}){n.level&&(e=n.level),!0===n.forceStderr?t=!0:!1===n.forceStderr?t=!1:"stdio"===n.transport?t=!0:"sse"!==n.transport&&"http"!==n.transport||(t=!1)},debug:(...e)=>n("debug",...e),info:(...e)=>n("info",...e),warn:(...e)=>n("warn",...e),error:(...e)=>n("error",...e)}}const de=ce(),ue=new Uint8Array([237,1]),le=32;function pe(e){return e.startsWith("did:key:z6Mk")}function fe(e){if(!e.startsWith("did:key:z"))return null;try{const t=W(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 he(e){return{kty:"OKP",crv:"Ed25519",x:c(e)}}function ge(){return{resolve:async e=>{if(!pe(e))return null;const t=fe(e);if(!t)return null;const n=he(t),r=e.replace("did:key:",""),i=se(e);return{id:e,verificationMethod:[{id:`${e}#${i}`,type:"Ed25519VerificationKey2020",controller:e,publicKeyJwk:n,publicKeyMultibase:r}],authentication:[`${e}#${i}`],assertionMethod:[`${e}#${i}`]}}}}function ye(e){if(!pe(e))return null;const t=fe(e);if(!t)return null;const n=he(t),r=e.replace("did:key:",""),i=se(e);return{id:e,verificationMethod:[{id:`${e}#${i}`,type:"Ed25519VerificationKey2020",controller:e,publicKeyJwk:n,publicKeyMultibase:r}],authentication:[`${e}#${i}`],assertionMethod:[`${e}#${i}`]}}function me(e){if(e.publicKeyJwk)return e.publicKeyJwk;const t=function(e){try{if(e.publicKeyMultibase?.startsWith("z")){const t=W(e.publicKeyMultibase.slice(1)),n=t.length===le+ue.length&&t[0]===ue[0]&&t[1]===ue[1]?t.slice(ue.length):t;return n.length===le?n:void 0}if(e.publicKeyBase58){const t=W(e.publicKeyBase58);return t.length===le?t:void 0}}catch{return}}(e);return t?he(t):void 0}const ve=["id","delegation"];function Ie(e,t={}){const n=I(e);if(!n.success)return{valid:!1,reason:`Schema validation failed: ${n.error?.message}`};if(m(e))return{valid:!1,reason:"Delegation credential expired"};if(v(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 i=function(e){const t=Object.keys(e.credentialSubject).filter(e=>!ve.includes(e));return 0===t.length?{valid:!0}:{valid:!1,reason:`credentialSubject contains non-delegation field(s): ${t.join(", ")}. A DelegationCredential subject MUST carry only 'id' and 'delegation' (KYA-OS §11.6).`}}(e);return i.valid?{valid:!0}:i}async function we(e,t){const n=Date.now();try{return t?await t.checkStatus(e)?{valid:!1,reason:`Credential revoked via StatusList2021 (${e.statusPurpose})`,outcome:"revoked",durationMs:Date.now()-n}:{valid:!0,durationMs:Date.now()-n}:{valid:!1,reason:"Credential has credentialStatus but no status list resolver is configured — cannot verify revocation status",outcome:"status_unresolvable",durationMs:Date.now()-n}}catch(e){return{valid:!1,reason:`Status check error: ${e instanceof Error?e.message:"Unknown error"}`,outcome:"status_unresolvable",durationMs:Date.now()-n}}}const _e=new TextEncoder,Ee=new TextDecoder,be=new TextDecoder("utf-8",{fatal:!0});function Se(...e){const t=e.reduce((e,{length:t})=>e+t,0),n=new Uint8Array(t);let r=0;for(const t of e)n.set(t,r),r+=t.length;return n}function Ae(e){const t=new Uint8Array(e.length);for(let n=0;n<e.length;n++){const r=e.charCodeAt(n);if(r>127)throw new TypeError("non-ASCII string encountered in encode()");t[n]=r}return t}function De(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e);const t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}const ke="The input to be decoded is not correctly encoded.";function Te(e){if(Uint8Array.fromBase64)try{return Uint8Array.fromBase64("string"==typeof e?e:Ee.decode(e),{alphabet:"base64url"})}catch(e){throw new TypeError(ke,{cause:e})}let t=e;if(t instanceof Uint8Array&&(t=Ee.decode(t)),t.includes("+")||t.includes("/"))throw new TypeError(ke);t=t.replace(/-/g,"+").replace(/_/g,"/");try{return De(t)}catch{throw new TypeError(ke)}}function Ce(e){let t=e;return"string"==typeof t&&(t=_e.encode(t)),Uint8Array.prototype.toBase64?t.toBase64({alphabet:"base64url",omitPadding:!0}):function(e){if(Uint8Array.prototype.toBase64)return e.toBase64();const t=[];for(let n=0;n<e.length;n+=32768)t.push(String.fromCharCode.apply(null,e.subarray(n,n+32768)));return btoa(t.join(""))}(t).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}class Oe 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 Ne extends Oe{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"}class Re extends Oe{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"}class Pe extends Oe{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"}class xe extends Oe{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"}Symbol.asyncIterator;class ze extends Oe{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(e="signature verification failed",t){super(e,t)}}function $e(e){const t={__proto__:null};for(const n in e)t[n]={...e[n],alg:n};return t}const Me=[["verify"],["sign"]];function Le(e){const t={name:"HMAC",hash:`SHA-${e}`};return{kty:["oct"],secret:!0,subtle:t,signing:t,usages:Me}}function Ue(e,t){const n={name:t?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:`SHA-${e}`};return{kty:["RSA"],subtle:n,signing:t?{...n,saltLength:t}:n,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 He(){const e={name:"Ed25519"};return{kty:["OKP"],crv:"Ed25519",subtle:e,signing:e,usages:Me}}function Ke(e){const t={name:`ML-DSA-${e}`};return{kty:["AKP"],subtle:t,signing:t,usages:Me}}const Ve=$e({HS256:Le(256),HS384:Le(384),HS512:Le(512),RS256:Ue(256),RS384:Ue(384),RS512:Ue(512),PS256:Ue(256,32),PS384:Ue(384,48),PS512:Ue(512,64),ES256:je("P-256",256),ES384:je("P-384",384),ES512:je("P-521",512),EdDSA:He(),Ed25519:He(),"ML-DSA-44":Ke(44),"ML-DSA-65":Ke(65),"ML-DSA-87":Ke(87)});function Fe(e){const t="string"==typeof e?Ve[e]:void 0;if(!t)throw new Re(`alg ${e} is not supported either by JOSE or your javascript runtime`);return t}const qe=[["encrypt","wrapKey"],["decrypt","unwrapKey"]],Be=[[],["deriveBits"]],Je=[[],[]];function We(e){return{kty:["RSA"],mode:"key-encryption",subtle:{name:"RSA-OAEP",hash:`SHA-${e}`},usages:qe,ops:["wrapKey","unwrapKey"]}}function Ge(e){return{kty:["EC","OKP"],mode:e,subtle:{name:"ECDH"},resolve:({kty:e,crv:t,asymmetricKeyType:n})=>{if("X25519"===t||"x25519"===n)return{name:"X25519"};if("OKP"===e)throw new Re('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');return{name:"ECDH",namedCurve:t}},usages:Be,ops:[void 0,"deriveBits"]}}function Ze(e,t=!1){return{kty:["oct"],mode:"key-wrapping",secret:!0,subtle:{name:t?"AES-GCM":"AES-KW",length:e},usages:Je,ops:t?["encrypt","decrypt"]:["wrapKey","unwrapKey"]}}function Ye(){return{kty:["oct"],mode:"key-wrapping",secret:!0,subtle:{name:"PBKDF2"},usages:Je,ops:["deriveBits","deriveBits"]}}const Xe=$e({dir:{kty:["oct"],mode:"direct-encryption",secret:!0,subtle:{name:"AES-GCM"},usages:Je,ops:["encrypt","decrypt"]},"RSA-OAEP":We(1),"RSA-OAEP-256":We(256),"RSA-OAEP-384":We(384),"RSA-OAEP-512":We(512),"ECDH-ES":Ge("direct-key-agreement"),"ECDH-ES+A128KW":Ge("key-agreement-with-key-wrapping"),"ECDH-ES+A192KW":Ge("key-agreement-with-key-wrapping"),"ECDH-ES+A256KW":Ge("key-agreement-with-key-wrapping"),A128KW:Ze(128),A192KW:Ze(192),A256KW:Ze(256),A128GCMKW:Ze(128,!0),A192GCMKW:Ze(192,!0),A256GCMKW:Ze(256,!0),"PBES2-HS256+A128KW":Ye(),"PBES2-HS384+A192KW":Ye(),"PBES2-HS512+A256KW":Ye()}),Qe=["encrypt","decrypt"];function et(e,t=!1){return{kty:["oct"],secret:!0,subtle:{name:t?"AES-CBC":"AES-GCM",length:e},usages:Je,ops:Qe,cekBits:e,ivBits:t?128:96,cbc:t}}$e({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 nt(e='JWK "alg" (Algorithm) Parameter'){throw new Re(`Invalid or unsupported ${e} value`)}function rt(e,t){return("string"==typeof e?Ve[e]??Xe[e]:void 0)??nt(t)}function it(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 n=0;n<e.byteLength;n++)if(e[n]!==t[n])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 n=127&t;let r=0;for(let t=0;t<n;t++)r=r<<8|st(e);return r}return t},ct=(e,t,n)=>{if(st(e)!==t)throw new Error(n)},dt=(e,t)=>{if(t<0||e.pos+t>e.data.length)throw new Error("Unexpected end of ASN.1 input");const n=e.data.subarray(e.pos,e.pos+t);return e.pos+=t,n},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 n=at(e),r=dt(e,n);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 Re('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');const n=e.resolve?.({kty:t.kty,crv:t.crv})??e.subtle,r=!(!t.d&&!t.priv),i={...t};return"AKP"!==i.kty&&delete i.alg,delete i.use,crypto.subtle.importKey("jwk",i,n,t.ext??!r,t.key_ops??e.usages[r?1:0])}function pt(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 ft(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,n=Array.isArray(e)?[...e]:void 0;if(!n||n.some(e=>"string"!=typeof e)||new Set(n).size!==n.length)throw new TypeError('"key_ops" (Key Operations) Parameter must be an array of unique strings');t.key_ops=n}return t}async function ht(e,t,n){if("string"!=typeof e||0!==e.indexOf("-----BEGIN PRIVATE KEY-----"))throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return((e,t,n)=>{const r=((e,t)=>De(e.replace(t,"")))(e,/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g);return(async(e,t,n,r)=>{const i=it(r?.extractable),o=rt(n,tt);o.secret&&nt(tt);const s="spki"===e;let a;if(o.resolve)try{const n={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)})(n,e),a=o.resolve({crv:ut(n)})}catch{throw new Re("Invalid or unsupported key format")}else a=o.subtle;return crypto.subtle.importKey(e,t,a,i??s,o.usages[s?0:1])})("pkcs8",r,t,n)})(e,t,n)}async function gt(e,t,n){if(!pt(e))throw new TypeError("JWK must be an object");const r=ft(e),i=it(n?.extractable),{alg:o}=r;t??=o;const s=i??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 Re('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 mt(e,t,n){return t instanceof Uint8Array?crypto.subtle.importKey("raw",t,e.subtle,!1,[n]):(function(e,t,n){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,n)}(t,e.subtle,n),e.minRsaBits&&function(e,t){const{modulusLength:n}=t.algorithm;if("number"!=typeof n||n<2048)throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}(e.alg,t),t)}function vt(e,t){if(void 0!==e)throw new TypeError(`${t} can only be called once`)}function It(e,t,n){try{return Te(e)}catch{throw new n(`Failed to base64url decode the ${t}`)}}const wt={__proto__:null,b64:!0};function _t(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 Et(e,t,n,r,i){if(void 0!==i.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===n?t:{__proto__:null,...n,...t};for(const t of r.crit){if(!(t in o))throw new Re(`Extension Header Parameter "${t}" is not recognized`);if(!Object.hasOwn(i,t)||void 0===i[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 bt(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 St=(e,t,...n)=>function(e,t,...n){if(n.length>2){const t=n.pop();e+=`one of type ${n.join(", ")}, or ${t}.`}else 2===n.length?e+=`one of type ${n[0]} or ${n[1]}.`:e+=`of type ${n[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,...n),At=e=>{if("CryptoKey"===e?.[Symbol.toStringTag])return!0;try{return e instanceof CryptoKey}catch{return!1}},Dt=e=>e[Symbol.toStringTag];function kt(e,t,n){const{alg:r,secret:i}=e,o="decrypt"===n||"sign"===n;if(i&&t instanceof Uint8Array)return[Tt,t];if(pt(t)){const s=ft(t);if("string"!=typeof s.kty)throw new TypeError(i?St(r,t,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"):St(r,t,"CryptoKey","KeyObject","JSON Web Key"));if(!(i?"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(i?'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,n)=>{const{alg:r}=e;if(void 0!==t.use){const e="sign"===n||"verify"===n?"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"===n||"decrypt"===n?e.ops?.["encrypt"===n?0:1]:n;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,n),[Nt,t,s]}if(!(e=>At(e)||(e=>"KeyObject"===e?.[Symbol.toStringTag])(e))(t))throw new TypeError(i?St(r,t,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"):St(r,t,"CryptoKey","KeyObject","JSON Web Key"));if(i){if("secret"!==t.type)throw new TypeError(`${Dt(t)} instances for symmetric algorithms must be of type "secret"`)}else{if("secret"===t.type)throw new TypeError(`${Dt(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"===n?"signing":"verify"===n?"verifying":`${n.slice(0,-1)}tion`;throw new TypeError(`${Dt(t)} instances for asymmetric algorithm ${r} must be of type "${e}"`)}}return At(t)?[Ct,t]:[Ot,t]}const Tt=0,Ct=1,Ot=2,Nt=3;let Rt;const Pt={__proto__:null,prime256v1:"P-256",secp384r1:"P-384",secp521r1:"P-521"};function xt(e,t,n){Rt||=new WeakMap;const r=Rt.get(e);return n&&(r?r[t]=n:Rt.set(e,{[t]:n})),n??r?.[t]}const zt=async(e,t,n)=>xt(e,n.alg)??xt(e,n.alg,await lt(n,{...t,alg:n.alg}));async function $t(e,t,n){const r=kt(e,t,n);switch(r[0]){case Tt:case Ct:return r[1];case Nt:{const t=r[1],n=r[2];if("oct"===n.kty)return Te(n.k);if(!Object.isFrozen(t)){const{key_ops:e}=t;Array.isArray(e)&&Object.freeze(e),Object.freeze(t)}return zt(t,n,e)}case Ot:{const t=r[1];return"secret"===t.type?t.export():"toCryptoKey"in t&&"function"==typeof t.toCryptoKey?((e,t)=>{const n=xt(e,t.alg);if(n)return n;const r="public"===e.type,i=t.usages[r?0:1],{asymmetricKeyType:o}=e,s=Pt[e.asymmetricKeyDetails?.namedCurve],a=t.resolve?.({crv:s,asymmetricKeyType:o})??t.subtle;return xt(e,t.alg,e.toCryptoKey(a,r,i))})(t,e):zt(t,t.export({format:"jwk"}),e)}}}async function Mt(e,t,n){if(e instanceof Uint8Array&&(e=Ee.decode(e)),"string"!=typeof e)throw new Pe("Compact JWS must be a string or Uint8Array");const{0:r,1:i,2:o,length:s}=e.split(".");if(3!==s)throw new Pe("Invalid Compact JWS");const a={payload:i,protected:r,signature:o},c=function(e,t=(void 0===e?{}:function(e,t,n){let r;try{r=JSON.parse(be.decode(Te(e)))}catch{throw new t(n)}if(!pt(r))throw new t(n);return r}(e,Pe,"JWS Protected Header is invalid"))){return t}(r),[d,u]=function(e,t,n){const r=bt(e,Et(Pe,wt,n[1],e,t)),i=t.alg;if("string"!=typeof i||!i)throw new Pe('JWS "alg" (Algorithm) Header Parameter missing or invalid');if(n[0]&&!n[0].has(i))throw new Ne('"alg" (Algorithm) Header Parameter value not allowed');return[r,i]}(c,c,t),l=d?i:function(e){try{return Ae(e)}catch{throw new Pe("JWS Compact Serialization payload must use only ASCII characters")}}(i);return async function(e,t,n,r,i,o,s){let a=!1;"function"==typeof n&&(n=await n(i,e),a=!0);const c="string"==typeof s,d=Fe(o),u=Se(void 0!==r?Ae(r):new Uint8Array,Ae("."),c?t[2]??=function(e,t,n){try{return Ae(e)}catch{throw new n("The payload is not a valid base64url string")}}(s,0,Pe):s),l=It(e.signature,"signature",Pe),p=await $t(d,n,"verify");if(!await async function(e,t,n,r){const i=await mt(e,t,"verify");try{return await crypto.subtle.verify(e.signing,i,n,r)}catch{return!1}}(d,p,l,u))throw new ze;return[c?It(s,"payload",Pe):s,i,c,p,a]}(a,t,n,r,c,u,l)}async function Lt(e,t,n){const r=await Mt(e,function(e){return[e&&_t("algorithms",e.algorithms),e?.crit]}(n),t),i={payload:r[0],protectedHeader:r[1]};return"function"==typeof t?{...i,key:r[3]}:i}function Ut(e,t,n){return{valid:!1,reason:e,stage:"basic",metrics:void 0!==n?{basicCheckMs:n,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 Ht{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 n=Date.now(),r=this.cacheKeyForCredential("di",e,t),i=Date.now(),o=Ie(e),s=Date.now()-i;if(!o.valid)return{valid:!1,reason:o.reason,stage:"basic",metrics:{basicCheckMs:s,totalMs:Date.now()-n},checks:{basicValid:!1}};const a=this.cachedSignature(r,()=>t.skipSignature?Promise.resolve({valid:!0,durationMs:0}):async function(e,t,n){const r=Date.now();try{const o="string"==typeof e.issuer?e.issuer:e.issuer.id;if(!t||!n)return{valid:!1,reason:"No DID resolver or signature verifier configured — signature cannot be verified",durationMs:Date.now()-r};if(e.proof&&("string"!=typeof(i=e.proof.type)||!g.has(i)))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=me(c);if(!d)return{valid:!1,reason:"Verification method has no usable public key (publicKeyJwk / publicKeyMultibase / publicKeyBase58)",durationMs:Date.now()-r};const u=await n(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 i}(e,t.didResolver||this.didResolver,this.signatureVerifier)),c=!t.skipStatus&&e.credentialStatus?we(e.credentialStatus,t.statusListResolver||this.statusListResolver):Promise.resolve({valid:!0,durationMs:0});return this.finalizeVerification(a,c,s,n)}async verifyDelegationJwt(e,t={}){const n=Date.now(),r=function(e,t){const n=K(e);if(!n)return{failure:Ut("Not a valid VC-JWT (parse failed)",t)};const r=Date.now(),i=n.payload.vc,o=Ie(i,{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}(i)!==n.payload.iss?{failure:Ut("Credential `issuer` does not match the JWT `iss` (the verified signer)",t,s)}:{vc:i,issuerDid:n.payload.iss,kid:n.header.kid,basicCheckMs:s}:{failure:Ut(o.reason,t,s)}}(e,n);if("failure"in r)return r.failure;const{vc:i,issuerDid:o,kid:s,basicCheckMs:a}=r,c=this.cacheKeyForJwt(e,i,t),d=this.cachedSignature(c,()=>t.skipSignature?Promise.resolve({valid:!0,durationMs:0}):async function(e,t,n,r){const i=Date.now(),o=(e,t)=>({valid:e,reason:t,durationMs:Date.now()-i});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??[],n);if(!a)return o(!1,n?`Verification method ${n} not found in DID Document`:"DID Document has no verification method");const c=me(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 Lt(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&&i.credentialStatus?we(i.credentialStatus,t.statusListResolver||this.statusListResolver):Promise.resolve({valid:!0,durationMs:0});return this.finalizeVerification(d,u,a,n)}async cachedSignature(e,t){if(null!==e){const t=this.cache.get(e);if(t)return{result:{...t,durationMs:0},cached:!0}}const n=await t();return n.valid&&null!==e&&this.cache.set(e,n),{result:n,cached:!1}}async finalizeVerification(e,t,n,r){const[i,o]=await Promise.all([e,t]),s=function(e,t,n,r){const i=e.valid&&t.valid;return{valid:i,reason:i?void 0:e.reason||t.reason||"Unknown failure",statusOutcome:t.outcome,stage:"complete",metrics:{basicCheckMs:n,signatureCheckMs:e.durationMs||0,statusCheckMs:t.durationMs||0,totalMs:Date.now()-r},checks:{basicValid:!0,signatureValid:e.valid,statusValid:t.valid}}}(i.result,o,n,r);return i.cached&&(s.cached=!0),s}cacheKeyForCredential(e,t,n){if(!this.cacheAllowed(n))return null;try{return`${e}\0${t.id??""}\0${M(t)}`}catch{return null}}cacheKeyForJwt(e,t,n){return this.cacheAllowed(n)?`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`,n=`jwt\0${e}\0`;this.cache.deleteWhere(e=>e.startsWith(t)||e.startsWith(n))}}function Kt(e){return new Ht(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(n=this.storage)&&"function"==typeof n.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 n;return t}async addChildToParent(e,t){const n=await this.storage.getNode(e);if(!n)throw new Error(`Parent delegation not found: ${e}`);n.children.includes(t)||(n.children.push(t),await this.storage.setNode(n))}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 n=t[e-1],r=t[e];if(r.issuerDid!==n.subjectDid)return{valid:!1,reason:`Invalid chain: ${r.id} issued by ${r.issuerDid} but parent ${n.id} subject is ${n.subjectDid}`};if(r.parentId!==n.id)return{valid:!1,reason:`Invalid chain: ${r.id} parentId=${r.parentId} but actual parent is ${n.id}`}}return{valid:!0}}async removeDelegation(e){const t=await this.storage.getNode(e);if(t){if(t.parentId){const n=await this.storage.getNode(t.parentId);n&&(n.children=n.children.filter(t=>t!==e),await this.storage.setNode(n))}await this.storage.deleteNode(e)}}}function Ft(e){return new Vt(e)}const qt=16777216,Bt="u";async function Jt(e,t){const n=e[0]===Bt?e.slice(1):e,r=await t(s(n));if(r.length>qt)throw new Error(`Status list too large: ${r.length} bytes exceeds ${qt}`);return r instanceof Uint8Array?r:new Uint8Array(r)}class Wt{compressor;bits;size;constructor(e,t,n){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 n=Math.floor(e/8),r=e%8;t?this.bits[n]|=128>>r:this.bits[n]&=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),n=e%8;return!!(this.bits[t]&128>>n)}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 Bt+this.base64urlEncode(e)}static async decode(e,t,n){const r=await Jt(e,e=>n.decompress(e)),i=8*r.length,o=new Wt(i,t,n);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,n,r){const i=new Wt(e,n,r);for(const e of t)i.setBit(e,!0);return i}}async function Gt(e,t,n){return function(e,t){const n=Number.isInteger(t)&&t>=0?e[Math.floor(t/8)]:void 0;if(void 0===n)throw new Error(`Bit index ${t} out of range for the status list`);return!!(n&128>>t%8)}(await Jt(e,e=>n.decompress(e)),t)}class Zt{storage;identity;signingFunction;compressor;decompressor;statusListBaseUrl;defaultListSize;updateLocks=new Map;constructor(e,t,n,r,i,o){this.storage=e,this.identity=t,this.signingFunction=n,this.compressor=r,this.decompressor=i,this.statusListBaseUrl=o?.statusListBaseUrl||"https://status.example.com",this.defaultListSize=o?.defaultListSize||131072}async allocateStatusEntry(e){const t=`${this.statusListBaseUrl}/${e}/v1`,n=await this.storage.allocateIndex(t);return await this.ensureStatusListExists(t,e),{id:`${t}#${n}`,type:"StatusList2021Entry",statusPurpose:e,statusListIndex:n.toString(),statusListCredential:t}}async updateStatus(e,t){const{statusListCredential:n}=e,r=(this.updateLocks.get(n)??Promise.resolve()).then(()=>this.doUpdateStatus(e,t));this.updateLocks.set(n,r.catch(()=>{})),await r}async doUpdateStatus(e,t){const{statusListCredential:n,statusListIndex:r}=e,i=await this.storage.getStatusList(n);if(!i)throw new Error(`Status list not found: ${n}`);const o=await Wt.decode(i.credentialSubject.encodedList,this.compressor,this.decompressor),s=parseInt(r,10);o.setBit(s,t);const a=await o.encode(),c={...i,credentialSubject:{...i.credentialSubject,encodedList:a}},d={...c};delete d.proof;const u=U(d),l=await this.signingFunction(u,this.identity.getDid(),this.identity.getKeyId()),p={...c,proof:l};await this.storage.setStatusList(n,p)}async checkStatus(e){const{statusListCredential:t,statusListIndex:n}=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 i=await Wt.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}(n);return i.getBit(o)}async getRevokedIndices(e){const t=await this.storage.getStatusList(e);return t?(await Wt.decode(t.credentialSubject.encodedList,this.compressor,this.decompressor)).getSetBits():[]}async ensureStatusListExists(e,t){if(await this.storage.getStatusList(e))return;const n=new Wt(this.defaultListSize,this.compressor,this.decompressor),r=await n.encode(),i={"@context":["https://www.w3.org/2018/credentials/v1","https://w3id.org/vc/status-list/2021/v1"],id:e,type:["VerifiableCredential","StatusList2021Credential"],issuer:this.identity.getDid(),issuanceDate:(new Date).toISOString(),credentialSubject:{id:`${e}#list`,type:"StatusList2021",statusPurpose:t,encodedList:r}},o=U(i),s=await this.signingFunction(o,this.identity.getDid(),this.identity.getKeyId()),a={...i,proof:s};await this.storage.setStatusList(e,a)}getStatusListBaseUrl(){return this.statusListBaseUrl}getDefaultListSize(){return this.defaultListSize}}function Yt(e,t,n,r,i,o){return new Zt(e,t,n,r,i,o)}class Xt{graph;statusList;constructor(e,t){this.graph=e,this.statusList=t}async revokeDelegation(e,t={}){const n=t.maxDepth||100,r=[],i=await this.graph.getNode(e);if(!i)throw new Error(`Delegation not found: ${e}`);const o=await this.graph.getDepth(e);if(o>n)throw new Error(`Delegation depth ${o} exceeds maximum ${n}`);const s=await this.revokeNode(i,!0,t.reason,t.dryRun);r.push(s),t.onRevoke&&await t.onRevoke(s);const a=await this.graph.getDescendants(e);for(const n of a){const i=await this.revokeNode(n,!1,`Cascaded from ${e}`,t.dryRun,e);r.push(i),t.onRevoke&&await t.onRevoke(i)}return r}async revokeNode(e,t,n,r,i){const o={delegationId:e.id,isRoot:t,parentId:i,timestamp:Date.now(),reason:n};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 n={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 n}async isRevoked(e){const t=await this.graph.getChain(e);for(const n of t)if(n.credentialStatusId){const t=this.parseCredentialStatus(n.credentialStatusId);if(t&&await this.statusList.checkStatus(t))return{revoked:!0,reason:n.id===e?"Directly revoked":"Ancestor revoked",revokedAncestor:n.id===e?void 0:n.id}}return{revoked:!1}}async getRevokedInSubtree(e){const t=await this.graph.getDescendants(e),n=[];(await this.isRevoked(e)).revoked&&n.push(e);for(const e of t)(await this.isRevoked(e.id)).revoked&&n.push(e.id);return n}parseCredentialStatus(e){const t=e.match(/^(.+)#(\d+)$/);if(!t)return null;const[,n,r]=t;return{id:e,type:"StatusList2021Entry",statusPurpose:"revocation",statusListIndex:parseInt(r,10).toString(),statusListCredential:n}}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 n=await this.graph.validateChain(e);return n.valid?{valid:!0}:n}}function Qt(e,t){return new Xt(e,t)}function en(e,t){if(!e.constraints.audience)return!0;const n=e.constraints.audience;return"string"==typeof n?n===t:n.includes(t)}async function tn(e,t,n,r,i){const[o,s]=function(e){if(void 0===e)return[void 0,""];const t=function(e,t){let n,r;try{n=JSON.stringify(t),r=JSON.parse(n)}catch(t){throw new e("JOSE Header is not valid JSON",{cause:t})}if(!pt(r))throw new e("JOSE Header is not a JSON object");return[r,n]}(Pe,e);return[t[0],Ce(t[1])]}(t);if(!o)throw new Pe("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");(function(e,t,n){return function(e,t){const{crit:n}=t??{};if(Array.isArray(n)&&new Set(n).size!==n.length)throw new e('"crit" (Critical) Header Parameter MUST NOT contain duplicate values')}(Pe,e),bt(e,Et(Pe,wt,n,e,t))})(o,o,n)||i();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 Fe(t)}(o),c=Ce(e);return`${s}.${c}.${await async function(e,t,n,r){const i=Se(Ae(e),Ae("."),t),o=await $t(n,r,"sign");return Ce(await async function(e,t,n){const r=await mt(e,t,"sign"),i=await crypto.subtle.sign(e.signing,r,n);return new Uint8Array(i)}(n,o,i))}(s,Ae(c),a,r)}`}const nn=e=>Math.floor(e.getTime()/1e3),rn={s:1,m:60,h:3600,d:86400,w:604800,y:31557600},on=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;function sn(){throw new TypeError("Invalid time period format")}function an(e){"string"!=typeof e&&sn();const t=on.exec(e);(!t||t[4]&&t[1])&&sn();const n=parseFloat(t[2]),r=Math.round(n*rn[t[3][0].toLowerCase()]);return Number.isFinite(r)||sn(),"-"===t[1]||"ago"===t[4]?-r:r}function cn(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}function dn(e,t){if("string"!=typeof t)throw new TypeError(`"${e}" claim must be a string`)}function un(e,t){return"number"==typeof e?cn(t,e):e instanceof Date?cn(t,nn(e)):nn(new Date)+an(e)}let ln;function pn(e){return ln.get(e)}const fn=class{constructor(e={}){if(!pt(e))throw new TypeError("JWT Claims Set MUST be an object");(ln||=new WeakMap).set(this,structuredClone(e))}setIssuer(e){return dn("iss",e),pn(this).iss=e,this}setSubject(e){return dn("sub",e),pn(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),pn(this).aud=e,this}setJti(e){return dn("jti",e),pn(this).jti=e,this}setNotBefore(e){return pn(this).nbf=un(e,"setNotBefore"),this}setExpirationTime(e){return pn(this).exp=un(e,"setExpirationTime"),this}setIssuedAt(e){return pn(this).iat=void 0===e?nn(new Date):"string"==typeof e?cn("setIssuedAt",nn(new Date)+an(e)):un(e,"setIssuedAt"),this}};class hn extends fn{#e;setProtectedHeader(e){return vt(this.#e,"setProtectedHeader"),this.#e=e,this}async sign(e,t){return tn(function(e){const t=pn(e);for(const e of["iat","nbf","exp"]){const n=t[e];if("number"==typeof n&&!Number.isFinite(n))throw new TypeError(`"${e}" claim must be a finite number`)}return _e.encode(JSON.stringify(t))}(this),this.#e,t?.crit,e,()=>{throw new xe("JWTs MUST NOT use unencoded payload")})}}async function gn(e){const{agentDid:t,userDid:n,delegationId:r,delegationChain:i,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 hn({delegation_id:r,delegation_chain:i,scope:o.join(",")}).setProtectedHeader({alg:"EdDSA",kid:a}).setIssuer(t).setSubject(n).setJti(crypto.randomUUID()).setAudience(c).setIssuedAt(u).setExpirationTime(l).sign(d)}function yn(e){return e.id||e.vcId?e.vcId?`${e.vcId}>${e.id}`:e.id:""}const mn={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 vn(e){const{session:t,delegation:n,serverIdentity:r,targetUrl:i}=e;if(!t.agentDid)throw new Error("Session must have agentDid for outbound delegation");if(!t.sessionId)throw new Error("Session must have sessionId for outbound delegation");if(!n.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}}(i),s=function(e,t){const n=u(e),r=64===n.length?n.subarray(0,32):n;if(!pe(t))throw new Error(`Server DID must be did:key with Ed25519: ${t}`);const i=fe(t);if(!i)throw new Error(`Failed to extract public key from DID: ${t}`);return{kty:"OKP",crv:"Ed25519",x:c(i),d:c(r)}}(r.privateKey,r.did),a=await gn({agentDid:r.did,userDid:t.agentDid,delegationId:n.id,delegationChain:n.vcId,scopes:["delegation:propagate"],privateKeyJwk:s,kid:r.kid,targetHostname:o});return de.debug("Built outbound delegation headers",{agentDid:t.agentDid,delegationChain:n.vcId,sessionId:t.sessionId,targetHostname:o}),{"KYA-OS-Agent-DID":t.agentDid,"KYA-OS-Delegation-Chain":n.vcId,"KYA-OS-Session-Id":t.sessionId,"KYA-OS-Delegation-Proof":a}}class In{#t;#e;constructor(e){if(!(e instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this.#t=e}setProtectedHeader(e){return vt(this.#e,"setProtectedHeader"),this.#e=e,this}async sign(e,t){return tn(this.#t,this.#e,t?.crit,e,()=>{throw new TypeError("use the flattened module for creating JWS with b64: false")})}}class wn{cryptoProvider;constructor(e){this.cryptoProvider=e}async verifyEd25519(e,t,n){try{return!0===await this.cryptoProvider.verify(e,t,n)}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[n,r,i]=t;let a,c,d;try{a=JSON.parse(o(n))}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(i)}catch(e){throw new Error(`Invalid signature base64: ${e instanceof Error?e.message:String(e)}`)}return{header:a,payload:c,signatureBytes:d,signingInput:`${n}.${r}`}}async verifyJWS(e,t,n){try{if(!this.isValidEd25519JWK(t))return de.error("[CryptoService] Invalid Ed25519 JWK format"),!1;if(n?.expectedKid&&t.kid!==n.expectedKid)return de.error("[CryptoService] Key ID mismatch"),!1;let r;try{r=this.parseJWS(e)}catch(t){if(void 0===n?.detachedPayload)return de.error("[CryptoService] Invalid JWS format:",t),!1;{const n=e.split(".");if(3!==n.length||""!==n[1])return de.error("[CryptoService] Invalid JWS format:",t),!1;try{const e=n[0],t=n[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 i=n?.alg||"EdDSA";if(r.header.alg!==i)return de.error(`[CryptoService] Unsupported algorithm: ${r.header.alg}, expected ${i}`),!1;if(void 0!==n?.expectedKid&&r.header.kid!==n.expectedKid)return de.error("[CryptoService] Protected JWS key ID mismatch"),!1;let a,d;if(void 0!==n?.detachedPayload){const t=e.split(".")[0];let r;r=n.detachedPayload instanceof Uint8Array?c(n.detachedPayload):c((new TextEncoder).encode(n.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 _n=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]),En=12,bn=32,Sn="org.kya-os/response-proof",An="org.kya-os/proof",Dn="proof";async function kn(e,t,n,r=A){const i={method:e.method,...e.params?{params:e.params}:{}},o=await n(L(i));if(void 0===t)return{requestHash:o};const s=await n(L(function(e,t){if(t!==D||null===e||"object"!=typeof e||Array.isArray(e))return e;const n={};for(const[t,r]of Object.entries(e))"_meta"!==t&&(n[t]=r);return n}(t.data,r)));return{requestHash:o,responseHash:s}}function Tn(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 Cn{identity;cryptoProvider;constructor(e,t){this.identity=e,this.cryptoProvider=t}async generateProof(e,t,n,r={}){const{profile:i=A,...o}=r;Reflect.deleteProperty(o,"prf");const s=await this.generateCanonicalHashes(e,t,i),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:n.audience,sessionId:n.sessionId,requestHash:s.requestHash,...void 0!==s.responseHash?{responseHash:s.responseHash}:{},...i===D?{prf:D}:{},...o};return{jws:await this.generateJWS(d),meta:d}}async hashRequest(e){return(await this.generateCanonicalHashes(e)).requestHash}async generateCanonicalHashes(e,t,n){return kn(e,t,e=>this.cryptoProvider.hash(e),n)}async resolveSigningKey(){const e=this.identity.privateKey;return"string"==typeof e?ht(this.formatPrivateKeyAsPEM(e),"EdDSA"):e}async generateJWS(e){try{const t=await this.resolveSigningKey(),n=M(Tn(e)),r=(new TextEncoder).encode(n);return await new In(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,bn),n=new Uint8Array(_n.length+t.length);n.set(_n),n.set(t,_n.length);const r=d(n);return"-----BEGIN PRIVATE KEY-----\n"+(r.match(/.{1,64}/g)?.join("\n")??r)+"\n-----END PRIVATE KEY-----"}async verifyProof(e,t,n){try{const r=await this.generateCanonicalHashes(t,n,e.meta.prf??A);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 i=this.base64PublicKeyToJWK(this.identity.publicKey);return new wn(this.cryptoProvider).verifyJWS(e.jws,i,{expectedKid:this.identity.kid,alg:"EdDSA"})}catch{return!1}}base64PublicKeyToJWK(e){const t=u(e);if(t.length!==bn)throw new Error(`Invalid Ed25519 public key length: ${t.length}`);return{kty:"OKP",crv:"Ed25519",x:c(t),kid:this.identity.kid}}}async function On(e,t,n,r,i,o={}){const s={data:t},a=new Cn(n,i),c=await a.generateProof(e,s,r,o);return s.meta={proof:c},s}function Nn(e,t){return{request:{method:e.method,...e.params?{params:e.params}:{}},response:t.data}}const Rn="_kyaos";function Pn(e){return e.startsWith(Rn)}function xn(e,t){const n={};for(const[e,r]of Object.entries(t))Pn(e)||(n[e]=r);return{method:e,params:n}}async function zn(e){const{identity:t,crypto:n,toolName:r,args:i,audience:o,sessionId:s}=e,a=new Cn(t,n),d=xn(r,i),u=c(await n.randomBytes(16)),l=Math.floor(Date.now()/1e3),p=s??`req-${c(await n.randomBytes(9))}`;return a.generateProof(d,void 0,{sessionId:p,audience:o,nonce:u,timestamp:l,createdAt:l,lastActivity:l,ttlMinutes:30,identityState:"anonymous"})}const $n="holder_binding_failed";function Mn(e){return null!==fe(e)}async function Ln(e){const{proof:t,subjectDid:n,request:r,response:i,expectedAudience:o,proofVerifier:s}=e,a=fe(n);if(!a)return{status:"not_applicable",reason:`Holder binding (phase 1) covers did:key subjects only; "${Y(n)??"unknown"}" is deferred to cnf-based binding`};if("object"!=typeof t?.meta||null===t.meta)return{status:"unbound",errorCode:$n,reason:"Malformed proof: missing meta"};if(t.meta.did!==n)return{status:"unbound",errorCode:$n,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:$n,reason:"Proof audience does not match this server",cause:"audience_mismatch"};const c=he(a);c.kid=`${n}#${se(n)}`;const d=await s.verifyProof(t,c,{request:r,...void 0!==i?{response:i}:{}});return d.valid?{status:"bound"}:{status:"unbound",errorCode:$n,reason:"Request proof is not bound to the delegation subject",...void 0!==d.errorCode?{cause:d.errorCode}:{}}}function Un(e){return structuredClone(e)}class jn{statusLists=new Map;versions=new Map;indexCounters=new Map;async getStatusList(e){const t=this.statusLists.get(e);return void 0===t?null:Un(t)}async setStatusList(e,t){const n=Un(t);this.statusLists.set(e,n);const r=this.versions.get(e)??[];r.push(n),this.versions.set(e,r)}async allocateIndex(e){const t=this.indexCounters.get(e)||0,n=t;return this.indexCounters.set(e,t+1),n}getIndexCount(e){return this.indexCounters.get(e)||0}async getStatusListVersion(e,t){if(!Number.isSafeInteger(t)||t<1)return null;const n=this.versions.get(e)?.[t-1];return void 0===n?null:Un(n)}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 Hn{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 n={...e,children:[...e.children]};if(null!=t){const n={...t,children:t.children.includes(e.id)?[...t.children]:[...t.children,e.id]};this.nodes.set(n.id,n)}this.nodes.set(n.id,n)}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 n=e;for(;n;){const e=this.nodes.get(n);if(!e)break;t.unshift(e),n=e.parentId}return t}async getDescendants(e){const t=[],n=[e],r=new Set;for(;n.length>0;){const e=n.shift();if(r.has(e))continue;r.add(e);const i=this.nodes.get(e);if(i)for(const e of i.children)if(!r.has(e)){n.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,n=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:n,maxDepth:r}}getChainSync(e){const t=[];let n=e;for(;n;){const e=this.nodes.get(n);if(!e)break;t.unshift(e),n=e.parentId}return t}}function Kn(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 Vn(e){return e.startsWith("did:web:")}function Fn(e){if(!Vn(e))return null;const t=e.slice(8);if(0===t.length)return null;const n=t.split(":"),r=decodeURIComponent(n[0]);return 0===r.length?null:{domain:r,path:n.slice(1).map(e=>decodeURIComponent(e))}}function qn(e){const t=Fn(e);if(!t)return null;const{domain:n,path:r}=t;let i=`https://${n}`;return 0===r.length?i+="/.well-known/did.json":i+="/"+r.join("/")+"/did.json",i}class Bn{fetchProvider;cache;cacheTtl;constructor(e,t){this.fetchProvider=e,this.cache=new Map,this.cacheTtl=t?.cacheTtl??3e5}async resolve(e){if(!Vn(e))return null;const t=this.cache.get(e);if(t&&Date.now()<t.expiresAt)return t.document;const n=qn(e);if(!n)return de.warn(`[DidWebResolver] Invalid did:web format: ${e}`),null;try{const t=await this.fetchProvider.fetch(n);if(!t.ok)return de.warn(`[DidWebResolver] HTTP ${t.status} fetching ${n}`),null;let r;try{r=await t.json()}catch{return de.warn(`[DidWebResolver] Invalid JSON from ${n}`),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(!Kn(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 ${n}`),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 Jn(e,t){return new Bn(e,t)}const Wn=new Uint8Array([237,1]),Gn=["https://www.w3.org/ns/did/v1","https://w3id.org/security/suites/ed25519-2020/v1"];function Zn(e,t){const n=Array.isArray(e)?e:[e],r=n[0];if(!r)throw new Error("buildDidWebDocument: at least one identity is required");const i=r.did;if(!Vn(i))throw new Error(`buildDidWebDocument: identity.did must be a did:web DID (got "${i}")`);const o=n.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 n=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:he(n),publicKeyMultibase:Yn(n)}}(e,i)),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?[...Gn,...t.additionalContexts]:[...Gn],id:i,...t?.alsoKnownAs?.length?{alsoKnownAs:[...t.alsoKnownAs]}:{},verificationMethod:o,authentication:s,assertionMethod:s}}function Yn(e){const t=new Uint8Array(Wn.length+e.length);return t.set(Wn),t.set(e,Wn.length),`z${J(t)}`}function Xn(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Qn(e){const t=e.requireBidirectional??!0,n=tr(e.primaryDid),r=tr(e.secondaryDid),i=e.primaryDidDocument,o=e.secondaryDidDocument,s={primaryReferencesSecondary:!1,secondaryReferencesPrimary:!1,primaryDocumentMatches:!1,secondaryDocumentMatches:!1};return nr(i)?nr(o)?(s.primaryDocumentMatches=tr(i.id)===n,s.secondaryDocumentMatches=tr(o.id)===r,s.primaryDocumentMatches&&s.secondaryDocumentMatches?(s.primaryReferencesSecondary=er(i,r),s.secondaryReferencesPrimary=er(o,n),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 er(e,t){return(e.alsoKnownAs??[]).some(e=>tr(e)===t)}function tr(e){return e.trim()}function nr(e){return!!Xn(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 rr(e,t){const n={};if(!e)return n;for(const[r,i]of Object.entries(e))/^[a-z0-9]+$/.test(r)&&("function"!=typeof i?n[r]=i:t&&(n[r]=i(t)));return n}class ir{tokens=new Map;ttl;constructor(e=6e5){this.ttl=e}async create(e,t,n){const r=new Uint8Array(16);globalThis.crypto.getRandomValues(r);const i=`rt_${Array.from(r).map(e=>e.toString(16).padStart(2,"0")).join("")}`,o=Date.now();return this.tokens.set(i,{agentDid:e,scopes:t,createdAt:o,expiresAt:o+this.ttl,metadata:n,fulfilled:!1}),i}async get(e){const t=this.tokens.get(e);return t?Date.now()>t.expiresAt?(this.tokens.delete(e),null):t.fulfilled?null:{agentDid:t.agentDid,scopes:t.scopes,createdAt:t.createdAt,expiresAt:t.expiresAt,metadata:t.metadata}:null}async fulfill(e){const t=this.tokens.get(e);t&&(t.fulfilled=!0)}clear(){this.tokens.clear()}}async function or(e,t,n){const r=Date.now();let i,o;if(n.debug&&de.debug(`[AuthHandshake] Verifying ${e} for scopes: ${t.join(", ")}`),n.reputationService&&void 0!==n.authorization.minReputationScore){const r=n.authorization.unknownAgentPolicy??"require-consent";try{i=await async function(e,t){const n=t.apiUrl.replace(/\/$/,""),r={"Content-Type":"application/json"};let i;if(t.apiKey&&(r["X-API-Key"]=t.apiKey),i="v2"===t.apiFormat?await fetch(`${n}/v1/reputation/${encodeURIComponent(e)}`,{method:"POST",headers:r,body:JSON.stringify({include_details:!1})}):await fetch(`${n}/api/v1/reputation/${encodeURIComponent(e)}`,{method:"GET",headers:r}),!i.ok){if(404===i.status)return{agentDid:e,score:null,totalInteractions:0,successRate:0,riskLevel:"unknown",updatedAt:Date.now()};throw new Error(`Reputation API error: ${i.status} ${i.statusText}`)}const o=await i.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,n.reputationService)}catch(t){de.error("[AuthHandshake] Reputation service unreachable, treating agent as unknown:",t),i={agentDid:e,score:null,totalInteractions:0,successRate:0,riskLevel:"unknown",updatedAt:Date.now()}}if(n.debug&&de.debug(`[AuthHandshake] Reputation score: ${i.score}`),null===i.score){if("deny"===r)return{authorized:!1,authError:await sr(e,t,n,"Unknown agent denied by policy"),reputation:i,reason:"Unknown agent — policy: deny"};if("require-consent"===r)return{authorized:!1,authError:await sr(e,t,n,"Unknown agent requires consent"),reputation:i,reason:"Unknown agent — policy: require-consent"};n.debug&&de.debug("[AuthHandshake] Unknown agent allowed by policy, skipping reputation gate")}if(null!==i.score&&i.score<n.authorization.minReputationScore)return n.debug&&de.debug(`[AuthHandshake] Reputation ${i.score} < ${n.authorization.minReputationScore}, requiring authorization`),{authorized:!1,authError:await sr(e,t,n,"Agent reputation score below threshold"),reputation:i,reason:"Low reputation score"}}try{o=await n.delegationVerifier.verify(e,t)}catch(r){de.error("[AuthHandshake] Delegation verification failed:",r);const i=`Delegation verification error: ${r instanceof Error?r.message:"Unknown error"}`;return{authorized:!1,authError:await sr(e,t,n,i),reason:i}}return o.valid&&o.delegation?(n.debug&&de.debug(`[AuthHandshake] Delegation valid, authorized (${Date.now()-r}ms)`),{authorized:!0,delegation:o.delegation,credential:o.credential,reputation:i,reason:"Valid delegation found"}):(n.debug&&de.debug(`[AuthHandshake] No delegation found, returning needs_authorization (${Date.now()-r}ms)`),{authorized:!1,authError:await sr(e,t,n,o.reason??"No valid delegation found"),reputation:i,reason:o.reason??"No delegation"})}async function sr(e,t,n,r){const i=await n.resumeTokenStore.create(e,t,{requestedAt:Date.now()}),o=Date.now()+(n.authorization.resumeTokenTtl??6e5),s=new URL(n.authorization.authorizationUrl);s.searchParams.set("agent_did",e),s.searchParams.set("scopes",t.join(",")),s.searchParams.set("resume_token",i);const a={title:"Authorization Required",hint:["link","qr"],authorizationCode:i.substring(0,8).toUpperCase(),qrUrl:`https://api.qrserver.com/v1/create-qr-code/?data=${encodeURIComponent(s.toString())}`};return k({message:r,authorizationUrl:s.toString(),resumeToken:i,expiresAt:o,scopes:t,display:a})}function ar(e){const t=["write","delete","admin","payment","transfer","execute","modify"];return e.some(e=>t.some(t=>e.toLowerCase().includes(t)))}const cr={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 dr extends Error{code;details;constructor(e,t,n){super(t),this.code=e,this.details=n,this.name="ProofVerificationError"}}function ur(e,t,n){return new dr(e,t,n)}const lr=120,pr=30,fr=600;class hr{cryptoService;clock;nonceCache;fetch;timestampSkewSeconds;nonceTtlSeconds;cryptoProvider;constructor(e){this.cryptoService=new wn(e.cryptoProvider),this.cryptoProvider=e.cryptoProvider,this.clock=e.clockProvider,this.nonceCache=e.nonceCacheProvider,this.fetch=e.fetchProvider,this.timestampSkewSeconds=e.timestampSkewSeconds??lr,this.nonceTtlSeconds=e.nonceTtlSeconds??300}setTimestampSkew(e){"number"==typeof e&&Number.isFinite(e)&&(this.timestampSkewSeconds=Math.max(pr,Math.min(fr,Math.floor(e))))}getTimestampSkew(){return this.timestampSkewSeconds}async verifyProof(e,t,n){try{const r=await this.validateProofStructure(e);if(!r.valid)return r;const i=r.proof,o=this.buildCanonicalPayload(i.meta),s=(new TextEncoder).encode(o);return await this.runVerificationPipeline(i,t,s,n)}catch(e){return this.handleVerificationError(e)}}async verifyProofArtifact(e,t,n){try{const r=await this.validateProofStructure(e);if(!r.valid)return r;const i=r.proof,o=(new TextEncoder).encode(this.buildCanonicalPayload(i.meta)),s=await this.verifySignature(i.jws,t,o,i.meta.kid);return s.valid?void 0!==n?this.validateContentBinding(i,n):{valid:!0}:s}catch(e){return this.handleVerificationError(e)}}async verifyProofDetached(e,t,n){try{const r=t instanceof Uint8Array?t:(new TextEncoder).encode(t);return await this.runVerificationPipeline(e,n,r)}catch(e){return this.handleVerificationError(e)}}async runVerificationPipeline(e,t,n,r){const i=await this.validateProofStructure(e);if(!i.valid)return i;const o=i.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,n,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:n,responseHash:r}=await kn(t.request,t.response,e=>this.cryptoProvider.hash(e),e.meta.prf??A);if(e.meta.requestHash!==n)return{valid:!1,reason:"Request hash mismatch: the proof does not bind the request you supplied",errorCode:cr.CONTENT_BINDING_MISMATCH};const i=void 0!==e.meta.responseHash;return i!==(void 0!==t.response)?{valid:!1,reason:i?"Proof binds a response (responseHash present) but no response was supplied to verify against — pass expected.response":"A response was supplied but the proof binds none — content/proof mismatch",errorCode:cr.CONTENT_BINDING_MISMATCH}:i&&e.meta.responseHash!==r?{valid:!1,reason:"Response hash mismatch: received content differs from what the server signed (possible substitution / MITM)",errorCode:cr.CONTENT_BINDING_MISMATCH}:{valid:!0}}handleVerificationError(e){return{valid:!1,reason:"Proof verification error",errorCode:cr.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=R(e);return t.success?{valid:!0,proof:t.data}:{valid:!1,reason:"Invalid proof structure",errorCode:cr.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:cr.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:cr.TIMESTAMP_SKEW_EXCEEDED,details:{timestamp:e,timestampMs:t,skewSeconds:this.timestampSkewSeconds,currentTime:this.clock.now()}}}async verifySignature(e,t,n,r){return await this.cryptoService.verifyJWS(e,t,{detachedPayload:n,expectedKid:r,alg:"EdDSA"})?{valid:!0}:{valid:!1,reason:"Invalid JWS signature",errorCode:cr.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 n=await this.fetch.resolveDID(e);if(!n)throw new dr(cr.DID_DOCUMENT_NOT_FOUND,`DID document not found: ${e}`,{did:e});const r=n;if(!r.verificationMethod||0===r.verificationMethod.length)throw new dr(cr.VERIFICATION_METHOD_NOT_FOUND,`No verification methods found in DID document: ${e}`,{did:e});let i;if(t){const n=t.startsWith("#")?t:`#${t}`;if(i=r.verificationMethod.find(t=>t.id===n||t.id===`${e}${n}`),!i)throw new dr(cr.VERIFICATION_METHOD_NOT_FOUND,`Verification method not found for kid: ${t}`,{did:e,kid:t,availableKids:r.verificationMethod.map(e=>e.id)})}else i=r.verificationMethod[0];if(!i?.publicKeyJwk)throw new dr(cr.PUBLIC_KEY_NOT_FOUND,"Public key JWK not found in verification method",{did:e,kid:t,verificationMethodId:i?.id});const o=i.publicKeyJwk;if("OKP"!==o.kty||"Ed25519"!==o.crv||!o.x)throw new dr(cr.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&&i.id&&(s.kid=i.id),s}catch(n){if(n instanceof dr)throw n;throw de.error("[ProofVerifier] Failed to fetch public key from DID",{error:n}),new dr(cr.DID_RESOLUTION_FAILED,`DID resolution failed: ${n instanceof Error?n.message:String(n)}`,{did:e,kid:t,originalError:n instanceof Error?n.message:String(n)})}}buildCanonicalPayload(e){return M(Tn(e))}}const gr=["io.modelcontextprotocol/"],yr=["traceparent","tracestate","baggage"];function mr(e){return yr.includes(e)||gr.some(t=>e.startsWith(t))}function vr(e,t="strict"){const n=Object.keys(e).filter(e=>e!==Sn&&e!==An&&e!==Dn);return"allow-extensions"===t&&n.length>0?{valid:!0,extraKeys:n}:{valid:!0}}function Ir(e,t="strict"){const n=e[Sn]??e[An]??e[Dn];if(!n)return{success:!1,reason:"_meta does not contain a proof",errorCode:cr.MISSING_REQUIRED_FIELD};vr(e,t);const r=R(n);return r.success?{success:!0,proof:r.data}:{success:!1,reason:r.error?.message??"Invalid proof structure",errorCode:cr.INVALID_PROOF_STRUCTURE}}class wr{}class _r{}class Er{}class br{}class Sr{}class Ar{}class Dr extends br{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 kr extends Sr{nonces=new Map;async has(e,t){const n=t?`nonce:${t}:${e}`:`nonce:${e}`,r=this.nonces.get(n);return!(!r||Date.now()>r&&(this.nonces.delete(n),1))}async add(e,t,n){const r=n?`nonce:${n}:${e}`:`nonce:${e}`,i=Date.now()+1e3*t;this.nonces.set(r,i)}async cleanup(){const e=Date.now();for(const[t,n]of this.nonces)e>n&&this.nonces.delete(t)}async destroy(){this.nonces.clear()}}class Tr extends Ar{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 Cr{}class Or extends Cr{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 Or({maxSessions:t.maxSessions??1e4}),this.config={timestampSkewSeconds:t.timestampSkewSeconds??120,sessionTtlMinutes:t.sessionTtlMinutes??30,nonceCache:t.nonceCache??new kr,metaPolicy:t.metaPolicy??"strict",...void 0!==t.absoluteSessionLifetime&&{absoluteSessionLifetime:t.absoluteSessionLifetime},...void 0!==t.serverDid&&{serverDid:t.serverDid}},this.config.nonceCache instanceof kr&&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),n=Math.abs(t-e.timestamp);if(n>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: ${n}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 i=e.agentDid?b:S,o=Math.ceil(i/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 n=Math.floor(Date.now()/1e3);return n-t.lastActivity>60*t.ttlMinutes||void 0!==this.config.absoluteSessionLifetime&&n-t.createdAt>60*this.config.absoluteSessionLifetime?(await this.sessionStore.delete(e),null):(t.lastActivity=n,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 n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}async cleanup(){const e=Math.floor(Date.now()/1e3);for(const[t,n]of await this.sessionStore.entries()){let r=e-n.lastActivity>60*n.ttlMinutes;r||void 0===this.config.absoluteSessionLifetime||(r=e-n.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 Pr(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 xr=n(77598);const zr=Buffer.from("302e020100300506032b657004220420","hex"),$r=Buffer.from("302a300506032b6570032100","hex");class Mr extends wr{async sign(e,t){const n=Buffer.from(t,"base64"),r=64===n.length?n.subarray(0,32):n,i=(0,xr.createPrivateKey)({key:Buffer.concat([zr,r]),format:"der",type:"pkcs8"});return new Uint8Array((0,xr.sign)(null,Buffer.from(e),i))}async verify(e,t,n){try{const r=(0,xr.createPublicKey)({key:Buffer.concat([$r,Buffer.from(n,"base64")]),format:"der",type:"spki"});return(0,xr.verify)(null,Buffer.from(e),r,Buffer.from(t))}catch{return!1}}async generateKeyPair(){const{publicKey:e,privateKey:t}=(0,xr.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,xr.createHash)("sha256").update(Buffer.from(e)).digest("hex")}`}async randomBytes(e){return new Uint8Array((0,xr.randomBytes)(e))}}class Lr extends _r{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 Er{didKeyResolver=ge();didWebResolver;didResolvers;allowPrivateNetworkHosts;constructor(e){super(),this.allowPrivateNetworkHosts=e?.allowPrivateNetworkHosts??!1,this.didResolvers=rr(e?.didResolvers,this)}async resolveDID(e){const t=Y(e),n=t?this.didResolvers[t]:void 0;if(n)try{const t=await n.resolve(e);if(t)return t}catch{return null}return e.startsWith("did:key:")?this.didKeyResolver.resolve(e):Vn(e)?this.isBlockedTarget(qn(e))?null:(this.didWebResolver||(this.didWebResolver=Jn(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 n=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 n=t.credentialSubject;if("object"!=typeof n||null===n)return!1;const r=n;return"StatusList2021"===r.type&&"string"==typeof r.encodedList}(n)?n: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 n=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(t);if(!n)return!1;const r=Number(n[1]),i=Number(n[2]);return 127===r||10===r||0===r||169===r&&254===i||192===r&&168===i||172===r&&i>=16&&i<=31}(t)}}class jr extends Er{async resolveDID(e){return null}async fetchStatusList(e){return null}async fetchDelegationChain(e){return[]}async fetch(e,t){throw new Error("fetch unavailable")}}function Hr(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 Vr 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(Hr(e)))}async logEvent(e){this.events.push(e)}}class Fr 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"];function Br(e){const t=Object.values(e).filter(e=>"number"==typeof e);return Object.entries(e).filter(([e,n])=>-1===t.indexOf(+e)).map(([e,t])=>t)}function Jr(e,t="|"){return e.map(e=>di(e)).join(t)}function Wr(e,t){return"bigint"==typeof t?t.toString():t}function Gr(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Zr(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function Yr(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Xr(...e){const t={};for(const n of e){const e=Object.getOwnPropertyDescriptors(n);Object.assign(t,e)}return Object.defineProperties({},t)}function Qr(e){return JSON.stringify(e)}const ei="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function ti(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}const ni=Gr(()=>{if($i.jitless)return!1;if("undefined"!=typeof navigator&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function ri(e){if(!1===ti(e))return!1;const t=e.constructor;if(void 0===t)return!0;if("function"!=typeof t)return!0;const n=t.prototype;return!1!==ti(n)&&!1!==Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")}function ii(e){return ri(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}const oi=new Set(["string","number","symbol"]);function si(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ai(e,t,n){const r=new e._zod.constr(t??e._zod.def);return t&&!n?.parent||(r._zod.parent=e),r}function ci(e){const t=e;if(!t)return{};if("string"==typeof t)return{error:()=>t};if(void 0!==t?.message){if(void 0!==t?.error)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,"string"==typeof t.error?{...t,error:()=>t.error}:t}function di(e){return"bigint"==typeof e?e.toString()+"n":"string"==typeof e?`"${e}"`:`${e}`}const ui=(()=>({safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]}))();function li(e,t,n,r="partial"){const i=t._zod.def.checks;if(i&&i.length>0)throw new Error(`.${r}() cannot be used on object schemas containing refinements`);const o=Xr(t._zod.def,{get shape(){const r=t._zod.def.shape,i={...r};if(n)for(const t of Reflect.ownKeys(n)){if(!Object.prototype.hasOwnProperty.call(r,t))throw new Error(`Unrecognized key: "${String(t)}"`);n[t]&&(i[t]=e?new e({type:"optional",innerType:r[t]}):r[t])}else for(const t of Reflect.ownKeys(r))i[t]=e?new e({type:"optional",innerType:r[t]}):r[t];return Yr(this,"shape",i),i},checks:[]});return ai(t,o)}function pi(e,t=0){if(!0===e.aborted)return!0;for(let n=t;n<e.issues.length;n++)if(!0!==e.issues[n]?.continue)return!0;return!1}function fi(e,t=0){if(!0===e.aborted)return!0;for(let n=t;n<e.issues.length;n++)if(!1===e.issues[n]?.continue)return!0;return!1}function hi(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function gi(e){return"string"==typeof e?e:e?.message}function yi(e,t,n){var r;for(let i=t;i<e.length;i++)(r=e[i]).schema??(r.schema=n)}function mi(e,t,n){var r;const i=e.inst?._zod?.traits;i?.has("$ZodType")&&(i.has("$ZodCheck")?(r=e).schema??(r.schema=e.inst):e.schema=e.inst);const o=e.schema!==e.inst?e.schema?._zod.def?.error:void 0,s=e.message?e.message:gi(e.inst?._zod.def?.error?.(e))??gi(o?.(e))??gi(t?.error?.(e))??gi(n.customError?.(e))??gi(n.localeError?.(e))??"Invalid input",{inst:a,schema:c,continue:d,input:u,...l}=e;return l.path??(l.path=[]),l.message=s,t?.reportInput&&(l.input=u),l}const vi=/[\uD800-\uDBFF]/;function Ii(e){const t=e.length;if(!vi.test(e))return t;let n=t;for(let r=0;r<t-1;r++)55296==(64512&e.charCodeAt(r))&&56320==(64512&e.charCodeAt(r+1))&&(n--,r++);return n}function wi(e){return Array.isArray(e)?"array":"string"==typeof e?"string":"unknown"}function _i(...e){const[t,n,r]=e;return"string"==typeof t?{message:t,code:"custom",input:n,inst:r}:{...t}}function Ei(e,t,n,r=!0){return Object.defineProperty(e,t,{configurable:!0,writable:!0,enumerable:r,value:n}),n}function bi(e,t,n){return Ei(e,t,n,!1)}function Si(e,t,n){Object.defineProperty(e,t,{configurable:!0,get(){return null==this?n:Ei(this,t,n.bind(this))},set(e){Ei(this,t,e)}})}let Ai,Di=!1;const ki={configurable:!0,get(){Di=!0}};function Ti(e,t,n){const r=Object.getPrototypeOf(e._zod);t in r&&Ai!==e._zod?Ai=void 0:(Ai=e._zod,Object.defineProperty(r,t,{configurable:!0,get(){Object.defineProperty(this,t,ki);const e=Di;Di=!1;try{const r=n(this);return Di?delete this[t]:Object.defineProperty(this,t,{configurable:!0,writable:!0,value:r}),Di=Di||e,r}catch(n){throw delete this[t],Di=Di||e,n}},set(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:e})}}))}function Ci(e){const t=()=>e;return t["~constantCatch"]=!0,t}var Oi;const Ni={value:void 0,enumerable:!1};let Ri="captureStackTrace"in Error?Error:null;function Pi(e,t,n,r){function i(e){this.def=e,this.constr=u,this.traits=new Set}i.prototype={};const o=n,s=o&&new WeakSet;function a(n,r){if(!n._zod){Ni.value=new i(r);try{Object.defineProperty(n,"_zod",Ni)}finally{Ni.value=void 0}}if(n._zod.traits.has(e))return;if(n._zod.traits.add(e),t(n,r),s){const e=Object.getPrototypeOf(n),t=n._zod.constr.prototype;let r=e;for(;r&&r!==t;)r=Object.getPrototypeOf(r);const i=r??e;s.has(i)||(s.add(i),function(e,t){for(const n in t){const r=Object.getOwnPropertyDescriptor(t,n);r.get?Object.defineProperty(e,n,{...r,enumerable:!1}):Si(e,n,r.value)}}(i,o))}const a=u.prototype;for(const e in a)Object.prototype.hasOwnProperty.call(a,e)&&(e in n||(n[e]=a[e].bind(n)))}const c=r?.Parent??Object;class d extends c{}function u(e){const t=r?.Parent?function(e){const t=Ri;if(t){const n=t.stackTraceLimit;if("number"==typeof n){try{t.stackTraceLimit=0}catch{return Ri=null,new e}try{return new e}finally{t.stackTraceLimit=n}}}return new e}(d):this;a(t,e);const n=t._zod.deferred;if(n){for(const e of n)e();t._zod.deferred=void 0}const i=globalThis.__zod_globalConfig?.postProcessor;return i&&i(t),t}return Object.defineProperty(d,"name",{value:e}),Object.defineProperty(u,"init",{value:a}),Object.defineProperty(u,Symbol.hasInstance,{value:t=>!!(r?.Parent&&t instanceof r.Parent)||t?._zod?.traits?.has(e)}),Object.defineProperty(u,"name",{value:e}),u}class xi extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class zi extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}}(Oi=globalThis).__zod_globalConfig??(Oi.__zod_globalConfig={});const $i=globalThis.__zod_globalConfig;function Mi(e){return e&&Object.assign($i,e),$i}class Li extends Error{constructor(){super("Cannot parse a reference cycle that closes through a transform"),this.name="ZodCyclicError"}}const Ui="~memo",ji=[];function Hi(e){return e.map(e=>e.path?{...e,path:e.path.slice()}:{...e})}const Ki=new WeakMap;function Vi(e,t){const n=Ki.get(e);if(void 0!==n)return n;if(t.has(e))return!0;t.add(e);let r=!1;const i=e=>{!r&&e?._zod&&Vi(e,t)&&(r=!0)},o=e._zod.def;switch(o.type){case"object":for(const e of Reflect.ownKeys(o.shape))i(o.shape[e]);i(o.catchall);break;case"array":i(o.element);break;case"tuple":for(const e of o.items)i(e);i(o.rest);break;case"record":case"map":i(o.keyType),i(o.valueType);break;case"set":i(o.valueType);break;case"union":for(const e of o.options)i(e);break;case"intersection":i(o.left),i(o.right);break;case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":i(o.innerType);break;case"pipe":i(o.in),i(o.out);break;case"function":i(o.input),i(o.output);break;case"lazy":i(e._zod.innerType);break;case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":break;default:for(const e in o){const t=Object.getOwnPropertyDescriptor(o,e);if(!t||t.get)continue;const n=t.value;if(n&&"object"==typeof n)if(n._zod)i(n);else if(Array.isArray(n))for(const e of n)i(e)}}return t.delete(e),Ki.set(e,r),r}let Fi;const qi=[],Bi={alloc(e,t,n){const r=Fi;if(!r)return n;Fi=void 0;const i={value:n,issues:null};return r.set(t.value,i),qi.push(i),n},guard(e){var t;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{const t=e._zod.parse,n=(e,n)=>{if("backward"!==n.direction&&function(e,t){const n=e[Ui]?.backEdges;return void 0!==n&&null!==t&&"object"==typeof t&&n.has(t)}(n,e.value))throw new Li;return t(e,n)};e._zod.parse=n,e._zod.run===t&&(e._zod.run=n)})},attach(e){var t;let n,r,i;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{const t=e._zod.parse,o=(s,a)=>{if(void 0===n&&(n=Vi(e,new Set),!n))return e._zod.parse=t,e._zod.run===o&&(e._zod.run=t),t(s,a);const c=s.value;if(null===c||"object"!=typeof c)return t(s,a);let d,u=a[Ui];u||(u={buckets:new Map,backEdges:void 0},a[Ui]=u),r===a?d=i:(d=function(e,t){let n=e.buckets.get(t);return n||(n=new Map,e.buckets.set(t,n)),n}(u,e),r=a,i=d);const l=d.get(c);if(l)return s.value=l.value,l.issues?l.issues.length&&s.issues.push(...Hi(l.issues)):(s.memo=!0,u.backEdges??(u.backEdges=new Set),u.backEdges.add(l.value)),s;Fi=d;const p=qi.length,f=t(s,a);Fi=void 0;const h=qi.length>p?qi.pop():void 0;return f instanceof Promise?f.then(e=>(h&&(h.issues=e.issues.length?Hi(e.issues):ji),e)):(h&&(h.issues=f.issues.length?Hi(f.issues):ji),f)};e._zod.parse=o,e._zod.run===t&&(e._zod.run=o)})}},Ji=/^[cC][0-9a-z]{6,}$/,Wi=/^[0-9a-z]+$/,Gi=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,Zi=/^[0-9a-vA-V]{20}$/,Yi=/^[A-Za-z0-9]{27}$/,Xi=/^[a-zA-Z0-9_-]{21}$/,Qi=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,eo=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,to=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,no=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,ro=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,io=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,oo=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,so=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,ao=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,co=/^[A-Za-z0-9_-]*$/,uo=/^https?$/,lo=/^\+[1-9]\d{6,14}$/,po="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))";function fo(e){return new RegExp(`^${e}$`)}const ho=fo(po);function go(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return"number"==typeof e.precision?-1===e.precision?`${t}`:0===e.precision?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:e.seconds?`${t}:[0-5]\\d(?:\\.\\d+)?`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}const yo=/^-?\d+$/,mo=/^-?\d+(?:\.\d+)?$/,vo=/^(?:true|false)$/i,Io=/^[^A-Z]*$/,wo=/^[^a-z]*$/,_o=Pi("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Eo=e=>{const t=e.value;return!(null==t||void 0===t.length)},bo={number:"number",bigint:"bigint",object:"date"},So=Pi("$ZodCheckLessThan",(e,t)=>{_o.init(e,t);const n=bo[typeof t.value];e._zod.onattach.push(e=>{const n=e._zod.bag,r=(t.inclusive?n.maximum:n.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<r&&(t.inclusive?n.maximum=t.value:n.exclusiveMaximum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:bo[typeof r.value]??n,code:"too_big",maximum:"object"==typeof t.value?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Ao=Pi("$ZodCheckGreaterThan",(e,t)=>{_o.init(e,t);const n=bo[typeof t.value];e._zod.onattach.push(e=>{const n=e._zod.bag,r=(t.inclusive?n.minimum:n.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>r&&(t.inclusive?n.minimum=t.value:n.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:bo[typeof r.value]??n,code:"too_small",minimum:"object"==typeof t.value?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Do=Pi("$ZodCheckMultipleOf",(e,t)=>{_o.init(e,t),e._zod.onattach.push(e=>{var n;(n=e._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");("bigint"==typeof n.value?t.value!==BigInt(0)&&n.value%t.value===BigInt(0):0===function(e,t){const n=e/t,r=Math.round(n),i=4*Number.EPSILON*Math.max(Math.abs(n),1);return Math.abs(n-r)<i?0:n-r}(n.value,t.value))||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),ko=Pi("$ZodCheckNumberFormat",(e,t)=>{_o.init(e,t),t.format=t.format||"float64";const n=t.format?.includes("int"),r=n?"int":"number",[i,o]=ui[t.format];e._zod.onattach.push(e=>{const r=e._zod.bag;r.format=t.format,r.minimum=i,r.maximum=o,n&&(r.pattern=yo)}),e._zod.check=s=>{const a=s.value;if(n){if(!Number.isInteger(a))return void s.issues.push({expected:r,format:t.format,code:"invalid_type",continue:!1,input:a,inst:e});if(!Number.isSafeInteger(a))return void(a>0?s.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort}):s.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort}))}a<i&&s.issues.push({origin:"number",input:a,code:"too_small",minimum:i,inclusive:!0,inst:e,continue:!t.abort}),a>o&&s.issues.push({origin:"number",input:a,code:"too_big",maximum:o,inclusive:!0,inst:e,continue:!t.abort})}}),To=Pi("$ZodCheckMaxLength",(e,t)=>{var n;_o.init(e,t),(n=e._zod.def).when??(n.when=Eo),e._zod.onattach.push(e=>{const n=e._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<n&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{const r=n.value,i=r.length;if(("string"==typeof r&&i>t.maximum?Ii(r):i)<=t.maximum)return;const o=wi(r);n.issues.push({origin:o,code:"too_big",maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Co=Pi("$ZodCheckMinLength",(e,t)=>{var n;_o.init(e,t),(n=e._zod.def).when??(n.when=Eo),e._zod.onattach.push(e=>{const n=e._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>n&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{const r=n.value,i=r.length;if(("string"==typeof r&&i>=t.minimum&&i<2*t.minimum?Ii(r):i)>=t.minimum)return;const o=wi(r);n.issues.push({origin:o,code:"too_small",minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Oo=Pi("$ZodCheckLengthEquals",(e,t)=>{var n;_o.init(e,t),(n=e._zod.def).when??(n.when=Eo),e._zod.onattach.push(e=>{const n=e._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=n=>{const r=n.value,i=r.length,o="string"==typeof r&&i>=t.length&&i<=2*t.length?Ii(r):i;if(o===t.length)return;const s=wi(r),a=o>t.length;n.issues.push({origin:s,...a?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),No=Pi("$ZodCheckStringFormat",(e,t)=>{var n,r;_o.init(e,t),e._zod.onattach.push(e=>{const n=e._zod.bag;n.format=t.format,t.pattern&&(n.patterns??(n.patterns=new Set),n.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,t.pattern.test(n.value)||n.issues.push({origin:"string",code:"invalid_format",format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),Ro=Pi("$ZodCheckRegex",(e,t)=>{No.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,t.pattern.test(n.value)||n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Po=Pi("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Io),No.init(e,t)}),xo=Pi("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=wo),No.init(e,t)}),zo=Pi("$ZodCheckIncludes",(e,t)=>{_o.init(e,t);const n=si(t.includes),r=new RegExp("number"==typeof t.position?`^.{${t.position},}${n}`:n);t.pattern=r,e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(r)}),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),$o=Pi("$ZodCheckStartsWith",(e,t)=>{_o.init(e,t);const n=new RegExp(`^${si(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(n)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),Mo=Pi("$ZodCheckEndsWith",(e,t)=>{_o.init(e,t);const n=new RegExp(`.*${si(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(n)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),Lo=Pi("$ZodCheckOverwrite",(e,t)=>{_o.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});class Uo{constructor(e=[],t={}){this.content=[],this.indent=0,this.args=e,this.closed=t}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if("function"==typeof e)return e(this,{execution:"sync"}),void e(this,{execution:"async"});const t=e.split("\n").filter(e=>e),n=Math.min(...t.map(e=>e.length-e.trimStart().length)),r=t.map(e=>e.slice(n)).map(e=>" ".repeat(2*this.indent)+e);for(const e of r)this.content.push(e)}compile(){const e=Function,t=this?.content??[""];return new e(...Object.keys(this.closed),`return function (${this.args.join(", ")}) {\n${t.join("\n")}\n};`)(...Object.values(this.closed))}}const jo={get:function(){const e=this._zod;return e.message??(e.message=JSON.stringify(e.def,Wr,2)),e.message},set:function(e){this._zod.message=e},enumerable:!0,configurable:!0},Ho={value:void 0,enumerable:!1},Ko={value:void 0,enumerable:!1},Vo=new WeakSet([Object.prototype,Error.prototype]),Fo=(e,t)=>{e.name="$ZodError",Ho.value=e._zod,Object.defineProperty(e,"_zod",Ho),Ko.value=t,Object.defineProperty(e,"issues",Ko),Ho.value=void 0,Ko.value=void 0,Object.defineProperty(e,"message",jo);const n=Object.getPrototypeOf(e);Vo.has(n)||(Vo.add(n),Object.defineProperty(n,"toString",{configurable:!0,enumerable:!1,get(){const e=()=>this.message;return Object.defineProperty(this,"toString",{value:e,configurable:!0,writable:!0}),e},set(e){Object.defineProperty(this,"toString",{value:e,configurable:!0,writable:!0})}}))},qo=Pi("$ZodError",Fo),Bo=Pi("$ZodError",Fo,void 0,{Parent:Error});function Jo(e,t,n){return Object.prototype.hasOwnProperty.call(e,t)||("__proto__"===t?Object.defineProperty(e,t,{value:n(),writable:!0,enumerable:!0,configurable:!0}):e[t]=n()),e[t]}function Wo(e,t){return{callee:t?.callee??e,Err:t?.Err}}const Go=e=>{const t=(n,r,i,o)=>{const s=i?{...i,async:!1}:{async:!1},a=n._zod.run({value:r,issues:[]},s);if(a instanceof Promise)throw new xi;if(a.issues.length){const n=new(o?.Err??e)(a.issues.map(e=>mi(e,s,Mi())));throw ei(n,o?.callee??t),n}return a.value};return t},Zo=e=>{const t=async(n,r,i,o)=>{const s=i?{...i,async:!0}:{async:!0};let a=n._zod.run({value:r,issues:[]},s);if(a instanceof Promise&&(a=await a),a.issues.length){const n=new(o?.Err??e)(a.issues.map(e=>mi(e,s,Mi())));throw ei(n,o?.callee??t),n}return a.value};return t},Yo=e=>(t,n,r)=>{const i=r?{...r,async:!1}:{async:!1},o=t._zod.run({value:n,issues:[]},i);if(o instanceof Promise)throw new xi;return o.issues.length?{success:!1,error:new(e??qo)(o.issues.map(e=>mi(e,i,Mi())))}:{success:!0,data:o.value}},Xo=Yo(Bo),Qo=e=>async(t,n,r)=>{const i=r?{...r,async:!0}:{async:!0};let o=t._zod.run({value:n,issues:[]},i);return o instanceof Promise&&(o=await o),o.issues.length?{success:!1,error:new e(o.issues.map(e=>mi(e,i,Mi())))}:{success:!0,data:o.value}},es=Qo(Bo),ts=e=>{const t=Go(e),n=(e,r,i,o)=>{const s=i?{...i,direction:"backward"}:{direction:"backward"};return t(e,r,s,Wo(n,o))};return n},ns=e=>{const t=Go(e),n=(e,r,i,o)=>t(e,r,i,Wo(n,o));return n},rs=e=>{const t=Zo(e),n=async(e,r,i,o)=>{const s=i?{...i,direction:"backward"}:{direction:"backward"};return await t(e,r,s,Wo(n,o))};return n},is=e=>{const t=Zo(e),n=async(e,r,i,o)=>await t(e,r,i,Wo(n,o));return n},os=e=>(t,n,r)=>{const i=r?{...r,direction:"backward"}:{direction:"backward"};return Yo(e)(t,n,i)},ss=e=>(t,n,r)=>Yo(e)(t,n,r),as=e=>async(t,n,r)=>{const i=r?{...r,direction:"backward"}:{direction:"backward"};return Qo(e)(t,n,i)},cs=e=>async(t,n,r)=>Qo(e)(t,n,r),ds={major:4,minor:5,patch:4},us=Pi("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=ds;const r=e._zod.def.checks,i=e._zod.traits.has("$ZodCheck")?[e,...r??[]]:r?.length?[...r]:[];for(const t of i)for(const n of t._zod.onattach)n(e);if(0===i.length)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const t=(t,n,r)=>{if(t.memo)return t;let i,o=pi(t);for(const s of n){if(s._zod.def.when){if(fi(t))continue;if(!s._zod.def.when(t))continue}else if(o)continue;const n=t.issues.length,a=s._zod.check(t);if(a instanceof Promise&&!1===r?.async)throw new xi;if(i||a instanceof Promise)i=(i??Promise.resolve()).then(async()=>{await a,t.issues.length!==n&&(yi(t.issues,n,e),o||(o=pi(t,n)))});else{if(t.issues.length===n)continue;yi(t.issues,n,e),o||(o=pi(t,n))}}return i?i.then(()=>t):t},n=(n,r,o)=>{if(pi(n))return n.aborted=!0,n;const s=t(r,i,o);if(s instanceof Promise){if(!1===o.async)throw new xi;return s.then(t=>e._zod.parse(t,o))}return e._zod.parse(s,o)};e._zod.run=(r,o)=>{if(o.skipChecks)return e._zod.parse(r,o);if("backward"===o.direction){const t=e._zod.parse({value:r.value,issues:[]},{...o,skipChecks:!0});return t instanceof Promise?t.then(e=>n(e,r,o)):n(t,r,o)}const s=e._zod.parse(r,o);if(s instanceof Promise){if(!1===o.async)throw new xi;return s.then(e=>t(e,i,o))}return t(s,i,o)}}},{get"~standard"(){return bi(this,"~standard",ps(this))},set"~standard"(e){Ei(this,"~standard",e)}}),ls=e=>e.success?{value:e.data}:{issues:e.error?.issues};function ps(e){return{validate:t=>{try{return ls(Xo(e,t))}catch(n){return es(e,t).then(ls)}},vendor:"zod",version:1}}const fs=Pi("$ZodString",(e,t)=>{var n;us.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??(n=e._zod.bag,new RegExp(`^${n?`[\\s\\S]{${n?.minimum??0},${n?.maximum??""}}`:"[\\s\\S]*"}$`)),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch(r){}return"string"==typeof n.value||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),hs=Pi("$ZodStringFormat",(e,t)=>{No.init(e,t),fs.init(e,t)}),gs=Pi("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=eo),hs.init(e,t)}),ys=Pi("$ZodUUID",(e,t)=>{if(t.version){const e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(void 0===e)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=to(e))}else t.pattern??(t.pattern=to());hs.init(e,t)}),ms=Pi("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=no),hs.init(e,t)}),vs=/[\t\n\r]/g,Is=Pi("$ZodURL",(e,t)=>{hs.init(e,t),e._zod.check=n=>{try{const i=n.value.trim(),o=function(e,t){if(!t.normalize&&t.protocol?.source===uo.source&&!/^https?:\/\//i.test(e))return 1;try{return new URL(e)}catch{return 2}}(i,t);return 1===o?void n.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:n.value,inst:e,continue:!t.abort}):2===o?void n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort}):(t.hostname&&!function(e,t){return t.lastIndex=0,t.test(e.hostname)}(o,t.hostname)&&n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort}),t.protocol&&!function(e,t){return t.lastIndex=0,t.test(e.protocol.endsWith(":")?e.protocol.slice(0,-1):e.protocol)}(o,t.protocol)&&n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort}),void(n.value=t.normalize?o.href:(r=i,r.replace(vs,""))))}catch(r){n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}var r}}),ws=Pi("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=new RegExp("^[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$","u")),hs.init(e,t)}),_s=Pi("$ZodNanoID",(e,t)=>{if(void 0!==t.length&&(!Number.isInteger(t.length)||t.length<1))throw new Error(`Invalid nanoid length: ${t.length}`);var n;t.pattern??(t.pattern=void 0===t.length?Xi:(n=t.length,new RegExp(`^[a-zA-Z0-9_-]{${n}}$`))),hs.init(e,t)}),Es=Pi("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Ji),hs.init(e,t)}),bs=Pi("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Wi),hs.init(e,t)}),Ss=Pi("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Gi),hs.init(e,t)}),As=Pi("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Zi),hs.init(e,t)}),Ds=Pi("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Yi),hs.init(e,t)}),ks=Pi("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=function(e){const t=["Z"];e.offset&&t.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const n=`${go({precision:e.precision,seconds:!0})}(?:${t.join("|")})`,r=e.local?`${n}|${go({precision:e.precision})}`:n;return new RegExp(`^${po}T(?:${r})$`)}(t)),hs.init(e,t),(t.local||-1===t.precision)&&(e._zod.bag.laxFormat=!0,e._zod.onattach.push(e=>{e._zod.bag.laxFormat=!0}))}),Ts=Pi("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=ho),hs.init(e,t)}),Cs=Pi("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=new RegExp(`^${go(t)}$`)),hs.init(e,t)}),Os=Pi("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Qi),hs.init(e,t)}),Ns=Pi("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=ro),hs.init(e,t),e._zod.bag.format="ipv4"}),Rs=/^[0-9a-fA-F:.]+$/;function Ps(e){if(!Rs.test(e))return!1;try{return new URL(`http://[${e}]`),!0}catch{return!1}}const xs=Pi("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=io),hs.init(e,t),e._zod.bag.format="ipv6",e._zod.check=n=>{Ps(n.value)||n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}),zs=Pi("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=oo),hs.init(e,t)}),$s=Pi("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=so),hs.init(e,t),e._zod.check=n=>{(function(e){const t=e.split("/");if(2!==t.length)return!1;const[n,r]=t;if(!r)return!1;const i=Number(r);return`${i}`===r&&!(i<0||i>128)&&Ps(n)})(n.value)||n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}});function Ms(e){if(""===e)return!0;if(/\s/.test(e))return!1;if(e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}const Ls=Pi("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=ao),hs.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=n=>{Ms(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}}),Us=Pi("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=co),hs.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=n=>{(function(e){if(!co.test(e))return!1;const t=e.replace(/[-_]/g,e=>"-"===e?"+":"/");return Ms(t.padEnd(4*Math.ceil(t.length/4),"="))})(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),js=Pi("$ZodE164",(e,t)=>{t.pattern??(t.pattern=lo),hs.init(e,t)}),Hs=Pi("$ZodJWT",(e,t)=>{hs.init(e,t),e._zod.check=n=>{(function(e,t=null){try{const n=e.split(".");if(3!==n.length)return!1;const[r]=n;if(!r)return!1;const i=JSON.parse(atob(r));return!("typ"in i&&"JWT"!==i?.typ||!i.alg||t&&(!("alg"in i)||i.alg!==t))}catch{return!1}})(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),Ks=Pi("$ZodNumber",(e,t)=>{us.init(e,t),e._zod.pattern=e._zod.bag.pattern??mo,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch(e){}const i=n.value;if("number"==typeof i&&!Number.isNaN(i)&&Number.isFinite(i))return n;const o="number"==typeof i?Number.isNaN(i)?"NaN":Number.isFinite(i)?void 0:String(i):void 0;return n.issues.push({expected:"number",code:"invalid_type",input:i,inst:e,...o?{received:o}:{}}),n}}),Vs=Pi("$ZodNumberFormat",(e,t)=>{ko.init(e,t),Ks.init(e,t)}),Fs=Pi("$ZodBoolean",(e,t)=>{us.init(e,t),e._zod.pattern=vo,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Boolean(n.value)}catch(e){}const i=n.value;return"boolean"==typeof i||n.issues.push({expected:"boolean",code:"invalid_type",input:i,inst:e}),n}}),qs=Pi("$ZodUnknown",(e,t)=>{us.init(e,t),e._zod.parse=e=>e}),Bs=Pi("$ZodNever",(e,t)=>{us.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:e}),t)});function Js(e,t,n){e.issues.length&&t.issues.push(...hi(n,e.issues)),t.value[n]=e.value}const Ws=Pi("$ZodArray",(e,t)=>{us.init(e,t);const n=$i.memoizer;n?.attach(e),e._zod.parse=(r,i)=>{const o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),r;r.value=n?n.alloc(e,r,Array(o.length),i):Array(o.length);const s=[];for(let e=0;e<o.length;e++){const n=o[e],a=t.element._zod.run({value:n,issues:[]},i);a instanceof Promise?s.push(a.then(t=>Js(t,r,e))):Js(a,r,e)}return s.length?Promise.all(s).then(()=>r):r}});function Gs(e,t,n,r,i,o){const s=n in r,a="optional"===o;if(s||!a||"optional"!==i){if(e.issues.length){if(void 0!==i&&a&&!s)return;t.issues.push(...hi(n,e.issues))}s||void 0!==i?void 0===e.value?s&&(t.value[n]=void 0):t.value[n]=e.value:e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]})}}const Zs=[];function Ys(e){const t=Object.keys(e.shape),n=Object.getOwnPropertySymbols(e.shape),r=n.length?n:Zs,i=r.length?[...t,...r]:t;for(const t of i)if(!e.shape?.[t]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${String(t)}": expected a Zod schema`);const o=(s=e.shape,Object.keys(s).filter(e=>void 0!==s[e]._zod.optin&&"optional"===s[e]._zod.optout));var s;return{...e,allKeys:i,symbolKeys:r,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(o)}}function Xs(e,t,n,r,i,o){const s=[],a=i.keySet,c=i.catchall._zod,d=c.def.type,u=c.optin,l=c.optout;for(const i in t){if(a.has(i))continue;if("__proto__"===i){"never"===d&&s.push(i);continue}if("never"===d){s.push(i);continue}const o=c.run({value:t[i],issues:[]},r);o instanceof Promise?e.push(o.then(e=>Gs(e,n,i,t,u,l))):Gs(o,n,i,t,u,l)}return s.length&&n.issues.push({code:"unrecognized_keys",keys:s,input:t,inst:o,continue:!0}),e.length?Promise.all(e).then(()=>n):n}const Qs=new WeakMap,ea=Pi("$ZodObject",(e,t)=>{us.init(e,t);const n=Object.getOwnPropertyDescriptor(t,"shape");if(!n?.get){const e=t.shape;Qs.set(t,e),Object.defineProperty(t,"shape",{get:()=>{const n={...e};return Object.defineProperty(t,"shape",{value:n}),Qs.set(t,n),n}})}const r=Gr(()=>Ys(t));Ti(e,"propValues",e=>{const t=e.def.shape,n={};for(const e in t){const r=t[e]._zod;if(r.values){Object.prototype.hasOwnProperty.call(n,e)||Yr(n,e,new Set);for(const t of r.values)n[e].add(t);void 0!==r.optin&&n[e].add(void 0)}}return n});const i=ti,o=t.catchall;let s;const a=$i.memoizer;a?.attach(e),e._zod.parse=(t,n)=>{s??(s=r.value);const c=t.value;if(!i(c))return t.issues.push({expected:"object",code:"invalid_type",input:c,inst:e}),t;t.value=a?a.alloc(e,t,{},n):{};const d=[],u=s.shape;for(const e of s.allKeys){if("__proto__"===e)continue;const r=u[e],i=r._zod.optin,o=r._zod.optout,s=r._zod.run({value:c[e],issues:[]},n);s instanceof Promise?d.push(s.then(n=>Gs(n,t,e,c,i,o))):Gs(s,t,e,c,i,o)}return o?Xs(d,c,t,n,r.value,e):d.length?Promise.all(d).then(()=>t):t}}),ta=Pi("$ZodObjectJIT",(e,t)=>{ea.init(e,t);const n=e._zod.parse,r=Gr(()=>Ys(t)),i=$i.memoizer;let o;const s=ti,a=!$i.jitless,c=a&&ni.value,d=t.catchall;let u;e._zod.parse=(l,p)=>{u??(u=r.value);const f=l.value;return s(f)?a&&c&&!1===p?.async&&!0!==p.jitless?(o||(o=(t=>{const n=r.value,o=n.symbolKeys,s=new Uo(["payload","ctx"],{shape:t,inst:e,memo:i,syms:o}),a=e=>`shape[${e}]._zod.run({ value: input[${e}], issues: [] }, ctx)`,c=(e,t)=>`\n for (let i = 0; i < ${e}.issues.length; i++) {\n const iss = ${e}.issues[i];\n iss.path = iss.path ? [${t}, ...iss.path] : [${t}];\n payload.issues.push(iss);\n }`;s.write("const input = payload.value;");const d=Object.create(null);let u=0;for(const e of n.allKeys)d[e]="key_"+u++;s.write(i?"const newResult = memo.alloc(inst, payload, {}, ctx);":"const newResult = {};");for(const e of n.allKeys){if("__proto__"===e)continue;const n=d[e],r="symbol"==typeof e?`syms[${o.indexOf(e)}]`:Qr(e),i=`${r} in input`,u=t[e],l=u?._zod?.optin,p=void 0!==l,f="optional"===u?._zod?.optout;if(s.write(`const ${n} = ${a(r)};`),p&&f){const e="optional"===l?`${n}_present`:`${n}.value !== undefined || ${n}_present`;s.write(`\n const ${n}_present = ${i};\n if (!${n}.issues.length || ${n}_present) {\n if (${n}.issues.length) {${c(n,r)}\n }\n\n if (${e}) {\n newResult[${r}] = ${n}.value;\n }\n }\n\n `)}else p?s.write(`\n if (${n}.issues.length) {${c(n,r)}\n }\n \n if (${n}.value === undefined) {\n if (${i}) {\n newResult[${r}] = undefined;\n }\n } else {\n newResult[${r}] = ${n}.value;\n }\n\n `):s.write(`\n const ${n}_present = ${i};\n if (${n}.issues.length) {${c(n,r)}\n }\n if (!${n}_present && !${n}.issues.length) {\n payload.issues.push({\n code: "invalid_type",\n expected: "nonoptional",\n input: undefined,\n path: [${r}]\n });\n }\n\n if (${n}_present) {\n newResult[${r}] = ${n}.value;\n }\n\n `)}return s.write("payload.value = newResult;"),s.write("return payload;"),s.compile()})(t.shape)),l=o(l,p),d?Xs([],f,l,p,u,e):l):n(l,p):(l.issues.push({expected:"object",code:"invalid_type",input:f,inst:e}),l)}});function na(e,t,n,r){for(const n of e)if(0===n.issues.length)return t.value=n.value,t;const i=e.filter(e=>!pi(e));return 1===i.length?(t.value=i[0].value,i[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>mi(e,r,Mi())))}),t)}const ra=Pi("$ZodUnion",(e,t)=>{us.init(e,t),Ti(e,"optin",e=>e.def.options.some(e=>"defaulted"===e._zod.optin)?"defaulted":e.def.options.some(e=>void 0!==e._zod.optin)?"optional":void 0),Ti(e,"optout",e=>e.def.options.some(e=>"optional"===e._zod.optout)?"optional":void 0),Ti(e,"values",e=>{if(e.def.options.every(e=>e._zod.values))return new Set(e.def.options.flatMap(e=>Array.from(e._zod.values)))}),Ti(e,"pattern",e=>{if(e.def.options.every(e=>e._zod.pattern)){const t=e.def.options.map(e=>e._zod.pattern);return new RegExp(`^(${t.map(e=>Zr(e.source)).join("|")})$`)}});const n=1===t.options.length?t.options[0]._zod.run:null;e._zod.parse=(r,i)=>{if(n)return n(r,i);let o=!1;const s=[];for(const e of t.options){const t=e._zod.run({value:r.value,issues:[]},i);if(t instanceof Promise)s.push(t),o=!0;else{if(0===t.issues.length)return t;s.push(t)}}return o?Promise.all(s).then(t=>na(t,r,e,i)):na(s,r,e,i)}}),ia=Pi("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,ra.init(e,t);const n=e._zod.parse;Ti(e,"propValues",e=>{const t={};for(const n of e.def.options){const r=n._zod.propValues;if(!r||0===Object.keys(r).length)throw new Error(`Invalid discriminated union option at index "${e.def.options.indexOf(n)}"`);for(const[e,n]of Object.entries(r)){Object.prototype.hasOwnProperty.call(t,e)||Yr(t,e,new Set);for(const r of n)t[e].add(r)}}return t}),t.options.forEach((e,n)=>{const r=Qs.get(e._zod.def);if(r&&!Object.prototype.hasOwnProperty.call(r,t.discriminator))throw new Error(`Invalid discriminated union option at index "${n}"`)});const r=Gr(()=>{const e=t.options,n=new Map;for(const r of e){const e=r._zod.propValues?.[t.discriminator];if(!e||0===e.size)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(r)}"`);for(const t of e){if(n.has(t))throw new Error(`Duplicate discriminator value "${String(t)}"`);n.set(t,r)}}return n});e._zod.parse=(i,o)=>{const s=i.value;if(!ti(s))return i.issues.push({code:"invalid_type",expected:"object",input:s,inst:e}),i;const a=r.value.get(s?.[t.discriminator]);return a?a._zod.run(i,o):t.unionFallback||"backward"===o.direction?n(i,o):(i.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,options:Array.from(r.value.keys()),input:s,path:[t.discriminator],inst:e}),i)}}),oa=Pi("$ZodIntersection",(e,t)=>{us.init(e,t),e._zod.parse=(e,n)=>{const r=e.value,i=t.left._zod.run({value:r,issues:[]},n),o=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||o instanceof Promise?Promise.all([i,o]).then(([t,n])=>aa(e,t,n)):aa(e,i,o)}});function sa(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e===+t)return{valid:!0,data:e};if(ri(e)&&ri(t)){const n=Object.keys(t),r=Object.keys(e).filter(e=>-1!==n.indexOf(e)),i={...e,...t};Object.prototype.hasOwnProperty.call(i,"__proto__")&&delete i.__proto__;for(const n of r){if("__proto__"===n)continue;const r=sa(e[n],t[n]);if(!r.valid)return{valid:!1,mergeErrorPath:[n,...r.mergeErrorPath]};i[n]=r.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let r=0;r<e.length;r++){const i=sa(e[r],t[r]);if(!i.valid)return{valid:!1,mergeErrorPath:[r,...i.mergeErrorPath]};n.push(i.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function aa(e,t,n){const r=new Map;let i;const o=new Map,s=(e,t)=>{let n;if("unrecognized_keys"!==e.code||e.path?.length){if("invalid_key"!==e.code||"record"!==e.origin||1!==e.path?.length)return!1;{const t=String(e.path[0]);o.has(t)||o.set(t,e),n=[t]}}else i??(i=e),n=e.keys;for(const e of n)r.has(e)||r.set(e,{}),r.get(e)[t]=!0;return!0};for(const n of t.issues)s(n,"l")||e.issues.push(n);for(const t of n.issues)s(t,"r")||e.issues.push(t);const a=[...r].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(a.length){const t=i?a.filter(e=>i.keys.includes(e)):[];t.length&&e.issues.push({...i,keys:t});for(const n of a)!t.includes(n)&&o.has(n)&&e.issues.push(o.get(n))}const c=sa(t.value,n.value);if(!c.valid){if(pi(e))return e;throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(c.mergeErrorPath)}`)}return e.value=c.data,e}const ca=Pi("$ZodRecord",(e,t)=>{us.init(e,t);const n=$i.memoizer;n?.attach(e),e._zod.parse=(r,i)=>{const o=r.value;if(!ri(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),r;const s=[],a=t.keyType._zod.values;if(a&&!t.partial){r.value=n?n.alloc(e,r,{},i):{};const c=new Set;for(const n of a)if("string"==typeof n||"number"==typeof n||"symbol"==typeof n){if(c.add("number"==typeof n?n.toString():n),"__proto__"===n)continue;const a=t.keyType._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){r.issues.push({code:"invalid_key",origin:"record",issues:a.issues.map(e=>mi(e,i,Mi())),input:n,path:[n],inst:e});continue}const d=a.value;if("__proto__"===d)continue;const u=t.valueType._zod.run({value:o[n],issues:[]},i);u instanceof Promise?s.push(u.then(e=>{e.issues.length&&r.issues.push(...hi(n,e.issues)),r.value[d]=e.value})):(u.issues.length&&r.issues.push(...hi(n,u.issues)),r.value[d]=u.value)}let d;for(const e in o)if(!c.has(e))if("loose"===t.mode){if("__proto__"===e)continue;r.value[e]=o[e]}else d=d??[],d.push(e);d&&d.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:d,continue:!0})}else{let c;r.value=n?n.alloc(e,r,{},i):{};for(const n of Reflect.ownKeys(o)){if("__proto__"===n)continue;if(!Object.prototype.propertyIsEnumerable.call(o,n))continue;let d=t.keyType._zod.run({value:n,issues:[]},i);if(d instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if("string"==typeof n&&mo.test(n)&&d.issues.length){const e=t.keyType._zod.run({value:Number(n),issues:[]},i);if(e instanceof Promise)throw new Error("Async schemas not supported in object keys currently");0===e.issues.length&&(d=e)}if(d.issues.length){"loose"===t.mode?r.value[n]=o[n]:a?(c=c??[],c.push(n)):r.issues.push({code:"invalid_key",origin:"record",issues:d.issues.map(e=>mi(e,i,Mi())),input:n,path:[n],inst:e});continue}const u=d.value;if("__proto__"===u)continue;const l=t.valueType._zod.run({value:o[n],issues:[]},i);l instanceof Promise?s.push(l.then(e=>{e.issues.length&&r.issues.push(...hi(n,e.issues)),r.value[u]=e.value})):(l.issues.length&&r.issues.push(...hi(n,l.issues)),r.value[u]=l.value)}c&&c.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:c,continue:!0})}return s.length?Promise.all(s).then(()=>r):r}}),da=Pi("$ZodEnum",(e,t)=>{us.init(e,t);const n=Br(t.entries),r=new Set(n);e._zod.values=r;const i=n.filter(e=>oi.has(typeof e));e._zod.pattern=new RegExp(i.length?`^(${i.map(e=>si(e.toString())).join("|")})$`:"^[^\\s\\S]$"),e._zod.parse=(t,i)=>{const o=t.value;return r.has(o)||t.issues.push({code:"invalid_value",values:n,input:o,inst:e}),t}}),ua=Pi("$ZodLiteral",(e,t)=>{us.init(e,t);const n=new Set(t.values);e._zod.values=n,e._zod.pattern=new RegExp(t.values.length?`^(${t.values.map(e=>"string"==typeof e?si(e):e?si(e.toString()):String(e)).join("|")})$`:"^[^\\s\\S]$"),e._zod.parse=(r,i)=>{const o=r.value;return n.has(o)||r.issues.push({code:"invalid_value",values:t.values,input:o,inst:e}),r}}),la=Pi("$ZodTransform",(e,t)=>{us.init(e,t),e._zod.optin="optional",$i.memoizer?.guard(e),e._zod.parse=(n,r)=>{if("backward"===r.direction)throw new zi(e.constructor.name);const i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(e=>(n.value=e,n));if(i instanceof Promise)throw new xi;return n.value=i,n}});function pa(e,t){return e.value=t.issues.length?void 0:t.value,e}const fa=Pi("$ZodOptional",(e,t)=>{us.init(e,t),Ti(e,"optin",e=>"defaulted"===e.def.innerType._zod.optin?"defaulted":"optional"),e._zod.optout="optional",Ti(e,"values",e=>{const t=e.def.innerType._zod.values;return t?new Set([...t,void 0]):void 0}),Ti(e,"pattern",e=>{const t=e.def.innerType._zod.pattern;return t?new RegExp(`^(${Zr(t.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if(void 0===e.value){if("defaulted"!==t.innerType._zod.optin)return e;const r=t.innerType._zod.run({value:e.value,issues:[]},n);return r instanceof Promise?r.then(t=>pa(e,t)):pa(e,r)}return t.innerType._zod.run(e,n)}}),ha=Pi("$ZodExactOptional",(e,t)=>{fa.init(e,t),Ti(e,"values",e=>e.def.innerType._zod.values),Ti(e,"pattern",e=>e.def.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),ga=Pi("$ZodNullable",(e,t)=>{us.init(e,t),Ti(e,"optin",e=>e.def.innerType._zod.optin),Ti(e,"optout",e=>e.def.innerType._zod.optout),Ti(e,"pattern",e=>{const t=e.def.innerType._zod.pattern;return t?new RegExp(`^(${Zr(t.source)}|null)$`):void 0}),Ti(e,"values",e=>e.def.innerType._zod.values?new Set([...e.def.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>null===e.value?e:t.innerType._zod.run(e,n)}),ya=Pi("$ZodDefault",(e,t)=>{us.init(e,t),e._zod.optin="defaulted",Ti(e,"values",e=>e.def.innerType._zod.values),e._zod.parse=(e,n)=>{if("backward"===n.direction)return t.innerType._zod.run(e,n);if(void 0===e.value)return e.value=t.defaultValue,e;const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>ma(e,t)):ma(r,t)}});function ma(e,t){return void 0===e.value&&(e.value=t.defaultValue),e}const va=Pi("$ZodPrefault",(e,t)=>{us.init(e,t),e._zod.optin="defaulted",Ti(e,"values",e=>e.def.innerType._zod.values),e._zod.parse=(e,n)=>("backward"===n.direction||void 0===e.value&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),Ia=Pi("$ZodNonOptional",(e,t)=>{us.init(e,t),Ti(e,"values",e=>{const t=e.def.innerType._zod.values;return t?new Set([...t].filter(e=>void 0!==e)):void 0}),e._zod.parse=(n,r)=>{const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(t=>wa(t,e)):wa(i,e)}});function wa(e,t){return e.issues.length||void 0!==e.value||e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}function _a(e,t,n,r){return t.issues.length?(e.value=n.catchValue({...t,value:e.value,error:{issues:t.issues.map(e=>mi(e,r,Mi()))},input:e.value}),e):(e.value=t.value,t.memo&&(e.memo=!0),e)}const Ea=Pi("$ZodCatch",(e,t)=>{us.init(e,t),Ti(e,"optin",e=>"defaulted"===e.def.innerType._zod.optin?"defaulted":"optional"),Ti(e,"optout",e=>e.def.innerType._zod.optout),Ti(e,"values",e=>e.def.innerType._zod.values),e._zod.parse=(e,n)=>{if("backward"===n.direction)return t.innerType._zod.run(e,n);const r=t.innerType._zod.run({value:e.value,issues:[]},n);return r instanceof Promise?r.then(r=>_a(e,r,t,n)):_a(e,r,t,n)}}),ba=Pi("$ZodPipe",(e,t)=>{us.init(e,t),Ti(e,"values",e=>e.def.in._zod.values),Ti(e,"optin",e=>e.def.in._zod.optin),Ti(e,"optout",e=>e.def.out._zod.optout),Ti(e,"propValues",e=>e.def.in._zod.propValues),e._zod.parse=(e,n)=>{if("backward"===n.direction){const r=t.out._zod.run(e,n);return r instanceof Promise?r.then(e=>Sa(e,t.in,n)):Sa(r,t.in,n)}const r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>Sa(e,t.out,n)):Sa(r,t.out,n)}});function Sa(e,t,n){return e.issues.some(e=>"unrecognized_keys"!==e.code)?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},n)}const Aa=Pi("$ZodReadonly",(e,t)=>{us.init(e,t),Ti(e,"propValues",e=>e.def.innerType._zod.propValues),Ti(e,"values",e=>e.def.innerType._zod.values),Ti(e,"optin",e=>e.def.innerType?._zod?.optin),Ti(e,"optout",e=>e.def.innerType?._zod?.optout),e._zod.parse=(e,n)=>{if("backward"===n.direction)return t.innerType._zod.run(e,n);const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(Da):Da(r)}});function Da(e){return e.memo||(e.value=Object.freeze(e.value)),e}const ka=Pi("$ZodCustom",(e,t)=>{_o.init(e,t),us.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{const r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(t=>Ta(t,n,r,e));Ta(i,n,r,e)}});function Ta(e,t,n,r){if(!e){const e={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(_i(e))}}var Ca;(Ca=globalThis).__zod_globalRegistry??(Ca.__zod_globalRegistry=new class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){const n=t[0];return this._map.set(e,n),n&&"object"==typeof n&&"id"in n&&this._idmap.set(n.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){const t=this._map.get(e);return t&&"object"==typeof t&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){const t=e._zod.parent;if(t){const n={...this.get(t)??{}};delete n.id;const r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}});const Oa=globalThis.__zod_globalRegistry;function Na(e,t){return new So({check:"less_than",...ci(t),value:e,inclusive:!1})}function Ra(e,t){return new So({check:"less_than",...ci(t),value:e,inclusive:!0})}function Pa(e,t){return new Ao({check:"greater_than",...ci(t),value:e,inclusive:!1})}function xa(e,t){return new Ao({check:"greater_than",...ci(t),value:e,inclusive:!0})}function za(e,t){return new Do({check:"multiple_of",...ci(t),value:e})}function $a(e,t){return new To({check:"max_length",...ci(t),maximum:e})}function Ma(e,t){return new Co({check:"min_length",...ci(t),minimum:e})}function La(e,t){return new Oo({check:"length_equals",...ci(t),length:e})}function Ua(e){return new Lo({check:"overwrite",tx:e})}function ja(e,...t){for(const n of t)for(const t of Reflect.ownKeys(n))Object.prototype.propertyIsEnumerable.call(n,t)&&Yr(e,t,n[t]);return e}function Ha(e){let t=e?.target??"draft-2020-12";return"draft-4"===t&&(t="draft-04"),"draft-7"===t&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??Oa,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:e?.cycles??"ref",reused:e?.reused??"inline",intersections:[],deferred:[],external:e?.external??void 0}}function Ka(e,t,n,r,i){const o="function"==typeof t.unrepresentable?t.unrepresentable({zodSchema:e,path:r.path,message:i}):t.unrepresentable;if("any"===o)return!1;if(void 0===o||"throw"===o)throw new Error(i);return Object.assign(n,o),!0}function Va(e,t,n={path:[],schemaPath:[]}){var r;const i=e._zod.def,o=t.seen.get(e);if(o)return o.count++,n.schemaPath.includes(e)&&(o.cycle=n.path),o.schema;const s={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,s),t.sharedDefsExtractedFor=void 0,t.sharedEmitDoneFor=void 0;const a=e._zod.toJSONSchema?.();if(a)s.schema=a;else{const r={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,s.schema,r);else{const n=s.schema,o=t.processors[i.type];if(!o)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);o(e,t,n,r)}const o=e._zod.parent;o&&(s.ref||(s.ref=o),Va(o,t,r),t.seen.get(o).isParent=!0)}const c=t.metadataRegistry.get(e);return c&&ja(s.schema,c),"input"===t.io&&Qa(e)&&(delete s.schema.examples,delete s.schema.default),"input"===t.io&&"_prefault"in s.schema&&((r=s.schema).default??(r.default=s.schema._prefault)),delete s.schema._prefault,t.seen.get(e).schema}function Fa(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function qa(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");if(e.external&&e.sharedDefsExtractedFor===e.external)return;const r=new Map;for(const t of e.seen.entries()){const n=e.metadataRegistry.get(t[0])?.id;if(n){const e=r.get(n);if(e&&e!==t[0])throw new Error(`Duplicate schema id "${n}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(n,t[0])}}const i=t=>{if(t[1].schema.$ref)return;const r=t[1],{ref:i,defId:o}=(t=>{const r="draft-2020-12"===e.target?"$defs":"definitions";if(e.external){const n=e.external.registry.get(t[0])?.id,i=e.external.uri??(e=>e);if(n)return{ref:i(n)};const o=t[1].defId??t[1].schema.id??"schema"+e.counter++;return t[1].defId=o,{defId:o,ref:`${i("__shared")}#/${r}/${Fa(o)}`}}const i=`#/${r}/`;if(t[1]===n&&!t[1].schema.id)return{ref:"#"};const o=t[1].schema.id??"__schema"+e.counter++;return{defId:o,ref:i+Fa(o)}})(t);r.def={...r.schema},o&&(r.defId=o);const s=r.schema;for(const e in s)delete s[e];s.$ref=i};if("throw"===e.cycles)for(const t of e.seen.entries()){const e=t[1];if(e.cycle)throw new Error(`Cycle detected: #/${e.cycle?.join("/")}/<root>\n\nSet the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const n of e.seen.entries()){const r=n[1];if(t===n[0]){i(n);continue}if(e.external){const r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){i(n);continue}}const o=e.metadataRegistry.get(n[0])?.id;(o||r.cycle||r.count>1&&"ref"===e.reused)&&i(n)}e.external&&(e.sharedDefsExtractedFor=e.external)}function Ba(e){const t=e.anyOf;if(!Array.isArray(t)||0===t.length||void 0!==e.type)return;const n=[];for(const e of t){if(!e||"object"!=typeof e)return;Ba(e);const t=Object.keys(e);if(1!==t.length||"type"!==t[0])return;const r=e.type;for(const e of Array.isArray(r)?r:[r]){if("string"!=typeof e)return;n.includes(e)||n.push(e)}}delete e.anyOf,e.type=1===n.length?n[0]:n}const Ja=new Set(["type","properties","required","additionalProperties"]),Wa=["oneOf","anyOf"];function Ga(e){const t=e.additionalProperties;return void 0===t||!1===t||"object"!=typeof t||null===t?null:Object.keys(t).length?t:null}function Za(e){const t=[];for(const n of e){if("object"!=typeof n||"object"!==n.type)return null;for(const e in n)if(!Ja.has(e))return null;t.push(n)}const n={},r=new Set;for(const e of t){for(const r in e.properties){if(Object.prototype.hasOwnProperty.call(n,r))continue;const e=[];for(const n of t){const t=n.properties?.[r]??Ga(n);null!=t&&(e.some(e=>JSON.stringify(e)===JSON.stringify(t))||e.push(t))}Yr(n,r,1===e.length?e[0]:Za(e)??{allOf:e})}for(const t of e.required??[])r.add(t)}const i={type:"object",properties:n};if(r.size&&(i.required=[...r]),t.every(e=>!1===e.additionalProperties))i.additionalProperties=!1;else{const e=[];for(const n of t){const t=Ga(n);t&&!e.some(e=>JSON.stringify(e)===JSON.stringify(t))&&e.push(t)}1===e.length?i.additionalProperties=e[0]:e.length>1&&(i.additionalProperties={allOf:e})}return i}function Ya(e){const t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(const t of Ja)if(t in e)return;const n=t.filter(e=>Wa.some(t=>Array.isArray(e[t])));let r=null;if(n.length){const e=n[0],i=Wa.find(t=>Array.isArray(e[t]));if(1!==Object.keys(e).length)return;const o=t.filter(t=>t!==e),s=e[i].map(e=>Za([...o,e]));if(s.some(e=>!e))return;r={[i]:s}}else r=Za(t);r&&(delete e.allOf,ja(e,r))}function Xa(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=t=>{const n=e.seen.get(t);if(null===n.ref)return;const i=n.def??n.schema,o={...i},s=n.ref;if(n.ref=null,s){r(s);const n=e.seen.get(s),a=n.schema;if(!a.$ref||"draft-07"!==e.target&&"draft-04"!==e.target&&"openapi-3.0"!==e.target?ja(i,a):(i.allOf=i.allOf??[],i.allOf.push(a)),ja(i,o),t._zod.parent===s)for(const e in i)"$ref"!==e&&"allOf"!==e&&(e in o||delete i[e]);if(a.$ref&&n.def)for(const e in i)"$ref"!==e&&"allOf"!==e&&e in n.def&&JSON.stringify(i[e])===JSON.stringify(n.def[e])&&delete i[e]}const a=t._zod.parent;if(a&&a!==s){r(a);const t=e.seen.get(a);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(const e in i)"$ref"!==e&&"allOf"!==e&&e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:n.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(const t of[...e.seen.entries()].reverse())r(t[0]);if("openapi-3.0"!==e.target)for(const t of e.seen.entries())Ba(t[1].def??t[1].schema);for(const t of e.deferred)t();if(e.intersections.length){const t=new Map;for(const n of e.seen.values())for(const e of[n.schema,n.def]){const n=e?.allOf;if(!Array.isArray(n))continue;const r=t.get(n);r?r.push(e):t.set(n,[e])}for(const n of e.intersections)for(const e of t.get(n)??[])Ya(e)}}const i={};if("draft-2020-12"===e.target?i.$schema="https://json-schema.org/draft/2020-12/schema":"draft-07"===e.target?i.$schema="http://json-schema.org/draft-07/schema#":"draft-04"===e.target?i.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const n=e.external.registry.get(t)?.id;if(!n)throw new Error("Schema is missing an `id` property");i.$id=e.external.uri(n)}ja(i,n.defId?n.schema:n.def??n.schema);const o=e.metadataRegistry.get(t)?.id;void 0!==o&&i.id===o&&delete i.id;const s=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(const t of e.seen.entries()){const e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,Yr(s,e.defId,e.def))}e.external&&(e.sharedEmitDoneFor=e.external),e.external||Object.keys(s).length>0&&("draft-2020-12"===e.target?i.$defs=s:i.definitions=s);try{const n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,"~standard",{value:{...t["~standard"],jsonSchema:{input:ec(t,"input",e.processors),output:ec(t,"output",e.processors)}},enumerable:!1,writable:!1}),n}catch(e){throw new Error("Error converting schema to JSON.")}}function Qa(e,t){const n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);const r=e._zod.def;if("transform"===r.type)return!0;if("array"===r.type)return Qa(r.element,n);if("set"===r.type)return Qa(r.valueType,n);if("lazy"===r.type)return Qa(r.getter(),n);if("promise"===r.type||"optional"===r.type||"nonoptional"===r.type||"nullable"===r.type||"readonly"===r.type||"default"===r.type||"prefault"===r.type||"catch"===r.type)return Qa(r.innerType,n);if("intersection"===r.type)return Qa(r.left,n)||Qa(r.right,n);if("record"===r.type||"map"===r.type)return Qa(r.keyType,n)||Qa(r.valueType,n);if("pipe"===r.type)return!!e._zod.traits.has("$ZodCodec")||Qa(r.in,n)||Qa(r.out,n);if("object"===r.type){for(const e in r.shape)if(Qa(r.shape[e],n))return!0;return!1}if("union"===r.type){for(const e of r.options)if(Qa(e,n))return!0;return!1}if("tuple"===r.type){for(const e of r.items)if(Qa(e,n))return!0;return!(!r.rest||!Qa(r.rest,n))}return!1}const ec=(e,t,n={})=>r=>{const{libraryOptions:i,target:o}=r??{},s=Ha({...i??{},target:o,io:t,processors:n});return Va(e,s),qa(s,e),Xa(s,e)},tc={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""};function nc(e){const t=e._zod.def;return"pipe"===t.type&&t.in._zod.traits.has("$ZodTransform")?nc(t.out):"catch"===t.type?nc(t.innerType):e._zod.optin}function rc(e,t,n){if(t.$ref){if(n.has(t))return t;n.add(t);const r=e.get(t)?.def;if(!r)return t;const i=rc(e,r,n);return i===r?t:i}for(const r of["anyOf","oneOf"]){const i=t[r];if(!Array.isArray(i))continue;const o=i.map(t=>rc(e,t,n));o.some((e,t)=>e!==i[t])&&(t={...t,[r]:o})}const r=Array.isArray(t.type)?t.type:[t.type],i=!r.includes("string")&&r.some(e=>"number"===e||"integer"===e),o=t.enum??(void 0!==t.const?[t.const]:void 0);if(!i&&!o?.some(e=>"number"==typeof e))return t;const{minimum:s,maximum:a,exclusiveMinimum:c,exclusiveMaximum:d,multipleOf:u,format:l,id:p,...f}=t;return f.enum?f.enum=f.enum.map(e=>"number"==typeof e?String(e):e):"number"==typeof f.const&&(f.const=String(f.const)),i?(f.type="string",o||(f.pattern=(r.includes("number")?mo:yo).source),f):f}const ic=new WeakMap,oc=Symbol();function sc(e,t,n,r,i){let o=!1;const s=JSON.stringify(e,(e,t)=>"bigint"!=typeof t?t:(o=!0,null));return o?(Ka(t,n,r,i,"BigInt defaults cannot be represented in JSON Schema"),oc):JSON.parse(s)}const ac=(e,t,n,r)=>{const i=e._zod.def;Va(i.innerType,t,r),t.seen.get(e).ref=i.innerType},cc=()=>{const e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function t(t){return e[t]??null}const n={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",credit_card:"credit card number",jwt:"JWT",template_literal:"input"},r={nan:"NaN"};function i(e,t){return"number"!==e||"number"!=typeof t||Number.isFinite(t)?r[e]??e:String(t)}return e=>{switch(e.code){case"invalid_type":return`Invalid input: expected ${i(e.expected)}, received ${i(function(e){const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(null===e)return"null";if(Array.isArray(e))return"array";const t=e;if(t&&Object.getPrototypeOf(t)!==Object.prototype&&"constructor"in t&&t.constructor)return t.constructor.name}}return t}(e.input),e.input)}`;case"invalid_value":return 1===e.values.length?`Invalid input: expected ${di(e.values[0])}`:`Invalid option: expected one of ${Jr(e.values,"|")}`;case"too_big":{const n=e.exact?"exactly ":e.inclusive?"<=":"<",r=t(e.origin);return r?`Too big: expected ${e.origin??"value"} to have ${n}${e.maximum.toString()} ${r.unit??"elements"}`:`Too big: expected ${e.origin??"value"} to be ${n}${e.maximum.toString()}`}case"too_small":{const n=e.exact?"exactly ":e.inclusive?">=":">",r=t(e.origin);return r?`Too small: expected ${e.origin} to have ${n}${e.minimum.toString()} ${r.unit}`:`Too small: expected ${e.origin} to be ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Invalid string: must start with "${t.prefix}"`:"ends_with"===t.format?`Invalid string: must end with "${t.suffix}"`:"includes"===t.format?`Invalid string: must include "${t.includes}"`:"regex"===t.format?`Invalid string: must match pattern ${t.pattern}`:`Invalid ${n[t.format]??e.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${e.divisor}`;case"unrecognized_keys":return`Unrecognized key${e.keys.length>1?"s":""}: ${Jr(e.keys,", ")}`;case"invalid_key":return`Invalid key in ${e.origin}`;case"invalid_union":return e.options&&Array.isArray(e.options)&&e.options.length>0?`Invalid discriminator value. Expected ${e.options.map(e=>`'${e}'`).join(" | ")}`:!1===e.inclusive?"Invalid input: more than one option matched":"Invalid input";case"invalid_element":return`Invalid value in ${e.origin}`;default:return"Invalid input"}}},dc=new WeakSet([Object.prototype,Error.prototype]);function uc(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){const e=n(this);return Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0}),e},set(e){Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0})}})}const lc=(e,t)=>{qo.init(e,t),e.name="ZodError";const n=Object.getPrototypeOf(e);dc.has(n)||(dc.add(n),uc(n,"format",e=>t=>function(e,t=e=>e.message){const n={_errors:[]},r=(e,i=[])=>{for(const o of e.issues)if("invalid_union"===o.code&&o.errors.length)o.errors.map(e=>r({issues:e},[...i,...o.path]));else if("invalid_key"===o.code)r({issues:o.issues},[...i,...o.path]);else if("invalid_element"===o.code)r({issues:o.issues},[...i,...o.path]);else{const e=[...i,...o.path];if(0===e.length)n._errors.push(t(o));else{let r=n,i=0;for(;i<e.length;){const n=e[i],s=i===e.length-1;if("_errors"===n){s&&r._errors.push(t(o)),i++;continue}Object.prototype.hasOwnProperty.call(r,n)||Object.defineProperty(r,n,{value:{_errors:[]},enumerable:!0,writable:!0,configurable:!0});const a=r[n];s&&a._errors.push(t(o)),r=a,i++}}}};return r(e),n}(e,t)),uc(n,"flatten",e=>t=>function(e,t=e=>e.message){const n={},r=[];for(const i of e.issues)i.path.length>0?Jo(n,i.path[0],()=>[]).push(t(i)):r.push(t(i));return{formErrors:r,fieldErrors:n}}(e,t)),uc(n,"addIssue",e=>t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,Wr,2)}),uc(n,"addIssues",e=>t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,Wr,2)}),Object.defineProperty(n,"isEmpty",{configurable:!0,enumerable:!1,get(){return 0===this.issues.length}}))},pc=Pi("ZodError",lc,void 0,{Parent:Error}),fc=Go(pc),hc=Zo(pc),gc=Yo(pc),yc=Qo(pc),mc=ts(pc),vc=ns(pc),Ic=rs(pc),wc=is(pc),_c=os(pc),Ec=ss(pc),bc=as(pc),Sc=cs(pc);function Ac(){$i.memoizer||Mi({memoizer:Bi})}const Dc=Pi("ZodType",(e,t)=>($i.localeError||Mi({localeError:cc()}),us.init(e,t),e.def=t,e.type=t.type,e),{check(...e){const t=this.def;return this.clone(Xr(t,{checks:[...t.checks??[],...e.map(e=>"function"==typeof e?{_zod:{check:e,def:{check:"custom"},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return ai(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(function(e,t={}){return function(e,t,n){return new e({type:"custom",check:"custom",fn:t,...ci(n)})}(zd,e,t)}(e,t))},superRefine(e,t){return this.check(function(e,t){return function(e,t){const n=function(e,t){const n=new _o({check:"custom",...ci(t)});return n._zod.check=e,n}(t=>(t.addIssue=e=>{if("string"==typeof e)t.issues.push(_i(e,t.value,n._zod.def));else{const r=e;r.fatal&&(r.continue=!1),r.code??(r.code="custom"),"input"in r||(r.input=t.value),r.inst??(r.inst=n),r.continue??(r.continue=!n._zod.def.abort),t.issues.push(_i(r))}},e(t.value,t)),t);return n}(e,t)}(e,t))},overwrite(e){return this.check(Ua(e))},optional(){return Sd(this)},exactOptional(){return new Ad({type:"optional",innerType:this})},nullable(){return kd(this)},nullish(){return Sd(kd(this))},nonoptional(e){return function(e,t){return new Od({type:"nonoptional",innerType:e,...ci(t)})}(this,e)},array(){return dd(this)},or(e){return fd([this,e])},and(e){return new yd({type:"intersection",left:this,right:e})},transform(e){return Pd(this,new Ed({type:"transform",transform:e}))},default(e){return t=e,new Td({type:"default",innerType:this,get defaultValue(){return"function"==typeof t?t():ii(t)}});var t},prefault(e){return t=e,new Cd({type:"prefault",innerType:this,get defaultValue(){return"function"==typeof t?t():ii(t)}});var t},catch(e){return new Nd({type:"catch",innerType:this,catchValue:"function"==typeof(t=e)?t:Ci(t)});var t},pipe(e){return Pd(this,e)},readonly(){return new xd({type:"readonly",innerType:this})},describe(e){const t=this.clone();return Oa.add(t,{description:e}),t},meta(...e){if(0===e.length)return Oa.get(this);const t=this.clone();return Oa.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...t){return 0===t.length?e(this):e(this,...t)},get"~standard"(){return bi(this,"~standard",{...ps(this),jsonSchema:{input:ec(this,"input"),output:ec(this,"output")}})},set"~standard"(e){Ei(this,"~standard",e)},parse:function e(t,n){return fc(this,t,n,{callee:e})},parseAsync:async function e(t,n){return await hc(this,t,n,{callee:e})},safeParse(e,t){return gc(this,e,t)},async safeParseAsync(e,t){return yc(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){Ei(this,"spa",e)},encode:function e(t,n){return mc(this,t,n,{callee:e})},decode:function e(t,n){return vc(this,t,n,{callee:e})},encodeAsync:async function e(t,n){return await Ic(this,t,n,{callee:e})},decodeAsync:async function e(t,n){return await wc(this,t,n,{callee:e})},safeEncode(e,t){return _c(this,e,t)},safeDecode(e,t){return Ec(this,e,t)},async safeEncodeAsync(e,t){return bc(this,e,t)},async safeDecodeAsync(e,t){return Sc(this,e,t)},toJSONSchema(e){return((e,t={})=>n=>{const r=Ha({...n,processors:t});return Va(e,r),qa(r,e),Xa(r,e)})(this,{})(e)},get description(){return Oa.get(this)?.description},get _def(){return this._zod.def}}),kc=Pi("_ZodString",(e,t)=>{fs.init(e,t),Dc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n)=>{const r=n;r.type="string";const{minimum:i,maximum:o,format:s,patterns:a,contentEncoding:c,laxFormat:d}=e._zod.bag;if("number"==typeof i&&(r.minLength=i),"number"==typeof o&&(r.maxLength=o),s&&(r.format=tc[s]??s,""===r.format&&delete r.format,("time"===s||d)&&delete r.format),c&&(r.contentEncoding=c),a&&a.size>0){const e=[...a];1===e.length?r.pattern=e[0].source:e.length>1&&(r.allOf=[...e.map(e=>({..."draft-07"===t.target||"draft-04"===t.target||"openapi-3.0"===t.target?{type:"string"}:{},pattern:e.source}))])}})(e,t,n);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null},{regex(...e){return this.check(function(e,t){return new Ro({check:"string_format",format:"regex",...ci(t),pattern:e})}(...e))},includes(...e){return this.check(function(e,t){return new zo({check:"string_format",format:"includes",...ci(t),includes:e})}(...e))},startsWith(...e){return this.check(function(e,t){return new $o({check:"string_format",format:"starts_with",...ci(t),prefix:e})}(...e))},endsWith(...e){return this.check(function(e,t){return new Mo({check:"string_format",format:"ends_with",...ci(t),suffix:e})}(...e))},min(...e){return this.check(Ma(...e))},max(...e){return this.check($a(...e))},length(...e){return this.check(La(...e))},nonempty(...e){return this.check(Ma(1,...e))},lowercase(e){return this.check(function(e){return new Po({check:"string_format",format:"lowercase",...ci(e)})}(e))},uppercase(e){return this.check(function(e){return new xo({check:"string_format",format:"uppercase",...ci(e)})}(e))},trim(){return this.check(Ua(e=>e.trim()))},normalize(...e){return this.check(function(e){return Ua(t=>t.normalize(e))}(...e))},toLowerCase(){return this.check(Ua(e=>e.toLowerCase()))},toUpperCase(){return this.check(Ua(e=>e.toUpperCase()))},slugify(){return this.check(Ua(e=>function(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}(e)))}}),Tc=Pi("ZodString",(e,t)=>{fs.init(e,t),kc.init(e,t)},{email(e){return this.check(function(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...ci(t)})}(zc,e))},url(e){return this.check(function(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...ci(t)})}(Lc,e))},jwt(e){return this.check(function(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...ci(t)})}(Qc,e))},emoji(e){return this.check(function(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...ci(t)})}(Uc,e))},guid(e){return this.check(function(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...ci(t)})}($c,e))},uuid(e){return this.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...ci(t)})}(Mc,e))},uuidv4(e){return this.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...ci(t)})}(Mc,e))},uuidv6(e){return this.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...ci(t)})}(Mc,e))},uuidv7(e){return this.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...ci(t)})}(Mc,e))},nanoid(e){return this.check(function(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...ci(t)})}(jc,e))},cuid(e){return this.check(function(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...ci(t)})}(Hc,e))},cuid2(e){return this.check(function(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...ci(t)})}(Kc,e))},ulid(e){return this.check(function(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...ci(t)})}(Vc,e))},base64(e){return this.check(function(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...ci(t)})}(Zc,e))},base64url(e){return this.check(function(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...ci(t)})}(Yc,e))},xid(e){return this.check(function(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...ci(t)})}(Fc,e))},ksuid(e){return this.check(function(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...ci(t)})}(qc,e))},ipv4(e){return this.check(function(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...ci(t)})}(Bc,e))},ipv6(e){return this.check(function(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...ci(t)})}(Jc,e))},cidrv4(e){return this.check(function(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...ci(t)})}(Wc,e))},cidrv6(e){return this.check(function(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...ci(t)})}(Gc,e))},e164(e){return this.check(function(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...ci(t)})}(Xc,e))},datetime(e){return this.check(function(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...ci(t)})}(Nc,e))},date(e){return this.check(function(e,t){return new e({type:"string",format:"date",check:"string_format",...ci(t)})}(Rc,e))},time(e){return this.check(function(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...ci(t)})}(Pc,e))},duration(e){return this.check(function(e,t){return new e({type:"string",format:"duration",check:"string_format",...ci(t)})}(xc,e))}});function Cc(e){return function(e,t){return new e({type:"string",...ci(t)})}(Tc,e)}const Oc=Pi("ZodStringFormat",(e,t)=>{hs.init(e,t),kc.init(e,t)}),Nc=Pi("ZodISODateTime",(e,t)=>{ks.init(e,t),Oc.init(e,t)}),Rc=Pi("ZodISODate",(e,t)=>{Ts.init(e,t),Oc.init(e,t)}),Pc=Pi("ZodISOTime",(e,t)=>{Cs.init(e,t),Oc.init(e,t)}),xc=Pi("ZodISODuration",(e,t)=>{Os.init(e,t),Oc.init(e,t)}),zc=Pi("ZodEmail",(e,t)=>{ms.init(e,t),Oc.init(e,t)}),$c=Pi("ZodGUID",(e,t)=>{gs.init(e,t),Oc.init(e,t)}),Mc=Pi("ZodUUID",(e,t)=>{ys.init(e,t),Oc.init(e,t)}),Lc=Pi("ZodURL",(e,t)=>{Is.init(e,t),Oc.init(e,t)}),Uc=Pi("ZodEmoji",(e,t)=>{ws.init(e,t),Oc.init(e,t)}),jc=Pi("ZodNanoID",(e,t)=>{_s.init(e,t),Oc.init(e,t)}),Hc=Pi("ZodCUID",(e,t)=>{Es.init(e,t),Oc.init(e,t)}),Kc=Pi("ZodCUID2",(e,t)=>{bs.init(e,t),Oc.init(e,t)}),Vc=Pi("ZodULID",(e,t)=>{Ss.init(e,t),Oc.init(e,t)}),Fc=Pi("ZodXID",(e,t)=>{As.init(e,t),Oc.init(e,t)}),qc=Pi("ZodKSUID",(e,t)=>{Ds.init(e,t),Oc.init(e,t)}),Bc=Pi("ZodIPv4",(e,t)=>{Ns.init(e,t),Oc.init(e,t)}),Jc=Pi("ZodIPv6",(e,t)=>{xs.init(e,t),Oc.init(e,t)}),Wc=Pi("ZodCIDRv4",(e,t)=>{zs.init(e,t),Oc.init(e,t)}),Gc=Pi("ZodCIDRv6",(e,t)=>{$s.init(e,t),Oc.init(e,t)}),Zc=Pi("ZodBase64",(e,t)=>{Ls.init(e,t),Oc.init(e,t)}),Yc=Pi("ZodBase64URL",(e,t)=>{Us.init(e,t),Oc.init(e,t)}),Xc=Pi("ZodE164",(e,t)=>{js.init(e,t),Oc.init(e,t)}),Qc=Pi("ZodJWT",(e,t)=>{Hs.init(e,t),Oc.init(e,t)}),ed=Pi("ZodNumber",(e,t)=>{Ks.init(e,t),Dc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=n,{minimum:o,maximum:s,format:a,multipleOf:c,exclusiveMaximum:d,exclusiveMinimum:u}=e._zod.bag;"string"==typeof a&&a.includes("int")?i.type="integer":i.type="number";const l="number"==typeof u&&u>=(o??Number.NEGATIVE_INFINITY),p="number"==typeof d&&d<=(s??Number.POSITIVE_INFINITY),f="draft-04"===t.target||"openapi-3.0"===t.target;l?f?(i.minimum=u,i.exclusiveMinimum=!0):i.exclusiveMinimum=u:"number"==typeof o&&(i.minimum=o),p?f?(i.maximum=d,i.exclusiveMaximum=!0):i.exclusiveMaximum=d:"number"==typeof s&&(i.maximum=s),"number"==typeof c&&(Number.isFinite(c)&&0!==c?i.multipleOf=Math.abs(c):Ka(e,t,i,r,`A multipleOf divisor of ${c} cannot be represented in JSON Schema`))})(e,t,n,r);const n=e._zod.bag;e.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null},{gt(e,t){return this.check(Pa(e,t))},gte(e,t){return this.check(xa(e,t))},min(e,t){return this.check(xa(e,t))},lt(e,t){return this.check(Na(e,t))},lte(e,t){return this.check(Ra(e,t))},max(e,t){return this.check(Ra(e,t))},int(e){return this.check(rd(e))},safe(e){return this.check(rd(e))},positive(e){return this.check(Pa(0,e))},nonnegative(e){return this.check(xa(0,e))},negative(e){return this.check(Na(0,e))},nonpositive(e){return this.check(Ra(0,e))},multipleOf(e,t){return this.check(za(e,t))},step(e,t){return this.check(za(e,t))},finite(){return this}});function td(e){return function(e,t){return new e({type:"number",checks:[],...ci(t)})}(ed,e)}const nd=Pi("ZodNumberFormat",(e,t)=>{Vs.init(e,t),ed.init(e,t)});function rd(e){return function(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...ci(t)})}(nd,e)}const id=Pi("ZodBoolean",(e,t)=>{Fs.init(e,t),Dc.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t,n)=>{n.type="boolean"})(0,0,t)});const od=Pi("ZodUnknown",(e,t)=>{qs.init(e,t),Dc.init(e,t),e._zod.processJSONSchema=(e,t,n)=>{}});function sd(){return new od({type:"unknown"})}const ad=Pi("ZodNever",(e,t)=>{Bs.init(e,t),Dc.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t,n)=>{n.not={}})(0,0,t)});const cd=Pi("ZodArray",(e,t)=>{Ac(),Ws.init(e,t),Dc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=n,o=e._zod.def,{minimum:s,maximum:a}=e._zod.bag;"number"==typeof s&&(i.minItems=s),"number"==typeof a&&(i.maxItems=a),i.type="array",i.items=Va(o.element,t,{...r,path:[...r.path,"items"]})})(e,t,n,r),e.element=t.element},{min(e,t){return this.check(Ma(e,t))},nonempty(e){return this.check(Ma(1,e))},max(e,t){return this.check($a(e,t))},length(e,t){return this.check(La(e,t))},unwrap(){return this.element}});function dd(e,t){return function(e,t,n){return new e({type:"array",element:t,...ci(n)})}(cd,e,t)}const ud=Pi("ZodObject",(e,t)=>{Ac(),ta.init(e,t),Dc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=n,o=e._zod.def,s=o.shape;if(Object.getOwnPropertySymbols(s).length&&Ka(e,t,i,r,"Symbol keys cannot be represented in JSON Schema"))return;i.type="object",i.properties={};for(const e in s)Yr(i.properties,e,Va(s[e],t,{...r,path:[...r.path,"properties",e]}));const a=new Set(Object.keys(s)),c=new Set([...a].filter(e=>{const n=o.shape[e];return"input"===t.io?void 0===nc(n):void 0===n._zod.optout}));c.size>0&&(i.required=Array.from(c)),"never"===o.catchall?._zod.def.type?i.additionalProperties=!1:o.catchall?o.catchall&&(i.additionalProperties=Va(o.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):"output"===t.io&&(i.additionalProperties=!1)})(e,t,n,r),function(e,t,n,r){const i=function(e,t){const n=Object.getPrototypeOf(e);return t in n?void 0:n}(e,t);i&&Object.defineProperty(i,t,{configurable:!0,get(){const e={configurable:!0,writable:!0,enumerable:r,value:void 0};return Object.defineProperty(this,t,e),e.value=n(this),Object.defineProperty(this,t,e),e.value},set(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,enumerable:r,value:e})}})}(e,"shape",e=>e._zod.def.shape,!1)},{keyof(){return Id(Object.keys(this._zod.def.shape))},catchall(e){return this.clone({...this._zod.def,catchall:e})},passthrough(){return this.clone({...this._zod.def,catchall:sd()})},loose(){return this.clone({...this._zod.def,catchall:sd()})},strict(){return this.clone({...this._zod.def,catchall:function(e,t){return new e({type:"never",...ci(t)})}(ad,e)});var e},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(e){return function(e,t){if(!ri(t))throw new Error("Invalid input to extend: expected a plain object");const n=e._zod.def.checks;if(n&&n.length>0){const n=e._zod.def.shape;for(const e of Reflect.ownKeys(t))if(void 0!==Object.getOwnPropertyDescriptor(n,e))throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const r=Xr(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return Yr(this,"shape",n),n}});return ai(e,r)}(this,e)},safeExtend(e){return function(e,t){if(!ri(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n=Xr(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return Yr(this,"shape",n),n}});return ai(e,n)}(this,e)},merge(e){return function(e,t){if(!t?._zod?.def)throw new Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.");if(e._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");const n=Xr(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t._zod.def.shape};return Yr(this,"shape",n),n},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return ai(e,n)}(this,e)},pick(e){return function(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");const i=Xr(e._zod.def,{get shape(){const e={};for(const r of Reflect.ownKeys(t)){if(!Object.prototype.hasOwnProperty.call(n.shape,r))throw new Error(`Unrecognized key: "${String(r)}"`);t[r]&&Yr(e,r,n.shape[r])}return Yr(this,"shape",e),e},checks:[]});return ai(e,i)}(this,e)},omit(e){return function(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const i=Xr(e._zod.def,{get shape(){const r={...e._zod.def.shape};for(const e of Reflect.ownKeys(t)){if(!Object.prototype.hasOwnProperty.call(n.shape,e))throw new Error(`Unrecognized key: "${String(e)}"`);t[e]&&delete r[e]}return Yr(this,"shape",r),r},checks:[]});return ai(e,i)}(this,e)},partial(...e){return li(bd,this,e[0])},exactPartial(...e){return li(Ad,this,e[0],"exactPartial")},required(...e){return function(e,t,n){const r=Xr(t._zod.def,{get shape(){const r=t._zod.def.shape,i={...r};if(n)for(const t of Reflect.ownKeys(n)){if(!Object.prototype.hasOwnProperty.call(i,t))throw new Error(`Unrecognized key: "${String(t)}"`);n[t]&&(i[t]=new e({type:"nonoptional",innerType:r[t]}))}else for(const t of Reflect.ownKeys(r))i[t]=new e({type:"nonoptional",innerType:r[t]});return Yr(this,"shape",i),i}});return ai(t,r)}(Od,this,e[0])}});function ld(e,t){const n={type:"object",shape:e??{},...ci(t)};return new ud(n)}const pd=Pi("ZodUnion",(e,t)=>{ra.init(e,t),Dc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.def,o=!1===i.inclusive,s=i.options.map((e,n)=>Va(e,t,{...r,path:[...r.path,o?"oneOf":"anyOf",n]}));o?n.oneOf=s:n.anyOf=s})(e,t,n,r),e.options=t.options});function fd(e,t){return new pd({type:"union",options:e,...ci(t)})}const hd=Pi("ZodDiscriminatedUnion",(e,t)=>{pd.init(e,t),ia.init(e,t)});function gd(e,t,n){return new hd({type:"union",options:t,discriminator:e,...ci(n)})}const yd=Pi("ZodIntersection",(e,t)=>{oa.init(e,t),Dc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.def,o=Va(i.left,t,{...r,path:[...r.path,"allOf",0]}),s=Va(i.right,t,{...r,path:[...r.path,"allOf",1]}),a=e=>"allOf"in e&&1===Object.keys(e).length,c=[...a(o)?o.allOf:[o],...a(s)?s.allOf:[s]];n.allOf=c,t.intersections.push(c)})(e,t,n,r)}),md=Pi("ZodRecord",(e,t)=>{Ac(),ca.init(e,t),Dc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=n,o=e._zod.def;i.type="object";const s=o.keyType,a=s._zod.bag,c=a?.patterns;if("loose"===o.mode&&c&&c.size>0){const e=Va(o.valueType,t,{...r,path:[...r.path,"patternProperties","*"]});i.patternProperties={};for(const t of c)Yr(i.patternProperties,t.source,e)}else{if("draft-07"===t.target||"draft-2020-12"===t.target){i.propertyNames=Va(o.keyType,t,{...r,path:[...r.path,"propertyNames"]});let n=ic.get(t);n||(n=[],ic.set(t,n),t.deferred.push(()=>function(e){const t=new Map;for(const n of e.seen.values())n.def&&!t.has(n.schema)&&t.set(n.schema,n);const n=new Map;for(const r of ic.get(e)??[]){const i=e.seen.get(r),o=(i?.def??i?.schema)?.propertyNames;if(!o||!0===o||n.has(o))continue;const s=rc(t,o,new Set);s!==o&&n.set(o,s)}if(n.size)for(const t of e.seen.values())for(const e of[t.schema,t.def]){const t=e&&n.get(e.propertyNames);t&&(e.propertyNames=t)}}(t))),n.push(e)}i.additionalProperties=Va(o.valueType,t,{...r,path:[...r.path,"additionalProperties"]})}const d=s._zod.values,u="input"===t.io&&void 0!==nc(o.valueType);if(d&&!o.partial&&!u){const e=[...d].filter(e=>"string"==typeof e||"number"==typeof e);e.length>0&&(i.required=e.map(String))}})(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});const vd=Pi("ZodEnum",(e,t)=>{da.init(e,t),Dc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n)=>{const r=Br(e._zod.def.entries);0!==r.length?(r.every(e=>"number"==typeof e)&&(n.type="number"),r.every(e=>"string"==typeof e)&&(n.type="string"),n.enum=r):n.not={}})(e,0,n),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{const i={};for(const r of e){if(!n.has(r))throw new Error(`Key ${r} not found in enum`);i[r]=t.entries[r]}return new vd({...t,checks:[],...ci(r),entries:i})},e.exclude=(e,r)=>{const i={...t.entries};for(const t of e){if(!n.has(t))throw new Error(`Key ${t} not found in enum`);delete i[t]}return new vd({...t,checks:[],...ci(r),entries:i})}});function Id(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new vd({type:"enum",entries:n,...ci(t)})}const wd=Pi("ZodLiteral",(e,t)=>{ua.init(e,t),Dc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.def;if(0===i.values.length)return void(n.not={});const o=[];for(const s of i.values)if(void 0===s){if(Ka(e,t,n,r,"Literal `undefined` cannot be represented in JSON Schema"))return}else if("bigint"==typeof s){if(Ka(e,t,n,r,"BigInt literals cannot be represented in JSON Schema"))return;o.push(Number(s))}else o.push(s);if(0===o.length);else if(1===o.length){const e=o[0];n.type=null===e?"null":typeof e,"draft-04"===t.target||"openapi-3.0"===t.target?n.enum=[e]:n.const=e}else o.every(e=>"number"==typeof e)&&(n.type="number"),o.every(e=>"string"==typeof e)&&(n.type="string"),o.every(e=>"boolean"==typeof e)&&(n.type="boolean"),o.every(e=>null===e)&&(n.type="null"),n.enum=o})(e,t,n,r),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function _d(e,t){return new wd({type:"literal",values:Array.isArray(e)?e:[e],...ci(t)})}const Ed=Pi("ZodTransform",(e,t)=>{Ac(),la.init(e,t),Dc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{Ka(e,t,n,r,"Transforms cannot be represented in JSON Schema")})(e,t,n,r),e._zod.parse=(n,r)=>{if("backward"===r.direction)throw new zi(e.constructor.name);n.addIssue=r=>{if("string"==typeof r)n.issues.push(_i(r,n.value,t));else{const t=r;t.fatal&&(t.continue=!1),t.code??(t.code="custom"),"input"in t||(t.input=n.value),t.inst??(t.inst=e),n.issues.push(_i(t))}};const i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n)):(n.value=i,n)}});const bd=Pi("ZodOptional",(e,t)=>{fa.init(e,t),Dc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ac(e,t,0,r),e.unwrap=()=>e._zod.def.innerType});function Sd(e){return new bd({type:"optional",innerType:e})}const Ad=Pi("ZodExactOptional",(e,t)=>{ha.init(e,t),Dc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ac(e,t,0,r),e.unwrap=()=>e._zod.def.innerType}),Dd=Pi("ZodNullable",(e,t)=>{ga.init(e,t),Dc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.def,o=Va(i.innerType,t,r),s=t.seen.get(e);"openapi-3.0"===t.target?(s.ref=i.innerType,n.nullable=!0):n.anyOf=[o,{type:"null"}]})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function kd(e){return new Dd({type:"nullable",innerType:e})}const Td=Pi("ZodDefault",(e,t)=>{ya.init(e,t),Dc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.def;Va(i.innerType,t,r),t.seen.get(e).ref=i.innerType;const o=sc(i.defaultValue,e,t,n,r);o!==oc&&(n.default=o)})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap}),Cd=Pi("ZodPrefault",(e,t)=>{va.init(e,t),Dc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.def;if(Va(i.innerType,t,r),t.seen.get(e).ref=i.innerType,"input"!==t.io)return;const o=sc(i.defaultValue,e,t,n,r);o!==oc&&(n._prefault=o)})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType}),Od=Pi("ZodNonOptional",(e,t)=>{Ia.init(e,t),Dc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.def;Va(i.innerType,t,r),t.seen.get(e).ref=i.innerType})(e,t,0,r),e.unwrap=()=>e._zod.def.innerType}),Nd=Pi("ZodCatch",(e,t)=>{Ea.init(e,t),Dc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.def;let o;Va(i.innerType,t,r),t.seen.get(e).ref=i.innerType;try{o=i.catchValue(void 0)}catch{return void Ka(e,t,n,r,"Dynamic catch values are not supported in JSON Schema")}n.default=o})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap}),Rd=Pi("ZodPipe",(e,t)=>{ba.init(e,t),Dc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.def,o=i.in._zod.traits.has("$ZodTransform"),s="input"===t.io?o?i.out:i.in:i.out;Va(s,t,r),t.seen.get(e).ref=s})(e,t,0,r),e.in=t.in,e.out=t.out});function Pd(e,t){return new Rd({type:"pipe",in:e,out:t})}const xd=Pi("ZodReadonly",(e,t)=>{Aa.init(e,t),Dc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.def;Va(i.innerType,t,r),t.seen.get(e).ref=i.innerType,n.readOnly=!0})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType}),zd=Pi("ZodCustom",(e,t)=>{ka.init(e,t),Dc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{Ka(e,t,n,r,"Custom types cannot be represented in JSON Schema")})(e,t,n,r)}),$d="https://schema.kya-os.org/v1/protocol/audit/event/v1.0.0",Md="https://schema.kya-os.org/v1/protocol/audit/entry/v1.0.0",Ld="https://schema.kya-os.org/v1/protocol/audit/receipt/v1.0.0",Ud="KYA-AUDIT-JCS-SHA256-JWS-2026",jd="https://schema.kya-os.org/v1/protocol/audit/checkpoint/v1.0.0",Hd="KYA-AUDIT-RFC9162-SHA256-JWS-2026",Kd="https://schema.kya-os.org/v1/protocol/audit/bundle-manifest/v1.0.0",Vd="KYA-AUDIT-BUNDLE-JCS-SHA256-JWS-2026",Fd=256,qd=4096,Bd=Cc().max(20).regex(/^(0|[1-9][0-9]*)$/),Jd=Cc().regex(/^sha256:[a-f0-9]{64}$/),Wd=Cc().min(5).max(2048).regex(/^did:[^\r\n]+$/),Gd=ld({did:Wd,kid:Cc().min(1).max(2304),alg:Id(["EdDSA","ES256"])}).strict(),Zd=ld({objectId:Cc().min(1).max(Fd),ciphertextDigest:Jd,plaintextCommitment:Jd.optional(),mediaType:Cc().min(1).max(Fd),size:Bd,encryption:ld({suite:_d("A256GCM"),keyId:Cc().min(1).max(Fd),nonce:Cc().min(1).max(Fd),aadDigest:Jd}).strict()}).strict(),Yd=gd("kind",[ld({kind:_d("public_did"),did:Wd}).strict(),ld({kind:_d("pairwise_did"),did:Wd}).strict(),ld({kind:_d("keyed_commitment"),value:Jd,keyId:Cc().min(1).max(Fd)}).strict(),ld({kind:_d("evidence_ref"),ref:Zd}).strict()]),Xd=gd("family",[ld({family:_d("session"),phase:Id(["established","rejected","expired","replay_rejected"]),reasonCode:Cc().min(1).max(128).optional()}).strict(),ld({family:_d("tool"),phase:Id(["started","completed","failed","denied","challenged"]),attempt:Bd,idempotencyRef:Cc().min(1).max(Fd).optional()}).strict(),ld({family:_d("proof"),phase:Id(["generated","verified","rejected"]),proofDigest:Jd.optional(),verificationCode:Cc().min(1).max(128).optional()}).strict(),ld({family:_d("delegation"),phase:Id(["issued","verified","rejected","revoked","cascade_revoked","outbound_attached"]),delegationRef:Cc().min(1).max(Fd),parentRef:Cc().min(1).max(Fd).optional(),statusEvidence:dd(Zd).max(256).optional()}).strict(),ld({family:_d("authorization"),phase:Id(["evaluated","approved","denied","step_up_required","grant_used"]),policyDigest:Jd.optional(),grantRef:Cc().min(1).max(Fd).optional()}).strict(),ld({family:_d("consent"),phase:Id(["requested","approved","denied","credential_required","credential_verified","credential_failed"]),consentRef:Cc().min(1).max(Fd).optional()}).strict(),ld({family:_d("key"),phase:Id(["rotated","policy_changed","configuration_changed","integrity_suite_transitioned"]),previousSigner:Gd.optional(),nextSigner:Gd.optional(),configurationDigest:Jd.optional()}).strict(),ld({family:_d("ledger"),phase:Id(["epoch_started","epoch_transitioned","checkpoint_created","checkpoint_anchored","checkpoint_anchor_failed","evidence_disposed","projection_reconciled"]),checkpointDigest:Jd.optional(),previousEpochId:Cc().min(1).max(Fd).optional(),previousTerminalCheckpointDigest:Jd.optional(),successorEpochIds:dd(Cc().min(1).max(Fd)).max(256).optional(),targetEvidenceRef:Zd.optional()}).strict(),ld({family:_d("administration"),phase:Id(["source_high_water","accessed","exported","legal_hold_applied","retention_executed"]),purpose:Cc().min(1).max(Fd).optional(),sourceSequence:Bd.optional(),selectionDigest:Jd.optional()}).strict()]),Qd=ld({source:Id(["delegation","grant","anonymous","policy"]),decision:Id(["allowed","denied","step_up_required","needs_authorization"]),scopeId:Cc().min(1).max(Fd).optional(),delegationRef:Cc().min(1).max(Fd).optional(),delegationCredentialDigest:Jd.optional(),delegationChainDigests:dd(Jd).max(256).optional(),statusEvidence:dd(Zd).max(256).optional(),grantRef:Cc().min(1).max(Fd).optional(),policyId:Cc().min(1).max(Fd).optional(),policyVersion:Cc().min(1).max(Fd).optional(),policyDigest:Jd.optional(),verificationCode:Cc().min(1).max(128).optional()}).strict(),eu=ld({schema:_d($d),eventId:Cc().min(1).max(256),eventType:Id(qr),eventVersion:_d("1.0.0"),binding:Cc().max(Fd).regex(/^urn:kya-os:audit-binding:[a-z0-9][a-z0-9._:-]*$/),occurredAt:td().int().nonnegative(),tenantRef:Yd,source:ld({producer:Yd,sourceId:Cc().min(1).max(256),sourceSequence:Bd.optional(),previousSourceEventDigest:Jd.optional()}).strict(),correlationId:Cc().min(1).max(256).optional(),causationId:Cc().min(1).max(256).optional(),trace:ld({traceId:Cc().regex(/^[a-f0-9]{32}$/).optional(),spanId:Cc().regex(/^[a-f0-9]{16}$/).optional()}).strict().optional(),session:ld({ref:Yd,handshakeNonceCommitment:Jd.optional()}).strict().optional(),actor:Yd.optional(),responsibleParty:Yd.optional(),resource:Yd.optional(),action:ld({category:Cc().min(1).max(128),name:Cc().min(1).max(256).optional(),detailRef:Zd.optional()}).strict(),outcome:Id(["succeeded","failed","denied","challenged","unknown"]),reason:ld({code:Cc().min(1).max(128),detailRef:Zd.optional()}).strict().optional(),authorization:Qd.optional(),proof:Zd.optional(),evidence:dd(Zd).max(256),details:Xd,privacy:ld({classification:Id(["public","internal","confidential","restricted"]),retentionClass:Cc().min(1).max(128),legalHold:Cc().min(1).max(256).optional()}).strict()}).strict().superRefine((e,t)=>{var n;e.details.family!==((n=e.eventType).startsWith("session.")?"session":n.startsWith("tool.")?"tool":n.startsWith("proof.")?"proof":n.startsWith("delegation.")?"delegation":n.startsWith("authorization.")||"grant.used"===n?"authorization":n.startsWith("consent.")||n.startsWith("credential.")?"consent":n.startsWith("key.")||n.startsWith("policy.")||n.startsWith("configuration.")||n.startsWith("integrity_suite.")?"key":n.startsWith("ledger.")||n.startsWith("checkpoint.")||n.startsWith("evidence.")||n.startsWith("projection.")?"ledger":"administration")&&t.addIssue({code:"custom",path:["details","family"],message:`Event detail family ${e.details.family} does not match ${e.eventType}`})}),tu=ld({schema:_d(Md),ledgerId:Cc().min(1).max(256),ledgerEpochId:Cc().min(1).max(256),sequence:Bd,previousEntryDigest:Jd.nullable(),recordedAt:td().int().nonnegative(),recorder:Gd,eventDigest:Jd,event:eu,evidenceManifestDigest:Jd,integritySuite:_d(Ud)}).strict(),nu=ld({schema:_d(Ld),ledgerId:Cc().min(1).max(256),ledgerEpochId:Cc().min(1).max(256),sequence:Bd,eventId:Cc().min(1).max(256),entryDigest:Jd,previousEntryDigest:Jd.nullable(),recordedAt:td().int().nonnegative(),recorder:Gd,integritySuite:_d(Ud)}).strict(),ru=ld({schema:_d(jd),checkpointId:Cc().min(1).max(512),ledgerId:Cc().min(1).max(256),ledgerEpochId:Cc().min(1).max(256),treeSize:Bd,firstSequence:Bd,lastSequence:Bd,rootDigest:Jd,headEntryDigest:Jd,previousCheckpointDigest:Jd.nullable(),createdAt:td().int().nonnegative(),issuer:Gd,integritySuite:_d(Hd)}).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"})}),iu=ld({core:ru,checkpointDigest:Jd,jws:Cc().min(1).max(qd)}).strict(),ou=ld({core:tu,eventDigest:Jd,entryDigest:Jd,recorderReceipt:ld({core:nu,jws:Cc().min(1).max(qd)}).strict()}).strict(),su=ld({core:ld({schema:_d("https://schema.kya-os.org/v1/protocol/audit/observation/v1.0.0"),observerId:Cc().min(1).max(256),observer:Gd,ledgerId:Cc().min(1).max(256),ledgerEpochId:Cc().min(1).max(256),checkpointDigest:Jd,treeSize:Bd,observedAt:td().int().nonnegative(),previousObservationDigest:Jd.nullable()}).strict(),observationDigest:Jd,jws:Cc().min(1).max(qd)}).strict(),au=ld({schema:_d("https://schema.kya-os.org/v1/protocol/audit/anchor-receipt/v1.0.0"),kind:Id(["worm","rfc3161","scitt"]),providerId:Cc().min(1).max(256),checkpointDigest:Jd,issuedAt:td().int().nonnegative(),receiptData:Cc().min(1).max(65536).optional()}).strict(),cu=ld({leafIndex:Bd,treeSize:Bd,auditPath:dd(Jd)}).strict(),du=ld({oldTreeSize:Bd,newTreeSize:Bd,auditPath:dd(Jd)}).strict(),uu=ld({ledgerId:Cc().min(1).max(256),ledgerEpochId:Cc().min(1).max(256),sequence:Bd,entryDigest:Jd,checkpointDigest:Jd,proof:cu}).strict(),lu=ld({ledgerId:Cc().min(1).max(256),ledgerEpochId:Cc().min(1).max(256),oldCheckpointDigest:Jd,newCheckpointDigest:Jd,proof:du}).strict(),pu=ld({ledgerId:Cc().min(1).max(256),ledgerEpochId:Cc().min(1).max(256),firstSequence:Bd,lastSequence:Bd,expectedHeadDigest:Jd,checkpointTreeSizes:dd(Bd).max(256)}).strict().superRefine((e,t)=>{BigInt(e.lastSequence)<BigInt(e.firstSequence)&&t.addIssue({code:"custom",message:"Bundle selection range is reversed"})}),fu=ld({path:Cc().min(1).max(1024),mediaType:Cc().min(1).max(256),disposition:Id(["included","redacted","disposed","unavailable","policy_excluded"]),digest:Jd.optional(),size:Bd.optional(),reasonCode:Cc().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"})}),hu=ld({schema:_d(Kd),bundleId:Cc().min(1).max(256),formatVersion:_d("1.0.0"),selections:dd(pu).min(1),exporter:Gd,purpose:Cc().min(1).max(256),exportedAt:td().int().nonnegative(),verificationPolicyDigest:Jd,inventory:dd(fu).max(1e4),integritySuite:_d(Vd)}).strict().superRefine((e,t)=>{const n=e.inventory.map(e=>e.path);new Set(n).size!==n.length&&t.addIssue({code:"custom",path:["inventory"],message:"Inventory paths must be unique"})}),gu=fu.extend({content:sd().optional()}).strict().superRefine((e,t)=>{const n=Object.prototype.hasOwnProperty.call(e,"content");if(("included"===e.disposition?!n:n)&&t.addIssue({code:"custom",path:["content"],message:"included"===e.disposition?"Included component content is required":"Excluded component content is forbidden"}),n)try{$(e.content)}catch(e){t.addIssue({code:"custom",path:["content"],message:e instanceof Error?e.message:"Content is not canonical JSON"})}}),yu=ld({manifest:ld({core:hu,manifestDigest:Jd,jws:Cc().min(1).max(qd)}).strict(),components:dd(gu)}).strict();function mu(e){return new Set(e).size===e.length}const vu=ld({signer:Gd,validFrom:td().int().nonnegative().optional(),validUntil:td().int().nonnegative().optional(),validFromCheckpoint:Jd.optional(),validUntilCheckpoint:Jd.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"})}),Iu=ld({policyId:Cc().min(1).max(256),trustedLedgerEpochs:dd(ld({ledgerId:Cc().min(1).max(256),ledgerEpochId:Cc().min(1).max(256),recorderKeys:dd(vu).min(1),validFromCheckpoint:Jd.optional(),validUntilCheckpoint:Jd.optional()}).strict()),trustedObservers:dd(vu),trustedSupportingAnchors:dd(ld({kind:Id(["worm","rfc3161","scitt"]),providerId:Cc().min(1).max(256),validFrom:td().int().nonnegative().optional(),validUntil:td().int().nonnegative().optional()}).strict()).optional(),authorizedExporters:dd(ld({signerKeys:dd(vu).min(1),allowedLedgerIds:dd(Cc().min(1).max(256)).min(1).refine(mu,"Allowed ledger IDs must be unique"),allowedPurposes:dd(Cc().min(1).max(256)).min(1).refine(mu,"Allowed purposes must be unique")}).strict()),acceptedIntegritySuites:dd(Cc().min(1).max(128)).min(1).refine(mu,"Accepted integrity suites must be unique"),acceptedAlgorithms:dd(Id(["EdDSA","ES256"])).min(1).refine(mu,"Accepted algorithms must be unique"),keyRevocationMode:Id(["as_observed","current","both"]),requiredCheckpointFreshnessMs:td().int().nonnegative().optional(),requiredAuditProfile:Id(["AAP-0","AAP-1","AAP-2","AAP-3","AAP-4"]).optional()}).strict();function wu(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 n of Object.values(e))wu(n,t);return Object.freeze(e)}function _u(e){return wu(structuredClone(e))}function Eu(e){return _u(eu.parse(e))}function bu(e){return _u(tu.parse(e))}function Su(e){return _u(ou.parse(e))}function Au(e){return _u(nu.parse(e))}function Du(e){return _u(ru.parse(e))}function ku(e){return _u(iu.parse(e))}function Tu(e){return _u(su.parse(e))}function Cu(e){return _u(hu.parse(e))}function Ou(e){return _u(yu.parse(e))}function Nu(e){return _u(Iu.parse(e))}const Ru=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 Pu(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 xu=new TextEncoder,zu=/^sha256:[a-f0-9]{64}$/;class $u{crypto;constructor(e){this.crypto=e}async sha256(e){const t=await this.crypto.hash(e);if(!zu.test(t))throw new TypeError("Audit hasher must return sha256:<lowercase-hex>");return t}}class Mu{keys;constructor(e){this.keys=e}async verify(e,t,n){try{if(!n.kid.startsWith(`${n.did}#`))return!1;const r=await this.keys.resolve(n);if(null===r)return!1;const i=await Lt(t,r,{algorithms:[n.alg]});return i.protectedHeader.alg===n.alg&&i.protectedHeader.kid===n.kid&&i.payload.length===e.length&&i.payload.every((t,n)=>t===e[n])}catch{return!1}}}class Lu{ref;privateKey;constructor(e,t){this.ref=e,this.privateKey=t}async sign(e){return new In(e).setProtectedHeader({alg:this.ref.alg,kid:this.ref.kid}).sign(this.privateKey)}}async function Uu(e,t,n){if(0===t.length||t.includes("\0"))throw new TypeError("Audit digest domain must be non-empty and cannot contain NUL");const r=xu.encode(`${t}\0`),i=L(n),o=new Uint8Array(r.length+i.length);return o.set(r),o.set(i,r.length),e.sha256(o)}function ju(e){return"evidence_ref"===e?.kind?[e.ref]:[]}function Hu(e){const t="delegation"===e.details.family?e.details.statusEvidence??[]:"ledger"===e.details.family&&void 0!==e.details.targetEvidenceRef?[e.details.targetEvidenceRef]:[];return[...ju(e.tenantRef),...ju(e.source.producer),...ju(e.session?.ref),...ju(e.actor),...ju(e.responsibleParty),...ju(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 Ku=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 Vu(e){return{refs:Hu(e)}}function Fu(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 qu(e,t){return Uu(e,Ku.event,t)}async function Bu(e,t){return Uu(e,Ku.entry,t)}async function Ju(e,t){return Uu(e,Ku.evidenceManifest,Vu(t))}const Wu={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 Gu extends Error{code;details;constructor(e,t,n,r){super(t,r),this.code=e,this.details=n,this.name="AuditProtocolError"}}class Zu{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),n=await this.config.randomBytes(16),r=await this.config.crypto.subtle.encrypt({name:"AES-GCM",iv:Xu(t),additionalData:Xu(e.aad),tagLength:128},e.key,Xu(e.plaintext)),i=new Uint8Array(r),o=await this.config.hasher.sha256(i),s=await this.config.hasher.sha256(e.aad),a={objectId:`evi_${c(n)}`,ciphertextDigest:o,...e.plaintextCommitment?{plaintextCommitment:e.plaintextCommitment}:{},mediaType:e.mediaType,size:String(i.byteLength),encryption:{suite:"A256GCM",keyId:e.keyId,nonce:c(t),aadDigest:s}};return{ref:Object.freeze(a),ciphertext:i}}async decrypt(e,t,n){if(0===n.byteLength)throw new TypeError("Evidence decryption requires entity-scoped authenticated data");const r=await this.config.hasher.sha256(e.ciphertext),i=await this.config.hasher.sha256(n);if(r!==e.ref.ciphertextDigest||i!==e.ref.encryption.aadDigest)throw new Gu(Wu.EVIDENCE_INTEGRITY,"Evidence ciphertext or authenticated metadata digest does not match");try{const r=await this.config.crypto.subtle.decrypt({name:"AES-GCM",iv:Xu(s(e.ref.encryption.nonce)),additionalData:Xu(n),tagLength:128},t,Xu(e.ciphertext));return new Uint8Array(r)}catch(e){throw new Gu(Wu.EVIDENCE_INTEGRITY,"Evidence AEAD verification failed",void 0,{cause:e})}}}class Yu{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 Gu(Wu.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 n=0;for(let r=0;r<e.byteLength;r+=1)n|=e[r]^t[r];return 0===n}(t.ciphertext,e.ciphertext))throw new Gu(Wu.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 Gu(Wu.EVIDENCE_ACCESS_DENIED,"Evidence access policy denied this actor and purpose");const n=this.states.get(e.objectId),r=void 0===n?"missing":null===n.ciphertext?"disposed":"found";return await(this.options.onAccess?.({ref:e,context:t,result:r})),null===n?.ciphertext||void 0===n?null:new Uint8Array(n.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 Gu(Wu.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 Xu(e){return Uint8Array.from(e).buffer}const Qu=/^sha256:([a-f0-9]{64})$/;function el(e){const t=Qu.exec(e);if(null===t)throw new TypeError("Expected sha256:<lowercase-hex> digest");const n=t[1],r=new Uint8Array(32);for(let e=0;e<r.length;e+=1)r[e]=Number.parseInt(n.slice(2*e,2*e+2),16);return r}function tl(...e){const t=new Uint8Array(e.reduce((e,t)=>e+t.length,0));let n=0;for(const r of e)t.set(r,n),n+=r.length;return t}function nl(e){let t=1;for(;2*t<e;)t*=2;return t}function rl(e,t){if(!Number.isSafeInteger(e)||e<0)throw new RangeError(`${t} must be a non-negative safe integer`)}class il{hasher;constructor(e){this.hasher=e}async leafHash(e){return this.hasher.sha256(tl(Uint8Array.of(0),el(e)))}async nodeHash(e,t){return this.hasher.sha256(tl(Uint8Array.of(1),el(e),el(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=nl(e.length),[n,r]=await Promise.all([this.root(e.slice(0,t)),this.root(e.slice(t))]);return this.nodeHash(n,r)}async inclusionProof(e,t){if(rl(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 n=nl(e.length);if(t<n){const[r,i]=await Promise.all([this.buildInclusionProof(e.slice(0,n),t),this.root(e.slice(n))]);return[...r,i]}const[r,i]=await Promise.all([this.buildInclusionProof(e.slice(n),t-n),this.root(e.slice(0,n))]);return[...r,i]}async verifyInclusion(e){try{if(rl(e.leafIndex,"Leaf index"),rl(e.treeSize,"Tree size"),0===e.treeSize||e.leafIndex>=e.treeSize)return!1;let t=e.leafIndex,n=e.treeSize-1,r=await this.leafHash(e.leaf);for(const i of e.auditPath){if(0===n)return!1;if(1&~t&&t!==n)r=await this.nodeHash(r,i);else for(r=await this.nodeHash(i,r);!(1&t)&&0!==t;)t=Math.floor(t/2),n=Math.floor(n/2);t=Math.floor(t/2),n=Math.floor(n/2)}return 0===n&&r===e.root}catch{return!1}}async consistencyProof(e,t){if(rl(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,n){if(e===t.length)return n?[]:[await this.root(t)];const r=nl(t.length);if(e<=r){const[i,o]=await Promise.all([this.buildConsistencyProof(e,t.slice(0,r),n),this.root(t.slice(r))]);return[...i,o]}const[i,o]=await Promise.all([this.buildConsistencyProof(e-r,t.slice(r),!1),this.root(t.slice(0,r))]);return[...i,o]}async verifyConsistency(e){try{if(rl(e.oldSize,"Old tree size"),rl(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,n=e.newSize-1;for(;!(1&~t);)t=Math.floor(t/2),n=Math.floor(n/2);let r,i,o=0;if(0===t)r=e.oldRoot,i=e.oldRoot;else{const t=e.auditPath[o++];if(void 0===t)return!1;r=t,i=t}for(;o<e.auditPath.length;o+=1){if(0===n)return!1;const s=e.auditPath[o];if(1&~t&&t!==n)i=await this.nodeHash(i,s);else for(r=await this.nodeHash(s,r),i=await this.nodeHash(s,i);!(1&t)&&0!==t;)t=Math.floor(t/2),n=Math.floor(n/2);t=Math.floor(t/2),n=Math.floor(n/2)}return 0===n&&r===e.oldRoot&&i===e.newRoot}catch{return!1}}}function ol(e){return`${e.ledgerId}\0${e.ledgerEpochId}`}function sl(e,t){return`${ol(e)}\0${t}`}function al(e,t){if(!/^(0|[1-9][0-9]*)$/.test(e))throw new Gu(Wu.CHECKPOINT_INVALID,`${t} must be a canonical non-negative decimal string`);return BigInt(e)}function cl(e,t){if(e>BigInt(Number.MAX_SAFE_INTEGER))throw new Gu(Wu.CHECKPOINT_INVALID,`${t} exceeds this implementation's safe in-memory proof range`);return Number(e)}function dl(e){if("object"!=typeof e||null===e||Object.isFrozen(e))return e;for(const t of Object.values(e))dl(t);return Object.freeze(e)}class ul{checkpoints=new Map;latest=new Map;async getLatest(e){return this.latest.get(ol(e))??null}async getByTreeSize(e,t){return this.checkpoints.get(sl(e,t))??null}async putIfAbsent(e){const t=e.core,n=sl(t,e.core.treeSize),r=this.checkpoints.get(n);if(void 0!==r)return r.checkpointDigest===e.checkpointDigest?{kind:"existing",checkpoint:r}:{kind:"conflict",checkpoint:r};const i=dl(e);this.checkpoints.set(n,i);const o=this.latest.get(ol(t));return(void 0===o||BigInt(o.core.treeSize)<BigInt(e.core.treeSize))&&this.latest.set(ol(t),i),{kind:"inserted",checkpoint:i}}}class ll{options;tree;clock;constructor(e){this.options=e,this.tree=new il(e.hasher),this.clock=e.clock??Date}async createCheckpoint(e){const t=await this.snapshotAtHead(e);if(0===t.length)throw new Gu(Wu.CHECKPOINT_INVALID,"Cannot checkpoint an empty audit epoch");const n=String(t.length),r=await this.options.store.getLatest(e);if(null!==r){const e=al(r.core.treeSize,"Previous tree size");if(e>BigInt(t.length))throw new Gu(Wu.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 Gu(Wu.CHECKPOINT_CONFLICT,"Journal content forked at the latest checkpointed tree size");return r}}const i=t[0],o=t[t.length-1],s=Du({schema:"https://schema.kya-os.org/v1/protocol/audit/checkpoint/v1.0.0",checkpointId:`checkpoint:${e.ledgerId}:${e.ledgerEpochId}:${n}`,...e,treeSize:n,firstSequence:i.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=dl({core:s,checkpointDigest:await Uu(this.options.hasher,Ku.checkpoint,s),jws:await this.options.signer.sign(L(s))}),c=await this.options.store.putIfAbsent(a);if("conflict"===c.kind)throw new Gu(Wu.CHECKPOINT_CONFLICT,"A different checkpoint already exists at this tree size",{treeSize:n});return"inserted"===c.kind&&await(this.options.onCheckpointCreated?.(c.checkpoint)),c.checkpoint}async inclusionProof(e,t,n){this.assertCheckpointLedger(e,n);const r=await this.entriesForCheckpoint(e,n),i=r.findIndex(e=>e.core.sequence===t);if(i<0)throw new Gu(Wu.CHECKPOINT_INVALID,"Sequence is not included in the checkpoint",{sequence:t,treeSize:n.core.treeSize});return dl({leafIndex:String(i),treeSize:n.core.treeSize,auditPath:await this.tree.inclusionProof(r.map(e=>e.entryDigest),i)})}async consistencyProof(e,t,n){this.assertCheckpointLedger(e,n);const r=await this.entriesForCheckpoint(e,n),i=cl(al(t,"Old tree size"),"Old tree size");return dl({oldTreeSize:t,newTreeSize:n.core.treeSize,auditPath:await this.tree.consistencyProof(r.map(e=>e.entryDigest),i)})}async rootForRange(e,t){const n=cl(al(t,"Tree size"),"Tree size");if(0===n)return this.tree.root([]);const r=await this.readEntries(e,n);if(r.length!==n)throw new Gu(Wu.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,n){return n.treeSize===t.core.treeSize&&this.tree.verifyInclusion({leaf:e,leafIndex:cl(al(n.leafIndex,"Leaf index"),"Leaf index"),treeSize:cl(al(n.treeSize,"Tree size"),"Tree size"),root:t.core.rootDigest,auditPath:n.auditPath})}async verifyConsistency(e){return e.proof.oldTreeSize===e.oldTreeSize&&e.proof.newTreeSize===e.checkpoint.core.treeSize&&this.tree.verifyConsistency({oldSize:cl(al(e.oldTreeSize,"Old tree size"),"Old tree size"),newSize:cl(al(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 n=cl(al(t.sequence,"Journal head sequence")+1n,"Journal tree size"),r=await this.readEntries(e,n),i=r[r.length-1];if(r.length!==n||i?.entryDigest!==t.entryDigest)throw new Gu(Wu.JOURNAL_FAILURE,"Journal could not provide a stable range through its reported head");return r}async entriesForCheckpoint(e,t){const n=cl(al(t.core.treeSize,"Checkpoint tree size"),"Checkpoint tree size"),r=await this.readEntries(e,n);if(r.length!==n||r[r.length-1]?.entryDigest!==t.core.headEntryDigest)throw new Gu(Wu.CHECKPOINT_INVALID,"Journal range does not match the signed checkpoint head");return r}async readEntries(e,t){const n=[];for await(const r of this.options.journal.readRange({...e,limit:t})){if(BigInt(r.core.sequence)!==BigInt(n.length))throw new Gu(Wu.JOURNAL_FAILURE,"Audit journal range is not contiguous from sequence zero");n.push(r)}return n}assertCheckpointLedger(e,t){if(t.core.ledgerId!==e.ledgerId||t.core.ledgerEpochId!==e.ledgerEpochId)throw new Gu(Wu.LEDGER_MISMATCH,"Checkpoint belongs to a different ledger or epoch")}}class pl{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 Gu(Wu.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 Gu(Wu.INVALID_CONFIGURATION,"Minimum checkpoint observers must be a non-negative safe integer")}async createAndPublish(e){const t=await this.options.checkpoints.createCheckpoint(e),n=[],r=[],i=[];await Promise.all(this.observers.map(async(e,r)=>{const o=await this.publishWithRetry("observer",r,()=>e.publish(t));o.ok?n.push(o.value):i.push(o.failure)})),await Promise.all(this.anchors.map(async(e,n)=>{const o=await this.publishWithRetry("anchor",n,()=>e.publish(t),e.kind);o.ok?r.push(o.value):i.push(o.failure)})),n.sort((e,t)=>e.core.observerId.localeCompare(t.core.observerId)),r.sort((e,t)=>e.kind.localeCompare(t.kind)||e.providerId.localeCompare(t.providerId)),i.sort((e,t)=>e.role.localeCompare(t.role)||e.providerIndex-t.providerIndex);const o={checkpoint:t,observations:n,anchors:r,failures:i};return this.assertRequirements(o),await(this.options.onPublished?.(o)),o}async publishWithRetry(e,t,n,r){let i;for(let o=1;o<=this.maxAttempts;o+=1)try{return{ok:!0,value:await n()}}catch(n){if(i=n,o<this.maxAttempts)try{await(this.options.backoff?.({role:e,providerIndex:t,attempt:o,error:n}))}catch(i){return{ok:!1,failure:{role:e,providerIndex:t,...void 0===r?{}:{kind:r},attempts:o,error:new AggregateError([n,i],"Checkpoint publication backoff failed")}}}}return{ok:!1,failure:{role:e,providerIndex:t,...void 0===r?{}:{kind:r},attempts:this.maxAttempts,error:i}}}assertRequirements(e){const t=this.options.requirements;if(void 0===t)return;const n=[...new Set(t.requiredAnchorKinds)].filter(t=>!e.anchors.some(e=>e.kind===t));if(e.observations.length<t.minimumObservers||n.length>0)throw new Gu(Wu.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:n,failedProviders:e.failures.map(({role:e,providerIndex:t,kind:n,attempts:r})=>({role:e,providerIndex:t,...void 0===n?{}:{kind:n},attempts:r}))})}}function fl(e,t){return`${e}\0${t.ledgerId}\0${t.ledgerEpochId}`}function hl(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 gl{capabilities={durability:"ephemeral",atomicOffset:!0};offsets=new Map;records=new Map;async getOffset(e,t){const n=this.offsets.get(fl(e,t));return void 0===n?null:{...n}}async compareAndApply(e){const t=fl(e.projectionId,e.ledger),n=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:n};if(i=n,o=e.expectedOffset,!(null===i||null===o?i===o:i.sequence===o.sequence&&i.entryDigest===o.entryDigest))return{kind:"conflict",actualOffset:n};var i,o;const s=null===n?0n:BigInt(n.sequence)+1n;if(BigInt(e.entry.core.sequence)!==s)return{kind:"conflict",actualOffset:n};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 n=fl(e,t);this.offsets.delete(n),this.records.delete(n)}async read(e,t){return(this.records.get(fl(e,t))??[]).map(e=>({...e}))}corruptOffsetForTesting(e,t,n){this.offsets.set(fl(e,t),{...n})}}class yl{options;constructor(e){if(this.options=e,!e.projectionId)throw new Gu(Wu.INVALID_CONFIGURATION,"Projection ID is required")}async synchronize(e){let t=await this.options.projections.getOffset(this.options.projectionId,e),n=0,r=0;for await(const i 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:i,record:hl(i)});if("conflict"===o.kind)throw new Gu(Wu.PROJECTION_CONFLICT,"Projection offset conflicted with the ordered ledger",{sequence:i.core.sequence,expectedOffset:t,actualOffset:o.actualOffset});"applied"===o.kind?n+=1:r+=1,t={sequence:i.core.sequence,entryDigest:i.entryDigest}}return{applied:n,duplicates:r}}async rebuild(e){return await this.options.projections.reset(this.options.projectionId,e),this.synchronize(e)}async reconcile(e){const[t,n]=await Promise.all([this.options.journal.getHead(e),this.options.projections.getOffset(this.options.projectionId,e)]);let r;return r=null===t&&null===n?"empty":null!==t&&null===n?"pending":null===t||null===n?"gap_detected":t.sequence===n.sequence?t.entryDigest===n.entryDigest?"verified":"gap_detected":BigInt(n.sequence)<BigInt(t.sequence)?"pending":"gap_detected",{status:r,journalHead:t,projectionHead:n}}}const ml=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 vl(e,t=[]){return{verdict:e,reasonCodes:[...new Set(t)].sort()}}function Il(e,t){return e.did===t.did&&e.kid===t.kid&&e.alg===t.alg}function wl(e,t){return(void 0===e.validFrom||t>=e.validFrom)&&(void 0===e.validUntil||t<=e.validUntil)}class _l{options;constructor(e){this.options=e}async verifyEntries(e,t){if(!Iu.safeParse(t).success)return function(e){const t="object"==typeof e&&null!==e&&"string"==typeof e.policyId?e.policyId:"invalid-policy",n=vl("invalid",[ml.VERIFICATION_POLICY_INVALID]);return{schema:"https://schema.kya-os.org/v1/protocol/audit/verification-report/v1.0.0",policyId:t,cryptographicIntegrity:n,chainIntegrity:n,checkpointIntegrity:n,anchorIntegrity:n,scopeEvidenceCompleteness:n,authorizedAsObserved:vl("indeterminate",[ml.NOT_EVALUATED]),currentAuthorization:vl("indeterminate",[ml.NOT_EVALUATED])}}(t);const n=t,r=new Set,i=new Set,o=[];0===e.length&&i.add(ml.BUNDLE_SELECTION_INCOMPLETE);for(const t of e){const e=ou.safeParse(t);if(!e.success){r.add(ml.SCHEMA_INVALID),i.add(ml.SCHEMA_INVALID);continue}const s=e.data,a=o.length;await this.verifyEntry(s,n,r),this.verifyChainPosition(s,o[a-1],a,i),o.push(s)}const s=o.some(e=>void 0!==e.core.event.authorization),[a,c]=void 0===this.options.authorization?[vl("indeterminate",[s?ml.AUTHORIZATION_COLLATERAL_NOT_VERIFIED:ml.AUTHORIZATION_EVIDENCE_MISSING]),vl("indeterminate",[ml.CURRENT_AUTHORIZATION_NOT_EVALUATED])]:await Promise.all([this.options.authorization.verifyAsObserved(o,n),this.options.authorization.verifyCurrent(o,n)]);return{schema:"https://schema.kya-os.org/v1/protocol/audit/verification-report/v1.0.0",policyId:n.policyId,...void 0===this.options.verifiedAt?{}:{verifiedAt:this.options.verifiedAt()},cryptographicIntegrity:vl(0===r.size&&e.length>0?"valid":"invalid",r),chainIntegrity:vl(0===i.size&&e.length>0?"valid":"invalid",i),checkpointIntegrity:vl("indeterminate",[ml.CHECKPOINT_MISSING]),anchorIntegrity:vl("indeterminate",[ml.OBSERVER_EVIDENCE_MISSING]),scopeEvidenceCompleteness:vl(e.length>0?"indeterminate":"invalid",[ml.NOT_EVALUATED]),authorizedAsObserved:a,currentAuthorization:c}}async verifyCheckpoint(e,t,n){const r=new Set;if(!Iu.safeParse(n).success)return vl("invalid",[ml.VERIFICATION_POLICY_INVALID]);const i=iu.safeParse(e);if(!i.success)return vl("invalid",[ml.SCHEMA_INVALID]);const o=i.data,s=o.core;n.acceptedIntegritySuites.includes(s.integritySuite)||r.add(ml.UNSUPPORTED_SUITE),n.acceptedAlgorithms.includes(s.issuer.alg)||r.add(ml.UNSUPPORTED_ALGORITHM);const a=n.trustedLedgerEpochs.find(e=>e.ledgerId===s.ledgerId&&e.ledgerEpochId===s.ledgerEpochId);a?.recorderKeys.some(e=>Il(e.signer,s.issuer)&&wl(e,s.createdAt))||r.add(ml.UNTRUSTED_RECORDER),await Uu(this.options.hasher,Ku.checkpoint,s)!==o.checkpointDigest&&r.add(ml.CHECKPOINT_DIGEST_MISMATCH),await this.options.signatures.verify(L(s),o.jws,s.issuer)||r.add(ml.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(ml.CHECKPOINT_RANGE_MISMATCH):await new il(this.options.hasher).root(t.map(e=>e.entryDigest))!==s.rootDigest&&r.add(ml.CHECKPOINT_ROOT_MISMATCH),vl(0===r.size?"valid":"invalid",r)}async verifyObservation(e,t,n){const r=new Set;let i=!1;if(!Iu.safeParse(n).success)return vl("invalid",[ml.VERIFICATION_POLICY_INVALID]);const o=iu.safeParse(e),s=su.safeParse(t);if(!o.success||!s.success)return vl("invalid",[ml.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(ml.SCHEMA_INVALID),d.ledgerId===a.core.ledgerId&&d.ledgerEpochId===a.core.ledgerEpochId&&d.checkpointDigest===a.checkpointDigest&&d.treeSize===a.core.treeSize||r.add(ml.OBSERVATION_SCOPE_MISMATCH),n.acceptedAlgorithms.includes(d.observer.alg)||r.add(ml.UNSUPPORTED_ALGORITHM),n.trustedObservers.some(e=>Il(e.signer,d.observer)&&wl(e,d.observedAt))||r.add(ml.UNTRUSTED_OBSERVER),void 0!==n.requiredCheckpointFreshnessMs){const e=this.options.verifiedAt?.();void 0===e?(r.add(ml.NOT_EVALUATED),i=!0):e-d.observedAt>n.requiredCheckpointFreshnessMs&&r.add(ml.OBSERVATION_STALE)}await Uu(this.options.hasher,Ku.observation,d)!==c.observationDigest&&r.add(ml.OBSERVATION_DIGEST_MISMATCH),await this.options.signatures.verify(L(d),c.jws,d.observer)||r.add(ml.OBSERVATION_SIGNATURE_INVALID);const u=i&&[...r].every(e=>e===ml.NOT_EVALUATED);return vl(0===r.size?"valid":u?"indeterminate":"invalid",r)}async verifyEntry(e,t,n){t.acceptedIntegritySuites.includes(e.core.integritySuite)||n.add(ml.UNSUPPORTED_SUITE),t.acceptedAlgorithms.includes(e.core.recorder.alg)||n.add(ml.UNSUPPORTED_ALGORITHM);const r=t.trustedLedgerEpochs.find(t=>t.ledgerId===e.core.ledgerId&&t.ledgerEpochId===e.core.ledgerEpochId),i=r?.recorderKeys.find(t=>Il(t.signer,e.core.recorder)&&wl(t,e.core.recordedAt));void 0===i&&n.add(ml.UNTRUSTED_RECORDER);const o=await qu(this.options.hasher,e.core.event);o===e.core.eventDigest&&o===e.eventDigest||n.add(ml.EVENT_DIGEST_MISMATCH),await Ju(this.options.hasher,e.core.event)!==e.core.evidenceManifestDigest&&n.add(ml.EVIDENCE_MANIFEST_DIGEST_MISMATCH),await Bu(this.options.hasher,e.core)!==e.entryDigest&&n.add(ml.ENTRY_DIGEST_MISMATCH),function(e,t){try{return M(e)===M(t)}catch{return!1}}(Fu(e.core,e.entryDigest),e.recorderReceipt.core)||n.add(ml.RECEIPT_MISMATCH),await this.options.signatures.verify(L(e.recorderReceipt.core),e.recorderReceipt.jws,e.core.recorder)||n.add(ml.SIGNATURE_INVALID)}verifyChainPosition(e,t,n,r){if(void 0!==t){e.core.ledgerId===t.core.ledgerId&&e.core.ledgerEpochId===t.core.ledgerEpochId||r.add(ml.LEDGER_SCOPE_MISMATCH);try{BigInt(e.core.sequence)!==BigInt(t.core.sequence)+1n&&r.add(ml.SEQUENCE_GAP)}catch{r.add(ml.SEQUENCE_GAP)}e.core.previousEntryDigest!==t.entryDigest&&r.add(ml.PREDECESSOR_MISMATCH)}else"0"===e.core.sequence?null===e.core.previousEntryDigest&&"ledger.epoch.started"===e.core.event.eventType||r.add(ml.GENESIS_INVALID):0===n&&null===e.core.previousEntryDigest&&r.add(ml.PREDECESSOR_MISMATCH)}}function El(...e){return 0===e.length?vl("indeterminate",[ml.NOT_EVALUATED]):vl(e.some(e=>"invalid"===e.verdict)?"invalid":e.every(e=>"valid"===e.verdict)?"valid":"indeterminate",e.flatMap(e=>e.reasonCodes))}const bl="https://schema.kya-os.org/v1/protocol/audit/bundle-manifest/v1.0.0",Sl=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 Al(e){if("object"!=typeof e||null===e||Object.isFrozen(e))return e;for(const t of Object.values(e))Al(t);return Object.freeze(e)}function Dl(e){return JSON.parse(M(e))}function kl(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 Tl(e,t){return(void 0===e.validFrom||t>=e.validFrom)&&(void 0===e.validUntil||t<=e.validUntil)}function Cl(e,t=[]){return{verdict:e,reasonCodes:[...new Set(t)].sort()}}class Ol{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,n=[...e.components].sort((e,t)=>e.path.localeCompare(t.path)),r=[];for(const e of n){if(kl(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=Dl(e.content),n=L(t);r.push({path:e.path,mediaType:e.mediaType,disposition:"included",digest:await this.options.hasher.sha256(n),size:String(n.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 i=r.map(e=>Nl(e)),o=Cu({schema:bl,bundleId:e.bundleId,formatVersion:"1.0.0",selections:Dl([...e.selections]),exporter:this.options.signer.ref,purpose:e.purpose,exportedAt:this.options.clock.now(),verificationPolicyDigest:e.verificationPolicyDigest,inventory:i,integritySuite:"KYA-AUDIT-BUNDLE-JCS-SHA256-JWS-2026"});return Al({manifest:{core:o,manifestDigest:await Uu(this.options.hasher,Ku.bundleManifest,o),jws:await this.options.signer.sign(L(o))},components:r})}}function Nl(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 Rl(e,t){const n=[];for(const r of e.components)"included"===r.disposition&&r.mediaType===t&&Array.isArray(r.content)&&n.push(...r.content);return n}function Pl(e){return`${e.ledgerId}\0${e.ledgerEpochId}`}function xl(e,t){const n=BigInt(e),r=BigInt(t);return n<r?-1:n>r?1:0}function zl(e,t,n){const r=new Set;for(const n of e){const e=t.filter(e=>e.core.ledgerId===n.ledgerId&&e.core.ledgerEpochId===n.ledgerEpochId),i=new Map;let o=!1;for(const t of e)i.has(t.core.sequence)?o=!0:i.set(t.core.sequence,t);const s=[...i.values()].sort((e,t)=>{const n=BigInt(e.core.sequence),r=BigInt(t.core.sequence);return n<r?-1:n>r?1:0});let a;try{a=BigInt(n.lastSequence)-BigInt(n.firstSequence)+1n}catch{r.add(ml.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!==n.firstSequence||s[s.length-1]?.core.sequence!==n.lastSequence||s[s.length-1]?.entryDigest!==n.expectedHeadDigest)&&r.add(ml.BUNDLE_SELECTION_INCOMPLETE)}for(const e of n)"redacted"===e.disposition&&r.add(ml.EXPLICITLY_REDACTED),"disposed"===e.disposition&&r.add(ml.EXPLICITLY_DISPOSED),"unavailable"===e.disposition&&r.add(ml.EXPLICITLY_UNAVAILABLE);return r.has(ml.BUNDLE_SELECTION_INCOMPLETE)?Cl("invalid",r):0===r.size?Cl("valid"):Cl("indeterminate",r)}async function $l(e,t,n){if(!Iu.safeParse(t).success){const e="string"==typeof t?.policyId?t.policyId:"invalid-policy",n=Cl("invalid",[ml.VERIFICATION_POLICY_INVALID]);return{schema:"https://schema.kya-os.org/v1/protocol/audit/verification-report/v1.0.0",policyId:e,cryptographicIntegrity:n,chainIntegrity:n,checkpointIntegrity:n,anchorIntegrity:n,scopeEvidenceCompleteness:n,authorizedAsObserved:Cl("indeterminate",[ml.NOT_EVALUATED]),currentAuthorization:Cl("indeterminate",[ml.NOT_EVALUATED])}}if(!yu.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:Cl("invalid",[ml.BUNDLE_SCHEMA_INVALID]),chainIntegrity:Cl("invalid",[ml.BUNDLE_SCHEMA_INVALID]),checkpointIntegrity:Cl("indeterminate",[ml.CHECKPOINT_MISSING]),anchorIntegrity:Cl("indeterminate",[ml.OBSERVER_EVIDENCE_MISSING]),scopeEvidenceCompleteness:Cl("invalid",[ml.BUNDLE_SCHEMA_INVALID]),authorizedAsObserved:Cl("indeterminate",[ml.AUTHORIZATION_COLLATERAL_NOT_VERIFIED]),currentAuthorization:Cl("indeterminate",[ml.CURRENT_AUTHORIZATION_NOT_EVALUATED])}}(t);const r=e,i=new Set,o=r.manifest.core;if(o?.schema===bl&&"1.0.0"===o.formatVersion||i.add(ml.BUNDLE_SCHEMA_INVALID),t.acceptedIntegritySuites.includes(o?.integritySuite??"")||i.add(ml.UNSUPPORTED_SUITE),void 0!==o&&t.acceptedAlgorithms.includes(o.exporter.alg)||i.add(ml.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 n=t.signer,r=e.exporter,n.did===r.did&&n.kid===r.kid&&n.alg===r.alg&&Tl(t,e.exportedAt);var n,r}))}(o,t)||i.add(ml.BUNDLE_EXPORTER_UNAUTHORIZED),void 0!==o){const[e,s]=await Promise.all([Uu(n.hasher,Ku.bundleManifest,o),Uu(n.hasher,"org.kya-os.audit.verification-policy.v1",t)]);e!==r.manifest.manifestDigest&&i.add(ml.BUNDLE_MANIFEST_DIGEST_MISMATCH),s!==o.verificationPolicyDigest&&i.add(ml.VERIFICATION_POLICY_MISMATCH),await n.signatures.verify(L(o),r.manifest.jws,o.exporter)||i.add(ml.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||i.add(ml.BUNDLE_INVENTORY_MISMATCH);for(const[e,t]of a){const r=c.get(e);if(void 0!==r&&M(t)===M(Nl(r))){try{kl(e)}catch{i.add(ml.BUNDLE_SCHEMA_INVALID)}if("included"===r.disposition){if(void 0===r.content){i.add(ml.BUNDLE_INVENTORY_MISMATCH);continue}const e=L(r.content);r.size===String(e.length)&&r.digest===await n.hasher.sha256(e)||i.add(ml.BUNDLE_COMPONENT_DIGEST_MISMATCH)}else void 0===r.content&&void 0!==r.reasonCode||i.add(ml.BUNDLE_INVENTORY_MISMATCH)}else i.add(ml.BUNDLE_INVENTORY_MISMATCH)}}const s=Rl(r,Sl.entries),a=Rl(r,Sl.checkpoints),c=Rl(r,Sl.observations),d=Rl(r,Sl.anchors),u=n.artifacts??new _l(n),l=await async function(e,t,n){const r=new Map,i=[];for(const t of e){if(!ou.safeParse(t).success){i.push(t);continue}const e=t,n=Pl(e.core),o=r.get(n)??[];o.push(e),r.set(n,o)}const o=await Promise.all([...[...r.values()].map(e=>n.verifyEntries(e,t)),...0===i.length?[]:[n.verifyEntries(i,t)]]);return 0===o.length?n.verifyEntries([],t):{...o[0],cryptographicIntegrity:El(...o.map(e=>e.cryptographicIntegrity)),chainIntegrity:El(...o.map(e=>e.chainIntegrity)),checkpointIntegrity:El(...o.map(e=>e.checkpointIntegrity)),anchorIntegrity:El(...o.map(e=>e.anchorIntegrity)),scopeEvidenceCompleteness:El(...o.map(e=>e.scopeEvidenceCompleteness)),authorizedAsObserved:El(...o.map(e=>e.authorizedAsObserved)),currentAuthorization:El(...o.map(e=>e.currentAuthorization))}}(s,t,u),p=s.filter(e=>ou.safeParse(e).success),f=a.filter(e=>iu.safeParse(e).success);let h=l.checkpointIntegrity;if(a.length>0){const e=[];for(const n of a){if(!iu.safeParse(n).success){e.push(Cl("invalid",[ml.SCHEMA_INVALID]));continue}const r=n,i=p.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,i,t))}h=El(...e,function(e,t,n){const r=new Set,i=new Map;for(const t of e){const e=Pl(t.core),n=i.get(e)??[];n.push(t),i.set(e,n)}for(const e of i.values()){e.sort((e,t)=>{const n=BigInt(e.core.treeSize),r=BigInt(t.core.treeSize);return n<r?-1:n>r?1:0});for(let t=1;t<e.length;t+=1){const n=e[t-1],i=e[t];i.core.treeSize===n.core.treeSize?r.add(ml.CHECKPOINT_FORK_DETECTED):i.core.previousCheckpointDigest!==n.checkpointDigest&&r.add(ml.CHECKPOINT_CHAIN_MISMATCH)}}for(const e of n){const t=(i.get(Pl(e))??[]).map(e=>e.core.treeSize).sort(xl),n=[...e.checkpointTreeSizes].sort(xl);M(t)!==M(n)&&r.add(ml.CHECKPOINT_MISSING)}for(const i of t){if("0"!==i.core.sequence||"ledger.epoch.started"!==i.core.event.eventType||"ledger"!==i.core.event.details.family)continue;const t=i.core.event.details;void 0!==t.previousEpochId&&void 0!==t.previousTerminalCheckpointDigest&&n.some(e=>e.ledgerId===i.core.ledgerId&&e.ledgerEpochId===t.previousEpochId)&&!e.some(e=>e.core.ledgerId===i.core.ledgerId&&e.core.ledgerEpochId===t.previousEpochId&&e.checkpointDigest===t.previousTerminalCheckpointDigest)&&r.add(ml.CHECKPOINT_CHAIN_MISMATCH)}return Cl(0===r.size?"valid":"invalid",r)}(f,p,o.selections),await async function(e,t,n,r){const i=new Set,o=new il(r),s=Rl(e,Sl.inclusionProofs);for(const e of s){if(!uu.safeParse(e).success){i.add(ml.SCHEMA_INVALID);continue}const r=e,s=n.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})||i.add(ml.MERKLE_PROOF_INVALID)}const a=Rl(e,Sl.consistencyProofs);for(const e of a){if(!lu.safeParse(e).success){i.add(ml.SCHEMA_INVALID);continue}const t=e,r=n.find(e=>e.checkpointDigest===t.oldCheckpointDigest&&e.core.ledgerId===t.ledgerId&&e.core.ledgerEpochId===t.ledgerEpochId),s=n.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})||i.add(ml.MERKLE_PROOF_INVALID)}return Cl(0===i.size?"valid":"invalid",i)}(r,p,f,n.hasher))}else o.selections.some(e=>e.checkpointTreeSizes.length>0)&&(h=Cl("invalid",[ml.CHECKPOINT_MISSING]));let g=l.anchorIntegrity;if(c.length>0){const e=[];for(const n of c){if(!su.safeParse(n).success){e.push(Cl("invalid",[ml.SCHEMA_INVALID]));continue}const r=n,i=f.find(e=>e.checkpointDigest===r.core.checkpointDigest);e.push(void 0===i?Cl("invalid",[ml.OBSERVATION_SCOPE_MISMATCH]):await u.verifyObservation(i,r,t))}const n=c.filter(e=>su.safeParse(e).success);g=El(...e,function(e){const t=new Set,n=new Map;for(const t of e){const e=`${Pl(t.core)}\0${t.core.observerId}`,r=n.get(e)??[];r.push(t),n.set(e,r)}for(const e of n.values()){e.sort((e,t)=>e.core.observedAt-t.core.observedAt||xl(e.core.treeSize,t.core.treeSize));for(let n=1;n<e.length;n+=1)e[n].core.previousObservationDigest!==e[n-1].observationDigest&&t.add(ml.OBSERVATION_CHAIN_MISMATCH)}return Cl(0===t.size?"valid":"invalid",t)}(n))}d.length>0&&(g=El(g,await async function(e,t,n,r){const i=new Set;let o=!1;for(const s of e){if(!au.safeParse(s).success){i.add(ml.SCHEMA_INVALID);continue}const e=s,a=t.find(t=>t.checkpointDigest===e.checkpointDigest);(n.trustedSupportingAnchors?.some(t=>t.kind===e.kind&&t.providerId===e.providerId&&Tl(t,e.issuedAt))??!1)||i.add(ml.UNTRUSTED_SUPPORTING_ANCHOR),void 0===a?i.add(ml.SUPPORTING_ANCHOR_INVALID):void 0===r?(i.add(ml.NOT_EVALUATED),o=!0):await r(a,e)||i.add(ml.SUPPORTING_ANCHOR_INVALID)}return Cl([...i].some(e=>e!==ml.NOT_EVALUATED)?"invalid":o?"indeterminate":"valid",i)}(d,f,t,n.verifySupportingAnchor)));const y=Cl(0===i.size?"valid":"invalid",i);return{...l,cryptographicIntegrity:El(y,l.cryptographicIntegrity),checkpointIntegrity:h,anchorIntegrity:g,scopeEvidenceCompleteness:zl(o?.selections??[],p,r.components.filter(e=>"included"!==e.disposition))}}class Ml{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 Gu(Wu.INVALID_CONFIGURATION,"Buffered audit delivery requires a durable outbox provider");if(void 0!==e.capabilities){if(e.capabilities.delivery!==e.delivery)throw new Gu(Wu.INVALID_CONFIGURATION,"Advertised audit delivery does not match the trail delivery mode");if(Pu(e.capabilities),e.capabilities.sourceHighWater&&"durable"!==e.sourceState.capabilities.durability)throw new Gu(Wu.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 n=e.eventId??this.nextEventId(),r=t.encryptedEvidence??[],i="buffered"===this.configuration.delivery,{event:o,submission:s}=await this.withSourceConstruction(async()=>{const t=await this.buildAndLinkEvent(e,n);this.assertEvidenceIsReferenced(t,r);const o=Object.freeze({ledgerId:this.configuration.ledgerId,...i||void 0===this.configuration.expectedLedgerEpochId?{}:{expectedLedgerEpochId:this.configuration.expectedLedgerEpochId},producerEvent:t,encryptedEvidence:Object.freeze([...r])});return i&&await this.configuration.outbox.enqueue(Object.freeze({eventId:t.eventId,submission:o,enqueuedAt:this.configuration.clock.now(),attempts:0})),{event:t,submission:o}});if(i)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,n=0;const r=new Set;for await(const i of this.configuration.outbox.pending(e)){const e=i.submission.producerEvent.source.sourceId;if(!r.has(e))try{const n=await this.submitAndValidate(i.submission);try{await this.sourceState.markReceipted(e,i.submission.producerEvent.source.sourceSequence,n.entryDigest)}catch(e){this.configuration.onSourceStateFailure?.(e,i.submission.producerEvent)}await this.configuration.outbox.markDelivered(i.eventId),t+=1}catch(t){await this.configuration.outbox.markFailed(i.eventId,t),this.configuration.onDeliveryFailure?.(t,i.submission.producerEvent),r.add(e),n+=1}}return{delivered:t,failed:n}}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 n;this.sourceConstructionTail=new Promise(e=>{n=e}),await t;try{return await e()}finally{n()}}async buildAndLinkEvent(e,t){const n=await this.sourceState.claimEvent(this.configuration.sourceId,t),r=this.buildEvent(e,t,n),i=await qu(this.configuration.hasher,r);return await this.sourceState.markEmitted(this.configuration.sourceId,t,n.sequence,i),r}buildEvent(e,t,n){return Eu({...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:n.sequence,...void 0===n.previousSourceEventDigest?{}:{previousSourceEventDigest:n.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 n=new Map(Hu(e).map(e=>[e.objectId,e])),r=new Set;for(const e of t){const t=n.get(e.ref.objectId);if(r.has(e.ref.objectId)||void 0===t||M(t)!==M(e.ref))throw new Gu(Wu.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),n=await qu(this.configuration.hasher,e.producerEvent);if(t.core.ledgerId!==e.ledgerId||t.eventDigest!==n||t.core.eventDigest!==n||M(t.core.event)!==M(e.producerEvent))throw new Gu(Wu.JOURNAL_FAILURE,"Recorder response does not bind the submitted frozen producer event");return t}}function Ll(e){return new Ml(e)}class Ul{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 Gu(Wu.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 Gu(Wu.MIRROR_VERIFICATION_FAILED,"Mirror rejected an entry that failed historical artifact verification",{reasonCodes:t.cryptographicIntegrity.reasonCodes});const n=await Uu(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,n);if(null!==r)return r.entryDigest!==e.entryDigest&&this.continuityFailure(),r;const i=await this.options.journal.getHead(this.options.ledger),o=BigInt(e.core.sequence);if(null===i&&o>0n||null!==i&&o>BigInt(i.sequence)+1n)throw new Gu(Wu.MIRROR_OUT_OF_ORDER,"Mirror entry arrived before its predecessor and may be retried",{sequence:e.core.sequence,observedHeadSequence:i?.sequence??null});(null===i?"0"===e.core.sequence&&null===e.core.previousEntryDigest:o===BigInt(i.sequence)+1n&&e.core.previousEntryDigest===i.entryDigest)||this.continuityFailure();const s=await this.options.journal.compareAndAppend({ledger:this.options.ledger,expectedHead:i,entry:e,idempotencyKey:n});if("appended"===s.kind||"duplicate"===s.kind)return s.entry;const a=await this.options.journal.getByIdempotencyKey(e.core.ledgerId,n);if(a?.entryDigest===e.entryDigest)return a;this.continuityFailure()}continuityFailure(){throw new Gu(Wu.MIRROR_CONTINUITY_FAILED,"Mirror entry does not exactly extend the observed recorder chain")}}function jl(e){if("object"!=typeof e||null===e||Object.isFrozen(e))return e;for(const t of Object.values(e))jl(t);return Object.freeze(e)}function Hl(e,t){return null===e||null===t?e===t:e.entryDigest===t.entryDigest&&e.sequence===t.sequence}function Kl(e,t){return M(e)===M(t)}function Vl(e,t,n){return void 0!==t?Kl(t,n):("public_did"===n.kind||"pairwise_did"===n.kind)&&n.did===e}class Fl{config;maxAppendConflicts;initialization;constructor(e){if(this.config=e,void 0===e.previousEpochId!=(void 0===e.previousTerminalCheckpointDigest))throw new Gu(Wu.INVALID_CONFIGURATION,"Previous epoch ID and terminal checkpoint digest must be supplied together");if(void 0!==e.previousEpochId&&void 0===e.epochTransitionGuard)throw new Gu(Wu.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 n=Eu(e.producerEvent);if(this.validateEventAuthority(n,t),void 0!==this.config.authorizer&&!await this.config.authorizer.authorize({submission:e,context:t}))throw new Gu(Wu.UNAUTHORIZED_SUBMISSION,"Audit producer is not authorized for this ledger");const r=await this.identifyEvent(n,t),i=await this.config.journal.getByIdempotencyKey(this.config.ledgerId,r.idempotencyKey);if(null!==i)return this.resolveDuplicate(i,r.eventDigest);if(void 0!==e.expectedLedgerEpochId&&e.expectedLedgerEpochId!==this.config.ledgerEpochId)throw new Gu(Wu.EPOCH_MISMATCH,"Wrong audit ledger epoch");await this.ensureInitialized(),await this.persistSubmittedEvidence(e.encryptedEvidence,n);try{return await this.appendEvent(n,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 Gu(Wu.UNAUTHORIZED_SUBMISSION,"Authenticated producer and tenant authority are required");if(e.ledgerId!==this.config.ledgerId)throw new Gu(Wu.LEDGER_MISMATCH,"Wrong audit ledger")}validateEventAuthority(e,t){if(!Vl(t.producerAuthority,t.producerRef,e.source.producer))throw new Gu(Wu.UNAUTHORIZED_SUBMISSION,"Event producer does not match the authenticated producer authority");if(!Kl(e.tenantRef,this.config.tenantRef)||!Vl(t.tenantAuthority,t.tenantRef,e.tenantRef))throw new Gu(Wu.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 Gu(Wu.EVIDENCE_FAILURE,"Encrypted evidence was submitted but no evidence provider is configured");try{const n=new Map(Hu(t).map(e=>[e.objectId,e])),r=new Set;for(const t of e){const e=n.get(t.ref.objectId);if(r.has(t.ref.objectId)||void 0===e||M(e)!==M(t.ref))throw new Gu(Wu.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 Gu&&e.code===Wu.EVIDENCE_FAILURE)throw e;throw new Gu(Wu.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 Gu(Wu.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 Gu(Wu.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=Su(e),i=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,n=this.config.signer.ref,t.did!==n.did||t.kid!==n.kid||t.alg!==n.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||!Kl(r.core.event.tenantRef,this.config.tenantRef)||"ledger"!==i.family||"epoch_started"!==i.phase||i.previousEpochId!==this.config.previousEpochId||i.previousTerminalCheckpointDigest!==this.config.previousTerminalCheckpointDigest)throw new Error("Genesis does not match recorder epoch configuration");return r}catch(e){throw new Gu(Wu.JOURNAL_FAILURE,"Existing ledger genesis does not match the authoritative recorder configuration",void 0,{cause:e})}var t,n}genesisEvent(){return Eu({schema:$d,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,n=!1,r){const{eventDigest:i,idempotencyKey:o}=r??await this.identifyEvent(e,t),s=await this.config.journal.getByIdempotencyKey(this.config.ledgerId,o);if(null!==s)return n?this.validateExistingGenesis(s):this.resolveDuplicate(s,i);const a=this.ledgerRef();for(let t=0;t<=this.maxAppendConflicts;t+=1){const t=await this.config.journal.getHead(a);if(n&&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,i,t,n);let s;try{s=await this.config.journal.compareAndAppend({ledger:a,expectedHead:t,entry:r,idempotencyKey:o})}catch(e){throw new Gu(Wu.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,i):s.entry;if("idempotency_conflict"===s.kind)return this.resolveDuplicate(s.existing,i);if(Hl(t,s.actualHead))throw new Gu(Wu.JOURNAL_FAILURE,"Audit journal reported a head conflict without advancing its head")}throw new Gu(Wu.APPEND_CONFLICT_EXHAUSTED,"Audit append conflict retry budget exhausted")}async identifyEvent(e,t){return{eventDigest:await qu(this.config.hasher,e),idempotencyKey:await Uu(this.config.hasher,Ku.idempotency,{ledgerId:this.config.ledgerId,producerAuthority:t.producerAuthority,sourceId:e.source.sourceId,eventId:e.eventId})}}resolveDuplicate(e,t){if(e.eventDigest!==t)throw new Gu(Wu.EVENT_ID_CONFLICT,"Authenticated producer event identity was reused with different content",{eventId:e.core.event.eventId});return e}async buildCandidate(e,t,n,r){const i=null===n?"0":(BigInt(n.sequence)+1n).toString();if(r!==("0"===i))throw new Gu(Wu.JOURNAL_FAILURE,r?"Genesis must be the first epoch entry":"Producer event cannot replace genesis");const o=this.config.clock.now(),s=await Ju(this.config.hasher,e),a=bu({schema:Md,ledgerId:this.config.ledgerId,ledgerEpochId:this.config.ledgerEpochId,sequence:i,previousEntryDigest:n?.entryDigest??null,recordedAt:o,recorder:this.config.signer.ref,eventDigest:t,event:e,evidenceManifestDigest:s,integritySuite:Ud}),c=await Bu(this.config.hasher,a),d=Fu(a,c);return jl({core:a,eventDigest:t,entryDigest:c,recorderReceipt:{core:d,jws:await this.config.signer.sign(L(d))}})}ledgerRef(){return{ledgerId:this.config.ledgerId,ledgerEpochId:this.config.ledgerEpochId}}}const ql=100,Bl=1e3;function Jl(e){return{ledgerId:e.ledgerId,ledgerEpochId:e.ledgerEpochId}}class Wl{journal;checkpoints;constructor(e){this.journal=e.journal,this.checkpoints=e.checkpoints}getHead(e){return this.journal.getHead(Jl(e))}async listEntries(e){const t=function(e){return void 0!==e&&Number.isFinite(e)?Math.max(1,Math.min(Bl,Math.trunc(e))):ql}(e.limit),n=Jl(e),r=[];for await(const i of this.journal.readRange({...n,...void 0===e.afterSequence?{}:{afterSequence:e.afterSequence},limit:t+1}))if(r.push(i),r.length>t)break;const i=r.length>t,o=i?r.slice(0,t):r,s=i?o[o.length-1].core.sequence:null;return{entries:o,head:await this.journal.getHead(n),nextAfterSequence:s}}async getLatestCheckpoint(e){return this.requireCheckpoints().store.getLatest(Jl(e))}async getInclusionProof(e){const t=this.requireCheckpoints(),n=Jl(e),r=await this.requireLatestCheckpoint(t,n),i=await this.entryAtSequence(n,e.sequence),o=await t.builder.inclusionProof(n,e.sequence,r);return Object.freeze({ledgerId:n.ledgerId,ledgerEpochId:n.ledgerEpochId,sequence:e.sequence,entryDigest:i.entryDigest,checkpointDigest:r.checkpointDigest,proof:o})}async getConsistencyProof(e){const t=this.requireCheckpoints(),n=Jl(e),r=await this.requireLatestCheckpoint(t,n),i=await t.store.getByTreeSize(n,e.oldTreeSize);if(null===i)throw new Gu(Wu.CHECKPOINT_INVALID,"No signed checkpoint exists at the requested old tree size",{oldTreeSize:e.oldTreeSize});const o=await t.builder.consistencyProof(n,e.oldTreeSize,r);return Object.freeze({ledgerId:n.ledgerId,ledgerEpochId:n.ledgerEpochId,oldCheckpointDigest:i.checkpointDigest,newCheckpointDigest:r.checkpointDigest,proof:o})}requireCheckpoints(){if(void 0===this.checkpoints)throw new Gu(Wu.INVALID_CONFIGURATION,"This read service was built without checkpoint access; proofs are unavailable");return this.checkpoints}async requireLatestCheckpoint(e,t){const n=await e.store.getLatest(t);if(null===n)throw new Gu(Wu.CHECKPOINT_INVALID,"No signed checkpoint exists for this ledger yet",{ledgerId:t.ledgerId});return n}async entryAtSequence(e,t){const n=function(e,t){if(!/^(0|[1-9][0-9]*)$/.test(e))throw new Gu(Wu.CHECKPOINT_INVALID,`${t} must be a canonical non-negative decimal string`,{[t]:e});return BigInt(e)}(t,"sequence"),r=n>1n?String(n-1n):void 0;for await(const n of this.journal.readRange({...e,...void 0===r?{}:{afterSequence:r},limit:1})){if(n.core.sequence===t)return n;break}throw new Gu(Wu.CHECKPOINT_INVALID,"No entry exists at the requested sequence",{sequence:t})}}function Gl(e){return new Wl(e)}const Zl="https://schema.kya-os.org/v1/protocol/audit/head-request/v1.0.0",Yl="https://schema.kya-os.org/v1/protocol/audit/head-response/v1.0.0",Xl="https://schema.kya-os.org/v1/protocol/audit/list-entries-request/v1.0.0",Ql="https://schema.kya-os.org/v1/protocol/audit/list-entries-response/v1.0.0",ep="https://schema.kya-os.org/v1/protocol/audit/inclusion-proof-request/v1.0.0",tp="https://schema.kya-os.org/v1/protocol/audit/inclusion-proof-response/v1.0.0",np="https://schema.kya-os.org/v1/protocol/audit/consistency-proof-request/v1.0.0",rp="https://schema.kya-os.org/v1/protocol/audit/consistency-proof-response/v1.0.0",ip=ld({ledgerId:Cc().min(1).max(256),ledgerEpochId:Cc().min(1).max(256)}).strict(),op=ld({ledgerId:Cc().min(1).max(256),ledgerEpochId:Cc().min(1).max(256),sequence:Bd,entryDigest:Jd}).strict();function sp(e){if("object"!=typeof e||null===e||Object.isFrozen(e))return e;for(const t of Object.values(e))sp(t);return Object.freeze(e)}const ap=ld({schema:_d(Zl),ledger:ip}).strict(),cp=ld({schema:_d(Yl),head:op.nullable()}).strict(),dp=ld({schema:_d(Xl),ledger:ip,afterSequence:Bd.optional(),limit:td().int().positive().max(Bl).optional()}).strict(),up=ld({schema:_d(Ql),entries:dd(ou),head:op.nullable(),nextAfterSequence:Bd.nullable()}).strict(),lp=ld({schema:_d(ep),ledger:ip,sequence:Bd}).strict(),pp=ld({schema:_d(tp),proof:uu}).strict(),fp=ld({schema:_d(np),ledger:ip,oldTreeSize:Bd}).strict(),hp=ld({schema:_d(rp),proof:lu}).strict();function gp(e){return sp(ap.parse(e))}function yp(e){return sp(cp.parse(e))}function mp(e){return sp(dp.parse(e))}function vp(e){return sp(up.parse(e))}function Ip(e){return sp(lp.parse(e))}function wp(e){return sp(pp.parse(e))}function _p(e){return sp(fp.parse(e))}function Ep(e){return sp(hp.parse(e))}function bp(e){return{schema:Yl,head:e}}function Sp(e){return{schema:Ql,entries:e.entries,head:e.head,nextAfterSequence:e.nextAfterSequence}}function Ap(e){return{schema:tp,proof:e}}function Dp(e){return{schema:rp,proof:e}}function kp(e){const t=e?.modulusLength??2048;if("number"!=typeof t||!Number.isInteger(t)||t<2048)throw new Re("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return t}const Tp="Ed25519",Cp=Uint8Array.from([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]);function Op(){if("undefined"==typeof crypto||!crypto.subtle)throw new Error("WebCryptoProvider: WebCrypto (crypto.subtle) is unavailable in this runtime");return crypto}function Np(e){return e.slice()}class Rp extends wr{async sign(e,t){const n=u(t),r=64===n.length?n.subarray(0,32):n,i=new Uint8Array(Cp.length+r.length);i.set(Cp,0),i.set(r,Cp.length);const o=await Op().subtle.importKey("pkcs8",i,{name:Tp},!1,["sign"]),s=await Op().subtle.sign({name:Tp},o,Np(e));return new Uint8Array(s)}async verify(e,t,n){try{const r=u(n),i=await Op().subtle.importKey("raw",Np(r),{name:Tp},!1,["verify"]);return await Op().subtle.verify({name:Tp},i,Np(t),Np(e))}catch{return!1}}async generateKeyPair(){const e=await Op().subtle.generateKey({name:Tp},!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 Op().subtle.exportKey("raw",e.publicKey));return{privateKey:d(new Uint8Array(await Op().subtle.exportKey("pkcs8",e.privateKey)).subarray(Cp.length,Cp.length+32)),publicKey:d(t)}}async hash(e){return`sha256:${function(e){let t="";for(const n of e)t+=n.toString(16).padStart(2,"0");return t}(new Uint8Array(await Op().subtle.digest("SHA-256",Np(e))))}`}async randomBytes(e){return Op().getRandomValues(new Uint8Array(e))}}function Pp(e){return`${e.ledgerId}\0${e.ledgerEpochId}`}function xp(e,t){return`${e}\0${t}`}class zp{capabilities={durability:"ephemeral",atomicAppend:!0,orderedRead:!0};entriesByLedger=new Map;entriesByIdempotency=new Map;heads=new Map;async getHead(e){return this.heads.get(Pp(e))??null}async getByIdempotencyKey(e,t){return this.entriesByIdempotency.get(xp(e,t))??null}async compareAndAppend(e){const t=xp(e.ledger.ledgerId,e.idempotencyKey),n=this.entriesByIdempotency.get(t);if(void 0!==n)return n.eventDigest===e.entry.eventDigest?{kind:"duplicate",entry:n}:{kind:"idempotency_conflict",existing:n};const r=Pp(e.ledger),i=this.heads.get(r)??null;if(s=i,!(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:i};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),n=void 0===e.afterSequence?null:BigInt(e.afterSequence);let r=0;for(const i of t)if(!(null!==n&&BigInt(i.core.sequence)<=n)){if(void 0!==e.limit&&r>=e.limit)return;r+=1,yield i}}async snapshot(e){return[...this.entriesByLedger.get(Pp(e))??[]]}}const $p="kya:reference:audit:primary",Mp="epoch_1",Lp="urn:kya-os:audit-binding:mcp:2025-11-25",Up="did:key:zReferenceProducer",jp="reference-recorder",Hp="reference-tenant",Kp={kind:"keyed_commitment",value:`sha256:${"a".repeat(64)}`,keyId:"reference-tenant-key"};function Vp(e,t={}){return{schema:$d,eventId:`evt_${e}`,eventType:"tool.call.completed",eventVersion:"1.0.0",binding:Lp,occurredAt:175e10+e,tenantRef:Kp,source:{producer:{kind:"pairwise_did",did:Up},sourceId:jp,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 Fp(e={}){const t={ledgerId:e.ledgerId??$p,ledgerEpochId:e.ledgerEpochId??Mp},{publicKey:n,privateKey:r}=await async function(e,t){const n=it(t?.extractable),r=rt(e,tt);let i;if(r.secret&&nt(tt),r.resolve){const e=t?.crv??"P-256";switch(e){case"P-256":case"P-384":case"P-521":i={name:"ECDH",namedCurve:e};break;case"X25519":i={name:"X25519"};break;default:throw new Re("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 Re(`Invalid or unsupported crv option provided, the only supported value for ${e} is ${r.crv}`);i="RSA"===r.kty[0]?{...r.subtle,publicExponent:Uint8Array.of(1,0,1),modulusLength:kp(t)}:r.subtle}return crypto.subtle.generateKey(i,n??!1,[...r.usages[1],...r.usages[0]])}("EdDSA",{extractable:!1}),i={did:"did:key:zReferenceRecorder",kid:"did:key:zReferenceRecorder#0",alg:"EdDSA"},o={resolve:async e=>e.kid===i.kid?n:null},s=new $u(new Rp),a=new Lu(i,r),c=new zp,d=e.clock??{now:()=>Date.now()},u=new Fl({ledgerId:t.ledgerId,ledgerEpochId:t.ledgerEpochId,tenantRef:Kp,binding:Lp,sourceId:jp,journal:c,signer:a,hasher:s,clock:d}),l=new ul,p=new ll({journal:c,store:l,signer:a,hasher:s,clock:d}),f=new Wl({journal:c,checkpoints:{builder:p,store:l}}),h=new _l({hasher:s,signatures:new Mu(o)});return{ledger:t,signerRef:i,read:f,checkpoints:{builder:p,store:l},verifier:h,verificationPolicy:{policyId:"policy:reference-recorder",trustedLedgerEpochs:[{ledgerId:t.ledgerId,ledgerEpochId:t.ledgerEpochId,recorderKeys:[{signer:i}]}],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:Up,tenantAuthority:Hp,tenantRef:Kp}),checkpoint:async()=>p.createCheckpoint(t)}}class qp{recorder;context;constructor(e,t){this.recorder=e,this.context=t}async submit(e){return this.recorder.submitAuthenticated(e,await this.context())}}function Bp(e,t){return new qp(new Fl(e),t)}function Jp(e){return`${e.ledgerId}\0${e.ledgerEpochId}`}class Wp{config;capability="independent-observer";observations=new Map;publicationTails=new Map;constructor(e){this.config=e}async publish(e){const t=Jp({ledgerId:e.core.ledgerId,ledgerEpochId:e.core.ledgerEpochId}),n=this.publicationTails.get(t)??Promise.resolve();let r;const i=new Promise(e=>{r=e}),o=n.then(()=>i);this.publicationTails.set(t,o),await n;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 Gu(Wu.CHECKPOINT_INVALID,"Observer rejected an invalid checkpoint");const t={ledgerId:e.core.ledgerId,ledgerEpochId:e.core.ledgerEpochId},n=this.observations.get(Jp(t));if(void 0!==n){const t=BigInt(n.checkpoint.core.treeSize),r=BigInt(e.core.treeSize);if(r<t)throw new Gu(Wu.CHECKPOINT_ROLLBACK,"Observed checkpoint tree size moved backwards");if(r===t){if(e.core.rootDigest!==n.checkpoint.core.rootDigest||e.checkpointDigest!==n.checkpoint.checkpointDigest)throw new Gu(Wu.CHECKPOINT_CONFLICT,"Conflicting checkpoint roots were observed at the same tree size");return n.receipt}if(!await this.config.verifyConsistency(n.checkpoint,e))throw new Gu(Wu.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:n?.receipt.observationDigest??null},i=await Uu(this.config.hasher,Ku.observation,r),o=Object.freeze({core:Object.freeze(r),observationDigest:i,jws:await this.config.signer.sign(L(r))});return this.observations.set(Jp(t),{checkpoint:e,receipt:o}),o}async latest(e){return this.observations.get(Jp(e))??null}async verifyObservation(e,t){const n=await this.latest({ledgerId:e.core.ledgerId,ledgerEpochId:e.core.ledgerEpochId});return n?.checkpoint.checkpointDigest===e.checkpointDigest&&n.receipt.observationDigest===t.observationDigest}}class Gp{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 Zp{capabilities={durability:"ephemeral",fifoPerSource:!0};items=new Map;async enqueue(e){const t=this.items.get(e.eventId);var n,r;if(void 0===t)this.items.set(e.eventId,e);else if(n=t.submission,r=e.submission,n.ledgerId!==r.ledgerId||n.expectedLedgerEpochId!==r.expectedLedgerEpochId||M(n.producerEvent)!==M(r.producerEvent)||n.encryptedEvidence.length!==r.encryptedEvidence.length||!n.encryptedEvidence.every((e,t)=>{const n=r.encryptedEvidence[t];if(void 0===n||M(e.ref)!==M(n.ref)||e.ciphertext.byteLength!==n.ciphertext.byteLength)return!1;let i=0;for(let t=0;t<e.ciphertext.byteLength;t+=1)i|=e.ciphertext[t]^n.ciphertext[t];return 0===i}))throw new Error(`Audit outbox event identity collision: ${e.eventId}`)}async*pending(e=Number.MAX_SAFE_INTEGER){let t=0;for(const n of[...this.items.values()]){if(t>=e)return;t+=1,yield n}}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 Yp{capabilities={durability:"ephemeral",atomicClaim:!0};states=new Map;async claimEvent(e,t){const n=this.state(e),r=n.claims.get(t);if(void 0!==r)return{sequence:r.sequence.toString(),...void 0===r.previousSourceEventDigest?{}:{previousSourceEventDigest:r.previousSourceEventDigest}};n.next+=1n;const i=n.eventDigests.get(n.next-1n),o={sequence:n.next,...void 0===i?{}:{previousSourceEventDigest:i}};return n.claims.set(t,o),{sequence:o.sequence.toString(),...void 0===o.previousSourceEventDigest?{}:{previousSourceEventDigest:o.previousSourceEventDigest}}}async markEmitted(e,t,n,r){const i=this.state(e),o=BigInt(n),s=i.claims.get(t);if(s?.sequence!==o)throw new RangeError("Unknown source event claim");const a=i.eventDigests.get(o);if(void 0!==a&&a!==r)throw new Error(`Source event identity collision: ${t}`);i.eventDigests.set(o,r)}async markReceipted(e,t){const n=BigInt(t),r=this.state(e);if(n<1n||n>r.next)throw new RangeError("Unknown source sequence");if(!(n<=r.receiptedWatermark)){for(r.receipted.add(n);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),n=[];for(let e=t.receiptedWatermark+1n;e<=t.next;e+=1n)t.receipted.has(e)||n.push(e.toString());return{sourceId:e,highestEmitted:t.next.toString(),highestReceipted:t.receiptedWatermark.toString(),pendingSequences:n}}state(e){const t=this.states.get(e);if(void 0!==t)return t;const n={next:0n,receiptedWatermark:0n,receipted:new Set,claims:new Map,eventDigests:new Map};return this.states.set(e,n),n}}class Xp 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 Qp(e,t=256){return e.slice(0,t)}class ef{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:Qp(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 n="grant_used"===e?"grant.used":`authorization.${e}`;await this.trail.record({eventType:n,...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:Qp(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:Qp(t.delegationRef),...void 0===t.parentRef?{}:{parentRef:Qp(t.parentRef)}}})}async consent(e,t){const n=e.startsWith("credential_")?`credential.${e.slice(11)}`:`consent.${e}`;await this.trail.record({eventType:n,...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:Qp(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 tf{}class nf extends tf{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(n=>n.agentDid===e&&this.coversScopes(n,t))}async getBySession(e,t){return this.activeGrants().filter(n=>n.sessionId===e&&this.coversScopes(n,t))}async getById(e){const t=this.grants.get(e);return t?{...t}:void 0}async revoke(e,t){const n=this.grants.get(e);n&&(n.status="revoked",void 0!==t&&(n.revocationReason=t))}async cleanup(){const e=this.now();for(const[t,n]of this.grants)void 0!==n.expiresAt&&n.expiresAt<=e&&this.grants.delete(t)}activeGrants(){const e=this.now(),t=[];for(const n of this.grants.values())"revoked"!==n.status&&(void 0!==n.expiresAt&&n.expiresAt<=e||t.push({...n}));return t}coversScopes(e,t){return!t||0===t.length||t.every(t=>e.scopes.includes(t))}}class rf{}class of extends rf{pending=new Map;now;constructor(e={}){super(),this.now=e.now??(()=>Date.now())}async put(e,t,n){this.pending.set(e,{flow:{...t},expiresAt:this.now()+n})}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,n]of this.pending)n.expiresAt<=e&&this.pending.delete(t)}}function sf(e){const t=new Set;for(const n of e.credentialSubject.delegation.scopes??[])t.add(n);for(const n of e.credentialSubject.delegation.constraints?.scopes??[])t.add(n);return Array.from(t)}function af(e,t){const n=sf(e),r=sf(t),i=t.credentialSubject.delegation,o=e=>`${e.matcher}\0${e.resource}`,s=new Set((e.credentialSubject.delegation.constraints.crisp?.scopes??[]).map(o)),a=(i.constraints.crisp?.scopes??[]).filter(e=>!s.has(o(e)));if(a.length>0)return{valid:!1,reason:`Delegation ${i.id} introduces crisp scope matcher(s) absent from parent ${e.credentialSubject.delegation.id}: ${a.map(e=>`${e.matcher}:${e.resource}`).join(", ")}`};if(0===n.length)return{valid:!0};if(0===r.length)return{valid:!1,reason:`Delegation ${i.id} omits scopes required to prove attenuation from parent ${e.credentialSubject.delegation.id}`};const c=new Set(n),d=r.filter(e=>!c.has(e));return d.length>0?{valid:!1,reason:`Delegation ${i.id} widens scopes beyond parent ${e.credentialSubject.delegation.id}: ${d.join(", ")}`}:{valid:!0}}const cf=["delete","drop","destroy","remove","terminate","transfer","payment","admin","execute","modify","write","rotate","revoke"],df=["read","get","list","describe","search","query"];class uf{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 n=lf(e.toolName),r=function(e){const t=lf(e);return t.includes("prod")||t.includes("production")}(e.namespace);let i;return i=n.some(e=>cf.includes(e))?{reversibility:"irreversible",blastRadius:r?"environment":"resource",severity:r?"catastrophic":"high"}:n.some(e=>df.includes(e))?{reversibility:"reversible",blastRadius:"record",severity:"low"}:{reversibility:"unknown",blastRadius:"unknown",severity:"unknown"},{...i,...pf(t)}}}function lf(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 pf(e){if(!e)return{};const t={};for(const[n,r]of Object.entries(e))void 0!==r&&(t[n]=r);return t}class ff{cfg;constructor(e={}){this.cfg=e}async evaluate(e){const{severity:t,reversibility:n,scopeMatched:r,humanApprovals:i}=e.context;if(!r)return{decision:"deny",reason:"scope_not_matched"};if("unknown"===t||"unknown"===n)return{decision:"deny",reason:"unclassified_high_risk"};if("irreversible"===n||"catastrophic"===t||"high"===t){const e=this.cfg.stepUpQuorum??1;return i.length>=e?{decision:"allow"}:{decision:"step_up",quorum:{n:e,approvers:this.cfg.stepUpApprovers??[]},reason:"destructive_action_requires_approval"}}return{decision:"allow"}}}async function hf(e,t,n,r){if(n.n<=0)return{satisfied:!1,reason:"invalid_quorum:n<=0"};const i=new Set;for(const o of e)"approve"===o.decision&&o.requestHash===t&&(n.approvers.length>0&&!n.approvers.includes(o.approverDid)||await r(o)&&i.add(o.approverDid));return i.size>=n.n?{satisfied:!0}:{satisfied:!1,reason:`quorum_not_met:${i.size}/${n.n}`}}function gf(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 yf(e,t=256){const n="string"==typeof e?e:String(e);let r="";for(const e of n){const t=e.codePointAt(0)??0;r+=t<=31||t>=127&&t<=159?"�":e}return r.length>t?`${r.slice(0,t)}…`:r}const mf=256,vf=256,If=/\([^()]*[+*?{][^()]*\)\s*[+*{]/;function wf(e,t,n){switch(t){case"exact":return e===n;case"prefix":{const t=e.endsWith("*")?e.slice(0,-1):e;return 0!==t.length&&n.startsWith(t)}case"regex":if(e.length>mf||n.length>vf)return!1;if(If.test(e))return!1;try{return new RegExp(`^(?:${e})$`).test(n)}catch{return!1}default:return!1}}function _f(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 n of function(e){return e?.credentialSubject?.delegation?.constraints?.crisp?.scopes??[]}(t))if(wf(n.resource,n.matcher,e))return{satisfied:!0,usedNonExactMatcher:"exact"!==n.matcher};return{satisfied:!1,usedNonExactMatcher:!1}}function Ef(e){const{identity:t,cryptoProvider:n,delegationConfig:r}=e,i=ge(),o=r?.fetchProvider??("function"==typeof globalThis.fetch?new Ur:void 0),a=o?Jn(o):void 0,c=rr(r?.didResolvers,o),u=new Ht({didResolver:{async resolve(e){const t=r?.didResolver;if(t){const n=await t.resolve(e);if(n)return n}const n=Y(e),o=n?c[n]:void 0;if(o)try{const t=await o.resolve(e);if(t)return t}catch{return null}return e.startsWith("did:key:")?i.resolve(e):e.startsWith("did:web:")?a?.resolve(e)??null:null}},signatureVerifier:async(e,t)=>{const r=e.proof;if(!r)return{valid:!1,reason:"Missing proof"};const i=h(r);if(!i)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=U(a),u=(new TextEncoder).encode(c),l=s(i),p=t;if(!p.x)return{valid:!1,reason:"No x field in publicKeyJwk"};const f=d(s(p.x)),g=await n.verify(u,l,f);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 n,i,o=!1;if("string"==typeof e){const t=K(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};n=t.payload.vc,n.proof||(n={...n,proof:{type:"JwtProof2020",jwt:e}}),o=!0}else n=e;try{i=await(s=n,a={skipSignature:o},async function(e,t,n){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 i=y(e);let o=[e];if(i.parentId){if(!t.resolveDelegationChain)return{valid:!1,reason:`Delegation ${i.id} references parent ${i.parentId} but no resolveDelegationChain handler is configured`};let n;try{n=await t.resolveDelegationChain(e)}catch(e){return{valid:!1,reason:`Failed to resolve delegation chain: ${e instanceof Error?e.message:"Unknown error"}`}}if(0===n.length)return{valid:!1,reason:`Delegation ${i.id} references parent ${i.parentId} but the resolved chain is empty`};const r=n.findIndex(e=>e.credentialSubject.delegation.id===i.id);if(-1!==r&&r!==n.length-1)return{valid:!1,reason:`Resolved delegation chain for ${i.id} must end with the leaf credential`};o=-1===r?[...n,e]:n}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 i=await t.verifier.verifyDelegationCredential(e,{...n?.skipSignature?{skipSignature:!0}:{}});if(!i.valid)return{valid:!1,reason:`Delegation ${r.id} invalid: ${i.reason}`};if(!en(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=af(c,e);if(!o.valid)return o;a=r,c=e}const d=y(o[o.length-1]);if(d.id!==i.id)return{valid:!1,reason:`Resolved delegation chain ended at ${d.id} instead of leaf ${i.id}`};if(t.revocationChecker){const e=await t.revocationChecker.isRevoked(i.id);if(e.revoked)return{valid:!1,reason:e.revokedAncestor?`Delegation ${i.id} is revoked via ancestor ${e.revokedAncestor}`:`Delegation ${i.id} is revoked${e.reason?`: ${e.reason}`:""}`}}return{valid:!0}}(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}),i={valid:!1,reason:"Delegation credential could not be verified"}}var s,a;return i.valid?{valid:!0,vc:n,isJwt:o}:{valid:!1,reason:i.reason??"Unknown delegation validation error",vc:n}},buildDelegationErrorResponse:(e,t)=>({content:[{type:"text",text:JSON.stringify({error:e,reason:yf(t)})}],isError:!0}),buildNeedsAuthorizationChallenge:async function(e,t){const r=await n.randomBytes(16),i=Array.from(r).map(e=>e.toString(16).padStart(2,"0")).join(""),o=[i.slice(0,8),i.slice(8,12),i.slice(12,16),i.slice(16,20),i.slice(20)].join("-"),s=Math.floor(Date.now()/1e3)+300,a=k({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 bf=256;function Sf(e){try{if("object"!=typeof e||null===e)return"unknown";const t=e,n=t.id;if("string"==typeof n&&n.length>0)return n.slice(0,bf);const r=t.credentialSubject;if("object"!=typeof r||null===r)return"unknown";const i=r.delegation;if("object"!=typeof i||null===i)return"unknown";const o=i.id;return"string"==typeof o&&o.length>0?o.slice(0,bf):"unknown"}catch{return"unknown"}}const Af=["handshake","identity","reputation"];function Df(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(Pu(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 n={did:e.identity.did,kid:e.identity.kid,privateKey:e.identity.privateKey,publicKey:e.identity.publicKey},i=e.nonceCache??new kr,o=new Nr(t,{...e.session,serverDid:n.did,nonceCache:i}),s=new Cn(n,t),a=e.delegation,d=e.auditLog??new Fr,u=void 0!==e.audit&&!1!==e.audit?new ef(e.audit,{includeToolNames:e.audit.includeToolNames??!1}):void 0,l=e.emitLegacyProofKey??!0,p=e.responseProofProfile??A,f=e.grantStore??new nf;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 h=a?.holderBinding??"off",g={identity:n,config:e,cryptoProvider:t,sessionManager:o,proofGenerator:s,auditLog:d,audit:u,grantStore:f,delegationConfig:a,holderBindingMode:h,holderBindingVerifier:"off"===h?void 0:new hr({cryptoProvider:t,clockProvider:new Lr,nonceCacheProvider:i,fetchProvider:a?.fetchProvider??("function"==typeof globalThis.fetch?new Ur:new jr)}),emitLegacyProofKey:l,responseProofProfile:p},y=function(e){const{identity:t,config:n,cryptoProvider:i,sessionManager:o,proofGenerator:s,auditLog:a,audit:d,emitLegacyProofKey:u,responseProofProfile:l}=e,p=l===D,f=new WeakSet,h="org.kya-os/audit",g=async(e,t,n)=>{try{return await t(),!0}catch(t){return de.error(`[kya-os] ${e}`,{...void 0===n?{}:{tool:n},error:t instanceof Error?t.message:String(t)}),!1}},y=(e,t,n)=>{const r={...e._meta??{}};return n&&(delete r[Sn],delete r[Dn]),r[h]={..."object"==typeof r[h]&&null!==r[h]?r[h]:{},status:"degraded",reason:t},e._meta=r,e.isError=!0,e},m=e=>({content:[{type:"text",text:JSON.stringify({success:!1,error:{code:"audit_delivery_failed",message:e}})}],isError:!0,_meta:{[h]:{status:"degraded",reason:e}}}),v=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,[Sn]:t,...u?{[Dn]:t}:{}});let w;async function _(){if(w&&await o.getSession(w))return o.getStats().activeSessions<=1?w: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(!n.autoSession)return;const e=c(await i.randomBytes(16)),r=Math.floor(Date.now()/1e3),s=await o.validateHandshake({nonce:e,audience:t.did,timestamp:r});return s.success&&s.session?(w=s.session.sessionId,w):void 0}return{handleHandshake:async function(e){if(!Pr(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 n=await o.validateHandshake(e),i=n.success?"established":n.error?.code===r.nonce_replay?"replay_rejected":"rejected",s=await g(`Failed to record ${i} session audit event`,()=>d?.session(i,{succeeded:n.success,...void 0===n.error?{}:{reasonCode:n.error.code}}));return n.success&&!s?{content:m("Required session audit delivery failed after handshake validation").content,isError:!0}:(n.success&&n.session&&(w=n.session.sessionId),{content:[{type:"text",text:JSON.stringify({success:n.success,...n.session&&{sessionId:n.session.sessionId,serverDid:t.did,serverKid:t.kid},...n.error&&{error:n.error}})}],...n.error&&{isError:!0}})},ensureSession:_,wrapWithProof:function(e,n){return async(r,i,c)=>{if(!await g("Required tool intent audit delivery failed",()=>d?.tool("started",{toolName:e,outcome:"unknown",context:v(c)}),e))return m("Required intent audit delivery failed before tool execution");let u;try{u=await n(r,i,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:v(c)}),e),t}if(u.isError)return(e=>{if(f.has(e))return!0;const t=e._meta,n=t?.[h];return"object"==typeof n&&null!==n&&!0===n.terminal})(u)||await g("Failed to record error tool outcome",()=>d?.tool("failed",{toolName:e,outcome:"failed",reasonCode:"HANDLER_ERROR_RESULT",context:v(c)}),e)||y(u,"Required terminal audit delivery failed for an error response",!1),u;const w=i??await _();if(!w)return await g("Failed to record unavailable proof session",()=>d?.proof("rejected",{outcome:"failed",verificationCode:"PROOF_SESSION_UNAVAILABLE",context:v(c)}),e)&&await g("Failed to record completed tool outcome",()=>d?.tool("completed",{toolName:e,outcome:"succeeded",context:v(c)}),e)?u:y(u,"Required terminal audit delivery failed after tool completion",!0);const E=await o.getSession(w);if(!E)return await g("Failed to record missing proof session",()=>d?.proof("rejected",{outcome:"failed",verificationCode:"PROOF_SESSION_NOT_FOUND",context:v(c)}),e)&&await g("Failed to record completed tool outcome",()=>d?.tool("completed",{toolName:e,outcome:"succeeded",context:v(c)}),e)?u:y(u,"Required terminal audit delivery failed after tool completion",!0);try{const n={method:e,params:r},i={data:p?u:u.content},o=await s.generateProof(n,i,E,{scopeId:c?.scopeId,profile:l});if(u._meta=I({},o),!await g("Required generated-proof audit delivery failed",()=>d?.proof("generated",{outcome:"succeeded",context:v(c)}),e)||!await g("Required completed-tool audit delivery failed",()=>d?.tool("completed",{toolName:e,outcome:"succeeded",context:v(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:E.sessionId,audience:E.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:v(c)}),e)||y(u,"Required proof-failure audit delivery failed after tool completion",!0)}return u}},attachOutcomeProof:async(e,t,n,r,i,a="denied",c,u)=>{const m="denied"===a?"denied":"step_up_required",v="needs_authorization"===a?"NEEDS_AUTHORIZATION":"step_up_required"===a?"STEP_UP_REQUIRED":"AUTHORIZATION_DENIED",w=await g("Failed to record authorization outcome",()=>d?.authorization(m,{outcome:"denied"===a?"denied":"challenged",reasonCode:v}),t)&&await g("Failed to record terminal authorization tool outcome",()=>d?.tool("denied"===a?"denied":"challenged",{toolName:t,outcome:"denied"===a?"denied":"challenged",reasonCode:v}),t);f.add(e),e._meta={...e._meta??{},[h]:{terminal:!0,outcome:a,...w?{}:{status:"degraded",reason:"Required terminal audit delivery failed for authorization outcome"}}};try{const f=r??await _();if(!f)return e;const h=await o.getSession(f);if(!h)return e;let m;if(void 0!==c)m=c;else{m={};for(const[e,t]of Object.entries(n))"_kyaos_delegation"!==e&&(m[e]=t)}const v={method:t,params:m},E=void 0!==u?{data:p?e:u}:void 0,b=await s.generateProof(v,E,h,{outcome:a,reason:yf(i),profile:l});e._meta=I(e._meta??{},b),w&&(await g("Failed to record generated outcome proof",()=>d?.proof("generated",{outcome:"succeeded"}),t)||y(e,"Required proof audit delivery failed for authorization outcome",p))}catch(e){de.error("[kya-os] Outcome proof generation failed",{tool:t,error:e instanceof Error?e.message:String(e)}),w&&await g("Failed to record outcome-proof rejection",()=>d?.proof("rejected",{outcome:"failed",verificationCode:"OUTCOME_PROOF_GENERATION_FAILED"}),t)}return e}}}(g),m=function(e,t){const{identity:n,config:i,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!==i.audit&&!1!==i.audit?{enabled:!0,profile:i.audit.capabilities?.profile??i.audit.auditProfile??"AAP-0",...void 0===i.audit.capabilities?{}:{capabilities:i.audit.capabilities}}:{enabled:!1,profile:"AAP-0"};return{content:[{type:"text",text:JSON.stringify({did:n.did,kid:n.kid,name:i.identity.agentName??n.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: ${Af.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:[...Af],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:v,bindGrantOnSuccess:I}=function(e){const{identity:t,cryptoProvider:n,grantStore:r,holderBindingMode:i,holderBindingVerifier:o}=e;async function s(e,t,r){const i=`${e}|${t??""}|${[...r].sort().join(",")}`;return`grant_${(await n.hash((new TextEncoder).encode(i))).replace(/^sha256:/,"")}`}return{resolveExistingGrant:async function(e,n,i,s){const a=await async function(e,n,i,s){if(!o)return;const a=n._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&&Mn(u)&&"bound"===(await Ln({proof:d,subjectDid:u,request:xn(e,n),expectedAudience:t.did,proofVerifier:o})).status?(await r.getByAgent(u,[s])).find(e=>void 0===e.sessionId||e.sessionId===i):void 0}(e,n,i,s);if(a)return a;if(i){const[e]=await r.getBySession(i,[s]);if(e)return e}},bindGrantOnSuccess:async function(e,t,n,o,a){try{const c=e.credentialSubject?.id;if(!c)return;if("off"===i&&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=sf(e)}catch{d=[]}const u=Array.from(new Set([a,...d])),l=e.credentialSubject?.delegation?.controller,p=function(e){if(e.expirationDate){const t=Date.parse(e.expirationDate);if(!Number.isNaN(t))return t}const t=e.credentialSubject?.delegation?.constraints?.notAfter;if("number"==typeof t)return 1e3*t}(e),f={id:await s(c,o,u),agentDid:c,...void 0!==l?{userDid:l}:{},scopes:u,...void 0!==o?{sessionId:o}:{},authorization:{type:"delegation"},...n&&"string"==typeof t?{credentialJwt:t}:{},issuedAt:Date.now(),...void 0!==p?{expiresAt:p}:{},status:"active"};await r.bind(f)}catch(e){de.error("[kya-os] Grant bind failed",{scope:a,error:e instanceof Error?e.message:String(e)})}}}}(g),{wrapWithDelegation:w}=function(e,t){const{identity:n,holderBindingMode:i,holderBindingVerifier:o,audit:s,cryptoProvider:a}=e,{attachOutcomeProof:c,resolveExistingGrant:d,bindGrantOnSuccess:u}=t,{verifyDelegation:l,buildDelegationErrorResponse:p,buildNeedsAuthorizationChallenge:f}=Ef(e);return{wrapWithDelegation:function(e,t,h){return async(g,y)=>{const m=g._kyaos_delegation;if(null==m){const n=await d(e,g,y,t.scopeId);if(n){const r={};for(const[e,t]of Object.entries(g))Pn(e)||(r[e]=t);de.debug(`[kya-os] Grant resolved for "${e}" (scope "${t.scopeId}") — no re-paste required`);const i={scopeId:t.scopeId,actor:{kind:"pairwise_did",did:n.agentDid},...n.userDid?.startsWith("did:")?{responsibleParty:{kind:"pairwise_did",did:n.userDid}}:{},authorization:{source:"grant",decision:"allowed",scopeId:t.scopeId,grantRef:n.id,verificationCode:"DURABLE_GRANT_RESOLVED"}};return await(s?.authorization("grant_used",{outcome:"succeeded",grantRef:n.id,context:i})),h(r,y,i)}const{challengeContent:r,message:i}=await f(e,t);return c({content:r},e,g,y,i,"needs_authorization",void 0,r)}const v=await l(m);if(!v.valid){try{await(s?.delegation("rejected",{delegationRef:Sf(v.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}": ${yf(v.reason)}`),c(p(r.delegation_invalid,v.reason),e,g,y,v.reason)}const{vc:I,isJwt:w}=v;if("off"!==i&&o){const t=I.credentialSubject?.id;if(t&&Mn(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"===i)return c(p(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 Ln({proof:a,subjectDid:t,request:xn(e,g),expectedAudience:n.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}": ${yf(t)}`),"enforce"===i)return c(p(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 _=_f(t.scopeId,I);if(_.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.`),!_.satisfied){const n=`Required scope "${t.scopeId}" not in delegation scopes`;return de.warn(`[kya-os] Delegation missing required scope "${t.scopeId}" for "${e}"`),c(p(r.insufficient_scope,n),e,g,y,n)}const E=w?(new TextEncoder).encode(m):L(I),b=await a.hash(E),S=I.id??I.credentialSubject.delegation.id,A={kind:"pairwise_did",did:I.credentialSubject.id},D=I.credentialSubject.delegation.controller,k={source:"delegation",decision:"allowed",scopeId:t.scopeId,delegationRef:S,delegationCredentialDigest:b,verificationCode:"DELEGATION_CHAIN_VALID"},T={scopeId:t.scopeId,actor:A,...D?.startsWith("did:")?{responsibleParty:{kind:"pairwise_did",did:D}}:{},authorization:k};await(s?.delegation("verified",{delegationRef:S,outcome:"succeeded",parentRef:I.credentialSubject.delegation.parentId,context:T})),await(s?.authorization("approved",{outcome:"succeeded",context:T}));const C={};for(const[e,t]of Object.entries(g))Pn(e)||(C[e]=t);return await u(I,m,w,y,t.scopeId),de.debug(`[kya-os] Delegation verified for "${e}", scope "${t.scopeId}"`),h(C,y,T)}}}}(g,{attachOutcomeProof:y.attachOutcomeProof,resolveExistingGrant:v,bindGrantOnSuccess:I}),{withPolicyGate:_}=function(e,t){const{proofGenerator:n,audit:i}=e,{attachOutcomeProof:o}=t,s=new uf,a=new ff;return{withPolicyGate:function(e,t,c={}){const d=c.engine??a,u=c.classifier??s,l=c.approvalsArgKey??"_kyaos_approvals",p=c.isValidApprovalSignature??(async()=>!1);return async(s,a,f)=>{const h={};for(const[e,t]of Object.entries(s))Pn(e)||e===l||(h[e]=t);const g=c.resolveNamespace?.(s)??e,y=u.classify({toolName:e,namespace:g}),m=function(e){if(!e||"object"!=typeof e)return{agentDid:"unknown",delegatedScopes:[]};try{const t=e,n=t.credentialSubject,r=n?.delegation?.subjectDid??n?.id??"unknown",i=n?.delegation?.controller;let o=[];try{o=sf(t)}catch{o=[]}return{agentDid:r,...i?{responsibleParty:i}:{},delegatedScopes:o}}catch{return{agentDid:"unknown",delegatedScopes:[]}}}(s._kyaos_delegation),v=gf({principal:{agentDid:m.agentDid,...m.responsibleParty?{responsibleParty:m.responsibleParty}:{}},action:{toolName:e},resource:{namespace:g},delegatedScopes:m.delegatedScopes,scopeMatched:c.scopeMatched??!1,risk:y}),I=await d.evaluate(v),w=void 0===f?void 0:{...void 0===f.actor?{}:{actor:f.actor},...void 0===f.responsibleParty?{}:{responsibleParty:f.responsibleParty},...void 0===f.authorization?{}:{authorization:f.authorization}};if(await(i?.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:w})),"allow"===I.decision)return await(i?.authorization("approved",{outcome:"succeeded",context:w})),t(h,a,f);if("deny"===I.decision){const t={content:[{type:"text",text:JSON.stringify({error:r.policy_denied,reason:yf(I.reason)})}],isError:!0};return o(t,e,s,a,I.reason,"denied",h)}const _=await n.hashRequest({method:e,params:h}),E=Array.isArray(s[l])?s[l]:[];if((await hf(E,_,I.quorum,p)).satisfied)return await(i?.authorization("approved",{outcome:"succeeded",context:w})),t(h,a,f);const b=C({message:`Tool "${e}" requires ${I.quorum.n}-of-N approval before it may proceed (${yf(I.reason)}).`,resumeToken:`step_up:${_}`,expiresAt:Math.floor(Date.now()/1e3)+300,requestHash:_,quorum:I.quorum}),S={content:[{type:"text",text:JSON.stringify(b)}],isError:!0};return o(S,e,s,a,I.reason,"step_up_required",h)}}}}(g,{attachOutcomeProof:y.attachOutcomeProof});return{identity:e.identity,sessionManager:o,proofGenerator:s,kyaOsTool:m.kyaOsTool,handshakeTool:m.handshakeTool,handleKyaOs:m.handleKyaOs,handleHandshake:y.handleHandshake,wrapWithProof:y.wrapWithProof,wrapWithDelegation:w,withPolicyGate:_}}async function kf(e){const t=await e.generateKeyPair(),n=oe(t.publicKey);return{did:n,kid:`${n}#${se(n)}`,privateKey:t.privateKey,publicKey:t.publicKey}}async function Tf(e,t){const n=Df({identity:t.identity??await kf(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:Id(Af).describe("Protocol operation to perform"),nonce:Cc().optional().describe("Client-generated unique nonce (handshake)"),audience:Cc().optional().describe("Intended audience (handshake)"),timestamp:td().optional().describe("Unix epoch seconds (handshake)"),agentDid:Cc().optional().describe("Client agent DID (handshake, optional)")}},async e=>{const t=await n.handleKyaOs(e);return{...t,content:t.content.map(e=>({...e,type:"text"}))}}),!1!==t.proofAllTools){const r=["_kyaos","_kyaos_handshake",...t.excludeTools??[]],i=e.connect.bind(e);e.connect=e=>i(function(e,t,n=["_kyaos","_kyaos_handshake"]){const r=new Map,i={start:()=>e.start(),close:()=>e.close(),set onmessage(t){e.onmessage=t},get onmessage(){return e.onmessage},set onclose(t){e.onclose=t},get onclose(){return e.onclose},set onerror(t){e.onerror=t},get onerror(){return e.onerror},async send(n){const i=n.id,o=void 0!==i?r.get(i):void 0;if(o){r.delete(i);try{const e=n.result;if(e){const r=async()=>({...e}),i=t.wrapWithProof(o.toolName,r),s=await i(o.args);e.isError||void 0===s._meta||(n={...n,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=n.result;t&&(t._meta={proofError:"Proof generation failed — response is unproven"},n={...n,result:t})}}return e.send(n)}},o=e.start.bind(e);return i.start=async()=>{await o();const t=e.onmessage;e.onmessage=e=>{if("tools/call"===e.method&&void 0!==e.id){const t=e.params,i=t?.name;i&&!n.includes(i)&&r.set(e.id,{toolName:i,args:t?.arguments??{}})}t?.(e)}},i}(e,n,r))}return n}const Cf=Cc().regex(/^did:(key|web):.+$/,"must be a did:key or did:web DID"),Of=Id(["mcp","agent","client","verifier","human"]),Nf=Id(["L1","L2","L3"]),Rf=ld({kty:_d("OKP"),crv:_d("Ed25519"),x:Cc(),kid:Cc().optional(),use:Cc().optional()}).strict(),Pf=(fd([Rf,ld({kty:_d("EC"),crv:_d("P-256"),x:Cc(),y:Cc(),kid:Cc().optional(),use:Cc().optional()}).strict()]),fd([Cc(),(Kf=Cc(),Vf=sd(),Vf&&Vf._zod?new md({type:"record",keyType:Kf,valueType:Vf,...ci(Ff)}):new md({type:"record",keyType:Cc(),valueType:Kf,...ci(Vf)}))])),xf=ld({vc:Pf}),zf=ld({name:Cc().min(1),attestations:dd(xf).min(1)}).strict(),$f=fd([Cc().min(1),zf]),Mf=ld({type:Id(["IdentityVerification","CapabilityAttestation"]),vc:Pf,subject:Cf.optional(),issuer:Cf.optional()}).strict(),Lf="org.kya-os/proof.v1",Uf=fd([_d(Lf),_d("org.kya-os/proof@1")]),jf=ld({clientId:Cc().min(1),jwksUri:Cc().min(1)}).strict(),Hf=ld({statusListCredential:Cc().min(1),statusListIndex:Cc().regex(/^[0-9]+$/,"statusListIndex must be a canonical non-negative decimal")}).strict();var Kf,Vf,Ff;ld({id:Cf,entityType:Of,name:Cc().min(1),kid:Cc().optional(),publicKeyJwk:Rf.optional(),createdAt:Cc().optional(),capabilities:dd($f).optional(),conformanceLevel:Nf.optional(),responsibleParty:Cf.optional(),principal:Cf.optional(),delegationRef:Cc().optional(),attestations:dd(Mf).optional(),didDocument:Cc().optional(),proofProfile:Uf.optional(),cimd:jf.optional(),revocation:Hf.optional()}).strict();const qf="org.kya-os/decentralized-authority",Bf="io.modelcontextprotocol/clientCapabilities",Jf=-32021,Wf="extension_not_declared",Gf="malformed_declaration",Zf=e=>new Set(e).size===e.length,Yf=ld({version:Cc().regex(/^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/,"version must be a semver string").optional(),proofProfiles:dd(Cc().min(1)).min(1).refine(Zf,"proofProfiles must be unique").optional(),didMethods:dd(Cc().regex(/^did:[a-z0-9]+$/,'didMethods entries look like "did:web"')).min(1).refine(Zf,"didMethods must be unique").optional(),required:function(e){return function(e,t){return new e({type:"boolean",...ci(t)})}(id,e)}().optional()}),Xf={version:"1.0.0",proofProfiles:[Lf],didMethods:["did:key","did:web"],required:!1};function Qf(e){const t=Yf.safeParse(e);return t.success?t.data:void 0}function eh(e={}){return{version:e.version??Xf.version,proofProfiles:e.proofProfiles??[...Xf.proofProfiles],didMethods:e.didMethods??[...Xf.didMethods],required:e.required??Xf.required}}function th(e={}){const t=Yf.safeParse(e);if(!t.success)throw new Error(`invalid ${qf} settings: ${t.error.message}`);return t.data}function nh(e={},t=qf){return{[t]:th(e)}}function rh(e){const t=e.extensionId??qf,n=oh(Xn(r=e.meta)?r[Bf]:void 0,t);var r;if(n.present){const e=Qf(n.value);return void 0===e?{status:"malformed",carriage:"stateless"}:{status:"declared",declaration:{settings:e,carriage:"stateless"}}}const i=oh(e.initializeCapabilities,t);if(i.present){const e=Qf(i.value);return void 0===e?{status:"malformed",carriage:"initialize"}:{status:"declared",declaration:{settings:e,carriage:"initialize"}}}return{status:"absent"}}function ih(e){const t=rh(e);return"declared"===t.status?t.declaration:void 0}function oh(e,t){if(!Xn(e))return{present:!1};const n=e.extensions;return Xn(n)&&Object.prototype.hasOwnProperty.call(n,t)?{present:!0,value:n[t]}:{present:!1}}const sh=-31e3,ah=-32099,ch=-32020,dh=["server/discover","ping"];function uh(e={},t={}){const n=eh(th(e)),r=t.extensionId??qf,i=t.exemptMethods??dh;return e=>{const t=rh({...e,extensionId:r});return"declared"===t.status?{ok:!0,declaration:t.declaration}:n.required?void 0!==e.method&&i.includes(e.method)?{ok:!0}:"malformed"===t.status?{ok:!1,error:fh(r)}:{ok:!1,error:lh(r)}:{ok:!0}}}function lh(e=qf){return{code:Jf,message:`Missing required client capability: ${e}`,data:{requiredCapabilities:{extensions:{[e]:{}}},reason:Wf,extension:e}}}const ph=-32602;function fh(e=qf){return{code:ph,message:`Invalid params: the ${e} settings declaration is present but malformed`,data:{reason:Gf,extension:e}}}function hh(e,t={}){if(void 0!==t.code&&t.code>=ah&&t.code<=ch)throw new Error(`JSON-RPC code ${t.code} is inside the MCP-reserved range (${ah}..${ch}); KYA-OS domain errors use implementation-defined codes (SPEC-MCP-EXTENSION.md §5.1)`);return{code:t.code??sh,message:e.message,data:{reason:e.code,profile:t.profile??Lf,...e.reasons&&e.reasons.length>0?{reasons:[...e.reasons]}:{}}}}}};
|