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