@easbot/memory 0.3.21 → 0.3.23
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 +2 -2
- package/README.md +4 -4
- package/dist/chunks/chunk-2TBNGTSA.mjs +65 -0
- package/dist/chunks/{chunk-TIZCWDJ7.mjs → chunk-3EDNN7MP.mjs} +1 -1
- package/dist/chunks/chunk-5YDI4K2F.cjs +65 -0
- package/dist/chunks/{chunk-EGWJG65Q.cjs → chunk-EK34SXJ7.cjs} +24 -17
- package/dist/chunks/{chunk-N5YRDTEH.mjs → chunk-K4K3YR6R.mjs} +35 -29
- package/dist/chunks/{chunk-S6S35LDL.cjs → chunk-MENFLGGM.cjs} +36 -30
- package/dist/chunks/{chunk-AYGZUNFR.cjs → chunk-OU5TQHJE.cjs} +1 -1
- package/dist/chunks/{chunk-JDPZ5U53.mjs → chunk-PJGILQSZ.mjs} +24 -17
- package/dist/chunks/cli-handler-7HISH37M.cjs +1 -0
- package/dist/chunks/cli-handler-WOX5EG34.mjs +1 -0
- package/dist/chunks/{config-RPPQ73HK.cjs → config-I2I6U4XM.cjs} +1 -1
- package/dist/chunks/consolidate-JBTOQWUX.mjs +2 -0
- package/dist/chunks/{consolidate-G4YJV756.cjs → consolidate-JGLVNSDT.cjs} +1 -1
- package/dist/chunks/doctor-C7RIJGYC.cjs +1 -0
- package/dist/chunks/{doctor-GKMREWZN.mjs → doctor-DLQO7QMW.mjs} +1 -1
- package/dist/chunks/{extract-YKDPZ7GA.cjs → extract-4ZGVF2DQ.cjs} +1 -1
- package/dist/chunks/extract-WH4DU4NQ.mjs +2 -0
- package/dist/chunks/{forget-VQB5DUJ3.mjs → forget-CRDWG4XE.mjs} +1 -1
- package/dist/chunks/{forget-GNIJL2DU.cjs → forget-PARGCUIH.cjs} +1 -1
- package/dist/chunks/{graph-GTYUNUJE.cjs → graph-NJJLGDZI.cjs} +1 -1
- package/dist/chunks/{graph-4W63TU2D.mjs → graph-T66JXDLU.mjs} +1 -1
- package/dist/chunks/init-2ZTVBJ6N.mjs +1 -0
- package/dist/chunks/{init-DGMGRNCG.cjs → init-EEWFFF4Y.cjs} +1 -1
- package/dist/chunks/{interfaces-XWE45ENK.cjs → interfaces-Q5OGU5EK.cjs} +1 -1
- package/dist/chunks/{llm-RMPVWEVP.cjs → llm-7LQGYSUE.cjs} +1 -1
- package/dist/chunks/{mcp-EHUKGJRB.cjs → mcp-ES7O3UKN.cjs} +1 -1
- package/dist/chunks/{mcp-QQBHEZFY.mjs → mcp-OAUOA4PI.mjs} +1 -1
- package/dist/chunks/{recall-ZENMAOMJ.cjs → recall-LCKRI4TB.cjs} +1 -1
- package/dist/chunks/recall-VMW7Y55X.mjs +2 -0
- package/dist/chunks/{remember-3ZY66RJQ.cjs → remember-OZOQ76IA.cjs} +1 -1
- package/dist/chunks/{remember-P3G7WWYB.mjs → remember-ZVTM3IP4.mjs} +1 -1
- package/dist/chunks/status-6R335JGR.cjs +1 -0
- package/dist/chunks/{status-JYI52QKB.mjs → status-LHXMB3ZY.mjs} +1 -1
- package/dist/chunks/stdio-server-IMJF7HB6.cjs +1 -0
- package/dist/chunks/stdio-server-SONZIWC4.mjs +1 -0
- package/dist/chunks/{sync-64JINCSC.cjs → sync-7VBREDVM.cjs} +1 -1
- package/dist/chunks/{sync-ZPRCA4MO.mjs → sync-KWHUII26.mjs} +1 -1
- package/dist/cli.cjs +1 -1
- package/dist/cli.mjs +1 -1
- package/dist/index.cjs +4 -4
- package/dist/index.d.cts +24 -1
- package/dist/index.d.ts +24 -1
- package/dist/index.mjs +4 -4
- package/package.json +11 -11
- package/dist/chunks/chunk-UF2Y2Q4L.mjs +0 -50
- package/dist/chunks/chunk-Z5E4HBGK.cjs +0 -50
- package/dist/chunks/cli-handler-2IPBL45N.cjs +0 -1
- package/dist/chunks/cli-handler-5YNHYDSM.mjs +0 -1
- package/dist/chunks/consolidate-MSPLH3T6.mjs +0 -2
- package/dist/chunks/doctor-YTUQCHFJ.cjs +0 -1
- package/dist/chunks/extract-3C4QFS7E.mjs +0 -2
- package/dist/chunks/init-G2WTR477.mjs +0 -1
- package/dist/chunks/recall-SGA2DITO.mjs +0 -2
- package/dist/chunks/status-UEKBJVCI.cjs +0 -1
- package/dist/chunks/stdio-server-2PWTBTDJ.mjs +0 -1
- package/dist/chunks/stdio-server-JL4XNUHH.cjs +0 -1
- /package/dist/chunks/{chunk-NVGACA7W.cjs → chunk-M2YU5LAI.cjs} +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
'use strict';var
|
|
1
|
+
'use strict';var chunkM2YU5LAI_cjs=require('./chunk-M2YU5LAI.cjs'),utils=require('@easbot/utils'),database=require('@easbot/database');var c=utils.Log.create({service:"memory-schema-migrations"}),m=1,I=[{id:1,description:"v1 baseline: memory_facts / memory_vectors / embedding_cache / memory_facts_fts / nodes / edges / meta\uFF08\u4E0E v0.3.x createTables \u8F93\u51FA\u5BF9\u9F50\uFF0C\u8001 db \u8DD1\u8BE5\u8FC1\u79FB\u4E0D\u7834\u574F\u73B0\u6709\u8868\uFF09",up:[`CREATE TABLE IF NOT EXISTS memory_facts (
|
|
2
2
|
id TEXT PRIMARY KEY,
|
|
3
3
|
agent_id TEXT NOT NULL,
|
|
4
4
|
session_id TEXT,
|
|
@@ -9,12 +9,12 @@
|
|
|
9
9
|
importance INTEGER NOT NULL CHECK(importance >= 1 AND importance <= 10),
|
|
10
10
|
source TEXT NOT NULL CHECK(source IN ('session_self_write', 'historical')),
|
|
11
11
|
tags TEXT,
|
|
12
|
-
node_ids TEXT,
|
|
13
12
|
file_path TEXT,
|
|
14
13
|
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
|
15
|
-
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
|
16
|
-
|
|
17
|
-
|
|
14
|
+
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
|
15
|
+
)`,"CREATE INDEX IF NOT EXISTS idx_memory_facts_agent_id ON memory_facts(agent_id)","CREATE INDEX IF NOT EXISTS idx_memory_facts_agent_category ON memory_facts(agent_id, category)","CREATE INDEX IF NOT EXISTS idx_memory_facts_agent_importance ON memory_facts(agent_id, importance DESC)","CREATE INDEX IF NOT EXISTS idx_memory_facts_created_at ON memory_facts(created_at)",`CREATE UNIQUE INDEX IF NOT EXISTS idx_memory_facts_session_msg_partial
|
|
16
|
+
ON memory_facts(session_id, msg_id)
|
|
17
|
+
WHERE msg_id IS NOT NULL`,`CREATE TABLE IF NOT EXISTS memory_vectors (
|
|
18
18
|
fact_id TEXT PRIMARY KEY,
|
|
19
19
|
embedding BLOB NOT NULL,
|
|
20
20
|
FOREIGN KEY (fact_id) REFERENCES memory_facts(id) ON DELETE CASCADE
|
|
@@ -34,9 +34,19 @@
|
|
|
34
34
|
type TEXT NOT NULL,
|
|
35
35
|
owner_agent_id TEXT,
|
|
36
36
|
properties TEXT,
|
|
37
|
+
embedding BLOB,
|
|
37
38
|
createdAt DATETIME DEFAULT CURRENT_TIMESTAMP,
|
|
38
39
|
updatedAt DATETIME DEFAULT CURRENT_TIMESTAMP
|
|
39
|
-
)`,"CREATE INDEX IF NOT EXISTS idx_nodes_name ON nodes(name)","CREATE INDEX IF NOT EXISTS idx_nodes_type ON nodes(type)","CREATE INDEX IF NOT EXISTS idx_nodes_owner_agent_id ON nodes(owner_agent_id)","CREATE UNIQUE INDEX IF NOT EXISTS idx_nodes_name_type ON nodes(name, type)",`CREATE TABLE IF NOT EXISTS
|
|
40
|
+
)`,"CREATE INDEX IF NOT EXISTS idx_nodes_name ON nodes(name)","CREATE INDEX IF NOT EXISTS idx_nodes_type ON nodes(type)","CREATE INDEX IF NOT EXISTS idx_nodes_owner_agent_id ON nodes(owner_agent_id)","CREATE INDEX IF NOT EXISTS idx_nodes_embedding ON nodes(embedding) WHERE embedding IS NOT NULL","CREATE UNIQUE INDEX IF NOT EXISTS idx_nodes_name_type ON nodes(name, type)",`CREATE TABLE IF NOT EXISTS fact_nodes (
|
|
41
|
+
fact_id TEXT NOT NULL,
|
|
42
|
+
node_id INTEGER NOT NULL,
|
|
43
|
+
source TEXT NOT NULL DEFAULT 'kg_extract',
|
|
44
|
+
score REAL NOT NULL DEFAULT 1.0,
|
|
45
|
+
createdAt DATETIME DEFAULT CURRENT_TIMESTAMP,
|
|
46
|
+
PRIMARY KEY (fact_id, node_id, source),
|
|
47
|
+
FOREIGN KEY (fact_id) REFERENCES memory_facts(id) ON DELETE CASCADE,
|
|
48
|
+
FOREIGN KEY (node_id) REFERENCES nodes(id) ON DELETE CASCADE
|
|
49
|
+
)`,"CREATE INDEX IF NOT EXISTS idx_fact_nodes_node ON fact_nodes(node_id)","CREATE INDEX IF NOT EXISTS idx_fact_nodes_fact ON fact_nodes(fact_id)","CREATE INDEX IF NOT EXISTS idx_fact_nodes_source ON fact_nodes(source)",`CREATE TABLE IF NOT EXISTS edges (
|
|
40
50
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
41
51
|
source INTEGER NOT NULL,
|
|
42
52
|
target INTEGER NOT NULL,
|
|
@@ -48,24 +58,21 @@
|
|
|
48
58
|
)`,"CREATE INDEX IF NOT EXISTS idx_edges_source ON edges(source)","CREATE INDEX IF NOT EXISTS idx_edges_target ON edges(target)","CREATE INDEX IF NOT EXISTS idx_edges_relation ON edges(relation)","CREATE UNIQUE INDEX IF NOT EXISTS idx_edges_unique ON edges(source, target, relation)",`CREATE TABLE IF NOT EXISTS meta (
|
|
49
59
|
key TEXT PRIMARY KEY,
|
|
50
60
|
value TEXT
|
|
51
|
-
)
|
|
61
|
+
)`,"ALTER TABLE nodes ADD COLUMN embedding BLOB","CREATE INDEX IF NOT EXISTS idx_nodes_embedding ON nodes(embedding) WHERE embedding IS NOT NULL"]}];function l(n,e=m,r={}){n.exec(`CREATE TABLE IF NOT EXISTS schema_migrations (
|
|
52
62
|
id INTEGER PRIMARY KEY,
|
|
53
63
|
applied_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
|
54
|
-
)`);let
|
|
55
|
-
SELECT COUNT(*) as c FROM
|
|
56
|
-
|
|
57
|
-
FROM memory_facts mf, JSON_EACH(mf.node_ids)
|
|
58
|
-
WHERE mf.node_ids IS NOT NULL
|
|
59
|
-
) LEFT JOIN nodes n ON n.id = CAST(node_id AS INTEGER)
|
|
64
|
+
)`);let t=n.prepare("SELECT id FROM schema_migrations").all(),s=new Set(t.map(i=>i.id)),a={applied:[],pending:[],errors:[],currentVersion:t.length===0?0:Math.max(...t.map(i=>i.id)),targetVersion:e};for(let i of I){if(i.id>e)break;if(s.has(i.id)){a.pending.push(i.id);continue}if(r.dryRun){a.applied.push(i.id);continue}try{R(n,i.up),n.prepare("INSERT INTO schema_migrations (id) VALUES (?)").run(i.id),s.add(i.id),a.applied.push(i.id),c.info("migration applied",{id:i.id,description:i.description});}catch(o){let d=o instanceof Error?o.message:String(o),T=i.up[0]??"";a.errors.push({migrationId:i.id,sql:T,error:d}),c.warn("migration step failed",{id:i.id,error:d,sqlCount:i.up.length});}}return a}function R(n,e){for(let r of e)try{n.exec(r);}catch(t){let s=t instanceof Error?t.message:String(t);if(f(s)){c.debug("migration: column already exists, skipping",{sql:r.slice(0,80)});continue}throw t}}function f(n){return /duplicate column name/i.test(n)}function _(n){try{let e=n.prepare("SELECT id FROM schema_migrations").all();return e.length===0?0:Math.max(...e.map(r=>r.id))}catch{return 0}}var N=utils.Log.create({service:"memory-database"}),u=class{constructor(e){chunkM2YU5LAI_cjs.a(this,"db",null);chunkM2YU5LAI_cjs.a(this,"storagePath");chunkM2YU5LAI_cjs.a(this,"backend","better-sqlite3");chunkM2YU5LAI_cjs.a(this,"initialized",false);chunkM2YU5LAI_cjs.a(this,"initPromise",null);this.storagePath=e===":memory:"?e:utils.Filesystem.normalize(e);}async initialize(){if(!this.initialized){if(this.initPromise){await this.initPromise;return}this.initPromise=this.doInitialize();try{await this.initPromise,this.initialized=!0;}catch(e){try{this.db&&this.db.close();}catch{}throw this.db=null,this.initPromise=null,e}}}async doInitialize(){try{let e=this.openConnection();e.initialize(),this.db=e,this.applyPragmas(),this.runAllMigrations();}catch(e){let r=e instanceof Error?e.message:String(e);throw N.error("Database initialization failed",{error:r}),e}}openConnection(){return database.createSyncSqliteConnection({path:this.storagePath,backend:this.backend,walMode:true,foreignKeys:true,busyTimeoutMs:5e3})}applyPragmas(){if(this.db)try{this.db.pragma("synchronous = NORMAL"),this.db.pragma("cache_size = -64000"),this.db.pragma("temp_store = MEMORY"),this.db.pragma("foreign_keys = ON");}catch(e){N.warn("Failed to apply memory PRAGMAs",{error:String(e)});}}runAllMigrations(){if(!this.db)throw new Error("Database not initialized");let e=l(this.db,m);if(e.errors.length>0){let r=e.errors.map(t=>`migration ${t.migrationId}: ${t.error}`).join("; ");throw new Error(`Some migrations failed: ${r}`)}}query(e,r){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");try{let t=this.db.prepare(e);return r?t.all(...r):t.all()}catch(t){throw new Error(`Query failed: ${t.message}`)}}agentFilter(e){return typeof e=="string"&&e.trim().length>0?{where:"WHERE agent_id = ?",params:[e.trim()]}:{where:"",params:[]}}run(e,r){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");try{let t=this.db.prepare(e),s=r?t.run(...r):t.run();return {lastID:Number(s.lastInsertRowid),changes:s.changes}}catch(t){throw new Error(`Write failed: ${t.message}`)}}transaction(e){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");return this.db.transaction(e)()}prepare(e){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");return this.db.prepare(e)}exec(e){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");this.db.exec(e);}getDb(){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");return this.db}getPath(){return this.storagePath}getSchemaVersion(){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");return _(this.db)}close(){if(this.db){try{this.db.close();}catch(e){N.warn("Failed to close memory database",{error:String(e)});}this.db=null,this.initialized=false,this.initPromise=null;}}healthCheck(){try{return this.db?(this.db.exec("SELECT 1"),!0):!1}catch{return false}}checkIntegrity(){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");let e=S=>this.db.prepare(S).get().c,r={memory_facts:e("SELECT COUNT(*) as c FROM memory_facts"),memory_vectors:e("SELECT COUNT(*) as c FROM memory_vectors"),embedding_cache:e("SELECT COUNT(*) as c FROM embedding_cache"),memory_facts_fts:e("SELECT COUNT(*) as c FROM memory_facts_fts"),nodes:e("SELECT COUNT(*) as c FROM nodes"),edges:e("SELECT COUNT(*) as c FROM edges"),fact_nodes:e("SELECT COUNT(*) as c FROM fact_nodes"),meta:e("SELECT COUNT(*) as c FROM meta"),schema_migrations:e("SELECT COUNT(*) as c FROM schema_migrations")},t=[],s=e(`
|
|
65
|
+
SELECT COUNT(*) as c FROM fact_nodes fn
|
|
66
|
+
LEFT JOIN nodes n ON n.id = fn.node_id
|
|
60
67
|
WHERE n.id IS NULL
|
|
61
|
-
`);s>0&&
|
|
68
|
+
`);s>0&&t.push({severity:"error",message:`orphan node references (fact_nodes): ${s}`});let a=e(`
|
|
62
69
|
SELECT COUNT(*) as c FROM edges e WHERE NOT EXISTS (SELECT 1 FROM nodes n WHERE n.id = e.source)
|
|
63
|
-
`);a>0&&
|
|
70
|
+
`);a>0&&t.push({severity:"error",message:`orphan edges (source): ${a}`});let i=e(`
|
|
64
71
|
SELECT COUNT(*) as c FROM edges e WHERE NOT EXISTS (SELECT 1 FROM nodes n WHERE n.id = e.target)
|
|
65
|
-
`);i>0&&
|
|
72
|
+
`);i>0&&t.push({severity:"error",message:`orphan edges (target): ${i}`});let o=e("SELECT COUNT(*) as c FROM edges WHERE source = target");o>0&&t.push({severity:"warn",message:`self-loop edges: ${o}`});let d=e(`
|
|
66
73
|
SELECT COUNT(*) as c FROM (
|
|
67
74
|
SELECT fact_id FROM memory_facts_fts
|
|
68
75
|
EXCEPT
|
|
69
76
|
SELECT id FROM memory_facts
|
|
70
77
|
)
|
|
71
|
-
`);d>0&&
|
|
78
|
+
`);d>0&&t.push({severity:"warn",message:`FTS out of sync (orphan entries): ${d}`});let T=e("SELECT COUNT(*) as c FROM (SELECT id, COUNT(*) as c FROM memory_facts GROUP BY id HAVING c > 1)");T>0&&t.push({severity:"error",message:`duplicate fact ids: ${T}`});let g=e("SELECT COUNT(*) as c FROM memory_facts WHERE content IS NULL OR content = ''");return g>0&&t.push({severity:"error",message:`memory_facts with null/empty content: ${g}`}),{issues:t,stats:r}}getMeta(e){if(!this.db)throw new Error("Database not initialized");return this.db.prepare("SELECT value FROM meta WHERE key = ?").get(e)?.value??null}setMeta(e,r){if(!this.db)throw new Error("Database not initialized");this.db.prepare("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)").run(e,r);}};exports.a=m;exports.b=I;exports.c=l;exports.d=_;exports.e=u;
|
|
@@ -1,22 +1,22 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {u,w as w$1,i,h,j,g,f as f$1,e,d,c,x as x$1}from'./chunk-2TBNGTSA.mjs';import {extendKnownErrorCodes,ToolRegistry,createAndStartStdioServer,formatFailClosed}from'@easbot/mcp';import {Log,Locale,TruncateContent}from'@easbot/utils';var te=Log.create({service:"memory-format-truncate"}),Q="**`";var z=24e3,J=25e3;async function f(e,n={}){let r=n.softLimit??z,s=n.hardCeiling??J,o=n.toolName??"memory",d=n.writeToDisk!==false;if(e.length<=r)return {content:e,truncated:false};let i=e.slice(0,s),t=i.lastIndexOf(`
|
|
2
2
|
${Q}`),a=i.lastIndexOf(`
|
|
3
|
-
`),u;t>s*.5?u=t:a>0?u=a:u=-1;let
|
|
3
|
+
`),u;t>s*.5?u=t:a>0?u=a:u=-1;let c=u>0?i.slice(0,u):i,l=c+"\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(!d)return {content:l,truncated:true,outputPath:"",hint:"Make another recall / graph_query with narrower scope.",info:`... ${e.length-c.length}/${e.length} characters truncated ...`};try{let g=await TruncateContent.truncate(e,{maxChars:c.length,direction:"head",label:`${o}-output`});return g.truncated?{content:l,truncated:!0,outputPath:g.outputPath,hint: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-c.length}/${e.length} characters truncated ...`}}catch(g){return te.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-c.length}/${e.length} characters truncated ...`}}}function $(e,n={}){let r=n.softLimit??z,s=n.hardCeiling??J;if(e.length<=r)return {content:e,truncated:false};let o=e.slice(0,s),d=o.lastIndexOf(`
|
|
4
4
|
${Q}`),i=o.lastIndexOf(`
|
|
5
|
-
`),t;
|
|
5
|
+
`),t;d>s*.5?t=d:i>0?t=i:t=-1;let a=t>0?o.slice(0,t):o;return {content:a+`
|
|
6
6
|
|
|
7
7
|
... (output truncated; tail dropped at section boundary)`,truncated:true,outputPath:"",hint:"",info:`... ${e.length-a.length}/${e.length} characters truncated ...`}}function ne(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
8
|
|
|
9
|
-
`}function I(e,n,r={}){return (X[e]??X.default).replace(/<(\w+)>/g,(o,
|
|
10
|
-
- tags: ${e.tags.join(", ")}`:"",
|
|
9
|
+
`}function I(e,n,r={}){return (X[e]??X.default).replace(/<(\w+)>/g,(o,d)=>d==="tool"?n:r[d]??`<${d}>`)}var X={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 Z(e,n,r,s){let o=e.tags&&e.tags.length>0?`
|
|
10
|
+
- tags: ${e.tags.join(", ")}`:"",d=e.sessionId?`
|
|
11
11
|
- session: ${e.sessionId}`:"",i=e.msgId?`
|
|
12
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
|
|
14
|
-
`):" (no relations)";
|
|
13
|
+
- score: ${n.toFixed(3)}${r?` (${r})`:""}`:"",a=e.truncated?" [truncated]":"",u="";if(s&&s.length>0){let c=[];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)";c.push(` - Node: ${m.name} (${m.type})
|
|
15
15
|
${g}`);}u=`
|
|
16
16
|
- linked KG nodes (${s.length}):
|
|
17
|
-
${
|
|
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}${
|
|
19
|
-
`)}async function
|
|
17
|
+
${c.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}${d}${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=ne(n.pendingFiles,new Set),i=[`Found ${e.total} fact(s) for query "${n.query}" (agentId=${n.agentId}, scope=${n.scope}):`,"",o??"",s].join(`
|
|
20
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=>Z(b.fact,b.score,b.source,b.nodes)).join(`
|
|
21
21
|
`);return `${g}
|
|
22
22
|
|
|
@@ -26,35 +26,41 @@ ${y}`}).join(`
|
|
|
26
26
|
\u26A0\uFE0F warnings:
|
|
27
27
|
${e.warnings.map(m=>` - ${m}`).join(`
|
|
28
28
|
`)}
|
|
29
|
-
`:"",
|
|
29
|
+
`:"",c=`${i}
|
|
30
30
|
|
|
31
31
|
${a}${u}
|
|
32
32
|
|
|
33
|
-
${I("recall",r)}`;return n.sync?$(
|
|
34
|
-
- linked KG nodes: ${
|
|
33
|
+
${I("recall",r)}`;return n.sync?$(c,{}).content:(await f(c,{toolName:r,writeToDisk:n.writeToDisk})).content}async function v(e,n={}){let r=n.toolName??"memory_remember",s=`**\`memory_remember:${e.fact.id}\`**`,o=Z(e.fact),d=e.nodeIds??[],i=d.length>0?`
|
|
34
|
+
- linked KG nodes: ${d.join(", ")}
|
|
35
35
|
`:"",t=`${s}
|
|
36
36
|
|
|
37
37
|
${o}${i}
|
|
38
38
|
|
|
39
|
-
${I("remember",r)}`;return n.sync?$(t,{}).content:(await f(t,{toolName:r,writeToDisk:n.writeToDisk})).content}async function N(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).`,
|
|
39
|
+
${I("remember",r)}`;return n.sync?$(t,{}).content:(await f(t,{toolName:r,writeToDisk:n.writeToDisk})).content}async function N(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).`,d=e.truncatedCount>0?` (truncated: ${e.truncatedCount} more, re-run with narrower filter)`:"",i=[s,"",o+d,"",e.deletedIds.length>0?`deleted ids:
|
|
40
40
|
${e.deletedIds.map(t=>` - ${t}`).join(`
|
|
41
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
|
|
43
|
-
`),
|
|
44
|
-
`),i=[s,"",`nodes (${e.nodes.length}${e.truncated?` / total ${e.totalNodes}`:""}):`,o||" (none)","",`edges (${e.edges.length}${e.truncated?` / total ${e.totalEdges}`:""}):`,
|
|
45
|
-
`);return n.sync?$(i,{}).content:(await f(i,{toolName:r,writeToDisk:n.writeToDisk})).content}async function A(e,n={}){let r=n.toolName??"memory_status",
|
|
46
|
-
`);return n.sync?$(
|
|
47
|
-
`);return n.sync?$(o,{}).content:(await f(o,{toolName:r,writeToDisk:n.writeToDisk})).content}var
|
|
48
|
-
`);return n.sync?$(
|
|
49
|
-
`),i=[s,"",
|
|
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
|
|
42
|
+
`);return n.sync?$(i,{}).content:(await f(i,{toolName:r,writeToDisk:n.writeToDisk})).content}async function _(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
|
+
`),d=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}`:""}):`,d||" (none)","",I("graph_query",r)].join(`
|
|
45
|
+
`);return n.sync?$(i,{}).content:(await f(i,{toolName:r,writeToDisk:n.writeToDisk})).content}async function A(e,n={}){let r=n.toolName??"memory_status",d=["**`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?$(d,{}).content:(await f(d,{toolName:r,writeToDisk:n.writeToDisk})).content}async function M(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 x=20;async function O(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,x);for(let t of i)o.push(`- ${t.firstFactId} (${t.firstCreatedAt})`),o.push(` - source: \`${t.source}\``),o.push(` - target: \`${t.target}\``);e.archivedRecords.length>x&&o.push(`... and ${e.archivedRecords.length-x} more (use --json for full list)`);}o.push("",`duration: ${e.durationMs}ms`,"",I("sync",r));let d=o.join(`
|
|
48
|
+
`);return n.sync?$(d,{}).content:(await f(d,{toolName:r,writeToDisk:n.writeToDisk})).content}async function P(e,n={}){let r=n.toolName??"memory_doctor",s=`**\`memory_doctor:${e.healthy?"OK":"ISSUES"}\`**`,o=t=>t?"\u2705":"\u274C",d=e.checks.map(t=>`${o(t.passed)} ${t.name}: ${t.message}`).join(`
|
|
49
|
+
`),i=[s,"",d,"",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 N(o?s:n,r);case "graph_query":return _(o?s:n,r);case "status":return A(o?s:n,r);case "consolidate":return M(o?s:n,r);case "sync":return O(o?s:n,r);case "doctor":return P(o?s:n,r);default:throw new Error(`renderOperationMarkdown: unsupported op "${e}"`)}}var k=Log.create({service:"memory-mcp-stdio"});function fe(e){let n=new Map,r=e.isRemote??true,s=!r;function o(t){let a=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:x$1({agentId:e.agentId,dbPath:e.dbPath})}}function d(t,a){return {content:[{type:"text",text:t}],isError:a}}function i(t){return formatFailClosed(t,s)}return n.set("recall",async t=>{try{let a=t,u=o({agentId:a.agentId}),c=await w$1("recall",t,u);return {content:[{type:"text",text:await w("recall",c,{toolName:"memory_recall",query:a.query,agentId:a.agentId??e.agentId,scope:a.scope??"agent_only"})}]}}catch(a){return d(i(a),true)}}),n.set("remember",async t=>{try{let u=o({agentId:t.agentId}),c=await w$1("remember",t,u);return {content:[{type:"text",text:await w("remember",c,{toolName:"memory_remember"})}]}}catch(a){return d(i(a),true)}}),n.set("update",async t=>{try{let u=o({agentId:t.agentId}),c=await w$1("update",t,u),m=c.fieldsUpdated.length>0?c.fieldsUpdated.join(", "):"(no-op)",l=c.contentChanged?" (embedding rewritten)":"";return {content:[{type:"text",text:`Memory updated.
|
|
51
|
+
id: ${c.fact.id}
|
|
52
|
+
category: ${c.fact.category}
|
|
53
|
+
importance: ${c.fact.importance}
|
|
54
|
+
fields updated: ${m}${l}
|
|
55
|
+
updated_at: ${c.fact.updatedAt}
|
|
56
|
+
`}]}}catch(a){return d(i(a),true)}}),n.set("forget",async t=>{try{let u=o({agentId:t.agentId}),c=await w$1("forget",t,u);return {content:[{type:"text",text:await w("forget",c,{toolName:"memory_forget"})}]}}catch(a){return d(i(a),true)}}),n.set("extract",async t=>{try{let u=o({agentId:t.agentId}),m=await w$1("extract",t,u);return {content:[{type:"text",text:`Extract completed.
|
|
51
57
|
sessionId: ${t.sessionId??"(unknown)"}
|
|
52
58
|
extractedCount: ${m.extractedCount}
|
|
53
59
|
factIds: ${m.factIds.length>0?m.factIds.join(", "):"(none)"}
|
|
54
60
|
messageRange: ${m.messageRange.fromMessageId} -> ${m.messageRange.toMessageId}
|
|
55
|
-
`}]}}catch(a){return
|
|
56
|
-
dbPath: ${
|
|
57
|
-
tablesCreated: ${
|
|
58
|
-
migrationsApplied: ${
|
|
59
|
-
durationMs: ${
|
|
60
|
-
`}]}}catch(a){return
|
|
61
|
+
`}]}}catch(a){return d(i(a),true)}}),n.set("consolidate",async t=>{try{let u=o({agentId:t.agentId,isTrustedLocal:!0}),c=await w$1("consolidate",t,u);return {content:[{type:"text",text:await w("consolidate",c,{toolName:"memory_consolidate"})}]}}catch(a){return d(i(a),true)}}),n.set("sync",async t=>{try{let u=t.agentId?.trim();if(!u)return d(i(new Error("memory_sync: agentId is required (sync requires agentId, see ADR 0069)")),!0);let c=o({agentId:u,isTrustedLocal:!0}),m=await w$1("sync",t,c);return {content:[{type:"text",text:await w("sync",m,{toolName:"memory_sync"})}]}}catch(a){return d(i(a),true)}}),n.set("graph_query",async t=>{try{let a=t,u=o({agentId:a.agentId}),c=await w$1("graph_query",t,u);return {content:[{type:"text",text:await w("graph_query",c,{toolName:"memory_graph_query",scope:a.scope??"agent_only"})}]}}catch(a){return d(i(a),true)}}),n.set("status",async t=>{try{let u=o({agentId:(t??{}).agentId}),c=await w$1("status",t,u);return {content:[{type:"text",text:await w("status",c,{toolName:"memory_status"})}]}}catch(a){return d(i(a),true)}}),n.set("doctor",async t=>{try{let u=o({agentId:(t??{}).agentId,isTrustedLocal:!0}),c=await w$1("doctor",t,u);return {content:[{type:"text",text:await w("doctor",c,{toolName:"memory_doctor"})}]}}catch(a){return d(i(a),true)}}),n.set("init",async t=>{try{let a=o({isTrustedLocal:!0}),c=await w$1("init",t,a);return {content:[{type:"text",text:`Init complete.
|
|
62
|
+
dbPath: ${c.dbPath}
|
|
63
|
+
tablesCreated: ${c.tablesCreated}
|
|
64
|
+
migrationsApplied: ${c.migrationsApplied}
|
|
65
|
+
durationMs: ${c.durationMs}
|
|
66
|
+
`}]}}catch(a){return d(i(a),true)}}),n}var $e={recall:c,remember:d,forget:e,extract:f$1,consolidate:g,sync:j,graph_query:h,init:i};function be(e,n){let r=u[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=$e[e];return {name:e,description:r?.annotations?.defaultDescription??`memory op: ${e}`,inputSchema:o??{type:"object",properties:{},required:[]},annotations:s,handler:n}}var V;(r=>{async function e(s,o){let{getMemoryDbPath:d,getInstance:i}=await import('./interfaces-LPJU4KS3.mjs'),a=o!==null&&typeof o=="object"&&"agentId"in o&&"dbPath"in o?o:{agentId:process.env.EASBOT_AGENT_ID??"default",dbPath:d(),workspaceDir:i().worktree,isRemote:false};extendKnownErrorCodes(["AGENT_ID_REQUIRED","SESSION_ID_REQUIRED","CATEGORY_REQUIRED","IMPORTANCE_REQUIRED","TIMERANGE_REQUIRED","DRY_RUN_NO_DELETE"]);let u$1=new ToolRegistry,c=fe(a),m=Object.keys(u);for(let p of m){let L=c.get(p);if(!L)throw new Error(`MemoryStdioServer.start: missing handler for tool "${p}"`);u$1.register(be(p,L));}k.info("starting memory MCP stdio server",{id:s.id,name:s.name,toolCount:m.length,isRemote:a.isRemote??true});let l=await createAndStartStdioServer(s,u$1),g=null,y=new Promise(p=>{g=p;}),b=p=>{k.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){k.warn("failed to remove signal handlers",{error:p instanceof Error?p.message:String(p)});}try{await l.stop();}catch(p){k.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(u)}r.getToolNames=n;})(V||(V={}));export{w as a,V as b};
|
|
@@ -1,22 +1,22 @@
|
|
|
1
|
-
'use strict';var
|
|
2
|
-
${
|
|
3
|
-
`),u;t>s*.5?u=t:a>0?u=a:u=-1;let
|
|
4
|
-
${
|
|
5
|
-
`),t;
|
|
1
|
+
'use strict';var chunk5YDI4K2F_cjs=require('./chunk-5YDI4K2F.cjs'),mcp=require('@easbot/mcp'),utils=require('@easbot/utils');var ee=utils.Log.create({service:"memory-format-truncate"}),K="**`";var Q=24e3,z=25e3;async function f(e,n={}){let r=n.softLimit??Q,s=n.hardCeiling??z,o=n.toolName??"memory",d=n.writeToDisk!==false;if(e.length<=r)return {content:e,truncated:false};let i=e.slice(0,s),t=i.lastIndexOf(`
|
|
2
|
+
${K}`),a=i.lastIndexOf(`
|
|
3
|
+
`),u;t>s*.5?u=t:a>0?u=a:u=-1;let c=u>0?i.slice(0,u):i,l=c+"\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(!d)return {content:l,truncated:true,outputPath:"",hint:"Make another recall / graph_query with narrower scope.",info:`... ${e.length-c.length}/${e.length} characters truncated ...`};try{let g=await utils.TruncateContent.truncate(e,{maxChars:c.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-c.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-c.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),d=o.lastIndexOf(`
|
|
4
|
+
${K}`),i=o.lastIndexOf(`
|
|
5
|
+
`),t;d>s*.5?t=d:i>0?t=i:t=-1;let a=t>0?o.slice(0,t):o;return {content:a+`
|
|
6
6
|
|
|
7
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
8
|
|
|
9
|
-
`}function I(e,n,r={}){return (J[e]??J.default).replace(/<(\w+)>/g,(o,
|
|
10
|
-
- tags: ${e.tags.join(", ")}`:"",
|
|
9
|
+
`}function I(e,n,r={}){return (J[e]??J.default).replace(/<(\w+)>/g,(o,d)=>d==="tool"?n:r[d]??`<${d}>`)}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(", ")}`:"",d=e.sessionId?`
|
|
11
11
|
- session: ${e.sessionId}`:"",i=e.msgId?`
|
|
12
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
|
|
14
|
-
`):" (no relations)";
|
|
13
|
+
- score: ${n.toFixed(3)}${r?` (${r})`:""}`:"",a=e.truncated?" [truncated]":"",u="";if(s&&s.length>0){let c=[];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)";c.push(` - Node: ${m.name} (${m.type})
|
|
15
15
|
${g}`);}u=`
|
|
16
16
|
- linked KG nodes (${s.length}):
|
|
17
|
-
${
|
|
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}${
|
|
19
|
-
`)}async function
|
|
17
|
+
${c.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}${d}${i}${u}`,"",e.content,""].join(`
|
|
19
|
+
`)}async function x(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
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
21
|
`);return `${g}
|
|
22
22
|
|
|
@@ -26,35 +26,41 @@ ${y}`}).join(`
|
|
|
26
26
|
\u26A0\uFE0F warnings:
|
|
27
27
|
${e.warnings.map(m=>` - ${m}`).join(`
|
|
28
28
|
`)}
|
|
29
|
-
`:"",
|
|
29
|
+
`:"",c=`${i}
|
|
30
30
|
|
|
31
31
|
${a}${u}
|
|
32
32
|
|
|
33
|
-
${I("recall",r)}`;return n.sync?$(
|
|
34
|
-
- linked KG nodes: ${
|
|
33
|
+
${I("recall",r)}`;return n.sync?$(c,{}).content:(await f(c,{toolName:r,writeToDisk:n.writeToDisk})).content}async function S(e,n={}){let r=n.toolName??"memory_remember",s=`**\`memory_remember:${e.fact.id}\`**`,o=X(e.fact),d=e.nodeIds??[],i=d.length>0?`
|
|
34
|
+
- linked KG nodes: ${d.join(", ")}
|
|
35
35
|
`:"",t=`${s}
|
|
36
36
|
|
|
37
37
|
${o}${i}
|
|
38
38
|
|
|
39
|
-
${I("remember",r)}`;return n.sync?$(t,{}).content:(await f(t,{toolName:r,writeToDisk:n.writeToDisk})).content}async function
|
|
39
|
+
${I("remember",r)}`;return n.sync?$(t,{}).content:(await f(t,{toolName:r,writeToDisk:n.writeToDisk})).content}async function v(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).`,d=e.truncatedCount>0?` (truncated: ${e.truncatedCount} more, re-run with narrower filter)`:"",i=[s,"",o+d,"",e.deletedIds.length>0?`deleted ids:
|
|
40
40
|
${e.deletedIds.map(t=>` - ${t}`).join(`
|
|
41
41
|
`)}`:"(no ids to show)","",I("forget",r)].join(`
|
|
42
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
|
-
`),
|
|
44
|
-
`),i=[s,"",`nodes (${e.nodes.length}${e.truncated?` / total ${e.totalNodes}`:""}):`,o||" (none)","",`edges (${e.edges.length}${e.truncated?` / total ${e.totalEdges}`:""}):`,
|
|
45
|
-
`);return n.sync?$(i,{}).content:(await f(i,{toolName:r,writeToDisk:n.writeToDisk})).content}async function
|
|
46
|
-
`);return n.sync?$(
|
|
47
|
-
`);return n.sync?$(o,{}).content:(await f(o,{toolName:r,writeToDisk:n.writeToDisk})).content}var
|
|
48
|
-
`);return n.sync?$(
|
|
49
|
-
`),i=[s,"",
|
|
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
|
|
43
|
+
`),d=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}`:""}):`,d||" (none)","",I("graph_query",r)].join(`
|
|
45
|
+
`);return n.sync?$(i,{}).content:(await f(i,{toolName:r,writeToDisk:n.writeToDisk})).content}async function _(e,n={}){let r=n.toolName??"memory_status",d=["**`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?$(d,{}).content:(await f(d,{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 k=20;async function M(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,k);for(let t of i)o.push(`- ${t.firstFactId} (${t.firstCreatedAt})`),o.push(` - source: \`${t.source}\``),o.push(` - target: \`${t.target}\``);e.archivedRecords.length>k&&o.push(`... and ${e.archivedRecords.length-k} more (use --json for full list)`);}o.push("",`duration: ${e.durationMs}ms`,"",I("sync",r));let d=o.join(`
|
|
48
|
+
`);return n.sync?$(d,{}).content:(await f(d,{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",d=e.checks.map(t=>`${o(t.passed)} ${t.name}: ${t.message}`).join(`
|
|
49
|
+
`),i=[s,"",d,"",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 x(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 S(i,r)}case "forget":return v(o?s:n,r);case "graph_query":return N(o?s:n,r);case "status":return _(o?s:n,r);case "consolidate":return A(o?s:n,r);case "sync":return M(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 ye(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:chunk5YDI4K2F_cjs.x({agentId:e.agentId,dbPath:e.dbPath})}}function d(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}),c=await chunk5YDI4K2F_cjs.w("recall",t,u);return {content:[{type:"text",text:await w("recall",c,{toolName:"memory_recall",query:a.query,agentId:a.agentId??e.agentId,scope:a.scope??"agent_only"})}]}}catch(a){return d(i(a),true)}}),n.set("remember",async t=>{try{let u=o({agentId:t.agentId}),c=await chunk5YDI4K2F_cjs.w("remember",t,u);return {content:[{type:"text",text:await w("remember",c,{toolName:"memory_remember"})}]}}catch(a){return d(i(a),true)}}),n.set("update",async t=>{try{let u=o({agentId:t.agentId}),c=await chunk5YDI4K2F_cjs.w("update",t,u),m=c.fieldsUpdated.length>0?c.fieldsUpdated.join(", "):"(no-op)",l=c.contentChanged?" (embedding rewritten)":"";return {content:[{type:"text",text:`Memory updated.
|
|
51
|
+
id: ${c.fact.id}
|
|
52
|
+
category: ${c.fact.category}
|
|
53
|
+
importance: ${c.fact.importance}
|
|
54
|
+
fields updated: ${m}${l}
|
|
55
|
+
updated_at: ${c.fact.updatedAt}
|
|
56
|
+
`}]}}catch(a){return d(i(a),true)}}),n.set("forget",async t=>{try{let u=o({agentId:t.agentId}),c=await chunk5YDI4K2F_cjs.w("forget",t,u);return {content:[{type:"text",text:await w("forget",c,{toolName:"memory_forget"})}]}}catch(a){return d(i(a),true)}}),n.set("extract",async t=>{try{let u=o({agentId:t.agentId}),m=await chunk5YDI4K2F_cjs.w("extract",t,u);return {content:[{type:"text",text:`Extract completed.
|
|
51
57
|
sessionId: ${t.sessionId??"(unknown)"}
|
|
52
58
|
extractedCount: ${m.extractedCount}
|
|
53
59
|
factIds: ${m.factIds.length>0?m.factIds.join(", "):"(none)"}
|
|
54
60
|
messageRange: ${m.messageRange.fromMessageId} -> ${m.messageRange.toMessageId}
|
|
55
|
-
`}]}}catch(a){return
|
|
56
|
-
dbPath: ${
|
|
57
|
-
tablesCreated: ${
|
|
58
|
-
migrationsApplied: ${
|
|
59
|
-
durationMs: ${
|
|
60
|
-
`}]}}catch(a){return
|
|
61
|
+
`}]}}catch(a){return d(i(a),true)}}),n.set("consolidate",async t=>{try{let u=o({agentId:t.agentId,isTrustedLocal:!0}),c=await chunk5YDI4K2F_cjs.w("consolidate",t,u);return {content:[{type:"text",text:await w("consolidate",c,{toolName:"memory_consolidate"})}]}}catch(a){return d(i(a),true)}}),n.set("sync",async t=>{try{let u=t.agentId?.trim();if(!u)return d(i(new Error("memory_sync: agentId is required (sync requires agentId, see ADR 0069)")),!0);let c=o({agentId:u,isTrustedLocal:!0}),m=await chunk5YDI4K2F_cjs.w("sync",t,c);return {content:[{type:"text",text:await w("sync",m,{toolName:"memory_sync"})}]}}catch(a){return d(i(a),true)}}),n.set("graph_query",async t=>{try{let a=t,u=o({agentId:a.agentId}),c=await chunk5YDI4K2F_cjs.w("graph_query",t,u);return {content:[{type:"text",text:await w("graph_query",c,{toolName:"memory_graph_query",scope:a.scope??"agent_only"})}]}}catch(a){return d(i(a),true)}}),n.set("status",async t=>{try{let u=o({agentId:(t??{}).agentId}),c=await chunk5YDI4K2F_cjs.w("status",t,u);return {content:[{type:"text",text:await w("status",c,{toolName:"memory_status"})}]}}catch(a){return d(i(a),true)}}),n.set("doctor",async t=>{try{let u=o({agentId:(t??{}).agentId,isTrustedLocal:!0}),c=await chunk5YDI4K2F_cjs.w("doctor",t,u);return {content:[{type:"text",text:await w("doctor",c,{toolName:"memory_doctor"})}]}}catch(a){return d(i(a),true)}}),n.set("init",async t=>{try{let a=o({isTrustedLocal:!0}),c=await chunk5YDI4K2F_cjs.w("init",t,a);return {content:[{type:"text",text:`Init complete.
|
|
62
|
+
dbPath: ${c.dbPath}
|
|
63
|
+
tablesCreated: ${c.tablesCreated}
|
|
64
|
+
migrationsApplied: ${c.migrationsApplied}
|
|
65
|
+
durationMs: ${c.durationMs}
|
|
66
|
+
`}]}}catch(a){return d(i(a),true)}}),n}var fe={recall:chunk5YDI4K2F_cjs.c,remember:chunk5YDI4K2F_cjs.d,forget:chunk5YDI4K2F_cjs.e,extract:chunk5YDI4K2F_cjs.f,consolidate:chunk5YDI4K2F_cjs.g,sync:chunk5YDI4K2F_cjs.j,graph_query:chunk5YDI4K2F_cjs.h,init:chunk5YDI4K2F_cjs.i};function $e(e,n){let r=chunk5YDI4K2F_cjs.u[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=fe[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:d,getInstance:i}=await import('./interfaces-Q5OGU5EK.cjs'),a=o!==null&&typeof o=="object"&&"agentId"in o&&"dbPath"in o?o:{agentId:process.env.EASBOT_AGENT_ID??"default",dbPath:d(),workspaceDir:i().worktree,isRemote:false};mcp.extendKnownErrorCodes(["AGENT_ID_REQUIRED","SESSION_ID_REQUIRED","CATEGORY_REQUIRED","IMPORTANCE_REQUIRED","TIMERANGE_REQUIRED","DRY_RUN_NO_DELETE"]);let u=new mcp.ToolRegistry,c=ye(a),m=Object.keys(chunk5YDI4K2F_cjs.u);for(let p of m){let P=c.get(p);if(!P)throw new Error(`MemoryStdioServer.start: missing handler for tool "${p}"`);u.register($e(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(chunk5YDI4K2F_cjs.u)}r.getToolNames=n;})(exports.b||(exports.b={}));exports.a=w;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
'use strict';var chunkCPRDIUQ4_cjs=require('./chunk-CPRDIUQ4.cjs'),utils=require('@easbot/utils'),terminal=require('@easbot/terminal');var y=utils.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 terminal.renderLines({title:t,flat:e.map(a=>`$ easbot-memory ${a.name.padEnd(14)} ${a.description}`)})}function v(){let m=[terminal.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:")];terminal.printHuman(m);}function C(){v(),terminal.printHuman(["",terminal.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-RMPVWEVP.cjs');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 E(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-DGMGRNCG.cjs'),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)terminal.emitJsonOk(i,{command:e});else {let p=i;terminal.printHuman([terminal.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-ZENMAOMJ.cjs'),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?terminal.emitJsonOk(i,{command:e}):terminal.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-3ZY66RJQ.cjs'),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?terminal.emitJsonOk(i,{command:e}):terminal.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-GNIJL2DU.cjs'),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?terminal.emitJsonOk(i,{command:e}):terminal.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-YKDPZ7GA.cjs'),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?terminal.emitJsonOk(i,{command:e}):terminal.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-G4YJV756.cjs'),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?terminal.emitJsonOk(i,{command:e}):terminal.printHuman([s(i)],{title:"consolidate (pipeline)"}),{code:0,handled:!0,command:e}}case "sync":{let{parseSyncOptions:r,runSync:n,formatSyncText:s}=await import('./sync-64JINCSC.cjs'),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?terminal.emitJsonOk(i,{command:e}):terminal.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-GTYUNUJE.cjs'),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?terminal.emitJsonOk(i,{command:e}):terminal.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-UEKBJVCI.cjs'),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?terminal.emitJsonOk(o,{command:e}):terminal.printHuman([terminal.formatKnowledgeStatus(I(o))],{title:"memory status",boxed:!0}),{code:0,handled:!0,command:e}}case "doctor":{let{parseDoctorOptions:r,runDoctor:n}=await import('./doctor-YTUQCHFJ.cjs'),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?terminal.emitJsonOk(o,{command:e}):terminal.printHuman([terminal.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-RPPQ73HK.cjs'),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?terminal.emitJsonOk(i,{command:e}):terminal.printHuman([s(i)],{title:"memory config"}),{code:0,handled:!0,command:e}}case "mcp":{let{parseMcpOptions:r,runMcp:n}=await import('./mcp-EHUKGJRB.cjs'),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?terminal.emitJsonOk(o,{command:e}):terminal.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??chunkCPRDIUQ4_cjs.f().worktree;return console.error(`[memory] ${s} :: ${e} failed: ${n}`),terminal.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}}exports.a=S;exports.b=v;exports.c=C;exports.d=E;
|
|
1
|
+
'use strict';var chunkCPRDIUQ4_cjs=require('./chunk-CPRDIUQ4.cjs'),utils=require('@easbot/utils'),terminal=require('@easbot/terminal');var y=utils.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(i=>i.group===m);return terminal.renderLines({title:t,flat:e.map(i=>`$ easbot-memory ${i.name.padEnd(14)} ${i.description}`)})}function v(){let m=[terminal.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:")];terminal.printHuman(m);}function C(){v(),terminal.printHuman(["",terminal.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 I(m){try{let{bootstrapLlm:t}=await import('@easbot/llm'),{Llm:e}=await import('./llm-7LQGYSUE.cjs');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,...i]=m,c=t?.cwd??process.cwd();if(!e)return C(),{code:0,handled:true,command:null};await I(c);try{switch(e){case "init":{let{parseInitOptions:r,runInit:n}=await import('./init-EEWFFF4Y.cjs'),s=r(i);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,a=await n({...s,ctxWorkspaceDir:o});if(s.json)terminal.emitJsonOk(a,{command:e});else {let p=a;terminal.printHuman([terminal.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-LCKRI4TB.cjs'),o=r(i);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 a=await n({...o,workspaceDir:c});return o.json?terminal.emitJsonOk(a,{command:e}):terminal.printHuman([s(a)],{title:`recall (agentId=${o.agentId??"default"})`}),{code:0,handled:!0,command:e}}case "remember":{let{parseRememberOptions:r,runRemember:n,formatRememberText:s}=await import('./remember-OZOQ76IA.cjs'),o=r(i);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 a=await n({...o,workspaceDir:c});return o.json?terminal.emitJsonOk(a,{command:e}):terminal.printHuman([s(a)],{title:"remember (persist fact)"}),{code:0,handled:!0,command:e}}case "forget":{let{parseForgetOptions:r,runForget:n,formatForgetText:s}=await import('./forget-PARGCUIH.cjs'),o=r(i);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 a=await n({...o,workspaceDir:c});return o.json?terminal.emitJsonOk(a,{command:e}):terminal.printHuman([s(a)],{title:"forget (delete facts)"}),{code:0,handled:!0,command:e}}case "extract":{let{parseExtractOptions:r,runExtract:n,formatExtractText:s}=await import('./extract-4ZGVF2DQ.cjs'),o=r(i);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 a=await n({...o,workspaceDir:c});return o.json?terminal.emitJsonOk(a,{command:e}):terminal.printHuman([s(a)],{title:"extract (from session)"}),{code:0,handled:!0,command:e}}case "consolidate":{let{parseConsolidateOptions:r,runConsolidate:n,formatConsolidateText:s}=await import('./consolidate-JGLVNSDT.cjs'),o=r(i);if(o.help)return console.log("Usage: easbot-memory consolidate [--agent <id>] [--window-days <n>] [--json]"),{code:0,handled:!0,command:e};let a=await n({...o,workspaceDir:c});return o.json?terminal.emitJsonOk(a,{command:e}):terminal.printHuman([s(a)],{title:"consolidate (pipeline)"}),{code:0,handled:!0,command:e}}case "sync":{let{parseSyncOptions:r,runSync:n,formatSyncText:s}=await import('./sync-7VBREDVM.cjs'),o=r(i);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 a=await n({...o,workspaceDir:c});return o.json?terminal.emitJsonOk(a,{command:e}):terminal.printHuman([s(a)],{title:"sync (db \u2192 .md + archive)"}),{code:0,handled:!0,command:e}}case "graph":{let{parseGraphOptions:r,runGraph:n,formatGraphText:s}=await import('./graph-NJJLGDZI.cjs'),o=r(i);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 a=await n({...o,workspaceDir:c});return o.json?terminal.emitJsonOk(a,{command:e}):terminal.printHuman([s(a)],{title:`graph_query (scope=${o.scope??"agent_only"})`}),{code:0,handled:!0,command:e}}case "status":{let{parseStatusOptions:r,runStatus:n}=await import('./status-6R335JGR.cjs'),s=r(i);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?terminal.emitJsonOk(o,{command:e}):terminal.printHuman([terminal.formatKnowledgeStatus(K(o))],{title:"memory status",boxed:!0}),{code:0,handled:!0,command:e}}case "doctor":{let{parseDoctorOptions:r,runDoctor:n}=await import('./doctor-C7RIJGYC.cjs'),s=r(i);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?terminal.emitJsonOk(o,{command:e}):terminal.printHuman([terminal.formatKnowledgeDoctor(j(o))],{title:"memory doctor",boxed:!0}),{code:0,handled:!0,command:e}}case "config":{let{parseConfigOptions:r,runConfig:n,formatConfigText:s}=await import('./config-I2I6U4XM.cjs'),o=r(i);if(o.help)return console.log("Usage: easbot-memory config [--json]"),{code:0,handled:!0,command:e};let a=n(o);return o.json?terminal.emitJsonOk(a,{command:e}):terminal.printHuman([s(a)],{title:"memory config"}),{code:0,handled:!0,command:e}}case "mcp":{let{parseMcpOptions:r,runMcp:n}=await import('./mcp-ES7O3UKN.cjs'),s=r(i);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?terminal.emitJsonOk(o,{command:e}):terminal.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??chunkCPRDIUQ4_cjs.f().worktree;return console.error(`[memory] ${s} :: ${e} failed: ${n}`),terminal.emitJsonError(e,n),{code:1,handled:true,command:e}}}function K(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 i=t.factsByCategory;for(let[c,r]of Object.entries(i))typeof r=="number"&&r>0&&(e[`facts/${c}`]=r);}return Object.keys(e).length>0?e:void 0})()}}function j(m){let t=m,e=Array.isArray(t.checks)?t.checks:[],i=t.integrityStats,c=t.backendAvailable,r=i?{...i}: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}}exports.a=S;exports.b=v;exports.c=C;exports.d=A;exports.e=j;
|