@easbot/memory 0.3.28 → 0.3.29

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 (92) hide show
  1. package/README.en.md +1 -1
  2. package/README.md +1 -1
  3. package/dist/chunks/chunk-3EENVVWK.cjs +67 -0
  4. package/dist/chunks/chunk-AJDMZTCQ.mjs +1 -0
  5. package/dist/chunks/chunk-AVECFV5K.cjs +1 -0
  6. package/dist/chunks/chunk-BYNUWUL2.cjs +77 -0
  7. package/dist/chunks/chunk-CIXJXCID.mjs +1 -0
  8. package/dist/chunks/chunk-CVS25NBK.mjs +77 -0
  9. package/dist/chunks/{chunk-P45OBSAC.cjs → chunk-DVZOWMF5.cjs} +19 -19
  10. package/dist/chunks/chunk-DWGCQLSH.mjs +1 -0
  11. package/dist/chunks/chunk-GHJLFUKH.cjs +1 -0
  12. package/dist/chunks/chunk-I5SOBIRK.cjs +1 -0
  13. package/dist/chunks/{chunk-I5YSX4DQ.mjs → chunk-NWY7CUSL.mjs} +19 -19
  14. package/dist/chunks/chunk-OOBYBPIN.mjs +67 -0
  15. package/dist/chunks/chunk-QJTEXVXX.mjs +1 -0
  16. package/dist/chunks/chunk-ZDTPURG4.cjs +1 -0
  17. package/dist/chunks/cli-handler-7KD65K5T.mjs +1 -0
  18. package/dist/chunks/cli-handler-L2HSWA2P.cjs +1 -0
  19. package/dist/chunks/consolidate-ANQFG7QD.mjs +2 -0
  20. package/dist/chunks/consolidate-GJPX4H7R.cjs +2 -0
  21. package/dist/chunks/doctor-4L2KSJXV.cjs +1 -0
  22. package/dist/chunks/doctor-CDS2OUAA.mjs +1 -0
  23. package/dist/chunks/extract-3MLEFVJV.cjs +2 -0
  24. package/dist/chunks/extract-V4BIBFW7.mjs +2 -0
  25. package/dist/chunks/forget-FG7ZFJL7.cjs +3 -0
  26. package/dist/chunks/forget-PQLRSYOJ.mjs +3 -0
  27. package/dist/chunks/graph-34HVP7TP.cjs +3 -0
  28. package/dist/chunks/graph-P6LEEEVA.mjs +3 -0
  29. package/dist/chunks/init-7SHKOGVZ.cjs +1 -0
  30. package/dist/chunks/init-TTINBBT4.mjs +1 -0
  31. package/dist/chunks/{interfaces-LPJU4KS3.mjs → interfaces-7TJ645HL.mjs} +1 -1
  32. package/dist/chunks/interfaces-BGC3V4WU.cjs +1 -0
  33. package/dist/chunks/llm-RSSNHF6T.cjs +1 -0
  34. package/dist/chunks/llm-XHWMIOUN.mjs +1 -0
  35. package/dist/chunks/mcp-7TMDANN6.cjs +1 -0
  36. package/dist/chunks/mcp-YNGRYILA.mjs +1 -0
  37. package/dist/chunks/recall-JIH4PAR5.mjs +2 -0
  38. package/dist/chunks/recall-TA4YPWD2.cjs +2 -0
  39. package/dist/chunks/remember-5JAWVMYX.cjs +2 -0
  40. package/dist/chunks/remember-KY4HDAE4.mjs +2 -0
  41. package/dist/chunks/status-QZ27UQJG.mjs +1 -0
  42. package/dist/chunks/status-YGRSKKZZ.cjs +1 -0
  43. package/dist/chunks/stdio-server-KEBLOUB2.cjs +1 -0
  44. package/dist/chunks/stdio-server-RTY5WYTU.mjs +1 -0
  45. package/dist/chunks/sync-D44EAJLK.mjs +2 -0
  46. package/dist/chunks/sync-SJI7PENR.cjs +2 -0
  47. package/dist/cli.cjs +1 -1
  48. package/dist/cli.mjs +1 -1
  49. package/dist/index.cjs +5 -5
  50. package/dist/index.d.cts +35 -8
  51. package/dist/index.d.ts +35 -8
  52. package/dist/index.mjs +5 -5
  53. package/package.json +9 -9
  54. package/dist/chunks/chunk-4YADRVIU.mjs +0 -1
  55. package/dist/chunks/chunk-6CQMBEIQ.mjs +0 -1
  56. package/dist/chunks/chunk-CPRDIUQ4.cjs +0 -1
  57. package/dist/chunks/chunk-DW3CJUBO.cjs +0 -1
  58. package/dist/chunks/chunk-FY4ILCIM.mjs +0 -77
  59. package/dist/chunks/chunk-HY2LFKG7.cjs +0 -67
  60. package/dist/chunks/chunk-J5XF2W4Z.cjs +0 -1
  61. package/dist/chunks/chunk-LYBUZDJK.cjs +0 -77
  62. package/dist/chunks/chunk-WDVDYZ25.mjs +0 -1
  63. package/dist/chunks/chunk-X7P7ZFZF.mjs +0 -67
  64. package/dist/chunks/cli-handler-ETHJPZPG.mjs +0 -1
  65. package/dist/chunks/cli-handler-PG4IBTY2.cjs +0 -1
  66. package/dist/chunks/consolidate-7GFUFPLX.cjs +0 -2
  67. package/dist/chunks/consolidate-BGMXJUQX.mjs +0 -2
  68. package/dist/chunks/doctor-C2FWFUDO.mjs +0 -1
  69. package/dist/chunks/doctor-SCXUJRSG.cjs +0 -1
  70. package/dist/chunks/extract-O4IOL6BZ.cjs +0 -2
  71. package/dist/chunks/extract-RBBSVK2S.mjs +0 -2
  72. package/dist/chunks/forget-JTACRG7Y.mjs +0 -3
  73. package/dist/chunks/forget-M4I6GVWI.cjs +0 -3
  74. package/dist/chunks/graph-AOMDJ6YA.cjs +0 -3
  75. package/dist/chunks/graph-VBVVRV6V.mjs +0 -3
  76. package/dist/chunks/init-2SBK7ZWO.mjs +0 -1
  77. package/dist/chunks/init-VTPJR56L.cjs +0 -1
  78. package/dist/chunks/interfaces-Q5OGU5EK.cjs +0 -1
  79. package/dist/chunks/llm-7LQGYSUE.cjs +0 -1
  80. package/dist/chunks/llm-UHTBU2HA.mjs +0 -1
  81. package/dist/chunks/mcp-VIOHPDO5.cjs +0 -1
  82. package/dist/chunks/mcp-ZQCLVZIR.mjs +0 -1
  83. package/dist/chunks/recall-JSTQDGGZ.cjs +0 -2
  84. package/dist/chunks/recall-UQSG6ECA.mjs +0 -2
  85. package/dist/chunks/remember-GVQJ5G7Z.mjs +0 -2
  86. package/dist/chunks/remember-Z4UJJN62.cjs +0 -2
  87. package/dist/chunks/status-DH33MQZV.cjs +0 -1
  88. package/dist/chunks/status-VZ5EBAOY.mjs +0 -1
  89. package/dist/chunks/stdio-server-JC53PUET.mjs +0 -1
  90. package/dist/chunks/stdio-server-OUZAN4IM.cjs +0 -1
  91. package/dist/chunks/sync-6I2ZJUH6.cjs +0 -2
  92. package/dist/chunks/sync-UT4D32ML.mjs +0 -2
package/dist/index.cjs CHANGED
@@ -1,6 +1,6 @@
1
- 'use strict';require('./chunks/chunk-URADAZYW.cjs');var chunkDW3CJUBO_cjs=require('./chunks/chunk-DW3CJUBO.cjs'),chunkP45OBSAC_cjs=require('./chunks/chunk-P45OBSAC.cjs'),chunkHY2LFKG7_cjs=require('./chunks/chunk-HY2LFKG7.cjs'),chunkLYBUZDJK_cjs=require('./chunks/chunk-LYBUZDJK.cjs'),chunkCPRDIUQ4_cjs=require('./chunks/chunk-CPRDIUQ4.cjs'),chunkJ5XF2W4Z_cjs=require('./chunks/chunk-J5XF2W4Z.cjs'),chunkM2YU5LAI_cjs=require('./chunks/chunk-M2YU5LAI.cjs'),types=require('@easbot/types'),d=require('jieba-wasm'),utils=require('@easbot/utils'),crypto=require('crypto');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 d__namespace=/*#__PURE__*/_interopNamespace(d);var Ae=["user_preference","task_context","technical_fact","decision","relationship","reminder","error_pattern","workflow","exploration_finding","experience_summary","tool_usage","skill_creation","test","other"],p=class extends Error{constructor(o,t,n){super(o,{cause:n});chunkM2YU5LAI_cjs.a(this,"code",t);chunkM2YU5LAI_cjs.a(this,"cause",n);this.name="MemoryError";}},N=class extends p{constructor(r,o){super(r,"MEMORY_VALIDATION_ERROR",o),this.name="MemoryValidationError";}},D=class extends p{constructor(r){super(`Memory not found: ${r}`,"MEMORY_NOT_FOUND"),this.name="MemoryNotFoundError";}},T=class extends p{constructor(r){super(r,"MEMORY_PERMISSION_ERROR"),this.name="MemoryPermissionError";}},v=class extends p{constructor(r,o){super(r,"MEMORY_DATABASE_ERROR",o),this.name="MemoryDatabaseError";}},F=class extends p{constructor(r,o){super(r,"MEMORY_FILE_ERROR",o),this.name="MemoryFileError";}},L=class extends p{constructor(r,o){super(r,"MEMORY_SEARCH_ERROR",o),this.name="MemorySearchError";}},$=class extends p{constructor(r,o){super(r,"MEMORY_EMBEDDING_ERROR",o),this.name="MemoryEmbeddingError";}},ue=(a=>(a.VALIDATION_ERROR="MEMORY_VALIDATION_ERROR",a.NOT_FOUND="MEMORY_NOT_FOUND",a.PERMISSION_ERROR="MEMORY_PERMISSION_ERROR",a.DATABASE_ERROR="MEMORY_DATABASE_ERROR",a.FILE_ERROR="MEMORY_FILE_ERROR",a.SEARCH_ERROR="MEMORY_SEARCH_ERROR",a.EMBEDDING_ERROR="MEMORY_EMBEDDING_ERROR",a))(ue||{});var s=utils.Log.create({service:"memory.tokenizer"}),l=false,Re=utils.loadTextFile("./assets/jieba_dict.txt",chunkM2YU5LAI_cjs.b);async function Le(e){if(!l)try{s.debug("Initializing jieba tokenizer");let r=Re();if(d__namespace.with_dict(r),s.debug("Built-in dictionary loaded"),e?.dictPath&&e.dictPath.length>0)for(let o of e.dictPath)await ke(o);l=!0,s.debug("Jieba tokenizer initialized successfully");}catch(r){s.error("Failed to initialize jieba tokenizer",{error:String(r)}),s.warn("Using fallback tokenization (space-based)");}}async function ke(e){if(!l)throw new Error("Tokenizer not initialized");try{let r=await utils.Filesystem.readText(e);s.debug("Loading custom dictionary",{dictPath:e}),d__namespace.with_dict(r),s.debug("Custom dictionary loaded successfully",{dictPath:e});}catch(r){s.warn("Failed to load custom dictionary",{dictPath:e,error:String(r)});}}function xe(e){if(!l)return e.split(/\s+/).filter(Boolean);try{return d__namespace.cut(e)}catch(r){return s.warn("Tokenization failed, using fallback",{error:String(r)}),e.split(/\s+/).filter(Boolean)}}function He(e){if(!l)return e.split(/\s+/).filter(Boolean);try{return d__namespace.cut_for_search(e)}catch(r){return s.warn("Tokenization for search failed, using fallback",{error:String(r)}),e.split(/\s+/).filter(Boolean)}}function $e(e,r,o){if(l)try{d__namespace.add_word(e,r,o),s.debug("Word added to dictionary",{word:e,freq:r,tag:o});}catch(t){s.warn("Failed to add word",{word:e,error:String(t)});}}function je(){return l}async function ze(){l=false,s.debug("Tokenizer closed");}function Ye(e){if(!l)return e.split(/\s+/).filter(Boolean).join(" ");try{return xe(e).join(" ")}catch(r){return s.warn("Tokenization failed, using fallback",{error:String(r)}),e.split(/\s+/).filter(Boolean).join(" ")}}function Be(e){if(!l)return e.split(/\s+/).filter(Boolean).join(" ");try{return He(e).join(" ")}catch(r){return s.warn("Tokenization for search failed, using fallback",{error:String(r)}),e.split(/\s+/).filter(Boolean).join(" ")}}function m(e){let r=chunkCPRDIUQ4_cjs.f().worktree,o=chunkCPRDIUQ4_cjs.j(r);return {agentId:e,isTrustedLocal:true,remote:false,locale:"en-US",dbPath:o,workspaceDir:r,rootDir:r,config:chunkHY2LFKG7_cjs.A({agentId:e,dbPath:o,workspaceDir:r})}}var j=async e=>{if(!e.agentId?.trim())return {ok:false,error:"session-start: agentId is required in ctx"};let r=e.extras?.topK??5,o=e.extras?.query??"";try{let t=await chunkHY2LFKG7_cjs.z("recall",{query:o,maxResults:r},m(e.agentId));if(t.hits.length===0)return {ok:!0,injected:"",logLine:"session-start: no facts found for agent; skipping context injection"};let n=t.hits.map(y=>`- [${y.category}/imp=${y.importance}] ${y.snippet.slice(0,200)}`);return {ok:!0,injected:`[memory:session-start recall top-${t.hits.length}]
1
+ 'use strict';require('./chunks/chunk-URADAZYW.cjs');var chunkI5SOBIRK_cjs=require('./chunks/chunk-I5SOBIRK.cjs'),chunkDVZOWMF5_cjs=require('./chunks/chunk-DVZOWMF5.cjs'),chunk3EENVVWK_cjs=require('./chunks/chunk-3EENVVWK.cjs'),chunkBYNUWUL2_cjs=require('./chunks/chunk-BYNUWUL2.cjs'),chunkGHJLFUKH_cjs=require('./chunks/chunk-GHJLFUKH.cjs'),chunkZDTPURG4_cjs=require('./chunks/chunk-ZDTPURG4.cjs'),chunkAVECFV5K_cjs=require('./chunks/chunk-AVECFV5K.cjs'),chunkM2YU5LAI_cjs=require('./chunks/chunk-M2YU5LAI.cjs'),types=require('@easbot/types'),m=require('jieba-wasm'),utils=require('@easbot/utils'),crypto=require('crypto');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 je=["user_preference","task_context","technical_fact","decision","relationship","reminder","error_pattern","workflow","exploration_finding","experience_summary","tool_usage","skill_creation","test","other"],p=class extends Error{constructor(t,o,n){super(t,{cause:n});chunkM2YU5LAI_cjs.a(this,"code",o);chunkM2YU5LAI_cjs.a(this,"cause",n);this.name="MemoryError";}},L=class extends p{constructor(r,t){super(r,"MEMORY_VALIDATION_ERROR",t),this.name="MemoryValidationError";}},F=class extends p{constructor(r){super(`Memory not found: ${r}`,"MEMORY_NOT_FOUND"),this.name="MemoryNotFoundError";}},$=class extends p{constructor(r){super(r,"MEMORY_PERMISSION_ERROR"),this.name="MemoryPermissionError";}},j=class extends p{constructor(r,t){super(r,"MEMORY_DATABASE_ERROR",t),this.name="MemoryDatabaseError";}},Y=class extends p{constructor(r,t){super(r,"MEMORY_FILE_ERROR",t),this.name="MemoryFileError";}},z=class extends p{constructor(r,t){super(r,"MEMORY_SEARCH_ERROR",t),this.name="MemorySearchError";}},B=class extends p{constructor(r,t){super(r,"MEMORY_EMBEDDING_ERROR",t),this.name="MemoryEmbeddingError";}},He=(a=>(a.VALIDATION_ERROR="MEMORY_VALIDATION_ERROR",a.NOT_FOUND="MEMORY_NOT_FOUND",a.PERMISSION_ERROR="MEMORY_PERMISSION_ERROR",a.DATABASE_ERROR="MEMORY_DATABASE_ERROR",a.FILE_ERROR="MEMORY_FILE_ERROR",a.SEARCH_ERROR="MEMORY_SEARCH_ERROR",a.EMBEDDING_ERROR="MEMORY_EMBEDDING_ERROR",a))(He||{});var s=utils.Log.create({service:"memory.tokenizer"}),l=false,Ie=utils.loadTextFile("./assets/jieba_dict.txt",chunkM2YU5LAI_cjs.b);async function We(e){if(!l)try{s.debug("Initializing jieba tokenizer");let r=Ie();if(m__namespace.with_dict(r),s.debug("Built-in dictionary loaded"),e?.dictPath&&e.dictPath.length>0)for(let t of e.dictPath)await _e(t);l=!0,s.debug("Jieba tokenizer initialized successfully");}catch(r){s.error("Failed to initialize jieba tokenizer",{error:utils.errorMeta(r)}),s.warn("Using fallback tokenization (space-based)");}}async function _e(e){if(!l)throw new chunkAVECFV5K_cjs.a.TokenizerNotInitializedError({message:"Tokenizer not initialized"});try{let r=await utils.Filesystem.readText(e);s.debug("Loading custom dictionary",{dictPath:e}),m__namespace.with_dict(r),s.debug("Custom dictionary loaded successfully",{dictPath:e});}catch(r){s.warn("Failed to load custom dictionary",{dictPath:e,error:utils.errorMeta(r)});}}function be(e){if(!l)return e.split(/\s+/).filter(Boolean);try{return m__namespace.cut(e)}catch(r){return s.warn("Tokenization failed, using fallback",{error:utils.errorMeta(r)}),e.split(/\s+/).filter(Boolean)}}function Oe(e){if(!l)return e.split(/\s+/).filter(Boolean);try{return m__namespace.cut_for_search(e)}catch(r){return s.warn("Tokenization for search failed, using fallback",{error:utils.errorMeta(r)}),e.split(/\s+/).filter(Boolean)}}function Ve(e,r,t){if(l)try{m__namespace.add_word(e,r,t),s.debug("Word added to dictionary",{word:e,freq:r,tag:t});}catch(o){s.warn("Failed to add word",{word:e,error:utils.errorMeta(o)});}}function Xe(){return l}async function Ze(){l=false,s.debug("Tokenizer closed");}function er(e){if(!l)return e.split(/\s+/).filter(Boolean).join(" ");try{return be(e).join(" ")}catch(r){return s.warn("Tokenization failed, using fallback",{error:utils.errorMeta(r)}),e.split(/\s+/).filter(Boolean).join(" ")}}function rr(e){if(!l)return e.split(/\s+/).filter(Boolean).join(" ");try{return Oe(e).join(" ")}catch(r){return s.warn("Tokenization for search failed, using fallback",{error:utils.errorMeta(r)}),e.split(/\s+/).filter(Boolean).join(" ")}}function d(e){let r=chunkGHJLFUKH_cjs.f().worktree,t=chunkGHJLFUKH_cjs.j(r);return {agentId:e,isTrustedLocal:true,remote:false,locale:"en-US",dbPath:t,workspaceDir:r,rootDir:r,config:chunk3EENVVWK_cjs.A({agentId:e,dbPath:t,workspaceDir:r})}}var G=async e=>{if(!e.agentId?.trim())return {ok:false,error:"session-start: agentId is required in ctx"};let r=e.extras?.topK??5,t=e.extras?.query??"";try{let o=await chunk3EENVVWK_cjs.z("recall",{query:t,maxResults:r},d(e.agentId));if(o.hits.length===0)return {ok:!0,injected:"",logLine:"session-start: no facts found for agent; skipping context injection"};let n=o.hits.map(R=>`- [${R.category}/imp=${R.importance}] ${R.snippet.slice(0,200)}`);return {ok:!0,injected:`[memory:session-start recall top-${o.hits.length}]
2
2
  ${n.join(`
3
- `)}`,logLine:`session-start: injected ${t.hits.length} facts into context (agent=${e.agentId})`}}catch(t){return {ok:false,error:t instanceof Error?t.message:String(t)}}};var he=3600*1e3,z=async e=>{if(!e.agentId?.trim())return {ok:false,error:"session-end: agentId is required in ctx"};let r=typeof e.extras?.lookbackMs=="number"&&e.extras.lookbackMs>0?e.extras.lookbackMs:he,o=e.extras?.fromTime??new Date(Date.now()-r).toISOString();try{let t=await chunkHY2LFKG7_cjs.z("consolidate",{fromTime:o},m(e.agentId));return {ok:!0,logLine:`session-end: lookback=${r}ms, total=${t.totalFacts}, deduped=${t.dedupedCount}, archived=${t.archivedCount}, skipped=${t.skippedCount}`}}catch(t){return {ok:false,error:t instanceof Error?t.message:String(t)}}};var Y=async e=>{if(!e.agentId?.trim())return {ok:false,error:"pre-compact: agentId is required in ctx"};let o=(e.contextPreview??e.messagePreview??"").slice(0,200).replace(/\s+/g," ").trim(),t=e.extras?.topK??3;if(!o)return {ok:true,injected:"",logLine:"pre-compact: empty contextPreview; skipping recall injection"};try{let n=await chunkHY2LFKG7_cjs.z("recall",{query:o,maxResults:t,minImportance:5},m(e.agentId));if(n.hits.length===0)return {ok:!0,injected:"",logLine:`pre-compact: no facts matched query for agent=${e.agentId}`};let H=n.hits.map(a=>`- [${a.category}/imp=${a.importance}] ${a.snippet.slice(0,150)}`);return {ok:!0,injected:`[memory:pre-compact recall top-${n.hits.length} (imp>=5)]
4
- ${H.join(`
5
- `)}`,logLine:`pre-compact: injected ${n.hits.length} facts before compaction`}}catch(n){return {ok:false,error:n instanceof Error?n.message:String(n)}}};var B=async e=>{if(!e.agentId?.trim())return {ok:false,error:"post-tool-failure: agentId is required in ctx"};if(!e.toolName?.trim()||!e.error?.trim())return {ok:false,error:"post-tool-failure: toolName and error are required in ctx"};let r=crypto.createHash("sha256").update(`${e.toolName}:${e.error}`).digest("hex").slice(0,8),o=e.messagePreview?e.messagePreview.slice(0,200).replace(/\s+/g," ").trim():"",t=[`[error_pattern] tool=${e.toolName}`,`[error] ${e.error}`,o?`[preview] ${o}`:"",`[errHash] ${r}`].filter(Boolean).join(`
6
- `);try{return {ok:!0,logLine:`post-tool-failure: wrote error_pattern fact ${(await chunkHY2LFKG7_cjs.z("remember",{content:t,category:"error_pattern",importance:6,tags:["post-tool-failure",`tool:${e.toolName}`,`err:${r}`],sessionId:e.sessionId,msgId:e.extras?.msgId},m(e.agentId))).fact.id} (tool=${e.toolName}, errHash=${r})`}}catch(n){return {ok:false,error:n instanceof Error?n.message:String(n)}}};var u=utils.Log.create({service:"memory.hooks"}),g=new Map;function f(e,r){let o={name:e,handler:r,registeredAt:new Date().toISOString()},t=g.get(e);g.set(e,o),t?u.info("Hook overwritten",{name:e,prevRegisteredAt:t.registeredAt,newRegisteredAt:o.registeredAt}):u.info("Hook registered",{name:e,registeredAt:o.registeredAt});}function Ie(e){return g.delete(e)}function Me(){return Array.from(g.values()).map(e=>({name:e.name,handler:e.handler,registeredAt:e.registeredAt}))}function _e(){f("session-start",j),f("session-end",z),f("pre-compact",Y),f("post-tool-failure",B);}function Se(){g.clear(),u.debug("All hooks cleared");}async function Oe(e,r){let o=g.get(e);if(!o)return u.debug("dispatchHook: no handler registered; noop",{name:e}),{ok:true,logLine:`hook ${e} not registered; noop`};try{let t=await o.handler(r);return t.ok?t.logLine&&u.debug("dispatchHook: ok",{name:e,logLine:t.logLine}):u.warn("dispatchHook: handler returned failure",{name:e,agentId:r.agentId,error:t.error}),t}catch(t){let n=t instanceof Error?t.message:String(t);return u.warn("dispatchHook: handler threw, caught and converted to failure result",{name:e,agentId:r.agentId,error:n}),{ok:false,error:n}}}Object.defineProperty(exports,"COMMANDS_HELP",{enumerable:true,get:function(){return chunkDW3CJUBO_cjs.a}});Object.defineProperty(exports,"handleMemoryCli",{enumerable:true,get:function(){return chunkDW3CJUBO_cjs.d}});Object.defineProperty(exports,"renderBanner",{enumerable:true,get:function(){return chunkDW3CJUBO_cjs.b}});Object.defineProperty(exports,"renderHelp",{enumerable:true,get:function(){return chunkDW3CJUBO_cjs.c}});Object.defineProperty(exports,"MemoryStdioServer",{enumerable:true,get:function(){return chunkP45OBSAC_cjs.b}});Object.defineProperty(exports,"renderOperationMarkdown",{enumerable:true,get:function(){return chunkP45OBSAC_cjs.a}});Object.defineProperty(exports,"ALL_OPS",{enumerable:true,get:function(){return chunkHY2LFKG7_cjs.y}});Object.defineProperty(exports,"GraphStore",{enumerable:true,get:function(){return chunkHY2LFKG7_cjs.a}});Object.defineProperty(exports,"OP_REGISTRY",{enumerable:true,get:function(){return chunkHY2LFKG7_cjs.x}});Object.defineProperty(exports,"consolidate",{enumerable:true,get:function(){return chunkHY2LFKG7_cjs.r}});Object.defineProperty(exports,"doctor",{enumerable:true,get:function(){return chunkHY2LFKG7_cjs.w}});Object.defineProperty(exports,"executeOp",{enumerable:true,get:function(){return chunkHY2LFKG7_cjs.z}});Object.defineProperty(exports,"extract",{enumerable:true,get:function(){return chunkHY2LFKG7_cjs.q}});Object.defineProperty(exports,"forget",{enumerable:true,get:function(){return chunkHY2LFKG7_cjs.p}});Object.defineProperty(exports,"graphQuery",{enumerable:true,get:function(){return chunkHY2LFKG7_cjs.t}});Object.defineProperty(exports,"init",{enumerable:true,get:function(){return chunkHY2LFKG7_cjs.u}});Object.defineProperty(exports,"recall",{enumerable:true,get:function(){return chunkHY2LFKG7_cjs.b}});Object.defineProperty(exports,"remember",{enumerable:true,get:function(){return chunkHY2LFKG7_cjs.n}});Object.defineProperty(exports,"status",{enumerable:true,get:function(){return chunkHY2LFKG7_cjs.v}});Object.defineProperty(exports,"sync",{enumerable:true,get:function(){return chunkHY2LFKG7_cjs.s}});Object.defineProperty(exports,"update",{enumerable:true,get:function(){return chunkHY2LFKG7_cjs.o}});Object.defineProperty(exports,"LATEST_SCHEMA_VERSION",{enumerable:true,get:function(){return chunkLYBUZDJK_cjs.a}});Object.defineProperty(exports,"MIGRATIONS",{enumerable:true,get:function(){return chunkLYBUZDJK_cjs.b}});Object.defineProperty(exports,"MemoryDatabaseManager",{enumerable:true,get:function(){return chunkLYBUZDJK_cjs.e}});Object.defineProperty(exports,"readCurrentSchemaVersion",{enumerable:true,get:function(){return chunkLYBUZDJK_cjs.d}});Object.defineProperty(exports,"runMigrations",{enumerable:true,get:function(){return chunkLYBUZDJK_cjs.c}});Object.defineProperty(exports,"getGlobal",{enumerable:true,get:function(){return chunkCPRDIUQ4_cjs.c}});Object.defineProperty(exports,"getHomeDir",{enumerable:true,get:function(){return chunkCPRDIUQ4_cjs.g}});Object.defineProperty(exports,"getInstance",{enumerable:true,get:function(){return chunkCPRDIUQ4_cjs.f}});Object.defineProperty(exports,"getMemoryDbPath",{enumerable:true,get:function(){return chunkCPRDIUQ4_cjs.j}});Object.defineProperty(exports,"getMemoryDir",{enumerable:true,get:function(){return chunkCPRDIUQ4_cjs.i}});Object.defineProperty(exports,"getXdgData",{enumerable:true,get:function(){return chunkCPRDIUQ4_cjs.h}});Object.defineProperty(exports,"resetGlobalAdapter",{enumerable:true,get:function(){return chunkCPRDIUQ4_cjs.b}});Object.defineProperty(exports,"resetInstanceAdapter",{enumerable:true,get:function(){return chunkCPRDIUQ4_cjs.e}});Object.defineProperty(exports,"setGlobalAdapter",{enumerable:true,get:function(){return chunkCPRDIUQ4_cjs.a}});Object.defineProperty(exports,"setInstanceAdapter",{enumerable:true,get:function(){return chunkCPRDIUQ4_cjs.d}});Object.defineProperty(exports,"Llm",{enumerable:true,get:function(){return chunkJ5XF2W4Z_cjs.a}});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=Ae;exports.MemoryDatabaseError=v;exports.MemoryEmbeddingError=$;exports.MemoryError=p;exports.MemoryErrorCode=ue;exports.MemoryFileError=F;exports.MemoryNotFoundError=D;exports.MemoryPermissionError=T;exports.MemorySearchError=L;exports.MemoryValidationError=N;exports.addWord=$e;exports.clearAllHooks=Se;exports.closeTokenizer=ze;exports.dispatchHook=Oe;exports.initTokenizer=Le;exports.isInitialized=je;exports.listHooks=Me;exports.loadCustomDict=ke;exports.registerAllDefaultHooks=_e;exports.registerHook=f;exports.toFtsTokens=Ye;exports.toFtsTokensForSearch=Be;exports.tokenize=xe;exports.tokenizeForSearch=He;exports.unregisterHook=Ie;
3
+ `)}`,logLine:`session-start: injected ${o.hits.length} facts into context (agent=${e.agentId})`}}catch(o){return {ok:false,error:utils.errorMeta(o).message}}};var we=3600*1e3,K=async e=>{if(!e.agentId?.trim())return {ok:false,error:"session-end: agentId is required in ctx"};let r=typeof e.extras?.lookbackMs=="number"&&e.extras.lookbackMs>0?e.extras.lookbackMs:we,t=e.extras?.fromTime??new Date(Date.now()-r).toISOString();try{let o=await chunk3EENVVWK_cjs.z("consolidate",{fromTime:t},d(e.agentId));return {ok:!0,logLine:`session-end: lookback=${r}ms, total=${o.totalFacts}, deduped=${o.dedupedCount}, archived=${o.archivedCount}, skipped=${o.skippedCount}`}}catch(o){return {ok:false,error:utils.errorMeta(o).message}}};var U=async e=>{if(!e.agentId?.trim())return {ok:false,error:"pre-compact: agentId is required in ctx"};let t=(e.contextPreview??e.messagePreview??"").slice(0,200).replace(/\s+/g," ").trim(),o=e.extras?.topK??3;if(!t)return {ok:true,injected:"",logLine:"pre-compact: empty contextPreview; skipping recall injection"};try{let n=await chunk3EENVVWK_cjs.z("recall",{query:t,maxResults:o,minImportance:5},d(e.agentId));if(n.hits.length===0)return {ok:!0,injected:"",logLine:`pre-compact: no facts matched query for agent=${e.agentId}`};let h=n.hits.map(a=>`- [${a.category}/imp=${a.importance}] ${a.snippet.slice(0,150)}`);return {ok:!0,injected:`[memory:pre-compact recall top-${n.hits.length} (imp>=5)]
4
+ ${h.join(`
5
+ `)}`,logLine:`pre-compact: injected ${n.hits.length} facts before compaction`}}catch(n){return {ok:false,error:utils.errorMeta(n).message}}};var q=async e=>{if(!e.agentId?.trim())return {ok:false,error:"post-tool-failure: agentId is required in ctx"};if(!e.toolName?.trim()||!e.error?.trim())return {ok:false,error:"post-tool-failure: toolName and error are required in ctx"};let r=crypto.createHash("sha256").update(`${e.toolName}:${e.error}`).digest("hex").slice(0,8),t=e.messagePreview?e.messagePreview.slice(0,200).replace(/\s+/g," ").trim():"",o=[`[error_pattern] tool=${e.toolName}`,`[error] ${e.error}`,t?`[preview] ${t}`:"",`[errHash] ${r}`].filter(Boolean).join(`
6
+ `);try{return {ok:!0,logLine:`post-tool-failure: wrote error_pattern fact ${(await chunk3EENVVWK_cjs.z("remember",{content:o,category:"error_pattern",importance:6,tags:["post-tool-failure",`tool:${e.toolName}`,`err:${r}`],sessionId:e.sessionId,msgId:e.extras?.msgId},d(e.agentId))).fact.id} (tool=${e.toolName}, errHash=${r})`}}catch(n){return {ok:false,error:utils.errorMeta(n).message}}};var g=utils.Log.create({service:"memory.hooks"}),f=new Map;function y(e,r){let t={name:e,handler:r,registeredAt:new Date().toISOString()},o=f.get(e);f.set(e,t),o?g.info("Hook overwritten",{name:e,prevRegisteredAt:o.registeredAt,newRegisteredAt:t.registeredAt}):g.info("Hook registered",{name:e,registeredAt:t.registeredAt});}function De(e){return f.delete(e)}function ve(){return Array.from(f.values()).map(e=>({name:e.name,handler:e.handler,registeredAt:e.registeredAt}))}function Le(){y("session-start",G),y("session-end",K),y("pre-compact",U),y("post-tool-failure",q);}function Fe(){f.clear(),g.debug("All hooks cleared");}async function $e(e,r){let t=f.get(e);if(!t)return g.debug("dispatchHook: no handler registered; noop",{name:e}),{ok:true,logLine:`hook ${e} not registered; noop`};try{let o=await t.handler(r);return o.ok?o.logLine&&g.debug("dispatchHook: ok",{name:e,logLine:o.logLine}):g.warn("dispatchHook: handler returned failure",{name:e,agentId:r.agentId,error:o.error}),o}catch(o){let n=utils.errorMeta(o).message;return g.warn("dispatchHook: handler threw, caught and converted to failure result",{name:e,agentId:r.agentId,error:utils.errorMeta(o)}),{ok:false,error:n}}}Object.defineProperty(exports,"COMMANDS_HELP",{enumerable:true,get:function(){return chunkI5SOBIRK_cjs.a}});Object.defineProperty(exports,"handleMemoryCli",{enumerable:true,get:function(){return chunkI5SOBIRK_cjs.d}});Object.defineProperty(exports,"renderBanner",{enumerable:true,get:function(){return chunkI5SOBIRK_cjs.b}});Object.defineProperty(exports,"renderHelp",{enumerable:true,get:function(){return chunkI5SOBIRK_cjs.c}});Object.defineProperty(exports,"MemoryStdioServer",{enumerable:true,get:function(){return chunkDVZOWMF5_cjs.b}});Object.defineProperty(exports,"renderOperationMarkdown",{enumerable:true,get:function(){return chunkDVZOWMF5_cjs.a}});Object.defineProperty(exports,"ALL_OPS",{enumerable:true,get:function(){return chunk3EENVVWK_cjs.y}});Object.defineProperty(exports,"GraphStore",{enumerable:true,get:function(){return chunk3EENVVWK_cjs.a}});Object.defineProperty(exports,"OP_REGISTRY",{enumerable:true,get:function(){return chunk3EENVVWK_cjs.x}});Object.defineProperty(exports,"consolidate",{enumerable:true,get:function(){return chunk3EENVVWK_cjs.r}});Object.defineProperty(exports,"doctor",{enumerable:true,get:function(){return chunk3EENVVWK_cjs.v}});Object.defineProperty(exports,"executeOp",{enumerable:true,get:function(){return chunk3EENVVWK_cjs.z}});Object.defineProperty(exports,"extract",{enumerable:true,get:function(){return chunk3EENVVWK_cjs.q}});Object.defineProperty(exports,"forget",{enumerable:true,get:function(){return chunk3EENVVWK_cjs.p}});Object.defineProperty(exports,"graphQuery",{enumerable:true,get:function(){return chunk3EENVVWK_cjs.t}});Object.defineProperty(exports,"init",{enumerable:true,get:function(){return chunk3EENVVWK_cjs.w}});Object.defineProperty(exports,"recall",{enumerable:true,get:function(){return chunk3EENVVWK_cjs.b}});Object.defineProperty(exports,"remember",{enumerable:true,get:function(){return chunk3EENVVWK_cjs.n}});Object.defineProperty(exports,"status",{enumerable:true,get:function(){return chunk3EENVVWK_cjs.u}});Object.defineProperty(exports,"sync",{enumerable:true,get:function(){return chunk3EENVVWK_cjs.s}});Object.defineProperty(exports,"update",{enumerable:true,get:function(){return chunk3EENVVWK_cjs.o}});Object.defineProperty(exports,"DEFAULT_MEMORY_JSON",{enumerable:true,get:function(){return chunkBYNUWUL2_cjs.g}});Object.defineProperty(exports,"LATEST_SCHEMA_VERSION",{enumerable:true,get:function(){return chunkBYNUWUL2_cjs.a}});Object.defineProperty(exports,"MEMORY_JSON_REL_PATH",{enumerable:true,get:function(){return chunkBYNUWUL2_cjs.h}});Object.defineProperty(exports,"MIGRATIONS",{enumerable:true,get:function(){return chunkBYNUWUL2_cjs.b}});Object.defineProperty(exports,"MemoryCache",{enumerable:true,get:function(){return chunkBYNUWUL2_cjs.i}});Object.defineProperty(exports,"MemoryDatabaseManager",{enumerable:true,get:function(){return chunkBYNUWUL2_cjs.e}});Object.defineProperty(exports,"MemoryJsonSchema",{enumerable:true,get:function(){return chunkBYNUWUL2_cjs.f}});Object.defineProperty(exports,"readCurrentSchemaVersion",{enumerable:true,get:function(){return chunkBYNUWUL2_cjs.d}});Object.defineProperty(exports,"runMigrations",{enumerable:true,get:function(){return chunkBYNUWUL2_cjs.c}});Object.defineProperty(exports,"getGlobal",{enumerable:true,get:function(){return chunkGHJLFUKH_cjs.c}});Object.defineProperty(exports,"getHomeDir",{enumerable:true,get:function(){return chunkGHJLFUKH_cjs.g}});Object.defineProperty(exports,"getInstance",{enumerable:true,get:function(){return chunkGHJLFUKH_cjs.f}});Object.defineProperty(exports,"getMemoryDbPath",{enumerable:true,get:function(){return chunkGHJLFUKH_cjs.j}});Object.defineProperty(exports,"getMemoryDir",{enumerable:true,get:function(){return chunkGHJLFUKH_cjs.i}});Object.defineProperty(exports,"getXdgData",{enumerable:true,get:function(){return chunkGHJLFUKH_cjs.h}});Object.defineProperty(exports,"resetGlobalAdapter",{enumerable:true,get:function(){return chunkGHJLFUKH_cjs.b}});Object.defineProperty(exports,"resetInstanceAdapter",{enumerable:true,get:function(){return chunkGHJLFUKH_cjs.e}});Object.defineProperty(exports,"setGlobalAdapter",{enumerable:true,get:function(){return chunkGHJLFUKH_cjs.a}});Object.defineProperty(exports,"setInstanceAdapter",{enumerable:true,get:function(){return chunkGHJLFUKH_cjs.d}});Object.defineProperty(exports,"Llm",{enumerable:true,get:function(){return chunkZDTPURG4_cjs.a}});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=je;exports.MemoryDatabaseError=j;exports.MemoryEmbeddingError=B;exports.MemoryError=p;exports.MemoryErrorCode=He;exports.MemoryFileError=Y;exports.MemoryNotFoundError=F;exports.MemoryPermissionError=$;exports.MemorySearchError=z;exports.MemoryValidationError=L;exports.addWord=Ve;exports.clearAllHooks=Fe;exports.closeTokenizer=Ze;exports.dispatchHook=$e;exports.initTokenizer=We;exports.isInitialized=Xe;exports.listHooks=ve;exports.loadCustomDict=_e;exports.registerAllDefaultHooks=Le;exports.registerHook=y;exports.toFtsTokens=er;exports.toFtsTokensForSearch=rr;exports.tokenize=be;exports.tokenizeForSearch=Oe;exports.unregisterHook=De;
package/dist/index.d.cts CHANGED
@@ -3,10 +3,25 @@ export { GRAPH_ENTITY_TYPE_DEFINITIONS, GRAPH_RELATION_TYPE_DEFINITIONS } from '
3
3
  import { EmbeddingModel, LanguageModel } from 'ai';
4
4
  export { EmbeddingModel, LanguageModel } from 'ai';
5
5
  import { ILLMInitConfig, ILLMCapabilities } from '@easbot/llm';
6
- import { ZodTypeAny } from 'zod';
6
+ import { z, ZodTypeAny } from 'zod';
7
7
  import { StdioServerConfig } from '@easbot/mcp';
8
8
  import { SyncSqliteConnection } from '@easbot/database';
9
9
 
10
+ declare const MemoryJsonSchema: z.ZodObject<{
11
+ version: z.ZodOptional<z.ZodLiteral<1>>;
12
+ schema_version: z.ZodOptional<z.ZodNumber>;
13
+ extraction_version: z.ZodOptional<z.ZodNumber>;
14
+ index_state: z.ZodOptional<z.ZodString>;
15
+ backend: z.ZodOptional<z.ZodString>;
16
+ created_at: z.ZodOptional<z.ZodString>;
17
+ embedding_model: z.ZodOptional<z.ZodNullable<z.ZodString>>;
18
+ graph_model: z.ZodOptional<z.ZodNullable<z.ZodString>>;
19
+ archive_days: z.ZodOptional<z.ZodNumber>;
20
+ short_term_max_rounds: z.ZodOptional<z.ZodNumber>;
21
+ }, z.core.$loose>;
22
+ type MemoryJson = z.infer<typeof MemoryJsonSchema>;
23
+ declare const DEFAULT_MEMORY_JSON: MemoryJson;
24
+
10
25
  type MemoryCategory = 'user_preference' | 'task_context' | 'technical_fact' | 'decision' | 'relationship' | 'reminder' | 'error_pattern' | 'workflow' | 'exploration_finding' | 'experience_summary' | 'tool_usage' | 'skill_creation' | 'test' | 'other';
11
26
  declare const MEMORY_CATEGORIES: MemoryCategory[];
12
27
  type MemorySource = 'session_self_write' | 'historical';
@@ -198,7 +213,6 @@ interface MemoryServiceContext {
198
213
  config?: MemoryKnowledgeConfigWithModels;
199
214
  agentId?: string;
200
215
  }
201
- type ErrorCode = 'AGENT_ID_REQUIRED' | 'SESSION_ID_REQUIRED' | 'CONTENT_REQUIRED' | 'INTERNAL' | 'NOT_FOUND' | 'AMBIGUOUS' | 'NOT_INDEXED' | 'OPTIONAL_DEP_MISSING' | 'TRUST_DENIED' | 'PATH_TRAVERSAL' | 'CATEGORY_REQUIRED' | 'IMPORTANCE_REQUIRED' | 'TIMERANGE_REQUIRED' | 'INGEST_FAILED' | 'UNSUPPORTED_FORMAT' | 'HAS_REFERENCES' | 'DRY_RUN_NO_DELETE' | 'MAX_DELETE_EXCEEDED' | 'JOB_NOT_FOUND' | 'JOB_TIMEOUT' | 'JOB_FAILED';
202
216
  type KGScope = 'agent_only' | 'shared_only' | 'both';
203
217
  interface RecallParams {
204
218
  query: string;
@@ -369,7 +383,6 @@ interface DoctorResult extends KnowledgeDoctorResult {
369
383
  }
370
384
  interface InitParams {
371
385
  dbPath?: string;
372
- workspaceDir?: string;
373
386
  archiveDays?: number;
374
387
  force?: boolean;
375
388
  }
@@ -537,10 +550,7 @@ declare function getInstance(): IInstance;
537
550
  declare function getHomeDir(): string;
538
551
  declare function getXdgData(): string;
539
552
  declare function getMemoryDir(): string;
540
- declare function getMemoryDbPath(input?: string | {
541
- dir?: string;
542
- workspaceDir?: string;
543
- }): string;
553
+ declare function getMemoryDbPath(workspaceDir: string): string;
544
554
 
545
555
  type MigrationDb = SyncSqliteConnection;
546
556
  declare const LATEST_SCHEMA_VERSION = 1;
@@ -661,4 +671,21 @@ declare function registerAllDefaultHooks(): void;
661
671
  declare function clearAllHooks(): void;
662
672
  declare function dispatchHook(name: HookName, ctx: HookContext): Promise<HookResult>;
663
673
 
664
- export { ALL_OPS, type ArchiveRecord, type ArchiveResult, COMMANDS_HELP, type CommandHelp, type ConsolidateParams, type ConsolidateResult, type DoctorResult, type EdgeQueryFilter, type ErrorCode, type ExtractParams, type ExtractResult, type ForgetParams, type ForgetResult, type GraphQueryParams, type GraphQueryResult, GraphStore, type HookContext, type HookHandler, type HookName, type HookResult, type InitParams, type InitResult, type KGScope, LATEST_SCHEMA_VERSION, Llm, type LlmInitConfig, type LlmModels, MEMORY_CATEGORIES, MIGRATIONS, type MemoryCategory, type MemoryCliDeps, type MemoryCliResult, MemoryDatabaseError, MemoryDatabaseManager, type MemoryEdge, MemoryEmbeddingError, MemoryError, MemoryErrorCode, type MemoryFact, MemoryFileError, type MemoryNode, type MemoryNodeWithEdges, MemoryNotFoundError, type MemoryOp, MemoryPermissionError, type MemoryQuery, type MemoryRecallResult, MemorySearchError, type MemorySource, MemoryStdioServer, type MemorySystemConfig, MemoryValidationError, type MemoryVector, type NodeQueryFilter, OP_REGISTRY, type OpAnnotations, type OpHandlerContext, type OpScope, type RecallParams, type RecallResult, type RegisteredHook, type RememberParams, type RememberResult, type StatusResult, type SyncParams, type SyncResult, type UpdateParams, type UpdateResult, addWord, clearAllHooks, closeTokenizer, consolidate, dispatchHook, doctor, executeOp, extract, forget, getGlobal, getHomeDir, getInstance, getMemoryDbPath, getMemoryDir, getXdgData, graphQuery, handleMemoryCli, init, initTokenizer, isInitialized, listHooks, loadCustomDict, readCurrentSchemaVersion, recall, registerAllDefaultHooks, registerHook, remember, renderBanner, renderHelp, renderOperationMarkdown, resetGlobalAdapter, resetInstanceAdapter, runMigrations, setGlobalAdapter, setInstanceAdapter, status, sync, toFtsTokens, toFtsTokensForSearch, tokenize, tokenizeForSearch, unregisterHook, update };
674
+ declare const MEMORY_JSON_REL_PATH: readonly [".easbot", "memory.json"];
675
+ type StateResult = {
676
+ memoryJson: MemoryJson | undefined;
677
+ exists: boolean;
678
+ rootDir: string;
679
+ };
680
+ declare namespace MemoryCache {
681
+ function state(): Promise<StateResult>;
682
+ function resetState(): void;
683
+ function init(): Promise<void>;
684
+ function getMemoryJson(): Promise<MemoryJson | undefined>;
685
+ function exists(): Promise<boolean>;
686
+ function getRootDir(): Promise<string>;
687
+ function writeMemoryJson(partial: Partial<MemoryJson>): Promise<MemoryJson>;
688
+ function getConfigPath(): Promise<string>;
689
+ }
690
+
691
+ 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 HookContext, type HookHandler, type HookName, type HookResult, 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, MemoryDatabaseError, MemoryDatabaseManager, type MemoryEdge, MemoryEmbeddingError, MemoryError, MemoryErrorCode, type MemoryFact, MemoryFileError, type MemoryJson, MemoryJsonSchema, type MemoryNode, type MemoryNodeWithEdges, MemoryNotFoundError, type MemoryOp, MemoryPermissionError, type MemoryQuery, type MemoryRecallResult, MemorySearchError, type MemorySource, MemoryStdioServer, type MemorySystemConfig, MemoryValidationError, type MemoryVector, type NodeQueryFilter, OP_REGISTRY, type OpAnnotations, type OpHandlerContext, type OpScope, type RecallParams, type RecallResult, type RegisteredHook, type RememberParams, type RememberResult, type StatusResult, type SyncParams, type SyncResult, type UpdateParams, type UpdateResult, addWord, clearAllHooks, closeTokenizer, consolidate, dispatchHook, doctor, executeOp, extract, forget, getGlobal, getHomeDir, getInstance, getMemoryDbPath, getMemoryDir, getXdgData, graphQuery, handleMemoryCli, init, initTokenizer, isInitialized, listHooks, loadCustomDict, readCurrentSchemaVersion, recall, registerAllDefaultHooks, registerHook, remember, renderBanner, renderHelp, renderOperationMarkdown, resetGlobalAdapter, resetInstanceAdapter, runMigrations, setGlobalAdapter, setInstanceAdapter, status, sync, toFtsTokens, toFtsTokensForSearch, tokenize, tokenizeForSearch, unregisterHook, update };
package/dist/index.d.ts CHANGED
@@ -3,10 +3,25 @@ export { GRAPH_ENTITY_TYPE_DEFINITIONS, GRAPH_RELATION_TYPE_DEFINITIONS } from '
3
3
  import { EmbeddingModel, LanguageModel } from 'ai';
4
4
  export { EmbeddingModel, LanguageModel } from 'ai';
5
5
  import { ILLMInitConfig, ILLMCapabilities } from '@easbot/llm';
6
- import { ZodTypeAny } from 'zod';
6
+ import { z, ZodTypeAny } from 'zod';
7
7
  import { StdioServerConfig } from '@easbot/mcp';
8
8
  import { SyncSqliteConnection } from '@easbot/database';
9
9
 
10
+ declare const MemoryJsonSchema: z.ZodObject<{
11
+ version: z.ZodOptional<z.ZodLiteral<1>>;
12
+ schema_version: z.ZodOptional<z.ZodNumber>;
13
+ extraction_version: z.ZodOptional<z.ZodNumber>;
14
+ index_state: z.ZodOptional<z.ZodString>;
15
+ backend: z.ZodOptional<z.ZodString>;
16
+ created_at: z.ZodOptional<z.ZodString>;
17
+ embedding_model: z.ZodOptional<z.ZodNullable<z.ZodString>>;
18
+ graph_model: z.ZodOptional<z.ZodNullable<z.ZodString>>;
19
+ archive_days: z.ZodOptional<z.ZodNumber>;
20
+ short_term_max_rounds: z.ZodOptional<z.ZodNumber>;
21
+ }, z.core.$loose>;
22
+ type MemoryJson = z.infer<typeof MemoryJsonSchema>;
23
+ declare const DEFAULT_MEMORY_JSON: MemoryJson;
24
+
10
25
  type MemoryCategory = 'user_preference' | 'task_context' | 'technical_fact' | 'decision' | 'relationship' | 'reminder' | 'error_pattern' | 'workflow' | 'exploration_finding' | 'experience_summary' | 'tool_usage' | 'skill_creation' | 'test' | 'other';
11
26
  declare const MEMORY_CATEGORIES: MemoryCategory[];
12
27
  type MemorySource = 'session_self_write' | 'historical';
@@ -198,7 +213,6 @@ interface MemoryServiceContext {
198
213
  config?: MemoryKnowledgeConfigWithModels;
199
214
  agentId?: string;
200
215
  }
201
- type ErrorCode = 'AGENT_ID_REQUIRED' | 'SESSION_ID_REQUIRED' | 'CONTENT_REQUIRED' | 'INTERNAL' | 'NOT_FOUND' | 'AMBIGUOUS' | 'NOT_INDEXED' | 'OPTIONAL_DEP_MISSING' | 'TRUST_DENIED' | 'PATH_TRAVERSAL' | 'CATEGORY_REQUIRED' | 'IMPORTANCE_REQUIRED' | 'TIMERANGE_REQUIRED' | 'INGEST_FAILED' | 'UNSUPPORTED_FORMAT' | 'HAS_REFERENCES' | 'DRY_RUN_NO_DELETE' | 'MAX_DELETE_EXCEEDED' | 'JOB_NOT_FOUND' | 'JOB_TIMEOUT' | 'JOB_FAILED';
202
216
  type KGScope = 'agent_only' | 'shared_only' | 'both';
203
217
  interface RecallParams {
204
218
  query: string;
@@ -369,7 +383,6 @@ interface DoctorResult extends KnowledgeDoctorResult {
369
383
  }
370
384
  interface InitParams {
371
385
  dbPath?: string;
372
- workspaceDir?: string;
373
386
  archiveDays?: number;
374
387
  force?: boolean;
375
388
  }
@@ -537,10 +550,7 @@ declare function getInstance(): IInstance;
537
550
  declare function getHomeDir(): string;
538
551
  declare function getXdgData(): string;
539
552
  declare function getMemoryDir(): string;
540
- declare function getMemoryDbPath(input?: string | {
541
- dir?: string;
542
- workspaceDir?: string;
543
- }): string;
553
+ declare function getMemoryDbPath(workspaceDir: string): string;
544
554
 
545
555
  type MigrationDb = SyncSqliteConnection;
546
556
  declare const LATEST_SCHEMA_VERSION = 1;
@@ -661,4 +671,21 @@ declare function registerAllDefaultHooks(): void;
661
671
  declare function clearAllHooks(): void;
662
672
  declare function dispatchHook(name: HookName, ctx: HookContext): Promise<HookResult>;
663
673
 
664
- export { ALL_OPS, type ArchiveRecord, type ArchiveResult, COMMANDS_HELP, type CommandHelp, type ConsolidateParams, type ConsolidateResult, type DoctorResult, type EdgeQueryFilter, type ErrorCode, type ExtractParams, type ExtractResult, type ForgetParams, type ForgetResult, type GraphQueryParams, type GraphQueryResult, GraphStore, type HookContext, type HookHandler, type HookName, type HookResult, type InitParams, type InitResult, type KGScope, LATEST_SCHEMA_VERSION, Llm, type LlmInitConfig, type LlmModels, MEMORY_CATEGORIES, MIGRATIONS, type MemoryCategory, type MemoryCliDeps, type MemoryCliResult, MemoryDatabaseError, MemoryDatabaseManager, type MemoryEdge, MemoryEmbeddingError, MemoryError, MemoryErrorCode, type MemoryFact, MemoryFileError, type MemoryNode, type MemoryNodeWithEdges, MemoryNotFoundError, type MemoryOp, MemoryPermissionError, type MemoryQuery, type MemoryRecallResult, MemorySearchError, type MemorySource, MemoryStdioServer, type MemorySystemConfig, MemoryValidationError, type MemoryVector, type NodeQueryFilter, OP_REGISTRY, type OpAnnotations, type OpHandlerContext, type OpScope, type RecallParams, type RecallResult, type RegisteredHook, type RememberParams, type RememberResult, type StatusResult, type SyncParams, type SyncResult, type UpdateParams, type UpdateResult, addWord, clearAllHooks, closeTokenizer, consolidate, dispatchHook, doctor, executeOp, extract, forget, getGlobal, getHomeDir, getInstance, getMemoryDbPath, getMemoryDir, getXdgData, graphQuery, handleMemoryCli, init, initTokenizer, isInitialized, listHooks, loadCustomDict, readCurrentSchemaVersion, recall, registerAllDefaultHooks, registerHook, remember, renderBanner, renderHelp, renderOperationMarkdown, resetGlobalAdapter, resetInstanceAdapter, runMigrations, setGlobalAdapter, setInstanceAdapter, status, sync, toFtsTokens, toFtsTokensForSearch, tokenize, tokenizeForSearch, unregisterHook, update };
674
+ declare const MEMORY_JSON_REL_PATH: readonly [".easbot", "memory.json"];
675
+ type StateResult = {
676
+ memoryJson: MemoryJson | undefined;
677
+ exists: boolean;
678
+ rootDir: string;
679
+ };
680
+ declare namespace MemoryCache {
681
+ function state(): Promise<StateResult>;
682
+ function resetState(): void;
683
+ function init(): Promise<void>;
684
+ function getMemoryJson(): Promise<MemoryJson | undefined>;
685
+ function exists(): Promise<boolean>;
686
+ function getRootDir(): Promise<string>;
687
+ function writeMemoryJson(partial: Partial<MemoryJson>): Promise<MemoryJson>;
688
+ function getConfigPath(): Promise<string>;
689
+ }
690
+
691
+ 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 HookContext, type HookHandler, type HookName, type HookResult, 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, MemoryDatabaseError, MemoryDatabaseManager, type MemoryEdge, MemoryEmbeddingError, MemoryError, MemoryErrorCode, type MemoryFact, MemoryFileError, type MemoryJson, MemoryJsonSchema, type MemoryNode, type MemoryNodeWithEdges, MemoryNotFoundError, type MemoryOp, MemoryPermissionError, type MemoryQuery, type MemoryRecallResult, MemorySearchError, type MemorySource, MemoryStdioServer, type MemorySystemConfig, MemoryValidationError, type MemoryVector, type NodeQueryFilter, OP_REGISTRY, type OpAnnotations, type OpHandlerContext, type OpScope, type RecallParams, type RecallResult, type RegisteredHook, type RememberParams, type RememberResult, type StatusResult, type SyncParams, type SyncResult, type UpdateParams, type UpdateResult, addWord, clearAllHooks, closeTokenizer, consolidate, dispatchHook, doctor, executeOp, extract, forget, getGlobal, getHomeDir, getInstance, getMemoryDbPath, getMemoryDir, getXdgData, graphQuery, handleMemoryCli, init, initTokenizer, isInitialized, listHooks, loadCustomDict, readCurrentSchemaVersion, recall, registerAllDefaultHooks, registerHook, remember, renderBanner, renderHelp, renderOperationMarkdown, resetGlobalAdapter, resetInstanceAdapter, runMigrations, setGlobalAdapter, setInstanceAdapter, status, sync, toFtsTokens, toFtsTokensForSearch, tokenize, tokenizeForSearch, unregisterHook, update };
package/dist/index.mjs CHANGED
@@ -1,6 +1,6 @@
1
- import'./chunks/chunk-QF5S5MG7.mjs';export{a as COMMANDS_HELP,d as handleMemoryCli,b as renderBanner,c as renderHelp}from'./chunks/chunk-4YADRVIU.mjs';export{b as MemoryStdioServer,a as renderOperationMarkdown}from'./chunks/chunk-I5YSX4DQ.mjs';import {z as z$1,A}from'./chunks/chunk-X7P7ZFZF.mjs';export{y as ALL_OPS,a as GraphStore,x as OP_REGISTRY,r as consolidate,w as doctor,z as executeOp,q as extract,p as forget,t as graphQuery,u as init,b as recall,n as remember,v as status,s as sync,o as update}from'./chunks/chunk-X7P7ZFZF.mjs';export{a as LATEST_SCHEMA_VERSION,b as MIGRATIONS,e as MemoryDatabaseManager,d as readCurrentSchemaVersion,c as runMigrations}from'./chunks/chunk-FY4ILCIM.mjs';import {f as f$1,j as j$1}from'./chunks/chunk-WDVDYZ25.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-WDVDYZ25.mjs';export{a as Llm}from'./chunks/chunk-6CQMBEIQ.mjs';import {a}from'./chunks/chunk-HQBRVVXS.mjs';export{GRAPH_ENTITY_TYPE_DEFINITIONS,GRAPH_RELATION_TYPE_DEFINITIONS}from'@easbot/types';import*as m from'jieba-wasm';import {Log,loadTextFile,Filesystem}from'@easbot/utils';import {createHash}from'crypto';var we=["user_preference","task_context","technical_fact","decision","relationship","reminder","error_pattern","workflow","exploration_finding","experience_summary","tool_usage","skill_creation","test","other"],d=class extends Error{constructor(o,t,n){super(o,{cause:n});a(this,"code",t);a(this,"cause",n);this.name="MemoryError";}},D=class extends d{constructor(r,o){super(r,"MEMORY_VALIDATION_ERROR",o),this.name="MemoryValidationError";}},T=class extends d{constructor(r){super(`Memory not found: ${r}`,"MEMORY_NOT_FOUND"),this.name="MemoryNotFoundError";}},v=class extends d{constructor(r){super(r,"MEMORY_PERMISSION_ERROR"),this.name="MemoryPermissionError";}},F=class extends d{constructor(r,o){super(r,"MEMORY_DATABASE_ERROR",o),this.name="MemoryDatabaseError";}},L=class extends d{constructor(r,o){super(r,"MEMORY_FILE_ERROR",o),this.name="MemoryFileError";}},$=class extends d{constructor(r,o){super(r,"MEMORY_SEARCH_ERROR",o),this.name="MemorySearchError";}},j=class extends d{constructor(r,o){super(r,"MEMORY_EMBEDDING_ERROR",o),this.name="MemoryEmbeddingError";}},ge=(i=>(i.VALIDATION_ERROR="MEMORY_VALIDATION_ERROR",i.NOT_FOUND="MEMORY_NOT_FOUND",i.PERMISSION_ERROR="MEMORY_PERMISSION_ERROR",i.DATABASE_ERROR="MEMORY_DATABASE_ERROR",i.FILE_ERROR="MEMORY_FILE_ERROR",i.SEARCH_ERROR="MEMORY_SEARCH_ERROR",i.EMBEDDING_ERROR="MEMORY_EMBEDDING_ERROR",i))(ge||{});var s=Log.create({service:"memory.tokenizer"}),c=false,ke=loadTextFile("./assets/jieba_dict.txt",import.meta.url);async function $e(e){if(!c)try{s.debug("Initializing jieba tokenizer");let r=ke();if(m.with_dict(r),s.debug("Built-in dictionary loaded"),e?.dictPath&&e.dictPath.length>0)for(let o of e.dictPath)await xe(o);c=!0,s.debug("Jieba tokenizer initialized successfully");}catch(r){s.error("Failed to initialize jieba tokenizer",{error:String(r)}),s.warn("Using fallback tokenization (space-based)");}}async function xe(e){if(!c)throw new Error("Tokenizer not initialized");try{let r=await Filesystem.readText(e);s.debug("Loading custom dictionary",{dictPath:e}),m.with_dict(r),s.debug("Custom dictionary loaded successfully",{dictPath:e});}catch(r){s.warn("Failed to load custom dictionary",{dictPath:e,error:String(r)});}}function He(e){if(!c)return e.split(/\s+/).filter(Boolean);try{return m.cut(e)}catch(r){return s.warn("Tokenization failed, using fallback",{error:String(r)}),e.split(/\s+/).filter(Boolean)}}function he(e){if(!c)return e.split(/\s+/).filter(Boolean);try{return m.cut_for_search(e)}catch(r){return s.warn("Tokenization for search failed, using fallback",{error:String(r)}),e.split(/\s+/).filter(Boolean)}}function je(e,r,o){if(c)try{m.add_word(e,r,o),s.debug("Word added to dictionary",{word:e,freq:r,tag:o});}catch(t){s.warn("Failed to add word",{word:e,error:String(t)});}}function ze(){return c}async function Ye(){c=false,s.debug("Tokenizer closed");}function Be(e){if(!c)return e.split(/\s+/).filter(Boolean).join(" ");try{return He(e).join(" ")}catch(r){return s.warn("Tokenization failed, using fallback",{error:String(r)}),e.split(/\s+/).filter(Boolean).join(" ")}}function Ge(e){if(!c)return e.split(/\s+/).filter(Boolean).join(" ");try{return he(e).join(" ")}catch(r){return s.warn("Tokenization for search failed, using fallback",{error:String(r)}),e.split(/\s+/).filter(Boolean).join(" ")}}function u(e){let r=f$1().worktree,o=j$1(r);return {agentId:e,isTrustedLocal:true,remote:false,locale:"en-US",dbPath:o,workspaceDir:r,rootDir:r,config:A({agentId:e,dbPath:o,workspaceDir:r})}}var z=async e=>{if(!e.agentId?.trim())return {ok:false,error:"session-start: agentId is required in ctx"};let r=e.extras?.topK??5,o=e.extras?.query??"";try{let t=await z$1("recall",{query:o,maxResults:r},u(e.agentId));if(t.hits.length===0)return {ok:!0,injected:"",logLine:"session-start: no facts found for agent; skipping context injection"};let n=t.hits.map(R=>`- [${R.category}/imp=${R.importance}] ${R.snippet.slice(0,200)}`);return {ok:!0,injected:`[memory:session-start recall top-${t.hits.length}]
1
+ import'./chunks/chunk-QF5S5MG7.mjs';export{a as COMMANDS_HELP,d as handleMemoryCli,b as renderBanner,c as renderHelp}from'./chunks/chunk-DWGCQLSH.mjs';export{b as MemoryStdioServer,a as renderOperationMarkdown}from'./chunks/chunk-NWY7CUSL.mjs';import {z as z$1,A}from'./chunks/chunk-OOBYBPIN.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-OOBYBPIN.mjs';export{g as DEFAULT_MEMORY_JSON,a as LATEST_SCHEMA_VERSION,h as MEMORY_JSON_REL_PATH,b as MIGRATIONS,i as MemoryCache,e as MemoryDatabaseManager,f as MemoryJsonSchema,d as readCurrentSchemaVersion,c as runMigrations}from'./chunks/chunk-CVS25NBK.mjs';import {f as f$1,j as j$1}from'./chunks/chunk-CIXJXCID.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-CIXJXCID.mjs';export{a as Llm}from'./chunks/chunk-QJTEXVXX.mjs';import {a as a$1}from'./chunks/chunk-AJDMZTCQ.mjs';import {a}from'./chunks/chunk-HQBRVVXS.mjs';export{GRAPH_ENTITY_TYPE_DEFINITIONS,GRAPH_RELATION_TYPE_DEFINITIONS}from'@easbot/types';import*as d from'jieba-wasm';import {Log,loadTextFile,errorMeta,Filesystem}from'@easbot/utils';import {createHash}from'crypto';var Ye=["user_preference","task_context","technical_fact","decision","relationship","reminder","error_pattern","workflow","exploration_finding","experience_summary","tool_usage","skill_creation","test","other"],m=class extends Error{constructor(t,o,n){super(t,{cause:n});a(this,"code",o);a(this,"cause",n);this.name="MemoryError";}},F=class extends m{constructor(r,t){super(r,"MEMORY_VALIDATION_ERROR",t),this.name="MemoryValidationError";}},$=class extends m{constructor(r){super(`Memory not found: ${r}`,"MEMORY_NOT_FOUND"),this.name="MemoryNotFoundError";}},j=class extends m{constructor(r){super(r,"MEMORY_PERMISSION_ERROR"),this.name="MemoryPermissionError";}},Y=class extends m{constructor(r,t){super(r,"MEMORY_DATABASE_ERROR",t),this.name="MemoryDatabaseError";}},z=class extends m{constructor(r,t){super(r,"MEMORY_FILE_ERROR",t),this.name="MemoryFileError";}},B=class extends m{constructor(r,t){super(r,"MEMORY_SEARCH_ERROR",t),this.name="MemorySearchError";}},G=class extends m{constructor(r,t){super(r,"MEMORY_EMBEDDING_ERROR",t),this.name="MemoryEmbeddingError";}},Me=(i=>(i.VALIDATION_ERROR="MEMORY_VALIDATION_ERROR",i.NOT_FOUND="MEMORY_NOT_FOUND",i.PERMISSION_ERROR="MEMORY_PERMISSION_ERROR",i.DATABASE_ERROR="MEMORY_DATABASE_ERROR",i.FILE_ERROR="MEMORY_FILE_ERROR",i.SEARCH_ERROR="MEMORY_SEARCH_ERROR",i.EMBEDDING_ERROR="MEMORY_EMBEDDING_ERROR",i))(Me||{});var s=Log.create({service:"memory.tokenizer"}),c=false,_e=loadTextFile("./assets/jieba_dict.txt",import.meta.url);async function Ve(e){if(!c)try{s.debug("Initializing jieba tokenizer");let r=_e();if(d.with_dict(r),s.debug("Built-in dictionary loaded"),e?.dictPath&&e.dictPath.length>0)for(let t of e.dictPath)await be(t);c=!0,s.debug("Jieba tokenizer initialized successfully");}catch(r){s.error("Failed to initialize jieba tokenizer",{error:errorMeta(r)}),s.warn("Using fallback tokenization (space-based)");}}async function be(e){if(!c)throw new a$1.TokenizerNotInitializedError({message:"Tokenizer not initialized"});try{let r=await Filesystem.readText(e);s.debug("Loading custom dictionary",{dictPath:e}),d.with_dict(r),s.debug("Custom dictionary loaded successfully",{dictPath:e});}catch(r){s.warn("Failed to load custom dictionary",{dictPath:e,error:errorMeta(r)});}}function Oe(e){if(!c)return e.split(/\s+/).filter(Boolean);try{return d.cut(e)}catch(r){return s.warn("Tokenization failed, using fallback",{error:errorMeta(r)}),e.split(/\s+/).filter(Boolean)}}function Se(e){if(!c)return e.split(/\s+/).filter(Boolean);try{return d.cut_for_search(e)}catch(r){return s.warn("Tokenization for search failed, using fallback",{error:errorMeta(r)}),e.split(/\s+/).filter(Boolean)}}function Xe(e,r,t){if(c)try{d.add_word(e,r,t),s.debug("Word added to dictionary",{word:e,freq:r,tag:t});}catch(o){s.warn("Failed to add word",{word:e,error:errorMeta(o)});}}function Ze(){return c}async function er(){c=false,s.debug("Tokenizer closed");}function rr(e){if(!c)return e.split(/\s+/).filter(Boolean).join(" ");try{return Oe(e).join(" ")}catch(r){return s.warn("Tokenization failed, using fallback",{error:errorMeta(r)}),e.split(/\s+/).filter(Boolean).join(" ")}}function tr(e){if(!c)return e.split(/\s+/).filter(Boolean).join(" ");try{return Se(e).join(" ")}catch(r){return s.warn("Tokenization for search failed, using fallback",{error:errorMeta(r)}),e.split(/\s+/).filter(Boolean).join(" ")}}function u(e){let r=f$1().worktree,t=j$1(r);return {agentId:e,isTrustedLocal:true,remote:false,locale:"en-US",dbPath:t,workspaceDir:r,rootDir:r,config:A({agentId:e,dbPath:t,workspaceDir:r})}}var K=async e=>{if(!e.agentId?.trim())return {ok:false,error:"session-start: agentId is required in ctx"};let r=e.extras?.topK??5,t=e.extras?.query??"";try{let o=await z$1("recall",{query:t,maxResults:r},u(e.agentId));if(o.hits.length===0)return {ok:!0,injected:"",logLine:"session-start: no facts found for agent; skipping context injection"};let n=o.hits.map(k=>`- [${k.category}/imp=${k.importance}] ${k.snippet.slice(0,200)}`);return {ok:!0,injected:`[memory:session-start recall top-${o.hits.length}]
2
2
  ${n.join(`
3
- `)}`,logLine:`session-start: injected ${t.hits.length} facts into context (agent=${e.agentId})`}}catch(t){return {ok:false,error:t instanceof Error?t.message:String(t)}}};var Ee=3600*1e3,Y=async e=>{if(!e.agentId?.trim())return {ok:false,error:"session-end: agentId is required in ctx"};let r=typeof e.extras?.lookbackMs=="number"&&e.extras.lookbackMs>0?e.extras.lookbackMs:Ee,o=e.extras?.fromTime??new Date(Date.now()-r).toISOString();try{let t=await z$1("consolidate",{fromTime:o},u(e.agentId));return {ok:!0,logLine:`session-end: lookback=${r}ms, total=${t.totalFacts}, deduped=${t.dedupedCount}, archived=${t.archivedCount}, skipped=${t.skippedCount}`}}catch(t){return {ok:false,error:t instanceof Error?t.message:String(t)}}};var B=async e=>{if(!e.agentId?.trim())return {ok:false,error:"pre-compact: agentId is required in ctx"};let o=(e.contextPreview??e.messagePreview??"").slice(0,200).replace(/\s+/g," ").trim(),t=e.extras?.topK??3;if(!o)return {ok:true,injected:"",logLine:"pre-compact: empty contextPreview; skipping recall injection"};try{let n=await z$1("recall",{query:o,maxResults:t,minImportance:5},u(e.agentId));if(n.hits.length===0)return {ok:!0,injected:"",logLine:`pre-compact: no facts matched query for agent=${e.agentId}`};let h=n.hits.map(i=>`- [${i.category}/imp=${i.importance}] ${i.snippet.slice(0,150)}`);return {ok:!0,injected:`[memory:pre-compact recall top-${n.hits.length} (imp>=5)]
4
- ${h.join(`
5
- `)}`,logLine:`pre-compact: injected ${n.hits.length} facts before compaction`}}catch(n){return {ok:false,error:n instanceof Error?n.message:String(n)}}};var G=async e=>{if(!e.agentId?.trim())return {ok:false,error:"post-tool-failure: agentId is required in ctx"};if(!e.toolName?.trim()||!e.error?.trim())return {ok:false,error:"post-tool-failure: toolName and error are required in ctx"};let r=createHash("sha256").update(`${e.toolName}:${e.error}`).digest("hex").slice(0,8),o=e.messagePreview?e.messagePreview.slice(0,200).replace(/\s+/g," ").trim():"",t=[`[error_pattern] tool=${e.toolName}`,`[error] ${e.error}`,o?`[preview] ${o}`:"",`[errHash] ${r}`].filter(Boolean).join(`
6
- `);try{return {ok:!0,logLine:`post-tool-failure: wrote error_pattern fact ${(await z$1("remember",{content:t,category:"error_pattern",importance:6,tags:["post-tool-failure",`tool:${e.toolName}`,`err:${r}`],sessionId:e.sessionId,msgId:e.extras?.msgId},u(e.agentId))).fact.id} (tool=${e.toolName}, errHash=${r})`}}catch(n){return {ok:false,error:n instanceof Error?n.message:String(n)}}};var g=Log.create({service:"memory.hooks"}),f=new Map;function y(e,r){let o={name:e,handler:r,registeredAt:new Date().toISOString()},t=f.get(e);f.set(e,o),t?g.info("Hook overwritten",{name:e,prevRegisteredAt:t.registeredAt,newRegisteredAt:o.registeredAt}):g.info("Hook registered",{name:e,registeredAt:o.registeredAt});}function Me(e){return f.delete(e)}function _e(){return Array.from(f.values()).map(e=>({name:e.name,handler:e.handler,registeredAt:e.registeredAt}))}function Se(){y("session-start",z),y("session-end",Y),y("pre-compact",B),y("post-tool-failure",G);}function Oe(){f.clear(),g.debug("All hooks cleared");}async function Ae(e,r){let o=f.get(e);if(!o)return g.debug("dispatchHook: no handler registered; noop",{name:e}),{ok:true,logLine:`hook ${e} not registered; noop`};try{let t=await o.handler(r);return t.ok?t.logLine&&g.debug("dispatchHook: ok",{name:e,logLine:t.logLine}):g.warn("dispatchHook: handler returned failure",{name:e,agentId:r.agentId,error:t.error}),t}catch(t){let n=t instanceof Error?t.message:String(t);return g.warn("dispatchHook: handler threw, caught and converted to failure result",{name:e,agentId:r.agentId,error:n}),{ok:false,error:n}}}export{we as MEMORY_CATEGORIES,F as MemoryDatabaseError,j as MemoryEmbeddingError,d as MemoryError,ge as MemoryErrorCode,L as MemoryFileError,T as MemoryNotFoundError,v as MemoryPermissionError,$ as MemorySearchError,D as MemoryValidationError,je as addWord,Oe as clearAllHooks,Ye as closeTokenizer,Ae as dispatchHook,$e as initTokenizer,ze as isInitialized,_e as listHooks,xe as loadCustomDict,Se as registerAllDefaultHooks,y as registerHook,Be as toFtsTokens,Ge as toFtsTokensForSearch,He as tokenize,he as tokenizeForSearch,Me as unregisterHook};
3
+ `)}`,logLine:`session-start: injected ${o.hits.length} facts into context (agent=${e.agentId})`}}catch(o){return {ok:false,error:errorMeta(o).message}}};var Ce=3600*1e3,U=async e=>{if(!e.agentId?.trim())return {ok:false,error:"session-end: agentId is required in ctx"};let r=typeof e.extras?.lookbackMs=="number"&&e.extras.lookbackMs>0?e.extras.lookbackMs:Ce,t=e.extras?.fromTime??new Date(Date.now()-r).toISOString();try{let o=await z$1("consolidate",{fromTime:t},u(e.agentId));return {ok:!0,logLine:`session-end: lookback=${r}ms, total=${o.totalFacts}, deduped=${o.dedupedCount}, archived=${o.archivedCount}, skipped=${o.skippedCount}`}}catch(o){return {ok:false,error:errorMeta(o).message}}};var q=async e=>{if(!e.agentId?.trim())return {ok:false,error:"pre-compact: agentId is required in ctx"};let t=(e.contextPreview??e.messagePreview??"").slice(0,200).replace(/\s+/g," ").trim(),o=e.extras?.topK??3;if(!t)return {ok:true,injected:"",logLine:"pre-compact: empty contextPreview; skipping recall injection"};try{let n=await z$1("recall",{query:t,maxResults:o,minImportance:5},u(e.agentId));if(n.hits.length===0)return {ok:!0,injected:"",logLine:`pre-compact: no facts matched query for agent=${e.agentId}`};let E=n.hits.map(i=>`- [${i.category}/imp=${i.importance}] ${i.snippet.slice(0,150)}`);return {ok:!0,injected:`[memory:pre-compact recall top-${n.hits.length} (imp>=5)]
4
+ ${E.join(`
5
+ `)}`,logLine:`pre-compact: injected ${n.hits.length} facts before compaction`}}catch(n){return {ok:false,error:errorMeta(n).message}}};var Q=async e=>{if(!e.agentId?.trim())return {ok:false,error:"post-tool-failure: agentId is required in ctx"};if(!e.toolName?.trim()||!e.error?.trim())return {ok:false,error:"post-tool-failure: toolName and error are required in ctx"};let r=createHash("sha256").update(`${e.toolName}:${e.error}`).digest("hex").slice(0,8),t=e.messagePreview?e.messagePreview.slice(0,200).replace(/\s+/g," ").trim():"",o=[`[error_pattern] tool=${e.toolName}`,`[error] ${e.error}`,t?`[preview] ${t}`:"",`[errHash] ${r}`].filter(Boolean).join(`
6
+ `);try{return {ok:!0,logLine:`post-tool-failure: wrote error_pattern fact ${(await z$1("remember",{content:o,category:"error_pattern",importance:6,tags:["post-tool-failure",`tool:${e.toolName}`,`err:${r}`],sessionId:e.sessionId,msgId:e.extras?.msgId},u(e.agentId))).fact.id} (tool=${e.toolName}, errHash=${r})`}}catch(n){return {ok:false,error:errorMeta(n).message}}};var f=Log.create({service:"memory.hooks"}),y=new Map;function R(e,r){let t={name:e,handler:r,registeredAt:new Date().toISOString()},o=y.get(e);y.set(e,t),o?f.info("Hook overwritten",{name:e,prevRegisteredAt:o.registeredAt,newRegisteredAt:t.registeredAt}):f.info("Hook registered",{name:e,registeredAt:t.registeredAt});}function ve(e){return y.delete(e)}function Le(){return Array.from(y.values()).map(e=>({name:e.name,handler:e.handler,registeredAt:e.registeredAt}))}function Fe(){R("session-start",K),R("session-end",U),R("pre-compact",q),R("post-tool-failure",Q);}function $e(){y.clear(),f.debug("All hooks cleared");}async function je(e,r){let t=y.get(e);if(!t)return f.debug("dispatchHook: no handler registered; noop",{name:e}),{ok:true,logLine:`hook ${e} not registered; noop`};try{let o=await t.handler(r);return o.ok?o.logLine&&f.debug("dispatchHook: ok",{name:e,logLine:o.logLine}):f.warn("dispatchHook: handler returned failure",{name:e,agentId:r.agentId,error:o.error}),o}catch(o){let n=errorMeta(o).message;return f.warn("dispatchHook: handler threw, caught and converted to failure result",{name:e,agentId:r.agentId,error:errorMeta(o)}),{ok:false,error:n}}}export{Ye as MEMORY_CATEGORIES,Y as MemoryDatabaseError,G as MemoryEmbeddingError,m as MemoryError,Me as MemoryErrorCode,z as MemoryFileError,$ as MemoryNotFoundError,j as MemoryPermissionError,B as MemorySearchError,F as MemoryValidationError,Xe as addWord,$e as clearAllHooks,er as closeTokenizer,je as dispatchHook,Ve as initTokenizer,Ze as isInitialized,Le as listHooks,be as loadCustomDict,Fe as registerAllDefaultHooks,R as registerHook,rr as toFtsTokens,tr as toFtsTokensForSearch,Oe as tokenize,Se as tokenizeForSearch,ve as unregisterHook};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@easbot/memory",
3
- "version": "0.3.28",
3
+ "version": "0.3.29",
4
4
  "description": "Memory management library for EASBOT ecosystem - 智能记忆管理库,支持混合搜索、中英文分词、增量索引",
5
5
  "type": "module",
6
6
  "main": "dist/index.cjs",
@@ -54,14 +54,14 @@
54
54
  "better-sqlite3": "^13.0.3",
55
55
  "jieba-wasm": "^2.4.0",
56
56
  "xdg-basedir": "^5.1.0",
57
- "@easbot/database": "0.3.28",
58
- "@easbot/mcp": "0.3.28",
59
- "@easbot/terminal": "0.3.28",
60
- "@easbot/types": "0.3.28",
61
- "@easbot/utils": "0.3.28",
62
- "@easbot/local-model-sdk": "0.3.28",
63
- "@easbot/llm": "0.3.28",
64
- "@easbot/ollama-sdk": "0.3.28"
57
+ "@easbot/database": "0.3.29",
58
+ "@easbot/mcp": "0.3.29",
59
+ "@easbot/terminal": "0.3.29",
60
+ "@easbot/types": "0.3.29",
61
+ "@easbot/utils": "0.3.29",
62
+ "@easbot/local-model-sdk": "0.3.29",
63
+ "@easbot/ollama-sdk": "0.3.29",
64
+ "@easbot/llm": "0.3.29"
65
65
  },
66
66
  "devDependencies": {
67
67
  "@types/node": "^25.9.5",
@@ -1 +0,0 @@
1
- import {f}from'./chunk-WDVDYZ25.mjs';import {Log}from'@easbot/utils';import {renderLines,printHuman,emitJsonOk,formatKnowledgeDoctor,formatKnowledgeStatus,formatKnowledgeInit,emitJsonError}from'@easbot/terminal';var b=Log.create({service:"memory-cli"}),S=[{i18nKey:"cli.cmd.init.description",name:"init",description:"Initialize memory workspace (.easbot/memory.db)",group:"lifecycle"},{i18nKey:"cli.cmd.status.description",name:"status",description:"Show memory state / db stats / facts by category",group:"lifecycle"},{i18nKey:"cli.cmd.doctor.description",name:"doctor",description:"Run health checks (backend, FTS, schema, lock)",group:"lifecycle"},{i18nKey:"cli.cmd.recall.description",name:"recall",description:"Hybrid search (FTS + vector) over memory facts",group:"memory"},{i18nKey:"cli.cmd.remember.description",name:"remember",description:"Persist a new memory fact (with dedup + KG extraction)",group:"memory"},{i18nKey:"cli.cmd.forget.description",name:"forget",description:"Delete memory facts (factId / category / timeRange / dryRun)",group:"memory"},{i18nKey:"cli.cmd.sync.description",name:"sync",description:"Sync facts to .md files (idempotent) and archive expired active files (default 30 days)",group:"memory"},{i18nKey:"cli.cmd.extract.description",name:"extract",description:"Extract facts from a session (sessionId + lastN)",group:"session"},{i18nKey:"cli.cmd.consolidate.description",name:"consolidate",description:"Run consolidation pipeline (extract \u2192 dedup \u2192 archive)",group:"session"},{i18nKey:"cli.cmd.graph.description",name:"graph",description:"KG query (nodes / edges / neighbors with scope \u4E09\u6863)",group:"graph"},{i18nKey:"cli.cmd.config.description",name:"config",description:"Show / validate memory configuration (dry-read)",group:"external"},{i18nKey:"cli.cmd.mcp.description",name:"mcp",description:"Start stdio MCP server (exposes 10 memory tools)",group:"external"}];function g(p,t){let e=S.filter(s=>s.group===p);return renderLines({title:t,flat:e.map(s=>`$ easbot-memory ${s.name.padEnd(14)} ${s.description}`)})}function v(){let p=[renderLines({title:"easbot-memory \xB7 Memory & Knowledge Module for EASBot",flat:["Usage: easbot-memory <command> [options]"]}),"",g("lifecycle","Commands (lifecycle):"),"",g("memory","Commands (memory):"),"",g("session","Commands (session):"),"",g("graph","Commands (graph query):"),"",g("external","External:")];printHuman(p);}function j(){v(),printHuman(["",renderLines({title:"Global flags & invocation",flat:["--cwd <dir> --config <path> --log-level <L> --print-logs --debug","Standalone CLI: easbot-memory <command>","Agent CLI: easbot memory <command>"]})]);}async function C(p){try{let{bootstrapLlm:t}=await import('@easbot/llm'),{Llm:e}=await import('./llm-UHTBU2HA.mjs');await t({target:e,cwd:p,subConfigPath:".easbot/memory.json",embedding:!0,graph:!0});}catch(t){b.warn("bootstrapLlm failed; Llm-related features will be disabled",{error:t instanceof Error?t.message:String(t)});}}async function P(p,t){let[e,...s]=p,c=t?.cwd??process.cwd(),d=t?.agentId??"default";if(!e)return j(),{code:0,handled:true,command:null};await C(c);try{switch(e){case "init":{let{parseInitOptions:n,runInit:a}=await import('./init-2SBK7ZWO.mjs'),r=n(s);if(r.help)return console.log("Usage: easbot-memory init [dir] [--force] [--json]"),{code:0,handled:!0,command:e};let o=r.workspaceDir?.trim()??c,i=await a({...r,ctxWorkspaceDir:o,agentId:d});if(r.json)emitJsonOk(i,{command:e});else {let u=i;printHuman([formatKnowledgeInit({packageName:"memory",configPath:u.configPath??u.dbPath,backend:"better-sqlite3",schemaVersion:u.schemaVersion,extras:{dbPath:u.dbPath,migrationsApplied:u.migrationsApplied,tablesCreated:u.tablesCreated,durationMs:`${u.durationMs}ms`}})],{title:"init memory workspace",boxed:!0});}return {code:0,handled:!0,command:e}}case "recall":{let{parseRecallOptions:n,runRecall:a,formatRecallText:r}=await import('./recall-UQSG6ECA.mjs'),o=n(s);if(o.help)return console.log("Usage: easbot-memory recall --query <q> [--limit <n>] [--category <c>] [--min-importance <n>] [--json]"),{code:0,handled:!0,command:e};let i=await a({...o,workspaceDir:c,agentId:d});return o.json?emitJsonOk(i,{command:e}):printHuman([r(i)],{title:`recall (agentId=${d??"default"})`}),{code:0,handled:!0,command:e}}case "remember":{let{parseRememberOptions:n,runRemember:a,formatRememberText:r}=await import('./remember-GVQJ5G7Z.mjs'),o=n(s);if(o.help)return console.log("Usage: easbot-memory remember --content <text> --category <c> --importance <1-10> [--tag <t>] [--session <s>] [--json]"),{code:0,handled:!0,command:e};let i=await a({...o,workspaceDir:c,agentId:d});return o.json?emitJsonOk(i,{command:e}):printHuman([r(i)],{title:"remember (persist fact)"}),{code:0,handled:!0,command:e}}case "forget":{let{parseForgetOptions:n,runForget:a,formatForgetText:r}=await import('./forget-JTACRG7Y.mjs'),o=n(s);if(o.help)return console.log("Usage: easbot-memory forget (--fact-id <id> | --category <c> | --from <ISO> --to <ISO>) [--max-delete <n>] [--dry-run] [--json]"),{code:0,handled:!0,command:e};let i=await a({...o,workspaceDir:c,agentId:d});return o.json?emitJsonOk(i,{command:e}):printHuman([r(i)],{title:"forget (delete facts)"}),{code:0,handled:!0,command:e}}case "extract":{let{parseExtractOptions:n,runExtract:a,formatExtractText:r}=await import('./extract-RBBSVK2S.mjs'),o=n(s);if(o.help)return console.log("Usage: easbot-memory extract --session <sessionId> [--last-n <n>] [--from-msg <id>] [--json]"),{code:0,handled:!0,command:e};let i=await a({...o,workspaceDir:c,agentId:d});return o.json?emitJsonOk(i,{command:e}):printHuman([r(i)],{title:"extract (from session)"}),{code:0,handled:!0,command:e}}case "consolidate":{let{parseConsolidateOptions:n,runConsolidate:a,formatConsolidateText:r}=await import('./consolidate-BGMXJUQX.mjs'),o=n(s);if(o.help)return console.log("Usage: easbot-memory consolidate [--window-days <n>] [--json]"),{code:0,handled:!0,command:e};let i=await a({...o,workspaceDir:c,agentId:d});return o.json?emitJsonOk(i,{command:e}):printHuman([r(i)],{title:"consolidate (pipeline)"}),{code:0,handled:!0,command:e}}case "sync":{let{parseSyncOptions:n,runSync:a,formatSyncText:r}=await import('./sync-UT4D32ML.mjs'),o=n(s);if(o.help)return console.log("Usage: easbot-memory sync [--window-days <n>] [--dry-run] [--json]"),console.log("Two-stage pipeline: (A) db \u2192 .md (idempotent skip on existing), (B) archive active/ files older than windowDays."),{code:0,handled:!0,command:e};let i=await a({...o,workspaceDir:c,agentId:d});return o.json?emitJsonOk(i,{command:e}):printHuman([r(i)],{title:"sync (db \u2192 .md + archive)"}),{code:0,handled:!0,command:e}}case "graph":{let{parseGraphOptions:n,runGraph:a,formatGraphText:r}=await import('./graph-VBVVRV6V.mjs'),o=n(s);if(o.help)return console.log("Usage: easbot-memory graph [--query <q>] [--node-id <id>] [--max-depth <n>] [--max-nodes <n>] [--max-edges-per-node <n>] [--json]\n (note: `--depth` is an alias for `--max-depth`; old `--kind` / `--start-node` / `--scope` flags removed since service schema is strict)"),{code:0,handled:!0,command:e};let i=await a({...o,workspaceDir:c,agentId:d});return o.json?emitJsonOk(i,{command:e}):printHuman([r(i)],{title:"graph_query"}),{code:0,handled:!0,command:e}}case "status":{let{parseStatusOptions:n,runStatus:a}=await import('./status-VZ5EBAOY.mjs'),r=n(s);if(r.help)return console.log("Usage: easbot-memory status [--json]"),{code:0,handled:!0,command:e};let o=await a({...r,workspaceDir:c,agentId:d});return r.json?emitJsonOk(o,{command:e}):printHuman([formatKnowledgeStatus(K(o))],{title:"memory status",boxed:!0}),{code:0,handled:!0,command:e}}case "doctor":{let{parseDoctorOptions:n,runDoctor:a}=await import('./doctor-C2FWFUDO.mjs'),r=n(s);if(r.help)return console.log("Usage: easbot-memory doctor [--repair] [--json]"),{code:0,handled:!0,command:e};let o=await a({...r,workspaceDir:c});return r.json?emitJsonOk(o,{command:e}):printHuman([formatKnowledgeDoctor(M(o))],{title:"memory doctor",boxed:!0}),{code:0,handled:!0,command:e}}case "config":{let{parseConfigOptions:n,runConfig:a,formatConfigText:r}=await import('./config-2SQJYVTO.mjs'),o=n(s);if(o.help)return console.log("Usage: easbot-memory config [--json]"),{code:0,handled:!0,command:e};let i=a(o);return o.json?emitJsonOk(i,{command:e}):printHuman([r(i)],{title:"memory config"}),{code:0,handled:!0,command:e}}case "mcp":{let{parseMcpOptions:n,runMcp:a}=await import('./mcp-ZQCLVZIR.mjs'),r=n(s);if(r.help)return console.log("Usage: easbot-memory mcp [start]"),console.log("Start a stdio MCP server exposing 10 memory tools:"),console.log(" recall / remember / forget / extract / consolidate"),console.log(" graph_query / status / doctor / init / sync"),{code:0,handled:!0,command:e};let o=await a(r);return r.json?emitJsonOk(o,{command:e}):printHuman([`memory mcp started (tools: ${o.tools.length})`],{title:"memory mcp server"}),{code:0,handled:!0,command:e}}default:return console.error(`Unknown command: ${e}`),console.error("Run `easbot-memory --help` for available commands."),{code:2,handled:!1,command:null}}}catch(n){let a=n instanceof Error?n.message:String(n);b.error("memory CLI command failed",{command:e,error:a,stack:n instanceof Error?n.stack:void 0});let r=t?.cwd??f().worktree;return console.error(`[memory] ${r} :: ${e} failed: ${a}`),emitJsonError(e,a),{code:1,handled:true,command:e}}}function K(p){let t=p;return {packageName:"memory",rootDir:t.workspaceDir??"",configPath:t.configPath??"",configExists:typeof t.configExists=="boolean"?t.configExists:true,dbPath:t.dbPath??"",dbExists:typeof t.dbExists=="boolean"?t.dbExists:true,dbSize:typeof t.dbSize=="number"?t.dbSize:void 0,indexState:t.indexState,schemaVersion:typeof t.schemaVersion=="number"?t.schemaVersion:void 0,extractionVersion:typeof t.extractionVersion=="number"?t.extractionVersion:void 0,lastSyncAt:t.lastSyncAt,vectorEnabled:typeof t.vectorEnabled=="boolean"?t.vectorEnabled:void 0,embeddingDims:typeof t.embeddingDims=="number"?t.embeddingDims:void 0,llm:t.llm??{initialized:false,capabilities:{}},backend:t.backend,healthy:typeof t.healthy=="boolean"?t.healthy:true,recommendation:t.recommendation,dbStats:(()=>{let e=t.dbStats;if(e&&typeof e=="object"&&Object.keys(e).length>0)return {...e};let s=t.integrityStats;if(s&&typeof s=="object"&&Object.keys(s).length>0)return {...s}})(),extras:(()=>{let e={};if(typeof t.agentId=="string"&&(e.agent_id=t.agentId),typeof t.ftsAvailable=="boolean"&&(e.fts_available=t.ftsAvailable?"yes":"no"),t.factsByCategory&&typeof t.factsByCategory=="object"){let s=t.factsByCategory;for(let[c,d]of Object.entries(s))typeof d=="number"&&d>0&&(e[`facts/${c}`]=d);}if(t.meta&&typeof t.meta=="object")for(let[s,c]of Object.entries(t.meta))e[`meta/${s}`]=c===void 0?"\u2205":c;return Object.keys(e).length>0?e:void 0})()}}function M(p){let t=p,e=Array.isArray(t.checks)?t.checks:[],s=t.integrityStats,c=t.backendAvailable,d=s?{...s}:void 0;return {packageName:"memory",healthy:typeof t.healthy=="boolean"?t.healthy:false,durationMs:typeof t.durationMs=="number"?t.durationMs:0,checks:e.map(n=>({code:typeof n.code=="string"?n.code:"",severity:n.severity??"info",name:typeof n.name=="string"?n.name:"",message:typeof n.message=="string"?n.message:"",durationMs:typeof n.durationMs=="number"?n.durationMs:void 0,details:n.details})),dbStats:d,backendAvailable:c}}export{S as a,v as b,j as c,P as d,M as e};
@@ -1 +0,0 @@
1
- import {embed,embedMany}from'ai';import {Log}from'@easbot/utils';var m;(a=>{let s=Log.create({service:"memory-llm"}),e=null;function f(n){if(g())return;let r=n;e={models:r.models,options:r.options??{}},s.debug("Llm initialized",{embeddingConfigured:!!r.models.embeddingLlm,graphConfigured:!!r.models.graphLlm});}a.init=f;function g(){return e!==null}a.isInitialized=g;function y(){e=null;}a.reset=y;function x(){return e?{embedding:!!e.models.embeddingLlm,graphLlm:!!e.models.graphLlm}:{embedding:false,graphLlm:false}}a.capabilities=x;function w(){return e?.models.embeddingLlm}a.getEmbeddingLlm=w;function I(){return e?.models.graphLlm}a.getGraphLlm=I;async function u(n){let t=l().models.embeddingLlm;if(!t)throw new Error("embeddingLlm model is not configured.");try{let o=await embed({model:t,value:n});return new Float32Array(o.embedding)}catch(o){let i=t.doEmbed;if(typeof i!="function")throw new Error("embeddingLlm model does not support embedding generation.",{cause:o});let d=(await i({values:[n]}))?.embeddings?.[0];if(!d||!Array.isArray(d))throw new Error("embeddingLlm model returned invalid embedding result.",{cause:o});return new Float32Array(d)}}a.embedText=u;async function b(n){let t=l().models.embeddingLlm;if(!t)throw new Error("embeddingLlm model is not configured.");try{return (await embedMany({model:t,values:n})).embeddings.map(i=>new Float32Array(i))}catch{return ((await t.doEmbed?.({values:n}))?.embeddings??[]).map(i=>new Float32Array(i))}}a.embedTexts=b;let l=()=>{if(!e)throw new Error("Llm is not initialized. Please call Llm.init() first.");return e};a.embed=u,a.embedMany=b;})(m||(m={}));var v=m;export{m as a,v as b};
@@ -1 +0,0 @@
1
- 'use strict';var os=require('os'),path=require('path'),xdgBasedir=require('xdg-basedir');var o=null,n=null;function b(t){o=t;}function f(){o=null;}function a(){if(o)return o;let t=os.homedir();return {Path:{home:t,data:process.env.EASBOT_DATA_PATH?.trim()||path.join(xdgBasedir.xdgData??path.join(t,".local","share"),"easbot"),config:process.env.EASBOT_CONFIG_PATH?.trim()||path.join(t,".config","easbot"),state:process.env.EASBOT_STATE_PATH?.trim()||path.join(xdgBasedir.xdgData??path.join(t,".local","share"),"easbot","state"),cache:process.env.EASBOT_CACHE_PATH?.trim()||path.join(t,".cache","easbot"),log:process.env.EASBOT_LOG_PATH?.trim()||path.join(xdgBasedir.xdgData??path.join(t,".local","share"),"easbot","log"),bin:process.env.EASBOT_BIN_PATH?.trim()||path.join(t,".local","bin")}}}function g(t){n=t;}function A(){n=null;}function I(){if(n)return n;let t=process.cwd();return {directory:t,worktree:t}}function c(){return a().Path.home||os.homedir()}function l(){let t=a().Path.data;return t||(xdgBasedir.xdgData??path.join(c(),".local","share"))}function T(){return path.join(l(),"memory")}function _(t){let i=typeof t=="string"?t:t?.dir??t?.workspaceDir??process.cwd();return path.join(i,".easbot","db","memory.db")}exports.a=b;exports.b=f;exports.c=a;exports.d=g;exports.e=A;exports.f=I;exports.g=c;exports.h=l;exports.i=T;exports.j=_;
@@ -1 +0,0 @@
1
- 'use strict';var chunkCPRDIUQ4_cjs=require('./chunk-CPRDIUQ4.cjs'),utils=require('@easbot/utils'),terminal=require('@easbot/terminal');var b=utils.Log.create({service:"memory-cli"}),S=[{i18nKey:"cli.cmd.init.description",name:"init",description:"Initialize memory workspace (.easbot/memory.db)",group:"lifecycle"},{i18nKey:"cli.cmd.status.description",name:"status",description:"Show memory state / db stats / facts by category",group:"lifecycle"},{i18nKey:"cli.cmd.doctor.description",name:"doctor",description:"Run health checks (backend, FTS, schema, lock)",group:"lifecycle"},{i18nKey:"cli.cmd.recall.description",name:"recall",description:"Hybrid search (FTS + vector) over memory facts",group:"memory"},{i18nKey:"cli.cmd.remember.description",name:"remember",description:"Persist a new memory fact (with dedup + KG extraction)",group:"memory"},{i18nKey:"cli.cmd.forget.description",name:"forget",description:"Delete memory facts (factId / category / timeRange / dryRun)",group:"memory"},{i18nKey:"cli.cmd.sync.description",name:"sync",description:"Sync facts to .md files (idempotent) and archive expired active files (default 30 days)",group:"memory"},{i18nKey:"cli.cmd.extract.description",name:"extract",description:"Extract facts from a session (sessionId + lastN)",group:"session"},{i18nKey:"cli.cmd.consolidate.description",name:"consolidate",description:"Run consolidation pipeline (extract \u2192 dedup \u2192 archive)",group:"session"},{i18nKey:"cli.cmd.graph.description",name:"graph",description:"KG query (nodes / edges / neighbors with scope \u4E09\u6863)",group:"graph"},{i18nKey:"cli.cmd.config.description",name:"config",description:"Show / validate memory configuration (dry-read)",group:"external"},{i18nKey:"cli.cmd.mcp.description",name:"mcp",description:"Start stdio MCP server (exposes 10 memory tools)",group:"external"}];function g(p,t){let e=S.filter(s=>s.group===p);return terminal.renderLines({title:t,flat:e.map(s=>`$ easbot-memory ${s.name.padEnd(14)} ${s.description}`)})}function v(){let p=[terminal.renderLines({title:"easbot-memory \xB7 Memory & Knowledge Module for EASBot",flat:["Usage: easbot-memory <command> [options]"]}),"",g("lifecycle","Commands (lifecycle):"),"",g("memory","Commands (memory):"),"",g("session","Commands (session):"),"",g("graph","Commands (graph query):"),"",g("external","External:")];terminal.printHuman(p);}function j(){v(),terminal.printHuman(["",terminal.renderLines({title:"Global flags & invocation",flat:["--cwd <dir> --config <path> --log-level <L> --print-logs --debug","Standalone CLI: easbot-memory <command>","Agent CLI: easbot memory <command>"]})]);}async function C(p){try{let{bootstrapLlm:t}=await import('@easbot/llm'),{Llm:e}=await import('./llm-7LQGYSUE.cjs');await t({target:e,cwd:p,subConfigPath:".easbot/memory.json",embedding:!0,graph:!0});}catch(t){b.warn("bootstrapLlm failed; Llm-related features will be disabled",{error:t instanceof Error?t.message:String(t)});}}async function A(p,t){let[e,...s]=p,c=t?.cwd??process.cwd(),d=t?.agentId??"default";if(!e)return j(),{code:0,handled:true,command:null};await C(c);try{switch(e){case "init":{let{parseInitOptions:n,runInit:a}=await import('./init-VTPJR56L.cjs'),r=n(s);if(r.help)return console.log("Usage: easbot-memory init [dir] [--force] [--json]"),{code:0,handled:!0,command:e};let o=r.workspaceDir?.trim()??c,i=await a({...r,ctxWorkspaceDir:o,agentId:d});if(r.json)terminal.emitJsonOk(i,{command:e});else {let u=i;terminal.printHuman([terminal.formatKnowledgeInit({packageName:"memory",configPath:u.configPath??u.dbPath,backend:"better-sqlite3",schemaVersion:u.schemaVersion,extras:{dbPath:u.dbPath,migrationsApplied:u.migrationsApplied,tablesCreated:u.tablesCreated,durationMs:`${u.durationMs}ms`}})],{title:"init memory workspace",boxed:!0});}return {code:0,handled:!0,command:e}}case "recall":{let{parseRecallOptions:n,runRecall:a,formatRecallText:r}=await import('./recall-JSTQDGGZ.cjs'),o=n(s);if(o.help)return console.log("Usage: easbot-memory recall --query <q> [--limit <n>] [--category <c>] [--min-importance <n>] [--json]"),{code:0,handled:!0,command:e};let i=await a({...o,workspaceDir:c,agentId:d});return o.json?terminal.emitJsonOk(i,{command:e}):terminal.printHuman([r(i)],{title:`recall (agentId=${d??"default"})`}),{code:0,handled:!0,command:e}}case "remember":{let{parseRememberOptions:n,runRemember:a,formatRememberText:r}=await import('./remember-Z4UJJN62.cjs'),o=n(s);if(o.help)return console.log("Usage: easbot-memory remember --content <text> --category <c> --importance <1-10> [--tag <t>] [--session <s>] [--json]"),{code:0,handled:!0,command:e};let i=await a({...o,workspaceDir:c,agentId:d});return o.json?terminal.emitJsonOk(i,{command:e}):terminal.printHuman([r(i)],{title:"remember (persist fact)"}),{code:0,handled:!0,command:e}}case "forget":{let{parseForgetOptions:n,runForget:a,formatForgetText:r}=await import('./forget-M4I6GVWI.cjs'),o=n(s);if(o.help)return console.log("Usage: easbot-memory forget (--fact-id <id> | --category <c> | --from <ISO> --to <ISO>) [--max-delete <n>] [--dry-run] [--json]"),{code:0,handled:!0,command:e};let i=await a({...o,workspaceDir:c,agentId:d});return o.json?terminal.emitJsonOk(i,{command:e}):terminal.printHuman([r(i)],{title:"forget (delete facts)"}),{code:0,handled:!0,command:e}}case "extract":{let{parseExtractOptions:n,runExtract:a,formatExtractText:r}=await import('./extract-O4IOL6BZ.cjs'),o=n(s);if(o.help)return console.log("Usage: easbot-memory extract --session <sessionId> [--last-n <n>] [--from-msg <id>] [--json]"),{code:0,handled:!0,command:e};let i=await a({...o,workspaceDir:c,agentId:d});return o.json?terminal.emitJsonOk(i,{command:e}):terminal.printHuman([r(i)],{title:"extract (from session)"}),{code:0,handled:!0,command:e}}case "consolidate":{let{parseConsolidateOptions:n,runConsolidate:a,formatConsolidateText:r}=await import('./consolidate-7GFUFPLX.cjs'),o=n(s);if(o.help)return console.log("Usage: easbot-memory consolidate [--window-days <n>] [--json]"),{code:0,handled:!0,command:e};let i=await a({...o,workspaceDir:c,agentId:d});return o.json?terminal.emitJsonOk(i,{command:e}):terminal.printHuman([r(i)],{title:"consolidate (pipeline)"}),{code:0,handled:!0,command:e}}case "sync":{let{parseSyncOptions:n,runSync:a,formatSyncText:r}=await import('./sync-6I2ZJUH6.cjs'),o=n(s);if(o.help)return console.log("Usage: easbot-memory sync [--window-days <n>] [--dry-run] [--json]"),console.log("Two-stage pipeline: (A) db \u2192 .md (idempotent skip on existing), (B) archive active/ files older than windowDays."),{code:0,handled:!0,command:e};let i=await a({...o,workspaceDir:c,agentId:d});return o.json?terminal.emitJsonOk(i,{command:e}):terminal.printHuman([r(i)],{title:"sync (db \u2192 .md + archive)"}),{code:0,handled:!0,command:e}}case "graph":{let{parseGraphOptions:n,runGraph:a,formatGraphText:r}=await import('./graph-AOMDJ6YA.cjs'),o=n(s);if(o.help)return console.log("Usage: easbot-memory graph [--query <q>] [--node-id <id>] [--max-depth <n>] [--max-nodes <n>] [--max-edges-per-node <n>] [--json]\n (note: `--depth` is an alias for `--max-depth`; old `--kind` / `--start-node` / `--scope` flags removed since service schema is strict)"),{code:0,handled:!0,command:e};let i=await a({...o,workspaceDir:c,agentId:d});return o.json?terminal.emitJsonOk(i,{command:e}):terminal.printHuman([r(i)],{title:"graph_query"}),{code:0,handled:!0,command:e}}case "status":{let{parseStatusOptions:n,runStatus:a}=await import('./status-DH33MQZV.cjs'),r=n(s);if(r.help)return console.log("Usage: easbot-memory status [--json]"),{code:0,handled:!0,command:e};let o=await a({...r,workspaceDir:c,agentId:d});return r.json?terminal.emitJsonOk(o,{command:e}):terminal.printHuman([terminal.formatKnowledgeStatus(K(o))],{title:"memory status",boxed:!0}),{code:0,handled:!0,command:e}}case "doctor":{let{parseDoctorOptions:n,runDoctor:a}=await import('./doctor-SCXUJRSG.cjs'),r=n(s);if(r.help)return console.log("Usage: easbot-memory doctor [--repair] [--json]"),{code:0,handled:!0,command:e};let o=await a({...r,workspaceDir:c});return r.json?terminal.emitJsonOk(o,{command:e}):terminal.printHuman([terminal.formatKnowledgeDoctor(M(o))],{title:"memory doctor",boxed:!0}),{code:0,handled:!0,command:e}}case "config":{let{parseConfigOptions:n,runConfig:a,formatConfigText:r}=await import('./config-I2I6U4XM.cjs'),o=n(s);if(o.help)return console.log("Usage: easbot-memory config [--json]"),{code:0,handled:!0,command:e};let i=a(o);return o.json?terminal.emitJsonOk(i,{command:e}):terminal.printHuman([r(i)],{title:"memory config"}),{code:0,handled:!0,command:e}}case "mcp":{let{parseMcpOptions:n,runMcp:a}=await import('./mcp-VIOHPDO5.cjs'),r=n(s);if(r.help)return console.log("Usage: easbot-memory mcp [start]"),console.log("Start a stdio MCP server exposing 10 memory tools:"),console.log(" recall / remember / forget / extract / consolidate"),console.log(" graph_query / status / doctor / init / sync"),{code:0,handled:!0,command:e};let o=await a(r);return r.json?terminal.emitJsonOk(o,{command:e}):terminal.printHuman([`memory mcp started (tools: ${o.tools.length})`],{title:"memory mcp server"}),{code:0,handled:!0,command:e}}default:return console.error(`Unknown command: ${e}`),console.error("Run `easbot-memory --help` for available commands."),{code:2,handled:!1,command:null}}}catch(n){let a=n instanceof Error?n.message:String(n);b.error("memory CLI command failed",{command:e,error:a,stack:n instanceof Error?n.stack:void 0});let r=t?.cwd??chunkCPRDIUQ4_cjs.f().worktree;return console.error(`[memory] ${r} :: ${e} failed: ${a}`),terminal.emitJsonError(e,a),{code:1,handled:true,command:e}}}function K(p){let t=p;return {packageName:"memory",rootDir:t.workspaceDir??"",configPath:t.configPath??"",configExists:typeof t.configExists=="boolean"?t.configExists:true,dbPath:t.dbPath??"",dbExists:typeof t.dbExists=="boolean"?t.dbExists:true,dbSize:typeof t.dbSize=="number"?t.dbSize:void 0,indexState:t.indexState,schemaVersion:typeof t.schemaVersion=="number"?t.schemaVersion:void 0,extractionVersion:typeof t.extractionVersion=="number"?t.extractionVersion:void 0,lastSyncAt:t.lastSyncAt,vectorEnabled:typeof t.vectorEnabled=="boolean"?t.vectorEnabled:void 0,embeddingDims:typeof t.embeddingDims=="number"?t.embeddingDims:void 0,llm:t.llm??{initialized:false,capabilities:{}},backend:t.backend,healthy:typeof t.healthy=="boolean"?t.healthy:true,recommendation:t.recommendation,dbStats:(()=>{let e=t.dbStats;if(e&&typeof e=="object"&&Object.keys(e).length>0)return {...e};let s=t.integrityStats;if(s&&typeof s=="object"&&Object.keys(s).length>0)return {...s}})(),extras:(()=>{let e={};if(typeof t.agentId=="string"&&(e.agent_id=t.agentId),typeof t.ftsAvailable=="boolean"&&(e.fts_available=t.ftsAvailable?"yes":"no"),t.factsByCategory&&typeof t.factsByCategory=="object"){let s=t.factsByCategory;for(let[c,d]of Object.entries(s))typeof d=="number"&&d>0&&(e[`facts/${c}`]=d);}if(t.meta&&typeof t.meta=="object")for(let[s,c]of Object.entries(t.meta))e[`meta/${s}`]=c===void 0?"\u2205":c;return Object.keys(e).length>0?e:void 0})()}}function M(p){let t=p,e=Array.isArray(t.checks)?t.checks:[],s=t.integrityStats,c=t.backendAvailable,d=s?{...s}:void 0;return {packageName:"memory",healthy:typeof t.healthy=="boolean"?t.healthy:false,durationMs:typeof t.durationMs=="number"?t.durationMs:0,checks:e.map(n=>({code:typeof n.code=="string"?n.code:"",severity:n.severity??"info",name:typeof n.name=="string"?n.name:"",message:typeof n.message=="string"?n.message:"",durationMs:typeof n.durationMs=="number"?n.durationMs:void 0,details:n.details})),dbStats:d,backendAvailable:c}}exports.a=S;exports.b=v;exports.c=j;exports.d=A;exports.e=M;
@@ -1,77 +0,0 @@
1
- import {a}from'./chunk-HQBRVVXS.mjs';import {Log,Filesystem}from'@easbot/utils';import {createSyncSqliteConnection}from'@easbot/database';var c=Log.create({service:"memory-schema-migrations"}),m=1,f=[{id:1,description:"v1 baseline: memory_facts / memory_vectors / embedding_cache / memory_facts_fts / nodes / edges / meta\uFF08\u4E0E v0.3.x createTables \u8F93\u51FA\u5BF9\u9F50\uFF0C\u8001 db \u8DD1\u8BE5\u8FC1\u79FB\u4E0D\u7834\u574F\u73B0\u6709\u8868\uFF09",up:[`CREATE TABLE IF NOT EXISTS memory_facts (
2
- id TEXT PRIMARY KEY,
3
- agent_id TEXT NOT NULL,
4
- session_id TEXT,
5
- msg_id TEXT,
6
- parent_msg_id TEXT,
7
- content TEXT NOT NULL,
8
- category TEXT NOT NULL,
9
- importance INTEGER NOT NULL CHECK(importance >= 1 AND importance <= 10),
10
- source TEXT NOT NULL CHECK(source IN ('session_self_write', 'historical')),
11
- tags TEXT,
12
- file_path TEXT,
13
- created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
14
- updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
15
- )`,"CREATE INDEX IF NOT EXISTS idx_memory_facts_agent_id ON memory_facts(agent_id)","CREATE INDEX IF NOT EXISTS idx_memory_facts_agent_category ON memory_facts(agent_id, category)","CREATE INDEX IF NOT EXISTS idx_memory_facts_agent_importance ON memory_facts(agent_id, importance DESC)","CREATE INDEX IF NOT EXISTS idx_memory_facts_created_at ON memory_facts(created_at)",`CREATE UNIQUE INDEX IF NOT EXISTS idx_memory_facts_session_msg_partial
16
- ON memory_facts(session_id, msg_id)
17
- WHERE msg_id IS NOT NULL`,`CREATE TABLE IF NOT EXISTS memory_vectors (
18
- fact_id TEXT PRIMARY KEY,
19
- embedding BLOB NOT NULL,
20
- FOREIGN KEY (fact_id) REFERENCES memory_facts(id) ON DELETE CASCADE
21
- )`,`CREATE TABLE IF NOT EXISTS embedding_cache (
22
- content_hash TEXT PRIMARY KEY,
23
- embedding BLOB NOT NULL,
24
- created_at DATETIME DEFAULT CURRENT_TIMESTAMP
25
- )`,`CREATE VIRTUAL TABLE IF NOT EXISTS memory_facts_fts USING fts5(
26
- fact_id UNINDEXED,
27
- agent_id UNINDEXED,
28
- content,
29
- tags,
30
- tokenize='porter unicode61'
31
- )`,`CREATE TABLE IF NOT EXISTS nodes (
32
- id INTEGER PRIMARY KEY AUTOINCREMENT,
33
- name TEXT NOT NULL,
34
- type TEXT NOT NULL,
35
- properties TEXT,
36
- embedding BLOB,
37
- createdAt DATETIME DEFAULT CURRENT_TIMESTAMP,
38
- updatedAt DATETIME DEFAULT CURRENT_TIMESTAMP
39
- )`,"CREATE INDEX IF NOT EXISTS idx_nodes_name ON nodes(name)","CREATE INDEX IF NOT EXISTS idx_nodes_type ON nodes(type)","CREATE INDEX IF NOT EXISTS idx_nodes_embedding ON nodes(embedding) WHERE embedding IS NOT NULL","CREATE UNIQUE INDEX IF NOT EXISTS idx_nodes_name_type ON nodes(name, type)",`CREATE TABLE IF NOT EXISTS fact_nodes (
40
- fact_id TEXT NOT NULL,
41
- node_id INTEGER NOT NULL,
42
- source TEXT NOT NULL DEFAULT 'kg_extract',
43
- score REAL NOT NULL DEFAULT 1.0,
44
- createdAt DATETIME DEFAULT CURRENT_TIMESTAMP,
45
- PRIMARY KEY (fact_id, node_id, source),
46
- FOREIGN KEY (fact_id) REFERENCES memory_facts(id) ON DELETE CASCADE,
47
- FOREIGN KEY (node_id) REFERENCES nodes(id) ON DELETE CASCADE
48
- )`,"CREATE INDEX IF NOT EXISTS idx_fact_nodes_node ON fact_nodes(node_id)","CREATE INDEX IF NOT EXISTS idx_fact_nodes_fact ON fact_nodes(fact_id)","CREATE INDEX IF NOT EXISTS idx_fact_nodes_source ON fact_nodes(source)",`CREATE TABLE IF NOT EXISTS edges (
49
- id INTEGER PRIMARY KEY AUTOINCREMENT,
50
- source INTEGER NOT NULL,
51
- target INTEGER NOT NULL,
52
- relation TEXT NOT NULL,
53
- properties TEXT,
54
- createdAt DATETIME DEFAULT CURRENT_TIMESTAMP,
55
- FOREIGN KEY (source) REFERENCES nodes(id) ON DELETE CASCADE,
56
- FOREIGN KEY (target) REFERENCES nodes(id) ON DELETE CASCADE
57
- )`,"CREATE INDEX IF NOT EXISTS idx_edges_source ON edges(source)","CREATE INDEX IF NOT EXISTS idx_edges_target ON edges(target)","CREATE INDEX IF NOT EXISTS idx_edges_relation ON edges(relation)","CREATE UNIQUE INDEX IF NOT EXISTS idx_edges_unique ON edges(source, target, relation)",`CREATE TABLE IF NOT EXISTS meta (
58
- key TEXT PRIMARY KEY,
59
- value TEXT
60
- )`,"ALTER TABLE nodes ADD COLUMN embedding BLOB","CREATE INDEX IF NOT EXISTS idx_nodes_embedding ON nodes(embedding) WHERE embedding IS NOT NULL"]}];function g(n,e=m,r={}){n.exec(`CREATE TABLE IF NOT EXISTS schema_migrations (
61
- id INTEGER PRIMARY KEY,
62
- applied_at DATETIME DEFAULT CURRENT_TIMESTAMP
63
- )`);let t=n.prepare("SELECT id FROM schema_migrations").all(),s=new Set(t.map(i=>i.id)),a={applied:[],pending:[],errors:[],currentVersion:t.length===0?0:Math.max(...t.map(i=>i.id)),targetVersion:e};for(let i of f){if(i.id>e)break;if(s.has(i.id)){a.pending.push(i.id);continue}if(r.dryRun){a.applied.push(i.id);continue}try{I(n,i.up),n.prepare("INSERT INTO schema_migrations (id) VALUES (?)").run(i.id),s.add(i.id),a.applied.push(i.id),c.info("migration applied",{id:i.id,description:i.description});}catch(o){let d=o instanceof Error?o.message:String(o),T=i.up[0]??"";a.errors.push({migrationId:i.id,sql:T,error:d}),c.warn("migration step failed",{id:i.id,error:d,sqlCount:i.up.length});}}return a}function I(n,e){for(let r of e)try{n.exec(r);}catch(t){let s=t instanceof Error?t.message:String(t);if(O(s)){c.debug("migration: column already exists, skipping",{sql:r.slice(0,80)});continue}throw t}}function O(n){return /duplicate column name/i.test(n)}function u(n){try{let e=n.prepare("SELECT id FROM schema_migrations").all();return e.length===0?0:Math.max(...e.map(r=>r.id))}catch{return 0}}var N=Log.create({service:"memory-database"}),_=class{constructor(e){a(this,"db",null);a(this,"storagePath");a(this,"backend","better-sqlite3");a(this,"initialized",false);a(this,"initPromise",null);this.storagePath=e===":memory:"?e:Filesystem.normalize(e);}async initialize(){if(!this.initialized){if(this.initPromise){await this.initPromise;return}this.initPromise=this.doInitialize();try{await this.initPromise,this.initialized=!0;}catch(e){try{this.db&&this.db.close();}catch{}throw this.db=null,this.initPromise=null,e}}}async doInitialize(){try{let e=this.openConnection();e.initialize(),this.db=e,this.applyPragmas(),this.runAllMigrations();}catch(e){let r=e instanceof Error?e.message:String(e);throw N.error("Database initialization failed",{error:r}),e}}openConnection(){return createSyncSqliteConnection({path:this.storagePath,backend:this.backend,walMode:true,foreignKeys:true,busyTimeoutMs:5e3})}applyPragmas(){if(this.db)try{this.db.pragma("synchronous = NORMAL"),this.db.pragma("cache_size = -64000"),this.db.pragma("temp_store = MEMORY"),this.db.pragma("foreign_keys = ON");}catch(e){N.warn("Failed to apply memory PRAGMAs",{error:String(e)});}}runAllMigrations(){if(!this.db)throw new Error("Database not initialized");let e=g(this.db,m);if(e.errors.length>0){let r=e.errors.map(t=>`migration ${t.migrationId}: ${t.error}`).join("; ");throw new Error(`Some migrations failed: ${r}`)}}query(e,r){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");try{let t=this.db.prepare(e);return r?t.all(...r):t.all()}catch(t){throw new Error(`Query failed: ${t.message}`)}}agentFilter(e){return typeof e=="string"&&e.trim().length>0?{where:"WHERE agent_id = ?",params:[e.trim()]}:{where:"",params:[]}}run(e,r){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");try{let t=this.db.prepare(e),s=r?t.run(...r):t.run();return {lastID:Number(s.lastInsertRowid),changes:s.changes}}catch(t){throw new Error(`Write failed: ${t.message}`)}}transaction(e){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");return this.db.transaction(e)()}prepare(e){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");return this.db.prepare(e)}exec(e){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");this.db.exec(e);}getDb(){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");return this.db}getPath(){return this.storagePath}getSchemaVersion(){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");return u(this.db)}close(){if(this.db){try{this.db.close();}catch(e){N.warn("Failed to close memory database",{error:String(e)});}this.db=null,this.initialized=false,this.initPromise=null;}}healthCheck(){try{return this.db?(this.db.exec("SELECT 1"),!0):!1}catch{return false}}checkIntegrity(){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");let e=p=>this.db.prepare(p).get().c,r={memory_facts:e("SELECT COUNT(*) as c FROM memory_facts"),memory_vectors:e("SELECT COUNT(*) as c FROM memory_vectors"),embedding_cache:e("SELECT COUNT(*) as c FROM embedding_cache"),memory_facts_fts:e("SELECT COUNT(*) as c FROM memory_facts_fts"),nodes:e("SELECT COUNT(*) as c FROM nodes"),edges:e("SELECT COUNT(*) as c FROM edges"),fact_nodes:e("SELECT COUNT(*) as c FROM fact_nodes"),meta:e("SELECT COUNT(*) as c FROM meta"),schema_migrations:e("SELECT COUNT(*) as c FROM schema_migrations")},t=[],s=e(`
64
- SELECT COUNT(*) as c FROM fact_nodes fn
65
- LEFT JOIN nodes n ON n.id = fn.node_id
66
- WHERE n.id IS NULL
67
- `);s>0&&t.push({severity:"error",message:`orphan node references (fact_nodes): ${s}`});let a=e(`
68
- SELECT COUNT(*) as c FROM edges e WHERE NOT EXISTS (SELECT 1 FROM nodes n WHERE n.id = e.source)
69
- `);a>0&&t.push({severity:"error",message:`orphan edges (source): ${a}`});let i=e(`
70
- SELECT COUNT(*) as c FROM edges e WHERE NOT EXISTS (SELECT 1 FROM nodes n WHERE n.id = e.target)
71
- `);i>0&&t.push({severity:"error",message:`orphan edges (target): ${i}`});let o=e("SELECT COUNT(*) as c FROM edges WHERE source = target");o>0&&t.push({severity:"warn",message:`self-loop edges: ${o}`});let d=e(`
72
- SELECT COUNT(*) as c FROM (
73
- SELECT fact_id FROM memory_facts_fts
74
- EXCEPT
75
- SELECT id FROM memory_facts
76
- )
77
- `);d>0&&t.push({severity:"warn",message:`FTS out of sync (orphan entries): ${d}`});let T=e("SELECT COUNT(*) as c FROM (SELECT id, COUNT(*) as c FROM memory_facts GROUP BY id HAVING c > 1)");T>0&&t.push({severity:"error",message:`duplicate fact ids: ${T}`});let l=e("SELECT COUNT(*) as c FROM memory_facts WHERE content IS NULL OR content = ''");return l>0&&t.push({severity:"error",message:`memory_facts with null/empty content: ${l}`}),{issues:t,stats:r}}getMeta(e){if(!this.db)throw new Error("Database not initialized");return this.db.prepare("SELECT value FROM meta WHERE key = ?").get(e)?.value??null}setMeta(e,r){if(!this.db)throw new Error("Database not initialized");this.db.prepare("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)").run(e,r);}};export{m as a,f as b,g as c,u as d,_ as e};