@mastra/memory 0.0.0-commonjs-20250227130920

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 ADDED
@@ -0,0 +1,259 @@
1
+ import { deepMerge } from '@mastra/core';
2
+ import { MastraMemory } from '@mastra/core/memory';
3
+ import { embed } from 'ai';
4
+
5
+ // src/index.ts
6
+ var Memory = class extends MastraMemory {
7
+ constructor(config = {}) {
8
+ super({ name: "Memory", ...config });
9
+ const mergedConfig = this.getMergedThreadConfig({
10
+ workingMemory: config.options?.workingMemory || {
11
+ enabled: false,
12
+ template: this.defaultWorkingMemoryTemplate
13
+ }
14
+ });
15
+ this.threadConfig = mergedConfig;
16
+ }
17
+ async query({
18
+ threadId,
19
+ selectBy,
20
+ threadConfig
21
+ }) {
22
+ let vectorResults = null;
23
+ this.logger.debug(`Memory query() with:`, {
24
+ threadId,
25
+ selectBy,
26
+ threadConfig
27
+ });
28
+ const config = this.getMergedThreadConfig(threadConfig || {});
29
+ const vectorConfig = typeof config?.semanticRecall === `boolean` ? {
30
+ topK: 2,
31
+ messageRange: { before: 2, after: 2 }
32
+ } : {
33
+ topK: config?.semanticRecall?.topK ?? 2,
34
+ messageRange: config?.semanticRecall?.messageRange ?? { before: 2, after: 2 }
35
+ };
36
+ if (config?.semanticRecall && selectBy?.vectorSearchString && this.vector) {
37
+ const { embedding } = await embed({
38
+ value: selectBy.vectorSearchString,
39
+ model: this.embedder
40
+ });
41
+ const { indexName } = await this.createEmbeddingIndex();
42
+ vectorResults = await this.vector.query(indexName, embedding, vectorConfig.topK, {
43
+ thread_id: threadId
44
+ });
45
+ }
46
+ const rawMessages = await this.storage.__getMessages({
47
+ threadId,
48
+ selectBy: {
49
+ ...selectBy,
50
+ ...vectorResults?.length ? {
51
+ include: vectorResults.map((r) => ({
52
+ id: r.metadata?.message_id,
53
+ withNextMessages: typeof vectorConfig.messageRange === "number" ? vectorConfig.messageRange : vectorConfig.messageRange.after,
54
+ withPreviousMessages: typeof vectorConfig.messageRange === "number" ? vectorConfig.messageRange : vectorConfig.messageRange.before
55
+ }))
56
+ } : {}
57
+ },
58
+ threadConfig: config
59
+ });
60
+ const messages = this.parseMessages(rawMessages);
61
+ const uiMessages = this.convertToUIMessages(rawMessages);
62
+ return { messages, uiMessages };
63
+ }
64
+ async rememberMessages({
65
+ threadId,
66
+ vectorMessageSearch,
67
+ config
68
+ }) {
69
+ const threadConfig = this.getMergedThreadConfig(config || {});
70
+ if (!threadConfig.lastMessages && !threadConfig.semanticRecall) {
71
+ return {
72
+ messages: [],
73
+ uiMessages: []
74
+ };
75
+ }
76
+ const messages = await this.query({
77
+ threadId,
78
+ selectBy: {
79
+ last: threadConfig.lastMessages,
80
+ vectorSearchString: threadConfig.semanticRecall && vectorMessageSearch ? vectorMessageSearch : void 0
81
+ },
82
+ threadConfig: config
83
+ });
84
+ this.logger.debug(`Remembered message history includes ${messages.messages.length} messages.`);
85
+ return messages;
86
+ }
87
+ async getThreadById({ threadId }) {
88
+ return this.storage.__getThreadById({ threadId });
89
+ }
90
+ async getThreadsByResourceId({ resourceId }) {
91
+ return this.storage.__getThreadsByResourceId({ resourceId });
92
+ }
93
+ async saveThread({
94
+ thread,
95
+ memoryConfig
96
+ }) {
97
+ const config = this.getMergedThreadConfig(memoryConfig || {});
98
+ if (config.workingMemory?.enabled && !thread?.metadata?.workingMemory) {
99
+ return this.storage.__saveThread({
100
+ thread: deepMerge(thread, {
101
+ metadata: {
102
+ workingMemory: config.workingMemory.template || this.defaultWorkingMemoryTemplate
103
+ }
104
+ })
105
+ });
106
+ }
107
+ return this.storage.__saveThread({ thread });
108
+ }
109
+ async updateThread({
110
+ id,
111
+ title,
112
+ metadata
113
+ }) {
114
+ return this.storage.__updateThread({
115
+ id,
116
+ title,
117
+ metadata
118
+ });
119
+ }
120
+ async deleteThread(threadId) {
121
+ await this.storage.__deleteThread({ threadId });
122
+ }
123
+ async saveMessages({
124
+ messages,
125
+ memoryConfig
126
+ }) {
127
+ await this.saveWorkingMemory(messages);
128
+ this.mutateMessagesToHideWorkingMemory(messages);
129
+ const config = this.getMergedThreadConfig(memoryConfig);
130
+ if (this.vector && config.semanticRecall) {
131
+ const { indexName } = await this.createEmbeddingIndex();
132
+ for (const message of messages) {
133
+ if (typeof message.content !== `string`) continue;
134
+ const { embedding } = await embed({ value: message.content, model: this.embedder, maxRetries: 3 });
135
+ await this.vector.upsert(
136
+ indexName,
137
+ [embedding],
138
+ [
139
+ {
140
+ text: message.content,
141
+ message_id: message.id,
142
+ thread_id: message.threadId
143
+ }
144
+ ]
145
+ );
146
+ }
147
+ }
148
+ return this.storage.__saveMessages({ messages });
149
+ }
150
+ mutateMessagesToHideWorkingMemory(messages) {
151
+ const workingMemoryRegex = /<working_memory>([^]*?)<\/working_memory>/g;
152
+ for (const message of messages) {
153
+ if (typeof message?.content === `string`) {
154
+ message.content = message.content.replace(workingMemoryRegex, ``).trim();
155
+ } else if (Array.isArray(message?.content)) {
156
+ for (const content of message.content) {
157
+ if (content.type === `text`) {
158
+ content.text = content.text.replace(workingMemoryRegex, ``).trim();
159
+ }
160
+ }
161
+ }
162
+ }
163
+ }
164
+ parseWorkingMemory(text) {
165
+ if (!this.threadConfig.workingMemory?.enabled) return null;
166
+ const workingMemoryRegex = /<working_memory>([^]*?)<\/working_memory>/g;
167
+ const matches = text.match(workingMemoryRegex);
168
+ const match = matches?.[0];
169
+ if (match) {
170
+ return match.replace(/<\/?working_memory>/g, "").trim();
171
+ }
172
+ return null;
173
+ }
174
+ async getWorkingMemory({ threadId }) {
175
+ if (!this.threadConfig.workingMemory?.enabled) return null;
176
+ const thread = await this.storage.__getThreadById({ threadId });
177
+ if (!thread) return this.threadConfig?.workingMemory?.template || this.defaultWorkingMemoryTemplate;
178
+ const memory = thread.metadata?.workingMemory || this.threadConfig.workingMemory.template || this.defaultWorkingMemoryTemplate;
179
+ return memory.split(`>
180
+ `).map((c) => c.trim()).join(`>`);
181
+ }
182
+ async saveWorkingMemory(messages) {
183
+ const latestMessage = messages[messages.length - 1];
184
+ if (!latestMessage || !this.threadConfig.workingMemory?.enabled) {
185
+ return;
186
+ }
187
+ const latestContent = !latestMessage?.content ? null : typeof latestMessage.content === "string" ? latestMessage.content : latestMessage.content.filter((c) => c.type === "text").map((c) => c.text).join("\n");
188
+ const threadId = latestMessage?.threadId;
189
+ if (!latestContent || !threadId) {
190
+ return;
191
+ }
192
+ const newMemory = this.parseWorkingMemory(latestContent);
193
+ if (!newMemory) {
194
+ return;
195
+ }
196
+ const thread = await this.storage.__getThreadById({ threadId });
197
+ if (!thread) return;
198
+ await this.storage.__updateThread({
199
+ id: thread.id,
200
+ title: thread.title || "",
201
+ metadata: deepMerge(thread.metadata || {}, {
202
+ workingMemory: newMemory
203
+ })
204
+ });
205
+ return newMemory;
206
+ }
207
+ async getSystemMessage({
208
+ threadId,
209
+ memoryConfig
210
+ }) {
211
+ const config = this.getMergedThreadConfig(memoryConfig);
212
+ if (!config.workingMemory?.enabled) {
213
+ return null;
214
+ }
215
+ const workingMemory = await this.getWorkingMemory({ threadId });
216
+ if (!workingMemory) {
217
+ return null;
218
+ }
219
+ return this.getWorkingMemoryWithInstruction(workingMemory);
220
+ }
221
+ defaultWorkingMemoryTemplate = `
222
+ <user>
223
+ <first_name></first_name>
224
+ <last_name></last_name>
225
+ <location></location>
226
+ <occupation></occupation>
227
+ <interests></interests>
228
+ <goals></goals>
229
+ <events></events>
230
+ <facts></facts>
231
+ <projects></projects>
232
+ </user>
233
+ `;
234
+ getWorkingMemoryWithInstruction(workingMemoryBlock) {
235
+ return `WORKING_MEMORY_SYSTEM_INSTRUCTION:
236
+ 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!
237
+
238
+ Guidelines:
239
+ 1. Store anything that could be useful later in the conversation
240
+ 2. Update proactively when information changes, no matter how small
241
+ 3. Use nested tags for all data
242
+ 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"
243
+
244
+ Memory Structure:
245
+ <working_memory>
246
+ ${workingMemoryBlock}
247
+ </working_memory>
248
+
249
+ Notes:
250
+ - Update memory whenever referenced information changes
251
+ - If you're unsure whether to store something, store it (eg if the user tells you their name or the value of another empty section in your working memory, output the <working_memory> block immediately to update it)
252
+ - 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
253
+ - Do not remove empty sections - you must output the empty sections along with the ones you're filling in
254
+ - 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.
255
+ - IMPORTANT: You MUST output the <working_memory> block in every response to a prompt where you received relevant information. `;
256
+ }
257
+ };
258
+
259
+ export { Memory };
@@ -0,0 +1,12 @@
1
+ import { createConfig } from '@internal/lint/eslint';
2
+
3
+ const config = await createConfig();
4
+
5
+ /** @type {import("eslint").Linter.Config[]} */
6
+ export default [
7
+ ...config,
8
+ {
9
+ files: ['integration-tests/**/*'],
10
+ ...(await import('typescript-eslint')).configs.disableTypeChecked,
11
+ },
12
+ ];
package/package.json ADDED
@@ -0,0 +1,72 @@
1
+ {
2
+ "name": "@mastra/memory",
3
+ "version": "0.0.0-commonjs-20250227130920",
4
+ "description": "",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "import": {
11
+ "types": "./dist/index.d.ts",
12
+ "default": "./dist/index.js"
13
+ },
14
+ "require": {
15
+ "types": "./dist/index.d.cts",
16
+ "default": "./dist/index.cjs"
17
+ }
18
+ },
19
+ "./kv-upstash": {
20
+ "import": {
21
+ "types": "./dist/kv/upstash.d.ts",
22
+ "default": "./dist/kv/upstash.js"
23
+ },
24
+ "require": {
25
+ "types": "./dist/kv/upstash.d.cts",
26
+ "default": "./dist/kv/upstash.cjs"
27
+ }
28
+ },
29
+ "./postgres": {
30
+ "import": {
31
+ "types": "./dist/postgres/index.d.ts",
32
+ "default": "./dist/postgres/index.js"
33
+ },
34
+ "require": {
35
+ "types": "./dist/postgres/index.d.cts",
36
+ "default": "./dist/postgres/index.cjs"
37
+ }
38
+ },
39
+ "./package.json": "./package.json"
40
+ },
41
+ "keywords": [],
42
+ "author": "",
43
+ "license": "ISC",
44
+ "dependencies": {
45
+ "@upstash/redis": "^1.34.3",
46
+ "ai": "^4.0.12",
47
+ "pg": "^8.13.1",
48
+ "pg-pool": "^3.7.0",
49
+ "postgres": "^3.4.5",
50
+ "redis": "^4.7.0",
51
+ "@mastra/core": "^0.0.0-commonjs-20250227130920"
52
+ },
53
+ "devDependencies": {
54
+ "@microsoft/api-extractor": "^7.49.2",
55
+ "@types/node": "^22.13.1",
56
+ "@types/pg": "^8.11.10",
57
+ "eslint": "^9.20.1",
58
+ "tsup": "^8.0.1",
59
+ "typescript": "^5.7.3",
60
+ "typescript-eslint": "^8.20.0",
61
+ "vitest": "^3.0.4",
62
+ "@internal/lint": "0.0.0"
63
+ },
64
+ "scripts": {
65
+ "check": "tsc --noEmit",
66
+ "build": "pnpm run check && tsup src/index.ts --format esm,cjs --experimental-dts --clean --treeshake",
67
+ "build:watch": "pnpm build --watch",
68
+ "test:integration": "cd integration-tests && pnpm run test",
69
+ "test": "pnpm test:integration",
70
+ "lint": "eslint ."
71
+ }
72
+ }