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