@mastra/core 0.5.0-alpha.8 → 0.5.0

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