@easbot/memory 0.3.28 → 0.3.32

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.
Files changed (101) hide show
  1. package/README.en.md +1 -1
  2. package/README.md +21 -1
  3. package/dist/chunks/cache-IGJVAUPS.cjs +1 -0
  4. package/dist/chunks/cache-U5YYUDWO.mjs +1 -0
  5. package/dist/chunks/chunk-6H5PTRZL.cjs +1 -0
  6. package/dist/chunks/chunk-7C2J2PDC.cjs +77 -0
  7. package/dist/chunks/chunk-AEAMQDNV.mjs +67 -0
  8. package/dist/chunks/chunk-AJDMZTCQ.mjs +1 -0
  9. package/dist/chunks/chunk-AVECFV5K.cjs +1 -0
  10. package/dist/chunks/{chunk-P45OBSAC.cjs → chunk-DYD3SEPC.cjs} +19 -19
  11. package/dist/chunks/chunk-EKSLNNMF.cjs +1 -0
  12. package/dist/chunks/{chunk-I5YSX4DQ.mjs → chunk-FZ3RTYIJ.mjs} +19 -19
  13. package/dist/chunks/chunk-GCVKM3RJ.cjs +1 -0
  14. package/dist/chunks/chunk-HH7EA2UE.mjs +1 -0
  15. package/dist/chunks/chunk-HX3TV7FD.mjs +1 -0
  16. package/dist/chunks/chunk-KFESJR3T.cjs +1 -0
  17. package/dist/chunks/chunk-NHRRIJFK.cjs +1 -0
  18. package/dist/chunks/chunk-S4DPVKMV.mjs +1 -0
  19. package/dist/chunks/chunk-SE3F5YQE.mjs +1 -0
  20. package/dist/chunks/chunk-YAF6HMAE.cjs +67 -0
  21. package/dist/chunks/chunk-YJLHS7JB.mjs +77 -0
  22. package/dist/chunks/chunk-YUWHNHAY.mjs +1 -0
  23. package/dist/chunks/cli-handler-IXFJAQFB.cjs +1 -0
  24. package/dist/chunks/cli-handler-JHSDGJHK.mjs +1 -0
  25. package/dist/chunks/{config-2SQJYVTO.mjs → config-5P7O45FH.mjs} +1 -1
  26. package/dist/chunks/{config-I2I6U4XM.cjs → config-KFPQDFJR.cjs} +1 -1
  27. package/dist/chunks/consolidate-KZAYROKJ.cjs +2 -0
  28. package/dist/chunks/consolidate-OOAMW7XW.mjs +2 -0
  29. package/dist/chunks/doctor-OAWL5FMH.cjs +1 -0
  30. package/dist/chunks/doctor-ZGHICE2Q.mjs +1 -0
  31. package/dist/chunks/extract-AJY2ETKE.mjs +2 -0
  32. package/dist/chunks/extract-BS6HOLXU.cjs +2 -0
  33. package/dist/chunks/forget-NIBBY6FG.mjs +3 -0
  34. package/dist/chunks/forget-Q6UN6GSW.cjs +3 -0
  35. package/dist/chunks/graph-4K56ZAVL.mjs +3 -0
  36. package/dist/chunks/graph-4KBXGMOL.cjs +3 -0
  37. package/dist/chunks/init-EBA3ZGC6.cjs +1 -0
  38. package/dist/chunks/init-HWR4SD6N.mjs +1 -0
  39. package/dist/chunks/{interfaces-LPJU4KS3.mjs → interfaces-OFM2XGSG.mjs} +1 -1
  40. package/dist/chunks/interfaces-TGSOKRFI.cjs +1 -0
  41. package/dist/chunks/llm-BRSMYENV.mjs +1 -0
  42. package/dist/chunks/llm-TQXCNG4J.cjs +1 -0
  43. package/dist/chunks/mcp-PH3CLOYP.cjs +1 -0
  44. package/dist/chunks/mcp-ZWZYH52C.mjs +1 -0
  45. package/dist/chunks/{recall-UQSG6ECA.mjs → recall-BRXHJPR4.mjs} +2 -2
  46. package/dist/chunks/recall-SBUTMJPU.cjs +2 -0
  47. package/dist/chunks/remember-3XSYCWKK.mjs +2 -0
  48. package/dist/chunks/remember-FXMXYHLK.cjs +2 -0
  49. package/dist/chunks/status-H4UKSZAH.cjs +1 -0
  50. package/dist/chunks/status-SW5BUHJ3.mjs +1 -0
  51. package/dist/chunks/stdio-server-3A3H4YJ7.mjs +1 -0
  52. package/dist/chunks/stdio-server-CWA2HGXA.cjs +1 -0
  53. package/dist/chunks/sync-EE4ZD3WB.mjs +2 -0
  54. package/dist/chunks/sync-FTZT6MWJ.cjs +2 -0
  55. package/dist/cli.cjs +1 -1
  56. package/dist/cli.mjs +1 -1
  57. package/dist/index.cjs +1 -6
  58. package/dist/index.d.cts +50 -78
  59. package/dist/index.d.ts +50 -78
  60. package/dist/index.mjs +1 -6
  61. package/package.json +9 -10
  62. package/dist/chunks/chunk-4YADRVIU.mjs +0 -1
  63. package/dist/chunks/chunk-6CQMBEIQ.mjs +0 -1
  64. package/dist/chunks/chunk-CPRDIUQ4.cjs +0 -1
  65. package/dist/chunks/chunk-DW3CJUBO.cjs +0 -1
  66. package/dist/chunks/chunk-FY4ILCIM.mjs +0 -77
  67. package/dist/chunks/chunk-HQBRVVXS.mjs +0 -1
  68. package/dist/chunks/chunk-HY2LFKG7.cjs +0 -67
  69. package/dist/chunks/chunk-J5XF2W4Z.cjs +0 -1
  70. package/dist/chunks/chunk-LYBUZDJK.cjs +0 -77
  71. package/dist/chunks/chunk-M2YU5LAI.cjs +0 -1
  72. package/dist/chunks/chunk-WDVDYZ25.mjs +0 -1
  73. package/dist/chunks/chunk-X7P7ZFZF.mjs +0 -67
  74. package/dist/chunks/cli-handler-ETHJPZPG.mjs +0 -1
  75. package/dist/chunks/cli-handler-PG4IBTY2.cjs +0 -1
  76. package/dist/chunks/consolidate-7GFUFPLX.cjs +0 -2
  77. package/dist/chunks/consolidate-BGMXJUQX.mjs +0 -2
  78. package/dist/chunks/doctor-C2FWFUDO.mjs +0 -1
  79. package/dist/chunks/doctor-SCXUJRSG.cjs +0 -1
  80. package/dist/chunks/extract-O4IOL6BZ.cjs +0 -2
  81. package/dist/chunks/extract-RBBSVK2S.mjs +0 -2
  82. package/dist/chunks/forget-JTACRG7Y.mjs +0 -3
  83. package/dist/chunks/forget-M4I6GVWI.cjs +0 -3
  84. package/dist/chunks/graph-AOMDJ6YA.cjs +0 -3
  85. package/dist/chunks/graph-VBVVRV6V.mjs +0 -3
  86. package/dist/chunks/init-2SBK7ZWO.mjs +0 -1
  87. package/dist/chunks/init-VTPJR56L.cjs +0 -1
  88. package/dist/chunks/interfaces-Q5OGU5EK.cjs +0 -1
  89. package/dist/chunks/llm-7LQGYSUE.cjs +0 -1
  90. package/dist/chunks/llm-UHTBU2HA.mjs +0 -1
  91. package/dist/chunks/mcp-VIOHPDO5.cjs +0 -1
  92. package/dist/chunks/mcp-ZQCLVZIR.mjs +0 -1
  93. package/dist/chunks/recall-JSTQDGGZ.cjs +0 -2
  94. package/dist/chunks/remember-GVQJ5G7Z.mjs +0 -2
  95. package/dist/chunks/remember-Z4UJJN62.cjs +0 -2
  96. package/dist/chunks/status-DH33MQZV.cjs +0 -1
  97. package/dist/chunks/status-VZ5EBAOY.mjs +0 -1
  98. package/dist/chunks/stdio-server-JC53PUET.mjs +0 -1
  99. package/dist/chunks/stdio-server-OUZAN4IM.cjs +0 -1
  100. package/dist/chunks/sync-6I2ZJUH6.cjs +0 -2
  101. package/dist/chunks/sync-UT4D32ML.mjs +0 -2
@@ -1,24 +1,24 @@
1
- 'use strict';var chunkHY2LFKG7_cjs=require('./chunk-HY2LFKG7.cjs'),mcp=require('@easbot/mcp'),utils=require('@easbot/utils');var oe=utils.Log.create({service:"memory-format-truncate"}),J="**`";var X=24e3,Z=25e3;async function $(e,n={}){let o=n.softLimit??X,s=n.hardCeiling??Z,r=n.toolName??"memory",c=n.writeToDisk!==false;if(e.length<=o)return {content:e,truncated:false};let d=e.slice(0,s),t=d.lastIndexOf(`
2
- ${J}`),a=d.lastIndexOf(`
3
- `),m;t>s*.5?m=t:a>0?m=a:m=-1;let u=m>0?d.slice(0,m):d,i=u+"\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:i,truncated:true,outputPath:"",hint:"Make another recall / graph_query with narrower scope.",info:`... ${e.length-u.length}/${e.length} characters truncated ...`};try{let p=await utils.TruncateContent.truncate(e,{maxChars:u.length,direction:"head",label:`${r}-output`});return p.truncated?{content:i,truncated:!0,outputPath:p.outputPath,hint:utils.TruncateContent.formatHint(p),info:`... ${p.removedLength}/${p.originalLength} characters truncated ...`}:{content:i,truncated:!0,outputPath:"",hint:"Make another recall / graph_query with narrower scope.",info:`... ${e.length-u.length}/${e.length} characters truncated ...`}}catch(p){return oe.warn("TruncateContent.truncate failed, returning without disk hint",{error:p instanceof Error?p.message:String(p)}),{content:i,truncated:true,outputPath:"",hint:"Make another recall / graph_query with narrower scope.",info:`... ${e.length-u.length}/${e.length} characters truncated ...`}}}function w(e,n={}){let o=n.softLimit??X,s=n.hardCeiling??Z;if(e.length<=o)return {content:e,truncated:false};let r=e.slice(0,s),c=r.lastIndexOf(`
4
- ${J}`),d=r.lastIndexOf(`
1
+ 'use strict';var chunkYAF6HMAE_cjs=require('./chunk-YAF6HMAE.cjs'),chunkAVECFV5K_cjs=require('./chunk-AVECFV5K.cjs'),mcp=require('@easbot/mcp'),utils=require('@easbot/utils');var ie=utils.Log.create({service:"memory.format.truncate"}),X="**`";var Z=24e3,ee=25e3;async function $(e,n={}){let o=n.softLimit??Z,s=n.hardCeiling??ee,r=n.toolName??"memory",c=n.writeToDisk!==false;if(e.length<=o)return {content:e,truncated:false};let d=e.slice(0,s),t=d.lastIndexOf(`
2
+ ${X}`),a=d.lastIndexOf(`
3
+ `),m;t>s*.5?m=t:a>0?m=a:m=-1;let u=m>0?d.slice(0,m):d,i=u+"\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:i,truncated:true,outputPath:"",hint:"Make another recall / graph_query with narrower scope.",info:`... ${e.length-u.length}/${e.length} characters truncated ...`};try{let f=await utils.TruncateContent.truncate(e,{maxChars:u.length,direction:"head",label:`${r}-output`});return f.truncated?{content:i,truncated:!0,outputPath:f.outputPath,hint:utils.TruncateContent.formatHint(f),info:`... ${f.removedLength}/${f.originalLength} characters truncated ...`}:{content:i,truncated:!0,outputPath:"",hint:"Make another recall / graph_query with narrower scope.",info:`... ${e.length-u.length}/${e.length} characters truncated ...`}}catch(f){return ie.warn("TruncateContent.truncate failed, returning without disk hint",{error:utils.errorMeta(f)}),{content:i,truncated:true,outputPath:"",hint:"Make another recall / graph_query with narrower scope.",info:`... ${e.length-u.length}/${e.length} characters truncated ...`}}}function w(e,n={}){let o=n.softLimit??Z,s=n.hardCeiling??ee;if(e.length<=o)return {content:e,truncated:false};let r=e.slice(0,s),c=r.lastIndexOf(`
4
+ ${X}`),d=r.lastIndexOf(`
5
5
  `),t;c>s*.5?t=c:d>0?t=d:t=-1;let a=t>0?r.slice(0,t):r;return {content:a+`
6
6
 
7
- ... (output truncated; tail dropped at section boundary)`,truncated:true,outputPath:"",hint:"",info:`... ${e.length-a.length}/${e.length} characters truncated ...`}}function ae(e,n){if(!e||e.length===0)return null;let o=e.filter(r=>n.has(r.path));return o.length===0?null:`\u26A0\uFE0F Index may be stale for: ${o.map(r=>`${r.path} (edited pending)`).join(", ")}
7
+ ... (output truncated; tail dropped at section boundary)`,truncated:true,outputPath:"",hint:"",info:`... ${e.length-a.length}/${e.length} characters truncated ...`}}function de(e,n){if(!e||e.length===0)return null;let o=e.filter(r=>n.has(r.path));return o.length===0?null:`\u26A0\uFE0F Index may be stale for: ${o.map(r=>`${r.path} (edited pending)`).join(", ")}
8
8
 
9
- `}function I(e,n,o={}){return (ee[e]??ee.default).replace(/<(\w+)>/g,(r,c)=>c==="tool"?n:o[c]??`<${c}>`)}var ee={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 se(e){let n=Array.isArray(e.edges)?e.edges.length:0;return ` - node #${e.id}: ${e.name} (${e.type}) [edges: ${n}]`}function te(e,n,o,s){let r=e.tags&&e.tags.length>0?`
9
+ `}function I(e,n,o={}){return (te[e]??te.default).replace(/<(\w+)>/g,(r,c)=>c==="tool"?n:o[c]??`<${c}>`)}var te={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 ce(e){let n=Array.isArray(e.edges)?e.edges.length:0;return ` - node #${e.id}: ${e.name} (${e.type}) [edges: ${n}]`}function ne(e,n,o,s){let r=e.tags&&e.tags.length>0?`
10
10
  - tags: ${e.tags.join(", ")}`:"",c=e.sessionId?`
11
11
  - session: ${e.sessionId}`:"",d=e.msgId?`
12
12
  - msg: ${e.msgId}`:"",t=typeof n=="number"?`
13
- - score: ${n.toFixed(3)}${o?` (${o})`:""}`:"",a=e.truncated?" [truncated]":"",m="";if(s&&s.length>0){let u=s.map(se);m=`
13
+ - score: ${n.toFixed(3)}${o?` (${o})`:""}`:"",a=e.truncated?" [truncated]":"",m="";if(s&&s.length>0){let u=s.map(ce);m=`
14
14
  - linked KG nodes (${s.length}) \u2014 use \`graph_query(nodeId=<id>)\` for full relation graph:
15
15
  ${u.join(`
16
16
  `)}`;}return [`### \`${e.id}\`${a}`,` - agentId: ${e.agentId}`,` - category: ${e.category}`,` - importance: ${e.importance}`,` - createdAt: ${e.createdAt}`,` - updatedAt: ${e.updatedAt}`,` - source: ${e.source}${t}${r}${c}${d}${m}`,"",e.content,""].join(`
17
- `)}async function k(e,n){let o=n.toolName??"memory_recall",s=`**\`memory_recall:${n.query.slice(0,40).replace(/[^a-zA-Z0-9_]/g,"_")}\`**`,r=ae(n.pendingFiles,new Set),d=[`Found ${e.total} fact(s) for query "${n.query}" (agentId=${n.agentId}, scope=${n.scope}):`,"",r??"",s].join(`
18
- `),t=new Map;for(let l of e.hits){let i=l.fact.category;t.has(i)||t.set(i,[]),t.get(i).push(l);}let a=Array.from(t.entries()).map(([l,i])=>{let p=`**\`category:${l}\`**`,h=i.map(f=>te(f.fact,f.score,f.source,f.nodes)).join(`
19
- `);return `${p}
17
+ `)}async function v(e,n){let o=n.toolName??"memory_recall",s=`**\`memory_recall:${n.query.slice(0,40).replace(/[^a-zA-Z0-9_]/g,"_")}\`**`,r=de(n.pendingFiles,new Set),d=[`Found ${e.total} fact(s) for query "${n.query}" (agentId=${n.agentId}, scope=${n.scope}):`,"",r??"",s].join(`
18
+ `),t=new Map;for(let l of e.hits){let i=l.fact.category;t.has(i)||t.set(i,[]),t.get(i).push(l);}let a=Array.from(t.entries()).map(([l,i])=>{let f=`**\`category:${l}\`**`,p=i.map(g=>ne(g.fact,g.score,g.source,g.nodes)).join(`
19
+ `);return `${f}
20
20
 
21
- ${h}`}).join(`
21
+ ${p}`}).join(`
22
22
  `),m=e.warnings&&e.warnings.length>0?`
23
23
 
24
24
  \u26A0\uFE0F warnings:
@@ -28,7 +28,7 @@ ${e.warnings.map(l=>` - ${l}`).join(`
28
28
 
29
29
  ${a}${m}
30
30
 
31
- ${I("recall",o)}`;return n.sync?w(u,{}).content:(await $(u,{toolName:o,writeToDisk:n.writeToDisk})).content}async function v(e,n={}){let o=n.toolName??"memory_remember",s=`**\`memory_remember:${e.fact.id}\`**`,r=te(e.fact),c=e.nodeIds??[],d=c.length>0?`
31
+ ${I("recall",o)}`;return n.sync?w(u,{}).content:(await $(u,{toolName:o,writeToDisk:n.writeToDisk})).content}async function M(e,n={}){let o=n.toolName??"memory_remember",s=`**\`memory_remember:${e.fact.id}\`**`,r=ne(e.fact),c=e.nodeIds??[],d=c.length>0?`
32
32
  - linked KG nodes: ${c.join(", ")}
33
33
  `:"",t=`${s}
34
34
 
@@ -41,24 +41,24 @@ ${e.deletedIds.map(t=>` - ${t}`).join(`
41
41
  `),c=e.edges.map(t=>` - edge #${t.id}: ${t.source} --${t.relation}--> ${t.target}`).join(`
42
42
  `),d=[s,"",`nodes (${e.nodes.length}${e.truncated?` / total ${e.totalNodes}`:""}):`,r||" (none)","",`edges (${e.edges.length}${e.truncated?` / total ${e.totalEdges}`:""}):`,c||" (none)","",I("graph_query",o)].join(`
43
43
  `);return n.sync?w(d,{}).content:(await $(d,{toolName:o,writeToDisk:n.writeToDisk})).content}async function N(e,n={}){let o=n.toolName??"memory_status",r=["**`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"}`,`healthy: ${e.healthy?"yes":"no"}`,"","factsByCategory:",...Object.entries(e.factsByCategory).map(([d,t])=>` - ${d}: ${t}`),"","meta:",...Object.entries(e.meta).map(([d,t])=>` - ${d}: ${t}`)];if(e.integrityStats&&Object.keys(e.integrityStats).length>0){r.push("","DB stats:");let d=Math.max(...Object.keys(e.integrityStats).map(t=>t.length));for(let[t,a]of Object.entries(e.integrityStats))r.push(` - ${t.padEnd(d)} ${a}`);}r.push("",I("status",o));let c=r.join(`
44
- `);return n.sync?w(c,{}).content:(await $(c,{toolName:o,writeToDisk:n.writeToDisk})).content}async function M(e,n={}){let o=n.toolName??"memory_consolidate",r=["**`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",o)].join(`
45
- `);return n.sync?w(r,{}).content:(await $(r,{toolName:o,writeToDisk:n.writeToDisk})).content}var S=20;async function O(e,n={}){let o=n.toolName??"memory_sync",r=[`**\`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){r.push("","### Archived records:");let d=e.archivedRecords.slice(0,S);for(let t of d)r.push(`- ${t.firstFactId} (${t.firstCreatedAt})`),r.push(` - source: \`${t.source}\``),r.push(` - target: \`${t.target}\``);e.archivedRecords.length>S&&r.push(`... and ${e.archivedRecords.length-S} more (use --json for full list)`);}r.push("",`duration: ${e.durationMs}ms`,"",I("sync",o));let c=r.join(`
46
- `);return n.sync?w(c,{}).content:(await $(c,{toolName:o,writeToDisk:n.writeToDisk})).content}async function P(e,n={}){let o=n.toolName??"memory_doctor",s=`**\`memory_doctor:${e.healthy?"OK":"ISSUES"}\`**`,r=t=>t?"\u2705":"\u274C",c=e.checks.map(t=>`${r(t.passed)} ${t.name}: ${t.message}`).join(`
44
+ `);return n.sync?w(c,{}).content:(await $(c,{toolName:o,writeToDisk:n.writeToDisk})).content}async function O(e,n={}){let o=n.toolName??"memory_consolidate",r=["**`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",o)].join(`
45
+ `);return n.sync?w(r,{}).content:(await $(r,{toolName:o,writeToDisk:n.writeToDisk})).content}var S=20;async function P(e,n={}){let o=n.toolName??"memory_sync",r=[`**\`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){r.push("","### Archived records:");let d=e.archivedRecords.slice(0,S);for(let t of d)r.push(`- ${t.firstFactId} (${t.firstCreatedAt})`),r.push(` - source: \`${t.source}\``),r.push(` - target: \`${t.target}\``);e.archivedRecords.length>S&&r.push(`... and ${e.archivedRecords.length-S} more (use --json for full list)`);}r.push("",`duration: ${e.durationMs}ms`,"",I("sync",o));let c=r.join(`
46
+ `);return n.sync?w(c,{}).content:(await $(c,{toolName:o,writeToDisk:n.writeToDisk})).content}async function j(e,n={}){let o=n.toolName??"memory_doctor",s=`**\`memory_doctor:${e.healthy?"OK":"ISSUES"}\`**`,r=t=>t?"\u2705":"\u274C",c=e.checks.map(t=>`${r(t.passed)} ${t.name}: ${t.message}`).join(`
47
47
  `),d=[s,"",c,"",I("doctor",o)].join(`
48
- `);return n.sync?w(d,{}).content:(await $(d,{toolName:o,writeToDisk:n.writeToDisk})).content}async function R(e,n,o={}){let s=n,r=typeof s.kind=="string";switch((r?s:{kind:e}).kind){case "recall":{let d=r?{hits:s.hits,total:s.totalCount??s.total??0,truncated:s.truncated??false}:n;return k(d,{...o,query:s.query??o.query??"",agentId:s.agentId??o.agentId??"",scope:s.scope??o.scope??"agent_only"})}case "remember":{let d=r?{fact:s.fact,nodeIds:s.nodeIds}:n;return v(d,o)}case "forget":return A(r?s:n,o);case "graph_query":return _(r?s:n,o);case "status":return N(r?s:n,o);case "consolidate":return M(r?s:n,o);case "sync":return O(r?s:n,o);case "doctor":return P(r?s:n,o);default:throw new Error(`renderOperationMarkdown: unsupported op "${e}"`)}}var x=utils.Log.create({service:"memory-mcp-stdio"});function Ie(e){let n=new Map,o=e.isRemote??true,s=!o;function r(t){let a=utils.Locale.resolveLocaleLang();return {agentId:t.agentId??e.agentId,isTrustedLocal:t.isTrustedLocal??s,remote:o,locale:a,dbPath:e.dbPath,workspaceDir:e.workspaceDir,rootDir:e.workspaceDir,config:chunkHY2LFKG7_cjs.A({agentId:e.agentId,dbPath:e.dbPath})}}function c(t,a){return {content:[{type:"text",text:t}],isError:a}}function d(t){return mcp.formatFailClosed(t,s)}return n.set("recall",async t=>{try{let a=t,m=r({agentId:a.agentId}),u=await chunkHY2LFKG7_cjs.z("recall",t,m);return {content:[{type:"text",text:await R("recall",u,{toolName:"memory_recall",query:a.query,agentId:a.agentId??e.agentId,scope:a.scope??"agent_only"})}]}}catch(a){return c(d(a),true)}}),n.set("remember",async t=>{try{let m=r({agentId:t.agentId}),u=await chunkHY2LFKG7_cjs.z("remember",t,m);return {content:[{type:"text",text:await R("remember",u,{toolName:"memory_remember"})}]}}catch(a){return c(d(a),true)}}),n.set("update",async t=>{try{let m=r({agentId:t.agentId}),u=await chunkHY2LFKG7_cjs.z("update",t,m),l=u.fieldsUpdated.length>0?u.fieldsUpdated.join(", "):"(no-op)",i=u.contentChanged?" (embedding rewritten)":"";return {content:[{type:"text",text:`Memory updated.
48
+ `);return n.sync?w(d,{}).content:(await $(d,{toolName:o,writeToDisk:n.writeToDisk})).content}async function R(e,n,o={}){let s=n,r=typeof s.kind=="string";switch((r?s:{kind:e}).kind){case "recall":{let d=r?{hits:s.hits,total:s.totalCount??s.total??0,truncated:s.truncated??false}:n;return v(d,{...o,query:s.query??o.query??"",agentId:s.agentId??o.agentId??"",scope:s.scope??o.scope??"agent_only"})}case "remember":{let d=r?{fact:s.fact,nodeIds:s.nodeIds}:n;return M(d,o)}case "forget":return A(r?s:n,o);case "graph_query":return _(r?s:n,o);case "status":return N(r?s:n,o);case "consolidate":return O(r?s:n,o);case "sync":return P(r?s:n,o);case "doctor":return j(r?s:n,o);default:throw new chunkAVECFV5K_cjs.a.UnsupportedOperationError({message:`renderOperationMarkdown: unsupported op "${e}"`,opName:e,renderer:"markdown"})}}var D=utils.Log.create({service:"memory.mcp.stdio"});function Te(e){let n=new Map,o=e.isRemote??true,s=!o;function r(t){let a=utils.Locale.resolveLocaleLang();return {agentId:t.agentId??e.agentId,isTrustedLocal:t.isTrustedLocal??s,remote:o,locale:a,dbPath:e.dbPath,workspaceDir:e.workspaceDir,rootDir:e.workspaceDir,config:chunkYAF6HMAE_cjs.A({agentId:e.agentId,dbPath:e.dbPath})}}function c(t,a){return {content:[{type:"text",text:t}],isError:a}}function d(t){return mcp.formatFailClosed(t,s)}return n.set("recall",async t=>{try{let a=t,m=r({agentId:a.agentId}),u=await chunkYAF6HMAE_cjs.z("recall",t,m);return {content:[{type:"text",text:await R("recall",u,{toolName:"memory_recall",query:a.query,agentId:a.agentId??e.agentId,scope:a.scope??"agent_only"})}]}}catch(a){return c(d(a),true)}}),n.set("remember",async t=>{try{let m=r({agentId:t.agentId}),u=await chunkYAF6HMAE_cjs.z("remember",t,m);return {content:[{type:"text",text:await R("remember",u,{toolName:"memory_remember"})}]}}catch(a){return c(d(a),true)}}),n.set("update",async t=>{try{let m=r({agentId:t.agentId}),u=await chunkYAF6HMAE_cjs.z("update",t,m),l=u.fieldsUpdated.length>0?u.fieldsUpdated.join(", "):"(no-op)",i=u.contentChanged?" (embedding rewritten)":"";return {content:[{type:"text",text:`Memory updated.
49
49
  id: ${u.fact.id}
50
50
  category: ${u.fact.category}
51
51
  importance: ${u.fact.importance}
52
52
  fields updated: ${l}${i}
53
53
  updated_at: ${u.fact.updatedAt}
54
- `}]}}catch(a){return c(d(a),true)}}),n.set("forget",async t=>{try{let m=r({agentId:t.agentId}),u=await chunkHY2LFKG7_cjs.z("forget",t,m);return {content:[{type:"text",text:await R("forget",u,{toolName:"memory_forget"})}]}}catch(a){return c(d(a),true)}}),n.set("extract",async t=>{try{let m=r({agentId:t.agentId}),l=await chunkHY2LFKG7_cjs.z("extract",t,m);return {content:[{type:"text",text:`Extract completed.
54
+ `}]}}catch(a){return c(d(a),true)}}),n.set("forget",async t=>{try{let m=r({agentId:t.agentId}),u=await chunkYAF6HMAE_cjs.z("forget",t,m);return {content:[{type:"text",text:await R("forget",u,{toolName:"memory_forget"})}]}}catch(a){return c(d(a),true)}}),n.set("extract",async t=>{try{let m=r({agentId:t.agentId}),l=await chunkYAF6HMAE_cjs.z("extract",t,m);return {content:[{type:"text",text:`Extract completed.
55
55
  sessionId: ${t.sessionId??"(unknown)"}
56
56
  extractedCount: ${l.extractedCount}
57
57
  factIds: ${l.factIds.length>0?l.factIds.join(", "):"(none)"}
58
58
  messageRange: ${l.messageRange.fromMessageId} -> ${l.messageRange.toMessageId}
59
- `}]}}catch(a){return c(d(a),true)}}),n.set("consolidate",async t=>{try{let m=r({agentId:t.agentId,isTrustedLocal:!0}),u=await chunkHY2LFKG7_cjs.z("consolidate",t,m);return {content:[{type:"text",text:await R("consolidate",u,{toolName:"memory_consolidate"})}]}}catch(a){return c(d(a),true)}}),n.set("sync",async t=>{try{let m=t.agentId?.trim();if(!m)return c(d(new Error("memory_sync: agentId is required (sync requires agentId, see ADR 0069)")),!0);let u=r({agentId:m,isTrustedLocal:!0}),l=await chunkHY2LFKG7_cjs.z("sync",t,u);return {content:[{type:"text",text:await R("sync",l,{toolName:"memory_sync"})}]}}catch(a){return c(d(a),true)}}),n.set("graph_query",async t=>{try{let a=t,m=r({agentId:a.agentId}),u=await chunkHY2LFKG7_cjs.z("graph_query",t,m);return {content:[{type:"text",text:await R("graph_query",u,{toolName:"memory_graph_query",scope:a.scope??"agent_only"})}]}}catch(a){return c(d(a),true)}}),n.set("status",async t=>{try{let m=r({agentId:(t??{}).agentId}),u=await chunkHY2LFKG7_cjs.z("status",t,m),{renderKnowledgeStatus:l}=await import('@easbot/terminal'),i=u;return {content:[{type:"text",text:l({packageName:"memory",rootDir:i.workspaceDir??"",configPath:i.configPath??"",configExists:typeof i.configExists=="boolean"?i.configExists:!0,dbPath:i.dbPath??"",dbExists:typeof i.dbExists=="boolean"?i.dbExists:!0,dbSize:typeof i.dbSize=="number"?i.dbSize:void 0,indexState:i.indexState,schemaVersion:typeof i.schemaVersion=="number"?i.schemaVersion:void 0,extractionVersion:typeof i.extractionVersion=="number"?i.extractionVersion:void 0,lastSyncAt:i.lastSyncAt,vectorEnabled:typeof i.vectorEnabled=="boolean"?i.vectorEnabled:!1,embeddingDims:typeof i.embeddingDims=="number"?i.embeddingDims:void 0,llm:i.llm??{initialized:!1,capabilities:{}},backend:i.backend,healthy:typeof i.healthy=="boolean"?i.healthy:!0,recommendation:i.recommendation,dbStats:(()=>{let h=i.dbStats;if(h&&typeof h=="object"&&Object.keys(h).length>0)return {...h};let f=i.integrityStats;if(f&&typeof f=="object"&&Object.keys(f).length>0)return {...f}})(),extras:(()=>{let h={};if(typeof i.agentId=="string"&&(h.agent_id=i.agentId),typeof i.ftsAvailable=="boolean"&&(h.fts_available=i.ftsAvailable?"yes":"no"),i.factsByCategory&&typeof i.factsByCategory=="object")for(let[f,b]of Object.entries(i.factsByCategory))typeof b=="number"&&b>0&&(h[`facts/${f}`]=b);if(i.meta&&typeof i.meta=="object")for(let[f,b]of Object.entries(i.meta))b!==void 0&&(h[`meta/${f}`]=b);return Object.keys(h).length>0?h:void 0})()})}]}}catch(a){return c(d(a),true)}}),n.set("doctor",async t=>{try{let m=r({agentId:(t??{}).agentId,isTrustedLocal:!0}),u=await chunkHY2LFKG7_cjs.z("doctor",t,m);return {content:[{type:"text",text:await R("doctor",u,{toolName:"memory_doctor"})}]}}catch(a){return c(d(a),true)}}),n.set("init",async t=>{try{let a=r({isTrustedLocal:!0}),u=await chunkHY2LFKG7_cjs.z("init",t,a);return {content:[{type:"text",text:`Init complete.
59
+ `}]}}catch(a){return c(d(a),true)}}),n.set("consolidate",async t=>{try{let m=r({agentId:t.agentId,isTrustedLocal:!0}),u=await chunkYAF6HMAE_cjs.z("consolidate",t,m);return {content:[{type:"text",text:await R("consolidate",u,{toolName:"memory_consolidate"})}]}}catch(a){return c(d(a),true)}}),n.set("sync",async t=>{try{let m=t.agentId?.trim();if(!m)return c(d(new Error("memory_sync: agentId is required (sync requires agentId, see ADR 0069)")),!0);let u=r({agentId:m,isTrustedLocal:!0}),l=await chunkYAF6HMAE_cjs.z("sync",t,u);return {content:[{type:"text",text:await R("sync",l,{toolName:"memory_sync"})}]}}catch(a){return c(d(a),true)}}),n.set("graph_query",async t=>{try{let a=t,m=r({agentId:a.agentId}),u=await chunkYAF6HMAE_cjs.z("graph_query",t,m);return {content:[{type:"text",text:await R("graph_query",u,{toolName:"memory_graph_query",scope:a.scope??"agent_only"})}]}}catch(a){return c(d(a),true)}}),n.set("status",async t=>{try{let m=r({agentId:(t??{}).agentId}),u=await chunkYAF6HMAE_cjs.z("status",t,m),{renderKnowledgeStatus:l}=await import('@easbot/terminal'),i=u;return {content:[{type:"text",text:l({packageName:"memory",rootDir:i.workspaceDir??"",configPath:i.configPath??"",configExists:typeof i.configExists=="boolean"?i.configExists:!0,dbPath:i.dbPath??"",dbExists:typeof i.dbExists=="boolean"?i.dbExists:!0,dbSize:typeof i.dbSize=="number"?i.dbSize:void 0,indexState:i.indexState,schemaVersion:typeof i.schemaVersion=="number"?i.schemaVersion:void 0,extractionVersion:typeof i.extractionVersion=="number"?i.extractionVersion:void 0,lastSyncAt:i.lastSyncAt,vectorEnabled:typeof i.vectorEnabled=="boolean"?i.vectorEnabled:!1,embeddingDims:typeof i.embeddingDims=="number"?i.embeddingDims:void 0,llm:i.llm??{initialized:!1,capabilities:{}},backend:i.backend,healthy:typeof i.healthy=="boolean"?i.healthy:!0,recommendation:i.recommendation,dbStats:(()=>{let p=i.dbStats;if(p&&typeof p=="object"&&Object.keys(p).length>0)return {...p};let g=i.integrityStats;if(g&&typeof g=="object"&&Object.keys(g).length>0)return {...g}})(),extras:(()=>{let p={};if(typeof i.agentId=="string"&&(p.agent_id=i.agentId),typeof i.ftsAvailable=="boolean"&&(p.fts_available=i.ftsAvailable?"yes":"no"),i.factsByCategory&&typeof i.factsByCategory=="object")for(let[g,b]of Object.entries(i.factsByCategory))typeof b=="number"&&b>0&&(p[`facts/${g}`]=b);if(i.meta&&typeof i.meta=="object")for(let[g,b]of Object.entries(i.meta))b!==void 0&&(p[`meta/${g}`]=b);return Object.keys(p).length>0?p:void 0})()})}]}}catch(a){return c(d(a),true)}}),n.set("doctor",async t=>{try{let m=r({agentId:(t??{}).agentId,isTrustedLocal:!0}),u=await chunkYAF6HMAE_cjs.z("doctor",t,m);return {content:[{type:"text",text:await R("doctor",u,{toolName:"memory_doctor"})}]}}catch(a){return c(d(a),true)}}),n.set("init",async t=>{try{let a=r({isTrustedLocal:!0}),u=await chunkYAF6HMAE_cjs.z("init",t,a);return {content:[{type:"text",text:`Init complete.
60
60
  dbPath: ${u.dbPath}
61
61
  tablesCreated: ${u.tablesCreated}
62
62
  migrationsApplied: ${u.migrationsApplied}
63
63
  durationMs: ${u.durationMs}
64
- `}]}}catch(a){return c(d(a),true)}}),n}var Re={recall:chunkHY2LFKG7_cjs.c,remember:chunkHY2LFKG7_cjs.d,update:chunkHY2LFKG7_cjs.e,forget:chunkHY2LFKG7_cjs.f,extract:chunkHY2LFKG7_cjs.g,consolidate:chunkHY2LFKG7_cjs.h,sync:chunkHY2LFKG7_cjs.m,graph_query:chunkHY2LFKG7_cjs.i,status:chunkHY2LFKG7_cjs.j,doctor:chunkHY2LFKG7_cjs.k,init:chunkHY2LFKG7_cjs.l};function Ce(e,n){let o=chunkHY2LFKG7_cjs.x[e],s={title:o?.annotations?.defaultDescription??e,readOnlyHint:o?.annotations?.readOnlyHint??false,destructiveHint:o?.annotations?.destructiveHint??false,idempotentHint:o?.annotations?.idempotentHint??true,openWorldHint:false},r=Re[e];return {name:e,description:o?.annotations?.defaultDescription??`memory op: ${e}`,inputSchema:r??{type:"object",properties:{},required:[],additionalProperties:false},annotations:s,handler:n}}exports.b=void 0;(o=>{async function e(s,r){let{getMemoryDbPath:c,getInstance:d}=await import('./interfaces-Q5OGU5EK.cjs'),a=r!==null&&typeof r=="object"&&"agentId"in r&&"dbPath"in r?r:{agentId:process.env.EASBOT_AGENT_ID??"default",dbPath:c(),workspaceDir:d().worktree,isRemote:false};mcp.extendKnownErrorCodes(["AGENT_ID_REQUIRED","SESSION_ID_REQUIRED","CATEGORY_REQUIRED","IMPORTANCE_REQUIRED","TIMERANGE_REQUIRED","DRY_RUN_NO_DELETE"]);let m=new mcp.ToolRegistry,u=Ie(a),l=Object.keys(chunkHY2LFKG7_cjs.x);for(let g of l){let C=u.get(g);if(!C)throw new Error(`MemoryStdioServer.start: missing handler for tool "${g}"`);m.register(Ce(g,C));}x.info("starting memory MCP stdio server",{id:s.id,name:s.name,toolCount:l.length,isRemote:a.isRemote??true});let i=await mcp.createAndStartStdioServer(s,m),p=null,h=new Promise(g=>{p=g;}),f=g=>{x.info("received signal, stopping MCP server",{signal:g}),p?.();},b=()=>f("SIGINT"),D=()=>f("SIGTERM"),j=(g,C)=>process.listeners(g).includes(C);j("SIGINT",b)||process.on("SIGINT",b),j("SIGTERM",D)||process.on("SIGTERM",D);try{await h;}finally{try{process.off("SIGINT",b),process.off("SIGTERM",D);}catch(g){x.warn("failed to remove signal handlers",{error:g instanceof Error?g.message:String(g)});}try{await i.stop();}catch(g){x.warn("server.stop failed during cleanup",{error:g instanceof Error?g.message:String(g)});}}return {id:s.id,name:s.name,version:s.version,tools:l}}o.start=e;function n(){return Object.keys(chunkHY2LFKG7_cjs.x)}o.getToolNames=n;})(exports.b||(exports.b={}));exports.a=R;
64
+ `}]}}catch(a){return c(d(a),true)}}),n}var Ee={recall:chunkYAF6HMAE_cjs.c,remember:chunkYAF6HMAE_cjs.d,update:chunkYAF6HMAE_cjs.e,forget:chunkYAF6HMAE_cjs.f,extract:chunkYAF6HMAE_cjs.g,consolidate:chunkYAF6HMAE_cjs.h,sync:chunkYAF6HMAE_cjs.m,graph_query:chunkYAF6HMAE_cjs.i,status:chunkYAF6HMAE_cjs.j,doctor:chunkYAF6HMAE_cjs.k,init:chunkYAF6HMAE_cjs.l};function xe(e,n){let o=chunkYAF6HMAE_cjs.x[e],s={title:o?.annotations?.defaultDescription??e,readOnlyHint:o?.annotations?.readOnlyHint??false,destructiveHint:o?.annotations?.destructiveHint??false,idempotentHint:o?.annotations?.idempotentHint??true,openWorldHint:false},r=Ee[e];return {name:e,description:o?.annotations?.defaultDescription??`memory op: ${e}`,inputSchema:r??{type:"object",properties:{},required:[],additionalProperties:false},annotations:s,handler:n}}exports.b=void 0;(o=>{async function e(s,r){let{getMemoryDbPath:c,getInstance:d}=await import('./interfaces-TGSOKRFI.cjs'),a=r!==null&&typeof r=="object"&&"agentId"in r&&"dbPath"in r?r:{agentId:process.env.EASBOT_AGENT_ID??"default",dbPath:c(d().worktree),workspaceDir:d().worktree,isRemote:false};mcp.extendKnownErrorCodes(["AGENT_ID_REQUIRED","SESSION_ID_REQUIRED","CATEGORY_REQUIRED","IMPORTANCE_REQUIRED","TIMERANGE_REQUIRED","DRY_RUN_NO_DELETE"]);let m=new mcp.ToolRegistry,u=Te(a),l=Object.keys(chunkYAF6HMAE_cjs.x);for(let y of l){let C=u.get(y);if(!C)throw new chunkAVECFV5K_cjs.a.MissingMcpHandlerError({message:`MemoryStdioServer.start: missing handler for tool "${y}"`,toolName:y});m.register(xe(y,C));}D.info("starting memory MCP stdio server",{id:s.id,name:s.name,toolCount:l.length,isRemote:a.isRemote??true});let i=await mcp.createAndStartStdioServer(s,m),f=null,p=new Promise(y=>{f=y;}),g=y=>{D.info("received signal, stopping MCP server",{signal:y}),f?.();},b=()=>g("SIGINT"),k=()=>g("SIGTERM"),L=(y,C)=>process.listeners(y).includes(C);L("SIGINT",b)||process.on("SIGINT",b),L("SIGTERM",k)||process.on("SIGTERM",k);try{await p;}finally{try{process.off("SIGINT",b),process.off("SIGTERM",k);}catch(y){D.warn("failed to remove signal handlers",{error:utils.errorMeta(y)});}try{await i.stop();}catch(y){D.warn("server.stop failed during cleanup",{error:utils.errorMeta(y)});}}return {id:s.id,name:s.name,version:s.version,tools:l}}o.start=e;function n(){return Object.keys(chunkYAF6HMAE_cjs.x)}o.getToolNames=n;})(exports.b||(exports.b={}));exports.a=R;
@@ -0,0 +1 @@
1
+ 'use strict';var chunkAVECFV5K_cjs=require('./chunk-AVECFV5K.cjs'),utils=require('@easbot/utils'),llm=require('@easbot/llm');exports.a=void 0;(s=>{let g=utils.Log.create({service:"memory.llm"}),n=null;function x(t){if(u())return;let e=t;n={models:e.models,options:e.options??{}},llm.ModelManager.declare(n.models),g.debug("Llm initialized",{embeddingConfigured:!!e.models.embedding,graphConfigured:!!e.models.graph});}s.init=x;function u(){return n!==null}s.isInitialized=u;function M(){n=null,llm.ModelManager.reset();}s.reset=M;function E(){return n?{embedding:n.models.embedding!==void 0,graph:n.models.graph!==void 0}:{embedding:false,graph:false}}s.capabilities=E;function h(){return n?.models.embedding}s.getEmbedding=h;function y(){return n?.models.graph}s.getGraph=y;async function p(t){let e=o();if(!e.models.embedding)throw new chunkAVECFV5K_cjs.a.EmbeddingModelNotConfiguredError({message:"embedding model is not configured."});let r=await llm.EmbeddingProvider.embedText({value:t,model:e.models.embedding});return new Float32Array(r.embedding)}s.embedText=p;async function f(t){let e=o();if(!e.models.embedding)throw new chunkAVECFV5K_cjs.a.EmbeddingModelNotConfiguredError({message:"embedding model is not configured."});return (await llm.EmbeddingProvider.embedTexts({values:t,model:e.models.embedding})).embeddings.map(i=>new Float32Array(i))}s.embedTexts=f;async function I(t){let e=o();if(e.models.embedding)return llm.probeEmbeddingDims(e.models.embedding,{timeoutMs:t?.timeoutMs??5e3})}s.probeEmbeddingDims=I;async function C(t,e){let r=o(),i=e?.graphLlm??r.models.graph;return i?llm.GraphProvider.generateGraph({chunks:t,model:i,includeRules:false}):{entities:[],relations:[],summary:""}}s.generateGraph=C;let o=()=>{if(!n)throw new chunkAVECFV5K_cjs.a.LlmNotInitializedError({message:"Llm is not initialized. Please call Llm.init() first."});return n};s.embed=p,s.embedMany=f;})(exports.a||(exports.a={}));var z=exports.a;exports.b=z;
@@ -1,24 +1,24 @@
1
- import {x,z,l,k as k$1,j as j$1,i,m,h,g,f,e,d,c,A as A$1}from'./chunk-X7P7ZFZF.mjs';import {extendKnownErrorCodes,ToolRegistry,createAndStartStdioServer,formatFailClosed}from'@easbot/mcp';import {Log,Locale,TruncateContent}from'@easbot/utils';var ae=Log.create({service:"memory-format-truncate"}),X="**`";var Z=24e3,ee=25e3;async function $(e,n={}){let o=n.softLimit??Z,s=n.hardCeiling??ee,r=n.toolName??"memory",c=n.writeToDisk!==false;if(e.length<=o)return {content:e,truncated:false};let d=e.slice(0,s),t=d.lastIndexOf(`
2
- ${X}`),a=d.lastIndexOf(`
3
- `),m;t>s*.5?m=t:a>0?m=a:m=-1;let u=m>0?d.slice(0,m):d,i=u+"\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:i,truncated:true,outputPath:"",hint:"Make another recall / graph_query with narrower scope.",info:`... ${e.length-u.length}/${e.length} characters truncated ...`};try{let p=await TruncateContent.truncate(e,{maxChars:u.length,direction:"head",label:`${r}-output`});return p.truncated?{content:i,truncated:!0,outputPath:p.outputPath,hint:TruncateContent.formatHint(p),info:`... ${p.removedLength}/${p.originalLength} characters truncated ...`}:{content:i,truncated:!0,outputPath:"",hint:"Make another recall / graph_query with narrower scope.",info:`... ${e.length-u.length}/${e.length} characters truncated ...`}}catch(p){return ae.warn("TruncateContent.truncate failed, returning without disk hint",{error:p instanceof Error?p.message:String(p)}),{content:i,truncated:true,outputPath:"",hint:"Make another recall / graph_query with narrower scope.",info:`... ${e.length-u.length}/${e.length} characters truncated ...`}}}function w(e,n={}){let o=n.softLimit??Z,s=n.hardCeiling??ee;if(e.length<=o)return {content:e,truncated:false};let r=e.slice(0,s),c=r.lastIndexOf(`
4
- ${X}`),d=r.lastIndexOf(`
1
+ import {x,z,l,k as k$1,j as j$1,i,m,h,g,f,e,d,c,A as A$1}from'./chunk-AEAMQDNV.mjs';import {a}from'./chunk-AJDMZTCQ.mjs';import {extendKnownErrorCodes,ToolRegistry,createAndStartStdioServer,formatFailClosed}from'@easbot/mcp';import {Log,errorMeta,Locale,TruncateContent}from'@easbot/utils';var de=Log.create({service:"memory.format.truncate"}),Z="**`";var ee=24e3,te=25e3;async function $(e,n={}){let o=n.softLimit??ee,s=n.hardCeiling??te,r=n.toolName??"memory",c=n.writeToDisk!==false;if(e.length<=o)return {content:e,truncated:false};let d=e.slice(0,s),t=d.lastIndexOf(`
2
+ ${Z}`),a=d.lastIndexOf(`
3
+ `),m;t>s*.5?m=t:a>0?m=a:m=-1;let u=m>0?d.slice(0,m):d,i=u+"\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:i,truncated:true,outputPath:"",hint:"Make another recall / graph_query with narrower scope.",info:`... ${e.length-u.length}/${e.length} characters truncated ...`};try{let f=await TruncateContent.truncate(e,{maxChars:u.length,direction:"head",label:`${r}-output`});return f.truncated?{content:i,truncated:!0,outputPath:f.outputPath,hint:TruncateContent.formatHint(f),info:`... ${f.removedLength}/${f.originalLength} characters truncated ...`}:{content:i,truncated:!0,outputPath:"",hint:"Make another recall / graph_query with narrower scope.",info:`... ${e.length-u.length}/${e.length} characters truncated ...`}}catch(f){return de.warn("TruncateContent.truncate failed, returning without disk hint",{error:errorMeta(f)}),{content:i,truncated:true,outputPath:"",hint:"Make another recall / graph_query with narrower scope.",info:`... ${e.length-u.length}/${e.length} characters truncated ...`}}}function w(e,n={}){let o=n.softLimit??ee,s=n.hardCeiling??te;if(e.length<=o)return {content:e,truncated:false};let r=e.slice(0,s),c=r.lastIndexOf(`
4
+ ${Z}`),d=r.lastIndexOf(`
5
5
  `),t;c>s*.5?t=c:d>0?t=d:t=-1;let a=t>0?r.slice(0,t):r;return {content:a+`
6
6
 
7
- ... (output truncated; tail dropped at section boundary)`,truncated:true,outputPath:"",hint:"",info:`... ${e.length-a.length}/${e.length} characters truncated ...`}}function se(e,n){if(!e||e.length===0)return null;let o=e.filter(r=>n.has(r.path));return o.length===0?null:`\u26A0\uFE0F Index may be stale for: ${o.map(r=>`${r.path} (edited pending)`).join(", ")}
7
+ ... (output truncated; tail dropped at section boundary)`,truncated:true,outputPath:"",hint:"",info:`... ${e.length-a.length}/${e.length} characters truncated ...`}}function ce(e,n){if(!e||e.length===0)return null;let o=e.filter(r=>n.has(r.path));return o.length===0?null:`\u26A0\uFE0F Index may be stale for: ${o.map(r=>`${r.path} (edited pending)`).join(", ")}
8
8
 
9
- `}function I(e,n,o={}){return (te[e]??te.default).replace(/<(\w+)>/g,(r,c)=>c==="tool"?n:o[c]??`<${c}>`)}var te={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 ie(e){let n=Array.isArray(e.edges)?e.edges.length:0;return ` - node #${e.id}: ${e.name} (${e.type}) [edges: ${n}]`}function ne(e,n,o,s){let r=e.tags&&e.tags.length>0?`
9
+ `}function I(e,n,o={}){return (ne[e]??ne.default).replace(/<(\w+)>/g,(r,c)=>c==="tool"?n:o[c]??`<${c}>`)}var ne={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 ue(e){let n=Array.isArray(e.edges)?e.edges.length:0;return ` - node #${e.id}: ${e.name} (${e.type}) [edges: ${n}]`}function re(e,n,o,s){let r=e.tags&&e.tags.length>0?`
10
10
  - tags: ${e.tags.join(", ")}`:"",c=e.sessionId?`
11
11
  - session: ${e.sessionId}`:"",d=e.msgId?`
12
12
  - msg: ${e.msgId}`:"",t=typeof n=="number"?`
13
- - score: ${n.toFixed(3)}${o?` (${o})`:""}`:"",a=e.truncated?" [truncated]":"",m="";if(s&&s.length>0){let u=s.map(ie);m=`
13
+ - score: ${n.toFixed(3)}${o?` (${o})`:""}`:"",a=e.truncated?" [truncated]":"",m="";if(s&&s.length>0){let u=s.map(ue);m=`
14
14
  - linked KG nodes (${s.length}) \u2014 use \`graph_query(nodeId=<id>)\` for full relation graph:
15
15
  ${u.join(`
16
16
  `)}`;}return [`### \`${e.id}\`${a}`,` - agentId: ${e.agentId}`,` - category: ${e.category}`,` - importance: ${e.importance}`,` - createdAt: ${e.createdAt}`,` - updatedAt: ${e.updatedAt}`,` - source: ${e.source}${t}${r}${c}${d}${m}`,"",e.content,""].join(`
17
- `)}async function v(e,n){let o=n.toolName??"memory_recall",s=`**\`memory_recall:${n.query.slice(0,40).replace(/[^a-zA-Z0-9_]/g,"_")}\`**`,r=se(n.pendingFiles,new Set),d=[`Found ${e.total} fact(s) for query "${n.query}" (agentId=${n.agentId}, scope=${n.scope}):`,"",r??"",s].join(`
18
- `),t=new Map;for(let l of e.hits){let i=l.fact.category;t.has(i)||t.set(i,[]),t.get(i).push(l);}let a=Array.from(t.entries()).map(([l,i])=>{let p=`**\`category:${l}\`**`,h=i.map(f=>ne(f.fact,f.score,f.source,f.nodes)).join(`
19
- `);return `${p}
17
+ `)}async function M(e,n){let o=n.toolName??"memory_recall",s=`**\`memory_recall:${n.query.slice(0,40).replace(/[^a-zA-Z0-9_]/g,"_")}\`**`,r=ce(n.pendingFiles,new Set),d=[`Found ${e.total} fact(s) for query "${n.query}" (agentId=${n.agentId}, scope=${n.scope}):`,"",r??"",s].join(`
18
+ `),t=new Map;for(let l of e.hits){let i=l.fact.category;t.has(i)||t.set(i,[]),t.get(i).push(l);}let a=Array.from(t.entries()).map(([l,i])=>{let f=`**\`category:${l}\`**`,p=i.map(g=>re(g.fact,g.score,g.source,g.nodes)).join(`
19
+ `);return `${f}
20
20
 
21
- ${h}`}).join(`
21
+ ${p}`}).join(`
22
22
  `),m=e.warnings&&e.warnings.length>0?`
23
23
 
24
24
  \u26A0\uFE0F warnings:
@@ -28,7 +28,7 @@ ${e.warnings.map(l=>` - ${l}`).join(`
28
28
 
29
29
  ${a}${m}
30
30
 
31
- ${I("recall",o)}`;return n.sync?w(u,{}).content:(await $(u,{toolName:o,writeToDisk:n.writeToDisk})).content}async function A(e,n={}){let o=n.toolName??"memory_remember",s=`**\`memory_remember:${e.fact.id}\`**`,r=ne(e.fact),c=e.nodeIds??[],d=c.length>0?`
31
+ ${I("recall",o)}`;return n.sync?w(u,{}).content:(await $(u,{toolName:o,writeToDisk:n.writeToDisk})).content}async function A(e,n={}){let o=n.toolName??"memory_remember",s=`**\`memory_remember:${e.fact.id}\`**`,r=re(e.fact),c=e.nodeIds??[],d=c.length>0?`
32
32
  - linked KG nodes: ${c.join(", ")}
33
33
  `:"",t=`${s}
34
34
 
@@ -40,12 +40,12 @@ ${e.deletedIds.map(t=>` - ${t}`).join(`
40
40
  `);return n.sync?w(d,{}).content:(await $(d,{toolName:o,writeToDisk:n.writeToDisk})).content}async function N(e,n={}){let o=n.toolName??"memory_graph_query",s=`**\`memory_graph_query:scope=${e.scope}\`**`,r=e.nodes.map(t=>` - node #${t.id}: ${t.name} (${t.type})${t.ownerAgentId?` [owner=${t.ownerAgentId}]`:" [shared]"}`).join(`
41
41
  `),c=e.edges.map(t=>` - edge #${t.id}: ${t.source} --${t.relation}--> ${t.target}`).join(`
42
42
  `),d=[s,"",`nodes (${e.nodes.length}${e.truncated?` / total ${e.totalNodes}`:""}):`,r||" (none)","",`edges (${e.edges.length}${e.truncated?` / total ${e.totalEdges}`:""}):`,c||" (none)","",I("graph_query",o)].join(`
43
- `);return n.sync?w(d,{}).content:(await $(d,{toolName:o,writeToDisk:n.writeToDisk})).content}async function M(e,n={}){let o=n.toolName??"memory_status",r=["**`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"}`,`healthy: ${e.healthy?"yes":"no"}`,"","factsByCategory:",...Object.entries(e.factsByCategory).map(([d,t])=>` - ${d}: ${t}`),"","meta:",...Object.entries(e.meta).map(([d,t])=>` - ${d}: ${t}`)];if(e.integrityStats&&Object.keys(e.integrityStats).length>0){r.push("","DB stats:");let d=Math.max(...Object.keys(e.integrityStats).map(t=>t.length));for(let[t,a]of Object.entries(e.integrityStats))r.push(` - ${t.padEnd(d)} ${a}`);}r.push("",I("status",o));let c=r.join(`
44
- `);return n.sync?w(c,{}).content:(await $(c,{toolName:o,writeToDisk:n.writeToDisk})).content}async function O(e,n={}){let o=n.toolName??"memory_consolidate",r=["**`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",o)].join(`
45
- `);return n.sync?w(r,{}).content:(await $(r,{toolName:o,writeToDisk:n.writeToDisk})).content}var k=20;async function P(e,n={}){let o=n.toolName??"memory_sync",r=[`**\`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){r.push("","### Archived records:");let d=e.archivedRecords.slice(0,k);for(let t of d)r.push(`- ${t.firstFactId} (${t.firstCreatedAt})`),r.push(` - source: \`${t.source}\``),r.push(` - target: \`${t.target}\``);e.archivedRecords.length>k&&r.push(`... and ${e.archivedRecords.length-k} more (use --json for full list)`);}r.push("",`duration: ${e.durationMs}ms`,"",I("sync",o));let c=r.join(`
46
- `);return n.sync?w(c,{}).content:(await $(c,{toolName:o,writeToDisk:n.writeToDisk})).content}async function j(e,n={}){let o=n.toolName??"memory_doctor",s=`**\`memory_doctor:${e.healthy?"OK":"ISSUES"}\`**`,r=t=>t?"\u2705":"\u274C",c=e.checks.map(t=>`${r(t.passed)} ${t.name}: ${t.message}`).join(`
43
+ `);return n.sync?w(d,{}).content:(await $(d,{toolName:o,writeToDisk:n.writeToDisk})).content}async function O(e,n={}){let o=n.toolName??"memory_status",r=["**`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"}`,`healthy: ${e.healthy?"yes":"no"}`,"","factsByCategory:",...Object.entries(e.factsByCategory).map(([d,t])=>` - ${d}: ${t}`),"","meta:",...Object.entries(e.meta).map(([d,t])=>` - ${d}: ${t}`)];if(e.integrityStats&&Object.keys(e.integrityStats).length>0){r.push("","DB stats:");let d=Math.max(...Object.keys(e.integrityStats).map(t=>t.length));for(let[t,a]of Object.entries(e.integrityStats))r.push(` - ${t.padEnd(d)} ${a}`);}r.push("",I("status",o));let c=r.join(`
44
+ `);return n.sync?w(c,{}).content:(await $(c,{toolName:o,writeToDisk:n.writeToDisk})).content}async function P(e,n={}){let o=n.toolName??"memory_consolidate",r=["**`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",o)].join(`
45
+ `);return n.sync?w(r,{}).content:(await $(r,{toolName:o,writeToDisk:n.writeToDisk})).content}var v=20;async function j(e,n={}){let o=n.toolName??"memory_sync",r=[`**\`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){r.push("","### Archived records:");let d=e.archivedRecords.slice(0,v);for(let t of d)r.push(`- ${t.firstFactId} (${t.firstCreatedAt})`),r.push(` - source: \`${t.source}\``),r.push(` - target: \`${t.target}\``);e.archivedRecords.length>v&&r.push(`... and ${e.archivedRecords.length-v} more (use --json for full list)`);}r.push("",`duration: ${e.durationMs}ms`,"",I("sync",o));let c=r.join(`
46
+ `);return n.sync?w(c,{}).content:(await $(c,{toolName:o,writeToDisk:n.writeToDisk})).content}async function L(e,n={}){let o=n.toolName??"memory_doctor",s=`**\`memory_doctor:${e.healthy?"OK":"ISSUES"}\`**`,r=t=>t?"\u2705":"\u274C",c=e.checks.map(t=>`${r(t.passed)} ${t.name}: ${t.message}`).join(`
47
47
  `),d=[s,"",c,"",I("doctor",o)].join(`
48
- `);return n.sync?w(d,{}).content:(await $(d,{toolName:o,writeToDisk:n.writeToDisk})).content}async function R(e,n,o={}){let s=n,r=typeof s.kind=="string";switch((r?s:{kind:e}).kind){case "recall":{let d=r?{hits:s.hits,total:s.totalCount??s.total??0,truncated:s.truncated??false}:n;return v(d,{...o,query:s.query??o.query??"",agentId:s.agentId??o.agentId??"",scope:s.scope??o.scope??"agent_only"})}case "remember":{let d=r?{fact:s.fact,nodeIds:s.nodeIds}:n;return A(d,o)}case "forget":return _(r?s:n,o);case "graph_query":return N(r?s:n,o);case "status":return M(r?s:n,o);case "consolidate":return O(r?s:n,o);case "sync":return P(r?s:n,o);case "doctor":return j(r?s:n,o);default:throw new Error(`renderOperationMarkdown: unsupported op "${e}"`)}}var D=Log.create({service:"memory-mcp-stdio"});function Re(e){let n=new Map,o=e.isRemote??true,s=!o;function r(t){let a=Locale.resolveLocaleLang();return {agentId:t.agentId??e.agentId,isTrustedLocal:t.isTrustedLocal??s,remote:o,locale:a,dbPath:e.dbPath,workspaceDir:e.workspaceDir,rootDir:e.workspaceDir,config:A$1({agentId:e.agentId,dbPath:e.dbPath})}}function c(t,a){return {content:[{type:"text",text:t}],isError:a}}function d(t){return formatFailClosed(t,s)}return n.set("recall",async t=>{try{let a=t,m=r({agentId:a.agentId}),u=await z("recall",t,m);return {content:[{type:"text",text:await R("recall",u,{toolName:"memory_recall",query:a.query,agentId:a.agentId??e.agentId,scope:a.scope??"agent_only"})}]}}catch(a){return c(d(a),true)}}),n.set("remember",async t=>{try{let m=r({agentId:t.agentId}),u=await z("remember",t,m);return {content:[{type:"text",text:await R("remember",u,{toolName:"memory_remember"})}]}}catch(a){return c(d(a),true)}}),n.set("update",async t=>{try{let m=r({agentId:t.agentId}),u=await z("update",t,m),l=u.fieldsUpdated.length>0?u.fieldsUpdated.join(", "):"(no-op)",i=u.contentChanged?" (embedding rewritten)":"";return {content:[{type:"text",text:`Memory updated.
48
+ `);return n.sync?w(d,{}).content:(await $(d,{toolName:o,writeToDisk:n.writeToDisk})).content}async function R(e,n,o={}){let s=n,r=typeof s.kind=="string";switch((r?s:{kind:e}).kind){case "recall":{let d=r?{hits:s.hits,total:s.totalCount??s.total??0,truncated:s.truncated??false}:n;return M(d,{...o,query:s.query??o.query??"",agentId:s.agentId??o.agentId??"",scope:s.scope??o.scope??"agent_only"})}case "remember":{let d=r?{fact:s.fact,nodeIds:s.nodeIds}:n;return A(d,o)}case "forget":return _(r?s:n,o);case "graph_query":return N(r?s:n,o);case "status":return O(r?s:n,o);case "consolidate":return P(r?s:n,o);case "sync":return j(r?s:n,o);case "doctor":return L(r?s:n,o);default:throw new a.UnsupportedOperationError({message:`renderOperationMarkdown: unsupported op "${e}"`,opName:e,renderer:"markdown"})}}var k=Log.create({service:"memory.mcp.stdio"});function Ee(e){let n=new Map,o=e.isRemote??true,s=!o;function r(t){let a=Locale.resolveLocaleLang();return {agentId:t.agentId??e.agentId,isTrustedLocal:t.isTrustedLocal??s,remote:o,locale:a,dbPath:e.dbPath,workspaceDir:e.workspaceDir,rootDir:e.workspaceDir,config:A$1({agentId:e.agentId,dbPath:e.dbPath})}}function c(t,a){return {content:[{type:"text",text:t}],isError:a}}function d(t){return formatFailClosed(t,s)}return n.set("recall",async t=>{try{let a=t,m=r({agentId:a.agentId}),u=await z("recall",t,m);return {content:[{type:"text",text:await R("recall",u,{toolName:"memory_recall",query:a.query,agentId:a.agentId??e.agentId,scope:a.scope??"agent_only"})}]}}catch(a){return c(d(a),true)}}),n.set("remember",async t=>{try{let m=r({agentId:t.agentId}),u=await z("remember",t,m);return {content:[{type:"text",text:await R("remember",u,{toolName:"memory_remember"})}]}}catch(a){return c(d(a),true)}}),n.set("update",async t=>{try{let m=r({agentId:t.agentId}),u=await z("update",t,m),l=u.fieldsUpdated.length>0?u.fieldsUpdated.join(", "):"(no-op)",i=u.contentChanged?" (embedding rewritten)":"";return {content:[{type:"text",text:`Memory updated.
49
49
  id: ${u.fact.id}
50
50
  category: ${u.fact.category}
51
51
  importance: ${u.fact.importance}
@@ -56,9 +56,9 @@ sessionId: ${t.sessionId??"(unknown)"}
56
56
  extractedCount: ${l.extractedCount}
57
57
  factIds: ${l.factIds.length>0?l.factIds.join(", "):"(none)"}
58
58
  messageRange: ${l.messageRange.fromMessageId} -> ${l.messageRange.toMessageId}
59
- `}]}}catch(a){return c(d(a),true)}}),n.set("consolidate",async t=>{try{let m=r({agentId:t.agentId,isTrustedLocal:!0}),u=await z("consolidate",t,m);return {content:[{type:"text",text:await R("consolidate",u,{toolName:"memory_consolidate"})}]}}catch(a){return c(d(a),true)}}),n.set("sync",async t=>{try{let m=t.agentId?.trim();if(!m)return c(d(new Error("memory_sync: agentId is required (sync requires agentId, see ADR 0069)")),!0);let u=r({agentId:m,isTrustedLocal:!0}),l=await z("sync",t,u);return {content:[{type:"text",text:await R("sync",l,{toolName:"memory_sync"})}]}}catch(a){return c(d(a),true)}}),n.set("graph_query",async t=>{try{let a=t,m=r({agentId:a.agentId}),u=await z("graph_query",t,m);return {content:[{type:"text",text:await R("graph_query",u,{toolName:"memory_graph_query",scope:a.scope??"agent_only"})}]}}catch(a){return c(d(a),true)}}),n.set("status",async t=>{try{let m=r({agentId:(t??{}).agentId}),u=await z("status",t,m),{renderKnowledgeStatus:l}=await import('@easbot/terminal'),i=u;return {content:[{type:"text",text:l({packageName:"memory",rootDir:i.workspaceDir??"",configPath:i.configPath??"",configExists:typeof i.configExists=="boolean"?i.configExists:!0,dbPath:i.dbPath??"",dbExists:typeof i.dbExists=="boolean"?i.dbExists:!0,dbSize:typeof i.dbSize=="number"?i.dbSize:void 0,indexState:i.indexState,schemaVersion:typeof i.schemaVersion=="number"?i.schemaVersion:void 0,extractionVersion:typeof i.extractionVersion=="number"?i.extractionVersion:void 0,lastSyncAt:i.lastSyncAt,vectorEnabled:typeof i.vectorEnabled=="boolean"?i.vectorEnabled:!1,embeddingDims:typeof i.embeddingDims=="number"?i.embeddingDims:void 0,llm:i.llm??{initialized:!1,capabilities:{}},backend:i.backend,healthy:typeof i.healthy=="boolean"?i.healthy:!0,recommendation:i.recommendation,dbStats:(()=>{let h=i.dbStats;if(h&&typeof h=="object"&&Object.keys(h).length>0)return {...h};let f=i.integrityStats;if(f&&typeof f=="object"&&Object.keys(f).length>0)return {...f}})(),extras:(()=>{let h={};if(typeof i.agentId=="string"&&(h.agent_id=i.agentId),typeof i.ftsAvailable=="boolean"&&(h.fts_available=i.ftsAvailable?"yes":"no"),i.factsByCategory&&typeof i.factsByCategory=="object")for(let[f,b]of Object.entries(i.factsByCategory))typeof b=="number"&&b>0&&(h[`facts/${f}`]=b);if(i.meta&&typeof i.meta=="object")for(let[f,b]of Object.entries(i.meta))b!==void 0&&(h[`meta/${f}`]=b);return Object.keys(h).length>0?h:void 0})()})}]}}catch(a){return c(d(a),true)}}),n.set("doctor",async t=>{try{let m=r({agentId:(t??{}).agentId,isTrustedLocal:!0}),u=await z("doctor",t,m);return {content:[{type:"text",text:await R("doctor",u,{toolName:"memory_doctor"})}]}}catch(a){return c(d(a),true)}}),n.set("init",async t=>{try{let a=r({isTrustedLocal:!0}),u=await z("init",t,a);return {content:[{type:"text",text:`Init complete.
59
+ `}]}}catch(a){return c(d(a),true)}}),n.set("consolidate",async t=>{try{let m=r({agentId:t.agentId,isTrustedLocal:!0}),u=await z("consolidate",t,m);return {content:[{type:"text",text:await R("consolidate",u,{toolName:"memory_consolidate"})}]}}catch(a){return c(d(a),true)}}),n.set("sync",async t=>{try{let m=t.agentId?.trim();if(!m)return c(d(new Error("memory_sync: agentId is required (sync requires agentId, see ADR 0069)")),!0);let u=r({agentId:m,isTrustedLocal:!0}),l=await z("sync",t,u);return {content:[{type:"text",text:await R("sync",l,{toolName:"memory_sync"})}]}}catch(a){return c(d(a),true)}}),n.set("graph_query",async t=>{try{let a=t,m=r({agentId:a.agentId}),u=await z("graph_query",t,m);return {content:[{type:"text",text:await R("graph_query",u,{toolName:"memory_graph_query",scope:a.scope??"agent_only"})}]}}catch(a){return c(d(a),true)}}),n.set("status",async t=>{try{let m=r({agentId:(t??{}).agentId}),u=await z("status",t,m),{renderKnowledgeStatus:l}=await import('@easbot/terminal'),i=u;return {content:[{type:"text",text:l({packageName:"memory",rootDir:i.workspaceDir??"",configPath:i.configPath??"",configExists:typeof i.configExists=="boolean"?i.configExists:!0,dbPath:i.dbPath??"",dbExists:typeof i.dbExists=="boolean"?i.dbExists:!0,dbSize:typeof i.dbSize=="number"?i.dbSize:void 0,indexState:i.indexState,schemaVersion:typeof i.schemaVersion=="number"?i.schemaVersion:void 0,extractionVersion:typeof i.extractionVersion=="number"?i.extractionVersion:void 0,lastSyncAt:i.lastSyncAt,vectorEnabled:typeof i.vectorEnabled=="boolean"?i.vectorEnabled:!1,embeddingDims:typeof i.embeddingDims=="number"?i.embeddingDims:void 0,llm:i.llm??{initialized:!1,capabilities:{}},backend:i.backend,healthy:typeof i.healthy=="boolean"?i.healthy:!0,recommendation:i.recommendation,dbStats:(()=>{let p=i.dbStats;if(p&&typeof p=="object"&&Object.keys(p).length>0)return {...p};let g=i.integrityStats;if(g&&typeof g=="object"&&Object.keys(g).length>0)return {...g}})(),extras:(()=>{let p={};if(typeof i.agentId=="string"&&(p.agent_id=i.agentId),typeof i.ftsAvailable=="boolean"&&(p.fts_available=i.ftsAvailable?"yes":"no"),i.factsByCategory&&typeof i.factsByCategory=="object")for(let[g,b]of Object.entries(i.factsByCategory))typeof b=="number"&&b>0&&(p[`facts/${g}`]=b);if(i.meta&&typeof i.meta=="object")for(let[g,b]of Object.entries(i.meta))b!==void 0&&(p[`meta/${g}`]=b);return Object.keys(p).length>0?p:void 0})()})}]}}catch(a){return c(d(a),true)}}),n.set("doctor",async t=>{try{let m=r({agentId:(t??{}).agentId,isTrustedLocal:!0}),u=await z("doctor",t,m);return {content:[{type:"text",text:await R("doctor",u,{toolName:"memory_doctor"})}]}}catch(a){return c(d(a),true)}}),n.set("init",async t=>{try{let a=r({isTrustedLocal:!0}),u=await z("init",t,a);return {content:[{type:"text",text:`Init complete.
60
60
  dbPath: ${u.dbPath}
61
61
  tablesCreated: ${u.tablesCreated}
62
62
  migrationsApplied: ${u.migrationsApplied}
63
63
  durationMs: ${u.durationMs}
64
- `}]}}catch(a){return c(d(a),true)}}),n}var Ce={recall:c,remember:d,update:e,forget:f,extract:g,consolidate:h,sync:m,graph_query:i,status:j$1,doctor:k$1,init:l};function Te(e,n){let o=x[e],s={title:o?.annotations?.defaultDescription??e,readOnlyHint:o?.annotations?.readOnlyHint??false,destructiveHint:o?.annotations?.destructiveHint??false,idempotentHint:o?.annotations?.idempotentHint??true,openWorldHint:false},r=Ce[e];return {name:e,description:o?.annotations?.defaultDescription??`memory op: ${e}`,inputSchema:r??{type:"object",properties:{},required:[],additionalProperties:false},annotations:s,handler:n}}var re;(o=>{async function e(s,r){let{getMemoryDbPath:c,getInstance:d}=await import('./interfaces-LPJU4KS3.mjs'),a=r!==null&&typeof r=="object"&&"agentId"in r&&"dbPath"in r?r:{agentId:process.env.EASBOT_AGENT_ID??"default",dbPath:c(),workspaceDir:d().worktree,isRemote:false};extendKnownErrorCodes(["AGENT_ID_REQUIRED","SESSION_ID_REQUIRED","CATEGORY_REQUIRED","IMPORTANCE_REQUIRED","TIMERANGE_REQUIRED","DRY_RUN_NO_DELETE"]);let m=new ToolRegistry,u=Re(a),l=Object.keys(x);for(let g of l){let C=u.get(g);if(!C)throw new Error(`MemoryStdioServer.start: missing handler for tool "${g}"`);m.register(Te(g,C));}D.info("starting memory MCP stdio server",{id:s.id,name:s.name,toolCount:l.length,isRemote:a.isRemote??true});let i=await createAndStartStdioServer(s,m),p=null,h=new Promise(g=>{p=g;}),f=g=>{D.info("received signal, stopping MCP server",{signal:g}),p?.();},b=()=>f("SIGINT"),S=()=>f("SIGTERM"),L=(g,C)=>process.listeners(g).includes(C);L("SIGINT",b)||process.on("SIGINT",b),L("SIGTERM",S)||process.on("SIGTERM",S);try{await h;}finally{try{process.off("SIGINT",b),process.off("SIGTERM",S);}catch(g){D.warn("failed to remove signal handlers",{error:g instanceof Error?g.message:String(g)});}try{await i.stop();}catch(g){D.warn("server.stop failed during cleanup",{error:g instanceof Error?g.message:String(g)});}}return {id:s.id,name:s.name,version:s.version,tools:l}}o.start=e;function n(){return Object.keys(x)}o.getToolNames=n;})(re||(re={}));export{R as a,re as b};
64
+ `}]}}catch(a){return c(d(a),true)}}),n}var xe={recall:c,remember:d,update:e,forget:f,extract:g,consolidate:h,sync:m,graph_query:i,status:j$1,doctor:k$1,init:l};function De(e,n){let o=x[e],s={title:o?.annotations?.defaultDescription??e,readOnlyHint:o?.annotations?.readOnlyHint??false,destructiveHint:o?.annotations?.destructiveHint??false,idempotentHint:o?.annotations?.idempotentHint??true,openWorldHint:false},r=xe[e];return {name:e,description:o?.annotations?.defaultDescription??`memory op: ${e}`,inputSchema:r??{type:"object",properties:{},required:[],additionalProperties:false},annotations:s,handler:n}}var ae;(o=>{async function e(s,r){let{getMemoryDbPath:c,getInstance:d}=await import('./interfaces-OFM2XGSG.mjs'),a$1=r!==null&&typeof r=="object"&&"agentId"in r&&"dbPath"in r?r:{agentId:process.env.EASBOT_AGENT_ID??"default",dbPath:c(d().worktree),workspaceDir:d().worktree,isRemote:false};extendKnownErrorCodes(["AGENT_ID_REQUIRED","SESSION_ID_REQUIRED","CATEGORY_REQUIRED","IMPORTANCE_REQUIRED","TIMERANGE_REQUIRED","DRY_RUN_NO_DELETE"]);let m=new ToolRegistry,u=Ee(a$1),l=Object.keys(x);for(let y of l){let C=u.get(y);if(!C)throw new a.MissingMcpHandlerError({message:`MemoryStdioServer.start: missing handler for tool "${y}"`,toolName:y});m.register(De(y,C));}k.info("starting memory MCP stdio server",{id:s.id,name:s.name,toolCount:l.length,isRemote:a$1.isRemote??true});let i=await createAndStartStdioServer(s,m),f=null,p=new Promise(y=>{f=y;}),g=y=>{k.info("received signal, stopping MCP server",{signal:y}),f?.();},b=()=>g("SIGINT"),S=()=>g("SIGTERM"),F=(y,C)=>process.listeners(y).includes(C);F("SIGINT",b)||process.on("SIGINT",b),F("SIGTERM",S)||process.on("SIGTERM",S);try{await p;}finally{try{process.off("SIGINT",b),process.off("SIGTERM",S);}catch(y){k.warn("failed to remove signal handlers",{error:errorMeta(y)});}try{await i.stop();}catch(y){k.warn("server.stop failed during cleanup",{error:errorMeta(y)});}}return {id:s.id,name:s.name,version:s.version,tools:l}}o.start=e;function n(){return Object.keys(x)}o.getToolNames=n;})(ae||(ae={}));export{R as a,ae as b};
@@ -0,0 +1 @@
1
+ 'use strict';var utils=require('@easbot/utils');var e=null,n=null;function u(t){e=t;}function c(){e=null;}function l(){return e||{Path:utils.Global.get()}}function p(t){n=t;}function d(){n=null;}function I(){if(n)return n;let t=utils.Filesystem.normalize(process.cwd());return {directory:t,worktree:t}}function m(){return utils.Filesystem.normalize(l().Path.home||utils.Global.home())}function a(){return l().Path.data||utils.Global.data()}function b(){return utils.Filesystem.join(a(),"memory")}function f(t){return utils.Filesystem.join(t,".easbot","db","memory.db")}exports.a=u;exports.b=c;exports.c=l;exports.d=p;exports.e=d;exports.f=I;exports.g=m;exports.h=a;exports.i=b;exports.j=f;
@@ -0,0 +1 @@
1
+ import {a}from'./chunk-AJDMZTCQ.mjs';import {Log}from'@easbot/utils';import {ModelManager,EmbeddingProvider,probeEmbeddingDims,GraphProvider}from'@easbot/llm';var m;(s=>{let g=Log.create({service:"memory.llm"}),n=null;function x(t){if(u())return;let e=t;n={models:e.models,options:e.options??{}},ModelManager.declare(n.models),g.debug("Llm initialized",{embeddingConfigured:!!e.models.embedding,graphConfigured:!!e.models.graph});}s.init=x;function u(){return n!==null}s.isInitialized=u;function M(){n=null,ModelManager.reset();}s.reset=M;function E(){return n?{embedding:n.models.embedding!==void 0,graph:n.models.graph!==void 0}:{embedding:false,graph:false}}s.capabilities=E;function h(){return n?.models.embedding}s.getEmbedding=h;function y(){return n?.models.graph}s.getGraph=y;async function p(t){let e=o();if(!e.models.embedding)throw new a.EmbeddingModelNotConfiguredError({message:"embedding model is not configured."});let r=await EmbeddingProvider.embedText({value:t,model:e.models.embedding});return new Float32Array(r.embedding)}s.embedText=p;async function f(t){let e=o();if(!e.models.embedding)throw new a.EmbeddingModelNotConfiguredError({message:"embedding model is not configured."});return (await EmbeddingProvider.embedTexts({values:t,model:e.models.embedding})).embeddings.map(i=>new Float32Array(i))}s.embedTexts=f;async function I(t){let e=o();if(e.models.embedding)return probeEmbeddingDims(e.models.embedding,{timeoutMs:t?.timeoutMs??5e3})}s.probeEmbeddingDims=I;async function C(t,e){let r=o(),i=e?.graphLlm??r.models.graph;return i?GraphProvider.generateGraph({chunks:t,model:i,includeRules:false}):{entities:[],relations:[],summary:""}}s.generateGraph=C;let o=()=>{if(!n)throw new a.LlmNotInitializedError({message:"Llm is not initialized. Please call Llm.init() first."});return n};s.embed=p,s.embedMany=f;})(m||(m={}));var A=m;export{m as a,A as b};
@@ -0,0 +1 @@
1
+ import {Global,Filesystem}from'@easbot/utils';var e=null,n=null;function c(t){e=t;}function p(){e=null;}function l(){return e||{Path:Global.get()}}function d(t){n=t;}function I(){n=null;}function m(){if(n)return n;let t=Filesystem.normalize(process.cwd());return {directory:t,worktree:t}}function b(){return Filesystem.normalize(l().Path.home||Global.home())}function a(){return l().Path.data||Global.data()}function f(){return Filesystem.join(a(),"memory")}function g(t){return Filesystem.join(t,".easbot","db","memory.db")}export{c as a,p as b,l as c,d,I as e,m as f,b as g,a as h,f as i,g as j};
@@ -0,0 +1 @@
1
+ 'use strict';var f=Object.defineProperty;var i=(t,e)=>(e=Symbol[t])?e:Symbol.for("Symbol."+t),d=t=>{throw TypeError(t)};var s=(t,e,r)=>e in t?f(t,e,{enumerable:true,configurable:true,writable:true,value:r}):t[e]=r;var l=(t,e,r)=>s(t,typeof e!="symbol"?e+"":e,r);var R=(t,e,r)=>{if(e!=null){typeof e!="object"&&typeof e!="function"&&d("Object expected");var c,o;r&&(c=e[i("asyncDispose")]),c===void 0&&(c=e[i("dispose")],r&&(o=c)),typeof c!="function"&&d("Object not disposable"),o&&(c=function(){try{o.call(this);}catch(m){return Promise.reject(m)}}),t.push([r,c,e]);}else r&&t.push([r]);return e},S=(t,e,r)=>{var c=typeof SuppressedError=="function"?SuppressedError:function(n,a,p,u){return u=Error(p),u.name="SuppressedError",u.error=n,u.suppressed=a,u},o=n=>e=r?new c(n,e,"An error was suppressed during disposal"):(r=true,n),m=n=>{for(;n=t.pop();)try{var a=n[1]&&n[1].call(n[2]);if(n[0])return Promise.resolve(a).then(m,p=>(o(p),m()))}catch(p){o(p);}if(r)throw e};return m()};var U=()=>typeof document>"u"?new URL(`file:${__filename}`).href:document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"?document.currentScript.src:new URL("main.js",document.baseURI).href,g=U();exports.a=l;exports.b=R;exports.c=S;exports.d=g;
@@ -0,0 +1 @@
1
+ 'use strict';var chunkGCVKM3RJ_cjs=require('./chunk-GCVKM3RJ.cjs'),fs=require('fs'),utils=require('@easbot/utils'),zod=require('zod');var y=zod.z.object({version:zod.z.literal(1).optional(),schema_version:zod.z.number().int().nonnegative().optional(),extraction_version:zod.z.number().int().nonnegative().optional(),index_state:zod.z.string().optional(),backend:zod.z.string().optional(),created_at:zod.z.string().optional(),embedding_model:zod.z.string().nullable().optional(),graph_model:zod.z.string().nullable().optional(),archive_days:zod.z.number().int().positive().optional(),short_term_max_rounds:zod.z.number().int().positive().optional()}).loose(),q={version:1,schema_version:1,extraction_version:1,index_state:"uninitialized",backend:"better-sqlite3",created_at:"",embedding_model:null,graph_model:null,archive_days:30,short_term_max_rounds:20};var i=utils.Log.create({service:"memory.cache"}),C=[".easbot","memory.json"],J=new Set;function w(){try{let e=chunkGCVKM3RJ_cjs.f().directory;if(e&&e.length>0)return e}catch{}return process.cwd()}function c(t){return utils.Filesystem.join(t,...C)}async function F(t){let e=c(t);if(J.add(utils.Filesystem.normalize(e)),!fs.existsSync(e))return {memoryJson:{},exists:false,rootDir:t};try{return {memoryJson:await utils.ConfigFileParse.loadFile(e,{schema:y}),exists:!0,rootDir:t}}catch(m){return i.warn("memory.json parse failed",{configPath:e,error:utils.errorMeta(m)}),{memoryJson:void 0,exists:true,rootDir:t}}}var h=utils.State.holder(()=>{try{let e=chunkGCVKM3RJ_cjs.f().directory;return e?utils.Filesystem.normalize(e):"__memory_cache_global__"}catch{return "__memory_cache_global__"}},async()=>F(w()));exports.d=void 0;(T=>{let t=false;async function e(){return h.get()}T.state=e;function d(r){h.clear(),t=false,utils.ConfigFileParse.invalidate(r??c(w()),"memory.resetState");}T.resetState=d;function m(){g||(g=utils.ConfigFileParse.onChange(r=>{J.has(r)&&(i.info("memory.json changed externally, reloading",{configPath:r}),utils.ConfigFileParse.invalidateNormalized(r,"memory.externalChange"),d(r));}));}let g;async function k(){t||(t=true,m(),i.info("MemoryCache init"),await e());}T.init=k;async function D(){return (await e()).memoryJson}T.getMemoryJson=D;async function N(){return (await e()).exists}T.exists=N;async function O(){return (await e()).rootDir}T.getRootDir=O;async function L(r){let f=await e(),n=c(f.rootDir),M=utils.ConfigFileParse.merge([f.memoryJson??{},r]),s=y.safeParse(M);if(!s.success)throw i.error("memory.json validation failed on write",{configPath:n,issues:s.error.issues}),new utils.NameErrors.ValidationError({message:`memory.json validation failed: ${s.error.message}`,location:n,issues:s.error.issues});let _=utils.Filesystem.dirname(n);fs.existsSync(_)||fs.mkdirSync(_,{recursive:true});try{fs.writeFileSync(n,JSON.stringify(s.data,null,2),"utf-8");}catch(p){throw i.error("memory.json write failed",{configPath:n,error:utils.errorMeta(p)}),p}return d(n),i.debug("memory.json written",{configPath:n}),s.data}T.writeMemoryJson=L;async function A(){let r=await e();return c(r.rootDir)}T.getConfigPath=A;})(exports.d||(exports.d={}));exports.a=y;exports.b=q;exports.c=C;
@@ -0,0 +1 @@
1
+ var m=Object.defineProperty;var k=(b,a)=>(a=Symbol[b])?a:Symbol.for("Symbol."+b),l=b=>{throw TypeError(b)};var n=(b,a,c)=>a in b?m(b,a,{enumerable:true,configurable:true,writable:true,value:c}):b[a]=c;var o=(b,a,c)=>n(b,typeof a!="symbol"?a+"":a,c);var p=(b,a,c)=>{if(a!=null){typeof a!="object"&&typeof a!="function"&&l("Object expected");var e,f;c&&(e=a[k("asyncDispose")]),e===void 0&&(e=a[k("dispose")],c&&(f=e)),typeof e!="function"&&l("Object not disposable"),f&&(e=function(){try{f.call(this);}catch(g){return Promise.reject(g)}}),b.push([c,e,a]);}else c&&b.push([c]);return a},q=(b,a,c)=>{var e=typeof SuppressedError=="function"?SuppressedError:function(d,j,h,i){return i=Error(h),i.name="SuppressedError",i.error=d,i.suppressed=j,i},f=d=>a=c?new e(d,a,"An error was suppressed during disposal"):(c=true,d),g=d=>{for(;d=b.pop();)try{var j=d[1]&&d[1].call(d[2]);if(d[0])return Promise.resolve(j).then(g,h=>(f(h),g()))}catch(h){f(h);}if(c)throw a};return g()};export{o as a,p as b,q as c};
@@ -0,0 +1 @@
1
+ import {f}from'./chunk-HX3TV7FD.mjs';import {existsSync,mkdirSync,writeFileSync}from'fs';import {Log,State,Filesystem,ConfigFileParse,errorMeta,NameErrors}from'@easbot/utils';import {z}from'zod';var y=z.object({version:z.literal(1).optional(),schema_version:z.number().int().nonnegative().optional(),extraction_version:z.number().int().nonnegative().optional(),index_state:z.string().optional(),backend:z.string().optional(),created_at:z.string().optional(),embedding_model:z.string().nullable().optional(),graph_model:z.string().nullable().optional(),archive_days:z.number().int().positive().optional(),short_term_max_rounds:z.number().int().positive().optional()}).loose(),H={version:1,schema_version:1,extraction_version:1,index_state:"uninitialized",backend:"better-sqlite3",created_at:"",embedding_model:null,graph_model:null,archive_days:30,short_term_max_rounds:20};var i=Log.create({service:"memory.cache"}),F=[".easbot","memory.json"],J=new Set;function w(){try{let e=f().directory;if(e&&e.length>0)return e}catch{}return process.cwd()}function c(t){return Filesystem.join(t,...F)}async function k(t){let e=c(t);if(J.add(Filesystem.normalize(e)),!existsSync(e))return {memoryJson:{},exists:false,rootDir:t};try{return {memoryJson:await ConfigFileParse.loadFile(e,{schema:y}),exists:!0,rootDir:t}}catch(m){return i.warn("memory.json parse failed",{configPath:e,error:errorMeta(m)}),{memoryJson:void 0,exists:true,rootDir:t}}}var h=State.holder(()=>{try{let e=f().directory;return e?Filesystem.normalize(e):"__memory_cache_global__"}catch{return "__memory_cache_global__"}},async()=>k(w())),x;(Y=>{let t=false;async function e(){return h.get()}Y.state=e;function d(r){h.clear(),t=false,ConfigFileParse.invalidate(r??c(w()),"memory.resetState");}Y.resetState=d;function m(){g||(g=ConfigFileParse.onChange(r=>{J.has(r)&&(i.info("memory.json changed externally, reloading",{configPath:r}),ConfigFileParse.invalidateNormalized(r,"memory.externalChange"),d(r));}));}let g;async function D(){t||(t=true,m(),i.info("MemoryCache init"),await e());}Y.init=D;async function N(){return (await e()).memoryJson}Y.getMemoryJson=N;async function O(){return (await e()).exists}Y.exists=O;async function L(){return (await e()).rootDir}Y.getRootDir=L;async function A(r){let f=await e(),n=c(f.rootDir),M=ConfigFileParse.merge([f.memoryJson??{},r]),s=y.safeParse(M);if(!s.success)throw i.error("memory.json validation failed on write",{configPath:n,issues:s.error.issues}),new NameErrors.ValidationError({message:`memory.json validation failed: ${s.error.message}`,location:n,issues:s.error.issues});let _=Filesystem.dirname(n);existsSync(_)||mkdirSync(_,{recursive:true});try{writeFileSync(n,JSON.stringify(s.data,null,2),"utf-8");}catch(p){throw i.error("memory.json write failed",{configPath:n,error:errorMeta(p)}),p}return d(n),i.debug("memory.json written",{configPath:n}),s.data}Y.writeMemoryJson=A;async function T(){let r=await e();return c(r.rootDir)}Y.getConfigPath=T;})(x||(x={}));export{y as a,H as b,F as c,x as d};