diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index 09c112b4..6254a9fd 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -10,7 +10,7 @@ "plugins": [ { "name": "claude-mem", - "version": "9.1.1", + "version": "10.0.0", "source": "./plugin", "description": "Persistent memory system for Claude Code - context compression across sessions" } diff --git a/package.json b/package.json index 34ecbd9a..f4ab9eeb 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "claude-mem", - "version": "9.1.1", + "version": "10.0.0", "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 948f2854..17b720d8 100644 --- a/plugin/.claude-plugin/plugin.json +++ b/plugin/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "claude-mem", - "version": "9.1.1", + "version": "10.0.0", "description": "Persistent memory system for Claude Code - seamlessly preserve context across sessions", "author": { "name": "Alex Newman" diff --git a/plugin/package.json b/plugin/package.json index d9efb1dd..1ceb2b35 100644 --- a/plugin/package.json +++ b/plugin/package.json @@ -1,6 +1,6 @@ { "name": "claude-mem-plugin", - "version": "9.1.1", + "version": "10.0.0", "private": true, "description": "Runtime dependencies for claude-mem bundled hooks", "type": "module", diff --git a/plugin/scripts/mcp-server.cjs b/plugin/scripts/mcp-server.cjs index 5f35d20a..ca2ca408 100755 --- a/plugin/scripts/mcp-server.cjs +++ b/plugin/scripts/mcp-server.cjs @@ -54,7 +54,7 @@ ${i.stack}`:` ${i.message}`:this.getLevel()===0&&typeof i=="object"?l=` Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let a of t.seen.entries()){let s=a[1];if(e===a[0]){i(a);continue}if(t.external){let u=t.external.registry.get(a[0])?.id;if(e!==a[0]&&u){i(a);continue}}if(t.metadataRegistry.get(a[0])?.id){i(a);continue}if(s.cycle){i(a);continue}if(s.count>1&&t.reused==="ref"){i(a);continue}}}function Xi(t,e){let r=t.seen.get(e);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let n=a=>{let s=t.seen.get(a);if(s.ref===null)return;let c=s.def??s.schema,u={...c},l=s.ref;if(s.ref=null,l){n(l);let m=t.seen.get(l),f=m.schema;if(f.$ref&&(t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0")?(c.allOf=c.allOf??[],c.allOf.push(f)):Object.assign(c,f),Object.assign(c,u),a._zod.parent===l)for(let v in c)v==="$ref"||v==="allOf"||v in u||delete c[v];if(f.$ref)for(let v in c)v==="$ref"||v==="allOf"||v in m.def&&JSON.stringify(c[v])===JSON.stringify(m.def[v])&&delete c[v]}let d=a._zod.parent;if(d&&d!==l){n(d);let m=t.seen.get(d);if(m?.schema.$ref&&(c.$ref=m.schema.$ref,m.def))for(let f in c)f==="$ref"||f==="allOf"||f in m.def&&JSON.stringify(c[f])===JSON.stringify(m.def[f])&&delete c[f]}t.override({zodSchema:a,jsonSchema:c,path:s.path??[]})};for(let a of[...t.seen.entries()].reverse())n(a[0]);let o={};if(t.target==="draft-2020-12"?o.$schema="https://json-schema.org/draft/2020-12/schema":t.target==="draft-07"?o.$schema="http://json-schema.org/draft-07/schema#":t.target==="draft-04"?o.$schema="http://json-schema.org/draft-04/schema#":t.target,t.external?.uri){let a=t.external.registry.get(e)?.id;if(!a)throw new Error("Schema is missing an `id` property");o.$id=t.external.uri(a)}Object.assign(o,r.def??r.schema);let i=t.external?.defs??{};for(let a of t.seen.entries()){let s=a[1];s.def&&s.defId&&(i[s.defId]=s.def)}t.external||Object.keys(i).length>0&&(t.target==="draft-2020-12"?o.$defs=i:o.definitions=i);try{let a=JSON.parse(JSON.stringify(o));return Object.defineProperty(a,"~standard",{value:{...e["~standard"],jsonSchema:{input:fo(e,"input",t.processors),output:fo(e,"output",t.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function Ue(t,e){let r=e??{seen:new Set};if(r.seen.has(t))return!1;r.seen.add(t);let n=t._zod.def;if(n.type==="transform")return!0;if(n.type==="array")return Ue(n.element,r);if(n.type==="set")return Ue(n.valueType,r);if(n.type==="lazy")return Ue(n.getter(),r);if(n.type==="promise"||n.type==="optional"||n.type==="nonoptional"||n.type==="nullable"||n.type==="readonly"||n.type==="default"||n.type==="prefault")return Ue(n.innerType,r);if(n.type==="intersection")return Ue(n.left,r)||Ue(n.right,r);if(n.type==="record"||n.type==="map")return Ue(n.keyType,r)||Ue(n.valueType,r);if(n.type==="pipe")return Ue(n.in,r)||Ue(n.out,r);if(n.type==="object"){for(let o in n.shape)if(Ue(n.shape[o],r))return!0;return!1}if(n.type==="union"){for(let o of n.options)if(Ue(o,r))return!0;return!1}if(n.type==="tuple"){for(let o of n.items)if(Ue(o,r))return!0;return!!(n.rest&&Ue(n.rest,r))}return!1}var Em=(t,e={})=>r=>{let n=Hi({...r,processors:e});return de(t,n),Bi(n,t),Xi(n,t)},fo=(t,e,r={})=>n=>{let{libraryOptions:o,target:i}=n??{},a=Hi({...o??{},target:i,io:e,processors:r});return de(t,a),Bi(a,t),Xi(a,t)};var Sb={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Tm=(t,e,r,n)=>{let o=r;o.type="string";let{minimum:i,maximum:a,format:s,patterns:c,contentEncoding:u}=t._zod.bag;if(typeof i=="number"&&(o.minLength=i),typeof a=="number"&&(o.maxLength=a),s&&(o.format=Sb[s]??s,o.format===""&&delete o.format,s==="time"&&delete o.format),u&&(o.contentEncoding=u),c&&c.size>0){let l=[...c];l.length===1?o.pattern=l[0].source:l.length>1&&(o.allOf=[...l.map(d=>({...e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"?{type:"string"}:{},pattern:d.source}))])}},Pm=(t,e,r,n)=>{let o=r,{minimum:i,maximum:a,format:s,multipleOf:c,exclusiveMaximum:u,exclusiveMinimum:l}=t._zod.bag;typeof s=="string"&&s.includes("int")?o.type="integer":o.type="number",typeof l=="number"&&(e.target==="draft-04"||e.target==="openapi-3.0"?(o.minimum=l,o.exclusiveMinimum=!0):o.exclusiveMinimum=l),typeof i=="number"&&(o.minimum=i,typeof l=="number"&&e.target!=="draft-04"&&(l>=i?delete o.minimum:delete o.exclusiveMinimum)),typeof u=="number"&&(e.target==="draft-04"||e.target==="openapi-3.0"?(o.maximum=u,o.exclusiveMaximum=!0):o.exclusiveMaximum=u),typeof a=="number"&&(o.maximum=a,typeof u=="number"&&e.target!=="draft-04"&&(u<=a?delete o.maximum:delete o.exclusiveMaximum)),typeof c=="number"&&(o.multipleOf=c)},Om=(t,e,r,n)=>{r.type="boolean"},jm=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema")},Dm=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema")},Nm=(t,e,r,n)=>{e.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"},Rm=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema")},Am=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema")},Um=(t,e,r,n)=>{r.not={}},Zm=(t,e,r,n)=>{},Cm=(t,e,r,n)=>{},Mm=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema")},Lm=(t,e,r,n)=>{let o=t._zod.def,i=Nn(o.entries);i.every(a=>typeof a=="number")&&(r.type="number"),i.every(a=>typeof a=="string")&&(r.type="string"),r.enum=i},qm=(t,e,r,n)=>{let o=t._zod.def,i=[];for(let a of o.values)if(a===void 0){if(e.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof a=="bigint"){if(e.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");i.push(Number(a))}else i.push(a);if(i.length!==0)if(i.length===1){let a=i[0];r.type=a===null?"null":typeof a,e.target==="draft-04"||e.target==="openapi-3.0"?r.enum=[a]:r.const=a}else i.every(a=>typeof a=="number")&&(r.type="number"),i.every(a=>typeof a=="string")&&(r.type="string"),i.every(a=>typeof a=="boolean")&&(r.type="boolean"),i.every(a=>a===null)&&(r.type="null"),r.enum=i},Fm=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema")},Vm=(t,e,r,n)=>{let o=r,i=t._zod.pattern;if(!i)throw new Error("Pattern not found in template literal");o.type="string",o.pattern=i.source},Jm=(t,e,r,n)=>{let o=r,i={type:"string",format:"binary",contentEncoding:"binary"},{minimum:a,maximum:s,mime:c}=t._zod.bag;a!==void 0&&(i.minLength=a),s!==void 0&&(i.maxLength=s),c?c.length===1?(i.contentMediaType=c[0],Object.assign(o,i)):(Object.assign(o,i),o.anyOf=c.map(u=>({contentMediaType:u}))):Object.assign(o,i)},Km=(t,e,r,n)=>{r.type="boolean"},Wm=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},Gm=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Function types cannot be represented in JSON Schema")},Hm=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},Bm=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema")},Xm=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema")},Ym=(t,e,r,n)=>{let o=r,i=t._zod.def,{minimum:a,maximum:s}=t._zod.bag;typeof a=="number"&&(o.minItems=a),typeof s=="number"&&(o.maxItems=s),o.type="array",o.items=de(i.element,e,{...n,path:[...n.path,"items"]})},Qm=(t,e,r,n)=>{let o=r,i=t._zod.def;o.type="object",o.properties={};let a=i.shape;for(let u in a)o.properties[u]=de(a[u],e,{...n,path:[...n.path,"properties",u]});let s=new Set(Object.keys(a)),c=new Set([...s].filter(u=>{let l=i.shape[u]._zod;return e.io==="input"?l.optin===void 0:l.optout===void 0}));c.size>0&&(o.required=Array.from(c)),i.catchall?._zod.def.type==="never"?o.additionalProperties=!1:i.catchall?i.catchall&&(o.additionalProperties=de(i.catchall,e,{...n,path:[...n.path,"additionalProperties"]})):e.io==="output"&&(o.additionalProperties=!1)},ml=(t,e,r,n)=>{let o=t._zod.def,i=o.inclusive===!1,a=o.options.map((s,c)=>de(s,e,{...n,path:[...n.path,i?"oneOf":"anyOf",c]}));i?r.oneOf=a:r.anyOf=a},eh=(t,e,r,n)=>{let o=t._zod.def,i=de(o.left,e,{...n,path:[...n.path,"allOf",0]}),a=de(o.right,e,{...n,path:[...n.path,"allOf",1]}),s=u=>"allOf"in u&&Object.keys(u).length===1,c=[...s(i)?i.allOf:[i],...s(a)?a.allOf:[a]];r.allOf=c},th=(t,e,r,n)=>{let o=r,i=t._zod.def;o.type="array";let a=e.target==="draft-2020-12"?"prefixItems":"items",s=e.target==="draft-2020-12"||e.target==="openapi-3.0"?"items":"additionalItems",c=i.items.map((m,f)=>de(m,e,{...n,path:[...n.path,a,f]})),u=i.rest?de(i.rest,e,{...n,path:[...n.path,s,...e.target==="openapi-3.0"?[i.items.length]:[]]}):null;e.target==="draft-2020-12"?(o.prefixItems=c,u&&(o.items=u)):e.target==="openapi-3.0"?(o.items={anyOf:c},u&&o.items.anyOf.push(u),o.minItems=c.length,u||(o.maxItems=c.length)):(o.items=c,u&&(o.additionalItems=u));let{minimum:l,maximum:d}=t._zod.bag;typeof l=="number"&&(o.minItems=l),typeof d=="number"&&(o.maxItems=d)},rh=(t,e,r,n)=>{let o=r,i=t._zod.def;o.type="object";let a=i.keyType,c=a._zod.bag?.patterns;if(i.mode==="loose"&&c&&c.size>0){let l=de(i.valueType,e,{...n,path:[...n.path,"patternProperties","*"]});o.patternProperties={};for(let d of c)o.patternProperties[d.source]=l}else(e.target==="draft-07"||e.target==="draft-2020-12")&&(o.propertyNames=de(i.keyType,e,{...n,path:[...n.path,"propertyNames"]})),o.additionalProperties=de(i.valueType,e,{...n,path:[...n.path,"additionalProperties"]});let u=a._zod.values;if(u){let l=[...u].filter(d=>typeof d=="string"||typeof d=="number");l.length>0&&(o.required=l)}},nh=(t,e,r,n)=>{let o=t._zod.def,i=de(o.innerType,e,n),a=e.seen.get(t);e.target==="openapi-3.0"?(a.ref=o.innerType,r.nullable=!0):r.anyOf=[i,{type:"null"}]},oh=(t,e,r,n)=>{let o=t._zod.def;de(o.innerType,e,n);let i=e.seen.get(t);i.ref=o.innerType},ih=(t,e,r,n)=>{let o=t._zod.def;de(o.innerType,e,n);let i=e.seen.get(t);i.ref=o.innerType,r.default=JSON.parse(JSON.stringify(o.defaultValue))},ah=(t,e,r,n)=>{let o=t._zod.def;de(o.innerType,e,n);let i=e.seen.get(t);i.ref=o.innerType,e.io==="input"&&(r._prefault=JSON.parse(JSON.stringify(o.defaultValue)))},sh=(t,e,r,n)=>{let o=t._zod.def;de(o.innerType,e,n);let i=e.seen.get(t);i.ref=o.innerType;let a;try{a=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}r.default=a},ch=(t,e,r,n)=>{let o=t._zod.def,i=e.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;de(i,e,n);let a=e.seen.get(t);a.ref=i},uh=(t,e,r,n)=>{let o=t._zod.def;de(o.innerType,e,n);let i=e.seen.get(t);i.ref=o.innerType,r.readOnly=!0},lh=(t,e,r,n)=>{let o=t._zod.def;de(o.innerType,e,n);let i=e.seen.get(t);i.ref=o.innerType},hl=(t,e,r,n)=>{let o=t._zod.def;de(o.innerType,e,n);let i=e.seen.get(t);i.ref=o.innerType},dh=(t,e,r,n)=>{let o=t._zod.innerType;de(o,e,n);let i=e.seen.get(t);i.ref=o};function Br(t){return!!t._zod}function Yt(t,e){return Br(t)?Jr(t,e):t.safeParse(e)}function Yi(t){if(!t)return;let e;if(Br(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function hh(t){if(Br(t)){let i=t._zod?.def;if(i){if(i.value!==void 0)return i.value;if(Array.isArray(i.values)&&i.values.length>0)return i.values[0]}}let r=t._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=t.value;if(n!==void 0)return n}var mo={};yn(mo,{ZodAny:()=>Dh,ZodArray:()=>Uh,ZodBase64:()=>Cl,ZodBase64URL:()=>Ml,ZodBigInt:()=>sa,ZodBigIntFormat:()=>Fl,ZodBoolean:()=>aa,ZodCIDRv4:()=>Ul,ZodCIDRv6:()=>Zl,ZodCUID:()=>Pl,ZodCUID2:()=>Ol,ZodCatch:()=>ng,ZodCodec:()=>Bl,ZodCustom:()=>pa,ZodCustomStringFormat:()=>go,ZodDate:()=>Jl,ZodDefault:()=>Xh,ZodDiscriminatedUnion:()=>Ch,ZodE164:()=>Ll,ZodEmail:()=>Il,ZodEmoji:()=>El,ZodEnum:()=>ho,ZodExactOptional:()=>Gh,ZodFile:()=>Kh,ZodFunction:()=>pg,ZodGUID:()=>ea,ZodIPv4:()=>Rl,ZodIPv6:()=>Al,ZodIntersection:()=>Mh,ZodJWT:()=>ql,ZodKSUID:()=>Nl,ZodLazy:()=>ug,ZodLiteral:()=>Jh,ZodMAC:()=>Th,ZodMap:()=>Fh,ZodNaN:()=>ig,ZodNanoID:()=>Tl,ZodNever:()=>Rh,ZodNonOptional:()=>Gl,ZodNull:()=>jh,ZodNullable:()=>Bh,ZodNumber:()=>ia,ZodNumberFormat:()=>Xr,ZodObject:()=>ca,ZodOptional:()=>Wl,ZodPipe:()=>Hl,ZodPrefault:()=>Qh,ZodPromise:()=>dg,ZodReadonly:()=>ag,ZodRecord:()=>da,ZodSet:()=>Vh,ZodString:()=>na,ZodStringFormat:()=>ce,ZodSuccess:()=>rg,ZodSymbol:()=>Ph,ZodTemplateLiteral:()=>cg,ZodTransform:()=>Wh,ZodTuple:()=>Lh,ZodType:()=>q,ZodULID:()=>jl,ZodURL:()=>oa,ZodUUID:()=>Rt,ZodUndefined:()=>Oh,ZodUnion:()=>ua,ZodUnknown:()=>Nh,ZodVoid:()=>Ah,ZodXID:()=>Dl,ZodXor:()=>Zh,_ZodString:()=>zl,_default:()=>Yh,_function:()=>qx,any:()=>Sx,array:()=>H,base64:()=>sx,base64url:()=>cx,bigint:()=>yx,boolean:()=>ve,catch:()=>og,check:()=>Fx,cidrv4:()=>ix,cidrv6:()=>ax,codec:()=>Cx,cuid:()=>Xb,cuid2:()=>Yb,custom:()=>Xl,date:()=>zx,describe:()=>Vx,discriminatedUnion:()=>la,e164:()=>ux,email:()=>Lb,emoji:()=>Hb,enum:()=>Te,exactOptional:()=>Hh,file:()=>Rx,float32:()=>hx,float64:()=>gx,function:()=>qx,guid:()=>qb,hash:()=>mx,hex:()=>fx,hostname:()=>px,httpUrl:()=>Gb,instanceof:()=>Kx,int:()=>wl,int32:()=>vx,int64:()=>$x,intersection:()=>_o,ipv4:()=>rx,ipv6:()=>ox,json:()=>Gx,jwt:()=>lx,keyof:()=>Ix,ksuid:()=>tx,lazy:()=>lg,literal:()=>T,looseObject:()=>Ee,looseRecord:()=>Ox,mac:()=>nx,map:()=>jx,meta:()=>Jx,nan:()=>Zx,nanoid:()=>Bb,nativeEnum:()=>Nx,never:()=>Vl,nonoptional:()=>tg,null:()=>vo,nullable:()=>ta,nullish:()=>Ax,number:()=>ne,object:()=>z,optional:()=>fe,partialRecord:()=>Px,pipe:()=>ra,prefault:()=>eg,preprocess:()=>fa,promise:()=>Lx,readonly:()=>sg,record:()=>pe,refine:()=>fg,set:()=>Dx,strictObject:()=>Ex,string:()=>h,stringFormat:()=>dx,stringbool:()=>Wx,success:()=>Ux,superRefine:()=>mg,symbol:()=>xx,templateLiteral:()=>Mx,transform:()=>Kl,tuple:()=>qh,uint32:()=>_x,uint64:()=>bx,ulid:()=>Qb,undefined:()=>kx,union:()=>ie,unknown:()=>ue,url:()=>Wb,uuid:()=>Fb,uuidv4:()=>Vb,uuidv6:()=>Jb,uuidv7:()=>Kb,void:()=>wx,xid:()=>ex,xor:()=>Tx});var Qi={};yn(Qi,{endsWith:()=>ao,gt:()=>Dt,gte:()=>Ae,includes:()=>oo,length:()=>Gr,lowercase:()=>ro,lt:()=>jt,lte:()=>Ge,maxLength:()=>Wr,maxSize:()=>gr,mime:()=>so,minLength:()=>Xt,minSize:()=>Nt,multipleOf:()=>hr,negative:()=>nl,nonnegative:()=>il,nonpositive:()=>ol,normalize:()=>co,overwrite:()=>_t,positive:()=>rl,property:()=>al,regex:()=>to,size:()=>Kr,slugify:()=>Gi,startsWith:()=>io,toLowerCase:()=>lo,toUpperCase:()=>po,trim:()=>uo,uppercase:()=>no});var vr={};yn(vr,{ZodISODate:()=>yl,ZodISODateTime:()=>vl,ZodISODuration:()=>kl,ZodISOTime:()=>bl,date:()=>$l,datetime:()=>_l,duration:()=>Sl,time:()=>xl});var vl=p("ZodISODateTime",(t,e)=>{Oc.init(t,e),ce.init(t,e)});function _l(t){return Du(vl,t)}var yl=p("ZodISODate",(t,e)=>{jc.init(t,e),ce.init(t,e)});function $l(t){return Nu(yl,t)}var bl=p("ZodISOTime",(t,e)=>{Dc.init(t,e),ce.init(t,e)});function xl(t){return Ru(bl,t)}var kl=p("ZodISODuration",(t,e)=>{Nc.init(t,e),ce.init(t,e)});function Sl(t){return Au(kl,t)}var gh=(t,e)=>{fi.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>hi(t,r)},flatten:{value:r=>mi(t,r)},addIssue:{value:r=>{t.issues.push(r),t.message=JSON.stringify(t.issues,qr,2)}},addIssues:{value:r=>{t.issues.push(...r),t.message=JSON.stringify(t.issues,qr,2)}},isEmpty:{get(){return t.issues.length===0}}})},ZN=p("ZodError",gh),He=p("ZodError",gh,{Parent:Error});var vh=Mn(He),_h=qn(He),yh=Vn(He),$h=Jn(He),bh=Of(He),xh=jf(He),kh=Df(He),Sh=Nf(He),wh=Rf(He),zh=Af(He),Ih=Uf(He),Eh=Zf(He);var q=p("ZodType",(t,e)=>(M.init(t,e),Object.assign(t["~standard"],{jsonSchema:{input:fo(t,"input"),output:fo(t,"output")}}),t.toJSONSchema=Em(t,{}),t.def=e,t.type=e.type,Object.defineProperty(t,"_def",{value:e}),t.check=(...r)=>t.clone(y.mergeDefs(e,{checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),{parent:!0}),t.with=t.check,t.clone=(r,n)=>Ne(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t)),t.parse=(r,n)=>vh(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>yh(t,r,n),t.parseAsync=async(r,n)=>_h(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>$h(t,r,n),t.spa=t.safeParseAsync,t.encode=(r,n)=>bh(t,r,n),t.decode=(r,n)=>xh(t,r,n),t.encodeAsync=async(r,n)=>kh(t,r,n),t.decodeAsync=async(r,n)=>Sh(t,r,n),t.safeEncode=(r,n)=>wh(t,r,n),t.safeDecode=(r,n)=>zh(t,r,n),t.safeEncodeAsync=async(r,n)=>Ih(t,r,n),t.safeDecodeAsync=async(r,n)=>Eh(t,r,n),t.refine=(r,n)=>t.check(fg(r,n)),t.superRefine=r=>t.check(mg(r)),t.overwrite=r=>t.check(_t(r)),t.optional=()=>fe(t),t.exactOptional=()=>Hh(t),t.nullable=()=>ta(t),t.nullish=()=>fe(ta(t)),t.nonoptional=r=>tg(t,r),t.array=()=>H(t),t.or=r=>ie([t,r]),t.and=r=>_o(t,r),t.transform=r=>ra(t,Kl(r)),t.default=r=>Yh(t,r),t.prefault=r=>eg(t,r),t.catch=r=>og(t,r),t.pipe=r=>ra(t,r),t.readonly=()=>sg(t),t.describe=r=>{let n=t.clone();return Re.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return Re.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return Re.get(t);let n=t.clone();return Re.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t.apply=r=>r(t),t)),zl=p("_ZodString",(t,e)=>{mr.init(t,e),q.init(t,e),t._zod.processJSONSchema=(n,o,i)=>Tm(t,n,o,i);let r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,t.regex=(...n)=>t.check(to(...n)),t.includes=(...n)=>t.check(oo(...n)),t.startsWith=(...n)=>t.check(io(...n)),t.endsWith=(...n)=>t.check(ao(...n)),t.min=(...n)=>t.check(Xt(...n)),t.max=(...n)=>t.check(Wr(...n)),t.length=(...n)=>t.check(Gr(...n)),t.nonempty=(...n)=>t.check(Xt(1,...n)),t.lowercase=n=>t.check(ro(n)),t.uppercase=n=>t.check(no(n)),t.trim=()=>t.check(uo()),t.normalize=(...n)=>t.check(co(...n)),t.toLowerCase=()=>t.check(lo()),t.toUpperCase=()=>t.check(po()),t.slugify=()=>t.check(Gi())}),na=p("ZodString",(t,e)=>{mr.init(t,e),zl.init(t,e),t.email=r=>t.check(Ei(Il,r)),t.url=r=>t.check(eo(oa,r)),t.jwt=r=>t.check(Wi(ql,r)),t.emoji=r=>t.check(Di(El,r)),t.guid=r=>t.check(Qn(ea,r)),t.uuid=r=>t.check(Ti(Rt,r)),t.uuidv4=r=>t.check(Pi(Rt,r)),t.uuidv6=r=>t.check(Oi(Rt,r)),t.uuidv7=r=>t.check(ji(Rt,r)),t.nanoid=r=>t.check(Ni(Tl,r)),t.guid=r=>t.check(Qn(ea,r)),t.cuid=r=>t.check(Ri(Pl,r)),t.cuid2=r=>t.check(Ai(Ol,r)),t.ulid=r=>t.check(Ui(jl,r)),t.base64=r=>t.check(Vi(Cl,r)),t.base64url=r=>t.check(Ji(Ml,r)),t.xid=r=>t.check(Zi(Dl,r)),t.ksuid=r=>t.check(Ci(Nl,r)),t.ipv4=r=>t.check(Mi(Rl,r)),t.ipv6=r=>t.check(Li(Al,r)),t.cidrv4=r=>t.check(qi(Ul,r)),t.cidrv6=r=>t.check(Fi(Zl,r)),t.e164=r=>t.check(Ki(Ll,r)),t.datetime=r=>t.check(_l(r)),t.date=r=>t.check($l(r)),t.time=r=>t.check(xl(r)),t.duration=r=>t.check(Sl(r))});function h(t){return Ou(na,t)}var ce=p("ZodStringFormat",(t,e)=>{oe.init(t,e),zl.init(t,e)}),Il=p("ZodEmail",(t,e)=>{xc.init(t,e),ce.init(t,e)});function Lb(t){return Ei(Il,t)}var ea=p("ZodGUID",(t,e)=>{$c.init(t,e),ce.init(t,e)});function qb(t){return Qn(ea,t)}var Rt=p("ZodUUID",(t,e)=>{bc.init(t,e),ce.init(t,e)});function Fb(t){return Ti(Rt,t)}function Vb(t){return Pi(Rt,t)}function Jb(t){return Oi(Rt,t)}function Kb(t){return ji(Rt,t)}var oa=p("ZodURL",(t,e)=>{kc.init(t,e),ce.init(t,e)});function Wb(t){return eo(oa,t)}function Gb(t){return eo(oa,{protocol:/^https?$/,hostname:Qe.domain,...y.normalizeParams(t)})}var El=p("ZodEmoji",(t,e)=>{Sc.init(t,e),ce.init(t,e)});function Hb(t){return Di(El,t)}var Tl=p("ZodNanoID",(t,e)=>{wc.init(t,e),ce.init(t,e)});function Bb(t){return Ni(Tl,t)}var Pl=p("ZodCUID",(t,e)=>{zc.init(t,e),ce.init(t,e)});function Xb(t){return Ri(Pl,t)}var Ol=p("ZodCUID2",(t,e)=>{Ic.init(t,e),ce.init(t,e)});function Yb(t){return Ai(Ol,t)}var jl=p("ZodULID",(t,e)=>{Ec.init(t,e),ce.init(t,e)});function Qb(t){return Ui(jl,t)}var Dl=p("ZodXID",(t,e)=>{Tc.init(t,e),ce.init(t,e)});function ex(t){return Zi(Dl,t)}var Nl=p("ZodKSUID",(t,e)=>{Pc.init(t,e),ce.init(t,e)});function tx(t){return Ci(Nl,t)}var Rl=p("ZodIPv4",(t,e)=>{Rc.init(t,e),ce.init(t,e)});function rx(t){return Mi(Rl,t)}var Th=p("ZodMAC",(t,e)=>{Uc.init(t,e),ce.init(t,e)});function nx(t){return ju(Th,t)}var Al=p("ZodIPv6",(t,e)=>{Ac.init(t,e),ce.init(t,e)});function ox(t){return Li(Al,t)}var Ul=p("ZodCIDRv4",(t,e)=>{Zc.init(t,e),ce.init(t,e)});function ix(t){return qi(Ul,t)}var Zl=p("ZodCIDRv6",(t,e)=>{Cc.init(t,e),ce.init(t,e)});function ax(t){return Fi(Zl,t)}var Cl=p("ZodBase64",(t,e)=>{Mc.init(t,e),ce.init(t,e)});function sx(t){return Vi(Cl,t)}var Ml=p("ZodBase64URL",(t,e)=>{Lc.init(t,e),ce.init(t,e)});function cx(t){return Ji(Ml,t)}var Ll=p("ZodE164",(t,e)=>{qc.init(t,e),ce.init(t,e)});function ux(t){return Ki(Ll,t)}var ql=p("ZodJWT",(t,e)=>{Fc.init(t,e),ce.init(t,e)});function lx(t){return Wi(ql,t)}var go=p("ZodCustomStringFormat",(t,e)=>{Vc.init(t,e),ce.init(t,e)});function dx(t,e,r={}){return Hr(go,t,e,r)}function px(t){return Hr(go,"hostname",Qe.hostname,t)}function fx(t){return Hr(go,"hex",Qe.hex,t)}function mx(t,e){let r=e?.enc??"hex",n=`${t}_${r}`,o=Qe[n];if(!o)throw new Error(`Unrecognized hash format: ${n}`);return Hr(go,n,o,e)}var ia=p("ZodNumber",(t,e)=>{Si.init(t,e),q.init(t,e),t._zod.processJSONSchema=(n,o,i)=>Pm(t,n,o,i),t.gt=(n,o)=>t.check(Dt(n,o)),t.gte=(n,o)=>t.check(Ae(n,o)),t.min=(n,o)=>t.check(Ae(n,o)),t.lt=(n,o)=>t.check(jt(n,o)),t.lte=(n,o)=>t.check(Ge(n,o)),t.max=(n,o)=>t.check(Ge(n,o)),t.int=n=>t.check(wl(n)),t.safe=n=>t.check(wl(n)),t.positive=n=>t.check(Dt(0,n)),t.nonnegative=n=>t.check(Ae(0,n)),t.negative=n=>t.check(jt(0,n)),t.nonpositive=n=>t.check(Ge(0,n)),t.multipleOf=(n,o)=>t.check(hr(n,o)),t.step=(n,o)=>t.check(hr(n,o)),t.finite=()=>t;let r=t._zod.bag;t.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),t.isFinite=!0,t.format=r.format??null});function ne(t){return Uu(ia,t)}var Xr=p("ZodNumberFormat",(t,e)=>{Jc.init(t,e),ia.init(t,e)});function wl(t){return Zu(Xr,t)}function hx(t){return Cu(Xr,t)}function gx(t){return Mu(Xr,t)}function vx(t){return Lu(Xr,t)}function _x(t){return qu(Xr,t)}var aa=p("ZodBoolean",(t,e)=>{Bn.init(t,e),q.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Om(t,r,n,o)});function ve(t){return Fu(aa,t)}var sa=p("ZodBigInt",(t,e)=>{wi.init(t,e),q.init(t,e),t._zod.processJSONSchema=(n,o,i)=>jm(t,n,o,i),t.gte=(n,o)=>t.check(Ae(n,o)),t.min=(n,o)=>t.check(Ae(n,o)),t.gt=(n,o)=>t.check(Dt(n,o)),t.gte=(n,o)=>t.check(Ae(n,o)),t.min=(n,o)=>t.check(Ae(n,o)),t.lt=(n,o)=>t.check(jt(n,o)),t.lte=(n,o)=>t.check(Ge(n,o)),t.max=(n,o)=>t.check(Ge(n,o)),t.positive=n=>t.check(Dt(BigInt(0),n)),t.negative=n=>t.check(jt(BigInt(0),n)),t.nonpositive=n=>t.check(Ge(BigInt(0),n)),t.nonnegative=n=>t.check(Ae(BigInt(0),n)),t.multipleOf=(n,o)=>t.check(hr(n,o));let r=t._zod.bag;t.minValue=r.minimum??null,t.maxValue=r.maximum??null,t.format=r.format??null});function yx(t){return Vu(sa,t)}var Fl=p("ZodBigIntFormat",(t,e)=>{Kc.init(t,e),sa.init(t,e)});function $x(t){return Ju(Fl,t)}function bx(t){return Ku(Fl,t)}var Ph=p("ZodSymbol",(t,e)=>{Wc.init(t,e),q.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Dm(t,r,n,o)});function xx(t){return Wu(Ph,t)}var Oh=p("ZodUndefined",(t,e)=>{Gc.init(t,e),q.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Rm(t,r,n,o)});function kx(t){return Gu(Oh,t)}var jh=p("ZodNull",(t,e)=>{Hc.init(t,e),q.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Nm(t,r,n,o)});function vo(t){return Hu(jh,t)}var Dh=p("ZodAny",(t,e)=>{Bc.init(t,e),q.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Zm(t,r,n,o)});function Sx(){return Bu(Dh)}var Nh=p("ZodUnknown",(t,e)=>{Xc.init(t,e),q.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Cm(t,r,n,o)});function ue(){return Xu(Nh)}var Rh=p("ZodNever",(t,e)=>{Yc.init(t,e),q.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Um(t,r,n,o)});function Vl(t){return Yu(Rh,t)}var Ah=p("ZodVoid",(t,e)=>{Qc.init(t,e),q.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Am(t,r,n,o)});function wx(t){return Qu(Ah,t)}var Jl=p("ZodDate",(t,e)=>{eu.init(t,e),q.init(t,e),t._zod.processJSONSchema=(n,o,i)=>Mm(t,n,o,i),t.min=(n,o)=>t.check(Ae(n,o)),t.max=(n,o)=>t.check(Ge(n,o));let r=t._zod.bag;t.minDate=r.minimum?new Date(r.minimum):null,t.maxDate=r.maximum?new Date(r.maximum):null});function zx(t){return el(Jl,t)}var Uh=p("ZodArray",(t,e)=>{tu.init(t,e),q.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Ym(t,r,n,o),t.element=e.element,t.min=(r,n)=>t.check(Xt(r,n)),t.nonempty=r=>t.check(Xt(1,r)),t.max=(r,n)=>t.check(Wr(r,n)),t.length=(r,n)=>t.check(Gr(r,n)),t.unwrap=()=>t.element});function H(t,e){return Im(Uh,t,e)}function Ix(t){let e=t._zod.def.shape;return Te(Object.keys(e))}var ca=p("ZodObject",(t,e)=>{wm.init(t,e),q.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Qm(t,r,n,o),y.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>Te(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:ue()}),t.loose=()=>t.clone({...t._zod.def,catchall:ue()}),t.strict=()=>t.clone({...t._zod.def,catchall:Vl()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>y.extend(t,r),t.safeExtend=r=>y.safeExtend(t,r),t.merge=r=>y.merge(t,r),t.pick=r=>y.pick(t,r),t.omit=r=>y.omit(t,r),t.partial=(...r)=>y.partial(Wl,t,r[0]),t.required=(...r)=>y.required(Gl,t,r[0])});function z(t,e){let r={type:"object",shape:t??{},...y.normalizeParams(e)};return new ca(r)}function Ex(t,e){return new ca({type:"object",shape:t,catchall:Vl(),...y.normalizeParams(e)})}function Ee(t,e){return new ca({type:"object",shape:t,catchall:ue(),...y.normalizeParams(e)})}var ua=p("ZodUnion",(t,e)=>{Xn.init(t,e),q.init(t,e),t._zod.processJSONSchema=(r,n,o)=>ml(t,r,n,o),t.options=e.options});function ie(t,e){return new ua({type:"union",options:t,...y.normalizeParams(e)})}var Zh=p("ZodXor",(t,e)=>{ua.init(t,e),ru.init(t,e),t._zod.processJSONSchema=(r,n,o)=>ml(t,r,n,o),t.options=e.options});function Tx(t,e){return new Zh({type:"union",options:t,inclusive:!1,...y.normalizeParams(e)})}var Ch=p("ZodDiscriminatedUnion",(t,e)=>{ua.init(t,e),nu.init(t,e)});function la(t,e,r){return new Ch({type:"union",options:e,discriminator:t,...y.normalizeParams(r)})}var Mh=p("ZodIntersection",(t,e)=>{ou.init(t,e),q.init(t,e),t._zod.processJSONSchema=(r,n,o)=>eh(t,r,n,o)});function _o(t,e){return new Mh({type:"intersection",left:t,right:e})}var Lh=p("ZodTuple",(t,e)=>{zi.init(t,e),q.init(t,e),t._zod.processJSONSchema=(r,n,o)=>th(t,r,n,o),t.rest=r=>t.clone({...t._zod.def,rest:r})});function qh(t,e,r){let n=e instanceof M,o=n?r:e,i=n?e:null;return new Lh({type:"tuple",items:t,rest:i,...y.normalizeParams(o)})}var da=p("ZodRecord",(t,e)=>{iu.init(t,e),q.init(t,e),t._zod.processJSONSchema=(r,n,o)=>rh(t,r,n,o),t.keyType=e.keyType,t.valueType=e.valueType});function pe(t,e,r){return new da({type:"record",keyType:t,valueType:e,...y.normalizeParams(r)})}function Px(t,e,r){let n=Ne(t);return n._zod.values=void 0,new da({type:"record",keyType:n,valueType:e,...y.normalizeParams(r)})}function Ox(t,e,r){return new da({type:"record",keyType:t,valueType:e,mode:"loose",...y.normalizeParams(r)})}var Fh=p("ZodMap",(t,e)=>{au.init(t,e),q.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Bm(t,r,n,o),t.keyType=e.keyType,t.valueType=e.valueType,t.min=(...r)=>t.check(Nt(...r)),t.nonempty=r=>t.check(Nt(1,r)),t.max=(...r)=>t.check(gr(...r)),t.size=(...r)=>t.check(Kr(...r))});function jx(t,e,r){return new Fh({type:"map",keyType:t,valueType:e,...y.normalizeParams(r)})}var Vh=p("ZodSet",(t,e)=>{su.init(t,e),q.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Xm(t,r,n,o),t.min=(...r)=>t.check(Nt(...r)),t.nonempty=r=>t.check(Nt(1,r)),t.max=(...r)=>t.check(gr(...r)),t.size=(...r)=>t.check(Kr(...r))});function Dx(t,e){return new Vh({type:"set",valueType:t,...y.normalizeParams(e)})}var ho=p("ZodEnum",(t,e)=>{cu.init(t,e),q.init(t,e),t._zod.processJSONSchema=(n,o,i)=>Lm(t,n,o,i),t.enum=e.entries,t.options=Object.values(e.entries);let r=new Set(Object.keys(e.entries));t.extract=(n,o)=>{let i={};for(let a of n)if(r.has(a))i[a]=e.entries[a];else throw new Error(`Key ${a} not found in enum`);return new ho({...e,checks:[],...y.normalizeParams(o),entries:i})},t.exclude=(n,o)=>{let i={...e.entries};for(let a of n)if(r.has(a))delete i[a];else throw new Error(`Key ${a} not found in enum`);return new ho({...e,checks:[],...y.normalizeParams(o),entries:i})}});function Te(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new ho({type:"enum",entries:r,...y.normalizeParams(e)})}function Nx(t,e){return new ho({type:"enum",entries:t,...y.normalizeParams(e)})}var Jh=p("ZodLiteral",(t,e)=>{uu.init(t,e),q.init(t,e),t._zod.processJSONSchema=(r,n,o)=>qm(t,r,n,o),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function T(t,e){return new Jh({type:"literal",values:Array.isArray(t)?t:[t],...y.normalizeParams(e)})}var Kh=p("ZodFile",(t,e)=>{lu.init(t,e),q.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Jm(t,r,n,o),t.min=(r,n)=>t.check(Nt(r,n)),t.max=(r,n)=>t.check(gr(r,n)),t.mime=(r,n)=>t.check(so(Array.isArray(r)?r:[r],n))});function Rx(t){return sl(Kh,t)}var Wh=p("ZodTransform",(t,e)=>{du.init(t,e),q.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Hm(t,r,n,o),t._zod.parse=(r,n)=>{if(n.direction==="backward")throw new dr(t.constructor.name);r.addIssue=i=>{if(typeof i=="string")r.issues.push(y.issue(i,r.value,e));else{let a=i;a.fatal&&(a.continue=!1),a.code??(a.code="custom"),a.input??(a.input=r.value),a.inst??(a.inst=t),r.issues.push(y.issue(a))}};let o=e.transform(r.value,r);return o instanceof Promise?o.then(i=>(r.value=i,r)):(r.value=o,r)}});function Kl(t){return new Wh({type:"transform",transform:t})}var Wl=p("ZodOptional",(t,e)=>{Ii.init(t,e),q.init(t,e),t._zod.processJSONSchema=(r,n,o)=>hl(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function fe(t){return new Wl({type:"optional",innerType:t})}var Gh=p("ZodExactOptional",(t,e)=>{pu.init(t,e),q.init(t,e),t._zod.processJSONSchema=(r,n,o)=>hl(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function Hh(t){return new Gh({type:"optional",innerType:t})}var Bh=p("ZodNullable",(t,e)=>{fu.init(t,e),q.init(t,e),t._zod.processJSONSchema=(r,n,o)=>nh(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function ta(t){return new Bh({type:"nullable",innerType:t})}function Ax(t){return fe(ta(t))}var Xh=p("ZodDefault",(t,e)=>{mu.init(t,e),q.init(t,e),t._zod.processJSONSchema=(r,n,o)=>ih(t,r,n,o),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function Yh(t,e){return new Xh({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():y.shallowClone(e)}})}var Qh=p("ZodPrefault",(t,e)=>{hu.init(t,e),q.init(t,e),t._zod.processJSONSchema=(r,n,o)=>ah(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function eg(t,e){return new Qh({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():y.shallowClone(e)}})}var Gl=p("ZodNonOptional",(t,e)=>{gu.init(t,e),q.init(t,e),t._zod.processJSONSchema=(r,n,o)=>oh(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function tg(t,e){return new Gl({type:"nonoptional",innerType:t,...y.normalizeParams(e)})}var rg=p("ZodSuccess",(t,e)=>{vu.init(t,e),q.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Km(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function Ux(t){return new rg({type:"success",innerType:t})}var ng=p("ZodCatch",(t,e)=>{_u.init(t,e),q.init(t,e),t._zod.processJSONSchema=(r,n,o)=>sh(t,r,n,o),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function og(t,e){return new ng({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var ig=p("ZodNaN",(t,e)=>{yu.init(t,e),q.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Fm(t,r,n,o)});function Zx(t){return tl(ig,t)}var Hl=p("ZodPipe",(t,e)=>{$u.init(t,e),q.init(t,e),t._zod.processJSONSchema=(r,n,o)=>ch(t,r,n,o),t.in=e.in,t.out=e.out});function ra(t,e){return new Hl({type:"pipe",in:t,out:e})}var Bl=p("ZodCodec",(t,e)=>{Hl.init(t,e),Yn.init(t,e)});function Cx(t,e,r){return new Bl({type:"pipe",in:t,out:e,transform:r.decode,reverseTransform:r.encode})}var ag=p("ZodReadonly",(t,e)=>{bu.init(t,e),q.init(t,e),t._zod.processJSONSchema=(r,n,o)=>uh(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function sg(t){return new ag({type:"readonly",innerType:t})}var cg=p("ZodTemplateLiteral",(t,e)=>{xu.init(t,e),q.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Vm(t,r,n,o)});function Mx(t,e){return new cg({type:"template_literal",parts:t,...y.normalizeParams(e)})}var ug=p("ZodLazy",(t,e)=>{wu.init(t,e),q.init(t,e),t._zod.processJSONSchema=(r,n,o)=>dh(t,r,n,o),t.unwrap=()=>t._zod.def.getter()});function lg(t){return new ug({type:"lazy",getter:t})}var dg=p("ZodPromise",(t,e)=>{Su.init(t,e),q.init(t,e),t._zod.processJSONSchema=(r,n,o)=>lh(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function Lx(t){return new dg({type:"promise",innerType:t})}var pg=p("ZodFunction",(t,e)=>{ku.init(t,e),q.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Gm(t,r,n,o)});function qx(t){return new pg({type:"function",input:Array.isArray(t?.input)?qh(t?.input):t?.input??H(ue()),output:t?.output??ue()})}var pa=p("ZodCustom",(t,e)=>{zu.init(t,e),q.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Wm(t,r,n,o)});function Fx(t){let e=new se({check:"custom"});return e._zod.check=t,e}function Xl(t,e){return cl(pa,t??(()=>!0),e)}function fg(t,e={}){return ul(pa,t,e)}function mg(t){return ll(t)}var Vx=dl,Jx=pl;function Kx(t,e={}){let r=new pa({type:"custom",check:"custom",fn:n=>n instanceof t,abort:!0,...y.normalizeParams(e)});return r._zod.bag.Class=t,r._zod.check=n=>{n.value instanceof t||n.issues.push({code:"invalid_type",expected:t.name,input:n.value,inst:r,path:[...r._zod.def.path??[]]})},r}var Wx=(...t)=>fl({Codec:Bl,Boolean:aa,String:na},...t);function Gx(t){let e=lg(()=>ie([h(t),ne(),ve(),vo(),H(e),pe(h(),e)]));return e}function fa(t,e){return ra(Kl(t),e)}var hg;hg||(hg={});var KN={...mo,...Qi,iso:vr};ye(Iu());var Ql="2025-11-25";var gg=[Ql,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Qt="io.modelcontextprotocol/related-task",ha="2.0",be=Xl(t=>t!==null&&(typeof t=="object"||typeof t=="function")),vg=ie([h(),ne().int()]),_g=h(),d4=Ee({ttl:ie([ne(),vo()]).optional(),pollInterval:ne().optional()}),Yx=z({ttl:ne().optional()}),Qx=z({taskId:h()}),ed=Ee({progressToken:vg.optional(),[Qt]:Qx.optional()}),Be=z({_meta:ed.optional()}),yo=Be.extend({task:Yx.optional()}),yg=t=>yo.safeParse(t).success,xe=z({method:h(),params:Be.loose().optional()}),et=z({_meta:ed.optional()}),tt=z({method:h(),params:et.loose().optional()}),ke=Ee({_meta:ed.optional()}),ga=ie([h(),ne().int()]),$g=z({jsonrpc:T(ha),id:ga,...xe.shape}).strict(),td=t=>$g.safeParse(t).success,bg=z({jsonrpc:T(ha),...tt.shape}).strict(),xg=t=>bg.safeParse(t).success,rd=z({jsonrpc:T(ha),id:ga,result:ke}).strict(),$o=t=>rd.safeParse(t).success;var Y;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(Y||(Y={}));var nd=z({jsonrpc:T(ha),id:ga.optional(),error:z({code:ne().int(),message:h(),data:ue().optional()})}).strict();var kg=t=>nd.safeParse(t).success;var Sg=ie([$g,bg,rd,nd]),p4=ie([rd,nd]),va=ke.strict(),ek=et.extend({requestId:ga.optional(),reason:h().optional()}),_a=tt.extend({method:T("notifications/cancelled"),params:ek}),tk=z({src:h(),mimeType:h().optional(),sizes:H(h()).optional(),theme:Te(["light","dark"]).optional()}),bo=z({icons:H(tk).optional()}),Yr=z({name:h(),title:h().optional()}),wg=Yr.extend({...Yr.shape,...bo.shape,version:h(),websiteUrl:h().optional(),description:h().optional()}),rk=_o(z({applyDefaults:ve().optional()}),pe(h(),ue())),nk=fa(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,_o(z({form:rk.optional(),url:be.optional()}),pe(h(),ue()).optional())),ok=Ee({list:be.optional(),cancel:be.optional(),requests:Ee({sampling:Ee({createMessage:be.optional()}).optional(),elicitation:Ee({create:be.optional()}).optional()}).optional()}),ik=Ee({list:be.optional(),cancel:be.optional(),requests:Ee({tools:Ee({call:be.optional()}).optional()}).optional()}),ak=z({experimental:pe(h(),be).optional(),sampling:z({context:be.optional(),tools:be.optional()}).optional(),elicitation:nk.optional(),roots:z({listChanged:ve().optional()}).optional(),tasks:ok.optional()}),sk=Be.extend({protocolVersion:h(),capabilities:ak,clientInfo:wg}),od=xe.extend({method:T("initialize"),params:sk});var ck=z({experimental:pe(h(),be).optional(),logging:be.optional(),completions:be.optional(),prompts:z({listChanged:ve().optional()}).optional(),resources:z({subscribe:ve().optional(),listChanged:ve().optional()}).optional(),tools:z({listChanged:ve().optional()}).optional(),tasks:ik.optional()}),uk=ke.extend({protocolVersion:h(),capabilities:ck,serverInfo:wg,instructions:h().optional()}),id=tt.extend({method:T("notifications/initialized"),params:et.optional()});var ya=xe.extend({method:T("ping"),params:Be.optional()}),lk=z({progress:ne(),total:fe(ne()),message:fe(h())}),dk=z({...et.shape,...lk.shape,progressToken:vg}),$a=tt.extend({method:T("notifications/progress"),params:dk}),pk=Be.extend({cursor:_g.optional()}),xo=xe.extend({params:pk.optional()}),ko=ke.extend({nextCursor:_g.optional()}),fk=Te(["working","input_required","completed","failed","cancelled"]),So=z({taskId:h(),status:fk,ttl:ie([ne(),vo()]),createdAt:h(),lastUpdatedAt:h(),pollInterval:fe(ne()),statusMessage:fe(h())}),Qr=ke.extend({task:So}),mk=et.merge(So),wo=tt.extend({method:T("notifications/tasks/status"),params:mk}),ba=xe.extend({method:T("tasks/get"),params:Be.extend({taskId:h()})}),xa=ke.merge(So),ka=xe.extend({method:T("tasks/result"),params:Be.extend({taskId:h()})}),f4=ke.loose(),Sa=xo.extend({method:T("tasks/list")}),wa=ko.extend({tasks:H(So)}),za=xe.extend({method:T("tasks/cancel"),params:Be.extend({taskId:h()})}),zg=ke.merge(So),Ig=z({uri:h(),mimeType:fe(h()),_meta:pe(h(),ue()).optional()}),Eg=Ig.extend({text:h()}),ad=h().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),Tg=Ig.extend({blob:ad}),zo=Te(["user","assistant"]),en=z({audience:H(zo).optional(),priority:ne().min(0).max(1).optional(),lastModified:vr.datetime({offset:!0}).optional()}),Pg=z({...Yr.shape,...bo.shape,uri:h(),description:fe(h()),mimeType:fe(h()),annotations:en.optional(),_meta:fe(Ee({}))}),hk=z({...Yr.shape,...bo.shape,uriTemplate:h(),description:fe(h()),mimeType:fe(h()),annotations:en.optional(),_meta:fe(Ee({}))}),gk=xo.extend({method:T("resources/list")}),vk=ko.extend({resources:H(Pg)}),_k=xo.extend({method:T("resources/templates/list")}),yk=ko.extend({resourceTemplates:H(hk)}),sd=Be.extend({uri:h()}),$k=sd,bk=xe.extend({method:T("resources/read"),params:$k}),xk=ke.extend({contents:H(ie([Eg,Tg]))}),kk=tt.extend({method:T("notifications/resources/list_changed"),params:et.optional()}),Sk=sd,wk=xe.extend({method:T("resources/subscribe"),params:Sk}),zk=sd,Ik=xe.extend({method:T("resources/unsubscribe"),params:zk}),Ek=et.extend({uri:h()}),Tk=tt.extend({method:T("notifications/resources/updated"),params:Ek}),Pk=z({name:h(),description:fe(h()),required:fe(ve())}),Ok=z({...Yr.shape,...bo.shape,description:fe(h()),arguments:fe(H(Pk)),_meta:fe(Ee({}))}),jk=xo.extend({method:T("prompts/list")}),Dk=ko.extend({prompts:H(Ok)}),Nk=Be.extend({name:h(),arguments:pe(h(),h()).optional()}),Rk=xe.extend({method:T("prompts/get"),params:Nk}),cd=z({type:T("text"),text:h(),annotations:en.optional(),_meta:pe(h(),ue()).optional()}),ud=z({type:T("image"),data:ad,mimeType:h(),annotations:en.optional(),_meta:pe(h(),ue()).optional()}),ld=z({type:T("audio"),data:ad,mimeType:h(),annotations:en.optional(),_meta:pe(h(),ue()).optional()}),Ak=z({type:T("tool_use"),name:h(),id:h(),input:pe(h(),ue()),_meta:pe(h(),ue()).optional()}),Uk=z({type:T("resource"),resource:ie([Eg,Tg]),annotations:en.optional(),_meta:pe(h(),ue()).optional()}),Zk=Pg.extend({type:T("resource_link")}),dd=ie([cd,ud,ld,Zk,Uk]),Ck=z({role:zo,content:dd}),Mk=ke.extend({description:h().optional(),messages:H(Ck)}),Lk=tt.extend({method:T("notifications/prompts/list_changed"),params:et.optional()}),qk=z({title:h().optional(),readOnlyHint:ve().optional(),destructiveHint:ve().optional(),idempotentHint:ve().optional(),openWorldHint:ve().optional()}),Fk=z({taskSupport:Te(["required","optional","forbidden"]).optional()}),Og=z({...Yr.shape,...bo.shape,description:h().optional(),inputSchema:z({type:T("object"),properties:pe(h(),be).optional(),required:H(h()).optional()}).catchall(ue()),outputSchema:z({type:T("object"),properties:pe(h(),be).optional(),required:H(h()).optional()}).catchall(ue()).optional(),annotations:qk.optional(),execution:Fk.optional(),_meta:pe(h(),ue()).optional()}),pd=xo.extend({method:T("tools/list")}),Vk=ko.extend({tools:H(Og)}),Ia=ke.extend({content:H(dd).default([]),structuredContent:pe(h(),ue()).optional(),isError:ve().optional()}),m4=Ia.or(ke.extend({toolResult:ue()})),Jk=yo.extend({name:h(),arguments:pe(h(),ue()).optional()}),Io=xe.extend({method:T("tools/call"),params:Jk}),Kk=tt.extend({method:T("notifications/tools/list_changed"),params:et.optional()}),h4=z({autoRefresh:ve().default(!0),debounceMs:ne().int().nonnegative().default(300)}),Eo=Te(["debug","info","notice","warning","error","critical","alert","emergency"]),Wk=Be.extend({level:Eo}),fd=xe.extend({method:T("logging/setLevel"),params:Wk}),Gk=et.extend({level:Eo,logger:h().optional(),data:ue()}),Hk=tt.extend({method:T("notifications/message"),params:Gk}),Bk=z({name:h().optional()}),Xk=z({hints:H(Bk).optional(),costPriority:ne().min(0).max(1).optional(),speedPriority:ne().min(0).max(1).optional(),intelligencePriority:ne().min(0).max(1).optional()}),Yk=z({mode:Te(["auto","required","none"]).optional()}),Qk=z({type:T("tool_result"),toolUseId:h().describe("The unique identifier for the corresponding tool call."),content:H(dd).default([]),structuredContent:z({}).loose().optional(),isError:ve().optional(),_meta:pe(h(),ue()).optional()}),eS=la("type",[cd,ud,ld]),ma=la("type",[cd,ud,ld,Ak,Qk]),tS=z({role:zo,content:ie([ma,H(ma)]),_meta:pe(h(),ue()).optional()}),rS=yo.extend({messages:H(tS),modelPreferences:Xk.optional(),systemPrompt:h().optional(),includeContext:Te(["none","thisServer","allServers"]).optional(),temperature:ne().optional(),maxTokens:ne().int(),stopSequences:H(h()).optional(),metadata:be.optional(),tools:H(Og).optional(),toolChoice:Yk.optional()}),nS=xe.extend({method:T("sampling/createMessage"),params:rS}),md=ke.extend({model:h(),stopReason:fe(Te(["endTurn","stopSequence","maxTokens"]).or(h())),role:zo,content:eS}),hd=ke.extend({model:h(),stopReason:fe(Te(["endTurn","stopSequence","maxTokens","toolUse"]).or(h())),role:zo,content:ie([ma,H(ma)])}),oS=z({type:T("boolean"),title:h().optional(),description:h().optional(),default:ve().optional()}),iS=z({type:T("string"),title:h().optional(),description:h().optional(),minLength:ne().optional(),maxLength:ne().optional(),format:Te(["email","uri","date","date-time"]).optional(),default:h().optional()}),aS=z({type:Te(["number","integer"]),title:h().optional(),description:h().optional(),minimum:ne().optional(),maximum:ne().optional(),default:ne().optional()}),sS=z({type:T("string"),title:h().optional(),description:h().optional(),enum:H(h()),default:h().optional()}),cS=z({type:T("string"),title:h().optional(),description:h().optional(),oneOf:H(z({const:h(),title:h()})),default:h().optional()}),uS=z({type:T("string"),title:h().optional(),description:h().optional(),enum:H(h()),enumNames:H(h()).optional(),default:h().optional()}),lS=ie([sS,cS]),dS=z({type:T("array"),title:h().optional(),description:h().optional(),minItems:ne().optional(),maxItems:ne().optional(),items:z({type:T("string"),enum:H(h())}),default:H(h()).optional()}),pS=z({type:T("array"),title:h().optional(),description:h().optional(),minItems:ne().optional(),maxItems:ne().optional(),items:z({anyOf:H(z({const:h(),title:h()}))}),default:H(h()).optional()}),fS=ie([dS,pS]),mS=ie([uS,lS,fS]),hS=ie([mS,oS,iS,aS]),gS=yo.extend({mode:T("form").optional(),message:h(),requestedSchema:z({type:T("object"),properties:pe(h(),hS),required:H(h()).optional()})}),vS=yo.extend({mode:T("url"),message:h(),elicitationId:h(),url:h().url()}),_S=ie([gS,vS]),yS=xe.extend({method:T("elicitation/create"),params:_S}),$S=et.extend({elicitationId:h()}),bS=tt.extend({method:T("notifications/elicitation/complete"),params:$S}),Ea=ke.extend({action:Te(["accept","decline","cancel"]),content:fa(t=>t===null?void 0:t,pe(h(),ie([h(),ne(),ve(),H(h())])).optional())}),xS=z({type:T("ref/resource"),uri:h()});var kS=z({type:T("ref/prompt"),name:h()}),SS=Be.extend({ref:ie([kS,xS]),argument:z({name:h(),value:h()}),context:z({arguments:pe(h(),h()).optional()}).optional()}),wS=xe.extend({method:T("completion/complete"),params:SS});var zS=ke.extend({completion:Ee({values:H(h()).max(100),total:fe(ne().int()),hasMore:fe(ve())})}),IS=z({uri:h().startsWith("file://"),name:h().optional(),_meta:pe(h(),ue()).optional()}),ES=xe.extend({method:T("roots/list"),params:Be.optional()}),gd=ke.extend({roots:H(IS)}),TS=tt.extend({method:T("notifications/roots/list_changed"),params:et.optional()}),g4=ie([ya,od,wS,fd,Rk,jk,gk,_k,bk,wk,Ik,Io,pd,ba,ka,Sa,za]),v4=ie([_a,$a,id,TS,wo]),_4=ie([va,md,hd,Ea,gd,xa,wa,Qr]),y4=ie([ya,nS,yS,ES,ba,ka,Sa,za]),$4=ie([_a,$a,Hk,Tk,kk,Kk,Lk,wo,bS]),b4=ie([va,uk,zS,Mk,Dk,vk,yk,xk,Ia,Vk,xa,wa,Qr]),J=class t extends Error{constructor(e,r,n){super(`MCP error ${e}: ${r}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,r,n){if(e===Y.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new Yl(o.elicitations,r)}return new t(e,r,n)}},Yl=class extends J{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(Y.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function er(t){return t==="completed"||t==="failed"||t==="cancelled"}var t1=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function vd(t){let r=Yi(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=hh(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function _d(t,e){let r=Yt(t,e);if(!r.success)throw r.error;return r.data}var RS=6e4,Ta=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(_a,r=>{this._oncancel(r)}),this.setNotificationHandler($a,r=>{this._onprogress(r)}),this.setRequestHandler(ya,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(ba,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new J(Y.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(ka,async(r,n)=>{let o=async()=>{let i=r.params.taskId;if(this._taskMessageQueue){let s;for(;s=await this._taskMessageQueue.dequeue(i,n.sessionId);){if(s.type==="response"||s.type==="error"){let c=s.message,u=c.id,l=this._requestResolvers.get(u);if(l)if(this._requestResolvers.delete(u),s.type==="response")l(c);else{let d=c,m=new J(d.error.code,d.error.message,d.error.data);l(m)}else{let d=s.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${u}`))}continue}await this._transport?.send(s.message,{relatedRequestId:n.requestId})}}let a=await this._taskStore.getTask(i,n.sessionId);if(!a)throw new J(Y.InvalidParams,`Task not found: ${i}`);if(!er(a.status))return await this._waitForTaskUpdate(i,n.signal),await o();if(er(a.status)){let s=await this._taskStore.getTaskResult(i,n.sessionId);return this._clearTaskQueue(i),{...s,_meta:{...s._meta,[Qt]:{taskId:i}}}}return await o()};return await o()}),this.setRequestHandler(Sa,async(r,n)=>{try{let{tasks:o,nextCursor:i}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:i,_meta:{}}}catch(o){throw new J(Y.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(za,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new J(Y.InvalidParams,`Task not found: ${r.params.taskId}`);if(er(o.status))throw new J(Y.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let i=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!i)throw new J(Y.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...i}}catch(o){throw o instanceof J?o:new J(Y.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,n,o,i=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:i,onTimeout:o})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),J.fromError(Y.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){this._transport=e;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=i=>{n?.(i),this._onerror(i)};let o=this._transport?.onmessage;this._transport.onmessage=(i,a)=>{o?.(i,a),$o(i)||kg(i)?this._onresponse(i):td(i)?this._onrequest(i,a):xg(i)?this._onnotification(i):this._onerror(new Error(`Unknown message type: ${JSON.stringify(i)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();let r=J.fromError(Y.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of e.values())n(r)}_onerror(e){this.onerror?.(e)}_onnotification(e){let r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,r){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,o=this._transport,i=e.params?._meta?.[Qt]?.taskId;if(n===void 0){let l={jsonrpc:"2.0",id:e.id,error:{code:Y.MethodNotFound,message:"Method not found"}};i&&this._taskMessageQueue?this._enqueueTaskMessage(i,{type:"error",message:l,timestamp:Date.now()},o?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):o?.send(l).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}let a=new AbortController;this._requestHandlerAbortControllers.set(e.id,a);let s=yg(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,u={signal:a.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async l=>{let d={relatedRequestId:e.id};i&&(d.relatedTask={taskId:i}),await this.notification(l,d)},sendRequest:async(l,d,m)=>{let f={...m,relatedRequestId:e.id};i&&!f.relatedTask&&(f.relatedTask={taskId:i});let g=f.relatedTask?.taskId??i;return g&&c&&await c.updateTaskStatus(g,"input_required"),await this.request(l,d,f)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:i,taskStore:c,taskRequestedTtl:s?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{s&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,u)).then(async l=>{if(a.signal.aborted)return;let d={result:l,jsonrpc:"2.0",id:e.id};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"response",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)},async l=>{if(a.signal.aborted)return;let d={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(l.code)?l.code:Y.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"error",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)}).catch(l=>this._onerror(new Error(`Failed to send response: ${l}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,o=Number(r),i=this._progressHandlers.get(o);if(!i){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let a=this._responseHandlers.get(o),s=this._timeoutInfo.get(o);if(s&&a&&s.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),a(c);return}i(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),$o(e))n(e);else{let a=new J(e.error.code,e.error.message,e.error.data);n(a)}return}let o=this._responseHandlers.get(r);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let i=!1;if($o(e)&&e.result&&typeof e.result=="object"){let a=e.result;if(a.task&&typeof a.task=="object"){let s=a.task;typeof s.taskId=="string"&&(i=!0,this._taskProgressTokens.set(s.taskId,r))}}if(i||this._progressHandlers.delete(r),$o(e))o(e);else{let a=J.fromError(e.error.code,e.error.message,e.error.data);o(a)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,n){let{task:o}=n??{};if(!o){try{yield{type:"result",result:await this.request(e,r,n)}}catch(a){yield{type:"error",error:a instanceof J?a:new J(Y.InternalError,String(a))}}return}let i;try{let a=await this.request(e,Qr,n);if(a.task)i=a.task.taskId,yield{type:"taskCreated",task:a.task};else throw new J(Y.InternalError,"Task creation did not return a task");for(;;){let s=await this.getTask({taskId:i},n);if(yield{type:"taskStatus",task:s},er(s.status)){s.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:i},r,n)}:s.status==="failed"?yield{type:"error",error:new J(Y.InternalError,`Task ${i} failed`)}:s.status==="cancelled"&&(yield{type:"error",error:new J(Y.InternalError,`Task ${i} was cancelled`)});return}if(s.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:i},r,n)};return}let c=s.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),n?.signal?.throwIfAborted()}}catch(a){yield{type:"error",error:a instanceof J?a:new J(Y.InternalError,String(a))}}}request(e,r,n){let{relatedRequestId:o,resumptionToken:i,onresumptiontoken:a,task:s,relatedTask:c}=n??{};return new Promise((u,l)=>{let d=O=>{l(O)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),s&&this.assertTaskCapability(e.method)}catch(O){d(O);return}n?.signal?.throwIfAborted();let m=this._requestMessageId++,f={...e,jsonrpc:"2.0",id:m};n?.onprogress&&(this._progressHandlers.set(m,n.onprogress),f.params={...e.params,_meta:{...e.params?._meta||{},progressToken:m}}),s&&(f.params={...f.params,task:s}),c&&(f.params={...f.params,_meta:{...f.params?._meta||{},[Qt]:c}});let g=O=>{this._responseHandlers.delete(m),this._progressHandlers.delete(m),this._cleanupTimeout(m),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:m,reason:String(O)}},{relatedRequestId:o,resumptionToken:i,onresumptiontoken:a}).catch(Z=>this._onerror(new Error(`Failed to send cancellation: ${Z}`)));let I=O instanceof J?O:new J(Y.RequestTimeout,String(O));l(I)};this._responseHandlers.set(m,O=>{if(!n?.signal?.aborted){if(O instanceof Error)return l(O);try{let I=Yt(r,O.result);I.success?u(I.data):l(I.error)}catch(I){l(I)}}}),n?.signal?.addEventListener("abort",()=>{g(n?.signal?.reason)});let v=n?.timeout??RS,$=()=>g(J.fromError(Y.RequestTimeout,"Request timed out",{timeout:v}));this._setupTimeout(m,v,n?.maxTotalTimeout,$,n?.resetTimeoutOnProgress??!1);let x=c?.taskId;if(x){let O=I=>{let Z=this._responseHandlers.get(m);Z?Z(I):this._onerror(new Error(`Response handler missing for side-channeled request ${m}`))};this._requestResolvers.set(m,O),this._enqueueTaskMessage(x,{type:"request",message:f,timestamp:Date.now()}).catch(I=>{this._cleanupTimeout(m),l(I)})}else this._transport.send(f,{relatedRequestId:o,resumptionToken:i,onresumptiontoken:a}).catch(O=>{this._cleanupTimeout(m),l(O)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},xa,r)}async getTaskResult(e,r,n){return this.request({method:"tasks/result",params:e},r,n)}async listTasks(e,r){return this.request({method:"tasks/list",params:e},wa,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},zg,r)}async notification(e,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let n=r?.relatedTask?.taskId;if(n){let s={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[Qt]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:s,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let s={...e,jsonrpc:"2.0"};r?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[Qt]:r.relatedTask}}}),this._transport?.send(s,r).catch(c=>this._onerror(c))});return}let a={...e,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[Qt]:r.relatedTask}}}),await this._transport.send(a,r)}setRequestHandler(e,r){let n=vd(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,i)=>{let a=_d(e,o);return Promise.resolve(r(a,i))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){let n=vd(e);this._notificationHandlers.set(n,o=>{let i=_d(e,o);return Promise.resolve(r(i))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,o)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,r);for(let o of n)if(o.type==="request"&&td(o.message)){let i=o.message.id,a=this._requestResolvers.get(i);a?(a(new J(Y.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(i)):this._onerror(new Error(`Resolver missing for request ${i} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let o=await this._taskStore?.getTask(e);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,i)=>{if(r.aborted){i(new J(Y.InvalidRequest,"Request cancelled"));return}let a=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(a),i(new J(Y.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async o=>{if(!e)throw new Error("No request provided");return await n.createTask(o,e.id,{method:e.method,params:e.params},r)},getTask:async o=>{let i=await n.getTask(o,r);if(!i)throw new J(Y.InvalidParams,"Failed to retrieve task: Task not found");return i},storeTaskResult:async(o,i,a)=>{await n.storeTaskResult(o,i,a,r);let s=await n.getTask(o,r);if(s){let c=wo.parse({method:"notifications/tasks/status",params:s});await this.notification(c),er(s.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,i,a)=>{let s=await n.getTask(o,r);if(!s)throw new J(Y.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(er(s.status))throw new J(Y.InvalidParams,`Cannot update task "${o}" from terminal status "${s.status}" to "${i}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,i,a,r);let c=await n.getTask(o,r);if(c){let u=wo.parse({method:"notifications/tasks/status",params:c});await this.notification(u),er(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function jg(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Dg(t,e){let r={...t};for(let n in e){let o=n,i=e[o];if(i===void 0)continue;let a=r[o];jg(a)&&jg(i)?r[o]={...a,...i}:r[o]=i}return r}var yy=ai(nf(),1),$y=ai(_y(),1);function wT(){let t=new yy.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,$y.default)(t),t}var ps=class{constructor(e){this._ajv=e??wT()}getValidator(e){let r="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}};var fs=class{constructor(e){this._server=e}requestStream(e,r,n){return this._server.requestStream(e,r,n)}async getTask(e,r){return this._server.getTask({taskId:e},r)}async getTaskResult(e,r,n){return this._server.getTaskResult({taskId:e},r,n)}async listTasks(e,r){return this._server.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._server.cancelTask({taskId:e},r)}};function by(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${e})`);break;default:break}}function xy(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}var ms=class extends Ta{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Eo.options.map((n,o)=>[n,o])),this.isMessageIgnored=(n,o)=>{let i=this._loggingLevels.get(o);return i?this.LOG_LEVEL_SEVERITY.get(n)this._oninitialize(n)),this.setNotificationHandler(id,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(fd,async(n,o)=>{let i=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:a}=n.params,s=Eo.safeParse(a);return s.success&&this._loggingLevels.set(i,s.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new fs(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Dg(this._capabilities,e)}setRequestHandler(e,r){let o=Yi(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let i;if(Br(o)){let s=o;i=s._zod?.def?.value??s.value}else{let s=o;i=s._def?.value??s.value}if(typeof i!="string")throw new Error("Schema method literal must be a string");if(i==="tools/call"){let s=async(c,u)=>{let l=Yt(Io,c);if(!l.success){let g=l.error instanceof Error?l.error.message:String(l.error);throw new J(Y.InvalidParams,`Invalid tools/call request: ${g}`)}let{params:d}=l.data,m=await Promise.resolve(r(c,u));if(d.task){let g=Yt(Qr,m);if(!g.success){let v=g.error instanceof Error?g.error.message:String(g.error);throw new J(Y.InvalidParams,`Invalid task creation result: ${v}`)}return g.data}let f=Yt(Ia,m);if(!f.success){let g=f.error instanceof Error?f.error.message:String(f.error);throw new J(Y.InvalidParams,`Invalid tools/call result: ${g}`)}return f.data};return super.setRequestHandler(e,s)}return super.setRequestHandler(e,r)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){xy(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&by(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let r=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:gg.includes(r)?r:Ql,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},va)}async createMessage(e,r){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let n=e.messages[e.messages.length-1],o=Array.isArray(n.content)?n.content:[n.content],i=o.some(u=>u.type==="tool_result"),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,s=a?Array.isArray(a.content)?a.content:[a.content]:[],c=s.some(u=>u.type==="tool_use");if(i){if(o.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let u=new Set(s.filter(d=>d.type==="tool_use").map(d=>d.id)),l=new Set(o.filter(d=>d.type==="tool_result").map(d=>d.toolUseId));if(u.size!==l.size||![...u].every(d=>l.has(d)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},hd,r):this.request({method:"sampling/createMessage",params:e},md,r)}async elicitInput(e,r){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let o=e;return this.request({method:"elicitation/create",params:o},Ea,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let o=e.mode==="form"?e:{...e,mode:"form"},i=await this.request({method:"elicitation/create",params:o},Ea,r);if(i.action==="accept"&&i.content&&o.requestedSchema)try{let s=this._jsonSchemaValidator.getValidator(o.requestedSchema)(i.content);if(!s.valid)throw new J(Y.InvalidParams,`Elicitation response content does not match requested schema: ${s.errorMessage}`)}catch(a){throw a instanceof J?a:new J(Y.InternalError,`Error validating elicitation response: ${a instanceof Error?a.message:String(a)}`)}return i}}}createElicitationCompletionNotifier(e,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},r)}async listRoots(e,r){return this.request({method:"roots/list",params:e},gd,r)}async sendLoggingMessage(e,r){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,r))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};var pf=ai(require("node:process"),1);var hs=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(` `);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),zT(r)}clear(){this._buffer=void 0}};function zT(t){return Sg.parse(JSON.parse(t))}function ky(t){return JSON.stringify(t)+` -`}var gs=class{constructor(e=pf.default.stdin,r=pf.default.stdout){this._stdin=e,this._stdout=r,this._readBuffer=new hs,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{this.onerror?.(n)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(r=>{let n=ky(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};var mf=ai(require("path"),1);var ff={DEFAULT:3e5,HEALTH_CHECK:3e4,WORKER_STARTUP_WAIT:1e3,WORKER_STARTUP_RETRIES:300,PRE_RESTART_SETTLE_DELAY:2e3,POWERSHELL_COMMAND:1e4,WINDOWS_MULTIPLIER:1.5};function Sy(t){return process.platform==="win32"?Math.round(t*ff.WINDOWS_MULTIPLIER):t}var wt=require("fs"),vs=require("path"),Iy=require("os");var wy="bugfix,feature,refactor,discovery,decision,change",zy="how-it-works,why-it-exists,what-changed,problem-solution,gotcha,pattern,trade-off";var qt=class{static DEFAULTS={CLAUDE_MEM_MODEL:"claude-sonnet-4-5",CLAUDE_MEM_CONTEXT_OBSERVATIONS:"50",CLAUDE_MEM_WORKER_PORT:"37777",CLAUDE_MEM_WORKER_HOST:"127.0.0.1",CLAUDE_MEM_SKIP_TOOLS:"ListMcpResourcesTool,SlashCommand,Skill,TodoWrite,AskUserQuestion",CLAUDE_MEM_PROVIDER:"claude",CLAUDE_MEM_CLAUDE_AUTH_METHOD:"cli",CLAUDE_MEM_GEMINI_API_KEY:"",CLAUDE_MEM_GEMINI_MODEL:"gemini-2.5-flash-lite",CLAUDE_MEM_GEMINI_RATE_LIMITING_ENABLED:"true",CLAUDE_MEM_OPENROUTER_API_KEY:"",CLAUDE_MEM_OPENROUTER_MODEL:"xiaomi/mimo-v2-flash:free",CLAUDE_MEM_OPENROUTER_SITE_URL:"",CLAUDE_MEM_OPENROUTER_APP_NAME:"claude-mem",CLAUDE_MEM_OPENROUTER_MAX_CONTEXT_MESSAGES:"20",CLAUDE_MEM_OPENROUTER_MAX_TOKENS:"100000",CLAUDE_MEM_DATA_DIR:(0,vs.join)((0,Iy.homedir)(),".claude-mem"),CLAUDE_MEM_LOG_LEVEL:"INFO",CLAUDE_MEM_PYTHON_VERSION:"3.13",CLAUDE_CODE_PATH:"",CLAUDE_MEM_MODE:"code",CLAUDE_MEM_CONTEXT_SHOW_READ_TOKENS:"true",CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS:"true",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT:"true",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT:"true",CLAUDE_MEM_CONTEXT_OBSERVATION_TYPES:wy,CLAUDE_MEM_CONTEXT_OBSERVATION_CONCEPTS:zy,CLAUDE_MEM_CONTEXT_FULL_COUNT:"5",CLAUDE_MEM_CONTEXT_FULL_FIELD:"narrative",CLAUDE_MEM_CONTEXT_SESSION_COUNT:"10",CLAUDE_MEM_CONTEXT_SHOW_LAST_SUMMARY:"true",CLAUDE_MEM_CONTEXT_SHOW_LAST_MESSAGE:"false",CLAUDE_MEM_FOLDER_CLAUDEMD_ENABLED:"false",CLAUDE_MEM_EXCLUDED_PROJECTS:"",CLAUDE_MEM_FOLDER_MD_EXCLUDE:"[]"};static getAllDefaults(){return{...this.DEFAULTS}}static get(e){return this.DEFAULTS[e]}static getInt(e){let r=this.get(e);return parseInt(r,10)}static getBool(e){let r=this.get(e);return r==="true"||r===!0}static applyEnvOverrides(e){let r={...e};for(let n of Object.keys(this.DEFAULTS))process.env[n]!==void 0&&(r[n]=process.env[n]);return r}static loadFromFile(e){try{if(!(0,wt.existsSync)(e)){let a=this.getAllDefaults();try{let s=(0,vs.dirname)(e);(0,wt.existsSync)(s)||(0,wt.mkdirSync)(s,{recursive:!0}),(0,wt.writeFileSync)(e,JSON.stringify(a,null,2),"utf-8"),console.log("[SETTINGS] Created settings file with defaults:",e)}catch(s){console.warn("[SETTINGS] Failed to create settings file, using in-memory defaults:",e,s)}return this.applyEnvOverrides(a)}let r=(0,wt.readFileSync)(e,"utf-8"),n=JSON.parse(r),o=n;if(n.env&&typeof n.env=="object"){o=n.env;try{(0,wt.writeFileSync)(e,JSON.stringify(o,null,2),"utf-8"),console.log("[SETTINGS] Migrated settings file from nested to flat schema:",e)}catch(a){console.warn("[SETTINGS] Failed to auto-migrate settings file:",e,a)}}let i={...this.DEFAULTS};for(let a of Object.keys(this.DEFAULTS))o[a]!==void 0&&(i[a]=o[a]);return this.applyEnvOverrides(i)}catch(r){return console.warn("[SETTINGS] Failed to load settings, using defaults:",e,r),this.applyEnvOverrides(this.getAllDefaults())}}};var $e=require("path"),Ey=require("os");var Ty=require("url");var TT={};function IT(){return typeof __dirname<"u"?__dirname:(0,$e.dirname)((0,Ty.fileURLToPath)(TT.url))}var ZZ=IT(),Ft=qt.get("CLAUDE_MEM_DATA_DIR"),_s=process.env.CLAUDE_CONFIG_DIR||(0,$e.join)((0,Ey.homedir)(),".claude"),ET=(0,$e.join)(_s,"plugins","marketplaces","thedotmack"),CZ=(0,$e.join)(Ft,"archives"),MZ=(0,$e.join)(Ft,"logs"),LZ=(0,$e.join)(Ft,"trash"),qZ=(0,$e.join)(Ft,"backups"),FZ=(0,$e.join)(Ft,"modes"),VZ=(0,$e.join)(Ft,"settings.json"),JZ=(0,$e.join)(Ft,"claude-mem.db"),KZ=(0,$e.join)(Ft,"vector-db"),WZ=(0,$e.join)(Ft,"observer-sessions"),GZ=(0,$e.join)(_s,"settings.json"),HZ=(0,$e.join)(_s,"commands"),BZ=(0,$e.join)(_s,"CLAUDE.md");var rC=Sy(ff.HEALTH_CHECK);var ys=null,$s=null;function Py(){if(ys!==null)return ys;let t=mf.default.join(qt.get("CLAUDE_MEM_DATA_DIR"),"settings.json"),e=qt.loadFromFile(t);return ys=parseInt(e.CLAUDE_MEM_WORKER_PORT,10),ys}function Oy(){if($s!==null)return $s;let t=mf.default.join(qt.get("CLAUDE_MEM_DATA_DIR"),"settings.json");return $s=qt.loadFromFile(t).CLAUDE_MEM_WORKER_HOST,$s}var PT="9.1.1";console.log=(...t)=>{_e.error("CONSOLE","Intercepted console output (MCP protocol protection)",void 0,{args:t})};var OT=Py(),jT=Oy(),ii=`http://${jT}:${OT}`,jy={search:"/api/search",timeline:"/api/timeline"};async function Dy(t,e){_e.debug("SYSTEM","\u2192 Worker API",void 0,{endpoint:t,params:e});try{let r=new URLSearchParams;for(let[a,s]of Object.entries(e))s!=null&&r.append(a,String(s));let n=`${ii}${t}?${r}`,o=await fetch(n);if(!o.ok){let a=await o.text();throw new Error(`Worker API error (${o.status}): ${a}`)}let i=await o.json();return _e.debug("SYSTEM","\u2190 Worker API success",void 0,{endpoint:t}),i}catch(r){return _e.error("SYSTEM","\u2190 Worker API error",{endpoint:t},r),{content:[{type:"text",text:`Error calling Worker API: ${r instanceof Error?r.message:String(r)}`}],isError:!0}}}async function Ny(t,e){_e.debug("HTTP","Worker API request (POST)",void 0,{endpoint:t});try{let r=`${ii}${t}`,n=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!n.ok){let i=await n.text();throw new Error(`Worker API error (${n.status}): ${i}`)}let o=await n.json();return _e.debug("HTTP","Worker API success (POST)",void 0,{endpoint:t}),{content:[{type:"text",text:JSON.stringify(o,null,2)}]}}catch(r){return _e.error("HTTP","Worker API error (POST)",{endpoint:t},r),{content:[{type:"text",text:`Error calling Worker API: ${r instanceof Error?r.message:String(r)}`}],isError:!0}}}async function DT(){try{return(await fetch(`${ii}/api/health`)).ok}catch(t){return _e.debug("SYSTEM","Worker health check failed",{},t),!1}}var Ry=[{name:"__IMPORTANT",description:`3-LAYER WORKFLOW (ALWAYS FOLLOW): +`}var gs=class{constructor(e=pf.default.stdin,r=pf.default.stdout){this._stdin=e,this._stdout=r,this._readBuffer=new hs,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{this.onerror?.(n)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(r=>{let n=ky(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};var mf=ai(require("path"),1);var ff={DEFAULT:3e5,HEALTH_CHECK:3e4,WORKER_STARTUP_WAIT:1e3,WORKER_STARTUP_RETRIES:300,PRE_RESTART_SETTLE_DELAY:2e3,POWERSHELL_COMMAND:1e4,WINDOWS_MULTIPLIER:1.5};function Sy(t){return process.platform==="win32"?Math.round(t*ff.WINDOWS_MULTIPLIER):t}var wt=require("fs"),vs=require("path"),Iy=require("os");var wy="bugfix,feature,refactor,discovery,decision,change",zy="how-it-works,why-it-exists,what-changed,problem-solution,gotcha,pattern,trade-off";var qt=class{static DEFAULTS={CLAUDE_MEM_MODEL:"claude-sonnet-4-5",CLAUDE_MEM_CONTEXT_OBSERVATIONS:"50",CLAUDE_MEM_WORKER_PORT:"37777",CLAUDE_MEM_WORKER_HOST:"127.0.0.1",CLAUDE_MEM_SKIP_TOOLS:"ListMcpResourcesTool,SlashCommand,Skill,TodoWrite,AskUserQuestion",CLAUDE_MEM_PROVIDER:"claude",CLAUDE_MEM_CLAUDE_AUTH_METHOD:"cli",CLAUDE_MEM_GEMINI_API_KEY:"",CLAUDE_MEM_GEMINI_MODEL:"gemini-2.5-flash-lite",CLAUDE_MEM_GEMINI_RATE_LIMITING_ENABLED:"true",CLAUDE_MEM_OPENROUTER_API_KEY:"",CLAUDE_MEM_OPENROUTER_MODEL:"xiaomi/mimo-v2-flash:free",CLAUDE_MEM_OPENROUTER_SITE_URL:"",CLAUDE_MEM_OPENROUTER_APP_NAME:"claude-mem",CLAUDE_MEM_OPENROUTER_MAX_CONTEXT_MESSAGES:"20",CLAUDE_MEM_OPENROUTER_MAX_TOKENS:"100000",CLAUDE_MEM_DATA_DIR:(0,vs.join)((0,Iy.homedir)(),".claude-mem"),CLAUDE_MEM_LOG_LEVEL:"INFO",CLAUDE_MEM_PYTHON_VERSION:"3.13",CLAUDE_CODE_PATH:"",CLAUDE_MEM_MODE:"code",CLAUDE_MEM_CONTEXT_SHOW_READ_TOKENS:"true",CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS:"true",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT:"true",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT:"true",CLAUDE_MEM_CONTEXT_OBSERVATION_TYPES:wy,CLAUDE_MEM_CONTEXT_OBSERVATION_CONCEPTS:zy,CLAUDE_MEM_CONTEXT_FULL_COUNT:"5",CLAUDE_MEM_CONTEXT_FULL_FIELD:"narrative",CLAUDE_MEM_CONTEXT_SESSION_COUNT:"10",CLAUDE_MEM_CONTEXT_SHOW_LAST_SUMMARY:"true",CLAUDE_MEM_CONTEXT_SHOW_LAST_MESSAGE:"false",CLAUDE_MEM_FOLDER_CLAUDEMD_ENABLED:"false",CLAUDE_MEM_EXCLUDED_PROJECTS:"",CLAUDE_MEM_FOLDER_MD_EXCLUDE:"[]"};static getAllDefaults(){return{...this.DEFAULTS}}static get(e){return this.DEFAULTS[e]}static getInt(e){let r=this.get(e);return parseInt(r,10)}static getBool(e){let r=this.get(e);return r==="true"||r===!0}static applyEnvOverrides(e){let r={...e};for(let n of Object.keys(this.DEFAULTS))process.env[n]!==void 0&&(r[n]=process.env[n]);return r}static loadFromFile(e){try{if(!(0,wt.existsSync)(e)){let a=this.getAllDefaults();try{let s=(0,vs.dirname)(e);(0,wt.existsSync)(s)||(0,wt.mkdirSync)(s,{recursive:!0}),(0,wt.writeFileSync)(e,JSON.stringify(a,null,2),"utf-8"),console.log("[SETTINGS] Created settings file with defaults:",e)}catch(s){console.warn("[SETTINGS] Failed to create settings file, using in-memory defaults:",e,s)}return this.applyEnvOverrides(a)}let r=(0,wt.readFileSync)(e,"utf-8"),n=JSON.parse(r),o=n;if(n.env&&typeof n.env=="object"){o=n.env;try{(0,wt.writeFileSync)(e,JSON.stringify(o,null,2),"utf-8"),console.log("[SETTINGS] Migrated settings file from nested to flat schema:",e)}catch(a){console.warn("[SETTINGS] Failed to auto-migrate settings file:",e,a)}}let i={...this.DEFAULTS};for(let a of Object.keys(this.DEFAULTS))o[a]!==void 0&&(i[a]=o[a]);return this.applyEnvOverrides(i)}catch(r){return console.warn("[SETTINGS] Failed to load settings, using defaults:",e,r),this.applyEnvOverrides(this.getAllDefaults())}}};var $e=require("path"),Ey=require("os");var Ty=require("url");var TT={};function IT(){return typeof __dirname<"u"?__dirname:(0,$e.dirname)((0,Ty.fileURLToPath)(TT.url))}var ZZ=IT(),Ft=qt.get("CLAUDE_MEM_DATA_DIR"),_s=process.env.CLAUDE_CONFIG_DIR||(0,$e.join)((0,Ey.homedir)(),".claude"),ET=(0,$e.join)(_s,"plugins","marketplaces","thedotmack"),CZ=(0,$e.join)(Ft,"archives"),MZ=(0,$e.join)(Ft,"logs"),LZ=(0,$e.join)(Ft,"trash"),qZ=(0,$e.join)(Ft,"backups"),FZ=(0,$e.join)(Ft,"modes"),VZ=(0,$e.join)(Ft,"settings.json"),JZ=(0,$e.join)(Ft,"claude-mem.db"),KZ=(0,$e.join)(Ft,"vector-db"),WZ=(0,$e.join)(Ft,"observer-sessions"),GZ=(0,$e.join)(_s,"settings.json"),HZ=(0,$e.join)(_s,"commands"),BZ=(0,$e.join)(_s,"CLAUDE.md");var rC=Sy(ff.HEALTH_CHECK);var ys=null,$s=null;function Py(){if(ys!==null)return ys;let t=mf.default.join(qt.get("CLAUDE_MEM_DATA_DIR"),"settings.json"),e=qt.loadFromFile(t);return ys=parseInt(e.CLAUDE_MEM_WORKER_PORT,10),ys}function Oy(){if($s!==null)return $s;let t=mf.default.join(qt.get("CLAUDE_MEM_DATA_DIR"),"settings.json");return $s=qt.loadFromFile(t).CLAUDE_MEM_WORKER_HOST,$s}var PT="10.0.0";console.log=(...t)=>{_e.error("CONSOLE","Intercepted console output (MCP protocol protection)",void 0,{args:t})};var OT=Py(),jT=Oy(),ii=`http://${jT}:${OT}`,jy={search:"/api/search",timeline:"/api/timeline"};async function Dy(t,e){_e.debug("SYSTEM","\u2192 Worker API",void 0,{endpoint:t,params:e});try{let r=new URLSearchParams;for(let[a,s]of Object.entries(e))s!=null&&r.append(a,String(s));let n=`${ii}${t}?${r}`,o=await fetch(n);if(!o.ok){let a=await o.text();throw new Error(`Worker API error (${o.status}): ${a}`)}let i=await o.json();return _e.debug("SYSTEM","\u2190 Worker API success",void 0,{endpoint:t}),i}catch(r){return _e.error("SYSTEM","\u2190 Worker API error",{endpoint:t},r),{content:[{type:"text",text:`Error calling Worker API: ${r instanceof Error?r.message:String(r)}`}],isError:!0}}}async function Ny(t,e){_e.debug("HTTP","Worker API request (POST)",void 0,{endpoint:t});try{let r=`${ii}${t}`,n=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!n.ok){let i=await n.text();throw new Error(`Worker API error (${n.status}): ${i}`)}let o=await n.json();return _e.debug("HTTP","Worker API success (POST)",void 0,{endpoint:t}),{content:[{type:"text",text:JSON.stringify(o,null,2)}]}}catch(r){return _e.error("HTTP","Worker API error (POST)",{endpoint:t},r),{content:[{type:"text",text:`Error calling Worker API: ${r instanceof Error?r.message:String(r)}`}],isError:!0}}}async function DT(){try{return(await fetch(`${ii}/api/health`)).ok}catch(t){return _e.debug("SYSTEM","Worker health check failed",{},t),!1}}var Ry=[{name:"__IMPORTANT",description:`3-LAYER WORKFLOW (ALWAYS FOLLOW): 1. search(query) \u2192 Get index with IDs (~50-100 tokens/result) 2. timeline(anchor=ID) \u2192 Get context around interesting results 3. get_observations([IDs]) \u2192 Fetch full details ONLY for filtered IDs diff --git a/plugin/scripts/worker-service.cjs b/plugin/scripts/worker-service.cjs index 506189d9..6c1a2850 100755 --- a/plugin/scripts/worker-service.cjs +++ b/plugin/scripts/worker-service.cjs @@ -872,9 +872,9 @@ ${s}`}(0,cr.writeFileSync)(n,o),(0,cr.renameSync)(n,r)}function ege(t,e,r,n,i,a, Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let s of t.seen.entries()){let o=s[1];if(e===s[0]){a(s);continue}if(t.external){let u=t.external.registry.get(s[0])?.id;if(e!==s[0]&&u){a(s);continue}}if(t.metadataRegistry.get(s[0])?.id){a(s);continue}if(o.cycle){a(s);continue}if(o.count>1&&t.reused==="ref"){a(s);continue}}}function tf(t,e){let r=t.seen.get(e);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let n=s=>{let o=t.seen.get(s);if(o.ref===null)return;let c=o.def??o.schema,u={...c},l=o.ref;if(o.ref=null,l){n(l);let p=t.seen.get(l),f=p.schema;if(f.$ref&&(t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0")?(c.allOf=c.allOf??[],c.allOf.push(f)):Object.assign(c,f),Object.assign(c,u),s._zod.parent===l)for(let y in c)y==="$ref"||y==="allOf"||y in u||delete c[y];if(f.$ref)for(let y in c)y==="$ref"||y==="allOf"||y in p.def&&JSON.stringify(c[y])===JSON.stringify(p.def[y])&&delete c[y]}let d=s._zod.parent;if(d&&d!==l){n(d);let p=t.seen.get(d);if(p?.schema.$ref&&(c.$ref=p.schema.$ref,p.def))for(let f in c)f==="$ref"||f==="allOf"||f in p.def&&JSON.stringify(c[f])===JSON.stringify(p.def[f])&&delete c[f]}t.override({zodSchema:s,jsonSchema:c,path:o.path??[]})};for(let s of[...t.seen.entries()].reverse())n(s[0]);let i={};if(t.target==="draft-2020-12"?i.$schema="https://json-schema.org/draft/2020-12/schema":t.target==="draft-07"?i.$schema="http://json-schema.org/draft-07/schema#":t.target==="draft-04"?i.$schema="http://json-schema.org/draft-04/schema#":t.target,t.external?.uri){let s=t.external.registry.get(e)?.id;if(!s)throw new Error("Schema is missing an `id` property");i.$id=t.external.uri(s)}Object.assign(i,r.def??r.schema);let a=t.external?.defs??{};for(let s of t.seen.entries()){let o=s[1];o.def&&o.defId&&(a[o.defId]=o.def)}t.external||Object.keys(a).length>0&&(t.target==="draft-2020-12"?i.$defs=a:i.definitions=a);try{let s=JSON.parse(JSON.stringify(i));return Object.defineProperty(s,"~standard",{value:{...e["~standard"],jsonSchema:{input:qu(e,"input",t.processors),output:qu(e,"output",t.processors)}},enumerable:!1,writable:!1}),s}catch{throw new Error("Error converting schema to JSON.")}}function Lr(t,e){let r=e??{seen:new Set};if(r.seen.has(t))return!1;r.seen.add(t);let n=t._zod.def;if(n.type==="transform")return!0;if(n.type==="array")return Lr(n.element,r);if(n.type==="set")return Lr(n.valueType,r);if(n.type==="lazy")return Lr(n.getter(),r);if(n.type==="promise"||n.type==="optional"||n.type==="nonoptional"||n.type==="nullable"||n.type==="readonly"||n.type==="default"||n.type==="prefault")return Lr(n.innerType,r);if(n.type==="intersection")return Lr(n.left,r)||Lr(n.right,r);if(n.type==="record"||n.type==="map")return Lr(n.keyType,r)||Lr(n.valueType,r);if(n.type==="pipe")return Lr(n.in,r)||Lr(n.out,r);if(n.type==="object"){for(let i in n.shape)if(Lr(n.shape[i],r))return!0;return!1}if(n.type==="union"){for(let i of n.options)if(Lr(i,r))return!0;return!1}if(n.type==="tuple"){for(let i of n.items)if(Lr(i,r))return!0;return!!(n.rest&&Lr(n.rest,r))}return!1}var kT=(t,e={})=>r=>{let n=Qp({...r,processors:e});return Rt(t,n),ef(n,t),tf(n,t)},qu=(t,e,r={})=>n=>{let{libraryOptions:i,target:a}=n??{},s=Qp({...i??{},target:a,io:e,processors:r});return Rt(t,s),ef(s,t),tf(s,t)};var RF={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},TT=(t,e,r,n)=>{let i=r;i.type="string";let{minimum:a,maximum:s,format:o,patterns:c,contentEncoding:u}=t._zod.bag;if(typeof a=="number"&&(i.minLength=a),typeof s=="number"&&(i.maxLength=s),o&&(i.format=RF[o]??o,i.format===""&&delete i.format,o==="time"&&delete i.format),u&&(i.contentEncoding=u),c&&c.size>0){let l=[...c];l.length===1?i.pattern=l[0].source:l.length>1&&(i.allOf=[...l.map(d=>({...e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"?{type:"string"}:{},pattern:d.source}))])}},IT=(t,e,r,n)=>{let i=r,{minimum:a,maximum:s,format:o,multipleOf:c,exclusiveMaximum:u,exclusiveMinimum:l}=t._zod.bag;typeof o=="string"&&o.includes("int")?i.type="integer":i.type="number",typeof l=="number"&&(e.target==="draft-04"||e.target==="openapi-3.0"?(i.minimum=l,i.exclusiveMinimum=!0):i.exclusiveMinimum=l),typeof a=="number"&&(i.minimum=a,typeof l=="number"&&e.target!=="draft-04"&&(l>=a?delete i.minimum:delete i.exclusiveMinimum)),typeof u=="number"&&(e.target==="draft-04"||e.target==="openapi-3.0"?(i.maximum=u,i.exclusiveMaximum=!0):i.exclusiveMaximum=u),typeof s=="number"&&(i.maximum=s,typeof u=="number"&&e.target!=="draft-04"&&(u<=s?delete i.maximum:delete i.exclusiveMaximum)),typeof c=="number"&&(i.multipleOf=c)},OT=(t,e,r,n)=>{r.type="boolean"},RT=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema")},PT=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema")},CT=(t,e,r,n)=>{e.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"},NT=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema")},AT=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema")},jT=(t,e,r,n)=>{r.not={}},MT=(t,e,r,n)=>{},DT=(t,e,r,n)=>{},zT=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema")},UT=(t,e,r,n)=>{let i=t._zod.def,a=uu(i.entries);a.every(s=>typeof s=="number")&&(r.type="number"),a.every(s=>typeof s=="string")&&(r.type="string"),r.enum=a},LT=(t,e,r,n)=>{let i=t._zod.def,a=[];for(let s of i.values)if(s===void 0){if(e.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof s=="bigint"){if(e.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");a.push(Number(s))}else a.push(s);if(a.length!==0)if(a.length===1){let s=a[0];r.type=s===null?"null":typeof s,e.target==="draft-04"||e.target==="openapi-3.0"?r.enum=[s]:r.const=s}else a.every(s=>typeof s=="number")&&(r.type="number"),a.every(s=>typeof s=="string")&&(r.type="string"),a.every(s=>typeof s=="boolean")&&(r.type="boolean"),a.every(s=>s===null)&&(r.type="null"),r.enum=a},qT=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema")},FT=(t,e,r,n)=>{let i=r,a=t._zod.pattern;if(!a)throw new Error("Pattern not found in template literal");i.type="string",i.pattern=a.source},ZT=(t,e,r,n)=>{let i=r,a={type:"string",format:"binary",contentEncoding:"binary"},{minimum:s,maximum:o,mime:c}=t._zod.bag;s!==void 0&&(a.minLength=s),o!==void 0&&(a.maxLength=o),c?c.length===1?(a.contentMediaType=c[0],Object.assign(i,a)):(Object.assign(i,a),i.anyOf=c.map(u=>({contentMediaType:u}))):Object.assign(i,a)},HT=(t,e,r,n)=>{r.type="boolean"},BT=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},VT=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Function types cannot be represented in JSON Schema")},GT=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},WT=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema")},KT=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema")},JT=(t,e,r,n)=>{let i=r,a=t._zod.def,{minimum:s,maximum:o}=t._zod.bag;typeof s=="number"&&(i.minItems=s),typeof o=="number"&&(i.maxItems=o),i.type="array",i.items=Rt(a.element,e,{...n,path:[...n.path,"items"]})},XT=(t,e,r,n)=>{let i=r,a=t._zod.def;i.type="object",i.properties={};let s=a.shape;for(let u in s)i.properties[u]=Rt(s[u],e,{...n,path:[...n.path,"properties",u]});let o=new Set(Object.keys(s)),c=new Set([...o].filter(u=>{let l=a.shape[u]._zod;return e.io==="input"?l.optin===void 0:l.optout===void 0}));c.size>0&&(i.required=Array.from(c)),a.catchall?._zod.def.type==="never"?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=Rt(a.catchall,e,{...n,path:[...n.path,"additionalProperties"]})):e.io==="output"&&(i.additionalProperties=!1)},Y_=(t,e,r,n)=>{let i=t._zod.def,a=i.inclusive===!1,s=i.options.map((o,c)=>Rt(o,e,{...n,path:[...n.path,a?"oneOf":"anyOf",c]}));a?r.oneOf=s:r.anyOf=s},YT=(t,e,r,n)=>{let i=t._zod.def,a=Rt(i.left,e,{...n,path:[...n.path,"allOf",0]}),s=Rt(i.right,e,{...n,path:[...n.path,"allOf",1]}),o=u=>"allOf"in u&&Object.keys(u).length===1,c=[...o(a)?a.allOf:[a],...o(s)?s.allOf:[s]];r.allOf=c},QT=(t,e,r,n)=>{let i=r,a=t._zod.def;i.type="array";let s=e.target==="draft-2020-12"?"prefixItems":"items",o=e.target==="draft-2020-12"||e.target==="openapi-3.0"?"items":"additionalItems",c=a.items.map((p,f)=>Rt(p,e,{...n,path:[...n.path,s,f]})),u=a.rest?Rt(a.rest,e,{...n,path:[...n.path,o,...e.target==="openapi-3.0"?[a.items.length]:[]]}):null;e.target==="draft-2020-12"?(i.prefixItems=c,u&&(i.items=u)):e.target==="openapi-3.0"?(i.items={anyOf:c},u&&i.items.anyOf.push(u),i.minItems=c.length,u||(i.maxItems=c.length)):(i.items=c,u&&(i.additionalItems=u));let{minimum:l,maximum:d}=t._zod.bag;typeof l=="number"&&(i.minItems=l),typeof d=="number"&&(i.maxItems=d)},eI=(t,e,r,n)=>{let i=r,a=t._zod.def;i.type="object";let s=a.keyType,c=s._zod.bag?.patterns;if(a.mode==="loose"&&c&&c.size>0){let l=Rt(a.valueType,e,{...n,path:[...n.path,"patternProperties","*"]});i.patternProperties={};for(let d of c)i.patternProperties[d.source]=l}else(e.target==="draft-07"||e.target==="draft-2020-12")&&(i.propertyNames=Rt(a.keyType,e,{...n,path:[...n.path,"propertyNames"]})),i.additionalProperties=Rt(a.valueType,e,{...n,path:[...n.path,"additionalProperties"]});let u=s._zod.values;if(u){let l=[...u].filter(d=>typeof d=="string"||typeof d=="number");l.length>0&&(i.required=l)}},tI=(t,e,r,n)=>{let i=t._zod.def,a=Rt(i.innerType,e,n),s=e.seen.get(t);e.target==="openapi-3.0"?(s.ref=i.innerType,r.nullable=!0):r.anyOf=[a,{type:"null"}]},rI=(t,e,r,n)=>{let i=t._zod.def;Rt(i.innerType,e,n);let a=e.seen.get(t);a.ref=i.innerType},nI=(t,e,r,n)=>{let i=t._zod.def;Rt(i.innerType,e,n);let a=e.seen.get(t);a.ref=i.innerType,r.default=JSON.parse(JSON.stringify(i.defaultValue))},iI=(t,e,r,n)=>{let i=t._zod.def;Rt(i.innerType,e,n);let a=e.seen.get(t);a.ref=i.innerType,e.io==="input"&&(r._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},aI=(t,e,r,n)=>{let i=t._zod.def;Rt(i.innerType,e,n);let a=e.seen.get(t);a.ref=i.innerType;let s;try{s=i.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}r.default=s},sI=(t,e,r,n)=>{let i=t._zod.def,a=e.io==="input"?i.in._zod.def.type==="transform"?i.out:i.in:i.out;Rt(a,e,n);let s=e.seen.get(t);s.ref=a},oI=(t,e,r,n)=>{let i=t._zod.def;Rt(i.innerType,e,n);let a=e.seen.get(t);a.ref=i.innerType,r.readOnly=!0},cI=(t,e,r,n)=>{let i=t._zod.def;Rt(i.innerType,e,n);let a=e.seen.get(t);a.ref=i.innerType},Q_=(t,e,r,n)=>{let i=t._zod.def;Rt(i.innerType,e,n);let a=e.seen.get(t);a.ref=i.innerType},uI=(t,e,r,n)=>{let i=t._zod.innerType;Rt(i,e,n);let a=e.seen.get(t);a.ref=i};function fo(t){return!!t._zod}function Fn(t,e){return fo(t)?oo(t,e):t.safeParse(e)}function rf(t){if(!t)return;let e;if(fo(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function fI(t){if(fo(t)){let a=t._zod?.def;if(a){if(a.value!==void 0)return a.value;if(Array.isArray(a.values)&&a.values.length>0)return a.values[0]}}let r=t._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=t.value;if(n!==void 0)return n}var Fu={};ln(Fu,{ZodAny:()=>PI,ZodArray:()=>jI,ZodBase64:()=>wb,ZodBase64URL:()=>Eb,ZodBigInt:()=>pf,ZodBigIntFormat:()=>Tb,ZodBoolean:()=>df,ZodCIDRv4:()=>Sb,ZodCIDRv6:()=>xb,ZodCUID:()=>mb,ZodCUID2:()=>hb,ZodCatch:()=>t1,ZodCodec:()=>Ab,ZodCustom:()=>vf,ZodCustomStringFormat:()=>Hu,ZodDate:()=>Ob,ZodDefault:()=>KI,ZodDiscriminatedUnion:()=>DI,ZodE164:()=>$b,ZodEmail:()=>db,ZodEmoji:()=>pb,ZodEnum:()=>Zu,ZodExactOptional:()=>VI,ZodFile:()=>HI,ZodFunction:()=>l1,ZodGUID:()=>af,ZodIPv4:()=>_b,ZodIPv6:()=>bb,ZodIntersection:()=>zI,ZodJWT:()=>kb,ZodKSUID:()=>yb,ZodLazy:()=>o1,ZodLiteral:()=>ZI,ZodMAC:()=>TI,ZodMap:()=>qI,ZodNaN:()=>n1,ZodNanoID:()=>fb,ZodNever:()=>NI,ZodNonOptional:()=>Cb,ZodNull:()=>RI,ZodNullable:()=>WI,ZodNumber:()=>lf,ZodNumberFormat:()=>mo,ZodObject:()=>ff,ZodOptional:()=>Pb,ZodPipe:()=>Nb,ZodPrefault:()=>XI,ZodPromise:()=>u1,ZodReadonly:()=>i1,ZodRecord:()=>gf,ZodSet:()=>FI,ZodString:()=>cf,ZodStringFormat:()=>kt,ZodSuccess:()=>e1,ZodSymbol:()=>II,ZodTemplateLiteral:()=>s1,ZodTransform:()=>BI,ZodTuple:()=>UI,ZodType:()=>Le,ZodULID:()=>gb,ZodURL:()=>uf,ZodUUID:()=>zi,ZodUndefined:()=>OI,ZodUnion:()=>mf,ZodUnknown:()=>CI,ZodVoid:()=>AI,ZodXID:()=>vb,ZodXor:()=>MI,_ZodString:()=>lb,_default:()=>JI,_function:()=>W8,any:()=>R8,array:()=>Ke,base64:()=>f8,base64url:()=>m8,bigint:()=>$8,boolean:()=>rr,catch:()=>r1,check:()=>K8,cidrv4:()=>d8,cidrv6:()=>p8,codec:()=>B8,cuid:()=>n8,cuid2:()=>i8,custom:()=>jb,date:()=>C8,describe:()=>J8,discriminatedUnion:()=>hf,e164:()=>h8,email:()=>GF,emoji:()=>t8,enum:()=>Tr,exactOptional:()=>GI,file:()=>q8,float32:()=>S8,float64:()=>x8,function:()=>W8,guid:()=>WF,hash:()=>b8,hex:()=>_8,hostname:()=>y8,httpUrl:()=>e8,instanceof:()=>Y8,int:()=>ub,int32:()=>w8,int64:()=>k8,intersection:()=>Vu,ipv4:()=>c8,ipv6:()=>l8,json:()=>e5,jwt:()=>g8,keyof:()=>N8,ksuid:()=>o8,lazy:()=>c1,literal:()=>ve,looseObject:()=>kr,looseRecord:()=>D8,mac:()=>u8,map:()=>z8,meta:()=>X8,nan:()=>H8,nanoid:()=>r8,nativeEnum:()=>L8,never:()=>Ib,nonoptional:()=>QI,null:()=>Bu,nullable:()=>sf,nullish:()=>F8,number:()=>ft,object:()=>le,optional:()=>jt,partialRecord:()=>M8,pipe:()=>of,prefault:()=>YI,preprocess:()=>yf,promise:()=>G8,readonly:()=>a1,record:()=>Pt,refine:()=>d1,set:()=>U8,strictObject:()=>A8,string:()=>H,stringFormat:()=>v8,stringbool:()=>Q8,success:()=>Z8,superRefine:()=>p1,symbol:()=>I8,templateLiteral:()=>V8,transform:()=>Rb,tuple:()=>LI,uint32:()=>E8,uint64:()=>T8,ulid:()=>a8,undefined:()=>O8,union:()=>St,unknown:()=>Tt,url:()=>QF,uuid:()=>KF,uuidv4:()=>JF,uuidv6:()=>XF,uuidv7:()=>YF,void:()=>P8,xid:()=>s8,xor:()=>j8});var nf={};ln(nf,{endsWith:()=>ju,gt:()=>Mi,gte:()=>Ur,includes:()=>Nu,length:()=>lo,lowercase:()=>Pu,lt:()=>ji,lte:()=>mn,maxLength:()=>uo,maxSize:()=>Xa,mime:()=>Mu,minLength:()=>pa,minSize:()=>Di,multipleOf:()=>Ja,negative:()=>q_,nonnegative:()=>Z_,nonpositive:()=>F_,normalize:()=>Du,overwrite:()=>ci,positive:()=>L_,property:()=>H_,regex:()=>Ru,size:()=>co,slugify:()=>Yp,startsWith:()=>Au,toLowerCase:()=>Uu,toUpperCase:()=>Lu,trim:()=>zu,uppercase:()=>Cu});var Ya={};ln(Ya,{ZodISODate:()=>nb,ZodISODateTime:()=>tb,ZodISODuration:()=>ob,ZodISOTime:()=>ab,date:()=>ib,datetime:()=>rb,duration:()=>cb,time:()=>sb});var tb=q("ZodISODateTime",(t,e)=>{hy.init(t,e),kt.init(t,e)});function rb(t){return v_(tb,t)}var nb=q("ZodISODate",(t,e)=>{gy.init(t,e),kt.init(t,e)});function ib(t){return y_(nb,t)}var ab=q("ZodISOTime",(t,e)=>{vy.init(t,e),kt.init(t,e)});function sb(t){return __(ab,t)}var ob=q("ZodISODuration",(t,e)=>{yy.init(t,e),kt.init(t,e)});function cb(t){return b_(ob,t)}var mI=(t,e)=>{vp.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>_p(t,r)},flatten:{value:r=>yp(t,r)},addIssue:{value:r=>{t.issues.push(r),t.message=JSON.stringify(t.issues,io,2)}},addIssues:{value:r=>{t.issues.push(...r),t.message=JSON.stringify(t.issues,io,2)}},isEmpty:{get(){return t.issues.length===0}}})},mSe=q("ZodError",mI),hn=q("ZodError",mI,{Parent:Error});var hI=hu(hn),gI=vu(hn),vI=_u(hn),yI=bu(hn),_I=Ok(hn),bI=Rk(hn),SI=Pk(hn),xI=Ck(hn),wI=Nk(hn),EI=Ak(hn),$I=jk(hn),kI=Mk(hn);var Le=q("ZodType",(t,e)=>(Me.init(t,e),Object.assign(t["~standard"],{jsonSchema:{input:qu(t,"input"),output:qu(t,"output")}}),t.toJSONSchema=kT(t,{}),t.def=e,t.type=e.type,Object.defineProperty(t,"_def",{value:e}),t.check=(...r)=>t.clone(ee.mergeDefs(e,{checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),{parent:!0}),t.with=t.check,t.clone=(r,n)=>Dr(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t)),t.parse=(r,n)=>hI(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>vI(t,r,n),t.parseAsync=async(r,n)=>gI(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>yI(t,r,n),t.spa=t.safeParseAsync,t.encode=(r,n)=>_I(t,r,n),t.decode=(r,n)=>bI(t,r,n),t.encodeAsync=async(r,n)=>SI(t,r,n),t.decodeAsync=async(r,n)=>xI(t,r,n),t.safeEncode=(r,n)=>wI(t,r,n),t.safeDecode=(r,n)=>EI(t,r,n),t.safeEncodeAsync=async(r,n)=>$I(t,r,n),t.safeDecodeAsync=async(r,n)=>kI(t,r,n),t.refine=(r,n)=>t.check(d1(r,n)),t.superRefine=r=>t.check(p1(r)),t.overwrite=r=>t.check(ci(r)),t.optional=()=>jt(t),t.exactOptional=()=>GI(t),t.nullable=()=>sf(t),t.nullish=()=>jt(sf(t)),t.nonoptional=r=>QI(t,r),t.array=()=>Ke(t),t.or=r=>St([t,r]),t.and=r=>Vu(t,r),t.transform=r=>of(t,Rb(r)),t.default=r=>JI(t,r),t.prefault=r=>YI(t,r),t.catch=r=>r1(t,r),t.pipe=r=>of(t,r),t.readonly=()=>a1(t),t.describe=r=>{let n=t.clone();return zr.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return zr.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return zr.get(t);let n=t.clone();return zr.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t.apply=r=>r(t),t)),lb=q("_ZodString",(t,e)=>{Ka.init(t,e),Le.init(t,e),t._zod.processJSONSchema=(n,i,a)=>TT(t,n,i,a);let r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,t.regex=(...n)=>t.check(Ru(...n)),t.includes=(...n)=>t.check(Nu(...n)),t.startsWith=(...n)=>t.check(Au(...n)),t.endsWith=(...n)=>t.check(ju(...n)),t.min=(...n)=>t.check(pa(...n)),t.max=(...n)=>t.check(uo(...n)),t.length=(...n)=>t.check(lo(...n)),t.nonempty=(...n)=>t.check(pa(1,...n)),t.lowercase=n=>t.check(Pu(n)),t.uppercase=n=>t.check(Cu(n)),t.trim=()=>t.check(zu()),t.normalize=(...n)=>t.check(Du(...n)),t.toLowerCase=()=>t.check(Uu()),t.toUpperCase=()=>t.check(Lu()),t.slugify=()=>t.check(Yp())}),cf=q("ZodString",(t,e)=>{Ka.init(t,e),lb.init(t,e),t.email=r=>t.check(Cp(db,r)),t.url=r=>t.check(Ou(uf,r)),t.jwt=r=>t.check(Xp(kb,r)),t.emoji=r=>t.check(Dp(pb,r)),t.guid=r=>t.check(Iu(af,r)),t.uuid=r=>t.check(Np(zi,r)),t.uuidv4=r=>t.check(Ap(zi,r)),t.uuidv6=r=>t.check(jp(zi,r)),t.uuidv7=r=>t.check(Mp(zi,r)),t.nanoid=r=>t.check(zp(fb,r)),t.guid=r=>t.check(Iu(af,r)),t.cuid=r=>t.check(Up(mb,r)),t.cuid2=r=>t.check(Lp(hb,r)),t.ulid=r=>t.check(qp(gb,r)),t.base64=r=>t.check(Wp(wb,r)),t.base64url=r=>t.check(Kp(Eb,r)),t.xid=r=>t.check(Fp(vb,r)),t.ksuid=r=>t.check(Zp(yb,r)),t.ipv4=r=>t.check(Hp(_b,r)),t.ipv6=r=>t.check(Bp(bb,r)),t.cidrv4=r=>t.check(Vp(Sb,r)),t.cidrv6=r=>t.check(Gp(xb,r)),t.e164=r=>t.check(Jp($b,r)),t.datetime=r=>t.check(rb(r)),t.date=r=>t.check(ib(r)),t.time=r=>t.check(sb(r)),t.duration=r=>t.check(cb(r))});function H(t){return h_(cf,t)}var kt=q("ZodStringFormat",(t,e)=>{bt.init(t,e),lb.init(t,e)}),db=q("ZodEmail",(t,e)=>{sy.init(t,e),kt.init(t,e)});function GF(t){return Cp(db,t)}var af=q("ZodGUID",(t,e)=>{iy.init(t,e),kt.init(t,e)});function WF(t){return Iu(af,t)}var zi=q("ZodUUID",(t,e)=>{ay.init(t,e),kt.init(t,e)});function KF(t){return Np(zi,t)}function JF(t){return Ap(zi,t)}function XF(t){return jp(zi,t)}function YF(t){return Mp(zi,t)}var uf=q("ZodURL",(t,e)=>{oy.init(t,e),kt.init(t,e)});function QF(t){return Ou(uf,t)}function e8(t){return Ou(uf,{protocol:/^https?$/,hostname:Sn.domain,...ee.normalizeParams(t)})}var pb=q("ZodEmoji",(t,e)=>{cy.init(t,e),kt.init(t,e)});function t8(t){return Dp(pb,t)}var fb=q("ZodNanoID",(t,e)=>{uy.init(t,e),kt.init(t,e)});function r8(t){return zp(fb,t)}var mb=q("ZodCUID",(t,e)=>{ly.init(t,e),kt.init(t,e)});function n8(t){return Up(mb,t)}var hb=q("ZodCUID2",(t,e)=>{dy.init(t,e),kt.init(t,e)});function i8(t){return Lp(hb,t)}var gb=q("ZodULID",(t,e)=>{py.init(t,e),kt.init(t,e)});function a8(t){return qp(gb,t)}var vb=q("ZodXID",(t,e)=>{fy.init(t,e),kt.init(t,e)});function s8(t){return Fp(vb,t)}var yb=q("ZodKSUID",(t,e)=>{my.init(t,e),kt.init(t,e)});function o8(t){return Zp(yb,t)}var _b=q("ZodIPv4",(t,e)=>{_y.init(t,e),kt.init(t,e)});function c8(t){return Hp(_b,t)}var TI=q("ZodMAC",(t,e)=>{Sy.init(t,e),kt.init(t,e)});function u8(t){return g_(TI,t)}var bb=q("ZodIPv6",(t,e)=>{by.init(t,e),kt.init(t,e)});function l8(t){return Bp(bb,t)}var Sb=q("ZodCIDRv4",(t,e)=>{xy.init(t,e),kt.init(t,e)});function d8(t){return Vp(Sb,t)}var xb=q("ZodCIDRv6",(t,e)=>{wy.init(t,e),kt.init(t,e)});function p8(t){return Gp(xb,t)}var wb=q("ZodBase64",(t,e)=>{Ey.init(t,e),kt.init(t,e)});function f8(t){return Wp(wb,t)}var Eb=q("ZodBase64URL",(t,e)=>{$y.init(t,e),kt.init(t,e)});function m8(t){return Kp(Eb,t)}var $b=q("ZodE164",(t,e)=>{ky.init(t,e),kt.init(t,e)});function h8(t){return Jp($b,t)}var kb=q("ZodJWT",(t,e)=>{Ty.init(t,e),kt.init(t,e)});function g8(t){return Xp(kb,t)}var Hu=q("ZodCustomStringFormat",(t,e)=>{Iy.init(t,e),kt.init(t,e)});function v8(t,e,r={}){return po(Hu,t,e,r)}function y8(t){return po(Hu,"hostname",Sn.hostname,t)}function _8(t){return po(Hu,"hex",Sn.hex,t)}function b8(t,e){let r=e?.enc??"hex",n=`${t}_${r}`,i=Sn[n];if(!i)throw new Error(`Unrecognized hash format: ${n}`);return po(Hu,n,i,e)}var lf=q("ZodNumber",(t,e)=>{Ip.init(t,e),Le.init(t,e),t._zod.processJSONSchema=(n,i,a)=>IT(t,n,i,a),t.gt=(n,i)=>t.check(Mi(n,i)),t.gte=(n,i)=>t.check(Ur(n,i)),t.min=(n,i)=>t.check(Ur(n,i)),t.lt=(n,i)=>t.check(ji(n,i)),t.lte=(n,i)=>t.check(mn(n,i)),t.max=(n,i)=>t.check(mn(n,i)),t.int=n=>t.check(ub(n)),t.safe=n=>t.check(ub(n)),t.positive=n=>t.check(Mi(0,n)),t.nonnegative=n=>t.check(Ur(0,n)),t.negative=n=>t.check(ji(0,n)),t.nonpositive=n=>t.check(mn(0,n)),t.multipleOf=(n,i)=>t.check(Ja(n,i)),t.step=(n,i)=>t.check(Ja(n,i)),t.finite=()=>t;let r=t._zod.bag;t.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),t.isFinite=!0,t.format=r.format??null});function ft(t){return S_(lf,t)}var mo=q("ZodNumberFormat",(t,e)=>{Oy.init(t,e),lf.init(t,e)});function ub(t){return x_(mo,t)}function S8(t){return w_(mo,t)}function x8(t){return E_(mo,t)}function w8(t){return $_(mo,t)}function E8(t){return k_(mo,t)}var df=q("ZodBoolean",(t,e)=>{$u.init(t,e),Le.init(t,e),t._zod.processJSONSchema=(r,n,i)=>OT(t,r,n,i)});function rr(t){return T_(df,t)}var pf=q("ZodBigInt",(t,e)=>{Op.init(t,e),Le.init(t,e),t._zod.processJSONSchema=(n,i,a)=>RT(t,n,i,a),t.gte=(n,i)=>t.check(Ur(n,i)),t.min=(n,i)=>t.check(Ur(n,i)),t.gt=(n,i)=>t.check(Mi(n,i)),t.gte=(n,i)=>t.check(Ur(n,i)),t.min=(n,i)=>t.check(Ur(n,i)),t.lt=(n,i)=>t.check(ji(n,i)),t.lte=(n,i)=>t.check(mn(n,i)),t.max=(n,i)=>t.check(mn(n,i)),t.positive=n=>t.check(Mi(BigInt(0),n)),t.negative=n=>t.check(ji(BigInt(0),n)),t.nonpositive=n=>t.check(mn(BigInt(0),n)),t.nonnegative=n=>t.check(Ur(BigInt(0),n)),t.multipleOf=(n,i)=>t.check(Ja(n,i));let r=t._zod.bag;t.minValue=r.minimum??null,t.maxValue=r.maximum??null,t.format=r.format??null});function $8(t){return I_(pf,t)}var Tb=q("ZodBigIntFormat",(t,e)=>{Ry.init(t,e),pf.init(t,e)});function k8(t){return O_(Tb,t)}function T8(t){return R_(Tb,t)}var II=q("ZodSymbol",(t,e)=>{Py.init(t,e),Le.init(t,e),t._zod.processJSONSchema=(r,n,i)=>PT(t,r,n,i)});function I8(t){return P_(II,t)}var OI=q("ZodUndefined",(t,e)=>{Cy.init(t,e),Le.init(t,e),t._zod.processJSONSchema=(r,n,i)=>NT(t,r,n,i)});function O8(t){return C_(OI,t)}var RI=q("ZodNull",(t,e)=>{Ny.init(t,e),Le.init(t,e),t._zod.processJSONSchema=(r,n,i)=>CT(t,r,n,i)});function Bu(t){return N_(RI,t)}var PI=q("ZodAny",(t,e)=>{Ay.init(t,e),Le.init(t,e),t._zod.processJSONSchema=(r,n,i)=>MT(t,r,n,i)});function R8(){return A_(PI)}var CI=q("ZodUnknown",(t,e)=>{jy.init(t,e),Le.init(t,e),t._zod.processJSONSchema=(r,n,i)=>DT(t,r,n,i)});function Tt(){return j_(CI)}var NI=q("ZodNever",(t,e)=>{My.init(t,e),Le.init(t,e),t._zod.processJSONSchema=(r,n,i)=>jT(t,r,n,i)});function Ib(t){return M_(NI,t)}var AI=q("ZodVoid",(t,e)=>{Dy.init(t,e),Le.init(t,e),t._zod.processJSONSchema=(r,n,i)=>AT(t,r,n,i)});function P8(t){return D_(AI,t)}var Ob=q("ZodDate",(t,e)=>{zy.init(t,e),Le.init(t,e),t._zod.processJSONSchema=(n,i,a)=>zT(t,n,i,a),t.min=(n,i)=>t.check(Ur(n,i)),t.max=(n,i)=>t.check(mn(n,i));let r=t._zod.bag;t.minDate=r.minimum?new Date(r.minimum):null,t.maxDate=r.maximum?new Date(r.maximum):null});function C8(t){return z_(Ob,t)}var jI=q("ZodArray",(t,e)=>{Uy.init(t,e),Le.init(t,e),t._zod.processJSONSchema=(r,n,i)=>JT(t,r,n,i),t.element=e.element,t.min=(r,n)=>t.check(pa(r,n)),t.nonempty=r=>t.check(pa(1,r)),t.max=(r,n)=>t.check(uo(r,n)),t.length=(r,n)=>t.check(lo(r,n)),t.unwrap=()=>t.element});function Ke(t,e){return $T(jI,t,e)}function N8(t){let e=t._zod.def.shape;return Tr(Object.keys(e))}var ff=q("ZodObject",(t,e)=>{wT.init(t,e),Le.init(t,e),t._zod.processJSONSchema=(r,n,i)=>XT(t,r,n,i),ee.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>Tr(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:Tt()}),t.loose=()=>t.clone({...t._zod.def,catchall:Tt()}),t.strict=()=>t.clone({...t._zod.def,catchall:Ib()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>ee.extend(t,r),t.safeExtend=r=>ee.safeExtend(t,r),t.merge=r=>ee.merge(t,r),t.pick=r=>ee.pick(t,r),t.omit=r=>ee.omit(t,r),t.partial=(...r)=>ee.partial(Pb,t,r[0]),t.required=(...r)=>ee.required(Cb,t,r[0])});function le(t,e){let r={type:"object",shape:t??{},...ee.normalizeParams(e)};return new ff(r)}function A8(t,e){return new ff({type:"object",shape:t,catchall:Ib(),...ee.normalizeParams(e)})}function kr(t,e){return new ff({type:"object",shape:t,catchall:Tt(),...ee.normalizeParams(e)})}var mf=q("ZodUnion",(t,e)=>{ku.init(t,e),Le.init(t,e),t._zod.processJSONSchema=(r,n,i)=>Y_(t,r,n,i),t.options=e.options});function St(t,e){return new mf({type:"union",options:t,...ee.normalizeParams(e)})}var MI=q("ZodXor",(t,e)=>{mf.init(t,e),Ly.init(t,e),t._zod.processJSONSchema=(r,n,i)=>Y_(t,r,n,i),t.options=e.options});function j8(t,e){return new MI({type:"union",options:t,inclusive:!1,...ee.normalizeParams(e)})}var DI=q("ZodDiscriminatedUnion",(t,e)=>{mf.init(t,e),qy.init(t,e)});function hf(t,e,r){return new DI({type:"union",options:e,discriminator:t,...ee.normalizeParams(r)})}var zI=q("ZodIntersection",(t,e)=>{Fy.init(t,e),Le.init(t,e),t._zod.processJSONSchema=(r,n,i)=>YT(t,r,n,i)});function Vu(t,e){return new zI({type:"intersection",left:t,right:e})}var UI=q("ZodTuple",(t,e)=>{Rp.init(t,e),Le.init(t,e),t._zod.processJSONSchema=(r,n,i)=>QT(t,r,n,i),t.rest=r=>t.clone({...t._zod.def,rest:r})});function LI(t,e,r){let n=e instanceof Me,i=n?r:e,a=n?e:null;return new UI({type:"tuple",items:t,rest:a,...ee.normalizeParams(i)})}var gf=q("ZodRecord",(t,e)=>{Zy.init(t,e),Le.init(t,e),t._zod.processJSONSchema=(r,n,i)=>eI(t,r,n,i),t.keyType=e.keyType,t.valueType=e.valueType});function Pt(t,e,r){return new gf({type:"record",keyType:t,valueType:e,...ee.normalizeParams(r)})}function M8(t,e,r){let n=Dr(t);return n._zod.values=void 0,new gf({type:"record",keyType:n,valueType:e,...ee.normalizeParams(r)})}function D8(t,e,r){return new gf({type:"record",keyType:t,valueType:e,mode:"loose",...ee.normalizeParams(r)})}var qI=q("ZodMap",(t,e)=>{Hy.init(t,e),Le.init(t,e),t._zod.processJSONSchema=(r,n,i)=>WT(t,r,n,i),t.keyType=e.keyType,t.valueType=e.valueType,t.min=(...r)=>t.check(Di(...r)),t.nonempty=r=>t.check(Di(1,r)),t.max=(...r)=>t.check(Xa(...r)),t.size=(...r)=>t.check(co(...r))});function z8(t,e,r){return new qI({type:"map",keyType:t,valueType:e,...ee.normalizeParams(r)})}var FI=q("ZodSet",(t,e)=>{By.init(t,e),Le.init(t,e),t._zod.processJSONSchema=(r,n,i)=>KT(t,r,n,i),t.min=(...r)=>t.check(Di(...r)),t.nonempty=r=>t.check(Di(1,r)),t.max=(...r)=>t.check(Xa(...r)),t.size=(...r)=>t.check(co(...r))});function U8(t,e){return new FI({type:"set",valueType:t,...ee.normalizeParams(e)})}var Zu=q("ZodEnum",(t,e)=>{Vy.init(t,e),Le.init(t,e),t._zod.processJSONSchema=(n,i,a)=>UT(t,n,i,a),t.enum=e.entries,t.options=Object.values(e.entries);let r=new Set(Object.keys(e.entries));t.extract=(n,i)=>{let a={};for(let s of n)if(r.has(s))a[s]=e.entries[s];else throw new Error(`Key ${s} not found in enum`);return new Zu({...e,checks:[],...ee.normalizeParams(i),entries:a})},t.exclude=(n,i)=>{let a={...e.entries};for(let s of n)if(r.has(s))delete a[s];else throw new Error(`Key ${s} not found in enum`);return new Zu({...e,checks:[],...ee.normalizeParams(i),entries:a})}});function Tr(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new Zu({type:"enum",entries:r,...ee.normalizeParams(e)})}function L8(t,e){return new Zu({type:"enum",entries:t,...ee.normalizeParams(e)})}var ZI=q("ZodLiteral",(t,e)=>{Gy.init(t,e),Le.init(t,e),t._zod.processJSONSchema=(r,n,i)=>LT(t,r,n,i),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function ve(t,e){return new ZI({type:"literal",values:Array.isArray(t)?t:[t],...ee.normalizeParams(e)})}var HI=q("ZodFile",(t,e)=>{Wy.init(t,e),Le.init(t,e),t._zod.processJSONSchema=(r,n,i)=>ZT(t,r,n,i),t.min=(r,n)=>t.check(Di(r,n)),t.max=(r,n)=>t.check(Xa(r,n)),t.mime=(r,n)=>t.check(Mu(Array.isArray(r)?r:[r],n))});function q8(t){return B_(HI,t)}var BI=q("ZodTransform",(t,e)=>{Ky.init(t,e),Le.init(t,e),t._zod.processJSONSchema=(r,n,i)=>GT(t,r,n,i),t._zod.parse=(r,n)=>{if(n.direction==="backward")throw new Va(t.constructor.name);r.addIssue=a=>{if(typeof a=="string")r.issues.push(ee.issue(a,r.value,e));else{let s=a;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=r.value),s.inst??(s.inst=t),r.issues.push(ee.issue(s))}};let i=e.transform(r.value,r);return i instanceof Promise?i.then(a=>(r.value=a,r)):(r.value=i,r)}});function Rb(t){return new BI({type:"transform",transform:t})}var Pb=q("ZodOptional",(t,e)=>{Pp.init(t,e),Le.init(t,e),t._zod.processJSONSchema=(r,n,i)=>Q_(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function jt(t){return new Pb({type:"optional",innerType:t})}var VI=q("ZodExactOptional",(t,e)=>{Jy.init(t,e),Le.init(t,e),t._zod.processJSONSchema=(r,n,i)=>Q_(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function GI(t){return new VI({type:"optional",innerType:t})}var WI=q("ZodNullable",(t,e)=>{Xy.init(t,e),Le.init(t,e),t._zod.processJSONSchema=(r,n,i)=>tI(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function sf(t){return new WI({type:"nullable",innerType:t})}function F8(t){return jt(sf(t))}var KI=q("ZodDefault",(t,e)=>{Yy.init(t,e),Le.init(t,e),t._zod.processJSONSchema=(r,n,i)=>nI(t,r,n,i),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function JI(t,e){return new KI({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():ee.shallowClone(e)}})}var XI=q("ZodPrefault",(t,e)=>{Qy.init(t,e),Le.init(t,e),t._zod.processJSONSchema=(r,n,i)=>iI(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function YI(t,e){return new XI({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():ee.shallowClone(e)}})}var Cb=q("ZodNonOptional",(t,e)=>{e_.init(t,e),Le.init(t,e),t._zod.processJSONSchema=(r,n,i)=>rI(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function QI(t,e){return new Cb({type:"nonoptional",innerType:t,...ee.normalizeParams(e)})}var e1=q("ZodSuccess",(t,e)=>{t_.init(t,e),Le.init(t,e),t._zod.processJSONSchema=(r,n,i)=>HT(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function Z8(t){return new e1({type:"success",innerType:t})}var t1=q("ZodCatch",(t,e)=>{r_.init(t,e),Le.init(t,e),t._zod.processJSONSchema=(r,n,i)=>aI(t,r,n,i),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function r1(t,e){return new t1({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var n1=q("ZodNaN",(t,e)=>{n_.init(t,e),Le.init(t,e),t._zod.processJSONSchema=(r,n,i)=>qT(t,r,n,i)});function H8(t){return U_(n1,t)}var Nb=q("ZodPipe",(t,e)=>{i_.init(t,e),Le.init(t,e),t._zod.processJSONSchema=(r,n,i)=>sI(t,r,n,i),t.in=e.in,t.out=e.out});function of(t,e){return new Nb({type:"pipe",in:t,out:e})}var Ab=q("ZodCodec",(t,e)=>{Nb.init(t,e),Tu.init(t,e)});function B8(t,e,r){return new Ab({type:"pipe",in:t,out:e,transform:r.decode,reverseTransform:r.encode})}var i1=q("ZodReadonly",(t,e)=>{a_.init(t,e),Le.init(t,e),t._zod.processJSONSchema=(r,n,i)=>oI(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function a1(t){return new i1({type:"readonly",innerType:t})}var s1=q("ZodTemplateLiteral",(t,e)=>{s_.init(t,e),Le.init(t,e),t._zod.processJSONSchema=(r,n,i)=>FT(t,r,n,i)});function V8(t,e){return new s1({type:"template_literal",parts:t,...ee.normalizeParams(e)})}var o1=q("ZodLazy",(t,e)=>{u_.init(t,e),Le.init(t,e),t._zod.processJSONSchema=(r,n,i)=>uI(t,r,n,i),t.unwrap=()=>t._zod.def.getter()});function c1(t){return new o1({type:"lazy",getter:t})}var u1=q("ZodPromise",(t,e)=>{c_.init(t,e),Le.init(t,e),t._zod.processJSONSchema=(r,n,i)=>cI(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function G8(t){return new u1({type:"promise",innerType:t})}var l1=q("ZodFunction",(t,e)=>{o_.init(t,e),Le.init(t,e),t._zod.processJSONSchema=(r,n,i)=>VT(t,r,n,i)});function W8(t){return new l1({type:"function",input:Array.isArray(t?.input)?LI(t?.input):t?.input??Ke(Tt()),output:t?.output??Tt()})}var vf=q("ZodCustom",(t,e)=>{l_.init(t,e),Le.init(t,e),t._zod.processJSONSchema=(r,n,i)=>BT(t,r,n,i)});function K8(t){let e=new $t({check:"custom"});return e._zod.check=t,e}function jb(t,e){return V_(vf,t??(()=>!0),e)}function d1(t,e={}){return G_(vf,t,e)}function p1(t){return W_(t)}var J8=K_,X8=J_;function Y8(t,e={}){let r=new vf({type:"custom",check:"custom",fn:n=>n instanceof t,abort:!0,...ee.normalizeParams(e)});return r._zod.bag.Class=t,r._zod.check=n=>{n.value instanceof t||n.issues.push({code:"invalid_type",expected:t.name,input:n.value,inst:r,path:[...r._zod.def.path??[]]})},r}var Q8=(...t)=>X_({Codec:Ab,Boolean:df,String:cf},...t);function e5(t){let e=c1(()=>St([H(t),ft(),rr(),Bu(),Ke(e),Pt(H(),e)]));return e}function yf(t,e){return of(Rb(t),e)}var f1;f1||(f1={});var xSe={...Fu,...nf,iso:Ya};ir(d_());var Db="2025-11-25";var m1=[Db,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],fa="io.modelcontextprotocol/related-task",bf="2.0",gr=jb(t=>t!==null&&(typeof t=="object"||typeof t=="function")),h1=St([H(),ft().int()]),g1=H(),qSe=kr({ttl:St([ft(),Bu()]).optional(),pollInterval:ft().optional()}),i5=le({ttl:ft().optional()}),a5=le({taskId:H()}),zb=kr({progressToken:h1.optional(),[fa]:a5.optional()}),gn=le({_meta:zb.optional()}),Gu=gn.extend({task:i5.optional()}),v1=t=>Gu.safeParse(t).success,vr=le({method:H(),params:gn.loose().optional()}),xn=le({_meta:zb.optional()}),wn=le({method:H(),params:xn.loose().optional()}),yr=kr({_meta:zb.optional()}),Sf=St([H(),ft().int()]),y1=le({jsonrpc:ve(bf),id:Sf,...vr.shape}).strict(),Ub=t=>y1.safeParse(t).success,_1=le({jsonrpc:ve(bf),...wn.shape}).strict(),b1=t=>_1.safeParse(t).success,Lb=le({jsonrpc:ve(bf),id:Sf,result:yr}).strict(),Wu=t=>Lb.safeParse(t).success;var Ce;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(Ce||(Ce={}));var qb=le({jsonrpc:ve(bf),id:Sf.optional(),error:le({code:ft().int(),message:H(),data:Tt().optional()})}).strict();var S1=t=>qb.safeParse(t).success;var x1=St([y1,_1,Lb,qb]),FSe=St([Lb,qb]),Qa=yr.strict(),s5=xn.extend({requestId:Sf.optional(),reason:H().optional()}),xf=wn.extend({method:ve("notifications/cancelled"),params:s5}),o5=le({src:H(),mimeType:H().optional(),sizes:Ke(H()).optional(),theme:Tr(["light","dark"]).optional()}),Ku=le({icons:Ke(o5).optional()}),ho=le({name:H(),title:H().optional()}),w1=ho.extend({...ho.shape,...Ku.shape,version:H(),websiteUrl:H().optional(),description:H().optional()}),c5=Vu(le({applyDefaults:rr().optional()}),Pt(H(),Tt())),u5=yf(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,Vu(le({form:c5.optional(),url:gr.optional()}),Pt(H(),Tt()).optional())),l5=kr({list:gr.optional(),cancel:gr.optional(),requests:kr({sampling:kr({createMessage:gr.optional()}).optional(),elicitation:kr({create:gr.optional()}).optional()}).optional()}),d5=kr({list:gr.optional(),cancel:gr.optional(),requests:kr({tools:kr({call:gr.optional()}).optional()}).optional()}),p5=le({experimental:Pt(H(),gr).optional(),sampling:le({context:gr.optional(),tools:gr.optional()}).optional(),elicitation:u5.optional(),roots:le({listChanged:rr().optional()}).optional(),tasks:l5.optional()}),f5=gn.extend({protocolVersion:H(),capabilities:p5,clientInfo:w1}),m5=vr.extend({method:ve("initialize"),params:f5});var h5=le({experimental:Pt(H(),gr).optional(),logging:gr.optional(),completions:gr.optional(),prompts:le({listChanged:rr().optional()}).optional(),resources:le({subscribe:rr().optional(),listChanged:rr().optional()}).optional(),tools:le({listChanged:rr().optional()}).optional(),tasks:d5.optional()}),Fb=yr.extend({protocolVersion:H(),capabilities:h5,serverInfo:w1,instructions:H().optional()}),g5=wn.extend({method:ve("notifications/initialized"),params:xn.optional()});var wf=vr.extend({method:ve("ping"),params:gn.optional()}),v5=le({progress:ft(),total:jt(ft()),message:jt(H())}),y5=le({...xn.shape,...v5.shape,progressToken:h1}),Ef=wn.extend({method:ve("notifications/progress"),params:y5}),_5=gn.extend({cursor:g1.optional()}),Ju=vr.extend({params:_5.optional()}),Xu=yr.extend({nextCursor:g1.optional()}),b5=Tr(["working","input_required","completed","failed","cancelled"]),Yu=le({taskId:H(),status:b5,ttl:St([ft(),Bu()]),createdAt:H(),lastUpdatedAt:H(),pollInterval:jt(ft()),statusMessage:jt(H())}),es=yr.extend({task:Yu}),S5=xn.merge(Yu),Qu=wn.extend({method:ve("notifications/tasks/status"),params:S5}),$f=vr.extend({method:ve("tasks/get"),params:gn.extend({taskId:H()})}),kf=yr.merge(Yu),Tf=vr.extend({method:ve("tasks/result"),params:gn.extend({taskId:H()})}),ZSe=yr.loose(),If=Ju.extend({method:ve("tasks/list")}),Of=Xu.extend({tasks:Ke(Yu)}),Rf=vr.extend({method:ve("tasks/cancel"),params:gn.extend({taskId:H()})}),E1=yr.merge(Yu),$1=le({uri:H(),mimeType:jt(H()),_meta:Pt(H(),Tt()).optional()}),k1=$1.extend({text:H()}),Zb=H().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),T1=$1.extend({blob:Zb}),el=Tr(["user","assistant"]),go=le({audience:Ke(el).optional(),priority:ft().min(0).max(1).optional(),lastModified:Ya.datetime({offset:!0}).optional()}),I1=le({...ho.shape,...Ku.shape,uri:H(),description:jt(H()),mimeType:jt(H()),annotations:go.optional(),_meta:jt(kr({}))}),x5=le({...ho.shape,...Ku.shape,uriTemplate:H(),description:jt(H()),mimeType:jt(H()),annotations:go.optional(),_meta:jt(kr({}))}),w5=Ju.extend({method:ve("resources/list")}),Hb=Xu.extend({resources:Ke(I1)}),E5=Ju.extend({method:ve("resources/templates/list")}),Bb=Xu.extend({resourceTemplates:Ke(x5)}),Vb=gn.extend({uri:H()}),$5=Vb,k5=vr.extend({method:ve("resources/read"),params:$5}),Gb=yr.extend({contents:Ke(St([k1,T1]))}),Wb=wn.extend({method:ve("notifications/resources/list_changed"),params:xn.optional()}),T5=Vb,I5=vr.extend({method:ve("resources/subscribe"),params:T5}),O5=Vb,R5=vr.extend({method:ve("resources/unsubscribe"),params:O5}),P5=xn.extend({uri:H()}),C5=wn.extend({method:ve("notifications/resources/updated"),params:P5}),N5=le({name:H(),description:jt(H()),required:jt(rr())}),A5=le({...ho.shape,...Ku.shape,description:jt(H()),arguments:jt(Ke(N5)),_meta:jt(kr({}))}),j5=Ju.extend({method:ve("prompts/list")}),Kb=Xu.extend({prompts:Ke(A5)}),M5=gn.extend({name:H(),arguments:Pt(H(),H()).optional()}),D5=vr.extend({method:ve("prompts/get"),params:M5}),Jb=le({type:ve("text"),text:H(),annotations:go.optional(),_meta:Pt(H(),Tt()).optional()}),Xb=le({type:ve("image"),data:Zb,mimeType:H(),annotations:go.optional(),_meta:Pt(H(),Tt()).optional()}),Yb=le({type:ve("audio"),data:Zb,mimeType:H(),annotations:go.optional(),_meta:Pt(H(),Tt()).optional()}),z5=le({type:ve("tool_use"),name:H(),id:H(),input:Pt(H(),Tt()),_meta:Pt(H(),Tt()).optional()}),U5=le({type:ve("resource"),resource:St([k1,T1]),annotations:go.optional(),_meta:Pt(H(),Tt()).optional()}),L5=I1.extend({type:ve("resource_link")}),Qb=St([Jb,Xb,Yb,L5,U5]),q5=le({role:el,content:Qb}),eS=yr.extend({description:H().optional(),messages:Ke(q5)}),tS=wn.extend({method:ve("notifications/prompts/list_changed"),params:xn.optional()}),F5=le({title:H().optional(),readOnlyHint:rr().optional(),destructiveHint:rr().optional(),idempotentHint:rr().optional(),openWorldHint:rr().optional()}),Z5=le({taskSupport:Tr(["required","optional","forbidden"]).optional()}),O1=le({...ho.shape,...Ku.shape,description:H().optional(),inputSchema:le({type:ve("object"),properties:Pt(H(),gr).optional(),required:Ke(H()).optional()}).catchall(Tt()),outputSchema:le({type:ve("object"),properties:Pt(H(),gr).optional(),required:Ke(H()).optional()}).catchall(Tt()).optional(),annotations:F5.optional(),execution:Z5.optional(),_meta:Pt(H(),Tt()).optional()}),H5=Ju.extend({method:ve("tools/list")}),rS=Xu.extend({tools:Ke(O1)}),vo=yr.extend({content:Ke(Qb).default([]),structuredContent:Pt(H(),Tt()).optional(),isError:rr().optional()}),HSe=vo.or(yr.extend({toolResult:Tt()})),B5=Gu.extend({name:H(),arguments:Pt(H(),Tt()).optional()}),V5=vr.extend({method:ve("tools/call"),params:B5}),nS=wn.extend({method:ve("notifications/tools/list_changed"),params:xn.optional()}),R1=le({autoRefresh:rr().default(!0),debounceMs:ft().int().nonnegative().default(300)}),P1=Tr(["debug","info","notice","warning","error","critical","alert","emergency"]),G5=gn.extend({level:P1}),W5=vr.extend({method:ve("logging/setLevel"),params:G5}),K5=xn.extend({level:P1,logger:H().optional(),data:Tt()}),J5=wn.extend({method:ve("notifications/message"),params:K5}),X5=le({name:H().optional()}),Y5=le({hints:Ke(X5).optional(),costPriority:ft().min(0).max(1).optional(),speedPriority:ft().min(0).max(1).optional(),intelligencePriority:ft().min(0).max(1).optional()}),Q5=le({mode:Tr(["auto","required","none"]).optional()}),e3=le({type:ve("tool_result"),toolUseId:H().describe("The unique identifier for the corresponding tool call."),content:Ke(Qb).default([]),structuredContent:le({}).loose().optional(),isError:rr().optional(),_meta:Pt(H(),Tt()).optional()}),t3=hf("type",[Jb,Xb,Yb]),_f=hf("type",[Jb,Xb,Yb,z5,e3]),r3=le({role:el,content:St([_f,Ke(_f)]),_meta:Pt(H(),Tt()).optional()}),n3=Gu.extend({messages:Ke(r3),modelPreferences:Y5.optional(),systemPrompt:H().optional(),includeContext:Tr(["none","thisServer","allServers"]).optional(),temperature:ft().optional(),maxTokens:ft().int(),stopSequences:Ke(H()).optional(),metadata:gr.optional(),tools:Ke(O1).optional(),toolChoice:Q5.optional()}),iS=vr.extend({method:ve("sampling/createMessage"),params:n3}),aS=yr.extend({model:H(),stopReason:jt(Tr(["endTurn","stopSequence","maxTokens"]).or(H())),role:el,content:t3}),i3=yr.extend({model:H(),stopReason:jt(Tr(["endTurn","stopSequence","maxTokens","toolUse"]).or(H())),role:el,content:St([_f,Ke(_f)])}),a3=le({type:ve("boolean"),title:H().optional(),description:H().optional(),default:rr().optional()}),s3=le({type:ve("string"),title:H().optional(),description:H().optional(),minLength:ft().optional(),maxLength:ft().optional(),format:Tr(["email","uri","date","date-time"]).optional(),default:H().optional()}),o3=le({type:Tr(["number","integer"]),title:H().optional(),description:H().optional(),minimum:ft().optional(),maximum:ft().optional(),default:ft().optional()}),c3=le({type:ve("string"),title:H().optional(),description:H().optional(),enum:Ke(H()),default:H().optional()}),u3=le({type:ve("string"),title:H().optional(),description:H().optional(),oneOf:Ke(le({const:H(),title:H()})),default:H().optional()}),l3=le({type:ve("string"),title:H().optional(),description:H().optional(),enum:Ke(H()),enumNames:Ke(H()).optional(),default:H().optional()}),d3=St([c3,u3]),p3=le({type:ve("array"),title:H().optional(),description:H().optional(),minItems:ft().optional(),maxItems:ft().optional(),items:le({type:ve("string"),enum:Ke(H())}),default:Ke(H()).optional()}),f3=le({type:ve("array"),title:H().optional(),description:H().optional(),minItems:ft().optional(),maxItems:ft().optional(),items:le({anyOf:Ke(le({const:H(),title:H()}))}),default:Ke(H()).optional()}),m3=St([p3,f3]),h3=St([l3,d3,m3]),g3=St([h3,a3,s3,o3]),v3=Gu.extend({mode:ve("form").optional(),message:H(),requestedSchema:le({type:ve("object"),properties:Pt(H(),g3),required:Ke(H()).optional()})}),y3=Gu.extend({mode:ve("url"),message:H(),elicitationId:H(),url:H().url()}),_3=St([v3,y3]),sS=vr.extend({method:ve("elicitation/create"),params:_3}),b3=xn.extend({elicitationId:H()}),S3=wn.extend({method:ve("notifications/elicitation/complete"),params:b3}),oS=yr.extend({action:Tr(["accept","decline","cancel"]),content:yf(t=>t===null?void 0:t,Pt(H(),St([H(),ft(),rr(),Ke(H())])).optional())}),x3=le({type:ve("ref/resource"),uri:H()});var w3=le({type:ve("ref/prompt"),name:H()}),E3=gn.extend({ref:St([w3,x3]),argument:le({name:H(),value:H()}),context:le({arguments:Pt(H(),H()).optional()}).optional()}),$3=vr.extend({method:ve("completion/complete"),params:E3});var cS=yr.extend({completion:kr({values:Ke(H()).max(100),total:jt(ft().int()),hasMore:jt(rr())})}),k3=le({uri:H().startsWith("file://"),name:H().optional(),_meta:Pt(H(),Tt()).optional()}),T3=vr.extend({method:ve("roots/list"),params:gn.optional()}),I3=yr.extend({roots:Ke(k3)}),O3=wn.extend({method:ve("notifications/roots/list_changed"),params:xn.optional()}),BSe=St([wf,m5,$3,W5,D5,j5,w5,E5,k5,I5,R5,V5,H5,$f,Tf,If,Rf]),VSe=St([xf,Ef,g5,O3,Qu]),GSe=St([Qa,aS,i3,oS,I3,kf,Of,es]),WSe=St([wf,iS,sS,T3,$f,Tf,If,Rf]),KSe=St([xf,Ef,J5,C5,Wb,nS,tS,Qu,S3]),JSe=St([Qa,Fb,cS,eS,Kb,Hb,Bb,Gb,vo,rS,kf,Of,es]),we=class t extends Error{constructor(e,r,n){super(`MCP error ${e}: ${r}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,r,n){if(e===Ce.UrlElicitationRequired&&n){let i=n;if(i.elicitations)return new Mb(i.elicitations,r)}return new t(e,r,n)}},Mb=class extends we{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(Ce.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function ma(t){return t==="completed"||t==="failed"||t==="cancelled"}var Rxe=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function uS(t){let r=rf(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=fI(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function lS(t,e){let r=Fn(t,e);if(!r.success)throw r.error;return r.data}var j3=6e4,Pf=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(xf,r=>{this._oncancel(r)}),this.setNotificationHandler(Ef,r=>{this._onprogress(r)}),this.setRequestHandler(wf,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler($f,async(r,n)=>{let i=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!i)throw new we(Ce.InvalidParams,"Failed to retrieve task: Task not found");return{...i}}),this.setRequestHandler(Tf,async(r,n)=>{let i=async()=>{let a=r.params.taskId;if(this._taskMessageQueue){let o;for(;o=await this._taskMessageQueue.dequeue(a,n.sessionId);){if(o.type==="response"||o.type==="error"){let c=o.message,u=c.id,l=this._requestResolvers.get(u);if(l)if(this._requestResolvers.delete(u),o.type==="response")l(c);else{let d=c,p=new we(d.error.code,d.error.message,d.error.data);l(p)}else{let d=o.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${u}`))}continue}await this._transport?.send(o.message,{relatedRequestId:n.requestId})}}let s=await this._taskStore.getTask(a,n.sessionId);if(!s)throw new we(Ce.InvalidParams,`Task not found: ${a}`);if(!ma(s.status))return await this._waitForTaskUpdate(a,n.signal),await i();if(ma(s.status)){let o=await this._taskStore.getTaskResult(a,n.sessionId);return this._clearTaskQueue(a),{...o,_meta:{...o._meta,[fa]:{taskId:a}}}}return await i()};return await i()}),this.setRequestHandler(If,async(r,n)=>{try{let{tasks:i,nextCursor:a}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:i,nextCursor:a,_meta:{}}}catch(i){throw new we(Ce.InvalidParams,`Failed to list tasks: ${i instanceof Error?i.message:String(i)}`)}}),this.setRequestHandler(Rf,async(r,n)=>{try{let i=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!i)throw new we(Ce.InvalidParams,`Task not found: ${r.params.taskId}`);if(ma(i.status))throw new we(Ce.InvalidParams,`Cannot cancel task in terminal status: ${i.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let a=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!a)throw new we(Ce.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...a}}catch(i){throw i instanceof we?i:new we(Ce.InvalidRequest,`Failed to cancel task: ${i instanceof Error?i.message:String(i)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,n,i,a=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(i,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:a,onTimeout:i})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),we.fromError(Ce.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){this._transport=e;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=a=>{n?.(a),this._onerror(a)};let i=this._transport?.onmessage;this._transport.onmessage=(a,s)=>{i?.(a,s),Wu(a)||S1(a)?this._onresponse(a):Ub(a)?this._onrequest(a,s):b1(a)?this._onnotification(a):this._onerror(new Error(`Unknown message type: ${JSON.stringify(a)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();let r=we.fromError(Ce.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of e.values())n(r)}_onerror(e){this.onerror?.(e)}_onnotification(e){let r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,r){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,i=this._transport,a=e.params?._meta?.[fa]?.taskId;if(n===void 0){let l={jsonrpc:"2.0",id:e.id,error:{code:Ce.MethodNotFound,message:"Method not found"}};a&&this._taskMessageQueue?this._enqueueTaskMessage(a,{type:"error",message:l,timestamp:Date.now()},i?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):i?.send(l).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}let s=new AbortController;this._requestHandlerAbortControllers.set(e.id,s);let o=v1(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,i?.sessionId):void 0,u={signal:s.signal,sessionId:i?.sessionId,_meta:e.params?._meta,sendNotification:async l=>{let d={relatedRequestId:e.id};a&&(d.relatedTask={taskId:a}),await this.notification(l,d)},sendRequest:async(l,d,p)=>{let f={...p,relatedRequestId:e.id};a&&!f.relatedTask&&(f.relatedTask={taskId:a});let h=f.relatedTask?.taskId??a;return h&&c&&await c.updateTaskStatus(h,"input_required"),await this.request(l,d,f)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:a,taskStore:c,taskRequestedTtl:o?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{o&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,u)).then(async l=>{if(s.signal.aborted)return;let d={result:l,jsonrpc:"2.0",id:e.id};a&&this._taskMessageQueue?await this._enqueueTaskMessage(a,{type:"response",message:d,timestamp:Date.now()},i?.sessionId):await i?.send(d)},async l=>{if(s.signal.aborted)return;let d={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(l.code)?l.code:Ce.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};a&&this._taskMessageQueue?await this._enqueueTaskMessage(a,{type:"error",message:d,timestamp:Date.now()},i?.sessionId):await i?.send(d)}).catch(l=>this._onerror(new Error(`Failed to send response: ${l}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,i=Number(r),a=this._progressHandlers.get(i);if(!a){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let s=this._responseHandlers.get(i),o=this._timeoutInfo.get(i);if(o&&s&&o.resetTimeoutOnProgress)try{this._resetTimeout(i)}catch(c){this._responseHandlers.delete(i),this._progressHandlers.delete(i),this._cleanupTimeout(i),s(c);return}a(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),Wu(e))n(e);else{let s=new we(e.error.code,e.error.message,e.error.data);n(s)}return}let i=this._responseHandlers.get(r);if(i===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let a=!1;if(Wu(e)&&e.result&&typeof e.result=="object"){let s=e.result;if(s.task&&typeof s.task=="object"){let o=s.task;typeof o.taskId=="string"&&(a=!0,this._taskProgressTokens.set(o.taskId,r))}}if(a||this._progressHandlers.delete(r),Wu(e))i(e);else{let s=we.fromError(e.error.code,e.error.message,e.error.data);i(s)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,n){let{task:i}=n??{};if(!i){try{yield{type:"result",result:await this.request(e,r,n)}}catch(s){yield{type:"error",error:s instanceof we?s:new we(Ce.InternalError,String(s))}}return}let a;try{let s=await this.request(e,es,n);if(s.task)a=s.task.taskId,yield{type:"taskCreated",task:s.task};else throw new we(Ce.InternalError,"Task creation did not return a task");for(;;){let o=await this.getTask({taskId:a},n);if(yield{type:"taskStatus",task:o},ma(o.status)){o.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:a},r,n)}:o.status==="failed"?yield{type:"error",error:new we(Ce.InternalError,`Task ${a} failed`)}:o.status==="cancelled"&&(yield{type:"error",error:new we(Ce.InternalError,`Task ${a} was cancelled`)});return}if(o.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:a},r,n)};return}let c=o.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),n?.signal?.throwIfAborted()}}catch(s){yield{type:"error",error:s instanceof we?s:new we(Ce.InternalError,String(s))}}}request(e,r,n){let{relatedRequestId:i,resumptionToken:a,onresumptiontoken:s,task:o,relatedTask:c}=n??{};return new Promise((u,l)=>{let d=_=>{l(_)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),o&&this.assertTaskCapability(e.method)}catch(_){d(_);return}n?.signal?.throwIfAborted();let p=this._requestMessageId++,f={...e,jsonrpc:"2.0",id:p};n?.onprogress&&(this._progressHandlers.set(p,n.onprogress),f.params={...e.params,_meta:{...e.params?._meta||{},progressToken:p}}),o&&(f.params={...f.params,task:o}),c&&(f.params={...f.params,_meta:{...f.params?._meta||{},[fa]:c}});let h=_=>{this._responseHandlers.delete(p),this._progressHandlers.delete(p),this._cleanupTimeout(p),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:p,reason:String(_)}},{relatedRequestId:i,resumptionToken:a,onresumptiontoken:s}).catch(b=>this._onerror(new Error(`Failed to send cancellation: ${b}`)));let v=_ instanceof we?_:new we(Ce.RequestTimeout,String(_));l(v)};this._responseHandlers.set(p,_=>{if(!n?.signal?.aborted){if(_ instanceof Error)return l(_);try{let v=Fn(r,_.result);v.success?u(v.data):l(v.error)}catch(v){l(v)}}}),n?.signal?.addEventListener("abort",()=>{h(n?.signal?.reason)});let y=n?.timeout??j3,g=()=>h(we.fromError(Ce.RequestTimeout,"Request timed out",{timeout:y}));this._setupTimeout(p,y,n?.maxTotalTimeout,g,n?.resetTimeoutOnProgress??!1);let m=c?.taskId;if(m){let _=v=>{let b=this._responseHandlers.get(p);b?b(v):this._onerror(new Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,_),this._enqueueTaskMessage(m,{type:"request",message:f,timestamp:Date.now()}).catch(v=>{this._cleanupTimeout(p),l(v)})}else this._transport.send(f,{relatedRequestId:i,resumptionToken:a,onresumptiontoken:s}).catch(_=>{this._cleanupTimeout(p),l(_)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},kf,r)}async getTaskResult(e,r,n){return this.request({method:"tasks/result",params:e},r,n)}async listTasks(e,r){return this.request({method:"tasks/list",params:e},Of,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},E1,r)}async notification(e,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let n=r?.relatedTask?.taskId;if(n){let o={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[fa]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:o,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let o={...e,jsonrpc:"2.0"};r?.relatedTask&&(o={...o,params:{...o.params,_meta:{...o.params?._meta||{},[fa]:r.relatedTask}}}),this._transport?.send(o,r).catch(c=>this._onerror(c))});return}let s={...e,jsonrpc:"2.0"};r?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[fa]:r.relatedTask}}}),await this._transport.send(s,r)}setRequestHandler(e,r){let n=uS(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(i,a)=>{let s=lS(e,i);return Promise.resolve(r(s,a))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){let n=uS(e);this._notificationHandlers.set(n,i=>{let a=lS(e,i);return Promise.resolve(r(a))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let i=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,i)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,r);for(let i of n)if(i.type==="request"&&Ub(i.message)){let a=i.message.id,s=this._requestResolvers.get(a);s?(s(new we(Ce.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(a)):this._onerror(new Error(`Resolver missing for request ${a} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let i=await this._taskStore?.getTask(e);i?.pollInterval&&(n=i.pollInterval)}catch{}return new Promise((i,a)=>{if(r.aborted){a(new we(Ce.InvalidRequest,"Request cancelled"));return}let s=setTimeout(i,n);r.addEventListener("abort",()=>{clearTimeout(s),a(new we(Ce.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async i=>{if(!e)throw new Error("No request provided");return await n.createTask(i,e.id,{method:e.method,params:e.params},r)},getTask:async i=>{let a=await n.getTask(i,r);if(!a)throw new we(Ce.InvalidParams,"Failed to retrieve task: Task not found");return a},storeTaskResult:async(i,a,s)=>{await n.storeTaskResult(i,a,s,r);let o=await n.getTask(i,r);if(o){let c=Qu.parse({method:"notifications/tasks/status",params:o});await this.notification(c),ma(o.status)&&this._cleanupTaskProgressHandler(i)}},getTaskResult:i=>n.getTaskResult(i,r),updateTaskStatus:async(i,a,s)=>{let o=await n.getTask(i,r);if(!o)throw new we(Ce.InvalidParams,`Task "${i}" not found - it may have been cleaned up`);if(ma(o.status))throw new we(Ce.InvalidParams,`Cannot update task "${i}" from terminal status "${o.status}" to "${a}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(i,a,s,r);let c=await n.getTask(i,r);if(c){let u=Qu.parse({method:"notifications/tasks/status",params:c});await this.notification(u),ma(c.status)&&this._cleanupTaskProgressHandler(i)}},listTasks:i=>n.listTasks(i,r)}}};function C1(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function N1(t,e){let r={...t};for(let n in e){let i=n,a=e[i];if(a===void 0)continue;let s=r[i];C1(s)&&C1(a)?r[i]={...s,...a}:r[i]=a}return r}var _P=nt(Kx(),1),bP=nt(yP(),1);function $7(){let t=new _P.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,bP.default)(t),t}var mm=class{constructor(e){this._ajv=e??$7()}getValidator(e){let r="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}};var hm=class{constructor(e){this._client=e}async*callToolStream(e,r=vo,n){let i=this._client,a={...n,task:n?.task??(i.isToolTask(e.name)?{}:void 0)},s=i.requestStream({method:"tools/call",params:e},r,a),o=i.getToolOutputValidator(e.name);for await(let c of s){if(c.type==="result"&&o){let u=c.result;if(!u.structuredContent&&!u.isError){yield{type:"error",error:new we(Ce.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`)};return}if(u.structuredContent)try{let l=o(u.structuredContent);if(!l.valid){yield{type:"error",error:new we(Ce.InvalidParams,`Structured content does not match the tool's output schema: ${l.errorMessage}`)};return}}catch(l){if(l instanceof we){yield{type:"error",error:l};return}yield{type:"error",error:new we(Ce.InvalidParams,`Failed to validate structured content: ${l instanceof Error?l.message:String(l)}`)};return}}yield c}}async getTask(e,r){return this._client.getTask({taskId:e},r)}async getTaskResult(e,r,n){return this._client.getTaskResult({taskId:e},r,n)}async listTasks(e,r){return this._client.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._client.cancelTask({taskId:e},r)}requestStream(e,r,n){return this._client.requestStream(e,r,n)}};function SP(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${e})`);break;default:break}}function xP(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}function gm(t,e){if(!(!t||e===null||typeof e!="object")){if(t.type==="object"&&t.properties&&typeof t.properties=="object"){let r=e,n=t.properties;for(let i of Object.keys(n)){let a=n[i];r[i]===void 0&&Object.prototype.hasOwnProperty.call(a,"default")&&(r[i]=a.default),r[i]!==void 0&&gm(a,r[i])}}if(Array.isArray(t.anyOf))for(let r of t.anyOf)typeof r!="boolean"&&gm(r,e);if(Array.isArray(t.oneOf))for(let r of t.oneOf)typeof r!="boolean"&&gm(r,e)}}function k7(t){if(!t)return{supportsFormMode:!1,supportsUrlMode:!1};let e=t.form!==void 0,r=t.url!==void 0;return{supportsFormMode:e||!e&&!r,supportsUrlMode:r}}var Ao=class extends Pf{constructor(e,r){super(r),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._cachedKnownTaskTools=new Set,this._cachedRequiredTaskTools=new Set,this._listChangedDebounceTimers=new Map,this._capabilities=r?.capabilities??{},this._jsonSchemaValidator=r?.jsonSchemaValidator??new mm,r?.listChanged&&(this._pendingListChangedConfig=r.listChanged)}_setupListChangedHandlers(e){e.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",nS,e.tools,async()=>(await this.listTools()).tools),e.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",tS,e.prompts,async()=>(await this.listPrompts()).prompts),e.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",Wb,e.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new hm(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=N1(this._capabilities,e)}setRequestHandler(e,r){let i=rf(e)?.method;if(!i)throw new Error("Schema is missing a method literal");let a;if(fo(i)){let o=i;a=o._zod?.def?.value??o.value}else{let o=i;a=o._def?.value??o.value}if(typeof a!="string")throw new Error("Schema method literal must be a string");let s=a;if(s==="elicitation/create"){let o=async(c,u)=>{let l=Fn(sS,c);if(!l.success){let _=l.error instanceof Error?l.error.message:String(l.error);throw new we(Ce.InvalidParams,`Invalid elicitation request: ${_}`)}let{params:d}=l.data;d.mode=d.mode??"form";let{supportsFormMode:p,supportsUrlMode:f}=k7(this._capabilities.elicitation);if(d.mode==="form"&&!p)throw new we(Ce.InvalidParams,"Client does not support form-mode elicitation requests");if(d.mode==="url"&&!f)throw new we(Ce.InvalidParams,"Client does not support URL-mode elicitation requests");let h=await Promise.resolve(r(c,u));if(d.task){let _=Fn(es,h);if(!_.success){let v=_.error instanceof Error?_.error.message:String(_.error);throw new we(Ce.InvalidParams,`Invalid task creation result: ${v}`)}return _.data}let y=Fn(oS,h);if(!y.success){let _=y.error instanceof Error?y.error.message:String(y.error);throw new we(Ce.InvalidParams,`Invalid elicitation result: ${_}`)}let g=y.data,m=d.mode==="form"?d.requestedSchema:void 0;if(d.mode==="form"&&g.action==="accept"&&g.content&&m&&this._capabilities.elicitation?.form?.applyDefaults)try{gm(m,g.content)}catch{}return g};return super.setRequestHandler(e,o)}if(s==="sampling/createMessage"){let o=async(c,u)=>{let l=Fn(iS,c);if(!l.success){let h=l.error instanceof Error?l.error.message:String(l.error);throw new we(Ce.InvalidParams,`Invalid sampling request: ${h}`)}let{params:d}=l.data,p=await Promise.resolve(r(c,u));if(d.task){let h=Fn(es,p);if(!h.success){let y=h.error instanceof Error?h.error.message:String(h.error);throw new we(Ce.InvalidParams,`Invalid task creation result: ${y}`)}return h.data}let f=Fn(aS,p);if(!f.success){let h=f.error instanceof Error?f.error.message:String(f.error);throw new we(Ce.InvalidParams,`Invalid sampling result: ${h}`)}return f.data};return super.setRequestHandler(e,o)}return super.setRequestHandler(e,r)}assertCapability(e,r){if(!this._serverCapabilities?.[e])throw new Error(`Server does not support ${e} (required for ${r})`)}async connect(e,r){if(await super.connect(e),e.sessionId===void 0)try{let n=await this.request({method:"initialize",params:{protocolVersion:Db,capabilities:this._capabilities,clientInfo:this._clientInfo}},Fb,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!m1.includes(n.protocolVersion))throw new Error(`Server's protocol version is not supported: ${n.protocolVersion}`);this._serverCapabilities=n.capabilities,this._serverVersion=n.serverInfo,e.setProtocolVersion&&e.setProtocolVersion(n.protocolVersion),this._instructions=n.instructions,await this.notification({method:"notifications/initialized"}),this._pendingListChangedConfig&&(this._setupListChangedHandlers(this._pendingListChangedConfig),this._pendingListChangedConfig=void 0)}catch(n){throw this.close(),n}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){switch(e){case"logging/setLevel":if(!this._serverCapabilities?.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._serverCapabilities?.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!this._serverCapabilities?.resources)throw new Error(`Server does not support resources (required for ${e})`);if(e==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._serverCapabilities?.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!this._serverCapabilities?.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"initialize":break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/roots/list_changed":if(!this._capabilities.roots?.listChanged)throw new Error(`Client does not support roots list changed notifications (required for ${e})`);break;case"notifications/initialized":break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Client does not support tasks capability (required for ${e})`);break;case"ping":break}}assertTaskCapability(e){SP(this._serverCapabilities?.tasks?.requests,e,"Server")}assertTaskHandlerCapability(e){this._capabilities&&xP(this._capabilities.tasks?.requests,e,"Client")}async ping(e){return this.request({method:"ping"},Qa,e)}async complete(e,r){return this.request({method:"completion/complete",params:e},cS,r)}async setLoggingLevel(e,r){return this.request({method:"logging/setLevel",params:{level:e}},Qa,r)}async getPrompt(e,r){return this.request({method:"prompts/get",params:e},eS,r)}async listPrompts(e,r){return this.request({method:"prompts/list",params:e},Kb,r)}async listResources(e,r){return this.request({method:"resources/list",params:e},Hb,r)}async listResourceTemplates(e,r){return this.request({method:"resources/templates/list",params:e},Bb,r)}async readResource(e,r){return this.request({method:"resources/read",params:e},Gb,r)}async subscribeResource(e,r){return this.request({method:"resources/subscribe",params:e},Qa,r)}async unsubscribeResource(e,r){return this.request({method:"resources/unsubscribe",params:e},Qa,r)}async callTool(e,r=vo,n){if(this.isToolTaskRequired(e.name))throw new we(Ce.InvalidRequest,`Tool "${e.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);let i=await this.request({method:"tools/call",params:e},r,n),a=this.getToolOutputValidator(e.name);if(a){if(!i.structuredContent&&!i.isError)throw new we(Ce.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(i.structuredContent)try{let s=a(i.structuredContent);if(!s.valid)throw new we(Ce.InvalidParams,`Structured content does not match the tool's output schema: ${s.errorMessage}`)}catch(s){throw s instanceof we?s:new we(Ce.InvalidParams,`Failed to validate structured content: ${s instanceof Error?s.message:String(s)}`)}}return i}isToolTask(e){return this._serverCapabilities?.tasks?.requests?.tools?.call?this._cachedKnownTaskTools.has(e):!1}isToolTaskRequired(e){return this._cachedRequiredTaskTools.has(e)}cacheToolMetadata(e){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(let r of e){if(r.outputSchema){let i=this._jsonSchemaValidator.getValidator(r.outputSchema);this._cachedToolOutputValidators.set(r.name,i)}let n=r.execution?.taskSupport;(n==="required"||n==="optional")&&this._cachedKnownTaskTools.add(r.name),n==="required"&&this._cachedRequiredTaskTools.add(r.name)}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,r){let n=await this.request({method:"tools/list",params:e},rS,r);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(e,r,n,i){let a=R1.safeParse(n);if(!a.success)throw new Error(`Invalid ${e} listChanged options: ${a.error.message}`);if(typeof n.onChanged!="function")throw new Error(`Invalid ${e} listChanged options: onChanged must be a function`);let{autoRefresh:s,debounceMs:o}=a.data,{onChanged:c}=n,u=async()=>{if(!s){c(null,null);return}try{let d=await i();c(null,d)}catch(d){let p=d instanceof Error?d:new Error(String(d));c(p,null)}},l=()=>{if(o){let d=this._listChangedDebounceTimers.get(e);d&&clearTimeout(d);let p=setTimeout(u,o);this._listChangedDebounceTimers.set(e,p)}else u()};this.setNotificationHandler(r,l)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};var pC=nt(lC(),1),Pl=nt(require("node:process"),1),fC=require("node:stream");var ym=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(` `);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),Q7(r)}clear(){this._buffer=void 0}};function Q7(t){return x1.parse(JSON.parse(t))}function dC(t){return JSON.stringify(t)+` -`}var eW=Pl.default.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function tW(){let t={};for(let e of eW){let r=Pl.default.env[e];r!==void 0&&(r.startsWith("()")||(t[e]=r))}return t}var Do=class{constructor(e){this._readBuffer=new ym,this._stderrStream=null,this._serverParams=e,(e.stderr==="pipe"||e.stderr==="overlapped")&&(this._stderrStream=new fC.PassThrough)}async start(){if(this._process)throw new Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((e,r)=>{this._process=(0,pC.default)(this._serverParams.command,this._serverParams.args??[],{env:{...tW(),...this._serverParams.env},stdio:["pipe","pipe",this._serverParams.stderr??"inherit"],shell:!1,windowsHide:Pl.default.platform==="win32"&&rW(),cwd:this._serverParams.cwd}),this._process.on("error",n=>{r(n),this.onerror?.(n)}),this._process.on("spawn",()=>{e()}),this._process.on("close",n=>{this._process=void 0,this.onclose?.()}),this._process.stdin?.on("error",n=>{this.onerror?.(n)}),this._process.stdout?.on("data",n=>{this._readBuffer.append(n),this.processReadBuffer()}),this._process.stdout?.on("error",n=>{this.onerror?.(n)}),this._stderrStream&&this._process.stderr&&this._process.stderr.pipe(this._stderrStream)})}get stderr(){return this._stderrStream?this._stderrStream:this._process?.stderr??null}get pid(){return this._process?.pid??null}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){if(this._process){let e=this._process;this._process=void 0;let r=new Promise(n=>{e.once("close",()=>{n()})});try{e.stdin?.end()}catch{}if(await Promise.race([r,new Promise(n=>setTimeout(n,2e3).unref())]),e.exitCode===null){try{e.kill("SIGTERM")}catch{}await Promise.race([r,new Promise(n=>setTimeout(n,2e3).unref())])}if(e.exitCode===null)try{e.kill("SIGKILL")}catch{}}this._readBuffer.clear()}send(e){return new Promise(r=>{if(!this._process?.stdin)throw new Error("Not connected");let n=dC(e);this._process.stdin.write(n)?r():this._process.stdin.once("drain",r)})}};function rW(){return"type"in Pl.default}Zr();lr();Se();var v0=nt(require("path"),1),AC=require("os"),Wn=require("fs"),ps=require("child_process"),jC=require("util");Se();gi();var $m=(0,jC.promisify)(ps.exec),MC=v0.default.join((0,AC.homedir)(),".claude-mem"),ds=v0.default.join(MC,"worker.pid"),NC=["mcp-server.cjs","worker-service.cjs","chroma-mcp"],g0=30;function DC(t){(0,Wn.mkdirSync)(MC,{recursive:!0}),(0,Wn.writeFileSync)(ds,JSON.stringify(t,null,2))}function zC(){if(!(0,Wn.existsSync)(ds))return null;try{return JSON.parse((0,Wn.readFileSync)(ds,"utf-8"))}catch(t){return $.warn("SYSTEM","Failed to parse PID file",{path:ds},t),null}}function _i(){if((0,Wn.existsSync)(ds))try{(0,Wn.unlinkSync)(ds)}catch(t){$.warn("SYSTEM","Failed to remove PID file",{path:ds},t)}}function fs(t){return process.platform==="win32"?Math.round(t*2):t}async function UC(t){if(process.platform!=="win32")return[];if(!Number.isInteger(t)||t<=0)return $.warn("SYSTEM","Invalid parent PID for child process enumeration",{parentPid:t}),[];try{let e=`powershell -NoProfile -NonInteractive -Command "Get-Process | Where-Object { \\$_.ParentProcessId -eq ${t} } | Select-Object -ExpandProperty Id"`,{stdout:r}=await $m(e,{timeout:hi.POWERSHELL_COMMAND});return r.split(` -`).map(n=>n.trim()).filter(n=>n.length>0&&/^\d+$/.test(n)).map(n=>parseInt(n,10)).filter(n=>n>0)}catch(e){return $.error("SYSTEM","Failed to enumerate child processes",{parentPid:t},e),[]}}async function LC(t){if(!Number.isInteger(t)||t<=0){$.warn("SYSTEM","Invalid PID for force kill",{pid:t});return}try{process.platform==="win32"?await $m(`taskkill /PID ${t} /T /F`,{timeout:hi.POWERSHELL_COMMAND}):process.kill(t,"SIGKILL"),$.info("SYSTEM","Killed process",{pid:t})}catch(e){$.debug("SYSTEM","Process already exited during force kill",{pid:t},e)}}async function qC(t,e){let r=Date.now();for(;Date.now()-r{try{return process.kill(i,0),!0}catch{return!1}});if(n.length===0){$.info("SYSTEM","All child processes exited");return}$.debug("SYSTEM","Waiting for processes to exit",{stillAlive:n}),await new Promise(i=>setTimeout(i,100))}$.warn("SYSTEM","Timeout waiting for child processes to exit")}function SW(t){if(!t||t.trim()==="")return-1;let e=t.trim(),r=0,n=e.match(/^(\d+)-(\d+):(\d+):(\d+)$/);if(n)return r=parseInt(n[1],10)*24*60+parseInt(n[2],10)*60+parseInt(n[3],10),r;let i=e.match(/^(\d+):(\d+):(\d+)$/);if(i)return r=parseInt(i[1],10)*60+parseInt(i[2],10),r;let a=e.match(/^(\d+):(\d+)$/);return a?parseInt(a[1],10):-1}async function FC(){let t=process.platform==="win32",e=process.pid,r=[];try{if(t){let i=`powershell -NoProfile -NonInteractive -Command "Get-CimInstance Win32_Process | Where-Object { (${NC.map(u=>`\\$_.CommandLine -like '*${u}*'`).join(" -or ")}) -and \\$_.ProcessId -ne ${e} } | Select-Object ProcessId, CreationDate | ConvertTo-Json"`,{stdout:a}=await $m(i,{timeout:hi.POWERSHELL_COMMAND});if(!a.trim()||a.trim()==="null"){$.debug("SYSTEM","No orphaned claude-mem processes found (Windows)");return}let s=JSON.parse(a),o=Array.isArray(s)?s:[s],c=Date.now();for(let u of o){let l=u.ProcessId;if(!Number.isInteger(l)||l<=0||l===e)continue;let d=u.CreationDate?.match(/\/Date\((\d+)\)\//);if(d){let p=parseInt(d[1],10),f=(c-p)/(1e3*60);f>=g0&&(r.push(l),$.debug("SYSTEM","Found orphaned process",{pid:l,ageMinutes:Math.round(f)}))}}}else{let n=NC.join("|"),{stdout:i}=await $m(`ps -eo pid,etime,command | grep -E "${n}" | grep -v grep || true`);if(!i.trim()){$.debug("SYSTEM","No orphaned claude-mem processes found (Unix)");return}let a=i.trim().split(` -`);for(let s of a){let o=s.trim().match(/^(\d+)\s+(\S+)\s+(.*)$/);if(!o)continue;let c=parseInt(o[1],10),u=o[2];if(!Number.isInteger(c)||c<=0||c===e)continue;let l=SW(u);l>=g0&&(r.push(c),$.debug("SYSTEM","Found orphaned process",{pid:c,ageMinutes:l,command:o[3].substring(0,80)}))}}}catch(n){$.error("SYSTEM","Failed to enumerate orphaned processes",{},n);return}if(r.length!==0){if($.info("SYSTEM","Cleaning up orphaned claude-mem processes",{platform:t?"Windows":"Unix",count:r.length,pids:r,maxAgeMinutes:g0}),t)for(let n of r){if(!Number.isInteger(n)||n<=0){$.warn("SYSTEM","Skipping invalid PID",{pid:n});continue}try{(0,ps.execSync)(`taskkill /PID ${n} /T /F`,{timeout:hi.POWERSHELL_COMMAND,stdio:"ignore"})}catch(i){$.debug("SYSTEM","Failed to kill process, may have already exited",{pid:n},i)}}else for(let n of r)try{process.kill(n,"SIGKILL")}catch(i){$.debug("SYSTEM","Process already exited",{pid:n},i)}$.info("SYSTEM","Orphaned processes cleaned up",{count:r.length})}}function y0(t,e,r={}){let n=process.platform==="win32",i={...process.env,CLAUDE_MEM_WORKER_PORT:String(e),...r};if(n){let c=`wmic process call create "\\"${process.execPath}\\" \\"${t}\\" --daemon"`;try{return(0,ps.execSync)(c,{stdio:"ignore",windowsHide:!0}),0}catch{return}}let a=(0,ps.spawn)(process.execPath,[t,"--daemon"],{detached:!0,stdio:"ignore",env:i});if(a.pid!==void 0)return a.unref(),a.pid}function ZC(t,e){return async r=>{if(e.value){$.warn("SYSTEM",`Received ${r} but shutdown already in progress`);return}e.value=!0,$.info("SYSTEM",`Received ${r}, shutting down...`);try{await t(),process.exit(0)}catch(n){$.error("SYSTEM","Error during shutdown",{},n),process.exit(0)}}}var HC=nt(require("path"),1),BC=require("fs");Se();er();async function Ml(t){try{return(await fetch(`http://127.0.0.1:${t}/api/health`)).ok}catch{return!1}}async function Dl(t,e=3e4){let r=Date.now();for(;Date.now()-rsetTimeout(n,500))}return!1}async function km(t,e=1e4){let r=Date.now();for(;Date.now()-rsetTimeout(n,500))}return!1}async function Tm(t){try{let e=await fetch(`http://127.0.0.1:${t}/api/admin/shutdown`,{method:"POST"});return e.ok?!0:($.warn("SYSTEM","Shutdown request returned error",{port:t,status:e.status}),!1)}catch(e){return e instanceof Error&&e.message?.includes("ECONNREFUSED")?($.debug("SYSTEM","Worker already stopped",{port:t},e),!1):($.error("SYSTEM","Shutdown request failed unexpectedly",{port:t},e),!1)}}function xW(){let t=HC.default.join(yi,"package.json");return JSON.parse((0,BC.readFileSync)(t,"utf-8")).version}async function wW(t){try{let e=await fetch(`http://127.0.0.1:${t}/api/version`);return e.ok?(await e.json()).version:null}catch{return $.debug("SYSTEM","Could not fetch worker version",{port:t}),null}}async function VC(t){let e=xW(),r=await wW(t);return r?{matches:e===r,pluginVersion:e,workerVersion:r}:{matches:!0,pluginVersion:e,workerVersion:r}}Se();async function GC(t){$.info("SYSTEM","Shutdown initiated"),_i();let e=await UC(process.pid);if($.info("SYSTEM","Found child processes",{count:e.length,pids:e}),t.server&&(await EW(t.server),$.info("SYSTEM","HTTP server closed")),await t.sessionManager.shutdownAll(),t.mcpClient&&(await t.mcpClient.close(),$.info("SYSTEM","MCP client closed")),t.dbManager&&await t.dbManager.close(),e.length>0){$.info("SYSTEM","Force killing remaining children");for(let r of e)await LC(r);await qC(e,5e3)}$.info("SYSTEM","Worker shutdown complete")}async function EW(t){t.closeAllConnections(),process.platform==="win32"&&await new Promise(e=>setTimeout(e,500)),await new Promise((e,r)=>{t.close(n=>n?r(n):e())}),process.platform==="win32"&&(await new Promise(e=>setTimeout(e,500)),$.info("SYSTEM","Waited for Windows port cleanup"))}var n2=nt(jh(),1),EE=nt(require("fs"),1),$E=nt(require("path"),1);Se();var SE=nt(jh(),1),Y4=nt(X4(),1),Q4=nt(require("path"),1);er();Se();function xE(t){let e=[];e.push(SE.default.json({limit:"50mb"})),e.push((0,Y4.default)({origin:(i,a)=>{!i||i.startsWith("http://localhost:")||i.startsWith("http://127.0.0.1:")?a(null,!0):a(new Error("CORS not allowed"))},credentials:!1})),e.push((i,a,s)=>{let c=[".html",".js",".css",".svg",".png",".jpg",".jpeg",".webp",".woff",".woff2",".ttf",".eot"].some(h=>i.path.endsWith(h)),u=i.path==="/api/logs";if(i.path.startsWith("/health")||i.path==="/"||c||u)return s();let l=Date.now(),d=`${i.method}-${Date.now()}`,p=t(i.method,i.path,i.body);$.info("HTTP",`\u2192 ${i.method} ${i.path}`,{requestId:d},p);let f=a.send.bind(a);a.send=function(h){let y=Date.now()-l;return $.info("HTTP",`\u2190 ${a.statusCode} ${i.path}`,{requestId:d,duration:`${y}ms`}),f(h)},s()});let r=Qr(),n=Q4.default.join(r,"plugin","ui");return e.push(SE.default.static(n)),e}function Mh(t,e,r){let n=t.ip||t.connection.remoteAddress||"";if(!(n==="127.0.0.1"||n==="::1"||n==="::ffff:127.0.0.1"||n==="localhost")){$.warn("SECURITY","Admin endpoint access denied - not localhost",{endpoint:t.path,clientIp:n,method:t.method}),e.status(403).json({error:"Forbidden",message:"Admin endpoints are only accessible from localhost"});return}r()}function wE(t,e,r){if(!r||Object.keys(r).length===0||e.includes("/init"))return"";if(e.includes("/observations")){let n=r.tool_name||"?",i=r.tool_input;return`tool=${$.formatTool(n,i)}`}return e.includes("/summarize")?"requesting summary":""}Se();var lc=class extends Error{constructor(r,n=500,i,a){super(r);this.statusCode=n;this.code=i;this.details=a;this.name="AppError"}};function e2(t,e,r,n){let i={error:t,message:e};return r&&(i.code=r),n&&(i.details=n),i}var t2=(t,e,r,n)=>{let i=t instanceof lc?t.statusCode:500;$.error("HTTP",`Error handling ${e.method} ${e.path}`,{statusCode:i,error:t.message,code:t instanceof lc?t.code:void 0},t);let a=e2(t.name||"Error",t.message,t instanceof lc?t.code:void 0,t instanceof lc?t.details:void 0);r.status(i).json(a)};function r2(t,e){e.status(404).json(e2("NotFound",`Cannot ${t.method} ${t.path}`))}var Eie="9.1.1",Dh=class{app;server=null;options;startTime=Date.now();constructor(e){this.options=e,this.app=(0,n2.default)(),this.setupMiddleware(),this.setupCoreRoutes()}getHttpServer(){return this.server}async listen(e,r){return new Promise((n,i)=>{this.server=this.app.listen(e,r,()=>{$.info("SYSTEM","HTTP server started",{host:r,port:e,pid:process.pid}),n()}),this.server.on("error",i)})}async close(){this.server&&(this.server.closeAllConnections(),process.platform==="win32"&&await new Promise(e=>setTimeout(e,500)),await new Promise((e,r)=>{this.server.close(n=>n?r(n):e())}),process.platform==="win32"&&await new Promise(e=>setTimeout(e,500)),this.server=null,$.info("SYSTEM","HTTP server closed"))}registerRoutes(e){e.setupRoutes(this.app)}finalizeRoutes(){this.app.use(r2),this.app.use(t2)}setupMiddleware(){xE(wE).forEach(r=>this.app.use(r))}setupCoreRoutes(){let e="TEST-008-wrapper-ipc";this.app.get("/api/health",(r,n)=>{n.status(200).json({status:"ok",build:e,managed:process.env.CLAUDE_MEM_MANAGED==="true",hasIpc:typeof process.send=="function",platform:process.platform,pid:process.pid,initialized:this.options.getInitializationComplete(),mcpReady:this.options.getMcpReady()})}),this.app.get("/api/readiness",(r,n)=>{this.options.getInitializationComplete()?n.status(200).json({status:"ready",mcpReady:this.options.getMcpReady()}):n.status(503).json({status:"initializing",message:"Worker is still initializing, please retry"})}),this.app.get("/api/version",(r,n)=>{n.status(200).json({version:Eie})}),this.app.get("/api/instructions",async(r,n)=>{let i=r.query.topic||"all",a=r.query.operation;try{let s;if(a){let o=$E.default.join(__dirname,"../skills/mem-search/operations",`${a}.md`);s=await EE.promises.readFile(o,"utf-8")}else{let o=$E.default.join(__dirname,"../skills/mem-search/SKILL.md"),c=await EE.promises.readFile(o,"utf-8");s=this.extractInstructionSection(c,i)}n.json({content:[{type:"text",text:s}]})}catch{n.status(404).json({error:"Instruction not found"})}}),this.app.post("/api/admin/restart",Mh,async(r,n)=>{n.json({status:"restarting"}),process.platform==="win32"&&process.env.CLAUDE_MEM_MANAGED==="true"&&process.send?($.info("SYSTEM","Sending restart request to wrapper"),process.send({type:"restart"})):setTimeout(async()=>{await this.options.onRestart()},100)}),this.app.post("/api/admin/shutdown",Mh,async(r,n)=>{n.json({status:"shutting_down"}),process.platform==="win32"&&process.env.CLAUDE_MEM_MANAGED==="true"&&process.send?($.info("SYSTEM","Sending shutdown request to wrapper"),process.send({type:"shutdown"})):setTimeout(async()=>{await this.options.onShutdown()},100)})}extractInstructionSection(e,r){let n={workflow:this.extractBetween(e,"## The Workflow","## Search Parameters"),search_params:this.extractBetween(e,"## Search Parameters","## Examples"),examples:this.extractBetween(e,"## Examples","## Why This Workflow"),all:e};return n[r]||n.all}extractBetween(e,r,n){let i=e.indexOf(r),a=e.indexOf(n);return i===-1?e:a===-1?e.substring(i):e.substring(i,a).trim()}};var at=nt(require("path"),1),bd=require("os"),zt=require("fs"),s2=require("child_process"),o2=require("util");Se();Zr();er();var Cn=require("fs"),_d=require("path");Se();function i2(t){try{return(0,Cn.existsSync)(t)?JSON.parse((0,Cn.readFileSync)(t,"utf-8")):{}}catch(e){return $.error("CONFIG","Failed to read Cursor registry, using empty registry",{file:t,error:e instanceof Error?e.message:String(e)}),{}}}function a2(t,e){let r=(0,_d.join)(t,"..");(0,Cn.mkdirSync)(r,{recursive:!0}),(0,Cn.writeFileSync)(t,JSON.stringify(e,null,2))}function kE(t,e){let r=(0,_d.join)(t,".cursor","rules"),n=(0,_d.join)(r,"claude-mem-context.mdc"),i=`${n}.tmp`;(0,Cn.mkdirSync)(r,{recursive:!0});let a=`--- +`}var eW=Pl.default.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function tW(){let t={};for(let e of eW){let r=Pl.default.env[e];r!==void 0&&(r.startsWith("()")||(t[e]=r))}return t}var Do=class{constructor(e){this._readBuffer=new ym,this._stderrStream=null,this._serverParams=e,(e.stderr==="pipe"||e.stderr==="overlapped")&&(this._stderrStream=new fC.PassThrough)}async start(){if(this._process)throw new Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((e,r)=>{this._process=(0,pC.default)(this._serverParams.command,this._serverParams.args??[],{env:{...tW(),...this._serverParams.env},stdio:["pipe","pipe",this._serverParams.stderr??"inherit"],shell:!1,windowsHide:Pl.default.platform==="win32"&&rW(),cwd:this._serverParams.cwd}),this._process.on("error",n=>{r(n),this.onerror?.(n)}),this._process.on("spawn",()=>{e()}),this._process.on("close",n=>{this._process=void 0,this.onclose?.()}),this._process.stdin?.on("error",n=>{this.onerror?.(n)}),this._process.stdout?.on("data",n=>{this._readBuffer.append(n),this.processReadBuffer()}),this._process.stdout?.on("error",n=>{this.onerror?.(n)}),this._stderrStream&&this._process.stderr&&this._process.stderr.pipe(this._stderrStream)})}get stderr(){return this._stderrStream?this._stderrStream:this._process?.stderr??null}get pid(){return this._process?.pid??null}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){if(this._process){let e=this._process;this._process=void 0;let r=new Promise(n=>{e.once("close",()=>{n()})});try{e.stdin?.end()}catch{}if(await Promise.race([r,new Promise(n=>setTimeout(n,2e3).unref())]),e.exitCode===null){try{e.kill("SIGTERM")}catch{}await Promise.race([r,new Promise(n=>setTimeout(n,2e3).unref())])}if(e.exitCode===null)try{e.kill("SIGKILL")}catch{}}this._readBuffer.clear()}send(e){return new Promise(r=>{if(!this._process?.stdin)throw new Error("Not connected");let n=dC(e);this._process.stdin.write(n)?r():this._process.stdin.once("drain",r)})}};function rW(){return"type"in Pl.default}Zr();lr();Se();var v0=nt(require("path"),1),AC=require("os"),Wn=require("fs"),ps=require("child_process"),jC=require("util");Se();gi();var $m=(0,jC.promisify)(ps.exec),MC=v0.default.join((0,AC.homedir)(),".claude-mem"),ds=v0.default.join(MC,"worker.pid"),NC=["mcp-server.cjs","worker-service.cjs","chroma-mcp"],g0=30;function DC(t){(0,Wn.mkdirSync)(MC,{recursive:!0}),(0,Wn.writeFileSync)(ds,JSON.stringify(t,null,2))}function zC(){if(!(0,Wn.existsSync)(ds))return null;try{return JSON.parse((0,Wn.readFileSync)(ds,"utf-8"))}catch(t){return $.warn("SYSTEM","Failed to parse PID file",{path:ds},t),null}}function _i(){if((0,Wn.existsSync)(ds))try{(0,Wn.unlinkSync)(ds)}catch(t){$.warn("SYSTEM","Failed to remove PID file",{path:ds},t)}}function fs(t){return process.platform==="win32"?Math.round(t*2):t}async function UC(t){if(process.platform!=="win32")return[];if(!Number.isInteger(t)||t<=0)return $.warn("SYSTEM","Invalid parent PID for child process enumeration",{parentPid:t}),[];try{let e=`powershell -NoProfile -NonInteractive -Command "Get-Process | Where-Object { $_.ParentProcessId -eq ${t} } | Select-Object -ExpandProperty Id"`,{stdout:r}=await $m(e,{timeout:hi.POWERSHELL_COMMAND});return r.split(` +`).map(n=>n.trim()).filter(n=>n.length>0&&/^\d+$/.test(n)).map(n=>parseInt(n,10)).filter(n=>n>0)}catch(e){return $.error("SYSTEM","Failed to enumerate child processes",{parentPid:t},e),[]}}async function LC(t){if(!Number.isInteger(t)||t<=0){$.warn("SYSTEM","Invalid PID for force kill",{pid:t});return}try{process.platform==="win32"?await $m(`taskkill /PID ${t} /T /F`,{timeout:hi.POWERSHELL_COMMAND}):process.kill(t,"SIGKILL"),$.info("SYSTEM","Killed process",{pid:t})}catch(e){$.debug("SYSTEM","Process already exited during force kill",{pid:t},e)}}async function qC(t,e){let r=Date.now();for(;Date.now()-r{try{return process.kill(i,0),!0}catch{return!1}});if(n.length===0){$.info("SYSTEM","All child processes exited");return}$.debug("SYSTEM","Waiting for processes to exit",{stillAlive:n}),await new Promise(i=>setTimeout(i,100))}$.warn("SYSTEM","Timeout waiting for child processes to exit")}function SW(t){if(!t||t.trim()==="")return-1;let e=t.trim(),r=0,n=e.match(/^(\d+)-(\d+):(\d+):(\d+)$/);if(n)return r=parseInt(n[1],10)*24*60+parseInt(n[2],10)*60+parseInt(n[3],10),r;let i=e.match(/^(\d+):(\d+):(\d+)$/);if(i)return r=parseInt(i[1],10)*60+parseInt(i[2],10),r;let a=e.match(/^(\d+):(\d+)$/);return a?parseInt(a[1],10):-1}async function FC(){let t=process.platform==="win32",e=process.pid,r=[];try{if(t){let i=`powershell -NoProfile -NonInteractive -Command "Get-CimInstance Win32_Process | Where-Object { (${NC.map(u=>`$_.CommandLine -like '*${u}*'`).join(" -or ")}) -and $_.ProcessId -ne ${e} } | Select-Object ProcessId, CreationDate | ConvertTo-Json"`,{stdout:a}=await $m(i,{timeout:hi.POWERSHELL_COMMAND});if(!a.trim()||a.trim()==="null"){$.debug("SYSTEM","No orphaned claude-mem processes found (Windows)");return}let s=JSON.parse(a),o=Array.isArray(s)?s:[s],c=Date.now();for(let u of o){let l=u.ProcessId;if(!Number.isInteger(l)||l<=0||l===e)continue;let d=u.CreationDate?.match(/\/Date\((\d+)\)\//);if(d){let p=parseInt(d[1],10),f=(c-p)/(1e3*60);f>=g0&&(r.push(l),$.debug("SYSTEM","Found orphaned process",{pid:l,ageMinutes:Math.round(f)}))}}}else{let n=NC.join("|"),{stdout:i}=await $m(`ps -eo pid,etime,command | grep -E "${n}" | grep -v grep || true`);if(!i.trim()){$.debug("SYSTEM","No orphaned claude-mem processes found (Unix)");return}let a=i.trim().split(` +`);for(let s of a){let o=s.trim().match(/^(\d+)\s+(\S+)\s+(.*)$/);if(!o)continue;let c=parseInt(o[1],10),u=o[2];if(!Number.isInteger(c)||c<=0||c===e)continue;let l=SW(u);l>=g0&&(r.push(c),$.debug("SYSTEM","Found orphaned process",{pid:c,ageMinutes:l,command:o[3].substring(0,80)}))}}}catch(n){$.error("SYSTEM","Failed to enumerate orphaned processes",{},n);return}if(r.length!==0){if($.info("SYSTEM","Cleaning up orphaned claude-mem processes",{platform:t?"Windows":"Unix",count:r.length,pids:r,maxAgeMinutes:g0}),t)for(let n of r){if(!Number.isInteger(n)||n<=0){$.warn("SYSTEM","Skipping invalid PID",{pid:n});continue}try{(0,ps.execSync)(`taskkill /PID ${n} /T /F`,{timeout:hi.POWERSHELL_COMMAND,stdio:"ignore"})}catch(i){$.debug("SYSTEM","Failed to kill process, may have already exited",{pid:n},i)}}else for(let n of r)try{process.kill(n,"SIGKILL")}catch(i){$.debug("SYSTEM","Process already exited",{pid:n},i)}$.info("SYSTEM","Orphaned processes cleaned up",{count:r.length})}}function y0(t,e,r={}){let n=process.platform==="win32",i={...process.env,CLAUDE_MEM_WORKER_PORT:String(e),...r};if(n){let c=`Start-Process -FilePath '${process.execPath}' -ArgumentList '${t}','--daemon' -WindowStyle Hidden`;try{return(0,ps.execSync)(`powershell -NoProfile -Command "${c}"`,{stdio:"ignore",windowsHide:!0,env:i}),0}catch{return}}let a=(0,ps.spawn)(process.execPath,[t,"--daemon"],{detached:!0,stdio:"ignore",env:i});if(a.pid!==void 0)return a.unref(),a.pid}function ZC(t,e){return async r=>{if(e.value){$.warn("SYSTEM",`Received ${r} but shutdown already in progress`);return}e.value=!0,$.info("SYSTEM",`Received ${r}, shutting down...`);try{await t(),process.exit(0)}catch(n){$.error("SYSTEM","Error during shutdown",{},n),process.exit(0)}}}var HC=nt(require("path"),1),BC=require("fs");Se();er();async function Ml(t){try{return(await fetch(`http://127.0.0.1:${t}/api/health`)).ok}catch{return!1}}async function Dl(t,e=3e4){let r=Date.now();for(;Date.now()-rsetTimeout(n,500))}return!1}async function km(t,e=1e4){let r=Date.now();for(;Date.now()-rsetTimeout(n,500))}return!1}async function Tm(t){try{let e=await fetch(`http://127.0.0.1:${t}/api/admin/shutdown`,{method:"POST"});return e.ok?!0:($.warn("SYSTEM","Shutdown request returned error",{port:t,status:e.status}),!1)}catch(e){return e instanceof Error&&e.message?.includes("ECONNREFUSED")?($.debug("SYSTEM","Worker already stopped",{port:t},e),!1):($.error("SYSTEM","Shutdown request failed unexpectedly",{port:t},e),!1)}}function xW(){let t=HC.default.join(yi,"package.json");return JSON.parse((0,BC.readFileSync)(t,"utf-8")).version}async function wW(t){try{let e=await fetch(`http://127.0.0.1:${t}/api/version`);return e.ok?(await e.json()).version:null}catch{return $.debug("SYSTEM","Could not fetch worker version",{port:t}),null}}async function VC(t){let e=xW(),r=await wW(t);return r?{matches:e===r,pluginVersion:e,workerVersion:r}:{matches:!0,pluginVersion:e,workerVersion:r}}Se();async function GC(t){$.info("SYSTEM","Shutdown initiated"),_i();let e=await UC(process.pid);if($.info("SYSTEM","Found child processes",{count:e.length,pids:e}),t.server&&(await EW(t.server),$.info("SYSTEM","HTTP server closed")),await t.sessionManager.shutdownAll(),t.mcpClient&&(await t.mcpClient.close(),$.info("SYSTEM","MCP client closed")),t.dbManager&&await t.dbManager.close(),e.length>0){$.info("SYSTEM","Force killing remaining children");for(let r of e)await LC(r);await qC(e,5e3)}$.info("SYSTEM","Worker shutdown complete")}async function EW(t){t.closeAllConnections(),process.platform==="win32"&&await new Promise(e=>setTimeout(e,500)),await new Promise((e,r)=>{t.close(n=>n?r(n):e())}),process.platform==="win32"&&(await new Promise(e=>setTimeout(e,500)),$.info("SYSTEM","Waited for Windows port cleanup"))}var n2=nt(jh(),1),EE=nt(require("fs"),1),$E=nt(require("path"),1);Se();var SE=nt(jh(),1),Y4=nt(X4(),1),Q4=nt(require("path"),1);er();Se();function xE(t){let e=[];e.push(SE.default.json({limit:"50mb"})),e.push((0,Y4.default)({origin:(i,a)=>{!i||i.startsWith("http://localhost:")||i.startsWith("http://127.0.0.1:")?a(null,!0):a(new Error("CORS not allowed"))},credentials:!1})),e.push((i,a,s)=>{let c=[".html",".js",".css",".svg",".png",".jpg",".jpeg",".webp",".woff",".woff2",".ttf",".eot"].some(h=>i.path.endsWith(h)),u=i.path==="/api/logs";if(i.path.startsWith("/health")||i.path==="/"||c||u)return s();let l=Date.now(),d=`${i.method}-${Date.now()}`,p=t(i.method,i.path,i.body);$.info("HTTP",`\u2192 ${i.method} ${i.path}`,{requestId:d},p);let f=a.send.bind(a);a.send=function(h){let y=Date.now()-l;return $.info("HTTP",`\u2190 ${a.statusCode} ${i.path}`,{requestId:d,duration:`${y}ms`}),f(h)},s()});let r=Qr(),n=Q4.default.join(r,"plugin","ui");return e.push(SE.default.static(n)),e}function Mh(t,e,r){let n=t.ip||t.connection.remoteAddress||"";if(!(n==="127.0.0.1"||n==="::1"||n==="::ffff:127.0.0.1"||n==="localhost")){$.warn("SECURITY","Admin endpoint access denied - not localhost",{endpoint:t.path,clientIp:n,method:t.method}),e.status(403).json({error:"Forbidden",message:"Admin endpoints are only accessible from localhost"});return}r()}function wE(t,e,r){if(!r||Object.keys(r).length===0||e.includes("/init"))return"";if(e.includes("/observations")){let n=r.tool_name||"?",i=r.tool_input;return`tool=${$.formatTool(n,i)}`}return e.includes("/summarize")?"requesting summary":""}Se();var lc=class extends Error{constructor(r,n=500,i,a){super(r);this.statusCode=n;this.code=i;this.details=a;this.name="AppError"}};function e2(t,e,r,n){let i={error:t,message:e};return r&&(i.code=r),n&&(i.details=n),i}var t2=(t,e,r,n)=>{let i=t instanceof lc?t.statusCode:500;$.error("HTTP",`Error handling ${e.method} ${e.path}`,{statusCode:i,error:t.message,code:t instanceof lc?t.code:void 0},t);let a=e2(t.name||"Error",t.message,t instanceof lc?t.code:void 0,t instanceof lc?t.details:void 0);r.status(i).json(a)};function r2(t,e){e.status(404).json(e2("NotFound",`Cannot ${t.method} ${t.path}`))}var Eie="10.0.0",Dh=class{app;server=null;options;startTime=Date.now();constructor(e){this.options=e,this.app=(0,n2.default)(),this.setupMiddleware(),this.setupCoreRoutes()}getHttpServer(){return this.server}async listen(e,r){return new Promise((n,i)=>{this.server=this.app.listen(e,r,()=>{$.info("SYSTEM","HTTP server started",{host:r,port:e,pid:process.pid}),n()}),this.server.on("error",i)})}async close(){this.server&&(this.server.closeAllConnections(),process.platform==="win32"&&await new Promise(e=>setTimeout(e,500)),await new Promise((e,r)=>{this.server.close(n=>n?r(n):e())}),process.platform==="win32"&&await new Promise(e=>setTimeout(e,500)),this.server=null,$.info("SYSTEM","HTTP server closed"))}registerRoutes(e){e.setupRoutes(this.app)}finalizeRoutes(){this.app.use(r2),this.app.use(t2)}setupMiddleware(){xE(wE).forEach(r=>this.app.use(r))}setupCoreRoutes(){let e="TEST-008-wrapper-ipc";this.app.get("/api/health",(r,n)=>{n.status(200).json({status:"ok",build:e,managed:process.env.CLAUDE_MEM_MANAGED==="true",hasIpc:typeof process.send=="function",platform:process.platform,pid:process.pid,initialized:this.options.getInitializationComplete(),mcpReady:this.options.getMcpReady()})}),this.app.get("/api/readiness",(r,n)=>{this.options.getInitializationComplete()?n.status(200).json({status:"ready",mcpReady:this.options.getMcpReady()}):n.status(503).json({status:"initializing",message:"Worker is still initializing, please retry"})}),this.app.get("/api/version",(r,n)=>{n.status(200).json({version:Eie})}),this.app.get("/api/instructions",async(r,n)=>{let i=r.query.topic||"all",a=r.query.operation;try{let s;if(a){let o=$E.default.join(__dirname,"../skills/mem-search/operations",`${a}.md`);s=await EE.promises.readFile(o,"utf-8")}else{let o=$E.default.join(__dirname,"../skills/mem-search/SKILL.md"),c=await EE.promises.readFile(o,"utf-8");s=this.extractInstructionSection(c,i)}n.json({content:[{type:"text",text:s}]})}catch{n.status(404).json({error:"Instruction not found"})}}),this.app.post("/api/admin/restart",Mh,async(r,n)=>{n.json({status:"restarting"}),process.platform==="win32"&&process.env.CLAUDE_MEM_MANAGED==="true"&&process.send?($.info("SYSTEM","Sending restart request to wrapper"),process.send({type:"restart"})):setTimeout(async()=>{await this.options.onRestart()},100)}),this.app.post("/api/admin/shutdown",Mh,async(r,n)=>{n.json({status:"shutting_down"}),process.platform==="win32"&&process.env.CLAUDE_MEM_MANAGED==="true"&&process.send?($.info("SYSTEM","Sending shutdown request to wrapper"),process.send({type:"shutdown"})):setTimeout(async()=>{await this.options.onShutdown()},100)})}extractInstructionSection(e,r){let n={workflow:this.extractBetween(e,"## The Workflow","## Search Parameters"),search_params:this.extractBetween(e,"## Search Parameters","## Examples"),examples:this.extractBetween(e,"## Examples","## Why This Workflow"),all:e};return n[r]||n.all}extractBetween(e,r,n){let i=e.indexOf(r),a=e.indexOf(n);return i===-1?e:a===-1?e.substring(i):e.substring(i,a).trim()}};var at=nt(require("path"),1),bd=require("os"),zt=require("fs"),s2=require("child_process"),o2=require("util");Se();Zr();er();var Cn=require("fs"),_d=require("path");Se();function i2(t){try{return(0,Cn.existsSync)(t)?JSON.parse((0,Cn.readFileSync)(t,"utf-8")):{}}catch(e){return $.error("CONFIG","Failed to read Cursor registry, using empty registry",{file:t,error:e instanceof Error?e.message:String(e)}),{}}}function a2(t,e){let r=(0,_d.join)(t,"..");(0,Cn.mkdirSync)(r,{recursive:!0}),(0,Cn.writeFileSync)(t,JSON.stringify(e,null,2))}function kE(t,e){let r=(0,_d.join)(t,".cursor","rules"),n=(0,_d.join)(r,"claude-mem-context.mdc"),i=`${n}.tmp`;(0,Cn.mkdirSync)(r,{recursive:!0});let a=`--- alwaysApply: true description: "Claude-mem context from past sessions (auto-updated)" --- @@ -1070,8 +1070,8 @@ For more info: https://docs.claude-mem.ai/cursor FROM user_prompts WHERE content_session_id = ? ORDER BY prompt_number ASC - `).all(e)}close(){this.db.close()}};zh();Se();lr();er();var OE=nt(require("path"),1),RE=nt(require("os"),1),Rs=nt(require("fs"),1),PE=require("child_process"),Aie="9.1.1",Lh=class{client=null;transport=null;connected=!1;project;collectionName;VECTOR_DB_DIR;BATCH_SIZE=100;disabled;constructor(e){this.project=e,this.collectionName=`cm__${e}`,this.VECTOR_DB_DIR=OE.default.join(RE.default.homedir(),".claude-mem","vector-db"),this.disabled=process.platform==="win32",this.disabled&&$.warn("CHROMA_SYNC","Vector search disabled on Windows (prevents console popups)",{project:this.project,reason:"MCP SDK subprocess spawning causes visible console windows"})}getCombinedCertPath(){let e=OE.default.join(RE.default.homedir(),".claude-mem","combined_certs.pem");if(Rs.default.existsSync(e)){let r=Rs.default.statSync(e);if(Date.now()-r.mtimeMs<1440*60*1e3)return e}if(process.platform==="darwin")try{let r;try{r=(0,PE.execSync)('uvx --with certifi python -c "import certifi; print(certifi.where())"',{encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:1e4}).trim()}catch{return}if(!r||!Rs.default.existsSync(r))return;let n="";try{n=(0,PE.execSync)('security find-certificate -a -c "Zscaler" -p /Library/Keychains/System.keychain',{encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:5e3})}catch{return}if(!n||!n.includes("-----BEGIN CERTIFICATE-----")||!n.includes("-----END CERTIFICATE-----"))return;let i=Rs.default.readFileSync(r,"utf8"),a=e+".tmp";return Rs.default.writeFileSync(a,i+` -`+n),Rs.default.renameSync(a,e),$.info("CHROMA_SYNC","Created combined SSL certificate bundle for Zscaler",{path:e}),e}catch(r){$.debug("CHROMA_SYNC","Could not create combined cert bundle",{},r);return}}isDisabled(){return this.disabled}async ensureConnection(){if(!(this.connected&&this.client)){$.info("CHROMA_SYNC","Connecting to Chroma MCP server...",{project:this.project});try{let r=Ae.loadFromFile(pr).CLAUDE_MEM_PYTHON_VERSION,n=process.platform==="win32",i=this.getCombinedCertPath(),a={command:"uvx",args:["--python",r,"chroma-mcp","--client-type","persistent","--data-dir",this.VECTOR_DB_DIR],stderr:"ignore"};i&&(a.env={...process.env,SSL_CERT_FILE:i,REQUESTS_CA_BUNDLE:i,CURL_CA_BUNDLE:i},$.info("CHROMA_SYNC","Using combined SSL certificates for Zscaler compatibility",{certPath:i})),n&&(a.windowsHide=!0,$.debug("CHROMA_SYNC","Windows detected, attempting to hide console window",{project:this.project})),this.transport=new Do(a),this.client=new Ao({name:"claude-mem-chroma-sync",version:Aie},{capabilities:{}}),await this.client.connect(this.transport),this.connected=!0,$.info("CHROMA_SYNC","Connected to Chroma MCP server",{project:this.project})}catch(e){throw $.error("CHROMA_SYNC","Failed to connect to Chroma MCP server",{project:this.project},e),new Error(`Chroma connection failed: ${e instanceof Error?e.message:String(e)}`)}}}async ensureCollection(){if(await this.ensureConnection(),!this.client)throw new Error(`Chroma client not initialized. Call ensureConnection() before using client methods. Project: ${this.project}`);try{await this.client.callTool({name:"chroma_get_collection_info",arguments:{collection_name:this.collectionName}}),$.debug("CHROMA_SYNC","Collection exists",{collection:this.collectionName})}catch(e){let r=e instanceof Error?e.message:String(e);if(r.includes("Not connected")||r.includes("Connection closed")||r.includes("MCP error -32000")){if(this.transport)try{await this.transport.close()}catch(i){$.debug("CHROMA_SYNC","Transport close error (expected if already dead)",{},i)}throw this.connected=!1,this.client=null,this.transport=null,$.error("CHROMA_SYNC","Connection lost during collection check",{collection:this.collectionName},e),new Error(`Chroma connection lost: ${r}`)}$.error("CHROMA_SYNC","Collection check failed, attempting to create",{collection:this.collectionName},e),$.info("CHROMA_SYNC","Creating collection",{collection:this.collectionName});try{await this.client.callTool({name:"chroma_create_collection",arguments:{collection_name:this.collectionName,embedding_function_name:"default"}}),$.info("CHROMA_SYNC","Collection created",{collection:this.collectionName})}catch(i){throw $.error("CHROMA_SYNC","Failed to create collection",{collection:this.collectionName},i),new Error(`Collection creation failed: ${i instanceof Error?i.message:String(i)}`)}}}formatObservationDocs(e){let r=[],n=e.facts?JSON.parse(e.facts):[],i=e.concepts?JSON.parse(e.concepts):[],a=e.files_read?JSON.parse(e.files_read):[],s=e.files_modified?JSON.parse(e.files_modified):[],o={sqlite_id:e.id,doc_type:"observation",memory_session_id:e.memory_session_id,project:e.project,created_at_epoch:e.created_at_epoch,type:e.type||"discovery",title:e.title||"Untitled"};return e.subtitle&&(o.subtitle=e.subtitle),i.length>0&&(o.concepts=i.join(",")),a.length>0&&(o.files_read=a.join(",")),s.length>0&&(o.files_modified=s.join(",")),e.narrative&&r.push({id:`obs_${e.id}_narrative`,document:e.narrative,metadata:{...o,field_type:"narrative"}}),e.text&&r.push({id:`obs_${e.id}_text`,document:e.text,metadata:{...o,field_type:"text"}}),n.forEach((c,u)=>{r.push({id:`obs_${e.id}_fact_${u}`,document:c,metadata:{...o,field_type:"fact",fact_index:u}})}),r}formatSummaryDocs(e){let r=[],n={sqlite_id:e.id,doc_type:"session_summary",memory_session_id:e.memory_session_id,project:e.project,created_at_epoch:e.created_at_epoch,prompt_number:e.prompt_number||0};return e.request&&r.push({id:`summary_${e.id}_request`,document:e.request,metadata:{...n,field_type:"request"}}),e.investigated&&r.push({id:`summary_${e.id}_investigated`,document:e.investigated,metadata:{...n,field_type:"investigated"}}),e.learned&&r.push({id:`summary_${e.id}_learned`,document:e.learned,metadata:{...n,field_type:"learned"}}),e.completed&&r.push({id:`summary_${e.id}_completed`,document:e.completed,metadata:{...n,field_type:"completed"}}),e.next_steps&&r.push({id:`summary_${e.id}_next_steps`,document:e.next_steps,metadata:{...n,field_type:"next_steps"}}),e.notes&&r.push({id:`summary_${e.id}_notes`,document:e.notes,metadata:{...n,field_type:"notes"}}),r}async addDocuments(e){if(e.length!==0){if(await this.ensureCollection(),!this.client)throw new Error(`Chroma client not initialized. Call ensureConnection() before using client methods. Project: ${this.project}`);try{await this.client.callTool({name:"chroma_add_documents",arguments:{collection_name:this.collectionName,documents:e.map(r=>r.document),ids:e.map(r=>r.id),metadatas:e.map(r=>r.metadata)}}),$.debug("CHROMA_SYNC","Documents added",{collection:this.collectionName,count:e.length})}catch(r){throw $.error("CHROMA_SYNC","Failed to add documents",{collection:this.collectionName,count:e.length},r),new Error(`Document add failed: ${r instanceof Error?r.message:String(r)}`)}}}async syncObservation(e,r,n,i,a,s,o=0){if(this.disabled)return;let c={id:e,memory_session_id:r,project:n,text:null,type:i.type,title:i.title,subtitle:i.subtitle,facts:JSON.stringify(i.facts),narrative:i.narrative,concepts:JSON.stringify(i.concepts),files_read:JSON.stringify(i.files_read),files_modified:JSON.stringify(i.files_modified),prompt_number:a,discovery_tokens:o,created_at:new Date(s*1e3).toISOString(),created_at_epoch:s},u=this.formatObservationDocs(c);$.info("CHROMA_SYNC","Syncing observation",{observationId:e,documentCount:u.length,project:n}),await this.addDocuments(u)}async syncSummary(e,r,n,i,a,s,o=0){if(this.disabled)return;let c={id:e,memory_session_id:r,project:n,request:i.request,investigated:i.investigated,learned:i.learned,completed:i.completed,next_steps:i.next_steps,notes:i.notes,prompt_number:a,discovery_tokens:o,created_at:new Date(s*1e3).toISOString(),created_at_epoch:s},u=this.formatSummaryDocs(c);$.info("CHROMA_SYNC","Syncing summary",{summaryId:e,documentCount:u.length,project:n}),await this.addDocuments(u)}formatUserPromptDoc(e){return{id:`prompt_${e.id}`,document:e.prompt_text,metadata:{sqlite_id:e.id,doc_type:"user_prompt",memory_session_id:e.memory_session_id,project:e.project,created_at_epoch:e.created_at_epoch,prompt_number:e.prompt_number}}}async syncUserPrompt(e,r,n,i,a,s){if(this.disabled)return;let o={id:e,content_session_id:"",prompt_number:a,prompt_text:i,created_at:new Date(s*1e3).toISOString(),created_at_epoch:s,memory_session_id:r,project:n},c=this.formatUserPromptDoc(o);$.info("CHROMA_SYNC","Syncing user prompt",{promptId:e,project:n}),await this.addDocuments([c])}async getExistingChromaIds(){if(await this.ensureConnection(),!this.client)throw new Error(`Chroma client not initialized. Call ensureConnection() before using client methods. Project: ${this.project}`);let e=new Set,r=new Set,n=new Set,i=0,a=1e3;for($.info("CHROMA_SYNC","Fetching existing Chroma document IDs...",{project:this.project});;)try{let o=(await this.client.callTool({name:"chroma_get_documents",arguments:{collection_name:this.collectionName,limit:a,offset:i,where:{project:this.project},include:["metadatas"]}})).content[0];if(o.type!=="text")throw new Error("Unexpected response type from chroma_get_documents");let u=JSON.parse(o.text).metadatas||[];if(u.length===0)break;for(let l of u)l.sqlite_id&&(l.doc_type==="observation"?e.add(l.sqlite_id):l.doc_type==="session_summary"?r.add(l.sqlite_id):l.doc_type==="user_prompt"&&n.add(l.sqlite_id));i+=a,$.debug("CHROMA_SYNC","Fetched batch of existing IDs",{project:this.project,offset:i,batchSize:u.length})}catch(s){throw $.error("CHROMA_SYNC","Failed to fetch existing IDs",{project:this.project},s),s}return $.info("CHROMA_SYNC","Existing IDs fetched",{project:this.project,observations:e.size,summaries:r.size,prompts:n.size}),{observations:e,summaries:r,prompts:n}}async ensureBackfilled(){if(this.disabled)return;$.info("CHROMA_SYNC","Starting smart backfill",{project:this.project}),await this.ensureCollection();let e=await this.getExistingChromaIds(),r=new Ca;try{let n=Array.from(e.observations),i=n.length>0?`AND id NOT IN (${n.join(",")})`:"",a=r.db.prepare(` + `).all(e)}close(){this.db.close()}};zh();Se();lr();er();var OE=nt(require("path"),1),RE=nt(require("os"),1),Rs=nt(require("fs"),1),PE=require("child_process"),Aie="10.0.0",Lh=class{client=null;transport=null;connected=!1;project;collectionName;VECTOR_DB_DIR;BATCH_SIZE=100;disabled=!1;constructor(e){this.project=e,this.collectionName=`cm__${e}`,this.VECTOR_DB_DIR=OE.default.join(RE.default.homedir(),".claude-mem","vector-db")}getCombinedCertPath(){let e=OE.default.join(RE.default.homedir(),".claude-mem","combined_certs.pem");if(Rs.default.existsSync(e)){let r=Rs.default.statSync(e);if(Date.now()-r.mtimeMs<1440*60*1e3)return e}if(process.platform==="darwin")try{let r;try{r=(0,PE.execSync)('uvx --with certifi python -c "import certifi; print(certifi.where())"',{encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:1e4}).trim()}catch{return}if(!r||!Rs.default.existsSync(r))return;let n="";try{n=(0,PE.execSync)('security find-certificate -a -c "Zscaler" -p /Library/Keychains/System.keychain',{encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:5e3})}catch{return}if(!n||!n.includes("-----BEGIN CERTIFICATE-----")||!n.includes("-----END CERTIFICATE-----"))return;let i=Rs.default.readFileSync(r,"utf8"),a=e+".tmp";return Rs.default.writeFileSync(a,i+` +`+n),Rs.default.renameSync(a,e),$.info("CHROMA_SYNC","Created combined SSL certificate bundle for Zscaler",{path:e}),e}catch(r){$.debug("CHROMA_SYNC","Could not create combined cert bundle",{},r);return}}isDisabled(){return this.disabled}async ensureConnection(){if(!(this.connected&&this.client)){$.info("CHROMA_SYNC","Connecting to Chroma MCP server...",{project:this.project});try{let r=Ae.loadFromFile(pr).CLAUDE_MEM_PYTHON_VERSION,n=this.getCombinedCertPath(),i={command:"uvx",args:["--python",r,"chroma-mcp","--client-type","persistent","--data-dir",this.VECTOR_DB_DIR],stderr:"ignore"};n&&(i.env={...process.env,SSL_CERT_FILE:n,REQUESTS_CA_BUNDLE:n,CURL_CA_BUNDLE:n},$.info("CHROMA_SYNC","Using combined SSL certificates for Zscaler compatibility",{certPath:n})),this.transport=new Do(i),this.client=new Ao({name:"claude-mem-chroma-sync",version:Aie},{capabilities:{}}),await this.client.connect(this.transport),this.connected=!0,$.info("CHROMA_SYNC","Connected to Chroma MCP server",{project:this.project})}catch(e){throw $.error("CHROMA_SYNC","Failed to connect to Chroma MCP server",{project:this.project},e),new Error(`Chroma connection failed: ${e instanceof Error?e.message:String(e)}`)}}}async ensureCollection(){if(await this.ensureConnection(),!this.client)throw new Error(`Chroma client not initialized. Call ensureConnection() before using client methods. Project: ${this.project}`);try{await this.client.callTool({name:"chroma_get_collection_info",arguments:{collection_name:this.collectionName}}),$.debug("CHROMA_SYNC","Collection exists",{collection:this.collectionName})}catch(e){let r=e instanceof Error?e.message:String(e);if(r.includes("Not connected")||r.includes("Connection closed")||r.includes("MCP error -32000")){if(this.transport)try{await this.transport.close()}catch(i){$.debug("CHROMA_SYNC","Transport close error (expected if already dead)",{},i)}throw this.connected=!1,this.client=null,this.transport=null,$.error("CHROMA_SYNC","Connection lost during collection check",{collection:this.collectionName},e),new Error(`Chroma connection lost: ${r}`)}$.error("CHROMA_SYNC","Collection check failed, attempting to create",{collection:this.collectionName},e),$.info("CHROMA_SYNC","Creating collection",{collection:this.collectionName});try{await this.client.callTool({name:"chroma_create_collection",arguments:{collection_name:this.collectionName,embedding_function_name:"default"}}),$.info("CHROMA_SYNC","Collection created",{collection:this.collectionName})}catch(i){throw $.error("CHROMA_SYNC","Failed to create collection",{collection:this.collectionName},i),new Error(`Collection creation failed: ${i instanceof Error?i.message:String(i)}`)}}}formatObservationDocs(e){let r=[],n=e.facts?JSON.parse(e.facts):[],i=e.concepts?JSON.parse(e.concepts):[],a=e.files_read?JSON.parse(e.files_read):[],s=e.files_modified?JSON.parse(e.files_modified):[],o={sqlite_id:e.id,doc_type:"observation",memory_session_id:e.memory_session_id,project:e.project,created_at_epoch:e.created_at_epoch,type:e.type||"discovery",title:e.title||"Untitled"};return e.subtitle&&(o.subtitle=e.subtitle),i.length>0&&(o.concepts=i.join(",")),a.length>0&&(o.files_read=a.join(",")),s.length>0&&(o.files_modified=s.join(",")),e.narrative&&r.push({id:`obs_${e.id}_narrative`,document:e.narrative,metadata:{...o,field_type:"narrative"}}),e.text&&r.push({id:`obs_${e.id}_text`,document:e.text,metadata:{...o,field_type:"text"}}),n.forEach((c,u)=>{r.push({id:`obs_${e.id}_fact_${u}`,document:c,metadata:{...o,field_type:"fact",fact_index:u}})}),r}formatSummaryDocs(e){let r=[],n={sqlite_id:e.id,doc_type:"session_summary",memory_session_id:e.memory_session_id,project:e.project,created_at_epoch:e.created_at_epoch,prompt_number:e.prompt_number||0};return e.request&&r.push({id:`summary_${e.id}_request`,document:e.request,metadata:{...n,field_type:"request"}}),e.investigated&&r.push({id:`summary_${e.id}_investigated`,document:e.investigated,metadata:{...n,field_type:"investigated"}}),e.learned&&r.push({id:`summary_${e.id}_learned`,document:e.learned,metadata:{...n,field_type:"learned"}}),e.completed&&r.push({id:`summary_${e.id}_completed`,document:e.completed,metadata:{...n,field_type:"completed"}}),e.next_steps&&r.push({id:`summary_${e.id}_next_steps`,document:e.next_steps,metadata:{...n,field_type:"next_steps"}}),e.notes&&r.push({id:`summary_${e.id}_notes`,document:e.notes,metadata:{...n,field_type:"notes"}}),r}async addDocuments(e){if(e.length!==0){if(await this.ensureCollection(),!this.client)throw new Error(`Chroma client not initialized. Call ensureConnection() before using client methods. Project: ${this.project}`);try{await this.client.callTool({name:"chroma_add_documents",arguments:{collection_name:this.collectionName,documents:e.map(r=>r.document),ids:e.map(r=>r.id),metadatas:e.map(r=>r.metadata)}}),$.debug("CHROMA_SYNC","Documents added",{collection:this.collectionName,count:e.length})}catch(r){throw $.error("CHROMA_SYNC","Failed to add documents",{collection:this.collectionName,count:e.length},r),new Error(`Document add failed: ${r instanceof Error?r.message:String(r)}`)}}}async syncObservation(e,r,n,i,a,s,o=0){if(this.disabled)return;let c={id:e,memory_session_id:r,project:n,text:null,type:i.type,title:i.title,subtitle:i.subtitle,facts:JSON.stringify(i.facts),narrative:i.narrative,concepts:JSON.stringify(i.concepts),files_read:JSON.stringify(i.files_read),files_modified:JSON.stringify(i.files_modified),prompt_number:a,discovery_tokens:o,created_at:new Date(s*1e3).toISOString(),created_at_epoch:s},u=this.formatObservationDocs(c);$.info("CHROMA_SYNC","Syncing observation",{observationId:e,documentCount:u.length,project:n}),await this.addDocuments(u)}async syncSummary(e,r,n,i,a,s,o=0){if(this.disabled)return;let c={id:e,memory_session_id:r,project:n,request:i.request,investigated:i.investigated,learned:i.learned,completed:i.completed,next_steps:i.next_steps,notes:i.notes,prompt_number:a,discovery_tokens:o,created_at:new Date(s*1e3).toISOString(),created_at_epoch:s},u=this.formatSummaryDocs(c);$.info("CHROMA_SYNC","Syncing summary",{summaryId:e,documentCount:u.length,project:n}),await this.addDocuments(u)}formatUserPromptDoc(e){return{id:`prompt_${e.id}`,document:e.prompt_text,metadata:{sqlite_id:e.id,doc_type:"user_prompt",memory_session_id:e.memory_session_id,project:e.project,created_at_epoch:e.created_at_epoch,prompt_number:e.prompt_number}}}async syncUserPrompt(e,r,n,i,a,s){if(this.disabled)return;let o={id:e,content_session_id:"",prompt_number:a,prompt_text:i,created_at:new Date(s*1e3).toISOString(),created_at_epoch:s,memory_session_id:r,project:n},c=this.formatUserPromptDoc(o);$.info("CHROMA_SYNC","Syncing user prompt",{promptId:e,project:n}),await this.addDocuments([c])}async getExistingChromaIds(){if(await this.ensureConnection(),!this.client)throw new Error(`Chroma client not initialized. Call ensureConnection() before using client methods. Project: ${this.project}`);let e=new Set,r=new Set,n=new Set,i=0,a=1e3;for($.info("CHROMA_SYNC","Fetching existing Chroma document IDs...",{project:this.project});;)try{let o=(await this.client.callTool({name:"chroma_get_documents",arguments:{collection_name:this.collectionName,limit:a,offset:i,where:{project:this.project},include:["metadatas"]}})).content[0];if(o.type!=="text")throw new Error("Unexpected response type from chroma_get_documents");let u=JSON.parse(o.text).metadatas||[];if(u.length===0)break;for(let l of u)l.sqlite_id&&(l.doc_type==="observation"?e.add(l.sqlite_id):l.doc_type==="session_summary"?r.add(l.sqlite_id):l.doc_type==="user_prompt"&&n.add(l.sqlite_id));i+=a,$.debug("CHROMA_SYNC","Fetched batch of existing IDs",{project:this.project,offset:i,batchSize:u.length})}catch(s){throw $.error("CHROMA_SYNC","Failed to fetch existing IDs",{project:this.project},s),s}return $.info("CHROMA_SYNC","Existing IDs fetched",{project:this.project,observations:e.size,summaries:r.size,prompts:n.size}),{observations:e,summaries:r,prompts:n}}async ensureBackfilled(){if(this.disabled)return;$.info("CHROMA_SYNC","Starting smart backfill",{project:this.project}),await this.ensureCollection();let e=await this.getExistingChromaIds(),r=new Ca;try{let n=Array.from(e.observations),i=n.length>0?`AND id NOT IN (${n.join(",")})`:"",a=r.db.prepare(` SELECT * FROM observations WHERE project = ? ${i} ORDER BY id ASC @@ -1239,8 +1239,8 @@ ${n.prompts.format_examples} ${n.prompts.footer} -${n.prompts.header_memory_continued}`}lr();er();var hc=require("fs"),NE=require("path"),w2=require("os");Se();var Uie=(0,NE.join)((0,w2.homedir)(),".claude-mem"),CE=(0,NE.join)(Uie,".env"),Lie=["PATH","HOME","USER","SHELL","TMPDIR","TMP","TEMP","LANG","LC_ALL","LC_CTYPE","NODE_ENV","NODE_PATH","SYSTEMROOT","WINDIR","PROGRAMFILES","APPDATA","LOCALAPPDATA","XDG_RUNTIME_DIR","XDG_CONFIG_HOME","XDG_DATA_HOME","CLAUDE_CONFIG_DIR","CLAUDE_CODE_DEBUG_LOGS_DIR"];function qie(t){let e={};for(let r of t.split(` -`)){let n=r.trim();if(!n||n.startsWith("#"))continue;let i=n.indexOf("=");if(i===-1)continue;let a=n.slice(0,i).trim(),s=n.slice(i+1).trim();(s.startsWith('"')&&s.endsWith('"')||s.startsWith("'")&&s.endsWith("'"))&&(s=s.slice(1,-1)),a&&(e[a]=s)}return e}function AE(){if(!(0,hc.existsSync)(CE))return{};try{let t=(0,hc.readFileSync)(CE,"utf-8"),e=qie(t),r={};return e.ANTHROPIC_API_KEY&&(r.ANTHROPIC_API_KEY=e.ANTHROPIC_API_KEY),e.GEMINI_API_KEY&&(r.GEMINI_API_KEY=e.GEMINI_API_KEY),e.OPENROUTER_API_KEY&&(r.OPENROUTER_API_KEY=e.OPENROUTER_API_KEY),r}catch(t){return $.warn("ENV","Failed to load .env file",{path:CE},t),{}}}function E2(t=!0){let e={};for(let r of Lie){let n=process.env[r];n!==void 0&&(e[r]=n)}if(e.CLAUDE_CODE_ENTRYPOINT="sdk-ts",t){let r=AE();r.ANTHROPIC_API_KEY&&(e.ANTHROPIC_API_KEY=r.ANTHROPIC_API_KEY),r.GEMINI_API_KEY&&(e.GEMINI_API_KEY=r.GEMINI_API_KEY),r.OPENROUTER_API_KEY&&(e.OPENROUTER_API_KEY=r.OPENROUTER_API_KEY)}return e}function gc(t){return AE()[t]}function Fie(){return!!AE().ANTHROPIC_API_KEY}function $2(){return Fie()?"API key (from ~/.claude-mem/.env)":"Claude Code CLI (subscription billing)"}Vr();var jE=["429","500","502","503","ECONNREFUSED","ETIMEDOUT","fetch failed"];Se();Se();Vr();function T2(t,e){let r=[],n=/([\s\S]*?)<\/observation>/g,i;for(;(i=n.exec(t))!==null;){let a=i[1],s=Ti(a,"type"),o=Ti(a,"title"),c=Ti(a,"subtitle"),u=Ti(a,"narrative"),l=Kh(a,"facts","fact"),d=Kh(a,"concepts","concept"),p=Kh(a,"files_read","file"),f=Kh(a,"files_modified","file"),y=Ve.getInstance().getActiveMode().observation_types.map(v=>v.id),g=y[0],m=g;s?y.includes(s.trim())?m=s.trim():$.error("PARSER",`Invalid observation type: ${s}, using "${g}"`,{correlationId:e}):$.error("PARSER",`Observation missing type field, using "${g}"`,{correlationId:e});let _=d.filter(v=>v!==m);_.length!==d.length&&$.error("PARSER","Removed observation type from concepts array",{correlationId:e,type:m,originalConcepts:d,cleanedConcepts:_}),r.push({type:m,title:o,subtitle:c,facts:l,narrative:u,concepts:_,files_read:p,files_modified:f})}return r}function I2(t,e){let n=//.exec(t);if(n)return $.info("PARSER","Summary skipped",{sessionId:e,reason:n[1]}),null;let a=/([\s\S]*?)<\/summary>/.exec(t);if(!a)return null;let s=a[1],o=Ti(s,"request"),c=Ti(s,"investigated"),u=Ti(s,"learned"),l=Ti(s,"completed"),d=Ti(s,"next_steps"),p=Ti(s,"notes");return{request:o,investigated:c,learned:u,completed:l,next_steps:d,notes:p}}function Ti(t,e){let n=new RegExp(`<${e}>([\\s\\S]*?)`).exec(t);if(!n)return null;let i=n[1].trim();return i===""?null:i}function Kh(t,e,r){let n=[],a=new RegExp(`<${e}>([\\s\\S]*?)`).exec(t);if(!a)return n;let s=a[1],o=new RegExp(`<${r}>([\\s\\S]*?)`,"g"),c;for(;(c=o.exec(s))!==null;){let u=c[1].trim();u&&n.push(u)}return n}var Qn=require("fs"),Yt=nt(require("path"),1),R2=nt(require("os"),1);Se();Cs();lr();Zr();var Zie=Yt.default.join(R2.default.homedir(),".claude-mem","settings.json");function Hie(t){let e=t.split(Yt.default.sep).filter(r=>r&&r!=="."&&r!=="..");for(let r=1;r([\s\S]*?)<\/observation>/g,i;for(;(i=n.exec(t))!==null;){let a=i[1],s=Ti(a,"type"),o=Ti(a,"title"),c=Ti(a,"subtitle"),u=Ti(a,"narrative"),l=Kh(a,"facts","fact"),d=Kh(a,"concepts","concept"),p=Kh(a,"files_read","file"),f=Kh(a,"files_modified","file"),y=Ve.getInstance().getActiveMode().observation_types.map(v=>v.id),g=y[0],m=g;s?y.includes(s.trim())?m=s.trim():$.error("PARSER",`Invalid observation type: ${s}, using "${g}"`,{correlationId:e}):$.error("PARSER",`Observation missing type field, using "${g}"`,{correlationId:e});let _=d.filter(v=>v!==m);_.length!==d.length&&$.error("PARSER","Removed observation type from concepts array",{correlationId:e,type:m,originalConcepts:d,cleanedConcepts:_}),r.push({type:m,title:o,subtitle:c,facts:l,narrative:u,concepts:_,files_read:p,files_modified:f})}return r}function I2(t,e){let n=//.exec(t);if(n)return $.info("PARSER","Summary skipped",{sessionId:e,reason:n[1]}),null;let a=/([\s\S]*?)<\/summary>/.exec(t);if(!a)return null;let s=a[1],o=Ti(s,"request"),c=Ti(s,"investigated"),u=Ti(s,"learned"),l=Ti(s,"completed"),d=Ti(s,"next_steps"),p=Ti(s,"notes");return{request:o,investigated:c,learned:u,completed:l,next_steps:d,notes:p}}function Ti(t,e){let n=new RegExp(`<${e}>([\\s\\S]*?)`).exec(t);if(!n)return null;let i=n[1].trim();return i===""?null:i}function Kh(t,e,r){let n=[],a=new RegExp(`<${e}>([\\s\\S]*?)`).exec(t);if(!a)return n;let s=a[1],o=new RegExp(`<${r}>([\\s\\S]*?)`,"g"),c;for(;(c=o.exec(s))!==null;){let u=c[1].trim();u&&n.push(u)}return n}var Qn=require("fs"),Yt=nt(require("path"),1),R2=nt(require("os"),1);Se();Cs();lr();Zr();var Zie=Yt.default.join(R2.default.homedir(),".claude-mem","settings.json");function Hie(t){let e=t.split(Yt.default.sep).filter(r=>r&&r!=="."&&r!=="..");for(let r=1;ro.project);n.json({projects:s})});handleGetProcessingStatus=this.wrapHandler((r,n)=>{let i=this.sessionManager.isAnySessionProcessing(),a=this.sessionManager.getTotalActiveWork();n.json({isProcessing:i,queueDepth:a})});handleSetProcessing=this.wrapHandler((r,n)=>{this.workerService.broadcastProcessingStatus();let i=this.sessionManager.isAnySessionProcessing(),a=this.sessionManager.getTotalQueueDepth(),s=this.sessionManager.getActiveSessionCount();n.json({status:"ok",isProcessing:i,queueDepth:a,activeSessions:s})});parsePaginationParams(r){let n=parseInt(r.query.offset,10)||0,i=Math.min(parseInt(r.query.limit,10)||20,100),a=r.query.project;return{offset:n,limit:i,project:a}}handleImport=this.wrapHandler((r,n)=>{let{sessions:i,summaries:a,observations:s,prompts:o}=r.body,c={sessionsImported:0,sessionsSkipped:0,summariesImported:0,summariesSkipped:0,observationsImported:0,observationsSkipped:0,promptsImported:0,promptsSkipped:0},u=this.dbManager.getSessionStore();if(Array.isArray(i))for(let l of i)u.importSdkSession(l).imported?c.sessionsImported++:c.sessionsSkipped++;if(Array.isArray(a))for(let l of a)u.importSessionSummary(l).imported?c.summariesImported++:c.summariesSkipped++;if(Array.isArray(s))for(let l of s)u.importObservation(l).imported?c.observationsImported++:c.observationsSkipped++;if(Array.isArray(o))for(let l of o)u.importUserPrompt(l).imported?c.promptsImported++:c.promptsSkipped++;n.json({success:!0,stats:c})});handleGetPendingQueue=this.wrapHandler((r,n)=>{let{PendingMessageStore:i}=(Na(),Kc(Ps)),a=new i(this.dbManager.getSessionStore().db,3),s=a.getQueueMessages(),o=a.getRecentlyProcessed(20,30),c=a.getStuckCount(300*1e3),u=a.getSessionsWithPendingMessages();n.json({queue:{messages:s,totalPending:s.filter(l=>l.status==="pending").length,totalProcessing:s.filter(l=>l.status==="processing").length,totalFailed:s.filter(l=>l.status==="failed").length,stuckCount:c},recentlyProcessed:o,sessionsWithPendingWork:u})});handleProcessPendingQueue=this.wrapHandler(async(r,n)=>{let i=Math.min(Math.max(parseInt(r.body.sessionLimit,10)||10,1),100),a=await this.workerService.processPendingQueues(i);n.json({success:!0,...a})});handleClearFailedQueue=this.wrapHandler((r,n)=>{let{PendingMessageStore:i}=(Na(),Kc(Ps)),s=new i(this.dbManager.getSessionStore().db,3).clearFailed();$.info("QUEUE","Cleared failed queue messages",{clearedCount:s}),n.json({success:!0,clearedCount:s})});handleClearAllQueue=this.wrapHandler((r,n)=>{let{PendingMessageStore:i}=(Na(),Kc(Ps)),s=new i(this.dbManager.getSessionStore().db,3).clearAll();$.warn("QUEUE","Cleared ALL queue messages (pending, processing, failed)",{clearedCount:s}),n.json({success:!0,clearedCount:s})})};var tv=class extends jr{constructor(r){super();this.searchManager=r}setupRoutes(r){r.get("/api/search",this.handleUnifiedSearch.bind(this)),r.get("/api/timeline",this.handleUnifiedTimeline.bind(this)),r.get("/api/decisions",this.handleDecisions.bind(this)),r.get("/api/changes",this.handleChanges.bind(this)),r.get("/api/how-it-works",this.handleHowItWorks.bind(this)),r.get("/api/search/observations",this.handleSearchObservations.bind(this)),r.get("/api/search/sessions",this.handleSearchSessions.bind(this)),r.get("/api/search/prompts",this.handleSearchPrompts.bind(this)),r.get("/api/search/by-concept",this.handleSearchByConcept.bind(this)),r.get("/api/search/by-file",this.handleSearchByFile.bind(this)),r.get("/api/search/by-type",this.handleSearchByType.bind(this)),r.get("/api/context/recent",this.handleGetRecentContext.bind(this)),r.get("/api/context/timeline",this.handleGetContextTimeline.bind(this)),r.get("/api/context/preview",this.handleContextPreview.bind(this)),r.get("/api/context/inject",this.handleContextInject.bind(this)),r.get("/api/timeline/by-query",this.handleGetTimelineByQuery.bind(this)),r.get("/api/search/help",this.handleSearchHelp.bind(this))}handleUnifiedSearch=this.wrapHandler(async(r,n)=>{let i=await this.searchManager.search(r.query);n.json(i)});handleUnifiedTimeline=this.wrapHandler(async(r,n)=>{let i=await this.searchManager.timeline(r.query);n.json(i)});handleDecisions=this.wrapHandler(async(r,n)=>{let i=await this.searchManager.decisions(r.query);n.json(i)});handleChanges=this.wrapHandler(async(r,n)=>{let i=await this.searchManager.changes(r.query);n.json(i)});handleHowItWorks=this.wrapHandler(async(r,n)=>{let i=await this.searchManager.howItWorks(r.query);n.json(i)});handleSearchObservations=this.wrapHandler(async(r,n)=>{let i=await this.searchManager.searchObservations(r.query);n.json(i)});handleSearchSessions=this.wrapHandler(async(r,n)=>{let i=await this.searchManager.searchSessions(r.query);n.json(i)});handleSearchPrompts=this.wrapHandler(async(r,n)=>{let i=await this.searchManager.searchUserPrompts(r.query);n.json(i)});handleSearchByConcept=this.wrapHandler(async(r,n)=>{let i=await this.searchManager.findByConcept(r.query);n.json(i)});handleSearchByFile=this.wrapHandler(async(r,n)=>{let i=await this.searchManager.findByFile(r.query);n.json(i)});handleSearchByType=this.wrapHandler(async(r,n)=>{let i=await this.searchManager.findByType(r.query);n.json(i)});handleGetRecentContext=this.wrapHandler(async(r,n)=>{let i=await this.searchManager.getRecentContext(r.query);n.json(i)});handleGetContextTimeline=this.wrapHandler(async(r,n)=>{let i=await this.searchManager.getContextTimeline(r.query);n.json(i)});handleContextPreview=this.wrapHandler(async(r,n)=>{let i=r.query.project;if(!i){this.badRequest(n,"Project parameter is required");return}let{generateContext:a}=await Promise.resolve().then(()=>(V$(),B$)),s=`/preview/${i}`,o=await a({session_id:"preview-"+Date.now(),cwd:s},!0);n.setHeader("Content-Type","text/plain; charset=utf-8"),n.send(o)});handleContextInject=this.wrapHandler(async(r,n)=>{let i=r.query.projects||r.query.project,a=r.query.colors==="true";if(!i){this.badRequest(n,"Project(s) parameter is required");return}let s=i.split(",").map(d=>d.trim()).filter(Boolean);if(s.length===0){this.badRequest(n,"At least one project is required");return}let{generateContext:o}=await Promise.resolve().then(()=>(V$(),B$)),u=`/context/${s[s.length-1]}`,l=await o({session_id:"context-inject-"+Date.now(),cwd:u,projects:s},a);n.setHeader("Content-Type","text/plain; charset=utf-8"),n.send(l)});handleGetTimelineByQuery=this.wrapHandler(async(r,n)=>{let i=await this.searchManager.getTimelineByQuery(r.query);n.json(i)});handleSearchHelp=this.wrapHandler((r,n)=>{n.json({title:"Claude-Mem Search API",description:"HTTP API for searching persistent memory",endpoints:[{path:"/api/search/observations",method:"GET",description:"Search observations using full-text search",parameters:{query:"Search query (required)",limit:"Number of results (default: 20)",project:"Filter by project name (optional)"}},{path:"/api/search/sessions",method:"GET",description:"Search session summaries using full-text search",parameters:{query:"Search query (required)",limit:"Number of results (default: 20)"}},{path:"/api/search/prompts",method:"GET",description:"Search user prompts using full-text search",parameters:{query:"Search query (required)",limit:"Number of results (default: 20)",project:"Filter by project name (optional)"}},{path:"/api/search/by-concept",method:"GET",description:"Find observations by concept tag",parameters:{concept:"Concept tag (required): discovery, decision, bugfix, feature, refactor",limit:"Number of results (default: 10)",project:"Filter by project name (optional)"}},{path:"/api/search/by-file",method:"GET",description:"Find observations and sessions by file path",parameters:{filePath:"File path or partial path (required)",limit:"Number of results per type (default: 10)",project:"Filter by project name (optional)"}},{path:"/api/search/by-type",method:"GET",description:"Find observations by type",parameters:{type:"Observation type (required): discovery, decision, bugfix, feature, refactor",limit:"Number of results (default: 10)",project:"Filter by project name (optional)"}},{path:"/api/context/recent",method:"GET",description:"Get recent session context including summaries and observations",parameters:{project:"Project name (default: current directory)",limit:"Number of recent sessions (default: 3)"}},{path:"/api/context/timeline",method:"GET",description:"Get unified timeline around a specific point in time",parameters:{anchor:'Anchor point: observation ID, session ID (e.g., "S123"), or ISO timestamp (required)',depth_before:"Number of records before anchor (default: 10)",depth_after:"Number of records after anchor (default: 10)",project:"Filter by project name (optional)"}},{path:"/api/timeline/by-query",method:"GET",description:"Search for best match, then get timeline around it",parameters:{query:"Search query (required)",mode:'Search mode: "auto", "observations", or "sessions" (default: "auto")',depth_before:"Number of records before match (default: 10)",depth_after:"Number of records after match (default: 10)",project:"Filter by project name (optional)"}},{path:"/api/search/help",method:"GET",description:"Get this help documentation"}],examples:['curl "http://localhost:37777/api/search/observations?query=authentication&limit=5"','curl "http://localhost:37777/api/search/by-type?type=bugfix&limit=10"','curl "http://localhost:37777/api/context/recent?project=claude-mem&limit=3"','curl "http://localhost:37777/api/context/timeline?anchor=123&depth_before=5&depth_after=5"']})})};var Fs=nt(require("path"),1),Er=require("fs"),J$=require("os");er();Se();var W$=require("child_process"),qs=require("fs"),rv=require("path");Se();er();var cp=yi;function G$(t){return!t||typeof t!="string"?!1:/^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/.test(t)&&!t.includes("..")}var Mhe=3e5,K$=6e5;function Dn(t){let e=(0,W$.spawnSync)("git",t,{cwd:cp,encoding:"utf-8",timeout:Mhe,windowsHide:!0,shell:!1});if(e.error)throw e.error;if(e.status!==0)throw new Error(e.stderr||e.stdout||"Git command failed");return e.stdout.trim()}function vq(t,e=K$){let n=process.platform==="win32"?"npm.cmd":"npm",i=(0,W$.spawnSync)(n,t,{cwd:cp,encoding:"utf-8",timeout:e,windowsHide:!0,shell:!1});if(i.error)throw i.error;if(i.status!==0)throw new Error(i.stderr||i.stdout||"npm command failed");return i.stdout.trim()}function nv(){let t=(0,rv.join)(cp,".git");if(!(0,qs.existsSync)(t))return{branch:null,isBeta:!1,isGitRepo:!1,isDirty:!1,canSwitch:!1,error:"Installed plugin is not a git repository"};try{let e=Dn(["rev-parse","--abbrev-ref","HEAD"]),n=Dn(["status","--porcelain"]).length>0,i=e.startsWith("beta");return{branch:e,isBeta:i,isGitRepo:!0,isDirty:n,canSwitch:!0}}catch(e){return $.error("BRANCH","Failed to get branch info",{},e),{branch:null,isBeta:!1,isGitRepo:!0,isDirty:!1,canSwitch:!1,error:e.message}}}async function yq(t){if(!G$(t))return{success:!1,error:`Invalid branch name: ${t}. Branch names must be alphanumeric with hyphens, underscores, slashes, or dots.`};let e=nv();if(!e.isGitRepo)return{success:!1,error:"Installed plugin is not a git repository. Please reinstall."};if(e.branch===t)return{success:!0,branch:t,message:`Already on branch ${t}`};try{$.info("BRANCH","Starting branch switch",{from:e.branch,to:t}),$.debug("BRANCH","Discarding local changes"),Dn(["checkout","--","."]),Dn(["clean","-fd"]),$.debug("BRANCH","Fetching from origin"),Dn(["fetch","origin"]),$.debug("BRANCH","Checking out branch",{branch:t});try{Dn(["checkout",t])}catch(n){$.debug("BRANCH","Branch not local, tracking remote",{branch:t,error:n instanceof Error?n.message:String(n)}),Dn(["checkout","-b",t,`origin/${t}`])}$.debug("BRANCH","Pulling latest"),Dn(["pull","origin",t]);let r=(0,rv.join)(cp,".install-version");return(0,qs.existsSync)(r)&&(0,qs.unlinkSync)(r),$.debug("BRANCH","Running npm install"),vq(["install"],K$),$.success("BRANCH","Branch switch complete",{branch:t}),{success:!0,branch:t,message:`Switched to ${t}. Worker will restart automatically.`}}catch(r){$.error("BRANCH","Branch switch failed",{targetBranch:t},r);try{e.branch&&G$(e.branch)&&Dn(["checkout",e.branch])}catch(n){$.error("BRANCH","Recovery checkout also failed",{originalBranch:e.branch},n)}return{success:!1,error:`Branch switch failed: ${r.message}`}}}async function _q(){let t=nv();if(!t.isGitRepo||!t.branch)return{success:!1,error:"Cannot pull updates: not a git repository"};try{if(!G$(t.branch))return{success:!1,error:`Invalid current branch name: ${t.branch}`};$.info("BRANCH","Pulling updates",{branch:t.branch}),Dn(["checkout","--","."]),Dn(["fetch","origin"]),Dn(["pull","origin",t.branch]);let e=(0,rv.join)(cp,".install-version");return(0,qs.existsSync)(e)&&(0,qs.unlinkSync)(e),vq(["install"],K$),$.success("BRANCH","Updates pulled",{branch:t.branch}),{success:!0,branch:t.branch,message:`Updated ${t.branch}. Worker will restart automatically.`}}catch(e){return $.error("BRANCH","Pull failed",{},e),{success:!1,error:`Pull failed: ${e.message}`}}}lr();Zr();var iv=class extends jr{constructor(r){super();this.settingsManager=r}setupRoutes(r){r.get("/api/settings",this.handleGetSettings.bind(this)),r.post("/api/settings",this.handleUpdateSettings.bind(this)),r.get("/api/mcp/status",this.handleGetMcpStatus.bind(this)),r.post("/api/mcp/toggle",this.handleToggleMcp.bind(this)),r.get("/api/branch/status",this.handleGetBranchStatus.bind(this)),r.post("/api/branch/switch",this.handleSwitchBranch.bind(this)),r.post("/api/branch/update",this.handleUpdateBranch.bind(this))}handleGetSettings=this.wrapHandler((r,n)=>{let i=Fs.default.join((0,J$.homedir)(),".claude-mem","settings.json");this.ensureSettingsFile(i);let a=Ae.loadFromFile(i);n.json(a)});handleUpdateSettings=this.wrapHandler((r,n)=>{let i=this.validateSettings(r.body);if(!i.valid){n.status(400).json({success:!1,error:i.error});return}let a=Fs.default.join((0,J$.homedir)(),".claude-mem","settings.json");this.ensureSettingsFile(a);let s={};if((0,Er.existsSync)(a)){let c=(0,Er.readFileSync)(a,"utf-8");try{s=JSON.parse(c)}catch(u){$.error("SETTINGS","Failed to parse settings file",{settingsPath:a},u),n.status(500).json({success:!1,error:"Settings file is corrupted. Delete ~/.claude-mem/settings.json to reset."});return}}let o=["CLAUDE_MEM_MODEL","CLAUDE_MEM_CONTEXT_OBSERVATIONS","CLAUDE_MEM_WORKER_PORT","CLAUDE_MEM_WORKER_HOST","CLAUDE_MEM_PROVIDER","CLAUDE_MEM_GEMINI_API_KEY","CLAUDE_MEM_GEMINI_MODEL","CLAUDE_MEM_GEMINI_RATE_LIMITING_ENABLED","CLAUDE_MEM_OPENROUTER_API_KEY","CLAUDE_MEM_OPENROUTER_MODEL","CLAUDE_MEM_OPENROUTER_SITE_URL","CLAUDE_MEM_OPENROUTER_APP_NAME","CLAUDE_MEM_OPENROUTER_MAX_CONTEXT_MESSAGES","CLAUDE_MEM_OPENROUTER_MAX_TOKENS","CLAUDE_MEM_DATA_DIR","CLAUDE_MEM_LOG_LEVEL","CLAUDE_MEM_PYTHON_VERSION","CLAUDE_CODE_PATH","CLAUDE_MEM_CONTEXT_SHOW_READ_TOKENS","CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS","CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT","CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT","CLAUDE_MEM_CONTEXT_OBSERVATION_TYPES","CLAUDE_MEM_CONTEXT_OBSERVATION_CONCEPTS","CLAUDE_MEM_CONTEXT_FULL_COUNT","CLAUDE_MEM_CONTEXT_FULL_FIELD","CLAUDE_MEM_CONTEXT_SESSION_COUNT","CLAUDE_MEM_CONTEXT_SHOW_LAST_SUMMARY","CLAUDE_MEM_CONTEXT_SHOW_LAST_MESSAGE","CLAUDE_MEM_FOLDER_CLAUDEMD_ENABLED"];for(let c of o)r.body[c]!==void 0&&(s[c]=r.body[c]);(0,Er.writeFileSync)(a,JSON.stringify(s,null,2),"utf-8"),CC(),$.info("WORKER","Settings updated"),n.json({success:!0,message:"Settings updated successfully"})});handleGetMcpStatus=this.wrapHandler((r,n)=>{let i=this.isMcpEnabled();n.json({enabled:i})});handleToggleMcp=this.wrapHandler((r,n)=>{let{enabled:i}=r.body;if(typeof i!="boolean"){this.badRequest(n,"enabled must be a boolean");return}this.toggleMcp(i),n.json({success:!0,enabled:this.isMcpEnabled()})});handleGetBranchStatus=this.wrapHandler((r,n)=>{let i=nv();n.json(i)});handleSwitchBranch=this.wrapHandler(async(r,n)=>{let{branch:i}=r.body;if(!i){n.status(400).json({success:!1,error:"Missing branch parameter"});return}let a=["main","beta/7.0","feature/bun-executable"];if(!a.includes(i)){n.status(400).json({success:!1,error:`Invalid branch. Allowed: ${a.join(", ")}`});return}$.info("WORKER","Branch switch requested",{branch:i});let s=await yq(i);s.success&&setTimeout(()=>{$.info("WORKER","Restarting worker after branch switch"),process.exit(0)},1e3),n.json(s)});handleUpdateBranch=this.wrapHandler(async(r,n)=>{$.info("WORKER","Branch update requested");let i=await _q();i.success&&setTimeout(()=>{$.info("WORKER","Restarting worker after branch update"),process.exit(0)},1e3),n.json(i)});validateSettings(r){if(r.CLAUDE_MEM_PROVIDER&&!["claude","gemini","openrouter"].includes(r.CLAUDE_MEM_PROVIDER))return{valid:!1,error:'CLAUDE_MEM_PROVIDER must be "claude", "gemini", or "openrouter"'};if(r.CLAUDE_MEM_GEMINI_MODEL&&!["gemini-2.5-flash-lite","gemini-2.5-flash","gemini-3-flash-preview"].includes(r.CLAUDE_MEM_GEMINI_MODEL))return{valid:!1,error:"CLAUDE_MEM_GEMINI_MODEL must be one of: gemini-2.5-flash-lite, gemini-2.5-flash, gemini-3-flash-preview"};if(r.CLAUDE_MEM_CONTEXT_OBSERVATIONS){let i=parseInt(r.CLAUDE_MEM_CONTEXT_OBSERVATIONS,10);if(isNaN(i)||i<1||i>200)return{valid:!1,error:"CLAUDE_MEM_CONTEXT_OBSERVATIONS must be between 1 and 200"}}if(r.CLAUDE_MEM_WORKER_PORT){let i=parseInt(r.CLAUDE_MEM_WORKER_PORT,10);if(isNaN(i)||i<1024||i>65535)return{valid:!1,error:"CLAUDE_MEM_WORKER_PORT must be between 1024 and 65535"}}if(r.CLAUDE_MEM_WORKER_HOST){let i=r.CLAUDE_MEM_WORKER_HOST;if(!/^(127\.0\.0\.1|0\.0\.0\.0|localhost|\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/.test(i))return{valid:!1,error:"CLAUDE_MEM_WORKER_HOST must be a valid IP address (e.g., 127.0.0.1, 0.0.0.0)"}}if(r.CLAUDE_MEM_LOG_LEVEL&&!["DEBUG","INFO","WARN","ERROR","SILENT"].includes(r.CLAUDE_MEM_LOG_LEVEL.toUpperCase()))return{valid:!1,error:"CLAUDE_MEM_LOG_LEVEL must be one of: DEBUG, INFO, WARN, ERROR, SILENT"};if(r.CLAUDE_MEM_PYTHON_VERSION&&!/^3\.\d{1,2}$/.test(r.CLAUDE_MEM_PYTHON_VERSION))return{valid:!1,error:'CLAUDE_MEM_PYTHON_VERSION must be in format "3.X" or "3.XX" (e.g., "3.13")'};let n=["CLAUDE_MEM_CONTEXT_SHOW_READ_TOKENS","CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS","CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT","CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT","CLAUDE_MEM_CONTEXT_SHOW_LAST_SUMMARY","CLAUDE_MEM_CONTEXT_SHOW_LAST_MESSAGE"];for(let i of n)if(r[i]&&!["true","false"].includes(r[i]))return{valid:!1,error:`${i} must be "true" or "false"`};if(r.CLAUDE_MEM_CONTEXT_FULL_COUNT){let i=parseInt(r.CLAUDE_MEM_CONTEXT_FULL_COUNT,10);if(isNaN(i)||i<0||i>20)return{valid:!1,error:"CLAUDE_MEM_CONTEXT_FULL_COUNT must be between 0 and 20"}}if(r.CLAUDE_MEM_CONTEXT_SESSION_COUNT){let i=parseInt(r.CLAUDE_MEM_CONTEXT_SESSION_COUNT,10);if(isNaN(i)||i<1||i>50)return{valid:!1,error:"CLAUDE_MEM_CONTEXT_SESSION_COUNT must be between 1 and 50"}}if(r.CLAUDE_MEM_CONTEXT_FULL_FIELD&&!["narrative","facts"].includes(r.CLAUDE_MEM_CONTEXT_FULL_FIELD))return{valid:!1,error:'CLAUDE_MEM_CONTEXT_FULL_FIELD must be "narrative" or "facts"'};if(r.CLAUDE_MEM_OPENROUTER_MAX_CONTEXT_MESSAGES){let i=parseInt(r.CLAUDE_MEM_OPENROUTER_MAX_CONTEXT_MESSAGES,10);if(isNaN(i)||i<1||i>100)return{valid:!1,error:"CLAUDE_MEM_OPENROUTER_MAX_CONTEXT_MESSAGES must be between 1 and 100"}}if(r.CLAUDE_MEM_OPENROUTER_MAX_TOKENS){let i=parseInt(r.CLAUDE_MEM_OPENROUTER_MAX_TOKENS,10);if(isNaN(i)||i<1e3||i>1e6)return{valid:!1,error:"CLAUDE_MEM_OPENROUTER_MAX_TOKENS must be between 1000 and 1000000"}}if(r.CLAUDE_MEM_OPENROUTER_SITE_URL)try{new URL(r.CLAUDE_MEM_OPENROUTER_SITE_URL)}catch(i){return $.debug("SETTINGS","Invalid URL format",{url:r.CLAUDE_MEM_OPENROUTER_SITE_URL,error:i instanceof Error?i.message:String(i)}),{valid:!1,error:"CLAUDE_MEM_OPENROUTER_SITE_URL must be a valid URL"}}return{valid:!0}}isMcpEnabled(){let r=Qr(),n=Fs.default.join(r,"plugin",".mcp.json");return(0,Er.existsSync)(n)}toggleMcp(r){let n=Qr(),i=Fs.default.join(n,"plugin",".mcp.json"),a=Fs.default.join(n,"plugin",".mcp.json.disabled");r&&(0,Er.existsSync)(a)?((0,Er.renameSync)(a,i),$.info("WORKER","MCP search server enabled")):!r&&(0,Er.existsSync)(i)?((0,Er.renameSync)(i,a),$.info("WORKER","MCP search server disabled")):$.debug("WORKER","MCP toggle no-op (already in desired state)",{enabled:r})}ensureSettingsFile(r){if(!(0,Er.existsSync)(r)){let n=Ae.getAllDefaults(),i=Fs.default.dirname(r);(0,Er.existsSync)(i)||(0,Er.mkdirSync)(i,{recursive:!0}),(0,Er.writeFileSync)(r,JSON.stringify(n,null,2),"utf-8"),$.info("SETTINGS","Created settings file with defaults",{settingsPath:r})}}};var Zs=require("fs"),av=require("path");Se();lr();var sv=class extends jr{getLogFilePath(){let e=Ae.get("CLAUDE_MEM_DATA_DIR"),r=(0,av.join)(e,"logs"),n=new Date().toISOString().split("T")[0];return(0,av.join)(r,`claude-mem-${n}.log`)}getLogsDir(){let e=Ae.get("CLAUDE_MEM_DATA_DIR");return(0,av.join)(e,"logs")}setupRoutes(e){e.get("/api/logs",this.handleGetLogs.bind(this)),e.post("/api/logs/clear",this.handleClearLogs.bind(this))}handleGetLogs=this.wrapHandler((e,r)=>{let n=this.getLogFilePath();if(!(0,Zs.existsSync)(n)){r.json({logs:"",path:n,exists:!1});return}let i=parseInt(e.query.lines||"1000",10),a=Math.min(i,1e4),o=(0,Zs.readFileSync)(n,"utf-8").split(` `),c=Math.max(0,o.length-a),u=o.slice(c).join(` -`);r.json({logs:u,path:n,exists:!0,totalLines:o.length,returnedLines:o.length-c})});handleClearLogs=this.wrapHandler((e,r)=>{let n=this.getLogFilePath();if(!(0,Zs.existsSync)(n)){r.json({success:!0,message:"Log file does not exist",path:n});return}(0,Zs.writeFileSync)(n,"","utf-8"),$.info("SYSTEM","Log file cleared via UI",{path:n}),r.json({success:!0,message:"Log file cleared",path:n})})};Se();var ov=class extends jr{constructor(r,n){super();this.dbManager=r;this.defaultProject=n}setupRoutes(r){r.post("/api/memory/save",this.handleSaveMemory.bind(this))}handleSaveMemory=this.wrapHandler(async(r,n)=>{let{text:i,title:a,project:s}=r.body,o=s||this.defaultProject;if(!i||typeof i!="string"||i.trim().length===0){this.badRequest(n,"text is required and must be non-empty");return}let c=this.dbManager.getSessionStore(),u=this.dbManager.getChromaSync(),l=c.getOrCreateManualSession(o),d={type:"discovery",title:a||i.substring(0,60).trim()+(i.length>60?"...":""),subtitle:"Manual memory",facts:[],narrative:i,concepts:[],files_read:[],files_modified:[]},p=c.storeObservation(l,o,d,0,0);$.info("HTTP","Manual observation saved",{id:p.id,project:o,title:d.title}),u.syncObservation(p.id,l,o,d,0,p.createdAtEpoch,0).catch(f=>{$.error("CHROMA","ChromaDB sync failed",{id:p.id},f)}),n.json({success:!0,id:p.id,title:d.title,project:o,message:`Memory saved as observation #${p.id}`})})};var dge={},nge=120*1e3;function gk(){return hk.default.join(Ae.get("CLAUDE_MEM_DATA_DIR"),".worker-start-attempted")}function ige(){if(process.platform!=="win32")return!1;let t=gk();if(!(0,ia.existsSync)(t))return!1;try{let e=(0,ia.statSync)(t).mtimeMs;return Date.now()-e{this.resolveInitialization=e}),this.dbManager=new qh,this.sessionManager=new Vh(this.dbManager),this.sseBroadcaster=new Gh,this.sdkAgent=new Pg(this.dbManager,this.sessionManager),this.geminiAgent=new Cg(this.dbManager,this.sessionManager),this.openRouterAgent=new jg(this.dbManager,this.sessionManager),this.paginationHelper=new Mg(this.dbManager),this.settingsManager=new Dg(this.dbManager),this.sessionEventBroadcaster=new qg(this.sseBroadcaster,this),this.sessionManager.setOnSessionDeleted(()=>{this.broadcastProcessingStatus()}),this.mcpClient=new Ao({name:"worker-search-proxy",version:oge},{capabilities:{}}),this.server=new Dh({getInitializationComplete:()=>this.initializationCompleteFlag,getMcpReady:()=>this.mcpReady,onShutdown:()=>this.shutdown(),onRestart:()=>this.shutdown()}),this.registerRoutes(),this.registerSignalHandlers()}registerSignalHandlers(){let e={value:this.isShuttingDown},r=ZC(()=>this.shutdown(),e);process.on("SIGTERM",()=>{this.isShuttingDown=e.value,r("SIGTERM")}),process.on("SIGINT",()=>{this.isShuttingDown=e.value,r("SIGINT")})}registerRoutes(){this.server.app.get("/api/context/inject",async(e,r,n)=>{if(!this.initializationCompleteFlag||!this.searchRoutes){$.warn("SYSTEM","Context requested before initialization complete, returning empty"),r.status(200).json({content:[{type:"text",text:""}]});return}n()}),this.server.app.use("/api",async(e,r,n)=>{if(this.initializationCompleteFlag){n();return}let i=3e4,a=new Promise((s,o)=>setTimeout(()=>o(new Error("Database initialization timeout")),i));try{await Promise.race([this.initializationComplete,a]),n()}catch(s){$.error("HTTP",`Request to ${e.method} ${e.path} rejected \u2014 DB not initialized`,{},s),r.status(503).json({error:"Service initializing",message:"Database is still initializing, please retry"})}}),this.server.registerRoutes(new Zg(this.sseBroadcaster,this.dbManager,this.sessionManager)),this.server.registerRoutes(new Vg(this.sessionManager,this.dbManager,this.sdkAgent,this.geminiAgent,this.openRouterAgent,this.sessionEventBroadcaster,this)),this.server.registerRoutes(new Gg(this.paginationHelper,this.dbManager,this.sessionManager,this.sseBroadcaster,this,this.startTime)),this.server.registerRoutes(new iv(this.settingsManager)),this.server.registerRoutes(new sv),this.server.registerRoutes(new ov(this.dbManager,"claude-mem"))}async start(){let e=wt(),r=Em();await this.server.listen(e,r),DC({pid:process.pid,port:e,startedAt:new Date().toISOString()}),$.info("SYSTEM","Worker started",{host:r,port:e,pid:process.pid}),this.initializeBackground().catch(n=>{$.error("SYSTEM","Background initialization failed",{},n)})}async initializeBackground(){try{await FC();let{ModeManager:e}=await Promise.resolve().then(()=>(Vr(),k2)),{SettingsDefaultsManager:r}=await Promise.resolve().then(()=>(lr(),bC)),{USER_SETTINGS_PATH:n}=await Promise.resolve().then(()=>(er(),OC)),a=r.loadFromFile(n).CLAUDE_MEM_MODE;e.getInstance().loadMode(a),$.info("SYSTEM",`Mode loaded: ${a}`),await this.dbManager.initialize();let{PendingMessageStore:s}=await Promise.resolve().then(()=>(Na(),Ps)),c=new s(this.dbManager.getSessionStore().db,3).resetStaleProcessingMessages(0);c>0&&$.info("SYSTEM",`Reset ${c} stale processing messages to pending`);let u=new Ug,l=new Lg,d=new zg(this.dbManager.getSessionSearch(),this.dbManager.getSessionStore(),this.dbManager.getChromaSync(),u,l);this.searchRoutes=new tv(d),this.server.registerRoutes(this.searchRoutes),$.info("WORKER","SearchManager initialized and search routes registered");let p=hk.default.join(__dirname,"mcp-server.cjs"),f=new Do({command:"node",args:[p],env:process.env}),h=3e5,y=this.mcpClient.connect(f),g=new Promise((m,_)=>setTimeout(()=>_(new Error("MCP connection timeout after 5 minutes")),h));await Promise.race([y,g]),this.mcpReady=!0,$.success("WORKER","Connected to MCP server"),this.initializationCompleteFlag=!0,this.resolveInitialization(),$.info("SYSTEM","Background initialization complete"),this.stopOrphanReaper=S2(()=>{let m=new Set;for(let[_]of this.sessionManager.sessions)m.add(_);return m}),$.info("SYSTEM","Started orphan reaper (runs every 5 minutes)"),this.processPendingQueues(50).then(m=>{m.sessionsStarted>0&&$.info("SYSTEM",`Auto-recovered ${m.sessionsStarted} sessions with pending work`,{totalPending:m.totalPendingSessions,started:m.sessionsStarted,sessionIds:m.startedSessionIds})}).catch(m=>{$.error("SYSTEM","Auto-recovery of pending queues failed",{},m)})}catch(e){throw $.error("SYSTEM","Background initialization failed",{},e),e}}getActiveAgent(){return Jd()&&Fc()?this.openRouterAgent:Kd()&&qc()?this.geminiAgent:this.sdkAgent}startSessionProcessor(e,r){if(!e)return;let n=e.sessionDbId,i=this.getActiveAgent(),a=i.constructor.name;e.abortController.signal.aborted&&($.debug("SYSTEM","Replacing aborted AbortController before starting generator",{sessionId:e.sessionDbId}),e.abortController=new AbortController);let s=!1;$.info("SYSTEM",`Starting generator (${r}) using ${a}`,{sessionId:n}),e.generatorPromise=i.startSession(e,this).catch(async o=>{let c=o?.message||"";if(["Claude executable not found","CLAUDE_CODE_PATH","ENOENT","spawn"].some(l=>c.includes(l))){s=!0,$.error("SDK","Unrecoverable generator error - will NOT restart",{sessionId:e.sessionDbId,project:e.project,errorMessage:c});return}if(this.isSessionTerminatedError(o))return $.warn("SDK","SDK resume failed, falling back to standalone processing",{sessionId:e.sessionDbId,project:e.project,reason:o instanceof Error?o.message:String(o)}),this.runFallbackForTerminatedSession(e,o);throw(c.includes("aborted by user")||c.includes("No conversation found"))&&e.memorySessionId&&($.warn("SDK","Detected stale resume failure, clearing memorySessionId for fresh start",{sessionId:e.sessionDbId,memorySessionId:e.memorySessionId,errorMessage:c}),this.dbManager.getSessionStore().updateMemorySessionId(e.sessionDbId,null),e.memorySessionId=null,e.forceInit=!0),$.error("SDK","Session generator failed",{sessionId:e.sessionDbId,project:e.project,provider:a},o),o}).finally(()=>{if(e.generatorPromise=null,s){$.warn("SYSTEM","Skipping restart due to unrecoverable error",{sessionId:e.sessionDbId}),this.broadcastProcessingStatus();return}let{PendingMessageStore:o}=(Na(),Kc(Ps)),u=new o(this.dbManager.getSessionStore().db,3).getPendingCount(e.sessionDbId);u>0&&($.info("SYSTEM","Pending work remains after generator exit, restarting with fresh AbortController",{sessionId:e.sessionDbId,pendingCount:u}),e.abortController=new AbortController,this.startSessionProcessor(e,"pending-work-restart")),this.broadcastProcessingStatus()})}isSessionTerminatedError(e){let n=(e instanceof Error?e.message:String(e)).toLowerCase();return n.includes("process aborted by user")||n.includes("processtransport")||n.includes("not ready for writing")||n.includes("session generator failed")||n.includes("claude code process")}async runFallbackForTerminatedSession(e,r){if(!e)return;let n=e.sessionDbId;if(!e.memorySessionId){let s=`fallback-${n}-${Date.now()}`;e.memorySessionId=s,this.dbManager.getSessionStore().updateMemorySessionId(n,s)}if(qc())try{await this.geminiAgent.startSession(e,this);return}catch(s){$.warn("SDK","Fallback Gemini failed, trying OpenRouter",{sessionId:n,error:s instanceof Error?s.message:String(s)})}if(Fc())try{await this.openRouterAgent.startSession(e,this);return}catch(s){$.warn("SDK","Fallback OpenRouter failed",{sessionId:n,error:s instanceof Error?s.message:String(s)})}let a=this.sessionManager.getPendingMessageStore().markAllSessionMessagesAbandoned(n);a>0&&$.warn("SDK","No fallback available; marked pending messages abandoned",{sessionId:n,abandoned:a}),this.sessionManager.removeSessionImmediate(n),this.sessionEventBroadcaster.broadcastSessionCompleted(n)}async processPendingQueues(e=10){let{PendingMessageStore:r}=await Promise.resolve().then(()=>(Na(),Ps)),n=new r(this.dbManager.getSessionStore().db,3),i=this.dbManager.getSessionStore(),a=360*60*1e3,s=Date.now()-a;try{let u=i.db.prepare(` +`);r.json({logs:u,path:n,exists:!0,totalLines:o.length,returnedLines:o.length-c})});handleClearLogs=this.wrapHandler((e,r)=>{let n=this.getLogFilePath();if(!(0,Zs.existsSync)(n)){r.json({success:!0,message:"Log file does not exist",path:n});return}(0,Zs.writeFileSync)(n,"","utf-8"),$.info("SYSTEM","Log file cleared via UI",{path:n}),r.json({success:!0,message:"Log file cleared",path:n})})};Se();var ov=class extends jr{constructor(r,n){super();this.dbManager=r;this.defaultProject=n}setupRoutes(r){r.post("/api/memory/save",this.handleSaveMemory.bind(this))}handleSaveMemory=this.wrapHandler(async(r,n)=>{let{text:i,title:a,project:s}=r.body,o=s||this.defaultProject;if(!i||typeof i!="string"||i.trim().length===0){this.badRequest(n,"text is required and must be non-empty");return}let c=this.dbManager.getSessionStore(),u=this.dbManager.getChromaSync(),l=c.getOrCreateManualSession(o),d={type:"discovery",title:a||i.substring(0,60).trim()+(i.length>60?"...":""),subtitle:"Manual memory",facts:[],narrative:i,concepts:[],files_read:[],files_modified:[]},p=c.storeObservation(l,o,d,0,0);$.info("HTTP","Manual observation saved",{id:p.id,project:o,title:d.title}),u.syncObservation(p.id,l,o,d,0,p.createdAtEpoch,0).catch(f=>{$.error("CHROMA","ChromaDB sync failed",{id:p.id},f)}),n.json({success:!0,id:p.id,title:d.title,project:o,message:`Memory saved as observation #${p.id}`})})};var dge={},nge=120*1e3;function gk(){return hk.default.join(Ae.get("CLAUDE_MEM_DATA_DIR"),".worker-start-attempted")}function ige(){if(process.platform!=="win32")return!1;let t=gk();if(!(0,ia.existsSync)(t))return!1;try{let e=(0,ia.statSync)(t).mtimeMs;return Date.now()-e{this.resolveInitialization=e}),this.dbManager=new qh,this.sessionManager=new Vh(this.dbManager),this.sseBroadcaster=new Gh,this.sdkAgent=new Pg(this.dbManager,this.sessionManager),this.geminiAgent=new Cg(this.dbManager,this.sessionManager),this.openRouterAgent=new jg(this.dbManager,this.sessionManager),this.paginationHelper=new Mg(this.dbManager),this.settingsManager=new Dg(this.dbManager),this.sessionEventBroadcaster=new qg(this.sseBroadcaster,this),this.sessionManager.setOnSessionDeleted(()=>{this.broadcastProcessingStatus()}),this.mcpClient=new Ao({name:"worker-search-proxy",version:oge},{capabilities:{}}),this.server=new Dh({getInitializationComplete:()=>this.initializationCompleteFlag,getMcpReady:()=>this.mcpReady,onShutdown:()=>this.shutdown(),onRestart:()=>this.shutdown()}),this.registerRoutes(),this.registerSignalHandlers()}registerSignalHandlers(){let e={value:this.isShuttingDown},r=ZC(()=>this.shutdown(),e);process.on("SIGTERM",()=>{this.isShuttingDown=e.value,r("SIGTERM")}),process.on("SIGINT",()=>{this.isShuttingDown=e.value,r("SIGINT")})}registerRoutes(){this.server.app.get("/api/context/inject",async(e,r,n)=>{if(!this.initializationCompleteFlag||!this.searchRoutes){$.warn("SYSTEM","Context requested before initialization complete, returning empty"),r.status(200).json({content:[{type:"text",text:""}]});return}n()}),this.server.app.use("/api",async(e,r,n)=>{if(this.initializationCompleteFlag){n();return}let i=3e4,a=new Promise((s,o)=>setTimeout(()=>o(new Error("Database initialization timeout")),i));try{await Promise.race([this.initializationComplete,a]),n()}catch(s){$.error("HTTP",`Request to ${e.method} ${e.path} rejected \u2014 DB not initialized`,{},s),r.status(503).json({error:"Service initializing",message:"Database is still initializing, please retry"})}}),this.server.registerRoutes(new Zg(this.sseBroadcaster,this.dbManager,this.sessionManager)),this.server.registerRoutes(new Vg(this.sessionManager,this.dbManager,this.sdkAgent,this.geminiAgent,this.openRouterAgent,this.sessionEventBroadcaster,this)),this.server.registerRoutes(new Gg(this.paginationHelper,this.dbManager,this.sessionManager,this.sseBroadcaster,this,this.startTime)),this.server.registerRoutes(new iv(this.settingsManager)),this.server.registerRoutes(new sv),this.server.registerRoutes(new ov(this.dbManager,"claude-mem"))}async start(){let e=wt(),r=Em();await this.server.listen(e,r),DC({pid:process.pid,port:e,startedAt:new Date().toISOString()}),$.info("SYSTEM","Worker started",{host:r,port:e,pid:process.pid}),this.initializeBackground().catch(n=>{$.error("SYSTEM","Background initialization failed",{},n)})}async initializeBackground(){try{await FC();let{ModeManager:e}=await Promise.resolve().then(()=>(Vr(),k2)),{SettingsDefaultsManager:r}=await Promise.resolve().then(()=>(lr(),bC)),{USER_SETTINGS_PATH:n}=await Promise.resolve().then(()=>(er(),OC)),a=r.loadFromFile(n).CLAUDE_MEM_MODE;e.getInstance().loadMode(a),$.info("SYSTEM",`Mode loaded: ${a}`),await this.dbManager.initialize();let{PendingMessageStore:s}=await Promise.resolve().then(()=>(Na(),Ps)),c=new s(this.dbManager.getSessionStore().db,3).resetStaleProcessingMessages(0);c>0&&$.info("SYSTEM",`Reset ${c} stale processing messages to pending`);let u=new Ug,l=new Lg,d=new zg(this.dbManager.getSessionSearch(),this.dbManager.getSessionStore(),this.dbManager.getChromaSync(),u,l);this.searchRoutes=new tv(d),this.server.registerRoutes(this.searchRoutes),$.info("WORKER","SearchManager initialized and search routes registered");let p=hk.default.join(__dirname,"mcp-server.cjs"),f=new Do({command:"node",args:[p],env:process.env}),h=3e5,y=this.mcpClient.connect(f),g=new Promise((m,_)=>setTimeout(()=>_(new Error("MCP connection timeout after 5 minutes")),h));await Promise.race([y,g]),this.mcpReady=!0,$.success("WORKER","Connected to MCP server"),this.initializationCompleteFlag=!0,this.resolveInitialization(),$.info("SYSTEM","Background initialization complete"),this.stopOrphanReaper=S2(()=>{let m=new Set;for(let[_]of this.sessionManager.sessions)m.add(_);return m}),$.info("SYSTEM","Started orphan reaper (runs every 5 minutes)"),this.processPendingQueues(50).then(m=>{m.sessionsStarted>0&&$.info("SYSTEM",`Auto-recovered ${m.sessionsStarted} sessions with pending work`,{totalPending:m.totalPendingSessions,started:m.sessionsStarted,sessionIds:m.startedSessionIds})}).catch(m=>{$.error("SYSTEM","Auto-recovery of pending queues failed",{},m)})}catch(e){throw $.error("SYSTEM","Background initialization failed",{},e),e}}getActiveAgent(){return Jd()&&Fc()?this.openRouterAgent:Kd()&&qc()?this.geminiAgent:this.sdkAgent}startSessionProcessor(e,r){if(!e)return;let n=e.sessionDbId,i=this.getActiveAgent(),a=i.constructor.name;e.abortController.signal.aborted&&($.debug("SYSTEM","Replacing aborted AbortController before starting generator",{sessionId:e.sessionDbId}),e.abortController=new AbortController);let s=!1;$.info("SYSTEM",`Starting generator (${r}) using ${a}`,{sessionId:n}),e.generatorPromise=i.startSession(e,this).catch(async o=>{let c=o?.message||"";if(["Claude executable not found","CLAUDE_CODE_PATH","ENOENT","spawn"].some(l=>c.includes(l))){s=!0,$.error("SDK","Unrecoverable generator error - will NOT restart",{sessionId:e.sessionDbId,project:e.project,errorMessage:c});return}if(this.isSessionTerminatedError(o))return $.warn("SDK","SDK resume failed, falling back to standalone processing",{sessionId:e.sessionDbId,project:e.project,reason:o instanceof Error?o.message:String(o)}),this.runFallbackForTerminatedSession(e,o);throw(c.includes("aborted by user")||c.includes("No conversation found"))&&e.memorySessionId&&($.warn("SDK","Detected stale resume failure, clearing memorySessionId for fresh start",{sessionId:e.sessionDbId,memorySessionId:e.memorySessionId,errorMessage:c}),this.dbManager.getSessionStore().updateMemorySessionId(e.sessionDbId,null),e.memorySessionId=null,e.forceInit=!0),$.error("SDK","Session generator failed",{sessionId:e.sessionDbId,project:e.project,provider:a},o),o}).finally(()=>{if(e.generatorPromise=null,s){$.warn("SYSTEM","Skipping restart due to unrecoverable error",{sessionId:e.sessionDbId}),this.broadcastProcessingStatus();return}let{PendingMessageStore:o}=(Na(),Kc(Ps)),u=new o(this.dbManager.getSessionStore().db,3).getPendingCount(e.sessionDbId);u>0&&($.info("SYSTEM","Pending work remains after generator exit, restarting with fresh AbortController",{sessionId:e.sessionDbId,pendingCount:u}),e.abortController=new AbortController,this.startSessionProcessor(e,"pending-work-restart")),this.broadcastProcessingStatus()})}isSessionTerminatedError(e){let n=(e instanceof Error?e.message:String(e)).toLowerCase();return n.includes("process aborted by user")||n.includes("processtransport")||n.includes("not ready for writing")||n.includes("session generator failed")||n.includes("claude code process")}async runFallbackForTerminatedSession(e,r){if(!e)return;let n=e.sessionDbId;if(!e.memorySessionId){let s=`fallback-${n}-${Date.now()}`;e.memorySessionId=s,this.dbManager.getSessionStore().updateMemorySessionId(n,s)}if(qc())try{await this.geminiAgent.startSession(e,this);return}catch(s){$.warn("SDK","Fallback Gemini failed, trying OpenRouter",{sessionId:n,error:s instanceof Error?s.message:String(s)})}if(Fc())try{await this.openRouterAgent.startSession(e,this);return}catch(s){$.warn("SDK","Fallback OpenRouter failed",{sessionId:n,error:s instanceof Error?s.message:String(s)})}let a=this.sessionManager.getPendingMessageStore().markAllSessionMessagesAbandoned(n);a>0&&$.warn("SDK","No fallback available; marked pending messages abandoned",{sessionId:n,abandoned:a}),this.sessionManager.removeSessionImmediate(n),this.sessionEventBroadcaster.broadcastSessionCompleted(n)}async processPendingQueues(e=10){let{PendingMessageStore:r}=await Promise.resolve().then(()=>(Na(),Ps)),n=new r(this.dbManager.getSessionStore().db,3),i=this.dbManager.getSessionStore(),a=360*60*1e3,s=Date.now()-a;try{let u=i.db.prepare(` SELECT id FROM sdk_sessions WHERE status = 'active' AND started_at_epoch < ? `).all(s);if(u.length>0){let l=u.map(f=>f.id),d=l.map(()=>"?").join(",");i.db.prepare(`