@mastra/core 0.9.4 → 0.10.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (168) hide show
  1. package/README.md +3 -2
  2. package/dist/agent/index.cjs +2 -2
  3. package/dist/agent/index.d.cts +13 -14
  4. package/dist/agent/index.d.ts +13 -14
  5. package/dist/agent/index.js +1 -1
  6. package/dist/{base-BCfssGt6.d.ts → base-DttB7sJD.d.ts} +1187 -886
  7. package/dist/{base-CAEcd6q2.d.cts → base-aJ3etsh5.d.cts} +1187 -886
  8. package/dist/{base-H7siSAfu.d.cts → base-aPYtPBT2.d.cts} +3 -3
  9. package/dist/{base-4Z34GQL8.d.ts → base-tc5kgDTD.d.ts} +3 -3
  10. package/dist/base.cjs +2 -2
  11. package/dist/base.d.cts +2 -3
  12. package/dist/base.d.ts +2 -3
  13. package/dist/base.js +1 -1
  14. package/dist/bundler/index.cjs +2 -2
  15. package/dist/bundler/index.d.cts +2 -3
  16. package/dist/bundler/index.d.ts +2 -3
  17. package/dist/bundler/index.js +1 -1
  18. package/dist/{chunk-W4BSLENO.js → chunk-2NTUAUGH.js} +1 -1
  19. package/dist/{chunk-S34QVMKE.js → chunk-2PW6UJMW.js} +77 -10
  20. package/dist/{chunk-WE36CRQV.cjs → chunk-2U7ZZUFO.cjs} +2 -2
  21. package/dist/{workflows/vNext/index.js → chunk-3SQ3G2EJ.js} +19 -16
  22. package/dist/chunk-5HULBQ2W.cjs +38 -0
  23. package/dist/{chunk-XRGDVLM4.cjs → chunk-5JRD3NDP.cjs} +15 -15
  24. package/dist/{chunk-GXKODTLA.cjs → chunk-5W2G7S44.cjs} +83 -68
  25. package/dist/chunk-75Z4BZEE.js +36 -0
  26. package/dist/{chunk-66GQROSI.cjs → chunk-AOGUTJUO.cjs} +58 -51
  27. package/dist/{chunk-WIKOYZ63.js → chunk-BPTSLJHA.js} +9 -9
  28. package/dist/{chunk-JBJ7KXN5.js → chunk-C3ICEF6E.js} +1 -1
  29. package/dist/{chunk-E4FAXBUV.cjs → chunk-CWSFP2HS.cjs} +2 -2
  30. package/dist/{chunk-FW5RS6WV.js → chunk-E7CLY6SK.js} +42 -35
  31. package/dist/{chunk-235X76GC.js → chunk-FI7R232B.js} +2 -2
  32. package/dist/chunk-GQ2XQ4UN.js +321 -0
  33. package/dist/{chunk-H4CEZSRM.js → chunk-J7GDGV6F.js} +1 -1
  34. package/dist/{chunk-NLBJOFNG.js → chunk-JW5TMK2L.js} +1 -1
  35. package/dist/{chunk-NOPY74PV.js → chunk-KJQFFEEQ.js} +1 -1
  36. package/dist/{chunk-V2Q2FEVO.cjs → chunk-KSPHQSZX.cjs} +2 -2
  37. package/dist/{chunk-NZV4OA6P.js → chunk-LHRZV5VG.js} +2 -23
  38. package/dist/chunk-NMDM4IZN.cjs +78 -0
  39. package/dist/chunk-OBEALYTK.js +74 -0
  40. package/dist/{chunk-PEK4TY3P.js → chunk-OCT2762Q.js} +1 -1
  41. package/dist/{chunk-5DUFC7TV.cjs → chunk-P7BGXOQV.cjs} +2 -2
  42. package/dist/{chunk-WQKOM7XM.cjs → chunk-PIZM25KI.cjs} +3 -24
  43. package/dist/{chunk-S7J63JOG.cjs → chunk-RVS6OUJN.cjs} +2 -2
  44. package/dist/{chunk-5JUWUTPJ.cjs → chunk-SKG2NIZW.cjs} +2 -2
  45. package/dist/chunk-SWW4EBUZ.cjs +96 -0
  46. package/dist/{chunk-RGE4UF6A.cjs → chunk-TMPFLJLG.cjs} +2 -2
  47. package/dist/{workflows/vNext/index.cjs → chunk-TTKQ37ZZ.cjs} +24 -21
  48. package/dist/{chunk-EJITEVAB.cjs → chunk-U3L3NEOM.cjs} +81 -10
  49. package/dist/chunk-VHLL4AZK.js +90 -0
  50. package/dist/{chunk-EG74VBSP.cjs → chunk-YEULQPUY.cjs} +6 -6
  51. package/dist/{chunk-SOLXHDNQ.js → chunk-ZB3LEHL2.js} +81 -66
  52. package/dist/{chunk-TAFOICHR.js → chunk-ZKN6HYYQ.js} +1 -1
  53. package/dist/chunk-ZZDAC5KD.cjs +325 -0
  54. package/dist/deployer/index.cjs +2 -2
  55. package/dist/deployer/index.d.cts +2 -3
  56. package/dist/deployer/index.d.ts +2 -3
  57. package/dist/deployer/index.js +1 -1
  58. package/dist/eval/index.d.cts +13 -14
  59. package/dist/eval/index.d.ts +13 -14
  60. package/dist/hooks/index.d.cts +1 -1
  61. package/dist/hooks/index.d.ts +1 -1
  62. package/dist/index.cjs +88 -159
  63. package/dist/index.d.cts +17 -25
  64. package/dist/index.d.ts +17 -25
  65. package/dist/index.js +18 -25
  66. package/dist/integration/index.cjs +3 -3
  67. package/dist/integration/index.d.cts +12 -13
  68. package/dist/integration/index.d.ts +12 -13
  69. package/dist/integration/index.js +1 -1
  70. package/dist/llm/index.d.cts +13 -14
  71. package/dist/llm/index.d.ts +13 -14
  72. package/dist/logger/index.cjs +18 -17
  73. package/dist/logger/index.d.cts +42 -2
  74. package/dist/logger/index.d.ts +42 -2
  75. package/dist/logger/index.js +2 -1
  76. package/dist/{index-QV27jkxQ.d.ts → logger-EhZkzZOr.d.cts} +38 -52
  77. package/dist/{index-QV27jkxQ.d.cts → logger-EhZkzZOr.d.ts} +38 -52
  78. package/dist/mastra/index.cjs +2 -2
  79. package/dist/mastra/index.d.cts +11 -12
  80. package/dist/mastra/index.d.ts +11 -12
  81. package/dist/mastra/index.js +1 -1
  82. package/dist/mcp/index.cjs +75 -17
  83. package/dist/mcp/index.d.cts +14 -15
  84. package/dist/mcp/index.d.ts +14 -15
  85. package/dist/mcp/index.js +69 -15
  86. package/dist/memory/index.cjs +4 -4
  87. package/dist/memory/index.d.cts +12 -13
  88. package/dist/memory/index.d.ts +12 -13
  89. package/dist/memory/index.js +1 -1
  90. package/dist/network/index.cjs +8 -8
  91. package/dist/network/index.d.cts +12 -13
  92. package/dist/network/index.d.ts +12 -13
  93. package/dist/network/index.js +5 -5
  94. package/dist/relevance/index.cjs +4 -4
  95. package/dist/relevance/index.d.cts +15 -16
  96. package/dist/relevance/index.d.ts +15 -16
  97. package/dist/relevance/index.js +1 -1
  98. package/dist/server/index.cjs +4 -0
  99. package/dist/server/index.d.cts +13 -12
  100. package/dist/server/index.d.ts +13 -12
  101. package/dist/server/index.js +4 -1
  102. package/dist/storage/index.cjs +184 -3
  103. package/dist/storage/index.d.cts +83 -13
  104. package/dist/storage/index.d.ts +83 -13
  105. package/dist/storage/index.js +186 -1
  106. package/dist/telemetry/index.d.cts +14 -15
  107. package/dist/telemetry/index.d.ts +14 -15
  108. package/dist/telemetry/otel-vendor.cjs +2 -2
  109. package/dist/telemetry/otel-vendor.d.cts +1 -1
  110. package/dist/telemetry/otel-vendor.d.ts +1 -1
  111. package/dist/telemetry/otel-vendor.js +1 -1
  112. package/dist/tools/index.cjs +4 -4
  113. package/dist/tools/index.d.cts +12 -13
  114. package/dist/tools/index.d.ts +12 -13
  115. package/dist/tools/index.js +1 -1
  116. package/dist/tts/index.cjs +2 -2
  117. package/dist/tts/index.d.cts +2 -3
  118. package/dist/tts/index.d.ts +2 -3
  119. package/dist/tts/index.js +1 -1
  120. package/dist/{types-BtMyV38I.d.ts → types-Bo1uigWx.d.cts} +1 -1
  121. package/dist/{types-BtMyV38I.d.cts → types-Bo1uigWx.d.ts} +1 -1
  122. package/dist/utils.cjs +28 -12
  123. package/dist/utils.d.cts +59 -16
  124. package/dist/utils.d.ts +59 -16
  125. package/dist/utils.js +1 -1
  126. package/dist/vector/filter/index.cjs +189 -7
  127. package/dist/vector/filter/index.js +190 -1
  128. package/dist/vector/index.cjs +2 -2
  129. package/dist/vector/index.d.cts +28 -20
  130. package/dist/vector/index.d.ts +28 -20
  131. package/dist/vector/index.js +1 -1
  132. package/dist/voice/index.cjs +4 -4
  133. package/dist/voice/index.d.cts +12 -13
  134. package/dist/voice/index.d.ts +12 -13
  135. package/dist/voice/index.js +1 -1
  136. package/dist/workflows/index.cjs +17 -69
  137. package/dist/workflows/index.d.cts +197 -77
  138. package/dist/workflows/index.d.ts +197 -77
  139. package/dist/workflows/index.js +1 -1
  140. package/dist/workflows/legacy/index.cjs +90 -0
  141. package/dist/workflows/legacy/index.d.cts +87 -0
  142. package/dist/workflows/legacy/index.d.ts +87 -0
  143. package/dist/workflows/legacy/index.js +1 -0
  144. package/package.json +19 -40
  145. package/workflows/legacy.d.ts +1 -0
  146. package/dist/chunk-4WABQORE.js +0 -781
  147. package/dist/chunk-CIEPFV6B.js +0 -658
  148. package/dist/chunk-CMPPXW4U.js +0 -154
  149. package/dist/chunk-CTKNWYK2.js +0 -131
  150. package/dist/chunk-LGERQTJM.js +0 -190
  151. package/dist/chunk-O44MSFMZ.cjs +0 -168
  152. package/dist/chunk-QDAMIZY3.cjs +0 -783
  153. package/dist/chunk-QHDPLMHB.cjs +0 -667
  154. package/dist/chunk-RAQBTCIR.cjs +0 -134
  155. package/dist/chunk-YK3XJ52U.cjs +0 -192
  156. package/dist/storage/libsql/index.cjs +0 -581
  157. package/dist/storage/libsql/index.d.cts +0 -104
  158. package/dist/storage/libsql/index.d.ts +0 -104
  159. package/dist/storage/libsql/index.js +0 -578
  160. package/dist/vector/libsql/index.cjs +0 -14
  161. package/dist/vector/libsql/index.d.cts +0 -82
  162. package/dist/vector/libsql/index.d.ts +0 -82
  163. package/dist/vector/libsql/index.js +0 -1
  164. package/dist/workflows/vNext/index.d.cts +0 -209
  165. package/dist/workflows/vNext/index.d.ts +0 -209
  166. package/storage/libsql.d.ts +0 -1
  167. package/vector/libsql.d.ts +0 -1
  168. package/workflows/vNext.d.ts +0 -1
@@ -1,658 +0,0 @@
1
- import { LibSQLVector } from './chunk-4WABQORE.js';
2
- import { DefaultProxyStorage, augmentWithInit } from './chunk-CTKNWYK2.js';
3
- import { deepMerge } from './chunk-S34QVMKE.js';
4
- import { MastraBase } from './chunk-235X76GC.js';
5
- import { existsSync } from 'fs';
6
- import { join } from 'path';
7
- import fsp from 'node:fs/promises';
8
- import os from 'node:os';
9
- import path from 'node:path';
10
- import { experimental_customProvider } from 'ai';
11
-
12
- async function getModelCachePath() {
13
- const cachePath = path.join(os.homedir(), ".cache", "mastra", "fastembed-models");
14
- await fsp.mkdir(cachePath, { recursive: true });
15
- return cachePath;
16
- }
17
- function unbundleableImport(name) {
18
- const nonStaticallyAnalyzableName = `${name}?d=${Date.now()}`;
19
- return import(nonStaticallyAnalyzableName.split(`?`)[0]);
20
- }
21
- async function generateEmbeddings(values, modelType) {
22
- try {
23
- let mod;
24
- const importErrors = [];
25
- {
26
- try {
27
- mod = await unbundleableImport("fastembed");
28
- } catch (e) {
29
- if (e instanceof Error) {
30
- importErrors.push(e);
31
- } else {
32
- throw e;
33
- }
34
- }
35
- }
36
- if (!mod) {
37
- throw new Error(`${importErrors.map((e) => e.message).join(`
38
- `)}
39
-
40
- This runtime does not support fastembed-js, which is the default embedder in Mastra.
41
- Scroll up to read import errors. These errors mean you can't use the default Mastra embedder on this hosting platform.
42
- You can either use Mastra Cloud which supports the default embedder, or you can configure an alternate provider.
43
-
44
- For example if you're using Memory:
45
-
46
- import { openai } from "@ai-sdk/openai";
47
-
48
- const memory = new Memory({
49
- embedder: openai.embedding("text-embedding-3-small"), // <- doesn't have to be openai
50
- })
51
-
52
- Visit https://sdk.vercel.ai/docs/foundations/overview#embedding-models to find an alternate embedding provider
53
-
54
- If you do not want to use the Memory semantic recall feature, you can disable it entirely and this error will go away.
55
-
56
- const memory = new Memory({
57
- options: {
58
- semanticRecall: false // <- an embedder will not be required with this set to false
59
- }
60
- })
61
- `);
62
- }
63
- const { FlagEmbedding, EmbeddingModel } = mod;
64
- const model = await FlagEmbedding.init({
65
- model: EmbeddingModel[modelType],
66
- cacheDir: await getModelCachePath()
67
- });
68
- const embeddings = await model.embed(values);
69
- const allResults = [];
70
- for await (const result of embeddings) {
71
- allResults.push(...result.map((embedding) => Array.from(embedding)));
72
- }
73
- if (allResults.length === 0) throw new Error("No embeddings generated");
74
- return {
75
- embeddings: allResults
76
- };
77
- } catch (error) {
78
- console.error("Error generating embeddings:", error);
79
- throw error;
80
- }
81
- }
82
- var fastEmbedProvider = experimental_customProvider({
83
- textEmbeddingModels: {
84
- "bge-small-en-v1.5": {
85
- specificationVersion: "v1",
86
- provider: "fastembed",
87
- modelId: "bge-small-en-v1.5",
88
- maxEmbeddingsPerCall: 256,
89
- supportsParallelCalls: true,
90
- async doEmbed({ values }) {
91
- return generateEmbeddings(values, "BGESmallENV15");
92
- }
93
- },
94
- "bge-base-en-v1.5": {
95
- specificationVersion: "v1",
96
- provider: "fastembed",
97
- modelId: "bge-base-en-v1.5",
98
- maxEmbeddingsPerCall: 256,
99
- supportsParallelCalls: true,
100
- async doEmbed({ values }) {
101
- return generateEmbeddings(values, "BGEBaseENV15");
102
- }
103
- }
104
- }
105
- });
106
- var defaultEmbedder = fastEmbedProvider.textEmbeddingModel;
107
-
108
- // src/memory/memory.ts
109
- var MemoryProcessor = class extends MastraBase {
110
- /**
111
- * Process a list of messages and return a filtered or transformed list.
112
- * @param messages The messages to process
113
- * @returns The processed messages
114
- */
115
- process(messages, _opts) {
116
- return messages;
117
- }
118
- };
119
- var memoryDefaultOptions = {
120
- lastMessages: 40,
121
- semanticRecall: {
122
- topK: 2,
123
- messageRange: {
124
- before: 2,
125
- after: 2
126
- }
127
- },
128
- threads: {
129
- generateTitle: true
130
- },
131
- workingMemory: {
132
- use: "text-stream",
133
- // will be deprecated, use 'tool-call' instead
134
- enabled: false,
135
- template: `
136
- # User Information
137
- - **First Name**:
138
- - **Last Name**:
139
- - **Location**:
140
- - **Occupation**:
141
- - **Interests**:
142
- - **Goals**:
143
- - **Events**:
144
- - **Facts**:
145
- - **Projects**:
146
- `
147
- }
148
- };
149
- var newMemoryDefaultOptions = {
150
- lastMessages: 10,
151
- semanticRecall: false,
152
- threads: {
153
- generateTitle: false
154
- },
155
- workingMemory: {
156
- // new
157
- use: "tool-call"}
158
- };
159
- var MastraMemory = class extends MastraBase {
160
- MAX_CONTEXT_TOKENS;
161
- storage;
162
- vector;
163
- embedder;
164
- processors = [];
165
- deprecationWarnings = [];
166
- threadConfig = { ...memoryDefaultOptions };
167
- constructor(config) {
168
- super({ component: "MEMORY", name: config.name });
169
- if (config.options) {
170
- this.threadConfig = this.getMergedThreadConfig(config.options);
171
- }
172
- const hasRootMemoryDbFile = existsSync(join(process.cwd(), `memory.db`));
173
- const hasParentMemoryDbFile = existsSync(join(process.cwd(), `..`, `..`, `memory.db`));
174
- const suggestDbPath = hasRootMemoryDbFile || hasParentMemoryDbFile ? `file:${hasParentMemoryDbFile ? `../../` : ``}memory.db` : `file:../mastra.db`;
175
- if (config.storage) {
176
- this.storage = config.storage;
177
- } else {
178
- this.storage = new DefaultProxyStorage({
179
- config: {
180
- url: "file:memory.db"
181
- }
182
- });
183
- this.deprecationWarnings.push(`
184
- Default storage is deprecated in Mastra Memory.
185
- You're using it as an implicit default by not setting a storage adapter.
186
-
187
- In the May 20th breaking change the default store will be removed.
188
-
189
- Instead of this:
190
- export const agent = new Agent({
191
- memory: new Memory({
192
- // your config
193
- })
194
- })
195
-
196
- Do this:
197
- import { LibSQLStore } from '@mastra/libsql';
198
-
199
- export const agent = new Agent({
200
- memory: new Memory({
201
- // your config
202
- storage: new LibSQLStore({
203
- url: '${suggestDbPath}' // relative path from bundled .mastra/output dir
204
- })
205
- })
206
- })
207
-
208
- Additionally, in the breaking release, Memory will inherit storage from the Mastra instance.
209
- If you plan on using that feature you can prepare by setting the same storage instance on Mastra and Memory.
210
-
211
- Ex:
212
- // mastra/storage.ts
213
- export const storage = new LibSQLStore({
214
- url: '${suggestDbPath}'
215
- })
216
-
217
- // mastra/index.ts
218
- import { storage } from "./storage"
219
- export const mastra = new Mastra({
220
- // your config
221
- storage
222
- })
223
-
224
- // mastra/agents/index.ts
225
- import { storage } from "../storage"
226
- export const yourAgent = new Agent({
227
- // your config
228
- storage
229
- })
230
- `);
231
- }
232
- this.storage = augmentWithInit(this.storage);
233
- const semanticRecallIsEnabled = this.threadConfig.semanticRecall !== false;
234
- if (config.vector && semanticRecallIsEnabled) {
235
- this.vector = config.vector;
236
- } else if (
237
- // if there's no configured vector store
238
- // and the vector store hasn't been explicitly disabled with vector: false
239
- config.vector !== false && // and semanticRecall is enabled
240
- semanticRecallIsEnabled
241
- ) {
242
- const oldDb = "memory-vector.db";
243
- const hasOldDb = existsSync(join(process.cwd(), oldDb)) || existsSync(join(process.cwd(), ".mastra", oldDb));
244
- const newDb = "memory.db";
245
- if (hasOldDb) {
246
- this.deprecationWarnings.push(
247
- `Found deprecated Memory vector db file ${oldDb}. In the May 20th breaking change, this will no longer be used by default. This db is now merged with the default storage file (${newDb}). You will need to manually migrate any data from ${oldDb} to ${newDb} if it's important to you. For now the deprecated path will be used, but in the May 20th breaking change we will only use the new db file path.`
248
- );
249
- }
250
- this.deprecationWarnings.push(`
251
- Default vector storage is deprecated in Mastra Memory.
252
- You're using it as an implicit default by not setting a vector store.
253
-
254
- In the May 20th breaking change the default vector store will be removed.
255
-
256
- Instead of this:
257
- export const agent = new Agent({
258
- memory: new Memory({
259
- options: { semanticRecall: true }
260
- })
261
- })
262
-
263
- Do this:
264
- import { LibSQLVector } from '@mastra/libsql';
265
-
266
- export const agent = new Agent({
267
- memory: new Memory({
268
- options: { semanticRecall: true },
269
- vector: new LibSQLVector({
270
- connectionUrl: '${suggestDbPath}' // relative path from bundled .mastra/output dir
271
- })
272
- })
273
- })
274
- `);
275
- this.vector = new LibSQLVector({
276
- // TODO: MAY 20th BREAKING CHANGE: remove this default and throw an error if semantic recall is enabled but there's no vector db
277
- connectionUrl: hasOldDb ? `file:${oldDb}` : `file:${newDb}`
278
- });
279
- }
280
- if (config.embedder) {
281
- this.embedder = config.embedder;
282
- } else if (
283
- // if there's no configured embedder
284
- // and there's a vector store
285
- typeof this.vector !== `undefined` && // and semanticRecall is enabled
286
- semanticRecallIsEnabled
287
- ) {
288
- this.deprecationWarnings.push(`
289
- The default embedder (FastEmbed) is deprecated in Mastra Memory.
290
- You're using it as an implicit default by not configuring an embedder.
291
-
292
- On May 20th there will be a breaking change and the default embedder will be removed from @mastra/core.
293
-
294
- To continue using FastEmbed, install the dedicated package:
295
- pnpm add @mastra/fastembed
296
-
297
- Then configure it in your Memory setup:
298
-
299
- import { fastembed } from '@mastra/fastembed';
300
-
301
- export const agent = new Agent({
302
- memory: new Memory({
303
- embedder: fastembed, // Configure the embedder
304
- // your other config
305
- })
306
- })
307
-
308
- Alternatively, you can use a different embedder, like OpenAI:
309
- import { openai } from '@ai-sdk/openai';
310
-
311
- export const agent = new Agent({
312
- memory: new Memory({
313
- embedder: openai.embedding('text-embedding-3-small'),
314
- // your other config
315
- })
316
- })
317
-
318
- --> This breaking change will be released on May 20th <--
319
- `);
320
- this.embedder = defaultEmbedder("bge-small-en-v1.5");
321
- }
322
- if (config.processors) {
323
- this.processors = config.processors;
324
- }
325
- this.addImplicitDefaultsWarning(config);
326
- if (this.deprecationWarnings.length > 0) {
327
- setTimeout(() => {
328
- this.logger?.warn(`
329
-
330
- !MEMORY DEPRECATION WARNING!
331
- ${this.deprecationWarnings.map((w, i) => `${this.deprecationWarnings.length > 1 ? `Warning ${i + 1}:
332
- ` : ``}${w}`).join(`
333
-
334
- `)}
335
- !END MEMORY DEPRECATION WARNING!
336
-
337
- `);
338
- }, 1e3);
339
- }
340
- }
341
- // We're changing the implicit defaults from memoryDefaultOptions to newMemoryDefaultOptions so we need to log and let people know
342
- addImplicitDefaultsWarning(config) {
343
- const fromToPairs = [];
344
- const indent = (s) => s.split(`
345
- `).join(`
346
- `);
347
- const format = (v) => typeof v === `object` && !Array.isArray(v) && v !== null ? indent(JSON.stringify(v, null, 2).replaceAll(`"`, ``)) : v;
348
- const options = config.options ?? {};
349
- if (!(`lastMessages` in options))
350
- fromToPairs.push({
351
- key: "lastMessages",
352
- from: memoryDefaultOptions.lastMessages,
353
- to: newMemoryDefaultOptions.lastMessages
354
- });
355
- if (!(`semanticRecall` in options))
356
- fromToPairs.push({
357
- key: "semanticRecall",
358
- from: memoryDefaultOptions.semanticRecall,
359
- to: newMemoryDefaultOptions.semanticRecall
360
- });
361
- if (!(`threads` in options))
362
- fromToPairs.push({
363
- key: "threads",
364
- from: memoryDefaultOptions.threads,
365
- to: newMemoryDefaultOptions.threads
366
- });
367
- if (`workingMemory` in options && // special handling for working memory since it's disabled by default and users should only care about the change if they're using
368
- options.workingMemory?.enabled === true && options.workingMemory?.use !== `tool-call`) {
369
- fromToPairs.push({
370
- key: "workingMemory",
371
- from: {
372
- use: memoryDefaultOptions.workingMemory.use
373
- },
374
- to: {
375
- use: newMemoryDefaultOptions.workingMemory.use
376
- },
377
- message: `
378
- Also, the text-stream output mode (which is the current default) will be fully removed in an upcoming breaking change. Please update your code to use the newer "use: 'tool-call'" setting instead.
379
- `
380
- });
381
- }
382
- if (fromToPairs.length > 0) {
383
- const currentDefaults = `{
384
- options: {
385
- ${fromToPairs.map(({ key, from }) => `${key}: ${format(from)}`).join(`,
386
- `)}
387
- }
388
- }`;
389
- const upcomingDefaults = `{
390
- options: {
391
- ${fromToPairs.map(({ key, to }) => `${key}: ${format(to)}`).join(`,
392
- `)}
393
- }
394
- }`;
395
- const messages = fromToPairs.filter((ft) => ft.message);
396
- this.deprecationWarnings.push(`
397
- Your Mastra memory instance has the
398
- following implicit default options:
399
-
400
- new Memory(${currentDefaults})
401
-
402
- In the next release these implicit defaults
403
- will be changed to the following default settings:
404
-
405
- new Memory(${upcomingDefaults})
406
-
407
- To keep your defaults as they are, add
408
- them directly into your Memory configuration,
409
- otherwise please add the new settings to
410
- your memory config to prepare for the change.
411
- ${messages.length ? messages.map((ft) => ft.message).join(`
412
- `) : ``}
413
- --> This breaking change will be released on May 20th <--
414
- `);
415
- }
416
- }
417
- setStorage(storage) {
418
- if (storage instanceof DefaultProxyStorage) {
419
- this.deprecationWarnings.push(`Importing "DefaultStorage" from '@mastra/core/storage/libsql' is deprecated.
420
-
421
- Instead of:
422
- import { DefaultStorage } from '@mastra/core/storage/libsql';
423
-
424
- Do:
425
- import { LibSQLStore } from '@mastra/libsql';
426
- `);
427
- }
428
- this.storage = storage;
429
- }
430
- setVector(vector) {
431
- this.vector = vector;
432
- }
433
- setEmbedder(embedder) {
434
- this.embedder = embedder;
435
- }
436
- /**
437
- * Get a system message to inject into the conversation.
438
- * This will be called before each conversation turn.
439
- * Implementations can override this to inject custom system messages.
440
- */
441
- async getSystemMessage(_input) {
442
- return null;
443
- }
444
- /**
445
- * Get tools that should be available to the agent.
446
- * This will be called when converting tools for the agent.
447
- * Implementations can override this to provide additional tools.
448
- */
449
- getTools(_config) {
450
- return {};
451
- }
452
- async createEmbeddingIndex(dimensions) {
453
- const defaultDimensions = 1536;
454
- const isDefault = dimensions === defaultDimensions;
455
- const usedDimensions = dimensions ?? defaultDimensions;
456
- const separator = this.vector?.indexSeparator ?? "_";
457
- const indexName = isDefault ? `memory${separator}messages` : `memory${separator}messages${separator}${usedDimensions}`;
458
- if (typeof this.vector === `undefined`) {
459
- throw new Error(`Tried to create embedding index but no vector db is attached to this Memory instance.`);
460
- }
461
- await this.vector.createIndex({
462
- indexName,
463
- dimension: usedDimensions
464
- });
465
- return { indexName };
466
- }
467
- getMergedThreadConfig(config) {
468
- return deepMerge(this.threadConfig, config || {});
469
- }
470
- /**
471
- * Apply all configured message processors to a list of messages.
472
- * @param messages The messages to process
473
- * @returns The processed messages
474
- */
475
- applyProcessors(messages, opts) {
476
- const processors = opts.processors || this.processors;
477
- if (!processors || processors.length === 0) {
478
- return messages;
479
- }
480
- let processedMessages = [...messages];
481
- for (const processor of processors) {
482
- processedMessages = processor.process(processedMessages, {
483
- systemMessage: opts.systemMessage,
484
- newMessages: opts.newMessages,
485
- memorySystemMessage: opts.memorySystemMessage
486
- });
487
- }
488
- return processedMessages;
489
- }
490
- processMessages({
491
- messages,
492
- processors,
493
- ...opts
494
- }) {
495
- return this.applyProcessors(messages, { processors: processors || this.processors, ...opts });
496
- }
497
- estimateTokens(text) {
498
- return Math.ceil(text.split(" ").length * 1.3);
499
- }
500
- parseMessages(messages) {
501
- return messages.map((msg) => {
502
- let content = msg.content;
503
- if (typeof content === "string" && (content.startsWith("[") || content.startsWith("{"))) {
504
- try {
505
- content = JSON.parse(content);
506
- } catch {
507
- }
508
- } else if (typeof content === "number") {
509
- content = String(content);
510
- }
511
- return {
512
- ...msg,
513
- content
514
- };
515
- });
516
- }
517
- convertToUIMessages(messages) {
518
- function addToolMessageToChat({
519
- toolMessage,
520
- messages: messages2,
521
- toolResultContents
522
- }) {
523
- const chatMessages2 = messages2.map((message) => {
524
- if (message.toolInvocations) {
525
- return {
526
- ...message,
527
- toolInvocations: message.toolInvocations.map((toolInvocation) => {
528
- const toolResult = toolMessage.content.find((tool) => tool.toolCallId === toolInvocation.toolCallId);
529
- if (toolResult) {
530
- return {
531
- ...toolInvocation,
532
- state: "result",
533
- result: toolResult.result
534
- };
535
- }
536
- return toolInvocation;
537
- })
538
- };
539
- }
540
- return message;
541
- });
542
- const resultContents = [...toolResultContents, ...toolMessage.content];
543
- return { chatMessages: chatMessages2, toolResultContents: resultContents };
544
- }
545
- const { chatMessages } = messages.reduce(
546
- (obj, message) => {
547
- if (message.role === "tool") {
548
- return addToolMessageToChat({
549
- toolMessage: message,
550
- messages: obj.chatMessages,
551
- toolResultContents: obj.toolResultContents
552
- });
553
- }
554
- let textContent = "";
555
- let toolInvocations = [];
556
- if (typeof message.content === "string") {
557
- textContent = message.content;
558
- } else if (typeof message.content === "number") {
559
- textContent = String(message.content);
560
- } else if (Array.isArray(message.content)) {
561
- for (const content of message.content) {
562
- if (content.type === "text") {
563
- textContent += content.text;
564
- } else if (content.type === "tool-call") {
565
- const toolResult = obj.toolResultContents.find((tool) => tool.toolCallId === content.toolCallId);
566
- toolInvocations.push({
567
- state: toolResult ? "result" : "call",
568
- toolCallId: content.toolCallId,
569
- toolName: content.toolName,
570
- args: content.args,
571
- result: toolResult?.result
572
- });
573
- }
574
- }
575
- }
576
- obj.chatMessages.push({
577
- id: message.id,
578
- role: message.role,
579
- content: textContent,
580
- toolInvocations,
581
- createdAt: message.createdAt
582
- });
583
- return obj;
584
- },
585
- { chatMessages: [], toolResultContents: [] }
586
- );
587
- return chatMessages;
588
- }
589
- /**
590
- * Helper method to create a new thread
591
- * @param title - Optional title for the thread
592
- * @param metadata - Optional metadata for the thread
593
- * @returns Promise resolving to the created thread
594
- */
595
- async createThread({
596
- threadId,
597
- resourceId,
598
- title,
599
- metadata,
600
- memoryConfig
601
- }) {
602
- const thread = {
603
- id: threadId || this.generateId(),
604
- title: title || `New Thread ${(/* @__PURE__ */ new Date()).toISOString()}`,
605
- resourceId,
606
- createdAt: /* @__PURE__ */ new Date(),
607
- updatedAt: /* @__PURE__ */ new Date(),
608
- metadata
609
- };
610
- return this.saveThread({ thread, memoryConfig });
611
- }
612
- /**
613
- * Helper method to add a single message to a thread
614
- * @param threadId - The thread to add the message to
615
- * @param content - The message content
616
- * @param role - The role of the message sender
617
- * @param type - The type of the message
618
- * @param toolNames - Optional array of tool names that were called
619
- * @param toolCallArgs - Optional array of tool call arguments
620
- * @param toolCallIds - Optional array of tool call ids
621
- * @returns Promise resolving to the saved message
622
- */
623
- async addMessage({
624
- threadId,
625
- resourceId,
626
- config,
627
- content,
628
- role,
629
- type,
630
- toolNames,
631
- toolCallArgs,
632
- toolCallIds
633
- }) {
634
- const message = {
635
- id: this.generateId(),
636
- content,
637
- role,
638
- createdAt: /* @__PURE__ */ new Date(),
639
- threadId,
640
- resourceId,
641
- type,
642
- toolNames,
643
- toolCallArgs,
644
- toolCallIds
645
- };
646
- const savedMessages = await this.saveMessages({ messages: [message], memoryConfig: config });
647
- return savedMessages[0];
648
- }
649
- /**
650
- * Generates a unique identifier
651
- * @returns A unique string ID
652
- */
653
- generateId() {
654
- return crypto.randomUUID();
655
- }
656
- };
657
-
658
- export { MastraMemory, MemoryProcessor, memoryDefaultOptions };