@easbot/memory 0.3.17 → 0.3.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/README.en.md +101 -0
  2. package/README.md +116 -11
  3. package/dist/chunks/chunk-4GSXSIV5.cjs +1 -0
  4. package/dist/chunks/chunk-6CQMBEIQ.mjs +1 -0
  5. package/dist/chunks/chunk-AYGZUNFR.cjs +1 -0
  6. package/dist/chunks/{chunk-OIUUTVLL.cjs → chunk-EGWJG65Q.cjs} +22 -4
  7. package/dist/chunks/chunk-J5XF2W4Z.cjs +1 -0
  8. package/dist/chunks/chunk-JDPZ5U53.mjs +71 -0
  9. package/dist/chunks/chunk-N5YRDTEH.mjs +60 -0
  10. package/dist/chunks/{chunk-MWRDF6VN.mjs → chunk-QYBWHFOX.mjs} +1 -1
  11. package/dist/chunks/chunk-S6S35LDL.cjs +60 -0
  12. package/dist/chunks/chunk-SWYQLQ7Z.mjs +1 -0
  13. package/dist/chunks/chunk-TIZCWDJ7.mjs +1 -0
  14. package/dist/chunks/chunk-UF2Y2Q4L.mjs +50 -0
  15. package/dist/chunks/chunk-WQB4D6DZ.cjs +1 -0
  16. package/dist/chunks/chunk-Z5E4HBGK.cjs +50 -0
  17. package/dist/chunks/cli-handler-2IPBL45N.cjs +1 -0
  18. package/dist/chunks/cli-handler-5YNHYDSM.mjs +1 -0
  19. package/dist/chunks/consolidate-G4YJV756.cjs +2 -0
  20. package/dist/chunks/consolidate-MSPLH3T6.mjs +2 -0
  21. package/dist/chunks/doctor-GKMREWZN.mjs +1 -0
  22. package/dist/chunks/doctor-YTUQCHFJ.cjs +1 -0
  23. package/dist/chunks/extract-3C4QFS7E.mjs +2 -0
  24. package/dist/chunks/extract-YKDPZ7GA.cjs +2 -0
  25. package/dist/chunks/forget-GNIJL2DU.cjs +3 -0
  26. package/dist/chunks/{forget-A4UJI3LE.mjs → forget-VQB5DUJ3.mjs} +1 -1
  27. package/dist/chunks/{graph-XZ46LEO7.mjs → graph-4W63TU2D.mjs} +1 -1
  28. package/dist/chunks/graph-GTYUNUJE.cjs +3 -0
  29. package/dist/chunks/init-DGMGRNCG.cjs +1 -0
  30. package/dist/chunks/init-G2WTR477.mjs +1 -0
  31. package/dist/chunks/llm-RMPVWEVP.cjs +1 -0
  32. package/dist/chunks/llm-UHTBU2HA.mjs +1 -0
  33. package/dist/chunks/{mcp-BXVXTUJK.cjs → mcp-EHUKGJRB.cjs} +1 -1
  34. package/dist/chunks/{mcp-BOD4ZOZS.mjs → mcp-QQBHEZFY.mjs} +1 -1
  35. package/dist/chunks/recall-SGA2DITO.mjs +2 -0
  36. package/dist/chunks/recall-ZENMAOMJ.cjs +2 -0
  37. package/dist/chunks/remember-3ZY66RJQ.cjs +2 -0
  38. package/dist/chunks/remember-P3G7WWYB.mjs +2 -0
  39. package/dist/chunks/status-JYI52QKB.mjs +1 -0
  40. package/dist/chunks/status-UEKBJVCI.cjs +1 -0
  41. package/dist/chunks/stdio-server-2PWTBTDJ.mjs +1 -0
  42. package/dist/chunks/stdio-server-JL4XNUHH.cjs +1 -0
  43. package/dist/chunks/sync-64JINCSC.cjs +2 -0
  44. package/dist/chunks/sync-ZPRCA4MO.mjs +2 -0
  45. package/dist/cli.cjs +1 -1
  46. package/dist/cli.mjs +1 -1
  47. package/dist/index.cjs +4 -4
  48. package/dist/index.d.cts +87 -38
  49. package/dist/index.d.ts +87 -38
  50. package/dist/index.mjs +4 -4
  51. package/package.json +9 -8
  52. package/dist/chunks/chunk-BSKFK4RC.mjs +0 -1
  53. package/dist/chunks/chunk-DFWC6WII.mjs +0 -53
  54. package/dist/chunks/chunk-DXU5WPK3.cjs +0 -42
  55. package/dist/chunks/chunk-EECBJNZI.mjs +0 -59
  56. package/dist/chunks/chunk-FMEXQ5YE.cjs +0 -59
  57. package/dist/chunks/chunk-HSK27DQ7.cjs +0 -1
  58. package/dist/chunks/chunk-I6XVFDN2.mjs +0 -42
  59. package/dist/chunks/chunk-QNDG7BTB.cjs +0 -1
  60. package/dist/chunks/chunk-RSJ2KT6X.cjs +0 -1
  61. package/dist/chunks/chunk-TPSRK4M3.mjs +0 -1
  62. package/dist/chunks/cli-handler-6VTKYXXM.mjs +0 -1
  63. package/dist/chunks/cli-handler-HNPA3STD.cjs +0 -1
  64. package/dist/chunks/consolidate-6P7LUPPL.cjs +0 -2
  65. package/dist/chunks/consolidate-NYH4IKJK.mjs +0 -2
  66. package/dist/chunks/doctor-IJJ5UYGT.cjs +0 -2
  67. package/dist/chunks/doctor-MZSZGVRL.mjs +0 -2
  68. package/dist/chunks/extract-6B7OD3VK.mjs +0 -2
  69. package/dist/chunks/extract-ERTOHQV6.cjs +0 -2
  70. package/dist/chunks/forget-KLFM5SBQ.cjs +0 -3
  71. package/dist/chunks/graph-P5ZHB4ZM.cjs +0 -3
  72. package/dist/chunks/init-CCOSHE3F.cjs +0 -3
  73. package/dist/chunks/init-WEPU32KF.mjs +0 -3
  74. package/dist/chunks/recall-BV4Z7HUJ.mjs +0 -2
  75. package/dist/chunks/recall-FEINUJKO.cjs +0 -2
  76. package/dist/chunks/remember-ESVRA73C.mjs +0 -2
  77. package/dist/chunks/remember-YNSY2JJB.cjs +0 -2
  78. package/dist/chunks/status-KVM7I6YC.cjs +0 -2
  79. package/dist/chunks/status-QQZS3ZCN.mjs +0 -2
  80. package/dist/chunks/stdio-server-MQKTUGNG.cjs +0 -1
  81. package/dist/chunks/stdio-server-ZLMSUTC5.mjs +0 -1
package/dist/index.d.ts CHANGED
@@ -1,8 +1,8 @@
1
- import { KnowledgeSearchOptions, MemoryKnowledgeConfigWithModels, IGlobal, IInstance } from '@easbot/types';
1
+ import { KnowledgeSearchOptions, MemoryKnowledgeConfigWithModels, KnowledgeDoctorResult, MemoryStatus, IGlobal, IInstance } from '@easbot/types';
2
2
  export { GRAPH_ENTITY_TYPE_DEFINITIONS, GRAPH_RELATION_TYPE_DEFINITIONS } from '@easbot/types';
3
3
  import { EmbeddingModel, LanguageModel } from 'ai';
4
4
  export { EmbeddingModel, LanguageModel } from 'ai';
5
- import { BuildPromptOptions } from '@easbot/utils';
5
+ import { ILLMInitConfig, ILLMCapabilities } from '@easbot/llm';
6
6
  import { ZodTypeAny } from 'zod';
7
7
  import { StdioServerConfig } from '@easbot/mcp';
8
8
  import { SyncSqliteConnection } from '@easbot/database';
@@ -158,35 +158,27 @@ interface LlmModels {
158
158
  embeddingLlm?: EmbeddingModel;
159
159
  graphLlm?: LanguageModel;
160
160
  }
161
- interface LlmOptions {
162
- maxOutputTokens?: number;
163
- temperature?: number;
164
- }
165
- interface LlmInitConfig {
166
- models: LlmModels;
161
+ interface LlmInitConfig extends ILLMInitConfig {
167
162
  options?: {
168
- graph?: LlmOptions;
169
- embedding?: LlmOptions;
163
+ graph?: {
164
+ maxOutputTokens?: number;
165
+ temperature?: number;
166
+ };
167
+ embedding?: {
168
+ maxOutputTokens?: number;
169
+ temperature?: number;
170
+ };
170
171
  };
171
172
  }
172
173
  declare namespace Llm {
173
- function init(config: LlmInitConfig): void;
174
+ function init(config: ILLMInitConfig): void;
174
175
  function isInitialized(): boolean;
175
176
  function reset(): void;
176
- function capabilities(): {
177
- embedding: boolean;
178
- graph: boolean;
179
- };
177
+ function capabilities(): ILLMCapabilities;
178
+ function getEmbeddingLlm(): EmbeddingModel | undefined;
179
+ function getGraphLlm(): LanguageModel | undefined;
180
180
  function embedText(value: string): Promise<Float32Array>;
181
181
  function embedTexts(values: string[]): Promise<Float32Array[]>;
182
- function generateGraph(chunks: string[], entityTypes: ReadonlyArray<{
183
- type: string;
184
- rule: string;
185
- }>, relationTypes: ReadonlyArray<{
186
- type: string;
187
- rule: string;
188
- }>, options?: BuildPromptOptions & LlmOptions): Promise<string>;
189
- function generate(prompt: string, options?: LlmOptions): Promise<string>;
190
182
  const embed: typeof embedText;
191
183
  const embedMany: typeof embedTexts;
192
184
  }
@@ -243,6 +235,8 @@ interface RememberResult {
243
235
  nodeIds?: number[];
244
236
  vectorsWritten: number;
245
237
  vectorDims: number;
238
+ entitiesExtracted: number;
239
+ relationsExtracted: number;
246
240
  }
247
241
  interface ForgetParams {
248
242
  factId?: string;
@@ -315,29 +309,37 @@ interface GraphQueryResult {
315
309
  durationMs: number;
316
310
  }
317
311
  type StatusParams = {};
318
- interface StatusResult {
319
- dbPath: string;
320
- workspaceDir: string;
312
+ interface StatusResult extends MemoryStatus {
321
313
  factsCount: number;
322
314
  nodesCount: number;
323
315
  edgesCount: number;
324
316
  factsByCategory: Record<MemoryCategory, number>;
325
317
  ftsAvailable: boolean;
326
- vectorEnabled: boolean;
327
- kgScopeEnabled: boolean;
328
- healthy: boolean;
329
- meta: Record<string, string>;
330
318
  }
331
319
  type DoctorParams = {};
332
- interface DoctorResult {
333
- healthy: boolean;
334
- checks: Array<{
320
+ interface DoctorResult extends KnowledgeDoctorResult {
321
+ legacyChecks: Array<{
335
322
  name: string;
336
323
  passed: boolean;
337
324
  message: string;
338
325
  details?: Record<string, unknown>;
339
- severity?: 'error' | 'info';
326
+ severity?: 'error' | 'info' | 'warn' | 'ok';
340
327
  }>;
328
+ integrityStats?: {
329
+ memory_facts: number;
330
+ memory_vectors: number;
331
+ embedding_cache: number;
332
+ memory_facts_fts: number;
333
+ nodes: number;
334
+ edges: number;
335
+ meta: number;
336
+ schema_migrations: number;
337
+ };
338
+ backendAvailable?: {
339
+ 'better-sqlite3': boolean;
340
+ 'node:sqlite': boolean;
341
+ '@tursodatabase/database': boolean;
342
+ };
341
343
  }
342
344
  interface InitParams {
343
345
  dbPath?: string;
@@ -349,12 +351,33 @@ interface InitResult {
349
351
  initialized: boolean;
350
352
  dbPath: string;
351
353
  configPath: string;
354
+ schemaVersion: number;
352
355
  workspaceDir: string;
353
356
  tablesCreated: number;
354
357
  migrationsApplied: number;
355
358
  durationMs: number;
356
359
  configCreated: boolean;
357
360
  }
361
+ interface SyncParams {
362
+ windowDays?: number;
363
+ dryRun?: boolean;
364
+ }
365
+ interface SyncResult {
366
+ generatedCount: number;
367
+ skippedCount: number;
368
+ failedGenerateCount: number;
369
+ archivedCount: number;
370
+ archiveThreshold: string;
371
+ archivedRecords: Array<{
372
+ source: string;
373
+ target: string;
374
+ firstCreatedAt: string;
375
+ firstFactId: string;
376
+ }>;
377
+ windowDays: number;
378
+ dryRun: boolean;
379
+ durationMs: number;
380
+ }
358
381
 
359
382
  declare function recall(ctx: MemoryServiceContext, params: RecallParams): Promise<RecallResult>;
360
383
 
@@ -366,11 +389,21 @@ declare function extract(ctx: MemoryServiceContext, params: ExtractParams): Prom
366
389
 
367
390
  declare function consolidate(ctx: MemoryServiceContext, params?: ConsolidateParams): Promise<ConsolidateResult>;
368
391
 
392
+ declare function sync(ctx: MemoryServiceContext, params?: SyncParams): Promise<SyncResult>;
393
+
369
394
  declare function graphQuery(ctx: MemoryServiceContext, params: GraphQueryParams): Promise<GraphQueryResult>;
370
395
 
371
- declare function status(ctx: MemoryServiceContext, _params?: StatusParams): Promise<StatusResult>;
396
+ interface StatusOptions {
397
+ skipEmbeddingProbe?: boolean;
398
+ skipLlm?: boolean;
399
+ }
400
+ declare function status(ctx: MemoryServiceContext, _params?: StatusParams, options?: StatusOptions): Promise<StatusResult>;
372
401
 
373
- declare function doctor(ctx: MemoryServiceContext, _params?: DoctorParams): Promise<DoctorResult>;
402
+ interface DoctorOptions {
403
+ skipEmbeddingProbe?: boolean;
404
+ skipLlm?: boolean;
405
+ }
406
+ declare function doctor(ctx: MemoryServiceContext, _params?: DoctorParams, options?: DoctorOptions): Promise<DoctorResult>;
374
407
 
375
408
  declare function init(ctx: MemoryServiceContext, params?: InitParams): Promise<InitResult>;
376
409
 
@@ -480,7 +513,7 @@ declare function getMemoryDbPath(input?: string | {
480
513
  }): string;
481
514
 
482
515
  type MigrationDb = SyncSqliteConnection;
483
- declare const LATEST_SCHEMA_VERSION = 2;
516
+ declare const LATEST_SCHEMA_VERSION = 1;
484
517
  interface SchemaMigration {
485
518
  id: number;
486
519
  description: string;
@@ -532,6 +565,22 @@ declare class MemoryDatabaseManager {
532
565
  getSchemaVersion(): number;
533
566
  close(): void;
534
567
  healthCheck(): boolean;
568
+ checkIntegrity(): {
569
+ issues: Array<{
570
+ severity: 'error' | 'warn' | 'info';
571
+ message: string;
572
+ }>;
573
+ stats: {
574
+ memory_facts: number;
575
+ memory_vectors: number;
576
+ embedding_cache: number;
577
+ memory_facts_fts: number;
578
+ nodes: number;
579
+ edges: number;
580
+ meta: number;
581
+ schema_migrations: number;
582
+ };
583
+ };
535
584
  getMeta(key: string): string | null;
536
585
  setMeta(key: string, value: string): void;
537
586
  }
@@ -581,4 +630,4 @@ declare function registerAllDefaultHooks(): void;
581
630
  declare function clearAllHooks(): void;
582
631
  declare function dispatchHook(name: HookName, ctx: HookContext): Promise<HookResult>;
583
632
 
584
- export { ALL_OPS, type ArchiveRecord, type ArchiveResult, COMMANDS_HELP, type CommandHelp, type ConsolidateParams, type ConsolidateResult, type DoctorResult, type EdgeQueryFilter, type ErrorCode, type ExtractParams, type ExtractResult, type ForgetParams, type ForgetResult, type GraphQueryParams, type GraphQueryResult, GraphStore, type HookContext, type HookHandler, type HookName, type HookResult, type InitParams, type InitResult, type KGScope, LATEST_SCHEMA_VERSION, Llm, type LlmInitConfig, type LlmModels, type LlmOptions, MEMORY_CATEGORIES, MIGRATIONS, type MemoryCategory, type MemoryCliDeps, type MemoryCliResult, MemoryDatabaseError, MemoryDatabaseManager, type MemoryEdge, MemoryEmbeddingError, MemoryError, MemoryErrorCode, type MemoryFact, MemoryFileError, type MemoryNode, type MemoryNodeWithEdges, MemoryNotFoundError, type MemoryOp, MemoryPermissionError, type MemoryQuery, type MemoryRecallResult, MemorySearchError, type MemorySource, MemoryStdioServer, type MemorySystemConfig, MemoryValidationError, type MemoryVector, type NodeQueryFilter, OP_REGISTRY, type OpAnnotations, type OpHandlerContext, type OpScope, type RecallParams, type RecallResult, type RegisteredHook, type RememberParams, type RememberResult, type StatusResult, addWord, clearAllHooks, closeTokenizer, consolidate, dispatchHook, doctor, executeOp, extract, forget, getGlobal, getHomeDir, getInstance, getMemoryDbPath, getMemoryDir, getXdgData, graphQuery, handleMemoryCli, init, initTokenizer, isInitialized, listHooks, loadCustomDict, readCurrentSchemaVersion, recall, registerAllDefaultHooks, registerHook, remember, renderBanner, renderHelp, renderOperationMarkdown, resetGlobalAdapter, resetInstanceAdapter, runMigrations, setGlobalAdapter, setInstanceAdapter, status, toFtsTokens, toFtsTokensForSearch, tokenize, tokenizeForSearch, unregisterHook };
633
+ export { ALL_OPS, type ArchiveRecord, type ArchiveResult, COMMANDS_HELP, type CommandHelp, type ConsolidateParams, type ConsolidateResult, type DoctorResult, type EdgeQueryFilter, type ErrorCode, type ExtractParams, type ExtractResult, type ForgetParams, type ForgetResult, type GraphQueryParams, type GraphQueryResult, GraphStore, type HookContext, type HookHandler, type HookName, type HookResult, type InitParams, type InitResult, type KGScope, LATEST_SCHEMA_VERSION, Llm, type LlmInitConfig, type LlmModels, MEMORY_CATEGORIES, MIGRATIONS, type MemoryCategory, type MemoryCliDeps, type MemoryCliResult, MemoryDatabaseError, MemoryDatabaseManager, type MemoryEdge, MemoryEmbeddingError, MemoryError, MemoryErrorCode, type MemoryFact, MemoryFileError, type MemoryNode, type MemoryNodeWithEdges, MemoryNotFoundError, type MemoryOp, MemoryPermissionError, type MemoryQuery, type MemoryRecallResult, MemorySearchError, type MemorySource, MemoryStdioServer, type MemorySystemConfig, MemoryValidationError, type MemoryVector, type NodeQueryFilter, OP_REGISTRY, type OpAnnotations, type OpHandlerContext, type OpScope, type RecallParams, type RecallResult, type RegisteredHook, type RememberParams, type RememberResult, type StatusResult, type SyncParams, type SyncResult, addWord, clearAllHooks, closeTokenizer, consolidate, dispatchHook, doctor, executeOp, extract, forget, getGlobal, getHomeDir, getInstance, getMemoryDbPath, getMemoryDir, getXdgData, graphQuery, handleMemoryCli, init, initTokenizer, isInitialized, listHooks, loadCustomDict, readCurrentSchemaVersion, recall, registerAllDefaultHooks, registerHook, remember, renderBanner, renderHelp, renderOperationMarkdown, resetGlobalAdapter, resetInstanceAdapter, runMigrations, setGlobalAdapter, setInstanceAdapter, status, sync, toFtsTokens, toFtsTokensForSearch, tokenize, tokenizeForSearch, unregisterHook };
package/dist/index.mjs CHANGED
@@ -1,6 +1,6 @@
1
- export{b as MemoryStdioServer,a as renderOperationMarkdown}from'./chunks/chunk-EECBJNZI.mjs';import'./chunks/chunk-QF5S5MG7.mjs';export{a as COMMANDS_HELP,d as handleMemoryCli,b as renderBanner,c as renderHelp}from'./chunks/chunk-TPSRK4M3.mjs';import {u as u$1,v as v$1}from'./chunks/chunk-I6XVFDN2.mjs';export{t as ALL_OPS,a as GraphStore,b as Llm,s as OP_REGISTRY,n as consolidate,q as doctor,u as executeOp,m as extract,l as forget,o as graphQuery,r as init,c as recall,k as remember,p as status}from'./chunks/chunk-I6XVFDN2.mjs';export{a as LATEST_SCHEMA_VERSION,b as MIGRATIONS,e as MemoryDatabaseManager,d as readCurrentSchemaVersion,c as runMigrations}from'./chunks/chunk-DFWC6WII.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';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 Oe=["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(t,o,n){super(t,{cause:n});a(this,"code",o);a(this,"cause",n);this.name="MemoryError";}},P=class extends d{constructor(r,t){super(r,"MEMORY_VALIDATION_ERROR",t),this.name="MemoryValidationError";}},N=class extends d{constructor(r){super(`Memory not found: ${r}`,"MEMORY_NOT_FOUND"),this.name="MemoryNotFoundError";}},D=class extends d{constructor(r){super(r,"MEMORY_PERMISSION_ERROR"),this.name="MemoryPermissionError";}},T=class extends d{constructor(r,t){super(r,"MEMORY_DATABASE_ERROR",t),this.name="MemoryDatabaseError";}},v=class extends d{constructor(r,t){super(r,"MEMORY_FILE_ERROR",t),this.name="MemoryFileError";}},F=class extends d{constructor(r,t){super(r,"MEMORY_SEARCH_ERROR",t),this.name="MemorySearchError";}},L=class extends d{constructor(r,t){super(r,"MEMORY_EMBEDDING_ERROR",t),this.name="MemoryEmbeddingError";}},me=(i=>(i.VALIDATION_ERROR="MEMORY_VALIDATION_ERROR",i.NOT_FOUND="MEMORY_NOT_FOUND",i.PERMISSION_ERROR="MEMORY_PERMISSION_ERROR",i.DATABASE_ERROR="MEMORY_DATABASE_ERROR",i.FILE_ERROR="MEMORY_FILE_ERROR",i.SEARCH_ERROR="MEMORY_SEARCH_ERROR",i.EMBEDDING_ERROR="MEMORY_EMBEDDING_ERROR",i))(me||{});var s=Log.create({service:"memory.tokenizer"}),c=false,ye=loadTextFile("./assets/jieba_dict.txt",import.meta.url);async function ve(e){if(!c)try{s.debug("Initializing jieba tokenizer");let r=ye();if(m.with_dict(r),s.debug("Built-in dictionary loaded"),e?.dictPath&&e.dictPath.length>0)for(let t of e.dictPath)await Re(t);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 Re(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 ke(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 xe(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 Fe(e,r,t){if(c)try{m.add_word(e,r,t),s.debug("Word added to dictionary",{word:e,freq:r,tag:t});}catch(o){s.warn("Failed to add word",{word:e,error:String(o)});}}function Le(){return c}async function $e(){c=false,s.debug("Tokenizer closed");}function je(e){if(!c)return e.split(/\s+/).filter(Boolean).join(" ");try{return ke(e).join(" ")}catch(r){return s.warn("Tokenization failed, using fallback",{error:String(r)}),e.split(/\s+/).filter(Boolean).join(" ")}}function ze(e){if(!c)return e.split(/\s+/).filter(Boolean).join(" ");try{return xe(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,t=j$1(r);return {agentId:e,isTrustedLocal:true,remote:false,locale:"en-US",dbPath:t,workspaceDir:r,rootDir:r,config:v$1({agentId:e,dbPath:t,workspaceDir:r})}}var $=async e=>{if(!e.agentId?.trim())return {ok:false,error:"session-start: agentId is required in ctx"};let r=e.extras?.topK??5,t=e.extras?.query??"";try{let o=await u$1("recall",{query:t,maxResults:r},u(e.agentId));if(o.hits.length===0)return {ok:!0,injected:"",logLine:"session-start: no facts found for agent; skipping context injection"};let n=o.hits.map(R=>`- [${R.category}/imp=${R.importance}] ${R.snippet.slice(0,200)}`);return {ok:!0,injected:`[memory:session-start recall top-${o.hits.length}]
1
+ import'./chunks/chunk-QF5S5MG7.mjs';export{a as COMMANDS_HELP,d as handleMemoryCli,b as renderBanner,c as renderHelp}from'./chunks/chunk-TIZCWDJ7.mjs';export{b as MemoryStdioServer,a as renderOperationMarkdown}from'./chunks/chunk-N5YRDTEH.mjs';import {v as v$1,w}from'./chunks/chunk-UF2Y2Q4L.mjs';export{u as ALL_OPS,a as GraphStore,t as OP_REGISTRY,n as consolidate,s as doctor,v as executeOp,m as extract,l as forget,p as graphQuery,q as init,b as recall,k as remember,r as status,o as sync}from'./chunks/chunk-UF2Y2Q4L.mjs';export{a as LATEST_SCHEMA_VERSION,b as MIGRATIONS,e as MemoryDatabaseManager,d as readCurrentSchemaVersion,c as runMigrations}from'./chunks/chunk-JDPZ5U53.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 Se=["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(t,o,n){super(t,{cause:n});a(this,"code",o);a(this,"cause",n);this.name="MemoryError";}},N=class extends d{constructor(r,t){super(r,"MEMORY_VALIDATION_ERROR",t),this.name="MemoryValidationError";}},D=class extends d{constructor(r){super(`Memory not found: ${r}`,"MEMORY_NOT_FOUND"),this.name="MemoryNotFoundError";}},T=class extends d{constructor(r){super(r,"MEMORY_PERMISSION_ERROR"),this.name="MemoryPermissionError";}},v=class extends d{constructor(r,t){super(r,"MEMORY_DATABASE_ERROR",t),this.name="MemoryDatabaseError";}},F=class extends d{constructor(r,t){super(r,"MEMORY_FILE_ERROR",t),this.name="MemoryFileError";}},L=class extends d{constructor(r,t){super(r,"MEMORY_SEARCH_ERROR",t),this.name="MemorySearchError";}},$=class extends d{constructor(r,t){super(r,"MEMORY_EMBEDDING_ERROR",t),this.name="MemoryEmbeddingError";}},ue=(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))(ue||{});var s=Log.create({service:"memory.tokenizer"}),c=false,Re=loadTextFile("./assets/jieba_dict.txt",import.meta.url);async function Fe(e){if(!c)try{s.debug("Initializing jieba tokenizer");let r=Re();if(m.with_dict(r),s.debug("Built-in dictionary loaded"),e?.dictPath&&e.dictPath.length>0)for(let t of e.dictPath)await ke(t);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 ke(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 xe(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 Le(e,r,t){if(c)try{m.add_word(e,r,t),s.debug("Word added to dictionary",{word:e,freq:r,tag:t});}catch(o){s.warn("Failed to add word",{word:e,error:String(o)});}}function $e(){return c}async function je(){c=false,s.debug("Tokenizer closed");}function ze(e){if(!c)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 Ye(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,t=j$1(r);return {agentId:e,isTrustedLocal:true,remote:false,locale:"en-US",dbPath:t,workspaceDir:r,rootDir:r,config:w({agentId:e,dbPath:t,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,t=e.extras?.query??"";try{let o=await v$1("recall",{query:t,maxResults:r},u(e.agentId));if(o.hits.length===0)return {ok:!0,injected:"",logLine:"session-start: no facts found for agent; skipping context injection"};let n=o.hits.map(R=>`- [${R.category}/imp=${R.importance}] ${R.snippet.slice(0,200)}`);return {ok:!0,injected:`[memory:session-start recall top-${o.hits.length}]
2
2
  ${n.join(`
3
- `)}`,logLine:`session-start: injected ${o.hits.length} facts into context (agent=${e.agentId})`}}catch(o){return {ok:false,error:o instanceof Error?o.message:String(o)}}};var j=async e=>{if(!e.agentId?.trim())return {ok:false,error:"session-end: agentId is required in ctx"};let r=e.extras?.windowDays??1;try{let t=await u$1("consolidate",{windowDays:r},u(e.agentId));return {ok:!0,logLine:`session-end: 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 z=async e=>{if(!e.agentId?.trim())return {ok:false,error:"pre-compact: agentId is required in ctx"};let t=(e.contextPreview??e.messagePreview??"").slice(0,200).replace(/\s+/g," ").trim(),o=e.extras?.topK??3;if(!t)return {ok:true,injected:"",logLine:"pre-compact: empty contextPreview; skipping recall injection"};try{let n=await u$1("recall",{query:t,maxResults:o,minImportance:5},u(e.agentId));if(n.hits.length===0)return {ok:!0,injected:"",logLine:`pre-compact: no facts matched query for agent=${e.agentId}`};let 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)]
3
+ `)}`,logLine:`session-start: injected ${o.hits.length} facts into context (agent=${e.agentId})`}}catch(o){return {ok:false,error:o instanceof Error?o.message:String(o)}}};var z=async e=>{if(!e.agentId?.trim())return {ok:false,error:"session-end: agentId is required in ctx"};let r=e.extras?.windowDays??1;try{let t=await v$1("consolidate",{windowDays:r},u(e.agentId));return {ok:!0,logLine:`session-end: 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 t=(e.contextPreview??e.messagePreview??"").slice(0,200).replace(/\s+/g," ").trim(),o=e.extras?.topK??3;if(!t)return {ok:true,injected:"",logLine:"pre-compact: empty contextPreview; skipping recall injection"};try{let n=await v$1("recall",{query:t,maxResults:o,minImportance:5},u(e.agentId));if(n.hits.length===0)return {ok:!0,injected:"",logLine:`pre-compact: no facts matched query for agent=${e.agentId}`};let 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 Y=async e=>{if(!e.agentId?.trim())return {ok:false,error:"post-tool-failure: agentId is required in ctx"};if(!e.toolName?.trim()||!e.error?.trim())return {ok:false,error:"post-tool-failure: toolName and error are required in ctx"};let r=createHash("sha256").update(`${e.toolName}:${e.error}`).digest("hex").slice(0,8),t=e.messagePreview?e.messagePreview.slice(0,200).replace(/\s+/g," ").trim():"",o=[`[error_pattern] tool=${e.toolName}`,`[error] ${e.error}`,t?`[preview] ${t}`:"",`[errHash] ${r}`].filter(Boolean).join(`
6
- `);try{return {ok:!0,logLine:`post-tool-failure: wrote error_pattern fact ${(await u$1("remember",{content:o,category:"error_pattern",importance:6,tags:["post-tool-failure",`tool:${e.toolName}`,`err:${r}`],sessionId:e.sessionId,msgId:e.extras?.msgId},u(e.agentId))).fact.id} (tool=${e.toolName}, errHash=${r})`}}catch(n){return {ok:false,error:n instanceof Error?n.message:String(n)}}};var g=Log.create({service:"memory.hooks"}),f=new Map;function y(e,r){let t={name:e,handler:r,registeredAt:new Date().toISOString()},o=f.get(e);f.set(e,t),o?g.info("Hook overwritten",{name:e,prevRegisteredAt:o.registeredAt,newRegisteredAt:t.registeredAt}):g.info("Hook registered",{name:e,registeredAt:t.registeredAt});}function Ee(e){return f.delete(e)}function be(){return Array.from(f.values()).map(e=>({name:e.name,handler:e.handler,registeredAt:e.registeredAt}))}function Ie(){y("session-start",$),y("session-end",j),y("pre-compact",z),y("post-tool-failure",Y);}function Me(){f.clear(),g.debug("All hooks cleared");}async function _e(e,r){let t=f.get(e);if(!t)return g.debug("dispatchHook: no handler registered; noop",{name:e}),{ok:true,logLine:`hook ${e} not registered; noop`};try{let o=await t.handler(r);return o.ok?o.logLine&&g.debug("dispatchHook: ok",{name:e,logLine:o.logLine}):g.warn("dispatchHook: handler returned failure",{name:e,agentId:r.agentId,error:o.error}),o}catch(o){let n=o instanceof Error?o.message:String(o);return g.warn("dispatchHook: handler threw, caught and converted to failure result",{name:e,agentId:r.agentId,error:n}),{ok:false,error:n}}}export{Oe as MEMORY_CATEGORIES,T as MemoryDatabaseError,L as MemoryEmbeddingError,d as MemoryError,me as MemoryErrorCode,v as MemoryFileError,N as MemoryNotFoundError,D as MemoryPermissionError,F as MemorySearchError,P as MemoryValidationError,Fe as addWord,Me as clearAllHooks,$e as closeTokenizer,_e as dispatchHook,ve as initTokenizer,Le as isInitialized,be as listHooks,Re as loadCustomDict,Ie as registerAllDefaultHooks,y as registerHook,je as toFtsTokens,ze as toFtsTokensForSearch,ke as tokenize,xe as tokenizeForSearch,Ee as unregisterHook};
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),t=e.messagePreview?e.messagePreview.slice(0,200).replace(/\s+/g," ").trim():"",o=[`[error_pattern] tool=${e.toolName}`,`[error] ${e.error}`,t?`[preview] ${t}`:"",`[errHash] ${r}`].filter(Boolean).join(`
6
+ `);try{return {ok:!0,logLine:`post-tool-failure: wrote error_pattern fact ${(await v$1("remember",{content:o,category:"error_pattern",importance:6,tags:["post-tool-failure",`tool:${e.toolName}`,`err:${r}`],sessionId:e.sessionId,msgId:e.extras?.msgId},u(e.agentId))).fact.id} (tool=${e.toolName}, errHash=${r})`}}catch(n){return {ok:false,error:n instanceof Error?n.message:String(n)}}};var g=Log.create({service:"memory.hooks"}),f=new Map;function y(e,r){let t={name:e,handler:r,registeredAt:new Date().toISOString()},o=f.get(e);f.set(e,t),o?g.info("Hook overwritten",{name:e,prevRegisteredAt:o.registeredAt,newRegisteredAt:t.registeredAt}):g.info("Hook registered",{name:e,registeredAt:t.registeredAt});}function be(e){return f.delete(e)}function Ie(){return Array.from(f.values()).map(e=>({name:e.name,handler:e.handler,registeredAt:e.registeredAt}))}function Me(){y("session-start",j),y("session-end",z),y("pre-compact",Y),y("post-tool-failure",G);}function _e(){f.clear(),g.debug("All hooks cleared");}async function Oe(e,r){let t=f.get(e);if(!t)return g.debug("dispatchHook: no handler registered; noop",{name:e}),{ok:true,logLine:`hook ${e} not registered; noop`};try{let o=await t.handler(r);return o.ok?o.logLine&&g.debug("dispatchHook: ok",{name:e,logLine:o.logLine}):g.warn("dispatchHook: handler returned failure",{name:e,agentId:r.agentId,error:o.error}),o}catch(o){let n=o instanceof Error?o.message:String(o);return g.warn("dispatchHook: handler threw, caught and converted to failure result",{name:e,agentId:r.agentId,error:n}),{ok:false,error:n}}}export{Se as MEMORY_CATEGORIES,v as MemoryDatabaseError,$ as MemoryEmbeddingError,d as MemoryError,ue as MemoryErrorCode,F as MemoryFileError,D as MemoryNotFoundError,T as MemoryPermissionError,L as MemorySearchError,N as MemoryValidationError,Le as addWord,_e as clearAllHooks,je as closeTokenizer,Oe as dispatchHook,Fe as initTokenizer,$e as isInitialized,Ie as listHooks,ke as loadCustomDict,Me as registerAllDefaultHooks,y as registerHook,ze as toFtsTokens,Ye as toFtsTokensForSearch,xe as tokenize,He as tokenizeForSearch,be as unregisterHook};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@easbot/memory",
3
- "version": "0.3.17",
3
+ "version": "0.3.20",
4
4
  "description": "Memory management library for EASBOT ecosystem - 智能记忆管理库,支持混合搜索、中英文分词、增量索引",
5
5
  "type": "module",
6
6
  "main": "dist/index.cjs",
@@ -54,13 +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.17",
58
- "@easbot/mcp": "0.3.17",
59
- "@easbot/terminal": "0.3.17",
60
- "@easbot/utils": "0.3.17",
61
- "@easbot/types": "0.3.17",
62
- "@easbot/local-model-sdk": "0.3.17",
63
- "@easbot/ollama-sdk": "0.3.17"
57
+ "@easbot/database": "0.3.20",
58
+ "@easbot/mcp": "0.3.20",
59
+ "@easbot/terminal": "0.3.20",
60
+ "@easbot/types": "0.3.20",
61
+ "@easbot/utils": "0.3.20",
62
+ "@easbot/local-model-sdk": "0.3.20",
63
+ "@easbot/ollama-sdk": "0.3.20",
64
+ "@easbot/llm": "0.3.20"
64
65
  },
65
66
  "devDependencies": {
66
67
  "@types/node": "^25.9.5",
@@ -1 +0,0 @@
1
- var f={languages:[{value:"zh-CN",name:"\u7B80\u4F53\u4E2D\u6587",example:"\u4F60\u597D\uFF0CEASBOT\uFF01",supported:true},{value:"en-US",name:"English (United States)",example:"Hello, EASBOT!",supported:true}]};var L=f.languages,C=L.filter(e=>e.supported).map(e=>e.value),a={defaultLocale:"zh-CN",locales:C},m={},p=(e,t)=>{let r=m[e]||{translation:{}};return m[e]={translation:{...r.translation,...t.translation}},m[e]},u=(e=a.defaultLocale)=>(m[e]||p(e,{translation:{}}),{locale:e,resources:m[e]||{translation:{}}});var S={translation:{"cli.cmd.init.description":"\u521D\u59CB\u5316\u8BB0\u5FC6 workspace\uFF08.easbot/memory.db\uFF09","cli.cmd.recall.description":"\u6DF7\u5408\u641C\u7D22\uFF08FTS + \u5411\u91CF\uFF09\u67E5\u8BE2\u8BB0\u5FC6","cli.cmd.remember.description":"\u5199\u5165\u4E00\u6761\u65B0\u8BB0\u5FC6\uFF08\u81EA\u5E26 dedup + \u77E5\u8BC6\u56FE\u8C31\u62BD\u53D6\uFF09","cli.cmd.forget.description":"\u5220\u9664\u8BB0\u5FC6\uFF08factId / category / \u65F6\u95F4\u7A97 / \u8BD5\u8FD0\u884C\uFF09","cli.cmd.extract.description":"\u4ECE session \u62BD\u53D6 facts\uFF08sessionId + lastN\uFF09","cli.cmd.consolidate.description":"\u8FD0\u884C consolidation \u6D41\u6C34\u7EBF\uFF08extract \u2192 dedup \u2192 archive\uFF09","cli.cmd.graph.description":"\u77E5\u8BC6\u56FE\u8C31\u67E5\u8BE2\uFF08nodes / edges / neighbors\uFF0Cscope \u4E09\u6863\uFF09","cli.cmd.status.description":"\u663E\u793A\u8BB0\u5FC6\u72B6\u6001 / \u6570\u636E\u5E93\u7EDF\u8BA1 / \u5404\u7C7B\u522B\u8BA1\u6570","cli.cmd.doctor.description":"\u8FD0\u884C\u5065\u5EB7\u68C0\u67E5\uFF08\u540E\u7AEF / FTS / schema / \u9501\uFF09","cli.cmd.config.description":"\u67E5\u770B / \u6821\u9A8C\u8BB0\u5FC6\u914D\u7F6E\uFF08dry-read\uFF09","cli.cmd.mcp.description":"\u542F\u52A8 stdio MCP \u670D\u52A1\u5668\uFF08\u66B4\u9732 9 \u4E2A memory \u5DE5\u5177\uFF09","memory.recall.empty":"\uFF08\u65E0\u5339\u914D\u8BB0\u5FC6\uFF09","memory.recall.summary":"\u5171\u5339\u914D {{total}} \u6761\u8BB0\u5FC6\uFF1A","memory.recall.item":" - {{id}} [{{category}}/\u91CD\u8981\u6027={{importance}}/\u5206\u6570={{score}}] {{content}}","memory.forget.empty":"\uFF08\u672A\u547D\u4E2D\u53EF\u5220\u9664\u7684\u8BB0\u5F55\uFF09\uFF09","memory.forget.summary":"\u5220\u9664 {{deletedCount}} \u6761\u8BB0\u5FC6\uFF08dryRun={{dryRun}}\uFF09\uFF1A","memory.forget.item":" - {{id}}","memory.remember.summary":"\u8BB0\u5FC6\u5DF2\u5199\u5165\uFF1A","memory.remember.item":" - id={{id}} \u7C7B\u522B={{category}} \u91CD\u8981\u6027={{importance}}","memory.consolidate.summary":"consolidation \u5B8C\u6210\uFF1A","memory.consolidate.item":" - \u603B\u8BA1 {{totalFacts}} \u53BB\u91CD {{dedupedCount}} \u5F52\u6863 {{archivedCount}}","memory.status.empty":"\uFF08\u6682\u65E0\u6570\u636E\uFF09","memory.status.summary":"\u8BB0\u5FC6\u72B6\u6001\uFF1A","memory.status.item":" - {{key}}: {{value}}","memory.doctor.empty":"\uFF08\u65E0\u68C0\u67E5\u9879\uFF09","memory.doctor.summary":"\u5065\u5EB7\u68C0\u67E5\uFF1A{{status}}","memory.doctor.item":" - {{name}}: {{message}}","memory.graph.empty":"\uFF08\u65E0\u8282\u70B9\u547D\u4E2D\uFF09","memory.graph.summary":"\u77E5\u8BC6\u56FE\u8C31\u67E5\u8BE2\uFF08\u5171 {{totalNodes}} \u8282\u70B9\uFF09\uFF1A","memory.graph.item":" - {{id}} {{name}} [{{type}}]","memory.extract.summary":"\u62BD\u53D6 {{extractedCount}} \u6761 facts\uFF1A","memory.extract.item":" - {{id}}","memory.init.summary":"\u521D\u59CB\u5316\u5B8C\u6210\uFF1A","memory.init.item":" - db={{dbPath}} \u8FC1\u79FB={{migrationsApplied}} \u8868={{tablesCreated}}"}},h=S;var v={translation:{"cli.cmd.init.description":"Initialize memory workspace (.easbot/memory.db)","cli.cmd.recall.description":"Hybrid search (FTS + vector) over memory facts","cli.cmd.remember.description":"Persist a new memory fact (with dedup + KG extraction)","cli.cmd.forget.description":"Delete memory facts (factId / category / timeRange / dryRun)","cli.cmd.extract.description":"Extract facts from a session (sessionId + lastN)","cli.cmd.consolidate.description":"Run consolidation pipeline (extract \u2192 dedup \u2192 archive)","cli.cmd.graph.description":"KG query (nodes / edges / neighbors with scope \u4E09\u6863)","cli.cmd.status.description":"Show memory state / db stats / facts by category","cli.cmd.doctor.description":"Run health checks (backend, FTS, schema, lock)","cli.cmd.config.description":"Show / validate memory configuration (dry-read)","cli.cmd.mcp.description":"Start stdio MCP server (exposes 9 memory tools)","memory.recall.empty":"(no matching facts)","memory.recall.summary":"Found {{total}} fact(s):","memory.recall.item":" - {{id}} [{{category}}/imp={{importance}}/score={{score}}] {{content}}","memory.forget.empty":"(no records to delete)","memory.forget.summary":"Deleted {{deletedCount}} fact(s) (dryRun={{dryRun}}):","memory.forget.item":" - {{id}}","memory.remember.summary":"Memory persisted:","memory.remember.item":" - id={{id}} category={{category}} importance={{importance}}","memory.consolidate.summary":"Consolidation complete:","memory.consolidate.item":" - total {{totalFacts}} deduped {{dedupedCount}} archived {{archivedCount}}","memory.status.empty":"(no data)","memory.status.summary":"Memory status:","memory.status.item":" - {{key}}: {{value}}","memory.doctor.empty":"(no checks)","memory.doctor.summary":"Health check: {{status}}","memory.doctor.item":" - {{name}}: {{message}}","memory.graph.empty":"(no nodes matched)","memory.graph.summary":"KG query ({{totalNodes}} node(s)):","memory.graph.item":" - {{id}} {{name}} [{{type}}]","memory.extract.summary":"Extracted {{extractedCount}} fact(s):","memory.extract.item":" - {{id}}","memory.init.summary":"Initialization complete:","memory.init.item":" - db={{dbPath}} migrations={{migrationsApplied}} tables={{tablesCreated}}"}},x=v;var w=()=>{u("zh-CN"),u("en-US"),p("zh-CN",h),p("en-US",x);};w();var g=new Map;var y=new Map;var k=e=>{if(y.has(e))return y.get(e);let t=/{{\s*(\w+)\s*}}/g,r=[],o;for(;(o=t.exec(e))!==null;){let n=o[1];n&&!r.includes(n)&&r.push(n);}let i=new RegExp("{{\\s*("+r.join("|")+")\\s*}}","g"),s={keys:r,regex:i};return y.set(e,s),s},R=(e,t)=>{if(!e||typeof e!="string")return "";if(!t||Object.keys(t).length===0)return e;let{regex:r,keys:o}=k(e);return o.length===0||!o.some(s=>s in t)?e:e.replace(r,(s,n)=>{let c=t[n];return c==null?"":String(c)})},I=e=>{if(e&&a.locales.includes(e))return e;let t=process.env.EASBOT_LANG?.trim()||process.env.LANG?.trim();if(t){let r=t.replace(/_/g,"-");if(a.locales.includes(r))return r;let o=r.split("-")[0];if(o==="zh")return "zh-CN";if(o==="en")return "en-US"}return a.defaultLocale},T=e=>{if(!g.has(e)){let{resources:t}=u(e);g.set(e,t);}return g.get(e)},N=(e,t={})=>{let r=I(t.locale),i=T(r)?.translation[e];if(i&&typeof i=="string"){let s=R(i,t.vars);return s!=null?String(s):String(e)}if(r!==a.defaultLocale){let n=T(a.defaultLocale)?.translation[e];if(n&&typeof n=="string"){let c=R(n,t.vars);return c!=null?String(c):String(e)}}return String(t.fallback??e)},B=N;export{B as a};
@@ -1,53 +0,0 @@
1
- import {a}from'./chunk-HQBRVVXS.mjs';import {Log,Filesystem}from'@easbot/utils';import {createSyncSqliteConnection}from'@easbot/database';var d=Log.create({service:"memory-schema-migrations"}),T=2,S=[{id:1,description:"v1 baseline: memory_facts / memory_vectors / embedding_cache / memory_facts_fts / nodes / edges / meta\uFF08\u4E0E v0.3.x createTables \u8F93\u51FA\u5BF9\u9F50\uFF0C\u8001 db \u8DD1\u8BE5\u8FC1\u79FB\u4E0D\u7834\u574F\u73B0\u6709\u8868\uFF09",up:[`CREATE TABLE IF NOT EXISTS memory_facts (
2
- id TEXT PRIMARY KEY,
3
- agent_id TEXT NOT NULL,
4
- session_id TEXT,
5
- msg_id TEXT,
6
- parent_msg_id TEXT,
7
- content TEXT NOT NULL,
8
- category TEXT NOT NULL,
9
- importance INTEGER NOT NULL CHECK(importance >= 1 AND importance <= 10),
10
- source TEXT NOT NULL CHECK(source IN ('session_self_write', 'historical')),
11
- tags TEXT,
12
- node_ids TEXT,
13
- file_path TEXT,
14
- created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
15
- updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
16
- UNIQUE(session_id, msg_id)
17
- )`,"CREATE INDEX IF NOT EXISTS idx_memory_facts_agent_id ON memory_facts(agent_id)","CREATE INDEX IF NOT EXISTS idx_memory_facts_agent_category ON memory_facts(agent_id, category)","CREATE INDEX IF NOT EXISTS idx_memory_facts_agent_importance ON memory_facts(agent_id, importance DESC)","CREATE INDEX IF NOT EXISTS idx_memory_facts_created_at ON memory_facts(created_at)",`CREATE TABLE IF NOT EXISTS memory_vectors (
18
- fact_id TEXT PRIMARY KEY,
19
- embedding BLOB NOT NULL,
20
- FOREIGN KEY (fact_id) REFERENCES memory_facts(id) ON DELETE CASCADE
21
- )`,`CREATE TABLE IF NOT EXISTS embedding_cache (
22
- content_hash TEXT PRIMARY KEY,
23
- embedding BLOB NOT NULL,
24
- created_at DATETIME DEFAULT CURRENT_TIMESTAMP
25
- )`,`CREATE VIRTUAL TABLE IF NOT EXISTS memory_facts_fts USING fts5(
26
- fact_id UNINDEXED,
27
- agent_id UNINDEXED,
28
- content,
29
- tags,
30
- tokenize='porter unicode61'
31
- )`,`CREATE TABLE IF NOT EXISTS nodes (
32
- id INTEGER PRIMARY KEY AUTOINCREMENT,
33
- name TEXT NOT NULL,
34
- type TEXT NOT NULL,
35
- properties TEXT,
36
- createdAt DATETIME DEFAULT CURRENT_TIMESTAMP,
37
- updatedAt DATETIME DEFAULT CURRENT_TIMESTAMP
38
- )`,"CREATE INDEX IF NOT EXISTS idx_nodes_name ON nodes(name)","CREATE INDEX IF NOT EXISTS idx_nodes_type ON nodes(type)","CREATE UNIQUE INDEX IF NOT EXISTS idx_nodes_name_type ON nodes(name, type)",`CREATE TABLE IF NOT EXISTS edges (
39
- id INTEGER PRIMARY KEY AUTOINCREMENT,
40
- source INTEGER NOT NULL,
41
- target INTEGER NOT NULL,
42
- relation TEXT NOT NULL,
43
- properties TEXT,
44
- createdAt DATETIME DEFAULT CURRENT_TIMESTAMP,
45
- FOREIGN KEY (source) REFERENCES nodes(id) ON DELETE CASCADE,
46
- FOREIGN KEY (target) REFERENCES nodes(id) ON DELETE CASCADE
47
- )`,"CREATE INDEX IF NOT EXISTS idx_edges_source ON edges(source)","CREATE INDEX IF NOT EXISTS idx_edges_target ON edges(target)","CREATE INDEX IF NOT EXISTS idx_edges_relation ON edges(relation)","CREATE UNIQUE INDEX IF NOT EXISTS idx_edges_unique ON edges(source, target, relation)",`CREATE TABLE IF NOT EXISTS meta (
48
- key TEXT PRIMARY KEY,
49
- value TEXT
50
- )`]},{id:2,description:"v2: \u7ED9 nodes \u8868\u52A0 owner_agent_id \u5217 + \u7D22\u5F15\uFF08ADR 0056 KG scope \u4E09\u6863\uFF0Cper-agent \u9694\u79BB\uFF09",up:["ALTER TABLE nodes ADD COLUMN owner_agent_id TEXT","CREATE INDEX IF NOT EXISTS idx_nodes_owner_agent_id ON nodes(owner_agent_id)"]}];function m(n,e=T,r={}){n.exec(`CREATE TABLE IF NOT EXISTS schema_migrations (
51
- id INTEGER PRIMARY KEY,
52
- applied_at DATETIME DEFAULT CURRENT_TIMESTAMP
53
- )`);let i=n.prepare("SELECT id FROM schema_migrations").all(),a=new Set(i.map(t=>t.id)),s={applied:[],pending:[],errors:[],currentVersion:i.length===0?0:Math.max(...i.map(t=>t.id)),targetVersion:e};for(let t of S){if(t.id>e)break;if(a.has(t.id)){s.pending.push(t.id);continue}if(r.dryRun){s.applied.push(t.id);continue}try{_(n,t.up),n.prepare("INSERT INTO schema_migrations (id) VALUES (?)").run(t.id),a.add(t.id),s.applied.push(t.id),d.info("migration applied",{id:t.id,description:t.description});}catch(E){let l=E instanceof Error?E.message:String(E),h=t.up[0]??"";s.errors.push({migrationId:t.id,sql:h,error:l}),d.warn("migration step failed",{id:t.id,error:l,sqlCount:t.up.length});}}return s}function _(n,e){for(let r of e)try{n.exec(r);}catch(i){let a=i instanceof Error?i.message:String(i);if(R(a)){d.debug("migration: column already exists, skipping",{sql:r.slice(0,80)});continue}throw i}}function R(n){return /duplicate column name/i.test(n)}function g(n){try{let e=n.prepare("SELECT id FROM schema_migrations").all();return e.length===0?0:Math.max(...e.map(r=>r.id))}catch{return 0}}var c=Log.create({service:"memory-database"}),p=class{constructor(e){a(this,"db",null);a(this,"storagePath");a(this,"backend","better-sqlite3");a(this,"initialized",false);a(this,"initPromise",null);this.storagePath=e===":memory:"?e:Filesystem.normalize(e);}async initialize(){if(!this.initialized){if(this.initPromise){await this.initPromise;return}this.initPromise=this.doInitialize();try{await this.initPromise,this.initialized=!0;}catch(e){try{this.db&&this.db.close();}catch{}throw this.db=null,this.initPromise=null,e}}}async doInitialize(){try{let e=this.openConnection();e.initialize(),this.db=e,this.applyPragmas(),this.runAllMigrations();}catch(e){let r=e instanceof Error?e.message:String(e);throw c.error("Database initialization failed",{error:r}),e}}openConnection(){return createSyncSqliteConnection({path:this.storagePath,backend:this.backend,walMode:true,foreignKeys:true,busyTimeoutMs:5e3})}applyPragmas(){if(this.db)try{this.db.pragma("synchronous = NORMAL"),this.db.pragma("cache_size = -64000"),this.db.pragma("temp_store = MEMORY"),this.db.pragma("foreign_keys = ON");}catch(e){c.warn("Failed to apply memory PRAGMAs",{error:String(e)});}}runAllMigrations(){if(!this.db)throw new Error("Database not initialized");let e=m(this.db,T);if(e.errors.length>0){let r=e.errors.map(i=>`migration ${i.migrationId}: ${i.error}`).join("; ");throw new Error(`Some migrations failed: ${r}`)}}query(e,r){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");try{let i=this.db.prepare(e);return r?i.all(...r):i.all()}catch(i){throw new Error(`Query failed: ${i.message}`)}}agentFilter(e){return typeof e=="string"&&e.trim().length>0?{where:"WHERE agent_id = ?",params:[e.trim()]}:{where:"",params:[]}}run(e,r){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");try{let i=this.db.prepare(e),a=r?i.run(...r):i.run();return {lastID:Number(a.lastInsertRowid),changes:a.changes}}catch(i){throw new Error(`Write failed: ${i.message}`)}}transaction(e){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");return this.db.transaction(e)()}prepare(e){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");return this.db.prepare(e)}exec(e){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");this.db.exec(e);}getDb(){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");return this.db}getPath(){return this.storagePath}getSchemaVersion(){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");return g(this.db)}close(){if(this.db){try{this.db.close();}catch(e){c.warn("Failed to close memory database",{error:String(e)});}this.db=null,this.initialized=false,this.initPromise=null;}}healthCheck(){try{return this.db?(this.db.exec("SELECT 1"),!0):!1}catch{return false}}getMeta(e){if(!this.db)throw new Error("Database not initialized");return this.db.prepare("SELECT value FROM meta WHERE key = ?").get(e)?.value??null}setMeta(e,r){if(!this.db)throw new Error("Database not initialized");this.db.prepare("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)").run(e,r);}};export{T as a,S as b,m as c,g as d,p as e};
@@ -1,42 +0,0 @@
1
- 'use strict';var chunkOIUUTVLL_cjs=require('./chunk-OIUUTVLL.cjs'),chunkCPRDIUQ4_cjs=require('./chunk-CPRDIUQ4.cjs'),chunkNVGACA7W_cjs=require('./chunk-NVGACA7W.cjs'),utils=require('@easbot/utils'),ai=require('ai'),zod=require('zod'),crypto=require('crypto'),types=require('@easbot/types'),P=require('fs/promises'),W=require('path'),fs=require('fs');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var P__default=/*#__PURE__*/_interopDefault(P);var W__default=/*#__PURE__*/_interopDefault(W);var G=utils.Log.create({service:"memory.graph-store"}),v=class{constructor(e){chunkNVGACA7W_cjs.a(this,"db");this.db=e;}async upsertNode(e,r,n,i){let c=Date.now(),o=JSON.stringify(n??{}),s=this.db.prepare("SELECT id FROM nodes WHERE name = ? AND type = ? LIMIT 1").get(e,r);if(s)return this.db.prepare("UPDATE nodes SET properties = ?, updatedAt = ? WHERE id = ?").run(o,c,s.id),s.id;let l=this.db.prepare("INSERT INTO nodes (name, type, properties, owner_agent_id, createdAt, updatedAt) VALUES (?, ?, ?, ?, ?, ?)").run(e,r,o,i??null,c,c);return Number(l.lastInsertRowid)}async deleteNode(e){this.db.prepare("DELETE FROM nodes WHERE id = ?").run(e);}async upsertEdge(e,r,n,i){let c=this.db.prepare("INSERT OR REPLACE INTO edges (source, target, relation, properties, createdAt) VALUES (?, ?, ?, ?, ?)").run(e,r,n,JSON.stringify(i??{}),Date.now());return Number(c.lastInsertRowid)}async queryNodes(e={}){let r="SELECT id, name, type, properties, owner_agent_id, createdAt, updatedAt FROM nodes",n=[],i=[];if(e.ids&&e.ids.length>0){let o=e.ids.map(s=>typeof s=="string"?parseInt(s,10):s).filter(s=>!Number.isNaN(s));i.push(`id IN (${o.map(()=>"?").join(", ")})`),n.push(...o);}e.name&&(i.push("name LIKE ?"),n.push(`%${e.name}%`)),e.type&&(i.push("type = ?"),n.push(e.type)),Je(i,n,e.agentId,e.scope??"agent_only"),i.length>0&&(r+=` WHERE ${i.join(" AND ")}`),r+=" ORDER BY id",e.limit&&(r+=" LIMIT ?",n.push(e.limit)),G.debug("queryNodes",{sql:r,params:n,filter:e});let c=this.db.prepare(r).all(...n);return G.debug("queryNodes result",{count:c.length}),c.map(o=>({id:o.id,name:o.name,type:o.type,properties:o.properties?JSON.parse(o.properties):void 0,createdAt:o.createdAt,updatedAt:o.updatedAt,ownerAgentId:o.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=[],i=[];if(e.ids&&e.ids.length>0&&(i.push(`e.id IN (${e.ids.map(()=>"?").join(", ")})`),n.push(...e.ids)),e.source!==void 0&&(i.push("e.source = ?"),n.push(e.source)),e.target!==void 0&&(i.push("e.target = ?"),n.push(e.target)),e.sourceOrTarget&&e.sourceOrTarget.length>0){let u=e.sourceOrTarget.map(d=>typeof d=="string"?parseInt(d,10):d).filter(d=>!Number.isNaN(d));i.push(`(e.source IN (${u.map(()=>"?").join(", ")}) OR e.target IN (${u.map(()=>"?").join(", ")}))`),n.push(...u,...u);}e.relation&&(i.push("e.relation = ?"),n.push(e.relation)),i.length>0&&(r+=` WHERE ${i.join(" AND ")}`),r+=" ORDER BY e.id",e.limit&&(r+=" LIMIT ?",n.push(e.limit)),G.debug("queryEdges",{sql:r,params:n,filter:e});let c=this.db.prepare(r).all(...n);G.debug("queryEdges result",{count:c.length});let o=[...new Set(c.map(u=>u.target))],s=o.length>0?await this.queryNodes({ids:o,limit:o.length}):[],l=new Map(s.map(u=>[u.id,u]));return c.map(u=>{let d={id:u.id,source:u.source,target:u.target,relation:u.relation,properties:u.properties?JSON.parse(u.properties):void 0,createdAt:u.createdAt},E=l.get(u.target);return E&&(d.targetNode=E),d})}async queryNeighbors(e,r=1,n){let i=n?.agentId,c=n?.scope??"agent_only",o=new Set,s=[{id:e,level:0}],l=[],u=n?.maxEdgesPerNode??50;for(;s.length>0;){let d=s.shift();if(!d)break;if(o.has(d.id)||d.level>r)continue;o.add(d.id);let R=(await this.queryNodes({ids:[d.id],limit:1,agentId:i,scope:c}))[0];if(!R)continue;let I=await this.queryEdges({sourceOrTarget:[d.id],limit:u}),f=i?await Ke(this,I,i,c):I;if(l.push({...R,edges:f}),d.level<r)for(let h of f){let g=h.source===d.id?h.target:h.source;o.has(g)||s.push({id:g,level:d.level+1});}}return l}};async function Ke(t,e,r,n){if(e.length===0)return e;let i=new Set;for(let s of e)i.add(s.source),i.add(s.target);let c=await t.queryNodes({ids:Array.from(i),agentId:r,scope:n,limit:i.size}),o=new Set(c.map(s=>s.id));return e.filter(s=>o.has(s.source)&&o.has(s.target))}function Je(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}}exports.b=void 0;(I=>{let t=utils.Log.create({service:"memory-llm"}),e=null;function r(f){n()||(e={models:f.models,options:f.options??{}},t.debug("Llm initialized",{embeddingConfigured:!!f.models.embeddingLlm,graphConfigured:!!f.models.graphLlm}));}I.init=r;function n(){return e!==null}I.isInitialized=n;function i(){e=null;}I.reset=i;function c(){return e?{embedding:!!e.models.embeddingLlm,graph:!!e.models.graphLlm}:{embedding:false,graph:false}}I.capabilities=c;async function o(f){let g=d().models.embeddingLlm;if(!g)throw new Error("embeddingLlm model is not configured.");try{let m=await ai.embed({model:g,value:f});return new Float32Array(m.embedding)}catch(m){let p=g.doEmbed;if(typeof p!="function")throw new Error("embeddingLlm model does not support embedding generation.",{cause:m});let S=(await p({values:[f]}))?.embeddings?.[0];if(!S||!Array.isArray(S))throw new Error("embeddingLlm model returned invalid embedding result.",{cause:m});return new Float32Array(S)}}I.embedText=o;async function s(f){let g=d().models.embeddingLlm;if(!g)throw new Error("embeddingLlm model is not configured.");try{return (await ai.embedMany({model:g,values:f})).embeddings.map(p=>new Float32Array(p))}catch{return ((await g.doEmbed?.({values:f}))?.embeddings??[]).map(p=>new Float32Array(p))}}I.embedTexts=s;async function l(f,h,g,m={}){if(!d().models.graphLlm)return t.debug("generateGraph skipped: graphLlm not configured"),"";let{maxContentLength:b,maxChunks:S,includeSummary:M,...y}=m,T=utils.buildEntityExtractionPrompt(f,h,g,{maxContentLength:b,maxChunks:S,includeSummary:M});return u(T,y)}I.generateGraph=l;async function u(f,h){let g=d(),m=g.models.graphLlm;if(!m)throw new Error("llm model is not configured.");try{return (await ai.streamText({model:m,prompt:f,maxOutputTokens:h?.maxOutputTokens??g.options.graph?.maxOutputTokens,temperature:h?.temperature??g.options.graph?.temperature})).text}catch{return (await m.doGenerate?.({prompt:[{role:"user",content:[{type:"text",text:f}]}],maxOutputTokens:h?.maxOutputTokens??g.options.graph?.maxOutputTokens}))?.content?.find(b=>b.type==="text")?.text??""}}I.generate=u;let d=()=>{if(!e)throw new Error("Llm is not initialized. Please call Llm.init() first.");return e};I.embed=o,I.embedMany=s;})(exports.b||(exports.b={}));var w=class extends Error{constructor(r,n,i){super(r);chunkNVGACA7W_cjs.a(this,"code",n);chunkNVGACA7W_cjs.a(this,"details",i);this.name="ServiceError";}};var Q=class extends w{constructor(){super("ctx.agentId is required for memory service (ADR 0055 per-agent isolation)","AGENT_ID_REQUIRED");}},k=class extends w{constructor(e,r){super(`Trust denied for operation "${e}": ${r}`,"TRUST_DENIED",{operation:e,reason:r});}},F=class extends w{constructor(e,r){super(`Memory ${e} has ${r} references (force=false)`,"HAS_REFERENCES",{memoryId:e,referenceCount:r});}},H=class extends w{constructor(e){super(`dryRun mode: ${e} memories matched but not deleted`,"DRY_RUN_NO_DELETE",{matchedCount:e});}},q=class extends w{constructor(e,r){super(`Matched ${e} memories exceeds maxDelete=${r}`,"MAX_DELETE_EXCEEDED",{matched:e,maxDelete:r});}};function D(t){if(typeof t.agentId!="string"||t.agentId.trim().length===0)throw new Q}function x(t,e){if(t.remote!==false)throw new k(e,"requires trusted local caller (CLI / agent tool / MCP with remote=false)")}function z(t,e,r){if(e!=="agent_only"&&t.remote!==false)throw new k(r,`scope="${e}" requires trusted local caller (cross-agent access denied)`)}function B(t){if(!t.dbPath||t.dbPath.trim().length===0)throw new w("service ctx.dbPath is required (MemoryKnowledgeConfigWithModels.database.path)","INTERNAL")}var $=utils.Log.create({service:"memory.service.recall"});async function Ee(t,e){let r=Date.now();if(D(t),B(t),!e.query||e.query.trim().length===0)throw new w("recall requires non-empty `query`","CONTENT_REQUIRED");let n=e.includeShared?"both":"agent_only";e.includeGraph&&z(t,n,"recall"),$.debug("recall invoked",{agentId:t.agentId,query:e.query,category:e.category,maxResults:e.maxResults,includeGraph:e.includeGraph,scope:n});let i=e.maxResults??10,c=e.minScore??0,o=[],s=new chunkOIUUTVLL_cjs.e(t.dbPath);try{await s.initialize();let l=exports.b.isInitialized()&&exports.b.capabilities().embedding,u=await rt(s,t.agentId,e.query,{category:e.category,minImportance:e.minImportance,fromTime:e.fromTime,toTime:e.toTime,limit:i,minScore:c,hasEmbedding:l}),d;if(e.includeGraph&&u.length>0)try{let R=new v(s.getDb()),I=e.depth??1,f=u.flatMap(b=>(b.nodes??[]).map(S=>S.id)).slice(0,5),h=new Set,g=new Map;for(let b of f){let S=await R.queryNeighbors(b,I,{agentId:t.agentId,scope:n,maxEdgesPerNode:10});for(let M of S)h.add(M.id),g.set(M.id,M.edges??[]);}let m=h.size>0?s.query(`SELECT id, name, type FROM nodes WHERE id IN (${Array.from(h).map(()=>"?").join(",")})`,Array.from(h)):[],p=Array.from(g.values()).flat();d={nodes:m.map(b=>({id:b.id,name:b.name,type:b.type,createdAt:"",updatedAt:""})),edges:p};}catch(R){let I=R instanceof Error?R.message:String(R);$.warn("recall: KG neighbor query failed",{error:I}),o.push(`kg_neighbor_query_failed: ${I}`),d={nodes:[],edges:[]};}let E=Date.now()-r;return {hits:u,total:u.length,truncated:u.length>=i,durationMs:E,graph:d,...o.length>0?{warnings:o}:{}}}catch(l){throw l instanceof w?l:new w(`recall failed: ${l instanceof Error?l.message:String(l)}`,"INTERNAL",{cause:l instanceof Error?l.message:String(l)})}finally{s.close();}}async function rt(t,e,r,n){let i=["mf.agent_id = ?"],c=[e];n.category&&(i.push("mf.category = ?"),c.push(n.category)),n.minImportance!==void 0&&(i.push("mf.importance >= ?"),c.push(n.minImportance)),n.fromTime&&(i.push("mf.created_at >= ?"),c.push(n.fromTime)),n.toTime&&(i.push("mf.created_at <= ?"),c.push(n.toTime));let o=i.join(" AND "),s=null;if(n.hasEmbedding)try{s=await exports.b.embedText(r);}catch(y){$.warn("recall: query embedding failed, falling back to FTS-only",{error:y instanceof Error?y.message:String(y)}),s=null;}let l=Math.max(n.limit*100,1e3),[u,d]=await Promise.all([s?nt(t,s,o,c,l):Promise.resolve([]),ot(t,r,o,c,n.limit)]),E=s?.7:0,R=s?.3:1,I=E+R,f=E/I,h=R/I,g=new Map;for(let y of u)g.set(y.id,y.score*f);for(let y of d)g.set(y.id,(g.get(y.id)??0)+y.score*h);let m=Array.from(g.entries()).sort((y,T)=>T[1]-y[1]).map(([y])=>y).slice(0,n.limit);if(m.length===0)return [];let p=m.map(()=>"?").join(","),b=t.query(`SELECT
2
- mf.id,
3
- mf.category,
4
- mf.importance,
5
- mf.agent_id as agentId,
6
- SUBSTR(mf.content, 1, 200) as snippet,
7
- mf.created_at as createdAt,
8
- mf.source,
9
- mf.file_path as filePath,
10
- mf.node_ids as nodeIds
11
- FROM memory_facts mf
12
- WHERE mf.id IN (${p})`,m),S=Date.now();return b.map(y=>{let T=g.get(y.id)??0,je=(S-new Date(y.createdAt).getTime())/864e5,Ge=Math.exp(-0.05*je),Qe=(y.importance-1)/9,ze=.4*T+.3*Ge+.3*Qe;return {memoryId:y.id,category:y.category,importance:y.importance,agentId:y.agentId,snippet:y.snippet,score:ze,createdAt:y.createdAt,source:y.source,filePath:y.filePath??void 0,nodes:void 0}}).filter(y=>y.score>=n.minScore).sort((y,T)=>T.score-y.score)}function nt(t,e,r,n,i){try{return t.query(`SELECT mf.id, mv.embedding
13
- FROM memory_facts mf
14
- JOIN memory_vectors mv ON mf.id = mv.fact_id
15
- WHERE ${r}
16
- LIMIT ?`,[...n,i]).map(o=>{let s=new Float32Array(o.embedding.buffer,o.embedding.byteOffset,o.embedding.byteLength/4);return {id:o.id,score:at(e,s)}}).sort((o,s)=>s.score-o.score)}catch(c){if(c instanceof w)throw c;return $.warn("vector search failed, falling back to FTS-only",{error:c instanceof Error?c.message:String(c)}),[]}}function ot(t,e,r,n,i){try{let c=t.query(`SELECT mf.id as id, bm25(memory_facts_fts) as score
17
- FROM memory_facts_fts fts
18
- JOIN memory_facts mf ON mf.id = fts.fact_id
19
- WHERE ${r} AND memory_facts_fts MATCH ?
20
- ORDER BY score DESC
21
- LIMIT ?`,[...n,st(e),i]);if(c.length===0)return [];let o=Math.max(...c.map(s=>Math.abs(s.score)),1);return c.map(s=>({id:s.id,score:1-Math.abs(s.score)/o})).filter(s=>s.score>=0)}catch(c){if(c instanceof w)throw c;return $.warn("FTS search failed, returning empty result",{err:c instanceof Error?c.message:String(c)}),[]}}function at(t,e){if(t.length!==e.length||t.length===0)return 0;let r=0,n=0,i=0;for(let o=0;o<t.length;o++){let s=t[o]??0,l=e[o]??0;r+=s*l,n+=s*s,i+=l*l;}let c=Math.sqrt(n)*Math.sqrt(i);return c===0?0:Math.max(0,r/c)}function st(t){return t.trim().split(/\s+/).filter(e=>e.length>0).map(e=>`"${e.replace(/"/g,'""')}"`).join(" ")}var we=zod.z.object({query:zod.z.string().min(1).max(500),category:zod.z.string().optional(),minImportance:zod.z.number().min(1).max(10).optional(),fromTime:zod.z.string().datetime().optional(),toTime:zod.z.string().datetime().optional(),maxResults:zod.z.number().int().min(1).max(100).optional().default(10),minScore:zod.z.number().min(0).max(1).optional(),includeGraph:zod.z.boolean().optional().default(false),depth:zod.z.number().int().min(1).max(5).optional().default(1),includeShared:zod.z.boolean().optional().default(false)});zod.z.object({hits:zod.z.array(zod.z.unknown()),total:zod.z.number(),truncated:zod.z.boolean(),durationMs:zod.z.number(),graph:zod.z.object({nodes:zod.z.array(zod.z.unknown()),edges:zod.z.array(zod.z.unknown())}).optional()});var Re=zod.z.object({content:zod.z.string().min(1).max(1e4),category:zod.z.string().min(1),importance:zod.z.number().int().min(1).max(10).optional().default(5),tags:zod.z.array(zod.z.string()).optional(),sessionId:zod.z.string().optional(),msgId:zod.z.string().optional(),parentMsgId:zod.z.string().optional(),skipDedup:zod.z.boolean().optional().default(false),extractGraph:zod.z.boolean().optional().default(true)});zod.z.object({fact:zod.z.object({id:zod.z.string(),agentId:zod.z.string(),content:zod.z.string(),category:zod.z.string(),importance:zod.z.number(),createdAt:zod.z.string(),updatedAt:zod.z.string()}),filePath:zod.z.string(),deduplicated:zod.z.boolean(),nodeIds:zod.z.array(zod.z.number()).optional()});var Se=zod.z.object({factId:zod.z.string().optional(),category:zod.z.string().optional(),fromTime:zod.z.string().datetime().optional(),toTime:zod.z.string().datetime().optional(),maxDelete:zod.z.number().int().min(1).max(1e4).optional().default(1e3),dryRun:zod.z.boolean().optional().default(false),force:zod.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"});zod.z.object({deletedCount:zod.z.number(),deletedIds:zod.z.array(zod.z.string()),dryRun:zod.z.boolean(),truncatedCount:zod.z.number()});var Ie=zod.z.object({sessionId:zod.z.string().min(1),lastN:zod.z.number().int().min(1).max(500).optional().default(50),fromMessageId:zod.z.string().optional(),writeToDisk:zod.z.boolean().optional().default(true)});zod.z.object({extractedCount:zod.z.number(),factIds:zod.z.array(zod.z.string()),entities:zod.z.array(zod.z.object({id:zod.z.number(),name:zod.z.string(),type:zod.z.string()})),relations:zod.z.array(zod.z.object({source:zod.z.string(),target:zod.z.string(),relation:zod.z.string()})),messageRange:zod.z.object({fromMessageId:zod.z.string(),toMessageId:zod.z.string()}),durationMs:zod.z.number()});var Me=zod.z.object({windowDays:zod.z.number().int().min(1).max(365).optional().default(30),dryRun:zod.z.boolean().optional().default(false)});zod.z.object({totalFacts:zod.z.number(),dedupedCount:zod.z.number(),compressedCount:zod.z.number(),archivedCount:zod.z.number(),skippedCount:zod.z.number(),durationMs:zod.z.number()});var _e=zod.z.object({query:zod.z.string().min(1),type:zod.z.string().optional(),depth:zod.z.number().int().min(1).max(5).optional().default(2),maxNodes:zod.z.number().int().min(1).max(500).optional().default(100),scope:zod.z.enum(["agent_only","shared_only","both"]).optional().default("agent_only"),relation:zod.z.string().optional()});zod.z.object({root:zod.z.unknown().nullable(),nodes:zod.z.array(zod.z.unknown()),edges:zod.z.array(zod.z.unknown()),truncated:zod.z.boolean(),totalNodes:zod.z.number(),totalEdges:zod.z.number(),scope:zod.z.enum(["agent_only","shared_only","both"]),durationMs:zod.z.number()});var Oe=zod.z.object({}).optional();zod.z.object({dbPath:zod.z.string(),workspaceDir:zod.z.string(),factsCount:zod.z.number(),nodesCount:zod.z.number(),edgesCount:zod.z.number(),factsByCategory:zod.z.record(zod.z.string(),zod.z.number()),ftsAvailable:zod.z.boolean(),vectorEnabled:zod.z.boolean(),kgScopeEnabled:zod.z.boolean(),healthy:zod.z.boolean(),meta:zod.z.record(zod.z.string(),zod.z.string())});var Te=zod.z.object({}).optional();zod.z.object({healthy:zod.z.boolean(),checks:zod.z.array(zod.z.object({name:zod.z.string(),passed:zod.z.boolean(),message:zod.z.string(),details:zod.z.record(zod.z.string(),zod.z.unknown()).optional()}))});var Ce=zod.z.object({workspaceDir:zod.z.string().optional(),dbPath:zod.z.string().optional(),archiveDays:zod.z.number().int().min(1).max(3650).optional().default(30),force:zod.z.boolean().optional().default(false)});zod.z.object({initialized:zod.z.boolean(),dbPath:zod.z.string(),workspaceDir:zod.z.string(),tablesCreated:zod.z.number(),migrationsApplied:zod.z.number(),durationMs:zod.z.number()});var U=utils.Log.create({service:"memory.fact-file-sync"}),dt=".easbot/memory/active";function X(t,e){let r=e.replace(/\\/g,"/").replace(/\/+$/,""),n=t.category||"uncategorized",i=t.createdAt?new Date(t.createdAt).getTime():Date.now(),c=Number.isNaN(i)?new Date:new Date(i),o=c.getFullYear(),s=String(c.getMonth()+1).padStart(2,"0"),l=String(c.getDate()).padStart(2,"0"),u=`${o}-${s}-${l}`;return `${r}/${dt}/${n}/${u}.md`}function De(t){let e=t.tags&&t.tags.length>0?t.tags:[],r=t.importance??5,n=t.source??"session_self_write",i=t.createdAt?utils.formatLocalISO(new Date(t.createdAt)):utils.formatLocalISO(new Date),c=t.updatedAt?utils.formatLocalISO(new Date(t.updatedAt)):i,o=["---",`id: ${t.id}`,`agent_id: ${t.agentId}`,`category: ${t.category}`,`importance: ${r}`,`created_at: ${i}`,`updated_at: ${c}`,`source: ${n}`,e.length>0?`tags: [${e.join(", ")}]`:"tags: []"];return t.sessionId&&o.push(`session_id: ${t.sessionId}`),t.msgId&&o.push(`msg_id: ${t.msgId}`),t.parentMsgId&&o.push(`parent_msg_id: ${t.parentMsgId}`),t.nodeIds&&t.nodeIds.length>0&&o.push(`node_ids: [${t.nodeIds.join(", ")}]`),o.push("---"),`${o.join(`
22
- `)}
23
- ${t.content.trim()}`}function Z(t,e){let r=t.replace(/\\/g,"/"),n=e.replace(/\\/g,"/").replace(/\/+$/,"");return r.startsWith(`${n}/`)?r.slice(n.length+1):r}async function mt(t,e){let r=X(t,e),n=Z(r,e);try{let i=De(t);await P__default.default.mkdir(W__default.default.dirname(r),{recursive:!0});let c="";try{c=await P__default.default.readFile(r,"utf-8");}catch(s){if(s.code!=="ENOENT")throw s}let o=c.length>0&&!c.endsWith(`
24
- `)?`
25
- `:"";return await P__default.default.writeFile(r,`${c}${o}${i}
26
- `,"utf-8"),U.debug("Fact file synced (append)",{id:t.id,relPath:n}),{ok:!0,absPath:r,relPath:n}}catch(i){let c=i instanceof Error?i.message:String(i);return U.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 lt(t,e){let r;t.filePath?r=`${e.replace(/\\/g,"/").replace(/\/+$/,"")}/${t.filePath.replace(/^\/+/,"")}`:r=X({id:t.id,category:t.category,createdAt:t.createdAt,updatedAt:t.createdAt},e);let n=Z(r,e);try{return await P__default.default.unlink(r),U.debug("Fact file deleted",{id:t.id,relPath:n}),{ok:!0,absPath:r,relPath:n}}catch(i){if(i.code==="ENOENT")return U.debug("Fact file not found (already deleted)",{id:t.id,relPath:n}),{ok:true,absPath:r,relPath:n};let o=i instanceof Error?i.message:String(i);return U.warn("Failed to delete fact file (best-effort, non-blocking)",{id:t.id,absPath:r,error:o}),{ok:false,absPath:r,relPath:n,error:o}}}var J={resolvePath:X,renderMarkdown:De,toRelPath:Z,write:mt,delete:lt};var N=utils.Log.create({service:"memory.service.remember"});async function Ae(t,e){if(D(t),B(t),!e.content||e.content.trim().length===0)throw new w("remember requires non-empty `content`","CONTENT_REQUIRED");if(!e.category)throw new w("remember requires `category`","CATEGORY_REQUIRED");N.debug("remember invoked",{agentId:t.agentId,category:e.category,importance:e.importance??5,contentLength:e.content.length,skipDedup:e.skipDedup,extractGraph:e.extractGraph??true});let r=new chunkOIUUTVLL_cjs.e(t.dbPath);try{await r.initialize();let n=new Date().toISOString(),i=ht(),c=e.importance??5,o=e.extractGraph!==!1?utils.extractEntitiesByRules(e.content):{entities:[],relations:[]},s=o.entities,l=o.relations;if(e.extractGraph!==!1&&exports.b.isInitialized()&&exports.b.capabilities().graph){let m=t.dbPath,p=t.agentId;exports.b.generateGraph([e.content],types.GRAPH_ENTITY_TYPE_DEFINITIONS,types.GRAPH_RELATION_TYPE_DEFINITIONS).then(b=>{try{let S=utils.parseEntityExtractionResult(b,types.GRAPH_ENTITY_TYPE_DEFINITIONS,types.GRAPH_RELATION_TYPE_DEFINITIONS),M=new chunkOIUUTVLL_cjs.e(m);M.initialize().then(()=>{try{wt(M,p,S.entities,S.relations);}finally{M.close();}}).catch(y=>{N.debug("background LLM extraction db init failed",{agentId:p,error:String(y)});});}catch(S){N.debug("background LLM extraction parse failed",{agentId:p,error:String(S)});}}).catch(b=>{N.warn("background LLM extraction failed",{agentId:p,error:String(b)});});}let u=exports.b.isInitialized()&&exports.b.capabilities().embedding,d=u?await Et(r.getDb(),e.content):null,E=d?d.length:null,R=[],I=0;r.transaction(()=>{let m=new Map;for(let p of s){let b=r.query("SELECT id FROM nodes WHERE name = ? AND type = ? LIMIT 1",[p.name,p.type])[0];if(b){m.set(p.name,b.id);continue}let S=r.run("INSERT INTO nodes (name, type, properties, owner_agent_id, createdAt, updatedAt) VALUES (?, ?, ?, ?, ?, ?)",[p.name,p.type,JSON.stringify({source:"rule_extracted"}),t.agentId,n,n]);S.lastID>0&&m.set(p.name,S.lastID);}for(let p of l){let b=m.get(p.source),S=m.get(p.target);!b||!S||r.run("INSERT OR REPLACE INTO edges (source, target, relation, properties, createdAt) VALUES (?, ?, ?, ?, ?)",[b,S,p.relation,JSON.stringify({}),n]);}if(r.run(`INSERT INTO memory_facts
27
- (id, agent_id, session_id, msg_id, parent_msg_id, content, category, importance,
28
- source, tags, node_ids, file_path, created_at, updated_at)
29
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[i,t.agentId,e.sessionId??null,e.msgId??null,e.parentMsgId??null,e.content,e.category,c,"session_self_write",e.tags?JSON.stringify(e.tags):null,JSON.stringify(Array.from(m.values())),null,n,n]),d&&E){let p=ve(d);r.run("INSERT OR REPLACE INTO memory_vectors (fact_id, embedding) VALUES (?, ?)",[i,p]),I=1,r.query("SELECT value FROM meta WHERE key = ?",["vectorDims"])[0]||r.run("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)",["vectorDims",String(E)]);}r.run("DELETE FROM memory_facts_fts WHERE fact_id = ?",[i]),r.run("INSERT INTO memory_facts_fts (fact_id, agent_id, content, tags) VALUES (?, ?, ?, ?)",[i,t.agentId,e.content,e.tags?e.tags.join(" "):""]),R.push(...Array.from(m.values()));}),N.info("Memory stored",{id:i,category:e.category,agentId:t.agentId,nodeCount:R.length,vectorsWritten:I,vectorDims:E??0,embeddingMode:u?"enabled":"fts_only"});let f={id:i,agentId:t.agentId,sessionId:e.sessionId,msgId:e.msgId,parentMsgId:e.parentMsgId,content:e.content,category:e.category,importance:c,source:"session_self_write",tags:e.tags,nodeIds:R.length>0?R:void 0,filePath:void 0,createdAt:n,updatedAt:n},h="",g=await J.write(f,t.workspaceDir);if(g.ok){h=g.relPath,f.filePath=g.relPath;try{r.run("UPDATE memory_facts SET file_path = ? WHERE id = ?",[g.relPath,i]);}catch(m){N.warn("Failed to update file_path column after sync",{id:i,error:m instanceof Error?m.message:String(m)});}}return {fact:f,filePath:h,deduplicated:!1,nodeIds:R,vectorsWritten:I,vectorDims:E??0}}catch(n){throw n instanceof w?n:new w(`remember failed: ${n instanceof Error?n.message:String(n)}`,"INTERNAL",{cause:n instanceof Error?n.message:String(n)})}finally{r.close();}}function ht(){let t=Date.now(),e=crypto.randomBytes(3).toString("hex");return `mem_${t}_${e}`}function ve(t){return Buffer.from(t.buffer,t.byteOffset,t.byteLength)}function bt(t){return crypto.createHash("sha256").update(t).digest("hex")}async function Et(t,e){let r=bt(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 i=await exports.b.embedText(e);if(!i||i.length===0)return null;let c=ve(i);return t.prepare("INSERT OR REPLACE INTO embedding_cache (content_hash, embedding) VALUES (?, ?)").run(r,c),i}function wt(t,e,r,n){if(r.length===0&&n.length===0)return;let i=new Date().toISOString(),c=new Map;t.transaction(()=>{for(let o of r){let s=t.query("SELECT id FROM nodes WHERE name = ? AND type = ? AND owner_agent_id = ? LIMIT 1",[o.name,o.type,e])[0];s&&c.set(o.name,s.id);}for(let o of r){if(c.has(o.name))continue;let s=t.run("INSERT INTO nodes (name, type, properties, owner_agent_id, createdAt, updatedAt) VALUES (?, ?, ?, ?, ?, ?)",[o.name,o.type,JSON.stringify({source:"llm_extracted",...o.properties??{}}),e,i,i]);s.lastID>0&&c.set(o.name,s.lastID);}for(let o of n){let s=c.get(o.source),l=c.get(o.target);!s||!l||t.run("INSERT OR REPLACE INTO edges (source, target, relation, properties, createdAt) VALUES (?, ?, ?, ?, ?)",[s,l,o.relation,JSON.stringify({}),i]);}}),N.debug("LLM extraction merged",{agentId:e,entityCount:r.length,relationCount:n.length,resolvedNodeCount:c.size});}var ee=utils.Log.create({service:"memory.service.forget"}),St=1e3;function It(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 w("CONTENT_REQUIRED: forget requires one of: `factId`, `category`, or `fromTime`/`toTime`","CONTENT_REQUIRED");if(e.length>1)throw new w(`mutually exclusive: forget requires exactly one of factId/category/timeRange, got [${e.join(", ")}]`,"CONTENT_REQUIRED");return e[0]}function Mt(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 i=["agent_id = ?"];return e.fromTime&&(i.push("created_at >= ?"),n.push(e.fromTime)),e.toTime&&(i.push("created_at <= ?"),n.push(e.toTime)),{where:i.join(" AND "),args:n}}}}function _t(t,e,r,n){return t.query(`SELECT id, node_ids FROM memory_facts WHERE ${e} LIMIT ?`,[...r,n+1]).map(c=>c.id)}function Ot(t,e,r,n){if(r.length===0)return 0;let i=r.map(()=>"?").join(",");return t.query(`SELECT COUNT(*) as count FROM memory_facts WHERE agent_id = ? AND id != ? AND node_ids IS NOT NULL AND EXISTS (
30
- SELECT 1 FROM json_each(node_ids) AS je WHERE je.value IN (${i})
31
- )`,[n,e,...r])[0]?.count??0}function Tt(t,e,r){let n,i,c="";return t.transaction(()=>{let o=t.query("SELECT node_ids, content, file_path, category, created_at FROM memory_facts WHERE id = ? AND agent_id = ?",[e,r])[0],s=[];if(o?.node_ids)try{s=JSON.parse(o.node_ids),Array.isArray(s)||(s=[]);}catch{s=[];}if(n=o?.file_path??void 0,i=o?.category,c=o?.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]),s.length>0){let l=s.map(()=>"?").join(",");t.run(`DELETE FROM nodes WHERE id IN (${l}) AND NOT EXISTS (
32
- SELECT 1 FROM memory_facts WHERE node_ids IS NOT NULL AND EXISTS (
33
- SELECT 1 FROM json_each(node_ids) AS je WHERE je.value = nodes.id
34
- )
35
- )`,s);}}),{filePath:n,category:i,createdAt:c}}async function xe(t,e){D(t),x(t,"forget");let r=It(e),n=e.maxDelete??St,i=e.dryRun??false,c=e.force??false;ee.debug("forget invoked",{agentId:t.agentId,mode:r,maxDelete:n,dryRun:i,force:c});let o=new chunkOIUUTVLL_cjs.e(t.dbPath);try{await o.initialize();let{where:s,args:l}=Mt(r,e,t.agentId),u=_t(o,s,l,n),d=u.length>n;if(d&&!c)throw new q(u.length,n);let E=d?u.slice(0,n):u;if(i)throw new H(E.length);let R=[],I=[];for(let f of E){if(!c){let p=o.query("SELECT node_ids FROM memory_facts WHERE id = ? AND agent_id = ?",[f,t.agentId])[0],b=p?.node_ids?(()=>{try{let M=JSON.parse(p.node_ids);if(Array.isArray(M))return M.filter(y=>typeof y=="number")}catch{}return []})():[],S=Ot(o,f,b,t.agentId);if(S>0)throw new F(f,S)}let{filePath:h,category:g,createdAt:m}=Tt(o,f,t.agentId);h&&g&&I.push({id:f,filePath:h,category:g,createdAt:m}),R.push(f);}ee.info("forget complete",{agentId:t.agentId,mode:r,deletedCount:R.length,force:c,dryRun:i});for(let{id:f,filePath:h,category:g,createdAt:m}of I)await J.delete({id:f,filePath:h,category:g,createdAt:m},t.workspaceDir).catch(p=>{ee.warn("Fact file delete failed (best-effort)",{id:f,filePath:h,error:p instanceof Error?p.message:String(p)});});return {deletedCount:R.length,deletedIds:R,dryRun:i,truncatedCount:d?u.length-n:0}}catch(s){throw s instanceof w?s:new w(`forget failed: ${s instanceof Error?s.message:String(s)}`,"INTERNAL",{cause:s instanceof Error?s.message:String(s)})}finally{o.close();}}var te=utils.Log.create({service:"memory.service.extract"}),Dt=50,re=500;async function Le(t,e){if(D(t),!e.sessionId||e.sessionId.trim().length===0)throw new w("extract requires non-empty `sessionId`","SESSION_ID_REQUIRED");let r=e.lastN??Dt;if(r>re)throw new w(`extract lastN=${r} exceeds max=${re}`,"CONTENT_REQUIRED",{lastN:r,maxLastN:re});let n=e.sessionId,i=e.fromMessageId;te.debug("extract invoked",{agentId:t.agentId,sessionId:n,lastN:r,fromMessageId:i,writeToDisk:e.writeToDisk??true});let c=Date.now(),o=new chunkOIUUTVLL_cjs.e(t.dbPath);try{await o.initialize();let s=o.query(`SELECT id, content, category, importance, 1.0 as score, created_at, node_ids
36
- FROM memory_facts
37
- WHERE agent_id = ? AND session_id = ?
38
- ORDER BY created_at ASC
39
- LIMIT ?`,[t.agentId,n,r]),l=i?s.filter(f=>f.id>i):s,u=new Set;for(let f of l)if(f.node_ids)try{let h=JSON.parse(f.node_ids);if(Array.isArray(h))for(let g of h)typeof g=="number"&&g>0&&u.add(g);}catch(h){te.warn("extract: invalid node_ids JSON",{factId:f.id,error:h instanceof Error?h.message:String(h)});}let d=Array.from(u),E=[],R=[];if(d.length>0){let f=d.map(()=>"?").join(","),h=o.query(`SELECT id, name, type FROM nodes WHERE id IN (${f})`,d),g=new Map;for(let b of h)g.set(b.id,b.name);E=h.map(b=>({id:b.id,name:b.name,type:b.type}));let m=o.query(`SELECT source, target, relation FROM edges WHERE source IN (${f}) OR target IN (${f})`,[...d,...d]),p=new Set;R=[];for(let b of m){let S=g.get(b.source),M=g.get(b.target);if(!S||!M)continue;let y=`${S}\0${b.relation}\0${M}`;p.has(y)||(p.add(y),R.push({source:S,target:M,relation:b.relation}));}}let I=Date.now()-c;return te.info("extract complete",{agentId:t.agentId,sessionId:n,factCount:l.length,nodeCount:E.length,relationCount:R.length,durationMs:I}),{extractedCount:l.length,factIds:l.map(f=>f.id),entities:E,relations:R,messageRange:{fromMessageId:l[0]?.id??"",toMessageId:l[l.length-1]?.id??""},durationMs:I}}catch(s){throw s instanceof w?s:new w(`extract failed: ${s instanceof Error?s.message:String(s)}`,"INTERNAL",{cause:s instanceof Error?s.message:String(s)})}finally{o.close();}}var ae=utils.Log.create({service:"memory.service.consolidate"}),Pt=30;async function At(t){let{createHash:e}=await import('crypto');return e("sha256").update(t).digest("hex")}async function ke(t,e={}){let r=Date.now();D(t),x(t,"consolidate");let n=e.windowDays??Pt,i=e.dryRun??false;ae.debug("consolidate invoked",{agentId:t.agentId,windowDays:n,dryRun:i});let c=new chunkOIUUTVLL_cjs.e(t.dbPath);try{await c.initialize();let o=c.query("SELECT id, content, category, importance, created_at FROM memory_facts WHERE agent_id = ? ORDER BY created_at DESC",[t.agentId]),s=new Map;for(let g of o){let m=await At(g.content);s.has(m)||s.set(m,[]),s.get(m)?.push(g);}let l=0,u=[];for(let[,g]of s){if(g.length<=1)continue;let m=[...g].sort((S,M)=>S.importance!==M.importance?M.importance-S.importance:M.created_at.localeCompare(S.created_at)),p=m[0];if(!p)continue;let b=m.slice(1).map(S=>S.id);l+=b.length,u.push({keep:p,removeIds:b});}let d=new Date(Date.now()-n*24*60*60*1e3).toISOString(),E=c.query(`SELECT id, content, category, importance, created_at FROM memory_facts
40
- WHERE agent_id = ? AND created_at < ?
41
- ORDER BY created_at ASC`,[t.agentId,d]),R=0,I=0;if(i)R=0,I=l;else {let g=W__default.default.join(t.workspaceDir,"archive");await P__default.default.mkdir(g,{recursive:!0});for(let{removeIds:m}of u){if(m.length===0)continue;let p=m.map(()=>"?").join(",");c.transaction(()=>{for(let b of m)c.run("DELETE FROM memory_facts WHERE id = ? AND agent_id = ?",[b,t.agentId]);}),I+=m.length;}for(let m of E){let p=m.created_at.slice(0,7),b=W__default.default.join(g,p,m.category);await P__default.default.mkdir(b,{recursive:!0});let S=W__default.default.join(b,`${m.id}.md`);try{await P__default.default.writeFile(S,[`# ${m.id}`,"",`category: ${m.category}`,`importance: ${m.importance}`,`createdAt: ${m.created_at}`,"",m.content,""].join(`
42
- `),"utf-8"),c.run("DELETE FROM memory_facts WHERE id = ? AND agent_id = ?",[m.id,t.agentId]),R++;}catch(M){ae.warn("consolidate: archive write failed",{factId:m.id,error:M instanceof Error?M.message:String(M)});}}}let f=o.length,h=0;return ae.info("consolidate complete",{agentId:t.agentId,totalFacts:f,dedupedCount:l,compressedCount:h,archivedCount:R,skippedCount:I,dryRun:i,durationMs:Date.now()-r}),{totalFacts:f,dedupedCount:l,compressedCount:h,archivedCount:R,skippedCount:I,durationMs:Date.now()-r}}catch(o){throw o instanceof w?o:new w(`consolidate failed: ${o instanceof Error?o.message:String(o)}`,"INTERNAL",{cause:o instanceof Error?o.message:String(o)})}finally{c.close();}}var Fe=utils.Log.create({service:"memory.service.graph-query"});async function He(t,e){let r=Date.now(),n=(t.agentId??"").trim()||"default",i=e.scope??"agent_only";if(!e.query||e.query.trim().length===0)throw new w("CONTENT_REQUIRED: graphQuery requires non-empty `query`","CONTENT_REQUIRED");z(t,i,"graph_query");let c=e.depth??2,o=e.maxNodes??100,s=e.query,l=e.type,u=e.relation;Fe.debug("graphQuery invoked",{agentId:n,query:s,type:l,depth:c,maxNodes:o,scope:i,remote:t.remote});let d=new chunkOIUUTVLL_cjs.e(t.dbPath);try{await d.initialize();let E=new v(d.getDb()),R=s.includes("*")||s.includes("%")?s:`%${s}%`,I=await E.queryNodes({name:R,...l?{type:l}:{},agentId:n,scope:i,limit:o}),h=(s.includes("*")||s.includes("%")?I:I.filter(y=>y.name.toLowerCase().includes(s.toLowerCase())))[0]??null;if(!h)return {root:null,nodes:[],edges:[],truncated:!1,totalNodes:0,totalEdges:0,scope:i,durationMs:Date.now()-r};let g=await E.queryNeighbors(h.id,c,{agentId:n,scope:i,maxEdgesPerNode:20}),m=new Map;m.set(h.id,h);for(let y of g)m.set(y.id,{id:y.id,name:y.name,type:y.type,createdAt:y.createdAt,updatedAt:y.updatedAt});let p=[];for(let y of g)if(y.edges)for(let T of y.edges)u&&T.relation!==u||p.push(T);for(let y of p){if(!m.has(y.source)){let T=await E.queryNodes({ids:[y.source],agentId:n,scope:i});T[0]&&m.set(T[0].id,T[0]);}if(!m.has(y.target)){let T=await E.queryNodes({ids:[y.target],agentId:n,scope:i});T[0]&&m.set(T[0].id,T[0]);}}let b=Array.from(m.values()),S=b.length>o,M=S?b.slice(0,o):b;return Fe.info("graphQuery complete",{agentId:n,rootId:h.id,nodeCount:M.length,edgeCount:p.length,truncated:S,durationMs:Date.now()-r}),{root:h,nodes:M,edges:p,truncated:S,totalNodes:b.length,totalEdges:p.length,scope:i,durationMs:Date.now()-r}}catch(E){throw E instanceof w?E:new w(`graphQuery failed: ${E instanceof Error?E.message:String(E)}`,"INTERNAL",{cause:E instanceof Error?E.message:String(E)})}finally{d.close();}}var Y=utils.Log.create({service:"memory.service.status"}),Lt=["user_preference","task_context","technical_fact","decision","relationship","reminder","error_pattern","workflow","exploration_finding","experience_summary","tool_usage","skill_creation","test","other"];async function qe(t,e={}){let r=t.agentId&&t.agentId.trim().length>0?t.agentId:void 0;Y.debug("status invoked",{agentId:r??"<global>"});let n=new chunkOIUUTVLL_cjs.e(t.dbPath);try{await n.initialize();let c=n.query(r!==void 0?"SELECT COUNT(*) as c FROM memory_facts WHERE agent_id = ?":"SELECT COUNT(*) as c FROM memory_facts WHERE agent_id IS NOT NULL",r!==void 0?[r]:[])[0]?.c??0,s=n.query(r!==void 0?"SELECT COUNT(*) AS c FROM nodes WHERE owner_agent_id = ? OR owner_agent_id IS NULL":"SELECT COUNT(*) AS c FROM nodes",r!==void 0?[r]:[])[0]?.c??0,u=n.query("SELECT COUNT(*) as c FROM edges")[0]?.c??0,d=Lt.reduce((m,p)=>(m[p]=0,m),{}),E=n.query(r!==void 0?"SELECT category, COUNT(*) as c FROM memory_facts WHERE agent_id = ? GROUP BY category":"SELECT category, COUNT(*) as c FROM memory_facts WHERE agent_id IS NOT NULL GROUP BY category",r!==void 0?[r]:[]);for(let m of E){let p=m.category;p in d&&(d[p]=m.c);}let R=!1;try{R=n.query("SELECT name FROM sqlite_master WHERE type = ? AND name = ?",["table","memory_facts_fts"]).length>0;}catch(m){Y.debug("status: fts probe failed",{error:m instanceof Error?m.message:String(m)});}let I=!!t.config?.embeddingLlm,f=!1;try{f=n.query("SELECT name FROM pragma_table_info('nodes') WHERE name = ?",["owner_agent_id"]).length>0;}catch(m){Y.debug("status: kg scope probe failed",{error:m instanceof Error?m.message:String(m)});}let h=n.healthCheck(),g={};try{let m=n.query("SELECT key, value FROM meta");for(let p of m)g[p.key]=p.value;}catch(m){Y.debug("status: meta read failed",{error:m instanceof Error?m.message:String(m)});}return {dbPath:t.dbPath,workspaceDir:t.workspaceDir,factsCount:c,nodesCount:s,edgesCount:u,factsByCategory:d,ftsAvailable:R,vectorEnabled:I,kgScopeEnabled:f,healthy:h,meta:g}}catch(i){throw i instanceof w?i:new w(`status failed: ${i instanceof Error?i.message:String(i)}`,"INTERNAL")}finally{n.close();}}var Ht=utils.Log.create({service:"memory.service.doctor"}),ie=100*1024*1024,ce=100*1024*1024;async function $e(t,e={}){Ht.debug("doctor invoked",{agentId:t.agentId});let r=[],n=null;try{n=new chunkOIUUTVLL_cjs.e(t.dbPath),await n.initialize();let o=n.healthCheck();r.push({name:"database",passed:o,message:o?"database connected and writable":"database unhealthy",details:{dbPath:t.dbPath}});}catch(o){r.push({name:"database",passed:false,message:`database connection failed: ${o instanceof Error?o.message:String(o)}`,details:{dbPath:t.dbPath}});}try{if(!n)throw new Error("db not initialized");let o=n.query("SELECT name FROM sqlite_master WHERE type = ? AND name = ?",["table","memory_facts_fts"]);r.push({name:"fts",passed:o.length>0,message:o.length>0?"FTS5 index available":"FTS5 index not found",details:o.length>0?{table:o[0]?.name}:void 0});}catch(o){r.push({name:"fts",passed:false,message:`fts probe failed: ${o instanceof Error?o.message:String(o)}`});}let i=!!t.config?.embeddingLlm;r.push({name:"vector",passed:true,message:i?"embedding model available":"no embedding model configured (FTS-only mode, recall still functional)",details:{mode:i?"hybrid":"fts_only",model:t.config?.embeddingLlm?"configured":"missing"}});try{if(!n)throw new Error("db not initialized");let o=["memory_facts","nodes","edges","meta"],s=n.query("SELECT name FROM sqlite_master WHERE type = ?",["table"]),l=new Set(s.map(d=>d.name)),u=o.filter(d=>!l.has(d));r.push({name:"schema",passed:u.length===0,message:u.length===0?`schema complete (${o.length} tables)`:`missing tables: ${u.join(", ")}`,details:{required:o,existing:Array.from(l)}});}catch(o){r.push({name:"schema",passed:false,message:`schema probe failed: ${o instanceof Error?o.message:String(o)}`});}try{let o=`${t.dbPath}-wal`,s=`${t.dbPath}-shm`,l=0,u=0;try{l=(await P__default.default.stat(o)).size;}catch{l=0;}try{u=(await P__default.default.stat(s)).size;}catch{u=0;}let d=l+u;r.push({name:"lock",passed:d<=ce,message:d<=ce?`no lock contention (wal+shm ${(d/1024).toFixed(1)} KB)`:`WAL/SHM files unusually large (${(d/1024/1024).toFixed(1)} MB > ${(ce/1024/1024).toFixed(0)} MB threshold)`,details:{walBytes:l,shmBytes:u}});}catch(o){r.push({name:"lock",passed:false,message:`lock probe failed: ${o instanceof Error?o.message:String(o)}`});}try{let o=W__default.default.dirname(t.dbPath),s=await P__default.default.statfs(o),l=typeof s.bsize=="bigint"?Number(s.bsize)*s.bavail:s.bsize*s.bavail,u=l>=ie;r.push({name:"disk_space",passed:u,message:u?`sufficient disk space (${(l/1024/1024).toFixed(1)} MB available)`:`low disk space (${(l/1024/1024).toFixed(1)} MB < ${(ie/1024/1024).toFixed(0)} MB threshold)`,details:{availableBytes:l,threshold:ie}});}catch(o){r.push({name:"disk_space",passed:false,message:`disk_space probe failed: ${o instanceof Error?o.message:String(o)}`});}try{if(!n)throw new Error("db not initialized");let o=n.agentFilter(t.agentId),s=n.query(`SELECT id, node_ids FROM memory_facts ${o.where} ${o.where?"AND":"WHERE"} node_ids IS NOT NULL`,o.params),l=[];for(let u of s)try{let d=JSON.parse(u.node_ids);if(!Array.isArray(d))continue;for(let E of d){if(typeof E!="number")continue;if((n.query("SELECT COUNT(*) as c FROM nodes WHERE id = ?",[E])[0]?.c??0)===0){l.push(`${u.id}->${E}`);break}}}catch{}r.push({name:"orphan",passed:l.length===0,message:l.length===0?"no orphan KG references":`${l.length} orphan references: ${l.slice(0,5).join(", ")}${l.length>5?", ...":""}`,details:{count:l.length}});}catch(o){r.push({name:"orphan",passed:false,message:`orphan probe failed: ${o instanceof Error?o.message:String(o)}`});}try{if(!n)throw new Error("db not initialized");let o=n.query("SELECT COUNT(*) as c FROM embedding_cache")[0],s=n.agentFilter(t.agentId),l=n.query(`SELECT COUNT(*) as c FROM memory_facts ${s.where}`,s.params)[0],u=o?.c??0,d=l?.c??0,E=Math.max(0,u-d),R=E>0;r.push({name:"embedding_cache_unused",passed:!R,severity:"info",message:R?`by design: ${E} 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)",details:{cacheCount:u,factsCount:d,unused:E,policy:"global_content_hash_dedup"}});}catch(o){r.push({name:"embedding_cache_unused",passed:false,message:`embedding_cache_unused probe failed: ${o instanceof Error?o.message:String(o)}`});}let c=r.every(o=>o.severity==="info"?true:o.passed);return n&&n.close(),{healthy:c,checks:r}}var A=utils.Log.create({service:"memory.service.init"});function Ut(t){return W__default.default.join(t,".easbot","memory.json")}function Wt(t,e={}){let r={version:1,schema_version:chunkOIUUTVLL_cjs.a,backend:"better-sqlite3",created_at:new Date().toISOString(),embedding_llm:e.embeddingLlm??null,embedding_batch_size:32,embedding_dimensions:768,graph_llm:e.graphLlm??null,entity_extraction_prompt:e.entityExtractionPrompt??null,relation_extraction_prompt:e.relationExtractionPrompt??null,tokenizer:{dictPath:["./packages/memory/src/assets/jieba_dict.txt"]},archiveDays:e.archiveDays??30,shortTermMaxRounds:e.shortTermMaxRounds??20};fs.writeFileSync(t,JSON.stringify(r,null,2),"utf-8");}async function Ue(t,e={}){let r=Date.now();x(t,"init");let n=e.workspaceDir??t.workspaceDir,i=e.dbPath??t.dbPath;if(!n||n.trim().length===0)throw new w("init requires non-empty `workspaceDir` (ctx.workspaceDir or params.workspaceDir)","CONTENT_REQUIRED");if(!i||i.trim().length===0)throw new w("init requires non-empty `dbPath` (ctx.dbPath or params.dbPath)","CONTENT_REQUIRED");let c=t.agentId?.trim()??"",o=e.force??false;A.debug("init invoked",{agentId:c,workspaceDir:n,dbPath:i,force:o});try{await P__default.default.mkdir(W__default.default.dirname(i),{recursive:!0}),await P__default.default.mkdir(W__default.default.join(n,".easbot","memory","active"),{recursive:!0}),await P__default.default.mkdir(W__default.default.join(n,"archive"),{recursive:!0}),await P__default.default.mkdir(W__default.default.join(n,".easbot"),{recursive:!0});}catch(d){throw new w(`init: failed to create directories: ${d instanceof Error?d.message:String(d)}`,"INTERNAL",{cause:d instanceof Error?d.message:String(d)})}if(o)try{await P__default.default.rm(i,{force:!0});}catch(d){A.warn("init: force rm db failed (may not exist)",{dbPath:i,error:d instanceof Error?d.message:String(d)});}let s=Ut(n),l=false;try{!await P__default.default.stat(s).then(()=>!0).catch(()=>!1)||o?(Wt(s,{embeddingLlm:t.config?.embeddingLlm?String(t.config.embeddingLlm.modelId??""):void 0,graphLlm:t.config?.graphLlm?String(t.config.graphLlm.modelId??""):void 0,archiveDays:t.config?.archiveDays,shortTermMaxRounds:t.config?.shortTermMaxRounds}),l=!0,A.info("init: memory.json written",{configPath:s,force:o,configCreated:l})):A.debug("init: memory.json already exists, skipping write",{configPath:s});}catch(d){A.warn("init: memory.json write failed (non-fatal)",{configPath:s,error:d instanceof Error?d.message:String(d)});}let u=new chunkOIUUTVLL_cjs.e(i);try{let d=await P__default.default.stat(i).then(()=>!0).catch(()=>!1);await u.initialize();let E=new Date().toISOString(),R=[["version","1.0.0"],["schemaVersion",String(chunkOIUUTVLL_cjs.a)],["createdAt",E],["defaultAgentId",c]];for(let[h,g]of R)try{u.run("INSERT OR IGNORE INTO meta (key, value) VALUES (?, ?)",[h,g]);}catch(m){A.warn("init: meta insert failed",{key:h,error:m instanceof Error?m.message:String(m)});}let I=d?0:12,f=d?0:1;return A.info("init complete",{agentId:c,workspaceDir:n,dbPath:i,configPath:s,configCreated:l,schemaVersion:chunkOIUUTVLL_cjs.a,durationMs:Date.now()-r}),{initialized:!0,dbPath:i,configPath:s,configCreated:l,workspaceDir:n,tablesCreated:I,migrationsApplied:f,durationMs:Date.now()-r}}catch(d){throw new w(`init failed: ${d instanceof Error?d.message:String(d)}`,"INTERNAL",{cause:d instanceof Error?d.message:String(d)})}finally{u.close();}}var de={name:"recall",scope:"read",schema:we,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 Ee({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 me={name:"remember",scope:"write",schema:Re,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 Ae({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:Se,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 xe({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:e.remote??false,config:e.config,agentId:e.agentId},r)}};var ue={name:"extract",scope:"write",schema:Ie,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 Le({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 ge={name:"consolidate",scope:"admin",schema:Me,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 ke({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:false,config:e.config,agentId:e.agentId},r)}};var pe={name:"graph_query",scope:"read",schema:_e,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 He({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 fe={name:"status",scope:"read",schema:Oe,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 qe({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:e.remote??false,config:e.config,agentId:e.agentId},r)}};var ye={name:"doctor",scope:"admin",schema:Te,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 $e({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:"init",scope:"admin",schema:Ce,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 Ue({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 We={[de.name]:de,[me.name]:me,[le.name]:le,[ue.name]:ue,[ge.name]:ge,[pe.name]:pe,[fe.name]:fe,[ye.name]:ye,[he.name]:he},jt=Object.values(We);function Gt(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 Po(t,e,r){let n=We[t];if(!n)throw new Error(`executeOp: unknown op "${t}"; available: ${jt.map(c=>c.name).join(", ")}`);return Gt(n,r,t),await n.handler(e,r)}function Bt(t){let e=t.dbPath??"";return {workspaceDir:t.workspaceDir??"",database:{path:e},embeddingLlm:void 0,graphLlm:void 0,search:types.DEFAULT_SEARCH_CONFIG,indexer:{batchSize:20,ignorePatterns:[],incremental:true},archiveDays:30,shortTermMaxRounds:20}}function qo(t,e,r={}){let n=chunkCPRDIUQ4_cjs.j(e),i=utils.Locale.resolveLocaleLang(r.locale);return {agentId:t,dbPath:n,workspaceDir:e,rootDir:e,config:Bt({dbPath:n,workspaceDir:e}),isTrustedLocal:true,locale:i,remote:false,...r}}exports.a=v;exports.c=Ee;exports.d=we;exports.e=Re;exports.f=Se;exports.g=Ie;exports.h=Me;exports.i=_e;exports.j=Ce;exports.k=Ae;exports.l=xe;exports.m=Le;exports.n=ke;exports.o=He;exports.p=qe;exports.q=$e;exports.r=Ue;exports.s=We;exports.t=jt;exports.u=Po;exports.v=Bt;exports.w=qo;