diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index 6cbf19be..dea7862b 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -10,7 +10,7 @@ "plugins": [ { "name": "claude-mem", - "version": "6.5.2", + "version": "6.5.3", "source": "./plugin", "description": "Persistent memory system for Claude Code - context compression across sessions" } diff --git a/CLAUDE.md b/CLAUDE.md index a9afa0db..a3ac4fa2 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -6,7 +6,7 @@ Claude-mem is a Claude Code plugin providing persistent memory across sessions. It captures tool usage, compresses observations using the Claude Agent SDK, and injects relevant context into future sessions. -**Current Version**: 6.5.2 +**Current Version**: 6.5.3 ## Architecture diff --git a/package.json b/package.json index a1ce54f4..2be9987d 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "claude-mem", - "version": "6.5.2", + "version": "6.5.3", "description": "Memory compression system for Claude Code - persist context across sessions", "keywords": [ "claude", diff --git a/plugin/.claude-plugin/plugin.json b/plugin/.claude-plugin/plugin.json index 4b7b9d8f..5e182d88 100644 --- a/plugin/.claude-plugin/plugin.json +++ b/plugin/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "claude-mem", - "version": "6.5.2", + "version": "6.5.3", "description": "Persistent memory system for Claude Code - seamlessly preserve context across sessions", "author": { "name": "Alex Newman" diff --git a/plugin/scripts/worker-service.cjs b/plugin/scripts/worker-service.cjs index 9507c845..5ee7b335 100755 --- a/plugin/scripts/worker-service.cjs +++ b/plugin/scripts/worker-service.cjs @@ -857,7 +857,7 @@ MEMORY PROCESSING CONTINUED `))})}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){ta("[Query.streamInput] Starting to process input stream"),ta(`[Query.streamInput] this.sdkMcpTransports.size = ${this.sdkMcpTransports.size}`);try{let r=0;for await(let t of e){if(r++,ta(`[Query.streamInput] Processing message ${r}: ${t.type}`),this.abortController?.signal.aborted)break;await Promise.resolve(this.transport.write(JSON.stringify(t)+` `))}if(ta(`[Query.streamInput] Finished processing ${r} messages from input stream`),ta(`[Query.streamInput] About to check MCP servers. this.sdkMcpTransports.size = ${this.sdkMcpTransports.size}`),this.sdkMcpTransports.size>0&&this.firstResultReceivedPromise){ta("[Query.streamInput] Entering Promise.race to wait for result");let t=1e4,s;await Promise.race([this.firstResultReceivedPromise.then(()=>{ta("[Query.streamInput] Received first result, closing input stream"),s&&clearTimeout(s)}),new Promise(i=>{s=setTimeout(()=>{ta("[Query.streamInput] Timed out waiting for first result, closing input stream"),i()},t)})]),s&&clearTimeout(s)}ta("[Query] Calling transport.endInput() to close stdin to CLI process"),this.transport.endInput()}catch(r){if(!(r instanceof vs))throw 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 t=`${e}:${r.id}`,s=this.pendingMcpResponses.get(t);if(s){s.resolve(r),this.pendingMcpResponses.delete(t);return}}throw new Error("No pending request found")}handleMcpControlRequest(e,r,t){let s="id"in r.message?r.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)},p=m=>{c(),o(m)};if(this.pendingMcpResponses.set(i,{resolve:u,reject:p}),t.onmessage)t.onmessage(r.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={};Fj(w,{void:()=>i6,util:()=>Ge,unknown:()=>s6,union:()=>u6,undefined:()=>t6,tuple:()=>f6,transformer:()=>i1,symbol:()=>e6,string:()=>N1,strictObject:()=>l6,setErrorMap:()=>P5,set:()=>v6,record:()=>m6,quotelessJson:()=>w5,promise:()=>E6,preprocess:()=>P6,pipeline:()=>T6,ostring:()=>R6,optional:()=>w6,onumber:()=>O6,oboolean:()=>C6,objectUtil:()=>Nd,object:()=>c6,number:()=>j1,nullable:()=>S6,null:()=>r6,never:()=>n6,nativeEnum:()=>_6,nan:()=>Q5,map:()=>h6,makeIssue:()=>Zc,literal:()=>b6,lazy:()=>y6,late:()=>K5,isValid:()=>ys,isDirty:()=>Dd,isAsync:()=>Ii,isAborted:()=>jd,intersection:()=>d6,instanceof:()=>X5,getParsedType:()=>aa,getErrorMap:()=>Wc,function:()=>g6,enum:()=>x6,effect:()=>i1,discriminatedUnion:()=>p6,defaultErrorMap:()=>Tn,datetimeRegex:()=>k1,date:()=>J5,custom:()=>I1,coerce:()=>k6,boolean:()=>D1,bigint:()=>Y5,array:()=>o6,any:()=>a6,addIssueToContext:()=>se,ZodVoid:()=>On,ZodUnknown:()=>na,ZodUnion:()=>Ps,ZodUndefined:()=>ws,ZodType:()=>Ne,ZodTuple:()=>zr,ZodTransformer:()=>Qt,ZodSymbol:()=>Rn,ZodString:()=>ka,ZodSet:()=>kn,ZodSchema:()=>Ne,ZodRecord:()=>Xc,ZodReadonly:()=>Ns,ZodPromise:()=>Ia,ZodPipeline:()=>ji,ZodParsedType:()=>le,ZodOptional:()=>dr,ZodObject:()=>zt,ZodNumber:()=>bs,ZodNullable:()=>Hr,ZodNull:()=>Ss,ZodNever:()=>Rr,ZodNativeEnum:()=>ks,ZodNaN:()=>An,ZodMap:()=>Cn,ZodLiteral:()=>Os,ZodLazy:()=>Rs,ZodIssueCode:()=>J,ZodIntersection:()=>Ts,ZodFunction:()=>Qc,ZodFirstPartyTypeKind:()=>Pe,ZodError:()=>Xt,ZodEnum:()=>Cs,ZodEffects:()=>Qt,ZodDiscriminatedUnion:()=>Kc,ZodDefault:()=>As,ZodDate:()=>Es,ZodCatch:()=>Is,ZodBranded:()=>Ni,ZodBoolean:()=>_s,ZodBigInt:()=>xs,ZodArray:()=>ia,ZodAny:()=>Aa,Schema:()=>Ne,ParseStatus:()=>Tt,OK:()=>Ct,NEVER:()=>A6,INVALID:()=>we,EMPTY_PATH:()=>T5,DIRTY:()=>Pn,BRAND:()=>Z5});var Ge;(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})(Ge||(Ge={}));var Nd;(function(a){a.mergeShapes=(e,r)=>({...e,...r})})(Nd||(Nd={}));var le=Ge.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),aa=a=>{switch(typeof a){case"undefined":return le.undefined;case"string":return le.string;case"number":return Number.isNaN(a)?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(a)?le.array:a===null?le.null:a.then&&typeof a.then=="function"&&a.catch&&typeof a.catch=="function"?le.promise:typeof Map<"u"&&a instanceof Map?le.map:typeof Set<"u"&&a instanceof Set?le.set:typeof Date<"u"&&a instanceof Date?le.date:le.object;default:return le.unknown}},J=Ge.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"]),w5=a=>JSON.stringify(a,null,2).replace(/"([^"]+)":/g,"$1:"),Xt=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()}};Xt.create=a=>new Xt(a);var S5=(a,e)=>{let r;switch(a.code){case J.invalid_type:a.received===le.undefined?r="Required":r=`Expected ${a.expected}, received ${a.received}`;break;case J.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(a.expected,Ge.jsonStringifyReplacer)}`;break;case J.unrecognized_keys:r=`Unrecognized key(s) in object: ${Ge.joinValues(a.keys,", ")}`;break;case J.invalid_union:r="Invalid input";break;case J.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${Ge.joinValues(a.options)}`;break;case J.invalid_enum_value:r=`Invalid enum value. Expected ${Ge.joinValues(a.options)}, received '${a.received}'`;break;case J.invalid_arguments:r="Invalid function arguments";break;case J.invalid_return_type:r="Invalid function return type";break;case J.invalid_date:r="Invalid date";break;case J.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}"`:Ge.assertNever(a.validation):a.validation!=="regex"?r=`Invalid ${a.validation}`:r="Invalid";break;case J.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 J.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 J.custom:r="Invalid input";break;case J.invalid_intersection_types:r="Intersection results could not be merged";break;case J.not_multiple_of:r=`Number must be a multiple of ${a.multipleOf}`;break;case J.not_finite:r="Number must be finite";break;default:r=e.defaultError,Ge.assertNever(a)}return{message:r}},Tn=S5,R1=Tn;function P5(a){R1=a}function Wc(){return R1}var Zc=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}},T5=[];function se(a,e){let r=Wc(),t=Zc({issueData:e,data:a.data,path:a.path,errorMaps:[a.common.contextualErrorMap,a.schemaErrorMap,r,r===Tn?void 0:Tn].filter(s=>!!s)});a.common.issues.push(t)}var Tt=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 we;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 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"}),Pn=a=>({status:"dirty",value:a}),Ct=a=>({status:"valid",value:a}),jd=a=>a.status==="aborted",Dd=a=>a.status==="dirty",ys=a=>a.status==="valid",Ii=a=>typeof Promise<"u"&&a instanceof Promise,me;(function(a){a.errToObj=e=>typeof e=="string"?{message:e}:e||{},a.toString=e=>typeof e=="string"?e:e?.message})(me||(me={}));var fr=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}},s1=(a,e)=>{if(ys(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 Xt(a.common.issues);return this._error=r,this._error}}};function $e(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 Ne=class{get description(){return this._def.description}_getType(e){return aa(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:aa(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Tt,ctx:{common:e.parent.common,data:e.data,parsedType:aa(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(Ii(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:aa(e)},s=this._parseSync({data:e,path:t.path,parent:t});return s1(t,s)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:aa(e)};if(!this["~standard"].async)try{let t=this._parseSync({data:e,path:[],parent:r});return ys(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=>ys(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:aa(e)},s=this._parse({data:e,path:t.path,parent:t}),i=await(Ii(s)?s:Promise.resolve(s));return s1(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:J.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 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:r=>this["~validate"](r)}}optional(){return dr.create(this,this._def)}nullable(){return Hr.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ia.create(this)}promise(){return Ia.create(this,this._def)}or(e){return Ps.create([this,e],this._def)}and(e){return Ts.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 r=typeof e=="function"?e:()=>e;return new As({...$e(this._def),innerType:this,defaultValue:r,typeName:Pe.ZodDefault})}brand(){return new Ni({typeName:Pe.ZodBranded,type:this,...$e(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new Is({...$e(this._def),innerType:this,catchValue:r,typeName:Pe.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return ji.create(this,e)}readonly(){return Ns.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},R5=/^c[^\s-]{8,}$/i,O5=/^[0-9a-z]+$/,C5=/^[0-9A-HJKMNP-TV-Z]{26}$/i,k5=/^[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,A5=/^[a-z0-9_-]{21}$/i,I5=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,N5=/^[-+]?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)?)??$/,j5=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,D5="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Pd,$5=/^(?:(?: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])$/,M5=/^(?:(?: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])$/,L5=/^(([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]))$/,q5=/^(([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])$/,F5=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,U5=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,O1="((\\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])))",z5=new RegExp(`^${O1}$`);function C1(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 H5(a){return new RegExp(`^${C1(a)}$`)}function k1(a){let e=`${O1}T${C1(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 B5(a,e){return!!((e==="v4"||!e)&&$5.test(a)||(e==="v6"||!e)&&L5.test(a))}function V5(a,e){if(!I5.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 G5(a,e){return!!((e==="v4"||!e)&&M5.test(a)||(e==="v6"||!e)&&q5.test(a))}var ka=class a extends Ne{_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 Tt,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:r,code:J.invalid_string,...me.errToObj(t)})}_addCheck(e){return new a({...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,r){return this._addCheck({kind:"regex",regex:e,...me.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...me.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...me.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...me.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...me.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...me.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...me.errToObj(r)})}nonempty(e){return this.min(1,me.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 ka({checks:[],typeName:Pe.ZodString,coerce:a?.coerce??!1,...$e(a)});function W5(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 bs=class a extends Ne{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 Tt;for(let i of this._def.checks)i.kind==="int"?Ge.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"?W5(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()):Ge.assertNever(i);return{status:s.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,me.toString(r))}gt(e,r){return this.setLimit("min",e,!1,me.toString(r))}lte(e,r){return this.setLimit("max",e,!0,me.toString(r))}lt(e,r){return this.setLimit("max",e,!1,me.toString(r))}setLimit(e,r,t,s){return new a({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:t,message:me.toString(s)}]})}_addCheck(e){return new a({...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,r){return this._addCheck({kind:"multipleOf",value:e,message:me.toString(r)})}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 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"&&Ge.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 bs({checks:[],typeName:Pe.ZodNumber,coerce:a?.coerce||!1,...$e(a)});var xs=class a extends Ne{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 Tt;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()):Ge.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return se(r,{code:J.invalid_type,expected:le.bigint,received:r.parsedType}),we}gte(e,r){return this.setLimit("min",e,!0,me.toString(r))}gt(e,r){return this.setLimit("min",e,!1,me.toString(r))}lte(e,r){return this.setLimit("max",e,!0,me.toString(r))}lt(e,r){return this.setLimit("max",e,!1,me.toString(r))}setLimit(e,r,t,s){return new a({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:t,message:me.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: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,r){return this._addCheck({kind:"multipleOf",value:e,message:me.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 xs({checks:[],typeName:Pe.ZodBigInt,coerce:a?.coerce??!1,...$e(a)});var _s=class extends Ne{_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 Ct(e.data)}};_s.create=a=>new _s({typeName:Pe.ZodBoolean,coerce:a?.coerce||!1,...$e(a)});var Es=class a extends Ne{_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 Tt,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()):Ge.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:me.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:me.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 Es({checks:[],coerce:a?.coerce||!1,typeName:Pe.ZodDate,...$e(a)});var Rn=class extends Ne{_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 Ct(e.data)}};Rn.create=a=>new Rn({typeName:Pe.ZodSymbol,...$e(a)});var ws=class extends Ne{_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 Ct(e.data)}};ws.create=a=>new ws({typeName:Pe.ZodUndefined,...$e(a)});var Ss=class extends Ne{_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 Ct(e.data)}};Ss.create=a=>new Ss({typeName:Pe.ZodNull,...$e(a)});var Aa=class extends Ne{constructor(){super(...arguments),this._any=!0}_parse(e){return Ct(e.data)}};Aa.create=a=>new Aa({typeName:Pe.ZodAny,...$e(a)});var na=class extends Ne{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Ct(e.data)}};na.create=a=>new na({typeName:Pe.ZodUnknown,...$e(a)});var Rr=class extends Ne{_parse(e){let r=this._getOrReturnCtx(e);return se(r,{code:J.invalid_type,expected:le.never,received:r.parsedType}),we}};Rr.create=a=>new Rr({typeName:Pe.ZodNever,...$e(a)});var On=class extends Ne{_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 Ct(e.data)}};On.create=a=>new On({typeName:Pe.ZodVoid,...$e(a)});var ia=class a extends Ne{_parse(e){let{ctx:r,status:t}=this._processInputParams(e),s=this._def;if(r.parsedType!==le.array)return se(r,{code:J.invalid_type,expected:le.array,received:r.parsedType}),we;if(s.exactLength!==null){let n=r.data.length>s.exactLength.value,o=r.data.lengths.maxLength.value&&(se(r,{code:J.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 fr(r,n,r.path,o)))).then(n=>Tt.mergeArray(t,n));let i=[...r.data].map((n,o)=>s.type._parseSync(new fr(r,n,r.path,o)));return Tt.mergeArray(t,i)}get element(){return this._def.type}min(e,r){return new a({...this._def,minLength:{value:e,message:me.toString(r)}})}max(e,r){return new a({...this._def,maxLength:{value:e,message:me.toString(r)}})}length(e,r){return new a({...this._def,exactLength:{value:e,message:me.toString(r)}})}nonempty(e){return this.min(1,e)}};ia.create=(a,e)=>new ia({type:a,minLength:null,maxLength:null,exactLength:null,typeName:Pe.ZodArray,...$e(e)});function Sn(a){if(a instanceof zt){let e={};for(let r in a.shape){let t=a.shape[r];e[r]=dr.create(Sn(t))}return new zt({...a._def,shape:()=>e})}else return a instanceof ia?new ia({...a._def,type:Sn(a.element)}):a instanceof dr?dr.create(Sn(a.unwrap())):a instanceof Hr?Hr.create(Sn(a.unwrap())):a instanceof zr?zr.create(a.items.map(e=>Sn(e))):a}var zt=class a extends Ne{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=Ge.objectKeys(e);return this._cached={shape:e,keys:r},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 Rr&&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 fr(s,p,s.path,c)),alwaysSet:c in s.data})}if(this._def.catchall instanceof Rr){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 p=s.data[u];l.push({key:{status:"valid",value:u},value:c._parse(new fr(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,m=await u.value;c.push({key:p,value:m,alwaysSet:u.alwaysSet})}return c}).then(c=>Tt.mergeObjectSync(t,c)):Tt.mergeObjectSync(t,l)}get shape(){return this._def.shape()}strict(e){return me.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:me.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:Pe.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 Ge.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 Ge.objectKeys(this.shape))e[t]||(r[t]=this.shape[t]);return new a({...this._def,shape:()=>r})}deepPartial(){return Sn(this)}partial(e){let r={};for(let t of Ge.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 Ge.objectKeys(this.shape))if(e&&!e[t])r[t]=this.shape[t];else{let i=this.shape[t];for(;i instanceof dr;)i=i._def.innerType;r[t]=i}return new a({...this._def,shape:()=>r})}keyof(){return A1(Ge.objectKeys(this.shape))}};zt.create=(a,e)=>new zt({shape:()=>a,unknownKeys:"strip",catchall:Rr.create(),typeName:Pe.ZodObject,...$e(e)});zt.strictCreate=(a,e)=>new zt({shape:()=>a,unknownKeys:"strict",catchall:Rr.create(),typeName:Pe.ZodObject,...$e(e)});zt.lazycreate=(a,e)=>new zt({shape:a,unknownKeys:"strip",catchall:Rr.create(),typeName:Pe.ZodObject,...$e(e)});var Ps=class extends Ne{_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 Xt(o.ctx.common.issues));return se(r,{code:J.invalid_union,unionErrors:n}),we}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 Xt(l));return se(r,{code:J.invalid_union,unionErrors:o}),we}}get options(){return this._def.options}};Ps.create=(a,e)=>new Ps({options:a,typeName:Pe.ZodUnion,...$e(e)});var ra=a=>a instanceof Rs?ra(a.schema):a instanceof Qt?ra(a.innerType()):a instanceof Os?[a.value]:a instanceof Cs?a.options:a instanceof ks?Ge.objectValues(a.enum):a instanceof As?ra(a._def.innerType):a instanceof ws?[void 0]:a instanceof Ss?[null]:a instanceof dr?[void 0,...ra(a.unwrap())]:a instanceof Hr?[null,...ra(a.unwrap())]:a instanceof Ni||a instanceof Ns?ra(a.unwrap()):a instanceof Is?ra(a._def.innerType):[],Kc=class a extends Ne{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==le.object)return se(r,{code:J.invalid_type,expected:le.object,received:r.parsedType}),we;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}):(se(r,{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,r,t){let s=new Map;for(let i of r){let n=ra(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:Pe.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:s,...$e(t)})}};function $d(a,e){let r=aa(a),t=aa(e);if(a===e)return{valid:!0,data:a};if(r===le.object&&t===le.object){let s=Ge.objectKeys(e),i=Ge.objectKeys(a).filter(o=>s.indexOf(o)!==-1),n={...a,...e};for(let o of i){let l=$d(a[o],e[o]);if(!l.valid)return{valid:!1};n[o]=l.data}return{valid:!0,data:n}}else if(r===le.array&&t===le.array){if(a.length!==e.length)return{valid:!1};let s=[];for(let i=0;i{if(jd(i)||jd(n))return we;let o=$d(i.value,n.value);return o.valid?((Dd(i)||Dd(n))&&r.dirty(),{status:r.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}))}};Ts.create=(a,e,r)=>new Ts({left:a,right:e,typeName:Pe.ZodIntersection,...$e(r)});var zr=class a extends Ne{_parse(e){let{status:r,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"}),r.dirty());let i=[...t.data].map((n,o)=>{let l=this._def.items[o]||this._def.rest;return l?l._parse(new fr(t,n,t.path,o)):null}).filter(n=>!!n);return t.common.async?Promise.all(i).then(n=>Tt.mergeArray(r,n)):Tt.mergeArray(r,i)}get items(){return this._def.items}rest(e){return new a({...this._def,rest:e})}};zr.create=(a,e)=>{if(!Array.isArray(a))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new zr({items:a,typeName:Pe.ZodTuple,rest:null,...$e(e)})};var Xc=class a extends Ne{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!==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 fr(t,o,t.path,o)),value:n._parse(new fr(t,t.data[o],t.path,o)),alwaysSet:o in t.data});return t.common.async?Tt.mergeObjectAsync(r,s):Tt.mergeObjectSync(r,s)}get element(){return this._def.valueType}static create(e,r,t){return r instanceof Ne?new a({keyType:e,valueType:r,typeName:Pe.ZodRecord,...$e(t)}):new a({keyType:ka.create(),valueType:e,typeName:Pe.ZodRecord,...$e(r)})}},Cn=class extends Ne{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!==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 fr(t,o,t.path,[c,"key"])),value:i._parse(new fr(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")&&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 we;(c.status==="dirty"||u.status==="dirty")&&r.dirty(),o.set(c.value,u.value)}return{status:r.value,value:o}}}};Cn.create=(a,e,r)=>new Cn({valueType:e,keyType:a,typeName:Pe.ZodMap,...$e(r)});var kn=class a extends Ne{_parse(e){let{status:r,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}),r.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"&&r.dirty(),c.add(u.value)}return{status:r.value,value:c}}let o=[...t.data.values()].map((l,c)=>i._parse(new fr(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:me.toString(r)}})}max(e,r){return new a({...this._def,maxSize:{value:e,message:me.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};kn.create=(a,e)=>new kn({valueType:a,minSize:null,maxSize:null,typeName:Pe.ZodSet,...$e(e)});var Qc=class a extends Ne{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==le.function)return se(r,{code:J.invalid_type,expected:le.function,received:r.parsedType}),we;function t(o,l){return Zc({data:o,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Wc(),Tn].filter(c=>!!c),issueData:{code:J.invalid_arguments,argumentsError:l}})}function s(o,l){return Zc({data:o,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Wc(),Tn].filter(c=>!!c),issueData:{code:J.invalid_return_type,returnTypeError:l}})}let i={errorMap:r.common.contextualErrorMap},n=r.data;if(this._def.returns instanceof Ia){let o=this;return Ct(async function(...l){let c=new Xt([]),u=await o._def.args.parseAsync(l,i).catch(f=>{throw c.addIssue(t(l,f)),c}),p=await Reflect.apply(n,this,u);return await o._def.returns._def.type.parseAsync(p,i).catch(f=>{throw c.addIssue(s(p,f)),c})})}else{let o=this;return Ct(function(...l){let c=o._def.args.safeParse(l,i);if(!c.success)throw new Xt([t(l,c.error)]);let u=Reflect.apply(n,this,c.data),p=o._def.returns.safeParse(u,i);if(!p.success)throw new Xt([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:zr.create(e).rest(na.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||zr.create([]).rest(na.create()),returns:r||na.create(),typeName:Pe.ZodFunction,...$e(t)})}},Rs=class extends Ne{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})}};Rs.create=(a,e)=>new Rs({getter:a,typeName:Pe.ZodLazy,...$e(e)});var Os=class extends Ne{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return se(r,{received:r.data,code:J.invalid_literal,expected:this._def.value}),we}return{status:"valid",value:e.data}}get value(){return this._def.value}};Os.create=(a,e)=>new Os({value:a,typeName:Pe.ZodLiteral,...$e(e)});function A1(a,e){return new Cs({values:a,typeName:Pe.ZodEnum,...$e(e)})}var Cs=class a extends Ne{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),t=this._def.values;return se(r,{expected:Ge.joinValues(t),received:r.parsedType,code:J.invalid_type}),we}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 se(r,{received:r.data,code:J.invalid_enum_value,options:t}),we}return Ct(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})}};Cs.create=A1;var ks=class extends Ne{_parse(e){let r=Ge.getValidEnumValues(this._def.values),t=this._getOrReturnCtx(e);if(t.parsedType!==le.string&&t.parsedType!==le.number){let s=Ge.objectValues(r);return se(t,{expected:Ge.joinValues(s),received:t.parsedType,code:J.invalid_type}),we}if(this._cache||(this._cache=new Set(Ge.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=Ge.objectValues(r);return se(t,{received:t.data,code:J.invalid_enum_value,options:s}),we}return Ct(e.data)}get enum(){return this._def.values}};ks.create=(a,e)=>new ks({values:a,typeName:Pe.ZodNativeEnum,...$e(e)});var Ia=class extends Ne{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==le.promise&&r.common.async===!1)return se(r,{code:J.invalid_type,expected:le.promise,received:r.parsedType}),we;let t=r.parsedType===le.promise?r.data:Promise.resolve(r.data);return Ct(t.then(s=>this._def.type.parseAsync(s,{path:r.path,errorMap:r.common.contextualErrorMap})))}};Ia.create=(a,e)=>new Ia({type:a,typeName:Pe.ZodPromise,...$e(e)});var Qt=class extends Ne{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:r,ctx:t}=this._processInputParams(e),s=this._def.effect||null,i={addIssue:n=>{se(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 we;let l=await this._def.schema._parseAsync({data:o,path:t.path,parent:t});return l.status==="aborted"?we:l.status==="dirty"||r.value==="dirty"?Pn(l.value):l});{if(r.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"||r.value==="dirty"?Pn(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"&&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"?we:(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(!ys(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:r.value,value:o}}else return this._def.schema._parseAsync({data:t.data,path:t.path,parent:t}).then(n=>ys(n)?Promise.resolve(s.transform(n.value,i)).then(o=>({status:r.value,value:o})):we);Ge.assertNever(s)}};Qt.create=(a,e,r)=>new Qt({schema:a,typeName:Pe.ZodEffects,effect:e,...$e(r)});Qt.createWithPreprocess=(a,e,r)=>new Qt({schema:e,effect:{type:"preprocess",transform:a},typeName:Pe.ZodEffects,...$e(r)});var dr=class extends Ne{_parse(e){return this._getType(e)===le.undefined?Ct(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};dr.create=(a,e)=>new dr({innerType:a,typeName:Pe.ZodOptional,...$e(e)});var Hr=class extends Ne{_parse(e){return this._getType(e)===le.null?Ct(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Hr.create=(a,e)=>new Hr({innerType:a,typeName:Pe.ZodNullable,...$e(e)});var As=class extends Ne{_parse(e){let{ctx:r}=this._processInputParams(e),t=r.data;return r.parsedType===le.undefined&&(t=this._def.defaultValue()),this._def.innerType._parse({data:t,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};As.create=(a,e)=>new As({innerType:a,typeName:Pe.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...$e(e)});var Is=class extends Ne{_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 Ii(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Xt(t.common.issues)},input:t.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Xt(t.common.issues)},input:t.data})}}removeCatch(){return this._def.innerType}};Is.create=(a,e)=>new Is({innerType:a,typeName:Pe.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...$e(e)});var An=class extends Ne{_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}}};An.create=a=>new An({typeName:Pe.ZodNaN,...$e(a)});var Z5=Symbol("zod_brand"),Ni=class extends Ne{_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}},ji=class a extends Ne{_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"?we:i.status==="dirty"?(r.dirty(),Pn(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"?(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:Pe.ZodPipeline})}},Ns=class extends Ne{_parse(e){let r=this._def.innerType._parse(e),t=s=>(ys(s)&&(s.value=Object.freeze(s.value)),s);return Ii(r)?r.then(s=>t(s)):t(r)}unwrap(){return this._def.innerType}};Ns.create=(a,e)=>new Ns({innerType:a,typeName:Pe.ZodReadonly,...$e(e)});function n1(a,e){let r=typeof a=="function"?a(e):typeof a=="string"?{message:a}:a;return typeof r=="string"?{message:r}:r}function I1(a,e={},r){return a?Aa.create().superRefine((t,s)=>{let i=a(t);if(i instanceof Promise)return i.then(n=>{if(!n){let o=n1(e,t),l=o.fatal??r??!0;s.addIssue({code:"custom",...o,fatal:l})}});if(!i){let n=n1(e,t),o=n.fatal??r??!0;s.addIssue({code:"custom",...n,fatal:o})}}):Aa.create()}var K5={object:zt.lazycreate},Pe;(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"})(Pe||(Pe={}));var X5=(a,e={message:`Input not instance of ${a.name}`})=>I1(r=>r instanceof a,e),N1=ka.create,j1=bs.create,Q5=An.create,Y5=xs.create,D1=_s.create,J5=Es.create,e6=Rn.create,t6=ws.create,r6=Ss.create,a6=Aa.create,s6=na.create,n6=Rr.create,i6=On.create,o6=ia.create,c6=zt.create,l6=zt.strictCreate,u6=Ps.create,p6=Kc.create,d6=Ts.create,f6=zr.create,m6=Xc.create,h6=Cn.create,v6=kn.create,g6=Qc.create,y6=Rs.create,b6=Os.create,x6=Cs.create,_6=ks.create,E6=Ia.create,i1=Qt.create,w6=dr.create,S6=Hr.create,P6=Qt.createWithPreprocess,T6=ji.create,R6=()=>N1().optional(),O6=()=>j1().optional(),C6=()=>D1().optional(),k6={string:a=>ka.create({...a,coerce:!0}),number:a=>bs.create({...a,coerce:!0}),boolean:a=>_s.create({...a,coerce:!0}),bigint:a=>xs.create({...a,coerce:!0}),date:a=>Es.create({...a,coerce:!0})},A6=we;var tl="2.0",$1=w.union([w.string(),w.number().int()]),M1=w.string(),I6=w.object({progressToken:w.optional($1)}).passthrough(),mr=w.object({_meta:w.optional(I6)}).passthrough(),Ht=w.object({method:w.string(),params:w.optional(mr)}),$i=w.object({_meta:w.optional(w.object({}).passthrough())}).passthrough(),Br=w.object({method:w.string(),params:w.optional($i)}),hr=w.object({_meta:w.optional(w.object({}).passthrough())}).passthrough(),rl=w.union([w.string(),w.number().int()]),N6=w.object({jsonrpc:w.literal(tl),id:rl}).merge(Ht).strict();var j6=w.object({jsonrpc:w.literal(tl)}).merge(Br).strict();var D6=w.object({jsonrpc:w.literal(tl),id:rl,result:hr}).strict();var o1;(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"})(o1||(o1={}));var $6=w.object({jsonrpc:w.literal(tl),id:rl,error:w.object({code:w.number().int(),message:w.string(),data:w.optional(w.unknown())})}).strict();var eU=w.union([N6,j6,D6,$6]),L1=hr.strict(),q1=Br.extend({method:w.literal("notifications/cancelled"),params:$i.extend({requestId:rl,reason:w.string().optional()})}),Mi=w.object({name:w.string(),title:w.optional(w.string())}).passthrough(),F1=Mi.extend({version:w.string()}),M6=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(),L6=Ht.extend({method:w.literal("initialize"),params:mr.extend({protocolVersion:w.string(),capabilities:M6,clientInfo:F1})}),q6=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(),F6=hr.extend({protocolVersion:w.string(),capabilities:q6,serverInfo:F1,instructions:w.optional(w.string())}),U6=Br.extend({method:w.literal("notifications/initialized")}),U1=Ht.extend({method:w.literal("ping")}),z6=w.object({progress:w.number(),total:w.optional(w.number()),message:w.optional(w.string())}).passthrough(),z1=Br.extend({method:w.literal("notifications/progress"),params:$i.merge(z6).extend({progressToken:$1})}),al=Ht.extend({params:mr.extend({cursor:w.optional(M1)}).optional()}),sl=hr.extend({nextCursor:w.optional(M1)}),H1=w.object({uri:w.string(),mimeType:w.optional(w.string()),_meta:w.optional(w.object({}).passthrough())}).passthrough(),B1=H1.extend({text:w.string()}),Hd=w.string().refine(a=>{try{return atob(a),!0}catch{return!1}},{message:"Invalid Base64 string"}),V1=H1.extend({blob:Hd}),G1=Mi.extend({uri:w.string(),description:w.optional(w.string()),mimeType:w.optional(w.string()),_meta:w.optional(w.object({}).passthrough())}),H6=Mi.extend({uriTemplate:w.string(),description:w.optional(w.string()),mimeType:w.optional(w.string()),_meta:w.optional(w.object({}).passthrough())}),B6=al.extend({method:w.literal("resources/list")}),V6=sl.extend({resources:w.array(G1)}),G6=al.extend({method:w.literal("resources/templates/list")}),W6=sl.extend({resourceTemplates:w.array(H6)}),Z6=Ht.extend({method:w.literal("resources/read"),params:mr.extend({uri:w.string()})}),K6=hr.extend({contents:w.array(w.union([B1,V1]))}),X6=Br.extend({method:w.literal("notifications/resources/list_changed")}),Q6=Ht.extend({method:w.literal("resources/subscribe"),params:mr.extend({uri:w.string()})}),Y6=Ht.extend({method:w.literal("resources/unsubscribe"),params:mr.extend({uri:w.string()})}),J6=Br.extend({method:w.literal("notifications/resources/updated"),params:$i.extend({uri:w.string()})}),e$=w.object({name:w.string(),description:w.optional(w.string()),required:w.optional(w.boolean())}).passthrough(),t$=Mi.extend({description:w.optional(w.string()),arguments:w.optional(w.array(e$)),_meta:w.optional(w.object({}).passthrough())}),r$=al.extend({method:w.literal("prompts/list")}),a$=sl.extend({prompts:w.array(t$)}),s$=Ht.extend({method:w.literal("prompts/get"),params:mr.extend({name:w.string(),arguments:w.optional(w.record(w.string()))})}),Bd=w.object({type:w.literal("text"),text:w.string(),_meta:w.optional(w.object({}).passthrough())}).passthrough(),Vd=w.object({type:w.literal("image"),data:Hd,mimeType:w.string(),_meta:w.optional(w.object({}).passthrough())}).passthrough(),Gd=w.object({type:w.literal("audio"),data:Hd,mimeType:w.string(),_meta:w.optional(w.object({}).passthrough())}).passthrough(),n$=w.object({type:w.literal("resource"),resource:w.union([B1,V1]),_meta:w.optional(w.object({}).passthrough())}).passthrough(),i$=G1.extend({type:w.literal("resource_link")}),W1=w.union([Bd,Vd,Gd,i$,n$]),o$=w.object({role:w.enum(["user","assistant"]),content:W1}).passthrough(),c$=hr.extend({description:w.optional(w.string()),messages:w.array(o$)}),l$=Br.extend({method:w.literal("notifications/prompts/list_changed")}),u$=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(),p$=Mi.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(u$),_meta:w.optional(w.object({}).passthrough())}),d$=al.extend({method:w.literal("tools/list")}),f$=sl.extend({tools:w.array(p$)}),Z1=hr.extend({content:w.array(W1).default([]),structuredContent:w.object({}).passthrough().optional(),isError:w.optional(w.boolean())}),tU=Z1.or(hr.extend({toolResult:w.unknown()})),m$=Ht.extend({method:w.literal("tools/call"),params:mr.extend({name:w.string(),arguments:w.optional(w.record(w.unknown()))})}),h$=Br.extend({method:w.literal("notifications/tools/list_changed")}),K1=w.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),v$=Ht.extend({method:w.literal("logging/setLevel"),params:mr.extend({level:K1})}),g$=Br.extend({method:w.literal("notifications/message"),params:$i.extend({level:K1,logger:w.optional(w.string()),data:w.unknown()})}),y$=w.object({name:w.string().optional()}).passthrough(),b$=w.object({hints:w.optional(w.array(y$)),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(),x$=w.object({role:w.enum(["user","assistant"]),content:w.union([Bd,Vd,Gd])}).passthrough(),_$=Ht.extend({method:w.literal("sampling/createMessage"),params:mr.extend({messages:w.array(x$),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(b$)})}),E$=hr.extend({model:w.string(),stopReason:w.optional(w.enum(["endTurn","stopSequence","maxTokens"]).or(w.string())),role:w.enum(["user","assistant"]),content:w.discriminatedUnion("type",[Bd,Vd,Gd])}),w$=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(),P$=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(),T$=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(),R$=w.union([w$,S$,P$,T$]),O$=Ht.extend({method:w.literal("elicitation/create"),params:mr.extend({message:w.string(),requestedSchema:w.object({type:w.literal("object"),properties:w.record(w.string(),R$),required:w.optional(w.array(w.string()))}).passthrough()})}),C$=hr.extend({action:w.enum(["accept","decline","cancel"]),content:w.optional(w.record(w.string(),w.unknown()))}),k$=w.object({type:w.literal("ref/resource"),uri:w.string()}).passthrough(),A$=w.object({type:w.literal("ref/prompt"),name:w.string()}).passthrough(),I$=Ht.extend({method:w.literal("completion/complete"),params:mr.extend({ref:w.union([A$,k$]),argument:w.object({name:w.string(),value:w.string()}).passthrough(),context:w.optional(w.object({arguments:w.optional(w.record(w.string(),w.string()))}))})}),N$=hr.extend({completion:w.object({values:w.array(w.string()).max(100),total:w.optional(w.number().int()),hasMore:w.optional(w.boolean())}).passthrough()}),j$=w.object({uri:w.string().startsWith("file://"),name:w.optional(w.string()),_meta:w.optional(w.object({}).passthrough())}).passthrough(),D$=Ht.extend({method:w.literal("roots/list")}),$$=hr.extend({roots:w.array(j$)}),M$=Br.extend({method:w.literal("notifications/roots/list_changed")}),rU=w.union([U1,L6,I$,v$,s$,r$,B6,G6,Z6,Q6,Y6,m$,d$]),aU=w.union([q1,z1,U6,M$]),sU=w.union([L1,E$,C$,$$]),nU=w.union([U1,_$,O$,D$]),iU=w.union([q1,z1,g$,J6,X6,h$,l$]),oU=w.union([L1,F6,N$,c$,a$,V6,W6,K6,Z1,f$]);var cU=qj(x9(),1);var lU=Symbol("Let zodToJsonSchema decide on which parser to use");var uU=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");var Md;(function(a){a.Completable="McpCompletable"})(Md||(Md={}));var Yc=class extends Ne{_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}};Yc.create=(a,e)=>new Yc({type:a,typeName:Md.Completable,complete:e.complete,...L$(e)});function L$(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 X1({prompt:a,options:e}){let{systemPrompt:r,settingSources:t,...s}=e??{},i,n;r===void 0?i="":typeof r=="string"?i=r:r.type==="preset"&&(n=r.append);let o=s.pathToClaudeCodeExecutable;if(!o){let xe=(0,d1.fileURLToPath)(q$.url),Ce=(0,Rd.join)(xe,"..");o=(0,Rd.join)(Ce,"cli.js")}process.env.CLAUDE_AGENT_SDK_VERSION="0.1.27";let{abortController:l=m1(),additionalDirectories:c=[],agents:u,allowedTools:p=[],canUseTool:m,continue:f,cwd:h,disallowedTools:d=[],env:v,executable:x=y1()?"bun":"node",executableArgs:b=[],extraArgs:E={},fallbackModel:O,forkSession:C,hooks:P,includePartialMessages:A,maxThinkingTokens:$,maxTurns:I,mcpServers:q,model:M,permissionMode:k="default",allowDangerouslySkipPermissions:T=!1,permissionPromptToolName:N,plugins:z,resume:B,resumeSessionAt:G,stderr:te,strictMcpConfig:Q}=s,V=v;if(V||(V={...process.env}),V.CLAUDE_CODE_ENTRYPOINT||(V.CLAUDE_CODE_ENTRYPOINT="sdk-ts"),!o)throw new Error("pathToClaudeCodeExecutable is required");let re={},ce=new Map;if(q)for(let[xe,Ce]of Object.entries(q))Ce.type==="sdk"&&"instance"in Ce?(ce.set(xe,Ce.instance),re[xe]={type:"sdk",name:xe}):re[xe]=Ce;let Be=typeof a=="string",be=new Od({abortController:l,additionalDirectories:c,agents:u,cwd:h,executable:x,executableArgs:b,extraArgs:E,pathToClaudeCodeExecutable:o,env:V,forkSession:C,stderr:te,customSystemPrompt:i,appendSystemPrompt:n,maxThinkingTokens:$,maxTurns:I,model:M,fallbackModel:O,permissionMode:k,allowDangerouslySkipPermissions:T,permissionPromptToolName:N,continueConversation:f,resume:B,resumeSessionAt:G,settingSources:t??[],allowedTools:p,disallowedTools:d,mcpServers:re,strictMcpConfig:Q,canUseTool:!!m,hooks:!!P,includePartialMessages:A,plugins:z}),Me=new Id(be,Be,m,P,l,ce);return typeof a=="string"?be.write(JSON.stringify({type:"user",session_id:"",message:{role:"user",content:[{type:"text",text:a}]},parent_tool_use_id:null})+` `):Me.streamInput(a),Me}var nl=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=X1({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(v=>v.type==="text").map(v=>v.text).join(` -`):typeof u=="string"?u:"",m=p.length,f=e.cumulativeInputTokens+e.cumulativeOutputTokens,h=c.message.usage;h&&(e.cumulativeInputTokens+=h.input_tokens||0,e.cumulativeOutputTokens+=h.output_tokens||0,h.cache_creation_input_tokens&&(e.cumulativeInputTokens+=h.cache_creation_input_tokens),H.debug("SDK","Token usage captured",{sessionId:e.sessionDbId,inputTokens:h.input_tokens,outputTokens:h.output_tokens,cacheCreation:h.cache_creation_input_tokens||0,cacheRead:h.cache_read_input_tokens||0,cumulativeInput:e.cumulativeInputTokens,cumulativeOutput:e.cumulativeOutputTokens}));let d=e.cumulativeInputTokens+e.cumulativeOutputTokens-f;if(m>0){let v=m>100?p.substring(0,100)+"...":p;H.dataOut("SDK",`Response received (${m} chars)`,{sessionId:e.sessionDbId,promptNumber:e.lastPromptNumber},v),await this.processSDKResponse(e,p,r,d)}}c.type==="result"&&c.subtype}let l=Date.now()-e.startTime;H.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"?H.warn("SDK","Agent aborted",{sessionId:e.sessionDbId}):H.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?BE(e.project,e.claudeSessionId,e.userPrompt):WE(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:VE({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:GE({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=zE(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);H.info("SDK","Observation saved",{sessionId:e.sessionDbId,obsId:l,type:o.type,title:o.title||Ut("obs.title is null",{obsId:l,type:o.type},"(untitled)"),filesRead:o.files_read?.length??(Ut("obs.files_read is null/undefined",{obsId:l}),0),filesModified:o.files_modified?.length??(Ut("obs.files_modified is null/undefined",{obsId:l}),0),concepts:o.concepts?.length??(Ut("obs.concepts is null/undefined",{obsId:l}),0)});let u=Date.now(),p=o.type,m=o.title||Ut("obs.title is null for Chroma sync",{obsId:l,type:o.type},"(untitled)");this.dbManager.getChromaSync().syncObservation(l,e.claudeSessionId,e.project,o,e.lastPromptNumber,c,s).then(()=>{let f=Date.now()-u;H.debug("CHROMA","Observation synced",{obsId:l,duration:`${f}ms`,type:p,title:m})}).catch(f=>{H.error("CHROMA","Failed to sync observation",{obsId:l,sessionId:e.sessionDbId,type:p,title:m},f)}),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=HE(r,e.sessionDbId);if(n){let{id:o,createdAtEpoch:l}=this.dbManager.getSessionStore().storeSummary(e.claudeSessionId,e.project,n,e.lastPromptNumber,s);H.info("SDK","Summary saved",{sessionId:e.sessionDbId,summaryId:o,request:n.request||Ut("summary.request is null",{summaryId:o},"(no request)"),hasCompleted:!!n.completed,hasNextSteps:!!n.next_steps});let c=Date.now(),u=n.request||Ut("summary.request is null for Chroma sync",{summaryId:o},"(no request)");this.dbManager.getChromaSync().syncSummary(o,e.claudeSessionId,e.project,n,e.lastPromptNumber,l,s).then(()=>{let p=Date.now()-c;H.debug("CHROMA","Summary synced",{summaryId:o,duration:`${p}ms`,request:u})}).catch(p=>{H.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}})}t&&typeof t.broadcastProcessingStatus=="function"&&t.broadcastProcessingStatus()}findClaudeExecutable(){let e=process.env.CLAUDE_CODE_PATH||(0,Q1.execSync)(process.platform==="win32"?"where claude":"which claude",{encoding:"utf8"}).trim().split(` +`):typeof u=="string"?u:"",m=p.length,f=e.cumulativeInputTokens+e.cumulativeOutputTokens,h=c.message.usage;h&&(e.cumulativeInputTokens+=h.input_tokens||0,e.cumulativeOutputTokens+=h.output_tokens||0,h.cache_creation_input_tokens&&(e.cumulativeInputTokens+=h.cache_creation_input_tokens),H.debug("SDK","Token usage captured",{sessionId:e.sessionDbId,inputTokens:h.input_tokens,outputTokens:h.output_tokens,cacheCreation:h.cache_creation_input_tokens||0,cacheRead:h.cache_read_input_tokens||0,cumulativeInput:e.cumulativeInputTokens,cumulativeOutput:e.cumulativeOutputTokens}));let d=e.cumulativeInputTokens+e.cumulativeOutputTokens-f;if(m>0){let v=m>100?p.substring(0,100)+"...":p;H.dataOut("SDK",`Response received (${m} chars)`,{sessionId:e.sessionDbId,promptNumber:e.lastPromptNumber},v),await this.processSDKResponse(e,p,r,d)}}c.type==="result"&&c.subtype}let l=Date.now()-e.startTime;H.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"?H.warn("SDK","Agent aborted",{sessionId:e.sessionDbId}):H.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?BE(e.project,e.claudeSessionId,e.userPrompt):WE(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:VE({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:GE({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=zE(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);H.info("SDK","Observation saved",{sessionId:e.sessionDbId,obsId:l,type:o.type,title:o.title||Ut("obs.title is null",{obsId:l,type:o.type},"(untitled)"),filesRead:o.files_read?.length??(Ut("obs.files_read is null/undefined",{obsId:l}),0),filesModified:o.files_modified?.length??(Ut("obs.files_modified is null/undefined",{obsId:l}),0),concepts:o.concepts?.length??(Ut("obs.concepts is null/undefined",{obsId:l}),0)});let u=Date.now(),p=o.type,m=o.title||Ut("obs.title is null for Chroma sync",{obsId:l,type:o.type},"(untitled)");this.dbManager.getChromaSync().syncObservation(l,e.claudeSessionId,e.project,o,e.lastPromptNumber,c,s).then(()=>{let f=Date.now()-u;H.debug("CHROMA","Observation synced",{obsId:l,duration:`${f}ms`,type:p,title:m})}).catch(f=>{H.error("CHROMA","Failed to sync observation",{obsId:l,sessionId:e.sessionDbId,type:p,title:m},f)}),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=HE(r,e.sessionDbId);if(n){let{id:o,createdAtEpoch:l}=this.dbManager.getSessionStore().storeSummary(e.claudeSessionId,e.project,n,e.lastPromptNumber,s);H.info("SDK","Summary saved",{sessionId:e.sessionDbId,summaryId:o,request:n.request||Ut("summary.request is null",{summaryId:o},"(no request)"),hasCompleted:!!n.completed,hasNextSteps:!!n.next_steps});let c=Date.now(),u=n.request||Ut("summary.request is null for Chroma sync",{summaryId:o},"(no request)");this.dbManager.getChromaSync().syncSummary(o,e.claudeSessionId,e.project,n,e.lastPromptNumber,l,s).then(()=>{let p=Date.now()-c;H.debug("CHROMA","Summary synced",{summaryId:o,duration:`${p}ms`,request:u})}).catch(p=>{H.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}})}t&&typeof t.broadcastProcessingStatus=="function"&&t.broadcastProcessingStatus()}findClaudeExecutable(){let e=process.env.CLAUDE_CODE_PATH||(0,Q1.execSync)(process.platform==="win32"?"where claude":"which claude",{encoding:"utf8",windowsHide:!0}).trim().split(` `)[0].trim();if(!e)throw new Error("Claude executable not found in PATH");return e}getModelId(){try{let e=J1.default.join((0,Y1.homedir)(),".claude-mem","settings.json");if((0,il.existsSync)(e)){let t=JSON.parse((0,il.readFileSync)(e,"utf-8")).env?.CLAUDE_MEM_MODEL;if(t)return t}}catch{}return process.env.CLAUDE_MEM_MODEL||"claude-haiku-4-5"}};var ol=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, @@ -879,8 +879,8 @@ MEMORY PROCESSING CONTINUED `,n=[];t&&(i+=" WHERE s.project = ?",n.push(t)),i+=" ORDER BY up.created_at_epoch DESC LIMIT ? OFFSET ?",n.push(r+1,e);let l=s.prepare(i).all(...n);return{items:l.slice(0,r),hasMore:l.length>r,offset:e,limit:r}}paginate(e,r,t,s,i){let n=this.dbManager.getSessionStore().db,o=`SELECT ${r} FROM ${e}`,l=[];i&&(o+=" WHERE project = ?",l.push(i)),o+=" ORDER BY created_at_epoch DESC LIMIT ? OFFSET ?",l.push(s+1,t);let u=n.prepare(o).all(...l);return{items:u.slice(0,s),hasMore:u.length>s,offset:t,limit:s}}};var cl=class{dbManager;defaultSettings={sidebarOpen:!0,selectedProject:null,theme:"system"};constructor(e){this.dbManager=e}getSettings(){let e=this.dbManager.getSessionStore().db;try{let t=e.prepare("SELECT key, value FROM viewer_settings").all(),s={...this.defaultSettings};for(let i of t){let n=i.key;n in s&&(s[n]=JSON.parse(i.value))}return s}catch(r){return H.debug("WORKER","Failed to load settings, using defaults",{},r),{...this.defaultSettings}}}updateSettings(e){let t=this.dbManager.getSessionStore().db.prepare(` INSERT OR REPLACE INTO viewer_settings (key, value) VALUES (?, ?) - `);for(let[s,i]of Object.entries(e))t.run(s,JSON.stringify(i));return this.getSettings()}};var Wd=require("child_process"),js=require("fs"),ew=require("os"),Li=require("path");var qi=(0,Li.join)((0,ew.homedir)(),".claude","plugins","marketplaces","thedotmack");function vr(a){return(0,Wd.execSync)(`git ${a}`,{cwd:qi,encoding:"utf-8",timeout:3e4}).trim()}function tw(a,e=6e4){return(0,Wd.execSync)(a,{cwd:qi,encoding:"utf-8",timeout:e}).trim()}function ll(){let a=(0,Li.join)(qi,".git");if(!(0,js.existsSync)(a))return{branch:null,isBeta:!1,isGitRepo:!1,isDirty:!1,canSwitch:!1,error:"Installed plugin is not a git repository"};try{let e=vr("rev-parse --abbrev-ref HEAD"),t=vr("status --porcelain").length>0,s=e.startsWith("beta");return{branch:e,isBeta:s,isGitRepo:!0,isDirty:t,canSwitch:!0}}catch(e){return H.error("BRANCH","Failed to get branch info",{},e),{branch:null,isBeta:!1,isGitRepo:!0,isDirty:!1,canSwitch:!1,error:e.message}}}async function rw(a){let e=ll();if(!e.isGitRepo)return{success:!1,error:"Installed plugin is not a git repository. Please reinstall."};if(e.branch===a)return{success:!0,branch:a,message:`Already on branch ${a}`};try{H.info("BRANCH","Starting branch switch",{from:e.branch,to:a}),H.debug("BRANCH","Discarding local changes"),vr("checkout -- ."),vr("clean -fd"),H.debug("BRANCH","Fetching from origin"),vr("fetch origin"),H.debug("BRANCH","Checking out branch",{branch:a});try{vr(`checkout ${a}`)}catch{vr(`checkout -b ${a} origin/${a}`)}H.debug("BRANCH","Pulling latest"),vr(`pull origin ${a}`);let r=(0,Li.join)(qi,".install-version");return(0,js.existsSync)(r)&&(0,js.unlinkSync)(r),H.debug("BRANCH","Running npm install"),tw("npm install",12e4),H.success("BRANCH","Branch switch complete",{branch:a}),{success:!0,branch:a,message:`Switched to ${a}. Worker will restart automatically.`}}catch(r){H.error("BRANCH","Branch switch failed",{targetBranch:a},r);try{e.branch&&vr(`checkout ${e.branch}`)}catch{}return{success:!1,error:`Branch switch failed: ${r.message}`}}}async function aw(){let a=ll();if(!a.isGitRepo||!a.branch)return{success:!1,error:"Cannot pull updates: not a git repository"};try{H.info("BRANCH","Pulling updates",{branch:a.branch}),vr("checkout -- ."),vr("fetch origin"),vr(`pull origin ${a.branch}`);let e=(0,Li.join)(qi,".install-version");return(0,js.existsSync)(e)&&(0,js.unlinkSync)(e),tw("npm install",12e4),H.success("BRANCH","Updates pulled",{branch:a.branch}),{success:!0,branch:a.branch,message:`Updated ${a.branch}. Worker will restart automatically.`}}catch(e){return H.error("BRANCH","Pull failed",{},e),{success:!1,error:`Pull failed: ${e.message}`}}}var ul=["bugfix","feature","refactor","discovery","decision","change"],pl=["how-it-works","why-it-exists","what-changed","problem-solution","gotcha","pattern","trade-off"];var Zd=ul.join(","),Kd=pl.join(",");var Fi=class{app;server=null;startTime=Date.now();mcpClient;dbManager;sessionManager;sseBroadcaster;sdkAgent;paginationHelper;settingsManager;constructor(){this.app=(0,dl.default)(),this.dbManager=new Uc,this.sessionManager=new zc(this.dbManager),this.sseBroadcaster=new Hc,this.sdkAgent=new nl(this.dbManager,this.sessionManager),this.paginationHelper=new ol(this.dbManager),this.settingsManager=new cl(this.dbManager),this.sessionManager.setOnSessionDeleted(()=>{this.broadcastProcessingStatus()}),this.mcpClient=new bn({name:"worker-search-proxy",version:"1.0.0"},{capabilities:{}}),this.setupMiddleware(),this.setupRoutes()}setupMiddleware(){this.app.use(dl.default.json({limit:"50mb"})),this.app.use((0,sw.default)()),this.app.use((t,s,i)=>{if(t.path.startsWith("/health")||t.path==="/"||t.path.includes("."))return i();let n=Date.now(),o=`${t.method}-${Date.now()}`,l=this.summarizeRequestBody(t.method,t.path,t.body);H.info("HTTP",`\u2192 ${t.method} ${t.path}`,{requestId:o},l);let c=s.send.bind(s);s.send=function(u){let p=Date.now()-n;return H.info("HTTP",`\u2190 ${s.statusCode} ${t.path}`,{requestId:o,duration:`${p}ms`}),c(u)},i()});let e=Ea(),r=gr.default.join(e,"plugin","ui");this.app.use(dl.default.static(r))}summarizeRequestBody(e,r,t){if(!t||Object.keys(t).length===0||r.includes("/init"))return"";if(r.includes("/observations")){let s=t.tool_name||"?",i=t.tool_input;return`tool=${H.formatTool(s,i)}`}return r.includes("/summarize")?"requesting summary":""}setupRoutes(){this.app.get("/health",this.handleHealth.bind(this)),this.app.get("/",this.handleViewerUI.bind(this)),this.app.get("/stream",this.handleSSEStream.bind(this)),this.app.post("/sessions/:sessionDbId/init",this.handleSessionInit.bind(this)),this.app.post("/sessions/:sessionDbId/observations",this.handleObservations.bind(this)),this.app.post("/sessions/:sessionDbId/summarize",this.handleSummarize.bind(this)),this.app.get("/sessions/:sessionDbId/status",this.handleSessionStatus.bind(this)),this.app.delete("/sessions/:sessionDbId",this.handleSessionDelete.bind(this)),this.app.post("/sessions/:sessionDbId/complete",this.handleSessionComplete.bind(this)),this.app.get("/api/observations",this.handleGetObservations.bind(this)),this.app.get("/api/summaries",this.handleGetSummaries.bind(this)),this.app.get("/api/prompts",this.handleGetPrompts.bind(this)),this.app.get("/api/observation/:id",this.handleGetObservationById.bind(this)),this.app.get("/api/session/:id",this.handleGetSessionById.bind(this)),this.app.get("/api/prompt/:id",this.handleGetPromptById.bind(this)),this.app.get("/api/stats",this.handleGetStats.bind(this)),this.app.get("/api/projects",this.handleGetProjects.bind(this)),this.app.get("/api/processing-status",this.handleGetProcessingStatus.bind(this)),this.app.post("/api/processing",this.handleSetProcessing.bind(this)),this.app.get("/api/settings",this.handleGetSettings.bind(this)),this.app.post("/api/settings",this.handleUpdateSettings.bind(this)),this.app.get("/api/mcp/status",this.handleGetMcpStatus.bind(this)),this.app.post("/api/mcp/toggle",this.handleToggleMcp.bind(this)),this.app.get("/api/branch/status",this.handleGetBranchStatus.bind(this)),this.app.post("/api/branch/switch",this.handleSwitchBranch.bind(this)),this.app.post("/api/branch/update",this.handleUpdateBranch.bind(this)),this.app.get("/api/search",this.handleUnifiedSearch.bind(this)),this.app.get("/api/timeline",this.handleUnifiedTimeline.bind(this)),this.app.get("/api/decisions",this.handleDecisions.bind(this)),this.app.get("/api/changes",this.handleChanges.bind(this)),this.app.get("/api/how-it-works",this.handleHowItWorks.bind(this)),this.app.get("/api/search/observations",this.handleSearchObservations.bind(this)),this.app.get("/api/search/sessions",this.handleSearchSessions.bind(this)),this.app.get("/api/search/prompts",this.handleSearchPrompts.bind(this)),this.app.get("/api/search/by-concept",this.handleSearchByConcept.bind(this)),this.app.get("/api/search/by-file",this.handleSearchByFile.bind(this)),this.app.get("/api/search/by-type",this.handleSearchByType.bind(this)),this.app.get("/api/context/recent",this.handleGetRecentContext.bind(this)),this.app.get("/api/context/timeline",this.handleGetContextTimeline.bind(this)),this.app.get("/api/context/preview",this.handleContextPreview.bind(this)),this.app.get("/api/timeline/by-query",this.handleGetTimelineByQuery.bind(this)),this.app.get("/api/search/help",this.handleSearchHelp.bind(this))}async cleanupOrphanedProcesses(){try{let{execSync:e}=await import("child_process");try{let r=e("pgrep -fl uvx",{encoding:"utf-8",stdio:"pipe"}).trim();if(r){let t=r.split(` -`).length;H.info("WORKER","Cleaning up orphaned MCP processes",{count:t}),e("pkill -f uvx",{stdio:"pipe"}),H.success("WORKER",`Cleaned up ${t} orphaned MCP server processes`)}}catch(r){if(r.status===1)H.debug("WORKER","No orphaned MCP processes to clean up");else throw r}}catch(e){H.warn("WORKER","Failed to cleanup orphaned processes (non-fatal)",{},e)}}async start(){await this.cleanupOrphanedProcesses(),await this.dbManager.initialize();let e=gr.default.join(__dirname,"..","..","plugin","scripts","search-server.cjs"),r=new En({command:"node",args:[e],env:process.env});await this.mcpClient.connect(r),H.success("WORKER","Connected to MCP search server");let t=sc();this.server=await new Promise((s,i)=>{let n=this.app.listen(t,()=>s(n));n.on("error",i)}),H.info("SYSTEM","Worker started",{port:t,pid:process.pid})}async shutdown(){if(await this.sessionManager.shutdownAll(),this.mcpClient)try{await this.mcpClient.close(),H.info("SYSTEM","MCP client closed")}catch(e){H.error("SYSTEM","Failed to close MCP client",{},e)}this.server&&await new Promise((e,r)=>{this.server.close(t=>t?r(t):e())}),await this.dbManager.close(),H.info("SYSTEM","Worker shutdown complete")}handleHealth(e,r){r.json({status:"ok",timestamp:Date.now()})}handleViewerUI(e,r){try{let t=Ea(),s=gr.default.join(t,"plugin","ui","viewer.html"),i=(0,vt.readFileSync)(s,"utf-8");r.setHeader("Content-Type","text/html"),r.send(i)}catch(t){H.failure("WORKER","Viewer UI error",{},t),r.status(500).json({error:"Failed to load viewer UI"})}}handleSSEStream(e,r){r.setHeader("Content-Type","text/event-stream"),r.setHeader("Cache-Control","no-cache"),r.setHeader("Connection","keep-alive"),this.sseBroadcaster.addClient(r);let t=this.dbManager.getSessionStore().getAllProjects();this.sseBroadcaster.broadcast({type:"initial_load",projects:t,timestamp:Date.now()});let s=this.sessionManager.isAnySessionProcessing(),i=this.sessionManager.getTotalActiveWork();this.sseBroadcaster.broadcast({type:"processing_status",isProcessing:s,queueDepth:i})}handleSessionInit(e,r){try{let t=parseInt(e.params.sessionDbId,10),{userPrompt:s,promptNumber:i}=e.body,n=this.sessionManager.initializeSession(t,s,i),l=this.dbManager.getSessionStore().db.prepare(` + `);for(let[s,i]of Object.entries(e))t.run(s,JSON.stringify(i));return this.getSettings()}};var Wd=require("child_process"),js=require("fs"),ew=require("os"),Li=require("path");var qi=(0,Li.join)((0,ew.homedir)(),".claude","plugins","marketplaces","thedotmack");function vr(a){return(0,Wd.execSync)(`git ${a}`,{cwd:qi,encoding:"utf-8",timeout:3e4}).trim()}function tw(a,e=6e4){return(0,Wd.execSync)(a,{cwd:qi,encoding:"utf-8",timeout:e}).trim()}function ll(){let a=(0,Li.join)(qi,".git");if(!(0,js.existsSync)(a))return{branch:null,isBeta:!1,isGitRepo:!1,isDirty:!1,canSwitch:!1,error:"Installed plugin is not a git repository"};try{let e=vr("rev-parse --abbrev-ref HEAD"),t=vr("status --porcelain").length>0,s=e.startsWith("beta");return{branch:e,isBeta:s,isGitRepo:!0,isDirty:t,canSwitch:!0}}catch(e){return H.error("BRANCH","Failed to get branch info",{},e),{branch:null,isBeta:!1,isGitRepo:!0,isDirty:!1,canSwitch:!1,error:e.message}}}async function rw(a){let e=ll();if(!e.isGitRepo)return{success:!1,error:"Installed plugin is not a git repository. Please reinstall."};if(e.branch===a)return{success:!0,branch:a,message:`Already on branch ${a}`};try{H.info("BRANCH","Starting branch switch",{from:e.branch,to:a}),H.debug("BRANCH","Discarding local changes"),vr("checkout -- ."),vr("clean -fd"),H.debug("BRANCH","Fetching from origin"),vr("fetch origin"),H.debug("BRANCH","Checking out branch",{branch:a});try{vr(`checkout ${a}`)}catch{vr(`checkout -b ${a} origin/${a}`)}H.debug("BRANCH","Pulling latest"),vr(`pull origin ${a}`);let r=(0,Li.join)(qi,".install-version");return(0,js.existsSync)(r)&&(0,js.unlinkSync)(r),H.debug("BRANCH","Running npm install"),tw("npm install",12e4),H.success("BRANCH","Branch switch complete",{branch:a}),{success:!0,branch:a,message:`Switched to ${a}. Worker will restart automatically.`}}catch(r){H.error("BRANCH","Branch switch failed",{targetBranch:a},r);try{e.branch&&vr(`checkout ${e.branch}`)}catch{}return{success:!1,error:`Branch switch failed: ${r.message}`}}}async function aw(){let a=ll();if(!a.isGitRepo||!a.branch)return{success:!1,error:"Cannot pull updates: not a git repository"};try{H.info("BRANCH","Pulling updates",{branch:a.branch}),vr("checkout -- ."),vr("fetch origin"),vr(`pull origin ${a.branch}`);let e=(0,Li.join)(qi,".install-version");return(0,js.existsSync)(e)&&(0,js.unlinkSync)(e),tw("npm install",12e4),H.success("BRANCH","Updates pulled",{branch:a.branch}),{success:!0,branch:a.branch,message:`Updated ${a.branch}. Worker will restart automatically.`}}catch(e){return H.error("BRANCH","Pull failed",{},e),{success:!1,error:`Pull failed: ${e.message}`}}}var ul=["bugfix","feature","refactor","discovery","decision","change"],pl=["how-it-works","why-it-exists","what-changed","problem-solution","gotcha","pattern","trade-off"];var Zd=ul.join(","),Kd=pl.join(",");var Fi=class{app;server=null;startTime=Date.now();mcpClient;dbManager;sessionManager;sseBroadcaster;sdkAgent;paginationHelper;settingsManager;constructor(){this.app=(0,dl.default)(),this.dbManager=new Uc,this.sessionManager=new zc(this.dbManager),this.sseBroadcaster=new Hc,this.sdkAgent=new nl(this.dbManager,this.sessionManager),this.paginationHelper=new ol(this.dbManager),this.settingsManager=new cl(this.dbManager),this.sessionManager.setOnSessionDeleted(()=>{this.broadcastProcessingStatus()}),this.mcpClient=new bn({name:"worker-search-proxy",version:"1.0.0"},{capabilities:{}}),this.setupMiddleware(),this.setupRoutes()}setupMiddleware(){this.app.use(dl.default.json({limit:"50mb"})),this.app.use((0,sw.default)()),this.app.use((t,s,i)=>{if(t.path.startsWith("/health")||t.path==="/"||t.path.includes("."))return i();let n=Date.now(),o=`${t.method}-${Date.now()}`,l=this.summarizeRequestBody(t.method,t.path,t.body);H.info("HTTP",`\u2192 ${t.method} ${t.path}`,{requestId:o},l);let c=s.send.bind(s);s.send=function(u){let p=Date.now()-n;return H.info("HTTP",`\u2190 ${s.statusCode} ${t.path}`,{requestId:o,duration:`${p}ms`}),c(u)},i()});let e=Ea(),r=gr.default.join(e,"plugin","ui");this.app.use(dl.default.static(r))}summarizeRequestBody(e,r,t){if(!t||Object.keys(t).length===0||r.includes("/init"))return"";if(r.includes("/observations")){let s=t.tool_name||"?",i=t.tool_input;return`tool=${H.formatTool(s,i)}`}return r.includes("/summarize")?"requesting summary":""}setupRoutes(){this.app.get("/health",this.handleHealth.bind(this)),this.app.get("/",this.handleViewerUI.bind(this)),this.app.get("/stream",this.handleSSEStream.bind(this)),this.app.post("/sessions/:sessionDbId/init",this.handleSessionInit.bind(this)),this.app.post("/sessions/:sessionDbId/observations",this.handleObservations.bind(this)),this.app.post("/sessions/:sessionDbId/summarize",this.handleSummarize.bind(this)),this.app.get("/sessions/:sessionDbId/status",this.handleSessionStatus.bind(this)),this.app.delete("/sessions/:sessionDbId",this.handleSessionDelete.bind(this)),this.app.post("/sessions/:sessionDbId/complete",this.handleSessionComplete.bind(this)),this.app.get("/api/observations",this.handleGetObservations.bind(this)),this.app.get("/api/summaries",this.handleGetSummaries.bind(this)),this.app.get("/api/prompts",this.handleGetPrompts.bind(this)),this.app.get("/api/observation/:id",this.handleGetObservationById.bind(this)),this.app.get("/api/session/:id",this.handleGetSessionById.bind(this)),this.app.get("/api/prompt/:id",this.handleGetPromptById.bind(this)),this.app.get("/api/stats",this.handleGetStats.bind(this)),this.app.get("/api/projects",this.handleGetProjects.bind(this)),this.app.get("/api/processing-status",this.handleGetProcessingStatus.bind(this)),this.app.post("/api/processing",this.handleSetProcessing.bind(this)),this.app.get("/api/settings",this.handleGetSettings.bind(this)),this.app.post("/api/settings",this.handleUpdateSettings.bind(this)),this.app.get("/api/mcp/status",this.handleGetMcpStatus.bind(this)),this.app.post("/api/mcp/toggle",this.handleToggleMcp.bind(this)),this.app.get("/api/branch/status",this.handleGetBranchStatus.bind(this)),this.app.post("/api/branch/switch",this.handleSwitchBranch.bind(this)),this.app.post("/api/branch/update",this.handleUpdateBranch.bind(this)),this.app.get("/api/search",this.handleUnifiedSearch.bind(this)),this.app.get("/api/timeline",this.handleUnifiedTimeline.bind(this)),this.app.get("/api/decisions",this.handleDecisions.bind(this)),this.app.get("/api/changes",this.handleChanges.bind(this)),this.app.get("/api/how-it-works",this.handleHowItWorks.bind(this)),this.app.get("/api/search/observations",this.handleSearchObservations.bind(this)),this.app.get("/api/search/sessions",this.handleSearchSessions.bind(this)),this.app.get("/api/search/prompts",this.handleSearchPrompts.bind(this)),this.app.get("/api/search/by-concept",this.handleSearchByConcept.bind(this)),this.app.get("/api/search/by-file",this.handleSearchByFile.bind(this)),this.app.get("/api/search/by-type",this.handleSearchByType.bind(this)),this.app.get("/api/context/recent",this.handleGetRecentContext.bind(this)),this.app.get("/api/context/timeline",this.handleGetContextTimeline.bind(this)),this.app.get("/api/context/preview",this.handleContextPreview.bind(this)),this.app.get("/api/timeline/by-query",this.handleGetTimelineByQuery.bind(this)),this.app.get("/api/search/help",this.handleSearchHelp.bind(this))}async cleanupOrphanedProcesses(){try{let{execSync:e}=await import("child_process");try{let r=e("pgrep -fl uvx",{encoding:"utf-8",stdio:"pipe",windowsHide:!0}).trim();if(r){let t=r.split(` +`).length;H.info("WORKER","Cleaning up orphaned MCP processes",{count:t}),e("pkill -f uvx",{stdio:"pipe",windowsHide:!0}),H.success("WORKER",`Cleaned up ${t} orphaned MCP server processes`)}}catch(r){if(r.status===1)H.debug("WORKER","No orphaned MCP processes to clean up");else throw r}}catch(e){H.warn("WORKER","Failed to cleanup orphaned processes (non-fatal)",{},e)}}async start(){await this.cleanupOrphanedProcesses(),await this.dbManager.initialize();let e=gr.default.join(__dirname,"..","..","plugin","scripts","search-server.cjs"),r=new En({command:"node",args:[e],env:process.env});await this.mcpClient.connect(r),H.success("WORKER","Connected to MCP search server");let t=sc();this.server=await new Promise((s,i)=>{let n=this.app.listen(t,()=>s(n));n.on("error",i)}),H.info("SYSTEM","Worker started",{port:t,pid:process.pid})}async shutdown(){if(await this.sessionManager.shutdownAll(),this.mcpClient)try{await this.mcpClient.close(),H.info("SYSTEM","MCP client closed")}catch(e){H.error("SYSTEM","Failed to close MCP client",{},e)}this.server&&await new Promise((e,r)=>{this.server.close(t=>t?r(t):e())}),await this.dbManager.close(),H.info("SYSTEM","Worker shutdown complete")}handleHealth(e,r){r.json({status:"ok",timestamp:Date.now()})}handleViewerUI(e,r){try{let t=Ea(),s=gr.default.join(t,"plugin","ui","viewer.html"),i=(0,vt.readFileSync)(s,"utf-8");r.setHeader("Content-Type","text/html"),r.send(i)}catch(t){H.failure("WORKER","Viewer UI error",{},t),r.status(500).json({error:"Failed to load viewer UI"})}}handleSSEStream(e,r){r.setHeader("Content-Type","text/event-stream"),r.setHeader("Cache-Control","no-cache"),r.setHeader("Connection","keep-alive"),this.sseBroadcaster.addClient(r);let t=this.dbManager.getSessionStore().getAllProjects();this.sseBroadcaster.broadcast({type:"initial_load",projects:t,timestamp:Date.now()});let s=this.sessionManager.isAnySessionProcessing(),i=this.sessionManager.getTotalActiveWork();this.sseBroadcaster.broadcast({type:"processing_status",isProcessing:s,queueDepth:i})}handleSessionInit(e,r){try{let t=parseInt(e.params.sessionDbId,10),{userPrompt:s,promptNumber:i}=e.body,n=this.sessionManager.initializeSession(t,s,i),l=this.dbManager.getSessionStore().db.prepare(` SELECT up.*, s.sdk_session_id,