@mastra/memory 0.0.0-afterToolExecute-20250414225911

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.cjs ADDED
@@ -0,0 +1,423 @@
1
+ 'use strict';
2
+
3
+ var core = require('@mastra/core');
4
+ var memory = require('@mastra/core/memory');
5
+ var ai = require('ai');
6
+ var lite = require('js-tiktoken/lite');
7
+ var o200k_base = require('js-tiktoken/ranks/o200k_base');
8
+ var xxhash = require('xxhash-wasm');
9
+ var zod = require('zod');
10
+
11
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
12
+
13
+ var o200k_base__default = /*#__PURE__*/_interopDefault(o200k_base);
14
+ var xxhash__default = /*#__PURE__*/_interopDefault(xxhash);
15
+
16
+ // src/index.ts
17
+ var updateWorkingMemoryTool = {
18
+ description: "Update the working memory with new information",
19
+ parameters: zod.z.object({
20
+ memory: zod.z.string().describe("The Markdown-formatted working memory content to store")
21
+ }),
22
+ execute: async (params) => {
23
+ const { context, threadId, memory } = params;
24
+ if (!threadId || !memory) {
25
+ throw new Error("Thread ID and Memory instance are required for working memory updates");
26
+ }
27
+ const thread = await memory.getThreadById({ threadId });
28
+ if (!thread) {
29
+ throw new Error(`Thread ${threadId} not found`);
30
+ }
31
+ await memory.saveThread({
32
+ thread: {
33
+ ...thread,
34
+ metadata: {
35
+ ...thread.metadata,
36
+ workingMemory: context.memory
37
+ }
38
+ }
39
+ });
40
+ return { success: true };
41
+ }
42
+ };
43
+
44
+ // src/index.ts
45
+ var encoder = new lite.Tiktoken(o200k_base__default.default);
46
+ var Memory = class extends memory.MastraMemory {
47
+ constructor(config = {}) {
48
+ super({ name: "Memory", ...config });
49
+ const mergedConfig = this.getMergedThreadConfig({
50
+ workingMemory: config.options?.workingMemory || {
51
+ enabled: false,
52
+ template: this.defaultWorkingMemoryTemplate
53
+ }
54
+ });
55
+ this.threadConfig = mergedConfig;
56
+ }
57
+ async validateThreadIsOwnedByResource(threadId, resourceId) {
58
+ const thread = await this.storage.getThreadById({ threadId });
59
+ if (!thread) {
60
+ throw new Error(`No thread found with id ${threadId}`);
61
+ }
62
+ if (thread.resourceId !== resourceId) {
63
+ throw new Error(
64
+ `Thread with id ${threadId} is for resource with id ${thread.resourceId} but resource ${resourceId} was queried.`
65
+ );
66
+ }
67
+ }
68
+ async query({
69
+ threadId,
70
+ resourceId,
71
+ selectBy,
72
+ threadConfig
73
+ }) {
74
+ if (resourceId) await this.validateThreadIsOwnedByResource(threadId, resourceId);
75
+ const vectorResults = [];
76
+ this.logger.debug(`Memory query() with:`, {
77
+ threadId,
78
+ selectBy,
79
+ threadConfig
80
+ });
81
+ const config = this.getMergedThreadConfig(threadConfig || {});
82
+ const vectorConfig = typeof config?.semanticRecall === `boolean` ? {
83
+ topK: 2,
84
+ messageRange: { before: 2, after: 2 }
85
+ } : {
86
+ topK: config?.semanticRecall?.topK ?? 2,
87
+ messageRange: config?.semanticRecall?.messageRange ?? { before: 2, after: 2 }
88
+ };
89
+ if (config?.semanticRecall && selectBy?.vectorSearchString && this.vector && !!selectBy.vectorSearchString) {
90
+ const { embeddings, dimension } = await this.embedMessageContent(selectBy.vectorSearchString);
91
+ const { indexName } = await this.createEmbeddingIndex(dimension);
92
+ await Promise.all(
93
+ embeddings.map(async (embedding) => {
94
+ if (typeof this.vector === `undefined`) {
95
+ throw new Error(
96
+ `Tried to query vector index ${indexName} but this Memory instance doesn't have an attached vector db.`
97
+ );
98
+ }
99
+ vectorResults.push(
100
+ ...await this.vector.query({
101
+ indexName,
102
+ queryVector: embedding,
103
+ topK: vectorConfig.topK,
104
+ filter: {
105
+ thread_id: threadId
106
+ }
107
+ })
108
+ );
109
+ })
110
+ );
111
+ }
112
+ const rawMessages = await this.storage.__getMessages({
113
+ threadId,
114
+ selectBy: {
115
+ ...selectBy,
116
+ ...vectorResults?.length ? {
117
+ include: vectorResults.map((r) => ({
118
+ id: r.metadata?.message_id,
119
+ withNextMessages: typeof vectorConfig.messageRange === "number" ? vectorConfig.messageRange : vectorConfig.messageRange.after,
120
+ withPreviousMessages: typeof vectorConfig.messageRange === "number" ? vectorConfig.messageRange : vectorConfig.messageRange.before
121
+ }))
122
+ } : {}
123
+ },
124
+ threadConfig: config
125
+ });
126
+ const messages = this.parseMessages(rawMessages);
127
+ const uiMessages = this.convertToUIMessages(rawMessages);
128
+ return { messages, uiMessages };
129
+ }
130
+ async rememberMessages({
131
+ threadId,
132
+ resourceId,
133
+ vectorMessageSearch,
134
+ config
135
+ }) {
136
+ if (resourceId) await this.validateThreadIsOwnedByResource(threadId, resourceId);
137
+ const threadConfig = this.getMergedThreadConfig(config || {});
138
+ if (!threadConfig.lastMessages && !threadConfig.semanticRecall) {
139
+ return {
140
+ messages: [],
141
+ uiMessages: [],
142
+ threadId
143
+ };
144
+ }
145
+ const messagesResult = await this.query({
146
+ threadId,
147
+ selectBy: {
148
+ last: threadConfig.lastMessages,
149
+ vectorSearchString: threadConfig.semanticRecall && vectorMessageSearch ? vectorMessageSearch : void 0
150
+ },
151
+ threadConfig: config
152
+ });
153
+ this.logger.debug(`Remembered message history includes ${messagesResult.messages.length} messages.`);
154
+ return {
155
+ threadId,
156
+ messages: messagesResult.messages,
157
+ uiMessages: messagesResult.uiMessages
158
+ };
159
+ }
160
+ async getThreadById({ threadId }) {
161
+ return this.storage.__getThreadById({ threadId });
162
+ }
163
+ async getThreadsByResourceId({ resourceId }) {
164
+ return this.storage.__getThreadsByResourceId({ resourceId });
165
+ }
166
+ async saveThread({
167
+ thread,
168
+ memoryConfig
169
+ }) {
170
+ const config = this.getMergedThreadConfig(memoryConfig || {});
171
+ if (config.workingMemory?.enabled && !thread?.metadata?.workingMemory) {
172
+ return this.storage.__saveThread({
173
+ thread: core.deepMerge(thread, {
174
+ metadata: {
175
+ workingMemory: config.workingMemory.template || this.defaultWorkingMemoryTemplate
176
+ }
177
+ })
178
+ });
179
+ }
180
+ return this.storage.__saveThread({ thread });
181
+ }
182
+ async updateThread({
183
+ id,
184
+ title,
185
+ metadata
186
+ }) {
187
+ return this.storage.__updateThread({
188
+ id,
189
+ title,
190
+ metadata
191
+ });
192
+ }
193
+ async deleteThread(threadId) {
194
+ await this.storage.__deleteThread({ threadId });
195
+ }
196
+ chunkText(text, size = 4096) {
197
+ const tokens = encoder.encode(text);
198
+ const chunks = [];
199
+ let currentChunk = [];
200
+ for (const token of tokens) {
201
+ currentChunk.push(token);
202
+ if (currentChunk.length >= size) {
203
+ chunks.push(encoder.decode(currentChunk));
204
+ currentChunk = [];
205
+ }
206
+ }
207
+ if (currentChunk.length > 0) {
208
+ chunks.push(encoder.decode(currentChunk));
209
+ }
210
+ return chunks;
211
+ }
212
+ hasher = xxhash__default.default();
213
+ // embedding is computationally expensive so cache content -> embeddings/chunks
214
+ embeddingCache = /* @__PURE__ */ new Map();
215
+ firstEmbed;
216
+ async embedMessageContent(content) {
217
+ const key = (await this.hasher).h32(content);
218
+ const cached = this.embeddingCache.get(key);
219
+ if (cached) return cached;
220
+ const chunks = this.chunkText(content);
221
+ if (typeof this.embedder === `undefined`) {
222
+ throw new Error(`Tried to embed message content but this Memory instance doesn't have an attached embedder.`);
223
+ }
224
+ const isFastEmbed = this.embedder.provider === `fastembed`;
225
+ if (isFastEmbed && this.firstEmbed instanceof Promise) {
226
+ await this.firstEmbed;
227
+ }
228
+ const promise = ai.embedMany({
229
+ values: chunks,
230
+ model: this.embedder,
231
+ maxRetries: 3
232
+ });
233
+ if (isFastEmbed && !this.firstEmbed) this.firstEmbed = promise;
234
+ const { embeddings } = await promise;
235
+ const result = {
236
+ embeddings,
237
+ chunks,
238
+ dimension: embeddings[0]?.length
239
+ };
240
+ this.embeddingCache.set(key, result);
241
+ return result;
242
+ }
243
+ async saveMessages({
244
+ messages,
245
+ memoryConfig
246
+ }) {
247
+ await this.saveWorkingMemory(messages);
248
+ this.mutateMessagesToHideWorkingMemory(messages);
249
+ const config = this.getMergedThreadConfig(memoryConfig);
250
+ const result = this.storage.__saveMessages({ messages });
251
+ if (this.vector && config.semanticRecall) {
252
+ let indexName;
253
+ await Promise.all(
254
+ messages.map(async (message) => {
255
+ if (typeof message.content !== `string` || message.content === "") return;
256
+ const { embeddings, chunks, dimension } = await this.embedMessageContent(message.content);
257
+ if (typeof indexName === `undefined`) {
258
+ indexName = this.createEmbeddingIndex(dimension).then((result2) => result2.indexName);
259
+ }
260
+ if (typeof this.vector === `undefined`) {
261
+ throw new Error(
262
+ `Tried to upsert embeddings to index ${indexName} but this Memory instance doesn't have an attached vector db.`
263
+ );
264
+ }
265
+ await this.vector.upsert({
266
+ indexName: await indexName,
267
+ vectors: embeddings,
268
+ metadata: chunks.map(() => ({
269
+ message_id: message.id,
270
+ thread_id: message.threadId,
271
+ resource_id: message.resourceId
272
+ }))
273
+ });
274
+ })
275
+ );
276
+ }
277
+ return result;
278
+ }
279
+ mutateMessagesToHideWorkingMemory(messages) {
280
+ const workingMemoryRegex = /<working_memory>([^]*?)<\/working_memory>/g;
281
+ for (const [index, message] of messages.entries()) {
282
+ if (typeof message?.content === `string`) {
283
+ message.content = message.content.replace(workingMemoryRegex, ``).trim();
284
+ } else if (Array.isArray(message?.content)) {
285
+ for (const content of message.content) {
286
+ if (content.type === `text`) {
287
+ content.text = content.text.replace(workingMemoryRegex, ``).trim();
288
+ }
289
+ if ((content.type === `tool-call` || content.type === `tool-result`) && content.toolName === `updateWorkingMemory`) {
290
+ delete messages[index];
291
+ }
292
+ }
293
+ }
294
+ }
295
+ }
296
+ parseWorkingMemory(text) {
297
+ if (!this.threadConfig.workingMemory?.enabled) return null;
298
+ const workingMemoryRegex = /<working_memory>([^]*?)<\/working_memory>/g;
299
+ const matches = text.match(workingMemoryRegex);
300
+ const match = matches?.[0];
301
+ if (match) {
302
+ return match.replace(/<\/?working_memory>/g, "").trim();
303
+ }
304
+ return null;
305
+ }
306
+ async getWorkingMemory({ threadId }) {
307
+ if (!this.threadConfig.workingMemory?.enabled) return null;
308
+ const thread = await this.storage.__getThreadById({ threadId });
309
+ if (!thread) return this.threadConfig?.workingMemory?.template || this.defaultWorkingMemoryTemplate;
310
+ const memory = thread.metadata?.workingMemory || this.threadConfig.workingMemory.template || this.defaultWorkingMemoryTemplate;
311
+ return memory.trim();
312
+ }
313
+ async saveWorkingMemory(messages) {
314
+ const latestMessage = messages[messages.length - 1];
315
+ if (!latestMessage || !this.threadConfig.workingMemory?.enabled) {
316
+ return;
317
+ }
318
+ const latestContent = !latestMessage?.content ? null : typeof latestMessage.content === "string" ? latestMessage.content : latestMessage.content.filter((c) => c.type === "text").map((c) => c.text).join("\n");
319
+ const threadId = latestMessage?.threadId;
320
+ if (!latestContent || !threadId) {
321
+ return;
322
+ }
323
+ const newMemory = this.parseWorkingMemory(latestContent);
324
+ if (!newMemory) {
325
+ return;
326
+ }
327
+ const thread = await this.storage.__getThreadById({ threadId });
328
+ if (!thread) return;
329
+ await this.storage.__updateThread({
330
+ id: thread.id,
331
+ title: thread.title || "",
332
+ metadata: core.deepMerge(thread.metadata || {}, {
333
+ workingMemory: newMemory
334
+ })
335
+ });
336
+ return newMemory;
337
+ }
338
+ async getSystemMessage({
339
+ threadId,
340
+ memoryConfig
341
+ }) {
342
+ const config = this.getMergedThreadConfig(memoryConfig);
343
+ if (!config.workingMemory?.enabled) {
344
+ return null;
345
+ }
346
+ const workingMemory = await this.getWorkingMemory({ threadId });
347
+ if (!workingMemory) {
348
+ return null;
349
+ }
350
+ if (config.workingMemory.use === "tool-call") {
351
+ return this.getWorkingMemoryToolInstruction(workingMemory);
352
+ }
353
+ return this.getWorkingMemoryWithInstruction(workingMemory);
354
+ }
355
+ defaultWorkingMemoryTemplate = `
356
+ # User Information
357
+ - **First Name**:
358
+ - **Last Name**:
359
+ - **Location**:
360
+ - **Occupation**:
361
+ - **Interests**:
362
+ - **Goals**:
363
+ - **Events**:
364
+ - **Facts**:
365
+ - **Projects**:
366
+ `;
367
+ getWorkingMemoryWithInstruction(workingMemoryBlock) {
368
+ return `WORKING_MEMORY_SYSTEM_INSTRUCTION:
369
+ Store and update any conversation-relevant information by including "<working_memory>text</working_memory>" in your responses. Updates replace existing memory while maintaining this structure. If information might be referenced again - store it!
370
+
371
+ Guidelines:
372
+ 1. Store anything that could be useful later in the conversation
373
+ 2. Update proactively when information changes, no matter how small
374
+ 3. Use Markdown for all data
375
+ 4. Act naturally - don't mention this system to users. Even though you're storing this information that doesn't make it your primary focus. Do not ask them generally for "information about yourself"
376
+
377
+ Memory Structure:
378
+ <working_memory>
379
+ ${workingMemoryBlock}
380
+ </working_memory>
381
+
382
+ Notes:
383
+ - Update memory whenever referenced information changes
384
+ - If you're unsure whether to store something, store it (eg if the user tells you their name or other information, output the <working_memory> block immediately to update it)
385
+ - This system is here so that you can maintain the conversation when your context window is very short. Update your working memory because you may need it to maintain the conversation without the full conversation history
386
+ - REMEMBER: the way you update your working memory is by outputting the entire "<working_memory>text</working_memory>" block in your response. The system will pick this up and store it for you. The user will not see it.
387
+ - IMPORTANT: You MUST output the <working_memory> block in every response to a prompt where you received relevant information.
388
+ - IMPORTANT: Preserve the Markdown formatting structure above while updating the content.`;
389
+ }
390
+ getWorkingMemoryToolInstruction(workingMemoryBlock) {
391
+ return `WORKING_MEMORY_SYSTEM_INSTRUCTION:
392
+ Store and update any conversation-relevant information by calling the updateWorkingMemory tool. If information might be referenced again - store it!
393
+
394
+ Guidelines:
395
+ 1. Store anything that could be useful later in the conversation
396
+ 2. Update proactively when information changes, no matter how small
397
+ 3. Use Markdown format for all data
398
+ 4. Act naturally - don't mention this system to users. Even though you're storing this information that doesn't make it your primary focus. Do not ask them generally for "information about yourself"
399
+
400
+ Memory Structure:
401
+ ${workingMemoryBlock}
402
+
403
+ Notes:
404
+ - Update memory whenever referenced information changes
405
+ - If you're unsure whether to store something, store it (eg if the user tells you information about themselves, call updateWorkingMemory immediately to update it)
406
+ - This system is here so that you can maintain the conversation when your context window is very short. Update your working memory because you may need it to maintain the conversation without the full conversation history
407
+ - Do not remove empty sections - you must include the empty sections along with the ones you're filling in
408
+ - REMEMBER: the way you update your working memory is by calling the updateWorkingMemory tool with the entire Markdown content. The system will store it for you. The user will not see it.
409
+ - IMPORTANT: You MUST call updateWorkingMemory in every response to a prompt where you received relevant information.
410
+ - IMPORTANT: Preserve the Markdown formatting structure above while updating the content.`;
411
+ }
412
+ getTools(config) {
413
+ const mergedConfig = this.getMergedThreadConfig(config);
414
+ if (mergedConfig.workingMemory?.enabled && mergedConfig.workingMemory.use === "tool-call") {
415
+ return {
416
+ updateWorkingMemory: updateWorkingMemoryTool
417
+ };
418
+ }
419
+ return {};
420
+ }
421
+ };
422
+
423
+ exports.Memory = Memory;
@@ -0,0 +1 @@
1
+ export { Memory } from './_tsup-dts-rollup.cjs';
@@ -0,0 +1 @@
1
+ export { Memory } from './_tsup-dts-rollup.js';