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