keepmind 1.3.0 → 1.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -80,7 +80,7 @@ ${s.stack}`:` ${s.message}`;else if(this.getLevel()===0&&typeof s=="object")try{
80
80
  Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let i of t.seen.entries()){let a=i[1];if(e===i[0]){s(i);continue}if(t.external){let u=t.external.registry.get(i[0])?.id;if(e!==i[0]&&u){s(i);continue}}if(t.metadataRegistry.get(i[0])?.id){s(i);continue}if(a.cycle){s(i);continue}if(a.count>1&&t.reused==="ref"){s(i);continue}}}function qi(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 c=t.seen.get(a);if(c.ref===null)return;let u=c.def??c.schema,l={...u},d=c.ref;if(c.ref=null,d){n(d);let f=t.seen.get(d),m=f.schema;if(m.$ref&&(t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0")?(u.allOf=u.allOf??[],u.allOf.push(m)):Object.assign(u,m),Object.assign(u,l),a._zod.parent===d)for(let S in u)S==="$ref"||S==="allOf"||S in l||delete u[S];if(m.$ref&&f.def)for(let S in u)S==="$ref"||S==="allOf"||S in f.def&&JSON.stringify(u[S])===JSON.stringify(f.def[S])&&delete u[S]}let p=a._zod.parent;if(p&&p!==d){n(p);let f=t.seen.get(p);if(f?.schema.$ref&&(u.$ref=f.schema.$ref,f.def))for(let m in u)m==="$ref"||m==="allOf"||m in f.def&&JSON.stringify(u[m])===JSON.stringify(f.def[m])&&delete u[m]}t.override({zodSchema:a,jsonSchema:u,path:c.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 s=t.metadataRegistry.get(e)?.id;s!==void 0&&o.id===s&&delete o.id;let i=t.external?.defs??{};for(let a of t.seen.entries()){let c=a[1];c.def&&c.defId&&(c.def.id===c.defId&&delete c.def.id,i[c.defId]=c.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:tn(e,"input",t.processors),output:tn(e,"output",t.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function Pe(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 Pe(n.element,r);if(n.type==="set")return Pe(n.valueType,r);if(n.type==="lazy")return Pe(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 Pe(n.innerType,r);if(n.type==="intersection")return Pe(n.left,r)||Pe(n.right,r);if(n.type==="record"||n.type==="map")return Pe(n.keyType,r)||Pe(n.valueType,r);if(n.type==="pipe")return t._zod.traits.has("$ZodCodec")?!0:Pe(n.in,r)||Pe(n.out,r);if(n.type==="object"){for(let o in n.shape)if(Pe(n.shape[o],r))return!0;return!1}if(n.type==="union"){for(let o of n.options)if(Pe(o,r))return!0;return!1}if(n.type==="tuple"){for(let o of n.items)if(Pe(o,r))return!0;return!!(n.rest&&Pe(n.rest,r))}return!1}var Dp=(t,e={})=>r=>{let n=Li({...r,processors:e});return ie(t,n),Ui(n,t),qi(n,t)},tn=(t,e,r={})=>n=>{let{libraryOptions:o,target:s}=n??{},i=Li({...o??{},target:s,io:e,processors:r});return ie(t,i),Ui(i,t),qi(i,t)};var dS={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},jp=(t,e,r,n)=>{let o=r;o.type="string";let{minimum:s,maximum:i,format:a,patterns:c,contentEncoding:u}=t._zod.bag;if(typeof s=="number"&&(o.minLength=s),typeof i=="number"&&(o.maxLength=i),a&&(o.format=dS[a]??a,o.format===""&&delete o.format,a==="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}))])}},Lp=(t,e,r,n)=>{let o=r,{minimum:s,maximum:i,format:a,multipleOf:c,exclusiveMaximum:u,exclusiveMinimum:l}=t._zod.bag;typeof a=="string"&&a.includes("int")?o.type="integer":o.type="number";let d=typeof l=="number"&&l>=(s??Number.NEGATIVE_INFINITY),p=typeof u=="number"&&u<=(i??Number.POSITIVE_INFINITY),f=e.target==="draft-04"||e.target==="openapi-3.0";d?f?(o.minimum=l,o.exclusiveMinimum=!0):o.exclusiveMinimum=l:typeof s=="number"&&(o.minimum=s),p?f?(o.maximum=u,o.exclusiveMaximum=!0):o.exclusiveMaximum=u:typeof i=="number"&&(o.maximum=i),typeof c=="number"&&(o.multipleOf=c)},Up=(t,e,r,n)=>{r.type="boolean"};var qp=(t,e,r,n)=>{e.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"};var Zp=(t,e,r,n)=>{r.not={}};var Fp=(t,e,r,n)=>{};var Hp=(t,e,r,n)=>{let o=t._zod.def,s=Wr(o.entries);s.every(i=>typeof i=="number")&&(r.type="number"),s.every(i=>typeof i=="string")&&(r.type="string"),r.enum=s},Wp=(t,e,r,n)=>{let o=t._zod.def,s=[];for(let i of o.values)if(i===void 0){if(e.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof i=="bigint"){if(e.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");s.push(Number(i))}else s.push(i);if(s.length!==0)if(s.length===1){let i=s[0];r.type=i===null?"null":typeof i,e.target==="draft-04"||e.target==="openapi-3.0"?r.enum=[i]:r.const=i}else s.every(i=>typeof i=="number")&&(r.type="number"),s.every(i=>typeof i=="string")&&(r.type="string"),s.every(i=>typeof i=="boolean")&&(r.type="boolean"),s.every(i=>i===null)&&(r.type="null"),r.enum=s};var Vp=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")};var Gp=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")};var Kp=(t,e,r,n)=>{let o=r,s=t._zod.def,{minimum:i,maximum:a}=t._zod.bag;typeof i=="number"&&(o.minItems=i),typeof a=="number"&&(o.maxItems=a),o.type="array",o.items=ie(s.element,e,{...n,path:[...n.path,"items"]})},Jp=(t,e,r,n)=>{let o=r,s=t._zod.def;o.type="object",o.properties={};let i=s.shape;for(let u in i)o.properties[u]=ie(i[u],e,{...n,path:[...n.path,"properties",u]});let a=new Set(Object.keys(i)),c=new Set([...a].filter(u=>{let l=s.shape[u]._zod;return e.io==="input"?l.optin===void 0:l.optout===void 0}));c.size>0&&(o.required=Array.from(c)),s.catchall?._zod.def.type==="never"?o.additionalProperties=!1:s.catchall?s.catchall&&(o.additionalProperties=ie(s.catchall,e,{...n,path:[...n.path,"additionalProperties"]})):e.io==="output"&&(o.additionalProperties=!1)},Bp=(t,e,r,n)=>{let o=t._zod.def,s=o.inclusive===!1,i=o.options.map((a,c)=>ie(a,e,{...n,path:[...n.path,s?"oneOf":"anyOf",c]}));s?r.oneOf=i:r.anyOf=i},Yp=(t,e,r,n)=>{let o=t._zod.def,s=ie(o.left,e,{...n,path:[...n.path,"allOf",0]}),i=ie(o.right,e,{...n,path:[...n.path,"allOf",1]}),a=u=>"allOf"in u&&Object.keys(u).length===1,c=[...a(s)?s.allOf:[s],...a(i)?i.allOf:[i]];r.allOf=c};var Xp=(t,e,r,n)=>{let o=r,s=t._zod.def;o.type="object";let i=s.keyType,c=i._zod.bag?.patterns;if(s.mode==="loose"&&c&&c.size>0){let l=ie(s.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=ie(s.keyType,e,{...n,path:[...n.path,"propertyNames"]})),o.additionalProperties=ie(s.valueType,e,{...n,path:[...n.path,"additionalProperties"]});let u=i._zod.values;if(u){let l=[...u].filter(d=>typeof d=="string"||typeof d=="number");l.length>0&&(o.required=l)}},Qp=(t,e,r,n)=>{let o=t._zod.def,s=ie(o.innerType,e,n),i=e.seen.get(t);e.target==="openapi-3.0"?(i.ref=o.innerType,r.nullable=!0):r.anyOf=[s,{type:"null"}]},ef=(t,e,r,n)=>{let o=t._zod.def;ie(o.innerType,e,n);let s=e.seen.get(t);s.ref=o.innerType},tf=(t,e,r,n)=>{let o=t._zod.def;ie(o.innerType,e,n);let s=e.seen.get(t);s.ref=o.innerType,r.default=JSON.parse(JSON.stringify(o.defaultValue))},rf=(t,e,r,n)=>{let o=t._zod.def;ie(o.innerType,e,n);let s=e.seen.get(t);s.ref=o.innerType,e.io==="input"&&(r._prefault=JSON.parse(JSON.stringify(o.defaultValue)))},nf=(t,e,r,n)=>{let o=t._zod.def;ie(o.innerType,e,n);let s=e.seen.get(t);s.ref=o.innerType;let i;try{i=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}r.default=i},of=(t,e,r,n)=>{let o=t._zod.def,s=o.in._zod.traits.has("$ZodTransform"),i=e.io==="input"?s?o.out:o.in:o.out;ie(i,e,n);let a=e.seen.get(t);a.ref=i},sf=(t,e,r,n)=>{let o=t._zod.def;ie(o.innerType,e,n);let s=e.seen.get(t);s.ref=o.innerType,r.readOnly=!0};var Zi=(t,e,r,n)=>{let o=t._zod.def;ie(o.innerType,e,n);let s=e.seen.get(t);s.ref=o.innerType};function mr(t){return!!t._zod}function zt(t,e){return mr(t)?Br(t,e):t.safeParse(e)}function zo(t){if(!t)return;let e;if(mr(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function af(t){if(mr(t)){let s=t._zod?.def;if(s){if(s.value!==void 0)return s.value;if(Array.isArray(s.values)&&s.values.length>0)return s.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 nn={};Lu(nn,{ZodISODate:()=>uf,ZodISODateTime:()=>cf,ZodISODuration:()=>df,ZodISOTime:()=>lf,date:()=>Hi,datetime:()=>Fi,duration:()=>Vi,time:()=>Wi});var cf=g("ZodISODateTime",(t,e)=>{gd.init(t,e),re.init(t,e)});function Fi(t){return wp(cf,t)}var uf=g("ZodISODate",(t,e)=>{_d.init(t,e),re.init(t,e)});function Hi(t){return kp(uf,t)}var lf=g("ZodISOTime",(t,e)=>{yd.init(t,e),re.init(t,e)});function Wi(t){return xp(lf,t)}var df=g("ZodISODuration",(t,e)=>{Sd.init(t,e),re.init(t,e)});function Vi(t){return $p(df,t)}var vS=(t,e)=>{ho.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>Qu(t,r)},flatten:{value:r=>Xu(t,r)},addIssue:{value:r=>{t.issues.push(r),t.message=JSON.stringify(t.issues,lr,2)}},addIssues:{value:r=>{t.issues.push(...r),t.message=JSON.stringify(t.issues,lr,2)}},isEmpty:{get(){return t.issues.length===0}}})};var Le=g("ZodError",vS,{Parent:Error});var pf=go(Le),ff=_o(Le),mf=Jr(Le),hf=Yr(Le),gf=el(Le),_f=tl(Le),yf=rl(Le),Sf=nl(Le),vf=ol(Le),bf=sl(Le),Ef=il(Le),wf=al(Le);var kf=new WeakMap;function on(t,e,r){let n=Object.getPrototypeOf(t),o=kf.get(n);if(o||(o=new Set,kf.set(n,o)),!o.has(e)){o.add(e);for(let s in r){let i=r[s];Object.defineProperty(n,s,{configurable:!0,enumerable:!1,get(){let a=i.bind(this);return Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:a}),a},set(a){Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:a})}})}}}var se=g("ZodType",(t,e)=>(Y.init(t,e),Object.assign(t["~standard"],{jsonSchema:{input:tn(t,"input"),output:tn(t,"output")}}),t.toJSONSchema=Dp(t,{}),t.def=e,t.type=e.type,Object.defineProperty(t,"_def",{value:e}),t.parse=(r,n)=>pf(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>mf(t,r,n),t.parseAsync=async(r,n)=>ff(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>hf(t,r,n),t.spa=t.safeParseAsync,t.encode=(r,n)=>gf(t,r,n),t.decode=(r,n)=>_f(t,r,n),t.encodeAsync=async(r,n)=>yf(t,r,n),t.decodeAsync=async(r,n)=>Sf(t,r,n),t.safeEncode=(r,n)=>vf(t,r,n),t.safeDecode=(r,n)=>bf(t,r,n),t.safeEncodeAsync=async(r,n)=>Ef(t,r,n),t.safeDecodeAsync=async(r,n)=>wf(t,r,n),on(t,"ZodType",{check(...r){let n=this.def;return this.clone(U.mergeDefs(n,{checks:[...n.checks??[],...r.map(o=>typeof o=="function"?{_zod:{check:o,def:{check:"custom"},onattach:[]}}:o)]}),{parent:!0})},with(...r){return this.check(...r)},clone(r,n){return Ye(this,r,n)},brand(){return this},register(r,n){return r.add(this,n),this},refine(r,n){return this.check(lv(r,n))},superRefine(r,n){return this.check(dv(r,n))},overwrite(r){return this.check(Tt(r))},optional(){return oe(this)},exactOptional(){return XS(this)},nullable(){return Tf(this)},nullish(){return oe(Tf(this))},nonoptional(r){return ov(this,r)},array(){return j(this)},or(r){return Q([this,r])},and(r){return Io(this,r)},transform(r){return zf(this,Cf(r))},default(r){return tv(this,r)},prefault(r){return nv(this,r)},catch(r){return iv(this,r)},pipe(r){return zf(this,r)},readonly(){return uv(this)},describe(r){let n=this.clone();return Wt.add(n,{description:r}),n},meta(...r){if(r.length===0)return Wt.get(this);let n=this.clone();return Wt.add(n,r[0]),n},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(r){return r(this)}}),Object.defineProperty(t,"description",{get(){return Wt.get(t)?.description},configurable:!0}),t)),Rf=g("_ZodString",(t,e)=>{wo.init(t,e),se.init(t,e),t._zod.processJSONSchema=(n,o,s)=>jp(t,n,o,s);let r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,on(t,"_ZodString",{regex(...n){return this.check(Ti(...n))},includes(...n){return this.check(Ii(...n))},startsWith(...n){return this.check(Oi(...n))},endsWith(...n){return this.check(Ai(...n))},min(...n){return this.check(fr(...n))},max(...n){return this.check(Po(...n))},length(...n){return this.check(To(...n))},nonempty(...n){return this.check(fr(1,...n))},lowercase(n){return this.check(zi(n))},uppercase(n){return this.check(Ri(n))},trim(){return this.check(Ci())},normalize(...n){return this.check(Mi(...n))},toLowerCase(){return this.check(Ni())},toUpperCase(){return this.check(Di())},slugify(){return this.check(ji())}})}),ES=g("ZodString",(t,e)=>{wo.init(t,e),Rf.init(t,e),t.email=r=>t.check(rp(wS,r)),t.url=r=>t.check(ap(kS,r)),t.jwt=r=>t.check(Ep(LS,r)),t.emoji=r=>t.check(cp(xS,r)),t.guid=r=>t.check(Pi(xf,r)),t.uuid=r=>t.check(np(Ro,r)),t.uuidv4=r=>t.check(op(Ro,r)),t.uuidv6=r=>t.check(sp(Ro,r)),t.uuidv7=r=>t.check(ip(Ro,r)),t.nanoid=r=>t.check(up($S,r)),t.guid=r=>t.check(Pi(xf,r)),t.cuid=r=>t.check(lp(PS,r)),t.cuid2=r=>t.check(dp(TS,r)),t.ulid=r=>t.check(pp(zS,r)),t.base64=r=>t.check(Sp(NS,r)),t.base64url=r=>t.check(vp(DS,r)),t.xid=r=>t.check(fp(RS,r)),t.ksuid=r=>t.check(mp(IS,r)),t.ipv4=r=>t.check(hp(OS,r)),t.ipv6=r=>t.check(gp(AS,r)),t.cidrv4=r=>t.check(_p(MS,r)),t.cidrv6=r=>t.check(yp(CS,r)),t.e164=r=>t.check(bp(jS,r)),t.datetime=r=>t.check(Fi(r)),t.date=r=>t.check(Hi(r)),t.time=r=>t.check(Wi(r)),t.duration=r=>t.check(Vi(r))});function h(t){return tp(ES,t)}var re=g("ZodStringFormat",(t,e)=>{X.init(t,e),Rf.init(t,e)}),wS=g("ZodEmail",(t,e)=>{ad.init(t,e),re.init(t,e)});var xf=g("ZodGUID",(t,e)=>{sd.init(t,e),re.init(t,e)});var Ro=g("ZodUUID",(t,e)=>{id.init(t,e),re.init(t,e)});var kS=g("ZodURL",(t,e)=>{cd.init(t,e),re.init(t,e)});var xS=g("ZodEmoji",(t,e)=>{ud.init(t,e),re.init(t,e)});var $S=g("ZodNanoID",(t,e)=>{ld.init(t,e),re.init(t,e)});var PS=g("ZodCUID",(t,e)=>{dd.init(t,e),re.init(t,e)});var TS=g("ZodCUID2",(t,e)=>{pd.init(t,e),re.init(t,e)});var zS=g("ZodULID",(t,e)=>{fd.init(t,e),re.init(t,e)});var RS=g("ZodXID",(t,e)=>{md.init(t,e),re.init(t,e)});var IS=g("ZodKSUID",(t,e)=>{hd.init(t,e),re.init(t,e)});var OS=g("ZodIPv4",(t,e)=>{vd.init(t,e),re.init(t,e)});var AS=g("ZodIPv6",(t,e)=>{bd.init(t,e),re.init(t,e)});var MS=g("ZodCIDRv4",(t,e)=>{Ed.init(t,e),re.init(t,e)});var CS=g("ZodCIDRv6",(t,e)=>{wd.init(t,e),re.init(t,e)});var NS=g("ZodBase64",(t,e)=>{xd.init(t,e),re.init(t,e)});var DS=g("ZodBase64URL",(t,e)=>{$d.init(t,e),re.init(t,e)});var jS=g("ZodE164",(t,e)=>{Pd.init(t,e),re.init(t,e)});var LS=g("ZodJWT",(t,e)=>{Td.init(t,e),re.init(t,e)});var If=g("ZodNumber",(t,e)=>{Ei.init(t,e),se.init(t,e),t._zod.processJSONSchema=(n,o,s)=>Lp(t,n,o,s),on(t,"ZodNumber",{gt(n,o){return this.check(xo(n,o))},gte(n,o){return this.check(en(n,o))},min(n,o){return this.check(en(n,o))},lt(n,o){return this.check(ko(n,o))},lte(n,o){return this.check(Qr(n,o))},max(n,o){return this.check(Qr(n,o))},int(n){return this.check($f(n))},safe(n){return this.check($f(n))},positive(n){return this.check(xo(0,n))},nonnegative(n){return this.check(en(0,n))},negative(n){return this.check(ko(0,n))},nonpositive(n){return this.check(Qr(0,n))},multipleOf(n,o){return this.check($o(n,o))},step(n,o){return this.check($o(n,o))},finite(){return this}});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 W(t){return Pp(If,t)}var US=g("ZodNumberFormat",(t,e)=>{zd.init(t,e),If.init(t,e)});function $f(t){return Tp(US,t)}var qS=g("ZodBoolean",(t,e)=>{Rd.init(t,e),se.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Up(t,r,n,o)});function pe(t){return zp(qS,t)}var ZS=g("ZodNull",(t,e)=>{Id.init(t,e),se.init(t,e),t._zod.processJSONSchema=(r,n,o)=>qp(t,r,n,o)});function Of(t){return Rp(ZS,t)}var FS=g("ZodUnknown",(t,e)=>{Od.init(t,e),se.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Fp(t,r,n,o)});function ne(){return Ip(FS)}var HS=g("ZodNever",(t,e)=>{Ad.init(t,e),se.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Zp(t,r,n,o)});function WS(t){return Op(HS,t)}var VS=g("ZodArray",(t,e)=>{Md.init(t,e),se.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Kp(t,r,n,o),t.element=e.element,on(t,"ZodArray",{min(r,n){return this.check(fr(r,n))},nonempty(r){return this.check(fr(1,r))},max(r,n){return this.check(Po(r,n))},length(r,n){return this.check(To(r,n))},unwrap(){return this.element}})});function j(t,e){return Ap(VS,t,e)}var Af=g("ZodObject",(t,e)=>{Dd.init(t,e),se.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Jp(t,r,n,o),U.defineLazy(t,"shape",()=>e.shape),on(t,"ZodObject",{keyof(){return Oe(Object.keys(this._zod.def.shape))},catchall(r){return this.clone({...this._zod.def,catchall:r})},passthrough(){return this.clone({...this._zod.def,catchall:ne()})},loose(){return this.clone({...this._zod.def,catchall:ne()})},strict(){return this.clone({...this._zod.def,catchall:WS()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(r){return U.extend(this,r)},safeExtend(r){return U.safeExtend(this,r)},merge(r){return U.merge(this,r)},pick(r){return U.pick(this,r)},omit(r){return U.omit(this,r)},partial(...r){return U.partial(Nf,this,r[0])},required(...r){return U.required(Df,this,r[0])}})});function k(t,e){let r={type:"object",shape:t??{},...U.normalizeParams(e)};return new Af(r)}function Te(t,e){return new Af({type:"object",shape:t,catchall:ne(),...U.normalizeParams(e)})}var Mf=g("ZodUnion",(t,e)=>{wi.init(t,e),se.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Bp(t,r,n,o),t.options=e.options});function Q(t,e){return new Mf({type:"union",options:t,...U.normalizeParams(e)})}var GS=g("ZodDiscriminatedUnion",(t,e)=>{Mf.init(t,e),jd.init(t,e)});function Ki(t,e,r){return new GS({type:"union",options:e,discriminator:t,...U.normalizeParams(r)})}var KS=g("ZodIntersection",(t,e)=>{Ld.init(t,e),se.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Yp(t,r,n,o)});function Io(t,e){return new KS({type:"intersection",left:t,right:e})}var Pf=g("ZodRecord",(t,e)=>{Ud.init(t,e),se.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Xp(t,r,n,o),t.keyType=e.keyType,t.valueType=e.valueType});function J(t,e,r){return!e||!e._zod?new Pf({type:"record",keyType:h(),valueType:t,...U.normalizeParams(e)}):new Pf({type:"record",keyType:t,valueType:e,...U.normalizeParams(r)})}var Gi=g("ZodEnum",(t,e)=>{qd.init(t,e),se.init(t,e),t._zod.processJSONSchema=(n,o,s)=>Hp(t,n,o,s),t.enum=e.entries,t.options=Object.values(e.entries);let r=new Set(Object.keys(e.entries));t.extract=(n,o)=>{let s={};for(let i of n)if(r.has(i))s[i]=e.entries[i];else throw new Error(`Key ${i} not found in enum`);return new Gi({...e,checks:[],...U.normalizeParams(o),entries:s})},t.exclude=(n,o)=>{let s={...e.entries};for(let i of n)if(r.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new Gi({...e,checks:[],...U.normalizeParams(o),entries:s})}});function Oe(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new Gi({type:"enum",entries:r,...U.normalizeParams(e)})}var JS=g("ZodLiteral",(t,e)=>{Zd.init(t,e),se.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Wp(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 P(t,e){return new JS({type:"literal",values:Array.isArray(t)?t:[t],...U.normalizeParams(e)})}var BS=g("ZodTransform",(t,e)=>{Fd.init(t,e),se.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Gp(t,r,n,o),t._zod.parse=(r,n)=>{if(n.direction==="backward")throw new cr(t.constructor.name);r.addIssue=s=>{if(typeof s=="string")r.issues.push(U.issue(s,r.value,e));else{let i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=t),r.issues.push(U.issue(i))}};let o=e.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r.fallback=!0,r)):(r.value=o,r.fallback=!0,r)}});function Cf(t){return new BS({type:"transform",transform:t})}var Nf=g("ZodOptional",(t,e)=>{ki.init(t,e),se.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Zi(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function oe(t){return new Nf({type:"optional",innerType:t})}var YS=g("ZodExactOptional",(t,e)=>{Hd.init(t,e),se.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Zi(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function XS(t){return new YS({type:"optional",innerType:t})}var QS=g("ZodNullable",(t,e)=>{Wd.init(t,e),se.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Qp(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function Tf(t){return new QS({type:"nullable",innerType:t})}var ev=g("ZodDefault",(t,e)=>{Vd.init(t,e),se.init(t,e),t._zod.processJSONSchema=(r,n,o)=>tf(t,r,n,o),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function tv(t,e){return new ev({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():U.shallowClone(e)}})}var rv=g("ZodPrefault",(t,e)=>{Gd.init(t,e),se.init(t,e),t._zod.processJSONSchema=(r,n,o)=>rf(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function nv(t,e){return new rv({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():U.shallowClone(e)}})}var Df=g("ZodNonOptional",(t,e)=>{Kd.init(t,e),se.init(t,e),t._zod.processJSONSchema=(r,n,o)=>ef(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function ov(t,e){return new Df({type:"nonoptional",innerType:t,...U.normalizeParams(e)})}var sv=g("ZodCatch",(t,e)=>{Jd.init(t,e),se.init(t,e),t._zod.processJSONSchema=(r,n,o)=>nf(t,r,n,o),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function iv(t,e){return new sv({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var jf=g("ZodPipe",(t,e)=>{xi.init(t,e),se.init(t,e),t._zod.processJSONSchema=(r,n,o)=>of(t,r,n,o),t.in=e.in,t.out=e.out});function zf(t,e){return new jf({type:"pipe",in:t,out:e})}var av=g("ZodPreprocess",(t,e)=>{jf.init(t,e),Bd.init(t,e)}),cv=g("ZodReadonly",(t,e)=>{Yd.init(t,e),se.init(t,e),t._zod.processJSONSchema=(r,n,o)=>sf(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function uv(t){return new cv({type:"readonly",innerType:t})}var Lf=g("ZodCustom",(t,e)=>{Xd.init(t,e),se.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Vp(t,r,n,o)});function Uf(t,e){return Mp(Lf,t??(()=>!0),e)}function lv(t,e={}){return Cp(Lf,t,e)}function dv(t,e){return Np(t,e)}function Ji(t,e){return new av({type:"pipe",in:Cf(t),out:e})}je(Qd());var Yi="2025-11-25";var qf=[Yi,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Rt="io.modelcontextprotocol/related-task",Ao="2.0",de=Uf(t=>t!==null&&(typeof t=="object"||typeof t=="function")),Zf=Q([h(),W().int()]),Ff=h(),XR=Te({ttl:W().optional(),pollInterval:W().optional()}),pv=k({ttl:W().optional()}),fv=k({taskId:h()}),Xi=Te({progressToken:Zf.optional(),[Rt]:fv.optional()}),Ue=k({_meta:Xi.optional()}),sn=Ue.extend({task:pv.optional()}),Hf=t=>sn.safeParse(t).success,me=k({method:h(),params:Ue.loose().optional()}),Ze=k({_meta:Xi.optional()}),Fe=k({method:h(),params:Ze.loose().optional()}),he=Te({_meta:Xi.optional()}),Mo=Q([h(),W().int()]),Wf=k({jsonrpc:P(Ao),id:Mo,...me.shape}).strict(),Qi=t=>Wf.safeParse(t).success,Vf=k({jsonrpc:P(Ao),...Fe.shape}).strict(),Gf=t=>Vf.safeParse(t).success,ea=k({jsonrpc:P(Ao),id:Mo,result:he}).strict(),an=t=>ea.safeParse(t).success;var N;(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"})(N||(N={}));var ta=k({jsonrpc:P(Ao),id:Mo.optional(),error:k({code:W().int(),message:h(),data:ne().optional()})}).strict();var Kf=t=>ta.safeParse(t).success;var Jf=Q([Wf,Vf,ea,ta]),QR=Q([ea,ta]),Co=he.strict(),mv=Ze.extend({requestId:Mo.optional(),reason:h().optional()}),No=Fe.extend({method:P("notifications/cancelled"),params:mv}),hv=k({src:h(),mimeType:h().optional(),sizes:j(h()).optional(),theme:Oe(["light","dark"]).optional()}),cn=k({icons:j(hv).optional()}),hr=k({name:h(),title:h().optional()}),Bf=hr.extend({...hr.shape,...cn.shape,version:h(),websiteUrl:h().optional(),description:h().optional()}),gv=Io(k({applyDefaults:pe().optional()}),J(h(),ne())),_v=Ji(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,Io(k({form:gv.optional(),url:de.optional()}),J(h(),ne()).optional())),yv=Te({list:de.optional(),cancel:de.optional(),requests:Te({sampling:Te({createMessage:de.optional()}).optional(),elicitation:Te({create:de.optional()}).optional()}).optional()}),Sv=Te({list:de.optional(),cancel:de.optional(),requests:Te({tools:Te({call:de.optional()}).optional()}).optional()}),vv=k({experimental:J(h(),de).optional(),sampling:k({context:de.optional(),tools:de.optional()}).optional(),elicitation:_v.optional(),roots:k({listChanged:pe().optional()}).optional(),tasks:yv.optional(),extensions:J(h(),de).optional()}),bv=Ue.extend({protocolVersion:h(),capabilities:vv,clientInfo:Bf}),ra=me.extend({method:P("initialize"),params:bv});var Ev=k({experimental:J(h(),de).optional(),logging:de.optional(),completions:de.optional(),prompts:k({listChanged:pe().optional()}).optional(),resources:k({subscribe:pe().optional(),listChanged:pe().optional()}).optional(),tools:k({listChanged:pe().optional()}).optional(),tasks:Sv.optional(),extensions:J(h(),de).optional()}),wv=he.extend({protocolVersion:h(),capabilities:Ev,serverInfo:Bf,instructions:h().optional()}),na=Fe.extend({method:P("notifications/initialized"),params:Ze.optional()});var Do=me.extend({method:P("ping"),params:Ue.optional()}),kv=k({progress:W(),total:oe(W()),message:oe(h())}),xv=k({...Ze.shape,...kv.shape,progressToken:Zf}),jo=Fe.extend({method:P("notifications/progress"),params:xv}),$v=Ue.extend({cursor:Ff.optional()}),un=me.extend({params:$v.optional()}),ln=he.extend({nextCursor:Ff.optional()}),Pv=Oe(["working","input_required","completed","failed","cancelled"]),dn=k({taskId:h(),status:Pv,ttl:Q([W(),Of()]),createdAt:h(),lastUpdatedAt:h(),pollInterval:oe(W()),statusMessage:oe(h())}),gr=he.extend({task:dn}),Tv=Ze.merge(dn),pn=Fe.extend({method:P("notifications/tasks/status"),params:Tv}),Lo=me.extend({method:P("tasks/get"),params:Ue.extend({taskId:h()})}),Uo=he.merge(dn),qo=me.extend({method:P("tasks/result"),params:Ue.extend({taskId:h()})}),eI=he.loose(),Zo=un.extend({method:P("tasks/list")}),Fo=ln.extend({tasks:j(dn)}),Ho=me.extend({method:P("tasks/cancel"),params:Ue.extend({taskId:h()})}),Yf=he.merge(dn),Xf=k({uri:h(),mimeType:oe(h()),_meta:J(h(),ne()).optional()}),Qf=Xf.extend({text:h()}),oa=h().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),em=Xf.extend({blob:oa}),fn=Oe(["user","assistant"]),_r=k({audience:j(fn).optional(),priority:W().min(0).max(1).optional(),lastModified:nn.datetime({offset:!0}).optional()}),tm=k({...hr.shape,...cn.shape,uri:h(),description:oe(h()),mimeType:oe(h()),size:oe(W()),annotations:_r.optional(),_meta:oe(Te({}))}),zv=k({...hr.shape,...cn.shape,uriTemplate:h(),description:oe(h()),mimeType:oe(h()),annotations:_r.optional(),_meta:oe(Te({}))}),Rv=un.extend({method:P("resources/list")}),Iv=ln.extend({resources:j(tm)}),Ov=un.extend({method:P("resources/templates/list")}),Av=ln.extend({resourceTemplates:j(zv)}),sa=Ue.extend({uri:h()}),Mv=sa,Cv=me.extend({method:P("resources/read"),params:Mv}),Nv=he.extend({contents:j(Q([Qf,em]))}),Dv=Fe.extend({method:P("notifications/resources/list_changed"),params:Ze.optional()}),jv=sa,Lv=me.extend({method:P("resources/subscribe"),params:jv}),Uv=sa,qv=me.extend({method:P("resources/unsubscribe"),params:Uv}),Zv=Ze.extend({uri:h()}),Fv=Fe.extend({method:P("notifications/resources/updated"),params:Zv}),Hv=k({name:h(),description:oe(h()),required:oe(pe())}),Wv=k({...hr.shape,...cn.shape,description:oe(h()),arguments:oe(j(Hv)),_meta:oe(Te({}))}),Vv=un.extend({method:P("prompts/list")}),Gv=ln.extend({prompts:j(Wv)}),Kv=Ue.extend({name:h(),arguments:J(h(),h()).optional()}),Jv=me.extend({method:P("prompts/get"),params:Kv}),ia=k({type:P("text"),text:h(),annotations:_r.optional(),_meta:J(h(),ne()).optional()}),aa=k({type:P("image"),data:oa,mimeType:h(),annotations:_r.optional(),_meta:J(h(),ne()).optional()}),ca=k({type:P("audio"),data:oa,mimeType:h(),annotations:_r.optional(),_meta:J(h(),ne()).optional()}),Bv=k({type:P("tool_use"),name:h(),id:h(),input:J(h(),ne()),_meta:J(h(),ne()).optional()}),Yv=k({type:P("resource"),resource:Q([Qf,em]),annotations:_r.optional(),_meta:J(h(),ne()).optional()}),Xv=tm.extend({type:P("resource_link")}),ua=Q([ia,aa,ca,Xv,Yv]),Qv=k({role:fn,content:ua}),eb=he.extend({description:h().optional(),messages:j(Qv)}),tb=Fe.extend({method:P("notifications/prompts/list_changed"),params:Ze.optional()}),rb=k({title:h().optional(),readOnlyHint:pe().optional(),destructiveHint:pe().optional(),idempotentHint:pe().optional(),openWorldHint:pe().optional()}),nb=k({taskSupport:Oe(["required","optional","forbidden"]).optional()}),rm=k({...hr.shape,...cn.shape,description:h().optional(),inputSchema:k({type:P("object"),properties:J(h(),de).optional(),required:j(h()).optional()}).catchall(ne()),outputSchema:k({type:P("object"),properties:J(h(),de).optional(),required:j(h()).optional()}).catchall(ne()).optional(),annotations:rb.optional(),execution:nb.optional(),_meta:J(h(),ne()).optional()}),la=un.extend({method:P("tools/list")}),ob=ln.extend({tools:j(rm)}),Wo=he.extend({content:j(ua).default([]),structuredContent:J(h(),ne()).optional(),isError:pe().optional()}),tI=Wo.or(he.extend({toolResult:ne()})),sb=sn.extend({name:h(),arguments:J(h(),ne()).optional()}),mn=me.extend({method:P("tools/call"),params:sb}),ib=Fe.extend({method:P("notifications/tools/list_changed"),params:Ze.optional()}),rI=k({autoRefresh:pe().default(!0),debounceMs:W().int().nonnegative().default(300)}),hn=Oe(["debug","info","notice","warning","error","critical","alert","emergency"]),ab=Ue.extend({level:hn}),da=me.extend({method:P("logging/setLevel"),params:ab}),cb=Ze.extend({level:hn,logger:h().optional(),data:ne()}),ub=Fe.extend({method:P("notifications/message"),params:cb}),lb=k({name:h().optional()}),db=k({hints:j(lb).optional(),costPriority:W().min(0).max(1).optional(),speedPriority:W().min(0).max(1).optional(),intelligencePriority:W().min(0).max(1).optional()}),pb=k({mode:Oe(["auto","required","none"]).optional()}),fb=k({type:P("tool_result"),toolUseId:h().describe("The unique identifier for the corresponding tool call."),content:j(ua).default([]),structuredContent:k({}).loose().optional(),isError:pe().optional(),_meta:J(h(),ne()).optional()}),mb=Ki("type",[ia,aa,ca]),Oo=Ki("type",[ia,aa,ca,Bv,fb]),hb=k({role:fn,content:Q([Oo,j(Oo)]),_meta:J(h(),ne()).optional()}),gb=sn.extend({messages:j(hb),modelPreferences:db.optional(),systemPrompt:h().optional(),includeContext:Oe(["none","thisServer","allServers"]).optional(),temperature:W().optional(),maxTokens:W().int(),stopSequences:j(h()).optional(),metadata:de.optional(),tools:j(rm).optional(),toolChoice:pb.optional()}),_b=me.extend({method:P("sampling/createMessage"),params:gb}),gn=he.extend({model:h(),stopReason:oe(Oe(["endTurn","stopSequence","maxTokens"]).or(h())),role:fn,content:mb}),pa=he.extend({model:h(),stopReason:oe(Oe(["endTurn","stopSequence","maxTokens","toolUse"]).or(h())),role:fn,content:Q([Oo,j(Oo)])}),yb=k({type:P("boolean"),title:h().optional(),description:h().optional(),default:pe().optional()}),Sb=k({type:P("string"),title:h().optional(),description:h().optional(),minLength:W().optional(),maxLength:W().optional(),format:Oe(["email","uri","date","date-time"]).optional(),default:h().optional()}),vb=k({type:Oe(["number","integer"]),title:h().optional(),description:h().optional(),minimum:W().optional(),maximum:W().optional(),default:W().optional()}),bb=k({type:P("string"),title:h().optional(),description:h().optional(),enum:j(h()),default:h().optional()}),Eb=k({type:P("string"),title:h().optional(),description:h().optional(),oneOf:j(k({const:h(),title:h()})),default:h().optional()}),wb=k({type:P("string"),title:h().optional(),description:h().optional(),enum:j(h()),enumNames:j(h()).optional(),default:h().optional()}),kb=Q([bb,Eb]),xb=k({type:P("array"),title:h().optional(),description:h().optional(),minItems:W().optional(),maxItems:W().optional(),items:k({type:P("string"),enum:j(h())}),default:j(h()).optional()}),$b=k({type:P("array"),title:h().optional(),description:h().optional(),minItems:W().optional(),maxItems:W().optional(),items:k({anyOf:j(k({const:h(),title:h()}))}),default:j(h()).optional()}),Pb=Q([xb,$b]),Tb=Q([wb,kb,Pb]),zb=Q([Tb,yb,Sb,vb]),Rb=sn.extend({mode:P("form").optional(),message:h(),requestedSchema:k({type:P("object"),properties:J(h(),zb),required:j(h()).optional()})}),Ib=sn.extend({mode:P("url"),message:h(),elicitationId:h(),url:h().url()}),Ob=Q([Rb,Ib]),Ab=me.extend({method:P("elicitation/create"),params:Ob}),Mb=Ze.extend({elicitationId:h()}),Cb=Fe.extend({method:P("notifications/elicitation/complete"),params:Mb}),yr=he.extend({action:Oe(["accept","decline","cancel"]),content:Ji(t=>t===null?void 0:t,J(h(),Q([h(),W(),pe(),j(h())])).optional())}),Nb=k({type:P("ref/resource"),uri:h()});var Db=k({type:P("ref/prompt"),name:h()}),jb=Ue.extend({ref:Q([Db,Nb]),argument:k({name:h(),value:h()}),context:k({arguments:J(h(),h()).optional()}).optional()}),Lb=me.extend({method:P("completion/complete"),params:jb});var Ub=he.extend({completion:Te({values:j(h()).max(100),total:oe(W().int()),hasMore:oe(pe())})}),qb=k({uri:h().startsWith("file://"),name:h().optional(),_meta:J(h(),ne()).optional()}),Zb=me.extend({method:P("roots/list"),params:Ue.optional()}),fa=he.extend({roots:j(qb)}),Fb=Fe.extend({method:P("notifications/roots/list_changed"),params:Ze.optional()}),nI=Q([Do,ra,Lb,da,Jv,Vv,Rv,Ov,Cv,Lv,qv,mn,la,Lo,qo,Zo,Ho]),oI=Q([No,jo,na,Fb,pn]),sI=Q([Co,gn,pa,yr,fa,Uo,Fo,gr]),iI=Q([Do,_b,Ab,Zb,Lo,qo,Zo,Ho]),aI=Q([No,jo,ub,Fv,Dv,ib,tb,pn,Cb]),cI=Q([Co,wv,Ub,eb,Gv,Iv,Av,Nv,Wo,ob,Uo,Fo,gr]),I=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===N.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new Bi(o.elicitations,r)}return new t(e,r,n)}},Bi=class extends I{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(N.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function It(t){return t==="completed"||t==="failed"||t==="cancelled"}var qI=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function ma(t){let r=zo(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=af(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function ha(t,e){let r=zt(t,e);if(!r.success)throw r.error;return r.data}var Jb=6e4,Vo=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(No,r=>{this._oncancel(r)}),this.setNotificationHandler(jo,r=>{this._onprogress(r)}),this.setRequestHandler(Do,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Lo,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new I(N.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(qo,async(r,n)=>{let o=async()=>{let s=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(s,n.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,u=c.id,l=this._requestResolvers.get(u);if(l)if(this._requestResolvers.delete(u),a.type==="response")l(c);else{let d=c,p=new I(d.error.code,d.error.message,d.error.data);l(p)}else{let d=a.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${u}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let i=await this._taskStore.getTask(s,n.sessionId);if(!i)throw new I(N.InvalidParams,`Task not found: ${s}`);if(!It(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(It(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[Rt]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(Zo,async(r,n)=>{try{let{tasks:o,nextCursor:s}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:s,_meta:{}}}catch(o){throw new I(N.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(Ho,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new I(N.InvalidParams,`Task not found: ${r.params.taskId}`);if(It(o.status))throw new I(N.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 s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new I(N.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof I?o:new I(N.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,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:s,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),I.fromError(N.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){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=s=>{n?.(s),this._onerror(s)};let o=this._transport?.onmessage;this._transport.onmessage=(s,i)=>{o?.(s,i),an(s)||Kf(s)?this._onresponse(s):Qi(s)?this._onrequest(s,i):Gf(s)?this._onnotification(s):this._onerror(new Error(`Unknown message type: ${JSON.stringify(s)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let r=I.fromError(N.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,s=e.params?._meta?.[Rt]?.taskId;if(n===void 0){let l={jsonrpc:"2.0",id:e.id,error:{code:N.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{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 i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let a=Hf(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,u={signal:i.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async l=>{if(i.signal.aborted)return;let d={relatedRequestId:e.id};s&&(d.relatedTask={taskId:s}),await this.notification(l,d)},sendRequest:async(l,d,p)=>{if(i.signal.aborted)throw new I(N.ConnectionClosed,"Request was cancelled");let f={...p,relatedRequestId:e.id};s&&!f.relatedTask&&(f.relatedTask={taskId:s});let m=f.relatedTask?.taskId??s;return m&&c&&await c.updateTaskStatus(m,"input_required"),await this.request(l,d,f)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:s,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,u)).then(async l=>{if(i.signal.aborted)return;let d={result:l,jsonrpc:"2.0",id:e.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)},async l=>{if(i.signal.aborted)return;let d={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(l.code)?l.code:N.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{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.get(e.id)===i&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,o=Number(r),s=this._progressHandlers.get(o);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),i(c);return}s(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),an(e))n(e);else{let i=new I(e.error.code,e.error.message,e.error.data);n(i)}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 s=!1;if(an(e)&&e.result&&typeof e.result=="object"){let i=e.result;if(i.task&&typeof i.task=="object"){let a=i.task;typeof a.taskId=="string"&&(s=!0,this._taskProgressTokens.set(a.taskId,r))}}if(s||this._progressHandlers.delete(r),an(e))o(e);else{let i=I.fromError(e.error.code,e.error.message,e.error.data);o(i)}}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(i){yield{type:"error",error:i instanceof I?i:new I(N.InternalError,String(i))}}return}let s;try{let i=await this.request(e,gr,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new I(N.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},It(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:a.status==="failed"?yield{type:"error",error:new I(N.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new I(N.InternalError,`Task ${s} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),n?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof I?i:new I(N.InternalError,String(i))}}}request(e,r,n){let{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i,task:a,relatedTask:c}=n??{};return new Promise((u,l)=>{let d=E=>{l(E)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(E){d(E);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}}),a&&(f.params={...f.params,task:a}),c&&(f.params={...f.params,_meta:{...f.params?._meta||{},[Rt]:c}});let m=E=>{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(E)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch($=>this._onerror(new Error(`Failed to send cancellation: ${$}`)));let v=E instanceof I?E:new I(N.RequestTimeout,String(E));l(v)};this._responseHandlers.set(p,E=>{if(!n?.signal?.aborted){if(E instanceof Error)return l(E);try{let v=zt(r,E.result);v.success?u(v.data):l(v.error)}catch(v){l(v)}}}),n?.signal?.addEventListener("abort",()=>{m(n?.signal?.reason)});let _=n?.timeout??Jb,S=()=>m(I.fromError(N.RequestTimeout,"Request timed out",{timeout:_}));this._setupTimeout(p,_,n?.maxTotalTimeout,S,n?.resetTimeoutOnProgress??!1);let b=c?.taskId;if(b){let E=v=>{let $=this._responseHandlers.get(p);$?$(v):this._onerror(new Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,E),this._enqueueTaskMessage(b,{type:"request",message:f,timestamp:Date.now()}).catch(v=>{this._cleanupTimeout(p),l(v)})}else this._transport.send(f,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(E=>{this._cleanupTimeout(p),l(E)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},Uo,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},Fo,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},Yf,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 a={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[Rt]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:a,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 a={...e,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[Rt]:r.relatedTask}}}),this._transport?.send(a,r).catch(c=>this._onerror(c))});return}let i={...e,jsonrpc:"2.0"};r?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[Rt]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=ma(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=ha(e,o);return Promise.resolve(r(i,s))})}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=ma(e);this._notificationHandlers.set(n,o=>{let s=ha(e,o);return Promise.resolve(r(s))})}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"&&Qi(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new I(N.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(s)):this._onerror(new Error(`Resolver missing for request ${s} 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,s)=>{if(r.aborted){s(new I(N.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(i),s(new I(N.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 s=await n.getTask(o,r);if(!s)throw new I(N.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(o,s,i)=>{await n.storeTaskResult(o,s,i,r);let a=await n.getTask(o,r);if(a){let c=pn.parse({method:"notifications/tasks/status",params:a});await this.notification(c),It(a.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,s,i)=>{let a=await n.getTask(o,r);if(!a)throw new I(N.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(It(a.status))throw new I(N.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,s,i,r);let c=await n.getTask(o,r);if(c){let u=pn.parse({method:"notifications/tasks/status",params:c});await this.notification(u),It(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function nm(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function om(t,e){let r={...t};for(let n in e){let o=n,s=e[o];if(s===void 0)continue;let i=r[o];nm(i)&&nm(s)?r[o]={...i,...s}:r[o]=s}return r}var Jg=Ft(tu(),1),Bg=Ft(Kg(),1);function X$(){let t=new Jg.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,Bg.default)(t),t}var Ps=class{constructor(e){this._ajv=e??X$()}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 Ts=class{constructor(e){this._server=e}requestStream(e,r,n){return this._server.requestStream(e,r,n)}createMessageStream(e,r){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let o=e.messages[e.messages.length-1],s=Array.isArray(o.content)?o.content:[o.content],i=s.some(l=>l.type==="tool_result"),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,c=a?Array.isArray(a.content)?a.content:[a.content]:[],u=c.some(l=>l.type==="tool_use");if(i){if(s.some(l=>l.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!u)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(u){let l=new Set(c.filter(p=>p.type==="tool_use").map(p=>p.id)),d=new Set(s.filter(p=>p.type==="tool_result").map(p=>p.toolUseId));if(l.size!==d.size||![...l].every(p=>d.has(p)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:e},gn,r)}elicitInputStream(e,r){let n=this._server.getClientCapabilities(),o=e.mode??"form";switch(o){case"url":{if(!n?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!n?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let s=o==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:s},yr,r)}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 Yg(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 Xg(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 zs=class extends Vo{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(hn.options.map((n,o)=>[n,o])),this.isMessageIgnored=(n,o)=>{let s=this._loggingLevels.get(o);return s?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(s):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new Ps,this.setRequestHandler(ra,n=>this._oninitialize(n)),this.setNotificationHandler(na,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(da,async(n,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=hn.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Ts(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=om(this._capabilities,e)}setRequestHandler(e,r){let o=zo(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s;if(mr(o)){let a=o;s=a._zod?.def?.value??a.value}else{let a=o;s=a._def?.value??a.value}if(typeof s!="string")throw new Error("Schema method literal must be a string");if(s==="tools/call"){let a=async(c,u)=>{let l=zt(mn,c);if(!l.success){let m=l.error instanceof Error?l.error.message:String(l.error);throw new I(N.InvalidParams,`Invalid tools/call request: ${m}`)}let{params:d}=l.data,p=await Promise.resolve(r(c,u));if(d.task){let m=zt(gr,p);if(!m.success){let _=m.error instanceof Error?m.error.message:String(m.error);throw new I(N.InvalidParams,`Invalid task creation result: ${_}`)}return m.data}let f=zt(Wo,p);if(!f.success){let m=f.error instanceof Error?f.error.message:String(f.error);throw new I(N.InvalidParams,`Invalid tools/call result: ${m}`)}return f.data};return super.setRequestHandler(e,a)}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){Xg(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&Yg(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:qf.includes(r)?r:Yi,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"},Co)}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],s=o.some(u=>u.type==="tool_result"),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],c=a.some(u=>u.type==="tool_use");if(s){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(a.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},pa,r):this.request({method:"sampling/createMessage",params:e},gn,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},yr,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"},s=await this.request({method:"elicitation/create",params:o},yr,r);if(s.action==="accept"&&s.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(s.content);if(!a.valid)throw new I(N.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof I?i:new I(N.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return s}}}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},fa,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 uu=Ft(require("node:process"),1);var Rs=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
81
81
  `);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),Q$(r)}clear(){this._buffer=void 0}};function Q$(t){return Jf.parse(JSON.parse(t))}function Qg(t){return JSON.stringify(t)+`
82
82
  `}var Is=class{constructor(e=uu.default.stdin,r=uu.default.stdout){this._stdin=e,this._stdout=r,this._readBuffer=new Rs,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=Qg(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};var Fs=Ft(require("path"),1),qt=require("fs");var e_=require("node:child_process");function Gn(t,e,r){return(0,e_.spawn)(t,e??[],{windowsHide:!0,...r})}var ue={DEFAULT:3e5,HEALTH_CHECK:3e3,API_REQUEST:3e4,HOOK_READINESS_WAIT:1e4,POST_SPAWN_WAIT:15e3,READINESS_WAIT:3e4,PORT_IN_USE_WAIT:3e3,WORKER_STARTUP_WAIT:1e3,PRE_RESTART_SETTLE_DELAY:2e3,POWERSHELL_COMMAND:1e4,WINDOWS_MULTIPLIER:1.5};function Et(t){return process.platform==="win32"?Math.round(t*ue.WINDOWS_MULTIPLIER):t}var dt=require("fs"),Kn=require("path"),lu=require("os");var V=require("fs");var lt=require("path");var t_=require("crypto");var eP=process.platform==="win32";function tP(t){(0,V.existsSync)(t)||(0,V.mkdirSync)(t,{recursive:!0})}function Os(t,e){let r=t;try{if((0,V.lstatSync)(t).isSymbolicLink())try{r=(0,V.realpathSync)(t)}catch{let u=(0,V.readlinkSync)(t);r=(0,lt.resolve)((0,lt.dirname)(t),u)}}catch(u){let l=u.code;if(l!=="ENOENT"&&l!=="ENOTDIR")throw u}tP((0,lt.dirname)(r));let n=(0,lt.dirname)(r),o=(0,lt.basename)(r),s=(0,lt.join)(n,`.${o}.${process.pid}.${(0,t_.randomBytes)(6).toString("hex")}.tmp`),i=Buffer.from(JSON.stringify(e,null,2)+`
83
- `,"utf-8"),a;try{a=(0,V.statSync)(r).mode&511}catch{}let c;try{c=a!==void 0?(0,V.openSync)(s,"w",a):(0,V.openSync)(s,"w");let u=0;for(;u<i.length;){let l=(0,V.writeSync)(c,i,u,i.length-u);if(l===0)throw new Error(`writeSync stalled at ${u}/${i.length} bytes`);u+=l}if((0,V.fsyncSync)(c),(0,V.closeSync)(c),c=void 0,(0,V.renameSync)(s,r),!eP){let l;try{l=(0,V.openSync)(n,"r"),(0,V.fsyncSync)(l)}catch{}finally{if(l!==void 0)try{(0,V.closeSync)(l)}catch{}}}}catch(u){if(c!==void 0)try{(0,V.closeSync)(c)}catch{}try{(0,V.unlinkSync)(s)}catch{}throw u}}var nr=class{static DEFAULTS={CLAUDE_MEM_MODEL:"claude-haiku-4-5-20251001",CLAUDE_MEM_CONTEXT_OBSERVATIONS:"50",CLAUDE_MEM_WORKER_PORT:String(37700+(process.getuid?.()??77)%100),CLAUDE_MEM_WORKER_HOST:"127.0.0.1",CLAUDE_MEM_API_TIMEOUT_MS:String(Et(ue.API_REQUEST)),CLAUDE_MEM_SKIP_TOOLS:"ListMcpResourcesTool,SlashCommand,Skill,TodoWrite,AskUserQuestion",CLAUDE_MEM_PROVIDER:"claude",CLAUDE_MEM_CLAUDE_AUTH_METHOD:"subscription",CLAUDE_MEM_GEMINI_API_KEY:"",CLAUDE_MEM_GEMINI_MODEL:"gemini-2.5-flash-lite",CLAUDE_MEM_GEMINI_RATE_LIMITING_ENABLED:"true",CLAUDE_MEM_GEMINI_MAX_CONTEXT_MESSAGES:"20",CLAUDE_MEM_GEMINI_MAX_TOKENS:"100000",CLAUDE_MEM_OPENROUTER_API_KEY:"",CLAUDE_MEM_OPENROUTER_MODEL:"xiaomi/mimo-v2-flash:free",CLAUDE_MEM_OPENROUTER_BASE_URL:"",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,Kn.join)((0,lu.homedir)(),".keepmind"),CLAUDE_MEM_LOG_LEVEL:"INFO",CLAUDE_MEM_PYTHON_VERSION:"3.13",CLAUDE_CODE_PATH:"",CLAUDE_MEM_MODE:"code",CLAUDE_MEM_CONTEXT_SHOW_READ_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT:"true",CLAUDE_MEM_CONTEXT_FULL_COUNT:"0",CLAUDE_MEM_CONTEXT_FULL_FIELD:"narrative",CLAUDE_MEM_CONTEXT_SESSION_COUNT:"5",CLAUDE_MEM_OBSERVATION_BATCH_MAX:"1",CLAUDE_MEM_MAX_CONTEXT_MESSAGES:"40",CLAUDE_MEM_CONTEXT_SHOW_LAST_SUMMARY:"true",CLAUDE_MEM_CONTEXT_SHOW_LAST_MESSAGE:"false",CLAUDE_MEM_CONTEXT_SHOW_TERMINAL_OUTPUT:"true",CLAUDE_MEM_WELCOME_HINT_ENABLED:"true",CLAUDE_MEM_FOLDER_CLAUDEMD_ENABLED:"false",CLAUDE_MEM_FOLDER_USE_LOCAL_MD:"false",CLAUDE_MEM_TRANSCRIPTS_ENABLED:"true",CLAUDE_MEM_TRANSCRIPTS_CONFIG_PATH:(0,Kn.join)((0,lu.homedir)(),".keepmind","transcript-watch.json"),CLAUDE_MEM_CODEX_TRANSCRIPT_INGESTION:"false",CLAUDE_MEM_MAX_CONCURRENT_AGENTS:"2",CLAUDE_MEM_HOOK_FAIL_LOUD_THRESHOLD:"3",CLAUDE_MEM_EXCLUDED_PROJECTS:"",CLAUDE_MEM_FOLDER_MD_EXCLUDE:"[]",CLAUDE_MEM_FOLDER_MD_SKELETON_DENYLIST:"[]",CLAUDE_MEM_SEMANTIC_INJECT:"false",CLAUDE_MEM_SEMANTIC_INJECT_LIMIT:"5",CLAUDE_MEM_TIER_ROUTING_ENABLED:"true",CLAUDE_MEM_TIER_SIMPLE_MODEL:"haiku",CLAUDE_MEM_TIER_SUMMARY_MODEL:"",CLAUDE_MEM_TIER_FAST_MODEL:"haiku",CLAUDE_MEM_TIER_SMART_MODEL:"sonnet",CLAUDE_MEM_CHROMA_ENABLED:"true",CLAUDE_MEM_TELEGRAM_ENABLED:"true",CLAUDE_MEM_TELEGRAM_BOT_TOKEN:"",CLAUDE_MEM_TELEGRAM_CHAT_ID:"",CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES:"security_alert",CLAUDE_MEM_TELEGRAM_TRIGGER_CONCEPTS:"",CLAUDE_MEM_QUEUE_ENGINE:"sqlite",CLAUDE_MEM_REDIS_URL:"",CLAUDE_MEM_REDIS_HOST:"127.0.0.1",CLAUDE_MEM_REDIS_PORT:"6379",CLAUDE_MEM_REDIS_MODE:"external",CLAUDE_MEM_QUEUE_REDIS_PREFIX:`claude_mem_${process.env.CLAUDE_MEM_WORKER_PORT??String(37700+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_AUTH_MODE:"api-key",CLAUDE_MEM_RUNTIME:"worker",CLAUDE_MEM_SERVER_URL:`http://127.0.0.1:${process.env.CLAUDE_MEM_SERVER_PORT??String(37877+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_SERVER_API_KEY:"",CLAUDE_MEM_SERVER_PROJECT_ID:"",CLAUDE_MEM_SERVER_BETA_URL:`http://127.0.0.1:${process.env.CLAUDE_MEM_SERVER_PORT??String(37877+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_SERVER_BETA_API_KEY:"",CLAUDE_MEM_SERVER_BETA_PROJECT_ID:""};static getAllDefaults(){return{...this.DEFAULTS}}static envOverride(e){let r=e.replace(/^CLAUDE_MEM_/,"KEEPMIND_");return process.env[r]??process.env[e]}static get(e){return this.envOverride(e)??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)){let o=this.envOverride(n);o!==void 0&&(r[n]=o)}return r}static loadFromFile(e,r=!0){try{if(!(0,dt.existsSync)(e)){let a=this.getAllDefaults();try{let c=(0,Kn.dirname)(e);(0,dt.existsSync)(c)||(0,dt.mkdirSync)(c,{recursive:!0}),Os(e,a),console.warn("[SETTINGS] Created settings file with defaults:",e)}catch(c){console.warn("[SETTINGS] Failed to create settings file, using in-memory defaults:",e,c instanceof Error?c.message:String(c))}return r?this.applyEnvOverrides(a):a}let n=(0,dt.readFileSync)(e,"utf-8"),o=JSON.parse(n.replace(/^\uFEFF/,"")),s=o;if(o.env&&typeof o.env=="object"){s=o.env;try{Os(e,s),console.warn("[SETTINGS] Migrated settings file from nested to flat schema:",e)}catch(a){console.warn("[SETTINGS] Failed to auto-migrate settings file:",e,a instanceof Error?a.message:String(a))}}let i={...this.DEFAULTS};for(let a of Object.keys(this.DEFAULTS))s[a]!==void 0&&(i[a]=s[a]);return r?this.applyEnvOverrides(i):i}catch(n){console.warn("[SETTINGS] Failed to load settings, using defaults:",e,n instanceof Error?n.message:String(n));let o=this.getAllDefaults();try{if((0,dt.existsSync)(e)){let s=`${e}.corrupt-${Date.now()}`;(0,dt.renameSync)(e,s),console.warn("[SETTINGS] Backed up corrupt settings file to:",s)}Os(e,o),console.warn("[SETTINGS] Recovered settings file with defaults:",e)}catch(s){console.warn("[SETTINGS] Failed to recover corrupt settings file:",e,s instanceof Error?s.message:String(s))}return r?this.applyEnvOverrides(o):o}}};var As=null;function Ms(){return As!==null||(As=nr.loadFromFile(qu)),As}var or=require("fs");var hu=require("child_process");var pt=require("fs"),fu=Ft(require("path"),1);var rP=["CLAUDECODE_","CLAUDE_CODE_"],nP=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID","HTTP_PROXY","HTTPS_PROXY","ALL_PROXY","NO_PROXY","http_proxy","https_proxy","all_proxy","no_proxy","npm_config_proxy","npm_config_https_proxy"]),oP=new Set(["CLAUDE_CODE_OAUTH_TOKEN","CLAUDE_CODE_GIT_BASH_PATH","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX","ANTHROPIC_BEDROCK_BASE_URL","AWS_REGION","AWS_PROFILE","AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","ANTHROPIC_VERTEX_PROJECT_ID","CLOUD_ML_REGION","GOOGLE_APPLICATION_CREDENTIALS"]);function Jn(t=process.env){let e={};for(let[r,n]of Object.entries(t))if(n!==void 0){if(oP.has(r)){e[r]=n;continue}nP.has(r)||rP.some(o=>r.startsWith(o))||(e[r]=n)}return e}var sP=5e3,iP=1e3,aP=$e.supervisorRegistry();function wt(t){if(!Number.isInteger(t)||t<0||t===0)return!1;try{return process.kill(t,0),!0}catch(e){if(e instanceof Error){let r=e.code;return r==="EPERM"?!0:(y.debug("SYSTEM","PID check failed",{pid:t,code:r}),!1)}return y.warn("SYSTEM","PID check threw non-Error",{pid:t,error:String(e)}),!1}}async function Cs(t,e){let r=Date.now()+e;for(;Date.now()<r;){if(t.every(n=>!wt(n.pid)))return;await new Promise(n=>setTimeout(n,100))}}var cP=5e3,r_=new Map;function uP(t){let e=r_.get(t);if(e&&Date.now()-e.capturedAtMs<cP)return e.token;let r=null;try{let n=(0,hu.spawnSync)("powershell.exe",["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId=${t}").CreationDate.ToString('yyyyMMddHHmmss.ffffff')`],{encoding:"utf-8",timeout:5e3,windowsHide:!0,env:{...Jn(process.env),LC_ALL:"C",LANG:"C"}});if(n.status===0){let o=n.stdout.trim();r=o.length>0?o:null}}catch(n){y.debug("SYSTEM","captureProcessStartToken: powershell CIM lookup failed",{pid:t,error:n instanceof Error?n.message:String(n)}),r=null}return r_.set(t,{token:r,capturedAtMs:Date.now()}),r}function n_(t){if(!Number.isInteger(t)||t<=0)return null;if(process.platform==="linux")try{let e=(0,pt.readFileSync)(`/proc/${t}/stat`,"utf-8"),r=e.lastIndexOf(") ");if(r<0)return null;let o=e.slice(r+2).split(" ")[19];return o&&/^\d+$/.test(o)?o:null}catch(e){return y.debug("SYSTEM","captureProcessStartToken: /proc read failed",{pid:t,error:e instanceof Error?e.message:String(e)}),null}if(process.platform==="win32")return uP(t);try{let e=(0,hu.spawnSync)("ps",["-p",String(t),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...Jn(process.env),LC_ALL:"C",LANG:"C"}});if(e.status!==0)return null;let r=e.stdout.trim();return r.length>0?r:null}catch(e){return y.debug("SYSTEM","captureProcessStartToken: ps exec failed",{pid:t,error:e instanceof Error?e.message:String(e)}),null}}function gu(t){if(!t||!wt(t.pid))return!1;if(!t.startToken)return!0;let e=n_(t.pid);if(e===null)return!0;let r=e===t.startToken;return r||y.debug("SYSTEM","verifyPidFileOwnership: start-token mismatch (PID reused)",{pid:t.pid,stored:t.startToken,current:e}),r}var mu=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;constructor(e=aP){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,(0,pt.mkdirSync)(fu.default.dirname(this.registryPath),{recursive:!0}),!(0,pt.existsSync)(this.registryPath)){this.persist();return}try{let n=JSON.parse((0,pt.readFileSync)(this.registryPath,"utf-8")).processes??{};for(let[o,s]of Object.entries(n))this.entries.set(o,s)}catch(r){r instanceof Error?y.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath},r):y.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath,error:String(r)}),this.entries.clear()}let e=this.pruneDeadEntries();e>0&&y.info("SYSTEM","Removed dead processes from supervisor registry",{removed:e}),this.persist()}register(e,r,n){this.initialize(),this.entries.set(e,r),n&&this.runtimeProcesses.set(e,n),this.persist()}unregister(e){this.initialize();let r=this.entries.get(e);this.entries.delete(e),this.runtimeProcesses.delete(e),this.persist(),r?.type==="sdk"&&pu()}clear(){this.entries.clear(),this.runtimeProcesses.clear(),this.persist()}getAll(){return this.initialize(),Array.from(this.entries.entries()).map(([e,r])=>({id:e,...r})).sort((e,r)=>{let n=Date.parse(e.startedAt),o=Date.parse(r.startedAt);return(Number.isNaN(n)?0:n)-(Number.isNaN(o)?0:o)})}getBySession(e){let r=String(e);return this.getAll().filter(n=>n.sessionId!==void 0&&String(n.sessionId)===r)}getRuntimeProcess(e){return this.runtimeProcesses.get(e)}getByPid(e){return this.getAll().filter(r=>r.pid===e)}pruneDeadEntries(){this.initialize();let e=0,r=0;for(let[n,o]of this.entries)wt(o.pid)||(this.entries.delete(n),this.runtimeProcesses.delete(n),e+=1,o.type==="sdk"&&(r+=1));e>0&&this.persist();for(let n=0;n<r;n+=1)pu();return e}async reapSession(e){this.initialize();let r=this.getBySession(e);if(r.length===0)return 0;let n=typeof e=="number"?e:Number(e)||void 0;y.info("SYSTEM",`Reaping ${r.length} process(es) for session ${e}`,{sessionId:n,pids:r.map(i=>i.pid)});let o=r.filter(i=>wt(i.pid));for(let i of o)try{typeof i.pgid=="number"&&process.platform!=="win32"?process.kill(-i.pgid,"SIGTERM"):process.kill(i.pid,"SIGTERM")}catch(a){a instanceof Error?a.code!=="ESRCH"&&y.debug("SYSTEM",`Failed to SIGTERM session process PID ${i.pid}`,{pid:i.pid,pgid:i.pgid},a):y.warn("SYSTEM",`Failed to SIGTERM session process PID ${i.pid} (non-Error)`,{pid:i.pid,pgid:i.pgid,error:String(a)})}await Cs(o,sP);let s=o.filter(i=>wt(i.pid));for(let i of s){y.warn("SYSTEM",`Session process PID ${i.pid} did not exit after SIGTERM, sending SIGKILL`,{pid:i.pid,pgid:i.pgid,sessionId:n});try{typeof i.pgid=="number"&&process.platform!=="win32"?process.kill(-i.pgid,"SIGKILL"):process.kill(i.pid,"SIGKILL")}catch(a){a instanceof Error?a.code!=="ESRCH"&&y.debug("SYSTEM",`Failed to SIGKILL session process PID ${i.pid}`,{pid:i.pid,pgid:i.pgid},a):y.warn("SYSTEM",`Failed to SIGKILL session process PID ${i.pid} (non-Error)`,{pid:i.pid,pgid:i.pgid,error:String(a)})}}if(s.length>0){let i=Date.now()+iP;for(;Date.now()<i&&s.filter(c=>wt(c.pid)).length!==0;)await new Promise(c=>setTimeout(c,100))}for(let i of r)this.entries.delete(i.id),this.runtimeProcesses.delete(i.id);this.persist();for(let i of r)i.type==="sdk"&&pu();return y.info("SYSTEM",`Reaped ${r.length} process(es) for session ${e}`,{sessionId:n,reaped:r.length}),r.length}persist(){let e={processes:Object.fromEntries(this.entries.entries())};(0,pt.mkdirSync)(fu.default.dirname(this.registryPath),{recursive:!0}),(0,pt.writeFileSync)(this.registryPath,JSON.stringify(e,null,2))}},du=null;function Ns(){return du||(du=new mu),du}var lP=[];function pu(){let t=lP.shift();t&&t()}var s_=require("child_process"),Dr=require("fs"),i_=require("util");var dP=(0,i_.promisify)(s_.execFile),pP=$e.workerPid();async function a_(t){let e=t.currentPid??process.pid,r=t.pidFilePath??pP,n=t.registry.getAll(),o=[...n].filter(i=>i.pid!==e).sort((i,a)=>Date.parse(a.startedAt)-Date.parse(i.startedAt));for(let i of o){if(!wt(i.pid)){t.registry.unregister(i.id);continue}try{await o_(i,"SIGTERM")}catch(a){a instanceof Error?y.debug("SYSTEM","Failed to send SIGTERM to child process",{pid:i.pid,pgid:i.pgid,type:i.type},a):y.warn("SYSTEM","Failed to send SIGTERM to child process (non-Error)",{pid:i.pid,pgid:i.pgid,type:i.type,error:String(a)})}}await Cs(o,5e3);let s=o.filter(i=>wt(i.pid));for(let i of s)try{await o_(i,"SIGKILL")}catch(a){a instanceof Error?y.debug("SYSTEM","Failed to force kill child process",{pid:i.pid,pgid:i.pgid,type:i.type},a):y.warn("SYSTEM","Failed to force kill child process (non-Error)",{pid:i.pid,pgid:i.pgid,type:i.type,error:String(a)})}await Cs(s,1e3);for(let i of o)t.registry.unregister(i.id);for(let i of n.filter(a=>a.pid===e))t.registry.unregister(i.id);fP(r,e),t.registry.pruneDeadEntries()}function fP(t,e){if(!(0,Dr.existsSync)(t))return;let r=null;try{let n=JSON.parse((0,Dr.readFileSync)(t,"utf-8"));r=typeof n.pid=="number"?n.pid:null}catch(n){y.debug("SYSTEM","PID file unreadable during shutdown \u2014 leaving it (cannot prove ownership)",{pidFilePath:t,error:n instanceof Error?n.message:String(n)});return}if(r!==e){y.debug("SYSTEM","PID file not owned by this process \u2014 leaving it for its owner (restart successor?)",{pidFilePath:t,recordedPid:r,currentPid:e});return}try{(0,Dr.rmSync)(t,{force:!0})}catch(n){n instanceof Error?y.debug("SYSTEM","Failed to remove PID file during shutdown",{pidFilePath:t},n):y.warn("SYSTEM","Failed to remove PID file during shutdown (non-Error)",{pidFilePath:t,error:String(n)})}}async function o_(t,e){let{pid:r,pgid:n}=t;if(process.platform!=="win32"){if(typeof n=="number")try{process.kill(-n,e);return}catch(i){if((i instanceof Error?i.code:void 0)!=="ESRCH")throw i}try{process.kill(r,e)}catch(i){if((i instanceof Error?i.code:void 0)!=="ESRCH")throw i}return}if(e==="SIGTERM"){try{process.kill(r,e)}catch(i){if(i instanceof Error&&i.code==="ESRCH")return;throw i}return}let o=await mP();if(o){await new Promise((i,a)=>{o(r,e,c=>{if(!c){i();return}if(c.code==="ESRCH"){i();return}a(c)})});return}let s=["/PID",String(r),"/T"];e==="SIGKILL"&&s.push("/F"),await dP("taskkill",s,{timeout:ue.POWERSHELL_COMMAND,windowsHide:!0})}async function mP(){let t="tree-kill";try{let e=await import(t);return e.default??e}catch(e){return y.debug("SYSTEM","tree-kill module not available, using fallback",{},e instanceof Error?e:void 0),null}}var c_=3e4,jr=null;function hP(){let e=Ns().pruneDeadEntries();e>0&&y.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function u_(){jr===null&&(jr=setInterval(hP,c_),jr.unref(),y.debug("SYSTEM","Health checker started",{intervalMs:c_}))}function l_(){jr!==null&&(clearInterval(jr),jr=null,y.debug("SYSTEM","Health checker stopped"))}var gP=$e.workerPid(),_u=class{registry;started=!1;stopPromise=null;signalHandlersRegistered=!1;shutdownInitiated=!1;shutdownHandler=null;constructor(e){this.registry=e}async start(){if(this.started)return;if(this.registry.initialize(),Ds({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,u_()}configureSignalHandlers(e){if(this.shutdownHandler=e,this.signalHandlersRegistered)return;this.signalHandlersRegistered=!0;let r=async n=>{if(this.shutdownInitiated){y.warn("SYSTEM",`Received ${n} but shutdown already in progress`);return}this.shutdownInitiated=!0,y.info("SYSTEM",`Received ${n}, shutting down...`);try{this.shutdownHandler?await this.shutdownHandler():await this.stop()}catch(o){o instanceof Error?y.error("SYSTEM","Error during shutdown",{},o):y.error("SYSTEM","Error during shutdown (non-Error)",{error:String(o)});try{await this.stop()}catch(s){s instanceof Error?y.debug("SYSTEM","Supervisor shutdown fallback failed",{},s):y.debug("SYSTEM","Supervisor shutdown fallback failed",{error:String(s)})}}process.exit(0)};process.on("SIGTERM",()=>{r("SIGTERM")}),process.on("SIGINT",()=>{r("SIGINT")}),process.platform!=="win32"&&(process.argv.includes("--daemon")?process.on("SIGHUP",()=>{y.debug("SYSTEM","Ignoring SIGHUP in daemon mode")}):process.on("SIGHUP",()=>{r("SIGHUP")}))}async stop(){if(this.stopPromise){await this.stopPromise;return}l_(),this.stopPromise=a_({registry:this.registry,currentPid:process.pid}).finally(()=>{this.started=!1,this.stopPromise=null}),await this.stopPromise}assertCanSpawn(e){if(this.stopPromise!==null)throw new Error(`Supervisor is shutting down, refusing to spawn ${e}`)}registerProcess(e,r,n){this.registry.register(e,r,n)}unregisterProcess(e){this.registry.unregister(e)}getRegistry(){return this.registry}},_P=new _u(Ns());function yu(){return _P}function Ds(t={}){let e=t.pidFilePath??gP;if(!(0,or.existsSync)(e))return"missing";let r=null;try{r=JSON.parse((0,or.readFileSync)(e,"utf-8"))}catch(o){return o instanceof Error?y.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e},o):y.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e,error:String(o)}),(0,or.rmSync)(e,{force:!0}),"invalid"}return gu(r)&&r?((t.logAlive??!0)&&y.info("SYSTEM","Worker already running (PID alive)",{existingPid:r.pid,existingPort:r.port,startedAt:r.startedAt}),"alive"):(y.info("SYSTEM","Removing stale PID file (worker process is dead or PID has been reused)",{pid:r?.pid,port:r?.port,startedAt:r?.startedAt}),(0,or.rmSync)(e,{force:!0}),"stale")}var f_=Ft(require("path"),1),m_=require("os"),ke=require("fs"),h_=require("child_process");function d_(t){return t instanceof Error?t:new Error(String(t))}var rD=$e.dataDir(),ft=$e.workerPid(),nD=$e.workerPort();function p_(t){return t?/(^|[\\/])node(\.exe)?$/i.test(t.trim()):!1}function yP(t,e){let r=e==="win32"?`where ${t}`:`which ${t}`,n;try{n=(0,h_.execSync)(r,{stdio:["ignore","pipe","ignore"],encoding:"utf-8",windowsHide:!0})}catch(s){return s instanceof Error?y.debug("SYSTEM",`Binary lookup failed for ${t}`,{command:r},s):y.debug("SYSTEM",`Binary lookup failed for ${t}`,{command:r},new Error(String(s))),null}return n.split(/\r?\n/).map(s=>s.trim()).find(s=>s.length>0)||null}var Su;function g_(t={}){let e=Object.keys(t).length===0;if(e&&Su!==void 0)return Su;let r=SP(t);return e&&r!==null&&(Su=r),r}function SP(t){let e=t.platform??process.platform,r=t.execPath??process.execPath;if(p_(r))return r;let n=t.env??process.env,o=t.homeDirectory??(0,m_.homedir)(),s=t.pathExists??ke.existsSync,i=t.lookupInPath??yP,a=e==="win32"?[n.NODE,f_.default.join(o,".nvm","current","bin","node.exe"),"node"]:[n.NODE,"/usr/local/bin/node","/opt/homebrew/bin/node","/usr/bin/node","node"];for(let c of a){let u=c?.trim();if(u&&(p_(u)&&s(u)||u.toLowerCase()==="node"))return u}return i("node",e)}function __(){if(!(0,ke.existsSync)(ft))return null;try{return JSON.parse((0,ke.readFileSync)(ft,"utf-8"))}catch(t){return t instanceof Error?y.warn("SYSTEM","Failed to parse PID file",{path:ft},t):y.warn("SYSTEM","Failed to parse PID file",{path:ft},new Error(String(t))),null}}function y_(){if((0,ke.existsSync)(ft))try{(0,ke.unlinkSync)(ft)}catch(t){t instanceof Error?y.warn("SYSTEM","Failed to remove PID file",{path:ft},t):y.warn("SYSTEM","Failed to remove PID file",{path:ft},new Error(String(t)))}}function Ut(t){return process.platform==="win32"?Math.round(t*2):t}function S_(t,e,r={}){yu().assertCanSpawn("worker daemon");let n=Jn({...process.env,CLAUDE_MEM_WORKER_PORT:String(e),...r}),o=g_();if(!o){y.error("SYSTEM","Node runtime not found \u2014 ensure node is on PATH or set the NODE env var. The worker daemon runs under Node (node:sqlite).");return}if(process.platform==="win32")try{let l=Gn(o,[t,"--daemon"],{detached:!0,stdio:"ignore",windowsHide:!0,env:n});if(l.pid===void 0){y.error("SYSTEM","Worker daemon spawn produced no PID on Windows",{runtimePath:o});return}return l.unref(),l.pid}catch(l){y.error("SYSTEM","Failed to spawn worker daemon on Windows",{runtimePath:o},d_(l));return}let s="/usr/bin/setsid",i=(0,ke.existsSync)(s),u=Gn(i?s:o,i?[o,t,"--daemon"]:[t,"--daemon"],{detached:!0,stdio:"ignore",env:n});if(u.pid!==void 0)return u.unref(),u.pid}function v_(t){if(t===0)return!0;if(!Number.isInteger(t)||t<0)return!1;try{return process.kill(t,0),!0}catch(e){if(e instanceof Error){let r=e.code;if(r==="EPERM")return!0;y.debug("SYSTEM","Process not alive",{pid:t,code:r})}else y.debug("SYSTEM","Process not alive (non-Error thrown)",{pid:t},new Error(String(e)));return!1}}function b_(){try{if(!(0,ke.existsSync)(ft))return;let t=new Date;(0,ke.utimesSync)(ft,t,t)}catch{}}function E_(){return Ds({logAlive:!1})}var w_=Ft(require("net"),1);var vP=2500;async function bP(t,e,r="GET"){let n=await fetch(`http://127.0.0.1:${t}${e}`,{method:r,signal:AbortSignal.timeout(vP)}),o="";try{o=await n.text()}catch{}return{ok:n.ok,statusCode:n.status,body:o}}async function k_(t){return new Promise(e=>{let r=w_.default.createServer();r.once("error",n=>{n.code==="EADDRINUSE"||n.code==="EACCES"?e(!0):e(!1)}),r.once("listening",()=>{r.close(()=>e(!1))}),r.listen(t,"127.0.0.1")})}async function x_(t,e,r,n){let o=Date.now();for(;Date.now()-o<r;){try{if((await bP(t,e)).ok)return!0}catch(s){s instanceof Error?y.debug("SYSTEM",n,{},s):y.debug("SYSTEM",n,{error:String(s)})}await new Promise(s=>setTimeout(s,500))}return!1}function Bn(t,e=3e4){return x_(t,"/api/health",e,"Service not ready yet, will retry")}function Yn(t,e=3e4){return x_(t,"/api/readiness",e,"Worker not ready yet, will retry")}var js=require("path"),Ke=require("fs");var EP=6e4;function $_(){return(0,js.join)(Qs(),"spawn.lock")}function vu(){let t=$_(),e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()});for(let r=0;r<2;r++)try{return(0,Ke.mkdirSync)((0,js.dirname)(t),{recursive:!0}),(0,Ke.writeFileSync)(t,e,{flag:"wx"}),!0}catch(n){if(n?.code!=="EEXIST")return!0;if(r>0)return!1;let s;try{s=(0,Ke.statSync)(t).mtimeMs}catch{continue}if(Date.now()-s<=EP)return!1;let i;try{i=(0,Ke.statSync)(t).mtimeMs}catch{continue}if(i!==s)return!1;try{(0,Ke.unlinkSync)(t)}catch{return!1}}return!1}function bu(){let t=$_();try{if(JSON.parse((0,Ke.readFileSync)(t,"utf-8")).pid!==process.pid)return;(0,Ke.unlinkSync)(t)}catch{}}function Eu(t,e,r){let n=process.env[t];if(n){let o=parseInt(n,10);if(Number.isFinite(o)&&o>=r.min&&o<=r.max)return o;y.warn("SYSTEM",`Invalid ${t}, using default`,{value:n,min:r.min,max:r.max})}return e}var RD=Eu("CLAUDE_MEM_HEALTH_TIMEOUT_MS",Et(ue.HEALTH_CHECK),{min:500,max:3e5}),ID=Eu("CLAUDE_MEM_API_TIMEOUT_MS",Et(ue.API_REQUEST),{min:500,max:3e5}),OD=Eu("CLAUDE_MEM_HOOK_READINESS_TIMEOUT_MS",Et(ue.HOOK_READINESS_WAIT),{min:0,max:3e5}),wP={min:500,max:3e5};async function wu(t,e={},r){try{return await fetch(t,{...e,signal:AbortSignal.timeout(r)})}catch(n){throw n instanceof DOMException&&n.name==="TimeoutError"?new Error(`Request timed out after ${r}ms`):n}}var Ls=null,Us=null,qs=null,Zs=null;function kP(){return Fs.default.join(nr.get("CLAUDE_MEM_DATA_DIR"),"settings.json")}function xP(t){if(!Number.isInteger(t)||t<=0)return!1;try{return process.kill(t,0),!0}catch(e){return e?.code==="EPERM"}}function $P(){try{let t=$e.workerPid();if(!(0,qt.existsSync)(t))return null;let e=JSON.parse((0,qt.readFileSync)(t,"utf-8"));return typeof e.pid!="number"||typeof e.port!="number"||!xP(e.pid)?null:e.port}catch{return null}}function ku(){return qs!==null||(qs=nr.loadFromFile(kP())),qs}function P_(t,e){if(!t)return null;let r=parseInt(t,10);return Number.isFinite(r)&&r>=e.min&&r<=e.max?r:null}function PP(t,e,r){let n=process.env[t];if(n!==void 0){let i=P_(n,r);return i!==null?i:(y.warn("SYSTEM",`Invalid ${t}, using default`,{value:n,min:r.min,max:r.max}),e)}let o=ku()[t],s=P_(o,r);return s!==null?s:(y.warn("SYSTEM",`Invalid ${t} in settings.json, using default`,{value:o,min:r.min,max:r.max}),e)}function TP(){if(Ls!==null)return Ls;let t=ku();return Ls=parseInt(t.CLAUDE_MEM_WORKER_PORT,10),Ls}function xu(){let t=$P();return t!==null?t:TP()}function zP(){return Us!==null||(Us=ku().CLAUDE_MEM_WORKER_HOST),Us}function RP(){return Zs!==null||(Zs=PP("CLAUDE_MEM_API_TIMEOUT_MS",Et(ue.API_REQUEST),wP)),Zs}function IP(t){return`http://${zP()}:${xu()}${t}`}function Xn(t,e={}){let r=e.method??"GET",n=e.timeoutMs??RP(),o=IP(t),s={method:r};return e.headers&&(s.headers=e.headers),e.body&&(s.body=e.body),n>0?wu(o,s,n):fetch(o,s)}function T_(){let t=[Fs.default.join(ei,"plugin","scripts","worker-service.cjs"),Fs.default.join(process.cwd(),"plugin","scripts","worker-service.cjs")];for(let e of t)if((0,qt.existsSync)(e))return e;return null}var z_=require("fs");function OP(t){let e=__();return e&&typeof e.port=="number"&&v_(e.pid)?e.port:t}async function AP(t,e){let r=Date.now()+e;for(;Date.now()<r;){let n=OP(t);if(await Bn(n,800))return n;await new Promise(o=>setTimeout(o,300))}return null}async function R_(t,e){if(!e)return y.error("SYSTEM","ensureWorkerStarted called with empty workerScriptPath \u2014 caller bug"),"dead";if(!(0,z_.existsSync)(e))return y.error("SYSTEM","ensureWorkerStarted: worker script not found at expected path \u2014 likely a partial install or build artifact missing",{workerScriptPath:e}),"dead";if(await Bn(t,1e3)){let a=await Yn(t,Ut(ue.READINESS_WAIT));return a||y.warn("SYSTEM","Worker is alive but readiness timed out \u2014 proceeding anyway"),y.info("SYSTEM","Worker already running and healthy (fast path)"),a?"ready":"warming"}if(E_()==="alive"){if(y.info("SYSTEM","Worker PID file points to a live process, waiting for it to become healthy"),await Bn(t,Ut(ue.POST_SPAWN_WAIT))){let c=await Yn(t,Ut(ue.READINESS_WAIT));return y.info("SYSTEM","Worker became healthy while waiting on live PID"),c?"ready":"warming"}y.warn("SYSTEM","PID file marked live but worker never became healthy within the cold-boot window \u2014 treating it as a stale/reused PID and re-spawning"),y_()}if(await k_(t)){if(y.info("SYSTEM","Port in use, waiting for worker to become healthy"),await Bn(t,Ut(ue.PORT_IN_USE_WAIT))){let c=await Yn(t,Ut(ue.READINESS_WAIT));return y.info("SYSTEM","Worker is now healthy"),c?"ready":"warming"}y.warn("SYSTEM","Configured port in use but no healthy worker \u2014 spawning anyway (worker will pick a free ephemeral port)")}let o=vu(),s=t;try{if(o){if(y.info("SYSTEM","Starting worker daemon",{workerScriptPath:e}),S_(e,t)===void 0)return y.error("SYSTEM","Failed to spawn worker daemon"),"dead"}else y.info("SYSTEM","Another launcher holds the spawn lock \u2014 skipping duplicate spawn and waiting for its worker");let a=await AP(t,Ut(ue.POST_SPAWN_WAIT));if(a===null)return y.warn("SYSTEM",o?"Worker spawned but health endpoint not responding within window \u2014 likely still starting in background":"Spawn-lock holder's worker not healthy within window \u2014 likely still starting in background"),"warming";s=a}finally{o&&bu()}let i=await Yn(s,Ut(ue.READINESS_WAIT));return i||y.warn("SYSTEM","Worker is alive but readiness timed out \u2014 proceeding anyway"),b_(),y.info("SYSTEM",o?"Worker started successfully":"Worker is up (started by another launcher)"),i?"ready":"warming"}var qr=require("node:fs/promises"),ro=require("node:path");var A_=require("node:child_process"),Se=require("node:fs"),le=require("node:path"),Iu=require("node:os"),Tu=require("node:module");var GP={},zu=typeof __filename<"u"?(0,Tu.createRequire)(__filename):(0,Tu.createRequire)(GP.url),Ru={".js":"javascript",".mjs":"javascript",".cjs":"javascript",".jsx":"tsx",".ts":"typescript",".tsx":"tsx",".py":"python",".pyw":"python",".go":"go",".rs":"rust",".rb":"ruby",".java":"java",".c":"c",".h":"c",".cpp":"cpp",".cc":"cpp",".cxx":"cpp",".hpp":"cpp",".hh":"cpp",".kt":"kotlin",".kts":"kotlin",".swift":"swift",".php":"php",".ex":"elixir",".exs":"elixir",".lua":"lua",".scala":"scala",".sc":"scala",".sh":"bash",".bash":"bash",".zsh":"bash",".hs":"haskell",".zig":"zig",".css":"css",".scss":"scss",".toml":"toml",".yml":"yaml",".yaml":"yaml",".sql":"sql",".md":"markdown",".mdx":"markdown"};function M_(t,e){let r=t.slice(t.lastIndexOf("."));return Ru[r]?Ru[r]:e.extensionToLanguage[r]?e.extensionToLanguage[r]:"unknown"}function C_(t,e){return e.languageToQueryKey[t]?e.languageToQueryKey[t]:NP(t)}var Qn=new Map,Lr={grammars:{},extensionToLanguage:{},languageToQueryKey:{}},N_=[".keepmind.json",".claude-mem.json"];function to(t){if(Qn.has(t))return Qn.get(t);let e;for(let s of N_)try{e=(0,Se.readFileSync)((0,le.join)(t,s),"utf-8");break}catch{}let r;try{if(e===void 0)throw new Error("no project config");r=JSON.parse(e)}catch{return Qn.set(t,Lr),Lr}let n=r.grammars;if(!n||typeof n!="object"||Array.isArray(n))return Qn.set(t,Lr),Lr;let o={grammars:{},extensionToLanguage:{},languageToQueryKey:{}};for(let[s,i]of Object.entries(n)){if(D_[s]||!i||typeof i!="object"||Array.isArray(i))continue;let a=i,c=a.package,u=a.extensions,l=a.query;if(!(typeof c!="string"||!Array.isArray(u))&&u.every(d=>typeof d=="string")){o.grammars[s]={package:c,extensions:u,query:typeof l=="string"?l:void 0};for(let d of u)Ru[d]||(o.extensionToLanguage[d]=s);if(typeof l=="string"){let d=(0,le.join)(t,l);try{let p=(0,Se.readFileSync)(d,"utf-8"),f=`user_${s}`;L_[f]=p,o.languageToQueryKey[s]=f}catch{y.warn("PARSER","Custom query file not found, falling back to generic",{fullQueryPath:d}),o.languageToQueryKey[s]="generic"}}else o.languageToQueryKey[s]="generic"}}return Qn.set(t,o),o}var D_={javascript:"tree-sitter-javascript",typescript:"tree-sitter-typescript/typescript",tsx:"tree-sitter-typescript/tsx",python:"tree-sitter-python",go:"tree-sitter-go",rust:"tree-sitter-rust",ruby:"tree-sitter-ruby",java:"tree-sitter-java",c:"tree-sitter-c",cpp:"tree-sitter-cpp",kotlin:"tree-sitter-kotlin",swift:"tree-sitter-swift",php:"tree-sitter-php/php",elixir:"tree-sitter-elixir",lua:"@tree-sitter-grammars/tree-sitter-lua",scala:"tree-sitter-scala",bash:"tree-sitter-bash",haskell:"tree-sitter-haskell",zig:"@tree-sitter-grammars/tree-sitter-zig",css:"tree-sitter-css",scss:"tree-sitter-scss",toml:"@tree-sitter-grammars/tree-sitter-toml",yaml:"@tree-sitter-grammars/tree-sitter-yaml",sql:"@derekstride/tree-sitter-sql",markdown:"@tree-sitter-grammars/tree-sitter-markdown"},MP={markdown:"tree-sitter-markdown"};function CP(t){let e=D_[t];if(!e)return null;let r=MP[t];if(r){try{let n=zu.resolve(e+"/package.json"),o=(0,le.join)((0,le.dirname)(n),r);if((0,Se.existsSync)((0,le.join)(o,"src")))return o}catch{}return null}try{let n=zu.resolve(e+"/package.json");return(0,le.dirname)(n)}catch{return null}}function j_(t,e){let r=CP(t);if(r)return r;if(!e)return null;let o=to(e).grammars[t];if(!o)return null;try{let s=(0,le.join)(e,"node_modules",o.package,"package.json");if((0,Se.existsSync)(s)){let i=(0,le.dirname)(s);if((0,Se.existsSync)((0,le.join)(i,"src")))return i}}catch{}return y.warn("PARSER","Grammar package not found",{language:t,package:o.package}),null}var L_={jsts:`
83
+ `,"utf-8"),a;try{a=(0,V.statSync)(r).mode&511}catch{}let c;try{c=a!==void 0?(0,V.openSync)(s,"w",a):(0,V.openSync)(s,"w");let u=0;for(;u<i.length;){let l=(0,V.writeSync)(c,i,u,i.length-u);if(l===0)throw new Error(`writeSync stalled at ${u}/${i.length} bytes`);u+=l}if((0,V.fsyncSync)(c),(0,V.closeSync)(c),c=void 0,(0,V.renameSync)(s,r),!eP){let l;try{l=(0,V.openSync)(n,"r"),(0,V.fsyncSync)(l)}catch{}finally{if(l!==void 0)try{(0,V.closeSync)(l)}catch{}}}}catch(u){if(c!==void 0)try{(0,V.closeSync)(c)}catch{}try{(0,V.unlinkSync)(s)}catch{}throw u}}var nr=class{static DEFAULTS={CLAUDE_MEM_MODEL:"claude-haiku-4-5-20251001",CLAUDE_MEM_CONTEXT_OBSERVATIONS:"50",CLAUDE_MEM_WORKER_PORT:String(37700+(process.getuid?.()??77)%100),CLAUDE_MEM_WORKER_HOST:"127.0.0.1",CLAUDE_MEM_API_TIMEOUT_MS:String(Et(ue.API_REQUEST)),CLAUDE_MEM_SKIP_TOOLS:"ListMcpResourcesTool,SlashCommand,Skill,TodoWrite,AskUserQuestion",CLAUDE_MEM_PROVIDER:"claude",CLAUDE_MEM_CLAUDE_AUTH_METHOD:"subscription",CLAUDE_MEM_GEMINI_API_KEY:"",CLAUDE_MEM_GEMINI_MODEL:"gemini-2.5-flash-lite",CLAUDE_MEM_GEMINI_RATE_LIMITING_ENABLED:"true",CLAUDE_MEM_GEMINI_MAX_CONTEXT_MESSAGES:"20",CLAUDE_MEM_GEMINI_MAX_TOKENS:"100000",CLAUDE_MEM_OPENROUTER_API_KEY:"",CLAUDE_MEM_OPENROUTER_MODEL:"xiaomi/mimo-v2-flash:free",CLAUDE_MEM_OPENROUTER_BASE_URL:"",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,Kn.join)((0,lu.homedir)(),".keepmind"),CLAUDE_MEM_LOG_LEVEL:"INFO",CLAUDE_MEM_PYTHON_VERSION:"3.13",CLAUDE_CODE_PATH:"",CLAUDE_MEM_MODE:"code",CLAUDE_MEM_CONTEXT_SHOW_READ_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT:"true",CLAUDE_MEM_CONTEXT_FULL_COUNT:"0",CLAUDE_MEM_CONTEXT_FULL_FIELD:"narrative",CLAUDE_MEM_CONTEXT_SESSION_COUNT:"5",CLAUDE_MEM_OBSERVATION_BATCH_MAX:"3",CLAUDE_MEM_MAX_CONTEXT_MESSAGES:"40",CLAUDE_MEM_CONTEXT_SHOW_LAST_SUMMARY:"true",CLAUDE_MEM_CONTEXT_SHOW_LAST_MESSAGE:"false",CLAUDE_MEM_CONTEXT_SHOW_TERMINAL_OUTPUT:"true",CLAUDE_MEM_WELCOME_HINT_ENABLED:"true",CLAUDE_MEM_FOLDER_CLAUDEMD_ENABLED:"false",CLAUDE_MEM_FOLDER_USE_LOCAL_MD:"false",CLAUDE_MEM_TRANSCRIPTS_ENABLED:"true",CLAUDE_MEM_TRANSCRIPTS_CONFIG_PATH:(0,Kn.join)((0,lu.homedir)(),".keepmind","transcript-watch.json"),CLAUDE_MEM_CODEX_TRANSCRIPT_INGESTION:"false",CLAUDE_MEM_MAX_CONCURRENT_AGENTS:"2",CLAUDE_MEM_HOOK_FAIL_LOUD_THRESHOLD:"3",CLAUDE_MEM_EXCLUDED_PROJECTS:"",CLAUDE_MEM_FOLDER_MD_EXCLUDE:"[]",CLAUDE_MEM_FOLDER_MD_SKELETON_DENYLIST:"[]",CLAUDE_MEM_SEMANTIC_INJECT:"false",CLAUDE_MEM_SEMANTIC_INJECT_LIMIT:"5",CLAUDE_MEM_TIER_ROUTING_ENABLED:"true",CLAUDE_MEM_TIER_SIMPLE_MODEL:"haiku",CLAUDE_MEM_TIER_SUMMARY_MODEL:"",CLAUDE_MEM_TIER_FAST_MODEL:"haiku",CLAUDE_MEM_TIER_SMART_MODEL:"sonnet",CLAUDE_MEM_CHROMA_ENABLED:"true",CLAUDE_MEM_TELEGRAM_ENABLED:"true",CLAUDE_MEM_TELEGRAM_BOT_TOKEN:"",CLAUDE_MEM_TELEGRAM_CHAT_ID:"",CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES:"security_alert",CLAUDE_MEM_TELEGRAM_TRIGGER_CONCEPTS:"",CLAUDE_MEM_QUEUE_ENGINE:"sqlite",CLAUDE_MEM_REDIS_URL:"",CLAUDE_MEM_REDIS_HOST:"127.0.0.1",CLAUDE_MEM_REDIS_PORT:"6379",CLAUDE_MEM_REDIS_MODE:"external",CLAUDE_MEM_QUEUE_REDIS_PREFIX:`claude_mem_${process.env.CLAUDE_MEM_WORKER_PORT??String(37700+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_AUTH_MODE:"api-key",CLAUDE_MEM_RUNTIME:"worker",CLAUDE_MEM_SERVER_URL:`http://127.0.0.1:${process.env.CLAUDE_MEM_SERVER_PORT??String(37877+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_SERVER_API_KEY:"",CLAUDE_MEM_SERVER_PROJECT_ID:"",CLAUDE_MEM_SERVER_BETA_URL:`http://127.0.0.1:${process.env.CLAUDE_MEM_SERVER_PORT??String(37877+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_SERVER_BETA_API_KEY:"",CLAUDE_MEM_SERVER_BETA_PROJECT_ID:""};static getAllDefaults(){return{...this.DEFAULTS}}static envOverride(e){let r=e.replace(/^CLAUDE_MEM_/,"KEEPMIND_");return process.env[r]??process.env[e]}static get(e){return this.envOverride(e)??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)){let o=this.envOverride(n);o!==void 0&&(r[n]=o)}return r}static loadFromFile(e,r=!0){try{if(!(0,dt.existsSync)(e)){let a=this.getAllDefaults();try{let c=(0,Kn.dirname)(e);(0,dt.existsSync)(c)||(0,dt.mkdirSync)(c,{recursive:!0}),Os(e,a),console.warn("[SETTINGS] Created settings file with defaults:",e)}catch(c){console.warn("[SETTINGS] Failed to create settings file, using in-memory defaults:",e,c instanceof Error?c.message:String(c))}return r?this.applyEnvOverrides(a):a}let n=(0,dt.readFileSync)(e,"utf-8"),o=JSON.parse(n.replace(/^\uFEFF/,"")),s=o;if(o.env&&typeof o.env=="object"){s=o.env;try{Os(e,s),console.warn("[SETTINGS] Migrated settings file from nested to flat schema:",e)}catch(a){console.warn("[SETTINGS] Failed to auto-migrate settings file:",e,a instanceof Error?a.message:String(a))}}let i={...this.DEFAULTS};for(let a of Object.keys(this.DEFAULTS))s[a]!==void 0&&(i[a]=s[a]);return r?this.applyEnvOverrides(i):i}catch(n){console.warn("[SETTINGS] Failed to load settings, using defaults:",e,n instanceof Error?n.message:String(n));let o=this.getAllDefaults();try{if((0,dt.existsSync)(e)){let s=`${e}.corrupt-${Date.now()}`;(0,dt.renameSync)(e,s),console.warn("[SETTINGS] Backed up corrupt settings file to:",s)}Os(e,o),console.warn("[SETTINGS] Recovered settings file with defaults:",e)}catch(s){console.warn("[SETTINGS] Failed to recover corrupt settings file:",e,s instanceof Error?s.message:String(s))}return r?this.applyEnvOverrides(o):o}}};var As=null;function Ms(){return As!==null||(As=nr.loadFromFile(qu)),As}var or=require("fs");var hu=require("child_process");var pt=require("fs"),fu=Ft(require("path"),1);var rP=["CLAUDECODE_","CLAUDE_CODE_"],nP=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID","HTTP_PROXY","HTTPS_PROXY","ALL_PROXY","NO_PROXY","http_proxy","https_proxy","all_proxy","no_proxy","npm_config_proxy","npm_config_https_proxy"]),oP=new Set(["CLAUDE_CODE_OAUTH_TOKEN","CLAUDE_CODE_GIT_BASH_PATH","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX","ANTHROPIC_BEDROCK_BASE_URL","AWS_REGION","AWS_PROFILE","AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","ANTHROPIC_VERTEX_PROJECT_ID","CLOUD_ML_REGION","GOOGLE_APPLICATION_CREDENTIALS"]);function Jn(t=process.env){let e={};for(let[r,n]of Object.entries(t))if(n!==void 0){if(oP.has(r)){e[r]=n;continue}nP.has(r)||rP.some(o=>r.startsWith(o))||(e[r]=n)}return e}var sP=5e3,iP=1e3,aP=$e.supervisorRegistry();function wt(t){if(!Number.isInteger(t)||t<0||t===0)return!1;try{return process.kill(t,0),!0}catch(e){if(e instanceof Error){let r=e.code;return r==="EPERM"?!0:(y.debug("SYSTEM","PID check failed",{pid:t,code:r}),!1)}return y.warn("SYSTEM","PID check threw non-Error",{pid:t,error:String(e)}),!1}}async function Cs(t,e){let r=Date.now()+e;for(;Date.now()<r;){if(t.every(n=>!wt(n.pid)))return;await new Promise(n=>setTimeout(n,100))}}var cP=5e3,r_=new Map;function uP(t){let e=r_.get(t);if(e&&Date.now()-e.capturedAtMs<cP)return e.token;let r=null;try{let n=(0,hu.spawnSync)("powershell.exe",["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId=${t}").CreationDate.ToString('yyyyMMddHHmmss.ffffff')`],{encoding:"utf-8",timeout:5e3,windowsHide:!0,env:{...Jn(process.env),LC_ALL:"C",LANG:"C"}});if(n.status===0){let o=n.stdout.trim();r=o.length>0?o:null}}catch(n){y.debug("SYSTEM","captureProcessStartToken: powershell CIM lookup failed",{pid:t,error:n instanceof Error?n.message:String(n)}),r=null}return r_.set(t,{token:r,capturedAtMs:Date.now()}),r}function n_(t){if(!Number.isInteger(t)||t<=0)return null;if(process.platform==="linux")try{let e=(0,pt.readFileSync)(`/proc/${t}/stat`,"utf-8"),r=e.lastIndexOf(") ");if(r<0)return null;let o=e.slice(r+2).split(" ")[19];return o&&/^\d+$/.test(o)?o:null}catch(e){return y.debug("SYSTEM","captureProcessStartToken: /proc read failed",{pid:t,error:e instanceof Error?e.message:String(e)}),null}if(process.platform==="win32")return uP(t);try{let e=(0,hu.spawnSync)("ps",["-p",String(t),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...Jn(process.env),LC_ALL:"C",LANG:"C"}});if(e.status!==0)return null;let r=e.stdout.trim();return r.length>0?r:null}catch(e){return y.debug("SYSTEM","captureProcessStartToken: ps exec failed",{pid:t,error:e instanceof Error?e.message:String(e)}),null}}function gu(t){if(!t||!wt(t.pid))return!1;if(!t.startToken)return!0;let e=n_(t.pid);if(e===null)return!0;let r=e===t.startToken;return r||y.debug("SYSTEM","verifyPidFileOwnership: start-token mismatch (PID reused)",{pid:t.pid,stored:t.startToken,current:e}),r}var mu=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;constructor(e=aP){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,(0,pt.mkdirSync)(fu.default.dirname(this.registryPath),{recursive:!0}),!(0,pt.existsSync)(this.registryPath)){this.persist();return}try{let n=JSON.parse((0,pt.readFileSync)(this.registryPath,"utf-8")).processes??{};for(let[o,s]of Object.entries(n))this.entries.set(o,s)}catch(r){r instanceof Error?y.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath},r):y.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath,error:String(r)}),this.entries.clear()}let e=this.pruneDeadEntries();e>0&&y.info("SYSTEM","Removed dead processes from supervisor registry",{removed:e}),this.persist()}register(e,r,n){this.initialize(),this.entries.set(e,r),n&&this.runtimeProcesses.set(e,n),this.persist()}unregister(e){this.initialize();let r=this.entries.get(e);this.entries.delete(e),this.runtimeProcesses.delete(e),this.persist(),r?.type==="sdk"&&pu()}clear(){this.entries.clear(),this.runtimeProcesses.clear(),this.persist()}getAll(){return this.initialize(),Array.from(this.entries.entries()).map(([e,r])=>({id:e,...r})).sort((e,r)=>{let n=Date.parse(e.startedAt),o=Date.parse(r.startedAt);return(Number.isNaN(n)?0:n)-(Number.isNaN(o)?0:o)})}getBySession(e){let r=String(e);return this.getAll().filter(n=>n.sessionId!==void 0&&String(n.sessionId)===r)}getRuntimeProcess(e){return this.runtimeProcesses.get(e)}getByPid(e){return this.getAll().filter(r=>r.pid===e)}pruneDeadEntries(){this.initialize();let e=0,r=0;for(let[n,o]of this.entries)wt(o.pid)||(this.entries.delete(n),this.runtimeProcesses.delete(n),e+=1,o.type==="sdk"&&(r+=1));e>0&&this.persist();for(let n=0;n<r;n+=1)pu();return e}async reapSession(e){this.initialize();let r=this.getBySession(e);if(r.length===0)return 0;let n=typeof e=="number"?e:Number(e)||void 0;y.info("SYSTEM",`Reaping ${r.length} process(es) for session ${e}`,{sessionId:n,pids:r.map(i=>i.pid)});let o=r.filter(i=>wt(i.pid));for(let i of o)try{typeof i.pgid=="number"&&process.platform!=="win32"?process.kill(-i.pgid,"SIGTERM"):process.kill(i.pid,"SIGTERM")}catch(a){a instanceof Error?a.code!=="ESRCH"&&y.debug("SYSTEM",`Failed to SIGTERM session process PID ${i.pid}`,{pid:i.pid,pgid:i.pgid},a):y.warn("SYSTEM",`Failed to SIGTERM session process PID ${i.pid} (non-Error)`,{pid:i.pid,pgid:i.pgid,error:String(a)})}await Cs(o,sP);let s=o.filter(i=>wt(i.pid));for(let i of s){y.warn("SYSTEM",`Session process PID ${i.pid} did not exit after SIGTERM, sending SIGKILL`,{pid:i.pid,pgid:i.pgid,sessionId:n});try{typeof i.pgid=="number"&&process.platform!=="win32"?process.kill(-i.pgid,"SIGKILL"):process.kill(i.pid,"SIGKILL")}catch(a){a instanceof Error?a.code!=="ESRCH"&&y.debug("SYSTEM",`Failed to SIGKILL session process PID ${i.pid}`,{pid:i.pid,pgid:i.pgid},a):y.warn("SYSTEM",`Failed to SIGKILL session process PID ${i.pid} (non-Error)`,{pid:i.pid,pgid:i.pgid,error:String(a)})}}if(s.length>0){let i=Date.now()+iP;for(;Date.now()<i&&s.filter(c=>wt(c.pid)).length!==0;)await new Promise(c=>setTimeout(c,100))}for(let i of r)this.entries.delete(i.id),this.runtimeProcesses.delete(i.id);this.persist();for(let i of r)i.type==="sdk"&&pu();return y.info("SYSTEM",`Reaped ${r.length} process(es) for session ${e}`,{sessionId:n,reaped:r.length}),r.length}persist(){let e={processes:Object.fromEntries(this.entries.entries())};(0,pt.mkdirSync)(fu.default.dirname(this.registryPath),{recursive:!0}),(0,pt.writeFileSync)(this.registryPath,JSON.stringify(e,null,2))}},du=null;function Ns(){return du||(du=new mu),du}var lP=[];function pu(){let t=lP.shift();t&&t()}var s_=require("child_process"),Dr=require("fs"),i_=require("util");var dP=(0,i_.promisify)(s_.execFile),pP=$e.workerPid();async function a_(t){let e=t.currentPid??process.pid,r=t.pidFilePath??pP,n=t.registry.getAll(),o=[...n].filter(i=>i.pid!==e).sort((i,a)=>Date.parse(a.startedAt)-Date.parse(i.startedAt));for(let i of o){if(!wt(i.pid)){t.registry.unregister(i.id);continue}try{await o_(i,"SIGTERM")}catch(a){a instanceof Error?y.debug("SYSTEM","Failed to send SIGTERM to child process",{pid:i.pid,pgid:i.pgid,type:i.type},a):y.warn("SYSTEM","Failed to send SIGTERM to child process (non-Error)",{pid:i.pid,pgid:i.pgid,type:i.type,error:String(a)})}}await Cs(o,5e3);let s=o.filter(i=>wt(i.pid));for(let i of s)try{await o_(i,"SIGKILL")}catch(a){a instanceof Error?y.debug("SYSTEM","Failed to force kill child process",{pid:i.pid,pgid:i.pgid,type:i.type},a):y.warn("SYSTEM","Failed to force kill child process (non-Error)",{pid:i.pid,pgid:i.pgid,type:i.type,error:String(a)})}await Cs(s,1e3);for(let i of o)t.registry.unregister(i.id);for(let i of n.filter(a=>a.pid===e))t.registry.unregister(i.id);fP(r,e),t.registry.pruneDeadEntries()}function fP(t,e){if(!(0,Dr.existsSync)(t))return;let r=null;try{let n=JSON.parse((0,Dr.readFileSync)(t,"utf-8"));r=typeof n.pid=="number"?n.pid:null}catch(n){y.debug("SYSTEM","PID file unreadable during shutdown \u2014 leaving it (cannot prove ownership)",{pidFilePath:t,error:n instanceof Error?n.message:String(n)});return}if(r!==e){y.debug("SYSTEM","PID file not owned by this process \u2014 leaving it for its owner (restart successor?)",{pidFilePath:t,recordedPid:r,currentPid:e});return}try{(0,Dr.rmSync)(t,{force:!0})}catch(n){n instanceof Error?y.debug("SYSTEM","Failed to remove PID file during shutdown",{pidFilePath:t},n):y.warn("SYSTEM","Failed to remove PID file during shutdown (non-Error)",{pidFilePath:t,error:String(n)})}}async function o_(t,e){let{pid:r,pgid:n}=t;if(process.platform!=="win32"){if(typeof n=="number")try{process.kill(-n,e);return}catch(i){if((i instanceof Error?i.code:void 0)!=="ESRCH")throw i}try{process.kill(r,e)}catch(i){if((i instanceof Error?i.code:void 0)!=="ESRCH")throw i}return}if(e==="SIGTERM"){try{process.kill(r,e)}catch(i){if(i instanceof Error&&i.code==="ESRCH")return;throw i}return}let o=await mP();if(o){await new Promise((i,a)=>{o(r,e,c=>{if(!c){i();return}if(c.code==="ESRCH"){i();return}a(c)})});return}let s=["/PID",String(r),"/T"];e==="SIGKILL"&&s.push("/F"),await dP("taskkill",s,{timeout:ue.POWERSHELL_COMMAND,windowsHide:!0})}async function mP(){let t="tree-kill";try{let e=await import(t);return e.default??e}catch(e){return y.debug("SYSTEM","tree-kill module not available, using fallback",{},e instanceof Error?e:void 0),null}}var c_=3e4,jr=null;function hP(){let e=Ns().pruneDeadEntries();e>0&&y.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function u_(){jr===null&&(jr=setInterval(hP,c_),jr.unref(),y.debug("SYSTEM","Health checker started",{intervalMs:c_}))}function l_(){jr!==null&&(clearInterval(jr),jr=null,y.debug("SYSTEM","Health checker stopped"))}var gP=$e.workerPid(),_u=class{registry;started=!1;stopPromise=null;signalHandlersRegistered=!1;shutdownInitiated=!1;shutdownHandler=null;constructor(e){this.registry=e}async start(){if(this.started)return;if(this.registry.initialize(),Ds({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,u_()}configureSignalHandlers(e){if(this.shutdownHandler=e,this.signalHandlersRegistered)return;this.signalHandlersRegistered=!0;let r=async n=>{if(this.shutdownInitiated){y.warn("SYSTEM",`Received ${n} but shutdown already in progress`);return}this.shutdownInitiated=!0,y.info("SYSTEM",`Received ${n}, shutting down...`);try{this.shutdownHandler?await this.shutdownHandler():await this.stop()}catch(o){o instanceof Error?y.error("SYSTEM","Error during shutdown",{},o):y.error("SYSTEM","Error during shutdown (non-Error)",{error:String(o)});try{await this.stop()}catch(s){s instanceof Error?y.debug("SYSTEM","Supervisor shutdown fallback failed",{},s):y.debug("SYSTEM","Supervisor shutdown fallback failed",{error:String(s)})}}process.exit(0)};process.on("SIGTERM",()=>{r("SIGTERM")}),process.on("SIGINT",()=>{r("SIGINT")}),process.platform!=="win32"&&(process.argv.includes("--daemon")?process.on("SIGHUP",()=>{y.debug("SYSTEM","Ignoring SIGHUP in daemon mode")}):process.on("SIGHUP",()=>{r("SIGHUP")}))}async stop(){if(this.stopPromise){await this.stopPromise;return}l_(),this.stopPromise=a_({registry:this.registry,currentPid:process.pid}).finally(()=>{this.started=!1,this.stopPromise=null}),await this.stopPromise}assertCanSpawn(e){if(this.stopPromise!==null)throw new Error(`Supervisor is shutting down, refusing to spawn ${e}`)}registerProcess(e,r,n){this.registry.register(e,r,n)}unregisterProcess(e){this.registry.unregister(e)}getRegistry(){return this.registry}},_P=new _u(Ns());function yu(){return _P}function Ds(t={}){let e=t.pidFilePath??gP;if(!(0,or.existsSync)(e))return"missing";let r=null;try{r=JSON.parse((0,or.readFileSync)(e,"utf-8"))}catch(o){return o instanceof Error?y.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e},o):y.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e,error:String(o)}),(0,or.rmSync)(e,{force:!0}),"invalid"}return gu(r)&&r?((t.logAlive??!0)&&y.info("SYSTEM","Worker already running (PID alive)",{existingPid:r.pid,existingPort:r.port,startedAt:r.startedAt}),"alive"):(y.info("SYSTEM","Removing stale PID file (worker process is dead or PID has been reused)",{pid:r?.pid,port:r?.port,startedAt:r?.startedAt}),(0,or.rmSync)(e,{force:!0}),"stale")}var f_=Ft(require("path"),1),m_=require("os"),ke=require("fs"),h_=require("child_process");function d_(t){return t instanceof Error?t:new Error(String(t))}var rD=$e.dataDir(),ft=$e.workerPid(),nD=$e.workerPort();function p_(t){return t?/(^|[\\/])node(\.exe)?$/i.test(t.trim()):!1}function yP(t,e){let r=e==="win32"?`where ${t}`:`which ${t}`,n;try{n=(0,h_.execSync)(r,{stdio:["ignore","pipe","ignore"],encoding:"utf-8",windowsHide:!0})}catch(s){return s instanceof Error?y.debug("SYSTEM",`Binary lookup failed for ${t}`,{command:r},s):y.debug("SYSTEM",`Binary lookup failed for ${t}`,{command:r},new Error(String(s))),null}return n.split(/\r?\n/).map(s=>s.trim()).find(s=>s.length>0)||null}var Su;function g_(t={}){let e=Object.keys(t).length===0;if(e&&Su!==void 0)return Su;let r=SP(t);return e&&r!==null&&(Su=r),r}function SP(t){let e=t.platform??process.platform,r=t.execPath??process.execPath;if(p_(r))return r;let n=t.env??process.env,o=t.homeDirectory??(0,m_.homedir)(),s=t.pathExists??ke.existsSync,i=t.lookupInPath??yP,a=e==="win32"?[n.NODE,f_.default.join(o,".nvm","current","bin","node.exe"),"node"]:[n.NODE,"/usr/local/bin/node","/opt/homebrew/bin/node","/usr/bin/node","node"];for(let c of a){let u=c?.trim();if(u&&(p_(u)&&s(u)||u.toLowerCase()==="node"))return u}return i("node",e)}function __(){if(!(0,ke.existsSync)(ft))return null;try{return JSON.parse((0,ke.readFileSync)(ft,"utf-8"))}catch(t){return t instanceof Error?y.warn("SYSTEM","Failed to parse PID file",{path:ft},t):y.warn("SYSTEM","Failed to parse PID file",{path:ft},new Error(String(t))),null}}function y_(){if((0,ke.existsSync)(ft))try{(0,ke.unlinkSync)(ft)}catch(t){t instanceof Error?y.warn("SYSTEM","Failed to remove PID file",{path:ft},t):y.warn("SYSTEM","Failed to remove PID file",{path:ft},new Error(String(t)))}}function Ut(t){return process.platform==="win32"?Math.round(t*2):t}function S_(t,e,r={}){yu().assertCanSpawn("worker daemon");let n=Jn({...process.env,CLAUDE_MEM_WORKER_PORT:String(e),...r}),o=g_();if(!o){y.error("SYSTEM","Node runtime not found \u2014 ensure node is on PATH or set the NODE env var. The worker daemon runs under Node (node:sqlite).");return}if(process.platform==="win32")try{let l=Gn(o,[t,"--daemon"],{detached:!0,stdio:"ignore",windowsHide:!0,env:n});if(l.pid===void 0){y.error("SYSTEM","Worker daemon spawn produced no PID on Windows",{runtimePath:o});return}return l.unref(),l.pid}catch(l){y.error("SYSTEM","Failed to spawn worker daemon on Windows",{runtimePath:o},d_(l));return}let s="/usr/bin/setsid",i=(0,ke.existsSync)(s),u=Gn(i?s:o,i?[o,t,"--daemon"]:[t,"--daemon"],{detached:!0,stdio:"ignore",env:n});if(u.pid!==void 0)return u.unref(),u.pid}function v_(t){if(t===0)return!0;if(!Number.isInteger(t)||t<0)return!1;try{return process.kill(t,0),!0}catch(e){if(e instanceof Error){let r=e.code;if(r==="EPERM")return!0;y.debug("SYSTEM","Process not alive",{pid:t,code:r})}else y.debug("SYSTEM","Process not alive (non-Error thrown)",{pid:t},new Error(String(e)));return!1}}function b_(){try{if(!(0,ke.existsSync)(ft))return;let t=new Date;(0,ke.utimesSync)(ft,t,t)}catch{}}function E_(){return Ds({logAlive:!1})}var w_=Ft(require("net"),1);var vP=2500;async function bP(t,e,r="GET"){let n=await fetch(`http://127.0.0.1:${t}${e}`,{method:r,signal:AbortSignal.timeout(vP)}),o="";try{o=await n.text()}catch{}return{ok:n.ok,statusCode:n.status,body:o}}async function k_(t){return new Promise(e=>{let r=w_.default.createServer();r.once("error",n=>{n.code==="EADDRINUSE"||n.code==="EACCES"?e(!0):e(!1)}),r.once("listening",()=>{r.close(()=>e(!1))}),r.listen(t,"127.0.0.1")})}async function x_(t,e,r,n){let o=Date.now();for(;Date.now()-o<r;){try{if((await bP(t,e)).ok)return!0}catch(s){s instanceof Error?y.debug("SYSTEM",n,{},s):y.debug("SYSTEM",n,{error:String(s)})}await new Promise(s=>setTimeout(s,500))}return!1}function Bn(t,e=3e4){return x_(t,"/api/health",e,"Service not ready yet, will retry")}function Yn(t,e=3e4){return x_(t,"/api/readiness",e,"Worker not ready yet, will retry")}var js=require("path"),Ke=require("fs");var EP=6e4;function $_(){return(0,js.join)(Qs(),"spawn.lock")}function vu(){let t=$_(),e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()});for(let r=0;r<2;r++)try{return(0,Ke.mkdirSync)((0,js.dirname)(t),{recursive:!0}),(0,Ke.writeFileSync)(t,e,{flag:"wx"}),!0}catch(n){if(n?.code!=="EEXIST")return!0;if(r>0)return!1;let s;try{s=(0,Ke.statSync)(t).mtimeMs}catch{continue}if(Date.now()-s<=EP)return!1;let i;try{i=(0,Ke.statSync)(t).mtimeMs}catch{continue}if(i!==s)return!1;try{(0,Ke.unlinkSync)(t)}catch{return!1}}return!1}function bu(){let t=$_();try{if(JSON.parse((0,Ke.readFileSync)(t,"utf-8")).pid!==process.pid)return;(0,Ke.unlinkSync)(t)}catch{}}function Eu(t,e,r){let n=process.env[t];if(n){let o=parseInt(n,10);if(Number.isFinite(o)&&o>=r.min&&o<=r.max)return o;y.warn("SYSTEM",`Invalid ${t}, using default`,{value:n,min:r.min,max:r.max})}return e}var RD=Eu("CLAUDE_MEM_HEALTH_TIMEOUT_MS",Et(ue.HEALTH_CHECK),{min:500,max:3e5}),ID=Eu("CLAUDE_MEM_API_TIMEOUT_MS",Et(ue.API_REQUEST),{min:500,max:3e5}),OD=Eu("CLAUDE_MEM_HOOK_READINESS_TIMEOUT_MS",Et(ue.HOOK_READINESS_WAIT),{min:0,max:3e5}),wP={min:500,max:3e5};async function wu(t,e={},r){try{return await fetch(t,{...e,signal:AbortSignal.timeout(r)})}catch(n){throw n instanceof DOMException&&n.name==="TimeoutError"?new Error(`Request timed out after ${r}ms`):n}}var Ls=null,Us=null,qs=null,Zs=null;function kP(){return Fs.default.join(nr.get("CLAUDE_MEM_DATA_DIR"),"settings.json")}function xP(t){if(!Number.isInteger(t)||t<=0)return!1;try{return process.kill(t,0),!0}catch(e){return e?.code==="EPERM"}}function $P(){try{let t=$e.workerPid();if(!(0,qt.existsSync)(t))return null;let e=JSON.parse((0,qt.readFileSync)(t,"utf-8"));return typeof e.pid!="number"||typeof e.port!="number"||!xP(e.pid)?null:e.port}catch{return null}}function ku(){return qs!==null||(qs=nr.loadFromFile(kP())),qs}function P_(t,e){if(!t)return null;let r=parseInt(t,10);return Number.isFinite(r)&&r>=e.min&&r<=e.max?r:null}function PP(t,e,r){let n=process.env[t];if(n!==void 0){let i=P_(n,r);return i!==null?i:(y.warn("SYSTEM",`Invalid ${t}, using default`,{value:n,min:r.min,max:r.max}),e)}let o=ku()[t],s=P_(o,r);return s!==null?s:(y.warn("SYSTEM",`Invalid ${t} in settings.json, using default`,{value:o,min:r.min,max:r.max}),e)}function TP(){if(Ls!==null)return Ls;let t=ku();return Ls=parseInt(t.CLAUDE_MEM_WORKER_PORT,10),Ls}function xu(){let t=$P();return t!==null?t:TP()}function zP(){return Us!==null||(Us=ku().CLAUDE_MEM_WORKER_HOST),Us}function RP(){return Zs!==null||(Zs=PP("CLAUDE_MEM_API_TIMEOUT_MS",Et(ue.API_REQUEST),wP)),Zs}function IP(t){return`http://${zP()}:${xu()}${t}`}function Xn(t,e={}){let r=e.method??"GET",n=e.timeoutMs??RP(),o=IP(t),s={method:r};return e.headers&&(s.headers=e.headers),e.body&&(s.body=e.body),n>0?wu(o,s,n):fetch(o,s)}function T_(){let t=[Fs.default.join(ei,"plugin","scripts","worker-service.cjs"),Fs.default.join(process.cwd(),"plugin","scripts","worker-service.cjs")];for(let e of t)if((0,qt.existsSync)(e))return e;return null}var z_=require("fs");function OP(t){let e=__();return e&&typeof e.port=="number"&&v_(e.pid)?e.port:t}async function AP(t,e){let r=Date.now()+e;for(;Date.now()<r;){let n=OP(t);if(await Bn(n,800))return n;await new Promise(o=>setTimeout(o,300))}return null}async function R_(t,e){if(!e)return y.error("SYSTEM","ensureWorkerStarted called with empty workerScriptPath \u2014 caller bug"),"dead";if(!(0,z_.existsSync)(e))return y.error("SYSTEM","ensureWorkerStarted: worker script not found at expected path \u2014 likely a partial install or build artifact missing",{workerScriptPath:e}),"dead";if(await Bn(t,1e3)){let a=await Yn(t,Ut(ue.READINESS_WAIT));return a||y.warn("SYSTEM","Worker is alive but readiness timed out \u2014 proceeding anyway"),y.info("SYSTEM","Worker already running and healthy (fast path)"),a?"ready":"warming"}if(E_()==="alive"){if(y.info("SYSTEM","Worker PID file points to a live process, waiting for it to become healthy"),await Bn(t,Ut(ue.POST_SPAWN_WAIT))){let c=await Yn(t,Ut(ue.READINESS_WAIT));return y.info("SYSTEM","Worker became healthy while waiting on live PID"),c?"ready":"warming"}y.warn("SYSTEM","PID file marked live but worker never became healthy within the cold-boot window \u2014 treating it as a stale/reused PID and re-spawning"),y_()}if(await k_(t)){if(y.info("SYSTEM","Port in use, waiting for worker to become healthy"),await Bn(t,Ut(ue.PORT_IN_USE_WAIT))){let c=await Yn(t,Ut(ue.READINESS_WAIT));return y.info("SYSTEM","Worker is now healthy"),c?"ready":"warming"}y.warn("SYSTEM","Configured port in use but no healthy worker \u2014 spawning anyway (worker will pick a free ephemeral port)")}let o=vu(),s=t;try{if(o){if(y.info("SYSTEM","Starting worker daemon",{workerScriptPath:e}),S_(e,t)===void 0)return y.error("SYSTEM","Failed to spawn worker daemon"),"dead"}else y.info("SYSTEM","Another launcher holds the spawn lock \u2014 skipping duplicate spawn and waiting for its worker");let a=await AP(t,Ut(ue.POST_SPAWN_WAIT));if(a===null)return y.warn("SYSTEM",o?"Worker spawned but health endpoint not responding within window \u2014 likely still starting in background":"Spawn-lock holder's worker not healthy within window \u2014 likely still starting in background"),"warming";s=a}finally{o&&bu()}let i=await Yn(s,Ut(ue.READINESS_WAIT));return i||y.warn("SYSTEM","Worker is alive but readiness timed out \u2014 proceeding anyway"),b_(),y.info("SYSTEM",o?"Worker started successfully":"Worker is up (started by another launcher)"),i?"ready":"warming"}var qr=require("node:fs/promises"),ro=require("node:path");var A_=require("node:child_process"),Se=require("node:fs"),le=require("node:path"),Iu=require("node:os"),Tu=require("node:module");var GP={},zu=typeof __filename<"u"?(0,Tu.createRequire)(__filename):(0,Tu.createRequire)(GP.url),Ru={".js":"javascript",".mjs":"javascript",".cjs":"javascript",".jsx":"tsx",".ts":"typescript",".tsx":"tsx",".py":"python",".pyw":"python",".go":"go",".rs":"rust",".rb":"ruby",".java":"java",".c":"c",".h":"c",".cpp":"cpp",".cc":"cpp",".cxx":"cpp",".hpp":"cpp",".hh":"cpp",".kt":"kotlin",".kts":"kotlin",".swift":"swift",".php":"php",".ex":"elixir",".exs":"elixir",".lua":"lua",".scala":"scala",".sc":"scala",".sh":"bash",".bash":"bash",".zsh":"bash",".hs":"haskell",".zig":"zig",".css":"css",".scss":"scss",".toml":"toml",".yml":"yaml",".yaml":"yaml",".sql":"sql",".md":"markdown",".mdx":"markdown"};function M_(t,e){let r=t.slice(t.lastIndexOf("."));return Ru[r]?Ru[r]:e.extensionToLanguage[r]?e.extensionToLanguage[r]:"unknown"}function C_(t,e){return e.languageToQueryKey[t]?e.languageToQueryKey[t]:NP(t)}var Qn=new Map,Lr={grammars:{},extensionToLanguage:{},languageToQueryKey:{}},N_=[".keepmind.json",".claude-mem.json"];function to(t){if(Qn.has(t))return Qn.get(t);let e;for(let s of N_)try{e=(0,Se.readFileSync)((0,le.join)(t,s),"utf-8");break}catch{}let r;try{if(e===void 0)throw new Error("no project config");r=JSON.parse(e)}catch{return Qn.set(t,Lr),Lr}let n=r.grammars;if(!n||typeof n!="object"||Array.isArray(n))return Qn.set(t,Lr),Lr;let o={grammars:{},extensionToLanguage:{},languageToQueryKey:{}};for(let[s,i]of Object.entries(n)){if(D_[s]||!i||typeof i!="object"||Array.isArray(i))continue;let a=i,c=a.package,u=a.extensions,l=a.query;if(!(typeof c!="string"||!Array.isArray(u))&&u.every(d=>typeof d=="string")){o.grammars[s]={package:c,extensions:u,query:typeof l=="string"?l:void 0};for(let d of u)Ru[d]||(o.extensionToLanguage[d]=s);if(typeof l=="string"){let d=(0,le.join)(t,l);try{let p=(0,Se.readFileSync)(d,"utf-8"),f=`user_${s}`;L_[f]=p,o.languageToQueryKey[s]=f}catch{y.warn("PARSER","Custom query file not found, falling back to generic",{fullQueryPath:d}),o.languageToQueryKey[s]="generic"}}else o.languageToQueryKey[s]="generic"}}return Qn.set(t,o),o}var D_={javascript:"tree-sitter-javascript",typescript:"tree-sitter-typescript/typescript",tsx:"tree-sitter-typescript/tsx",python:"tree-sitter-python",go:"tree-sitter-go",rust:"tree-sitter-rust",ruby:"tree-sitter-ruby",java:"tree-sitter-java",c:"tree-sitter-c",cpp:"tree-sitter-cpp",kotlin:"tree-sitter-kotlin",swift:"tree-sitter-swift",php:"tree-sitter-php/php",elixir:"tree-sitter-elixir",lua:"@tree-sitter-grammars/tree-sitter-lua",scala:"tree-sitter-scala",bash:"tree-sitter-bash",haskell:"tree-sitter-haskell",zig:"@tree-sitter-grammars/tree-sitter-zig",css:"tree-sitter-css",scss:"tree-sitter-scss",toml:"@tree-sitter-grammars/tree-sitter-toml",yaml:"@tree-sitter-grammars/tree-sitter-yaml",sql:"@derekstride/tree-sitter-sql",markdown:"@tree-sitter-grammars/tree-sitter-markdown"},MP={markdown:"tree-sitter-markdown"};function CP(t){let e=D_[t];if(!e)return null;let r=MP[t];if(r){try{let n=zu.resolve(e+"/package.json"),o=(0,le.join)((0,le.dirname)(n),r);if((0,Se.existsSync)((0,le.join)(o,"src")))return o}catch{}return null}try{let n=zu.resolve(e+"/package.json");return(0,le.dirname)(n)}catch{return null}}function j_(t,e){let r=CP(t);if(r)return r;if(!e)return null;let o=to(e).grammars[t];if(!o)return null;try{let s=(0,le.join)(e,"node_modules",o.package,"package.json");if((0,Se.existsSync)(s)){let i=(0,le.dirname)(s);if((0,Se.existsSync)((0,le.join)(i,"src")))return i}}catch{}return y.warn("PARSER","Grammar package not found",{language:t,package:o.package}),null}var L_={jsts:`
84
84
  (function_declaration name: (identifier) @name) @func
85
85
  (lexical_declaration (variable_declarator name: (identifier) @name value: [(arrow_function) (function_expression)])) @const_func
86
86
  (class_declaration name: (type_identifier) @name) @cls
@@ -202,7 +202,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
202
202
  (class_definition name: (identifier) @name) @cls
203
203
  (import_statement) @imp
204
204
  (import_declaration) @imp
205
- `};function NP(t){switch(t){case"javascript":return"js";case"typescript":case"tsx":return"jsts";case"python":return"python";case"go":return"go";case"rust":return"rust";case"ruby":return"ruby";case"java":return"java";case"kotlin":return"kotlin";case"swift":return"swift";case"php":return"php";case"elixir":return"generic";case"lua":return"lua";case"scala":return"scala";case"bash":return"bash";case"haskell":return"haskell";case"zig":return"zig";case"css":return"css";case"scss":return"scss";case"toml":return"toml";case"yaml":return"yaml";case"sql":return"sql";case"markdown":return"markdown";default:return"generic"}}var $u=null,Pu=new Map;function U_(t){if(Pu.has(t))return Pu.get(t);$u||($u=(0,Se.mkdtempSync)((0,le.join)((0,Iu.tmpdir)(),"smart-read-queries-")));let e=(0,le.join)($u,`${t}.scm`);return(0,Se.writeFileSync)(e,L_[t]),Pu.set(t,e),e}var eo=null;function DP(){if(eo)return eo;try{let t=zu.resolve("tree-sitter-cli/package.json"),e=(0,le.join)((0,le.dirname)(t),"tree-sitter");if((0,Se.existsSync)(e))return eo=e,e}catch{}return eo="tree-sitter",eo}function jP(t,e,r){return q_(t,[e],r).get(e)||[]}function q_(t,e,r){if(e.length===0)return new Map;let n=DP(),o=["query","-p",r,t,...e],s;try{s=(0,A_.execFileSync)(n,o,{encoding:"utf-8",timeout:3e4,stdio:["pipe","pipe","pipe"]})}catch(i){return y.debug("WORKER",`tree-sitter query failed for ${e.length} file(s)`,void 0,i instanceof Error?i:void 0),new Map}return LP(s)}function LP(t){let e=new Map,r=null,n=null;for(let o of t.split(`
205
+ `};function NP(t){switch(t){case"javascript":return"js";case"typescript":case"tsx":return"jsts";case"python":return"python";case"go":return"go";case"rust":return"rust";case"ruby":return"ruby";case"java":return"java";case"kotlin":return"kotlin";case"swift":return"swift";case"php":return"php";case"elixir":return"generic";case"lua":return"lua";case"scala":return"scala";case"bash":return"bash";case"haskell":return"haskell";case"zig":return"zig";case"css":return"css";case"scss":return"scss";case"toml":return"toml";case"yaml":return"yaml";case"sql":return"sql";case"markdown":return"markdown";default:return"generic"}}var $u=null,Pu=new Map;function U_(t){if(Pu.has(t))return Pu.get(t);$u||($u=(0,Se.mkdtempSync)((0,le.join)((0,Iu.tmpdir)(),"smart-read-queries-")));let e=(0,le.join)($u,`${t}.scm`);return(0,Se.writeFileSync)(e,L_[t]),Pu.set(t,e),e}var eo=null;function DP(){if(eo)return eo;try{let t=zu.resolve("tree-sitter-cli/package.json"),e=(0,le.join)((0,le.dirname)(t),"tree-sitter");if((0,Se.existsSync)(e))return eo=e,e}catch{}return eo="tree-sitter",eo}function jP(t,e,r){return q_(t,[e],r).get(e)||[]}function q_(t,e,r){if(e.length===0)return new Map;let n=DP(),o=["query","-p",r,t,...e],s;try{s=(0,A_.execFileSync)(n,o,{encoding:"utf-8",timeout:3e4,stdio:["pipe","pipe","pipe"],windowsHide:!0})}catch(i){return y.debug("WORKER",`tree-sitter query failed for ${e.length} file(s)`,void 0,i instanceof Error?i:void 0),new Map}return LP(s)}function LP(t){let e=new Map,r=null,n=null;for(let o of t.split(`
206
206
  `)){if(o.length>0&&!o.startsWith(" ")&&!o.startsWith(" ")){r=o.trim(),e.has(r)||e.set(r,[]),n=null;continue}if(!r)continue;let s=o.match(/^\s+pattern:\s+(\d+)/);if(s){n={pattern:parseInt(s[1]),captures:[]},e.get(r).push(n);continue}let i=o.match(/^\s+capture:\s+(?:\d+\s*-\s*)?(\w+),\s*start:\s*\((\d+),\s*(\d+)\),\s*end:\s*\((\d+),\s*(\d+)\)(?:,\s*text:\s*`([^`]*)`)?/);i&&n&&n.captures.push({tag:i[1],startRow:parseInt(i[2]),startCol:parseInt(i[3]),endRow:parseInt(i[4]),endCol:parseInt(i[5]),text:i[6]})}return e}var I_={func:"function",const_func:"function",cls:"class",method:"method",iface:"interface",tdef:"type",enm:"enum",struct_def:"struct",trait_def:"trait",impl_def:"impl",mixin_def:"mixin",heading:"section",code_block:"code",frontmatter:"metadata",ref:"reference"},UP=new Set(["class","struct","impl","trait"]);function qP(t,e,r,n=200){let s=t[e]||"";if(!s.trimEnd().endsWith("{")&&!s.trimEnd().endsWith(":")){let i=t.slice(e,Math.min(e+10,r+1)).join(`
207
207
  `),a=i.indexOf("{");a!==-1&&a<500&&(s=i.slice(0,a).replace(/\n/g," ").replace(/\s+/g," ").trim())}return s=s.replace(/\s*[{:]\s*$/,"").trim(),s.length>n&&(s=s.slice(0,n-3)+"..."),s}function ZP(t,e){let r=[],n=!1;for(let o=e-1;o>=0;o--){let s=t[o].trim();if(s===""){if(n)break;continue}if(s.startsWith("/**")||s.startsWith("*")||s.startsWith("*/")||s.startsWith("//")||s.startsWith("///")||s.startsWith("//!")||s.startsWith("#")||s.startsWith("@"))r.unshift(t[o]),n=!0;else break}return r.length>0?r.join(`
208
208
  `).trim():void 0}function FP(t,e,r){for(let n=e+1;n<=Math.min(e+3,r);n++){let o=t[n]?.trim();if(o){if(o.startsWith('"""')||o.startsWith("'''"))return o;break}}}function HP(t,e,r,n,o,s){switch(s){case"javascript":case"typescript":case"tsx":return n.some(i=>e>=i.startRow&&r<=i.endRow);case"python":return!t.startsWith("_");case"go":return t.length>0&&t[0]===t[0].toUpperCase()&&t[0]!==t[0].toLowerCase();case"rust":return o[e]?.trimStart().startsWith("pub")??!1;default:return!0}}function Z_(t,e,r){let n=[],o=[],s=[],i=[];for(let c of t)for(let u of c.captures)u.tag==="exp"&&s.push({startRow:u.startRow,endRow:u.endRow}),u.tag==="imp"&&o.push(u.text||e[u.startRow]?.trim()||"");for(let c of t){let u=c.captures.find(v=>I_[v.tag]),l=c.captures.find(v=>v.tag==="name");if(!u)continue;let d=u.startRow,p=u.endRow,f=I_[u.tag],m=l?.text||"anonymous",_;if(r==="markdown"&&f==="section"){let $=(e[d]||"").match(/^(#{1,6})\s/),x=$?$[1].length:1;_=`${"#".repeat(x)} ${m}`}else if(r==="markdown"&&f==="code"){let v=m!=="anonymous"?m:"";_=v?"```"+v:"```"}else r==="markdown"&&f==="metadata"?_="---frontmatter---":r==="markdown"&&f==="reference"?_=e[d]?.trim()||m:_=qP(e,d,p);let S=r==="markdown"?void 0:ZP(e,d),b=r==="python"?FP(e,d,p):void 0,E={name:m,kind:f,signature:_,jsdoc:S||b,lineStart:d,lineEnd:p,exported:HP(m,d,p,s,e,r)};UP.has(f)&&(E.children=[],i.push({sym:E,startRow:d,endRow:p})),n.push(E)}if(r==="markdown"){let c=new Map,u=new Set;for(let l of n){if(l.kind!=="code")continue;let d=`${l.lineStart}:${l.lineEnd}`,p=c.get(d);p?l.name!=="anonymous"?(u.add(p),c.set(d,l)):u.add(l):c.set(d,l)}if(u.size>0){let l=n.filter(d=>!u.has(d));n.length=0,n.push(...l)}}let a=new Set;for(let c of i)for(let u of n)u!==c.sym&&u.lineStart>c.startRow&&u.lineEnd<=c.endRow&&(u.kind==="function"&&(u.kind="method"),c.sym.children.push(u),a.add(u));return{symbols:n.filter(c=>!a.has(c)),imports:o}}function Ou(t){let e=(0,le.dirname)(t);for(;;){if(N_.some(n=>(0,Se.existsSync)((0,le.join)(e,n))))return e;let r=(0,le.dirname)(e);if(r===e)return;e=r}}function Hs(t,e,r){let n=r?to(r):Lr,o=M_(e,n),s=t.split(`
@@ -220,7 +220,7 @@ ${m}`}let c=i.lineStart;for(let l=i.lineStart-1;l>=0;l--){let d=a[l].trim();if(d
220
220
  ${u}`}var V_=new Set([".js",".jsx",".ts",".tsx",".mjs",".cjs",".py",".pyw",".go",".rs",".rb",".java",".cs",".cpp",".cc",".cxx",".c",".h",".hpp",".hh",".swift",".kt",".kts",".php",".vue",".svelte",".ex",".exs",".lua",".scala",".sc",".sh",".bash",".zsh",".hs",".zig",".css",".scss",".toml",".yml",".yaml",".sql",".md",".mdx"]),KP=new Set(["node_modules",".git","dist","build",".next","__pycache__",".venv","venv","env",".env","target","vendor",".cache",".turbo","coverage",".nyc_output",".claude",".smart-file-read"]),JP=512*1024;async function*G_(t,e,r=20,n){if(r<=0)return;let o;try{o=await(0,qr.readdir)(t,{withFileTypes:!0})}catch(s){y.debug("WORKER",`walkDir: failed to read directory ${t}`,void 0,s instanceof Error?s:void 0);return}for(let s of o){if(s.name.startsWith(".")&&s.name!=="."||KP.has(s.name))continue;let i=(0,ro.join)(t,s.name);if(s.isDirectory())yield*G_(i,e,r-1,n);else if(s.isFile()){let a=s.name.slice(s.name.lastIndexOf("."));(V_.has(a)||n&&n.has(a))&&(yield i)}}}async function BP(t){try{let e=await(0,qr.stat)(t);if(e.size>JP||e.size===0)return null;let r=await(0,qr.readFile)(t,"utf-8");return r.slice(0,1e3).includes("\0")?null:r}catch(e){return y.debug("WORKER",`safeReadFile: failed to read ${t}`,void 0,e instanceof Error?e:void 0),null}}async function K_(t,e,r={}){let n=r.maxResults||20,o=e.toLowerCase(),s=o.split(/[\s_\-./]+/).filter(E=>E.length>0),i=r.projectRoot||t,a=to(i),c=new Set;for(let E of Object.values(a.grammars))for(let v of E.extensions)V_.has(v)||c.add(v);let u=[];for await(let E of G_(t,t,20,c.size>0?c:void 0)){if(r.filePattern&&!(0,ro.relative)(t,E).toLowerCase().includes(r.filePattern.toLowerCase()))continue;let v=await BP(E);v&&u.push({absolutePath:E,relativePath:(0,ro.relative)(t,E),content:v})}let l=F_(u,i),d=[],p=[],f=0;for(let[E,v]of l){f+=YP(v);let x=Ws(E.toLowerCase(),s)>0,ve=[],xe=(Zt,ir)=>{for(let ce of Zt){let kt=0,Be="",Zr=Ws(ce.name.toLowerCase(),s);Zr>0&&(kt+=Zr*3,Be="name match"),ce.signature.toLowerCase().includes(o)&&(kt+=2,Be=Be?`${Be} + signature`:"signature match"),ce.jsdoc&&ce.jsdoc.toLowerCase().includes(o)&&(kt+=1,Be=Be?`${Be} + jsdoc`:"jsdoc match"),kt>0&&(x=!0,ve.push({filePath:E,symbolName:ir?`${ir}.${ce.name}`:ce.name,kind:ce.kind,signature:ce.signature,jsdoc:ce.jsdoc,lineStart:ce.lineStart,lineEnd:ce.lineEnd,matchReason:Be})),ce.children&&xe(ce.children,ce.name)}};xe(v.symbols),x&&(d.push(v),p.push(...ve))}p.sort((E,v)=>{let $=Ws(E.symbolName.toLowerCase(),s);return Ws(v.symbolName.toLowerCase(),s)-$});let m=p.slice(0,n),_=new Set(m.map(E=>E.filePath)),S=d.filter(E=>_.has(E.filePath)).slice(0,n),b=S.reduce((E,v)=>E+v.foldedTokenEstimate,0);return{foldedFiles:S,matchingSymbols:m,totalFilesScanned:u.length,totalSymbolsFound:f,tokenEstimate:b}}function Ws(t,e){let r=0;for(let n of e)if(t===n)r+=10;else if(t.includes(n))r+=5;else{let o=0,s=0;for(let i of n){let a=t.indexOf(i,o);a!==-1&&(s++,o=a+1)}s===n.length&&(r+=1)}return r}function YP(t){let e=t.symbols.length;for(let r of t.symbols)r.children&&(e+=r.children.length);return e}function J_(t,e){let r=[];if(r.push(`\u{1F50D} Smart Search: "${e}"`),r.push(` Scanned ${t.totalFilesScanned} files, found ${t.totalSymbolsFound} symbols`),r.push(` ${t.matchingSymbols.length} matches across ${t.foldedFiles.length} files (~${t.tokenEstimate} tokens for folded view)`),r.push(""),t.matchingSymbols.length===0)return r.push(" No matching symbols found."),r.join(`
221
221
  `);r.push("\u2500\u2500 Matching Symbols \u2500\u2500"),r.push("");for(let n of t.matchingSymbols){if(r.push(` ${n.kind} ${n.symbolName} (${n.filePath}:${n.lineStart+1})`),r.push(` ${n.signature}`),n.jsdoc){let o=n.jsdoc.split(`
222
222
  `).find(s=>s.replace(/^[\s*/]+/,"").trim().length>0);o&&r.push(` \u{1F4AC} ${o.replace(/^[\s*/]+/,"").trim()}`)}r.push("")}r.push("\u2500\u2500 Folded File Views \u2500\u2500"),r.push("");for(let n of t.foldedFiles)r.push(Ur(n)),r.push("");return r.push("\u2500\u2500 Actions \u2500\u2500"),r.push(" To see full implementation: use smart_unfold with file path and symbol name"),r.join(`
223
- `)}var Nu=require("node:fs/promises"),Ks=require("node:fs"),nt=require("node:path"),oy=require("node:os"),sy=require("node:url");var B_="claude";function XP(t){return t.trim().toLowerCase().replace(/\s+/g,"-")}function Vs(t){if(!t)return B_;let e=XP(t);return e?e==="transcript"||e.includes("codex")?"codex":e.includes("cursor")?"cursor":e.includes("claude")?"claude":e:B_}var QP=Et(ue.API_REQUEST),Je=class extends Error{kind;status;cause;constructor(e,r,n={}){super(r),this.name="ServerClientError",this.kind=e,this.status=n.status??null,this.cause=n.cause}isFallbackEligible(){return this.kind==="transport"||this.kind==="timeout"||this.kind==="missing_api_key"||this.kind==="http_error"&&(this.status!==null&&this.status>=500||this.status===429)}},Gs=class{baseUrl;apiKey;timeoutMs;constructor(e){this.baseUrl=eT(e.serverBaseUrl),this.apiKey=e.apiKey,this.timeoutMs=e.timeoutMs??QP}async startSession(e){let r=this.buildStartSessionPayload(e);return this.request("POST","/v1/sessions/start",r)}async recordEvent(e){let r=this.buildEventPayload(e),n=e.generate===!1?"/v1/events?generate=false":"/v1/events";return this.request("POST",n,r)}async endSession(e){if(!e.sessionId)throw new Je("invalid_response","sessionId is required for endSession");return this.request("POST",`/v1/sessions/${encodeURIComponent(e.sessionId)}/end`,{})}async addObservation(e){return this.request("POST","/v1/memories",this.buildAddObservationPayload(e))}async searchObservations(e){return this.request("POST","/v1/search",this.buildSearchPayload(e))}async contextObservations(e){return this.request("POST","/v1/context",this.buildSearchPayload(e))}async getJobStatus(e){if(!e)throw new Je("invalid_response","jobId is required for getJobStatus");return this.request("GET",`/v1/jobs/${encodeURIComponent(e)}`)}buildAddObservationPayload(e){let r=e.content,n=e.kind??"manual",o=typeof e.metadata?.title=="string"?e.metadata.title:void 0;return{projectId:e.projectId,kind:n,type:n,narrative:r,...o?{title:o}:{},...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}buildSearchPayload(e){return{projectId:e.projectId,query:e.query,...e.limit!==void 0?{limit:e.limit}:{},...e.platformSource!==void 0?{platformSource:Au(e.platformSource)}:{}}}buildStartSessionPayload(e){return{projectId:e.projectId,...e.externalSessionId!==void 0?{externalSessionId:e.externalSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.agentId!==void 0?{agentId:e.agentId}:{},...e.agentType!==void 0?{agentType:e.agentType}:{},...e.platformSource!==void 0?{platformSource:Au(e.platformSource)}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}buildEventPayload(e){return{projectId:e.projectId,sourceType:e.sourceType,eventType:e.eventType,occurredAtEpoch:e.occurredAtEpoch,...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.memorySessionId!==void 0?{memorySessionId:e.memorySessionId}:{},...e.platformSource!==void 0?{platformSource:Au(e.platformSource)}:{},...e.payload!==void 0?{payload:e.payload}:{}}}async request(e,r,n){if(!this.apiKey||!this.apiKey.trim())throw new Je("missing_api_key","Server API key is not configured (CLAUDE_MEM_SERVER_API_KEY).");let o=`${this.baseUrl}${r}`,s={method:e,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}};n!==void 0&&(s.body=JSON.stringify(n));let i;try{i=await wu(o,s,this.timeoutMs)}catch(c){let u=c instanceof Error?c.message:String(c),l=/timed out|timeout/i.test(u);throw new Je(l?"timeout":"transport",`Server ${e} ${r} failed: ${u}`,{cause:c})}if(!i.ok){let c=await i.text().catch(()=>"");throw new Je("http_error",`Server ${e} ${r} returned ${i.status}: ${tT(c,200)}`,{status:i.status})}let a=await i.text();if(!a||a.length===0)return{};try{return JSON.parse(a)}catch(c){throw new Je("invalid_response",`Server ${e} ${r} returned non-JSON response`,{cause:c})}}};function Y_(t){return t instanceof Je}function eT(t){return t.replace(/\/+$/,"")}function Au(t){return typeof t=="string"?Vs(t):null}function tT(t,e){return t.length<=e?t:`${t.slice(0,e)}\u2026`}function Mu(){let e=(Ms().CLAUDE_MEM_RUNTIME??"worker").trim().toLowerCase();return e==="server"||e==="server-beta"?"server":"worker"}function X_(){let t=Ms(),e=(...i)=>{for(let a of i){let c=(a??"").trim();if(c.length>0)return c}return""},r=e(t.CLAUDE_MEM_SERVER_URL,t.CLAUDE_MEM_SERVER_BETA_URL),n=e(t.CLAUDE_MEM_SERVER_API_KEY,t.CLAUDE_MEM_SERVER_BETA_API_KEY),o=e(t.CLAUDE_MEM_SERVER_PROJECT_ID,t.CLAUDE_MEM_SERVER_BETA_PROJECT_ID);if(!r)return y.warn("HOOK","[server-fallback] reason=missing_base_url"),null;if(!n)return y.warn("HOOK","[server-fallback] reason=missing_api_key"),null;if(!o)return y.warn("HOOK","[server-fallback] reason=missing_project_id"),null;let s={serverBaseUrl:r,apiKey:n};return{runtime:"server",client:new Gs(s),projectId:o,serverBaseUrl:r}}var ST={},rT="1.3.0";console.log=(...t)=>{y.error("CONSOLE","Intercepted console output (MCP protocol protection)",void 0,{args:t})};var iy=!1,ay=(()=>{if(typeof __dirname<"u")return __dirname;try{return(0,nt.dirname)((0,sy.fileURLToPath)(ST.url))}catch{return iy=!0,process.cwd()}})(),Du=T_()??(0,nt.resolve)(ay,"worker-service.cjs");function nT(){iy&&((0,Ks.existsSync)(Du)||y.error("SYSTEM","mcp-server: dirname resolution failed (both __dirname and import.meta.url are unavailable). Fell back to process.cwd() and the resolved WORKER_SCRIPT_PATH does not exist. This is the actual problem \u2014 the worker bundle is fine, but mcp-server cannot locate it. Worker auto-start will fail until the dirname-resolution path is fixed.",{workerScriptPath:Du,mcpServerDir:ay}))}var Q_={search:"/api/search",timeline:"/api/timeline"};async function Cu(t,e){y.debug("SYSTEM","\u2192 Worker API",void 0,{endpoint:t,params:e});let r=new URLSearchParams;for(let[o,s]of Object.entries(e))s!=null&&r.append(o,String(s));let n=`${t}?${r}`;try{let o=await Xn(n);if(!o.ok){let i=await o.text();throw new Error(`Worker API error (${o.status}): ${i}`)}let s=await o.json();return y.debug("SYSTEM","\u2190 Worker API success",void 0,{endpoint:t}),s}catch(o){return y.error("SYSTEM","\u2190 Worker API error",{endpoint:t},o instanceof Error?o:new Error(String(o))),{content:[{type:"text",text:`Error calling Worker API: ${o instanceof Error?o.message:String(o)}`}],isError:!0}}}async function oT(t,e){y.debug("SYSTEM","\u2192 Worker API text",void 0,{endpoint:t,params:e});let r=new URLSearchParams;for(let[o,s]of Object.entries(e))s!=null&&r.append(o,String(s));let n=`${t}?${r}`;try{let o=await Xn(n);if(!o.ok){let i=await o.text();throw new Error(`Worker API error (${o.status}): ${i}`)}let s=await o.text();return y.debug("SYSTEM","\u2190 Worker API text success",void 0,{endpoint:t}),{content:[{type:"text",text:s}]}}catch(o){return y.error("SYSTEM","\u2190 Worker API text error",{endpoint:t},o instanceof Error?o:new Error(String(o))),{content:[{type:"text",text:`Error calling Worker API: ${o instanceof Error?o.message:String(o)}`}],isError:!0}}}async function sT(t,e){let r=await Xn(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok){let o=await r.text();throw new Error(`Worker API error (${r.status}): ${o}`)}let n=await r.json();return y.debug("HTTP","Worker API success (POST)",void 0,{endpoint:t}),{content:[{type:"text",text:JSON.stringify(n,null,2)}]}}async function sr(t,e){y.debug("HTTP","Worker API request (POST)",void 0,{endpoint:t});try{return await sT(t,e)}catch(r){return y.error("HTTP","Worker API error (POST)",{endpoint:t},r instanceof Error?r:new Error(String(r))),{content:[{type:"text",text:`Error calling Worker API: ${r instanceof Error?r.message:String(r)}`}],isError:!0}}}async function iT(){try{return(await Xn("/api/health")).ok}catch(t){return y.debug("SYSTEM","Worker health check failed",{},t instanceof Error?t:new Error(String(t))),!1}}function aT(){if(Mu()!=="server")return null;let e=X_();return e?{...e,available:!0}:{runtime:"server",available:!1,reason:"server runtime is selected but configuration is incomplete (missing url, api key, or project id)"}}function oo(t){return Y_(t)?{content:[{type:"text",text:`Server error (${t.kind}${t.status?` ${t.status}`:""}): ${t.message}`}],isError:!0}:{content:[{type:"text",text:`Tool error: ${t instanceof Error?t.message:String(t)}`}],isError:!0}}function so(t){return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}function io(t){let e=aT();if(!e)throw new Je("transport",`${t} requires CLAUDE_MEM_RUNTIME=server. Current runtime is "worker"; use the existing search/timeline/get_observations tools for worker-mode memory access.`);if(!e.available)throw new Je("missing_api_key",`${t}: ${e.reason}`);return e}async function ey(t){try{let e=io("observation_add");if(typeof t?.content!="string"||t.content.trim().length===0)throw new Error('observation_add: "content" is required');let n={projectId:t.projectId&&t.projectId.trim().length>0?t.projectId:e.projectId,content:t.content,...t.serverSessionId!==void 0?{serverSessionId:t.serverSessionId}:{},...t.kind!==void 0?{kind:t.kind}:{},...t.metadata!==void 0?{metadata:t.metadata}:{}},o=await e.client.addObservation(n);return so(o)}catch(e){return oo(e)}}function Bs(t){return typeof t=="string"?Vs(t):null}async function cT(t){try{let e=io("observation_record_event");if(typeof t?.eventType!="string"||t.eventType.trim().length===0)throw new Error('observation_record_event: "eventType" is required');let n={projectId:t.projectId&&t.projectId.trim().length>0?t.projectId:e.projectId,sourceType:t.sourceType??"api",eventType:t.eventType,occurredAtEpoch:typeof t.occurredAtEpoch=="number"?t.occurredAtEpoch:Date.now(),...t.serverSessionId!==void 0?{serverSessionId:t.serverSessionId}:{},...t.contentSessionId!==void 0?{contentSessionId:t.contentSessionId}:{},...t.memorySessionId!==void 0?{memorySessionId:t.memorySessionId}:{},...t.platformSource!==void 0?{platformSource:Bs(t.platformSource)}:{},...t.payload!==void 0?{payload:t.payload}:{},...t.generate!==void 0?{generate:t.generate}:{}},o=await e.client.recordEvent(n);return so(o)}catch(e){return oo(e)}}async function ty(t){try{let e=io("observation_search");if(typeof t?.query!="string"||t.query.trim().length===0)throw new Error('observation_search: "query" is required');let n={projectId:t.projectId&&t.projectId.trim().length>0?t.projectId:e.projectId,query:t.query,...t.limit!==void 0?{limit:t.limit}:{},...t.platformSource!==void 0?{platformSource:Bs(t.platformSource)}:{}},o=await e.client.searchObservations(n);return so(o)}catch(e){return oo(e)}}async function ry(t){try{let e=io("observation_context");if(typeof t?.query!="string"||t.query.trim().length===0)throw new Error('observation_context: "query" is required');let n={projectId:t.projectId&&t.projectId.trim().length>0?t.projectId:e.projectId,query:t.query,...t.limit!==void 0?{limit:t.limit}:{},...t.platformSource!==void 0?{platformSource:Bs(t.platformSource)}:{}},o=await e.client.contextObservations(n);return so(o)}catch(e){return oo(e)}}function uT(t){return Array.isArray(t.projects)?t.projects.map(e=>typeof e=="string"?e.trim():"").filter(Boolean):typeof t.projects=="string"?t.projects.split(",").map(e=>e.trim()).filter(Boolean):typeof t.project=="string"&&t.project.trim().length>0?[t.project.trim()]:[]}async function lT(t){let e=uT(t);return e.length===0?{content:[{type:"text",text:'session_start_context: "project" or "projects" is required'}],isError:!0}:oT("/api/context/inject",{projects:e.join(","),...t.platformSource!==void 0?{platformSource:Bs(t.platformSource)}:{},...t.full!==void 0?{full:t.full}:{},...t.colors!==void 0?{colors:t.colors}:{}})}async function dT(t){try{let e=io("observation_generation_status"),r=(t?.jobId??t?.job_id??"").trim();if(!r)throw new Error('observation_generation_status: "jobId" is required');let n=await e.client.getJobStatus(r);return so(n)}catch(e){return oo(e)}}async function pT(){if(await iT())return!0;y.warn("SYSTEM","Worker not available, attempting auto-start for MCP client"),nT();try{let t=xu(),e=await R_(t,Du);return e==="dead"&&y.error("SYSTEM","Worker auto-start failed \u2014 MCP tools that require the worker (search, timeline, get_observations) will fail until the worker is running. Check earlier log lines for the specific failure reason (Bun not found, missing worker bundle, port conflict, etc.)."),e!=="dead"}catch(t){return y.error("SYSTEM","Worker auto-start threw \u2014 MCP tools that require the worker (search, timeline, get_observations) will fail until the worker is running.",void 0,t instanceof Error?t:new Error(String(t))),!1}}var cy=[{name:"__IMPORTANT",description:`3-LAYER WORKFLOW (ALWAYS FOLLOW):
223
+ `)}var Nu=require("node:fs/promises"),Ks=require("node:fs"),nt=require("node:path"),oy=require("node:os"),sy=require("node:url");var B_="claude";function XP(t){return t.trim().toLowerCase().replace(/\s+/g,"-")}function Vs(t){if(!t)return B_;let e=XP(t);return e?e==="transcript"||e.includes("codex")?"codex":e.includes("cursor")?"cursor":e.includes("claude")?"claude":e:B_}var QP=Et(ue.API_REQUEST),Je=class extends Error{kind;status;cause;constructor(e,r,n={}){super(r),this.name="ServerClientError",this.kind=e,this.status=n.status??null,this.cause=n.cause}isFallbackEligible(){return this.kind==="transport"||this.kind==="timeout"||this.kind==="missing_api_key"||this.kind==="http_error"&&(this.status!==null&&this.status>=500||this.status===429)}},Gs=class{baseUrl;apiKey;timeoutMs;constructor(e){this.baseUrl=eT(e.serverBaseUrl),this.apiKey=e.apiKey,this.timeoutMs=e.timeoutMs??QP}async startSession(e){let r=this.buildStartSessionPayload(e);return this.request("POST","/v1/sessions/start",r)}async recordEvent(e){let r=this.buildEventPayload(e),n=e.generate===!1?"/v1/events?generate=false":"/v1/events";return this.request("POST",n,r)}async endSession(e){if(!e.sessionId)throw new Je("invalid_response","sessionId is required for endSession");return this.request("POST",`/v1/sessions/${encodeURIComponent(e.sessionId)}/end`,{})}async addObservation(e){return this.request("POST","/v1/memories",this.buildAddObservationPayload(e))}async searchObservations(e){return this.request("POST","/v1/search",this.buildSearchPayload(e))}async contextObservations(e){return this.request("POST","/v1/context",this.buildSearchPayload(e))}async getJobStatus(e){if(!e)throw new Je("invalid_response","jobId is required for getJobStatus");return this.request("GET",`/v1/jobs/${encodeURIComponent(e)}`)}buildAddObservationPayload(e){let r=e.content,n=e.kind??"manual",o=typeof e.metadata?.title=="string"?e.metadata.title:void 0;return{projectId:e.projectId,kind:n,type:n,narrative:r,...o?{title:o}:{},...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}buildSearchPayload(e){return{projectId:e.projectId,query:e.query,...e.limit!==void 0?{limit:e.limit}:{},...e.platformSource!==void 0?{platformSource:Au(e.platformSource)}:{}}}buildStartSessionPayload(e){return{projectId:e.projectId,...e.externalSessionId!==void 0?{externalSessionId:e.externalSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.agentId!==void 0?{agentId:e.agentId}:{},...e.agentType!==void 0?{agentType:e.agentType}:{},...e.platformSource!==void 0?{platformSource:Au(e.platformSource)}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}buildEventPayload(e){return{projectId:e.projectId,sourceType:e.sourceType,eventType:e.eventType,occurredAtEpoch:e.occurredAtEpoch,...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.memorySessionId!==void 0?{memorySessionId:e.memorySessionId}:{},...e.platformSource!==void 0?{platformSource:Au(e.platformSource)}:{},...e.payload!==void 0?{payload:e.payload}:{}}}async request(e,r,n){if(!this.apiKey||!this.apiKey.trim())throw new Je("missing_api_key","Server API key is not configured (CLAUDE_MEM_SERVER_API_KEY).");let o=`${this.baseUrl}${r}`,s={method:e,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}};n!==void 0&&(s.body=JSON.stringify(n));let i;try{i=await wu(o,s,this.timeoutMs)}catch(c){let u=c instanceof Error?c.message:String(c),l=/timed out|timeout/i.test(u);throw new Je(l?"timeout":"transport",`Server ${e} ${r} failed: ${u}`,{cause:c})}if(!i.ok){let c=await i.text().catch(()=>"");throw new Je("http_error",`Server ${e} ${r} returned ${i.status}: ${tT(c,200)}`,{status:i.status})}let a=await i.text();if(!a||a.length===0)return{};try{return JSON.parse(a)}catch(c){throw new Je("invalid_response",`Server ${e} ${r} returned non-JSON response`,{cause:c})}}};function Y_(t){return t instanceof Je}function eT(t){return t.replace(/\/+$/,"")}function Au(t){return typeof t=="string"?Vs(t):null}function tT(t,e){return t.length<=e?t:`${t.slice(0,e)}\u2026`}function Mu(){let e=(Ms().CLAUDE_MEM_RUNTIME??"worker").trim().toLowerCase();return e==="server"||e==="server-beta"?"server":"worker"}function X_(){let t=Ms(),e=(...i)=>{for(let a of i){let c=(a??"").trim();if(c.length>0)return c}return""},r=e(t.CLAUDE_MEM_SERVER_URL,t.CLAUDE_MEM_SERVER_BETA_URL),n=e(t.CLAUDE_MEM_SERVER_API_KEY,t.CLAUDE_MEM_SERVER_BETA_API_KEY),o=e(t.CLAUDE_MEM_SERVER_PROJECT_ID,t.CLAUDE_MEM_SERVER_BETA_PROJECT_ID);if(!r)return y.warn("HOOK","[server-fallback] reason=missing_base_url"),null;if(!n)return y.warn("HOOK","[server-fallback] reason=missing_api_key"),null;if(!o)return y.warn("HOOK","[server-fallback] reason=missing_project_id"),null;let s={serverBaseUrl:r,apiKey:n};return{runtime:"server",client:new Gs(s),projectId:o,serverBaseUrl:r}}var ST={},rT="1.3.1";console.log=(...t)=>{y.error("CONSOLE","Intercepted console output (MCP protocol protection)",void 0,{args:t})};var iy=!1,ay=(()=>{if(typeof __dirname<"u")return __dirname;try{return(0,nt.dirname)((0,sy.fileURLToPath)(ST.url))}catch{return iy=!0,process.cwd()}})(),Du=T_()??(0,nt.resolve)(ay,"worker-service.cjs");function nT(){iy&&((0,Ks.existsSync)(Du)||y.error("SYSTEM","mcp-server: dirname resolution failed (both __dirname and import.meta.url are unavailable). Fell back to process.cwd() and the resolved WORKER_SCRIPT_PATH does not exist. This is the actual problem \u2014 the worker bundle is fine, but mcp-server cannot locate it. Worker auto-start will fail until the dirname-resolution path is fixed.",{workerScriptPath:Du,mcpServerDir:ay}))}var Q_={search:"/api/search",timeline:"/api/timeline"};async function Cu(t,e){y.debug("SYSTEM","\u2192 Worker API",void 0,{endpoint:t,params:e});let r=new URLSearchParams;for(let[o,s]of Object.entries(e))s!=null&&r.append(o,String(s));let n=`${t}?${r}`;try{let o=await Xn(n);if(!o.ok){let i=await o.text();throw new Error(`Worker API error (${o.status}): ${i}`)}let s=await o.json();return y.debug("SYSTEM","\u2190 Worker API success",void 0,{endpoint:t}),s}catch(o){return y.error("SYSTEM","\u2190 Worker API error",{endpoint:t},o instanceof Error?o:new Error(String(o))),{content:[{type:"text",text:`Error calling Worker API: ${o instanceof Error?o.message:String(o)}`}],isError:!0}}}async function oT(t,e){y.debug("SYSTEM","\u2192 Worker API text",void 0,{endpoint:t,params:e});let r=new URLSearchParams;for(let[o,s]of Object.entries(e))s!=null&&r.append(o,String(s));let n=`${t}?${r}`;try{let o=await Xn(n);if(!o.ok){let i=await o.text();throw new Error(`Worker API error (${o.status}): ${i}`)}let s=await o.text();return y.debug("SYSTEM","\u2190 Worker API text success",void 0,{endpoint:t}),{content:[{type:"text",text:s}]}}catch(o){return y.error("SYSTEM","\u2190 Worker API text error",{endpoint:t},o instanceof Error?o:new Error(String(o))),{content:[{type:"text",text:`Error calling Worker API: ${o instanceof Error?o.message:String(o)}`}],isError:!0}}}async function sT(t,e){let r=await Xn(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok){let o=await r.text();throw new Error(`Worker API error (${r.status}): ${o}`)}let n=await r.json();return y.debug("HTTP","Worker API success (POST)",void 0,{endpoint:t}),{content:[{type:"text",text:JSON.stringify(n,null,2)}]}}async function sr(t,e){y.debug("HTTP","Worker API request (POST)",void 0,{endpoint:t});try{return await sT(t,e)}catch(r){return y.error("HTTP","Worker API error (POST)",{endpoint:t},r instanceof Error?r:new Error(String(r))),{content:[{type:"text",text:`Error calling Worker API: ${r instanceof Error?r.message:String(r)}`}],isError:!0}}}async function iT(){try{return(await Xn("/api/health")).ok}catch(t){return y.debug("SYSTEM","Worker health check failed",{},t instanceof Error?t:new Error(String(t))),!1}}function aT(){if(Mu()!=="server")return null;let e=X_();return e?{...e,available:!0}:{runtime:"server",available:!1,reason:"server runtime is selected but configuration is incomplete (missing url, api key, or project id)"}}function oo(t){return Y_(t)?{content:[{type:"text",text:`Server error (${t.kind}${t.status?` ${t.status}`:""}): ${t.message}`}],isError:!0}:{content:[{type:"text",text:`Tool error: ${t instanceof Error?t.message:String(t)}`}],isError:!0}}function so(t){return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}function io(t){let e=aT();if(!e)throw new Je("transport",`${t} requires CLAUDE_MEM_RUNTIME=server. Current runtime is "worker"; use the existing search/timeline/get_observations tools for worker-mode memory access.`);if(!e.available)throw new Je("missing_api_key",`${t}: ${e.reason}`);return e}async function ey(t){try{let e=io("observation_add");if(typeof t?.content!="string"||t.content.trim().length===0)throw new Error('observation_add: "content" is required');let n={projectId:t.projectId&&t.projectId.trim().length>0?t.projectId:e.projectId,content:t.content,...t.serverSessionId!==void 0?{serverSessionId:t.serverSessionId}:{},...t.kind!==void 0?{kind:t.kind}:{},...t.metadata!==void 0?{metadata:t.metadata}:{}},o=await e.client.addObservation(n);return so(o)}catch(e){return oo(e)}}function Bs(t){return typeof t=="string"?Vs(t):null}async function cT(t){try{let e=io("observation_record_event");if(typeof t?.eventType!="string"||t.eventType.trim().length===0)throw new Error('observation_record_event: "eventType" is required');let n={projectId:t.projectId&&t.projectId.trim().length>0?t.projectId:e.projectId,sourceType:t.sourceType??"api",eventType:t.eventType,occurredAtEpoch:typeof t.occurredAtEpoch=="number"?t.occurredAtEpoch:Date.now(),...t.serverSessionId!==void 0?{serverSessionId:t.serverSessionId}:{},...t.contentSessionId!==void 0?{contentSessionId:t.contentSessionId}:{},...t.memorySessionId!==void 0?{memorySessionId:t.memorySessionId}:{},...t.platformSource!==void 0?{platformSource:Bs(t.platformSource)}:{},...t.payload!==void 0?{payload:t.payload}:{},...t.generate!==void 0?{generate:t.generate}:{}},o=await e.client.recordEvent(n);return so(o)}catch(e){return oo(e)}}async function ty(t){try{let e=io("observation_search");if(typeof t?.query!="string"||t.query.trim().length===0)throw new Error('observation_search: "query" is required');let n={projectId:t.projectId&&t.projectId.trim().length>0?t.projectId:e.projectId,query:t.query,...t.limit!==void 0?{limit:t.limit}:{},...t.platformSource!==void 0?{platformSource:Bs(t.platformSource)}:{}},o=await e.client.searchObservations(n);return so(o)}catch(e){return oo(e)}}async function ry(t){try{let e=io("observation_context");if(typeof t?.query!="string"||t.query.trim().length===0)throw new Error('observation_context: "query" is required');let n={projectId:t.projectId&&t.projectId.trim().length>0?t.projectId:e.projectId,query:t.query,...t.limit!==void 0?{limit:t.limit}:{},...t.platformSource!==void 0?{platformSource:Bs(t.platformSource)}:{}},o=await e.client.contextObservations(n);return so(o)}catch(e){return oo(e)}}function uT(t){return Array.isArray(t.projects)?t.projects.map(e=>typeof e=="string"?e.trim():"").filter(Boolean):typeof t.projects=="string"?t.projects.split(",").map(e=>e.trim()).filter(Boolean):typeof t.project=="string"&&t.project.trim().length>0?[t.project.trim()]:[]}async function lT(t){let e=uT(t);return e.length===0?{content:[{type:"text",text:'session_start_context: "project" or "projects" is required'}],isError:!0}:oT("/api/context/inject",{projects:e.join(","),...t.platformSource!==void 0?{platformSource:Bs(t.platformSource)}:{},...t.full!==void 0?{full:t.full}:{},...t.colors!==void 0?{colors:t.colors}:{}})}async function dT(t){try{let e=io("observation_generation_status"),r=(t?.jobId??t?.job_id??"").trim();if(!r)throw new Error('observation_generation_status: "jobId" is required');let n=await e.client.getJobStatus(r);return so(n)}catch(e){return oo(e)}}async function pT(){if(await iT())return!0;y.warn("SYSTEM","Worker not available, attempting auto-start for MCP client"),nT();try{let t=xu(),e=await R_(t,Du);return e==="dead"&&y.error("SYSTEM","Worker auto-start failed \u2014 MCP tools that require the worker (search, timeline, get_observations) will fail until the worker is running. Check earlier log lines for the specific failure reason (Bun not found, missing worker bundle, port conflict, etc.)."),e!=="dead"}catch(t){return y.error("SYSTEM","Worker auto-start threw \u2014 MCP tools that require the worker (search, timeline, get_observations) will fail until the worker is running.",void 0,t instanceof Error?t:new Error(String(t))),!1}}var cy=[{name:"__IMPORTANT",description:`3-LAYER WORKFLOW (ALWAYS FOLLOW):
224
224
  1. search(query) \u2192 Get index with IDs (~50-100 tokens/result)
225
225
  2. timeline(anchor=ID) \u2192 Get context around interesting results
226
226
  3. get_observations([IDs]) \u2192 Fetch full details ONLY for filtered IDs