@sowonai/crewx-cli 0.8.0-rc.1 → 0.8.0-rc.3

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.
@@ -1,707 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
19
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
20
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
21
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
22
- return c > 3 && r && Object.defineProperty(target, key, r), r;
23
- };
24
- var __importStar = (this && this.__importStar) || (function () {
25
- var ownKeys = function(o) {
26
- ownKeys = Object.getOwnPropertyNames || function (o) {
27
- var ar = [];
28
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
29
- return ar;
30
- };
31
- return ownKeys(o);
32
- };
33
- return function (mod) {
34
- if (mod && mod.__esModule) return mod;
35
- var result = {};
36
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
37
- __setModuleDefault(result, mod);
38
- return result;
39
- };
40
- })();
41
- var __metadata = (this && this.__metadata) || function (k, v) {
42
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
43
- };
44
- var MemoryService_1;
45
- Object.defineProperty(exports, "__esModule", { value: true });
46
- exports.MemoryService = exports.MemoryType = void 0;
47
- const common_1 = require("@nestjs/common");
48
- const path = __importStar(require("path"));
49
- const fs = __importStar(require("fs"));
50
- var MemoryType;
51
- (function (MemoryType) {
52
- MemoryType["FACT"] = "fact";
53
- MemoryType["PREFERENCE"] = "preference";
54
- MemoryType["CONTEXT"] = "context";
55
- MemoryType["SUMMARY"] = "summary";
56
- MemoryType["TASK"] = "task";
57
- MemoryType["CUSTOM"] = "custom";
58
- })(MemoryType || (exports.MemoryType = MemoryType = {}));
59
- let MemoryService = MemoryService_1 = class MemoryService {
60
- constructor() {
61
- this.logger = new common_1.Logger(MemoryService_1.name);
62
- this.db = null;
63
- this.initialized = false;
64
- const homeDir = process.env.HOME || process.env.USERPROFILE || '.';
65
- const crewxDir = path.join(homeDir, '.crewx');
66
- this.dbPath = path.join(crewxDir, 'memory.db');
67
- }
68
- async ensureInitialized() {
69
- if (this.initialized) {
70
- return true;
71
- }
72
- try {
73
- const Database = await this.loadBetterSqlite3();
74
- if (!Database) {
75
- this.logger.warn('better-sqlite3 not available, memory service disabled');
76
- return false;
77
- }
78
- const dir = path.dirname(this.dbPath);
79
- if (!fs.existsSync(dir)) {
80
- fs.mkdirSync(dir, { recursive: true });
81
- }
82
- this.db = new Database(this.dbPath);
83
- this.db.pragma('journal_mode = WAL');
84
- this.db.pragma('synchronous = NORMAL');
85
- this.db.pragma('cache_size = -64000');
86
- this.db.pragma('temp_store = MEMORY');
87
- this.createTables();
88
- this.initialized = true;
89
- this.logger.log(`Memory database initialized at ${this.dbPath}`);
90
- return true;
91
- }
92
- catch (error) {
93
- this.logger.warn(`Failed to initialize memory database: ${error instanceof Error ? error.message : String(error)}`);
94
- return false;
95
- }
96
- }
97
- async loadBetterSqlite3() {
98
- try {
99
- return require('better-sqlite3');
100
- }
101
- catch {
102
- return null;
103
- }
104
- }
105
- createTables() {
106
- this.db.exec(`
107
- CREATE TABLE IF NOT EXISTS memories (
108
- id TEXT PRIMARY KEY,
109
- type TEXT NOT NULL,
110
- agent_id TEXT,
111
- session_id TEXT,
112
- content TEXT NOT NULL,
113
- embedding BLOB,
114
- metadata TEXT,
115
- tags TEXT,
116
- importance REAL DEFAULT 0.5,
117
- created_at INTEGER NOT NULL,
118
- updated_at INTEGER NOT NULL,
119
- expires_at INTEGER
120
- );
121
-
122
- CREATE INDEX IF NOT EXISTS idx_memories_type ON memories(type);
123
- CREATE INDEX IF NOT EXISTS idx_memories_agent_id ON memories(agent_id);
124
- CREATE INDEX IF NOT EXISTS idx_memories_session_id ON memories(session_id);
125
- CREATE INDEX IF NOT EXISTS idx_memories_importance ON memories(importance);
126
- CREATE INDEX IF NOT EXISTS idx_memories_created_at ON memories(created_at);
127
- CREATE INDEX IF NOT EXISTS idx_memories_expires_at ON memories(expires_at);
128
- `);
129
- this.db.exec(`
130
- CREATE VIRTUAL TABLE IF NOT EXISTS memories_fts USING fts5(
131
- id UNINDEXED,
132
- content,
133
- tags,
134
- content='memories',
135
- content_rowid='rowid',
136
- tokenize='porter unicode61'
137
- );
138
- `);
139
- this.db.exec(`
140
- CREATE TRIGGER IF NOT EXISTS memories_ai AFTER INSERT ON memories BEGIN
141
- INSERT INTO memories_fts(rowid, id, content, tags)
142
- VALUES (new.rowid, new.id, new.content, new.tags);
143
- END;
144
-
145
- CREATE TRIGGER IF NOT EXISTS memories_ad AFTER DELETE ON memories BEGIN
146
- INSERT INTO memories_fts(memories_fts, rowid, id, content, tags)
147
- VALUES ('delete', old.rowid, old.id, old.content, old.tags);
148
- END;
149
-
150
- CREATE TRIGGER IF NOT EXISTS memories_au AFTER UPDATE ON memories BEGIN
151
- INSERT INTO memories_fts(memories_fts, rowid, id, content, tags)
152
- VALUES ('delete', old.rowid, old.id, old.content, old.tags);
153
- INSERT INTO memories_fts(rowid, id, content, tags)
154
- VALUES (new.rowid, new.id, new.content, new.tags);
155
- END;
156
- `);
157
- this.db.exec(`
158
- CREATE TABLE IF NOT EXISTS memory_tags (
159
- memory_id TEXT NOT NULL,
160
- tag TEXT NOT NULL,
161
- PRIMARY KEY (memory_id, tag),
162
- FOREIGN KEY (memory_id) REFERENCES memories(id) ON DELETE CASCADE
163
- );
164
-
165
- CREATE INDEX IF NOT EXISTS idx_memory_tags_tag ON memory_tags(tag);
166
- `);
167
- }
168
- generateId() {
169
- const timestamp = Date.now().toString(36);
170
- const randomPart = Math.random().toString(36).substring(2, 10);
171
- return `mem_${timestamp}_${randomPart}`;
172
- }
173
- async create(input) {
174
- if (!(await this.ensureInitialized())) {
175
- return null;
176
- }
177
- const id = this.generateId();
178
- const now = Date.now();
179
- const tagsJson = input.tags ? JSON.stringify(input.tags) : null;
180
- try {
181
- const stmt = this.db.prepare(`
182
- INSERT INTO memories (
183
- id, type, agent_id, session_id, content, metadata, tags, importance, created_at, updated_at, expires_at
184
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
185
- `);
186
- stmt.run(id, input.type, input.agentId || null, input.sessionId || null, input.content, input.metadata ? JSON.stringify(input.metadata) : null, tagsJson, input.importance ?? 0.5, now, now, input.expiresAt || null);
187
- if (input.tags && input.tags.length > 0) {
188
- const tagStmt = this.db.prepare('INSERT INTO memory_tags (memory_id, tag) VALUES (?, ?)');
189
- for (const tag of input.tags) {
190
- tagStmt.run(id, tag);
191
- }
192
- }
193
- this.logger.debug(`Created memory: ${id}`);
194
- return {
195
- id,
196
- type: input.type,
197
- agentId: input.agentId,
198
- sessionId: input.sessionId,
199
- content: input.content,
200
- metadata: input.metadata,
201
- tags: input.tags,
202
- importance: input.importance ?? 0.5,
203
- createdAt: now,
204
- updatedAt: now,
205
- expiresAt: input.expiresAt,
206
- };
207
- }
208
- catch (error) {
209
- this.logger.error(`Failed to create memory: ${error instanceof Error ? error.message : String(error)}`);
210
- return null;
211
- }
212
- }
213
- async get(id) {
214
- if (!(await this.ensureInitialized())) {
215
- return null;
216
- }
217
- try {
218
- const stmt = this.db.prepare('SELECT * FROM memories WHERE id = ?');
219
- const row = stmt.get(id);
220
- if (!row) {
221
- return null;
222
- }
223
- return this.rowToMemory(row);
224
- }
225
- catch (error) {
226
- this.logger.error(`Failed to get memory: ${error instanceof Error ? error.message : String(error)}`);
227
- return null;
228
- }
229
- }
230
- async update(id, input) {
231
- if (!(await this.ensureInitialized())) {
232
- return null;
233
- }
234
- try {
235
- const updates = [];
236
- const params = [];
237
- if (input.content !== undefined) {
238
- updates.push('content = ?');
239
- params.push(input.content);
240
- }
241
- if (input.metadata !== undefined) {
242
- updates.push('metadata = ?');
243
- params.push(JSON.stringify(input.metadata));
244
- }
245
- if (input.tags !== undefined) {
246
- updates.push('tags = ?');
247
- params.push(JSON.stringify(input.tags));
248
- }
249
- if (input.importance !== undefined) {
250
- updates.push('importance = ?');
251
- params.push(input.importance);
252
- }
253
- if (input.expiresAt !== undefined) {
254
- updates.push('expires_at = ?');
255
- params.push(input.expiresAt);
256
- }
257
- if (updates.length === 0) {
258
- return this.get(id);
259
- }
260
- const now = Date.now();
261
- updates.push('updated_at = ?');
262
- params.push(now);
263
- params.push(id);
264
- const stmt = this.db.prepare(`
265
- UPDATE memories SET ${updates.join(', ')} WHERE id = ?
266
- `);
267
- const result = stmt.run(...params);
268
- if (result.changes === 0) {
269
- return null;
270
- }
271
- if (input.tags !== undefined) {
272
- this.db.prepare('DELETE FROM memory_tags WHERE memory_id = ?').run(id);
273
- if (input.tags.length > 0) {
274
- const tagStmt = this.db.prepare('INSERT INTO memory_tags (memory_id, tag) VALUES (?, ?)');
275
- for (const tag of input.tags) {
276
- tagStmt.run(id, tag);
277
- }
278
- }
279
- }
280
- this.logger.debug(`Updated memory: ${id}`);
281
- return this.get(id);
282
- }
283
- catch (error) {
284
- this.logger.error(`Failed to update memory: ${error instanceof Error ? error.message : String(error)}`);
285
- return null;
286
- }
287
- }
288
- async delete(id) {
289
- if (!(await this.ensureInitialized())) {
290
- return false;
291
- }
292
- try {
293
- const stmt = this.db.prepare('DELETE FROM memories WHERE id = ?');
294
- const result = stmt.run(id);
295
- if (result.changes > 0) {
296
- this.logger.debug(`Deleted memory: ${id}`);
297
- return true;
298
- }
299
- return false;
300
- }
301
- catch (error) {
302
- this.logger.error(`Failed to delete memory: ${error instanceof Error ? error.message : String(error)}`);
303
- return false;
304
- }
305
- }
306
- async query(options = {}) {
307
- if (!(await this.ensureInitialized())) {
308
- return [];
309
- }
310
- try {
311
- const conditions = [];
312
- const params = [];
313
- if (options.type) {
314
- conditions.push('type = ?');
315
- params.push(options.type);
316
- }
317
- if (options.agentId) {
318
- conditions.push('agent_id = ?');
319
- params.push(options.agentId);
320
- }
321
- if (options.sessionId) {
322
- conditions.push('session_id = ?');
323
- params.push(options.sessionId);
324
- }
325
- if (options.createdAtFrom !== undefined) {
326
- conditions.push('created_at >= ?');
327
- params.push(options.createdAtFrom);
328
- }
329
- if (options.createdAtTo !== undefined) {
330
- conditions.push('created_at <= ?');
331
- params.push(options.createdAtTo);
332
- }
333
- if (options.minImportance !== undefined) {
334
- conditions.push('importance >= ?');
335
- params.push(options.minImportance);
336
- }
337
- conditions.push('(expires_at IS NULL OR expires_at > ?)');
338
- params.push(Date.now());
339
- if (options.tags && options.tags.length > 0) {
340
- conditions.push(`
341
- id IN (
342
- SELECT memory_id FROM memory_tags
343
- WHERE tag IN (${options.tags.map(() => '?').join(', ')})
344
- GROUP BY memory_id
345
- HAVING COUNT(DISTINCT tag) = ?
346
- )
347
- `);
348
- params.push(...options.tags, options.tags.length);
349
- }
350
- const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';
351
- const orderBy = options.orderBy || 'createdAt';
352
- const orderDir = options.orderDir || 'desc';
353
- const orderColumn = orderBy === 'createdAt' ? 'created_at'
354
- : orderBy === 'updatedAt' ? 'updated_at'
355
- : 'importance';
356
- const limit = options.limit || 100;
357
- const offset = options.offset || 0;
358
- const stmt = this.db.prepare(`
359
- SELECT * FROM memories
360
- ${whereClause}
361
- ORDER BY ${orderColumn} ${orderDir.toUpperCase()}
362
- LIMIT ? OFFSET ?
363
- `);
364
- params.push(limit, offset);
365
- const rows = stmt.all(...params);
366
- return rows.map((row) => this.rowToMemory(row));
367
- }
368
- catch (error) {
369
- this.logger.error(`Failed to query memories: ${error instanceof Error ? error.message : String(error)}`);
370
- return [];
371
- }
372
- }
373
- async search(query, options = {}) {
374
- if (!(await this.ensureInitialized())) {
375
- return [];
376
- }
377
- if (!query.trim()) {
378
- return [];
379
- }
380
- try {
381
- const conditions = [];
382
- const params = [];
383
- if (options.type) {
384
- conditions.push('m.type = ?');
385
- params.push(options.type);
386
- }
387
- if (options.agentId) {
388
- conditions.push('m.agent_id = ?');
389
- params.push(options.agentId);
390
- }
391
- if (options.sessionId) {
392
- conditions.push('m.session_id = ?');
393
- params.push(options.sessionId);
394
- }
395
- if (options.createdAtFrom !== undefined) {
396
- conditions.push('m.created_at >= ?');
397
- params.push(options.createdAtFrom);
398
- }
399
- if (options.createdAtTo !== undefined) {
400
- conditions.push('m.created_at <= ?');
401
- params.push(options.createdAtTo);
402
- }
403
- if (options.minImportance !== undefined) {
404
- conditions.push('m.importance >= ?');
405
- params.push(options.minImportance);
406
- }
407
- conditions.push('(m.expires_at IS NULL OR m.expires_at > ?)');
408
- params.push(Date.now());
409
- const additionalWhere = conditions.length > 0 ? `AND ${conditions.join(' AND ')}` : '';
410
- const limit = options.limit || 50;
411
- const offset = options.offset || 0;
412
- const stmt = this.db.prepare(`
413
- SELECT m.*, fts.rank as score,
414
- snippet(memories_fts, 1, '<mark>', '</mark>', '...', 32) as highlight
415
- FROM memories_fts fts
416
- JOIN memories m ON fts.id = m.id
417
- WHERE memories_fts MATCH ?
418
- ${additionalWhere}
419
- ORDER BY fts.rank
420
- LIMIT ? OFFSET ?
421
- `);
422
- const searchParams = [query, ...params, limit, offset];
423
- const rows = stmt.all(...searchParams);
424
- return rows.map((row) => ({
425
- ...this.rowToMemory(row),
426
- score: Math.abs(row.score),
427
- highlights: row.highlight ? [row.highlight] : undefined,
428
- }));
429
- }
430
- catch (error) {
431
- this.logger.error(`Failed to search memories: ${error instanceof Error ? error.message : String(error)}`);
432
- return [];
433
- }
434
- }
435
- async getByTags(tags, options = {}) {
436
- if (!(await this.ensureInitialized())) {
437
- return [];
438
- }
439
- if (!tags || tags.length === 0) {
440
- return [];
441
- }
442
- try {
443
- const placeholders = tags.map(() => '?').join(', ');
444
- const matchAll = options.matchAll ?? true;
445
- let sql;
446
- if (matchAll) {
447
- sql = `
448
- SELECT m.* FROM memories m
449
- JOIN memory_tags mt ON m.id = mt.memory_id
450
- WHERE mt.tag IN (${placeholders})
451
- AND (m.expires_at IS NULL OR m.expires_at > ?)
452
- GROUP BY m.id
453
- HAVING COUNT(DISTINCT mt.tag) = ?
454
- ORDER BY m.importance DESC, m.created_at DESC
455
- `;
456
- }
457
- else {
458
- sql = `
459
- SELECT DISTINCT m.* FROM memories m
460
- JOIN memory_tags mt ON m.id = mt.memory_id
461
- WHERE mt.tag IN (${placeholders})
462
- AND (m.expires_at IS NULL OR m.expires_at > ?)
463
- ORDER BY m.importance DESC, m.created_at DESC
464
- `;
465
- }
466
- const stmt = this.db.prepare(sql);
467
- const params = matchAll
468
- ? [...tags, Date.now(), tags.length]
469
- : [...tags, Date.now()];
470
- const rows = stmt.all(...params);
471
- return rows.map((row) => this.rowToMemory(row));
472
- }
473
- catch (error) {
474
- this.logger.error(`Failed to get memories by tags: ${error instanceof Error ? error.message : String(error)}`);
475
- return [];
476
- }
477
- }
478
- async getAllTags() {
479
- if (!(await this.ensureInitialized())) {
480
- return [];
481
- }
482
- try {
483
- const stmt = this.db.prepare('SELECT DISTINCT tag FROM memory_tags ORDER BY tag');
484
- const rows = stmt.all();
485
- return rows.map((row) => row.tag);
486
- }
487
- catch (error) {
488
- this.logger.error(`Failed to get all tags: ${error instanceof Error ? error.message : String(error)}`);
489
- return [];
490
- }
491
- }
492
- async deleteExpired() {
493
- if (!(await this.ensureInitialized())) {
494
- return 0;
495
- }
496
- try {
497
- const now = Date.now();
498
- const stmt = this.db.prepare('DELETE FROM memories WHERE expires_at IS NOT NULL AND expires_at <= ?');
499
- const result = stmt.run(now);
500
- if (result.changes > 0) {
501
- this.logger.log(`Deleted ${result.changes} expired memories`);
502
- }
503
- return result.changes;
504
- }
505
- catch (error) {
506
- this.logger.error(`Failed to delete expired memories: ${error instanceof Error ? error.message : String(error)}`);
507
- return 0;
508
- }
509
- }
510
- async getStats(options = {}) {
511
- if (!(await this.ensureInitialized())) {
512
- return { total: 0, byType: {}, tagCount: 0, avgImportance: 0 };
513
- }
514
- try {
515
- const agentCondition = options.agentId ? 'WHERE agent_id = ?' : '';
516
- const params = options.agentId ? [options.agentId] : [];
517
- const totalStmt = this.db.prepare(`SELECT COUNT(*) as count FROM memories ${agentCondition}`);
518
- const total = totalStmt.get(...params).count;
519
- const typeStmt = this.db.prepare(`
520
- SELECT type, COUNT(*) as count
521
- FROM memories ${agentCondition}
522
- GROUP BY type
523
- `);
524
- const typeRows = typeStmt.all(...params);
525
- const byType = typeRows.reduce((acc, row) => {
526
- acc[row.type] = row.count;
527
- return acc;
528
- }, {});
529
- const tagStmt = this.db.prepare('SELECT COUNT(DISTINCT tag) as count FROM memory_tags');
530
- const tagCount = tagStmt.get().count;
531
- const avgStmt = this.db.prepare(`SELECT AVG(importance) as avg FROM memories ${agentCondition}`);
532
- const avgImportance = avgStmt.get(...params)?.avg || 0;
533
- return { total, byType, tagCount, avgImportance };
534
- }
535
- catch (error) {
536
- this.logger.error(`Failed to get stats: ${error instanceof Error ? error.message : String(error)}`);
537
- return { total: 0, byType: {}, tagCount: 0, avgImportance: 0 };
538
- }
539
- }
540
- async consolidate(options) {
541
- if (!(await this.ensureInitialized())) {
542
- return { months: 0, summarized: 0, deleted: 0, summaryIds: [] };
543
- }
544
- const windowDays = options.windowDays ?? 180;
545
- const maxEntriesPerMonth = options.maxEntriesPerMonth ?? 20;
546
- const cutoff = Date.now() - windowDays * 24 * 60 * 60 * 1000;
547
- const rows = this.db.prepare(`
548
- SELECT * FROM memories
549
- WHERE agent_id = ?
550
- AND type != ?
551
- AND created_at < ?
552
- AND (expires_at IS NULL OR expires_at > ?)
553
- ORDER BY created_at ASC
554
- `).all(options.agentId, MemoryType.SUMMARY, cutoff, Date.now());
555
- if (!rows || rows.length === 0) {
556
- return { months: 0, summarized: 0, deleted: 0, summaryIds: [] };
557
- }
558
- const byMonth = new Map();
559
- for (const row of rows) {
560
- const monthKey = new Date(row.created_at).toISOString().slice(0, 7);
561
- const bucket = byMonth.get(monthKey) ?? [];
562
- bucket.push(row);
563
- byMonth.set(monthKey, bucket);
564
- }
565
- const insertStmt = this.db.prepare(`
566
- INSERT INTO memories (
567
- id, type, agent_id, session_id, content, metadata, tags, importance, created_at, updated_at, expires_at
568
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
569
- `);
570
- const insertTagStmt = this.db.prepare('INSERT INTO memory_tags (memory_id, tag) VALUES (?, ?)');
571
- const deleteStmt = this.db.prepare('DELETE FROM memories WHERE id = ?');
572
- const summaryIds = [];
573
- let deleted = 0;
574
- const now = Date.now();
575
- const consolidateTransaction = this.db.transaction(() => {
576
- for (const [month, monthRows] of byMonth.entries()) {
577
- const total = monthRows.length;
578
- const samples = monthRows.slice(0, maxEntriesPerMonth).map((r) => {
579
- const content = String(r.content ?? '').replace(/\s+/g, ' ').trim();
580
- const preview = content.length > 160 ? `${content.slice(0, 157)}...` : content;
581
- return `- [${r.type}] ${preview}`;
582
- });
583
- const content = [
584
- `Monthly memory summary for ${month}`,
585
- `Entries: ${total}`,
586
- '',
587
- ...samples,
588
- ].join('\n');
589
- const id = this.generateId();
590
- const tags = ['consolidated', `month:${month}`];
591
- const metadata = {
592
- consolidated: {
593
- month,
594
- windowDays,
595
- sourceCount: total,
596
- sourceIds: monthRows.map((r) => r.id),
597
- },
598
- };
599
- insertStmt.run(id, MemoryType.SUMMARY, options.agentId, null, content, JSON.stringify(metadata), JSON.stringify(tags), 0.5, now, now, null);
600
- for (const tag of tags) {
601
- insertTagStmt.run(id, tag);
602
- }
603
- summaryIds.push(id);
604
- for (const row of monthRows) {
605
- const result = deleteStmt.run(row.id);
606
- deleted += result.changes ?? 0;
607
- }
608
- }
609
- });
610
- try {
611
- consolidateTransaction();
612
- return {
613
- months: byMonth.size,
614
- summarized: rows.length,
615
- deleted,
616
- summaryIds,
617
- };
618
- }
619
- catch (error) {
620
- this.logger.error(`Failed to consolidate memories: ${error instanceof Error ? error.message : String(error)}`);
621
- return { months: 0, summarized: 0, deleted: 0, summaryIds: [] };
622
- }
623
- }
624
- async bulkCreate(inputs) {
625
- if (!(await this.ensureInitialized())) {
626
- return [];
627
- }
628
- const results = [];
629
- try {
630
- const transaction = this.db.transaction(() => {
631
- for (const input of inputs) {
632
- const id = this.generateId();
633
- const now = Date.now();
634
- const tagsJson = input.tags ? JSON.stringify(input.tags) : null;
635
- const stmt = this.db.prepare(`
636
- INSERT INTO memories (
637
- id, type, agent_id, session_id, content, metadata, tags, importance, created_at, updated_at, expires_at
638
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
639
- `);
640
- stmt.run(id, input.type, input.agentId || null, input.sessionId || null, input.content, input.metadata ? JSON.stringify(input.metadata) : null, tagsJson, input.importance ?? 0.5, now, now, input.expiresAt || null);
641
- if (input.tags && input.tags.length > 0) {
642
- const tagStmt = this.db.prepare('INSERT INTO memory_tags (memory_id, tag) VALUES (?, ?)');
643
- for (const tag of input.tags) {
644
- tagStmt.run(id, tag);
645
- }
646
- }
647
- results.push({
648
- id,
649
- type: input.type,
650
- agentId: input.agentId,
651
- sessionId: input.sessionId,
652
- content: input.content,
653
- metadata: input.metadata,
654
- tags: input.tags,
655
- importance: input.importance ?? 0.5,
656
- createdAt: now,
657
- updatedAt: now,
658
- expiresAt: input.expiresAt,
659
- });
660
- }
661
- });
662
- transaction();
663
- this.logger.debug(`Bulk created ${results.length} memories`);
664
- return results;
665
- }
666
- catch (error) {
667
- this.logger.error(`Failed to bulk create memories: ${error instanceof Error ? error.message : String(error)}`);
668
- return [];
669
- }
670
- }
671
- rowToMemory(row) {
672
- return {
673
- id: row.id,
674
- type: row.type,
675
- agentId: row.agent_id || undefined,
676
- sessionId: row.session_id || undefined,
677
- content: row.content,
678
- embedding: row.embedding ? Array.from(row.embedding) : undefined,
679
- metadata: row.metadata ? JSON.parse(row.metadata) : undefined,
680
- tags: row.tags ? JSON.parse(row.tags) : undefined,
681
- importance: row.importance,
682
- createdAt: row.created_at,
683
- updatedAt: row.updated_at,
684
- expiresAt: row.expires_at || undefined,
685
- };
686
- }
687
- async isAvailable() {
688
- return this.ensureInitialized();
689
- }
690
- onModuleDestroy() {
691
- if (this.db) {
692
- try {
693
- this.db.close();
694
- this.logger.log('Memory database connection closed');
695
- }
696
- catch (error) {
697
- this.logger.warn(`Error closing database: ${error instanceof Error ? error.message : String(error)}`);
698
- }
699
- }
700
- }
701
- };
702
- exports.MemoryService = MemoryService;
703
- exports.MemoryService = MemoryService = MemoryService_1 = __decorate([
704
- (0, common_1.Injectable)(),
705
- __metadata("design:paramtypes", [])
706
- ], MemoryService);
707
- //# sourceMappingURL=memory.service.js.map