@mastra/core 0.0.0-storage-20250225005900

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 (82) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +180 -0
  3. package/dist/agent/index.d.ts +15 -0
  4. package/dist/agent/index.js +1 -0
  5. package/dist/base-CHNzbTDj.d.ts +894 -0
  6. package/dist/base-eWkcLLSb.d.ts +139 -0
  7. package/dist/base.d.ts +6 -0
  8. package/dist/base.js +1 -0
  9. package/dist/bundler/index.d.ts +28 -0
  10. package/dist/bundler/index.js +1 -0
  11. package/dist/chunk-4IIE6KIC.js +10 -0
  12. package/dist/chunk-4ZNSY7J7.js +215 -0
  13. package/dist/chunk-4ZRHVG25.js +402 -0
  14. package/dist/chunk-5275WBGX.js +318 -0
  15. package/dist/chunk-6RDA4JYW.js +49 -0
  16. package/dist/chunk-BB4KXGBU.js +83 -0
  17. package/dist/chunk-C6A6W6XS.js +77 -0
  18. package/dist/chunk-FEBWYMJQ.js +416 -0
  19. package/dist/chunk-KP5SHTKA.js +145 -0
  20. package/dist/chunk-N7KZVQDK.js +61 -0
  21. package/dist/chunk-NDQR6IPC.js +37 -0
  22. package/dist/chunk-NUDAZEOG.js +35 -0
  23. package/dist/chunk-ORM3OCHX.js +1367 -0
  24. package/dist/chunk-PNZK456O.js +88 -0
  25. package/dist/chunk-QXPUH6PK.js +620 -0
  26. package/dist/chunk-RG66XEJT.js +8 -0
  27. package/dist/chunk-SIFBBGY6.js +190 -0
  28. package/dist/chunk-TCMOYQ74.js +1204 -0
  29. package/dist/chunk-WIBGG4X6.js +173 -0
  30. package/dist/chunk-YKDBP67T.js +346 -0
  31. package/dist/chunk-YUOADWSP.js +22 -0
  32. package/dist/chunk-Z735LDV7.js +10 -0
  33. package/dist/chunk-ZDWFBE5L.js +1 -0
  34. package/dist/chunk-ZINPRHAN.js +22 -0
  35. package/dist/deployer/index.d.ts +19 -0
  36. package/dist/deployer/index.js +1 -0
  37. package/dist/eval/index.d.ts +28 -0
  38. package/dist/eval/index.js +1 -0
  39. package/dist/filter/index.d.ts +90 -0
  40. package/dist/filter/index.js +1 -0
  41. package/dist/hooks/index.d.ts +33 -0
  42. package/dist/hooks/index.js +1 -0
  43. package/dist/index-C5uPdbs4.d.ts +90 -0
  44. package/dist/index.d.ts +98 -0
  45. package/dist/index.js +119 -0
  46. package/dist/integration/index.d.ts +53 -0
  47. package/dist/integration/index.js +1 -0
  48. package/dist/llm/index.d.ts +15 -0
  49. package/dist/llm/index.js +1 -0
  50. package/dist/logger/index.d.ts +3 -0
  51. package/dist/logger/index.js +1 -0
  52. package/dist/mastra/index.d.ts +68 -0
  53. package/dist/mastra/index.js +1 -0
  54. package/dist/memory/index.d.ts +15 -0
  55. package/dist/memory/index.js +1 -0
  56. package/dist/relevance/index.d.ts +21 -0
  57. package/dist/relevance/index.js +1 -0
  58. package/dist/storage/index.d.ts +15 -0
  59. package/dist/storage/index.js +2 -0
  60. package/dist/storage/libsql/index.d.ts +81 -0
  61. package/dist/storage/libsql/index.js +1 -0
  62. package/dist/telemetry/index.d.ts +51 -0
  63. package/dist/telemetry/index.js +1 -0
  64. package/dist/telemetry/otel-vendor.d.ts +7 -0
  65. package/dist/telemetry/otel-vendor.js +7 -0
  66. package/dist/tools/index.d.ts +29 -0
  67. package/dist/tools/index.js +1 -0
  68. package/dist/tts/index.d.ts +28 -0
  69. package/dist/tts/index.js +1 -0
  70. package/dist/types-m9RryK9a.d.ts +14 -0
  71. package/dist/utils.d.ts +26 -0
  72. package/dist/utils.js +1 -0
  73. package/dist/vector/index.d.ts +29 -0
  74. package/dist/vector/index.js +1 -0
  75. package/dist/vector/libsql/index.d.ts +29 -0
  76. package/dist/vector/libsql/index.js +1 -0
  77. package/dist/voice/index.d.ts +67 -0
  78. package/dist/voice/index.js +76 -0
  79. package/dist/workflow-CddifUps.d.ts +92 -0
  80. package/dist/workflows/index.d.ts +31 -0
  81. package/dist/workflows/index.js +1 -0
  82. package/package.json +134 -0
@@ -0,0 +1,1367 @@
1
+ import { InstrumentClass } from './chunk-4ZRHVG25.js';
2
+ import { delay } from './chunk-WIBGG4X6.js';
3
+ import { MastraBase } from './chunk-6RDA4JYW.js';
4
+ import { RegisteredLogger } from './chunk-KP5SHTKA.js';
5
+ import { executeHook } from './chunk-BB4KXGBU.js';
6
+ import { __decoratorStart, __decorateElement, __runInitializers } from './chunk-C6A6W6XS.js';
7
+ import { randomUUID } from 'crypto';
8
+ import { z } from 'zod';
9
+ import { generateText, jsonSchema, generateObject, streamText, streamObject } from 'ai';
10
+
11
+ // src/llm/model/base.ts
12
+ var MastraLLMBase = class extends MastraBase {
13
+ // @ts-ignore
14
+ #mastra;
15
+ #model;
16
+ constructor({
17
+ name,
18
+ model
19
+ }) {
20
+ super({
21
+ component: RegisteredLogger.LLM,
22
+ name
23
+ });
24
+ this.#model = model;
25
+ }
26
+ getProvider() {
27
+ return this.#model.provider;
28
+ }
29
+ getModelId() {
30
+ return this.#model.modelId;
31
+ }
32
+ getModel() {
33
+ return this.#model;
34
+ }
35
+ convertToMessages(messages) {
36
+ if (Array.isArray(messages)) {
37
+ return messages.map(m => {
38
+ if (typeof m === "string") {
39
+ return {
40
+ role: "user",
41
+ content: m
42
+ };
43
+ }
44
+ return m;
45
+ });
46
+ }
47
+ return [{
48
+ role: "user",
49
+ content: messages
50
+ }];
51
+ }
52
+ __registerPrimitives(p) {
53
+ if (p.telemetry) {
54
+ this.__setTelemetry(p.telemetry);
55
+ }
56
+ if (p.logger) {
57
+ this.__setLogger(p.logger);
58
+ }
59
+ this.#mastra = p;
60
+ }
61
+ async __text(input) {
62
+ this.logger.debug(`[LLMs:${this.name}] Generating text.`, {
63
+ input
64
+ });
65
+ throw new Error("Method not implemented.");
66
+ }
67
+ async __textObject(input) {
68
+ this.logger.debug(`[LLMs:${this.name}] Generating object.`, {
69
+ input
70
+ });
71
+ throw new Error("Method not implemented.");
72
+ }
73
+ async generate(messages, options = {}) {
74
+ this.logger.debug(`[LLMs:${this.name}] Generating text.`, {
75
+ messages,
76
+ options
77
+ });
78
+ throw new Error("Method not implemented.");
79
+ }
80
+ async __stream(input) {
81
+ this.logger.debug(`[LLMs:${this.name}] Streaming text.`, {
82
+ input
83
+ });
84
+ throw new Error("Method not implemented.");
85
+ }
86
+ async __streamObject(input) {
87
+ this.logger.debug(`[LLMs:${this.name}] Streaming object.`, {
88
+ input
89
+ });
90
+ throw new Error("Method not implemented.");
91
+ }
92
+ async stream(messages, options = {}) {
93
+ this.logger.debug(`[LLMs:${this.name}] Streaming text.`, {
94
+ messages,
95
+ options
96
+ });
97
+ throw new Error("Method not implemented.");
98
+ }
99
+ };
100
+ var MastraLLM = class extends MastraLLMBase {
101
+ #model;
102
+ #mastra;
103
+ constructor({
104
+ model,
105
+ mastra
106
+ }) {
107
+ super({
108
+ name: "aisdk",
109
+ model
110
+ });
111
+ this.#model = model;
112
+ if (mastra) {
113
+ this.#mastra = mastra;
114
+ if (mastra.logger) {
115
+ this.__setLogger(mastra.logger);
116
+ }
117
+ }
118
+ }
119
+ __registerPrimitives(p) {
120
+ if (p.telemetry) {
121
+ this.__setTelemetry(p.telemetry);
122
+ }
123
+ if (p.logger) {
124
+ this.__setLogger(p.logger);
125
+ }
126
+ this.#mastra = p;
127
+ }
128
+ getProvider() {
129
+ return this.#model.provider;
130
+ }
131
+ getModelId() {
132
+ return this.#model.modelId;
133
+ }
134
+ getModel() {
135
+ return this.#model;
136
+ }
137
+ convertTools({
138
+ tools,
139
+ runId
140
+ } = {}) {
141
+ this.logger.debug("Starting tool conversion for LLM");
142
+ const converted = Object.entries(tools || {}).reduce((memo, value) => {
143
+ const k = value[0];
144
+ const tool = value[1];
145
+ if (tool) {
146
+ memo[k] = {
147
+ description: tool.description,
148
+ parameters: tool.inputSchema,
149
+ execute: async props => {
150
+ try {
151
+ this.logger.debug("Executing tool", {
152
+ tool: k,
153
+ props
154
+ });
155
+ return tool.execute({
156
+ context: props,
157
+ mastra: this.#mastra,
158
+ runId
159
+ });
160
+ } catch (error) {
161
+ this.logger.error("Error executing tool", {
162
+ tool: k,
163
+ props,
164
+ error
165
+ });
166
+ throw error;
167
+ }
168
+ }
169
+ };
170
+ }
171
+ return memo;
172
+ }, {});
173
+ this.logger.debug(`Converted tools for LLM`);
174
+ return converted;
175
+ }
176
+ async __text({
177
+ runId,
178
+ messages,
179
+ maxSteps,
180
+ tools,
181
+ convertedTools,
182
+ temperature,
183
+ toolChoice = "auto",
184
+ onStepFinish
185
+ }) {
186
+ const model = this.#model;
187
+ this.logger.debug(`[LLM] - Generating text`, {
188
+ runId,
189
+ messages,
190
+ maxSteps,
191
+ tools: Object.keys(tools || convertedTools || {})
192
+ });
193
+ const finalTools = convertedTools || this.convertTools({
194
+ tools,
195
+ runId
196
+ });
197
+ const argsForExecute = {
198
+ model,
199
+ temperature,
200
+ tools: {
201
+ ...finalTools
202
+ },
203
+ toolChoice,
204
+ maxSteps,
205
+ onStepFinish: async props => {
206
+ onStepFinish?.(JSON.stringify(props, null, 2));
207
+ this.logger.debug("[LLM] - Step Change:", {
208
+ text: props?.text,
209
+ toolCalls: props?.toolCalls,
210
+ toolResults: props?.toolResults,
211
+ finishReason: props?.finishReason,
212
+ usage: props?.usage,
213
+ runId
214
+ });
215
+ if (props?.response?.headers?.["x-ratelimit-remaining-tokens"] && parseInt(props?.response?.headers?.["x-ratelimit-remaining-tokens"], 10) < 2e3) {
216
+ this.logger.warn("Rate limit approaching, waiting 10 seconds");
217
+ await delay(10 * 1e3);
218
+ }
219
+ }
220
+ };
221
+ return await generateText({
222
+ messages,
223
+ ...argsForExecute,
224
+ experimental_telemetry: this.experimental_telemetry
225
+ });
226
+ }
227
+ async __textObject({
228
+ messages,
229
+ onStepFinish,
230
+ maxSteps = 5,
231
+ tools,
232
+ convertedTools,
233
+ structuredOutput,
234
+ runId,
235
+ temperature,
236
+ toolChoice = "auto"
237
+ }) {
238
+ const model = this.#model;
239
+ this.logger.debug(`[LLM] - Generating a text object`, {
240
+ runId
241
+ });
242
+ const finalTools = convertedTools || this.convertTools({
243
+ tools,
244
+ runId
245
+ });
246
+ const argsForExecute = {
247
+ model,
248
+ temperature,
249
+ tools: {
250
+ ...finalTools
251
+ },
252
+ maxSteps,
253
+ toolChoice,
254
+ onStepFinish: async props => {
255
+ onStepFinish?.(JSON.stringify(props, null, 2));
256
+ this.logger.debug("[LLM] - Step Change:", {
257
+ text: props?.text,
258
+ toolCalls: props?.toolCalls,
259
+ toolResults: props?.toolResults,
260
+ finishReason: props?.finishReason,
261
+ usage: props?.usage,
262
+ runId
263
+ });
264
+ if (props?.response?.headers?.["x-ratelimit-remaining-tokens"] && parseInt(props?.response?.headers?.["x-ratelimit-remaining-tokens"], 10) < 2e3) {
265
+ this.logger.warn("Rate limit approaching, waiting 10 seconds", {
266
+ runId
267
+ });
268
+ await delay(10 * 1e3);
269
+ }
270
+ }
271
+ };
272
+ let schema;
273
+ let output = "object";
274
+ if (typeof structuredOutput.parse === "function") {
275
+ schema = structuredOutput;
276
+ if (schema instanceof z.ZodArray) {
277
+ output = "array";
278
+ schema = schema._def.type;
279
+ }
280
+ } else {
281
+ schema = jsonSchema(structuredOutput);
282
+ }
283
+ return await generateObject({
284
+ messages,
285
+ ...argsForExecute,
286
+ output,
287
+ schema,
288
+ experimental_telemetry: this.experimental_telemetry
289
+ });
290
+ }
291
+ async __stream({
292
+ messages,
293
+ onStepFinish,
294
+ onFinish,
295
+ maxSteps = 5,
296
+ tools,
297
+ convertedTools,
298
+ runId,
299
+ temperature,
300
+ toolChoice = "auto"
301
+ }) {
302
+ const model = this.#model;
303
+ this.logger.debug(`[LLM] - Streaming text`, {
304
+ runId,
305
+ messages,
306
+ maxSteps,
307
+ tools: Object.keys(tools || convertedTools || {})
308
+ });
309
+ const finalTools = convertedTools || this.convertTools({
310
+ tools,
311
+ runId
312
+ });
313
+ const argsForExecute = {
314
+ model,
315
+ temperature,
316
+ tools: {
317
+ ...finalTools
318
+ },
319
+ maxSteps,
320
+ toolChoice,
321
+ onStepFinish: async props => {
322
+ onStepFinish?.(JSON.stringify(props, null, 2));
323
+ this.logger.debug("[LLM] - Stream Step Change:", {
324
+ text: props?.text,
325
+ toolCalls: props?.toolCalls,
326
+ toolResults: props?.toolResults,
327
+ finishReason: props?.finishReason,
328
+ usage: props?.usage,
329
+ runId
330
+ });
331
+ if (props?.response?.headers?.["x-ratelimit-remaining-tokens"] && parseInt(props?.response?.headers?.["x-ratelimit-remaining-tokens"], 10) < 2e3) {
332
+ this.logger.warn("Rate limit approaching, waiting 10 seconds", {
333
+ runId
334
+ });
335
+ await delay(10 * 1e3);
336
+ }
337
+ },
338
+ onFinish: async props => {
339
+ onFinish?.(JSON.stringify(props, null, 2));
340
+ this.logger.debug("[LLM] - Stream Finished:", {
341
+ text: props?.text,
342
+ toolCalls: props?.toolCalls,
343
+ toolResults: props?.toolResults,
344
+ finishReason: props?.finishReason,
345
+ usage: props?.usage,
346
+ runId
347
+ });
348
+ }
349
+ };
350
+ return await streamText({
351
+ messages,
352
+ ...argsForExecute,
353
+ experimental_telemetry: this.experimental_telemetry
354
+ });
355
+ }
356
+ async __streamObject({
357
+ messages,
358
+ onStepFinish,
359
+ onFinish,
360
+ maxSteps = 5,
361
+ tools,
362
+ convertedTools,
363
+ structuredOutput,
364
+ runId,
365
+ temperature,
366
+ toolChoice = "auto"
367
+ }) {
368
+ const model = this.#model;
369
+ this.logger.debug(`[LLM] - Streaming structured output`, {
370
+ runId,
371
+ messages,
372
+ maxSteps,
373
+ tools: Object.keys(tools || convertedTools || {})
374
+ });
375
+ const finalTools = convertedTools || this.convertTools({
376
+ tools,
377
+ runId
378
+ });
379
+ const argsForExecute = {
380
+ model,
381
+ temperature,
382
+ tools: {
383
+ ...finalTools
384
+ },
385
+ maxSteps,
386
+ toolChoice,
387
+ onStepFinish: async props => {
388
+ onStepFinish?.(JSON.stringify(props, null, 2));
389
+ this.logger.debug("[LLM] - Stream Step Change:", {
390
+ text: props?.text,
391
+ toolCalls: props?.toolCalls,
392
+ toolResults: props?.toolResults,
393
+ finishReason: props?.finishReason,
394
+ usage: props?.usage,
395
+ runId
396
+ });
397
+ if (props?.response?.headers?.["x-ratelimit-remaining-tokens"] && parseInt(props?.response?.headers?.["x-ratelimit-remaining-tokens"], 10) < 2e3) {
398
+ this.logger.warn("Rate limit approaching, waiting 10 seconds", {
399
+ runId
400
+ });
401
+ await delay(10 * 1e3);
402
+ }
403
+ },
404
+ onFinish: async props => {
405
+ onFinish?.(JSON.stringify(props, null, 2));
406
+ this.logger.debug("[LLM] - Stream Finished:", {
407
+ text: props?.text,
408
+ toolCalls: props?.toolCalls,
409
+ toolResults: props?.toolResults,
410
+ finishReason: props?.finishReason,
411
+ usage: props?.usage,
412
+ runId
413
+ });
414
+ }
415
+ };
416
+ let schema;
417
+ let output = "object";
418
+ if (typeof structuredOutput.parse === "function") {
419
+ schema = structuredOutput;
420
+ if (schema instanceof z.ZodArray) {
421
+ output = "array";
422
+ schema = schema._def.type;
423
+ }
424
+ } else {
425
+ schema = jsonSchema(structuredOutput);
426
+ }
427
+ return streamObject({
428
+ messages,
429
+ ...argsForExecute,
430
+ output,
431
+ schema,
432
+ experimental_telemetry: this.experimental_telemetry
433
+ });
434
+ }
435
+ async generate(messages, {
436
+ maxSteps = 5,
437
+ onStepFinish,
438
+ tools,
439
+ convertedTools,
440
+ runId,
441
+ output = "text",
442
+ temperature
443
+ } = {}) {
444
+ const msgs = this.convertToMessages(messages);
445
+ if (output === "text") {
446
+ return await this.__text({
447
+ messages: msgs,
448
+ onStepFinish,
449
+ maxSteps,
450
+ tools,
451
+ convertedTools,
452
+ runId,
453
+ temperature
454
+ });
455
+ }
456
+ return await this.__textObject({
457
+ messages: msgs,
458
+ structuredOutput: output,
459
+ onStepFinish,
460
+ maxSteps,
461
+ tools,
462
+ convertedTools,
463
+ runId
464
+ });
465
+ }
466
+ async stream(messages, {
467
+ maxSteps = 5,
468
+ onFinish,
469
+ onStepFinish,
470
+ tools,
471
+ convertedTools,
472
+ runId,
473
+ output = "text",
474
+ temperature
475
+ } = {}) {
476
+ const msgs = this.convertToMessages(messages);
477
+ if (output === "text") {
478
+ return await this.__stream({
479
+ messages: msgs,
480
+ onStepFinish,
481
+ onFinish,
482
+ maxSteps,
483
+ tools,
484
+ convertedTools,
485
+ runId,
486
+ temperature
487
+ });
488
+ }
489
+ return await this.__streamObject({
490
+ messages: msgs,
491
+ structuredOutput: output,
492
+ onStepFinish,
493
+ onFinish,
494
+ maxSteps,
495
+ tools,
496
+ convertedTools,
497
+ runId,
498
+ temperature
499
+ });
500
+ }
501
+ };
502
+
503
+ // src/agent/index.ts
504
+ var _Agent_decorators, _init, _a;
505
+ _Agent_decorators = [InstrumentClass({
506
+ prefix: "agent",
507
+ excludeMethods: ["__setTools", "__setLogger", "__setTelemetry", "log"]
508
+ })];
509
+ var Agent = class extends (_a = MastraBase) {
510
+ name;
511
+ llm;
512
+ instructions;
513
+ model;
514
+ #mastra;
515
+ #memory;
516
+ tools;
517
+ /** @deprecated This property is deprecated. Use evals instead. */
518
+ metrics;
519
+ evals;
520
+ voice;
521
+ constructor(config) {
522
+ super({
523
+ component: RegisteredLogger.AGENT
524
+ });
525
+ this.name = config.name;
526
+ this.instructions = config.instructions;
527
+ if (!config.model) {
528
+ throw new Error(`LanugageModel is required to create an Agent. Please provider the 'model'.`);
529
+ }
530
+ this.llm = new MastraLLM({
531
+ model: config.model
532
+ });
533
+ this.tools = {};
534
+ this.metrics = {};
535
+ this.evals = {};
536
+ if (config.tools) {
537
+ this.tools = config.tools;
538
+ }
539
+ if (config.mastra) {
540
+ this.#mastra = config.mastra;
541
+ }
542
+ if (config.metrics) {
543
+ this.logger.warn("The metrics property is deprecated. Please use evals instead to add evaluation metrics.");
544
+ this.metrics = config.metrics;
545
+ this.evals = config.metrics;
546
+ }
547
+ if (config.evals) {
548
+ this.evals = config.evals;
549
+ }
550
+ if (config.memory) {
551
+ this.#memory = config.memory;
552
+ }
553
+ if (config.voice) {
554
+ this.voice = config.voice;
555
+ }
556
+ }
557
+ hasOwnMemory() {
558
+ return Boolean(this.#memory);
559
+ }
560
+ getMemory() {
561
+ return this.#memory ?? this.#mastra?.memory;
562
+ }
563
+ __updateInstructions(newInstructions) {
564
+ this.instructions = newInstructions;
565
+ this.logger.debug(`[Agents:${this.name}] Instructions updated.`, {
566
+ model: this.model,
567
+ name: this.name
568
+ });
569
+ }
570
+ __registerPrimitives(p) {
571
+ if (p.telemetry) {
572
+ this.__setTelemetry(p.telemetry);
573
+ }
574
+ if (p.logger) {
575
+ this.__setLogger(p.logger);
576
+ }
577
+ this.llm.__registerPrimitives(p);
578
+ this.#mastra = p;
579
+ this.logger.debug(`[Agents:${this.name}] initialized.`, {
580
+ model: this.model,
581
+ name: this.name
582
+ });
583
+ }
584
+ /**
585
+ * Set the concrete tools for the agent
586
+ * @param tools
587
+ */
588
+ __setTools(tools) {
589
+ this.tools = tools;
590
+ this.logger.debug(`[Agents:${this.name}] Tools set for agent ${this.name}`, {
591
+ model: this.model,
592
+ name: this.name
593
+ });
594
+ }
595
+ async generateTitleFromUserMessage({
596
+ message
597
+ }) {
598
+ const {
599
+ object
600
+ } = await this.llm.__textObject({
601
+ messages: [{
602
+ role: "system",
603
+ content: `
604
+
605
+ - you will generate a short title based on the first message a user begins a conversation with
606
+ - ensure it is not more than 80 characters long
607
+ - the title should be a summary of the user's message
608
+ - do not use quotes or colons`
609
+ }, {
610
+ role: "user",
611
+ content: JSON.stringify(message)
612
+ }],
613
+ structuredOutput: z.object({
614
+ title: z.string()
615
+ })
616
+ });
617
+ return object.title;
618
+ }
619
+ getMostRecentUserMessage(messages) {
620
+ const userMessages = messages.filter(message => message.role === "user");
621
+ return userMessages.at(-1);
622
+ }
623
+ async genTitle(userMessage) {
624
+ let title = "New Thread";
625
+ try {
626
+ if (userMessage) {
627
+ title = await this.generateTitleFromUserMessage({
628
+ message: userMessage
629
+ });
630
+ }
631
+ } catch (e) {
632
+ console.error("Error generating title:", e);
633
+ }
634
+ return title;
635
+ }
636
+ async saveMemory({
637
+ threadId,
638
+ memoryConfig,
639
+ resourceId,
640
+ userMessages,
641
+ runId
642
+ }) {
643
+ const userMessage = this.getMostRecentUserMessage(userMessages);
644
+ const memory = this.getMemory();
645
+ if (memory) {
646
+ let thread;
647
+ if (!threadId) {
648
+ this.logger.debug(`No threadId, creating new thread for agent ${this.name}`, {
649
+ runId: runId || this.name
650
+ });
651
+ const title = await this.genTitle(userMessage);
652
+ thread = await memory.createThread({
653
+ threadId,
654
+ resourceId,
655
+ title,
656
+ memoryConfig
657
+ });
658
+ } else {
659
+ thread = await memory.getThreadById({
660
+ threadId
661
+ });
662
+ if (!thread) {
663
+ this.logger.debug(`Thread with id ${threadId} not found, creating new thread for agent ${this.name}`, {
664
+ runId: runId || this.name
665
+ });
666
+ const title = await this.genTitle(userMessage);
667
+ thread = await memory.createThread({
668
+ threadId,
669
+ resourceId,
670
+ title,
671
+ memoryConfig
672
+ });
673
+ }
674
+ }
675
+ const newMessages = userMessage ? [userMessage] : userMessages;
676
+ if (thread) {
677
+ const messages = newMessages.map(u => {
678
+ return {
679
+ id: this.getMemory()?.generateId(),
680
+ createdAt: /* @__PURE__ */new Date(),
681
+ threadId: thread.id,
682
+ ...u,
683
+ content: u.content,
684
+ role: u.role,
685
+ type: "text"
686
+ };
687
+ });
688
+ const memoryMessages = threadId && memory ? (await memory.rememberMessages({
689
+ threadId,
690
+ config: memoryConfig,
691
+ vectorMessageSearch: messages.slice(-1).map(m => {
692
+ if (typeof m === `string`) {
693
+ return m;
694
+ }
695
+ return m?.content || ``;
696
+ }).join(`
697
+ `)
698
+ })).messages : [];
699
+ if (memory) {
700
+ await memory.saveMessages({
701
+ messages,
702
+ memoryConfig
703
+ });
704
+ }
705
+ this.logger.debug("Saved messages to memory", {
706
+ threadId: thread.id,
707
+ runId
708
+ });
709
+ const memorySystemMessage = memory && threadId ? await memory.getSystemMessage({
710
+ threadId,
711
+ memoryConfig
712
+ }) : null;
713
+ return {
714
+ threadId: thread.id,
715
+ messages: [memorySystemMessage ? {
716
+ role: "system",
717
+ content: memorySystemMessage
718
+ } : null, ...this.sanitizeResponseMessages(memoryMessages), ...newMessages].filter(message => Boolean(message))
719
+ };
720
+ }
721
+ return {
722
+ threadId: thread?.id || threadId || "",
723
+ messages: userMessages
724
+ };
725
+ }
726
+ return {
727
+ threadId: threadId || "",
728
+ messages: userMessages
729
+ };
730
+ }
731
+ async saveResponse({
732
+ result,
733
+ threadId,
734
+ resourceId,
735
+ runId,
736
+ memoryConfig
737
+ }) {
738
+ const {
739
+ response
740
+ } = result;
741
+ try {
742
+ if (response.messages) {
743
+ const ms = Array.isArray(response.messages) ? response.messages : [response.messages];
744
+ const responseMessagesWithoutIncompleteToolCalls = this.sanitizeResponseMessages(ms);
745
+ const memory = this.getMemory();
746
+ if (memory) {
747
+ this.logger.debug(`[Agent:${this.name}] - Memory persistence: store=${this.getMemory()?.constructor.name} threadId=${threadId}`, {
748
+ runId,
749
+ resourceId,
750
+ threadId,
751
+ memoryStore: this.getMemory()?.constructor.name
752
+ });
753
+ await memory.saveMessages({
754
+ memoryConfig,
755
+ messages: responseMessagesWithoutIncompleteToolCalls.map(message => {
756
+ const messageId = randomUUID();
757
+ let toolCallIds;
758
+ let toolCallArgs;
759
+ let toolNames;
760
+ let type = "text";
761
+ if (message.role === "tool") {
762
+ toolCallIds = message.content.map(content => content.toolCallId);
763
+ type = "tool-result";
764
+ }
765
+ if (message.role === "assistant") {
766
+ const assistantContent = message.content;
767
+ const assistantToolCalls = assistantContent.map(content => {
768
+ if (content.type === "tool-call") {
769
+ return {
770
+ toolCallId: content.toolCallId,
771
+ toolArgs: content.args,
772
+ toolName: content.toolName
773
+ };
774
+ }
775
+ return void 0;
776
+ })?.filter(Boolean);
777
+ toolCallIds = assistantToolCalls?.map(toolCall => toolCall.toolCallId);
778
+ toolCallArgs = assistantToolCalls?.map(toolCall => toolCall.toolArgs);
779
+ toolNames = assistantToolCalls?.map(toolCall => toolCall.toolName);
780
+ type = assistantContent?.[0]?.type;
781
+ }
782
+ return {
783
+ id: messageId,
784
+ threadId,
785
+ role: message.role,
786
+ content: message.content,
787
+ createdAt: /* @__PURE__ */new Date(),
788
+ toolCallIds: toolCallIds?.length ? toolCallIds : void 0,
789
+ toolCallArgs: toolCallArgs?.length ? toolCallArgs : void 0,
790
+ toolNames: toolNames?.length ? toolNames : void 0,
791
+ type
792
+ };
793
+ })
794
+ });
795
+ }
796
+ }
797
+ } catch (err) {
798
+ this.logger.error(`[Agent:${this.name}] - Failed to save assistant response`, {
799
+ error: err,
800
+ runId
801
+ });
802
+ }
803
+ }
804
+ sanitizeResponseMessages(messages) {
805
+ let toolResultIds = [];
806
+ let toolCallIds = [];
807
+ for (const message of messages) {
808
+ if (message.role === "tool") {
809
+ for (const content of message.content) {
810
+ if (content.type === "tool-result") {
811
+ toolResultIds.push(content.toolCallId);
812
+ }
813
+ }
814
+ }
815
+ if (message.role === "assistant" || message.role === "user") {
816
+ for (const content of message.content) {
817
+ if (typeof content !== `string`) {
818
+ if (content.type === `tool-call`) {
819
+ toolCallIds.push(content.toolCallId);
820
+ }
821
+ }
822
+ }
823
+ }
824
+ }
825
+ const messagesBySanitizedContent = messages.map(message => {
826
+ if (message.role !== "assistant" && message.role !== `tool` && message.role !== `user`) return message;
827
+ if (typeof message.content === "string") return message;
828
+ const sanitizedContent = message.content.filter(content => {
829
+ if (content.type === `tool-call`) {
830
+ return toolResultIds.includes(content.toolCallId);
831
+ }
832
+ if (content.type === `text`) {
833
+ return content.text.trim() !== ``;
834
+ }
835
+ if (content.type === `tool-result`) {
836
+ return toolCallIds.includes(content.toolCallId);
837
+ }
838
+ return true;
839
+ });
840
+ return {
841
+ ...message,
842
+ content: sanitizedContent
843
+ };
844
+ });
845
+ return messagesBySanitizedContent.filter(message => {
846
+ if (typeof message.content === `string`) {
847
+ return message.content !== "";
848
+ }
849
+ if (Array.isArray(message.content)) {
850
+ return message.content.length && message.content.every(c => {
851
+ if (c.type === `text`) {
852
+ return c.text && c.text !== "";
853
+ }
854
+ return true;
855
+ });
856
+ }
857
+ return true;
858
+ });
859
+ }
860
+ convertTools({
861
+ toolsets,
862
+ // threadId,
863
+ runId
864
+ }) {
865
+ this.logger.debug(`[Agents:${this.name}] - Assigning tools`, {
866
+ runId
867
+ });
868
+ const converted = Object.entries(this.tools || {}).reduce((memo, value) => {
869
+ const k = value[0];
870
+ const tool = this.tools[k];
871
+ if (tool) {
872
+ memo[k] = {
873
+ description: tool.description,
874
+ parameters: tool.inputSchema,
875
+ execute: async args => {
876
+ try {
877
+ this.logger.debug(`[Agent:${this.name}] - Executing tool ${k}`, {
878
+ name: k,
879
+ description: tool.description,
880
+ args,
881
+ runId
882
+ });
883
+ return tool.execute({
884
+ context: args,
885
+ mastra: this.#mastra,
886
+ runId
887
+ });
888
+ } catch (err) {
889
+ this.logger.error(`[Agent:${this.name}] - Failed execution`, {
890
+ error: err,
891
+ runId
892
+ });
893
+ throw err;
894
+ }
895
+ }
896
+ };
897
+ }
898
+ return memo;
899
+ }, {});
900
+ const toolsFromToolsetsConverted = {
901
+ ...converted
902
+ };
903
+ const toolsFromToolsets = Object.values(toolsets || {});
904
+ if (toolsFromToolsets.length > 0) {
905
+ this.logger.debug(`[Agent:${this.name}] - Adding tools from toolsets ${Object.keys(toolsets || {}).join(", ")}`, {
906
+ runId
907
+ });
908
+ toolsFromToolsets.forEach(toolset => {
909
+ Object.entries(toolset).forEach(([toolName, tool]) => {
910
+ const toolObj = tool;
911
+ toolsFromToolsetsConverted[toolName] = {
912
+ description: toolObj.description || "",
913
+ parameters: toolObj.inputSchema,
914
+ execute: async args => {
915
+ try {
916
+ this.logger.debug(`[Agent:${this.name}] - Executing tool ${toolName}`, {
917
+ name: toolName,
918
+ description: toolObj.description,
919
+ args,
920
+ runId
921
+ });
922
+ return toolObj.execute({
923
+ context: args,
924
+ runId
925
+ });
926
+ } catch (err) {
927
+ this.logger.error(`[Agent:${this.name}] - Failed toolset execution`, {
928
+ error: err,
929
+ runId
930
+ });
931
+ throw err;
932
+ }
933
+ }
934
+ };
935
+ });
936
+ });
937
+ }
938
+ return toolsFromToolsetsConverted;
939
+ }
940
+ async preExecute({
941
+ resourceId,
942
+ runId,
943
+ threadId,
944
+ memoryConfig,
945
+ messages
946
+ }) {
947
+ let coreMessages = [];
948
+ let threadIdToUse = threadId;
949
+ this.logger.debug(`Saving user messages in memory for agent ${this.name}`, {
950
+ runId
951
+ });
952
+ const saveMessageResponse = await this.saveMemory({
953
+ threadId,
954
+ resourceId,
955
+ userMessages: messages,
956
+ memoryConfig
957
+ });
958
+ coreMessages = saveMessageResponse.messages;
959
+ threadIdToUse = saveMessageResponse.threadId;
960
+ return {
961
+ coreMessages,
962
+ threadIdToUse
963
+ };
964
+ }
965
+ __primitive({
966
+ messages,
967
+ context,
968
+ threadId,
969
+ memoryConfig,
970
+ resourceId,
971
+ runId,
972
+ toolsets
973
+ }) {
974
+ return {
975
+ before: async () => {
976
+ if (process.env.NODE_ENV !== "test") {
977
+ this.logger.debug(`[Agents:${this.name}] - Starting generation`, {
978
+ runId
979
+ });
980
+ }
981
+ const systemMessage = {
982
+ role: "system",
983
+ content: `${this.instructions}.`
984
+ };
985
+ let coreMessages = messages;
986
+ let threadIdToUse = threadId;
987
+ if (this.getMemory() && resourceId) {
988
+ this.logger.debug(`[Agent:${this.name}] - Memory persistence enabled: store=${this.getMemory()?.constructor.name}, resourceId=${resourceId}`, {
989
+ runId,
990
+ resourceId,
991
+ threadId: threadIdToUse,
992
+ memoryStore: this.getMemory()?.constructor.name
993
+ });
994
+ const preExecuteResult = await this.preExecute({
995
+ resourceId,
996
+ runId,
997
+ threadId: threadIdToUse,
998
+ memoryConfig,
999
+ messages
1000
+ });
1001
+ coreMessages = preExecuteResult.coreMessages;
1002
+ threadIdToUse = preExecuteResult.threadIdToUse;
1003
+ }
1004
+ let convertedTools;
1005
+ if (toolsets && Object.keys(toolsets || {}).length > 0 || this.getMemory() && resourceId) {
1006
+ const reasons = [];
1007
+ if (toolsets && Object.keys(toolsets || {}).length > 0) {
1008
+ reasons.push(`toolsets present (${Object.keys(toolsets || {}).length} tools)`);
1009
+ }
1010
+ if (this.getMemory() && resourceId) {
1011
+ reasons.push("memory and resourceId available");
1012
+ }
1013
+ this.logger.debug(`[Agent:${this.name}] - Enhancing tools: ${reasons.join(", ")}`, {
1014
+ runId,
1015
+ toolsets: toolsets ? Object.keys(toolsets) : void 0,
1016
+ hasMemory: !!this.getMemory(),
1017
+ hasResourceId: !!resourceId
1018
+ });
1019
+ convertedTools = this.convertTools({
1020
+ toolsets,
1021
+ threadId: threadIdToUse,
1022
+ runId
1023
+ });
1024
+ }
1025
+ const messageObjects = [systemMessage, ...(context || []), ...coreMessages];
1026
+ return {
1027
+ messageObjects,
1028
+ convertedTools,
1029
+ threadId: threadIdToUse
1030
+ };
1031
+ },
1032
+ after: async ({
1033
+ result,
1034
+ threadId: threadId2,
1035
+ memoryConfig: memoryConfig2,
1036
+ outputText,
1037
+ runId: runId2
1038
+ }) => {
1039
+ const resToLog = {
1040
+ text: result?.text,
1041
+ object: result?.object,
1042
+ toolResults: result?.toolResults,
1043
+ toolCalls: result?.toolCalls,
1044
+ usage: result?.usage,
1045
+ steps: result?.steps?.map(s => {
1046
+ return {
1047
+ stepType: s?.stepType,
1048
+ text: result?.text,
1049
+ object: result?.object,
1050
+ toolResults: result?.toolResults,
1051
+ toolCalls: result?.toolCalls,
1052
+ usage: result?.usage
1053
+ };
1054
+ })
1055
+ };
1056
+ this.logger.debug(`[Agent:${this.name}] - Post processing LLM response`, {
1057
+ runId: runId2,
1058
+ result: resToLog,
1059
+ threadId: threadId2
1060
+ });
1061
+ if (this.getMemory() && resourceId) {
1062
+ try {
1063
+ await this.saveResponse({
1064
+ result,
1065
+ threadId: threadId2,
1066
+ resourceId,
1067
+ memoryConfig: memoryConfig2,
1068
+ runId: runId2
1069
+ });
1070
+ } catch (e) {
1071
+ this.logger.error("Error saving response", {
1072
+ error: e,
1073
+ runId: runId2,
1074
+ result: resToLog,
1075
+ threadId: threadId2
1076
+ });
1077
+ }
1078
+ }
1079
+ if (Object.keys(this.evals || {}).length > 0) {
1080
+ const input = messages.map(message => message.content).join("\n");
1081
+ const runIdToUse = runId2 || crypto.randomUUID();
1082
+ for (const metric of Object.values(this.evals || {})) {
1083
+ executeHook("onGeneration" /* ON_GENERATION */, {
1084
+ input,
1085
+ output: outputText,
1086
+ runId: runIdToUse,
1087
+ metric,
1088
+ agentName: this.name,
1089
+ instructions: this.instructions
1090
+ });
1091
+ }
1092
+ }
1093
+ }
1094
+ };
1095
+ }
1096
+ async generate(messages, {
1097
+ context,
1098
+ threadId: threadIdInFn,
1099
+ memoryOptions,
1100
+ resourceId,
1101
+ maxSteps = 5,
1102
+ onStepFinish,
1103
+ runId,
1104
+ toolsets,
1105
+ output = "text",
1106
+ temperature,
1107
+ toolChoice = "auto"
1108
+ } = {}) {
1109
+ let messagesToUse = [];
1110
+ if (typeof messages === `string`) {
1111
+ messagesToUse = [{
1112
+ role: "user",
1113
+ content: messages
1114
+ }];
1115
+ } else {
1116
+ messagesToUse = messages.map(message => {
1117
+ if (typeof message === `string`) {
1118
+ return {
1119
+ role: "user",
1120
+ content: message
1121
+ };
1122
+ }
1123
+ return message;
1124
+ });
1125
+ }
1126
+ const runIdToUse = runId || randomUUID();
1127
+ const {
1128
+ before,
1129
+ after
1130
+ } = this.__primitive({
1131
+ messages: messagesToUse,
1132
+ context,
1133
+ threadId: threadIdInFn,
1134
+ memoryConfig: memoryOptions,
1135
+ resourceId,
1136
+ runId: runIdToUse,
1137
+ toolsets
1138
+ });
1139
+ const {
1140
+ threadId,
1141
+ messageObjects,
1142
+ convertedTools
1143
+ } = await before();
1144
+ if (output === "text") {
1145
+ const result2 = await this.llm.__text({
1146
+ messages: messageObjects,
1147
+ tools: this.tools,
1148
+ convertedTools,
1149
+ onStepFinish,
1150
+ maxSteps,
1151
+ runId: runIdToUse,
1152
+ temperature,
1153
+ toolChoice
1154
+ });
1155
+ const outputText2 = result2.text;
1156
+ await after({
1157
+ result: result2,
1158
+ threadId,
1159
+ memoryConfig: memoryOptions,
1160
+ outputText: outputText2,
1161
+ runId: runIdToUse
1162
+ });
1163
+ return result2;
1164
+ }
1165
+ const result = await this.llm.__textObject({
1166
+ messages: messageObjects,
1167
+ tools: this.tools,
1168
+ structuredOutput: output,
1169
+ convertedTools,
1170
+ onStepFinish,
1171
+ maxSteps,
1172
+ runId: runIdToUse,
1173
+ temperature,
1174
+ toolChoice
1175
+ });
1176
+ const outputText = JSON.stringify(result.object);
1177
+ await after({
1178
+ result,
1179
+ threadId,
1180
+ memoryConfig: memoryOptions,
1181
+ outputText,
1182
+ runId: runIdToUse
1183
+ });
1184
+ return result;
1185
+ }
1186
+ async stream(messages, {
1187
+ context,
1188
+ threadId: threadIdInFn,
1189
+ memoryOptions,
1190
+ resourceId,
1191
+ maxSteps = 5,
1192
+ onFinish,
1193
+ onStepFinish,
1194
+ runId,
1195
+ toolsets,
1196
+ output = "text",
1197
+ temperature,
1198
+ toolChoice = "auto"
1199
+ } = {}) {
1200
+ const runIdToUse = runId || randomUUID();
1201
+ let messagesToUse = [];
1202
+ if (typeof messages === `string`) {
1203
+ messagesToUse = [{
1204
+ role: "user",
1205
+ content: messages
1206
+ }];
1207
+ } else {
1208
+ messagesToUse = messages.map(message => {
1209
+ if (typeof message === `string`) {
1210
+ return {
1211
+ role: "user",
1212
+ content: message
1213
+ };
1214
+ }
1215
+ return message;
1216
+ });
1217
+ }
1218
+ const {
1219
+ before,
1220
+ after
1221
+ } = this.__primitive({
1222
+ messages: messagesToUse,
1223
+ context,
1224
+ threadId: threadIdInFn,
1225
+ memoryConfig: memoryOptions,
1226
+ resourceId,
1227
+ runId: runIdToUse,
1228
+ toolsets
1229
+ });
1230
+ const {
1231
+ threadId,
1232
+ messageObjects,
1233
+ convertedTools
1234
+ } = await before();
1235
+ if (output === "text") {
1236
+ this.logger.debug(`Starting agent ${this.name} llm stream call`, {
1237
+ runId
1238
+ });
1239
+ return this.llm.__stream({
1240
+ messages: messageObjects,
1241
+ temperature,
1242
+ tools: this.tools,
1243
+ convertedTools,
1244
+ onStepFinish,
1245
+ onFinish: async result => {
1246
+ try {
1247
+ const res = JSON.parse(result) || {};
1248
+ const outputText = res.text;
1249
+ await after({
1250
+ result: res,
1251
+ threadId,
1252
+ memoryConfig: memoryOptions,
1253
+ outputText,
1254
+ runId: runIdToUse
1255
+ });
1256
+ } catch (e) {
1257
+ this.logger.error("Error saving memory on finish", {
1258
+ error: e,
1259
+ runId
1260
+ });
1261
+ }
1262
+ onFinish?.(result);
1263
+ },
1264
+ maxSteps,
1265
+ runId: runIdToUse,
1266
+ toolChoice
1267
+ });
1268
+ }
1269
+ this.logger.debug(`Starting agent ${this.name} llm streamObject call`, {
1270
+ runId
1271
+ });
1272
+ return this.llm.__streamObject({
1273
+ messages: messageObjects,
1274
+ tools: this.tools,
1275
+ temperature,
1276
+ structuredOutput: output,
1277
+ convertedTools,
1278
+ onStepFinish,
1279
+ onFinish: async result => {
1280
+ try {
1281
+ const res = JSON.parse(result) || {};
1282
+ const outputText = JSON.stringify(res.object);
1283
+ await after({
1284
+ result: res,
1285
+ threadId,
1286
+ memoryConfig: memoryOptions,
1287
+ outputText,
1288
+ runId: runIdToUse
1289
+ });
1290
+ } catch (e) {
1291
+ this.logger.error("Error saving memory on finish", {
1292
+ error: e,
1293
+ runId
1294
+ });
1295
+ }
1296
+ onFinish?.(result);
1297
+ },
1298
+ maxSteps,
1299
+ runId: runIdToUse,
1300
+ toolChoice
1301
+ });
1302
+ }
1303
+ /**
1304
+ * Convert text to speech using the configured voice provider
1305
+ * @param input Text or text stream to convert to speech
1306
+ * @param options Speech options including speaker and provider-specific options
1307
+ * @returns Audio stream
1308
+ */
1309
+ async speak(input, options) {
1310
+ if (!this.voice) {
1311
+ throw new Error("No voice provider configured");
1312
+ }
1313
+ try {
1314
+ return this.voice.speak(input, options);
1315
+ } catch (e) {
1316
+ this.logger.error("Error during agent speak", {
1317
+ error: e
1318
+ });
1319
+ throw e;
1320
+ }
1321
+ }
1322
+ /**
1323
+ * Convert speech to text using the configured voice provider
1324
+ * @param audioStream Audio stream to transcribe
1325
+ * @param options Provider-specific transcription options
1326
+ * @returns Text or text stream
1327
+ */
1328
+ async listen(audioStream, options) {
1329
+ if (!this.voice) {
1330
+ throw new Error("No voice provider configured");
1331
+ }
1332
+ try {
1333
+ return this.voice.listen(audioStream, options);
1334
+ } catch (e) {
1335
+ this.logger.error("Error during agent listen", {
1336
+ error: e
1337
+ });
1338
+ throw e;
1339
+ }
1340
+ }
1341
+ /**
1342
+ * Get a list of available speakers from the configured voice provider
1343
+ * @throws {Error} If no voice provider is configured
1344
+ * @returns {Promise<Array<{voiceId: string}>>} List of available speakers
1345
+ */
1346
+ async getSpeakers() {
1347
+ if (!this.voice) {
1348
+ throw new Error("No voice provider configured");
1349
+ }
1350
+ try {
1351
+ return await this.voice.getSpeakers();
1352
+ } catch (e) {
1353
+ this.logger.error("Error during agent getSpeakers", {
1354
+ error: e
1355
+ });
1356
+ throw e;
1357
+ }
1358
+ }
1359
+ };
1360
+ Agent = /*@__PURE__*/(_ => {
1361
+ _init = __decoratorStart(_a);
1362
+ Agent = __decorateElement(_init, 0, "Agent", _Agent_decorators, Agent);
1363
+ __runInitializers(_init, 1, Agent);
1364
+ return Agent;
1365
+ })();
1366
+
1367
+ export { Agent };