claude-mem 10.7.1 → 11.0.0
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/modes/code.json
CHANGED
|
@@ -87,8 +87,8 @@
|
|
|
87
87
|
"system_identity": "You are a Claude-Mem, a specialized observer tool for creating searchable memory FOR FUTURE SESSIONS.\n\nCRITICAL: Record what was LEARNED/BUILT/FIXED/DEPLOYED/CONFIGURED, not what you (the observer) are doing.\n\nYou do not have access to tools. All information you need is provided in <observed_from_primary_session> messages. Create observations from what you observe - no investigation needed.",
|
|
88
88
|
"spatial_awareness": "SPATIAL AWARENESS: Tool executions include the working directory (tool_cwd) to help you understand:\n- Which repository/project is being worked on\n- Where files are located relative to the project root\n- How to match requested paths to actual execution paths",
|
|
89
89
|
"observer_role": "Your job is to monitor a different Claude Code session happening RIGHT NOW, with the goal of creating observations and progress summaries as the work is being done LIVE by the user. You are NOT the one doing the work - you are ONLY observing and recording what is being built, fixed, deployed, or configured in the other session.",
|
|
90
|
-
"recording_focus": "WHAT TO RECORD\n--------------\nFocus on
|
|
91
|
-
"skip_guidance": "WHEN TO SKIP\n------------\nSkip routine operations:\n- Empty status checks\n- Package installations with no errors\n- Simple file listings\n- Repetitive operations you've already documented\n-
|
|
90
|
+
"recording_focus": "WHAT TO RECORD\n--------------\nFocus on durable technical signal:\n- What the system NOW DOES differently (new capabilities)\n- What shipped to users/production (features, fixes, configs, docs)\n- Changes in technical domains (auth, data, UI, infra, DevOps, docs)\n- Concrete debugging or investigative findings from logs, traces, queue state, database rows, and code-path inspection\n\nUse verbs like: implemented, fixed, deployed, configured, migrated, optimized, added, refactored, discovered, confirmed, traced\n\n✅ GOOD EXAMPLES (describes what was built or learned):\n- \"Authentication now supports OAuth2 with PKCE flow\"\n- \"Deployment pipeline runs canary releases with auto-rollback\"\n- \"Database indexes optimized for common query patterns\"\n- \"Observation queue for claude-mem session timed out waiting for an agent pool slot\"\n- \"Fallback processing abandoned pending messages after Gemini and OpenRouter returned 404\"\n\n❌ BAD EXAMPLES (describes observation process - DO NOT DO THIS):\n- \"Analyzed authentication implementation and stored findings\"\n- \"Tracked deployment steps and logged outcomes\"\n- \"Monitored database performance and recorded metrics\"",
|
|
91
|
+
"skip_guidance": "WHEN TO SKIP\n------------\nSkip routine operations:\n- Empty status checks\n- Package installations with no errors\n- Simple file listings with no follow-on finding\n- Repetitive operations you've already documented\n- File related research that comes back empty or not found\n\nIf skipping, return an empty response only. Do not explain the skip in prose.",
|
|
92
92
|
"type_guidance": "**type**: MUST be EXACTLY one of these 6 options (no other values allowed):\n - bugfix: something was broken, now fixed\n - feature: new capability or functionality added\n - refactor: code restructured, behavior unchanged\n - change: generic modification (docs, config, misc)\n - discovery: learning about existing system\n - decision: architectural/design choice with rationale",
|
|
93
93
|
"concept_guidance": "**concepts**: 2-5 knowledge-type categories. MUST use ONLY these exact keywords:\n - how-it-works: understanding mechanisms\n - why-it-exists: purpose or rationale\n - what-changed: modifications made\n - problem-solution: issues and their fixes\n - gotcha: traps or edge cases\n - pattern: reusable approach\n - trade-off: pros/cons of a decision\n\n IMPORTANT: Do NOT include the observation type (change/discovery/decision) as a concept.\n Types and concepts are separate dimensions.",
|
|
94
94
|
"field_guidance": "**facts**: Concise, self-contained statements\nEach fact is ONE piece of information\n No pronouns - each fact must stand alone\n Include specific details: filenames, functions, values\n\n**files**: All files touched (full paths from project root)",
|
|
@@ -122,4 +122,4 @@
|
|
|
122
122
|
"summary_format_instruction": "Respond in this XML format:",
|
|
123
123
|
"summary_footer": "IMPORTANT! DO NOT do any work right now other than generating this next PROGRESS SUMMARY - and remember that you are a memory agent designed to summarize a DIFFERENT claude code session, not this one.\n\nNever reference yourself or your own actions. Do not output anything other than the summary content formatted in the XML structure above. All other output is ignored by the system, and the system has been designed to be smart about token usage. Please spend your tokens wisely on useful summary content.\n\nThank you, this summary will be very useful for keeping track of our progress!"
|
|
124
124
|
}
|
|
125
|
-
}
|
|
125
|
+
}
|
package/plugin/package.json
CHANGED
|
@@ -114,7 +114,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
114
114
|
${c}`}var xP=new Set([".js",".jsx",".ts",".tsx",".mjs",".cjs",".py",".pyw",".go",".rs",".rb",".java",".cs",".cpp",".c",".h",".hpp",".swift",".kt",".php",".vue",".svelte"]),kP=new Set(["node_modules",".git","dist","build",".next","__pycache__",".venv","venv","env",".env","target","vendor",".cache",".turbo","coverage",".nyc_output",".claude",".smart-file-read"]),SP=512*1024;async function*u$(t,e,r=20){if(r<=0)return;let n;try{n=await(0,zn.readdir)(t,{withFileTypes:!0})}catch{return}for(let o of n){if(o.name.startsWith(".")&&o.name!=="."||kP.has(o.name))continue;let i=(0,mi.join)(t,o.name);if(o.isDirectory())yield*u$(i,e,r-1);else if(o.isFile()){let a=o.name.slice(o.name.lastIndexOf("."));xP.has(a)&&(yield i)}}}async function wP(t){try{let e=await(0,zn.stat)(t);if(e.size>SP||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 l$(t,e,r={}){let n=r.maxResults||20,o=e.toLowerCase(),i=o.split(/[\s_\-./]+/).filter(h=>h.length>0),a=[];for await(let h of u$(t,t)){if(r.filePattern&&!(0,mi.relative)(t,h).toLowerCase().includes(r.filePattern.toLowerCase()))continue;let _=await wP(h);_&&a.push({absolutePath:h,relativePath:(0,mi.relative)(t,h),content:_})}let s=a$(a),c=[],u=[],l=0;for(let[h,_]of s){l+=zP(_);let E=js(h.toLowerCase(),i)>0,I=[],A=(j,Le)=>{for(let pe of j){let Wt=0,Qe="",Kt=js(pe.name.toLowerCase(),i);Kt>0&&(Wt+=Kt*3,Qe="name match"),pe.signature.toLowerCase().includes(o)&&(Wt+=2,Qe=Qe?`${Qe} + signature`:"signature match"),pe.jsdoc&&pe.jsdoc.toLowerCase().includes(o)&&(Wt+=1,Qe=Qe?`${Qe} + jsdoc`:"jsdoc match"),Wt>0&&(E=!0,I.push({filePath:h,symbolName:Le?`${Le}.${pe.name}`:pe.name,kind:pe.kind,signature:pe.signature,jsdoc:pe.jsdoc,lineStart:pe.lineStart,lineEnd:pe.lineEnd,matchReason:Qe})),pe.children&&A(pe.children,pe.name)}};A(_.symbols),E&&(c.push(_),u.push(...I))}u.sort((h,_)=>{let b=js(h.symbolName.toLowerCase(),i);return js(_.symbolName.toLowerCase(),i)-b});let d=u.slice(0,n),p=new Set(d.map(h=>h.filePath)),f=c.filter(h=>p.has(h.filePath)).slice(0,n),v=f.reduce((h,_)=>h+_.foldedTokenEstimate,0);return{foldedFiles:f,matchingSymbols:d,totalFilesScanned:a.length,totalSymbolsFound:l,tokenEstimate:v}}function js(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 zP(t){let e=t.symbols.length;for(let r of t.symbols)r.children&&(e+=r.children.length);return e}function d$(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(`
|
|
115
115
|
`);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(`
|
|
116
116
|
`).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(wn(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(`
|
|
117
|
-
`)}var jf=require("node:fs/promises"),Ds=require("node:path"),IP="
|
|
117
|
+
`)}var jf=require("node:fs/promises"),Ds=require("node:path"),IP="11.0.0";console.log=(...t)=>{ve.error("CONSOLE","Intercepted console output (MCP protocol protection)",void 0,{args:t})};var p$={search:"/api/search",timeline:"/api/timeline"};async function f$(t,e){ve.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 Ps(n);if(!o.ok){let a=await o.text();throw new Error(`Worker API error (${o.status}): ${a}`)}let i=await o.json();return ve.debug("SYSTEM","\u2190 Worker API success",void 0,{endpoint:t}),i}catch(r){return ve.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 EP(t,e){ve.debug("HTTP","Worker API request (POST)",void 0,{endpoint:t});try{let r=await Ps(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 ve.debug("HTTP","Worker API success (POST)",void 0,{endpoint:t}),{content:[{type:"text",text:JSON.stringify(n,null,2)}]}}catch(r){return ve.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 TP(){try{return(await Ps("/api/health")).ok}catch(t){return ve.debug("SYSTEM","Worker health check failed",{},t),!1}}var m$=[{name:"__IMPORTANT",description:`3-LAYER WORKFLOW (ALWAYS FOLLOW):
|
|
118
118
|
1. search(query) \u2192 Get index with IDs (~50-100 tokens/result)
|
|
119
119
|
2. timeline(anchor=ID) \u2192 Get context around interesting results
|
|
120
120
|
3. get_observations([IDs]) \u2192 Fetch full details ONLY for filtered IDs
|
|
@@ -925,7 +925,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
925
925
|
JOIN sdk_sessions s ON up.content_session_id = s.content_session_id
|
|
926
926
|
WHERE s.project = ?
|
|
927
927
|
`).get(r);b.info("CHROMA_SYNC","Backfilling user prompts",{project:r,missing:v.length,existing:n.prompts.size,total:_.count});let S=[];for(let y of v)S.push(this.formatUserPromptDoc(y));for(let y=0;y<S.length;y+=this.BATCH_SIZE){let x=S.slice(y,y+this.BATCH_SIZE);await this.addDocuments(x),b.debug("CHROMA_SYNC","Backfill progress",{project:r,progress:`${Math.min(y+this.BATCH_SIZE,S.length)}/${S.length}`})}b.info("CHROMA_SYNC","Smart backfill complete",{project:r,synced:{observationDocs:u.length,summaryDocs:m.length,promptDocs:S.length},skipped:{observations:n.observations.size,summaries:n.summaries.size,prompts:n.prompts.size}})}catch(s){throw b.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 ks.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 f=0;f<c.length;f++){let m=c[f],h=m.match(/obs_(\d+)_/),g=m.match(/summary_(\d+)_/),v=m.match(/prompt_(\d+)/),_=null;h?_=parseInt(h[1],10):g?_=parseInt(g[1],10):v&&(_=parseInt(v[1],10)),_!==null&&!a.has(_)&&(a.add(_),o.push(_),d.push(u[f]??null),p.push(l[f]??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,b.error("CHROMA_SYNC","Connection lost during query",{project:this.project,query:e},i),new Error(`Chroma query failed - connection lost: ${s}`)):(b.error("CHROMA_SYNC","Query failed",{project:this.project,query:e},i),i)}}static async backfillAllProjects(){let e=new Ts,r=new t("claude-mem");try{let n=e.db.prepare("SELECT DISTINCT project FROM observations WHERE project IS NOT NULL AND project != ?").all("");b.info("CHROMA_SYNC",`Backfill check for ${n.length} projects`);for(let{project:i}of n)try{await r.ensureBackfilled(i)}catch(s){b.error("CHROMA_SYNC",`Backfill failed for project: ${i}`,{},s)}}finally{await r.close(),e.close()}}async close(){b.info("CHROMA_SYNC","ChromaSync closed",{project:this.project})}};var ug=require("fs"),HE=require("path"),BM=require("os"),sQ="claude-mem@thedotmack";function lg(){try{let t=process.env.CLAUDE_CONFIG_DIR||(0,HE.join)((0,BM.homedir)(),".claude"),e=(0,HE.join)(t,"settings.json");if(!(0,ug.existsSync)(e))return!1;let r=(0,ug.readFileSync)(e,"utf-8");return JSON.parse(r)?.enabledPlugins?.[sQ]===!1}catch{return!1}}var qi=Pe(require("path"),1),BE=require("os"),Lt=require("fs"),$s=require("child_process"),KM=require("util");re();$n();var GM=(0,KM.promisify)($s.exec),GE=qi.default.join((0,BE.homedir)(),".claude-mem"),Hi=qi.default.join(GE,"worker.pid");var WM=30;function VM(t){return t?/(^|[\\/])bun(\.exe)?$/i.test(t.trim()):!1}function oQ(t,e){let r=e==="win32"?`where ${t}`:`which ${t}`;try{return(0,$s.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}}function aQ(t={}){let e=t.platform??process.platform,r=t.execPath??process.execPath;if(e!=="win32"||VM(r))return r;let n=t.env??process.env,i=t.homeDirectory??(0,BE.homedir)(),s=t.pathExists??Lt.existsSync,o=t.lookupInPath??oQ,a=[n.BUN,n.BUN_PATH,qi.default.join(i,".bun","bin","bun.exe"),qi.default.join(i,".bun","bin","bun"),n.USERPROFILE?qi.default.join(n.USERPROFILE,".bun","bin","bun.exe"):void 0,n.LOCALAPPDATA?qi.default.join(n.LOCALAPPDATA,"bun","bun.exe"):void 0,n.LOCALAPPDATA?qi.default.join(n.LOCALAPPDATA,"bun","bin","bun.exe"):void 0];for(let c of a){let u=c?.trim();if(u&&(VM(u)&&s(u)||u.toLowerCase()==="bun"))return u}return o("bun",e)}function JM(t){(0,Lt.mkdirSync)(GE,{recursive:!0}),(0,Lt.writeFileSync)(Hi,JSON.stringify(t,null,2))}function WE(){if(!(0,Lt.existsSync)(Hi))return null;try{return JSON.parse((0,Lt.readFileSync)(Hi,"utf-8"))}catch(t){return b.warn("SYSTEM","Failed to parse PID file",{path:Hi},t),null}}function Yo(){if((0,Lt.existsSync)(Hi))try{(0,Lt.unlinkSync)(Hi)}catch(t){b.warn("SYSTEM","Failed to remove PID file",{path:Hi},t)}}function Is(t){return process.platform==="win32"?Math.round(t*2):t}function cQ(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 ZE=["worker-service.cjs","chroma-mcp"],uQ=["mcp-server.cjs"];async function XM(){let t=process.platform==="win32",e=process.pid,r=[],n=[...ZE,...uQ];try{if(t){let s=`powershell -NoProfile -NonInteractive -Command "Get-CimInstance Win32_Process -Filter '(${n.map(l=>`CommandLine LIKE '%${l}%'`).join(" OR ")}) AND ProcessId != ${e}' | Select-Object ProcessId, CommandLine, CreationDate | ConvertTo-Json"`,{stdout:o}=await GM(s,{timeout:kr.POWERSHELL_COMMAND,windowsHide:!0});if(!o.trim()||o.trim()==="null"){b.debug("SYSTEM","No orphaned claude-mem processes found (Windows)");return}let a=JSON.parse(o),c=Array.isArray(a)?a:[a],u=Date.now();for(let l of c){let d=l.ProcessId;if(!Number.isInteger(d)||d<=0||d===e)continue;let p=l.CommandLine||"";if(ZE.some(m=>p.includes(m)))r.push(d),b.debug("SYSTEM","Found orphaned process (aggressive)",{pid:d,commandLine:p.substring(0,80)});else{let m=l.CreationDate?.match(/\/Date\((\d+)\)\//);if(m){let h=parseInt(m[1],10),g=(u-h)/(1e3*60);g>=WM&&(r.push(d),b.debug("SYSTEM","Found orphaned process (age-gated)",{pid:d,ageMinutes:Math.round(g)}))}}}}else{let i=n.join("|"),{stdout:s}=await GM(`ps -eo pid,etime,command | grep -E "${i}" | grep -v grep || true`);if(!s.trim()){b.debug("SYSTEM","No orphaned claude-mem processes found (Unix)");return}let o=s.trim().split(`
|
|
928
|
-
`);for(let a of o){let c=a.trim().match(/^(\d+)\s+(\S+)\s+(.*)$/);if(!c)continue;let u=parseInt(c[1],10),l=c[2],d=c[3];if(!Number.isInteger(u)||u<=0||u===e)continue;if(ZE.some(f=>d.includes(f)))r.push(u),b.debug("SYSTEM","Found orphaned process (aggressive)",{pid:u,command:d.substring(0,80)});else{let f=cQ(l);f>=WM&&(r.push(u),b.debug("SYSTEM","Found orphaned process (age-gated)",{pid:u,ageMinutes:f,command:d.substring(0,80)}))}}}}catch(i){b.error("SYSTEM","Failed to enumerate orphaned processes during aggressive cleanup",{},i);return}if(r.length!==0){if(b.info("SYSTEM","Aggressive startup cleanup: killing orphaned processes",{platform:t?"Windows":"Unix",count:r.length,pids:r}),t){for(let i of r)if(!(!Number.isInteger(i)||i<=0))try{(0,$s.execSync)(`taskkill /PID ${i} /T /F`,{timeout:kr.POWERSHELL_COMMAND,stdio:"ignore",windowsHide:!0})}catch(s){b.debug("SYSTEM","Failed to kill process, may have already exited",{pid:i},s)}}else for(let i of r)try{process.kill(i,"SIGKILL")}catch(s){b.debug("SYSTEM","Process already exited",{pid:i},s)}b.info("SYSTEM","Aggressive startup cleanup complete",{count:r.length})}}var lQ=".chroma-cleaned-v10.3";function YM(t){let e=t??GE,r=qi.default.join(e,lQ),n=qi.default.join(e,"chroma");if((0,Lt.existsSync)(r)){b.debug("SYSTEM","Chroma migration marker exists, skipping wipe");return}b.warn("SYSTEM","Running one-time chroma data wipe (upgrade from pre-v10.3)",{chromaDir:n}),(0,Lt.existsSync)(n)&&((0,Lt.rmSync)(n,{recursive:!0,force:!0}),b.info("SYSTEM","Chroma data directory removed",{chromaDir:n})),(0,Lt.mkdirSync)(e,{recursive:!0}),(0,Lt.writeFileSync)(r,new Date().toISOString()),b.info("SYSTEM","Chroma migration marker written",{markerPath:r})}function VE(t,e,r={}){let n=process.platform==="win32";vt().assertCanSpawn("worker daemon");let i=Fi({...process.env,CLAUDE_MEM_WORKER_PORT:String(e),...r});if(n){let a=aQ();if(!a){b.error("SYSTEM","Failed to locate Bun runtime for Windows worker spawn");return}let c=`Start-Process -FilePath '${a.replace(/'/g,"''")}' -ArgumentList @('${t.replace(/'/g,"''")}','--daemon') -WindowStyle Hidden`,u=Buffer.from(c,"utf16le").toString("base64");try{return(0,$s.execSync)(`powershell -NoProfile -EncodedCommand ${u}`,{stdio:"ignore",windowsHide:!0,env:i}),0}catch(l){b.error("SYSTEM","Failed to spawn worker daemon on Windows",{runtimePath:a},l);return}}let s="/usr/bin/setsid";if((0,Lt.existsSync)(s)){let a=(0,$s.spawn)(s,[process.execPath,t,"--daemon"],{detached:!0,stdio:"ignore",env:i});return a.pid===void 0?void 0:(a.unref(),a.pid)}let o=(0,$s.spawn)(process.execPath,[t,"--daemon"],{detached:!0,stdio:"ignore",env:i});if(o.pid!==void 0)return o.unref(),o.pid}function QM(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 eD(t=15e3){try{let e=(0,Lt.statSync)(Hi);return Date.now()-e.mtimeMs<t}catch{return!1}}function tD(){try{if(!(0,Lt.existsSync)(Hi))return;let t=new Date;(0,Lt.utimesSync)(Hi,t,t)}catch{}}function rD(){return LE({logAlive:!1})}var nD=Pe(require("path"),1),iD=Pe(require("net"),1),sD=require("fs");re();zt();async function KE(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 Ud(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=iD.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 oD(t,e,r,n){let i=Date.now();for(;Date.now()-i<r;){try{if((await KE(t,e)).ok)return!0}catch(s){b.debug("SYSTEM",n,{},s)}await new Promise(s=>setTimeout(s,500))}return!1}function Qo(t,e=3e4){return oD(t,"/api/health",e,"Service not ready yet, will retry")}function aD(t,e=3e4){return oD(t,"/api/readiness",e,"Worker not ready yet, will retry")}async function dg(t,e=1e4){let r=Date.now();for(;Date.now()-r<e;){if(!await Ud(t))return!0;await new Promise(n=>setTimeout(n,500))}return!1}async function pg(t){try{let e=await KE(t,"/api/admin/shutdown","POST");return e.ok?!0:(b.warn("SYSTEM","Shutdown request returned error",{status:e.statusCode}),!1)}catch(e){return e instanceof Error&&e.message?.includes("ECONNREFUSED")?(b.debug("SYSTEM","Worker already stopped",{},e),!1):(b.error("SYSTEM","Shutdown request failed unexpectedly",{},e),!1)}}function dQ(){try{let t=nD.default.join(ws,"package.json");return JSON.parse((0,sD.readFileSync)(t,"utf-8")).version}catch(t){let e=t.code;if(e==="ENOENT"||e==="EBUSY")return b.debug("SYSTEM","Could not read plugin version (shutdown race)",{code:e}),"unknown";throw t}}async function pQ(t){try{let e=await KE(t,"/api/version");return e.ok?JSON.parse(e.body).version:null}catch{return b.debug("SYSTEM","Could not fetch worker version",{}),null}}async function cD(t){let e=dQ(),r=await pQ(t);return!r||e==="unknown"?{matches:!0,pluginVersion:e,workerVersion:r}:{matches:e===r,pluginVersion:e,workerVersion:r}}re();async function uD(t){b.info("SYSTEM","Shutdown initiated"),t.server&&(await fQ(t.server),b.info("SYSTEM","HTTP server closed")),await t.sessionManager.shutdownAll(),t.mcpClient&&(await t.mcpClient.close(),b.info("SYSTEM","MCP client closed")),t.chromaMcpManager&&(b.info("SHUTDOWN","Stopping Chroma MCP connection..."),await t.chromaMcpManager.stop(),b.info("SHUTDOWN","Chroma MCP connection stopped")),t.dbManager&&await t.dbManager.close(),await zM(),b.info("SYSTEM","Worker shutdown complete")}async function fQ(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)),b.info("SYSTEM","Waited for Windows port cleanup"))}var _6=Pe(_v(),1),t$=Pe(require("fs"),1),kp=Pe(require("path"),1);var o6=["search","context","summarize","import","export"],a6=["workflow","search_params","examples","all"];re();var YT=Pe(_v(),1),f6=Pe(p6(),1),m6=Pe(require("path"),1);zt();re();function QT(t){let e=[];e.push(YT.default.json({limit:"50mb"})),e.push((0,f6.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(m=>i.path.endsWith(m)),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);b.debug("HTTP",`\u2192 ${i.method} ${i.path}`,{requestId:d},p);let f=s.send.bind(s);s.send=function(m){let h=Date.now()-l;return b.debug("HTTP",`\u2190 ${s.statusCode} ${i.path}`,{requestId:d,duration:`${h}ms`}),f(m)},o()});let r=dn(),n=m6.default.join(r,"plugin","ui");return e.push(YT.default.static(n)),e}function Ep(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")){b.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 e$(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=${b.formatTool(n,i)}`}return e.includes("/summarize")?"requesting summary":""}re();var cu=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 h6(t,e,r,n){let i={error:t,message:e};return r&&(i.code=r),n&&(i.details=n),i}var g6=(t,e,r,n)=>{let i=t instanceof cu?t.statusCode:500;b.error("HTTP",`Error handling ${e.method} ${e.path}`,{statusCode:i,error:t.message,code:t instanceof cu?t.code:void 0},t);let s=h6(t.name||"Error",t.message,t instanceof cu?t.code:void 0,t instanceof cu?t.details:void 0);r.status(i).json(s)};function v6(t,e){e.status(404).json(h6("NotFound",`Cannot ${t.method} ${t.path}`))}var y6="10.7.1",bv=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,()=>{b.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,b.info("SYSTEM","HTTP server closed"))}registerRoutes(e){e.setupRoutes(this.app)}finalizeRoutes(){this.app.use(v6),this.app.use(g6)}setupMiddleware(){QT(e$).forEach(r=>this.app.use(r))}setupCoreRoutes(){this.app.get("/api/health",(e,r)=>{r.status(200).json({status:"ok",version:y6,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:y6})}),this.app.get("/api/instructions",async(e,r)=>{let n=e.query.topic||"all",i=e.query.operation;if(n&&!a6.includes(n))return r.status(400).json({error:"Invalid topic"});try{let s;if(i){if(!o6.includes(i))return r.status(400).json({error:"Invalid operation"});let o=kp.default.resolve(__dirname,"../skills/mem-search/operations"),a=kp.default.resolve(o,`${i}.md`);if(!a.startsWith(o+kp.default.sep))return r.status(400).json({error:"Invalid request"});s=await t$.promises.readFile(a,"utf-8")}else{let o=kp.default.join(__dirname,"../skills/mem-search/SKILL.md"),a=await t$.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",Ep,async(e,r)=>{r.json({status:"restarting"}),process.platform==="win32"&&process.env.CLAUDE_MEM_MANAGED==="true"&&process.send?(b.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",Ep,async(e,r)=>{r.json({status:"shutting_down"}),process.platform==="win32"&&process.env.CLAUDE_MEM_MANAGED==="true"&&process.send?(b.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",Ep,(e,r)=>{let o=vt().getRegistry().getAll().map(m=>({id:m.id,pid:m.pid,type:m.type,status:In(m.pid)?"alive":"dead",startedAt:m.startedAt})),a=o.filter(m=>m.status==="dead").map(m=>m.pid),c=!Object.keys(process.env).some(m=>AE.has(m)||PE.some(h=>m.startsWith(h))),u=Date.now()-this.startTime,l=Math.floor(u/1e3),d=Math.floor(l/3600),p=Math.floor(l%3600/60),f=d>0?`${d}h ${p}m`:`${p}m`;r.json({supervisor:{running:!0,pid:process.pid,uptime:f},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 Rt=Pe(require("path"),1),$p=require("os"),Kt=require("fs"),x6=require("child_process"),w6=require("util");re();Dr();zt();var Kn=require("fs"),Tp=require("path");re();function b6(t){try{return(0,Kn.existsSync)(t)?JSON.parse((0,Kn.readFileSync)(t,"utf-8")):{}}catch(e){return b.error("CONFIG","Failed to read Cursor registry, using empty registry",{file:t,error:e instanceof Error?e.message:String(e)}),{}}}function S6(t,e){let r=(0,Tp.join)(t,"..");(0,Kn.mkdirSync)(r,{recursive:!0}),(0,Kn.writeFileSync)(t,JSON.stringify(e,null,2))}function r$(t,e){let r=(0,Tp.join)(t,".cursor","rules"),n=(0,Tp.join)(r,"claude-mem-context.mdc"),i=`${n}.tmp`;(0,Kn.mkdirSync)(r,{recursive:!0});let s=`---
|
|
928
|
+
`);for(let a of o){let c=a.trim().match(/^(\d+)\s+(\S+)\s+(.*)$/);if(!c)continue;let u=parseInt(c[1],10),l=c[2],d=c[3];if(!Number.isInteger(u)||u<=0||u===e)continue;if(ZE.some(f=>d.includes(f)))r.push(u),b.debug("SYSTEM","Found orphaned process (aggressive)",{pid:u,command:d.substring(0,80)});else{let f=cQ(l);f>=WM&&(r.push(u),b.debug("SYSTEM","Found orphaned process (age-gated)",{pid:u,ageMinutes:f,command:d.substring(0,80)}))}}}}catch(i){b.error("SYSTEM","Failed to enumerate orphaned processes during aggressive cleanup",{},i);return}if(r.length!==0){if(b.info("SYSTEM","Aggressive startup cleanup: killing orphaned processes",{platform:t?"Windows":"Unix",count:r.length,pids:r}),t){for(let i of r)if(!(!Number.isInteger(i)||i<=0))try{(0,$s.execSync)(`taskkill /PID ${i} /T /F`,{timeout:kr.POWERSHELL_COMMAND,stdio:"ignore",windowsHide:!0})}catch(s){b.debug("SYSTEM","Failed to kill process, may have already exited",{pid:i},s)}}else for(let i of r)try{process.kill(i,"SIGKILL")}catch(s){b.debug("SYSTEM","Process already exited",{pid:i},s)}b.info("SYSTEM","Aggressive startup cleanup complete",{count:r.length})}}var lQ=".chroma-cleaned-v10.3";function YM(t){let e=t??GE,r=qi.default.join(e,lQ),n=qi.default.join(e,"chroma");if((0,Lt.existsSync)(r)){b.debug("SYSTEM","Chroma migration marker exists, skipping wipe");return}b.warn("SYSTEM","Running one-time chroma data wipe (upgrade from pre-v10.3)",{chromaDir:n}),(0,Lt.existsSync)(n)&&((0,Lt.rmSync)(n,{recursive:!0,force:!0}),b.info("SYSTEM","Chroma data directory removed",{chromaDir:n})),(0,Lt.mkdirSync)(e,{recursive:!0}),(0,Lt.writeFileSync)(r,new Date().toISOString()),b.info("SYSTEM","Chroma migration marker written",{markerPath:r})}function VE(t,e,r={}){let n=process.platform==="win32";vt().assertCanSpawn("worker daemon");let i=Fi({...process.env,CLAUDE_MEM_WORKER_PORT:String(e),...r});if(n){let a=aQ();if(!a){b.error("SYSTEM","Failed to locate Bun runtime for Windows worker spawn");return}let c=`Start-Process -FilePath '${a.replace(/'/g,"''")}' -ArgumentList @('${t.replace(/'/g,"''")}','--daemon') -WindowStyle Hidden`,u=Buffer.from(c,"utf16le").toString("base64");try{return(0,$s.execSync)(`powershell -NoProfile -EncodedCommand ${u}`,{stdio:"ignore",windowsHide:!0,env:i}),0}catch(l){b.error("SYSTEM","Failed to spawn worker daemon on Windows",{runtimePath:a},l);return}}let s="/usr/bin/setsid";if((0,Lt.existsSync)(s)){let a=(0,$s.spawn)(s,[process.execPath,t,"--daemon"],{detached:!0,stdio:"ignore",env:i});return a.pid===void 0?void 0:(a.unref(),a.pid)}let o=(0,$s.spawn)(process.execPath,[t,"--daemon"],{detached:!0,stdio:"ignore",env:i});if(o.pid!==void 0)return o.unref(),o.pid}function QM(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 eD(t=15e3){try{let e=(0,Lt.statSync)(Hi);return Date.now()-e.mtimeMs<t}catch{return!1}}function tD(){try{if(!(0,Lt.existsSync)(Hi))return;let t=new Date;(0,Lt.utimesSync)(Hi,t,t)}catch{}}function rD(){return LE({logAlive:!1})}var nD=Pe(require("path"),1),iD=Pe(require("net"),1),sD=require("fs");re();zt();async function KE(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 Ud(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=iD.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 oD(t,e,r,n){let i=Date.now();for(;Date.now()-i<r;){try{if((await KE(t,e)).ok)return!0}catch(s){b.debug("SYSTEM",n,{},s)}await new Promise(s=>setTimeout(s,500))}return!1}function Qo(t,e=3e4){return oD(t,"/api/health",e,"Service not ready yet, will retry")}function aD(t,e=3e4){return oD(t,"/api/readiness",e,"Worker not ready yet, will retry")}async function dg(t,e=1e4){let r=Date.now();for(;Date.now()-r<e;){if(!await Ud(t))return!0;await new Promise(n=>setTimeout(n,500))}return!1}async function pg(t){try{let e=await KE(t,"/api/admin/shutdown","POST");return e.ok?!0:(b.warn("SYSTEM","Shutdown request returned error",{status:e.statusCode}),!1)}catch(e){return e instanceof Error&&e.message?.includes("ECONNREFUSED")?(b.debug("SYSTEM","Worker already stopped",{},e),!1):(b.error("SYSTEM","Shutdown request failed unexpectedly",{},e),!1)}}function dQ(){try{let t=nD.default.join(ws,"package.json");return JSON.parse((0,sD.readFileSync)(t,"utf-8")).version}catch(t){let e=t.code;if(e==="ENOENT"||e==="EBUSY")return b.debug("SYSTEM","Could not read plugin version (shutdown race)",{code:e}),"unknown";throw t}}async function pQ(t){try{let e=await KE(t,"/api/version");return e.ok?JSON.parse(e.body).version:null}catch{return b.debug("SYSTEM","Could not fetch worker version",{}),null}}async function cD(t){let e=dQ(),r=await pQ(t);return!r||e==="unknown"?{matches:!0,pluginVersion:e,workerVersion:r}:{matches:e===r,pluginVersion:e,workerVersion:r}}re();async function uD(t){b.info("SYSTEM","Shutdown initiated"),t.server&&(await fQ(t.server),b.info("SYSTEM","HTTP server closed")),await t.sessionManager.shutdownAll(),t.mcpClient&&(await t.mcpClient.close(),b.info("SYSTEM","MCP client closed")),t.chromaMcpManager&&(b.info("SHUTDOWN","Stopping Chroma MCP connection..."),await t.chromaMcpManager.stop(),b.info("SHUTDOWN","Chroma MCP connection stopped")),t.dbManager&&await t.dbManager.close(),await zM(),b.info("SYSTEM","Worker shutdown complete")}async function fQ(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)),b.info("SYSTEM","Waited for Windows port cleanup"))}var _6=Pe(_v(),1),t$=Pe(require("fs"),1),kp=Pe(require("path"),1);var o6=["search","context","summarize","import","export"],a6=["workflow","search_params","examples","all"];re();var YT=Pe(_v(),1),f6=Pe(p6(),1),m6=Pe(require("path"),1);zt();re();function QT(t){let e=[];e.push(YT.default.json({limit:"50mb"})),e.push((0,f6.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(m=>i.path.endsWith(m)),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);b.debug("HTTP",`\u2192 ${i.method} ${i.path}`,{requestId:d},p);let f=s.send.bind(s);s.send=function(m){let h=Date.now()-l;return b.debug("HTTP",`\u2190 ${s.statusCode} ${i.path}`,{requestId:d,duration:`${h}ms`}),f(m)},o()});let r=dn(),n=m6.default.join(r,"plugin","ui");return e.push(YT.default.static(n)),e}function Ep(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")){b.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 e$(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=${b.formatTool(n,i)}`}return e.includes("/summarize")?"requesting summary":""}re();var cu=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 h6(t,e,r,n){let i={error:t,message:e};return r&&(i.code=r),n&&(i.details=n),i}var g6=(t,e,r,n)=>{let i=t instanceof cu?t.statusCode:500;b.error("HTTP",`Error handling ${e.method} ${e.path}`,{statusCode:i,error:t.message,code:t instanceof cu?t.code:void 0},t);let s=h6(t.name||"Error",t.message,t instanceof cu?t.code:void 0,t instanceof cu?t.details:void 0);r.status(i).json(s)};function v6(t,e){e.status(404).json(h6("NotFound",`Cannot ${t.method} ${t.path}`))}var y6="11.0.0",bv=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,()=>{b.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,b.info("SYSTEM","HTTP server closed"))}registerRoutes(e){e.setupRoutes(this.app)}finalizeRoutes(){this.app.use(v6),this.app.use(g6)}setupMiddleware(){QT(e$).forEach(r=>this.app.use(r))}setupCoreRoutes(){this.app.get("/api/health",(e,r)=>{r.status(200).json({status:"ok",version:y6,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:y6})}),this.app.get("/api/instructions",async(e,r)=>{let n=e.query.topic||"all",i=e.query.operation;if(n&&!a6.includes(n))return r.status(400).json({error:"Invalid topic"});try{let s;if(i){if(!o6.includes(i))return r.status(400).json({error:"Invalid operation"});let o=kp.default.resolve(__dirname,"../skills/mem-search/operations"),a=kp.default.resolve(o,`${i}.md`);if(!a.startsWith(o+kp.default.sep))return r.status(400).json({error:"Invalid request"});s=await t$.promises.readFile(a,"utf-8")}else{let o=kp.default.join(__dirname,"../skills/mem-search/SKILL.md"),a=await t$.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",Ep,async(e,r)=>{r.json({status:"restarting"}),process.platform==="win32"&&process.env.CLAUDE_MEM_MANAGED==="true"&&process.send?(b.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",Ep,async(e,r)=>{r.json({status:"shutting_down"}),process.platform==="win32"&&process.env.CLAUDE_MEM_MANAGED==="true"&&process.send?(b.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",Ep,(e,r)=>{let o=vt().getRegistry().getAll().map(m=>({id:m.id,pid:m.pid,type:m.type,status:In(m.pid)?"alive":"dead",startedAt:m.startedAt})),a=o.filter(m=>m.status==="dead").map(m=>m.pid),c=!Object.keys(process.env).some(m=>AE.has(m)||PE.some(h=>m.startsWith(h))),u=Date.now()-this.startTime,l=Math.floor(u/1e3),d=Math.floor(l/3600),p=Math.floor(l%3600/60),f=d>0?`${d}h ${p}m`:`${p}m`;r.json({supervisor:{running:!0,pid:process.pid,uptime:f},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 Rt=Pe(require("path"),1),$p=require("os"),Kt=require("fs"),x6=require("child_process"),w6=require("util");re();Dr();zt();var Kn=require("fs"),Tp=require("path");re();function b6(t){try{return(0,Kn.existsSync)(t)?JSON.parse((0,Kn.readFileSync)(t,"utf-8")):{}}catch(e){return b.error("CONFIG","Failed to read Cursor registry, using empty registry",{file:t,error:e instanceof Error?e.message:String(e)}),{}}}function S6(t,e){let r=(0,Tp.join)(t,"..");(0,Kn.mkdirSync)(r,{recursive:!0}),(0,Kn.writeFileSync)(t,JSON.stringify(e,null,2))}function r$(t,e){let r=(0,Tp.join)(t,".cursor","rules"),n=(0,Tp.join)(r,"claude-mem-context.mdc"),i=`${n}.tmp`;(0,Kn.mkdirSync)(r,{recursive:!0});let s=`---
|
|
929
929
|
alwaysApply: true
|
|
930
930
|
description: "Claude-mem context from past sessions (auto-updated)"
|
|
931
931
|
---
|
|
@@ -1245,7 +1245,11 @@ ${n.prompts.header_memory_start}`}function pu(t){let e,r;try{e=typeof t.tool_inp
|
|
|
1245
1245
|
<working_directory>${t.cwd}</working_directory>`:""}
|
|
1246
1246
|
<parameters>${JSON.stringify(e,null,2)}</parameters>
|
|
1247
1247
|
<outcome>${JSON.stringify(r,null,2)}</outcome>
|
|
1248
|
-
</observed_from_primary_session
|
|
1248
|
+
</observed_from_primary_session>
|
|
1249
|
+
|
|
1250
|
+
Return either one or more <observation>...</observation> blocks, or an empty response if this tool use should be skipped.
|
|
1251
|
+
Concrete debugging findings from logs, queue state, database rows, session routing, or code-path inspection count as durable discoveries and should be recorded.
|
|
1252
|
+
Never reply with prose such as "Skipping", "No substantive tool executions", or any explanation outside XML. Non-XML text is discarded.`}function fu(t,e){let r=t.last_assistant_message||(b.error("SDK","Missing last_assistant_message in session for summary prompt",{sessionId:t.id}),"");return`--- MODE SWITCH: PROGRESS SUMMARY ---
|
|
1249
1253
|
Do NOT output <observation> tags. This is a summary request, not an observation request.
|
|
1250
1254
|
Your response MUST use <summary> tags ONLY. Any <observation> output will be discarded.
|
|
1251
1255
|
|
|
@@ -1324,7 +1328,7 @@ ${n.prompts.format_examples}
|
|
|
1324
1328
|
|
|
1325
1329
|
${n.prompts.footer}
|
|
1326
1330
|
|
|
1327
|
-
${n.prompts.header_memory_continued}`}ir();zt();Qr();var c$=["429","500","502","503","ECONNREFUSED","ETIMEDOUT","fetch failed"];re();re();Qr();function Z6(t,e){let r=[],n=/<observation>([\s\S]*?)<\/observation>/g,i;for(;(i=n.exec(t))!==null;){let s=i[1],o=Yi(s,"type"),a=Yi(s,"title"),c=Yi(s,"subtitle"),u=Yi(s,"narrative"),l=Cv(s,"facts","fact"),d=Cv(s,"concepts","concept"),p=Cv(s,"files_read","file"),f=Cv(s,"files_modified","file"),h=He.getInstance().getActiveMode().observation_types.map(S=>S.id),g=h[0],v=g;o?h.includes(o.trim())?v=o.trim():b.error("PARSER",`Invalid observation type: ${o}, using "${g}"`,{correlationId:e}):b.error("PARSER",`Observation missing type field, using "${g}"`,{correlationId:e});let _=d.filter(S=>S!==v);_.length!==d.length&&b.
|
|
1331
|
+
${n.prompts.header_memory_continued}`}ir();zt();Qr();var c$=["429","500","502","503","ECONNREFUSED","ETIMEDOUT","fetch failed"];re();re();Qr();function Z6(t,e){let r=[],n=/<observation>([\s\S]*?)<\/observation>/g,i;for(;(i=n.exec(t))!==null;){let s=i[1],o=Yi(s,"type"),a=Yi(s,"title"),c=Yi(s,"subtitle"),u=Yi(s,"narrative"),l=Cv(s,"facts","fact"),d=Cv(s,"concepts","concept"),p=Cv(s,"files_read","file"),f=Cv(s,"files_modified","file"),h=He.getInstance().getActiveMode().observation_types.map(S=>S.id),g=h[0],v=g;o?h.includes(o.trim())?v=o.trim():b.error("PARSER",`Invalid observation type: ${o}, using "${g}"`,{correlationId:e}):b.error("PARSER",`Observation missing type field, using "${g}"`,{correlationId:e});let _=d.filter(S=>S!==v);_.length!==d.length&&b.debug("PARSER","Removed observation type from concepts array",{correlationId:e,type:v,originalConcepts:d,cleanedConcepts:_}),r.push({type:v,title:a,subtitle:c,facts:l,narrative:u,concepts:_,files_read:p,files_modified:f})}return r}function B6(t,e){let n=/<skip_summary\s+reason="([^"]+)"\s*\/>/.exec(t);if(n)return b.info("PARSER","Summary skipped",{sessionId:e,reason:n[1]}),null;let s=/<summary>([\s\S]*?)<\/summary>/.exec(t);if(!s)return/<observation>/.test(t)&&b.warn("PARSER","Summary response contained <observation> tags instead of <summary> \u2014 prompt conditioning may need strengthening",{sessionId:e}),null;let o=s[1],a=Yi(o,"request"),c=Yi(o,"investigated"),u=Yi(o,"learned"),l=Yi(o,"completed"),d=Yi(o,"next_steps"),p=Yi(o,"notes");return{request:a,investigated:c,learned:u,completed:l,next_steps:d,notes:p}}function Yi(t,e){let n=new RegExp(`<${e}>([\\s\\S]*?)</${e}>`).exec(t);if(!n)return null;let i=n[1].trim();return i===""?null:i}function Cv(t,e,r){let n=[],s=new RegExp(`<${e}>([\\s\\S]*?)</${e}>`).exec(t);if(!s)return n;let o=s[1],a=new RegExp(`<${r}>([\\s\\S]*?)</${r}>`,"g"),c;for(;(c=a.exec(o))!==null;){let u=c[1].trim();u&&n.push(u)}return n}var _i=require("fs"),Zt=Pe(require("path"),1),W6=Pe(require("os"),1);re();ya();ir();Dr();var Aue=Zt.default.join(W6.default.homedir(),".claude-mem","settings.json");function Nue(t){let e=t.split(Zt.default.sep).filter(r=>r&&r!=="."&&r!=="..");for(let r=1;r<e.length;r++)if(e[r]===e[r-1])return!0;return!1}function Mue(t,e){if(!t||!t.trim()||t.startsWith("~")||t.startsWith("http://")||t.startsWith("https://")||t.includes(" ")||t.includes("#"))return!1;if(e){let r=Zt.default.isAbsolute(t)?t:Zt.default.resolve(e,t),n=Zt.default.resolve(e);if(!r.startsWith(n+Zt.default.sep)&&r!==n||Nue(r))return!1}return!0}function l$(t,e){let r="<claude-mem-context>",n="</claude-mem-context>";if(!t)return`${r}
|
|
1328
1332
|
${e}
|
|
1329
1333
|
${n}`;let i=t.indexOf(r),s=t.indexOf(n);return i!==-1&&s!==-1?t.substring(0,i)+`${r}
|
|
1330
1334
|
${e}
|
|
@@ -1334,7 +1338,7 @@ ${r}
|
|
|
1334
1338
|
${e}
|
|
1335
1339
|
${n}`}function Due(t,e){let r=Zt.default.resolve(t);if(r.includes("/.git/")||r.includes("\\.git\\")||r.endsWith("/.git")||r.endsWith("\\.git"))return;let n=Zt.default.join(t,"CLAUDE.md"),i=`${n}.tmp`;if(!(0,_i.existsSync)(t)){b.debug("FOLDER_INDEX","Skipping non-existent folder",{folderPath:t});return}let s="";(0,_i.existsSync)(n)&&(s=(0,_i.readFileSync)(n,"utf-8"));let o=l$(s,e);(0,_i.writeFileSync)(i,o),(0,_i.renameSync)(i,n)}function jue(t){let e=[];e.push("# Recent Activity"),e.push("");let r=t.split(`
|
|
1336
1340
|
`),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,f,m]=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),_=g.getTime();if(v){let S=parseInt(v[1],10),y=parseInt(v[2],10),x=v[3].toUpperCase()==="PM";x&&S!==12&&(S+=12),!x&&S===12&&(S=0),g.setHours(S,y,0,0),_=g.getTime()}n.push({id:l.trim(),time:h,typeEmoji:p.trim(),title:f.trim(),tokens:m.trim(),epoch:_})}}if(n.length===0)return"";let o=Ps(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(`
|
|
1337
|
-
`).trim()}var zue=new Set(["res",".git","build","node_modules","__pycache__"]);function Lue(t){return Zt.default.normalize(t).split(Zt.default.sep).some(n=>zue.has(n))}function Uue(t){let e=Zt.default.join(t,".git");return(0,_i.existsSync)(e)}function Fue(t,e){let r=Zt.default.resolve(t);for(let n of e){let i=Zt.default.resolve(n);if(r===i||r.startsWith(i+Zt.default.sep))return!0}return!1}async function V6(t,e,r,n){let i=Se.loadFromFile(Aue),s=parseInt(i.CLAUDE_MEM_CONTEXT_OBSERVATIONS,10)||50,o=[];try{let u=JSON.parse(i.CLAUDE_MEM_FOLDER_MD_EXCLUDE||"[]");Array.isArray(u)&&(o=u.filter(l=>typeof l=="string"))}catch{b.warn("FOLDER_INDEX","Failed to parse CLAUDE_MEM_FOLDER_MD_EXCLUDE setting")}let a=new Set;for(let u of t){if(!u)continue;if(Zt.default.basename(u)==="CLAUDE.md"){let d=u;n&&!Zt.default.isAbsolute(u)&&(d=Zt.default.join(n,u));let p=Zt.default.dirname(d);a.add(p),b.debug("FOLDER_INDEX","Detected active CLAUDE.md, will skip folder",{folderPath:p})}}let c=new Set;for(let u of t){if(!u||u==="")continue;if(!Mue(u,n)){b.debug("FOLDER_INDEX","Skipping invalid file path",{filePath:u,reason:"Failed path validation"});continue}let l=u;n&&!Zt.default.isAbsolute(u)&&(l=Zt.default.join(n,u));let d=Zt.default.dirname(l);if(d&&d!=="."&&d!=="/"){if(Uue(d)){b.debug("FOLDER_INDEX","Skipping project root CLAUDE.md",{folderPath:d});continue}if(Lue(d)){b.debug("FOLDER_INDEX","Skipping unsafe directory for CLAUDE.md",{folderPath:d});continue}if(a.has(d)){b.debug("FOLDER_INDEX","Skipping folder with active CLAUDE.md to avoid race condition",{folderPath:d});continue}if(o.length>0&&Fue(d,o)){b.debug("FOLDER_INDEX","Skipping excluded folder",{folderPath:d});continue}c.add(d)}}if(c.size!==0){b.debug("FOLDER_INDEX","Updating CLAUDE.md files",{project:e,folderCount:c.size});for(let u of c)try{let l=await dt(`/api/search/by-file?filePath=${encodeURIComponent(u)}&limit=${s}&project=${encodeURIComponent(e)}&isFolder=true`);if(!l.ok){b.error("FOLDER_INDEX","Failed to fetch timeline",{folderPath:u,status:l.status});continue}let d=await l.json();if(!d.content?.[0]?.text){b.debug("FOLDER_INDEX","No content for folder",{folderPath:u});continue}let p=jue(d.content[0].text),f=Zt.default.join(u,"CLAUDE.md"),m=p.includes("*No recent activity*"),h=(0,_i.existsSync)(f);if(m&&!h){b.debug("FOLDER_INDEX","Skipping empty CLAUDE.md creation",{folderPath:u});continue}Due(u,p),b.debug("FOLDER_INDEX","Updated CLAUDE.md",{folderPath:u})}catch(l){let d=l;b.error("FOLDER_INDEX","Failed to update CLAUDE.md",{folderPath:u,errorMessage:d.message,errorStack:d.stack})}}}Dr();ir();zt();function d$(t,e){t?.sseBroadcaster&&t.sseBroadcaster.broadcast({type:"new_observation",observation:e})}function p$(t,e){t?.sseBroadcaster&&t.sseBroadcaster.broadcast({type:"new_summary",summary:e})}function f$(t,e){t.earliestPendingTimestamp=null,e&&typeof e.broadcastProcessingStatus=="function"&&e.broadcastProcessingStatus()}async function bi(t,e,r,n,i,s,o,a,c){e.lastGeneratorActivity=Date.now(),t&&e.conversationHistory.push({role:"assistant",content:t});let u=Z6(t,e.contentSessionId),l=B6(t,e.sessionDbId),d=que(l),p=r.getSessionStore();if(!e.memorySessionId)throw new Error("Cannot store observations: memorySessionId not yet captured");p.ensureMemorySessionIdRegistered(e.sessionDbId,e.memorySessionId),b.info("DB",`STORING | sessionDbId=${e.sessionDbId} | memorySessionId=${e.memorySessionId} | obsCount=${u.length} | hasSummary=${!!d}`,{sessionId:e.sessionDbId,memorySessionId:e.memorySessionId});let f=p.storeObservations(e.memorySessionId,e.project,u,d,e.lastPromptNumber,s,o??void 0);b.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});let m=n.getPendingMessageStore();for(let h of e.processingMessageIds)m.confirmProcessed(h);e.processingMessageIds.length>0&&b.debug("QUEUE",`CONFIRMED_BATCH | sessionDbId=${e.sessionDbId} | count=${e.processingMessageIds.length} | ids=[${e.processingMessageIds.join(",")}]`),e.processingMessageIds=[],await Hue(u,f,e,r,i,s,a,c),await Zue(l,d,f,e,r,i,s,a),f$(e,i)}function que(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 Hue(t,e,r,n,i,s,o,a){for(let d=0;d<t.length;d++){let p=e.observationIds[d],f=t[d],m=Date.now();n.getChromaSync()?.syncObservation(p,r.contentSessionId,r.project,f,r.lastPromptNumber,e.createdAtEpoch,s).then(()=>{let h=Date.now()-m;b.debug("CHROMA","Observation synced",{obsId:p,duration:`${h}ms`,type:f.type,title:f.title||"(untitled)"})}).catch(h=>{b.error("CHROMA",`${o} chroma sync failed, continuing without vector search`,{obsId:p,type:f.type,title:f.title||"(untitled)"},h)}),d$(i,{id:p,memory_session_id:r.memorySessionId,session_id:r.contentSessionId,type:f.type,title:f.title,subtitle:f.subtitle,text:null,narrative:f.narrative||null,facts:JSON.stringify(f.facts||[]),concepts:JSON.stringify(f.concepts||[]),files_read:JSON.stringify(f.files_read||[]),files_modified:JSON.stringify(f.files_modified||[]),project:r.project,prompt_number:r.lastPromptNumber,created_at_epoch:e.createdAtEpoch})}let u=Se.loadFromFile(jt).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&&V6(d,r.project,Jr(),a).catch(p=>{b.warn("FOLDER_INDEX","CLAUDE.md update failed (non-critical)",{project:r.project},p)})}}async function Zue(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;b.debug("CHROMA","Summary synced",{summaryId:r.summaryId,duration:`${u}ms`,request:e.request||"(no request)"})}).catch(u=>{b.error("CHROMA",`${a} chroma sync failed, continuing without vector search`,{summaryId:r.summaryId,request:e.request||"(no request)"},u)}),p$(s,{id:r.summaryId,session_id:n.contentSessionId,request:t.request,investigated:t.investigated,learned:t.learned,completed:t.completed,next_steps:t.next_steps,notes:t.notes,project:n.project,prompt_number:n.lastPromptNumber,created_at_epoch:r.createdAtEpoch}),T6(n.project,Jr()).catch(u=>{b.warn("CURSOR","Context update failed (non-critical)",{project:n.project},u)})}function Ap(t){let e=Bue(t);return c$.some(r=>e.includes(r))}function Bue(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 Np(t){return t==null?!1:t instanceof Error&&t.name==="AbortError"?!0:typeof t=="object"&&"name"in t?t.name==="AbortError":!1}var b$=require("path"),MF=require("url"),DF=require("events"),zF=require("child_process"),LF=require("readline"),Ie=Pe(require("fs"),1),UF=require("fs/promises"),BF=require("path"),GF=require("os"),Sa=require("path"),VF=require("process"),KF=require("fs"),JF=require("crypto"),iq=require("crypto"),Du=require("fs"),S$=require("path"),sq=require("crypto");var f_e={},Gue=Object.create,Wue=Object.getPrototypeOf,_$=Object.defineProperty,Vue=Object.getOwnPropertyNames,Kue=Object.prototype.hasOwnProperty,TF=(t,e,r)=>{r=t!=null?Gue(Wue(t)):{};let n=e||!t||!t.__esModule?_$(r,"default",{value:t,enumerable:!0}):r;for(let i of Vue(t))Kue.call(n,i)||_$(n,i,{get:()=>t[i],enumerable:!0});return n},ne=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),$F=(t,e)=>{for(var r in e)_$(t,r,{get:e[r],enumerable:!0,configurable:!0,set:n=>e[r]=()=>n})};var Lv=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(_){if(super(),!t.IDENTIFIER.test(_))throw new Error("CodeGen: name must be a valid identifier");this.str=_}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}t.Name=r;class n extends e{constructor(_){super(),this._items=typeof _=="string"?[_]:_}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let _=this._items[0];return _===""||_==='""'}get str(){var _;return(_=this._str)!==null&&_!==void 0?_:this._str=this._items.reduce((S,y)=>`${S}${y}`,"")}get names(){var _;return(_=this._names)!==null&&_!==void 0?_:this._names=this._items.reduce((S,y)=>(y instanceof r&&(S[y.str]=(S[y.str]||0)+1),S),{})}}t._Code=n,t.nil=new n("");function i(v,..._){let S=[v[0]],y=0;for(;y<_.length;)a(S,_[y]),S.push(v[++y]);return new n(S)}t._=i;var s=new n("+");function o(v,..._){let S=[f(v[0])],y=0;for(;y<_.length;)S.push(s),a(S,_[y]),S.push(s,f(v[++y]));return c(S),new n(S)}t.str=o;function a(v,_){_ instanceof n?v.push(..._._items):_ instanceof r?v.push(_):v.push(d(_))}t.addCodeArg=a;function c(v){let _=1;for(;_<v.length-1;){if(v[_]===s){let S=u(v[_-1],v[_+1]);if(S!==void 0){v.splice(_-1,3,S);continue}v[_++]="+"}_++}}function u(v,_){if(_==='""')return v;if(v==='""')return _;if(typeof v=="string")return _ instanceof r||v[v.length-1]!=='"'?void 0:typeof _!="string"?`${v.slice(0,-1)}${_}"`:_[0]==='"'?v.slice(0,-1)+_.slice(1):void 0;if(typeof _=="string"&&_[0]==='"'&&!(v instanceof r))return`"${v}${_.slice(1)}`}function l(v,_){return _.emptyStr()?v:v.emptyStr()?_:o`${v}${_}`}t.strConcat=l;function d(v){return typeof v=="number"||typeof v=="boolean"||v===null?v:f(Array.isArray(v)?v.join(","):v)}function p(v){return new n(f(v))}t.stringify=p;function f(v){return JSON.stringify(v).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}t.safeStringify=f;function m(v){return typeof v=="string"&&t.IDENTIFIER.test(v)?new n(`.${v}`):i`[${v}]`}t.getProperty=m;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}),K6=ne(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ValueScope=t.ValueScopeName=t.Scope=t.varKinds=t.UsedValueState=void 0;var e=Lv();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:f}=p,m=(d=l.key)!==null&&d!==void 0?d:l.ref,h=this._values[f];if(h){let _=h.get(m);if(_)return _}else h=this._values[f]=new Map;h.set(m,p);let g=this._scope[f]||(this._scope[f]=[]),v=g.length;return g[v]=l.ref,p.setValue(l,{property:f,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 f=e.nil;for(let m in u){let h=u[m];if(!h)continue;let g=d[m]=d[m]||new Map;h.forEach(v=>{if(g.has(v))return;g.set(v,n.Started);let _=l(v);if(_){let S=this.opts.es5?t.varKinds.var:t.varKinds.const;f=(0,e._)`${f}${S} ${v} = ${_};${this.opts._n}`}else if(_=p?.(v))f=(0,e._)`${f}${_}${this.opts._n}`;else throw new r(v);g.set(v,n.Completed)})}return f}}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=Lv(),r=K6(),n=Lv();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=K6();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(k,R){return this}}class o extends s{constructor(k,R,F){super(),this.varKind=k,this.name=R,this.rhs=F}render({es5:k,_n:R}){let F=k?r.varKinds.var:this.varKind,le=this.rhs===void 0?"":` = ${this.rhs}`;return`${F} ${this.name}${le};`+R}optimizeNames(k,R){if(k[this.name.str])return this.rhs&&(this.rhs=j(this.rhs,k,R)),this}get names(){return this.rhs instanceof e._CodeOrName?this.rhs.names:{}}}class a extends s{constructor(k,R,F){super(),this.lhs=k,this.rhs=R,this.sideEffects=F}render({_n:k}){return`${this.lhs} = ${this.rhs};`+k}optimizeNames(k,R){if(!(this.lhs instanceof e.Name&&!k[this.lhs.str]&&!this.sideEffects))return this.rhs=j(this.rhs,k,R),this}get names(){let k=this.lhs instanceof e.Name?{}:{...this.lhs.names};return V(k,this.rhs)}}class c extends a{constructor(k,R,F,le){super(k,F,le),this.op=R}render({_n:k}){return`${this.lhs} ${this.op}= ${this.rhs};`+k}}class u extends s{constructor(k){super(),this.label=k,this.names={}}render({_n:k}){return`${this.label}:`+k}}class l extends s{constructor(k){super(),this.label=k,this.names={}}render({_n:k}){return`break${this.label?` ${this.label}`:""};`+k}}class d extends s{constructor(k){super(),this.error=k}render({_n:k}){return`throw ${this.error};`+k}get names(){return this.error.names}}class p extends s{constructor(k){super(),this.code=k}render({_n:k}){return`${this.code};`+k}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(k,R){return this.code=j(this.code,k,R),this}get names(){return this.code instanceof e._CodeOrName?this.code.names:{}}}class f extends s{constructor(k=[]){super(),this.nodes=k}render(k){return this.nodes.reduce((R,F)=>R+F.render(k),"")}optimizeNodes(){let{nodes:k}=this,R=k.length;for(;R--;){let F=k[R].optimizeNodes();Array.isArray(F)?k.splice(R,1,...F):F?k[R]=F:k.splice(R,1)}return k.length>0?this:void 0}optimizeNames(k,R){let{nodes:F}=this,le=F.length;for(;le--;){let ce=F[le];ce.optimizeNames(k,R)||(ae(k,ce.names),F.splice(le,1))}return F.length>0?this:void 0}get names(){return this.nodes.reduce((k,R)=>U(k,R.names),{})}}class m extends f{render(k){return"{"+k._n+super.render(k)+"}"+k._n}}class h extends f{}class g extends m{}g.kind="else";class v extends m{constructor(k,R){super(R),this.condition=k}render(k){let R=`if(${this.condition})`+super.render(k);return this.else&&(R+="else "+this.else.render(k)),R}optimizeNodes(){super.optimizeNodes();let k=this.condition;if(k===!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 k===!1?R instanceof v?R:R.nodes:this.nodes.length?this:new v(Me(k),R instanceof v?[R]:R.nodes);if(!(k===!1||!this.nodes.length))return this}optimizeNames(k,R){var F;if(this.else=(F=this.else)===null||F===void 0?void 0:F.optimizeNames(k,R),!!(super.optimizeNames(k,R)||this.else))return this.condition=j(this.condition,k,R),this}get names(){let k=super.names;return V(k,this.condition),this.else&&U(k,this.else.names),k}}v.kind="if";class _ extends m{}_.kind="for";class S extends _{constructor(k){super(),this.iteration=k}render(k){return`for(${this.iteration})`+super.render(k)}optimizeNames(k,R){if(super.optimizeNames(k,R))return this.iteration=j(this.iteration,k,R),this}get names(){return U(super.names,this.iteration.names)}}class y extends _{constructor(k,R,F,le){super(),this.varKind=k,this.name=R,this.from=F,this.to=le}render(k){let R=k.es5?r.varKinds.var:this.varKind,{name:F,from:le,to:ce}=this;return`for(${R} ${F}=${le}; ${F}<${ce}; ${F}++)`+super.render(k)}get names(){let k=V(super.names,this.from);return V(k,this.to)}}class x extends _{constructor(k,R,F,le){super(),this.loop=k,this.varKind=R,this.name=F,this.iterable=le}render(k){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(k)}optimizeNames(k,R){if(super.optimizeNames(k,R))return this.iterable=j(this.iterable,k,R),this}get names(){return U(super.names,this.iterable.names)}}class w extends m{constructor(k,R,F){super(),this.name=k,this.args=R,this.async=F}render(k){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(k)}}w.kind="func";class E extends f{render(k){return"return "+super.render(k)}}E.kind="return";class T extends m{render(k){let R="try"+super.render(k);return this.catch&&(R+=this.catch.render(k)),this.finally&&(R+=this.finally.render(k)),R}optimizeNodes(){var k,R;return super.optimizeNodes(),(k=this.catch)===null||k===void 0||k.optimizeNodes(),(R=this.finally)===null||R===void 0||R.optimizeNodes(),this}optimizeNames(k,R){var F,le;return super.optimizeNames(k,R),(F=this.catch)===null||F===void 0||F.optimizeNames(k,R),(le=this.finally)===null||le===void 0||le.optimizeNames(k,R),this}get names(){let k=super.names;return this.catch&&U(k,this.catch.names),this.finally&&U(k,this.finally.names),k}}class I extends m{constructor(k){super(),this.error=k}render(k){return`catch(${this.error})`+super.render(k)}}I.kind="catch";class A extends m{render(k){return"finally"+super.render(k)}}A.kind="finally";class N{constructor(k,R={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...R,_n:R.lines?`
|
|
1341
|
+
`).trim()}var zue=new Set(["res",".git","build","node_modules","__pycache__"]);function Lue(t){return Zt.default.normalize(t).split(Zt.default.sep).some(n=>zue.has(n))}function Uue(t){let e=Zt.default.join(t,".git");return(0,_i.existsSync)(e)}function Fue(t,e){let r=Zt.default.resolve(t);for(let n of e){let i=Zt.default.resolve(n);if(r===i||r.startsWith(i+Zt.default.sep))return!0}return!1}async function V6(t,e,r,n){let i=Se.loadFromFile(Aue),s=parseInt(i.CLAUDE_MEM_CONTEXT_OBSERVATIONS,10)||50,o=[];try{let u=JSON.parse(i.CLAUDE_MEM_FOLDER_MD_EXCLUDE||"[]");Array.isArray(u)&&(o=u.filter(l=>typeof l=="string"))}catch{b.warn("FOLDER_INDEX","Failed to parse CLAUDE_MEM_FOLDER_MD_EXCLUDE setting")}let a=new Set;for(let u of t){if(!u)continue;if(Zt.default.basename(u)==="CLAUDE.md"){let d=u;n&&!Zt.default.isAbsolute(u)&&(d=Zt.default.join(n,u));let p=Zt.default.dirname(d);a.add(p),b.debug("FOLDER_INDEX","Detected active CLAUDE.md, will skip folder",{folderPath:p})}}let c=new Set;for(let u of t){if(!u||u==="")continue;if(!Mue(u,n)){b.debug("FOLDER_INDEX","Skipping invalid file path",{filePath:u,reason:"Failed path validation"});continue}let l=u;n&&!Zt.default.isAbsolute(u)&&(l=Zt.default.join(n,u));let d=Zt.default.dirname(l);if(d&&d!=="."&&d!=="/"){if(Uue(d)){b.debug("FOLDER_INDEX","Skipping project root CLAUDE.md",{folderPath:d});continue}if(Lue(d)){b.debug("FOLDER_INDEX","Skipping unsafe directory for CLAUDE.md",{folderPath:d});continue}if(a.has(d)){b.debug("FOLDER_INDEX","Skipping folder with active CLAUDE.md to avoid race condition",{folderPath:d});continue}if(o.length>0&&Fue(d,o)){b.debug("FOLDER_INDEX","Skipping excluded folder",{folderPath:d});continue}c.add(d)}}if(c.size!==0){b.debug("FOLDER_INDEX","Updating CLAUDE.md files",{project:e,folderCount:c.size});for(let u of c)try{let l=await dt(`/api/search/by-file?filePath=${encodeURIComponent(u)}&limit=${s}&project=${encodeURIComponent(e)}&isFolder=true`);if(!l.ok){b.error("FOLDER_INDEX","Failed to fetch timeline",{folderPath:u,status:l.status});continue}let d=await l.json();if(!d.content?.[0]?.text){b.debug("FOLDER_INDEX","No content for folder",{folderPath:u});continue}let p=jue(d.content[0].text),f=Zt.default.join(u,"CLAUDE.md"),m=p.includes("*No recent activity*"),h=(0,_i.existsSync)(f);if(m&&!h){b.debug("FOLDER_INDEX","Skipping empty CLAUDE.md creation",{folderPath:u});continue}Due(u,p),b.debug("FOLDER_INDEX","Updated CLAUDE.md",{folderPath:u})}catch(l){let d=l;b.error("FOLDER_INDEX","Failed to update CLAUDE.md",{folderPath:u,errorMessage:d.message,errorStack:d.stack})}}}Dr();ir();zt();function d$(t,e){t?.sseBroadcaster&&t.sseBroadcaster.broadcast({type:"new_observation",observation:e})}function p$(t,e){t?.sseBroadcaster&&t.sseBroadcaster.broadcast({type:"new_summary",summary:e})}function f$(t,e){t.earliestPendingTimestamp=null,e&&typeof e.broadcastProcessingStatus=="function"&&e.broadcastProcessingStatus()}async function bi(t,e,r,n,i,s,o,a,c){e.lastGeneratorActivity=Date.now(),t&&e.conversationHistory.push({role:"assistant",content:t});let u=Z6(t,e.contentSessionId),l=B6(t,e.sessionDbId);if(t.trim()&&u.length===0&&!l&&!/<observation>|<summary>|<skip_summary\b/.test(t)){let h=t.length>200?`${t.slice(0,200)}...`:t;b.warn("PARSER",`${a} returned non-XML response; observation content was discarded`,{sessionId:e.sessionDbId,preview:h})}let d=que(l),p=r.getSessionStore();if(!e.memorySessionId)throw new Error("Cannot store observations: memorySessionId not yet captured");p.ensureMemorySessionIdRegistered(e.sessionDbId,e.memorySessionId),b.info("DB",`STORING | sessionDbId=${e.sessionDbId} | memorySessionId=${e.memorySessionId} | obsCount=${u.length} | hasSummary=${!!d}`,{sessionId:e.sessionDbId,memorySessionId:e.memorySessionId});let f=p.storeObservations(e.memorySessionId,e.project,u,d,e.lastPromptNumber,s,o??void 0);b.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});let m=n.getPendingMessageStore();for(let h of e.processingMessageIds)m.confirmProcessed(h);e.processingMessageIds.length>0&&b.debug("QUEUE",`CONFIRMED_BATCH | sessionDbId=${e.sessionDbId} | count=${e.processingMessageIds.length} | ids=[${e.processingMessageIds.join(",")}]`),e.processingMessageIds=[],await Hue(u,f,e,r,i,s,a,c),await Zue(l,d,f,e,r,i,s,a),f$(e,i)}function que(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 Hue(t,e,r,n,i,s,o,a){for(let d=0;d<t.length;d++){let p=e.observationIds[d],f=t[d],m=Date.now();n.getChromaSync()?.syncObservation(p,r.contentSessionId,r.project,f,r.lastPromptNumber,e.createdAtEpoch,s).then(()=>{let h=Date.now()-m;b.debug("CHROMA","Observation synced",{obsId:p,duration:`${h}ms`,type:f.type,title:f.title||"(untitled)"})}).catch(h=>{b.error("CHROMA",`${o} chroma sync failed, continuing without vector search`,{obsId:p,type:f.type,title:f.title||"(untitled)"},h)}),d$(i,{id:p,memory_session_id:r.memorySessionId,session_id:r.contentSessionId,type:f.type,title:f.title,subtitle:f.subtitle,text:null,narrative:f.narrative||null,facts:JSON.stringify(f.facts||[]),concepts:JSON.stringify(f.concepts||[]),files_read:JSON.stringify(f.files_read||[]),files_modified:JSON.stringify(f.files_modified||[]),project:r.project,prompt_number:r.lastPromptNumber,created_at_epoch:e.createdAtEpoch})}let u=Se.loadFromFile(jt).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&&V6(d,r.project,Jr(),a).catch(p=>{b.warn("FOLDER_INDEX","CLAUDE.md update failed (non-critical)",{project:r.project},p)})}}async function Zue(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;b.debug("CHROMA","Summary synced",{summaryId:r.summaryId,duration:`${u}ms`,request:e.request||"(no request)"})}).catch(u=>{b.error("CHROMA",`${a} chroma sync failed, continuing without vector search`,{summaryId:r.summaryId,request:e.request||"(no request)"},u)}),p$(s,{id:r.summaryId,session_id:n.contentSessionId,request:t.request,investigated:t.investigated,learned:t.learned,completed:t.completed,next_steps:t.next_steps,notes:t.notes,project:n.project,prompt_number:n.lastPromptNumber,created_at_epoch:r.createdAtEpoch}),T6(n.project,Jr()).catch(u=>{b.warn("CURSOR","Context update failed (non-critical)",{project:n.project},u)})}function Ap(t){let e=Bue(t);return c$.some(r=>e.includes(r))}function Bue(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 Np(t){return t==null?!1:t instanceof Error&&t.name==="AbortError"?!0:typeof t=="object"&&"name"in t?t.name==="AbortError":!1}var b$=require("path"),MF=require("url"),DF=require("events"),zF=require("child_process"),LF=require("readline"),Ie=Pe(require("fs"),1),UF=require("fs/promises"),BF=require("path"),GF=require("os"),Sa=require("path"),VF=require("process"),KF=require("fs"),JF=require("crypto"),iq=require("crypto"),Du=require("fs"),S$=require("path"),sq=require("crypto");var f_e={},Gue=Object.create,Wue=Object.getPrototypeOf,_$=Object.defineProperty,Vue=Object.getOwnPropertyNames,Kue=Object.prototype.hasOwnProperty,TF=(t,e,r)=>{r=t!=null?Gue(Wue(t)):{};let n=e||!t||!t.__esModule?_$(r,"default",{value:t,enumerable:!0}):r;for(let i of Vue(t))Kue.call(n,i)||_$(n,i,{get:()=>t[i],enumerable:!0});return n},ne=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),$F=(t,e)=>{for(var r in e)_$(t,r,{get:e[r],enumerable:!0,configurable:!0,set:n=>e[r]=()=>n})};var Lv=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(_){if(super(),!t.IDENTIFIER.test(_))throw new Error("CodeGen: name must be a valid identifier");this.str=_}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}t.Name=r;class n extends e{constructor(_){super(),this._items=typeof _=="string"?[_]:_}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let _=this._items[0];return _===""||_==='""'}get str(){var _;return(_=this._str)!==null&&_!==void 0?_:this._str=this._items.reduce((S,y)=>`${S}${y}`,"")}get names(){var _;return(_=this._names)!==null&&_!==void 0?_:this._names=this._items.reduce((S,y)=>(y instanceof r&&(S[y.str]=(S[y.str]||0)+1),S),{})}}t._Code=n,t.nil=new n("");function i(v,..._){let S=[v[0]],y=0;for(;y<_.length;)a(S,_[y]),S.push(v[++y]);return new n(S)}t._=i;var s=new n("+");function o(v,..._){let S=[f(v[0])],y=0;for(;y<_.length;)S.push(s),a(S,_[y]),S.push(s,f(v[++y]));return c(S),new n(S)}t.str=o;function a(v,_){_ instanceof n?v.push(..._._items):_ instanceof r?v.push(_):v.push(d(_))}t.addCodeArg=a;function c(v){let _=1;for(;_<v.length-1;){if(v[_]===s){let S=u(v[_-1],v[_+1]);if(S!==void 0){v.splice(_-1,3,S);continue}v[_++]="+"}_++}}function u(v,_){if(_==='""')return v;if(v==='""')return _;if(typeof v=="string")return _ instanceof r||v[v.length-1]!=='"'?void 0:typeof _!="string"?`${v.slice(0,-1)}${_}"`:_[0]==='"'?v.slice(0,-1)+_.slice(1):void 0;if(typeof _=="string"&&_[0]==='"'&&!(v instanceof r))return`"${v}${_.slice(1)}`}function l(v,_){return _.emptyStr()?v:v.emptyStr()?_:o`${v}${_}`}t.strConcat=l;function d(v){return typeof v=="number"||typeof v=="boolean"||v===null?v:f(Array.isArray(v)?v.join(","):v)}function p(v){return new n(f(v))}t.stringify=p;function f(v){return JSON.stringify(v).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}t.safeStringify=f;function m(v){return typeof v=="string"&&t.IDENTIFIER.test(v)?new n(`.${v}`):i`[${v}]`}t.getProperty=m;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}),K6=ne(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ValueScope=t.ValueScopeName=t.Scope=t.varKinds=t.UsedValueState=void 0;var e=Lv();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:f}=p,m=(d=l.key)!==null&&d!==void 0?d:l.ref,h=this._values[f];if(h){let _=h.get(m);if(_)return _}else h=this._values[f]=new Map;h.set(m,p);let g=this._scope[f]||(this._scope[f]=[]),v=g.length;return g[v]=l.ref,p.setValue(l,{property:f,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 f=e.nil;for(let m in u){let h=u[m];if(!h)continue;let g=d[m]=d[m]||new Map;h.forEach(v=>{if(g.has(v))return;g.set(v,n.Started);let _=l(v);if(_){let S=this.opts.es5?t.varKinds.var:t.varKinds.const;f=(0,e._)`${f}${S} ${v} = ${_};${this.opts._n}`}else if(_=p?.(v))f=(0,e._)`${f}${_}${this.opts._n}`;else throw new r(v);g.set(v,n.Completed)})}return f}}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=Lv(),r=K6(),n=Lv();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=K6();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(k,R){return this}}class o extends s{constructor(k,R,F){super(),this.varKind=k,this.name=R,this.rhs=F}render({es5:k,_n:R}){let F=k?r.varKinds.var:this.varKind,le=this.rhs===void 0?"":` = ${this.rhs}`;return`${F} ${this.name}${le};`+R}optimizeNames(k,R){if(k[this.name.str])return this.rhs&&(this.rhs=j(this.rhs,k,R)),this}get names(){return this.rhs instanceof e._CodeOrName?this.rhs.names:{}}}class a extends s{constructor(k,R,F){super(),this.lhs=k,this.rhs=R,this.sideEffects=F}render({_n:k}){return`${this.lhs} = ${this.rhs};`+k}optimizeNames(k,R){if(!(this.lhs instanceof e.Name&&!k[this.lhs.str]&&!this.sideEffects))return this.rhs=j(this.rhs,k,R),this}get names(){let k=this.lhs instanceof e.Name?{}:{...this.lhs.names};return V(k,this.rhs)}}class c extends a{constructor(k,R,F,le){super(k,F,le),this.op=R}render({_n:k}){return`${this.lhs} ${this.op}= ${this.rhs};`+k}}class u extends s{constructor(k){super(),this.label=k,this.names={}}render({_n:k}){return`${this.label}:`+k}}class l extends s{constructor(k){super(),this.label=k,this.names={}}render({_n:k}){return`break${this.label?` ${this.label}`:""};`+k}}class d extends s{constructor(k){super(),this.error=k}render({_n:k}){return`throw ${this.error};`+k}get names(){return this.error.names}}class p extends s{constructor(k){super(),this.code=k}render({_n:k}){return`${this.code};`+k}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(k,R){return this.code=j(this.code,k,R),this}get names(){return this.code instanceof e._CodeOrName?this.code.names:{}}}class f extends s{constructor(k=[]){super(),this.nodes=k}render(k){return this.nodes.reduce((R,F)=>R+F.render(k),"")}optimizeNodes(){let{nodes:k}=this,R=k.length;for(;R--;){let F=k[R].optimizeNodes();Array.isArray(F)?k.splice(R,1,...F):F?k[R]=F:k.splice(R,1)}return k.length>0?this:void 0}optimizeNames(k,R){let{nodes:F}=this,le=F.length;for(;le--;){let ce=F[le];ce.optimizeNames(k,R)||(ae(k,ce.names),F.splice(le,1))}return F.length>0?this:void 0}get names(){return this.nodes.reduce((k,R)=>U(k,R.names),{})}}class m extends f{render(k){return"{"+k._n+super.render(k)+"}"+k._n}}class h extends f{}class g extends m{}g.kind="else";class v extends m{constructor(k,R){super(R),this.condition=k}render(k){let R=`if(${this.condition})`+super.render(k);return this.else&&(R+="else "+this.else.render(k)),R}optimizeNodes(){super.optimizeNodes();let k=this.condition;if(k===!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 k===!1?R instanceof v?R:R.nodes:this.nodes.length?this:new v(Me(k),R instanceof v?[R]:R.nodes);if(!(k===!1||!this.nodes.length))return this}optimizeNames(k,R){var F;if(this.else=(F=this.else)===null||F===void 0?void 0:F.optimizeNames(k,R),!!(super.optimizeNames(k,R)||this.else))return this.condition=j(this.condition,k,R),this}get names(){let k=super.names;return V(k,this.condition),this.else&&U(k,this.else.names),k}}v.kind="if";class _ extends m{}_.kind="for";class S extends _{constructor(k){super(),this.iteration=k}render(k){return`for(${this.iteration})`+super.render(k)}optimizeNames(k,R){if(super.optimizeNames(k,R))return this.iteration=j(this.iteration,k,R),this}get names(){return U(super.names,this.iteration.names)}}class y extends _{constructor(k,R,F,le){super(),this.varKind=k,this.name=R,this.from=F,this.to=le}render(k){let R=k.es5?r.varKinds.var:this.varKind,{name:F,from:le,to:ce}=this;return`for(${R} ${F}=${le}; ${F}<${ce}; ${F}++)`+super.render(k)}get names(){let k=V(super.names,this.from);return V(k,this.to)}}class x extends _{constructor(k,R,F,le){super(),this.loop=k,this.varKind=R,this.name=F,this.iterable=le}render(k){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(k)}optimizeNames(k,R){if(super.optimizeNames(k,R))return this.iterable=j(this.iterable,k,R),this}get names(){return U(super.names,this.iterable.names)}}class w extends m{constructor(k,R,F){super(),this.name=k,this.args=R,this.async=F}render(k){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(k)}}w.kind="func";class E extends f{render(k){return"return "+super.render(k)}}E.kind="return";class T extends m{render(k){let R="try"+super.render(k);return this.catch&&(R+=this.catch.render(k)),this.finally&&(R+=this.finally.render(k)),R}optimizeNodes(){var k,R;return super.optimizeNodes(),(k=this.catch)===null||k===void 0||k.optimizeNodes(),(R=this.finally)===null||R===void 0||R.optimizeNodes(),this}optimizeNames(k,R){var F,le;return super.optimizeNames(k,R),(F=this.catch)===null||F===void 0||F.optimizeNames(k,R),(le=this.finally)===null||le===void 0||le.optimizeNames(k,R),this}get names(){let k=super.names;return this.catch&&U(k,this.catch.names),this.finally&&U(k,this.finally.names),k}}class I extends m{constructor(k){super(),this.error=k}render(k){return`catch(${this.error})`+super.render(k)}}I.kind="catch";class A extends m{render(k){return"finally"+super.render(k)}}A.kind="finally";class N{constructor(k,R={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...R,_n:R.lines?`
|
|
1338
1342
|
`:""},this._extScope=k,this._scope=new r.Scope({parent:k}),this._nodes=[new h]}toString(){return this._root.render(this.opts)}name(k){return this._scope.name(k)}scopeName(k){return this._extScope.name(k)}scopeValue(k,R){let F=this._extScope.value(k,R);return(this._values[F.prefix]||(this._values[F.prefix]=new Set)).add(F),F}getScopeValue(k,R){return this._extScope.getValue(k,R)}scopeRefs(k){return this._extScope.scopeRefs(k,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(k,R,F,le){let ce=this._scope.toName(R);return F!==void 0&&le&&(this._constants[ce.str]=F),this._leafNode(new o(k,ce,F)),ce}const(k,R,F){return this._def(r.varKinds.const,k,R,F)}let(k,R,F){return this._def(r.varKinds.let,k,R,F)}var(k,R,F){return this._def(r.varKinds.var,k,R,F)}assign(k,R,F){return this._leafNode(new a(k,R,F))}add(k,R){return this._leafNode(new c(k,t.operators.ADD,R))}code(k){return typeof k=="function"?k():k!==e.nil&&this._leafNode(new p(k)),this}object(...k){let R=["{"];for(let[F,le]of k)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(k,R,F){if(this._blockNode(new v(k)),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(k){return this._elseNode(new v(k))}else(){return this._elseNode(new g)}endIf(){return this._endBlockNode(v,g)}_for(k,R){return this._blockNode(k),R&&this.code(R).endFor(),this}for(k,R){return this._for(new S(k),R)}forRange(k,R,F,le,ce=this.opts.es5?r.varKinds.var:r.varKinds.let){let Qe=this._scope.toName(k);return this._for(new y(ce,Qe,R,F),()=>le(Qe))}forOf(k,R,F,le=r.varKinds.const){let ce=this._scope.toName(k);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(k,R,F,le=this.opts.es5?r.varKinds.var:r.varKinds.const){if(this.opts.ownProperties)return this.forOf(k,(0,e._)`Object.keys(${R})`,F);let ce=this._scope.toName(k);return this._for(new x("in",le,ce,R),()=>F(ce))}endFor(){return this._endBlockNode(_)}label(k){return this._leafNode(new u(k))}break(k){return this._leafNode(new l(k))}return(k){let R=new E;if(this._blockNode(R),this.code(k),R.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(E)}try(k,R,F){if(!R&&!F)throw new Error('CodeGen: "try" without "catch" and "finally"');let le=new T;if(this._blockNode(le),this.code(k),R){let ce=this.name("e");this._currNode=le.catch=new I(ce),R(ce)}return F&&(this._currNode=le.finally=new A,this.code(F)),this._endBlockNode(I,A)}throw(k){return this._leafNode(new d(k))}block(k,R){return this._blockStarts.push(this._nodes.length),k&&this.code(k).endBlock(R),this}endBlock(k){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||k!==void 0&&F!==k)throw new Error(`CodeGen: wrong number of nodes: ${F} vs ${k} expected`);return this._nodes.length=R,this}func(k,R=e.nil,F,le){return this._blockNode(new w(k,R,F)),le&&this.code(le).endFunc(),this}endFunc(){return this._endBlockNode(w)}optimize(k=1){for(;k-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(k){return this._currNode.nodes.push(k),this}_blockNode(k){this._currNode.nodes.push(k),this._nodes.push(k)}_endBlockNode(k,R){let F=this._currNode;if(F instanceof k||R&&F instanceof R)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${R?`${k.kind}/${R.kind}`:k.kind}"`)}_elseNode(k){let R=this._currNode;if(!(R instanceof v))throw new Error('CodeGen: "else" without "if"');return this._currNode=R.else=k,this}get _root(){return this._nodes[0]}get _currNode(){let k=this._nodes;return k[k.length-1]}set _currNode(k){let R=this._nodes;R[R.length-1]=k}}t.CodeGen=N;function U(M,k){for(let R in k)M[R]=(M[R]||0)+(k[R]||0);return M}function V(M,k){return k instanceof e._CodeOrName?U(M,k.names):M}function j(M,k,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||k[ce.str]!==1?ce:(delete k[ce.str],Qe)}function le(ce){return ce instanceof e._Code&&ce._items.some(Qe=>Qe instanceof e.Name&&k[Qe.str]===1&&R[Qe.str]!==void 0)}}function ae(M,k){for(let R in k)M[R]=(M[R]||0)-(k[R]||0)}function Me(M){return typeof M=="boolean"||typeof M=="number"||M===null?!M:(0,e._)`!${H(M)}`}t.not=Me;var Le=C(t.operators.AND);function kt(...M){return M.reduce(Le)}t.and=kt;var Ge=C(t.operators.OR);function K(...M){return M.reduce(Ge)}t.or=K;function C(M){return(k,R)=>k===e.nil?R:R===e.nil?k:(0,e._)`${H(k)} ${M} ${H(R)}`}function H(M){return M instanceof e.Name?M:(0,e._)`(${M})`}}),ct=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=Lv();function n(w){let E={};for(let T of w)E[T]=!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:T,self:I}=w;if(!T.strictSchema||typeof E=="boolean")return;let A=I.RULES.keywords;for(let N in E)A[N]||x(w,`unknown keyword: "${N}"`)}t.checkUnknownRules=s;function o(w,E){if(typeof w=="boolean")return!w;for(let T in w)if(E[T])return!0;return!1}t.schemaHasRules=o;function a(w,E){if(typeof w=="boolean")return!w;for(let T in w)if(T!=="$ref"&&E.all[T])return!0;return!1}t.schemaHasRulesButRef=a;function c({topSchemaRef:w,schemaPath:E},T,I,A){if(!A){if(typeof T=="number"||typeof T=="boolean")return T;if(typeof T=="string")return(0,e._)`${T}`}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 f(w,E){if(Array.isArray(w))for(let T of w)E(T);else E(w)}t.eachItem=f;function m({mergeNames:w,mergeToName:E,mergeValues:T,resultToName:I}){return(A,N,U,V)=>{let j=U===void 0?N:U instanceof e.Name?(N instanceof e.Name?w(A,N,U):E(A,N,U),U):N instanceof e.Name?(E(A,U,N),N):T(N,U);return V===e.Name&&!(j instanceof e.Name)?I(A,j):j}}t.mergeEvaluated={props:m({mergeNames:(w,E,T)=>w.if((0,e._)`${T} !== true && ${E} !== undefined`,()=>{w.if((0,e._)`${E} === true`,()=>w.assign(T,!0),()=>w.assign(T,(0,e._)`${T} || {}`).code((0,e._)`Object.assign(${T}, ${E})`))}),mergeToName:(w,E,T)=>w.if((0,e._)`${T} !== true`,()=>{E===!0?w.assign(T,!0):(w.assign(T,(0,e._)`${T} || {}`),g(w,T,E))}),mergeValues:(w,E)=>w===!0?!0:{...w,...E},resultToName:h}),items:m({mergeNames:(w,E,T)=>w.if((0,e._)`${T} !== true && ${E} !== undefined`,()=>w.assign(T,(0,e._)`${E} === true ? true : ${T} > ${E} ? ${T} : ${E}`)),mergeToName:(w,E,T)=>w.if((0,e._)`${T} !== true`,()=>w.assign(T,E===!0?!0:(0,e._)`${T} > ${E} ? ${T} : ${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 T=w.var("props",(0,e._)`{}`);return E!==void 0&&g(w,T,E),T}t.evaluatedPropsToName=h;function g(w,E,T){Object.keys(T).forEach(I=>w.assign((0,e._)`${E}${(0,e.getProperty)(I)}`,!0))}t.setEvaluated=g;var v={};function _(w,E){return w.scopeValue("func",{ref:E,code:v[E.code]||(v[E.code]=new r._Code(E.code))})}t.useFunc=_;var S;(function(w){w[w.Num=0]="Num",w[w.Str=1]="Str"})(S||(t.Type=S={}));function y(w,E,T){if(w instanceof e.Name){let I=E===S.Num;return T?I?(0,e._)`"[" + ${w} + "]"`:(0,e._)`"['" + ${w} + "']"`:I?(0,e._)`"/" + ${w}`:(0,e._)`"/" + ${w}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return T?(0,e.getProperty)(w).toString():"/"+d(w)}t.getErrorPath=y;function x(w,E,T=w.opts.strictSchema){if(T){if(E=`strict mode: ${E}`,T===!0)throw new Error(E);w.self.logger.warn(E)}}t.checkStrictMode=x}),wo=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}),Wv=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=ct(),n=wo();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,_,S){let{it:y}=g,{gen:x,compositeRule:w,allErrors:E}=y,T=d(g,v,_);S??(w||E)?c(x,T):u(y,(0,e._)`[${T}]`)}t.reportError=i;function s(g,v=t.keywordError,_){let{it:S}=g,{gen:y,compositeRule:x,allErrors:w}=S,E=d(g,v,_);c(y,E),x||w||u(S,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:_,data:S,errsCount:y,it:x}){if(y===void 0)throw new Error("ajv implementation error");let w=g.name("err");g.forRange("i",y,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`,_),g.assign((0,e._)`${w}.data`,S))})}t.extendErrors=a;function c(g,v){let _=g.const("err",v);g.if((0,e._)`${n.default.vErrors} === null`,()=>g.assign(n.default.vErrors,(0,e._)`[${_}]`),(0,e._)`${n.default.vErrors}.push(${_})`),g.code((0,e._)`${n.default.errors}++`)}function u(g,v){let{gen:_,validateName:S,schemaEnv:y}=g;y.$async?_.throw((0,e._)`new ${g.ValidationError}(${v})`):(_.assign((0,e._)`${S}.errors`,v),_.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,_){let{createErrors:S}=g.it;return S===!1?(0,e._)`{}`:p(g,v,_)}function p(g,v,_={}){let{gen:S,it:y}=g,x=[f(y,_),m(g,_)];return h(g,v,x),S.object(...x)}function f({errorPath:g},{instancePath:v}){let _=v?(0,e.str)`${g}${(0,r.getErrorPath)(v,r.Type.Str)}`:g;return[n.default.instancePath,(0,e.strConcat)(n.default.instancePath,_)]}function m({keyword:g,it:{errSchemaPath:v}},{schemaPath:_,parentSchema:S}){let y=S?v:(0,e.str)`${v}/${g}`;return _&&(y=(0,e.str)`${y}${(0,r.getErrorPath)(_,r.Type.Str)}`),[l.schemaPath,y]}function h(g,{params:v,message:_},S){let{keyword:y,data:x,schemaValue:w,it:E}=g,{opts:T,propertyName:I,topSchemaRef:A,schemaPath:N}=E;S.push([l.keyword,y],[l.params,typeof v=="function"?v(g):v||(0,e._)`{}`]),T.messages&&S.push([l.message,typeof _=="function"?_(g):_]),T.verbose&&S.push([l.schema,w],[l.parentSchema,(0,e._)`${A}${N}`],[n.default.data,x]),I&&S.push([l.propertyName,I])}}),Jue=ne(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.boolOrEmptySchema=t.topBoolOrEmptySchema=void 0;var e=Wv(),r=Ze(),n=wo(),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)}}),IF=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}),RF=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}),Uv=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=IF(),r=RF(),n=Wv(),i=Ze(),s=ct(),o;(function(S){S[S.Correct=0]="Correct",S[S.Wrong=1]="Wrong"})(o||(t.DataType=o={}));function a(S){let y=c(S.type);if(y.includes("null")){if(S.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!y.length&&S.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');S.nullable===!0&&y.push("null")}return y}t.getSchemaTypes=a;function c(S){let y=Array.isArray(S)?S:S?[S]:[];if(y.every(e.isJSONType))return y;throw new Error("type must be JSONType or JSONType[]: "+y.join(","))}t.getJSONTypes=c;function u(S,y){let{gen:x,data:w,opts:E}=S,T=d(y,E.coerceTypes),I=y.length>0&&!(T.length===0&&y.length===1&&(0,r.schemaHasRulesForType)(S,y[0]));if(I){let A=h(y,w,E.strictNumbers,o.Wrong);x.if(A,()=>{T.length?p(S,y,T):v(S)})}return I}t.coerceAndCheckDataType=u;var l=new Set(["string","number","integer","boolean","null"]);function d(S,y){return y?S.filter(x=>l.has(x)||y==="array"&&x==="array"):[]}function p(S,y,x){let{gen:w,data:E,opts:T}=S,I=w.let("dataType",(0,i._)`typeof ${E}`),A=w.let("coerced",(0,i._)`undefined`);T.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(y,E,T.strictNumbers),()=>w.assign(A,E))),w.if((0,i._)`${A} !== undefined`);for(let U of x)(l.has(U)||U==="array"&&T.coerceTypes==="array")&&N(U);w.else(),v(S),w.endIf(),w.if((0,i._)`${A} !== undefined`,()=>{w.assign(E,A),f(S,A)});function N(U){switch(U){case"string":w.elseIf((0,i._)`${I} == "number" || ${I} == "boolean"`).assign(A,(0,i._)`"" + ${E}`).elseIf((0,i._)`${E} === null`).assign(A,(0,i._)`""`);return;case"number":w.elseIf((0,i._)`${I} == "boolean" || ${E} === null
|
|
1339
1343
|
|| (${I} == "string" && ${E} && ${E} == +${E})`).assign(A,(0,i._)`+${E}`);return;case"integer":w.elseIf((0,i._)`${I} === "boolean" || ${E} === null
|
|
1340
1344
|
|| (${I} === "string" && ${E} && ${E} == +${E} && !(${E} % 1))`).assign(A,(0,i._)`+${E}`);return;case"boolean":w.elseIf((0,i._)`${E} === "false" || ${E} === 0 || ${E} === null`).assign(A,!1).elseIf((0,i._)`${E} === "true" || ${E} === 1`).assign(A,!0);return;case"null":w.elseIf((0,i._)`${E} === "" || ${E} === 0 || ${E} === false`),w.assign(A,null);return;case"array":w.elseIf((0,i._)`${I} === "string" || ${I} === "number"
|
|
@@ -1497,7 +1501,7 @@ Tips:
|
|
|
1497
1501
|
|
|
1498
1502
|
${e}`,o=l$(i,s),a=`${t}.tmp`;try{(0,Ri.writeFileSync)(a,o),(0,Ri.renameSync)(a,t)}catch(c){b.error("AGENTS_MD","Failed to write AGENTS.md",{agentsPath:t},c)}}function gSe(t){let e=t.trim().replace(/^\$\.?/,"");if(!e)return[];let r=[],n=e.split(".");for(let i of n){let s=/([^[\]]+)|\[(\d+)\]/g,o;for(;(o=s.exec(i))!==null;)o[1]?r.push(o[1]):o[2]&&r.push(parseInt(o[2],10))}return r}function BI(t,e){if(!e)return;let r=gSe(e),n=t;for(let i of r){if(n==null)return;n=n[i]}return n}function M5(t){return t==null||t===""}function D5(t,e){if(t.startsWith("$watch.")){let r=t.slice(7);return e.watch[r]}if(t.startsWith("$schema.")){let r=t.slice(8);return e.schema[r]}if(t.startsWith("$session.")){let r=t.slice(9);return e.session?e.session[r]:void 0}if(t==="$cwd")return e.watch.workspace;if(t==="$project")return e.watch.project}function Qu(t,e,r){if(t!==void 0){if(typeof t=="string"){let n=D5(t,r);return n!==void 0?n:BI(e,t)}if(t.coalesce&&Array.isArray(t.coalesce))for(let n of t.coalesce){let i=Qu(n,e,r);if(!M5(i))return i}if(t.path){let n=D5(t.path,r);if(n!==void 0)return n;let i=BI(e,t.path);if(!M5(i))return i}if(t.value!==void 0)return t.value;if(t.default!==void 0)return t.default}}function j5(t,e,r){let n={};if(!t)return n;for(let[i,s]of Object.entries(t))n[i]=Qu(s,e,r);return n}function z5(t,e,r){if(!e)return!0;let n=e.path||r.eventTypePath||"type",i=n?BI(t,n):void 0;if(e.exists&&(i==null||i===""))return!1;if(e.equals!==void 0)return i===e.equals;if(e.in&&Array.isArray(e.in))return e.in.includes(i);if(e.contains!==void 0)return typeof i=="string"&&i.includes(e.contains);if(e.regex)try{return new RegExp(e.regex).test(String(i??""))}catch{return!1}return!0}var p_=class{sessions=new Map;async processEntry(e,r,n,i){for(let s of n.events)z5(e,s.match,n)&&await this.handleEvent(e,r,n,s,i??void 0)}getSessionKey(e,r){return`${e.name}:${r}`}getOrCreateSession(e,r){let n=this.getSessionKey(e,r),i=this.sessions.get(n);return i||(i={sessionId:r,pendingTools:new Map},this.sessions.set(n,i)),i}resolveSessionId(e,r,n,i,s){let o={watch:r,schema:n},a=i.fields?.sessionId??(n.sessionIdPath?{path:n.sessionIdPath}:void 0),c=Qu(a,e,o);return typeof c=="string"&&c.trim()?c:typeof c=="number"?String(c):s&&s.trim()?s:null}resolveCwd(e,r,n,i,s){let o={watch:r,schema:n,session:s},a=i.fields?.cwd??(n.cwdPath?{path:n.cwdPath}:void 0),c=Qu(a,e,o);return typeof c=="string"&&c.trim()?c:r.workspace?r.workspace:s.cwd}resolveProject(e,r,n,i,s){let o={watch:r,schema:n,session:s},a=i.fields?.project??(n.projectPath?{path:n.projectPath}:void 0),c=Qu(a,e,o);return typeof c=="string"&&c.trim()?c:r.project?r.project:s.cwd?Ia(s.cwd):s.project}async handleEvent(e,r,n,i,s){let o=this.resolveSessionId(e,r,n,i,s);if(!o){b.debug("TRANSCRIPT","Skipping event without sessionId",{event:i.name,watch:r.name});return}let a=this.getOrCreateSession(r,o),c=this.resolveCwd(e,r,n,i,a);c&&(a.cwd=c);let u=this.resolveProject(e,r,n,i,a);u&&(a.project=u);let l=j5(i.fields,e,{watch:r,schema:n,session:a});switch(i.action){case"session_context":this.applySessionContext(a,l);break;case"session_init":await this.handleSessionInit(a,l),r.context?.updateOn?.includes("session_start")&&await this.updateContext(a,r);break;case"user_message":typeof l.message=="string"&&(a.lastUserMessage=l.message),typeof l.prompt=="string"&&(a.lastUserMessage=l.prompt);break;case"assistant_message":typeof l.message=="string"&&(a.lastAssistantMessage=l.message);break;case"tool_use":await this.handleToolUse(a,l);break;case"tool_result":await this.handleToolResult(a,l);break;case"observation":await this.sendObservation(a,l);break;case"file_edit":await this.sendFileEdit(a,l);break;case"session_end":await this.handleSessionEnd(a,r);break;default:break}}applySessionContext(e,r){let n=typeof r.cwd=="string"?r.cwd:void 0,i=typeof r.project=="string"?r.project:void 0;n&&(e.cwd=n),i&&(e.project=i)}async handleSessionInit(e,r){let n=typeof r.prompt=="string"?r.prompt:"",i=e.cwd??process.cwd();n&&(e.lastUserMessage=n),await jf.execute({sessionId:e.sessionId,cwd:i,prompt:n,platform:"transcript"})}async handleToolUse(e,r){let n=typeof r.toolId=="string"?r.toolId:void 0,i=typeof r.toolName=="string"?r.toolName:void 0,s=this.maybeParseJson(r.toolInput),o=this.maybeParseJson(r.toolResponse),a={id:n,name:i,input:s,response:o};if(n&&e.pendingTools.set(n,{name:a.name,input:a.input}),i==="apply_patch"&&typeof s=="string"){let c=this.parseApplyPatchFiles(s);for(let u of c)await this.sendFileEdit(e,{filePath:u,edits:[{type:"apply_patch",patch:s}]})}o!==void 0&&i&&await this.sendObservation(e,{toolName:i,toolInput:s,toolResponse:o})}async handleToolResult(e,r){let n=typeof r.toolId=="string"?r.toolId:void 0,i=typeof r.toolName=="string"?r.toolName:void 0,s=this.maybeParseJson(r.toolResponse),o=this.maybeParseJson(r.toolInput),a=i;if(n&&e.pendingTools.has(n)){let c=e.pendingTools.get(n);o=c.input??o,a=a??c.name,e.pendingTools.delete(n)}a&&await this.sendObservation(e,{toolName:a,toolInput:o,toolResponse:s})}async sendObservation(e,r){let n=typeof r.toolName=="string"?r.toolName:void 0;n&&await zf.execute({sessionId:e.sessionId,cwd:e.cwd??process.cwd(),toolName:n,toolInput:this.maybeParseJson(r.toolInput),toolResponse:this.maybeParseJson(r.toolResponse),platform:"transcript"})}async sendFileEdit(e,r){let n=typeof r.filePath=="string"?r.filePath:void 0;n&&await Lf.execute({sessionId:e.sessionId,cwd:e.cwd??process.cwd(),filePath:n,edits:Array.isArray(r.edits)?r.edits:void 0,platform:"transcript"})}maybeParseJson(e){if(typeof e!="string")return e;let r=e.trim();if(!r||!(r.startsWith("{")||r.startsWith("[")))return e;try{return JSON.parse(r)}catch{return e}}parseApplyPatchFiles(e){let r=[],n=e.split(`
|
|
1499
1503
|
`);for(let i of n){let s=i.trim();if(s.startsWith("*** Update File: "))r.push(s.replace("*** Update File: ","").trim());else if(s.startsWith("*** Add File: "))r.push(s.replace("*** Add File: ","").trim());else if(s.startsWith("*** Delete File: "))r.push(s.replace("*** Delete File: ","").trim());else if(s.startsWith("*** Move to: "))r.push(s.replace("*** Move to: ","").trim());else if(s.startsWith("+++ ")){let o=s.replace("+++ ","").replace(/^b\//,"").trim();o&&o!=="/dev/null"&&r.push(o)}}return Array.from(new Set(r))}async handleSessionEnd(e,r){await this.queueSummary(e),await Uf.execute({sessionId:e.sessionId,cwd:e.cwd??process.cwd(),platform:"transcript"}),await this.updateContext(e,r),e.pendingTools.clear();let n=this.getSessionKey(r,e.sessionId);this.sessions.delete(n)}async queueSummary(e){if(!await Tr())return;let n=e.lastAssistantMessage??"";try{await dt("/api/sessions/summarize",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({contentSessionId:e.sessionId,last_assistant_message:n})})}catch(i){b.warn("TRANSCRIPT","Summary request failed",{error:i instanceof Error?i.message:String(i)})}}async updateContext(e,r){if(!r.context||r.context.mode!=="agents"||!await Tr())return;let i=e.cwd??r.workspace;if(!i)return;let o=Ty(i).allProjects.join(",");try{let a=await dt(`/api/context/inject?projects=${encodeURIComponent(o)}`);if(!a.ok)return;let c=(await a.text()).trim();if(!c)return;let u=Ma(r.context.path??`${i}/AGENTS.md`);N5(u,c),b.debug("TRANSCRIPT","Updated AGENTS.md context",{agentsPath:u,watch:r.name})}catch(a){b.warn("TRANSCRIPT","Failed to update AGENTS.md context",{error:a instanceof Error?a.message:String(a)})}}};var GI=class{constructor(e,r,n,i){this.filePath=e;this.onLine=n;this.onOffset=i;this.tailState={offset:r,partial:""}}filePath;onLine;onOffset;watcher=null;tailState;start(){this.readNewData().catch(()=>{}),this.watcher=(0,Oi.watch)(this.filePath,{persistent:!0},()=>{this.readNewData().catch(()=>{})})}close(){this.watcher?.close(),this.watcher=null}async readNewData(){if(!(0,Oi.existsSync)(this.filePath))return;let e=0;try{e=(0,Oi.statSync)(this.filePath).size}catch{return}if(e<this.tailState.offset&&(this.tailState.offset=0),e===this.tailState.offset)return;let r=(0,Oi.createReadStream)(this.filePath,{start:this.tailState.offset,end:e-1,encoding:"utf8"}),n="";for await(let o of r)n+=o;this.tailState.offset=e,this.onOffset(this.tailState.offset);let s=(this.tailState.partial+n).split(`
|
|
1500
|
-
`);this.tailState.partial=s.pop()??"";for(let o of s){let a=o.trim();a&&await this.onLine(a)}}},f_=class{constructor(e,r){this.config=e;this.statePath=r;this.state=C5(r)}config;statePath;processor=new p_;tailers=new Map;state;rescanTimers=[];async start(){for(let e of this.config.watches)await this.setupWatch(e)}stop(){for(let e of this.tailers.values())e.close();this.tailers.clear();for(let e of this.rescanTimers)clearInterval(e);this.rescanTimers=[]}async setupWatch(e){let r=this.resolveSchema(e);if(!r){b.warn("TRANSCRIPT","Missing schema for watch",{watch:e.name});return}let n=Ma(e.path),i=this.resolveWatchFiles(n);for(let a of i)await this.addTailer(a,e,r);let s=e.rescanIntervalMs??5e3,o=setInterval(async()=>{let a=this.resolveWatchFiles(n);for(let c of a)this.tailers.has(c)||await this.addTailer(c,e,r)},s);this.rescanTimers.push(o)}resolveSchema(e){return typeof e.schema=="string"?this.config.schemas?.[e.schema]??null:e.schema}resolveWatchFiles(e){if(this.hasGlob(e))return Mf(e,{nodir:!0,absolute:!0});if((0,Oi.existsSync)(e))try{if((0,Oi.statSync)(e).isDirectory()){let n=(0,m_.join)(e,"**","*.jsonl");return Mf(n,{nodir:!0,absolute:!0})}return[e]}catch{return[]}return[]}hasGlob(e){return/[*?[\]{}()]/.test(e)}async addTailer(e,r,n){if(this.tailers.has(e))return;let i=this.extractSessionIdFromPath(e),s=this.state.offsets[e]??0;if(s===0&&r.startAtEnd)try{s=(0,Oi.statSync)(e).size}catch{s=0}let o=new GI(e,s,async a=>{await this.handleLine(a,r,n,e,i)},a=>{this.state.offsets[e]=a,P5(this.statePath,this.state)});o.start(),this.tailers.set(e,o),b.info("TRANSCRIPT","Watching transcript file",{file:e,watch:r.name,schema:n.name})}async handleLine(e,r,n,i,s){try{let o=JSON.parse(e);await this.processor.processEntry(o,r,n,s??void 0)}catch(o){b.debug("TRANSCRIPT","Failed to parse transcript line",{watch:r.name,file:(0,m_.basename)(i)},o)}}extractSessionIdFromPath(e){let r=e.match(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i);return r?r[0]:null}};var GSe={},zSe=120*1e3;function iR(){return nR.default.join(Se.get("CLAUDE_MEM_DATA_DIR"),".worker-start-attempted")}function LSe(){if(process.platform!=="win32")return!1;let t=iR();if(!(0,ss.existsSync)(t))return!1;try{let e=(0,ss.statSync)(t).mtimeMs;return Date.now()-e<zSe}catch{return!1}}function USe(){if(process.platform==="win32")try{(0,ss.writeFileSync)(iR(),"","utf-8")}catch{}}function FSe(){if(process.platform==="win32")try{let t=iR();(0,ss.existsSync)(t)&&(0,ss.unlinkSync)(t)}catch{}}var qSe="10.7.1";function pH(t,e){return{continue:!0,suppressOutput:!0,status:t,...e&&{message:e}}}var g_=class{server;startTime=Date.now();mcpClient;mcpReady=!1;initializationCompleteFlag=!1;isShuttingDown=!1;dbManager;sessionManager;sseBroadcaster;sdkAgent;geminiAgent;openRouterAgent;paginationHelper;settingsManager;sessionEventBroadcaster;searchRoutes=null;chromaMcpManager=null;initializationComplete;resolveInitialization;stopOrphanReaper=null;staleSessionReaperInterval=null;transcriptWatcher=null;lastAiInteraction=null;constructor(){this.initializationComplete=new Promise(e=>{this.resolveInitialization=e}),this.dbManager=new Ev,this.sessionManager=new Iv(this.dbManager),this.sseBroadcaster=new Rv,this.sdkAgent=new ay(this.dbManager,this.sessionManager),this.geminiAgent=new cy(this.dbManager,this.sessionManager),this.openRouterAgent=new dy(this.dbManager,this.sessionManager),this.paginationHelper=new py(this.dbManager),this.settingsManager=new fy(this.dbManager),this.sessionEventBroadcaster=new vy(this.sseBroadcaster,this),this.sessionManager.setOnSessionDeleted(()=>{this.broadcastProcessingStatus()}),this.mcpClient=new $c({name:"worker-search-proxy",version:qSe},{capabilities:{}}),this.server=new bv({getInitializationComplete:()=>this.initializationCompleteFlag,getMcpReady:()=>this.mcpReady,onShutdown:()=>this.shutdown(),onRestart:()=>this.shutdown(),workerPath:__filename,getAiStatus:()=>{let e="claude";return Uu()&&Ta()?e="openrouter":Lu()&&ka()&&(e="gemini"),{provider:e,authMethod:rg(),lastInteraction:this.lastAiInteraction?{timestamp:this.lastAiInteraction.timestamp,success:this.lastAiInteraction.success,...this.lastAiInteraction.error&&{error:this.lastAiInteraction.error}}:null}}}),this.registerRoutes(),this.registerSignalHandlers()}registerSignalHandlers(){LM(async()=>{this.isShuttingDown=!0,await this.shutdown()})}registerRoutes(){this.server.app.get("/api/context/inject",async(e,r,n)=>{if(!this.initializationCompleteFlag||!this.searchRoutes){b.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){b.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 _y(this.sseBroadcaster,this.dbManager,this.sessionManager)),this.server.registerRoutes(new xy(this.sessionManager,this.dbManager,this.sdkAgent,this.geminiAgent,this.openRouterAgent,this.sessionEventBroadcaster,this)),this.server.registerRoutes(new wy(this.paginationHelper,this.dbManager,this.sessionManager,this.sseBroadcaster,this,this.startTime)),this.server.registerRoutes(new Ny(this.settingsManager)),this.server.registerRoutes(new Dy),this.server.registerRoutes(new jy(this.dbManager,"claude-mem"))}async start(){let e=Jr(),r=IE();await jM(),await this.server.listen(e,r),JM({pid:process.pid,port:e,startedAt:new Date().toISOString()}),vt().registerProcess("worker",{pid:process.pid,type:"worker",startedAt:new Date().toISOString()}),b.info("SYSTEM","Worker started",{host:r,port:e,pid:process.pid}),this.initializeBackground().catch(n=>{b.error("SYSTEM","Background initialization failed",{},n)})}async initializeBackground(){try{await XM();let{ModeManager:e}=await Promise.resolve().then(()=>(Qr(),H6)),{SettingsDefaultsManager:r}=await Promise.resolve().then(()=>(ir(),pM)),{USER_SETTINGS_PATH:n}=await Promise.resolve().then(()=>(zt(),bM)),i=r.loadFromFile(n);(i.CLAUDE_MEM_MODE==="local"||!i.CLAUDE_MEM_MODE)&&YM(),i.CLAUDE_MEM_CHROMA_ENABLED!=="false"?(this.chromaMcpManager=ks.getInstance(),b.info("SYSTEM","ChromaMcpManager initialized (lazy - connects on first use)")):b.info("SYSTEM","Chroma disabled via CLAUDE_MEM_CHROMA_ENABLED=false, skipping ChromaMcpManager");let o=i.CLAUDE_MEM_MODE;e.getInstance().loadMode(o),b.info("SYSTEM",`Mode loaded: ${o}`),await this.dbManager.initialize();let{PendingMessageStore:a}=await Promise.resolve().then(()=>(va(),lu)),u=new a(this.dbManager.getSessionStore().db,3).resetStaleProcessingMessages(0);u>0&&b.info("SYSTEM",`Reset ${u} stale processing messages to pending`);let l=new hy,d=new gy,p=new my(this.dbManager.getSessionSearch(),this.dbManager.getSessionStore(),this.dbManager.getChromaSync(),l,d);if(this.searchRoutes=new Cy(p),this.server.registerRoutes(this.searchRoutes),b.info("WORKER","SearchManager initialized and search routes registered"),this.initializationCompleteFlag=!0,this.resolveInitialization(),b.info("SYSTEM","Core initialization complete (DB + search ready)"),(0,ss.existsSync)(s_))try{let y=R5(s_);if(y.watches.length>0){let x=Ma(y.stateFile??"~/.claude-mem/transcript-watch-state.json");this.transcriptWatcher=new f_(y,x),await this.transcriptWatcher.start(),b.info("SYSTEM",`Transcript watcher started with ${y.watches.length} watch target(s)`)}}catch(y){b.warn("SYSTEM","Failed to start transcript watcher (non-fatal)",{},y)}this.chromaMcpManager&&Nc.backfillAllProjects().then(()=>{b.info("CHROMA_SYNC","Backfill check complete for all projects")}).catch(y=>{b.error("CHROMA_SYNC","Backfill failed (non-blocking)",{},y)});let f=nR.default.join(__dirname,"mcp-server.cjs");vt().assertCanSpawn("mcp server");let m=new Oc({command:"node",args:[f],env:Fi(process.env)}),h=3e5,g=this.mcpClient.connect(m),v,_=new Promise((y,x)=>{v=setTimeout(()=>x(new Error("MCP connection timeout after 5 minutes")),h)});try{await Promise.race([g,_])}catch(y){clearTimeout(v),b.warn("WORKER","MCP server connection failed, cleaning up subprocess",{error:y instanceof Error?y.message:String(y)});try{await m.close()}catch{}throw y}clearTimeout(v);let S=m._process;S?.pid&&(vt().registerProcess("mcp-server",{pid:S.pid,type:"mcp",startedAt:new Date().toISOString()},S),S.once("exit",()=>{vt().unregisterProcess("mcp-server")})),this.mcpReady=!0,b.success("WORKER","MCP server connected"),this.stopOrphanReaper=F6(()=>{let y=new Set;for(let[x]of this.sessionManager.sessions)y.add(x);return y}),b.info("SYSTEM","Started orphan reaper (runs every 30 seconds)"),this.staleSessionReaperInterval=setInterval(async()=>{try{let y=await this.sessionManager.reapStaleSessions();y>0&&b.info("SYSTEM",`Reaped ${y} stale sessions`)}catch(y){b.error("SYSTEM","Stale session reaper error",{error:y instanceof Error?y.message:String(y)})}},120*1e3),this.processPendingQueues(50).then(y=>{y.sessionsStarted>0&&b.info("SYSTEM",`Auto-recovered ${y.sessionsStarted} sessions with pending work`,{totalPending:y.totalPendingSessions,started:y.sessionsStarted,sessionIds:y.startedSessionIds})}).catch(y=>{b.error("SYSTEM","Auto-recovery of pending queues failed",{},y)})}catch(e){throw b.error("SYSTEM","Background initialization failed",{},e),e}}getActiveAgent(){return Uu()&&Ta()?this.openRouterAgent:Lu()&&ka()?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&&(b.debug("SYSTEM","Replacing aborted AbortController before starting generator",{sessionId:e.sessionDbId}),e.abortController=new AbortController);let o=!1,a=!1;b.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},b.error("SDK","Unrecoverable generator error - will NOT restart",{sessionId:e.sessionDbId,project:e.project,errorMessage:u});return}if(this.isSessionTerminatedError(c))return b.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&&(b.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),b.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=vo(e.sessionDbId);if(c&&c.process.exitCode===null&&await yo(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){b.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}b.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(ka())try{await this.geminiAgent.startSession(e,this);return}catch(o){b.warn("SDK","Fallback Gemini failed, trying OpenRouter",{sessionId:n,error:o instanceof Error?o.message:String(o)})}if(Ta())try{await this.openRouterAgent.startSession(e,this);return}catch(o){b.warn("SDK","Fallback OpenRouter failed",{sessionId:n,error:o instanceof Error?o.message:String(o)})}let s=this.sessionManager.getPendingMessageStore().markAllSessionMessagesAbandoned(n);s>0&&b.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);b.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(()=>(va(),lu)),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(`
|
|
1504
|
+
`);this.tailState.partial=s.pop()??"";for(let o of s){let a=o.trim();a&&await this.onLine(a)}}},f_=class{constructor(e,r){this.config=e;this.statePath=r;this.state=C5(r)}config;statePath;processor=new p_;tailers=new Map;state;rescanTimers=[];async start(){for(let e of this.config.watches)await this.setupWatch(e)}stop(){for(let e of this.tailers.values())e.close();this.tailers.clear();for(let e of this.rescanTimers)clearInterval(e);this.rescanTimers=[]}async setupWatch(e){let r=this.resolveSchema(e);if(!r){b.warn("TRANSCRIPT","Missing schema for watch",{watch:e.name});return}let n=Ma(e.path),i=this.resolveWatchFiles(n);for(let a of i)await this.addTailer(a,e,r);let s=e.rescanIntervalMs??5e3,o=setInterval(async()=>{let a=this.resolveWatchFiles(n);for(let c of a)this.tailers.has(c)||await this.addTailer(c,e,r)},s);this.rescanTimers.push(o)}resolveSchema(e){return typeof e.schema=="string"?this.config.schemas?.[e.schema]??null:e.schema}resolveWatchFiles(e){if(this.hasGlob(e))return Mf(e,{nodir:!0,absolute:!0});if((0,Oi.existsSync)(e))try{if((0,Oi.statSync)(e).isDirectory()){let n=(0,m_.join)(e,"**","*.jsonl");return Mf(n,{nodir:!0,absolute:!0})}return[e]}catch{return[]}return[]}hasGlob(e){return/[*?[\]{}()]/.test(e)}async addTailer(e,r,n){if(this.tailers.has(e))return;let i=this.extractSessionIdFromPath(e),s=this.state.offsets[e]??0;if(s===0&&r.startAtEnd)try{s=(0,Oi.statSync)(e).size}catch{s=0}let o=new GI(e,s,async a=>{await this.handleLine(a,r,n,e,i)},a=>{this.state.offsets[e]=a,P5(this.statePath,this.state)});o.start(),this.tailers.set(e,o),b.info("TRANSCRIPT","Watching transcript file",{file:e,watch:r.name,schema:n.name})}async handleLine(e,r,n,i,s){try{let o=JSON.parse(e);await this.processor.processEntry(o,r,n,s??void 0)}catch(o){b.debug("TRANSCRIPT","Failed to parse transcript line",{watch:r.name,file:(0,m_.basename)(i)},o)}}extractSessionIdFromPath(e){let r=e.match(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i);return r?r[0]:null}};var GSe={},zSe=120*1e3;function iR(){return nR.default.join(Se.get("CLAUDE_MEM_DATA_DIR"),".worker-start-attempted")}function LSe(){if(process.platform!=="win32")return!1;let t=iR();if(!(0,ss.existsSync)(t))return!1;try{let e=(0,ss.statSync)(t).mtimeMs;return Date.now()-e<zSe}catch{return!1}}function USe(){if(process.platform==="win32")try{(0,ss.writeFileSync)(iR(),"","utf-8")}catch{}}function FSe(){if(process.platform==="win32")try{let t=iR();(0,ss.existsSync)(t)&&(0,ss.unlinkSync)(t)}catch{}}var qSe="11.0.0";function pH(t,e){return{continue:!0,suppressOutput:!0,status:t,...e&&{message:e}}}var g_=class{server;startTime=Date.now();mcpClient;mcpReady=!1;initializationCompleteFlag=!1;isShuttingDown=!1;dbManager;sessionManager;sseBroadcaster;sdkAgent;geminiAgent;openRouterAgent;paginationHelper;settingsManager;sessionEventBroadcaster;searchRoutes=null;chromaMcpManager=null;initializationComplete;resolveInitialization;stopOrphanReaper=null;staleSessionReaperInterval=null;transcriptWatcher=null;lastAiInteraction=null;constructor(){this.initializationComplete=new Promise(e=>{this.resolveInitialization=e}),this.dbManager=new Ev,this.sessionManager=new Iv(this.dbManager),this.sseBroadcaster=new Rv,this.sdkAgent=new ay(this.dbManager,this.sessionManager),this.geminiAgent=new cy(this.dbManager,this.sessionManager),this.openRouterAgent=new dy(this.dbManager,this.sessionManager),this.paginationHelper=new py(this.dbManager),this.settingsManager=new fy(this.dbManager),this.sessionEventBroadcaster=new vy(this.sseBroadcaster,this),this.sessionManager.setOnSessionDeleted(()=>{this.broadcastProcessingStatus()}),this.mcpClient=new $c({name:"worker-search-proxy",version:qSe},{capabilities:{}}),this.server=new bv({getInitializationComplete:()=>this.initializationCompleteFlag,getMcpReady:()=>this.mcpReady,onShutdown:()=>this.shutdown(),onRestart:()=>this.shutdown(),workerPath:__filename,getAiStatus:()=>{let e="claude";return Uu()&&Ta()?e="openrouter":Lu()&&ka()&&(e="gemini"),{provider:e,authMethod:rg(),lastInteraction:this.lastAiInteraction?{timestamp:this.lastAiInteraction.timestamp,success:this.lastAiInteraction.success,...this.lastAiInteraction.error&&{error:this.lastAiInteraction.error}}:null}}}),this.registerRoutes(),this.registerSignalHandlers()}registerSignalHandlers(){LM(async()=>{this.isShuttingDown=!0,await this.shutdown()})}registerRoutes(){this.server.app.get("/api/context/inject",async(e,r,n)=>{if(!this.initializationCompleteFlag||!this.searchRoutes){b.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){b.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 _y(this.sseBroadcaster,this.dbManager,this.sessionManager)),this.server.registerRoutes(new xy(this.sessionManager,this.dbManager,this.sdkAgent,this.geminiAgent,this.openRouterAgent,this.sessionEventBroadcaster,this)),this.server.registerRoutes(new wy(this.paginationHelper,this.dbManager,this.sessionManager,this.sseBroadcaster,this,this.startTime)),this.server.registerRoutes(new Ny(this.settingsManager)),this.server.registerRoutes(new Dy),this.server.registerRoutes(new jy(this.dbManager,"claude-mem"))}async start(){let e=Jr(),r=IE();await jM(),await this.server.listen(e,r),JM({pid:process.pid,port:e,startedAt:new Date().toISOString()}),vt().registerProcess("worker",{pid:process.pid,type:"worker",startedAt:new Date().toISOString()}),b.info("SYSTEM","Worker started",{host:r,port:e,pid:process.pid}),this.initializeBackground().catch(n=>{b.error("SYSTEM","Background initialization failed",{},n)})}async initializeBackground(){try{await XM();let{ModeManager:e}=await Promise.resolve().then(()=>(Qr(),H6)),{SettingsDefaultsManager:r}=await Promise.resolve().then(()=>(ir(),pM)),{USER_SETTINGS_PATH:n}=await Promise.resolve().then(()=>(zt(),bM)),i=r.loadFromFile(n);(i.CLAUDE_MEM_MODE==="local"||!i.CLAUDE_MEM_MODE)&&YM(),i.CLAUDE_MEM_CHROMA_ENABLED!=="false"?(this.chromaMcpManager=ks.getInstance(),b.info("SYSTEM","ChromaMcpManager initialized (lazy - connects on first use)")):b.info("SYSTEM","Chroma disabled via CLAUDE_MEM_CHROMA_ENABLED=false, skipping ChromaMcpManager");let o=i.CLAUDE_MEM_MODE;e.getInstance().loadMode(o),b.info("SYSTEM",`Mode loaded: ${o}`),await this.dbManager.initialize();let{PendingMessageStore:a}=await Promise.resolve().then(()=>(va(),lu)),u=new a(this.dbManager.getSessionStore().db,3).resetStaleProcessingMessages(0);u>0&&b.info("SYSTEM",`Reset ${u} stale processing messages to pending`);let l=new hy,d=new gy,p=new my(this.dbManager.getSessionSearch(),this.dbManager.getSessionStore(),this.dbManager.getChromaSync(),l,d);if(this.searchRoutes=new Cy(p),this.server.registerRoutes(this.searchRoutes),b.info("WORKER","SearchManager initialized and search routes registered"),this.initializationCompleteFlag=!0,this.resolveInitialization(),b.info("SYSTEM","Core initialization complete (DB + search ready)"),(0,ss.existsSync)(s_))try{let y=R5(s_);if(y.watches.length>0){let x=Ma(y.stateFile??"~/.claude-mem/transcript-watch-state.json");this.transcriptWatcher=new f_(y,x),await this.transcriptWatcher.start(),b.info("SYSTEM",`Transcript watcher started with ${y.watches.length} watch target(s)`)}}catch(y){b.warn("SYSTEM","Failed to start transcript watcher (non-fatal)",{},y)}this.chromaMcpManager&&Nc.backfillAllProjects().then(()=>{b.info("CHROMA_SYNC","Backfill check complete for all projects")}).catch(y=>{b.error("CHROMA_SYNC","Backfill failed (non-blocking)",{},y)});let f=nR.default.join(__dirname,"mcp-server.cjs");vt().assertCanSpawn("mcp server");let m=new Oc({command:"node",args:[f],env:Fi(process.env)}),h=3e5,g=this.mcpClient.connect(m),v,_=new Promise((y,x)=>{v=setTimeout(()=>x(new Error("MCP connection timeout after 5 minutes")),h)});try{await Promise.race([g,_])}catch(y){clearTimeout(v),b.warn("WORKER","MCP server connection failed, cleaning up subprocess",{error:y instanceof Error?y.message:String(y)});try{await m.close()}catch{}throw y}clearTimeout(v);let S=m._process;S?.pid&&(vt().registerProcess("mcp-server",{pid:S.pid,type:"mcp",startedAt:new Date().toISOString()},S),S.once("exit",()=>{vt().unregisterProcess("mcp-server")})),this.mcpReady=!0,b.success("WORKER","MCP server connected"),this.stopOrphanReaper=F6(()=>{let y=new Set;for(let[x]of this.sessionManager.sessions)y.add(x);return y}),b.info("SYSTEM","Started orphan reaper (runs every 30 seconds)"),this.staleSessionReaperInterval=setInterval(async()=>{try{let y=await this.sessionManager.reapStaleSessions();y>0&&b.info("SYSTEM",`Reaped ${y} stale sessions`)}catch(y){b.error("SYSTEM","Stale session reaper error",{error:y instanceof Error?y.message:String(y)})}},120*1e3),this.processPendingQueues(50).then(y=>{y.sessionsStarted>0&&b.info("SYSTEM",`Auto-recovered ${y.sessionsStarted} sessions with pending work`,{totalPending:y.totalPendingSessions,started:y.sessionsStarted,sessionIds:y.startedSessionIds})}).catch(y=>{b.error("SYSTEM","Auto-recovery of pending queues failed",{},y)})}catch(e){throw b.error("SYSTEM","Background initialization failed",{},e),e}}getActiveAgent(){return Uu()&&Ta()?this.openRouterAgent:Lu()&&ka()?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&&(b.debug("SYSTEM","Replacing aborted AbortController before starting generator",{sessionId:e.sessionDbId}),e.abortController=new AbortController);let o=!1,a=!1;b.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},b.error("SDK","Unrecoverable generator error - will NOT restart",{sessionId:e.sessionDbId,project:e.project,errorMessage:u});return}if(this.isSessionTerminatedError(c))return b.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&&(b.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),b.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=vo(e.sessionDbId);if(c&&c.process.exitCode===null&&await yo(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){b.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}b.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(ka())try{await this.geminiAgent.startSession(e,this);return}catch(o){b.warn("SDK","Fallback Gemini failed, trying OpenRouter",{sessionId:n,error:o instanceof Error?o.message:String(o)})}if(Ta())try{await this.openRouterAgent.startSession(e,this);return}catch(o){b.warn("SDK","Fallback OpenRouter failed",{sessionId:n,error:o instanceof Error?o.message:String(o)})}let s=this.sessionManager.getPendingMessageStore().markAllSessionMessagesAbandoned(n);s>0&&b.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);b.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(()=>(va(),lu)),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(`
|
|
1501
1505
|
SELECT id FROM sdk_sessions
|
|
1502
1506
|
WHERE status = 'active' AND started_at_epoch < ?
|
|
1503
1507
|
`).all(o);if(u.length>0){let l=u.map(f=>f.id),d=l.map(()=>"?").join(",");i.db.prepare(`
|