@easbot/memory 0.3.17 → 0.3.20
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/README.en.md +101 -0
- package/README.md +116 -11
- package/dist/chunks/chunk-4GSXSIV5.cjs +1 -0
- package/dist/chunks/chunk-6CQMBEIQ.mjs +1 -0
- package/dist/chunks/chunk-AYGZUNFR.cjs +1 -0
- package/dist/chunks/{chunk-OIUUTVLL.cjs → chunk-EGWJG65Q.cjs} +22 -4
- package/dist/chunks/chunk-J5XF2W4Z.cjs +1 -0
- package/dist/chunks/chunk-JDPZ5U53.mjs +71 -0
- package/dist/chunks/chunk-N5YRDTEH.mjs +60 -0
- package/dist/chunks/{chunk-MWRDF6VN.mjs → chunk-QYBWHFOX.mjs} +1 -1
- package/dist/chunks/chunk-S6S35LDL.cjs +60 -0
- package/dist/chunks/chunk-SWYQLQ7Z.mjs +1 -0
- package/dist/chunks/chunk-TIZCWDJ7.mjs +1 -0
- package/dist/chunks/chunk-UF2Y2Q4L.mjs +50 -0
- package/dist/chunks/chunk-WQB4D6DZ.cjs +1 -0
- package/dist/chunks/chunk-Z5E4HBGK.cjs +50 -0
- package/dist/chunks/cli-handler-2IPBL45N.cjs +1 -0
- package/dist/chunks/cli-handler-5YNHYDSM.mjs +1 -0
- package/dist/chunks/consolidate-G4YJV756.cjs +2 -0
- package/dist/chunks/consolidate-MSPLH3T6.mjs +2 -0
- package/dist/chunks/doctor-GKMREWZN.mjs +1 -0
- package/dist/chunks/doctor-YTUQCHFJ.cjs +1 -0
- package/dist/chunks/extract-3C4QFS7E.mjs +2 -0
- package/dist/chunks/extract-YKDPZ7GA.cjs +2 -0
- package/dist/chunks/forget-GNIJL2DU.cjs +3 -0
- package/dist/chunks/{forget-A4UJI3LE.mjs → forget-VQB5DUJ3.mjs} +1 -1
- package/dist/chunks/{graph-XZ46LEO7.mjs → graph-4W63TU2D.mjs} +1 -1
- package/dist/chunks/graph-GTYUNUJE.cjs +3 -0
- package/dist/chunks/init-DGMGRNCG.cjs +1 -0
- package/dist/chunks/init-G2WTR477.mjs +1 -0
- package/dist/chunks/llm-RMPVWEVP.cjs +1 -0
- package/dist/chunks/llm-UHTBU2HA.mjs +1 -0
- package/dist/chunks/{mcp-BXVXTUJK.cjs → mcp-EHUKGJRB.cjs} +1 -1
- package/dist/chunks/{mcp-BOD4ZOZS.mjs → mcp-QQBHEZFY.mjs} +1 -1
- package/dist/chunks/recall-SGA2DITO.mjs +2 -0
- package/dist/chunks/recall-ZENMAOMJ.cjs +2 -0
- package/dist/chunks/remember-3ZY66RJQ.cjs +2 -0
- package/dist/chunks/remember-P3G7WWYB.mjs +2 -0
- package/dist/chunks/status-JYI52QKB.mjs +1 -0
- package/dist/chunks/status-UEKBJVCI.cjs +1 -0
- package/dist/chunks/stdio-server-2PWTBTDJ.mjs +1 -0
- package/dist/chunks/stdio-server-JL4XNUHH.cjs +1 -0
- package/dist/chunks/sync-64JINCSC.cjs +2 -0
- package/dist/chunks/sync-ZPRCA4MO.mjs +2 -0
- package/dist/cli.cjs +1 -1
- package/dist/cli.mjs +1 -1
- package/dist/index.cjs +4 -4
- package/dist/index.d.cts +87 -38
- package/dist/index.d.ts +87 -38
- package/dist/index.mjs +4 -4
- package/package.json +9 -8
- package/dist/chunks/chunk-BSKFK4RC.mjs +0 -1
- package/dist/chunks/chunk-DFWC6WII.mjs +0 -53
- package/dist/chunks/chunk-DXU5WPK3.cjs +0 -42
- package/dist/chunks/chunk-EECBJNZI.mjs +0 -59
- package/dist/chunks/chunk-FMEXQ5YE.cjs +0 -59
- package/dist/chunks/chunk-HSK27DQ7.cjs +0 -1
- package/dist/chunks/chunk-I6XVFDN2.mjs +0 -42
- package/dist/chunks/chunk-QNDG7BTB.cjs +0 -1
- package/dist/chunks/chunk-RSJ2KT6X.cjs +0 -1
- package/dist/chunks/chunk-TPSRK4M3.mjs +0 -1
- package/dist/chunks/cli-handler-6VTKYXXM.mjs +0 -1
- package/dist/chunks/cli-handler-HNPA3STD.cjs +0 -1
- package/dist/chunks/consolidate-6P7LUPPL.cjs +0 -2
- package/dist/chunks/consolidate-NYH4IKJK.mjs +0 -2
- package/dist/chunks/doctor-IJJ5UYGT.cjs +0 -2
- package/dist/chunks/doctor-MZSZGVRL.mjs +0 -2
- package/dist/chunks/extract-6B7OD3VK.mjs +0 -2
- package/dist/chunks/extract-ERTOHQV6.cjs +0 -2
- package/dist/chunks/forget-KLFM5SBQ.cjs +0 -3
- package/dist/chunks/graph-P5ZHB4ZM.cjs +0 -3
- package/dist/chunks/init-CCOSHE3F.cjs +0 -3
- package/dist/chunks/init-WEPU32KF.mjs +0 -3
- package/dist/chunks/recall-BV4Z7HUJ.mjs +0 -2
- package/dist/chunks/recall-FEINUJKO.cjs +0 -2
- package/dist/chunks/remember-ESVRA73C.mjs +0 -2
- package/dist/chunks/remember-YNSY2JJB.cjs +0 -2
- package/dist/chunks/status-KVM7I6YC.cjs +0 -2
- package/dist/chunks/status-QQZS3ZCN.mjs +0 -2
- package/dist/chunks/stdio-server-MQKTUGNG.cjs +0 -1
- package/dist/chunks/stdio-server-ZLMSUTC5.mjs +0 -1
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
'use strict';var chunkZ5E4HBGK_cjs=require('./chunk-Z5E4HBGK.cjs'),mcp=require('@easbot/mcp'),utils=require('@easbot/utils');var ee=utils.Log.create({service:"memory-format-truncate"}),U="**`";var Q=24e3,z=25e3;async function f(e,n={}){let r=n.softLimit??Q,s=n.hardCeiling??z,o=n.toolName??"memory",c=n.writeToDisk!==false;if(e.length<=r)return {content:e,truncated:false};let i=e.slice(0,s),t=i.lastIndexOf(`
|
|
2
|
+
${U}`),a=i.lastIndexOf(`
|
|
3
|
+
`),u;t>s*.5?u=t:a>0?u=a:u=-1;let d=u>0?i.slice(0,u):i,l=d+"\n\n... (output truncated to budget; the source above is complete and verbatim \u2014 treat it as already Read. For any area not covered, make ANOTHER `<tool>` targeting those names \u2014 do NOT Read these files.)";if(!c)return {content:l,truncated:true,outputPath:"",hint:"Make another recall / graph_query with narrower scope.",info:`... ${e.length-d.length}/${e.length} characters truncated ...`};try{let g=await utils.TruncateContent.truncate(e,{maxChars:d.length,direction:"head",label:`${o}-output`});return g.truncated?{content:l,truncated:!0,outputPath:g.outputPath,hint:utils.TruncateContent.formatHint(g),info:`... ${g.removedLength}/${g.originalLength} characters truncated ...`}:{content:l,truncated:!0,outputPath:"",hint:"Make another recall / graph_query with narrower scope.",info:`... ${e.length-d.length}/${e.length} characters truncated ...`}}catch(g){return ee.warn("TruncateContent.truncate failed, returning without disk hint",{error:g instanceof Error?g.message:String(g)}),{content:l,truncated:true,outputPath:"",hint:"Make another recall / graph_query with narrower scope.",info:`... ${e.length-d.length}/${e.length} characters truncated ...`}}}function $(e,n={}){let r=n.softLimit??Q,s=n.hardCeiling??z;if(e.length<=r)return {content:e,truncated:false};let o=e.slice(0,s),c=o.lastIndexOf(`
|
|
4
|
+
${U}`),i=o.lastIndexOf(`
|
|
5
|
+
`),t;c>s*.5?t=c:i>0?t=i:t=-1;let a=t>0?o.slice(0,t):o;return {content:a+`
|
|
6
|
+
|
|
7
|
+
... (output truncated; tail dropped at section boundary)`,truncated:true,outputPath:"",hint:"",info:`... ${e.length-a.length}/${e.length} characters truncated ...`}}function te(e,n){if(!e||e.length===0)return null;let r=e.filter(o=>n.has(o.path));return r.length===0?null:`\u26A0\uFE0F Index may be stale for: ${r.map(o=>`${o.path} (edited pending)`).join(", ")}
|
|
8
|
+
|
|
9
|
+
`}function I(e,n,r={}){return (J[e]??J.default).replace(/<(\w+)>/g,(o,c)=>c==="tool"?n:r[c]??`<${c}>`)}var J={recall:"If you need more facts, make ANOTHER `<tool>` query with a different scope / interval.\nIf you have enough context, proceed with the current task. Do NOT call `<tool>` again for the same query.",remember:"Memory persisted. To recall it later, use `<tool>` with the same query.\nDo NOT call `<tool>` again to verify \u2014 the fact is already in the database.",forget:"Memory deleted. To verify, run `<tool>` with the same filter (no results expected).\nIf you deleted too much, the data is gone (no auto-restore).",graph_query:"If you need to explore further, make ANOTHER `<tool>` from a different start node or depth.\nOtherwise, the graph is complete for this scope.",status:"Status snapshot. To inspect a specific fact, use `<tool>` (recall) with its id.\nOtherwise, this is a complete read.",consolidate:"Consolidation done. To inspect the new facts, use `<tool>` with the same agentId.\nIf you want to undo, archives are in <archive_dir>.",doctor:"Doctor report. To fix a failing check, run with `repair=true`.\nRe-run after fix to confirm.",default:"If you need more, make ANOTHER `<tool>` with refined parameters.\nOtherwise, this is a complete read."};function X(e,n,r,s){let o=e.tags&&e.tags.length>0?`
|
|
10
|
+
- tags: ${e.tags.join(", ")}`:"",c=e.sessionId?`
|
|
11
|
+
- session: ${e.sessionId}`:"",i=e.msgId?`
|
|
12
|
+
- msg: ${e.msgId}`:"",t=typeof n=="number"?`
|
|
13
|
+
- score: ${n.toFixed(3)}${r?` (${r})`:""}`:"",a=e.truncated?" [truncated]":"",u="";if(s&&s.length>0){let d=[];for(let m of s){let l=[];if(m.edges&&m.edges.length>0)for(let y of m.edges){let b=y.direction??(y.source===m.id?"out":"in"),R=y.targetNode?.name??String(y.target),C=y.targetNode?.type??"node";l.push(` --[${b}] ${y.relation}--> ${R} (${C})`);}let g=l.length>0?l.join(`
|
|
14
|
+
`):" (no relations)";d.push(` - Node: ${m.name} (${m.type})
|
|
15
|
+
${g}`);}u=`
|
|
16
|
+
- linked KG nodes (${s.length}):
|
|
17
|
+
${d.join(`
|
|
18
|
+
`)}`;}return [`### \`${e.id}\`${a}`,` - agentId: ${e.agentId}`,` - category: ${e.category}`,` - importance: ${e.importance}`,` - createdAt: ${e.createdAt}`,` - updatedAt: ${e.updatedAt}`,` - source: ${e.source}${t}${o}${c}${i}${u}`,"",e.content,""].join(`
|
|
19
|
+
`)}async function S(e,n){let r=n.toolName??"memory_recall",s=`**\`memory_recall:${n.query.slice(0,40).replace(/[^a-zA-Z0-9_]/g,"_")}\`**`,o=te(n.pendingFiles,new Set),i=[`Found ${e.total} fact(s) for query "${n.query}" (agentId=${n.agentId}, scope=${n.scope}):`,"",o??"",s].join(`
|
|
20
|
+
`),t=new Map;for(let m of e.hits){let l=m.fact.category;t.has(l)||t.set(l,[]),t.get(l).push(m);}let a=Array.from(t.entries()).map(([m,l])=>{let g=`**\`category:${m}\`**`,y=l.map(b=>X(b.fact,b.score,b.source,b.nodes)).join(`
|
|
21
|
+
`);return `${g}
|
|
22
|
+
|
|
23
|
+
${y}`}).join(`
|
|
24
|
+
`),u=e.warnings&&e.warnings.length>0?`
|
|
25
|
+
|
|
26
|
+
\u26A0\uFE0F warnings:
|
|
27
|
+
${e.warnings.map(m=>` - ${m}`).join(`
|
|
28
|
+
`)}
|
|
29
|
+
`:"",d=`${i}
|
|
30
|
+
|
|
31
|
+
${a}${u}
|
|
32
|
+
|
|
33
|
+
${I("recall",r)}`;return n.sync?$(d,{}).content:(await f(d,{toolName:r,writeToDisk:n.writeToDisk})).content}async function v(e,n={}){let r=n.toolName??"memory_remember",s=`**\`memory_remember:${e.fact.id}\`**`,o=X(e.fact),c=e.nodeIds??[],i=c.length>0?`
|
|
34
|
+
- linked KG nodes: ${c.join(", ")}
|
|
35
|
+
`:"",t=`${s}
|
|
36
|
+
|
|
37
|
+
${o}${i}
|
|
38
|
+
|
|
39
|
+
${I("remember",r)}`;return n.sync?$(t,{}).content:(await f(t,{toolName:r,writeToDisk:n.writeToDisk})).content}async function x(e,n={}){let r=n.toolName??"memory_forget",s="**`memory_forget:result`**",o=e.dryRun?"**DRY RUN** \u2014 no facts were actually deleted. Run again without dryRun to execute.":`Deleted ${e.deletedCount} fact(s).`,c=e.truncatedCount>0?` (truncated: ${e.truncatedCount} more, re-run with narrower filter)`:"",i=[s,"",o+c,"",e.deletedIds.length>0?`deleted ids:
|
|
40
|
+
${e.deletedIds.map(t=>` - ${t}`).join(`
|
|
41
|
+
`)}`:"(no ids to show)","",I("forget",r)].join(`
|
|
42
|
+
`);return n.sync?$(i,{}).content:(await f(i,{toolName:r,writeToDisk:n.writeToDisk})).content}async function N(e,n={}){let r=n.toolName??"memory_graph_query",s=`**\`memory_graph_query:scope=${e.scope}\`**`,o=e.nodes.map(t=>` - node #${t.id}: ${t.name} (${t.type})${t.ownerAgentId?` [owner=${t.ownerAgentId}]`:" [shared]"}`).join(`
|
|
43
|
+
`),c=e.edges.map(t=>` - edge #${t.id}: ${t.source} --${t.relation}--> ${t.target}`).join(`
|
|
44
|
+
`),i=[s,"",`nodes (${e.nodes.length}${e.truncated?` / total ${e.totalNodes}`:""}):`,o||" (none)","",`edges (${e.edges.length}${e.truncated?` / total ${e.totalEdges}`:""}):`,c||" (none)","",I("graph_query",r)].join(`
|
|
45
|
+
`);return n.sync?$(i,{}).content:(await f(i,{toolName:r,writeToDisk:n.writeToDisk})).content}async function M(e,n={}){let r=n.toolName??"memory_status",c=["**`memory_status`**","",`dbPath: ${e.dbPath}`,`workspaceDir: ${e.workspaceDir}`,`factsCount: ${e.factsCount}`,`nodesCount: ${e.nodesCount} (KG nodes)`,`edgesCount: ${e.edgesCount} (KG edges)`,`ftsAvailable: ${e.ftsAvailable?"yes":"no"}`,`vectorEnabled: ${e.vectorEnabled?"yes":"no"}`,`kgScopeEnabled: ${e.kgScopeEnabled?"yes":"no"}`,`healthy: ${e.healthy?"yes":"no"}`,"","factsByCategory:",...Object.entries(e.factsByCategory).map(([i,t])=>` - ${i}: ${t}`),"","meta:",...Object.entries(e.meta).map(([i,t])=>` - ${i}: ${t}`),"",I("status",r)].join(`
|
|
46
|
+
`);return n.sync?$(c,{}).content:(await f(c,{toolName:r,writeToDisk:n.writeToDisk})).content}async function A(e,n={}){let r=n.toolName??"memory_consolidate",o=["**`memory_consolidate:result`**","",`total facts scanned: ${e.totalFacts}`,`deduped (merged): ${e.dedupedCount}`,`compressed: ${e.compressedCount}`,`archived to archive/: ${e.archivedCount}`,`skipped (no change): ${e.skippedCount}`,`duration: ${e.durationMs}ms`,"",I("consolidate",r)].join(`
|
|
47
|
+
`);return n.sync?$(o,{}).content:(await f(o,{toolName:r,writeToDisk:n.writeToDisk})).content}var E=20;async function _(e,n={}){let r=n.toolName??"memory_sync",o=[`**\`memory_sync:${e.dryRun?"DRY_RUN":"OK"}\`**`,"",`windowDays: ${e.windowDays} (threshold: ${e.archiveThreshold})`,"","## Stage A (db \u2192 .md)",`- generated: ${e.generatedCount}`,`- skipped (idempotent): ${e.skippedCount}`,`- failed (best-effort): ${e.failedGenerateCount}`,"","## Stage B (active/ \u2192 archive/)",`- ${e.dryRun?"would archive":"archived"}: ${e.archivedCount}`];if(e.archivedRecords.length>0){o.push("","### Archived records:");let i=e.archivedRecords.slice(0,E);for(let t of i)o.push(`- ${t.firstFactId} (${t.firstCreatedAt})`),o.push(` - source: \`${t.source}\``),o.push(` - target: \`${t.target}\``);e.archivedRecords.length>E&&o.push(`... and ${e.archivedRecords.length-E} more (use --json for full list)`);}o.push("",`duration: ${e.durationMs}ms`,"",I("sync",r));let c=o.join(`
|
|
48
|
+
`);return n.sync?$(c,{}).content:(await f(c,{toolName:r,writeToDisk:n.writeToDisk})).content}async function O(e,n={}){let r=n.toolName??"memory_doctor",s=`**\`memory_doctor:${e.healthy?"OK":"ISSUES"}\`**`,o=t=>t?"\u2705":"\u274C",c=e.checks.map(t=>`${o(t.passed)} ${t.name}: ${t.message}`).join(`
|
|
49
|
+
`),i=[s,"",c,"",I("doctor",r)].join(`
|
|
50
|
+
`);return n.sync?$(i,{}).content:(await f(i,{toolName:r,writeToDisk:n.writeToDisk})).content}async function w(e,n,r={}){let s=n,o=typeof s.kind=="string";switch((o?s:{kind:e}).kind){case "recall":{let i=o?{hits:s.hits,total:s.totalCount??s.total??0,truncated:s.truncated??false}:n;return S(i,{...r,query:s.query??r.query??"",agentId:s.agentId??r.agentId??"",scope:s.scope??r.scope??"agent_only"})}case "remember":{let i=o?{fact:s.fact,nodeIds:s.nodeIds}:n;return v(i,r)}case "forget":return x(o?s:n,r);case "graph_query":return N(o?s:n,r);case "status":return M(o?s:n,r);case "consolidate":return A(o?s:n,r);case "sync":return _(o?s:n,r);case "doctor":return O(o?s:n,r);default:throw new Error(`renderOperationMarkdown: unsupported op "${e}"`)}}var D=utils.Log.create({service:"memory-mcp-stdio"});function he(e){let n=new Map,r=e.isRemote??true,s=!r;function o(t){let a=utils.Locale.resolveLocaleLang();return {agentId:t.agentId??e.agentId,isTrustedLocal:t.isTrustedLocal??s,remote:r,locale:a,dbPath:e.dbPath,workspaceDir:e.workspaceDir,rootDir:e.workspaceDir,config:chunkZ5E4HBGK_cjs.w({agentId:e.agentId,dbPath:e.dbPath})}}function c(t,a){return {content:[{type:"text",text:t}],isError:a}}function i(t){return mcp.formatFailClosed(t,s)}return n.set("recall",async t=>{try{let a=t,u=o({agentId:a.agentId}),d=await chunkZ5E4HBGK_cjs.v("recall",t,u);return {content:[{type:"text",text:await w("recall",d,{toolName:"memory_recall",query:a.query,agentId:a.agentId??e.agentId,scope:a.scope??"agent_only"})}]}}catch(a){return c(i(a),true)}}),n.set("remember",async t=>{try{let u=o({agentId:t.agentId}),d=await chunkZ5E4HBGK_cjs.v("remember",t,u);return {content:[{type:"text",text:await w("remember",d,{toolName:"memory_remember"})}]}}catch(a){return c(i(a),true)}}),n.set("forget",async t=>{try{let u=o({agentId:t.agentId}),d=await chunkZ5E4HBGK_cjs.v("forget",t,u);return {content:[{type:"text",text:await w("forget",d,{toolName:"memory_forget"})}]}}catch(a){return c(i(a),true)}}),n.set("extract",async t=>{try{let u=o({agentId:t.agentId}),m=await chunkZ5E4HBGK_cjs.v("extract",t,u);return {content:[{type:"text",text:`Extract completed.
|
|
51
|
+
sessionId: ${t.sessionId??"(unknown)"}
|
|
52
|
+
extractedCount: ${m.extractedCount}
|
|
53
|
+
factIds: ${m.factIds.length>0?m.factIds.join(", "):"(none)"}
|
|
54
|
+
messageRange: ${m.messageRange.fromMessageId} -> ${m.messageRange.toMessageId}
|
|
55
|
+
`}]}}catch(a){return c(i(a),true)}}),n.set("consolidate",async t=>{try{let u=o({agentId:t.agentId,isTrustedLocal:!0}),d=await chunkZ5E4HBGK_cjs.v("consolidate",t,u);return {content:[{type:"text",text:await w("consolidate",d,{toolName:"memory_consolidate"})}]}}catch(a){return c(i(a),true)}}),n.set("sync",async t=>{try{let u=t.agentId?.trim();if(!u)return c(i(new Error("memory_sync: agentId is required (sync requires agentId, see ADR 0069)")),!0);let d=o({agentId:u,isTrustedLocal:!0}),m=await chunkZ5E4HBGK_cjs.v("sync",t,d);return {content:[{type:"text",text:await w("sync",m,{toolName:"memory_sync"})}]}}catch(a){return c(i(a),true)}}),n.set("graph_query",async t=>{try{let a=t,u=o({agentId:a.agentId}),d=await chunkZ5E4HBGK_cjs.v("graph_query",t,u);return {content:[{type:"text",text:await w("graph_query",d,{toolName:"memory_graph_query",scope:a.scope??"agent_only"})}]}}catch(a){return c(i(a),true)}}),n.set("status",async t=>{try{let u=o({agentId:(t??{}).agentId}),d=await chunkZ5E4HBGK_cjs.v("status",t,u);return {content:[{type:"text",text:await w("status",d,{toolName:"memory_status"})}]}}catch(a){return c(i(a),true)}}),n.set("doctor",async t=>{try{let u=o({agentId:(t??{}).agentId,isTrustedLocal:!0}),d=await chunkZ5E4HBGK_cjs.v("doctor",t,u);return {content:[{type:"text",text:await w("doctor",d,{toolName:"memory_doctor"})}]}}catch(a){return c(i(a),true)}}),n.set("init",async t=>{try{let a=o({isTrustedLocal:!0}),d=await chunkZ5E4HBGK_cjs.v("init",t,a);return {content:[{type:"text",text:`Init complete.
|
|
56
|
+
dbPath: ${d.dbPath}
|
|
57
|
+
tablesCreated: ${d.tablesCreated}
|
|
58
|
+
migrationsApplied: ${d.migrationsApplied}
|
|
59
|
+
durationMs: ${d.durationMs}
|
|
60
|
+
`}]}}catch(a){return c(i(a),true)}}),n}var ye={recall:chunkZ5E4HBGK_cjs.c,remember:chunkZ5E4HBGK_cjs.d,forget:chunkZ5E4HBGK_cjs.e,extract:chunkZ5E4HBGK_cjs.f,consolidate:chunkZ5E4HBGK_cjs.g,sync:chunkZ5E4HBGK_cjs.j,graph_query:chunkZ5E4HBGK_cjs.h,init:chunkZ5E4HBGK_cjs.i};function fe(e,n){let r=chunkZ5E4HBGK_cjs.t[e],s={title:r?.annotations?.defaultDescription??e,readOnlyHint:r?.annotations?.readOnlyHint??false,destructiveHint:r?.annotations?.destructiveHint??false,idempotentHint:r?.annotations?.idempotentHint??true,openWorldHint:false},o=ye[e];return {name:e,description:r?.annotations?.defaultDescription??`memory op: ${e}`,inputSchema:o??{type:"object",properties:{},required:[]},annotations:s,handler:n}}exports.b=void 0;(r=>{async function e(s,o){let{getMemoryDbPath:c,getInstance:i}=await import('./interfaces-XWE45ENK.cjs'),a=o!==null&&typeof o=="object"&&"agentId"in o&&"dbPath"in o?o:{agentId:process.env.EASBOT_AGENT_ID??"default",dbPath:c(),workspaceDir:i().worktree,isRemote:false},u=new mcp.ToolRegistry,d=he(a),m=Object.keys(chunkZ5E4HBGK_cjs.t);for(let p of m){let P=d.get(p);if(!P)throw new Error(`MemoryStdioServer.start: missing handler for tool "${p}"`);u.register(fe(p,P));}D.info("starting memory MCP stdio server",{id:s.id,name:s.name,toolCount:m.length,isRemote:a.isRemote??true});let l=await mcp.createAndStartStdioServer(s,u),g=null,y=new Promise(p=>{g=p;}),b=p=>{D.info("received signal, stopping MCP server",{signal:p}),g?.();},R=()=>b("SIGINT"),C=()=>b("SIGTERM");process.on("SIGINT",R),process.on("SIGTERM",C);try{await y;}finally{try{process.off("SIGINT",R),process.off("SIGTERM",C);}catch(p){D.warn("failed to remove signal handlers",{error:p instanceof Error?p.message:String(p)});}try{await l.stop();}catch(p){D.warn("server.stop failed during cleanup",{error:p instanceof Error?p.message:String(p)});}}return {id:s.id,name:s.name,version:s.version,tools:m}}r.start=e;function n(){return Object.keys(chunkZ5E4HBGK_cjs.t)}r.getToolNames=n;})(exports.b||(exports.b={}));exports.a=w;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var f={languages:[{value:"zh-CN",name:"\u7B80\u4F53\u4E2D\u6587",example:"\u4F60\u597D\uFF0CEASBOT\uFF01",supported:true},{value:"en-US",name:"English (United States)",example:"Hello, EASBOT!",supported:true}]};var b=f.languages,v=b.filter(e=>e.supported).map(e=>e.value),a={defaultLocale:"zh-CN",locales:v},m={},p=(e,t)=>{let r=m[e]||{translation:{}};return m[e]={translation:{...r.translation,...t.translation}},m[e]},u=(e=a.defaultLocale)=>(m[e]||p(e,{translation:{}}),{locale:e,resources:m[e]||{translation:{}}});var L={translation:{"cli.cmd.init.description":"\u521D\u59CB\u5316\u8BB0\u5FC6 workspace\uFF08.easbot/memory.db\uFF09","cli.cmd.recall.description":"\u6DF7\u5408\u641C\u7D22\uFF08FTS + \u5411\u91CF\uFF09\u67E5\u8BE2\u8BB0\u5FC6","cli.cmd.remember.description":"\u5199\u5165\u4E00\u6761\u65B0\u8BB0\u5FC6\uFF08\u81EA\u5E26 dedup + \u77E5\u8BC6\u56FE\u8C31\u62BD\u53D6\uFF09","cli.cmd.forget.description":"\u5220\u9664\u8BB0\u5FC6\uFF08factId / category / \u65F6\u95F4\u7A97 / \u8BD5\u8FD0\u884C\uFF09","cli.cmd.sync.description":"\u540C\u6B65 facts \u5230 .md\uFF08\u5E42\u7B49\u8DF3\u8FC7\uFF09\u5E76\u5F52\u6863\u8FC7\u671F active \u6587\u4EF6\uFF08\u9ED8\u8BA4 30 \u5929\uFF09","cli.cmd.extract.description":"\u4ECE session \u62BD\u53D6 facts\uFF08sessionId + lastN\uFF09","cli.cmd.consolidate.description":"\u8FD0\u884C consolidation \u6D41\u6C34\u7EBF\uFF08extract \u2192 dedup \u2192 archive\uFF09","cli.cmd.graph.description":"\u77E5\u8BC6\u56FE\u8C31\u67E5\u8BE2\uFF08nodes / edges / neighbors\uFF0Cscope \u4E09\u6863\uFF09","cli.cmd.status.description":"\u663E\u793A\u8BB0\u5FC6\u72B6\u6001 / \u6570\u636E\u5E93\u7EDF\u8BA1 / \u5404\u7C7B\u522B\u8BA1\u6570","cli.cmd.doctor.description":"\u8FD0\u884C\u5065\u5EB7\u68C0\u67E5\uFF08\u540E\u7AEF / FTS / schema / \u9501\uFF09","cli.cmd.config.description":"\u67E5\u770B / \u6821\u9A8C\u8BB0\u5FC6\u914D\u7F6E\uFF08dry-read\uFF09","cli.cmd.mcp.description":"\u542F\u52A8 stdio MCP \u670D\u52A1\u5668\uFF08\u66B4\u9732 10 \u4E2A memory \u5DE5\u5177\uFF09","memory.recall.empty":"\uFF08\u65E0\u5339\u914D\u8BB0\u5FC6\uFF09","memory.recall.summary":"\u5171\u5339\u914D {{total}} \u6761\u8BB0\u5FC6\uFF1A","memory.recall.item":" - {{id}} [{{category}}/\u91CD\u8981\u6027={{importance}}/\u5206\u6570={{score}}] {{content}}","memory.forget.empty":"\uFF08\u672A\u547D\u4E2D\u53EF\u5220\u9664\u7684\u8BB0\u5F55\uFF09\uFF09","memory.forget.summary":"\u5220\u9664 {{deletedCount}} \u6761\u8BB0\u5FC6\uFF08dryRun={{dryRun}}\uFF09\uFF1A","memory.forget.item":" - {{id}}","memory.remember.summary":"\u8BB0\u5FC6\u5DF2\u5199\u5165\uFF1A","memory.remember.item":" - id={{id}} \u7C7B\u522B={{category}} \u91CD\u8981\u6027={{importance}}","memory.consolidate.summary":"consolidation \u5B8C\u6210\uFF1A","memory.consolidate.item":" - \u603B\u8BA1 {{totalFacts}} \u53BB\u91CD {{dedupedCount}} \u5F52\u6863 {{archivedCount}}","memory.sync.summary":"sync \u5B8C\u6210\uFF08windowDays={{windowDays}}, dryRun={{dryRun}}\uFF09\uFF1A","memory.sync.item":" - \u751F\u6210 {{generatedCount}} \u8DF3\u8FC7 {{skippedCount}} \u5931\u8D25 {{failedGenerateCount}} \u5F52\u6863 {{archivedCount}}\uFF08\u9608\u503C {{archiveThreshold}}\uFF09","memory.status.empty":"\uFF08\u6682\u65E0\u6570\u636E\uFF09","memory.status.summary":"\u8BB0\u5FC6\u72B6\u6001\uFF1A","memory.status.item":" - {{key}}: {{value}}","memory.doctor.empty":"\uFF08\u65E0\u68C0\u67E5\u9879\uFF09","memory.doctor.summary":"\u5065\u5EB7\u68C0\u67E5\uFF1A{{status}}","memory.doctor.item":" - {{name}}: {{message}}","memory.graph.empty":"\uFF08\u65E0\u8282\u70B9\u547D\u4E2D\uFF09","memory.graph.summary":"\u77E5\u8BC6\u56FE\u8C31\u67E5\u8BE2\uFF08\u5171 {{totalNodes}} \u8282\u70B9\uFF09\uFF1A","memory.graph.item":" - {{id}} {{name}} [{{type}}]","memory.extract.summary":"\u62BD\u53D6 {{extractedCount}} \u6761 facts\uFF1A","memory.extract.item":" - {{id}}","memory.init.summary":"\u521D\u59CB\u5316\u5B8C\u6210\uFF1A","memory.init.item":" - db={{dbPath}} \u8FC1\u79FB={{migrationsApplied}} \u8868={{tablesCreated}}"}},h=L;var S={translation:{"cli.cmd.init.description":"Initialize memory workspace (.easbot/memory.db)","cli.cmd.recall.description":"Hybrid search (FTS + vector) over memory facts","cli.cmd.remember.description":"Persist a new memory fact (with dedup + KG extraction)","cli.cmd.forget.description":"Delete memory facts (factId / category / timeRange / dryRun)","cli.cmd.sync.description":"Sync facts to .md (idempotent skip) and archive expired active files (default 30 days)","cli.cmd.extract.description":"Extract facts from a session (sessionId + lastN)","cli.cmd.consolidate.description":"Run consolidation pipeline (extract \u2192 dedup \u2192 archive)","cli.cmd.graph.description":"KG query (nodes / edges / neighbors with scope \u4E09\u6863)","cli.cmd.status.description":"Show memory state / db stats / facts by category","cli.cmd.doctor.description":"Run health checks (backend, FTS, schema, lock)","cli.cmd.config.description":"Show / validate memory configuration (dry-read)","cli.cmd.mcp.description":"Start stdio MCP server (exposes 10 memory tools)","memory.recall.empty":"(no matching facts)","memory.recall.summary":"Found {{total}} fact(s):","memory.recall.item":" - {{id}} [{{category}}/imp={{importance}}/score={{score}}] {{content}}","memory.forget.empty":"(no records to delete)","memory.forget.summary":"Deleted {{deletedCount}} fact(s) (dryRun={{dryRun}}):","memory.forget.item":" - {{id}}","memory.remember.summary":"Memory persisted:","memory.remember.item":" - id={{id}} category={{category}} importance={{importance}}","memory.consolidate.summary":"Consolidation complete:","memory.consolidate.item":" - total {{totalFacts}} deduped {{dedupedCount}} archived {{archivedCount}}","memory.sync.summary":"Sync complete (windowDays={{windowDays}}, dryRun={{dryRun}}):","memory.sync.item":" - generated {{generatedCount}} skipped {{skippedCount}} failed {{failedGenerateCount}} archived {{archivedCount}} (threshold {{archiveThreshold}})","memory.status.empty":"(no data)","memory.status.summary":"Memory status:","memory.status.item":" - {{key}}: {{value}}","memory.doctor.empty":"(no checks)","memory.doctor.summary":"Health check: {{status}}","memory.doctor.item":" - {{name}}: {{message}}","memory.graph.empty":"(no nodes matched)","memory.graph.summary":"KG query ({{totalNodes}} node(s)):","memory.graph.item":" - {{id}} {{name}} [{{type}}]","memory.extract.summary":"Extracted {{extractedCount}} fact(s):","memory.extract.item":" - {{id}}","memory.init.summary":"Initialization complete:","memory.init.item":" - db={{dbPath}} migrations={{migrationsApplied}} tables={{tablesCreated}}"}},x=S;var w=()=>{u("zh-CN"),u("en-US"),p("zh-CN",h),p("en-US",x);};w();var y=new Map;var g=new Map;var k=e=>{if(g.has(e))return g.get(e);let t=/{{\s*(\w+)\s*}}/g,r=[],o;for(;(o=t.exec(e))!==null;){let n=o[1];n&&!r.includes(n)&&r.push(n);}let i=new RegExp("{{\\s*("+r.join("|")+")\\s*}}","g"),s={keys:r,regex:i};return g.set(e,s),s},R=(e,t)=>{if(!e||typeof e!="string")return "";if(!t||Object.keys(t).length===0)return e;let{regex:r,keys:o}=k(e);return o.length===0||!o.some(s=>s in t)?e:e.replace(r,(s,n)=>{let c=t[n];return c==null?"":String(c)})},I=e=>{if(e&&a.locales.includes(e))return e;let t=process.env.EASBOT_LANG?.trim()||process.env.LANG?.trim();if(t){let r=t.replace(/_/g,"-");if(a.locales.includes(r))return r;let o=r.split("-")[0];if(o==="zh")return "zh-CN";if(o==="en")return "en-US"}return a.defaultLocale},T=e=>{if(!y.has(e)){let{resources:t}=u(e);y.set(e,t);}return y.get(e)},N=(e,t={})=>{let r=I(t.locale),i=T(r)?.translation[e];if(i&&typeof i=="string"){let s=R(i,t.vars);return s!=null?String(s):String(e)}if(r!==a.defaultLocale){let n=T(a.defaultLocale)?.translation[e];if(n&&typeof n=="string"){let c=R(n,t.vars);return c!=null?String(c):String(e)}}return String(t.fallback??e)},_=N;export{_ as a};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {f}from'./chunk-WDVDYZ25.mjs';import {Log}from'@easbot/utils';import {renderLines,printHuman,emitJsonOk,formatKnowledgeDoctor,formatKnowledgeStatus,formatKnowledgeInit,emitJsonError}from'@easbot/terminal';var y=Log.create({service:"memory-cli"}),S=[{i18nKey:"cli.cmd.init.description",name:"init",description:"Initialize memory workspace (.easbot/memory.db)",group:"lifecycle"},{i18nKey:"cli.cmd.status.description",name:"status",description:"Show memory state / db stats / facts by category",group:"lifecycle"},{i18nKey:"cli.cmd.doctor.description",name:"doctor",description:"Run health checks (backend, FTS, schema, lock)",group:"lifecycle"},{i18nKey:"cli.cmd.recall.description",name:"recall",description:"Hybrid search (FTS + vector) over memory facts",group:"memory"},{i18nKey:"cli.cmd.remember.description",name:"remember",description:"Persist a new memory fact (with dedup + KG extraction)",group:"memory"},{i18nKey:"cli.cmd.forget.description",name:"forget",description:"Delete memory facts (factId / category / timeRange / dryRun)",group:"memory"},{i18nKey:"cli.cmd.sync.description",name:"sync",description:"Sync facts to .md files (idempotent) and archive expired active files (default 30 days)",group:"memory"},{i18nKey:"cli.cmd.extract.description",name:"extract",description:"Extract facts from a session (sessionId + lastN)",group:"session"},{i18nKey:"cli.cmd.consolidate.description",name:"consolidate",description:"Run consolidation pipeline (extract \u2192 dedup \u2192 archive)",group:"session"},{i18nKey:"cli.cmd.graph.description",name:"graph",description:"KG query (nodes / edges / neighbors with scope \u4E09\u6863)",group:"graph"},{i18nKey:"cli.cmd.config.description",name:"config",description:"Show / validate memory configuration (dry-read)",group:"external"},{i18nKey:"cli.cmd.mcp.description",name:"mcp",description:"Start stdio MCP server (exposes 10 memory tools)",group:"external"}];function u(m,t){let e=S.filter(a=>a.group===m);return renderLines({title:t,flat:e.map(a=>`$ easbot-memory ${a.name.padEnd(14)} ${a.description}`)})}function v(){let m=[renderLines({title:"easbot-memory \xB7 Memory & Knowledge Module for EASBot",flat:["Usage: easbot-memory <command> [options]"]}),"",u("lifecycle","Commands (lifecycle):"),"",u("memory","Commands (memory):"),"",u("session","Commands (session):"),"",u("graph","Commands (graph query):"),"",u("external","External:")];printHuman(m);}function C(){v(),printHuman(["",renderLines({title:"Global flags & invocation",flat:["--cwd <dir> --config <path> --log-level <L> --print-logs --debug","Standalone CLI: easbot-memory <command>","Agent CLI: easbot memory <command>"]})]);}async function j(m){try{let{bootstrapLlm:t}=await import('@easbot/llm'),{Llm:e}=await import('./llm-UHTBU2HA.mjs');await t({target:e,cwd:m,subConfigPath:".easbot/memory.json",embedding:!0,graph:!0});}catch(t){y.warn("bootstrapLlm failed; Llm-related features will be disabled",{error:t instanceof Error?t.message:String(t)});}}async function A(m,t){let[e,...a]=m,c=t?.cwd??process.cwd();if(!e)return C(),{code:0,handled:true,command:null};await j(c);try{switch(e){case "init":{let{parseInitOptions:r,runInit:n}=await import('./init-G2WTR477.mjs'),s=r(a);if(s.help)return console.log("Usage: easbot-memory init [dir] [--agent <id>] [--force] [--json]"),{code:0,handled:!0,command:e};let o=s.workspaceDir?.trim()??c,i=await n({...s,ctxWorkspaceDir:o});if(s.json)emitJsonOk(i,{command:e});else {let p=i;printHuman([formatKnowledgeInit({packageName:"memory",configPath:p.configPath??p.dbPath,backend:"better-sqlite3",schemaVersion:p.schemaVersion,extras:{dbPath:p.dbPath,migrationsApplied:p.migrationsApplied,tablesCreated:p.tablesCreated,durationMs:`${p.durationMs}ms`}})],{title:"init memory workspace",boxed:!0});}return {code:0,handled:!0,command:e}}case "recall":{let{parseRecallOptions:r,runRecall:n,formatRecallText:s}=await import('./recall-SGA2DITO.mjs'),o=r(a);if(o.help)return console.log("Usage: easbot-memory recall --query <q> [--agent <id>] [--limit <n>] [--category <c>] [--min-importance <n>] [--json]"),{code:0,handled:!0,command:e};let i=await n({...o,workspaceDir:c});return o.json?emitJsonOk(i,{command:e}):printHuman([s(i)],{title:`recall (agentId=${o.agentId??"default"})`}),{code:0,handled:!0,command:e}}case "remember":{let{parseRememberOptions:r,runRemember:n,formatRememberText:s}=await import('./remember-P3G7WWYB.mjs'),o=r(a);if(o.help)return console.log("Usage: easbot-memory remember --content <text> --category <c> --importance <1-10> [--agent <id>] [--tag <t>] [--session <s>] [--json]"),{code:0,handled:!0,command:e};let i=await n({...o,workspaceDir:c});return o.json?emitJsonOk(i,{command:e}):printHuman([s(i)],{title:"remember (persist fact)"}),{code:0,handled:!0,command:e}}case "forget":{let{parseForgetOptions:r,runForget:n,formatForgetText:s}=await import('./forget-VQB5DUJ3.mjs'),o=r(a);if(o.help)return console.log("Usage: easbot-memory forget [--agent <id>] (--fact-id <id> | --category <c> | --from <ISO> --to <ISO>) [--max-delete <n>] [--dry-run] [--json]"),{code:0,handled:!0,command:e};let i=await n({...o,workspaceDir:c});return o.json?emitJsonOk(i,{command:e}):printHuman([s(i)],{title:"forget (delete facts)"}),{code:0,handled:!0,command:e}}case "extract":{let{parseExtractOptions:r,runExtract:n,formatExtractText:s}=await import('./extract-3C4QFS7E.mjs'),o=r(a);if(o.help)return console.log("Usage: easbot-memory extract --session <sessionId> [--agent <id>] [--last-n <n>] [--from-msg <id>] [--json]"),{code:0,handled:!0,command:e};let i=await n({...o,workspaceDir:c});return o.json?emitJsonOk(i,{command:e}):printHuman([s(i)],{title:"extract (from session)"}),{code:0,handled:!0,command:e}}case "consolidate":{let{parseConsolidateOptions:r,runConsolidate:n,formatConsolidateText:s}=await import('./consolidate-MSPLH3T6.mjs'),o=r(a);if(o.help)return console.log("Usage: easbot-memory consolidate [--agent <id>] [--window-days <n>] [--json]"),{code:0,handled:!0,command:e};let i=await n({...o,workspaceDir:c});return o.json?emitJsonOk(i,{command:e}):printHuman([s(i)],{title:"consolidate (pipeline)"}),{code:0,handled:!0,command:e}}case "sync":{let{parseSyncOptions:r,runSync:n,formatSyncText:s}=await import('./sync-ZPRCA4MO.mjs'),o=r(a);if(o.help)return console.log("Usage: easbot-memory sync [--agent <id>] [--window-days <n>] [--dry-run] [--json]"),console.log("Two-stage pipeline: (A) db \u2192 .md (idempotent skip on existing), (B) archive active/ files older than windowDays."),{code:0,handled:!0,command:e};let i=await n({...o,workspaceDir:c});return o.json?emitJsonOk(i,{command:e}):printHuman([s(i)],{title:"sync (db \u2192 .md + archive)"}),{code:0,handled:!0,command:e}}case "graph":{let{parseGraphOptions:r,runGraph:n,formatGraphText:s}=await import('./graph-4W63TU2D.mjs'),o=r(a);if(o.help)return console.log("Usage: easbot-memory graph [--agent <id>] --kind <nodes|edges|neighbors> [--query <q>] [--start-node <id>] [--depth <n>] [--max-nodes <n>] [--scope <agent_only|shared_only|both>] [--json]"),{code:0,handled:!0,command:e};let i=await n({...o,workspaceDir:c});return o.json?emitJsonOk(i,{command:e}):printHuman([s(i)],{title:`graph_query (scope=${o.scope??"agent_only"})`}),{code:0,handled:!0,command:e}}case "status":{let{parseStatusOptions:r,runStatus:n}=await import('./status-JYI52QKB.mjs'),s=r(a);if(s.help)return console.log("Usage: easbot-memory status [--agent <id>] [--json]"),{code:0,handled:!0,command:e};let o=await n({...s,workspaceDir:c});return s.json?emitJsonOk(o,{command:e}):printHuman([formatKnowledgeStatus(I(o))],{title:"memory status",boxed:!0}),{code:0,handled:!0,command:e}}case "doctor":{let{parseDoctorOptions:r,runDoctor:n}=await import('./doctor-GKMREWZN.mjs'),s=r(a);if(s.help)return console.log("Usage: easbot-memory doctor [--repair] [--json]"),{code:0,handled:!0,command:e};let o=await n({...s,workspaceDir:c});return s.json?emitJsonOk(o,{command:e}):printHuman([formatKnowledgeDoctor(K(o))],{title:"memory doctor",boxed:!0}),{code:0,handled:!0,command:e}}case "config":{let{parseConfigOptions:r,runConfig:n,formatConfigText:s}=await import('./config-2SQJYVTO.mjs'),o=r(a);if(o.help)return console.log("Usage: easbot-memory config [--json]"),{code:0,handled:!0,command:e};let i=n(o);return o.json?emitJsonOk(i,{command:e}):printHuman([s(i)],{title:"memory config"}),{code:0,handled:!0,command:e}}case "mcp":{let{parseMcpOptions:r,runMcp:n}=await import('./mcp-QQBHEZFY.mjs'),s=r(a);if(s.help)return console.log("Usage: easbot-memory mcp [start]"),console.log("Start a stdio MCP server exposing 10 memory tools:"),console.log(" recall / remember / forget / extract / consolidate"),console.log(" graph_query / status / doctor / init / sync"),{code:0,handled:!0,command:e};let o=await n(s);return s.json?emitJsonOk(o,{command:e}):printHuman([`memory mcp started (tools: ${o.tools.length})`],{title:"memory mcp server"}),{code:0,handled:!0,command:e}}default:return console.error(`Unknown command: ${e}`),console.error("Run `easbot-memory --help` for available commands."),{code:2,handled:!1,command:null}}}catch(r){let n=r instanceof Error?r.message:String(r);y.error("memory CLI command failed",{command:e,error:n,stack:r instanceof Error?r.stack:void 0});let s=t?.cwd??f().worktree;return console.error(`[memory] ${s} :: ${e} failed: ${n}`),emitJsonError(e,n),{code:1,handled:true,command:e}}}function I(m){let t=m;return {packageName:"memory",rootDir:t.workspaceDir??"",configPath:t.configPath??"",configExists:true,dbPath:t.dbPath??"",dbExists:true,dbSize:typeof t.dbSize=="number"?t.dbSize:void 0,indexState:t.indexState,schemaVersion:typeof t.schemaVersion=="number"?t.schemaVersion:void 0,extractionVersion:typeof t.extractionVersion=="number"?t.extractionVersion:void 0,lastSyncAt:t.lastSyncAt,vectorEnabled:typeof t.vectorEnabled=="boolean"?t.vectorEnabled:void 0,embeddingDims:typeof t.embeddingDims=="number"?t.embeddingDims:void 0,llm:t.llm??{initialized:false,capabilities:{}},backend:t.backend,counts:t.counts??{},healthy:typeof t.healthy=="boolean"?t.healthy:true,recommendation:t.recommendation,extras:(()=>{let e={};if(typeof t.agentId=="string"&&(e.agent_id=t.agentId),typeof t.ftsAvailable=="boolean"&&(e.fts_available=t.ftsAvailable?"yes":"no"),typeof t.kgScopeEnabled=="boolean"&&(e.kg_scope_enabled=t.kgScopeEnabled?"yes":"no"),t.factsByCategory&&typeof t.factsByCategory=="object"){let a=t.factsByCategory;for(let[c,r]of Object.entries(a))typeof r=="number"&&r>0&&(e[`facts/${c}`]=r);}return Object.keys(e).length>0?e:void 0})()}}function K(m){let t=m,e=Array.isArray(t.checks)?t.checks:[],a=t.integrityStats,c=t.backendAvailable,r=a?{nodes:a.nodes??0,edges:a.edges??0,file_hashes:0,fts:a.memory_facts_fts??0,node_embeddings:a.memory_vectors??0,embedding_cache:a.embedding_cache??0,parse_errors:0,unresolved_refs:0,name_segment_vocab:0,project_metadata:0,meta:a.meta??0}:void 0;return {packageName:"memory",healthy:typeof t.healthy=="boolean"?t.healthy:false,durationMs:typeof t.durationMs=="number"?t.durationMs:0,checks:e.map(n=>({code:typeof n.code=="string"?n.code:"",severity:n.severity??"info",name:typeof n.name=="string"?n.name:"",message:typeof n.message=="string"?n.message:"",durationMs:typeof n.durationMs=="number"?n.durationMs:void 0,details:n.details})),dbStats:r,backendAvailable:c}}export{S as a,v as b,C as c,A as d};
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import {e,a as a$2}from'./chunk-JDPZ5U53.mjs';import {j}from'./chunk-WDVDYZ25.mjs';import {a as a$1}from'./chunk-6CQMBEIQ.mjs';import {a}from'./chunk-HQBRVVXS.mjs';import {Log,Locale,formatLocalISO}from'@easbot/utils';import {z}from'zod';import {randomBytes,createHash}from'crypto';import {GraphProvider,probeEmbeddingDims,syncMeta}from'@easbot/llm';import z$1 from'fs/promises';import de from'path';import {writeFileSync}from'fs';import {createRequire}from'module';import {EMBEDDING_DIMS_CONSISTENCY_CHECK,DEFAULT_SEARCH_CONFIG}from'@easbot/types';var le=Log.create({service:"memory.graph-store"}),V=class{constructor(e){a(this,"db");this.db=e;}async upsertNode(e,n,r,o){let c=Date.now(),s=JSON.stringify(r??{}),i=this.db.prepare("SELECT id FROM nodes WHERE name = ? AND type = ? LIMIT 1").get(e,n);if(i)return this.db.prepare("UPDATE nodes SET properties = ?, updatedAt = ? WHERE id = ?").run(s,c,i.id),i.id;let p=this.db.prepare("INSERT INTO nodes (name, type, properties, owner_agent_id, createdAt, updatedAt) VALUES (?, ?, ?, ?, ?, ?)").run(e,n,s,o??null,c,c);return Number(p.lastInsertRowid)}async deleteNode(e){this.db.prepare("DELETE FROM nodes WHERE id = ?").run(e);}async upsertEdge(e,n,r,o){let c=this.db.prepare("INSERT OR REPLACE INTO edges (source, target, relation, properties, createdAt) VALUES (?, ?, ?, ?, ?)").run(e,n,r,JSON.stringify(o??{}),Date.now());return Number(c.lastInsertRowid)}async queryNodes(e={}){let n="SELECT id, name, type, properties, owner_agent_id, createdAt, updatedAt FROM nodes",r=[],o=[];if(e.ids&&e.ids.length>0){let s=e.ids.map(i=>typeof i=="string"?parseInt(i,10):i).filter(i=>!Number.isNaN(i));o.push(`id IN (${s.map(()=>"?").join(", ")})`),r.push(...s);}e.name&&(o.push("name LIKE ?"),r.push(`%${e.name}%`)),e.type&&(o.push("type = ?"),r.push(e.type)),gt(o,r,e.agentId,e.scope??"agent_only"),o.length>0&&(n+=` WHERE ${o.join(" AND ")}`),n+=" ORDER BY id",e.limit&&(n+=" LIMIT ?",r.push(e.limit)),le.debug("queryNodes",{sql:n,params:r,filter:e});let c=this.db.prepare(n).all(...r);return le.debug("queryNodes result",{count:c.length}),c.map(s=>({id:s.id,name:s.name,type:s.type,properties:s.properties?JSON.parse(s.properties):void 0,createdAt:s.createdAt,updatedAt:s.updatedAt,ownerAgentId:s.owner_agent_id}))}async queryEdges(e={}){let n="SELECT e.id, e.source, e.target, e.relation, e.properties, e.createdAt FROM edges e",r=[],o=[];if(e.ids&&e.ids.length>0&&(o.push(`e.id IN (${e.ids.map(()=>"?").join(", ")})`),r.push(...e.ids)),e.source!==void 0&&(o.push("e.source = ?"),r.push(e.source)),e.target!==void 0&&(o.push("e.target = ?"),r.push(e.target)),e.sourceOrTarget&&e.sourceOrTarget.length>0){let f=e.sourceOrTarget.map(m=>typeof m=="string"?parseInt(m,10):m).filter(m=>!Number.isNaN(m));o.push(`(e.source IN (${f.map(()=>"?").join(", ")}) OR e.target IN (${f.map(()=>"?").join(", ")}))`),r.push(...f,...f);}e.relation&&(o.push("e.relation = ?"),r.push(e.relation)),o.length>0&&(n+=` WHERE ${o.join(" AND ")}`),n+=" ORDER BY e.id",e.limit&&(n+=" LIMIT ?",r.push(e.limit)),le.debug("queryEdges",{sql:n,params:r,filter:e});let c=this.db.prepare(n).all(...r);le.debug("queryEdges result",{count:c.length});let s=[...new Set(c.map(f=>f.target))],i=s.length>0?await this.queryNodes({ids:s,limit:s.length}):[],p=new Map(i.map(f=>[f.id,f]));return c.map(f=>{let m={id:f.id,source:f.source,target:f.target,relation:f.relation,properties:f.properties?JSON.parse(f.properties):void 0,createdAt:f.createdAt},u=p.get(f.target);return u&&(m.targetNode=u),m})}async queryNeighbors(e,n=1,r){let o=r?.agentId,c=r?.scope??"agent_only",s=new Set,i=[{id:e,level:0}],p=[],f=r?.maxEdgesPerNode??50;for(;i.length>0;){let m=i.shift();if(!m)break;if(s.has(m.id)||m.level>n)continue;s.add(m.id);let I=(await this.queryNodes({ids:[m.id],limit:1,agentId:o,scope:c}))[0];if(!I)continue;let v=await this.queryEdges({sourceOrTarget:[m.id],limit:f}),S=o?await ut(this,v,o,c):v;if(p.push({...I,edges:S}),m.level<n)for(let w of S){let h=w.source===m.id?w.target:w.source;s.has(h)||i.push({id:h,level:m.level+1});}}return p}};async function ut(t,e,n,r){if(e.length===0)return e;let o=new Set;for(let i of e)o.add(i.source),o.add(i.target);let c=await t.queryNodes({ids:Array.from(o),agentId:n,scope:r,limit:o.size}),s=new Set(c.map(i=>i.id));return e.filter(i=>s.has(i.source)&&s.has(i.target))}function gt(t,e,n,r){if(n)switch(r){case "agent_only":t.push("owner_agent_id = ?"),e.push(n);break;case "shared_only":t.push("owner_agent_id IS NULL");break;case "both":t.push("(owner_agent_id = ? OR owner_agent_id IS NULL)"),e.push(n);break}}var M=class extends Error{constructor(n,r,o){super(n);a(this,"code",r);a(this,"details",o);this.name="ServiceError";}};var ue=class extends M{constructor(){super("ctx.agentId is required for memory service (ADR 0055 per-agent isolation)","AGENT_ID_REQUIRED");}},re=class extends M{constructor(e,n){super(`Trust denied for operation "${e}": ${n}`,"TRUST_DENIED",{operation:e,reason:n});}},ne=class extends M{constructor(e,n){super(`Memory ${e} has ${n} references (force=false)`,"HAS_REFERENCES",{memoryId:e,referenceCount:n});}},oe=class extends M{constructor(e){super(`dryRun mode: ${e} memories matched but not deleted`,"DRY_RUN_NO_DELETE",{matchedCount:e});}},ae=class extends M{constructor(e,n){super(`Matched ${e} memories exceeds maxDelete=${n}`,"MAX_DELETE_EXCEEDED",{matched:e,maxDelete:n});}};function U(t){if(typeof t.agentId!="string"||t.agentId.trim().length===0)throw new ue}function G(t,e){if(t.remote!==false)throw new re(e,"requires trusted local caller (CLI / agent tool / MCP with remote=false)")}function ge(t,e,n){if(e!=="agent_only"&&t.remote!==false)throw new re(n,`scope="${e}" requires trusted local caller (cross-agent access denied)`)}function pe(t){if(!t.dbPath||t.dbPath.trim().length===0)throw new M("service ctx.dbPath is required (MemoryKnowledgeConfigWithModels.database.path)","INTERNAL")}var se=Log.create({service:"memory.service.recall"});async function qe(t,e$1){let n=Date.now();if(U(t),pe(t),!e$1.query||e$1.query.trim().length===0)throw new M("recall requires non-empty `query`","CONTENT_REQUIRED");let r=e$1.includeShared?"both":"agent_only";e$1.includeGraph&&ge(t,r,"recall"),se.debug("recall invoked",{agentId:t.agentId,query:e$1.query,category:e$1.category,maxResults:e$1.maxResults,includeGraph:e$1.includeGraph,scope:r});let o=e$1.maxResults??10,c=e$1.minScore??0,s=[],i=new e(t.dbPath);try{await i.initialize();let p=a$1.isInitialized()&&a$1.capabilities().embedding===!0,f=await ft(i,t.agentId,e$1.query,{category:e$1.category,minImportance:e$1.minImportance,fromTime:e$1.fromTime,toTime:e$1.toTime,limit:o,minScore:c,hasEmbedding:p}),m;if(e$1.includeGraph&&f.length>0)try{let I=new V(i.getDb()),v=e$1.depth??1,S=f.flatMap(y=>(y.nodes??[]).map(E=>E.id)).slice(0,5),w=new Set,h=new Map;for(let y of S){let E=await I.queryNeighbors(y,v,{agentId:t.agentId,scope:r,maxEdgesPerNode:10});for(let _ of E)w.add(_.id),h.set(_.id,_.edges??[]);}let b=w.size>0?i.query(`SELECT id, name, type FROM nodes WHERE id IN (${Array.from(w).map(()=>"?").join(",")})`,Array.from(w)):[],R=Array.from(h.values()).flat();m={nodes:b.map(y=>({id:y.id,name:y.name,type:y.type,createdAt:"",updatedAt:""})),edges:R};}catch(I){let v=I instanceof Error?I.message:String(I);se.warn("recall: KG neighbor query failed",{error:v}),s.push(`kg_neighbor_query_failed: ${v}`),m={nodes:[],edges:[]};}let u=Date.now()-n;return {hits:f,total:f.length,truncated:f.length>=o,durationMs:u,graph:m,...s.length>0?{warnings:s}:{}}}catch(p){throw p instanceof M?p:new M(`recall failed: ${p instanceof Error?p.message:String(p)}`,"INTERNAL",{cause:p instanceof Error?p.message:String(p)})}finally{i.close();}}async function ft(t,e,n,r){let o=["mf.agent_id = ?"],c=[e];r.category&&(o.push("mf.category = ?"),c.push(r.category)),r.minImportance!==void 0&&(o.push("mf.importance >= ?"),c.push(r.minImportance)),r.fromTime&&(o.push("mf.created_at >= ?"),c.push(r.fromTime)),r.toTime&&(o.push("mf.created_at <= ?"),c.push(r.toTime));let s=o.join(" AND "),i=null;if(r.hasEmbedding)try{i=await a$1.embedText(n);}catch(g){se.warn("recall: query embedding failed, falling back to FTS-only",{error:g instanceof Error?g.message:String(g)}),i=null;}let p=Math.max(r.limit*100,1e3),[f,m]=await Promise.all([i?yt(t,i,s,c,p):Promise.resolve([]),ht(t,n,s,c,r.limit)]),u=i?.7:0,I=i?.3:1,v=u+I,S=u/v,w=I/v,h=new Map;for(let g of f)h.set(g.id,g.score*S);for(let g of m)h.set(g.id,(h.get(g.id)??0)+g.score*w);let b=Array.from(h.entries()).sort((g,A)=>A[1]-g[1]).map(([g])=>g).slice(0,r.limit);if(b.length===0)return [];let R=b.map(()=>"?").join(","),y=t.query(`SELECT
|
|
2
|
+
mf.id,
|
|
3
|
+
mf.category,
|
|
4
|
+
mf.importance,
|
|
5
|
+
mf.agent_id as agentId,
|
|
6
|
+
SUBSTR(mf.content, 1, 200) as snippet,
|
|
7
|
+
mf.created_at as createdAt,
|
|
8
|
+
mf.source,
|
|
9
|
+
mf.file_path as filePath,
|
|
10
|
+
mf.node_ids as nodeIds
|
|
11
|
+
FROM memory_facts mf
|
|
12
|
+
WHERE mf.id IN (${R})`,b),E=Date.now();return y.map(g=>{let A=h.get(g.id)??0,O=(E-new Date(g.createdAt).getTime())/864e5,q=Math.exp(-0.05*O),j=(g.importance-1)/9,Q=.4*A+.3*q+.3*j;return {memoryId:g.id,category:g.category,importance:g.importance,agentId:g.agentId,snippet:g.snippet,score:Q,createdAt:g.createdAt,source:g.source,filePath:g.filePath??void 0,nodes:void 0}}).filter(g=>g.score>=r.minScore).sort((g,A)=>A.score-g.score)}function yt(t,e,n,r,o){try{return t.query(`SELECT mf.id, mv.embedding
|
|
13
|
+
FROM memory_facts mf
|
|
14
|
+
JOIN memory_vectors mv ON mf.id = mv.fact_id
|
|
15
|
+
WHERE ${n}
|
|
16
|
+
LIMIT ?`,[...r,o]).map(s=>{let i=new Float32Array(s.embedding.buffer,s.embedding.byteOffset,s.embedding.byteLength/4);return {id:s.id,score:bt(e,i)}}).sort((s,i)=>i.score-s.score)}catch(c){if(c instanceof M)throw c;return se.warn("vector search failed, falling back to FTS-only",{error:c instanceof Error?c.message:String(c)}),[]}}function ht(t,e,n,r,o){try{let c=t.query(`SELECT mf.id as id, bm25(memory_facts_fts) as score
|
|
17
|
+
FROM memory_facts_fts fts
|
|
18
|
+
JOIN memory_facts mf ON mf.id = fts.fact_id
|
|
19
|
+
WHERE ${n} AND memory_facts_fts MATCH ?
|
|
20
|
+
ORDER BY score DESC
|
|
21
|
+
LIMIT ?`,[...r,Et(e),o]);if(c.length===0)return [];let s=Math.max(...c.map(i=>Math.abs(i.score)),1);return c.map(i=>({id:i.id,score:1-Math.abs(i.score)/s})).filter(i=>i.score>=0)}catch(c){if(c instanceof M)throw c;return se.warn("FTS search failed, returning empty result",{err:c instanceof Error?c.message:String(c)}),[]}}function bt(t,e){if(t.length!==e.length||t.length===0)return 0;let n=0,r=0,o=0;for(let s=0;s<t.length;s++){let i=t[s]??0,p=e[s]??0;n+=i*p,r+=i*i,o+=p*p;}let c=Math.sqrt(r)*Math.sqrt(o);return c===0?0:Math.max(0,n/c)}function Et(t){return t.trim().split(/\s+/).filter(e=>e.length>0).map(e=>`"${e.replace(/"/g,'""')}"`).join(" ")}var $e=z.object({query:z.string().min(1).max(500),category:z.string().optional(),minImportance:z.number().min(1).max(10).optional(),fromTime:z.string().datetime().optional(),toTime:z.string().datetime().optional(),maxResults:z.number().int().min(1).max(100).optional().default(10),minScore:z.number().min(0).max(1).optional(),includeGraph:z.boolean().optional().default(false),depth:z.number().int().min(1).max(5).optional().default(1),includeShared:z.boolean().optional().default(false)});z.object({hits:z.array(z.unknown()),total:z.number(),truncated:z.boolean(),durationMs:z.number(),graph:z.object({nodes:z.array(z.unknown()),edges:z.array(z.unknown())}).optional()});var He=z.object({content:z.string().min(1).max(1e4),category:z.string().min(1),importance:z.number().int().min(1).max(10).optional().default(5),tags:z.array(z.string()).optional(),sessionId:z.string().optional(),msgId:z.string().optional(),parentMsgId:z.string().optional(),skipDedup:z.boolean().optional().default(false),extractGraph:z.boolean().optional().default(true)});z.object({fact:z.object({id:z.string(),agentId:z.string(),content:z.string(),category:z.string(),importance:z.number(),createdAt:z.string(),updatedAt:z.string()}),filePath:z.string(),deduplicated:z.boolean(),nodeIds:z.array(z.number()).optional()});var Ue=z.object({factId:z.string().optional(),category:z.string().optional(),fromTime:z.string().datetime().optional(),toTime:z.string().datetime().optional(),maxDelete:z.number().int().min(1).max(1e4).optional().default(1e3),dryRun:z.boolean().optional().default(false),force:z.boolean().optional().default(false)}).refine(t=>t.factId!==void 0&&t.factId.length>0||t.category!==void 0&&t.category.length>0||t.fromTime!==void 0||t.toTime!==void 0,{message:"one of `factId`, `category`, `fromTime`, or `toTime` is required"});z.object({deletedCount:z.number(),deletedIds:z.array(z.string()),dryRun:z.boolean(),truncatedCount:z.number()});var We=z.object({sessionId:z.string().min(1),lastN:z.number().int().min(1).max(500).optional().default(50),fromMessageId:z.string().optional(),writeToDisk:z.boolean().optional().default(true)});z.object({extractedCount:z.number(),factIds:z.array(z.string()),entities:z.array(z.object({id:z.number(),name:z.string(),type:z.string()})),relations:z.array(z.object({source:z.string(),target:z.string(),relation:z.string()})),messageRange:z.object({fromMessageId:z.string(),toMessageId:z.string()}),durationMs:z.number()});var je=z.object({windowDays:z.number().int().min(1).max(365).optional().default(30),dryRun:z.boolean().optional().default(false)});z.object({totalFacts:z.number(),dedupedCount:z.number(),compressedCount:z.number(),archivedCount:z.number(),skippedCount:z.number(),durationMs:z.number()});var Ge=z.object({query:z.string().min(1),type:z.string().optional(),depth:z.number().int().min(1).max(5).optional().default(2),maxNodes:z.number().int().min(1).max(500).optional().default(100),scope:z.enum(["agent_only","shared_only","both"]).optional().default("agent_only"),relation:z.string().optional()});z.object({root:z.unknown().nullable(),nodes:z.array(z.unknown()),edges:z.array(z.unknown()),truncated:z.boolean(),totalNodes:z.number(),totalEdges:z.number(),scope:z.enum(["agent_only","shared_only","both"]),durationMs:z.number()});var ze=z.object({}).optional();z.object({dbPath:z.string(),workspaceDir:z.string(),factsCount:z.number(),nodesCount:z.number(),edgesCount:z.number(),factsByCategory:z.record(z.string(),z.number()),ftsAvailable:z.boolean(),vectorEnabled:z.boolean(),kgScopeEnabled:z.boolean(),healthy:z.boolean(),meta:z.record(z.string(),z.string())});var Be=z.object({}).optional();z.object({healthy:z.boolean(),checks:z.array(z.object({name:z.string(),passed:z.boolean(),message:z.string(),details:z.record(z.string(),z.unknown()).optional()}))});var Qe=z.object({workspaceDir:z.string().optional(),dbPath:z.string().optional(),archiveDays:z.number().int().min(1).max(3650).optional().default(30),force:z.boolean().optional().default(false)});z.object({initialized:z.boolean(),dbPath:z.string(),workspaceDir:z.string(),tablesCreated:z.number(),migrationsApplied:z.number(),durationMs:z.number()});var Ke=z.object({windowDays:z.number().int().min(1).max(3650).optional(),dryRun:z.boolean().optional().default(false)});z.object({generatedCount:z.number(),skippedCount:z.number(),failedGenerateCount:z.number(),archivedCount:z.number(),archiveThreshold:z.string(),archivedRecords:z.array(z.object({source:z.string(),target:z.string(),firstCreatedAt:z.string(),firstFactId:z.string()})),windowDays:z.number(),dryRun:z.boolean(),durationMs:z.number()});var ie=Log.create({service:"memory.fact-file-sync"}),St=".easbot/memory/active";function ce(t,e){let n=e.replace(/\\/g,"/").replace(/\/+$/,""),r=t.category||"uncategorized",o=t.createdAt?new Date(t.createdAt).getTime():Date.now(),c=Number.isNaN(o)?new Date:new Date(o),s=c.getFullYear(),i=String(c.getMonth()+1).padStart(2,"0"),p=String(c.getDate()).padStart(2,"0"),f=`${s}-${i}-${p}`;return `${n}/${St}/${r}/${f}.md`}function Je(t){let e=t.tags&&t.tags.length>0?t.tags:[],n=t.importance??5,r=t.source??"session_self_write",o=t.createdAt?formatLocalISO(new Date(t.createdAt)):formatLocalISO(new Date),c=t.updatedAt?formatLocalISO(new Date(t.updatedAt)):o,s=["---",`id: ${t.id}`,`agent_id: ${t.agentId}`,`category: ${t.category}`,`importance: ${n}`,`created_at: ${o}`,`updated_at: ${c}`,`source: ${r}`,e.length>0?`tags: [${e.join(", ")}]`:"tags: []"];return t.sessionId&&s.push(`session_id: ${t.sessionId}`),t.msgId&&s.push(`msg_id: ${t.msgId}`),t.parentMsgId&&s.push(`parent_msg_id: ${t.parentMsgId}`),t.nodeIds&&t.nodeIds.length>0&&s.push(`node_ids: [${t.nodeIds.join(", ")}]`),s.push("---"),`${s.join(`
|
|
22
|
+
`)}
|
|
23
|
+
${t.content.trim()}`}function Y(t,e){let n=t.replace(/\\/g,"/"),r=e.replace(/\\/g,"/").replace(/\/+$/,"");return n.startsWith(`${r}/`)?n.slice(r.length+1):n}async function It(t,e){let n=ce(t,e),r=Y(n,e);try{let o=Je(t);await z$1.mkdir(de.dirname(n),{recursive:!0});let c="";try{c=await z$1.readFile(n,"utf-8");}catch(i){if(i.code!=="ENOENT")throw i}let s=c.length>0&&!c.endsWith(`
|
|
24
|
+
`)?`
|
|
25
|
+
`:"";return await z$1.writeFile(n,`${c}${s}${o}
|
|
26
|
+
`,"utf-8"),ie.debug("Fact file synced (append)",{id:t.id,relPath:r}),{ok:!0,absPath:n,relPath:r}}catch(o){let c=o instanceof Error?o.message:String(o);return ie.warn("Failed to write fact file (best-effort, non-blocking)",{id:t.id,absPath:n,error:c}),{ok:false,absPath:n,relPath:r,error:c}}}async function Mt(t,e){let n;t.filePath?n=`${e.replace(/\\/g,"/").replace(/\/+$/,"")}/${t.filePath.replace(/^\/+/,"")}`:n=ce({id:t.id,category:t.category,createdAt:t.createdAt,updatedAt:t.createdAt},e);let r=Y(n,e);try{return await z$1.unlink(n),ie.debug("Fact file deleted",{id:t.id,relPath:r}),{ok:!0,absPath:n,relPath:r}}catch(o){if(o.code==="ENOENT")return ie.debug("Fact file not found (already deleted)",{id:t.id,relPath:r}),{ok:true,absPath:n,relPath:r};let s=o instanceof Error?o.message:String(o);return ie.warn("Failed to delete fact file (best-effort, non-blocking)",{id:t.id,absPath:n,error:s}),{ok:false,absPath:n,relPath:r,error:s}}}var X={resolvePath:ce,renderMarkdown:Je,toRelPath:Y,write:It,delete:Mt};var ye=Log.create({service:"memory.service.remember"});async function Ve(t,e$1){if(U(t),pe(t),!e$1.content||e$1.content.trim().length===0)throw new M("remember requires non-empty `content`","CONTENT_REQUIRED");if(!e$1.category)throw new M("remember requires `category`","CATEGORY_REQUIRED");ye.debug("remember invoked",{agentId:t.agentId,category:e$1.category,importance:e$1.importance??5,contentLength:e$1.content.length,skipDedup:e$1.skipDedup,extractGraph:e$1.extractGraph??true});let n=new e(t.dbPath);try{await n.initialize();let r=new Date().toISOString(),o=Ot(),c=e$1.importance??5,s={entities:[],relations:[]},p=e$1.extractGraph!==!1&&a$1.isInitialized()&&a$1.capabilities().graphLlm?a$1.getGraphLlm():void 0;if(p)try{s=await Pt(p,e$1.content);}catch(y){ye.warn("LLM KG extraction failed (continuing without KG)",{agentId:t.agentId,error:y instanceof Error?y.message:String(y)});}let f=a$1.isInitialized()&&a$1.capabilities().embedding===!0,m=f?await Tt(n.getDb(),e$1.content):null,u=m?m.length:null,I=s.entities,v=s.relations,S=[],w=0;n.transaction(()=>{let y=new Map;for(let E of I){let _=n.query("SELECT id FROM nodes WHERE name = ? AND type = ? AND owner_agent_id = ? LIMIT 1",[E.name,E.type,t.agentId])[0];if(_){y.set(E.name,_.id);continue}let g=n.run("INSERT INTO nodes (name, type, properties, owner_agent_id, createdAt, updatedAt) VALUES (?, ?, ?, ?, ?, ?)",[E.name,E.type,JSON.stringify({source:"llm_extracted",...E.properties??{}}),t.agentId,r,r]);g.lastID>0&&y.set(E.name,g.lastID);}for(let E of v){let _=y.get(E.source),g=y.get(E.target);!_||!g||_===g||n.run("INSERT OR REPLACE INTO edges (source, target, relation, properties, createdAt) VALUES (?, ?, ?, ?, ?)",[_,g,E.relation,JSON.stringify({}),r]);}if(n.run(`INSERT INTO memory_facts
|
|
27
|
+
(id, agent_id, session_id, msg_id, parent_msg_id, content, category, importance,
|
|
28
|
+
source, tags, node_ids, file_path, created_at, updated_at)
|
|
29
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[o,t.agentId,e$1.sessionId??null,e$1.msgId??null,e$1.parentMsgId??null,e$1.content,e$1.category,c,"session_self_write",e$1.tags?JSON.stringify(e$1.tags):null,JSON.stringify(Array.from(y.values())),null,r,r]),m&&u){let E=Ye(m);n.run("INSERT OR REPLACE INTO memory_vectors (fact_id, embedding) VALUES (?, ?)",[o,E]),w=1,n.query("SELECT value FROM meta WHERE key = ?",["vectorDims"])[0]||n.run("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)",["vectorDims",String(u)]);}n.run("DELETE FROM memory_facts_fts WHERE fact_id = ?",[o]),n.run("INSERT INTO memory_facts_fts (fact_id, agent_id, content, tags) VALUES (?, ?, ?, ?)",[o,t.agentId,e$1.content,e$1.tags?e$1.tags.join(" "):""]),S.push(...Array.from(y.values()));}),ye.info("Memory stored",{id:o,category:e$1.category,agentId:t.agentId,nodeCount:S.length,vectorsWritten:w,vectorDims:u??0,embeddingMode:f?"enabled":"fts_only",entitiesExtracted:I.length,relationsExtracted:v.length});let h={id:o,agentId:t.agentId,sessionId:e$1.sessionId,msgId:e$1.msgId,parentMsgId:e$1.parentMsgId,content:e$1.content,category:e$1.category,importance:c,source:"session_self_write",tags:e$1.tags,nodeIds:S.length>0?S:void 0,filePath:void 0,createdAt:r,updatedAt:r},b="",R=await X.write(h,t.workspaceDir);if(R.ok){b=R.relPath,h.filePath=R.relPath;try{n.run("UPDATE memory_facts SET file_path = ? WHERE id = ?",[R.relPath,o]);}catch(y){ye.warn("Failed to update file_path column after sync",{id:o,error:y instanceof Error?y.message:String(y)});}}return {fact:h,filePath:b,deduplicated:!1,nodeIds:S,vectorsWritten:w,vectorDims:u??0,entitiesExtracted:I.length,relationsExtracted:v.length}}catch(r){throw r instanceof M?r:new M(`remember failed: ${r instanceof Error?r.message:String(r)}`,"INTERNAL",{cause:r instanceof Error?r.message:String(r)})}finally{n.close();}}function Ot(){let t=Date.now(),e=randomBytes(3).toString("hex");return `mem_${t}_${e}`}function Ye(t){return Buffer.from(t.buffer,t.byteOffset,t.byteLength)}function Nt(t){return createHash("sha256").update(t).digest("hex")}async function Tt(t,e){let n=Nt(e),r=t.prepare("SELECT embedding FROM embedding_cache WHERE content_hash = ?").get(n);if(r?.embedding)return new Float32Array(r.embedding.buffer,r.embedding.byteOffset,r.embedding.byteLength/4);let o=await a$1.embedText(e);if(!o||o.length===0)return null;let c=Ye(o);return t.prepare("INSERT OR REPLACE INTO embedding_cache (content_hash, embedding) VALUES (?, ?)").run(n,c),o}async function Pt(t,e){let n=await GraphProvider.generateGraph({chunks:[e],model:t,includeRules:false});return {entities:n.entities,relations:n.relations}}var be=Log.create({service:"memory.service.forget"}),At=1e3;function xt(t){let e=[];if(t.factId&&t.factId.trim().length>0&&e.push("factId"),t.category&&t.category.trim().length>0&&e.push("category"),(t.fromTime||t.toTime)&&e.push("timeRange"),e.length===0)throw new M("CONTENT_REQUIRED: forget requires one of: `factId`, `category`, or `fromTime`/`toTime`","CONTENT_REQUIRED");if(e.length>1)throw new M(`mutually exclusive: forget requires exactly one of factId/category/timeRange, got [${e.join(", ")}]`,"CONTENT_REQUIRED");return e[0]}function Lt(t,e,n){let r=[n];switch(t){case "factId":return {where:"agent_id = ? AND id = ?",args:[...r,e.factId]};case "category":return {where:"agent_id = ? AND category = ?",args:[...r,e.category]};case "timeRange":{let o=["agent_id = ?"];return e.fromTime&&(o.push("created_at >= ?"),r.push(e.fromTime)),e.toTime&&(o.push("created_at <= ?"),r.push(e.toTime)),{where:o.join(" AND "),args:r}}}}function Ft(t,e,n,r){return t.query(`SELECT id, node_ids FROM memory_facts WHERE ${e} LIMIT ?`,[...n,r+1]).map(c=>c.id)}function qt(t,e,n,r){if(n.length===0)return 0;let o=n.map(()=>"?").join(",");return t.query(`SELECT COUNT(*) as count FROM memory_facts WHERE agent_id = ? AND id != ? AND node_ids IS NOT NULL AND EXISTS (
|
|
30
|
+
SELECT 1 FROM json_each(node_ids) AS je WHERE je.value IN (${o})
|
|
31
|
+
)`,[r,e,...n])[0]?.count??0}function $t(t,e,n){let r,o,c="";return t.transaction(()=>{let s=t.query("SELECT node_ids, content, file_path, category, created_at FROM memory_facts WHERE id = ? AND agent_id = ?",[e,n])[0],i=[];if(s?.node_ids)try{i=JSON.parse(s.node_ids),Array.isArray(i)||(i=[]);}catch{i=[];}if(r=s?.file_path??void 0,o=s?.category,c=s?.created_at??"",t.run("DELETE FROM memory_facts_fts WHERE fact_id = ?",[e]),t.run("DELETE FROM memory_facts WHERE id = ? AND agent_id = ?",[e,n]),i.length>0){let p=i.map(()=>"?").join(",");t.run(`DELETE FROM nodes WHERE id IN (${p}) AND NOT EXISTS (
|
|
32
|
+
SELECT 1 FROM memory_facts WHERE node_ids IS NOT NULL AND EXISTS (
|
|
33
|
+
SELECT 1 FROM json_each(node_ids) AS je WHERE je.value = nodes.id
|
|
34
|
+
)
|
|
35
|
+
)`,i);}}),{filePath:r,category:o,createdAt:c}}async function Xe(t,e$1){U(t),G(t,"forget");let n=xt(e$1),r=e$1.maxDelete??At,o=e$1.dryRun??false,c=e$1.force??false;be.debug("forget invoked",{agentId:t.agentId,mode:n,maxDelete:r,dryRun:o,force:c});let s=new e(t.dbPath);try{await s.initialize();let{where:i,args:p}=Lt(n,e$1,t.agentId),f=Ft(s,i,p,r),m=f.length>r;if(m&&!c)throw new ae(f.length,r);let u=m?f.slice(0,r):f;if(o)throw new oe(u.length);let I=[],v=[];for(let S of u){if(!c){let R=s.query("SELECT node_ids FROM memory_facts WHERE id = ? AND agent_id = ?",[S,t.agentId])[0],y=R?.node_ids?(()=>{try{let _=JSON.parse(R.node_ids);if(Array.isArray(_))return _.filter(g=>typeof g=="number")}catch{}return []})():[],E=qt(s,S,y,t.agentId);if(E>0)throw new ne(S,E)}let{filePath:w,category:h,createdAt:b}=$t(s,S,t.agentId);w&&h&&v.push({id:S,filePath:w,category:h,createdAt:b}),I.push(S);}be.info("forget complete",{agentId:t.agentId,mode:n,deletedCount:I.length,force:c,dryRun:o});for(let{id:S,filePath:w,category:h,createdAt:b}of v)await X.delete({id:S,filePath:w,category:h,createdAt:b},t.workspaceDir).catch(R=>{be.warn("Fact file delete failed (best-effort)",{id:S,filePath:w,error:R instanceof Error?R.message:String(R)});});return {deletedCount:I.length,deletedIds:I,dryRun:o,truncatedCount:m?f.length-r:0}}catch(i){throw i instanceof M?i:new M(`forget failed: ${i instanceof Error?i.message:String(i)}`,"INTERNAL",{cause:i instanceof Error?i.message:String(i)})}finally{s.close();}}var Ee=Log.create({service:"memory.service.extract"}),Ut=50,we=500;async function Ze(t,e$1){if(U(t),!e$1.sessionId||e$1.sessionId.trim().length===0)throw new M("extract requires non-empty `sessionId`","SESSION_ID_REQUIRED");let n=e$1.lastN??Ut;if(n>we)throw new M(`extract lastN=${n} exceeds max=${we}`,"CONTENT_REQUIRED",{lastN:n,maxLastN:we});let r=e$1.sessionId,o=e$1.fromMessageId;Ee.debug("extract invoked",{agentId:t.agentId,sessionId:r,lastN:n,fromMessageId:o,writeToDisk:e$1.writeToDisk??true});let c=Date.now(),s=new e(t.dbPath);try{await s.initialize();let i=s.query(`SELECT id, content, category, importance, 1.0 as score, created_at, node_ids
|
|
36
|
+
FROM memory_facts
|
|
37
|
+
WHERE agent_id = ? AND session_id = ?
|
|
38
|
+
ORDER BY created_at ASC
|
|
39
|
+
LIMIT ?`,[t.agentId,r,n]),p=o?i.filter(S=>S.id>o):i,f=new Set;for(let S of p)if(S.node_ids)try{let w=JSON.parse(S.node_ids);if(Array.isArray(w))for(let h of w)typeof h=="number"&&h>0&&f.add(h);}catch(w){Ee.warn("extract: invalid node_ids JSON",{factId:S.id,error:w instanceof Error?w.message:String(w)});}let m=Array.from(f),u=[],I=[];if(m.length>0){let S=m.map(()=>"?").join(","),w=s.query(`SELECT id, name, type FROM nodes WHERE id IN (${S})`,m),h=new Map;for(let y of w)h.set(y.id,y.name);u=w.map(y=>({id:y.id,name:y.name,type:y.type}));let b=s.query(`SELECT source, target, relation FROM edges WHERE source IN (${S}) OR target IN (${S})`,[...m,...m]),R=new Set;I=[];for(let y of b){let E=h.get(y.source),_=h.get(y.target);if(!E||!_)continue;let g=`${E}\0${y.relation}\0${_}`;R.has(g)||(R.add(g),I.push({source:E,target:_,relation:y.relation}));}}let v=Date.now()-c;return Ee.info("extract complete",{agentId:t.agentId,sessionId:r,factCount:p.length,nodeCount:u.length,relationCount:I.length,durationMs:v}),{extractedCount:p.length,factIds:p.map(S=>S.id),entities:u,relations:I,messageRange:{fromMessageId:p[0]?.id??"",toMessageId:p[p.length-1]?.id??""},durationMs:v}}catch(i){throw i instanceof M?i:new M(`extract failed: ${i instanceof Error?i.message:String(i)}`,"INTERNAL",{cause:i instanceof Error?i.message:String(i)})}finally{s.close();}}var Ie=Log.create({service:"memory.service.consolidate"}),jt=30;async function Gt(t){let{createHash:e}=await import('crypto');return e("sha256").update(t).digest("hex")}async function et(t,e$1={}){let n=Date.now();U(t),G(t,"consolidate");let r=e$1.windowDays??jt,o=e$1.dryRun??false;Ie.debug("consolidate invoked",{agentId:t.agentId,windowDays:r,dryRun:o});let c=new e(t.dbPath);try{await c.initialize();let s=c.query("SELECT id, content, category, importance, created_at FROM memory_facts WHERE agent_id = ? ORDER BY created_at DESC",[t.agentId]),i=new Map;for(let h of s){let b=await Gt(h.content);i.has(b)||i.set(b,[]),i.get(b)?.push(h);}let p=0,f=[];for(let[,h]of i){if(h.length<=1)continue;let b=[...h].sort((E,_)=>E.importance!==_.importance?_.importance-E.importance:_.created_at.localeCompare(E.created_at)),R=b[0];if(!R)continue;let y=b.slice(1).map(E=>E.id);p+=y.length,f.push({keep:R,removeIds:y});}let m=new Date(Date.now()-r*24*60*60*1e3).toISOString(),u=c.query(`SELECT id, content, category, importance, created_at FROM memory_facts
|
|
40
|
+
WHERE agent_id = ? AND created_at < ?
|
|
41
|
+
ORDER BY created_at ASC`,[t.agentId,m]),I=0,v=0;if(o)I=0,v=p;else {let h=de.join(t.workspaceDir,"archive");await z$1.mkdir(h,{recursive:!0});for(let{removeIds:b}of f){if(b.length===0)continue;let R=b.map(()=>"?").join(",");c.transaction(()=>{for(let y of b)c.run("DELETE FROM memory_facts WHERE id = ? AND agent_id = ?",[y,t.agentId]);}),v+=b.length;}for(let b of u){let R=b.created_at.slice(0,7),y=de.join(h,R,b.category);await z$1.mkdir(y,{recursive:!0});let E=de.join(y,`${b.id}.md`);try{await z$1.writeFile(E,[`# ${b.id}`,"",`category: ${b.category}`,`importance: ${b.importance}`,`createdAt: ${b.created_at}`,"",b.content,""].join(`
|
|
42
|
+
`),"utf-8"),c.run("DELETE FROM memory_facts WHERE id = ? AND agent_id = ?",[b.id,t.agentId]),I++;}catch(_){Ie.warn("consolidate: archive write failed",{factId:b.id,error:_ instanceof Error?_.message:String(_)});}}}let S=s.length,w=0;return Ie.info("consolidate complete",{agentId:t.agentId,totalFacts:S,dedupedCount:p,compressedCount:w,archivedCount:I,skippedCount:v,dryRun:o,durationMs:Date.now()-n}),{totalFacts:S,dedupedCount:p,compressedCount:w,archivedCount:I,skippedCount:v,durationMs:Date.now()-n}}catch(s){throw s instanceof M?s:new M(`consolidate failed: ${s instanceof Error?s.message:String(s)}`,"INTERNAL",{cause:s instanceof Error?s.message:String(s)})}finally{c.close();}}var H=Log.create({service:"memory.service.sync"}),Qt=30,Kt=".easbot/memory/active",tt=".easbot/memory/archive";function Jt(t){return {id:t.id,agentId:t.agent_id,sessionId:t.session_id??void 0,msgId:t.msg_id??void 0,parentMsgId:t.parent_msg_id??void 0,content:t.content,category:t.category,importance:t.importance,source:t.source,tags:t.tags?JSON.parse(t.tags):void 0,nodeIds:t.node_ids?JSON.parse(t.node_ids):void 0,filePath:t.file_path??void 0,createdAt:t.created_at,updatedAt:t.updated_at}}async function Vt(t,e){let n=0,r=0,o=0,{where:c,params:s}=t.agentFilter(e.agentId),i=t.query(`SELECT id, agent_id, session_id, msg_id, parent_msg_id, content, category, importance,
|
|
43
|
+
source, tags, node_ids, file_path, created_at, updated_at
|
|
44
|
+
FROM memory_facts ${c}
|
|
45
|
+
ORDER BY created_at ASC`,s);for(let p of i){let f=Jt(p);if(p.file_path?.startsWith(`${tt}/`)){r++;continue}let m=ce(f,e.workspaceDir);try{await z$1.access(m),r++;continue}catch(I){let v=I;if(v.code!=="ENOENT"){H.warn("sync generate: fs.access failed (non-ENOENT)",{factId:f.id,absPath:m,error:v.message}),o++;continue}}let u=await X.write(f,e.workspaceDir);u.ok?n++:(o++,H.warn("sync generate: factFileSync.write failed",{factId:f.id,absPath:m,error:u.error}));}return H.debug("sync stage A complete",{agentId:e.agentId,generatedCount:n,skippedCount:r,failedGenerateCount:o}),{generatedCount:n,skippedCount:r,failedGenerateCount:o}}async function Yt(t,e,n,r){let o=n*24*60*60*1e3,c=Date.now(),s=formatLocalISO(new Date(c-o)),i=[],p=de.join(e.workspaceDir,Kt),f=await Xt(p);H.debug("sync stage B: scan active dir",{activeDir:p,fileCount:f.length,windowDays:n,threshold:s,dryRun:r});for(let m of f){let u=await Zt(m);if(!u){H.warn("sync stage B: skip unparseable file",{absPath:m});continue}let{firstCreatedAt:I,firstFactId:v}=u,S=new Date(I).getTime();if(Number.isNaN(S)){H.warn("sync stage B: skip invalid createdAt",{absPath:m,firstCreatedAt:I});continue}if(c-S<=o)continue;let w=er(m);if(!w){H.warn("sync stage B: cannot infer category from path",{absPath:m});continue}let h=I.slice(0,7),b=de.join(e.workspaceDir,tt,h,w),R=de.basename(m),y=de.join(b,R);if(r){i.push({source:m,target:y,firstCreatedAt:I,firstFactId:v});continue}try{await z$1.mkdir(b,{recursive:!0});try{await z$1.rename(m,y);}catch(g){let A=g;H.warn("sync stage B: fs.rename failed, falling back to copy+unlink",{absPath:m,targetPath:y,error:A.message}),await z$1.copyFile(m,y),await z$1.unlink(m);}let E=Y(m,e.workspaceDir),_=Y(y,e.workspaceDir);t.run(`UPDATE memory_facts SET file_path = ?
|
|
46
|
+
WHERE agent_id = ? AND file_path = ?`,[_,e.agentId??"",E]),i.push({source:m,target:y,firstCreatedAt:I,firstFactId:v});}catch(E){H.warn("sync stage B: archive failed",{absPath:m,targetPath:y,error:E instanceof Error?E.message:String(E)});}}return H.debug("sync stage B complete",{agentId:e.agentId,archivedCount:i.length,dryRun:r}),{archivedCount:i.length,archiveThreshold:s,archivedRecords:i}}async function Xt(t){let e=[];try{await rt(t,e);}catch(n){let r=n;if(r.code==="ENOENT")return e;throw H.warn("sync: listActiveMdFiles failed",{activeDir:t,error:r.message}),new M(`sync: listActiveMdFiles failed: ${r.message}`,"INTERNAL",{cause:r.message})}return e}async function rt(t,e){let n=await z$1.readdir(t,{withFileTypes:true});for(let r of n){let o=de.join(t,r.name);r.isDirectory()?await rt(o,e):r.isFile()&&r.name.endsWith(".md")&&e.push(o);}}async function Zt(t){let e;try{e=await z$1.readFile(t,"utf-8");}catch(s){if(s.code==="ENOENT")return null;throw s}if(!e.startsWith(`---
|
|
47
|
+
`))return null;let n=e.indexOf(`
|
|
48
|
+
---
|
|
49
|
+
`,4);if(n===-1)return null;let r=e.slice(4,n),o,c;for(let s of r.split(`
|
|
50
|
+
`)){let i=s.trim();if(i.startsWith("created_at:")?o=i.slice(11).trim().replace(/^["']|["']$/g,""):i.startsWith("id:")&&(c=i.slice(3).trim().replace(/^["']|["']$/g,"")),o&&c)break}return !o||!c?null:{firstCreatedAt:o,firstFactId:c}}function er(t){let e=t.replace(/\\/g,"/").split("/"),n=e.findIndex(c=>c==="active");if(n===-1)return null;let r=e.slice(n+1);return r.length!==2||!r[1].endsWith(".md")?null:r[0]??null}async function nt(t,e$1={}){let n=Date.now();U(t),G(t,"sync");let r=e$1.windowDays??t.config?.archiveDays??Qt,o=e$1.dryRun??false;H.info("sync invoked",{agentId:t.agentId,windowDays:r,dryRun:o,workspaceDir:t.workspaceDir});let c=new e(t.dbPath);try{await c.initialize();let s=await Vt(c,t),i=await Yt(c,t,r,o),p={generatedCount:s.generatedCount,skippedCount:s.skippedCount,failedGenerateCount:s.failedGenerateCount,archivedCount:i.archivedCount,archiveThreshold:i.archiveThreshold,archivedRecords:i.archivedRecords,windowDays:r,dryRun:o,durationMs:Date.now()-n};return H.info("sync complete",{agentId:t.agentId,...p}),p}catch(s){throw s instanceof M?s:new M(`sync failed: ${s instanceof Error?s.message:String(s)}`,"INTERNAL",{cause:s instanceof Error?s.message:String(s)})}finally{c.close();}}var ot=Log.create({service:"memory.service.graph-query"});async function at(t,e$1){let n=Date.now(),r=(t.agentId??"").trim()||"default",o=e$1.scope??"agent_only";if(!e$1.query||e$1.query.trim().length===0)throw new M("CONTENT_REQUIRED: graphQuery requires non-empty `query`","CONTENT_REQUIRED");ge(t,o,"graph_query");let c=e$1.depth??2,s=e$1.maxNodes??100,i=e$1.query,p=e$1.type,f=e$1.relation;ot.debug("graphQuery invoked",{agentId:r,query:i,type:p,depth:c,maxNodes:s,scope:o,remote:t.remote});let m=new e(t.dbPath);try{await m.initialize();let u=new V(m.getDb()),I=i.includes("*")||i.includes("%")?i:`%${i}%`,v=await u.queryNodes({name:I,...p?{type:p}:{},agentId:r,scope:o,limit:s}),w=(i.includes("*")||i.includes("%")?v:v.filter(g=>g.name.toLowerCase().includes(i.toLowerCase())))[0]??null;if(!w)return {root:null,nodes:[],edges:[],truncated:!1,totalNodes:0,totalEdges:0,scope:o,durationMs:Date.now()-n};let h=await u.queryNeighbors(w.id,c,{agentId:r,scope:o,maxEdgesPerNode:20}),b=new Map;b.set(w.id,w);for(let g of h)b.set(g.id,{id:g.id,name:g.name,type:g.type,createdAt:g.createdAt,updatedAt:g.updatedAt});let R=[];for(let g of h)if(g.edges)for(let A of g.edges)f&&A.relation!==f||R.push(A);for(let g of R){if(!b.has(g.source)){let A=await u.queryNodes({ids:[g.source],agentId:r,scope:o});A[0]&&b.set(A[0].id,A[0]);}if(!b.has(g.target)){let A=await u.queryNodes({ids:[g.target],agentId:r,scope:o});A[0]&&b.set(A[0].id,A[0]);}}let y=Array.from(b.values()),E=y.length>s,_=E?y.slice(0,s):y;return ot.info("graphQuery complete",{agentId:r,rootId:w.id,nodeCount:_.length,edgeCount:R.length,truncated:E,durationMs:Date.now()-n}),{root:w,nodes:_,edges:R,truncated:E,totalNodes:y.length,totalEdges:R.length,scope:o,durationMs:Date.now()-n}}catch(u){throw u instanceof M?u:new M(`graphQuery failed: ${u instanceof Error?u.message:String(u)}`,"INTERNAL",{cause:u instanceof Error?u.message:String(u)})}finally{m.close();}}var W=Log.create({service:"memory.service.init"});function Me(t){return de.join(t,".easbot","memory.json")}async function or(t){try{let{Config:e}=await import('@easbot/llm'),n=await e.get(),r=o=>typeof o=="string"&&o.length>0?o:void 0;return {embeddingModel:r(n.embedding_model),graphModel:r(n.graph_model)}}catch{return {}}}function ar(t,e={}){let n={version:1,schema_version:a$2,backend:"better-sqlite3",created_at:new Date().toISOString(),embedding_model:e.embeddingModel??null,graph_model:e.graphModel??null,entity_extraction_prompt:e.entityExtractionPrompt??null,relation_extraction_prompt:e.relationExtractionPrompt??null,archiveDays:e.archiveDays??30,shortTermMaxRounds:e.shortTermMaxRounds??20};writeFileSync(t,JSON.stringify(n,null,2),"utf-8");}async function st(t,e$1={}){let n=Date.now();G(t,"init");let r=e$1.workspaceDir??t.workspaceDir,o=e$1.dbPath??t.dbPath;if(!r||r.trim().length===0)throw new M("init requires non-empty `workspaceDir` (ctx.workspaceDir or params.workspaceDir)","CONTENT_REQUIRED");if(!o||o.trim().length===0)throw new M("init requires non-empty `dbPath` (ctx.dbPath or params.dbPath)","CONTENT_REQUIRED");let c=t.agentId?.trim()??"",s=e$1.force??false;W.debug("init invoked",{agentId:c,workspaceDir:r,dbPath:o,force:s});let i=Me(r);if(!s)try{if(await z$1.stat(i).then(()=>!0).catch(()=>!1))return W.info("init: idempotent skip (memory.json exists, no --force)",{workspaceDir:r,configPath:i}),{initialized:!1,dbPath:o,configPath:i,configCreated:!1,schemaVersion:a$2,workspaceDir:r,tablesCreated:0,migrationsApplied:0,durationMs:0}}catch{}try{await z$1.mkdir(de.dirname(o),{recursive:!0}),await z$1.mkdir(de.join(r,".easbot","memory","active"),{recursive:!0}),await z$1.mkdir(de.join(r,"archive"),{recursive:!0}),await z$1.mkdir(de.join(r,".easbot"),{recursive:!0});}catch(u){throw new M(`init: failed to create directories: ${u instanceof Error?u.message:String(u)}`,"INTERNAL",{cause:u instanceof Error?u.message:String(u)})}if(s)try{await z$1.rm(o,{force:!0});}catch(u){W.warn("init: force rm db failed (may not exist)",{dbPath:o,error:u instanceof Error?u.message:String(u)});}let p=await or(),f=false;try{!await z$1.stat(i).then(()=>!0).catch(()=>!1)||s?(ar(i,{embeddingModel:p.embeddingModel,graphModel:p.graphModel,archiveDays:t.config?.archiveDays,shortTermMaxRounds:t.config?.shortTermMaxRounds}),f=!0,W.info("init: memory.json written",{configPath:i,force:s,configCreated:f})):W.debug("init: memory.json already exists, skipping write",{configPath:i});}catch(u){W.warn("init: memory.json write failed (non-fatal)",{configPath:i,error:u instanceof Error?u.message:String(u)});}let m=new e(o);try{let u=await z$1.stat(o).then(()=>!0).catch(()=>!1);await m.initialize();let I=new Date().toISOString(),v=[["version","1.0.0"],["schemaVersion",String(a$2)],["createdAt",I],["defaultAgentId",c]];for(let[h,b]of v)try{m.run("INSERT OR IGNORE INTO meta (key, value) VALUES (?, ?)",[h,b]);}catch(R){W.warn("init: meta insert failed",{key:h,error:R instanceof Error?R.message:String(R)});}let S=0;try{S=m.prepare("SELECT COUNT(*) as n FROM sqlite_master WHERE type IN ('table', 'index', 'trigger', 'view')").get()?.n??0;}catch(h){W.warn("init: tablesCreated count failed",{error:h instanceof Error?h.message:String(h)});}let w=0;try{w=m.prepare("SELECT id FROM schema_migrations").all().length;}catch(h){W.warn("init: migrationsApplied count failed",{error:h instanceof Error?h.message:String(h)});}return W.info("init complete",{agentId:c,workspaceDir:r,dbPath:o,configPath:i,configCreated:f,schemaVersion:a$2,durationMs:Date.now()-n}),{initialized:!0,dbPath:o,configPath:i,configCreated:f,schemaVersion:a$2,workspaceDir:r,tablesCreated:S,migrationsApplied:w,durationMs:Date.now()-n}}catch(u){throw new M(`init failed: ${u instanceof Error?u.message:String(u)}`,"INTERNAL",{cause:u instanceof Error?u.message:String(u)})}finally{m.close();}}var Z=Log.create({service:"memory.service.status"}),dr=["user_preference","task_context","technical_fact","decision","relationship","reminder","error_pattern","workflow","exploration_finding","experience_summary","tool_usage","skill_creation","test","other"],mr={};async function it(t,e$1={},n=mr){let r=t.agentId&&t.agentId.trim().length>0?t.agentId:void 0;if(Z.debug("status invoked",{agentId:r??"<global>"}),!t.dbPath||t.dbPath.length===0)throw new M("`ctx.dbPath` is required","INTERNAL");let o={initialized:false,capabilities:{embedding:false,graphLlm:false}},c={},s={},i=0,p=0,f=0,m,u,I,v=false,S,w="uninitialized",h=false,b=false,R=false,y,E=dr.reduce((O,q)=>(O[q]=0,O),{}),_=new e(t.dbPath);try{await _.initialize(),i=_.query(r!==void 0?"SELECT COUNT(*) as c FROM memory_facts WHERE agent_id = ?":"SELECT COUNT(*) as c FROM memory_facts WHERE agent_id IS NOT NULL",r!==void 0?[r]:[])[0]?.c??0,p=_.query(r!==void 0?"SELECT COUNT(*) AS c FROM nodes WHERE owner_agent_id = ? OR owner_agent_id IS NULL":"SELECT COUNT(*) AS c FROM nodes",r!==void 0?[r]:[])[0]?.c??0,f=_.query("SELECT COUNT(*) as c FROM edges")[0]?.c??0;let Q=_.query(r!==void 0?"SELECT category, COUNT(*) as c FROM memory_facts WHERE agent_id = ? GROUP BY category":"SELECT category, COUNT(*) as c FROM memory_facts WHERE agent_id IS NOT NULL GROUP BY category",r!==void 0?[r]:[]);for(let D of Q){let F=D.category;F in E&&(E[F]=D.c);}c.facts=i,c.nodes=p,c.edges=f;try{b=_.query("SELECT name FROM sqlite_master WHERE type = ? AND name = ?",["table","memory_facts_fts"]).length>0;}catch(D){Z.debug("status: fts probe failed",{error:D instanceof Error?D.message:String(D)});}v=!!t.config?.embeddingLlm;try{h=_.query("SELECT name FROM pragma_table_info('nodes') WHERE name = ?",["owner_agent_id"]).length>0;}catch(D){Z.debug("status: kg scope probe failed",{error:D instanceof Error?D.message:String(D)});}R=_.healthCheck();try{let D=_.query("SELECT key, value FROM meta");for(let F of D)s[F.key]=F.value;}catch(D){Z.debug("status: meta read failed",{error:D instanceof Error?D.message:String(D)});}let d=s.schema_version,l=s.extraction_version,C=s.lastSyncAt??s.lastSync,T=s.embeddingDims;m=d&&Number.parseInt(d,10)||void 0,u=l&&Number.parseInt(l,10)||void 0,I=C,S=T&&Number.parseInt(T,10)||void 0,i>0&&(w="complete");try{y=_.query("SELECT value FROM meta WHERE key = ?",["backend"])[0]?.value??"better-sqlite3";}catch{y="better-sqlite3";}}catch(O){if(O instanceof M)throw O;Z.warn("status: db phase failed; returning partial result",{dbPath:t.dbPath,error:O instanceof Error?O.message:String(O)}),y="unknown",R=false;}finally{_.close();}if(!n.skipLlm&&a$1.isInitialized()){let q=a$1.capabilities();o.initialized=true,o.capabilities={embedding:q.embedding===true,graphLlm:q.graphLlm===true},o.embeddingModel=o.capabilities.embedding?"configured":void 0,o.graphModel=o.capabilities.graphLlm?"configured":void 0;}if(!n.skipEmbeddingProbe&&!n.skipLlm&&o.initialized&&o.capabilities.embedding)try{let O=a$1.getEmbeddingLlm?.();if(O){let q=await probeEmbeddingDims(O,{timeoutMs:5e3});if(typeof q=="number"){S=q,s.embeddingDims=String(q);try{let j=new e(t.dbPath);try{await j.initialize();let Q=j.getDb();syncMeta(Q,[["embeddingDims",String(q)]]);}finally{j.close();}}catch{}}}}catch{}let g;return R?w==="uninitialized"&&(g="Run `easbot memory remember <content>` to add the first fact."):g="Run `easbot memory init` to initialize the database.",R&&(w??"uninitialized")==="failed"&&(R=false),Z.info("status complete",{dbPath:t.dbPath,agentId:r??"<global>",factsCount:i,nodesCount:p,edgesCount:f,healthy:R}),{package:"memory",agentId:r,dbPath:t.dbPath,configPath:Me(t.workspaceDir),configExists:true,schemaVersion:m,extractionVersion:u,lastSyncAt:I,indexState:w,vectorEnabled:v,embeddingDims:S,llm:o,backend:y,counts:c,meta:s,recommendation:g,healthy:R,factsByCategory:E,kgScopeEnabled:h,factsCount:i,nodesCount:p,edgesCount:f,ftsAvailable:b}}var fr=Log.create({service:"memory.service.doctor"}),De=100*1024*1024,ct=100*1024*1024,yr={};function N(t,e,n,r,o){return {code:t.toUpperCase().replace(/[^A-Z0-9]+/g,"_"),severity:e,name:t,message:n,details:o,durationMs:r,passed:e!=="error"}}async function dt(t,e$1={},n=yr){if(fr.debug("doctor invoked",{agentId:t.agentId}),!t.dbPath||t.dbPath.length===0)throw new Error("`ctx.dbPath` is required");let r=[],o=[],c=Date.now(),s=null,i=false,p=Date.now();try{s=new e(t.dbPath),await s.initialize(),i=!0;let d=s.healthCheck(),l=N("database",d?"ok":"error",d?"database connected and writable":"database unhealthy",Date.now()-p,{dbPath:t.dbPath});r.push(l),o.push({name:l.name,passed:l.severity!=="error",message:l.message,details:l.details,severity:l.severity});}catch(d){let l=N("database","error",`database connection failed: ${d instanceof Error?d.message:String(d)}`,Date.now()-p,{dbPath:t.dbPath});r.push(l),o.push({name:l.name,passed:false,message:l.message,details:l.details,severity:"error"});}let f=Date.now();if(i&&s)try{let d=s.query("SELECT name FROM sqlite_master WHERE type = ? AND name = ?",["table","memory_facts_fts"]),l=d.length>0,C=N("fts",l?"ok":"warn",l?"FTS5 index available":"FTS5 index not found",Date.now()-f,l?{table:d[0]?.name}:void 0);r.push(C),o.push({name:C.name,passed:C.severity!=="error",message:C.message,details:C.details,severity:C.severity});}catch(d){let l=N("fts","error",`fts probe failed: ${d instanceof Error?d.message:String(d)}`,Date.now()-f);r.push(l),o.push({name:l.name,passed:false,message:l.message,details:l.details,severity:"error"});}else {let d=N("fts","info","skipped (db not initialized)",0);r.push(d),o.push({name:d.name,passed:true,message:d.message,severity:"info"});}let m=Date.now(),u=!!t.config?.embeddingLlm,I=N("vector","ok",u?"embedding model available":"no embedding model configured (FTS-only mode, recall still functional)",Date.now()-m,{mode:u?"hybrid":"fts_only",model:u?"configured":"missing"});r.push(I),o.push({name:I.name,passed:true,message:I.message,details:I.details,severity:"ok"});let v=Date.now();if(i&&s)try{let d=["memory_facts","nodes","edges","meta"],l=s.query("SELECT name FROM sqlite_master WHERE type = ?",["table"]),C=new Set(l.map(F=>F.name)),T=d.filter(F=>!C.has(F)),D=N("schema",T.length===0?"ok":"error",T.length===0?`schema complete (${d.length} tables)`:`missing tables: ${T.join(", ")}`,Date.now()-v,{required:d,existing:Array.from(C)});r.push(D),o.push({name:D.name,passed:D.severity!=="error",message:D.message,details:D.details,severity:D.severity});}catch(d){let l=N("schema","error",`schema probe failed: ${d instanceof Error?d.message:String(d)}`,Date.now()-v);r.push(l),o.push({name:l.name,passed:false,message:l.message,details:l.details,severity:"error"});}else {let d=N("schema","info","skipped (db not initialized)",0);r.push(d),o.push({name:d.name,passed:true,message:d.message,severity:"info"});}let S=Date.now();try{let d=`${t.dbPath}-wal`,l=`${t.dbPath}-shm`,C=0,T=0;try{C=(await z$1.stat(d)).size;}catch{C=0;}try{T=(await z$1.stat(l)).size;}catch{T=0;}let D=C+T,F=D<=ct,$=N("lock",F?"ok":"warn",F?`no lock contention (wal+shm ${(D/1024).toFixed(1)} KB)`:`WAL/SHM files unusually large (${(D/1024/1024).toFixed(1)} MB > ${(ct/1024/1024).toFixed(0)} MB threshold)`,Date.now()-S,{walBytes:C,shmBytes:T});r.push($),o.push({name:$.name,passed:$.severity!=="error",message:$.message,details:$.details,severity:$.severity});}catch(d){let l=N("lock","error",`lock probe failed: ${d instanceof Error?d.message:String(d)}`,Date.now()-S);r.push(l),o.push({name:l.name,passed:false,message:l.message,details:l.details,severity:"error"});}let w=Date.now();try{let d=de.dirname(t.dbPath),l=await z$1.statfs(d),C=typeof l.bsize=="bigint"?Number(l.bsize)*l.bavail:l.bsize*l.bavail,T=C>=De,D=N("disk_space",T?"ok":"error",T?`sufficient disk space (${(C/1024/1024).toFixed(1)} MB available)`:`low disk space (${(C/1024/1024).toFixed(1)} MB < ${(De/1024/1024).toFixed(0)} MB threshold)`,Date.now()-w,{availableBytes:C,threshold:De});r.push(D),o.push({name:D.name,passed:D.severity!=="error",message:D.message,details:D.details,severity:D.severity});}catch(d){let l=N("disk_space","error",`disk_space probe failed: ${d instanceof Error?d.message:String(d)}`,Date.now()-w);r.push(l),o.push({name:l.name,passed:false,message:l.message,details:l.details,severity:"error"});}let h=Date.now();if(i&&s)try{let d=s.agentFilter(t.agentId),l=s.query(`SELECT id, node_ids FROM memory_facts ${d.where} ${d.where?"AND":"WHERE"} node_ids IS NOT NULL`,d.params),C=[];for(let D of l)try{let F=JSON.parse(D.node_ids);if(!Array.isArray(F))continue;for(let $ of F){if(typeof $!="number")continue;if((s.query("SELECT COUNT(*) as c FROM nodes WHERE id = ?",[$])[0]?.c??0)===0){C.push(`${D.id}->${$}`);break}}}catch{}let T=N("orphan",C.length===0?"ok":"warn",C.length===0?"no orphan KG references":`${C.length} orphan references: ${C.slice(0,5).join(", ")}${C.length>5?", ...":""}`,Date.now()-h,{count:C.length});r.push(T),o.push({name:T.name,passed:T.severity!=="error",message:T.message,details:T.details,severity:T.severity});}catch(d){let l=N("orphan","warn",`orphan probe failed: ${d instanceof Error?d.message:String(d)}`,Date.now()-h);r.push(l),o.push({name:l.name,passed:false,message:l.message,details:l.details,severity:"warn"});}else {let d=N("orphan","info","skipped (db not initialized)",0);r.push(d),o.push({name:d.name,passed:true,message:d.message,severity:"info"});}let b=Date.now(),R={"better-sqlite3":false,"node:sqlite":false,"@tursodatabase/database":false};try{let d=createRequire(import.meta.url);try{d.resolve("better-sqlite3"),R["better-sqlite3"]=!0;}catch{}R["node:sqlite"]=typeof process.versions.sqlite=="string";try{d.resolve("@tursodatabase/database"),R["@tursodatabase/database"]=!0;}catch{}}catch{}let y=R["better-sqlite3"]||R["node:sqlite"],E=N("backend",y?"ok":"error",y?`SQLite backend available (better-sqlite3: ${R["better-sqlite3"]}, node:sqlite: ${R["node:sqlite"]})`:"no SQLite backend available (install better-sqlite3 or use Node 22.5+)",Date.now()-b,R);r.push(E),o.push({name:E.name,passed:E.severity!=="error",message:E.message,details:E.details,severity:E.severity});let _=Date.now();if(i&&s)try{let d=s.query("SELECT COUNT(*) as c FROM embedding_cache")[0],l=s.agentFilter(t.agentId),C=s.query(`SELECT COUNT(*) as c FROM memory_facts ${l.where}`,l.params)[0],T=d?.c??0,D=C?.c??0,F=Math.max(0,T-D),$=F>0,ee=N("embedding_cache_unused","info",$?`by design: ${F} embedding_cache rows remain after fact deletion (cache is global content-hash dedup; forget intentionally doesn't cascade clear cache to preserve same-content hit rate)`:"embedding_cache in sync with memory_facts (no unused rows)",Date.now()-_,{cacheCount:T,factsCount:D,unused:F,policy:"global_content_hash_dedup"});r.push(ee),o.push({name:ee.name,passed:!$,message:ee.message,details:ee.details,severity:"info"});}catch(d){let l=N("embedding_cache_unused","info",`embedding_cache_unused probe failed: ${d instanceof Error?d.message:String(d)}`,Date.now()-_);r.push(l),o.push({name:l.name,passed:true,message:l.message,severity:"info"});}else {let d=N("embedding_cache_unused","info","skipped (db not initialized)",0);r.push(d),o.push({name:d.name,passed:true,message:d.message,severity:"info"});}let g=Date.now(),A;if(i&&s)try{let d=s.query("SELECT value FROM meta WHERE key = ?",["embeddingDims"]);A=d[0]?.value&&Number.parseInt(d[0].value,10)||void 0;}catch{}let O;if(n.skipLlm||!a$1.isInitialized()||!a$1.capabilities().embedding)O=N(EMBEDDING_DIMS_CONSISTENCY_CHECK,"info","llm not initialized; probe skipped",Date.now()-g);else if(n.skipEmbeddingProbe)O=N(EMBEDDING_DIMS_CONSISTENCY_CHECK,"info","probe skipped (--skip-embedding-probe)",Date.now()-g);else try{let d=a$1.getEmbeddingLlm?.();if(!d)O=N(EMBEDDING_DIMS_CONSISTENCY_CHECK,"info","embedding llm not exposed; probe skipped",Date.now()-g);else {let l=await probeEmbeddingDims(d,{timeoutMs:5e3});typeof l!="number"?O=N(EMBEDDING_DIMS_CONSISTENCY_CHECK,"info","probe failed (network / model error)",Date.now()-g):A===void 0?O=N(EMBEDDING_DIMS_CONSISTENCY_CHECK,"info",`probe=${l}, meta missing \u2014 next status will sync`,Date.now()-g):l!==A?O=N(EMBEDDING_DIMS_CONSISTENCY_CHECK,"warn",`probe=${l}, meta=${A} \u2014 mismatch`,Date.now()-g,{probe:l,meta:A}):O=N(EMBEDDING_DIMS_CONSISTENCY_CHECK,"ok",`probe=${l}, meta=${A} \u2014 consistent`,Date.now()-g);}}catch(d){O=N(EMBEDDING_DIMS_CONSISTENCY_CHECK,"info",`probe threw: ${d instanceof Error?d.message:String(d)}`,Date.now()-g);}r.push({...O,details:O.details??void 0,passed:O.severity!=="error"}),o.push({name:O.name,passed:O.severity!=="error",message:O.message,details:O.details??void 0,severity:O.severity});let q;if(i&&s){let d=Date.now();try{let{issues:l,stats:C}=s.checkIntegrity();q=C;for(let T of l)r.push(N("integrity_stats",T.severity,T.message,0,{source:"database.checkIntegrity"}));}catch(l){r.push(N("integrity_stats","warn",`db integrity check failed: ${l instanceof Error?l.message:String(l)}`,Date.now()-d));}}let j=!r.some(d=>d.severity==="error");s&&s.close();let Q=Date.now()-c;return {healthy:j,checks:r,legacyChecks:o,durationMs:Q,integrityStats:q,backendAvailable:R}}var ve={name:"recall",scope:"read",schema:$e,annotations:{localOnly:false,requiresAgentId:true,defaultDescription:"Query memory via hybrid search (FTS + vector); returns ranked facts.",readOnlyHint:true,destructiveHint:false,idempotentHint:true},handler:async(t,e)=>{let n=t;if(!e.agentId?.trim())throw new Error("recall: agentId is required");return qe({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:e.remote??false,config:e.config,agentId:e.agentId},n)}};var Ce={name:"remember",scope:"write",schema:He,annotations:{localOnly:false,requiresAgentId:true,defaultDescription:"Persist a new self-memory fact; auto-extract entities into KG.",readOnlyHint:false,destructiveHint:false,idempotentHint:false},handler:async(t,e)=>{let n=t;if(!e.agentId?.trim())throw new Error("remember: agentId is required");return Ve({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:e.remote??false,config:e.config,agentId:e.agentId},n)}};var Oe={name:"forget",scope:"write",schema:Ue,annotations:{localOnly:false,requiresAgentId:true,defaultDescription:"Delete memory facts by id / category / time range; supports dryRun.",readOnlyHint:false,destructiveHint:true,idempotentHint:true},handler:async(t,e)=>{let n=t;if(!e.agentId?.trim())throw new Error("forget: agentId is required");return Xe({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:e.remote??false,config:e.config,agentId:e.agentId},n)}};var Ne={name:"extract",scope:"write",schema:We,annotations:{localOnly:false,requiresAgentId:true,defaultDescription:"Extract facts from a session (server-side pulls messages by lastN).",readOnlyHint:false,destructiveHint:false,idempotentHint:true},handler:async(t,e)=>{let n=t;if(!e.agentId?.trim())throw new Error("extract: agentId is required");return Ze({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:e.remote??false,config:e.config,agentId:e.agentId},n)}};var Te={name:"consolidate",scope:"admin",schema:je,annotations:{localOnly:true,requiresAgentId:true,defaultDescription:"Run consolidation pipeline: dedup \u2192 archive.",readOnlyHint:false,destructiveHint:true,idempotentHint:true},handler:async(t,e)=>{let n=t;if(!e.isTrustedLocal)throw new Error("consolidate: only trusted local process can invoke this op");if(!e.agentId?.trim())throw new Error("consolidate: agentId is required");return et({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:false,config:e.config,agentId:e.agentId},n)}};var Pe={name:"sync",scope:"admin",schema:Ke,annotations:{localOnly:true,requiresAgentId:true,defaultDescription:"Sync memory facts to .md files (idempotent skip on existing) and archive expired active files (default 30 days)",readOnlyHint:false,destructiveHint:true,idempotentHint:true},handler:async(t,e)=>{let n=t;if(!e.isTrustedLocal)throw new Error("sync: only trusted local process can invoke this op");if(!e.agentId?.trim())throw new Error("sync: agentId is required");return nt({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:false,config:e.config,agentId:e.agentId},n)}};var ke={name:"graph_query",scope:"read",schema:Ge,annotations:{localOnly:false,requiresAgentId:true,defaultDescription:"Query KG nodes / edges / neighbors with scope filtering.",readOnlyHint:true,destructiveHint:false,idempotentHint:true},handler:async(t,e)=>{let n=t,r=e.agentId?.trim()||"default";return at({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:e.remote??false,config:e.config,agentId:r},n)}};var Ae={name:"status",scope:"read",schema:ze,annotations:{localOnly:false,requiresAgentId:false,defaultDescription:"Memory system status (factsCount / nodesCount / edgesCount / fts / vector).",readOnlyHint:true,destructiveHint:false,idempotentHint:true},handler:async(t,e)=>{let n=t??{};return it({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:e.remote??false,config:e.config,agentId:e.agentId},n)}};var xe={name:"doctor",scope:"admin",schema:Be,annotations:{localOnly:true,requiresAgentId:false,defaultDescription:"Run 7 health checks (database / fts / vector / schema / lock / disk_space / orphan).",readOnlyHint:true,destructiveHint:false,idempotentHint:true},handler:async(t,e)=>{let n=t??{};if(!e.isTrustedLocal)throw new Error("doctor: only trusted local process can invoke this op");return dt({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:false,config:e.config,agentId:e.agentId},n)}};var Le={name:"init",scope:"admin",schema:Qe,annotations:{localOnly:true,requiresAgentId:false,defaultDescription:"Initialize memory workspace (dirs + db schema + meta).",readOnlyHint:false,destructiveHint:false,idempotentHint:true},handler:async(t,e)=>{if(!e.isTrustedLocal)throw new Error("init: only trusted local process can invoke this op");let n=t??{};return st({workspaceDir:n.workspaceDir??e.workspaceDir??"",rootDir:n.workspaceDir??e.workspaceDir??"",dbPath:n.dbPath??e.dbPath??"",locale:e.locale??"en-US",remote:false,config:e.config,agentId:e.agentId??""},n)}};var mt={[ve.name]:ve,[Ce.name]:Ce,[Oe.name]:Oe,[Ne.name]:Ne,[Te.name]:Te,[Pe.name]:Pe,[ke.name]:ke,[Ae.name]:Ae,[xe.name]:xe,[Le.name]:Le},hr=Object.values(mt);function br(t,e,n){if(t.annotations.localOnly&&!e.isTrustedLocal)throw new Error(`MEMORY:executeOp: op "${n}" is localOnly; non-trusted caller rejected`);if(t.annotations.requiresAgentId){let r=e.agentId?.trim()??"";if(r.length===0)throw new Error(`MEMORY:executeOp: op "${n}" requires agentId`);e.agentId=r;}}async function Sa(t,e,n){let r=mt[t];if(!r)throw new Error(`executeOp: unknown op "${t}"; available: ${hr.map(c=>c.name).join(", ")}`);return br(r,n,t),await r.handler(e,n)}function Rr(t){let e=t.dbPath??"";return {workspaceDir:t.workspaceDir??"",database:{path:e},embeddingLlm:a$1.getEmbeddingLlm(),graphLlm:a$1.getGraphLlm(),search:DEFAULT_SEARCH_CONFIG,indexer:{batchSize:20,ignorePatterns:[],incremental:true},archiveDays:30,shortTermMaxRounds:20}}function Ta(t,e,n={}){let r=j(e),o=Locale.resolveLocaleLang(n.locale);return {agentId:t,dbPath:r,workspaceDir:e,rootDir:e,config:Rr({dbPath:r,workspaceDir:e}),isTrustedLocal:true,locale:o,remote:false,...n}}export{V as a,qe as b,$e as c,He as d,Ue as e,We as f,je as g,Ge as h,Qe as i,Ke as j,Ve as k,Xe as l,Ze as m,et as n,nt as o,at as p,st as q,it as r,dt as s,mt as t,hr as u,Sa as v,Rr as w,Ta as x};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
'use strict';var g={languages:[{value:"zh-CN",name:"\u7B80\u4F53\u4E2D\u6587",example:"\u4F60\u597D\uFF0CEASBOT\uFF01",supported:true},{value:"en-US",name:"English (United States)",example:"Hello, EASBOT!",supported:true}]};var C=g.languages,b=C.filter(e=>e.supported).map(e=>e.value),a={defaultLocale:"zh-CN",locales:b},m={},l=(e,t)=>{let r=m[e]||{translation:{}};return m[e]={translation:{...r.translation,...t.translation}},m[e]},p=(e=a.defaultLocale)=>(m[e]||l(e,{translation:{}}),{locale:e,resources:m[e]||{translation:{}}});var v={translation:{"cli.cmd.init.description":"\u521D\u59CB\u5316\u8BB0\u5FC6 workspace\uFF08.easbot/memory.db\uFF09","cli.cmd.recall.description":"\u6DF7\u5408\u641C\u7D22\uFF08FTS + \u5411\u91CF\uFF09\u67E5\u8BE2\u8BB0\u5FC6","cli.cmd.remember.description":"\u5199\u5165\u4E00\u6761\u65B0\u8BB0\u5FC6\uFF08\u81EA\u5E26 dedup + \u77E5\u8BC6\u56FE\u8C31\u62BD\u53D6\uFF09","cli.cmd.forget.description":"\u5220\u9664\u8BB0\u5FC6\uFF08factId / category / \u65F6\u95F4\u7A97 / \u8BD5\u8FD0\u884C\uFF09","cli.cmd.sync.description":"\u540C\u6B65 facts \u5230 .md\uFF08\u5E42\u7B49\u8DF3\u8FC7\uFF09\u5E76\u5F52\u6863\u8FC7\u671F active \u6587\u4EF6\uFF08\u9ED8\u8BA4 30 \u5929\uFF09","cli.cmd.extract.description":"\u4ECE session \u62BD\u53D6 facts\uFF08sessionId + lastN\uFF09","cli.cmd.consolidate.description":"\u8FD0\u884C consolidation \u6D41\u6C34\u7EBF\uFF08extract \u2192 dedup \u2192 archive\uFF09","cli.cmd.graph.description":"\u77E5\u8BC6\u56FE\u8C31\u67E5\u8BE2\uFF08nodes / edges / neighbors\uFF0Cscope \u4E09\u6863\uFF09","cli.cmd.status.description":"\u663E\u793A\u8BB0\u5FC6\u72B6\u6001 / \u6570\u636E\u5E93\u7EDF\u8BA1 / \u5404\u7C7B\u522B\u8BA1\u6570","cli.cmd.doctor.description":"\u8FD0\u884C\u5065\u5EB7\u68C0\u67E5\uFF08\u540E\u7AEF / FTS / schema / \u9501\uFF09","cli.cmd.config.description":"\u67E5\u770B / \u6821\u9A8C\u8BB0\u5FC6\u914D\u7F6E\uFF08dry-read\uFF09","cli.cmd.mcp.description":"\u542F\u52A8 stdio MCP \u670D\u52A1\u5668\uFF08\u66B4\u9732 10 \u4E2A memory \u5DE5\u5177\uFF09","memory.recall.empty":"\uFF08\u65E0\u5339\u914D\u8BB0\u5FC6\uFF09","memory.recall.summary":"\u5171\u5339\u914D {{total}} \u6761\u8BB0\u5FC6\uFF1A","memory.recall.item":" - {{id}} [{{category}}/\u91CD\u8981\u6027={{importance}}/\u5206\u6570={{score}}] {{content}}","memory.forget.empty":"\uFF08\u672A\u547D\u4E2D\u53EF\u5220\u9664\u7684\u8BB0\u5F55\uFF09\uFF09","memory.forget.summary":"\u5220\u9664 {{deletedCount}} \u6761\u8BB0\u5FC6\uFF08dryRun={{dryRun}}\uFF09\uFF1A","memory.forget.item":" - {{id}}","memory.remember.summary":"\u8BB0\u5FC6\u5DF2\u5199\u5165\uFF1A","memory.remember.item":" - id={{id}} \u7C7B\u522B={{category}} \u91CD\u8981\u6027={{importance}}","memory.consolidate.summary":"consolidation \u5B8C\u6210\uFF1A","memory.consolidate.item":" - \u603B\u8BA1 {{totalFacts}} \u53BB\u91CD {{dedupedCount}} \u5F52\u6863 {{archivedCount}}","memory.sync.summary":"sync \u5B8C\u6210\uFF08windowDays={{windowDays}}, dryRun={{dryRun}}\uFF09\uFF1A","memory.sync.item":" - \u751F\u6210 {{generatedCount}} \u8DF3\u8FC7 {{skippedCount}} \u5931\u8D25 {{failedGenerateCount}} \u5F52\u6863 {{archivedCount}}\uFF08\u9608\u503C {{archiveThreshold}}\uFF09","memory.status.empty":"\uFF08\u6682\u65E0\u6570\u636E\uFF09","memory.status.summary":"\u8BB0\u5FC6\u72B6\u6001\uFF1A","memory.status.item":" - {{key}}: {{value}}","memory.doctor.empty":"\uFF08\u65E0\u68C0\u67E5\u9879\uFF09","memory.doctor.summary":"\u5065\u5EB7\u68C0\u67E5\uFF1A{{status}}","memory.doctor.item":" - {{name}}: {{message}}","memory.graph.empty":"\uFF08\u65E0\u8282\u70B9\u547D\u4E2D\uFF09","memory.graph.summary":"\u77E5\u8BC6\u56FE\u8C31\u67E5\u8BE2\uFF08\u5171 {{totalNodes}} \u8282\u70B9\uFF09\uFF1A","memory.graph.item":" - {{id}} {{name}} [{{type}}]","memory.extract.summary":"\u62BD\u53D6 {{extractedCount}} \u6761 facts\uFF1A","memory.extract.item":" - {{id}}","memory.init.summary":"\u521D\u59CB\u5316\u5B8C\u6210\uFF1A","memory.init.item":" - db={{dbPath}} \u8FC1\u79FB={{migrationsApplied}} \u8868={{tablesCreated}}"}},f=v;var L={translation:{"cli.cmd.init.description":"Initialize memory workspace (.easbot/memory.db)","cli.cmd.recall.description":"Hybrid search (FTS + vector) over memory facts","cli.cmd.remember.description":"Persist a new memory fact (with dedup + KG extraction)","cli.cmd.forget.description":"Delete memory facts (factId / category / timeRange / dryRun)","cli.cmd.sync.description":"Sync facts to .md (idempotent skip) and archive expired active files (default 30 days)","cli.cmd.extract.description":"Extract facts from a session (sessionId + lastN)","cli.cmd.consolidate.description":"Run consolidation pipeline (extract \u2192 dedup \u2192 archive)","cli.cmd.graph.description":"KG query (nodes / edges / neighbors with scope \u4E09\u6863)","cli.cmd.status.description":"Show memory state / db stats / facts by category","cli.cmd.doctor.description":"Run health checks (backend, FTS, schema, lock)","cli.cmd.config.description":"Show / validate memory configuration (dry-read)","cli.cmd.mcp.description":"Start stdio MCP server (exposes 10 memory tools)","memory.recall.empty":"(no matching facts)","memory.recall.summary":"Found {{total}} fact(s):","memory.recall.item":" - {{id}} [{{category}}/imp={{importance}}/score={{score}}] {{content}}","memory.forget.empty":"(no records to delete)","memory.forget.summary":"Deleted {{deletedCount}} fact(s) (dryRun={{dryRun}}):","memory.forget.item":" - {{id}}","memory.remember.summary":"Memory persisted:","memory.remember.item":" - id={{id}} category={{category}} importance={{importance}}","memory.consolidate.summary":"Consolidation complete:","memory.consolidate.item":" - total {{totalFacts}} deduped {{dedupedCount}} archived {{archivedCount}}","memory.sync.summary":"Sync complete (windowDays={{windowDays}}, dryRun={{dryRun}}):","memory.sync.item":" - generated {{generatedCount}} skipped {{skippedCount}} failed {{failedGenerateCount}} archived {{archivedCount}} (threshold {{archiveThreshold}})","memory.status.empty":"(no data)","memory.status.summary":"Memory status:","memory.status.item":" - {{key}}: {{value}}","memory.doctor.empty":"(no checks)","memory.doctor.summary":"Health check: {{status}}","memory.doctor.item":" - {{name}}: {{message}}","memory.graph.empty":"(no nodes matched)","memory.graph.summary":"KG query ({{totalNodes}} node(s)):","memory.graph.item":" - {{id}} {{name}} [{{type}}]","memory.extract.summary":"Extracted {{extractedCount}} fact(s):","memory.extract.item":" - {{id}}","memory.init.summary":"Initialization complete:","memory.init.item":" - db={{dbPath}} migrations={{migrationsApplied}} tables={{tablesCreated}}"}},h=L;var S=()=>{p("zh-CN"),p("en-US"),l("zh-CN",f),l("en-US",h);};S();var u=new Map;var y=new Map;var w=e=>{if(y.has(e))return y.get(e);let t=/{{\s*(\w+)\s*}}/g,r=[],o;for(;(o=t.exec(e))!==null;){let n=o[1];n&&!r.includes(n)&&r.push(n);}let i=new RegExp("{{\\s*("+r.join("|")+")\\s*}}","g"),s={keys:r,regex:i};return y.set(e,s),s},x=(e,t)=>{if(!e||typeof e!="string")return "";if(!t||Object.keys(t).length===0)return e;let{regex:r,keys:o}=w(e);return o.length===0||!o.some(s=>s in t)?e:e.replace(r,(s,n)=>{let c=t[n];return c==null?"":String(c)})},k=e=>{if(e&&a.locales.includes(e))return e;let t=process.env.EASBOT_LANG?.trim()||process.env.LANG?.trim();if(t){let r=t.replace(/_/g,"-");if(a.locales.includes(r))return r;let o=r.split("-")[0];if(o==="zh")return "zh-CN";if(o==="en")return "en-US"}return a.defaultLocale},R=e=>{if(!u.has(e)){let{resources:t}=p(e);u.set(e,t);}return u.get(e)},I=(e,t={})=>{let r=k(t.locale),i=R(r)?.translation[e];if(i&&typeof i=="string"){let s=x(i,t.vars);return s!=null?String(s):String(e)}if(r!==a.defaultLocale){let n=R(a.defaultLocale)?.translation[e];if(n&&typeof n=="string"){let c=x(n,t.vars);return c!=null?String(c):String(e)}}return String(t.fallback??e)},P=I;exports.a=P;
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
'use strict';var chunkEGWJG65Q_cjs=require('./chunk-EGWJG65Q.cjs'),chunkCPRDIUQ4_cjs=require('./chunk-CPRDIUQ4.cjs'),chunkJ5XF2W4Z_cjs=require('./chunk-J5XF2W4Z.cjs'),chunkNVGACA7W_cjs=require('./chunk-NVGACA7W.cjs'),utils=require('@easbot/utils'),zod=require('zod'),crypto=require('crypto'),llm=require('@easbot/llm'),G=require('fs/promises'),ce=require('path'),fs=require('fs'),module$1=require('module'),types=require('@easbot/types');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var G__default=/*#__PURE__*/_interopDefault(G);var ce__default=/*#__PURE__*/_interopDefault(ce);var me=utils.Log.create({service:"memory.graph-store"}),J=class{constructor(e){chunkNVGACA7W_cjs.a(this,"db");this.db=e;}async upsertNode(e,n,r,o){let c=Date.now(),s=JSON.stringify(r??{}),i=this.db.prepare("SELECT id FROM nodes WHERE name = ? AND type = ? LIMIT 1").get(e,n);if(i)return this.db.prepare("UPDATE nodes SET properties = ?, updatedAt = ? WHERE id = ?").run(s,c,i.id),i.id;let p=this.db.prepare("INSERT INTO nodes (name, type, properties, owner_agent_id, createdAt, updatedAt) VALUES (?, ?, ?, ?, ?, ?)").run(e,n,s,o??null,c,c);return Number(p.lastInsertRowid)}async deleteNode(e){this.db.prepare("DELETE FROM nodes WHERE id = ?").run(e);}async upsertEdge(e,n,r,o){let c=this.db.prepare("INSERT OR REPLACE INTO edges (source, target, relation, properties, createdAt) VALUES (?, ?, ?, ?, ?)").run(e,n,r,JSON.stringify(o??{}),Date.now());return Number(c.lastInsertRowid)}async queryNodes(e={}){let n="SELECT id, name, type, properties, owner_agent_id, createdAt, updatedAt FROM nodes",r=[],o=[];if(e.ids&&e.ids.length>0){let s=e.ids.map(i=>typeof i=="string"?parseInt(i,10):i).filter(i=>!Number.isNaN(i));o.push(`id IN (${s.map(()=>"?").join(", ")})`),r.push(...s);}e.name&&(o.push("name LIKE ?"),r.push(`%${e.name}%`)),e.type&&(o.push("type = ?"),r.push(e.type)),ut(o,r,e.agentId,e.scope??"agent_only"),o.length>0&&(n+=` WHERE ${o.join(" AND ")}`),n+=" ORDER BY id",e.limit&&(n+=" LIMIT ?",r.push(e.limit)),me.debug("queryNodes",{sql:n,params:r,filter:e});let c=this.db.prepare(n).all(...r);return me.debug("queryNodes result",{count:c.length}),c.map(s=>({id:s.id,name:s.name,type:s.type,properties:s.properties?JSON.parse(s.properties):void 0,createdAt:s.createdAt,updatedAt:s.updatedAt,ownerAgentId:s.owner_agent_id}))}async queryEdges(e={}){let n="SELECT e.id, e.source, e.target, e.relation, e.properties, e.createdAt FROM edges e",r=[],o=[];if(e.ids&&e.ids.length>0&&(o.push(`e.id IN (${e.ids.map(()=>"?").join(", ")})`),r.push(...e.ids)),e.source!==void 0&&(o.push("e.source = ?"),r.push(e.source)),e.target!==void 0&&(o.push("e.target = ?"),r.push(e.target)),e.sourceOrTarget&&e.sourceOrTarget.length>0){let f=e.sourceOrTarget.map(m=>typeof m=="string"?parseInt(m,10):m).filter(m=>!Number.isNaN(m));o.push(`(e.source IN (${f.map(()=>"?").join(", ")}) OR e.target IN (${f.map(()=>"?").join(", ")}))`),r.push(...f,...f);}e.relation&&(o.push("e.relation = ?"),r.push(e.relation)),o.length>0&&(n+=` WHERE ${o.join(" AND ")}`),n+=" ORDER BY e.id",e.limit&&(n+=" LIMIT ?",r.push(e.limit)),me.debug("queryEdges",{sql:n,params:r,filter:e});let c=this.db.prepare(n).all(...r);me.debug("queryEdges result",{count:c.length});let s=[...new Set(c.map(f=>f.target))],i=s.length>0?await this.queryNodes({ids:s,limit:s.length}):[],p=new Map(i.map(f=>[f.id,f]));return c.map(f=>{let m={id:f.id,source:f.source,target:f.target,relation:f.relation,properties:f.properties?JSON.parse(f.properties):void 0,createdAt:f.createdAt},u=p.get(f.target);return u&&(m.targetNode=u),m})}async queryNeighbors(e,n=1,r){let o=r?.agentId,c=r?.scope??"agent_only",s=new Set,i=[{id:e,level:0}],p=[],f=r?.maxEdgesPerNode??50;for(;i.length>0;){let m=i.shift();if(!m)break;if(s.has(m.id)||m.level>n)continue;s.add(m.id);let I=(await this.queryNodes({ids:[m.id],limit:1,agentId:o,scope:c}))[0];if(!I)continue;let v=await this.queryEdges({sourceOrTarget:[m.id],limit:f}),S=o?await lt(this,v,o,c):v;if(p.push({...I,edges:S}),m.level<n)for(let w of S){let h=w.source===m.id?w.target:w.source;s.has(h)||i.push({id:h,level:m.level+1});}}return p}};async function lt(t,e,n,r){if(e.length===0)return e;let o=new Set;for(let i of e)o.add(i.source),o.add(i.target);let c=await t.queryNodes({ids:Array.from(o),agentId:n,scope:r,limit:o.size}),s=new Set(c.map(i=>i.id));return e.filter(i=>s.has(i.source)&&s.has(i.target))}function ut(t,e,n,r){if(n)switch(r){case "agent_only":t.push("owner_agent_id = ?"),e.push(n);break;case "shared_only":t.push("owner_agent_id IS NULL");break;case "both":t.push("(owner_agent_id = ? OR owner_agent_id IS NULL)"),e.push(n);break}}var M=class extends Error{constructor(n,r,o){super(n);chunkNVGACA7W_cjs.a(this,"code",r);chunkNVGACA7W_cjs.a(this,"details",o);this.name="ServiceError";}};var le=class extends M{constructor(){super("ctx.agentId is required for memory service (ADR 0055 per-agent isolation)","AGENT_ID_REQUIRED");}},te=class extends M{constructor(e,n){super(`Trust denied for operation "${e}": ${n}`,"TRUST_DENIED",{operation:e,reason:n});}},re=class extends M{constructor(e,n){super(`Memory ${e} has ${n} references (force=false)`,"HAS_REFERENCES",{memoryId:e,referenceCount:n});}},ne=class extends M{constructor(e){super(`dryRun mode: ${e} memories matched but not deleted`,"DRY_RUN_NO_DELETE",{matchedCount:e});}},oe=class extends M{constructor(e,n){super(`Matched ${e} memories exceeds maxDelete=${n}`,"MAX_DELETE_EXCEEDED",{matched:e,maxDelete:n});}};function H(t){if(typeof t.agentId!="string"||t.agentId.trim().length===0)throw new le}function j(t,e){if(t.remote!==false)throw new te(e,"requires trusted local caller (CLI / agent tool / MCP with remote=false)")}function ue(t,e,n){if(e!=="agent_only"&&t.remote!==false)throw new te(n,`scope="${e}" requires trusted local caller (cross-agent access denied)`)}function ge(t){if(!t.dbPath||t.dbPath.trim().length===0)throw new M("service ctx.dbPath is required (MemoryKnowledgeConfigWithModels.database.path)","INTERNAL")}var ae=utils.Log.create({service:"memory.service.recall"});async function Fe(t,e){let n=Date.now();if(H(t),ge(t),!e.query||e.query.trim().length===0)throw new M("recall requires non-empty `query`","CONTENT_REQUIRED");let r=e.includeShared?"both":"agent_only";e.includeGraph&&ue(t,r,"recall"),ae.debug("recall invoked",{agentId:t.agentId,query:e.query,category:e.category,maxResults:e.maxResults,includeGraph:e.includeGraph,scope:r});let o=e.maxResults??10,c=e.minScore??0,s=[],i=new chunkEGWJG65Q_cjs.e(t.dbPath);try{await i.initialize();let p=chunkJ5XF2W4Z_cjs.a.isInitialized()&&chunkJ5XF2W4Z_cjs.a.capabilities().embedding===!0,f=await pt(i,t.agentId,e.query,{category:e.category,minImportance:e.minImportance,fromTime:e.fromTime,toTime:e.toTime,limit:o,minScore:c,hasEmbedding:p}),m;if(e.includeGraph&&f.length>0)try{let I=new J(i.getDb()),v=e.depth??1,S=f.flatMap(y=>(y.nodes??[]).map(E=>E.id)).slice(0,5),w=new Set,h=new Map;for(let y of S){let E=await I.queryNeighbors(y,v,{agentId:t.agentId,scope:r,maxEdgesPerNode:10});for(let _ of E)w.add(_.id),h.set(_.id,_.edges??[]);}let b=w.size>0?i.query(`SELECT id, name, type FROM nodes WHERE id IN (${Array.from(w).map(()=>"?").join(",")})`,Array.from(w)):[],R=Array.from(h.values()).flat();m={nodes:b.map(y=>({id:y.id,name:y.name,type:y.type,createdAt:"",updatedAt:""})),edges:R};}catch(I){let v=I instanceof Error?I.message:String(I);ae.warn("recall: KG neighbor query failed",{error:v}),s.push(`kg_neighbor_query_failed: ${v}`),m={nodes:[],edges:[]};}let u=Date.now()-n;return {hits:f,total:f.length,truncated:f.length>=o,durationMs:u,graph:m,...s.length>0?{warnings:s}:{}}}catch(p){throw p instanceof M?p:new M(`recall failed: ${p instanceof Error?p.message:String(p)}`,"INTERNAL",{cause:p instanceof Error?p.message:String(p)})}finally{i.close();}}async function pt(t,e,n,r){let o=["mf.agent_id = ?"],c=[e];r.category&&(o.push("mf.category = ?"),c.push(r.category)),r.minImportance!==void 0&&(o.push("mf.importance >= ?"),c.push(r.minImportance)),r.fromTime&&(o.push("mf.created_at >= ?"),c.push(r.fromTime)),r.toTime&&(o.push("mf.created_at <= ?"),c.push(r.toTime));let s=o.join(" AND "),i=null;if(r.hasEmbedding)try{i=await chunkJ5XF2W4Z_cjs.a.embedText(n);}catch(g){ae.warn("recall: query embedding failed, falling back to FTS-only",{error:g instanceof Error?g.message:String(g)}),i=null;}let p=Math.max(r.limit*100,1e3),[f,m]=await Promise.all([i?ft(t,i,s,c,p):Promise.resolve([]),yt(t,n,s,c,r.limit)]),u=i?.7:0,I=i?.3:1,v=u+I,S=u/v,w=I/v,h=new Map;for(let g of f)h.set(g.id,g.score*S);for(let g of m)h.set(g.id,(h.get(g.id)??0)+g.score*w);let b=Array.from(h.entries()).sort((g,k)=>k[1]-g[1]).map(([g])=>g).slice(0,r.limit);if(b.length===0)return [];let R=b.map(()=>"?").join(","),y=t.query(`SELECT
|
|
2
|
+
mf.id,
|
|
3
|
+
mf.category,
|
|
4
|
+
mf.importance,
|
|
5
|
+
mf.agent_id as agentId,
|
|
6
|
+
SUBSTR(mf.content, 1, 200) as snippet,
|
|
7
|
+
mf.created_at as createdAt,
|
|
8
|
+
mf.source,
|
|
9
|
+
mf.file_path as filePath,
|
|
10
|
+
mf.node_ids as nodeIds
|
|
11
|
+
FROM memory_facts mf
|
|
12
|
+
WHERE mf.id IN (${R})`,b),E=Date.now();return y.map(g=>{let k=h.get(g.id)??0,O=(E-new Date(g.createdAt).getTime())/864e5,F=Math.exp(-0.05*O),W=(g.importance-1)/9,B=.4*k+.3*F+.3*W;return {memoryId:g.id,category:g.category,importance:g.importance,agentId:g.agentId,snippet:g.snippet,score:B,createdAt:g.createdAt,source:g.source,filePath:g.filePath??void 0,nodes:void 0}}).filter(g=>g.score>=r.minScore).sort((g,k)=>k.score-g.score)}function ft(t,e,n,r,o){try{return t.query(`SELECT mf.id, mv.embedding
|
|
13
|
+
FROM memory_facts mf
|
|
14
|
+
JOIN memory_vectors mv ON mf.id = mv.fact_id
|
|
15
|
+
WHERE ${n}
|
|
16
|
+
LIMIT ?`,[...r,o]).map(s=>{let i=new Float32Array(s.embedding.buffer,s.embedding.byteOffset,s.embedding.byteLength/4);return {id:s.id,score:ht(e,i)}}).sort((s,i)=>i.score-s.score)}catch(c){if(c instanceof M)throw c;return ae.warn("vector search failed, falling back to FTS-only",{error:c instanceof Error?c.message:String(c)}),[]}}function yt(t,e,n,r,o){try{let c=t.query(`SELECT mf.id as id, bm25(memory_facts_fts) as score
|
|
17
|
+
FROM memory_facts_fts fts
|
|
18
|
+
JOIN memory_facts mf ON mf.id = fts.fact_id
|
|
19
|
+
WHERE ${n} AND memory_facts_fts MATCH ?
|
|
20
|
+
ORDER BY score DESC
|
|
21
|
+
LIMIT ?`,[...r,bt(e),o]);if(c.length===0)return [];let s=Math.max(...c.map(i=>Math.abs(i.score)),1);return c.map(i=>({id:i.id,score:1-Math.abs(i.score)/s})).filter(i=>i.score>=0)}catch(c){if(c instanceof M)throw c;return ae.warn("FTS search failed, returning empty result",{err:c instanceof Error?c.message:String(c)}),[]}}function ht(t,e){if(t.length!==e.length||t.length===0)return 0;let n=0,r=0,o=0;for(let s=0;s<t.length;s++){let i=t[s]??0,p=e[s]??0;n+=i*p,r+=i*i,o+=p*p;}let c=Math.sqrt(r)*Math.sqrt(o);return c===0?0:Math.max(0,n/c)}function bt(t){return t.trim().split(/\s+/).filter(e=>e.length>0).map(e=>`"${e.replace(/"/g,'""')}"`).join(" ")}var qe=zod.z.object({query:zod.z.string().min(1).max(500),category:zod.z.string().optional(),minImportance:zod.z.number().min(1).max(10).optional(),fromTime:zod.z.string().datetime().optional(),toTime:zod.z.string().datetime().optional(),maxResults:zod.z.number().int().min(1).max(100).optional().default(10),minScore:zod.z.number().min(0).max(1).optional(),includeGraph:zod.z.boolean().optional().default(false),depth:zod.z.number().int().min(1).max(5).optional().default(1),includeShared:zod.z.boolean().optional().default(false)});zod.z.object({hits:zod.z.array(zod.z.unknown()),total:zod.z.number(),truncated:zod.z.boolean(),durationMs:zod.z.number(),graph:zod.z.object({nodes:zod.z.array(zod.z.unknown()),edges:zod.z.array(zod.z.unknown())}).optional()});var $e=zod.z.object({content:zod.z.string().min(1).max(1e4),category:zod.z.string().min(1),importance:zod.z.number().int().min(1).max(10).optional().default(5),tags:zod.z.array(zod.z.string()).optional(),sessionId:zod.z.string().optional(),msgId:zod.z.string().optional(),parentMsgId:zod.z.string().optional(),skipDedup:zod.z.boolean().optional().default(false),extractGraph:zod.z.boolean().optional().default(true)});zod.z.object({fact:zod.z.object({id:zod.z.string(),agentId:zod.z.string(),content:zod.z.string(),category:zod.z.string(),importance:zod.z.number(),createdAt:zod.z.string(),updatedAt:zod.z.string()}),filePath:zod.z.string(),deduplicated:zod.z.boolean(),nodeIds:zod.z.array(zod.z.number()).optional()});var He=zod.z.object({factId:zod.z.string().optional(),category:zod.z.string().optional(),fromTime:zod.z.string().datetime().optional(),toTime:zod.z.string().datetime().optional(),maxDelete:zod.z.number().int().min(1).max(1e4).optional().default(1e3),dryRun:zod.z.boolean().optional().default(false),force:zod.z.boolean().optional().default(false)}).refine(t=>t.factId!==void 0&&t.factId.length>0||t.category!==void 0&&t.category.length>0||t.fromTime!==void 0||t.toTime!==void 0,{message:"one of `factId`, `category`, `fromTime`, or `toTime` is required"});zod.z.object({deletedCount:zod.z.number(),deletedIds:zod.z.array(zod.z.string()),dryRun:zod.z.boolean(),truncatedCount:zod.z.number()});var Ue=zod.z.object({sessionId:zod.z.string().min(1),lastN:zod.z.number().int().min(1).max(500).optional().default(50),fromMessageId:zod.z.string().optional(),writeToDisk:zod.z.boolean().optional().default(true)});zod.z.object({extractedCount:zod.z.number(),factIds:zod.z.array(zod.z.string()),entities:zod.z.array(zod.z.object({id:zod.z.number(),name:zod.z.string(),type:zod.z.string()})),relations:zod.z.array(zod.z.object({source:zod.z.string(),target:zod.z.string(),relation:zod.z.string()})),messageRange:zod.z.object({fromMessageId:zod.z.string(),toMessageId:zod.z.string()}),durationMs:zod.z.number()});var We=zod.z.object({windowDays:zod.z.number().int().min(1).max(365).optional().default(30),dryRun:zod.z.boolean().optional().default(false)});zod.z.object({totalFacts:zod.z.number(),dedupedCount:zod.z.number(),compressedCount:zod.z.number(),archivedCount:zod.z.number(),skippedCount:zod.z.number(),durationMs:zod.z.number()});var je=zod.z.object({query:zod.z.string().min(1),type:zod.z.string().optional(),depth:zod.z.number().int().min(1).max(5).optional().default(2),maxNodes:zod.z.number().int().min(1).max(500).optional().default(100),scope:zod.z.enum(["agent_only","shared_only","both"]).optional().default("agent_only"),relation:zod.z.string().optional()});zod.z.object({root:zod.z.unknown().nullable(),nodes:zod.z.array(zod.z.unknown()),edges:zod.z.array(zod.z.unknown()),truncated:zod.z.boolean(),totalNodes:zod.z.number(),totalEdges:zod.z.number(),scope:zod.z.enum(["agent_only","shared_only","both"]),durationMs:zod.z.number()});var Ge=zod.z.object({}).optional();zod.z.object({dbPath:zod.z.string(),workspaceDir:zod.z.string(),factsCount:zod.z.number(),nodesCount:zod.z.number(),edgesCount:zod.z.number(),factsByCategory:zod.z.record(zod.z.string(),zod.z.number()),ftsAvailable:zod.z.boolean(),vectorEnabled:zod.z.boolean(),kgScopeEnabled:zod.z.boolean(),healthy:zod.z.boolean(),meta:zod.z.record(zod.z.string(),zod.z.string())});var ze=zod.z.object({}).optional();zod.z.object({healthy:zod.z.boolean(),checks:zod.z.array(zod.z.object({name:zod.z.string(),passed:zod.z.boolean(),message:zod.z.string(),details:zod.z.record(zod.z.string(),zod.z.unknown()).optional()}))});var Be=zod.z.object({workspaceDir:zod.z.string().optional(),dbPath:zod.z.string().optional(),archiveDays:zod.z.number().int().min(1).max(3650).optional().default(30),force:zod.z.boolean().optional().default(false)});zod.z.object({initialized:zod.z.boolean(),dbPath:zod.z.string(),workspaceDir:zod.z.string(),tablesCreated:zod.z.number(),migrationsApplied:zod.z.number(),durationMs:zod.z.number()});var Qe=zod.z.object({windowDays:zod.z.number().int().min(1).max(3650).optional(),dryRun:zod.z.boolean().optional().default(false)});zod.z.object({generatedCount:zod.z.number(),skippedCount:zod.z.number(),failedGenerateCount:zod.z.number(),archivedCount:zod.z.number(),archiveThreshold:zod.z.string(),archivedRecords:zod.z.array(zod.z.object({source:zod.z.string(),target:zod.z.string(),firstCreatedAt:zod.z.string(),firstFactId:zod.z.string()})),windowDays:zod.z.number(),dryRun:zod.z.boolean(),durationMs:zod.z.number()});var se=utils.Log.create({service:"memory.fact-file-sync"}),Rt=".easbot/memory/active";function ie(t,e){let n=e.replace(/\\/g,"/").replace(/\/+$/,""),r=t.category||"uncategorized",o=t.createdAt?new Date(t.createdAt).getTime():Date.now(),c=Number.isNaN(o)?new Date:new Date(o),s=c.getFullYear(),i=String(c.getMonth()+1).padStart(2,"0"),p=String(c.getDate()).padStart(2,"0"),f=`${s}-${i}-${p}`;return `${n}/${Rt}/${r}/${f}.md`}function Ke(t){let e=t.tags&&t.tags.length>0?t.tags:[],n=t.importance??5,r=t.source??"session_self_write",o=t.createdAt?utils.formatLocalISO(new Date(t.createdAt)):utils.formatLocalISO(new Date),c=t.updatedAt?utils.formatLocalISO(new Date(t.updatedAt)):o,s=["---",`id: ${t.id}`,`agent_id: ${t.agentId}`,`category: ${t.category}`,`importance: ${n}`,`created_at: ${o}`,`updated_at: ${c}`,`source: ${r}`,e.length>0?`tags: [${e.join(", ")}]`:"tags: []"];return t.sessionId&&s.push(`session_id: ${t.sessionId}`),t.msgId&&s.push(`msg_id: ${t.msgId}`),t.parentMsgId&&s.push(`parent_msg_id: ${t.parentMsgId}`),t.nodeIds&&t.nodeIds.length>0&&s.push(`node_ids: [${t.nodeIds.join(", ")}]`),s.push("---"),`${s.join(`
|
|
22
|
+
`)}
|
|
23
|
+
${t.content.trim()}`}function V(t,e){let n=t.replace(/\\/g,"/"),r=e.replace(/\\/g,"/").replace(/\/+$/,"");return n.startsWith(`${r}/`)?n.slice(r.length+1):n}async function St(t,e){let n=ie(t,e),r=V(n,e);try{let o=Ke(t);await G__default.default.mkdir(ce__default.default.dirname(n),{recursive:!0});let c="";try{c=await G__default.default.readFile(n,"utf-8");}catch(i){if(i.code!=="ENOENT")throw i}let s=c.length>0&&!c.endsWith(`
|
|
24
|
+
`)?`
|
|
25
|
+
`:"";return await G__default.default.writeFile(n,`${c}${s}${o}
|
|
26
|
+
`,"utf-8"),se.debug("Fact file synced (append)",{id:t.id,relPath:r}),{ok:!0,absPath:n,relPath:r}}catch(o){let c=o instanceof Error?o.message:String(o);return se.warn("Failed to write fact file (best-effort, non-blocking)",{id:t.id,absPath:n,error:c}),{ok:false,absPath:n,relPath:r,error:c}}}async function It(t,e){let n;t.filePath?n=`${e.replace(/\\/g,"/").replace(/\/+$/,"")}/${t.filePath.replace(/^\/+/,"")}`:n=ie({id:t.id,category:t.category,createdAt:t.createdAt,updatedAt:t.createdAt},e);let r=V(n,e);try{return await G__default.default.unlink(n),se.debug("Fact file deleted",{id:t.id,relPath:r}),{ok:!0,absPath:n,relPath:r}}catch(o){if(o.code==="ENOENT")return se.debug("Fact file not found (already deleted)",{id:t.id,relPath:r}),{ok:true,absPath:n,relPath:r};let s=o instanceof Error?o.message:String(o);return se.warn("Failed to delete fact file (best-effort, non-blocking)",{id:t.id,absPath:n,error:s}),{ok:false,absPath:n,relPath:r,error:s}}}var Y={resolvePath:ie,renderMarkdown:Ke,toRelPath:V,write:St,delete:It};var fe=utils.Log.create({service:"memory.service.remember"});async function Je(t,e){if(H(t),ge(t),!e.content||e.content.trim().length===0)throw new M("remember requires non-empty `content`","CONTENT_REQUIRED");if(!e.category)throw new M("remember requires `category`","CATEGORY_REQUIRED");fe.debug("remember invoked",{agentId:t.agentId,category:e.category,importance:e.importance??5,contentLength:e.content.length,skipDedup:e.skipDedup,extractGraph:e.extractGraph??true});let n=new chunkEGWJG65Q_cjs.e(t.dbPath);try{await n.initialize();let r=new Date().toISOString(),o=Ct(),c=e.importance??5,s={entities:[],relations:[]},p=e.extractGraph!==!1&&chunkJ5XF2W4Z_cjs.a.isInitialized()&&chunkJ5XF2W4Z_cjs.a.capabilities().graphLlm?chunkJ5XF2W4Z_cjs.a.getGraphLlm():void 0;if(p)try{s=await Tt(p,e.content);}catch(y){fe.warn("LLM KG extraction failed (continuing without KG)",{agentId:t.agentId,error:y instanceof Error?y.message:String(y)});}let f=chunkJ5XF2W4Z_cjs.a.isInitialized()&&chunkJ5XF2W4Z_cjs.a.capabilities().embedding===!0,m=f?await Nt(n.getDb(),e.content):null,u=m?m.length:null,I=s.entities,v=s.relations,S=[],w=0;n.transaction(()=>{let y=new Map;for(let E of I){let _=n.query("SELECT id FROM nodes WHERE name = ? AND type = ? AND owner_agent_id = ? LIMIT 1",[E.name,E.type,t.agentId])[0];if(_){y.set(E.name,_.id);continue}let g=n.run("INSERT INTO nodes (name, type, properties, owner_agent_id, createdAt, updatedAt) VALUES (?, ?, ?, ?, ?, ?)",[E.name,E.type,JSON.stringify({source:"llm_extracted",...E.properties??{}}),t.agentId,r,r]);g.lastID>0&&y.set(E.name,g.lastID);}for(let E of v){let _=y.get(E.source),g=y.get(E.target);!_||!g||_===g||n.run("INSERT OR REPLACE INTO edges (source, target, relation, properties, createdAt) VALUES (?, ?, ?, ?, ?)",[_,g,E.relation,JSON.stringify({}),r]);}if(n.run(`INSERT INTO memory_facts
|
|
27
|
+
(id, agent_id, session_id, msg_id, parent_msg_id, content, category, importance,
|
|
28
|
+
source, tags, node_ids, file_path, created_at, updated_at)
|
|
29
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[o,t.agentId,e.sessionId??null,e.msgId??null,e.parentMsgId??null,e.content,e.category,c,"session_self_write",e.tags?JSON.stringify(e.tags):null,JSON.stringify(Array.from(y.values())),null,r,r]),m&&u){let E=Ve(m);n.run("INSERT OR REPLACE INTO memory_vectors (fact_id, embedding) VALUES (?, ?)",[o,E]),w=1,n.query("SELECT value FROM meta WHERE key = ?",["vectorDims"])[0]||n.run("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)",["vectorDims",String(u)]);}n.run("DELETE FROM memory_facts_fts WHERE fact_id = ?",[o]),n.run("INSERT INTO memory_facts_fts (fact_id, agent_id, content, tags) VALUES (?, ?, ?, ?)",[o,t.agentId,e.content,e.tags?e.tags.join(" "):""]),S.push(...Array.from(y.values()));}),fe.info("Memory stored",{id:o,category:e.category,agentId:t.agentId,nodeCount:S.length,vectorsWritten:w,vectorDims:u??0,embeddingMode:f?"enabled":"fts_only",entitiesExtracted:I.length,relationsExtracted:v.length});let h={id:o,agentId:t.agentId,sessionId:e.sessionId,msgId:e.msgId,parentMsgId:e.parentMsgId,content:e.content,category:e.category,importance:c,source:"session_self_write",tags:e.tags,nodeIds:S.length>0?S:void 0,filePath:void 0,createdAt:r,updatedAt:r},b="",R=await Y.write(h,t.workspaceDir);if(R.ok){b=R.relPath,h.filePath=R.relPath;try{n.run("UPDATE memory_facts SET file_path = ? WHERE id = ?",[R.relPath,o]);}catch(y){fe.warn("Failed to update file_path column after sync",{id:o,error:y instanceof Error?y.message:String(y)});}}return {fact:h,filePath:b,deduplicated:!1,nodeIds:S,vectorsWritten:w,vectorDims:u??0,entitiesExtracted:I.length,relationsExtracted:v.length}}catch(r){throw r instanceof M?r:new M(`remember failed: ${r instanceof Error?r.message:String(r)}`,"INTERNAL",{cause:r instanceof Error?r.message:String(r)})}finally{n.close();}}function Ct(){let t=Date.now(),e=crypto.randomBytes(3).toString("hex");return `mem_${t}_${e}`}function Ve(t){return Buffer.from(t.buffer,t.byteOffset,t.byteLength)}function Ot(t){return crypto.createHash("sha256").update(t).digest("hex")}async function Nt(t,e){let n=Ot(e),r=t.prepare("SELECT embedding FROM embedding_cache WHERE content_hash = ?").get(n);if(r?.embedding)return new Float32Array(r.embedding.buffer,r.embedding.byteOffset,r.embedding.byteLength/4);let o=await chunkJ5XF2W4Z_cjs.a.embedText(e);if(!o||o.length===0)return null;let c=Ve(o);return t.prepare("INSERT OR REPLACE INTO embedding_cache (content_hash, embedding) VALUES (?, ?)").run(n,c),o}async function Tt(t,e){let n=await llm.GraphProvider.generateGraph({chunks:[e],model:t,includeRules:false});return {entities:n.entities,relations:n.relations}}var he=utils.Log.create({service:"memory.service.forget"}),kt=1e3;function At(t){let e=[];if(t.factId&&t.factId.trim().length>0&&e.push("factId"),t.category&&t.category.trim().length>0&&e.push("category"),(t.fromTime||t.toTime)&&e.push("timeRange"),e.length===0)throw new M("CONTENT_REQUIRED: forget requires one of: `factId`, `category`, or `fromTime`/`toTime`","CONTENT_REQUIRED");if(e.length>1)throw new M(`mutually exclusive: forget requires exactly one of factId/category/timeRange, got [${e.join(", ")}]`,"CONTENT_REQUIRED");return e[0]}function xt(t,e,n){let r=[n];switch(t){case "factId":return {where:"agent_id = ? AND id = ?",args:[...r,e.factId]};case "category":return {where:"agent_id = ? AND category = ?",args:[...r,e.category]};case "timeRange":{let o=["agent_id = ?"];return e.fromTime&&(o.push("created_at >= ?"),r.push(e.fromTime)),e.toTime&&(o.push("created_at <= ?"),r.push(e.toTime)),{where:o.join(" AND "),args:r}}}}function Lt(t,e,n,r){return t.query(`SELECT id, node_ids FROM memory_facts WHERE ${e} LIMIT ?`,[...n,r+1]).map(c=>c.id)}function Ft(t,e,n,r){if(n.length===0)return 0;let o=n.map(()=>"?").join(",");return t.query(`SELECT COUNT(*) as count FROM memory_facts WHERE agent_id = ? AND id != ? AND node_ids IS NOT NULL AND EXISTS (
|
|
30
|
+
SELECT 1 FROM json_each(node_ids) AS je WHERE je.value IN (${o})
|
|
31
|
+
)`,[r,e,...n])[0]?.count??0}function qt(t,e,n){let r,o,c="";return t.transaction(()=>{let s=t.query("SELECT node_ids, content, file_path, category, created_at FROM memory_facts WHERE id = ? AND agent_id = ?",[e,n])[0],i=[];if(s?.node_ids)try{i=JSON.parse(s.node_ids),Array.isArray(i)||(i=[]);}catch{i=[];}if(r=s?.file_path??void 0,o=s?.category,c=s?.created_at??"",t.run("DELETE FROM memory_facts_fts WHERE fact_id = ?",[e]),t.run("DELETE FROM memory_facts WHERE id = ? AND agent_id = ?",[e,n]),i.length>0){let p=i.map(()=>"?").join(",");t.run(`DELETE FROM nodes WHERE id IN (${p}) AND NOT EXISTS (
|
|
32
|
+
SELECT 1 FROM memory_facts WHERE node_ids IS NOT NULL AND EXISTS (
|
|
33
|
+
SELECT 1 FROM json_each(node_ids) AS je WHERE je.value = nodes.id
|
|
34
|
+
)
|
|
35
|
+
)`,i);}}),{filePath:r,category:o,createdAt:c}}async function Ye(t,e){H(t),j(t,"forget");let n=At(e),r=e.maxDelete??kt,o=e.dryRun??false,c=e.force??false;he.debug("forget invoked",{agentId:t.agentId,mode:n,maxDelete:r,dryRun:o,force:c});let s=new chunkEGWJG65Q_cjs.e(t.dbPath);try{await s.initialize();let{where:i,args:p}=xt(n,e,t.agentId),f=Lt(s,i,p,r),m=f.length>r;if(m&&!c)throw new oe(f.length,r);let u=m?f.slice(0,r):f;if(o)throw new ne(u.length);let I=[],v=[];for(let S of u){if(!c){let R=s.query("SELECT node_ids FROM memory_facts WHERE id = ? AND agent_id = ?",[S,t.agentId])[0],y=R?.node_ids?(()=>{try{let _=JSON.parse(R.node_ids);if(Array.isArray(_))return _.filter(g=>typeof g=="number")}catch{}return []})():[],E=Ft(s,S,y,t.agentId);if(E>0)throw new re(S,E)}let{filePath:w,category:h,createdAt:b}=qt(s,S,t.agentId);w&&h&&v.push({id:S,filePath:w,category:h,createdAt:b}),I.push(S);}he.info("forget complete",{agentId:t.agentId,mode:n,deletedCount:I.length,force:c,dryRun:o});for(let{id:S,filePath:w,category:h,createdAt:b}of v)await Y.delete({id:S,filePath:w,category:h,createdAt:b},t.workspaceDir).catch(R=>{he.warn("Fact file delete failed (best-effort)",{id:S,filePath:w,error:R instanceof Error?R.message:String(R)});});return {deletedCount:I.length,deletedIds:I,dryRun:o,truncatedCount:m?f.length-r:0}}catch(i){throw i instanceof M?i:new M(`forget failed: ${i instanceof Error?i.message:String(i)}`,"INTERNAL",{cause:i instanceof Error?i.message:String(i)})}finally{s.close();}}var be=utils.Log.create({service:"memory.service.extract"}),Ht=50,Ee=500;async function Xe(t,e){if(H(t),!e.sessionId||e.sessionId.trim().length===0)throw new M("extract requires non-empty `sessionId`","SESSION_ID_REQUIRED");let n=e.lastN??Ht;if(n>Ee)throw new M(`extract lastN=${n} exceeds max=${Ee}`,"CONTENT_REQUIRED",{lastN:n,maxLastN:Ee});let r=e.sessionId,o=e.fromMessageId;be.debug("extract invoked",{agentId:t.agentId,sessionId:r,lastN:n,fromMessageId:o,writeToDisk:e.writeToDisk??true});let c=Date.now(),s=new chunkEGWJG65Q_cjs.e(t.dbPath);try{await s.initialize();let i=s.query(`SELECT id, content, category, importance, 1.0 as score, created_at, node_ids
|
|
36
|
+
FROM memory_facts
|
|
37
|
+
WHERE agent_id = ? AND session_id = ?
|
|
38
|
+
ORDER BY created_at ASC
|
|
39
|
+
LIMIT ?`,[t.agentId,r,n]),p=o?i.filter(S=>S.id>o):i,f=new Set;for(let S of p)if(S.node_ids)try{let w=JSON.parse(S.node_ids);if(Array.isArray(w))for(let h of w)typeof h=="number"&&h>0&&f.add(h);}catch(w){be.warn("extract: invalid node_ids JSON",{factId:S.id,error:w instanceof Error?w.message:String(w)});}let m=Array.from(f),u=[],I=[];if(m.length>0){let S=m.map(()=>"?").join(","),w=s.query(`SELECT id, name, type FROM nodes WHERE id IN (${S})`,m),h=new Map;for(let y of w)h.set(y.id,y.name);u=w.map(y=>({id:y.id,name:y.name,type:y.type}));let b=s.query(`SELECT source, target, relation FROM edges WHERE source IN (${S}) OR target IN (${S})`,[...m,...m]),R=new Set;I=[];for(let y of b){let E=h.get(y.source),_=h.get(y.target);if(!E||!_)continue;let g=`${E}\0${y.relation}\0${_}`;R.has(g)||(R.add(g),I.push({source:E,target:_,relation:y.relation}));}}let v=Date.now()-c;return be.info("extract complete",{agentId:t.agentId,sessionId:r,factCount:p.length,nodeCount:u.length,relationCount:I.length,durationMs:v}),{extractedCount:p.length,factIds:p.map(S=>S.id),entities:u,relations:I,messageRange:{fromMessageId:p[0]?.id??"",toMessageId:p[p.length-1]?.id??""},durationMs:v}}catch(i){throw i instanceof M?i:new M(`extract failed: ${i instanceof Error?i.message:String(i)}`,"INTERNAL",{cause:i instanceof Error?i.message:String(i)})}finally{s.close();}}var Se=utils.Log.create({service:"memory.service.consolidate"}),Wt=30;async function jt(t){let{createHash:e}=await import('crypto');return e("sha256").update(t).digest("hex")}async function Ze(t,e={}){let n=Date.now();H(t),j(t,"consolidate");let r=e.windowDays??Wt,o=e.dryRun??false;Se.debug("consolidate invoked",{agentId:t.agentId,windowDays:r,dryRun:o});let c=new chunkEGWJG65Q_cjs.e(t.dbPath);try{await c.initialize();let s=c.query("SELECT id, content, category, importance, created_at FROM memory_facts WHERE agent_id = ? ORDER BY created_at DESC",[t.agentId]),i=new Map;for(let h of s){let b=await jt(h.content);i.has(b)||i.set(b,[]),i.get(b)?.push(h);}let p=0,f=[];for(let[,h]of i){if(h.length<=1)continue;let b=[...h].sort((E,_)=>E.importance!==_.importance?_.importance-E.importance:_.created_at.localeCompare(E.created_at)),R=b[0];if(!R)continue;let y=b.slice(1).map(E=>E.id);p+=y.length,f.push({keep:R,removeIds:y});}let m=new Date(Date.now()-r*24*60*60*1e3).toISOString(),u=c.query(`SELECT id, content, category, importance, created_at FROM memory_facts
|
|
40
|
+
WHERE agent_id = ? AND created_at < ?
|
|
41
|
+
ORDER BY created_at ASC`,[t.agentId,m]),I=0,v=0;if(o)I=0,v=p;else {let h=ce__default.default.join(t.workspaceDir,"archive");await G__default.default.mkdir(h,{recursive:!0});for(let{removeIds:b}of f){if(b.length===0)continue;let R=b.map(()=>"?").join(",");c.transaction(()=>{for(let y of b)c.run("DELETE FROM memory_facts WHERE id = ? AND agent_id = ?",[y,t.agentId]);}),v+=b.length;}for(let b of u){let R=b.created_at.slice(0,7),y=ce__default.default.join(h,R,b.category);await G__default.default.mkdir(y,{recursive:!0});let E=ce__default.default.join(y,`${b.id}.md`);try{await G__default.default.writeFile(E,[`# ${b.id}`,"",`category: ${b.category}`,`importance: ${b.importance}`,`createdAt: ${b.created_at}`,"",b.content,""].join(`
|
|
42
|
+
`),"utf-8"),c.run("DELETE FROM memory_facts WHERE id = ? AND agent_id = ?",[b.id,t.agentId]),I++;}catch(_){Se.warn("consolidate: archive write failed",{factId:b.id,error:_ instanceof Error?_.message:String(_)});}}}let S=s.length,w=0;return Se.info("consolidate complete",{agentId:t.agentId,totalFacts:S,dedupedCount:p,compressedCount:w,archivedCount:I,skippedCount:v,dryRun:o,durationMs:Date.now()-n}),{totalFacts:S,dedupedCount:p,compressedCount:w,archivedCount:I,skippedCount:v,durationMs:Date.now()-n}}catch(s){throw s instanceof M?s:new M(`consolidate failed: ${s instanceof Error?s.message:String(s)}`,"INTERNAL",{cause:s instanceof Error?s.message:String(s)})}finally{c.close();}}var $=utils.Log.create({service:"memory.service.sync"}),Bt=30,Qt=".easbot/memory/active",et=".easbot/memory/archive";function Kt(t){return {id:t.id,agentId:t.agent_id,sessionId:t.session_id??void 0,msgId:t.msg_id??void 0,parentMsgId:t.parent_msg_id??void 0,content:t.content,category:t.category,importance:t.importance,source:t.source,tags:t.tags?JSON.parse(t.tags):void 0,nodeIds:t.node_ids?JSON.parse(t.node_ids):void 0,filePath:t.file_path??void 0,createdAt:t.created_at,updatedAt:t.updated_at}}async function Jt(t,e){let n=0,r=0,o=0,{where:c,params:s}=t.agentFilter(e.agentId),i=t.query(`SELECT id, agent_id, session_id, msg_id, parent_msg_id, content, category, importance,
|
|
43
|
+
source, tags, node_ids, file_path, created_at, updated_at
|
|
44
|
+
FROM memory_facts ${c}
|
|
45
|
+
ORDER BY created_at ASC`,s);for(let p of i){let f=Kt(p);if(p.file_path?.startsWith(`${et}/`)){r++;continue}let m=ie(f,e.workspaceDir);try{await G__default.default.access(m),r++;continue}catch(I){let v=I;if(v.code!=="ENOENT"){$.warn("sync generate: fs.access failed (non-ENOENT)",{factId:f.id,absPath:m,error:v.message}),o++;continue}}let u=await Y.write(f,e.workspaceDir);u.ok?n++:(o++,$.warn("sync generate: factFileSync.write failed",{factId:f.id,absPath:m,error:u.error}));}return $.debug("sync stage A complete",{agentId:e.agentId,generatedCount:n,skippedCount:r,failedGenerateCount:o}),{generatedCount:n,skippedCount:r,failedGenerateCount:o}}async function Vt(t,e,n,r){let o=n*24*60*60*1e3,c=Date.now(),s=utils.formatLocalISO(new Date(c-o)),i=[],p=ce__default.default.join(e.workspaceDir,Qt),f=await Yt(p);$.debug("sync stage B: scan active dir",{activeDir:p,fileCount:f.length,windowDays:n,threshold:s,dryRun:r});for(let m of f){let u=await Xt(m);if(!u){$.warn("sync stage B: skip unparseable file",{absPath:m});continue}let{firstCreatedAt:I,firstFactId:v}=u,S=new Date(I).getTime();if(Number.isNaN(S)){$.warn("sync stage B: skip invalid createdAt",{absPath:m,firstCreatedAt:I});continue}if(c-S<=o)continue;let w=Zt(m);if(!w){$.warn("sync stage B: cannot infer category from path",{absPath:m});continue}let h=I.slice(0,7),b=ce__default.default.join(e.workspaceDir,et,h,w),R=ce__default.default.basename(m),y=ce__default.default.join(b,R);if(r){i.push({source:m,target:y,firstCreatedAt:I,firstFactId:v});continue}try{await G__default.default.mkdir(b,{recursive:!0});try{await G__default.default.rename(m,y);}catch(g){let k=g;$.warn("sync stage B: fs.rename failed, falling back to copy+unlink",{absPath:m,targetPath:y,error:k.message}),await G__default.default.copyFile(m,y),await G__default.default.unlink(m);}let E=V(m,e.workspaceDir),_=V(y,e.workspaceDir);t.run(`UPDATE memory_facts SET file_path = ?
|
|
46
|
+
WHERE agent_id = ? AND file_path = ?`,[_,e.agentId??"",E]),i.push({source:m,target:y,firstCreatedAt:I,firstFactId:v});}catch(E){$.warn("sync stage B: archive failed",{absPath:m,targetPath:y,error:E instanceof Error?E.message:String(E)});}}return $.debug("sync stage B complete",{agentId:e.agentId,archivedCount:i.length,dryRun:r}),{archivedCount:i.length,archiveThreshold:s,archivedRecords:i}}async function Yt(t){let e=[];try{await tt(t,e);}catch(n){let r=n;if(r.code==="ENOENT")return e;throw $.warn("sync: listActiveMdFiles failed",{activeDir:t,error:r.message}),new M(`sync: listActiveMdFiles failed: ${r.message}`,"INTERNAL",{cause:r.message})}return e}async function tt(t,e){let n=await G__default.default.readdir(t,{withFileTypes:true});for(let r of n){let o=ce__default.default.join(t,r.name);r.isDirectory()?await tt(o,e):r.isFile()&&r.name.endsWith(".md")&&e.push(o);}}async function Xt(t){let e;try{e=await G__default.default.readFile(t,"utf-8");}catch(s){if(s.code==="ENOENT")return null;throw s}if(!e.startsWith(`---
|
|
47
|
+
`))return null;let n=e.indexOf(`
|
|
48
|
+
---
|
|
49
|
+
`,4);if(n===-1)return null;let r=e.slice(4,n),o,c;for(let s of r.split(`
|
|
50
|
+
`)){let i=s.trim();if(i.startsWith("created_at:")?o=i.slice(11).trim().replace(/^["']|["']$/g,""):i.startsWith("id:")&&(c=i.slice(3).trim().replace(/^["']|["']$/g,"")),o&&c)break}return !o||!c?null:{firstCreatedAt:o,firstFactId:c}}function Zt(t){let e=t.replace(/\\/g,"/").split("/"),n=e.findIndex(c=>c==="active");if(n===-1)return null;let r=e.slice(n+1);return r.length!==2||!r[1].endsWith(".md")?null:r[0]??null}async function rt(t,e={}){let n=Date.now();H(t),j(t,"sync");let r=e.windowDays??t.config?.archiveDays??Bt,o=e.dryRun??false;$.info("sync invoked",{agentId:t.agentId,windowDays:r,dryRun:o,workspaceDir:t.workspaceDir});let c=new chunkEGWJG65Q_cjs.e(t.dbPath);try{await c.initialize();let s=await Jt(c,t),i=await Vt(c,t,r,o),p={generatedCount:s.generatedCount,skippedCount:s.skippedCount,failedGenerateCount:s.failedGenerateCount,archivedCount:i.archivedCount,archiveThreshold:i.archiveThreshold,archivedRecords:i.archivedRecords,windowDays:r,dryRun:o,durationMs:Date.now()-n};return $.info("sync complete",{agentId:t.agentId,...p}),p}catch(s){throw s instanceof M?s:new M(`sync failed: ${s instanceof Error?s.message:String(s)}`,"INTERNAL",{cause:s instanceof Error?s.message:String(s)})}finally{c.close();}}var nt=utils.Log.create({service:"memory.service.graph-query"});async function ot(t,e){let n=Date.now(),r=(t.agentId??"").trim()||"default",o=e.scope??"agent_only";if(!e.query||e.query.trim().length===0)throw new M("CONTENT_REQUIRED: graphQuery requires non-empty `query`","CONTENT_REQUIRED");ue(t,o,"graph_query");let c=e.depth??2,s=e.maxNodes??100,i=e.query,p=e.type,f=e.relation;nt.debug("graphQuery invoked",{agentId:r,query:i,type:p,depth:c,maxNodes:s,scope:o,remote:t.remote});let m=new chunkEGWJG65Q_cjs.e(t.dbPath);try{await m.initialize();let u=new J(m.getDb()),I=i.includes("*")||i.includes("%")?i:`%${i}%`,v=await u.queryNodes({name:I,...p?{type:p}:{},agentId:r,scope:o,limit:s}),w=(i.includes("*")||i.includes("%")?v:v.filter(g=>g.name.toLowerCase().includes(i.toLowerCase())))[0]??null;if(!w)return {root:null,nodes:[],edges:[],truncated:!1,totalNodes:0,totalEdges:0,scope:o,durationMs:Date.now()-n};let h=await u.queryNeighbors(w.id,c,{agentId:r,scope:o,maxEdgesPerNode:20}),b=new Map;b.set(w.id,w);for(let g of h)b.set(g.id,{id:g.id,name:g.name,type:g.type,createdAt:g.createdAt,updatedAt:g.updatedAt});let R=[];for(let g of h)if(g.edges)for(let k of g.edges)f&&k.relation!==f||R.push(k);for(let g of R){if(!b.has(g.source)){let k=await u.queryNodes({ids:[g.source],agentId:r,scope:o});k[0]&&b.set(k[0].id,k[0]);}if(!b.has(g.target)){let k=await u.queryNodes({ids:[g.target],agentId:r,scope:o});k[0]&&b.set(k[0].id,k[0]);}}let y=Array.from(b.values()),E=y.length>s,_=E?y.slice(0,s):y;return nt.info("graphQuery complete",{agentId:r,rootId:w.id,nodeCount:_.length,edgeCount:R.length,truncated:E,durationMs:Date.now()-n}),{root:w,nodes:_,edges:R,truncated:E,totalNodes:y.length,totalEdges:R.length,scope:o,durationMs:Date.now()-n}}catch(u){throw u instanceof M?u:new M(`graphQuery failed: ${u instanceof Error?u.message:String(u)}`,"INTERNAL",{cause:u instanceof Error?u.message:String(u)})}finally{m.close();}}var U=utils.Log.create({service:"memory.service.init"});function Ie(t){return ce__default.default.join(t,".easbot","memory.json")}async function nr(t){try{let{Config:e}=await import('@easbot/llm'),n=await e.get(),r=o=>typeof o=="string"&&o.length>0?o:void 0;return {embeddingModel:r(n.embedding_model),graphModel:r(n.graph_model)}}catch{return {}}}function or(t,e={}){let n={version:1,schema_version:chunkEGWJG65Q_cjs.a,backend:"better-sqlite3",created_at:new Date().toISOString(),embedding_model:e.embeddingModel??null,graph_model:e.graphModel??null,entity_extraction_prompt:e.entityExtractionPrompt??null,relation_extraction_prompt:e.relationExtractionPrompt??null,archiveDays:e.archiveDays??30,shortTermMaxRounds:e.shortTermMaxRounds??20};fs.writeFileSync(t,JSON.stringify(n,null,2),"utf-8");}async function at(t,e={}){let n=Date.now();j(t,"init");let r=e.workspaceDir??t.workspaceDir,o=e.dbPath??t.dbPath;if(!r||r.trim().length===0)throw new M("init requires non-empty `workspaceDir` (ctx.workspaceDir or params.workspaceDir)","CONTENT_REQUIRED");if(!o||o.trim().length===0)throw new M("init requires non-empty `dbPath` (ctx.dbPath or params.dbPath)","CONTENT_REQUIRED");let c=t.agentId?.trim()??"",s=e.force??false;U.debug("init invoked",{agentId:c,workspaceDir:r,dbPath:o,force:s});let i=Ie(r);if(!s)try{if(await G__default.default.stat(i).then(()=>!0).catch(()=>!1))return U.info("init: idempotent skip (memory.json exists, no --force)",{workspaceDir:r,configPath:i}),{initialized:!1,dbPath:o,configPath:i,configCreated:!1,schemaVersion:chunkEGWJG65Q_cjs.a,workspaceDir:r,tablesCreated:0,migrationsApplied:0,durationMs:0}}catch{}try{await G__default.default.mkdir(ce__default.default.dirname(o),{recursive:!0}),await G__default.default.mkdir(ce__default.default.join(r,".easbot","memory","active"),{recursive:!0}),await G__default.default.mkdir(ce__default.default.join(r,"archive"),{recursive:!0}),await G__default.default.mkdir(ce__default.default.join(r,".easbot"),{recursive:!0});}catch(u){throw new M(`init: failed to create directories: ${u instanceof Error?u.message:String(u)}`,"INTERNAL",{cause:u instanceof Error?u.message:String(u)})}if(s)try{await G__default.default.rm(o,{force:!0});}catch(u){U.warn("init: force rm db failed (may not exist)",{dbPath:o,error:u instanceof Error?u.message:String(u)});}let p=await nr(),f=false;try{!await G__default.default.stat(i).then(()=>!0).catch(()=>!1)||s?(or(i,{embeddingModel:p.embeddingModel,graphModel:p.graphModel,archiveDays:t.config?.archiveDays,shortTermMaxRounds:t.config?.shortTermMaxRounds}),f=!0,U.info("init: memory.json written",{configPath:i,force:s,configCreated:f})):U.debug("init: memory.json already exists, skipping write",{configPath:i});}catch(u){U.warn("init: memory.json write failed (non-fatal)",{configPath:i,error:u instanceof Error?u.message:String(u)});}let m=new chunkEGWJG65Q_cjs.e(o);try{let u=await G__default.default.stat(o).then(()=>!0).catch(()=>!1);await m.initialize();let I=new Date().toISOString(),v=[["version","1.0.0"],["schemaVersion",String(chunkEGWJG65Q_cjs.a)],["createdAt",I],["defaultAgentId",c]];for(let[h,b]of v)try{m.run("INSERT OR IGNORE INTO meta (key, value) VALUES (?, ?)",[h,b]);}catch(R){U.warn("init: meta insert failed",{key:h,error:R instanceof Error?R.message:String(R)});}let S=0;try{S=m.prepare("SELECT COUNT(*) as n FROM sqlite_master WHERE type IN ('table', 'index', 'trigger', 'view')").get()?.n??0;}catch(h){U.warn("init: tablesCreated count failed",{error:h instanceof Error?h.message:String(h)});}let w=0;try{w=m.prepare("SELECT id FROM schema_migrations").all().length;}catch(h){U.warn("init: migrationsApplied count failed",{error:h instanceof Error?h.message:String(h)});}return U.info("init complete",{agentId:c,workspaceDir:r,dbPath:o,configPath:i,configCreated:f,schemaVersion:chunkEGWJG65Q_cjs.a,durationMs:Date.now()-n}),{initialized:!0,dbPath:o,configPath:i,configCreated:f,schemaVersion:chunkEGWJG65Q_cjs.a,workspaceDir:r,tablesCreated:S,migrationsApplied:w,durationMs:Date.now()-n}}catch(u){throw new M(`init failed: ${u instanceof Error?u.message:String(u)}`,"INTERNAL",{cause:u instanceof Error?u.message:String(u)})}finally{m.close();}}var X=utils.Log.create({service:"memory.service.status"}),cr=["user_preference","task_context","technical_fact","decision","relationship","reminder","error_pattern","workflow","exploration_finding","experience_summary","tool_usage","skill_creation","test","other"],dr={};async function st(t,e={},n=dr){let r=t.agentId&&t.agentId.trim().length>0?t.agentId:void 0;if(X.debug("status invoked",{agentId:r??"<global>"}),!t.dbPath||t.dbPath.length===0)throw new M("`ctx.dbPath` is required","INTERNAL");let o={initialized:false,capabilities:{embedding:false,graphLlm:false}},c={},s={},i=0,p=0,f=0,m,u,I,v=false,S,w="uninitialized",h=false,b=false,R=false,y,E=cr.reduce((O,F)=>(O[F]=0,O),{}),_=new chunkEGWJG65Q_cjs.e(t.dbPath);try{await _.initialize(),i=_.query(r!==void 0?"SELECT COUNT(*) as c FROM memory_facts WHERE agent_id = ?":"SELECT COUNT(*) as c FROM memory_facts WHERE agent_id IS NOT NULL",r!==void 0?[r]:[])[0]?.c??0,p=_.query(r!==void 0?"SELECT COUNT(*) AS c FROM nodes WHERE owner_agent_id = ? OR owner_agent_id IS NULL":"SELECT COUNT(*) AS c FROM nodes",r!==void 0?[r]:[])[0]?.c??0,f=_.query("SELECT COUNT(*) as c FROM edges")[0]?.c??0;let B=_.query(r!==void 0?"SELECT category, COUNT(*) as c FROM memory_facts WHERE agent_id = ? GROUP BY category":"SELECT category, COUNT(*) as c FROM memory_facts WHERE agent_id IS NOT NULL GROUP BY category",r!==void 0?[r]:[]);for(let D of B){let L=D.category;L in E&&(E[L]=D.c);}c.facts=i,c.nodes=p,c.edges=f;try{b=_.query("SELECT name FROM sqlite_master WHERE type = ? AND name = ?",["table","memory_facts_fts"]).length>0;}catch(D){X.debug("status: fts probe failed",{error:D instanceof Error?D.message:String(D)});}v=!!t.config?.embeddingLlm;try{h=_.query("SELECT name FROM pragma_table_info('nodes') WHERE name = ?",["owner_agent_id"]).length>0;}catch(D){X.debug("status: kg scope probe failed",{error:D instanceof Error?D.message:String(D)});}R=_.healthCheck();try{let D=_.query("SELECT key, value FROM meta");for(let L of D)s[L.key]=L.value;}catch(D){X.debug("status: meta read failed",{error:D instanceof Error?D.message:String(D)});}let d=s.schema_version,l=s.extraction_version,C=s.lastSyncAt??s.lastSync,P=s.embeddingDims;m=d&&Number.parseInt(d,10)||void 0,u=l&&Number.parseInt(l,10)||void 0,I=C,S=P&&Number.parseInt(P,10)||void 0,i>0&&(w="complete");try{y=_.query("SELECT value FROM meta WHERE key = ?",["backend"])[0]?.value??"better-sqlite3";}catch{y="better-sqlite3";}}catch(O){if(O instanceof M)throw O;X.warn("status: db phase failed; returning partial result",{dbPath:t.dbPath,error:O instanceof Error?O.message:String(O)}),y="unknown",R=false;}finally{_.close();}if(!n.skipLlm&&chunkJ5XF2W4Z_cjs.a.isInitialized()){let F=chunkJ5XF2W4Z_cjs.a.capabilities();o.initialized=true,o.capabilities={embedding:F.embedding===true,graphLlm:F.graphLlm===true},o.embeddingModel=o.capabilities.embedding?"configured":void 0,o.graphModel=o.capabilities.graphLlm?"configured":void 0;}if(!n.skipEmbeddingProbe&&!n.skipLlm&&o.initialized&&o.capabilities.embedding)try{let O=chunkJ5XF2W4Z_cjs.a.getEmbeddingLlm?.();if(O){let F=await llm.probeEmbeddingDims(O,{timeoutMs:5e3});if(typeof F=="number"){S=F,s.embeddingDims=String(F);try{let W=new chunkEGWJG65Q_cjs.e(t.dbPath);try{await W.initialize();let B=W.getDb();llm.syncMeta(B,[["embeddingDims",String(F)]]);}finally{W.close();}}catch{}}}}catch{}let g;return R?w==="uninitialized"&&(g="Run `easbot memory remember <content>` to add the first fact."):g="Run `easbot memory init` to initialize the database.",R&&(w??"uninitialized")==="failed"&&(R=false),X.info("status complete",{dbPath:t.dbPath,agentId:r??"<global>",factsCount:i,nodesCount:p,edgesCount:f,healthy:R}),{package:"memory",agentId:r,dbPath:t.dbPath,configPath:Ie(t.workspaceDir),configExists:true,schemaVersion:m,extractionVersion:u,lastSyncAt:I,indexState:w,vectorEnabled:v,embeddingDims:S,llm:o,backend:y,counts:c,meta:s,recommendation:g,healthy:R,factsByCategory:E,kgScopeEnabled:h,factsCount:i,nodesCount:p,edgesCount:f,ftsAvailable:b}}var pr=utils.Log.create({service:"memory.service.doctor"}),_e=100*1024*1024,it=100*1024*1024,fr={};function N(t,e,n,r,o){return {code:t.toUpperCase().replace(/[^A-Z0-9]+/g,"_"),severity:e,name:t,message:n,details:o,durationMs:r,passed:e!=="error"}}async function ct(t,e={},n=fr){if(pr.debug("doctor invoked",{agentId:t.agentId}),!t.dbPath||t.dbPath.length===0)throw new Error("`ctx.dbPath` is required");let r=[],o=[],c=Date.now(),s=null,i=false,p=Date.now();try{s=new chunkEGWJG65Q_cjs.e(t.dbPath),await s.initialize(),i=!0;let d=s.healthCheck(),l=N("database",d?"ok":"error",d?"database connected and writable":"database unhealthy",Date.now()-p,{dbPath:t.dbPath});r.push(l),o.push({name:l.name,passed:l.severity!=="error",message:l.message,details:l.details,severity:l.severity});}catch(d){let l=N("database","error",`database connection failed: ${d instanceof Error?d.message:String(d)}`,Date.now()-p,{dbPath:t.dbPath});r.push(l),o.push({name:l.name,passed:false,message:l.message,details:l.details,severity:"error"});}let f=Date.now();if(i&&s)try{let d=s.query("SELECT name FROM sqlite_master WHERE type = ? AND name = ?",["table","memory_facts_fts"]),l=d.length>0,C=N("fts",l?"ok":"warn",l?"FTS5 index available":"FTS5 index not found",Date.now()-f,l?{table:d[0]?.name}:void 0);r.push(C),o.push({name:C.name,passed:C.severity!=="error",message:C.message,details:C.details,severity:C.severity});}catch(d){let l=N("fts","error",`fts probe failed: ${d instanceof Error?d.message:String(d)}`,Date.now()-f);r.push(l),o.push({name:l.name,passed:false,message:l.message,details:l.details,severity:"error"});}else {let d=N("fts","info","skipped (db not initialized)",0);r.push(d),o.push({name:d.name,passed:true,message:d.message,severity:"info"});}let m=Date.now(),u=!!t.config?.embeddingLlm,I=N("vector","ok",u?"embedding model available":"no embedding model configured (FTS-only mode, recall still functional)",Date.now()-m,{mode:u?"hybrid":"fts_only",model:u?"configured":"missing"});r.push(I),o.push({name:I.name,passed:true,message:I.message,details:I.details,severity:"ok"});let v=Date.now();if(i&&s)try{let d=["memory_facts","nodes","edges","meta"],l=s.query("SELECT name FROM sqlite_master WHERE type = ?",["table"]),C=new Set(l.map(L=>L.name)),P=d.filter(L=>!C.has(L)),D=N("schema",P.length===0?"ok":"error",P.length===0?`schema complete (${d.length} tables)`:`missing tables: ${P.join(", ")}`,Date.now()-v,{required:d,existing:Array.from(C)});r.push(D),o.push({name:D.name,passed:D.severity!=="error",message:D.message,details:D.details,severity:D.severity});}catch(d){let l=N("schema","error",`schema probe failed: ${d instanceof Error?d.message:String(d)}`,Date.now()-v);r.push(l),o.push({name:l.name,passed:false,message:l.message,details:l.details,severity:"error"});}else {let d=N("schema","info","skipped (db not initialized)",0);r.push(d),o.push({name:d.name,passed:true,message:d.message,severity:"info"});}let S=Date.now();try{let d=`${t.dbPath}-wal`,l=`${t.dbPath}-shm`,C=0,P=0;try{C=(await G__default.default.stat(d)).size;}catch{C=0;}try{P=(await G__default.default.stat(l)).size;}catch{P=0;}let D=C+P,L=D<=it,q=N("lock",L?"ok":"warn",L?`no lock contention (wal+shm ${(D/1024).toFixed(1)} KB)`:`WAL/SHM files unusually large (${(D/1024/1024).toFixed(1)} MB > ${(it/1024/1024).toFixed(0)} MB threshold)`,Date.now()-S,{walBytes:C,shmBytes:P});r.push(q),o.push({name:q.name,passed:q.severity!=="error",message:q.message,details:q.details,severity:q.severity});}catch(d){let l=N("lock","error",`lock probe failed: ${d instanceof Error?d.message:String(d)}`,Date.now()-S);r.push(l),o.push({name:l.name,passed:false,message:l.message,details:l.details,severity:"error"});}let w=Date.now();try{let d=ce__default.default.dirname(t.dbPath),l=await G__default.default.statfs(d),C=typeof l.bsize=="bigint"?Number(l.bsize)*l.bavail:l.bsize*l.bavail,P=C>=_e,D=N("disk_space",P?"ok":"error",P?`sufficient disk space (${(C/1024/1024).toFixed(1)} MB available)`:`low disk space (${(C/1024/1024).toFixed(1)} MB < ${(_e/1024/1024).toFixed(0)} MB threshold)`,Date.now()-w,{availableBytes:C,threshold:_e});r.push(D),o.push({name:D.name,passed:D.severity!=="error",message:D.message,details:D.details,severity:D.severity});}catch(d){let l=N("disk_space","error",`disk_space probe failed: ${d instanceof Error?d.message:String(d)}`,Date.now()-w);r.push(l),o.push({name:l.name,passed:false,message:l.message,details:l.details,severity:"error"});}let h=Date.now();if(i&&s)try{let d=s.agentFilter(t.agentId),l=s.query(`SELECT id, node_ids FROM memory_facts ${d.where} ${d.where?"AND":"WHERE"} node_ids IS NOT NULL`,d.params),C=[];for(let D of l)try{let L=JSON.parse(D.node_ids);if(!Array.isArray(L))continue;for(let q of L){if(typeof q!="number")continue;if((s.query("SELECT COUNT(*) as c FROM nodes WHERE id = ?",[q])[0]?.c??0)===0){C.push(`${D.id}->${q}`);break}}}catch{}let P=N("orphan",C.length===0?"ok":"warn",C.length===0?"no orphan KG references":`${C.length} orphan references: ${C.slice(0,5).join(", ")}${C.length>5?", ...":""}`,Date.now()-h,{count:C.length});r.push(P),o.push({name:P.name,passed:P.severity!=="error",message:P.message,details:P.details,severity:P.severity});}catch(d){let l=N("orphan","warn",`orphan probe failed: ${d instanceof Error?d.message:String(d)}`,Date.now()-h);r.push(l),o.push({name:l.name,passed:false,message:l.message,details:l.details,severity:"warn"});}else {let d=N("orphan","info","skipped (db not initialized)",0);r.push(d),o.push({name:d.name,passed:true,message:d.message,severity:"info"});}let b=Date.now(),R={"better-sqlite3":false,"node:sqlite":false,"@tursodatabase/database":false};try{let d=module$1.createRequire(chunkNVGACA7W_cjs.b);try{d.resolve("better-sqlite3"),R["better-sqlite3"]=!0;}catch{}R["node:sqlite"]=typeof process.versions.sqlite=="string";try{d.resolve("@tursodatabase/database"),R["@tursodatabase/database"]=!0;}catch{}}catch{}let y=R["better-sqlite3"]||R["node:sqlite"],E=N("backend",y?"ok":"error",y?`SQLite backend available (better-sqlite3: ${R["better-sqlite3"]}, node:sqlite: ${R["node:sqlite"]})`:"no SQLite backend available (install better-sqlite3 or use Node 22.5+)",Date.now()-b,R);r.push(E),o.push({name:E.name,passed:E.severity!=="error",message:E.message,details:E.details,severity:E.severity});let _=Date.now();if(i&&s)try{let d=s.query("SELECT COUNT(*) as c FROM embedding_cache")[0],l=s.agentFilter(t.agentId),C=s.query(`SELECT COUNT(*) as c FROM memory_facts ${l.where}`,l.params)[0],P=d?.c??0,D=C?.c??0,L=Math.max(0,P-D),q=L>0,Z=N("embedding_cache_unused","info",q?`by design: ${L} embedding_cache rows remain after fact deletion (cache is global content-hash dedup; forget intentionally doesn't cascade clear cache to preserve same-content hit rate)`:"embedding_cache in sync with memory_facts (no unused rows)",Date.now()-_,{cacheCount:P,factsCount:D,unused:L,policy:"global_content_hash_dedup"});r.push(Z),o.push({name:Z.name,passed:!q,message:Z.message,details:Z.details,severity:"info"});}catch(d){let l=N("embedding_cache_unused","info",`embedding_cache_unused probe failed: ${d instanceof Error?d.message:String(d)}`,Date.now()-_);r.push(l),o.push({name:l.name,passed:true,message:l.message,severity:"info"});}else {let d=N("embedding_cache_unused","info","skipped (db not initialized)",0);r.push(d),o.push({name:d.name,passed:true,message:d.message,severity:"info"});}let g=Date.now(),k;if(i&&s)try{let d=s.query("SELECT value FROM meta WHERE key = ?",["embeddingDims"]);k=d[0]?.value&&Number.parseInt(d[0].value,10)||void 0;}catch{}let O;if(n.skipLlm||!chunkJ5XF2W4Z_cjs.a.isInitialized()||!chunkJ5XF2W4Z_cjs.a.capabilities().embedding)O=N(types.EMBEDDING_DIMS_CONSISTENCY_CHECK,"info","llm not initialized; probe skipped",Date.now()-g);else if(n.skipEmbeddingProbe)O=N(types.EMBEDDING_DIMS_CONSISTENCY_CHECK,"info","probe skipped (--skip-embedding-probe)",Date.now()-g);else try{let d=chunkJ5XF2W4Z_cjs.a.getEmbeddingLlm?.();if(!d)O=N(types.EMBEDDING_DIMS_CONSISTENCY_CHECK,"info","embedding llm not exposed; probe skipped",Date.now()-g);else {let l=await llm.probeEmbeddingDims(d,{timeoutMs:5e3});typeof l!="number"?O=N(types.EMBEDDING_DIMS_CONSISTENCY_CHECK,"info","probe failed (network / model error)",Date.now()-g):k===void 0?O=N(types.EMBEDDING_DIMS_CONSISTENCY_CHECK,"info",`probe=${l}, meta missing \u2014 next status will sync`,Date.now()-g):l!==k?O=N(types.EMBEDDING_DIMS_CONSISTENCY_CHECK,"warn",`probe=${l}, meta=${k} \u2014 mismatch`,Date.now()-g,{probe:l,meta:k}):O=N(types.EMBEDDING_DIMS_CONSISTENCY_CHECK,"ok",`probe=${l}, meta=${k} \u2014 consistent`,Date.now()-g);}}catch(d){O=N(types.EMBEDDING_DIMS_CONSISTENCY_CHECK,"info",`probe threw: ${d instanceof Error?d.message:String(d)}`,Date.now()-g);}r.push({...O,details:O.details??void 0,passed:O.severity!=="error"}),o.push({name:O.name,passed:O.severity!=="error",message:O.message,details:O.details??void 0,severity:O.severity});let F;if(i&&s){let d=Date.now();try{let{issues:l,stats:C}=s.checkIntegrity();F=C;for(let P of l)r.push(N("integrity_stats",P.severity,P.message,0,{source:"database.checkIntegrity"}));}catch(l){r.push(N("integrity_stats","warn",`db integrity check failed: ${l instanceof Error?l.message:String(l)}`,Date.now()-d));}}let W=!r.some(d=>d.severity==="error");s&&s.close();let B=Date.now()-c;return {healthy:W,checks:r,legacyChecks:o,durationMs:B,integrityStats:F,backendAvailable:R}}var De={name:"recall",scope:"read",schema:qe,annotations:{localOnly:false,requiresAgentId:true,defaultDescription:"Query memory via hybrid search (FTS + vector); returns ranked facts.",readOnlyHint:true,destructiveHint:false,idempotentHint:true},handler:async(t,e)=>{let n=t;if(!e.agentId?.trim())throw new Error("recall: agentId is required");return Fe({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:e.remote??false,config:e.config,agentId:e.agentId},n)}};var ve={name:"remember",scope:"write",schema:$e,annotations:{localOnly:false,requiresAgentId:true,defaultDescription:"Persist a new self-memory fact; auto-extract entities into KG.",readOnlyHint:false,destructiveHint:false,idempotentHint:false},handler:async(t,e)=>{let n=t;if(!e.agentId?.trim())throw new Error("remember: agentId is required");return Je({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:e.remote??false,config:e.config,agentId:e.agentId},n)}};var Ce={name:"forget",scope:"write",schema:He,annotations:{localOnly:false,requiresAgentId:true,defaultDescription:"Delete memory facts by id / category / time range; supports dryRun.",readOnlyHint:false,destructiveHint:true,idempotentHint:true},handler:async(t,e)=>{let n=t;if(!e.agentId?.trim())throw new Error("forget: agentId is required");return Ye({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:e.remote??false,config:e.config,agentId:e.agentId},n)}};var Oe={name:"extract",scope:"write",schema:Ue,annotations:{localOnly:false,requiresAgentId:true,defaultDescription:"Extract facts from a session (server-side pulls messages by lastN).",readOnlyHint:false,destructiveHint:false,idempotentHint:true},handler:async(t,e)=>{let n=t;if(!e.agentId?.trim())throw new Error("extract: agentId is required");return Xe({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:e.remote??false,config:e.config,agentId:e.agentId},n)}};var Ne={name:"consolidate",scope:"admin",schema:We,annotations:{localOnly:true,requiresAgentId:true,defaultDescription:"Run consolidation pipeline: dedup \u2192 archive.",readOnlyHint:false,destructiveHint:true,idempotentHint:true},handler:async(t,e)=>{let n=t;if(!e.isTrustedLocal)throw new Error("consolidate: only trusted local process can invoke this op");if(!e.agentId?.trim())throw new Error("consolidate: agentId is required");return Ze({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:false,config:e.config,agentId:e.agentId},n)}};var Te={name:"sync",scope:"admin",schema:Qe,annotations:{localOnly:true,requiresAgentId:true,defaultDescription:"Sync memory facts to .md files (idempotent skip on existing) and archive expired active files (default 30 days)",readOnlyHint:false,destructiveHint:true,idempotentHint:true},handler:async(t,e)=>{let n=t;if(!e.isTrustedLocal)throw new Error("sync: only trusted local process can invoke this op");if(!e.agentId?.trim())throw new Error("sync: agentId is required");return rt({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:false,config:e.config,agentId:e.agentId},n)}};var Pe={name:"graph_query",scope:"read",schema:je,annotations:{localOnly:false,requiresAgentId:true,defaultDescription:"Query KG nodes / edges / neighbors with scope filtering.",readOnlyHint:true,destructiveHint:false,idempotentHint:true},handler:async(t,e)=>{let n=t,r=e.agentId?.trim()||"default";return ot({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:e.remote??false,config:e.config,agentId:r},n)}};var ke={name:"status",scope:"read",schema:Ge,annotations:{localOnly:false,requiresAgentId:false,defaultDescription:"Memory system status (factsCount / nodesCount / edgesCount / fts / vector).",readOnlyHint:true,destructiveHint:false,idempotentHint:true},handler:async(t,e)=>{let n=t??{};return st({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:e.remote??false,config:e.config,agentId:e.agentId},n)}};var Ae={name:"doctor",scope:"admin",schema:ze,annotations:{localOnly:true,requiresAgentId:false,defaultDescription:"Run 7 health checks (database / fts / vector / schema / lock / disk_space / orphan).",readOnlyHint:true,destructiveHint:false,idempotentHint:true},handler:async(t,e)=>{let n=t??{};if(!e.isTrustedLocal)throw new Error("doctor: only trusted local process can invoke this op");return ct({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:false,config:e.config,agentId:e.agentId},n)}};var xe={name:"init",scope:"admin",schema:Be,annotations:{localOnly:true,requiresAgentId:false,defaultDescription:"Initialize memory workspace (dirs + db schema + meta).",readOnlyHint:false,destructiveHint:false,idempotentHint:true},handler:async(t,e)=>{if(!e.isTrustedLocal)throw new Error("init: only trusted local process can invoke this op");let n=t??{};return at({workspaceDir:n.workspaceDir??e.workspaceDir??"",rootDir:n.workspaceDir??e.workspaceDir??"",dbPath:n.dbPath??e.dbPath??"",locale:e.locale??"en-US",remote:false,config:e.config,agentId:e.agentId??""},n)}};var dt={[De.name]:De,[ve.name]:ve,[Ce.name]:Ce,[Oe.name]:Oe,[Ne.name]:Ne,[Te.name]:Te,[Pe.name]:Pe,[ke.name]:ke,[Ae.name]:Ae,[xe.name]:xe},yr=Object.values(dt);function hr(t,e,n){if(t.annotations.localOnly&&!e.isTrustedLocal)throw new Error(`MEMORY:executeOp: op "${n}" is localOnly; non-trusted caller rejected`);if(t.annotations.requiresAgentId){let r=e.agentId?.trim()??"";if(r.length===0)throw new Error(`MEMORY:executeOp: op "${n}" requires agentId`);e.agentId=r;}}async function Ra(t,e,n){let r=dt[t];if(!r)throw new Error(`executeOp: unknown op "${t}"; available: ${yr.map(c=>c.name).join(", ")}`);return hr(r,n,t),await r.handler(e,n)}function wr(t){let e=t.dbPath??"";return {workspaceDir:t.workspaceDir??"",database:{path:e},embeddingLlm:chunkJ5XF2W4Z_cjs.a.getEmbeddingLlm(),graphLlm:chunkJ5XF2W4Z_cjs.a.getGraphLlm(),search:types.DEFAULT_SEARCH_CONFIG,indexer:{batchSize:20,ignorePatterns:[],incremental:true},archiveDays:30,shortTermMaxRounds:20}}function Na(t,e,n={}){let r=chunkCPRDIUQ4_cjs.j(e),o=utils.Locale.resolveLocaleLang(n.locale);return {agentId:t,dbPath:r,workspaceDir:e,rootDir:e,config:wr({dbPath:r,workspaceDir:e}),isTrustedLocal:true,locale:o,remote:false,...n}}exports.a=J;exports.b=Fe;exports.c=qe;exports.d=$e;exports.e=He;exports.f=Ue;exports.g=We;exports.h=je;exports.i=Be;exports.j=Qe;exports.k=Je;exports.l=Ye;exports.m=Xe;exports.n=Ze;exports.o=rt;exports.p=ot;exports.q=at;exports.r=st;exports.s=ct;exports.t=dt;exports.u=yr;exports.v=Ra;exports.w=wr;exports.x=Na;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
'use strict';var chunkAYGZUNFR_cjs=require('./chunk-AYGZUNFR.cjs');require('./chunk-CPRDIUQ4.cjs'),require('./chunk-NVGACA7W.cjs');Object.defineProperty(exports,"COMMANDS_HELP",{enumerable:true,get:function(){return chunkAYGZUNFR_cjs.a}});Object.defineProperty(exports,"handleMemoryCli",{enumerable:true,get:function(){return chunkAYGZUNFR_cjs.d}});Object.defineProperty(exports,"renderBanner",{enumerable:true,get:function(){return chunkAYGZUNFR_cjs.b}});Object.defineProperty(exports,"renderHelp",{enumerable:true,get:function(){return chunkAYGZUNFR_cjs.c}});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export{a as COMMANDS_HELP,d as handleMemoryCli,b as renderBanner,c as renderHelp}from'./chunk-TIZCWDJ7.mjs';import'./chunk-WDVDYZ25.mjs';import'./chunk-HQBRVVXS.mjs';
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
'use strict';var chunk4GSXSIV5_cjs=require('./chunk-4GSXSIV5.cjs');require('./chunk-WQB4D6DZ.cjs');var chunkZ5E4HBGK_cjs=require('./chunk-Z5E4HBGK.cjs');require('./chunk-EGWJG65Q.cjs'),require('./chunk-CPRDIUQ4.cjs'),require('./chunk-J5XF2W4Z.cjs'),require('./chunk-NVGACA7W.cjs');async function m(t){let n=t.agentId?.trim()||"default",o=t.workspaceDir??process.cwd();return chunkZ5E4HBGK_cjs.v("consolidate",{windowDays:t.windowDays??30,dryRun:false},chunkZ5E4HBGK_cjs.x(n,o))}function C(t){let n=t;return [chunk4GSXSIV5_cjs.b("consolidate",{},"Consolidation complete ({{totalFacts}} total / deduped {{dedupedCount}} / archived {{archivedCount}}):"),chunk4GSXSIV5_cjs.c("consolidate",{totalFacts:String(n.totalFacts),dedupedCount:String(n.dedupedCount),archivedCount:String(n.archivedCount)}," - total: {{totalFacts}}, deduped: {{dedupedCount}}, archived: {{archivedCount}}"),` - skipped: ${n.skippedCount}, duration: ${n.durationMs}ms`].join(`
|
|
2
|
+
`)}function f(t){let n={};for(let o=0;o<t.length;o++){let e=t[o];if(e===void 0)continue;let i=t[o+1];e==="--agent"?(n.agentId=i,o++):e==="--window-days"?(n.windowDays=Number(i),o++):e==="--json"?n.json=true:(e==="--help"||e==="-h")&&(n.help=true);}return n}exports.formatConsolidateText=C;exports.parseConsolidateOptions=f;exports.runConsolidate=m;
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {b,c}from'./chunk-QYBWHFOX.mjs';import'./chunk-SWYQLQ7Z.mjs';import {v,x}from'./chunk-UF2Y2Q4L.mjs';import'./chunk-JDPZ5U53.mjs';import'./chunk-WDVDYZ25.mjs';import'./chunk-6CQMBEIQ.mjs';import'./chunk-HQBRVVXS.mjs';async function C(t){let n=t.agentId?.trim()||"default",o=t.workspaceDir??process.cwd();return v("consolidate",{windowDays:t.windowDays??30,dryRun:false},x(n,o))}function f(t){let n=t;return [b("consolidate",{},"Consolidation complete ({{totalFacts}} total / deduped {{dedupedCount}} / archived {{archivedCount}}):"),c("consolidate",{totalFacts:String(n.totalFacts),dedupedCount:String(n.dedupedCount),archivedCount:String(n.archivedCount)}," - total: {{totalFacts}}, deduped: {{dedupedCount}}, archived: {{archivedCount}}"),` - skipped: ${n.skippedCount}, duration: ${n.durationMs}ms`].join(`
|
|
2
|
+
`)}function w(t){let n={};for(let o=0;o<t.length;o++){let e=t[o];if(e===void 0)continue;let i=t[o+1];e==="--agent"?(n.agentId=i,o++):e==="--window-days"?(n.windowDays=Number(i),o++):e==="--json"?n.json=true:(e==="--help"||e==="-h")&&(n.help=true);}return n}export{f as formatConsolidateText,w as parseConsolidateOptions,C as runConsolidate};
|