snow-flow 2.0.4 → 2.0.5

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.
@@ -0,0 +1,364 @@
1
+ "use strict";
2
+ /**
3
+ * Snow-Flow Memory Client
4
+ * Simple API for agents to interact with the memory system
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.MemoryClient = void 0;
8
+ const logger_js_1 = require("../utils/logger.js");
9
+ const swarm_memory_js_1 = require("./swarm-memory.js");
10
+ const memory_operations_js_1 = require("./memory-operations.js");
11
+ /**
12
+ * Singleton instance management
13
+ */
14
+ let memoryInstance = null;
15
+ let operationsInstance = null;
16
+ class MemoryClient {
17
+ constructor(config = {}) {
18
+ this.logger = new logger_js_1.Logger('MemoryClient');
19
+ // Use singleton instances for memory and operations
20
+ if (!memoryInstance) {
21
+ memoryInstance = new swarm_memory_js_1.SwarmMemory(config);
22
+ }
23
+ if (!operationsInstance) {
24
+ operationsInstance = new memory_operations_js_1.MemoryOperations(memoryInstance);
25
+ }
26
+ this.memory = memoryInstance;
27
+ this.operations = operationsInstance;
28
+ // Set session and agent context
29
+ this.sessionId = config.sessionId || this.generateSessionId();
30
+ this.agentId = config.agentId || 'anonymous';
31
+ this.agentType = config.agentType || 'unknown';
32
+ this.logger.info('Memory client initialized', {
33
+ sessionId: this.sessionId,
34
+ agentId: this.agentId,
35
+ agentType: this.agentType
36
+ });
37
+ }
38
+ // ==================== Simple Context Storage ====================
39
+ /**
40
+ * Store data in shared context
41
+ */
42
+ async store(options) {
43
+ await this.operations.setContext(this.sessionId, options.key, options.value, this.agentId, options.expires, options.permissions);
44
+ }
45
+ /**
46
+ * Retrieve data from shared context with agent isolation
47
+ */
48
+ async retrieve(options) {
49
+ // CRITICAL FIX: Pass agent ID for proper memory isolation
50
+ const context = await this.operations.getContext(this.sessionId, options.key, this.agentId);
51
+ if (!context) {
52
+ return options.defaultValue !== undefined ? options.defaultValue : null;
53
+ }
54
+ return context.context_value;
55
+ }
56
+ /**
57
+ * Retrieve data from truly shared context (no agent isolation)
58
+ * Use this when agents need to access shared coordination data
59
+ */
60
+ async retrieveShared(options) {
61
+ // Try shared prefix first
62
+ const sharedKey = `__shared__::${options.key}`;
63
+ let context = await this.operations.getContext(this.sessionId, sharedKey);
64
+ // Fallback to original key for backward compatibility
65
+ if (!context) {
66
+ context = await this.operations.getContext(this.sessionId, options.key);
67
+ }
68
+ if (!context) {
69
+ return options.defaultValue !== undefined ? options.defaultValue : null;
70
+ }
71
+ return context.context_value;
72
+ }
73
+ /**
74
+ * Store data in truly shared context (no agent isolation)
75
+ * Use this when you want all agents to access the same data
76
+ */
77
+ async storeShared(options) {
78
+ // Use a special shared prefix to avoid conflicts with namespaced keys
79
+ const sharedKey = `__shared__::${options.key}`;
80
+ await this.operations.setContext(this.sessionId, sharedKey, options.value, this.agentId, // Still track who created it
81
+ options.expires, options.permissions);
82
+ }
83
+ /**
84
+ * Get all context for current session
85
+ */
86
+ async getSessionData() {
87
+ const contexts = await this.operations.getSessionContext(this.sessionId);
88
+ const data = {};
89
+ for (const context of contexts) {
90
+ data[context.context_key] = context.context_value;
91
+ }
92
+ return data;
93
+ }
94
+ // ==================== Agent Coordination ====================
95
+ /**
96
+ * Register current agent
97
+ */
98
+ async register(assignedTasks = []) {
99
+ await this.operations.registerAgent(this.sessionId, this.agentId, this.agentType, assignedTasks);
100
+ }
101
+ /**
102
+ * Update agent progress
103
+ */
104
+ async updateProgress(percentage, currentTool) {
105
+ await this.operations.updateAgentStatus(this.sessionId, this.agentId, {
106
+ status: 'active',
107
+ progress_percentage: percentage,
108
+ current_tool: currentTool
109
+ });
110
+ }
111
+ /**
112
+ * Mark agent as completed
113
+ */
114
+ async complete() {
115
+ await this.operations.updateAgentStatus(this.sessionId, this.agentId, {
116
+ status: 'completed',
117
+ progress_percentage: 100
118
+ });
119
+ }
120
+ /**
121
+ * Report agent error
122
+ */
123
+ async reportError(error) {
124
+ await this.operations.updateAgentStatus(this.sessionId, this.agentId, {
125
+ status: 'failed',
126
+ error_state: error
127
+ });
128
+ }
129
+ /**
130
+ * Check if agent should wait for dependencies
131
+ */
132
+ async checkDependencies() {
133
+ const satisfied = await this.operations.checkDependenciesSatisfied(this.sessionId, this.agentId);
134
+ if (!satisfied) {
135
+ await this.operations.updateAgentStatus(this.sessionId, this.agentId, {
136
+ status: 'blocked'
137
+ });
138
+ }
139
+ return satisfied;
140
+ }
141
+ // ==================== Artifact Management ====================
142
+ /**
143
+ * Store ServiceNow artifact information
144
+ */
145
+ async storeArtifact(artifact) {
146
+ await this.operations.storeArtifact({
147
+ sys_id: artifact.sys_id,
148
+ artifact_type: artifact.type,
149
+ name: artifact.name,
150
+ description: artifact.description,
151
+ created_by_agent: this.agentId,
152
+ session_id: this.sessionId,
153
+ deployment_status: artifact.status || 'created',
154
+ update_set_id: artifact.update_set_id,
155
+ dependencies: artifact.dependencies ? JSON.stringify(artifact.dependencies) : undefined,
156
+ metadata: artifact.metadata ? JSON.stringify(artifact.metadata) : undefined
157
+ });
158
+ }
159
+ /**
160
+ * Update artifact status
161
+ */
162
+ async updateArtifactStatus(sys_id, status) {
163
+ await this.operations.updateArtifactStatus(sys_id, status);
164
+ }
165
+ /**
166
+ * Find artifacts created in current session
167
+ */
168
+ async findSessionArtifacts(type) {
169
+ const artifacts = await this.operations.searchArtifacts({
170
+ session_id: this.sessionId,
171
+ artifact_type: type
172
+ });
173
+ return artifacts.map(a => ({
174
+ sys_id: a.sys_id,
175
+ type: a.artifact_type,
176
+ name: a.name,
177
+ description: a.description,
178
+ status: a.deployment_status,
179
+ update_set_id: a.update_set_id,
180
+ dependencies: a.dependencies ? JSON.parse(a.dependencies) : undefined,
181
+ metadata: a.metadata ? JSON.parse(a.metadata) : undefined
182
+ }));
183
+ }
184
+ // ==================== Agent Communication ====================
185
+ /**
186
+ * Send handoff to another agent
187
+ */
188
+ async handoff(handoff) {
189
+ await this.operations.sendMessage(this.sessionId, this.agentId, handoff.to_agent, 'handoff', handoff.data, handoff.artifact_reference);
190
+ }
191
+ /**
192
+ * Check for incoming handoffs
193
+ */
194
+ async checkHandoffs() {
195
+ const messages = await this.operations.getUnprocessedMessages(this.agentId, this.sessionId);
196
+ const handoffs = messages.filter(m => m.message_type === 'handoff');
197
+ const results = handoffs.map(h => ({
198
+ from: h.from_agent,
199
+ data: typeof h.content === 'string' ? JSON.parse(h.content) : h.content,
200
+ artifact_reference: h.artifact_reference
201
+ }));
202
+ // Mark messages as processed
203
+ for (const handoff of handoffs) {
204
+ await this.operations.markMessageProcessed(handoff.id);
205
+ }
206
+ return results;
207
+ }
208
+ /**
209
+ * Send status update
210
+ */
211
+ async sendStatus(status, details) {
212
+ await this.operations.sendMessage(this.sessionId, this.agentId, 'queen', // Always send status to Queen
213
+ 'status_update', { status, details });
214
+ }
215
+ /**
216
+ * Report dependency ready
217
+ */
218
+ async reportDependencyReady(dependent_agent, artifact_reference) {
219
+ await this.operations.sendMessage(this.sessionId, this.agentId, dependent_agent, 'dependency_ready', { ready: true }, artifact_reference);
220
+ // Also update dependency status
221
+ await this.operations.satisfyDependency(this.sessionId, dependent_agent, this.agentId);
222
+ }
223
+ // ==================== Performance Tracking ====================
224
+ /**
225
+ * Start tracking an operation
226
+ */
227
+ trackOperation(operation) {
228
+ const tracking = this.operations.startPerformanceTracking(this.sessionId, this.agentId, operation);
229
+ return {
230
+ complete: async (success, error, metadata) => {
231
+ await this.operations.completePerformanceTracking(tracking, this.sessionId, this.agentId, operation, success, error, metadata);
232
+ }
233
+ };
234
+ }
235
+ /**
236
+ * Get average performance for an operation
237
+ */
238
+ async getPerformanceStats(operation) {
239
+ const stats = await this.operations.getAveragePerformance(operation, this.sessionId);
240
+ if (!stats)
241
+ return null;
242
+ return {
243
+ avgDuration: stats.avg_duration_ms,
244
+ successRate: stats.success_rate,
245
+ totalOperations: stats.total_operations
246
+ };
247
+ }
248
+ // ==================== Deployment Tracking ====================
249
+ /**
250
+ * Record successful deployment
251
+ */
252
+ async recordDeployment(artifact_sys_id, type, success = true, error) {
253
+ await this.operations.recordDeployment(this.sessionId, artifact_sys_id, type, this.agentId, success, error, type === 'create' || type === 'update' // Rollback available for create/update
254
+ );
255
+ }
256
+ /**
257
+ * Get deployment history for an artifact
258
+ */
259
+ async getDeploymentHistory(artifact_sys_id) {
260
+ const history = await this.operations.getDeploymentHistory(artifact_sys_id);
261
+ return history.map(h => ({
262
+ type: h.deployment_type,
263
+ success: h.success,
264
+ time: new Date(h.deployment_time),
265
+ agent: h.agent_id,
266
+ error: h.error_details
267
+ }));
268
+ }
269
+ // ==================== Session Management ====================
270
+ /**
271
+ * Get current session ID
272
+ */
273
+ getSessionId() {
274
+ return this.sessionId;
275
+ }
276
+ /**
277
+ * Get current agent ID
278
+ */
279
+ getAgentId() {
280
+ return this.agentId;
281
+ }
282
+ /**
283
+ * Get complete session state
284
+ */
285
+ async getSessionState() {
286
+ return this.operations.getSessionState(this.sessionId);
287
+ }
288
+ /**
289
+ * Clean up current session
290
+ */
291
+ async cleanup() {
292
+ await this.operations.cleanupSession(this.sessionId);
293
+ }
294
+ // ==================== Analytics ====================
295
+ /**
296
+ * Get memory statistics
297
+ */
298
+ getStats() {
299
+ return this.memory.getStats();
300
+ }
301
+ /**
302
+ * Run memory cleanup
303
+ */
304
+ async runCleanup() {
305
+ this.memory.cleanup();
306
+ }
307
+ // ==================== Raw Access ====================
308
+ /**
309
+ * Get direct access to operations (for advanced use cases)
310
+ */
311
+ getOperations() {
312
+ return this.operations;
313
+ }
314
+ /**
315
+ * Get direct access to database (for custom queries)
316
+ */
317
+ getDatabase() {
318
+ return this.memory;
319
+ }
320
+ // ==================== Static Methods ====================
321
+ /**
322
+ * Create a memory client for an agent
323
+ */
324
+ static forAgent(agentId, agentType, sessionId) {
325
+ return new MemoryClient({
326
+ agentId,
327
+ agentType,
328
+ sessionId
329
+ });
330
+ }
331
+ /**
332
+ * Create a memory client for a session
333
+ */
334
+ static forSession(sessionId) {
335
+ return new MemoryClient({ sessionId });
336
+ }
337
+ /**
338
+ * Close all connections (call when shutting down)
339
+ */
340
+ static shutdown() {
341
+ if (memoryInstance) {
342
+ memoryInstance.close();
343
+ memoryInstance = null;
344
+ operationsInstance = null;
345
+ }
346
+ }
347
+ // ==================== Private Methods ====================
348
+ generateSessionId() {
349
+ return `session_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
350
+ }
351
+ /**
352
+ * COMPATIBILITY FIX: makeRequest method for phantom calls
353
+ * MemoryClient doesn't use HTTP requests, so this is a no-op fallback
354
+ */
355
+ async makeRequest(config) {
356
+ console.log('🔧 MemoryClient.makeRequest called with config:', config);
357
+ console.log('🔧 WARNING: MemoryClient does not support HTTP requests');
358
+ // Since MemoryClient doesn't do HTTP requests, we should throw an error
359
+ // to help identify which code is incorrectly trying to use this client for HTTP
360
+ throw new Error('🔧 MemoryClient does not support HTTP requests (makeRequest called incorrectly)');
361
+ }
362
+ }
363
+ exports.MemoryClient = MemoryClient;
364
+ //# sourceMappingURL=memory-client.js.map
@@ -0,0 +1,29 @@
1
+ import { MemoryEntry } from '../types/index.js';
2
+ export declare class MemoryManager {
3
+ private static instance;
4
+ private memoryDir;
5
+ private cache;
6
+ private initialized;
7
+ private constructor();
8
+ static getInstance(): MemoryManager;
9
+ initialize(): Promise<void>;
10
+ private loadCache;
11
+ store(key: string, value: any, namespace?: string, ttl?: number): Promise<void>;
12
+ get(key: string, namespace?: string): Promise<any>;
13
+ list(namespace?: string): Promise<MemoryEntry[]>;
14
+ search(pattern: string, namespace?: string): Promise<MemoryEntry[]>;
15
+ delete(key: string, namespace?: string): Promise<void>;
16
+ clear(namespace?: string): Promise<void>;
17
+ export(filePath: string, namespace?: string): Promise<void>;
18
+ import(filePath: string, overwrite?: boolean): Promise<void>;
19
+ stats(): Promise<{
20
+ totalEntries: number;
21
+ namespaces: string[];
22
+ totalSize: number;
23
+ oldestEntry?: Date;
24
+ newestEntry?: Date;
25
+ }>;
26
+ cleanup(): Promise<number>;
27
+ }
28
+ export declare const memoryManager: MemoryManager;
29
+ //# sourceMappingURL=memory-manager.d.ts.map
@@ -0,0 +1,280 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.memoryManager = exports.MemoryManager = void 0;
7
+ const fs_extra_1 = __importDefault(require("fs-extra"));
8
+ const path_1 = require("path");
9
+ const config_js_1 = require("../utils/config.js");
10
+ const logger_js_1 = require("../utils/logger.js");
11
+ class MemoryManager {
12
+ constructor() {
13
+ this.cache = new Map();
14
+ this.initialized = false;
15
+ const memoryConfig = config_js_1.configManager.get('memory');
16
+ this.memoryDir = memoryConfig?.storageDir || (0, path_1.join)(process.cwd(), '.snow-flow-memory');
17
+ }
18
+ static getInstance() {
19
+ if (!MemoryManager.instance) {
20
+ MemoryManager.instance = new MemoryManager();
21
+ }
22
+ return MemoryManager.instance;
23
+ }
24
+ // Initialize memory storage
25
+ async initialize() {
26
+ if (this.initialized)
27
+ return;
28
+ try {
29
+ await fs_extra_1.default.ensureDir(this.memoryDir);
30
+ await this.loadCache();
31
+ this.initialized = true;
32
+ logger_js_1.logger.debug(`Memory manager initialized at ${this.memoryDir}`);
33
+ }
34
+ catch (error) {
35
+ logger_js_1.logger.error('Failed to initialize memory manager', error);
36
+ throw error;
37
+ }
38
+ }
39
+ // Load memory entries into cache
40
+ async loadCache() {
41
+ try {
42
+ const files = await fs_extra_1.default.readdir(this.memoryDir);
43
+ for (const file of files) {
44
+ if (file.endsWith('.json')) {
45
+ const filePath = (0, path_1.join)(this.memoryDir, file);
46
+ const entry = await fs_extra_1.default.readJson(filePath);
47
+ // Check if entry has expired
48
+ if (entry.expiresAt && new Date(entry.expiresAt) < new Date()) {
49
+ await fs_extra_1.default.remove(filePath);
50
+ continue;
51
+ }
52
+ this.cache.set(entry.key, entry);
53
+ }
54
+ }
55
+ logger_js_1.logger.debug(`Loaded ${this.cache.size} memory entries`);
56
+ }
57
+ catch (error) {
58
+ logger_js_1.logger.error('Failed to load memory cache', error);
59
+ }
60
+ }
61
+ // Store data in memory
62
+ async store(key, value, namespace = 'default', ttl) {
63
+ await this.initialize();
64
+ const entry = {
65
+ key,
66
+ value,
67
+ namespace,
68
+ createdAt: new Date(),
69
+ expiresAt: ttl ? new Date(Date.now() + ttl) : undefined
70
+ };
71
+ // Save to cache
72
+ this.cache.set(key, entry);
73
+ // Persist to disk
74
+ const filename = `${namespace}_${key.replace(/[^a-zA-Z0-9-_]/g, '_')}.json`;
75
+ const filePath = (0, path_1.join)(this.memoryDir, filename);
76
+ try {
77
+ await fs_extra_1.default.writeJson(filePath, entry, { spaces: 2 });
78
+ logger_js_1.logger.success(`Stored memory entry: ${key}`);
79
+ }
80
+ catch (error) {
81
+ logger_js_1.logger.error(`Failed to store memory entry: ${key}`, error);
82
+ throw error;
83
+ }
84
+ }
85
+ // Retrieve data from memory
86
+ async get(key, namespace = 'default') {
87
+ await this.initialize();
88
+ // Check cache first
89
+ const entry = this.cache.get(key);
90
+ if (entry) {
91
+ // Check if expired
92
+ if (entry.expiresAt && new Date(entry.expiresAt) < new Date()) {
93
+ await this.delete(key, namespace);
94
+ return null;
95
+ }
96
+ if (entry.namespace === namespace) {
97
+ return entry.value;
98
+ }
99
+ }
100
+ // Try loading from disk if not in cache
101
+ const filename = `${namespace}_${key.replace(/[^a-zA-Z0-9-_]/g, '_')}.json`;
102
+ const filePath = (0, path_1.join)(this.memoryDir, filename);
103
+ try {
104
+ if (await fs_extra_1.default.pathExists(filePath)) {
105
+ const entry = await fs_extra_1.default.readJson(filePath);
106
+ // Check if expired
107
+ if (entry.expiresAt && new Date(entry.expiresAt) < new Date()) {
108
+ await fs_extra_1.default.remove(filePath);
109
+ return null;
110
+ }
111
+ // Update cache
112
+ this.cache.set(key, entry);
113
+ return entry.value;
114
+ }
115
+ }
116
+ catch (error) {
117
+ logger_js_1.logger.error(`Failed to retrieve memory entry: ${key}`, error);
118
+ }
119
+ return null;
120
+ }
121
+ // List all memory entries
122
+ async list(namespace) {
123
+ await this.initialize();
124
+ const entries = [];
125
+ for (const entry of this.cache.values()) {
126
+ // Skip expired entries
127
+ if (entry.expiresAt && new Date(entry.expiresAt) < new Date()) {
128
+ continue;
129
+ }
130
+ // Filter by namespace if provided
131
+ if (!namespace || entry.namespace === namespace) {
132
+ entries.push(entry);
133
+ }
134
+ }
135
+ return entries.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
136
+ }
137
+ // Search memory entries
138
+ async search(pattern, namespace) {
139
+ await this.initialize();
140
+ const regex = new RegExp(pattern, 'i');
141
+ const entries = [];
142
+ for (const entry of this.cache.values()) {
143
+ // Skip expired entries
144
+ if (entry.expiresAt && new Date(entry.expiresAt) < new Date()) {
145
+ continue;
146
+ }
147
+ // Filter by namespace if provided
148
+ if (namespace && entry.namespace !== namespace) {
149
+ continue;
150
+ }
151
+ // Search in key and value
152
+ if (regex.test(entry.key) ||
153
+ regex.test(JSON.stringify(entry.value))) {
154
+ entries.push(entry);
155
+ }
156
+ }
157
+ return entries.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
158
+ }
159
+ // Delete memory entry
160
+ async delete(key, namespace = 'default') {
161
+ await this.initialize();
162
+ // Remove from cache
163
+ this.cache.delete(key);
164
+ // Remove from disk
165
+ const filename = `${namespace}_${key.replace(/[^a-zA-Z0-9-_]/g, '_')}.json`;
166
+ const filePath = (0, path_1.join)(this.memoryDir, filename);
167
+ try {
168
+ await fs_extra_1.default.remove(filePath);
169
+ logger_js_1.logger.success(`Deleted memory entry: ${key}`);
170
+ }
171
+ catch (error) {
172
+ logger_js_1.logger.error(`Failed to delete memory entry: ${key}`, error);
173
+ }
174
+ }
175
+ // Clear all memory entries
176
+ async clear(namespace) {
177
+ await this.initialize();
178
+ if (namespace) {
179
+ // Clear specific namespace
180
+ const entries = await this.list(namespace);
181
+ for (const entry of entries) {
182
+ await this.delete(entry.key, namespace);
183
+ }
184
+ }
185
+ else {
186
+ // Clear all
187
+ this.cache.clear();
188
+ await fs_extra_1.default.emptyDir(this.memoryDir);
189
+ logger_js_1.logger.success('Cleared all memory entries');
190
+ }
191
+ }
192
+ // Export memory to file
193
+ async export(filePath, namespace) {
194
+ await this.initialize();
195
+ const entries = await this.list(namespace);
196
+ const exportData = {
197
+ exported: new Date().toISOString(),
198
+ namespace: namespace || 'all',
199
+ entries
200
+ };
201
+ try {
202
+ await fs_extra_1.default.writeJson(filePath, exportData, { spaces: 2 });
203
+ logger_js_1.logger.success(`Exported ${entries.length} memory entries to ${filePath}`);
204
+ }
205
+ catch (error) {
206
+ logger_js_1.logger.error('Failed to export memory', error);
207
+ throw error;
208
+ }
209
+ }
210
+ // Import memory from file
211
+ async import(filePath, overwrite = false) {
212
+ await this.initialize();
213
+ try {
214
+ const importData = await fs_extra_1.default.readJson(filePath);
215
+ if (!importData.entries || !Array.isArray(importData.entries)) {
216
+ throw new Error('Invalid import file format');
217
+ }
218
+ let imported = 0;
219
+ for (const entry of importData.entries) {
220
+ const existing = await this.get(entry.key, entry.namespace);
221
+ if (!existing || overwrite) {
222
+ await this.store(entry.key, entry.value, entry.namespace, entry.ttl);
223
+ imported++;
224
+ }
225
+ }
226
+ logger_js_1.logger.success(`Imported ${imported} memory entries from ${filePath}`);
227
+ }
228
+ catch (error) {
229
+ logger_js_1.logger.error('Failed to import memory', error);
230
+ throw error;
231
+ }
232
+ }
233
+ // Get memory statistics
234
+ async stats() {
235
+ await this.initialize();
236
+ const entries = await this.list();
237
+ const namespaces = [...new Set(entries.map(e => e.namespace))];
238
+ let totalSize = 0;
239
+ let oldestEntry;
240
+ let newestEntry;
241
+ for (const entry of entries) {
242
+ const size = JSON.stringify(entry).length;
243
+ totalSize += size;
244
+ const createdAt = new Date(entry.createdAt);
245
+ if (!oldestEntry || createdAt < oldestEntry) {
246
+ oldestEntry = createdAt;
247
+ }
248
+ if (!newestEntry || createdAt > newestEntry) {
249
+ newestEntry = createdAt;
250
+ }
251
+ }
252
+ return {
253
+ totalEntries: entries.length,
254
+ namespaces,
255
+ totalSize,
256
+ oldestEntry,
257
+ newestEntry
258
+ };
259
+ }
260
+ // Cleanup expired entries
261
+ async cleanup() {
262
+ await this.initialize();
263
+ let cleaned = 0;
264
+ const now = new Date();
265
+ for (const [key, entry] of this.cache.entries()) {
266
+ if (entry.expiresAt && new Date(entry.expiresAt) < now) {
267
+ await this.delete(key, entry.namespace);
268
+ cleaned++;
269
+ }
270
+ }
271
+ if (cleaned > 0) {
272
+ logger_js_1.logger.success(`Cleaned up ${cleaned} expired memory entries`);
273
+ }
274
+ return cleaned;
275
+ }
276
+ }
277
+ exports.MemoryManager = MemoryManager;
278
+ // Export singleton instance
279
+ exports.memoryManager = MemoryManager.getInstance();
280
+ //# sourceMappingURL=memory-manager.js.map