@kya-os/mcp-i 1.11.1 → 1.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ "use strict";exports.id=160,exports.ids=[160],exports.modules={34160:(e,t,n)=>{n.r(t),n.d(t,{ANON_NONCE_TTL_MS:()=>D,AUDIT_ASSURANCE_PROFILES:()=>ch,AUDIT_BUNDLE_INTEGRITY_SUITE:()=>Ip,AUDIT_BUNDLE_MANIFEST_SCHEMA_ID:()=>vp,AUDIT_BUNDLE_MEDIA_TYPES:()=>ef,AUDIT_CHECKPOINT_INTEGRITY_SUITE:()=>yp,AUDIT_CHECKPOINT_SCHEMA_ID:()=>mp,AUDIT_DIGEST_DOMAINS:()=>vh,AUDIT_ENTRY_SCHEMA_ID:()=>hp,AUDIT_ERROR_CODES:()=>bh,AUDIT_EVENT_SCHEMA_ID:()=>pp,AUDIT_EVENT_TYPES:()=>ui,AUDIT_INTEGRITY_SUITE:()=>gp,AUDIT_REASON_CODES:()=>Jh,AUDIT_RECEIPT_SCHEMA_ID:()=>fp,AUTH_NONCE_TTL_MS:()=>A,AuditArtifactVerifier:()=>Yh,AuditCheckpointBuilder:()=>Hh,AuditCheckpointCoordinator:()=>Kh,AuditLogProvider:()=>ai,AuditMirrorService:()=>mf,AuditProjectionWorker:()=>Zh,AuditProtocolError:()=>Ah,AuditRecorderService:()=>_f,AuditReplayBundleExporter:()=>af,AuditTrailService:()=>ff,BitstringManager:()=>We,CascadingRevocationManager:()=>et,ClockProvider:()=>jn,CompactJwsAuditSignatureVerifier:()=>hh,CompactJwsAuditSigner:()=>fh,CryptoProvider:()=>Un,CryptoProviderAuditHasher:()=>ph,DEFAULT_CLOCK_SKEW_SECONDS:()=>Nn,DEFAULT_SESSION_TTL_MINUTES:()=>E,DEFAULT_TIMESTAMP_SKEW_SECONDS:()=>S,DELEGATION_CREDENTIAL_CONTEXT:()=>m,DefaultPolicyEngine:()=>Zf,DelegationCredentialIssuer:()=>V,DelegationCredentialVerifier:()=>Ve,DelegationGraphManager:()=>Be,DidWebResolver:()=>pn,ED25519_KEY_SIZE:()=>Ft,ED25519_PKCS8_DER_HEADER:()=>Kt,ED25519_SPKI_DER_HEADER_LENGTH:()=>Vt,FetchProvider:()=>Hn,GrantStore:()=>xf,HOLDER_BINDING_ERROR:()=>tn,IdentityProvider:()=>Fn,KYA_OS_ERROR_CODES:()=>a,KYA_OS_PROOF_META_KEY:()=>Bt,LEGACY_PROOF_META_KEY:()=>Zt,LegacyAuditSinkAdapter:()=>zf,LocalAuditRecorderClient:()=>Af,MAX_CLOCK_SKEW_SECONDS:()=>zn,MIN_CLOCK_SKEW_SECONDS:()=>On,McpAuditEventAdapter:()=>Pf,MemoryAuditCheckpointObserver:()=>Tf,MemoryAuditCheckpointStore:()=>jh,MemoryAuditEvidenceProvider:()=>kh,MemoryAuditJournal:()=>bf,MemoryAuditLogProvider:()=>ci,MemoryAuditOutbox:()=>Nf,MemoryAuditProjectionProvider:()=>Bh,MemoryAuditSourceState:()=>Of,MemoryDelegationGraphStorage:()=>an,MemoryGrantStore:()=>$f,MemoryIdentityProvider:()=>Jn,MemoryNonceCacheProvider:()=>Zn,MemoryPendingFlowStore:()=>Mf,MemoryResumeTokenStore:()=>Sn,MemorySessionStore:()=>Wn,MemoryStatusListStorage:()=>sn,MemoryStorageProvider:()=>Bn,MemorySupportingAnchorProvider:()=>Cf,NONCE_LENGTH_BYTES:()=>b,NodeCryptoProvider:()=>ni,NonceCacheProvider:()=>Vn,NoopAuditLogProvider:()=>di,NoopFetchProvider:()=>oi,OUTBOUND_HEADER_NAMES:()=>Ut,PROOF_VERIFICATION_ERROR_CODES:()=>kn,PendingFlowStore:()=>Lf,ProofGenerator:()=>qt,ProofVerificationError:()=>Tn,ProofVerifier:()=>Rn,Rfc9162MerkleTree:()=>Ph,RiskClassifier:()=>Vf,RuntimeFetchProvider:()=>ri,SENSITIVE_VERBS:()=>Hf,SessionManager:()=>Gn,SessionStore:()=>qn,StatusList2021Manager:()=>Xe,StorageProvider:()=>Kn,SystemClockProvider:()=>ii,WebCryptoEvidenceEncryptor:()=>Dh,assertAuditCapabilities:()=>dh,assertHolderBinding:()=>rn,auditAnchorReceiptSchema:()=>Lp,auditBundleConsistencyProofSchema:()=>Hp,auditBundleInclusionProofSchema:()=>jp,auditBundleManifestCoreSchema:()=>Fp,auditCheckpointCoreSchema:()=>Rp,auditEntryCoreSchema:()=>Op,auditMerkleConsistencyProofSchema:()=>Up,auditMerkleInclusionProofSchema:()=>Mp,auditObservationReceiptSchema:()=>$p,auditProducerEventSchema:()=>Np,auditRecorderReceiptCoreSchema:()=>zp,auditReplayBundleSchema:()=>Zp,auditVerificationPolicySchema:()=>Wp,base58Decode:()=>mt,base58Encode:()=>gt,base64ToBytes:()=>f,base64urlDecodeToBytes:()=>u,base64urlEncodeFromBytes:()=>p,buildAuditRecord:()=>si,buildAuditRecorderReceiptCore:()=>wh,buildChainString:()=>pt,buildDelegationProofJWT:()=>lt,buildDidResolverRegistry:()=>En,buildDidWebDocument:()=>mn,buildOutboundDelegationHeaders:()=>jt,buildPolicyRequest:()=>qf,bytesToBase64:()=>h,canonicalizeJSON:()=>U,collectAuditEvidenceManifest:()=>Ih,collectAuditEvidenceRefs:()=>yh,compareDids:()=>_t,completeVCJWT:()=>H,createAuditTrail:()=>gf,createCascadingRevocationManager:()=>tt,createDefaultConsoleLogger:()=>Nt,createDelegationGraph:()=>Ze,createDelegationIssuer:()=>F,createDelegationVerifier:()=>Fe,createDidKeyResolver:()=>Lt,createDidWebResolver:()=>hn,createHandshakeRequest:()=>Yn,createKyaOsError:()=>c,createKyaOsMiddleware:()=>rg,createLocalAuditRecorder:()=>Df,createNeedsApprovalError:()=>C,createNeedsAuthorizationError:()=>k,createProofResponse:()=>Wt,createProofVerificationError:()=>Cn,createStatusListManager:()=>Qe,createUnsignedVCJWT:()=>j,didKeyFragment:()=>Tt,didWebToUrl:()=>ln,digestAuditEntry:()=>Eh,digestAuditEvent:()=>_h,digestAuditEvidenceManifest:()=>Sh,digestSchema:()=>Sp,evidenceRefSchema:()=>Dp,extractAgentId:()=>St,extractAgentSlug:()=>bt,extractCanonicalData:()=>Gt,extractDelegationFromVC:()=>v,extractProofFromMeta:()=>Mn,extractPublicKeyFromDidKey:()=>xt,generateDidKeyFromBase64:()=>kt,generateDidKeyFromBytes:()=>Dt,generateIdentity:()=>og,generateRequestProof:()=>en,getDidMethod:()=>It,getServerDid:()=>Et,hasSensitiveScopes:()=>Dn,hashAuditValue:()=>gh,isDelegationCredentialExpired:()=>I,isDelegationCredentialNotYetValid:()=>w,isDidWeb:()=>dn,isEd25519DidKey:()=>Pt,isHolderBindingApplicable:()=>nn,isIndexSet:()=>Ye,isKyaOsControlArg:()=>Xt,isNeedsApprovalError:()=>N,isNeedsAuthorizationError:()=>T,isReservedMcpMetaKey:()=>$n,isValidBase58:()=>yt,isValidDid:()=>vt,logger:()=>Ot,matchScope:()=>Qf,mergeAuditDimensions:()=>Xh,normalizeDid:()=>wt,parseAuditBundleManifestCore:()=>oh,parseAuditCheckpointCore:()=>nh,parseAuditEntryCore:()=>Qp,parseAuditObservationReceipt:()=>rh,parseAuditProducerEvent:()=>Xp,parseAuditRecorderReceiptCore:()=>th,parseAuditReplayBundle:()=>sh,parseAuditVerificationPolicy:()=>ah,parseDidWeb:()=>un,parseSignedAuditCheckpoint:()=>ih,parseSignedAuditEntry:()=>eh,parseVCJWT:()=>K,partyRefSchema:()=>kp,publicKeyToJwk:()=>$t,resolveDidKeySync:()=>Mt,scopeSatisfies:()=>eg,signedAuditCheckpointSchema:()=>Pp,signedAuditEntrySchema:()=>xp,signerRefSchema:()=>Ap,toHolderBindingRequest:()=>Qt,validateDelegationCredential:()=>_,validateDetachedProof:()=>z,validateHandshakeFormat:()=>Xn,validateMetaStructure:()=>Ln,verifyApprovalQuorum:()=>Jf,verifyAuditBundle:()=>hf,verifyDelegationAudience:()=>nt,verifyDidLinkage:()=>vn,verifyOrHints:()=>bn,withKyaOs:()=>sg,wrapDelegationAsVC:()=>y});var i={};n.r(i),n.d(i,{base64:()=>Mr,base64url:()=>Ur,bigint:()=>Wr,boolean:()=>Xr,browserEmail:()=>Nr,cidrv4:()=>$r,cidrv6:()=>Lr,cuid:()=>pr,cuid2:()=>hr,date:()=>Fr,datetime:()=>Jr,domain:()=>Hr,duration:()=>vr,e164:()=>Kr,email:()=>Ar,emoji:()=>zr,extendedDuration:()=>Ir,guid:()=>wr,hex:()=>io,hostname:()=>jr,html5Email:()=>Dr,idnEmail:()=>Cr,integer:()=>Gr,ipv4:()=>Rr,ipv6:()=>Pr,ksuid:()=>mr,lowercase:()=>to,mac:()=>xr,md5_base64:()=>ao,md5_base64url:()=>co,md5_hex:()=>so,nanoid:()=>yr,null:()=>Qr,number:()=>Yr,rfc5322Email:()=>kr,sha1_base64:()=>lo,sha1_base64url:()=>po,sha1_hex:()=>uo,sha256_base64:()=>fo,sha256_base64url:()=>go,sha256_hex:()=>ho,sha384_base64:()=>yo,sha384_base64url:()=>vo,sha384_hex:()=>mo,sha512_base64:()=>wo,sha512_base64url:()=>_o,sha512_hex:()=>Io,string:()=>qr,time:()=>Zr,ulid:()=>fr,undefined:()=>eo,unicodeEmail:()=>Tr,uppercase:()=>no,uuid:()=>_r,uuid4:()=>Er,uuid6:()=>Sr,uuid7:()=>br,xid:()=>gr});var r={};n.r(r),n.d(r,{endsWith:()=>Sc,gt:()=>oc,gte:()=>sc,includes:()=>_c,length:()=>yc,lowercase:()=>Ic,lt:()=>ic,lte:()=>rc,maxLength:()=>gc,maxSize:()=>pc,mime:()=>Ac,minLength:()=>mc,minSize:()=>hc,multipleOf:()=>lc,negative:()=>cc,nonnegative:()=>uc,nonpositive:()=>dc,normalize:()=>kc,overwrite:()=>Dc,positive:()=>ac,property:()=>bc,regex:()=>vc,size:()=>fc,slugify:()=>Oc,startsWith:()=>Ec,toLowerCase:()=>Cc,toUpperCase:()=>Nc,trim:()=>Tc,uppercase:()=>wc});var o={};n.r(o),n.d(o,{ZodISODate:()=>Fc,ZodISODateTime:()=>Kc,ZodISODuration:()=>qc,ZodISOTime:()=>Zc,date:()=>Bc,datetime:()=>Vc,duration:()=>Wc,time:()=>Jc});var s={};n.r(s),n.d(s,{ZodAny:()=>Ou,ZodArray:()=>Hu,ZodBase64:()=>Yd,ZodBase64URL:()=>Qd,ZodBigInt:()=>wu,ZodBigIntFormat:()=>Eu,ZodBoolean:()=>vu,ZodCIDRv4:()=>Jd,ZodCIDRv6:()=>Wd,ZodCUID:()=>Od,ZodCUID2:()=>Rd,ZodCatch:()=>$l,ZodCodec:()=>Kl,ZodCustom:()=>ep,ZodCustomStringFormat:()=>ou,ZodDate:()=>Uu,ZodDefault:()=>Tl,ZodDiscriminatedUnion:()=>Xu,ZodE164:()=>tu,ZodEmail:()=>gd,ZodEmoji:()=>kd,ZodEnum:()=>pl,ZodExactOptional:()=>Sl,ZodFile:()=>yl,ZodFunction:()=>Xl,ZodGUID:()=>yd,ZodIPv4:()=>Hd,ZodIPv6:()=>Bd,ZodIntersection:()=>el,ZodJWT:()=>iu,ZodKSUID:()=>Ud,ZodLazy:()=>ql,ZodLiteral:()=>gl,ZodMAC:()=>Vd,ZodMap:()=>cl,ZodNaN:()=>Ml,ZodNanoID:()=>Cd,ZodNever:()=>xu,ZodNonOptional:()=>zl,ZodNull:()=>Cu,ZodNullable:()=>Al,ZodNumber:()=>uu,ZodNumberFormat:()=>pu,ZodObject:()=>Fu,ZodOptional:()=>_l,ZodPipe:()=>jl,ZodPrefault:()=>Nl,ZodPromise:()=>Gl,ZodReadonly:()=>Fl,ZodRecord:()=>rl,ZodSet:()=>ul,ZodString:()=>pd,ZodStringFormat:()=>fd,ZodSuccess:()=>Pl,ZodSymbol:()=>Au,ZodTemplateLiteral:()=>Zl,ZodTransform:()=>Il,ZodTuple:()=>nl,ZodType:()=>ud,ZodULID:()=>xd,ZodURL:()=>bd,ZodUUID:()=>Id,ZodUndefined:()=>ku,ZodUnion:()=>qu,ZodUnknown:()=>Ru,ZodVoid:()=>Lu,ZodXID:()=>Ld,ZodXor:()=>Gu,_ZodString:()=>ld,_default:()=>Cl,_function:()=>Ql,any:()=>zu,array:()=>Ku,base64:()=>Xd,base64url:()=>eu,bigint:()=>_u,boolean:()=>Iu,catch:()=>Ll,check:()=>tp,cidrv4:()=>qd,cidrv6:()=>Gd,codec:()=>Vl,cuid:()=>zd,cuid2:()=>Pd,custom:()=>np,date:()=>ju,describe:()=>op,discriminatedUnion:()=>Qu,e164:()=>nu,email:()=>md,emoji:()=>Td,enum:()=>hl,exactOptional:()=>bl,file:()=>vl,float32:()=>fu,float64:()=>gu,function:()=>Ql,guid:()=>vd,hash:()=>du,hex:()=>cu,hostname:()=>au,httpUrl:()=>Dd,instanceof:()=>ap,int:()=>hu,int32:()=>mu,int64:()=>Su,intersection:()=>tl,ipv4:()=>Kd,ipv6:()=>Zd,json:()=>dp,jwt:()=>ru,keyof:()=>Vu,ksuid:()=>jd,lazy:()=>Wl,literal:()=>ml,looseObject:()=>Ju,looseRecord:()=>al,mac:()=>Fd,map:()=>dl,meta:()=>sp,nan:()=>Ul,nanoid:()=>Nd,nativeEnum:()=>fl,never:()=>$u,nonoptional:()=>Rl,null:()=>Nu,nullable:()=>Dl,nullish:()=>kl,number:()=>lu,object:()=>Bu,optional:()=>El,partialRecord:()=>sl,pipe:()=>Hl,prefault:()=>Ol,preprocess:()=>up,promise:()=>Yl,readonly:()=>Bl,record:()=>ol,refine:()=>ip,set:()=>ll,strictObject:()=>Zu,string:()=>hd,stringFormat:()=>su,stringbool:()=>cp,success:()=>xl,superRefine:()=>rp,symbol:()=>Du,templateLiteral:()=>Jl,transform:()=>wl,tuple:()=>il,uint32:()=>yu,uint64:()=>bu,ulid:()=>$d,undefined:()=>Tu,union:()=>Wu,unknown:()=>Pu,url:()=>Ad,uuid:()=>wd,uuidv4:()=>_d,uuidv6:()=>Ed,uuidv7:()=>Sd,void:()=>Mu,xid:()=>Md,xor:()=>Yu});const a={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 c(e,t,n){return n?{code:e,message:t,details:n}:{code:e,message:t}}function d(e){const t=g(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 u(e){const t=g(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 l(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 p(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 h(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 f(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 g(e){const t=e.length%4;return 0===t?e:e+"=".repeat((4-t)%4)}const m="https://schema.kya-os.org/v1/protocol/delegation/context/v1.0.0";function y(e,t){const n=(new Date).toISOString(),i=e.constraints.notAfter?new Date(1e3*e.constraints.notAfter).toISOString():t?.expirationDate;let r=t?.issuanceDate||n;!t?.issuanceDate&&e.createdAt&&(r=new Date(e.createdAt).toISOString());const o=t?.scopes||e.constraints.scopes;return{"@context":["https://www.w3.org/2018/credentials/v1",m],id:t?.id||e.vcId||`urn:uuid:${e.id}`,type:["VerifiableCredential","DelegationCredential"],issuer:e.issuerDid,issuanceDate:r,...void 0!==i&&{expirationDate:i},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 v(e){const t=e?.credentialSubject?.delegation;if(!t||"object"!=typeof t)throw new Error("extractDelegationFromVC: credential is missing credentialSubject.delegation");let n="";if(e.proof){const t=e.proof;n=t.proofValue||t.jws||t.signatureValue||""}return{id:t.id,issuerDid:t.issuerDid,subjectDid:t.subjectDid,controller:t.controller,vcId:e.id||`vc:${t.id}`,parentId:t.parentId,constraints:t.constraints,signature:n,status:t.status,createdAt:t.createdAt,revokedAt:void 0,revokedReason:void 0,metadata:t.metadata}}function I(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 w(e){const t=e.credentialSubject.delegation;return!!(t.constraints.notBefore&&Math.floor(Date.now()/1e3)<t.constraints.notBefore)}function _(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 i=n.delegation;return i&&"object"==typeof i?i.id&&i.issuerDid&&i.subjectDid&&i.constraints?{success:!0,data:e}:{success:!1,error:{message:"delegation fields missing"}}:{success:!1,error:{message:"credentialSubject.delegation missing"}}}const E=30,S=120,b=16,A=12e4,D=6e4;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 N(e){return"object"==typeof e&&null!==e&&"needs_approval"===e.error}const O=/^sha256:[a-f0-9]{64}$/;function z(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 i=n,r=["did","kid","nonce","audience","sessionId"];for(const e of r)if("string"!=typeof i[e]||i[e].length<1)return{success:!1,error:{message:`meta.${e} must be a non-empty string`}};if("number"!=typeof i.ts||!Number.isInteger(i.ts)||i.ts<=0)return{success:!1,error:{message:"meta.ts must be a positive integer"}};if("string"!=typeof i.requestHash||!O.test(i.requestHash))return{success:!1,error:{message:"meta.requestHash must match sha256:<64 hex chars>"}};if(void 0!==i.responseHash&&("string"!=typeof i.responseHash||!O.test(i.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!==i[e]&&"string"!=typeof i[e])return{success:!1,error:{message:`meta.${e} must be a string if present`}};return void 0===i.outcome||["allowed","denied","step_up_required","needs_authorization"].includes(i.outcome)?{success:!0,data:e}:{success:!1,error:{message:"meta.outcome must be one of allowed | denied | step_up_required | needs_authorization"}}}var R=n(77753);const P=new TextEncoder;function x(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 i=0;i<e.length;i+=1){if(!(i in e))throw new TypeError(`Cannot canonicalize sparse array element at ${t}[${i}]`);$(e[i],`${t}[${i}]`,n)}return}const i=Object.getPrototypeOf(e);if(i!==Object.prototype&&null!==i)throw new TypeError(`Cannot canonicalize non-plain object at ${t}`);for(const i of Reflect.ownKeys(e)){if("symbol"==typeof i)throw new TypeError(`Cannot canonicalize symbol-keyed property at ${t}`);if(x(i))throw new TypeError(`Cannot canonicalize object key with lone surrogate at ${t}`);const r=Object.getOwnPropertyDescriptor(e,i);if(r?.enumerable){if(!("value"in r))throw new TypeError(`Cannot canonicalize accessor property at ${t}.${i}`);$(r.value,`${t}.${i}`,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(x(e))throw new TypeError(`Cannot canonicalize string with lone surrogate at ${t}`)}function L(e){return $(e),(0,R.d)(e)}function M(e){return P.encode(L(e))}function U(e){return L(e)}function j(e,t={}){const n={alg:"EdDSA",typ:"JWT"};t.keyId&&(n.kid=t.keyId);const i="string"==typeof e.issuer?e.issuer:e.issuer?.id,r=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 a={...e};delete a.proof;const c={iss:i,vc:a};r&&(c.sub=r),o&&(c.exp=o),s&&(c.iat=s),e.id&&"string"==typeof e.id&&(c.jti=e.id);const d=l(JSON.stringify(n)),u=l(JSON.stringify(c));return{header:n,payload:c,encodedHeader:d,encodedPayload:u,signingInput:`${d}.${u}`}}function H(e,t){return`${e}.${t}`}function K(e){const t=e.split(".");if(3!==t.length)return null;try{const e=d(t[0]),n=d(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=y(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 i=this.canonicalizeVC(n),r=await this.signingFunction(i,this.identity.getDid(),this.identity.getKeyId());return{...n,proof:r}}async createAndIssueDelegation(e,t={}){const n=Date.now(),i={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(i,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 B=["id","delegation"];function Z(e,t={}){const n=_(e);if(!n.success)return{valid:!1,reason:`Schema validation failed: ${n.error?.message}`};if(I(e))return{valid:!1,reason:"Delegation credential expired"};if(w(e))return{valid:!1,reason:"Delegation credential not yet valid"};const i=e.credentialSubject.delegation;if("revoked"===i.status)return{valid:!1,reason:"Delegation status is revoked"};if("expired"===i.status)return{valid:!1,reason:"Delegation status is expired"};if(!i.issuerDid||!i.subjectDid)return{valid:!1,reason:"Missing issuer or subject DID"};if((t.requireEmbeddedProof??1)&&!e.proof)return{valid:!1,reason:"Missing proof"};const r=function(e){const t=Object.keys(e.credentialSubject).filter(e=>!B.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 r.valid?{valid:!0}:r}async function J(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 q=new TextEncoder,W=new TextDecoder;function G(...e){const t=e.reduce((e,{length:t})=>e+t,0),n=new Uint8Array(t);let i=0;for(const t of e)n.set(t,i),i+=t.length;return n}function Y(e){const t=new Uint8Array(e.length);for(let n=0;n<e.length;n++){const i=e.charCodeAt(n);if(i>127)throw new TypeError("non-ASCII string encountered in encode()");t[n]=i}return t}function X(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}function Q(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64("string"==typeof e?e:W.decode(e),{alphabet:"base64url"});let t=e;t instanceof Uint8Array&&(t=W.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/");try{return X(t)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}}function ee(e){let t=e;return"string"==typeof t&&(t=q.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 te 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 te{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"}class ie extends te{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"}class re extends te{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"}class oe extends te{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"}Symbol.asyncIterator;class se extends te{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(e="signature verification failed",t){super(e,t)}}const ae=(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},ce=e=>{const t=e.data[e.pos++];if(128&t){const n=127&t;let i=0;for(let t=0;t<n;t++)i=i<<8|e.data[e.pos++];return i}return t},de=(e,t,n)=>{if(e.data[e.pos++]!==t)throw new Error(n)},ue=(e,t)=>{const n=e.data.subarray(e.pos,e.pos+t);return e.pos+=t,n},le=(e,t,n)=>{const i=((e,t)=>X(e.replace(t,"")))(e,/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g);let r=n;return t?.startsWith?.("ECDH-ES")&&(r||={},r.getNamedCurve=e=>{const t={data:e,pos:0};return function(e){de(e,48,"Invalid PKCS#8 structure"),ce(e),de(e,2,"Expected version field");const t=ce(e);e.pos+=t,de(e,48,"Expected algorithm identifier");ce(e);e.pos}(t),(e=>{const t=(e=>{de(e,6,"Expected algorithm OID");const t=ce(e);return ue(e,t)})(e);if(ae(t,[43,101,110]))return"X25519";if(!ae(t,[42,134,72,206,61,2,1]))throw new Error("Unsupported key algorithm");de(e,6,"Expected curve OID");const n=ce(e),i=ue(e,n);for(const{name:e,oid:t}of[{name:"P-256",oid:[42,134,72,206,61,3,1,7]},{name:"P-384",oid:[43,129,4,0,34]},{name:"P-521",oid:[43,129,4,0,35]}])if(ae(i,t))return e;throw new Error("Unsupported named curve")})(t)}),(async(e,t,n,i)=>{let r,o;const s="spki"===e,a=()=>s?["verify"]:["sign"];switch(n){case"PS256":case"PS384":case"PS512":r={name:"RSA-PSS",hash:`SHA-${n.slice(-3)}`},o=a();break;case"RS256":case"RS384":case"RS512":r={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${n.slice(-3)}`},o=a();break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":r={name:"RSA-OAEP",hash:`SHA-${parseInt(n.slice(-3),10)||1}`},o=s?["encrypt","wrapKey"]:["decrypt","unwrapKey"];break;case"ES256":case"ES384":case"ES512":r={name:"ECDSA",namedCurve:{ES256:"P-256",ES384:"P-384",ES512:"P-521"}[n]},o=a();break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":try{const e=i.getNamedCurve(t);r="X25519"===e?{name:"X25519"}:{name:"ECDH",namedCurve:e}}catch(e){throw new ie("Invalid or unsupported key format")}o=s?[]:["deriveBits"];break;case"Ed25519":case"EdDSA":r={name:"Ed25519"},o=a();break;case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":r={name:n},o=a();break;default:throw new ie('Invalid or unsupported "alg" (Algorithm) value')}return crypto.subtle.importKey(e,t,r,i?.extractable??!!s,o)})("pkcs8",i,t,r)},pe='Invalid or unsupported JWK "alg" (Algorithm) Parameter value';async function he(e){if(!e.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:t,keyUsages:n}=function(e){let t,n;switch(e.kty){case"AKP":switch(e.alg){case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":t={name:e.alg},n=e.priv?["sign"]:["verify"];break;default:throw new ie(pe)}break;case"RSA":switch(e.alg){case"PS256":case"PS384":case"PS512":t={name:"RSA-PSS",hash:`SHA-${e.alg.slice(-3)}`},n=e.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":t={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.alg.slice(-3)}`},n=e.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":t={name:"RSA-OAEP",hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},n=e.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new ie(pe)}break;case"EC":switch(e.alg){case"ES256":case"ES384":case"ES512":t={name:"ECDSA",namedCurve:{ES256:"P-256",ES384:"P-384",ES512:"P-521"}[e.alg]},n=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:"ECDH",namedCurve:e.crv},n=e.d?["deriveBits"]:[];break;default:throw new ie(pe)}break;case"OKP":switch(e.alg){case"Ed25519":case"EdDSA":t={name:"Ed25519"},n=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:e.crv},n=e.d?["deriveBits"]:[];break;default:throw new ie(pe)}break;default:throw new ie('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:n}}(e),i={...e};return"AKP"!==i.kty&&delete i.alg,delete i.use,crypto.subtle.importKey("jwk",i,t,e.ext??(!e.d&&!e.priv),e.key_ops??n)}const fe=e=>"object"==typeof e&&null!==e;function ge(e){if(!fe(e)||"[object Object]"!==Object.prototype.toString.call(e))return!1;if(null===Object.getPrototypeOf(e))return!0;let t=e;for(;null!==Object.getPrototypeOf(t);)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function me(...e){const t=e.filter(Boolean);if(0===t.length||1===t.length)return!0;let n;for(const e of t){const t=Object.keys(e);if(n&&0!==n.size)for(const e of t){if(n.has(e))return!1;n.add(e)}else n=new Set(t)}return!0}const ye=e=>ge(e)&&"string"==typeof e.kty;async function ve(e,t,n){if(!ge(e))throw new TypeError("JWK must be an object");let i;switch(t??=e.alg,i??=n?.extractable??e.ext,e.kty){case"oct":if("string"!=typeof e.k||!e.k)throw new TypeError('missing "k" (Key Value) Parameter value');return Q(e.k);case"RSA":if("oth"in e&&void 0!==e.oth)throw new ie('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');return he({...e,alg:t,ext:i});case"AKP":if("string"!=typeof e.alg||!e.alg)throw new TypeError('missing "alg" (Algorithm) Parameter value');if(void 0!==t&&t!==e.alg)throw new TypeError("JWK alg and alg option value mismatch");return he({...e,ext:i});case"EC":case"OKP":return he({...e,alg:t,ext:i});default:throw new ie('Unsupported "kty" (Key Type) Parameter value')}}const Ie=(e,t="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`),we=(e,t)=>e.name===t;function _e(e,t){const n=function(e){return parseInt(e.name.slice(4),10)}(e.hash);if(n!==t)throw Ie(`SHA-${t}`,"algorithm.hash")}function Ee(e,t,n){switch(t){case"HS256":case"HS384":case"HS512":if(!we(e.algorithm,"HMAC"))throw Ie("HMAC");_e(e.algorithm,parseInt(t.slice(2),10));break;case"RS256":case"RS384":case"RS512":if(!we(e.algorithm,"RSASSA-PKCS1-v1_5"))throw Ie("RSASSA-PKCS1-v1_5");_e(e.algorithm,parseInt(t.slice(2),10));break;case"PS256":case"PS384":case"PS512":if(!we(e.algorithm,"RSA-PSS"))throw Ie("RSA-PSS");_e(e.algorithm,parseInt(t.slice(2),10));break;case"Ed25519":case"EdDSA":if(!we(e.algorithm,"Ed25519"))throw Ie("Ed25519");break;case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":if(!we(e.algorithm,t))throw Ie(t);break;case"ES256":case"ES384":case"ES512":{if(!we(e.algorithm,"ECDSA"))throw Ie("ECDSA");const n=function(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}(t);if(e.algorithm.namedCurve!==n)throw Ie(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}!function(e,t){if(t&&!e.usages.includes(t))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}(e,n)}function Se(e,t,...n){if((n=n.filter(Boolean)).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}const be=(e,t,...n)=>Se(`Key for the ${e} algorithm must be `,t,...n);function Ae(e,t){if(e.startsWith("RS")||e.startsWith("PS")){const{modulusLength:n}=t.algorithm;if("number"!=typeof n||n<2048)throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}}function De(e,t){const n=`SHA-${e.slice(-3)}`;switch(e){case"HS256":case"HS384":case"HS512":return{hash:n,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:n,name:"RSA-PSS",saltLength:parseInt(e.slice(-3),10)>>3};case"RS256":case"RS384":case"RS512":return{hash:n,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:n,name:"ECDSA",namedCurve:t.namedCurve};case"Ed25519":case"EdDSA":return{name:"Ed25519"};case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":return{name:e};default:throw new ie(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}async function ke(e,t,n){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(Se("Key must be ",t,"CryptoKey","KeyObject","JSON Web Key"));return crypto.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[n])}return Ee(t,e,n),t}function Te(e,t){if(e)throw new TypeError(`${t} can only be called once`)}function Ce(e,t,n){try{return Q(e)}catch{throw new n(`Failed to base64url decode the ${t}`)}}Symbol();const Ne=e=>{if("CryptoKey"===e?.[Symbol.toStringTag])return!0;try{return e instanceof CryptoKey}catch{return!1}},Oe=e=>"KeyObject"===e?.[Symbol.toStringTag],ze=e=>Ne(e)||Oe(e),Re=e=>e?.[Symbol.toStringTag],Pe=(e,t,n)=>{if(void 0!==t.use){let e;switch(n){case"sign":case"verify":e="sig";break;case"encrypt":case"decrypt":e="enc"}if(t.use!==e)throw new TypeError(`Invalid key for this operation, its "use" must be "${e}" when present`)}if(void 0!==t.alg&&t.alg!==e)throw new TypeError(`Invalid key for this operation, its "alg" must be "${e}" when present`);if(Array.isArray(t.key_ops)){let i;switch(!0){case"sign"===n||"verify"===n:case"dir"===e:case e.includes("CBC-HS"):i=n;break;case e.startsWith("PBES2"):i="deriveBits";break;case/^A\d{3}(?:GCM)?(?:KW)?$/.test(e):i=!e.includes("GCM")&&e.endsWith("KW")?"encrypt"===n?"wrapKey":"unwrapKey":n;break;case"encrypt"===n&&e.startsWith("RSA"):i="wrapKey";break;case"decrypt"===n:i=e.startsWith("RSA")?"unwrapKey":"deriveBits"}if(i&&!1===t.key_ops?.includes?.(i))throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${i}" when present`)}return!0};function xe(e,t,n){switch(e.substring(0,2)){case"A1":case"A2":case"di":case"HS":case"PB":((e,t,n)=>{if(!(t instanceof Uint8Array)){if(ye(t)){if((e=>"oct"===e.kty&&"string"==typeof e.k)(t)&&Pe(e,t,n))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!ze(t))throw new TypeError(be(e,t,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"));if("secret"!==t.type)throw new TypeError(`${Re(t)} instances for symmetric algorithms must be of type "secret"`)}})(e,t,n);break;default:((e,t,n)=>{if(ye(t))switch(n){case"decrypt":case"sign":if((e=>"oct"!==e.kty&&("AKP"===e.kty&&"string"==typeof e.priv||"string"==typeof e.d))(t)&&Pe(e,t,n))return;throw new TypeError("JSON Web Key for this operation must be a private JWK");case"encrypt":case"verify":if((e=>"oct"!==e.kty&&void 0===e.d&&void 0===e.priv)(t)&&Pe(e,t,n))return;throw new TypeError("JSON Web Key for this operation must be a public JWK")}if(!ze(t))throw new TypeError(be(e,t,"CryptoKey","KeyObject","JSON Web Key"));if("secret"===t.type)throw new TypeError(`${Re(t)} instances for asymmetric algorithms must not be of type "secret"`);if("public"===t.type)switch(n){case"sign":throw new TypeError(`${Re(t)} instances for asymmetric algorithm signing must be of type "private"`);case"decrypt":throw new TypeError(`${Re(t)} instances for asymmetric algorithm decryption must be of type "private"`)}if("private"===t.type)switch(n){case"verify":throw new TypeError(`${Re(t)} instances for asymmetric algorithm verifying must be of type "public"`);case"encrypt":throw new TypeError(`${Re(t)} instances for asymmetric algorithm encryption must be of type "public"`)}})(e,t,n)}}function $e(e,t,n,i,r){if(void 0!==r.crit&&void 0===i?.crit)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!i||void 0===i.crit)return new Set;if(!Array.isArray(i.crit)||0===i.crit.length||i.crit.some(e=>"string"!=typeof e||0===e.length))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let o;o=void 0!==n?new Map([...Object.entries(n),...t.entries()]):t;for(const t of i.crit){if(!o.has(t))throw new ie(`Extension Header Parameter "${t}" is not recognized`);if(void 0===r[t])throw new e(`Extension Header Parameter "${t}" is missing`);if(o.get(t)&&void 0===i[t])throw new e(`Extension Header Parameter "${t}" MUST be integrity protected`)}return new Set(i.crit)}const Le="given KeyObject instance cannot be used for this algorithm";let Me;const Ue=async(e,t,n,i=!1)=>{Me||=new WeakMap;let r=Me.get(e);if(r?.[n])return r[n];const o=await he({...t,alg:n});return i&&Object.freeze(e),r?r[n]=o:Me.set(e,{[n]:o}),o};async function je(e,t){if(e instanceof Uint8Array)return e;if(Ne(e))return e;if(Oe(e)){if("secret"===e.type)return e.export();if("toCryptoKey"in e&&"function"==typeof e.toCryptoKey)try{return((e,t)=>{Me||=new WeakMap;let n=Me.get(e);if(n?.[t])return n[t];const i="public"===e.type,r=!!i;let o;if("x25519"===e.asymmetricKeyType){switch(t){case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":break;default:throw new TypeError(Le)}o=e.toCryptoKey(e.asymmetricKeyType,r,i?[]:["deriveBits"])}if("ed25519"===e.asymmetricKeyType){if("EdDSA"!==t&&"Ed25519"!==t)throw new TypeError(Le);o=e.toCryptoKey(e.asymmetricKeyType,r,[i?"verify":"sign"])}switch(e.asymmetricKeyType){case"ml-dsa-44":case"ml-dsa-65":case"ml-dsa-87":if(t!==e.asymmetricKeyType.toUpperCase())throw new TypeError(Le);o=e.toCryptoKey(e.asymmetricKeyType,r,[i?"verify":"sign"])}if("rsa"===e.asymmetricKeyType){let n;switch(t){case"RSA-OAEP":n="SHA-1";break;case"RS256":case"PS256":case"RSA-OAEP-256":n="SHA-256";break;case"RS384":case"PS384":case"RSA-OAEP-384":n="SHA-384";break;case"RS512":case"PS512":case"RSA-OAEP-512":n="SHA-512";break;default:throw new TypeError(Le)}if(t.startsWith("RSA-OAEP"))return e.toCryptoKey({name:"RSA-OAEP",hash:n},r,i?["encrypt"]:["decrypt"]);o=e.toCryptoKey({name:t.startsWith("PS")?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:n},r,[i?"verify":"sign"])}if("ec"===e.asymmetricKeyType){const n=new Map([["prime256v1","P-256"],["secp384r1","P-384"],["secp521r1","P-521"]]).get(e.asymmetricKeyDetails?.namedCurve);if(!n)throw new TypeError(Le);const s={ES256:"P-256",ES384:"P-384",ES512:"P-521"};s[t]&&n===s[t]&&(o=e.toCryptoKey({name:"ECDSA",namedCurve:n},r,[i?"verify":"sign"])),t.startsWith("ECDH-ES")&&(o=e.toCryptoKey({name:"ECDH",namedCurve:n},r,i?[]:["deriveBits"]))}if(!o)throw new TypeError(Le);return n?n[t]=o:Me.set(e,{[t]:o}),o})(e,t)}catch(e){if(e instanceof TypeError)throw e}let n=e.export({format:"jwk"});return Ue(e,n,t)}if(ye(e))return e.k?Q(e.k):Ue(e,e,t,!0);throw new Error("unreachable")}async function He(e,t,n){if(e instanceof Uint8Array&&(e=W.decode(e)),"string"!=typeof e)throw new re("Compact JWS must be a string or Uint8Array");const{0:i,1:r,2:o,length:s}=e.split(".");if(3!==s)throw new re("Invalid Compact JWS");const a=await async function(e,t,n){if(!ge(e))throw new re("Flattened JWS must be an object");if(void 0===e.protected&&void 0===e.header)throw new re('Flattened JWS must have either of the "protected" or "header" members');if(void 0!==e.protected&&"string"!=typeof e.protected)throw new re("JWS Protected Header incorrect type");if(void 0===e.payload)throw new re("JWS Payload missing");if("string"!=typeof e.signature)throw new re("JWS Signature missing or incorrect type");if(void 0!==e.header&&!ge(e.header))throw new re("JWS Unprotected Header incorrect type");let i={};if(e.protected)try{const t=Q(e.protected);i=JSON.parse(W.decode(t))}catch{throw new re("JWS Protected Header is invalid")}if(!me(i,e.header))throw new re("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const r={...i,...e.header};let o=!0;if($e(re,new Map([["b64",!0]]),n?.crit,i,r).has("b64")&&(o=i.b64,"boolean"!=typeof o))throw new re('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:s}=r;if("string"!=typeof s||!s)throw new re('JWS "alg" (Algorithm) Header Parameter missing or invalid');const a=n&&function(e,t){if(void 0!==t&&(!Array.isArray(t)||t.some(e=>"string"!=typeof e)))throw new TypeError('"algorithms" option must be an array of strings');if(t)return new Set(t)}(0,n.algorithms);if(a&&!a.has(s))throw new ne('"alg" (Algorithm) Header Parameter value not allowed');if(o){if("string"!=typeof e.payload)throw new re("JWS Payload must be a string")}else if("string"!=typeof e.payload&&!(e.payload instanceof Uint8Array))throw new re("JWS Payload must be a string or an Uint8Array instance");let c=!1;"function"==typeof t&&(t=await t(i,e),c=!0),xe(s,t,"verify");const d=G(void 0!==e.protected?Y(e.protected):new Uint8Array,Y("."),"string"==typeof e.payload?o?Y(e.payload):q.encode(e.payload):e.payload),u=Ce(e.signature,"signature",re),l=await je(t,s),p=await async function(e,t,n,i){const r=await ke(e,t,"verify");Ae(e,r);const o=De(e,r.algorithm);try{return await crypto.subtle.verify(o,r,n,i)}catch{return!1}}(s,l,u,d);if(!p)throw new se;let h;h=o?Ce(e.payload,"payload",re):"string"==typeof e.payload?q.encode(e.payload):e.payload;const f={payload:h};return void 0!==e.protected&&(f.protectedHeader=i),void 0!==e.header&&(f.unprotectedHeader=e.header),c?{...f,key:l}:f}({payload:r,protected:i,signature:o},t,n),c={payload:a.payload,protectedHeader:a.protectedHeader};return"function"==typeof t?{...c,key:a.key}:c}function Ke(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 Ve{didResolver;statusListResolver;signatureVerifier;cache=new Map;cacheInsertionOrder=[];cacheTtl;maxCacheSize;constructor(e){this.didResolver=e?.didResolver,this.statusListResolver=e?.statusListResolver,this.signatureVerifier=e?.signatureVerifier,this.cacheTtl=e?.cacheTtl||6e4,this.maxCacheSize=e?.maxCacheSize??1e3}async verifyDelegationCredential(e,t={}){const n=Date.now(),i=this.cacheKeyForCredential("di",e,t);if(null!==i){const e=this.getFromCache(i);if(e)return{...e,cached:!0}}const r=Date.now(),o=Z(e),s=Date.now()-r;if(!o.valid)return{valid:!1,reason:o.reason,stage:"basic",metrics:{basicCheckMs:s,totalMs:Date.now()-n},checks:{basicValid:!1}};const a=t.skipSignature?Promise.resolve({valid:!0,durationMs:0}):async function(e,t,n){const i=Date.now();try{const r="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()-i};const o=await t.resolve(r);if(!o)return{valid:!1,reason:`Could not resolve issuer DID: ${r}`,durationMs:Date.now()-i};if(!e.proof)return{valid:!1,reason:"Proof is missing",durationMs:Date.now()-i};const s=e.proof.verificationMethod;if(!s)return{valid:!1,reason:"Proof missing verificationMethod",durationMs:Date.now()-i};const a=function(e,t){return e.verificationMethod?.find(e=>e.id===t)}(o,s);if(!a)return{valid:!1,reason:`Verification method ${s} not found`,durationMs:Date.now()-i};const c=a.publicKeyJwk;if(!c)return{valid:!1,reason:"Verification method missing publicKeyJwk",durationMs:Date.now()-i};const d=await n(e,c);return{valid:d.valid,reason:d.reason,durationMs:Date.now()-i}}catch(e){return{valid:!1,reason:`Signature verification error: ${e instanceof Error?e.message:"Unknown error"}`,durationMs:Date.now()-i}}}(e,t.didResolver||this.didResolver,this.signatureVerifier),c=!t.skipStatus&&e.credentialStatus?J(e.credentialStatus,t.statusListResolver||this.statusListResolver):Promise.resolve({valid:!0,durationMs:0});return this.finalizeVerification(a,c,s,n,i)}async verifyDelegationJwt(e,t={}){const n=Date.now(),i=function(e,t){const n=K(e);if(!n)return{failure:Ke("Not a valid VC-JWT (parse failed)",t)};const i=Date.now(),r=n.payload.vc,o=Z(r,{requireEmbeddedProof:!1}),s=Date.now()-i;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}(r)!==n.payload.iss?{failure:Ke("Credential `issuer` does not match the JWT `iss` (the verified signer)",t,s)}:{vc:r,issuerDid:n.payload.iss,kid:n.header.kid,basicCheckMs:s}:{failure:Ke(o.reason,t,s)}}(e,n);if("failure"in i)return i.failure;const{vc:r,issuerDid:o,kid:s,basicCheckMs:a}=i,c=this.cacheKeyForJwt(e,r,t);if(null!==c){const e=this.getFromCache(c);if(e)return{...e,cached:!0}}const d=t.skipSignature?Promise.resolve({valid:!0,durationMs:0}):async function(e,t,n,i){const r=Date.now(),o=(e,t)=>({valid:e,reason:t,durationMs:Date.now()-r});if(!i)return o(!1,"No DID resolver configured — signature cannot be verified");const s=await i.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");if(!a.publicKeyJwk)return o(!1,"Verification method missing publicKeyJwk");try{const t=await ve(a.publicKeyJwk,"EdDSA");return await He(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&&r.credentialStatus?J(r.credentialStatus,t.statusListResolver||this.statusListResolver):Promise.resolve({valid:!0,durationMs:0});return this.finalizeVerification(d,u,a,n,c)}async finalizeVerification(e,t,n,i,r){const[o,s]=await Promise.all([e,t]),a=function(e,t,n,i){const r=e.valid&&t.valid;return{valid:r,reason:r?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()-i},checks:{basicValid:!0,signatureValid:e.valid,statusValid:t.valid}}}(o,s,n,i);return a.valid&&null!==r&&this.setInCache(r,a),a}cacheKeyForCredential(e,t,n){if(!this.cacheAllowed(n))return null;try{return`${e}\0${t.id??""}\0${this.verificationProfile(n)}\0${L(t)}`}catch{return null}}cacheKeyForJwt(e,t,n){return this.cacheAllowed(n)?`jwt\0${t.id??""}\0${this.verificationProfile(n)}\0${e}`:null}cacheAllowed(e){return!e.skipCache&&void 0===e.didResolver&&void 0===e.statusListResolver}verificationProfile(e){return`signature:${e.skipSignature?"skip":"verify"}|status:${e.skipStatus?"skip":"verify"}`}getFromCache(e){const t=this.cache.get(e);return t?Date.now()>t.expiresAt?(this.cache.delete(e),null):t.result:null}setInCache(e,t){for(;this.cache.size>=this.maxCacheSize&&this.cacheInsertionOrder.length>0;){const e=this.cacheInsertionOrder.shift();e&&this.cache.delete(e)}this.cache.set(e,{result:t,expiresAt:Date.now()+this.cacheTtl}),this.cacheInsertionOrder.push(e)}clearCache(){this.cache.clear(),this.cacheInsertionOrder=[]}clearCacheEntry(e){const t=`di\0${e}\0`,n=`jwt\0${e}\0`;for(const e of[...this.cache.keys()]){if(!e.startsWith(t)&&!e.startsWith(n))continue;this.cache.delete(e);const i=this.cacheInsertionOrder.indexOf(e);-1!==i&&this.cacheInsertionOrder.splice(i,1)}}}function Fe(e){return new Ve(e)}class Be{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],i=t[e];if(i.issuerDid!==n.subjectDid)return{valid:!1,reason:`Invalid chain: ${i.id} issued by ${i.issuerDid} but parent ${n.id} subject is ${n.subjectDid}`};if(i.parentId!==n.id)return{valid:!1,reason:`Invalid chain: ${i.id} parentId=${i.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 Ze(e){return new Be(e)}const Je=16777216,qe="u";class We{compressor;bits;size;constructor(e,t,n){this.compressor=t,this.size=e;const i=Math.ceil(e/8);this.bits=new Uint8Array(i)}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),i=e%8;t?this.bits[n]|=128>>i:this.bits[n]&=255^128>>i}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 qe+this.base64urlEncode(e)}static async decode(e,t,n){const i=await Ge(e,n),r=8*i.length,o=new We(r,t,n);return o.bits=i,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,i){const r=new We(e,n,i);for(const e of t)r.setBit(e,!0);return r}}async function Ge(e,t){const n=await t.decompress(function(e){let t=(e[0]===qe?e.slice(1):e).replace(/-/g,"+").replace(/_/g,"/");t+="=".repeat((4-t.length%4)%4);const n=atob(t),i=new Uint8Array(n.length);for(let e=0;e<n.length;e++)i[e]=n.charCodeAt(e);return i}(e));if(n.length>Je)throw new Error(`Status list too large: ${n.length} bytes exceeds ${Je}`);return n}async function Ye(e,t,n){const i=await Ge(e,n),r=Math.floor(t/8),o=t%8;if(!Number.isInteger(t)||t<0||r>=i.length)throw new Error(`Bit index ${t} out of range for the status list`);return!!(i[r]&128>>o)}class Xe{storage;identity;signingFunction;compressor;decompressor;statusListBaseUrl;defaultListSize;updateLocks=new Map;constructor(e,t,n,i,r,o){this.storage=e,this.identity=t,this.signingFunction=n,this.compressor=i,this.decompressor=r,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,i=(this.updateLocks.get(n)??Promise.resolve()).then(()=>this.doUpdateStatus(e,t));this.updateLocks.set(n,i.catch(()=>{})),await i}async doUpdateStatus(e,t){const{statusListCredential:n,statusListIndex:i}=e,r=await this.storage.getStatusList(n);if(!r)throw new Error(`Status list not found: ${n}`);const o=await We.decode(r.credentialSubject.encodedList,this.compressor,this.decompressor),s=parseInt(i,10);o.setBit(s,t);const a=await o.encode(),c={...r,credentialSubject:{...r.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,i=await this.storage.getStatusList(t);if(!i)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}"`)}(i.credentialSubject.statusPurpose,e.statusPurpose);const r=await We.decode(i.credentialSubject.encodedList,this.compressor,this.decompressor);if(!/^[0-9]+$/.test(n))throw new Error(`Invalid statusListIndex "${n}" — must be a canonical non-negative decimal`);const o=Number(n);if(!Number.isSafeInteger(o))throw new Error(`statusListIndex "${n}" exceeds the safe integer range`);return r.getBit(o)}async getRevokedIndices(e){const t=await this.storage.getStatusList(e);return t?(await We.decode(t.credentialSubject.encodedList,this.compressor,this.decompressor)).getSetBits():[]}async ensureStatusListExists(e,t){if(await this.storage.getStatusList(e))return;const n=new We(this.defaultListSize,this.compressor,this.decompressor),i=await n.encode(),r={"@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:i}},o=U(r),s=await this.signingFunction(o,this.identity.getDid(),this.identity.getKeyId()),a={...r,proof:s};await this.storage.setStatusList(e,a)}getStatusListBaseUrl(){return this.statusListBaseUrl}getDefaultListSize(){return this.defaultListSize}}function Qe(e,t,n,i,r,o){return new Xe(e,t,n,i,r,o)}class et{graph;statusList;constructor(e,t){this.graph=e,this.statusList=t}async revokeDelegation(e,t={}){const n=t.maxDepth||100,i=[],r=await this.graph.getNode(e);if(!r)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(r,!0,t.reason,t.dryRun);i.push(s),t.onRevoke&&await t.onRevoke(s);const a=await this.graph.getDescendants(e);for(const n of a){const r=await this.revokeNode(n,!1,`Cascaded from ${e}`,t.dryRun,e);i.push(r),t.onRevoke&&await t.onRevoke(r)}return i}async revokeNode(e,t,n,i,r){const o={delegationId:e.id,isRoot:t,parentId:r,timestamp:Date.now(),reason:n};if(i)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,i]=t;return{id:e,type:"StatusList2021Entry",statusPurpose:"revocation",statusListIndex:parseInt(i,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 tt(e,t){return new et(e,t)}function nt(e,t){if(!e.constraints.audience)return!0;const n=e.constraints.audience;return"string"==typeof n?n===t:n.includes(t)}class it{#e;#t;#n;constructor(e){if(!(e instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this.#e=e}setProtectedHeader(e){return Te(this.#t,"setProtectedHeader"),this.#t=e,this}setUnprotectedHeader(e){return Te(this.#n,"setUnprotectedHeader"),this.#n=e,this}async sign(e,t){if(!this.#t&&!this.#n)throw new re("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!me(this.#t,this.#n))throw new re("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const n={...this.#t,...this.#n};let i=!0;if($e(re,new Map([["b64",!0]]),t?.crit,this.#t,n).has("b64")&&(i=this.#t.b64,"boolean"!=typeof i))throw new re('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:r}=n;if("string"!=typeof r||!r)throw new re('JWS "alg" (Algorithm) Header Parameter missing or invalid');let o,s,a,c;xe(r,e,"sign"),i?(o=ee(this.#e),s=Y(o)):(s=this.#e,o=""),this.#t?(a=ee(JSON.stringify(this.#t)),c=Y(a)):(a="",c=new Uint8Array);const d=G(c,Y("."),s),u=await je(e,r),l=await async function(e,t,n){const i=await ke(e,t,"sign");Ae(e,i);const r=await crypto.subtle.sign(De(e,i.algorithm),i,n);return new Uint8Array(r)}(r,u,d),p={signature:ee(l),payload:o};return this.#n&&(p.header=this.#n),this.#t&&(p.protected=a),p}}class rt{#i;constructor(e){this.#i=new it(e)}setProtectedHeader(e){return this.#i.setProtectedHeader(e),this}async sign(e,t){const n=await this.#i.sign(e,t);if(void 0===n.payload)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${n.protected}.${n.payload}.${n.signature}`}}const ot=e=>Math.floor(e.getTime()/1e3),st=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;function at(e){const t=st.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");const n=parseFloat(t[2]);let i;switch(t[3].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":i=Math.round(n);break;case"minute":case"minutes":case"min":case"mins":case"m":i=Math.round(60*n);break;case"hour":case"hours":case"hr":case"hrs":case"h":i=Math.round(3600*n);break;case"day":case"days":case"d":i=Math.round(86400*n);break;case"week":case"weeks":case"w":i=Math.round(604800*n);break;default:i=Math.round(31557600*n)}return"-"===t[1]||"ago"===t[4]?-i:i}function ct(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}class dt{#e;constructor(e){if(!ge(e))throw new TypeError("JWT Claims Set MUST be an object");this.#e=structuredClone(e)}data(){return q.encode(JSON.stringify(this.#e))}get iss(){return this.#e.iss}set iss(e){this.#e.iss=e}get sub(){return this.#e.sub}set sub(e){this.#e.sub=e}get aud(){return this.#e.aud}set aud(e){this.#e.aud=e}set jti(e){this.#e.jti=e}set nbf(e){"number"==typeof e?this.#e.nbf=ct("setNotBefore",e):e instanceof Date?this.#e.nbf=ct("setNotBefore",ot(e)):this.#e.nbf=ot(new Date)+at(e)}set exp(e){"number"==typeof e?this.#e.exp=ct("setExpirationTime",e):e instanceof Date?this.#e.exp=ct("setExpirationTime",ot(e)):this.#e.exp=ot(new Date)+at(e)}set iat(e){void 0===e?this.#e.iat=ot(new Date):e instanceof Date?this.#e.iat=ct("setIssuedAt",ot(e)):this.#e.iat=ct("setIssuedAt","string"==typeof e?ot(new Date)+at(e):e)}}class ut{#t;#r;constructor(e={}){this.#r=new dt(e)}setIssuer(e){return this.#r.iss=e,this}setSubject(e){return this.#r.sub=e,this}setAudience(e){return this.#r.aud=e,this}setJti(e){return this.#r.jti=e,this}setNotBefore(e){return this.#r.nbf=e,this}setExpirationTime(e){return this.#r.exp=e,this}setIssuedAt(e){return this.#r.iat=e,this}setProtectedHeader(e){return this.#t=e,this}async sign(e,t){const n=new rt(this.#r.data());if(n.setProtectedHeader(this.#t),Array.isArray(this.#t?.crit)&&this.#t.crit.includes("b64")&&!1===this.#t.b64)throw new oe("JWTs MUST NOT use unencoded payload");return n.sign(e,t)}}async function lt(e){const{agentDid:t,userDid:n,delegationId:i,delegationChain:r,scopes:o,privateKeyJwk:s,kid:a,targetHostname:c}=e,d=await ve(s,"EdDSA"),u=Math.floor(Date.now()/1e3),l=u+60;return await new ut({delegation_id:i,delegation_chain:r,scope:o.join(",")}).setProtectedHeader({alg:"EdDSA",kid:a}).setIssuer(t).setSubject(n).setJti(crypto.randomUUID()).setAudience(c).setIssuedAt(u).setExpirationTime(l).sign(d)}function pt(e){return e.id||e.vcId?e.vcId?`${e.vcId}>${e.id}`:e.id:""}const ht="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",ft=new Map;for(let e=0;e<ht.length;e++){const t=ht[e];void 0!==t&&ft.set(t,e)}function gt(e){if(0===e.length)return"";let t=BigInt(0);for(let n=0;n<e.length;n++){const i=e[n];void 0!==i&&(t=t*BigInt(256)+BigInt(i))}let n="";for(;t>0;)n=ht[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 mt(e){if(0===e.length)return new Uint8Array(0);let t=BigInt(0);for(const n of e){const e=ft.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 i=0;for(const t of e){if("1"!==t)break;i++}const r=new Uint8Array(i+n.length);return r.set(n,i),r}function yt(e){if(0===e.length)return!0;for(const t of e)if(!ft.has(t))return!1;return!0}function vt(e){return"string"==typeof e&&e.startsWith("did:")}function It(e){if(!vt(e))return null;const t=e.match(/^did:([^:]+):/);return t?.[1]??null}function wt(e){return e.trim()}function _t(e,t){return wt(e)===wt(t)}function Et(e){const t=e.identity.serverDid||e.identity.agentDid;if(!t)throw new Error("Server DID not configured");return t}function St(e){const t=e.split(":");return t[t.length-1]??e}function bt(e){return St(e)}const At=new Uint8Array([237,1]);function Dt(e){const t=new Uint8Array(At.length+e.length);return t.set(At),t.set(e,At.length),`did:key:z${gt(t)}`}function kt(e){return Dt(Uint8Array.from(atob(e),e=>e.charCodeAt(0)))}function Tt(e){return e.startsWith("did:key:")?e.slice(8):"keys-1"}const Ct={debug:10,info:20,warn:30,error:40};function Nt(){let e="info",t=!1;function n(n,...i){if(function(t){return Ct[t]>=Ct[e]}(n))if(t)console.error(...i);else switch(n){case"debug":"function"==typeof console.debug?console.debug(...i):console.log(...i);break;case"info":"function"==typeof console.info?console.info(...i):console.log(...i);break;case"warn":"function"==typeof console.warn?console.warn(...i):console.error(...i);break;case"error":console.error(...i)}}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 Ot=Nt(),zt=new Uint8Array([237,1]),Rt=32;function Pt(e){return e.startsWith("did:key:z6Mk")}function xt(e){if(!e.startsWith("did:key:z"))return null;try{const t=mt(e.replace("did:key:","").slice(1));return t.length<zt.length+Rt||t[0]!==zt[0]||t[1]!==zt[1]?null:t.slice(zt.length)}catch(e){return Ot.debug("Failed to extract public key from did:key",e),null}}function $t(e){return{kty:"OKP",crv:"Ed25519",x:p(e)}}function Lt(){return{resolve:async e=>{if(!Pt(e))return null;const t=xt(e);if(!t)return null;const n=$t(t),i=e.replace("did:key:",""),r=Tt(e);return{id:e,verificationMethod:[{id:`${e}#${r}`,type:"Ed25519VerificationKey2020",controller:e,publicKeyJwk:n,publicKeyMultibase:i}],authentication:[`${e}#${r}`],assertionMethod:[`${e}#${r}`]}}}}function Mt(e){if(!Pt(e))return null;const t=xt(e);if(!t)return null;const n=$t(t),i=e.replace("did:key:",""),r=Tt(e);return{id:e,verificationMethod:[{id:`${e}#${r}`,type:"Ed25519VerificationKey2020",controller:e,publicKeyJwk:n,publicKeyMultibase:i}],authentication:[`${e}#${r}`],assertionMethod:[`${e}#${r}`]}}const Ut={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 jt(e){const{session:t,delegation:n,serverIdentity:i,targetUrl:r}=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 Ot.warn("Failed to parse target URL, using as-is",{url:e}),e}}(r),s=function(e,t){const n=f(e),i=64===n.length?n.subarray(0,32):n;if(!Pt(t))throw new Error(`Server DID must be did:key with Ed25519: ${t}`);const r=xt(t);if(!r)throw new Error(`Failed to extract public key from DID: ${t}`);return{kty:"OKP",crv:"Ed25519",x:p(r),d:p(i)}}(i.privateKey,i.did),a=await lt({agentDid:i.did,userDid:t.agentDid,delegationId:n.id,delegationChain:n.vcId,scopes:["delegation:propagate"],privateKeyJwk:s,kid:i.kid,targetHostname:o});return Ot.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 Ht{cryptoProvider;constructor(e){this.cryptoProvider=e}async verifyEd25519(e,t,n){try{return!0===await this.cryptoProvider.verify(e,t,n)}catch(e){return Ot.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,i,r]=t;let o,s,a;try{o=JSON.parse(d(n))}catch(e){throw new Error(`Invalid header base64: ${e instanceof Error?e.message:String(e)}`)}if(i)try{s=JSON.parse(d(i))}catch(e){throw new Error(`Invalid payload base64: ${e instanceof Error?e.message:String(e)}`)}try{a=u(r)}catch(e){throw new Error(`Invalid signature base64: ${e instanceof Error?e.message:String(e)}`)}return{header:o,payload:s,signatureBytes:a,signingInput:`${n}.${i}`}}async verifyJWS(e,t,n){try{if(!this.isValidEd25519JWK(t))return Ot.error("[CryptoService] Invalid Ed25519 JWK format"),!1;if(n?.expectedKid&&t.kid!==n.expectedKid)return Ot.error("[CryptoService] Key ID mismatch"),!1;let i;try{i=this.parseJWS(e)}catch(t){if(void 0===n?.detachedPayload)return Ot.error("[CryptoService] Invalid JWS format:",t),!1;{const n=e.split(".");if(3!==n.length||""!==n[1])return Ot.error("[CryptoService] Invalid JWS format:",t),!1;try{const e=n[0],t=n[2];i={header:JSON.parse(d(e)),payload:void 0,signatureBytes:u(t),signingInput:""}}catch{return Ot.error("[CryptoService] Invalid detached JWS format"),!1}}}const r=n?.alg||"EdDSA";if(i.header.alg!==r)return Ot.error(`[CryptoService] Unsupported algorithm: ${i.header.alg}, expected ${r}`),!1;if(void 0!==n?.expectedKid&&i.header.kid!==n.expectedKid)return Ot.error("[CryptoService] Protected JWS key ID mismatch"),!1;let o,s;if(void 0!==n?.detachedPayload){const t=e.split(".")[0];let i;i=n.detachedPayload instanceof Uint8Array?p(n.detachedPayload):p((new TextEncoder).encode(n.detachedPayload)),o=(new TextEncoder).encode(`${t}.${i}`)}else{if(!i.signingInput)return Ot.error("[CryptoService] Missing signing input for compact JWS"),!1;o=(new TextEncoder).encode(i.signingInput)}try{s=this.jwkToBase64PublicKey(t)}catch(e){return Ot.error("[CryptoService] Failed to extract public key:",e),!1}return await this.verifyEd25519(o,i.signatureBytes,s)}catch(e){return Ot.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=u(e.x);if(32!==t.length)throw new Error(`Invalid Ed25519 public key length: ${t.length}`);return h(t)}}const Kt=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]),Vt=12,Ft=32,Bt="org.kya-os/proof",Zt="proof";async function Jt(e,t,n){const i={method:e.method,...e.params?{params:e.params}:{}},r=await n(M(i));return void 0===t?{requestHash:r}:{requestHash:r,responseHash:await n(M(t.data))}}class qt{identity;cryptoProvider;constructor(e,t){this.identity=e,this.cryptoProvider=t}async generateProof(e,t,n,i={}){const r=await this.generateCanonicalHashes(e,t),o=p(await this.cryptoProvider.randomBytes(16)),s={did:this.identity.did,kid:this.identity.kid,ts:Math.floor(Date.now()/1e3),nonce:o,audience:n.audience,sessionId:n.sessionId,requestHash:r.requestHash,...void 0!==r.responseHash?{responseHash:r.responseHash}:{},...i};return{jws:await this.generateJWS(s),meta:s}}async hashRequest(e){return(await this.generateCanonicalHashes(e)).requestHash}async generateCanonicalHashes(e,t){return Jt(e,t,e=>this.cryptoProvider.hash(e))}async resolveSigningKey(){const e=this.identity.privateKey;return"string"==typeof e?async function(e){if("string"!=typeof e||0!==e.indexOf("-----BEGIN PRIVATE KEY-----"))throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return le(e,"EdDSA",void 0)}(this.formatPrivateKeyAsPEM(e)):e}async generateJWS(e){try{const t=await this.resolveSigningKey(),n=L({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}}),i=(new TextEncoder).encode(n);return await new rt(i).setProtectedHeader({alg:"EdDSA",kid:this.identity.kid}).sign(t)}catch(e){throw new Error(`Failed to generate JWS: ${e instanceof Error?e.message:"Unknown error"}`)}}formatPrivateKeyAsPEM(e){const t=f(e).subarray(0,Ft),n=new Uint8Array(Kt.length+t.length);n.set(Kt),n.set(t,Kt.length);const i=h(n);return"-----BEGIN PRIVATE KEY-----\n"+(i.match(/.{1,64}/g)?.join("\n")??i)+"\n-----END PRIVATE KEY-----"}async verifyProof(e,t,n){try{const i=await this.generateCanonicalHashes(t,n);if(e.meta.requestHash!==i.requestHash)return!1;if(void 0!==e.meta.responseHash&&(void 0===i.responseHash||e.meta.responseHash!==i.responseHash))return!1;const r=this.base64PublicKeyToJWK(this.identity.publicKey);return new Ht(this.cryptoProvider).verifyJWS(e.jws,r,{expectedKid:this.identity.kid,alg:"EdDSA"})}catch{return!1}}base64PublicKeyToJWK(e){const t=f(e);if(t.length!==Ft)throw new Error(`Invalid Ed25519 public key length: ${t.length}`);return{kty:"OKP",crv:"Ed25519",x:p(t),kid:this.identity.kid}}}async function Wt(e,t,n,i,r,o={}){const s={data:t},a=new qt(n,r),c=await a.generateProof(e,s,i,o);return s.meta={proof:c},s}function Gt(e,t){return{request:{method:e.method,...e.params?{params:e.params}:{}},response:t.data}}const Yt="_kyaos";function Xt(e){return e.startsWith(Yt)}function Qt(e,t){const n={};for(const[e,i]of Object.entries(t))Xt(e)||(n[e]=i);return{method:e,params:n}}async function en(e){const{identity:t,crypto:n,toolName:i,args:r,audience:o,sessionId:s}=e,a=new qt(t,n),c=Qt(i,r),d=p(await n.randomBytes(16)),u=Math.floor(Date.now()/1e3);return a.generateProof(c,void 0,{sessionId:s??"",audience:o,nonce:d,timestamp:u,createdAt:u,lastActivity:u,ttlMinutes:30,identityState:"anonymous"})}const tn="holder_binding_failed";function nn(e){return null!==xt(e)}async function rn(e){const{proof:t,subjectDid:n,request:i,response:r,expectedAudience:o,proofVerifier:s}=e,a=xt(n);if(!a)return{status:"not_applicable",reason:`Holder binding (phase 1) covers did:key subjects only; "${It(n)??"unknown"}" is deferred to cnf-based binding`};if("object"!=typeof t?.meta||null===t.meta)return{status:"unbound",errorCode:tn,reason:"Malformed proof: missing meta"};if(t.meta.did!==n)return{status:"unbound",errorCode:tn,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:tn,reason:"Proof audience does not match this server",cause:"audience_mismatch"};const c=$t(a);c.kid=`${n}#${Tt(n)}`;const d=await s.verifyProof(t,c,{request:i,...void 0!==r?{response:r}:{}});return d.valid?{status:"bound"}:{status:"unbound",errorCode:tn,reason:"Request proof is not bound to the delegation subject",...void 0!==d.errorCode?{cause:d.errorCode}:{}}}function on(e){return structuredClone(e)}class sn{statusLists=new Map;versions=new Map;indexCounters=new Map;async getStatusList(e){const t=this.statusLists.get(e);return void 0===t?null:on(t)}async setStatusList(e,t){const n=on(t);this.statusLists.set(e,n);const i=this.versions.get(e)??[];i.push(n),this.versions.set(e,i)}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:on(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 an{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],i=new Set;for(;n.length>0;){const e=n.shift();if(i.has(e))continue;i.add(e);const r=this.nodes.get(e);if(r)for(const e of r.children)if(!i.has(e)){n.push(e);const i=this.nodes.get(e);i&&t.push(i)}}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 i=0;for(const t of e){const e=this.getChainSync(t.id);i=Math.max(i,e.length-1)}return{totalNodes:e.length,rootNodes:t,leafNodes:n,maxDepth:i}}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 cn(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 dn(e){return e.startsWith("did:web:")}function un(e){if(!dn(e))return null;const t=e.slice(8);if(0===t.length)return null;const n=t.split(":"),i=decodeURIComponent(n[0]);return 0===i.length?null:{domain:i,path:n.slice(1).map(e=>decodeURIComponent(e))}}function ln(e){const t=un(e);if(!t)return null;const{domain:n,path:i}=t;let r=`https://${n}`;return 0===i.length?r+="/.well-known/did.json":r+="/"+i.join("/")+"/did.json",r}class pn{fetchProvider;cache;cacheTtl;constructor(e,t){this.fetchProvider=e,this.cache=new Map,this.cacheTtl=t?.cacheTtl??3e5}async resolve(e){if(!dn(e))return null;const t=this.cache.get(e);if(t&&Date.now()<t.expiresAt)return t.document;const n=ln(e);if(!n)return Ot.warn(`[DidWebResolver] Invalid did:web format: ${e}`),null;try{const t=await this.fetchProvider.fetch(n);if(!t.ok)return Ot.warn(`[DidWebResolver] HTTP ${t.status} fetching ${n}`),null;let i;try{i=await t.json()}catch{return Ot.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(!cn(e))return!1}return!0}(i)?i.id!==e?(Ot.warn(`[DidWebResolver] DID Document id mismatch: expected ${e}, got ${i.id}`),null):(this.cache.set(e,{document:i,expiresAt:Date.now()+this.cacheTtl}),i):(Ot.warn(`[DidWebResolver] Invalid DID Document structure from ${n}`),null)}catch(t){return Ot.warn(`[DidWebResolver] Error resolving ${e}: ${t instanceof Error?t.message:"Unknown error"}`),null}}clearCache(){this.cache.clear()}clearCacheEntry(e){this.cache.delete(e)}}function hn(e,t){return new pn(e,t)}const fn=new Uint8Array([237,1]),gn=["https://www.w3.org/ns/did/v1","https://w3id.org/security/suites/ed25519-2020/v1"];function mn(e,t){const n=Array.isArray(e)?e:[e],i=n[0];if(!i)throw new Error("buildDidWebDocument: at least one identity is required");const r=i.did;if(!dn(r))throw new Error(`buildDidWebDocument: identity.did must be a did:web DID (got "${r}")`);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=f(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:$t(n),publicKeyMultibase:yn(n)}}(e,r)),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:r,...t?.alsoKnownAs?.length?{alsoKnownAs:[...t.alsoKnownAs]}:{},verificationMethod:o,authentication:s,assertionMethod:s}}function yn(e){const t=new Uint8Array(fn.length+e.length);return t.set(fn),t.set(e,fn.length),`z${gt(t)}`}function vn(e){const t=e.requireBidirectional??!0,n=wn(e.primaryDid),i=wn(e.secondaryDid),r=e.primaryDidDocument,o=e.secondaryDidDocument,s={primaryReferencesSecondary:!1,secondaryReferencesPrimary:!1,primaryDocumentMatches:!1,secondaryDocumentMatches:!1};return _n(r)?_n(o)?(s.primaryDocumentMatches=wn(r.id)===n,s.secondaryDocumentMatches=wn(o.id)===i,s.primaryDocumentMatches&&s.secondaryDocumentMatches?(s.primaryReferencesSecondary=In(r,i),s.secondaryReferencesPrimary=In(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 In(e,t){return(e.alsoKnownAs??[]).some(e=>wn(e)===t)}function wn(e){return e.trim()}function _n(e){return!!function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}(e)&&"string"==typeof e.id&&0!==e.id.trim().length&&(void 0===e.alsoKnownAs||Array.isArray(e.alsoKnownAs)&&e.alsoKnownAs.every(e=>"string"==typeof e))}function En(e,t){const n={};if(!e)return n;for(const[i,r]of Object.entries(e))/^[a-z0-9]+$/.test(i)&&("function"!=typeof r?n[i]=r:t&&(n[i]=r(t)));return n}class Sn{tokens=new Map;ttl;constructor(e=6e5){this.ttl=e}async create(e,t,n){const i=new Uint8Array(16);globalThis.crypto.getRandomValues(i);const r=`rt_${Array.from(i).map(e=>e.toString(16).padStart(2,"0")).join("")}`,o=Date.now();return this.tokens.set(r,{agentDid:e,scopes:t,createdAt:o,expiresAt:o+this.ttl,metadata:n,fulfilled:!1}),r}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 bn(e,t,n){const i=Date.now();let r,o;if(n.debug&&Ot.debug(`[AuthHandshake] Verifying ${e} for scopes: ${t.join(", ")}`),n.reputationService&&void 0!==n.authorization.minReputationScore){const i=n.authorization.unknownAgentPolicy??"require-consent";try{r=await async function(e,t){const n=t.apiUrl.replace(/\/$/,""),i={"Content-Type":"application/json"};let r;if(t.apiKey&&(i["X-API-Key"]=t.apiKey),r="v2"===t.apiFormat?await fetch(`${n}/v1/reputation/${encodeURIComponent(e)}`,{method:"POST",headers:i,body:JSON.stringify({include_details:!1})}):await fetch(`${n}/api/v1/reputation/${encodeURIComponent(e)}`,{method:"GET",headers:i}),!r.ok){if(404===r.status)return{agentDid:e,score:null,totalInteractions:0,successRate:0,riskLevel:"unknown",updatedAt:Date.now()};throw new Error(`Reputation API error: ${r.status} ${r.statusText}`)}const o=await r.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){Ot.error("[AuthHandshake] Reputation service unreachable, treating agent as unknown:",t),r={agentDid:e,score:null,totalInteractions:0,successRate:0,riskLevel:"unknown",updatedAt:Date.now()}}if(n.debug&&Ot.debug(`[AuthHandshake] Reputation score: ${r.score}`),null===r.score){if("deny"===i)return{authorized:!1,authError:await An(e,t,n,"Unknown agent denied by policy"),reputation:r,reason:"Unknown agent — policy: deny"};if("require-consent"===i)return{authorized:!1,authError:await An(e,t,n,"Unknown agent requires consent"),reputation:r,reason:"Unknown agent — policy: require-consent"};n.debug&&Ot.debug("[AuthHandshake] Unknown agent allowed by policy, skipping reputation gate")}if(null!==r.score&&r.score<n.authorization.minReputationScore)return n.debug&&Ot.debug(`[AuthHandshake] Reputation ${r.score} < ${n.authorization.minReputationScore}, requiring authorization`),{authorized:!1,authError:await An(e,t,n,"Agent reputation score below threshold"),reputation:r,reason:"Low reputation score"}}try{o=await n.delegationVerifier.verify(e,t)}catch(i){Ot.error("[AuthHandshake] Delegation verification failed:",i);const r=`Delegation verification error: ${i instanceof Error?i.message:"Unknown error"}`;return{authorized:!1,authError:await An(e,t,n,r),reason:r}}return o.valid&&o.delegation?(n.debug&&Ot.debug(`[AuthHandshake] Delegation valid, authorized (${Date.now()-i}ms)`),{authorized:!0,delegation:o.delegation,credential:o.credential,reputation:r,reason:"Valid delegation found"}):(n.debug&&Ot.debug(`[AuthHandshake] No delegation found, returning needs_authorization (${Date.now()-i}ms)`),{authorized:!1,authError:await An(e,t,n,o.reason??"No valid delegation found"),reputation:r,reason:o.reason??"No delegation"})}async function An(e,t,n,i){const r=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",r);const a={title:"Authorization Required",hint:["link","qr"],authorizationCode:r.substring(0,8).toUpperCase(),qrUrl:`https://api.qrserver.com/v1/create-qr-code/?data=${encodeURIComponent(s.toString())}`};return k({message:i,authorizationUrl:s.toString(),resumeToken:r,expiresAt:o,scopes:t,display:a})}function Dn(e){const t=["write","delete","admin","payment","transfer","execute","modify"];return e.some(e=>t.some(t=>e.toLowerCase().includes(t)))}const kn={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 Tn extends Error{code;details;constructor(e,t,n){super(t),this.code=e,this.details=n,this.name="ProofVerificationError"}}function Cn(e,t,n){return new Tn(e,t,n)}const Nn=120,On=30,zn=600;class Rn{cryptoService;clock;nonceCache;fetch;timestampSkewSeconds;nonceTtlSeconds;cryptoProvider;constructor(e){this.cryptoService=new Ht(e.cryptoProvider),this.cryptoProvider=e.cryptoProvider,this.clock=e.clockProvider,this.nonceCache=e.nonceCacheProvider,this.fetch=e.fetchProvider,this.timestampSkewSeconds=e.timestampSkewSeconds??Nn,this.nonceTtlSeconds=e.nonceTtlSeconds??300}setTimestampSkew(e){"number"==typeof e&&Number.isFinite(e)&&(this.timestampSkewSeconds=Math.max(On,Math.min(zn,Math.floor(e))))}getTimestampSkew(){return this.timestampSkewSeconds}async verifyProof(e,t,n){try{const i=await this.validateProofStructure(e);if(!i.valid)return i;const r=i.proof,o=this.buildCanonicalPayload(r.meta),s=(new TextEncoder).encode(o);return await this.runVerificationPipeline(r,t,s,n)}catch(e){return this.handleVerificationError(e)}}async verifyProofArtifact(e,t,n){try{const i=await this.validateProofStructure(e);if(!i.valid)return i;const r=i.proof,o=(new TextEncoder).encode(this.buildCanonicalPayload(r.meta)),s=await this.verifySignature(r.jws,t,o,r.meta.kid);return s.valid?void 0!==n?this.validateContentBinding(r,n):{valid:!0}:s}catch(e){return this.handleVerificationError(e)}}async verifyProofDetached(e,t,n){try{const i=t instanceof Uint8Array?t:(new TextEncoder).encode(t);return await this.runVerificationPipeline(e,n,i)}catch(e){return this.handleVerificationError(e)}}async runVerificationPipeline(e,t,n,i){const r=await this.validateProofStructure(e);if(!r.valid)return r;const o=r.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!==i){const e=await this.validateContentBinding(o,i);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:i}=await Jt(t.request,t.response,e=>this.cryptoProvider.hash(e));if(e.meta.requestHash!==n)return{valid:!1,reason:"Request hash mismatch: the proof does not bind the request you supplied",errorCode:kn.CONTENT_BINDING_MISMATCH};const r=void 0!==e.meta.responseHash;return r!==(void 0!==t.response)?{valid:!1,reason:r?"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:kn.CONTENT_BINDING_MISMATCH}:r&&e.meta.responseHash!==i?{valid:!1,reason:"Response hash mismatch: received content differs from what the server signed (possible substitution / MITM)",errorCode:kn.CONTENT_BINDING_MISMATCH}:{valid:!0}}handleVerificationError(e){return{valid:!1,reason:"Proof verification error",errorCode:kn.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=z(e);return t.success?{valid:!0,proof:t.data}:{valid:!1,reason:"Invalid proof structure",errorCode:kn.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:kn.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:kn.TIMESTAMP_SKEW_EXCEEDED,details:{timestamp:e,timestampMs:t,skewSeconds:this.timestampSkewSeconds,currentTime:this.clock.now()}}}async verifySignature(e,t,n,i){return await this.cryptoService.verifyJWS(e,t,{detachedPayload:n,expectedKid:i,alg:"EdDSA"})?{valid:!0}:{valid:!1,reason:"Invalid JWS signature",errorCode:kn.INVALID_JWS_SIGNATURE,details:{jwsLength:e.length,expectedKid:i,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 Tn(kn.DID_DOCUMENT_NOT_FOUND,`DID document not found: ${e}`,{did:e});const i=n;if(!i.verificationMethod||0===i.verificationMethod.length)throw new Tn(kn.VERIFICATION_METHOD_NOT_FOUND,`No verification methods found in DID document: ${e}`,{did:e});let r;if(t){const n=t.startsWith("#")?t:`#${t}`;if(r=i.verificationMethod.find(t=>t.id===n||t.id===`${e}${n}`),!r)throw new Tn(kn.VERIFICATION_METHOD_NOT_FOUND,`Verification method not found for kid: ${t}`,{did:e,kid:t,availableKids:i.verificationMethod.map(e=>e.id)})}else r=i.verificationMethod[0];if(!r?.publicKeyJwk)throw new Tn(kn.PUBLIC_KEY_NOT_FOUND,"Public key JWK not found in verification method",{did:e,kid:t,verificationMethodId:r?.id});const o=r.publicKeyJwk;if("OKP"!==o.kty||"Ed25519"!==o.crv||!o.x)throw new Tn(kn.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&&r.id&&(s.kid=r.id),s}catch(n){if(n instanceof Tn)throw n;throw Ot.error("[ProofVerifier] Failed to fetch public key from DID",{error:n}),new Tn(kn.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 L({aud:e.audience,sub:e.did,iss:e.did,requestHash:e.requestHash,...void 0!==e.responseHash&&{responseHash:e.responseHash},ts:e.ts,nonce:e.nonce,sessionId:e.sessionId,...e.scopeId&&{scopeId:e.scopeId},...e.delegationRef&&{delegationRef:e.delegationRef},...e.clientDid&&{clientDid:e.clientDid},...e.outcome&&{outcome:e.outcome},...e.reason&&{reason:e.reason}})}}const Pn=["io.modelcontextprotocol/"],xn=["traceparent","tracestate","baggage"];function $n(e){return xn.includes(e)||Pn.some(t=>e.startsWith(t))}function Ln(e,t="strict"){const n=Object.keys(e).filter(e=>e!==Bt&&e!==Zt);return"allow-extensions"===t&&n.length>0?{valid:!0,extraKeys:n}:{valid:!0}}function Mn(e,t="strict"){const n=e[Bt]??e[Zt];if(!n)return{success:!1,reason:"_meta does not contain a proof",errorCode:kn.MISSING_REQUIRED_FIELD};Ln(e,t);const i=z(n);return i.success?{success:!0,proof:i.data}:{success:!1,reason:i.error?.message??"Invalid proof structure",errorCode:kn.INVALID_PROOF_STRUCTURE}}class Un{}class jn{}class Hn{}class Kn{}class Vn{}class Fn{}class Bn extends Kn{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 Zn extends Vn{nonces=new Map;async has(e,t){const n=t?`nonce:${t}:${e}`:`nonce:${e}`,i=this.nonces.get(n);return!(!i||Date.now()>i&&(this.nonces.delete(n),1))}async add(e,t,n){const i=n?`nonce:${n}:${e}`:`nonce:${e}`,r=Date.now()+1e3*t;this.nonces.set(i,r)}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 Jn extends Fn{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}#${Tt(t)}`,privateKey:e.privateKey,publicKey:e.publicKey,createdAt:(new Date).toISOString(),type:"development"}}generateDIDFromPublicKey(e){return kt(e)}}class qn{}class Wn extends qn{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 Gn{config;cryptoProvider;sessionStore;constructor(e,t={}){this.cryptoProvider=e,this.sessionStore=t.sessionStore??new Wn({maxSessions:t.maxSessions??1e4}),this.config={timestampSkewSeconds:t.timestampSkewSeconds??120,sessionTtlMinutes:t.sessionTtlMinutes??30,nonceCache:t.nonceCache??new Zn,metaPolicy:t.metaPolicy??"strict",...void 0!==t.absoluteSessionLifetime&&{absoluteSessionLifetime:t.absoluteSessionLifetime},...void 0!==t.serverDid&&{serverDid:t.serverDid}},this.config.nonceCache instanceof Zn&&Ot.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:a.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:a.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:a.nonce_replay,message:"Nonce already used (replay attack prevention)",remediation:"Generate a new unique nonce for each request"}};const i=e.agentDid?A:D,r=Math.ceil(i/1e3);await this.config.nonceCache.add(e.nonce,r,e.agentDid);const o=await this.generateSessionId(),s=await this.buildClientInfo(e),c={sessionId:o,audience:e.audience,nonce:e.nonce,timestamp:e.timestamp,createdAt:t,lastActivity:t,ttlMinutes:this.config.sessionTtlMinutes,identityState:"anonymous",metaPolicy:this.config.metaPolicy,agentDid:e.agentDid,...this.config.serverDid&&{serverDid:this.config.serverDid},...s&&{clientInfo:s}};return await this.sessionStore.set(o,c),{success:!0,session:c}}catch(e){return{success:!1,error:{code:a.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 i=e-n.lastActivity>60*n.ttlMinutes;i||void 0===this.config.absoluteSessionLifetime||(i=e-n.createdAt>60*this.config.absoluteSessionLifetime),i&&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 Yn(e){return{nonce:Gn.generateNonce(),audience:e,timestamp:Math.floor(Date.now()/1e3)}}function Xn(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 Qn=n(77598);const ei=Buffer.from("302e020100300506032b657004220420","hex"),ti=Buffer.from("302a300506032b6570032100","hex");class ni extends Un{async sign(e,t){const n=Buffer.from(t,"base64"),i=64===n.length?n.subarray(0,32):n,r=(0,Qn.createPrivateKey)({key:Buffer.concat([ei,i]),format:"der",type:"pkcs8"});return new Uint8Array((0,Qn.sign)(null,Buffer.from(e),r))}async verify(e,t,n){try{const i=(0,Qn.createPublicKey)({key:Buffer.concat([ti,Buffer.from(n,"base64")]),format:"der",type:"spki"});return(0,Qn.verify)(null,Buffer.from(e),i,Buffer.from(t))}catch{return!1}}async generateKeyPair(){const{publicKey:e,privateKey:t}=(0,Qn.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,Qn.createHash)("sha256").update(Buffer.from(e)).digest("hex")}`}async randomBytes(e){return new Uint8Array((0,Qn.randomBytes)(e))}}class ii extends jn{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 ri extends Hn{didKeyResolver=Lt();didWebResolver;didResolvers;allowPrivateNetworkHosts;constructor(e){super(),this.allowPrivateNetworkHosts=e?.allowPrivateNetworkHosts??!1,this.didResolvers=En(e?.didResolvers,this)}async resolveDID(e){const t=It(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):dn(e)?this.isBlockedTarget(ln(e))?null:(this.didWebResolver||(this.didWebResolver=hn(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 i=n;return"StatusList2021"===i.type&&"string"==typeof i.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 i=Number(n[1]),r=Number(n[2]);return 127===i||10===i||0===i||169===i&&254===r||192===i&&168===r||172===i&&r>=16&&r<=31}(t)}}class oi extends Hn{async resolveDID(e){return null}async fetchStatusList(e){return null}async fetchDelegationChain(e){return[]}async fetch(e,t){throw new Error("fetch unavailable")}}function si(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 ai{}class ci extends ai{records=[];events=[];loggedSessions=new Set;async logAuditRecord(e){const t=e.session.sessionId;this.loggedSessions.has(t)||(this.loggedSessions.add(t),this.records.push(si(e)))}async logEvent(e){this.events.push(e)}}class di extends ai{async logAuditRecord(e){}async logEvent(e){}}const ui=["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 li(e,t,n){function i(n,i){if(n._zod||Object.defineProperty(n,"_zod",{value:{def:i,constr:s,traits:new Set},enumerable:!1}),n._zod.traits.has(e))return;n._zod.traits.add(e),t(n,i);const r=s.prototype,o=Object.keys(r);for(let e=0;e<o.length;e++){const t=o[e];t in n||(n[t]=r[t].bind(n))}}const r=n?.Parent??Object;class o extends r{}function s(e){var t;const r=n?.Parent?new o:this;i(r,e),(t=r._zod).deferred??(t.deferred=[]);for(const e of r._zod.deferred)e();return r}return Object.defineProperty(o,"name",{value:e}),Object.defineProperty(s,"init",{value:i}),Object.defineProperty(s,Symbol.hasInstance,{value:t=>!!(n?.Parent&&t instanceof n.Parent)||t?._zod?.traits?.has(e)}),Object.defineProperty(s,"name",{value:e}),s}Object.freeze({status:"aborted"}),Symbol("zod_brand");class pi extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class hi extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}}const fi={};function gi(e){return e&&Object.assign(fi,e),fi}function mi(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 yi(e,t="|"){return e.map(e=>Li(e)).join(t)}function vi(e,t){return"bigint"==typeof t?t.toString():t}function Ii(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function wi(e){return null==e}function _i(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}const Ei=Symbol("evaluating");function Si(e,t,n){let i;Object.defineProperty(e,t,{get(){if(i!==Ei)return void 0===i&&(i=Ei,i=n()),i},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function bi(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Ai(...e){const t={};for(const n of e){const e=Object.getOwnPropertyDescriptors(n);Object.assign(t,e)}return Object.defineProperties({},t)}function Di(e){return JSON.stringify(e)}const ki="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Ti(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}const Ci=Ii(()=>{if("undefined"!=typeof navigator&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function Ni(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 Oi(e){return Ni(e)?{...e}:Array.isArray(e)?[...e]:e}const zi=new Set(["string","number","symbol"]),Ri=new Set(["string","number","bigint","boolean","symbol","undefined"]);function Pi(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function xi(e,t,n){const i=new e._zod.constr(t??e._zod.def);return t&&!n?.parent||(i._zod.parent=e),i}function $i(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 Li(e){return"bigint"==typeof e?e.toString()+"n":"string"==typeof e?`"${e}"`:`${e}`}const Mi={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]},Ui={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function ji(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 Hi(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function Ki(e){return"string"==typeof e?e:e?.message}function Vi(e,t,n){const i={...e,path:e.path??[]};if(!e.message){const r=Ki(e.inst?._zod.def?.error?.(e))??Ki(t?.error?.(e))??Ki(n.customError?.(e))??Ki(n.localeError?.(e))??"Invalid input";i.message=r}return delete i.inst,delete i.continue,t?.reportInput||delete i.input,i}function Fi(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function Bi(e){return Array.isArray(e)?"array":"string"==typeof e?"string":"unknown"}function Zi(...e){const[t,n,i]=e;return"string"==typeof t?{message:t,code:"custom",input:n,inst:i}:{...t}}const Ji=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,vi,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},qi=li("$ZodError",Ji),Wi=li("$ZodError",Ji,{Parent:Error}),Gi=e=>(t,n,i,r)=>{const o=i?Object.assign(i,{async:!1}):{async:!1},s=t._zod.run({value:n,issues:[]},o);if(s instanceof Promise)throw new pi;if(s.issues.length){const t=new(r?.Err??e)(s.issues.map(e=>Vi(e,o,gi())));throw ki(t,r?.callee),t}return s.value},Yi=Gi(Wi),Xi=e=>async(t,n,i,r)=>{const o=i?Object.assign(i,{async:!0}):{async:!0};let s=t._zod.run({value:n,issues:[]},o);if(s instanceof Promise&&(s=await s),s.issues.length){const t=new(r?.Err??e)(s.issues.map(e=>Vi(e,o,gi())));throw ki(t,r?.callee),t}return s.value},Qi=Xi(Wi),er=e=>(t,n,i)=>{const r=i?{...i,async:!1}:{async:!1},o=t._zod.run({value:n,issues:[]},r);if(o instanceof Promise)throw new pi;return o.issues.length?{success:!1,error:new(e??qi)(o.issues.map(e=>Vi(e,r,gi())))}:{success:!0,data:o.value}},tr=er(Wi),nr=e=>async(t,n,i)=>{const r=i?Object.assign(i,{async:!0}):{async:!0};let o=t._zod.run({value:n,issues:[]},r);return o instanceof Promise&&(o=await o),o.issues.length?{success:!1,error:new e(o.issues.map(e=>Vi(e,r,gi())))}:{success:!0,data:o.value}},ir=nr(Wi),rr=e=>(t,n,i)=>{const r=i?Object.assign(i,{direction:"backward"}):{direction:"backward"};return Gi(e)(t,n,r)},or=e=>(t,n,i)=>Gi(e)(t,n,i),sr=e=>async(t,n,i)=>{const r=i?Object.assign(i,{direction:"backward"}):{direction:"backward"};return Xi(e)(t,n,r)},ar=e=>async(t,n,i)=>Xi(e)(t,n,i),cr=e=>(t,n,i)=>{const r=i?Object.assign(i,{direction:"backward"}):{direction:"backward"};return er(e)(t,n,r)},dr=e=>(t,n,i)=>er(e)(t,n,i),ur=e=>async(t,n,i)=>{const r=i?Object.assign(i,{direction:"backward"}):{direction:"backward"};return nr(e)(t,n,r)},lr=e=>async(t,n,i)=>nr(e)(t,n,i),pr=/^[cC][^\s-]{8,}$/,hr=/^[0-9a-z]+$/,fr=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,gr=/^[0-9a-vA-V]{20}$/,mr=/^[A-Za-z0-9]{27}$/,yr=/^[a-zA-Z0-9_-]{21}$/,vr=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Ir=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,wr=/^([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})$/,_r=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)$/,Er=_r(4),Sr=_r(6),br=_r(7),Ar=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Dr=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,kr=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,Tr=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,Cr=Tr,Nr=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,Or="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function zr(){return new RegExp(Or,"u")}const Rr=/^(?:(?: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])$/,Pr=/^(([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}|:))$/,xr=e=>{const t=Pi(e??":");return new RegExp(`^(?:[0-9A-F]{2}${t}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${t}){5}[0-9a-f]{2}$`)},$r=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,Lr=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Mr=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Ur=/^[A-Za-z0-9_-]*$/,jr=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,Hr=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,Kr=/^\+[1-9]\d{6,14}$/,Vr="(?:(?:\\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])))",Fr=new RegExp(`^${Vr}$`);function Br(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}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Zr(e){return new RegExp(`^${Br(e)}$`)}function Jr(e){const t=Br({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const i=`${t}(?:${n.join("|")})`;return new RegExp(`^${Vr}T(?:${i})$`)}const qr=e=>new RegExp(`^${e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*"}$`),Wr=/^-?\d+n?$/,Gr=/^-?\d+$/,Yr=/^-?\d+(?:\.\d+)?$/,Xr=/^(?:true|false)$/i,Qr=/^null$/i,eo=/^undefined$/i,to=/^[^A-Z]*$/,no=/^[^a-z]*$/,io=/^[0-9a-fA-F]*$/;function ro(e,t){return new RegExp(`^[A-Za-z0-9+/]{${e}}${t}$`)}function oo(e){return new RegExp(`^[A-Za-z0-9_-]{${e}}$`)}const so=/^[0-9a-fA-F]{32}$/,ao=ro(22,"=="),co=oo(22),uo=/^[0-9a-fA-F]{40}$/,lo=ro(27,"="),po=oo(27),ho=/^[0-9a-fA-F]{64}$/,fo=ro(43,"="),go=oo(43),mo=/^[0-9a-fA-F]{96}$/,yo=ro(64,""),vo=oo(64),Io=/^[0-9a-fA-F]{128}$/,wo=ro(86,"=="),_o=oo(86),Eo=li("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),So={number:"number",bigint:"bigint",object:"date"},bo=li("$ZodCheckLessThan",(e,t)=>{Eo.init(e,t);const n=So[typeof t.value];e._zod.onattach.push(e=>{const n=e._zod.bag,i=(t.inclusive?n.maximum:n.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<i&&(t.inclusive?n.maximum=t.value:n.exclusiveMaximum=t.value)}),e._zod.check=i=>{(t.inclusive?i.value<=t.value:i.value<t.value)||i.issues.push({origin:n,code:"too_big",maximum:"object"==typeof t.value?t.value.getTime():t.value,input:i.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Ao=li("$ZodCheckGreaterThan",(e,t)=>{Eo.init(e,t);const n=So[typeof t.value];e._zod.onattach.push(e=>{const n=e._zod.bag,i=(t.inclusive?n.minimum:n.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>i&&(t.inclusive?n.minimum=t.value:n.exclusiveMinimum=t.value)}),e._zod.check=i=>{(t.inclusive?i.value>=t.value:i.value>t.value)||i.issues.push({origin:n,code:"too_small",minimum:"object"==typeof t.value?t.value.getTime():t.value,input:i.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Do=li("$ZodCheckMultipleOf",(e,t)=>{Eo.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?n.value%t.value===BigInt(0):0===function(e,t){const n=(e.toString().split(".")[1]||"").length,i=t.toString();let r=(i.split(".")[1]||"").length;if(0===r&&/\d?e-\d?/.test(i)){const e=i.match(/\d?e-(\d?)/);e?.[1]&&(r=Number.parseInt(e[1]))}const o=n>r?n:r;return Number.parseInt(e.toFixed(o).replace(".",""))%Number.parseInt(t.toFixed(o).replace(".",""))/10**o}(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=li("$ZodCheckNumberFormat",(e,t)=>{Eo.init(e,t),t.format=t.format||"float64";const n=t.format?.includes("int"),i=n?"int":"number",[r,o]=Mi[t.format];e._zod.onattach.push(e=>{const i=e._zod.bag;i.format=t.format,i.minimum=r,i.maximum=o,n&&(i.pattern=Gr)}),e._zod.check=s=>{const a=s.value;if(n){if(!Number.isInteger(a))return void s.issues.push({expected:i,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:i,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:i,inclusive:!0,continue:!t.abort}))}a<r&&s.issues.push({origin:"number",input:a,code:"too_small",minimum:r,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=li("$ZodCheckBigIntFormat",(e,t)=>{Eo.init(e,t);const[n,i]=Ui[t.format];e._zod.onattach.push(e=>{const r=e._zod.bag;r.format=t.format,r.minimum=n,r.maximum=i}),e._zod.check=r=>{const o=r.value;o<n&&r.issues.push({origin:"bigint",input:o,code:"too_small",minimum:n,inclusive:!0,inst:e,continue:!t.abort}),o>i&&r.issues.push({origin:"bigint",input:o,code:"too_big",maximum:i,inclusive:!0,inst:e,continue:!t.abort})}}),Co=li("$ZodCheckMaxSize",(e,t)=>{var n;Eo.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!wi(t)&&void 0!==t.size}),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 i=n.value;i.size<=t.maximum||n.issues.push({origin:Fi(i),code:"too_big",maximum:t.maximum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),No=li("$ZodCheckMinSize",(e,t)=>{var n;Eo.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!wi(t)&&void 0!==t.size}),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 i=n.value;i.size>=t.minimum||n.issues.push({origin:Fi(i),code:"too_small",minimum:t.minimum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),Oo=li("$ZodCheckSizeEquals",(e,t)=>{var n;Eo.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!wi(t)&&void 0!==t.size}),e._zod.onattach.push(e=>{const n=e._zod.bag;n.minimum=t.size,n.maximum=t.size,n.size=t.size}),e._zod.check=n=>{const i=n.value,r=i.size;if(r===t.size)return;const o=r>t.size;n.issues.push({origin:Fi(i),...o?{code:"too_big",maximum:t.size}:{code:"too_small",minimum:t.size},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),zo=li("$ZodCheckMaxLength",(e,t)=>{var n;Eo.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!wi(t)&&void 0!==t.length}),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 i=n.value;if(i.length<=t.maximum)return;const r=Bi(i);n.issues.push({origin:r,code:"too_big",maximum:t.maximum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),Ro=li("$ZodCheckMinLength",(e,t)=>{var n;Eo.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!wi(t)&&void 0!==t.length}),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 i=n.value;if(i.length>=t.minimum)return;const r=Bi(i);n.issues.push({origin:r,code:"too_small",minimum:t.minimum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),Po=li("$ZodCheckLengthEquals",(e,t)=>{var n;Eo.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!wi(t)&&void 0!==t.length}),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 i=n.value,r=i.length;if(r===t.length)return;const o=Bi(i),s=r>t.length;n.issues.push({origin:o,...s?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),xo=li("$ZodCheckStringFormat",(e,t)=>{var n,i;Eo.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})}):(i=e._zod).check??(i.check=()=>{})}),$o=li("$ZodCheckRegex",(e,t)=>{xo.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})}}),Lo=li("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=to),xo.init(e,t)}),Mo=li("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=no),xo.init(e,t)}),Uo=li("$ZodCheckIncludes",(e,t)=>{Eo.init(e,t);const n=Pi(t.includes),i=new RegExp("number"==typeof t.position?`^.{${t.position}}${n}`:n);t.pattern=i,e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(i)}),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})}}),jo=li("$ZodCheckStartsWith",(e,t)=>{Eo.init(e,t);const n=new RegExp(`^${Pi(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})}}),Ho=li("$ZodCheckEndsWith",(e,t)=>{Eo.init(e,t);const n=new RegExp(`.*${Pi(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})}});function Ko(e,t,n){e.issues.length&&t.issues.push(...Hi(n,e.issues))}const Vo=li("$ZodCheckProperty",(e,t)=>{Eo.init(e,t),e._zod.check=e=>{const n=t.schema._zod.run({value:e.value[t.property],issues:[]},{});if(n instanceof Promise)return n.then(n=>Ko(n,e,t.property));Ko(n,e,t.property)}}),Fo=li("$ZodCheckMimeType",(e,t)=>{Eo.init(e,t);const n=new Set(t.mime);e._zod.onattach.push(e=>{e._zod.bag.mime=t.mime}),e._zod.check=i=>{n.has(i.value.type)||i.issues.push({code:"invalid_value",values:t.mime,input:i.value.type,inst:e,continue:!t.abort})}}),Bo=li("$ZodCheckOverwrite",(e,t)=>{Eo.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});class Zo{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}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)),i=t.map(e=>e.slice(n)).map(e=>" ".repeat(2*this.indent)+e);for(const e of i)this.content.push(e)}compile(){const e=Function,t=this?.args;return new e(...t,[...(this?.content??[""]).map(e=>` ${e}`)].join("\n"))}}const Jo={major:4,minor:3,patch:6},qo=li("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Jo;const i=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&i.unshift(e);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=(e,t,n)=>{let i,r=ji(e);for(const o of t){if(o._zod.def.when){if(!o._zod.def.when(e))continue}else if(r)continue;const t=e.issues.length,s=o._zod.check(e);if(s instanceof Promise&&!1===n?.async)throw new pi;if(i||s instanceof Promise)i=(i??Promise.resolve()).then(async()=>{await s,e.issues.length!==t&&(r||(r=ji(e,t)))});else{if(e.issues.length===t)continue;r||(r=ji(e,t))}}return i?i.then(()=>e):e},n=(n,r,o)=>{if(ji(n))return n.aborted=!0,n;const s=t(r,i,o);if(s instanceof Promise){if(!1===o.async)throw new pi;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 pi;return s.then(e=>t(e,i,o))}return t(s,i,o)}}Si(e,"~standard",()=>({validate:t=>{try{const n=tr(e,t);return n.success?{value:n.data}:{issues:n.error?.issues}}catch(n){return ir(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:"zod",version:1}))}),Wo=li("$ZodString",(e,t)=>{qo.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??qr(e._zod.bag),e._zod.parse=(n,i)=>{if(t.coerce)try{n.value=String(n.value)}catch(i){}return"string"==typeof n.value||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),Go=li("$ZodStringFormat",(e,t)=>{xo.init(e,t),Wo.init(e,t)}),Yo=li("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=wr),Go.init(e,t)}),Xo=li("$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=_r(e))}else t.pattern??(t.pattern=_r());Go.init(e,t)}),Qo=li("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Ar),Go.init(e,t)}),es=li("$ZodURL",(e,t)=>{Go.init(e,t),e._zod.check=n=>{try{const i=n.value.trim(),r=new URL(i);return t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(r.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&&(t.protocol.lastIndex=0,t.protocol.test(r.protocol.endsWith(":")?r.protocol.slice(0,-1):r.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(t.normalize?n.value=r.href:n.value=i)}catch(i){n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),ts=li("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=zr()),Go.init(e,t)}),ns=li("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=yr),Go.init(e,t)}),is=li("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=pr),Go.init(e,t)}),rs=li("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=hr),Go.init(e,t)}),os=li("$ZodULID",(e,t)=>{t.pattern??(t.pattern=fr),Go.init(e,t)}),ss=li("$ZodXID",(e,t)=>{t.pattern??(t.pattern=gr),Go.init(e,t)}),as=li("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=mr),Go.init(e,t)}),cs=li("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=Jr(t)),Go.init(e,t)}),ds=li("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Fr),Go.init(e,t)}),us=li("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=Zr(t)),Go.init(e,t)}),ls=li("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=vr),Go.init(e,t)}),ps=li("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=Rr),Go.init(e,t),e._zod.bag.format="ipv4"}),hs=li("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=Pr),Go.init(e,t),e._zod.bag.format="ipv6",e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}}),fs=li("$ZodMAC",(e,t)=>{t.pattern??(t.pattern=xr(t.delimiter)),Go.init(e,t),e._zod.bag.format="mac"}),gs=li("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=$r),Go.init(e,t)}),ms=li("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=Lr),Go.init(e,t),e._zod.check=n=>{const i=n.value.split("/");try{if(2!==i.length)throw new Error;const[e,t]=i;if(!t)throw new Error;const n=Number(t);if(`${n}`!==t)throw new Error;if(n<0||n>128)throw new Error;new URL(`http://[${e}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function ys(e){if(""===e)return!0;if(e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}const vs=li("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=Mr),Go.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=n=>{ys(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}}),Is=li("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Ur),Go.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=n=>{(function(e){if(!Ur.test(e))return!1;const t=e.replace(/[-_]/g,e=>"-"===e?"+":"/");return ys(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})}}),ws=li("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Kr),Go.init(e,t)}),_s=li("$ZodJWT",(e,t)=>{Go.init(e,t),e._zod.check=n=>{(function(e,t=null){try{const n=e.split(".");if(3!==n.length)return!1;const[i]=n;if(!i)return!1;const r=JSON.parse(atob(i));return!("typ"in r&&"JWT"!==r?.typ||!r.alg||t&&(!("alg"in r)||r.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})}}),Es=li("$ZodCustomStringFormat",(e,t)=>{Go.init(e,t),e._zod.check=n=>{t.fn(n.value)||n.issues.push({code:"invalid_format",format:t.format,input:n.value,inst:e,continue:!t.abort})}}),Ss=li("$ZodNumber",(e,t)=>{qo.init(e,t),e._zod.pattern=e._zod.bag.pattern??Yr,e._zod.parse=(n,i)=>{if(t.coerce)try{n.value=Number(n.value)}catch(e){}const r=n.value;if("number"==typeof r&&!Number.isNaN(r)&&Number.isFinite(r))return n;const o="number"==typeof r?Number.isNaN(r)?"NaN":Number.isFinite(r)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:r,inst:e,...o?{received:o}:{}}),n}}),bs=li("$ZodNumberFormat",(e,t)=>{ko.init(e,t),Ss.init(e,t)}),As=li("$ZodBoolean",(e,t)=>{qo.init(e,t),e._zod.pattern=Xr,e._zod.parse=(n,i)=>{if(t.coerce)try{n.value=Boolean(n.value)}catch(e){}const r=n.value;return"boolean"==typeof r||n.issues.push({expected:"boolean",code:"invalid_type",input:r,inst:e}),n}}),Ds=li("$ZodBigInt",(e,t)=>{qo.init(e,t),e._zod.pattern=Wr,e._zod.parse=(n,i)=>{if(t.coerce)try{n.value=BigInt(n.value)}catch(e){}return"bigint"==typeof n.value||n.issues.push({expected:"bigint",code:"invalid_type",input:n.value,inst:e}),n}}),ks=li("$ZodBigIntFormat",(e,t)=>{To.init(e,t),Ds.init(e,t)}),Ts=li("$ZodSymbol",(e,t)=>{qo.init(e,t),e._zod.parse=(t,n)=>{const i=t.value;return"symbol"==typeof i||t.issues.push({expected:"symbol",code:"invalid_type",input:i,inst:e}),t}}),Cs=li("$ZodUndefined",(e,t)=>{qo.init(e,t),e._zod.pattern=eo,e._zod.values=new Set([void 0]),e._zod.optin="optional",e._zod.optout="optional",e._zod.parse=(t,n)=>{const i=t.value;return void 0===i||t.issues.push({expected:"undefined",code:"invalid_type",input:i,inst:e}),t}}),Ns=li("$ZodNull",(e,t)=>{qo.init(e,t),e._zod.pattern=Qr,e._zod.values=new Set([null]),e._zod.parse=(t,n)=>{const i=t.value;return null===i||t.issues.push({expected:"null",code:"invalid_type",input:i,inst:e}),t}}),Os=li("$ZodAny",(e,t)=>{qo.init(e,t),e._zod.parse=e=>e}),zs=li("$ZodUnknown",(e,t)=>{qo.init(e,t),e._zod.parse=e=>e}),Rs=li("$ZodNever",(e,t)=>{qo.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:e}),t)}),Ps=li("$ZodVoid",(e,t)=>{qo.init(e,t),e._zod.parse=(t,n)=>{const i=t.value;return void 0===i||t.issues.push({expected:"void",code:"invalid_type",input:i,inst:e}),t}}),xs=li("$ZodDate",(e,t)=>{qo.init(e,t),e._zod.parse=(n,i)=>{if(t.coerce)try{n.value=new Date(n.value)}catch(e){}const r=n.value,o=r instanceof Date;return o&&!Number.isNaN(r.getTime())||n.issues.push({expected:"date",code:"invalid_type",input:r,...o?{received:"Invalid Date"}:{},inst:e}),n}});function $s(e,t,n){e.issues.length&&t.issues.push(...Hi(n,e.issues)),t.value[n]=e.value}const Ls=li("$ZodArray",(e,t)=>{qo.init(e,t),e._zod.parse=(n,i)=>{const r=n.value;if(!Array.isArray(r))return n.issues.push({expected:"array",code:"invalid_type",input:r,inst:e}),n;n.value=Array(r.length);const o=[];for(let e=0;e<r.length;e++){const s=r[e],a=t.element._zod.run({value:s,issues:[]},i);a instanceof Promise?o.push(a.then(t=>$s(t,n,e))):$s(a,n,e)}return o.length?Promise.all(o).then(()=>n):n}});function Ms(e,t,n,i,r){if(e.issues.length){if(r&&!(n in i))return;t.issues.push(...Hi(n,e.issues))}void 0===e.value?n in i&&(t.value[n]=void 0):t.value[n]=e.value}function Us(e){const t=Object.keys(e.shape);for(const n of t)if(!e.shape?.[n]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${n}": expected a Zod schema`);const n=(i=e.shape,Object.keys(i).filter(e=>"optional"===i[e]._zod.optin&&"optional"===i[e]._zod.optout));var i;return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function js(e,t,n,i,r,o){const s=[],a=r.keySet,c=r.catchall._zod,d=c.def.type,u="optional"===c.optout;for(const r in t){if(a.has(r))continue;if("never"===d){s.push(r);continue}const o=c.run({value:t[r],issues:[]},i);o instanceof Promise?e.push(o.then(e=>Ms(e,n,r,t,u))):Ms(o,n,r,t,u)}return s.length&&n.issues.push({code:"unrecognized_keys",keys:s,input:t,inst:o}),e.length?Promise.all(e).then(()=>n):n}const Hs=li("$ZodObject",(e,t)=>{qo.init(e,t);const n=Object.getOwnPropertyDescriptor(t,"shape");if(!n?.get){const e=t.shape;Object.defineProperty(t,"shape",{get:()=>{const n={...e};return Object.defineProperty(t,"shape",{value:n}),n}})}const i=Ii(()=>Us(t));Si(e._zod,"propValues",()=>{const e=t.shape,n={};for(const t in e){const i=e[t]._zod;if(i.values){n[t]??(n[t]=new Set);for(const e of i.values)n[t].add(e)}}return n});const r=Ti,o=t.catchall;let s;e._zod.parse=(t,n)=>{s??(s=i.value);const a=t.value;if(!r(a))return t.issues.push({expected:"object",code:"invalid_type",input:a,inst:e}),t;t.value={};const c=[],d=s.shape;for(const e of s.keys){const i=d[e],r="optional"===i._zod.optout,o=i._zod.run({value:a[e],issues:[]},n);o instanceof Promise?c.push(o.then(n=>Ms(n,t,e,a,r))):Ms(o,t,e,a,r)}return o?js(c,a,t,n,i.value,e):c.length?Promise.all(c).then(()=>t):t}}),Ks=li("$ZodObjectJIT",(e,t)=>{Hs.init(e,t);const n=e._zod.parse,i=Ii(()=>Us(t));let r;const o=Ti,s=!fi.jitless,a=s&&Ci.value,c=t.catchall;let d;e._zod.parse=(u,l)=>{d??(d=i.value);const p=u.value;return o(p)?s&&a&&!1===l?.async&&!0!==l.jitless?(r||(r=(e=>{const t=new Zo(["shape","payload","ctx"]),n=i.value,r=e=>{const t=Di(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write("const input = payload.value;");const o=Object.create(null);let s=0;for(const e of n.keys)o[e]="key_"+s++;t.write("const newResult = {};");for(const i of n.keys){const n=o[i],s=Di(i),a=e[i],c="optional"===a?._zod?.optout;t.write(`const ${n} = ${r(i)};`),c?t.write(`\n if (${n}.issues.length) {\n if (${s} in input) {\n payload.issues = payload.issues.concat(${n}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${s}, ...iss.path] : [${s}]\n })));\n }\n }\n \n if (${n}.value === undefined) {\n if (${s} in input) {\n newResult[${s}] = undefined;\n }\n } else {\n newResult[${s}] = ${n}.value;\n }\n \n `):t.write(`\n if (${n}.issues.length) {\n payload.issues = payload.issues.concat(${n}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${s}, ...iss.path] : [${s}]\n })));\n }\n \n if (${n}.value === undefined) {\n if (${s} in input) {\n newResult[${s}] = undefined;\n }\n } else {\n newResult[${s}] = ${n}.value;\n }\n \n `)}t.write("payload.value = newResult;"),t.write("return payload;");const a=t.compile();return(t,n)=>a(e,t,n)})(t.shape)),u=r(u,l),c?js([],p,u,l,d,e):u):n(u,l):(u.issues.push({expected:"object",code:"invalid_type",input:p,inst:e}),u)}});function Vs(e,t,n,i){for(const n of e)if(0===n.issues.length)return t.value=n.value,t;const r=e.filter(e=>!ji(e));return 1===r.length?(t.value=r[0].value,r[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>Vi(e,i,gi())))}),t)}const Fs=li("$ZodUnion",(e,t)=>{qo.init(e,t),Si(e._zod,"optin",()=>t.options.some(e=>"optional"===e._zod.optin)?"optional":void 0),Si(e._zod,"optout",()=>t.options.some(e=>"optional"===e._zod.optout)?"optional":void 0),Si(e._zod,"values",()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),Si(e._zod,"pattern",()=>{if(t.options.every(e=>e._zod.pattern)){const e=t.options.map(e=>e._zod.pattern);return new RegExp(`^(${e.map(e=>_i(e.source)).join("|")})$`)}});const n=1===t.options.length,i=t.options[0]._zod.run;e._zod.parse=(r,o)=>{if(n)return i(r,o);let s=!1;const a=[];for(const e of t.options){const t=e._zod.run({value:r.value,issues:[]},o);if(t instanceof Promise)a.push(t),s=!0;else{if(0===t.issues.length)return t;a.push(t)}}return s?Promise.all(a).then(t=>Vs(t,r,e,o)):Vs(a,r,e,o)}});function Bs(e,t,n,i){const r=e.filter(e=>0===e.issues.length);return 1===r.length?(t.value=r[0].value,t):(0===r.length?t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>Vi(e,i,gi())))}):t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:[],inclusive:!1}),t)}const Zs=li("$ZodXor",(e,t)=>{Fs.init(e,t),t.inclusive=!1;const n=1===t.options.length,i=t.options[0]._zod.run;e._zod.parse=(r,o)=>{if(n)return i(r,o);let s=!1;const a=[];for(const e of t.options){const t=e._zod.run({value:r.value,issues:[]},o);t instanceof Promise?(a.push(t),s=!0):a.push(t)}return s?Promise.all(a).then(t=>Bs(t,r,e,o)):Bs(a,r,e,o)}}),Js=li("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,Fs.init(e,t);const n=e._zod.parse;Si(e._zod,"propValues",()=>{const e={};for(const n of t.options){const i=n._zod.propValues;if(!i||0===Object.keys(i).length)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(n)}"`);for(const[t,n]of Object.entries(i)){e[t]||(e[t]=new Set);for(const i of n)e[t].add(i)}}return e});const i=Ii(()=>{const e=t.options,n=new Map;for(const i of e){const e=i._zod.propValues?.[t.discriminator];if(!e||0===e.size)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(i)}"`);for(const t of e){if(n.has(t))throw new Error(`Duplicate discriminator value "${String(t)}"`);n.set(t,i)}}return n});e._zod.parse=(r,o)=>{const s=r.value;if(!Ti(s))return r.issues.push({code:"invalid_type",expected:"object",input:s,inst:e}),r;const a=i.value.get(s?.[t.discriminator]);return a?a._zod.run(r,o):t.unionFallback?n(r,o):(r.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,input:s,path:[t.discriminator],inst:e}),r)}}),qs=li("$ZodIntersection",(e,t)=>{qo.init(e,t),e._zod.parse=(e,n)=>{const i=e.value,r=t.left._zod.run({value:i,issues:[]},n),o=t.right._zod.run({value:i,issues:[]},n);return r instanceof Promise||o instanceof Promise?Promise.all([r,o]).then(([t,n])=>Gs(e,t,n)):Gs(e,r,o)}});function Ws(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(Ni(e)&&Ni(t)){const n=Object.keys(t),i=Object.keys(e).filter(e=>-1!==n.indexOf(e)),r={...e,...t};for(const n of i){const i=Ws(e[n],t[n]);if(!i.valid)return{valid:!1,mergeErrorPath:[n,...i.mergeErrorPath]};r[n]=i.data}return{valid:!0,data:r}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let i=0;i<e.length;i++){const r=Ws(e[i],t[i]);if(!r.valid)return{valid:!1,mergeErrorPath:[i,...r.mergeErrorPath]};n.push(r.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function Gs(e,t,n){const i=new Map;let r;for(const n of t.issues)if("unrecognized_keys"===n.code){r??(r=n);for(const e of n.keys)i.has(e)||i.set(e,{}),i.get(e).l=!0}else e.issues.push(n);for(const t of n.issues)if("unrecognized_keys"===t.code)for(const e of t.keys)i.has(e)||i.set(e,{}),i.get(e).r=!0;else e.issues.push(t);const o=[...i].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(o.length&&r&&e.issues.push({...r,keys:o}),ji(e))return e;const s=Ws(t.value,n.value);if(!s.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(s.mergeErrorPath)}`);return e.value=s.data,e}const Ys=li("$ZodTuple",(e,t)=>{qo.init(e,t);const n=t.items;e._zod.parse=(i,r)=>{const o=i.value;if(!Array.isArray(o))return i.issues.push({input:o,inst:e,expected:"tuple",code:"invalid_type"}),i;i.value=[];const s=[],a=[...n].reverse().findIndex(e=>"optional"!==e._zod.optin),c=-1===a?0:n.length-a;if(!t.rest){const t=o.length>n.length,r=o.length<c-1;if(t||r)return i.issues.push({...t?{code:"too_big",maximum:n.length,inclusive:!0}:{code:"too_small",minimum:n.length},input:o,inst:e,origin:"array"}),i}let d=-1;for(const e of n){if(d++,d>=o.length&&d>=c)continue;const t=e._zod.run({value:o[d],issues:[]},r);t instanceof Promise?s.push(t.then(e=>Xs(e,i,d))):Xs(t,i,d)}if(t.rest){const e=o.slice(n.length);for(const n of e){d++;const e=t.rest._zod.run({value:n,issues:[]},r);e instanceof Promise?s.push(e.then(e=>Xs(e,i,d))):Xs(e,i,d)}}return s.length?Promise.all(s).then(()=>i):i}});function Xs(e,t,n){e.issues.length&&t.issues.push(...Hi(n,e.issues)),t.value[n]=e.value}const Qs=li("$ZodRecord",(e,t)=>{qo.init(e,t),e._zod.parse=(n,i)=>{const r=n.value;if(!Ni(r))return n.issues.push({expected:"record",code:"invalid_type",input:r,inst:e}),n;const o=[],s=t.keyType._zod.values;if(s){n.value={};const a=new Set;for(const e of s)if("string"==typeof e||"number"==typeof e||"symbol"==typeof e){a.add("number"==typeof e?e.toString():e);const s=t.valueType._zod.run({value:r[e],issues:[]},i);s instanceof Promise?o.push(s.then(t=>{t.issues.length&&n.issues.push(...Hi(e,t.issues)),n.value[e]=t.value})):(s.issues.length&&n.issues.push(...Hi(e,s.issues)),n.value[e]=s.value)}let c;for(const e in r)a.has(e)||(c=c??[],c.push(e));c&&c.length>0&&n.issues.push({code:"unrecognized_keys",input:r,inst:e,keys:c})}else{n.value={};for(const s of Reflect.ownKeys(r)){if("__proto__"===s)continue;let a=t.keyType._zod.run({value:s,issues:[]},i);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if("string"==typeof s&&Yr.test(s)&&a.issues.length){const e=t.keyType._zod.run({value:Number(s),issues:[]},i);if(e instanceof Promise)throw new Error("Async schemas not supported in object keys currently");0===e.issues.length&&(a=e)}if(a.issues.length){"loose"===t.mode?n.value[s]=r[s]:n.issues.push({code:"invalid_key",origin:"record",issues:a.issues.map(e=>Vi(e,i,gi())),input:s,path:[s],inst:e});continue}const c=t.valueType._zod.run({value:r[s],issues:[]},i);c instanceof Promise?o.push(c.then(e=>{e.issues.length&&n.issues.push(...Hi(s,e.issues)),n.value[a.value]=e.value})):(c.issues.length&&n.issues.push(...Hi(s,c.issues)),n.value[a.value]=c.value)}}return o.length?Promise.all(o).then(()=>n):n}}),ea=li("$ZodMap",(e,t)=>{qo.init(e,t),e._zod.parse=(n,i)=>{const r=n.value;if(!(r instanceof Map))return n.issues.push({expected:"map",code:"invalid_type",input:r,inst:e}),n;const o=[];n.value=new Map;for(const[s,a]of r){const c=t.keyType._zod.run({value:s,issues:[]},i),d=t.valueType._zod.run({value:a,issues:[]},i);c instanceof Promise||d instanceof Promise?o.push(Promise.all([c,d]).then(([t,o])=>{ta(t,o,n,s,r,e,i)})):ta(c,d,n,s,r,e,i)}return o.length?Promise.all(o).then(()=>n):n}});function ta(e,t,n,i,r,o,s){e.issues.length&&(zi.has(typeof i)?n.issues.push(...Hi(i,e.issues)):n.issues.push({code:"invalid_key",origin:"map",input:r,inst:o,issues:e.issues.map(e=>Vi(e,s,gi()))})),t.issues.length&&(zi.has(typeof i)?n.issues.push(...Hi(i,t.issues)):n.issues.push({origin:"map",code:"invalid_element",input:r,inst:o,key:i,issues:t.issues.map(e=>Vi(e,s,gi()))})),n.value.set(e.value,t.value)}const na=li("$ZodSet",(e,t)=>{qo.init(e,t),e._zod.parse=(n,i)=>{const r=n.value;if(!(r instanceof Set))return n.issues.push({input:r,inst:e,expected:"set",code:"invalid_type"}),n;const o=[];n.value=new Set;for(const e of r){const r=t.valueType._zod.run({value:e,issues:[]},i);r instanceof Promise?o.push(r.then(e=>ia(e,n))):ia(r,n)}return o.length?Promise.all(o).then(()=>n):n}});function ia(e,t){e.issues.length&&t.issues.push(...e.issues),t.value.add(e.value)}const ra=li("$ZodEnum",(e,t)=>{qo.init(e,t);const n=mi(t.entries),i=new Set(n);e._zod.values=i,e._zod.pattern=new RegExp(`^(${n.filter(e=>zi.has(typeof e)).map(e=>"string"==typeof e?Pi(e):e.toString()).join("|")})$`),e._zod.parse=(t,r)=>{const o=t.value;return i.has(o)||t.issues.push({code:"invalid_value",values:n,input:o,inst:e}),t}}),oa=li("$ZodLiteral",(e,t)=>{if(qo.init(e,t),0===t.values.length)throw new Error("Cannot create literal schema with no valid values");const n=new Set(t.values);e._zod.values=n,e._zod.pattern=new RegExp(`^(${t.values.map(e=>"string"==typeof e?Pi(e):e?Pi(e.toString()):String(e)).join("|")})$`),e._zod.parse=(i,r)=>{const o=i.value;return n.has(o)||i.issues.push({code:"invalid_value",values:t.values,input:o,inst:e}),i}}),sa=li("$ZodFile",(e,t)=>{qo.init(e,t),e._zod.parse=(t,n)=>{const i=t.value;return i instanceof File||t.issues.push({expected:"file",code:"invalid_type",input:i,inst:e}),t}}),aa=li("$ZodTransform",(e,t)=>{qo.init(e,t),e._zod.parse=(n,i)=>{if("backward"===i.direction)throw new hi(e.constructor.name);const r=t.transform(n.value,n);if(i.async)return(r instanceof Promise?r:Promise.resolve(r)).then(e=>(n.value=e,n));if(r instanceof Promise)throw new pi;return n.value=r,n}});function ca(e,t){return e.issues.length&&void 0===t?{issues:[],value:void 0}:e}const da=li("$ZodOptional",(e,t)=>{qo.init(e,t),e._zod.optin="optional",e._zod.optout="optional",Si(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),Si(e._zod,"pattern",()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${_i(e.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if("optional"===t.innerType._zod.optin){const i=t.innerType._zod.run(e,n);return i instanceof Promise?i.then(t=>ca(t,e.value)):ca(i,e.value)}return void 0===e.value?e:t.innerType._zod.run(e,n)}}),ua=li("$ZodExactOptional",(e,t)=>{da.init(e,t),Si(e._zod,"values",()=>t.innerType._zod.values),Si(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),la=li("$ZodNullable",(e,t)=>{qo.init(e,t),Si(e._zod,"optin",()=>t.innerType._zod.optin),Si(e._zod,"optout",()=>t.innerType._zod.optout),Si(e._zod,"pattern",()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${_i(e.source)}|null)$`):void 0}),Si(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>null===e.value?e:t.innerType._zod.run(e,n)}),pa=li("$ZodDefault",(e,t)=>{qo.init(e,t),e._zod.optin="optional",Si(e._zod,"values",()=>t.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 i=t.innerType._zod.run(e,n);return i instanceof Promise?i.then(e=>ha(e,t)):ha(i,t)}});function ha(e,t){return void 0===e.value&&(e.value=t.defaultValue),e}const fa=li("$ZodPrefault",(e,t)=>{qo.init(e,t),e._zod.optin="optional",Si(e._zod,"values",()=>t.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))}),ga=li("$ZodNonOptional",(e,t)=>{qo.init(e,t),Si(e._zod,"values",()=>{const e=t.innerType._zod.values;return e?new Set([...e].filter(e=>void 0!==e)):void 0}),e._zod.parse=(n,i)=>{const r=t.innerType._zod.run(n,i);return r instanceof Promise?r.then(t=>ma(t,e)):ma(r,e)}});function ma(e,t){return e.issues.length||void 0!==e.value||e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const ya=li("$ZodSuccess",(e,t)=>{qo.init(e,t),e._zod.parse=(e,n)=>{if("backward"===n.direction)throw new hi("ZodSuccess");const i=t.innerType._zod.run(e,n);return i instanceof Promise?i.then(t=>(e.value=0===t.issues.length,e)):(e.value=0===i.issues.length,e)}}),va=li("$ZodCatch",(e,t)=>{qo.init(e,t),Si(e._zod,"optin",()=>t.innerType._zod.optin),Si(e._zod,"optout",()=>t.innerType._zod.optout),Si(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if("backward"===n.direction)return t.innerType._zod.run(e,n);const i=t.innerType._zod.run(e,n);return i instanceof Promise?i.then(i=>(e.value=i.value,i.issues.length&&(e.value=t.catchValue({...e,error:{issues:i.issues.map(e=>Vi(e,n,gi()))},input:e.value}),e.issues=[]),e)):(e.value=i.value,i.issues.length&&(e.value=t.catchValue({...e,error:{issues:i.issues.map(e=>Vi(e,n,gi()))},input:e.value}),e.issues=[]),e)}}),Ia=li("$ZodNaN",(e,t)=>{qo.init(e,t),e._zod.parse=(t,n)=>("number"==typeof t.value&&Number.isNaN(t.value)||t.issues.push({input:t.value,inst:e,expected:"nan",code:"invalid_type"}),t)}),wa=li("$ZodPipe",(e,t)=>{qo.init(e,t),Si(e._zod,"values",()=>t.in._zod.values),Si(e._zod,"optin",()=>t.in._zod.optin),Si(e._zod,"optout",()=>t.out._zod.optout),Si(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(e,n)=>{if("backward"===n.direction){const i=t.out._zod.run(e,n);return i instanceof Promise?i.then(e=>_a(e,t.in,n)):_a(i,t.in,n)}const i=t.in._zod.run(e,n);return i instanceof Promise?i.then(e=>_a(e,t.out,n)):_a(i,t.out,n)}});function _a(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},n)}const Ea=li("$ZodCodec",(e,t)=>{qo.init(e,t),Si(e._zod,"values",()=>t.in._zod.values),Si(e._zod,"optin",()=>t.in._zod.optin),Si(e._zod,"optout",()=>t.out._zod.optout),Si(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(e,n)=>{if("forward"===(n.direction||"forward")){const i=t.in._zod.run(e,n);return i instanceof Promise?i.then(e=>Sa(e,t,n)):Sa(i,t,n)}{const i=t.out._zod.run(e,n);return i instanceof Promise?i.then(e=>Sa(e,t,n)):Sa(i,t,n)}}});function Sa(e,t,n){if(e.issues.length)return e.aborted=!0,e;if("forward"===(n.direction||"forward")){const i=t.transform(e.value,e);return i instanceof Promise?i.then(i=>ba(e,i,t.out,n)):ba(e,i,t.out,n)}{const i=t.reverseTransform(e.value,e);return i instanceof Promise?i.then(i=>ba(e,i,t.in,n)):ba(e,i,t.in,n)}}function ba(e,t,n,i){return e.issues.length?(e.aborted=!0,e):n._zod.run({value:t,issues:e.issues},i)}const Aa=li("$ZodReadonly",(e,t)=>{qo.init(e,t),Si(e._zod,"propValues",()=>t.innerType._zod.propValues),Si(e._zod,"values",()=>t.innerType._zod.values),Si(e._zod,"optin",()=>t.innerType?._zod?.optin),Si(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(e,n)=>{if("backward"===n.direction)return t.innerType._zod.run(e,n);const i=t.innerType._zod.run(e,n);return i instanceof Promise?i.then(Da):Da(i)}});function Da(e){return e.value=Object.freeze(e.value),e}const ka=li("$ZodTemplateLiteral",(e,t)=>{qo.init(e,t);const n=[];for(const e of t.parts)if("object"==typeof e&&null!==e){if(!e._zod.pattern)throw new Error(`Invalid template literal part, no pattern found: ${[...e._zod.traits].shift()}`);const t=e._zod.pattern instanceof RegExp?e._zod.pattern.source:e._zod.pattern;if(!t)throw new Error(`Invalid template literal part: ${e._zod.traits}`);const i=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;n.push(t.slice(i,r))}else{if(null!==e&&!Ri.has(typeof e))throw new Error(`Invalid template literal part: ${e}`);n.push(Pi(`${e}`))}e._zod.pattern=new RegExp(`^${n.join("")}$`),e._zod.parse=(n,i)=>"string"!=typeof n.value?(n.issues.push({input:n.value,inst:e,expected:"string",code:"invalid_type"}),n):(e._zod.pattern.lastIndex=0,e._zod.pattern.test(n.value)||n.issues.push({input:n.value,inst:e,code:"invalid_format",format:t.format??"template_literal",pattern:e._zod.pattern.source}),n)}),Ta=li("$ZodFunction",(e,t)=>(qo.init(e,t),e._def=t,e._zod.def=t,e.implement=t=>{if("function"!=typeof t)throw new Error("implement() must be called with a function");return function(...n){const i=e._def.input?Yi(e._def.input,n):n,r=Reflect.apply(t,this,i);return e._def.output?Yi(e._def.output,r):r}},e.implementAsync=t=>{if("function"!=typeof t)throw new Error("implementAsync() must be called with a function");return async function(...n){const i=e._def.input?await Qi(e._def.input,n):n,r=await Reflect.apply(t,this,i);return e._def.output?await Qi(e._def.output,r):r}},e._zod.parse=(t,n)=>{if("function"!=typeof t.value)return t.issues.push({code:"invalid_type",expected:"function",input:t.value,inst:e}),t;const i=e._def.output&&"promise"===e._def.output._zod.def.type;return t.value=i?e.implementAsync(t.value):e.implement(t.value),t},e.input=(...t)=>{const n=e.constructor;return Array.isArray(t[0])?new n({type:"function",input:new Ys({type:"tuple",items:t[0],rest:t[1]}),output:e._def.output}):new n({type:"function",input:t[0],output:e._def.output})},e.output=t=>new(0,e.constructor)({type:"function",input:e._def.input,output:t}),e)),Ca=li("$ZodPromise",(e,t)=>{qo.init(e,t),e._zod.parse=(e,n)=>Promise.resolve(e.value).then(e=>t.innerType._zod.run({value:e,issues:[]},n))}),Na=li("$ZodLazy",(e,t)=>{qo.init(e,t),Si(e._zod,"innerType",()=>t.getter()),Si(e._zod,"pattern",()=>e._zod.innerType?._zod?.pattern),Si(e._zod,"propValues",()=>e._zod.innerType?._zod?.propValues),Si(e._zod,"optin",()=>e._zod.innerType?._zod?.optin??void 0),Si(e._zod,"optout",()=>e._zod.innerType?._zod?.optout??void 0),e._zod.parse=(t,n)=>e._zod.innerType._zod.run(t,n)}),Oa=li("$ZodCustom",(e,t)=>{Eo.init(e,t),qo.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{const i=n.value,r=t.fn(i);if(r instanceof Promise)return r.then(t=>za(t,n,i,e));za(r,n,i,e)}});function za(e,t,n,i){if(!e){const e={code:"custom",input:n,inst:i,path:[...i._zod.def.path??[]],continue:!i._zod.def.abort};i._zod.def.params&&(e.params=i._zod.def.params),t.issues.push(Zi(e))}}var Ra;Symbol("ZodOutput"),Symbol("ZodInput");(Ra=globalThis).__zod_globalRegistry??(Ra.__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 i={...n,...this._map.get(e)};return Object.keys(i).length?i:void 0}return this._map.get(e)}has(e){return this._map.has(e)}});const Pa=globalThis.__zod_globalRegistry;function xa(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...$i(t)})}function $a(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...$i(t)})}function La(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...$i(t)})}function Ma(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...$i(t)})}function Ua(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...$i(t)})}function ja(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...$i(t)})}function Ha(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...$i(t)})}function Ka(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...$i(t)})}function Va(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...$i(t)})}function Fa(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...$i(t)})}function Ba(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...$i(t)})}function Za(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...$i(t)})}function Ja(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...$i(t)})}function qa(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...$i(t)})}function Wa(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...$i(t)})}function Ga(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...$i(t)})}function Ya(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...$i(t)})}function Xa(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...$i(t)})}function Qa(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...$i(t)})}function ec(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...$i(t)})}function tc(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...$i(t)})}function nc(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...$i(t)})}function ic(e,t){return new bo({check:"less_than",...$i(t),value:e,inclusive:!1})}function rc(e,t){return new bo({check:"less_than",...$i(t),value:e,inclusive:!0})}function oc(e,t){return new Ao({check:"greater_than",...$i(t),value:e,inclusive:!1})}function sc(e,t){return new Ao({check:"greater_than",...$i(t),value:e,inclusive:!0})}function ac(e){return oc(0,e)}function cc(e){return ic(0,e)}function dc(e){return rc(0,e)}function uc(e){return sc(0,e)}function lc(e,t){return new Do({check:"multiple_of",...$i(t),value:e})}function pc(e,t){return new Co({check:"max_size",...$i(t),maximum:e})}function hc(e,t){return new No({check:"min_size",...$i(t),minimum:e})}function fc(e,t){return new Oo({check:"size_equals",...$i(t),size:e})}function gc(e,t){return new zo({check:"max_length",...$i(t),maximum:e})}function mc(e,t){return new Ro({check:"min_length",...$i(t),minimum:e})}function yc(e,t){return new Po({check:"length_equals",...$i(t),length:e})}function vc(e,t){return new $o({check:"string_format",format:"regex",...$i(t),pattern:e})}function Ic(e){return new Lo({check:"string_format",format:"lowercase",...$i(e)})}function wc(e){return new Mo({check:"string_format",format:"uppercase",...$i(e)})}function _c(e,t){return new Uo({check:"string_format",format:"includes",...$i(t),includes:e})}function Ec(e,t){return new jo({check:"string_format",format:"starts_with",...$i(t),prefix:e})}function Sc(e,t){return new Ho({check:"string_format",format:"ends_with",...$i(t),suffix:e})}function bc(e,t,n){return new Vo({check:"property",property:e,schema:t,...$i(n)})}function Ac(e,t){return new Fo({check:"mime_type",mime:e,...$i(t)})}function Dc(e){return new Bo({check:"overwrite",tx:e})}function kc(e){return Dc(t=>t.normalize(e))}function Tc(){return Dc(e=>e.trim())}function Cc(){return Dc(e=>e.toLowerCase())}function Nc(){return Dc(e=>e.toUpperCase())}function Oc(){return Dc(e=>function(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}(e))}function zc(e,t,n,i={}){const r=$i(i),o={...$i(i),check:"string_format",type:"string",format:t,fn:"function"==typeof n?n:e=>n.test(e),...r};return n instanceof RegExp&&(o.pattern=n),new e(o)}function Rc(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??Pa,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function Pc(e,t,n={path:[],schemaPath:[]}){var i;const r=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);const a=e._zod.toJSONSchema?.();if(a)s.schema=a;else{const i={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,s.schema,i);else{const n=s.schema,o=t.processors[r.type];if(!o)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${r.type}`);o(e,t,n,i)}const o=e._zod.parent;o&&(s.ref||(s.ref=o),Pc(o,t,i),t.seen.get(o).isParent=!0)}const c=t.metadataRegistry.get(e);return c&&Object.assign(s.schema,c),"input"===t.io&&Lc(e)&&(delete s.schema.examples,delete s.schema.default),"input"===t.io&&s.schema._prefault&&((i=s.schema).default??(i.default=s.schema._prefault)),delete s.schema._prefault,t.seen.get(e).schema}function xc(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const i=new Map;for(const t of e.seen.entries()){const n=e.metadataRegistry.get(t[0])?.id;if(n){const e=i.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.`);i.set(n,t[0])}}const r=t=>{if(t[1].schema.$ref)return;const i=t[1],{ref:r,defId:o}=(t=>{const i="draft-2020-12"===e.target?"$defs":"definitions";if(e.external){const n=e.external.registry.get(t[0])?.id,r=e.external.uri??(e=>e);if(n)return{ref:r(n)};const o=t[1].defId??t[1].schema.id??"schema"+e.counter++;return t[1].defId=o,{defId:o,ref:`${r("__shared")}#/${i}/${o}`}}if(t[1]===n)return{ref:"#"};const r=`#/${i}/`,o=t[1].schema.id??"__schema"+e.counter++;return{defId:o,ref:r+o}})(t);i.def={...i.schema},o&&(i.defId=o);const s=i.schema;for(const e in s)delete s[e];s.$ref=r};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 i=n[1];if(t===n[0]){r(n);continue}if(e.external){const i=e.external.registry.get(n[0])?.id;if(t!==n[0]&&i){r(n);continue}}const o=e.metadataRegistry.get(n[0])?.id;(o||i.cycle||i.count>1&&"ref"===e.reused)&&r(n)}}function $c(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const i=t=>{const n=e.seen.get(t);if(null===n.ref)return;const r=n.def??n.schema,o={...r},s=n.ref;if(n.ref=null,s){i(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?Object.assign(r,a):(r.allOf=r.allOf??[],r.allOf.push(a)),Object.assign(r,o),t._zod.parent===s)for(const e in r)"$ref"!==e&&"allOf"!==e&&(e in o||delete r[e]);if(a.$ref&&n.def)for(const e in r)"$ref"!==e&&"allOf"!==e&&e in n.def&&JSON.stringify(r[e])===JSON.stringify(n.def[e])&&delete r[e]}const a=t._zod.parent;if(a&&a!==s){i(a);const t=e.seen.get(a);if(t?.schema.$ref&&(r.$ref=t.schema.$ref,t.def))for(const e in r)"$ref"!==e&&"allOf"!==e&&e in t.def&&JSON.stringify(r[e])===JSON.stringify(t.def[e])&&delete r[e]}e.override({zodSchema:t,jsonSchema:r,path:n.path??[]})};for(const t of[...e.seen.entries()].reverse())i(t[0]);const r={};if("draft-2020-12"===e.target?r.$schema="https://json-schema.org/draft/2020-12/schema":"draft-07"===e.target?r.$schema="http://json-schema.org/draft-07/schema#":"draft-04"===e.target?r.$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");r.$id=e.external.uri(n)}Object.assign(r,n.def??n.schema);const o=e.external?.defs??{};for(const t of e.seen.entries()){const e=t[1];e.def&&e.defId&&(o[e.defId]=e.def)}e.external||Object.keys(o).length>0&&("draft-2020-12"===e.target?r.$defs=o:r.definitions=o);try{const n=JSON.parse(JSON.stringify(r));return Object.defineProperty(n,"~standard",{value:{...t["~standard"],jsonSchema:{input:Mc(t,"input",e.processors),output:Mc(t,"output",e.processors)}},enumerable:!1,writable:!1}),n}catch(e){throw new Error("Error converting schema to JSON.")}}function Lc(e,t){const n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);const i=e._zod.def;if("transform"===i.type)return!0;if("array"===i.type)return Lc(i.element,n);if("set"===i.type)return Lc(i.valueType,n);if("lazy"===i.type)return Lc(i.getter(),n);if("promise"===i.type||"optional"===i.type||"nonoptional"===i.type||"nullable"===i.type||"readonly"===i.type||"default"===i.type||"prefault"===i.type)return Lc(i.innerType,n);if("intersection"===i.type)return Lc(i.left,n)||Lc(i.right,n);if("record"===i.type||"map"===i.type)return Lc(i.keyType,n)||Lc(i.valueType,n);if("pipe"===i.type)return Lc(i.in,n)||Lc(i.out,n);if("object"===i.type){for(const e in i.shape)if(Lc(i.shape[e],n))return!0;return!1}if("union"===i.type){for(const e of i.options)if(Lc(e,n))return!0;return!1}if("tuple"===i.type){for(const e of i.items)if(Lc(e,n))return!0;return!(!i.rest||!Lc(i.rest,n))}return!1}const Mc=(e,t,n={})=>i=>{const{libraryOptions:r,target:o}=i??{},s=Rc({...r??{},target:o,io:t,processors:n});return Pc(e,s),xc(s,e),$c(s,e)},Uc={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},jc=(e,t,n,i)=>{const r=e._zod.def,o=!1===r.inclusive,s=r.options.map((e,n)=>Pc(e,t,{...i,path:[...i.path,o?"oneOf":"anyOf",n]}));o?n.oneOf=s:n.anyOf=s},Hc=(e,t,n,i)=>{const r=e._zod.def;Pc(r.innerType,t,i),t.seen.get(e).ref=r.innerType},Kc=li("ZodISODateTime",(e,t)=>{cs.init(e,t),fd.init(e,t)});function Vc(e){return function(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...$i(t)})}(Kc,e)}const Fc=li("ZodISODate",(e,t)=>{ds.init(e,t),fd.init(e,t)});function Bc(e){return function(e,t){return new e({type:"string",format:"date",check:"string_format",...$i(t)})}(Fc,e)}const Zc=li("ZodISOTime",(e,t)=>{us.init(e,t),fd.init(e,t)});function Jc(e){return function(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...$i(t)})}(Zc,e)}const qc=li("ZodISODuration",(e,t)=>{ls.init(e,t),fd.init(e,t)});function Wc(e){return function(e,t){return new e({type:"string",format:"duration",check:"string_format",...$i(t)})}(qc,e)}const Gc=(e,t)=>{qi.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:t=>function(e,t=e=>e.message){const n={_errors:[]},i=e=>{for(const r of e.issues)if("invalid_union"===r.code&&r.errors.length)r.errors.map(e=>i({issues:e}));else if("invalid_key"===r.code)i({issues:r.issues});else if("invalid_element"===r.code)i({issues:r.issues});else if(0===r.path.length)n._errors.push(t(r));else{let e=n,i=0;for(;i<r.path.length;){const n=r.path[i];i===r.path.length-1?(e[n]=e[n]||{_errors:[]},e[n]._errors.push(t(r))):e[n]=e[n]||{_errors:[]},e=e[n],i++}}};return i(e),n}(e,t)},flatten:{value:t=>function(e,t=e=>e.message){const n={},i=[];for(const r of e.issues)r.path.length>0?(n[r.path[0]]=n[r.path[0]]||[],n[r.path[0]].push(t(r))):i.push(t(r));return{formErrors:i,fieldErrors:n}}(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,vi,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,vi,2)}},isEmpty:{get:()=>0===e.issues.length}})},Yc=(li("ZodError",Gc),li("ZodError",Gc,{Parent:Error})),Xc=Gi(Yc),Qc=Xi(Yc),ed=er(Yc),td=nr(Yc),nd=rr(Yc),id=or(Yc),rd=sr(Yc),od=ar(Yc),sd=cr(Yc),ad=dr(Yc),cd=ur(Yc),dd=lr(Yc),ud=li("ZodType",(e,t)=>(qo.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Mc(e,"input"),output:Mc(e,"output")}}),e.toJSONSchema=((e,t={})=>n=>{const i=Rc({...n,processors:t});return Pc(e,i),xc(i,e),$c(i,e)})(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...n)=>e.clone(Ai(t,{checks:[...t.checks??[],...n.map(e=>"function"==typeof e?{_zod:{check:e,def:{check:"custom"},onattach:[]}}:e)]}),{parent:!0}),e.with=e.check,e.clone=(t,n)=>xi(e,t,n),e.brand=()=>e,e.register=(t,n)=>(t.add(e,n),e),e.parse=(t,n)=>Xc(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>ed(e,t,n),e.parseAsync=async(t,n)=>Qc(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>td(e,t,n),e.spa=e.safeParseAsync,e.encode=(t,n)=>nd(e,t,n),e.decode=(t,n)=>id(e,t,n),e.encodeAsync=async(t,n)=>rd(e,t,n),e.decodeAsync=async(t,n)=>od(e,t,n),e.safeEncode=(t,n)=>sd(e,t,n),e.safeDecode=(t,n)=>ad(e,t,n),e.safeEncodeAsync=async(t,n)=>cd(e,t,n),e.safeDecodeAsync=async(t,n)=>dd(e,t,n),e.refine=(t,n)=>e.check(ip(t,n)),e.superRefine=t=>e.check(rp(t)),e.overwrite=t=>e.check(Dc(t)),e.optional=()=>El(e),e.exactOptional=()=>bl(e),e.nullable=()=>Dl(e),e.nullish=()=>El(Dl(e)),e.nonoptional=t=>Rl(e,t),e.array=()=>Ku(e),e.or=t=>Wu([e,t]),e.and=t=>tl(e,t),e.transform=t=>Hl(e,wl(t)),e.default=t=>Cl(e,t),e.prefault=t=>Ol(e,t),e.catch=t=>Ll(e,t),e.pipe=t=>Hl(e,t),e.readonly=()=>Bl(e),e.describe=t=>{const n=e.clone();return Pa.add(n,{description:t}),n},Object.defineProperty(e,"description",{get:()=>Pa.get(e)?.description,configurable:!0}),e.meta=(...t)=>{if(0===t.length)return Pa.get(e);const n=e.clone();return Pa.add(n,t[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e.apply=t=>t(e),e)),ld=li("_ZodString",(e,t)=>{Wo.init(e,t),ud.init(e,t),e._zod.processJSONSchema=(t,n,i)=>((e,t,n)=>{const i=n;i.type="string";const{minimum:r,maximum:o,format:s,patterns:a,contentEncoding:c}=e._zod.bag;if("number"==typeof r&&(i.minLength=r),"number"==typeof o&&(i.maxLength=o),s&&(i.format=Uc[s]??s,""===i.format&&delete i.format,"time"===s&&delete i.format),c&&(i.contentEncoding=c),a&&a.size>0){const e=[...a];1===e.length?i.pattern=e[0].source:e.length>1&&(i.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,e.regex=(...t)=>e.check(vc(...t)),e.includes=(...t)=>e.check(_c(...t)),e.startsWith=(...t)=>e.check(Ec(...t)),e.endsWith=(...t)=>e.check(Sc(...t)),e.min=(...t)=>e.check(mc(...t)),e.max=(...t)=>e.check(gc(...t)),e.length=(...t)=>e.check(yc(...t)),e.nonempty=(...t)=>e.check(mc(1,...t)),e.lowercase=t=>e.check(Ic(t)),e.uppercase=t=>e.check(wc(t)),e.trim=()=>e.check(Tc()),e.normalize=(...t)=>e.check(kc(...t)),e.toLowerCase=()=>e.check(Cc()),e.toUpperCase=()=>e.check(Nc()),e.slugify=()=>e.check(Oc())}),pd=li("ZodString",(e,t)=>{Wo.init(e,t),ld.init(e,t),e.email=t=>e.check(xa(gd,t)),e.url=t=>e.check(Ha(bd,t)),e.jwt=t=>e.check(nc(iu,t)),e.emoji=t=>e.check(Ka(kd,t)),e.guid=t=>e.check($a(yd,t)),e.uuid=t=>e.check(La(Id,t)),e.uuidv4=t=>e.check(Ma(Id,t)),e.uuidv6=t=>e.check(Ua(Id,t)),e.uuidv7=t=>e.check(ja(Id,t)),e.nanoid=t=>e.check(Va(Cd,t)),e.guid=t=>e.check($a(yd,t)),e.cuid=t=>e.check(Fa(Od,t)),e.cuid2=t=>e.check(Ba(Rd,t)),e.ulid=t=>e.check(Za(xd,t)),e.base64=t=>e.check(Qa(Yd,t)),e.base64url=t=>e.check(ec(Qd,t)),e.xid=t=>e.check(Ja(Ld,t)),e.ksuid=t=>e.check(qa(Ud,t)),e.ipv4=t=>e.check(Wa(Hd,t)),e.ipv6=t=>e.check(Ga(Bd,t)),e.cidrv4=t=>e.check(Ya(Jd,t)),e.cidrv6=t=>e.check(Xa(Wd,t)),e.e164=t=>e.check(tc(tu,t)),e.datetime=t=>e.check(Vc(t)),e.date=t=>e.check(Bc(t)),e.time=t=>e.check(Jc(t)),e.duration=t=>e.check(Wc(t))});function hd(e){return function(e,t){return new e({type:"string",...$i(t)})}(pd,e)}const fd=li("ZodStringFormat",(e,t)=>{Go.init(e,t),ld.init(e,t)}),gd=li("ZodEmail",(e,t)=>{Qo.init(e,t),fd.init(e,t)});function md(e){return xa(gd,e)}const yd=li("ZodGUID",(e,t)=>{Yo.init(e,t),fd.init(e,t)});function vd(e){return $a(yd,e)}const Id=li("ZodUUID",(e,t)=>{Xo.init(e,t),fd.init(e,t)});function wd(e){return La(Id,e)}function _d(e){return Ma(Id,e)}function Ed(e){return Ua(Id,e)}function Sd(e){return ja(Id,e)}const bd=li("ZodURL",(e,t)=>{es.init(e,t),fd.init(e,t)});function Ad(e){return Ha(bd,e)}function Dd(e){return Ha(bd,{protocol:/^https?$/,hostname:Hr,...$i(e)})}const kd=li("ZodEmoji",(e,t)=>{ts.init(e,t),fd.init(e,t)});function Td(e){return Ka(kd,e)}const Cd=li("ZodNanoID",(e,t)=>{ns.init(e,t),fd.init(e,t)});function Nd(e){return Va(Cd,e)}const Od=li("ZodCUID",(e,t)=>{is.init(e,t),fd.init(e,t)});function zd(e){return Fa(Od,e)}const Rd=li("ZodCUID2",(e,t)=>{rs.init(e,t),fd.init(e,t)});function Pd(e){return Ba(Rd,e)}const xd=li("ZodULID",(e,t)=>{os.init(e,t),fd.init(e,t)});function $d(e){return Za(xd,e)}const Ld=li("ZodXID",(e,t)=>{ss.init(e,t),fd.init(e,t)});function Md(e){return Ja(Ld,e)}const Ud=li("ZodKSUID",(e,t)=>{as.init(e,t),fd.init(e,t)});function jd(e){return qa(Ud,e)}const Hd=li("ZodIPv4",(e,t)=>{ps.init(e,t),fd.init(e,t)});function Kd(e){return Wa(Hd,e)}const Vd=li("ZodMAC",(e,t)=>{fs.init(e,t),fd.init(e,t)});function Fd(e){return function(e,t){return new e({type:"string",format:"mac",check:"string_format",abort:!1,...$i(t)})}(Vd,e)}const Bd=li("ZodIPv6",(e,t)=>{hs.init(e,t),fd.init(e,t)});function Zd(e){return Ga(Bd,e)}const Jd=li("ZodCIDRv4",(e,t)=>{gs.init(e,t),fd.init(e,t)});function qd(e){return Ya(Jd,e)}const Wd=li("ZodCIDRv6",(e,t)=>{ms.init(e,t),fd.init(e,t)});function Gd(e){return Xa(Wd,e)}const Yd=li("ZodBase64",(e,t)=>{vs.init(e,t),fd.init(e,t)});function Xd(e){return Qa(Yd,e)}const Qd=li("ZodBase64URL",(e,t)=>{Is.init(e,t),fd.init(e,t)});function eu(e){return ec(Qd,e)}const tu=li("ZodE164",(e,t)=>{ws.init(e,t),fd.init(e,t)});function nu(e){return tc(tu,e)}const iu=li("ZodJWT",(e,t)=>{_s.init(e,t),fd.init(e,t)});function ru(e){return nc(iu,e)}const ou=li("ZodCustomStringFormat",(e,t)=>{Es.init(e,t),fd.init(e,t)});function su(e,t,n={}){return zc(ou,e,t,n)}function au(e){return zc(ou,"hostname",jr,e)}function cu(e){return zc(ou,"hex",io,e)}function du(e,t){const n=`${e}_${t?.enc??"hex"}`,r=i[n];if(!r)throw new Error(`Unrecognized hash format: ${n}`);return zc(ou,n,r,t)}const uu=li("ZodNumber",(e,t)=>{Ss.init(e,t),ud.init(e,t),e._zod.processJSONSchema=(t,n,i)=>((e,t,n)=>{const i=n,{minimum:r,maximum:o,format:s,multipleOf:a,exclusiveMaximum:c,exclusiveMinimum:d}=e._zod.bag;"string"==typeof s&&s.includes("int")?i.type="integer":i.type="number","number"==typeof d&&("draft-04"===t.target||"openapi-3.0"===t.target?(i.minimum=d,i.exclusiveMinimum=!0):i.exclusiveMinimum=d),"number"==typeof r&&(i.minimum=r,"number"==typeof d&&"draft-04"!==t.target&&(d>=r?delete i.minimum:delete i.exclusiveMinimum)),"number"==typeof c&&("draft-04"===t.target||"openapi-3.0"===t.target?(i.maximum=c,i.exclusiveMaximum=!0):i.exclusiveMaximum=c),"number"==typeof o&&(i.maximum=o,"number"==typeof c&&"draft-04"!==t.target&&(c<=o?delete i.maximum:delete i.exclusiveMaximum)),"number"==typeof a&&(i.multipleOf=a)})(e,t,n),e.gt=(t,n)=>e.check(oc(t,n)),e.gte=(t,n)=>e.check(sc(t,n)),e.min=(t,n)=>e.check(sc(t,n)),e.lt=(t,n)=>e.check(ic(t,n)),e.lte=(t,n)=>e.check(rc(t,n)),e.max=(t,n)=>e.check(rc(t,n)),e.int=t=>e.check(hu(t)),e.safe=t=>e.check(hu(t)),e.positive=t=>e.check(oc(0,t)),e.nonnegative=t=>e.check(sc(0,t)),e.negative=t=>e.check(ic(0,t)),e.nonpositive=t=>e.check(rc(0,t)),e.multipleOf=(t,n)=>e.check(lc(t,n)),e.step=(t,n)=>e.check(lc(t,n)),e.finite=()=>e;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});function lu(e){return function(e,t){return new e({type:"number",checks:[],...$i(t)})}(uu,e)}const pu=li("ZodNumberFormat",(e,t)=>{bs.init(e,t),uu.init(e,t)});function hu(e){return function(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...$i(t)})}(pu,e)}function fu(e){return function(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float32",...$i(t)})}(pu,e)}function gu(e){return function(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float64",...$i(t)})}(pu,e)}function mu(e){return function(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"int32",...$i(t)})}(pu,e)}function yu(e){return function(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"uint32",...$i(t)})}(pu,e)}const vu=li("ZodBoolean",(e,t)=>{As.init(e,t),ud.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t,n)=>{n.type="boolean"})(0,0,t)});function Iu(e){return function(e,t){return new e({type:"boolean",...$i(t)})}(vu,e)}const wu=li("ZodBigInt",(e,t)=>{Ds.init(e,t),ud.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t)=>{if("throw"===t.unrepresentable)throw new Error("BigInt cannot be represented in JSON Schema")})(0,e),e.gte=(t,n)=>e.check(sc(t,n)),e.min=(t,n)=>e.check(sc(t,n)),e.gt=(t,n)=>e.check(oc(t,n)),e.gte=(t,n)=>e.check(sc(t,n)),e.min=(t,n)=>e.check(sc(t,n)),e.lt=(t,n)=>e.check(ic(t,n)),e.lte=(t,n)=>e.check(rc(t,n)),e.max=(t,n)=>e.check(rc(t,n)),e.positive=t=>e.check(oc(BigInt(0),t)),e.negative=t=>e.check(ic(BigInt(0),t)),e.nonpositive=t=>e.check(rc(BigInt(0),t)),e.nonnegative=t=>e.check(sc(BigInt(0),t)),e.multipleOf=(t,n)=>e.check(lc(t,n));const n=e._zod.bag;e.minValue=n.minimum??null,e.maxValue=n.maximum??null,e.format=n.format??null});function _u(e){return function(e,t){return new e({type:"bigint",...$i(t)})}(wu,e)}const Eu=li("ZodBigIntFormat",(e,t)=>{ks.init(e,t),wu.init(e,t)});function Su(e){return function(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...$i(t)})}(Eu,e)}function bu(e){return function(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...$i(t)})}(Eu,e)}const Au=li("ZodSymbol",(e,t)=>{Ts.init(e,t),ud.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t)=>{if("throw"===t.unrepresentable)throw new Error("Symbols cannot be represented in JSON Schema")})(0,e)});function Du(e){return function(e,t){return new e({type:"symbol",...$i(t)})}(Au,e)}const ku=li("ZodUndefined",(e,t)=>{Cs.init(e,t),ud.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t)=>{if("throw"===t.unrepresentable)throw new Error("Undefined cannot be represented in JSON Schema")})(0,e)});function Tu(e){return function(e,t){return new e({type:"undefined",...$i(t)})}(ku,e)}const Cu=li("ZodNull",(e,t)=>{Ns.init(e,t),ud.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t,n)=>{"openapi-3.0"===t.target?(n.type="string",n.nullable=!0,n.enum=[null]):n.type="null"})(0,e,t)});function Nu(e){return function(e,t){return new e({type:"null",...$i(t)})}(Cu,e)}const Ou=li("ZodAny",(e,t)=>{Os.init(e,t),ud.init(e,t),e._zod.processJSONSchema=(e,t,n)=>{}});function zu(){return new Ou({type:"any"})}const Ru=li("ZodUnknown",(e,t)=>{zs.init(e,t),ud.init(e,t),e._zod.processJSONSchema=(e,t,n)=>{}});function Pu(){return new Ru({type:"unknown"})}const xu=li("ZodNever",(e,t)=>{Rs.init(e,t),ud.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t,n)=>{n.not={}})(0,0,t)});function $u(e){return function(e,t){return new e({type:"never",...$i(t)})}(xu,e)}const Lu=li("ZodVoid",(e,t)=>{Ps.init(e,t),ud.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t)=>{if("throw"===t.unrepresentable)throw new Error("Void cannot be represented in JSON Schema")})(0,e)});function Mu(e){return function(e,t){return new e({type:"void",...$i(t)})}(Lu,e)}const Uu=li("ZodDate",(e,t)=>{xs.init(e,t),ud.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t)=>{if("throw"===t.unrepresentable)throw new Error("Date cannot be represented in JSON Schema")})(0,e),e.min=(t,n)=>e.check(sc(t,n)),e.max=(t,n)=>e.check(rc(t,n));const n=e._zod.bag;e.minDate=n.minimum?new Date(n.minimum):null,e.maxDate=n.maximum?new Date(n.maximum):null});function ju(e){return function(e,t){return new e({type:"date",...$i(t)})}(Uu,e)}const Hu=li("ZodArray",(e,t)=>{Ls.init(e,t),ud.init(e,t),e._zod.processJSONSchema=(t,n,i)=>((e,t,n,i)=>{const r=n,o=e._zod.def,{minimum:s,maximum:a}=e._zod.bag;"number"==typeof s&&(r.minItems=s),"number"==typeof a&&(r.maxItems=a),r.type="array",r.items=Pc(o.element,t,{...i,path:[...i.path,"items"]})})(e,t,n,i),e.element=t.element,e.min=(t,n)=>e.check(mc(t,n)),e.nonempty=t=>e.check(mc(1,t)),e.max=(t,n)=>e.check(gc(t,n)),e.length=(t,n)=>e.check(yc(t,n)),e.unwrap=()=>e.element});function Ku(e,t){return function(e,t,n){return new e({type:"array",element:t,...$i(n)})}(Hu,e,t)}function Vu(e){const t=e._zod.def.shape;return hl(Object.keys(t))}const Fu=li("ZodObject",(e,t)=>{Ks.init(e,t),ud.init(e,t),e._zod.processJSONSchema=(t,n,i)=>((e,t,n,i)=>{const r=n,o=e._zod.def;r.type="object",r.properties={};const s=o.shape;for(const e in s)r.properties[e]=Pc(s[e],t,{...i,path:[...i.path,"properties",e]});const a=new Set(Object.keys(s)),c=new Set([...a].filter(e=>{const n=o.shape[e]._zod;return"input"===t.io?void 0===n.optin:void 0===n.optout}));c.size>0&&(r.required=Array.from(c)),"never"===o.catchall?._zod.def.type?r.additionalProperties=!1:o.catchall?o.catchall&&(r.additionalProperties=Pc(o.catchall,t,{...i,path:[...i.path,"additionalProperties"]})):"output"===t.io&&(r.additionalProperties=!1)})(e,t,n,i),Si(e,"shape",()=>t.shape),e.keyof=()=>hl(Object.keys(e._zod.def.shape)),e.catchall=t=>e.clone({...e._zod.def,catchall:t}),e.passthrough=()=>e.clone({...e._zod.def,catchall:Pu()}),e.loose=()=>e.clone({...e._zod.def,catchall:Pu()}),e.strict=()=>e.clone({...e._zod.def,catchall:$u()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=t=>function(e,t){if(!Ni(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 in t)if(void 0!==Object.getOwnPropertyDescriptor(n,e))throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const i=Ai(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return bi(this,"shape",n),n}});return xi(e,i)}(e,t),e.safeExtend=t=>function(e,t){if(!Ni(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n=Ai(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return bi(this,"shape",n),n}});return xi(e,n)}(e,t),e.merge=t=>function(e,t){const n=Ai(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t._zod.def.shape};return bi(this,"shape",n),n},get catchall(){return t._zod.def.catchall},checks:[]});return xi(e,n)}(e,t),e.pick=t=>function(e,t){const n=e._zod.def,i=n.checks;if(i&&i.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");const r=Ai(e._zod.def,{get shape(){const e={};for(const i in t){if(!(i in n.shape))throw new Error(`Unrecognized key: "${i}"`);t[i]&&(e[i]=n.shape[i])}return bi(this,"shape",e),e},checks:[]});return xi(e,r)}(e,t),e.omit=t=>function(e,t){const n=e._zod.def,i=n.checks;if(i&&i.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const r=Ai(e._zod.def,{get shape(){const i={...e._zod.def.shape};for(const e in t){if(!(e in n.shape))throw new Error(`Unrecognized key: "${e}"`);t[e]&&delete i[e]}return bi(this,"shape",i),i},checks:[]});return xi(e,r)}(e,t),e.partial=(...t)=>function(e,t,n){const i=t._zod.def.checks;if(i&&i.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");const r=Ai(t._zod.def,{get shape(){const i=t._zod.def.shape,r={...i};if(n)for(const t in n){if(!(t in i))throw new Error(`Unrecognized key: "${t}"`);n[t]&&(r[t]=e?new e({type:"optional",innerType:i[t]}):i[t])}else for(const t in i)r[t]=e?new e({type:"optional",innerType:i[t]}):i[t];return bi(this,"shape",r),r},checks:[]});return xi(t,r)}(_l,e,t[0]),e.required=(...t)=>function(e,t,n){const i=Ai(t._zod.def,{get shape(){const i=t._zod.def.shape,r={...i};if(n)for(const t in n){if(!(t in r))throw new Error(`Unrecognized key: "${t}"`);n[t]&&(r[t]=new e({type:"nonoptional",innerType:i[t]}))}else for(const t in i)r[t]=new e({type:"nonoptional",innerType:i[t]});return bi(this,"shape",r),r}});return xi(t,i)}(zl,e,t[0])});function Bu(e,t){const n={type:"object",shape:e??{},...$i(t)};return new Fu(n)}function Zu(e,t){return new Fu({type:"object",shape:e,catchall:$u(),...$i(t)})}function Ju(e,t){return new Fu({type:"object",shape:e,catchall:Pu(),...$i(t)})}const qu=li("ZodUnion",(e,t)=>{Fs.init(e,t),ud.init(e,t),e._zod.processJSONSchema=(t,n,i)=>jc(e,t,n,i),e.options=t.options});function Wu(e,t){return new qu({type:"union",options:e,...$i(t)})}const Gu=li("ZodXor",(e,t)=>{qu.init(e,t),Zs.init(e,t),e._zod.processJSONSchema=(t,n,i)=>jc(e,t,n,i),e.options=t.options});function Yu(e,t){return new Gu({type:"union",options:e,inclusive:!1,...$i(t)})}const Xu=li("ZodDiscriminatedUnion",(e,t)=>{qu.init(e,t),Js.init(e,t)});function Qu(e,t,n){return new Xu({type:"union",options:t,discriminator:e,...$i(n)})}const el=li("ZodIntersection",(e,t)=>{qs.init(e,t),ud.init(e,t),e._zod.processJSONSchema=(t,n,i)=>((e,t,n,i)=>{const r=e._zod.def,o=Pc(r.left,t,{...i,path:[...i.path,"allOf",0]}),s=Pc(r.right,t,{...i,path:[...i.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})(e,t,n,i)});function tl(e,t){return new el({type:"intersection",left:e,right:t})}const nl=li("ZodTuple",(e,t)=>{Ys.init(e,t),ud.init(e,t),e._zod.processJSONSchema=(t,n,i)=>((e,t,n,i)=>{const r=n,o=e._zod.def;r.type="array";const s="draft-2020-12"===t.target?"prefixItems":"items",a="draft-2020-12"===t.target||"openapi-3.0"===t.target?"items":"additionalItems",c=o.items.map((e,n)=>Pc(e,t,{...i,path:[...i.path,s,n]})),d=o.rest?Pc(o.rest,t,{...i,path:[...i.path,a,..."openapi-3.0"===t.target?[o.items.length]:[]]}):null;"draft-2020-12"===t.target?(r.prefixItems=c,d&&(r.items=d)):"openapi-3.0"===t.target?(r.items={anyOf:c},d&&r.items.anyOf.push(d),r.minItems=c.length,d||(r.maxItems=c.length)):(r.items=c,d&&(r.additionalItems=d));const{minimum:u,maximum:l}=e._zod.bag;"number"==typeof u&&(r.minItems=u),"number"==typeof l&&(r.maxItems=l)})(e,t,n,i),e.rest=t=>e.clone({...e._zod.def,rest:t})});function il(e,t,n){const i=t instanceof qo;return new nl({type:"tuple",items:e,rest:i?t:null,...$i(i?n:t)})}const rl=li("ZodRecord",(e,t)=>{Qs.init(e,t),ud.init(e,t),e._zod.processJSONSchema=(t,n,i)=>((e,t,n,i)=>{const r=n,o=e._zod.def;r.type="object";const s=o.keyType,a=s._zod.bag,c=a?.patterns;if("loose"===o.mode&&c&&c.size>0){const e=Pc(o.valueType,t,{...i,path:[...i.path,"patternProperties","*"]});r.patternProperties={};for(const t of c)r.patternProperties[t.source]=e}else"draft-07"!==t.target&&"draft-2020-12"!==t.target||(r.propertyNames=Pc(o.keyType,t,{...i,path:[...i.path,"propertyNames"]})),r.additionalProperties=Pc(o.valueType,t,{...i,path:[...i.path,"additionalProperties"]});const d=s._zod.values;if(d){const e=[...d].filter(e=>"string"==typeof e||"number"==typeof e);e.length>0&&(r.required=e)}})(e,t,n,i),e.keyType=t.keyType,e.valueType=t.valueType});function ol(e,t,n){return new rl({type:"record",keyType:e,valueType:t,...$i(n)})}function sl(e,t,n){const i=xi(e);return i._zod.values=void 0,new rl({type:"record",keyType:i,valueType:t,...$i(n)})}function al(e,t,n){return new rl({type:"record",keyType:e,valueType:t,mode:"loose",...$i(n)})}const cl=li("ZodMap",(e,t)=>{ea.init(e,t),ud.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t)=>{if("throw"===t.unrepresentable)throw new Error("Map cannot be represented in JSON Schema")})(0,e),e.keyType=t.keyType,e.valueType=t.valueType,e.min=(...t)=>e.check(hc(...t)),e.nonempty=t=>e.check(hc(1,t)),e.max=(...t)=>e.check(pc(...t)),e.size=(...t)=>e.check(fc(...t))});function dl(e,t,n){return new cl({type:"map",keyType:e,valueType:t,...$i(n)})}const ul=li("ZodSet",(e,t)=>{na.init(e,t),ud.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t)=>{if("throw"===t.unrepresentable)throw new Error("Set cannot be represented in JSON Schema")})(0,e),e.min=(...t)=>e.check(hc(...t)),e.nonempty=t=>e.check(hc(1,t)),e.max=(...t)=>e.check(pc(...t)),e.size=(...t)=>e.check(fc(...t))});function ll(e,t){return new ul({type:"set",valueType:e,...$i(t)})}const pl=li("ZodEnum",(e,t)=>{ra.init(e,t),ud.init(e,t),e._zod.processJSONSchema=(t,n,i)=>((e,t,n)=>{const i=mi(e._zod.def.entries);i.every(e=>"number"==typeof e)&&(n.type="number"),i.every(e=>"string"==typeof e)&&(n.type="string"),n.enum=i})(e,0,n),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(e,i)=>{const r={};for(const i of e){if(!n.has(i))throw new Error(`Key ${i} not found in enum`);r[i]=t.entries[i]}return new pl({...t,checks:[],...$i(i),entries:r})},e.exclude=(e,i)=>{const r={...t.entries};for(const t of e){if(!n.has(t))throw new Error(`Key ${t} not found in enum`);delete r[t]}return new pl({...t,checks:[],...$i(i),entries:r})}});function hl(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new pl({type:"enum",entries:n,...$i(t)})}function fl(e,t){return new pl({type:"enum",entries:e,...$i(t)})}const gl=li("ZodLiteral",(e,t)=>{oa.init(e,t),ud.init(e,t),e._zod.processJSONSchema=(t,n,i)=>((e,t,n)=>{const i=e._zod.def,r=[];for(const e of i.values)if(void 0===e){if("throw"===t.unrepresentable)throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if("bigint"==typeof e){if("throw"===t.unrepresentable)throw new Error("BigInt literals cannot be represented in JSON Schema");r.push(Number(e))}else r.push(e);if(0===r.length);else if(1===r.length){const e=r[0];n.type=null===e?"null":typeof e,"draft-04"===t.target||"openapi-3.0"===t.target?n.enum=[e]:n.const=e}else r.every(e=>"number"==typeof e)&&(n.type="number"),r.every(e=>"string"==typeof e)&&(n.type="string"),r.every(e=>"boolean"==typeof e)&&(n.type="boolean"),r.every(e=>null===e)&&(n.type="null"),n.enum=r})(e,t,n),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 ml(e,t){return new gl({type:"literal",values:Array.isArray(e)?e:[e],...$i(t)})}const yl=li("ZodFile",(e,t)=>{sa.init(e,t),ud.init(e,t),e._zod.processJSONSchema=(t,n,i)=>((e,t,n)=>{const i=n,r={type:"string",format:"binary",contentEncoding:"binary"},{minimum:o,maximum:s,mime:a}=e._zod.bag;void 0!==o&&(r.minLength=o),void 0!==s&&(r.maxLength=s),a?1===a.length?(r.contentMediaType=a[0],Object.assign(i,r)):(Object.assign(i,r),i.anyOf=a.map(e=>({contentMediaType:e}))):Object.assign(i,r)})(e,0,n),e.min=(t,n)=>e.check(hc(t,n)),e.max=(t,n)=>e.check(pc(t,n)),e.mime=(t,n)=>e.check(Ac(Array.isArray(t)?t:[t],n))});function vl(e){return function(e,t){return new e({type:"file",...$i(t)})}(yl,e)}const Il=li("ZodTransform",(e,t)=>{aa.init(e,t),ud.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t)=>{if("throw"===t.unrepresentable)throw new Error("Transforms cannot be represented in JSON Schema")})(0,e),e._zod.parse=(n,i)=>{if("backward"===i.direction)throw new hi(e.constructor.name);n.addIssue=i=>{if("string"==typeof i)n.issues.push(Zi(i,n.value,t));else{const t=i;t.fatal&&(t.continue=!1),t.code??(t.code="custom"),t.input??(t.input=n.value),t.inst??(t.inst=e),n.issues.push(Zi(t))}};const r=t.transform(n.value,n);return r instanceof Promise?r.then(e=>(n.value=e,n)):(n.value=r,n)}});function wl(e){return new Il({type:"transform",transform:e})}const _l=li("ZodOptional",(e,t)=>{da.init(e,t),ud.init(e,t),e._zod.processJSONSchema=(t,n,i)=>Hc(e,t,0,i),e.unwrap=()=>e._zod.def.innerType});function El(e){return new _l({type:"optional",innerType:e})}const Sl=li("ZodExactOptional",(e,t)=>{ua.init(e,t),ud.init(e,t),e._zod.processJSONSchema=(t,n,i)=>Hc(e,t,0,i),e.unwrap=()=>e._zod.def.innerType});function bl(e){return new Sl({type:"optional",innerType:e})}const Al=li("ZodNullable",(e,t)=>{la.init(e,t),ud.init(e,t),e._zod.processJSONSchema=(t,n,i)=>((e,t,n,i)=>{const r=e._zod.def,o=Pc(r.innerType,t,i),s=t.seen.get(e);"openapi-3.0"===t.target?(s.ref=r.innerType,n.nullable=!0):n.anyOf=[o,{type:"null"}]})(e,t,n,i),e.unwrap=()=>e._zod.def.innerType});function Dl(e){return new Al({type:"nullable",innerType:e})}function kl(e){return El(Dl(e))}const Tl=li("ZodDefault",(e,t)=>{pa.init(e,t),ud.init(e,t),e._zod.processJSONSchema=(t,n,i)=>((e,t,n,i)=>{const r=e._zod.def;Pc(r.innerType,t,i),t.seen.get(e).ref=r.innerType,n.default=JSON.parse(JSON.stringify(r.defaultValue))})(e,t,n,i),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Cl(e,t){return new Tl({type:"default",innerType:e,get defaultValue(){return"function"==typeof t?t():Oi(t)}})}const Nl=li("ZodPrefault",(e,t)=>{fa.init(e,t),ud.init(e,t),e._zod.processJSONSchema=(t,n,i)=>((e,t,n,i)=>{const r=e._zod.def;Pc(r.innerType,t,i),t.seen.get(e).ref=r.innerType,"input"===t.io&&(n._prefault=JSON.parse(JSON.stringify(r.defaultValue)))})(e,t,n,i),e.unwrap=()=>e._zod.def.innerType});function Ol(e,t){return new Nl({type:"prefault",innerType:e,get defaultValue(){return"function"==typeof t?t():Oi(t)}})}const zl=li("ZodNonOptional",(e,t)=>{ga.init(e,t),ud.init(e,t),e._zod.processJSONSchema=(t,n,i)=>((e,t,n,i)=>{const r=e._zod.def;Pc(r.innerType,t,i),t.seen.get(e).ref=r.innerType})(e,t,0,i),e.unwrap=()=>e._zod.def.innerType});function Rl(e,t){return new zl({type:"nonoptional",innerType:e,...$i(t)})}const Pl=li("ZodSuccess",(e,t)=>{ya.init(e,t),ud.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t,n)=>{n.type="boolean"})(0,0,t),e.unwrap=()=>e._zod.def.innerType});function xl(e){return new Pl({type:"success",innerType:e})}const $l=li("ZodCatch",(e,t)=>{va.init(e,t),ud.init(e,t),e._zod.processJSONSchema=(t,n,i)=>((e,t,n,i)=>{const r=e._zod.def;let o;Pc(r.innerType,t,i),t.seen.get(e).ref=r.innerType;try{o=r.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=o})(e,t,n,i),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Ll(e,t){return new $l({type:"catch",innerType:e,catchValue:"function"==typeof t?t:()=>t})}const Ml=li("ZodNaN",(e,t)=>{Ia.init(e,t),ud.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t)=>{if("throw"===t.unrepresentable)throw new Error("NaN cannot be represented in JSON Schema")})(0,e)});function Ul(e){return function(e,t){return new e({type:"nan",...$i(t)})}(Ml,e)}const jl=li("ZodPipe",(e,t)=>{wa.init(e,t),ud.init(e,t),e._zod.processJSONSchema=(t,n,i)=>((e,t,n,i)=>{const r=e._zod.def,o="input"===t.io?"transform"===r.in._zod.def.type?r.out:r.in:r.out;Pc(o,t,i),t.seen.get(e).ref=o})(e,t,0,i),e.in=t.in,e.out=t.out});function Hl(e,t){return new jl({type:"pipe",in:e,out:t})}const Kl=li("ZodCodec",(e,t)=>{jl.init(e,t),Ea.init(e,t)});function Vl(e,t,n){return new Kl({type:"pipe",in:e,out:t,transform:n.decode,reverseTransform:n.encode})}const Fl=li("ZodReadonly",(e,t)=>{Aa.init(e,t),ud.init(e,t),e._zod.processJSONSchema=(t,n,i)=>((e,t,n,i)=>{const r=e._zod.def;Pc(r.innerType,t,i),t.seen.get(e).ref=r.innerType,n.readOnly=!0})(e,t,n,i),e.unwrap=()=>e._zod.def.innerType});function Bl(e){return new Fl({type:"readonly",innerType:e})}const Zl=li("ZodTemplateLiteral",(e,t)=>{ka.init(e,t),ud.init(e,t),e._zod.processJSONSchema=(t,n,i)=>((e,t,n)=>{const i=n,r=e._zod.pattern;if(!r)throw new Error("Pattern not found in template literal");i.type="string",i.pattern=r.source})(e,0,n)});function Jl(e,t){return new Zl({type:"template_literal",parts:e,...$i(t)})}const ql=li("ZodLazy",(e,t)=>{Na.init(e,t),ud.init(e,t),e._zod.processJSONSchema=(t,n,i)=>((e,t,n,i)=>{const r=e._zod.innerType;Pc(r,t,i),t.seen.get(e).ref=r})(e,t,0,i),e.unwrap=()=>e._zod.def.getter()});function Wl(e){return new ql({type:"lazy",getter:e})}const Gl=li("ZodPromise",(e,t)=>{Ca.init(e,t),ud.init(e,t),e._zod.processJSONSchema=(t,n,i)=>((e,t,n,i)=>{const r=e._zod.def;Pc(r.innerType,t,i),t.seen.get(e).ref=r.innerType})(e,t,0,i),e.unwrap=()=>e._zod.def.innerType});function Yl(e){return new Gl({type:"promise",innerType:e})}const Xl=li("ZodFunction",(e,t)=>{Ta.init(e,t),ud.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t)=>{if("throw"===t.unrepresentable)throw new Error("Function types cannot be represented in JSON Schema")})(0,e)});function Ql(e){return new Xl({type:"function",input:Array.isArray(e?.input)?il(e?.input):e?.input??Ku(Pu()),output:e?.output??Pu()})}const ep=li("ZodCustom",(e,t)=>{Oa.init(e,t),ud.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t)=>{if("throw"===t.unrepresentable)throw new Error("Custom types cannot be represented in JSON Schema")})(0,e)});function tp(e){const t=new Eo({check:"custom"});return t._zod.check=e,t}function np(e,t){return function(e,t,n){const i=$i(n);return i.abort??(i.abort=!0),new e({type:"custom",check:"custom",fn:t,...i})}(ep,e??(()=>!0),t)}function ip(e,t={}){return function(e,t,n){return new e({type:"custom",check:"custom",fn:t,...$i(n)})}(ep,e,t)}function rp(e){return function(e){const t=function(e){const t=new Eo({check:"custom",...$i(void 0)});return t._zod.check=e,t}(n=>(n.addIssue=e=>{if("string"==typeof e)n.issues.push(Zi(e,n.value,t._zod.def));else{const i=e;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=n.value),i.inst??(i.inst=t),i.continue??(i.continue=!t._zod.def.abort),n.issues.push(Zi(i))}},e(n.value,n)));return t}(e)}const op=function(e){const t=new Eo({check:"describe"});return t._zod.onattach=[t=>{const n=Pa.get(t)??{};Pa.add(t,{...n,description:e})}],t._zod.check=()=>{},t},sp=function(e){const t=new Eo({check:"meta"});return t._zod.onattach=[t=>{const n=Pa.get(t)??{};Pa.add(t,{...n,...e})}],t._zod.check=()=>{},t};function ap(e,t={}){const n=new ep({type:"custom",check:"custom",fn:t=>t instanceof e,abort:!0,...$i(t)});return n._zod.bag.Class=e,n._zod.check=t=>{t.value instanceof e||t.issues.push({code:"invalid_type",expected:e.name,input:t.value,inst:n,path:[...n._zod.def.path??[]]})},n}const cp=(...e)=>function(e,t){const n=$i(t);let i=n.truthy??["true","1","yes","on","y","enabled"],r=n.falsy??["false","0","no","off","n","disabled"];"sensitive"!==n.case&&(i=i.map(e=>"string"==typeof e?e.toLowerCase():e),r=r.map(e=>"string"==typeof e?e.toLowerCase():e));const o=new Set(i),s=new Set(r),a=e.Codec??Ea,c=e.Boolean??As,d=new a({type:"pipe",in:new(e.String??Wo)({type:"string",error:n.error}),out:new c({type:"boolean",error:n.error}),transform:(e,t)=>{let i=e;return"sensitive"!==n.case&&(i=i.toLowerCase()),!!o.has(i)||!s.has(i)&&(t.issues.push({code:"invalid_value",expected:"stringbool",values:[...o,...s],input:t.value,inst:d,continue:!1}),{})},reverseTransform:(e,t)=>!0===e?i[0]||"true":r[0]||"false",error:n.error});return d}({Codec:Kl,Boolean:vu,String:pd},...e);function dp(e){const t=Wl(()=>Wu([hd(e),lu(),Iu(),Nu(),Ku(t),ol(hd(),t)]));return t}function up(e,t){return Hl(wl(e),t)}var lp;lp||(lp={}),new Set(["$schema","$ref","$defs","definitions","$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor","type","enum","const","anyOf","oneOf","allOf","not","properties","required","additionalProperties","patternProperties","propertyNames","minProperties","maxProperties","items","prefixItems","additionalItems","minItems","maxItems","uniqueItems","contains","minContains","maxContains","minLength","maxLength","pattern","format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","description","default","contentEncoding","contentMediaType","contentSchema","unevaluatedItems","unevaluatedProperties","if","then","else","dependentSchemas","dependentRequired","nullable","readOnly"]),gi({localeError:(()=>{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",jwt:"JWT",template_literal:"input"},i={nan:"NaN"};return e=>{switch(e.code){case"invalid_type":{const t=i[e.expected]??e.expected,n=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);return`Invalid input: expected ${t}, received ${i[n]??n}`}case"invalid_value":return 1===e.values.length?`Invalid input: expected ${Li(e.values[0])}`:`Invalid option: expected one of ${yi(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",i=t(e.origin);return i?`Too big: expected ${e.origin??"value"} to have ${n}${e.maximum.toString()} ${i.unit??"elements"}`:`Too big: expected ${e.origin??"value"} to be ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",i=t(e.origin);return i?`Too small: expected ${e.origin} to have ${n}${e.minimum.toString()} ${i.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":""}: ${yi(e.keys,", ")}`;case"invalid_key":return`Invalid key in ${e.origin}`;case"invalid_union":default:return"Invalid input";case"invalid_element":return`Invalid value in ${e.origin}`}}})()});const pp="https://schema.kya-os.org/v1/protocol/audit/event/v1.0.0",hp="https://schema.kya-os.org/v1/protocol/audit/entry/v1.0.0",fp="https://schema.kya-os.org/v1/protocol/audit/receipt/v1.0.0",gp="KYA-AUDIT-JCS-SHA256-JWS-2026",mp="https://schema.kya-os.org/v1/protocol/audit/checkpoint/v1.0.0",yp="KYA-AUDIT-RFC9162-SHA256-JWS-2026",vp="https://schema.kya-os.org/v1/protocol/audit/bundle-manifest/v1.0.0",Ip="KYA-AUDIT-BUNDLE-JCS-SHA256-JWS-2026",wp=256,_p=4096,Ep=hd().max(20).regex(/^(0|[1-9][0-9]*)$/),Sp=hd().regex(/^sha256:[a-f0-9]{64}$/),bp=hd().min(5).max(2048).regex(/^did:[^\r\n]+$/),Ap=Bu({did:bp,kid:hd().min(1).max(2304),alg:hl(["EdDSA","ES256"])}).strict(),Dp=Bu({objectId:hd().min(1).max(wp),ciphertextDigest:Sp,plaintextCommitment:Sp.optional(),mediaType:hd().min(1).max(wp),size:Ep,encryption:Bu({suite:ml("A256GCM"),keyId:hd().min(1).max(wp),nonce:hd().min(1).max(wp),aadDigest:Sp}).strict()}).strict(),kp=Qu("kind",[Bu({kind:ml("public_did"),did:bp}).strict(),Bu({kind:ml("pairwise_did"),did:bp}).strict(),Bu({kind:ml("keyed_commitment"),value:Sp,keyId:hd().min(1).max(wp)}).strict(),Bu({kind:ml("evidence_ref"),ref:Dp}).strict()]),Tp=Qu("family",[Bu({family:ml("session"),phase:hl(["established","rejected","expired","replay_rejected"]),reasonCode:hd().min(1).max(128).optional()}).strict(),Bu({family:ml("tool"),phase:hl(["started","completed","failed","denied","challenged"]),attempt:Ep,idempotencyRef:hd().min(1).max(wp).optional()}).strict(),Bu({family:ml("proof"),phase:hl(["generated","verified","rejected"]),proofDigest:Sp.optional(),verificationCode:hd().min(1).max(128).optional()}).strict(),Bu({family:ml("delegation"),phase:hl(["issued","verified","rejected","revoked","cascade_revoked","outbound_attached"]),delegationRef:hd().min(1).max(wp),parentRef:hd().min(1).max(wp).optional(),statusEvidence:Ku(Dp).max(256).optional()}).strict(),Bu({family:ml("authorization"),phase:hl(["evaluated","approved","denied","step_up_required","grant_used"]),policyDigest:Sp.optional(),grantRef:hd().min(1).max(wp).optional()}).strict(),Bu({family:ml("consent"),phase:hl(["requested","approved","denied","credential_required","credential_verified","credential_failed"]),consentRef:hd().min(1).max(wp).optional()}).strict(),Bu({family:ml("key"),phase:hl(["rotated","policy_changed","configuration_changed","integrity_suite_transitioned"]),previousSigner:Ap.optional(),nextSigner:Ap.optional(),configurationDigest:Sp.optional()}).strict(),Bu({family:ml("ledger"),phase:hl(["epoch_started","epoch_transitioned","checkpoint_created","checkpoint_anchored","checkpoint_anchor_failed","evidence_disposed","projection_reconciled"]),checkpointDigest:Sp.optional(),previousEpochId:hd().min(1).max(wp).optional(),previousTerminalCheckpointDigest:Sp.optional(),successorEpochIds:Ku(hd().min(1).max(wp)).max(256).optional(),targetEvidenceRef:Dp.optional()}).strict(),Bu({family:ml("administration"),phase:hl(["source_high_water","accessed","exported","legal_hold_applied","retention_executed"]),purpose:hd().min(1).max(wp).optional(),sourceSequence:Ep.optional(),selectionDigest:Sp.optional()}).strict()]),Cp=Bu({source:hl(["delegation","grant","anonymous","policy"]),decision:hl(["allowed","denied","step_up_required","needs_authorization"]),scopeId:hd().min(1).max(wp).optional(),delegationRef:hd().min(1).max(wp).optional(),delegationCredentialDigest:Sp.optional(),delegationChainDigests:Ku(Sp).max(256).optional(),statusEvidence:Ku(Dp).max(256).optional(),grantRef:hd().min(1).max(wp).optional(),policyId:hd().min(1).max(wp).optional(),policyVersion:hd().min(1).max(wp).optional(),policyDigest:Sp.optional(),verificationCode:hd().min(1).max(128).optional()}).strict(),Np=Bu({schema:ml(pp),eventId:hd().min(1).max(256),eventType:hl(ui),eventVersion:ml("1.0.0"),binding:hd().max(wp).regex(/^urn:kya-os:audit-binding:[a-z0-9][a-z0-9._:-]*$/),occurredAt:lu().int().nonnegative(),tenantRef:kp,source:Bu({producer:kp,sourceId:hd().min(1).max(256),sourceSequence:Ep.optional(),previousSourceEventDigest:Sp.optional()}).strict(),correlationId:hd().min(1).max(256).optional(),causationId:hd().min(1).max(256).optional(),trace:Bu({traceId:hd().regex(/^[a-f0-9]{32}$/).optional(),spanId:hd().regex(/^[a-f0-9]{16}$/).optional()}).strict().optional(),session:Bu({ref:kp,handshakeNonceCommitment:Sp.optional()}).strict().optional(),actor:kp.optional(),responsibleParty:kp.optional(),resource:kp.optional(),action:Bu({category:hd().min(1).max(128),name:hd().min(1).max(256).optional(),detailRef:Dp.optional()}).strict(),outcome:hl(["succeeded","failed","denied","challenged","unknown"]),reason:Bu({code:hd().min(1).max(128),detailRef:Dp.optional()}).strict().optional(),authorization:Cp.optional(),proof:Dp.optional(),evidence:Ku(Dp).max(256),details:Tp,privacy:Bu({classification:hl(["public","internal","confidential","restricted"]),retentionClass:hd().min(1).max(128),legalHold:hd().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}`})}),Op=Bu({schema:ml(hp),ledgerId:hd().min(1).max(256),ledgerEpochId:hd().min(1).max(256),sequence:Ep,previousEntryDigest:Sp.nullable(),recordedAt:lu().int().nonnegative(),recorder:Ap,eventDigest:Sp,event:Np,evidenceManifestDigest:Sp,integritySuite:ml(gp)}).strict(),zp=Bu({schema:ml(fp),ledgerId:hd().min(1).max(256),ledgerEpochId:hd().min(1).max(256),sequence:Ep,eventId:hd().min(1).max(256),entryDigest:Sp,previousEntryDigest:Sp.nullable(),recordedAt:lu().int().nonnegative(),recorder:Ap,integritySuite:ml(gp)}).strict(),Rp=Bu({schema:ml(mp),checkpointId:hd().min(1).max(512),ledgerId:hd().min(1).max(256),ledgerEpochId:hd().min(1).max(256),treeSize:Ep,firstSequence:Ep,lastSequence:Ep,rootDigest:Sp,headEntryDigest:Sp,previousCheckpointDigest:Sp.nullable(),createdAt:lu().int().nonnegative(),issuer:Ap,integritySuite:ml(yp)}).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"})}),Pp=Bu({core:Rp,checkpointDigest:Sp,jws:hd().min(1).max(_p)}).strict(),xp=Bu({core:Op,eventDigest:Sp,entryDigest:Sp,recorderReceipt:Bu({core:zp,jws:hd().min(1).max(_p)}).strict()}).strict(),$p=Bu({core:Bu({schema:ml("https://schema.kya-os.org/v1/protocol/audit/observation/v1.0.0"),observerId:hd().min(1).max(256),observer:Ap,ledgerId:hd().min(1).max(256),ledgerEpochId:hd().min(1).max(256),checkpointDigest:Sp,treeSize:Ep,observedAt:lu().int().nonnegative(),previousObservationDigest:Sp.nullable()}).strict(),observationDigest:Sp,jws:hd().min(1).max(_p)}).strict(),Lp=Bu({schema:ml("https://schema.kya-os.org/v1/protocol/audit/anchor-receipt/v1.0.0"),kind:hl(["worm","rfc3161","scitt"]),providerId:hd().min(1).max(256),checkpointDigest:Sp,issuedAt:lu().int().nonnegative(),receiptData:hd().min(1).max(65536).optional()}).strict(),Mp=Bu({leafIndex:Ep,treeSize:Ep,auditPath:Ku(Sp)}).strict(),Up=Bu({oldTreeSize:Ep,newTreeSize:Ep,auditPath:Ku(Sp)}).strict(),jp=Bu({ledgerId:hd().min(1).max(256),ledgerEpochId:hd().min(1).max(256),sequence:Ep,entryDigest:Sp,checkpointDigest:Sp,proof:Mp}).strict(),Hp=Bu({ledgerId:hd().min(1).max(256),ledgerEpochId:hd().min(1).max(256),oldCheckpointDigest:Sp,newCheckpointDigest:Sp,proof:Up}).strict(),Kp=Bu({ledgerId:hd().min(1).max(256),ledgerEpochId:hd().min(1).max(256),firstSequence:Ep,lastSequence:Ep,expectedHeadDigest:Sp,checkpointTreeSizes:Ku(Ep).max(256)}).strict().superRefine((e,t)=>{BigInt(e.lastSequence)<BigInt(e.firstSequence)&&t.addIssue({code:"custom",message:"Bundle selection range is reversed"})}),Vp=Bu({path:hd().min(1).max(1024),mediaType:hd().min(1).max(256),disposition:hl(["included","redacted","disposed","unavailable","policy_excluded"]),digest:Sp.optional(),size:Ep.optional(),reasonCode:hd().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"})}),Fp=Bu({schema:ml(vp),bundleId:hd().min(1).max(256),formatVersion:ml("1.0.0"),selections:Ku(Kp).min(1),exporter:Ap,purpose:hd().min(1).max(256),exportedAt:lu().int().nonnegative(),verificationPolicyDigest:Sp,inventory:Ku(Vp).max(1e4),integritySuite:ml(Ip)}).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"})}),Bp=Vp.extend({content:Pu().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"})}}),Zp=Bu({manifest:Bu({core:Fp,manifestDigest:Sp,jws:hd().min(1).max(_p)}).strict(),components:Ku(Bp)}).strict();function Jp(e){return new Set(e).size===e.length}const qp=Bu({signer:Ap,validFrom:lu().int().nonnegative().optional(),validUntil:lu().int().nonnegative().optional(),validFromCheckpoint:Sp.optional(),validUntilCheckpoint:Sp.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"})}),Wp=Bu({policyId:hd().min(1).max(256),trustedLedgerEpochs:Ku(Bu({ledgerId:hd().min(1).max(256),ledgerEpochId:hd().min(1).max(256),recorderKeys:Ku(qp).min(1),validFromCheckpoint:Sp.optional(),validUntilCheckpoint:Sp.optional()}).strict()),trustedObservers:Ku(qp),trustedSupportingAnchors:Ku(Bu({kind:hl(["worm","rfc3161","scitt"]),providerId:hd().min(1).max(256),validFrom:lu().int().nonnegative().optional(),validUntil:lu().int().nonnegative().optional()}).strict()).optional(),authorizedExporters:Ku(Bu({signerKeys:Ku(qp).min(1),allowedLedgerIds:Ku(hd().min(1).max(256)).min(1).refine(Jp,"Allowed ledger IDs must be unique"),allowedPurposes:Ku(hd().min(1).max(256)).min(1).refine(Jp,"Allowed purposes must be unique")}).strict()),acceptedIntegritySuites:Ku(hd().min(1).max(128)).min(1).refine(Jp,"Accepted integrity suites must be unique"),acceptedAlgorithms:Ku(hl(["EdDSA","ES256"])).min(1).refine(Jp,"Accepted algorithms must be unique"),keyRevocationMode:hl(["as_observed","current","both"]),requiredCheckpointFreshnessMs:lu().int().nonnegative().optional(),requiredAuditProfile:hl(["AAP-0","AAP-1","AAP-2","AAP-3","AAP-4"]).optional()}).strict();function Gp(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))Gp(n,t);return Object.freeze(e)}function Yp(e){return Gp(structuredClone(e))}function Xp(e){return Yp(Np.parse(e))}function Qp(e){return Yp(Op.parse(e))}function eh(e){return Yp(xp.parse(e))}function th(e){return Yp(zp.parse(e))}function nh(e){return Yp(Rp.parse(e))}function ih(e){return Yp(Pp.parse(e))}function rh(e){return Yp($p.parse(e))}function oh(e){return Yp(Fp.parse(e))}function sh(e){return Yp(Zp.parse(e))}function ah(e){return Yp(Wp.parse(e))}const ch=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 dh(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 uh=new TextEncoder,lh=/^sha256:[a-f0-9]{64}$/;class ph{crypto;constructor(e){this.crypto=e}async sha256(e){const t=await this.crypto.hash(e);if(!lh.test(t))throw new TypeError("Audit hasher must return sha256:<lowercase-hex>");return t}}class hh{keys;constructor(e){this.keys=e}async verify(e,t,n){try{if(!n.kid.startsWith(`${n.did}#`))return!1;const i=await this.keys.resolve(n);if(null===i)return!1;const r=await He(t,i,{algorithms:[n.alg]});return r.protectedHeader.alg===n.alg&&r.protectedHeader.kid===n.kid&&r.payload.length===e.length&&r.payload.every((t,n)=>t===e[n])}catch{return!1}}}class fh{ref;privateKey;constructor(e,t){this.ref=e,this.privateKey=t}async sign(e){return new rt(e).setProtectedHeader({alg:this.ref.alg,kid:this.ref.kid}).sign(this.privateKey)}}async function gh(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 i=uh.encode(`${t}\0`),r=M(n),o=new Uint8Array(i.length+r.length);return o.set(i),o.set(r,i.length),e.sha256(o)}function mh(e){return"evidence_ref"===e?.kind?[e.ref]:[]}function yh(e){const t="delegation"===e.details.family?e.details.statusEvidence??[]:"ledger"===e.details.family&&void 0!==e.details.targetEvidenceRef?[e.details.targetEvidenceRef]:[];return[...mh(e.tenantRef),...mh(e.source.producer),...mh(e.session?.ref),...mh(e.actor),...mh(e.responsibleParty),...mh(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 vh=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 Ih(e){return{refs:yh(e)}}function wh(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 _h(e,t){return gh(e,vh.event,t)}async function Eh(e,t){return gh(e,vh.entry,t)}async function Sh(e,t){return gh(e,vh.evidenceManifest,Ih(t))}const bh={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 Ah extends Error{code;details;constructor(e,t,n,i){super(t,i),this.code=e,this.details=n,this.name="AuditProtocolError"}}class Dh{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),i=await this.config.crypto.subtle.encrypt({name:"AES-GCM",iv:Th(t),additionalData:Th(e.aad),tagLength:128},e.key,Th(e.plaintext)),r=new Uint8Array(i),o=await this.config.hasher.sha256(r),s=await this.config.hasher.sha256(e.aad),a={objectId:`evi_${p(n)}`,ciphertextDigest:o,...e.plaintextCommitment?{plaintextCommitment:e.plaintextCommitment}:{},mediaType:e.mediaType,size:String(r.byteLength),encryption:{suite:"A256GCM",keyId:e.keyId,nonce:p(t),aadDigest:s}};return{ref:Object.freeze(a),ciphertext:r}}async decrypt(e,t,n){if(0===n.byteLength)throw new TypeError("Evidence decryption requires entity-scoped authenticated data");const i=await this.config.hasher.sha256(e.ciphertext),r=await this.config.hasher.sha256(n);if(i!==e.ref.ciphertextDigest||r!==e.ref.encryption.aadDigest)throw new Ah(bh.EVIDENCE_INTEGRITY,"Evidence ciphertext or authenticated metadata digest does not match");try{const i=await this.config.crypto.subtle.decrypt({name:"AES-GCM",iv:Th(u(e.ref.encryption.nonce)),additionalData:Th(n),tagLength:128},t,Th(e.ciphertext));return new Uint8Array(i)}catch(e){throw new Ah(bh.EVIDENCE_INTEGRITY,"Evidence AEAD verification failed",void 0,{cause:e})}}}class kh{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 Ah(bh.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 i=0;i<e.byteLength;i+=1)n|=e[i]^t[i];return 0===n}(t.ciphertext,e.ciphertext))throw new Ah(bh.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 Ah(bh.EVIDENCE_ACCESS_DENIED,"Evidence access policy denied this actor and purpose");const n=this.states.get(e.objectId),i=void 0===n?"missing":null===n.ciphertext?"disposed":"found";return await(this.options.onAccess?.({ref:e,context:t,result:i})),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 Ah(bh.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 Th(e){return Uint8Array.from(e).buffer}const Ch=/^sha256:([a-f0-9]{64})$/;function Nh(e){const t=Ch.exec(e);if(null===t)throw new TypeError("Expected sha256:<lowercase-hex> digest");const n=t[1],i=new Uint8Array(32);for(let e=0;e<i.length;e+=1)i[e]=Number.parseInt(n.slice(2*e,2*e+2),16);return i}function Oh(...e){const t=new Uint8Array(e.reduce((e,t)=>e+t.length,0));let n=0;for(const i of e)t.set(i,n),n+=i.length;return t}function zh(e){let t=1;for(;2*t<e;)t*=2;return t}function Rh(e,t){if(!Number.isSafeInteger(e)||e<0)throw new RangeError(`${t} must be a non-negative safe integer`)}class Ph{hasher;constructor(e){this.hasher=e}async leafHash(e){return this.hasher.sha256(Oh(Uint8Array.of(0),Nh(e)))}async nodeHash(e,t){return this.hasher.sha256(Oh(Uint8Array.of(1),Nh(e),Nh(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=zh(e.length),[n,i]=await Promise.all([this.root(e.slice(0,t)),this.root(e.slice(t))]);return this.nodeHash(n,i)}async inclusionProof(e,t){if(Rh(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=zh(e.length);if(t<n){const[i,r]=await Promise.all([this.buildInclusionProof(e.slice(0,n),t),this.root(e.slice(n))]);return[...i,r]}const[i,r]=await Promise.all([this.buildInclusionProof(e.slice(n),t-n),this.root(e.slice(0,n))]);return[...i,r]}async verifyInclusion(e){try{if(Rh(e.leafIndex,"Leaf index"),Rh(e.treeSize,"Tree size"),0===e.treeSize||e.leafIndex>=e.treeSize)return!1;let t=e.leafIndex,n=e.treeSize-1,i=await this.leafHash(e.leaf);for(const r of e.auditPath){if(0===n)return!1;if(1&~t&&t!==n)i=await this.nodeHash(i,r);else for(i=await this.nodeHash(r,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&&i===e.root}catch{return!1}}async consistencyProof(e,t){if(Rh(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 i=zh(t.length);if(e<=i){const[r,o]=await Promise.all([this.buildConsistencyProof(e,t.slice(0,i),n),this.root(t.slice(i))]);return[...r,o]}const[r,o]=await Promise.all([this.buildConsistencyProof(e-i,t.slice(i),!1),this.root(t.slice(0,i))]);return[...r,o]}async verifyConsistency(e){try{if(Rh(e.oldSize,"Old tree size"),Rh(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 i,r,o=0;if(0===t)i=e.oldRoot,r=e.oldRoot;else{const t=e.auditPath[o++];if(void 0===t)return!1;i=t,r=t}for(;o<e.auditPath.length;o+=1){if(0===n)return!1;const s=e.auditPath[o];if(1&~t&&t!==n)r=await this.nodeHash(r,s);else for(i=await this.nodeHash(s,i),r=await this.nodeHash(s,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&&i===e.oldRoot&&r===e.newRoot}catch{return!1}}}function xh(e){return`${e.ledgerId}\0${e.ledgerEpochId}`}function $h(e,t){return`${xh(e)}\0${t}`}function Lh(e,t){if(!/^(0|[1-9][0-9]*)$/.test(e))throw new Ah(bh.CHECKPOINT_INVALID,`${t} must be a canonical non-negative decimal string`);return BigInt(e)}function Mh(e,t){if(e>BigInt(Number.MAX_SAFE_INTEGER))throw new Ah(bh.CHECKPOINT_INVALID,`${t} exceeds this implementation's safe in-memory proof range`);return Number(e)}function Uh(e){if("object"!=typeof e||null===e||Object.isFrozen(e))return e;for(const t of Object.values(e))Uh(t);return Object.freeze(e)}class jh{checkpoints=new Map;latest=new Map;async getLatest(e){return this.latest.get(xh(e))??null}async getByTreeSize(e,t){return this.checkpoints.get($h(e,t))??null}async putIfAbsent(e){const t=e.core,n=$h(t,e.core.treeSize),i=this.checkpoints.get(n);if(void 0!==i)return i.checkpointDigest===e.checkpointDigest?{kind:"existing",checkpoint:i}:{kind:"conflict",checkpoint:i};const r=Uh(e);this.checkpoints.set(n,r);const o=this.latest.get(xh(t));return(void 0===o||BigInt(o.core.treeSize)<BigInt(e.core.treeSize))&&this.latest.set(xh(t),r),{kind:"inserted",checkpoint:r}}}class Hh{options;tree;clock;constructor(e){this.options=e,this.tree=new Ph(e.hasher),this.clock=e.clock??Date}async createCheckpoint(e){const t=await this.snapshotAtHead(e);if(0===t.length)throw new Ah(bh.CHECKPOINT_INVALID,"Cannot checkpoint an empty audit epoch");const n=String(t.length),i=await this.options.store.getLatest(e);if(null!==i){const e=Lh(i.core.treeSize,"Previous tree size");if(e>BigInt(t.length))throw new Ah(bh.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(i.core.rootDigest!==e||i.core.headEntryDigest!==t[t.length-1].entryDigest)throw new Ah(bh.CHECKPOINT_CONFLICT,"Journal content forked at the latest checkpointed tree size");return i}}const r=t[0],o=t[t.length-1],s=nh({schema:"https://schema.kya-os.org/v1/protocol/audit/checkpoint/v1.0.0",checkpointId:`checkpoint:${e.ledgerId}:${e.ledgerEpochId}:${n}`,...e,treeSize:n,firstSequence:r.core.sequence,lastSequence:o.core.sequence,rootDigest:await this.tree.root(t.map(e=>e.entryDigest)),headEntryDigest:o.entryDigest,previousCheckpointDigest:i?.checkpointDigest??null,createdAt:this.clock.now(),issuer:this.options.signer.ref,integritySuite:"KYA-AUDIT-RFC9162-SHA256-JWS-2026"}),a=Uh({core:s,checkpointDigest:await gh(this.options.hasher,vh.checkpoint,s),jws:await this.options.signer.sign(M(s))}),c=await this.options.store.putIfAbsent(a);if("conflict"===c.kind)throw new Ah(bh.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 i=await this.entriesForCheckpoint(e,n),r=i.findIndex(e=>e.core.sequence===t);if(r<0)throw new Ah(bh.CHECKPOINT_INVALID,"Sequence is not included in the checkpoint",{sequence:t,treeSize:n.core.treeSize});return Uh({leafIndex:String(r),treeSize:n.core.treeSize,auditPath:await this.tree.inclusionProof(i.map(e=>e.entryDigest),r)})}async consistencyProof(e,t,n){this.assertCheckpointLedger(e,n);const i=await this.entriesForCheckpoint(e,n),r=Mh(Lh(t,"Old tree size"),"Old tree size");return Uh({oldTreeSize:t,newTreeSize:n.core.treeSize,auditPath:await this.tree.consistencyProof(i.map(e=>e.entryDigest),r)})}async rootForRange(e,t){const n=Mh(Lh(t,"Tree size"),"Tree size");if(0===n)return this.tree.root([]);const i=await this.readEntries(e,n);if(i.length!==n)throw new Ah(bh.CHECKPOINT_INVALID,"Journal does not contain the requested tree range",{treeSize:t});return this.tree.root(i.map(e=>e.entryDigest))}async verifyInclusion(e,t,n){return n.treeSize===t.core.treeSize&&this.tree.verifyInclusion({leaf:e,leafIndex:Mh(Lh(n.leafIndex,"Leaf index"),"Leaf index"),treeSize:Mh(Lh(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:Mh(Lh(e.oldTreeSize,"Old tree size"),"Old tree size"),newSize:Mh(Lh(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=Mh(Lh(t.sequence,"Journal head sequence")+1n,"Journal tree size"),i=await this.readEntries(e,n),r=i[i.length-1];if(i.length!==n||r?.entryDigest!==t.entryDigest)throw new Ah(bh.JOURNAL_FAILURE,"Journal could not provide a stable range through its reported head");return i}async entriesForCheckpoint(e,t){const n=Mh(Lh(t.core.treeSize,"Checkpoint tree size"),"Checkpoint tree size"),i=await this.readEntries(e,n);if(i.length!==n||i[i.length-1]?.entryDigest!==t.core.headEntryDigest)throw new Ah(bh.CHECKPOINT_INVALID,"Journal range does not match the signed checkpoint head");return i}async readEntries(e,t){const n=[];for await(const i of this.options.journal.readRange({...e,limit:t})){if(BigInt(i.core.sequence)!==BigInt(n.length))throw new Ah(bh.JOURNAL_FAILURE,"Audit journal range is not contiguous from sequence zero");n.push(i)}return n}assertCheckpointLedger(e,t){if(t.core.ledgerId!==e.ledgerId||t.core.ledgerEpochId!==e.ledgerEpochId)throw new Ah(bh.LEDGER_MISMATCH,"Checkpoint belongs to a different ledger or epoch")}}class Kh{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 Ah(bh.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 Ah(bh.INVALID_CONFIGURATION,"Minimum checkpoint observers must be a non-negative safe integer")}async createAndPublish(e){const t=await this.options.checkpoints.createCheckpoint(e),n=[],i=[],r=[];await Promise.all(this.observers.map(async(e,i)=>{const o=await this.publishWithRetry("observer",i,()=>e.publish(t));o.ok?n.push(o.value):r.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?i.push(o.value):r.push(o.failure)})),n.sort((e,t)=>e.core.observerId.localeCompare(t.core.observerId)),i.sort((e,t)=>e.kind.localeCompare(t.kind)||e.providerId.localeCompare(t.providerId)),r.sort((e,t)=>e.role.localeCompare(t.role)||e.providerIndex-t.providerIndex);const o={checkpoint:t,observations:n,anchors:i,failures:r};return this.assertRequirements(o),await(this.options.onPublished?.(o)),o}async publishWithRetry(e,t,n,i){let r;for(let o=1;o<=this.maxAttempts;o+=1)try{return{ok:!0,value:await n()}}catch(n){if(r=n,o<this.maxAttempts)try{await(this.options.backoff?.({role:e,providerIndex:t,attempt:o,error:n}))}catch(r){return{ok:!1,failure:{role:e,providerIndex:t,...void 0===i?{}:{kind:i},attempts:o,error:new AggregateError([n,r],"Checkpoint publication backoff failed")}}}}return{ok:!1,failure:{role:e,providerIndex:t,...void 0===i?{}:{kind:i},attempts:this.maxAttempts,error:r}}}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 Ah(bh.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:i})=>({role:e,providerIndex:t,...void 0===n?{}:{kind:n},attempts:i}))})}}function Vh(e,t){return`${e}\0${t.ledgerId}\0${t.ledgerEpochId}`}function Fh(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 Bh{capabilities={durability:"ephemeral",atomicOffset:!0};offsets=new Map;records=new Map;async getOffset(e,t){const n=this.offsets.get(Vh(e,t));return void 0===n?null:{...n}}async compareAndApply(e){const t=Vh(e.projectionId,e.ledger),n=this.offsets.get(t)??null,i=this.records.get(t)?.find(t=>t.sequence===e.entry.core.sequence);if(void 0!==i)return i.entryDigest===e.entry.entryDigest?{kind:"duplicate"}:{kind:"conflict",actualOffset:n};if(r=n,o=e.expectedOffset,!(null===r||null===o?r===o:r.sequence===o.sequence&&r.entryDigest===o.entryDigest))return{kind:"conflict",actualOffset:n};var r,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=Vh(e,t);this.offsets.delete(n),this.records.delete(n)}async read(e,t){return(this.records.get(Vh(e,t))??[]).map(e=>({...e}))}corruptOffsetForTesting(e,t,n){this.offsets.set(Vh(e,t),{...n})}}class Zh{options;constructor(e){if(this.options=e,!e.projectionId)throw new Ah(bh.INVALID_CONFIGURATION,"Projection ID is required")}async synchronize(e){let t=await this.options.projections.getOffset(this.options.projectionId,e),n=0,i=0;for await(const r 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:r,record:Fh(r)});if("conflict"===o.kind)throw new Ah(bh.PROJECTION_CONFLICT,"Projection offset conflicted with the ordered ledger",{sequence:r.core.sequence,expectedOffset:t,actualOffset:o.actualOffset});"applied"===o.kind?n+=1:i+=1,t={sequence:r.core.sequence,entryDigest:r.entryDigest}}return{applied:n,duplicates:i}}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 i;return i=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:i,journalHead:t,projectionHead:n}}}const Jh=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 qh(e,t=[]){return{verdict:e,reasonCodes:[...new Set(t)].sort()}}function Wh(e,t){return e.did===t.did&&e.kid===t.kid&&e.alg===t.alg}function Gh(e,t){return(void 0===e.validFrom||t>=e.validFrom)&&(void 0===e.validUntil||t<=e.validUntil)}class Yh{options;constructor(e){this.options=e}async verifyEntries(e,t){if(!Wp.safeParse(t).success)return function(e){const t="object"==typeof e&&null!==e&&"string"==typeof e.policyId?e.policyId:"invalid-policy",n=qh("invalid",[Jh.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:qh("indeterminate",[Jh.NOT_EVALUATED]),currentAuthorization:qh("indeterminate",[Jh.NOT_EVALUATED])}}(t);const n=t,i=new Set,r=new Set,o=[];0===e.length&&r.add(Jh.BUNDLE_SELECTION_INCOMPLETE);for(const t of e){const e=xp.safeParse(t);if(!e.success){i.add(Jh.SCHEMA_INVALID),r.add(Jh.SCHEMA_INVALID);continue}const s=e.data,a=o.length;await this.verifyEntry(s,n,i),this.verifyChainPosition(s,o[a-1],a,r),o.push(s)}const s=o.some(e=>void 0!==e.core.event.authorization),[a,c]=void 0===this.options.authorization?[qh("indeterminate",[s?Jh.AUTHORIZATION_COLLATERAL_NOT_VERIFIED:Jh.AUTHORIZATION_EVIDENCE_MISSING]),qh("indeterminate",[Jh.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:qh(0===i.size&&e.length>0?"valid":"invalid",i),chainIntegrity:qh(0===r.size&&e.length>0?"valid":"invalid",r),checkpointIntegrity:qh("indeterminate",[Jh.CHECKPOINT_MISSING]),anchorIntegrity:qh("indeterminate",[Jh.OBSERVER_EVIDENCE_MISSING]),scopeEvidenceCompleteness:qh(e.length>0?"indeterminate":"invalid",[Jh.NOT_EVALUATED]),authorizedAsObserved:a,currentAuthorization:c}}async verifyCheckpoint(e,t,n){const i=new Set;if(!Wp.safeParse(n).success)return qh("invalid",[Jh.VERIFICATION_POLICY_INVALID]);const r=Pp.safeParse(e);if(!r.success)return qh("invalid",[Jh.SCHEMA_INVALID]);const o=r.data,s=o.core;n.acceptedIntegritySuites.includes(s.integritySuite)||i.add(Jh.UNSUPPORTED_SUITE),n.acceptedAlgorithms.includes(s.issuer.alg)||i.add(Jh.UNSUPPORTED_ALGORITHM);const a=n.trustedLedgerEpochs.find(e=>e.ledgerId===s.ledgerId&&e.ledgerEpochId===s.ledgerEpochId);a?.recorderKeys.some(e=>Wh(e.signer,s.issuer)&&Gh(e,s.createdAt))||i.add(Jh.UNTRUSTED_RECORDER),await gh(this.options.hasher,vh.checkpoint,s)!==o.checkpointDigest&&i.add(Jh.CHECKPOINT_DIGEST_MISMATCH),await this.options.signatures.verify(M(s),o.jws,s.issuer)||i.add(Jh.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)?i.add(Jh.CHECKPOINT_RANGE_MISMATCH):await new Ph(this.options.hasher).root(t.map(e=>e.entryDigest))!==s.rootDigest&&i.add(Jh.CHECKPOINT_ROOT_MISMATCH),qh(0===i.size?"valid":"invalid",i)}async verifyObservation(e,t,n){const i=new Set;let r=!1;if(!Wp.safeParse(n).success)return qh("invalid",[Jh.VERIFICATION_POLICY_INVALID]);const o=Pp.safeParse(e),s=$p.safeParse(t);if(!o.success||!s.success)return qh("invalid",[Jh.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&&i.add(Jh.SCHEMA_INVALID),d.ledgerId===a.core.ledgerId&&d.ledgerEpochId===a.core.ledgerEpochId&&d.checkpointDigest===a.checkpointDigest&&d.treeSize===a.core.treeSize||i.add(Jh.OBSERVATION_SCOPE_MISMATCH),n.acceptedAlgorithms.includes(d.observer.alg)||i.add(Jh.UNSUPPORTED_ALGORITHM),n.trustedObservers.some(e=>Wh(e.signer,d.observer)&&Gh(e,d.observedAt))||i.add(Jh.UNTRUSTED_OBSERVER),void 0!==n.requiredCheckpointFreshnessMs){const e=this.options.verifiedAt?.();void 0===e?(i.add(Jh.NOT_EVALUATED),r=!0):e-d.observedAt>n.requiredCheckpointFreshnessMs&&i.add(Jh.OBSERVATION_STALE)}await gh(this.options.hasher,vh.observation,d)!==c.observationDigest&&i.add(Jh.OBSERVATION_DIGEST_MISMATCH),await this.options.signatures.verify(M(d),c.jws,d.observer)||i.add(Jh.OBSERVATION_SIGNATURE_INVALID);const u=r&&[...i].every(e=>e===Jh.NOT_EVALUATED);return qh(0===i.size?"valid":u?"indeterminate":"invalid",i)}async verifyEntry(e,t,n){t.acceptedIntegritySuites.includes(e.core.integritySuite)||n.add(Jh.UNSUPPORTED_SUITE),t.acceptedAlgorithms.includes(e.core.recorder.alg)||n.add(Jh.UNSUPPORTED_ALGORITHM);const i=t.trustedLedgerEpochs.find(t=>t.ledgerId===e.core.ledgerId&&t.ledgerEpochId===e.core.ledgerEpochId),r=i?.recorderKeys.find(t=>Wh(t.signer,e.core.recorder)&&Gh(t,e.core.recordedAt));void 0===r&&n.add(Jh.UNTRUSTED_RECORDER);const o=await _h(this.options.hasher,e.core.event);o===e.core.eventDigest&&o===e.eventDigest||n.add(Jh.EVENT_DIGEST_MISMATCH),await Sh(this.options.hasher,e.core.event)!==e.core.evidenceManifestDigest&&n.add(Jh.EVIDENCE_MANIFEST_DIGEST_MISMATCH),await Eh(this.options.hasher,e.core)!==e.entryDigest&&n.add(Jh.ENTRY_DIGEST_MISMATCH),function(e,t){try{return L(e)===L(t)}catch{return!1}}(wh(e.core,e.entryDigest),e.recorderReceipt.core)||n.add(Jh.RECEIPT_MISMATCH),await this.options.signatures.verify(M(e.recorderReceipt.core),e.recorderReceipt.jws,e.core.recorder)||n.add(Jh.SIGNATURE_INVALID)}verifyChainPosition(e,t,n,i){if(void 0!==t){e.core.ledgerId===t.core.ledgerId&&e.core.ledgerEpochId===t.core.ledgerEpochId||i.add(Jh.LEDGER_SCOPE_MISMATCH);try{BigInt(e.core.sequence)!==BigInt(t.core.sequence)+1n&&i.add(Jh.SEQUENCE_GAP)}catch{i.add(Jh.SEQUENCE_GAP)}e.core.previousEntryDigest!==t.entryDigest&&i.add(Jh.PREDECESSOR_MISMATCH)}else"0"===e.core.sequence?null===e.core.previousEntryDigest&&"ledger.epoch.started"===e.core.event.eventType||i.add(Jh.GENESIS_INVALID):0===n&&null===e.core.previousEntryDigest&&i.add(Jh.PREDECESSOR_MISMATCH)}}function Xh(...e){return 0===e.length?qh("indeterminate",[Jh.NOT_EVALUATED]):qh(e.some(e=>"invalid"===e.verdict)?"invalid":e.every(e=>"valid"===e.verdict)?"valid":"indeterminate",e.flatMap(e=>e.reasonCodes))}const Qh="https://schema.kya-os.org/v1/protocol/audit/bundle-manifest/v1.0.0",ef=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 tf(e){if("object"!=typeof e||null===e||Object.isFrozen(e))return e;for(const t of Object.values(e))tf(t);return Object.freeze(e)}function nf(e){return JSON.parse(L(e))}function rf(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 of(e,t){return(void 0===e.validFrom||t>=e.validFrom)&&(void 0===e.validUntil||t<=e.validUntil)}function sf(e,t=[]){return{verdict:e,reasonCodes:[...new Set(t)].sort()}}class af{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)),i=[];for(const e of n){if(rf(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=nf(e.content),n=M(t);i.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");i.push({path:e.path,mediaType:e.mediaType,disposition:e.disposition,reasonCode:e.reasonCode})}}const r=i.map(e=>cf(e)),o=oh({schema:Qh,bundleId:e.bundleId,formatVersion:"1.0.0",selections:nf([...e.selections]),exporter:this.options.signer.ref,purpose:e.purpose,exportedAt:this.options.clock.now(),verificationPolicyDigest:e.verificationPolicyDigest,inventory:r,integritySuite:"KYA-AUDIT-BUNDLE-JCS-SHA256-JWS-2026"});return tf({manifest:{core:o,manifestDigest:await gh(this.options.hasher,vh.bundleManifest,o),jws:await this.options.signer.sign(M(o))},components:i})}}function cf(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 df(e,t){const n=[];for(const i of e.components)"included"===i.disposition&&i.mediaType===t&&Array.isArray(i.content)&&n.push(...i.content);return n}function uf(e){return`${e.ledgerId}\0${e.ledgerEpochId}`}function lf(e,t){const n=BigInt(e),i=BigInt(t);return n<i?-1:n>i?1:0}function pf(e,t,n){const i=new Set;for(const n of e){const e=t.filter(e=>e.core.ledgerId===n.ledgerId&&e.core.ledgerEpochId===n.ledgerEpochId),r=new Map;let o=!1;for(const t of e)r.has(t.core.sequence)?o=!0:r.set(t.core.sequence,t);const s=[...r.values()].sort((e,t)=>{const n=BigInt(e.core.sequence),i=BigInt(t.core.sequence);return n<i?-1:n>i?1:0});let a;try{a=BigInt(n.lastSequence)-BigInt(n.firstSequence)+1n}catch{i.add(Jh.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)&&i.add(Jh.BUNDLE_SELECTION_INCOMPLETE)}for(const e of n)"redacted"===e.disposition&&i.add(Jh.EXPLICITLY_REDACTED),"disposed"===e.disposition&&i.add(Jh.EXPLICITLY_DISPOSED),"unavailable"===e.disposition&&i.add(Jh.EXPLICITLY_UNAVAILABLE);return i.has(Jh.BUNDLE_SELECTION_INCOMPLETE)?sf("invalid",i):0===i.size?sf("valid"):sf("indeterminate",i)}async function hf(e,t,n){if(!Wp.safeParse(t).success){const e="string"==typeof t?.policyId?t.policyId:"invalid-policy",n=sf("invalid",[Jh.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:sf("indeterminate",[Jh.NOT_EVALUATED]),currentAuthorization:sf("indeterminate",[Jh.NOT_EVALUATED])}}if(!Zp.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:sf("invalid",[Jh.BUNDLE_SCHEMA_INVALID]),chainIntegrity:sf("invalid",[Jh.BUNDLE_SCHEMA_INVALID]),checkpointIntegrity:sf("indeterminate",[Jh.CHECKPOINT_MISSING]),anchorIntegrity:sf("indeterminate",[Jh.OBSERVER_EVIDENCE_MISSING]),scopeEvidenceCompleteness:sf("invalid",[Jh.BUNDLE_SCHEMA_INVALID]),authorizedAsObserved:sf("indeterminate",[Jh.AUTHORIZATION_COLLATERAL_NOT_VERIFIED]),currentAuthorization:sf("indeterminate",[Jh.CURRENT_AUTHORIZATION_NOT_EVALUATED])}}(t);const i=e,r=new Set,o=i.manifest.core;if(o?.schema===Qh&&"1.0.0"===o.formatVersion||r.add(Jh.BUNDLE_SCHEMA_INVALID),t.acceptedIntegritySuites.includes(o?.integritySuite??"")||r.add(Jh.UNSUPPORTED_SUITE),void 0!==o&&t.acceptedAlgorithms.includes(o.exporter.alg)||r.add(Jh.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,i=e.exporter,n.did===i.did&&n.kid===i.kid&&n.alg===i.alg&&of(t,e.exportedAt);var n,i}))}(o,t)||r.add(Jh.BUNDLE_EXPORTER_UNAUTHORIZED),void 0!==o){const[e,s]=await Promise.all([gh(n.hasher,vh.bundleManifest,o),gh(n.hasher,"org.kya-os.audit.verification-policy.v1",t)]);e!==i.manifest.manifestDigest&&r.add(Jh.BUNDLE_MANIFEST_DIGEST_MISMATCH),s!==o.verificationPolicyDigest&&r.add(Jh.VERIFICATION_POLICY_MISMATCH),await n.signatures.verify(M(o),i.manifest.jws,o.exporter)||r.add(Jh.BUNDLE_SIGNATURE_INVALID);const a=new Map(o.inventory.map(e=>[e.path,e])),c=new Map(i.components.map(e=>[e.path,e]));a.size===o.inventory.length&&c.size===i.components.length&&a.size===c.size||r.add(Jh.BUNDLE_INVENTORY_MISMATCH);for(const[e,t]of a){const i=c.get(e);if(void 0!==i&&L(t)===L(cf(i))){try{rf(e)}catch{r.add(Jh.BUNDLE_SCHEMA_INVALID)}if("included"===i.disposition){if(void 0===i.content){r.add(Jh.BUNDLE_INVENTORY_MISMATCH);continue}const e=M(i.content);i.size===String(e.length)&&i.digest===await n.hasher.sha256(e)||r.add(Jh.BUNDLE_COMPONENT_DIGEST_MISMATCH)}else void 0===i.content&&void 0!==i.reasonCode||r.add(Jh.BUNDLE_INVENTORY_MISMATCH)}else r.add(Jh.BUNDLE_INVENTORY_MISMATCH)}}const s=df(i,ef.entries),a=df(i,ef.checkpoints),c=df(i,ef.observations),d=df(i,ef.anchors),u=n.artifacts??new Yh(n),l=await async function(e,t,n){const i=new Map,r=[];for(const t of e){if(!xp.safeParse(t).success){r.push(t);continue}const e=t,n=uf(e.core),o=i.get(n)??[];o.push(e),i.set(n,o)}const o=await Promise.all([...[...i.values()].map(e=>n.verifyEntries(e,t)),...0===r.length?[]:[n.verifyEntries(r,t)]]);return 0===o.length?n.verifyEntries([],t):{...o[0],cryptographicIntegrity:Xh(...o.map(e=>e.cryptographicIntegrity)),chainIntegrity:Xh(...o.map(e=>e.chainIntegrity)),checkpointIntegrity:Xh(...o.map(e=>e.checkpointIntegrity)),anchorIntegrity:Xh(...o.map(e=>e.anchorIntegrity)),scopeEvidenceCompleteness:Xh(...o.map(e=>e.scopeEvidenceCompleteness)),authorizedAsObserved:Xh(...o.map(e=>e.authorizedAsObserved)),currentAuthorization:Xh(...o.map(e=>e.currentAuthorization))}}(s,t,u),p=s.filter(e=>xp.safeParse(e).success),h=a.filter(e=>Pp.safeParse(e).success);let f=l.checkpointIntegrity;if(a.length>0){const e=[];for(const n of a){if(!Pp.safeParse(n).success){e.push(sf("invalid",[Jh.SCHEMA_INVALID]));continue}const i=n,r=p.filter(e=>e.core.ledgerId===i.core.ledgerId&&e.core.ledgerEpochId===i.core.ledgerEpochId&&BigInt(e.core.sequence)<BigInt(i.core.treeSize));e.push(await u.verifyCheckpoint(i,r,t))}f=Xh(...e,function(e,t,n){const i=new Set,r=new Map;for(const t of e){const e=uf(t.core),n=r.get(e)??[];n.push(t),r.set(e,n)}for(const e of r.values()){e.sort((e,t)=>{const n=BigInt(e.core.treeSize),i=BigInt(t.core.treeSize);return n<i?-1:n>i?1:0});for(let t=1;t<e.length;t+=1){const n=e[t-1],r=e[t];r.core.treeSize===n.core.treeSize?i.add(Jh.CHECKPOINT_FORK_DETECTED):r.core.previousCheckpointDigest!==n.checkpointDigest&&i.add(Jh.CHECKPOINT_CHAIN_MISMATCH)}}for(const e of n){const t=(r.get(uf(e))??[]).map(e=>e.core.treeSize).sort(lf),n=[...e.checkpointTreeSizes].sort(lf);L(t)!==L(n)&&i.add(Jh.CHECKPOINT_MISSING)}for(const r of t){if("0"!==r.core.sequence||"ledger.epoch.started"!==r.core.event.eventType||"ledger"!==r.core.event.details.family)continue;const t=r.core.event.details;void 0!==t.previousEpochId&&void 0!==t.previousTerminalCheckpointDigest&&n.some(e=>e.ledgerId===r.core.ledgerId&&e.ledgerEpochId===t.previousEpochId)&&!e.some(e=>e.core.ledgerId===r.core.ledgerId&&e.core.ledgerEpochId===t.previousEpochId&&e.checkpointDigest===t.previousTerminalCheckpointDigest)&&i.add(Jh.CHECKPOINT_CHAIN_MISMATCH)}return sf(0===i.size?"valid":"invalid",i)}(h,p,o.selections),await async function(e,t,n,i){const r=new Set,o=new Ph(i),s=df(e,ef.inclusionProofs);for(const e of s){if(!jp.safeParse(e).success){r.add(Jh.SCHEMA_INVALID);continue}const i=e,s=n.find(e=>e.checkpointDigest===i.checkpointDigest&&e.core.ledgerId===i.ledgerId&&e.core.ledgerEpochId===i.ledgerEpochId),a=t.find(e=>e.entryDigest===i.entryDigest&&e.core.sequence===i.sequence&&e.core.ledgerId===i.ledgerId&&e.core.ledgerEpochId===i.ledgerEpochId),c=Number(i.proof.leafIndex),d=Number(i.proof.treeSize);void 0!==s&&void 0!==a&&i.proof.treeSize===s.core.treeSize&&i.proof.leafIndex===i.sequence&&await o.verifyInclusion({leaf:i.entryDigest,leafIndex:c,treeSize:d,root:s.core.rootDigest,auditPath:i.proof.auditPath})||r.add(Jh.MERKLE_PROOF_INVALID)}const a=df(e,ef.consistencyProofs);for(const e of a){if(!Hp.safeParse(e).success){r.add(Jh.SCHEMA_INVALID);continue}const t=e,i=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!==i&&void 0!==s&&t.proof.oldTreeSize===i.core.treeSize&&t.proof.newTreeSize===s.core.treeSize&&await o.verifyConsistency({oldSize:Number(t.proof.oldTreeSize),newSize:Number(t.proof.newTreeSize),oldRoot:i.core.rootDigest,newRoot:s.core.rootDigest,auditPath:t.proof.auditPath})||r.add(Jh.MERKLE_PROOF_INVALID)}return sf(0===r.size?"valid":"invalid",r)}(i,p,h,n.hasher))}else o.selections.some(e=>e.checkpointTreeSizes.length>0)&&(f=sf("invalid",[Jh.CHECKPOINT_MISSING]));let g=l.anchorIntegrity;if(c.length>0){const e=[];for(const n of c){if(!$p.safeParse(n).success){e.push(sf("invalid",[Jh.SCHEMA_INVALID]));continue}const i=n,r=h.find(e=>e.checkpointDigest===i.core.checkpointDigest);e.push(void 0===r?sf("invalid",[Jh.OBSERVATION_SCOPE_MISMATCH]):await u.verifyObservation(r,i,t))}const n=c.filter(e=>$p.safeParse(e).success);g=Xh(...e,function(e){const t=new Set,n=new Map;for(const t of e){const e=`${uf(t.core)}\0${t.core.observerId}`,i=n.get(e)??[];i.push(t),n.set(e,i)}for(const e of n.values()){e.sort((e,t)=>e.core.observedAt-t.core.observedAt||lf(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(Jh.OBSERVATION_CHAIN_MISMATCH)}return sf(0===t.size?"valid":"invalid",t)}(n))}d.length>0&&(g=Xh(g,await async function(e,t,n,i){const r=new Set;let o=!1;for(const s of e){if(!Lp.safeParse(s).success){r.add(Jh.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&&of(t,e.issuedAt))??!1)||r.add(Jh.UNTRUSTED_SUPPORTING_ANCHOR),void 0===a?r.add(Jh.SUPPORTING_ANCHOR_INVALID):void 0===i?(r.add(Jh.NOT_EVALUATED),o=!0):await i(a,e)||r.add(Jh.SUPPORTING_ANCHOR_INVALID)}return sf([...r].some(e=>e!==Jh.NOT_EVALUATED)?"invalid":o?"indeterminate":"valid",r)}(d,h,t,n.verifySupportingAnchor)));const m=sf(0===r.size?"valid":"invalid",r);return{...l,cryptographicIntegrity:Xh(m,l.cryptographicIntegrity),checkpointIntegrity:f,anchorIntegrity:g,scopeEvidenceCompleteness:pf(o?.selections??[],p,i.components.filter(e=>"included"!==e.disposition))}}class ff{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 Ah(bh.INVALID_CONFIGURATION,"Buffered audit delivery requires a durable outbox provider");if(void 0!==e.capabilities){if(e.capabilities.delivery!==e.delivery)throw new Ah(bh.INVALID_CONFIGURATION,"Advertised audit delivery does not match the trail delivery mode");if(dh(e.capabilities),e.capabilities.sourceHighWater&&"durable"!==e.sourceState.capabilities.durability)throw new Ah(bh.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(),i=t.encryptedEvidence??[],r="buffered"===this.configuration.delivery,{event:o,submission:s}=await this.withSourceConstruction(async()=>{const t=await this.buildAndLinkEvent(e,n);this.assertEvidenceIsReferenced(t,i);const o=Object.freeze({ledgerId:this.configuration.ledgerId,...r||void 0===this.configuration.expectedLedgerEpochId?{}:{expectedLedgerEpochId:this.configuration.expectedLedgerEpochId},producerEvent:t,encryptedEvidence:Object.freeze([...i])});return r&&await this.configuration.outbox.enqueue(Object.freeze({eventId:t.eventId,submission:o,enqueuedAt:this.configuration.clock.now(),attempts:0})),{event:t,submission:o}});if(r)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 i=new Set;for await(const r of this.configuration.outbox.pending(e)){const e=r.submission.producerEvent.source.sourceId;if(!i.has(e))try{const n=await this.submitAndValidate(r.submission);try{await this.sourceState.markReceipted(e,r.submission.producerEvent.source.sourceSequence,n.entryDigest)}catch(e){this.configuration.onSourceStateFailure?.(e,r.submission.producerEvent)}await this.configuration.outbox.markDelivered(r.eventId),t+=1}catch(t){await this.configuration.outbox.markFailed(r.eventId,t),this.configuration.onDeliveryFailure?.(t,r.submission.producerEvent),i.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),i=this.buildEvent(e,t,n),r=await _h(this.configuration.hasher,i);return await this.sourceState.markEmitted(this.configuration.sourceId,t,n.sequence,r),i}buildEvent(e,t,n){return Xp({...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(yh(e).map(e=>[e.objectId,e])),i=new Set;for(const e of t){const t=n.get(e.ref.objectId);if(i.has(e.ref.objectId)||void 0===t||L(t)!==L(e.ref))throw new Ah(bh.EVIDENCE_FAILURE,"Encrypted evidence must exactly match one unique reference in the frozen event",{objectId:e.ref.objectId});i.add(e.ref.objectId)}}async submitAndValidate(e){const t=await this.configuration.recorder.submit(e),n=await _h(this.configuration.hasher,e.producerEvent);if(t.core.ledgerId!==e.ledgerId||t.eventDigest!==n||t.core.eventDigest!==n||L(t.core.event)!==L(e.producerEvent))throw new Ah(bh.JOURNAL_FAILURE,"Recorder response does not bind the submitted frozen producer event");return t}}function gf(e){return new ff(e)}class mf{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 Ah(bh.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 Ah(bh.MIRROR_VERIFICATION_FAILED,"Mirror rejected an entry that failed historical artifact verification",{reasonCodes:t.cryptographicIntegrity.reasonCodes});const n=await gh(this.options.hasher,"org.kya-os.audit.mirror-idempotency.v1",{ledgerId:e.core.ledgerId,entryDigest:e.entryDigest}),i=await this.options.journal.getByIdempotencyKey(e.core.ledgerId,n);if(null!==i)return i.entryDigest!==e.entryDigest&&this.continuityFailure(),i;const r=await this.options.journal.getHead(this.options.ledger),o=BigInt(e.core.sequence);if(null===r&&o>0n||null!==r&&o>BigInt(r.sequence)+1n)throw new Ah(bh.MIRROR_OUT_OF_ORDER,"Mirror entry arrived before its predecessor and may be retried",{sequence:e.core.sequence,observedHeadSequence:r?.sequence??null});(null===r?"0"===e.core.sequence&&null===e.core.previousEntryDigest:o===BigInt(r.sequence)+1n&&e.core.previousEntryDigest===r.entryDigest)||this.continuityFailure();const s=await this.options.journal.compareAndAppend({ledger:this.options.ledger,expectedHead:r,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 Ah(bh.MIRROR_CONTINUITY_FAILED,"Mirror entry does not exactly extend the observed recorder chain")}}function yf(e){if("object"!=typeof e||null===e||Object.isFrozen(e))return e;for(const t of Object.values(e))yf(t);return Object.freeze(e)}function vf(e,t){return null===e||null===t?e===t:e.entryDigest===t.entryDigest&&e.sequence===t.sequence}function If(e,t){return L(e)===L(t)}function wf(e,t,n){return void 0!==t?If(t,n):("public_did"===n.kind||"pairwise_did"===n.kind)&&n.did===e}class _f{config;maxAppendConflicts;initialization;constructor(e){if(this.config=e,void 0===e.previousEpochId!=(void 0===e.previousTerminalCheckpointDigest))throw new Ah(bh.INVALID_CONFIGURATION,"Previous epoch ID and terminal checkpoint digest must be supplied together");if(void 0!==e.previousEpochId&&void 0===e.epochTransitionGuard)throw new Ah(bh.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=Xp(e.producerEvent);if(this.validateEventAuthority(n,t),void 0!==this.config.authorizer&&!await this.config.authorizer.authorize({submission:e,context:t}))throw new Ah(bh.UNAUTHORIZED_SUBMISSION,"Audit producer is not authorized for this ledger");const i=await this.identifyEvent(n,t),r=await this.config.journal.getByIdempotencyKey(this.config.ledgerId,i.idempotencyKey);if(null!==r)return this.resolveDuplicate(r,i.eventDigest);if(void 0!==e.expectedLedgerEpochId&&e.expectedLedgerEpochId!==this.config.ledgerEpochId)throw new Ah(bh.EPOCH_MISMATCH,"Wrong audit ledger epoch");await this.ensureInitialized(),await this.persistSubmittedEvidence(e.encryptedEvidence,n);try{return await this.appendEvent(n,t,!1,i)}catch(t){throw await this.disposeUncommittedEvidence(e.encryptedEvidence,i),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 Ah(bh.UNAUTHORIZED_SUBMISSION,"Authenticated producer and tenant authority are required");if(e.ledgerId!==this.config.ledgerId)throw new Ah(bh.LEDGER_MISMATCH,"Wrong audit ledger")}validateEventAuthority(e,t){if(!wf(t.producerAuthority,t.producerRef,e.source.producer))throw new Ah(bh.UNAUTHORIZED_SUBMISSION,"Event producer does not match the authenticated producer authority");if(!If(e.tenantRef,this.config.tenantRef)||!wf(t.tenantAuthority,t.tenantRef,e.tenantRef))throw new Ah(bh.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 Ah(bh.EVIDENCE_FAILURE,"Encrypted evidence was submitted but no evidence provider is configured");try{const n=new Map(yh(t).map(e=>[e.objectId,e])),i=new Set;for(const t of e){const e=n.get(t.ref.objectId);if(i.has(t.ref.objectId)||void 0===e||L(e)!==L(t.ref))throw new Ah(bh.EVIDENCE_FAILURE,"Submitted evidence does not exactly match a unique frozen event reference",{objectId:t.ref.objectId});i.add(t.ref.objectId),await this.config.evidence.putIfAbsent(t)}}catch(e){if(e instanceof Ah&&e.code===bh.EVIDENCE_FAILURE)throw e;throw new Ah(bh.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 Ah(bh.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 Ah(bh.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 i=eh(e),r=i.core.event.details;if("0"!==i.core.sequence||null!==i.core.previousEntryDigest||i.core.ledgerId!==this.config.ledgerId||i.core.ledgerEpochId!==this.config.ledgerEpochId||(t=i.core.recorder,n=this.config.signer.ref,t.did!==n.did||t.kid!==n.kid||t.alg!==n.alg)||"ledger.epoch.started"!==i.core.event.eventType||i.core.event.binding!==this.config.binding||i.core.event.source.sourceId!==this.config.sourceId||"public_did"!==i.core.event.source.producer.kind||i.core.event.source.producer.did!==this.config.signer.ref.did||!If(i.core.event.tenantRef,this.config.tenantRef)||"ledger"!==r.family||"epoch_started"!==r.phase||r.previousEpochId!==this.config.previousEpochId||r.previousTerminalCheckpointDigest!==this.config.previousTerminalCheckpointDigest)throw new Error("Genesis does not match recorder epoch configuration");return i}catch(e){throw new Ah(bh.JOURNAL_FAILURE,"Existing ledger genesis does not match the authoritative recorder configuration",void 0,{cause:e})}var t,n}genesisEvent(){return Xp({schema:pp,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,i){const{eventDigest:r,idempotencyKey:o}=i??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,r);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 i=await this.buildCandidate(e,r,t,n);let s;try{s=await this.config.journal.compareAndAppend({ledger:a,expectedHead:t,entry:i,idempotencyKey:o})}catch(e){throw new Ah(bh.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,r):s.entry;if("idempotency_conflict"===s.kind)return this.resolveDuplicate(s.existing,r);if(vf(t,s.actualHead))throw new Ah(bh.JOURNAL_FAILURE,"Audit journal reported a head conflict without advancing its head")}throw new Ah(bh.APPEND_CONFLICT_EXHAUSTED,"Audit append conflict retry budget exhausted")}async identifyEvent(e,t){return{eventDigest:await _h(this.config.hasher,e),idempotencyKey:await gh(this.config.hasher,vh.idempotency,{ledgerId:this.config.ledgerId,producerAuthority:t.producerAuthority,sourceId:e.source.sourceId,eventId:e.eventId})}}resolveDuplicate(e,t){if(e.eventDigest!==t)throw new Ah(bh.EVENT_ID_CONFLICT,"Authenticated producer event identity was reused with different content",{eventId:e.core.event.eventId});return e}async buildCandidate(e,t,n,i){const r=null===n?"0":(BigInt(n.sequence)+1n).toString();if(i!==("0"===r))throw new Ah(bh.JOURNAL_FAILURE,i?"Genesis must be the first epoch entry":"Producer event cannot replace genesis");const o=this.config.clock.now(),s=await Sh(this.config.hasher,e),a=Qp({schema:hp,ledgerId:this.config.ledgerId,ledgerEpochId:this.config.ledgerEpochId,sequence:r,previousEntryDigest:n?.entryDigest??null,recordedAt:o,recorder:this.config.signer.ref,eventDigest:t,event:e,evidenceManifestDigest:s,integritySuite:gp}),c=await Eh(this.config.hasher,a),d=wh(a,c);return yf({core:a,eventDigest:t,entryDigest:c,recorderReceipt:{core:d,jws:await this.config.signer.sign(M(d))}})}ledgerRef(){return{ledgerId:this.config.ledgerId,ledgerEpochId:this.config.ledgerEpochId}}}function Ef(e){return`${e.ledgerId}\0${e.ledgerEpochId}`}function Sf(e,t){return`${e}\0${t}`}class bf{capabilities={durability:"ephemeral",atomicAppend:!0,orderedRead:!0};entriesByLedger=new Map;entriesByIdempotency=new Map;heads=new Map;async getHead(e){return this.heads.get(Ef(e))??null}async getByIdempotencyKey(e,t){return this.entriesByIdempotency.get(Sf(e,t))??null}async compareAndAppend(e){const t=Sf(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 i=Ef(e.ledger),r=this.heads.get(i)??null;if(s=r,!(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:r};var o,s;const a=this.entriesByLedger.get(i)??[];return a.push(e.entry),this.entriesByLedger.set(i,a),this.entriesByIdempotency.set(t,e.entry),this.heads.set(i,{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 i=0;for(const r of t)if(!(null!==n&&BigInt(r.core.sequence)<=n)){if(void 0!==e.limit&&i>=e.limit)return;i+=1,yield r}}async snapshot(e){return[...this.entriesByLedger.get(Ef(e))??[]]}}class Af{recorder;context;constructor(e,t){this.recorder=e,this.context=t}async submit(e){return this.recorder.submitAuthenticated(e,await this.context())}}function Df(e,t){return new Af(new _f(e),t)}function kf(e){return`${e.ledgerId}\0${e.ledgerEpochId}`}class Tf{config;capability="independent-observer";observations=new Map;publicationTails=new Map;constructor(e){this.config=e}async publish(e){const t=kf({ledgerId:e.core.ledgerId,ledgerEpochId:e.core.ledgerEpochId}),n=this.publicationTails.get(t)??Promise.resolve();let i;const r=new Promise(e=>{i=e}),o=n.then(()=>r);this.publicationTails.set(t,o),await n;try{return await this.publishSerialized(e)}finally{i(),this.publicationTails.get(t)===o&&this.publicationTails.delete(t)}}async publishSerialized(e){if(!await this.config.verifyCheckpoint(e))throw new Ah(bh.CHECKPOINT_INVALID,"Observer rejected an invalid checkpoint");const t={ledgerId:e.core.ledgerId,ledgerEpochId:e.core.ledgerEpochId},n=this.observations.get(kf(t));if(void 0!==n){const t=BigInt(n.checkpoint.core.treeSize),i=BigInt(e.core.treeSize);if(i<t)throw new Ah(bh.CHECKPOINT_ROLLBACK,"Observed checkpoint tree size moved backwards");if(i===t){if(e.core.rootDigest!==n.checkpoint.core.rootDigest||e.checkpointDigest!==n.checkpoint.checkpointDigest)throw new Ah(bh.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 Ah(bh.CHECKPOINT_CONFLICT,"Checkpoint does not consistently extend the previously observed tree")}const i={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},r=await gh(this.config.hasher,vh.observation,i),o=Object.freeze({core:Object.freeze(i),observationDigest:r,jws:await this.config.signer.sign(M(i))});return this.observations.set(kf(t),{checkpoint:e,receipt:o}),o}async latest(e){return this.observations.get(kf(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 Cf{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 Nf{capabilities={durability:"ephemeral",fifoPerSource:!0};items=new Map;async enqueue(e){const t=this.items.get(e.eventId);var n,i;if(void 0===t)this.items.set(e.eventId,e);else if(n=t.submission,i=e.submission,n.ledgerId!==i.ledgerId||n.expectedLedgerEpochId!==i.expectedLedgerEpochId||L(n.producerEvent)!==L(i.producerEvent)||n.encryptedEvidence.length!==i.encryptedEvidence.length||!n.encryptedEvidence.every((e,t)=>{const n=i.encryptedEvidence[t];if(void 0===n||L(e.ref)!==L(n.ref)||e.ciphertext.byteLength!==n.ciphertext.byteLength)return!1;let r=0;for(let t=0;t<e.ciphertext.byteLength;t+=1)r|=e.ciphertext[t]^n.ciphertext[t];return 0===r}))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 Of{capabilities={durability:"ephemeral",atomicClaim:!0};states=new Map;async claimEvent(e,t){const n=this.state(e),i=n.claims.get(t);if(void 0!==i)return{sequence:i.sequence.toString(),...void 0===i.previousSourceEventDigest?{}:{previousSourceEventDigest:i.previousSourceEventDigest}};n.next+=1n;const r=n.eventDigests.get(n.next-1n),o={sequence:n.next,...void 0===r?{}:{previousSourceEventDigest:r}};return n.claims.set(t,o),{sequence:o.sequence.toString(),...void 0===o.previousSourceEventDigest?{}:{previousSourceEventDigest:o.previousSourceEventDigest}}}async markEmitted(e,t,n,i){const r=this.state(e),o=BigInt(n),s=r.claims.get(t);if(s?.sequence!==o)throw new RangeError("Unknown source event claim");const a=r.eventDigests.get(o);if(void 0!==a&&a!==i)throw new Error(`Source event identity collision: ${t}`);r.eventDigests.set(o,i)}async markReceipted(e,t){const n=BigInt(t),i=this.state(e);if(n<1n||n>i.next)throw new RangeError("Unknown source sequence");if(!(n<=i.receiptedWatermark)){for(i.receipted.add(n);i.receipted.delete(i.receiptedWatermark+1n);)i.receiptedWatermark+=1n;for(const[e,t]of i.claims)t.sequence<i.receiptedWatermark&&i.claims.delete(e);for(const e of i.eventDigests.keys())e<i.receiptedWatermark&&i.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 zf extends ai{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 Rf(e,t=256){return e.slice(0,t)}class Pf{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:Rf(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:Rf(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:Rf(t.delegationRef),...void 0===t.parentRef?{}:{parentRef:Rf(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:Rf(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 xf{}class $f extends xf{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 Lf{}class Mf extends Lf{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 Uf(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 jf(e,t){const n=Uf(e),i=Uf(t),r=t.credentialSubject.delegation,o=e=>`${e.matcher}\0${e.resource}`,s=new Set((e.credentialSubject.delegation.constraints.crisp?.scopes??[]).map(o)),a=(r.constraints.crisp?.scopes??[]).filter(e=>!s.has(o(e)));if(a.length>0)return{valid:!1,reason:`Delegation ${r.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===i.length)return{valid:!1,reason:`Delegation ${r.id} omits scopes required to prove attenuation from parent ${e.credentialSubject.delegation.id}`};const c=new Set(n),d=i.filter(e=>!c.has(e));return d.length>0?{valid:!1,reason:`Delegation ${r.id} widens scopes beyond parent ${e.credentialSubject.delegation.id}: ${d.join(", ")}`}:{valid:!0}}const Hf=["delete","drop","destroy","remove","terminate","transfer","payment","admin","execute","modify","write","rotate","revoke"],Kf=["read","get","list","describe","search","query"];class Vf{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=Ff(e.toolName),i=function(e){const t=Ff(e);return t.includes("prod")||t.includes("production")}(e.namespace);let r;return r=n.some(e=>Hf.includes(e))?{reversibility:"irreversible",blastRadius:i?"environment":"resource",severity:i?"catastrophic":"high"}:n.some(e=>Kf.includes(e))?{reversibility:"reversible",blastRadius:"record",severity:"low"}:{reversibility:"unknown",blastRadius:"unknown",severity:"unknown"},{...r,...Bf(t)}}}function Ff(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 Bf(e){if(!e)return{};const t={};for(const[n,i]of Object.entries(e))void 0!==i&&(t[n]=i);return t}class Zf{cfg;constructor(e={}){this.cfg=e}async evaluate(e){const{severity:t,reversibility:n,scopeMatched:i,humanApprovals:r}=e.context;if(!i)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 r.length>=e?{decision:"allow"}:{decision:"step_up",quorum:{n:e,approvers:this.cfg.stepUpApprovers??[]},reason:"destructive_action_requires_approval"}}return{decision:"allow"}}}async function Jf(e,t,n,i){if(n.n<=0)return{satisfied:!1,reason:"invalid_quorum:n<=0"};const r=new Set;for(const o of e)"approve"===o.decision&&o.requestHash===t&&(n.approvers.length>0&&!n.approvers.includes(o.approverDid)||await i(o)&&r.add(o.approverDid));return r.size>=n.n?{satisfied:!0}:{satisfied:!1,reason:`quorum_not_met:${r.size}/${n.n}`}}function qf(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 Wf(e,t=256){const n="string"==typeof e?e:String(e);let i="";for(const e of n){const t=e.codePointAt(0)??0;i+=t<=31||t>=127&&t<=159?"�":e}return i.length>t?`${i.slice(0,t)}…`:i}const Gf=256,Yf=256,Xf=/\([^()]*[+*?{][^()]*\)\s*[+*{]/;function Qf(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>Gf||n.length>Yf)return!1;if(Xf.test(e))return!1;try{return new RegExp(`^(?:${e})$`).test(n)}catch{return!1}default:return!1}}function eg(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(Qf(n.resource,n.matcher,e))return{satisfied:!0,usedNonExactMatcher:"exact"!==n.matcher};return{satisfied:!1,usedNonExactMatcher:!1}}const tg=256;function ng(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,tg);const i=t.credentialSubject;if("object"!=typeof i||null===i)return"unknown";const r=i.delegation;if("object"!=typeof r||null===r)return"unknown";const o=r.id;return"string"==typeof o&&o.length>0?o.slice(0,tg):"unknown"}catch{return"unknown"}}const ig=["handshake","identity","reputation"];function rg(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(dh(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 Zn,r=new Gn(t,{...e.session,serverDid:n.did,nonceCache:i}),o=new qt(n,t),s=e.delegation,c=e.auditLog??new di,d=void 0!==e.audit&&!1!==e.audit?new Pf(e.audit,{includeToolNames:e.audit.includeToolNames??!1}):void 0,l=e.emitLegacyProofKey??!0,f=e.grantStore??new $f;e.grantStore||Ot.warn("[kya-os] Using MemoryGrantStore — grants are lost on restart and not shared across instances. Inject a Redis / Durable Object / DB-backed GrantStore via config.grantStore for production / multi-instance use.");const g=s?.holderBinding??"off",m={identity:n,config:e,cryptoProvider:t,sessionManager:r,proofGenerator:o,auditLog:c,audit:d,grantStore:f,delegationConfig:s,holderBindingMode:g,holderBindingVerifier:"off"===g?void 0:new Rn({cryptoProvider:t,clockProvider:new ii,nonceCacheProvider:i,fetchProvider:s?.fetchProvider??("function"==typeof globalThis.fetch?new ri:new oi)}),emitLegacyProofKey:l},y=function(e){const{identity:t,config:n,cryptoProvider:i,sessionManager:r,proofGenerator:o,auditLog:s,audit:c,emitLegacyProofKey:d}=e,u=new WeakSet,l="org.kya-os/audit",h=async(e,t,n)=>{try{return await t(),!0}catch(t){return Ot.error(`[kya-os] ${e}`,{...void 0===n?{}:{tool:n},error:t instanceof Error?t.message:String(t)}),!1}},f=(e,t,n)=>{const i={...e._meta??{}};return n&&(delete i[Bt],delete i[Zt]),i[l]={..."object"==typeof i[l]&&null!==i[l]?i[l]:{},status:"degraded",reason:t},e._meta=i,e.isError=!0,e},g=e=>({content:[{type:"text",text:JSON.stringify({success:!1,error:{code:"audit_delivery_failed",message:e}})}],isError:!0,_meta:{[l]:{status:"degraded",reason:e}}}),m=e=>void 0===e?void 0:{...void 0===e.actor?{}:{actor:e.actor},...void 0===e.responsibleParty?{}:{responsibleParty:e.responsibleParty},...void 0===e.authorization?{}:{authorization:e.authorization},...void 0===e.correlationId?{}:{correlationId:e.correlationId},...void 0===e.causationId?{}:{causationId:e.causationId}},y=(e,t)=>({...e,[Bt]:t,...d?{[Zt]:t}:{}});let v;async function I(){if(v&&await r.getSession(v))return r.getStats().activeSessions<=1?v:void Ot.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=p(await i.randomBytes(16)),o=Math.floor(Date.now()/1e3),s=await r.validateHandshake({nonce:e,audience:t.did,timestamp:o});return s.success&&s.session?(v=s.session.sessionId,v):void 0}return{handleHandshake:async function(e){if(!Xn(e))return await h("Failed to record rejected session audit event",()=>c?.session("rejected",{succeeded:!1,reasonCode:a.handshake_failed})),{content:[{type:"text",text:JSON.stringify({success:!1,error:{code:a.handshake_failed,message:"Invalid handshake format: requires nonce (string), audience (string), and timestamp (positive integer)"}})}],isError:!0};const n=await r.validateHandshake(e),i=n.success?"established":n.error?.code===a.nonce_replay?"replay_rejected":"rejected",o=await h(`Failed to record ${i} session audit event`,()=>c?.session(i,{succeeded:n.success,...void 0===n.error?{}:{reasonCode:n.error.code}}));return n.success&&!o?{content:g("Required session audit delivery failed after handshake validation").content,isError:!0}:(n.success&&n.session&&(v=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:I,wrapWithProof:function(e,n){return async(i,a,d)=>{if(!await h("Required tool intent audit delivery failed",()=>c?.tool("started",{toolName:e,outcome:"unknown",context:m(d)}),e))return g("Required intent audit delivery failed before tool execution");let p;try{p=await n(i,a,d)}catch(t){throw await h("Failed to record thrown tool outcome; preserving original handler error",()=>c?.tool("failed",{toolName:e,outcome:"failed",reasonCode:"HANDLER_THROWN",context:m(d)}),e),t}if(p.isError)return(e=>{if(u.has(e))return!0;const t=e._meta,n=t?.[l];return"object"==typeof n&&null!==n&&!0===n.terminal})(p)||await h("Failed to record error tool outcome",()=>c?.tool("failed",{toolName:e,outcome:"failed",reasonCode:"HANDLER_ERROR_RESULT",context:m(d)}),e)||f(p,"Required terminal audit delivery failed for an error response",!1),p;const v=a??await I();if(!v)return await h("Failed to record unavailable proof session",()=>c?.proof("rejected",{outcome:"failed",verificationCode:"PROOF_SESSION_UNAVAILABLE",context:m(d)}),e)&&await h("Failed to record completed tool outcome",()=>c?.tool("completed",{toolName:e,outcome:"succeeded",context:m(d)}),e)?p:f(p,"Required terminal audit delivery failed after tool completion",!0);const w=await r.getSession(v);if(!w)return await h("Failed to record missing proof session",()=>c?.proof("rejected",{outcome:"failed",verificationCode:"PROOF_SESSION_NOT_FOUND",context:m(d)}),e)&&await h("Failed to record completed tool outcome",()=>c?.tool("completed",{toolName:e,outcome:"succeeded",context:m(d)}),e)?p:f(p,"Required terminal audit delivery failed after tool completion",!0);try{const n={method:e,params:i},r={data:p.content},a=await o.generateProof(n,r,w,{scopeId:d?.scopeId});if(p._meta=y({},a),!await h("Required generated-proof audit delivery failed",()=>c?.proof("generated",{outcome:"succeeded",context:m(d)}),e)||!await h("Required completed-tool audit delivery failed",()=>c?.tool("completed",{toolName:e,outcome:"succeeded",context:m(d)}),e))return f(p,"Required terminal audit delivery failed after tool completion",!0);try{await s.logAuditRecord({identity:{did:t.did,kid:t.kid},session:{sessionId:w.sessionId,audience:w.audience},requestHash:a.meta.requestHash,responseHash:a.meta.responseHash,verified:"yes",scopeId:a.meta.scopeId})}catch(t){Ot.error("[kya-os] Audit log failed",{tool:e,error:t instanceof Error?t.message:String(t)})}}catch(t){Ot.error("[kya-os] Proof generation failed",{tool:e,error:t instanceof Error?t.message:String(t)}),p._meta={proofError:"Proof generation failed — response is unproven"},await h("Failed to record proof-generation rejection",()=>c?.proof("rejected",{outcome:"failed",verificationCode:"PROOF_GENERATION_FAILED",context:m(d)}),e)||f(p,"Required proof-failure audit delivery failed after tool completion",!0)}return p}},attachOutcomeProof:async(e,t,n,i,s,a="denied",d,p)=>{const g="denied"===a?"denied":"step_up_required",m="needs_authorization"===a?"NEEDS_AUTHORIZATION":"step_up_required"===a?"STEP_UP_REQUIRED":"AUTHORIZATION_DENIED",v=await h("Failed to record authorization outcome",()=>c?.authorization(g,{outcome:"denied"===a?"denied":"challenged",reasonCode:m}),t)&&await h("Failed to record terminal authorization tool outcome",()=>c?.tool("denied"===a?"denied":"challenged",{toolName:t,outcome:"denied"===a?"denied":"challenged",reasonCode:m}),t);u.add(e),e._meta={...e._meta??{},[l]:{terminal:!0,outcome:a,...v?{}:{status:"degraded",reason:"Required terminal audit delivery failed for authorization outcome"}}};try{const u=i??await I();if(!u)return e;const l=await r.getSession(u);if(!l)return e;let g;if(void 0!==d)g=d;else{g={};for(const[e,t]of Object.entries(n))"_kyaos_delegation"!==e&&(g[e]=t)}const m={method:t,params:g},w=void 0!==p?{data:p}:void 0,_=await o.generateProof(m,w,l,{outcome:a,reason:Wf(s)});e._meta=y(e._meta??{},_),v&&(await h("Failed to record generated outcome proof",()=>c?.proof("generated",{outcome:"succeeded"}),t)||f(e,"Required proof audit delivery failed for authorization outcome",!1))}catch(e){Ot.error("[kya-os] Outcome proof generation failed",{tool:t,error:e instanceof Error?e.message:String(e)}),v&&await h("Failed to record outcome-proof rejection",()=>c?.proof("rejected",{outcome:"failed",verificationCode:"OUTCOME_PROOF_GENERATION_FAILED"}),t)}return e}}}(m),I=function(e,t){const{identity:n,config:i,sessionManager:r}=e,{handleHandshake:o}=t;return{handleKyaOs:async function(e){const t="string"==typeof e.action?e.action:void 0;switch(t){case"handshake":return o(e);case"identity":return async function(){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:r.getStats().config.timestampSkewSeconds,auditAssurance:e})}]}}();case"reputation":return{content:[{type:"text",text:JSON.stringify({success:!1,error:{code:a.runtime_error,message:'action: "reputation" is not yet implemented.'}})}],isError:!0};default:return{content:[{type:"text",text:JSON.stringify({success:!1,error:{code:a.invalid_request,message:`Unknown _kyaos action: "${t??"(missing)"}". Valid actions: ${ig.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:[...ig],description:"Protocol operation to perform"},nonce:{type:"string",description:"Client-generated unique nonce"},audience:{type:"string",description:"Intended audience (server DID or URL)"},timestamp:{type:"number",description:"Unix epoch seconds"},agentDid:{type:"string",description:"Client agent DID (optional)"}},required:["action"]}}}}(m,{handleHandshake:y.handleHandshake}),{resolveExistingGrant:w,bindGrantOnSuccess:_}=function(e){const{identity:t,cryptoProvider:n,grantStore:i,holderBindingMode:r,holderBindingVerifier:o}=e;async function s(e,t,i){const r=`${e}|${t??""}|${[...i].sort().join(",")}`;return`grant_${(await n.hash((new TextEncoder).encode(r))).replace(/^sha256:/,"")}`}return{resolveExistingGrant:async function(e,n,r,s){const a=await async function(e,n,r,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&&nn(u)&&"bound"===(await rn({proof:d,subjectDid:u,request:Qt(e,n),expectedAudience:t.did,proofVerifier:o})).status?(await i.getByAgent(u,[s])).find(e=>void 0===e.sessionId||e.sessionId===r):void 0}(e,n,r,s);if(a)return a;if(r){const[e]=await i.getBySession(r,[s]);if(e)return e}},bindGrantOnSuccess:async function(e,t,n,o,a){try{const c=e.credentialSubject?.id;if(!c)return;if("off"===r&&void 0===o)return void Ot.debug(`[kya-os] Skipping an unresolvable session-less grant for scope "${a}" (holderBinding 'off', no sessionId).`);let d;try{d=Uf(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),h={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 i.bind(h)}catch(e){Ot.error("[kya-os] Grant bind failed",{scope:a,error:e instanceof Error?e.message:String(e)})}}}}(m),{wrapWithDelegation:E}=function(e,t){const{identity:n,holderBindingMode:i,holderBindingVerifier:r,audit:o,cryptoProvider:s}=e,{attachOutcomeProof:c,resolveExistingGrant:d,bindGrantOnSuccess:l}=t,{validateDelegationChain:p,buildDelegationErrorResponse:f,buildNeedsAuthorizationChallenge:g}=function(e){const{identity:t,cryptoProvider:n,delegationConfig:i}=e,r=Lt(),o=i?.fetchProvider??("function"==typeof globalThis.fetch?new ri:void 0),s=o?hn(o):void 0,a=En(i?.didResolvers,o),c=new Ve({didResolver:{async resolve(e){const t=i?.didResolver;if(t){const n=await t.resolve(e);if(n)return n}const n=It(e),o=n?a[n]:void 0;if(o)try{const t=await o.resolve(e);if(t)return t}catch{return null}return e.startsWith("did:key:")?r.resolve(e):e.startsWith("did:web:")?s?.resolve(e)??null:null}},signatureVerifier:async(e,t)=>{const i=e.proof;if(!i)return{valid:!1,reason:"Missing proof"};const r=i.proofValue;if(!r)return{valid:!1,reason:"Missing proofValue in proof"};const o=e,s={};for(const[e,t]of Object.entries(o))"proof"!==e&&(s[e]=t);const a=U(s),c=(new TextEncoder).encode(a),d=u(r),l=t;if(!l.x)return{valid:!1,reason:"No x field in publicKeyJwk"};const p=h(u(l.x)),f=await n.verify(c,d,p);return{valid:f,reason:f?void 0:"Signature verification failed"}},statusListResolver:i?.statusListResolver});return{validateDelegationChain:(e,n)=>async function(e,t,n){const i=e?.credentialSubject?.delegation;if(!i||"object"!=typeof i||!i.constraints||"object"!=typeof i.constraints)return{valid:!1,reason:"Malformed delegation credential: missing credentialSubject.delegation or its constraints"};const r=v(e);let o=[e];if(r.parentId){if(!t.resolveDelegationChain)return{valid:!1,reason:`Delegation ${r.id} references parent ${r.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 ${r.id} references parent ${r.parentId} but the resolved chain is empty`};const i=n.findIndex(e=>e.credentialSubject.delegation.id===r.id);if(-1!==i&&i!==n.length-1)return{valid:!1,reason:`Resolved delegation chain for ${r.id} must end with the leaf credential`};o=-1===i?[...n,e]:n}const s=new Set;let a,c;for(const e of o){const i=v(e);if(s.has(i.id))return{valid:!1,reason:`Delegation chain contains a circular reference at ${i.id}`};if(s.add(i.id),e.credentialStatus&&!t.statusListConfigured)return{valid:!1,reason:`Delegation ${i.id} has credentialStatus but no statusListResolver is configured`};const r=await t.verifier.verifyDelegationCredential(e,{...n?.skipSignature?{skipSignature:!0}:{}});if(!r.valid)return{valid:!1,reason:`Delegation ${i.id} invalid: ${r.reason}`};if(!nt(i,t.serverDid))return{valid:!1,reason:`Delegation ${i.id} audience does not include server DID ${t.serverDid}`};if(i.parentId&&!i.constraints.audience)return{valid:!1,reason:`Delegation ${i.id} is a re-delegation (parentId: ${i.parentId}) but has no audience constraint. Re-delegations MUST include an audience constraint (KYA-OS §11.6)`};if(!a||!c){if(i.parentId)return{valid:!1,reason:`Resolved delegation chain is incomplete: root delegation ${i.id} still references parent ${i.parentId}`};a=i,c=e;continue}if(i.parentId!==a.id)return{valid:!1,reason:`Delegation ${i.id} references parent ${i.parentId} but expected ${a.id}`};if(i.issuerDid!==a.subjectDid)return{valid:!1,reason:`Delegation ${i.id} issued by ${i.issuerDid} but parent subject is ${a.subjectDid}`};const o=jf(c,e);if(!o.valid)return o;a=i,c=e}const d=v(o[o.length-1]);if(d.id!==r.id)return{valid:!1,reason:`Resolved delegation chain ended at ${d.id} instead of leaf ${r.id}`};if(t.revocationChecker){const e=await t.revocationChecker.isRevoked(r.id);if(e.revoked)return{valid:!1,reason:e.revokedAncestor?`Delegation ${r.id} is revoked via ancestor ${e.revokedAncestor}`:`Delegation ${r.id} is revoked${e.reason?`: ${e.reason}`:""}`}}return{valid:!0}}(e,{serverDid:t.did,verifier:c,resolveDelegationChain:i?.resolveDelegationChain,statusListConfigured:!!i?.statusListResolver,revocationChecker:i?.revocationChecker},n),buildDelegationErrorResponse:(e,t)=>({content:[{type:"text",text:JSON.stringify({error:e,reason:Wf(t)})}],isError:!0}),buildNeedsAuthorizationChallenge:async function(e,t){const i=await n.randomBytes(16),r=Array.from(i).map(e=>e.toString(16).padStart(2,"0")).join(""),o=[r.slice(0,8),r.slice(8,12),r.slice(12,16),r.slice(16,20),r.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){Ot.error("[kya-os] formatChallenge threw; using the default challenge",{tool:e,error:t instanceof Error?t.message:String(t)}),d=c}return{challengeContent:d,message:a.message}}}}(e);return{wrapWithDelegation:function(e,t,u){return async(h,m)=>{const y=h._kyaos_delegation;if(null==y){const n=await d(e,h,m,t.scopeId);if(n){const i={};for(const[e,t]of Object.entries(h))Xt(e)||(i[e]=t);Ot.debug(`[kya-os] Grant resolved for "${e}" (scope "${t.scopeId}") — no re-paste required`);const r={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(o?.authorization("grant_used",{outcome:"succeeded",grantRef:n.id,context:r})),u(i,m,r)}const{challengeContent:i,message:r}=await g(e,t);return c({content:i},e,h,m,r,"needs_authorization",void 0,i)}let v,I=!1;if("string"==typeof y){const t=K(y);if(!t||!t.payload.vc)return c(f(a.delegation_invalid,"Invalid VC-JWT format"),e,h,m,"Invalid VC-JWT format");v=t.payload.vc,v.proof||(v={...v,proof:{type:"JwtProof2020",jwt:y}}),I=!0}else v=y;const w=await(async()=>{try{return await p(v,{skipSignature:I})}catch(t){return Ot.error("[kya-os] Unexpected error verifying delegation",{tool:e,error:t instanceof Error?t.message:String(t),stack:t instanceof Error?t.stack:void 0}),{valid:!1,reason:"Delegation credential could not be verified"}}})();if(!w.valid){const t=w.reason??"Unknown delegation validation error";try{await(o?.delegation("rejected",{delegationRef:ng(v),outcome:"failed",reasonCode:"DELEGATION_VERIFICATION_FAILED"}))}catch(t){Ot.error("[kya-os] Failed to record rejected delegation audit event",{tool:e,error:t instanceof Error?t.message:String(t)})}return Ot.warn(`[kya-os] Delegation verification failed for "${e}": ${Wf(t)}`),c(f(a.delegation_invalid,t),e,h,m,t)}if("off"!==i&&r){const t=v.credentialSubject?.id;if(t&&nn(t)){const o=h._kyaos_proof;if(void 0===o){const t="Holder-of-key proof (_kyaos_proof) is required for this delegation subject";if(Ot.warn(`[kya-os] Holder binding: "${e}" called without _kyaos_proof`),"enforce"===i)return c(f(a.holder_binding_failed,t),e,h,m,t)}else{let s=o;if("string"==typeof o)try{s=JSON.parse(o)}catch{s={}}const d=await rn({proof:s,subjectDid:t,request:Qt(e,h),expectedAudience:n.did,proofVerifier:r});if("bound"!==d.status){const t=d.reason??"Holder-of-key proof did not bind the delegation subject";if(Ot.warn(`[kya-os] Holder binding ${d.status} for "${e}": ${Wf(t)}`),"enforce"===i)return c(f(a.holder_binding_failed,t),e,h,m,t)}}}else t&&Ot.warn(`[kya-os] Holder binding: subject "${t}" is not did:key; deferring to cnf binding (phase 2)`)}const _=eg(t.scopeId,v);if(_.usedNonExactMatcher&&Ot.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 Ot.warn(`[kya-os] Delegation missing required scope "${t.scopeId}" for "${e}"`),c(f(a.insufficient_scope,n),e,h,m,n)}const E=I?(new TextEncoder).encode(y):M(v),S=await s.hash(E),b=v.id??v.credentialSubject.delegation.id,A={kind:"pairwise_did",did:v.credentialSubject.id},D=v.credentialSubject.delegation.controller,k={source:"delegation",decision:"allowed",scopeId:t.scopeId,delegationRef:b,delegationCredentialDigest:S,verificationCode:"DELEGATION_CHAIN_VALID"},T={scopeId:t.scopeId,actor:A,...D?.startsWith("did:")?{responsibleParty:{kind:"pairwise_did",did:D}}:{},authorization:k};await(o?.delegation("verified",{delegationRef:b,outcome:"succeeded",parentRef:v.credentialSubject.delegation.parentId,context:T})),await(o?.authorization("approved",{outcome:"succeeded",context:T}));const C={};for(const[e,t]of Object.entries(h))Xt(e)||(C[e]=t);return await l(v,y,I,m,t.scopeId),Ot.debug(`[kya-os] Delegation verified for "${e}", scope "${t.scopeId}"`),u(C,m,T)}}}}(m,{attachOutcomeProof:y.attachOutcomeProof,resolveExistingGrant:w,bindGrantOnSuccess:_}),{withPolicyGate:S}=function(e,t){const{proofGenerator:n,audit:i}=e,{attachOutcomeProof:r}=t,o=new Vf,s=new Zf;return{withPolicyGate:function(e,t,c={}){const d=c.engine??s,u=c.classifier??o,l=c.approvalsArgKey??"_kyaos_approvals",p=c.isValidApprovalSignature??(async()=>!1);return async(o,s,h)=>{const f={};for(const[e,t]of Object.entries(o))Xt(e)||e===l||(f[e]=t);const g=c.resolveNamespace?.(o)??e,m=u.classify({toolName:e,namespace:g}),y=function(e){if(!e||"object"!=typeof e)return{agentDid:"unknown",delegatedScopes:[]};try{const t=e,n=t.credentialSubject,i=n?.delegation?.subjectDid??n?.id??"unknown",r=n?.delegation?.controller;let o=[];try{o=Uf(t)}catch{o=[]}return{agentDid:i,...r?{responsibleParty:r}:{},delegatedScopes:o}}catch{return{agentDid:"unknown",delegatedScopes:[]}}}(o._kyaos_delegation),v=qf({principal:{agentDid:y.agentDid,...y.responsibleParty?{responsibleParty:y.responsibleParty}:{}},action:{toolName:e},resource:{namespace:g},delegatedScopes:y.delegatedScopes,scopeMatched:c.scopeMatched??!1,risk:m}),I=await d.evaluate(v),w=void 0===h?void 0:{...void 0===h.actor?{}:{actor:h.actor},...void 0===h.responsibleParty?{}:{responsibleParty:h.responsibleParty},...void 0===h.authorization?{}:{authorization:h.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(f,s,h);if("deny"===I.decision){const t={content:[{type:"text",text:JSON.stringify({error:a.policy_denied,reason:Wf(I.reason)})}],isError:!0};return r(t,e,o,s,I.reason,"denied",f)}const _=await n.hashRequest({method:e,params:f}),E=Array.isArray(o[l])?o[l]:[];if((await Jf(E,_,I.quorum,p)).satisfied)return await(i?.authorization("approved",{outcome:"succeeded",context:w})),t(f,s,h);const S=C({message:`Tool "${e}" requires ${I.quorum.n}-of-N approval before it may proceed (${Wf(I.reason)}).`,resumeToken:`step_up:${_}`,expiresAt:Math.floor(Date.now()/1e3)+300,requestHash:_,quorum:I.quorum}),b={content:[{type:"text",text:JSON.stringify(S)}],isError:!0};return r(b,e,o,s,I.reason,"step_up_required",f)}}}}(m,{attachOutcomeProof:y.attachOutcomeProof});return{identity:e.identity,sessionManager:r,proofGenerator:o,kyaOsTool:I.kyaOsTool,handshakeTool:I.handshakeTool,handleKyaOs:I.handleKyaOs,handleHandshake:y.handleHandshake,wrapWithProof:y.wrapWithProof,wrapWithDelegation:E,withPolicyGate:S}}async function og(e){const t=await e.generateKeyPair(),n=kt(t.publicKey);return{did:n,kid:`${n}#${Tt(n)}`,privateKey:t.privateKey,publicKey:t.publicKey}}async function sg(e,t){const n=rg({identity:t.identity??await og(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:hl(ig).describe("Protocol operation to perform"),nonce:hd().optional().describe("Client-generated unique nonce (handshake)"),audience:hd().optional().describe("Intended audience (handshake)"),timestamp:lu().optional().describe("Unix epoch seconds (handshake)"),agentDid:hd().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 i=["_kyaos","_kyaos_handshake",...t.excludeTools??[]],r=e.connect.bind(e);e.connect=e=>r(function(e,t,n=["_kyaos","_kyaos_handshake"]){const i=new Map,r={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 r=n.id,o=void 0!==r?i.get(r):void 0;if(o){i.delete(r);try{const e=n.result;if(e){const i=async()=>({...e}),r=t.wrapWithProof(o.toolName,i),s=await r(o.args);e.isError||void 0===s._meta||(n={...n,result:s})}}catch(e){Ot.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 r.start=async()=>{await o();const t=e.onmessage;e.onmessage=e=>{if("tools/call"===e.method&&void 0!==e.id){const t=e.params,r=t?.name;r&&!n.includes(r)&&i.set(e.id,{toolName:r,args:t?.arguments??{}})}t?.(e)}},r}(e,n,i))}return n}}};