@easbot/memory 0.3.32 → 0.3.37

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/README.en.md +116 -1
  2. package/README.md +103 -8
  3. package/dist/assets/txt/src/plugin/tool/memory.txt +231 -0
  4. package/dist/chunks/{cache-IGJVAUPS.cjs → cache-IS6GEN55.cjs} +1 -1
  5. package/dist/chunks/{chunk-6H5PTRZL.cjs → chunk-4G4FSAFY.cjs} +1 -1
  6. package/dist/chunks/{chunk-7C2J2PDC.cjs → chunk-IP7VEKQY.cjs} +2 -2
  7. package/dist/chunks/{chunk-DYD3SEPC.cjs → chunk-ISYAE6B7.cjs} +5 -5
  8. package/dist/chunks/{chunk-YAF6HMAE.cjs → chunk-QAEIHJOF.cjs} +8 -8
  9. package/dist/chunks/cli-handler-USK4CPAU.cjs +1 -0
  10. package/dist/chunks/{config-KFPQDFJR.cjs → config-5OTOQBQN.cjs} +1 -1
  11. package/dist/chunks/{consolidate-KZAYROKJ.cjs → consolidate-IKQVVWIQ.cjs} +1 -1
  12. package/dist/chunks/doctor-N6HHFR6Y.cjs +1 -0
  13. package/dist/chunks/{extract-BS6HOLXU.cjs → extract-7DQ6OV34.cjs} +1 -1
  14. package/dist/chunks/{forget-Q6UN6GSW.cjs → forget-4KGLTQ5Q.cjs} +1 -1
  15. package/dist/chunks/{graph-4KBXGMOL.cjs → graph-OG23VZZM.cjs} +1 -1
  16. package/dist/chunks/{init-EBA3ZGC6.cjs → init-UQTPANNI.cjs} +1 -1
  17. package/dist/chunks/{interfaces-TGSOKRFI.cjs → interfaces-LDOE5ZTS.cjs} +1 -1
  18. package/dist/chunks/{llm-TQXCNG4J.cjs → llm-JSVYSX5Y.cjs} +1 -1
  19. package/dist/chunks/{mcp-PH3CLOYP.cjs → mcp-ONIMP7FB.cjs} +1 -1
  20. package/dist/chunks/{recall-SBUTMJPU.cjs → recall-KZRYTTWA.cjs} +1 -1
  21. package/dist/chunks/{remember-FXMXYHLK.cjs → remember-GLOJH457.cjs} +1 -1
  22. package/dist/chunks/{status-H4UKSZAH.cjs → status-POX2GWSQ.cjs} +1 -1
  23. package/dist/chunks/stdio-server-W52CMVJO.cjs +1 -0
  24. package/dist/chunks/{sync-FTZT6MWJ.cjs → sync-I423W5G7.cjs} +1 -1
  25. package/dist/cli.cjs +1 -1
  26. package/dist/index.cjs +28 -1
  27. package/dist/index.d.cts +121 -1
  28. package/dist/index.d.ts +121 -1
  29. package/dist/index.mjs +28 -1
  30. package/package.json +14 -11
  31. package/dist/chunks/cli-handler-IXFJAQFB.cjs +0 -1
  32. package/dist/chunks/doctor-OAWL5FMH.cjs +0 -1
  33. package/dist/chunks/stdio-server-CWA2HGXA.cjs +0 -1
  34. /package/dist/assets/txt/{assets → src/assets}/jieba_dict.txt +0 -0
  35. /package/dist/chunks/{chunk-KFESJR3T.cjs → chunk-R32346OA.cjs} +0 -0
@@ -1,2 +1,2 @@
1
- 'use strict';var chunk4GSXSIV5_cjs=require('./chunk-4GSXSIV5.cjs');require('./chunk-WQB4D6DZ.cjs');var chunkYAF6HMAE_cjs=require('./chunk-YAF6HMAE.cjs');require('./chunk-7C2J2PDC.cjs'),require('./chunk-EKSLNNMF.cjs'),require('./chunk-AVECFV5K.cjs');var chunkNHRRIJFK_cjs=require('./chunk-NHRRIJFK.cjs');require('./chunk-GCVKM3RJ.cjs'),require('./chunk-KFESJR3T.cjs');var utils=require('@easbot/utils');async function h(e){let n=e.agentId?.trim();if(!n)throw new utils.NameErrors.MissingFieldError({field:"agentId",message:"sync: agentId is required (ctx environment; agent CLI / standalone CLI must inject)"});let r=await chunkNHRRIJFK_cjs.d.getRootDir();return chunkYAF6HMAE_cjs.z("sync",{windowDays:e.windowDays,dryRun:e.dryRun??false},chunkYAF6HMAE_cjs.B(n,r))}function C(e){let n=e;return [chunk4GSXSIV5_cjs.b("sync",{windowDays:String(n.windowDays),dryRun:String(n.dryRun)},"sync complete (windowDays={{windowDays}}, dryRun={{dryRun}}):"),chunk4GSXSIV5_cjs.c("sync",{generatedCount:String(n.generatedCount),skippedCount:String(n.skippedCount),failedGenerateCount:String(n.failedGenerateCount),archivedCount:String(n.archivedCount),archiveThreshold:n.archiveThreshold}," - generated: {{generatedCount}}, skipped: {{skippedCount}}, failed: {{failedGenerateCount}}, archived: {{archivedCount}} (threshold: {{archiveThreshold}})"),` - duration: ${n.durationMs}ms`].join(`
1
+ 'use strict';var chunk4GSXSIV5_cjs=require('./chunk-4GSXSIV5.cjs');require('./chunk-WQB4D6DZ.cjs');var chunkQAEIHJOF_cjs=require('./chunk-QAEIHJOF.cjs');require('./chunk-IP7VEKQY.cjs'),require('./chunk-EKSLNNMF.cjs'),require('./chunk-AVECFV5K.cjs');var chunkNHRRIJFK_cjs=require('./chunk-NHRRIJFK.cjs');require('./chunk-GCVKM3RJ.cjs'),require('./chunk-R32346OA.cjs');var utils=require('@easbot/utils');async function h(e){let n=e.agentId?.trim();if(!n)throw new utils.NameErrors.MissingFieldError({field:"agentId",message:"sync: agentId is required (ctx environment; agent CLI / standalone CLI must inject)"});let r=await chunkNHRRIJFK_cjs.d.getRootDir();return chunkQAEIHJOF_cjs.z("sync",{windowDays:e.windowDays,dryRun:e.dryRun??false},chunkQAEIHJOF_cjs.B(n,r))}function C(e){let n=e;return [chunk4GSXSIV5_cjs.b("sync",{windowDays:String(n.windowDays),dryRun:String(n.dryRun)},"sync complete (windowDays={{windowDays}}, dryRun={{dryRun}}):"),chunk4GSXSIV5_cjs.c("sync",{generatedCount:String(n.generatedCount),skippedCount:String(n.skippedCount),failedGenerateCount:String(n.failedGenerateCount),archivedCount:String(n.archivedCount),archiveThreshold:n.archiveThreshold}," - generated: {{generatedCount}}, skipped: {{skippedCount}}, failed: {{failedGenerateCount}}, archived: {{archivedCount}} (threshold: {{archiveThreshold}})"),` - duration: ${n.durationMs}ms`].join(`
2
2
  `)}function b(e){let n={};for(let r=0;r<e.length;r++){let t=e[r];if(t===void 0)continue;let i=e[r+1];if(t==="--agent")r++;else if(t==="--window-days"){let o=Number(i);if(Number.isNaN(o)||o<1||o>3650)throw new utils.NameErrors.InvalidArgumentError({param:"window-days",message:`--window-days must be an integer in [1, 3650], got: ${i??"(empty)"}`});n.windowDays=o,r++;}else t==="--dry-run"?n.dryRun=true:t==="--json"?n.json=true:(t==="--help"||t==="-h")&&(n.help=true);}return n}exports.formatSyncText=C;exports.parseSyncOptions=b;exports.runSync=h;
package/dist/cli.cjs CHANGED
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- 'use strict';var chunkKFESJR3T_cjs=require('./chunks/chunk-KFESJR3T.cjs'),fs=require('fs'),path=require('path'),url=require('url'),terminal=require('@easbot/terminal');var N=path.dirname(url.fileURLToPath(chunkKFESJR3T_cjs.d));function C(){try{let t=path.join(N,"..","package.json");return JSON.parse(fs.readFileSync(t,"utf-8")).version??"0.0.0"}catch{return "0.0.0"}}var u=new Set(["DEBUG","INFO","WARN","ERROR"]);function D(t){let o={logLevel:"INFO",printLogs:false,debug:false};for(let s=0;s<t.length;s++){let e=t[s];if(e)if(e==="--cwd"&&s+1<t.length){let n=t[s+1];n&&!n.startsWith("-")&&(o.cwd=n,s++);}else if(e.startsWith("--cwd="))o.cwd=e.slice(6);else if(e==="--config"&&s+1<t.length){let n=t[s+1];n&&!n.startsWith("-")&&(o.configPath=n,s++);}else if(e.startsWith("--config="))o.configPath=e.slice(9);else if(e==="--log-level"&&s+1<t.length){let n=t[s+1];if(n&&!n.startsWith("-")){let c=n.toUpperCase();u.has(c)&&(o.logLevel=c,s++);}}else if(e.startsWith("--log-level=")){let n=e.slice(12).toUpperCase();u.has(n)&&(o.logLevel=n);}else e==="--print-logs"?o.printLogs=true:e==="--debug"&&(o.debug=true);}return o}async function R(){let t=process.argv.slice(2),o=C(),{loadEnv:s}=await import('@easbot/utils');s(),process.env.EASBOT_LANG||(process.env.EASBOT_LANG="en-US");let e=D(t),{Log:n}=await import('@easbot/utils'),{getXdgData:c}=await import('./chunks/interfaces-TGSOKRFI.cjs'),L=path.join(c(),"memory","log");if(await n.init({logDir:L,print:e.printLogs,dev:e.debug||false,level:e.logLevel}),t.length===0){let{renderBanner:a}=await import('./chunks/cli-handler-IXFJAQFB.cjs');a();return}if(t[0]==="--help"||t[0]==="-h"){let{renderHelp:a}=await import('./chunks/cli-handler-IXFJAQFB.cjs');a();return}if(t[0]==="--version"||t[0]==="-v"){terminal.printHuman([terminal.formatInfo(o)]);return}let i=e.cwd??process.cwd(),{handleMemoryCli:b}=await import('./chunks/cli-handler-IXFJAQFB.cjs'),{setInstanceAdapter:v}=await import('./chunks/interfaces-TGSOKRFI.cjs');v({directory:i,worktree:i});let{setAdapterRegistry:y}=await import('@easbot/llm'),{getGlobal:r,getInstance:p}=await import('./chunks/interfaces-TGSOKRFI.cjs');y({config:void 0,instance:{getDirectory:()=>p().directory,getWorktree:()=>p().worktree},global:{home:r().Path.home,data:r().Path.data,cache:r().Path.cache,config:r().Path.config,state:r().Path.state,log:r().Path.log,bin:r().Path.bin},installation:{getVersion:()=>o,getChannel:()=>"local",getUserAgent:()=>`easbot-memory/${o}`}});let d=n.create({service:"memory.cli.standalone"}),l;try{let{readFileSync:a}=await import('fs'),{join:g}=await import('path'),m=g(i,".easbot","protocol.json"),O=a(m,"utf-8");l=JSON.parse(O)?.metadata?.agentId?.trim()||void 0,d.debug("standalone CLI: resolved hostAgentId from protocol.json",{hostAgentId:l,protocolPath:m});}catch(a){let{errorMeta:g}=await import('@easbot/utils');d.errorDegradable("standalone CLI: read protocol.json failed; hostAgentId stays undefined",{cwd:i,error:g(a)});}let f=await b(t,{version:o,cwd:i,agentId:l});f.code!==0&&(process.exitCode=f.code);}R().catch(async t=>{try{let{Log:o,errorMeta:s}=await import('@easbot/utils');o.create({service:"memory.cli.standalone"}).error("memory CLI crashed",{error:s(t)});}catch{console.error(t);}process.exitCode=1;}).finally(async()=>{try{let{Log:t}=await import('@easbot/utils');await t.close();}catch{}process.exit(process.exitCode??0);});
2
+ 'use strict';var chunkR32346OA_cjs=require('./chunks/chunk-R32346OA.cjs'),fs=require('fs'),path=require('path'),url=require('url'),terminal=require('@easbot/terminal');var N=path.dirname(url.fileURLToPath(chunkR32346OA_cjs.d));function C(){try{let t=path.join(N,"..","package.json");return JSON.parse(fs.readFileSync(t,"utf-8")).version??"0.0.0"}catch{return "0.0.0"}}var u=new Set(["DEBUG","INFO","WARN","ERROR"]);function D(t){let o={logLevel:"INFO",printLogs:false,debug:false};for(let s=0;s<t.length;s++){let e=t[s];if(e)if(e==="--cwd"&&s+1<t.length){let n=t[s+1];n&&!n.startsWith("-")&&(o.cwd=n,s++);}else if(e.startsWith("--cwd="))o.cwd=e.slice(6);else if(e==="--config"&&s+1<t.length){let n=t[s+1];n&&!n.startsWith("-")&&(o.configPath=n,s++);}else if(e.startsWith("--config="))o.configPath=e.slice(9);else if(e==="--log-level"&&s+1<t.length){let n=t[s+1];if(n&&!n.startsWith("-")){let c=n.toUpperCase();u.has(c)&&(o.logLevel=c,s++);}}else if(e.startsWith("--log-level=")){let n=e.slice(12).toUpperCase();u.has(n)&&(o.logLevel=n);}else e==="--print-logs"?o.printLogs=true:e==="--debug"&&(o.debug=true);}return o}async function R(){let t=process.argv.slice(2),o=C(),{loadEnv:s}=await import('@easbot/utils');s(),process.env.EASBOT_LANG||(process.env.EASBOT_LANG="en-US");let e=D(t),{Log:n}=await import('@easbot/utils'),{getXdgData:c}=await import('./chunks/interfaces-LDOE5ZTS.cjs'),L=path.join(c(),"memory","log");if(await n.init({logDir:L,print:e.printLogs,dev:e.debug||false,level:e.logLevel}),t.length===0){let{renderBanner:a}=await import('./chunks/cli-handler-USK4CPAU.cjs');a();return}if(t[0]==="--help"||t[0]==="-h"){let{renderHelp:a}=await import('./chunks/cli-handler-USK4CPAU.cjs');a();return}if(t[0]==="--version"||t[0]==="-v"){terminal.printHuman([terminal.formatInfo(o)]);return}let i=e.cwd??process.cwd(),{handleMemoryCli:b}=await import('./chunks/cli-handler-USK4CPAU.cjs'),{setInstanceAdapter:v}=await import('./chunks/interfaces-LDOE5ZTS.cjs');v({directory:i,worktree:i});let{setAdapterRegistry:y}=await import('@easbot/llm'),{getGlobal:r,getInstance:p}=await import('./chunks/interfaces-LDOE5ZTS.cjs');y({config:void 0,instance:{getDirectory:()=>p().directory,getWorktree:()=>p().worktree},global:{home:r().Path.home,data:r().Path.data,cache:r().Path.cache,config:r().Path.config,state:r().Path.state,log:r().Path.log,bin:r().Path.bin},installation:{getVersion:()=>o,getChannel:()=>"local",getUserAgent:()=>`easbot-memory/${o}`}});let d=n.create({service:"memory.cli.standalone"}),l;try{let{readFileSync:a}=await import('fs'),{join:g}=await import('path'),m=g(i,".easbot","protocol.json"),O=a(m,"utf-8");l=JSON.parse(O)?.metadata?.agentId?.trim()||void 0,d.debug("standalone CLI: resolved hostAgentId from protocol.json",{hostAgentId:l,protocolPath:m});}catch(a){let{errorMeta:g}=await import('@easbot/utils');d.errorDegradable("standalone CLI: read protocol.json failed; hostAgentId stays undefined",{cwd:i,error:g(a)});}let f=await b(t,{version:o,cwd:i,agentId:l});f.code!==0&&(process.exitCode=f.code);}R().catch(async t=>{try{let{Log:o,errorMeta:s}=await import('@easbot/utils');o.create({service:"memory.cli.standalone"}).error("memory CLI crashed",{error:s(t)});}catch{console.error(t);}process.exitCode=1;}).finally(async()=>{try{let{Log:t}=await import('@easbot/utils');await t.close();}catch{}process.exit(process.exitCode??0);});
package/dist/index.cjs CHANGED
@@ -1 +1,28 @@
1
- 'use strict';var chunkDYD3SEPC_cjs=require('./chunks/chunk-DYD3SEPC.cjs');require('./chunks/chunk-URADAZYW.cjs');var chunk6H5PTRZL_cjs=require('./chunks/chunk-6H5PTRZL.cjs'),chunkYAF6HMAE_cjs=require('./chunks/chunk-YAF6HMAE.cjs'),chunk7C2J2PDC_cjs=require('./chunks/chunk-7C2J2PDC.cjs'),chunkEKSLNNMF_cjs=require('./chunks/chunk-EKSLNNMF.cjs'),chunkAVECFV5K_cjs=require('./chunks/chunk-AVECFV5K.cjs'),chunkNHRRIJFK_cjs=require('./chunks/chunk-NHRRIJFK.cjs'),chunkGCVKM3RJ_cjs=require('./chunks/chunk-GCVKM3RJ.cjs'),chunkKFESJR3T_cjs=require('./chunks/chunk-KFESJR3T.cjs'),types=require('@easbot/types'),n=require('jieba-wasm'),utils=require('@easbot/utils');function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var n__namespace=/*#__PURE__*/_interopNamespace(n);var ne=["user_preference","task_context","technical_fact","decision","relationship","reminder","error_pattern","workflow","exploration_finding","experience_summary","tool_usage","skill_creation","test","other"];var t=utils.Log.create({service:"memory.tokenizer"}),o=false,ee=utils.loadTextFile("./assets/jieba_dict.txt",chunkKFESJR3T_cjs.d);async function ue(e){if(!o)try{t.debug("Initializing jieba tokenizer");let r=ee();if(n__namespace.with_dict(r),t.debug("Built-in dictionary loaded"),e?.dictPath&&e.dictPath.length>0)for(let s of e.dictPath)await re(s);o=!0,t.debug("Jieba tokenizer initialized successfully");}catch(r){t.error("Failed to initialize jieba tokenizer",{error:utils.errorMeta(r)}),t.warn("Using fallback tokenization (space-based)");}}async function re(e){if(!o)throw new chunkAVECFV5K_cjs.a.TokenizerNotInitializedError({message:"Tokenizer not initialized"});try{let r=await utils.Filesystem.readText(e);t.debug("Loading custom dictionary",{dictPath:e}),n__namespace.with_dict(r),t.debug("Custom dictionary loaded successfully",{dictPath:e});}catch(r){t.warn("Failed to load custom dictionary",{dictPath:e,error:utils.errorMeta(r)});}}function te(e){if(!o)return e.split(/\s+/).filter(Boolean);try{return n__namespace.cut(e)}catch(r){return t.warn("Tokenization failed, using fallback",{error:utils.errorMeta(r)}),e.split(/\s+/).filter(Boolean)}}function oe(e){if(!o)return e.split(/\s+/).filter(Boolean);try{return n__namespace.cut_for_search(e)}catch(r){return t.warn("Tokenization for search failed, using fallback",{error:utils.errorMeta(r)}),e.split(/\s+/).filter(Boolean)}}function ge(e,r,s){if(o)try{n__namespace.add_word(e,r,s),t.debug("Word added to dictionary",{word:e,freq:r,tag:s});}catch(S){t.warn("Failed to add word",{word:e,error:utils.errorMeta(S)});}}function ye(){return o}async function fe(){o=false,t.debug("Tokenizer closed");}function xe(e){if(!o)return e.split(/\s+/).filter(Boolean).join(" ");try{return te(e).join(" ")}catch(r){return t.warn("Tokenization failed, using fallback",{error:utils.errorMeta(r)}),e.split(/\s+/).filter(Boolean).join(" ")}}function Me(e){if(!o)return e.split(/\s+/).filter(Boolean).join(" ");try{return oe(e).join(" ")}catch(r){return t.warn("Tokenization for search failed, using fallback",{error:utils.errorMeta(r)}),e.split(/\s+/).filter(Boolean).join(" ")}}Object.defineProperty(exports,"MemoryStdioServer",{enumerable:true,get:function(){return chunkDYD3SEPC_cjs.b}});Object.defineProperty(exports,"renderOperationMarkdown",{enumerable:true,get:function(){return chunkDYD3SEPC_cjs.a}});Object.defineProperty(exports,"COMMANDS_HELP",{enumerable:true,get:function(){return chunk6H5PTRZL_cjs.a}});Object.defineProperty(exports,"handleMemoryCli",{enumerable:true,get:function(){return chunk6H5PTRZL_cjs.d}});Object.defineProperty(exports,"renderBanner",{enumerable:true,get:function(){return chunk6H5PTRZL_cjs.b}});Object.defineProperty(exports,"renderHelp",{enumerable:true,get:function(){return chunk6H5PTRZL_cjs.c}});Object.defineProperty(exports,"ALL_OPS",{enumerable:true,get:function(){return chunkYAF6HMAE_cjs.y}});Object.defineProperty(exports,"GraphStore",{enumerable:true,get:function(){return chunkYAF6HMAE_cjs.a}});Object.defineProperty(exports,"OP_REGISTRY",{enumerable:true,get:function(){return chunkYAF6HMAE_cjs.x}});Object.defineProperty(exports,"consolidate",{enumerable:true,get:function(){return chunkYAF6HMAE_cjs.r}});Object.defineProperty(exports,"doctor",{enumerable:true,get:function(){return chunkYAF6HMAE_cjs.v}});Object.defineProperty(exports,"executeOp",{enumerable:true,get:function(){return chunkYAF6HMAE_cjs.z}});Object.defineProperty(exports,"extract",{enumerable:true,get:function(){return chunkYAF6HMAE_cjs.q}});Object.defineProperty(exports,"forget",{enumerable:true,get:function(){return chunkYAF6HMAE_cjs.p}});Object.defineProperty(exports,"graphQuery",{enumerable:true,get:function(){return chunkYAF6HMAE_cjs.t}});Object.defineProperty(exports,"init",{enumerable:true,get:function(){return chunkYAF6HMAE_cjs.w}});Object.defineProperty(exports,"recall",{enumerable:true,get:function(){return chunkYAF6HMAE_cjs.b}});Object.defineProperty(exports,"remember",{enumerable:true,get:function(){return chunkYAF6HMAE_cjs.n}});Object.defineProperty(exports,"status",{enumerable:true,get:function(){return chunkYAF6HMAE_cjs.u}});Object.defineProperty(exports,"sync",{enumerable:true,get:function(){return chunkYAF6HMAE_cjs.s}});Object.defineProperty(exports,"update",{enumerable:true,get:function(){return chunkYAF6HMAE_cjs.o}});Object.defineProperty(exports,"LATEST_SCHEMA_VERSION",{enumerable:true,get:function(){return chunk7C2J2PDC_cjs.a}});Object.defineProperty(exports,"MIGRATIONS",{enumerable:true,get:function(){return chunk7C2J2PDC_cjs.b}});Object.defineProperty(exports,"MemoryDatabaseManager",{enumerable:true,get:function(){return chunk7C2J2PDC_cjs.e}});Object.defineProperty(exports,"readCurrentSchemaVersion",{enumerable:true,get:function(){return chunk7C2J2PDC_cjs.d}});Object.defineProperty(exports,"runMigrations",{enumerable:true,get:function(){return chunk7C2J2PDC_cjs.c}});Object.defineProperty(exports,"Llm",{enumerable:true,get:function(){return chunkEKSLNNMF_cjs.a}});Object.defineProperty(exports,"DEFAULT_MEMORY_JSON",{enumerable:true,get:function(){return chunkNHRRIJFK_cjs.b}});Object.defineProperty(exports,"MEMORY_JSON_REL_PATH",{enumerable:true,get:function(){return chunkNHRRIJFK_cjs.c}});Object.defineProperty(exports,"MemoryCache",{enumerable:true,get:function(){return chunkNHRRIJFK_cjs.d}});Object.defineProperty(exports,"MemoryJsonSchema",{enumerable:true,get:function(){return chunkNHRRIJFK_cjs.a}});Object.defineProperty(exports,"getGlobal",{enumerable:true,get:function(){return chunkGCVKM3RJ_cjs.c}});Object.defineProperty(exports,"getHomeDir",{enumerable:true,get:function(){return chunkGCVKM3RJ_cjs.g}});Object.defineProperty(exports,"getInstance",{enumerable:true,get:function(){return chunkGCVKM3RJ_cjs.f}});Object.defineProperty(exports,"getMemoryDbPath",{enumerable:true,get:function(){return chunkGCVKM3RJ_cjs.j}});Object.defineProperty(exports,"getMemoryDir",{enumerable:true,get:function(){return chunkGCVKM3RJ_cjs.i}});Object.defineProperty(exports,"getXdgData",{enumerable:true,get:function(){return chunkGCVKM3RJ_cjs.h}});Object.defineProperty(exports,"resetGlobalAdapter",{enumerable:true,get:function(){return chunkGCVKM3RJ_cjs.b}});Object.defineProperty(exports,"resetInstanceAdapter",{enumerable:true,get:function(){return chunkGCVKM3RJ_cjs.e}});Object.defineProperty(exports,"setGlobalAdapter",{enumerable:true,get:function(){return chunkGCVKM3RJ_cjs.a}});Object.defineProperty(exports,"setInstanceAdapter",{enumerable:true,get:function(){return chunkGCVKM3RJ_cjs.d}});Object.defineProperty(exports,"GRAPH_ENTITY_TYPE_DEFINITIONS",{enumerable:true,get:function(){return types.GRAPH_ENTITY_TYPE_DEFINITIONS}});Object.defineProperty(exports,"GRAPH_RELATION_TYPE_DEFINITIONS",{enumerable:true,get:function(){return types.GRAPH_RELATION_TYPE_DEFINITIONS}});exports.MEMORY_CATEGORIES=ne;exports.addWord=ge;exports.closeTokenizer=fe;exports.initTokenizer=ue;exports.isInitialized=ye;exports.loadCustomDict=re;exports.toFtsTokens=xe;exports.toFtsTokensForSearch=Me;exports.tokenize=te;exports.tokenizeForSearch=oe;
1
+ 'use strict';var chunkISYAE6B7_cjs=require('./chunks/chunk-ISYAE6B7.cjs');require('./chunks/chunk-URADAZYW.cjs');var chunk4G4FSAFY_cjs=require('./chunks/chunk-4G4FSAFY.cjs'),chunkQAEIHJOF_cjs=require('./chunks/chunk-QAEIHJOF.cjs'),chunkIP7VEKQY_cjs=require('./chunks/chunk-IP7VEKQY.cjs'),chunkEKSLNNMF_cjs=require('./chunks/chunk-EKSLNNMF.cjs'),chunkAVECFV5K_cjs=require('./chunks/chunk-AVECFV5K.cjs'),chunkNHRRIJFK_cjs=require('./chunks/chunk-NHRRIJFK.cjs'),chunkGCVKM3RJ_cjs=require('./chunks/chunk-GCVKM3RJ.cjs'),chunkR32346OA_cjs=require('./chunks/chunk-R32346OA.cjs'),types=require('@easbot/types'),M=require('jieba-wasm'),utils=require('@easbot/utils'),plugin=require('@easbot/plugin'),crypto=require('crypto'),fs=require('fs'),zod=require('zod');function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var M__namespace=/*#__PURE__*/_interopNamespace(M);var Sr=["user_preference","task_context","technical_fact","decision","relationship","reminder","error_pattern","workflow","exploration_finding","experience_summary","tool_usage","skill_creation","test","other"];var g=utils.Log.create({service:"memory.tokenizer"}),y=false,Be=utils.loadTextFile("./assets/jieba_dict.txt",chunkR32346OA_cjs.d);async function Gr(e){if(!y)try{g.debug("Initializing jieba tokenizer");let t=Be();if(M__namespace.with_dict(t),g.debug("Built-in dictionary loaded"),e?.dictPath&&e.dictPath.length>0)for(let o of e.dictPath)await Ye(o);y=!0,g.debug("Jieba tokenizer initialized successfully");}catch(t){g.error("Failed to initialize jieba tokenizer",{error:utils.errorMeta(t)}),g.warn("Using fallback tokenization (space-based)");}}async function Ye(e){if(!y)throw new chunkAVECFV5K_cjs.a.TokenizerNotInitializedError({message:"Tokenizer not initialized"});try{let t=await utils.Filesystem.readText(e);g.debug("Loading custom dictionary",{dictPath:e}),M__namespace.with_dict(t),g.debug("Custom dictionary loaded successfully",{dictPath:e});}catch(t){g.warn("Failed to load custom dictionary",{dictPath:e,error:utils.errorMeta(t)});}}function qe(e){if(!y)return e.split(/\s+/).filter(Boolean);try{return M__namespace.cut(e)}catch(t){return g.warn("Tokenization failed, using fallback",{error:utils.errorMeta(t)}),e.split(/\s+/).filter(Boolean)}}function je(e){if(!y)return e.split(/\s+/).filter(Boolean);try{return M__namespace.cut_for_search(e)}catch(t){return g.warn("Tokenization for search failed, using fallback",{error:utils.errorMeta(t)}),e.split(/\s+/).filter(Boolean)}}function Fr(e,t,o){if(y)try{M__namespace.add_word(e,t,o),g.debug("Word added to dictionary",{word:e,freq:t,tag:o});}catch(r){g.warn("Failed to add word",{word:e,error:utils.errorMeta(r)});}}function Dr(){return y}async function $r(){y=false,g.debug("Tokenizer closed");}function Br(e){if(!y)return e.split(/\s+/).filter(Boolean).join(" ");try{return qe(e).join(" ")}catch(t){return g.warn("Tokenization failed, using fallback",{error:utils.errorMeta(t)}),e.split(/\s+/).filter(Boolean).join(" ")}}function Yr(e){if(!y)return e.split(/\s+/).filter(Boolean).join(" ");try{return je(e).join(" ")}catch(t){return g.warn("Tokenization for search failed, using fallback",{error:utils.errorMeta(t)}),e.split(/\s+/).filter(Boolean).join(" ")}}var j="memory",K="0.3.36",v={name:j,version:K,description:"EASBot memory plugin: lifecycle hooks and memory tool",entry:"./index.mjs",capabilities:["hooks","tools"]};function f(e,t){if(typeof e!="object"||e===null)return;let o=e;for(let r of t){let l=o[r];if(typeof l=="string"&&l.length>0)return l}}function me(e){if(typeof e!="object"||e===null)return {};let t=e.extras;return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:{}}function ce(e){if(typeof e!="object"||e===null)return;let t=e.protocolMetadata;if(typeof t!="object"||t===null)return;let o=t.agentId;return typeof o=="string"&&o.length>0?o:void 0}function b(e,t){let o={...me(e),...me(t)};return {agentId:f(t,["agentId"])??ce(e)??ce(t)??f(e,["agentId"])??f(t,["agent"])??f(e,["agent"])??"",sessionId:f(t,["sessionId"])??f(e,["sessionId"]),toolName:f(e,["toolName","tool","name"])??f(t,["toolName"]),error:f(e,["error","message"])??f(t,["error"]),messagePreview:f(e,["messagePreview"])??f(t,["messagePreview"]),contextPreview:f(e,["contextPreview","text","prompt"])??f(t,["contextPreview"]),extras:o}}function h(e){let t=chunkGCVKM3RJ_cjs.f().worktree,o=chunkGCVKM3RJ_cjs.j(t),r=e.trim()||"memory-plugin";return {agentId:r,isTrustedLocal:true,remote:false,locale:"en-US",dbPath:o,workspaceDir:t,rootDir:t,config:chunkQAEIHJOF_cjs.A({agentId:r,dbPath:o,workspaceDir:t})}}function u(e,t){return {modified:false,input:e,output:{...t}}}function de(e,t){return {modified:true,input:e,output:{...t}}}function pe(e,t){return f(e,[t])}var We=utils.Log.create({service:"memory.plugin.hook"}),C=async(e,t)=>{let o=plugin.HookEvent.ContextBuildBefore,r=b(e,t);if(!r.agentId.trim())return u(e,{hook:o,ok:false,error:"context build: agentId is required"});let l=typeof r.extras.topK=="number"?r.extras.topK:5,c=typeof r.extras.query=="string"?r.extras.query:"";try{let d=await chunkQAEIHJOF_cjs.z("recall",{query:c,maxResults:l},h(r.agentId));if(d.hits.length===0)return u(e,{hook:o,ok:!0,context:[],logLine:"context build: no facts found; skipping context injection"});let i=d.hits.map($=>`- [${$.category}/imp=${$.importance}] ${$.snippet.slice(0,200)}`),a=`[memory:recall top-${d.hits.length}]
2
+ ${i.join(`
3
+ `)}`,x=pe(e,"userMessage");return x===void 0?u(e,{hook:o,ok:!0,context:[a],logLine:`context build: recalled ${d.hits.length} facts (input shape unexpected, not injected)`}):de({...e,userMessage:x?`${a}
4
+
5
+ ${x}`:a},{hook:o,ok:!0,context:[a],logLine:`context build: injected ${d.hits.length} facts`})}catch(d){let i=utils.errorMeta(d);return We.warn("memory context build hook failed",{error:i}),u(e,{hook:o,ok:false,error:i.message})}};var Xe=utils.Log.create({service:"memory.plugin.hook"}),Ze=200,A=async(e,t)=>{let o=plugin.HookEvent.SessionCompacting,r=b(e,t);if(!r.agentId.trim())return u(e,{hook:o,ok:false,error:"pre compact: agentId is required"});let c=(r.contextPreview??r.messagePreview??"").slice(0,Ze).replace(/\s+/g," ").trim(),d=typeof r.extras.topK=="number"?r.extras.topK:3;if(!c)return u(e,{hook:o,ok:true,context:[],logLine:"pre compact: empty context preview; skipping recall injection"});try{let i=await chunkQAEIHJOF_cjs.z("recall",{query:c,maxResults:d,minImportance:5},h(r.agentId));if(i.hits.length===0)return u(e,{hook:o,ok:!0,context:[],logLine:"pre compact: no facts matched query"});let a=i.hits.map(N=>`- [${N.category}/imp=${N.importance}] ${N.snippet.slice(0,150)}`),x=`[memory:pre-compact recall top-${i.hits.length} (imp>=5)]
6
+ ${a.join(`
7
+ `)}`;return u(e,{hook:o,ok:!0,context:[x],logLine:`pre compact: injected ${i.hits.length} facts before compaction`})}catch(i){let a=utils.errorMeta(i);return Xe.warn("memory pre compact hook failed",{error:a}),u(e,{hook:o,ok:false,error:a.message})}};var nr=utils.Log.create({service:"memory.plugin.hook"}),ar=8,L=async(e,t)=>{let o=plugin.HookEvent.ToolFailure,r=b(e,t);if(!r.agentId.trim())return u(e,{hook:o,ok:false,error:"tool failure: agentId is required"});if(!r.toolName?.trim()||!r.error?.trim())return u(e,{hook:o,ok:false,error:"tool failure: toolName and error are required"});let l=crypto.createHash("sha256").update(`${r.toolName}:${r.error}`).digest("hex").slice(0,ar),c=r.messagePreview?r.messagePreview.slice(0,200).replace(/\s+/g," ").trim():"",d=[`[error_pattern] tool=${r.toolName}`,`[error] ${r.error}`,c?`[preview] ${c}`:"",`[errHash] ${l}`].filter(Boolean).join(`
8
+ `);try{let i=await chunkQAEIHJOF_cjs.z("remember",{content:d,category:"error_pattern",importance:6,tags:["post-tool-failure",`tool:${r.toolName}`,`err:${l}`],sessionId:r.sessionId,msgId:typeof r.extras.msgId=="string"?r.extras.msgId:void 0},h(r.agentId));return u(e,{hook:o,ok:!0,logLine:`tool failure: wrote error_pattern fact ${i.fact.id} (tool=${r.toolName}, errHash=${l})`})}catch(i){let a=utils.errorMeta(i);return nr.warn("memory tool failure hook failed",{error:a}),u(e,{hook:o,ok:false,error:a.message})}};var I=[{event:plugin.HookEvent.ContextBuildBefore,handler:C},{event:plugin.HookEvent.SessionCompacting,handler:A},{event:plugin.HookEvent.ToolFailure,handler:L}];function E(){return I.map(({event:e,handler:t})=>({event:e,hooks:[{type:"function",handler:t}]}))}var S=utils.Log.create({service:"memory.plugin.tool"}),W="memory",G=["recall","remember","update","forget","extract","graph_query","status"],pr=500,ue="Access EASBot long-term memory via `operation` (recall / remember / update / forget / extract / graph_query / status).",F=zod.z.enum(["user_preference","task_context","technical_fact","decision","relationship","reminder","error_pattern","workflow","exploration_finding","experience_summary","tool_usage","skill_creation","test","other"]),ur=zod.z.object({operation:zod.z.literal("recall"),query:zod.z.string().describe("Search query text"),limit:utils.Schema.positiveInt.optional().default(10).describe("Max results (default 10)"),category:F.optional().describe("Filter by memory category"),minImportance:utils.Schema.positiveInt.optional().refine(e=>e===void 0||e>=1&&e<=10,{message:"minImportance must be in [1, 10] (inclusive); the service uses `WHERE importance >= ?` SQL"}).describe("INCLUSIVE `>=` filter on 1-10 importance scale"),maxEdgesPerNode:utils.Schema.positiveInt.optional().default(10).refine(e=>e===void 0||e>=1&&e<=100,{message:"maxEdgesPerNode must be in [1, 100]"}).describe("Max edges per KG neighbor node returned by recall (default 10; range [1, 100])"),includeGraph:zod.z.boolean().optional().default(false).describe("Include KG neighbor subgraph (default false)"),includeShared:zod.z.boolean().optional().default(false).describe("Include shared KG nodes from other agents (default false)")}).strict(),gr=zod.z.object({operation:zod.z.literal("remember"),content:zod.z.string().describe("Memory content"),category:F.describe("Memory category"),importance:utils.Schema.positiveInt.describe("Importance 1-10 (service layer enforces range)"),tags:utils.Schema.stringArray.optional().describe("Optional tags (string[])")}).strict(),fr=zod.z.object({operation:zod.z.literal("update"),factId:zod.z.string().describe("Target fact id (must belong to ctx.agentId)"),content:zod.z.string().optional().describe("New content (triggers embedding rewrite + FTS reindex)"),category:F.optional().describe("New category"),importance:utils.Schema.positiveInt.optional().describe("New importance 1-10"),tags:utils.Schema.stringArray.optional().describe("New tags (string[]; empty array clears tags)")}).strict().refine(e=>e.content!==void 0||e.category!==void 0||e.importance!==void 0||e.tags!==void 0,{message:"update requires at least one of: `content`, `category`, `importance`, `tags`"}),yr=zod.z.object({operation:zod.z.literal("forget"),factId:zod.z.string().describe("Target fact id to delete (must belong to ctx.agentId)"),dryRun:zod.z.boolean().optional().default(false).describe("Preview without deleting (returns matched count, never deletes)"),force:zod.z.boolean().optional().default(false).describe("Skip KG reference check and delete anyway (use after dryRun confirms the match)")}).strict(),Mr=zod.z.object({operation:zod.z.literal("extract"),lastN:utils.Schema.positiveInt.optional().default(10).describe("Recent messages (default 10)"),fromMessageId:zod.z.string().optional().describe("Process messages after this id")}).strict(),xr=zod.z.object({operation:zod.z.literal("graph_query"),query:zod.z.string().min(1).optional().describe('Node name fragment (NOT natural-language query): locate one root node by case-insensitive `LIKE %name%` match against `nodes.name`, then BFS neighbor expansion. Pass only short identifiers (e.g. "easbot"). Use `recall` for natural-language fact search.'),nodeId:utils.Schema.positiveInt.optional().describe("KG node id to start BFS from (alternative to `query`)"),maxDepth:utils.Schema.positiveInt.optional().default(2).describe("BFS depth for neighbor expansion (default 2; range [1, 5])"),maxNodes:utils.Schema.nonNegativeInt.optional().default(100).describe("Max nodes returned after BFS (default 100; service max 500)"),maxEdgesPerNode:utils.Schema.positiveInt.optional().default(10).refine(e=>e===void 0||e>=1&&e<=100,{message:"maxEdgesPerNode must be in [1, 100]"}).describe("Max edges per BFS neighbor node (default 10; range [1, 100])"),relation:zod.z.string().optional().describe('Edge relation filter (e.g. "uses"; single-value exact match)'),type:zod.z.string().optional().describe('Node type filter for root node (e.g. "decision")')}).strict().refine(e=>e.query!==void 0||e.nodeId!==void 0,{message:"graph_query requires either `query` (node name fragment) or `nodeId` (KG node id)"}),kr=zod.z.object({operation:zod.z.literal("status")}).strict(),br={recall:ur,remember:gr,update:fr,forget:yr,extract:Mr,graph_query:xr,status:kr},D={operation:zod.z.enum(G).describe("Operation to run (exactly one per call)"),query:zod.z.string().optional().describe("recall: search query text / graph_query: node name fragment"),limit:utils.Schema.positiveInt.optional().describe("recall: max results (default 10, max 100)"),category:F.optional().describe("remember/update: memory category / recall: category filter"),minImportance:utils.Schema.positiveInt.optional().describe("recall: INCLUSIVE `>=` filter on the 1-10 importance scale"),maxEdgesPerNode:utils.Schema.positiveInt.optional().describe("recall/graph_query: max edges per KG neighbor node (default 10, max 100)"),includeGraph:zod.z.boolean().optional().describe("recall: include KG neighbor subgraph (default false)"),includeShared:zod.z.boolean().optional().describe("recall: include shared KG nodes from other agents (default false)"),content:zod.z.string().optional().describe("remember/update: fact body"),importance:utils.Schema.positiveInt.optional().describe("remember/update: importance 1-10"),tags:utils.Schema.stringArray.optional().describe("remember/update: tags (string[] or comma-separated string)"),factId:zod.z.string().optional().describe("update/forget: target fact id"),dryRun:zod.z.boolean().optional().describe("forget: preview without deleting (default false)"),force:zod.z.boolean().optional().describe("forget: skip KG reference check and delete anyway (default false)"),lastN:utils.Schema.positiveInt.optional().describe("extract: recent messages to scan (default 10)"),fromMessageId:zod.z.string().optional().describe("extract: process messages after this id"),nodeId:utils.Schema.positiveInt.optional().describe("graph_query: KG node id to start BFS from"),maxDepth:utils.Schema.positiveInt.optional().describe("graph_query: BFS depth (default 2, max 5)"),maxNodes:utils.Schema.nonNegativeInt.optional().describe("graph_query: max nodes returned after BFS (default 100, max 500)"),relation:zod.z.string().optional().describe("graph_query: edge relation filter (single-value exact match)"),type:zod.z.string().optional().describe("graph_query: node type filter for root node")};function hr(){try{let e=utils.loadTextFile("./memory.txt",chunkR32346OA_cjs.d)();return e.trim().length>0?e:ue}catch(e){return S.warn("memory tool description unavailable, using fallback",{error:utils.errorMeta(e)}),ue}}function Ir(e){let t=e.agent?.trim();if(!t)throw new utils.NameErrors.MissingFieldError({message:"memory tool: agentId is required (ctx.agent must be set)",field:"agentId"});return t}function _r(e,t){let o=br[e],r={};for(let c of Object.keys(o.shape))r[c]=t[c];let l=o.safeParse({...r,operation:e});if(!l.success){let c=l.error.issues.map(d=>`${d.path.join(".")||"(root)"}: ${d.message}`).join("; ");throw new utils.NameErrors.InvalidArgumentError({message:`memory tool: invalid parameters for operation "${e}" \u2014 ${c}`,param:e})}return l.data}async function Or(e,t){let o=chunkGCVKM3RJ_cjs.j(e);if(!fs.existsSync(o)){S.debug("memory db not found, auto-initializing",{dbPath:o,workspaceDir:e});try{await chunkQAEIHJOF_cjs.z("init",{workspaceDir:e,force:!1},t);}catch(r){throw new utils.NameErrors.OperationFailedError({message:`memory tool: auto-init failed (${utils.errorMeta(r).message}). Try running \`easbot memory init\` manually.`,operation:"memory-auto-init"})}}}async function Rr(){if(!(chunkEKSLNNMF_cjs.a.isInitialized()&&chunkEKSLNNMF_cjs.a.capabilities().graph))try{let e=await chunkNHRRIJFK_cjs.d.getMemoryJson();chunkEKSLNNMF_cjs.a.init({models:{embedding:e?.embedding_model??void 0,graph:e?.graph_model??void 0}});}catch(e){S.warn("memory Llm init failed; KG extraction will be skipped",{error:utils.errorMeta(e)});}}var w=plugin.createTool({description:hr(),args:D,execute:async(e,t)=>{let o=String(e.operation);try{await t.ask({permission:"memory",patterns:o==="recall"?[String(e.query??"")]:["*"],always:["*"],metadata:{operation:o}});let r=_r(o,e),l=Ir(t),c=t.worktree||t.directory||process.cwd(),d=chunkGCVKM3RJ_cjs.j(c),i={agentId:l,isTrustedLocal:!0,remote:!1,locale:"en-US",dbPath:d,workspaceDir:c,rootDir:c,config:chunkQAEIHJOF_cjs.A({agentId:l,dbPath:d,workspaceDir:c}),signal:t.abort};switch(await Rr(),await Or(c,i),o){case "recall":{let a=await chunkQAEIHJOF_cjs.z("recall",{query:r.query,maxResults:r.limit,category:r.category,minImportance:r.minImportance,maxEdgesPerNode:r.maxEdgesPerNode,includeGraph:r.includeGraph,includeShared:r.includeShared,snippetMaxChars:pr},i);return await chunkISYAE6B7_cjs.a("recall",a,{toolName:"memory_recall",query:r.query,agentId:l,scope:r.includeShared?"both":"agent_only"})}case "remember":{let a=await chunkQAEIHJOF_cjs.z("remember",{content:r.content,category:r.category,importance:r.importance,tags:r.tags,sessionId:t.sessionId},i);return `<memory_result>
9
+ Memory saved.
10
+ id: ${a.fact.id}
11
+ category: ${a.fact.category}
12
+ importance: ${r.importance}
13
+ linked nodes: ${a.nodeIds?.length??0}
14
+ </memory_result>`}case "update":{let a=await chunkQAEIHJOF_cjs.z("update",{factId:r.factId,content:r.content,category:r.category,importance:r.importance,tags:r.tags},i),x=a.fieldsUpdated?.join(", ")??"none";return `<memory_result>
15
+ Memory updated.
16
+ id: ${r.factId}
17
+ updated fields: ${x}
18
+ content changed: ${a.contentChanged}
19
+ </memory_result>`}case "forget":{let a=await chunkQAEIHJOF_cjs.z("forget",{factId:r.factId,dryRun:r.dryRun,force:r.force},i);return await chunkISYAE6B7_cjs.a("forget",a)}case "extract":{let a=await chunkQAEIHJOF_cjs.z("extract",{sessionId:t.sessionId,lastN:r.lastN,fromMessageId:r.fromMessageId},i);return `<memory_result>
20
+ Extraction finished.
21
+ extracted: ${a.extractedCount??0}
22
+ entities: ${a.entities?.length??0}
23
+ relations: ${a.relations?.length??0}
24
+ </memory_result>`}case "graph_query":{let a=await chunkQAEIHJOF_cjs.z("graph_query",{query:r.query,nodeId:r.nodeId,maxDepth:r.maxDepth,maxNodes:r.maxNodes,maxEdgesPerNode:r.maxEdgesPerNode,relation:r.relation,type:r.type},i);return await chunkISYAE6B7_cjs.a("graph_query",a)}case "status":{let a=await chunkQAEIHJOF_cjs.z("status",{},i);return await chunkISYAE6B7_cjs.a("status",a)}}}catch(r){if(r instanceof utils.ServiceError)try{return utils.ServiceErrorBus.toMarkdown(r,{tool:"memory",operation:o,resultTag:"<memory_result>",pack:"memory"})}catch(l){return S.error("memory tool ServiceErrorBus formatting failed",{error:utils.errorMeta(l)}),`<memory_result>
25
+ Error: ${r.message}
26
+ </memory_result>`}return S.error("memory tool execution failed",{operation:o,error:utils.errorMeta(r)}),`<memory_result>
27
+ Error: ${utils.errorMeta(r).message}
28
+ </memory_result>`}}});var P=async e=>({hooks:E(),tools:{[v.name]:w}});utils.Log.create({service:"memory.plugin.hook"});var ge=[plugin.HookEvent.ContextBuildBefore,plugin.HookEvent.SessionCompacting,plugin.HookEvent.ToolFailure];var fe={name:"memory.plugin",async init(){return {isEnabled:()=>true,handlers:I.map(({event:e,handler:t})=>({name:e,handler:t}))}}};Object.defineProperty(exports,"MemoryStdioServer",{enumerable:true,get:function(){return chunkISYAE6B7_cjs.b}});Object.defineProperty(exports,"renderOperationMarkdown",{enumerable:true,get:function(){return chunkISYAE6B7_cjs.a}});Object.defineProperty(exports,"COMMANDS_HELP",{enumerable:true,get:function(){return chunk4G4FSAFY_cjs.a}});Object.defineProperty(exports,"handleMemoryCli",{enumerable:true,get:function(){return chunk4G4FSAFY_cjs.d}});Object.defineProperty(exports,"renderBanner",{enumerable:true,get:function(){return chunk4G4FSAFY_cjs.b}});Object.defineProperty(exports,"renderHelp",{enumerable:true,get:function(){return chunk4G4FSAFY_cjs.c}});Object.defineProperty(exports,"ALL_OPS",{enumerable:true,get:function(){return chunkQAEIHJOF_cjs.y}});Object.defineProperty(exports,"GraphStore",{enumerable:true,get:function(){return chunkQAEIHJOF_cjs.a}});Object.defineProperty(exports,"OP_REGISTRY",{enumerable:true,get:function(){return chunkQAEIHJOF_cjs.x}});Object.defineProperty(exports,"consolidate",{enumerable:true,get:function(){return chunkQAEIHJOF_cjs.r}});Object.defineProperty(exports,"doctor",{enumerable:true,get:function(){return chunkQAEIHJOF_cjs.v}});Object.defineProperty(exports,"executeOp",{enumerable:true,get:function(){return chunkQAEIHJOF_cjs.z}});Object.defineProperty(exports,"extract",{enumerable:true,get:function(){return chunkQAEIHJOF_cjs.q}});Object.defineProperty(exports,"forget",{enumerable:true,get:function(){return chunkQAEIHJOF_cjs.p}});Object.defineProperty(exports,"graphQuery",{enumerable:true,get:function(){return chunkQAEIHJOF_cjs.t}});Object.defineProperty(exports,"init",{enumerable:true,get:function(){return chunkQAEIHJOF_cjs.w}});Object.defineProperty(exports,"recall",{enumerable:true,get:function(){return chunkQAEIHJOF_cjs.b}});Object.defineProperty(exports,"remember",{enumerable:true,get:function(){return chunkQAEIHJOF_cjs.n}});Object.defineProperty(exports,"status",{enumerable:true,get:function(){return chunkQAEIHJOF_cjs.u}});Object.defineProperty(exports,"sync",{enumerable:true,get:function(){return chunkQAEIHJOF_cjs.s}});Object.defineProperty(exports,"update",{enumerable:true,get:function(){return chunkQAEIHJOF_cjs.o}});Object.defineProperty(exports,"LATEST_SCHEMA_VERSION",{enumerable:true,get:function(){return chunkIP7VEKQY_cjs.a}});Object.defineProperty(exports,"MIGRATIONS",{enumerable:true,get:function(){return chunkIP7VEKQY_cjs.b}});Object.defineProperty(exports,"MemoryDatabaseManager",{enumerable:true,get:function(){return chunkIP7VEKQY_cjs.e}});Object.defineProperty(exports,"readCurrentSchemaVersion",{enumerable:true,get:function(){return chunkIP7VEKQY_cjs.d}});Object.defineProperty(exports,"runMigrations",{enumerable:true,get:function(){return chunkIP7VEKQY_cjs.c}});Object.defineProperty(exports,"Llm",{enumerable:true,get:function(){return chunkEKSLNNMF_cjs.a}});Object.defineProperty(exports,"DEFAULT_MEMORY_JSON",{enumerable:true,get:function(){return chunkNHRRIJFK_cjs.b}});Object.defineProperty(exports,"MEMORY_JSON_REL_PATH",{enumerable:true,get:function(){return chunkNHRRIJFK_cjs.c}});Object.defineProperty(exports,"MemoryCache",{enumerable:true,get:function(){return chunkNHRRIJFK_cjs.d}});Object.defineProperty(exports,"MemoryJsonSchema",{enumerable:true,get:function(){return chunkNHRRIJFK_cjs.a}});Object.defineProperty(exports,"getGlobal",{enumerable:true,get:function(){return chunkGCVKM3RJ_cjs.c}});Object.defineProperty(exports,"getHomeDir",{enumerable:true,get:function(){return chunkGCVKM3RJ_cjs.g}});Object.defineProperty(exports,"getInstance",{enumerable:true,get:function(){return chunkGCVKM3RJ_cjs.f}});Object.defineProperty(exports,"getMemoryDbPath",{enumerable:true,get:function(){return chunkGCVKM3RJ_cjs.j}});Object.defineProperty(exports,"getMemoryDir",{enumerable:true,get:function(){return chunkGCVKM3RJ_cjs.i}});Object.defineProperty(exports,"getXdgData",{enumerable:true,get:function(){return chunkGCVKM3RJ_cjs.h}});Object.defineProperty(exports,"resetGlobalAdapter",{enumerable:true,get:function(){return chunkGCVKM3RJ_cjs.b}});Object.defineProperty(exports,"resetInstanceAdapter",{enumerable:true,get:function(){return chunkGCVKM3RJ_cjs.e}});Object.defineProperty(exports,"setGlobalAdapter",{enumerable:true,get:function(){return chunkGCVKM3RJ_cjs.a}});Object.defineProperty(exports,"setInstanceAdapter",{enumerable:true,get:function(){return chunkGCVKM3RJ_cjs.d}});Object.defineProperty(exports,"GRAPH_ENTITY_TYPE_DEFINITIONS",{enumerable:true,get:function(){return types.GRAPH_ENTITY_TYPE_DEFINITIONS}});Object.defineProperty(exports,"GRAPH_RELATION_TYPE_DEFINITIONS",{enumerable:true,get:function(){return types.GRAPH_RELATION_TYPE_DEFINITIONS}});exports.MEMORY_CATEGORIES=Sr;exports.MEMORY_HOOK_BINDINGS=I;exports.MEMORY_HOOK_EVENTS=ge;exports.MEMORY_PLUGIN_ID=j;exports.MEMORY_PLUGIN_MANIFEST=v;exports.MEMORY_PLUGIN_VERSION=K;exports.MEMORY_TOOL_ARGS=D;exports.MEMORY_TOOL_ID=W;exports.MEMORY_TOOL_OPS=G;exports.MemoryPlugin=P;exports.MemoryPluginEntry=P;exports.MemoryPluginHook=fe;exports.MemoryTool=w;exports.addWord=Fr;exports.closeTokenizer=$r;exports.createMemoryHookMatchers=E;exports.initTokenizer=Gr;exports.isInitialized=Dr;exports.loadCustomDict=Ye;exports.toFtsTokens=Br;exports.toFtsTokensForSearch=Yr;exports.tokenize=qe;exports.tokenizeForSearch=je;
package/dist/index.d.cts CHANGED
@@ -1,9 +1,11 @@
1
+ import * as _easbot_types from '@easbot/types';
1
2
  import { KnowledgeSearchOptions, MemoryKnowledgeConfigWithModels, KnowledgeDoctorResult, MemoryStatus, IGlobal, IInstance } from '@easbot/types';
2
3
  export { GRAPH_ENTITY_TYPE_DEFINITIONS, GRAPH_RELATION_TYPE_DEFINITIONS } from '@easbot/types';
3
4
  import { ILLMInitConfig, ILLMCapabilities, EmbeddingModelRef, LanguageModelRef, ExtractedEntity, ExtractedRelation } from '@easbot/llm';
4
5
  import { z, ZodTypeAny } from 'zod';
5
6
  import { StdioServerConfig } from '@easbot/mcp';
6
7
  import { SyncSqliteConnection } from '@easbot/database';
8
+ import { Plugin, PluginManifest, HookMatcher, HookHandler, HookInfo } from '@easbot/plugin';
7
9
  export { EmbeddingModelV3 as EmbeddingModel, LanguageModelV3 as LanguageModel } from '@ai-sdk/provider';
8
10
 
9
11
  declare const MemoryJsonSchema: z.ZodObject<{
@@ -633,4 +635,122 @@ declare namespace MemoryCache {
633
635
  function getConfigPath(): Promise<string>;
634
636
  }
635
637
 
636
- export { ALL_OPS, type ArchiveRecord, type ArchiveResult, COMMANDS_HELP, type CommandHelp, type ConsolidateParams, type ConsolidateResult, DEFAULT_MEMORY_JSON, type DoctorResult, type EdgeQueryFilter, type ExtractParams, type ExtractResult, type ForgetParams, type ForgetResult, type GraphQueryParams, type GraphQueryResult, GraphStore, type InitParams, type InitResult, type KGScope, LATEST_SCHEMA_VERSION, Llm, type LlmInitConfig, type LlmModels, MEMORY_CATEGORIES, MEMORY_JSON_REL_PATH, MIGRATIONS, MemoryCache, type MemoryCategory, type MemoryCliDeps, type MemoryCliResult, MemoryDatabaseManager, type MemoryEdge, type MemoryFact, type MemoryJson, MemoryJsonSchema, type MemoryNode, type MemoryNodeWithEdges, type MemoryOp, type MemoryQuery, type MemoryRecallResult, type MemorySource, MemoryStdioServer, type MemorySystemConfig, type MemoryVector, type NodeQueryFilter, OP_REGISTRY, type OpAnnotations, type OpHandlerContext, type OpScope, type RecallParams, type RecallResult, type RememberParams, type RememberResult, type StatusResult, type SyncParams, type SyncResult, type UpdateParams, type UpdateResult, addWord, closeTokenizer, consolidate, doctor, executeOp, extract, forget, getGlobal, getHomeDir, getInstance, getMemoryDbPath, getMemoryDir, getXdgData, graphQuery, handleMemoryCli, init, initTokenizer, isInitialized, loadCustomDict, readCurrentSchemaVersion, recall, remember, renderBanner, renderHelp, renderOperationMarkdown, resetGlobalAdapter, resetInstanceAdapter, runMigrations, setGlobalAdapter, setInstanceAdapter, status, sync, toFtsTokens, toFtsTokensForSearch, tokenize, tokenizeForSearch, update };
638
+ declare const MemoryPlugin: Plugin;
639
+
640
+ declare const MEMORY_PLUGIN_ID = "memory";
641
+ declare const MEMORY_PLUGIN_VERSION = "0.3.36";
642
+ declare const MEMORY_PLUGIN_MANIFEST: PluginManifest;
643
+
644
+ declare function createMemoryHookMatchers(): HookMatcher[];
645
+
646
+ declare const MEMORY_HOOK_EVENTS: readonly ["context.build.before", "session.compacting", "tool.failure"];
647
+ type MemoryHookEvent = (typeof MEMORY_HOOK_EVENTS)[number];
648
+ type MemoryHookHandler = HookHandler<unknown>;
649
+
650
+ type MemoryHookBinding = {
651
+ event: MemoryHookEvent;
652
+ handler: MemoryHookHandler;
653
+ };
654
+ declare const MEMORY_HOOK_BINDINGS: readonly MemoryHookBinding[];
655
+
656
+ declare const MemoryPluginHook: HookInfo;
657
+
658
+ declare const MEMORY_TOOL_ID = "memory";
659
+ declare const MEMORY_TOOL_OPS: readonly ["recall", "remember", "update", "forget", "extract", "graph_query", "status"];
660
+ type MemoryToolOperation = (typeof MEMORY_TOOL_OPS)[number];
661
+ declare const MEMORY_TOOL_ARGS: {
662
+ operation: z.ZodEnum<{
663
+ status: "status";
664
+ recall: "recall";
665
+ forget: "forget";
666
+ graph_query: "graph_query";
667
+ remember: "remember";
668
+ update: "update";
669
+ extract: "extract";
670
+ }>;
671
+ query: z.ZodOptional<z.ZodString>;
672
+ limit: z.ZodOptional<z.ZodPipe<z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>, z.ZodTransform<number, string | number>>, z.ZodNumber>>;
673
+ category: z.ZodOptional<z.ZodEnum<{
674
+ user_preference: "user_preference";
675
+ task_context: "task_context";
676
+ technical_fact: "technical_fact";
677
+ decision: "decision";
678
+ relationship: "relationship";
679
+ reminder: "reminder";
680
+ error_pattern: "error_pattern";
681
+ workflow: "workflow";
682
+ exploration_finding: "exploration_finding";
683
+ experience_summary: "experience_summary";
684
+ tool_usage: "tool_usage";
685
+ skill_creation: "skill_creation";
686
+ test: "test";
687
+ other: "other";
688
+ }>>;
689
+ minImportance: z.ZodOptional<z.ZodPipe<z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>, z.ZodTransform<number, string | number>>, z.ZodNumber>>;
690
+ maxEdgesPerNode: z.ZodOptional<z.ZodPipe<z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>, z.ZodTransform<number, string | number>>, z.ZodNumber>>;
691
+ includeGraph: z.ZodOptional<z.ZodBoolean>;
692
+ includeShared: z.ZodOptional<z.ZodBoolean>;
693
+ content: z.ZodOptional<z.ZodString>;
694
+ importance: z.ZodOptional<z.ZodPipe<z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>, z.ZodTransform<number, string | number>>, z.ZodNumber>>;
695
+ tags: z.ZodOptional<z.ZodPipe<z.ZodPipe<z.ZodUnion<readonly [z.ZodArray<z.ZodString>, z.ZodString]>, z.ZodTransform<string[], string | string[]>>, z.ZodArray<z.ZodString>>>;
696
+ factId: z.ZodOptional<z.ZodString>;
697
+ dryRun: z.ZodOptional<z.ZodBoolean>;
698
+ force: z.ZodOptional<z.ZodBoolean>;
699
+ lastN: z.ZodOptional<z.ZodPipe<z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>, z.ZodTransform<number, string | number>>, z.ZodNumber>>;
700
+ fromMessageId: z.ZodOptional<z.ZodString>;
701
+ nodeId: z.ZodOptional<z.ZodPipe<z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>, z.ZodTransform<number, string | number>>, z.ZodNumber>>;
702
+ maxDepth: z.ZodOptional<z.ZodPipe<z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>, z.ZodTransform<number, string | number>>, z.ZodNumber>>;
703
+ maxNodes: z.ZodOptional<z.ZodPipe<z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>, z.ZodTransform<number, string | number>>, z.ZodNumber>>;
704
+ relation: z.ZodOptional<z.ZodString>;
705
+ type: z.ZodOptional<z.ZodString>;
706
+ };
707
+ declare const MemoryTool: _easbot_types.ToolDefinition & {
708
+ args: {
709
+ operation: z.ZodEnum<{
710
+ status: "status";
711
+ recall: "recall";
712
+ forget: "forget";
713
+ graph_query: "graph_query";
714
+ remember: "remember";
715
+ update: "update";
716
+ extract: "extract";
717
+ }>;
718
+ query: z.ZodOptional<z.ZodString>;
719
+ limit: z.ZodOptional<z.ZodPipe<z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>, z.ZodTransform<number, string | number>>, z.ZodNumber>>;
720
+ category: z.ZodOptional<z.ZodEnum<{
721
+ user_preference: "user_preference";
722
+ task_context: "task_context";
723
+ technical_fact: "technical_fact";
724
+ decision: "decision";
725
+ relationship: "relationship";
726
+ reminder: "reminder";
727
+ error_pattern: "error_pattern";
728
+ workflow: "workflow";
729
+ exploration_finding: "exploration_finding";
730
+ experience_summary: "experience_summary";
731
+ tool_usage: "tool_usage";
732
+ skill_creation: "skill_creation";
733
+ test: "test";
734
+ other: "other";
735
+ }>>;
736
+ minImportance: z.ZodOptional<z.ZodPipe<z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>, z.ZodTransform<number, string | number>>, z.ZodNumber>>;
737
+ maxEdgesPerNode: z.ZodOptional<z.ZodPipe<z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>, z.ZodTransform<number, string | number>>, z.ZodNumber>>;
738
+ includeGraph: z.ZodOptional<z.ZodBoolean>;
739
+ includeShared: z.ZodOptional<z.ZodBoolean>;
740
+ content: z.ZodOptional<z.ZodString>;
741
+ importance: z.ZodOptional<z.ZodPipe<z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>, z.ZodTransform<number, string | number>>, z.ZodNumber>>;
742
+ tags: z.ZodOptional<z.ZodPipe<z.ZodPipe<z.ZodUnion<readonly [z.ZodArray<z.ZodString>, z.ZodString]>, z.ZodTransform<string[], string | string[]>>, z.ZodArray<z.ZodString>>>;
743
+ factId: z.ZodOptional<z.ZodString>;
744
+ dryRun: z.ZodOptional<z.ZodBoolean>;
745
+ force: z.ZodOptional<z.ZodBoolean>;
746
+ lastN: z.ZodOptional<z.ZodPipe<z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>, z.ZodTransform<number, string | number>>, z.ZodNumber>>;
747
+ fromMessageId: z.ZodOptional<z.ZodString>;
748
+ nodeId: z.ZodOptional<z.ZodPipe<z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>, z.ZodTransform<number, string | number>>, z.ZodNumber>>;
749
+ maxDepth: z.ZodOptional<z.ZodPipe<z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>, z.ZodTransform<number, string | number>>, z.ZodNumber>>;
750
+ maxNodes: z.ZodOptional<z.ZodPipe<z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>, z.ZodTransform<number, string | number>>, z.ZodNumber>>;
751
+ relation: z.ZodOptional<z.ZodString>;
752
+ type: z.ZodOptional<z.ZodString>;
753
+ };
754
+ };
755
+
756
+ export { ALL_OPS, type ArchiveRecord, type ArchiveResult, COMMANDS_HELP, type CommandHelp, type ConsolidateParams, type ConsolidateResult, DEFAULT_MEMORY_JSON, type DoctorResult, type EdgeQueryFilter, type ExtractParams, type ExtractResult, type ForgetParams, type ForgetResult, type GraphQueryParams, type GraphQueryResult, GraphStore, type InitParams, type InitResult, type KGScope, LATEST_SCHEMA_VERSION, Llm, type LlmInitConfig, type LlmModels, MEMORY_CATEGORIES, MEMORY_HOOK_BINDINGS, MEMORY_HOOK_EVENTS, MEMORY_JSON_REL_PATH, MEMORY_PLUGIN_ID, MEMORY_PLUGIN_MANIFEST, MEMORY_PLUGIN_VERSION, MEMORY_TOOL_ARGS, MEMORY_TOOL_ID, MEMORY_TOOL_OPS, MIGRATIONS, MemoryCache, type MemoryCategory, type MemoryCliDeps, type MemoryCliResult, MemoryDatabaseManager, type MemoryEdge, type MemoryFact, type MemoryJson, MemoryJsonSchema, type MemoryNode, type MemoryNodeWithEdges, type MemoryOp, MemoryPlugin, MemoryPlugin as MemoryPluginEntry, MemoryPluginHook, type MemoryQuery, type MemoryRecallResult, type MemorySource, MemoryStdioServer, type MemorySystemConfig, MemoryTool, type MemoryToolOperation, type MemoryVector, type NodeQueryFilter, OP_REGISTRY, type OpAnnotations, type OpHandlerContext, type OpScope, type RecallParams, type RecallResult, type RememberParams, type RememberResult, type StatusResult, type SyncParams, type SyncResult, type UpdateParams, type UpdateResult, addWord, closeTokenizer, consolidate, createMemoryHookMatchers, doctor, executeOp, extract, forget, getGlobal, getHomeDir, getInstance, getMemoryDbPath, getMemoryDir, getXdgData, graphQuery, handleMemoryCli, init, initTokenizer, isInitialized, loadCustomDict, readCurrentSchemaVersion, recall, remember, renderBanner, renderHelp, renderOperationMarkdown, resetGlobalAdapter, resetInstanceAdapter, runMigrations, setGlobalAdapter, setInstanceAdapter, status, sync, toFtsTokens, toFtsTokensForSearch, tokenize, tokenizeForSearch, update };
package/dist/index.d.ts CHANGED
@@ -1,9 +1,11 @@
1
+ import * as _easbot_types from '@easbot/types';
1
2
  import { KnowledgeSearchOptions, MemoryKnowledgeConfigWithModels, KnowledgeDoctorResult, MemoryStatus, IGlobal, IInstance } from '@easbot/types';
2
3
  export { GRAPH_ENTITY_TYPE_DEFINITIONS, GRAPH_RELATION_TYPE_DEFINITIONS } from '@easbot/types';
3
4
  import { ILLMInitConfig, ILLMCapabilities, EmbeddingModelRef, LanguageModelRef, ExtractedEntity, ExtractedRelation } from '@easbot/llm';
4
5
  import { z, ZodTypeAny } from 'zod';
5
6
  import { StdioServerConfig } from '@easbot/mcp';
6
7
  import { SyncSqliteConnection } from '@easbot/database';
8
+ import { Plugin, PluginManifest, HookMatcher, HookHandler, HookInfo } from '@easbot/plugin';
7
9
  export { EmbeddingModelV3 as EmbeddingModel, LanguageModelV3 as LanguageModel } from '@ai-sdk/provider';
8
10
 
9
11
  declare const MemoryJsonSchema: z.ZodObject<{
@@ -633,4 +635,122 @@ declare namespace MemoryCache {
633
635
  function getConfigPath(): Promise<string>;
634
636
  }
635
637
 
636
- export { ALL_OPS, type ArchiveRecord, type ArchiveResult, COMMANDS_HELP, type CommandHelp, type ConsolidateParams, type ConsolidateResult, DEFAULT_MEMORY_JSON, type DoctorResult, type EdgeQueryFilter, type ExtractParams, type ExtractResult, type ForgetParams, type ForgetResult, type GraphQueryParams, type GraphQueryResult, GraphStore, type InitParams, type InitResult, type KGScope, LATEST_SCHEMA_VERSION, Llm, type LlmInitConfig, type LlmModels, MEMORY_CATEGORIES, MEMORY_JSON_REL_PATH, MIGRATIONS, MemoryCache, type MemoryCategory, type MemoryCliDeps, type MemoryCliResult, MemoryDatabaseManager, type MemoryEdge, type MemoryFact, type MemoryJson, MemoryJsonSchema, type MemoryNode, type MemoryNodeWithEdges, type MemoryOp, type MemoryQuery, type MemoryRecallResult, type MemorySource, MemoryStdioServer, type MemorySystemConfig, type MemoryVector, type NodeQueryFilter, OP_REGISTRY, type OpAnnotations, type OpHandlerContext, type OpScope, type RecallParams, type RecallResult, type RememberParams, type RememberResult, type StatusResult, type SyncParams, type SyncResult, type UpdateParams, type UpdateResult, addWord, closeTokenizer, consolidate, doctor, executeOp, extract, forget, getGlobal, getHomeDir, getInstance, getMemoryDbPath, getMemoryDir, getXdgData, graphQuery, handleMemoryCli, init, initTokenizer, isInitialized, loadCustomDict, readCurrentSchemaVersion, recall, remember, renderBanner, renderHelp, renderOperationMarkdown, resetGlobalAdapter, resetInstanceAdapter, runMigrations, setGlobalAdapter, setInstanceAdapter, status, sync, toFtsTokens, toFtsTokensForSearch, tokenize, tokenizeForSearch, update };
638
+ declare const MemoryPlugin: Plugin;
639
+
640
+ declare const MEMORY_PLUGIN_ID = "memory";
641
+ declare const MEMORY_PLUGIN_VERSION = "0.3.36";
642
+ declare const MEMORY_PLUGIN_MANIFEST: PluginManifest;
643
+
644
+ declare function createMemoryHookMatchers(): HookMatcher[];
645
+
646
+ declare const MEMORY_HOOK_EVENTS: readonly ["context.build.before", "session.compacting", "tool.failure"];
647
+ type MemoryHookEvent = (typeof MEMORY_HOOK_EVENTS)[number];
648
+ type MemoryHookHandler = HookHandler<unknown>;
649
+
650
+ type MemoryHookBinding = {
651
+ event: MemoryHookEvent;
652
+ handler: MemoryHookHandler;
653
+ };
654
+ declare const MEMORY_HOOK_BINDINGS: readonly MemoryHookBinding[];
655
+
656
+ declare const MemoryPluginHook: HookInfo;
657
+
658
+ declare const MEMORY_TOOL_ID = "memory";
659
+ declare const MEMORY_TOOL_OPS: readonly ["recall", "remember", "update", "forget", "extract", "graph_query", "status"];
660
+ type MemoryToolOperation = (typeof MEMORY_TOOL_OPS)[number];
661
+ declare const MEMORY_TOOL_ARGS: {
662
+ operation: z.ZodEnum<{
663
+ status: "status";
664
+ recall: "recall";
665
+ forget: "forget";
666
+ graph_query: "graph_query";
667
+ remember: "remember";
668
+ update: "update";
669
+ extract: "extract";
670
+ }>;
671
+ query: z.ZodOptional<z.ZodString>;
672
+ limit: z.ZodOptional<z.ZodPipe<z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>, z.ZodTransform<number, string | number>>, z.ZodNumber>>;
673
+ category: z.ZodOptional<z.ZodEnum<{
674
+ user_preference: "user_preference";
675
+ task_context: "task_context";
676
+ technical_fact: "technical_fact";
677
+ decision: "decision";
678
+ relationship: "relationship";
679
+ reminder: "reminder";
680
+ error_pattern: "error_pattern";
681
+ workflow: "workflow";
682
+ exploration_finding: "exploration_finding";
683
+ experience_summary: "experience_summary";
684
+ tool_usage: "tool_usage";
685
+ skill_creation: "skill_creation";
686
+ test: "test";
687
+ other: "other";
688
+ }>>;
689
+ minImportance: z.ZodOptional<z.ZodPipe<z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>, z.ZodTransform<number, string | number>>, z.ZodNumber>>;
690
+ maxEdgesPerNode: z.ZodOptional<z.ZodPipe<z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>, z.ZodTransform<number, string | number>>, z.ZodNumber>>;
691
+ includeGraph: z.ZodOptional<z.ZodBoolean>;
692
+ includeShared: z.ZodOptional<z.ZodBoolean>;
693
+ content: z.ZodOptional<z.ZodString>;
694
+ importance: z.ZodOptional<z.ZodPipe<z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>, z.ZodTransform<number, string | number>>, z.ZodNumber>>;
695
+ tags: z.ZodOptional<z.ZodPipe<z.ZodPipe<z.ZodUnion<readonly [z.ZodArray<z.ZodString>, z.ZodString]>, z.ZodTransform<string[], string | string[]>>, z.ZodArray<z.ZodString>>>;
696
+ factId: z.ZodOptional<z.ZodString>;
697
+ dryRun: z.ZodOptional<z.ZodBoolean>;
698
+ force: z.ZodOptional<z.ZodBoolean>;
699
+ lastN: z.ZodOptional<z.ZodPipe<z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>, z.ZodTransform<number, string | number>>, z.ZodNumber>>;
700
+ fromMessageId: z.ZodOptional<z.ZodString>;
701
+ nodeId: z.ZodOptional<z.ZodPipe<z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>, z.ZodTransform<number, string | number>>, z.ZodNumber>>;
702
+ maxDepth: z.ZodOptional<z.ZodPipe<z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>, z.ZodTransform<number, string | number>>, z.ZodNumber>>;
703
+ maxNodes: z.ZodOptional<z.ZodPipe<z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>, z.ZodTransform<number, string | number>>, z.ZodNumber>>;
704
+ relation: z.ZodOptional<z.ZodString>;
705
+ type: z.ZodOptional<z.ZodString>;
706
+ };
707
+ declare const MemoryTool: _easbot_types.ToolDefinition & {
708
+ args: {
709
+ operation: z.ZodEnum<{
710
+ status: "status";
711
+ recall: "recall";
712
+ forget: "forget";
713
+ graph_query: "graph_query";
714
+ remember: "remember";
715
+ update: "update";
716
+ extract: "extract";
717
+ }>;
718
+ query: z.ZodOptional<z.ZodString>;
719
+ limit: z.ZodOptional<z.ZodPipe<z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>, z.ZodTransform<number, string | number>>, z.ZodNumber>>;
720
+ category: z.ZodOptional<z.ZodEnum<{
721
+ user_preference: "user_preference";
722
+ task_context: "task_context";
723
+ technical_fact: "technical_fact";
724
+ decision: "decision";
725
+ relationship: "relationship";
726
+ reminder: "reminder";
727
+ error_pattern: "error_pattern";
728
+ workflow: "workflow";
729
+ exploration_finding: "exploration_finding";
730
+ experience_summary: "experience_summary";
731
+ tool_usage: "tool_usage";
732
+ skill_creation: "skill_creation";
733
+ test: "test";
734
+ other: "other";
735
+ }>>;
736
+ minImportance: z.ZodOptional<z.ZodPipe<z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>, z.ZodTransform<number, string | number>>, z.ZodNumber>>;
737
+ maxEdgesPerNode: z.ZodOptional<z.ZodPipe<z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>, z.ZodTransform<number, string | number>>, z.ZodNumber>>;
738
+ includeGraph: z.ZodOptional<z.ZodBoolean>;
739
+ includeShared: z.ZodOptional<z.ZodBoolean>;
740
+ content: z.ZodOptional<z.ZodString>;
741
+ importance: z.ZodOptional<z.ZodPipe<z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>, z.ZodTransform<number, string | number>>, z.ZodNumber>>;
742
+ tags: z.ZodOptional<z.ZodPipe<z.ZodPipe<z.ZodUnion<readonly [z.ZodArray<z.ZodString>, z.ZodString]>, z.ZodTransform<string[], string | string[]>>, z.ZodArray<z.ZodString>>>;
743
+ factId: z.ZodOptional<z.ZodString>;
744
+ dryRun: z.ZodOptional<z.ZodBoolean>;
745
+ force: z.ZodOptional<z.ZodBoolean>;
746
+ lastN: z.ZodOptional<z.ZodPipe<z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>, z.ZodTransform<number, string | number>>, z.ZodNumber>>;
747
+ fromMessageId: z.ZodOptional<z.ZodString>;
748
+ nodeId: z.ZodOptional<z.ZodPipe<z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>, z.ZodTransform<number, string | number>>, z.ZodNumber>>;
749
+ maxDepth: z.ZodOptional<z.ZodPipe<z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>, z.ZodTransform<number, string | number>>, z.ZodNumber>>;
750
+ maxNodes: z.ZodOptional<z.ZodPipe<z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>, z.ZodTransform<number, string | number>>, z.ZodNumber>>;
751
+ relation: z.ZodOptional<z.ZodString>;
752
+ type: z.ZodOptional<z.ZodString>;
753
+ };
754
+ };
755
+
756
+ export { ALL_OPS, type ArchiveRecord, type ArchiveResult, COMMANDS_HELP, type CommandHelp, type ConsolidateParams, type ConsolidateResult, DEFAULT_MEMORY_JSON, type DoctorResult, type EdgeQueryFilter, type ExtractParams, type ExtractResult, type ForgetParams, type ForgetResult, type GraphQueryParams, type GraphQueryResult, GraphStore, type InitParams, type InitResult, type KGScope, LATEST_SCHEMA_VERSION, Llm, type LlmInitConfig, type LlmModels, MEMORY_CATEGORIES, MEMORY_HOOK_BINDINGS, MEMORY_HOOK_EVENTS, MEMORY_JSON_REL_PATH, MEMORY_PLUGIN_ID, MEMORY_PLUGIN_MANIFEST, MEMORY_PLUGIN_VERSION, MEMORY_TOOL_ARGS, MEMORY_TOOL_ID, MEMORY_TOOL_OPS, MIGRATIONS, MemoryCache, type MemoryCategory, type MemoryCliDeps, type MemoryCliResult, MemoryDatabaseManager, type MemoryEdge, type MemoryFact, type MemoryJson, MemoryJsonSchema, type MemoryNode, type MemoryNodeWithEdges, type MemoryOp, MemoryPlugin, MemoryPlugin as MemoryPluginEntry, MemoryPluginHook, type MemoryQuery, type MemoryRecallResult, type MemorySource, MemoryStdioServer, type MemorySystemConfig, MemoryTool, type MemoryToolOperation, type MemoryVector, type NodeQueryFilter, OP_REGISTRY, type OpAnnotations, type OpHandlerContext, type OpScope, type RecallParams, type RecallResult, type RememberParams, type RememberResult, type StatusResult, type SyncParams, type SyncResult, type UpdateParams, type UpdateResult, addWord, closeTokenizer, consolidate, createMemoryHookMatchers, doctor, executeOp, extract, forget, getGlobal, getHomeDir, getInstance, getMemoryDbPath, getMemoryDir, getXdgData, graphQuery, handleMemoryCli, init, initTokenizer, isInitialized, loadCustomDict, readCurrentSchemaVersion, recall, remember, renderBanner, renderHelp, renderOperationMarkdown, resetGlobalAdapter, resetInstanceAdapter, runMigrations, setGlobalAdapter, setInstanceAdapter, status, sync, toFtsTokens, toFtsTokensForSearch, tokenize, tokenizeForSearch, update };
package/dist/index.mjs CHANGED
@@ -1 +1,28 @@
1
- export{b as MemoryStdioServer,a as renderOperationMarkdown}from'./chunks/chunk-FZ3RTYIJ.mjs';import'./chunks/chunk-QF5S5MG7.mjs';export{a as COMMANDS_HELP,d as handleMemoryCli,b as renderBanner,c as renderHelp}from'./chunks/chunk-YUWHNHAY.mjs';export{y as ALL_OPS,a as GraphStore,x as OP_REGISTRY,r as consolidate,v as doctor,z as executeOp,q as extract,p as forget,t as graphQuery,w as init,b as recall,n as remember,u as status,s as sync,o as update}from'./chunks/chunk-AEAMQDNV.mjs';export{a as LATEST_SCHEMA_VERSION,b as MIGRATIONS,e as MemoryDatabaseManager,d as readCurrentSchemaVersion,c as runMigrations}from'./chunks/chunk-YJLHS7JB.mjs';export{a as Llm}from'./chunks/chunk-HH7EA2UE.mjs';import {a}from'./chunks/chunk-AJDMZTCQ.mjs';export{b as DEFAULT_MEMORY_JSON,c as MEMORY_JSON_REL_PATH,d as MemoryCache,a as MemoryJsonSchema}from'./chunks/chunk-SE3F5YQE.mjs';export{c as getGlobal,g as getHomeDir,f as getInstance,j as getMemoryDbPath,i as getMemoryDir,h as getXdgData,b as resetGlobalAdapter,e as resetInstanceAdapter,a as setGlobalAdapter,d as setInstanceAdapter}from'./chunks/chunk-HX3TV7FD.mjs';import'./chunks/chunk-S4DPVKMV.mjs';export{GRAPH_ENTITY_TYPE_DEFINITIONS,GRAPH_RELATION_TYPE_DEFINITIONS}from'@easbot/types';import*as n from'jieba-wasm';import {Log,loadTextFile,errorMeta,Filesystem}from'@easbot/utils';var ie=["user_preference","task_context","technical_fact","decision","relationship","reminder","error_pattern","workflow","exploration_finding","experience_summary","tool_usage","skill_creation","test","other"];var t=Log.create({service:"memory.tokenizer"}),o=false,re=loadTextFile("./assets/jieba_dict.txt",import.meta.url);async function ge(e){if(!o)try{t.debug("Initializing jieba tokenizer");let r=re();if(n.with_dict(r),t.debug("Built-in dictionary loaded"),e?.dictPath&&e.dictPath.length>0)for(let a of e.dictPath)await te(a);o=!0,t.debug("Jieba tokenizer initialized successfully");}catch(r){t.error("Failed to initialize jieba tokenizer",{error:errorMeta(r)}),t.warn("Using fallback tokenization (space-based)");}}async function te(e){if(!o)throw new a.TokenizerNotInitializedError({message:"Tokenizer not initialized"});try{let r=await Filesystem.readText(e);t.debug("Loading custom dictionary",{dictPath:e}),n.with_dict(r),t.debug("Custom dictionary loaded successfully",{dictPath:e});}catch(r){t.warn("Failed to load custom dictionary",{dictPath:e,error:errorMeta(r)});}}function oe(e){if(!o)return e.split(/\s+/).filter(Boolean);try{return n.cut(e)}catch(r){return t.warn("Tokenization failed, using fallback",{error:errorMeta(r)}),e.split(/\s+/).filter(Boolean)}}function ne(e){if(!o)return e.split(/\s+/).filter(Boolean);try{return n.cut_for_search(e)}catch(r){return t.warn("Tokenization for search failed, using fallback",{error:errorMeta(r)}),e.split(/\s+/).filter(Boolean)}}function ye(e,r,a){if(o)try{n.add_word(e,r,a),t.debug("Word added to dictionary",{word:e,freq:r,tag:a});}catch(_){t.warn("Failed to add word",{word:e,error:errorMeta(_)});}}function fe(){return o}async function xe(){o=false,t.debug("Tokenizer closed");}function Me(e){if(!o)return e.split(/\s+/).filter(Boolean).join(" ");try{return oe(e).join(" ")}catch(r){return t.warn("Tokenization failed, using fallback",{error:errorMeta(r)}),e.split(/\s+/).filter(Boolean).join(" ")}}function be(e){if(!o)return e.split(/\s+/).filter(Boolean).join(" ");try{return ne(e).join(" ")}catch(r){return t.warn("Tokenization for search failed, using fallback",{error:errorMeta(r)}),e.split(/\s+/).filter(Boolean).join(" ")}}export{ie as MEMORY_CATEGORIES,ye as addWord,xe as closeTokenizer,ge as initTokenizer,fe as isInitialized,te as loadCustomDict,Me as toFtsTokens,be as toFtsTokensForSearch,oe as tokenize,ne as tokenizeForSearch};
1
+ import {a}from'./chunks/chunk-FZ3RTYIJ.mjs';export{b as MemoryStdioServer,a as renderOperationMarkdown}from'./chunks/chunk-FZ3RTYIJ.mjs';import'./chunks/chunk-QF5S5MG7.mjs';export{a as COMMANDS_HELP,d as handleMemoryCli,b as renderBanner,c as renderHelp}from'./chunks/chunk-YUWHNHAY.mjs';import {A as A$1,z as z$1}from'./chunks/chunk-AEAMQDNV.mjs';export{y as ALL_OPS,a as GraphStore,x as OP_REGISTRY,r as consolidate,v as doctor,z as executeOp,q as extract,p as forget,t as graphQuery,w as init,b as recall,n as remember,u as status,s as sync,o as update}from'./chunks/chunk-AEAMQDNV.mjs';export{a as LATEST_SCHEMA_VERSION,b as MIGRATIONS,e as MemoryDatabaseManager,d as readCurrentSchemaVersion,c as runMigrations}from'./chunks/chunk-YJLHS7JB.mjs';import {a as a$1}from'./chunks/chunk-HH7EA2UE.mjs';export{a as Llm}from'./chunks/chunk-HH7EA2UE.mjs';import {a as a$2}from'./chunks/chunk-AJDMZTCQ.mjs';import {d}from'./chunks/chunk-SE3F5YQE.mjs';export{b as DEFAULT_MEMORY_JSON,c as MEMORY_JSON_REL_PATH,d as MemoryCache,a as MemoryJsonSchema}from'./chunks/chunk-SE3F5YQE.mjs';import {j,f as f$1}from'./chunks/chunk-HX3TV7FD.mjs';export{c as getGlobal,g as getHomeDir,f as getInstance,j as getMemoryDbPath,i as getMemoryDir,h as getXdgData,b as resetGlobalAdapter,e as resetInstanceAdapter,a as setGlobalAdapter,d as setInstanceAdapter}from'./chunks/chunk-HX3TV7FD.mjs';import'./chunks/chunk-S4DPVKMV.mjs';export{GRAPH_ENTITY_TYPE_DEFINITIONS,GRAPH_RELATION_TYPE_DEFINITIONS}from'@easbot/types';import*as x from'jieba-wasm';import {Log,loadTextFile,Schema,ServiceError,ServiceErrorBus,errorMeta,NameErrors,Filesystem}from'@easbot/utils';import {HookEvent,createTool}from'@easbot/plugin';import {createHash}from'crypto';import {existsSync}from'fs';import {z}from'zod';var wr=["user_preference","task_context","technical_fact","decision","relationship","reminder","error_pattern","workflow","exploration_finding","experience_summary","tool_usage","skill_creation","test","other"];var f=Log.create({service:"memory.tokenizer"}),M=false,Ye=loadTextFile("./assets/jieba_dict.txt",import.meta.url);async function Fr(e){if(!M)try{f.debug("Initializing jieba tokenizer");let t=Ye();if(x.with_dict(t),f.debug("Built-in dictionary loaded"),e?.dictPath&&e.dictPath.length>0)for(let o of e.dictPath)await qe(o);M=!0,f.debug("Jieba tokenizer initialized successfully");}catch(t){f.error("Failed to initialize jieba tokenizer",{error:errorMeta(t)}),f.warn("Using fallback tokenization (space-based)");}}async function qe(e){if(!M)throw new a$2.TokenizerNotInitializedError({message:"Tokenizer not initialized"});try{let t=await Filesystem.readText(e);f.debug("Loading custom dictionary",{dictPath:e}),x.with_dict(t),f.debug("Custom dictionary loaded successfully",{dictPath:e});}catch(t){f.warn("Failed to load custom dictionary",{dictPath:e,error:errorMeta(t)});}}function je(e){if(!M)return e.split(/\s+/).filter(Boolean);try{return x.cut(e)}catch(t){return f.warn("Tokenization failed, using fallback",{error:errorMeta(t)}),e.split(/\s+/).filter(Boolean)}}function Ke(e){if(!M)return e.split(/\s+/).filter(Boolean);try{return x.cut_for_search(e)}catch(t){return f.warn("Tokenization for search failed, using fallback",{error:errorMeta(t)}),e.split(/\s+/).filter(Boolean)}}function Dr(e,t,o){if(M)try{x.add_word(e,t,o),f.debug("Word added to dictionary",{word:e,freq:t,tag:o});}catch(r){f.warn("Failed to add word",{word:e,error:errorMeta(r)});}}function $r(){return M}async function Br(){M=false,f.debug("Tokenizer closed");}function Yr(e){if(!M)return e.split(/\s+/).filter(Boolean).join(" ");try{return je(e).join(" ")}catch(t){return f.warn("Tokenization failed, using fallback",{error:errorMeta(t)}),e.split(/\s+/).filter(Boolean).join(" ")}}function qr(e){if(!M)return e.split(/\s+/).filter(Boolean).join(" ");try{return Ke(e).join(" ")}catch(t){return f.warn("Tokenization for search failed, using fallback",{error:errorMeta(t)}),e.split(/\s+/).filter(Boolean).join(" ")}}var K="memory",U="0.3.36",C={name:K,version:U,description:"EASBot memory plugin: lifecycle hooks and memory tool",entry:"./index.mjs",capabilities:["hooks","tools"]};function y(e,t){if(typeof e!="object"||e===null)return;let o=e;for(let r of t){let l=o[r];if(typeof l=="string"&&l.length>0)return l}}function ce(e){if(typeof e!="object"||e===null)return {};let t=e.extras;return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:{}}function pe(e){if(typeof e!="object"||e===null)return;let t=e.protocolMetadata;if(typeof t!="object"||t===null)return;let o=t.agentId;return typeof o=="string"&&o.length>0?o:void 0}function h(e,t){let o={...ce(e),...ce(t)};return {agentId:y(t,["agentId"])??pe(e)??pe(t)??y(e,["agentId"])??y(t,["agent"])??y(e,["agent"])??"",sessionId:y(t,["sessionId"])??y(e,["sessionId"]),toolName:y(e,["toolName","tool","name"])??y(t,["toolName"]),error:y(e,["error","message"])??y(t,["error"]),messagePreview:y(e,["messagePreview"])??y(t,["messagePreview"]),contextPreview:y(e,["contextPreview","text","prompt"])??y(t,["contextPreview"]),extras:o}}function I(e){let t=f$1().worktree,o=j(t),r=e.trim()||"memory-plugin";return {agentId:r,isTrustedLocal:true,remote:false,locale:"en-US",dbPath:o,workspaceDir:t,rootDir:t,config:A$1({agentId:r,dbPath:o,workspaceDir:t})}}function g(e,t){return {modified:false,input:e,output:{...t}}}function de(e,t){return {modified:true,input:e,output:{...t}}}function ue(e,t){return y(e,[t])}var Qe=Log.create({service:"memory.plugin.hook"}),A=async(e,t)=>{let o=HookEvent.ContextBuildBefore,r=h(e,t);if(!r.agentId.trim())return g(e,{hook:o,ok:false,error:"context build: agentId is required"});let l=typeof r.extras.topK=="number"?r.extras.topK:5,m=typeof r.extras.query=="string"?r.extras.query:"";try{let c=await z$1("recall",{query:m,maxResults:l},I(r.agentId));if(c.hits.length===0)return g(e,{hook:o,ok:!0,context:[],logLine:"context build: no facts found; skipping context injection"});let i=c.hits.map(B=>`- [${B.category}/imp=${B.importance}] ${B.snippet.slice(0,200)}`),a=`[memory:recall top-${c.hits.length}]
2
+ ${i.join(`
3
+ `)}`,k=ue(e,"userMessage");return k===void 0?g(e,{hook:o,ok:!0,context:[a],logLine:`context build: recalled ${c.hits.length} facts (input shape unexpected, not injected)`}):de({...e,userMessage:k?`${a}
4
+
5
+ ${k}`:a},{hook:o,ok:!0,context:[a],logLine:`context build: injected ${c.hits.length} facts`})}catch(c){let i=errorMeta(c);return Qe.warn("memory context build hook failed",{error:i}),g(e,{hook:o,ok:false,error:i.message})}};var Ze=Log.create({service:"memory.plugin.hook"}),er=200,L=async(e,t)=>{let o=HookEvent.SessionCompacting,r=h(e,t);if(!r.agentId.trim())return g(e,{hook:o,ok:false,error:"pre compact: agentId is required"});let m=(r.contextPreview??r.messagePreview??"").slice(0,er).replace(/\s+/g," ").trim(),c=typeof r.extras.topK=="number"?r.extras.topK:3;if(!m)return g(e,{hook:o,ok:true,context:[],logLine:"pre compact: empty context preview; skipping recall injection"});try{let i=await z$1("recall",{query:m,maxResults:c,minImportance:5},I(r.agentId));if(i.hits.length===0)return g(e,{hook:o,ok:!0,context:[],logLine:"pre compact: no facts matched query"});let a=i.hits.map(T=>`- [${T.category}/imp=${T.importance}] ${T.snippet.slice(0,150)}`),k=`[memory:pre-compact recall top-${i.hits.length} (imp>=5)]
6
+ ${a.join(`
7
+ `)}`;return g(e,{hook:o,ok:!0,context:[k],logLine:`pre compact: injected ${i.hits.length} facts before compaction`})}catch(i){let a=errorMeta(i);return Ze.warn("memory pre compact hook failed",{error:a}),g(e,{hook:o,ok:false,error:a.message})}};var ar=Log.create({service:"memory.plugin.hook"}),ir=8,G=async(e,t)=>{let o=HookEvent.ToolFailure,r=h(e,t);if(!r.agentId.trim())return g(e,{hook:o,ok:false,error:"tool failure: agentId is required"});if(!r.toolName?.trim()||!r.error?.trim())return g(e,{hook:o,ok:false,error:"tool failure: toolName and error are required"});let l=createHash("sha256").update(`${r.toolName}:${r.error}`).digest("hex").slice(0,ir),m=r.messagePreview?r.messagePreview.slice(0,200).replace(/\s+/g," ").trim():"",c=[`[error_pattern] tool=${r.toolName}`,`[error] ${r.error}`,m?`[preview] ${m}`:"",`[errHash] ${l}`].filter(Boolean).join(`
8
+ `);try{let i=await z$1("remember",{content:c,category:"error_pattern",importance:6,tags:["post-tool-failure",`tool:${r.toolName}`,`err:${l}`],sessionId:r.sessionId,msgId:typeof r.extras.msgId=="string"?r.extras.msgId:void 0},I(r.agentId));return g(e,{hook:o,ok:!0,logLine:`tool failure: wrote error_pattern fact ${i.fact.id} (tool=${r.toolName}, errHash=${l})`})}catch(i){let a=errorMeta(i);return ar.warn("memory tool failure hook failed",{error:a}),g(e,{hook:o,ok:false,error:a.message})}};var _=[{event:HookEvent.ContextBuildBefore,handler:A},{event:HookEvent.SessionCompacting,handler:L},{event:HookEvent.ToolFailure,handler:G}];function S(){return _.map(({event:e,handler:t})=>({event:e,hooks:[{type:"function",handler:t}]}))}var w=Log.create({service:"memory.plugin.tool"}),Q="memory",F=["recall","remember","update","forget","extract","graph_query","status"],ur=500,ge="Access EASBot long-term memory via `operation` (recall / remember / update / forget / extract / graph_query / status).",D=z.enum(["user_preference","task_context","technical_fact","decision","relationship","reminder","error_pattern","workflow","exploration_finding","experience_summary","tool_usage","skill_creation","test","other"]),gr=z.object({operation:z.literal("recall"),query:z.string().describe("Search query text"),limit:Schema.positiveInt.optional().default(10).describe("Max results (default 10)"),category:D.optional().describe("Filter by memory category"),minImportance:Schema.positiveInt.optional().refine(e=>e===void 0||e>=1&&e<=10,{message:"minImportance must be in [1, 10] (inclusive); the service uses `WHERE importance >= ?` SQL"}).describe("INCLUSIVE `>=` filter on 1-10 importance scale"),maxEdgesPerNode:Schema.positiveInt.optional().default(10).refine(e=>e===void 0||e>=1&&e<=100,{message:"maxEdgesPerNode must be in [1, 100]"}).describe("Max edges per KG neighbor node returned by recall (default 10; range [1, 100])"),includeGraph:z.boolean().optional().default(false).describe("Include KG neighbor subgraph (default false)"),includeShared:z.boolean().optional().default(false).describe("Include shared KG nodes from other agents (default false)")}).strict(),fr=z.object({operation:z.literal("remember"),content:z.string().describe("Memory content"),category:D.describe("Memory category"),importance:Schema.positiveInt.describe("Importance 1-10 (service layer enforces range)"),tags:Schema.stringArray.optional().describe("Optional tags (string[])")}).strict(),yr=z.object({operation:z.literal("update"),factId:z.string().describe("Target fact id (must belong to ctx.agentId)"),content:z.string().optional().describe("New content (triggers embedding rewrite + FTS reindex)"),category:D.optional().describe("New category"),importance:Schema.positiveInt.optional().describe("New importance 1-10"),tags:Schema.stringArray.optional().describe("New tags (string[]; empty array clears tags)")}).strict().refine(e=>e.content!==void 0||e.category!==void 0||e.importance!==void 0||e.tags!==void 0,{message:"update requires at least one of: `content`, `category`, `importance`, `tags`"}),Mr=z.object({operation:z.literal("forget"),factId:z.string().describe("Target fact id to delete (must belong to ctx.agentId)"),dryRun:z.boolean().optional().default(false).describe("Preview without deleting (returns matched count, never deletes)"),force:z.boolean().optional().default(false).describe("Skip KG reference check and delete anyway (use after dryRun confirms the match)")}).strict(),xr=z.object({operation:z.literal("extract"),lastN:Schema.positiveInt.optional().default(10).describe("Recent messages (default 10)"),fromMessageId:z.string().optional().describe("Process messages after this id")}).strict(),kr=z.object({operation:z.literal("graph_query"),query:z.string().min(1).optional().describe('Node name fragment (NOT natural-language query): locate one root node by case-insensitive `LIKE %name%` match against `nodes.name`, then BFS neighbor expansion. Pass only short identifiers (e.g. "easbot"). Use `recall` for natural-language fact search.'),nodeId:Schema.positiveInt.optional().describe("KG node id to start BFS from (alternative to `query`)"),maxDepth:Schema.positiveInt.optional().default(2).describe("BFS depth for neighbor expansion (default 2; range [1, 5])"),maxNodes:Schema.nonNegativeInt.optional().default(100).describe("Max nodes returned after BFS (default 100; service max 500)"),maxEdgesPerNode:Schema.positiveInt.optional().default(10).refine(e=>e===void 0||e>=1&&e<=100,{message:"maxEdgesPerNode must be in [1, 100]"}).describe("Max edges per BFS neighbor node (default 10; range [1, 100])"),relation:z.string().optional().describe('Edge relation filter (e.g. "uses"; single-value exact match)'),type:z.string().optional().describe('Node type filter for root node (e.g. "decision")')}).strict().refine(e=>e.query!==void 0||e.nodeId!==void 0,{message:"graph_query requires either `query` (node name fragment) or `nodeId` (KG node id)"}),br=z.object({operation:z.literal("status")}).strict(),hr={recall:gr,remember:fr,update:yr,forget:Mr,extract:xr,graph_query:kr,status:br},$={operation:z.enum(F).describe("Operation to run (exactly one per call)"),query:z.string().optional().describe("recall: search query text / graph_query: node name fragment"),limit:Schema.positiveInt.optional().describe("recall: max results (default 10, max 100)"),category:D.optional().describe("remember/update: memory category / recall: category filter"),minImportance:Schema.positiveInt.optional().describe("recall: INCLUSIVE `>=` filter on the 1-10 importance scale"),maxEdgesPerNode:Schema.positiveInt.optional().describe("recall/graph_query: max edges per KG neighbor node (default 10, max 100)"),includeGraph:z.boolean().optional().describe("recall: include KG neighbor subgraph (default false)"),includeShared:z.boolean().optional().describe("recall: include shared KG nodes from other agents (default false)"),content:z.string().optional().describe("remember/update: fact body"),importance:Schema.positiveInt.optional().describe("remember/update: importance 1-10"),tags:Schema.stringArray.optional().describe("remember/update: tags (string[] or comma-separated string)"),factId:z.string().optional().describe("update/forget: target fact id"),dryRun:z.boolean().optional().describe("forget: preview without deleting (default false)"),force:z.boolean().optional().describe("forget: skip KG reference check and delete anyway (default false)"),lastN:Schema.positiveInt.optional().describe("extract: recent messages to scan (default 10)"),fromMessageId:z.string().optional().describe("extract: process messages after this id"),nodeId:Schema.positiveInt.optional().describe("graph_query: KG node id to start BFS from"),maxDepth:Schema.positiveInt.optional().describe("graph_query: BFS depth (default 2, max 5)"),maxNodes:Schema.nonNegativeInt.optional().describe("graph_query: max nodes returned after BFS (default 100, max 500)"),relation:z.string().optional().describe("graph_query: edge relation filter (single-value exact match)"),type:z.string().optional().describe("graph_query: node type filter for root node")};function Ir(){try{let e=loadTextFile("./memory.txt",import.meta.url)();return e.trim().length>0?e:ge}catch(e){return w.warn("memory tool description unavailable, using fallback",{error:errorMeta(e)}),ge}}function _r(e){let t=e.agent?.trim();if(!t)throw new NameErrors.MissingFieldError({message:"memory tool: agentId is required (ctx.agent must be set)",field:"agentId"});return t}function Or(e,t){let o=hr[e],r={};for(let m of Object.keys(o.shape))r[m]=t[m];let l=o.safeParse({...r,operation:e});if(!l.success){let m=l.error.issues.map(c=>`${c.path.join(".")||"(root)"}: ${c.message}`).join("; ");throw new NameErrors.InvalidArgumentError({message:`memory tool: invalid parameters for operation "${e}" \u2014 ${m}`,param:e})}return l.data}async function Rr(e,t){let o=j(e);if(!existsSync(o)){w.debug("memory db not found, auto-initializing",{dbPath:o,workspaceDir:e});try{await z$1("init",{workspaceDir:e,force:!1},t);}catch(r){throw new NameErrors.OperationFailedError({message:`memory tool: auto-init failed (${errorMeta(r).message}). Try running \`easbot memory init\` manually.`,operation:"memory-auto-init"})}}}async function Hr(){if(!(a$1.isInitialized()&&a$1.capabilities().graph))try{let e=await d.getMemoryJson();a$1.init({models:{embedding:e?.embedding_model??void 0,graph:e?.graph_model??void 0}});}catch(e){w.warn("memory Llm init failed; KG extraction will be skipped",{error:errorMeta(e)});}}var P=createTool({description:Ir(),args:$,execute:async(e,t)=>{let o=String(e.operation);try{await t.ask({permission:"memory",patterns:o==="recall"?[String(e.query??"")]:["*"],always:["*"],metadata:{operation:o}});let r=Or(o,e),l=_r(t),m=t.worktree||t.directory||process.cwd(),c=j(m),i={agentId:l,isTrustedLocal:!0,remote:!1,locale:"en-US",dbPath:c,workspaceDir:m,rootDir:m,config:A$1({agentId:l,dbPath:c,workspaceDir:m}),signal:t.abort};switch(await Hr(),await Rr(m,i),o){case "recall":{let a$1=await z$1("recall",{query:r.query,maxResults:r.limit,category:r.category,minImportance:r.minImportance,maxEdgesPerNode:r.maxEdgesPerNode,includeGraph:r.includeGraph,includeShared:r.includeShared,snippetMaxChars:ur},i);return await a("recall",a$1,{toolName:"memory_recall",query:r.query,agentId:l,scope:r.includeShared?"both":"agent_only"})}case "remember":{let a=await z$1("remember",{content:r.content,category:r.category,importance:r.importance,tags:r.tags,sessionId:t.sessionId},i);return `<memory_result>
9
+ Memory saved.
10
+ id: ${a.fact.id}
11
+ category: ${a.fact.category}
12
+ importance: ${r.importance}
13
+ linked nodes: ${a.nodeIds?.length??0}
14
+ </memory_result>`}case "update":{let a=await z$1("update",{factId:r.factId,content:r.content,category:r.category,importance:r.importance,tags:r.tags},i),k=a.fieldsUpdated?.join(", ")??"none";return `<memory_result>
15
+ Memory updated.
16
+ id: ${r.factId}
17
+ updated fields: ${k}
18
+ content changed: ${a.contentChanged}
19
+ </memory_result>`}case "forget":{let a$1=await z$1("forget",{factId:r.factId,dryRun:r.dryRun,force:r.force},i);return await a("forget",a$1)}case "extract":{let a=await z$1("extract",{sessionId:t.sessionId,lastN:r.lastN,fromMessageId:r.fromMessageId},i);return `<memory_result>
20
+ Extraction finished.
21
+ extracted: ${a.extractedCount??0}
22
+ entities: ${a.entities?.length??0}
23
+ relations: ${a.relations?.length??0}
24
+ </memory_result>`}case "graph_query":{let a$1=await z$1("graph_query",{query:r.query,nodeId:r.nodeId,maxDepth:r.maxDepth,maxNodes:r.maxNodes,maxEdgesPerNode:r.maxEdgesPerNode,relation:r.relation,type:r.type},i);return await a("graph_query",a$1)}case "status":{let a$1=await z$1("status",{},i);return await a("status",a$1)}}}catch(r){if(r instanceof ServiceError)try{return ServiceErrorBus.toMarkdown(r,{tool:"memory",operation:o,resultTag:"<memory_result>",pack:"memory"})}catch(l){return w.error("memory tool ServiceErrorBus formatting failed",{error:errorMeta(l)}),`<memory_result>
25
+ Error: ${r.message}
26
+ </memory_result>`}return w.error("memory tool execution failed",{operation:o,error:errorMeta(r)}),`<memory_result>
27
+ Error: ${errorMeta(r).message}
28
+ </memory_result>`}}});var N=async e=>({hooks:S(),tools:{[C.name]:P}});Log.create({service:"memory.plugin.hook"});var fe=[HookEvent.ContextBuildBefore,HookEvent.SessionCompacting,HookEvent.ToolFailure];var ye={name:"memory.plugin",async init(){return {isEnabled:()=>true,handlers:_.map(({event:e,handler:t})=>({name:e,handler:t}))}}};export{wr as MEMORY_CATEGORIES,_ as MEMORY_HOOK_BINDINGS,fe as MEMORY_HOOK_EVENTS,K as MEMORY_PLUGIN_ID,C as MEMORY_PLUGIN_MANIFEST,U as MEMORY_PLUGIN_VERSION,$ as MEMORY_TOOL_ARGS,Q as MEMORY_TOOL_ID,F as MEMORY_TOOL_OPS,N as MemoryPlugin,N as MemoryPluginEntry,ye as MemoryPluginHook,P as MemoryTool,Dr as addWord,Br as closeTokenizer,S as createMemoryHookMatchers,Fr as initTokenizer,$r as isInitialized,qe as loadCustomDict,Yr as toFtsTokens,qr as toFtsTokensForSearch,je as tokenize,Ke as tokenizeForSearch};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@easbot/memory",
3
- "version": "0.3.32",
3
+ "version": "0.3.37",
4
4
  "description": "Memory management library for EASBOT ecosystem - 智能记忆管理库,支持混合搜索、中英文分词、增量索引",
5
5
  "type": "module",
6
6
  "main": "dist/index.cjs",
@@ -45,7 +45,7 @@
45
45
  "LICENSE"
46
46
  ],
47
47
  "dependencies": {
48
- "zod": "^4.4.3",
48
+ "zod": "^4.6.7",
49
49
  "@ai-sdk/provider": "^3.0.15",
50
50
  "@ai-sdk/provider-utils": "^4.0.45",
51
51
  "@ai-sdk/openai-compatible": "2.0.70",
@@ -53,21 +53,22 @@
53
53
  "ai": "^6.0.253",
54
54
  "better-sqlite3": "^13.0.3",
55
55
  "jieba-wasm": "^2.4.0",
56
- "@easbot/database": "0.3.32",
57
- "@easbot/mcp": "0.3.32",
58
- "@easbot/types": "0.3.32",
59
- "@easbot/terminal": "0.3.32",
60
- "@easbot/utils": "0.3.32",
61
- "@easbot/llm": "0.3.32",
62
- "@easbot/local-model-sdk": "0.3.32",
63
- "@easbot/ollama-sdk": "0.3.32"
56
+ "@easbot/database": "0.3.37",
57
+ "@easbot/mcp": "0.3.37",
58
+ "@easbot/plugin": "0.3.37",
59
+ "@easbot/types": "0.3.37",
60
+ "@easbot/utils": "0.3.37",
61
+ "@easbot/terminal": "0.3.37",
62
+ "@easbot/llm": "0.3.37",
63
+ "@easbot/local-model-sdk": "0.3.37",
64
+ "@easbot/ollama-sdk": "0.3.37"
64
65
  },
65
66
  "devDependencies": {
66
67
  "@types/node": "^25.9.5",
67
68
  "@types/better-sqlite3": "^9.6.0",
68
69
  "tsup": "^8.5.1",
69
70
  "typescript": "^6.0.3",
70
- "vitest": "^4.1.10"
71
+ "vitest": "^5.0.5"
71
72
  },
72
73
  "engines": {
73
74
  "node": ">=22.22.2"
@@ -82,6 +83,8 @@
82
83
  "test:run": "vitest run",
83
84
  "test:coverage": "vitest run --coverage",
84
85
  "test:clean": "tsx scripts/clean-test-fixtures.ts",
86
+ "plugin:generate": "tsx scripts/generate-plugin-distribution.ts",
87
+ "plugin:check": "tsx scripts/generate-plugin-distribution.ts --check",
85
88
  "lint": "biome check .",
86
89
  "lint:fix": "biome check --write .",
87
90
  "lint:report": "biome check --reporter=summary .",
@@ -1 +0,0 @@
1
- 'use strict';var chunk6H5PTRZL_cjs=require('./chunk-6H5PTRZL.cjs');require('./chunk-GCVKM3RJ.cjs'),require('./chunk-KFESJR3T.cjs');Object.defineProperty(exports,"COMMANDS_HELP",{enumerable:true,get:function(){return chunk6H5PTRZL_cjs.a}});Object.defineProperty(exports,"handleMemoryCli",{enumerable:true,get:function(){return chunk6H5PTRZL_cjs.d}});Object.defineProperty(exports,"mapMemoryDoctor",{enumerable:true,get:function(){return chunk6H5PTRZL_cjs.e}});Object.defineProperty(exports,"renderBanner",{enumerable:true,get:function(){return chunk6H5PTRZL_cjs.b}});Object.defineProperty(exports,"renderHelp",{enumerable:true,get:function(){return chunk6H5PTRZL_cjs.c}});
@@ -1 +0,0 @@
1
- 'use strict';var chunkYAF6HMAE_cjs=require('./chunk-YAF6HMAE.cjs');require('./chunk-7C2J2PDC.cjs'),require('./chunk-EKSLNNMF.cjs'),require('./chunk-AVECFV5K.cjs');var chunkNHRRIJFK_cjs=require('./chunk-NHRRIJFK.cjs');require('./chunk-GCVKM3RJ.cjs'),require('./chunk-KFESJR3T.cjs');async function f(t){let o=t.agentId,r=await chunkNHRRIJFK_cjs.d.getRootDir();return chunkYAF6HMAE_cjs.z("doctor",{},chunkYAF6HMAE_cjs.B(o,r))}function l(t){return ""}function g(t){let o={};for(let r=0;r<t.length;r++){let n=t[r];n!==void 0&&(n==="--repair"?o.repair=true:n==="--json"?o.json=true:(n==="--help"||n==="-h")&&(o.help=true));}return o}exports.formatDoctorText=l;exports.parseDoctorOptions=g;exports.runDoctor=f;
@@ -1 +0,0 @@
1
- 'use strict';var chunkDYD3SEPC_cjs=require('./chunk-DYD3SEPC.cjs');require('./chunk-YAF6HMAE.cjs'),require('./chunk-7C2J2PDC.cjs'),require('./chunk-EKSLNNMF.cjs'),require('./chunk-AVECFV5K.cjs'),require('./chunk-NHRRIJFK.cjs'),require('./chunk-GCVKM3RJ.cjs'),require('./chunk-KFESJR3T.cjs');Object.defineProperty(exports,"MemoryStdioServer",{enumerable:true,get:function(){return chunkDYD3SEPC_cjs.b}});