claude-mem 12.1.2 → 12.1.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/package.json
CHANGED
package/plugin/package.json
CHANGED
|
@@ -194,7 +194,7 @@ ${f}`}let s=i.lineStart;for(let u=i.lineStart-1;u>=0;u--){let l=a[u].trim();if(l
|
|
|
194
194
|
${c}`}var vb=new Set([".js",".jsx",".ts",".tsx",".mjs",".cjs",".py",".pyw",".go",".rs",".rb",".java",".cs",".cpp",".cc",".cxx",".c",".h",".hpp",".hh",".swift",".kt",".kts",".php",".vue",".svelte",".ex",".exs",".lua",".scala",".sc",".sh",".bash",".zsh",".hs",".zig",".css",".scss",".toml",".yml",".yaml",".sql",".md",".mdx"]),oj=new Set(["node_modules",".git","dist","build",".next","__pycache__",".venv","venv","env",".env","target","vendor",".cache",".turbo","coverage",".nyc_output",".claude",".smart-file-read"]),ij=512*1024;async function*_b(t,e,r=20,n){if(r<=0)return;let o;try{o=await(0,Zn.readdir)(t,{withFileTypes:!0})}catch{return}for(let i of o){if(i.name.startsWith(".")&&i.name!=="."||oj.has(i.name))continue;let a=(0,Ai.join)(t,i.name);if(i.isDirectory())yield*_b(a,e,r-1,n);else if(i.isFile()){let s=i.name.slice(i.name.lastIndexOf("."));(vb.has(s)||n&&n.has(s))&&(yield a)}}}async function aj(t){try{let e=await(0,Zn.stat)(t);if(e.size>ij||e.size===0)return null;let r=await(0,Zn.readFile)(t,"utf-8");return r.slice(0,1e3).includes("\0")?null:r}catch{return null}}async function yb(t,e,r={}){let n=r.maxResults||20,o=e.toLowerCase(),i=o.split(/[\s_\-./]+/).filter(x=>x.length>0),a=r.projectRoot||t,s=Mi(a),c=new Set;for(let x of Object.values(s.grammars))for(let b of x.extensions)vb.has(b)||c.add(b);let u=[];for await(let x of _b(t,t,20,c.size>0?c:void 0)){if(r.filePattern&&!(0,Ai.relative)(t,x).toLowerCase().includes(r.filePattern.toLowerCase()))continue;let b=await aj(x);b&&u.push({absolutePath:x,relativePath:(0,Ai.relative)(t,x),content:b})}let l=mb(u,a),d=[],p=[],f=0;for(let[x,b]of l){f+=sj(b);let T=rc(x.toLowerCase(),i)>0,qe=[],Ve=(Fn,qr)=>{for(let _e of Fn){let tr=0,mt="",qn=rc(_e.name.toLowerCase(),i);qn>0&&(tr+=qn*3,mt="name match"),_e.signature.toLowerCase().includes(o)&&(tr+=2,mt=mt?`${mt} + signature`:"signature match"),_e.jsdoc&&_e.jsdoc.toLowerCase().includes(o)&&(tr+=1,mt=mt?`${mt} + jsdoc`:"jsdoc match"),tr>0&&(T=!0,qe.push({filePath:x,symbolName:qr?`${qr}.${_e.name}`:_e.name,kind:_e.kind,signature:_e.signature,jsdoc:_e.jsdoc,lineStart:_e.lineStart,lineEnd:_e.lineEnd,matchReason:mt})),_e.children&&Ve(_e.children,_e.name)}};Ve(b.symbols),T&&(d.push(b),p.push(...qe))}p.sort((x,b)=>{let N=rc(x.symbolName.toLowerCase(),i);return rc(b.symbolName.toLowerCase(),i)-N});let h=p.slice(0,n),g=new Set(h.map(x=>x.filePath)),y=d.filter(x=>g.has(x.filePath)).slice(0,n),S=y.reduce((x,b)=>x+b.foldedTokenEstimate,0);return{foldedFiles:y,matchingSymbols:h,totalFilesScanned:u.length,totalSymbolsFound:f,tokenEstimate:S}}function rc(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,i=0;for(let a of n){let s=t.indexOf(a,o);s!==-1&&(i++,o=s+1)}i===n.length&&(r+=1)}return r}function sj(t){let e=t.symbols.length;for(let r of t.symbols)r.children&&(e+=r.children.length);return e}function $b(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(`
|
|
195
195
|
`);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(`
|
|
196
196
|
`).find(i=>i.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(Un(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(`
|
|
197
|
-
`)}var gm=require("node:fs/promises"),Sb=require("node:fs"),Fr=require("node:path"),kb=require("node:url"),vj={},cj="12.1.
|
|
197
|
+
`)}var gm=require("node:fs/promises"),Sb=require("node:fs"),Fr=require("node:path"),kb=require("node:url"),vj={},cj="12.1.3";console.log=(...t)=>{E.error("CONSOLE","Intercepted console output (MCP protocol protection)",void 0,{args:t})};var wb=!1,Eb=(()=>{if(typeof __dirname<"u")return __dirname;try{return(0,Fr.dirname)((0,kb.fileURLToPath)(vj.url))}catch{return wb=!0,process.cwd()}})(),vm=(0,Fr.resolve)(Eb,"worker-service.cjs");function uj(){wb&&((0,Sb.existsSync)(vm)||E.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:vm,mcpServerDir:Eb}))}var bb={search:"/api/search",timeline:"/api/timeline"};async function hm(t,e){E.debug("SYSTEM","\u2192 Worker API",void 0,{endpoint:t,params:e});try{let r=new URLSearchParams;for(let[a,s]of Object.entries(e))s!=null&&r.append(a,String(s));let n=`${t}?${r}`,o=await Xs(n);if(!o.ok){let a=await o.text();throw new Error(`Worker API error (${o.status}): ${a}`)}let i=await o.json();return E.debug("SYSTEM","\u2190 Worker API success",void 0,{endpoint:t}),i}catch(r){return E.error("SYSTEM","\u2190 Worker API error",{endpoint:t},r),{content:[{type:"text",text:`Error calling Worker API: ${r instanceof Error?r.message:String(r)}`}],isError:!0}}}async function Ln(t,e){E.debug("HTTP","Worker API request (POST)",void 0,{endpoint:t});try{let r=await Xs(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok){let o=await r.text();throw new Error(`Worker API error (${r.status}): ${o}`)}let n=await r.json();return E.debug("HTTP","Worker API success (POST)",void 0,{endpoint:t}),{content:[{type:"text",text:JSON.stringify(n,null,2)}]}}catch(r){return E.error("HTTP","Worker API error (POST)",{endpoint:t},r),{content:[{type:"text",text:`Error calling Worker API: ${r instanceof Error?r.message:String(r)}`}],isError:!0}}}async function lj(){try{return(await Xs("/api/health")).ok}catch(t){return E.debug("SYSTEM","Worker health check failed",{},t),!1}}async function dj(){if(await lj())return!0;E.warn("SYSTEM","Worker not available, attempting auto-start for MCP client"),uj();try{let t=Yf(),e=await rb(t,vm);return e||E.error("SYSTEM","Worker auto-start returned false \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}catch(t){return E.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),!1}}var Ib=[{name:"__IMPORTANT",description:`3-LAYER WORKFLOW (ALWAYS FOLLOW):
|
|
198
198
|
1. search(query) \u2192 Get index with IDs (~50-100 tokens/result)
|
|
199
199
|
2. timeline(anchor=ID) \u2192 Get context around interesting results
|
|
200
200
|
3. get_observations([IDs]) \u2192 Fetch full details ONLY for filtered IDs
|
|
@@ -1054,7 +1054,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
1054
1054
|
JOIN sdk_sessions s ON up.content_session_id = s.content_session_id
|
|
1055
1055
|
WHERE s.project = ?
|
|
1056
1056
|
`).get(r);_.info("CHROMA_SYNC","Backfilling user prompts",{project:r,missing:v.length,existing:n.prompts.size,total:y.count});let b=[];for(let S of v)b.push(this.formatUserPromptDoc(S));for(let S=0;S<b.length;S+=this.BATCH_SIZE){let x=b.slice(S,S+this.BATCH_SIZE);await this.addDocuments(x),_.debug("CHROMA_SYNC","Backfill progress",{project:r,progress:`${Math.min(S+this.BATCH_SIZE,b.length)}/${b.length}`})}_.info("CHROMA_SYNC","Smart backfill complete",{project:r,synced:{observationDocs:u.length,summaryDocs:f.length,promptDocs:b.length},skipped:{observations:n.observations.size,summaries:n.summaries.size,prompts:n.prompts.size}})}catch(s){throw _.error("CHROMA_SYNC","Backfill failed",{project:r},s),new Error(`Backfill failed: ${s instanceof Error?s.message:String(s)}`)}finally{i.close()}}async queryChroma(e,r,n){await this.ensureCollectionExists();try{let s=await Rs.getInstance().callTool("chroma_query_documents",{collection_name:this.collectionName,query_texts:[e],n_results:r,...n&&{where:n},include:["documents","metadatas","distances"]}),o=[],a=new Set,c=s?.ids?.[0]||[],u=s?.metadatas?.[0]||[],l=s?.distances?.[0]||[],d=[],p=[];for(let m=0;m<c.length;m++){let f=c[m],h=f.match(/obs_(\d+)_/),g=f.match(/summary_(\d+)_/),v=f.match(/prompt_(\d+)/),y=null;h?y=parseInt(h[1],10):g?y=parseInt(g[1],10):v&&(y=parseInt(v[1],10)),y!==null&&!a.has(y)&&(a.add(y),o.push(y),d.push(u[m]??null),p.push(l[m]??0))}return{ids:o,distances:p,metadatas:d}}catch(i){let s=i instanceof Error?i.message:String(i);throw s.includes("ECONNREFUSED")||s.includes("ENOTFOUND")||s.includes("fetch failed")||s.includes("subprocess closed")||s.includes("timed out")?(this.collectionCreated=!1,_.error("CHROMA_SYNC","Connection lost during query",{project:this.project,query:e},i),new Error(`Chroma query failed - connection lost: ${s}`)):(_.error("CHROMA_SYNC","Query failed",{project:this.project,query:e},i),i)}}static async backfillAllProjects(){let e=new Os,r=new t("claude-mem");try{let n=e.db.prepare("SELECT DISTINCT project FROM observations WHERE project IS NOT NULL AND project != ?").all("");_.info("CHROMA_SYNC",`Backfill check for ${n.length} projects`);for(let{project:i}of n)try{await r.ensureBackfilled(i)}catch(s){_.error("CHROMA_SYNC",`Backfill failed for project: ${i}`,{},s)}}finally{await r.close(),e.close()}}async close(){_.info("CHROMA_SYNC","ChromaSync closed",{project:this.project})}};var nk=Oe(require("path"),1),Jn=require("fs");Q();fn();Yt();var bi=Oe(require("path"),1),XE=require("os"),Ht=require("fs"),Ps=require("child_process"),sD=require("util");Q();fn();var rD=(0,sD.promisify)(Ps.exec),YE=bi.default.join((0,XE.homedir)(),".claude-mem"),Cs=bi.default.join(YE,"worker.pid");var nD=30;function iD(t){return t?/(^|[\\/])bun(\.exe)?$/i.test(t.trim()):!1}function HQ(t,e){let r=e==="win32"?`where ${t}`:`which ${t}`;try{return(0,Ps.execSync)(r,{stdio:["ignore","pipe","ignore"],encoding:"utf-8",windowsHide:!0}).split(/\r?\n/).map(s=>s.trim()).find(s=>s.length>0)||null}catch{return null}}var KE;function ZQ(t={}){let e=Object.keys(t).length===0;if(e&&KE!==void 0)return KE;let r=BQ(t);return e&&r!==null&&(KE=r),r}function BQ(t){let e=t.platform??process.platform,r=t.execPath??process.execPath;if(iD(r))return r;let n=t.env??process.env,i=t.homeDirectory??(0,XE.homedir)(),s=t.pathExists??Ht.existsSync,o=t.lookupInPath??HQ,a=e==="win32"?[n.BUN,n.BUN_PATH,bi.default.join(i,".bun","bin","bun.exe"),bi.default.join(i,".bun","bin","bun"),n.USERPROFILE?bi.default.join(n.USERPROFILE,".bun","bin","bun.exe"):void 0,n.LOCALAPPDATA?bi.default.join(n.LOCALAPPDATA,"bun","bun.exe"):void 0,n.LOCALAPPDATA?bi.default.join(n.LOCALAPPDATA,"bun","bin","bun.exe"):void 0]:[n.BUN,n.BUN_PATH,bi.default.join(i,".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&&(iD(u)&&s(u)||u.toLowerCase()==="bun"))return u}return o("bun",e)}function oD(t){(0,Ht.mkdirSync)(YE,{recursive:!0}),(0,Ht.writeFileSync)(Cs,JSON.stringify(t,null,2))}function QE(){if(!(0,Ht.existsSync)(Cs))return null;try{return JSON.parse((0,Ht.readFileSync)(Cs,"utf-8"))}catch(t){return _.warn("SYSTEM","Failed to parse PID file",{path:Cs},t),null}}function ua(){if((0,Ht.existsSync)(Cs))try{(0,Ht.unlinkSync)(Cs)}catch(t){_.warn("SYSTEM","Failed to remove PID file",{path:Cs},t)}}function Wi(t){return process.platform==="win32"?Math.round(t*2):t}function GQ(t){if(!t||t.trim()==="")return-1;let e=t.trim(),r=0,n=e.match(/^(\d+)-(\d+):(\d+):(\d+)$/);if(n)return r=parseInt(n[1],10)*24*60+parseInt(n[2],10)*60+parseInt(n[3],10),r;let i=e.match(/^(\d+):(\d+):(\d+)$/);if(i)return r=parseInt(i[1],10)*60+parseInt(i[2],10),r;let s=e.match(/^(\d+):(\d+)$/);return s?parseInt(s[1],10):-1}var JE=["worker-service.cjs","chroma-mcp"],WQ=["mcp-server.cjs"];async function aD(){let t=process.platform==="win32",e=process.pid,r=[],n=[...JE,...WQ],i=new Set([e]);process.ppid&&process.ppid>0&&i.add(process.ppid);try{if(t){let o=`powershell -NoProfile -NonInteractive -Command "Get-CimInstance Win32_Process -Filter '(${n.map(d=>`CommandLine LIKE '%${d}%'`).join(" OR ")}) AND ProcessId != ${e}' | Select-Object ProcessId, CommandLine, CreationDate | ConvertTo-Json"`,{stdout:a}=await rD(o,{timeout:mr.POWERSHELL_COMMAND,windowsHide:!0});if(!a.trim()||a.trim()==="null"){_.debug("SYSTEM","No orphaned claude-mem processes found (Windows)");return}let c=JSON.parse(a),u=Array.isArray(c)?c:[c],l=Date.now();for(let d of u){let p=d.ProcessId;if(!Number.isInteger(p)||p<=0||i.has(p))continue;let m=d.CommandLine||"";if(JE.some(h=>m.includes(h)))r.push(p),_.debug("SYSTEM","Found orphaned process (aggressive)",{pid:p,commandLine:m.substring(0,80)});else{let h=d.CreationDate?.match(/\/Date\((\d+)\)\//);if(h){let g=parseInt(h[1],10),v=(l-g)/(1e3*60);v>=nD&&(r.push(p),_.debug("SYSTEM","Found orphaned process (age-gated)",{pid:p,ageMinutes:Math.round(v)}))}}}}else{let s=n.join("|"),{stdout:o}=await rD(`ps -eo pid,etime,command | grep -E "${s}" | grep -v grep || true`);if(!o.trim()){_.debug("SYSTEM","No orphaned claude-mem processes found (Unix)");return}let a=o.trim().split(`
|
|
1057
|
-
`);for(let c of a){let u=c.trim().match(/^(\d+)\s+(\S+)\s+(.*)$/);if(!u)continue;let l=parseInt(u[1],10),d=u[2],p=u[3];if(!Number.isInteger(l)||l<=0||i.has(l))continue;if(JE.some(f=>p.includes(f)))r.push(l),_.debug("SYSTEM","Found orphaned process (aggressive)",{pid:l,command:p.substring(0,80)});else{let f=GQ(d);f>=nD&&(r.push(l),_.debug("SYSTEM","Found orphaned process (age-gated)",{pid:l,ageMinutes:f,command:p.substring(0,80)}))}}}}catch(s){_.error("SYSTEM","Failed to enumerate orphaned processes during aggressive cleanup",{},s);return}if(r.length!==0){if(_.info("SYSTEM","Aggressive startup cleanup: killing orphaned processes",{platform:t?"Windows":"Unix",count:r.length,pids:r}),t){for(let s of r)if(!(!Number.isInteger(s)||s<=0))try{(0,Ps.execSync)(`taskkill /PID ${s} /T /F`,{timeout:mr.POWERSHELL_COMMAND,stdio:"ignore",windowsHide:!0})}catch(o){_.debug("SYSTEM","Failed to kill process, may have already exited",{pid:s},o)}}else for(let s of r)try{process.kill(s,"SIGKILL")}catch(o){_.debug("SYSTEM","Process already exited",{pid:s},o)}_.info("SYSTEM","Aggressive startup cleanup complete",{count:r.length})}}var VQ=".chroma-cleaned-v10.3";function cD(t){let e=t??YE,r=bi.default.join(e,VQ),n=bi.default.join(e,"chroma");if((0,Ht.existsSync)(r)){_.debug("SYSTEM","Chroma migration marker exists, skipping wipe");return}_.warn("SYSTEM","Running one-time chroma data wipe (upgrade from pre-v10.3)",{chromaDir:n}),(0,Ht.existsSync)(n)&&((0,Ht.rmSync)(n,{recursive:!0,force:!0}),_.info("SYSTEM","Chroma data directory removed",{chromaDir:n})),(0,Ht.mkdirSync)(e,{recursive:!0}),(0,Ht.writeFileSync)(r,new Date().toISOString()),_.info("SYSTEM","Chroma migration marker written",{markerPath:r})}function mg(t,e,r={}){let n=process.platform==="win32";_t().assertCanSpawn("worker daemon");let i=Cn({...process.env,CLAUDE_MEM_WORKER_PORT:String(e),...r}),s=ZQ();if(!s){_.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(n){let c=`Start-Process -FilePath '${s.replace(/'/g,"''")}' -ArgumentList @('${t.replace(/'/g,"''")}','--daemon') -WindowStyle Hidden`,u=Buffer.from(c,"utf16le").toString("base64");try{return(0,Ps.execSync)(`powershell -NoProfile -EncodedCommand ${u}`,{stdio:"ignore",windowsHide:!0,env:i}),0}catch(l){_.error("SYSTEM","Failed to spawn worker daemon on Windows",{runtimePath:s},l);return}}let o="/usr/bin/setsid";if((0,Ht.existsSync)(o)){let c=(0,Ps.spawn)(o,[s,t,"--daemon"],{detached:!0,stdio:"ignore",env:i});return c.pid===void 0?void 0:(c.unref(),c.pid)}let a=(0,Ps.spawn)(s,[t,"--daemon"],{detached:!0,stdio:"ignore",env:i});if(a.pid!==void 0)return a.unref(),a.pid}function uD(t){if(t===0)return!0;if(!Number.isInteger(t)||t<0)return!1;try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function lD(){try{if(!(0,Ht.existsSync)(Cs))return;let t=new Date;(0,Ht.utimesSync)(Cs,t,t)}catch{}}function dD(){return BE({logAlive:!1})}var pD=Oe(require("net"),1);Q();$t();async function mD(t,e,r="GET"){let n=await fetch(`http://127.0.0.1:${t}${e}`,{method:r}),i="";try{i=await n.text()}catch{}return{ok:n.ok,statusCode:n.status,body:i}}async function Bc(t){if(process.platform==="win32")try{return(await fetch(`http://127.0.0.1:${t}/api/health`)).ok}catch{return!1}return new Promise(e=>{let r=pD.default.createServer();r.once("error",n=>{n.code==="EADDRINUSE"?e(!0):e(!1)}),r.once("listening",()=>{r.close(()=>e(!1))}),r.listen(t,"127.0.0.1")})}async function fD(t,e,r,n){let i=Date.now();for(;Date.now()-i<r;){try{if((await mD(t,e)).ok)return!0}catch(s){_.debug("SYSTEM",n,{},s)}await new Promise(s=>setTimeout(s,500))}return!1}function yo(t,e=3e4){return fD(t,"/api/health",e,"Service not ready yet, will retry")}function ek(t,e=3e4){return fD(t,"/api/readiness",e,"Worker not ready yet, will retry")}async function tk(t,e=1e4){let r=Date.now();for(;Date.now()-r<e;){if(!await Bc(t))return!0;await new Promise(n=>setTimeout(n,500))}return!1}async function rk(t){try{let e=await mD(t,"/api/admin/shutdown","POST");return e.ok?!0:(_.warn("SYSTEM","Shutdown request returned error",{status:e.statusCode}),!1)}catch(e){return e instanceof Error&&e.message?.includes("ECONNREFUSED")?(_.debug("SYSTEM","Worker already stopped",{},e),!1):(_.error("SYSTEM","Shutdown request failed unexpectedly",{},e),!1)}}var KQ=120*1e3;function ik(){return nk.default.join(ge.get("CLAUDE_MEM_DATA_DIR"),".worker-start-attempted")}function JQ(){if(process.platform!=="win32")return!1;let t=ik();if(!(0,Jn.existsSync)(t))return!1;try{let e=(0,Jn.statSync)(t).mtimeMs;return Date.now()-e<KQ}catch{return!1}}function XQ(){if(process.platform==="win32")try{let t=ik();(0,Jn.mkdirSync)(nk.default.dirname(t),{recursive:!0}),(0,Jn.writeFileSync)(t,"","utf-8")}catch{}}function fg(){if(process.platform==="win32")try{let t=ik();(0,Jn.existsSync)(t)&&(0,Jn.unlinkSync)(t)}catch{}}async function hD(t,e){return e?(0,Jn.existsSync)(e)?dD()==="alive"?(_.info("SYSTEM","Worker PID file points to a live process, skipping duplicate spawn"),await yo(t,Wi(mr.PORT_IN_USE_WAIT))?(fg(),_.info("SYSTEM","Worker became healthy while waiting on live PID"),!0):(_.warn("SYSTEM","Live PID detected but worker did not become healthy before timeout"),!1)):await yo(t,1e3)?(fg(),await ek(t,Wi(mr.READINESS_WAIT))||_.warn("SYSTEM","Worker is alive but readiness timed out \u2014 proceeding anyway"),_.info("SYSTEM","Worker already running and healthy"),!0):await Bc(t)?(_.info("SYSTEM","Port in use, waiting for worker to become healthy"),await yo(t,Wi(mr.PORT_IN_USE_WAIT))?(fg(),_.info("SYSTEM","Worker is now healthy"),!0):(_.error("SYSTEM","Port in use but worker not responding to health checks"),!1)):JQ()?(_.warn("SYSTEM","Worker unavailable on Windows \u2014 skipping spawn (recent attempt failed within cooldown)"),!1):(_.info("SYSTEM","Starting worker daemon",{workerScriptPath:e}),XQ(),mg(e,t)===void 0?(_.error("SYSTEM","Failed to spawn worker daemon"),!1):await yo(t,Wi(mr.POST_SPAWN_WAIT))?(await ek(t,Wi(mr.READINESS_WAIT))||_.warn("SYSTEM","Worker is alive but readiness timed out \u2014 proceeding anyway"),fg(),lD(),_.info("SYSTEM","Worker started successfully"),!0):(ua(),_.error("SYSTEM","Worker failed to start (health check timeout)"),!1)):(_.error("SYSTEM","ensureWorkerStarted: worker script not found at expected path \u2014 likely a partial install or build artifact missing",{workerScriptPath:e}),!1):(_.error("SYSTEM","ensureWorkerStarted called with empty workerScriptPath \u2014 caller bug"),!1)}var hg=require("fs"),sk=require("path"),gD=require("os"),YQ="claude-mem@thedotmack";function gg(){try{let t=process.env.CLAUDE_CONFIG_DIR||(0,sk.join)((0,gD.homedir)(),".claude"),e=(0,sk.join)(t,"settings.json");if(!(0,hg.existsSync)(e))return!1;let r=(0,hg.readFileSync)(e,"utf-8");return JSON.parse(r)?.enabledPlugins?.[YQ]===!1}catch{return!1}}Q();async function vD(t){_.info("SYSTEM","Shutdown initiated"),t.server&&(await QQ(t.server),_.info("SYSTEM","HTTP server closed")),await t.sessionManager.shutdownAll(),t.mcpClient&&(await t.mcpClient.close(),_.info("SYSTEM","MCP client closed")),t.chromaMcpManager&&(_.info("SHUTDOWN","Stopping Chroma MCP connection..."),await t.chromaMcpManager.stop(),_.info("SHUTDOWN","Chroma MCP connection stopped")),t.dbManager&&await t.dbManager.close(),await VM(),_.info("SYSTEM","Worker shutdown complete")}async function QQ(t){t.closeAllConnections(),process.platform==="win32"&&await new Promise(e=>setTimeout(e,500)),await new Promise((e,r)=>{t.close(n=>n?r(n):e())}),process.platform==="win32"&&(await new Promise(e=>setTimeout(e,500)),_.info("SYSTEM","Waited for Windows port cleanup"))}var $6=Oe(wv(),1),d$=Oe(require("fs"),1),Dp=Oe(require("path"),1);var f6=["search","context","summarize","import","export"],h6=["workflow","search_params","examples","all"];Q();var c$=Oe(wv(),1),S6=Oe(b6(),1),x6=Oe(require("path"),1);$t();Q();function u$(t){let e=[];e.push(c$.default.json({limit:"50mb"})),e.push((0,S6.default)({origin:(i,s)=>{!i||i.startsWith("http://localhost:")||i.startsWith("http://127.0.0.1:")?s(null,!0):s(new Error("CORS not allowed"))},methods:["GET","HEAD","POST","PUT","PATCH","DELETE"],allowedHeaders:["Content-Type","Authorization","X-Requested-With"],credentials:!1})),e.push((i,s,o)=>{let c=[".html",".js",".css",".svg",".png",".jpg",".jpeg",".webp",".woff",".woff2",".ttf",".eot"].some(f=>i.path.endsWith(f)),u=i.path==="/api/logs";if(i.path.startsWith("/health")||i.path==="/"||c||u)return o();let l=Date.now(),d=`${i.method}-${Date.now()}`,p=t(i.method,i.path,i.body);_.debug("HTTP",`\u2192 ${i.method} ${i.path}`,{requestId:d},p);let m=s.send.bind(s);s.send=function(f){let h=Date.now()-l;return _.debug("HTTP",`\u2190 ${s.statusCode} ${i.path}`,{requestId:d,duration:`${h}ms`}),m(f)},o()});let r=hn(),n=x6.default.join(r,"plugin","ui");return e.push(c$.default.static(n)),e}function Mp(t,e,r){let n=t.ip||t.connection.remoteAddress||"";if(!(n==="127.0.0.1"||n==="::1"||n==="::ffff:127.0.0.1"||n==="localhost")){_.warn("SECURITY","Admin endpoint access denied - not localhost",{endpoint:t.path,clientIp:n,method:t.method}),e.status(403).json({error:"Forbidden",message:"Admin endpoints are only accessible from localhost"});return}r()}function l$(t,e,r){if(!r||Object.keys(r).length===0||e.includes("/init"))return"";if(e.includes("/observations")){let n=r.tool_name||"?",i=r.tool_input;return`tool=${_.formatTool(n,i)}`}return e.includes("/summarize")?"requesting summary":""}Q();var bn=class extends Error{constructor(r,n=500,i,s){super(r);this.statusCode=n;this.code=i;this.details=s;this.name="AppError"}statusCode;code;details};function w6(t,e,r,n){let i={error:t,message:e};return r&&(i.code=r),n&&(i.details=n),i}var E6=(t,e,r,n)=>{let i=t instanceof bn?t.statusCode:500;_.error("HTTP",`Error handling ${e.method} ${e.path}`,{statusCode:i,error:t.message,code:t instanceof bn?t.code:void 0},t);let s=w6(t.name||"Error",t.message,t instanceof bn?t.code:void 0,t instanceof bn?t.details:void 0);r.status(i).json(s)};function k6(t,e){e.status(404).json(w6("NotFound",`Cannot ${t.method} ${t.path}`))}var T6="12.1.2",Ev=class{app;server=null;options;startTime=Date.now();constructor(e){this.options=e,this.app=(0,$6.default)(),this.setupMiddleware(),this.setupCoreRoutes()}getHttpServer(){return this.server}async listen(e,r){return new Promise((n,i)=>{this.server=this.app.listen(e,r,()=>{_.info("SYSTEM","HTTP server started",{host:r,port:e,pid:process.pid}),n()}),this.server.on("error",i)})}async close(){this.server&&(this.server.closeAllConnections(),process.platform==="win32"&&await new Promise(e=>setTimeout(e,500)),await new Promise((e,r)=>{this.server.close(n=>n?r(n):e())}),process.platform==="win32"&&await new Promise(e=>setTimeout(e,500)),this.server=null,_.info("SYSTEM","HTTP server closed"))}registerRoutes(e){e.setupRoutes(this.app)}finalizeRoutes(){this.app.use(k6),this.app.use(E6)}setupMiddleware(){u$(l$).forEach(r=>this.app.use(r))}setupCoreRoutes(){this.app.get("/api/health",(e,r)=>{r.status(200).json({status:"ok",version:T6,workerPath:this.options.workerPath,uptime:Date.now()-this.startTime,managed:process.env.CLAUDE_MEM_MANAGED==="true",hasIpc:typeof process.send=="function",platform:process.platform,pid:process.pid,initialized:this.options.getInitializationComplete(),mcpReady:this.options.getMcpReady(),ai:this.options.getAiStatus()})}),this.app.get("/api/readiness",(e,r)=>{this.options.getInitializationComplete()?r.status(200).json({status:"ready",mcpReady:this.options.getMcpReady()}):r.status(503).json({status:"initializing",message:"Worker is still initializing, please retry"})}),this.app.get("/api/version",(e,r)=>{r.status(200).json({version:T6})}),this.app.get("/api/instructions",async(e,r)=>{let n=e.query.topic||"all",i=e.query.operation;if(n&&!h6.includes(n))return r.status(400).json({error:"Invalid topic"});try{let s;if(i){if(!f6.includes(i))return r.status(400).json({error:"Invalid operation"});let o=Dp.default.resolve(__dirname,"../skills/mem-search/operations"),a=Dp.default.resolve(o,`${i}.md`);if(!a.startsWith(o+Dp.default.sep))return r.status(400).json({error:"Invalid request"});s=await d$.promises.readFile(a,"utf-8")}else{let o=Dp.default.join(__dirname,"../skills/mem-search/SKILL.md"),a=await d$.promises.readFile(o,"utf-8");s=this.extractInstructionSection(a,n)}r.json({content:[{type:"text",text:s}]})}catch{r.status(404).json({error:"Instruction not found"})}}),this.app.post("/api/admin/restart",Mp,async(e,r)=>{r.json({status:"restarting"}),process.platform==="win32"&&process.env.CLAUDE_MEM_MANAGED==="true"&&process.send?(_.info("SYSTEM","Sending restart request to wrapper"),process.send({type:"restart"})):setTimeout(async()=>{try{await this.options.onRestart()}finally{process.exit(0)}},100)}),this.app.post("/api/admin/shutdown",Mp,async(e,r)=>{r.json({status:"shutting_down"}),process.platform==="win32"&&process.env.CLAUDE_MEM_MANAGED==="true"&&process.send?(_.info("SYSTEM","Sending shutdown request to wrapper"),process.send({type:"shutdown"})):setTimeout(async()=>{try{await this.options.onShutdown()}finally{process.exit(0)}},100)}),this.app.get("/api/admin/doctor",Mp,(e,r)=>{let o=_t().getRegistry().getAll().map(f=>({id:f.id,pid:f.pid,type:f.type,status:Pn(f.pid)?"alive":"dead",startedAt:f.startedAt})),a=o.filter(f=>f.status==="dead").map(f=>f.pid),c=!Object.keys(process.env).some(f=>LE.has(f)||zE.some(h=>f.startsWith(h))),u=Date.now()-this.startTime,l=Math.floor(u/1e3),d=Math.floor(l/3600),p=Math.floor(l%3600/60),m=d>0?`${d}h ${p}m`:`${p}m`;r.json({supervisor:{running:!0,pid:process.pid,uptime:m},processes:o,health:{deadProcessPids:a,envClean:c}})})}extractInstructionSection(e,r){let n={workflow:this.extractBetween(e,"## The Workflow","## Search Parameters"),search_params:this.extractBetween(e,"## Search Parameters","## Examples"),examples:this.extractBetween(e,"## Examples","## Why This Workflow"),all:e};return n[r]||n.all}extractBetween(e,r,n){let i=e.indexOf(r),s=e.indexOf(n);return i===-1?e:s===-1?e.substring(i):e.substring(i,s).trim()}};var Pt=Oe(require("path"),1),zp=require("os"),Jt=require("fs"),O6=require("child_process"),C6=require("util");Q();Rr();$t();var ti=require("fs"),jp=require("path");Q();function I6(t){try{return(0,ti.existsSync)(t)?JSON.parse((0,ti.readFileSync)(t,"utf-8")):{}}catch(e){return _.error("CONFIG","Failed to read Cursor registry, using empty registry",{file:t,error:e instanceof Error?e.message:String(e)}),{}}}function R6(t,e){let r=(0,jp.join)(t,"..");(0,ti.mkdirSync)(r,{recursive:!0}),(0,ti.writeFileSync)(t,JSON.stringify(e,null,2))}function p$(t,e){let r=(0,jp.join)(t,".cursor","rules"),n=(0,jp.join)(r,"claude-mem-context.mdc"),i=`${n}.tmp`;(0,ti.mkdirSync)(r,{recursive:!0});let s=`---
|
|
1057
|
+
`);for(let c of a){let u=c.trim().match(/^(\d+)\s+(\S+)\s+(.*)$/);if(!u)continue;let l=parseInt(u[1],10),d=u[2],p=u[3];if(!Number.isInteger(l)||l<=0||i.has(l))continue;if(JE.some(f=>p.includes(f)))r.push(l),_.debug("SYSTEM","Found orphaned process (aggressive)",{pid:l,command:p.substring(0,80)});else{let f=GQ(d);f>=nD&&(r.push(l),_.debug("SYSTEM","Found orphaned process (age-gated)",{pid:l,ageMinutes:f,command:p.substring(0,80)}))}}}}catch(s){_.error("SYSTEM","Failed to enumerate orphaned processes during aggressive cleanup",{},s);return}if(r.length!==0){if(_.info("SYSTEM","Aggressive startup cleanup: killing orphaned processes",{platform:t?"Windows":"Unix",count:r.length,pids:r}),t){for(let s of r)if(!(!Number.isInteger(s)||s<=0))try{(0,Ps.execSync)(`taskkill /PID ${s} /T /F`,{timeout:mr.POWERSHELL_COMMAND,stdio:"ignore",windowsHide:!0})}catch(o){_.debug("SYSTEM","Failed to kill process, may have already exited",{pid:s},o)}}else for(let s of r)try{process.kill(s,"SIGKILL")}catch(o){_.debug("SYSTEM","Process already exited",{pid:s},o)}_.info("SYSTEM","Aggressive startup cleanup complete",{count:r.length})}}var VQ=".chroma-cleaned-v10.3";function cD(t){let e=t??YE,r=bi.default.join(e,VQ),n=bi.default.join(e,"chroma");if((0,Ht.existsSync)(r)){_.debug("SYSTEM","Chroma migration marker exists, skipping wipe");return}_.warn("SYSTEM","Running one-time chroma data wipe (upgrade from pre-v10.3)",{chromaDir:n}),(0,Ht.existsSync)(n)&&((0,Ht.rmSync)(n,{recursive:!0,force:!0}),_.info("SYSTEM","Chroma data directory removed",{chromaDir:n})),(0,Ht.mkdirSync)(e,{recursive:!0}),(0,Ht.writeFileSync)(r,new Date().toISOString()),_.info("SYSTEM","Chroma migration marker written",{markerPath:r})}function mg(t,e,r={}){let n=process.platform==="win32";_t().assertCanSpawn("worker daemon");let i=Cn({...process.env,CLAUDE_MEM_WORKER_PORT:String(e),...r}),s=ZQ();if(!s){_.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(n){let c=`Start-Process -FilePath '${s.replace(/'/g,"''")}' -ArgumentList @('${t.replace(/'/g,"''")}','--daemon') -WindowStyle Hidden`,u=Buffer.from(c,"utf16le").toString("base64");try{return(0,Ps.execSync)(`powershell -NoProfile -EncodedCommand ${u}`,{stdio:"ignore",windowsHide:!0,env:i}),0}catch(l){_.error("SYSTEM","Failed to spawn worker daemon on Windows",{runtimePath:s},l);return}}let o="/usr/bin/setsid";if((0,Ht.existsSync)(o)){let c=(0,Ps.spawn)(o,[s,t,"--daemon"],{detached:!0,stdio:"ignore",env:i});return c.pid===void 0?void 0:(c.unref(),c.pid)}let a=(0,Ps.spawn)(s,[t,"--daemon"],{detached:!0,stdio:"ignore",env:i});if(a.pid!==void 0)return a.unref(),a.pid}function uD(t){if(t===0)return!0;if(!Number.isInteger(t)||t<0)return!1;try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function lD(){try{if(!(0,Ht.existsSync)(Cs))return;let t=new Date;(0,Ht.utimesSync)(Cs,t,t)}catch{}}function dD(){return BE({logAlive:!1})}var pD=Oe(require("net"),1);Q();$t();async function mD(t,e,r="GET"){let n=await fetch(`http://127.0.0.1:${t}${e}`,{method:r}),i="";try{i=await n.text()}catch{}return{ok:n.ok,statusCode:n.status,body:i}}async function Bc(t){if(process.platform==="win32")try{return(await fetch(`http://127.0.0.1:${t}/api/health`)).ok}catch{return!1}return new Promise(e=>{let r=pD.default.createServer();r.once("error",n=>{n.code==="EADDRINUSE"?e(!0):e(!1)}),r.once("listening",()=>{r.close(()=>e(!1))}),r.listen(t,"127.0.0.1")})}async function fD(t,e,r,n){let i=Date.now();for(;Date.now()-i<r;){try{if((await mD(t,e)).ok)return!0}catch(s){_.debug("SYSTEM",n,{},s)}await new Promise(s=>setTimeout(s,500))}return!1}function yo(t,e=3e4){return fD(t,"/api/health",e,"Service not ready yet, will retry")}function ek(t,e=3e4){return fD(t,"/api/readiness",e,"Worker not ready yet, will retry")}async function tk(t,e=1e4){let r=Date.now();for(;Date.now()-r<e;){if(!await Bc(t))return!0;await new Promise(n=>setTimeout(n,500))}return!1}async function rk(t){try{let e=await mD(t,"/api/admin/shutdown","POST");return e.ok?!0:(_.warn("SYSTEM","Shutdown request returned error",{status:e.statusCode}),!1)}catch(e){return e instanceof Error&&e.message?.includes("ECONNREFUSED")?(_.debug("SYSTEM","Worker already stopped",{},e),!1):(_.error("SYSTEM","Shutdown request failed unexpectedly",{},e),!1)}}var KQ=120*1e3;function ik(){return nk.default.join(ge.get("CLAUDE_MEM_DATA_DIR"),".worker-start-attempted")}function JQ(){if(process.platform!=="win32")return!1;let t=ik();if(!(0,Jn.existsSync)(t))return!1;try{let e=(0,Jn.statSync)(t).mtimeMs;return Date.now()-e<KQ}catch{return!1}}function XQ(){if(process.platform==="win32")try{let t=ik();(0,Jn.mkdirSync)(nk.default.dirname(t),{recursive:!0}),(0,Jn.writeFileSync)(t,"","utf-8")}catch{}}function fg(){if(process.platform==="win32")try{let t=ik();(0,Jn.existsSync)(t)&&(0,Jn.unlinkSync)(t)}catch{}}async function hD(t,e){return e?(0,Jn.existsSync)(e)?dD()==="alive"?(_.info("SYSTEM","Worker PID file points to a live process, skipping duplicate spawn"),await yo(t,Wi(mr.PORT_IN_USE_WAIT))?(fg(),_.info("SYSTEM","Worker became healthy while waiting on live PID"),!0):(_.warn("SYSTEM","Live PID detected but worker did not become healthy before timeout"),!1)):await yo(t,1e3)?(fg(),await ek(t,Wi(mr.READINESS_WAIT))||_.warn("SYSTEM","Worker is alive but readiness timed out \u2014 proceeding anyway"),_.info("SYSTEM","Worker already running and healthy"),!0):await Bc(t)?(_.info("SYSTEM","Port in use, waiting for worker to become healthy"),await yo(t,Wi(mr.PORT_IN_USE_WAIT))?(fg(),_.info("SYSTEM","Worker is now healthy"),!0):(_.error("SYSTEM","Port in use but worker not responding to health checks"),!1)):JQ()?(_.warn("SYSTEM","Worker unavailable on Windows \u2014 skipping spawn (recent attempt failed within cooldown)"),!1):(_.info("SYSTEM","Starting worker daemon",{workerScriptPath:e}),XQ(),mg(e,t)===void 0?(_.error("SYSTEM","Failed to spawn worker daemon"),!1):await yo(t,Wi(mr.POST_SPAWN_WAIT))?(await ek(t,Wi(mr.READINESS_WAIT))||_.warn("SYSTEM","Worker is alive but readiness timed out \u2014 proceeding anyway"),fg(),lD(),_.info("SYSTEM","Worker started successfully"),!0):(ua(),_.error("SYSTEM","Worker failed to start (health check timeout)"),!1)):(_.error("SYSTEM","ensureWorkerStarted: worker script not found at expected path \u2014 likely a partial install or build artifact missing",{workerScriptPath:e}),!1):(_.error("SYSTEM","ensureWorkerStarted called with empty workerScriptPath \u2014 caller bug"),!1)}var hg=require("fs"),sk=require("path"),gD=require("os"),YQ="claude-mem@thedotmack";function gg(){try{let t=process.env.CLAUDE_CONFIG_DIR||(0,sk.join)((0,gD.homedir)(),".claude"),e=(0,sk.join)(t,"settings.json");if(!(0,hg.existsSync)(e))return!1;let r=(0,hg.readFileSync)(e,"utf-8");return JSON.parse(r)?.enabledPlugins?.[YQ]===!1}catch{return!1}}Q();async function vD(t){_.info("SYSTEM","Shutdown initiated"),t.server&&(await QQ(t.server),_.info("SYSTEM","HTTP server closed")),await t.sessionManager.shutdownAll(),t.mcpClient&&(await t.mcpClient.close(),_.info("SYSTEM","MCP client closed")),t.chromaMcpManager&&(_.info("SHUTDOWN","Stopping Chroma MCP connection..."),await t.chromaMcpManager.stop(),_.info("SHUTDOWN","Chroma MCP connection stopped")),t.dbManager&&await t.dbManager.close(),await VM(),_.info("SYSTEM","Worker shutdown complete")}async function QQ(t){t.closeAllConnections(),process.platform==="win32"&&await new Promise(e=>setTimeout(e,500)),await new Promise((e,r)=>{t.close(n=>n?r(n):e())}),process.platform==="win32"&&(await new Promise(e=>setTimeout(e,500)),_.info("SYSTEM","Waited for Windows port cleanup"))}var $6=Oe(wv(),1),d$=Oe(require("fs"),1),Dp=Oe(require("path"),1);var f6=["search","context","summarize","import","export"],h6=["workflow","search_params","examples","all"];Q();var c$=Oe(wv(),1),S6=Oe(b6(),1),x6=Oe(require("path"),1);$t();Q();function u$(t){let e=[];e.push(c$.default.json({limit:"50mb"})),e.push((0,S6.default)({origin:(i,s)=>{!i||i.startsWith("http://localhost:")||i.startsWith("http://127.0.0.1:")?s(null,!0):s(new Error("CORS not allowed"))},methods:["GET","HEAD","POST","PUT","PATCH","DELETE"],allowedHeaders:["Content-Type","Authorization","X-Requested-With"],credentials:!1})),e.push((i,s,o)=>{let c=[".html",".js",".css",".svg",".png",".jpg",".jpeg",".webp",".woff",".woff2",".ttf",".eot"].some(f=>i.path.endsWith(f)),u=i.path==="/api/logs";if(i.path.startsWith("/health")||i.path==="/"||c||u)return o();let l=Date.now(),d=`${i.method}-${Date.now()}`,p=t(i.method,i.path,i.body);_.debug("HTTP",`\u2192 ${i.method} ${i.path}`,{requestId:d},p);let m=s.send.bind(s);s.send=function(f){let h=Date.now()-l;return _.debug("HTTP",`\u2190 ${s.statusCode} ${i.path}`,{requestId:d,duration:`${h}ms`}),m(f)},o()});let r=hn(),n=x6.default.join(r,"plugin","ui");return e.push(c$.default.static(n)),e}function Mp(t,e,r){let n=t.ip||t.connection.remoteAddress||"";if(!(n==="127.0.0.1"||n==="::1"||n==="::ffff:127.0.0.1"||n==="localhost")){_.warn("SECURITY","Admin endpoint access denied - not localhost",{endpoint:t.path,clientIp:n,method:t.method}),e.status(403).json({error:"Forbidden",message:"Admin endpoints are only accessible from localhost"});return}r()}function l$(t,e,r){if(!r||Object.keys(r).length===0||e.includes("/init"))return"";if(e.includes("/observations")){let n=r.tool_name||"?",i=r.tool_input;return`tool=${_.formatTool(n,i)}`}return e.includes("/summarize")?"requesting summary":""}Q();var bn=class extends Error{constructor(r,n=500,i,s){super(r);this.statusCode=n;this.code=i;this.details=s;this.name="AppError"}statusCode;code;details};function w6(t,e,r,n){let i={error:t,message:e};return r&&(i.code=r),n&&(i.details=n),i}var E6=(t,e,r,n)=>{let i=t instanceof bn?t.statusCode:500;_.error("HTTP",`Error handling ${e.method} ${e.path}`,{statusCode:i,error:t.message,code:t instanceof bn?t.code:void 0},t);let s=w6(t.name||"Error",t.message,t instanceof bn?t.code:void 0,t instanceof bn?t.details:void 0);r.status(i).json(s)};function k6(t,e){e.status(404).json(w6("NotFound",`Cannot ${t.method} ${t.path}`))}var T6="12.1.3",Ev=class{app;server=null;options;startTime=Date.now();constructor(e){this.options=e,this.app=(0,$6.default)(),this.setupMiddleware(),this.setupCoreRoutes()}getHttpServer(){return this.server}async listen(e,r){return new Promise((n,i)=>{this.server=this.app.listen(e,r,()=>{_.info("SYSTEM","HTTP server started",{host:r,port:e,pid:process.pid}),n()}),this.server.on("error",i)})}async close(){this.server&&(this.server.closeAllConnections(),process.platform==="win32"&&await new Promise(e=>setTimeout(e,500)),await new Promise((e,r)=>{this.server.close(n=>n?r(n):e())}),process.platform==="win32"&&await new Promise(e=>setTimeout(e,500)),this.server=null,_.info("SYSTEM","HTTP server closed"))}registerRoutes(e){e.setupRoutes(this.app)}finalizeRoutes(){this.app.use(k6),this.app.use(E6)}setupMiddleware(){u$(l$).forEach(r=>this.app.use(r))}setupCoreRoutes(){this.app.get("/api/health",(e,r)=>{r.status(200).json({status:"ok",version:T6,workerPath:this.options.workerPath,uptime:Date.now()-this.startTime,managed:process.env.CLAUDE_MEM_MANAGED==="true",hasIpc:typeof process.send=="function",platform:process.platform,pid:process.pid,initialized:this.options.getInitializationComplete(),mcpReady:this.options.getMcpReady(),ai:this.options.getAiStatus()})}),this.app.get("/api/readiness",(e,r)=>{this.options.getInitializationComplete()?r.status(200).json({status:"ready",mcpReady:this.options.getMcpReady()}):r.status(503).json({status:"initializing",message:"Worker is still initializing, please retry"})}),this.app.get("/api/version",(e,r)=>{r.status(200).json({version:T6})}),this.app.get("/api/instructions",async(e,r)=>{let n=e.query.topic||"all",i=e.query.operation;if(n&&!h6.includes(n))return r.status(400).json({error:"Invalid topic"});try{let s;if(i){if(!f6.includes(i))return r.status(400).json({error:"Invalid operation"});let o=Dp.default.resolve(__dirname,"../skills/mem-search/operations"),a=Dp.default.resolve(o,`${i}.md`);if(!a.startsWith(o+Dp.default.sep))return r.status(400).json({error:"Invalid request"});s=await d$.promises.readFile(a,"utf-8")}else{let o=Dp.default.join(__dirname,"../skills/mem-search/SKILL.md"),a=await d$.promises.readFile(o,"utf-8");s=this.extractInstructionSection(a,n)}r.json({content:[{type:"text",text:s}]})}catch{r.status(404).json({error:"Instruction not found"})}}),this.app.post("/api/admin/restart",Mp,async(e,r)=>{r.json({status:"restarting"}),process.platform==="win32"&&process.env.CLAUDE_MEM_MANAGED==="true"&&process.send?(_.info("SYSTEM","Sending restart request to wrapper"),process.send({type:"restart"})):setTimeout(async()=>{try{await this.options.onRestart()}finally{process.exit(0)}},100)}),this.app.post("/api/admin/shutdown",Mp,async(e,r)=>{r.json({status:"shutting_down"}),process.platform==="win32"&&process.env.CLAUDE_MEM_MANAGED==="true"&&process.send?(_.info("SYSTEM","Sending shutdown request to wrapper"),process.send({type:"shutdown"})):setTimeout(async()=>{try{await this.options.onShutdown()}finally{process.exit(0)}},100)}),this.app.get("/api/admin/doctor",Mp,(e,r)=>{let o=_t().getRegistry().getAll().map(f=>({id:f.id,pid:f.pid,type:f.type,status:Pn(f.pid)?"alive":"dead",startedAt:f.startedAt})),a=o.filter(f=>f.status==="dead").map(f=>f.pid),c=!Object.keys(process.env).some(f=>LE.has(f)||zE.some(h=>f.startsWith(h))),u=Date.now()-this.startTime,l=Math.floor(u/1e3),d=Math.floor(l/3600),p=Math.floor(l%3600/60),m=d>0?`${d}h ${p}m`:`${p}m`;r.json({supervisor:{running:!0,pid:process.pid,uptime:m},processes:o,health:{deadProcessPids:a,envClean:c}})})}extractInstructionSection(e,r){let n={workflow:this.extractBetween(e,"## The Workflow","## Search Parameters"),search_params:this.extractBetween(e,"## Search Parameters","## Examples"),examples:this.extractBetween(e,"## Examples","## Why This Workflow"),all:e};return n[r]||n.all}extractBetween(e,r,n){let i=e.indexOf(r),s=e.indexOf(n);return i===-1?e:s===-1?e.substring(i):e.substring(i,s).trim()}};var Pt=Oe(require("path"),1),zp=require("os"),Jt=require("fs"),O6=require("child_process"),C6=require("util");Q();Rr();$t();var ti=require("fs"),jp=require("path");Q();function I6(t){try{return(0,ti.existsSync)(t)?JSON.parse((0,ti.readFileSync)(t,"utf-8")):{}}catch(e){return _.error("CONFIG","Failed to read Cursor registry, using empty registry",{file:t,error:e instanceof Error?e.message:String(e)}),{}}}function R6(t,e){let r=(0,jp.join)(t,"..");(0,ti.mkdirSync)(r,{recursive:!0}),(0,ti.writeFileSync)(t,JSON.stringify(e,null,2))}function p$(t,e){let r=(0,jp.join)(t,".cursor","rules"),n=(0,jp.join)(r,"claude-mem-context.mdc"),i=`${n}.tmp`;(0,ti.mkdirSync)(r,{recursive:!0});let s=`---
|
|
1058
1058
|
alwaysApply: true
|
|
1059
1059
|
description: "Claude-mem context from past sessions (auto-updated)"
|
|
1060
1060
|
---
|
|
@@ -1467,7 +1467,7 @@ ${r}
|
|
|
1467
1467
|
${e}
|
|
1468
1468
|
${n}`}function xle(t,e,r){let n=Bt.default.resolve(t);if(n.includes("/.git/")||n.includes("\\.git\\")||n.endsWith("/.git")||n.endsWith("\\.git"))return;let i=r??oF(),s=Bt.default.join(t,i),o=`${s}.tmp`;if(!(0,$i.existsSync)(t)){_.debug("FOLDER_INDEX","Skipping non-existent folder",{folderPath:t});return}let a="";(0,$i.existsSync)(s)&&(a=(0,$i.readFileSync)(s,"utf-8"));let c=b$(a,e);(0,$i.writeFileSync)(o,c),(0,$i.renameSync)(o,s)}function wle(t){let e=[];e.push("# Recent Activity"),e.push("");let r=t.split(`
|
|
1469
1469
|
`),n=[],i="",s=null;for(let a of r){let c=a.match(/^###\s+(.+)$/);if(c){let l=c[1].trim(),d=new Date(l);isNaN(d.getTime())||(s=d);continue}let u=a.match(/^\|\s*(#[S]?\d+)\s*\|\s*([^|]+)\s*\|\s*([^|]+)\s*\|\s*([^|]+)\s*\|\s*([^|]+)\s*\|/);if(u){let[,l,d,p,m,f]=u,h;d.trim()==="\u2033"||d.trim()==='"'?h=i:(h=d.trim(),i=h);let g=s?new Date(s):new Date,v=h.match(/(\d+):(\d+)\s*(AM|PM)/i),y=g.getTime();if(v){let b=parseInt(v[1],10),S=parseInt(v[2],10),x=v[3].toUpperCase()==="PM";x&&b!==12&&(b+=12),!x&&b===12&&(b=0),g.setHours(b,S,0,0),y=g.getTime()}n.push({id:l.trim(),time:h,typeEmoji:p.trim(),title:m.trim(),tokens:f.trim(),epoch:y})}}if(n.length===0)return"";let o=js(n,a=>new Date(a.epoch).toISOString());for(let[a,c]of o){e.push(`### ${a}`),e.push(""),e.push("| ID | Time | T | Title | Read |"),e.push("|----|------|---|-------|------|");let u="";for(let l of c){let d=l.time===u?'"':l.time;u=l.time,e.push(`| ${l.id} | ${d} | ${l.typeEmoji} | ${l.title} | ${l.tokens} |`)}e.push("")}return e.join(`
|
|
1470
|
-
`).trim()}var Ele=new Set(["res",".git","build","node_modules","__pycache__"]);function kle(t){return Bt.default.normalize(t).split(Bt.default.sep).some(n=>Ele.has(n))}function Tle(t){let e=Bt.default.join(t,".git");return(0,$i.existsSync)(e)}function $le(t,e){let r=Bt.default.resolve(t);for(let n of e){let i=Bt.default.resolve(n);if(r===i||r.startsWith(i+Bt.default.sep))return!0}return!1}async function aF(t,e,r,n){let i=ge.loadFromFile(nF),s=parseInt(i.CLAUDE_MEM_CONTEXT_OBSERVATIONS,10)||50,o=oF(i),a=[];try{let l=JSON.parse(i.CLAUDE_MEM_FOLDER_MD_EXCLUDE||"[]");Array.isArray(l)&&(a=l.filter(d=>typeof d=="string"))}catch{_.warn("FOLDER_INDEX","Failed to parse CLAUDE_MEM_FOLDER_MD_EXCLUDE setting")}let c=new Set;for(let l of t){if(!l)continue;let d=Bt.default.basename(l);if(d===iF||d===sF){let p=l;n&&!Bt.default.isAbsolute(l)&&(p=Bt.default.join(n,l));let m=Bt.default.dirname(p);c.add(m),_.debug("FOLDER_INDEX","Detected active context file, will skip folder",{folderPath:m,basename:d})}}let u=new Set;for(let l of t){if(!l||l==="")continue;if(!Sle(l,n)){_.debug("FOLDER_INDEX","Skipping invalid file path",{filePath:l,reason:"Failed path validation"});continue}let d=l;n&&!Bt.default.isAbsolute(l)&&(d=Bt.default.join(n,l));let p=Bt.default.dirname(d);if(p&&p!=="."&&p!=="/"){if(Tle(p)){_.debug("FOLDER_INDEX","Skipping project root CLAUDE.md",{folderPath:p});continue}if(kle(p)){_.debug("FOLDER_INDEX","Skipping unsafe directory for CLAUDE.md",{folderPath:p});continue}if(c.has(p)){_.debug("FOLDER_INDEX","Skipping folder with active CLAUDE.md to avoid race condition",{folderPath:p});continue}if(a.length>0&&$le(p,a)){_.debug("FOLDER_INDEX","Skipping excluded folder",{folderPath:p});continue}u.add(p)}}if(u.size!==0){_.debug("FOLDER_INDEX","Updating CLAUDE.md files",{project:e,folderCount:u.size});for(let l of u)try{let d=await ct(`/api/search/by-file?filePath=${encodeURIComponent(l)}&limit=${s}&project=${encodeURIComponent(e)}&isFolder=true`);if(!d.ok){_.error("FOLDER_INDEX","Failed to fetch timeline",{folderPath:l,status:d.status});continue}let p=await d.json();if(!p.content?.[0]?.text){_.debug("FOLDER_INDEX","No content for folder",{folderPath:l});continue}let m=wle(p.content[0].text),f=Bt.default.join(l,o),h=m.includes("*No recent activity*"),g=(0,$i.existsSync)(f);if(h&&!g){_.debug("FOLDER_INDEX","Skipping empty context file creation",{folderPath:l,targetFilename:o});continue}xle(l,m,o),_.debug("FOLDER_INDEX","Updated context file",{folderPath:l,targetFilename:o})}catch(d){let p=d;_.error("FOLDER_INDEX",`Failed to update ${o}`,{folderPath:l,errorMessage:p.message,errorStack:p.stack})}}}Rr();Yt();$t();function S$(t,e){t?.sseBroadcaster&&t.sseBroadcaster.broadcast({type:"new_observation",observation:e})}function x$(t,e){t?.sseBroadcaster&&t.sseBroadcaster.broadcast({type:"new_summary",summary:e})}function w$(t,e){t.earliestPendingTimestamp=null,e&&typeof e.broadcastProcessingStatus=="function"&&e.broadcastProcessingStatus()}async function Ii(t,e,r,n,i,s,o,a,c,u){e.lastGeneratorActivity=Date.now(),t&&e.conversationHistory.push({role:"assistant",content:t});let l=Q6(t,e.contentSessionId),d=eF(t,e.sessionDbId);if(t.trim()&&l.length===0&&!d&&!/<observation>|<summary>|<skip_summary\b/.test(t)){let v=t.length>200?`${t.slice(0,200)}...`:t;_.warn("PARSER",`${a} returned non-XML response; observation content was discarded`,{sessionId:e.sessionDbId,preview:v})}let p=Ile(d),m=p;if(!p&&l.length>0){let v=l[0];m={request:v.title||`Session observations (${l.length} items)`,investigated:v.narrative||v.facts?.join("; ")||"",learned:v.facts?.join("; ")||"",completed:(v.type==="feature"||v.type==="bugfix")&&v.title||"",next_steps:"",notes:`[Salvaged from ${l.length} observation(s)] AI returned <observation> instead of <summary>`},_.warn("PARSER",`SALVAGED summary from ${l.length} observation(s) \u2014 AI did not output <summary> tags`,{sessionId:e.sessionDbId,agentName:a,observationIds:l.map(y=>y.title).filter(Boolean).slice(0,3)})}let f=r.getSessionStore();if(!e.memorySessionId)throw new Error("Cannot store observations: memorySessionId not yet captured");f.ensureMemorySessionIdRegistered(e.sessionDbId,e.memorySessionId),_.info("DB",`STORING | sessionDbId=${e.sessionDbId} | memorySessionId=${e.memorySessionId} | obsCount=${l.length} | hasSummary=${!!m}`,{sessionId:e.sessionDbId,memorySessionId:e.memorySessionId});let h=f.storeObservations(e.memorySessionId,e.project,l,m,e.lastPromptNumber,s,o??void 0,u);_.info("DB",`STORED | sessionDbId=${e.sessionDbId} | memorySessionId=${e.memorySessionId} | obsCount=${h.observationIds.length} | obsIds=[${h.observationIds.join(",")}] | summaryId=${h.summaryId||"none"}`,{sessionId:e.sessionDbId,memorySessionId:e.memorySessionId}),e.lastSummaryStored=h.summaryId!==null;let g=n.getPendingMessageStore();for(let v of e.processingMessageIds)g.confirmProcessed(v);e.processingMessageIds.length>0&&_.debug("QUEUE",`CONFIRMED_BATCH | sessionDbId=${e.sessionDbId} | count=${e.processingMessageIds.length} | ids=[${e.processingMessageIds.join(",")}]`),e.processingMessageIds=[],await Rle(l,h,e,r,i,s,a,c),await Ole(d,m,h,e,r,i,s,a),w$(e,i)}function Ile(t){return t?{request:t.request||"",investigated:t.investigated||"",learned:t.learned||"",completed:t.completed||"",next_steps:t.next_steps||"",notes:t.notes}:null}async function Rle(t,e,r,n,i,s,o,a){for(let d=0;d<t.length;d++){let p=e.observationIds[d],m=t[d],f=Date.now();n.getChromaSync()?.syncObservation(p,r.contentSessionId,r.project,m,r.lastPromptNumber,e.createdAtEpoch,s).then(()=>{let h=Date.now()-f;_.debug("CHROMA","Observation synced",{obsId:p,duration:`${h}ms`,type:m.type,title:m.title||"(untitled)"})}).catch(h=>{_.error("CHROMA",`${o} chroma sync failed, continuing without vector search`,{obsId:p,type:m.type,title:m.title||"(untitled)"},h)}),S$(i,{id:p,memory_session_id:r.memorySessionId,session_id:r.contentSessionId,platform_source:r.platformSource,type:m.type,title:m.title,subtitle:m.subtitle,text:null,narrative:m.narrative||null,facts:JSON.stringify(m.facts||[]),concepts:JSON.stringify(m.concepts||[]),files_read:JSON.stringify(m.files_read||[]),files_modified:JSON.stringify(m.files_modified||[]),project:r.project,prompt_number:r.lastPromptNumber,created_at_epoch:e.createdAtEpoch})}let u=ge.loadFromFile(lt).CLAUDE_MEM_FOLDER_CLAUDEMD_ENABLED;if(u==="true"||u===!0){let d=[];for(let p of t)d.push(...p.files_modified||[]),d.push(...p.files_read||[]);d.length>0&&aF(d,r.project,Xr(),a).catch(p=>{_.warn("FOLDER_INDEX","CLAUDE.md update failed (non-critical)",{project:r.project},p)})}}async function Ole(t,e,r,n,i,s,o,a){if(!e||!r.summaryId)return;let c=Date.now();i.getChromaSync()?.syncSummary(r.summaryId,n.contentSessionId,n.project,e,n.lastPromptNumber,r.createdAtEpoch,o).then(()=>{let u=Date.now()-c;_.debug("CHROMA","Summary synced",{summaryId:r.summaryId,duration:`${u}ms`,request:e.request||"(no request)"})}).catch(u=>{_.error("CHROMA",`${a} chroma sync failed, continuing without vector search`,{summaryId:r.summaryId,request:e.request||"(no request)"},u)}),x$(s,{id:r.summaryId,session_id:n.contentSessionId,platform_source:n.platformSource,request:e.request,investigated:e.investigated,learned:e.learned,completed:e.completed,next_steps:e.next_steps,notes:e.notes,project:n.project,prompt_number:n.lastPromptNumber,created_at_epoch:r.createdAtEpoch}),N6(n.project,Xr()).catch(u=>{_.warn("CURSOR","Context update failed (non-critical)",{project:n.project},u)})}function Bp(t){let e=Cle(t);return y$.some(r=>e.includes(r))}function Cle(t){return t==null?"":typeof t=="string"?t:t instanceof Error?t.message:typeof t=="object"&&"message"in t?String(t.message):String(t)}function Gp(t){return t==null?!1:t instanceof Error&&t.name==="AbortError"?!0:typeof t=="object"&&"name"in t?t.name==="AbortError":!1}var O$=require("path"),VF=require("url"),KF=require("events"),XF=require("child_process"),YF=require("readline"),Re=Oe(require("fs"),1),QF=require("fs/promises"),iq=require("path"),sq=require("os"),Ca=require("path"),aq=require("process"),cq=require("fs"),uq=require("crypto"),vq=require("crypto"),Bu=require("fs"),C$=require("path"),yq=require("crypto");var Q_e={},Ple=Object.create,Ale=Object.getPrototypeOf,R$=Object.defineProperty,Nle=Object.getOwnPropertyNames,Mle=Object.prototype.hasOwnProperty,LF=(t,e,r)=>{r=t!=null?Ple(Ale(t)):{};let n=e||!t||!t.__esModule?R$(r,"default",{value:t,enumerable:!0}):r;for(let i of Nle(t))Mle.call(n,i)||R$(n,i,{get:()=>t[i],enumerable:!0});return n},ne=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),UF=(t,e)=>{for(var r in e)R$(t,r,{get:e[r],enumerable:!0,configurable:!0,set:n=>e[r]=()=>n})};var Fv=ne(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.regexpCode=t.getEsmExportName=t.getProperty=t.safeStringify=t.stringify=t.strConcat=t.addCodeArg=t.str=t._=t.nil=t._Code=t.Name=t.IDENTIFIER=t._CodeOrName=void 0;class e{}t._CodeOrName=e,t.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class r extends e{constructor(y){if(super(),!t.IDENTIFIER.test(y))throw new Error("CodeGen: name must be a valid identifier");this.str=y}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}t.Name=r;class n extends e{constructor(y){super(),this._items=typeof y=="string"?[y]:y}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let y=this._items[0];return y===""||y==='""'}get str(){var y;return(y=this._str)!==null&&y!==void 0?y:this._str=this._items.reduce((b,S)=>`${b}${S}`,"")}get names(){var y;return(y=this._names)!==null&&y!==void 0?y:this._names=this._items.reduce((b,S)=>(S instanceof r&&(b[S.str]=(b[S.str]||0)+1),b),{})}}t._Code=n,t.nil=new n("");function i(v,...y){let b=[v[0]],S=0;for(;S<y.length;)a(b,y[S]),b.push(v[++S]);return new n(b)}t._=i;var s=new n("+");function o(v,...y){let b=[m(v[0])],S=0;for(;S<y.length;)b.push(s),a(b,y[S]),b.push(s,m(v[++S]));return c(b),new n(b)}t.str=o;function a(v,y){y instanceof n?v.push(...y._items):y instanceof r?v.push(y):v.push(d(y))}t.addCodeArg=a;function c(v){let y=1;for(;y<v.length-1;){if(v[y]===s){let b=u(v[y-1],v[y+1]);if(b!==void 0){v.splice(y-1,3,b);continue}v[y++]="+"}y++}}function u(v,y){if(y==='""')return v;if(v==='""')return y;if(typeof v=="string")return y instanceof r||v[v.length-1]!=='"'?void 0:typeof y!="string"?`${v.slice(0,-1)}${y}"`:y[0]==='"'?v.slice(0,-1)+y.slice(1):void 0;if(typeof y=="string"&&y[0]==='"'&&!(v instanceof r))return`"${v}${y.slice(1)}`}function l(v,y){return y.emptyStr()?v:v.emptyStr()?y:o`${v}${y}`}t.strConcat=l;function d(v){return typeof v=="number"||typeof v=="boolean"||v===null?v:m(Array.isArray(v)?v.join(","):v)}function p(v){return new n(m(v))}t.stringify=p;function m(v){return JSON.stringify(v).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}t.safeStringify=m;function f(v){return typeof v=="string"&&t.IDENTIFIER.test(v)?new n(`.${v}`):i`[${v}]`}t.getProperty=f;function h(v){if(typeof v=="string"&&t.IDENTIFIER.test(v))return new n(`${v}`);throw new Error(`CodeGen: invalid export name: ${v}, use explicit $id name mapping`)}t.getEsmExportName=h;function g(v){return new n(v.toString())}t.regexpCode=g}),cF=ne(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ValueScope=t.ValueScopeName=t.Scope=t.varKinds=t.UsedValueState=void 0;var e=Fv();class r extends Error{constructor(u){super(`CodeGen: "code" for ${u} not defined`),this.value=u.value}}var n;(function(c){c[c.Started=0]="Started",c[c.Completed=1]="Completed"})(n||(t.UsedValueState=n={})),t.varKinds={const:new e.Name("const"),let:new e.Name("let"),var:new e.Name("var")};class i{constructor({prefixes:u,parent:l}={}){this._names={},this._prefixes=u,this._parent=l}toName(u){return u instanceof e.Name?u:this.name(u)}name(u){return new e.Name(this._newName(u))}_newName(u){let l=this._names[u]||this._nameGroup(u);return`${u}${l.index++}`}_nameGroup(u){var l,d;if(!((d=(l=this._parent)===null||l===void 0?void 0:l._prefixes)===null||d===void 0)&&d.has(u)||this._prefixes&&!this._prefixes.has(u))throw new Error(`CodeGen: prefix "${u}" is not allowed in this scope`);return this._names[u]={prefix:u,index:0}}}t.Scope=i;class s extends e.Name{constructor(u,l){super(l),this.prefix=u}setValue(u,{property:l,itemIndex:d}){this.value=u,this.scopePath=(0,e._)`.${new e.Name(l)}[${d}]`}}t.ValueScopeName=s;var o=(0,e._)`\n`;class a extends i{constructor(u){super(u),this._values={},this._scope=u.scope,this.opts={...u,_n:u.lines?o:e.nil}}get(){return this._scope}name(u){return new s(u,this._newName(u))}value(u,l){var d;if(l.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let p=this.toName(u),{prefix:m}=p,f=(d=l.key)!==null&&d!==void 0?d:l.ref,h=this._values[m];if(h){let y=h.get(f);if(y)return y}else h=this._values[m]=new Map;h.set(f,p);let g=this._scope[m]||(this._scope[m]=[]),v=g.length;return g[v]=l.ref,p.setValue(l,{property:m,itemIndex:v}),p}getValue(u,l){let d=this._values[u];if(d)return d.get(l)}scopeRefs(u,l=this._values){return this._reduceValues(l,d=>{if(d.scopePath===void 0)throw new Error(`CodeGen: name "${d}" has no value`);return(0,e._)`${u}${d.scopePath}`})}scopeCode(u=this._values,l,d){return this._reduceValues(u,p=>{if(p.value===void 0)throw new Error(`CodeGen: name "${p}" has no value`);return p.value.code},l,d)}_reduceValues(u,l,d={},p){let m=e.nil;for(let f in u){let h=u[f];if(!h)continue;let g=d[f]=d[f]||new Map;h.forEach(v=>{if(g.has(v))return;g.set(v,n.Started);let y=l(v);if(y){let b=this.opts.es5?t.varKinds.var:t.varKinds.const;m=(0,e._)`${m}${b} ${v} = ${y};${this.opts._n}`}else if(y=p?.(v))m=(0,e._)`${m}${y}${this.opts._n}`;else throw new r(v);g.set(v,n.Completed)})}return m}}t.ValueScope=a}),Ze=ne(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.or=t.and=t.not=t.CodeGen=t.operators=t.varKinds=t.ValueScopeName=t.ValueScope=t.Scope=t.Name=t.regexpCode=t.stringify=t.getProperty=t.nil=t.strConcat=t.str=t._=void 0;var e=Fv(),r=cF(),n=Fv();Object.defineProperty(t,"_",{enumerable:!0,get:function(){return n._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return n.str}}),Object.defineProperty(t,"strConcat",{enumerable:!0,get:function(){return n.strConcat}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return n.nil}}),Object.defineProperty(t,"getProperty",{enumerable:!0,get:function(){return n.getProperty}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return n.stringify}}),Object.defineProperty(t,"regexpCode",{enumerable:!0,get:function(){return n.regexpCode}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return n.Name}});var i=cF();Object.defineProperty(t,"Scope",{enumerable:!0,get:function(){return i.Scope}}),Object.defineProperty(t,"ValueScope",{enumerable:!0,get:function(){return i.ValueScope}}),Object.defineProperty(t,"ValueScopeName",{enumerable:!0,get:function(){return i.ValueScopeName}}),Object.defineProperty(t,"varKinds",{enumerable:!0,get:function(){return i.varKinds}}),t.operators={GT:new e._Code(">"),GTE:new e._Code(">="),LT:new e._Code("<"),LTE:new e._Code("<="),EQ:new e._Code("==="),NEQ:new e._Code("!=="),NOT:new e._Code("!"),OR:new e._Code("||"),AND:new e._Code("&&"),ADD:new e._Code("+")};class s{optimizeNodes(){return this}optimizeNames(T,R){return this}}class o extends s{constructor(T,R,F){super(),this.varKind=T,this.name=R,this.rhs=F}render({es5:T,_n:R}){let F=T?r.varKinds.var:this.varKind,le=this.rhs===void 0?"":` = ${this.rhs}`;return`${F} ${this.name}${le};`+R}optimizeNames(T,R){if(T[this.name.str])return this.rhs&&(this.rhs=j(this.rhs,T,R)),this}get names(){return this.rhs instanceof e._CodeOrName?this.rhs.names:{}}}class a extends s{constructor(T,R,F){super(),this.lhs=T,this.rhs=R,this.sideEffects=F}render({_n:T}){return`${this.lhs} = ${this.rhs};`+T}optimizeNames(T,R){if(!(this.lhs instanceof e.Name&&!T[this.lhs.str]&&!this.sideEffects))return this.rhs=j(this.rhs,T,R),this}get names(){let T=this.lhs instanceof e.Name?{}:{...this.lhs.names};return G(T,this.rhs)}}class c extends a{constructor(T,R,F,le){super(T,F,le),this.op=R}render({_n:T}){return`${this.lhs} ${this.op}= ${this.rhs};`+T}}class u extends s{constructor(T){super(),this.label=T,this.names={}}render({_n:T}){return`${this.label}:`+T}}class l extends s{constructor(T){super(),this.label=T,this.names={}}render({_n:T}){return`break${this.label?` ${this.label}`:""};`+T}}class d extends s{constructor(T){super(),this.error=T}render({_n:T}){return`throw ${this.error};`+T}get names(){return this.error.names}}class p extends s{constructor(T){super(),this.code=T}render({_n:T}){return`${this.code};`+T}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(T,R){return this.code=j(this.code,T,R),this}get names(){return this.code instanceof e._CodeOrName?this.code.names:{}}}class m extends s{constructor(T=[]){super(),this.nodes=T}render(T){return this.nodes.reduce((R,F)=>R+F.render(T),"")}optimizeNodes(){let{nodes:T}=this,R=T.length;for(;R--;){let F=T[R].optimizeNodes();Array.isArray(F)?T.splice(R,1,...F):F?T[R]=F:T.splice(R,1)}return T.length>0?this:void 0}optimizeNames(T,R){let{nodes:F}=this,le=F.length;for(;le--;){let ce=F[le];ce.optimizeNames(T,R)||(ae(T,ce.names),F.splice(le,1))}return F.length>0?this:void 0}get names(){return this.nodes.reduce((T,R)=>L(T,R.names),{})}}class f extends m{render(T){return"{"+T._n+super.render(T)+"}"+T._n}}class h extends m{}class g extends f{}g.kind="else";class v extends f{constructor(T,R){super(R),this.condition=T}render(T){let R=`if(${this.condition})`+super.render(T);return this.else&&(R+="else "+this.else.render(T)),R}optimizeNodes(){super.optimizeNodes();let T=this.condition;if(T===!0)return this.nodes;let R=this.else;if(R){let F=R.optimizeNodes();R=this.else=Array.isArray(F)?new g(F):F}if(R)return T===!1?R instanceof v?R:R.nodes:this.nodes.length?this:new v(Ae(T),R instanceof v?[R]:R.nodes);if(!(T===!1||!this.nodes.length))return this}optimizeNames(T,R){var F;if(this.else=(F=this.else)===null||F===void 0?void 0:F.optimizeNames(T,R),!!(super.optimizeNames(T,R)||this.else))return this.condition=j(this.condition,T,R),this}get names(){let T=super.names;return G(T,this.condition),this.else&&L(T,this.else.names),T}}v.kind="if";class y extends f{}y.kind="for";class b extends y{constructor(T){super(),this.iteration=T}render(T){return`for(${this.iteration})`+super.render(T)}optimizeNames(T,R){if(super.optimizeNames(T,R))return this.iteration=j(this.iteration,T,R),this}get names(){return L(super.names,this.iteration.names)}}class S extends y{constructor(T,R,F,le){super(),this.varKind=T,this.name=R,this.from=F,this.to=le}render(T){let R=T.es5?r.varKinds.var:this.varKind,{name:F,from:le,to:ce}=this;return`for(${R} ${F}=${le}; ${F}<${ce}; ${F}++)`+super.render(T)}get names(){let T=G(super.names,this.from);return G(T,this.to)}}class x extends y{constructor(T,R,F,le){super(),this.loop=T,this.varKind=R,this.name=F,this.iterable=le}render(T){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(T)}optimizeNames(T,R){if(super.optimizeNames(T,R))return this.iterable=j(this.iterable,T,R),this}get names(){return L(super.names,this.iterable.names)}}class w extends f{constructor(T,R,F){super(),this.name=T,this.args=R,this.async=F}render(T){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(T)}}w.kind="func";class E extends m{render(T){return"return "+super.render(T)}}E.kind="return";class k extends f{render(T){let R="try"+super.render(T);return this.catch&&(R+=this.catch.render(T)),this.finally&&(R+=this.finally.render(T)),R}optimizeNodes(){var T,R;return super.optimizeNodes(),(T=this.catch)===null||T===void 0||T.optimizeNodes(),(R=this.finally)===null||R===void 0||R.optimizeNodes(),this}optimizeNames(T,R){var F,le;return super.optimizeNames(T,R),(F=this.catch)===null||F===void 0||F.optimizeNames(T,R),(le=this.finally)===null||le===void 0||le.optimizeNames(T,R),this}get names(){let T=super.names;return this.catch&&L(T,this.catch.names),this.finally&&L(T,this.finally.names),T}}class I extends f{constructor(T){super(),this.error=T}render(T){return`catch(${this.error})`+super.render(T)}}I.kind="catch";class P extends f{render(T){return"finally"+super.render(T)}}P.kind="finally";class N{constructor(T,R={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...R,_n:R.lines?`
|
|
1470
|
+
`).trim()}var Ele=new Set(["res",".git","build","node_modules","__pycache__"]);function kle(t){return Bt.default.normalize(t).split(Bt.default.sep).some(n=>Ele.has(n))}function Tle(t){let e=Bt.default.join(t,".git");return(0,$i.existsSync)(e)}function $le(t,e){let r=Bt.default.resolve(t);for(let n of e){let i=Bt.default.resolve(n);if(r===i||r.startsWith(i+Bt.default.sep))return!0}return!1}async function aF(t,e,r,n){let i=ge.loadFromFile(nF),s=parseInt(i.CLAUDE_MEM_CONTEXT_OBSERVATIONS,10)||50,o=oF(i),a=[];try{let l=JSON.parse(i.CLAUDE_MEM_FOLDER_MD_EXCLUDE||"[]");Array.isArray(l)&&(a=l.filter(d=>typeof d=="string"))}catch{_.warn("FOLDER_INDEX","Failed to parse CLAUDE_MEM_FOLDER_MD_EXCLUDE setting")}let c=new Set;for(let l of t){if(!l)continue;let d=Bt.default.basename(l);if(d===iF||d===sF){let p=l;n&&!Bt.default.isAbsolute(l)&&(p=Bt.default.join(n,l));let m=Bt.default.dirname(p);c.add(m),_.debug("FOLDER_INDEX","Detected active context file, will skip folder",{folderPath:m,basename:d})}}let u=new Set;for(let l of t){if(!l||l==="")continue;if(!Sle(l,n)){_.debug("FOLDER_INDEX","Skipping invalid file path",{filePath:l,reason:"Failed path validation"});continue}let d=l;n&&!Bt.default.isAbsolute(l)&&(d=Bt.default.join(n,l));let p=Bt.default.dirname(d);if(p&&p!=="."&&p!=="/"){if(Tle(p)){_.debug("FOLDER_INDEX","Skipping project root CLAUDE.md",{folderPath:p});continue}if(kle(p)){_.debug("FOLDER_INDEX","Skipping unsafe directory for CLAUDE.md",{folderPath:p});continue}if(c.has(p)){_.debug("FOLDER_INDEX","Skipping folder with active CLAUDE.md to avoid race condition",{folderPath:p});continue}if(a.length>0&&$le(p,a)){_.debug("FOLDER_INDEX","Skipping excluded folder",{folderPath:p});continue}u.add(p)}}if(u.size!==0){_.debug("FOLDER_INDEX","Updating CLAUDE.md files",{project:e,folderCount:u.size});for(let l of u)try{let d=await ct(`/api/search/by-file?filePath=${encodeURIComponent(l)}&limit=${s}&project=${encodeURIComponent(e)}&isFolder=true`);if(!d.ok){_.error("FOLDER_INDEX","Failed to fetch timeline",{folderPath:l,status:d.status});continue}let p=await d.json();if(!p.content?.[0]?.text){_.debug("FOLDER_INDEX","No content for folder",{folderPath:l});continue}let m=wle(p.content[0].text),f=Bt.default.join(l,o),h=m.includes("*No recent activity*"),g=(0,$i.existsSync)(f);if(h&&!g){_.debug("FOLDER_INDEX","Skipping empty context file creation",{folderPath:l,targetFilename:o});continue}xle(l,m,o),_.debug("FOLDER_INDEX","Updated context file",{folderPath:l,targetFilename:o})}catch(d){let p=d;_.error("FOLDER_INDEX",`Failed to update ${o}`,{folderPath:l,errorMessage:p.message,errorStack:p.stack})}}}Rr();Yt();$t();function S$(t,e){t?.sseBroadcaster&&t.sseBroadcaster.broadcast({type:"new_observation",observation:e})}function x$(t,e){t?.sseBroadcaster&&t.sseBroadcaster.broadcast({type:"new_summary",summary:e})}function w$(t,e){t.earliestPendingTimestamp=null,e&&typeof e.broadcastProcessingStatus=="function"&&e.broadcastProcessingStatus()}async function Ii(t,e,r,n,i,s,o,a,c,u){e.lastGeneratorActivity=Date.now(),t&&e.conversationHistory.push({role:"assistant",content:t});let l=Q6(t,e.contentSessionId),d=eF(t,e.sessionDbId);if(t.trim()&&l.length===0&&!d&&!/<observation>|<summary>|<skip_summary\b/.test(t)){let g=t.length>200?`${t.slice(0,200)}...`:t;_.warn("PARSER",`${a} returned non-XML response; observation content was discarded`,{sessionId:e.sessionDbId,preview:g})}let p=Ile(d),m=r.getSessionStore();if(!e.memorySessionId)throw new Error("Cannot store observations: memorySessionId not yet captured");m.ensureMemorySessionIdRegistered(e.sessionDbId,e.memorySessionId),_.info("DB",`STORING | sessionDbId=${e.sessionDbId} | memorySessionId=${e.memorySessionId} | obsCount=${l.length} | hasSummary=${!!p}`,{sessionId:e.sessionDbId,memorySessionId:e.memorySessionId});let f=m.storeObservations(e.memorySessionId,e.project,l,p,e.lastPromptNumber,s,o??void 0,u);_.info("DB",`STORED | sessionDbId=${e.sessionDbId} | memorySessionId=${e.memorySessionId} | obsCount=${f.observationIds.length} | obsIds=[${f.observationIds.join(",")}] | summaryId=${f.summaryId||"none"}`,{sessionId:e.sessionDbId,memorySessionId:e.memorySessionId}),e.lastSummaryStored=f.summaryId!==null;let h=n.getPendingMessageStore();for(let g of e.processingMessageIds)h.confirmProcessed(g);e.processingMessageIds.length>0&&_.debug("QUEUE",`CONFIRMED_BATCH | sessionDbId=${e.sessionDbId} | count=${e.processingMessageIds.length} | ids=[${e.processingMessageIds.join(",")}]`),e.processingMessageIds=[],await Rle(l,f,e,r,i,s,a,c),await Ole(d,p,f,e,r,i,s,a),w$(e,i)}function Ile(t){return t?{request:t.request||"",investigated:t.investigated||"",learned:t.learned||"",completed:t.completed||"",next_steps:t.next_steps||"",notes:t.notes}:null}async function Rle(t,e,r,n,i,s,o,a){for(let d=0;d<t.length;d++){let p=e.observationIds[d],m=t[d],f=Date.now();n.getChromaSync()?.syncObservation(p,r.contentSessionId,r.project,m,r.lastPromptNumber,e.createdAtEpoch,s).then(()=>{let h=Date.now()-f;_.debug("CHROMA","Observation synced",{obsId:p,duration:`${h}ms`,type:m.type,title:m.title||"(untitled)"})}).catch(h=>{_.error("CHROMA",`${o} chroma sync failed, continuing without vector search`,{obsId:p,type:m.type,title:m.title||"(untitled)"},h)}),S$(i,{id:p,memory_session_id:r.memorySessionId,session_id:r.contentSessionId,platform_source:r.platformSource,type:m.type,title:m.title,subtitle:m.subtitle,text:null,narrative:m.narrative||null,facts:JSON.stringify(m.facts||[]),concepts:JSON.stringify(m.concepts||[]),files_read:JSON.stringify(m.files_read||[]),files_modified:JSON.stringify(m.files_modified||[]),project:r.project,prompt_number:r.lastPromptNumber,created_at_epoch:e.createdAtEpoch})}let u=ge.loadFromFile(lt).CLAUDE_MEM_FOLDER_CLAUDEMD_ENABLED;if(u==="true"||u===!0){let d=[];for(let p of t)d.push(...p.files_modified||[]),d.push(...p.files_read||[]);d.length>0&&aF(d,r.project,Xr(),a).catch(p=>{_.warn("FOLDER_INDEX","CLAUDE.md update failed (non-critical)",{project:r.project},p)})}}async function Ole(t,e,r,n,i,s,o,a){if(!e||!r.summaryId)return;let c=Date.now();i.getChromaSync()?.syncSummary(r.summaryId,n.contentSessionId,n.project,e,n.lastPromptNumber,r.createdAtEpoch,o).then(()=>{let u=Date.now()-c;_.debug("CHROMA","Summary synced",{summaryId:r.summaryId,duration:`${u}ms`,request:e.request||"(no request)"})}).catch(u=>{_.error("CHROMA",`${a} chroma sync failed, continuing without vector search`,{summaryId:r.summaryId,request:e.request||"(no request)"},u)}),x$(s,{id:r.summaryId,session_id:n.contentSessionId,platform_source:n.platformSource,request:e.request,investigated:e.investigated,learned:e.learned,completed:e.completed,next_steps:e.next_steps,notes:e.notes,project:n.project,prompt_number:n.lastPromptNumber,created_at_epoch:r.createdAtEpoch}),N6(n.project,Xr()).catch(u=>{_.warn("CURSOR","Context update failed (non-critical)",{project:n.project},u)})}function Bp(t){let e=Cle(t);return y$.some(r=>e.includes(r))}function Cle(t){return t==null?"":typeof t=="string"?t:t instanceof Error?t.message:typeof t=="object"&&"message"in t?String(t.message):String(t)}function Gp(t){return t==null?!1:t instanceof Error&&t.name==="AbortError"?!0:typeof t=="object"&&"name"in t?t.name==="AbortError":!1}var O$=require("path"),VF=require("url"),KF=require("events"),XF=require("child_process"),YF=require("readline"),Re=Oe(require("fs"),1),QF=require("fs/promises"),iq=require("path"),sq=require("os"),Ca=require("path"),aq=require("process"),cq=require("fs"),uq=require("crypto"),vq=require("crypto"),Bu=require("fs"),C$=require("path"),yq=require("crypto");var Q_e={},Ple=Object.create,Ale=Object.getPrototypeOf,R$=Object.defineProperty,Nle=Object.getOwnPropertyNames,Mle=Object.prototype.hasOwnProperty,LF=(t,e,r)=>{r=t!=null?Ple(Ale(t)):{};let n=e||!t||!t.__esModule?R$(r,"default",{value:t,enumerable:!0}):r;for(let i of Nle(t))Mle.call(n,i)||R$(n,i,{get:()=>t[i],enumerable:!0});return n},ne=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),UF=(t,e)=>{for(var r in e)R$(t,r,{get:e[r],enumerable:!0,configurable:!0,set:n=>e[r]=()=>n})};var Fv=ne(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.regexpCode=t.getEsmExportName=t.getProperty=t.safeStringify=t.stringify=t.strConcat=t.addCodeArg=t.str=t._=t.nil=t._Code=t.Name=t.IDENTIFIER=t._CodeOrName=void 0;class e{}t._CodeOrName=e,t.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class r extends e{constructor(y){if(super(),!t.IDENTIFIER.test(y))throw new Error("CodeGen: name must be a valid identifier");this.str=y}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}t.Name=r;class n extends e{constructor(y){super(),this._items=typeof y=="string"?[y]:y}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let y=this._items[0];return y===""||y==='""'}get str(){var y;return(y=this._str)!==null&&y!==void 0?y:this._str=this._items.reduce((b,S)=>`${b}${S}`,"")}get names(){var y;return(y=this._names)!==null&&y!==void 0?y:this._names=this._items.reduce((b,S)=>(S instanceof r&&(b[S.str]=(b[S.str]||0)+1),b),{})}}t._Code=n,t.nil=new n("");function i(v,...y){let b=[v[0]],S=0;for(;S<y.length;)a(b,y[S]),b.push(v[++S]);return new n(b)}t._=i;var s=new n("+");function o(v,...y){let b=[m(v[0])],S=0;for(;S<y.length;)b.push(s),a(b,y[S]),b.push(s,m(v[++S]));return c(b),new n(b)}t.str=o;function a(v,y){y instanceof n?v.push(...y._items):y instanceof r?v.push(y):v.push(d(y))}t.addCodeArg=a;function c(v){let y=1;for(;y<v.length-1;){if(v[y]===s){let b=u(v[y-1],v[y+1]);if(b!==void 0){v.splice(y-1,3,b);continue}v[y++]="+"}y++}}function u(v,y){if(y==='""')return v;if(v==='""')return y;if(typeof v=="string")return y instanceof r||v[v.length-1]!=='"'?void 0:typeof y!="string"?`${v.slice(0,-1)}${y}"`:y[0]==='"'?v.slice(0,-1)+y.slice(1):void 0;if(typeof y=="string"&&y[0]==='"'&&!(v instanceof r))return`"${v}${y.slice(1)}`}function l(v,y){return y.emptyStr()?v:v.emptyStr()?y:o`${v}${y}`}t.strConcat=l;function d(v){return typeof v=="number"||typeof v=="boolean"||v===null?v:m(Array.isArray(v)?v.join(","):v)}function p(v){return new n(m(v))}t.stringify=p;function m(v){return JSON.stringify(v).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}t.safeStringify=m;function f(v){return typeof v=="string"&&t.IDENTIFIER.test(v)?new n(`.${v}`):i`[${v}]`}t.getProperty=f;function h(v){if(typeof v=="string"&&t.IDENTIFIER.test(v))return new n(`${v}`);throw new Error(`CodeGen: invalid export name: ${v}, use explicit $id name mapping`)}t.getEsmExportName=h;function g(v){return new n(v.toString())}t.regexpCode=g}),cF=ne(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ValueScope=t.ValueScopeName=t.Scope=t.varKinds=t.UsedValueState=void 0;var e=Fv();class r extends Error{constructor(u){super(`CodeGen: "code" for ${u} not defined`),this.value=u.value}}var n;(function(c){c[c.Started=0]="Started",c[c.Completed=1]="Completed"})(n||(t.UsedValueState=n={})),t.varKinds={const:new e.Name("const"),let:new e.Name("let"),var:new e.Name("var")};class i{constructor({prefixes:u,parent:l}={}){this._names={},this._prefixes=u,this._parent=l}toName(u){return u instanceof e.Name?u:this.name(u)}name(u){return new e.Name(this._newName(u))}_newName(u){let l=this._names[u]||this._nameGroup(u);return`${u}${l.index++}`}_nameGroup(u){var l,d;if(!((d=(l=this._parent)===null||l===void 0?void 0:l._prefixes)===null||d===void 0)&&d.has(u)||this._prefixes&&!this._prefixes.has(u))throw new Error(`CodeGen: prefix "${u}" is not allowed in this scope`);return this._names[u]={prefix:u,index:0}}}t.Scope=i;class s extends e.Name{constructor(u,l){super(l),this.prefix=u}setValue(u,{property:l,itemIndex:d}){this.value=u,this.scopePath=(0,e._)`.${new e.Name(l)}[${d}]`}}t.ValueScopeName=s;var o=(0,e._)`\n`;class a extends i{constructor(u){super(u),this._values={},this._scope=u.scope,this.opts={...u,_n:u.lines?o:e.nil}}get(){return this._scope}name(u){return new s(u,this._newName(u))}value(u,l){var d;if(l.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let p=this.toName(u),{prefix:m}=p,f=(d=l.key)!==null&&d!==void 0?d:l.ref,h=this._values[m];if(h){let y=h.get(f);if(y)return y}else h=this._values[m]=new Map;h.set(f,p);let g=this._scope[m]||(this._scope[m]=[]),v=g.length;return g[v]=l.ref,p.setValue(l,{property:m,itemIndex:v}),p}getValue(u,l){let d=this._values[u];if(d)return d.get(l)}scopeRefs(u,l=this._values){return this._reduceValues(l,d=>{if(d.scopePath===void 0)throw new Error(`CodeGen: name "${d}" has no value`);return(0,e._)`${u}${d.scopePath}`})}scopeCode(u=this._values,l,d){return this._reduceValues(u,p=>{if(p.value===void 0)throw new Error(`CodeGen: name "${p}" has no value`);return p.value.code},l,d)}_reduceValues(u,l,d={},p){let m=e.nil;for(let f in u){let h=u[f];if(!h)continue;let g=d[f]=d[f]||new Map;h.forEach(v=>{if(g.has(v))return;g.set(v,n.Started);let y=l(v);if(y){let b=this.opts.es5?t.varKinds.var:t.varKinds.const;m=(0,e._)`${m}${b} ${v} = ${y};${this.opts._n}`}else if(y=p?.(v))m=(0,e._)`${m}${y}${this.opts._n}`;else throw new r(v);g.set(v,n.Completed)})}return m}}t.ValueScope=a}),Ze=ne(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.or=t.and=t.not=t.CodeGen=t.operators=t.varKinds=t.ValueScopeName=t.ValueScope=t.Scope=t.Name=t.regexpCode=t.stringify=t.getProperty=t.nil=t.strConcat=t.str=t._=void 0;var e=Fv(),r=cF(),n=Fv();Object.defineProperty(t,"_",{enumerable:!0,get:function(){return n._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return n.str}}),Object.defineProperty(t,"strConcat",{enumerable:!0,get:function(){return n.strConcat}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return n.nil}}),Object.defineProperty(t,"getProperty",{enumerable:!0,get:function(){return n.getProperty}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return n.stringify}}),Object.defineProperty(t,"regexpCode",{enumerable:!0,get:function(){return n.regexpCode}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return n.Name}});var i=cF();Object.defineProperty(t,"Scope",{enumerable:!0,get:function(){return i.Scope}}),Object.defineProperty(t,"ValueScope",{enumerable:!0,get:function(){return i.ValueScope}}),Object.defineProperty(t,"ValueScopeName",{enumerable:!0,get:function(){return i.ValueScopeName}}),Object.defineProperty(t,"varKinds",{enumerable:!0,get:function(){return i.varKinds}}),t.operators={GT:new e._Code(">"),GTE:new e._Code(">="),LT:new e._Code("<"),LTE:new e._Code("<="),EQ:new e._Code("==="),NEQ:new e._Code("!=="),NOT:new e._Code("!"),OR:new e._Code("||"),AND:new e._Code("&&"),ADD:new e._Code("+")};class s{optimizeNodes(){return this}optimizeNames(T,R){return this}}class o extends s{constructor(T,R,F){super(),this.varKind=T,this.name=R,this.rhs=F}render({es5:T,_n:R}){let F=T?r.varKinds.var:this.varKind,le=this.rhs===void 0?"":` = ${this.rhs}`;return`${F} ${this.name}${le};`+R}optimizeNames(T,R){if(T[this.name.str])return this.rhs&&(this.rhs=j(this.rhs,T,R)),this}get names(){return this.rhs instanceof e._CodeOrName?this.rhs.names:{}}}class a extends s{constructor(T,R,F){super(),this.lhs=T,this.rhs=R,this.sideEffects=F}render({_n:T}){return`${this.lhs} = ${this.rhs};`+T}optimizeNames(T,R){if(!(this.lhs instanceof e.Name&&!T[this.lhs.str]&&!this.sideEffects))return this.rhs=j(this.rhs,T,R),this}get names(){let T=this.lhs instanceof e.Name?{}:{...this.lhs.names};return G(T,this.rhs)}}class c extends a{constructor(T,R,F,le){super(T,F,le),this.op=R}render({_n:T}){return`${this.lhs} ${this.op}= ${this.rhs};`+T}}class u extends s{constructor(T){super(),this.label=T,this.names={}}render({_n:T}){return`${this.label}:`+T}}class l extends s{constructor(T){super(),this.label=T,this.names={}}render({_n:T}){return`break${this.label?` ${this.label}`:""};`+T}}class d extends s{constructor(T){super(),this.error=T}render({_n:T}){return`throw ${this.error};`+T}get names(){return this.error.names}}class p extends s{constructor(T){super(),this.code=T}render({_n:T}){return`${this.code};`+T}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(T,R){return this.code=j(this.code,T,R),this}get names(){return this.code instanceof e._CodeOrName?this.code.names:{}}}class m extends s{constructor(T=[]){super(),this.nodes=T}render(T){return this.nodes.reduce((R,F)=>R+F.render(T),"")}optimizeNodes(){let{nodes:T}=this,R=T.length;for(;R--;){let F=T[R].optimizeNodes();Array.isArray(F)?T.splice(R,1,...F):F?T[R]=F:T.splice(R,1)}return T.length>0?this:void 0}optimizeNames(T,R){let{nodes:F}=this,le=F.length;for(;le--;){let ce=F[le];ce.optimizeNames(T,R)||(ae(T,ce.names),F.splice(le,1))}return F.length>0?this:void 0}get names(){return this.nodes.reduce((T,R)=>L(T,R.names),{})}}class f extends m{render(T){return"{"+T._n+super.render(T)+"}"+T._n}}class h extends m{}class g extends f{}g.kind="else";class v extends f{constructor(T,R){super(R),this.condition=T}render(T){let R=`if(${this.condition})`+super.render(T);return this.else&&(R+="else "+this.else.render(T)),R}optimizeNodes(){super.optimizeNodes();let T=this.condition;if(T===!0)return this.nodes;let R=this.else;if(R){let F=R.optimizeNodes();R=this.else=Array.isArray(F)?new g(F):F}if(R)return T===!1?R instanceof v?R:R.nodes:this.nodes.length?this:new v(Ae(T),R instanceof v?[R]:R.nodes);if(!(T===!1||!this.nodes.length))return this}optimizeNames(T,R){var F;if(this.else=(F=this.else)===null||F===void 0?void 0:F.optimizeNames(T,R),!!(super.optimizeNames(T,R)||this.else))return this.condition=j(this.condition,T,R),this}get names(){let T=super.names;return G(T,this.condition),this.else&&L(T,this.else.names),T}}v.kind="if";class y extends f{}y.kind="for";class b extends y{constructor(T){super(),this.iteration=T}render(T){return`for(${this.iteration})`+super.render(T)}optimizeNames(T,R){if(super.optimizeNames(T,R))return this.iteration=j(this.iteration,T,R),this}get names(){return L(super.names,this.iteration.names)}}class S extends y{constructor(T,R,F,le){super(),this.varKind=T,this.name=R,this.from=F,this.to=le}render(T){let R=T.es5?r.varKinds.var:this.varKind,{name:F,from:le,to:ce}=this;return`for(${R} ${F}=${le}; ${F}<${ce}; ${F}++)`+super.render(T)}get names(){let T=G(super.names,this.from);return G(T,this.to)}}class x extends y{constructor(T,R,F,le){super(),this.loop=T,this.varKind=R,this.name=F,this.iterable=le}render(T){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(T)}optimizeNames(T,R){if(super.optimizeNames(T,R))return this.iterable=j(this.iterable,T,R),this}get names(){return L(super.names,this.iterable.names)}}class w extends f{constructor(T,R,F){super(),this.name=T,this.args=R,this.async=F}render(T){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(T)}}w.kind="func";class E extends m{render(T){return"return "+super.render(T)}}E.kind="return";class k extends f{render(T){let R="try"+super.render(T);return this.catch&&(R+=this.catch.render(T)),this.finally&&(R+=this.finally.render(T)),R}optimizeNodes(){var T,R;return super.optimizeNodes(),(T=this.catch)===null||T===void 0||T.optimizeNodes(),(R=this.finally)===null||R===void 0||R.optimizeNodes(),this}optimizeNames(T,R){var F,le;return super.optimizeNames(T,R),(F=this.catch)===null||F===void 0||F.optimizeNames(T,R),(le=this.finally)===null||le===void 0||le.optimizeNames(T,R),this}get names(){let T=super.names;return this.catch&&L(T,this.catch.names),this.finally&&L(T,this.finally.names),T}}class I extends f{constructor(T){super(),this.error=T}render(T){return`catch(${this.error})`+super.render(T)}}I.kind="catch";class P extends f{render(T){return"finally"+super.render(T)}}P.kind="finally";class N{constructor(T,R={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...R,_n:R.lines?`
|
|
1471
1471
|
`:""},this._extScope=T,this._scope=new r.Scope({parent:T}),this._nodes=[new h]}toString(){return this._root.render(this.opts)}name(T){return this._scope.name(T)}scopeName(T){return this._extScope.name(T)}scopeValue(T,R){let F=this._extScope.value(T,R);return(this._values[F.prefix]||(this._values[F.prefix]=new Set)).add(F),F}getScopeValue(T,R){return this._extScope.getValue(T,R)}scopeRefs(T){return this._extScope.scopeRefs(T,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(T,R,F,le){let ce=this._scope.toName(R);return F!==void 0&&le&&(this._constants[ce.str]=F),this._leafNode(new o(T,ce,F)),ce}const(T,R,F){return this._def(r.varKinds.const,T,R,F)}let(T,R,F){return this._def(r.varKinds.let,T,R,F)}var(T,R,F){return this._def(r.varKinds.var,T,R,F)}assign(T,R,F){return this._leafNode(new a(T,R,F))}add(T,R){return this._leafNode(new c(T,t.operators.ADD,R))}code(T){return typeof T=="function"?T():T!==e.nil&&this._leafNode(new p(T)),this}object(...T){let R=["{"];for(let[F,le]of T)R.length>1&&R.push(","),R.push(F),(F!==le||this.opts.es5)&&(R.push(":"),(0,e.addCodeArg)(R,le));return R.push("}"),new e._Code(R)}if(T,R,F){if(this._blockNode(new v(T)),R&&F)this.code(R).else().code(F).endIf();else if(R)this.code(R).endIf();else if(F)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(T){return this._elseNode(new v(T))}else(){return this._elseNode(new g)}endIf(){return this._endBlockNode(v,g)}_for(T,R){return this._blockNode(T),R&&this.code(R).endFor(),this}for(T,R){return this._for(new b(T),R)}forRange(T,R,F,le,ce=this.opts.es5?r.varKinds.var:r.varKinds.let){let Qe=this._scope.toName(T);return this._for(new S(ce,Qe,R,F),()=>le(Qe))}forOf(T,R,F,le=r.varKinds.const){let ce=this._scope.toName(T);if(this.opts.es5){let Qe=R instanceof e.Name?R:this.var("_arr",R);return this.forRange("_i",0,(0,e._)`${Qe}.length`,Xe=>{this.var(ce,(0,e._)`${Qe}[${Xe}]`),F(ce)})}return this._for(new x("of",le,ce,R),()=>F(ce))}forIn(T,R,F,le=this.opts.es5?r.varKinds.var:r.varKinds.const){if(this.opts.ownProperties)return this.forOf(T,(0,e._)`Object.keys(${R})`,F);let ce=this._scope.toName(T);return this._for(new x("in",le,ce,R),()=>F(ce))}endFor(){return this._endBlockNode(y)}label(T){return this._leafNode(new u(T))}break(T){return this._leafNode(new l(T))}return(T){let R=new E;if(this._blockNode(R),this.code(T),R.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(E)}try(T,R,F){if(!R&&!F)throw new Error('CodeGen: "try" without "catch" and "finally"');let le=new k;if(this._blockNode(le),this.code(T),R){let ce=this.name("e");this._currNode=le.catch=new I(ce),R(ce)}return F&&(this._currNode=le.finally=new P,this.code(F)),this._endBlockNode(I,P)}throw(T){return this._leafNode(new d(T))}block(T,R){return this._blockStarts.push(this._nodes.length),T&&this.code(T).endBlock(R),this}endBlock(T){let R=this._blockStarts.pop();if(R===void 0)throw new Error("CodeGen: not in self-balancing block");let F=this._nodes.length-R;if(F<0||T!==void 0&&F!==T)throw new Error(`CodeGen: wrong number of nodes: ${F} vs ${T} expected`);return this._nodes.length=R,this}func(T,R=e.nil,F,le){return this._blockNode(new w(T,R,F)),le&&this.code(le).endFunc(),this}endFunc(){return this._endBlockNode(w)}optimize(T=1){for(;T-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(T){return this._currNode.nodes.push(T),this}_blockNode(T){this._currNode.nodes.push(T),this._nodes.push(T)}_endBlockNode(T,R){let F=this._currNode;if(F instanceof T||R&&F instanceof R)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${R?`${T.kind}/${R.kind}`:T.kind}"`)}_elseNode(T){let R=this._currNode;if(!(R instanceof v))throw new Error('CodeGen: "else" without "if"');return this._currNode=R.else=T,this}get _root(){return this._nodes[0]}get _currNode(){let T=this._nodes;return T[T.length-1]}set _currNode(T){let R=this._nodes;R[R.length-1]=T}}t.CodeGen=N;function L(M,T){for(let R in T)M[R]=(M[R]||0)+(T[R]||0);return M}function G(M,T){return T instanceof e._CodeOrName?L(M,T.names):M}function j(M,T,R){if(M instanceof e.Name)return F(M);if(!le(M))return M;return new e._Code(M._items.reduce((ce,Qe)=>(Qe instanceof e.Name&&(Qe=F(Qe)),Qe instanceof e._Code?ce.push(...Qe._items):ce.push(Qe),ce),[]));function F(ce){let Qe=R[ce.str];return Qe===void 0||T[ce.str]!==1?ce:(delete T[ce.str],Qe)}function le(ce){return ce instanceof e._Code&&ce._items.some(Qe=>Qe instanceof e.Name&&T[Qe.str]===1&&R[Qe.str]!==void 0)}}function ae(M,T){for(let R in T)M[R]=(M[R]||0)-(T[R]||0)}function Ae(M){return typeof M=="boolean"||typeof M=="number"||M===null?!M:(0,e._)`!${H(M)}`}t.not=Ae;var Ne=C(t.operators.AND);function ht(...M){return M.reduce(Ne)}t.and=ht;var Ge=C(t.operators.OR);function K(...M){return M.reduce(Ge)}t.or=K;function C(M){return(T,R)=>T===e.nil?R:R===e.nil?T:(0,e._)`${H(T)} ${M} ${H(R)}`}function H(M){return M instanceof e.Name?M:(0,e._)`(${M})`}}),ut=ne(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.checkStrictMode=t.getErrorPath=t.Type=t.useFunc=t.setEvaluated=t.evaluatedPropsToName=t.mergeEvaluated=t.eachItem=t.unescapeJsonPointer=t.escapeJsonPointer=t.escapeFragment=t.unescapeFragment=t.schemaRefOrVal=t.schemaHasRulesButRef=t.schemaHasRules=t.checkUnknownRules=t.alwaysValidSchema=t.toHash=void 0;var e=Ze(),r=Fv();function n(w){let E={};for(let k of w)E[k]=!0;return E}t.toHash=n;function i(w,E){return typeof E=="boolean"?E:Object.keys(E).length===0?!0:(s(w,E),!o(E,w.self.RULES.all))}t.alwaysValidSchema=i;function s(w,E=w.schema){let{opts:k,self:I}=w;if(!k.strictSchema||typeof E=="boolean")return;let P=I.RULES.keywords;for(let N in E)P[N]||x(w,`unknown keyword: "${N}"`)}t.checkUnknownRules=s;function o(w,E){if(typeof w=="boolean")return!w;for(let k in w)if(E[k])return!0;return!1}t.schemaHasRules=o;function a(w,E){if(typeof w=="boolean")return!w;for(let k in w)if(k!=="$ref"&&E.all[k])return!0;return!1}t.schemaHasRulesButRef=a;function c({topSchemaRef:w,schemaPath:E},k,I,P){if(!P){if(typeof k=="number"||typeof k=="boolean")return k;if(typeof k=="string")return(0,e._)`${k}`}return(0,e._)`${w}${E}${(0,e.getProperty)(I)}`}t.schemaRefOrVal=c;function u(w){return p(decodeURIComponent(w))}t.unescapeFragment=u;function l(w){return encodeURIComponent(d(w))}t.escapeFragment=l;function d(w){return typeof w=="number"?`${w}`:w.replace(/~/g,"~0").replace(/\//g,"~1")}t.escapeJsonPointer=d;function p(w){return w.replace(/~1/g,"/").replace(/~0/g,"~")}t.unescapeJsonPointer=p;function m(w,E){if(Array.isArray(w))for(let k of w)E(k);else E(w)}t.eachItem=m;function f({mergeNames:w,mergeToName:E,mergeValues:k,resultToName:I}){return(P,N,L,G)=>{let j=L===void 0?N:L instanceof e.Name?(N instanceof e.Name?w(P,N,L):E(P,N,L),L):N instanceof e.Name?(E(P,L,N),N):k(N,L);return G===e.Name&&!(j instanceof e.Name)?I(P,j):j}}t.mergeEvaluated={props:f({mergeNames:(w,E,k)=>w.if((0,e._)`${k} !== true && ${E} !== undefined`,()=>{w.if((0,e._)`${E} === true`,()=>w.assign(k,!0),()=>w.assign(k,(0,e._)`${k} || {}`).code((0,e._)`Object.assign(${k}, ${E})`))}),mergeToName:(w,E,k)=>w.if((0,e._)`${k} !== true`,()=>{E===!0?w.assign(k,!0):(w.assign(k,(0,e._)`${k} || {}`),g(w,k,E))}),mergeValues:(w,E)=>w===!0?!0:{...w,...E},resultToName:h}),items:f({mergeNames:(w,E,k)=>w.if((0,e._)`${k} !== true && ${E} !== undefined`,()=>w.assign(k,(0,e._)`${E} === true ? true : ${k} > ${E} ? ${k} : ${E}`)),mergeToName:(w,E,k)=>w.if((0,e._)`${k} !== true`,()=>w.assign(k,E===!0?!0:(0,e._)`${k} > ${E} ? ${k} : ${E}`)),mergeValues:(w,E)=>w===!0?!0:Math.max(w,E),resultToName:(w,E)=>w.var("items",E)})};function h(w,E){if(E===!0)return w.var("props",!0);let k=w.var("props",(0,e._)`{}`);return E!==void 0&&g(w,k,E),k}t.evaluatedPropsToName=h;function g(w,E,k){Object.keys(k).forEach(I=>w.assign((0,e._)`${E}${(0,e.getProperty)(I)}`,!0))}t.setEvaluated=g;var v={};function y(w,E){return w.scopeValue("func",{ref:E,code:v[E.code]||(v[E.code]=new r._Code(E.code))})}t.useFunc=y;var b;(function(w){w[w.Num=0]="Num",w[w.Str=1]="Str"})(b||(t.Type=b={}));function S(w,E,k){if(w instanceof e.Name){let I=E===b.Num;return k?I?(0,e._)`"[" + ${w} + "]"`:(0,e._)`"['" + ${w} + "']"`:I?(0,e._)`"/" + ${w}`:(0,e._)`"/" + ${w}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return k?(0,e.getProperty)(w).toString():"/"+d(w)}t.getErrorPath=S;function x(w,E,k=w.opts.strictSchema){if(k){if(E=`strict mode: ${E}`,k===!0)throw new Error(E);w.self.logger.warn(E)}}t.checkStrictMode=x}),Po=ne(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Ze(),r={data:new e.Name("data"),valCxt:new e.Name("valCxt"),instancePath:new e.Name("instancePath"),parentData:new e.Name("parentData"),parentDataProperty:new e.Name("parentDataProperty"),rootData:new e.Name("rootData"),dynamicAnchors:new e.Name("dynamicAnchors"),vErrors:new e.Name("vErrors"),errors:new e.Name("errors"),this:new e.Name("this"),self:new e.Name("self"),scope:new e.Name("scope"),json:new e.Name("json"),jsonPos:new e.Name("jsonPos"),jsonLen:new e.Name("jsonLen"),jsonPart:new e.Name("jsonPart")};t.default=r}),Kv=ne(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.extendErrors=t.resetErrorsCount=t.reportExtraError=t.reportError=t.keyword$DataError=t.keywordError=void 0;var e=Ze(),r=ut(),n=Po();t.keywordError={message:({keyword:g})=>(0,e.str)`must pass "${g}" keyword validation`},t.keyword$DataError={message:({keyword:g,schemaType:v})=>v?(0,e.str)`"${g}" keyword must be ${v} ($data)`:(0,e.str)`"${g}" keyword is invalid ($data)`};function i(g,v=t.keywordError,y,b){let{it:S}=g,{gen:x,compositeRule:w,allErrors:E}=S,k=d(g,v,y);b??(w||E)?c(x,k):u(S,(0,e._)`[${k}]`)}t.reportError=i;function s(g,v=t.keywordError,y){let{it:b}=g,{gen:S,compositeRule:x,allErrors:w}=b,E=d(g,v,y);c(S,E),x||w||u(b,n.default.vErrors)}t.reportExtraError=s;function o(g,v){g.assign(n.default.errors,v),g.if((0,e._)`${n.default.vErrors} !== null`,()=>g.if(v,()=>g.assign((0,e._)`${n.default.vErrors}.length`,v),()=>g.assign(n.default.vErrors,null)))}t.resetErrorsCount=o;function a({gen:g,keyword:v,schemaValue:y,data:b,errsCount:S,it:x}){if(S===void 0)throw new Error("ajv implementation error");let w=g.name("err");g.forRange("i",S,n.default.errors,E=>{g.const(w,(0,e._)`${n.default.vErrors}[${E}]`),g.if((0,e._)`${w}.instancePath === undefined`,()=>g.assign((0,e._)`${w}.instancePath`,(0,e.strConcat)(n.default.instancePath,x.errorPath))),g.assign((0,e._)`${w}.schemaPath`,(0,e.str)`${x.errSchemaPath}/${v}`),x.opts.verbose&&(g.assign((0,e._)`${w}.schema`,y),g.assign((0,e._)`${w}.data`,b))})}t.extendErrors=a;function c(g,v){let y=g.const("err",v);g.if((0,e._)`${n.default.vErrors} === null`,()=>g.assign(n.default.vErrors,(0,e._)`[${y}]`),(0,e._)`${n.default.vErrors}.push(${y})`),g.code((0,e._)`${n.default.errors}++`)}function u(g,v){let{gen:y,validateName:b,schemaEnv:S}=g;S.$async?y.throw((0,e._)`new ${g.ValidationError}(${v})`):(y.assign((0,e._)`${b}.errors`,v),y.return(!1))}var l={keyword:new e.Name("keyword"),schemaPath:new e.Name("schemaPath"),params:new e.Name("params"),propertyName:new e.Name("propertyName"),message:new e.Name("message"),schema:new e.Name("schema"),parentSchema:new e.Name("parentSchema")};function d(g,v,y){let{createErrors:b}=g.it;return b===!1?(0,e._)`{}`:p(g,v,y)}function p(g,v,y={}){let{gen:b,it:S}=g,x=[m(S,y),f(g,y)];return h(g,v,x),b.object(...x)}function m({errorPath:g},{instancePath:v}){let y=v?(0,e.str)`${g}${(0,r.getErrorPath)(v,r.Type.Str)}`:g;return[n.default.instancePath,(0,e.strConcat)(n.default.instancePath,y)]}function f({keyword:g,it:{errSchemaPath:v}},{schemaPath:y,parentSchema:b}){let S=b?v:(0,e.str)`${v}/${g}`;return y&&(S=(0,e.str)`${S}${(0,r.getErrorPath)(y,r.Type.Str)}`),[l.schemaPath,S]}function h(g,{params:v,message:y},b){let{keyword:S,data:x,schemaValue:w,it:E}=g,{opts:k,propertyName:I,topSchemaRef:P,schemaPath:N}=E;b.push([l.keyword,S],[l.params,typeof v=="function"?v(g):v||(0,e._)`{}`]),k.messages&&b.push([l.message,typeof y=="function"?y(g):y]),k.verbose&&b.push([l.schema,w],[l.parentSchema,(0,e._)`${P}${N}`],[n.default.data,x]),I&&b.push([l.propertyName,I])}}),Dle=ne(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.boolOrEmptySchema=t.topBoolOrEmptySchema=void 0;var e=Kv(),r=Ze(),n=Po(),i={message:"boolean schema is false"};function s(c){let{gen:u,schema:l,validateName:d}=c;l===!1?a(c,!1):typeof l=="object"&&l.$async===!0?u.return(n.default.data):(u.assign((0,r._)`${d}.errors`,null),u.return(!0))}t.topBoolOrEmptySchema=s;function o(c,u){let{gen:l,schema:d}=c;d===!1?(l.var(u,!1),a(c)):l.var(u,!0)}t.boolOrEmptySchema=o;function a(c,u){let{gen:l,data:d}=c,p={gen:l,keyword:"false schema",data:d,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:c};(0,e.reportError)(p,i,void 0,u)}}),FF=ne(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getRules=t.isJSONType=void 0;var e=["string","number","integer","boolean","null","object","array"],r=new Set(e);function n(s){return typeof s=="string"&&r.has(s)}t.isJSONType=n;function i(){let s={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...s,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},s.number,s.string,s.array,s.object],post:{rules:[]},all:{},keywords:{}}}t.getRules=i}),qF=ne(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.shouldUseRule=t.shouldUseGroup=t.schemaHasRulesForType=void 0;function e({schema:i,self:s},o){let a=s.RULES.types[o];return a&&a!==!0&&r(i,a)}t.schemaHasRulesForType=e;function r(i,s){return s.rules.some(o=>n(i,o))}t.shouldUseGroup=r;function n(i,s){var o;return i[s.keyword]!==void 0||((o=s.definition.implements)===null||o===void 0?void 0:o.some(a=>i[a]!==void 0))}t.shouldUseRule=n}),qv=ne(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.reportTypeError=t.checkDataTypes=t.checkDataType=t.coerceAndCheckDataType=t.getJSONTypes=t.getSchemaTypes=t.DataType=void 0;var e=FF(),r=qF(),n=Kv(),i=Ze(),s=ut(),o;(function(b){b[b.Correct=0]="Correct",b[b.Wrong=1]="Wrong"})(o||(t.DataType=o={}));function a(b){let S=c(b.type);if(S.includes("null")){if(b.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!S.length&&b.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');b.nullable===!0&&S.push("null")}return S}t.getSchemaTypes=a;function c(b){let S=Array.isArray(b)?b:b?[b]:[];if(S.every(e.isJSONType))return S;throw new Error("type must be JSONType or JSONType[]: "+S.join(","))}t.getJSONTypes=c;function u(b,S){let{gen:x,data:w,opts:E}=b,k=d(S,E.coerceTypes),I=S.length>0&&!(k.length===0&&S.length===1&&(0,r.schemaHasRulesForType)(b,S[0]));if(I){let P=h(S,w,E.strictNumbers,o.Wrong);x.if(P,()=>{k.length?p(b,S,k):v(b)})}return I}t.coerceAndCheckDataType=u;var l=new Set(["string","number","integer","boolean","null"]);function d(b,S){return S?b.filter(x=>l.has(x)||S==="array"&&x==="array"):[]}function p(b,S,x){let{gen:w,data:E,opts:k}=b,I=w.let("dataType",(0,i._)`typeof ${E}`),P=w.let("coerced",(0,i._)`undefined`);k.coerceTypes==="array"&&w.if((0,i._)`${I} == 'object' && Array.isArray(${E}) && ${E}.length == 1`,()=>w.assign(E,(0,i._)`${E}[0]`).assign(I,(0,i._)`typeof ${E}`).if(h(S,E,k.strictNumbers),()=>w.assign(P,E))),w.if((0,i._)`${P} !== undefined`);for(let L of x)(l.has(L)||L==="array"&&k.coerceTypes==="array")&&N(L);w.else(),v(b),w.endIf(),w.if((0,i._)`${P} !== undefined`,()=>{w.assign(E,P),m(b,P)});function N(L){switch(L){case"string":w.elseIf((0,i._)`${I} == "number" || ${I} == "boolean"`).assign(P,(0,i._)`"" + ${E}`).elseIf((0,i._)`${E} === null`).assign(P,(0,i._)`""`);return;case"number":w.elseIf((0,i._)`${I} == "boolean" || ${E} === null
|
|
1472
1472
|
|| (${I} == "string" && ${E} && ${E} == +${E})`).assign(P,(0,i._)`+${E}`);return;case"integer":w.elseIf((0,i._)`${I} === "boolean" || ${E} === null
|
|
1473
1473
|
|| (${I} === "string" && ${E} && ${E} == +${E} && !(${E} % 1))`).assign(P,(0,i._)`+${E}`);return;case"boolean":w.elseIf((0,i._)`${E} === "false" || ${E} === 0 || ${E} === null`).assign(P,!1).elseIf((0,i._)`${E} === "true" || ${E} === 1`).assign(P,!0);return;case"null":w.elseIf((0,i._)`${E} === "" || ${E} === 0 || ${E} === false`),w.assign(P,null);return;case"array":w.elseIf((0,i._)`${I} === "string" || ${I} === "number"
|
|
@@ -1652,7 +1652,7 @@ ${e}`,o=b$(i,s),a=`${t}.tmp`;try{(0,Mi.writeFileSync)(a,o),(0,Mi.renameSync)(a,t
|
|
|
1652
1652
|
`);sr($s);let i=this.findClaudeExecutable(),s=Cn(Jd()),o=gm({prompt:n,options:{model:this.getModelId(),cwd:$s,disallowedTools:_5,pathToClaudeCodeExecutable:i,env:s}}),a;try{for await(let c of o)c.session_id&&(a=c.session_id),c.type==="result"&&_.info("WORKER",`Knowledge agent primed for corpus "${e.name}"`)}catch(c){if(a)_.debug("WORKER",`SDK process exited after priming corpus "${e.name}" \u2014 session captured, continuing`,{},c);else throw c}if(!a)throw new Error(`Failed to capture session_id while priming corpus "${e.name}"`);return e.session_id=a,this.corpusStore.write(e),a}async query(e,r){if(!e.session_id)throw new Error(`Corpus "${e.name}" has no session \u2014 call prime first`);try{let n=await this.executeQuery(e,r);return n.session_id!==e.session_id&&(e.session_id=n.session_id,this.corpusStore.write(e)),n}catch(n){if(!this.isSessionResumeError(n))throw n;_.info("WORKER",`Session expired for corpus "${e.name}", auto-repriming...`),await this.prime(e);let i=this.corpusStore.read(e.name);if(!i||!i.session_id)throw new Error(`Auto-reprime failed for corpus "${e.name}"`);let s=await this.executeQuery(i,r);return s.session_id!==i.session_id&&(i.session_id=s.session_id,this.corpusStore.write(i)),s}}async reprime(e){return e.session_id=null,this.prime(e)}isSessionResumeError(e){let r=e instanceof Error?e.message:String(e);return/session|resume|expired|invalid.*session|not found/i.test(r)}async executeQuery(e,r){sr($s);let n=this.findClaudeExecutable(),i=Cn(Jd()),s=gm({prompt:r,options:{model:this.getModelId(),resume:e.session_id,cwd:$s,disallowedTools:_5,pathToClaudeCodeExecutable:n,env:i}}),o="",a=e.session_id;try{for await(let c of s)c.session_id&&(a=c.session_id),c.type==="assistant"&&(o=c.message.content.filter(l=>l.type==="text").map(l=>l.text).join(""))}catch(c){if(o)_.debug("WORKER","SDK process exited after query \u2014 answer captured, continuing",{},c);else throw c}return{answer:o,session_id:a}}getModelId(){return ge.loadFromFile(lt).CLAUDE_MEM_MODEL}findClaudeExecutable(){let e=ge.loadFromFile(lt);if(e.CLAUDE_CODE_PATH){let{existsSync:r}=require("fs");if(!r(e.CLAUDE_CODE_PATH))throw new Error(`CLAUDE_CODE_PATH is set to "${e.CLAUDE_CODE_PATH}" but the file does not exist.`);return e.CLAUDE_CODE_PATH}if(process.platform==="win32")try{return(0,rR.execSync)("where claude.cmd",{encoding:"utf8",windowsHide:!0,stdio:["ignore","pipe","ignore"]}),"claude.cmd"}catch{}try{let r=(0,rR.execSync)(process.platform==="win32"?"where claude":"which claude",{encoding:"utf8",windowsHide:!0,stdio:["ignore","pipe","ignore"]}).trim().split(`
|
|
1653
1653
|
`)[0].trim();if(r)return r}catch(r){_.debug("WORKER","Claude executable auto-detection failed",{},r)}throw new Error(`Claude executable not found. Please either:
|
|
1654
1654
|
1. Add "claude" to your system PATH, or
|
|
1655
|
-
2. Set CLAUDE_CODE_PATH in ~/.claude-mem/settings.json`)}};var Yxe={},Vxe="12.1.2";function V5(t,e){return{continue:!0,suppressOutput:!0,status:t,...e&&{message:e}}}var S_=class{server;startTime=Date.now();mcpClient;mcpReady=!1;initializationCompleteFlag=!1;isShuttingDown=!1;dbManager;sessionManager;sseBroadcaster;sdkAgent;geminiAgent;openRouterAgent;paginationHelper;settingsManager;sessionEventBroadcaster;corpusStore;searchRoutes=null;chromaMcpManager=null;transcriptWatcher=null;initializationComplete;resolveInitialization;stopOrphanReaper=null;staleSessionReaperInterval=null;lastAiInteraction=null;constructor(){this.initializationComplete=new Promise(e=>{this.resolveInitialization=e}),this.dbManager=new Iv,this.sessionManager=new Cv(this.dbManager),this.sseBroadcaster=new Pv,this.sdkAgent=new uy(this.dbManager,this.sessionManager),this.geminiAgent=new ly(this.dbManager,this.sessionManager),this.openRouterAgent=new my(this.dbManager,this.sessionManager),this.paginationHelper=new fy(this.dbManager),this.settingsManager=new hy(this.dbManager),this.sessionEventBroadcaster=new _y(this.sseBroadcaster,this),this.corpusStore=new g_,this.sessionManager.setOnSessionDeleted(()=>{this.broadcastProcessingStatus()}),this.mcpClient=new jc({name:"worker-search-proxy",version:Vxe},{capabilities:{}}),this.server=new Ev({getInitializationComplete:()=>this.initializationCompleteFlag,getMcpReady:()=>this.mcpReady,onShutdown:()=>this.shutdown(),onRestart:()=>this.shutdown(),workerPath:__filename,getAiStatus:()=>{let e="claude";return Ku()&&Da()?e="openrouter":Vu()&&Ma()&&(e="gemini"),{provider:e,authMethod:sg(),lastInteraction:this.lastAiInteraction?{timestamp:this.lastAiInteraction.timestamp,success:this.lastAiInteraction.success,...this.lastAiInteraction.error&&{error:this.lastAiInteraction.error}}:null}}}),this.registerRoutes(),this.registerSignalHandlers()}registerSignalHandlers(){KM(async()=>{this.isShuttingDown=!0,await this.shutdown()})}registerRoutes(){this.server.app.get("/api/context/inject",async(e,r,n)=>{if(!this.initializationCompleteFlag||!this.searchRoutes){_.warn("SYSTEM","Context requested before initialization complete, returning empty"),r.status(200).json({content:[{type:"text",text:""}]});return}n()}),this.server.app.use("/api",async(e,r,n)=>{if(this.initializationCompleteFlag){n();return}let i=3e4,s=new Promise((o,a)=>setTimeout(()=>a(new Error("Database initialization timeout")),i));try{await Promise.race([this.initializationComplete,s]),n()}catch(o){_.error("HTTP",`Request to ${e.method} ${e.path} rejected \u2014 DB not initialized`,{},o),r.status(503).json({error:"Service initializing",message:"Database is still initializing, please retry"})}}),this.server.registerRoutes(new Yy(this.sseBroadcaster,this.dbManager,this.sessionManager)),this.server.registerRoutes(new r_(this.sessionManager,this.dbManager,this.sdkAgent,this.geminiAgent,this.openRouterAgent,this.sessionEventBroadcaster,this)),this.server.registerRoutes(new n_(this.paginationHelper,this.dbManager,this.sessionManager,this.sseBroadcaster,this,this.startTime)),this.server.registerRoutes(new d_(this.settingsManager)),this.server.registerRoutes(new m_),this.server.registerRoutes(new f_(this.dbManager,"claude-mem"))}async start(){let e=Xr(),r=NE();await WM(),await this.server.listen(e,r),oD({pid:process.pid,port:e,startedAt:new Date().toISOString()}),_t().registerProcess("worker",{pid:process.pid,type:"worker",startedAt:new Date().toISOString()}),_.info("SYSTEM","Worker started",{host:r,port:e,pid:process.pid}),this.initializeBackground().catch(n=>{_.error("SYSTEM","Background initialization failed",{},n)})}async initializeBackground(){try{await aD();let{ModeManager:e}=await Promise.resolve().then(()=>(en(),Y6)),{SettingsDefaultsManager:r}=await Promise.resolve().then(()=>(Yt(),wM)),{USER_SETTINGS_PATH:n}=await Promise.resolve().then(()=>($t(),CM)),i=r.loadFromFile(n);(i.CLAUDE_MEM_MODE==="local"||!i.CLAUDE_MEM_MODE)&&cD(),i.CLAUDE_MEM_CHROMA_ENABLED!=="false"?(this.chromaMcpManager=Rs.getInstance(),_.info("SYSTEM","ChromaMcpManager initialized (lazy - connects on first use)")):_.info("SYSTEM","Chroma disabled via CLAUDE_MEM_CHROMA_ENABLED=false, skipping ChromaMcpManager");let o=i.CLAUDE_MEM_MODE;e.getInstance().loadMode(o),_.info("SYSTEM",`Mode loaded: ${o}`),await this.dbManager.initialize();let{PendingMessageStore:a}=await Promise.resolve().then(()=>($a(),bu)),u=new a(this.dbManager.getSessionStore().db,3).resetStaleProcessingMessages(0);u>0&&_.info("SYSTEM",`Reset ${u} stale processing messages to pending`);let l=new vy,d=new yy,p=new gy(this.dbManager.getSessionSearch(),this.dbManager.getSessionStore(),this.dbManager.getChromaSync(),l,d);this.searchRoutes=new c_(p),this.server.registerRoutes(this.searchRoutes),_.info("WORKER","SearchManager initialized and search routes registered");let{SearchOrchestrator:m}=await Promise.resolve().then(()=>(bI(),j9)),f=new m(this.dbManager.getSessionSearch(),this.dbManager.getSessionStore(),this.dbManager.getChromaSync()),h=new y_(this.dbManager.getSessionStore(),f,this.corpusStore),g=new __(this.corpusStore);this.server.registerRoutes(new h_(this.corpusStore,h,g)),_.info("WORKER","CorpusRoutes registered"),this.initializationCompleteFlag=!0,this.resolveInitialization(),_.info("SYSTEM","Core initialization complete (DB + search ready)"),await this.startTranscriptWatcher(i),this.chromaMcpManager&&Zc.backfillAllProjects().then(()=>{_.info("CHROMA_SYNC","Backfill check complete for all projects")}).catch(k=>{_.error("CHROMA_SYNC","Backfill failed (non-blocking)",{},k)});let v=W5.default.join(__dirname,"mcp-server.cjs");this.mcpReady=(0,hR.existsSync)(v),_t().assertCanSpawn("mcp server");let y=new Uc({command:"node",args:[v],env:Cn(process.env)}),b=3e5,S=this.mcpClient.connect(y),x,w=new Promise((k,I)=>{x=setTimeout(()=>I(new Error("MCP connection timeout after 5 minutes")),b)});try{await Promise.race([S,w])}catch(k){clearTimeout(x),_.warn("WORKER","MCP loopback self-check failed, cleaning up subprocess",{error:k instanceof Error?k.message:String(k)});try{await y.close()}catch{}_.info("WORKER","Bundled MCP server remains available for external stdio clients",{path:v});return}clearTimeout(x);let E=y._process;E?.pid&&(_t().registerProcess("mcp-server",{pid:E.pid,type:"mcp",startedAt:new Date().toISOString()},E),E.once("exit",()=>{_t().unregisterProcess("mcp-server")})),_.success("WORKER","MCP loopback self-check connected"),this.stopOrphanReaper=K6(()=>{let k=new Set;for(let[I]of this.sessionManager.sessions)k.add(I);return k}),_.info("SYSTEM","Started orphan reaper (runs every 30 seconds)"),this.staleSessionReaperInterval=setInterval(async()=>{try{let k=await this.sessionManager.reapStaleSessions();k>0&&_.info("SYSTEM",`Reaped ${k} stale sessions`)}catch(k){_.error("SYSTEM","Stale session reaper error",{error:k instanceof Error?k.message:String(k)})}},120*1e3),this.processPendingQueues(50).then(k=>{k.sessionsStarted>0&&_.info("SYSTEM",`Auto-recovered ${k.sessionsStarted} sessions with pending work`,{totalPending:k.totalPendingSessions,started:k.sessionsStarted,sessionIds:k.startedSessionIds})}).catch(k=>{_.error("SYSTEM","Auto-recovery of pending queues failed",{},k)})}catch(e){throw _.error("SYSTEM","Background initialization failed",{},e),e}}async startTranscriptWatcher(e){if(!(e.CLAUDE_MEM_TRANSCRIPTS_ENABLED!=="false")){_.info("TRANSCRIPT","Transcript watcher disabled via CLAUDE_MEM_TRANSCRIPTS_ENABLED=false");return}let n=e.CLAUDE_MEM_TRANSCRIPTS_CONFIG_PATH||Sy,i=Vs(n);try{(0,hR.existsSync)(i)||(U9(n),_.info("TRANSCRIPT","Created default transcript watch config",{configPath:i}));let s=L9(n),o=Vs(s.stateFile??xy);this.transcriptWatcher=new Ky(s,o),await this.transcriptWatcher.start(),_.info("TRANSCRIPT","Transcript watcher started",{configPath:i,statePath:o,watches:s.watches.length})}catch(s){this.transcriptWatcher?.stop(),this.transcriptWatcher=null,_.error("TRANSCRIPT","Failed to start transcript watcher (continuing without Codex ingestion)",{configPath:i},s)}}getActiveAgent(){return Ku()&&Da()?this.openRouterAgent:Vu()&&Ma()?this.geminiAgent:this.sdkAgent}startSessionProcessor(e,r){if(!e)return;let n=e.sessionDbId,i=this.getActiveAgent(),s=i.constructor.name;e.abortController.signal.aborted&&(_.debug("SYSTEM","Replacing aborted AbortController before starting generator",{sessionId:e.sessionDbId}),e.abortController=new AbortController);let o=!1,a=!1;_.info("SYSTEM",`Starting generator (${r}) using ${s}`,{sessionId:n}),e.lastGeneratorActivity=Date.now(),e.generatorPromise=i.startSession(e,this).catch(async c=>{let u=c?.message||"";if(["Claude executable not found","CLAUDE_CODE_PATH","ENOENT","spawn","Invalid API key","API_KEY_INVALID","API key expired","API key not valid","PERMISSION_DENIED","Gemini API error: 400","Gemini API error: 401","Gemini API error: 403","FOREIGN KEY constraint failed"].some(d=>u.includes(d))){o=!0,this.lastAiInteraction={timestamp:Date.now(),success:!1,provider:s,error:u},_.error("SDK","Unrecoverable generator error - will NOT restart",{sessionId:e.sessionDbId,project:e.project,errorMessage:u});return}if(this.isSessionTerminatedError(c))return _.warn("SDK","SDK resume failed, falling back to standalone processing",{sessionId:e.sessionDbId,project:e.project,reason:c instanceof Error?c.message:String(c)}),this.runFallbackForTerminatedSession(e,c);throw(u.includes("aborted by user")||u.includes("No conversation found"))&&e.memorySessionId&&(_.warn("SDK","Detected stale resume failure, clearing memorySessionId for fresh start",{sessionId:e.sessionDbId,memorySessionId:e.memorySessionId,errorMessage:u}),this.dbManager.getSessionStore().updateMemorySessionId(e.sessionDbId,null),e.memorySessionId=null,e.forceInit=!0),_.error("SDK","Session generator failed",{sessionId:e.sessionDbId,project:e.project,provider:s},c),a=!0,this.lastAiInteraction={timestamp:Date.now(),success:!1,provider:s,error:u},c}).finally(async()=>{let c=rs(e.sessionDbId);if(c&&c.process.exitCode===null&&await $o(c,5e3),e.generatorPromise=null,!a&&!o&&(this.lastAiInteraction={timestamp:Date.now(),success:!0,provider:s}),o){this.terminateSession(e.sessionDbId,"unrecoverable_error");return}let l=this.sessionManager.getPendingMessageStore().getPendingCount(e.sessionDbId);if(e.idleTimedOut&&(e.idleTimedOut=!1,l===0)){this.terminateSession(e.sessionDbId,"idle_timeout");return}let d=3;if(l>0){if(e.consecutiveRestarts=(e.consecutiveRestarts||0)+1,e.consecutiveRestarts>d){_.error("SYSTEM","Exceeded max pending-work restarts, stopping to prevent infinite loop",{sessionId:e.sessionDbId,pendingCount:l,consecutiveRestarts:e.consecutiveRestarts}),e.consecutiveRestarts=0,this.terminateSession(e.sessionDbId,"max_restarts_exceeded");return}_.info("SYSTEM","Pending work remains after generator exit, restarting with fresh AbortController",{sessionId:e.sessionDbId,pendingCount:l,attempt:e.consecutiveRestarts}),e.abortController=new AbortController,this.startSessionProcessor(e,"pending-work-restart"),this.broadcastProcessingStatus()}else e.consecutiveRestarts=0,this.sessionManager.removeSessionImmediate(e.sessionDbId)})}isSessionTerminatedError(e){let n=(e instanceof Error?e.message:String(e)).toLowerCase();return n.includes("process aborted by user")||n.includes("processtransport")||n.includes("not ready for writing")||n.includes("session generator failed")||n.includes("claude code process")}async runFallbackForTerminatedSession(e,r){if(!e)return;let n=e.sessionDbId;if(!e.memorySessionId){let o=`fallback-${n}-${Date.now()}`;e.memorySessionId=o,this.dbManager.getSessionStore().updateMemorySessionId(n,o)}if(Ma())try{await this.geminiAgent.startSession(e,this);return}catch(o){_.warn("SDK","Fallback Gemini failed, trying OpenRouter",{sessionId:n,error:o instanceof Error?o.message:String(o)})}if(Da())try{await this.openRouterAgent.startSession(e,this);return}catch(o){_.warn("SDK","Fallback OpenRouter failed",{sessionId:n,error:o instanceof Error?o.message:String(o)})}let s=this.sessionManager.getPendingMessageStore().markAllSessionMessagesAbandoned(n);s>0&&_.warn("SDK","No fallback available; marked pending messages abandoned",{sessionId:n,abandoned:s}),this.sessionManager.removeSessionImmediate(n),this.sessionEventBroadcaster.broadcastSessionCompleted(n)}terminateSession(e,r){let i=this.sessionManager.getPendingMessageStore().markAllSessionMessagesAbandoned(e);_.info("SYSTEM","Session terminated",{sessionId:e,reason:r,abandonedMessages:i}),this.sessionManager.removeSessionImmediate(e)}async processPendingQueues(e=10){let{PendingMessageStore:r}=await Promise.resolve().then(()=>($a(),bu)),n=new r(this.dbManager.getSessionStore().db,3),i=this.dbManager.getSessionStore(),s=360*60*1e3,o=Date.now()-s;try{let u=i.db.prepare(`
|
|
1655
|
+
2. Set CLAUDE_CODE_PATH in ~/.claude-mem/settings.json`)}};var Yxe={},Vxe="12.1.3";function V5(t,e){return{continue:!0,suppressOutput:!0,status:t,...e&&{message:e}}}var S_=class{server;startTime=Date.now();mcpClient;mcpReady=!1;initializationCompleteFlag=!1;isShuttingDown=!1;dbManager;sessionManager;sseBroadcaster;sdkAgent;geminiAgent;openRouterAgent;paginationHelper;settingsManager;sessionEventBroadcaster;corpusStore;searchRoutes=null;chromaMcpManager=null;transcriptWatcher=null;initializationComplete;resolveInitialization;stopOrphanReaper=null;staleSessionReaperInterval=null;lastAiInteraction=null;constructor(){this.initializationComplete=new Promise(e=>{this.resolveInitialization=e}),this.dbManager=new Iv,this.sessionManager=new Cv(this.dbManager),this.sseBroadcaster=new Pv,this.sdkAgent=new uy(this.dbManager,this.sessionManager),this.geminiAgent=new ly(this.dbManager,this.sessionManager),this.openRouterAgent=new my(this.dbManager,this.sessionManager),this.paginationHelper=new fy(this.dbManager),this.settingsManager=new hy(this.dbManager),this.sessionEventBroadcaster=new _y(this.sseBroadcaster,this),this.corpusStore=new g_,this.sessionManager.setOnSessionDeleted(()=>{this.broadcastProcessingStatus()}),this.mcpClient=new jc({name:"worker-search-proxy",version:Vxe},{capabilities:{}}),this.server=new Ev({getInitializationComplete:()=>this.initializationCompleteFlag,getMcpReady:()=>this.mcpReady,onShutdown:()=>this.shutdown(),onRestart:()=>this.shutdown(),workerPath:__filename,getAiStatus:()=>{let e="claude";return Ku()&&Da()?e="openrouter":Vu()&&Ma()&&(e="gemini"),{provider:e,authMethod:sg(),lastInteraction:this.lastAiInteraction?{timestamp:this.lastAiInteraction.timestamp,success:this.lastAiInteraction.success,...this.lastAiInteraction.error&&{error:this.lastAiInteraction.error}}:null}}}),this.registerRoutes(),this.registerSignalHandlers()}registerSignalHandlers(){KM(async()=>{this.isShuttingDown=!0,await this.shutdown()})}registerRoutes(){this.server.app.get("/api/context/inject",async(e,r,n)=>{if(!this.initializationCompleteFlag||!this.searchRoutes){_.warn("SYSTEM","Context requested before initialization complete, returning empty"),r.status(200).json({content:[{type:"text",text:""}]});return}n()}),this.server.app.use("/api",async(e,r,n)=>{if(this.initializationCompleteFlag){n();return}let i=3e4,s=new Promise((o,a)=>setTimeout(()=>a(new Error("Database initialization timeout")),i));try{await Promise.race([this.initializationComplete,s]),n()}catch(o){_.error("HTTP",`Request to ${e.method} ${e.path} rejected \u2014 DB not initialized`,{},o),r.status(503).json({error:"Service initializing",message:"Database is still initializing, please retry"})}}),this.server.registerRoutes(new Yy(this.sseBroadcaster,this.dbManager,this.sessionManager)),this.server.registerRoutes(new r_(this.sessionManager,this.dbManager,this.sdkAgent,this.geminiAgent,this.openRouterAgent,this.sessionEventBroadcaster,this)),this.server.registerRoutes(new n_(this.paginationHelper,this.dbManager,this.sessionManager,this.sseBroadcaster,this,this.startTime)),this.server.registerRoutes(new d_(this.settingsManager)),this.server.registerRoutes(new m_),this.server.registerRoutes(new f_(this.dbManager,"claude-mem"))}async start(){let e=Xr(),r=NE();await WM(),await this.server.listen(e,r),oD({pid:process.pid,port:e,startedAt:new Date().toISOString()}),_t().registerProcess("worker",{pid:process.pid,type:"worker",startedAt:new Date().toISOString()}),_.info("SYSTEM","Worker started",{host:r,port:e,pid:process.pid}),this.initializeBackground().catch(n=>{_.error("SYSTEM","Background initialization failed",{},n)})}async initializeBackground(){try{await aD();let{ModeManager:e}=await Promise.resolve().then(()=>(en(),Y6)),{SettingsDefaultsManager:r}=await Promise.resolve().then(()=>(Yt(),wM)),{USER_SETTINGS_PATH:n}=await Promise.resolve().then(()=>($t(),CM)),i=r.loadFromFile(n);(i.CLAUDE_MEM_MODE==="local"||!i.CLAUDE_MEM_MODE)&&cD(),i.CLAUDE_MEM_CHROMA_ENABLED!=="false"?(this.chromaMcpManager=Rs.getInstance(),_.info("SYSTEM","ChromaMcpManager initialized (lazy - connects on first use)")):_.info("SYSTEM","Chroma disabled via CLAUDE_MEM_CHROMA_ENABLED=false, skipping ChromaMcpManager");let o=i.CLAUDE_MEM_MODE;e.getInstance().loadMode(o),_.info("SYSTEM",`Mode loaded: ${o}`),await this.dbManager.initialize();let{PendingMessageStore:a}=await Promise.resolve().then(()=>($a(),bu)),u=new a(this.dbManager.getSessionStore().db,3).resetStaleProcessingMessages(0);u>0&&_.info("SYSTEM",`Reset ${u} stale processing messages to pending`);let l=new vy,d=new yy,p=new gy(this.dbManager.getSessionSearch(),this.dbManager.getSessionStore(),this.dbManager.getChromaSync(),l,d);this.searchRoutes=new c_(p),this.server.registerRoutes(this.searchRoutes),_.info("WORKER","SearchManager initialized and search routes registered");let{SearchOrchestrator:m}=await Promise.resolve().then(()=>(bI(),j9)),f=new m(this.dbManager.getSessionSearch(),this.dbManager.getSessionStore(),this.dbManager.getChromaSync()),h=new y_(this.dbManager.getSessionStore(),f,this.corpusStore),g=new __(this.corpusStore);this.server.registerRoutes(new h_(this.corpusStore,h,g)),_.info("WORKER","CorpusRoutes registered"),this.initializationCompleteFlag=!0,this.resolveInitialization(),_.info("SYSTEM","Core initialization complete (DB + search ready)"),await this.startTranscriptWatcher(i),this.chromaMcpManager&&Zc.backfillAllProjects().then(()=>{_.info("CHROMA_SYNC","Backfill check complete for all projects")}).catch(k=>{_.error("CHROMA_SYNC","Backfill failed (non-blocking)",{},k)});let v=W5.default.join(__dirname,"mcp-server.cjs");this.mcpReady=(0,hR.existsSync)(v),_t().assertCanSpawn("mcp server");let y=new Uc({command:"node",args:[v],env:Cn(process.env)}),b=3e5,S=this.mcpClient.connect(y),x,w=new Promise((k,I)=>{x=setTimeout(()=>I(new Error("MCP connection timeout after 5 minutes")),b)});try{await Promise.race([S,w])}catch(k){clearTimeout(x),_.warn("WORKER","MCP loopback self-check failed, cleaning up subprocess",{error:k instanceof Error?k.message:String(k)});try{await y.close()}catch{}_.info("WORKER","Bundled MCP server remains available for external stdio clients",{path:v});return}clearTimeout(x);let E=y._process;E?.pid&&(_t().registerProcess("mcp-server",{pid:E.pid,type:"mcp",startedAt:new Date().toISOString()},E),E.once("exit",()=>{_t().unregisterProcess("mcp-server")})),_.success("WORKER","MCP loopback self-check connected"),this.stopOrphanReaper=K6(()=>{let k=new Set;for(let[I]of this.sessionManager.sessions)k.add(I);return k}),_.info("SYSTEM","Started orphan reaper (runs every 30 seconds)"),this.staleSessionReaperInterval=setInterval(async()=>{try{let k=await this.sessionManager.reapStaleSessions();k>0&&_.info("SYSTEM",`Reaped ${k} stale sessions`)}catch(k){_.error("SYSTEM","Stale session reaper error",{error:k instanceof Error?k.message:String(k)})}},120*1e3),this.processPendingQueues(50).then(k=>{k.sessionsStarted>0&&_.info("SYSTEM",`Auto-recovered ${k.sessionsStarted} sessions with pending work`,{totalPending:k.totalPendingSessions,started:k.sessionsStarted,sessionIds:k.startedSessionIds})}).catch(k=>{_.error("SYSTEM","Auto-recovery of pending queues failed",{},k)})}catch(e){throw _.error("SYSTEM","Background initialization failed",{},e),e}}async startTranscriptWatcher(e){if(!(e.CLAUDE_MEM_TRANSCRIPTS_ENABLED!=="false")){_.info("TRANSCRIPT","Transcript watcher disabled via CLAUDE_MEM_TRANSCRIPTS_ENABLED=false");return}let n=e.CLAUDE_MEM_TRANSCRIPTS_CONFIG_PATH||Sy,i=Vs(n);try{(0,hR.existsSync)(i)||(U9(n),_.info("TRANSCRIPT","Created default transcript watch config",{configPath:i}));let s=L9(n),o=Vs(s.stateFile??xy);this.transcriptWatcher=new Ky(s,o),await this.transcriptWatcher.start(),_.info("TRANSCRIPT","Transcript watcher started",{configPath:i,statePath:o,watches:s.watches.length})}catch(s){this.transcriptWatcher?.stop(),this.transcriptWatcher=null,_.error("TRANSCRIPT","Failed to start transcript watcher (continuing without Codex ingestion)",{configPath:i},s)}}getActiveAgent(){return Ku()&&Da()?this.openRouterAgent:Vu()&&Ma()?this.geminiAgent:this.sdkAgent}startSessionProcessor(e,r){if(!e)return;let n=e.sessionDbId,i=this.getActiveAgent(),s=i.constructor.name;e.abortController.signal.aborted&&(_.debug("SYSTEM","Replacing aborted AbortController before starting generator",{sessionId:e.sessionDbId}),e.abortController=new AbortController);let o=!1,a=!1;_.info("SYSTEM",`Starting generator (${r}) using ${s}`,{sessionId:n}),e.lastGeneratorActivity=Date.now(),e.generatorPromise=i.startSession(e,this).catch(async c=>{let u=c?.message||"";if(["Claude executable not found","CLAUDE_CODE_PATH","ENOENT","spawn","Invalid API key","API_KEY_INVALID","API key expired","API key not valid","PERMISSION_DENIED","Gemini API error: 400","Gemini API error: 401","Gemini API error: 403","FOREIGN KEY constraint failed"].some(d=>u.includes(d))){o=!0,this.lastAiInteraction={timestamp:Date.now(),success:!1,provider:s,error:u},_.error("SDK","Unrecoverable generator error - will NOT restart",{sessionId:e.sessionDbId,project:e.project,errorMessage:u});return}if(this.isSessionTerminatedError(c))return _.warn("SDK","SDK resume failed, falling back to standalone processing",{sessionId:e.sessionDbId,project:e.project,reason:c instanceof Error?c.message:String(c)}),this.runFallbackForTerminatedSession(e,c);throw(u.includes("aborted by user")||u.includes("No conversation found"))&&e.memorySessionId&&(_.warn("SDK","Detected stale resume failure, clearing memorySessionId for fresh start",{sessionId:e.sessionDbId,memorySessionId:e.memorySessionId,errorMessage:u}),this.dbManager.getSessionStore().updateMemorySessionId(e.sessionDbId,null),e.memorySessionId=null,e.forceInit=!0),_.error("SDK","Session generator failed",{sessionId:e.sessionDbId,project:e.project,provider:s},c),a=!0,this.lastAiInteraction={timestamp:Date.now(),success:!1,provider:s,error:u},c}).finally(async()=>{let c=rs(e.sessionDbId);if(c&&c.process.exitCode===null&&await $o(c,5e3),e.generatorPromise=null,!a&&!o&&(this.lastAiInteraction={timestamp:Date.now(),success:!0,provider:s}),o){this.terminateSession(e.sessionDbId,"unrecoverable_error");return}let l=this.sessionManager.getPendingMessageStore().getPendingCount(e.sessionDbId);if(e.idleTimedOut&&(e.idleTimedOut=!1,l===0)){this.terminateSession(e.sessionDbId,"idle_timeout");return}let d=3;if(l>0){if(e.consecutiveRestarts=(e.consecutiveRestarts||0)+1,e.consecutiveRestarts>d){_.error("SYSTEM","Exceeded max pending-work restarts, stopping to prevent infinite loop",{sessionId:e.sessionDbId,pendingCount:l,consecutiveRestarts:e.consecutiveRestarts}),e.consecutiveRestarts=0,this.terminateSession(e.sessionDbId,"max_restarts_exceeded");return}_.info("SYSTEM","Pending work remains after generator exit, restarting with fresh AbortController",{sessionId:e.sessionDbId,pendingCount:l,attempt:e.consecutiveRestarts}),e.abortController=new AbortController,this.startSessionProcessor(e,"pending-work-restart"),this.broadcastProcessingStatus()}else e.consecutiveRestarts=0,this.sessionManager.removeSessionImmediate(e.sessionDbId)})}isSessionTerminatedError(e){let n=(e instanceof Error?e.message:String(e)).toLowerCase();return n.includes("process aborted by user")||n.includes("processtransport")||n.includes("not ready for writing")||n.includes("session generator failed")||n.includes("claude code process")}async runFallbackForTerminatedSession(e,r){if(!e)return;let n=e.sessionDbId;if(!e.memorySessionId){let o=`fallback-${n}-${Date.now()}`;e.memorySessionId=o,this.dbManager.getSessionStore().updateMemorySessionId(n,o)}if(Ma())try{await this.geminiAgent.startSession(e,this);return}catch(o){_.warn("SDK","Fallback Gemini failed, trying OpenRouter",{sessionId:n,error:o instanceof Error?o.message:String(o)})}if(Da())try{await this.openRouterAgent.startSession(e,this);return}catch(o){_.warn("SDK","Fallback OpenRouter failed",{sessionId:n,error:o instanceof Error?o.message:String(o)})}let s=this.sessionManager.getPendingMessageStore().markAllSessionMessagesAbandoned(n);s>0&&_.warn("SDK","No fallback available; marked pending messages abandoned",{sessionId:n,abandoned:s}),this.sessionManager.removeSessionImmediate(n),this.sessionEventBroadcaster.broadcastSessionCompleted(n)}terminateSession(e,r){let i=this.sessionManager.getPendingMessageStore().markAllSessionMessagesAbandoned(e);_.info("SYSTEM","Session terminated",{sessionId:e,reason:r,abandonedMessages:i}),this.sessionManager.removeSessionImmediate(e)}async processPendingQueues(e=10){let{PendingMessageStore:r}=await Promise.resolve().then(()=>($a(),bu)),n=new r(this.dbManager.getSessionStore().db,3),i=this.dbManager.getSessionStore(),s=360*60*1e3,o=Date.now()-s;try{let u=i.db.prepare(`
|
|
1656
1656
|
SELECT id FROM sdk_sessions
|
|
1657
1657
|
WHERE status = 'active' AND started_at_epoch < ?
|
|
1658
1658
|
`).all(o);if(u.length>0){let l=u.map(m=>m.id),d=l.map(()=>"?").join(",");i.db.prepare(`
|