@mastra/core 0.10.1 → 0.10.2-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 (79) hide show
  1. package/dist/agent/index.cjs +7 -2
  2. package/dist/agent/index.d.cts +9 -9
  3. package/dist/agent/index.d.ts +9 -9
  4. package/dist/agent/index.js +2 -1
  5. package/dist/{base-B96VvaWm.d.cts → base-BIRXTC4Q.d.cts} +1456 -1361
  6. package/dist/{base-QP4OC4dB.d.ts → base-BUTjc86H.d.ts} +1456 -1361
  7. package/dist/{chunk-XRF2JEZJ.cjs → chunk-2CK6E5UF.cjs} +24 -0
  8. package/dist/{chunk-STLR3SIQ.cjs → chunk-4I6LG5EO.cjs} +6 -92
  9. package/dist/{chunk-2YYOF7DO.js → chunk-5UFUPI3G.js} +5 -91
  10. package/dist/{chunk-MTIZRZZI.js → chunk-75EMTCUM.js} +24 -0
  11. package/dist/{chunk-VRACJIAE.js → chunk-A4RQDNP3.js} +2 -2
  12. package/dist/{chunk-RFERFI6B.js → chunk-D3237VN7.js} +183 -369
  13. package/dist/{chunk-U3L3NEOM.cjs → chunk-DXLVS7ML.cjs} +1 -19
  14. package/dist/{chunk-2PW6UJMW.js → chunk-EQTIDVPN.js} +2 -19
  15. package/dist/{chunk-SFZZYGKB.cjs → chunk-EZYCQBP2.cjs} +2 -2
  16. package/dist/{chunk-MAFHTHTJ.cjs → chunk-GXEDBJC5.cjs} +4 -4
  17. package/dist/{chunk-5JRD3NDP.cjs → chunk-I5OLBJ26.cjs} +6 -77
  18. package/dist/chunk-LCCQWUQP.js +962 -0
  19. package/dist/{chunk-RARKB3F2.js → chunk-NY4KJJWC.js} +1 -1
  20. package/dist/{chunk-SLKAWVQR.cjs → chunk-QUCBJ363.cjs} +192 -378
  21. package/dist/{chunk-SKG2NIZW.cjs → chunk-RK6DHZUA.cjs} +2 -2
  22. package/dist/{chunk-OCT2762Q.js → chunk-RMTG7VWR.js} +1 -1
  23. package/dist/chunk-XAO67QBR.cjs +964 -0
  24. package/dist/{chunk-BPTSLJHA.js → chunk-ZJYHZO6Y.js} +2 -73
  25. package/dist/eval/index.d.cts +8 -8
  26. package/dist/eval/index.d.ts +8 -8
  27. package/dist/index.cjs +41 -45
  28. package/dist/index.d.cts +7 -7
  29. package/dist/index.d.ts +7 -7
  30. package/dist/index.js +10 -10
  31. package/dist/integration/index.cjs +3 -3
  32. package/dist/integration/index.d.cts +9 -9
  33. package/dist/integration/index.d.ts +9 -9
  34. package/dist/integration/index.js +1 -1
  35. package/dist/llm/index.d.cts +8 -8
  36. package/dist/llm/index.d.ts +8 -8
  37. package/dist/mastra/index.cjs +2 -2
  38. package/dist/mastra/index.d.cts +6 -6
  39. package/dist/mastra/index.d.ts +6 -6
  40. package/dist/mastra/index.js +1 -1
  41. package/dist/mcp/index.d.cts +11 -11
  42. package/dist/mcp/index.d.ts +11 -11
  43. package/dist/memory/index.cjs +4 -4
  44. package/dist/memory/index.d.cts +9 -9
  45. package/dist/memory/index.d.ts +9 -9
  46. package/dist/memory/index.js +1 -1
  47. package/dist/network/index.cjs +4 -4
  48. package/dist/network/index.d.cts +9 -9
  49. package/dist/network/index.d.ts +9 -9
  50. package/dist/network/index.js +2 -2
  51. package/dist/relevance/index.cjs +4 -4
  52. package/dist/relevance/index.d.cts +11 -11
  53. package/dist/relevance/index.d.ts +11 -11
  54. package/dist/relevance/index.js +1 -1
  55. package/dist/server/index.d.cts +9 -9
  56. package/dist/server/index.d.ts +9 -9
  57. package/dist/storage/index.d.cts +18 -18
  58. package/dist/storage/index.d.ts +18 -18
  59. package/dist/telemetry/index.d.cts +9 -9
  60. package/dist/telemetry/index.d.ts +9 -9
  61. package/dist/tools/index.cjs +4 -4
  62. package/dist/tools/index.d.cts +9 -9
  63. package/dist/tools/index.d.ts +9 -9
  64. package/dist/tools/index.js +1 -1
  65. package/dist/utils.cjs +15 -19
  66. package/dist/utils.d.cts +10 -11
  67. package/dist/utils.d.ts +10 -11
  68. package/dist/utils.js +1 -1
  69. package/dist/voice/index.d.cts +9 -9
  70. package/dist/voice/index.d.ts +9 -9
  71. package/dist/workflows/index.cjs +9 -9
  72. package/dist/workflows/index.d.cts +9 -9
  73. package/dist/workflows/index.d.ts +9 -9
  74. package/dist/workflows/index.js +1 -1
  75. package/dist/workflows/legacy/index.cjs +22 -22
  76. package/dist/workflows/legacy/index.d.cts +9 -9
  77. package/dist/workflows/legacy/index.d.ts +9 -9
  78. package/dist/workflows/legacy/index.js +1 -1
  79. package/package.json +5 -2
@@ -0,0 +1,964 @@
1
+ 'use strict';
2
+
3
+ var chunkDXLVS7ML_cjs = require('./chunk-DXLVS7ML.cjs');
4
+ var crypto = require('crypto');
5
+ var ai = require('ai');
6
+ var providerUtils = require('@ai-sdk/provider-utils');
7
+ var zod = require('zod');
8
+
9
+ zod.z.union([
10
+ zod.z.string(),
11
+ zod.z.instanceof(Uint8Array),
12
+ zod.z.instanceof(ArrayBuffer),
13
+ zod.z.custom(
14
+ // Buffer might not be available in some environments such as CloudFlare:
15
+ (value) => globalThis.Buffer?.isBuffer(value) ?? false,
16
+ { message: "Must be a Buffer" }
17
+ )
18
+ ]);
19
+ function convertDataContentToBase64String(content) {
20
+ if (typeof content === "string") {
21
+ return content;
22
+ }
23
+ if (content instanceof ArrayBuffer) {
24
+ return providerUtils.convertUint8ArrayToBase64(new Uint8Array(content));
25
+ }
26
+ return providerUtils.convertUint8ArrayToBase64(content);
27
+ }
28
+ function convertDataContentToUint8Array(content) {
29
+ if (content instanceof Uint8Array) {
30
+ return content;
31
+ }
32
+ if (typeof content === "string") {
33
+ try {
34
+ return providerUtils.convertBase64ToUint8Array(content);
35
+ } catch (error) {
36
+ throw new Error("Invalid data content. Content string is not a base64-encoded media.", {
37
+ cause: error
38
+ });
39
+ }
40
+ }
41
+ if (content instanceof ArrayBuffer) {
42
+ return new Uint8Array(content);
43
+ }
44
+ throw new Error(content);
45
+ }
46
+ function convertUint8ArrayToText(uint8Array) {
47
+ try {
48
+ return new TextDecoder().decode(uint8Array);
49
+ } catch {
50
+ throw new Error("Error decoding Uint8Array to text");
51
+ }
52
+ }
53
+
54
+ // src/agent/message-list/prompt/attachments-to-parts.ts
55
+ function attachmentsToParts(attachments) {
56
+ const parts = [];
57
+ for (const attachment of attachments) {
58
+ let url;
59
+ try {
60
+ url = new URL(attachment.url);
61
+ } catch {
62
+ throw new Error(`Invalid URL: ${attachment.url}`);
63
+ }
64
+ switch (url.protocol) {
65
+ case "http:":
66
+ case "https:": {
67
+ if (attachment.contentType?.startsWith("image/")) {
68
+ parts.push({ type: "image", image: url });
69
+ } else {
70
+ if (!attachment.contentType) {
71
+ throw new Error("If the attachment is not an image, it must specify a content type");
72
+ }
73
+ parts.push({
74
+ type: "file",
75
+ data: url,
76
+ mimeType: attachment.contentType
77
+ });
78
+ }
79
+ break;
80
+ }
81
+ case "data:": {
82
+ let header;
83
+ let base64Content;
84
+ let mimeType;
85
+ try {
86
+ [header, base64Content] = attachment.url.split(",");
87
+ mimeType = header?.split?.(";")?.[0]?.split(":")[1];
88
+ } catch {
89
+ throw new Error(`Error processing data URL: ${attachment.url}`);
90
+ }
91
+ if (mimeType == null || base64Content == null) {
92
+ throw new Error(`Invalid data URL format: ${attachment.url}`);
93
+ }
94
+ if (attachment.contentType?.startsWith("image/")) {
95
+ parts.push({
96
+ type: "image",
97
+ image: convertDataContentToUint8Array(base64Content)
98
+ });
99
+ } else if (attachment.contentType?.startsWith("text/")) {
100
+ parts.push({
101
+ type: "text",
102
+ text: convertUint8ArrayToText(convertDataContentToUint8Array(base64Content))
103
+ });
104
+ } else {
105
+ if (!attachment.contentType) {
106
+ throw new Error("If the attachment is not an image or text, it must specify a content type");
107
+ }
108
+ parts.push({
109
+ type: "file",
110
+ data: base64Content,
111
+ mimeType: attachment.contentType
112
+ });
113
+ }
114
+ break;
115
+ }
116
+ default: {
117
+ throw new Error(`Unsupported URL protocol: ${url.protocol}`);
118
+ }
119
+ }
120
+ }
121
+ return parts;
122
+ }
123
+
124
+ // src/agent/message-list/prompt/convert-to-mastra-v1.ts
125
+ var makePushOrCombine = (v1Messages) => (msg) => {
126
+ const previousMessage = v1Messages.at(-1);
127
+ if (msg.role === previousMessage?.role && Array.isArray(previousMessage.content) && Array.isArray(msg.content) && // we were creating new messages for tool calls before and not appending to the assistant message
128
+ // so don't append here so everything works as before
129
+ (msg.role !== `assistant` || msg.role === `assistant` && msg.content.at(-1)?.type !== `tool-call`)) {
130
+ for (const part of msg.content) {
131
+ previousMessage.content.push(part);
132
+ }
133
+ } else {
134
+ v1Messages.push(msg);
135
+ }
136
+ };
137
+ function convertToV1Messages(messages) {
138
+ const v1Messages = [];
139
+ const pushOrCombine = makePushOrCombine(v1Messages);
140
+ for (let i = 0; i < messages.length; i++) {
141
+ const message = messages[i];
142
+ const isLastMessage = i === messages.length - 1;
143
+ if (!message?.content) continue;
144
+ const { content, experimental_attachments, parts } = message.content;
145
+ const { role } = message;
146
+ const fields = {
147
+ id: message.id,
148
+ createdAt: message.createdAt,
149
+ resourceId: message.resourceId,
150
+ threadId: message.threadId
151
+ };
152
+ switch (role) {
153
+ case "user": {
154
+ if (parts == null) {
155
+ const userContent = experimental_attachments ? [{ type: "text", text: content || "" }, ...attachmentsToParts(experimental_attachments)] : { type: "text", text: content || "" };
156
+ pushOrCombine({
157
+ role: "user",
158
+ ...fields,
159
+ type: "text",
160
+ // @ts-ignore
161
+ content: userContent
162
+ // Array.isArray(userContent) && userContent.length === 1 && userContent[0]?.type === `text`
163
+ // ? userContent[0].text
164
+ // : userContent,
165
+ });
166
+ throw new Error(`will we ever hit this code?`);
167
+ } else {
168
+ const textParts = message.content.parts.filter((part) => part.type === "text").map((part) => ({
169
+ type: "text",
170
+ text: part.text
171
+ }));
172
+ const userContent = experimental_attachments ? [...textParts, ...attachmentsToParts(experimental_attachments)] : textParts;
173
+ pushOrCombine({
174
+ role: "user",
175
+ ...fields,
176
+ type: "text",
177
+ // content: userContent,
178
+ // @ts-ignore
179
+ content: Array.isArray(userContent) && userContent.length === 1 && userContent[0]?.type === `text` && typeof content !== `undefined` ? content : userContent
180
+ });
181
+ }
182
+ break;
183
+ }
184
+ case "assistant": {
185
+ if (message.content.parts != null) {
186
+ let processBlock2 = function() {
187
+ const content2 = [];
188
+ for (const part of block) {
189
+ switch (part.type) {
190
+ case "file":
191
+ case "text": {
192
+ content2.push(part);
193
+ break;
194
+ }
195
+ case "reasoning": {
196
+ for (const detail of part.details) {
197
+ switch (detail.type) {
198
+ case "text":
199
+ content2.push({
200
+ type: "reasoning",
201
+ text: detail.text,
202
+ signature: detail.signature
203
+ });
204
+ break;
205
+ case "redacted":
206
+ content2.push({
207
+ type: "redacted-reasoning",
208
+ data: detail.data
209
+ });
210
+ break;
211
+ }
212
+ }
213
+ break;
214
+ }
215
+ case "tool-invocation":
216
+ content2.push({
217
+ type: "tool-call",
218
+ toolCallId: part.toolInvocation.toolCallId,
219
+ toolName: part.toolInvocation.toolName,
220
+ args: part.toolInvocation.args
221
+ });
222
+ break;
223
+ }
224
+ }
225
+ pushOrCombine({
226
+ role: "assistant",
227
+ ...fields,
228
+ type: content2.some((c) => c.type === `tool-call`) ? "tool-call" : "text",
229
+ // content: content,
230
+ content: typeof content2 !== `string` && Array.isArray(content2) && content2.length === 1 && content2[0]?.type === `text` ? message?.content?.content || content2 : content2
231
+ });
232
+ const stepInvocations = block.filter((part) => `type` in part && part.type === "tool-invocation").map((part) => part.toolInvocation);
233
+ if (stepInvocations.length > 0) {
234
+ pushOrCombine({
235
+ role: "tool",
236
+ ...fields,
237
+ type: "tool-result",
238
+ // @ts-ignore
239
+ content: stepInvocations.map((toolInvocation) => {
240
+ const { toolCallId, toolName } = toolInvocation;
241
+ return {
242
+ type: "tool-result",
243
+ toolCallId,
244
+ toolName,
245
+ // @ts-ignore
246
+ result: toolInvocation.result
247
+ };
248
+ })
249
+ });
250
+ }
251
+ block = [];
252
+ blockHasToolInvocations = false;
253
+ currentStep++;
254
+ };
255
+ let currentStep = 0;
256
+ let blockHasToolInvocations = false;
257
+ let block = [];
258
+ for (const part of message.content.parts) {
259
+ switch (part.type) {
260
+ case "text": {
261
+ if (blockHasToolInvocations) {
262
+ processBlock2();
263
+ }
264
+ block.push(part);
265
+ break;
266
+ }
267
+ case "file":
268
+ case "reasoning": {
269
+ block.push(part);
270
+ break;
271
+ }
272
+ case "tool-invocation": {
273
+ if ((part.toolInvocation.step ?? 0) !== currentStep) {
274
+ processBlock2();
275
+ }
276
+ block.push(part);
277
+ blockHasToolInvocations = true;
278
+ break;
279
+ }
280
+ }
281
+ }
282
+ processBlock2();
283
+ break;
284
+ }
285
+ const toolInvocations = message.content.toolInvocations;
286
+ if (toolInvocations == null || toolInvocations.length === 0) {
287
+ pushOrCombine({ role: "assistant", ...fields, content: content || "", type: "text" });
288
+ break;
289
+ }
290
+ const maxStep = toolInvocations.reduce((max, toolInvocation) => {
291
+ return Math.max(max, toolInvocation.step ?? 0);
292
+ }, 0);
293
+ for (let i2 = 0; i2 <= maxStep; i2++) {
294
+ const stepInvocations = toolInvocations.filter((toolInvocation) => (toolInvocation.step ?? 0) === i2);
295
+ if (stepInvocations.length === 0) {
296
+ continue;
297
+ }
298
+ pushOrCombine({
299
+ role: "assistant",
300
+ ...fields,
301
+ type: "tool-call",
302
+ content: [
303
+ ...isLastMessage && content && i2 === 0 ? [{ type: "text", text: content }] : [],
304
+ ...stepInvocations.map(({ toolCallId, toolName, args }) => ({
305
+ type: "tool-call",
306
+ toolCallId,
307
+ toolName,
308
+ args
309
+ }))
310
+ ]
311
+ });
312
+ pushOrCombine({
313
+ role: "tool",
314
+ ...fields,
315
+ type: "tool-result",
316
+ content: stepInvocations.map((toolInvocation) => {
317
+ if (!("result" in toolInvocation)) {
318
+ return toolInvocation;
319
+ }
320
+ const { toolCallId, toolName, result } = toolInvocation;
321
+ return {
322
+ type: "tool-result",
323
+ toolCallId,
324
+ toolName,
325
+ result
326
+ };
327
+ })
328
+ });
329
+ }
330
+ if (content && !isLastMessage) {
331
+ pushOrCombine({ role: "assistant", ...fields, type: "text", content: content || "" });
332
+ }
333
+ break;
334
+ }
335
+ }
336
+ }
337
+ return v1Messages;
338
+ }
339
+
340
+ // src/agent/message-list/index.ts
341
+ var MessageList = class _MessageList {
342
+ messages = [];
343
+ // passed in by dev in input or context
344
+ systemMessages = [];
345
+ // passed in by us for a specific purpose, eg memory system message
346
+ taggedSystemMessages = {};
347
+ memoryInfo = null;
348
+ // used to filter this.messages by how it was added: input/response/memory
349
+ memoryMessages = /* @__PURE__ */ new Set();
350
+ newMessages = /* @__PURE__ */ new Set();
351
+ responseMessages = /* @__PURE__ */ new Set();
352
+ generateMessageId;
353
+ constructor({
354
+ threadId,
355
+ resourceId,
356
+ generateMessageId
357
+ } = {}) {
358
+ if (threadId) {
359
+ this.memoryInfo = { threadId, resourceId };
360
+ this.generateMessageId = generateMessageId;
361
+ }
362
+ }
363
+ add(messages, messageSource) {
364
+ for (const message of Array.isArray(messages) ? messages : [messages]) {
365
+ this.addOne(
366
+ typeof message === `string` ? {
367
+ role: "user",
368
+ content: message
369
+ } : message,
370
+ messageSource
371
+ );
372
+ }
373
+ return this;
374
+ }
375
+ getLatestUserContent() {
376
+ const currentUserMessages = this.all.core().filter((m) => m.role === "user");
377
+ const content = currentUserMessages.at(-1)?.content;
378
+ if (!content) return null;
379
+ return _MessageList.coreContentToString(content);
380
+ }
381
+ get get() {
382
+ return {
383
+ all: this.all,
384
+ remembered: this.remembered,
385
+ input: this.input,
386
+ response: this.response
387
+ };
388
+ }
389
+ all = {
390
+ mastra: () => this.messages,
391
+ v1: () => convertToV1Messages(this.messages),
392
+ ui: () => this.messages.map(_MessageList.toUIMessage),
393
+ core: () => this.convertToCoreMessages(this.all.ui()),
394
+ prompt: () => {
395
+ return [...this.systemMessages, ...Object.values(this.taggedSystemMessages).flat(), ...this.all.core()];
396
+ }
397
+ };
398
+ remembered = {
399
+ mastra: () => this.messages.filter((m) => this.memoryMessages.has(m)),
400
+ v1: () => convertToV1Messages(this.remembered.mastra()),
401
+ ui: () => this.remembered.mastra().map(_MessageList.toUIMessage),
402
+ core: () => this.convertToCoreMessages(this.remembered.ui())
403
+ };
404
+ input = {
405
+ mastra: () => this.messages.filter((m) => this.newMessages.has(m)),
406
+ v1: () => convertToV1Messages(this.input.mastra()),
407
+ ui: () => this.input.mastra().map(_MessageList.toUIMessage),
408
+ core: () => this.convertToCoreMessages(this.input.ui())
409
+ };
410
+ response = {
411
+ mastra: () => this.messages.filter((m) => this.responseMessages.has(m))
412
+ };
413
+ drainUnsavedMessages() {
414
+ const messages = this.messages.filter((m) => this.newMessages.has(m) || this.responseMessages.has(m));
415
+ this.newMessages.clear();
416
+ this.responseMessages.clear();
417
+ return messages;
418
+ }
419
+ getSystemMessages(tag) {
420
+ if (tag) {
421
+ return this.taggedSystemMessages[tag] || [];
422
+ }
423
+ return this.systemMessages;
424
+ }
425
+ addSystem(messages, tag) {
426
+ if (!messages) return this;
427
+ for (const message of Array.isArray(messages) ? messages : [messages]) {
428
+ this.addOneSystem(message, tag);
429
+ }
430
+ return this;
431
+ }
432
+ convertToCoreMessages(messages) {
433
+ return ai.convertToCoreMessages(this.sanitizeUIMessages(messages));
434
+ }
435
+ sanitizeUIMessages(messages) {
436
+ const msgs = messages.map((m) => {
437
+ if (m.parts.length === 0) return false;
438
+ const safeParts = m.parts.filter(
439
+ (p) => p.type !== `tool-invocation` || // calls and partial-calls should be updated to be results at this point
440
+ // if they haven't we can't send them back to the llm and need to remove them.
441
+ p.toolInvocation.state !== `call` && p.toolInvocation.state !== `partial-call`
442
+ );
443
+ if (!safeParts.length) return false;
444
+ const sanitized = {
445
+ ...m,
446
+ parts: safeParts
447
+ };
448
+ if (`toolInvocations` in m && m.toolInvocations) {
449
+ sanitized.toolInvocations = m.toolInvocations.filter((t) => t.state === `result`);
450
+ }
451
+ return sanitized;
452
+ }).filter((m) => Boolean(m));
453
+ return msgs;
454
+ }
455
+ addOneSystem(message, tag) {
456
+ if (typeof message === `string`) message = { role: "system", content: message };
457
+ if (tag && !this.isDuplicateSystem(message, tag)) {
458
+ this.taggedSystemMessages[tag] ||= [];
459
+ this.taggedSystemMessages[tag].push(message);
460
+ } else if (!this.isDuplicateSystem(message)) {
461
+ this.systemMessages.push(message);
462
+ }
463
+ }
464
+ isDuplicateSystem(message, tag) {
465
+ if (tag) {
466
+ if (!this.taggedSystemMessages[tag]) return false;
467
+ return this.taggedSystemMessages[tag].some(
468
+ (m) => _MessageList.cacheKeyFromContent(m.content) === _MessageList.cacheKeyFromContent(message.content)
469
+ );
470
+ }
471
+ return this.systemMessages.some(
472
+ (m) => _MessageList.cacheKeyFromContent(m.content) === _MessageList.cacheKeyFromContent(message.content)
473
+ );
474
+ }
475
+ static toUIMessage(m) {
476
+ const contentString = typeof m.content.content === `string` && m.content.content !== "" ? m.content.content : m.content.parts.reduce((prev, part) => {
477
+ if (part.type === `text`) {
478
+ return part.text;
479
+ }
480
+ return prev;
481
+ }, "");
482
+ if (m.role === `user`) {
483
+ return {
484
+ id: m.id,
485
+ role: m.role,
486
+ content: m.content.content || contentString,
487
+ createdAt: m.createdAt,
488
+ parts: m.content.parts,
489
+ experimental_attachments: m.content.experimental_attachments || []
490
+ };
491
+ } else if (m.role === `assistant`) {
492
+ return {
493
+ id: m.id,
494
+ role: m.role,
495
+ content: m.content.content || contentString,
496
+ createdAt: m.createdAt,
497
+ parts: m.content.parts,
498
+ reasoning: void 0,
499
+ toolInvocations: `toolInvocations` in m.content ? m.content.toolInvocations : void 0
500
+ };
501
+ }
502
+ return {
503
+ id: m.id,
504
+ role: m.role,
505
+ content: m.content.content || contentString,
506
+ createdAt: m.createdAt,
507
+ parts: m.content.parts
508
+ };
509
+ }
510
+ getMessageById(id) {
511
+ return this.messages.find((m) => m.id === id);
512
+ }
513
+ shouldReplaceMessage(message) {
514
+ if (!this.messages.length) return { exists: false };
515
+ if (!(`id` in message) || !message?.id) {
516
+ return { exists: false };
517
+ }
518
+ const existingMessage = this.getMessageById(message.id);
519
+ if (!existingMessage) return { exists: false };
520
+ return {
521
+ exists: true,
522
+ shouldReplace: !_MessageList.messagesAreEqual(existingMessage, message),
523
+ id: existingMessage.id
524
+ };
525
+ }
526
+ addOne(message, messageSource) {
527
+ if (message.role === `system` && _MessageList.isVercelCoreMessage(message)) return this.addSystem(message);
528
+ if (message.role === `system`) {
529
+ throw new Error(
530
+ `A non-CoreMessage system message was added - this is not supported as we didn't expect this could happen. Please open a Github issue and let us know what you did to get here. This is the non-CoreMessage system message we received:
531
+
532
+ messageSource: ${messageSource}
533
+
534
+ ${JSON.stringify(message, null, 2)}`
535
+ );
536
+ }
537
+ const messageV2 = this.inputToMastraMessageV2(message, messageSource);
538
+ const { exists, shouldReplace, id } = this.shouldReplaceMessage(messageV2);
539
+ const latestMessage = this.messages.at(-1);
540
+ const singleToolResult = messageV2.role === `assistant` && messageV2.content.parts.length === 1 && messageV2.content.parts[0]?.type === `tool-invocation` && messageV2.content.parts[0].toolInvocation.state === `result` && messageV2.content.parts[0];
541
+ if (singleToolResult && (latestMessage?.role !== `assistant` || !latestMessage.content.parts.some(
542
+ (p) => p.type === `tool-invocation` && p.toolInvocation.toolCallId === singleToolResult.toolInvocation.toolCallId
543
+ ))) {
544
+ return;
545
+ }
546
+ if (messageSource === `memory`) {
547
+ for (const existingMessage of this.messages) {
548
+ if (_MessageList.messagesAreEqual(existingMessage, messageV2)) {
549
+ return;
550
+ }
551
+ }
552
+ }
553
+ const latestMessagePartType = latestMessage?.content?.parts?.filter((p) => p.type !== `step-start`)?.at?.(-1)?.type;
554
+ const newMessageFirstPartType = messageV2.content.parts.filter((p) => p.type !== `step-start`).at(0)?.type;
555
+ const shouldAppendToLastAssistantMessage = latestMessage?.role === "assistant" && messageV2.role === "assistant";
556
+ const shouldAppendToLastAssistantMessageParts = shouldAppendToLastAssistantMessage && newMessageFirstPartType && (newMessageFirstPartType === `tool-invocation` && latestMessagePartType !== `text` || newMessageFirstPartType === latestMessagePartType);
557
+ if (
558
+ // backwards compat check!
559
+ // this condition can technically be removed and it will make it so all new assistant parts will be added to the last assistant message parts instead of creating new db entries.
560
+ // however, for any downstream code that isn't based around using message parts yet, this may cause tool invocations to show up in the wrong order in their UI, because they use the message.toolInvocations and message.content properties which do not indicate how each is ordered in relation to each other.
561
+ // this code check then causes any tool invocation to be created as a new message and not update the previous assistant message parts.
562
+ // without this condition we will see something like
563
+ // parts: [{type:"step-start"}, {type: "text", text: "let me check the weather"}, {type: "tool-invocation", toolInvocation: x}, {type: "text", text: "the weather in x is y"}]
564
+ // with this condition we will see
565
+ // message1.parts: [{type:"step-start"}, {type: "text", text: "let me check the weather"}]
566
+ // message2.parts: [{type: "tool-invocation", toolInvocation: x}]
567
+ // message3.parts: [{type: "text", text: "the weather in x is y"}]
568
+ shouldAppendToLastAssistantMessageParts
569
+ ) {
570
+ latestMessage.createdAt = messageV2.createdAt || latestMessage.createdAt;
571
+ for (const [index, part] of messageV2.content.parts.entries()) {
572
+ if (part.type === "tool-invocation" && part.toolInvocation.state === "result") {
573
+ const existingCallPart = [...latestMessage.content.parts].reverse().find((p) => p.type === "tool-invocation" && p.toolInvocation.toolCallId === part.toolInvocation.toolCallId);
574
+ if (existingCallPart && existingCallPart.type === "tool-invocation") {
575
+ existingCallPart.toolInvocation = {
576
+ ...existingCallPart.toolInvocation,
577
+ state: "result",
578
+ result: part.toolInvocation.result
579
+ };
580
+ if (!latestMessage.content.toolInvocations) {
581
+ latestMessage.content.toolInvocations = [];
582
+ }
583
+ if (!latestMessage.content.toolInvocations.some(
584
+ (t) => t.toolCallId === existingCallPart.toolInvocation.toolCallId
585
+ )) {
586
+ latestMessage.content.toolInvocations.push(existingCallPart.toolInvocation);
587
+ }
588
+ }
589
+ } else if (
590
+ // if there's no part at this index yet in the existing message we're merging into
591
+ !latestMessage.content.parts[index] || // or there is and the parts are not identical
592
+ _MessageList.cacheKeyFromParts([latestMessage.content.parts[index]]) !== _MessageList.cacheKeyFromParts([part])
593
+ ) {
594
+ latestMessage.content.parts.push(part);
595
+ }
596
+ }
597
+ if (latestMessage.createdAt.getTime() < messageV2.createdAt.getTime()) {
598
+ latestMessage.createdAt = messageV2.createdAt;
599
+ }
600
+ if (!latestMessage.content.content && messageV2.content.content) {
601
+ latestMessage.content.content = messageV2.content.content;
602
+ }
603
+ if (latestMessage.content.content && messageV2.content.content && latestMessage.content.content !== messageV2.content.content) {
604
+ latestMessage.content.content = messageV2.content.content;
605
+ }
606
+ } else {
607
+ if (messageV2.role === "assistant" && messageV2.content.parts[0]?.type !== `step-start`) {
608
+ messageV2.content.parts.unshift({ type: "step-start" });
609
+ }
610
+ const existingIndex = shouldReplace && this.messages.findIndex((m) => m.id === id) || -1;
611
+ const existingMessage = existingIndex !== -1 && this.messages[existingIndex];
612
+ if (shouldReplace && existingMessage) {
613
+ this.messages[existingIndex] = messageV2;
614
+ } else if (!exists) {
615
+ this.messages.push(messageV2);
616
+ }
617
+ if (messageSource === `memory`) {
618
+ this.memoryMessages.add(messageV2);
619
+ } else if (messageSource === `response`) {
620
+ this.responseMessages.add(messageV2);
621
+ } else if (messageSource === `user`) {
622
+ this.newMessages.add(messageV2);
623
+ } else {
624
+ throw new Error(`Missing message source for message ${messageV2}`);
625
+ }
626
+ }
627
+ this.messages.sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime());
628
+ return this;
629
+ }
630
+ inputToMastraMessageV2(message, messageSource) {
631
+ if (`threadId` in message && message.threadId && this.memoryInfo && message.threadId !== this.memoryInfo.threadId) {
632
+ throw new Error(
633
+ `Received input message with wrong threadId. Input ${message.threadId}, expected ${this.memoryInfo.threadId}`
634
+ );
635
+ }
636
+ if (`resourceId` in message && message.resourceId && this.memoryInfo?.resourceId && message.resourceId !== this.memoryInfo.resourceId) {
637
+ throw new Error(
638
+ `Received input message with wrong resourceId. Input ${message.resourceId}, expected ${this.memoryInfo.resourceId}`
639
+ );
640
+ }
641
+ if (_MessageList.isMastraMessageV1(message)) {
642
+ return this.mastraMessageV1ToMastraMessageV2(message, messageSource);
643
+ }
644
+ if (_MessageList.isMastraMessageV2(message)) {
645
+ return this.hydrateMastraMessageV2Fields(message);
646
+ }
647
+ if (_MessageList.isVercelCoreMessage(message)) {
648
+ return this.vercelCoreMessageToMastraMessageV2(message, messageSource);
649
+ }
650
+ if (_MessageList.isVercelUIMessage(message)) {
651
+ return this.vercelUIMessageToMastraMessageV2(message, messageSource);
652
+ }
653
+ throw new Error(`Found unhandled message ${JSON.stringify(message)}`);
654
+ }
655
+ lastCreatedAt;
656
+ // this makes sure messages added in order will always have a date atleast 1ms apart.
657
+ generateCreatedAt(messageSource, start) {
658
+ start = start instanceof Date ? start : start ? new Date(start) : void 0;
659
+ if (start && !this.lastCreatedAt) {
660
+ this.lastCreatedAt = start.getTime();
661
+ return start;
662
+ }
663
+ if (start && messageSource === `memory`) {
664
+ return start;
665
+ }
666
+ const now = /* @__PURE__ */ new Date();
667
+ const nowTime = start?.getTime() || now.getTime();
668
+ const lastTime = this.messages.reduce((p, m) => {
669
+ if (m.createdAt.getTime() > p) return m.createdAt.getTime();
670
+ return p;
671
+ }, this.lastCreatedAt || 0);
672
+ if (nowTime <= lastTime) {
673
+ const newDate = new Date(lastTime + 1);
674
+ this.lastCreatedAt = newDate.getTime();
675
+ return newDate;
676
+ }
677
+ this.lastCreatedAt = nowTime;
678
+ return now;
679
+ }
680
+ newMessageId() {
681
+ if (this.generateMessageId) {
682
+ return this.generateMessageId();
683
+ }
684
+ return crypto.randomUUID();
685
+ }
686
+ mastraMessageV1ToMastraMessageV2(message, messageSource) {
687
+ const coreV2 = this.vercelCoreMessageToMastraMessageV2(
688
+ {
689
+ content: message.content,
690
+ role: message.role
691
+ },
692
+ messageSource
693
+ );
694
+ return {
695
+ id: message.id,
696
+ role: coreV2.role,
697
+ createdAt: this.generateCreatedAt(messageSource, message.createdAt),
698
+ threadId: message.threadId,
699
+ resourceId: message.resourceId,
700
+ content: coreV2.content
701
+ };
702
+ }
703
+ hydrateMastraMessageV2Fields(message) {
704
+ if (!(message.createdAt instanceof Date)) message.createdAt = new Date(message.createdAt);
705
+ return message;
706
+ }
707
+ vercelUIMessageToMastraMessageV2(message, messageSource) {
708
+ const content = {
709
+ format: 2,
710
+ parts: message.parts
711
+ };
712
+ if (message.toolInvocations) content.toolInvocations = message.toolInvocations;
713
+ if (message.reasoning) content.reasoning = message.reasoning;
714
+ if (message.annotations) content.annotations = message.annotations;
715
+ if (message.experimental_attachments) {
716
+ content.experimental_attachments = message.experimental_attachments;
717
+ }
718
+ return {
719
+ id: message.id || this.newMessageId(),
720
+ role: _MessageList.getRole(message),
721
+ createdAt: this.generateCreatedAt(messageSource, message.createdAt),
722
+ threadId: this.memoryInfo?.threadId,
723
+ resourceId: this.memoryInfo?.resourceId,
724
+ content
725
+ };
726
+ }
727
+ vercelCoreMessageToMastraMessageV2(coreMessage, messageSource) {
728
+ const id = `id` in coreMessage ? coreMessage.id : this.newMessageId();
729
+ const parts = [];
730
+ const experimentalAttachments = [];
731
+ const toolInvocations = [];
732
+ if (typeof coreMessage.content === "string") {
733
+ parts.push({ type: "step-start" });
734
+ parts.push({
735
+ type: "text",
736
+ text: coreMessage.content
737
+ });
738
+ } else if (Array.isArray(coreMessage.content)) {
739
+ for (const part of coreMessage.content) {
740
+ switch (part.type) {
741
+ case "text":
742
+ parts.push({
743
+ type: "text",
744
+ text: part.text
745
+ });
746
+ break;
747
+ case "tool-call":
748
+ parts.push({
749
+ type: "tool-invocation",
750
+ toolInvocation: {
751
+ state: "call",
752
+ toolCallId: part.toolCallId,
753
+ toolName: part.toolName,
754
+ args: part.args
755
+ }
756
+ });
757
+ break;
758
+ case "tool-result":
759
+ const invocation = {
760
+ state: "result",
761
+ toolCallId: part.toolCallId,
762
+ toolName: part.toolName,
763
+ result: part.result ?? "",
764
+ // undefined will cause AI SDK to throw an error, but for client side tool calls this really could be undefined
765
+ args: {}
766
+ // when we combine this invocation onto the existing tool-call part it will have args already
767
+ };
768
+ parts.push({
769
+ type: "tool-invocation",
770
+ toolInvocation: invocation
771
+ });
772
+ toolInvocations.push(invocation);
773
+ break;
774
+ case "reasoning":
775
+ parts.push({
776
+ type: "reasoning",
777
+ reasoning: part.text,
778
+ // Assuming text is the main reasoning content
779
+ details: [{ type: "text", text: part.text, signature: part.signature }]
780
+ });
781
+ break;
782
+ case "redacted-reasoning":
783
+ parts.push({
784
+ type: "reasoning",
785
+ reasoning: "",
786
+ // No text reasoning for redacted parts
787
+ details: [{ type: "redacted", data: part.data }]
788
+ });
789
+ break;
790
+ case "file":
791
+ if (part.data instanceof URL) {
792
+ if (part.data.protocol !== "data:") {
793
+ experimentalAttachments.push({
794
+ name: part.filename,
795
+ url: part.data.toString(),
796
+ contentType: part.mimeType
797
+ });
798
+ } else {
799
+ try {
800
+ const base64Match = part.data.toString().match(/^data:[^;]+;base64,(.+)$/);
801
+ if (base64Match && base64Match[1]) {
802
+ parts.push({
803
+ type: "file",
804
+ mimeType: part.mimeType,
805
+ data: base64Match[1]
806
+ });
807
+ } else {
808
+ console.error(`Invalid data URL format: ${part.data}`);
809
+ }
810
+ } catch (error) {
811
+ console.error(`Failed to process data URL in CoreMessage file part: ${error}`, error);
812
+ }
813
+ }
814
+ } else {
815
+ try {
816
+ parts.push({
817
+ type: "file",
818
+ mimeType: part.mimeType,
819
+ data: convertDataContentToBase64String(part.data)
820
+ });
821
+ } catch (error) {
822
+ console.error(`Failed to convert binary data to base64 in CoreMessage file part: ${error}`, error);
823
+ }
824
+ }
825
+ break;
826
+ default:
827
+ throw new Error(`Found unknown CoreMessage content part type: ${part.type}`);
828
+ }
829
+ }
830
+ }
831
+ const content = {
832
+ format: 2,
833
+ parts
834
+ };
835
+ if (toolInvocations.length) content.toolInvocations = toolInvocations;
836
+ if (typeof coreMessage.content === `string`) content.content = coreMessage.content;
837
+ if (experimentalAttachments.length) content.experimental_attachments = experimentalAttachments;
838
+ return {
839
+ id,
840
+ role: _MessageList.getRole(coreMessage),
841
+ createdAt: this.generateCreatedAt(messageSource),
842
+ threadId: this.memoryInfo?.threadId,
843
+ resourceId: this.memoryInfo?.resourceId,
844
+ content
845
+ };
846
+ }
847
+ static isVercelUIMessage(msg) {
848
+ return !_MessageList.isMastraMessage(msg) && chunkDXLVS7ML_cjs.isUiMessage(msg);
849
+ }
850
+ static isVercelCoreMessage(msg) {
851
+ return !_MessageList.isMastraMessage(msg) && chunkDXLVS7ML_cjs.isCoreMessage(msg);
852
+ }
853
+ static isMastraMessage(msg) {
854
+ return _MessageList.isMastraMessageV2(msg) || _MessageList.isMastraMessageV1(msg);
855
+ }
856
+ static isMastraMessageV1(msg) {
857
+ return !_MessageList.isMastraMessageV2(msg) && (`threadId` in msg || `resourceId` in msg);
858
+ }
859
+ static isMastraMessageV2(msg) {
860
+ return Boolean(
861
+ msg.content && !Array.isArray(msg.content) && typeof msg.content !== `string` && // any newly saved Mastra message v2 shape will have content: { format: 2 }
862
+ `format` in msg.content && msg.content.format === 2
863
+ );
864
+ }
865
+ static getRole(message) {
866
+ if (message.role === `assistant` || message.role === `tool`) return `assistant`;
867
+ if (message.role === `user`) return `user`;
868
+ throw new Error(
869
+ `BUG: add handling for message role ${message.role} in message ${JSON.stringify(message, null, 2)}`
870
+ );
871
+ }
872
+ static cacheKeyFromParts(parts) {
873
+ let key = ``;
874
+ for (const part of parts) {
875
+ key += part.type;
876
+ if (part.type === `text`) {
877
+ key += part.text.length;
878
+ }
879
+ if (part.type === `tool-invocation`) {
880
+ key += part.toolInvocation.toolCallId;
881
+ key += part.toolInvocation.state;
882
+ }
883
+ if (part.type === `reasoning`) {
884
+ key += part.reasoning.length;
885
+ }
886
+ if (part.type === `file`) {
887
+ key += part.data.length;
888
+ key += part.mimeType;
889
+ }
890
+ }
891
+ return key;
892
+ }
893
+ static coreContentToString(content) {
894
+ if (typeof content === `string`) return content;
895
+ return content.reduce((p, c) => {
896
+ if (c.type === `text`) {
897
+ p += c.text;
898
+ }
899
+ return p;
900
+ }, "");
901
+ }
902
+ static cacheKeyFromContent(content) {
903
+ if (typeof content === `string`) return content;
904
+ let key = ``;
905
+ for (const part of content) {
906
+ key += part.type;
907
+ if (part.type === `text`) {
908
+ key += part.text.length;
909
+ }
910
+ if (part.type === `reasoning`) {
911
+ key += part.text.length;
912
+ }
913
+ if (part.type === `tool-call`) {
914
+ key += part.toolCallId;
915
+ key += part.toolName;
916
+ }
917
+ if (part.type === `tool-result`) {
918
+ key += part.toolCallId;
919
+ key += part.toolName;
920
+ }
921
+ if (part.type === `file`) {
922
+ key += part.filename;
923
+ key += part.mimeType;
924
+ }
925
+ if (part.type === `image`) {
926
+ key += part.image instanceof URL ? part.image.toString() : part.image.toString().length;
927
+ key += part.mimeType;
928
+ }
929
+ if (part.type === `redacted-reasoning`) {
930
+ key += part.data.length;
931
+ }
932
+ }
933
+ return key;
934
+ }
935
+ static messagesAreEqual(one, two) {
936
+ const oneUI = _MessageList.isVercelUIMessage(one) && one;
937
+ const twoUI = _MessageList.isVercelUIMessage(two) && two;
938
+ if (oneUI && !twoUI) return false;
939
+ if (oneUI && twoUI) {
940
+ return _MessageList.cacheKeyFromParts(one.parts) === _MessageList.cacheKeyFromParts(two.parts);
941
+ }
942
+ const oneCM = _MessageList.isVercelCoreMessage(one) && one;
943
+ const twoCM = _MessageList.isVercelCoreMessage(two) && two;
944
+ if (oneCM && !twoCM) return false;
945
+ if (oneCM && twoCM) {
946
+ return _MessageList.cacheKeyFromContent(oneCM.content) === _MessageList.cacheKeyFromContent(twoCM.content);
947
+ }
948
+ const oneMM1 = _MessageList.isMastraMessageV1(one) && one;
949
+ const twoMM1 = _MessageList.isMastraMessageV1(two) && two;
950
+ if (oneMM1 && !twoMM1) return false;
951
+ if (oneMM1 && twoMM1) {
952
+ return oneMM1.id === twoMM1.id && _MessageList.cacheKeyFromContent(oneMM1.content) === _MessageList.cacheKeyFromContent(twoMM1.content);
953
+ }
954
+ const oneMM2 = _MessageList.isMastraMessageV2(one) && one;
955
+ const twoMM2 = _MessageList.isMastraMessageV2(two) && two;
956
+ if (oneMM2 && !twoMM2) return false;
957
+ if (oneMM2 && twoMM2) {
958
+ return oneMM2.id === twoMM2.id && _MessageList.cacheKeyFromParts(oneMM2.content.parts) === _MessageList.cacheKeyFromParts(twoMM2.content.parts);
959
+ }
960
+ return true;
961
+ }
962
+ };
963
+
964
+ exports.MessageList = MessageList;