@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,1741 @@
1
+ 'use strict';
2
+
3
+ var stream = require('stream');
4
+ var pino = require('pino');
5
+ var pretty = require('pino-pretty');
6
+ var path = require('path');
7
+ var client = require('@libsql/client');
8
+ var api = require('@opentelemetry/api');
9
+ var core = require('@opentelemetry/core');
10
+ var otlpTransformer = require('@opentelemetry/otlp-transformer');
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(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 RegisteredLogger = {
66
+ LLM: "LLM"};
67
+ var LogLevel = {
68
+ INFO: "info",
69
+ WARN: "warn"};
70
+ var Logger = class {
71
+ logger;
72
+ transports;
73
+ constructor(options = {}) {
74
+ this.transports = options.transports || {};
75
+ const transportsAry = Object.entries(this.transports);
76
+ this.logger = pino__default.default({
77
+ name: options.name || "app",
78
+ level: options.level || LogLevel.INFO
79
+ }, options.overrideDefaultTransports ? options?.transports?.default : transportsAry.length === 0 ? pretty__default.default({
80
+ colorize: true,
81
+ levelFirst: true,
82
+ ignore: "pid,hostname",
83
+ colorizeObjects: true,
84
+ translateTime: "SYS:standard",
85
+ singleLine: false
86
+ }) : pino__default.default.multistream([...transportsAry.map(([_, transport]) => ({
87
+ stream: transport,
88
+ level: options.level || LogLevel.INFO
89
+ })), {
90
+ stream: pretty__default.default({
91
+ colorize: true,
92
+ levelFirst: true,
93
+ ignore: "pid,hostname",
94
+ colorizeObjects: true,
95
+ translateTime: "SYS:standard",
96
+ singleLine: false
97
+ }),
98
+ level: options.level || LogLevel.INFO
99
+ }]));
100
+ }
101
+ debug(message, args = {}) {
102
+ this.logger.debug(args, message);
103
+ }
104
+ info(message, args = {}) {
105
+ this.logger.info(args, message);
106
+ }
107
+ warn(message, args = {}) {
108
+ this.logger.warn(args, message);
109
+ }
110
+ error(message, args = {}) {
111
+ this.logger.error(args, message);
112
+ }
113
+ // Stream creation for process output handling
114
+ createStream() {
115
+ return new stream.Transform({
116
+ transform: (chunk, _encoding, callback) => {
117
+ const line = chunk.toString().trim();
118
+ if (line) {
119
+ this.info(line);
120
+ }
121
+ callback(null, chunk);
122
+ }
123
+ });
124
+ }
125
+ async getLogs(transportId) {
126
+ if (!transportId || !this.transports[transportId]) {
127
+ return [];
128
+ }
129
+ return this.transports[transportId].getLogs();
130
+ }
131
+ async getLogsByRunId({
132
+ runId,
133
+ transportId
134
+ }) {
135
+ return this.transports[transportId]?.getLogsByRunId({
136
+ runId
137
+ });
138
+ }
139
+ };
140
+ function createLogger(options) {
141
+ return new Logger(options);
142
+ }
143
+ var noopLogger = {
144
+ debug: () => {},
145
+ info: () => {},
146
+ warn: () => {},
147
+ error: () => {},
148
+ cleanup: async () => {}
149
+ };
150
+
151
+ // src/base.ts
152
+ var MastraBase = class {
153
+ component = RegisteredLogger.LLM;
154
+ logger;
155
+ name;
156
+ telemetry;
157
+ constructor({
158
+ component,
159
+ name
160
+ }) {
161
+ this.component = component || RegisteredLogger.LLM;
162
+ this.name = name;
163
+ this.logger = createLogger({
164
+ name: `${this.component} - ${this.name}`
165
+ });
166
+ }
167
+ /**
168
+ * Set the logger for the agent
169
+ * @param logger
170
+ */
171
+ __setLogger(logger) {
172
+ this.logger = logger;
173
+ this.logger.debug(`Logger updated [component=${this.component}] [name=${this.name}]`);
174
+ }
175
+ /**
176
+ * Set the telemetry for the
177
+ * @param telemetry
178
+ */
179
+ __setTelemetry(telemetry) {
180
+ this.telemetry = telemetry;
181
+ this.logger.debug(`Telemetry updated [component=${this.component}] [tracer=${this.telemetry.tracer}]`);
182
+ }
183
+ /**
184
+ * Get the telemetry on the vector
185
+ * @returns telemetry
186
+ */
187
+ __getTelemetry() {
188
+ return this.telemetry;
189
+ }
190
+ /*
191
+ get experimental_telemetry config
192
+ */
193
+ get experimental_telemetry() {
194
+ return this.telemetry ? {
195
+ // tracer: this.telemetry.tracer,
196
+ tracer: this.telemetry.getBaggageTracer(),
197
+ isEnabled: !!this.telemetry.tracer
198
+ } : void 0;
199
+ }
200
+ };
201
+
202
+ // src/storage/constants.ts
203
+ var TABLE_WORKFLOW_SNAPSHOT = "mastra_workflow_snapshot";
204
+ var TABLE_EVALS = "mastra_evals";
205
+ var TABLE_MESSAGES = "mastra_messages";
206
+ var TABLE_THREADS = "mastra_threads";
207
+ var TABLE_TRACES = "mastra_traces";
208
+
209
+ // src/storage/base.ts
210
+ var MastraStorage = class extends MastraBase {
211
+ /** @deprecated import from { TABLE_WORKFLOW_SNAPSHOT } '@mastra/core/storage' instead */
212
+ static TABLE_WORKFLOW_SNAPSHOT = TABLE_WORKFLOW_SNAPSHOT;
213
+ /** @deprecated import from { TABLE_EVALS } '@mastra/core/storage' instead */
214
+ static TABLE_EVALS = TABLE_EVALS;
215
+ /** @deprecated import from { TABLE_MESSAGES } '@mastra/core/storage' instead */
216
+ static TABLE_MESSAGES = TABLE_MESSAGES;
217
+ /** @deprecated import from { TABLE_THREADS } '@mastra/core/storage' instead */
218
+ static TABLE_THREADS = TABLE_THREADS;
219
+ /** @deprecated import { TABLE_TRACES } from '@mastra/core/storage' instead */
220
+ static TABLE_TRACES = TABLE_TRACES;
221
+ hasInitialized = null;
222
+ constructor({
223
+ name
224
+ }) {
225
+ super({
226
+ component: "STORAGE",
227
+ name
228
+ });
229
+ }
230
+ async __batchInsert({
231
+ tableName,
232
+ records
233
+ }) {
234
+ await this.init();
235
+ return this.batchInsert({
236
+ tableName,
237
+ records
238
+ });
239
+ }
240
+ async __getThreadById({
241
+ threadId
242
+ }) {
243
+ await this.init();
244
+ return this.getThreadById({
245
+ threadId
246
+ });
247
+ }
248
+ async __getThreadsByResourceId({
249
+ resourceId
250
+ }) {
251
+ await this.init();
252
+ return this.getThreadsByResourceId({
253
+ resourceId
254
+ });
255
+ }
256
+ async __saveThread({
257
+ thread
258
+ }) {
259
+ await this.init();
260
+ return this.saveThread({
261
+ thread
262
+ });
263
+ }
264
+ async __updateThread({
265
+ id,
266
+ title,
267
+ metadata
268
+ }) {
269
+ await this.init();
270
+ return this.updateThread({
271
+ id,
272
+ title,
273
+ metadata
274
+ });
275
+ }
276
+ async __deleteThread({
277
+ threadId
278
+ }) {
279
+ await this.init();
280
+ return this.deleteThread({
281
+ threadId
282
+ });
283
+ }
284
+ async __getMessages({
285
+ threadId,
286
+ selectBy,
287
+ threadConfig
288
+ }) {
289
+ await this.init();
290
+ return this.getMessages({
291
+ threadId,
292
+ selectBy,
293
+ threadConfig
294
+ });
295
+ }
296
+ async __saveMessages({
297
+ messages
298
+ }) {
299
+ await this.init();
300
+ return this.saveMessages({
301
+ messages
302
+ });
303
+ }
304
+ async __getTraces({
305
+ scope,
306
+ page,
307
+ perPage,
308
+ attributes
309
+ }) {
310
+ await this.init();
311
+ return this.getTraces({
312
+ scope,
313
+ page,
314
+ perPage,
315
+ attributes
316
+ });
317
+ }
318
+ async init() {
319
+ if (await this.hasInitialized) {
320
+ return;
321
+ }
322
+ this.hasInitialized = Promise.all([this.createTable({
323
+ tableName: TABLE_WORKFLOW_SNAPSHOT,
324
+ schema: {
325
+ workflow_name: {
326
+ type: "text"
327
+ },
328
+ run_id: {
329
+ type: "text"
330
+ },
331
+ snapshot: {
332
+ type: "text"
333
+ },
334
+ createdAt: {
335
+ type: "timestamp"
336
+ },
337
+ updatedAt: {
338
+ type: "timestamp"
339
+ }
340
+ }
341
+ }), this.createTable({
342
+ tableName: TABLE_EVALS,
343
+ schema: {
344
+ input: {
345
+ type: "text"
346
+ },
347
+ output: {
348
+ type: "text"
349
+ },
350
+ result: {
351
+ type: "jsonb"
352
+ },
353
+ agent_name: {
354
+ type: "text"
355
+ },
356
+ metric_name: {
357
+ type: "text"
358
+ },
359
+ instructions: {
360
+ type: "text"
361
+ },
362
+ test_info: {
363
+ type: "jsonb",
364
+ nullable: true
365
+ },
366
+ global_run_id: {
367
+ type: "text"
368
+ },
369
+ run_id: {
370
+ type: "text"
371
+ },
372
+ created_at: {
373
+ type: "timestamp"
374
+ }
375
+ }
376
+ }), this.createTable({
377
+ tableName: TABLE_THREADS,
378
+ schema: {
379
+ id: {
380
+ type: "text",
381
+ nullable: false,
382
+ primaryKey: true
383
+ },
384
+ resourceId: {
385
+ type: "text",
386
+ nullable: false
387
+ },
388
+ title: {
389
+ type: "text",
390
+ nullable: false
391
+ },
392
+ metadata: {
393
+ type: "text",
394
+ nullable: true
395
+ },
396
+ createdAt: {
397
+ type: "timestamp",
398
+ nullable: false
399
+ },
400
+ updatedAt: {
401
+ type: "timestamp",
402
+ nullable: false
403
+ }
404
+ }
405
+ }), this.createTable({
406
+ tableName: TABLE_MESSAGES,
407
+ schema: {
408
+ id: {
409
+ type: "text",
410
+ nullable: false,
411
+ primaryKey: true
412
+ },
413
+ thread_id: {
414
+ type: "text",
415
+ nullable: false
416
+ },
417
+ content: {
418
+ type: "text",
419
+ nullable: false
420
+ },
421
+ role: {
422
+ type: "text",
423
+ nullable: false
424
+ },
425
+ type: {
426
+ type: "text",
427
+ nullable: false
428
+ },
429
+ createdAt: {
430
+ type: "timestamp",
431
+ nullable: false
432
+ }
433
+ }
434
+ }), this.createTable({
435
+ tableName: TABLE_TRACES,
436
+ schema: {
437
+ id: {
438
+ type: "text",
439
+ nullable: false,
440
+ primaryKey: true
441
+ },
442
+ parentSpanId: {
443
+ type: "text",
444
+ nullable: true
445
+ },
446
+ name: {
447
+ type: "text",
448
+ nullable: false
449
+ },
450
+ traceId: {
451
+ type: "text",
452
+ nullable: false
453
+ },
454
+ scope: {
455
+ type: "text",
456
+ nullable: false
457
+ },
458
+ kind: {
459
+ type: "integer",
460
+ nullable: false
461
+ },
462
+ attributes: {
463
+ type: "jsonb",
464
+ nullable: true
465
+ },
466
+ status: {
467
+ type: "jsonb",
468
+ nullable: true
469
+ },
470
+ events: {
471
+ type: "jsonb",
472
+ nullable: true
473
+ },
474
+ links: {
475
+ type: "jsonb",
476
+ nullable: true
477
+ },
478
+ other: {
479
+ type: "text",
480
+ nullable: true
481
+ },
482
+ startTime: {
483
+ type: "bigint",
484
+ nullable: false
485
+ },
486
+ endTime: {
487
+ type: "bigint",
488
+ nullable: false
489
+ },
490
+ createdAt: {
491
+ type: "timestamp",
492
+ nullable: false
493
+ }
494
+ }
495
+ })]).then(() => true);
496
+ await this.hasInitialized;
497
+ }
498
+ async persistWorkflowSnapshot({
499
+ workflowName,
500
+ runId,
501
+ snapshot
502
+ }) {
503
+ await this.init();
504
+ const data = {
505
+ workflow_name: workflowName,
506
+ run_id: runId,
507
+ snapshot,
508
+ createdAt: /* @__PURE__ */new Date(),
509
+ updatedAt: /* @__PURE__ */new Date()
510
+ };
511
+ this.logger.debug("Persisting workflow snapshot", {
512
+ workflowName,
513
+ runId,
514
+ data
515
+ });
516
+ await this.insert({
517
+ tableName: TABLE_WORKFLOW_SNAPSHOT,
518
+ record: data
519
+ });
520
+ }
521
+ async loadWorkflowSnapshot({
522
+ workflowName,
523
+ runId
524
+ }) {
525
+ if (!this.hasInitialized) {
526
+ await this.init();
527
+ }
528
+ this.logger.debug("Loading workflow snapshot", {
529
+ workflowName,
530
+ runId
531
+ });
532
+ const d = await this.load({
533
+ tableName: TABLE_WORKFLOW_SNAPSHOT,
534
+ keys: {
535
+ workflow_name: workflowName,
536
+ run_id: runId
537
+ }
538
+ });
539
+ return d ? d.snapshot : null;
540
+ }
541
+ async __getEvalsByAgentName(agentName, type) {
542
+ await this.init();
543
+ return this.getEvalsByAgentName(agentName, type);
544
+ }
545
+ };
546
+
547
+ // src/storage/libsql/index.ts
548
+ function safelyParseJSON(jsonString) {
549
+ try {
550
+ return JSON.parse(jsonString);
551
+ } catch {
552
+ return {};
553
+ }
554
+ }
555
+ var LibSQLStore = class extends MastraStorage {
556
+ client;
557
+ constructor({
558
+ config
559
+ }) {
560
+ super({
561
+ name: `LibSQLStore`
562
+ });
563
+ this.client = client.createClient({
564
+ url: this.rewriteDbUrl(config.url),
565
+ authToken: config.authToken
566
+ });
567
+ }
568
+ rewriteDbUrl(url) {
569
+ if (url.startsWith("file:") && !url.startsWith("file:/")) {
570
+ const cwd = process.cwd();
571
+ const relativePath = url.slice("file:".length);
572
+ if (cwd.endsWith(".mastra") || cwd.endsWith(".mastra/")) {
573
+ const baseDir = path.join(cwd, `..`);
574
+ const fullPath = path.join(baseDir, relativePath);
575
+ this.logger.debug(`Initializing LibSQL db with url ${url} with relative file path from inside .mastra directory. Rewriting relative file url to "file:${fullPath}". This ensures it's outside the .mastra directory. If the db is stored inside .mastra it will be deleted when Mastra re-bundles code.`);
576
+ return `file:${fullPath}`;
577
+ }
578
+ }
579
+ return url;
580
+ }
581
+ getCreateTableSQL(tableName, schema) {
582
+ const columns = Object.entries(schema).map(([name, col]) => {
583
+ let type = col.type.toUpperCase();
584
+ if (type === "TEXT") type = "TEXT";
585
+ if (type === "TIMESTAMP") type = "TEXT";
586
+ const nullable = col.nullable ? "" : "NOT NULL";
587
+ const primaryKey = col.primaryKey ? "PRIMARY KEY" : "";
588
+ return `${name} ${type} ${nullable} ${primaryKey}`.trim();
589
+ });
590
+ if (tableName === TABLE_WORKFLOW_SNAPSHOT) {
591
+ const stmnt = `CREATE TABLE IF NOT EXISTS ${tableName} (
592
+ ${columns.join(",\n")},
593
+ PRIMARY KEY (workflow_name, run_id)
594
+ )`;
595
+ return stmnt;
596
+ }
597
+ return `CREATE TABLE IF NOT EXISTS ${tableName} (${columns.join(", ")})`;
598
+ }
599
+ async createTable({
600
+ tableName,
601
+ schema
602
+ }) {
603
+ try {
604
+ this.logger.debug(`Creating database table`, {
605
+ tableName,
606
+ operation: "schema init"
607
+ });
608
+ const sql = this.getCreateTableSQL(tableName, schema);
609
+ await this.client.execute(sql);
610
+ } catch (error) {
611
+ this.logger.error(`Error creating table ${tableName}: ${error}`);
612
+ throw error;
613
+ }
614
+ }
615
+ async clearTable({
616
+ tableName
617
+ }) {
618
+ try {
619
+ await this.client.execute(`DELETE FROM ${tableName}`);
620
+ } catch (e) {
621
+ if (e instanceof Error) {
622
+ this.logger.error(e.message);
623
+ }
624
+ }
625
+ }
626
+ prepareStatement({
627
+ tableName,
628
+ record
629
+ }) {
630
+ const columns = Object.keys(record);
631
+ const values = Object.values(record).map(v => {
632
+ if (typeof v === `undefined`) {
633
+ return null;
634
+ }
635
+ return typeof v === "object" ? JSON.stringify(v) : v;
636
+ });
637
+ const placeholders = values.map(() => "?").join(", ");
638
+ return {
639
+ sql: `INSERT OR REPLACE INTO ${tableName} (${columns.join(", ")}) VALUES (${placeholders})`,
640
+ args: values
641
+ };
642
+ }
643
+ async insert({
644
+ tableName,
645
+ record
646
+ }) {
647
+ try {
648
+ await this.client.execute(this.prepareStatement({
649
+ tableName,
650
+ record
651
+ }));
652
+ } catch (error) {
653
+ this.logger.error(`Error upserting into table ${tableName}: ${error}`);
654
+ throw error;
655
+ }
656
+ }
657
+ async batchInsert({
658
+ tableName,
659
+ records
660
+ }) {
661
+ if (records.length === 0) return;
662
+ try {
663
+ const batchStatements = records.map(r => this.prepareStatement({
664
+ tableName,
665
+ record: r
666
+ }));
667
+ await this.client.batch(batchStatements, "write");
668
+ } catch (error) {
669
+ this.logger.error(`Error upserting into table ${tableName}: ${error}`);
670
+ throw error;
671
+ }
672
+ }
673
+ async load({
674
+ tableName,
675
+ keys
676
+ }) {
677
+ const conditions = Object.entries(keys).map(([key]) => `${key} = ?`).join(" AND ");
678
+ const values = Object.values(keys);
679
+ const result = await this.client.execute({
680
+ sql: `SELECT * FROM ${tableName} WHERE ${conditions} ORDER BY createdAt DESC LIMIT 1`,
681
+ args: values
682
+ });
683
+ if (!result.rows || result.rows.length === 0) {
684
+ return null;
685
+ }
686
+ const row = result.rows[0];
687
+ const parsed = Object.fromEntries(Object.entries(row || {}).map(([k, v]) => {
688
+ try {
689
+ return [k, typeof v === "string" ? JSON.parse(v) : v];
690
+ } catch {
691
+ return [k, v];
692
+ }
693
+ }));
694
+ return parsed;
695
+ }
696
+ async getThreadById({
697
+ threadId
698
+ }) {
699
+ const result = await this.load({
700
+ tableName: TABLE_THREADS,
701
+ keys: {
702
+ id: threadId
703
+ }
704
+ });
705
+ if (!result) {
706
+ return null;
707
+ }
708
+ return {
709
+ ...result,
710
+ metadata: typeof result.metadata === "string" ? JSON.parse(result.metadata) : result.metadata
711
+ };
712
+ }
713
+ async getThreadsByResourceId({
714
+ resourceId
715
+ }) {
716
+ const result = await this.client.execute({
717
+ sql: `SELECT * FROM ${TABLE_THREADS} WHERE resourceId = ?`,
718
+ args: [resourceId]
719
+ });
720
+ if (!result.rows) {
721
+ return [];
722
+ }
723
+ return result.rows.map(thread => ({
724
+ id: thread.id,
725
+ resourceId: thread.resourceId,
726
+ title: thread.title,
727
+ createdAt: thread.createdAt,
728
+ updatedAt: thread.updatedAt,
729
+ metadata: typeof thread.metadata === "string" ? JSON.parse(thread.metadata) : thread.metadata
730
+ }));
731
+ }
732
+ async saveThread({
733
+ thread
734
+ }) {
735
+ await this.insert({
736
+ tableName: TABLE_THREADS,
737
+ record: {
738
+ ...thread,
739
+ metadata: JSON.stringify(thread.metadata)
740
+ }
741
+ });
742
+ return thread;
743
+ }
744
+ async updateThread({
745
+ id,
746
+ title,
747
+ metadata
748
+ }) {
749
+ const thread = await this.getThreadById({
750
+ threadId: id
751
+ });
752
+ if (!thread) {
753
+ throw new Error(`Thread ${id} not found`);
754
+ }
755
+ const updatedThread = {
756
+ ...thread,
757
+ title,
758
+ metadata: {
759
+ ...thread.metadata,
760
+ ...metadata
761
+ }
762
+ };
763
+ await this.client.execute({
764
+ sql: `UPDATE ${TABLE_THREADS} SET title = ?, metadata = ? WHERE id = ?`,
765
+ args: [title, JSON.stringify(updatedThread.metadata), id]
766
+ });
767
+ return updatedThread;
768
+ }
769
+ async deleteThread({
770
+ threadId
771
+ }) {
772
+ await this.client.execute({
773
+ sql: `DELETE FROM ${TABLE_THREADS} WHERE id = ?`,
774
+ args: [threadId]
775
+ });
776
+ }
777
+ parseRow(row) {
778
+ let content = row.content;
779
+ try {
780
+ content = JSON.parse(row.content);
781
+ } catch {}
782
+ return {
783
+ id: row.id,
784
+ content,
785
+ role: row.role,
786
+ type: row.type,
787
+ createdAt: new Date(row.createdAt),
788
+ threadId: row.thread_id
789
+ };
790
+ }
791
+ async getMessages({
792
+ threadId,
793
+ selectBy
794
+ }) {
795
+ try {
796
+ const messages = [];
797
+ const limit = typeof selectBy?.last === `number` ? selectBy.last : 40;
798
+ if (selectBy?.include?.length) {
799
+ const includeIds = selectBy.include.map(i => i.id);
800
+ const maxPrev = Math.max(...selectBy.include.map(i => i.withPreviousMessages || 0));
801
+ const maxNext = Math.max(...selectBy.include.map(i => i.withNextMessages || 0));
802
+ const includeResult = await this.client.execute({
803
+ sql: `
804
+ WITH numbered_messages AS (
805
+ SELECT
806
+ id,
807
+ content,
808
+ role,
809
+ type,
810
+ "createdAt",
811
+ thread_id,
812
+ ROW_NUMBER() OVER (ORDER BY "createdAt" ASC) as row_num
813
+ FROM "${TABLE_MESSAGES}"
814
+ WHERE thread_id = ?
815
+ ),
816
+ target_positions AS (
817
+ SELECT row_num as target_pos
818
+ FROM numbered_messages
819
+ WHERE id IN (${includeIds.map(() => "?").join(", ")})
820
+ )
821
+ SELECT DISTINCT m.*
822
+ FROM numbered_messages m
823
+ CROSS JOIN target_positions t
824
+ WHERE m.row_num BETWEEN (t.target_pos - ?) AND (t.target_pos + ?)
825
+ ORDER BY m."createdAt" ASC
826
+ `,
827
+ args: [threadId, ...includeIds, maxPrev, maxNext]
828
+ });
829
+ if (includeResult.rows) {
830
+ messages.push(...includeResult.rows.map(row => this.parseRow(row)));
831
+ }
832
+ }
833
+ const excludeIds = messages.map(m => m.id);
834
+ const remainingSql = `
835
+ SELECT
836
+ id,
837
+ content,
838
+ role,
839
+ type,
840
+ "createdAt",
841
+ thread_id
842
+ FROM "${TABLE_MESSAGES}"
843
+ WHERE thread_id = ?
844
+ ${excludeIds.length ? `AND id NOT IN (${excludeIds.map(() => "?").join(", ")})` : ""}
845
+ ORDER BY "createdAt" DESC
846
+ LIMIT ?
847
+ `;
848
+ const remainingArgs = [threadId, ...(excludeIds.length ? excludeIds : []), limit];
849
+ const remainingResult = await this.client.execute({
850
+ sql: remainingSql,
851
+ args: remainingArgs
852
+ });
853
+ if (remainingResult.rows) {
854
+ messages.push(...remainingResult.rows.map(row => this.parseRow(row)));
855
+ }
856
+ messages.sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime());
857
+ return messages;
858
+ } catch (error) {
859
+ this.logger.error("Error getting messages:", error);
860
+ throw error;
861
+ }
862
+ }
863
+ async saveMessages({
864
+ messages
865
+ }) {
866
+ if (messages.length === 0) return messages;
867
+ const tx = await this.client.transaction("write");
868
+ try {
869
+ const threadId = messages[0]?.threadId;
870
+ if (!threadId) {
871
+ throw new Error("Thread ID is required");
872
+ }
873
+ for (const message of messages) {
874
+ const time = message.createdAt || /* @__PURE__ */new Date();
875
+ await tx.execute({
876
+ sql: `INSERT INTO ${TABLE_MESSAGES} (id, thread_id, content, role, type, createdAt)
877
+ VALUES (?, ?, ?, ?, ?, ?)`,
878
+ args: [message.id, threadId, typeof message.content === "object" ? JSON.stringify(message.content) : message.content, message.role, message.type, time instanceof Date ? time.toISOString() : time]
879
+ });
880
+ }
881
+ await tx.commit();
882
+ return messages;
883
+ } catch (error) {
884
+ this.logger.error("Failed to save messages in database: " + error?.message);
885
+ await tx.rollback();
886
+ throw error;
887
+ }
888
+ }
889
+ transformEvalRow(row) {
890
+ const resultValue = JSON.parse(row.result);
891
+ const testInfoValue = row.test_info ? JSON.parse(row.test_info) : void 0;
892
+ if (!resultValue || typeof resultValue !== "object" || !("score" in resultValue)) {
893
+ throw new Error(`Invalid MetricResult format: ${JSON.stringify(resultValue)}`);
894
+ }
895
+ return {
896
+ input: row.input,
897
+ output: row.output,
898
+ result: resultValue,
899
+ agentName: row.agent_name,
900
+ metricName: row.metric_name,
901
+ instructions: row.instructions,
902
+ testInfo: testInfoValue,
903
+ globalRunId: row.global_run_id,
904
+ runId: row.run_id,
905
+ createdAt: row.created_at
906
+ };
907
+ }
908
+ async getEvalsByAgentName(agentName, type) {
909
+ try {
910
+ const baseQuery = `SELECT * FROM ${TABLE_EVALS} WHERE agent_name = ?`;
911
+ const typeCondition = type === "test" ? " AND test_info IS NOT NULL AND test_info->>'testPath' IS NOT NULL" : type === "live" ? " AND (test_info IS NULL OR test_info->>'testPath' IS NULL)" : "";
912
+ const result = await this.client.execute({
913
+ sql: `${baseQuery}${typeCondition} ORDER BY created_at DESC`,
914
+ args: [agentName]
915
+ });
916
+ return result.rows?.map(row => this.transformEvalRow(row)) ?? [];
917
+ } catch (error) {
918
+ if (error instanceof Error && error.message.includes("no such table")) {
919
+ return [];
920
+ }
921
+ this.logger.error("Failed to get evals for the specified agent: " + error?.message);
922
+ throw error;
923
+ }
924
+ }
925
+ // TODO: add types
926
+ async getTraces({
927
+ name,
928
+ scope,
929
+ page,
930
+ perPage,
931
+ attributes
932
+ } = {
933
+ page: 0,
934
+ perPage: 100
935
+ }) {
936
+ const limit = perPage;
937
+ const offset = page * perPage;
938
+ const args = [];
939
+ const conditions = [];
940
+ if (name) {
941
+ conditions.push("name LIKE CONCAT(?, '%')");
942
+ }
943
+ if (scope) {
944
+ conditions.push("scope = ?");
945
+ }
946
+ if (attributes) {
947
+ Object.keys(attributes).forEach(key => {
948
+ conditions.push(`attributes->>'$.${key}' = ?`);
949
+ });
950
+ }
951
+ const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
952
+ if (name) {
953
+ args.push(name);
954
+ }
955
+ if (scope) {
956
+ args.push(scope);
957
+ }
958
+ if (attributes) {
959
+ for (const [_key, value] of Object.entries(attributes)) {
960
+ args.push(value);
961
+ }
962
+ }
963
+ args.push(limit, offset);
964
+ const result = await this.client.execute({
965
+ sql: `SELECT * FROM ${TABLE_TRACES} ${whereClause} ORDER BY "startTime" DESC LIMIT ? OFFSET ?`,
966
+ args
967
+ });
968
+ if (!result.rows) {
969
+ return [];
970
+ }
971
+ return result.rows.map(row => ({
972
+ id: row.id,
973
+ parentSpanId: row.parentSpanId,
974
+ traceId: row.traceId,
975
+ name: row.name,
976
+ scope: row.scope,
977
+ kind: row.kind,
978
+ status: safelyParseJSON(row.status),
979
+ events: safelyParseJSON(row.events),
980
+ links: safelyParseJSON(row.links),
981
+ attributes: safelyParseJSON(row.attributes),
982
+ startTime: row.startTime,
983
+ endTime: row.endTime,
984
+ other: safelyParseJSON(row.other),
985
+ createdAt: row.createdAt
986
+ }));
987
+ }
988
+ };
989
+ function hasActiveTelemetry(tracerName = "default-tracer") {
990
+ try {
991
+ return !!api.trace.getTracer(tracerName);
992
+ } catch {
993
+ return false;
994
+ }
995
+ }
996
+
997
+ // src/telemetry/telemetry.decorators.ts
998
+ function withSpan(options) {
999
+ return function (_target, propertyKey, descriptor) {
1000
+ if (!descriptor || typeof descriptor === "number") return;
1001
+ const originalMethod = descriptor.value;
1002
+ const methodName = String(propertyKey);
1003
+ descriptor.value = function (...args) {
1004
+ if (options?.skipIfNoTelemetry && !hasActiveTelemetry(options?.tracerName)) {
1005
+ return originalMethod.apply(this, args);
1006
+ }
1007
+ const tracer = api.trace.getTracer(options?.tracerName ?? "default-tracer");
1008
+ let spanName;
1009
+ let spanKind;
1010
+ if (typeof options === "string") {
1011
+ spanName = options;
1012
+ } else if (options) {
1013
+ spanName = options.spanName || methodName;
1014
+ spanKind = options.spanKind;
1015
+ } else {
1016
+ spanName = methodName;
1017
+ }
1018
+ const span = tracer.startSpan(spanName, {
1019
+ kind: spanKind
1020
+ });
1021
+ let ctx = api.trace.setSpan(api.context.active(), span);
1022
+ args.forEach((arg, index) => {
1023
+ try {
1024
+ span.setAttribute(`${spanName}.argument.${index}`, JSON.stringify(arg));
1025
+ } catch {
1026
+ span.setAttribute(`${spanName}.argument.${index}`, "[Not Serializable]");
1027
+ }
1028
+ });
1029
+ const currentBaggage = api.propagation.getBaggage(ctx);
1030
+ if (currentBaggage?.componentName) {
1031
+ span.setAttribute("componentName", currentBaggage?.componentName);
1032
+ span.setAttribute("runId", currentBaggage?.runId);
1033
+ } else if (this && this.name) {
1034
+ span.setAttribute("componentName", this.name);
1035
+ span.setAttribute("runId", this.runId);
1036
+ ctx = api.propagation.setBaggage(ctx, {
1037
+ componentName: this.name,
1038
+ runId: this.runId
1039
+ });
1040
+ }
1041
+ let result;
1042
+ try {
1043
+ result = api.context.with(ctx, () => originalMethod.apply(this, args));
1044
+ if (result instanceof Promise) {
1045
+ return result.then(resolvedValue => {
1046
+ try {
1047
+ span.setAttribute(`${spanName}.result`, JSON.stringify(resolvedValue));
1048
+ } catch {
1049
+ span.setAttribute(`${spanName}.result`, "[Not Serializable]");
1050
+ }
1051
+ return resolvedValue;
1052
+ }).finally(() => span.end());
1053
+ }
1054
+ try {
1055
+ span.setAttribute(`${spanName}.result`, JSON.stringify(result));
1056
+ } catch {
1057
+ span.setAttribute(`${spanName}.result`, "[Not Serializable]");
1058
+ }
1059
+ return result;
1060
+ } catch (error) {
1061
+ span.setStatus({
1062
+ code: api.SpanStatusCode.ERROR,
1063
+ message: error instanceof Error ? error.message : "Unknown error"
1064
+ });
1065
+ if (error instanceof Error) {
1066
+ span.recordException(error);
1067
+ }
1068
+ throw error;
1069
+ } finally {
1070
+ if (!(result instanceof Promise)) {
1071
+ span.end();
1072
+ }
1073
+ }
1074
+ };
1075
+ return descriptor;
1076
+ };
1077
+ }
1078
+ function InstrumentClass(options) {
1079
+ return function (target) {
1080
+ const methods = Object.getOwnPropertyNames(target.prototype);
1081
+ methods.forEach(method => {
1082
+ if (options?.excludeMethods?.includes(method) || method === "constructor") return;
1083
+ if (options?.methodFilter && !options.methodFilter(method)) return;
1084
+ const descriptor = Object.getOwnPropertyDescriptor(target.prototype, method);
1085
+ if (descriptor && typeof descriptor.value === "function") {
1086
+ Object.defineProperty(target.prototype, method, withSpan({
1087
+ spanName: options?.prefix ? `${options.prefix}.${method}` : method,
1088
+ skipIfNoTelemetry: true,
1089
+ spanKind: options?.spanKind || api.SpanKind.INTERNAL,
1090
+ tracerName: options?.tracerName
1091
+ })(target, method, descriptor));
1092
+ }
1093
+ });
1094
+ return target;
1095
+ };
1096
+ }
1097
+ var OTLPTraceExporter = class {
1098
+ storage;
1099
+ queue = [];
1100
+ serializer;
1101
+ logger;
1102
+ activeFlush = void 0;
1103
+ constructor({
1104
+ logger,
1105
+ storage
1106
+ }) {
1107
+ this.storage = storage;
1108
+ this.serializer = otlpTransformer.JsonTraceSerializer;
1109
+ this.logger = logger;
1110
+ }
1111
+ export(internalRepresentation, resultCallback) {
1112
+ const serializedRequest = this.serializer.serializeRequest(internalRepresentation);
1113
+ const payload = JSON.parse(Buffer.from(serializedRequest.buffer, "utf8"));
1114
+ const items = payload?.resourceSpans?.[0]?.scopeSpans;
1115
+ this.logger.debug(`Exporting telemetry: ${items.length} scope spans to be processed [trace batch]`);
1116
+ this.queue.push({
1117
+ data: items,
1118
+ resultCallback
1119
+ });
1120
+ if (!this.activeFlush) {
1121
+ this.activeFlush = this.flush();
1122
+ }
1123
+ }
1124
+ shutdown() {
1125
+ return this.forceFlush();
1126
+ }
1127
+ flush() {
1128
+ const now = /* @__PURE__ */new Date();
1129
+ const items = this.queue.shift();
1130
+ if (!items) return Promise.resolve();
1131
+ const allSpans = items.data.reduce((acc, scopedSpans) => {
1132
+ const {
1133
+ scope,
1134
+ spans
1135
+ } = scopedSpans;
1136
+ for (const span of spans) {
1137
+ const {
1138
+ spanId,
1139
+ parentSpanId,
1140
+ traceId,
1141
+ name,
1142
+ kind,
1143
+ attributes,
1144
+ status,
1145
+ events,
1146
+ links,
1147
+ startTimeUnixNano,
1148
+ endTimeUnixNano,
1149
+ ...rest
1150
+ } = span;
1151
+ const startTime = Number(BigInt(startTimeUnixNano) / 1000n);
1152
+ const endTime = Number(BigInt(endTimeUnixNano) / 1000n);
1153
+ acc.push({
1154
+ id: spanId,
1155
+ parentSpanId,
1156
+ traceId,
1157
+ name,
1158
+ scope: scope.name,
1159
+ kind,
1160
+ status: JSON.stringify(status),
1161
+ events: JSON.stringify(events),
1162
+ links: JSON.stringify(links),
1163
+ attributes: JSON.stringify(attributes.reduce((acc2, attr) => {
1164
+ const valueKey = Object.keys(attr.value)[0];
1165
+ if (valueKey) {
1166
+ acc2[attr.key] = attr.value[valueKey];
1167
+ }
1168
+ return acc2;
1169
+ }, {})),
1170
+ startTime,
1171
+ endTime,
1172
+ other: JSON.stringify(rest),
1173
+ createdAt: now
1174
+ });
1175
+ }
1176
+ return acc;
1177
+ }, []);
1178
+ return this.storage.__batchInsert({
1179
+ tableName: TABLE_TRACES,
1180
+ records: allSpans
1181
+ }).then(() => {
1182
+ items.resultCallback({
1183
+ code: core.ExportResultCode.SUCCESS
1184
+ });
1185
+ }).catch(e => {
1186
+ this.logger.error("span err:" + e?.message);
1187
+ items.resultCallback({
1188
+ code: core.ExportResultCode.FAILED,
1189
+ error: e
1190
+ });
1191
+ }).finally(() => {
1192
+ this.activeFlush = void 0;
1193
+ });
1194
+ }
1195
+ async forceFlush() {
1196
+ if (!this.queue.length) {
1197
+ return;
1198
+ }
1199
+ await this.activeFlush;
1200
+ while (this.queue.length) {
1201
+ await this.flush();
1202
+ }
1203
+ }
1204
+ __setLogger(logger) {
1205
+ this.logger = logger;
1206
+ }
1207
+ };
1208
+ var Telemetry = class _Telemetry {
1209
+ tracer = api.trace.getTracer("default");
1210
+ name = "default-service";
1211
+ constructor(config) {
1212
+ this.name = config.serviceName ?? "default-service";
1213
+ this.tracer = api.trace.getTracer(this.name);
1214
+ }
1215
+ /**
1216
+ * @deprecated This method does not do anything
1217
+ */
1218
+ async shutdown() {}
1219
+ /**
1220
+ * Initialize telemetry with the given configuration
1221
+ * @param config - Optional telemetry configuration object
1222
+ * @returns Telemetry instance that can be used for tracing
1223
+ */
1224
+ static init(config = {}) {
1225
+ try {
1226
+ if (!global.__TELEMETRY__) {
1227
+ global.__TELEMETRY__ = new _Telemetry(config);
1228
+ }
1229
+ return global.__TELEMETRY__;
1230
+ } catch (error) {
1231
+ console.error("Failed to initialize telemetry:", error);
1232
+ throw error;
1233
+ }
1234
+ }
1235
+ /**
1236
+ * Get the global telemetry instance
1237
+ * @throws {Error} If telemetry has not been initialized
1238
+ * @returns {Telemetry} The global telemetry instance
1239
+ */
1240
+ static get() {
1241
+ if (!global.__TELEMETRY__) {
1242
+ throw new Error("Telemetry not initialized");
1243
+ }
1244
+ return global.__TELEMETRY__;
1245
+ }
1246
+ /**
1247
+ * Wraps a class instance with telemetry tracing
1248
+ * @param instance The class instance to wrap
1249
+ * @param options Optional configuration for tracing
1250
+ * @returns Wrapped instance with all methods traced
1251
+ */
1252
+ traceClass(instance, options = {}) {
1253
+ const {
1254
+ skipIfNoTelemetry = true
1255
+ } = options;
1256
+ if (skipIfNoTelemetry && !hasActiveTelemetry()) {
1257
+ return instance;
1258
+ }
1259
+ const {
1260
+ spanNamePrefix = instance.constructor.name.toLowerCase(),
1261
+ attributes = {},
1262
+ excludeMethods = []
1263
+ } = options;
1264
+ return new Proxy(instance, {
1265
+ get: (target, prop) => {
1266
+ const value = target[prop];
1267
+ if (typeof value === "function" && prop !== "constructor" && !prop.toString().startsWith("_") && !excludeMethods.includes(prop.toString())) {
1268
+ return this.traceMethod(value.bind(target), {
1269
+ spanName: `${spanNamePrefix}.${prop.toString()}`,
1270
+ attributes: {
1271
+ ...attributes,
1272
+ [`${spanNamePrefix}.name`]: target.constructor.name,
1273
+ [`${spanNamePrefix}.method.name`]: prop.toString()
1274
+ }
1275
+ });
1276
+ }
1277
+ return value;
1278
+ }
1279
+ });
1280
+ }
1281
+ /**
1282
+ * method to trace individual methods with proper context
1283
+ * @param method The method to trace
1284
+ * @param context Additional context for the trace
1285
+ * @returns Wrapped method with tracing
1286
+ */
1287
+ traceMethod(method, context3) {
1288
+ let ctx = api.context.active();
1289
+ const {
1290
+ skipIfNoTelemetry = true
1291
+ } = context3;
1292
+ if (skipIfNoTelemetry && !hasActiveTelemetry()) {
1293
+ return method;
1294
+ }
1295
+ return (...args) => {
1296
+ const span = this.tracer.startSpan(context3.spanName);
1297
+ function handleError(error) {
1298
+ span.recordException(error);
1299
+ span.setStatus({
1300
+ code: api.SpanStatusCode.ERROR,
1301
+ message: error.message
1302
+ });
1303
+ span.end();
1304
+ throw error;
1305
+ }
1306
+ try {
1307
+ let recordResult2 = function (res) {
1308
+ try {
1309
+ span.setAttribute(`${context3.spanName}.result`, JSON.stringify(res));
1310
+ } catch {
1311
+ span.setAttribute(`${context3.spanName}.result`, "[Not Serializable]");
1312
+ }
1313
+ span.end();
1314
+ return res;
1315
+ };
1316
+ if (context3.attributes) {
1317
+ span.setAttributes(context3.attributes);
1318
+ }
1319
+ if (context3.attributes?.componentName) {
1320
+ ctx = api.propagation.setBaggage(ctx, {
1321
+ // @ts-ignore
1322
+ componentName: context3.attributes.componentName,
1323
+ runId: context3.attributes.runId
1324
+ });
1325
+ } else {
1326
+ const currentBaggage = api.propagation.getBaggage(ctx);
1327
+ if (currentBaggage?.componentName) {
1328
+ span.setAttribute("componentName", currentBaggage?.componentName);
1329
+ span.setAttribute("runId", currentBaggage?.runId);
1330
+ } else if (this && this.name) {
1331
+ span.setAttribute("componentName", this.name);
1332
+ span.setAttribute("runId", this.runId);
1333
+ ctx = api.propagation.setBaggage(ctx, {
1334
+ componentName: this.name,
1335
+ runId: this.runId
1336
+ });
1337
+ }
1338
+ }
1339
+ args.forEach((arg, index) => {
1340
+ try {
1341
+ span.setAttribute(`${context3.spanName}.argument.${index}`, JSON.stringify(arg));
1342
+ } catch {
1343
+ span.setAttribute(`${context3.spanName}.argument.${index}`, "[Not Serializable]");
1344
+ }
1345
+ });
1346
+ let result;
1347
+ api.context.with(api.trace.setSpan(ctx, span), () => {
1348
+ result = method(...args);
1349
+ });
1350
+ if (result instanceof Promise) {
1351
+ return result.then(recordResult2).catch(handleError);
1352
+ } else {
1353
+ return recordResult2(result);
1354
+ }
1355
+ } catch (error) {
1356
+ handleError(error);
1357
+ }
1358
+ };
1359
+ }
1360
+ getBaggageTracer() {
1361
+ return new BaggageTracer(this.tracer);
1362
+ }
1363
+ };
1364
+ var BaggageTracer = class {
1365
+ _tracer;
1366
+ constructor(tracer) {
1367
+ this._tracer = tracer;
1368
+ }
1369
+ startSpan(name, options = {}, ctx) {
1370
+ ctx = ctx ?? api.context.active();
1371
+ const span = this._tracer.startSpan(name, options, ctx);
1372
+ const currentBaggage = api.propagation.getBaggage(ctx);
1373
+ span.setAttribute("componentName", currentBaggage?.componentName);
1374
+ span.setAttribute("runId", currentBaggage?.runId);
1375
+ return span;
1376
+ }
1377
+ startActiveSpan(name, optionsOrFn, ctxOrFn, fn) {
1378
+ if (typeof optionsOrFn === "function") {
1379
+ const wrappedFn2 = span => {
1380
+ const currentBaggage = api.propagation.getBaggage(api.context.active());
1381
+ span.setAttribute("componentName", currentBaggage?.componentName);
1382
+ return optionsOrFn(span);
1383
+ };
1384
+ return this._tracer.startActiveSpan(name, {}, api.context.active(), wrappedFn2);
1385
+ }
1386
+ if (typeof ctxOrFn === "function") {
1387
+ const wrappedFn2 = span => {
1388
+ const currentBaggage = api.propagation.getBaggage(api.context.active());
1389
+ span.setAttribute("componentName", currentBaggage?.componentName);
1390
+ return ctxOrFn(span);
1391
+ };
1392
+ return this._tracer.startActiveSpan(name, optionsOrFn, api.context.active(), wrappedFn2);
1393
+ }
1394
+ const wrappedFn = span => {
1395
+ const currentBaggage = api.propagation.getBaggage(ctxOrFn ?? api.context.active());
1396
+ span.setAttribute("componentName", currentBaggage?.componentName);
1397
+ return fn(span);
1398
+ };
1399
+ return this._tracer.startActiveSpan(name, optionsOrFn, ctxOrFn, wrappedFn);
1400
+ }
1401
+ };
1402
+
1403
+ // src/mastra/index.ts
1404
+ var _Mastra_decorators, _init;
1405
+ _Mastra_decorators = [InstrumentClass({
1406
+ prefix: "mastra",
1407
+ excludeMethods: ["getLogger", "getTelemetry"]
1408
+ })];
1409
+ exports.Mastra = class Mastra {
1410
+ vectors;
1411
+ agents;
1412
+ logger;
1413
+ workflows;
1414
+ telemetry;
1415
+ tts;
1416
+ deployer;
1417
+ storage;
1418
+ memory;
1419
+ constructor(config) {
1420
+ let logger;
1421
+ if (config?.logger === false) {
1422
+ logger = noopLogger;
1423
+ } else {
1424
+ if (config?.logger) {
1425
+ logger = config.logger;
1426
+ } else {
1427
+ const levleOnEnv = process.env.NODE_ENV === "production" ? LogLevel.WARN : LogLevel.INFO;
1428
+ logger = createLogger({
1429
+ name: "Mastra",
1430
+ level: levleOnEnv
1431
+ });
1432
+ }
1433
+ }
1434
+ this.logger = logger;
1435
+ let storage = config?.storage;
1436
+ if (!storage) {
1437
+ storage = new LibSQLStore({
1438
+ config: {
1439
+ url: process.env.MASTRA_DEFAULT_STORAGE_URL || `:memory:`
1440
+ }
1441
+ });
1442
+ }
1443
+ if (storage instanceof LibSQLStore && config?.telemetry?.export?.type !== "custom") {
1444
+ const newTelemetry = {
1445
+ ...(config?.telemetry || {}),
1446
+ export: {
1447
+ type: "custom",
1448
+ exporter: new OTLPTraceExporter({
1449
+ logger: this.getLogger(),
1450
+ storage
1451
+ })
1452
+ }
1453
+ };
1454
+ this.telemetry = Telemetry.init(newTelemetry);
1455
+ } else if (config?.telemetry) {
1456
+ this.telemetry = Telemetry.init(config?.telemetry);
1457
+ }
1458
+ if (config?.deployer) {
1459
+ this.deployer = config.deployer;
1460
+ if (this.telemetry) {
1461
+ this.deployer = this.telemetry.traceClass(config.deployer, {
1462
+ excludeMethods: ["__setTelemetry", "__getTelemetry"]
1463
+ });
1464
+ this.deployer.__setTelemetry(this.telemetry);
1465
+ }
1466
+ }
1467
+ if (this.telemetry) {
1468
+ this.storage = this.telemetry.traceClass(storage, {
1469
+ excludeMethods: ["__setTelemetry", "__getTelemetry"]
1470
+ });
1471
+ this.storage.__setTelemetry(this.telemetry);
1472
+ } else {
1473
+ this.storage = storage;
1474
+ }
1475
+ if (config?.vectors) {
1476
+ let vectors = {};
1477
+ Object.entries(config.vectors).forEach(([key, vector]) => {
1478
+ if (this.telemetry) {
1479
+ vectors[key] = this.telemetry.traceClass(vector, {
1480
+ excludeMethods: ["__setTelemetry", "__getTelemetry"]
1481
+ });
1482
+ vectors[key].__setTelemetry(this.telemetry);
1483
+ } else {
1484
+ vectors[key] = vector;
1485
+ }
1486
+ });
1487
+ this.vectors = vectors;
1488
+ }
1489
+ if (config?.vectors) {
1490
+ this.vectors = config.vectors;
1491
+ }
1492
+ if (config?.memory) {
1493
+ this.memory = config.memory;
1494
+ if (this.telemetry) {
1495
+ this.memory = this.telemetry.traceClass(config.memory, {
1496
+ excludeMethods: ["__setTelemetry", "__getTelemetry"]
1497
+ });
1498
+ this.memory.__setTelemetry(this.telemetry);
1499
+ }
1500
+ }
1501
+ if (config && `memory` in config) {
1502
+ this.logger.warn(`
1503
+ Memory should be added to Agents, not to Mastra.
1504
+
1505
+ Instead of:
1506
+ new Mastra({ memory: new Memory() })
1507
+
1508
+ do:
1509
+ new Agent({ memory: new Memory() })
1510
+
1511
+ This is a warning for now, but will throw an error in the future
1512
+ `);
1513
+ }
1514
+ if (config?.tts) {
1515
+ this.tts = config.tts;
1516
+ Object.entries(this.tts).forEach(([key, ttsCl]) => {
1517
+ if (this.tts?.[key]) {
1518
+ if (this.telemetry) {
1519
+ this.tts[key] = this.telemetry.traceClass(ttsCl, {
1520
+ excludeMethods: ["__setTelemetry", "__getTelemetry"]
1521
+ });
1522
+ this.tts[key].__setTelemetry(this.telemetry);
1523
+ }
1524
+ }
1525
+ });
1526
+ }
1527
+ const agents = {};
1528
+ if (config?.agents) {
1529
+ Object.entries(config.agents).forEach(([key, agent]) => {
1530
+ if (agents[key]) {
1531
+ throw new Error(`Agent with name ID:${key} already exists`);
1532
+ }
1533
+ agent.__registerPrimitives({
1534
+ logger: this.getLogger(),
1535
+ telemetry: this.telemetry,
1536
+ storage: this.storage,
1537
+ memory: this.memory,
1538
+ agents,
1539
+ tts: this.tts,
1540
+ vectors: this.vectors
1541
+ });
1542
+ agents[key] = agent;
1543
+ });
1544
+ }
1545
+ this.agents = agents;
1546
+ this.workflows = {};
1547
+ if (config?.workflows) {
1548
+ Object.entries(config.workflows).forEach(([key, workflow]) => {
1549
+ workflow.__registerPrimitives({
1550
+ logger: this.getLogger(),
1551
+ telemetry: this.telemetry,
1552
+ storage: this.storage,
1553
+ memory: this.memory,
1554
+ agents: this.agents,
1555
+ tts: this.tts,
1556
+ vectors: this.vectors
1557
+ });
1558
+ this.workflows[key] = workflow;
1559
+ });
1560
+ }
1561
+ this.setLogger({
1562
+ logger
1563
+ });
1564
+ }
1565
+ getAgent(name) {
1566
+ const agent = this.agents?.[name];
1567
+ if (!agent) {
1568
+ throw new Error(`Agent with name ${String(name)} not found`);
1569
+ }
1570
+ return this.agents[name];
1571
+ }
1572
+ getAgents() {
1573
+ return this.agents;
1574
+ }
1575
+ getVector(name) {
1576
+ const vector = this.vectors?.[name];
1577
+ if (!vector) {
1578
+ throw new Error(`Vector with name ${String(name)} not found`);
1579
+ }
1580
+ return vector;
1581
+ }
1582
+ getVectors() {
1583
+ return this.vectors;
1584
+ }
1585
+ getDeployer() {
1586
+ return this.deployer;
1587
+ }
1588
+ getWorkflow(id, {
1589
+ serialized
1590
+ } = {}) {
1591
+ const workflow = this.workflows?.[id];
1592
+ if (!workflow) {
1593
+ throw new Error(`Workflow with ID ${String(id)} not found`);
1594
+ }
1595
+ if (serialized) {
1596
+ return {
1597
+ name: workflow.name
1598
+ };
1599
+ }
1600
+ return workflow;
1601
+ }
1602
+ getWorkflows(props = {}) {
1603
+ if (props.serialized) {
1604
+ return Object.entries(this.workflows).reduce((acc, [k, v]) => {
1605
+ return {
1606
+ ...acc,
1607
+ [k]: {
1608
+ name: v.name
1609
+ }
1610
+ };
1611
+ }, {});
1612
+ }
1613
+ return this.workflows;
1614
+ }
1615
+ setStorage(storage) {
1616
+ this.storage = storage;
1617
+ }
1618
+ setLogger({
1619
+ logger
1620
+ }) {
1621
+ this.logger = logger;
1622
+ if (this.agents) {
1623
+ Object.keys(this.agents).forEach(key => {
1624
+ this.agents?.[key]?.__setLogger(this.logger);
1625
+ });
1626
+ }
1627
+ if (this.workflows) {
1628
+ Object.keys(this.workflows).forEach(key => {
1629
+ this.workflows?.[key]?.__setLogger(this.logger);
1630
+ });
1631
+ }
1632
+ if (this.memory) {
1633
+ this.memory.__setLogger(this.logger);
1634
+ }
1635
+ if (this.deployer) {
1636
+ this.deployer.__setLogger(this.logger);
1637
+ }
1638
+ if (this.tts) {
1639
+ Object.keys(this.tts).forEach(key => {
1640
+ this.tts?.[key]?.__setLogger(this.logger);
1641
+ });
1642
+ }
1643
+ if (this.storage) {
1644
+ this.storage.__setLogger(this.logger);
1645
+ }
1646
+ if (this.vectors) {
1647
+ Object.keys(this.vectors).forEach(key => {
1648
+ this.vectors?.[key]?.__setLogger(this.logger);
1649
+ });
1650
+ }
1651
+ }
1652
+ setTelemetry(telemetry) {
1653
+ this.telemetry = Telemetry.init(telemetry);
1654
+ if (this.agents) {
1655
+ Object.keys(this.agents).forEach(key => {
1656
+ if (this.telemetry) {
1657
+ this.agents?.[key]?.__setTelemetry(this.telemetry);
1658
+ }
1659
+ });
1660
+ }
1661
+ if (this.workflows) {
1662
+ Object.keys(this.workflows).forEach(key => {
1663
+ if (this.telemetry) {
1664
+ this.workflows?.[key]?.__setTelemetry(this.telemetry);
1665
+ }
1666
+ });
1667
+ }
1668
+ if (this.memory) {
1669
+ this.memory = this.telemetry.traceClass(this.memory, {
1670
+ excludeMethods: ["__setTelemetry", "__getTelemetry"]
1671
+ });
1672
+ this.memory.__setTelemetry(this.telemetry);
1673
+ }
1674
+ if (this.deployer) {
1675
+ this.deployer = this.telemetry.traceClass(this.deployer, {
1676
+ excludeMethods: ["__setTelemetry", "__getTelemetry"]
1677
+ });
1678
+ this.deployer.__setTelemetry(this.telemetry);
1679
+ }
1680
+ if (this.tts) {
1681
+ let tts = {};
1682
+ Object.entries(this.tts).forEach(([key, ttsCl]) => {
1683
+ if (this.telemetry) {
1684
+ tts[key] = this.telemetry.traceClass(ttsCl, {
1685
+ excludeMethods: ["__setTelemetry", "__getTelemetry"]
1686
+ });
1687
+ tts[key].__setTelemetry(this.telemetry);
1688
+ }
1689
+ });
1690
+ this.tts = tts;
1691
+ }
1692
+ if (this.storage) {
1693
+ this.storage = this.telemetry.traceClass(this.storage, {
1694
+ excludeMethods: ["__setTelemetry", "__getTelemetry"]
1695
+ });
1696
+ this.storage.__setTelemetry(this.telemetry);
1697
+ }
1698
+ if (this.vectors) {
1699
+ let vectors = {};
1700
+ Object.entries(this.vectors).forEach(([key, vector]) => {
1701
+ if (this.telemetry) {
1702
+ vectors[key] = this.telemetry.traceClass(vector, {
1703
+ excludeMethods: ["__setTelemetry", "__getTelemetry"]
1704
+ });
1705
+ vectors[key].__setTelemetry(this.telemetry);
1706
+ }
1707
+ });
1708
+ this.vectors = vectors;
1709
+ }
1710
+ }
1711
+ getLogger() {
1712
+ return this.logger;
1713
+ }
1714
+ getTelemetry() {
1715
+ return this.telemetry;
1716
+ }
1717
+ async getLogsByRunId({
1718
+ runId,
1719
+ transportId
1720
+ }) {
1721
+ if (!transportId) {
1722
+ throw new Error("Transport ID is required");
1723
+ }
1724
+ return await this.logger.getLogsByRunId({
1725
+ runId,
1726
+ transportId
1727
+ });
1728
+ }
1729
+ async getLogs(transportId) {
1730
+ if (!transportId) {
1731
+ throw new Error("Transport ID is required");
1732
+ }
1733
+ return await this.logger.getLogs(transportId);
1734
+ }
1735
+ };
1736
+ exports.Mastra = /*@__PURE__*/(_ => {
1737
+ _init = __decoratorStart();
1738
+ exports.Mastra = __decorateElement(_init, 0, "Mastra", _Mastra_decorators, exports.Mastra);
1739
+ __runInitializers(_init, 1, exports.Mastra);
1740
+ return exports.Mastra;
1741
+ })();