@kya-os/mcp-i 1.9.0 → 1.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/227.js +1 -0
- package/dist/{263.js → 242.js} +1 -1
- package/dist/283.js +1 -0
- package/dist/317.js +1 -0
- package/dist/354.js +1 -0
- package/dist/361.js +1 -0
- package/dist/452.js +1 -0
- package/dist/533.js +1 -0
- package/dist/622.js +1 -0
- package/dist/65.js +1 -0
- package/dist/839.js +1 -0
- package/dist/843.js +1 -0
- package/dist/{644.js → 861.js} +1 -1
- package/dist/914.js +1 -0
- package/dist/95.js +1 -0
- package/dist/cli-adapter/index.js +1 -1
- package/dist/runtime/102.js +1 -0
- package/dist/runtime/adapter-express.js +3 -3
- package/dist/runtime/adapter-nextjs.js +5 -5
- package/dist/runtime/audit.d.ts +1 -1
- package/dist/runtime/debug.d.ts +1 -1
- package/dist/runtime/debug.js +3 -2
- package/dist/runtime/delegation-hooks.d.ts +1 -1
- package/dist/runtime/http.js +3 -3
- package/dist/runtime/identity.d.ts +4 -4
- package/dist/runtime/identity.js +4 -4
- package/dist/runtime/index.d.ts +6 -2
- package/dist/runtime/index.js +10 -2
- package/dist/runtime/mcpi-runtime.d.ts +9 -1
- package/dist/runtime/mcpi-runtime.js +20 -3
- package/dist/runtime/outbound-delegation.d.ts +5 -3
- package/dist/runtime/outbound-delegation.js +14 -8
- package/dist/runtime/outbound-identity-bridge.d.ts +40 -0
- package/dist/runtime/outbound-identity-bridge.js +114 -0
- package/dist/runtime/proof-batch-queue.d.ts +1 -1
- package/dist/runtime/request-context.d.ts +10 -0
- package/dist/runtime/request-context.js +4 -0
- package/dist/runtime/resume-token-store-kv.d.ts +44 -0
- package/dist/runtime/resume-token-store-kv.js +93 -0
- package/dist/runtime/resume-token-store.d.ts +30 -0
- package/dist/runtime/resume-token-store.js +46 -0
- package/dist/runtime/session.js +6 -0
- package/dist/runtime/stdio.js +3 -3
- package/dist/runtime/utils/tools.d.ts +1 -1
- package/dist/runtime/utils/tools.js +29 -7
- package/dist/runtime/well-known.d.ts +12 -1
- package/dist/runtime/well-known.js +13 -2
- package/package.json +7 -5
- package/dist/114.js +0 -1
- package/dist/139.js +0 -1
- package/dist/200.js +0 -1
- package/dist/202.js +0 -1
- package/dist/238.js +0 -1
- package/dist/294.js +0 -1
- package/dist/374.js +0 -1
- package/dist/529.js +0 -1
- package/dist/627.js +0 -1
- package/dist/669.js +0 -1
- package/dist/857.js +0 -1
- package/dist/997.js +0 -1
- package/dist/runtime/verifier-middleware.d.ts +0 -99
- package/dist/runtime/verifier-middleware.js +0 -416
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";exports.id=102,exports.ids=[102],exports.modules={53102:(e,t,n)=>{n.r(t),n.d(t,{ANON_NONCE_TTL_MS:()=>D,AUTH_NONCE_TTL_MS:()=>z,AuditLogProvider:()=>fn,BitstringManager:()=>V,CascadingRevocationManager:()=>Y,ClockProvider:()=>Bt,CryptoProvider:()=>Wt,DEFAULT_CLOCK_SKEW_SECONDS:()=>Ut,DEFAULT_SESSION_TTL_MINUTES:()=>S,DEFAULT_TIMESTAMP_SKEW_SECONDS:()=>k,DELEGATION_CREDENTIAL_CONTEXT:()=>g,DefaultPolicyEngine:()=>$n,DelegationCredentialIssuer:()=>M,DelegationCredentialVerifier:()=>K,DelegationGraphManager:()=>H,DidWebResolver:()=>Tt,ED25519_KEY_SIZE:()=>lt,ED25519_PKCS8_DER_HEADER:()=>dt,ED25519_SPKI_DER_HEADER_LENGTH:()=>ut,FetchProvider:()=>qt,HOLDER_BINDING_ERROR:()=>_t,IdentityProvider:()=>Xt,KYA_OS_ERROR_CODES:()=>a,MAX_CLOCK_SKEW_SECONDS:()=>Jt,MIN_CLOCK_SKEW_SECONDS:()=>Kt,MemoryAuditLogProvider:()=>hn,MemoryDelegationGraphStorage:()=>It,MemoryIdentityProvider:()=>tn,MemoryNonceCacheProvider:()=>en,MemoryResumeTokenStore:()=>Pt,MemoryStatusListStorage:()=>kt,MemoryStorageProvider:()=>Qt,NONCE_LENGTH_BYTES:()=>I,NodeCryptoProvider:()=>cn,NonceCacheProvider:()=>Gt,NoopAuditLogProvider:()=>mn,NoopFetchProvider:()=>ln,OUTBOUND_HEADER_NAMES:()=>st,PROOF_VERIFICATION_ERROR_CODES:()=>Zt,ProofGenerator:()=>ft,ProofVerificationError:()=>Mt,ProofVerifier:()=>Ht,RiskClassifier:()=>zn,RuntimeFetchProvider:()=>un,SENSITIVE_VERBS:()=>kn,SessionManager:()=>nn,StatusList2021Manager:()=>B,StorageProvider:()=>Yt,SystemClockProvider:()=>dn,assertHolderBinding:()=>St,base58Decode:()=>je,base58Encode:()=>Re,base64ToBytes:()=>h,base64urlDecodeToBytes:()=>u,base64urlEncodeFromBytes:()=>p,buildAuditRecord:()=>pn,buildChainString:()=>Ne,buildDelegationProofJWT:()=>Oe,buildDidWebDocument:()=>Nt,buildOutboundDelegationHeaders:()=>at,buildPolicyRequest:()=>An,bytesToBase64:()=>f,canonicalizeJSON:()=>P,compareDids:()=>Ke,completeVCJWT:()=>j,createCascadingRevocationManager:()=>G,createDefaultConsoleLogger:()=>Ge,createDelegationGraph:()=>F,createDelegationIssuer:()=>L,createDelegationVerifier:()=>J,createDidKeyResolver:()=>it,createDidWebResolver:()=>At,createHandshakeRequest:()=>rn,createKyaOsError:()=>c,createKyaOsMiddleware:()=>Nn,createNeedsApprovalError:()=>T,createNeedsAuthorizationError:()=>E,createProofResponse:()=>ht,createProofVerificationError:()=>Lt,createStatusListManager:()=>q,createUnsignedVCJWT:()=>R,didKeyFragment:()=>qe,didWebToUrl:()=>$t,extractAgentId:()=>He,extractAgentSlug:()=>Fe,extractCanonicalData:()=>mt,extractDelegationFromVC:()=>v,extractProofFromMeta:()=>Vt,extractPublicKeyFromDidKey:()=>nt,generateDidKeyFromBase64:()=>Be,generateDidKeyFromBytes:()=>We,generateIdentity:()=>Cl,generateRequestProof:()=>wt,getDidMethod:()=>Le,getServerDid:()=>Je,hasSensitiveScopes:()=>jt,isDelegationCredentialExpired:()=>w,isDelegationCredentialNotYetValid:()=>_,isDidWeb:()=>Dt,isEd25519DidKey:()=>tt,isHolderBindingApplicable:()=>bt,isIndexSet:()=>W,isKyaOsControlArg:()=>yt,isNeedsApprovalError:()=>A,isNeedsAuthorizationError:()=>$,isValidBase58:()=>Ze,isValidDid:()=>Me,logger:()=>Xe,matchScope:()=>wn,normalizeDid:()=>Ue,parseDidWeb:()=>Et,parseVCJWT:()=>Z,publicKeyToJwk:()=>rt,resolveDidKeySync:()=>ot,scopeSatisfies:()=>_n,toHolderBindingRequest:()=>vt,validateDelegationCredential:()=>b,validateDetachedProof:()=>O,validateHandshakeFormat:()=>on,validateMetaStructure:()=>Ft,verifyApprovalQuorum:()=>Tn,verifyDelegationAudience:()=>X,verifyOrHints:()=>Ct,withKyaOs:()=>Rl,wrapDelegationAsVC:()=>y});var r={};n.r(r),n.d(r,{base64:()=>ai,base64url:()=>ci,bigint:()=>vi,boolean:()=>bi,browserEmail:()=>Qr,cidrv4:()=>oi,cidrv6:()=>si,cuid:()=>Cr,cuid2:()=>Rr,date:()=>fi,datetime:()=>gi,domain:()=>ui,duration:()=>Ur,e164:()=>li,email:()=>Br,emoji:()=>ti,extendedDuration:()=>Kr,guid:()=>Jr,hex:()=>Di,hostname:()=>di,html5Email:()=>qr,idnEmail:()=>Xr,integer:()=>wi,ipv4:()=>ni,ipv6:()=>ri,ksuid:()=>Mr,lowercase:()=>Ii,mac:()=>ii,md5_base64:()=>Ai,md5_base64url:()=>xi,md5_hex:()=>Ti,nanoid:()=>Lr,null:()=>Si,number:()=>_i,rfc5322Email:()=>Yr,sha1_base64:()=>Ni,sha1_base64url:()=>Pi,sha1_hex:()=>Oi,sha256_base64:()=>Ri,sha256_base64url:()=>ji,sha256_hex:()=>Ci,sha384_base64:()=>Mi,sha384_base64url:()=>Li,sha384_hex:()=>Zi,sha512_base64:()=>Ki,sha512_base64url:()=>Ji,sha512_hex:()=>Ui,string:()=>yi,time:()=>mi,ulid:()=>jr,undefined:()=>ki,unicodeEmail:()=>Gr,uppercase:()=>zi,uuid:()=>Hr,uuid4:()=>Fr,uuid6:()=>Vr,uuid7:()=>Wr,xid:()=>Zr});var i={};n.r(i),n.d(i,{endsWith:()=>Va,gt:()=>$a,gte:()=>Ta,includes:()=>Ha,length:()=>La,lowercase:()=>Ka,lt:()=>Da,lte:()=>Ea,maxLength:()=>Za,maxSize:()=>Ca,mime:()=>Ba,minLength:()=>Ma,minSize:()=>Ra,multipleOf:()=>Pa,negative:()=>xa,nonnegative:()=>Na,nonpositive:()=>Oa,normalize:()=>Ya,overwrite:()=>qa,positive:()=>Aa,property:()=>Wa,regex:()=>Ua,size:()=>ja,slugify:()=>ec,startsWith:()=>Fa,toLowerCase:()=>Xa,toUpperCase:()=>Qa,trim:()=>Ga,uppercase:()=>Ja});var o={};n.r(o),n.d(o,{ZodISODate:()=>fc,ZodISODateTime:()=>lc,ZodISODuration:()=>yc,ZodISOTime:()=>mc,date:()=>hc,datetime:()=>pc,duration:()=>vc,time:()=>gc});var s={};n.r(s),n.d(s,{ZodAny:()=>eu,ZodArray:()=>uu,ZodBase64:()=>_d,ZodBase64URL:()=>Sd,ZodBigInt:()=>Jd,ZodBigIntFormat:()=>Fd,ZodBoolean:()=>Ud,ZodCIDRv4:()=>gd,ZodCIDRv6:()=>vd,ZodCUID:()=>ed,ZodCUID2:()=>nd,ZodCatch:()=>ol,ZodCodec:()=>ll,ZodCustom:()=>kl,ZodCustomStringFormat:()=>$d,ZodDate:()=>cu,ZodDefault:()=>Gu,ZodDiscriminatedUnion:()=>bu,ZodE164:()=>Id,ZodEmail:()=>Zc,ZodEmoji:()=>Yc,ZodEnum:()=>Cu,ZodExactOptional:()=>Vu,ZodFile:()=>Lu,ZodFunction:()=>bl,ZodGUID:()=>Lc,ZodIPv4:()=>ud,ZodIPv6:()=>hd,ZodIntersection:()=>ku,ZodJWT:()=>Dd,ZodKSUID:()=>cd,ZodLazy:()=>yl,ZodLiteral:()=>Zu,ZodMAC:()=>pd,ZodMap:()=>xu,ZodNaN:()=>al,ZodNanoID:()=>Xc,ZodNever:()=>iu,ZodNonOptional:()=>tl,ZodNull:()=>Xd,ZodNullable:()=>Bu,ZodNumber:()=>Nd,ZodNumberFormat:()=>Cd,ZodObject:()=>fu,ZodOptional:()=>Hu,ZodPipe:()=>dl,ZodPrefault:()=>Qu,ZodPromise:()=>wl,ZodReadonly:()=>fl,ZodRecord:()=>Eu,ZodSet:()=>Nu,ZodString:()=>Cc,ZodStringFormat:()=>jc,ZodSuccess:()=>rl,ZodSymbol:()=>Bd,ZodTemplateLiteral:()=>ml,ZodTransform:()=>Ku,ZodTuple:()=>zu,ZodType:()=>Nc,ZodULID:()=>id,ZodURL:()=>Wc,ZodUUID:()=>Kc,ZodUndefined:()=>Yd,ZodUnion:()=>yu,ZodUnknown:()=>nu,ZodVoid:()=>su,ZodXID:()=>sd,ZodXor:()=>wu,_ZodString:()=>Pc,_default:()=>Xu,_function:()=>Sl,any:()=>tu,array:()=>lu,base64:()=>bd,base64url:()=>kd,bigint:()=>Hd,boolean:()=>Kd,catch:()=>sl,check:()=>Il,cidrv4:()=>yd,cidrv6:()=>wd,codec:()=>pl,cuid:()=>td,cuid2:()=>rd,custom:()=>zl,date:()=>du,describe:()=>$l,discriminatedUnion:()=>Su,e164:()=>zd,email:()=>Mc,emoji:()=>Gc,enum:()=>Ru,exactOptional:()=>Wu,file:()=>Uu,float32:()=>jd,float64:()=>Zd,function:()=>Sl,guid:()=>Uc,hash:()=>Od,hex:()=>xd,hostname:()=>Ad,httpUrl:()=>qc,instanceof:()=>Al,int:()=>Rd,int32:()=>Md,int64:()=>Vd,intersection:()=>Iu,ipv4:()=>ld,ipv6:()=>md,json:()=>Ol,jwt:()=>Ed,keyof:()=>pu,ksuid:()=>dd,lazy:()=>vl,literal:()=>Mu,looseObject:()=>gu,looseRecord:()=>Au,mac:()=>fd,map:()=>Ou,meta:()=>Tl,nan:()=>cl,nanoid:()=>Qc,nativeEnum:()=>ju,never:()=>ou,nonoptional:()=>nl,null:()=>Qd,nullable:()=>qu,nullish:()=>Yu,number:()=>Pd,object:()=>hu,optional:()=>Fu,partialRecord:()=>Tu,pipe:()=>ul,prefault:()=>el,preprocess:()=>Nl,promise:()=>_l,readonly:()=>hl,record:()=>$u,refine:()=>Dl,set:()=>Pu,strictObject:()=>mu,string:()=>Rc,stringFormat:()=>Td,stringbool:()=>xl,success:()=>il,superRefine:()=>El,symbol:()=>qd,templateLiteral:()=>gl,transform:()=>Ju,tuple:()=>Du,uint32:()=>Ld,uint64:()=>Wd,ulid:()=>od,undefined:()=>Gd,union:()=>vu,unknown:()=>ru,url:()=>Bc,uuid:()=>Jc,uuidv4:()=>Hc,uuidv6:()=>Fc,uuidv7:()=>Vc,void:()=>au,xid:()=>ad,xor:()=>_u});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=m(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=m(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 f(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 h(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 m(e){const t=e.length%4;return 0===t?e:e+"=".repeat((4-t)%4)}const g="https://schema.kya-os.org/v1/protocol/delegation/context/v1.0.0";function y(e,t){const n=(new Date).toISOString(),r=e.constraints.notAfter?new Date(1e3*e.constraints.notAfter).toISOString():t?.expirationDate;let i=t?.issuanceDate||n;!t?.issuanceDate&&e.createdAt&&(i=new Date(e.createdAt).toISOString());const o=t?.scopes||e.constraints.scopes;return{"@context":["https://www.w3.org/2018/credentials/v1",g],id:t?.id||e.vcId||`urn:uuid:${e.id}`,type:["VerifiableCredential","DelegationCredential"],issuer:e.issuerDid,issuanceDate:i,...void 0!==r&&{expirationDate:r},credentialSubject:{id:e.subjectDid,delegation:{id:e.id,issuerDid:e.issuerDid,subjectDid:e.subjectDid,...t?.userDid&&{userDid:t.userDid},...t?.userIdentifier&&{userIdentifier:t.userIdentifier},...t?.sessionId&&{sessionId:t.sessionId},...o&&o.length>0&&{scopes:o},...void 0!==e.controller&&{controller:e.controller},...void 0!==e.parentId&&{parentId:e.parentId},constraints:e.constraints,status:e.status,...void 0!==e.createdAt&&{createdAt:e.createdAt},...void 0!==e.metadata&&{metadata:e.metadata}}},...void 0!==t?.credentialStatus&&{credentialStatus:t.credentialStatus}}}function 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 w(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 _(e){const t=e.credentialSubject.delegation;return!!(t.constraints.notBefore&&Math.floor(Date.now()/1e3)<t.constraints.notBefore)}function b(e){if(!e||"object"!=typeof e)return{success:!1,error:{message:"Not an object"}};const t=e;if(!Array.isArray(t["@context"])||0===t["@context"].length)return{success:!1,error:{message:"Missing or invalid @context"}};if("https://www.w3.org/2018/credentials/v1"!==t["@context"][0])return{success:!1,error:{message:"First @context must be W3C VC context"}};if(!Array.isArray(t.type))return{success:!1,error:{message:"Missing type array"}};if(!t.type.includes("VerifiableCredential")||!t.type.includes("DelegationCredential"))return{success:!1,error:{message:"type must include VerifiableCredential and DelegationCredential"}};if(!t.issuer||"string"!=typeof t.issuer&&"object"!=typeof t.issuer)return{success:!1,error:{message:"Missing or invalid issuer"}};if(!t.issuanceDate||"string"!=typeof t.issuanceDate)return{success:!1,error:{message:"Missing issuanceDate"}};const n=t.credentialSubject;if(!n||"object"!=typeof n)return{success:!1,error:{message:"Missing credentialSubject"}};if(!n.id||"string"!=typeof n.id)return{success:!1,error:{message:"credentialSubject.id missing"}};const r=n.delegation;return r&&"object"==typeof r?r.id&&r.issuerDid&&r.subjectDid&&r.constraints?{success:!0,data:e}:{success:!1,error:{message:"delegation fields missing"}}:{success:!1,error:{message:"credentialSubject.delegation missing"}}}const S=30,k=120,I=16,z=12e4,D=6e4;function E(e){return{error:"needs_authorization",...e}}function $(e){return"object"==typeof e&&null!==e&&"needs_authorization"===e.error}function T(e){return{error:"needs_approval",...e}}function A(e){return"object"==typeof e&&null!==e&&"needs_approval"===e.error}const x=/^sha256:[a-f0-9]{64}$/;function O(e){if(!e||"object"!=typeof e)return{success:!1,error:{message:"Not an object"}};const t=e;if("string"!=typeof t.jws||t.jws.length<1)return{success:!1,error:{message:"jws must be a non-empty string"}};const n=t.meta;if(!n||"object"!=typeof n)return{success:!1,error:{message:"meta must be an object"}};const r=n,i=["did","kid","nonce","audience","sessionId"];for(const e of i)if("string"!=typeof r[e]||r[e].length<1)return{success:!1,error:{message:`meta.${e} must be a non-empty string`}};if("number"!=typeof r.ts||!Number.isInteger(r.ts)||r.ts<=0)return{success:!1,error:{message:"meta.ts must be a positive integer"}};if("string"!=typeof r.requestHash||!x.test(r.requestHash))return{success:!1,error:{message:"meta.requestHash must match sha256:<64 hex chars>"}};if(void 0!==r.responseHash&&("string"!=typeof r.responseHash||!x.test(r.responseHash)))return{success:!1,error:{message:"meta.responseHash must match sha256:<64 hex chars> when present"}};const o=["scopeId","delegationRef","clientDid","reason"];for(const e of o)if(void 0!==r[e]&&"string"!=typeof r[e])return{success:!1,error:{message:`meta.${e} must be a string if present`}};return void 0===r.outcome||["allowed","denied","step_up_required","needs_authorization"].includes(r.outcome)?{success:!0,data:e}:{success:!1,error:{message:"meta.outcome must be one of allowed | denied | step_up_required | needs_authorization"}}}var N=n(77753);function P(e){return C(e),(0,N.d)(e)}function C(e,t="$"){if(null!==e&&"boolean"!=typeof e&&"string"!=typeof e)if("number"!=typeof e){if(void 0===e)throw new TypeError(`Cannot canonicalize undefined at ${t}`);if("function"==typeof e)throw new TypeError(`Cannot canonicalize function at ${t}`);if("symbol"==typeof e)throw new TypeError(`Cannot canonicalize symbol at ${t}`);if("bigint"==typeof e)throw new TypeError(`Cannot canonicalize bigint at ${t}`);if(Array.isArray(e))for(let n=0;n<e.length;n++)C(e[n],`${t}[${n}]`);else if("object"!=typeof e);else for(const[n,r]of Object.entries(e))C(r,`${t}.${n}`)}else if(!Number.isFinite(e))throw new TypeError(`Cannot canonicalize non-finite number at ${t}: ${e}`)}function R(e,t={}){const n={alg:"EdDSA",typ:"JWT"};t.keyId&&(n.kid=t.keyId);const r="string"==typeof e.issuer?e.issuer:e.issuer?.id,i=e.credentialSubject?.id;let o,s;e.expirationDate&&"string"==typeof e.expirationDate&&(o=Math.floor(new Date(e.expirationDate).getTime()/1e3)),e.issuanceDate&&"string"==typeof e.issuanceDate&&(s=Math.floor(new Date(e.issuanceDate).getTime()/1e3));const a={...e};delete a.proof;const c={iss:r,vc:a};i&&(c.sub=i),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 j(e,t){return`${e}.${t}`}function Z(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 M{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 r=this.canonicalizeVC(n),i=await this.signingFunction(r,this.identity.getDid(),this.identity.getKeyId());return{...n,proof:i}}async createAndIssueDelegation(e,t={}){const n=Date.now(),r={id:e.id,issuerDid:e.issuerDid,subjectDid:e.subjectDid,controller:e.controller,vcId:t.id||`urn:uuid:${e.id}`,parentId:e.parentId,constraints:e.constraints,signature:"",status:e.status||"active",createdAt:n,metadata:e.metadata};return this.issueDelegationCredential(r,t)}canonicalizeVC(e){return P(e)}getIssuerDid(){return this.identity.getDid()}getIssuerKeyId(){return this.identity.getKeyId()}}function L(e,t){return new M(e,t)}const U=["id","delegation"];class K{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();if(!t.skipCache){const t=this.getFromCache(e.id||"");if(t)return{...t,cached:!0}}const r=Date.now(),i=this.validateBasicProperties(e),o=Date.now()-r;if(!i.valid)return{valid:!1,reason:i.reason,stage:"basic",metrics:{basicCheckMs:o,totalMs:Date.now()-n},checks:{basicValid:!1}};const s=t.skipSignature?Promise.resolve({valid:!0,durationMs:0}):this.verifySignature(e,t.didResolver||this.didResolver),a=!t.skipStatus&&e.credentialStatus?this.checkCredentialStatus(e.credentialStatus,t.statusListResolver||this.statusListResolver):Promise.resolve({valid:!0,durationMs:0}),[c,d]=await Promise.all([s,a]),u=c.durationMs||0,l=d.durationMs||0,p=i.valid&&c.valid&&d.valid,f={valid:p,reason:p?void 0:c.reason||d.reason||"Unknown failure",stage:"complete",metrics:{basicCheckMs:o,signatureCheckMs:u,statusCheckMs:l,totalMs:Date.now()-n},checks:{basicValid:i.valid,signatureValid:c.valid,statusValid:d.valid}};return f.valid&&e.id&&this.setInCache(e.id,f),f}validateBasicProperties(e){const t=b(e);if(!t.success)return{valid:!1,reason:`Schema validation failed: ${t.error?.message}`};if(w(e))return{valid:!1,reason:"Delegation credential expired"};if(_(e))return{valid:!1,reason:"Delegation credential not yet valid"};const n=e.credentialSubject.delegation;if("revoked"===n.status)return{valid:!1,reason:"Delegation status is revoked"};if("expired"===n.status)return{valid:!1,reason:"Delegation status is expired"};if(!n.issuerDid||!n.subjectDid)return{valid:!1,reason:"Missing issuer or subject DID"};if(!e.proof)return{valid:!1,reason:"Missing proof"};const r=this.validateSubjectShape(e);return r.valid?{valid:!0}:r}validateSubjectShape(e){const t=Object.keys(e.credentialSubject).filter(e=>!U.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).`}}async verifySignature(e,t){const n=Date.now();try{const r="string"==typeof e.issuer?e.issuer:e.issuer.id;if(!t||!this.signatureVerifier)return{valid:!1,reason:"No DID resolver or signature verifier configured — signature cannot be verified",durationMs:Date.now()-n};const i=await t.resolve(r);if(!i)return{valid:!1,reason:`Could not resolve issuer DID: ${r}`,durationMs:Date.now()-n};if(!e.proof)return{valid:!1,reason:"Proof is missing",durationMs:Date.now()-n};const o=e.proof.verificationMethod;if(!o)return{valid:!1,reason:"Proof missing verificationMethod",durationMs:Date.now()-n};const s=this.findVerificationMethod(i,o);if(!s)return{valid:!1,reason:`Verification method ${o} not found`,durationMs:Date.now()-n};const a=s.publicKeyJwk;if(!a)return{valid:!1,reason:"Verification method missing publicKeyJwk",durationMs:Date.now()-n};const c=await this.signatureVerifier(e,a);return{valid:c.valid,reason:c.reason,durationMs:Date.now()-n}}catch(e){return{valid:!1,reason:`Signature verification error: ${e instanceof Error?e.message:"Unknown error"}`,durationMs:Date.now()-n}}}async checkCredentialStatus(e,t){const n=Date.now();try{return t?await t.checkStatus(e)?{valid:!1,reason:`Credential revoked via StatusList2021 (${e.statusPurpose})`,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",durationMs:Date.now()-n}}catch(e){return{valid:!1,reason:`Status check error: ${e instanceof Error?e.message:"Unknown error"}`,durationMs:Date.now()-n}}}findVerificationMethod(e,t){return e.verificationMethod?.find(e=>e.id===t)}getFromCache(e){const t=this.cache.get(e);return t?Date.now()>t.expiresAt?(this.cache.delete(e),null):t.result:null}setInCache(e,t){for(;this.cache.size>=this.maxCacheSize&&this.cacheInsertionOrder.length>0;){const e=this.cacheInsertionOrder.shift();e&&this.cache.delete(e)}this.cache.set(e,{result:t,expiresAt:Date.now()+this.cacheTtl}),this.cacheInsertionOrder.push(e)}clearCache(){this.cache.clear(),this.cacheInsertionOrder=[]}clearCacheEntry(e){this.cache.delete(e);const t=this.cacheInsertionOrder.indexOf(e);-1!==t&&this.cacheInsertionOrder.splice(t,1)}}function J(e){return new K(e)}class H{storage;constructor(e){this.storage=e}async registerDelegation(e){const t={id:e.id,parentId:e.parentId,children:[],issuerDid:e.issuerDid,subjectDid:e.subjectDid,credentialStatusId:e.credentialStatusId};return await this.storage.setNode(t),e.parentId&&await this.addChildToParent(e.parentId,e.id),t}async addChildToParent(e,t){const n=await this.storage.getNode(e);if(!n)throw new Error(`Parent delegation not found: ${e}`);n.children.includes(t)||(n.children.push(t),await this.storage.setNode(n))}async getNode(e){return this.storage.getNode(e)}async getChildren(e){return this.storage.getChildren(e)}async getDescendants(e){return this.storage.getDescendants(e)}async getChain(e){return this.storage.getChain(e)}async isAncestor(e,t){return(await this.getChain(t)).some(t=>t.id===e)}async getDepth(e){return(await this.getChain(e)).length-1}async validateChain(e){const t=await this.getChain(e);if(0===t.length)return{valid:!1,reason:"Delegation not found"};for(let e=1;e<t.length;e++){const n=t[e-1],r=t[e];if(r.issuerDid!==n.subjectDid)return{valid:!1,reason:`Invalid chain: ${r.id} issued by ${r.issuerDid} but parent ${n.id} subject is ${n.subjectDid}`};if(r.parentId!==n.id)return{valid:!1,reason:`Invalid chain: ${r.id} parentId=${r.parentId} but actual parent is ${n.id}`}}return{valid:!0}}async removeDelegation(e){const t=await this.storage.getNode(e);if(t){if(t.parentId){const n=await this.storage.getNode(t.parentId);n&&(n.children=n.children.filter(t=>t!==e),await this.storage.setNode(n))}await this.storage.deleteNode(e)}}}function F(e){return new H(e)}class V{compressor;decompressor;bits;size;constructor(e,t,n){this.compressor=t,this.decompressor=n,this.size=e;const r=Math.ceil(e/8);this.bits=new Uint8Array(r)}setBit(e,t){if(e<0||e>=this.size)throw new Error(`Bit index ${e} out of range (0-${this.size-1})`);const n=Math.floor(e/8),r=e%8;t?this.bits[n]|=1<<r:this.bits[n]&=~(1<<r)}getBit(e){if(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]&1<<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 this.base64urlEncode(e)}static async decode(e,t,n){const r=V.base64urlDecode(e),i=await n.decompress(r),o=8*i.length,s=new V(o,t,n);return s.bits=i,s}getRawBits(){return this.bits}getSize(){return this.size}base64urlEncode(e){return this.bytesToBase64(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}static base64urlDecode(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");for(;t.length%4!=0;)t+="=";return V.base64ToBytes(t)}bytesToBase64(e){const t=Array.from(e).map(e=>String.fromCharCode(e)).join("");return btoa(t)}static base64ToBytes(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");const n=(4-t.length%4)%4;t+="=".repeat(n);const r=atob(t),i=new Uint8Array(r.length);for(let e=0;e<r.length;e++)i[e]=r.charCodeAt(e);return i}static fromSetBits(e,t,n,r){const i=new V(e,n,r);for(const e of t)i.setBit(e,!0);return i}}async function W(e,t,n){const r=V.base64urlDecode(e),i=await n.decompress(r),o=Math.floor(t/8),s=t%8;return!(o>=i.length||!(i[o]&1<<s))}class B{storage;identity;signingFunction;compressor;decompressor;statusListBaseUrl;defaultListSize;updateLocks=new Map;constructor(e,t,n,r,i,o){this.storage=e,this.identity=t,this.signingFunction=n,this.compressor=r,this.decompressor=i,this.statusListBaseUrl=o?.statusListBaseUrl||"https://status.example.com",this.defaultListSize=o?.defaultListSize||131072}async allocateStatusEntry(e){const t=`${this.statusListBaseUrl}/${e}/v1`,n=await this.storage.allocateIndex(t);return await this.ensureStatusListExists(t,e),{id:`${t}#${n}`,type:"StatusList2021Entry",statusPurpose:e,statusListIndex:n.toString(),statusListCredential:t}}async updateStatus(e,t){const{statusListCredential:n}=e,r=(this.updateLocks.get(n)??Promise.resolve()).then(()=>this.doUpdateStatus(e,t));this.updateLocks.set(n,r.catch(()=>{})),await r}async doUpdateStatus(e,t){const{statusListCredential:n,statusListIndex:r}=e,i=await this.storage.getStatusList(n);if(!i)throw new Error(`Status list not found: ${n}`);const o=await V.decode(i.credentialSubject.encodedList,this.compressor,this.decompressor),s=parseInt(r,10);o.setBit(s,t);const a=await o.encode(),c={...i,credentialSubject:{...i.credentialSubject,encodedList:a}},d={...c};delete d.proof;const u=P(d),l=await this.signingFunction(u,this.identity.getDid(),this.identity.getKeyId()),p={...c,proof:l};await this.storage.setStatusList(n,p)}async checkStatus(e){const{statusListCredential:t,statusListIndex:n}=e,r=await this.storage.getStatusList(t);if(!r)throw new Error(`Status list not found: ${t} — cannot determine revocation status`);const i=await V.decode(r.credentialSubject.encodedList,this.compressor,this.decompressor),o=parseInt(n,10);return i.getBit(o)}async getRevokedIndices(e){const t=await this.storage.getStatusList(e);return t?(await V.decode(t.credentialSubject.encodedList,this.compressor,this.decompressor)).getSetBits():[]}async ensureStatusListExists(e,t){if(await this.storage.getStatusList(e))return;const n=new V(this.defaultListSize,this.compressor,this.decompressor),r=await n.encode(),i={"@context":["https://www.w3.org/2018/credentials/v1","https://w3id.org/vc/status-list/2021/v1"],id:e,type:["VerifiableCredential","StatusList2021Credential"],issuer:this.identity.getDid(),issuanceDate:(new Date).toISOString(),credentialSubject:{id:`${e}#list`,type:"StatusList2021",statusPurpose:t,encodedList:r}},o=P(i),s=await this.signingFunction(o,this.identity.getDid(),this.identity.getKeyId()),a={...i,proof:s};await this.storage.setStatusList(e,a)}getStatusListBaseUrl(){return this.statusListBaseUrl}getDefaultListSize(){return this.defaultListSize}}function q(e,t,n,r,i,o){return new B(e,t,n,r,i,o)}class Y{graph;statusList;constructor(e,t){this.graph=e,this.statusList=t}async revokeDelegation(e,t={}){const n=t.maxDepth||100,r=[],i=await this.graph.getNode(e);if(!i)throw new Error(`Delegation not found: ${e}`);const o=await this.graph.getDepth(e);if(o>n)throw new Error(`Delegation depth ${o} exceeds maximum ${n}`);const s=await this.revokeNode(i,!0,t.reason,t.dryRun);r.push(s),t.onRevoke&&await t.onRevoke(s);const a=await this.graph.getDescendants(e);for(const n of a){const i=await this.revokeNode(n,!1,`Cascaded from ${e}`,t.dryRun,e);r.push(i),t.onRevoke&&await t.onRevoke(i)}return r}async revokeNode(e,t,n,r,i){const o={delegationId:e.id,isRoot:t,parentId:i,timestamp:Date.now(),reason:n};if(r)return o;if(e.credentialStatusId){const t=this.parseCredentialStatus(e.credentialStatusId);t&&await this.statusList.updateStatus(t,!0)}return o}async restoreDelegation(e){const t=await this.graph.getNode(e);if(!t)throw new Error(`Delegation not found: ${e}`);const n={delegationId:t.id,isRoot:!0,timestamp:Date.now(),reason:"Restored"};if(t.credentialStatusId){const e=this.parseCredentialStatus(t.credentialStatusId);e&&await this.statusList.updateStatus(e,!1)}return n}async isRevoked(e){const t=await this.graph.getChain(e);for(const n of t)if(n.credentialStatusId){const t=this.parseCredentialStatus(n.credentialStatusId);if(t&&await this.statusList.checkStatus(t))return{revoked:!0,reason:n.id===e?"Directly revoked":"Ancestor revoked",revokedAncestor:n.id===e?void 0:n.id}}return{revoked:!1}}async getRevokedInSubtree(e){const t=await this.graph.getDescendants(e),n=[];(await this.isRevoked(e)).revoked&&n.push(e);for(const e of t)(await this.isRevoked(e.id)).revoked&&n.push(e.id);return n}parseCredentialStatus(e){const t=e.match(/^(.+)#(\d+)$/);if(!t)return null;const[,n,r]=t;return{id:e,type:"StatusList2021Entry",statusPurpose:"revocation",statusListIndex:parseInt(r,10).toString(),statusListCredential:n}}async validateDelegation(e){const t=await this.isRevoked(e);if(t.revoked)return{valid:!1,reason:t.revokedAncestor?`Ancestor ${t.revokedAncestor} is revoked`:"Delegation is revoked"};const n=await this.graph.validateChain(e);return n.valid?{valid:!0}:n}}function G(e,t){return new Y(e,t)}function X(e,t){if(!e.constraints.audience)return!0;const n=e.constraints.audience;return"string"==typeof n?n===t:n.includes(t)}var Q=n(95354),ee=n(77598),te=n(4573);const ne=e=>e.d?(0,ee.createPrivateKey)({format:"jwk",key:e}):(0,ee.createPublicKey)({format:"jwk",key:e});var re=n(36463);function ie(e){if("object"!=typeof(t=e)||null===t||"[object Object]"!==Object.prototype.toString.call(e))return!1;var t;if(null===Object.getPrototypeOf(e))return!0;let n=e;for(;null!==Object.getPrototypeOf(n);)n=Object.getPrototypeOf(n);return Object.getPrototypeOf(e)===n}var oe=n(57975),se=n(56233),ae=n(73960),ce=n(99769),de=n(71964);function ue(e){return ie(e)&&"string"==typeof e.kty}new WeakMap;const le=(e,t)=>{let n;if((0,se.R)(e))n=ee.KeyObject.from(e);else{if(!(0,ae.A)(e)){if(ue(e))return e.crv;throw new TypeError((0,ce.A)(e,...de.g))}n=e}if("secret"===n.type)throw new TypeError('only "private" or "public" type keys can be used for this operation');switch(n.asymmetricKeyType){case"ed25519":case"ed448":return`Ed${n.asymmetricKeyType.slice(2)}`;case"x25519":case"x448":return`X${n.asymmetricKeyType.slice(1)}`;case"ec":{const e=n.asymmetricKeyDetails.namedCurve;return t?e:(e=>{switch(e){case"prime256v1":return"P-256";case"secp384r1":return"P-384";case"secp521r1":return"P-521";case"secp256k1":return"secp256k1";default:throw new re.T0("Unsupported key curve for this operation")}})(e)}default:throw new TypeError("Invalid asymmetric key type for this operation")}},pe=(e,t)=>{let n;try{n=e instanceof ee.KeyObject?e.asymmetricKeyDetails?.modulusLength:Buffer.from(e.n,"base64url").byteLength<<3}catch{}if("number"!=typeof n||n<2048)throw new TypeError(`${t} requires key modulusLength to be 2048 bits or larger`)},fe=new Map([["ES256","P-256"],["ES256K","secp256k1"],["ES384","P-384"],["ES512","P-521"]]);function he(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function me(e,t){return e.name===t}function ge(e){return parseInt(e.name.slice(4),10)}function ye(e,t,...n){switch(t){case"HS256":case"HS384":case"HS512":{if(!me(e.algorithm,"HMAC"))throw he("HMAC");const n=parseInt(t.slice(2),10);if(ge(e.algorithm.hash)!==n)throw he(`SHA-${n}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!me(e.algorithm,"RSASSA-PKCS1-v1_5"))throw he("RSASSA-PKCS1-v1_5");const n=parseInt(t.slice(2),10);if(ge(e.algorithm.hash)!==n)throw he(`SHA-${n}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!me(e.algorithm,"RSA-PSS"))throw he("RSA-PSS");const n=parseInt(t.slice(2),10);if(ge(e.algorithm.hash)!==n)throw he(`SHA-${n}`,"algorithm.hash");break}case"EdDSA":if("Ed25519"!==e.algorithm.name&&"Ed448"!==e.algorithm.name)throw he("Ed25519 or Ed448");break;case"Ed25519":if(!me(e.algorithm,"Ed25519"))throw he("Ed25519");break;case"ES256":case"ES384":case"ES512":{if(!me(e.algorithm,"ECDSA"))throw he("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 he(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}!function(e,t){if(t.length&&!t.some(t=>e.usages.includes(t))){let e="CryptoKey does not support this operation, its usages must include ";if(t.length>2){const n=t.pop();e+=`one of ${t.join(", ")}, or ${n}.`}else 2===t.length?e+=`one of ${t[0]} or ${t[1]}.`:e+=`${t[0]}.`;throw new TypeError(e)}}(e,n)}const ve=(0,oe.promisify)(ee.sign);var we=n(62165);const _e=e=>e?.[Symbol.toStringTag],be=(e,t,n)=>{if(void 0!==t.use&&"sig"!==t.use)throw new TypeError("Invalid key for this operation, when present its use must be sig");if(void 0!==t.key_ops&&!0!==t.key_ops.includes?.(n))throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${n}`);if(void 0!==t.alg&&t.alg!==e)throw new TypeError(`Invalid key for this operation, when present its alg must be ${e}`);return!0};function Se(e,t,n,r){t.startsWith("HS")||"dir"===t||t.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(t)?((e,t,n,r)=>{if(!(t instanceof Uint8Array)){if(r&&ue(t)){if(function(e){return ue(e)&&"oct"===e.kty&&"string"==typeof e.k}(t)&&be(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(!(0,de.A)(t))throw new TypeError((0,ce.t)(e,t,...de.g,"Uint8Array",r?"JSON Web Key":null));if("secret"!==t.type)throw new TypeError(`${_e(t)} instances for symmetric algorithms must be of type "secret"`)}})(t,n,r,e):((e,t,n,r)=>{if(r&&ue(t))switch(n){case"sign":if(function(e){return"oct"!==e.kty&&"string"==typeof e.d}(t)&&be(e,t,n))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(function(e){return"oct"!==e.kty&&void 0===e.d}(t)&&be(e,t,n))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!(0,de.A)(t))throw new TypeError((0,ce.t)(e,t,...de.g,r?"JSON Web Key":null));if("secret"===t.type)throw new TypeError(`${_e(t)} instances for asymmetric algorithms must not be of type "secret"`);if("sign"===n&&"public"===t.type)throw new TypeError(`${_e(t)} instances for asymmetric algorithm signing must be of type "private"`);if("decrypt"===n&&"public"===t.type)throw new TypeError(`${_e(t)} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&"verify"===n&&"private"===t.type)throw new TypeError(`${_e(t)} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&"encrypt"===n&&"private"===t.type)throw new TypeError(`${_e(t)} instances for asymmetric algorithm encryption must be of type "public"`)})(t,n,r,e)}Se.bind(void 0,!1);const ke=Se.bind(void 0,!0);class Ie{_payload;_protectedHeader;_unprotectedHeader;constructor(e){if(!(e instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this._payload=e}setProtectedHeader(e){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=e,this}setUnprotectedHeader(e){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=e,this}async sign(e,t){if(!this._protectedHeader&&!this._unprotectedHeader)throw new re.Ye("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!((...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})(this._protectedHeader,this._unprotectedHeader))throw new re.Ye("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const n={...this._protectedHeader,...this._unprotectedHeader};let r=!0;if(function(e,t,n,r,i){if(void 0!==i.crit&&void 0===r?.crit)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!r||void 0===r.crit)return new Set;if(!Array.isArray(r.crit)||0===r.crit.length||r.crit.some(e=>"string"!=typeof e||0===e.length))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let o;o=void 0!==n?new Map([...Object.entries(n),...t.entries()]):t;for(const t of r.crit){if(!o.has(t))throw new re.T0(`Extension Header Parameter "${t}" is not recognized`);if(void 0===i[t])throw new e(`Extension Header Parameter "${t}" is missing`);if(o.get(t)&&void 0===r[t])throw new e(`Extension Header Parameter "${t}" MUST be integrity protected`)}return new Set(r.crit)}(re.Ye,new Map([["b64",!0]]),t?.crit,this._protectedHeader,n).has("b64")&&(r=this._protectedHeader.b64,"boolean"!=typeof r))throw new re.Ye('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:i}=n;if("string"!=typeof i||!i)throw new re.Ye('JWS "alg" (Algorithm) Header Parameter missing or invalid');ke(i,e,"sign");let o,s=this._payload;r&&(s=we.Rd.encode((0,Q.lF)(s))),o=this._protectedHeader?we.Rd.encode((0,Q.lF)(JSON.stringify(this._protectedHeader))):we.Rd.encode("");const a=(0,we.xW)(o,we.Rd.encode("."),s),c=await(async(e,t,n)=>{const r=function(e,t){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError((0,ce.A)(t,...de.g));return(0,ee.createSecretKey)(t)}if(t instanceof ee.KeyObject)return t;if((0,se.R)(t))return ye(t,e,"sign"),ee.KeyObject.from(t);if(ue(t))return e.startsWith("HS")?(0,ee.createSecretKey)(Buffer.from(t.k,"base64url")):t;throw new TypeError((0,ce.A)(t,...de.g,"Uint8Array","JSON Web Key"))}(e,t);if(e.startsWith("HS")){const t=ee.createHmac(function(e){switch(e){case"HS256":return"sha256";case"HS384":return"sha384";case"HS512":return"sha512";default:throw new re.T0(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}(e),r);return t.update(n),t.digest()}return ve(function(e){switch(e){case"PS256":case"RS256":case"ES256":case"ES256K":return"sha256";case"PS384":case"RS384":case"ES384":return"sha384";case"PS512":case"RS512":case"ES512":return"sha512";case"Ed25519":case"EdDSA":return;default:throw new re.T0(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}(e),n,function(e,t){let n,r,i,o;if(t instanceof ee.KeyObject)n=t.asymmetricKeyType,r=t.asymmetricKeyDetails;else switch(i=!0,t.kty){case"RSA":n="rsa";break;case"EC":n="ec";break;case"OKP":if("Ed25519"===t.crv){n="ed25519";break}if("Ed448"===t.crv){n="ed448";break}throw new TypeError("Invalid key for this operation, its crv must be Ed25519 or Ed448");default:throw new TypeError("Invalid key for this operation, its kty must be RSA, OKP, or EC")}switch(e){case"Ed25519":if("ed25519"!==n)throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ed25519");break;case"EdDSA":if(!["ed25519","ed448"].includes(n))throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ed25519 or ed448");break;case"RS256":case"RS384":case"RS512":if("rsa"!==n)throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa");pe(t,e);break;case"PS256":case"PS384":case"PS512":if("rsa-pss"===n){const{hashAlgorithm:t,mgf1HashAlgorithm:n,saltLength:i}=r,o=parseInt(e.slice(-3),10);if(void 0!==t&&(t!==`sha${o}`||n!==t))throw new TypeError(`Invalid key for this operation, its RSA-PSS parameters do not meet the requirements of "alg" ${e}`);if(void 0!==i&&i>o>>3)throw new TypeError(`Invalid key for this operation, its RSA-PSS parameter saltLength does not meet the requirements of "alg" ${e}`)}else if("rsa"!==n)throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa or rsa-pss");pe(t,e),o={padding:ee.constants.RSA_PKCS1_PSS_PADDING,saltLength:ee.constants.RSA_PSS_SALTLEN_DIGEST};break;case"ES256":case"ES256K":case"ES384":case"ES512":{if("ec"!==n)throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ec");const r=le(t),i=fe.get(e);if(r!==i)throw new TypeError(`Invalid key curve for the algorithm, its curve must be ${i}, got ${r}`);o={dsaEncoding:"ieee-p1363"};break}default:throw new re.T0(`alg ${e} is not supported either by JOSE or your javascript runtime`)}return i?{format:"jwk",key:t,...o}:o?{...o,key:t}:t}(e,r))})(i,e,a),d={signature:(0,Q.lF)(c),payload:""};return r&&(d.payload=we.D0.decode(s)),this._unprotectedHeader&&(d.header=this._unprotectedHeader),this._protectedHeader&&(d.protected=we.D0.decode(o)),d}}class ze{_flattened;constructor(e){this._flattened=new Ie(e)}setProtectedHeader(e){return this._flattened.setProtectedHeader(e),this}async sign(e,t){const n=await this._flattened.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 De=e=>Math.floor(e.getTime()/1e3),Ee=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,$e=e=>{const t=Ee.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");const n=parseFloat(t[2]);let r;switch(t[3].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":r=Math.round(n);break;case"minute":case"minutes":case"min":case"mins":case"m":r=Math.round(60*n);break;case"hour":case"hours":case"hr":case"hrs":case"h":r=Math.round(3600*n);break;case"day":case"days":case"d":r=Math.round(86400*n);break;case"week":case"weeks":case"w":r=Math.round(604800*n);break;default:r=Math.round(31557600*n)}return"-"===t[1]||"ago"===t[4]?-r:r};function Te(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}class Ae{_payload;constructor(e={}){if(!ie(e))throw new TypeError("JWT Claims Set MUST be an object");this._payload=e}setIssuer(e){return this._payload={...this._payload,iss:e},this}setSubject(e){return this._payload={...this._payload,sub:e},this}setAudience(e){return this._payload={...this._payload,aud:e},this}setJti(e){return this._payload={...this._payload,jti:e},this}setNotBefore(e){return"number"==typeof e?this._payload={...this._payload,nbf:Te("setNotBefore",e)}:e instanceof Date?this._payload={...this._payload,nbf:Te("setNotBefore",De(e))}:this._payload={...this._payload,nbf:De(new Date)+$e(e)},this}setExpirationTime(e){return"number"==typeof e?this._payload={...this._payload,exp:Te("setExpirationTime",e)}:e instanceof Date?this._payload={...this._payload,exp:Te("setExpirationTime",De(e))}:this._payload={...this._payload,exp:De(new Date)+$e(e)},this}setIssuedAt(e){return void 0===e?this._payload={...this._payload,iat:De(new Date)}:e instanceof Date?this._payload={...this._payload,iat:Te("setIssuedAt",De(e))}:this._payload="string"==typeof e?{...this._payload,iat:Te("setIssuedAt",De(new Date)+$e(e))}:{...this._payload,iat:Te("setIssuedAt",e)},this}}class xe extends Ae{_protectedHeader;setProtectedHeader(e){return this._protectedHeader=e,this}async sign(e,t){const n=new ze(we.Rd.encode(JSON.stringify(this._payload)));if(n.setProtectedHeader(this._protectedHeader),Array.isArray(this._protectedHeader?.crit)&&this._protectedHeader.crit.includes("b64")&&!1===this._protectedHeader.b64)throw new re.Dp("JWTs MUST NOT use unencoded payload");return n.sign(e,t)}}async function Oe(e){const{agentDid:t,userDid:n,delegationId:r,delegationChain:i,scopes:o,privateKeyJwk:s,kid:a,targetHostname:c}=e,d=await async function(e,t){if(!ie(e))throw new TypeError("JWK must be an object");switch(t||=e.alg,e.kty){case"oct":if("string"!=typeof e.k||!e.k)throw new TypeError('missing "k" (Key Value) Parameter value');return(0,Q.D4)(e.k);case"RSA":if("oth"in e&&void 0!==e.oth)throw new re.T0('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return ne({...e,alg:t});default:throw new re.T0('Unsupported "kty" (Key Type) Parameter value')}}(s,"EdDSA"),u=Math.floor(Date.now()/1e3),l=u+60;return await new xe({delegation_id:r,delegation_chain:i,scope:o.join(",")}).setProtectedHeader({alg:"EdDSA",kid:a}).setIssuer(t).setSubject(n).setJti(crypto.randomUUID()).setAudience(c).setIssuedAt(u).setExpirationTime(l).sign(d)}function Ne(e){return e.id||e.vcId?e.vcId?`${e.vcId}>${e.id}`:e.id:""}const Pe="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",Ce=new Map;for(let e=0;e<Pe.length;e++){const t=Pe[e];void 0!==t&&Ce.set(t,e)}function Re(e){if(0===e.length)return"";let t=BigInt(0);for(let n=0;n<e.length;n++){const r=e[n];void 0!==r&&(t=t*BigInt(256)+BigInt(r))}let n="";for(;t>0;)n=Pe[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 je(e){if(0===e.length)return new Uint8Array(0);let t=BigInt(0);for(const n of e){const e=Ce.get(n);if(void 0===e)throw new Error(`Invalid base58 character: ${n}`);t=t*BigInt(58)+BigInt(e)}const n=[];for(;t>0;)n.unshift(Number(t%BigInt(256))),t/=BigInt(256);let r=0;for(const t of e){if("1"!==t)break;r++}const i=new Uint8Array(r+n.length);return i.set(n,r),i}function Ze(e){if(0===e.length)return!0;for(const t of e)if(!Ce.has(t))return!1;return!0}function Me(e){return"string"==typeof e&&e.startsWith("did:")}function Le(e){if(!Me(e))return null;const t=e.match(/^did:([^:]+):/);return t?.[1]??null}function Ue(e){return e.trim()}function Ke(e,t){return Ue(e)===Ue(t)}function Je(e){const t=e.identity.serverDid||e.identity.agentDid;if(!t)throw new Error("Server DID not configured");return t}function He(e){const t=e.split(":");return t[t.length-1]??e}function Fe(e){return He(e)}const Ve=new Uint8Array([237,1]);function We(e){const t=new Uint8Array(Ve.length+e.length);return t.set(Ve),t.set(e,Ve.length),`did:key:z${Re(t)}`}function Be(e){return We(Uint8Array.from(atob(e),e=>e.charCodeAt(0)))}function qe(e){return e.startsWith("did:key:")?e.slice(8):"keys-1"}const Ye={debug:10,info:20,warn:30,error:40};function Ge(){let e="info",t=!1;function n(n,...r){if(function(t){return Ye[t]>=Ye[e]}(n))if(t)console.error(...r);else switch(n){case"debug":"function"==typeof console.debug?console.debug(...r):console.log(...r);break;case"info":"function"==typeof console.info?console.info(...r):console.log(...r);break;case"warn":"function"==typeof console.warn?console.warn(...r):console.error(...r);break;case"error":console.error(...r)}}return{configure(n={}){n.level&&(e=n.level),!0===n.forceStderr?t=!0:!1===n.forceStderr?t=!1:"stdio"===n.transport?t=!0:"sse"!==n.transport&&"http"!==n.transport||(t=!1)},debug:(...e)=>n("debug",...e),info:(...e)=>n("info",...e),warn:(...e)=>n("warn",...e),error:(...e)=>n("error",...e)}}const Xe=Ge(),Qe=new Uint8Array([237,1]),et=32;function tt(e){return e.startsWith("did:key:z6Mk")}function nt(e){if(!e.startsWith("did:key:z"))return null;try{const t=je(e.replace("did:key:","").slice(1));return t.length<Qe.length+et||t[0]!==Qe[0]||t[1]!==Qe[1]?null:t.slice(Qe.length)}catch(e){return Xe.debug("Failed to extract public key from did:key",e),null}}function rt(e){return{kty:"OKP",crv:"Ed25519",x:p(e)}}function it(){return{resolve:async e=>{if(!tt(e))return null;const t=nt(e);if(!t)return null;const n=rt(t),r=e.replace("did:key:",""),i=qe(e);return{id:e,verificationMethod:[{id:`${e}#${i}`,type:"Ed25519VerificationKey2020",controller:e,publicKeyJwk:n,publicKeyMultibase:r}],authentication:[`${e}#${i}`],assertionMethod:[`${e}#${i}`]}}}}function ot(e){if(!tt(e))return null;const t=nt(e);if(!t)return null;const n=rt(t),r=e.replace("did:key:",""),i=qe(e);return{id:e,verificationMethod:[{id:`${e}#${i}`,type:"Ed25519VerificationKey2020",controller:e,publicKeyJwk:n,publicKeyMultibase:r}],authentication:[`${e}#${i}`],assertionMethod:[`${e}#${i}`]}}const st={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 at(e){const{session:t,delegation:n,serverIdentity:r,targetUrl:i}=e;if(!t.agentDid)throw new Error("Session must have agentDid for outbound delegation");if(!t.sessionId)throw new Error("Session must have sessionId for outbound delegation");if(!n.vcId)throw new Error("Delegation must have vcId for outbound delegation");const o=function(e){try{return new URL(e).hostname}catch{return Xe.warn("Failed to parse target URL, using as-is",{url:e}),e}}(i),s=function(e,t){const n=h(e),r=64===n.length?n.subarray(0,32):n;if(!tt(t))throw new Error(`Server DID must be did:key with Ed25519: ${t}`);const i=nt(t);if(!i)throw new Error(`Failed to extract public key from DID: ${t}`);return{kty:"OKP",crv:"Ed25519",x:p(i),d:p(r)}}(r.privateKey,r.did),a=await Oe({agentDid:r.did,userDid:t.agentDid,delegationId:n.id,delegationChain:n.vcId,scopes:["delegation:propagate"],privateKeyJwk:s,kid:r.kid,targetHostname:o});return Xe.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 ct{cryptoProvider;constructor(e){this.cryptoProvider=e}async verifyEd25519(e,t,n){try{return!0===await this.cryptoProvider.verify(e,t,n)}catch(e){return Xe.error("[CryptoService] Ed25519 verification error:",e),!1}}parseJWS(e){const t=e.split(".");if(3!==t.length)throw new Error("Invalid JWS format: expected header.payload.signature");const[n,r,i]=t;let 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(r)try{s=JSON.parse(d(r))}catch(e){throw new Error(`Invalid payload base64: ${e instanceof Error?e.message:String(e)}`)}try{a=u(i)}catch(e){throw new Error(`Invalid signature base64: ${e instanceof Error?e.message:String(e)}`)}return{header:o,payload:s,signatureBytes:a,signingInput:`${n}.${r}`}}async verifyJWS(e,t,n){try{if(!this.isValidEd25519JWK(t))return Xe.error("[CryptoService] Invalid Ed25519 JWK format"),!1;if(n?.expectedKid&&t.kid!==n.expectedKid)return Xe.error("[CryptoService] Key ID mismatch"),!1;let r;try{r=this.parseJWS(e)}catch(t){if(void 0===n?.detachedPayload)return Xe.error("[CryptoService] Invalid JWS format:",t),!1;{const n=e.split(".");if(3!==n.length||""!==n[1])return Xe.error("[CryptoService] Invalid JWS format:",t),!1;try{const e=n[0],t=n[2];r={header:JSON.parse(d(e)),payload:void 0,signatureBytes:u(t),signingInput:""}}catch{return Xe.error("[CryptoService] Invalid detached JWS format"),!1}}}const i=n?.alg||"EdDSA";if(r.header.alg!==i)return Xe.error(`[CryptoService] Unsupported algorithm: ${r.header.alg}, expected ${i}`),!1;let o,s;if(void 0!==n?.detachedPayload){const t=e.split(".")[0];let r;r=n.detachedPayload instanceof Uint8Array?p(n.detachedPayload):p((new TextEncoder).encode(n.detachedPayload)),o=(new TextEncoder).encode(`${t}.${r}`)}else{if(!r.signingInput)return Xe.error("[CryptoService] Missing signing input for compact JWS"),!1;o=(new TextEncoder).encode(r.signingInput)}try{s=this.jwkToBase64PublicKey(t)}catch(e){return Xe.error("[CryptoService] Failed to extract public key:",e),!1}return await this.verifyEd25519(o,r.signatureBytes,s)}catch(e){return Xe.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 f(t)}}const dt=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]),ut=12,lt=32;async function pt(e,t,n){const r={method:e.method,...e.params?{params:e.params}:{}},i=await n((new TextEncoder).encode((0,N.d)(r)));return void 0===t?{requestHash:i}:{requestHash:i,responseHash:await n((new TextEncoder).encode((0,N.d)(t.data)))}}class ft{identity;cryptoProvider;constructor(e,t){this.identity=e,this.cryptoProvider=t}async generateProof(e,t,n,r={}){const i=await this.generateCanonicalHashes(e,t),o={did:this.identity.did,kid:this.identity.kid,ts:Math.floor(Date.now()/1e3),nonce:n.nonce,audience:n.audience,sessionId:n.sessionId,requestHash:i.requestHash,...void 0!==i.responseHash?{responseHash:i.responseHash}:{},...r};return{jws:await this.generateJWS(o),meta:o}}async hashRequest(e){return(await this.generateCanonicalHashes(e)).requestHash}async generateCanonicalHashes(e,t){return pt(e,t,e=>this.cryptoProvider.hash(e))}async generateJWS(e){try{const t=this.formatPrivateKeyAsPEM(this.identity.privateKey),n=await async function(e){if("string"!=typeof e||0!==e.indexOf("-----BEGIN PRIVATE KEY-----"))throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return t=e,(0,ee.createPrivateKey)({key:te.Buffer.from(t.replace(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g,""),"base64"),type:"pkcs8",format:"der"});var t}(t),r={aud:e.audience,sub:e.did,iss:e.did,requestHash:e.requestHash,...void 0!==e.responseHash&&{responseHash:e.responseHash},ts:e.ts,nonce:e.nonce,sessionId:e.sessionId,...e.scopeId&&{scopeId:e.scopeId},...e.delegationRef&&{delegationRef:e.delegationRef},...e.clientDid&&{clientDid:e.clientDid},...e.outcome&&{outcome:e.outcome},...e.reason&&{reason:e.reason}},i=(0,N.d)(r),o=(new TextEncoder).encode(i);return await new ze(o).setProtectedHeader({alg:"EdDSA",kid:this.identity.kid}).sign(n)}catch(e){throw new Error(`Failed to generate JWS: ${e instanceof Error?e.message:"Unknown error"}`)}}formatPrivateKeyAsPEM(e){const t=h(e).subarray(0,lt),n=new Uint8Array(dt.length+t.length);n.set(dt),n.set(t,dt.length);const r=f(n);return"-----BEGIN PRIVATE KEY-----\n"+(r.match(/.{1,64}/g)?.join("\n")??r)+"\n-----END PRIVATE KEY-----"}async verifyProof(e,t,n){try{const r=await this.generateCanonicalHashes(t,n);if(e.meta.requestHash!==r.requestHash)return!1;if(void 0!==e.meta.responseHash&&(void 0===r.responseHash||e.meta.responseHash!==r.responseHash))return!1;const i=this.base64PublicKeyToJWK(this.identity.publicKey);return new ct(this.cryptoProvider).verifyJWS(e.jws,i,{expectedKid:this.identity.kid,alg:"EdDSA"})}catch{return!1}}base64PublicKeyToJWK(e){const t=h(e);if(t.length!==lt)throw new Error(`Invalid Ed25519 public key length: ${t.length}`);return{kty:"OKP",crv:"Ed25519",x:p(t),kid:this.identity.kid}}}async function ht(e,t,n,r,i,o={}){const s={data:t},a=new ft(n,i),c=await a.generateProof(e,s,r,o);return s.meta={proof:c},s}function mt(e,t){return{request:{method:e.method,...e.params?{params:e.params}:{}},response:t.data}}const gt="_kyaos";function yt(e){return e.startsWith(gt)}function vt(e,t){const n={};for(const[e,r]of Object.entries(t))yt(e)||(n[e]=r);return{method:e,params:n}}async function wt(e){const{identity:t,crypto:n,toolName:r,args:i,audience:o,sessionId:s}=e,a=new ft(t,n),c=vt(r,i),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 _t="holder_binding_failed";function bt(e){return null!==nt(e)}async function St(e){const{proof:t,subjectDid:n,request:r,response:i,expectedAudience:o,proofVerifier:s}=e,a=nt(n);if(!a)return{status:"not_applicable",reason:`Holder binding (phase 1) covers did:key subjects only; "${Le(n)??"unknown"}" is deferred to cnf-based binding`};if("object"!=typeof t?.meta||null===t.meta)return{status:"unbound",errorCode:_t,reason:"Malformed proof: missing meta"};if(t.meta.did!==n)return{status:"unbound",errorCode:_t,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:_t,reason:"Proof audience does not match this server",cause:"audience_mismatch"};const c=rt(a);c.kid=`${n}#${qe(n)}`;const d=await s.verifyProof(t,c,{request:r,...void 0!==i?{response:i}:{}});return d.valid?{status:"bound"}:{status:"unbound",errorCode:_t,reason:"Request proof is not bound to the delegation subject",...void 0!==d.errorCode?{cause:d.errorCode}:{}}}class kt{statusLists=new Map;indexCounters=new Map;async getStatusList(e){return this.statusLists.get(e)||null}async setStatusList(e,t){this.statusLists.set(e,t)}async allocateIndex(e){const t=this.indexCounters.get(e)||0,n=t;return this.indexCounters.set(e,t+1),n}getIndexCount(e){return this.indexCounters.get(e)||0}clear(){this.statusLists.clear(),this.indexCounters.clear()}getAllStatusListIds(){return Array.from(this.statusLists.keys())}}class It{nodes=new Map;async getNode(e){return this.nodes.get(e)||null}async setNode(e){this.nodes.set(e.id,e)}async getChildren(e){const t=this.nodes.get(e);return t?t.children.map(e=>this.nodes.get(e)).filter(e=>void 0!==e):[]}async getChain(e){const t=[];let n=e;for(;n;){const e=this.nodes.get(n);if(!e)break;t.unshift(e),n=e.parentId}return t}async getDescendants(e){const t=[],n=[e],r=new Set;for(;n.length>0;){const e=n.shift();if(r.has(e))continue;r.add(e);const i=this.nodes.get(e);if(i)for(const e of i.children)if(!r.has(e)){n.push(e);const r=this.nodes.get(e);r&&t.push(r)}}return t}async deleteNode(e){this.nodes.delete(e)}clear(){this.nodes.clear()}getAllNodeIds(){return Array.from(this.nodes.keys())}getStats(){const e=Array.from(this.nodes.values()),t=e.filter(e=>null===e.parentId).length,n=e.filter(e=>0===e.children.length).length;let r=0;for(const t of e){const e=this.getChainSync(t.id);r=Math.max(r,e.length-1)}return{totalNodes:e.length,rootNodes:t,leafNodes:n,maxDepth:r}}getChainSync(e){const t=[];let n=e;for(;n;){const e=this.nodes.get(n);if(!e)break;t.unshift(e),n=e.parentId}return t}}function zt(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 Dt(e){return e.startsWith("did:web:")}function Et(e){if(!Dt(e))return null;const t=e.slice(8);if(0===t.length)return null;const n=t.split(":"),r=decodeURIComponent(n[0]);return 0===r.length?null:{domain:r,path:n.slice(1).map(e=>decodeURIComponent(e))}}function $t(e){const t=Et(e);if(!t)return null;const{domain:n,path:r}=t;let i=`https://${n}`;return 0===r.length?i+="/.well-known/did.json":i+="/"+r.join("/")+"/did.json",i}class Tt{fetchProvider;cache;cacheTtl;constructor(e,t){this.fetchProvider=e,this.cache=new Map,this.cacheTtl=t?.cacheTtl??3e5}async resolve(e){if(!Dt(e))return null;const t=this.cache.get(e);if(t&&Date.now()<t.expiresAt)return t.document;const n=$t(e);if(!n)return Xe.warn(`[DidWebResolver] Invalid did:web format: ${e}`),null;try{const t=await this.fetchProvider.fetch(n);if(!t.ok)return Xe.warn(`[DidWebResolver] HTTP ${t.status} fetching ${n}`),null;let r;try{r=await t.json()}catch{return Xe.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(!zt(e))return!1}return!0}(r)?r.id!==e?(Xe.warn(`[DidWebResolver] DID Document id mismatch: expected ${e}, got ${r.id}`),null):(this.cache.set(e,{document:r,expiresAt:Date.now()+this.cacheTtl}),r):(Xe.warn(`[DidWebResolver] Invalid DID Document structure from ${n}`),null)}catch(t){return Xe.warn(`[DidWebResolver] Error resolving ${e}: ${t instanceof Error?t.message:"Unknown error"}`),null}}clearCache(){this.cache.clear()}clearCacheEntry(e){this.cache.delete(e)}}function At(e,t){return new Tt(e,t)}const xt=new Uint8Array([237,1]),Ot=["https://www.w3.org/ns/did/v1","https://w3id.org/security/suites/ed25519-2020/v1"];function Nt(e,t){if(!Dt(e.did))throw new Error(`buildDidWebDocument: identity.did must be a did:web DID (got "${e.did}")`);if(!e.kid.startsWith(`${e.did}#`))throw new Error(`buildDidWebDocument: identity.kid "${e.kid}" does not reference identity.did "${e.did}"`);const n=function(e){const t=h(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),r=rt(n),i=function(e){const t=new Uint8Array(xt.length+e.length);return t.set(xt),t.set(e,xt.length),`z${Re(t)}`}(n),o={id:e.kid,type:"Ed25519VerificationKey2020",controller:e.did,publicKeyJwk:r,publicKeyMultibase:i};return{"@context":t?.additionalContexts?.length?[...Ot,...t.additionalContexts]:[...Ot],id:e.did,verificationMethod:[o],authentication:[e.kid],assertionMethod:[e.kid]}}class Pt{tokens=new Map;ttl;constructor(e=6e5){this.ttl=e}async create(e,t,n){const r=new Uint8Array(16);globalThis.crypto.getRandomValues(r);const i=`rt_${Array.from(r).map(e=>e.toString(16).padStart(2,"0")).join("")}`,o=Date.now();return this.tokens.set(i,{agentDid:e,scopes:t,createdAt:o,expiresAt:o+this.ttl,metadata:n,fulfilled:!1}),i}async get(e){const t=this.tokens.get(e);return t?Date.now()>t.expiresAt?(this.tokens.delete(e),null):t.fulfilled?null:{agentDid:t.agentDid,scopes:t.scopes,createdAt:t.createdAt,expiresAt:t.expiresAt,metadata:t.metadata}:null}async fulfill(e){const t=this.tokens.get(e);t&&(t.fulfilled=!0)}clear(){this.tokens.clear()}}async function Ct(e,t,n){const r=Date.now();let i,o;if(n.debug&&Xe.debug(`[AuthHandshake] Verifying ${e} for scopes: ${t.join(", ")}`),n.reputationService&&void 0!==n.authorization.minReputationScore){const r=n.authorization.unknownAgentPolicy??"require-consent";try{i=await async function(e,t){const n=t.apiUrl.replace(/\/$/,""),r={"Content-Type":"application/json"};let i;if(t.apiKey&&(r["X-API-Key"]=t.apiKey),i="v2"===t.apiFormat?await fetch(`${n}/v1/reputation/${encodeURIComponent(e)}`,{method:"POST",headers:r,body:JSON.stringify({include_details:!1})}):await fetch(`${n}/api/v1/reputation/${encodeURIComponent(e)}`,{method:"GET",headers:r}),!i.ok){if(404===i.status)return{agentDid:e,score:null,totalInteractions:0,successRate:0,riskLevel:"unknown",updatedAt:Date.now()};throw new Error(`Reputation API error: ${i.status} ${i.statusText}`)}const o=await i.json(),s=o.score??0,a=(o.level??o.riskLevel??"unknown").toLowerCase(),c="low"===a||"medium"===a||"high"===a?a:"unknown";return{agentDid:o.agent_did??o.agentDid??e,score:s,totalInteractions:o.totalInteractions??0,successRate:o.successRate??0,riskLevel:c,updatedAt:o.calculatedAt?new Date(o.calculatedAt).getTime():o.updatedAt??Date.now()}}(e,n.reputationService)}catch(t){Xe.error("[AuthHandshake] Reputation service unreachable, treating agent as unknown:",t),i={agentDid:e,score:null,totalInteractions:0,successRate:0,riskLevel:"unknown",updatedAt:Date.now()}}if(n.debug&&Xe.debug(`[AuthHandshake] Reputation score: ${i.score}`),null===i.score){if("deny"===r)return{authorized:!1,authError:await Rt(e,t,n,"Unknown agent denied by policy"),reputation:i,reason:"Unknown agent — policy: deny"};if("require-consent"===r)return{authorized:!1,authError:await Rt(e,t,n,"Unknown agent requires consent"),reputation:i,reason:"Unknown agent — policy: require-consent"};n.debug&&Xe.debug("[AuthHandshake] Unknown agent allowed by policy, skipping reputation gate")}if(null!==i.score&&i.score<n.authorization.minReputationScore)return n.debug&&Xe.debug(`[AuthHandshake] Reputation ${i.score} < ${n.authorization.minReputationScore}, requiring authorization`),{authorized:!1,authError:await Rt(e,t,n,"Agent reputation score below threshold"),reputation:i,reason:"Low reputation score"}}try{o=await n.delegationVerifier.verify(e,t)}catch(r){Xe.error("[AuthHandshake] Delegation verification failed:",r);const i=`Delegation verification error: ${r instanceof Error?r.message:"Unknown error"}`;return{authorized:!1,authError:await Rt(e,t,n,i),reason:i}}return o.valid&&o.delegation?(n.debug&&Xe.debug(`[AuthHandshake] Delegation valid, authorized (${Date.now()-r}ms)`),{authorized:!0,delegation:o.delegation,credential:o.credential,reputation:i,reason:"Valid delegation found"}):(n.debug&&Xe.debug(`[AuthHandshake] No delegation found, returning needs_authorization (${Date.now()-r}ms)`),{authorized:!1,authError:await Rt(e,t,n,o.reason??"No valid delegation found"),reputation:i,reason:o.reason??"No delegation"})}async function Rt(e,t,n,r){const i=await n.resumeTokenStore.create(e,t,{requestedAt:Date.now()}),o=Date.now()+(n.authorization.resumeTokenTtl??6e5),s=new URL(n.authorization.authorizationUrl);s.searchParams.set("agent_did",e),s.searchParams.set("scopes",t.join(",")),s.searchParams.set("resume_token",i);const a={title:"Authorization Required",hint:["link","qr"],authorizationCode:i.substring(0,8).toUpperCase(),qrUrl:`https://api.qrserver.com/v1/create-qr-code/?data=${encodeURIComponent(s.toString())}`};return E({message:r,authorizationUrl:s.toString(),resumeToken:i,expiresAt:o,scopes:t,display:a})}function jt(e){const t=["write","delete","admin","payment","transfer","execute","modify"];return e.some(e=>t.some(t=>e.toLowerCase().includes(t)))}const Zt={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 Mt extends Error{code;details;constructor(e,t,n){super(t),this.code=e,this.details=n,this.name="ProofVerificationError"}}function Lt(e,t,n){return new Mt(e,t,n)}const Ut=120,Kt=30,Jt=600;class Ht{cryptoService;clock;nonceCache;fetch;timestampSkewSeconds;nonceTtlSeconds;cryptoProvider;constructor(e){this.cryptoService=new ct(e.cryptoProvider),this.cryptoProvider=e.cryptoProvider,this.clock=e.clockProvider,this.nonceCache=e.nonceCacheProvider,this.fetch=e.fetchProvider,this.timestampSkewSeconds=e.timestampSkewSeconds??Ut,this.nonceTtlSeconds=e.nonceTtlSeconds??300}setTimestampSkew(e){"number"==typeof e&&Number.isFinite(e)&&(this.timestampSkewSeconds=Math.max(Kt,Math.min(Jt,Math.floor(e))))}getTimestampSkew(){return this.timestampSkewSeconds}async verifyProof(e,t,n){try{const r=this.buildCanonicalPayload(e.meta),i=(new TextEncoder).encode(r);return await this.runVerificationPipeline(e,t,i,n)}catch(e){return this.handleVerificationError(e)}}async verifyProofDetached(e,t,n){try{const r=t instanceof Uint8Array?t:(new TextEncoder).encode(t);return await this.runVerificationPipeline(e,n,r)}catch(e){return this.handleVerificationError(e)}}async runVerificationPipeline(e,t,n,r){const i=await this.validateProofStructure(e);if(!i.valid)return i;const o=i.proof,s=await this.validateNonce(o.meta.nonce,o.meta.did);if(!s.valid)return s;const a=await this.validateTimestamp(o.meta.ts);if(!a.valid)return a;const c=await this.verifySignature(o.jws,t,n,o.meta.kid);if(!c.valid)return c;if(void 0!==r){const e=await this.validateContentBinding(o,r);if(!e.valid)return e}return await this.addNonceToCache(o.meta.nonce,o.meta.did),{valid:!0}}async validateContentBinding(e,t){const{requestHash:n,responseHash:r}=await pt(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:Zt.CONTENT_BINDING_MISMATCH};const i=void 0!==e.meta.responseHash;return i!==(void 0!==t.response)?{valid:!1,reason:i?"Proof binds a response (responseHash present) but no response was supplied to verify against — pass expected.response":"A response was supplied but the proof binds none — content/proof mismatch",errorCode:Zt.CONTENT_BINDING_MISMATCH}:i&&e.meta.responseHash!==r?{valid:!1,reason:"Response hash mismatch: received content differs from what the server signed (possible substitution / MITM)",errorCode:Zt.CONTENT_BINDING_MISMATCH}:{valid:!0}}handleVerificationError(e){return{valid:!1,reason:"Proof verification error",errorCode:Zt.VERIFICATION_ERROR,error:e instanceof Error?e:new Error(String(e)),details:{errorMessage:e instanceof Error?e.message:String(e)}}}async validateProofStructure(e){const t=O(e);return t.success?{valid:!0,proof:t.data}:{valid:!1,reason:"Invalid proof structure",errorCode:Zt.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:Zt.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:Zt.TIMESTAMP_SKEW_EXCEEDED,details:{timestamp:e,timestampMs:t,skewSeconds:this.timestampSkewSeconds,currentTime:this.clock.now()}}}async verifySignature(e,t,n,r){return await this.cryptoService.verifyJWS(e,t,{detachedPayload:n,expectedKid:r,alg:"EdDSA"})?{valid:!0}:{valid:!1,reason:"Invalid JWS signature",errorCode:Zt.INVALID_JWS_SIGNATURE,details:{jwsLength:e.length,expectedKid:r,actualKid:t.kid}}}async addNonceToCache(e,t){await this.nonceCache.add(e,this.nonceTtlSeconds,t)}async fetchPublicKeyFromDID(e,t){try{const n=await this.fetch.resolveDID(e);if(!n)throw new Mt(Zt.DID_DOCUMENT_NOT_FOUND,`DID document not found: ${e}`,{did:e});const r=n;if(!r.verificationMethod||0===r.verificationMethod.length)throw new Mt(Zt.VERIFICATION_METHOD_NOT_FOUND,`No verification methods found in DID document: ${e}`,{did:e});let i;if(t){const n=t.startsWith("#")?t:`#${t}`;if(i=r.verificationMethod.find(t=>t.id===n||t.id===`${e}${n}`),!i)throw new Mt(Zt.VERIFICATION_METHOD_NOT_FOUND,`Verification method not found for kid: ${t}`,{did:e,kid:t,availableKids:r.verificationMethod.map(e=>e.id)})}else i=r.verificationMethod[0];if(!i?.publicKeyJwk)throw new Mt(Zt.PUBLIC_KEY_NOT_FOUND,"Public key JWK not found in verification method",{did:e,kid:t,verificationMethodId:i?.id});const o=i.publicKeyJwk;if("OKP"!==o.kty||"Ed25519"!==o.crv||!o.x)throw new Mt(Zt.INVALID_JWK_FORMAT,`Unsupported key type or curve: kty=${o.kty}, crv=${o.crv}`,{did:e,kid:t,jwk:{kty:o.kty,crv:o.crv}});const s=o;return!s.kid&&i.id&&(s.kid=i.id),s}catch(n){if(n instanceof Mt)throw n;throw Xe.error("[ProofVerifier] Failed to fetch public key from DID",{error:n}),new Mt(Zt.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){const t={aud:e.audience,sub:e.did,iss:e.did,requestHash:e.requestHash,...void 0!==e.responseHash&&{responseHash:e.responseHash},ts:e.ts,nonce:e.nonce,sessionId:e.sessionId,...e.scopeId&&{scopeId:e.scopeId},...e.delegationRef&&{delegationRef:e.delegationRef},...e.clientDid&&{clientDid:e.clientDid},...e.outcome&&{outcome:e.outcome},...e.reason&&{reason:e.reason}};return(0,N.d)(t)}}function Ft(e,t="strict"){const n=Object.keys(e).filter(e=>"proof"!==e);return"strict"===t&&n.length>0?{valid:!1,reason:`_meta contains keys other than 'proof' in strict mode: ${n.join(", ")}`,extraKeys:n}:{valid:!0}}function Vt(e,t="strict"){const n=e.proof;if(!n)return{success:!1,reason:"_meta does not contain proof",errorCode:Zt.MISSING_REQUIRED_FIELD};const r=Ft(e,t);if(!r.valid)return{success:!1,reason:r.reason,errorCode:Zt.META_POLICY_VIOLATION};const i=O(n);return i.success?{success:!0,proof:i.data}:{success:!1,reason:i.error?.message??"Invalid proof structure",errorCode:Zt.INVALID_PROOF_STRUCTURE}}class Wt{}class Bt{}class qt{}class Yt{}class Gt{}class Xt{}class Qt extends Yt{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 en extends Gt{nonces=new Map;async has(e,t){const n=t?`nonce:${t}:${e}`:`nonce:${e}`,r=this.nonces.get(n);return!(!r||Date.now()>r&&(this.nonces.delete(n),1))}async add(e,t,n){const r=n?`nonce:${n}:${e}`:`nonce:${e}`,i=Date.now()+1e3*t;this.nonces.set(r,i)}async cleanup(){const e=Date.now();for(const[t,n]of this.nonces)e>n&&this.nonces.delete(t)}async destroy(){this.nonces.clear()}}class tn extends Xt{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}#${qe(t)}`,privateKey:e.privateKey,publicKey:e.publicKey,createdAt:(new Date).toISOString(),type:"development"}}generateDIDFromPublicKey(e){return Be(e)}}class nn{config;cryptoProvider;sessions=new Map;sessionInsertionOrder=[];maxSessions;constructor(e,t={}){this.cryptoProvider=e,this.maxSessions=t.maxSessions??1e4,this.config={timestampSkewSeconds:t.timestampSkewSeconds??120,sessionTtlMinutes:t.sessionTtlMinutes??30,nonceCache:t.nonceCache??new en,metaPolicy:t.metaPolicy??"strict",...void 0!==t.absoluteSessionLifetime&&{absoluteSessionLifetime:t.absoluteSessionLifetime},...void 0!==t.serverDid&&{serverDid:t.serverDid}},this.config.nonceCache instanceof en&&Xe.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.handshake_failed,message:"Nonce already used (replay attack prevention)",remediation:"Generate a new unique nonce for each request"}};const r=e.agentDid?z:D,i=Math.ceil(r/1e3);await this.config.nonceCache.add(e.nonce,i,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 this.evictIfNeeded(),this.sessions.set(o,c),this.sessionInsertionOrder.push(o),{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=this.sessions.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?(this.sessions.delete(e),null):(t.lastActivity=n,this.sessions.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,"")}evictIfNeeded(){for(;this.sessions.size>=this.maxSessions&&this.sessionInsertionOrder.length>0;){const e=this.sessionInsertionOrder.shift();e&&this.sessions.delete(e)}}async cleanup(){const e=Math.floor(Date.now()/1e3);for(const[t,n]of this.sessions.entries()){let r=e-n.lastActivity>60*n.ttlMinutes;r||void 0===this.config.absoluteSessionLifetime||(r=e-n.createdAt>60*this.config.absoluteSessionLifetime),r&&this.sessions.delete(t)}this.sessionInsertionOrder=this.sessionInsertionOrder.filter(e=>this.sessions.has(e)),await this.config.nonceCache.cleanup()}getStats(){return{activeSessions:this.sessions.size,config:{timestampSkewSeconds:this.config.timestampSkewSeconds,sessionTtlMinutes:this.config.sessionTtlMinutes,absoluteSessionLifetime:this.config.absoluteSessionLifetime,cacheType:this.config.nonceCache.constructor.name}}}clearSessions(){this.sessions.clear(),this.sessionInsertionOrder=[]}}function rn(e){return{nonce:nn.generateNonce(),audience:e,timestamp:Math.floor(Date.now()/1e3)}}function on(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)}const sn=Buffer.from("302e020100300506032b657004220420","hex"),an=Buffer.from("302a300506032b6570032100","hex");class cn extends Wt{async sign(e,t){const n=Buffer.from(t,"base64"),r=64===n.length?n.subarray(0,32):n,i=(0,ee.createPrivateKey)({key:Buffer.concat([sn,r]),format:"der",type:"pkcs8"});return new Uint8Array((0,ee.sign)(null,Buffer.from(e),i))}async verify(e,t,n){try{const r=(0,ee.createPublicKey)({key:Buffer.concat([an,Buffer.from(n,"base64")]),format:"der",type:"spki"});return(0,ee.verify)(null,Buffer.from(e),r,Buffer.from(t))}catch{return!1}}async generateKeyPair(){const{publicKey:e,privateKey:t}=(0,ee.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,ee.createHash)("sha256").update(Buffer.from(e)).digest("hex")}`}async randomBytes(e){return new Uint8Array((0,ee.randomBytes)(e))}}class dn extends Bt{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 un extends qt{didKeyResolver=it();didWebResolver;allowPrivateNetworkHosts;constructor(e){super(),this.allowPrivateNetworkHosts=e?.allowPrivateNetworkHosts??!1}async resolveDID(e){return e.startsWith("did:key:")?this.didKeyResolver.resolve(e):Dt(e)?this.isBlockedTarget($t(e))?null:(this.didWebResolver||(this.didWebResolver=At(this)),this.didWebResolver.resolve(e)):null}async fetchStatusList(e){if(this.isBlockedTarget(e))return null;try{const t=await this.fetch(e);if(!t.ok)return null;const n=await t.json();return function(e){if("object"!=typeof e||null===e)return!1;const t=e;if(!Array.isArray(t.type)||!t.type.includes("StatusList2021Credential"))return!1;const n=t.credentialSubject;if("object"!=typeof n||null===n)return!1;const r=n;return"StatusList2021"===r.type&&"string"==typeof r.encodedList}(n)?n:null}catch{return null}}async fetchDelegationChain(e){return[]}async fetch(e,t){if("function"!=typeof globalThis.fetch)throw new Error("Global fetch is not available in this runtime");return globalThis.fetch(e,t)}isBlockedTarget(e){if(this.allowPrivateNetworkHosts||null===e)return!1;let t;try{t=new URL(e).hostname}catch{return!1}return function(e){let t=e.toLowerCase();if(t.startsWith("[")&&t.endsWith("]")&&(t=t.slice(1,-1)),t.includes(":"))return"::1"===t||"::"===t||t.startsWith("fe80:")||t.startsWith("fc")||t.startsWith("fd");const n=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(t);if(!n)return!1;const r=Number(n[1]),i=Number(n[2]);return 127===r||10===r||0===r||169===r&&254===i||192===r&&168===i||172===r&&i>=16&&i<=31}(t)}}class ln extends qt{async resolveDID(e){return null}async fetchStatusList(e){return null}async fetchDelegationChain(e){return[]}async fetch(e,t){throw new Error("fetch unavailable")}}function pn(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 fn{}class hn extends fn{records=[];events=[];loggedSessions=new Set;async logAuditRecord(e){const t=e.session.sessionId;this.loggedSessions.has(t)||(this.loggedSessions.add(t),this.records.push(pn(e)))}async logEvent(e){this.events.push(e)}}class mn extends fn{async logAuditRecord(e){}async logEvent(e){}}const gn=256,yn=256,vn=/\([^()]*[+*?{][^()]*\)\s*[+*{]/;function wn(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>gn||n.length>yn)return!1;if(vn.test(e))return!1;try{return new RegExp(`^(?:${e})$`).test(n)}catch{return!1}default:return!1}}function _n(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(wn(n.resource,n.matcher,e))return{satisfied:!0,usedNonExactMatcher:"exact"!==n.matcher};return{satisfied:!1,usedNonExactMatcher:!1}}function bn(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 Sn(e,t){const n=bn(e),r=bn(t),i=t.credentialSubject.delegation,o=e=>`${e.matcher}\0${e.resource}`,s=new Set((e.credentialSubject.delegation.constraints.crisp?.scopes??[]).map(o)),a=(i.constraints.crisp?.scopes??[]).filter(e=>!s.has(o(e)));if(a.length>0)return{valid:!1,reason:`Delegation ${i.id} introduces crisp scope matcher(s) absent from parent ${e.credentialSubject.delegation.id}: ${a.map(e=>`${e.matcher}:${e.resource}`).join(", ")}`};if(0===n.length)return{valid:!0};if(0===r.length)return{valid:!1,reason:`Delegation ${i.id} omits scopes required to prove attenuation from parent ${e.credentialSubject.delegation.id}`};const c=new Set(n),d=r.filter(e=>!c.has(e));return d.length>0?{valid:!1,reason:`Delegation ${i.id} widens scopes beyond parent ${e.credentialSubject.delegation.id}: ${d.join(", ")}`}:{valid:!0}}const kn=["delete","drop","destroy","remove","terminate","transfer","payment","admin","execute","modify","write","rotate","revoke"],In=["read","get","list","describe","search","query"];class zn{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=Dn(e.toolName),r=function(e){const t=Dn(e);return t.includes("prod")||t.includes("production")}(e.namespace);let i;return i=n.some(e=>kn.includes(e))?{reversibility:"irreversible",blastRadius:r?"environment":"resource",severity:r?"catastrophic":"high"}:n.some(e=>In.includes(e))?{reversibility:"reversible",blastRadius:"record",severity:"low"}:{reversibility:"unknown",blastRadius:"unknown",severity:"unknown"},{...i,...En(t)}}}function Dn(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 En(e){if(!e)return{};const t={};for(const[n,r]of Object.entries(e))void 0!==r&&(t[n]=r);return t}class $n{cfg;constructor(e={}){this.cfg=e}async evaluate(e){const{severity:t,reversibility:n,scopeMatched:r,humanApprovals:i}=e.context;if(!r)return{decision:"deny",reason:"scope_not_matched"};if("unknown"===t||"unknown"===n)return{decision:"deny",reason:"unclassified_high_risk"};if("irreversible"===n||"catastrophic"===t||"high"===t){const e=this.cfg.stepUpQuorum??1;return i.length>=e?{decision:"allow"}:{decision:"step_up",quorum:{n:e,approvers:this.cfg.stepUpApprovers??[]},reason:"destructive_action_requires_approval"}}return{decision:"allow"}}}async function Tn(e,t,n,r){if(n.n<=0)return{satisfied:!1,reason:"invalid_quorum:n<=0"};const i=new Set;for(const o of e)"approve"===o.decision&&o.requestHash===t&&(n.approvers.length>0&&!n.approvers.includes(o.approverDid)||await r(o)&&i.add(o.approverDid));return i.size>=n.n?{satisfied:!0}:{satisfied:!1,reason:`quorum_not_met:${i.size}/${n.n}`}}function An(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}:{}}}}const xn=["handshake","identity","reputation"];function On(e,t=256){const n="string"==typeof e?e:String(e);let r="";for(const e of n){const t=e.codePointAt(0)??0;r+=t<=31||t>=127&&t<=159?"�":e}return r.length>t?`${r.slice(0,t)}…`:r}function Nn(e,t){const n={did:e.identity.did,kid:e.identity.kid,privateKey:e.identity.privateKey,publicKey:e.identity.publicKey},r=e.nonceCache??new en,i=new nn(t,{...e.session,serverDid:n.did,nonceCache:r}),o=new ft(n,t),s=e.delegation,c=e.auditLog??new mn,d=s?.holderBinding??"off",l="off"===d?void 0:new Ht({cryptoProvider:t,clockProvider:new dn,nonceCacheProvider:r,fetchProvider:s?.fetchProvider??("function"==typeof globalThis.fetch?new un:new ln)}),h=new Map;let m;const g={name:"_kyaos",description:"KYA-OS protocol — identity verification, session handshake, and server metadata",inputSchema:{type:"object",properties:{action:{type:"string",enum:[...xn],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"]}};async function y(e){if(!on(e))return{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 t=await i.validateHandshake(e);return t.success&&t.session&&(h.set(t.session.sessionId,t.session.nonce),m=t.session.sessionId),{content:[{type:"text",text:JSON.stringify({success:t.success,...t.session&&{sessionId:t.session.sessionId,serverDid:n.did,serverKid:n.kid},...t.error&&{error:t.error}})}],...t.error&&{isError:!0}}}async function w(){if(m&&await i.getSession(m))return m;if(!e.autoSession)return;const r=p(await t.randomBytes(16)),o=Math.floor(Date.now()/1e3),s=await i.validateHandshake({nonce:r,audience:n.did,timestamp:o});return s.success&&s.session?(m=s.session.sessionId,h.set(s.session.sessionId,s.session.nonce),m):void 0}async function _(e,t,n,r,s,a="denied",c,d){try{const u=r??await w();if(!u)return e;const l=await i.getSession(u);if(!l)return e;let p;if(void 0!==c)p=c;else{p={};for(const[e,t]of Object.entries(n))"_kyaos_delegation"!==e&&(p[e]=t)}const f={method:t,params:p},h=void 0!==d?{data:d}:void 0,m=await o.generateProof(f,h,l,{outcome:a,reason:On(s)});e._meta={...e._meta??{},proof:m}}catch(e){Xe.error("[kya-os] Outcome proof generation failed",{tool:t,error:e instanceof Error?e.message:String(e)})}return e}const b=new zn,S=new $n;return{identity:e.identity,sessionManager:i,proofGenerator:o,kyaOsTool:g,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"]}},handleKyaOs:async function(t){const r="string"==typeof t.action?t.action:void 0;switch(r){case"handshake":return y(t);case"identity":return async function(){return{content:[{type:"text",text:JSON.stringify({did:n.did,kid:n.kid,name:e.identity.agentName??n.did,capabilities:["handshake","signing","verification"],protocolVersion:"1.0.0",clockSkewSeconds:i.getStats().config.timestampSkewSeconds})}]}}();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: "${r??"(missing)"}". Valid actions: ${xn.join(", ")}`}})}],isError:!0}}},handleHandshake:y,wrapWithProof:function(e,t){return async(r,s,a)=>{const d=await t(r,s,a);if(d.isError)return d;const u=s??await w();if(!u)return d;const l=await i.getSession(u);if(!l)return d;try{const t={method:e,params:r},i={data:d.content},s=await o.generateProof(t,i,l,{scopeId:a?.scopeId});d._meta={proof:s};try{await c.logAuditRecord({identity:{did:n.did,kid:n.kid},session:{sessionId:l.sessionId,audience:l.audience},requestHash:s.meta.requestHash,responseHash:s.meta.responseHash,verified:"yes",scopeId:s.meta.scopeId})}catch(t){Xe.error("[kya-os] Audit log failed",{tool:e,error:t instanceof Error?t.message:String(t)})}}catch(t){Xe.error("[kya-os] Proof generation failed",{tool:e,error:t instanceof Error?t.message:String(t)}),d._meta={proofError:"Proof generation failed — response is unproven"}}return d}},wrapWithDelegation:function(e,r,i){const o=it(),c=s?.fetchProvider??("function"==typeof globalThis.fetch?new un:void 0),p=c?At(c):void 0,h=new K({didResolver:{async resolve(e){const t=s?.didResolver;if(t){const n=await t.resolve(e);if(n)return n}return e.startsWith("did:key:")?o.resolve(e):e.startsWith("did:web:")?p?.resolve(e)??null:null}},signatureVerifier:async(e,n)=>{const r=e.proof;if(!r)return{valid:!1,reason:"Missing proof"};const i=r.proofValue;if(!i)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=P(s),c=(new TextEncoder).encode(a),d=u(i),l=n;if(!l.x)return{valid:!1,reason:"No x field in publicKeyJwk"};const p=f(u(l.x)),h=await t.verify(c,d,p);return{valid:h,reason:h?void 0:"Signature verification failed"}},statusListResolver:s?.statusListResolver}),m=(e,t)=>({content:[{type:"text",text:JSON.stringify({error:e,reason:On(t)})}],isError:!0});return async(o,c)=>{const u=o._kyaos_delegation;if(null==u){const n=await t.randomBytes(16),i=Array.from(n).map(e=>e.toString(16).padStart(2,"0")).join(""),s=[i.slice(0,8),i.slice(8,12),i.slice(12,16),i.slice(16,20),i.slice(20)].join("-"),a=Math.floor(Date.now()/1e3)+300,d=E({message:`Tool "${e}" requires delegation with scope: ${r.scopeId}`,authorizationUrl:r.consentUrl,resumeToken:s,expiresAt:a,scopes:[r.scopeId]}),u=[{type:"text",text:JSON.stringify(d)}];let l=u;if(r.formatChallenge)try{l=r.formatChallenge(d)}catch(t){Xe.error("[kya-os] formatChallenge threw; using the default challenge",{tool:e,error:t instanceof Error?t.message:String(t)}),l=u}return _({content:l},e,o,c,d.message,"needs_authorization",void 0,l)}let p,f=!1;if("string"==typeof u){const t=Z(u);if(!t||!t.payload.vc)return _(m(a.delegation_invalid,"Invalid VC-JWT format"),e,o,c,"Invalid VC-JWT format");p=t.payload.vc,p.proof||(p={...p,proof:{type:"JwtProof2020",jwt:u}}),f=!0}else p=u;const g=await(async()=>{try{return await(t=p,r={skipSignature:f},async function(e,t,n){const r=e?.credentialSubject?.delegation;if(!r||"object"!=typeof r||!r.constraints||"object"!=typeof r.constraints)return{valid:!1,reason:"Malformed delegation credential: missing credentialSubject.delegation or its constraints"};const i=v(e);let o=[e];if(i.parentId){if(!t.resolveDelegationChain)return{valid:!1,reason:`Delegation ${i.id} references parent ${i.parentId} but no resolveDelegationChain handler is configured`};let n;try{n=await t.resolveDelegationChain(e)}catch(e){return{valid:!1,reason:`Failed to resolve delegation chain: ${e instanceof Error?e.message:"Unknown error"}`}}if(0===n.length)return{valid:!1,reason:`Delegation ${i.id} references parent ${i.parentId} but the resolved chain is empty`};const r=n.findIndex(e=>e.credentialSubject.delegation.id===i.id);if(-1!==r&&r!==n.length-1)return{valid:!1,reason:`Resolved delegation chain for ${i.id} must end with the leaf credential`};o=-1===r?[...n,e]:n}const s=new Set;let a,c;for(const e of o){const r=v(e);if(s.has(r.id))return{valid:!1,reason:`Delegation chain contains a circular reference at ${r.id}`};if(s.add(r.id),e.credentialStatus&&!t.statusListConfigured)return{valid:!1,reason:`Delegation ${r.id} has credentialStatus but no statusListResolver is configured`};const i=await t.verifier.verifyDelegationCredential(e,{...n?.skipSignature?{skipSignature:!0}:{}});if(!i.valid)return{valid:!1,reason:`Delegation ${r.id} invalid: ${i.reason}`};if(!X(r,t.serverDid))return{valid:!1,reason:`Delegation ${r.id} audience does not include server DID ${t.serverDid}`};if(r.parentId&&!r.constraints.audience)return{valid:!1,reason:`Delegation ${r.id} is a re-delegation (parentId: ${r.parentId}) but has no audience constraint. Re-delegations MUST include an audience constraint (KYA-OS §11.6)`};if(!a||!c){if(r.parentId)return{valid:!1,reason:`Resolved delegation chain is incomplete: root delegation ${r.id} still references parent ${r.parentId}`};a=r,c=e;continue}if(r.parentId!==a.id)return{valid:!1,reason:`Delegation ${r.id} references parent ${r.parentId} but expected ${a.id}`};if(r.issuerDid!==a.subjectDid)return{valid:!1,reason:`Delegation ${r.id} issued by ${r.issuerDid} but parent subject is ${a.subjectDid}`};const o=Sn(c,e);if(!o.valid)return o;a=r,c=e}const d=v(o[o.length-1]);if(d.id!==i.id)return{valid:!1,reason:`Resolved delegation chain ended at ${d.id} instead of leaf ${i.id}`};if(t.revocationChecker){const e=await t.revocationChecker.isRevoked(i.id);if(e.revoked)return{valid:!1,reason:e.revokedAncestor?`Delegation ${i.id} is revoked via ancestor ${e.revokedAncestor}`:`Delegation ${i.id} is revoked${e.reason?`: ${e.reason}`:""}`}}return{valid:!0}}(t,{serverDid:n.did,verifier:h,resolveDelegationChain:s?.resolveDelegationChain,statusListConfigured:!!s?.statusListResolver,revocationChecker:s?.revocationChecker},r))}catch(t){return Xe.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"}}var t,r})();if(!g.valid){const t=g.reason??"Unknown delegation validation error";return Xe.warn(`[kya-os] Delegation verification failed for "${e}": ${On(t)}`),_(m(a.delegation_invalid,t),e,o,c,t)}if("off"!==d&&l){const t=p.credentialSubject?.id;if(t&&bt(t)){const r=o._kyaos_proof;if(void 0===r){const t="Holder-of-key proof (_kyaos_proof) is required for this delegation subject";if(Xe.warn(`[kya-os] Holder binding: "${e}" called without _kyaos_proof`),"enforce"===d)return _(m(a.holder_binding_failed,t),e,o,c,t)}else{let i=r;if("string"==typeof r)try{i=JSON.parse(r)}catch{i={}}const s=await St({proof:i,subjectDid:t,request:vt(e,o),expectedAudience:n.did,proofVerifier:l});if("bound"!==s.status){const t=s.reason??"Holder-of-key proof did not bind the delegation subject";if(Xe.warn(`[kya-os] Holder binding ${s.status} for "${e}": ${On(t)}`),"enforce"===d)return _(m(a.holder_binding_failed,t),e,o,c,t)}}}else t&&Xe.warn(`[kya-os] Holder binding: subject "${t}" is not did:key; deferring to cnf binding (phase 2)`)}const y=_n(r.scopeId,p);if(y.usedNonExactMatcher&&Xe.warn(`[kya-os] Scope "${r.scopeId}" for "${e}" granted via a non-exact (prefix/regex) matcher. Verify this is intended — non-exact matchers widen authority.`),!y.satisfied){const t=`Required scope "${r.scopeId}" not in delegation scopes`;return Xe.warn(`[kya-os] Delegation missing required scope "${r.scopeId}" for "${e}"`),_(m(a.insufficient_scope,t),e,o,c,t)}const w={};for(const[e,t]of Object.entries(o))yt(e)||(w[e]=t);return Xe.debug(`[kya-os] Delegation verified for "${e}", scope "${r.scopeId}"`),i(w,c,{scopeId:r.scopeId})}},withPolicyGate:function(e,t,n={}){const r=n.engine??S,i=n.classifier??b,s=n.approvalsArgKey??"_kyaos_approvals",c=n.isValidApprovalSignature??(async()=>!1);return async(d,u)=>{const l={};for(const[e,t]of Object.entries(d))yt(e)||e===s||(l[e]=t);const p=n.resolveNamespace?.(d)??e,f=i.classify({toolName:e,namespace:p}),h=function(e){if(!e||"object"!=typeof e)return{agentDid:"unknown",delegatedScopes:[]};try{const t=e,n=t.credentialSubject,r=n?.delegation?.subjectDid??n?.id??"unknown",i=n?.delegation?.controller;let o=[];try{o=bn(t)}catch{o=[]}return{agentDid:r,...i?{responsibleParty:i}:{},delegatedScopes:o}}catch{return{agentDid:"unknown",delegatedScopes:[]}}}(d._kyaos_delegation),m=An({principal:{agentDid:h.agentDid,...h.responsibleParty?{responsibleParty:h.responsibleParty}:{}},action:{toolName:e},resource:{namespace:p},delegatedScopes:h.delegatedScopes,scopeMatched:n.scopeMatched??!1,risk:f}),g=await r.evaluate(m);if("allow"===g.decision)return t(l,u);if("deny"===g.decision)return _({content:[{type:"text",text:JSON.stringify({error:a.policy_denied,reason:On(g.reason)})}],isError:!0},e,d,u,g.reason,"denied",l);const y=await o.hashRequest({method:e,params:l}),v=Array.isArray(d[s])?d[s]:[];if((await Tn(v,y,g.quorum,c)).satisfied)return t(l,u);const w=T({message:`Tool "${e}" requires ${g.quorum.n}-of-N approval before it may proceed (${On(g.reason)}).`,resumeToken:`step_up:${y}`,expiresAt:Math.floor(Date.now()/1e3)+300,requestHash:y,quorum:g.quorum});return _({content:[{type:"text",text:JSON.stringify(w)}],isError:!0},e,d,u,g.reason,"step_up_required",l)}}}}function Pn(e,t,n){function r(n,r){if(n._zod||Object.defineProperty(n,"_zod",{value:{def:r,constr:s,traits:new Set},enumerable:!1}),n._zod.traits.has(e))return;n._zod.traits.add(e),t(n,r);const i=s.prototype,o=Object.keys(i);for(let e=0;e<o.length;e++){const t=o[e];t in n||(n[t]=i[t].bind(n))}}const i=n?.Parent??Object;class o extends i{}function s(e){var t;const i=n?.Parent?new o:this;r(i,e),(t=i._zod).deferred??(t.deferred=[]);for(const e of i._zod.deferred)e();return i}return Object.defineProperty(o,"name",{value:e}),Object.defineProperty(s,"init",{value:r}),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 Cn extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class Rn extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}}const jn={};function Zn(e){return e&&Object.assign(jn,e),jn}function Mn(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 Ln(e,t="|"){return e.map(e=>sr(e)).join(t)}function Un(e,t){return"bigint"==typeof t?t.toString():t}function Kn(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Jn(e){return null==e}function Hn(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}const Fn=Symbol("evaluating");function Vn(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==Fn)return void 0===r&&(r=Fn,r=n()),r},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function Wn(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Bn(...e){const t={};for(const n of e){const e=Object.getOwnPropertyDescriptors(n);Object.assign(t,e)}return Object.defineProperties({},t)}function qn(e){return JSON.stringify(e)}const Yn="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Gn(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}const Xn=Kn(()=>{if("undefined"!=typeof navigator&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function Qn(e){if(!1===Gn(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!==Gn(n)&&!1!==Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")}function er(e){return Qn(e)?{...e}:Array.isArray(e)?[...e]:e}const tr=new Set(["string","number","symbol"]),nr=new Set(["string","number","bigint","boolean","symbol","undefined"]);function rr(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ir(e,t,n){const r=new e._zod.constr(t??e._zod.def);return t&&!n?.parent||(r._zod.parent=e),r}function or(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 sr(e){return"bigint"==typeof e?e.toString()+"n":"string"==typeof e?`"${e}"`:`${e}`}const ar={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]},cr={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function dr(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 ur(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function lr(e){return"string"==typeof e?e:e?.message}function pr(e,t,n){const r={...e,path:e.path??[]};if(!e.message){const i=lr(e.inst?._zod.def?.error?.(e))??lr(t?.error?.(e))??lr(n.customError?.(e))??lr(n.localeError?.(e))??"Invalid input";r.message=i}return delete r.inst,delete r.continue,t?.reportInput||delete r.input,r}function fr(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function hr(e){return Array.isArray(e)?"array":"string"==typeof e?"string":"unknown"}function mr(...e){const[t,n,r]=e;return"string"==typeof t?{message:t,code:"custom",input:n,inst:r}:{...t}}const gr=(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,Un,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},yr=Pn("$ZodError",gr),vr=Pn("$ZodError",gr,{Parent:Error}),wr=e=>(t,n,r,i)=>{const o=r?Object.assign(r,{async:!1}):{async:!1},s=t._zod.run({value:n,issues:[]},o);if(s instanceof Promise)throw new Cn;if(s.issues.length){const t=new(i?.Err??e)(s.issues.map(e=>pr(e,o,Zn())));throw Yn(t,i?.callee),t}return s.value},_r=wr(vr),br=e=>async(t,n,r,i)=>{const o=r?Object.assign(r,{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(i?.Err??e)(s.issues.map(e=>pr(e,o,Zn())));throw Yn(t,i?.callee),t}return s.value},Sr=br(vr),kr=e=>(t,n,r)=>{const i=r?{...r,async:!1}:{async:!1},o=t._zod.run({value:n,issues:[]},i);if(o instanceof Promise)throw new Cn;return o.issues.length?{success:!1,error:new(e??yr)(o.issues.map(e=>pr(e,i,Zn())))}:{success:!0,data:o.value}},Ir=kr(vr),zr=e=>async(t,n,r)=>{const i=r?Object.assign(r,{async:!0}):{async:!0};let o=t._zod.run({value:n,issues:[]},i);return o instanceof Promise&&(o=await o),o.issues.length?{success:!1,error:new e(o.issues.map(e=>pr(e,i,Zn())))}:{success:!0,data:o.value}},Dr=zr(vr),Er=e=>(t,n,r)=>{const i=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return wr(e)(t,n,i)},$r=e=>(t,n,r)=>wr(e)(t,n,r),Tr=e=>async(t,n,r)=>{const i=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return br(e)(t,n,i)},Ar=e=>async(t,n,r)=>br(e)(t,n,r),xr=e=>(t,n,r)=>{const i=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return kr(e)(t,n,i)},Or=e=>(t,n,r)=>kr(e)(t,n,r),Nr=e=>async(t,n,r)=>{const i=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return zr(e)(t,n,i)},Pr=e=>async(t,n,r)=>zr(e)(t,n,r),Cr=/^[cC][^\s-]{8,}$/,Rr=/^[0-9a-z]+$/,jr=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Zr=/^[0-9a-vA-V]{20}$/,Mr=/^[A-Za-z0-9]{27}$/,Lr=/^[a-zA-Z0-9_-]{21}$/,Ur=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Kr=/^[-+]?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)?)??$/,Jr=/^([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})$/,Hr=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)$/,Fr=Hr(4),Vr=Hr(6),Wr=Hr(7),Br=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,qr=/^[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])?)*$/,Yr=/^(([^<>()\[\]\\.,;:\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,}))$/,Gr=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,Xr=Gr,Qr=/^[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])?)*$/,ei="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function ti(){return new RegExp(ei,"u")}const ni=/^(?:(?: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])$/,ri=/^(([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}|:))$/,ii=e=>{const t=rr(e??":");return new RegExp(`^(?:[0-9A-F]{2}${t}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${t}){5}[0-9a-f]{2}$`)},oi=/^((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])$/,si=/^(([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])$/,ai=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,ci=/^[A-Za-z0-9_-]*$/,di=/^(?=.{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])?)*\.?$/,ui=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,li=/^\+[1-9]\d{6,14}$/,pi="(?:(?:\\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])))",fi=new RegExp(`^${pi}$`);function hi(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 mi(e){return new RegExp(`^${hi(e)}$`)}function gi(e){const t=hi({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const r=`${t}(?:${n.join("|")})`;return new RegExp(`^${pi}T(?:${r})$`)}const yi=e=>new RegExp(`^${e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*"}$`),vi=/^-?\d+n?$/,wi=/^-?\d+$/,_i=/^-?\d+(?:\.\d+)?$/,bi=/^(?:true|false)$/i,Si=/^null$/i,ki=/^undefined$/i,Ii=/^[^A-Z]*$/,zi=/^[^a-z]*$/,Di=/^[0-9a-fA-F]*$/;function Ei(e,t){return new RegExp(`^[A-Za-z0-9+/]{${e}}${t}$`)}function $i(e){return new RegExp(`^[A-Za-z0-9_-]{${e}}$`)}const Ti=/^[0-9a-fA-F]{32}$/,Ai=Ei(22,"=="),xi=$i(22),Oi=/^[0-9a-fA-F]{40}$/,Ni=Ei(27,"="),Pi=$i(27),Ci=/^[0-9a-fA-F]{64}$/,Ri=Ei(43,"="),ji=$i(43),Zi=/^[0-9a-fA-F]{96}$/,Mi=Ei(64,""),Li=$i(64),Ui=/^[0-9a-fA-F]{128}$/,Ki=Ei(86,"=="),Ji=$i(86),Hi=Pn("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Fi={number:"number",bigint:"bigint",object:"date"},Vi=Pn("$ZodCheckLessThan",(e,t)=>{Hi.init(e,t);const n=Fi[typeof t.value];e._zod.onattach.push(e=>{const n=e._zod.bag,r=(t.inclusive?n.maximum:n.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<r&&(t.inclusive?n.maximum=t.value:n.exclusiveMaximum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:n,code:"too_big",maximum:"object"==typeof t.value?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Wi=Pn("$ZodCheckGreaterThan",(e,t)=>{Hi.init(e,t);const n=Fi[typeof t.value];e._zod.onattach.push(e=>{const n=e._zod.bag,r=(t.inclusive?n.minimum:n.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>r&&(t.inclusive?n.minimum=t.value:n.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:"too_small",minimum:"object"==typeof t.value?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Bi=Pn("$ZodCheckMultipleOf",(e,t)=>{Hi.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,r=t.toString();let i=(r.split(".")[1]||"").length;if(0===i&&/\d?e-\d?/.test(r)){const e=r.match(/\d?e-(\d?)/);e?.[1]&&(i=Number.parseInt(e[1]))}const o=n>i?n:i;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})}}),qi=Pn("$ZodCheckNumberFormat",(e,t)=>{Hi.init(e,t),t.format=t.format||"float64";const n=t.format?.includes("int"),r=n?"int":"number",[i,o]=ar[t.format];e._zod.onattach.push(e=>{const r=e._zod.bag;r.format=t.format,r.minimum=i,r.maximum=o,n&&(r.pattern=wi)}),e._zod.check=s=>{const a=s.value;if(n){if(!Number.isInteger(a))return void s.issues.push({expected:r,format:t.format,code:"invalid_type",continue:!1,input:a,inst:e});if(!Number.isSafeInteger(a))return void(a>0?s.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort}):s.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort}))}a<i&&s.issues.push({origin:"number",input:a,code:"too_small",minimum:i,inclusive:!0,inst:e,continue:!t.abort}),a>o&&s.issues.push({origin:"number",input:a,code:"too_big",maximum:o,inclusive:!0,inst:e,continue:!t.abort})}}),Yi=Pn("$ZodCheckBigIntFormat",(e,t)=>{Hi.init(e,t);const[n,r]=cr[t.format];e._zod.onattach.push(e=>{const i=e._zod.bag;i.format=t.format,i.minimum=n,i.maximum=r}),e._zod.check=i=>{const o=i.value;o<n&&i.issues.push({origin:"bigint",input:o,code:"too_small",minimum:n,inclusive:!0,inst:e,continue:!t.abort}),o>r&&i.issues.push({origin:"bigint",input:o,code:"too_big",maximum:r,inclusive:!0,inst:e,continue:!t.abort})}}),Gi=Pn("$ZodCheckMaxSize",(e,t)=>{var n;Hi.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!Jn(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 r=n.value;r.size<=t.maximum||n.issues.push({origin:fr(r),code:"too_big",maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Xi=Pn("$ZodCheckMinSize",(e,t)=>{var n;Hi.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!Jn(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 r=n.value;r.size>=t.minimum||n.issues.push({origin:fr(r),code:"too_small",minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Qi=Pn("$ZodCheckSizeEquals",(e,t)=>{var n;Hi.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!Jn(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 r=n.value,i=r.size;if(i===t.size)return;const o=i>t.size;n.issues.push({origin:fr(r),...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})}}),eo=Pn("$ZodCheckMaxLength",(e,t)=>{var n;Hi.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!Jn(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 r=n.value;if(r.length<=t.maximum)return;const i=hr(r);n.issues.push({origin:i,code:"too_big",maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),to=Pn("$ZodCheckMinLength",(e,t)=>{var n;Hi.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!Jn(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 r=n.value;if(r.length>=t.minimum)return;const i=hr(r);n.issues.push({origin:i,code:"too_small",minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),no=Pn("$ZodCheckLengthEquals",(e,t)=>{var n;Hi.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!Jn(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 r=n.value,i=r.length;if(i===t.length)return;const o=hr(r),s=i>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})}}),ro=Pn("$ZodCheckStringFormat",(e,t)=>{var n,r;Hi.init(e,t),e._zod.onattach.push(e=>{const n=e._zod.bag;n.format=t.format,t.pattern&&(n.patterns??(n.patterns=new Set),n.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,t.pattern.test(n.value)||n.issues.push({origin:"string",code:"invalid_format",format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),io=Pn("$ZodCheckRegex",(e,t)=>{ro.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})}}),oo=Pn("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Ii),ro.init(e,t)}),so=Pn("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=zi),ro.init(e,t)}),ao=Pn("$ZodCheckIncludes",(e,t)=>{Hi.init(e,t);const n=rr(t.includes),r=new RegExp("number"==typeof t.position?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(r)}),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),co=Pn("$ZodCheckStartsWith",(e,t)=>{Hi.init(e,t);const n=new RegExp(`^${rr(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})}}),uo=Pn("$ZodCheckEndsWith",(e,t)=>{Hi.init(e,t);const n=new RegExp(`.*${rr(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 lo(e,t,n){e.issues.length&&t.issues.push(...ur(n,e.issues))}const po=Pn("$ZodCheckProperty",(e,t)=>{Hi.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=>lo(n,e,t.property));lo(n,e,t.property)}}),fo=Pn("$ZodCheckMimeType",(e,t)=>{Hi.init(e,t);const n=new Set(t.mime);e._zod.onattach.push(e=>{e._zod.bag.mime=t.mime}),e._zod.check=r=>{n.has(r.value.type)||r.issues.push({code:"invalid_value",values:t.mime,input:r.value.type,inst:e,continue:!t.abort})}}),ho=Pn("$ZodCheckOverwrite",(e,t)=>{Hi.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});class mo{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)),r=t.map(e=>e.slice(n)).map(e=>" ".repeat(2*this.indent)+e);for(const e of r)this.content.push(e)}compile(){const e=Function,t=this?.args;return new e(...t,[...(this?.content??[""]).map(e=>` ${e}`)].join("\n"))}}const go={major:4,minor:3,patch:6},yo=Pn("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=go;const r=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&r.unshift(e);for(const t of r)for(const n of t._zod.onattach)n(e);if(0===r.length)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const t=(e,t,n)=>{let r,i=dr(e);for(const o of t){if(o._zod.def.when){if(!o._zod.def.when(e))continue}else if(i)continue;const t=e.issues.length,s=o._zod.check(e);if(s instanceof Promise&&!1===n?.async)throw new Cn;if(r||s instanceof Promise)r=(r??Promise.resolve()).then(async()=>{await s,e.issues.length!==t&&(i||(i=dr(e,t)))});else{if(e.issues.length===t)continue;i||(i=dr(e,t))}}return r?r.then(()=>e):e},n=(n,i,o)=>{if(dr(n))return n.aborted=!0,n;const s=t(i,r,o);if(s instanceof Promise){if(!1===o.async)throw new Cn;return s.then(t=>e._zod.parse(t,o))}return e._zod.parse(s,o)};e._zod.run=(i,o)=>{if(o.skipChecks)return e._zod.parse(i,o);if("backward"===o.direction){const t=e._zod.parse({value:i.value,issues:[]},{...o,skipChecks:!0});return t instanceof Promise?t.then(e=>n(e,i,o)):n(t,i,o)}const s=e._zod.parse(i,o);if(s instanceof Promise){if(!1===o.async)throw new Cn;return s.then(e=>t(e,r,o))}return t(s,r,o)}}Vn(e,"~standard",()=>({validate:t=>{try{const n=Ir(e,t);return n.success?{value:n.data}:{issues:n.error?.issues}}catch(n){return Dr(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:"zod",version:1}))}),vo=Pn("$ZodString",(e,t)=>{yo.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??yi(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch(r){}return"string"==typeof n.value||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),wo=Pn("$ZodStringFormat",(e,t)=>{ro.init(e,t),vo.init(e,t)}),_o=Pn("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Jr),wo.init(e,t)}),bo=Pn("$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=Hr(e))}else t.pattern??(t.pattern=Hr());wo.init(e,t)}),So=Pn("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Br),wo.init(e,t)}),ko=Pn("$ZodURL",(e,t)=>{wo.init(e,t),e._zod.check=n=>{try{const r=n.value.trim(),i=new URL(r);return t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.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(i.protocol.endsWith(":")?i.protocol.slice(0,-1):i.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=i.href:n.value=r)}catch(r){n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),Io=Pn("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=ti()),wo.init(e,t)}),zo=Pn("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=Lr),wo.init(e,t)}),Do=Pn("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Cr),wo.init(e,t)}),Eo=Pn("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Rr),wo.init(e,t)}),$o=Pn("$ZodULID",(e,t)=>{t.pattern??(t.pattern=jr),wo.init(e,t)}),To=Pn("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Zr),wo.init(e,t)}),Ao=Pn("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Mr),wo.init(e,t)}),xo=Pn("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=gi(t)),wo.init(e,t)}),Oo=Pn("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=fi),wo.init(e,t)}),No=Pn("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=mi(t)),wo.init(e,t)}),Po=Pn("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Ur),wo.init(e,t)}),Co=Pn("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=ni),wo.init(e,t),e._zod.bag.format="ipv4"}),Ro=Pn("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=ri),wo.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})}}}),jo=Pn("$ZodMAC",(e,t)=>{t.pattern??(t.pattern=ii(t.delimiter)),wo.init(e,t),e._zod.bag.format="mac"}),Zo=Pn("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=oi),wo.init(e,t)}),Mo=Pn("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=si),wo.init(e,t),e._zod.check=n=>{const r=n.value.split("/");try{if(2!==r.length)throw new Error;const[e,t]=r;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 Lo(e){if(""===e)return!0;if(e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}const Uo=Pn("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=ai),wo.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=n=>{Lo(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}}),Ko=Pn("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=ci),wo.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=n=>{(function(e){if(!ci.test(e))return!1;const t=e.replace(/[-_]/g,e=>"-"===e?"+":"/");return Lo(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})}}),Jo=Pn("$ZodE164",(e,t)=>{t.pattern??(t.pattern=li),wo.init(e,t)}),Ho=Pn("$ZodJWT",(e,t)=>{wo.init(e,t),e._zod.check=n=>{(function(e,t=null){try{const n=e.split(".");if(3!==n.length)return!1;const[r]=n;if(!r)return!1;const i=JSON.parse(atob(r));return!("typ"in i&&"JWT"!==i?.typ||!i.alg||t&&(!("alg"in i)||i.alg!==t))}catch{return!1}})(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),Fo=Pn("$ZodCustomStringFormat",(e,t)=>{wo.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})}}),Vo=Pn("$ZodNumber",(e,t)=>{yo.init(e,t),e._zod.pattern=e._zod.bag.pattern??_i,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch(e){}const i=n.value;if("number"==typeof i&&!Number.isNaN(i)&&Number.isFinite(i))return n;const o="number"==typeof i?Number.isNaN(i)?"NaN":Number.isFinite(i)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:i,inst:e,...o?{received:o}:{}}),n}}),Wo=Pn("$ZodNumberFormat",(e,t)=>{qi.init(e,t),Vo.init(e,t)}),Bo=Pn("$ZodBoolean",(e,t)=>{yo.init(e,t),e._zod.pattern=bi,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Boolean(n.value)}catch(e){}const i=n.value;return"boolean"==typeof i||n.issues.push({expected:"boolean",code:"invalid_type",input:i,inst:e}),n}}),qo=Pn("$ZodBigInt",(e,t)=>{yo.init(e,t),e._zod.pattern=vi,e._zod.parse=(n,r)=>{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}}),Yo=Pn("$ZodBigIntFormat",(e,t)=>{Yi.init(e,t),qo.init(e,t)}),Go=Pn("$ZodSymbol",(e,t)=>{yo.init(e,t),e._zod.parse=(t,n)=>{const r=t.value;return"symbol"==typeof r||t.issues.push({expected:"symbol",code:"invalid_type",input:r,inst:e}),t}}),Xo=Pn("$ZodUndefined",(e,t)=>{yo.init(e,t),e._zod.pattern=ki,e._zod.values=new Set([void 0]),e._zod.optin="optional",e._zod.optout="optional",e._zod.parse=(t,n)=>{const r=t.value;return void 0===r||t.issues.push({expected:"undefined",code:"invalid_type",input:r,inst:e}),t}}),Qo=Pn("$ZodNull",(e,t)=>{yo.init(e,t),e._zod.pattern=Si,e._zod.values=new Set([null]),e._zod.parse=(t,n)=>{const r=t.value;return null===r||t.issues.push({expected:"null",code:"invalid_type",input:r,inst:e}),t}}),es=Pn("$ZodAny",(e,t)=>{yo.init(e,t),e._zod.parse=e=>e}),ts=Pn("$ZodUnknown",(e,t)=>{yo.init(e,t),e._zod.parse=e=>e}),ns=Pn("$ZodNever",(e,t)=>{yo.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:e}),t)}),rs=Pn("$ZodVoid",(e,t)=>{yo.init(e,t),e._zod.parse=(t,n)=>{const r=t.value;return void 0===r||t.issues.push({expected:"void",code:"invalid_type",input:r,inst:e}),t}}),is=Pn("$ZodDate",(e,t)=>{yo.init(e,t),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=new Date(n.value)}catch(e){}const i=n.value,o=i instanceof Date;return o&&!Number.isNaN(i.getTime())||n.issues.push({expected:"date",code:"invalid_type",input:i,...o?{received:"Invalid Date"}:{},inst:e}),n}});function os(e,t,n){e.issues.length&&t.issues.push(...ur(n,e.issues)),t.value[n]=e.value}const ss=Pn("$ZodArray",(e,t)=>{yo.init(e,t),e._zod.parse=(n,r)=>{const i=n.value;if(!Array.isArray(i))return n.issues.push({expected:"array",code:"invalid_type",input:i,inst:e}),n;n.value=Array(i.length);const o=[];for(let e=0;e<i.length;e++){const s=i[e],a=t.element._zod.run({value:s,issues:[]},r);a instanceof Promise?o.push(a.then(t=>os(t,n,e))):os(a,n,e)}return o.length?Promise.all(o).then(()=>n):n}});function as(e,t,n,r,i){if(e.issues.length){if(i&&!(n in r))return;t.issues.push(...ur(n,e.issues))}void 0===e.value?n in r&&(t.value[n]=void 0):t.value[n]=e.value}function cs(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=(r=e.shape,Object.keys(r).filter(e=>"optional"===r[e]._zod.optin&&"optional"===r[e]._zod.optout));var r;return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function ds(e,t,n,r,i,o){const s=[],a=i.keySet,c=i.catchall._zod,d=c.def.type,u="optional"===c.optout;for(const i in t){if(a.has(i))continue;if("never"===d){s.push(i);continue}const o=c.run({value:t[i],issues:[]},r);o instanceof Promise?e.push(o.then(e=>as(e,n,i,t,u))):as(o,n,i,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 us=Pn("$ZodObject",(e,t)=>{yo.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 r=Kn(()=>cs(t));Vn(e._zod,"propValues",()=>{const e=t.shape,n={};for(const t in e){const r=e[t]._zod;if(r.values){n[t]??(n[t]=new Set);for(const e of r.values)n[t].add(e)}}return n});const i=Gn,o=t.catchall;let s;e._zod.parse=(t,n)=>{s??(s=r.value);const a=t.value;if(!i(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 r=d[e],i="optional"===r._zod.optout,o=r._zod.run({value:a[e],issues:[]},n);o instanceof Promise?c.push(o.then(n=>as(n,t,e,a,i))):as(o,t,e,a,i)}return o?ds(c,a,t,n,r.value,e):c.length?Promise.all(c).then(()=>t):t}}),ls=Pn("$ZodObjectJIT",(e,t)=>{us.init(e,t);const n=e._zod.parse,r=Kn(()=>cs(t));let i;const o=Gn,s=!jn.jitless,a=s&&Xn.value,c=t.catchall;let d;e._zod.parse=(u,l)=>{d??(d=r.value);const p=u.value;return o(p)?s&&a&&!1===l?.async&&!0!==l.jitless?(i||(i=(e=>{const t=new mo(["shape","payload","ctx"]),n=r.value,i=e=>{const t=qn(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 r of n.keys){const n=o[r],s=qn(r),a=e[r],c="optional"===a?._zod?.optout;t.write(`const ${n} = ${i(r)};`),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=i(u,l),c?ds([],p,u,l,d,e):u):n(u,l):(u.issues.push({expected:"object",code:"invalid_type",input:p,inst:e}),u)}});function ps(e,t,n,r){for(const n of e)if(0===n.issues.length)return t.value=n.value,t;const i=e.filter(e=>!dr(e));return 1===i.length?(t.value=i[0].value,i[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>pr(e,r,Zn())))}),t)}const fs=Pn("$ZodUnion",(e,t)=>{yo.init(e,t),Vn(e._zod,"optin",()=>t.options.some(e=>"optional"===e._zod.optin)?"optional":void 0),Vn(e._zod,"optout",()=>t.options.some(e=>"optional"===e._zod.optout)?"optional":void 0),Vn(e._zod,"values",()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),Vn(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=>Hn(e.source)).join("|")})$`)}});const n=1===t.options.length,r=t.options[0]._zod.run;e._zod.parse=(i,o)=>{if(n)return r(i,o);let s=!1;const a=[];for(const e of t.options){const t=e._zod.run({value:i.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=>ps(t,i,e,o)):ps(a,i,e,o)}});function hs(e,t,n,r){const i=e.filter(e=>0===e.issues.length);return 1===i.length?(t.value=i[0].value,t):(0===i.length?t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>pr(e,r,Zn())))}):t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:[],inclusive:!1}),t)}const ms=Pn("$ZodXor",(e,t)=>{fs.init(e,t),t.inclusive=!1;const n=1===t.options.length,r=t.options[0]._zod.run;e._zod.parse=(i,o)=>{if(n)return r(i,o);let s=!1;const a=[];for(const e of t.options){const t=e._zod.run({value:i.value,issues:[]},o);t instanceof Promise?(a.push(t),s=!0):a.push(t)}return s?Promise.all(a).then(t=>hs(t,i,e,o)):hs(a,i,e,o)}}),gs=Pn("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,fs.init(e,t);const n=e._zod.parse;Vn(e._zod,"propValues",()=>{const e={};for(const n of t.options){const r=n._zod.propValues;if(!r||0===Object.keys(r).length)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(n)}"`);for(const[t,n]of Object.entries(r)){e[t]||(e[t]=new Set);for(const r of n)e[t].add(r)}}return e});const r=Kn(()=>{const e=t.options,n=new Map;for(const r of e){const e=r._zod.propValues?.[t.discriminator];if(!e||0===e.size)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(r)}"`);for(const t of e){if(n.has(t))throw new Error(`Duplicate discriminator value "${String(t)}"`);n.set(t,r)}}return n});e._zod.parse=(i,o)=>{const s=i.value;if(!Gn(s))return i.issues.push({code:"invalid_type",expected:"object",input:s,inst:e}),i;const a=r.value.get(s?.[t.discriminator]);return a?a._zod.run(i,o):t.unionFallback?n(i,o):(i.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,input:s,path:[t.discriminator],inst:e}),i)}}),ys=Pn("$ZodIntersection",(e,t)=>{yo.init(e,t),e._zod.parse=(e,n)=>{const r=e.value,i=t.left._zod.run({value:r,issues:[]},n),o=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||o instanceof Promise?Promise.all([i,o]).then(([t,n])=>ws(e,t,n)):ws(e,i,o)}});function vs(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(Qn(e)&&Qn(t)){const n=Object.keys(t),r=Object.keys(e).filter(e=>-1!==n.indexOf(e)),i={...e,...t};for(const n of r){const r=vs(e[n],t[n]);if(!r.valid)return{valid:!1,mergeErrorPath:[n,...r.mergeErrorPath]};i[n]=r.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let r=0;r<e.length;r++){const i=vs(e[r],t[r]);if(!i.valid)return{valid:!1,mergeErrorPath:[r,...i.mergeErrorPath]};n.push(i.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function ws(e,t,n){const r=new Map;let i;for(const n of t.issues)if("unrecognized_keys"===n.code){i??(i=n);for(const e of n.keys)r.has(e)||r.set(e,{}),r.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)r.has(e)||r.set(e,{}),r.get(e).r=!0;else e.issues.push(t);const o=[...r].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(o.length&&i&&e.issues.push({...i,keys:o}),dr(e))return e;const s=vs(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 _s=Pn("$ZodTuple",(e,t)=>{yo.init(e,t);const n=t.items;e._zod.parse=(r,i)=>{const o=r.value;if(!Array.isArray(o))return r.issues.push({input:o,inst:e,expected:"tuple",code:"invalid_type"}),r;r.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,i=o.length<c-1;if(t||i)return r.issues.push({...t?{code:"too_big",maximum:n.length,inclusive:!0}:{code:"too_small",minimum:n.length},input:o,inst:e,origin:"array"}),r}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:[]},i);t instanceof Promise?s.push(t.then(e=>bs(e,r,d))):bs(t,r,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:[]},i);e instanceof Promise?s.push(e.then(e=>bs(e,r,d))):bs(e,r,d)}}return s.length?Promise.all(s).then(()=>r):r}});function bs(e,t,n){e.issues.length&&t.issues.push(...ur(n,e.issues)),t.value[n]=e.value}const Ss=Pn("$ZodRecord",(e,t)=>{yo.init(e,t),e._zod.parse=(n,r)=>{const i=n.value;if(!Qn(i))return n.issues.push({expected:"record",code:"invalid_type",input:i,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:i[e],issues:[]},r);s instanceof Promise?o.push(s.then(t=>{t.issues.length&&n.issues.push(...ur(e,t.issues)),n.value[e]=t.value})):(s.issues.length&&n.issues.push(...ur(e,s.issues)),n.value[e]=s.value)}let c;for(const e in i)a.has(e)||(c=c??[],c.push(e));c&&c.length>0&&n.issues.push({code:"unrecognized_keys",input:i,inst:e,keys:c})}else{n.value={};for(const s of Reflect.ownKeys(i)){if("__proto__"===s)continue;let a=t.keyType._zod.run({value:s,issues:[]},r);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if("string"==typeof s&&_i.test(s)&&a.issues.length){const e=t.keyType._zod.run({value:Number(s),issues:[]},r);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]=i[s]:n.issues.push({code:"invalid_key",origin:"record",issues:a.issues.map(e=>pr(e,r,Zn())),input:s,path:[s],inst:e});continue}const c=t.valueType._zod.run({value:i[s],issues:[]},r);c instanceof Promise?o.push(c.then(e=>{e.issues.length&&n.issues.push(...ur(s,e.issues)),n.value[a.value]=e.value})):(c.issues.length&&n.issues.push(...ur(s,c.issues)),n.value[a.value]=c.value)}}return o.length?Promise.all(o).then(()=>n):n}}),ks=Pn("$ZodMap",(e,t)=>{yo.init(e,t),e._zod.parse=(n,r)=>{const i=n.value;if(!(i instanceof Map))return n.issues.push({expected:"map",code:"invalid_type",input:i,inst:e}),n;const o=[];n.value=new Map;for(const[s,a]of i){const c=t.keyType._zod.run({value:s,issues:[]},r),d=t.valueType._zod.run({value:a,issues:[]},r);c instanceof Promise||d instanceof Promise?o.push(Promise.all([c,d]).then(([t,o])=>{Is(t,o,n,s,i,e,r)})):Is(c,d,n,s,i,e,r)}return o.length?Promise.all(o).then(()=>n):n}});function Is(e,t,n,r,i,o,s){e.issues.length&&(tr.has(typeof r)?n.issues.push(...ur(r,e.issues)):n.issues.push({code:"invalid_key",origin:"map",input:i,inst:o,issues:e.issues.map(e=>pr(e,s,Zn()))})),t.issues.length&&(tr.has(typeof r)?n.issues.push(...ur(r,t.issues)):n.issues.push({origin:"map",code:"invalid_element",input:i,inst:o,key:r,issues:t.issues.map(e=>pr(e,s,Zn()))})),n.value.set(e.value,t.value)}const zs=Pn("$ZodSet",(e,t)=>{yo.init(e,t),e._zod.parse=(n,r)=>{const i=n.value;if(!(i instanceof Set))return n.issues.push({input:i,inst:e,expected:"set",code:"invalid_type"}),n;const o=[];n.value=new Set;for(const e of i){const i=t.valueType._zod.run({value:e,issues:[]},r);i instanceof Promise?o.push(i.then(e=>Ds(e,n))):Ds(i,n)}return o.length?Promise.all(o).then(()=>n):n}});function Ds(e,t){e.issues.length&&t.issues.push(...e.issues),t.value.add(e.value)}const Es=Pn("$ZodEnum",(e,t)=>{yo.init(e,t);const n=Mn(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=new RegExp(`^(${n.filter(e=>tr.has(typeof e)).map(e=>"string"==typeof e?rr(e):e.toString()).join("|")})$`),e._zod.parse=(t,i)=>{const o=t.value;return r.has(o)||t.issues.push({code:"invalid_value",values:n,input:o,inst:e}),t}}),$s=Pn("$ZodLiteral",(e,t)=>{if(yo.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?rr(e):e?rr(e.toString()):String(e)).join("|")})$`),e._zod.parse=(r,i)=>{const o=r.value;return n.has(o)||r.issues.push({code:"invalid_value",values:t.values,input:o,inst:e}),r}}),Ts=Pn("$ZodFile",(e,t)=>{yo.init(e,t),e._zod.parse=(t,n)=>{const r=t.value;return r instanceof File||t.issues.push({expected:"file",code:"invalid_type",input:r,inst:e}),t}}),As=Pn("$ZodTransform",(e,t)=>{yo.init(e,t),e._zod.parse=(n,r)=>{if("backward"===r.direction)throw new Rn(e.constructor.name);const i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(e=>(n.value=e,n));if(i instanceof Promise)throw new Cn;return n.value=i,n}});function xs(e,t){return e.issues.length&&void 0===t?{issues:[],value:void 0}:e}const Os=Pn("$ZodOptional",(e,t)=>{yo.init(e,t),e._zod.optin="optional",e._zod.optout="optional",Vn(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),Vn(e._zod,"pattern",()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${Hn(e.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if("optional"===t.innerType._zod.optin){const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(t=>xs(t,e.value)):xs(r,e.value)}return void 0===e.value?e:t.innerType._zod.run(e,n)}}),Ns=Pn("$ZodExactOptional",(e,t)=>{Os.init(e,t),Vn(e._zod,"values",()=>t.innerType._zod.values),Vn(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),Ps=Pn("$ZodNullable",(e,t)=>{yo.init(e,t),Vn(e._zod,"optin",()=>t.innerType._zod.optin),Vn(e._zod,"optout",()=>t.innerType._zod.optout),Vn(e._zod,"pattern",()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${Hn(e.source)}|null)$`):void 0}),Vn(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)}),Cs=Pn("$ZodDefault",(e,t)=>{yo.init(e,t),e._zod.optin="optional",Vn(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 r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>Rs(e,t)):Rs(r,t)}});function Rs(e,t){return void 0===e.value&&(e.value=t.defaultValue),e}const js=Pn("$ZodPrefault",(e,t)=>{yo.init(e,t),e._zod.optin="optional",Vn(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))}),Zs=Pn("$ZodNonOptional",(e,t)=>{yo.init(e,t),Vn(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,r)=>{const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(t=>Ms(t,e)):Ms(i,e)}});function Ms(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 Ls=Pn("$ZodSuccess",(e,t)=>{yo.init(e,t),e._zod.parse=(e,n)=>{if("backward"===n.direction)throw new Rn("ZodSuccess");const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(t=>(e.value=0===t.issues.length,e)):(e.value=0===r.issues.length,e)}}),Us=Pn("$ZodCatch",(e,t)=>{yo.init(e,t),Vn(e._zod,"optin",()=>t.innerType._zod.optin),Vn(e._zod,"optout",()=>t.innerType._zod.optout),Vn(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if("backward"===n.direction)return t.innerType._zod.run(e,n);const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(r=>(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>pr(e,n,Zn()))},input:e.value}),e.issues=[]),e)):(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>pr(e,n,Zn()))},input:e.value}),e.issues=[]),e)}}),Ks=Pn("$ZodNaN",(e,t)=>{yo.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)}),Js=Pn("$ZodPipe",(e,t)=>{yo.init(e,t),Vn(e._zod,"values",()=>t.in._zod.values),Vn(e._zod,"optin",()=>t.in._zod.optin),Vn(e._zod,"optout",()=>t.out._zod.optout),Vn(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(e,n)=>{if("backward"===n.direction){const r=t.out._zod.run(e,n);return r instanceof Promise?r.then(e=>Hs(e,t.in,n)):Hs(r,t.in,n)}const r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>Hs(e,t.out,n)):Hs(r,t.out,n)}});function Hs(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},n)}const Fs=Pn("$ZodCodec",(e,t)=>{yo.init(e,t),Vn(e._zod,"values",()=>t.in._zod.values),Vn(e._zod,"optin",()=>t.in._zod.optin),Vn(e._zod,"optout",()=>t.out._zod.optout),Vn(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(e,n)=>{if("forward"===(n.direction||"forward")){const r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>Vs(e,t,n)):Vs(r,t,n)}{const r=t.out._zod.run(e,n);return r instanceof Promise?r.then(e=>Vs(e,t,n)):Vs(r,t,n)}}});function Vs(e,t,n){if(e.issues.length)return e.aborted=!0,e;if("forward"===(n.direction||"forward")){const r=t.transform(e.value,e);return r instanceof Promise?r.then(r=>Ws(e,r,t.out,n)):Ws(e,r,t.out,n)}{const r=t.reverseTransform(e.value,e);return r instanceof Promise?r.then(r=>Ws(e,r,t.in,n)):Ws(e,r,t.in,n)}}function Ws(e,t,n,r){return e.issues.length?(e.aborted=!0,e):n._zod.run({value:t,issues:e.issues},r)}const Bs=Pn("$ZodReadonly",(e,t)=>{yo.init(e,t),Vn(e._zod,"propValues",()=>t.innerType._zod.propValues),Vn(e._zod,"values",()=>t.innerType._zod.values),Vn(e._zod,"optin",()=>t.innerType?._zod?.optin),Vn(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(e,n)=>{if("backward"===n.direction)return t.innerType._zod.run(e,n);const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(qs):qs(r)}});function qs(e){return e.value=Object.freeze(e.value),e}const Ys=Pn("$ZodTemplateLiteral",(e,t)=>{yo.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 r=t.startsWith("^")?1:0,i=t.endsWith("$")?t.length-1:t.length;n.push(t.slice(r,i))}else{if(null!==e&&!nr.has(typeof e))throw new Error(`Invalid template literal part: ${e}`);n.push(rr(`${e}`))}e._zod.pattern=new RegExp(`^${n.join("")}$`),e._zod.parse=(n,r)=>"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)}),Gs=Pn("$ZodFunction",(e,t)=>(yo.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 r=e._def.input?_r(e._def.input,n):n,i=Reflect.apply(t,this,r);return e._def.output?_r(e._def.output,i):i}},e.implementAsync=t=>{if("function"!=typeof t)throw new Error("implementAsync() must be called with a function");return async function(...n){const r=e._def.input?await Sr(e._def.input,n):n,i=await Reflect.apply(t,this,r);return e._def.output?await Sr(e._def.output,i):i}},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 r=e._def.output&&"promise"===e._def.output._zod.def.type;return t.value=r?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 _s({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)),Xs=Pn("$ZodPromise",(e,t)=>{yo.init(e,t),e._zod.parse=(e,n)=>Promise.resolve(e.value).then(e=>t.innerType._zod.run({value:e,issues:[]},n))}),Qs=Pn("$ZodLazy",(e,t)=>{yo.init(e,t),Vn(e._zod,"innerType",()=>t.getter()),Vn(e._zod,"pattern",()=>e._zod.innerType?._zod?.pattern),Vn(e._zod,"propValues",()=>e._zod.innerType?._zod?.propValues),Vn(e._zod,"optin",()=>e._zod.innerType?._zod?.optin??void 0),Vn(e._zod,"optout",()=>e._zod.innerType?._zod?.optout??void 0),e._zod.parse=(t,n)=>e._zod.innerType._zod.run(t,n)}),ea=Pn("$ZodCustom",(e,t)=>{Hi.init(e,t),yo.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{const r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(t=>ta(t,n,r,e));ta(i,n,r,e)}});function ta(e,t,n,r){if(!e){const e={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(mr(e))}}var na;Symbol("ZodOutput"),Symbol("ZodInput");(na=globalThis).__zod_globalRegistry??(na.__zod_globalRegistry=new class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){const n=t[0];return this._map.set(e,n),n&&"object"==typeof n&&"id"in n&&this._idmap.set(n.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){const t=this._map.get(e);return t&&"object"==typeof t&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){const t=e._zod.parent;if(t){const n={...this.get(t)??{}};delete n.id;const r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}});const ra=globalThis.__zod_globalRegistry;function ia(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...or(t)})}function oa(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...or(t)})}function sa(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...or(t)})}function aa(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...or(t)})}function ca(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...or(t)})}function da(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...or(t)})}function ua(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...or(t)})}function la(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...or(t)})}function pa(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...or(t)})}function fa(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...or(t)})}function ha(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...or(t)})}function ma(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...or(t)})}function ga(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...or(t)})}function ya(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...or(t)})}function va(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...or(t)})}function wa(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...or(t)})}function _a(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...or(t)})}function ba(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...or(t)})}function Sa(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...or(t)})}function ka(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...or(t)})}function Ia(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...or(t)})}function za(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...or(t)})}function Da(e,t){return new Vi({check:"less_than",...or(t),value:e,inclusive:!1})}function Ea(e,t){return new Vi({check:"less_than",...or(t),value:e,inclusive:!0})}function $a(e,t){return new Wi({check:"greater_than",...or(t),value:e,inclusive:!1})}function Ta(e,t){return new Wi({check:"greater_than",...or(t),value:e,inclusive:!0})}function Aa(e){return $a(0,e)}function xa(e){return Da(0,e)}function Oa(e){return Ea(0,e)}function Na(e){return Ta(0,e)}function Pa(e,t){return new Bi({check:"multiple_of",...or(t),value:e})}function Ca(e,t){return new Gi({check:"max_size",...or(t),maximum:e})}function Ra(e,t){return new Xi({check:"min_size",...or(t),minimum:e})}function ja(e,t){return new Qi({check:"size_equals",...or(t),size:e})}function Za(e,t){return new eo({check:"max_length",...or(t),maximum:e})}function Ma(e,t){return new to({check:"min_length",...or(t),minimum:e})}function La(e,t){return new no({check:"length_equals",...or(t),length:e})}function Ua(e,t){return new io({check:"string_format",format:"regex",...or(t),pattern:e})}function Ka(e){return new oo({check:"string_format",format:"lowercase",...or(e)})}function Ja(e){return new so({check:"string_format",format:"uppercase",...or(e)})}function Ha(e,t){return new ao({check:"string_format",format:"includes",...or(t),includes:e})}function Fa(e,t){return new co({check:"string_format",format:"starts_with",...or(t),prefix:e})}function Va(e,t){return new uo({check:"string_format",format:"ends_with",...or(t),suffix:e})}function Wa(e,t,n){return new po({check:"property",property:e,schema:t,...or(n)})}function Ba(e,t){return new fo({check:"mime_type",mime:e,...or(t)})}function qa(e){return new ho({check:"overwrite",tx:e})}function Ya(e){return qa(t=>t.normalize(e))}function Ga(){return qa(e=>e.trim())}function Xa(){return qa(e=>e.toLowerCase())}function Qa(){return qa(e=>e.toUpperCase())}function ec(){return qa(e=>function(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}(e))}function tc(e,t,n,r={}){const i=or(r),o={...or(r),check:"string_format",type:"string",format:t,fn:"function"==typeof n?n:e=>n.test(e),...i};return n instanceof RegExp&&(o.pattern=n),new e(o)}function nc(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??ra,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 rc(e,t,n={path:[],schemaPath:[]}){var r;const i=e._zod.def,o=t.seen.get(e);if(o)return o.count++,n.schemaPath.includes(e)&&(o.cycle=n.path),o.schema;const s={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,s);const a=e._zod.toJSONSchema?.();if(a)s.schema=a;else{const r={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,s.schema,r);else{const n=s.schema,o=t.processors[i.type];if(!o)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);o(e,t,n,r)}const o=e._zod.parent;o&&(s.ref||(s.ref=o),rc(o,t,r),t.seen.get(o).isParent=!0)}const c=t.metadataRegistry.get(e);return c&&Object.assign(s.schema,c),"input"===t.io&&sc(e)&&(delete s.schema.examples,delete s.schema.default),"input"===t.io&&s.schema._prefault&&((r=s.schema).default??(r.default=s.schema._prefault)),delete s.schema._prefault,t.seen.get(e).schema}function ic(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=new Map;for(const t of e.seen.entries()){const n=e.metadataRegistry.get(t[0])?.id;if(n){const e=r.get(n);if(e&&e!==t[0])throw new Error(`Duplicate schema id "${n}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(n,t[0])}}const i=t=>{if(t[1].schema.$ref)return;const r=t[1],{ref:i,defId:o}=(t=>{const r="draft-2020-12"===e.target?"$defs":"definitions";if(e.external){const n=e.external.registry.get(t[0])?.id,i=e.external.uri??(e=>e);if(n)return{ref:i(n)};const o=t[1].defId??t[1].schema.id??"schema"+e.counter++;return t[1].defId=o,{defId:o,ref:`${i("__shared")}#/${r}/${o}`}}if(t[1]===n)return{ref:"#"};const i=`#/${r}/`,o=t[1].schema.id??"__schema"+e.counter++;return{defId:o,ref:i+o}})(t);r.def={...r.schema},o&&(r.defId=o);const s=r.schema;for(const e in s)delete s[e];s.$ref=i};if("throw"===e.cycles)for(const t of e.seen.entries()){const e=t[1];if(e.cycle)throw new Error(`Cycle detected: #/${e.cycle?.join("/")}/<root>\n\nSet the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const n of e.seen.entries()){const r=n[1];if(t===n[0]){i(n);continue}if(e.external){const r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){i(n);continue}}const o=e.metadataRegistry.get(n[0])?.id;(o||r.cycle||r.count>1&&"ref"===e.reused)&&i(n)}}function oc(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=t=>{const n=e.seen.get(t);if(null===n.ref)return;const i=n.def??n.schema,o={...i},s=n.ref;if(n.ref=null,s){r(s);const n=e.seen.get(s),a=n.schema;if(!a.$ref||"draft-07"!==e.target&&"draft-04"!==e.target&&"openapi-3.0"!==e.target?Object.assign(i,a):(i.allOf=i.allOf??[],i.allOf.push(a)),Object.assign(i,o),t._zod.parent===s)for(const e in i)"$ref"!==e&&"allOf"!==e&&(e in o||delete i[e]);if(a.$ref&&n.def)for(const e in i)"$ref"!==e&&"allOf"!==e&&e in n.def&&JSON.stringify(i[e])===JSON.stringify(n.def[e])&&delete i[e]}const a=t._zod.parent;if(a&&a!==s){r(a);const t=e.seen.get(a);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(const e in i)"$ref"!==e&&"allOf"!==e&&e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:n.path??[]})};for(const t of[...e.seen.entries()].reverse())r(t[0]);const i={};if("draft-2020-12"===e.target?i.$schema="https://json-schema.org/draft/2020-12/schema":"draft-07"===e.target?i.$schema="http://json-schema.org/draft-07/schema#":"draft-04"===e.target?i.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const n=e.external.registry.get(t)?.id;if(!n)throw new Error("Schema is missing an `id` property");i.$id=e.external.uri(n)}Object.assign(i,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?i.$defs=o:i.definitions=o);try{const n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,"~standard",{value:{...t["~standard"],jsonSchema:{input:ac(t,"input",e.processors),output:ac(t,"output",e.processors)}},enumerable:!1,writable:!1}),n}catch(e){throw new Error("Error converting schema to JSON.")}}function sc(e,t){const n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);const r=e._zod.def;if("transform"===r.type)return!0;if("array"===r.type)return sc(r.element,n);if("set"===r.type)return sc(r.valueType,n);if("lazy"===r.type)return sc(r.getter(),n);if("promise"===r.type||"optional"===r.type||"nonoptional"===r.type||"nullable"===r.type||"readonly"===r.type||"default"===r.type||"prefault"===r.type)return sc(r.innerType,n);if("intersection"===r.type)return sc(r.left,n)||sc(r.right,n);if("record"===r.type||"map"===r.type)return sc(r.keyType,n)||sc(r.valueType,n);if("pipe"===r.type)return sc(r.in,n)||sc(r.out,n);if("object"===r.type){for(const e in r.shape)if(sc(r.shape[e],n))return!0;return!1}if("union"===r.type){for(const e of r.options)if(sc(e,n))return!0;return!1}if("tuple"===r.type){for(const e of r.items)if(sc(e,n))return!0;return!(!r.rest||!sc(r.rest,n))}return!1}const ac=(e,t,n={})=>r=>{const{libraryOptions:i,target:o}=r??{},s=nc({...i??{},target:o,io:t,processors:n});return rc(e,s),ic(s,e),oc(s,e)},cc={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},dc=(e,t,n,r)=>{const i=e._zod.def,o=!1===i.inclusive,s=i.options.map((e,n)=>rc(e,t,{...r,path:[...r.path,o?"oneOf":"anyOf",n]}));o?n.oneOf=s:n.anyOf=s},uc=(e,t,n,r)=>{const i=e._zod.def;rc(i.innerType,t,r),t.seen.get(e).ref=i.innerType},lc=Pn("ZodISODateTime",(e,t)=>{xo.init(e,t),jc.init(e,t)});function pc(e){return function(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...or(t)})}(lc,e)}const fc=Pn("ZodISODate",(e,t)=>{Oo.init(e,t),jc.init(e,t)});function hc(e){return function(e,t){return new e({type:"string",format:"date",check:"string_format",...or(t)})}(fc,e)}const mc=Pn("ZodISOTime",(e,t)=>{No.init(e,t),jc.init(e,t)});function gc(e){return function(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...or(t)})}(mc,e)}const yc=Pn("ZodISODuration",(e,t)=>{Po.init(e,t),jc.init(e,t)});function vc(e){return function(e,t){return new e({type:"string",format:"duration",check:"string_format",...or(t)})}(yc,e)}const wc=(e,t)=>{yr.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:t=>function(e,t=e=>e.message){const n={_errors:[]},r=e=>{for(const i of e.issues)if("invalid_union"===i.code&&i.errors.length)i.errors.map(e=>r({issues:e}));else if("invalid_key"===i.code)r({issues:i.issues});else if("invalid_element"===i.code)r({issues:i.issues});else if(0===i.path.length)n._errors.push(t(i));else{let e=n,r=0;for(;r<i.path.length;){const n=i.path[r];r===i.path.length-1?(e[n]=e[n]||{_errors:[]},e[n]._errors.push(t(i))):e[n]=e[n]||{_errors:[]},e=e[n],r++}}};return r(e),n}(e,t)},flatten:{value:t=>function(e,t=e=>e.message){const n={},r=[];for(const i of e.issues)i.path.length>0?(n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i))):r.push(t(i));return{formErrors:r,fieldErrors:n}}(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,Un,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,Un,2)}},isEmpty:{get:()=>0===e.issues.length}})},_c=(Pn("ZodError",wc),Pn("ZodError",wc,{Parent:Error})),bc=wr(_c),Sc=br(_c),kc=kr(_c),Ic=zr(_c),zc=Er(_c),Dc=$r(_c),Ec=Tr(_c),$c=Ar(_c),Tc=xr(_c),Ac=Or(_c),xc=Nr(_c),Oc=Pr(_c),Nc=Pn("ZodType",(e,t)=>(yo.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:ac(e,"input"),output:ac(e,"output")}}),e.toJSONSchema=((e,t={})=>n=>{const r=nc({...n,processors:t});return rc(e,r),ic(r,e),oc(r,e)})(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...n)=>e.clone(Bn(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)=>ir(e,t,n),e.brand=()=>e,e.register=(t,n)=>(t.add(e,n),e),e.parse=(t,n)=>bc(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>kc(e,t,n),e.parseAsync=async(t,n)=>Sc(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>Ic(e,t,n),e.spa=e.safeParseAsync,e.encode=(t,n)=>zc(e,t,n),e.decode=(t,n)=>Dc(e,t,n),e.encodeAsync=async(t,n)=>Ec(e,t,n),e.decodeAsync=async(t,n)=>$c(e,t,n),e.safeEncode=(t,n)=>Tc(e,t,n),e.safeDecode=(t,n)=>Ac(e,t,n),e.safeEncodeAsync=async(t,n)=>xc(e,t,n),e.safeDecodeAsync=async(t,n)=>Oc(e,t,n),e.refine=(t,n)=>e.check(Dl(t,n)),e.superRefine=t=>e.check(El(t)),e.overwrite=t=>e.check(qa(t)),e.optional=()=>Fu(e),e.exactOptional=()=>Wu(e),e.nullable=()=>qu(e),e.nullish=()=>Fu(qu(e)),e.nonoptional=t=>nl(e,t),e.array=()=>lu(e),e.or=t=>vu([e,t]),e.and=t=>Iu(e,t),e.transform=t=>ul(e,Ju(t)),e.default=t=>Xu(e,t),e.prefault=t=>el(e,t),e.catch=t=>sl(e,t),e.pipe=t=>ul(e,t),e.readonly=()=>hl(e),e.describe=t=>{const n=e.clone();return ra.add(n,{description:t}),n},Object.defineProperty(e,"description",{get:()=>ra.get(e)?.description,configurable:!0}),e.meta=(...t)=>{if(0===t.length)return ra.get(e);const n=e.clone();return ra.add(n,t[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e.apply=t=>t(e),e)),Pc=Pn("_ZodString",(e,t)=>{vo.init(e,t),Nc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n)=>{const r=n;r.type="string";const{minimum:i,maximum:o,format:s,patterns:a,contentEncoding:c}=e._zod.bag;if("number"==typeof i&&(r.minLength=i),"number"==typeof o&&(r.maxLength=o),s&&(r.format=cc[s]??s,""===r.format&&delete r.format,"time"===s&&delete r.format),c&&(r.contentEncoding=c),a&&a.size>0){const e=[...a];1===e.length?r.pattern=e[0].source:e.length>1&&(r.allOf=[...e.map(e=>({..."draft-07"===t.target||"draft-04"===t.target||"openapi-3.0"===t.target?{type:"string"}:{},pattern:e.source}))])}})(e,t,n);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,e.regex=(...t)=>e.check(Ua(...t)),e.includes=(...t)=>e.check(Ha(...t)),e.startsWith=(...t)=>e.check(Fa(...t)),e.endsWith=(...t)=>e.check(Va(...t)),e.min=(...t)=>e.check(Ma(...t)),e.max=(...t)=>e.check(Za(...t)),e.length=(...t)=>e.check(La(...t)),e.nonempty=(...t)=>e.check(Ma(1,...t)),e.lowercase=t=>e.check(Ka(t)),e.uppercase=t=>e.check(Ja(t)),e.trim=()=>e.check(Ga()),e.normalize=(...t)=>e.check(Ya(...t)),e.toLowerCase=()=>e.check(Xa()),e.toUpperCase=()=>e.check(Qa()),e.slugify=()=>e.check(ec())}),Cc=Pn("ZodString",(e,t)=>{vo.init(e,t),Pc.init(e,t),e.email=t=>e.check(ia(Zc,t)),e.url=t=>e.check(ua(Wc,t)),e.jwt=t=>e.check(za(Dd,t)),e.emoji=t=>e.check(la(Yc,t)),e.guid=t=>e.check(oa(Lc,t)),e.uuid=t=>e.check(sa(Kc,t)),e.uuidv4=t=>e.check(aa(Kc,t)),e.uuidv6=t=>e.check(ca(Kc,t)),e.uuidv7=t=>e.check(da(Kc,t)),e.nanoid=t=>e.check(pa(Xc,t)),e.guid=t=>e.check(oa(Lc,t)),e.cuid=t=>e.check(fa(ed,t)),e.cuid2=t=>e.check(ha(nd,t)),e.ulid=t=>e.check(ma(id,t)),e.base64=t=>e.check(Sa(_d,t)),e.base64url=t=>e.check(ka(Sd,t)),e.xid=t=>e.check(ga(sd,t)),e.ksuid=t=>e.check(ya(cd,t)),e.ipv4=t=>e.check(va(ud,t)),e.ipv6=t=>e.check(wa(hd,t)),e.cidrv4=t=>e.check(_a(gd,t)),e.cidrv6=t=>e.check(ba(vd,t)),e.e164=t=>e.check(Ia(Id,t)),e.datetime=t=>e.check(pc(t)),e.date=t=>e.check(hc(t)),e.time=t=>e.check(gc(t)),e.duration=t=>e.check(vc(t))});function Rc(e){return function(e,t){return new e({type:"string",...or(t)})}(Cc,e)}const jc=Pn("ZodStringFormat",(e,t)=>{wo.init(e,t),Pc.init(e,t)}),Zc=Pn("ZodEmail",(e,t)=>{So.init(e,t),jc.init(e,t)});function Mc(e){return ia(Zc,e)}const Lc=Pn("ZodGUID",(e,t)=>{_o.init(e,t),jc.init(e,t)});function Uc(e){return oa(Lc,e)}const Kc=Pn("ZodUUID",(e,t)=>{bo.init(e,t),jc.init(e,t)});function Jc(e){return sa(Kc,e)}function Hc(e){return aa(Kc,e)}function Fc(e){return ca(Kc,e)}function Vc(e){return da(Kc,e)}const Wc=Pn("ZodURL",(e,t)=>{ko.init(e,t),jc.init(e,t)});function Bc(e){return ua(Wc,e)}function qc(e){return ua(Wc,{protocol:/^https?$/,hostname:ui,...or(e)})}const Yc=Pn("ZodEmoji",(e,t)=>{Io.init(e,t),jc.init(e,t)});function Gc(e){return la(Yc,e)}const Xc=Pn("ZodNanoID",(e,t)=>{zo.init(e,t),jc.init(e,t)});function Qc(e){return pa(Xc,e)}const ed=Pn("ZodCUID",(e,t)=>{Do.init(e,t),jc.init(e,t)});function td(e){return fa(ed,e)}const nd=Pn("ZodCUID2",(e,t)=>{Eo.init(e,t),jc.init(e,t)});function rd(e){return ha(nd,e)}const id=Pn("ZodULID",(e,t)=>{$o.init(e,t),jc.init(e,t)});function od(e){return ma(id,e)}const sd=Pn("ZodXID",(e,t)=>{To.init(e,t),jc.init(e,t)});function ad(e){return ga(sd,e)}const cd=Pn("ZodKSUID",(e,t)=>{Ao.init(e,t),jc.init(e,t)});function dd(e){return ya(cd,e)}const ud=Pn("ZodIPv4",(e,t)=>{Co.init(e,t),jc.init(e,t)});function ld(e){return va(ud,e)}const pd=Pn("ZodMAC",(e,t)=>{jo.init(e,t),jc.init(e,t)});function fd(e){return function(e,t){return new e({type:"string",format:"mac",check:"string_format",abort:!1,...or(t)})}(pd,e)}const hd=Pn("ZodIPv6",(e,t)=>{Ro.init(e,t),jc.init(e,t)});function md(e){return wa(hd,e)}const gd=Pn("ZodCIDRv4",(e,t)=>{Zo.init(e,t),jc.init(e,t)});function yd(e){return _a(gd,e)}const vd=Pn("ZodCIDRv6",(e,t)=>{Mo.init(e,t),jc.init(e,t)});function wd(e){return ba(vd,e)}const _d=Pn("ZodBase64",(e,t)=>{Uo.init(e,t),jc.init(e,t)});function bd(e){return Sa(_d,e)}const Sd=Pn("ZodBase64URL",(e,t)=>{Ko.init(e,t),jc.init(e,t)});function kd(e){return ka(Sd,e)}const Id=Pn("ZodE164",(e,t)=>{Jo.init(e,t),jc.init(e,t)});function zd(e){return Ia(Id,e)}const Dd=Pn("ZodJWT",(e,t)=>{Ho.init(e,t),jc.init(e,t)});function Ed(e){return za(Dd,e)}const $d=Pn("ZodCustomStringFormat",(e,t)=>{Fo.init(e,t),jc.init(e,t)});function Td(e,t,n={}){return tc($d,e,t,n)}function Ad(e){return tc($d,"hostname",di,e)}function xd(e){return tc($d,"hex",Di,e)}function Od(e,t){const n=`${e}_${t?.enc??"hex"}`,i=r[n];if(!i)throw new Error(`Unrecognized hash format: ${n}`);return tc($d,n,i,t)}const Nd=Pn("ZodNumber",(e,t)=>{Vo.init(e,t),Nc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n)=>{const r=n,{minimum:i,maximum:o,format:s,multipleOf:a,exclusiveMaximum:c,exclusiveMinimum:d}=e._zod.bag;"string"==typeof s&&s.includes("int")?r.type="integer":r.type="number","number"==typeof d&&("draft-04"===t.target||"openapi-3.0"===t.target?(r.minimum=d,r.exclusiveMinimum=!0):r.exclusiveMinimum=d),"number"==typeof i&&(r.minimum=i,"number"==typeof d&&"draft-04"!==t.target&&(d>=i?delete r.minimum:delete r.exclusiveMinimum)),"number"==typeof c&&("draft-04"===t.target||"openapi-3.0"===t.target?(r.maximum=c,r.exclusiveMaximum=!0):r.exclusiveMaximum=c),"number"==typeof o&&(r.maximum=o,"number"==typeof c&&"draft-04"!==t.target&&(c<=o?delete r.maximum:delete r.exclusiveMaximum)),"number"==typeof a&&(r.multipleOf=a)})(e,t,n),e.gt=(t,n)=>e.check($a(t,n)),e.gte=(t,n)=>e.check(Ta(t,n)),e.min=(t,n)=>e.check(Ta(t,n)),e.lt=(t,n)=>e.check(Da(t,n)),e.lte=(t,n)=>e.check(Ea(t,n)),e.max=(t,n)=>e.check(Ea(t,n)),e.int=t=>e.check(Rd(t)),e.safe=t=>e.check(Rd(t)),e.positive=t=>e.check($a(0,t)),e.nonnegative=t=>e.check(Ta(0,t)),e.negative=t=>e.check(Da(0,t)),e.nonpositive=t=>e.check(Ea(0,t)),e.multipleOf=(t,n)=>e.check(Pa(t,n)),e.step=(t,n)=>e.check(Pa(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 Pd(e){return function(e,t){return new e({type:"number",checks:[],...or(t)})}(Nd,e)}const Cd=Pn("ZodNumberFormat",(e,t)=>{Wo.init(e,t),Nd.init(e,t)});function Rd(e){return function(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...or(t)})}(Cd,e)}function jd(e){return function(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float32",...or(t)})}(Cd,e)}function Zd(e){return function(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float64",...or(t)})}(Cd,e)}function Md(e){return function(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"int32",...or(t)})}(Cd,e)}function Ld(e){return function(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"uint32",...or(t)})}(Cd,e)}const Ud=Pn("ZodBoolean",(e,t)=>{Bo.init(e,t),Nc.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t,n)=>{n.type="boolean"})(0,0,t)});function Kd(e){return function(e,t){return new e({type:"boolean",...or(t)})}(Ud,e)}const Jd=Pn("ZodBigInt",(e,t)=>{qo.init(e,t),Nc.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(Ta(t,n)),e.min=(t,n)=>e.check(Ta(t,n)),e.gt=(t,n)=>e.check($a(t,n)),e.gte=(t,n)=>e.check(Ta(t,n)),e.min=(t,n)=>e.check(Ta(t,n)),e.lt=(t,n)=>e.check(Da(t,n)),e.lte=(t,n)=>e.check(Ea(t,n)),e.max=(t,n)=>e.check(Ea(t,n)),e.positive=t=>e.check($a(BigInt(0),t)),e.negative=t=>e.check(Da(BigInt(0),t)),e.nonpositive=t=>e.check(Ea(BigInt(0),t)),e.nonnegative=t=>e.check(Ta(BigInt(0),t)),e.multipleOf=(t,n)=>e.check(Pa(t,n));const n=e._zod.bag;e.minValue=n.minimum??null,e.maxValue=n.maximum??null,e.format=n.format??null});function Hd(e){return function(e,t){return new e({type:"bigint",...or(t)})}(Jd,e)}const Fd=Pn("ZodBigIntFormat",(e,t)=>{Yo.init(e,t),Jd.init(e,t)});function Vd(e){return function(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...or(t)})}(Fd,e)}function Wd(e){return function(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...or(t)})}(Fd,e)}const Bd=Pn("ZodSymbol",(e,t)=>{Go.init(e,t),Nc.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 qd(e){return function(e,t){return new e({type:"symbol",...or(t)})}(Bd,e)}const Yd=Pn("ZodUndefined",(e,t)=>{Xo.init(e,t),Nc.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 Gd(e){return function(e,t){return new e({type:"undefined",...or(t)})}(Yd,e)}const Xd=Pn("ZodNull",(e,t)=>{Qo.init(e,t),Nc.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 Qd(e){return function(e,t){return new e({type:"null",...or(t)})}(Xd,e)}const eu=Pn("ZodAny",(e,t)=>{es.init(e,t),Nc.init(e,t),e._zod.processJSONSchema=(e,t,n)=>{}});function tu(){return new eu({type:"any"})}const nu=Pn("ZodUnknown",(e,t)=>{ts.init(e,t),Nc.init(e,t),e._zod.processJSONSchema=(e,t,n)=>{}});function ru(){return new nu({type:"unknown"})}const iu=Pn("ZodNever",(e,t)=>{ns.init(e,t),Nc.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t,n)=>{n.not={}})(0,0,t)});function ou(e){return function(e,t){return new e({type:"never",...or(t)})}(iu,e)}const su=Pn("ZodVoid",(e,t)=>{rs.init(e,t),Nc.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 au(e){return function(e,t){return new e({type:"void",...or(t)})}(su,e)}const cu=Pn("ZodDate",(e,t)=>{is.init(e,t),Nc.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(Ta(t,n)),e.max=(t,n)=>e.check(Ea(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 du(e){return function(e,t){return new e({type:"date",...or(t)})}(cu,e)}const uu=Pn("ZodArray",(e,t)=>{ss.init(e,t),Nc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=n,o=e._zod.def,{minimum:s,maximum:a}=e._zod.bag;"number"==typeof s&&(i.minItems=s),"number"==typeof a&&(i.maxItems=a),i.type="array",i.items=rc(o.element,t,{...r,path:[...r.path,"items"]})})(e,t,n,r),e.element=t.element,e.min=(t,n)=>e.check(Ma(t,n)),e.nonempty=t=>e.check(Ma(1,t)),e.max=(t,n)=>e.check(Za(t,n)),e.length=(t,n)=>e.check(La(t,n)),e.unwrap=()=>e.element});function lu(e,t){return function(e,t,n){return new e({type:"array",element:t,...or(n)})}(uu,e,t)}function pu(e){const t=e._zod.def.shape;return Ru(Object.keys(t))}const fu=Pn("ZodObject",(e,t)=>{ls.init(e,t),Nc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=n,o=e._zod.def;i.type="object",i.properties={};const s=o.shape;for(const e in s)i.properties[e]=rc(s[e],t,{...r,path:[...r.path,"properties",e]});const a=new Set(Object.keys(s)),c=new Set([...a].filter(e=>{const n=o.shape[e]._zod;return"input"===t.io?void 0===n.optin:void 0===n.optout}));c.size>0&&(i.required=Array.from(c)),"never"===o.catchall?._zod.def.type?i.additionalProperties=!1:o.catchall?o.catchall&&(i.additionalProperties=rc(o.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):"output"===t.io&&(i.additionalProperties=!1)})(e,t,n,r),Vn(e,"shape",()=>t.shape),e.keyof=()=>Ru(Object.keys(e._zod.def.shape)),e.catchall=t=>e.clone({...e._zod.def,catchall:t}),e.passthrough=()=>e.clone({...e._zod.def,catchall:ru()}),e.loose=()=>e.clone({...e._zod.def,catchall:ru()}),e.strict=()=>e.clone({...e._zod.def,catchall:ou()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=t=>function(e,t){if(!Qn(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 r=Bn(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return Wn(this,"shape",n),n}});return ir(e,r)}(e,t),e.safeExtend=t=>function(e,t){if(!Qn(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n=Bn(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return Wn(this,"shape",n),n}});return ir(e,n)}(e,t),e.merge=t=>function(e,t){const n=Bn(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t._zod.def.shape};return Wn(this,"shape",n),n},get catchall(){return t._zod.def.catchall},checks:[]});return ir(e,n)}(e,t),e.pick=t=>function(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");return ir(e,Bn(e._zod.def,{get shape(){const e={};for(const r in t){if(!(r in n.shape))throw new Error(`Unrecognized key: "${r}"`);t[r]&&(e[r]=n.shape[r])}return Wn(this,"shape",e),e},checks:[]}))}(e,t),e.omit=t=>function(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const i=Bn(e._zod.def,{get shape(){const r={...e._zod.def.shape};for(const e in t){if(!(e in n.shape))throw new Error(`Unrecognized key: "${e}"`);t[e]&&delete r[e]}return Wn(this,"shape",r),r},checks:[]});return ir(e,i)}(e,t),e.partial=(...t)=>function(e,t,n){const r=t._zod.def.checks;if(r&&r.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");const i=Bn(t._zod.def,{get shape(){const r=t._zod.def.shape,i={...r};if(n)for(const t in n){if(!(t in r))throw new Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=e?new e({type:"optional",innerType:r[t]}):r[t])}else for(const t in r)i[t]=e?new e({type:"optional",innerType:r[t]}):r[t];return Wn(this,"shape",i),i},checks:[]});return ir(t,i)}(Hu,e,t[0]),e.required=(...t)=>function(e,t,n){const r=Bn(t._zod.def,{get shape(){const r=t._zod.def.shape,i={...r};if(n)for(const t in n){if(!(t in i))throw new Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=new e({type:"nonoptional",innerType:r[t]}))}else for(const t in r)i[t]=new e({type:"nonoptional",innerType:r[t]});return Wn(this,"shape",i),i}});return ir(t,r)}(tl,e,t[0])});function hu(e,t){const n={type:"object",shape:e??{},...or(t)};return new fu(n)}function mu(e,t){return new fu({type:"object",shape:e,catchall:ou(),...or(t)})}function gu(e,t){return new fu({type:"object",shape:e,catchall:ru(),...or(t)})}const yu=Pn("ZodUnion",(e,t)=>{fs.init(e,t),Nc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>dc(e,t,n,r),e.options=t.options});function vu(e,t){return new yu({type:"union",options:e,...or(t)})}const wu=Pn("ZodXor",(e,t)=>{yu.init(e,t),ms.init(e,t),e._zod.processJSONSchema=(t,n,r)=>dc(e,t,n,r),e.options=t.options});function _u(e,t){return new wu({type:"union",options:e,inclusive:!1,...or(t)})}const bu=Pn("ZodDiscriminatedUnion",(e,t)=>{yu.init(e,t),gs.init(e,t)});function Su(e,t,n){return new bu({type:"union",options:t,discriminator:e,...or(n)})}const ku=Pn("ZodIntersection",(e,t)=>{ys.init(e,t),Nc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.def,o=rc(i.left,t,{...r,path:[...r.path,"allOf",0]}),s=rc(i.right,t,{...r,path:[...r.path,"allOf",1]}),a=e=>"allOf"in e&&1===Object.keys(e).length,c=[...a(o)?o.allOf:[o],...a(s)?s.allOf:[s]];n.allOf=c})(e,t,n,r)});function Iu(e,t){return new ku({type:"intersection",left:e,right:t})}const zu=Pn("ZodTuple",(e,t)=>{_s.init(e,t),Nc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=n,o=e._zod.def;i.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)=>rc(e,t,{...r,path:[...r.path,s,n]})),d=o.rest?rc(o.rest,t,{...r,path:[...r.path,a,..."openapi-3.0"===t.target?[o.items.length]:[]]}):null;"draft-2020-12"===t.target?(i.prefixItems=c,d&&(i.items=d)):"openapi-3.0"===t.target?(i.items={anyOf:c},d&&i.items.anyOf.push(d),i.minItems=c.length,d||(i.maxItems=c.length)):(i.items=c,d&&(i.additionalItems=d));const{minimum:u,maximum:l}=e._zod.bag;"number"==typeof u&&(i.minItems=u),"number"==typeof l&&(i.maxItems=l)})(e,t,n,r),e.rest=t=>e.clone({...e._zod.def,rest:t})});function Du(e,t,n){const r=t instanceof yo;return new zu({type:"tuple",items:e,rest:r?t:null,...or(r?n:t)})}const Eu=Pn("ZodRecord",(e,t)=>{Ss.init(e,t),Nc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=n,o=e._zod.def;i.type="object";const s=o.keyType,a=s._zod.bag,c=a?.patterns;if("loose"===o.mode&&c&&c.size>0){const e=rc(o.valueType,t,{...r,path:[...r.path,"patternProperties","*"]});i.patternProperties={};for(const t of c)i.patternProperties[t.source]=e}else"draft-07"!==t.target&&"draft-2020-12"!==t.target||(i.propertyNames=rc(o.keyType,t,{...r,path:[...r.path,"propertyNames"]})),i.additionalProperties=rc(o.valueType,t,{...r,path:[...r.path,"additionalProperties"]});const d=s._zod.values;if(d){const e=[...d].filter(e=>"string"==typeof e||"number"==typeof e);e.length>0&&(i.required=e)}})(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function $u(e,t,n){return new Eu({type:"record",keyType:e,valueType:t,...or(n)})}function Tu(e,t,n){const r=ir(e);return r._zod.values=void 0,new Eu({type:"record",keyType:r,valueType:t,...or(n)})}function Au(e,t,n){return new Eu({type:"record",keyType:e,valueType:t,mode:"loose",...or(n)})}const xu=Pn("ZodMap",(e,t)=>{ks.init(e,t),Nc.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(Ra(...t)),e.nonempty=t=>e.check(Ra(1,t)),e.max=(...t)=>e.check(Ca(...t)),e.size=(...t)=>e.check(ja(...t))});function Ou(e,t,n){return new xu({type:"map",keyType:e,valueType:t,...or(n)})}const Nu=Pn("ZodSet",(e,t)=>{zs.init(e,t),Nc.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(Ra(...t)),e.nonempty=t=>e.check(Ra(1,t)),e.max=(...t)=>e.check(Ca(...t)),e.size=(...t)=>e.check(ja(...t))});function Pu(e,t){return new Nu({type:"set",valueType:e,...or(t)})}const Cu=Pn("ZodEnum",(e,t)=>{Es.init(e,t),Nc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n)=>{const r=Mn(e._zod.def.entries);r.every(e=>"number"==typeof e)&&(n.type="number"),r.every(e=>"string"==typeof e)&&(n.type="string"),n.enum=r})(e,0,n),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{const i={};for(const r of e){if(!n.has(r))throw new Error(`Key ${r} not found in enum`);i[r]=t.entries[r]}return new Cu({...t,checks:[],...or(r),entries:i})},e.exclude=(e,r)=>{const i={...t.entries};for(const t of e){if(!n.has(t))throw new Error(`Key ${t} not found in enum`);delete i[t]}return new Cu({...t,checks:[],...or(r),entries:i})}});function Ru(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new Cu({type:"enum",entries:n,...or(t)})}function ju(e,t){return new Cu({type:"enum",entries:e,...or(t)})}const Zu=Pn("ZodLiteral",(e,t)=>{$s.init(e,t),Nc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n)=>{const r=e._zod.def,i=[];for(const e of r.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");i.push(Number(e))}else i.push(e);if(0===i.length);else if(1===i.length){const e=i[0];n.type=null===e?"null":typeof e,"draft-04"===t.target||"openapi-3.0"===t.target?n.enum=[e]:n.const=e}else i.every(e=>"number"==typeof e)&&(n.type="number"),i.every(e=>"string"==typeof e)&&(n.type="string"),i.every(e=>"boolean"==typeof e)&&(n.type="boolean"),i.every(e=>null===e)&&(n.type="null"),n.enum=i})(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 Mu(e,t){return new Zu({type:"literal",values:Array.isArray(e)?e:[e],...or(t)})}const Lu=Pn("ZodFile",(e,t)=>{Ts.init(e,t),Nc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n)=>{const r=n,i={type:"string",format:"binary",contentEncoding:"binary"},{minimum:o,maximum:s,mime:a}=e._zod.bag;void 0!==o&&(i.minLength=o),void 0!==s&&(i.maxLength=s),a?1===a.length?(i.contentMediaType=a[0],Object.assign(r,i)):(Object.assign(r,i),r.anyOf=a.map(e=>({contentMediaType:e}))):Object.assign(r,i)})(e,0,n),e.min=(t,n)=>e.check(Ra(t,n)),e.max=(t,n)=>e.check(Ca(t,n)),e.mime=(t,n)=>e.check(Ba(Array.isArray(t)?t:[t],n))});function Uu(e){return function(e,t){return new e({type:"file",...or(t)})}(Lu,e)}const Ku=Pn("ZodTransform",(e,t)=>{As.init(e,t),Nc.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,r)=>{if("backward"===r.direction)throw new Rn(e.constructor.name);n.addIssue=r=>{if("string"==typeof r)n.issues.push(mr(r,n.value,t));else{const t=r;t.fatal&&(t.continue=!1),t.code??(t.code="custom"),t.input??(t.input=n.value),t.inst??(t.inst=e),n.issues.push(mr(t))}};const i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n)):(n.value=i,n)}});function Ju(e){return new Ku({type:"transform",transform:e})}const Hu=Pn("ZodOptional",(e,t)=>{Os.init(e,t),Nc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>uc(e,t,0,r),e.unwrap=()=>e._zod.def.innerType});function Fu(e){return new Hu({type:"optional",innerType:e})}const Vu=Pn("ZodExactOptional",(e,t)=>{Ns.init(e,t),Nc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>uc(e,t,0,r),e.unwrap=()=>e._zod.def.innerType});function Wu(e){return new Vu({type:"optional",innerType:e})}const Bu=Pn("ZodNullable",(e,t)=>{Ps.init(e,t),Nc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.def,o=rc(i.innerType,t,r),s=t.seen.get(e);"openapi-3.0"===t.target?(s.ref=i.innerType,n.nullable=!0):n.anyOf=[o,{type:"null"}]})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function qu(e){return new Bu({type:"nullable",innerType:e})}function Yu(e){return Fu(qu(e))}const Gu=Pn("ZodDefault",(e,t)=>{Cs.init(e,t),Nc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.def;rc(i.innerType,t,r),t.seen.get(e).ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Xu(e,t){return new Gu({type:"default",innerType:e,get defaultValue(){return"function"==typeof t?t():er(t)}})}const Qu=Pn("ZodPrefault",(e,t)=>{js.init(e,t),Nc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.def;rc(i.innerType,t,r),t.seen.get(e).ref=i.innerType,"input"===t.io&&(n._prefault=JSON.parse(JSON.stringify(i.defaultValue)))})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function el(e,t){return new Qu({type:"prefault",innerType:e,get defaultValue(){return"function"==typeof t?t():er(t)}})}const tl=Pn("ZodNonOptional",(e,t)=>{Zs.init(e,t),Nc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.def;rc(i.innerType,t,r),t.seen.get(e).ref=i.innerType})(e,t,0,r),e.unwrap=()=>e._zod.def.innerType});function nl(e,t){return new tl({type:"nonoptional",innerType:e,...or(t)})}const rl=Pn("ZodSuccess",(e,t)=>{Ls.init(e,t),Nc.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 il(e){return new rl({type:"success",innerType:e})}const ol=Pn("ZodCatch",(e,t)=>{Us.init(e,t),Nc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.def;let o;rc(i.innerType,t,r),t.seen.get(e).ref=i.innerType;try{o=i.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=o})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function sl(e,t){return new ol({type:"catch",innerType:e,catchValue:"function"==typeof t?t:()=>t})}const al=Pn("ZodNaN",(e,t)=>{Ks.init(e,t),Nc.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 cl(e){return function(e,t){return new e({type:"nan",...or(t)})}(al,e)}const dl=Pn("ZodPipe",(e,t)=>{Js.init(e,t),Nc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.def,o="input"===t.io?"transform"===i.in._zod.def.type?i.out:i.in:i.out;rc(o,t,r),t.seen.get(e).ref=o})(e,t,0,r),e.in=t.in,e.out=t.out});function ul(e,t){return new dl({type:"pipe",in:e,out:t})}const ll=Pn("ZodCodec",(e,t)=>{dl.init(e,t),Fs.init(e,t)});function pl(e,t,n){return new ll({type:"pipe",in:e,out:t,transform:n.decode,reverseTransform:n.encode})}const fl=Pn("ZodReadonly",(e,t)=>{Bs.init(e,t),Nc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.def;rc(i.innerType,t,r),t.seen.get(e).ref=i.innerType,n.readOnly=!0})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function hl(e){return new fl({type:"readonly",innerType:e})}const ml=Pn("ZodTemplateLiteral",(e,t)=>{Ys.init(e,t),Nc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n)=>{const r=n,i=e._zod.pattern;if(!i)throw new Error("Pattern not found in template literal");r.type="string",r.pattern=i.source})(e,0,n)});function gl(e,t){return new ml({type:"template_literal",parts:e,...or(t)})}const yl=Pn("ZodLazy",(e,t)=>{Qs.init(e,t),Nc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.innerType;rc(i,t,r),t.seen.get(e).ref=i})(e,t,0,r),e.unwrap=()=>e._zod.def.getter()});function vl(e){return new yl({type:"lazy",getter:e})}const wl=Pn("ZodPromise",(e,t)=>{Xs.init(e,t),Nc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.def;rc(i.innerType,t,r),t.seen.get(e).ref=i.innerType})(e,t,0,r),e.unwrap=()=>e._zod.def.innerType});function _l(e){return new wl({type:"promise",innerType:e})}const bl=Pn("ZodFunction",(e,t)=>{Gs.init(e,t),Nc.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 Sl(e){return new bl({type:"function",input:Array.isArray(e?.input)?Du(e?.input):e?.input??lu(ru()),output:e?.output??ru()})}const kl=Pn("ZodCustom",(e,t)=>{ea.init(e,t),Nc.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 Il(e){const t=new Hi({check:"custom"});return t._zod.check=e,t}function zl(e,t){return function(e,t,n){const r=or(n);return r.abort??(r.abort=!0),new e({type:"custom",check:"custom",fn:t,...r})}(kl,e??(()=>!0),t)}function Dl(e,t={}){return function(e,t,n){return new e({type:"custom",check:"custom",fn:t,...or(n)})}(kl,e,t)}function El(e){return function(e){const t=function(e){const t=new Hi({check:"custom",...or(void 0)});return t._zod.check=e,t}(n=>(n.addIssue=e=>{if("string"==typeof e)n.issues.push(mr(e,n.value,t._zod.def));else{const r=e;r.fatal&&(r.continue=!1),r.code??(r.code="custom"),r.input??(r.input=n.value),r.inst??(r.inst=t),r.continue??(r.continue=!t._zod.def.abort),n.issues.push(mr(r))}},e(n.value,n)));return t}(e)}const $l=function(e){const t=new Hi({check:"describe"});return t._zod.onattach=[t=>{const n=ra.get(t)??{};ra.add(t,{...n,description:e})}],t._zod.check=()=>{},t},Tl=function(e){const t=new Hi({check:"meta"});return t._zod.onattach=[t=>{const n=ra.get(t)??{};ra.add(t,{...n,...e})}],t._zod.check=()=>{},t};function Al(e,t={}){const n=new kl({type:"custom",check:"custom",fn:t=>t instanceof e,abort:!0,...or(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 xl=(...e)=>function(e,t){const n=or(t);let r=n.truthy??["true","1","yes","on","y","enabled"],i=n.falsy??["false","0","no","off","n","disabled"];"sensitive"!==n.case&&(r=r.map(e=>"string"==typeof e?e.toLowerCase():e),i=i.map(e=>"string"==typeof e?e.toLowerCase():e));const o=new Set(r),s=new Set(i),a=e.Codec??Fs,c=e.Boolean??Bo,d=new a({type:"pipe",in:new(e.String??vo)({type:"string",error:n.error}),out:new c({type:"boolean",error:n.error}),transform:(e,t)=>{let r=e;return"sensitive"!==n.case&&(r=r.toLowerCase()),!!o.has(r)||!s.has(r)&&(t.issues.push({code:"invalid_value",expected:"stringbool",values:[...o,...s],input:t.value,inst:d,continue:!1}),{})},reverseTransform:(e,t)=>!0===e?r[0]||"true":i[0]||"false",error:n.error});return d}({Codec:ll,Boolean:Ud,String:Cc},...e);function Ol(e){const t=vl(()=>vu([Rc(e),Pd(),Kd(),Qd(),lu(t),$u(Rc(),t)]));return t}function Nl(e,t){return ul(Ju(e),t)}var Pl;async function Cl(e){const t=await e.generateKeyPair(),n=Be(t.publicKey);return{did:n,kid:`${n}#${qe(n)}`,privateKey:t.privateKey,publicKey:t.publicKey}}async function Rl(e,t){const n=Nn({identity:t.identity??await Cl(t.crypto),session:t.session,delegation:t.delegation,autoSession:t.autoSession??!0},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:Ru(xn).describe("Protocol operation to perform"),nonce:Rc().optional().describe("Client-generated unique nonce (handshake)"),audience:Rc().optional().describe("Intended audience (handshake)"),timestamp:Pd().optional().describe("Unix epoch seconds (handshake)"),agentDid:Rc().optional().describe("Client agent DID (handshake, optional)")}},async e=>{const t=await n.handleKyaOs(e);return{...t,content:t.content.map(e=>({...e,type:"text"}))}}),!1!==t.proofAllTools){const r=["_kyaos","_kyaos_handshake",...t.excludeTools??[]],i=e.connect.bind(e);e.connect=e=>i(function(e,t,n=["_kyaos","_kyaos_handshake"]){const r=new Map,i={start:()=>e.start(),close:()=>e.close(),set onmessage(t){e.onmessage=t},get onmessage(){return e.onmessage},set onclose(t){e.onclose=t},get onclose(){return e.onclose},set onerror(t){e.onerror=t},get onerror(){return e.onerror},async send(n){const i=n.id,o=void 0!==i?r.get(i):void 0;if(o){r.delete(i);try{const e=n.result;if(e&&!e.isError){const r=async()=>e,i=t.wrapWithProof(o.toolName,r),s=await i(o.args);void 0!==s._meta&&(n={...n,result:s})}}catch(e){Xe.error("[kya-os-transport] Proof injection failed",{tool:o.toolName,error:e instanceof Error?e.message:String(e)});const t=n.result;t&&(t._meta={proofError:"Proof generation failed — response is unproven"},n={...n,result:t})}}return e.send(n)}},o=e.start.bind(e);return i.start=async()=>{await o();const t=e.onmessage;e.onmessage=e=>{if("tools/call"===e.method&&void 0!==e.id){const t=e.params,i=t?.name;i&&!n.includes(i)&&r.set(e.id,{toolName:i,args:t?.arguments??{}})}t?.(e)}},i}(e,n,r))}return n}Pl||(Pl={}),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"]),Zn({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"},r={nan:"NaN"};return e=>{switch(e.code){case"invalid_type":{const t=r[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 ${r[n]??n}`}case"invalid_value":return 1===e.values.length?`Invalid input: expected ${sr(e.values[0])}`:`Invalid option: expected one of ${Ln(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Too big: expected ${e.origin??"value"} to have ${n}${e.maximum.toString()} ${r.unit??"elements"}`:`Too big: expected ${e.origin??"value"} to be ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Too small: expected ${e.origin} to have ${n}${e.minimum.toString()} ${r.unit}`:`Too small: expected ${e.origin} to be ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Invalid string: must start with "${t.prefix}"`:"ends_with"===t.format?`Invalid string: must end with "${t.suffix}"`:"includes"===t.format?`Invalid string: must include "${t.includes}"`:"regex"===t.format?`Invalid string: must match pattern ${t.pattern}`:`Invalid ${n[t.format]??e.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${e.divisor}`;case"unrecognized_keys":return`Unrecognized key${e.keys.length>1?"s":""}: ${Ln(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}`}}})()})}};
|