claude-mem 13.12.2 → 13.12.3
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.
- package/.codex-plugin/plugin.json +1 -1
- package/dist/npx-cli/index.js +12 -12
- package/openclaw/openclaw.plugin.json +1 -1
- package/package.json +1 -1
- package/plugin/.claude-plugin/plugin.json +1 -1
- package/plugin/.codex-plugin/plugin.json +1 -1
- package/plugin/package.json +1 -1
- package/plugin/scripts/mcp-server.cjs +2 -2
- package/plugin/scripts/server-service.cjs +2 -2
- package/plugin/scripts/transcript-watcher.cjs +15 -15
- package/plugin/scripts/worker-service.cjs +218 -218
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"name": "Claude-Mem (Persistent Memory)",
|
|
4
4
|
"description": "OpenClaw plugin for Claude-Mem. Records observations from embedded runner sessions and streams them to messaging channels.",
|
|
5
5
|
"kind": "memory",
|
|
6
|
-
"version": "13.12.
|
|
6
|
+
"version": "13.12.3",
|
|
7
7
|
"license": "Apache-2.0",
|
|
8
8
|
"author": "thedotmack",
|
|
9
9
|
"homepage": "https://claude-mem.ai",
|
package/package.json
CHANGED
package/plugin/package.json
CHANGED
|
@@ -82,7 +82,7 @@ ${m.stack??""}
|
|
|
82
82
|
|
|
83
83
|
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 Hi(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:nn(e,"input",t.processors),output:nn(e,"output",t.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function we(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 we(n.element,r);if(n.type==="set")return we(n.valueType,r);if(n.type==="lazy")return we(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 we(n.innerType,r);if(n.type==="intersection")return we(n.left,r)||we(n.right,r);if(n.type==="record"||n.type==="map")return we(n.keyType,r)||we(n.valueType,r);if(n.type==="pipe")return t._zod.traits.has("$ZodCodec")?!0:we(n.in,r)||we(n.out,r);if(n.type==="object"){for(let o in n.shape)if(we(n.shape[o],r))return!0;return!1}if(n.type==="union"){for(let o of n.options)if(we(o,r))return!0;return!1}if(n.type==="tuple"){for(let o of n.items)if(we(o,r))return!0;return!!(n.rest&&we(n.rest,r))}return!1}var Zp=(t,e={})=>r=>{let n=Zi({...r,processors:e});return ie(t,n),Fi(n,t),Hi(n,t)},nn=(t,e,r={})=>n=>{let{libraryOptions:o,target:s}=n??{},i=Zi({...o??{},target:s,io:e,processors:r});return ie(t,i),Fi(i,t),Hi(i,t)};var oS={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Fp=(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=oS[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}))])}},Hp=(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)},Wp=(t,e,r,n)=>{r.type="boolean"};var Vp=(t,e,r,n)=>{e.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"};var Kp=(t,e,r,n)=>{r.not={}};var Jp=(t,e,r,n)=>{};var Bp=(t,e,r,n)=>{let o=t._zod.def,s=Kr(o.entries);s.every(i=>typeof i=="number")&&(r.type="number"),s.every(i=>typeof i=="string")&&(r.type="string"),r.enum=s},Yp=(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 Gp=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")};var Xp=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")};var Qp=(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"]})},ef=(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)},tf=(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},rf=(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 nf=(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)}},of=(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"}]},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},af=(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))},cf=(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)))},uf=(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},lf=(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},df=(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 Wi=(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 At(t,e){return mr(t)?Xr(t,e):t.safeParse(e)}function Ro(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 pf(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 sn={};Fu(sn,{ZodISODate:()=>mf,ZodISODateTime:()=>ff,ZodISODuration:()=>gf,ZodISOTime:()=>hf,date:()=>Ki,datetime:()=>Vi,duration:()=>Bi,time:()=>Ji});var ff=_("ZodISODateTime",(t,e)=>{bd.init(t,e),re.init(t,e)});function Vi(t){return Tp(ff,t)}var mf=_("ZodISODate",(t,e)=>{Ed.init(t,e),re.init(t,e)});function Ki(t){return Rp(mf,t)}var hf=_("ZodISOTime",(t,e)=>{wd.init(t,e),re.init(t,e)});function Ji(t){return zp(hf,t)}var gf=_("ZodISODuration",(t,e)=>{kd.init(t,e),re.init(t,e)});function Bi(t){return Ip(gf,t)}var fS=(t,e)=>{ho.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>ol(t,r)},flatten:{value:r=>nl(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 Me=_("ZodError",fS,{Parent:Error});var _f=go(Me),yf=_o(Me),Sf=Gr(Me),vf=Qr(Me),bf=sl(Me),Ef=il(Me),wf=al(Me),kf=cl(Me),xf=ul(Me),$f=ll(Me),Pf=dl(Me),Tf=pl(Me);var Rf=new WeakMap;function an(t,e,r){let n=Object.getPrototypeOf(t),o=Rf.get(n);if(o||(o=new Set,Rf.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=_("ZodType",(t,e)=>(G.init(t,e),Object.assign(t["~standard"],{jsonSchema:{input:nn(t,"input"),output:nn(t,"output")}}),t.toJSONSchema=Zp(t,{}),t.def=e,t.type=e.type,Object.defineProperty(t,"_def",{value:e}),t.parse=(r,n)=>_f(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>Sf(t,r,n),t.parseAsync=async(r,n)=>yf(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>vf(t,r,n),t.spa=t.safeParseAsync,t.encode=(r,n)=>bf(t,r,n),t.decode=(r,n)=>Ef(t,r,n),t.encodeAsync=async(r,n)=>wf(t,r,n),t.decodeAsync=async(r,n)=>kf(t,r,n),t.safeEncode=(r,n)=>xf(t,r,n),t.safeDecode=(r,n)=>$f(t,r,n),t.safeEncodeAsync=async(r,n)=>Pf(t,r,n),t.safeDecodeAsync=async(r,n)=>Tf(t,r,n),an(t,"ZodType",{check(...r){let n=this.def;return this.clone(L.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 Qe(this,r,n)},brand(){return this},register(r,n){return r.add(this,n),this},refine(r,n){return this.check(nv(r,n))},superRefine(r,n){return this.check(ov(r,n))},overwrite(r){return this.check(Ot(r))},optional(){return oe(this)},exactOptional(){return WS(this)},nullable(){return Af(this)},nullish(){return oe(Af(this))},nonoptional(r){return GS(this,r)},array(){return N(this)},or(r){return Q([this,r])},and(r){return Io(this,r)},transform(r){return Cf(this,Uf(r))},default(r){return JS(this,r)},prefault(r){return YS(this,r)},catch(r){return QS(this,r)},pipe(r){return Cf(this,r)},readonly(){return rv(this)},describe(r){let n=this.clone();return Kt.add(n,{description:r}),n},meta(...r){if(r.length===0)return Kt.get(this);let n=this.clone();return Kt.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 Kt.get(t)?.description},configurable:!0}),t)),Mf=_("_ZodString",(t,e)=>{wo.init(t,e),se.init(t,e),t._zod.processJSONSchema=(n,o,s)=>Fp(t,n,o,s);let r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,an(t,"_ZodString",{regex(...n){return this.check(Ii(...n))},includes(...n){return this.check(Ci(...n))},startsWith(...n){return this.check(Mi(...n))},endsWith(...n){return this.check(Di(...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(Oi(n))},uppercase(n){return this.check(Ai(n))},trim(){return this.check(ji())},normalize(...n){return this.check(Ni(...n))},toLowerCase(){return this.check(Li())},toUpperCase(){return this.check(Ui())},slugify(){return this.check(qi())}})}),hS=_("ZodString",(t,e)=>{wo.init(t,e),Mf.init(t,e),t.email=r=>t.check(ap(gS,r)),t.url=r=>t.check(pp(_S,r)),t.jwt=r=>t.check(Pp(OS,r)),t.emoji=r=>t.check(fp(yS,r)),t.guid=r=>t.check(zi(zf,r)),t.uuid=r=>t.check(cp(zo,r)),t.uuidv4=r=>t.check(up(zo,r)),t.uuidv6=r=>t.check(lp(zo,r)),t.uuidv7=r=>t.check(dp(zo,r)),t.nanoid=r=>t.check(mp(SS,r)),t.guid=r=>t.check(zi(zf,r)),t.cuid=r=>t.check(hp(vS,r)),t.cuid2=r=>t.check(gp(bS,r)),t.ulid=r=>t.check(_p(ES,r)),t.base64=r=>t.check(kp(RS,r)),t.base64url=r=>t.check(xp(zS,r)),t.xid=r=>t.check(yp(wS,r)),t.ksuid=r=>t.check(Sp(kS,r)),t.ipv4=r=>t.check(vp(xS,r)),t.ipv6=r=>t.check(bp($S,r)),t.cidrv4=r=>t.check(Ep(PS,r)),t.cidrv6=r=>t.check(wp(TS,r)),t.e164=r=>t.check($p(IS,r)),t.datetime=r=>t.check(Vi(r)),t.date=r=>t.check(Ki(r)),t.time=r=>t.check(Ji(r)),t.duration=r=>t.check(Bi(r))});function h(t){return ip(hS,t)}var re=_("ZodStringFormat",(t,e)=>{X.init(t,e),Mf.init(t,e)}),gS=_("ZodEmail",(t,e)=>{pd.init(t,e),re.init(t,e)});var zf=_("ZodGUID",(t,e)=>{ld.init(t,e),re.init(t,e)});var zo=_("ZodUUID",(t,e)=>{dd.init(t,e),re.init(t,e)});var _S=_("ZodURL",(t,e)=>{fd.init(t,e),re.init(t,e)});var yS=_("ZodEmoji",(t,e)=>{md.init(t,e),re.init(t,e)});var SS=_("ZodNanoID",(t,e)=>{hd.init(t,e),re.init(t,e)});var vS=_("ZodCUID",(t,e)=>{gd.init(t,e),re.init(t,e)});var bS=_("ZodCUID2",(t,e)=>{_d.init(t,e),re.init(t,e)});var ES=_("ZodULID",(t,e)=>{yd.init(t,e),re.init(t,e)});var wS=_("ZodXID",(t,e)=>{Sd.init(t,e),re.init(t,e)});var kS=_("ZodKSUID",(t,e)=>{vd.init(t,e),re.init(t,e)});var xS=_("ZodIPv4",(t,e)=>{xd.init(t,e),re.init(t,e)});var $S=_("ZodIPv6",(t,e)=>{$d.init(t,e),re.init(t,e)});var PS=_("ZodCIDRv4",(t,e)=>{Pd.init(t,e),re.init(t,e)});var TS=_("ZodCIDRv6",(t,e)=>{Td.init(t,e),re.init(t,e)});var RS=_("ZodBase64",(t,e)=>{zd.init(t,e),re.init(t,e)});var zS=_("ZodBase64URL",(t,e)=>{Id.init(t,e),re.init(t,e)});var IS=_("ZodE164",(t,e)=>{Od.init(t,e),re.init(t,e)});var OS=_("ZodJWT",(t,e)=>{Ad.init(t,e),re.init(t,e)});var Df=_("ZodNumber",(t,e)=>{xi.init(t,e),se.init(t,e),t._zod.processJSONSchema=(n,o,s)=>Hp(t,n,o,s),an(t,"ZodNumber",{gt(n,o){return this.check(xo(n,o))},gte(n,o){return this.check(rn(n,o))},min(n,o){return this.check(rn(n,o))},lt(n,o){return this.check(ko(n,o))},lte(n,o){return this.check(tn(n,o))},max(n,o){return this.check(tn(n,o))},int(n){return this.check(If(n))},safe(n){return this.check(If(n))},positive(n){return this.check(xo(0,n))},nonnegative(n){return this.check(rn(0,n))},negative(n){return this.check(ko(0,n))},nonpositive(n){return this.check(tn(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 Op(Df,t)}var AS=_("ZodNumberFormat",(t,e)=>{Cd.init(t,e),Df.init(t,e)});function If(t){return Ap(AS,t)}var CS=_("ZodBoolean",(t,e)=>{Md.init(t,e),se.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Wp(t,r,n,o)});function de(t){return Cp(CS,t)}var MS=_("ZodNull",(t,e)=>{Dd.init(t,e),se.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Vp(t,r,n,o)});function Nf(t){return Mp(MS,t)}var DS=_("ZodUnknown",(t,e)=>{Nd.init(t,e),se.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Jp(t,r,n,o)});function ne(){return Dp(DS)}var NS=_("ZodNever",(t,e)=>{jd.init(t,e),se.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Kp(t,r,n,o)});function jS(t){return Np(NS,t)}var LS=_("ZodArray",(t,e)=>{Ld.init(t,e),se.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Qp(t,r,n,o),t.element=e.element,an(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 N(t,e){return jp(LS,t,e)}var jf=_("ZodObject",(t,e)=>{Zd.init(t,e),se.init(t,e),t._zod.processJSONSchema=(r,n,o)=>ef(t,r,n,o),L.defineLazy(t,"shape",()=>e.shape),an(t,"ZodObject",{keyof(){return Te(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:jS()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(r){return L.extend(this,r)},safeExtend(r){return L.safeExtend(this,r)},merge(r){return L.merge(this,r)},pick(r){return L.pick(this,r)},omit(r){return L.omit(this,r)},partial(...r){return L.partial(qf,this,r[0])},required(...r){return L.required(Zf,this,r[0])}})});function w(t,e){let r={type:"object",shape:t??{},...L.normalizeParams(e)};return new jf(r)}function ke(t,e){return new jf({type:"object",shape:t,catchall:ne(),...L.normalizeParams(e)})}var Lf=_("ZodUnion",(t,e)=>{$i.init(t,e),se.init(t,e),t._zod.processJSONSchema=(r,n,o)=>tf(t,r,n,o),t.options=e.options});function Q(t,e){return new Lf({type:"union",options:t,...L.normalizeParams(e)})}var US=_("ZodDiscriminatedUnion",(t,e)=>{Lf.init(t,e),Fd.init(t,e)});function Gi(t,e,r){return new US({type:"union",options:e,discriminator:t,...L.normalizeParams(r)})}var qS=_("ZodIntersection",(t,e)=>{Hd.init(t,e),se.init(t,e),t._zod.processJSONSchema=(r,n,o)=>rf(t,r,n,o)});function Io(t,e){return new qS({type:"intersection",left:t,right:e})}var Of=_("ZodRecord",(t,e)=>{Wd.init(t,e),se.init(t,e),t._zod.processJSONSchema=(r,n,o)=>nf(t,r,n,o),t.keyType=e.keyType,t.valueType=e.valueType});function Y(t,e,r){return!e||!e._zod?new Of({type:"record",keyType:h(),valueType:t,...L.normalizeParams(e)}):new Of({type:"record",keyType:t,valueType:e,...L.normalizeParams(r)})}var Yi=_("ZodEnum",(t,e)=>{Vd.init(t,e),se.init(t,e),t._zod.processJSONSchema=(n,o,s)=>Bp(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 Yi({...e,checks:[],...L.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 Yi({...e,checks:[],...L.normalizeParams(o),entries:s})}});function Te(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new Yi({type:"enum",entries:r,...L.normalizeParams(e)})}var ZS=_("ZodLiteral",(t,e)=>{Kd.init(t,e),se.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Yp(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 ZS({type:"literal",values:Array.isArray(t)?t:[t],...L.normalizeParams(e)})}var FS=_("ZodTransform",(t,e)=>{Jd.init(t,e),se.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Xp(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(L.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(L.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 Uf(t){return new FS({type:"transform",transform:t})}var qf=_("ZodOptional",(t,e)=>{Pi.init(t,e),se.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Wi(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function oe(t){return new qf({type:"optional",innerType:t})}var HS=_("ZodExactOptional",(t,e)=>{Bd.init(t,e),se.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Wi(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function WS(t){return new HS({type:"optional",innerType:t})}var VS=_("ZodNullable",(t,e)=>{Yd.init(t,e),se.init(t,e),t._zod.processJSONSchema=(r,n,o)=>of(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function Af(t){return new VS({type:"nullable",innerType:t})}var KS=_("ZodDefault",(t,e)=>{Gd.init(t,e),se.init(t,e),t._zod.processJSONSchema=(r,n,o)=>af(t,r,n,o),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function JS(t,e){return new KS({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():L.shallowClone(e)}})}var BS=_("ZodPrefault",(t,e)=>{Xd.init(t,e),se.init(t,e),t._zod.processJSONSchema=(r,n,o)=>cf(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function YS(t,e){return new BS({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():L.shallowClone(e)}})}var Zf=_("ZodNonOptional",(t,e)=>{Qd.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 GS(t,e){return new Zf({type:"nonoptional",innerType:t,...L.normalizeParams(e)})}var XS=_("ZodCatch",(t,e)=>{ep.init(t,e),se.init(t,e),t._zod.processJSONSchema=(r,n,o)=>uf(t,r,n,o),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function QS(t,e){return new XS({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var Ff=_("ZodPipe",(t,e)=>{Ti.init(t,e),se.init(t,e),t._zod.processJSONSchema=(r,n,o)=>lf(t,r,n,o),t.in=e.in,t.out=e.out});function Cf(t,e){return new Ff({type:"pipe",in:t,out:e})}var ev=_("ZodPreprocess",(t,e)=>{Ff.init(t,e),tp.init(t,e)}),tv=_("ZodReadonly",(t,e)=>{rp.init(t,e),se.init(t,e),t._zod.processJSONSchema=(r,n,o)=>df(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function rv(t){return new tv({type:"readonly",innerType:t})}var Hf=_("ZodCustom",(t,e)=>{np.init(t,e),se.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Gp(t,r,n,o)});function Wf(t,e){return Lp(Hf,t??(()=>!0),e)}function nv(t,e={}){return Up(Hf,t,e)}function ov(t,e){return qp(t,e)}function Xi(t,e){return new ev({type:"pipe",in:Uf(t),out:e})}Ce(op());var ea="2025-11-25";var Vf=[ea,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Ct="io.modelcontextprotocol/related-task",Ao="2.0",le=Wf(t=>t!==null&&(typeof t=="object"||typeof t=="function")),Kf=Q([h(),W().int()]),Jf=h(),eI=ke({ttl:W().optional(),pollInterval:W().optional()}),sv=w({ttl:W().optional()}),iv=w({taskId:h()}),ta=ke({progressToken:Kf.optional(),[Ct]:iv.optional()}),De=w({_meta:ta.optional()}),cn=De.extend({task:sv.optional()}),Bf=t=>cn.safeParse(t).success,fe=w({method:h(),params:De.loose().optional()}),Ue=w({_meta:ta.optional()}),qe=w({method:h(),params:Ue.loose().optional()}),me=ke({_meta:ta.optional()}),Co=Q([h(),W().int()]),Yf=w({jsonrpc:P(Ao),id:Co,...fe.shape}).strict(),ra=t=>Yf.safeParse(t).success,Gf=w({jsonrpc:P(Ao),...qe.shape}).strict(),Xf=t=>Gf.safeParse(t).success,na=w({jsonrpc:P(Ao),id:Co,result:me}).strict(),un=t=>na.safeParse(t).success;var D;(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"})(D||(D={}));var oa=w({jsonrpc:P(Ao),id:Co.optional(),error:w({code:W().int(),message:h(),data:ne().optional()})}).strict();var Qf=t=>oa.safeParse(t).success;var em=Q([Yf,Gf,na,oa]),tI=Q([na,oa]),Mo=me.strict(),av=Ue.extend({requestId:Co.optional(),reason:h().optional()}),Do=qe.extend({method:P("notifications/cancelled"),params:av}),cv=w({src:h(),mimeType:h().optional(),sizes:N(h()).optional(),theme:Te(["light","dark"]).optional()}),ln=w({icons:N(cv).optional()}),hr=w({name:h(),title:h().optional()}),tm=hr.extend({...hr.shape,...ln.shape,version:h(),websiteUrl:h().optional(),description:h().optional()}),uv=Io(w({applyDefaults:de().optional()}),Y(h(),ne())),lv=Xi(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,Io(w({form:uv.optional(),url:le.optional()}),Y(h(),ne()).optional())),dv=ke({list:le.optional(),cancel:le.optional(),requests:ke({sampling:ke({createMessage:le.optional()}).optional(),elicitation:ke({create:le.optional()}).optional()}).optional()}),pv=ke({list:le.optional(),cancel:le.optional(),requests:ke({tools:ke({call:le.optional()}).optional()}).optional()}),fv=w({experimental:Y(h(),le).optional(),sampling:w({context:le.optional(),tools:le.optional()}).optional(),elicitation:lv.optional(),roots:w({listChanged:de().optional()}).optional(),tasks:dv.optional(),extensions:Y(h(),le).optional()}),mv=De.extend({protocolVersion:h(),capabilities:fv,clientInfo:tm}),sa=fe.extend({method:P("initialize"),params:mv});var hv=w({experimental:Y(h(),le).optional(),logging:le.optional(),completions:le.optional(),prompts:w({listChanged:de().optional()}).optional(),resources:w({subscribe:de().optional(),listChanged:de().optional()}).optional(),tools:w({listChanged:de().optional()}).optional(),tasks:pv.optional(),extensions:Y(h(),le).optional()}),gv=me.extend({protocolVersion:h(),capabilities:hv,serverInfo:tm,instructions:h().optional()}),ia=qe.extend({method:P("notifications/initialized"),params:Ue.optional()});var No=fe.extend({method:P("ping"),params:De.optional()}),_v=w({progress:W(),total:oe(W()),message:oe(h())}),yv=w({...Ue.shape,..._v.shape,progressToken:Kf}),jo=qe.extend({method:P("notifications/progress"),params:yv}),Sv=De.extend({cursor:Jf.optional()}),dn=fe.extend({params:Sv.optional()}),pn=me.extend({nextCursor:Jf.optional()}),vv=Te(["working","input_required","completed","failed","cancelled"]),fn=w({taskId:h(),status:vv,ttl:Q([W(),Nf()]),createdAt:h(),lastUpdatedAt:h(),pollInterval:oe(W()),statusMessage:oe(h())}),gr=me.extend({task:fn}),bv=Ue.merge(fn),mn=qe.extend({method:P("notifications/tasks/status"),params:bv}),Lo=fe.extend({method:P("tasks/get"),params:De.extend({taskId:h()})}),Uo=me.merge(fn),qo=fe.extend({method:P("tasks/result"),params:De.extend({taskId:h()})}),rI=me.loose(),Zo=dn.extend({method:P("tasks/list")}),Fo=pn.extend({tasks:N(fn)}),Ho=fe.extend({method:P("tasks/cancel"),params:De.extend({taskId:h()})}),rm=me.merge(fn),nm=w({uri:h(),mimeType:oe(h()),_meta:Y(h(),ne()).optional()}),om=nm.extend({text:h()}),aa=h().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),sm=nm.extend({blob:aa}),hn=Te(["user","assistant"]),_r=w({audience:N(hn).optional(),priority:W().min(0).max(1).optional(),lastModified:sn.datetime({offset:!0}).optional()}),im=w({...hr.shape,...ln.shape,uri:h(),description:oe(h()),mimeType:oe(h()),size:oe(W()),annotations:_r.optional(),_meta:oe(ke({}))}),Ev=w({...hr.shape,...ln.shape,uriTemplate:h(),description:oe(h()),mimeType:oe(h()),annotations:_r.optional(),_meta:oe(ke({}))}),wv=dn.extend({method:P("resources/list")}),kv=pn.extend({resources:N(im)}),xv=dn.extend({method:P("resources/templates/list")}),$v=pn.extend({resourceTemplates:N(Ev)}),ca=De.extend({uri:h()}),Pv=ca,Tv=fe.extend({method:P("resources/read"),params:Pv}),Rv=me.extend({contents:N(Q([om,sm]))}),zv=qe.extend({method:P("notifications/resources/list_changed"),params:Ue.optional()}),Iv=ca,Ov=fe.extend({method:P("resources/subscribe"),params:Iv}),Av=ca,Cv=fe.extend({method:P("resources/unsubscribe"),params:Av}),Mv=Ue.extend({uri:h()}),Dv=qe.extend({method:P("notifications/resources/updated"),params:Mv}),Nv=w({name:h(),description:oe(h()),required:oe(de())}),jv=w({...hr.shape,...ln.shape,description:oe(h()),arguments:oe(N(Nv)),_meta:oe(ke({}))}),Lv=dn.extend({method:P("prompts/list")}),Uv=pn.extend({prompts:N(jv)}),qv=De.extend({name:h(),arguments:Y(h(),h()).optional()}),Zv=fe.extend({method:P("prompts/get"),params:qv}),ua=w({type:P("text"),text:h(),annotations:_r.optional(),_meta:Y(h(),ne()).optional()}),la=w({type:P("image"),data:aa,mimeType:h(),annotations:_r.optional(),_meta:Y(h(),ne()).optional()}),da=w({type:P("audio"),data:aa,mimeType:h(),annotations:_r.optional(),_meta:Y(h(),ne()).optional()}),Fv=w({type:P("tool_use"),name:h(),id:h(),input:Y(h(),ne()),_meta:Y(h(),ne()).optional()}),Hv=w({type:P("resource"),resource:Q([om,sm]),annotations:_r.optional(),_meta:Y(h(),ne()).optional()}),Wv=im.extend({type:P("resource_link")}),pa=Q([ua,la,da,Wv,Hv]),Vv=w({role:hn,content:pa}),Kv=me.extend({description:h().optional(),messages:N(Vv)}),Jv=qe.extend({method:P("notifications/prompts/list_changed"),params:Ue.optional()}),Bv=w({title:h().optional(),readOnlyHint:de().optional(),destructiveHint:de().optional(),idempotentHint:de().optional(),openWorldHint:de().optional()}),Yv=w({taskSupport:Te(["required","optional","forbidden"]).optional()}),am=w({...hr.shape,...ln.shape,description:h().optional(),inputSchema:w({type:P("object"),properties:Y(h(),le).optional(),required:N(h()).optional()}).catchall(ne()),outputSchema:w({type:P("object"),properties:Y(h(),le).optional(),required:N(h()).optional()}).catchall(ne()).optional(),annotations:Bv.optional(),execution:Yv.optional(),_meta:Y(h(),ne()).optional()}),fa=dn.extend({method:P("tools/list")}),Gv=pn.extend({tools:N(am)}),Wo=me.extend({content:N(pa).default([]),structuredContent:Y(h(),ne()).optional(),isError:de().optional()}),nI=Wo.or(me.extend({toolResult:ne()})),Xv=cn.extend({name:h(),arguments:Y(h(),ne()).optional()}),gn=fe.extend({method:P("tools/call"),params:Xv}),Qv=qe.extend({method:P("notifications/tools/list_changed"),params:Ue.optional()}),oI=w({autoRefresh:de().default(!0),debounceMs:W().int().nonnegative().default(300)}),_n=Te(["debug","info","notice","warning","error","critical","alert","emergency"]),eb=De.extend({level:_n}),ma=fe.extend({method:P("logging/setLevel"),params:eb}),tb=Ue.extend({level:_n,logger:h().optional(),data:ne()}),rb=qe.extend({method:P("notifications/message"),params:tb}),nb=w({name:h().optional()}),ob=w({hints:N(nb).optional(),costPriority:W().min(0).max(1).optional(),speedPriority:W().min(0).max(1).optional(),intelligencePriority:W().min(0).max(1).optional()}),sb=w({mode:Te(["auto","required","none"]).optional()}),ib=w({type:P("tool_result"),toolUseId:h().describe("The unique identifier for the corresponding tool call."),content:N(pa).default([]),structuredContent:w({}).loose().optional(),isError:de().optional(),_meta:Y(h(),ne()).optional()}),ab=Gi("type",[ua,la,da]),Oo=Gi("type",[ua,la,da,Fv,ib]),cb=w({role:hn,content:Q([Oo,N(Oo)]),_meta:Y(h(),ne()).optional()}),ub=cn.extend({messages:N(cb),modelPreferences:ob.optional(),systemPrompt:h().optional(),includeContext:Te(["none","thisServer","allServers"]).optional(),temperature:W().optional(),maxTokens:W().int(),stopSequences:N(h()).optional(),metadata:le.optional(),tools:N(am).optional(),toolChoice:sb.optional()}),lb=fe.extend({method:P("sampling/createMessage"),params:ub}),yn=me.extend({model:h(),stopReason:oe(Te(["endTurn","stopSequence","maxTokens"]).or(h())),role:hn,content:ab}),ha=me.extend({model:h(),stopReason:oe(Te(["endTurn","stopSequence","maxTokens","toolUse"]).or(h())),role:hn,content:Q([Oo,N(Oo)])}),db=w({type:P("boolean"),title:h().optional(),description:h().optional(),default:de().optional()}),pb=w({type:P("string"),title:h().optional(),description:h().optional(),minLength:W().optional(),maxLength:W().optional(),format:Te(["email","uri","date","date-time"]).optional(),default:h().optional()}),fb=w({type:Te(["number","integer"]),title:h().optional(),description:h().optional(),minimum:W().optional(),maximum:W().optional(),default:W().optional()}),mb=w({type:P("string"),title:h().optional(),description:h().optional(),enum:N(h()),default:h().optional()}),hb=w({type:P("string"),title:h().optional(),description:h().optional(),oneOf:N(w({const:h(),title:h()})),default:h().optional()}),gb=w({type:P("string"),title:h().optional(),description:h().optional(),enum:N(h()),enumNames:N(h()).optional(),default:h().optional()}),_b=Q([mb,hb]),yb=w({type:P("array"),title:h().optional(),description:h().optional(),minItems:W().optional(),maxItems:W().optional(),items:w({type:P("string"),enum:N(h())}),default:N(h()).optional()}),Sb=w({type:P("array"),title:h().optional(),description:h().optional(),minItems:W().optional(),maxItems:W().optional(),items:w({anyOf:N(w({const:h(),title:h()}))}),default:N(h()).optional()}),vb=Q([yb,Sb]),bb=Q([gb,_b,vb]),Eb=Q([bb,db,pb,fb]),wb=cn.extend({mode:P("form").optional(),message:h(),requestedSchema:w({type:P("object"),properties:Y(h(),Eb),required:N(h()).optional()})}),kb=cn.extend({mode:P("url"),message:h(),elicitationId:h(),url:h().url()}),xb=Q([wb,kb]),$b=fe.extend({method:P("elicitation/create"),params:xb}),Pb=Ue.extend({elicitationId:h()}),Tb=qe.extend({method:P("notifications/elicitation/complete"),params:Pb}),yr=me.extend({action:Te(["accept","decline","cancel"]),content:Xi(t=>t===null?void 0:t,Y(h(),Q([h(),W(),de(),N(h())])).optional())}),Rb=w({type:P("ref/resource"),uri:h()});var zb=w({type:P("ref/prompt"),name:h()}),Ib=De.extend({ref:Q([zb,Rb]),argument:w({name:h(),value:h()}),context:w({arguments:Y(h(),h()).optional()}).optional()}),Ob=fe.extend({method:P("completion/complete"),params:Ib});var Ab=me.extend({completion:ke({values:N(h()).max(100),total:oe(W().int()),hasMore:oe(de())})}),Cb=w({uri:h().startsWith("file://"),name:h().optional(),_meta:Y(h(),ne()).optional()}),Mb=fe.extend({method:P("roots/list"),params:De.optional()}),ga=me.extend({roots:N(Cb)}),Db=qe.extend({method:P("notifications/roots/list_changed"),params:Ue.optional()}),sI=Q([No,sa,Ob,ma,Zv,Lv,wv,xv,Tv,Ov,Cv,gn,fa,Lo,qo,Zo,Ho]),iI=Q([Do,jo,ia,Db,mn]),aI=Q([Mo,yn,ha,yr,ga,Uo,Fo,gr]),cI=Q([No,lb,$b,Mb,Lo,qo,Zo,Ho]),uI=Q([Do,jo,rb,Dv,zv,Qv,Jv,mn,Tb]),lI=Q([Mo,gv,Ab,Kv,Uv,kv,$v,Rv,Wo,Gv,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===D.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new Qi(o.elicitations,r)}return new t(e,r,n)}},Qi=class extends I{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(D.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function Mt(t){return t==="completed"||t==="failed"||t==="cancelled"}var FI=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function _a(t){let r=Ro(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=pf(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function ya(t,e){let r=At(t,e);if(!r.success)throw r.error;return r.data}var Zb=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(Do,r=>{this._oncancel(r)}),this.setNotificationHandler(jo,r=>{this._onprogress(r)}),this.setRequestHandler(No,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(D.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(D.InvalidParams,`Task not found: ${s}`);if(!Mt(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(Mt(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[Ct]:{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(D.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(D.InvalidParams,`Task not found: ${r.params.taskId}`);if(Mt(o.status))throw new I(D.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(D.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof I?o:new I(D.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(D.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),un(s)||Qf(s)?this._onresponse(s):ra(s)?this._onrequest(s,i):Xf(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(D.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?.[Ct]?.taskId;if(n===void 0){let l={jsonrpc:"2.0",id:e.id,error:{code:D.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=Bf(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(D.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:D.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),un(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(un(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),un(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(D.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(D.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},Mt(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(D.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new I(D.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(D.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=x=>{l(x)};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(x){d(x);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||{},[Ct]:c}});let m=x=>{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(x)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch($=>this._onerror(new Error(`Failed to send cancellation: ${$}`)));let b=x instanceof I?x:new I(D.RequestTimeout,String(x));l(b)};this._responseHandlers.set(p,x=>{if(!n?.signal?.aborted){if(x instanceof Error)return l(x);try{let b=At(r,x.result);b.success?u(b.data):l(b.error)}catch(b){l(b)}}}),n?.signal?.addEventListener("abort",()=>{m(n?.signal?.reason)});let g=n?.timeout??Zb,S=()=>m(I.fromError(D.RequestTimeout,"Request timed out",{timeout:g}));this._setupTimeout(p,g,n?.maxTotalTimeout,S,n?.resetTimeoutOnProgress??!1);let v=c?.taskId;if(v){let x=b=>{let $=this._responseHandlers.get(p);$?$(b):this._onerror(new Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,x),this._enqueueTaskMessage(v,{type:"request",message:f,timestamp:Date.now()}).catch(b=>{this._cleanupTimeout(p),l(b)})}else this._transport.send(f,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(x=>{this._cleanupTimeout(p),l(x)})})}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},rm,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||{},[Ct]: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||{},[Ct]: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||{},[Ct]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=_a(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=ya(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=_a(e);this._notificationHandlers.set(n,o=>{let s=ya(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"&&ra(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new I(D.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(D.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(i),s(new I(D.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(D.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=mn.parse({method:"notifications/tasks/status",params:a});await this.notification(c),Mt(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(D.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(Mt(a.status))throw new I(D.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=mn.parse({method:"notifications/tasks/status",params:c});await this.notification(u),Mt(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function cm(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function um(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];cm(i)&&cm(s)?r[o]={...i,...s}:r[o]=s}return r}var e_=Tt(ou(),1),t_=Tt(Qg(),1);function W$(){let t=new e_.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,t_.default)(t),t}var Ps=class{constructor(e){this._ajv=e??W$()}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},yn,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 r_(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 n_(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 Rs=class extends Vo{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(_n.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(sa,n=>this._oninitialize(n)),this.setNotificationHandler(ia,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(ma,async(n,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=_n.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=um(this._capabilities,e)}setRequestHandler(e,r){let o=Ro(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=At(gn,c);if(!l.success){let m=l.error instanceof Error?l.error.message:String(l.error);throw new I(D.InvalidParams,`Invalid tools/call request: ${m}`)}let{params:d}=l.data,p=await Promise.resolve(r(c,u));if(d.task){let m=At(gr,p);if(!m.success){let g=m.error instanceof Error?m.error.message:String(m.error);throw new I(D.InvalidParams,`Invalid task creation result: ${g}`)}return m.data}let f=At(Wo,p);if(!f.success){let m=f.error instanceof Error?f.error.message:String(f.error);throw new I(D.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){n_(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&r_(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:Vf.includes(r)?r:ea,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"},Mo)}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},ha,r):this.request({method:"sampling/createMessage",params:e},yn,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(D.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof I?i:new I(D.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},ga,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 pu=Tt(require("node:process"),1);var zs=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
|
|
84
84
|
`);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),V$(r)}clear(){this._buffer=void 0}};function V$(t){return em.parse(JSON.parse(t))}function o_(t){return JSON.stringify(t)+`
|
|
85
|
-
`}var Is=class{constructor(e=pu.default.stdin,r=pu.default.stdout){this._stdin=e,this._stdout=r,this._readBuffer=new zs,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=o_(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};var Pe=Tt(require("path"),1),Ae=require("fs");var fu=require("node:child_process");function Os(t,e,r){return(0,fu.spawn)(t,e??[],{windowsHide:!0,...r})}var K$=new Set([".cmd",".bat"]),J$=new Set([".exe",".com"]),yD=new Set([...J$,...K$]);ce();var ye={HEALTH_CHECK:3e3,API_REQUEST:3e4,HOOK_READINESS_WAIT:1e4,POST_SPAWN_WAIT:15e3,READINESS_WAIT:3e4,PORT_IN_USE_WAIT:3e3,POWERSHELL_COMMAND:1e4,WINDOWS_MULTIPLIER:1.5};function Ht(t){return process.platform==="win32"?Math.round(t*ye.WINDOWS_MULTIPLIER):t}var As=require("fs"),mu=require("path"),Bn=require("os");Fr();var st=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(Ht(ye.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-flash-latest",CLAUDE_MEM_GEMINI_RATE_LIMITING_ENABLED:"true",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_DATA_DIR:(0,mu.join)((0,Bn.homedir)(),".claude-mem"),CLAUDE_MEM_LOG_LEVEL:"INFO",CLAUDE_MEM_PYTHON_VERSION:"3.13",CLAUDE_CODE_PATH:"",CLAUDE_MEM_MODE:"code",CLAUDE_MEM_CONTEXT_SHOW_READ_TOKENS:"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:"10",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,mu.join)((0,Bn.homedir)(),".claude-mem","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_CHROMA_MODE:"local",CLAUDE_MEM_CHROMA_HOST:"127.0.0.1",CLAUDE_MEM_CHROMA_PORT:"8000",CLAUDE_MEM_CHROMA_SSL:"false",CLAUDE_MEM_CHROMA_API_KEY:"",CLAUDE_MEM_CHROMA_TENANT:"default_tenant",CLAUDE_MEM_CHROMA_DATABASE:"default_database",CLAUDE_MEM_CHROMA_PREWARM_TIMEOUT_MS:"120000",CLAUDE_MEM_CLOUD_SYNC_TOKEN:"",CLAUDE_MEM_CLOUD_SYNC_USER_ID:"",CLAUDE_MEM_CLOUD_SYNC_HUB_URL:"",CLAUDE_MEM_CLOUD_SYNC_DEVICE_ID:"",CLAUDE_MEM_CLOUD_SYNC_DEVICE_NAME:(0,Bn.hostname)(),CLAUDE_MEM_CLOUD_SYNC_WS:"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 get(e){return process.env[e]??this.DEFAULTS[e]}static getInt(e){let r=this.get(e);return parseInt(r,10)}static applyEnvOverrides(e){let r={...e};for(let n of Object.keys(this.DEFAULTS))process.env[n]!==void 0&&(r[n]=process.env[n]);return r}static loadFromFile(e,r=!0){try{if(!(0,As.existsSync)(e)){let a=this.getAllDefaults();try{oi(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,As.readFileSync)(e,"utf-8"),o=Wt(n),s=o;if(o.env&&typeof o.env=="object"){s=o.env;try{oi(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();return r?this.applyEnvOverrides(o):o}}};Xe();Xe();var Cs=null;function Ms(){return Cs!==null||(Cs=st.loadFromFile(uo)),Cs}var sr=require("fs");ce();var Su=require("child_process");var gt=require("fs"),_u=Tt(require("path"),1);ce();var B$=["CLAUDECODE_","CLAUDE_CODE_"],Y$=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID"]),G$=new Set(["HTTP_PROXY","HTTPS_PROXY","ALL_PROXY","NO_PROXY","http_proxy","https_proxy","all_proxy","no_proxy","npm_config_proxy","npm_config_https_proxy","npm_config_noproxy"]),X$=new Set(["CLAUDE_CODE_OAUTH_TOKEN","CLAUDE_CODE_GIT_BASH_PATH","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX","CLAUDE_CODE_USE_FOUNDRY","CLAUDE_CODE_SKIP_BEDROCK_AUTH","CLAUDE_CODE_SKIP_VERTEX_AUTH","CLAUDE_CODE_SKIP_FOUNDRY_AUTH","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",...G$]);function Yn(t=process.env){let e={};for(let[r,n]of Object.entries(t))if(n!==void 0){if(X$.has(r)){e[r]=n;continue}Y$.has(r)||B$.some(o=>r.startsWith(o))||(e[r]=n)}return e}Xe();var Q$=5e3,eP=1e3,tP=je.supervisorRegistry();function Ve(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 Ds(t,e){let r=Date.now()+e;for(;Date.now()<r;){if(t.every(n=>!Ve(n.pid)))return;await new Promise(n=>setTimeout(n,100))}}var rP=5e3,s_=new Map;function nP(t){let e=(0,Su.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:{...Yn(process.env),LC_ALL:"C",LANG:"C"}});if(e.status===0){let r=e.stdout.trim();return r.length>0?r:null}return null}function oP(t){let e=s_.get(t);if(e&&Date.now()-e.capturedAtMs<rP)return e.token;let r=null;try{r=nP(t)}catch(n){y.debug("SYSTEM","captureProcessStartToken: powershell CIM lookup failed",{pid:t,error:n instanceof Error?n.message:String(n)}),r=null}return s_.set(t,{token:r,capturedAtMs:Date.now()}),r}function i_(t){if(!Number.isInteger(t)||t<=0)return null;if(process.platform==="linux")try{let e=(0,gt.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 oP(t);try{let e=(0,Su.spawnSync)("ps",["-p",String(t),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...Yn(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 vu(t){if(!t||!Ve(t.pid))return!1;if(!t.startToken)return!0;let e=i_(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 yu=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;constructor(e=tP){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,(0,gt.mkdirSync)(_u.default.dirname(this.registryPath),{recursive:!0}),!(0,gt.existsSync)(this.registryPath)){this.persist();return}try{let n=JSON.parse((0,gt.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"&&gu()}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)}pruneDeadEntries(){this.initialize();let e=0,r=0;for(let[n,o]of this.entries)Ve(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)gu();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=>Ve(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 Ds(o,Q$);let s=o.filter(i=>Ve(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()+eP;for(;Date.now()<i&&s.filter(c=>Ve(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"&&gu();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,gt.mkdirSync)(_u.default.dirname(this.registryPath),{recursive:!0}),(0,gt.writeFileSync)(this.registryPath,JSON.stringify(e,null,2))}},hu=null;function Ns(){return hu||(hu=new yu),hu}var sP=[];function gu(){let t=sP.shift();t&&t()}var c_=require("child_process"),Nr=require("fs"),u_=require("util");ce();Xe();var iP=(0,u_.promisify)(c_.execFile),aP=je.workerPid();async function l_(t){let e=t.currentPid??process.pid,r=t.pidFilePath??aP,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(!Ve(i.pid)){t.registry.unregister(i.id);continue}try{await a_(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 Ds(o,5e3);let s=o.filter(i=>Ve(i.pid));for(let i of s)try{await a_(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 Ds(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);d_(r,e),t.registry.pruneDeadEntries()}function d_(t,e,r=!1){if(!(0,Nr.existsSync)(t))return;let n=null;try{let i=JSON.parse((0,Nr.readFileSync)(t,"utf-8"));n=typeof i.pid=="number"?i.pid:null}catch(i){y.debug("SYSTEM","PID file unreadable \u2014 leaving it (cannot prove ownership)",{pidFilePath:t,error:i instanceof Error?i.message:String(i)});return}let o=e!==null&&n===e,s=n===null||!Ve(n);if(!o&&!(r&&s)){y.debug("SYSTEM","PID file not owned by this process \u2014 leaving it for its owner (restart successor?)",{pidFilePath:t,recordedPid:n,currentPid:e});return}try{(0,Nr.rmSync)(t,{force:!0})}catch(i){i instanceof Error?y.debug("SYSTEM","Failed to remove PID file",{pidFilePath:t},i):y.warn("SYSTEM","Failed to remove PID file (non-Error)",{pidFilePath:t,error:String(i)})}}async function a_(t,e){let{pid:r,pgid:n}=t;if(process.platform!=="win32"){if(typeof n=="number")try{process.kill(-n,e);return}catch(s){if((s instanceof Error?s.code:void 0)!=="ESRCH")throw s}try{process.kill(r,e)}catch(s){if((s instanceof Error?s.code:void 0)!=="ESRCH")throw s}return}if(e==="SIGTERM"){try{process.kill(r,e)}catch(s){if(s instanceof Error&&s.code==="ESRCH")return;throw s}return}let o=["/PID",String(r),"/T"];e==="SIGKILL"&&o.push("/F"),await iP("taskkill",o,{timeout:ye.POWERSHELL_COMMAND,windowsHide:!0})}ce();var p_=3e4,jr=null;function cP(){let e=Ns().pruneDeadEntries();e>0&&y.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function f_(){jr===null&&(jr=setInterval(cP,p_),jr.unref(),y.debug("SYSTEM","Health checker started",{intervalMs:p_}))}function m_(){jr!==null&&(clearInterval(jr),jr=null,y.debug("SYSTEM","Health checker stopped"))}Xe();var uP=je.workerPid(),bu=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(),js({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,f_()}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}m_(),this.stopPromise=l_({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}},lP=new bu(Ns());function Eu(){return lP}function js(t={}){let e=t.pidFilePath??uP;if(!(0,sr.existsSync)(e))return"missing";let r=null;try{r=JSON.parse((0,sr.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,sr.rmSync)(e,{force:!0}),"invalid"}return vu(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,sr.rmSync)(e,{force:!0}),"stale")}io();Xe();Fr();ce();ce();var ir=Tt(require("path"),1),__=require("os"),Ke=require("fs"),Ls=require("child_process");ce();ce();ce();Xe();var AN=je.dataDir(),h_=je.workerPid();function g_(t){return t?/(^|[\\/])bun(\.exe)?$/i.test(t.trim()):!1}function dP(t,e){let r=e==="win32"?`where ${t}`:`which ${t}`,n;try{n=(0,Ls.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 wu;function y_(t={}){let e=Object.keys(t).length===0;if(e&&wu!==void 0)return wu;let r=pP(t);return e&&r!==null&&(wu=r),r}function pP(t){let e=t.platform??process.platform,r=t.execPath??process.execPath;if(g_(r))return r;let n=t.env??process.env,o=t.homeDirectory??(0,__.homedir)(),s=t.pathExists??Ke.existsSync,i=t.lookupInPath??dP,a=e==="win32"?[n.BUN,n.BUN_PATH,ir.default.join(o,".bun","bin","bun.exe"),ir.default.join(o,".bun","bin","bun"),n.USERPROFILE?ir.default.join(n.USERPROFILE,".bun","bin","bun.exe"):void 0,n.LOCALAPPDATA?ir.default.join(n.LOCALAPPDATA,"bun","bun.exe"):void 0,n.LOCALAPPDATA?ir.default.join(n.LOCALAPPDATA,"bun","bin","bun.exe"):void 0]:[n.BUN,n.BUN_PATH,ir.default.join(o,".bun","bin","bun"),"/usr/local/bin/bun","/opt/homebrew/bin/bun","/home/linuxbrew/.linuxbrew/bin/bun","/usr/bin/bun","/snap/bin/bun"];for(let c of a){let u=c?.trim();if(u&&(g_(u)&&s(u)||u.toLowerCase()==="bun"))return u}return i("bun",e)}function Lr(t){return process.platform==="win32"?Math.round(t*2):t}function fP(t,e){let r=n=>n.replace(/'/g,"''");return`Start-Process -FilePath '${r(t)}' -ArgumentList @('"${r(e)}"','--daemon') -WindowStyle Hidden`}function S_(t,e,r={}){Eu().assertCanSpawn("worker daemon");let n=Yn({...process.env,CLAUDE_MEM_WORKER_PORT:String(e),...r}),o=y_();if(!o){y.error("SYSTEM","Bun runtime not found \u2014 install from https://bun.sh and ensure it is on PATH or set BUN env var. The worker daemon requires Bun because it uses bun:sqlite.");return}if(process.platform==="win32"){let l=fP(o,t),d=Buffer.from(l,"utf16le").toString("base64");try{return(0,Ls.execSync)(`powershell -NoProfile -EncodedCommand ${d}`,{stdio:"ignore",windowsHide:!0,env:n}),0}catch(p){let f=p instanceof Error?p:new Error(String(p));y.error("SYSTEM","Failed to spawn worker daemon on Windows",{runtimePath:o},f);return}}let s="/usr/bin/setsid",i=(0,Ke.existsSync)(s),u=Os(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_(){try{if(!(0,Ke.existsSync)(h_))return;let t=new Date;(0,Ke.utimesSync)(h_,t,t)}catch{}}function Us(){return js({logAlive:!1})}var b_=Tt(require("net"),1);ce();Xe();function ku(){return st.loadFromFile(uo).CLAUDE_MEM_WORKER_HOST}function E_(t){return t.startsWith("[")&&t.endsWith("]")?t:t.includes(":")?`[${t}]`:t}async function mP(t,e,r="GET"){let n=await fetch(`http://${E_(ku())}:${t}${e}`,{method:r}),o="";try{o=await n.text()}catch{}return{ok:n.ok,statusCode:n.status,body:o}}async function w_(t){if(process.platform==="win32")try{let e=await fetch(`http://${E_(ku())}:${t}/api/health`);if(e.ok)return!0;y.debug("SYSTEM","Windows health check returned non-ok; falling through to socket probe",{port:t,status:e.status})}catch(e){e instanceof Error?y.debug("SYSTEM","Windows health check threw; falling through to socket probe",{port:t,message:e.message}):y.debug("SYSTEM","Windows health check threw; falling through to socket probe",{port:t,error:String(e)})}return new Promise(e=>{let r=b_.default.createServer(),n=ku();r.once("error",o=>{o.code==="EADDRINUSE"?e(!0):e(!1)}),r.once("listening",()=>{r.close(()=>e(!1))}),r.listen(t,n)})}async function k_(t,e,r,n){let o=Date.now();for(;Date.now()-o<r;){try{if((await mP(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 Gn(t,e=3e4){return k_(t,"/api/health",e,"Service not ready yet, will retry")}function Xn(t,e=3e4){return k_(t,"/api/readiness",e,"Worker not ready yet, will retry")}ce();var qs=require("path"),Je=require("fs");Xe();ce();var hP=9e4;function x_(){return(0,qs.join)(ao(),"spawn.lock")}function xu(){let t=x_(),e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()});for(let r=0;r<2;r++)try{return(0,Je.mkdirSync)((0,qs.dirname)(t),{recursive:!0}),(0,Je.writeFileSync)(t,e,{flag:"wx"}),!0}catch(n){let o=n instanceof Error?n:new Error(String(n)),s=o.code;if(s!=="EEXIST")return y.warn("SYSTEM","Spawn lock write failed for a non-contention reason; failing open (spawning unlocked)",{lockPath:t,code:s},o),!0;if(r>0)return!1;let i;try{i=(0,Je.statSync)(t).mtimeMs}catch{continue}if(Date.now()-i<=hP)return!1;let a;try{a=(0,Je.statSync)(t).mtimeMs}catch{continue}if(a!==i)return!1;try{(0,Je.unlinkSync)(t)}catch{return!1}}return!1}function $u(){let t=x_();try{if(JSON.parse((0,Je.readFileSync)(t,"utf-8")).pid!==process.pid)return;(0,Je.unlinkSync)(t)}catch{}}function T_(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 dj=T_("CLAUDE_MEM_HEALTH_TIMEOUT_MS",Ht(ye.HEALTH_CHECK),{min:500,max:3e5}),pj=T_("CLAUDE_MEM_HOOK_READINESS_TIMEOUT_MS",Ht(ye.HOOK_READINESS_WAIT),{min:0,max:3e5}),gP={min:500,max:3e5};async function Pu(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 Zs=null,Fs=null,Hs=null,Ws=null;function _P(){return Pe.default.join(st.get("CLAUDE_MEM_DATA_DIR"),"settings.json")}function Tu(){return Hs!==null||(Hs=st.loadFromFile(_P())),Hs}function $_(t,e){if(!t)return null;let r=parseInt(t,10);return Number.isFinite(r)&&r>=e.min&&r<=e.max?r:null}function yP(t,e,r){let n=process.env[t];if(n!==void 0){let i=$_(n,r);return i!==null?i:(y.warn("SYSTEM",`Invalid ${t}, using default`,{value:n,min:r.min,max:r.max}),e)}let o=Tu()[t],s=$_(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 Ru(){if(Zs!==null)return Zs;let t=Tu();return Zs=parseInt(t.CLAUDE_MEM_WORKER_PORT,10),Zs}function SP(){return Fs!==null||(Fs=Tu().CLAUDE_MEM_WORKER_HOST),Fs}function vP(){return Ws!==null||(Ws=yP("CLAUDE_MEM_API_TIMEOUT_MS",Ht(ye.API_REQUEST),gP)),Ws}function bP(t){return t.startsWith("[")&&t.endsWith("]")?t:t.includes(":")?`[${t}]`:t}function EP(t){return`http://${bP(SP())}:${Ru()}${t}`}function Vs(t,e={}){let r=e.method??"GET",n=e.timeoutMs??vP(),o=EP(t),s={method:r};return e.headers&&(s.headers=e.headers),e.body&&(s.body=e.body),n>0?Pu(o,s,n):fetch(o,s)}function R_(t){let e=(0,Ae.existsSync)(Pe.default.join(t,"plugin","scripts"))?Pe.default.join(t,"plugin"):t;return Pe.default.join(e,"scripts","worker-service.cjs")}function wP(t,e){let r=d=>{let p=d.split("-")[0].split(".");return[parseInt(p[0],10)||0,parseInt(p[1],10)||0,parseInt(p[2],10)||0]},[n,o,s]=r(t),[i,a,c]=r(e);if(i!==n)return i-n;if(a!==o)return a-o;if(c!==s)return c-s;let u=t.includes("-")?1:0,l=e.includes("-")?1:0;return u!==l?u-l:t<e?1:t>e?-1:0}function kP(t=Pe.default.join(Pe.default.dirname(Pe.default.dirname(co)),"cache","thedotmack","claude-mem")){try{return(0,Ae.readdirSync)(t).filter(e=>/^\d/.test(e)).map(e=>Pe.default.join(t,e)).filter(e=>{try{if(!(0,Ae.statSync)(e).isDirectory())return!1}catch{return!1}return!(0,Ae.existsSync)(Pe.default.join(e,".orphaned_at"))}).map(e=>({scriptPath:R_(e),version:Pe.default.basename(e)}))}catch{return[]}}function P_(t){try{let e=JSON.parse((0,Ae.readFileSync)(t,"utf-8"));return typeof e.version=="string"?e.version:null}catch(e){let r=e.code;return r!=="ENOENT"&&y.debug("SYSTEM","Could not read package version for worker resolution",{packageJsonPath:t,code:r}),null}}function xP(){let t=process.env.CLAUDE_MEM_WORKER_SCRIPT_PATH?.trim();if(t){if((0,Ae.existsSync)(t))return{scriptPath:t,version:null};y.debug("SYSTEM","Ignoring missing CLAUDE_MEM_WORKER_SCRIPT_PATH override",{override:t})}let e=[...kP(),{scriptPath:R_(Pe.default.join(co,"plugin")),version:P_(Pe.default.join(co,"package.json"))},{scriptPath:Pe.default.join(process.cwd(),"plugin","scripts","worker-service.cjs"),version:P_(Pe.default.join(process.cwd(),"package.json"))}];return $P(e)}function $P(t){let e=t.filter(r=>(0,Ae.existsSync)(r.scriptPath));return e.length===0?null:(e.sort((r,n)=>r.version===null&&n.version===null?0:r.version===null?1:n.version===null?-1:wP(r.version,n.version)),e[0])}function z_(){return xP()?.scriptPath??null}var zu=Tt(require("path"),1),Be=require("fs");ce();var PP=120*1e3;function Iu(){return zu.default.join(st.get("CLAUDE_MEM_DATA_DIR"),".worker-start-attempted")}function TP(){if(process.platform!=="win32")return!1;let t=Iu();if(!(0,Be.existsSync)(t))return!1;try{let e=(0,Be.statSync)(t).mtimeMs;return Date.now()-e<PP}catch(e){return e instanceof Error?y.debug("SYSTEM","Could not stat worker spawn lock file",{},e):y.debug("SYSTEM","Could not stat worker spawn lock file",{error:String(e)}),!1}}function RP(){if(process.platform==="win32")try{let t=Iu();(0,Be.mkdirSync)(zu.default.dirname(t),{recursive:!0}),(0,Be.writeFileSync)(t,"","utf-8")}catch{}}function Ks(){if(process.platform==="win32")try{let t=Iu();(0,Be.existsSync)(t)&&(0,Be.unlinkSync)(t)}catch{}}async function I_(t,e){if(!e)return y.error("SYSTEM","ensureWorkerStarted called with empty workerScriptPath \u2014 caller bug"),"dead";if(!(0,Be.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(Us()==="alive"){if(y.info("SYSTEM","Worker PID file points to a live process, skipping duplicate spawn"),await Xn(t,Lr(ye.READINESS_WAIT)))return Ks(),y.info("SYSTEM","Worker became ready while waiting on live PID"),"ready";let a=await Gn(t,1e3),c=Us()==="alive";return!a&&!c?(y.error("SYSTEM","Live PID disappeared before readiness endpoint became available"),"dead"):(y.warn("SYSTEM","Live PID detected but worker did not become ready before timeout"),"warming")}if(await Gn(t,1e3)){Ks();let i=await Xn(t,Lr(ye.READINESS_WAIT));return i||y.warn("SYSTEM","Worker is alive but readiness timed out \u2014 proceeding anyway"),y.info("SYSTEM","Worker already running and healthy"),i?"ready":"warming"}if(await w_(t)){if(y.info("SYSTEM","Port in use, waiting for worker to become healthy"),await Gn(t,Lr(ye.PORT_IN_USE_WAIT))){Ks();let a=await Xn(t,Lr(ye.READINESS_WAIT));return y.info("SYSTEM","Worker is now healthy"),a?"ready":"warming"}return y.error("SYSTEM","Port in use but worker not responding to health checks"),"dead"}if(TP())return y.warn("SYSTEM","Worker unavailable on Windows \u2014 skipping spawn (recent attempt failed within cooldown)"),"dead";let o=xu(),s;try{if(o){if(y.info("SYSTEM","Starting worker daemon",{workerScriptPath:e}),RP(),s=S_(e,t),s===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");if(!await Xn(t,Lr(ye.READINESS_WAIT))){let a=await Gn(t,1e3),c=Us()==="alive",u=s!==void 0&&s>0&&Ve(s);return!a&&!c&&!u?(y.error("SYSTEM",o?"Worker exited before readiness endpoint became available":"Spawn-lock holder never produced a live worker before readiness timed out"),"dead"):(y.warn("SYSTEM",o?"Worker spawned but readiness endpoint not responding within window":"Spawn-lock holder's worker not ready within window"),"warming")}return Ks(),v_(),y.info("SYSTEM",o?"Worker started successfully":"Worker is up (started by another launcher)"),"ready"}finally{o&&$u()}}var qr=require("node:fs/promises"),eo=require("node:path");var C_=require("node:child_process"),it=require("node:fs"),Ye=require("node:path"),Du=require("node:os"),Cu=require("node:module");ce();var HP={},Mu=typeof __filename<"u"?(0,Cu.createRequire)(__filename):(0,Cu.createRequire)(HP.url),zP={".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",".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){let e=t.slice(t.lastIndexOf("."));return zP[e]??"unknown"}var IP={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",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"},OP={markdown:"tree-sitter-markdown"};function D_(t){let e=IP[t];if(!e)return null;let r=OP[t];if(r){try{let n=Mu.resolve(e+"/package.json"),o=(0,Ye.join)((0,Ye.dirname)(n),r);if((0,it.existsSync)((0,Ye.join)(o,"src")))return o}catch{}return null}try{let n=Mu.resolve(e+"/package.json");return(0,Ye.dirname)(n)}catch{return null}}var AP={jsts:`
|
|
85
|
+
`}var Is=class{constructor(e=pu.default.stdin,r=pu.default.stdout){this._stdin=e,this._stdout=r,this._readBuffer=new zs,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=o_(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};var Pe=Tt(require("path"),1),Ae=require("fs");var fu=require("node:child_process");function Os(t,e,r){return(0,fu.spawn)(t,e??[],{windowsHide:!0,...r})}var K$=new Set([".cmd",".bat"]),J$=new Set([".exe",".com"]),yD=new Set([...J$,...K$]);ce();var ye={HEALTH_CHECK:3e3,API_REQUEST:3e4,HOOK_READINESS_WAIT:1e4,POST_SPAWN_WAIT:15e3,READINESS_WAIT:3e4,PORT_IN_USE_WAIT:3e3,POWERSHELL_COMMAND:1e4,WINDOWS_MULTIPLIER:1.5};function Ht(t){return process.platform==="win32"?Math.round(t*ye.WINDOWS_MULTIPLIER):t}var As=require("fs"),mu=require("path"),Bn=require("os");Fr();var st=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(Ht(ye.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-flash-latest",CLAUDE_MEM_GEMINI_RATE_LIMITING_ENABLED:"true",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_DATA_DIR:(0,mu.join)((0,Bn.homedir)(),".claude-mem"),CLAUDE_MEM_LOG_LEVEL:"INFO",CLAUDE_MEM_PYTHON_VERSION:"3.13",CLAUDE_CODE_PATH:"",CLAUDE_MEM_MODE:"code",CLAUDE_MEM_CONTEXT_SHOW_READ_TOKENS:"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:"10",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,mu.join)((0,Bn.homedir)(),".claude-mem","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_CHROMA_MODE:"local",CLAUDE_MEM_CHROMA_HOST:"127.0.0.1",CLAUDE_MEM_CHROMA_PORT:"8000",CLAUDE_MEM_CHROMA_SSL:"false",CLAUDE_MEM_CHROMA_API_KEY:"",CLAUDE_MEM_CHROMA_TENANT:"default_tenant",CLAUDE_MEM_CHROMA_DATABASE:"default_database",CLAUDE_MEM_CHROMA_PREWARM_TIMEOUT_MS:"120000",CLAUDE_MEM_CLOUD_SYNC_TOKEN:"",CLAUDE_MEM_CLOUD_SYNC_USER_ID:"",CLAUDE_MEM_CLOUD_SYNC_HUB_URL:"",CLAUDE_MEM_CLOUD_SYNC_DEVICE_ID:"",CLAUDE_MEM_CLOUD_SYNC_DEVICE_NAME:(0,Bn.hostname)(),CLAUDE_MEM_CLOUD_SYNC_WS:"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 get(e){return process.env[e]??this.DEFAULTS[e]}static getInt(e){let r=this.get(e);return parseInt(r,10)}static applyEnvOverrides(e){let r={...e};for(let n of Object.keys(this.DEFAULTS))process.env[n]!==void 0&&(r[n]=process.env[n]);return r}static loadFromFile(e,r=!0){try{if(!(0,As.existsSync)(e)){let a=this.getAllDefaults();try{oi(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,As.readFileSync)(e,"utf-8"),o=Wt(n),s=o;if(o.env&&typeof o.env=="object"){s=o.env;try{oi(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();return r?this.applyEnvOverrides(o):o}}};Xe();Xe();var Cs=null;function Ms(){return Cs!==null||(Cs=st.loadFromFile(uo)),Cs}var sr=require("fs");ce();var Su=require("child_process");var gt=require("fs"),_u=Tt(require("path"),1);ce();var B$=["CLAUDECODE_","CLAUDE_CODE_"],Y$=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID"]),G$=new Set(["HTTP_PROXY","HTTPS_PROXY","ALL_PROXY","NO_PROXY","http_proxy","https_proxy","all_proxy","no_proxy","npm_config_proxy","npm_config_https_proxy","npm_config_noproxy"]),X$=new Set(["CLAUDE_CODE_OAUTH_TOKEN","CLAUDE_CODE_GIT_BASH_PATH","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX","CLAUDE_CODE_USE_FOUNDRY","CLAUDE_CODE_SKIP_BEDROCK_AUTH","CLAUDE_CODE_SKIP_VERTEX_AUTH","CLAUDE_CODE_SKIP_FOUNDRY_AUTH","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",...G$]);function Yn(t=process.env){let e={};for(let[r,n]of Object.entries(t))if(n!==void 0){if(X$.has(r)){e[r]=n;continue}Y$.has(r)||B$.some(o=>r.startsWith(o))||(e[r]=n)}return e}Xe();var Q$=5e3,eP=1e3,tP=je.supervisorRegistry();function Ve(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 Ds(t,e){let r=Date.now()+e;for(;Date.now()<r;){if(t.every(n=>!Ve(n.pid)))return;await new Promise(n=>setTimeout(n,100))}}var rP=5e3,s_=new Map;function nP(t){let e=(0,Su.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:{...Yn(process.env),LC_ALL:"C",LANG:"C"}});if(e.status===0){let r=e.stdout.trim();return r.length>0?r:null}return null}function oP(t){let e=s_.get(t);if(e&&Date.now()-e.capturedAtMs<rP)return e.token;let r=null;try{r=nP(t)}catch(n){y.debug("SYSTEM","captureProcessStartToken: powershell CIM lookup failed",{pid:t,error:n instanceof Error?n.message:String(n)}),r=null}return s_.set(t,{token:r,capturedAtMs:Date.now()}),r}function i_(t){if(!Number.isInteger(t)||t<=0)return null;if(process.platform==="linux")try{let e=(0,gt.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 oP(t);try{let e=(0,Su.spawnSync)("ps",["-p",String(t),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...Yn(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 vu(t){if(!t||!Ve(t.pid))return!1;if(!t.startToken)return!0;let e=i_(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 yu=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;constructor(e=tP){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,(0,gt.mkdirSync)(_u.default.dirname(this.registryPath),{recursive:!0}),!(0,gt.existsSync)(this.registryPath)){this.persist();return}try{let n=JSON.parse((0,gt.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"&&gu()}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)}pruneDeadEntries(){this.initialize();let e=0,r=0;for(let[n,o]of this.entries)Ve(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)gu();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=>Ve(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 Ds(o,Q$);let s=o.filter(i=>Ve(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()+eP;for(;Date.now()<i&&s.filter(c=>Ve(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"&&gu();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,gt.mkdirSync)(_u.default.dirname(this.registryPath),{recursive:!0}),(0,gt.writeFileSync)(this.registryPath,JSON.stringify(e,null,2))}},hu=null;function Ns(){return hu||(hu=new yu),hu}var sP=[];function gu(){let t=sP.shift();t&&t()}var c_=require("child_process"),Nr=require("fs"),u_=require("util");ce();Xe();var iP=(0,u_.promisify)(c_.execFile),aP=je.workerPid();async function l_(t){let e=t.currentPid??process.pid,r=t.pidFilePath??aP,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(!Ve(i.pid)){t.registry.unregister(i.id);continue}try{await a_(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 Ds(o,5e3);let s=o.filter(i=>Ve(i.pid));for(let i of s)try{await a_(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 Ds(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);d_(r,e),t.registry.pruneDeadEntries()}function d_(t,e,r=!1){if(!(0,Nr.existsSync)(t))return;let n=null;try{let i=JSON.parse((0,Nr.readFileSync)(t,"utf-8"));n=typeof i.pid=="number"?i.pid:null}catch(i){y.debug("SYSTEM","PID file unreadable \u2014 leaving it (cannot prove ownership)",{pidFilePath:t,error:i instanceof Error?i.message:String(i)});return}let o=e!==null&&n===e,s=n===null||!Ve(n);if(!o&&!(r&&s)){y.debug("SYSTEM","PID file not owned by this process \u2014 leaving it for its owner (restart successor?)",{pidFilePath:t,recordedPid:n,currentPid:e});return}try{(0,Nr.rmSync)(t,{force:!0})}catch(i){i instanceof Error?y.debug("SYSTEM","Failed to remove PID file",{pidFilePath:t},i):y.warn("SYSTEM","Failed to remove PID file (non-Error)",{pidFilePath:t,error:String(i)})}}async function a_(t,e){let{pid:r,pgid:n}=t;if(process.platform!=="win32"){if(typeof n=="number")try{process.kill(-n,e);return}catch(s){if((s instanceof Error?s.code:void 0)!=="ESRCH")throw s}try{process.kill(r,e)}catch(s){if((s instanceof Error?s.code:void 0)!=="ESRCH")throw s}return}if(e==="SIGTERM"){try{process.kill(r,e)}catch(s){if(s instanceof Error&&s.code==="ESRCH")return;throw s}return}let o=["/PID",String(r),"/T"];e==="SIGKILL"&&o.push("/F"),await iP("taskkill",o,{timeout:ye.POWERSHELL_COMMAND,windowsHide:!0})}ce();var p_=3e4,jr=null;function cP(){let e=Ns().pruneDeadEntries();e>0&&y.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function f_(){jr===null&&(jr=setInterval(cP,p_),jr.unref(),y.debug("SYSTEM","Health checker started",{intervalMs:p_}))}function m_(){jr!==null&&(clearInterval(jr),jr=null,y.debug("SYSTEM","Health checker stopped"))}Xe();var uP=je.workerPid(),bu=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(),js({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,f_()}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}m_(),this.stopPromise=l_({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}},lP=new bu(Ns());function Eu(){return lP}function js(t={}){let e=t.pidFilePath??uP;if(!(0,sr.existsSync)(e))return"missing";let r=null;try{r=JSON.parse((0,sr.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,sr.rmSync)(e,{force:!0}),"invalid"}return vu(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,sr.rmSync)(e,{force:!0}),"stale")}io();Xe();Fr();ce();ce();var ir=Tt(require("path"),1),__=require("os"),Ke=require("fs"),Ls=require("child_process");ce();ce();ce();Xe();var AN=je.dataDir(),h_=je.workerPid();function g_(t){return t?/(^|[\\/])bun(\.exe)?$/i.test(t.trim()):!1}function dP(t,e){let r=e==="win32"?`where ${t}`:`which ${t}`,n;try{n=(0,Ls.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 wu;function y_(t={}){let e=Object.keys(t).length===0;if(e&&wu!==void 0)return wu;let r=pP(t);return e&&r!==null&&(wu=r),r}function pP(t){let e=t.platform??process.platform,r=t.execPath??process.execPath;if(g_(r))return r;let n=t.env??process.env,o=t.homeDirectory??(0,__.homedir)(),s=t.pathExists??Ke.existsSync,i=t.lookupInPath??dP,a=e==="win32"?[n.BUN,n.BUN_PATH,ir.default.join(o,".bun","bin","bun.exe"),ir.default.join(o,".bun","bin","bun"),n.USERPROFILE?ir.default.join(n.USERPROFILE,".bun","bin","bun.exe"):void 0,n.LOCALAPPDATA?ir.default.join(n.LOCALAPPDATA,"bun","bun.exe"):void 0,n.LOCALAPPDATA?ir.default.join(n.LOCALAPPDATA,"bun","bin","bun.exe"):void 0]:[n.BUN,n.BUN_PATH,ir.default.join(o,".bun","bin","bun"),"/usr/local/bin/bun","/opt/homebrew/bin/bun","/home/linuxbrew/.linuxbrew/bin/bun","/usr/bin/bun","/snap/bin/bun"];for(let c of a){let u=c?.trim();if(u&&(g_(u)&&s(u)||u.toLowerCase()==="bun"))return u}return i("bun",e)}function Lr(t){return process.platform==="win32"?Math.round(t*2):t}function fP(t,e){let r=n=>n.replace(/'/g,"''");return`Start-Process -FilePath '${r(t)}' -ArgumentList @('"${r(e)}"','--daemon') -WindowStyle Hidden`}function S_(t,e,r={}){Eu().assertCanSpawn("worker daemon");let n=Yn({...process.env,CLAUDE_MEM_WORKER_PORT:String(e),...r}),o=y_();if(!o){y.error("SYSTEM","Bun runtime not found \u2014 install from https://bun.sh and ensure it is on PATH or set BUN env var. The worker daemon requires Bun because it uses bun:sqlite.");return}if(process.platform==="win32"){let l=fP(o,t),d=Buffer.from(l,"utf16le").toString("base64");try{return(0,Ls.execSync)(`powershell -NoProfile -EncodedCommand ${d}`,{stdio:"ignore",windowsHide:!0,env:n}),0}catch(p){let f=p instanceof Error?p:new Error(String(p));y.error("SYSTEM","Failed to spawn worker daemon on Windows",{runtimePath:o},f);return}}let s="/usr/bin/setsid",i=(0,Ke.existsSync)(s),u=Os(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_(){try{if(!(0,Ke.existsSync)(h_))return;let t=new Date;(0,Ke.utimesSync)(h_,t,t)}catch{}}function Us(){return js({logAlive:!1})}var b_=Tt(require("net"),1);ce();Xe();function ku(){return st.loadFromFile(uo).CLAUDE_MEM_WORKER_HOST}function E_(t){return t.startsWith("[")&&t.endsWith("]")?t:t.includes(":")?`[${t}]`:t}async function mP(t,e,r="GET"){let n=await fetch(`http://${E_(ku())}:${t}${e}`,{method:r}),o="";try{o=await n.text()}catch{}return{ok:n.ok,statusCode:n.status,body:o}}async function w_(t){if(process.platform==="win32")try{let e=await fetch(`http://${E_(ku())}:${t}/api/health`);if(e.ok)return!0;y.debug("SYSTEM","Windows health check returned non-ok; falling through to socket probe",{port:t,status:e.status})}catch(e){e instanceof Error?y.debug("SYSTEM","Windows health check threw; falling through to socket probe",{port:t,message:e.message}):y.debug("SYSTEM","Windows health check threw; falling through to socket probe",{port:t,error:String(e)})}return new Promise(e=>{let r=b_.default.createServer(),n=ku();r.once("error",o=>{o.code==="EADDRINUSE"?e(!0):e(!1)}),r.once("listening",()=>{r.close(()=>e(!1))}),r.listen(t,n)})}async function k_(t,e,r,n){let o=Date.now();for(;Date.now()-o<r;){try{if((await mP(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 Gn(t,e=3e4){return k_(t,"/api/health",e,"Service not ready yet, will retry")}function Xn(t,e=3e4){return k_(t,"/api/readiness",e,"Worker not ready yet, will retry")}ce();var qs=require("path"),Je=require("fs");Xe();ce();var hP=9e4;function x_(){return(0,qs.join)(ao(),"spawn.lock")}function xu(){let t=x_(),e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()});for(let r=0;r<2;r++)try{return(0,Je.mkdirSync)((0,qs.dirname)(t),{recursive:!0}),(0,Je.writeFileSync)(t,e,{flag:"wx"}),!0}catch(n){let o=n instanceof Error?n:new Error(String(n)),s=o.code;if(s!=="EEXIST")return y.warn("SYSTEM","Spawn lock write failed for a non-contention reason; failing open (spawning unlocked)",{lockPath:t,code:s},o),!0;if(r>0)return!1;let i;try{i=(0,Je.statSync)(t).mtimeMs}catch{continue}if(Date.now()-i<=hP)return!1;let a;try{a=(0,Je.statSync)(t).mtimeMs}catch{continue}if(a!==i)return!1;try{(0,Je.unlinkSync)(t)}catch{return!1}}return!1}function $u(){let t=x_();try{if(JSON.parse((0,Je.readFileSync)(t,"utf-8")).pid!==process.pid)return;(0,Je.unlinkSync)(t)}catch{}}function T_(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 pj=T_("CLAUDE_MEM_HEALTH_TIMEOUT_MS",Ht(ye.HEALTH_CHECK),{min:500,max:3e5}),fj=T_("CLAUDE_MEM_HOOK_READINESS_TIMEOUT_MS",Ht(ye.HOOK_READINESS_WAIT),{min:0,max:3e5}),gP={min:500,max:3e5};async function Pu(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 Zs=null,Fs=null,Hs=null,Ws=null;function _P(){return Pe.default.join(st.get("CLAUDE_MEM_DATA_DIR"),"settings.json")}function Tu(){return Hs!==null||(Hs=st.loadFromFile(_P())),Hs}function $_(t,e){if(!t)return null;let r=parseInt(t,10);return Number.isFinite(r)&&r>=e.min&&r<=e.max?r:null}function yP(t,e,r){let n=process.env[t];if(n!==void 0){let i=$_(n,r);return i!==null?i:(y.warn("SYSTEM",`Invalid ${t}, using default`,{value:n,min:r.min,max:r.max}),e)}let o=Tu()[t],s=$_(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 Ru(){if(Zs!==null)return Zs;let t=Tu();return Zs=parseInt(t.CLAUDE_MEM_WORKER_PORT,10),Zs}function SP(){return Fs!==null||(Fs=Tu().CLAUDE_MEM_WORKER_HOST),Fs}function vP(){return Ws!==null||(Ws=yP("CLAUDE_MEM_API_TIMEOUT_MS",Ht(ye.API_REQUEST),gP)),Ws}function bP(t){return t.startsWith("[")&&t.endsWith("]")?t:t.includes(":")?`[${t}]`:t}function EP(t){return`http://${bP(SP())}:${Ru()}${t}`}function Vs(t,e={}){let r=e.method??"GET",n=e.timeoutMs??vP(),o=EP(t),s={method:r};return e.headers&&(s.headers=e.headers),e.body&&(s.body=e.body),n>0?Pu(o,s,n):fetch(o,s)}function R_(t){let e=(0,Ae.existsSync)(Pe.default.join(t,"plugin","scripts"))?Pe.default.join(t,"plugin"):t;return Pe.default.join(e,"scripts","worker-service.cjs")}function wP(t,e){let r=d=>{let p=d.split("-")[0].split(".");return[parseInt(p[0],10)||0,parseInt(p[1],10)||0,parseInt(p[2],10)||0]},[n,o,s]=r(t),[i,a,c]=r(e);if(i!==n)return i-n;if(a!==o)return a-o;if(c!==s)return c-s;let u=t.includes("-")?1:0,l=e.includes("-")?1:0;return u!==l?u-l:t<e?1:t>e?-1:0}function kP(t=Pe.default.join(Pe.default.dirname(Pe.default.dirname(co)),"cache","thedotmack","claude-mem")){try{return(0,Ae.readdirSync)(t).filter(e=>/^\d/.test(e)).map(e=>Pe.default.join(t,e)).filter(e=>{try{if(!(0,Ae.statSync)(e).isDirectory())return!1}catch{return!1}return!(0,Ae.existsSync)(Pe.default.join(e,".orphaned_at"))}).map(e=>({scriptPath:R_(e),version:Pe.default.basename(e)}))}catch{return[]}}function P_(t){try{let e=JSON.parse((0,Ae.readFileSync)(t,"utf-8"));return typeof e.version=="string"?e.version:null}catch(e){let r=e.code;return r!=="ENOENT"&&y.debug("SYSTEM","Could not read package version for worker resolution",{packageJsonPath:t,code:r}),null}}function xP(){let t=process.env.CLAUDE_MEM_WORKER_SCRIPT_PATH?.trim();if(t){if((0,Ae.existsSync)(t))return{scriptPath:t,version:null};y.debug("SYSTEM","Ignoring missing CLAUDE_MEM_WORKER_SCRIPT_PATH override",{override:t})}let e=[...kP(),{scriptPath:R_(Pe.default.join(co,"plugin")),version:P_(Pe.default.join(co,"package.json"))},{scriptPath:Pe.default.join(process.cwd(),"plugin","scripts","worker-service.cjs"),version:P_(Pe.default.join(process.cwd(),"package.json"))}];return $P(e)}function $P(t){let e=t.filter(r=>(0,Ae.existsSync)(r.scriptPath));return e.length===0?null:(e.sort((r,n)=>r.version===null&&n.version===null?0:r.version===null?1:n.version===null?-1:wP(r.version,n.version)),e[0])}function z_(){return xP()?.scriptPath??null}var zu=Tt(require("path"),1),Be=require("fs");ce();var PP=120*1e3;function Iu(){return zu.default.join(st.get("CLAUDE_MEM_DATA_DIR"),".worker-start-attempted")}function TP(){if(process.platform!=="win32")return!1;let t=Iu();if(!(0,Be.existsSync)(t))return!1;try{let e=(0,Be.statSync)(t).mtimeMs;return Date.now()-e<PP}catch(e){return e instanceof Error?y.debug("SYSTEM","Could not stat worker spawn lock file",{},e):y.debug("SYSTEM","Could not stat worker spawn lock file",{error:String(e)}),!1}}function RP(){if(process.platform==="win32")try{let t=Iu();(0,Be.mkdirSync)(zu.default.dirname(t),{recursive:!0}),(0,Be.writeFileSync)(t,"","utf-8")}catch{}}function Ks(){if(process.platform==="win32")try{let t=Iu();(0,Be.existsSync)(t)&&(0,Be.unlinkSync)(t)}catch{}}async function I_(t,e){if(!e)return y.error("SYSTEM","ensureWorkerStarted called with empty workerScriptPath \u2014 caller bug"),"dead";if(!(0,Be.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(Us()==="alive"){if(y.info("SYSTEM","Worker PID file points to a live process, skipping duplicate spawn"),await Xn(t,Lr(ye.READINESS_WAIT)))return Ks(),y.info("SYSTEM","Worker became ready while waiting on live PID"),"ready";let a=await Gn(t,1e3),c=Us()==="alive";return!a&&!c?(y.error("SYSTEM","Live PID disappeared before readiness endpoint became available"),"dead"):(y.warn("SYSTEM","Live PID detected but worker did not become ready before timeout"),"warming")}if(await Gn(t,1e3)){Ks();let i=await Xn(t,Lr(ye.READINESS_WAIT));return i||y.warn("SYSTEM","Worker is alive but readiness timed out \u2014 proceeding anyway"),y.info("SYSTEM","Worker already running and healthy"),i?"ready":"warming"}if(await w_(t)){if(y.info("SYSTEM","Port in use, waiting for worker to become healthy"),await Gn(t,Lr(ye.PORT_IN_USE_WAIT))){Ks();let a=await Xn(t,Lr(ye.READINESS_WAIT));return y.info("SYSTEM","Worker is now healthy"),a?"ready":"warming"}return y.error("SYSTEM","Port in use but worker not responding to health checks"),"dead"}if(TP())return y.warn("SYSTEM","Worker unavailable on Windows \u2014 skipping spawn (recent attempt failed within cooldown)"),"dead";let o=xu(),s;try{if(o){if(y.info("SYSTEM","Starting worker daemon",{workerScriptPath:e}),RP(),s=S_(e,t),s===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");if(!await Xn(t,Lr(ye.READINESS_WAIT))){let a=await Gn(t,1e3),c=Us()==="alive",u=s!==void 0&&s>0&&Ve(s);return!a&&!c&&!u?(y.error("SYSTEM",o?"Worker exited before readiness endpoint became available":"Spawn-lock holder never produced a live worker before readiness timed out"),"dead"):(y.warn("SYSTEM",o?"Worker spawned but readiness endpoint not responding within window":"Spawn-lock holder's worker not ready within window"),"warming")}return Ks(),v_(),y.info("SYSTEM",o?"Worker started successfully":"Worker is up (started by another launcher)"),"ready"}finally{o&&$u()}}var qr=require("node:fs/promises"),eo=require("node:path");var C_=require("node:child_process"),it=require("node:fs"),Ye=require("node:path"),Du=require("node:os"),Cu=require("node:module");ce();var HP={},Mu=typeof __filename<"u"?(0,Cu.createRequire)(__filename):(0,Cu.createRequire)(HP.url),zP={".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",".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){let e=t.slice(t.lastIndexOf("."));return zP[e]??"unknown"}var IP={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",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"},OP={markdown:"tree-sitter-markdown"};function D_(t){let e=IP[t];if(!e)return null;let r=OP[t];if(r){try{let n=Mu.resolve(e+"/package.json"),o=(0,Ye.join)((0,Ye.dirname)(n),r);if((0,it.existsSync)((0,Ye.join)(o,"src")))return o}catch{}return null}try{let n=Mu.resolve(e+"/package.json");return(0,Ye.dirname)(n)}catch{return null}}var AP={jsts:`
|
|
86
86
|
(function_declaration name: (identifier) @name) @func
|
|
87
87
|
(lexical_declaration (variable_declarator name: (identifier) @name value: [(arrow_function) (function_expression)])) @const_func
|
|
88
88
|
(class_declaration name: (type_identifier) @name) @cls
|
|
@@ -222,7 +222,7 @@ ${f}`}let a=s.lineStart;for(let u=s.lineStart-1;u>=0;u--){let l=i[u].trim();if(l
|
|
|
222
222
|
${c}`}ce();var WP=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",".lua",".scala",".sc",".sh",".bash",".zsh",".hs",".zig",".css",".scss",".toml",".yml",".yaml",".sql",".md",".mdx"]),VP=new Set(["node_modules",".git","dist","build",".next","__pycache__",".venv","venv","env",".env","target","vendor",".cache",".turbo","coverage",".nyc_output",".claude",".smart-file-read"]),KP=512*1024;async function*H_(t,e,r=20){if(r<=0)return;let n;try{n=await(0,qr.readdir)(t,{withFileTypes:!0})}catch(o){y.debug("WORKER",`walkDir: failed to read directory ${t}`,void 0,o instanceof Error?o:void 0);return}for(let o of n){if(o.name.startsWith(".")&&o.name!=="."||VP.has(o.name))continue;let s=(0,eo.join)(t,o.name);if(o.isDirectory())yield*H_(s,e,r-1);else if(o.isFile()){let i=o.name.slice(o.name.lastIndexOf("."));WP.has(i)&&(yield s)}}}async function JP(t){try{let e=await(0,qr.stat)(t);if(e.size>KP||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 W_(t,e,r={}){let n=r.maxResults||20,o=e.toLowerCase(),s=o.split(/[\s_\-./]+/).filter(g=>g.length>0),i=[];for await(let g of H_(t,t,20)){if(r.filePattern&&!(0,eo.relative)(t,g).toLowerCase().includes(r.filePattern.toLowerCase()))continue;let S=await JP(g);S&&i.push({absolutePath:g,relativePath:(0,eo.relative)(t,g),content:S})}let a=q_(i),c=[],u=[],l=0;for(let[g,S]of a){l+=BP(S);let x=Bs(g.toLowerCase(),s)>0,b=[],$=(k,Se)=>{for(let K of k){let ct=0,Ne="",Pt=Bs(K.name.toLowerCase(),s);Pt>0&&(ct+=Pt*3,Ne="name match"),K.signature.toLowerCase().includes(o)&&(ct+=2,Ne=Ne?`${Ne} + signature`:"signature match"),K.jsdoc&&K.jsdoc.toLowerCase().includes(o)&&(ct+=1,Ne=Ne?`${Ne} + jsdoc`:"jsdoc match"),ct>0&&(x=!0,b.push({filePath:g,symbolName:Se?`${Se}.${K.name}`:K.name,kind:K.kind,signature:K.signature,jsdoc:K.jsdoc,lineStart:K.lineStart,lineEnd:K.lineEnd,matchReason:Ne})),K.children&&$(K.children,K.name)}};$(S.symbols),x&&(c.push(S),u.push(...b))}u.sort((g,S)=>{let v=Bs(g.symbolName.toLowerCase(),s);return Bs(S.symbolName.toLowerCase(),s)-v});let d=u.slice(0,n),p=new Set(d.map(g=>g.filePath)),f=c.filter(g=>p.has(g.filePath)).slice(0,n),m=f.reduce((g,S)=>g+S.foldedTokenEstimate,0);return{foldedFiles:f,matchingSymbols:d,totalFilesScanned:i.length,totalSymbolsFound:l,tokenEstimate:m}}function Bs(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 BP(t){let e=t.symbols.length;for(let r of t.symbols)r.children&&(e+=r.children.length);return e}function V_(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(`
|
|
223
223
|
`);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(`
|
|
224
224
|
`).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(`
|
|
225
|
-
`)}var ju=require("node:fs/promises"),Qs=require("node:fs"),at=require("node:path"),Q_=require("node:os"),ey=require("node:url");var K_="claude";function YP(t){return t.trim().toLowerCase().replace(/\s+/g,"-")}function Ys(t){if(!t)return K_;let e=YP(t);return e?e==="transcript"||e.includes("codex")?"codex":e.includes("cursor")?"cursor":e.includes("claude")?"claude":e:K_}var GP=Ht(ye.API_REQUEST),Ge=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=XP(e.serverBaseUrl),this.apiKey=e.apiKey,this.timeoutMs=e.timeoutMs??GP}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 Ge("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 Ge("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:Nu(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:Nu(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:Nu(e.platformSource)}:{},...e.payload!==void 0?{payload:e.payload}:{}}}async request(e,r,n){if(!this.apiKey||!this.apiKey.trim())throw new Ge("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 Pu(o,s,this.timeoutMs)}catch(c){let u=c instanceof Error?c.message:String(c),l=/timed out|timeout/i.test(u);throw new Ge(l?"timeout":"transport",`Server ${e} ${r} failed: ${u}`,{cause:c})}if(!i.ok){let c=await i.text().catch(()=>"");throw new Ge("http_error",`Server ${e} ${r} returned ${i.status}: ${QP(c,200)}`,{status:i.status})}let a=await i.text();if(!a||a.length===0)return{};try{return JSON.parse(a)}catch(c){let u=c instanceof Error?c:new Error(String(c));throw new Ge("invalid_response",`Server ${e} ${r} returned non-JSON response`,{cause:u})}}};function J_(t){return t instanceof Ge}function XP(t){return t.replace(/\/+$/,"")}function Nu(t){return typeof t=="string"?Ys(t):null}function QP(t,e){return t.length<=e?t:`${t.slice(0,e)}\u2026`}ce();function Xs(){let e=(Ms().CLAUDE_MEM_RUNTIME??"worker").trim().toLowerCase();return e==="server"||e==="server-beta"?"server":"worker"}function B_(){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}}ce();var Y_=["observation_add","observation_record_event","observation_search","observation_context","observation_generation_status","memory_add","memory_search","memory_context"],eT=new Set(Y_);function G_(t,e){return e==="server"?[...t]:(y.debug("SYSTEM","Filtering server-beta-only MCP tools from worker runtime advertisement",{runtime:e,hiddenToolCount:Y_.length}),t.filter(r=>!eT.has(r.name)))}var vT={},tT="13.12.2";console.log=(...t)=>{y.error("CONSOLE","Intercepted console output (MCP protocol protection)",void 0,{args:t})};var ty=!1,ry=(()=>{if(typeof __dirname<"u")return __dirname;try{return(0,at.dirname)((0,ey.fileURLToPath)(vT.url))}catch(t){return ty=!0,y.warn("SYSTEM","mcp-server: failed to resolve module directory from import.meta.url, falling back to process.cwd()",void 0,t instanceof Error?t:new Error(String(t))),process.cwd()}})(),Lu=z_()??(0,at.resolve)(ry,"worker-service.cjs");function rT(){ty&&((0,Qs.existsSync)(Lu)||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:Lu,mcpServerDir:ry}))}async function _t(t,e={}){y.debug("SYSTEM","\u2192 Worker API",void 0,{endpoint:t});try{let r;if(e.body)r=await Vs(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e.body)});else{let n=new URLSearchParams;for(let[o,s]of Object.entries(e.query??{}))s!=null&&n.append(o,String(s));r=await Vs(`${t}?${n}`)}if(!r.ok){let n=await r.text();throw new Error(`Worker API error (${r.status}): ${n}`)}return y.debug("SYSTEM","\u2190 Worker API success",void 0,{endpoint:t}),e.text?{content:[{type:"text",text:await r.text()}]}:e.body?{content:[{type:"text",text:JSON.stringify(await r.json(),null,2)}]}:await r.json()}catch(r){return y.error("SYSTEM","\u2190 Worker API error",{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 nT(){try{return(await Vs("/api/health")).ok}catch(t){return y.debug("SYSTEM","Worker health check failed",{},t instanceof Error?t:new Error(String(t))),!1}}function ny(){if(Xs()!=="server")return null;let e=B_();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 oT(t){return J_(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 Zr(t){return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}function ro(t){let e=ny();if(!e)throw new Ge("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 Ge("missing_api_key",`${t}: ${e.reason}`);return e}function no(t,e){return async r=>{try{return await e(r)}catch(n){let o=n instanceof Error?n:new Error(String(n));return y.warn("SYSTEM",`${t} failed`,void 0,o),oT(n)}}}var sT=no("observation_add",async t=>{let e=ro("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 Zr(o)});function ti(t){return typeof t=="string"?Ys(t):null}var iT=no("observation_record_event",async t=>{let e=ro("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:ti(t.platformSource)}:{},...t.payload!==void 0?{payload:t.payload}:{},...t.generate!==void 0?{generate:t.generate}:{}},o=await e.client.recordEvent(n);return Zr(o)}),aT=no("observation_search",async t=>{let e=ro("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:ti(t.platformSource)}:{}},o=await e.client.searchObservations(n);return Zr(o)}),cT=no("observation_context",async t=>{let e=ro("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:ti(t.platformSource)}:{}},o=await e.client.contextObservations(n);return Zr(o)});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}:_t("/api/context/inject",{query:{projects:e.join(","),...t.platformSource!==void 0?{platformSource:ti(t.platformSource)}:{},...t.full!==void 0?{full:t.full}:{},...t.colors!==void 0?{colors:t.colors}:{}},text:!0})}var dT=no("observation_generation_status",async t=>{let e=ro("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 Zr(n)});async function pT(){if(await nT())return!0;y.warn("SYSTEM","Worker not available, attempting auto-start for MCP client"),rT();try{let t=Ru(),e=await I_(t,Lu);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 oy=[{name:"important_workflow",description:`3-LAYER WORKFLOW (ALWAYS FOLLOW):
|
|
225
|
+
`)}var ju=require("node:fs/promises"),Qs=require("node:fs"),at=require("node:path"),Q_=require("node:os"),ey=require("node:url");var K_="claude";function YP(t){return t.trim().toLowerCase().replace(/\s+/g,"-")}function Ys(t){if(!t)return K_;let e=YP(t);return e?e==="transcript"||e.includes("codex")?"codex":e.includes("cursor")?"cursor":e.includes("claude")?"claude":e:K_}var GP=Ht(ye.API_REQUEST),Ge=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=XP(e.serverBaseUrl),this.apiKey=e.apiKey,this.timeoutMs=e.timeoutMs??GP}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 Ge("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 Ge("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:Nu(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:Nu(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:Nu(e.platformSource)}:{},...e.payload!==void 0?{payload:e.payload}:{}}}async request(e,r,n){if(!this.apiKey||!this.apiKey.trim())throw new Ge("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 Pu(o,s,this.timeoutMs)}catch(c){let u=c instanceof Error?c.message:String(c),l=/timed out|timeout/i.test(u);throw new Ge(l?"timeout":"transport",`Server ${e} ${r} failed: ${u}`,{cause:c})}if(!i.ok){let c=await i.text().catch(()=>"");throw new Ge("http_error",`Server ${e} ${r} returned ${i.status}: ${QP(c,200)}`,{status:i.status})}let a=await i.text();if(!a||a.length===0)return{};try{return JSON.parse(a)}catch(c){let u=c instanceof Error?c:new Error(String(c));throw new Ge("invalid_response",`Server ${e} ${r} returned non-JSON response`,{cause:u})}}};function J_(t){return t instanceof Ge}function XP(t){return t.replace(/\/+$/,"")}function Nu(t){return typeof t=="string"?Ys(t):null}function QP(t,e){return t.length<=e?t:`${t.slice(0,e)}\u2026`}ce();function Xs(){let e=(Ms().CLAUDE_MEM_RUNTIME??"worker").trim().toLowerCase();return e==="server"||e==="server-beta"?"server":"worker"}function B_(){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}}ce();var Y_=["observation_add","observation_record_event","observation_search","observation_context","observation_generation_status","memory_add","memory_search","memory_context"],eT=new Set(Y_);function G_(t,e){return e==="server"?[...t]:(y.debug("SYSTEM","Filtering server-beta-only MCP tools from worker runtime advertisement",{runtime:e,hiddenToolCount:Y_.length}),t.filter(r=>!eT.has(r.name)))}var vT={},tT="13.12.3";console.log=(...t)=>{y.error("CONSOLE","Intercepted console output (MCP protocol protection)",void 0,{args:t})};var ty=!1,ry=(()=>{if(typeof __dirname<"u")return __dirname;try{return(0,at.dirname)((0,ey.fileURLToPath)(vT.url))}catch(t){return ty=!0,y.warn("SYSTEM","mcp-server: failed to resolve module directory from import.meta.url, falling back to process.cwd()",void 0,t instanceof Error?t:new Error(String(t))),process.cwd()}})(),Lu=z_()??(0,at.resolve)(ry,"worker-service.cjs");function rT(){ty&&((0,Qs.existsSync)(Lu)||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:Lu,mcpServerDir:ry}))}async function _t(t,e={}){y.debug("SYSTEM","\u2192 Worker API",void 0,{endpoint:t});try{let r;if(e.body)r=await Vs(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e.body)});else{let n=new URLSearchParams;for(let[o,s]of Object.entries(e.query??{}))s!=null&&n.append(o,String(s));r=await Vs(`${t}?${n}`)}if(!r.ok){let n=await r.text();throw new Error(`Worker API error (${r.status}): ${n}`)}return y.debug("SYSTEM","\u2190 Worker API success",void 0,{endpoint:t}),e.text?{content:[{type:"text",text:await r.text()}]}:e.body?{content:[{type:"text",text:JSON.stringify(await r.json(),null,2)}]}:await r.json()}catch(r){return y.error("SYSTEM","\u2190 Worker API error",{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 nT(){try{return(await Vs("/api/health")).ok}catch(t){return y.debug("SYSTEM","Worker health check failed",{},t instanceof Error?t:new Error(String(t))),!1}}function ny(){if(Xs()!=="server")return null;let e=B_();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 oT(t){return J_(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 Zr(t){return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}function ro(t){let e=ny();if(!e)throw new Ge("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 Ge("missing_api_key",`${t}: ${e.reason}`);return e}function no(t,e){return async r=>{try{return await e(r)}catch(n){let o=n instanceof Error?n:new Error(String(n));return y.warn("SYSTEM",`${t} failed`,void 0,o),oT(n)}}}var sT=no("observation_add",async t=>{let e=ro("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 Zr(o)});function ti(t){return typeof t=="string"?Ys(t):null}var iT=no("observation_record_event",async t=>{let e=ro("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:ti(t.platformSource)}:{},...t.payload!==void 0?{payload:t.payload}:{},...t.generate!==void 0?{generate:t.generate}:{}},o=await e.client.recordEvent(n);return Zr(o)}),aT=no("observation_search",async t=>{let e=ro("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:ti(t.platformSource)}:{}},o=await e.client.searchObservations(n);return Zr(o)}),cT=no("observation_context",async t=>{let e=ro("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:ti(t.platformSource)}:{}},o=await e.client.contextObservations(n);return Zr(o)});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}:_t("/api/context/inject",{query:{projects:e.join(","),...t.platformSource!==void 0?{platformSource:ti(t.platformSource)}:{},...t.full!==void 0?{full:t.full}:{},...t.colors!==void 0?{colors:t.colors}:{}},text:!0})}var dT=no("observation_generation_status",async t=>{let e=ro("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 Zr(n)});async function pT(){if(await nT())return!0;y.warn("SYSTEM","Worker not available, attempting auto-start for MCP client"),rT();try{let t=Ru(),e=await I_(t,Lu);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 oy=[{name:"important_workflow",description:`3-LAYER WORKFLOW (ALWAYS FOLLOW):
|
|
226
226
|
1. search(query) \u2192 Get index with IDs (~50-100 tokens/result)
|
|
227
227
|
2. timeline(anchor=ID) \u2192 Get context around interesting results
|
|
228
228
|
3. get_observations([IDs]) \u2192 Fetch full details ONLY for filtered IDs
|