From 54ef9662c183fb0448d64dd1fd37bf613c2b1a19 Mon Sep 17 00:00:00 2001 From: Alex Newman Date: Wed, 17 Dec 2025 16:00:12 -0500 Subject: [PATCH] Enhance SDKAgent response handling and message processing - Updated response logging to process both empty and non-empty responses. - Added functionality to mark messages as processed even when the response is empty. - Refactored message processing logic to ensure all pending messages are marked as processed after successful observation/summary storage. - Introduced a new private method `markMessagesProcessed` to encapsulate the logic for marking messages as processed, preventing message loss and duplicate processing. --- plugin/scripts/worker-service.cjs | 2 +- plugin/skills/mem-search.zip | Bin 32124 -> 32124 bytes src/services/worker/SDKAgent.ts | 16 +++++++++++++--- 3 files changed, 14 insertions(+), 4 deletions(-) diff --git a/plugin/scripts/worker-service.cjs b/plugin/scripts/worker-service.cjs index 6b88dbe1..84b74773 100755 --- a/plugin/scripts/worker-service.cjs +++ b/plugin/scripts/worker-service.cjs @@ -1086,7 +1086,7 @@ MEMORY PROCESSING CONTINUED `))}Ir(`[Query.streamInput] Finished processing ${r} messages from input stream`),this.hasBidirectionalNeeds()&&(Ir("[Query.streamInput] Has bidirectional needs, waiting for inactivity"),await this.waitForInactivity()),Ir("[Query] Calling transport.endInput() to close stdin to CLI process"),this.transport.endInput()}catch(r){if(!(r instanceof Ts))throw r}}async handleSingleTurnInputComplete(){this.hasBidirectionalNeeds()&&(Ir("[Query.handleSingleTurnInputComplete] Has bidirectional needs, waiting for inactivity"),await this.waitForInactivity()),Ir("[Query.handleSingleTurnInputComplete] Calling transport.endInput()"),this.transport.endInput()}async waitForInactivity(){return Ir(`[Query.waitForInactivity] Waiting for inactivity (timeout: ${this.streamCloseTimeout}ms)`),new Promise(e=>{if(this.userInputEndedResolve=e,this.abortController?.signal.aborted){e();return}this.abortController?.signal.addEventListener("abort",()=>e(),{once:!0});let r=()=>{if(this.abortController?.signal.aborted){e();return}let t=Date.now()-this.lastActivityTime;if(t>=this.streamCloseTimeout)Ir(`[Query.waitForInactivity] Inactivity timeout reached (${t}ms elapsed). Closing stdin. If your tools or hooks need more time, set CLAUDE_CODE_STREAM_CLOSE_TIMEOUT to a higher value (current: ${this.streamCloseTimeout}ms).`),e();else{let s=this.streamCloseTimeout-t;Ir(`[Query.waitForInactivity] Still active, checking again in ${s}ms`),setTimeout(r,s)}};r()})}handleHookCallbacks(e,r,t,s){let i=this.hookCallbacks.get(e);if(!i)throw new Error(`No hook callback found for ID: ${e}`);return i(r,t,{signal:s})}sendMcpServerMessageToCli(e,r){if("id"in r&&r.id!==null&&r.id!==void 0){let s=`${e}:${r.id}`,i=this.pendingMcpResponses.get(s);if(i){i.resolve(r),this.pendingMcpResponses.delete(s);return}}let t={type:"control_request",request_id:(0,Tw.randomUUID)(),request:{subtype:"mcp_message",server_name:e,message:r}};this.transport.write(JSON.stringify(t)+` `)}handleMcpControlRequest(e,r,t){let s="id"in r.message?r.message.id:null,i=`${e}:${s}`;return new Promise((n,o)=>{let l=()=>{this.pendingMcpResponses.delete(i)},c=p=>{l(),n(p)},u=p=>{l(),o(p)};if(this.pendingMcpResponses.set(i,{resolve:c,reject:u}),t.onmessage)t.onmessage(r.message);else{l(),o(new Error("No message handler registered"));return}})}};var w={};r8(w,{void:()=>CL,util:()=>Ke,unknown:()=>PL,union:()=>NL,undefined:()=>wL,tuple:()=>$L,transformer:()=>JS,symbol:()=>SL,string:()=>Aw,strictObject:()=>AL,setErrorMap:()=>Z9,set:()=>FL,record:()=>ML,quotelessJson:()=>W9,promise:()=>VL,preprocess:()=>ZL,pipeline:()=>KL,ostring:()=>XL,optional:()=>WL,onumber:()=>YL,oboolean:()=>QL,objectUtil:()=>_f,object:()=>IL,number:()=>Nw,nullable:()=>GL,null:()=>TL,never:()=>OL,nativeEnum:()=>zL,nan:()=>xL,map:()=>LL,makeIssue:()=>_l,literal:()=>HL,lazy:()=>UL,late:()=>yL,isValid:()=>Ps,isDirty:()=>Sf,isAsync:()=>Ji,isAborted:()=>Ef,intersection:()=>jL,instanceof:()=>bL,getParsedType:()=>la,getErrorMap:()=>xl,function:()=>qL,enum:()=>BL,effect:()=>JS,discriminatedUnion:()=>DL,defaultErrorMap:()=>Un,datetimeRegex:()=>Cw,date:()=>EL,custom:()=>Iw,coerce:()=>JL,boolean:()=>Dw,bigint:()=>_L,array:()=>kL,any:()=>RL,addIssueToContext:()=>ce,ZodVoid:()=>Bn,ZodUnknown:()=>pa,ZodUnion:()=>Ds,ZodUndefined:()=>As,ZodType:()=>$e,ZodTuple:()=>Gr,ZodTransformer:()=>tr,ZodSymbol:()=>Hn,ZodString:()=>$a,ZodSet:()=>Vn,ZodSchema:()=>$e,ZodRecord:()=>Sl,ZodReadonly:()=>Hs,ZodPromise:()=>La,ZodPipeline:()=>to,ZodParsedType:()=>de,ZodOptional:()=>vr,ZodObject:()=>Wt,ZodNumber:()=>Os,ZodNullable:()=>Zr,ZodNull:()=>Ns,ZodNever:()=>Ar,ZodNativeEnum:()=>Fs,ZodNaN:()=>Wn,ZodMap:()=>zn,ZodLiteral:()=>Ms,ZodLazy:()=>$s,ZodIssueCode:()=>te,ZodIntersection:()=>js,ZodFunction:()=>wl,ZodFirstPartyTypeKind:()=>Ce,ZodError:()=>er,ZodEnum:()=>Ls,ZodEffects:()=>tr,ZodDiscriminatedUnion:()=>El,ZodDefault:()=>qs,ZodDate:()=>Is,ZodCatch:()=>Us,ZodBranded:()=>eo,ZodBoolean:()=>ks,ZodBigInt:()=>Cs,ZodArray:()=>da,ZodAny:()=>Ma,Schema:()=>$e,ParseStatus:()=>It,OK:()=>Dt,NEVER:()=>e6,INVALID:()=>Pe,EMPTY_PATH:()=>K9,DIRTY:()=>qn,BRAND:()=>gL});var Ke;(function(a){a.assertEqual=s=>{};function e(s){}a.assertIs=e;function r(s){throw new Error}a.assertNever=r,a.arrayToEnum=s=>{let i={};for(let n of s)i[n]=n;return i},a.getValidEnumValues=s=>{let i=a.objectKeys(s).filter(o=>typeof s[s[o]]!="number"),n={};for(let o of i)n[o]=s[o];return a.objectValues(n)},a.objectValues=s=>a.objectKeys(s).map(function(i){return s[i]}),a.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},a.find=(s,i)=>{for(let n of s)if(i(n))return n},a.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)}a.joinValues=t,a.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})(Ke||(Ke={}));var _f;(function(a){a.mergeShapes=(e,r)=>({...e,...r})})(_f||(_f={}));var de=Ke.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),la=a=>{switch(typeof a){case"undefined":return de.undefined;case"string":return de.string;case"number":return Number.isNaN(a)?de.nan:de.number;case"boolean":return de.boolean;case"function":return de.function;case"bigint":return de.bigint;case"symbol":return de.symbol;case"object":return Array.isArray(a)?de.array:a===null?de.null:a.then&&typeof a.then=="function"&&a.catch&&typeof a.catch=="function"?de.promise:typeof Map<"u"&&a instanceof Map?de.map:typeof Set<"u"&&a instanceof Set?de.set:typeof Date<"u"&&a instanceof Date?de.date:de.object;default:return de.unknown}},te=Ke.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"]),W9=a=>JSON.stringify(a,null,2).replace(/"([^"]+)":/g,"$1:"),er=class a 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 r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=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(r(n));else{let o=t,l=0;for(;lr.message){let r={},t=[];for(let s of this.issues)if(s.path.length>0){let i=s.path[0];r[i]=r[i]||[],r[i].push(e(s))}else t.push(e(s));return{formErrors:t,fieldErrors:r}}get formErrors(){return this.flatten()}};er.create=a=>new er(a);var G9=(a,e)=>{let r;switch(a.code){case te.invalid_type:a.received===de.undefined?r="Required":r=`Expected ${a.expected}, received ${a.received}`;break;case te.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(a.expected,Ke.jsonStringifyReplacer)}`;break;case te.unrecognized_keys:r=`Unrecognized key(s) in object: ${Ke.joinValues(a.keys,", ")}`;break;case te.invalid_union:r="Invalid input";break;case te.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${Ke.joinValues(a.options)}`;break;case te.invalid_enum_value:r=`Invalid enum value. Expected ${Ke.joinValues(a.options)}, received '${a.received}'`;break;case te.invalid_arguments:r="Invalid function arguments";break;case te.invalid_return_type:r="Invalid function return type";break;case te.invalid_date:r="Invalid date";break;case te.invalid_string:typeof a.validation=="object"?"includes"in a.validation?(r=`Invalid input: must include "${a.validation.includes}"`,typeof a.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${a.validation.position}`)):"startsWith"in a.validation?r=`Invalid input: must start with "${a.validation.startsWith}"`:"endsWith"in a.validation?r=`Invalid input: must end with "${a.validation.endsWith}"`:Ke.assertNever(a.validation):a.validation!=="regex"?r=`Invalid ${a.validation}`:r="Invalid";break;case te.too_small:a.type==="array"?r=`Array must contain ${a.exact?"exactly":a.inclusive?"at least":"more than"} ${a.minimum} element(s)`:a.type==="string"?r=`String must contain ${a.exact?"exactly":a.inclusive?"at least":"over"} ${a.minimum} character(s)`:a.type==="number"?r=`Number must be ${a.exact?"exactly equal to ":a.inclusive?"greater than or equal to ":"greater than "}${a.minimum}`:a.type==="bigint"?r=`Number must be ${a.exact?"exactly equal to ":a.inclusive?"greater than or equal to ":"greater than "}${a.minimum}`:a.type==="date"?r=`Date must be ${a.exact?"exactly equal to ":a.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(a.minimum))}`:r="Invalid input";break;case te.too_big:a.type==="array"?r=`Array must contain ${a.exact?"exactly":a.inclusive?"at most":"less than"} ${a.maximum} element(s)`:a.type==="string"?r=`String must contain ${a.exact?"exactly":a.inclusive?"at most":"under"} ${a.maximum} character(s)`:a.type==="number"?r=`Number must be ${a.exact?"exactly":a.inclusive?"less than or equal to":"less than"} ${a.maximum}`:a.type==="bigint"?r=`BigInt must be ${a.exact?"exactly":a.inclusive?"less than or equal to":"less than"} ${a.maximum}`:a.type==="date"?r=`Date must be ${a.exact?"exactly":a.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(a.maximum))}`:r="Invalid input";break;case te.custom:r="Invalid input";break;case te.invalid_intersection_types:r="Intersection results could not be merged";break;case te.not_multiple_of:r=`Number must be a multiple of ${a.multipleOf}`;break;case te.not_finite:r="Number must be finite";break;default:r=e.defaultError,Ke.assertNever(a)}return{message:r}},Un=G9,Rw=Un;function Z9(a){Rw=a}function xl(){return Rw}var _l=a=>{let{data:e,path:r,errorMaps:t,issueData:s}=a,i=[...r,...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}},K9=[];function ce(a,e){let r=xl(),t=_l({issueData:e,data:a.data,path:a.path,errorMaps:[a.common.contextualErrorMap,a.schemaErrorMap,r,r===Un?void 0:Un].filter(s=>!!s)});a.common.issues.push(t)}var It=class a{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let t=[];for(let s of r){if(s.status==="aborted")return Pe;s.status==="dirty"&&e.dirty(),t.push(s.value)}return{status:e.value,value:t}}static async mergeObjectAsync(e,r){let t=[];for(let s of r){let i=await s.key,n=await s.value;t.push({key:i,value:n})}return a.mergeObjectSync(e,t)}static mergeObjectSync(e,r){let t={};for(let s of r){let{key:i,value:n}=s;if(i.status==="aborted"||n.status==="aborted")return Pe;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}}},Pe=Object.freeze({status:"aborted"}),qn=a=>({status:"dirty",value:a}),Dt=a=>({status:"valid",value:a}),Ef=a=>a.status==="aborted",Sf=a=>a.status==="dirty",Ps=a=>a.status==="valid",Ji=a=>typeof Promise<"u"&&a instanceof Promise,ye;(function(a){a.errToObj=e=>typeof e=="string"?{message:e}:e||{},a.toString=e=>typeof e=="string"?e:e?.message})(ye||(ye={}));var gr=class{constructor(e,r,t,s){this._cachedPath=[],this.parent=e,this.data=r,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}},YS=(a,e)=>{if(Ps(e))return{success:!0,data:e.value};if(!a.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new er(a.common.issues);return this._error=r,this._error}}};function Fe(a){if(!a)return{};let{errorMap:e,invalid_type_error:r,required_error:t,description:s}=a;if(e&&(r||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}=a;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??r??o.defaultError}},description:s}}var $e=class{get description(){return this._def.description}_getType(e){return la(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:la(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new It,ctx:{common:e.parent.common,data:e.data,parsedType:la(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(Ji(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let t=this.safeParse(e,r);if(t.success)return t.data;throw t.error}safeParse(e,r){let t={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:la(e)},s=this._parseSync({data:e,path:t.path,parent:t});return YS(t,s)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:la(e)};if(!this["~standard"].async)try{let t=this._parseSync({data:e,path:[],parent:r});return Ps(t)?{value:t.value}:{issues:r.common.issues}}catch(t){t?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(t=>Ps(t)?{value:t.value}:{issues:r.common.issues})}async parseAsync(e,r){let t=await this.safeParseAsync(e,r);if(t.success)return t.data;throw t.error}async safeParseAsync(e,r){let t={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:la(e)},s=this._parse({data:e,path:t.path,parent:t}),i=await(Ji(s)?s:Promise.resolve(s));return YS(t,i)}refine(e,r){let t=s=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(s):r;return this._refinement((s,i)=>{let n=e(s),o=()=>i.addIssue({code:te.custom,...t(s)});return typeof Promise<"u"&&n instanceof Promise?n.then(l=>l?!0:(o(),!1)):n?!0:(o(),!1)})}refinement(e,r){return this._refinement((t,s)=>e(t)?!0:(s.addIssue(typeof r=="function"?r(t,s):r),!1))}_refinement(e){return new tr({schema:this,typeName:Ce.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:r=>this["~validate"](r)}}optional(){return vr.create(this,this._def)}nullable(){return Zr.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return da.create(this)}promise(){return La.create(this,this._def)}or(e){return Ds.create([this,e],this._def)}and(e){return js.create(this,e,this._def)}transform(e){return new tr({...Fe(this._def),schema:this,typeName:Ce.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new qs({...Fe(this._def),innerType:this,defaultValue:r,typeName:Ce.ZodDefault})}brand(){return new eo({typeName:Ce.ZodBranded,type:this,...Fe(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new Us({...Fe(this._def),innerType:this,catchValue:r,typeName:Ce.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return to.create(this,e)}readonly(){return Hs.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},X9=/^c[^\s-]{8,}$/i,Y9=/^[0-9a-z]+$/,Q9=/^[0-9A-HJKMNP-TV-Z]{26}$/i,J9=/^[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,eL=/^[a-z0-9_-]{21}$/i,tL=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,rL=/^[-+]?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)?)??$/,aL=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,sL="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",ff,nL=/^(?:(?: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])$/,iL=/^(?:(?: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])$/,oL=/^(([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]))$/,cL=/^(([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])$/,lL=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,uL=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Pw="((\\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])))",pL=new RegExp(`^${Pw}$`);function Ow(a){let e="[0-5]\\d";a.precision?e=`${e}\\.\\d{${a.precision}}`:a.precision==null&&(e=`${e}(\\.\\d+)?`);let r=a.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function dL(a){return new RegExp(`^${Ow(a)}$`)}function Cw(a){let e=`${Pw}T${Ow(a)}`,r=[];return r.push(a.local?"Z?":"Z"),a.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function fL(a,e){return!!((e==="v4"||!e)&&nL.test(a)||(e==="v6"||!e)&&oL.test(a))}function mL(a,e){if(!tL.test(a))return!1;try{let[r]=a.split(".");if(!r)return!1;let t=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.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 hL(a,e){return!!((e==="v4"||!e)&&iL.test(a)||(e==="v6"||!e)&&cL.test(a))}var $a=class a extends $e{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==de.string){let i=this._getOrReturnCtx(e);return ce(i,{code:te.invalid_type,expected:de.string,received:i.parsedType}),Pe}let t=new It,s;for(let i of this._def.checks)if(i.kind==="min")e.data.lengthi.value&&(s=this._getOrReturnCtx(e,s),ce(s,{code:te.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:r,code:te.invalid_string,...ye.errToObj(t)})}_addCheck(e){return new a({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...ye.errToObj(e)})}url(e){return this._addCheck({kind:"url",...ye.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...ye.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...ye.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...ye.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...ye.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...ye.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...ye.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...ye.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...ye.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...ye.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...ye.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...ye.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,...ye.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,...ye.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...ye.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...ye.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...ye.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...ye.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...ye.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...ye.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...ye.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...ye.errToObj(r)})}nonempty(e){return this.min(1,ye.errToObj(e))}trim(){return new a({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new a({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new a({...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 r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.valuenew $a({checks:[],typeName:Ce.ZodString,coerce:a?.coerce??!1,...Fe(a)});function vL(a,e){let r=(a.toString().split(".")[1]||"").length,t=(e.toString().split(".")[1]||"").length,s=r>t?r:t,i=Number.parseInt(a.toFixed(s).replace(".","")),n=Number.parseInt(e.toFixed(s).replace(".",""));return i%n/10**s}var Os=class a extends $e{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)!==de.number){let i=this._getOrReturnCtx(e);return ce(i,{code:te.invalid_type,expected:de.number,received:i.parsedType}),Pe}let t,s=new It;for(let i of this._def.checks)i.kind==="int"?Ke.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),ce(t,{code:te.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),ce(t,{code:te.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?vL(e.data,i.value)!==0&&(t=this._getOrReturnCtx(e,t),ce(t,{code:te.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),ce(t,{code:te.not_finite,message:i.message}),s.dirty()):Ke.assertNever(i);return{status:s.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,ye.toString(r))}gt(e,r){return this.setLimit("min",e,!1,ye.toString(r))}lte(e,r){return this.setLimit("max",e,!0,ye.toString(r))}lt(e,r){return this.setLimit("max",e,!1,ye.toString(r))}setLimit(e,r,t,s){return new a({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:t,message:ye.toString(s)}]})}_addCheck(e){return new a({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:ye.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:ye.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:ye.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:ye.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:ye.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:ye.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:ye.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:ye.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:ye.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.valuee.kind==="int"||e.kind==="multipleOf"&&Ke.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let t of this._def.checks){if(t.kind==="finite"||t.kind==="int"||t.kind==="multipleOf")return!0;t.kind==="min"?(r===null||t.value>r)&&(r=t.value):t.kind==="max"&&(e===null||t.valuenew Os({checks:[],typeName:Ce.ZodNumber,coerce:a?.coerce||!1,...Fe(a)});var Cs=class a extends $e{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)!==de.bigint)return this._getInvalidInput(e);let t,s=new It;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?e.datai.value:e.data>=i.value)&&(t=this._getOrReturnCtx(e,t),ce(t,{code:te.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),ce(t,{code:te.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):Ke.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return ce(r,{code:te.invalid_type,expected:de.bigint,received:r.parsedType}),Pe}gte(e,r){return this.setLimit("min",e,!0,ye.toString(r))}gt(e,r){return this.setLimit("min",e,!1,ye.toString(r))}lte(e,r){return this.setLimit("max",e,!0,ye.toString(r))}lt(e,r){return this.setLimit("max",e,!1,ye.toString(r))}setLimit(e,r,t,s){return new a({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:t,message:ye.toString(s)}]})}_addCheck(e){return new a({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:ye.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:ye.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:ye.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:ye.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:ye.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.valuenew Cs({checks:[],typeName:Ce.ZodBigInt,coerce:a?.coerce??!1,...Fe(a)});var ks=class extends $e{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==de.boolean){let t=this._getOrReturnCtx(e);return ce(t,{code:te.invalid_type,expected:de.boolean,received:t.parsedType}),Pe}return Dt(e.data)}};ks.create=a=>new ks({typeName:Ce.ZodBoolean,coerce:a?.coerce||!1,...Fe(a)});var Is=class a extends $e{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==de.date){let i=this._getOrReturnCtx(e);return ce(i,{code:te.invalid_type,expected:de.date,received:i.parsedType}),Pe}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return ce(i,{code:te.invalid_date}),Pe}let t=new It,s;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()i.value&&(s=this._getOrReturnCtx(e,s),ce(s,{code:te.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),t.dirty()):Ke.assertNever(i);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(e){return new a({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:ye.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:ye.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.valuenew Is({checks:[],coerce:a?.coerce||!1,typeName:Ce.ZodDate,...Fe(a)});var Hn=class extends $e{_parse(e){if(this._getType(e)!==de.symbol){let t=this._getOrReturnCtx(e);return ce(t,{code:te.invalid_type,expected:de.symbol,received:t.parsedType}),Pe}return Dt(e.data)}};Hn.create=a=>new Hn({typeName:Ce.ZodSymbol,...Fe(a)});var As=class extends $e{_parse(e){if(this._getType(e)!==de.undefined){let t=this._getOrReturnCtx(e);return ce(t,{code:te.invalid_type,expected:de.undefined,received:t.parsedType}),Pe}return Dt(e.data)}};As.create=a=>new As({typeName:Ce.ZodUndefined,...Fe(a)});var Ns=class extends $e{_parse(e){if(this._getType(e)!==de.null){let t=this._getOrReturnCtx(e);return ce(t,{code:te.invalid_type,expected:de.null,received:t.parsedType}),Pe}return Dt(e.data)}};Ns.create=a=>new Ns({typeName:Ce.ZodNull,...Fe(a)});var Ma=class extends $e{constructor(){super(...arguments),this._any=!0}_parse(e){return Dt(e.data)}};Ma.create=a=>new Ma({typeName:Ce.ZodAny,...Fe(a)});var pa=class extends $e{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Dt(e.data)}};pa.create=a=>new pa({typeName:Ce.ZodUnknown,...Fe(a)});var Ar=class extends $e{_parse(e){let r=this._getOrReturnCtx(e);return ce(r,{code:te.invalid_type,expected:de.never,received:r.parsedType}),Pe}};Ar.create=a=>new Ar({typeName:Ce.ZodNever,...Fe(a)});var Bn=class extends $e{_parse(e){if(this._getType(e)!==de.undefined){let t=this._getOrReturnCtx(e);return ce(t,{code:te.invalid_type,expected:de.void,received:t.parsedType}),Pe}return Dt(e.data)}};Bn.create=a=>new Bn({typeName:Ce.ZodVoid,...Fe(a)});var da=class a extends $e{_parse(e){let{ctx:r,status:t}=this._processInputParams(e),s=this._def;if(r.parsedType!==de.array)return ce(r,{code:te.invalid_type,expected:de.array,received:r.parsedType}),Pe;if(s.exactLength!==null){let n=r.data.length>s.exactLength.value,o=r.data.lengths.maxLength.value&&(ce(r,{code:te.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),t.dirty()),r.common.async)return Promise.all([...r.data].map((n,o)=>s.type._parseAsync(new gr(r,n,r.path,o)))).then(n=>It.mergeArray(t,n));let i=[...r.data].map((n,o)=>s.type._parseSync(new gr(r,n,r.path,o)));return It.mergeArray(t,i)}get element(){return this._def.type}min(e,r){return new a({...this._def,minLength:{value:e,message:ye.toString(r)}})}max(e,r){return new a({...this._def,maxLength:{value:e,message:ye.toString(r)}})}length(e,r){return new a({...this._def,exactLength:{value:e,message:ye.toString(r)}})}nonempty(e){return this.min(1,e)}};da.create=(a,e)=>new da({type:a,minLength:null,maxLength:null,exactLength:null,typeName:Ce.ZodArray,...Fe(e)});function Fn(a){if(a instanceof Wt){let e={};for(let r in a.shape){let t=a.shape[r];e[r]=vr.create(Fn(t))}return new Wt({...a._def,shape:()=>e})}else return a instanceof da?new da({...a._def,type:Fn(a.element)}):a instanceof vr?vr.create(Fn(a.unwrap())):a instanceof Zr?Zr.create(Fn(a.unwrap())):a instanceof Gr?Gr.create(a.items.map(e=>Fn(e))):a}var Wt=class a extends $e{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(),r=Ke.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==de.object){let c=this._getOrReturnCtx(e);return ce(c,{code:te.invalid_type,expected:de.object,received:c.parsedType}),Pe}let{status:t,ctx:s}=this._processInputParams(e),{shape:i,keys:n}=this._getCached(),o=[];if(!(this._def.catchall instanceof Ar&&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],p=s.data[c];l.push({key:{status:"valid",value:c},value:u._parse(new gr(s,p,s.path,c)),alwaysSet:c in s.data})}if(this._def.catchall instanceof Ar){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&&(ce(s,{code:te.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 p=s.data[u];l.push({key:{status:"valid",value:u},value:c._parse(new gr(s,p,s.path,u)),alwaysSet:u in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let c=[];for(let u of l){let p=await u.key,f=await u.value;c.push({key:p,value:f,alwaysSet:u.alwaysSet})}return c}).then(c=>It.mergeObjectSync(t,c)):It.mergeObjectSync(t,l)}get shape(){return this._def.shape()}strict(e){return ye.errToObj,new a({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,t)=>{let s=this._def.errorMap?.(r,t).message??t.defaultError;return r.code==="unrecognized_keys"?{message:ye.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new a({...this._def,unknownKeys:"strip"})}passthrough(){return new a({...this._def,unknownKeys:"passthrough"})}extend(e){return new a({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new a({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:Ce.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new a({...this._def,catchall:e})}pick(e){let r={};for(let t of Ke.objectKeys(e))e[t]&&this.shape[t]&&(r[t]=this.shape[t]);return new a({...this._def,shape:()=>r})}omit(e){let r={};for(let t of Ke.objectKeys(this.shape))e[t]||(r[t]=this.shape[t]);return new a({...this._def,shape:()=>r})}deepPartial(){return Fn(this)}partial(e){let r={};for(let t of Ke.objectKeys(this.shape)){let s=this.shape[t];e&&!e[t]?r[t]=s:r[t]=s.optional()}return new a({...this._def,shape:()=>r})}required(e){let r={};for(let t of Ke.objectKeys(this.shape))if(e&&!e[t])r[t]=this.shape[t];else{let i=this.shape[t];for(;i instanceof vr;)i=i._def.innerType;r[t]=i}return new a({...this._def,shape:()=>r})}keyof(){return kw(Ke.objectKeys(this.shape))}};Wt.create=(a,e)=>new Wt({shape:()=>a,unknownKeys:"strip",catchall:Ar.create(),typeName:Ce.ZodObject,...Fe(e)});Wt.strictCreate=(a,e)=>new Wt({shape:()=>a,unknownKeys:"strict",catchall:Ar.create(),typeName:Ce.ZodObject,...Fe(e)});Wt.lazycreate=(a,e)=>new Wt({shape:a,unknownKeys:"strip",catchall:Ar.create(),typeName:Ce.ZodObject,...Fe(e)});var Ds=class extends $e{_parse(e){let{ctx:r}=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 r.common.issues.push(...o.ctx.common.issues),o.result;let n=i.map(o=>new er(o.ctx.common.issues));return ce(r,{code:te.invalid_union,unionErrors:n}),Pe}if(r.common.async)return Promise.all(t.map(async i=>{let n={...r,common:{...r.common,issues:[]},parent:null};return{result:await i._parseAsync({data:r.data,path:r.path,parent:n}),ctx:n}})).then(s);{let i,n=[];for(let l of t){let c={...r,common:{...r.common,issues:[]},parent:null},u=l._parseSync({data:r.data,path:r.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 r.common.issues.push(...i.ctx.common.issues),i.result;let o=n.map(l=>new er(l));return ce(r,{code:te.invalid_union,unionErrors:o}),Pe}}get options(){return this._def.options}};Ds.create=(a,e)=>new Ds({options:a,typeName:Ce.ZodUnion,...Fe(e)});var ca=a=>a instanceof $s?ca(a.schema):a instanceof tr?ca(a.innerType()):a instanceof Ms?[a.value]:a instanceof Ls?a.options:a instanceof Fs?Ke.objectValues(a.enum):a instanceof qs?ca(a._def.innerType):a instanceof As?[void 0]:a instanceof Ns?[null]:a instanceof vr?[void 0,...ca(a.unwrap())]:a instanceof Zr?[null,...ca(a.unwrap())]:a instanceof eo||a instanceof Hs?ca(a.unwrap()):a instanceof Us?ca(a._def.innerType):[],El=class a extends $e{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==de.object)return ce(r,{code:te.invalid_type,expected:de.object,received:r.parsedType}),Pe;let t=this.discriminator,s=r.data[t],i=this.optionsMap.get(s);return i?r.common.async?i._parseAsync({data:r.data,path:r.path,parent:r}):i._parseSync({data:r.data,path:r.path,parent:r}):(ce(r,{code:te.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[t]}),Pe)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,t){let s=new Map;for(let i of r){let n=ca(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 a({typeName:Ce.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:s,...Fe(t)})}};function wf(a,e){let r=la(a),t=la(e);if(a===e)return{valid:!0,data:a};if(r===de.object&&t===de.object){let s=Ke.objectKeys(e),i=Ke.objectKeys(a).filter(o=>s.indexOf(o)!==-1),n={...a,...e};for(let o of i){let l=wf(a[o],e[o]);if(!l.valid)return{valid:!1};n[o]=l.data}return{valid:!0,data:n}}else if(r===de.array&&t===de.array){if(a.length!==e.length)return{valid:!1};let s=[];for(let i=0;i{if(Ef(i)||Ef(n))return Pe;let o=wf(i.value,n.value);return o.valid?((Sf(i)||Sf(n))&&r.dirty(),{status:r.value,value:o.data}):(ce(t,{code:te.invalid_intersection_types}),Pe)};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}))}};js.create=(a,e,r)=>new js({left:a,right:e,typeName:Ce.ZodIntersection,...Fe(r)});var Gr=class a extends $e{_parse(e){let{status:r,ctx:t}=this._processInputParams(e);if(t.parsedType!==de.array)return ce(t,{code:te.invalid_type,expected:de.array,received:t.parsedType}),Pe;if(t.data.lengththis._def.items.length&&(ce(t,{code:te.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let i=[...t.data].map((n,o)=>{let l=this._def.items[o]||this._def.rest;return l?l._parse(new gr(t,n,t.path,o)):null}).filter(n=>!!n);return t.common.async?Promise.all(i).then(n=>It.mergeArray(r,n)):It.mergeArray(r,i)}get items(){return this._def.items}rest(e){return new a({...this._def,rest:e})}};Gr.create=(a,e)=>{if(!Array.isArray(a))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Gr({items:a,typeName:Ce.ZodTuple,rest:null,...Fe(e)})};var Sl=class a extends $e{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:t}=this._processInputParams(e);if(t.parsedType!==de.object)return ce(t,{code:te.invalid_type,expected:de.object,received:t.parsedType}),Pe;let s=[],i=this._def.keyType,n=this._def.valueType;for(let o in t.data)s.push({key:i._parse(new gr(t,o,t.path,o)),value:n._parse(new gr(t,t.data[o],t.path,o)),alwaysSet:o in t.data});return t.common.async?It.mergeObjectAsync(r,s):It.mergeObjectSync(r,s)}get element(){return this._def.valueType}static create(e,r,t){return r instanceof $e?new a({keyType:e,valueType:r,typeName:Ce.ZodRecord,...Fe(t)}):new a({keyType:$a.create(),valueType:e,typeName:Ce.ZodRecord,...Fe(r)})}},zn=class extends $e{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:t}=this._processInputParams(e);if(t.parsedType!==de.map)return ce(t,{code:te.invalid_type,expected:de.map,received:t.parsedType}),Pe;let s=this._def.keyType,i=this._def.valueType,n=[...t.data.entries()].map(([o,l],c)=>({key:s._parse(new gr(t,o,t.path,[c,"key"])),value:i._parse(new gr(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 Pe;(c.status==="dirty"||u.status==="dirty")&&r.dirty(),o.set(c.value,u.value)}return{status:r.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 Pe;(c.status==="dirty"||u.status==="dirty")&&r.dirty(),o.set(c.value,u.value)}return{status:r.value,value:o}}}};zn.create=(a,e,r)=>new zn({valueType:e,keyType:a,typeName:Ce.ZodMap,...Fe(r)});var Vn=class a extends $e{_parse(e){let{status:r,ctx:t}=this._processInputParams(e);if(t.parsedType!==de.set)return ce(t,{code:te.invalid_type,expected:de.set,received:t.parsedType}),Pe;let s=this._def;s.minSize!==null&&t.data.sizes.maxSize.value&&(ce(t,{code:te.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),r.dirty());let i=this._def.valueType;function n(l){let c=new Set;for(let u of l){if(u.status==="aborted")return Pe;u.status==="dirty"&&r.dirty(),c.add(u.value)}return{status:r.value,value:c}}let o=[...t.data.values()].map((l,c)=>i._parse(new gr(t,l,t.path,c)));return t.common.async?Promise.all(o).then(l=>n(l)):n(o)}min(e,r){return new a({...this._def,minSize:{value:e,message:ye.toString(r)}})}max(e,r){return new a({...this._def,maxSize:{value:e,message:ye.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};Vn.create=(a,e)=>new Vn({valueType:a,minSize:null,maxSize:null,typeName:Ce.ZodSet,...Fe(e)});var wl=class a extends $e{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==de.function)return ce(r,{code:te.invalid_type,expected:de.function,received:r.parsedType}),Pe;function t(o,l){return _l({data:o,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,xl(),Un].filter(c=>!!c),issueData:{code:te.invalid_arguments,argumentsError:l}})}function s(o,l){return _l({data:o,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,xl(),Un].filter(c=>!!c),issueData:{code:te.invalid_return_type,returnTypeError:l}})}let i={errorMap:r.common.contextualErrorMap},n=r.data;if(this._def.returns instanceof La){let o=this;return Dt(async function(...l){let c=new er([]),u=await o._def.args.parseAsync(l,i).catch(d=>{throw c.addIssue(t(l,d)),c}),p=await Reflect.apply(n,this,u);return await o._def.returns._def.type.parseAsync(p,i).catch(d=>{throw c.addIssue(s(p,d)),c})})}else{let o=this;return Dt(function(...l){let c=o._def.args.safeParse(l,i);if(!c.success)throw new er([t(l,c.error)]);let u=Reflect.apply(n,this,c.data),p=o._def.returns.safeParse(u,i);if(!p.success)throw new er([s(u,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new a({...this._def,args:Gr.create(e).rest(pa.create())})}returns(e){return new a({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,t){return new a({args:e||Gr.create([]).rest(pa.create()),returns:r||pa.create(),typeName:Ce.ZodFunction,...Fe(t)})}},$s=class extends $e{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};$s.create=(a,e)=>new $s({getter:a,typeName:Ce.ZodLazy,...Fe(e)});var Ms=class extends $e{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return ce(r,{received:r.data,code:te.invalid_literal,expected:this._def.value}),Pe}return{status:"valid",value:e.data}}get value(){return this._def.value}};Ms.create=(a,e)=>new Ms({value:a,typeName:Ce.ZodLiteral,...Fe(e)});function kw(a,e){return new Ls({values:a,typeName:Ce.ZodEnum,...Fe(e)})}var Ls=class a extends $e{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),t=this._def.values;return ce(r,{expected:Ke.joinValues(t),received:r.parsedType,code:te.invalid_type}),Pe}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),t=this._def.values;return ce(r,{received:r.data,code:te.invalid_enum_value,options:t}),Pe}return Dt(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return a.create(e,{...this._def,...r})}exclude(e,r=this._def){return a.create(this.options.filter(t=>!e.includes(t)),{...this._def,...r})}};Ls.create=kw;var Fs=class extends $e{_parse(e){let r=Ke.getValidEnumValues(this._def.values),t=this._getOrReturnCtx(e);if(t.parsedType!==de.string&&t.parsedType!==de.number){let s=Ke.objectValues(r);return ce(t,{expected:Ke.joinValues(s),received:t.parsedType,code:te.invalid_type}),Pe}if(this._cache||(this._cache=new Set(Ke.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=Ke.objectValues(r);return ce(t,{received:t.data,code:te.invalid_enum_value,options:s}),Pe}return Dt(e.data)}get enum(){return this._def.values}};Fs.create=(a,e)=>new Fs({values:a,typeName:Ce.ZodNativeEnum,...Fe(e)});var La=class extends $e{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==de.promise&&r.common.async===!1)return ce(r,{code:te.invalid_type,expected:de.promise,received:r.parsedType}),Pe;let t=r.parsedType===de.promise?r.data:Promise.resolve(r.data);return Dt(t.then(s=>this._def.type.parseAsync(s,{path:r.path,errorMap:r.common.contextualErrorMap})))}};La.create=(a,e)=>new La({type:a,typeName:Ce.ZodPromise,...Fe(e)});var tr=class extends $e{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Ce.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:t}=this._processInputParams(e),s=this._def.effect||null,i={addIssue:n=>{ce(t,n),n.fatal?r.abort():r.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(r.value==="aborted")return Pe;let l=await this._def.schema._parseAsync({data:o,path:t.path,parent:t});return l.status==="aborted"?Pe:l.status==="dirty"||r.value==="dirty"?qn(l.value):l});{if(r.value==="aborted")return Pe;let o=this._def.schema._parseSync({data:n,path:t.path,parent:t});return o.status==="aborted"?Pe:o.status==="dirty"||r.value==="dirty"?qn(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"?Pe:(o.status==="dirty"&&r.dirty(),n(o.value),{status:r.value,value:o.value})}else return this._def.schema._parseAsync({data:t.data,path:t.path,parent:t}).then(o=>o.status==="aborted"?Pe:(o.status==="dirty"&&r.dirty(),n(o.value).then(()=>({status:r.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(!Ps(n))return Pe;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:r.value,value:o}}else return this._def.schema._parseAsync({data:t.data,path:t.path,parent:t}).then(n=>Ps(n)?Promise.resolve(s.transform(n.value,i)).then(o=>({status:r.value,value:o})):Pe);Ke.assertNever(s)}};tr.create=(a,e,r)=>new tr({schema:a,typeName:Ce.ZodEffects,effect:e,...Fe(r)});tr.createWithPreprocess=(a,e,r)=>new tr({schema:e,effect:{type:"preprocess",transform:a},typeName:Ce.ZodEffects,...Fe(r)});var vr=class extends $e{_parse(e){return this._getType(e)===de.undefined?Dt(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};vr.create=(a,e)=>new vr({innerType:a,typeName:Ce.ZodOptional,...Fe(e)});var Zr=class extends $e{_parse(e){return this._getType(e)===de.null?Dt(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Zr.create=(a,e)=>new Zr({innerType:a,typeName:Ce.ZodNullable,...Fe(e)});var qs=class extends $e{_parse(e){let{ctx:r}=this._processInputParams(e),t=r.data;return r.parsedType===de.undefined&&(t=this._def.defaultValue()),this._def.innerType._parse({data:t,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};qs.create=(a,e)=>new qs({innerType:a,typeName:Ce.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...Fe(e)});var Us=class extends $e{_parse(e){let{ctx:r}=this._processInputParams(e),t={...r,common:{...r.common,issues:[]}},s=this._def.innerType._parse({data:t.data,path:t.path,parent:{...t}});return Ji(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new er(t.common.issues)},input:t.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new er(t.common.issues)},input:t.data})}}removeCatch(){return this._def.innerType}};Us.create=(a,e)=>new Us({innerType:a,typeName:Ce.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...Fe(e)});var Wn=class extends $e{_parse(e){if(this._getType(e)!==de.nan){let t=this._getOrReturnCtx(e);return ce(t,{code:te.invalid_type,expected:de.nan,received:t.parsedType}),Pe}return{status:"valid",value:e.data}}};Wn.create=a=>new Wn({typeName:Ce.ZodNaN,...Fe(a)});var gL=Symbol("zod_brand"),eo=class extends $e{_parse(e){let{ctx:r}=this._processInputParams(e),t=r.data;return this._def.type._parse({data:t,path:r.path,parent:r})}unwrap(){return this._def.type}},to=class a extends $e{_parse(e){let{status:r,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"?Pe:i.status==="dirty"?(r.dirty(),qn(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"?Pe:s.status==="dirty"?(r.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:t.path,parent:t})}}static create(e,r){return new a({in:e,out:r,typeName:Ce.ZodPipeline})}},Hs=class extends $e{_parse(e){let r=this._def.innerType._parse(e),t=s=>(Ps(s)&&(s.value=Object.freeze(s.value)),s);return Ji(r)?r.then(s=>t(s)):t(r)}unwrap(){return this._def.innerType}};Hs.create=(a,e)=>new Hs({innerType:a,typeName:Ce.ZodReadonly,...Fe(e)});function QS(a,e){let r=typeof a=="function"?a(e):typeof a=="string"?{message:a}:a;return typeof r=="string"?{message:r}:r}function Iw(a,e={},r){return a?Ma.create().superRefine((t,s)=>{let i=a(t);if(i instanceof Promise)return i.then(n=>{if(!n){let o=QS(e,t),l=o.fatal??r??!0;s.addIssue({code:"custom",...o,fatal:l})}});if(!i){let n=QS(e,t),o=n.fatal??r??!0;s.addIssue({code:"custom",...n,fatal:o})}}):Ma.create()}var yL={object:Wt.lazycreate},Ce;(function(a){a.ZodString="ZodString",a.ZodNumber="ZodNumber",a.ZodNaN="ZodNaN",a.ZodBigInt="ZodBigInt",a.ZodBoolean="ZodBoolean",a.ZodDate="ZodDate",a.ZodSymbol="ZodSymbol",a.ZodUndefined="ZodUndefined",a.ZodNull="ZodNull",a.ZodAny="ZodAny",a.ZodUnknown="ZodUnknown",a.ZodNever="ZodNever",a.ZodVoid="ZodVoid",a.ZodArray="ZodArray",a.ZodObject="ZodObject",a.ZodUnion="ZodUnion",a.ZodDiscriminatedUnion="ZodDiscriminatedUnion",a.ZodIntersection="ZodIntersection",a.ZodTuple="ZodTuple",a.ZodRecord="ZodRecord",a.ZodMap="ZodMap",a.ZodSet="ZodSet",a.ZodFunction="ZodFunction",a.ZodLazy="ZodLazy",a.ZodLiteral="ZodLiteral",a.ZodEnum="ZodEnum",a.ZodEffects="ZodEffects",a.ZodNativeEnum="ZodNativeEnum",a.ZodOptional="ZodOptional",a.ZodNullable="ZodNullable",a.ZodDefault="ZodDefault",a.ZodCatch="ZodCatch",a.ZodPromise="ZodPromise",a.ZodBranded="ZodBranded",a.ZodPipeline="ZodPipeline",a.ZodReadonly="ZodReadonly"})(Ce||(Ce={}));var bL=(a,e={message:`Input not instance of ${a.name}`})=>Iw(r=>r instanceof a,e),Aw=$a.create,Nw=Os.create,xL=Wn.create,_L=Cs.create,Dw=ks.create,EL=Is.create,SL=Hn.create,wL=As.create,TL=Ns.create,RL=Ma.create,PL=pa.create,OL=Ar.create,CL=Bn.create,kL=da.create,IL=Wt.create,AL=Wt.strictCreate,NL=Ds.create,DL=El.create,jL=js.create,$L=Gr.create,ML=Sl.create,LL=zn.create,FL=Vn.create,qL=wl.create,UL=$s.create,HL=Ms.create,BL=Ls.create,zL=Fs.create,VL=La.create,JS=tr.create,WL=vr.create,GL=Zr.create,ZL=tr.createWithPreprocess,KL=to.create,XL=()=>Aw().optional(),YL=()=>Nw().optional(),QL=()=>Dw().optional(),JL={string:a=>$a.create({...a,coerce:!0}),number:a=>Os.create({...a,coerce:!0}),boolean:a=>ks.create({...a,coerce:!0}),bigint:a=>Cs.create({...a,coerce:!0}),date:a=>Is.create({...a,coerce:!0})},e6=Pe;var Ol="2.0",jw=w.union([w.string(),w.number().int()]),$w=w.string(),t6=w.object({progressToken:w.optional(jw)}).passthrough(),yr=w.object({_meta:w.optional(t6)}).passthrough(),Gt=w.object({method:w.string(),params:w.optional(yr)}),ao=w.object({_meta:w.optional(w.object({}).passthrough())}).passthrough(),Kr=w.object({method:w.string(),params:w.optional(ao)}),br=w.object({_meta:w.optional(w.object({}).passthrough())}).passthrough(),Cl=w.union([w.string(),w.number().int()]),r6=w.object({jsonrpc:w.literal(Ol),id:Cl}).merge(Gt).strict();var a6=w.object({jsonrpc:w.literal(Ol)}).merge(Kr).strict();var s6=w.object({jsonrpc:w.literal(Ol),id:Cl,result:br}).strict();var ew;(function(a){a[a.ConnectionClosed=-32e3]="ConnectionClosed",a[a.RequestTimeout=-32001]="RequestTimeout",a[a.ParseError=-32700]="ParseError",a[a.InvalidRequest=-32600]="InvalidRequest",a[a.MethodNotFound=-32601]="MethodNotFound",a[a.InvalidParams=-32602]="InvalidParams",a[a.InternalError=-32603]="InternalError"})(ew||(ew={}));var n6=w.object({jsonrpc:w.literal(Ol),id:Cl,error:w.object({code:w.number().int(),message:w.string(),data:w.optional(w.unknown())})}).strict();var oB=w.union([r6,a6,s6,n6]),Mw=br.strict(),Lw=Kr.extend({method:w.literal("notifications/cancelled"),params:ao.extend({requestId:Cl,reason:w.string().optional()})}),so=w.object({name:w.string(),title:w.optional(w.string())}).passthrough(),Fw=so.extend({version:w.string()}),i6=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(),o6=Gt.extend({method:w.literal("initialize"),params:yr.extend({protocolVersion:w.string(),capabilities:i6,clientInfo:Fw})}),c6=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(),l6=br.extend({protocolVersion:w.string(),capabilities:c6,serverInfo:Fw,instructions:w.optional(w.string())}),u6=Kr.extend({method:w.literal("notifications/initialized")}),qw=Gt.extend({method:w.literal("ping")}),p6=w.object({progress:w.number(),total:w.optional(w.number()),message:w.optional(w.string())}).passthrough(),Uw=Kr.extend({method:w.literal("notifications/progress"),params:ao.merge(p6).extend({progressToken:jw})}),kl=Gt.extend({params:yr.extend({cursor:w.optional($w)}).optional()}),Il=br.extend({nextCursor:w.optional($w)}),Hw=w.object({uri:w.string(),mimeType:w.optional(w.string()),_meta:w.optional(w.object({}).passthrough())}).passthrough(),Bw=Hw.extend({text:w.string()}),If=w.string().refine(a=>{try{return atob(a),!0}catch{return!1}},{message:"Invalid Base64 string"}),zw=Hw.extend({blob:If}),Vw=so.extend({uri:w.string(),description:w.optional(w.string()),mimeType:w.optional(w.string()),_meta:w.optional(w.object({}).passthrough())}),d6=so.extend({uriTemplate:w.string(),description:w.optional(w.string()),mimeType:w.optional(w.string()),_meta:w.optional(w.object({}).passthrough())}),f6=kl.extend({method:w.literal("resources/list")}),m6=Il.extend({resources:w.array(Vw)}),h6=kl.extend({method:w.literal("resources/templates/list")}),v6=Il.extend({resourceTemplates:w.array(d6)}),g6=Gt.extend({method:w.literal("resources/read"),params:yr.extend({uri:w.string()})}),y6=br.extend({contents:w.array(w.union([Bw,zw]))}),b6=Kr.extend({method:w.literal("notifications/resources/list_changed")}),x6=Gt.extend({method:w.literal("resources/subscribe"),params:yr.extend({uri:w.string()})}),_6=Gt.extend({method:w.literal("resources/unsubscribe"),params:yr.extend({uri:w.string()})}),E6=Kr.extend({method:w.literal("notifications/resources/updated"),params:ao.extend({uri:w.string()})}),S6=w.object({name:w.string(),description:w.optional(w.string()),required:w.optional(w.boolean())}).passthrough(),w6=so.extend({description:w.optional(w.string()),arguments:w.optional(w.array(S6)),_meta:w.optional(w.object({}).passthrough())}),T6=kl.extend({method:w.literal("prompts/list")}),R6=Il.extend({prompts:w.array(w6)}),P6=Gt.extend({method:w.literal("prompts/get"),params:yr.extend({name:w.string(),arguments:w.optional(w.record(w.string()))})}),Af=w.object({type:w.literal("text"),text:w.string(),_meta:w.optional(w.object({}).passthrough())}).passthrough(),Nf=w.object({type:w.literal("image"),data:If,mimeType:w.string(),_meta:w.optional(w.object({}).passthrough())}).passthrough(),Df=w.object({type:w.literal("audio"),data:If,mimeType:w.string(),_meta:w.optional(w.object({}).passthrough())}).passthrough(),O6=w.object({type:w.literal("resource"),resource:w.union([Bw,zw]),_meta:w.optional(w.object({}).passthrough())}).passthrough(),C6=Vw.extend({type:w.literal("resource_link")}),Ww=w.union([Af,Nf,Df,C6,O6]),k6=w.object({role:w.enum(["user","assistant"]),content:Ww}).passthrough(),I6=br.extend({description:w.optional(w.string()),messages:w.array(k6)}),A6=Kr.extend({method:w.literal("notifications/prompts/list_changed")}),N6=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(),D6=so.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(N6),_meta:w.optional(w.object({}).passthrough())}),j6=kl.extend({method:w.literal("tools/list")}),$6=Il.extend({tools:w.array(D6)}),Gw=br.extend({content:w.array(Ww).default([]),structuredContent:w.object({}).passthrough().optional(),isError:w.optional(w.boolean())}),cB=Gw.or(br.extend({toolResult:w.unknown()})),M6=Gt.extend({method:w.literal("tools/call"),params:yr.extend({name:w.string(),arguments:w.optional(w.record(w.unknown()))})}),L6=Kr.extend({method:w.literal("notifications/tools/list_changed")}),Zw=w.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),F6=Gt.extend({method:w.literal("logging/setLevel"),params:yr.extend({level:Zw})}),q6=Kr.extend({method:w.literal("notifications/message"),params:ao.extend({level:Zw,logger:w.optional(w.string()),data:w.unknown()})}),U6=w.object({name:w.string().optional()}).passthrough(),H6=w.object({hints:w.optional(w.array(U6)),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(),B6=w.object({role:w.enum(["user","assistant"]),content:w.union([Af,Nf,Df])}).passthrough(),z6=Gt.extend({method:w.literal("sampling/createMessage"),params:yr.extend({messages:w.array(B6),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(H6)})}),V6=br.extend({model:w.string(),stopReason:w.optional(w.enum(["endTurn","stopSequence","maxTokens"]).or(w.string())),role:w.enum(["user","assistant"]),content:w.discriminatedUnion("type",[Af,Nf,Df])}),W6=w.object({type:w.literal("boolean"),title:w.optional(w.string()),description:w.optional(w.string()),default:w.optional(w.boolean())}).passthrough(),G6=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(),Z6=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(),K6=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(),X6=w.union([W6,G6,Z6,K6]),Y6=Gt.extend({method:w.literal("elicitation/create"),params:yr.extend({message:w.string(),requestedSchema:w.object({type:w.literal("object"),properties:w.record(w.string(),X6),required:w.optional(w.array(w.string()))}).passthrough()})}),Q6=br.extend({action:w.enum(["accept","decline","cancel"]),content:w.optional(w.record(w.string(),w.unknown()))}),J6=w.object({type:w.literal("ref/resource"),uri:w.string()}).passthrough(),e5=w.object({type:w.literal("ref/prompt"),name:w.string()}).passthrough(),t5=Gt.extend({method:w.literal("completion/complete"),params:yr.extend({ref:w.union([e5,J6]),argument:w.object({name:w.string(),value:w.string()}).passthrough(),context:w.optional(w.object({arguments:w.optional(w.record(w.string(),w.string()))}))})}),r5=br.extend({completion:w.object({values:w.array(w.string()).max(100),total:w.optional(w.number().int()),hasMore:w.optional(w.boolean())}).passthrough()}),a5=w.object({uri:w.string().startsWith("file://"),name:w.optional(w.string()),_meta:w.optional(w.object({}).passthrough())}).passthrough(),s5=Gt.extend({method:w.literal("roots/list")}),n5=br.extend({roots:w.array(a5)}),i5=Kr.extend({method:w.literal("notifications/roots/list_changed")}),lB=w.union([qw,o6,t5,F6,P6,T6,f6,h6,g6,x6,_6,M6,j6]),uB=w.union([Lw,Uw,u6,i5]),pB=w.union([Mw,V6,Q6,n5]),dB=w.union([qw,z6,Y6,s5]),fB=w.union([Lw,Uw,q6,E6,b6,L6,A6]),mB=w.union([Mw,l6,r5,I6,R6,m6,v6,y6,Gw,$6]);var hB=t8($8(),1);var vB=Symbol("Let zodToJsonSchema decide on which parser to use");var gB=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");var Tf;(function(a){a.Completable="McpCompletable"})(Tf||(Tf={}));var Tl=class extends $e{_parse(e){let{ctx:r}=this._processInputParams(e),t=r.data;return this._def.type._parse({data:t,path:r.path,parent:r})}unwrap(){return this._def.type}};Tl.create=(a,e)=>new Tl({type:a,typeName:Tf.Completable,complete:e.complete,...o5(e)});function o5(a){if(!a)return{};let{errorMap:e,invalid_type_error:r,required_error:t,description:s}=a;if(e&&(r||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}=a;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??r)!==null&&c!==void 0?c:o.defaultError}},description:s}}function Kw({prompt:a,options:e}){let{systemPrompt:r,settingSources:t,sandbox:s,...i}=e??{},n,o;r===void 0?n="":typeof r=="string"?n=r:r.type==="preset"&&(o=r.append);let l=i.pathToClaudeCodeExecutable;if(!l){let ge=(0,nw.fileURLToPath)(c5.url),oe=(0,hf.join)(ge,"..");l=(0,hf.join)(oe,"cli.js")}process.env.CLAUDE_AGENT_SDK_VERSION="0.1.67";let{abortController:c=ow(),additionalDirectories:u=[],agents:p,allowedTools:f=[],betas:d,canUseTool:v,continue:h,cwd:m,disallowedTools:y=[],tools:g,env:b,executable:R=Sw()?"bun":"node",executableArgs:T=[],extraArgs:S={},fallbackModel:k,enableFileCheckpointing:N,forkSession:A,hooks:M,includePartialMessages:D,persistSession:C,maxThinkingTokens:O,maxTurns:j,maxBudgetUsd:L,mcpServers:z,model:V,outputFormat:X,permissionMode:Z="default",allowDangerouslySkipPermissions:K=!1,permissionPromptToolName:ae,plugins:J,resume:we,resumeSessionAt:fe,stderr:Ne,strictMcpConfig:Se}=i,De=X?.type==="json_schema"?X.schema:void 0,H=b;if(H||(H={...process.env}),H.CLAUDE_CODE_ENTRYPOINT||(H.CLAUDE_CODE_ENTRYPOINT="sdk-ts"),N&&(H.CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING="true"),!l)throw new Error("pathToClaudeCodeExecutable is required");let W={},re=new Map;if(z)for(let[ge,oe]of Object.entries(z))oe.type==="sdk"&&"instance"in oe?(re.set(ge,oe.instance),W[ge]={type:"sdk",name:ge}):W[ge]=oe;let ue=typeof a=="string",G=new gf({abortController:c,additionalDirectories:u,betas:d,cwd:m,executable:R,executableArgs:T,extraArgs:S,pathToClaudeCodeExecutable:l,env:H,forkSession:A,stderr:Ne,maxThinkingTokens:O,maxTurns:j,maxBudgetUsd:L,model:V,fallbackModel:k,jsonSchema:De,permissionMode:Z,allowDangerouslySkipPermissions:K,permissionPromptToolName:ae,continueConversation:h,resume:we,resumeSessionAt:fe,settingSources:t??[],allowedTools:f,disallowedTools:y,tools:g,mcpServers:W,strictMcpConfig:Se,canUseTool:!!v,hooks:!!M,includePartialMessages:D,persistSession:C,plugins:J,sandbox:s,spawnClaudeCodeProcess:i.spawnClaudeCodeProcess}),Y={systemPrompt:n,appendSystemPrompt:o,agents:p},ne=new xf(G,ue,v,M,c,re,De,Y);return typeof a=="string"?(G.write(JSON.stringify({type:"user",session_id:"",message:{role:"user",content:[{type:"text",text:a}]},parent_tool_use_id:null})+` `),ne.handleSingleTurnInputComplete()):ne.streamInput(a),ne}var Al=class{dbManager;sessionManager;constructor(e,r){this.dbManager=e,this.sessionManager=r}async startSession(e,r){try{let t=this.findClaudeExecutable(),s=this.getModelId(),i=["Bash","Read","Write","Edit","Grep","Glob","WebFetch","WebSearch","Task","NotebookEdit","AskUserQuestion","TodoWrite"],n=this.createMessageGenerator(e),o=Kw({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,p=Array.isArray(u)?u.filter(m=>m.type==="text").map(m=>m.text).join(` -`):typeof u=="string"?u:"",f=p.length,d=e.cumulativeInputTokens+e.cumulativeOutputTokens,v=c.message.usage;v&&(e.cumulativeInputTokens+=v.input_tokens||0,e.cumulativeOutputTokens+=v.output_tokens||0,v.cache_creation_input_tokens&&(e.cumulativeInputTokens+=v.cache_creation_input_tokens),$.debug("SDK","Token usage captured",{sessionId:e.sessionDbId,inputTokens:v.input_tokens,outputTokens:v.output_tokens,cacheCreation:v.cache_creation_input_tokens||0,cacheRead:v.cache_read_input_tokens||0,cumulativeInput:e.cumulativeInputTokens,cumulativeOutput:e.cumulativeOutputTokens}));let h=e.cumulativeInputTokens+e.cumulativeOutputTokens-d;if(f>0){let m=f>100?p.substring(0,100)+"...":p;$.dataOut("SDK",`Response received (${f} chars)`,{sessionId:e.sessionDbId,promptNumber:e.lastPromptNumber},m),await this.processSDKResponse(e,p,r,h)}}c.type==="result"&&c.subtype}let l=Date.now()-e.startTime;$.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"?$.warn("SDK","Agent aborted",{sessionId:e.sessionDbId}):$.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:e.lastPromptNumber===1?$S(e.project,e.claudeSessionId,e.userPrompt):FS(e.userPrompt,e.lastPromptNumber,e.claudeSessionId)},session_id:e.claudeSessionId,parent_tool_use_id:null,isSynthetic:!0};for await(let r of this.sessionManager.getMessageIterator(e.sessionDbId))r.type==="observation"?(r.prompt_number!==void 0&&(e.lastPromptNumber=r.prompt_number),yield{type:"user",message:{role:"user",content:MS({id:0,tool_name:r.tool_name,tool_input:JSON.stringify(r.tool_input),tool_output:JSON.stringify(r.tool_response),created_at_epoch:Date.now(),cwd:r.cwd})},session_id:e.claudeSessionId,parent_tool_use_id:null,isSynthetic:!0}):r.type==="summarize"&&(yield{type:"user",message:{role:"user",content:LS({id:e.sessionDbId,sdk_session_id:e.sdkSessionId,project:e.project,user_prompt:e.userPrompt,last_user_message:r.last_user_message||"",last_assistant_message:r.last_assistant_message||""})},session_id:e.claudeSessionId,parent_tool_use_id:null,isSynthetic:!0})}async processSDKResponse(e,r,t,s){let i=DS(r,e.claudeSessionId);for(let l of i){let{id:c,createdAtEpoch:u}=this.dbManager.getSessionStore().storeObservation(e.claudeSessionId,e.project,l,e.lastPromptNumber,s);$.info("SDK","Observation saved",{sessionId:e.sessionDbId,obsId:c,type:l.type,title:l.title||"(untitled)",filesRead:l.files_read?.length??0,filesModified:l.files_modified?.length??0,concepts:l.concepts?.length??0});let p=Date.now(),f=l.type,d=l.title||"(untitled)";this.dbManager.getChromaSync().syncObservation(c,e.claudeSessionId,e.project,l,e.lastPromptNumber,u,s).then(()=>{let v=Date.now()-p;$.debug("CHROMA","Observation synced",{obsId:c,duration:`${v}ms`,type:f,title:d})}).catch(v=>{$.error("CHROMA","Failed to sync observation",{obsId:c,sessionId:e.sessionDbId,type:f,title:d},v)}),t&&t.sseBroadcaster&&t.sseBroadcaster.broadcast({type:"new_observation",observation:{id:c,sdk_session_id:e.sdkSessionId,session_id:e.claudeSessionId,type:l.type,title:l.title,subtitle:l.subtitle,text:l.text||null,narrative:l.narrative||null,facts:JSON.stringify(l.facts||[]),concepts:JSON.stringify(l.concepts||[]),files_read:JSON.stringify(l.files||[]),files_modified:JSON.stringify([]),project:e.project,prompt_number:e.lastPromptNumber,created_at_epoch:u}})}let n=jS(r,e.sessionDbId);if(n){let{id:l,createdAtEpoch:c}=this.dbManager.getSessionStore().storeSummary(e.claudeSessionId,e.project,n,e.lastPromptNumber,s);$.info("SDK","Summary saved",{sessionId:e.sessionDbId,summaryId:l,request:n.request||"(no request)",hasCompleted:!!n.completed,hasNextSteps:!!n.next_steps});let u=Date.now(),p=n.request||"(no request)";this.dbManager.getChromaSync().syncSummary(l,e.claudeSessionId,e.project,n,e.lastPromptNumber,c,s).then(()=>{let f=Date.now()-u;$.debug("CHROMA","Summary synced",{summaryId:l,duration:`${f}ms`,request:p})}).catch(f=>{$.error("CHROMA","Failed to sync summary",{summaryId:l,sessionId:e.sessionDbId,request:p},f)}),t&&t.sseBroadcaster&&t.sseBroadcaster.broadcast({type:"new_summary",summary:{id:l,session_id:e.claudeSessionId,request:n.request,investigated:n.investigated,learned:n.learned,completed:n.completed,next_steps:n.next_steps,notes:n.notes,project:e.project,prompt_number:e.lastPromptNumber,created_at_epoch:c}})}let o=this.sessionManager.getPendingMessageStore();if(e.pendingProcessingIds.size>0){for(let c of e.pendingProcessingIds)o.markProcessed(c);$.debug("SDK","Messages marked as processed",{sessionId:e.sessionDbId,messageIds:Array.from(e.pendingProcessingIds),count:e.pendingProcessingIds.size}),e.pendingProcessingIds.clear();let l=o.cleanupProcessed(100);l>0&&$.debug("SDK","Cleaned up old processed messages",{deletedCount:l})}t&&typeof t.broadcastProcessingStatus=="function"&&t.broadcastProcessingStatus()}findClaudeExecutable(){let r=lt.loadFromFile(Mn).CLAUDE_CODE_PATH||(0,Xw.execSync)(process.platform==="win32"?"where claude":"which claude",{encoding:"utf8",windowsHide:!0}).trim().split(` +`):typeof u=="string"?u:"",f=p.length,d=e.cumulativeInputTokens+e.cumulativeOutputTokens,v=c.message.usage;v&&(e.cumulativeInputTokens+=v.input_tokens||0,e.cumulativeOutputTokens+=v.output_tokens||0,v.cache_creation_input_tokens&&(e.cumulativeInputTokens+=v.cache_creation_input_tokens),$.debug("SDK","Token usage captured",{sessionId:e.sessionDbId,inputTokens:v.input_tokens,outputTokens:v.output_tokens,cacheCreation:v.cache_creation_input_tokens||0,cacheRead:v.cache_read_input_tokens||0,cumulativeInput:e.cumulativeInputTokens,cumulativeOutput:e.cumulativeOutputTokens}));let h=e.cumulativeInputTokens+e.cumulativeOutputTokens-d;if(f>0){let m=f>100?p.substring(0,100)+"...":p;$.dataOut("SDK",`Response received (${f} chars)`,{sessionId:e.sessionDbId,promptNumber:e.lastPromptNumber},m),await this.processSDKResponse(e,p,r,h)}else await this.markMessagesProcessed(e,r)}c.type==="result"&&c.subtype}let l=Date.now()-e.startTime;$.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"?$.warn("SDK","Agent aborted",{sessionId:e.sessionDbId}):$.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:e.lastPromptNumber===1?$S(e.project,e.claudeSessionId,e.userPrompt):FS(e.userPrompt,e.lastPromptNumber,e.claudeSessionId)},session_id:e.claudeSessionId,parent_tool_use_id:null,isSynthetic:!0};for await(let r of this.sessionManager.getMessageIterator(e.sessionDbId))r.type==="observation"?(r.prompt_number!==void 0&&(e.lastPromptNumber=r.prompt_number),yield{type:"user",message:{role:"user",content:MS({id:0,tool_name:r.tool_name,tool_input:JSON.stringify(r.tool_input),tool_output:JSON.stringify(r.tool_response),created_at_epoch:Date.now(),cwd:r.cwd})},session_id:e.claudeSessionId,parent_tool_use_id:null,isSynthetic:!0}):r.type==="summarize"&&(yield{type:"user",message:{role:"user",content:LS({id:e.sessionDbId,sdk_session_id:e.sdkSessionId,project:e.project,user_prompt:e.userPrompt,last_user_message:r.last_user_message||"",last_assistant_message:r.last_assistant_message||""})},session_id:e.claudeSessionId,parent_tool_use_id:null,isSynthetic:!0})}async processSDKResponse(e,r,t,s){let i=DS(r,e.claudeSessionId);for(let o of i){let{id:l,createdAtEpoch:c}=this.dbManager.getSessionStore().storeObservation(e.claudeSessionId,e.project,o,e.lastPromptNumber,s);$.info("SDK","Observation saved",{sessionId:e.sessionDbId,obsId:l,type:o.type,title:o.title||"(untitled)",filesRead:o.files_read?.length??0,filesModified:o.files_modified?.length??0,concepts:o.concepts?.length??0});let u=Date.now(),p=o.type,f=o.title||"(untitled)";this.dbManager.getChromaSync().syncObservation(l,e.claudeSessionId,e.project,o,e.lastPromptNumber,c,s).then(()=>{let d=Date.now()-u;$.debug("CHROMA","Observation synced",{obsId:l,duration:`${d}ms`,type:p,title:f})}).catch(d=>{$.error("CHROMA","Failed to sync observation",{obsId:l,sessionId:e.sessionDbId,type:p,title:f},d)}),t&&t.sseBroadcaster&&t.sseBroadcaster.broadcast({type:"new_observation",observation:{id:l,sdk_session_id:e.sdkSessionId,session_id:e.claudeSessionId,type:o.type,title:o.title,subtitle:o.subtitle,text:o.text||null,narrative:o.narrative||null,facts:JSON.stringify(o.facts||[]),concepts:JSON.stringify(o.concepts||[]),files_read:JSON.stringify(o.files||[]),files_modified:JSON.stringify([]),project:e.project,prompt_number:e.lastPromptNumber,created_at_epoch:c}})}let n=jS(r,e.sessionDbId);if(n){let{id:o,createdAtEpoch:l}=this.dbManager.getSessionStore().storeSummary(e.claudeSessionId,e.project,n,e.lastPromptNumber,s);$.info("SDK","Summary saved",{sessionId:e.sessionDbId,summaryId:o,request:n.request||"(no request)",hasCompleted:!!n.completed,hasNextSteps:!!n.next_steps});let c=Date.now(),u=n.request||"(no request)";this.dbManager.getChromaSync().syncSummary(o,e.claudeSessionId,e.project,n,e.lastPromptNumber,l,s).then(()=>{let p=Date.now()-c;$.debug("CHROMA","Summary synced",{summaryId:o,duration:`${p}ms`,request:u})}).catch(p=>{$.error("CHROMA","Failed to sync summary",{summaryId:o,sessionId:e.sessionDbId,request:u},p)}),t&&t.sseBroadcaster&&t.sseBroadcaster.broadcast({type:"new_summary",summary:{id:o,session_id:e.claudeSessionId,request:n.request,investigated:n.investigated,learned:n.learned,completed:n.completed,next_steps:n.next_steps,notes:n.notes,project:e.project,prompt_number:e.lastPromptNumber,created_at_epoch:l}})}await this.markMessagesProcessed(e,t)}async markMessagesProcessed(e,r){let t=this.sessionManager.getPendingMessageStore();if(e.pendingProcessingIds.size>0){for(let i of e.pendingProcessingIds)t.markProcessed(i);$.debug("SDK","Messages marked as processed",{sessionId:e.sessionDbId,messageIds:Array.from(e.pendingProcessingIds),count:e.pendingProcessingIds.size}),e.pendingProcessingIds.clear();let s=t.cleanupProcessed(100);s>0&&$.debug("SDK","Cleaned up old processed messages",{deletedCount:s})}r&&typeof r.broadcastProcessingStatus=="function"&&r.broadcastProcessingStatus()}findClaudeExecutable(){let r=lt.loadFromFile(Mn).CLAUDE_CODE_PATH||(0,Xw.execSync)(process.platform==="win32"?"where claude":"which claude",{encoding:"utf8",windowsHide:!0}).trim().split(` `)[0].trim();if(!r)throw new Error("Claude executable not found in PATH");return r}getModelId(){let e=Qw.default.join((0,Yw.homedir)(),".claude-mem","settings.json");return lt.loadFromFile(e).CLAUDE_MEM_MODEL}};var Nl=class{dbManager;constructor(e){this.dbManager=e}stripProjectPath(e,r){let t=`/${r}/`,s=e.indexOf(t);return s!==-1?e.substring(s+t.length):e}stripProjectPaths(e,r){if(!e)return e;try{let s=JSON.parse(e).map(i=>this.stripProjectPath(i,r));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,r,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,r,t);return{...s,items:s.items.map(i=>this.sanitizeObservation(i))}}getSummaries(e,r,t){let s=this.dbManager.getSessionStore().db,i=` SELECT ss.id, diff --git a/plugin/skills/mem-search.zip b/plugin/skills/mem-search.zip index 49d8812325245c4de58fec0184fb566a26ea2573..ac8cd76b752cfd04101144dc924db48ecec11a78 100644 GIT binary patch delta 142 zcmezKi}BAd#tBcEUkW>Ke6fQQL~mZqWxxhzToce^2Q%0uWdVyFAhwAtGmTH}C@hRWvlq delta 142 zcmezKi}BAd#tBcEXa05E_+keqh~B)I%YY5cxF(>-4rZ`R%!G(6mQ&{di=0)9fk^4- zL8VTZ6hhS4SbIYlU5&1#g?D9x!gqU+CcLP5FrP(~K diff --git a/src/services/worker/SDKAgent.ts b/src/services/worker/SDKAgent.ts index 815b384c..ee686530 100644 --- a/src/services/worker/SDKAgent.ts +++ b/src/services/worker/SDKAgent.ts @@ -113,7 +113,7 @@ export class SDKAgent { // Calculate discovery tokens (delta for this response only) const discoveryTokens = (session.cumulativeInputTokens + session.cumulativeOutputTokens) - tokensBeforeResponse; - // Only log non-empty responses (filter out noise) + // Process response (empty or not) and mark messages as processed if (responseSize > 0) { const truncatedResponse = responseSize > 100 ? textContent.substring(0, 100) + '...' @@ -125,6 +125,9 @@ export class SDKAgent { // Parse and process response with discovery token delta await this.processSDKResponse(session, textContent, worker, discoveryTokens); + } else { + // Empty response - still need to mark pending messages as processed + await this.markMessagesProcessed(session, worker); } } @@ -396,8 +399,15 @@ export class SDKAgent { } } - // CRITICAL: Mark ALL pending messages as successfully processed - // This prevents message loss if worker crashes before SDK finishes + // Mark messages as processed after successful observation/summary storage + await this.markMessagesProcessed(session, worker); + } + + /** + * Mark all pending messages as successfully processed + * CRITICAL: Prevents message loss and duplicate processing + */ + private async markMessagesProcessed(session: ActiveSession, worker: any | undefined): Promise { const pendingMessageStore = this.sessionManager.getPendingMessageStore(); if (session.pendingProcessingIds.size > 0) { for (const messageId of session.pendingProcessingIds) {