@easbot/memory 0.3.23 → 0.3.24
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +15 -5
- package/dist/chunks/{chunk-OU5TQHJE.cjs → chunk-46Y7MLBE.cjs} +1 -1
- package/dist/chunks/chunk-5VZKEZI4.cjs +67 -0
- package/dist/chunks/chunk-C3Z455VR.mjs +67 -0
- package/dist/chunks/{chunk-PJGILQSZ.mjs → chunk-FY4ILCIM.mjs} +5 -6
- package/dist/chunks/chunk-GL5U3MRI.mjs +64 -0
- package/dist/chunks/{chunk-EK34SXJ7.cjs → chunk-LYBUZDJK.cjs} +5 -6
- package/dist/chunks/chunk-MPGIP3IF.cjs +64 -0
- package/dist/chunks/{chunk-3EDNN7MP.mjs → chunk-PGJB2U24.mjs} +1 -1
- package/dist/chunks/cli-handler-KTFW5CCH.mjs +1 -0
- package/dist/chunks/cli-handler-Y43WWXOO.cjs +1 -0
- package/dist/chunks/consolidate-VGPUQRPU.mjs +2 -0
- package/dist/chunks/{consolidate-JGLVNSDT.cjs → consolidate-X52RRH2C.cjs} +1 -1
- package/dist/chunks/doctor-RNI5F6GO.mjs +1 -0
- package/dist/chunks/doctor-SJY3K3DV.cjs +1 -0
- package/dist/chunks/{extract-WH4DU4NQ.mjs → extract-ANENWMHZ.mjs} +1 -1
- package/dist/chunks/{extract-4ZGVF2DQ.cjs → extract-L2V2RMDQ.cjs} +1 -1
- package/dist/chunks/{forget-CRDWG4XE.mjs → forget-QNG6GELC.mjs} +1 -1
- package/dist/chunks/{forget-PARGCUIH.cjs → forget-SSGVAE5Y.cjs} +1 -1
- package/dist/chunks/graph-KNLZRAPI.mjs +3 -0
- package/dist/chunks/graph-WIKKSBLC.cjs +3 -0
- package/dist/chunks/{init-2ZTVBJ6N.mjs → init-2UNKNWR5.mjs} +1 -1
- package/dist/chunks/{init-EEWFFF4Y.cjs → init-UNDHFDAC.cjs} +1 -1
- package/dist/chunks/{mcp-ES7O3UKN.cjs → mcp-PRR2RYOP.cjs} +1 -1
- package/dist/chunks/{mcp-OAUOA4PI.mjs → mcp-RMLMXPZ7.mjs} +1 -1
- package/dist/chunks/recall-7TPMD7ZE.mjs +2 -0
- package/dist/chunks/{recall-LCKRI4TB.cjs → recall-M2EWX25U.cjs} +1 -1
- package/dist/chunks/{remember-OZOQ76IA.cjs → remember-BXVUUY5M.cjs} +1 -1
- package/dist/chunks/{remember-ZVTM3IP4.mjs → remember-H5CYMLG5.mjs} +1 -1
- package/dist/chunks/{status-6R335JGR.cjs → status-A2JC6NFH.cjs} +1 -1
- package/dist/chunks/{status-LHXMB3ZY.mjs → status-MJFDNSPW.mjs} +1 -1
- package/dist/chunks/stdio-server-43QC3XIS.mjs +1 -0
- package/dist/chunks/{stdio-server-IMJF7HB6.cjs → stdio-server-SXDIW3RQ.cjs} +1 -1
- package/dist/chunks/{sync-7VBREDVM.cjs → sync-3RWIZYR6.cjs} +1 -1
- package/dist/chunks/{sync-KWHUII26.mjs → sync-GPRNZLZA.mjs} +1 -1
- package/dist/cli.cjs +1 -1
- package/dist/cli.mjs +1 -1
- package/dist/index.cjs +4 -4
- package/dist/index.d.cts +7 -2
- package/dist/index.d.ts +7 -2
- package/dist/index.mjs +4 -4
- package/package.json +9 -9
- package/dist/chunks/chunk-2TBNGTSA.mjs +0 -65
- package/dist/chunks/chunk-5YDI4K2F.cjs +0 -65
- package/dist/chunks/chunk-K4K3YR6R.mjs +0 -66
- package/dist/chunks/chunk-MENFLGGM.cjs +0 -66
- package/dist/chunks/cli-handler-7HISH37M.cjs +0 -1
- package/dist/chunks/cli-handler-WOX5EG34.mjs +0 -1
- package/dist/chunks/consolidate-JBTOQWUX.mjs +0 -2
- package/dist/chunks/doctor-C7RIJGYC.cjs +0 -1
- package/dist/chunks/doctor-DLQO7QMW.mjs +0 -1
- package/dist/chunks/graph-NJJLGDZI.cjs +0 -3
- package/dist/chunks/graph-T66JXDLU.mjs +0 -3
- package/dist/chunks/recall-VMW7Y55X.mjs +0 -2
- package/dist/chunks/stdio-server-SONZIWC4.mjs +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export{b as MemoryStdioServer}from'./chunk-GL5U3MRI.mjs';import'./chunk-C3Z455VR.mjs';import'./chunk-FY4ILCIM.mjs';import'./chunk-WDVDYZ25.mjs';import'./chunk-6CQMBEIQ.mjs';import'./chunk-HQBRVVXS.mjs';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
'use strict';var
|
|
1
|
+
'use strict';var chunkMPGIP3IF_cjs=require('./chunk-MPGIP3IF.cjs');require('./chunk-5VZKEZI4.cjs'),require('./chunk-LYBUZDJK.cjs'),require('./chunk-CPRDIUQ4.cjs'),require('./chunk-J5XF2W4Z.cjs'),require('./chunk-M2YU5LAI.cjs');Object.defineProperty(exports,"MemoryStdioServer",{enumerable:true,get:function(){return chunkMPGIP3IF_cjs.b}});
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var chunk4GSXSIV5_cjs=require('./chunk-4GSXSIV5.cjs');require('./chunk-WQB4D6DZ.cjs');var
|
|
1
|
+
'use strict';var chunk4GSXSIV5_cjs=require('./chunk-4GSXSIV5.cjs');require('./chunk-WQB4D6DZ.cjs');var chunk5VZKEZI4_cjs=require('./chunk-5VZKEZI4.cjs');require('./chunk-LYBUZDJK.cjs'),require('./chunk-CPRDIUQ4.cjs'),require('./chunk-J5XF2W4Z.cjs'),require('./chunk-M2YU5LAI.cjs');async function w(e){let n=e.agentId?.trim()||"default",r=e.workspaceDir??process.cwd();return chunk5VZKEZI4_cjs.z("sync",{windowDays:e.windowDays,dryRun:e.dryRun??false},chunk5VZKEZI4_cjs.B(n,r))}function m(e){let n=e;return [chunk4GSXSIV5_cjs.b("sync",{windowDays:String(n.windowDays),dryRun:String(n.dryRun)},"sync complete (windowDays={{windowDays}}, dryRun={{dryRun}}):"),chunk4GSXSIV5_cjs.c("sync",{generatedCount:String(n.generatedCount),skippedCount:String(n.skippedCount),failedGenerateCount:String(n.failedGenerateCount),archivedCount:String(n.archivedCount),archiveThreshold:n.archiveThreshold}," - generated: {{generatedCount}}, skipped: {{skippedCount}}, failed: {{failedGenerateCount}}, archived: {{archivedCount}} (threshold: {{archiveThreshold}})"),` - duration: ${n.durationMs}ms`].join(`
|
|
2
2
|
`)}function f(e){let n={};for(let r=0;r<e.length;r++){let t=e[r];if(t===void 0)continue;let i=e[r+1];if(t==="--agent")n.agentId=i,r++;else if(t==="--window-days"){let o=Number(i);if(Number.isNaN(o)||o<1||o>3650)throw new Error(`--window-days must be an integer in [1, 3650], got: ${i??"(empty)"}`);n.windowDays=o,r++;}else t==="--dry-run"?n.dryRun=true:t==="--json"?n.json=true:(t==="--help"||t==="-h")&&(n.help=true);}return n}exports.formatSyncText=m;exports.parseSyncOptions=f;exports.runSync=w;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {b,c}from'./chunk-QYBWHFOX.mjs';import'./chunk-SWYQLQ7Z.mjs';import {
|
|
1
|
+
import {b,c}from'./chunk-QYBWHFOX.mjs';import'./chunk-SWYQLQ7Z.mjs';import {z,B}from'./chunk-C3Z455VR.mjs';import'./chunk-FY4ILCIM.mjs';import'./chunk-WDVDYZ25.mjs';import'./chunk-6CQMBEIQ.mjs';import'./chunk-HQBRVVXS.mjs';async function m(e){let n=e.agentId?.trim()||"default",r=e.workspaceDir??process.cwd();return z("sync",{windowDays:e.windowDays,dryRun:e.dryRun??false},B(n,r))}function f(e){let n=e;return [b("sync",{windowDays:String(n.windowDays),dryRun:String(n.dryRun)},"sync complete (windowDays={{windowDays}}, dryRun={{dryRun}}):"),c("sync",{generatedCount:String(n.generatedCount),skippedCount:String(n.skippedCount),failedGenerateCount:String(n.failedGenerateCount),archivedCount:String(n.archivedCount),archiveThreshold:n.archiveThreshold}," - generated: {{generatedCount}}, skipped: {{skippedCount}}, failed: {{failedGenerateCount}}, archived: {{archivedCount}} (threshold: {{archiveThreshold}})"),` - duration: ${n.durationMs}ms`].join(`
|
|
2
2
|
`)}function h(e){let n={};for(let r=0;r<e.length;r++){let t=e[r];if(t===void 0)continue;let i=e[r+1];if(t==="--agent")n.agentId=i,r++;else if(t==="--window-days"){let o=Number(i);if(Number.isNaN(o)||o<1||o>3650)throw new Error(`--window-days must be an integer in [1, 3650], got: ${i??"(empty)"}`);n.windowDays=o,r++;}else t==="--dry-run"?n.dryRun=true:t==="--json"?n.json=true:(t==="--help"||t==="-h")&&(n.help=true);}return n}export{f as formatSyncText,h as parseSyncOptions,m as runSync};
|
package/dist/cli.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
'use strict';var chunkM2YU5LAI_cjs=require('./chunks/chunk-M2YU5LAI.cjs'),fs=require('fs'),path=require('path'),url=require('url'),terminal=require('@easbot/terminal');var E=path.dirname(url.fileURLToPath(chunkM2YU5LAI_cjs.b));function A(){try{let t=path.join(E,"..","package.json");return JSON.parse(fs.readFileSync(t,"utf-8")).version??"0.0.0"}catch{return "0.0.0"}}var f=new Set(["DEBUG","INFO","WARN","ERROR"]);function N(t){let n={logLevel:"INFO",printLogs:false,debug:false};for(let i=0;i<t.length;i++){let e=t[i];if(e)if(e==="--cwd"&&i+1<t.length){let o=t[i+1];o&&!o.startsWith("-")&&(n.cwd=o,i++);}else if(e.startsWith("--cwd="))n.cwd=e.slice(6);else if(e==="--config"&&i+1<t.length){let o=t[i+1];o&&!o.startsWith("-")&&(n.configPath=o,i++);}else if(e.startsWith("--config="))n.configPath=e.slice(9);else if(e==="--log-level"&&i+1<t.length){let o=t[i+1];if(o&&!o.startsWith("-")){let r=o.toUpperCase();f.has(r)&&(n.logLevel=r,i++);}}else if(e.startsWith("--log-level=")){let o=e.slice(12).toUpperCase();f.has(o)&&(n.logLevel=o);}else e==="--print-logs"?n.printLogs=true:e==="--debug"&&(n.debug=true);}return n}async function R(){let t=process.argv.slice(2),n=A(),{loadEnv:i}=await import('@easbot/utils');i(),process.env.EASBOT_LANG||(process.env.EASBOT_LANG="en-US");let e=N(t),{Log:o}=await import('@easbot/utils'),{getXdgData:r}=await import('./chunks/interfaces-Q5OGU5EK.cjs'),h=path.join(r(),"memory","log");if(await o.init({logDir:h,print:e.printLogs,dev:e.debug||false,level:e.logLevel}),t.length===0){let{renderBanner:l}=await import('./chunks/cli-handler-
|
|
2
|
+
'use strict';var chunkM2YU5LAI_cjs=require('./chunks/chunk-M2YU5LAI.cjs'),fs=require('fs'),path=require('path'),url=require('url'),terminal=require('@easbot/terminal');var E=path.dirname(url.fileURLToPath(chunkM2YU5LAI_cjs.b));function A(){try{let t=path.join(E,"..","package.json");return JSON.parse(fs.readFileSync(t,"utf-8")).version??"0.0.0"}catch{return "0.0.0"}}var f=new Set(["DEBUG","INFO","WARN","ERROR"]);function N(t){let n={logLevel:"INFO",printLogs:false,debug:false};for(let i=0;i<t.length;i++){let e=t[i];if(e)if(e==="--cwd"&&i+1<t.length){let o=t[i+1];o&&!o.startsWith("-")&&(n.cwd=o,i++);}else if(e.startsWith("--cwd="))n.cwd=e.slice(6);else if(e==="--config"&&i+1<t.length){let o=t[i+1];o&&!o.startsWith("-")&&(n.configPath=o,i++);}else if(e.startsWith("--config="))n.configPath=e.slice(9);else if(e==="--log-level"&&i+1<t.length){let o=t[i+1];if(o&&!o.startsWith("-")){let r=o.toUpperCase();f.has(r)&&(n.logLevel=r,i++);}}else if(e.startsWith("--log-level=")){let o=e.slice(12).toUpperCase();f.has(o)&&(n.logLevel=o);}else e==="--print-logs"?n.printLogs=true:e==="--debug"&&(n.debug=true);}return n}async function R(){let t=process.argv.slice(2),n=A(),{loadEnv:i}=await import('@easbot/utils');i(),process.env.EASBOT_LANG||(process.env.EASBOT_LANG="en-US");let e=N(t),{Log:o}=await import('@easbot/utils'),{getXdgData:r}=await import('./chunks/interfaces-Q5OGU5EK.cjs'),h=path.join(r(),"memory","log");if(await o.init({logDir:h,print:e.printLogs,dev:e.debug||false,level:e.logLevel}),t.length===0){let{renderBanner:l}=await import('./chunks/cli-handler-Y43WWXOO.cjs');l();return}if(t[0]==="--help"||t[0]==="-h"){let{renderHelp:l}=await import('./chunks/cli-handler-Y43WWXOO.cjs');l();return}if(t[0]==="--version"||t[0]==="-v"){terminal.printHuman([terminal.formatInfo(n)]);return}let a=e.cwd??process.cwd(),{handleMemoryCli:m}=await import('./chunks/cli-handler-Y43WWXOO.cjs'),{setInstanceAdapter:u}=await import('./chunks/interfaces-Q5OGU5EK.cjs');u({directory:a,worktree:a});let{Llm:w}=await import('./chunks/llm-7LQGYSUE.cjs'),{bootstrapLlm:L,setAdapterRegistry:b}=await import('@easbot/llm'),{getGlobal:s,getInstance:c}=await import('./chunks/interfaces-Q5OGU5EK.cjs');b({config:void 0,instance:{getDirectory:()=>c().directory,getWorktree:()=>c().worktree},global:{home:s().Path.home,data:s().Path.data,cache:s().Path.cache,config:s().Path.config,state:s().Path.state,log:s().Path.log,bin:s().Path.bin},installation:{getVersion:()=>n,getChannel:()=>"local",getUserAgent:()=>`easbot-memory/${n}`}}),await L({target:w,cwd:a,subConfigPath:".easbot/memory.json",embedding:true,graph:true});let g=await m(t,{version:n,cwd:a});g.code!==0&&(process.exitCode=g.code);}R().catch(t=>{console.error(t),process.exitCode=1;}).finally(async()=>{try{let{Log:t}=await import('@easbot/utils');await t.close();}catch{}process.exit(process.exitCode??0);});
|
package/dist/cli.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {readFileSync}from'fs';import {dirname,join}from'path';import {fileURLToPath}from'url';import {printHuman,formatInfo}from'@easbot/terminal';var G=dirname(fileURLToPath(import.meta.url));function E(){try{let t=join(G,"..","package.json");return JSON.parse(readFileSync(t,"utf-8")).version??"0.0.0"}catch{return "0.0.0"}}var p=new Set(["DEBUG","INFO","WARN","ERROR"]);function A(t){let n={logLevel:"INFO",printLogs:false,debug:false};for(let i=0;i<t.length;i++){let e=t[i];if(e)if(e==="--cwd"&&i+1<t.length){let o=t[i+1];o&&!o.startsWith("-")&&(n.cwd=o,i++);}else if(e.startsWith("--cwd="))n.cwd=e.slice(6);else if(e==="--config"&&i+1<t.length){let o=t[i+1];o&&!o.startsWith("-")&&(n.configPath=o,i++);}else if(e.startsWith("--config="))n.configPath=e.slice(9);else if(e==="--log-level"&&i+1<t.length){let o=t[i+1];if(o&&!o.startsWith("-")){let r=o.toUpperCase();p.has(r)&&(n.logLevel=r,i++);}}else if(e.startsWith("--log-level=")){let o=e.slice(12).toUpperCase();p.has(o)&&(n.logLevel=o);}else e==="--print-logs"?n.printLogs=true:e==="--debug"&&(n.debug=true);}return n}async function N(){let t=process.argv.slice(2),n=E(),{loadEnv:i}=await import('@easbot/utils');i(),process.env.EASBOT_LANG||(process.env.EASBOT_LANG="en-US");let e=A(t),{Log:o}=await import('@easbot/utils'),{getXdgData:r}=await import('./chunks/interfaces-LPJU4KS3.mjs'),d=join(r(),"memory","log");if(await o.init({logDir:d,print:e.printLogs,dev:e.debug||false,level:e.logLevel}),t.length===0){let{renderBanner:l}=await import('./chunks/cli-handler-
|
|
2
|
+
import {readFileSync}from'fs';import {dirname,join}from'path';import {fileURLToPath}from'url';import {printHuman,formatInfo}from'@easbot/terminal';var G=dirname(fileURLToPath(import.meta.url));function E(){try{let t=join(G,"..","package.json");return JSON.parse(readFileSync(t,"utf-8")).version??"0.0.0"}catch{return "0.0.0"}}var p=new Set(["DEBUG","INFO","WARN","ERROR"]);function A(t){let n={logLevel:"INFO",printLogs:false,debug:false};for(let i=0;i<t.length;i++){let e=t[i];if(e)if(e==="--cwd"&&i+1<t.length){let o=t[i+1];o&&!o.startsWith("-")&&(n.cwd=o,i++);}else if(e.startsWith("--cwd="))n.cwd=e.slice(6);else if(e==="--config"&&i+1<t.length){let o=t[i+1];o&&!o.startsWith("-")&&(n.configPath=o,i++);}else if(e.startsWith("--config="))n.configPath=e.slice(9);else if(e==="--log-level"&&i+1<t.length){let o=t[i+1];if(o&&!o.startsWith("-")){let r=o.toUpperCase();p.has(r)&&(n.logLevel=r,i++);}}else if(e.startsWith("--log-level=")){let o=e.slice(12).toUpperCase();p.has(o)&&(n.logLevel=o);}else e==="--print-logs"?n.printLogs=true:e==="--debug"&&(n.debug=true);}return n}async function N(){let t=process.argv.slice(2),n=E(),{loadEnv:i}=await import('@easbot/utils');i(),process.env.EASBOT_LANG||(process.env.EASBOT_LANG="en-US");let e=A(t),{Log:o}=await import('@easbot/utils'),{getXdgData:r}=await import('./chunks/interfaces-LPJU4KS3.mjs'),d=join(r(),"memory","log");if(await o.init({logDir:d,print:e.printLogs,dev:e.debug||false,level:e.logLevel}),t.length===0){let{renderBanner:l}=await import('./chunks/cli-handler-KTFW5CCH.mjs');l();return}if(t[0]==="--help"||t[0]==="-h"){let{renderHelp:l}=await import('./chunks/cli-handler-KTFW5CCH.mjs');l();return}if(t[0]==="--version"||t[0]==="-v"){printHuman([formatInfo(n)]);return}let a=e.cwd??process.cwd(),{handleMemoryCli:m}=await import('./chunks/cli-handler-KTFW5CCH.mjs'),{setInstanceAdapter:h}=await import('./chunks/interfaces-LPJU4KS3.mjs');h({directory:a,worktree:a});let{Llm:u}=await import('./chunks/llm-UHTBU2HA.mjs'),{bootstrapLlm:w,setAdapterRegistry:L}=await import('@easbot/llm'),{getGlobal:s,getInstance:c}=await import('./chunks/interfaces-LPJU4KS3.mjs');L({config:void 0,instance:{getDirectory:()=>c().directory,getWorktree:()=>c().worktree},global:{home:s().Path.home,data:s().Path.data,cache:s().Path.cache,config:s().Path.config,state:s().Path.state,log:s().Path.log,bin:s().Path.bin},installation:{getVersion:()=>n,getChannel:()=>"local",getUserAgent:()=>`easbot-memory/${n}`}}),await w({target:u,cwd:a,subConfigPath:".easbot/memory.json",embedding:true,graph:true});let g=await m(t,{version:n,cwd:a});g.code!==0&&(process.exitCode=g.code);}N().catch(t=>{console.error(t),process.exitCode=1;}).finally(async()=>{try{let{Log:t}=await import('@easbot/utils');await t.close();}catch{}process.exit(process.exitCode??0);});
|
package/dist/index.cjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
'use strict';require('./chunks/chunk-URADAZYW.cjs');var
|
|
1
|
+
'use strict';require('./chunks/chunk-URADAZYW.cjs');var chunk46Y7MLBE_cjs=require('./chunks/chunk-46Y7MLBE.cjs'),chunkMPGIP3IF_cjs=require('./chunks/chunk-MPGIP3IF.cjs'),chunk5VZKEZI4_cjs=require('./chunks/chunk-5VZKEZI4.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:chunk5VZKEZI4_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 chunk5VZKEZI4_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}]
|
|
2
2
|
${n.join(`
|
|
3
|
-
`)}`,logLine:`session-start: injected ${
|
|
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 chunk5VZKEZI4_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 chunk5VZKEZI4_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
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
|
|
6
|
-
`);try{return {ok:!0,logLine:`post-tool-failure: wrote error_pattern fact ${(await
|
|
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 chunk5VZKEZI4_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 chunk46Y7MLBE_cjs.a}});Object.defineProperty(exports,"handleMemoryCli",{enumerable:true,get:function(){return chunk46Y7MLBE_cjs.d}});Object.defineProperty(exports,"renderBanner",{enumerable:true,get:function(){return chunk46Y7MLBE_cjs.b}});Object.defineProperty(exports,"renderHelp",{enumerable:true,get:function(){return chunk46Y7MLBE_cjs.c}});Object.defineProperty(exports,"MemoryStdioServer",{enumerable:true,get:function(){return chunkMPGIP3IF_cjs.b}});Object.defineProperty(exports,"renderOperationMarkdown",{enumerable:true,get:function(){return chunkMPGIP3IF_cjs.a}});Object.defineProperty(exports,"ALL_OPS",{enumerable:true,get:function(){return chunk5VZKEZI4_cjs.y}});Object.defineProperty(exports,"GraphStore",{enumerable:true,get:function(){return chunk5VZKEZI4_cjs.a}});Object.defineProperty(exports,"OP_REGISTRY",{enumerable:true,get:function(){return chunk5VZKEZI4_cjs.x}});Object.defineProperty(exports,"consolidate",{enumerable:true,get:function(){return chunk5VZKEZI4_cjs.r}});Object.defineProperty(exports,"doctor",{enumerable:true,get:function(){return chunk5VZKEZI4_cjs.w}});Object.defineProperty(exports,"executeOp",{enumerable:true,get:function(){return chunk5VZKEZI4_cjs.z}});Object.defineProperty(exports,"extract",{enumerable:true,get:function(){return chunk5VZKEZI4_cjs.q}});Object.defineProperty(exports,"forget",{enumerable:true,get:function(){return chunk5VZKEZI4_cjs.p}});Object.defineProperty(exports,"graphQuery",{enumerable:true,get:function(){return chunk5VZKEZI4_cjs.t}});Object.defineProperty(exports,"init",{enumerable:true,get:function(){return chunk5VZKEZI4_cjs.u}});Object.defineProperty(exports,"recall",{enumerable:true,get:function(){return chunk5VZKEZI4_cjs.b}});Object.defineProperty(exports,"remember",{enumerable:true,get:function(){return chunk5VZKEZI4_cjs.n}});Object.defineProperty(exports,"status",{enumerable:true,get:function(){return chunk5VZKEZI4_cjs.v}});Object.defineProperty(exports,"sync",{enumerable:true,get:function(){return chunk5VZKEZI4_cjs.s}});Object.defineProperty(exports,"update",{enumerable:true,get:function(){return chunk5VZKEZI4_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;
|
package/dist/index.d.cts
CHANGED
|
@@ -210,6 +210,7 @@ interface RecallParams {
|
|
|
210
210
|
minScore?: number;
|
|
211
211
|
includeGraph?: boolean;
|
|
212
212
|
depth?: number;
|
|
213
|
+
maxEdgesPerNode?: number;
|
|
213
214
|
includeShared?: boolean;
|
|
214
215
|
}
|
|
215
216
|
interface RecallResult {
|
|
@@ -300,6 +301,7 @@ interface ExtractResult {
|
|
|
300
301
|
interface ConsolidateParams {
|
|
301
302
|
windowDays?: number;
|
|
302
303
|
dryRun?: boolean;
|
|
304
|
+
fromTime?: string;
|
|
303
305
|
}
|
|
304
306
|
interface ConsolidateResult {
|
|
305
307
|
totalFacts: number;
|
|
@@ -310,10 +312,12 @@ interface ConsolidateResult {
|
|
|
310
312
|
durationMs: number;
|
|
311
313
|
}
|
|
312
314
|
interface GraphQueryParams {
|
|
313
|
-
|
|
315
|
+
nodeId?: number;
|
|
316
|
+
query?: string;
|
|
314
317
|
type?: string;
|
|
315
318
|
depth?: number;
|
|
316
319
|
maxNodes?: number;
|
|
320
|
+
maxEdgesPerNode?: number;
|
|
317
321
|
scope?: KGScope;
|
|
318
322
|
relation?: string;
|
|
319
323
|
}
|
|
@@ -387,6 +391,7 @@ interface SyncResult {
|
|
|
387
391
|
skippedCount: number;
|
|
388
392
|
failedGenerateCount: number;
|
|
389
393
|
archivedCount: number;
|
|
394
|
+
failedArchivePaths: string[];
|
|
390
395
|
archiveThreshold: string;
|
|
391
396
|
archivedRecords: Array<{
|
|
392
397
|
source: string;
|
|
@@ -611,7 +616,7 @@ declare class MemoryDatabaseManager {
|
|
|
611
616
|
declare class GraphStore {
|
|
612
617
|
private db;
|
|
613
618
|
constructor(db: SyncSqliteConnection);
|
|
614
|
-
upsertNode(name: string, type: string, properties?: Record<string, unknown>,
|
|
619
|
+
upsertNode(name: string, type: string, properties?: Record<string, unknown>, _ownerAgentId?: string | null): Promise<number>;
|
|
615
620
|
deleteNode(id: number): Promise<void>;
|
|
616
621
|
upsertEdge(source: number, target: number, relation: string, properties?: Record<string, unknown>): Promise<number>;
|
|
617
622
|
queryNodes(filter?: NodeQueryFilter): Promise<MemoryNode[]>;
|
package/dist/index.d.ts
CHANGED
|
@@ -210,6 +210,7 @@ interface RecallParams {
|
|
|
210
210
|
minScore?: number;
|
|
211
211
|
includeGraph?: boolean;
|
|
212
212
|
depth?: number;
|
|
213
|
+
maxEdgesPerNode?: number;
|
|
213
214
|
includeShared?: boolean;
|
|
214
215
|
}
|
|
215
216
|
interface RecallResult {
|
|
@@ -300,6 +301,7 @@ interface ExtractResult {
|
|
|
300
301
|
interface ConsolidateParams {
|
|
301
302
|
windowDays?: number;
|
|
302
303
|
dryRun?: boolean;
|
|
304
|
+
fromTime?: string;
|
|
303
305
|
}
|
|
304
306
|
interface ConsolidateResult {
|
|
305
307
|
totalFacts: number;
|
|
@@ -310,10 +312,12 @@ interface ConsolidateResult {
|
|
|
310
312
|
durationMs: number;
|
|
311
313
|
}
|
|
312
314
|
interface GraphQueryParams {
|
|
313
|
-
|
|
315
|
+
nodeId?: number;
|
|
316
|
+
query?: string;
|
|
314
317
|
type?: string;
|
|
315
318
|
depth?: number;
|
|
316
319
|
maxNodes?: number;
|
|
320
|
+
maxEdgesPerNode?: number;
|
|
317
321
|
scope?: KGScope;
|
|
318
322
|
relation?: string;
|
|
319
323
|
}
|
|
@@ -387,6 +391,7 @@ interface SyncResult {
|
|
|
387
391
|
skippedCount: number;
|
|
388
392
|
failedGenerateCount: number;
|
|
389
393
|
archivedCount: number;
|
|
394
|
+
failedArchivePaths: string[];
|
|
390
395
|
archiveThreshold: string;
|
|
391
396
|
archivedRecords: Array<{
|
|
392
397
|
source: string;
|
|
@@ -611,7 +616,7 @@ declare class MemoryDatabaseManager {
|
|
|
611
616
|
declare class GraphStore {
|
|
612
617
|
private db;
|
|
613
618
|
constructor(db: SyncSqliteConnection);
|
|
614
|
-
upsertNode(name: string, type: string, properties?: Record<string, unknown>,
|
|
619
|
+
upsertNode(name: string, type: string, properties?: Record<string, unknown>, _ownerAgentId?: string | null): Promise<number>;
|
|
615
620
|
deleteNode(id: number): Promise<void>;
|
|
616
621
|
upsertEdge(source: number, target: number, relation: string, properties?: Record<string, unknown>): Promise<number>;
|
|
617
622
|
queryNodes(filter?: NodeQueryFilter): Promise<MemoryNode[]>;
|
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-
|
|
1
|
+
import'./chunks/chunk-QF5S5MG7.mjs';export{a as COMMANDS_HELP,d as handleMemoryCli,b as renderBanner,c as renderHelp}from'./chunks/chunk-PGJB2U24.mjs';export{b as MemoryStdioServer,a as renderOperationMarkdown}from'./chunks/chunk-GL5U3MRI.mjs';import {z as z$1,A}from'./chunks/chunk-C3Z455VR.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-C3Z455VR.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}]
|
|
2
2
|
${n.join(`
|
|
3
|
-
`)}`,logLine:`session-start: injected ${
|
|
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
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
|
|
6
|
-
`);try{return {ok:!0,logLine:`post-tool-failure: wrote error_pattern fact ${(await
|
|
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};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@easbot/memory",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.24",
|
|
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.
|
|
58
|
-
"@easbot/
|
|
59
|
-
"@easbot/
|
|
60
|
-
"@easbot/
|
|
61
|
-
"@easbot/utils": "0.3.
|
|
62
|
-
"@easbot/local-model-sdk": "0.3.
|
|
63
|
-
"@easbot/
|
|
64
|
-
"@easbot/
|
|
57
|
+
"@easbot/database": "0.3.24",
|
|
58
|
+
"@easbot/mcp": "0.3.24",
|
|
59
|
+
"@easbot/terminal": "0.3.24",
|
|
60
|
+
"@easbot/types": "0.3.24",
|
|
61
|
+
"@easbot/utils": "0.3.24",
|
|
62
|
+
"@easbot/local-model-sdk": "0.3.24",
|
|
63
|
+
"@easbot/llm": "0.3.24",
|
|
64
|
+
"@easbot/ollama-sdk": "0.3.24"
|
|
65
65
|
},
|
|
66
66
|
"devDependencies": {
|
|
67
67
|
"@types/node": "^25.9.5",
|
|
@@ -1,65 +0,0 @@
|
|
|
1
|
-
import {e,a as a$2}from'./chunk-PJGILQSZ.mjs';import {j}from'./chunk-WDVDYZ25.mjs';import {a as a$1}from'./chunk-6CQMBEIQ.mjs';import {a}from'./chunk-HQBRVVXS.mjs';import {Log,Locale,formatLocalISO}from'@easbot/utils';import {z}from'zod';import {randomBytes,createHash}from'crypto';import {GraphProvider,probeEmbeddingDims,syncMeta}from'@easbot/llm';import K from'fs/promises';import pe from'path';import {writeFileSync}from'fs';import {createRequire}from'module';import {EMBEDDING_DIMS_CONSISTENCY_CHECK,DEFAULT_SEARCH_CONFIG}from'@easbot/types';var he=Log.create({service:"memory.graph-store"}),ee=class{constructor(e){a(this,"db");this.db=e;}async upsertNode(e,r,n,o){let c=Date.now(),s=JSON.stringify(n??{}),i=this.db.prepare("SELECT id FROM nodes WHERE name = ? AND type = ? LIMIT 1").get(e,r);if(i)return this.db.prepare("UPDATE nodes SET properties = ?, updatedAt = ? WHERE id = ?").run(s,c,i.id),i.id;let g=this.db.prepare("INSERT INTO nodes (name, type, properties, owner_agent_id, createdAt, updatedAt) VALUES (?, ?, ?, ?, ?, ?)").run(e,r,s,o??null,c,c);return Number(g.lastInsertRowid)}async deleteNode(e){this.db.prepare("DELETE FROM nodes WHERE id = ?").run(e);}async upsertEdge(e,r,n,o){let c=this.db.prepare("INSERT OR REPLACE INTO edges (source, target, relation, properties, createdAt) VALUES (?, ?, ?, ?, ?)").run(e,r,n,JSON.stringify(o??{}),Date.now());return Number(c.lastInsertRowid)}async queryNodes(e={}){let r="SELECT id, name, type, properties, owner_agent_id, createdAt, updatedAt FROM nodes",n=[],o=[];if(e.ids&&e.ids.length>0){let s=e.ids.map(i=>typeof i=="string"?parseInt(i,10):i).filter(i=>!Number.isNaN(i));o.push(`id IN (${s.map(()=>"?").join(", ")})`),n.push(...s);}e.name&&(o.push("name LIKE ?"),n.push(`%${e.name}%`)),e.type&&(o.push("type = ?"),n.push(e.type)),St(o,n,e.agentId,e.scope??"agent_only"),o.length>0&&(r+=` WHERE ${o.join(" AND ")}`),r+=" ORDER BY id",e.limit&&(r+=" LIMIT ?",n.push(e.limit)),he.debug("queryNodes",{sql:r,params:n,filter:e});let c=this.db.prepare(r).all(...n);return he.debug("queryNodes result",{count:c.length}),c.map(s=>({id:s.id,name:s.name,type:s.type,properties:s.properties?JSON.parse(s.properties):void 0,createdAt:s.createdAt,updatedAt:s.updatedAt,ownerAgentId:s.owner_agent_id}))}async queryEdges(e={}){let r="SELECT e.id, e.source, e.target, e.relation, e.properties, e.createdAt FROM edges e",n=[],o=[];if(e.ids&&e.ids.length>0&&(o.push(`e.id IN (${e.ids.map(()=>"?").join(", ")})`),n.push(...e.ids)),e.source!==void 0&&(o.push("e.source = ?"),n.push(e.source)),e.target!==void 0&&(o.push("e.target = ?"),n.push(e.target)),e.sourceOrTarget&&e.sourceOrTarget.length>0){let l=e.sourceOrTarget.map(p=>typeof p=="string"?parseInt(p,10):p).filter(p=>!Number.isNaN(p));o.push(`(e.source IN (${l.map(()=>"?").join(", ")}) OR e.target IN (${l.map(()=>"?").join(", ")}))`),n.push(...l,...l);}e.relation&&(o.push("e.relation = ?"),n.push(e.relation)),o.length>0&&(r+=` WHERE ${o.join(" AND ")}`),r+=" ORDER BY e.id",e.limit&&(r+=" LIMIT ?",n.push(e.limit)),he.debug("queryEdges",{sql:r,params:n,filter:e});let c=this.db.prepare(r).all(...n);he.debug("queryEdges result",{count:c.length});let s=[...new Set(c.map(l=>l.target))],i=s.length>0?await this.queryNodes({ids:s,limit:s.length}):[],g=new Map(i.map(l=>[l.id,l]));return c.map(l=>{let p={id:l.id,source:l.source,target:l.target,relation:l.relation,properties:l.properties?JSON.parse(l.properties):void 0,createdAt:l.createdAt},y=g.get(l.target);return y&&(p.targetNode=y),p})}async queryNeighbors(e,r=1,n){let o=n?.agentId,c=n?.scope??"agent_only",s=new Set,i=[{id:e,level:0}],g=[],l=n?.maxEdgesPerNode??50;for(;i.length>0;){let p=i.shift();if(!p)break;if(s.has(p.id)||p.level>r)continue;s.add(p.id);let h=(await this.queryNodes({ids:[p.id],limit:1,agentId:o,scope:c}))[0];if(!h)continue;let M=await this.queryEdges({sourceOrTarget:[p.id],limit:l}),D=o?await Rt(this,M,o,c):M;if(g.push({...h,edges:D}),p.level<r)for(let I of D){let u=I.source===p.id?I.target:I.source;s.has(u)||i.push({id:u,level:p.level+1});}}return g}};async function Rt(t,e,r,n){if(e.length===0)return e;let o=new Set;for(let i of e)o.add(i.source),o.add(i.target);let c=await t.queryNodes({ids:Array.from(o),agentId:r,scope:n,limit:o.size}),s=new Set(c.map(i=>i.id));return e.filter(i=>s.has(i.source)&&s.has(i.target))}function St(t,e,r,n){if(r)switch(n){case "agent_only":t.push("owner_agent_id = ?"),e.push(r);break;case "shared_only":t.push("owner_agent_id IS NULL");break;case "both":t.push("(owner_agent_id = ? OR owner_agent_id IS NULL)"),e.push(r);break}}var S=class extends Error{constructor(r,n,o){super(r);a(this,"code",n);a(this,"details",o);this.name="ServiceError";}},ce=class extends S{constructor(e,r=[]){super(`Memory not found: ${e}`,"NOT_FOUND",{memoryId:e,candidates:r});}};var be=class extends S{constructor(){super("ctx.agentId is required for memory service (ADR 0055 per-agent isolation)","AGENT_ID_REQUIRED");}},de=class extends S{constructor(e,r){super(`Trust denied for operation "${e}": ${r}`,"TRUST_DENIED",{operation:e,reason:r});}},me=class extends S{constructor(e,r){super(`Memory ${e} has ${r} references (force=false)`,"HAS_REFERENCES",{memoryId:e,referenceCount:r});}},le=class extends S{constructor(e){super(`dryRun mode: ${e} memories matched but not deleted`,"DRY_RUN_NO_DELETE",{matchedCount:e});}},ge=class extends S{constructor(e,r){super(`Matched ${e} memories exceeds maxDelete=${r}`,"MAX_DELETE_EXCEEDED",{matched:e,maxDelete:r});}};function H(t){if(typeof t.agentId!="string"||t.agentId.trim().length===0)throw new be}function Q(t,e){if(t.remote!==false)throw new de(e,"requires trusted local caller (CLI / agent tool / MCP with remote=false)")}function Ee(t,e,r){if(e!=="agent_only"&&t.remote!==false)throw new de(r,`scope="${e}" requires trusted local caller (cross-agent access denied)`)}function te(t){if(!t.dbPath||t.dbPath.trim().length===0)throw new S("service ctx.dbPath is required (MemoryKnowledgeConfigWithModels.database.path)","INTERNAL")}var ne=Log.create({service:"memory.service.recall"});async function Be(t,e$1){let r=Date.now();if(H(t),te(t),!e$1.query||e$1.query.trim().length===0)throw new S("recall requires non-empty `query`","CONTENT_REQUIRED");let n=e$1.includeShared?"both":"agent_only";e$1.includeGraph&&Ee(t,n,"recall"),ne.debug("recall invoked",{agentId:t.agentId,query:e$1.query,category:e$1.category,maxResults:e$1.maxResults,includeGraph:e$1.includeGraph,scope:n});let o=e$1.maxResults??10,c=e$1.minScore??0,s=[],i=new e(t.dbPath);try{await i.initialize();let g=a$1.isInitialized()&&a$1.capabilities().embedding===!0,l=await _t(i,t.agentId,e$1.query,{category:e$1.category,minImportance:e$1.minImportance,fromTime:e$1.fromTime,toTime:e$1.toTime,limit:o,minScore:c,hasEmbedding:g}),p;if(e$1.includeGraph&&l.length>0)try{let h=new ee(i.getDb()),M=e$1.depth??1,D=l.flatMap(v=>(v.nodes??[]).map(b=>b.id)).slice(0,5),I=new Set,u=new Map;for(let v of D){let b=await h.queryNeighbors(v,M,{agentId:t.agentId,scope:n,maxEdgesPerNode:10});for(let _ of b)I.add(_.id),u.set(_.id,_.edges??[]);}let E=I.size>0?i.query(`SELECT id, name, type FROM nodes WHERE id IN (${Array.from(I).map(()=>"?").join(",")})`,Array.from(I)):[],C=Array.from(u.values()).flat();p={nodes:E.map(v=>({id:v.id,name:v.name,type:v.type,createdAt:"",updatedAt:""})),edges:C};}catch(h){let M=h instanceof Error?h.message:String(h);ne.warn("recall: KG neighbor query failed",{error:M}),s.push(`kg_neighbor_query_failed: ${M}`),p={nodes:[],edges:[]};}let y=Date.now()-r;return {hits:l,total:l.length,truncated:l.length>=o,durationMs:y,graph:p,...s.length>0?{warnings:s}:{}}}catch(g){throw g instanceof S?g:new S(`recall failed: ${g instanceof Error?g.message:String(g)}`,"INTERNAL",{cause:g instanceof Error?g.message:String(g)})}finally{i.close();}}async function _t(t,e,r,n){let o=["mf.agent_id = ?"],c=[e];n.category&&(o.push("mf.category = ?"),c.push(n.category)),n.minImportance!==void 0&&(o.push("mf.importance >= ?"),c.push(n.minImportance)),n.fromTime&&(o.push("mf.created_at >= ?"),c.push(n.fromTime)),n.toTime&&(o.push("mf.created_at <= ?"),c.push(n.toTime));let s=o.join(" AND "),i=null;if(n.hasEmbedding)try{i=await a$1.embedText(r);}catch(f){ne.warn("recall: query embedding failed, falling back to FTS-only",{error:f instanceof Error?f.message:String(f)}),i=null;}let g=Math.max(n.limit*100,1e3),[l,p]=await Promise.all([i?Dt(t,i,s,c,g):Promise.resolve([]),vt(t,r,s,c,n.limit)]),y=i?.7:0,h=i?.3:1,M=y+h,D=y/M,I=h/M,u=new Map;for(let f of l)u.set(f.id,f.score*D);for(let f of p)u.set(f.id,(u.get(f.id)??0)+f.score*I);let E=Array.from(u.entries()).sort((f,O)=>O[1]-f[1]).map(([f])=>f).slice(0,n.limit);if(E.length===0)return [];let C=E.map(()=>"?").join(","),v=t.query(`SELECT
|
|
2
|
-
mf.id,
|
|
3
|
-
mf.category,
|
|
4
|
-
mf.importance,
|
|
5
|
-
mf.agent_id as agentId,
|
|
6
|
-
mf.content as content,
|
|
7
|
-
SUBSTR(mf.content, 1, 200) as snippet,
|
|
8
|
-
mf.created_at as createdAt,
|
|
9
|
-
mf.updated_at as updatedAt,
|
|
10
|
-
mf.source,
|
|
11
|
-
mf.file_path as filePath,
|
|
12
|
-
mf.tags,
|
|
13
|
-
mf.session_id as sessionId,
|
|
14
|
-
mf.msg_id as msgId,
|
|
15
|
-
mf.parent_msg_id as parentMsgId
|
|
16
|
-
FROM memory_facts mf
|
|
17
|
-
WHERE mf.id IN (${C})`,E),b=Mt(t,v.map(f=>f.id)),_=Date.now();return v.map(f=>{let O=u.get(f.id)??0,F=(_-new Date(f.createdAt).getTime())/864e5,k=Math.exp(-0.05*F),j=(f.importance-1)/9,z=.4*O+.3*k+.3*j,V;if(f.tags)try{let d=JSON.parse(f.tags);Array.isArray(d)&&(V=d.filter(m=>typeof m=="string"));}catch{}return {memoryId:f.id,category:f.category,importance:f.importance,agentId:f.agentId,content:f.content,snippet:f.snippet,score:z,createdAt:f.createdAt,updatedAt:f.updatedAt,source:f.source,filePath:f.filePath??void 0,tags:V,sessionId:f.sessionId??void 0,msgId:f.msgId??void 0,parentMsgId:f.parentMsgId??void 0,nodes:b.get(f.id)??[]}}).filter(f=>f.score>=n.minScore).sort((f,O)=>O.score-f.score)}function Mt(t,e){let r=new Map;if(e.length===0)return r;try{let n=e.map(()=>"?").join(","),o=t.query(`SELECT fn.fact_id as fact_id, n.id, n.name, n.type
|
|
18
|
-
FROM fact_nodes fn
|
|
19
|
-
JOIN nodes n ON fn.node_id = n.id
|
|
20
|
-
WHERE fn.fact_id IN (${n})
|
|
21
|
-
ORDER BY fn.fact_id, fn.score DESC, n.id`,e);for(let c of o){let s=r.get(c.fact_id);s||(s=[],r.set(c.fact_id,s)),s.push({id:c.id,name:c.name,type:c.type});}}catch(n){ne.warn("recall: loadFactNodes failed (KG associations unavailable for this recall)",{error:n instanceof Error?n.message:String(n)});}return r}function Dt(t,e,r,n,o){try{return t.query(`SELECT mf.id, mv.embedding
|
|
22
|
-
FROM memory_facts mf
|
|
23
|
-
JOIN memory_vectors mv ON mf.id = mv.fact_id
|
|
24
|
-
WHERE ${r}
|
|
25
|
-
LIMIT ?`,[...n,o]).map(s=>{let i=new Float32Array(s.embedding.buffer,s.embedding.byteOffset,s.embedding.byteLength/4);return {id:s.id,score:Ct(e,i)}}).sort((s,i)=>i.score-s.score)}catch(c){if(c instanceof S)throw c;return ne.warn("vector search failed, falling back to FTS-only",{error:c instanceof Error?c.message:String(c)}),[]}}function vt(t,e,r,n,o){try{let c=t.query(`SELECT mf.id as id, bm25(memory_facts_fts) as score
|
|
26
|
-
FROM memory_facts_fts fts
|
|
27
|
-
JOIN memory_facts mf ON mf.id = fts.fact_id
|
|
28
|
-
WHERE ${r} AND memory_facts_fts MATCH ?
|
|
29
|
-
ORDER BY score DESC
|
|
30
|
-
LIMIT ?`,[...n,Ot(e),o]);if(c.length===0)return [];let s=Math.max(...c.map(i=>Math.abs(i.score)),1);return c.map(i=>({id:i.id,score:1-Math.abs(i.score)/s})).filter(i=>i.score>=0)}catch(c){if(c instanceof S)throw c;return ne.warn("FTS search failed, returning empty result",{err:c instanceof Error?c.message:String(c)}),[]}}function Ct(t,e){if(t.length!==e.length||t.length===0)return 0;let r=0,n=0,o=0;for(let s=0;s<t.length;s++){let i=t[s]??0,g=e[s]??0;r+=i*g,n+=i*i,o+=g*g;}let c=Math.sqrt(n)*Math.sqrt(o);return c===0?0:Math.max(0,r/c)}function Ot(t){return t.trim().split(/\s+/).filter(e=>e.length>0).map(e=>`"${e.replace(/"/g,'""')}"`).join(" ")}var ze=z.object({query:z.string().min(1).max(500),category:z.string().optional(),minImportance:z.number().min(1).max(10).optional(),fromTime:z.string().datetime().optional(),toTime:z.string().datetime().optional(),maxResults:z.number().int().min(1).max(100).optional().default(10),minScore:z.number().min(0).max(1).optional(),includeGraph:z.boolean().optional().default(false),depth:z.number().int().min(1).max(5).optional().default(1),includeShared:z.boolean().optional().default(false)});z.object({hits:z.array(z.unknown()),total:z.number(),truncated:z.boolean(),durationMs:z.number(),graph:z.object({nodes:z.array(z.unknown()),edges:z.array(z.unknown())}).optional()});var Qe=z.object({content:z.string().min(1).max(1e4),category:z.string().min(1),importance:z.number().int().min(1).max(10).optional().default(5),tags:z.array(z.string()).optional(),sessionId:z.string().optional(),msgId:z.string().optional(),parentMsgId:z.string().optional(),skipDedup:z.boolean().optional().default(false),extractGraph:z.boolean().optional().default(true)});z.object({fact:z.object({id:z.string(),agentId:z.string(),content:z.string(),category:z.string(),importance:z.number(),createdAt:z.string(),updatedAt:z.string()}),filePath:z.string(),deduplicated:z.boolean(),nodeIds:z.array(z.number()).optional()});var Ke=z.object({factId:z.string().min(1).describe("Target fact id (must belong to ctx.agentId)"),content:z.string().min(1).max(1e4).optional().describe("New content (triggers embedding rewrite + FTS reindex)"),category:z.string().min(1).optional().describe("New category (one of MemoryCategory enum)"),importance:z.number().int().min(1).max(10).optional().describe("New importance 1-10"),tags:z.array(z.string()).optional().describe("New tags array (empty array clears tags)")}).refine(t=>t.content!==void 0||t.category!==void 0||t.importance!==void 0||t.tags!==void 0,{message:"at least one of `content`, `category`, `importance`, `tags` is required"});z.object({fact:z.object({id:z.string(),agentId:z.string(),content:z.string(),category:z.string(),importance:z.number(),createdAt:z.string(),updatedAt:z.string()}),contentChanged:z.boolean(),fieldsUpdated:z.array(z.string()),durationMs:z.number()});var Je=z.object({factId:z.string().optional(),category:z.string().optional(),fromTime:z.string().datetime().optional(),toTime:z.string().datetime().optional(),maxDelete:z.number().int().min(1).max(1e4).optional().default(1e3),dryRun:z.boolean().optional().default(false),force:z.boolean().optional().default(false)}).refine(t=>t.factId!==void 0&&t.factId.length>0||t.category!==void 0&&t.category.length>0||t.fromTime!==void 0||t.toTime!==void 0,{message:"one of `factId`, `category`, `fromTime`, or `toTime` is required"});z.object({deletedCount:z.number(),deletedIds:z.array(z.string()),dryRun:z.boolean(),truncatedCount:z.number()});var Ve=z.object({sessionId:z.string().min(1),lastN:z.number().int().min(1).max(500).optional().default(50),fromMessageId:z.string().optional(),writeToDisk:z.boolean().optional().default(true)});z.object({extractedCount:z.number(),factIds:z.array(z.string()),entities:z.array(z.object({id:z.number(),name:z.string(),type:z.string()})),relations:z.array(z.object({source:z.string(),target:z.string(),relation:z.string()})),messageRange:z.object({fromMessageId:z.string(),toMessageId:z.string()}),durationMs:z.number()});var Ye=z.object({windowDays:z.number().int().min(1).max(365).optional().default(30),dryRun:z.boolean().optional().default(false)});z.object({totalFacts:z.number(),dedupedCount:z.number(),compressedCount:z.number(),archivedCount:z.number(),skippedCount:z.number(),durationMs:z.number()});var Xe=z.object({query:z.string().min(1),type:z.string().optional(),depth:z.number().int().min(1).max(5).optional().default(2),maxNodes:z.number().int().min(1).max(500).optional().default(100),scope:z.enum(["agent_only","shared_only","both"]).optional().default("agent_only"),relation:z.string().optional()});z.object({root:z.unknown().nullable(),nodes:z.array(z.unknown()),edges:z.array(z.unknown()),truncated:z.boolean(),totalNodes:z.number(),totalEdges:z.number(),scope:z.enum(["agent_only","shared_only","both"]),durationMs:z.number()});var Ze=z.object({}).optional();z.object({dbPath:z.string(),workspaceDir:z.string(),factsCount:z.number(),nodesCount:z.number(),edgesCount:z.number(),factsByCategory:z.record(z.string(),z.number()),ftsAvailable:z.boolean(),vectorEnabled:z.boolean(),kgScopeEnabled:z.boolean(),healthy:z.boolean(),meta:z.record(z.string(),z.string())});var et=z.object({}).optional();z.object({healthy:z.boolean(),checks:z.array(z.object({name:z.string(),passed:z.boolean(),message:z.string(),details:z.record(z.string(),z.unknown()).optional()}))});var tt=z.object({workspaceDir:z.string().optional(),dbPath:z.string().optional(),archiveDays:z.number().int().min(1).max(3650).optional().default(30),force:z.boolean().optional().default(false)});z.object({initialized:z.boolean(),dbPath:z.string(),workspaceDir:z.string(),tablesCreated:z.number(),migrationsApplied:z.number(),durationMs:z.number()});var nt=z.object({windowDays:z.number().int().min(1).max(3650).optional(),dryRun:z.boolean().optional().default(false)});z.object({generatedCount:z.number(),skippedCount:z.number(),failedGenerateCount:z.number(),archivedCount:z.number(),archiveThreshold:z.string(),archivedRecords:z.array(z.object({source:z.string(),target:z.string(),firstCreatedAt:z.string(),firstFactId:z.string()})),windowDays:z.number(),dryRun:z.boolean(),durationMs:z.number()});var ue=Log.create({service:"memory.fact-file-sync"}),Pt=".easbot/memory/active";function fe(t,e){let r=e.replace(/\\/g,"/").replace(/\/+$/,""),n=t.category||"uncategorized",o=t.createdAt?new Date(t.createdAt).getTime():Date.now(),c=Number.isNaN(o)?new Date:new Date(o),s=c.getFullYear(),i=String(c.getMonth()+1).padStart(2,"0"),g=String(c.getDate()).padStart(2,"0"),l=`${s}-${i}-${g}`;return `${r}/${Pt}/${n}/${l}.md`}function rt(t){let e=t.tags&&t.tags.length>0?t.tags:[],r=t.importance??5,n=t.source??"session_self_write",o=t.createdAt?formatLocalISO(new Date(t.createdAt)):formatLocalISO(new Date),c=t.updatedAt?formatLocalISO(new Date(t.updatedAt)):o,s=["---",`id: ${t.id}`,`agent_id: ${t.agentId}`,`category: ${t.category}`,`importance: ${r}`,`created_at: ${o}`,`updated_at: ${c}`,`source: ${n}`,e.length>0?`tags: [${e.join(", ")}]`:"tags: []"];return t.sessionId&&s.push(`session_id: ${t.sessionId}`),t.msgId&&s.push(`msg_id: ${t.msgId}`),t.parentMsgId&&s.push(`parent_msg_id: ${t.parentMsgId}`),s.push("---"),`${s.join(`
|
|
31
|
-
`)}
|
|
32
|
-
${t.content.trim()}`}function re(t,e){let r=t.replace(/\\/g,"/"),n=e.replace(/\\/g,"/").replace(/\/+$/,"");return r.startsWith(`${n}/`)?r.slice(n.length+1):r}async function kt(t,e){let r=fe(t,e),n=re(r,e);try{let o=rt(t);await K.mkdir(pe.dirname(r),{recursive:!0});let c="";try{c=await K.readFile(r,"utf-8");}catch(i){if(i.code!=="ENOENT")throw i}let s=c.length>0&&!c.endsWith(`
|
|
33
|
-
`)?`
|
|
34
|
-
`:"";return await K.writeFile(r,`${c}${s}${o}
|
|
35
|
-
`,"utf-8"),ue.debug("Fact file synced (append)",{id:t.id,relPath:n}),{ok:!0,absPath:r,relPath:n}}catch(o){let c=o instanceof Error?o.message:String(o);return ue.warn("Failed to write fact file (best-effort, non-blocking)",{id:t.id,absPath:r,error:c}),{ok:false,absPath:r,relPath:n,error:c}}}async function At(t,e){let r;t.filePath?r=`${e.replace(/\\/g,"/").replace(/\/+$/,"")}/${t.filePath.replace(/^\/+/,"")}`:r=fe({id:t.id,category:t.category,createdAt:t.createdAt,updatedAt:t.createdAt},e);let n=re(r,e);try{return await K.unlink(r),ue.debug("Fact file deleted",{id:t.id,relPath:n}),{ok:!0,absPath:r,relPath:n}}catch(o){if(o.code==="ENOENT")return ue.debug("Fact file not found (already deleted)",{id:t.id,relPath:n}),{ok:true,absPath:r,relPath:n};let s=o instanceof Error?o.message:String(o);return ue.warn("Failed to delete fact file (best-effort, non-blocking)",{id:t.id,absPath:r,error:s}),{ok:false,absPath:r,relPath:n,error:s}}}var oe={resolvePath:fe,renderMarkdown:rt,toRelPath:re,write:kt,delete:At};var ae=Log.create({service:"memory.service.remember"});async function ot(t,e$1){if(H(t),te(t),!e$1.content||e$1.content.trim().length===0)throw new S("remember requires non-empty `content`","CONTENT_REQUIRED");if(!e$1.category)throw new S("remember requires `category`","CATEGORY_REQUIRED");ae.debug("remember invoked",{agentId:t.agentId,category:e$1.category,importance:e$1.importance??5,contentLength:e$1.content.length,skipDedup:e$1.skipDedup,extractGraph:e$1.extractGraph??true});let r=new e(t.dbPath);try{await r.initialize();let n=new Date().toISOString(),o=$t(),c=e$1.importance??5,s={entities:[],relations:[]},g=e$1.extractGraph!==!1&&a$1.isInitialized()&&a$1.capabilities().graphLlm?a$1.getGraphLlm():void 0;if(g)try{s=await Ut(g,e$1.content);}catch(b){ae.warn("LLM KG extraction failed (continuing without KG)",{agentId:t.agentId,error:b instanceof Error?b.message:String(b)});}let l=a$1.isInitialized()&&a$1.capabilities().embedding===!0,p=l?await Ht(r.getDb(),e$1.content):null,y=p?p.length:null,h=s.entities,M=s.relations,D=[],I=0,u=[];if(r.transaction(()=>{let b=new Map;for(let R of h){let f=r.query("SELECT id FROM nodes WHERE name = ? AND type = ? AND owner_agent_id = ? LIMIT 1",[R.name,R.type,t.agentId])[0];if(f){b.set(R.name,f.id);continue}let O=null;try{let j=Ie(R.name),z=r.query("SELECT embedding FROM embedding_cache WHERE content_hash = ?",[j])[0];z?.embedding&&(O=z.embedding);}catch{}let k=r.run("INSERT INTO nodes (name, type, properties, owner_agent_id, embedding, createdAt, updatedAt) VALUES (?, ?, ?, ?, ?, ?, ?)",[R.name,R.type,JSON.stringify({source:"llm_extracted",...R.properties??{}}),t.agentId,O,n,n]).lastID;k>0&&(b.set(R.name,k),O===null&&u.push({name:R.name,nodeId:k}));}for(let R of M){let f=b.get(R.source),O=b.get(R.target);!f||!O||f===O||r.run("INSERT OR REPLACE INTO edges (source, target, relation, properties, createdAt) VALUES (?, ?, ?, ?, ?)",[f,O,R.relation,JSON.stringify({}),n]);}r.run(`INSERT INTO memory_facts
|
|
36
|
-
(id, agent_id, session_id, msg_id, parent_msg_id, content, category, importance,
|
|
37
|
-
source, tags, file_path, created_at, updated_at)
|
|
38
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[o,t.agentId,e$1.sessionId??null,e$1.msgId??null,e$1.parentMsgId??null,e$1.content,e$1.category,c,"session_self_write",e$1.tags?JSON.stringify(e$1.tags):null,null,n,n]);let _=Array.from(b.values());if(_.length>0)try{for(let R of _)r.run("INSERT OR IGNORE INTO fact_nodes (fact_id, node_id, source, score, createdAt) VALUES (?, ?, ?, ?, ?)",[o,R,"kg_extract",1,n]);}catch(R){ae.warn("fact_nodes write failed (non-fatal)",{factId:o,nodeCount:_.length,error:R instanceof Error?R.message:String(R)});}if(p&&y){let R=Se(p);r.run("INSERT OR REPLACE INTO memory_vectors (fact_id, embedding) VALUES (?, ?)",[o,R]),I=1,r.query("SELECT value FROM meta WHERE key = ?",["vectorDims"])[0]||r.run("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)",["vectorDims",String(y)]);}r.run("DELETE FROM memory_facts_fts WHERE fact_id = ?",[o]),r.run("INSERT INTO memory_facts_fts (fact_id, agent_id, content, tags) VALUES (?, ?, ?, ?)",[o,t.agentId,e$1.content,e$1.tags?e$1.tags.join(" "):""]),D.push(...Array.from(b.values()));}),u.length>0&&a$1.isInitialized()&&a$1.capabilities().embedding)try{let b=u.map(f=>f.name),_=await a$1.embedMany(b),R=new Date().toISOString();for(let f=0;f<u.length;f++){let O=u[f],F=_[f];if(!O||!F||F.length===0)continue;let k=Se(new Float32Array(F));r.run("INSERT OR REPLACE INTO embedding_cache (content_hash, embedding) VALUES (?, ?)",[Ie(O.name),k]),r.run("UPDATE nodes SET embedding = ?, updatedAt = ? WHERE id = ?",[k,R,O.nodeId]);}}catch(b){ae.warn("memory entity name batch embed failed (non-fatal)",{pendingCount:u.length,error:b instanceof Error?b.message:String(b)});}ae.info("Memory stored",{id:o,category:e$1.category,agentId:t.agentId,nodeCount:D.length,vectorsWritten:I,vectorDims:y??0,embeddingMode:l?"enabled":"fts_only",entitiesExtracted:h.length,relationsExtracted:M.length});let E={id:o,agentId:t.agentId,sessionId:e$1.sessionId,msgId:e$1.msgId,parentMsgId:e$1.parentMsgId,content:e$1.content,category:e$1.category,importance:c,source:"session_self_write",tags:e$1.tags,nodeIds:D.length>0?D:void 0,filePath:void 0,createdAt:n,updatedAt:n},C="",v=await oe.write(E,t.workspaceDir);if(v.ok){C=v.relPath,E.filePath=v.relPath;try{r.run("UPDATE memory_facts SET file_path = ? WHERE id = ?",[v.relPath,o]);}catch(b){ae.warn("Failed to update file_path column after sync",{id:o,error:b instanceof Error?b.message:String(b)});}}return {fact:E,filePath:C,deduplicated:!1,nodeIds:D,vectorsWritten:I,vectorDims:y??0,entitiesExtracted:h.length,relationsExtracted:M.length}}catch(n){throw n instanceof S?n:new S(`remember failed: ${n instanceof Error?n.message:String(n)}`,"INTERNAL",{cause:n instanceof Error?n.message:String(n)})}finally{r.close();}}function $t(){let t=Date.now(),e=randomBytes(3).toString("hex");return `mem_${t}_${e}`}function Se(t){return Buffer.from(t.buffer,t.byteOffset,t.byteLength)}function Ie(t){return createHash("sha256").update(t).digest("hex")}async function Ht(t,e){let r=Ie(e),n=t.prepare("SELECT embedding FROM embedding_cache WHERE content_hash = ?").get(r);if(n?.embedding)return new Float32Array(n.embedding.buffer,n.embedding.byteOffset,n.embedding.byteLength/4);let o=await a$1.embedText(e);if(!o||o.length===0)return null;let c=Se(o);return t.prepare("INSERT OR REPLACE INTO embedding_cache (content_hash, embedding) VALUES (?, ?)").run(r,c),o}async function Ut(t,e){let r=await GraphProvider.generateGraph({chunks:[e],model:t,includeRules:false});return {entities:r.entities,relations:r.relations}}var _e=Log.create({service:"memory.service.update"});function jt(t){if(t.content===void 0&&t.category===void 0&&t.importance===void 0&&t.tags===void 0)throw new S("update requires at least one of: `content`, `category`, `importance`, `tags`","CONTENT_REQUIRED");if(t.content!==void 0&&t.content.trim().length===0)throw new S("update: `content` cannot be empty (use `forget` to delete)","CONTENT_REQUIRED");if(t.importance!==void 0&&(t.importance<1||t.importance>10))throw new S(`update: \`importance\` must be 1-10, got ${t.importance}`,"IMPORTANCE_REQUIRED")}async function at(t,e$1){let r=Date.now();H(t),te(t),jt(e$1),_e.debug("update invoked",{agentId:t.agentId,factId:e$1.factId,fields:{content:e$1.content!==void 0,category:e$1.category!==void 0,importance:e$1.importance!==void 0,tags:e$1.tags!==void 0}});let n=e$1.content!==void 0,o=n&&a$1.isInitialized()&&a$1.capabilities().embedding===true,c=null;if(o&&e$1.content)try{c=await a$1.embedText(e$1.content);}catch(i){_e.warn("update: embedding rewrite failed (continuing without vector update)",{factId:e$1.factId,error:i instanceof Error?i.message:String(i)});}let s=new e(t.dbPath);try{await s.initialize();let i=new Date().toISOString(),g=[];s.transaction(()=>{let h=s.query("SELECT id, content, category, importance, tags FROM memory_facts WHERE id = ? AND agent_id = ?",[e$1.factId,t.agentId])[0];if(!h)throw new ce(e$1.factId);let M=["updated_at = ?"],D=[i];if(e$1.content!==void 0&&e$1.content!==h.content&&(M.push("content = ?"),D.push(e$1.content),g.push("content")),e$1.category!==void 0&&e$1.category!==h.category&&(M.push("category = ?"),D.push(e$1.category),g.push("category")),e$1.importance!==void 0&&e$1.importance!==h.importance&&(M.push("importance = ?"),D.push(e$1.importance),g.push("importance")),e$1.tags!==void 0){let I=e$1.tags.length>0?JSON.stringify(e$1.tags):null;I!==h.tags&&(M.push("tags = ?"),D.push(I),g.push("tags"));}if(g.length>0&&s.run(`UPDATE memory_facts SET ${M.join(", ")} WHERE id = ? AND agent_id = ?`,[...D,e$1.factId,t.agentId]),g.includes("content")||g.includes("tags")){let I=e$1.content??h.content,u=g.includes("tags")?e$1.tags&&e$1.tags.length>0?JSON.stringify(e$1.tags):null:h.tags,E=u?(()=>{try{let C=JSON.parse(u);return Array.isArray(C)?C.filter(v=>typeof v=="string"):[]}catch{return []}})():[];s.run("DELETE FROM memory_facts_fts WHERE fact_id = ?",[e$1.factId]),s.run("INSERT INTO memory_facts_fts (fact_id, agent_id, content, tags) VALUES (?, ?, ?, ?)",[e$1.factId,t.agentId,I,E.join(" ")]);}if(g.includes("content")&&c){let I=Bt(c);s.run("INSERT OR REPLACE INTO memory_vectors (fact_id, embedding) VALUES (?, ?)",[e$1.factId,I]);try{let u=zt(e$1.content);s.run("INSERT OR REPLACE INTO embedding_cache (content_hash, embedding) VALUES (?, ?)",[u,I]);}catch{}}});let l=s.query("SELECT id, agent_id, session_id, msg_id, parent_msg_id, content, category, importance, source, tags, file_path, created_at, updated_at FROM memory_facts WHERE id = ? AND agent_id = ?",[e$1.factId,t.agentId])[0];if(!l)throw new S(`update: failed to read back updated fact ${e$1.factId}`,"INTERNAL");let p;if(l.tags)try{let h=JSON.parse(l.tags);Array.isArray(h)&&(p=h.filter(M=>typeof M=="string"));}catch{}let y={id:l.id,agentId:l.agent_id,sessionId:l.session_id??void 0,msgId:l.msg_id??void 0,parentMsgId:l.parent_msg_id??void 0,content:l.content,category:l.category,importance:l.importance,source:l.source,tags:p,filePath:l.file_path??void 0,createdAt:l.created_at,updatedAt:l.updated_at};return _e.info("Memory updated",{agentId:t.agentId,factId:e$1.factId,fieldsUpdated:g,contentChanged:n,durationMs:Date.now()-r}),{fact:y,contentChanged:n,fieldsUpdated:g,durationMs:Date.now()-r}}catch(i){throw i instanceof S?i:new S(`update failed: ${i instanceof Error?i.message:String(i)}`,"INTERNAL",{cause:i instanceof Error?i.message:String(i)})}finally{s.close();}}function Bt(t){return Buffer.from(t.buffer,t.byteOffset,t.byteLength)}function zt(t){return createHash("sha256").update(t).digest("hex")}var Me=Log.create({service:"memory.service.forget"}),Kt=1e3;function Jt(t){let e=[];if(t.factId&&t.factId.trim().length>0&&e.push("factId"),t.category&&t.category.trim().length>0&&e.push("category"),(t.fromTime||t.toTime)&&e.push("timeRange"),e.length===0)throw new S("CONTENT_REQUIRED: forget requires one of: `factId`, `category`, or `fromTime`/`toTime`","CONTENT_REQUIRED");if(e.length>1)throw new S(`mutually exclusive: forget requires exactly one of factId/category/timeRange, got [${e.join(", ")}]`,"CONTENT_REQUIRED");return e[0]}function Vt(t,e,r){let n=[r];switch(t){case "factId":return {where:"agent_id = ? AND id = ?",args:[...n,e.factId]};case "category":return {where:"agent_id = ? AND category = ?",args:[...n,e.category]};case "timeRange":{let o=["agent_id = ?"];return e.fromTime&&(o.push("created_at >= ?"),n.push(e.fromTime)),e.toTime&&(o.push("created_at <= ?"),n.push(e.toTime)),{where:o.join(" AND "),args:n}}}}function Yt(t,e,r,n){return t.query(`SELECT id FROM memory_facts WHERE ${e} LIMIT ?`,[...r,n+1]).map(c=>c.id)}function Xt(t,e,r,n){if(r.length===0)return 0;let o=r.map(()=>"?").join(",");return t.query(`SELECT COUNT(DISTINCT fn.fact_id) as count
|
|
39
|
-
FROM fact_nodes fn
|
|
40
|
-
JOIN memory_facts mf ON fn.fact_id = mf.id
|
|
41
|
-
WHERE mf.agent_id = ? AND fn.fact_id != ? AND fn.node_id IN (${o})`,[n,e,...r])[0]?.count??0}function Zt(t,e,r){let n,o,c="";return t.transaction(()=>{let s=t.query("SELECT content, file_path, category, created_at FROM memory_facts WHERE id = ? AND agent_id = ?",[e,r])[0],g=t.query("SELECT node_id FROM fact_nodes WHERE fact_id = ?",[e]).map(l=>l.node_id).filter(l=>typeof l=="number");if(n=s?.file_path??void 0,o=s?.category,c=s?.created_at??"",t.run("DELETE FROM memory_facts_fts WHERE fact_id = ?",[e]),t.run("DELETE FROM memory_facts WHERE id = ? AND agent_id = ?",[e,r]),g.length>0){let l=g.map(()=>"?").join(",");t.run(`DELETE FROM nodes WHERE id IN (${l}) AND NOT EXISTS (
|
|
42
|
-
SELECT 1 FROM fact_nodes fn WHERE fn.node_id = nodes.id
|
|
43
|
-
)`,g);}}),{filePath:n,category:o,createdAt:c}}async function st(t,e$1){H(t),Q(t,"forget");let r=Jt(e$1),n=e$1.maxDelete??Kt,o=e$1.dryRun??false,c=e$1.force??false;Me.debug("forget invoked",{agentId:t.agentId,mode:r,maxDelete:n,dryRun:o,force:c});let s=new e(t.dbPath);try{await s.initialize();let{where:i,args:g}=Vt(r,e$1,t.agentId),l=Yt(s,i,g,n),p=l.length>n;if(p&&!c)throw new ge(l.length,n);let y=p?l.slice(0,n):l;if(o)throw new le(y.length);let h=[],M=[];for(let D of y){if(!c){let v=s.query("SELECT node_id FROM fact_nodes WHERE fact_id = ? AND node_id IS NOT NULL",[D]).map(_=>_.node_id).filter(_=>typeof _=="number"),b=Xt(s,D,v,t.agentId);if(b>0)throw new me(D,b)}let{filePath:I,category:u,createdAt:E}=Zt(s,D,t.agentId);I&&u&&M.push({id:D,filePath:I,category:u,createdAt:E}),h.push(D);}Me.info("forget complete",{agentId:t.agentId,mode:r,deletedCount:h.length,force:c,dryRun:o});for(let{id:D,filePath:I,category:u,createdAt:E}of M)await oe.delete({id:D,filePath:I,category:u,createdAt:E},t.workspaceDir).catch(C=>{Me.warn("Fact file delete failed (best-effort)",{id:D,filePath:I,error:C instanceof Error?C.message:String(C)});});return {deletedCount:h.length,deletedIds:h,dryRun:o,truncatedCount:p?l.length-n:0}}catch(i){throw i instanceof S?i:new S(`forget failed: ${i instanceof Error?i.message:String(i)}`,"INTERNAL",{cause:i instanceof Error?i.message:String(i)})}finally{s.close();}}var it=Log.create({service:"memory.service.extract"}),tn=50,De=500;async function ct(t,e$1){if(H(t),!e$1.sessionId||e$1.sessionId.trim().length===0)throw new S("extract requires non-empty `sessionId`","SESSION_ID_REQUIRED");let r=e$1.lastN??tn;if(r>De)throw new S(`extract lastN=${r} exceeds max=${De}`,"CONTENT_REQUIRED",{lastN:r,maxLastN:De});let n=e$1.sessionId,o=e$1.fromMessageId;it.debug("extract invoked",{agentId:t.agentId,sessionId:n,lastN:r,fromMessageId:o,writeToDisk:e$1.writeToDisk??true});let c=Date.now(),s=new e(t.dbPath);try{await s.initialize();let i=s.query(`SELECT id, content, category, importance, 1.0 as score, created_at
|
|
44
|
-
FROM memory_facts
|
|
45
|
-
WHERE agent_id = ? AND session_id = ?
|
|
46
|
-
ORDER BY created_at ASC
|
|
47
|
-
LIMIT ?`,[t.agentId,n,r]),g=o?i.filter(u=>u.id>o):i,l=g.map(u=>u.id),p=l.length>0?s.query(`SELECT node_id FROM fact_nodes WHERE fact_id IN (${l.map(()=>"?").join(",")})`,l):[],y=new Set;for(let u of p)typeof u.node_id=="number"&&u.node_id>0&&y.add(u.node_id);let h=Array.from(y),M=[],D=[];if(h.length>0){let u=h.map(()=>"?").join(","),E=s.query(`SELECT id, name, type FROM nodes WHERE id IN (${u})`,h),C=new Map;for(let _ of E)C.set(_.id,_.name);M=E.map(_=>({id:_.id,name:_.name,type:_.type}));let v=s.query(`SELECT source, target, relation FROM edges WHERE source IN (${u}) OR target IN (${u})`,[...h,...h]),b=new Set;D=[];for(let _ of v){let R=C.get(_.source),f=C.get(_.target);if(!R||!f)continue;let O=`${R}\0${_.relation}\0${f}`;b.has(O)||(b.add(O),D.push({source:R,target:f,relation:_.relation}));}}let I=Date.now()-c;return it.info("extract complete",{agentId:t.agentId,sessionId:n,factCount:g.length,nodeCount:M.length,relationCount:D.length,durationMs:I}),{extractedCount:g.length,factIds:g.map(u=>u.id),entities:M,relations:D,messageRange:{fromMessageId:g[0]?.id??"",toMessageId:g[g.length-1]?.id??""},durationMs:I}}catch(i){throw i instanceof S?i:new S(`extract failed: ${i instanceof Error?i.message:String(i)}`,"INTERNAL",{cause:i instanceof Error?i.message:String(i)})}finally{s.close();}}var Oe=Log.create({service:"memory.service.consolidate"}),rn=30;async function on(t){let{createHash:e}=await import('crypto');return e("sha256").update(t).digest("hex")}async function dt(t,e$1={}){let r=Date.now();H(t),Q(t,"consolidate");let n=e$1.windowDays??rn,o=e$1.dryRun??false;Oe.debug("consolidate invoked",{agentId:t.agentId,windowDays:n,dryRun:o});let c=new e(t.dbPath);try{await c.initialize();let s=c.query("SELECT id, content, category, importance, created_at FROM memory_facts WHERE agent_id = ? ORDER BY created_at DESC",[t.agentId]),i=new Map;for(let u of s){let E=await on(u.content);i.has(E)||i.set(E,[]),i.get(E)?.push(u);}let g=0,l=[];for(let[,u]of i){if(u.length<=1)continue;let E=[...u].sort((b,_)=>b.importance!==_.importance?_.importance-b.importance:_.created_at.localeCompare(b.created_at)),C=E[0];if(!C)continue;let v=E.slice(1).map(b=>b.id);g+=v.length,l.push({keep:C,removeIds:v});}let p=new Date(Date.now()-n*24*60*60*1e3).toISOString(),y=c.query(`SELECT id, content, category, importance, created_at FROM memory_facts
|
|
48
|
-
WHERE agent_id = ? AND created_at < ?
|
|
49
|
-
ORDER BY created_at ASC`,[t.agentId,p]),h=0,M=0;if(o)h=0,M=g;else {let u=pe.join(t.workspaceDir,"archive");await K.mkdir(u,{recursive:!0});for(let{removeIds:E}of l){if(E.length===0)continue;let C=E.map(()=>"?").join(",");c.transaction(()=>{for(let v of E)c.run("DELETE FROM memory_facts WHERE id = ? AND agent_id = ?",[v,t.agentId]);}),M+=E.length;}for(let E of y){let C=E.created_at.slice(0,7),v=pe.join(u,C,E.category);await K.mkdir(v,{recursive:!0});let b=pe.join(v,`${E.id}.md`);try{await K.writeFile(b,[`# ${E.id}`,"",`category: ${E.category}`,`importance: ${E.importance}`,`createdAt: ${E.created_at}`,"",E.content,""].join(`
|
|
50
|
-
`),"utf-8"),c.run("DELETE FROM memory_facts WHERE id = ? AND agent_id = ?",[E.id,t.agentId]),h++;}catch(_){Oe.warn("consolidate: archive write failed",{factId:E.id,error:_ instanceof Error?_.message:String(_)});}}}let D=s.length,I=0;return Oe.info("consolidate complete",{agentId:t.agentId,totalFacts:D,dedupedCount:g,compressedCount:I,archivedCount:h,skippedCount:M,dryRun:o,durationMs:Date.now()-r}),{totalFacts:D,dedupedCount:g,compressedCount:I,archivedCount:h,skippedCount:M,durationMs:Date.now()-r}}catch(s){throw s instanceof S?s:new S(`consolidate failed: ${s instanceof Error?s.message:String(s)}`,"INTERNAL",{cause:s instanceof Error?s.message:String(s)})}finally{c.close();}}var G=Log.create({service:"memory.service.sync"}),cn=30,dn=".easbot/memory/active",mt=".easbot/memory/archive";function mn(t,e){let n=t.query("SELECT node_id FROM fact_nodes WHERE fact_id = ?",[e.id]).map(o=>o.node_id).filter(o=>typeof o=="number");return {id:e.id,agentId:e.agent_id,sessionId:e.session_id??void 0,msgId:e.msg_id??void 0,parentMsgId:e.parent_msg_id??void 0,content:e.content,category:e.category,importance:e.importance,source:e.source,tags:e.tags?JSON.parse(e.tags):void 0,nodeIds:n.length>0?n:void 0,filePath:e.file_path??void 0,createdAt:e.created_at,updatedAt:e.updated_at}}async function ln(t,e){let r=0,n=0,o=0,{where:c,params:s}=t.agentFilter(e.agentId),i=t.query(`SELECT id, agent_id, session_id, msg_id, parent_msg_id, content, category, importance,
|
|
51
|
-
source, tags, file_path, created_at, updated_at
|
|
52
|
-
FROM memory_facts ${c}
|
|
53
|
-
ORDER BY created_at ASC`,s);for(let g of i){let l=mn(t,g);if(g.file_path?.startsWith(`${mt}/`)){n++;continue}let p=fe(l,e.workspaceDir);try{await K.access(p),n++;continue}catch(h){let M=h;if(M.code!=="ENOENT"){G.warn("sync generate: fs.access failed (non-ENOENT)",{factId:l.id,absPath:p,error:M.message}),o++;continue}}let y=await oe.write(l,e.workspaceDir);y.ok?r++:(o++,G.warn("sync generate: factFileSync.write failed",{factId:l.id,absPath:p,error:y.error}));}return G.debug("sync stage A complete",{agentId:e.agentId,generatedCount:r,skippedCount:n,failedGenerateCount:o}),{generatedCount:r,skippedCount:n,failedGenerateCount:o}}async function gn(t,e,r,n){let o=r*24*60*60*1e3,c=Date.now(),s=formatLocalISO(new Date(c-o)),i=[],g=pe.join(e.workspaceDir,dn),l=await un(g);G.debug("sync stage B: scan active dir",{activeDir:g,fileCount:l.length,windowDays:r,threshold:s,dryRun:n});for(let p of l){let y=await fn(p);if(!y){G.warn("sync stage B: skip unparseable file",{absPath:p});continue}let{firstCreatedAt:h,firstFactId:M}=y,D=new Date(h).getTime();if(Number.isNaN(D)){G.warn("sync stage B: skip invalid createdAt",{absPath:p,firstCreatedAt:h});continue}if(c-D<=o)continue;let I=pn(p);if(!I){G.warn("sync stage B: cannot infer category from path",{absPath:p});continue}let u=h.slice(0,7),E=pe.join(e.workspaceDir,mt,u,I),C=pe.basename(p),v=pe.join(E,C);if(n){i.push({source:p,target:v,firstCreatedAt:h,firstFactId:M});continue}try{await K.mkdir(E,{recursive:!0});try{await K.rename(p,v);}catch(R){let f=R;G.warn("sync stage B: fs.rename failed, falling back to copy+unlink",{absPath:p,targetPath:v,error:f.message}),await K.copyFile(p,v),await K.unlink(p);}let b=re(p,e.workspaceDir),_=re(v,e.workspaceDir);t.run(`UPDATE memory_facts SET file_path = ?
|
|
54
|
-
WHERE agent_id = ? AND file_path = ?`,[_,e.agentId??"",b]),i.push({source:p,target:v,firstCreatedAt:h,firstFactId:M});}catch(b){G.warn("sync stage B: archive failed",{absPath:p,targetPath:v,error:b instanceof Error?b.message:String(b)});}}return G.debug("sync stage B complete",{agentId:e.agentId,archivedCount:i.length,dryRun:n}),{archivedCount:i.length,archiveThreshold:s,archivedRecords:i}}async function un(t){let e=[];try{await lt(t,e);}catch(r){let n=r;if(n.code==="ENOENT")return e;throw G.warn("sync: listActiveMdFiles failed",{activeDir:t,error:n.message}),new S(`sync: listActiveMdFiles failed: ${n.message}`,"INTERNAL",{cause:n.message})}return e}async function lt(t,e){let r=await K.readdir(t,{withFileTypes:true});for(let n of r){let o=pe.join(t,n.name);n.isDirectory()?await lt(o,e):n.isFile()&&n.name.endsWith(".md")&&e.push(o);}}async function fn(t){let e;try{e=await K.readFile(t,"utf-8");}catch(s){if(s.code==="ENOENT")return null;throw s}if(!e.startsWith(`---
|
|
55
|
-
`))return null;let r=e.indexOf(`
|
|
56
|
-
---
|
|
57
|
-
`,4);if(r===-1)return null;let n=e.slice(4,r),o,c;for(let s of n.split(`
|
|
58
|
-
`)){let i=s.trim();if(i.startsWith("created_at:")?o=i.slice(11).trim().replace(/^["']|["']$/g,""):i.startsWith("id:")&&(c=i.slice(3).trim().replace(/^["']|["']$/g,"")),o&&c)break}return !o||!c?null:{firstCreatedAt:o,firstFactId:c}}function pn(t){let e=t.replace(/\\/g,"/").split("/"),r=e.findIndex(c=>c==="active");if(r===-1)return null;let n=e.slice(r+1);return n.length!==2||!n[1].endsWith(".md")?null:n[0]??null}async function gt(t,e$1={}){let r=Date.now();H(t),Q(t,"sync");let n=e$1.windowDays??t.config?.archiveDays??cn,o=e$1.dryRun??false;G.info("sync invoked",{agentId:t.agentId,windowDays:n,dryRun:o,workspaceDir:t.workspaceDir});let c=new e(t.dbPath);try{await c.initialize();let s=await ln(c,t),i=await gn(c,t,n,o),g={generatedCount:s.generatedCount,skippedCount:s.skippedCount,failedGenerateCount:s.failedGenerateCount,archivedCount:i.archivedCount,archiveThreshold:i.archiveThreshold,archivedRecords:i.archivedRecords,windowDays:n,dryRun:o,durationMs:Date.now()-r};return G.info("sync complete",{agentId:t.agentId,...g}),g}catch(s){throw s instanceof S?s:new S(`sync failed: ${s instanceof Error?s.message:String(s)}`,"INTERNAL",{cause:s instanceof Error?s.message:String(s)})}finally{c.close();}}var ut=Log.create({service:"memory.service.graph-query"});async function ft(t,e$1){let r=Date.now(),n=(t.agentId??"").trim()||"default",o=e$1.scope??"agent_only";if(!e$1.query||e$1.query.trim().length===0)throw new S("CONTENT_REQUIRED: graphQuery requires non-empty `query`","CONTENT_REQUIRED");Ee(t,o,"graph_query");let c=e$1.depth??2,s=e$1.maxNodes??100,i=e$1.query,g=e$1.type,l=e$1.relation;ut.debug("graphQuery invoked",{agentId:n,query:i,type:g,depth:c,maxNodes:s,scope:o,remote:t.remote});let p=new e(t.dbPath);try{await p.initialize();let y=new ee(p.getDb()),h=i.includes("*")||i.includes("%")?i:`%${i}%`,M=await y.queryNodes({name:h,...g?{type:g}:{},agentId:n,scope:o,limit:s}),I=(i.includes("*")||i.includes("%")?M:M.filter(R=>R.name.toLowerCase().includes(i.toLowerCase())))[0]??null;if(!I)return {root:null,nodes:[],edges:[],truncated:!1,totalNodes:0,totalEdges:0,scope:o,durationMs:Date.now()-r};let u=await y.queryNeighbors(I.id,c,{agentId:n,scope:o,maxEdgesPerNode:20}),E=new Map;E.set(I.id,I);for(let R of u)E.set(R.id,{id:R.id,name:R.name,type:R.type,createdAt:R.createdAt,updatedAt:R.updatedAt});let C=[];for(let R of u)if(R.edges)for(let f of R.edges)l&&f.relation!==l||C.push(f);for(let R of C){if(!E.has(R.source)){let f=await y.queryNodes({ids:[R.source],agentId:n,scope:o});f[0]&&E.set(f[0].id,f[0]);}if(!E.has(R.target)){let f=await y.queryNodes({ids:[R.target],agentId:n,scope:o});f[0]&&E.set(f[0].id,f[0]);}}let v=Array.from(E.values()),b=v.length>s,_=b?v.slice(0,s):v;return ut.info("graphQuery complete",{agentId:n,rootId:I.id,nodeCount:_.length,edgeCount:C.length,truncated:b,durationMs:Date.now()-r}),{root:I,nodes:_,edges:C,truncated:b,totalNodes:v.length,totalEdges:C.length,scope:o,durationMs:Date.now()-r}}catch(y){throw y instanceof S?y:new S(`graphQuery failed: ${y instanceof Error?y.message:String(y)}`,"INTERNAL",{cause:y instanceof Error?y.message:String(y)})}finally{p.close();}}var B=Log.create({service:"memory.service.init"});function Ne(t){return pe.join(t,".easbot","memory.json")}async function En(t){try{let{Config:e}=await import('@easbot/llm'),r=await e.get(),n=o=>typeof o=="string"&&o.length>0?o:void 0;return {embeddingModel:n(r.embedding_model),graphModel:n(r.graph_model)}}catch{return {}}}function wn(t,e={}){let r={version:1,schema_version:a$2,backend:"better-sqlite3",created_at:new Date().toISOString(),embedding_model:e.embeddingModel??null,graph_model:e.graphModel??null,entity_extraction_prompt:e.entityExtractionPrompt??null,relation_extraction_prompt:e.relationExtractionPrompt??null,archiveDays:e.archiveDays??30,shortTermMaxRounds:e.shortTermMaxRounds??20};writeFileSync(t,JSON.stringify(r,null,2),"utf-8");}async function pt(t,e$1={}){let r=Date.now();Q(t,"init");let n=e$1.workspaceDir??t.workspaceDir,o=e$1.dbPath??t.dbPath;if(!n||n.trim().length===0)throw new S("init requires non-empty `workspaceDir` (ctx.workspaceDir or params.workspaceDir)","CONTENT_REQUIRED");if(!o||o.trim().length===0)throw new S("init requires non-empty `dbPath` (ctx.dbPath or params.dbPath)","CONTENT_REQUIRED");let c=t.agentId?.trim()??"",s=e$1.force??false;B.debug("init invoked",{agentId:c,workspaceDir:n,dbPath:o,force:s});let i=Ne(n);if(!s)try{if(await K.stat(i).then(()=>!0).catch(()=>!1))return B.info("init: idempotent skip (memory.json exists, no --force)",{workspaceDir:n,configPath:i}),{initialized:!1,dbPath:o,configPath:i,configCreated:!1,schemaVersion:a$2,workspaceDir:n,tablesCreated:0,migrationsApplied:0,durationMs:0}}catch{}try{await K.mkdir(pe.dirname(o),{recursive:!0}),await K.mkdir(pe.join(n,".easbot","memory","active"),{recursive:!0}),await K.mkdir(pe.join(n,"archive"),{recursive:!0}),await K.mkdir(pe.join(n,".easbot"),{recursive:!0});}catch(y){throw new S(`init: failed to create directories: ${y instanceof Error?y.message:String(y)}`,"INTERNAL",{cause:y instanceof Error?y.message:String(y)})}if(s)for(let y of [o,`${o}-wal`,`${o}-shm`])try{await K.rm(y,{force:!0});}catch(h){B.warn("init: force rm failed (may not exist)",{path:y,error:h instanceof Error?h.message:String(h)});}let g=await En(),l=false;try{!await K.stat(i).then(()=>!0).catch(()=>!1)||s?(wn(i,{embeddingModel:g.embeddingModel,graphModel:g.graphModel,archiveDays:t.config?.archiveDays,shortTermMaxRounds:t.config?.shortTermMaxRounds}),l=!0,B.info("init: memory.json written",{configPath:i,force:s,configCreated:l})):B.debug("init: memory.json already exists, skipping write",{configPath:i});}catch(y){B.warn("init: memory.json write failed (non-fatal)",{configPath:i,error:y instanceof Error?y.message:String(y)});}let p=new e(o);try{let y=await K.stat(o).then(()=>!0).catch(()=>!1);await p.initialize();let h=new Date().toISOString(),M=[["version","1.0.0"],["schemaVersion",String(a$2)],["createdAt",h],["defaultAgentId",c]];for(let[u,E]of M)try{p.run("INSERT OR IGNORE INTO meta (key, value) VALUES (?, ?)",[u,E]);}catch(C){B.warn("init: meta insert failed",{key:u,error:C instanceof Error?C.message:String(C)});}let D=0;try{D=p.prepare("SELECT COUNT(*) as n FROM sqlite_master WHERE type IN ('table', 'index', 'trigger', 'view')").get()?.n??0;}catch(u){B.warn("init: tablesCreated count failed",{error:u instanceof Error?u.message:String(u)});}let I=0;try{I=p.prepare("SELECT id FROM schema_migrations").all().length;}catch(u){B.warn("init: migrationsApplied count failed",{error:u instanceof Error?u.message:String(u)});}return B.info("init complete",{agentId:c,workspaceDir:n,dbPath:o,configPath:i,configCreated:l,schemaVersion:a$2,durationMs:Date.now()-r}),{initialized:!0,dbPath:o,configPath:i,configCreated:l,schemaVersion:a$2,workspaceDir:n,tablesCreated:D,migrationsApplied:I,durationMs:Date.now()-r}}catch(y){throw new S(`init failed: ${y instanceof Error?y.message:String(y)}`,"INTERNAL",{cause:y instanceof Error?y.message:String(y)})}finally{p.close();}}var se=Log.create({service:"memory.service.status"}),_n=["user_preference","task_context","technical_fact","decision","relationship","reminder","error_pattern","workflow","exploration_finding","experience_summary","tool_usage","skill_creation","test","other"],Mn={};async function yt(t,e$1={},r=Mn){let n=t.agentId&&t.agentId.trim().length>0?t.agentId:void 0;if(se.debug("status invoked",{agentId:n??"<global>"}),!t.dbPath||t.dbPath.length===0)throw new S("`ctx.dbPath` is required","INTERNAL");let o={initialized:false,capabilities:{embedding:false,graphLlm:false}},c={},s={},i=0,g=0,l=0,p,y,h,M=false,D,I="uninitialized",u=false,E=false,C=false,v,b=_n.reduce((O,F)=>(O[F]=0,O),{}),_=new e(t.dbPath);try{await _.initialize(),i=_.query(n!==void 0?"SELECT COUNT(*) as c FROM memory_facts WHERE agent_id = ?":"SELECT COUNT(*) as c FROM memory_facts WHERE agent_id IS NOT NULL",n!==void 0?[n]:[])[0]?.c??0,g=_.query(n!==void 0?"SELECT COUNT(*) AS c FROM nodes WHERE owner_agent_id = ? OR owner_agent_id IS NULL":"SELECT COUNT(*) AS c FROM nodes",n!==void 0?[n]:[])[0]?.c??0,l=_.query("SELECT COUNT(*) as c FROM edges")[0]?.c??0;let j=_.query(n!==void 0?"SELECT category, COUNT(*) as c FROM memory_facts WHERE agent_id = ? GROUP BY category":"SELECT category, COUNT(*) as c FROM memory_facts WHERE agent_id IS NOT NULL GROUP BY category",n!==void 0?[n]:[]);for(let w of j){let T=w.category;T in b&&(b[T]=w.c);}c.facts=i,c.nodes=g,c.edges=l;try{E=_.query("SELECT name FROM sqlite_master WHERE type = ? AND name = ?",["table","memory_facts_fts"]).length>0;}catch(w){se.debug("status: fts probe failed",{error:w instanceof Error?w.message:String(w)});}M=!!t.config?.embeddingLlm;try{u=_.query("SELECT name FROM pragma_table_info('nodes') WHERE name = ?",["owner_agent_id"]).length>0;}catch(w){se.debug("status: kg scope probe failed",{error:w instanceof Error?w.message:String(w)});}C=_.healthCheck();try{let w=_.query("SELECT key, value FROM meta");for(let T of w)s[T.key]=T.value;}catch(w){se.debug("status: meta read failed",{error:w instanceof Error?w.message:String(w)});}let z=s.schema_version,V=s.extraction_version,d=s.lastSyncAt??s.lastSync,m=s.embeddingDims;p=z&&Number.parseInt(z,10)||void 0,y=V&&Number.parseInt(V,10)||void 0,h=d,D=m&&Number.parseInt(m,10)||void 0,i>0&&(I="complete");try{v=_.query("SELECT value FROM meta WHERE key = ?",["backend"])[0]?.value??"better-sqlite3";}catch{v="better-sqlite3";}}catch(O){if(O instanceof S)throw O;se.warn("status: db phase failed; returning partial result",{dbPath:t.dbPath,error:O instanceof Error?O.message:String(O)}),v="unknown",C=false;}finally{_.close();}if(!r.skipLlm&&a$1.isInitialized()){let F=a$1.capabilities();o.initialized=true,o.capabilities={embedding:F.embedding===true,graphLlm:F.graphLlm===true},o.embeddingModel=o.capabilities.embedding?"configured":void 0,o.graphModel=o.capabilities.graphLlm?"configured":void 0;}if(!r.skipEmbeddingProbe&&!r.skipLlm&&o.initialized&&o.capabilities.embedding)try{let O=a$1.getEmbeddingLlm?.();if(O){let F=await probeEmbeddingDims(O,{timeoutMs:5e3});if(typeof F=="number"){D=F,s.embeddingDims=String(F);try{let k=new e(t.dbPath);try{await k.initialize();let j=k.getDb();syncMeta(j,[["embeddingDims",String(F)]]);}finally{k.close();}}catch{}}}}catch{}let R;return C?I==="uninitialized"&&(R="Run `easbot memory remember <content>` to add the first fact."):R="Run `easbot memory init` to initialize the database.",C&&(I??"uninitialized")==="failed"&&(C=false),se.info("status complete",{dbPath:t.dbPath,agentId:n??"<global>",factsCount:i,nodesCount:g,edgesCount:l,healthy:C}),{package:"memory",agentId:n,dbPath:t.dbPath,configPath:Ne(t.workspaceDir),configExists:true,schemaVersion:p,extractionVersion:y,lastSyncAt:h,indexState:I,vectorEnabled:M,embeddingDims:D,llm:o,backend:v,counts:c,meta:s,recommendation:R,healthy:C,factsByCategory:b,kgScopeEnabled:u,factsCount:i,nodesCount:g,edgesCount:l,ftsAvailable:E}}var Nn=Log.create({service:"memory.service.doctor"}),Pe=100*1024*1024,ht=100*1024*1024,Tn={};function N(t,e,r,n,o){return {code:t.toUpperCase().replace(/[^A-Z0-9]+/g,"_"),severity:e,name:t,message:r,details:o,durationMs:n,passed:e!=="error"}}async function bt(t,e$1={},r=Tn){if(Nn.debug("doctor invoked",{agentId:t.agentId}),!t.dbPath||t.dbPath.length===0)throw new Error("`ctx.dbPath` is required");let n=[],o=[],c=Date.now(),s=null,i=false,g=Date.now();try{s=new e(t.dbPath),await s.initialize(),i=!0;let d=s.healthCheck(),m=N("database",d?"ok":"error",d?"database connected and writable":"database unhealthy",Date.now()-g,{dbPath:t.dbPath});n.push(m),o.push({name:m.name,passed:m.severity!=="error",message:m.message,details:m.details,severity:m.severity});}catch(d){let m=N("database","error",`database connection failed: ${d instanceof Error?d.message:String(d)}`,Date.now()-g,{dbPath:t.dbPath});n.push(m),o.push({name:m.name,passed:false,message:m.message,details:m.details,severity:"error"});}let l=Date.now();if(i&&s)try{let d=s.query("SELECT name FROM sqlite_master WHERE type = ? AND name = ?",["table","memory_facts_fts"]),m=d.length>0,w=N("fts",m?"ok":"warn",m?"FTS5 index available":"FTS5 index not found",Date.now()-l,m?{table:d[0]?.name}:void 0);n.push(w),o.push({name:w.name,passed:w.severity!=="error",message:w.message,details:w.details,severity:w.severity});}catch(d){let m=N("fts","error",`fts probe failed: ${d instanceof Error?d.message:String(d)}`,Date.now()-l);n.push(m),o.push({name:m.name,passed:false,message:m.message,details:m.details,severity:"error"});}else {let d=N("fts","info","skipped (db not initialized)",0);n.push(d),o.push({name:d.name,passed:true,message:d.message,severity:"info"});}let p=Date.now(),y=!!t.config?.embeddingLlm,h=N("vector","ok",y?"embedding model available":"no embedding model configured (FTS-only mode, recall still functional)",Date.now()-p,{mode:y?"hybrid":"fts_only",model:y?"configured":"missing"});n.push(h),o.push({name:h.name,passed:true,message:h.message,details:h.details,severity:"ok"});let M=Date.now();if(i&&s)try{let d=["memory_facts","nodes","edges","meta"],m=s.query("SELECT name FROM sqlite_master WHERE type = ?",["table"]),w=new Set(m.map($=>$.name)),T=d.filter($=>!w.has($)),P=N("schema",T.length===0?"ok":"error",T.length===0?`schema complete (${d.length} tables)`:`missing tables: ${T.join(", ")}`,Date.now()-M,{required:d,existing:Array.from(w)});n.push(P),o.push({name:P.name,passed:P.severity!=="error",message:P.message,details:P.details,severity:P.severity});}catch(d){let m=N("schema","error",`schema probe failed: ${d instanceof Error?d.message:String(d)}`,Date.now()-M);n.push(m),o.push({name:m.name,passed:false,message:m.message,details:m.details,severity:"error"});}else {let d=N("schema","info","skipped (db not initialized)",0);n.push(d),o.push({name:d.name,passed:true,message:d.message,severity:"info"});}let D=Date.now();try{let d=`${t.dbPath}-wal`,m=`${t.dbPath}-shm`,w=0,T=0;try{w=(await K.stat(d)).size;}catch{w=0;}try{T=(await K.stat(m)).size;}catch{T=0;}let P=w+T,$=P<=ht,U=N("lock",$?"ok":"warn",$?`no lock contention (wal+shm ${(P/1024).toFixed(1)} KB)`:`WAL/SHM files unusually large (${(P/1024/1024).toFixed(1)} MB > ${(ht/1024/1024).toFixed(0)} MB threshold)`,Date.now()-D,{walBytes:w,shmBytes:T});n.push(U),o.push({name:U.name,passed:U.severity!=="error",message:U.message,details:U.details,severity:U.severity});}catch(d){let m=N("lock","error",`lock probe failed: ${d instanceof Error?d.message:String(d)}`,Date.now()-D);n.push(m),o.push({name:m.name,passed:false,message:m.message,details:m.details,severity:"error"});}let I=Date.now();try{let d=pe.dirname(t.dbPath),m=await K.statfs(d),w=typeof m.bsize=="bigint"?Number(m.bsize)*m.bavail:m.bsize*m.bavail,T=w>=Pe,P=N("disk_space",T?"ok":"error",T?`sufficient disk space (${(w/1024/1024).toFixed(1)} MB available)`:`low disk space (${(w/1024/1024).toFixed(1)} MB < ${(Pe/1024/1024).toFixed(0)} MB threshold)`,Date.now()-I,{availableBytes:w,threshold:Pe});n.push(P),o.push({name:P.name,passed:P.severity!=="error",message:P.message,details:P.details,severity:P.severity});}catch(d){let m=N("disk_space","error",`disk_space probe failed: ${d instanceof Error?d.message:String(d)}`,Date.now()-I);n.push(m),o.push({name:m.name,passed:false,message:m.message,details:m.details,severity:"error"});}let u=Date.now();if(i&&s)try{let d=s.agentFilter(t.agentId),w=s.query(`SELECT COUNT(*) as c FROM memory_facts ${d.where}`,d.params)[0]?.c??0;if(w===0){let T=N("fact_node_consistency","info","no facts in db \u2014 nothing to check",Date.now()-u);n.push(T),o.push({name:T.name,passed:!0,message:T.message,severity:"info"});}else {let P=s.query(`SELECT COUNT(DISTINCT fn.fact_id) as c
|
|
59
|
-
FROM fact_nodes fn
|
|
60
|
-
INNER JOIN memory_facts mf ON mf.id = fn.fact_id
|
|
61
|
-
${d.where}`,d.params)[0]?.c??0,$=w>0?P/w*100:0,U=$>=50?"ok":$>=30?"info":"warn",W=$>=50?`${$.toFixed(1)}% facts linked to KG nodes`:$>=30?`${$.toFixed(1)}% facts linked to KG nodes \u2014 run \`easbot memory remember\` to improve`:`${$.toFixed(1)}% facts linked to KG nodes \u2014 KG extraction may be disabled`,X=N("fact_node_consistency",U,W,Date.now()-u,{facts:w,linked:P,pct:$});n.push(X),o.push({name:X.name,passed:X.severity!=="error",message:X.message,details:X.details,severity:X.severity});}}catch(d){let m=N("fact_node_consistency","warn",`fact_node_consistency probe failed: ${d instanceof Error?d.message:String(d)}`,Date.now()-u);n.push(m),o.push({name:m.name,passed:false,message:m.message,details:m.details,severity:"warn"});}else {let d=N("fact_node_consistency","info","skipped (db not initialized)",0);n.push(d),o.push({name:d.name,passed:true,message:d.message,severity:"info"});}let E=Date.now();if(i&&s)try{let m=s.query("SELECT COUNT(*) as c FROM nodes"+(t.agentId?" WHERE owner_agent_id = ?":""),t.agentId?[t.agentId]:[])[0]?.c??0;if(m===0){let w=N("node_embedding_coverage","info","no nodes in KG \u2014 nothing to check",Date.now()-E);n.push(w),o.push({name:w.name,passed:!0,message:w.message,severity:"info"});}else {let T=s.query("SELECT COUNT(*) as c FROM nodes WHERE embedding IS NOT NULL"+(t.agentId?" AND owner_agent_id = ?":""),t.agentId?[t.agentId]:[])[0]?.c??0,P=m>0?T/m*100:0,$=P>=50?"ok":P>=30?"info":"warn",U=P>=50?`${P.toFixed(1)}% nodes have embedding (${T}/${m})`:P>=30?`${P.toFixed(1)}% nodes have embedding (${T}/${m}) \u2014 GraphRAG entity vector partial`:`${P.toFixed(1)}% nodes have embedding (${T}/${m}) \u2014 GraphRAG entity vector disabled`,W=N("node_embedding_coverage",$,U,Date.now()-E,{total:m,withEmbedding:T,pct:P});n.push(W),o.push({name:W.name,passed:W.severity!=="error",message:W.message,details:W.details,severity:W.severity});}}catch(d){let m=N("node_embedding_coverage","warn",`node_embedding_coverage probe failed: ${d instanceof Error?d.message:String(d)}`,Date.now()-E);n.push(m),o.push({name:m.name,passed:false,message:m.message,details:m.details,severity:"warn"});}else {let d=N("node_embedding_coverage","info","skipped (db not initialized)",0);n.push(d),o.push({name:d.name,passed:true,message:d.message,severity:"info"});}let C=Date.now();if(i&&s)try{let m=s.query(`SELECT fn.fact_id, fn.node_id
|
|
62
|
-
FROM fact_nodes fn
|
|
63
|
-
LEFT JOIN nodes n ON fn.node_id = n.id
|
|
64
|
-
WHERE n.id IS NULL
|
|
65
|
-
LIMIT 100`).map(T=>`${T.fact_id}->${T.node_id}`),w=N("orphan",m.length===0?"ok":"warn",m.length===0?"no orphan KG references (fact_nodes all resolved)":`${m.length} orphan fact_nodes references: ${m.slice(0,5).join(", ")}${m.length>5?", ...":""}`,Date.now()-C,{count:m.length});n.push(w),o.push({name:w.name,passed:w.severity!=="error",message:w.message,details:w.details,severity:w.severity});}catch(d){let m=N("orphan","warn",`orphan probe failed: ${d instanceof Error?d.message:String(d)}`,Date.now()-C);n.push(m),o.push({name:m.name,passed:false,message:m.message,details:m.details,severity:"warn"});}else {let d=N("orphan","info","skipped (db not initialized)",0);n.push(d),o.push({name:d.name,passed:true,message:d.message,severity:"info"});}let v=Date.now(),b={"better-sqlite3":false,"node:sqlite":false,"@tursodatabase/database":false};try{let d=createRequire(import.meta.url);try{d.resolve("better-sqlite3"),b["better-sqlite3"]=!0;}catch{}b["node:sqlite"]=typeof process.versions.sqlite=="string";try{d.resolve("@tursodatabase/database"),b["@tursodatabase/database"]=!0;}catch{}}catch{}let _=b["better-sqlite3"]||b["node:sqlite"],R=N("backend",_?"ok":"error",_?`SQLite backend available (better-sqlite3: ${b["better-sqlite3"]}, node:sqlite: ${b["node:sqlite"]})`:"no SQLite backend available (install better-sqlite3 or use Node 22.5+)",Date.now()-v,b);n.push(R),o.push({name:R.name,passed:R.severity!=="error",message:R.message,details:R.details,severity:R.severity});let f=Date.now();if(i&&s)try{let d=s.query("SELECT COUNT(*) as c FROM embedding_cache")[0],m=s.agentFilter(t.agentId),w=s.query(`SELECT COUNT(*) as c FROM memory_facts ${m.where}`,m.params)[0],T=d?.c??0,P=w?.c??0,$=Math.max(0,T-P),U=$>0,W=N("embedding_cache_unused","info",U?`by design: ${$} embedding_cache rows remain after fact deletion (cache is global content-hash dedup; forget intentionally doesn't cascade clear cache to preserve same-content hit rate)`:"embedding_cache in sync with memory_facts (no unused rows)",Date.now()-f,{cacheCount:T,factsCount:P,unused:$,policy:"global_content_hash_dedup"});n.push(W),o.push({name:W.name,passed:!U,message:W.message,details:W.details,severity:"info"});}catch(d){let m=N("embedding_cache_unused","info",`embedding_cache_unused probe failed: ${d instanceof Error?d.message:String(d)}`,Date.now()-f);n.push(m),o.push({name:m.name,passed:true,message:m.message,severity:"info"});}else {let d=N("embedding_cache_unused","info","skipped (db not initialized)",0);n.push(d),o.push({name:d.name,passed:true,message:d.message,severity:"info"});}let O=Date.now(),F;if(i&&s)try{let d=s.query("SELECT value FROM meta WHERE key = ?",["embeddingDims"]);F=d[0]?.value&&Number.parseInt(d[0].value,10)||void 0;}catch{}let k;if(r.skipLlm||!a$1.isInitialized()||!a$1.capabilities().embedding)k=N(EMBEDDING_DIMS_CONSISTENCY_CHECK,"info","llm not initialized; probe skipped",Date.now()-O);else if(r.skipEmbeddingProbe)k=N(EMBEDDING_DIMS_CONSISTENCY_CHECK,"info","probe skipped (--skip-embedding-probe)",Date.now()-O);else try{let d=a$1.getEmbeddingLlm?.();if(!d)k=N(EMBEDDING_DIMS_CONSISTENCY_CHECK,"info","embedding llm not exposed; probe skipped",Date.now()-O);else {let m=await probeEmbeddingDims(d,{timeoutMs:5e3});typeof m!="number"?k=N(EMBEDDING_DIMS_CONSISTENCY_CHECK,"info","probe failed (network / model error)",Date.now()-O):F===void 0?k=N(EMBEDDING_DIMS_CONSISTENCY_CHECK,"info",`probe=${m}, meta missing \u2014 next status will sync`,Date.now()-O):m!==F?k=N(EMBEDDING_DIMS_CONSISTENCY_CHECK,"warn",`probe=${m}, meta=${F} \u2014 mismatch`,Date.now()-O,{probe:m,meta:F}):k=N(EMBEDDING_DIMS_CONSISTENCY_CHECK,"ok",`probe=${m}, meta=${F} \u2014 consistent`,Date.now()-O);}}catch(d){k=N(EMBEDDING_DIMS_CONSISTENCY_CHECK,"info",`probe threw: ${d instanceof Error?d.message:String(d)}`,Date.now()-O);}n.push({...k,details:k.details??void 0,passed:k.severity!=="error"}),o.push({name:k.name,passed:k.severity!=="error",message:k.message,details:k.details??void 0,severity:k.severity});let j;if(i&&s){let d=Date.now();try{let{issues:m,stats:w}=s.checkIntegrity();j=w;for(let T of m)n.push(N("integrity_stats",T.severity,T.message,0,{source:"database.checkIntegrity"}));}catch(m){n.push(N("integrity_stats","warn",`db integrity check failed: ${m instanceof Error?m.message:String(m)}`,Date.now()-d));}}let z=!n.some(d=>d.severity==="error");s&&s.close();let V=Date.now()-c;return {healthy:z,checks:n,legacyChecks:o,durationMs:V,integrityStats:j,backendAvailable:b}}var ke={name:"recall",scope:"read",schema:ze,annotations:{localOnly:false,requiresAgentId:true,defaultDescription:"Query memory via hybrid search (FTS + vector); returns ranked facts.",readOnlyHint:true,destructiveHint:false,idempotentHint:true},handler:async(t,e)=>{let r=t;if(!e.agentId?.trim())throw new Error("recall: agentId is required");return Be({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:e.remote??false,config:e.config,agentId:e.agentId},r)}};var Ae={name:"remember",scope:"write",schema:Qe,annotations:{localOnly:false,requiresAgentId:true,defaultDescription:"Persist a new self-memory fact; auto-extract entities into KG.",readOnlyHint:false,destructiveHint:false,idempotentHint:false},handler:async(t,e)=>{let r=t;if(!e.agentId?.trim())throw new Error("remember: agentId is required");return ot({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:e.remote??false,config:e.config,agentId:e.agentId},r)}};var xe={name:"update",scope:"write",schema:Ke,annotations:{localOnly:false,requiresAgentId:true,defaultDescription:"Update an existing memory fact (atomic; preserves factId + KG associations).",readOnlyHint:false,destructiveHint:false,idempotentHint:true},handler:async(t,e)=>{let r=t;if(!e.agentId?.trim())throw new Error("update: agentId is required");return at({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:e.remote??false,config:e.config,agentId:e.agentId},r)}};var Le={name:"forget",scope:"write",schema:Je,annotations:{localOnly:false,requiresAgentId:true,defaultDescription:"Delete memory facts by id / category / time range; supports dryRun.",readOnlyHint:false,destructiveHint:true,idempotentHint:true},handler:async(t,e)=>{let r=t;if(!e.agentId?.trim())throw new Error("forget: agentId is required");return st({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:e.remote??false,config:e.config,agentId:e.agentId},r)}};var Fe={name:"extract",scope:"write",schema:Ve,annotations:{localOnly:false,requiresAgentId:true,defaultDescription:"Extract facts from a session (server-side pulls messages by lastN).",readOnlyHint:false,destructiveHint:false,idempotentHint:true},handler:async(t,e)=>{let r=t;if(!e.agentId?.trim())throw new Error("extract: agentId is required");return ct({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:e.remote??false,config:e.config,agentId:e.agentId},r)}};var qe={name:"consolidate",scope:"admin",schema:Ye,annotations:{localOnly:true,requiresAgentId:true,defaultDescription:"Run consolidation pipeline: dedup \u2192 archive.",readOnlyHint:false,destructiveHint:true,idempotentHint:true},handler:async(t,e)=>{let r=t;if(!e.isTrustedLocal)throw new Error("consolidate: only trusted local process can invoke this op");if(!e.agentId?.trim())throw new Error("consolidate: agentId is required");return dt({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:false,config:e.config,agentId:e.agentId},r)}};var $e={name:"sync",scope:"admin",schema:nt,annotations:{localOnly:true,requiresAgentId:true,defaultDescription:"Sync memory facts to .md files (idempotent skip on existing) and archive expired active files (default 30 days)",readOnlyHint:false,destructiveHint:true,idempotentHint:true},handler:async(t,e)=>{let r=t;if(!e.isTrustedLocal)throw new Error("sync: only trusted local process can invoke this op");if(!e.agentId?.trim())throw new Error("sync: agentId is required");return gt({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:false,config:e.config,agentId:e.agentId},r)}};var He={name:"graph_query",scope:"read",schema:Xe,annotations:{localOnly:false,requiresAgentId:true,defaultDescription:"Query KG nodes / edges / neighbors with scope filtering.",readOnlyHint:true,destructiveHint:false,idempotentHint:true},handler:async(t,e)=>{let r=t,n=e.agentId?.trim()||"default";return ft({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:e.remote??false,config:e.config,agentId:n},r)}};var Ue={name:"status",scope:"read",schema:Ze,annotations:{localOnly:false,requiresAgentId:false,defaultDescription:"Memory system status (factsCount / nodesCount / edgesCount / fts / vector).",readOnlyHint:true,destructiveHint:false,idempotentHint:true},handler:async(t,e)=>{let r=t??{};return yt({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:e.remote??false,config:e.config,agentId:e.agentId},r)}};var We={name:"doctor",scope:"admin",schema:et,annotations:{localOnly:true,requiresAgentId:false,defaultDescription:"Run 7 health checks (database / fts / vector / schema / lock / disk_space / orphan).",readOnlyHint:true,destructiveHint:false,idempotentHint:true},handler:async(t,e)=>{let r=t??{};if(!e.isTrustedLocal)throw new Error("doctor: only trusted local process can invoke this op");return bt({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:false,config:e.config,agentId:e.agentId},r)}};var Ge={name:"init",scope:"admin",schema:tt,annotations:{localOnly:true,requiresAgentId:false,defaultDescription:"Initialize memory workspace (dirs + db schema + meta).",readOnlyHint:false,destructiveHint:false,idempotentHint:true},handler:async(t,e)=>{if(!e.isTrustedLocal)throw new Error("init: only trusted local process can invoke this op");let r=t??{};return pt({workspaceDir:r.workspaceDir??e.workspaceDir??"",rootDir:r.workspaceDir??e.workspaceDir??"",dbPath:r.dbPath??e.dbPath??"",locale:e.locale??"en-US",remote:false,config:e.config,agentId:e.agentId??""},r)}};var Et={[ke.name]:ke,[Ae.name]:Ae,[xe.name]:xe,[Le.name]:Le,[Fe.name]:Fe,[qe.name]:qe,[$e.name]:$e,[He.name]:He,[Ue.name]:Ue,[We.name]:We,[Ge.name]:Ge},Pn=Object.values(Et);function kn(t,e,r){if(t.annotations.localOnly&&!e.isTrustedLocal)throw new Error(`MEMORY:executeOp: op "${r}" is localOnly; non-trusted caller rejected`);if(t.annotations.requiresAgentId){let n=e.agentId?.trim()??"";if(n.length===0)throw new Error(`MEMORY:executeOp: op "${r}" requires agentId`);e.agentId=n;}}async function Ja(t,e,r){let n=Et[t];if(!n)throw new Error(`executeOp: unknown op "${t}"; available: ${Pn.map(c=>c.name).join(", ")}`);return kn(n,r,t),await n.handler(e,r)}function Ln(t){let e=t.dbPath??"";return {workspaceDir:t.workspaceDir??"",database:{path:e},embeddingLlm:a$1.getEmbeddingLlm(),graphLlm:a$1.getGraphLlm(),search:DEFAULT_SEARCH_CONFIG,indexer:{batchSize:20,ignorePatterns:[],incremental:true},archiveDays:30,shortTermMaxRounds:20}}function os(t,e,r={}){let n=j(e),o=Locale.resolveLocaleLang(r.locale);return {agentId:t,dbPath:n,workspaceDir:e,rootDir:e,config:Ln({dbPath:n,workspaceDir:e}),isTrustedLocal:true,locale:o,remote:false,...r}}export{ee as a,Be as b,ze as c,Qe as d,Je as e,Ve as f,Ye as g,Xe as h,tt as i,nt as j,ot as k,at as l,st as m,ct as n,dt as o,gt as p,ft as q,pt as r,yt as s,bt as t,Et as u,Pn as v,Ja as w,Ln as x,os as y};
|