@elizaos/plugin-memory 1.1.2 → 2.0.0-alpha

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 (43) hide show
  1. package/dist/evaluators/index.d.ts +3 -0
  2. package/dist/evaluators/index.d.ts.map +1 -0
  3. package/dist/evaluators/long-term-extraction.d.ts +1 -6
  4. package/dist/evaluators/long-term-extraction.d.ts.map +1 -0
  5. package/dist/evaluators/summarization.d.ts +1 -28
  6. package/dist/evaluators/summarization.d.ts.map +1 -0
  7. package/dist/generated/prompts/typescript/prompts.d.ts +16 -0
  8. package/dist/generated/prompts/typescript/prompts.d.ts.map +1 -0
  9. package/dist/index.d.ts +7 -38
  10. package/dist/index.d.ts.map +1 -0
  11. package/dist/{node/index.node.js → index.js} +931 -980
  12. package/dist/index.js.map +20 -0
  13. package/dist/providers/context-summary.d.ts +2 -11
  14. package/dist/providers/context-summary.d.ts.map +1 -0
  15. package/dist/providers/index.d.ts +3 -0
  16. package/dist/providers/index.d.ts.map +1 -0
  17. package/dist/providers/long-term-memory.d.ts +2 -16
  18. package/dist/providers/long-term-memory.d.ts.map +1 -0
  19. package/dist/schemas/index.d.ts +4 -9
  20. package/dist/schemas/index.d.ts.map +1 -0
  21. package/dist/schemas/long-term-memories.d.ts +1 -4
  22. package/dist/schemas/long-term-memories.d.ts.map +1 -0
  23. package/dist/schemas/memory-access-logs.d.ts +20 -58
  24. package/dist/schemas/memory-access-logs.d.ts.map +1 -0
  25. package/dist/schemas/session-summaries.d.ts +1 -4
  26. package/dist/schemas/session-summaries.d.ts.map +1 -0
  27. package/dist/services/memory-service.d.ts +7 -75
  28. package/dist/services/memory-service.d.ts.map +1 -0
  29. package/dist/types/index.d.ts +5 -26
  30. package/dist/types/index.d.ts.map +1 -0
  31. package/package.json +45 -48
  32. package/README.md +0 -335
  33. package/dist/actions/remember.d.ts +0 -11
  34. package/dist/browser/index.browser.js +0 -205
  35. package/dist/browser/index.browser.js.map +0 -19
  36. package/dist/browser/index.d.ts +0 -2
  37. package/dist/cjs/index.d.ts +0 -2
  38. package/dist/cjs/index.node.cjs +0 -1168
  39. package/dist/cjs/index.node.js.map +0 -19
  40. package/dist/index.browser.d.ts +0 -2
  41. package/dist/index.node.d.ts +0 -2
  42. package/dist/node/index.d.ts +0 -2
  43. package/dist/node/index.node.js.map +0 -19
@@ -1,1168 +0,0 @@
1
- var __defProp = Object.defineProperty;
2
- var __getOwnPropNames = Object.getOwnPropertyNames;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __hasOwnProp = Object.prototype.hasOwnProperty;
5
- var __moduleCache = /* @__PURE__ */ new WeakMap;
6
- var __toCommonJS = (from) => {
7
- var entry = __moduleCache.get(from), desc;
8
- if (entry)
9
- return entry;
10
- entry = __defProp({}, "__esModule", { value: true });
11
- if (from && typeof from === "object" || typeof from === "function")
12
- __getOwnPropNames(from).map((key) => !__hasOwnProp.call(entry, key) && __defProp(entry, key, {
13
- get: () => from[key],
14
- enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
15
- }));
16
- __moduleCache.set(from, entry);
17
- return entry;
18
- };
19
- var __export = (target, all) => {
20
- for (var name in all)
21
- __defProp(target, name, {
22
- get: all[name],
23
- enumerable: true,
24
- configurable: true,
25
- set: (newValue) => all[name] = () => newValue
26
- });
27
- };
28
-
29
- // src/index.node.ts
30
- var exports_index_node = {};
31
- __export(exports_index_node, {
32
- sessionSummaries: () => sessionSummaries,
33
- memoryPlugin: () => memoryPlugin,
34
- memoryAccessLogs: () => memoryAccessLogs,
35
- longTermMemoryProvider: () => longTermMemoryProvider,
36
- longTermMemories: () => longTermMemories,
37
- default: () => src_default,
38
- contextSummaryProvider: () => contextSummaryProvider,
39
- MemoryService: () => MemoryService,
40
- LongTermMemoryCategory: () => LongTermMemoryCategory
41
- });
42
- module.exports = __toCommonJS(exports_index_node);
43
-
44
- // src/services/memory-service.ts
45
- var import_core = require("@elizaos/core");
46
- var import_drizzle_orm4 = require("drizzle-orm");
47
-
48
- // src/schemas/index.ts
49
- var exports_schemas = {};
50
- __export(exports_schemas, {
51
- sessionSummaries: () => sessionSummaries,
52
- memoryAccessLogs: () => memoryAccessLogs,
53
- longTermMemories: () => longTermMemories
54
- });
55
-
56
- // src/schemas/long-term-memories.ts
57
- var import_drizzle_orm = require("drizzle-orm");
58
- var import_pg_core = require("drizzle-orm/pg-core");
59
- var longTermMemories = import_pg_core.pgTable("long_term_memories", {
60
- id: import_pg_core.varchar("id", { length: 36 }).primaryKey(),
61
- agentId: import_pg_core.varchar("agent_id", { length: 36 }).notNull(),
62
- entityId: import_pg_core.varchar("entity_id", { length: 36 }).notNull(),
63
- category: import_pg_core.text("category").notNull(),
64
- content: import_pg_core.text("content").notNull(),
65
- metadata: import_pg_core.jsonb("metadata"),
66
- embedding: import_pg_core.real("embedding").array(),
67
- confidence: import_pg_core.real("confidence").default(1),
68
- source: import_pg_core.text("source"),
69
- createdAt: import_pg_core.timestamp("created_at").default(import_drizzle_orm.sql`now()`).notNull(),
70
- updatedAt: import_pg_core.timestamp("updated_at").default(import_drizzle_orm.sql`now()`).notNull(),
71
- lastAccessedAt: import_pg_core.timestamp("last_accessed_at"),
72
- accessCount: import_pg_core.integer("access_count").default(0)
73
- }, (table) => ({
74
- agentEntityIdx: import_pg_core.index("long_term_memories_agent_entity_idx").on(table.agentId, table.entityId),
75
- categoryIdx: import_pg_core.index("long_term_memories_category_idx").on(table.category),
76
- confidenceIdx: import_pg_core.index("long_term_memories_confidence_idx").on(table.confidence),
77
- createdAtIdx: import_pg_core.index("long_term_memories_created_at_idx").on(table.createdAt)
78
- }));
79
- // src/schemas/session-summaries.ts
80
- var import_drizzle_orm2 = require("drizzle-orm");
81
- var import_pg_core2 = require("drizzle-orm/pg-core");
82
- var sessionSummaries = import_pg_core2.pgTable("session_summaries", {
83
- id: import_pg_core2.varchar("id", { length: 36 }).primaryKey(),
84
- agentId: import_pg_core2.varchar("agent_id", { length: 36 }).notNull(),
85
- roomId: import_pg_core2.varchar("room_id", { length: 36 }).notNull(),
86
- entityId: import_pg_core2.varchar("entity_id", { length: 36 }),
87
- summary: import_pg_core2.text("summary").notNull(),
88
- messageCount: import_pg_core2.integer("message_count").notNull(),
89
- lastMessageOffset: import_pg_core2.integer("last_message_offset").notNull().default(0),
90
- startTime: import_pg_core2.timestamp("start_time").notNull(),
91
- endTime: import_pg_core2.timestamp("end_time").notNull(),
92
- topics: import_pg_core2.jsonb("topics"),
93
- metadata: import_pg_core2.jsonb("metadata"),
94
- embedding: import_pg_core2.real("embedding").array(),
95
- createdAt: import_pg_core2.timestamp("created_at").default(import_drizzle_orm2.sql`now()`).notNull(),
96
- updatedAt: import_pg_core2.timestamp("updated_at").default(import_drizzle_orm2.sql`now()`).notNull()
97
- }, (table) => ({
98
- agentRoomIdx: import_pg_core2.index("session_summaries_agent_room_idx").on(table.agentId, table.roomId),
99
- entityIdx: import_pg_core2.index("session_summaries_entity_idx").on(table.entityId),
100
- startTimeIdx: import_pg_core2.index("session_summaries_start_time_idx").on(table.startTime)
101
- }));
102
- // src/schemas/memory-access-logs.ts
103
- var import_drizzle_orm3 = require("drizzle-orm");
104
- var import_pg_core3 = require("drizzle-orm/pg-core");
105
- var memoryAccessLogs = import_pg_core3.pgTable("memory_access_logs", {
106
- id: import_pg_core3.varchar("id", { length: 36 }).primaryKey(),
107
- agentId: import_pg_core3.varchar("agent_id", { length: 36 }).notNull(),
108
- memoryId: import_pg_core3.varchar("memory_id", { length: 36 }).notNull(),
109
- memoryType: import_pg_core3.text("memory_type").notNull(),
110
- accessedAt: import_pg_core3.timestamp("accessed_at").default(import_drizzle_orm3.sql`now()`).notNull(),
111
- roomId: import_pg_core3.varchar("room_id", { length: 36 }),
112
- relevanceScore: import_pg_core3.real("relevance_score"),
113
- wasUseful: import_pg_core3.integer("was_useful")
114
- }, (table) => ({
115
- memoryIdx: import_pg_core3.index("memory_access_logs_memory_idx").on(table.memoryId),
116
- agentIdx: import_pg_core3.index("memory_access_logs_agent_idx").on(table.agentId),
117
- accessedAtIdx: import_pg_core3.index("memory_access_logs_accessed_at_idx").on(table.accessedAt)
118
- }));
119
- // src/services/memory-service.ts
120
- class MemoryService extends import_core.Service {
121
- static serviceType = "memory";
122
- sessionMessageCounts;
123
- memoryConfig;
124
- lastExtractionCheckpoints;
125
- capabilityDescription = "Advanced memory management with short-term summarization and long-term persistent facts";
126
- constructor(runtime) {
127
- super(runtime);
128
- this.sessionMessageCounts = new Map;
129
- this.lastExtractionCheckpoints = new Map;
130
- this.memoryConfig = {
131
- shortTermSummarizationThreshold: 16,
132
- shortTermRetainRecent: 6,
133
- shortTermSummarizationInterval: 10,
134
- longTermExtractionEnabled: true,
135
- longTermVectorSearchEnabled: false,
136
- longTermConfidenceThreshold: 0.85,
137
- longTermExtractionThreshold: 30,
138
- longTermExtractionInterval: 10,
139
- summaryModelType: "TEXT_LARGE",
140
- summaryMaxTokens: 2500,
141
- summaryMaxNewMessages: 20
142
- };
143
- }
144
- static async start(runtime) {
145
- const service = new MemoryService(runtime);
146
- await service.initialize(runtime);
147
- return service;
148
- }
149
- async stop() {
150
- import_core.logger.info("MemoryService stopped");
151
- }
152
- async initialize(runtime) {
153
- this.runtime = runtime;
154
- const threshold = runtime.getSetting("MEMORY_SUMMARIZATION_THRESHOLD");
155
- if (threshold) {
156
- this.memoryConfig.shortTermSummarizationThreshold = parseInt(threshold, 10);
157
- }
158
- const retainRecent = runtime.getSetting("MEMORY_RETAIN_RECENT");
159
- if (retainRecent) {
160
- this.memoryConfig.shortTermRetainRecent = parseInt(retainRecent, 10);
161
- }
162
- const summarizationInterval = runtime.getSetting("MEMORY_SUMMARIZATION_INTERVAL");
163
- if (summarizationInterval) {
164
- this.memoryConfig.shortTermSummarizationInterval = parseInt(summarizationInterval, 10);
165
- }
166
- const maxNewMessages = runtime.getSetting("MEMORY_MAX_NEW_MESSAGES");
167
- if (maxNewMessages) {
168
- this.memoryConfig.summaryMaxNewMessages = parseInt(maxNewMessages, 10);
169
- }
170
- const longTermEnabled = runtime.getSetting("MEMORY_LONG_TERM_ENABLED");
171
- if (longTermEnabled === "false") {
172
- this.memoryConfig.longTermExtractionEnabled = false;
173
- } else if (longTermEnabled === "true") {
174
- this.memoryConfig.longTermExtractionEnabled = true;
175
- }
176
- const confidenceThreshold = runtime.getSetting("MEMORY_CONFIDENCE_THRESHOLD");
177
- if (confidenceThreshold) {
178
- this.memoryConfig.longTermConfidenceThreshold = parseFloat(confidenceThreshold);
179
- }
180
- const extractionThreshold = runtime.getSetting("MEMORY_EXTRACTION_THRESHOLD");
181
- if (extractionThreshold) {
182
- this.memoryConfig.longTermExtractionThreshold = parseInt(extractionThreshold, 10);
183
- }
184
- const extractionInterval = runtime.getSetting("MEMORY_EXTRACTION_INTERVAL");
185
- if (extractionInterval) {
186
- this.memoryConfig.longTermExtractionInterval = parseInt(extractionInterval, 10);
187
- }
188
- import_core.logger.debug({
189
- summarizationThreshold: this.memoryConfig.shortTermSummarizationThreshold,
190
- summarizationInterval: this.memoryConfig.shortTermSummarizationInterval,
191
- maxNewMessages: this.memoryConfig.summaryMaxNewMessages,
192
- retainRecent: this.memoryConfig.shortTermRetainRecent,
193
- longTermEnabled: this.memoryConfig.longTermExtractionEnabled,
194
- extractionThreshold: this.memoryConfig.longTermExtractionThreshold,
195
- extractionInterval: this.memoryConfig.longTermExtractionInterval,
196
- confidenceThreshold: this.memoryConfig.longTermConfidenceThreshold
197
- }, "MemoryService initialized");
198
- }
199
- getDb() {
200
- const db = this.runtime.db;
201
- if (!db) {
202
- throw new Error("Database not available");
203
- }
204
- return db;
205
- }
206
- getConfig() {
207
- return { ...this.memoryConfig };
208
- }
209
- updateConfig(updates) {
210
- this.memoryConfig = { ...this.memoryConfig, ...updates };
211
- }
212
- incrementMessageCount(roomId) {
213
- const current = this.sessionMessageCounts.get(roomId) || 0;
214
- const newCount = current + 1;
215
- this.sessionMessageCounts.set(roomId, newCount);
216
- return newCount;
217
- }
218
- resetMessageCount(roomId) {
219
- this.sessionMessageCounts.set(roomId, 0);
220
- }
221
- async shouldSummarize(roomId) {
222
- const count = await this.runtime.countMemories(roomId, false, "messages");
223
- return count >= this.memoryConfig.shortTermSummarizationThreshold;
224
- }
225
- getExtractionKey(entityId, roomId) {
226
- return `memory:extraction:${entityId}:${roomId}`;
227
- }
228
- async getLastExtractionCheckpoint(entityId, roomId) {
229
- const key = this.getExtractionKey(entityId, roomId);
230
- const cached = this.lastExtractionCheckpoints.get(key);
231
- if (cached !== undefined) {
232
- return cached;
233
- }
234
- try {
235
- const checkpoint = await this.runtime.getCache(key);
236
- const messageCount = checkpoint ?? 0;
237
- this.lastExtractionCheckpoints.set(key, messageCount);
238
- return messageCount;
239
- } catch (error) {
240
- import_core.logger.warn({ error }, "Failed to get extraction checkpoint from cache");
241
- return 0;
242
- }
243
- }
244
- async setLastExtractionCheckpoint(entityId, roomId, messageCount) {
245
- const key = this.getExtractionKey(entityId, roomId);
246
- this.lastExtractionCheckpoints.set(key, messageCount);
247
- try {
248
- await this.runtime.setCache(key, messageCount);
249
- import_core.logger.debug(`Set extraction checkpoint for ${entityId} in room ${roomId} at message count ${messageCount}`);
250
- } catch (error) {
251
- import_core.logger.error({ error }, "Failed to persist extraction checkpoint to cache");
252
- }
253
- }
254
- async shouldRunExtraction(entityId, roomId, currentMessageCount) {
255
- const threshold = this.memoryConfig.longTermExtractionThreshold;
256
- const interval = this.memoryConfig.longTermExtractionInterval;
257
- if (currentMessageCount < threshold) {
258
- return false;
259
- }
260
- const lastCheckpoint = await this.getLastExtractionCheckpoint(entityId, roomId);
261
- const currentCheckpoint = Math.floor(currentMessageCount / interval) * interval;
262
- const shouldRun = currentMessageCount >= threshold && currentCheckpoint > lastCheckpoint;
263
- import_core.logger.debug({
264
- entityId,
265
- roomId,
266
- currentMessageCount,
267
- threshold,
268
- interval,
269
- lastCheckpoint,
270
- currentCheckpoint,
271
- shouldRun
272
- }, "Extraction check");
273
- return shouldRun;
274
- }
275
- async storeLongTermMemory(memory) {
276
- const db = this.getDb();
277
- const id = crypto.randomUUID();
278
- const now = new Date;
279
- const newMemory = {
280
- id,
281
- createdAt: now,
282
- updatedAt: now,
283
- accessCount: 0,
284
- ...memory
285
- };
286
- try {
287
- await db.insert(longTermMemories).values({
288
- id: newMemory.id,
289
- agentId: newMemory.agentId,
290
- entityId: newMemory.entityId,
291
- category: newMemory.category,
292
- content: newMemory.content,
293
- metadata: newMemory.metadata || {},
294
- embedding: newMemory.embedding,
295
- confidence: newMemory.confidence,
296
- source: newMemory.source,
297
- accessCount: newMemory.accessCount,
298
- createdAt: now,
299
- updatedAt: now,
300
- lastAccessedAt: newMemory.lastAccessedAt
301
- });
302
- } catch (error) {
303
- import_core.logger.error({ error }, "Failed to store long-term memory");
304
- throw error;
305
- }
306
- import_core.logger.info(`Stored long-term memory: ${newMemory.category} for entity ${newMemory.entityId}`);
307
- return newMemory;
308
- }
309
- async getLongTermMemories(entityId, category, limit = 10) {
310
- const db = this.getDb();
311
- const conditions = [
312
- import_drizzle_orm4.eq(longTermMemories.agentId, this.runtime.agentId),
313
- import_drizzle_orm4.eq(longTermMemories.entityId, entityId)
314
- ];
315
- if (category) {
316
- conditions.push(import_drizzle_orm4.eq(longTermMemories.category, category));
317
- }
318
- const results = await db.select().from(longTermMemories).where(import_drizzle_orm4.and(...conditions)).orderBy(import_drizzle_orm4.desc(longTermMemories.confidence), import_drizzle_orm4.desc(longTermMemories.updatedAt)).limit(limit);
319
- return results.map((row) => ({
320
- id: row.id,
321
- agentId: row.agentId,
322
- entityId: row.entityId,
323
- category: row.category,
324
- content: row.content,
325
- metadata: row.metadata,
326
- embedding: row.embedding,
327
- confidence: row.confidence,
328
- source: row.source,
329
- createdAt: row.createdAt,
330
- updatedAt: row.updatedAt,
331
- lastAccessedAt: row.lastAccessedAt,
332
- accessCount: row.accessCount
333
- }));
334
- }
335
- async updateLongTermMemory(id, entityId, updates) {
336
- const db = this.getDb();
337
- const updateData = {
338
- updatedAt: new Date
339
- };
340
- if (updates.content !== undefined) {
341
- updateData.content = updates.content;
342
- }
343
- if (updates.metadata !== undefined) {
344
- updateData.metadata = updates.metadata;
345
- }
346
- if (updates.confidence !== undefined) {
347
- updateData.confidence = updates.confidence;
348
- }
349
- if (updates.embedding !== undefined) {
350
- updateData.embedding = updates.embedding;
351
- }
352
- if (updates.lastAccessedAt !== undefined) {
353
- updateData.lastAccessedAt = updates.lastAccessedAt;
354
- }
355
- if (updates.accessCount !== undefined) {
356
- updateData.accessCount = updates.accessCount;
357
- }
358
- await db.update(longTermMemories).set(updateData).where(import_drizzle_orm4.and(import_drizzle_orm4.eq(longTermMemories.id, id), import_drizzle_orm4.eq(longTermMemories.agentId, this.runtime.agentId), import_drizzle_orm4.eq(longTermMemories.entityId, entityId)));
359
- import_core.logger.info(`Updated long-term memory: ${id} for entity ${entityId}`);
360
- }
361
- async deleteLongTermMemory(id, entityId) {
362
- const db = this.getDb();
363
- await db.delete(longTermMemories).where(import_drizzle_orm4.and(import_drizzle_orm4.eq(longTermMemories.id, id), import_drizzle_orm4.eq(longTermMemories.agentId, this.runtime.agentId), import_drizzle_orm4.eq(longTermMemories.entityId, entityId)));
364
- import_core.logger.info(`Deleted long-term memory: ${id} for entity ${entityId}`);
365
- }
366
- async getCurrentSessionSummary(roomId) {
367
- const db = this.getDb();
368
- const results = await db.select().from(sessionSummaries).where(import_drizzle_orm4.and(import_drizzle_orm4.eq(sessionSummaries.agentId, this.runtime.agentId), import_drizzle_orm4.eq(sessionSummaries.roomId, roomId))).orderBy(import_drizzle_orm4.desc(sessionSummaries.updatedAt)).limit(1);
369
- if (results.length === 0) {
370
- return null;
371
- }
372
- const row = results[0];
373
- return {
374
- id: row.id,
375
- agentId: row.agentId,
376
- roomId: row.roomId,
377
- entityId: row.entityId,
378
- summary: row.summary,
379
- messageCount: row.messageCount,
380
- lastMessageOffset: row.lastMessageOffset,
381
- startTime: row.startTime,
382
- endTime: row.endTime,
383
- topics: row.topics || [],
384
- metadata: row.metadata,
385
- embedding: row.embedding,
386
- createdAt: row.createdAt,
387
- updatedAt: row.updatedAt
388
- };
389
- }
390
- async storeSessionSummary(summary) {
391
- const db = this.getDb();
392
- const id = crypto.randomUUID();
393
- const now = new Date;
394
- const newSummary = {
395
- id,
396
- createdAt: now,
397
- updatedAt: now,
398
- ...summary
399
- };
400
- await db.insert(sessionSummaries).values({
401
- id: newSummary.id,
402
- agentId: newSummary.agentId,
403
- roomId: newSummary.roomId,
404
- entityId: newSummary.entityId || null,
405
- summary: newSummary.summary,
406
- messageCount: newSummary.messageCount,
407
- lastMessageOffset: newSummary.lastMessageOffset,
408
- startTime: newSummary.startTime,
409
- endTime: newSummary.endTime,
410
- topics: newSummary.topics || [],
411
- metadata: newSummary.metadata || {},
412
- embedding: newSummary.embedding,
413
- createdAt: now,
414
- updatedAt: now
415
- });
416
- import_core.logger.info(`Stored session summary for room ${newSummary.roomId}`);
417
- return newSummary;
418
- }
419
- async updateSessionSummary(id, roomId, updates) {
420
- const db = this.getDb();
421
- const updateData = {
422
- updatedAt: new Date
423
- };
424
- if (updates.summary !== undefined) {
425
- updateData.summary = updates.summary;
426
- }
427
- if (updates.messageCount !== undefined) {
428
- updateData.messageCount = updates.messageCount;
429
- }
430
- if (updates.lastMessageOffset !== undefined) {
431
- updateData.lastMessageOffset = updates.lastMessageOffset;
432
- }
433
- if (updates.endTime !== undefined) {
434
- updateData.endTime = updates.endTime;
435
- }
436
- if (updates.topics !== undefined) {
437
- updateData.topics = updates.topics;
438
- }
439
- if (updates.metadata !== undefined) {
440
- updateData.metadata = updates.metadata;
441
- }
442
- if (updates.embedding !== undefined) {
443
- updateData.embedding = updates.embedding;
444
- }
445
- await db.update(sessionSummaries).set(updateData).where(import_drizzle_orm4.and(import_drizzle_orm4.eq(sessionSummaries.id, id), import_drizzle_orm4.eq(sessionSummaries.agentId, this.runtime.agentId), import_drizzle_orm4.eq(sessionSummaries.roomId, roomId)));
446
- import_core.logger.info(`Updated session summary: ${id} for room ${roomId}`);
447
- }
448
- async getSessionSummaries(roomId, limit = 5) {
449
- const db = this.getDb();
450
- const results = await db.select().from(sessionSummaries).where(import_drizzle_orm4.and(import_drizzle_orm4.eq(sessionSummaries.agentId, this.runtime.agentId), import_drizzle_orm4.eq(sessionSummaries.roomId, roomId))).orderBy(import_drizzle_orm4.desc(sessionSummaries.updatedAt)).limit(limit);
451
- return results.map((row) => ({
452
- id: row.id,
453
- agentId: row.agentId,
454
- roomId: row.roomId,
455
- entityId: row.entityId,
456
- summary: row.summary,
457
- messageCount: row.messageCount,
458
- lastMessageOffset: row.lastMessageOffset,
459
- startTime: row.startTime,
460
- endTime: row.endTime,
461
- topics: row.topics || [],
462
- metadata: row.metadata,
463
- embedding: row.embedding,
464
- createdAt: row.createdAt,
465
- updatedAt: row.updatedAt
466
- }));
467
- }
468
- async searchLongTermMemories(entityId, queryEmbedding, limit = 5, matchThreshold = 0.7) {
469
- if (!this.memoryConfig.longTermVectorSearchEnabled) {
470
- import_core.logger.warn("Vector search is not enabled, falling back to recent memories");
471
- return this.getLongTermMemories(entityId, undefined, limit);
472
- }
473
- const db = this.getDb();
474
- try {
475
- const cleanVector = queryEmbedding.map((n) => Number.isFinite(n) ? Number(n.toFixed(6)) : 0);
476
- const similarity = import_drizzle_orm4.sql`1 - (${import_drizzle_orm4.cosineDistance(longTermMemories.embedding, cleanVector)})`;
477
- const conditions = [
478
- import_drizzle_orm4.eq(longTermMemories.agentId, this.runtime.agentId),
479
- import_drizzle_orm4.eq(longTermMemories.entityId, entityId),
480
- import_drizzle_orm4.sql`${longTermMemories.embedding} IS NOT NULL`
481
- ];
482
- if (matchThreshold > 0) {
483
- conditions.push(import_drizzle_orm4.gte(similarity, matchThreshold));
484
- }
485
- const results = await db.select({
486
- memory: longTermMemories,
487
- similarity
488
- }).from(longTermMemories).where(import_drizzle_orm4.and(...conditions)).orderBy(import_drizzle_orm4.desc(similarity)).limit(limit);
489
- return results.map((row) => ({
490
- id: row.memory.id,
491
- agentId: row.memory.agentId,
492
- entityId: row.memory.entityId,
493
- category: row.memory.category,
494
- content: row.memory.content,
495
- metadata: row.memory.metadata,
496
- embedding: row.memory.embedding,
497
- confidence: row.memory.confidence,
498
- source: row.memory.source,
499
- createdAt: row.memory.createdAt,
500
- updatedAt: row.memory.updatedAt,
501
- lastAccessedAt: row.memory.lastAccessedAt,
502
- accessCount: row.memory.accessCount,
503
- similarity: row.similarity
504
- }));
505
- } catch (error) {
506
- import_core.logger.warn({ error }, "Vector search failed, falling back to recent memories");
507
- return this.getLongTermMemories(entityId, undefined, limit);
508
- }
509
- }
510
- async getFormattedLongTermMemories(entityId) {
511
- const memories = await this.getLongTermMemories(entityId, undefined, 20);
512
- if (memories.length === 0) {
513
- return "";
514
- }
515
- const grouped = new Map;
516
- for (const memory of memories) {
517
- if (!grouped.has(memory.category)) {
518
- grouped.set(memory.category, []);
519
- }
520
- grouped.get(memory.category)?.push(memory);
521
- }
522
- const sections = [];
523
- for (const [category, categoryMemories] of grouped.entries()) {
524
- const categoryName = category.split("_").map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join(" ");
525
- const items = categoryMemories.map((m) => `- ${m.content}`).join(`
526
- `);
527
- sections.push(`**${categoryName}**:
528
- ${items}`);
529
- }
530
- return sections.join(`
531
-
532
- `);
533
- }
534
- }
535
-
536
- // src/evaluators/summarization.ts
537
- var import_core2 = require("@elizaos/core");
538
- async function getDialogueMessageCount(runtime, roomId) {
539
- const messages = await runtime.getMemories({
540
- tableName: "messages",
541
- roomId,
542
- count: 100,
543
- unique: false
544
- });
545
- const dialogueMessages = messages.filter((msg) => !(msg.content?.type === "action_result" && msg.metadata?.type === "action_result") && (msg.metadata?.type === "agent_response_message" || msg.metadata?.type === "user_message"));
546
- return dialogueMessages.length;
547
- }
548
- var initialSummarizationTemplate = `# Task: Summarize Conversation
549
-
550
- You are analyzing a conversation to create a concise summary that captures the key points, topics, and important details.
551
-
552
- # Recent Messages
553
- {{recentMessages}}
554
-
555
- # Instructions
556
- Generate a summary that:
557
- 1. Captures the main topics discussed
558
- 2. Highlights key information shared
559
- 3. Notes any decisions made or questions asked
560
- 4. Maintains context for future reference
561
- 5. Is concise but comprehensive
562
-
563
- **IMPORTANT**: Keep the summary under 2500 tokens. Be comprehensive but concise.
564
-
565
- Also extract:
566
- - **Topics**: List of main topics discussed (comma-separated)
567
- - **Key Points**: Important facts or decisions (bullet points)
568
-
569
- Respond in this XML format:
570
- <summary>
571
- <text>Your comprehensive summary here</text>
572
- <topics>topic1, topic2, topic3</topics>
573
- <keyPoints>
574
- <point>First key point</point>
575
- <point>Second key point</point>
576
- </keyPoints>
577
- </summary>`;
578
- var updateSummarizationTemplate = `# Task: Update and Condense Conversation Summary
579
-
580
- You are updating an existing conversation summary with new messages, while keeping the total summary concise.
581
-
582
- # Existing Summary
583
- {{existingSummary}}
584
-
585
- # Existing Topics
586
- {{existingTopics}}
587
-
588
- # New Messages Since Last Summary
589
- {{newMessages}}
590
-
591
- # Instructions
592
- Update the summary by:
593
- 1. Merging the existing summary with insights from the new messages
594
- 2. Removing redundant or less important details to stay under the token limit
595
- 3. Keeping the most important context and decisions
596
- 4. Adding new topics if they emerge
597
- 5. **CRITICAL**: Keep the ENTIRE updated summary under 2500 tokens
598
-
599
- The goal is a rolling summary that captures the essence of the conversation without growing indefinitely.
600
-
601
- Respond in this XML format:
602
- <summary>
603
- <text>Your updated and condensed summary here</text>
604
- <topics>topic1, topic2, topic3</topics>
605
- <keyPoints>
606
- <point>First key point</point>
607
- <point>Second key point</point>
608
- </keyPoints>
609
- </summary>`;
610
- function parseSummaryXML(xml) {
611
- const summaryMatch = xml.match(/<text>([\s\S]*?)<\/text>/);
612
- const topicsMatch = xml.match(/<topics>([\s\S]*?)<\/topics>/);
613
- const keyPointsMatches = xml.matchAll(/<point>([\s\S]*?)<\/point>/g);
614
- const summary = summaryMatch ? summaryMatch[1].trim() : "Summary not available";
615
- const topics = topicsMatch ? topicsMatch[1].split(",").map((t) => t.trim()).filter(Boolean) : [];
616
- const keyPoints = Array.from(keyPointsMatches).map((match) => match[1].trim());
617
- return { summary, topics, keyPoints };
618
- }
619
- var summarizationEvaluator = {
620
- name: "MEMORY_SUMMARIZATION",
621
- description: "Automatically summarizes conversations to optimize context usage",
622
- similes: [
623
- "CONVERSATION_SUMMARY",
624
- "CONTEXT_COMPRESSION",
625
- "MEMORY_OPTIMIZATION"
626
- ],
627
- alwaysRun: true,
628
- validate: async (runtime, message) => {
629
- if (!message.content?.text) {
630
- return false;
631
- }
632
- const memoryService = runtime.getService("memory");
633
- if (!memoryService) {
634
- return false;
635
- }
636
- const config = memoryService.getConfig();
637
- const currentDialogueCount = await getDialogueMessageCount(runtime, message.roomId);
638
- const existingSummary = await memoryService.getCurrentSessionSummary(message.roomId);
639
- if (!existingSummary) {
640
- const shouldSummarize = currentDialogueCount >= config.shortTermSummarizationThreshold;
641
- return shouldSummarize;
642
- } else {
643
- const newDialogueCount = currentDialogueCount - existingSummary.lastMessageOffset;
644
- const shouldUpdate = newDialogueCount >= config.shortTermSummarizationInterval;
645
- return shouldUpdate;
646
- }
647
- },
648
- handler: async (runtime, message) => {
649
- const memoryService = runtime.getService("memory");
650
- if (!memoryService) {
651
- import_core2.logger.error("MemoryService not found");
652
- return;
653
- }
654
- const config = memoryService.getConfig();
655
- const { roomId } = message;
656
- try {
657
- import_core2.logger.info(`Starting summarization for room ${roomId}`);
658
- const existingSummary = await memoryService.getCurrentSessionSummary(roomId);
659
- const lastOffset = existingSummary?.lastMessageOffset || 0;
660
- const allMessages = await runtime.getMemories({
661
- tableName: "messages",
662
- roomId,
663
- count: 1000,
664
- unique: false
665
- });
666
- const allDialogueMessages = allMessages.filter((msg) => !(msg.content?.type === "action_result" && msg.metadata?.type === "action_result") && (msg.metadata?.type === "agent_response_message" || msg.metadata?.type === "user_message"));
667
- const totalDialogueCount = allDialogueMessages.length;
668
- const newDialogueCount = totalDialogueCount - lastOffset;
669
- if (newDialogueCount === 0) {
670
- import_core2.logger.debug("No new dialogue messages to summarize");
671
- return;
672
- }
673
- const maxNewMessages = config.summaryMaxNewMessages || 50;
674
- const messagesToProcess = Math.min(newDialogueCount, maxNewMessages);
675
- if (newDialogueCount > maxNewMessages) {
676
- import_core2.logger.warn(`Capping new dialogue messages at ${maxNewMessages} (${newDialogueCount} available). Oldest messages will be skipped.`);
677
- }
678
- const sortedDialogueMessages = allDialogueMessages.sort((a, b) => (a.createdAt || 0) - (b.createdAt || 0));
679
- const newDialogueMessages = sortedDialogueMessages.slice(lastOffset, lastOffset + messagesToProcess);
680
- if (newDialogueMessages.length === 0) {
681
- import_core2.logger.debug("No new dialogue messages retrieved after filtering");
682
- return;
683
- }
684
- const formattedMessages = newDialogueMessages.map((msg) => {
685
- const sender = msg.entityId === runtime.agentId ? runtime.character.name : "User";
686
- return `${sender}: ${msg.content.text || "[non-text message]"}`;
687
- }).join(`
688
- `);
689
- const state = await runtime.composeState(message);
690
- let prompt;
691
- let template;
692
- if (existingSummary) {
693
- template = updateSummarizationTemplate;
694
- prompt = import_core2.composePromptFromState({
695
- state: {
696
- ...state,
697
- existingSummary: existingSummary.summary,
698
- existingTopics: existingSummary.topics?.join(", ") || "None",
699
- newMessages: formattedMessages
700
- },
701
- template
702
- });
703
- } else {
704
- const initialMessages = sortedDialogueMessages.map((msg) => {
705
- const sender = msg.entityId === runtime.agentId ? runtime.character.name : "User";
706
- return `${sender}: ${msg.content.text || "[non-text message]"}`;
707
- }).join(`
708
- `);
709
- template = initialSummarizationTemplate;
710
- prompt = import_core2.composePromptFromState({
711
- state: {
712
- ...state,
713
- recentMessages: initialMessages
714
- },
715
- template
716
- });
717
- }
718
- const response = await runtime.useModel(import_core2.ModelType.TEXT_LARGE, {
719
- prompt,
720
- maxTokens: config.summaryMaxTokens || 2500
721
- });
722
- const summaryResult = parseSummaryXML(response);
723
- import_core2.logger.info(`${existingSummary ? "Updated" : "Generated"} summary: ${summaryResult.summary.substring(0, 100)}...`);
724
- const newOffset = lastOffset + newDialogueMessages.length;
725
- const firstMessage = newDialogueMessages[0];
726
- const lastMessage = newDialogueMessages[newDialogueMessages.length - 1];
727
- const startTime = existingSummary ? existingSummary.startTime : firstMessage?.createdAt && firstMessage.createdAt > 0 ? new Date(firstMessage.createdAt) : new Date;
728
- const endTime = lastMessage?.createdAt && lastMessage.createdAt > 0 ? new Date(lastMessage.createdAt) : new Date;
729
- if (existingSummary) {
730
- await memoryService.updateSessionSummary(existingSummary.id, roomId, {
731
- summary: summaryResult.summary,
732
- messageCount: existingSummary.messageCount + newDialogueMessages.length,
733
- lastMessageOffset: newOffset,
734
- endTime,
735
- topics: summaryResult.topics,
736
- metadata: {
737
- keyPoints: summaryResult.keyPoints
738
- }
739
- });
740
- import_core2.logger.info(`Updated summary for room ${roomId}: ${newDialogueMessages.length} new dialogue messages processed (offset: ${lastOffset} → ${newOffset})`);
741
- } else {
742
- await memoryService.storeSessionSummary({
743
- agentId: runtime.agentId,
744
- roomId,
745
- entityId: message.entityId !== runtime.agentId ? message.entityId : undefined,
746
- summary: summaryResult.summary,
747
- messageCount: totalDialogueCount,
748
- lastMessageOffset: totalDialogueCount,
749
- startTime,
750
- endTime,
751
- topics: summaryResult.topics,
752
- metadata: {
753
- keyPoints: summaryResult.keyPoints
754
- }
755
- });
756
- import_core2.logger.info(`Created new summary for room ${roomId}: ${totalDialogueCount} dialogue messages summarized (offset: 0 → ${totalDialogueCount})`);
757
- }
758
- } catch (error) {
759
- import_core2.logger.error({ error }, "Error during summarization:");
760
- }
761
- },
762
- examples: []
763
- };
764
-
765
- // src/evaluators/long-term-extraction.ts
766
- var import_core3 = require("@elizaos/core");
767
-
768
- // src/types/index.ts
769
- var LongTermMemoryCategory;
770
- ((LongTermMemoryCategory2) => {
771
- LongTermMemoryCategory2["EPISODIC"] = "episodic";
772
- LongTermMemoryCategory2["SEMANTIC"] = "semantic";
773
- LongTermMemoryCategory2["PROCEDURAL"] = "procedural";
774
- })(LongTermMemoryCategory ||= {});
775
-
776
- // src/evaluators/long-term-extraction.ts
777
- var extractionTemplate = `# Task: Extract Long-Term Memory (Strict Criteria)
778
-
779
- You are analyzing a conversation to extract ONLY the most critical, persistent information about the user using cognitive science memory categories.
780
-
781
- # Recent Messages
782
- {{recentMessages}}
783
-
784
- # Current Long-Term Memories
785
- {{existingMemories}}
786
-
787
- # Memory Categories (Based on Cognitive Science)
788
-
789
- ## 1. EPISODIC Memory
790
- Personal experiences and specific events with temporal/spatial context.
791
- **Examples:**
792
- - "User completed migration project from MongoDB to PostgreSQL in Q2 2024"
793
- - "User encountered authentication bug in production on March 15th"
794
- - "User had a negative experience with Docker networking in previous job"
795
-
796
- **Requirements:**
797
- - Must include WHO did WHAT, WHEN/WHERE
798
- - Must be a specific, concrete event (not a pattern)
799
- - Must have significant impact or relevance to future work
800
-
801
- ## 2. SEMANTIC Memory
802
- General facts, concepts, knowledge, and established truths about the user.
803
- **Examples:**
804
- - "User is a senior backend engineer with 8 years experience"
805
- - "User specializes in distributed systems and microservices architecture"
806
- - "User's primary programming language is TypeScript"
807
- - "User works at Acme Corp as technical lead"
808
-
809
- **Requirements:**
810
- - Must be factual, timeless information
811
- - Must be explicitly stated or demonstrated conclusively
812
- - No speculation or inference from single instances
813
- - Core identity, expertise, or knowledge only
814
-
815
- ## 3. PROCEDURAL Memory
816
- Skills, workflows, methodologies, and how-to knowledge.
817
- **Examples:**
818
- - "User follows strict TDD workflow: write tests first, then implementation"
819
- - "User prefers git rebase over merge to maintain linear history"
820
- - "User's debugging process: check logs → reproduce locally → binary search"
821
- - "User always writes JSDoc comments before implementing functions"
822
-
823
- **Requirements:**
824
- - Must describe HOW user does something
825
- - Must be a repeated, consistent pattern (seen 3+ times or explicitly stated as standard practice)
826
- - Must be a workflow, methodology, or skill application
827
- - Not one-off preferences
828
-
829
- # ULTRA-STRICT EXTRACTION CRITERIA
830
-
831
- ## ✅ DO EXTRACT (Only These):
832
-
833
- **EPISODIC:**
834
- - Significant completed projects or milestones
835
- - Important bugs, incidents, or problems encountered
836
- - Major decisions made with lasting impact
837
- - Formative experiences that shape future work
838
-
839
- **SEMANTIC:**
840
- - Professional identity (role, title, company)
841
- - Core expertise and specializations (stated explicitly or demonstrated conclusively)
842
- - Primary languages, frameworks, or tools (not exploratory use)
843
- - Established facts about their work context
844
-
845
- **PROCEDURAL:**
846
- - Consistent workflows demonstrated 3+ times or explicitly stated
847
- - Standard practices user always follows
848
- - Methodology preferences with clear rationale
849
- - Debugging, testing, or development processes
850
-
851
- ## ❌ NEVER EXTRACT:
852
-
853
- - **One-time requests or tasks** (e.g., "can you generate an image", "help me debug this")
854
- - **Casual conversations** without lasting significance
855
- - **Exploratory questions** (e.g., "how does X work?")
856
- - **Temporary context** (current bug, today's task)
857
- - **Preferences from single occurrence** (e.g., user asked for code once)
858
- - **Social pleasantries** (thank you, greetings)
859
- - **Testing or experimentation** (trying out a feature)
860
- - **Common patterns everyone has** (likes clear explanations)
861
- - **Situational information** (working on feature X today)
862
- - **Opinions without persistence** (single complaint, isolated praise)
863
- - **General knowledge** (not specific to user)
864
-
865
- # Quality Gates (ALL Must Pass)
866
-
867
- 1. **Significance Test**: Will this matter in 3+ months?
868
- 2. **Specificity Test**: Is this concrete and actionable?
869
- 3. **Evidence Test**: Is there strong evidence (3+ instances OR explicit self-identification)?
870
- 4. **Uniqueness Test**: Is this specific to THIS user (not generic)?
871
- 5. **Confidence Test**: Confidence must be >= 0.85 (be VERY conservative)
872
- 6. **Non-Redundancy Test**: Does this add NEW information not in existing memories?
873
-
874
- # Confidence Scoring (Be Conservative)
875
-
876
- - **0.95-1.0**: User explicitly stated as core identity/practice AND demonstrated multiple times
877
- - **0.85-0.94**: User explicitly stated OR consistently demonstrated 5+ times
878
- - **0.75-0.84**: Strong pattern (3-4 instances) with supporting context
879
- - **Below 0.75**: DO NOT EXTRACT (insufficient evidence)
880
-
881
- # Critical Instructions
882
-
883
- 1. **Default to NOT extracting** - When in doubt, skip it
884
- 2. **Require overwhelming evidence** - One or two mentions is NOT enough
885
- 3. **Focus on what's PERSISTENT** - Not what's temporary or situational
886
- 4. **Verify against existing memories** - Don't duplicate or contradict
887
- 5. **Maximum 2-3 extractions per run** - Quality over quantity
888
-
889
- **If there are no qualifying facts (which is common), respond with <memories></memories>**
890
-
891
- # Response Format
892
-
893
- <memories>
894
- <memory>
895
- <category>semantic</category>
896
- <content>User is a senior TypeScript developer with 8 years of backend experience</content>
897
- <confidence>0.95</confidence>
898
- </memory>
899
- <memory>
900
- <category>procedural</category>
901
- <content>User follows TDD workflow: writes tests before implementation, runs tests after each change</content>
902
- <confidence>0.88</confidence>
903
- </memory>
904
- <memory>
905
- <category>episodic</category>
906
- <content>User led database migration from MongoDB to PostgreSQL for payment system in Q2 2024</content>
907
- <confidence>0.92</confidence>
908
- </memory>
909
- </memories>`;
910
- function parseMemoryExtractionXML(xml) {
911
- const memoryMatches = xml.matchAll(/<memory>[\s\S]*?<category>(.*?)<\/category>[\s\S]*?<content>(.*?)<\/content>[\s\S]*?<confidence>(.*?)<\/confidence>[\s\S]*?<\/memory>/g);
912
- const extractions = [];
913
- for (const match of memoryMatches) {
914
- const category = match[1].trim();
915
- const content = match[2].trim();
916
- const confidence = parseFloat(match[3].trim());
917
- if (!Object.values(LongTermMemoryCategory).includes(category)) {
918
- import_core3.logger.warn(`Invalid memory category: ${category}`);
919
- continue;
920
- }
921
- if (content && !isNaN(confidence)) {
922
- extractions.push({ category, content, confidence });
923
- }
924
- }
925
- return extractions;
926
- }
927
- var longTermExtractionEvaluator = {
928
- name: "LONG_TERM_MEMORY_EXTRACTION",
929
- description: "Extracts long-term facts about users from conversations",
930
- similes: ["MEMORY_EXTRACTION", "FACT_LEARNING", "USER_PROFILING"],
931
- alwaysRun: true,
932
- validate: async (runtime, message) => {
933
- if (message.entityId === runtime.agentId) {
934
- return false;
935
- }
936
- if (!message.content?.text) {
937
- return false;
938
- }
939
- const memoryService = runtime.getService("memory");
940
- if (!memoryService) {
941
- return false;
942
- }
943
- const config = memoryService.getConfig();
944
- if (!config.longTermExtractionEnabled) {
945
- import_core3.logger.debug("Long-term memory extraction is disabled");
946
- return false;
947
- }
948
- const currentMessageCount = await runtime.countMemories(message.roomId, false, "messages");
949
- const shouldRun = await memoryService.shouldRunExtraction(message.entityId, message.roomId, currentMessageCount);
950
- return shouldRun;
951
- },
952
- handler: async (runtime, message) => {
953
- const memoryService = runtime.getService("memory");
954
- if (!memoryService) {
955
- import_core3.logger.error("MemoryService not found");
956
- return;
957
- }
958
- const config = memoryService.getConfig();
959
- const { entityId, roomId } = message;
960
- try {
961
- import_core3.logger.info(`Extracting long-term memories for entity ${entityId}`);
962
- const recentMessages = await runtime.getMemories({
963
- tableName: "messages",
964
- roomId,
965
- count: 20,
966
- unique: false
967
- });
968
- const formattedMessages = recentMessages.sort((a, b) => (a.createdAt || 0) - (b.createdAt || 0)).map((msg) => {
969
- const sender = msg.entityId === runtime.agentId ? runtime.character.name : "User";
970
- return `${sender}: ${msg.content.text || "[non-text message]"}`;
971
- }).join(`
972
- `);
973
- const existingMemories = await memoryService.getLongTermMemories(entityId, undefined, 30);
974
- const formattedExisting = existingMemories.length > 0 ? existingMemories.map((m) => `[${m.category}] ${m.content} (confidence: ${m.confidence})`).join(`
975
- `) : "None yet";
976
- const state = await runtime.composeState(message);
977
- const prompt = import_core3.composePromptFromState({
978
- state: {
979
- ...state,
980
- recentMessages: formattedMessages,
981
- existingMemories: formattedExisting
982
- },
983
- template: extractionTemplate
984
- });
985
- const response = await runtime.useModel(import_core3.ModelType.TEXT_LARGE, {
986
- prompt
987
- });
988
- const extractions = parseMemoryExtractionXML(response);
989
- import_core3.logger.info(`Extracted ${extractions.length} long-term memories`);
990
- for (const extraction of extractions) {
991
- if (extraction.confidence >= Math.max(config.longTermConfidenceThreshold, 0.85)) {
992
- await memoryService.storeLongTermMemory({
993
- agentId: runtime.agentId,
994
- entityId,
995
- category: extraction.category,
996
- content: extraction.content,
997
- confidence: extraction.confidence,
998
- source: "conversation",
999
- metadata: {
1000
- roomId,
1001
- extractedAt: new Date().toISOString()
1002
- }
1003
- });
1004
- import_core3.logger.info(`Stored long-term memory: [${extraction.category}] ${extraction.content.substring(0, 50)}...`);
1005
- } else {
1006
- import_core3.logger.debug(`Skipped low-confidence memory: ${extraction.content} (confidence: ${extraction.confidence}, threshold: ${Math.max(config.longTermConfidenceThreshold, 0.85)})`);
1007
- }
1008
- }
1009
- const currentMessageCount = await runtime.countMemories(roomId, false, "messages");
1010
- await memoryService.setLastExtractionCheckpoint(entityId, roomId, currentMessageCount);
1011
- import_core3.logger.debug(`Updated extraction checkpoint to ${currentMessageCount} for entity ${entityId} in room ${roomId}`);
1012
- } catch (error) {
1013
- import_core3.logger.error({ error }, "Error during long-term memory extraction:");
1014
- }
1015
- },
1016
- examples: []
1017
- };
1018
-
1019
- // src/providers/long-term-memory.ts
1020
- var import_core4 = require("@elizaos/core");
1021
- var longTermMemoryProvider = {
1022
- name: "LONG_TERM_MEMORY",
1023
- description: "Persistent facts and preferences about the user",
1024
- position: 50,
1025
- get: async (runtime, message, _state) => {
1026
- try {
1027
- const memoryService = runtime.getService("memory");
1028
- if (!memoryService) {
1029
- return {
1030
- data: { memories: [] },
1031
- values: { longTermMemories: "" },
1032
- text: ""
1033
- };
1034
- }
1035
- const { entityId } = message;
1036
- if (entityId === runtime.agentId) {
1037
- return {
1038
- data: { memories: [] },
1039
- values: { longTermMemories: "" },
1040
- text: ""
1041
- };
1042
- }
1043
- const memories = await memoryService.getLongTermMemories(entityId, undefined, 25);
1044
- if (memories.length === 0) {
1045
- return {
1046
- data: { memories: [] },
1047
- values: { longTermMemories: "" },
1048
- text: ""
1049
- };
1050
- }
1051
- const formattedMemories = await memoryService.getFormattedLongTermMemories(entityId);
1052
- const text4 = import_core4.addHeader("# What I Know About You", formattedMemories);
1053
- const categoryCounts = new Map;
1054
- for (const memory of memories) {
1055
- const count = categoryCounts.get(memory.category) || 0;
1056
- categoryCounts.set(memory.category, count + 1);
1057
- }
1058
- const categoryList = Array.from(categoryCounts.entries()).map(([cat, count]) => `${cat}: ${count}`).join(", ");
1059
- return {
1060
- data: {
1061
- memories,
1062
- categoryCounts: Object.fromEntries(categoryCounts)
1063
- },
1064
- values: {
1065
- longTermMemories: text4,
1066
- memoryCategories: categoryList
1067
- },
1068
- text: text4
1069
- };
1070
- } catch (error) {
1071
- import_core4.logger.error({ error }, "Error in longTermMemoryProvider:");
1072
- return {
1073
- data: { memories: [] },
1074
- values: { longTermMemories: "" },
1075
- text: ""
1076
- };
1077
- }
1078
- }
1079
- };
1080
-
1081
- // src/providers/context-summary.ts
1082
- var import_core5 = require("@elizaos/core");
1083
- var contextSummaryProvider = {
1084
- name: "SUMMARIZED_CONTEXT",
1085
- description: "Provides summarized context from previous conversations",
1086
- position: 96,
1087
- get: async (runtime, message, _state) => {
1088
- try {
1089
- const memoryService = runtime.getService("memory");
1090
- const { roomId } = message;
1091
- if (!memoryService) {
1092
- return {
1093
- data: {
1094
- summary: null
1095
- },
1096
- values: {
1097
- sessionSummaries: "",
1098
- sessionSummariesWithTopics: ""
1099
- },
1100
- text: ""
1101
- };
1102
- }
1103
- const currentSummary = await memoryService.getCurrentSessionSummary(roomId);
1104
- if (!currentSummary) {
1105
- return {
1106
- data: {
1107
- summary: null
1108
- },
1109
- values: {
1110
- sessionSummaries: "",
1111
- sessionSummariesWithTopics: ""
1112
- },
1113
- text: ""
1114
- };
1115
- }
1116
- const messageRange = `${currentSummary.messageCount} messages`;
1117
- const timeRange = new Date(currentSummary.startTime).toLocaleDateString();
1118
- let summaryOnly = `**Previous Conversation** (${messageRange}, ${timeRange})
1119
- `;
1120
- summaryOnly += currentSummary.summary;
1121
- let summaryWithTopics = summaryOnly;
1122
- if (currentSummary.topics && currentSummary.topics.length > 0) {
1123
- summaryWithTopics += `
1124
- *Topics: ${currentSummary.topics.join(", ")}*`;
1125
- }
1126
- const sessionSummaries2 = import_core5.addHeader("# Conversation Summary", summaryOnly);
1127
- const sessionSummariesWithTopics = import_core5.addHeader("# Conversation Summary", summaryWithTopics);
1128
- return {
1129
- data: {
1130
- summary: currentSummary
1131
- },
1132
- values: {
1133
- sessionSummaries: sessionSummaries2,
1134
- sessionSummariesWithTopics
1135
- },
1136
- text: sessionSummariesWithTopics
1137
- };
1138
- } catch (error) {
1139
- import_core5.logger.error({ error }, "Error in contextSummaryProvider:");
1140
- return {
1141
- data: {
1142
- summary: null
1143
- },
1144
- values: {
1145
- sessionSummaries: "",
1146
- sessionSummariesWithTopics: ""
1147
- },
1148
- text: ""
1149
- };
1150
- }
1151
- }
1152
- };
1153
-
1154
- // src/index.ts
1155
- var memoryPlugin = {
1156
- name: "memory",
1157
- description: "Advanced memory management with conversation summarization and long-term persistent memory",
1158
- services: [MemoryService],
1159
- evaluators: [summarizationEvaluator, longTermExtractionEvaluator],
1160
- providers: [
1161
- longTermMemoryProvider,
1162
- contextSummaryProvider
1163
- ],
1164
- schema: exports_schemas
1165
- };
1166
- var src_default = memoryPlugin;
1167
-
1168
- //# debugId=F9F8FE6AD7DE8BD864756E2164756E21