@mastra/core 0.0.0-commonjs-20250227130920

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