@mastra/core 0.21.2-alpha.0 → 0.22.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 (181) hide show
  1. package/CHANGELOG.md +194 -0
  2. package/dist/agent/agent.d.ts +1 -0
  3. package/dist/agent/agent.d.ts.map +1 -1
  4. package/dist/agent/index.cjs +13 -13
  5. package/dist/agent/index.js +2 -2
  6. package/dist/agent/input-processor/index.cjs +6 -6
  7. package/dist/agent/input-processor/index.js +1 -1
  8. package/dist/agent/message-list/index.d.ts +14 -1
  9. package/dist/agent/message-list/index.d.ts.map +1 -1
  10. package/dist/agent/test-utils.d.ts +1 -0
  11. package/dist/agent/test-utils.d.ts.map +1 -1
  12. package/dist/agent/types.d.ts +6 -1
  13. package/dist/agent/types.d.ts.map +1 -1
  14. package/dist/agent/utils.d.ts +1 -1
  15. package/dist/agent/utils.d.ts.map +1 -1
  16. package/dist/ai-tracing/chunk-tracing.d.ts +76 -0
  17. package/dist/ai-tracing/chunk-tracing.d.ts.map +1 -0
  18. package/dist/ai-tracing/exporters/base.d.ts +111 -0
  19. package/dist/ai-tracing/exporters/base.d.ts.map +1 -0
  20. package/dist/ai-tracing/exporters/cloud.d.ts +6 -8
  21. package/dist/ai-tracing/exporters/cloud.d.ts.map +1 -1
  22. package/dist/ai-tracing/exporters/console.d.ts +6 -6
  23. package/dist/ai-tracing/exporters/console.d.ts.map +1 -1
  24. package/dist/ai-tracing/exporters/index.d.ts +1 -0
  25. package/dist/ai-tracing/exporters/index.d.ts.map +1 -1
  26. package/dist/ai-tracing/index.cjs +48 -32
  27. package/dist/ai-tracing/index.d.ts +1 -0
  28. package/dist/ai-tracing/index.d.ts.map +1 -1
  29. package/dist/ai-tracing/index.js +1 -1
  30. package/dist/ai-tracing/spans/base.d.ts +4 -1
  31. package/dist/ai-tracing/spans/base.d.ts.map +1 -1
  32. package/dist/ai-tracing/spans/default.d.ts.map +1 -1
  33. package/dist/ai-tracing/tracers/base.d.ts +15 -1
  34. package/dist/ai-tracing/tracers/base.d.ts.map +1 -1
  35. package/dist/ai-tracing/types.d.ts +85 -11
  36. package/dist/ai-tracing/types.d.ts.map +1 -1
  37. package/dist/ai-tracing/utils.d.ts +14 -0
  38. package/dist/ai-tracing/utils.d.ts.map +1 -1
  39. package/dist/{chunk-D3IOLHNB.cjs → chunk-34L2Z6PH.cjs} +12 -12
  40. package/dist/{chunk-D3IOLHNB.cjs.map → chunk-34L2Z6PH.cjs.map} +1 -1
  41. package/dist/{chunk-BLVB2IJK.js → chunk-3CVE7NQC.js} +728 -267
  42. package/dist/chunk-3CVE7NQC.js.map +1 -0
  43. package/dist/{chunk-URQI7RJ3.cjs → chunk-5GIAZ3CH.cjs} +734 -269
  44. package/dist/chunk-5GIAZ3CH.cjs.map +1 -0
  45. package/dist/{chunk-XYNSPEJO.js → chunk-5NYWRAJN.js} +3 -3
  46. package/dist/{chunk-XYNSPEJO.js.map → chunk-5NYWRAJN.js.map} +1 -1
  47. package/dist/{chunk-URVM3Y4T.cjs → chunk-634YFL42.cjs} +44 -7
  48. package/dist/chunk-634YFL42.cjs.map +1 -0
  49. package/dist/{chunk-NIESGYOH.js → chunk-A3TQYIIR.js} +1392 -1416
  50. package/dist/chunk-A3TQYIIR.js.map +1 -0
  51. package/dist/{chunk-EGNHIPGJ.cjs → chunk-A4B6IAKN.cjs} +4 -4
  52. package/dist/{chunk-EGNHIPGJ.cjs.map → chunk-A4B6IAKN.cjs.map} +1 -1
  53. package/dist/{chunk-LMP5KMU3.js → chunk-AGD5B3FB.js} +43 -6
  54. package/dist/chunk-AGD5B3FB.js.map +1 -0
  55. package/dist/{chunk-V5WDWSQ5.cjs → chunk-CAZTWPDK.cjs} +11 -11
  56. package/dist/{chunk-V5WDWSQ5.cjs.map → chunk-CAZTWPDK.cjs.map} +1 -1
  57. package/dist/{chunk-N3ZSX5OS.js → chunk-F7OMDF5K.js} +72 -36
  58. package/dist/chunk-F7OMDF5K.js.map +1 -0
  59. package/dist/{chunk-ZMPSVDDO.cjs → chunk-FMNZ3BPT.cjs} +1393 -1417
  60. package/dist/chunk-FMNZ3BPT.cjs.map +1 -0
  61. package/dist/{chunk-4ZFVJA3A.js → chunk-HZIF7HQC.js} +3 -3
  62. package/dist/{chunk-4ZFVJA3A.js.map → chunk-HZIF7HQC.js.map} +1 -1
  63. package/dist/{chunk-KLWDUSBX.js → chunk-ITFEGBP2.js} +4 -4
  64. package/dist/{chunk-KLWDUSBX.js.map → chunk-ITFEGBP2.js.map} +1 -1
  65. package/dist/{chunk-GKTRUHKB.js → chunk-KQBF5ZEN.js} +5 -5
  66. package/dist/{chunk-GKTRUHKB.js.map → chunk-KQBF5ZEN.js.map} +1 -1
  67. package/dist/{chunk-R35PINKN.js → chunk-MHICZASQ.js} +5 -5
  68. package/dist/{chunk-R35PINKN.js.map → chunk-MHICZASQ.js.map} +1 -1
  69. package/dist/{chunk-H4KO46HZ.js → chunk-MKCC5K77.js} +3 -3
  70. package/dist/{chunk-H4KO46HZ.js.map → chunk-MKCC5K77.js.map} +1 -1
  71. package/dist/{chunk-UN653TND.cjs → chunk-O4KVF3MI.cjs} +4 -4
  72. package/dist/{chunk-UN653TND.cjs.map → chunk-O4KVF3MI.cjs.map} +1 -1
  73. package/dist/{chunk-WI2YMBNG.cjs → chunk-QBPTDMR7.cjs} +102 -64
  74. package/dist/chunk-QBPTDMR7.cjs.map +1 -0
  75. package/dist/{chunk-7P5FMQQK.cjs → chunk-RWWOJXMF.cjs} +6 -6
  76. package/dist/{chunk-7P5FMQQK.cjs.map → chunk-RWWOJXMF.cjs.map} +1 -1
  77. package/dist/{chunk-XBJP7THY.js → chunk-RXBG6UV2.js} +4 -4
  78. package/dist/chunk-RXBG6UV2.js.map +1 -0
  79. package/dist/{chunk-NL3P7IFI.js → chunk-SF75RENF.js} +3 -3
  80. package/dist/{chunk-NL3P7IFI.js.map → chunk-SF75RENF.js.map} +1 -1
  81. package/dist/{chunk-SE4PA467.cjs → chunk-VF676YCO.cjs} +2 -2
  82. package/dist/chunk-VF676YCO.cjs.map +1 -0
  83. package/dist/{chunk-6OLRLZJ3.js → chunk-WM4RO23J.js} +2 -2
  84. package/dist/chunk-WM4RO23J.js.map +1 -0
  85. package/dist/{chunk-MVVMHOAC.cjs → chunk-YOVX3R5U.cjs} +14 -14
  86. package/dist/chunk-YOVX3R5U.cjs.map +1 -0
  87. package/dist/{chunk-L5A4MRCK.cjs → chunk-ZABG3SZ2.cjs} +4 -4
  88. package/dist/{chunk-L5A4MRCK.cjs.map → chunk-ZABG3SZ2.cjs.map} +1 -1
  89. package/dist/{chunk-YKVVW65D.cjs → chunk-ZDW322JC.cjs} +8 -8
  90. package/dist/{chunk-YKVVW65D.cjs.map → chunk-ZDW322JC.cjs.map} +1 -1
  91. package/dist/index.cjs +53 -53
  92. package/dist/index.js +11 -11
  93. package/dist/integration/index.cjs +3 -3
  94. package/dist/integration/index.js +1 -1
  95. package/dist/llm/index.cjs +7 -7
  96. package/dist/llm/index.js +1 -1
  97. package/dist/llm/model/model.loop.d.ts.map +1 -1
  98. package/dist/llm/model/provider-types.generated.d.ts +585 -597
  99. package/dist/loop/index.cjs +2 -2
  100. package/dist/loop/index.js +1 -1
  101. package/dist/loop/loop.d.ts.map +1 -1
  102. package/dist/loop/test-utils/mock-server-response.d.ts +7 -2
  103. package/dist/loop/test-utils/mock-server-response.d.ts.map +1 -1
  104. package/dist/loop/test-utils/options.d.ts.map +1 -1
  105. package/dist/loop/types.d.ts +2 -1
  106. package/dist/loop/types.d.ts.map +1 -1
  107. package/dist/loop/workflows/agentic-execution/llm-execution-step.d.ts.map +1 -1
  108. package/dist/loop/workflows/agentic-execution/tool-call-step.d.ts +1 -1
  109. package/dist/loop/workflows/agentic-execution/tool-call-step.d.ts.map +1 -1
  110. package/dist/mastra/index.cjs +2 -2
  111. package/dist/mastra/index.js +1 -1
  112. package/dist/memory/index.cjs +4 -4
  113. package/dist/memory/index.js +1 -1
  114. package/dist/memory/memory.d.ts +3 -2
  115. package/dist/memory/memory.d.ts.map +1 -1
  116. package/dist/processors/index.cjs +11 -11
  117. package/dist/processors/index.js +1 -1
  118. package/dist/provider-registry.json +1390 -1414
  119. package/dist/relevance/index.cjs +4 -4
  120. package/dist/relevance/index.js +1 -1
  121. package/dist/scores/index.cjs +9 -9
  122. package/dist/scores/index.js +2 -2
  123. package/dist/scores/scoreTraces/index.cjs +8 -8
  124. package/dist/scores/scoreTraces/index.js +3 -3
  125. package/dist/storage/index.cjs +3 -3
  126. package/dist/storage/index.js +1 -1
  127. package/dist/stream/RunOutput.d.ts +72 -0
  128. package/dist/stream/RunOutput.d.ts.map +1 -0
  129. package/dist/stream/aisdk/v5/output.d.ts +2 -2
  130. package/dist/stream/aisdk/v5/output.d.ts.map +1 -1
  131. package/dist/stream/base/base.d.ts +7 -0
  132. package/dist/stream/base/base.d.ts.map +1 -0
  133. package/dist/stream/base/consume-stream.d.ts +5 -0
  134. package/dist/stream/base/consume-stream.d.ts.map +1 -0
  135. package/dist/stream/base/output.d.ts.map +1 -1
  136. package/dist/stream/index.cjs +14 -10
  137. package/dist/stream/index.d.ts +2 -1
  138. package/dist/stream/index.d.ts.map +1 -1
  139. package/dist/stream/index.js +2 -2
  140. package/dist/stream/types.d.ts +1 -1
  141. package/dist/stream/types.d.ts.map +1 -1
  142. package/dist/test-utils/llm-mock.cjs +2 -2
  143. package/dist/test-utils/llm-mock.js +1 -1
  144. package/dist/tools/index.cjs +4 -4
  145. package/dist/tools/index.js +1 -1
  146. package/dist/tools/is-vercel-tool.cjs +2 -2
  147. package/dist/tools/is-vercel-tool.js +1 -1
  148. package/dist/tools/tool-builder/builder.d.ts +75 -2
  149. package/dist/tools/tool-builder/builder.d.ts.map +1 -1
  150. package/dist/tools/tool.d.ts +2 -2
  151. package/dist/tools/tool.d.ts.map +1 -1
  152. package/dist/tools/types.d.ts +17 -12
  153. package/dist/tools/types.d.ts.map +1 -1
  154. package/dist/utils.cjs +17 -17
  155. package/dist/utils.d.ts +1 -0
  156. package/dist/utils.d.ts.map +1 -1
  157. package/dist/utils.js +1 -1
  158. package/dist/workflows/evented/index.cjs +10 -10
  159. package/dist/workflows/evented/index.js +1 -1
  160. package/dist/workflows/evented/workflow.d.ts +5 -3
  161. package/dist/workflows/evented/workflow.d.ts.map +1 -1
  162. package/dist/workflows/index.cjs +12 -12
  163. package/dist/workflows/index.js +1 -1
  164. package/dist/workflows/legacy/index.cjs +22 -22
  165. package/dist/workflows/legacy/index.js +1 -1
  166. package/dist/workflows/workflow.d.ts +30 -23
  167. package/dist/workflows/workflow.d.ts.map +1 -1
  168. package/package.json +12 -10
  169. package/src/llm/model/provider-types.generated.d.ts +585 -597
  170. package/dist/chunk-6OLRLZJ3.js.map +0 -1
  171. package/dist/chunk-BLVB2IJK.js.map +0 -1
  172. package/dist/chunk-LMP5KMU3.js.map +0 -1
  173. package/dist/chunk-MVVMHOAC.cjs.map +0 -1
  174. package/dist/chunk-N3ZSX5OS.js.map +0 -1
  175. package/dist/chunk-NIESGYOH.js.map +0 -1
  176. package/dist/chunk-SE4PA467.cjs.map +0 -1
  177. package/dist/chunk-URQI7RJ3.cjs.map +0 -1
  178. package/dist/chunk-URVM3Y4T.cjs.map +0 -1
  179. package/dist/chunk-WI2YMBNG.cjs.map +0 -1
  180. package/dist/chunk-XBJP7THY.js.map +0 -1
  181. package/dist/chunk-ZMPSVDDO.cjs.map +0 -1
@@ -3,13 +3,14 @@
3
3
  var chunkGPWMM745_cjs = require('./chunk-GPWMM745.cjs');
4
4
  var chunkWM4VQWOZ_cjs = require('./chunk-WM4VQWOZ.cjs');
5
5
  var chunkLRSB62Z6_cjs = require('./chunk-LRSB62Z6.cjs');
6
- var chunkSE4PA467_cjs = require('./chunk-SE4PA467.cjs');
6
+ var chunkVF676YCO_cjs = require('./chunk-VF676YCO.cjs');
7
7
  var chunk6VOPKVYH_cjs = require('./chunk-6VOPKVYH.cjs');
8
8
  var chunkA5KDVZDL_cjs = require('./chunk-A5KDVZDL.cjs');
9
9
  var crypto$1 = require('crypto');
10
10
  var jsonSchemaToZod = require('json-schema-to-zod');
11
11
  var zod = require('zod');
12
12
  var schemaCompat = require('@mastra/schema-compat');
13
+ var web = require('stream/web');
13
14
 
14
15
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
15
16
 
@@ -20,6 +21,7 @@ var AISpanType = /* @__PURE__ */ ((AISpanType2) => {
20
21
  AISpanType2["AGENT_RUN"] = "agent_run";
21
22
  AISpanType2["GENERIC"] = "generic";
22
23
  AISpanType2["LLM_GENERATION"] = "llm_generation";
24
+ AISpanType2["LLM_STEP"] = "llm_step";
23
25
  AISpanType2["LLM_CHUNK"] = "llm_chunk";
24
26
  AISpanType2["MCP_TOOL_CALL"] = "mcp_tool_call";
25
27
  AISpanType2["PROCESSOR_RUN"] = "processor_run";
@@ -82,6 +84,7 @@ function isSpanInternal(spanType, flags) {
82
84
  return (flags & 4 /* TOOL */) !== 0;
83
85
  // LLM-related spans
84
86
  case "llm_generation" /* LLM_GENERATION */:
87
+ case "llm_step" /* LLM_STEP */:
85
88
  case "llm_chunk" /* LLM_CHUNK */:
86
89
  return (flags & 8 /* LLM */) !== 0;
87
90
  // Default: never internal
@@ -103,6 +106,9 @@ var BaseAISpan = class {
103
106
  output;
104
107
  errorInfo;
105
108
  metadata;
109
+ traceState;
110
+ /** Parent span ID (for root spans that are children of external spans) */
111
+ parentSpanId;
106
112
  constructor(options, aiTracing) {
107
113
  this.name = options.name;
108
114
  this.type = options.type;
@@ -113,6 +119,7 @@ var BaseAISpan = class {
113
119
  this.aiTracing = aiTracing;
114
120
  this.isEvent = options.isEvent ?? false;
115
121
  this.isInternal = isSpanInternal(this.type, options.tracingPolicy?.internal);
122
+ this.traceState = options.traceState;
116
123
  if (this.isEvent) {
117
124
  this.output = deepClean(options.output);
118
125
  } else {
@@ -131,7 +138,9 @@ var BaseAISpan = class {
131
138
  }
132
139
  /** Get the closest parent spanId that isn't an internal span */
133
140
  getParentSpanId(includeInternalSpans) {
134
- if (!this.parent) return void 0;
141
+ if (!this.parent) {
142
+ return this.parentSpanId;
143
+ }
135
144
  if (includeInternalSpans) return this.parent.id;
136
145
  if (this.parent.isInternal) return this.parent.getParentSpanId(includeInternalSpans);
137
146
  return this.parent.id;
@@ -215,10 +224,28 @@ var DefaultAISpan = class extends BaseAISpan {
215
224
  constructor(options, aiTracing) {
216
225
  super(options, aiTracing);
217
226
  this.id = generateSpanId();
218
- if (!options.parent) {
219
- this.traceId = generateTraceId();
220
- } else {
227
+ if (options.parent) {
221
228
  this.traceId = options.parent.traceId;
229
+ } else if (options.traceId) {
230
+ if (isValidTraceId(options.traceId)) {
231
+ this.traceId = options.traceId;
232
+ } else {
233
+ console.error(
234
+ `[Mastra Tracing] Invalid traceId: must be 1-32 hexadecimal characters, got "${options.traceId}". Generating new trace ID.`
235
+ );
236
+ this.traceId = generateTraceId();
237
+ }
238
+ } else {
239
+ this.traceId = generateTraceId();
240
+ }
241
+ if (!options.parent && options.parentSpanId) {
242
+ if (isValidSpanId(options.parentSpanId)) {
243
+ this.parentSpanId = options.parentSpanId;
244
+ } else {
245
+ console.error(
246
+ `[Mastra Tracing] Invalid parentSpanId: must be 1-16 hexadecimal characters, got "${options.parentSpanId}". Ignoring parent span ID.`
247
+ );
248
+ }
222
249
  }
223
250
  }
224
251
  end(options) {
@@ -315,6 +342,12 @@ function generateTraceId() {
315
342
  }
316
343
  return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
317
344
  }
345
+ function isValidTraceId(traceId) {
346
+ return /^[0-9a-f]{1,32}$/i.test(traceId);
347
+ }
348
+ function isValidSpanId(spanId) {
349
+ return /^[0-9a-f]{1,16}$/i.test(spanId);
350
+ }
318
351
 
319
352
  // src/ai-tracing/spans/no-op.ts
320
353
  var NoOpAISpan = class extends BaseAISpan {
@@ -336,247 +369,72 @@ var NoOpAISpan = class extends BaseAISpan {
336
369
  }
337
370
  };
338
371
 
339
- // src/ai-tracing/tracers/base.ts
340
- var BaseAITracing = class extends chunk6VOPKVYH_cjs.MastraBase {
341
- config;
342
- constructor(config) {
343
- super({ component: chunkA5KDVZDL_cjs.RegisteredLogger.AI_TRACING, name: config.serviceName });
344
- this.config = {
345
- serviceName: config.serviceName,
346
- name: config.name,
347
- sampling: config.sampling ?? { type: "always" /* ALWAYS */ },
348
- exporters: config.exporters ?? [],
349
- processors: config.processors ?? [],
350
- includeInternalSpans: config.includeInternalSpans ?? false
351
- };
352
- }
353
- /**
354
- * Override setLogger to add AI tracing specific initialization log
355
- */
356
- __setLogger(logger) {
357
- super.__setLogger(logger);
358
- this.logger.debug(
359
- `[AI Tracing] Initialized [service=${this.config.serviceName}] [instance=${this.config.name}] [sampling=${this.config.sampling.type}]`
360
- );
361
- }
362
- // ============================================================================
363
- // Protected getters for clean config access
364
- // ============================================================================
365
- get exporters() {
366
- return this.config.exporters || [];
367
- }
368
- get processors() {
369
- return this.config.processors || [];
370
- }
371
- // ============================================================================
372
- // Public API - Single type-safe span creation method
373
- // ============================================================================
374
- /**
375
- * Start a new span of a specific AISpanType
376
- */
377
- startSpan(options) {
378
- const { customSamplerOptions, ...createSpanOptions } = options;
379
- if (!this.shouldSample(customSamplerOptions)) {
380
- return new NoOpAISpan(createSpanOptions, this);
381
- }
382
- const span = this.createSpan(createSpanOptions);
383
- if (span.isEvent) {
384
- this.emitSpanEnded(span);
385
- } else {
386
- this.wireSpanLifecycle(span);
387
- this.emitSpanStarted(span);
388
- }
389
- return span;
390
- }
391
- // ============================================================================
392
- // Configuration Management
393
- // ============================================================================
394
- /**
395
- * Get current configuration
396
- */
397
- getConfig() {
398
- return { ...this.config };
399
- }
400
- // ============================================================================
401
- // Plugin Access
402
- // ============================================================================
403
- /**
404
- * Get all exporters
405
- */
406
- getExporters() {
407
- return [...this.exporters];
408
- }
372
+ // src/ai-tracing/exporters/base.ts
373
+ var BaseExporter = class {
374
+ /** Mastra logger instance */
375
+ logger;
376
+ /** Whether this exporter is disabled */
377
+ isDisabled = false;
409
378
  /**
410
- * Get all processors
379
+ * Initialize the base exporter with logger
411
380
  */
412
- getProcessors() {
413
- return [...this.processors];
381
+ constructor(config = {}) {
382
+ const logLevel = this.resolveLogLevel(config.logLevel);
383
+ this.logger = config.logger ?? new chunkA5KDVZDL_cjs.ConsoleLogger({ level: logLevel, name: this.constructor.name });
414
384
  }
415
385
  /**
416
- * Get the logger instance (for exporters and other components)
386
+ * Set the logger for the exporter (called by Mastra/AITracing during initialization)
417
387
  */
418
- getLogger() {
419
- return this.logger;
388
+ __setLogger(logger) {
389
+ this.logger = logger;
390
+ this.logger.debug(`Logger updated for exporter [name=${this.name}]`);
420
391
  }
421
- // ============================================================================
422
- // Span Lifecycle Management
423
- // ============================================================================
424
392
  /**
425
- * Automatically wires up AI tracing lifecycle events for any span
426
- * This ensures all spans emit events regardless of implementation
393
+ * Convert string log level to LogLevel enum
427
394
  */
428
- wireSpanLifecycle(span) {
429
- if (!this.config.includeInternalSpans && span.isInternal) {
430
- return;
431
- }
432
- const originalEnd = span.end.bind(span);
433
- const originalUpdate = span.update.bind(span);
434
- span.end = (options) => {
435
- if (span.isEvent) {
436
- this.logger.warn(`End event is not available on event spans`);
437
- return;
438
- }
439
- originalEnd(options);
440
- this.emitSpanEnded(span);
441
- };
442
- span.update = (options) => {
443
- if (span.isEvent) {
444
- this.logger.warn(`Update() is not available on event spans`);
445
- return;
446
- }
447
- originalUpdate(options);
448
- this.emitSpanUpdated(span);
395
+ resolveLogLevel(logLevel) {
396
+ if (!logLevel) {
397
+ return chunkA5KDVZDL_cjs.LogLevel.INFO;
398
+ }
399
+ if (typeof logLevel === "number") {
400
+ return logLevel;
401
+ }
402
+ const logLevelMap = {
403
+ debug: chunkA5KDVZDL_cjs.LogLevel.DEBUG,
404
+ info: chunkA5KDVZDL_cjs.LogLevel.INFO,
405
+ warn: chunkA5KDVZDL_cjs.LogLevel.WARN,
406
+ error: chunkA5KDVZDL_cjs.LogLevel.ERROR
449
407
  };
450
- }
451
- // ============================================================================
452
- // Utility Methods
453
- // ============================================================================
454
- /**
455
- * Check if an AI trace should be sampled
456
- */
457
- shouldSample(options) {
458
- const { sampling } = this.config;
459
- switch (sampling.type) {
460
- case "always" /* ALWAYS */:
461
- return true;
462
- case "never" /* NEVER */:
463
- return false;
464
- case "ratio" /* RATIO */:
465
- if (sampling.probability === void 0 || sampling.probability < 0 || sampling.probability > 1) {
466
- this.logger.warn(
467
- `Invalid sampling probability: ${sampling.probability}. Expected value between 0 and 1. Defaulting to no sampling.`
468
- );
469
- return false;
470
- }
471
- return Math.random() < sampling.probability;
472
- case "custom" /* CUSTOM */:
473
- return sampling.sampler(options);
474
- default:
475
- throw new Error(`Sampling strategy type not implemented: ${sampling.type}`);
476
- }
477
- }
478
- /**
479
- * Process a span through all processors
480
- */
481
- processSpan(span) {
482
- for (const processor of this.processors) {
483
- if (!span) {
484
- break;
485
- }
486
- try {
487
- span = processor.process(span);
488
- } catch (error) {
489
- this.logger.error(`[AI Tracing] Processor error [name=${processor.name}]`, error);
490
- }
491
- }
492
- return span;
493
- }
494
- // ============================================================================
495
- // Event-driven Export Methods
496
- // ============================================================================
497
- getSpanForExport(span) {
498
- if (!span.isValid) return void 0;
499
- if (span.isInternal && !this.config.includeInternalSpans) return void 0;
500
- const processedSpan = this.processSpan(span);
501
- return processedSpan?.exportSpan(this.config.includeInternalSpans);
502
- }
503
- /**
504
- * Emit a span started event
505
- */
506
- emitSpanStarted(span) {
507
- const exportedSpan = this.getSpanForExport(span);
508
- if (exportedSpan) {
509
- this.exportEvent({ type: "span_started" /* SPAN_STARTED */, exportedSpan }).catch((error) => {
510
- this.logger.error("[AI Tracing] Failed to export span_started event", error);
511
- });
512
- }
513
- }
514
- /**
515
- * Emit a span ended event (called automatically when spans end)
516
- */
517
- emitSpanEnded(span) {
518
- const exportedSpan = this.getSpanForExport(span);
519
- if (exportedSpan) {
520
- this.exportEvent({ type: "span_ended" /* SPAN_ENDED */, exportedSpan }).catch((error) => {
521
- this.logger.error("[AI Tracing] Failed to export span_ended event", error);
522
- });
523
- }
408
+ return logLevelMap[logLevel] ?? chunkA5KDVZDL_cjs.LogLevel.INFO;
524
409
  }
525
410
  /**
526
- * Emit a span updated event
411
+ * Mark the exporter as disabled and log a message
412
+ *
413
+ * @param reason - Reason why the exporter is disabled
527
414
  */
528
- emitSpanUpdated(span) {
529
- const exportedSpan = this.getSpanForExport(span);
530
- if (exportedSpan) {
531
- this.exportEvent({ type: "span_updated" /* SPAN_UPDATED */, exportedSpan }).catch((error) => {
532
- this.logger.error("[AI Tracing] Failed to export span_updated event", error);
533
- });
534
- }
415
+ setDisabled(reason) {
416
+ this.isDisabled = true;
417
+ this.logger.warn(`${this.name} disabled: ${reason}`);
535
418
  }
536
419
  /**
537
- * Export tracing event through all exporters (realtime mode)
420
+ * Export a tracing event
421
+ *
422
+ * This method checks if the exporter is disabled before calling _exportEvent.
423
+ * Subclasses should implement _exportEvent instead of overriding this method.
538
424
  */
539
425
  async exportEvent(event) {
540
- const exportPromises = this.exporters.map(async (exporter) => {
541
- try {
542
- if (exporter.exportEvent) {
543
- await exporter.exportEvent(event);
544
- this.logger.debug(`[AI Tracing] Event exported [exporter=${exporter.name}] [type=${event.type}]`);
545
- }
546
- } catch (error) {
547
- this.logger.error(`[AI Tracing] Export error [exporter=${exporter.name}]`, error);
548
- }
549
- });
550
- await Promise.allSettled(exportPromises);
551
- }
552
- // ============================================================================
553
- // Lifecycle Management
554
- // ============================================================================
555
- /**
556
- * Initialize AI tracing (called by Mastra during component registration)
557
- */
558
- init() {
559
- this.logger.debug(`[AI Tracing] Initialization started [name=${this.name}]`);
560
- this.logger.info(`[AI Tracing] Initialized successfully [name=${this.name}]`);
426
+ if (this.isDisabled) {
427
+ return;
428
+ }
429
+ await this._exportEvent(event);
561
430
  }
562
431
  /**
563
- * Shutdown AI tracing and clean up resources
432
+ * Shutdown the exporter and clean up resources
433
+ *
434
+ * Default implementation just logs. Override to add custom cleanup.
564
435
  */
565
436
  async shutdown() {
566
- this.logger.debug(`[AI Tracing] Shutdown started [name=${this.name}]`);
567
- const shutdownPromises = [...this.exporters.map((e) => e.shutdown()), ...this.processors.map((p) => p.shutdown())];
568
- await Promise.allSettled(shutdownPromises);
569
- this.logger.info(`[AI Tracing] Shutdown completed [name=${this.name}]`);
570
- }
571
- };
572
-
573
- // src/ai-tracing/tracers/default.ts
574
- var DefaultAITracing = class extends BaseAITracing {
575
- constructor(config) {
576
- super(config);
577
- }
578
- createSpan(options) {
579
- return new DefaultAISpan(options, this);
437
+ this.logger.info(`${this.name} shutdown complete`);
580
438
  }
581
439
  };
582
440
  var CoreToolBuilder = class extends chunk6VOPKVYH_cjs.MastraBase {
@@ -591,13 +449,27 @@ var CoreToolBuilder = class extends chunk6VOPKVYH_cjs.MastraBase {
591
449
  }
592
450
  // Helper to get parameters based on tool type
593
451
  getParameters = () => {
594
- if (chunkSE4PA467_cjs.isVercelTool(this.originalTool)) {
595
- return this.originalTool.parameters ?? zod.z.object({});
452
+ if (chunkVF676YCO_cjs.isVercelTool(this.originalTool)) {
453
+ let schema2 = this.originalTool.parameters ?? ("inputSchema" in this.originalTool ? this.originalTool.inputSchema : void 0) ?? zod.z.object({});
454
+ if (typeof schema2 === "function") {
455
+ schema2 = schema2();
456
+ }
457
+ return schema2;
596
458
  }
597
- return this.originalTool.inputSchema ?? zod.z.object({});
459
+ let schema = this.originalTool.inputSchema ?? zod.z.object({});
460
+ if (typeof schema === "function") {
461
+ schema = schema();
462
+ }
463
+ return schema;
598
464
  };
599
465
  getOutputSchema = () => {
600
- if ("outputSchema" in this.originalTool) return this.originalTool.outputSchema;
466
+ if ("outputSchema" in this.originalTool) {
467
+ let schema = this.originalTool.outputSchema;
468
+ if (typeof schema === "function") {
469
+ schema = schema();
470
+ }
471
+ return schema;
472
+ }
601
473
  return null;
602
474
  };
603
475
  // For provider-defined tools, we need to include all required properties
@@ -610,8 +482,8 @@ var CoreToolBuilder = class extends chunk6VOPKVYH_cjs.MastraBase {
610
482
  id: tool.id,
611
483
  args: "args" in this.originalTool ? this.originalTool.args : {},
612
484
  description: tool.description,
613
- parameters: schemaCompat.convertZodSchemaToAISDKSchema(parameters),
614
- ...outputSchema ? { outputSchema: schemaCompat.convertZodSchemaToAISDKSchema(outputSchema) } : {},
485
+ parameters: parameters.jsonSchema ? parameters : schemaCompat.convertZodSchemaToAISDKSchema(parameters),
486
+ ...outputSchema ? { outputSchema: outputSchema.jsonSchema ? outputSchema : schemaCompat.convertZodSchemaToAISDKSchema(outputSchema) } : {},
615
487
  execute: this.originalTool.execute ? this.createExecute(
616
488
  this.originalTool,
617
489
  { ...this.options, description: this.originalTool.description },
@@ -648,7 +520,8 @@ var CoreToolBuilder = class extends chunk6VOPKVYH_cjs.MastraBase {
648
520
  type: logType
649
521
  });
650
522
  const execFunction = async (args, execOptions) => {
651
- const toolSpan = options.tracingContext?.currentSpan?.createChildSpan({
523
+ const tracingContext = execOptions.tracingContext || options.tracingContext;
524
+ const toolSpan = tracingContext?.currentSpan?.createChildSpan({
652
525
  type: "tool_call" /* TOOL_CALL */,
653
526
  name: `tool: '${options.name}'`,
654
527
  input: args,
@@ -661,7 +534,7 @@ var CoreToolBuilder = class extends chunk6VOPKVYH_cjs.MastraBase {
661
534
  });
662
535
  try {
663
536
  let result;
664
- if (chunkSE4PA467_cjs.isVercelTool(tool)) {
537
+ if (chunkVF676YCO_cjs.isVercelTool(tool)) {
665
538
  result = await tool?.execute?.(args, execOptions);
666
539
  } else {
667
540
  const wrappedMastra = options.mastra ? wrapMastra(options.mastra, { currentSpan: toolSpan }) : options.mastra;
@@ -700,7 +573,7 @@ var CoreToolBuilder = class extends chunk6VOPKVYH_cjs.MastraBase {
700
573
  try {
701
574
  logger2.debug(start, { ...rest, model: logModelObject, args });
702
575
  const parameters = this.getParameters();
703
- const { data, error: error2 } = chunkSE4PA467_cjs.validateToolInput(parameters, args, options.name);
576
+ const { data, error: error2 } = chunkVF676YCO_cjs.validateToolInput(parameters, args, options.name);
704
577
  if (error2) {
705
578
  logger2.warn(`Tool input validation failed for '${options.name}'`, {
706
579
  toolName: options.name,
@@ -745,13 +618,25 @@ var CoreToolBuilder = class extends chunk6VOPKVYH_cjs.MastraBase {
745
618
  if (!builtTool.parameters) {
746
619
  throw new Error("Tool parameters are required");
747
620
  }
748
- return {
621
+ const base = {
749
622
  ...builtTool,
750
623
  inputSchema: builtTool.parameters,
751
624
  onInputStart: "onInputStart" in this.originalTool ? this.originalTool.onInputStart : void 0,
752
625
  onInputDelta: "onInputDelta" in this.originalTool ? this.originalTool.onInputDelta : void 0,
753
626
  onInputAvailable: "onInputAvailable" in this.originalTool ? this.originalTool.onInputAvailable : void 0
754
627
  };
628
+ if (builtTool.type === "provider-defined") {
629
+ const { execute, parameters, ...rest } = base;
630
+ const name = builtTool.id.split(".")[1] || builtTool.id;
631
+ return {
632
+ ...rest,
633
+ type: builtTool.type,
634
+ id: builtTool.id,
635
+ name,
636
+ args: builtTool.args
637
+ };
638
+ }
639
+ return base;
755
640
  }
756
641
  build() {
757
642
  const providerTool = this.buildProviderTool(this.originalTool);
@@ -932,7 +817,7 @@ function createDeterministicId(input) {
932
817
  return crypto$1.createHash("sha256").update(input).digest("hex").slice(0, 8);
933
818
  }
934
819
  function setVercelToolProperties(tool) {
935
- const inputSchema = convertVercelToolParameters(tool);
820
+ const inputSchema = "inputSchema" in tool ? tool.inputSchema : convertVercelToolParameters(tool);
936
821
  const toolId = !("id" in tool) ? tool.description ? `tool-${createDeterministicId(tool.description)}` : `tool-${Math.random().toString(36).substring(2, 9)}` : tool.id;
937
822
  return {
938
823
  ...tool,
@@ -944,7 +829,7 @@ function ensureToolProperties(tools) {
944
829
  const toolsWithProperties = Object.keys(tools).reduce((acc, key) => {
945
830
  const tool = tools?.[key];
946
831
  if (tool) {
947
- if (chunkSE4PA467_cjs.isVercelTool(tool)) {
832
+ if (chunkVF676YCO_cjs.isVercelTool(tool)) {
948
833
  acc[key] = setVercelToolProperties(tool);
949
834
  } else {
950
835
  acc[key] = tool;
@@ -955,7 +840,10 @@ function ensureToolProperties(tools) {
955
840
  return toolsWithProperties;
956
841
  }
957
842
  function convertVercelToolParameters(tool) {
958
- const schema = tool.parameters ?? zod.z.object({});
843
+ let schema = tool.parameters ?? zod.z.object({});
844
+ if (typeof schema === "function") {
845
+ schema = schema();
846
+ }
959
847
  return isZodType(schema) ? schema : resolveSerializedZodOutput(jsonSchemaToZod__default.default(schema));
960
848
  }
961
849
  function makeCoreTool(originalTool, options, logType) {
@@ -1100,42 +988,36 @@ async function fetchWithRetry(url, options = {}, maxRetries = 3) {
1100
988
  }
1101
989
 
1102
990
  // src/ai-tracing/exporters/cloud.ts
1103
- var CloudExporter = class {
991
+ var CloudExporter = class extends BaseExporter {
1104
992
  name = "mastra-cloud-ai-tracing-exporter";
1105
993
  config;
1106
994
  buffer;
1107
995
  flushTimer = null;
1108
- logger;
1109
- isDisabled = false;
1110
996
  constructor(config = {}) {
1111
- this.logger = config.logger ?? new chunkA5KDVZDL_cjs.ConsoleLogger({ level: chunkA5KDVZDL_cjs.LogLevel.INFO });
997
+ super(config);
1112
998
  const accessToken = config.accessToken ?? process.env.MASTRA_CLOUD_ACCESS_TOKEN;
1113
999
  if (!accessToken) {
1114
- this.logger.debug(
1115
- "CloudExporter disabled: MASTRA_CLOUD_ACCESS_TOKEN environment variable not set. \u{1F680} Sign up for Mastra Cloud at https://cloud.mastra.ai to see your AI traces online and obtain your access token."
1000
+ this.setDisabled(
1001
+ "MASTRA_CLOUD_ACCESS_TOKEN environment variable not set. \u{1F680} Sign up for Mastra Cloud at https://cloud.mastra.ai to see your AI traces online and obtain your access token."
1116
1002
  );
1117
- this.isDisabled = true;
1118
1003
  }
1119
1004
  const endpoint = config.endpoint ?? process.env.MASTRA_CLOUD_AI_TRACES_ENDPOINT ?? "https://api.mastra.ai/ai/spans/publish";
1120
1005
  this.config = {
1006
+ logger: this.logger,
1007
+ logLevel: config.logLevel ?? chunkA5KDVZDL_cjs.LogLevel.INFO,
1121
1008
  maxBatchSize: config.maxBatchSize ?? 1e3,
1122
1009
  maxBatchWaitMs: config.maxBatchWaitMs ?? 5e3,
1123
1010
  maxRetries: config.maxRetries ?? 3,
1124
1011
  accessToken: accessToken || "",
1125
- // Empty string if no token
1126
- endpoint,
1127
- logger: this.logger
1012
+ endpoint
1128
1013
  };
1129
1014
  this.buffer = {
1130
1015
  spans: [],
1131
1016
  totalSize: 0
1132
1017
  };
1133
1018
  }
1134
- async exportEvent(event) {
1135
- if (this.isDisabled) {
1136
- return;
1137
- }
1138
- if (event.type !== "span_ended" /* SPAN_ENDED */) {
1019
+ async _exportEvent(event) {
1020
+ if (event.type !== "span_ended" /* SPAN_ENDED */) {
1139
1021
  return;
1140
1022
  }
1141
1023
  this.addToBuffer(event);
@@ -1248,7 +1130,6 @@ var CloudExporter = class {
1248
1130
  * Uploads spans to cloud API using fetchWithRetry for all retry logic
1249
1131
  */
1250
1132
  async batchUpload(spans) {
1251
- const url = `${this.config.endpoint}`;
1252
1133
  const headers = {
1253
1134
  Authorization: `Bearer ${this.config.accessToken}`,
1254
1135
  "Content-Type": "application/json"
@@ -1258,7 +1139,7 @@ var CloudExporter = class {
1258
1139
  headers,
1259
1140
  body: JSON.stringify({ spans })
1260
1141
  };
1261
- await fetchWithRetry(url, options, this.config.maxRetries);
1142
+ await fetchWithRetry(this.config.endpoint, options, this.config.maxRetries);
1262
1143
  }
1263
1144
  resetBuffer() {
1264
1145
  this.buffer.spans = [];
@@ -1300,17 +1181,12 @@ var CloudExporter = class {
1300
1181
  };
1301
1182
 
1302
1183
  // src/ai-tracing/exporters/console.ts
1303
- var ConsoleExporter = class {
1184
+ var ConsoleExporter = class extends BaseExporter {
1304
1185
  name = "tracing-console-exporter";
1305
- logger;
1306
- constructor(logger) {
1307
- if (logger) {
1308
- this.logger = logger;
1309
- } else {
1310
- this.logger = new chunkA5KDVZDL_cjs.ConsoleLogger({ level: chunkA5KDVZDL_cjs.LogLevel.INFO });
1311
- }
1186
+ constructor(config = {}) {
1187
+ super(config);
1312
1188
  }
1313
- async exportEvent(event) {
1189
+ async _exportEvent(event) {
1314
1190
  const span = event.exportedSpan;
1315
1191
  const formatAttributes = (attributes) => {
1316
1192
  try {
@@ -2197,10 +2073,10 @@ function getValidTraceId(span) {
2197
2073
  return span?.isValid ? span.traceId : void 0;
2198
2074
  }
2199
2075
  function getOrCreateSpan(options) {
2200
- const { type, attributes, tracingContext, runtimeContext, ...rest } = options;
2076
+ const { type, attributes, tracingContext, runtimeContext, tracingOptions, ...rest } = options;
2201
2077
  const metadata = {
2202
2078
  ...rest.metadata ?? {},
2203
- ...rest.tracingOptions?.metadata ?? {}
2079
+ ...tracingOptions?.metadata ?? {}
2204
2080
  };
2205
2081
  if (tracingContext?.currentSpan) {
2206
2082
  return tracingContext.currentSpan.createChildSpan({
@@ -2218,6 +2094,10 @@ function getOrCreateSpan(options) {
2218
2094
  attributes,
2219
2095
  ...rest,
2220
2096
  metadata,
2097
+ runtimeContext,
2098
+ tracingOptions,
2099
+ traceId: tracingOptions?.traceId,
2100
+ parentSpanId: tracingOptions?.parentSpanId,
2221
2101
  customSamplerOptions: {
2222
2102
  runtimeContext,
2223
2103
  metadata
@@ -2225,6 +2105,322 @@ function getOrCreateSpan(options) {
2225
2105
  });
2226
2106
  }
2227
2107
 
2108
+ // src/ai-tracing/tracers/base.ts
2109
+ var BaseAITracing = class extends chunk6VOPKVYH_cjs.MastraBase {
2110
+ config;
2111
+ constructor(config) {
2112
+ super({ component: chunkA5KDVZDL_cjs.RegisteredLogger.AI_TRACING, name: config.serviceName });
2113
+ this.config = {
2114
+ serviceName: config.serviceName,
2115
+ name: config.name,
2116
+ sampling: config.sampling ?? { type: "always" /* ALWAYS */ },
2117
+ exporters: config.exporters ?? [],
2118
+ processors: config.processors ?? [],
2119
+ includeInternalSpans: config.includeInternalSpans ?? false,
2120
+ runtimeContextKeys: config.runtimeContextKeys ?? []
2121
+ };
2122
+ }
2123
+ /**
2124
+ * Override setLogger to add AI tracing specific initialization log
2125
+ * and propagate logger to exporters
2126
+ */
2127
+ __setLogger(logger) {
2128
+ super.__setLogger(logger);
2129
+ this.exporters.forEach((exporter) => {
2130
+ if (typeof exporter.__setLogger === "function") {
2131
+ exporter.__setLogger(logger);
2132
+ }
2133
+ });
2134
+ this.logger.debug(
2135
+ `[AI Tracing] Initialized [service=${this.config.serviceName}] [instance=${this.config.name}] [sampling=${this.config.sampling.type}]`
2136
+ );
2137
+ }
2138
+ // ============================================================================
2139
+ // Protected getters for clean config access
2140
+ // ============================================================================
2141
+ get exporters() {
2142
+ return this.config.exporters || [];
2143
+ }
2144
+ get processors() {
2145
+ return this.config.processors || [];
2146
+ }
2147
+ // ============================================================================
2148
+ // Public API - Single type-safe span creation method
2149
+ // ============================================================================
2150
+ /**
2151
+ * Start a new span of a specific AISpanType
2152
+ */
2153
+ startSpan(options) {
2154
+ const { customSamplerOptions, runtimeContext, metadata, tracingOptions, ...rest } = options;
2155
+ if (!this.shouldSample(customSamplerOptions)) {
2156
+ return new NoOpAISpan({ ...rest, metadata }, this);
2157
+ }
2158
+ let traceState;
2159
+ if (options.parent) {
2160
+ traceState = options.parent.traceState;
2161
+ } else {
2162
+ traceState = this.computeTraceState(tracingOptions);
2163
+ }
2164
+ const enrichedMetadata = this.extractMetadataFromRuntimeContext(runtimeContext, metadata, traceState);
2165
+ const span = this.createSpan({
2166
+ ...rest,
2167
+ metadata: enrichedMetadata,
2168
+ traceState
2169
+ });
2170
+ if (span.isEvent) {
2171
+ this.emitSpanEnded(span);
2172
+ } else {
2173
+ this.wireSpanLifecycle(span);
2174
+ this.emitSpanStarted(span);
2175
+ }
2176
+ return span;
2177
+ }
2178
+ // ============================================================================
2179
+ // Configuration Management
2180
+ // ============================================================================
2181
+ /**
2182
+ * Get current configuration
2183
+ */
2184
+ getConfig() {
2185
+ return { ...this.config };
2186
+ }
2187
+ // ============================================================================
2188
+ // Plugin Access
2189
+ // ============================================================================
2190
+ /**
2191
+ * Get all exporters
2192
+ */
2193
+ getExporters() {
2194
+ return [...this.exporters];
2195
+ }
2196
+ /**
2197
+ * Get all processors
2198
+ */
2199
+ getProcessors() {
2200
+ return [...this.processors];
2201
+ }
2202
+ /**
2203
+ * Get the logger instance (for exporters and other components)
2204
+ */
2205
+ getLogger() {
2206
+ return this.logger;
2207
+ }
2208
+ // ============================================================================
2209
+ // Span Lifecycle Management
2210
+ // ============================================================================
2211
+ /**
2212
+ * Automatically wires up AI tracing lifecycle events for any span
2213
+ * This ensures all spans emit events regardless of implementation
2214
+ */
2215
+ wireSpanLifecycle(span) {
2216
+ if (!this.config.includeInternalSpans && span.isInternal) {
2217
+ return;
2218
+ }
2219
+ const originalEnd = span.end.bind(span);
2220
+ const originalUpdate = span.update.bind(span);
2221
+ span.end = (options) => {
2222
+ if (span.isEvent) {
2223
+ this.logger.warn(`End event is not available on event spans`);
2224
+ return;
2225
+ }
2226
+ originalEnd(options);
2227
+ this.emitSpanEnded(span);
2228
+ };
2229
+ span.update = (options) => {
2230
+ if (span.isEvent) {
2231
+ this.logger.warn(`Update() is not available on event spans`);
2232
+ return;
2233
+ }
2234
+ originalUpdate(options);
2235
+ this.emitSpanUpdated(span);
2236
+ };
2237
+ }
2238
+ // ============================================================================
2239
+ // Utility Methods
2240
+ // ============================================================================
2241
+ /**
2242
+ * Check if an AI trace should be sampled
2243
+ */
2244
+ shouldSample(options) {
2245
+ const { sampling } = this.config;
2246
+ switch (sampling.type) {
2247
+ case "always" /* ALWAYS */:
2248
+ return true;
2249
+ case "never" /* NEVER */:
2250
+ return false;
2251
+ case "ratio" /* RATIO */:
2252
+ if (sampling.probability === void 0 || sampling.probability < 0 || sampling.probability > 1) {
2253
+ this.logger.warn(
2254
+ `Invalid sampling probability: ${sampling.probability}. Expected value between 0 and 1. Defaulting to no sampling.`
2255
+ );
2256
+ return false;
2257
+ }
2258
+ return Math.random() < sampling.probability;
2259
+ case "custom" /* CUSTOM */:
2260
+ return sampling.sampler(options);
2261
+ default:
2262
+ throw new Error(`Sampling strategy type not implemented: ${sampling.type}`);
2263
+ }
2264
+ }
2265
+ /**
2266
+ * Compute TraceState for a new trace based on configured and per-request keys
2267
+ */
2268
+ computeTraceState(tracingOptions) {
2269
+ const configuredKeys = this.config.runtimeContextKeys ?? [];
2270
+ const additionalKeys = tracingOptions?.runtimeContextKeys ?? [];
2271
+ const allKeys = [...configuredKeys, ...additionalKeys];
2272
+ if (allKeys.length === 0) {
2273
+ return void 0;
2274
+ }
2275
+ return {
2276
+ runtimeContextKeys: allKeys
2277
+ };
2278
+ }
2279
+ /**
2280
+ * Extract metadata from RuntimeContext using TraceState
2281
+ */
2282
+ extractMetadataFromRuntimeContext(runtimeContext, explicitMetadata, traceState) {
2283
+ if (!runtimeContext || !traceState || traceState.runtimeContextKeys.length === 0) {
2284
+ return explicitMetadata;
2285
+ }
2286
+ const extracted = this.extractKeys(runtimeContext, traceState.runtimeContextKeys);
2287
+ if (Object.keys(extracted).length === 0 && !explicitMetadata) {
2288
+ return void 0;
2289
+ }
2290
+ return {
2291
+ ...extracted,
2292
+ ...explicitMetadata
2293
+ // Explicit metadata always wins
2294
+ };
2295
+ }
2296
+ /**
2297
+ * Extract specific keys from RuntimeContext
2298
+ */
2299
+ extractKeys(runtimeContext, keys) {
2300
+ const result = {};
2301
+ for (const key of keys) {
2302
+ const parts = key.split(".");
2303
+ const rootKey = parts[0];
2304
+ const value = runtimeContext.get(rootKey);
2305
+ if (value !== void 0) {
2306
+ if (parts.length > 1) {
2307
+ const nestedPath = parts.slice(1).join(".");
2308
+ const nestedValue = getNestedValue(value, nestedPath);
2309
+ if (nestedValue !== void 0) {
2310
+ setNestedValue(result, key, nestedValue);
2311
+ }
2312
+ } else {
2313
+ setNestedValue(result, key, value);
2314
+ }
2315
+ }
2316
+ }
2317
+ return result;
2318
+ }
2319
+ /**
2320
+ * Process a span through all processors
2321
+ */
2322
+ processSpan(span) {
2323
+ for (const processor of this.processors) {
2324
+ if (!span) {
2325
+ break;
2326
+ }
2327
+ try {
2328
+ span = processor.process(span);
2329
+ } catch (error) {
2330
+ this.logger.error(`[AI Tracing] Processor error [name=${processor.name}]`, error);
2331
+ }
2332
+ }
2333
+ return span;
2334
+ }
2335
+ // ============================================================================
2336
+ // Event-driven Export Methods
2337
+ // ============================================================================
2338
+ getSpanForExport(span) {
2339
+ if (!span.isValid) return void 0;
2340
+ if (span.isInternal && !this.config.includeInternalSpans) return void 0;
2341
+ const processedSpan = this.processSpan(span);
2342
+ return processedSpan?.exportSpan(this.config.includeInternalSpans);
2343
+ }
2344
+ /**
2345
+ * Emit a span started event
2346
+ */
2347
+ emitSpanStarted(span) {
2348
+ const exportedSpan = this.getSpanForExport(span);
2349
+ if (exportedSpan) {
2350
+ this.exportEvent({ type: "span_started" /* SPAN_STARTED */, exportedSpan }).catch((error) => {
2351
+ this.logger.error("[AI Tracing] Failed to export span_started event", error);
2352
+ });
2353
+ }
2354
+ }
2355
+ /**
2356
+ * Emit a span ended event (called automatically when spans end)
2357
+ */
2358
+ emitSpanEnded(span) {
2359
+ const exportedSpan = this.getSpanForExport(span);
2360
+ if (exportedSpan) {
2361
+ this.exportEvent({ type: "span_ended" /* SPAN_ENDED */, exportedSpan }).catch((error) => {
2362
+ this.logger.error("[AI Tracing] Failed to export span_ended event", error);
2363
+ });
2364
+ }
2365
+ }
2366
+ /**
2367
+ * Emit a span updated event
2368
+ */
2369
+ emitSpanUpdated(span) {
2370
+ const exportedSpan = this.getSpanForExport(span);
2371
+ if (exportedSpan) {
2372
+ this.exportEvent({ type: "span_updated" /* SPAN_UPDATED */, exportedSpan }).catch((error) => {
2373
+ this.logger.error("[AI Tracing] Failed to export span_updated event", error);
2374
+ });
2375
+ }
2376
+ }
2377
+ /**
2378
+ * Export tracing event through all exporters (realtime mode)
2379
+ */
2380
+ async exportEvent(event) {
2381
+ const exportPromises = this.exporters.map(async (exporter) => {
2382
+ try {
2383
+ if (exporter.exportEvent) {
2384
+ await exporter.exportEvent(event);
2385
+ this.logger.debug(`[AI Tracing] Event exported [exporter=${exporter.name}] [type=${event.type}]`);
2386
+ }
2387
+ } catch (error) {
2388
+ this.logger.error(`[AI Tracing] Export error [exporter=${exporter.name}]`, error);
2389
+ }
2390
+ });
2391
+ await Promise.allSettled(exportPromises);
2392
+ }
2393
+ // ============================================================================
2394
+ // Lifecycle Management
2395
+ // ============================================================================
2396
+ /**
2397
+ * Initialize AI tracing (called by Mastra during component registration)
2398
+ */
2399
+ init() {
2400
+ this.logger.debug(`[AI Tracing] Initialization started [name=${this.name}]`);
2401
+ this.logger.info(`[AI Tracing] Initialized successfully [name=${this.name}]`);
2402
+ }
2403
+ /**
2404
+ * Shutdown AI tracing and clean up resources
2405
+ */
2406
+ async shutdown() {
2407
+ this.logger.debug(`[AI Tracing] Shutdown started [name=${this.name}]`);
2408
+ const shutdownPromises = [...this.exporters.map((e) => e.shutdown()), ...this.processors.map((p) => p.shutdown())];
2409
+ await Promise.allSettled(shutdownPromises);
2410
+ this.logger.info(`[AI Tracing] Shutdown completed [name=${this.name}]`);
2411
+ }
2412
+ };
2413
+
2414
+ // src/ai-tracing/tracers/default.ts
2415
+ var DefaultAITracing = class extends BaseAITracing {
2416
+ constructor(config) {
2417
+ super(config);
2418
+ }
2419
+ createSpan(options) {
2420
+ return new DefaultAISpan(options, this);
2421
+ }
2422
+ };
2423
+
2228
2424
  // src/ai-tracing/context.ts
2229
2425
  var AGENT_GETTERS = ["getAgent", "getAgentById"];
2230
2426
  var AGENT_METHODS_TO_WRAP = ["generate", "stream", "generateLegacy", "streamLegacy"];
@@ -2371,17 +2567,284 @@ function wrapRun(run, tracingContext) {
2371
2567
  return run;
2372
2568
  }
2373
2569
  }
2570
+ var ModelSpanTracker = class {
2571
+ modelSpan;
2572
+ currentStepSpan;
2573
+ currentChunkSpan;
2574
+ accumulator = {};
2575
+ stepIndex = 0;
2576
+ chunkSequence = 0;
2577
+ constructor(modelSpan) {
2578
+ this.modelSpan = modelSpan;
2579
+ }
2580
+ /**
2581
+ * Start a new Model execution step
2582
+ */
2583
+ startStepSpan(payload) {
2584
+ this.currentStepSpan = this.modelSpan?.createChildSpan({
2585
+ name: `step: ${this.stepIndex}`,
2586
+ type: "llm_step" /* LLM_STEP */,
2587
+ attributes: {
2588
+ stepIndex: this.stepIndex,
2589
+ ...payload?.messageId ? { messageId: payload.messageId } : {},
2590
+ ...payload?.warnings?.length ? { warnings: payload.warnings } : {}
2591
+ },
2592
+ input: payload?.request
2593
+ });
2594
+ this.chunkSequence = 0;
2595
+ }
2596
+ /**
2597
+ * End the current Model execution step with token usage, finish reason, output, and metadata
2598
+ */
2599
+ endStepSpan(payload) {
2600
+ if (!this.currentStepSpan) return;
2601
+ const output = payload.output;
2602
+ const { usage, ...otherOutput } = output;
2603
+ const stepResult = payload.stepResult;
2604
+ const metadata = payload.metadata;
2605
+ const cleanMetadata = metadata ? { ...metadata } : void 0;
2606
+ if (cleanMetadata?.request) {
2607
+ delete cleanMetadata.request;
2608
+ }
2609
+ this.currentStepSpan.end({
2610
+ output: otherOutput,
2611
+ attributes: {
2612
+ usage,
2613
+ isContinued: stepResult.isContinued,
2614
+ finishReason: stepResult.reason,
2615
+ warnings: stepResult.warnings
2616
+ },
2617
+ metadata: {
2618
+ ...cleanMetadata
2619
+ }
2620
+ });
2621
+ this.currentStepSpan = void 0;
2622
+ this.stepIndex++;
2623
+ }
2624
+ /**
2625
+ * Create a new chunk span (for multi-part chunks like text-start/delta/end)
2626
+ */
2627
+ startChunkSpan(chunkType, initialData) {
2628
+ if (!this.currentStepSpan) {
2629
+ this.startStepSpan();
2630
+ }
2631
+ this.currentChunkSpan = this.currentStepSpan?.createChildSpan({
2632
+ name: `chunk: '${chunkType}'`,
2633
+ type: "llm_chunk" /* LLM_CHUNK */,
2634
+ attributes: {
2635
+ chunkType,
2636
+ sequenceNumber: this.chunkSequence
2637
+ }
2638
+ });
2639
+ this.accumulator = initialData || {};
2640
+ }
2641
+ /**
2642
+ * Append string content to a specific field in the accumulator
2643
+ */
2644
+ appendToAccumulator(field, text) {
2645
+ if (this.accumulator[field] === void 0) {
2646
+ this.accumulator[field] = text;
2647
+ } else {
2648
+ this.accumulator[field] += text;
2649
+ }
2650
+ }
2651
+ /**
2652
+ * End the current chunk span.
2653
+ * Safe to call multiple times - will no-op if span already ended.
2654
+ */
2655
+ endChunkSpan(output) {
2656
+ if (!this.currentChunkSpan) return;
2657
+ this.currentChunkSpan.end({
2658
+ output: output !== void 0 ? output : this.accumulator
2659
+ });
2660
+ this.currentChunkSpan = void 0;
2661
+ this.accumulator = {};
2662
+ this.chunkSequence++;
2663
+ }
2664
+ /**
2665
+ * Create an event span (for single chunks like tool-call)
2666
+ */
2667
+ createEventSpan(chunkType, output) {
2668
+ if (!this.currentStepSpan) {
2669
+ this.startStepSpan();
2670
+ }
2671
+ const span = this.currentStepSpan?.createEventSpan({
2672
+ name: `chunk: '${chunkType}'`,
2673
+ type: "llm_chunk" /* LLM_CHUNK */,
2674
+ attributes: {
2675
+ chunkType,
2676
+ sequenceNumber: this.chunkSequence
2677
+ },
2678
+ output
2679
+ });
2680
+ if (span) {
2681
+ this.chunkSequence++;
2682
+ }
2683
+ }
2684
+ /**
2685
+ * Check if there is currently an active chunk span
2686
+ */
2687
+ hasActiveChunkSpan() {
2688
+ return !!this.currentChunkSpan;
2689
+ }
2690
+ /**
2691
+ * Get the current accumulator value
2692
+ */
2693
+ getAccumulator() {
2694
+ return this.accumulator;
2695
+ }
2696
+ /**
2697
+ * Get the current step span (for making tool calls children of steps)
2698
+ */
2699
+ getCurrentStepSpan() {
2700
+ return this.currentStepSpan;
2701
+ }
2702
+ /**
2703
+ * Wraps a stream with model tracing transform to track LLM_STEP and LLM_CHUNK spans.
2704
+ *
2705
+ * This should be added to the stream pipeline to automatically
2706
+ * create LLM_STEP and LLM_CHUNK spans for each semantic unit in the stream.
2707
+ */
2708
+ wrapStream(stream) {
2709
+ const tracker = this;
2710
+ return stream.pipeThrough(
2711
+ new web.TransformStream({
2712
+ transform(chunk, controller) {
2713
+ controller.enqueue(chunk);
2714
+ switch (chunk.type) {
2715
+ case "text-start":
2716
+ case "text-delta":
2717
+ case "text-end":
2718
+ handleTextChunk(chunk, tracker);
2719
+ break;
2720
+ case "tool-call-input-streaming-start":
2721
+ case "tool-call-delta":
2722
+ case "tool-call-input-streaming-end":
2723
+ case "tool-call":
2724
+ handleToolCallChunk(chunk, tracker);
2725
+ break;
2726
+ case "reasoning-start":
2727
+ case "reasoning-delta":
2728
+ case "reasoning-end":
2729
+ handleReasoningChunk(chunk, tracker);
2730
+ break;
2731
+ case "object":
2732
+ case "object-result":
2733
+ handleObjectChunk(chunk, tracker);
2734
+ break;
2735
+ case "step-start":
2736
+ tracker.startStepSpan(chunk.payload);
2737
+ break;
2738
+ case "step-finish":
2739
+ tracker.endStepSpan(chunk.payload);
2740
+ break;
2741
+ case "raw":
2742
+ // Skip raw chunks as they're redundant
2743
+ case "start":
2744
+ case "finish":
2745
+ break;
2746
+ // Default: auto-create event span for all other chunk types
2747
+ default: {
2748
+ let outputPayload = chunk.payload;
2749
+ if (outputPayload && typeof outputPayload === "object" && "data" in outputPayload) {
2750
+ const typedPayload = outputPayload;
2751
+ outputPayload = { ...typedPayload };
2752
+ if (typedPayload.data) {
2753
+ outputPayload.size = typeof typedPayload.data === "string" ? typedPayload.data.length : typedPayload.data instanceof Uint8Array ? typedPayload.data.length : void 0;
2754
+ delete outputPayload.data;
2755
+ }
2756
+ }
2757
+ tracker.createEventSpan(chunk.type, outputPayload);
2758
+ break;
2759
+ }
2760
+ }
2761
+ }
2762
+ })
2763
+ );
2764
+ }
2765
+ };
2766
+ function handleTextChunk(chunk, tracker) {
2767
+ switch (chunk.type) {
2768
+ case "text-start":
2769
+ tracker.startChunkSpan("text");
2770
+ break;
2771
+ case "text-delta":
2772
+ tracker.appendToAccumulator("text", chunk.payload.text);
2773
+ break;
2774
+ case "text-end": {
2775
+ tracker.endChunkSpan();
2776
+ break;
2777
+ }
2778
+ }
2779
+ }
2780
+ function handleReasoningChunk(chunk, tracker) {
2781
+ switch (chunk.type) {
2782
+ case "reasoning-start":
2783
+ tracker.startChunkSpan("reasoning");
2784
+ break;
2785
+ case "reasoning-delta":
2786
+ tracker.appendToAccumulator("text", chunk.payload.text);
2787
+ break;
2788
+ case "reasoning-end": {
2789
+ tracker.endChunkSpan();
2790
+ break;
2791
+ }
2792
+ }
2793
+ }
2794
+ function handleToolCallChunk(chunk, tracker) {
2795
+ switch (chunk.type) {
2796
+ case "tool-call-input-streaming-start":
2797
+ tracker.startChunkSpan("tool-call", {
2798
+ toolName: chunk.payload.toolName,
2799
+ toolCallId: chunk.payload.toolCallId
2800
+ });
2801
+ break;
2802
+ case "tool-call-delta":
2803
+ tracker.appendToAccumulator("toolInput", chunk.payload.argsTextDelta);
2804
+ break;
2805
+ case "tool-call-input-streaming-end":
2806
+ case "tool-call": {
2807
+ const acc = tracker.getAccumulator();
2808
+ let toolInput;
2809
+ try {
2810
+ toolInput = acc.toolInput ? JSON.parse(acc.toolInput) : {};
2811
+ } catch {
2812
+ toolInput = acc.toolInput;
2813
+ }
2814
+ tracker.endChunkSpan({
2815
+ toolName: acc.toolName,
2816
+ toolCallId: acc.toolCallId,
2817
+ toolInput
2818
+ });
2819
+ break;
2820
+ }
2821
+ }
2822
+ }
2823
+ function handleObjectChunk(chunk, tracker) {
2824
+ switch (chunk.type) {
2825
+ case "object":
2826
+ if (!tracker.hasActiveChunkSpan()) {
2827
+ tracker.startChunkSpan("object");
2828
+ }
2829
+ break;
2830
+ case "object-result":
2831
+ tracker.endChunkSpan(chunk.object);
2832
+ break;
2833
+ }
2834
+ }
2374
2835
 
2375
2836
  exports.AISpanType = AISpanType;
2376
2837
  exports.AITracingEventType = AITracingEventType;
2377
2838
  exports.BaseAISpan = BaseAISpan;
2378
2839
  exports.BaseAITracing = BaseAITracing;
2840
+ exports.BaseExporter = BaseExporter;
2379
2841
  exports.CloudExporter = CloudExporter;
2380
2842
  exports.ConsoleExporter = ConsoleExporter;
2381
2843
  exports.DefaultAISpan = DefaultAISpan;
2382
2844
  exports.DefaultAITracing = DefaultAITracing;
2383
2845
  exports.DefaultExporter = DefaultExporter;
2384
2846
  exports.InternalSpans = InternalSpans;
2847
+ exports.ModelSpanTracker = ModelSpanTracker;
2385
2848
  exports.NoOpAISpan = NoOpAISpan;
2386
2849
  exports.SamplingStrategyType = SamplingStrategyType;
2387
2850
  exports.SensitiveDataFilter = SensitiveDataFilter;
@@ -2397,6 +2860,7 @@ exports.generateEmptyFromSchema = generateEmptyFromSchema;
2397
2860
  exports.getAITracing = getAITracing;
2398
2861
  exports.getAllAITracing = getAllAITracing;
2399
2862
  exports.getDefaultAITracing = getDefaultAITracing;
2863
+ exports.getNestedValue = getNestedValue;
2400
2864
  exports.getOrCreateSpan = getOrCreateSpan;
2401
2865
  exports.getSelectedAITracing = getSelectedAITracing;
2402
2866
  exports.getValidTraceId = getValidTraceId;
@@ -2414,10 +2878,11 @@ exports.parseSqlIdentifier = parseSqlIdentifier;
2414
2878
  exports.registerAITracing = registerAITracing;
2415
2879
  exports.resolveSerializedZodOutput = resolveSerializedZodOutput;
2416
2880
  exports.selectFields = selectFields;
2881
+ exports.setNestedValue = setNestedValue;
2417
2882
  exports.setSelector = setSelector;
2418
2883
  exports.setupAITracing = setupAITracing;
2419
2884
  exports.shutdownAITracingRegistry = shutdownAITracingRegistry;
2420
2885
  exports.unregisterAITracing = unregisterAITracing;
2421
2886
  exports.wrapMastra = wrapMastra;
2422
- //# sourceMappingURL=chunk-URQI7RJ3.cjs.map
2423
- //# sourceMappingURL=chunk-URQI7RJ3.cjs.map
2887
+ //# sourceMappingURL=chunk-5GIAZ3CH.cjs.map
2888
+ //# sourceMappingURL=chunk-5GIAZ3CH.cjs.map