@yamo/memory-mesh 2.3.2 → 3.0.1

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 (124) hide show
  1. package/README.md +8 -2
  2. package/bin/memory_mesh.js +1 -1
  3. package/lib/llm/client.d.ts +86 -0
  4. package/lib/llm/client.js +300 -357
  5. package/lib/llm/client.ts +334 -0
  6. package/lib/llm/index.d.ts +17 -0
  7. package/lib/llm/index.js +16 -8
  8. package/lib/llm/index.ts +18 -0
  9. package/lib/memory/adapters/client.d.ts +120 -0
  10. package/lib/memory/adapters/client.js +519 -0
  11. package/lib/memory/adapters/client.ts +519 -0
  12. package/lib/memory/adapters/config.d.ts +130 -0
  13. package/lib/memory/adapters/config.js +190 -0
  14. package/lib/memory/adapters/config.ts +190 -0
  15. package/lib/memory/adapters/errors.d.ts +84 -0
  16. package/lib/memory/adapters/errors.js +129 -0
  17. package/lib/memory/adapters/errors.ts +129 -0
  18. package/lib/memory/context-manager.d.ts +41 -0
  19. package/lib/memory/context-manager.js +345 -0
  20. package/lib/memory/context-manager.ts +345 -0
  21. package/lib/memory/embeddings/factory.d.ts +57 -0
  22. package/lib/memory/embeddings/factory.js +149 -0
  23. package/lib/memory/embeddings/factory.ts +149 -0
  24. package/lib/memory/embeddings/index.d.ts +2 -0
  25. package/lib/memory/embeddings/index.js +3 -0
  26. package/lib/memory/embeddings/index.ts +3 -0
  27. package/lib/memory/embeddings/service.d.ts +134 -0
  28. package/lib/memory/embeddings/service.js +516 -0
  29. package/lib/memory/embeddings/service.ts +516 -0
  30. package/lib/memory/index.d.ts +9 -0
  31. package/lib/memory/index.js +10 -1
  32. package/lib/memory/index.ts +10 -0
  33. package/lib/memory/memory-mesh.d.ts +332 -0
  34. package/lib/memory/memory-mesh.js +1470 -678
  35. package/lib/memory/memory-mesh.ts +1517 -0
  36. package/lib/memory/memory-translator.d.ts +14 -0
  37. package/lib/memory/memory-translator.js +126 -0
  38. package/lib/memory/memory-translator.ts +126 -0
  39. package/lib/memory/schema.d.ts +130 -0
  40. package/lib/memory/schema.js +184 -0
  41. package/lib/memory/schema.ts +184 -0
  42. package/lib/memory/scorer.d.ts +25 -0
  43. package/lib/memory/scorer.js +78 -0
  44. package/lib/memory/scorer.ts +78 -0
  45. package/lib/memory/search/index.d.ts +1 -0
  46. package/lib/memory/search/index.js +2 -0
  47. package/lib/memory/search/index.ts +2 -0
  48. package/lib/memory/search/keyword-search.d.ts +46 -0
  49. package/lib/memory/search/keyword-search.js +136 -0
  50. package/lib/memory/search/keyword-search.ts +136 -0
  51. package/lib/scrubber/config/defaults.d.ts +46 -0
  52. package/lib/scrubber/config/defaults.js +50 -57
  53. package/lib/scrubber/config/defaults.ts +55 -0
  54. package/lib/scrubber/errors/scrubber-error.d.ts +22 -0
  55. package/lib/scrubber/errors/scrubber-error.js +28 -32
  56. package/lib/scrubber/errors/scrubber-error.ts +44 -0
  57. package/lib/scrubber/index.d.ts +5 -0
  58. package/lib/scrubber/index.js +4 -23
  59. package/lib/scrubber/index.ts +6 -0
  60. package/lib/scrubber/scrubber.d.ts +44 -0
  61. package/lib/scrubber/scrubber.js +100 -121
  62. package/lib/scrubber/scrubber.ts +109 -0
  63. package/lib/scrubber/stages/chunker.d.ts +25 -0
  64. package/lib/scrubber/stages/chunker.js +74 -91
  65. package/lib/scrubber/stages/chunker.ts +104 -0
  66. package/lib/scrubber/stages/metadata-annotator.d.ts +17 -0
  67. package/lib/scrubber/stages/metadata-annotator.js +55 -65
  68. package/lib/scrubber/stages/metadata-annotator.ts +75 -0
  69. package/lib/scrubber/stages/normalizer.d.ts +16 -0
  70. package/lib/scrubber/stages/normalizer.js +42 -50
  71. package/lib/scrubber/stages/normalizer.ts +60 -0
  72. package/lib/scrubber/stages/semantic-filter.d.ts +16 -0
  73. package/lib/scrubber/stages/semantic-filter.js +42 -52
  74. package/lib/scrubber/stages/semantic-filter.ts +62 -0
  75. package/lib/scrubber/stages/structural-cleaner.d.ts +18 -0
  76. package/lib/scrubber/stages/structural-cleaner.js +66 -75
  77. package/lib/scrubber/stages/structural-cleaner.ts +83 -0
  78. package/lib/scrubber/stages/validator.d.ts +17 -0
  79. package/lib/scrubber/stages/validator.js +46 -56
  80. package/lib/scrubber/stages/validator.ts +67 -0
  81. package/lib/scrubber/telemetry.d.ts +29 -0
  82. package/lib/scrubber/telemetry.js +54 -58
  83. package/lib/scrubber/telemetry.ts +62 -0
  84. package/lib/scrubber/utils/hash.d.ts +14 -0
  85. package/lib/scrubber/utils/hash.js +30 -32
  86. package/lib/scrubber/utils/hash.ts +40 -0
  87. package/lib/scrubber/utils/html-parser.d.ts +14 -0
  88. package/lib/scrubber/utils/html-parser.js +32 -39
  89. package/lib/scrubber/utils/html-parser.ts +46 -0
  90. package/lib/scrubber/utils/pattern-matcher.d.ts +12 -0
  91. package/lib/scrubber/utils/pattern-matcher.js +48 -57
  92. package/lib/scrubber/utils/pattern-matcher.ts +64 -0
  93. package/lib/scrubber/utils/token-counter.d.ts +18 -0
  94. package/lib/scrubber/utils/token-counter.js +24 -25
  95. package/lib/scrubber/utils/token-counter.ts +32 -0
  96. package/lib/utils/logger.d.ts +19 -0
  97. package/lib/utils/logger.js +65 -0
  98. package/lib/utils/logger.ts +65 -0
  99. package/lib/utils/skill-metadata.d.ts +24 -0
  100. package/lib/utils/skill-metadata.js +133 -0
  101. package/lib/utils/skill-metadata.ts +133 -0
  102. package/lib/yamo/emitter.d.ts +46 -0
  103. package/lib/yamo/emitter.js +79 -143
  104. package/lib/yamo/emitter.ts +171 -0
  105. package/lib/yamo/index.d.ts +14 -0
  106. package/lib/yamo/index.js +6 -7
  107. package/lib/yamo/index.ts +16 -0
  108. package/lib/yamo/schema.d.ts +56 -0
  109. package/lib/yamo/schema.js +82 -108
  110. package/lib/yamo/schema.ts +133 -0
  111. package/package.json +13 -8
  112. package/index.d.ts +0 -111
  113. package/lib/embeddings/factory.js +0 -151
  114. package/lib/embeddings/index.js +0 -2
  115. package/lib/embeddings/service.js +0 -586
  116. package/lib/index.js +0 -6
  117. package/lib/lancedb/client.js +0 -633
  118. package/lib/lancedb/config.js +0 -215
  119. package/lib/lancedb/errors.js +0 -144
  120. package/lib/lancedb/index.js +0 -4
  121. package/lib/lancedb/schema.js +0 -217
  122. package/lib/search/index.js +0 -1
  123. package/lib/search/keyword-search.js +0 -144
  124. package/lib/utils/index.js +0 -1
@@ -0,0 +1,129 @@
1
+ // @ts-nocheck
2
+ /**
3
+ * Custom error classes for LanceDB operations
4
+ *
5
+ * Base error class for all LanceDB-related errors. Captures proper stack traces
6
+ * to ensure debugging information points to where errors are thrown, not to the
7
+ * error constructor.
8
+ */
9
+ export class LanceDBError extends Error {
10
+ code;
11
+ details;
12
+ timestamp;
13
+ /**
14
+ * Create a new LanceDBError
15
+ * @param {string} message - Human-readable error message
16
+ * @param {string} code - Machine-readable error code (e.g., 'EMBEDDING_ERROR')
17
+ * @param {Object} details - Additional error context and metadata
18
+ */
19
+ constructor(message, code, details = {}) {
20
+ super(message);
21
+ this.name = "LanceDBError";
22
+ this.code = code;
23
+ this.details = details;
24
+ this.timestamp = new Date().toISOString();
25
+ // Capture stack trace for proper debugging (Node.js best practice)
26
+ // This ensures stack traces point to where the error was thrown,
27
+ // not to the error constructor itself
28
+ Error.captureStackTrace(this, this.constructor);
29
+ }
30
+ }
31
+ /**
32
+ * Error raised when embedding generation or comparison fails
33
+ */
34
+ export class EmbeddingError extends LanceDBError {
35
+ constructor(message, details) {
36
+ super(message, "EMBEDDING_ERROR", details);
37
+ this.name = "EmbeddingError";
38
+ }
39
+ }
40
+ /**
41
+ * Error raised when storage operations (read/write/delete) fail
42
+ */
43
+ export class StorageError extends LanceDBError {
44
+ constructor(message, details) {
45
+ super(message, "STORAGE_ERROR", details);
46
+ this.name = "StorageError";
47
+ }
48
+ }
49
+ /**
50
+ * Error raised when database queries fail or return invalid results
51
+ */
52
+ export class QueryError extends LanceDBError {
53
+ constructor(message, details) {
54
+ super(message, "QUERY_ERROR", details);
55
+ this.name = "QueryError";
56
+ }
57
+ }
58
+ /**
59
+ * Error raised when configuration is missing or invalid
60
+ */
61
+ export class ConfigurationError extends LanceDBError {
62
+ constructor(message, details) {
63
+ super(message, "CONFIGURATION_ERROR", details);
64
+ this.name = "ConfigurationError";
65
+ }
66
+ }
67
+ /**
68
+ * Sanitize error messages by redacting sensitive information
69
+ * @param {string} message - Error message to sanitize
70
+ * @returns {string} Sanitized error message
71
+ */
72
+ export function sanitizeErrorMessage(message) {
73
+ if (typeof message !== "string") {
74
+ return "[Non-string error message]";
75
+ }
76
+ // Redact common sensitive patterns
77
+ return (message
78
+ // Redact Bearer tokens
79
+ .replace(/Bearer\s+[A-Za-z0-9\-._~+/]+=*/gi, "Bearer [REDACTED]")
80
+ // Redact OpenAI API keys (sk- followed by 32+ chars)
81
+ .replace(/sk-[A-Za-z0-9]{32,}/g, "sk-[REDACTED]")
82
+ // Redact generic API keys (20+ alphanumeric chars after api_key)
83
+ .replace(/api_key["\s:]+[A-Za-z0-9]{20,}/gi, "api_key: [REDACTED]")
84
+ // Redact environment variable patterns that might contain secrets
85
+ .replace(/(OPENAI_API_KEY|ANTHROPIC_API_KEY|GOOGLE_API_KEY)["='\s]+[A-Za-z0-9\-_]+/gi, "$1=[REDACTED]")
86
+ // Redact Authorization headers
87
+ .replace(/Authorization:\s*[^"\r\n]+/gi, "Authorization: [REDACTED]")
88
+ // Redact potential JWT tokens
89
+ .replace(/eyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*/g, "[JWT_REDACTED]"));
90
+ }
91
+ /**
92
+ * Normalize errors into a consistent response format
93
+ * @param {Error} error - The error to handle
94
+ * @param {Object} context - Additional context about where/when the error occurred
95
+ * @returns {Object} Formatted error response with success: false
96
+ */
97
+ export function handleError(error, context = {}) {
98
+ if (error instanceof LanceDBError) {
99
+ return {
100
+ success: false,
101
+ error: {
102
+ code: error.code,
103
+ message: sanitizeErrorMessage(error.message),
104
+ details: error.details,
105
+ context,
106
+ },
107
+ };
108
+ }
109
+ const err = error instanceof Error ? error : new Error(String(error));
110
+ // Wrap unknown errors
111
+ return {
112
+ success: false,
113
+ error: {
114
+ code: "UNKNOWN_ERROR",
115
+ message: sanitizeErrorMessage(err.message),
116
+ stack: process.env.NODE_ENV === "development" ? err.stack : undefined,
117
+ context,
118
+ },
119
+ };
120
+ }
121
+ export default {
122
+ LanceDBError,
123
+ EmbeddingError,
124
+ StorageError,
125
+ QueryError,
126
+ ConfigurationError,
127
+ handleError,
128
+ sanitizeErrorMessage,
129
+ };
@@ -0,0 +1,41 @@
1
+ export declare class MemoryContextManager {
2
+ #private;
3
+ /**
4
+ * Create a new MemoryContextManager
5
+ */
6
+ constructor(config?: {});
7
+ /**
8
+ * Initialize the memory context manager
9
+ */
10
+ initialize(): Promise<void>;
11
+ /**
12
+ * Capture an interaction as memory
13
+ */
14
+ captureInteraction(prompt: any, response: any, context?: {}): Promise<any>;
15
+ /**
16
+ * Recall relevant memories for a query
17
+ */
18
+ recallMemories(query: any, options?: {}): Promise<any>;
19
+ /**
20
+ * Format memories for inclusion in prompt
21
+ */
22
+ formatMemoriesForPrompt(memories: any, options?: {}): string;
23
+ clearCache(): void;
24
+ getCacheStats(): {
25
+ size: number;
26
+ maxSize: number;
27
+ ttlMs: number;
28
+ };
29
+ healthCheck(): Promise<{
30
+ status: string;
31
+ timestamp: string;
32
+ initialized: boolean;
33
+ checks: {};
34
+ }>;
35
+ /**
36
+ * Dispose of resources (cleanup timer and cache)
37
+ * Call this when the MemoryContextManager is no longer needed
38
+ */
39
+ dispose(): void;
40
+ }
41
+ export default MemoryContextManager;
@@ -0,0 +1,345 @@
1
+ // @ts-nocheck
2
+ /**
3
+ * MemoryContextManager - High-level memory management for YAMO
4
+ */
5
+ import { MemoryMesh } from "./memory-mesh.js";
6
+ import { MemoryScorer } from "./scorer.js";
7
+ import { MemoryTranslator } from "./memory-translator.js";
8
+ import { createLogger } from "../utils/logger.js";
9
+ const logger = createLogger("context-manager");
10
+ export class MemoryContextManager {
11
+ #config;
12
+ #mesh;
13
+ #scorer;
14
+ #initialized = false;
15
+ #queryCache = new Map();
16
+ #cacheConfig = {
17
+ maxSize: 100,
18
+ ttlMs: 2 * 60 * 1000, // 2 minutes
19
+ };
20
+ #cleanupTimer = null;
21
+ /**
22
+ * Create a new MemoryContextManager
23
+ */
24
+ constructor(config = {}) {
25
+ this.#config = {
26
+ autoInit: true,
27
+ enableCache: true,
28
+ recallLimit: 5,
29
+ minImportance: 0.1,
30
+ silent: config.silent !== false,
31
+ ...config,
32
+ };
33
+ // Use provided mesh or create new instance
34
+ this.#mesh = config.mesh || new MemoryMesh();
35
+ this.#scorer = new MemoryScorer(this.#mesh);
36
+ // Start periodic cleanup timer (every 60 seconds)
37
+ this.#startCleanupTimer();
38
+ }
39
+ /**
40
+ * Initialize the memory context manager
41
+ */
42
+ async initialize() {
43
+ if (this.#initialized) {
44
+ return;
45
+ }
46
+ try {
47
+ await this.#mesh.init();
48
+ this.#initialized = true;
49
+ }
50
+ catch (error) {
51
+ this.#logWarn(`Initialization failed: ${error.message}`);
52
+ this.#initialized = false;
53
+ }
54
+ }
55
+ /**
56
+ * Capture an interaction as memory
57
+ */
58
+ async captureInteraction(prompt, response, context = {}) {
59
+ try {
60
+ if (this.#config.autoInit && !this.#initialized) {
61
+ await this.initialize();
62
+ }
63
+ if (!this.#initialized) {
64
+ return null;
65
+ }
66
+ const content = this.#formatInteraction(prompt, response);
67
+ const metadata = this.#buildMetadata(context);
68
+ const isDuplicate = await this.#scorer.isDuplicate(content);
69
+ if (isDuplicate) {
70
+ return null;
71
+ }
72
+ const importance = this.#scorer.calculateImportance(content, metadata);
73
+ if (importance < (this.#config.minImportance ?? 0.1)) {
74
+ return null;
75
+ }
76
+ const memory = await this.#mesh.add(content, {
77
+ ...metadata,
78
+ importanceScore: importance,
79
+ });
80
+ return memory;
81
+ }
82
+ catch (error) {
83
+ this.#logWarn(`Failed to capture interaction: ${error.message}`);
84
+ return null;
85
+ }
86
+ }
87
+ /**
88
+ * Recall relevant memories for a query
89
+ */
90
+ async recallMemories(query, options = {}) {
91
+ try {
92
+ if (this.#config.autoInit && !this.#initialized) {
93
+ await this.initialize();
94
+ }
95
+ if (!this.#initialized) {
96
+ return [];
97
+ }
98
+ const { limit = this.#config.recallLimit, useCache = this.#config.enableCache, memoryType = null, skillName = null, } = options;
99
+ if (useCache) {
100
+ const cacheKey = this.#cacheKey(query, {
101
+ limit,
102
+ memoryType,
103
+ skillName,
104
+ });
105
+ const cached = this.#getCached(cacheKey);
106
+ if (cached) {
107
+ return cached;
108
+ }
109
+ }
110
+ const filter = memoryType ? `memoryType == '${memoryType}'` : null;
111
+ // Fetch extra when skill-scoping — some results will be filtered out post-query
112
+ const fetchLimit = skillName ? limit * 2 : limit;
113
+ let memories = [];
114
+ if (memoryType === "synthesized_skill" &&
115
+ typeof this.#mesh.searchSkills === "function") {
116
+ memories = await this.#mesh.searchSkills(query, { limit: fetchLimit });
117
+ }
118
+ else {
119
+ memories = await this.#mesh.search(query, {
120
+ limit: fetchLimit,
121
+ filter,
122
+ useCache: false,
123
+ });
124
+ }
125
+ memories = memories.map((memory) => {
126
+ const metadata = typeof memory.metadata === "string"
127
+ ? JSON.parse(memory.metadata)
128
+ : memory.metadata || {};
129
+ return {
130
+ ...memory,
131
+ importanceScore: memory.score || metadata.importanceScore || 0,
132
+ memoryType: metadata.memoryType ||
133
+ (memoryType === "synthesized_skill"
134
+ ? "synthesized_skill"
135
+ : "global"),
136
+ };
137
+ });
138
+ // Deduplicate by content — results are already sorted by score, so first occurrence wins
139
+ const seen = new Set();
140
+ memories = memories.filter((memory) => {
141
+ if (seen.has(memory.content)) {
142
+ return false;
143
+ }
144
+ seen.add(memory.content);
145
+ return true;
146
+ });
147
+ // Skill-scope filter: keep memories tagged with this skill OR untagged (global).
148
+ // Untagged memories are shared context; tagged memories are skill-private.
149
+ if (skillName) {
150
+ memories = memories.filter((memory) => {
151
+ const meta = typeof memory.metadata === "string"
152
+ ? JSON.parse(memory.metadata)
153
+ : memory.metadata || {};
154
+ return !meta.skill_name || meta.skill_name === skillName;
155
+ });
156
+ memories = memories.slice(0, limit);
157
+ }
158
+ if (useCache) {
159
+ const cacheKey = this.#cacheKey(query, {
160
+ limit,
161
+ memoryType,
162
+ skillName,
163
+ });
164
+ this.#setCached(cacheKey, memories);
165
+ }
166
+ return memories;
167
+ }
168
+ catch (error) {
169
+ this.#logWarn(`Failed to recall memories: ${error.message}`);
170
+ return [];
171
+ }
172
+ }
173
+ /**
174
+ * Format memories for inclusion in prompt
175
+ */
176
+ formatMemoriesForPrompt(memories, options = {}) {
177
+ try {
178
+ if (!memories || memories.length === 0) {
179
+ return "";
180
+ }
181
+ return MemoryTranslator.toYAMOContext(memories, options);
182
+ }
183
+ catch (error) {
184
+ this.#logWarn(`Failed to format memories: ${error.message}`);
185
+ return "";
186
+ }
187
+ }
188
+ #logWarn(message) {
189
+ if (!this.#config.silent || process.env.YAMO_DEBUG === "true") {
190
+ logger.warn(message);
191
+ }
192
+ }
193
+ #formatInteraction(prompt, response) {
194
+ const lines = [
195
+ `[USER] ${prompt}`,
196
+ `[ASSISTANT] ${response.substring(0, 500)}${response.length > 500 ? "..." : ""}`,
197
+ ];
198
+ return lines.join("\n\n");
199
+ }
200
+ #buildMetadata(context) {
201
+ const metadata = {
202
+ interaction_type: context.interactionType || "llm_response",
203
+ created_at: new Date().toISOString(),
204
+ };
205
+ if (context.toolsUsed?.length > 0) {
206
+ metadata.tools_used = context.toolsUsed;
207
+ }
208
+ if (context.filesInvolved?.length > 0) {
209
+ metadata.files_involved = context.filesInvolved;
210
+ }
211
+ if (context.tags?.length > 0) {
212
+ metadata.tags = context.tags;
213
+ }
214
+ if (context.skillName) {
215
+ metadata.skill_name = context.skillName;
216
+ }
217
+ if (context.sessionId) {
218
+ metadata.session_id = context.sessionId;
219
+ }
220
+ return metadata;
221
+ }
222
+ #cacheKey(query, options) {
223
+ return `recall:${query}:${JSON.stringify(options)}`;
224
+ }
225
+ /**
226
+ * Get cached result if valid
227
+ * Race condition fix: Update timestamp atomically for LRU tracking
228
+ */
229
+ #getCached(key) {
230
+ const entry = this.#queryCache.get(key);
231
+ if (!entry) {
232
+ return null;
233
+ }
234
+ // Check TTL before any mutation
235
+ const now = Date.now();
236
+ if (now - entry.timestamp > this.#cacheConfig.ttlMs) {
237
+ this.#queryCache.delete(key);
238
+ return null;
239
+ }
240
+ // Move to end (most recently used) - delete and re-add with updated timestamp
241
+ this.#queryCache.delete(key);
242
+ this.#queryCache.set(key, {
243
+ ...entry,
244
+ timestamp: now, // Update timestamp for LRU tracking
245
+ });
246
+ return entry.result;
247
+ }
248
+ #setCached(key, result) {
249
+ if (this.#queryCache.size >= this.#cacheConfig.maxSize) {
250
+ const firstKey = this.#queryCache.keys().next().value;
251
+ if (firstKey !== undefined) {
252
+ this.#queryCache.delete(firstKey);
253
+ }
254
+ }
255
+ this.#queryCache.set(key, {
256
+ result,
257
+ timestamp: Date.now(),
258
+ });
259
+ }
260
+ clearCache() {
261
+ this.#queryCache.clear();
262
+ }
263
+ getCacheStats() {
264
+ return {
265
+ size: this.#queryCache.size,
266
+ maxSize: this.#cacheConfig.maxSize,
267
+ ttlMs: this.#cacheConfig.ttlMs,
268
+ };
269
+ }
270
+ async healthCheck() {
271
+ const health = {
272
+ status: "healthy",
273
+ timestamp: new Date().toISOString(),
274
+ initialized: this.#initialized,
275
+ checks: {},
276
+ };
277
+ try {
278
+ health.checks.mesh = await this.#mesh.stats(); // brain.ts has stats()
279
+ if (health.checks.mesh.isConnected === false) {
280
+ health.status = "degraded";
281
+ }
282
+ }
283
+ catch (error) {
284
+ health.checks.mesh = {
285
+ status: "error",
286
+ error: error.message,
287
+ };
288
+ health.status = "unhealthy";
289
+ }
290
+ health.checks.cache = {
291
+ status: "up",
292
+ size: this.#queryCache.size,
293
+ maxSize: this.#cacheConfig.maxSize,
294
+ };
295
+ return health;
296
+ }
297
+ /**
298
+ * Start periodic cleanup timer to remove expired cache entries
299
+ * @private
300
+ */
301
+ #startCleanupTimer() {
302
+ // Clear any existing timer
303
+ if (this.#cleanupTimer) {
304
+ clearInterval(this.#cleanupTimer);
305
+ }
306
+ // Run cleanup every 60 seconds
307
+ this.#cleanupTimer = setInterval(() => {
308
+ this.#cleanupExpired();
309
+ }, 60000);
310
+ }
311
+ /**
312
+ * Clean up expired cache entries
313
+ * @private
314
+ */
315
+ #cleanupExpired() {
316
+ const now = Date.now();
317
+ const expiredKeys = [];
318
+ // Find expired entries
319
+ for (const [key, entry] of this.#queryCache.entries()) {
320
+ if (now - entry.timestamp > this.#cacheConfig.ttlMs) {
321
+ expiredKeys.push(key);
322
+ }
323
+ }
324
+ // Remove expired entries
325
+ for (const key of expiredKeys) {
326
+ this.#queryCache.delete(key);
327
+ }
328
+ if (expiredKeys.length > 0 &&
329
+ (process.env.YAMO_DEBUG === "true" || !this.#config.silent)) {
330
+ logger.debug({ count: expiredKeys.length }, "Cleaned up expired cache entries");
331
+ }
332
+ }
333
+ /**
334
+ * Dispose of resources (cleanup timer and cache)
335
+ * Call this when the MemoryContextManager is no longer needed
336
+ */
337
+ dispose() {
338
+ if (this.#cleanupTimer) {
339
+ clearInterval(this.#cleanupTimer);
340
+ this.#cleanupTimer = null;
341
+ }
342
+ this.clearCache();
343
+ }
344
+ }
345
+ export default MemoryContextManager;