@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,1865 @@
1
+ 'use strict';
2
+
3
+ var crypto$1 = require('crypto');
4
+ var zod = require('zod');
5
+ var stream = require('stream');
6
+ var pino = require('pino');
7
+ var pretty = require('pino-pretty');
8
+ var ai = require('ai');
9
+ var api = require('@opentelemetry/api');
10
+
11
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
12
+
13
+ var pino__default = /*#__PURE__*/_interopDefault(pino);
14
+ var pretty__default = /*#__PURE__*/_interopDefault(pretty);
15
+
16
+ var __create = Object.create;
17
+ var __defProp = Object.defineProperty;
18
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
19
+ var __knownSymbol = (name, symbol) => (symbol = Symbol[name]) ? symbol : Symbol.for("Symbol." + name);
20
+ var __typeError = msg => {
21
+ throw TypeError(msg);
22
+ };
23
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, {
24
+ enumerable: true,
25
+ configurable: true,
26
+ writable: true,
27
+ value
28
+ }) : obj[key] = value;
29
+ var __name = (target, value) => __defProp(target, "name", {
30
+ value,
31
+ configurable: true
32
+ });
33
+ var __decoratorStart = base => [,,, __create(base?.[__knownSymbol("metadata")] ?? null)];
34
+ var __decoratorStrings = ["class", "method", "getter", "setter", "accessor", "field", "value", "get", "set"];
35
+ var __expectFn = fn => fn !== void 0 && typeof fn !== "function" ? __typeError("Function expected") : fn;
36
+ var __decoratorContext = (kind, name, done, metadata, fns) => ({
37
+ kind: __decoratorStrings[kind],
38
+ name,
39
+ metadata,
40
+ addInitializer: fn => done._ ? __typeError("Already initialized") : fns.push(__expectFn(fn || null))
41
+ });
42
+ var __decoratorMetadata = (array, target) => __defNormalProp(target, __knownSymbol("metadata"), array[3]);
43
+ var __runInitializers = (array, flags, self, value) => {
44
+ for (var i = 0, fns = array[flags >> 1], n = fns && fns.length; i < n; i++) fns[i].call(self) ;
45
+ return value;
46
+ };
47
+ var __decorateElement = (array, flags, name, decorators, target, extra) => {
48
+ var it,
49
+ done,
50
+ ctx,
51
+ k = flags & 7,
52
+ p = false;
53
+ var j = 0;
54
+ var extraInitializers = array[j] || (array[j] = []);
55
+ var desc = k && ((target = target.prototype), k < 5 && (k > 3 || !p) && __getOwnPropDesc(target , name));
56
+ __name(target, name);
57
+ for (var i = decorators.length - 1; i >= 0; i--) {
58
+ ctx = __decoratorContext(k, name, done = {}, array[3], extraInitializers);
59
+ it = (0, decorators[i])(target, ctx), done._ = 1;
60
+ __expectFn(it) && (target = it);
61
+ }
62
+ return __decoratorMetadata(array, target), desc && __defProp(target, name, desc), p ? k ^ 4 ? extra : desc : target;
63
+ };
64
+ var RegisteredLogger = {
65
+ AGENT: "AGENT",
66
+ LLM: "LLM"};
67
+ var LogLevel = {
68
+ INFO: "info"};
69
+ var Logger = class {
70
+ logger;
71
+ transports;
72
+ constructor(options = {}) {
73
+ this.transports = options.transports || {};
74
+ const transportsAry = Object.entries(this.transports);
75
+ this.logger = pino__default.default({
76
+ name: options.name || "app",
77
+ level: options.level || LogLevel.INFO
78
+ }, options.overrideDefaultTransports ? options?.transports?.default : transportsAry.length === 0 ? pretty__default.default({
79
+ colorize: true,
80
+ levelFirst: true,
81
+ ignore: "pid,hostname",
82
+ colorizeObjects: true,
83
+ translateTime: "SYS:standard",
84
+ singleLine: false
85
+ }) : pino__default.default.multistream([...transportsAry.map(([_, transport]) => ({
86
+ stream: transport,
87
+ level: options.level || LogLevel.INFO
88
+ })), {
89
+ stream: pretty__default.default({
90
+ colorize: true,
91
+ levelFirst: true,
92
+ ignore: "pid,hostname",
93
+ colorizeObjects: true,
94
+ translateTime: "SYS:standard",
95
+ singleLine: false
96
+ }),
97
+ level: options.level || LogLevel.INFO
98
+ }]));
99
+ }
100
+ debug(message, args = {}) {
101
+ this.logger.debug(args, message);
102
+ }
103
+ info(message, args = {}) {
104
+ this.logger.info(args, message);
105
+ }
106
+ warn(message, args = {}) {
107
+ this.logger.warn(args, message);
108
+ }
109
+ error(message, args = {}) {
110
+ this.logger.error(args, message);
111
+ }
112
+ // Stream creation for process output handling
113
+ createStream() {
114
+ return new stream.Transform({
115
+ transform: (chunk, _encoding, callback) => {
116
+ const line = chunk.toString().trim();
117
+ if (line) {
118
+ this.info(line);
119
+ }
120
+ callback(null, chunk);
121
+ }
122
+ });
123
+ }
124
+ async getLogs(transportId) {
125
+ if (!transportId || !this.transports[transportId]) {
126
+ return [];
127
+ }
128
+ return this.transports[transportId].getLogs();
129
+ }
130
+ async getLogsByRunId({
131
+ runId,
132
+ transportId
133
+ }) {
134
+ return this.transports[transportId]?.getLogsByRunId({
135
+ runId
136
+ });
137
+ }
138
+ };
139
+ function createLogger(options) {
140
+ return new Logger(options);
141
+ }
142
+
143
+ // src/base.ts
144
+ var MastraBase = class {
145
+ component = RegisteredLogger.LLM;
146
+ logger;
147
+ name;
148
+ telemetry;
149
+ constructor({
150
+ component,
151
+ name
152
+ }) {
153
+ this.component = component || RegisteredLogger.LLM;
154
+ this.name = name;
155
+ this.logger = createLogger({
156
+ name: `${this.component} - ${this.name}`
157
+ });
158
+ }
159
+ /**
160
+ * Set the logger for the agent
161
+ * @param logger
162
+ */
163
+ __setLogger(logger) {
164
+ this.logger = logger;
165
+ this.logger.debug(`Logger updated [component=${this.component}] [name=${this.name}]`);
166
+ }
167
+ /**
168
+ * Set the telemetry for the
169
+ * @param telemetry
170
+ */
171
+ __setTelemetry(telemetry) {
172
+ this.telemetry = telemetry;
173
+ this.logger.debug(`Telemetry updated [component=${this.component}] [tracer=${this.telemetry.tracer}]`);
174
+ }
175
+ /**
176
+ * Get the telemetry on the vector
177
+ * @returns telemetry
178
+ */
179
+ __getTelemetry() {
180
+ return this.telemetry;
181
+ }
182
+ /*
183
+ get experimental_telemetry config
184
+ */
185
+ get experimental_telemetry() {
186
+ return this.telemetry ? {
187
+ // tracer: this.telemetry.tracer,
188
+ tracer: this.telemetry.getBaggageTracer(),
189
+ isEnabled: !!this.telemetry.tracer
190
+ } : void 0;
191
+ }
192
+ };
193
+
194
+ // src/hooks/mitt.ts
195
+ function mitt(all) {
196
+ all = all || /* @__PURE__ */new Map();
197
+ return {
198
+ /**
199
+ * A Map of event names to registered handler functions.
200
+ */
201
+ all,
202
+ /**
203
+ * Register an event handler for the given type.
204
+ * @param {string|symbol} type Type of event to listen for, or `'*'` for all events
205
+ * @param {Function} handler Function to call in response to given event
206
+ * @memberOf mitt
207
+ */
208
+ on(type, handler) {
209
+ const handlers = all.get(type);
210
+ if (handlers) {
211
+ handlers.push(handler);
212
+ } else {
213
+ all.set(type, [handler]);
214
+ }
215
+ },
216
+ /**
217
+ * Remove an event handler for the given type.
218
+ * If `handler` is omitted, all handlers of the given type are removed.
219
+ * @param {string|symbol} type Type of event to unregister `handler` from (`'*'` to remove a wildcard handler)
220
+ * @param {Function} [handler] Handler function to remove
221
+ * @memberOf mitt
222
+ */
223
+ off(type, handler) {
224
+ const handlers = all.get(type);
225
+ if (handlers) {
226
+ if (handler) {
227
+ handlers.splice(handlers.indexOf(handler) >>> 0, 1);
228
+ } else {
229
+ all.set(type, []);
230
+ }
231
+ }
232
+ },
233
+ /**
234
+ * Invoke all handlers for the given type.
235
+ * If present, `'*'` handlers are invoked after type-matched handlers.
236
+ *
237
+ * Note: Manually firing '*' handlers is not supported.
238
+ *
239
+ * @param {string|symbol} type The event type to invoke
240
+ * @param {Any} [evt] Any value (object is recommended and powerful), passed to each handler
241
+ * @memberOf mitt
242
+ */
243
+ emit(type, evt) {
244
+ let handlers = all.get(type);
245
+ if (handlers) {
246
+ handlers.slice().map(handler => {
247
+ handler(evt);
248
+ });
249
+ }
250
+ handlers = all.get("*");
251
+ if (handlers) {
252
+ handlers.slice().map(handler => {
253
+ handler(type, evt);
254
+ });
255
+ }
256
+ }
257
+ };
258
+ }
259
+
260
+ // src/hooks/index.ts
261
+ var hooks = mitt();
262
+ function executeHook(hook, data) {
263
+ setImmediate(() => {
264
+ hooks.emit(hook, data);
265
+ });
266
+ }
267
+
268
+ // src/llm/model/base.ts
269
+ var MastraLLMBase = class extends MastraBase {
270
+ // @ts-ignore
271
+ #mastra;
272
+ #model;
273
+ constructor({
274
+ name,
275
+ model
276
+ }) {
277
+ super({
278
+ component: RegisteredLogger.LLM,
279
+ name
280
+ });
281
+ this.#model = model;
282
+ }
283
+ getProvider() {
284
+ return this.#model.provider;
285
+ }
286
+ getModelId() {
287
+ return this.#model.modelId;
288
+ }
289
+ getModel() {
290
+ return this.#model;
291
+ }
292
+ convertToMessages(messages) {
293
+ if (Array.isArray(messages)) {
294
+ return messages.map(m => {
295
+ if (typeof m === "string") {
296
+ return {
297
+ role: "user",
298
+ content: m
299
+ };
300
+ }
301
+ return m;
302
+ });
303
+ }
304
+ return [{
305
+ role: "user",
306
+ content: messages
307
+ }];
308
+ }
309
+ __registerPrimitives(p) {
310
+ if (p.telemetry) {
311
+ this.__setTelemetry(p.telemetry);
312
+ }
313
+ if (p.logger) {
314
+ this.__setLogger(p.logger);
315
+ }
316
+ this.#mastra = p;
317
+ }
318
+ async __text(input) {
319
+ this.logger.debug(`[LLMs:${this.name}] Generating text.`, {
320
+ input
321
+ });
322
+ throw new Error("Method not implemented.");
323
+ }
324
+ async __textObject(input) {
325
+ this.logger.debug(`[LLMs:${this.name}] Generating object.`, {
326
+ input
327
+ });
328
+ throw new Error("Method not implemented.");
329
+ }
330
+ async generate(messages, options = {}) {
331
+ this.logger.debug(`[LLMs:${this.name}] Generating text.`, {
332
+ messages,
333
+ options
334
+ });
335
+ throw new Error("Method not implemented.");
336
+ }
337
+ async __stream(input) {
338
+ this.logger.debug(`[LLMs:${this.name}] Streaming text.`, {
339
+ input
340
+ });
341
+ throw new Error("Method not implemented.");
342
+ }
343
+ async __streamObject(input) {
344
+ this.logger.debug(`[LLMs:${this.name}] Streaming object.`, {
345
+ input
346
+ });
347
+ throw new Error("Method not implemented.");
348
+ }
349
+ async stream(messages, options = {}) {
350
+ this.logger.debug(`[LLMs:${this.name}] Streaming text.`, {
351
+ messages,
352
+ options
353
+ });
354
+ throw new Error("Method not implemented.");
355
+ }
356
+ };
357
+ var delay = ms => new Promise(resolve => setTimeout(resolve, ms));
358
+
359
+ // src/llm/model/model.ts
360
+ var MastraLLM = class extends MastraLLMBase {
361
+ #model;
362
+ #mastra;
363
+ constructor({
364
+ model,
365
+ mastra
366
+ }) {
367
+ super({
368
+ name: "aisdk",
369
+ model
370
+ });
371
+ this.#model = model;
372
+ if (mastra) {
373
+ this.#mastra = mastra;
374
+ if (mastra.logger) {
375
+ this.__setLogger(mastra.logger);
376
+ }
377
+ }
378
+ }
379
+ __registerPrimitives(p) {
380
+ if (p.telemetry) {
381
+ this.__setTelemetry(p.telemetry);
382
+ }
383
+ if (p.logger) {
384
+ this.__setLogger(p.logger);
385
+ }
386
+ this.#mastra = p;
387
+ }
388
+ getProvider() {
389
+ return this.#model.provider;
390
+ }
391
+ getModelId() {
392
+ return this.#model.modelId;
393
+ }
394
+ getModel() {
395
+ return this.#model;
396
+ }
397
+ convertTools({
398
+ tools,
399
+ runId
400
+ } = {}) {
401
+ this.logger.debug("Starting tool conversion for LLM");
402
+ const converted = Object.entries(tools || {}).reduce((memo, value) => {
403
+ const k = value[0];
404
+ const tool = value[1];
405
+ if (tool) {
406
+ memo[k] = {
407
+ description: tool.description,
408
+ parameters: tool.inputSchema,
409
+ execute: async props => {
410
+ try {
411
+ this.logger.debug("Executing tool", {
412
+ tool: k,
413
+ props
414
+ });
415
+ return tool?.execute?.({
416
+ context: props,
417
+ mastra: this.#mastra,
418
+ runId
419
+ }) ?? void 0;
420
+ } catch (error) {
421
+ this.logger.error("Error executing tool", {
422
+ tool: k,
423
+ props,
424
+ error
425
+ });
426
+ throw error;
427
+ }
428
+ }
429
+ };
430
+ }
431
+ return memo;
432
+ }, {});
433
+ this.logger.debug(`Converted tools for LLM`);
434
+ return converted;
435
+ }
436
+ async __text({
437
+ runId,
438
+ messages,
439
+ maxSteps,
440
+ tools,
441
+ convertedTools,
442
+ temperature,
443
+ toolChoice = "auto",
444
+ onStepFinish,
445
+ experimental_output,
446
+ telemetry
447
+ }) {
448
+ const model = this.#model;
449
+ this.logger.debug(`[LLM] - Generating text`, {
450
+ runId,
451
+ messages,
452
+ maxSteps,
453
+ tools: Object.keys(tools || convertedTools || {})
454
+ });
455
+ const finalTools = convertedTools || this.convertTools({
456
+ tools,
457
+ runId
458
+ });
459
+ const argsForExecute = {
460
+ model,
461
+ temperature,
462
+ tools: {
463
+ ...finalTools
464
+ },
465
+ toolChoice,
466
+ maxSteps,
467
+ onStepFinish: async props => {
468
+ onStepFinish?.(JSON.stringify(props, null, 2));
469
+ this.logger.debug("[LLM] - Step Change:", {
470
+ text: props?.text,
471
+ toolCalls: props?.toolCalls,
472
+ toolResults: props?.toolResults,
473
+ finishReason: props?.finishReason,
474
+ usage: props?.usage,
475
+ runId
476
+ });
477
+ if (props?.response?.headers?.["x-ratelimit-remaining-tokens"] && parseInt(props?.response?.headers?.["x-ratelimit-remaining-tokens"], 10) < 2e3) {
478
+ this.logger.warn("Rate limit approaching, waiting 10 seconds", {
479
+ runId
480
+ });
481
+ await delay(10 * 1e3);
482
+ }
483
+ }
484
+ };
485
+ let schema;
486
+ if (experimental_output) {
487
+ this.logger.debug("[LLM] - Using experimental output", {
488
+ runId
489
+ });
490
+ if (typeof experimental_output.parse === "function") {
491
+ schema = experimental_output;
492
+ if (schema instanceof zod.z.ZodArray) {
493
+ schema = schema._def.type;
494
+ }
495
+ } else {
496
+ schema = ai.jsonSchema(experimental_output);
497
+ }
498
+ }
499
+ return await ai.generateText({
500
+ messages,
501
+ ...argsForExecute,
502
+ experimental_telemetry: {
503
+ ...this.experimental_telemetry,
504
+ ...telemetry
505
+ },
506
+ experimental_output: schema ? ai.Output.object({
507
+ schema
508
+ }) : void 0
509
+ });
510
+ }
511
+ async __textObject({
512
+ messages,
513
+ onStepFinish,
514
+ maxSteps = 5,
515
+ tools,
516
+ convertedTools,
517
+ structuredOutput,
518
+ runId,
519
+ temperature,
520
+ toolChoice = "auto",
521
+ telemetry
522
+ }) {
523
+ const model = this.#model;
524
+ this.logger.debug(`[LLM] - Generating a text object`, {
525
+ runId
526
+ });
527
+ const finalTools = convertedTools || this.convertTools({
528
+ tools,
529
+ runId
530
+ });
531
+ const argsForExecute = {
532
+ model,
533
+ temperature,
534
+ tools: {
535
+ ...finalTools
536
+ },
537
+ maxSteps,
538
+ toolChoice,
539
+ onStepFinish: async props => {
540
+ onStepFinish?.(JSON.stringify(props, null, 2));
541
+ this.logger.debug("[LLM] - Step Change:", {
542
+ text: props?.text,
543
+ toolCalls: props?.toolCalls,
544
+ toolResults: props?.toolResults,
545
+ finishReason: props?.finishReason,
546
+ usage: props?.usage,
547
+ runId
548
+ });
549
+ if (props?.response?.headers?.["x-ratelimit-remaining-tokens"] && parseInt(props?.response?.headers?.["x-ratelimit-remaining-tokens"], 10) < 2e3) {
550
+ this.logger.warn("Rate limit approaching, waiting 10 seconds", {
551
+ runId
552
+ });
553
+ await delay(10 * 1e3);
554
+ }
555
+ }
556
+ };
557
+ let schema;
558
+ let output = "object";
559
+ if (typeof structuredOutput.parse === "function") {
560
+ schema = structuredOutput;
561
+ if (schema instanceof zod.z.ZodArray) {
562
+ output = "array";
563
+ schema = schema._def.type;
564
+ }
565
+ } else {
566
+ schema = ai.jsonSchema(structuredOutput);
567
+ }
568
+ return await ai.generateObject({
569
+ messages,
570
+ ...argsForExecute,
571
+ output,
572
+ schema,
573
+ experimental_telemetry: {
574
+ ...this.experimental_telemetry,
575
+ ...telemetry
576
+ }
577
+ });
578
+ }
579
+ async __stream({
580
+ messages,
581
+ onStepFinish,
582
+ onFinish,
583
+ maxSteps = 5,
584
+ tools,
585
+ convertedTools,
586
+ runId,
587
+ temperature,
588
+ toolChoice = "auto",
589
+ experimental_output,
590
+ telemetry
591
+ }) {
592
+ const model = this.#model;
593
+ this.logger.debug(`[LLM] - Streaming text`, {
594
+ runId,
595
+ messages,
596
+ maxSteps,
597
+ tools: Object.keys(tools || convertedTools || {})
598
+ });
599
+ const finalTools = convertedTools || this.convertTools({
600
+ tools,
601
+ runId
602
+ });
603
+ const argsForExecute = {
604
+ model,
605
+ temperature,
606
+ tools: {
607
+ ...finalTools
608
+ },
609
+ maxSteps,
610
+ toolChoice,
611
+ onStepFinish: async props => {
612
+ onStepFinish?.(JSON.stringify(props, null, 2));
613
+ this.logger.debug("[LLM] - Stream Step Change:", {
614
+ text: props?.text,
615
+ toolCalls: props?.toolCalls,
616
+ toolResults: props?.toolResults,
617
+ finishReason: props?.finishReason,
618
+ usage: props?.usage,
619
+ runId
620
+ });
621
+ if (props?.response?.headers?.["x-ratelimit-remaining-tokens"] && parseInt(props?.response?.headers?.["x-ratelimit-remaining-tokens"], 10) < 2e3) {
622
+ this.logger.warn("Rate limit approaching, waiting 10 seconds", {
623
+ runId
624
+ });
625
+ await delay(10 * 1e3);
626
+ }
627
+ },
628
+ onFinish: async props => {
629
+ onFinish?.(JSON.stringify(props, null, 2));
630
+ this.logger.debug("[LLM] - Stream Finished:", {
631
+ text: props?.text,
632
+ toolCalls: props?.toolCalls,
633
+ toolResults: props?.toolResults,
634
+ finishReason: props?.finishReason,
635
+ usage: props?.usage,
636
+ runId
637
+ });
638
+ }
639
+ };
640
+ let schema;
641
+ if (experimental_output) {
642
+ this.logger.debug("[LLM] - Using experimental output", {
643
+ runId
644
+ });
645
+ if (typeof experimental_output.parse === "function") {
646
+ schema = experimental_output;
647
+ if (schema instanceof zod.z.ZodArray) {
648
+ schema = schema._def.type;
649
+ }
650
+ } else {
651
+ schema = ai.jsonSchema(experimental_output);
652
+ }
653
+ }
654
+ return await ai.streamText({
655
+ messages,
656
+ ...argsForExecute,
657
+ experimental_telemetry: {
658
+ ...this.experimental_telemetry,
659
+ ...telemetry
660
+ },
661
+ experimental_output: schema ? ai.Output.object({
662
+ schema
663
+ }) : void 0
664
+ });
665
+ }
666
+ async __streamObject({
667
+ messages,
668
+ onStepFinish,
669
+ onFinish,
670
+ maxSteps = 5,
671
+ tools,
672
+ convertedTools,
673
+ structuredOutput,
674
+ runId,
675
+ temperature,
676
+ toolChoice = "auto",
677
+ telemetry
678
+ }) {
679
+ const model = this.#model;
680
+ this.logger.debug(`[LLM] - Streaming structured output`, {
681
+ runId,
682
+ messages,
683
+ maxSteps,
684
+ tools: Object.keys(tools || convertedTools || {})
685
+ });
686
+ const finalTools = convertedTools || this.convertTools({
687
+ tools,
688
+ runId
689
+ });
690
+ const argsForExecute = {
691
+ model,
692
+ temperature,
693
+ tools: {
694
+ ...finalTools
695
+ },
696
+ maxSteps,
697
+ toolChoice,
698
+ onStepFinish: async props => {
699
+ onStepFinish?.(JSON.stringify(props, null, 2));
700
+ this.logger.debug("[LLM] - Stream Step Change:", {
701
+ text: props?.text,
702
+ toolCalls: props?.toolCalls,
703
+ toolResults: props?.toolResults,
704
+ finishReason: props?.finishReason,
705
+ usage: props?.usage,
706
+ runId
707
+ });
708
+ if (props?.response?.headers?.["x-ratelimit-remaining-tokens"] && parseInt(props?.response?.headers?.["x-ratelimit-remaining-tokens"], 10) < 2e3) {
709
+ this.logger.warn("Rate limit approaching, waiting 10 seconds", {
710
+ runId
711
+ });
712
+ await delay(10 * 1e3);
713
+ }
714
+ },
715
+ onFinish: async props => {
716
+ onFinish?.(JSON.stringify(props, null, 2));
717
+ this.logger.debug("[LLM] - Stream Finished:", {
718
+ text: props?.text,
719
+ toolCalls: props?.toolCalls,
720
+ toolResults: props?.toolResults,
721
+ finishReason: props?.finishReason,
722
+ usage: props?.usage,
723
+ runId
724
+ });
725
+ }
726
+ };
727
+ let schema;
728
+ let output = "object";
729
+ if (typeof structuredOutput.parse === "function") {
730
+ schema = structuredOutput;
731
+ if (schema instanceof zod.z.ZodArray) {
732
+ output = "array";
733
+ schema = schema._def.type;
734
+ }
735
+ } else {
736
+ schema = ai.jsonSchema(structuredOutput);
737
+ }
738
+ return ai.streamObject({
739
+ messages,
740
+ ...argsForExecute,
741
+ output,
742
+ schema,
743
+ experimental_telemetry: {
744
+ ...this.experimental_telemetry,
745
+ ...telemetry
746
+ }
747
+ });
748
+ }
749
+ async generate(messages, {
750
+ maxSteps = 5,
751
+ onStepFinish,
752
+ tools,
753
+ convertedTools,
754
+ runId,
755
+ output = "text",
756
+ temperature,
757
+ telemetry
758
+ } = {}) {
759
+ const msgs = this.convertToMessages(messages);
760
+ if (output === "text") {
761
+ return await this.__text({
762
+ messages: msgs,
763
+ onStepFinish,
764
+ maxSteps,
765
+ tools,
766
+ convertedTools,
767
+ runId,
768
+ temperature
769
+ });
770
+ }
771
+ return await this.__textObject({
772
+ messages: msgs,
773
+ structuredOutput: output,
774
+ onStepFinish,
775
+ maxSteps,
776
+ tools,
777
+ convertedTools,
778
+ runId,
779
+ telemetry
780
+ });
781
+ }
782
+ async stream(messages, {
783
+ maxSteps = 5,
784
+ onFinish,
785
+ onStepFinish,
786
+ tools,
787
+ convertedTools,
788
+ runId,
789
+ output = "text",
790
+ temperature,
791
+ telemetry
792
+ } = {}) {
793
+ const msgs = this.convertToMessages(messages);
794
+ if (output === "text") {
795
+ return await this.__stream({
796
+ messages: msgs,
797
+ onStepFinish,
798
+ onFinish,
799
+ maxSteps,
800
+ tools,
801
+ convertedTools,
802
+ runId,
803
+ temperature,
804
+ telemetry
805
+ });
806
+ }
807
+ return await this.__streamObject({
808
+ messages: msgs,
809
+ structuredOutput: output,
810
+ onStepFinish,
811
+ onFinish,
812
+ maxSteps,
813
+ tools,
814
+ convertedTools,
815
+ runId,
816
+ temperature,
817
+ telemetry
818
+ });
819
+ }
820
+ };
821
+ function hasActiveTelemetry(tracerName = "default-tracer") {
822
+ try {
823
+ return !!api.trace.getTracer(tracerName);
824
+ } catch {
825
+ return false;
826
+ }
827
+ }
828
+
829
+ // src/telemetry/telemetry.decorators.ts
830
+ function withSpan(options) {
831
+ return function (_target, propertyKey, descriptor) {
832
+ if (!descriptor || typeof descriptor === "number") return;
833
+ const originalMethod = descriptor.value;
834
+ const methodName = String(propertyKey);
835
+ descriptor.value = function (...args) {
836
+ if (options?.skipIfNoTelemetry && !hasActiveTelemetry(options?.tracerName)) {
837
+ return originalMethod.apply(this, args);
838
+ }
839
+ const tracer = api.trace.getTracer(options?.tracerName ?? "default-tracer");
840
+ let spanName;
841
+ let spanKind;
842
+ if (typeof options === "string") {
843
+ spanName = options;
844
+ } else if (options) {
845
+ spanName = options.spanName || methodName;
846
+ spanKind = options.spanKind;
847
+ } else {
848
+ spanName = methodName;
849
+ }
850
+ const span = tracer.startSpan(spanName, {
851
+ kind: spanKind
852
+ });
853
+ let ctx = api.trace.setSpan(api.context.active(), span);
854
+ args.forEach((arg, index) => {
855
+ try {
856
+ span.setAttribute(`${spanName}.argument.${index}`, JSON.stringify(arg));
857
+ } catch {
858
+ span.setAttribute(`${spanName}.argument.${index}`, "[Not Serializable]");
859
+ }
860
+ });
861
+ const currentBaggage = api.propagation.getBaggage(ctx);
862
+ if (currentBaggage?.componentName) {
863
+ span.setAttribute("componentName", currentBaggage?.componentName);
864
+ span.setAttribute("runId", currentBaggage?.runId);
865
+ } else if (this && this.name) {
866
+ span.setAttribute("componentName", this.name);
867
+ span.setAttribute("runId", this.runId);
868
+ ctx = api.propagation.setBaggage(ctx, {
869
+ componentName: this.name,
870
+ runId: this.runId
871
+ });
872
+ }
873
+ let result;
874
+ try {
875
+ result = api.context.with(ctx, () => originalMethod.apply(this, args));
876
+ if (result instanceof Promise) {
877
+ return result.then(resolvedValue => {
878
+ try {
879
+ span.setAttribute(`${spanName}.result`, JSON.stringify(resolvedValue));
880
+ } catch {
881
+ span.setAttribute(`${spanName}.result`, "[Not Serializable]");
882
+ }
883
+ return resolvedValue;
884
+ }).finally(() => span.end());
885
+ }
886
+ try {
887
+ span.setAttribute(`${spanName}.result`, JSON.stringify(result));
888
+ } catch {
889
+ span.setAttribute(`${spanName}.result`, "[Not Serializable]");
890
+ }
891
+ return result;
892
+ } catch (error) {
893
+ span.setStatus({
894
+ code: api.SpanStatusCode.ERROR,
895
+ message: error instanceof Error ? error.message : "Unknown error"
896
+ });
897
+ if (error instanceof Error) {
898
+ span.recordException(error);
899
+ }
900
+ throw error;
901
+ } finally {
902
+ if (!(result instanceof Promise)) {
903
+ span.end();
904
+ }
905
+ }
906
+ };
907
+ return descriptor;
908
+ };
909
+ }
910
+ function InstrumentClass(options) {
911
+ return function (target) {
912
+ const methods = Object.getOwnPropertyNames(target.prototype);
913
+ methods.forEach(method => {
914
+ if (options?.excludeMethods?.includes(method) || method === "constructor") return;
915
+ if (options?.methodFilter && !options.methodFilter(method)) return;
916
+ const descriptor = Object.getOwnPropertyDescriptor(target.prototype, method);
917
+ if (descriptor && typeof descriptor.value === "function") {
918
+ Object.defineProperty(target.prototype, method, withSpan({
919
+ spanName: options?.prefix ? `${options.prefix}.${method}` : method,
920
+ skipIfNoTelemetry: true,
921
+ spanKind: options?.spanKind || api.SpanKind.INTERNAL,
922
+ tracerName: options?.tracerName
923
+ })(target, method, descriptor));
924
+ }
925
+ });
926
+ return target;
927
+ };
928
+ }
929
+
930
+ // src/agent/index.ts
931
+ var _Agent_decorators, _init, _a;
932
+ _Agent_decorators = [InstrumentClass({
933
+ prefix: "agent",
934
+ excludeMethods: ["__setTools", "__setLogger", "__setTelemetry", "log"]
935
+ })];
936
+ exports.Agent = class Agent extends (_a = MastraBase) {
937
+ name;
938
+ llm;
939
+ instructions;
940
+ model;
941
+ #mastra;
942
+ #memory;
943
+ tools;
944
+ /** @deprecated This property is deprecated. Use evals instead. */
945
+ metrics;
946
+ evals;
947
+ voice;
948
+ constructor(config) {
949
+ super({
950
+ component: RegisteredLogger.AGENT
951
+ });
952
+ this.name = config.name;
953
+ this.instructions = config.instructions;
954
+ if (!config.model) {
955
+ throw new Error(`LanguageModel is required to create an Agent. Please provide the 'model'.`);
956
+ }
957
+ this.llm = new MastraLLM({
958
+ model: config.model
959
+ });
960
+ this.tools = {};
961
+ this.metrics = {};
962
+ this.evals = {};
963
+ if (config.tools) {
964
+ this.tools = config.tools;
965
+ }
966
+ if (config.mastra) {
967
+ this.#mastra = config.mastra;
968
+ }
969
+ if (config.metrics) {
970
+ this.logger.warn("The metrics property is deprecated. Please use evals instead to add evaluation metrics.");
971
+ this.metrics = config.metrics;
972
+ this.evals = config.metrics;
973
+ }
974
+ if (config.evals) {
975
+ this.evals = config.evals;
976
+ }
977
+ if (config.memory) {
978
+ this.#memory = config.memory;
979
+ }
980
+ if (config.voice) {
981
+ this.voice = config.voice;
982
+ }
983
+ }
984
+ hasOwnMemory() {
985
+ return Boolean(this.#memory);
986
+ }
987
+ getMemory() {
988
+ return this.#memory ?? this.#mastra?.memory;
989
+ }
990
+ __updateInstructions(newInstructions) {
991
+ this.instructions = newInstructions;
992
+ this.logger.debug(`[Agents:${this.name}] Instructions updated.`, {
993
+ model: this.model,
994
+ name: this.name
995
+ });
996
+ }
997
+ __registerPrimitives(p) {
998
+ if (p.telemetry) {
999
+ this.__setTelemetry(p.telemetry);
1000
+ }
1001
+ if (p.logger) {
1002
+ this.__setLogger(p.logger);
1003
+ }
1004
+ this.llm.__registerPrimitives(p);
1005
+ this.#mastra = p;
1006
+ this.logger.debug(`[Agents:${this.name}] initialized.`, {
1007
+ model: this.model,
1008
+ name: this.name
1009
+ });
1010
+ }
1011
+ /**
1012
+ * Set the concrete tools for the agent
1013
+ * @param tools
1014
+ */
1015
+ __setTools(tools) {
1016
+ this.tools = tools;
1017
+ this.logger.debug(`[Agents:${this.name}] Tools set for agent ${this.name}`, {
1018
+ model: this.model,
1019
+ name: this.name
1020
+ });
1021
+ }
1022
+ async generateTitleFromUserMessage({
1023
+ message
1024
+ }) {
1025
+ const {
1026
+ object
1027
+ } = await this.llm.__textObject({
1028
+ messages: [{
1029
+ role: "system",
1030
+ content: `
1031
+
1032
+ - you will generate a short title based on the first message a user begins a conversation with
1033
+ - ensure it is not more than 80 characters long
1034
+ - the title should be a summary of the user's message
1035
+ - do not use quotes or colons`
1036
+ }, {
1037
+ role: "user",
1038
+ content: JSON.stringify(message)
1039
+ }],
1040
+ structuredOutput: zod.z.object({
1041
+ title: zod.z.string()
1042
+ })
1043
+ });
1044
+ return object.title;
1045
+ }
1046
+ getMostRecentUserMessage(messages) {
1047
+ const userMessages = messages.filter(message => message.role === "user");
1048
+ return userMessages.at(-1);
1049
+ }
1050
+ async genTitle(userMessage) {
1051
+ let title = "New Thread";
1052
+ try {
1053
+ if (userMessage) {
1054
+ title = await this.generateTitleFromUserMessage({
1055
+ message: userMessage
1056
+ });
1057
+ }
1058
+ } catch (e) {
1059
+ console.error("Error generating title:", e);
1060
+ }
1061
+ return title;
1062
+ }
1063
+ async saveMemory({
1064
+ threadId,
1065
+ memoryConfig,
1066
+ resourceId,
1067
+ userMessages,
1068
+ runId
1069
+ }) {
1070
+ const userMessage = this.getMostRecentUserMessage(userMessages);
1071
+ const memory = this.getMemory();
1072
+ if (memory) {
1073
+ let thread;
1074
+ if (!threadId) {
1075
+ this.logger.debug(`No threadId, creating new thread for agent ${this.name}`, {
1076
+ runId: runId || this.name
1077
+ });
1078
+ const title = await this.genTitle(userMessage);
1079
+ thread = await memory.createThread({
1080
+ threadId,
1081
+ resourceId,
1082
+ title,
1083
+ memoryConfig
1084
+ });
1085
+ } else {
1086
+ thread = await memory.getThreadById({
1087
+ threadId
1088
+ });
1089
+ if (!thread) {
1090
+ this.logger.debug(`Thread with id ${threadId} not found, creating new thread for agent ${this.name}`, {
1091
+ runId: runId || this.name
1092
+ });
1093
+ const title = await this.genTitle(userMessage);
1094
+ thread = await memory.createThread({
1095
+ threadId,
1096
+ resourceId,
1097
+ title,
1098
+ memoryConfig
1099
+ });
1100
+ }
1101
+ }
1102
+ const newMessages = userMessage ? [userMessage] : userMessages;
1103
+ if (thread) {
1104
+ const messages = newMessages.map(u => {
1105
+ return {
1106
+ id: this.getMemory()?.generateId(),
1107
+ createdAt: /* @__PURE__ */new Date(),
1108
+ threadId: thread.id,
1109
+ ...u,
1110
+ content: u.content,
1111
+ role: u.role,
1112
+ type: "text"
1113
+ };
1114
+ });
1115
+ const memoryMessages = threadId && memory ? (await memory.rememberMessages({
1116
+ threadId,
1117
+ config: memoryConfig,
1118
+ vectorMessageSearch: messages.slice(-1).map(m => {
1119
+ if (typeof m === `string`) {
1120
+ return m;
1121
+ }
1122
+ return m?.content || ``;
1123
+ }).join(`
1124
+ `)
1125
+ })).messages : [];
1126
+ if (memory) {
1127
+ await memory.saveMessages({
1128
+ messages,
1129
+ memoryConfig
1130
+ });
1131
+ }
1132
+ this.logger.debug("Saved messages to memory", {
1133
+ threadId: thread.id,
1134
+ runId
1135
+ });
1136
+ const memorySystemMessage = memory && threadId ? await memory.getSystemMessage({
1137
+ threadId,
1138
+ memoryConfig
1139
+ }) : null;
1140
+ return {
1141
+ threadId: thread.id,
1142
+ messages: [memorySystemMessage ? {
1143
+ role: "system",
1144
+ content: memorySystemMessage
1145
+ } : null, ...this.sanitizeResponseMessages(memoryMessages), ...newMessages].filter(message => Boolean(message))
1146
+ };
1147
+ }
1148
+ return {
1149
+ threadId: thread?.id || threadId || "",
1150
+ messages: userMessages
1151
+ };
1152
+ }
1153
+ return {
1154
+ threadId: threadId || "",
1155
+ messages: userMessages
1156
+ };
1157
+ }
1158
+ async saveResponse({
1159
+ result,
1160
+ threadId,
1161
+ resourceId,
1162
+ runId,
1163
+ memoryConfig
1164
+ }) {
1165
+ const {
1166
+ response
1167
+ } = result;
1168
+ try {
1169
+ if (response.messages) {
1170
+ const ms = Array.isArray(response.messages) ? response.messages : [response.messages];
1171
+ const responseMessagesWithoutIncompleteToolCalls = this.sanitizeResponseMessages(ms);
1172
+ const memory = this.getMemory();
1173
+ if (memory) {
1174
+ this.logger.debug(`[Agent:${this.name}] - Memory persistence: store=${this.getMemory()?.constructor.name} threadId=${threadId}`, {
1175
+ runId,
1176
+ resourceId,
1177
+ threadId,
1178
+ memoryStore: this.getMemory()?.constructor.name
1179
+ });
1180
+ await memory.saveMessages({
1181
+ memoryConfig,
1182
+ messages: responseMessagesWithoutIncompleteToolCalls.map(message => {
1183
+ const messageId = crypto$1.randomUUID();
1184
+ let toolCallIds;
1185
+ let toolCallArgs;
1186
+ let toolNames;
1187
+ let type = "text";
1188
+ if (message.role === "tool") {
1189
+ toolCallIds = message.content.map(content => content.toolCallId);
1190
+ type = "tool-result";
1191
+ }
1192
+ if (message.role === "assistant") {
1193
+ const assistantContent = message.content;
1194
+ const assistantToolCalls = assistantContent.map(content => {
1195
+ if (content.type === "tool-call") {
1196
+ return {
1197
+ toolCallId: content.toolCallId,
1198
+ toolArgs: content.args,
1199
+ toolName: content.toolName
1200
+ };
1201
+ }
1202
+ return void 0;
1203
+ })?.filter(Boolean);
1204
+ toolCallIds = assistantToolCalls?.map(toolCall => toolCall.toolCallId);
1205
+ toolCallArgs = assistantToolCalls?.map(toolCall => toolCall.toolArgs);
1206
+ toolNames = assistantToolCalls?.map(toolCall => toolCall.toolName);
1207
+ type = assistantContent?.[0]?.type;
1208
+ }
1209
+ return {
1210
+ id: messageId,
1211
+ threadId,
1212
+ role: message.role,
1213
+ content: message.content,
1214
+ createdAt: /* @__PURE__ */new Date(),
1215
+ toolCallIds: toolCallIds?.length ? toolCallIds : void 0,
1216
+ toolCallArgs: toolCallArgs?.length ? toolCallArgs : void 0,
1217
+ toolNames: toolNames?.length ? toolNames : void 0,
1218
+ type
1219
+ };
1220
+ })
1221
+ });
1222
+ }
1223
+ }
1224
+ } catch (err) {
1225
+ this.logger.error(`[Agent:${this.name}] - Failed to save assistant response`, {
1226
+ error: err,
1227
+ runId
1228
+ });
1229
+ }
1230
+ }
1231
+ sanitizeResponseMessages(messages) {
1232
+ let toolResultIds = [];
1233
+ let toolCallIds = [];
1234
+ for (const message of messages) {
1235
+ if (message.role === "tool") {
1236
+ for (const content of message.content) {
1237
+ if (content.type === "tool-result") {
1238
+ toolResultIds.push(content.toolCallId);
1239
+ }
1240
+ }
1241
+ }
1242
+ if (message.role === "assistant" || message.role === "user") {
1243
+ for (const content of message.content) {
1244
+ if (typeof content !== `string`) {
1245
+ if (content.type === `tool-call`) {
1246
+ toolCallIds.push(content.toolCallId);
1247
+ }
1248
+ }
1249
+ }
1250
+ }
1251
+ }
1252
+ const messagesBySanitizedContent = messages.map(message => {
1253
+ if (message.role !== "assistant" && message.role !== `tool` && message.role !== `user`) return message;
1254
+ if (typeof message.content === "string") return message;
1255
+ const sanitizedContent = message.content.filter(content => {
1256
+ if (content.type === `tool-call`) {
1257
+ return toolResultIds.includes(content.toolCallId);
1258
+ }
1259
+ if (content.type === `text`) {
1260
+ return content.text.trim() !== ``;
1261
+ }
1262
+ if (content.type === `tool-result`) {
1263
+ return toolCallIds.includes(content.toolCallId);
1264
+ }
1265
+ return true;
1266
+ });
1267
+ return {
1268
+ ...message,
1269
+ content: sanitizedContent
1270
+ };
1271
+ });
1272
+ return messagesBySanitizedContent.filter(message => {
1273
+ if (typeof message.content === `string`) {
1274
+ return message.content !== "";
1275
+ }
1276
+ if (Array.isArray(message.content)) {
1277
+ return message.content.length && message.content.every(c => {
1278
+ if (c.type === `text`) {
1279
+ return c.text && c.text !== "";
1280
+ }
1281
+ return true;
1282
+ });
1283
+ }
1284
+ return true;
1285
+ });
1286
+ }
1287
+ convertTools({
1288
+ toolsets,
1289
+ // threadId,
1290
+ runId
1291
+ }) {
1292
+ this.logger.debug(`[Agents:${this.name}] - Assigning tools`, {
1293
+ runId
1294
+ });
1295
+ const converted = Object.entries(this.tools || {}).reduce((memo, value) => {
1296
+ const k = value[0];
1297
+ const tool = this.tools[k];
1298
+ if (tool) {
1299
+ memo[k] = {
1300
+ description: tool.description,
1301
+ parameters: tool.inputSchema,
1302
+ execute: async args => {
1303
+ try {
1304
+ this.logger.debug(`[Agent:${this.name}] - Executing tool ${k}`, {
1305
+ name: k,
1306
+ description: tool.description,
1307
+ args,
1308
+ runId
1309
+ });
1310
+ return tool?.execute?.({
1311
+ context: args,
1312
+ mastra: this.#mastra,
1313
+ runId
1314
+ }) ?? void 0;
1315
+ } catch (err) {
1316
+ this.logger.error(`[Agent:${this.name}] - Failed execution`, {
1317
+ error: err,
1318
+ runId
1319
+ });
1320
+ throw err;
1321
+ }
1322
+ }
1323
+ };
1324
+ }
1325
+ return memo;
1326
+ }, {});
1327
+ const toolsFromToolsetsConverted = {
1328
+ ...converted
1329
+ };
1330
+ const toolsFromToolsets = Object.values(toolsets || {});
1331
+ if (toolsFromToolsets.length > 0) {
1332
+ this.logger.debug(`[Agent:${this.name}] - Adding tools from toolsets ${Object.keys(toolsets || {}).join(", ")}`, {
1333
+ runId
1334
+ });
1335
+ toolsFromToolsets.forEach(toolset => {
1336
+ Object.entries(toolset).forEach(([toolName, tool]) => {
1337
+ const toolObj = tool;
1338
+ toolsFromToolsetsConverted[toolName] = {
1339
+ description: toolObj.description || "",
1340
+ parameters: toolObj.inputSchema,
1341
+ execute: async args => {
1342
+ try {
1343
+ this.logger.debug(`[Agent:${this.name}] - Executing tool ${toolName}`, {
1344
+ name: toolName,
1345
+ description: toolObj.description,
1346
+ args,
1347
+ runId
1348
+ });
1349
+ return toolObj.execute({
1350
+ context: args,
1351
+ runId
1352
+ });
1353
+ } catch (err) {
1354
+ this.logger.error(`[Agent:${this.name}] - Failed toolset execution`, {
1355
+ error: err,
1356
+ runId
1357
+ });
1358
+ throw err;
1359
+ }
1360
+ }
1361
+ };
1362
+ });
1363
+ });
1364
+ }
1365
+ return toolsFromToolsetsConverted;
1366
+ }
1367
+ async preExecute({
1368
+ resourceId,
1369
+ runId,
1370
+ threadId,
1371
+ memoryConfig,
1372
+ messages
1373
+ }) {
1374
+ let coreMessages = [];
1375
+ let threadIdToUse = threadId;
1376
+ this.logger.debug(`Saving user messages in memory for agent ${this.name}`, {
1377
+ runId
1378
+ });
1379
+ const saveMessageResponse = await this.saveMemory({
1380
+ threadId,
1381
+ resourceId,
1382
+ userMessages: messages,
1383
+ memoryConfig
1384
+ });
1385
+ coreMessages = saveMessageResponse.messages;
1386
+ threadIdToUse = saveMessageResponse.threadId;
1387
+ return {
1388
+ coreMessages,
1389
+ threadIdToUse
1390
+ };
1391
+ }
1392
+ __primitive({
1393
+ messages,
1394
+ context: context2,
1395
+ threadId,
1396
+ memoryConfig,
1397
+ resourceId,
1398
+ runId,
1399
+ toolsets
1400
+ }) {
1401
+ return {
1402
+ before: async () => {
1403
+ if (process.env.NODE_ENV !== "test") {
1404
+ this.logger.debug(`[Agents:${this.name}] - Starting generation`, {
1405
+ runId
1406
+ });
1407
+ }
1408
+ const systemMessage = {
1409
+ role: "system",
1410
+ content: `${this.instructions}.`
1411
+ };
1412
+ let coreMessages = messages;
1413
+ let threadIdToUse = threadId;
1414
+ const memory = this.getMemory();
1415
+ if (threadId && memory && !resourceId) {
1416
+ throw new Error(`A resourceId must be provided when passing a threadId and using Memory. Saw threadId ${threadId} but resourceId is ${resourceId}`);
1417
+ }
1418
+ if (memory && resourceId) {
1419
+ this.logger.debug(`[Agent:${this.name}] - Memory persistence enabled: store=${this.getMemory()?.constructor.name}, resourceId=${resourceId}`, {
1420
+ runId,
1421
+ resourceId,
1422
+ threadId: threadIdToUse,
1423
+ memoryStore: this.getMemory()?.constructor.name
1424
+ });
1425
+ const preExecuteResult = await this.preExecute({
1426
+ resourceId,
1427
+ runId,
1428
+ threadId: threadIdToUse,
1429
+ memoryConfig,
1430
+ messages
1431
+ });
1432
+ coreMessages = preExecuteResult.coreMessages;
1433
+ threadIdToUse = preExecuteResult.threadIdToUse;
1434
+ }
1435
+ let convertedTools;
1436
+ if (toolsets && Object.keys(toolsets || {}).length > 0 || this.getMemory() && resourceId) {
1437
+ const reasons = [];
1438
+ if (toolsets && Object.keys(toolsets || {}).length > 0) {
1439
+ reasons.push(`toolsets present (${Object.keys(toolsets || {}).length} tools)`);
1440
+ }
1441
+ if (this.getMemory() && resourceId) {
1442
+ reasons.push("memory and resourceId available");
1443
+ }
1444
+ this.logger.debug(`[Agent:${this.name}] - Enhancing tools: ${reasons.join(", ")}`, {
1445
+ runId,
1446
+ toolsets: toolsets ? Object.keys(toolsets) : void 0,
1447
+ hasMemory: !!this.getMemory(),
1448
+ hasResourceId: !!resourceId
1449
+ });
1450
+ convertedTools = this.convertTools({
1451
+ toolsets,
1452
+ threadId: threadIdToUse,
1453
+ runId
1454
+ });
1455
+ }
1456
+ const messageObjects = [systemMessage, ...(context2 || []), ...coreMessages];
1457
+ return {
1458
+ messageObjects,
1459
+ convertedTools,
1460
+ threadId: threadIdToUse
1461
+ };
1462
+ },
1463
+ after: async ({
1464
+ result,
1465
+ threadId: threadId2,
1466
+ memoryConfig: memoryConfig2,
1467
+ outputText,
1468
+ runId: runId2
1469
+ }) => {
1470
+ const resToLog = {
1471
+ text: result?.text,
1472
+ object: result?.object,
1473
+ toolResults: result?.toolResults,
1474
+ toolCalls: result?.toolCalls,
1475
+ usage: result?.usage,
1476
+ steps: result?.steps?.map(s => {
1477
+ return {
1478
+ stepType: s?.stepType,
1479
+ text: result?.text,
1480
+ object: result?.object,
1481
+ toolResults: result?.toolResults,
1482
+ toolCalls: result?.toolCalls,
1483
+ usage: result?.usage
1484
+ };
1485
+ })
1486
+ };
1487
+ this.logger.debug(`[Agent:${this.name}] - Post processing LLM response`, {
1488
+ runId: runId2,
1489
+ result: resToLog,
1490
+ threadId: threadId2
1491
+ });
1492
+ if (this.getMemory() && resourceId) {
1493
+ try {
1494
+ await this.saveResponse({
1495
+ result,
1496
+ threadId: threadId2,
1497
+ resourceId,
1498
+ memoryConfig: memoryConfig2,
1499
+ runId: runId2
1500
+ });
1501
+ } catch (e) {
1502
+ this.logger.error("Error saving response", {
1503
+ error: e,
1504
+ runId: runId2,
1505
+ result: resToLog,
1506
+ threadId: threadId2
1507
+ });
1508
+ }
1509
+ }
1510
+ if (Object.keys(this.evals || {}).length > 0) {
1511
+ const input = messages.map(message => message.content).join("\n");
1512
+ const runIdToUse = runId2 || crypto.randomUUID();
1513
+ for (const metric of Object.values(this.evals || {})) {
1514
+ executeHook("onGeneration" /* ON_GENERATION */, {
1515
+ input,
1516
+ output: outputText,
1517
+ runId: runIdToUse,
1518
+ metric,
1519
+ agentName: this.name,
1520
+ instructions: this.instructions
1521
+ });
1522
+ }
1523
+ }
1524
+ }
1525
+ };
1526
+ }
1527
+ async generate(messages, {
1528
+ context: context2,
1529
+ threadId: threadIdInFn,
1530
+ memoryOptions,
1531
+ resourceId,
1532
+ maxSteps = 5,
1533
+ onStepFinish,
1534
+ runId,
1535
+ toolsets,
1536
+ output = "text",
1537
+ temperature,
1538
+ toolChoice = "auto",
1539
+ experimental_output,
1540
+ telemetry
1541
+ } = {}) {
1542
+ let messagesToUse = [];
1543
+ if (typeof messages === `string`) {
1544
+ messagesToUse = [{
1545
+ role: "user",
1546
+ content: messages
1547
+ }];
1548
+ } else {
1549
+ messagesToUse = messages.map(message => {
1550
+ if (typeof message === `string`) {
1551
+ return {
1552
+ role: "user",
1553
+ content: message
1554
+ };
1555
+ }
1556
+ return message;
1557
+ });
1558
+ }
1559
+ const runIdToUse = runId || crypto$1.randomUUID();
1560
+ const {
1561
+ before,
1562
+ after
1563
+ } = this.__primitive({
1564
+ messages: messagesToUse,
1565
+ context: context2,
1566
+ threadId: threadIdInFn,
1567
+ memoryConfig: memoryOptions,
1568
+ resourceId,
1569
+ runId: runIdToUse,
1570
+ toolsets
1571
+ });
1572
+ const {
1573
+ threadId,
1574
+ messageObjects,
1575
+ convertedTools
1576
+ } = await before();
1577
+ if (output === "text" && experimental_output) {
1578
+ const result2 = await this.llm.__text({
1579
+ messages: messageObjects,
1580
+ tools: this.tools,
1581
+ convertedTools,
1582
+ onStepFinish,
1583
+ maxSteps,
1584
+ runId: runIdToUse,
1585
+ temperature,
1586
+ toolChoice,
1587
+ experimental_output
1588
+ });
1589
+ const outputText2 = result2.text;
1590
+ await after({
1591
+ result: result2,
1592
+ threadId,
1593
+ memoryConfig: memoryOptions,
1594
+ outputText: outputText2,
1595
+ runId: runIdToUse
1596
+ });
1597
+ const newResult = result2;
1598
+ newResult.object = result2.experimental_output;
1599
+ return newResult;
1600
+ }
1601
+ if (output === "text") {
1602
+ const result2 = await this.llm.__text({
1603
+ messages: messageObjects,
1604
+ tools: this.tools,
1605
+ convertedTools,
1606
+ onStepFinish,
1607
+ maxSteps,
1608
+ runId: runIdToUse,
1609
+ temperature,
1610
+ toolChoice,
1611
+ telemetry
1612
+ });
1613
+ const outputText2 = result2.text;
1614
+ await after({
1615
+ result: result2,
1616
+ threadId,
1617
+ memoryConfig: memoryOptions,
1618
+ outputText: outputText2,
1619
+ runId: runIdToUse
1620
+ });
1621
+ return result2;
1622
+ }
1623
+ const result = await this.llm.__textObject({
1624
+ messages: messageObjects,
1625
+ tools: this.tools,
1626
+ structuredOutput: output,
1627
+ convertedTools,
1628
+ onStepFinish,
1629
+ maxSteps,
1630
+ runId: runIdToUse,
1631
+ temperature,
1632
+ toolChoice,
1633
+ telemetry
1634
+ });
1635
+ const outputText = JSON.stringify(result.object);
1636
+ await after({
1637
+ result,
1638
+ threadId,
1639
+ memoryConfig: memoryOptions,
1640
+ outputText,
1641
+ runId: runIdToUse
1642
+ });
1643
+ return result;
1644
+ }
1645
+ async stream(messages, {
1646
+ context: context2,
1647
+ threadId: threadIdInFn,
1648
+ memoryOptions,
1649
+ resourceId,
1650
+ maxSteps = 5,
1651
+ onFinish,
1652
+ onStepFinish,
1653
+ runId,
1654
+ toolsets,
1655
+ output = "text",
1656
+ temperature,
1657
+ toolChoice = "auto",
1658
+ experimental_output,
1659
+ telemetry
1660
+ } = {}) {
1661
+ const runIdToUse = runId || crypto$1.randomUUID();
1662
+ let messagesToUse = [];
1663
+ if (typeof messages === `string`) {
1664
+ messagesToUse = [{
1665
+ role: "user",
1666
+ content: messages
1667
+ }];
1668
+ } else {
1669
+ messagesToUse = messages.map(message => {
1670
+ if (typeof message === `string`) {
1671
+ return {
1672
+ role: "user",
1673
+ content: message
1674
+ };
1675
+ }
1676
+ return message;
1677
+ });
1678
+ }
1679
+ const {
1680
+ before,
1681
+ after
1682
+ } = this.__primitive({
1683
+ messages: messagesToUse,
1684
+ context: context2,
1685
+ threadId: threadIdInFn,
1686
+ memoryConfig: memoryOptions,
1687
+ resourceId,
1688
+ runId: runIdToUse,
1689
+ toolsets
1690
+ });
1691
+ const {
1692
+ threadId,
1693
+ messageObjects,
1694
+ convertedTools
1695
+ } = await before();
1696
+ if (output === "text" && experimental_output) {
1697
+ this.logger.debug(`Starting agent ${this.name} llm stream call`, {
1698
+ runId
1699
+ });
1700
+ const streamResult = await this.llm.__stream({
1701
+ messages: messageObjects,
1702
+ temperature,
1703
+ tools: this.tools,
1704
+ convertedTools,
1705
+ onStepFinish,
1706
+ onFinish: async result => {
1707
+ try {
1708
+ const res = JSON.parse(result) || {};
1709
+ const outputText = res.text;
1710
+ await after({
1711
+ result: res,
1712
+ threadId,
1713
+ memoryConfig: memoryOptions,
1714
+ outputText,
1715
+ runId: runIdToUse
1716
+ });
1717
+ } catch (e) {
1718
+ this.logger.error("Error saving memory on finish", {
1719
+ error: e,
1720
+ runId
1721
+ });
1722
+ }
1723
+ onFinish?.(result);
1724
+ },
1725
+ maxSteps,
1726
+ runId: runIdToUse,
1727
+ toolChoice,
1728
+ experimental_output
1729
+ });
1730
+ const newStreamResult = streamResult;
1731
+ newStreamResult.partialObjectStream = streamResult.experimental_partialOutputStream;
1732
+ return newStreamResult;
1733
+ } else if (output === "text") {
1734
+ this.logger.debug(`Starting agent ${this.name} llm stream call`, {
1735
+ runId
1736
+ });
1737
+ return this.llm.__stream({
1738
+ messages: messageObjects,
1739
+ temperature,
1740
+ tools: this.tools,
1741
+ convertedTools,
1742
+ onStepFinish,
1743
+ onFinish: async result => {
1744
+ try {
1745
+ const res = JSON.parse(result) || {};
1746
+ const outputText = res.text;
1747
+ await after({
1748
+ result: res,
1749
+ threadId,
1750
+ memoryConfig: memoryOptions,
1751
+ outputText,
1752
+ runId: runIdToUse
1753
+ });
1754
+ } catch (e) {
1755
+ this.logger.error("Error saving memory on finish", {
1756
+ error: e,
1757
+ runId
1758
+ });
1759
+ }
1760
+ onFinish?.(result);
1761
+ },
1762
+ maxSteps,
1763
+ runId: runIdToUse,
1764
+ toolChoice,
1765
+ telemetry
1766
+ });
1767
+ }
1768
+ this.logger.debug(`Starting agent ${this.name} llm streamObject call`, {
1769
+ runId
1770
+ });
1771
+ return this.llm.__streamObject({
1772
+ messages: messageObjects,
1773
+ tools: this.tools,
1774
+ temperature,
1775
+ structuredOutput: output,
1776
+ convertedTools,
1777
+ onStepFinish,
1778
+ onFinish: async result => {
1779
+ try {
1780
+ const res = JSON.parse(result) || {};
1781
+ const outputText = JSON.stringify(res.object);
1782
+ await after({
1783
+ result: res,
1784
+ threadId,
1785
+ memoryConfig: memoryOptions,
1786
+ outputText,
1787
+ runId: runIdToUse
1788
+ });
1789
+ } catch (e) {
1790
+ this.logger.error("Error saving memory on finish", {
1791
+ error: e,
1792
+ runId
1793
+ });
1794
+ }
1795
+ onFinish?.(result);
1796
+ },
1797
+ maxSteps,
1798
+ runId: runIdToUse,
1799
+ toolChoice,
1800
+ telemetry
1801
+ });
1802
+ }
1803
+ /**
1804
+ * Convert text to speech using the configured voice provider
1805
+ * @param input Text or text stream to convert to speech
1806
+ * @param options Speech options including speaker and provider-specific options
1807
+ * @returns Audio stream
1808
+ */
1809
+ async speak(input, options) {
1810
+ if (!this.voice) {
1811
+ throw new Error("No voice provider configured");
1812
+ }
1813
+ try {
1814
+ return this.voice.speak(input, options);
1815
+ } catch (e) {
1816
+ this.logger.error("Error during agent speak", {
1817
+ error: e
1818
+ });
1819
+ throw e;
1820
+ }
1821
+ }
1822
+ /**
1823
+ * Convert speech to text using the configured voice provider
1824
+ * @param audioStream Audio stream to transcribe
1825
+ * @param options Provider-specific transcription options
1826
+ * @returns Text or text stream
1827
+ */
1828
+ async listen(audioStream, options) {
1829
+ if (!this.voice) {
1830
+ throw new Error("No voice provider configured");
1831
+ }
1832
+ try {
1833
+ return this.voice.listen(audioStream, options);
1834
+ } catch (e) {
1835
+ this.logger.error("Error during agent listen", {
1836
+ error: e
1837
+ });
1838
+ throw e;
1839
+ }
1840
+ }
1841
+ /**
1842
+ * Get a list of available speakers from the configured voice provider
1843
+ * @throws {Error} If no voice provider is configured
1844
+ * @returns {Promise<Array<{voiceId: string}>>} List of available speakers
1845
+ */
1846
+ async getSpeakers() {
1847
+ if (!this.voice) {
1848
+ throw new Error("No voice provider configured");
1849
+ }
1850
+ try {
1851
+ return await this.voice.getSpeakers();
1852
+ } catch (e) {
1853
+ this.logger.error("Error during agent getSpeakers", {
1854
+ error: e
1855
+ });
1856
+ throw e;
1857
+ }
1858
+ }
1859
+ };
1860
+ exports.Agent = /*@__PURE__*/(_ => {
1861
+ _init = __decoratorStart(_a);
1862
+ exports.Agent = __decorateElement(_init, 0, "Agent", _Agent_decorators, exports.Agent);
1863
+ __runInitializers(_init, 1, exports.Agent);
1864
+ return exports.Agent;
1865
+ })();