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