diff --git a/plugin/scripts/worker-service.cjs b/plugin/scripts/worker-service.cjs index dff1fe77..cfd6a958 100755 --- a/plugin/scripts/worker-service.cjs +++ b/plugin/scripts/worker-service.cjs @@ -747,7 +747,7 @@ IMPORTANT: This is not the end of the session. You will receive more requests to `))})}async supportedCommands(){return(await this.initialization).commands}async supportedModels(){return(await this.initialization).models}async mcpServerStatus(){return(await this.request({subtype:"mcp_status"})).response.mcpServers}async accountInfo(){return(await this.initialization).account}async streamInput(e){Jr("[Query.streamInput] Starting to process input stream"),Jr(`[Query.streamInput] this.sdkMcpTransports.size = ${this.sdkMcpTransports.size}`);try{let a=0;for await(let t of e){if(a++,Jr(`[Query.streamInput] Processing message ${a}: ${t.type}`),this.abortController?.signal.aborted)break;await Promise.resolve(this.transport.write(JSON.stringify(t)+` `))}if(Jr(`[Query.streamInput] Finished processing ${a} messages from input stream`),Jr(`[Query.streamInput] About to check MCP servers. this.sdkMcpTransports.size = ${this.sdkMcpTransports.size}`),this.sdkMcpTransports.size>0&&this.firstResultReceivedPromise){Jr("[Query.streamInput] Entering Promise.race to wait for result");let t=1e4,s;await Promise.race([this.firstResultReceivedPromise.then(()=>{Jr("[Query.streamInput] Received first result, closing input stream"),s&&clearTimeout(s)}),new Promise(i=>{s=setTimeout(()=>{Jr("[Query.streamInput] Timed out waiting for first result, closing input stream"),i()},t)})]),s&&clearTimeout(s)}Jr("[Query] Calling transport.endInput() to close stdin to CLI process"),this.transport.endInput()}catch(a){if(!(a instanceof ds))throw a}}handleHookCallbacks(e,a,t,s){let i=this.hookCallbacks.get(e);if(!i)throw new Error(`No hook callback found for ID: ${e}`);return i(a,t,{signal:s})}sendMcpServerMessageToCli(e,a){if("id"in a&&a.id!==null&&a.id!==void 0){let t=`${e}:${a.id}`,s=this.pendingMcpResponses.get(t);if(s){s.resolve(a),this.pendingMcpResponses.delete(t);return}}throw new Error("No pending request found")}handleMcpControlRequest(e,a,t){let s="id"in a.message?a.message.id:null,i=`${e}:${s}`;return new Promise((n,o)=>{let l=null,c=()=>{l&&clearTimeout(l),this.pendingMcpResponses.delete(i)},u=m=>{c(),n(m)},f=m=>{c(),o(m)};if(this.pendingMcpResponses.set(i,{resolve:u,reject:f}),t.onmessage)t.onmessage(a.message);else{c(),o(new Error("No message handler registered"));return}l=setTimeout(()=>{this.pendingMcpResponses.has(i)&&(c(),o(new Error("Request timeout")))},3e4)})}},w={};xj(w,{void:()=>M6,util:()=>Ze,unknown:()=>F6,union:()=>B6,undefined:()=>D6,tuple:()=>G6,transformer:()=>V1,symbol:()=>N6,string:()=>yE,strictObject:()=>H6,setErrorMap:()=>n6,set:()=>K6,record:()=>W6,quotelessJson:()=>a6,promise:()=>r5,preprocess:()=>n5,pipeline:()=>i5,ostring:()=>o5,optional:()=>a5,onumber:()=>c5,oboolean:()=>l5,objectUtil:()=>Pd,object:()=>z6,number:()=>bE,nullable:()=>s5,null:()=>$6,never:()=>L6,nativeEnum:()=>t5,nan:()=>I6,map:()=>Q6,makeIssue:()=>Hc,literal:()=>Y6,lazy:()=>J6,late:()=>O6,isValid:()=>ms,isDirty:()=>Td,isAsync:()=>Ti,isAborted:()=>Rd,intersection:()=>Z6,instanceof:()=>C6,getParsedType:()=>ea,getErrorMap:()=>zc,function:()=>X6,enum:()=>e5,effect:()=>V1,discriminatedUnion:()=>V6,defaultErrorMap:()=>xn,datetimeRegex:()=>hE,date:()=>j6,custom:()=>gE,coerce:()=>u5,boolean:()=>xE,bigint:()=>A6,array:()=>U6,any:()=>q6,addIssueToContext:()=>se,ZodVoid:()=>En,ZodUnknown:()=>ra,ZodUnion:()=>_s,ZodUndefined:()=>bs,ZodType:()=>je,ZodTuple:()=>Lr,ZodTransformer:()=>Qt,ZodSymbol:()=>_n,ZodString:()=>Ra,ZodSet:()=>Sn,ZodSchema:()=>je,ZodRecord:()=>Vc,ZodReadonly:()=>Os,ZodPromise:()=>ka,ZodPipeline:()=>Oi,ZodParsedType:()=>le,ZodOptional:()=>pr,ZodObject:()=>Lt,ZodNumber:()=>hs,ZodNullable:()=>Mr,ZodNull:()=>xs,ZodNever:()=>Sr,ZodNativeEnum:()=>Rs,ZodNaN:()=>Pn,ZodMap:()=>wn,ZodLiteral:()=>Ss,ZodLazy:()=>ws,ZodIssueCode:()=>J,ZodIntersection:()=>Es,ZodFunction:()=>Zc,ZodFirstPartyTypeKind:()=>Pe,ZodError:()=>Wt,ZodEnum:()=>Ps,ZodEffects:()=>Qt,ZodDiscriminatedUnion:()=>Bc,ZodDefault:()=>Ts,ZodDate:()=>ys,ZodCatch:()=>ks,ZodBranded:()=>ki,ZodBoolean:()=>gs,ZodBigInt:()=>vs,ZodArray:()=>aa,ZodAny:()=>Ta,Schema:()=>je,ParseStatus:()=>Pt,OK:()=>kt,NEVER:()=>p5,INVALID:()=>we,EMPTY_PATH:()=>i6,DIRTY:()=>bn,BRAND:()=>k6});var Ze;(function(r){r.assertEqual=s=>{};function e(s){}r.assertIs=e;function a(s){throw new Error}r.assertNever=a,r.arrayToEnum=s=>{let i={};for(let n of s)i[n]=n;return i},r.getValidEnumValues=s=>{let i=r.objectKeys(s).filter(o=>typeof s[s[o]]!="number"),n={};for(let o of i)n[o]=s[o];return r.objectValues(n)},r.objectValues=s=>r.objectKeys(s).map(function(i){return s[i]}),r.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{let i=[];for(let n in s)Object.prototype.hasOwnProperty.call(s,n)&&i.push(n);return i},r.find=(s,i)=>{for(let n of s)if(i(n))return n},r.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function t(s,i=" | "){return s.map(n=>typeof n=="string"?`'${n}'`:n).join(i)}r.joinValues=t,r.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})(Ze||(Ze={}));var Pd;(function(r){r.mergeShapes=(e,a)=>({...e,...a})})(Pd||(Pd={}));var le=Ze.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ea=r=>{switch(typeof r){case"undefined":return le.undefined;case"string":return le.string;case"number":return Number.isNaN(r)?le.nan:le.number;case"boolean":return le.boolean;case"function":return le.function;case"bigint":return le.bigint;case"symbol":return le.symbol;case"object":return Array.isArray(r)?le.array:r===null?le.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?le.promise:typeof Map<"u"&&r instanceof Map?le.map:typeof Set<"u"&&r instanceof Set?le.set:typeof Date<"u"&&r instanceof Date?le.date:le.object;default:return le.unknown}},J=Ze.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),a6=r=>JSON.stringify(r,null,2).replace(/"([^"]+)":/g,"$1:"),Wt=class r extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=t=>{this.issues=[...this.issues,t]},this.addIssues=(t=[])=>{this.issues=[...this.issues,...t]};let a=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,a):this.__proto__=a,this.name="ZodError",this.issues=e}format(e){let a=e||function(i){return i.message},t={_errors:[]},s=i=>{for(let n of i.issues)if(n.code==="invalid_union")n.unionErrors.map(s);else if(n.code==="invalid_return_type")s(n.returnTypeError);else if(n.code==="invalid_arguments")s(n.argumentsError);else if(n.path.length===0)t._errors.push(a(n));else{let o=t,l=0;for(;la.message){let a={},t=[];for(let s of this.issues)if(s.path.length>0){let i=s.path[0];a[i]=a[i]||[],a[i].push(e(s))}else t.push(e(s));return{formErrors:t,fieldErrors:a}}get formErrors(){return this.flatten()}};Wt.create=r=>new Wt(r);var s6=(r,e)=>{let a;switch(r.code){case J.invalid_type:r.received===le.undefined?a="Required":a=`Expected ${r.expected}, received ${r.received}`;break;case J.invalid_literal:a=`Invalid literal value, expected ${JSON.stringify(r.expected,Ze.jsonStringifyReplacer)}`;break;case J.unrecognized_keys:a=`Unrecognized key(s) in object: ${Ze.joinValues(r.keys,", ")}`;break;case J.invalid_union:a="Invalid input";break;case J.invalid_union_discriminator:a=`Invalid discriminator value. Expected ${Ze.joinValues(r.options)}`;break;case J.invalid_enum_value:a=`Invalid enum value. Expected ${Ze.joinValues(r.options)}, received '${r.received}'`;break;case J.invalid_arguments:a="Invalid function arguments";break;case J.invalid_return_type:a="Invalid function return type";break;case J.invalid_date:a="Invalid date";break;case J.invalid_string:typeof r.validation=="object"?"includes"in r.validation?(a=`Invalid input: must include "${r.validation.includes}"`,typeof r.validation.position=="number"&&(a=`${a} at one or more positions greater than or equal to ${r.validation.position}`)):"startsWith"in r.validation?a=`Invalid input: must start with "${r.validation.startsWith}"`:"endsWith"in r.validation?a=`Invalid input: must end with "${r.validation.endsWith}"`:Ze.assertNever(r.validation):r.validation!=="regex"?a=`Invalid ${r.validation}`:a="Invalid";break;case J.too_small:r.type==="array"?a=`Array must contain ${r.exact?"exactly":r.inclusive?"at least":"more than"} ${r.minimum} element(s)`:r.type==="string"?a=`String must contain ${r.exact?"exactly":r.inclusive?"at least":"over"} ${r.minimum} character(s)`:r.type==="number"?a=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="bigint"?a=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="date"?a=`Date must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(r.minimum))}`:a="Invalid input";break;case J.too_big:r.type==="array"?a=`Array must contain ${r.exact?"exactly":r.inclusive?"at most":"less than"} ${r.maximum} element(s)`:r.type==="string"?a=`String must contain ${r.exact?"exactly":r.inclusive?"at most":"under"} ${r.maximum} character(s)`:r.type==="number"?a=`Number must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="bigint"?a=`BigInt must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="date"?a=`Date must be ${r.exact?"exactly":r.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(r.maximum))}`:a="Invalid input";break;case J.custom:a="Invalid input";break;case J.invalid_intersection_types:a="Intersection results could not be merged";break;case J.not_multiple_of:a=`Number must be a multiple of ${r.multipleOf}`;break;case J.not_finite:a="Number must be finite";break;default:a=e.defaultError,Ze.assertNever(r)}return{message:a}},xn=s6,dE=xn;function n6(r){dE=r}function zc(){return dE}var Hc=r=>{let{data:e,path:a,errorMaps:t,issueData:s}=r,i=[...a,...s.path||[]],n={...s,path:i};if(s.message!==void 0)return{...s,path:i,message:s.message};let o="",l=t.filter(c=>!!c).slice().reverse();for(let c of l)o=c(n,{data:e,defaultError:o}).message;return{...s,path:i,message:o}},i6=[];function se(r,e){let a=zc(),t=Hc({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,a,a===xn?void 0:xn].filter(s=>!!s)});r.common.issues.push(t)}var Pt=class r{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,a){let t=[];for(let s of a){if(s.status==="aborted")return we;s.status==="dirty"&&e.dirty(),t.push(s.value)}return{status:e.value,value:t}}static async mergeObjectAsync(e,a){let t=[];for(let s of a){let i=await s.key,n=await s.value;t.push({key:i,value:n})}return r.mergeObjectSync(e,t)}static mergeObjectSync(e,a){let t={};for(let s of a){let{key:i,value:n}=s;if(i.status==="aborted"||n.status==="aborted")return we;i.status==="dirty"&&e.dirty(),n.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof n.value<"u"||s.alwaysSet)&&(t[i.value]=n.value)}return{status:e.value,value:t}}},we=Object.freeze({status:"aborted"}),bn=r=>({status:"dirty",value:r}),kt=r=>({status:"valid",value:r}),Rd=r=>r.status==="aborted",Td=r=>r.status==="dirty",ms=r=>r.status==="valid",Ti=r=>typeof Promise<"u"&&r instanceof Promise,me;(function(r){r.errToObj=e=>typeof e=="string"?{message:e}:e||{},r.toString=e=>typeof e=="string"?e:e?.message})(me||(me={}));var dr=class{constructor(e,a,t,s){this._cachedPath=[],this.parent=e,this.data=a,this._path=t,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},H1=(r,e)=>{if(ms(e))return{success:!0,data:e.value};if(!r.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let a=new Wt(r.common.issues);return this._error=a,this._error}}};function $e(r){if(!r)return{};let{errorMap:e,invalid_type_error:a,required_error:t,description:s}=r;if(e&&(a||t))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(n,o)=>{let{message:l}=r;return n.code==="invalid_enum_value"?{message:l??o.defaultError}:typeof o.data>"u"?{message:l??t??o.defaultError}:n.code!=="invalid_type"?{message:o.defaultError}:{message:l??a??o.defaultError}},description:s}}var je=class{get description(){return this._def.description}_getType(e){return ea(e.data)}_getOrReturnCtx(e,a){return a||{common:e.parent.common,data:e.data,parsedType:ea(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Pt,ctx:{common:e.parent.common,data:e.data,parsedType:ea(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let a=this._parse(e);if(Ti(a))throw new Error("Synchronous parse encountered promise.");return a}_parseAsync(e){let a=this._parse(e);return Promise.resolve(a)}parse(e,a){let t=this.safeParse(e,a);if(t.success)return t.data;throw t.error}safeParse(e,a){let t={common:{issues:[],async:a?.async??!1,contextualErrorMap:a?.errorMap},path:a?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ea(e)},s=this._parseSync({data:e,path:t.path,parent:t});return H1(t,s)}"~validate"(e){let a={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ea(e)};if(!this["~standard"].async)try{let t=this._parseSync({data:e,path:[],parent:a});return ms(t)?{value:t.value}:{issues:a.common.issues}}catch(t){t?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),a.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:a}).then(t=>ms(t)?{value:t.value}:{issues:a.common.issues})}async parseAsync(e,a){let t=await this.safeParseAsync(e,a);if(t.success)return t.data;throw t.error}async safeParseAsync(e,a){let t={common:{issues:[],contextualErrorMap:a?.errorMap,async:!0},path:a?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ea(e)},s=this._parse({data:e,path:t.path,parent:t}),i=await(Ti(s)?s:Promise.resolve(s));return H1(t,i)}refine(e,a){let t=s=>typeof a=="string"||typeof a>"u"?{message:a}:typeof a=="function"?a(s):a;return this._refinement((s,i)=>{let n=e(s),o=()=>i.addIssue({code:J.custom,...t(s)});return typeof Promise<"u"&&n instanceof Promise?n.then(l=>l?!0:(o(),!1)):n?!0:(o(),!1)})}refinement(e,a){return this._refinement((t,s)=>e(t)?!0:(s.addIssue(typeof a=="function"?a(t,s):a),!1))}_refinement(e){return new Qt({schema:this,typeName:Pe.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:a=>this["~validate"](a)}}optional(){return pr.create(this,this._def)}nullable(){return Mr.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return aa.create(this)}promise(){return ka.create(this,this._def)}or(e){return _s.create([this,e],this._def)}and(e){return Es.create(this,e,this._def)}transform(e){return new Qt({...$e(this._def),schema:this,typeName:Pe.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let a=typeof e=="function"?e:()=>e;return new Ts({...$e(this._def),innerType:this,defaultValue:a,typeName:Pe.ZodDefault})}brand(){return new ki({typeName:Pe.ZodBranded,type:this,...$e(this._def)})}catch(e){let a=typeof e=="function"?e:()=>e;return new ks({...$e(this._def),innerType:this,catchValue:a,typeName:Pe.ZodCatch})}describe(e){let a=this.constructor;return new a({...this._def,description:e})}pipe(e){return Oi.create(this,e)}readonly(){return Os.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},o6=/^c[^\s-]{8,}$/i,c6=/^[0-9a-z]+$/,l6=/^[0-9A-HJKMNP-TV-Z]{26}$/i,u6=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,p6=/^[a-z0-9_-]{21}$/i,d6=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,f6=/^[-+]?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)?)??$/,m6=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,h6="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",gd,v6=/^(?:(?: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])$/,g6=/^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/,y6=/^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,b6=/^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,x6=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,_6=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,fE="((\\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])))",E6=new RegExp(`^${fE}$`);function mE(r){let e="[0-5]\\d";r.precision?e=`${e}\\.\\d{${r.precision}}`:r.precision==null&&(e=`${e}(\\.\\d+)?`);let a=r.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${a}`}function w6(r){return new RegExp(`^${mE(r)}$`)}function hE(r){let e=`${fE}T${mE(r)}`,a=[];return a.push(r.local?"Z?":"Z"),r.offset&&a.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${a.join("|")})`,new RegExp(`^${e}$`)}function S6(r,e){return!!((e==="v4"||!e)&&v6.test(r)||(e==="v6"||!e)&&y6.test(r))}function P6(r,e){if(!d6.test(r))return!1;try{let[a]=r.split(".");if(!a)return!1;let t=a.replace(/-/g,"+").replace(/_/g,"/").padEnd(a.length+(4-a.length%4)%4,"="),s=JSON.parse(atob(t));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function R6(r,e){return!!((e==="v4"||!e)&&g6.test(r)||(e==="v6"||!e)&&b6.test(r))}var Ra=class r extends je{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==le.string){let i=this._getOrReturnCtx(e);return se(i,{code:J.invalid_type,expected:le.string,received:i.parsedType}),we}let t=new Pt,s;for(let i of this._def.checks)if(i.kind==="min")e.data.lengthi.value&&(s=this._getOrReturnCtx(e,s),se(s,{code:J.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),t.dirty());else if(i.kind==="length"){let n=e.data.length>i.value,o=e.data.lengthe.test(s),{validation:a,code:J.invalid_string,...me.errToObj(t)})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...me.errToObj(e)})}url(e){return this._addCheck({kind:"url",...me.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...me.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...me.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...me.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...me.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...me.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...me.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...me.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...me.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...me.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...me.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...me.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...me.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...me.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...me.errToObj(e)})}regex(e,a){return this._addCheck({kind:"regex",regex:e,...me.errToObj(a)})}includes(e,a){return this._addCheck({kind:"includes",value:e,position:a?.position,...me.errToObj(a?.message)})}startsWith(e,a){return this._addCheck({kind:"startsWith",value:e,...me.errToObj(a)})}endsWith(e,a){return this._addCheck({kind:"endsWith",value:e,...me.errToObj(a)})}min(e,a){return this._addCheck({kind:"min",value:e,...me.errToObj(a)})}max(e,a){return this._addCheck({kind:"max",value:e,...me.errToObj(a)})}length(e,a){return this._addCheck({kind:"length",value:e,...me.errToObj(a)})}nonempty(e){return this.min(1,me.errToObj(e))}trim(){return new r({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let a of this._def.checks)a.kind==="min"&&(e===null||a.value>e)&&(e=a.value);return e}get maxLength(){let e=null;for(let a of this._def.checks)a.kind==="max"&&(e===null||a.valuenew Ra({checks:[],typeName:Pe.ZodString,coerce:r?.coerce??!1,...$e(r)});function T6(r,e){let a=(r.toString().split(".")[1]||"").length,t=(e.toString().split(".")[1]||"").length,s=a>t?a:t,i=Number.parseInt(r.toFixed(s).replace(".","")),n=Number.parseInt(e.toFixed(s).replace(".",""));return i%n/10**s}var hs=class r extends je{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==le.number){let i=this._getOrReturnCtx(e);return se(i,{code:J.invalid_type,expected:le.number,received:i.parsedType}),we}let t,s=new Pt;for(let i of this._def.checks)i.kind==="int"?Ze.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),se(t,{code:J.invalid_type,expected:"integer",received:"float",message:i.message}),s.dirty()):i.kind==="min"?(i.inclusive?e.datai.value:e.data>=i.value)&&(t=this._getOrReturnCtx(e,t),se(t,{code:J.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?T6(e.data,i.value)!==0&&(t=this._getOrReturnCtx(e,t),se(t,{code:J.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),se(t,{code:J.not_finite,message:i.message}),s.dirty()):Ze.assertNever(i);return{status:s.value,value:e.data}}gte(e,a){return this.setLimit("min",e,!0,me.toString(a))}gt(e,a){return this.setLimit("min",e,!1,me.toString(a))}lte(e,a){return this.setLimit("max",e,!0,me.toString(a))}lt(e,a){return this.setLimit("max",e,!1,me.toString(a))}setLimit(e,a,t,s){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:a,inclusive:t,message:me.toString(s)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:me.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:me.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:me.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:me.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:me.toString(e)})}multipleOf(e,a){return this._addCheck({kind:"multipleOf",value:e,message:me.toString(a)})}finite(e){return this._addCheck({kind:"finite",message:me.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:me.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:me.toString(e)})}get minValue(){let e=null;for(let a of this._def.checks)a.kind==="min"&&(e===null||a.value>e)&&(e=a.value);return e}get maxValue(){let e=null;for(let a of this._def.checks)a.kind==="max"&&(e===null||a.valuee.kind==="int"||e.kind==="multipleOf"&&Ze.isInteger(e.value))}get isFinite(){let e=null,a=null;for(let t of this._def.checks){if(t.kind==="finite"||t.kind==="int"||t.kind==="multipleOf")return!0;t.kind==="min"?(a===null||t.value>a)&&(a=t.value):t.kind==="max"&&(e===null||t.valuenew hs({checks:[],typeName:Pe.ZodNumber,coerce:r?.coerce||!1,...$e(r)});var vs=class r extends je{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==le.bigint)return this._getInvalidInput(e);let t,s=new Pt;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?e.datai.value:e.data>=i.value)&&(t=this._getOrReturnCtx(e,t),se(t,{code:J.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),se(t,{code:J.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):Ze.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){let a=this._getOrReturnCtx(e);return se(a,{code:J.invalid_type,expected:le.bigint,received:a.parsedType}),we}gte(e,a){return this.setLimit("min",e,!0,me.toString(a))}gt(e,a){return this.setLimit("min",e,!1,me.toString(a))}lte(e,a){return this.setLimit("max",e,!0,me.toString(a))}lt(e,a){return this.setLimit("max",e,!1,me.toString(a))}setLimit(e,a,t,s){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:a,inclusive:t,message:me.toString(s)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:me.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:me.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:me.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:me.toString(e)})}multipleOf(e,a){return this._addCheck({kind:"multipleOf",value:e,message:me.toString(a)})}get minValue(){let e=null;for(let a of this._def.checks)a.kind==="min"&&(e===null||a.value>e)&&(e=a.value);return e}get maxValue(){let e=null;for(let a of this._def.checks)a.kind==="max"&&(e===null||a.valuenew vs({checks:[],typeName:Pe.ZodBigInt,coerce:r?.coerce??!1,...$e(r)});var gs=class extends je{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==le.boolean){let t=this._getOrReturnCtx(e);return se(t,{code:J.invalid_type,expected:le.boolean,received:t.parsedType}),we}return kt(e.data)}};gs.create=r=>new gs({typeName:Pe.ZodBoolean,coerce:r?.coerce||!1,...$e(r)});var ys=class r extends je{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==le.date){let i=this._getOrReturnCtx(e);return se(i,{code:J.invalid_type,expected:le.date,received:i.parsedType}),we}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return se(i,{code:J.invalid_date}),we}let t=new Pt,s;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()i.value&&(s=this._getOrReturnCtx(e,s),se(s,{code:J.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),t.dirty()):Ze.assertNever(i);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}min(e,a){return this._addCheck({kind:"min",value:e.getTime(),message:me.toString(a)})}max(e,a){return this._addCheck({kind:"max",value:e.getTime(),message:me.toString(a)})}get minDate(){let e=null;for(let a of this._def.checks)a.kind==="min"&&(e===null||a.value>e)&&(e=a.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let a of this._def.checks)a.kind==="max"&&(e===null||a.valuenew ys({checks:[],coerce:r?.coerce||!1,typeName:Pe.ZodDate,...$e(r)});var _n=class extends je{_parse(e){if(this._getType(e)!==le.symbol){let t=this._getOrReturnCtx(e);return se(t,{code:J.invalid_type,expected:le.symbol,received:t.parsedType}),we}return kt(e.data)}};_n.create=r=>new _n({typeName:Pe.ZodSymbol,...$e(r)});var bs=class extends je{_parse(e){if(this._getType(e)!==le.undefined){let t=this._getOrReturnCtx(e);return se(t,{code:J.invalid_type,expected:le.undefined,received:t.parsedType}),we}return kt(e.data)}};bs.create=r=>new bs({typeName:Pe.ZodUndefined,...$e(r)});var xs=class extends je{_parse(e){if(this._getType(e)!==le.null){let t=this._getOrReturnCtx(e);return se(t,{code:J.invalid_type,expected:le.null,received:t.parsedType}),we}return kt(e.data)}};xs.create=r=>new xs({typeName:Pe.ZodNull,...$e(r)});var Ta=class extends je{constructor(){super(...arguments),this._any=!0}_parse(e){return kt(e.data)}};Ta.create=r=>new Ta({typeName:Pe.ZodAny,...$e(r)});var ra=class extends je{constructor(){super(...arguments),this._unknown=!0}_parse(e){return kt(e.data)}};ra.create=r=>new ra({typeName:Pe.ZodUnknown,...$e(r)});var Sr=class extends je{_parse(e){let a=this._getOrReturnCtx(e);return se(a,{code:J.invalid_type,expected:le.never,received:a.parsedType}),we}};Sr.create=r=>new Sr({typeName:Pe.ZodNever,...$e(r)});var En=class extends je{_parse(e){if(this._getType(e)!==le.undefined){let t=this._getOrReturnCtx(e);return se(t,{code:J.invalid_type,expected:le.void,received:t.parsedType}),we}return kt(e.data)}};En.create=r=>new En({typeName:Pe.ZodVoid,...$e(r)});var aa=class r extends je{_parse(e){let{ctx:a,status:t}=this._processInputParams(e),s=this._def;if(a.parsedType!==le.array)return se(a,{code:J.invalid_type,expected:le.array,received:a.parsedType}),we;if(s.exactLength!==null){let n=a.data.length>s.exactLength.value,o=a.data.lengths.maxLength.value&&(se(a,{code:J.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),t.dirty()),a.common.async)return Promise.all([...a.data].map((n,o)=>s.type._parseAsync(new dr(a,n,a.path,o)))).then(n=>Pt.mergeArray(t,n));let i=[...a.data].map((n,o)=>s.type._parseSync(new dr(a,n,a.path,o)));return Pt.mergeArray(t,i)}get element(){return this._def.type}min(e,a){return new r({...this._def,minLength:{value:e,message:me.toString(a)}})}max(e,a){return new r({...this._def,maxLength:{value:e,message:me.toString(a)}})}length(e,a){return new r({...this._def,exactLength:{value:e,message:me.toString(a)}})}nonempty(e){return this.min(1,e)}};aa.create=(r,e)=>new aa({type:r,minLength:null,maxLength:null,exactLength:null,typeName:Pe.ZodArray,...$e(e)});function yn(r){if(r instanceof Lt){let e={};for(let a in r.shape){let t=r.shape[a];e[a]=pr.create(yn(t))}return new Lt({...r._def,shape:()=>e})}else return r instanceof aa?new aa({...r._def,type:yn(r.element)}):r instanceof pr?pr.create(yn(r.unwrap())):r instanceof Mr?Mr.create(yn(r.unwrap())):r instanceof Lr?Lr.create(r.items.map(e=>yn(e))):r}var Lt=class r extends je{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),a=Ze.objectKeys(e);return this._cached={shape:e,keys:a},this._cached}_parse(e){if(this._getType(e)!==le.object){let c=this._getOrReturnCtx(e);return se(c,{code:J.invalid_type,expected:le.object,received:c.parsedType}),we}let{status:t,ctx:s}=this._processInputParams(e),{shape:i,keys:n}=this._getCached(),o=[];if(!(this._def.catchall instanceof Sr&&this._def.unknownKeys==="strip"))for(let c in s.data)n.includes(c)||o.push(c);let l=[];for(let c of n){let u=i[c],f=s.data[c];l.push({key:{status:"valid",value:c},value:u._parse(new dr(s,f,s.path,c)),alwaysSet:c in s.data})}if(this._def.catchall instanceof Sr){let c=this._def.unknownKeys;if(c==="passthrough")for(let u of o)l.push({key:{status:"valid",value:u},value:{status:"valid",value:s.data[u]}});else if(c==="strict")o.length>0&&(se(s,{code:J.unrecognized_keys,keys:o}),t.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let u of o){let f=s.data[u];l.push({key:{status:"valid",value:u},value:c._parse(new dr(s,f,s.path,u)),alwaysSet:u in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let c=[];for(let u of l){let f=await u.key,m=await u.value;c.push({key:f,value:m,alwaysSet:u.alwaysSet})}return c}).then(c=>Pt.mergeObjectSync(t,c)):Pt.mergeObjectSync(t,l)}get shape(){return this._def.shape()}strict(e){return me.errToObj,new r({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(a,t)=>{let s=this._def.errorMap?.(a,t).message??t.defaultError;return a.code==="unrecognized_keys"?{message:me.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new r({...this._def,unknownKeys:"strip"})}passthrough(){return new r({...this._def,unknownKeys:"passthrough"})}extend(e){return new r({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new r({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:Pe.ZodObject})}setKey(e,a){return this.augment({[e]:a})}catchall(e){return new r({...this._def,catchall:e})}pick(e){let a={};for(let t of Ze.objectKeys(e))e[t]&&this.shape[t]&&(a[t]=this.shape[t]);return new r({...this._def,shape:()=>a})}omit(e){let a={};for(let t of Ze.objectKeys(this.shape))e[t]||(a[t]=this.shape[t]);return new r({...this._def,shape:()=>a})}deepPartial(){return yn(this)}partial(e){let a={};for(let t of Ze.objectKeys(this.shape)){let s=this.shape[t];e&&!e[t]?a[t]=s:a[t]=s.optional()}return new r({...this._def,shape:()=>a})}required(e){let a={};for(let t of Ze.objectKeys(this.shape))if(e&&!e[t])a[t]=this.shape[t];else{let i=this.shape[t];for(;i instanceof pr;)i=i._def.innerType;a[t]=i}return new r({...this._def,shape:()=>a})}keyof(){return vE(Ze.objectKeys(this.shape))}};Lt.create=(r,e)=>new Lt({shape:()=>r,unknownKeys:"strip",catchall:Sr.create(),typeName:Pe.ZodObject,...$e(e)});Lt.strictCreate=(r,e)=>new Lt({shape:()=>r,unknownKeys:"strict",catchall:Sr.create(),typeName:Pe.ZodObject,...$e(e)});Lt.lazycreate=(r,e)=>new Lt({shape:r,unknownKeys:"strip",catchall:Sr.create(),typeName:Pe.ZodObject,...$e(e)});var _s=class extends je{_parse(e){let{ctx:a}=this._processInputParams(e),t=this._def.options;function s(i){for(let o of i)if(o.result.status==="valid")return o.result;for(let o of i)if(o.result.status==="dirty")return a.common.issues.push(...o.ctx.common.issues),o.result;let n=i.map(o=>new Wt(o.ctx.common.issues));return se(a,{code:J.invalid_union,unionErrors:n}),we}if(a.common.async)return Promise.all(t.map(async i=>{let n={...a,common:{...a.common,issues:[]},parent:null};return{result:await i._parseAsync({data:a.data,path:a.path,parent:n}),ctx:n}})).then(s);{let i,n=[];for(let l of t){let c={...a,common:{...a.common,issues:[]},parent:null},u=l._parseSync({data:a.data,path:a.path,parent:c});if(u.status==="valid")return u;u.status==="dirty"&&!i&&(i={result:u,ctx:c}),c.common.issues.length&&n.push(c.common.issues)}if(i)return a.common.issues.push(...i.ctx.common.issues),i.result;let o=n.map(l=>new Wt(l));return se(a,{code:J.invalid_union,unionErrors:o}),we}}get options(){return this._def.options}};_s.create=(r,e)=>new _s({options:r,typeName:Pe.ZodUnion,...$e(e)});var Yr=r=>r instanceof ws?Yr(r.schema):r instanceof Qt?Yr(r.innerType()):r instanceof Ss?[r.value]:r instanceof Ps?r.options:r instanceof Rs?Ze.objectValues(r.enum):r instanceof Ts?Yr(r._def.innerType):r instanceof bs?[void 0]:r instanceof xs?[null]:r instanceof pr?[void 0,...Yr(r.unwrap())]:r instanceof Mr?[null,...Yr(r.unwrap())]:r instanceof ki||r instanceof Os?Yr(r.unwrap()):r instanceof ks?Yr(r._def.innerType):[],Bc=class r extends je{_parse(e){let{ctx:a}=this._processInputParams(e);if(a.parsedType!==le.object)return se(a,{code:J.invalid_type,expected:le.object,received:a.parsedType}),we;let t=this.discriminator,s=a.data[t],i=this.optionsMap.get(s);return i?a.common.async?i._parseAsync({data:a.data,path:a.path,parent:a}):i._parseSync({data:a.data,path:a.path,parent:a}):(se(a,{code:J.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[t]}),we)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,a,t){let s=new Map;for(let i of a){let n=Yr(i.shape[e]);if(!n.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let o of n){if(s.has(o))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(o)}`);s.set(o,i)}}return new r({typeName:Pe.ZodDiscriminatedUnion,discriminator:e,options:a,optionsMap:s,...$e(t)})}};function kd(r,e){let a=ea(r),t=ea(e);if(r===e)return{valid:!0,data:r};if(a===le.object&&t===le.object){let s=Ze.objectKeys(e),i=Ze.objectKeys(r).filter(o=>s.indexOf(o)!==-1),n={...r,...e};for(let o of i){let l=kd(r[o],e[o]);if(!l.valid)return{valid:!1};n[o]=l.data}return{valid:!0,data:n}}else if(a===le.array&&t===le.array){if(r.length!==e.length)return{valid:!1};let s=[];for(let i=0;i{if(Rd(i)||Rd(n))return we;let o=kd(i.value,n.value);return o.valid?((Td(i)||Td(n))&&a.dirty(),{status:a.value,value:o.data}):(se(t,{code:J.invalid_intersection_types}),we)};return t.common.async?Promise.all([this._def.left._parseAsync({data:t.data,path:t.path,parent:t}),this._def.right._parseAsync({data:t.data,path:t.path,parent:t})]).then(([i,n])=>s(i,n)):s(this._def.left._parseSync({data:t.data,path:t.path,parent:t}),this._def.right._parseSync({data:t.data,path:t.path,parent:t}))}};Es.create=(r,e,a)=>new Es({left:r,right:e,typeName:Pe.ZodIntersection,...$e(a)});var Lr=class r extends je{_parse(e){let{status:a,ctx:t}=this._processInputParams(e);if(t.parsedType!==le.array)return se(t,{code:J.invalid_type,expected:le.array,received:t.parsedType}),we;if(t.data.lengththis._def.items.length&&(se(t,{code:J.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),a.dirty());let i=[...t.data].map((n,o)=>{let l=this._def.items[o]||this._def.rest;return l?l._parse(new dr(t,n,t.path,o)):null}).filter(n=>!!n);return t.common.async?Promise.all(i).then(n=>Pt.mergeArray(a,n)):Pt.mergeArray(a,i)}get items(){return this._def.items}rest(e){return new r({...this._def,rest:e})}};Lr.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Lr({items:r,typeName:Pe.ZodTuple,rest:null,...$e(e)})};var Vc=class r extends je{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:a,ctx:t}=this._processInputParams(e);if(t.parsedType!==le.object)return se(t,{code:J.invalid_type,expected:le.object,received:t.parsedType}),we;let s=[],i=this._def.keyType,n=this._def.valueType;for(let o in t.data)s.push({key:i._parse(new dr(t,o,t.path,o)),value:n._parse(new dr(t,t.data[o],t.path,o)),alwaysSet:o in t.data});return t.common.async?Pt.mergeObjectAsync(a,s):Pt.mergeObjectSync(a,s)}get element(){return this._def.valueType}static create(e,a,t){return a instanceof je?new r({keyType:e,valueType:a,typeName:Pe.ZodRecord,...$e(t)}):new r({keyType:Ra.create(),valueType:e,typeName:Pe.ZodRecord,...$e(a)})}},wn=class extends je{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:a,ctx:t}=this._processInputParams(e);if(t.parsedType!==le.map)return se(t,{code:J.invalid_type,expected:le.map,received:t.parsedType}),we;let s=this._def.keyType,i=this._def.valueType,n=[...t.data.entries()].map(([o,l],c)=>({key:s._parse(new dr(t,o,t.path,[c,"key"])),value:i._parse(new dr(t,l,t.path,[c,"value"]))}));if(t.common.async){let o=new Map;return Promise.resolve().then(async()=>{for(let l of n){let c=await l.key,u=await l.value;if(c.status==="aborted"||u.status==="aborted")return we;(c.status==="dirty"||u.status==="dirty")&&a.dirty(),o.set(c.value,u.value)}return{status:a.value,value:o}})}else{let o=new Map;for(let l of n){let c=l.key,u=l.value;if(c.status==="aborted"||u.status==="aborted")return we;(c.status==="dirty"||u.status==="dirty")&&a.dirty(),o.set(c.value,u.value)}return{status:a.value,value:o}}}};wn.create=(r,e,a)=>new wn({valueType:e,keyType:r,typeName:Pe.ZodMap,...$e(a)});var Sn=class r extends je{_parse(e){let{status:a,ctx:t}=this._processInputParams(e);if(t.parsedType!==le.set)return se(t,{code:J.invalid_type,expected:le.set,received:t.parsedType}),we;let s=this._def;s.minSize!==null&&t.data.sizes.maxSize.value&&(se(t,{code:J.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),a.dirty());let i=this._def.valueType;function n(l){let c=new Set;for(let u of l){if(u.status==="aborted")return we;u.status==="dirty"&&a.dirty(),c.add(u.value)}return{status:a.value,value:c}}let o=[...t.data.values()].map((l,c)=>i._parse(new dr(t,l,t.path,c)));return t.common.async?Promise.all(o).then(l=>n(l)):n(o)}min(e,a){return new r({...this._def,minSize:{value:e,message:me.toString(a)}})}max(e,a){return new r({...this._def,maxSize:{value:e,message:me.toString(a)}})}size(e,a){return this.min(e,a).max(e,a)}nonempty(e){return this.min(1,e)}};Sn.create=(r,e)=>new Sn({valueType:r,minSize:null,maxSize:null,typeName:Pe.ZodSet,...$e(e)});var Zc=class r extends je{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:a}=this._processInputParams(e);if(a.parsedType!==le.function)return se(a,{code:J.invalid_type,expected:le.function,received:a.parsedType}),we;function t(o,l){return Hc({data:o,path:a.path,errorMaps:[a.common.contextualErrorMap,a.schemaErrorMap,zc(),xn].filter(c=>!!c),issueData:{code:J.invalid_arguments,argumentsError:l}})}function s(o,l){return Hc({data:o,path:a.path,errorMaps:[a.common.contextualErrorMap,a.schemaErrorMap,zc(),xn].filter(c=>!!c),issueData:{code:J.invalid_return_type,returnTypeError:l}})}let i={errorMap:a.common.contextualErrorMap},n=a.data;if(this._def.returns instanceof ka){let o=this;return kt(async function(...l){let c=new Wt([]),u=await o._def.args.parseAsync(l,i).catch(d=>{throw c.addIssue(t(l,d)),c}),f=await Reflect.apply(n,this,u);return await o._def.returns._def.type.parseAsync(f,i).catch(d=>{throw c.addIssue(s(f,d)),c})})}else{let o=this;return kt(function(...l){let c=o._def.args.safeParse(l,i);if(!c.success)throw new Wt([t(l,c.error)]);let u=Reflect.apply(n,this,c.data),f=o._def.returns.safeParse(u,i);if(!f.success)throw new Wt([s(u,f.error)]);return f.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new r({...this._def,args:Lr.create(e).rest(ra.create())})}returns(e){return new r({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,a,t){return new r({args:e||Lr.create([]).rest(ra.create()),returns:a||ra.create(),typeName:Pe.ZodFunction,...$e(t)})}},ws=class extends je{get schema(){return this._def.getter()}_parse(e){let{ctx:a}=this._processInputParams(e);return this._def.getter()._parse({data:a.data,path:a.path,parent:a})}};ws.create=(r,e)=>new ws({getter:r,typeName:Pe.ZodLazy,...$e(e)});var Ss=class extends je{_parse(e){if(e.data!==this._def.value){let a=this._getOrReturnCtx(e);return se(a,{received:a.data,code:J.invalid_literal,expected:this._def.value}),we}return{status:"valid",value:e.data}}get value(){return this._def.value}};Ss.create=(r,e)=>new Ss({value:r,typeName:Pe.ZodLiteral,...$e(e)});function vE(r,e){return new Ps({values:r,typeName:Pe.ZodEnum,...$e(e)})}var Ps=class r extends je{_parse(e){if(typeof e.data!="string"){let a=this._getOrReturnCtx(e),t=this._def.values;return se(a,{expected:Ze.joinValues(t),received:a.parsedType,code:J.invalid_type}),we}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let a=this._getOrReturnCtx(e),t=this._def.values;return se(a,{received:a.data,code:J.invalid_enum_value,options:t}),we}return kt(e.data)}get options(){return this._def.values}get enum(){let e={};for(let a of this._def.values)e[a]=a;return e}get Values(){let e={};for(let a of this._def.values)e[a]=a;return e}get Enum(){let e={};for(let a of this._def.values)e[a]=a;return e}extract(e,a=this._def){return r.create(e,{...this._def,...a})}exclude(e,a=this._def){return r.create(this.options.filter(t=>!e.includes(t)),{...this._def,...a})}};Ps.create=vE;var Rs=class extends je{_parse(e){let a=Ze.getValidEnumValues(this._def.values),t=this._getOrReturnCtx(e);if(t.parsedType!==le.string&&t.parsedType!==le.number){let s=Ze.objectValues(a);return se(t,{expected:Ze.joinValues(s),received:t.parsedType,code:J.invalid_type}),we}if(this._cache||(this._cache=new Set(Ze.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=Ze.objectValues(a);return se(t,{received:t.data,code:J.invalid_enum_value,options:s}),we}return kt(e.data)}get enum(){return this._def.values}};Rs.create=(r,e)=>new Rs({values:r,typeName:Pe.ZodNativeEnum,...$e(e)});var ka=class extends je{unwrap(){return this._def.type}_parse(e){let{ctx:a}=this._processInputParams(e);if(a.parsedType!==le.promise&&a.common.async===!1)return se(a,{code:J.invalid_type,expected:le.promise,received:a.parsedType}),we;let t=a.parsedType===le.promise?a.data:Promise.resolve(a.data);return kt(t.then(s=>this._def.type.parseAsync(s,{path:a.path,errorMap:a.common.contextualErrorMap})))}};ka.create=(r,e)=>new ka({type:r,typeName:Pe.ZodPromise,...$e(e)});var Qt=class extends je{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Pe.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:a,ctx:t}=this._processInputParams(e),s=this._def.effect||null,i={addIssue:n=>{se(t,n),n.fatal?a.abort():a.dirty()},get path(){return t.path}};if(i.addIssue=i.addIssue.bind(i),s.type==="preprocess"){let n=s.transform(t.data,i);if(t.common.async)return Promise.resolve(n).then(async o=>{if(a.value==="aborted")return we;let l=await this._def.schema._parseAsync({data:o,path:t.path,parent:t});return l.status==="aborted"?we:l.status==="dirty"||a.value==="dirty"?bn(l.value):l});{if(a.value==="aborted")return we;let o=this._def.schema._parseSync({data:n,path:t.path,parent:t});return o.status==="aborted"?we:o.status==="dirty"||a.value==="dirty"?bn(o.value):o}}if(s.type==="refinement"){let n=o=>{let l=s.refinement(o,i);if(t.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(t.common.async===!1){let o=this._def.schema._parseSync({data:t.data,path:t.path,parent:t});return o.status==="aborted"?we:(o.status==="dirty"&&a.dirty(),n(o.value),{status:a.value,value:o.value})}else return this._def.schema._parseAsync({data:t.data,path:t.path,parent:t}).then(o=>o.status==="aborted"?we:(o.status==="dirty"&&a.dirty(),n(o.value).then(()=>({status:a.value,value:o.value}))))}if(s.type==="transform")if(t.common.async===!1){let n=this._def.schema._parseSync({data:t.data,path:t.path,parent:t});if(!ms(n))return we;let o=s.transform(n.value,i);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:a.value,value:o}}else return this._def.schema._parseAsync({data:t.data,path:t.path,parent:t}).then(n=>ms(n)?Promise.resolve(s.transform(n.value,i)).then(o=>({status:a.value,value:o})):we);Ze.assertNever(s)}};Qt.create=(r,e,a)=>new Qt({schema:r,typeName:Pe.ZodEffects,effect:e,...$e(a)});Qt.createWithPreprocess=(r,e,a)=>new Qt({schema:e,effect:{type:"preprocess",transform:r},typeName:Pe.ZodEffects,...$e(a)});var pr=class extends je{_parse(e){return this._getType(e)===le.undefined?kt(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};pr.create=(r,e)=>new pr({innerType:r,typeName:Pe.ZodOptional,...$e(e)});var Mr=class extends je{_parse(e){return this._getType(e)===le.null?kt(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Mr.create=(r,e)=>new Mr({innerType:r,typeName:Pe.ZodNullable,...$e(e)});var Ts=class extends je{_parse(e){let{ctx:a}=this._processInputParams(e),t=a.data;return a.parsedType===le.undefined&&(t=this._def.defaultValue()),this._def.innerType._parse({data:t,path:a.path,parent:a})}removeDefault(){return this._def.innerType}};Ts.create=(r,e)=>new Ts({innerType:r,typeName:Pe.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...$e(e)});var ks=class extends je{_parse(e){let{ctx:a}=this._processInputParams(e),t={...a,common:{...a.common,issues:[]}},s=this._def.innerType._parse({data:t.data,path:t.path,parent:{...t}});return Ti(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Wt(t.common.issues)},input:t.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Wt(t.common.issues)},input:t.data})}}removeCatch(){return this._def.innerType}};ks.create=(r,e)=>new ks({innerType:r,typeName:Pe.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...$e(e)});var Pn=class extends je{_parse(e){if(this._getType(e)!==le.nan){let t=this._getOrReturnCtx(e);return se(t,{code:J.invalid_type,expected:le.nan,received:t.parsedType}),we}return{status:"valid",value:e.data}}};Pn.create=r=>new Pn({typeName:Pe.ZodNaN,...$e(r)});var k6=Symbol("zod_brand"),ki=class extends je{_parse(e){let{ctx:a}=this._processInputParams(e),t=a.data;return this._def.type._parse({data:t,path:a.path,parent:a})}unwrap(){return this._def.type}},Oi=class r extends je{_parse(e){let{status:a,ctx:t}=this._processInputParams(e);if(t.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:t.data,path:t.path,parent:t});return i.status==="aborted"?we:i.status==="dirty"?(a.dirty(),bn(i.value)):this._def.out._parseAsync({data:i.value,path:t.path,parent:t})})();{let s=this._def.in._parseSync({data:t.data,path:t.path,parent:t});return s.status==="aborted"?we:s.status==="dirty"?(a.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:t.path,parent:t})}}static create(e,a){return new r({in:e,out:a,typeName:Pe.ZodPipeline})}},Os=class extends je{_parse(e){let a=this._def.innerType._parse(e),t=s=>(ms(s)&&(s.value=Object.freeze(s.value)),s);return Ti(a)?a.then(s=>t(s)):t(a)}unwrap(){return this._def.innerType}};Os.create=(r,e)=>new Os({innerType:r,typeName:Pe.ZodReadonly,...$e(e)});function B1(r,e){let a=typeof r=="function"?r(e):typeof r=="string"?{message:r}:r;return typeof a=="string"?{message:a}:a}function gE(r,e={},a){return r?Ta.create().superRefine((t,s)=>{let i=r(t);if(i instanceof Promise)return i.then(n=>{if(!n){let o=B1(e,t),l=o.fatal??a??!0;s.addIssue({code:"custom",...o,fatal:l})}});if(!i){let n=B1(e,t),o=n.fatal??a??!0;s.addIssue({code:"custom",...n,fatal:o})}}):Ta.create()}var O6={object:Lt.lazycreate},Pe;(function(r){r.ZodString="ZodString",r.ZodNumber="ZodNumber",r.ZodNaN="ZodNaN",r.ZodBigInt="ZodBigInt",r.ZodBoolean="ZodBoolean",r.ZodDate="ZodDate",r.ZodSymbol="ZodSymbol",r.ZodUndefined="ZodUndefined",r.ZodNull="ZodNull",r.ZodAny="ZodAny",r.ZodUnknown="ZodUnknown",r.ZodNever="ZodNever",r.ZodVoid="ZodVoid",r.ZodArray="ZodArray",r.ZodObject="ZodObject",r.ZodUnion="ZodUnion",r.ZodDiscriminatedUnion="ZodDiscriminatedUnion",r.ZodIntersection="ZodIntersection",r.ZodTuple="ZodTuple",r.ZodRecord="ZodRecord",r.ZodMap="ZodMap",r.ZodSet="ZodSet",r.ZodFunction="ZodFunction",r.ZodLazy="ZodLazy",r.ZodLiteral="ZodLiteral",r.ZodEnum="ZodEnum",r.ZodEffects="ZodEffects",r.ZodNativeEnum="ZodNativeEnum",r.ZodOptional="ZodOptional",r.ZodNullable="ZodNullable",r.ZodDefault="ZodDefault",r.ZodCatch="ZodCatch",r.ZodPromise="ZodPromise",r.ZodBranded="ZodBranded",r.ZodPipeline="ZodPipeline",r.ZodReadonly="ZodReadonly"})(Pe||(Pe={}));var C6=(r,e={message:`Input not instance of ${r.name}`})=>gE(a=>a instanceof r,e),yE=Ra.create,bE=hs.create,I6=Pn.create,A6=vs.create,xE=gs.create,j6=ys.create,N6=_n.create,D6=bs.create,$6=xs.create,q6=Ta.create,F6=ra.create,L6=Sr.create,M6=En.create,U6=aa.create,z6=Lt.create,H6=Lt.strictCreate,B6=_s.create,V6=Bc.create,Z6=Es.create,G6=Lr.create,W6=Vc.create,Q6=wn.create,K6=Sn.create,X6=Zc.create,J6=ws.create,Y6=Ss.create,e5=Ps.create,t5=Rs.create,r5=ka.create,V1=Qt.create,a5=pr.create,s5=Mr.create,n5=Qt.createWithPreprocess,i5=Oi.create,o5=()=>yE().optional(),c5=()=>bE().optional(),l5=()=>xE().optional(),u5={string:r=>Ra.create({...r,coerce:!0}),number:r=>hs.create({...r,coerce:!0}),boolean:r=>gs.create({...r,coerce:!0}),bigint:r=>vs.create({...r,coerce:!0}),date:r=>ys.create({...r,coerce:!0})},p5=we;var Kc="2.0",_E=w.union([w.string(),w.number().int()]),EE=w.string(),d5=w.object({progressToken:w.optional(_E)}).passthrough(),fr=w.object({_meta:w.optional(d5)}).passthrough(),Mt=w.object({method:w.string(),params:w.optional(fr)}),Ii=w.object({_meta:w.optional(w.object({}).passthrough())}).passthrough(),Ur=w.object({method:w.string(),params:w.optional(Ii)}),mr=w.object({_meta:w.optional(w.object({}).passthrough())}).passthrough(),Xc=w.union([w.string(),w.number().int()]),f5=w.object({jsonrpc:w.literal(Kc),id:Xc}).merge(Mt).strict();var m5=w.object({jsonrpc:w.literal(Kc)}).merge(Ur).strict();var h5=w.object({jsonrpc:w.literal(Kc),id:Xc,result:mr}).strict();var Z1;(function(r){r[r.ConnectionClosed=-32e3]="ConnectionClosed",r[r.RequestTimeout=-32001]="RequestTimeout",r[r.ParseError=-32700]="ParseError",r[r.InvalidRequest=-32600]="InvalidRequest",r[r.MethodNotFound=-32601]="MethodNotFound",r[r.InvalidParams=-32602]="InvalidParams",r[r.InternalError=-32603]="InternalError"})(Z1||(Z1={}));var v5=w.object({jsonrpc:w.literal(Kc),id:Xc,error:w.object({code:w.number().int(),message:w.string(),data:w.optional(w.unknown())})}).strict();var AM=w.union([f5,m5,h5,v5]),wE=mr.strict(),SE=Ur.extend({method:w.literal("notifications/cancelled"),params:Ii.extend({requestId:Xc,reason:w.string().optional()})}),Ai=w.object({name:w.string(),title:w.optional(w.string())}).passthrough(),PE=Ai.extend({version:w.string()}),g5=w.object({experimental:w.optional(w.object({}).passthrough()),sampling:w.optional(w.object({}).passthrough()),elicitation:w.optional(w.object({}).passthrough()),roots:w.optional(w.object({listChanged:w.optional(w.boolean())}).passthrough())}).passthrough(),y5=Mt.extend({method:w.literal("initialize"),params:fr.extend({protocolVersion:w.string(),capabilities:g5,clientInfo:PE})}),b5=w.object({experimental:w.optional(w.object({}).passthrough()),logging:w.optional(w.object({}).passthrough()),completions:w.optional(w.object({}).passthrough()),prompts:w.optional(w.object({listChanged:w.optional(w.boolean())}).passthrough()),resources:w.optional(w.object({subscribe:w.optional(w.boolean()),listChanged:w.optional(w.boolean())}).passthrough()),tools:w.optional(w.object({listChanged:w.optional(w.boolean())}).passthrough())}).passthrough(),x5=mr.extend({protocolVersion:w.string(),capabilities:b5,serverInfo:PE,instructions:w.optional(w.string())}),_5=Ur.extend({method:w.literal("notifications/initialized")}),RE=Mt.extend({method:w.literal("ping")}),E5=w.object({progress:w.number(),total:w.optional(w.number()),message:w.optional(w.string())}).passthrough(),TE=Ur.extend({method:w.literal("notifications/progress"),params:Ii.merge(E5).extend({progressToken:_E})}),Jc=Mt.extend({params:fr.extend({cursor:w.optional(EE)}).optional()}),Yc=mr.extend({nextCursor:w.optional(EE)}),kE=w.object({uri:w.string(),mimeType:w.optional(w.string()),_meta:w.optional(w.object({}).passthrough())}).passthrough(),OE=kE.extend({text:w.string()}),Dd=w.string().refine(r=>{try{return atob(r),!0}catch{return!1}},{message:"Invalid Base64 string"}),CE=kE.extend({blob:Dd}),IE=Ai.extend({uri:w.string(),description:w.optional(w.string()),mimeType:w.optional(w.string()),_meta:w.optional(w.object({}).passthrough())}),w5=Ai.extend({uriTemplate:w.string(),description:w.optional(w.string()),mimeType:w.optional(w.string()),_meta:w.optional(w.object({}).passthrough())}),S5=Jc.extend({method:w.literal("resources/list")}),P5=Yc.extend({resources:w.array(IE)}),R5=Jc.extend({method:w.literal("resources/templates/list")}),T5=Yc.extend({resourceTemplates:w.array(w5)}),k5=Mt.extend({method:w.literal("resources/read"),params:fr.extend({uri:w.string()})}),O5=mr.extend({contents:w.array(w.union([OE,CE]))}),C5=Ur.extend({method:w.literal("notifications/resources/list_changed")}),I5=Mt.extend({method:w.literal("resources/subscribe"),params:fr.extend({uri:w.string()})}),A5=Mt.extend({method:w.literal("resources/unsubscribe"),params:fr.extend({uri:w.string()})}),j5=Ur.extend({method:w.literal("notifications/resources/updated"),params:Ii.extend({uri:w.string()})}),N5=w.object({name:w.string(),description:w.optional(w.string()),required:w.optional(w.boolean())}).passthrough(),D5=Ai.extend({description:w.optional(w.string()),arguments:w.optional(w.array(N5)),_meta:w.optional(w.object({}).passthrough())}),$5=Jc.extend({method:w.literal("prompts/list")}),q5=Yc.extend({prompts:w.array(D5)}),F5=Mt.extend({method:w.literal("prompts/get"),params:fr.extend({name:w.string(),arguments:w.optional(w.record(w.string()))})}),$d=w.object({type:w.literal("text"),text:w.string(),_meta:w.optional(w.object({}).passthrough())}).passthrough(),qd=w.object({type:w.literal("image"),data:Dd,mimeType:w.string(),_meta:w.optional(w.object({}).passthrough())}).passthrough(),Fd=w.object({type:w.literal("audio"),data:Dd,mimeType:w.string(),_meta:w.optional(w.object({}).passthrough())}).passthrough(),L5=w.object({type:w.literal("resource"),resource:w.union([OE,CE]),_meta:w.optional(w.object({}).passthrough())}).passthrough(),M5=IE.extend({type:w.literal("resource_link")}),AE=w.union([$d,qd,Fd,M5,L5]),U5=w.object({role:w.enum(["user","assistant"]),content:AE}).passthrough(),z5=mr.extend({description:w.optional(w.string()),messages:w.array(U5)}),H5=Ur.extend({method:w.literal("notifications/prompts/list_changed")}),B5=w.object({title:w.optional(w.string()),readOnlyHint:w.optional(w.boolean()),destructiveHint:w.optional(w.boolean()),idempotentHint:w.optional(w.boolean()),openWorldHint:w.optional(w.boolean())}).passthrough(),V5=Ai.extend({description:w.optional(w.string()),inputSchema:w.object({type:w.literal("object"),properties:w.optional(w.object({}).passthrough()),required:w.optional(w.array(w.string()))}).passthrough(),outputSchema:w.optional(w.object({type:w.literal("object"),properties:w.optional(w.object({}).passthrough()),required:w.optional(w.array(w.string()))}).passthrough()),annotations:w.optional(B5),_meta:w.optional(w.object({}).passthrough())}),Z5=Jc.extend({method:w.literal("tools/list")}),G5=Yc.extend({tools:w.array(V5)}),jE=mr.extend({content:w.array(AE).default([]),structuredContent:w.object({}).passthrough().optional(),isError:w.optional(w.boolean())}),jM=jE.or(mr.extend({toolResult:w.unknown()})),W5=Mt.extend({method:w.literal("tools/call"),params:fr.extend({name:w.string(),arguments:w.optional(w.record(w.unknown()))})}),Q5=Ur.extend({method:w.literal("notifications/tools/list_changed")}),NE=w.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),K5=Mt.extend({method:w.literal("logging/setLevel"),params:fr.extend({level:NE})}),X5=Ur.extend({method:w.literal("notifications/message"),params:Ii.extend({level:NE,logger:w.optional(w.string()),data:w.unknown()})}),J5=w.object({name:w.string().optional()}).passthrough(),Y5=w.object({hints:w.optional(w.array(J5)),costPriority:w.optional(w.number().min(0).max(1)),speedPriority:w.optional(w.number().min(0).max(1)),intelligencePriority:w.optional(w.number().min(0).max(1))}).passthrough(),e$=w.object({role:w.enum(["user","assistant"]),content:w.union([$d,qd,Fd])}).passthrough(),t$=Mt.extend({method:w.literal("sampling/createMessage"),params:fr.extend({messages:w.array(e$),systemPrompt:w.optional(w.string()),includeContext:w.optional(w.enum(["none","thisServer","allServers"])),temperature:w.optional(w.number()),maxTokens:w.number().int(),stopSequences:w.optional(w.array(w.string())),metadata:w.optional(w.object({}).passthrough()),modelPreferences:w.optional(Y5)})}),r$=mr.extend({model:w.string(),stopReason:w.optional(w.enum(["endTurn","stopSequence","maxTokens"]).or(w.string())),role:w.enum(["user","assistant"]),content:w.discriminatedUnion("type",[$d,qd,Fd])}),a$=w.object({type:w.literal("boolean"),title:w.optional(w.string()),description:w.optional(w.string()),default:w.optional(w.boolean())}).passthrough(),s$=w.object({type:w.literal("string"),title:w.optional(w.string()),description:w.optional(w.string()),minLength:w.optional(w.number()),maxLength:w.optional(w.number()),format:w.optional(w.enum(["email","uri","date","date-time"]))}).passthrough(),n$=w.object({type:w.enum(["number","integer"]),title:w.optional(w.string()),description:w.optional(w.string()),minimum:w.optional(w.number()),maximum:w.optional(w.number())}).passthrough(),i$=w.object({type:w.literal("string"),title:w.optional(w.string()),description:w.optional(w.string()),enum:w.array(w.string()),enumNames:w.optional(w.array(w.string()))}).passthrough(),o$=w.union([a$,s$,n$,i$]),c$=Mt.extend({method:w.literal("elicitation/create"),params:fr.extend({message:w.string(),requestedSchema:w.object({type:w.literal("object"),properties:w.record(w.string(),o$),required:w.optional(w.array(w.string()))}).passthrough()})}),l$=mr.extend({action:w.enum(["accept","decline","cancel"]),content:w.optional(w.record(w.string(),w.unknown()))}),u$=w.object({type:w.literal("ref/resource"),uri:w.string()}).passthrough(),p$=w.object({type:w.literal("ref/prompt"),name:w.string()}).passthrough(),d$=Mt.extend({method:w.literal("completion/complete"),params:fr.extend({ref:w.union([p$,u$]),argument:w.object({name:w.string(),value:w.string()}).passthrough(),context:w.optional(w.object({arguments:w.optional(w.record(w.string(),w.string()))}))})}),f$=mr.extend({completion:w.object({values:w.array(w.string()).max(100),total:w.optional(w.number().int()),hasMore:w.optional(w.boolean())}).passthrough()}),m$=w.object({uri:w.string().startsWith("file://"),name:w.optional(w.string()),_meta:w.optional(w.object({}).passthrough())}).passthrough(),h$=Mt.extend({method:w.literal("roots/list")}),v$=mr.extend({roots:w.array(m$)}),g$=Ur.extend({method:w.literal("notifications/roots/list_changed")}),NM=w.union([RE,y5,d$,K5,F5,$5,S5,R5,k5,I5,A5,W5,Z5]),DM=w.union([SE,TE,_5,g$]),$M=w.union([wE,r$,l$,v$]),qM=w.union([RE,t$,c$,h$]),FM=w.union([SE,TE,X5,j5,C5,Q5,H5]),LM=w.union([wE,x5,f$,z5,q5,P5,T5,O5,jE,G5]);var MM=bj(eN(),1);var UM=Symbol("Let zodToJsonSchema decide on which parser to use");var zM=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");var Od;(function(r){r.Completable="McpCompletable"})(Od||(Od={}));var Gc=class extends je{_parse(e){let{ctx:a}=this._processInputParams(e),t=a.data;return this._def.type._parse({data:t,path:a.path,parent:a})}unwrap(){return this._def.type}};Gc.create=(r,e)=>new Gc({type:r,typeName:Od.Completable,complete:e.complete,...y$(e)});function y$(r){if(!r)return{};let{errorMap:e,invalid_type_error:a,required_error:t,description:s}=r;if(e&&(a||t))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(n,o)=>{var l,c;let{message:u}=r;return n.code==="invalid_enum_value"?{message:u??o.defaultError}:typeof o.data>"u"?{message:(l=u??t)!==null&&l!==void 0?l:o.defaultError}:n.code!=="invalid_type"?{message:o.defaultError}:{message:(c=u??a)!==null&&c!==void 0?c:o.defaultError}},description:s}}function DE({prompt:r,options:e}){let{systemPrompt:a,settingSources:t,...s}=e??{},i,n;a===void 0?i="":typeof a=="string"?i=a:a.type==="preset"&&(n=a.append);let o=s.pathToClaudeCodeExecutable;if(!o){let xe=(0,X1.fileURLToPath)(b$.url),Oe=(0,bd.join)(xe,"..");o=(0,bd.join)(Oe,"cli.js")}process.env.CLAUDE_AGENT_SDK_VERSION="0.1.27";let{abortController:l=Y1(),additionalDirectories:c=[],agents:u,allowedTools:f=[],canUseTool:m,continue:d,cwd:h,disallowedTools:p=[],env:v,executable:g=aE()?"bun":"node",executableArgs:b=[],extraArgs:E={},fallbackModel:k,forkSession:O,hooks:P,includePartialMessages:I,maxThinkingTokens:$,maxTurns:A,mcpServers:L,model:q,permissionMode:C="default",allowDangerouslySkipPermissions:R=!1,permissionPromptToolName:j,plugins:z,resume:H,resumeSessionAt:V,stderr:te,strictMcpConfig:K}=s,B=v;if(B||(B={...process.env}),B.CLAUDE_CODE_ENTRYPOINT||(B.CLAUDE_CODE_ENTRYPOINT="sdk-ts"),!o)throw new Error("pathToClaudeCodeExecutable is required");let re={},ce=new Map;if(L)for(let[xe,Oe]of Object.entries(L))Oe.type==="sdk"&&"instance"in Oe?(ce.set(xe,Oe.instance),re[xe]={type:"sdk",name:xe}):re[xe]=Oe;let Be=typeof r=="string",be=new xd({abortController:l,additionalDirectories:c,agents:u,cwd:h,executable:g,executableArgs:b,extraArgs:E,pathToClaudeCodeExecutable:o,env:B,forkSession:O,stderr:te,customSystemPrompt:i,appendSystemPrompt:n,maxThinkingTokens:$,maxTurns:A,model:q,fallbackModel:k,permissionMode:C,allowDangerouslySkipPermissions:R,permissionPromptToolName:j,continueConversation:d,resume:H,resumeSessionAt:V,settingSources:t??[],allowedTools:f,disallowedTools:p,mcpServers:re,strictMcpConfig:K,canUseTool:!!m,hooks:!!P,includePartialMessages:I,plugins:z}),qe=new Sd(be,Be,m,P,l,ce);return typeof r=="string"?be.write(JSON.stringify({type:"user",session_id:"",message:{role:"user",content:[{type:"text",text:r}]},parent_tool_use_id:null})+` `):qe.streamInput(r),qe}var el=class{dbManager;sessionManager;constructor(e,a){this.dbManager=e,this.sessionManager=a}async startSession(e,a){try{let t=this.findClaudeExecutable(),s=this.getModelId(),i=["Bash"],n=this.createMessageGenerator(e),o=DE({prompt:n,options:{model:s,disallowedTools:i,abortController:e.abortController,pathToClaudeCodeExecutable:t}});for await(let c of o){if(c.type==="assistant"){let u=c.message.content,f=Array.isArray(u)?u.filter(d=>d.type==="text").map(d=>d.text).join(` -`):typeof u=="string"?u:"",m=f.length;ee.dataOut("SDK",`Response received (${m} chars)`,{sessionId:e.sessionDbId,promptNumber:e.lastPromptNumber}),await this.processSDKResponse(e,f,a)}c.type==="result"&&c.subtype}let l=Date.now()-e.startTime;ee.success("SDK","Agent completed",{sessionId:e.sessionDbId,duration:`${(l/1e3).toFixed(1)}s`}),this.dbManager.getSessionStore().markSessionCompleted(e.sessionDbId)}catch(t){throw t.name==="AbortError"?ee.warn("SDK","Agent aborted",{sessionId:e.sessionDbId}):ee.failure("SDK","Agent error",{sessionDbId:e.sessionDbId},t),t}finally{this.sessionManager.deleteSession(e.sessionDbId).catch(()=>{})}}async*createMessageGenerator(e){yield{type:"user",message:{role:"user",content:C1(e.project,e.claudeSessionId,e.userPrompt)},session_id:e.claudeSessionId,parent_tool_use_id:null,isSynthetic:!0};for await(let a of this.sessionManager.getMessageIterator(e.sessionDbId))a.type==="observation"?(a.prompt_number!==void 0&&(e.lastPromptNumber=a.prompt_number),yield{type:"user",message:{role:"user",content:I1({id:0,tool_name:a.tool_name,tool_input:JSON.stringify(a.tool_input),tool_output:JSON.stringify(a.tool_response),created_at_epoch:Date.now()})},session_id:e.claudeSessionId,parent_tool_use_id:null,isSynthetic:!0}):a.type==="summarize"&&(yield{type:"user",message:{role:"user",content:A1({id:e.sessionDbId,sdk_session_id:e.sdkSessionId,project:e.project,user_prompt:e.userPrompt})},session_id:e.claudeSessionId,parent_tool_use_id:null,isSynthetic:!0})}async processSDKResponse(e,a,t){let s=k1(a,e.claudeSessionId);for(let n of s){let{id:o,createdAtEpoch:l}=this.dbManager.getSessionStore().storeObservation(e.claudeSessionId,e.project,n,e.lastPromptNumber);this.dbManager.getChromaSync().syncObservation(o,e.claudeSessionId,e.project,n,e.lastPromptNumber,l).catch(()=>{}),t&&t.sseBroadcaster&&t.sseBroadcaster.broadcast({type:"new_observation",observation:{id:o,sdk_session_id:e.sdkSessionId,session_id:e.claudeSessionId,type:n.type,title:n.title,subtitle:n.subtitle,text:n.text||null,narrative:null,facts:JSON.stringify(n.facts||[]),concepts:JSON.stringify(n.concepts||[]),files_read:JSON.stringify(n.files||[]),files_modified:JSON.stringify([]),project:e.project,prompt_number:e.lastPromptNumber,created_at_epoch:l}}),ee.info("SDK","Observation saved",{obsId:o,type:n.type})}let i=O1(a,e.sessionDbId);if(i){let{id:n,createdAtEpoch:o}=this.dbManager.getSessionStore().storeSummary(e.claudeSessionId,e.project,i,e.lastPromptNumber);this.dbManager.getChromaSync().syncSummary(n,e.claudeSessionId,e.project,i,e.lastPromptNumber,o).catch(()=>{}),t&&t.sseBroadcaster&&t.sseBroadcaster.broadcast({type:"new_summary",summary:{id:n,session_id:e.claudeSessionId,request:i.request,investigated:i.investigated,learned:i.learned,completed:i.completed,next_steps:i.next_steps,notes:i.notes,project:e.project,prompt_number:e.lastPromptNumber,created_at_epoch:o}}),ee.info("SDK","Summary saved",{summaryId:n})}t&&typeof t.checkAndStopSpinner=="function"&&t.checkAndStopSpinner()}findClaudeExecutable(){let e=process.env.CLAUDE_CODE_PATH||(0,$E.execSync)(process.platform==="win32"?"where claude":"which claude",{encoding:"utf8"}).trim().split(` +`):typeof u=="string"?u:"",m=f.length;ee.dataOut("SDK",`Response received (${m} chars)`,{sessionId:e.sessionDbId,promptNumber:e.lastPromptNumber}),await this.processSDKResponse(e,f,a)}c.type==="result"&&c.subtype}let l=Date.now()-e.startTime;ee.success("SDK","Agent completed",{sessionId:e.sessionDbId,duration:`${(l/1e3).toFixed(1)}s`}),this.dbManager.getSessionStore().markSessionCompleted(e.sessionDbId)}catch(t){throw t.name==="AbortError"?ee.warn("SDK","Agent aborted",{sessionId:e.sessionDbId}):ee.failure("SDK","Agent error",{sessionDbId:e.sessionDbId},t),t}finally{this.sessionManager.deleteSession(e.sessionDbId).catch(()=>{})}}async*createMessageGenerator(e){yield{type:"user",message:{role:"user",content:C1(e.project,e.claudeSessionId,e.userPrompt)},session_id:e.claudeSessionId,parent_tool_use_id:null,isSynthetic:!0};for await(let a of this.sessionManager.getMessageIterator(e.sessionDbId))a.type==="observation"?(a.prompt_number!==void 0&&(e.lastPromptNumber=a.prompt_number),yield{type:"user",message:{role:"user",content:I1({id:0,tool_name:a.tool_name,tool_input:JSON.stringify(a.tool_input),tool_output:JSON.stringify(a.tool_response),created_at_epoch:Date.now()})},session_id:e.claudeSessionId,parent_tool_use_id:null,isSynthetic:!0}):a.type==="summarize"&&(yield{type:"user",message:{role:"user",content:A1({id:e.sessionDbId,sdk_session_id:e.sdkSessionId,project:e.project,user_prompt:e.userPrompt})},session_id:e.claudeSessionId,parent_tool_use_id:null,isSynthetic:!0})}async processSDKResponse(e,a,t){let s=k1(a,e.claudeSessionId);for(let n of s){let{id:o,createdAtEpoch:l}=this.dbManager.getSessionStore().storeObservation(e.claudeSessionId,e.project,n,e.lastPromptNumber);this.dbManager.getChromaSync().syncObservation(o,e.claudeSessionId,e.project,n,e.lastPromptNumber,l).catch(()=>{}),t&&t.sseBroadcaster&&t.sseBroadcaster.broadcast({type:"new_observation",observation:{id:o,sdk_session_id:e.sdkSessionId,session_id:e.claudeSessionId,type:n.type,title:n.title,subtitle:n.subtitle,text:n.text||null,narrative:n.narrative||null,facts:JSON.stringify(n.facts||[]),concepts:JSON.stringify(n.concepts||[]),files_read:JSON.stringify(n.files||[]),files_modified:JSON.stringify([]),project:e.project,prompt_number:e.lastPromptNumber,created_at_epoch:l}}),ee.info("SDK","Observation saved",{obsId:o,type:n.type})}let i=O1(a,e.sessionDbId);if(i){let{id:n,createdAtEpoch:o}=this.dbManager.getSessionStore().storeSummary(e.claudeSessionId,e.project,i,e.lastPromptNumber);this.dbManager.getChromaSync().syncSummary(n,e.claudeSessionId,e.project,i,e.lastPromptNumber,o).catch(()=>{}),t&&t.sseBroadcaster&&t.sseBroadcaster.broadcast({type:"new_summary",summary:{id:n,session_id:e.claudeSessionId,request:i.request,investigated:i.investigated,learned:i.learned,completed:i.completed,next_steps:i.next_steps,notes:i.notes,project:e.project,prompt_number:e.lastPromptNumber,created_at_epoch:o}}),ee.info("SDK","Summary saved",{summaryId:n})}t&&typeof t.checkAndStopSpinner=="function"&&t.checkAndStopSpinner()}findClaudeExecutable(){let e=process.env.CLAUDE_CODE_PATH||(0,$E.execSync)(process.platform==="win32"?"where claude":"which claude",{encoding:"utf8"}).trim().split(` `)[0].trim();if(!e)throw new Error("Claude executable not found in PATH");return e}getModelId(){try{let e=FE.default.join((0,qE.homedir)(),".claude-mem","settings.json");if((0,tl.existsSync)(e)){let t=JSON.parse((0,tl.readFileSync)(e,"utf-8")).env?.CLAUDE_MEM_MODEL;if(t)return t}}catch{}return process.env.CLAUDE_MEM_MODEL||"claude-haiku-4-5"}};var rl=class{dbManager;constructor(e){this.dbManager=e}stripProjectPath(e,a){let t=`/${a}/`,s=e.indexOf(t);return s!==-1?e.substring(s+t.length):e}stripProjectPaths(e,a){if(!e)return e;try{let s=JSON.parse(e).map(i=>this.stripProjectPath(i,a));return JSON.stringify(s)}catch{return e}}sanitizeObservation(e){return{...e,files_read:this.stripProjectPaths(e.files_read,e.project),files_modified:this.stripProjectPaths(e.files_modified,e.project)}}getObservations(e,a,t){let s=this.paginate("observations","id, sdk_session_id, project, type, title, subtitle, narrative, text, facts, concepts, files_read, files_modified, prompt_number, created_at, created_at_epoch",e,a,t);return{...s,items:s.items.map(i=>this.sanitizeObservation(i))}}getSummaries(e,a,t){let s=this.dbManager.getSessionStore().db,i=` SELECT ss.id, diff --git a/src/services/worker/SDKAgent.ts b/src/services/worker/SDKAgent.ts index ed39207a..ead6c4f3 100644 --- a/src/services/worker/SDKAgent.ts +++ b/src/services/worker/SDKAgent.ts @@ -204,7 +204,7 @@ export class SDKAgent { title: obs.title, subtitle: obs.subtitle, text: obs.text || null, - narrative: null, + narrative: obs.narrative || null, facts: JSON.stringify(obs.facts || []), concepts: JSON.stringify(obs.concepts || []), files_read: JSON.stringify(obs.files || []),