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