@mastra/core 0.16.2 → 0.16.3-alpha.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 (166) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/dist/agent/agent.d.ts +316 -0
  3. package/dist/agent/agent.d.ts.map +1 -0
  4. package/dist/agent/agent.types.d.ts +19 -2
  5. package/dist/agent/agent.types.d.ts.map +1 -1
  6. package/dist/agent/index.cjs +11 -11
  7. package/dist/agent/index.d.ts +4 -313
  8. package/dist/agent/index.d.ts.map +1 -1
  9. package/dist/agent/index.js +2 -2
  10. package/dist/agent/input-processor/index.cjs +6 -6
  11. package/dist/agent/input-processor/index.js +1 -1
  12. package/dist/agent/types.d.ts +8 -1
  13. package/dist/agent/types.d.ts.map +1 -1
  14. package/dist/ai-tracing/base.d.ts.map +1 -1
  15. package/dist/ai-tracing/context.d.ts.map +1 -1
  16. package/dist/ai-tracing/default.d.ts +1 -2
  17. package/dist/ai-tracing/default.d.ts.map +1 -1
  18. package/dist/ai-tracing/exporters/cloud.d.ts +32 -0
  19. package/dist/ai-tracing/exporters/cloud.d.ts.map +1 -0
  20. package/dist/ai-tracing/exporters/default.d.ts.map +1 -1
  21. package/dist/ai-tracing/exporters/index.d.ts +2 -0
  22. package/dist/ai-tracing/exporters/index.d.ts.map +1 -1
  23. package/dist/ai-tracing/index.cjs +36 -40
  24. package/dist/ai-tracing/index.js +1 -1
  25. package/dist/ai-tracing/no-op.d.ts +1 -0
  26. package/dist/ai-tracing/no-op.d.ts.map +1 -1
  27. package/dist/ai-tracing/registry.d.ts.map +1 -1
  28. package/dist/ai-tracing/types.d.ts +39 -14
  29. package/dist/ai-tracing/types.d.ts.map +1 -1
  30. package/dist/ai-tracing/utils.d.ts +29 -19
  31. package/dist/ai-tracing/utils.d.ts.map +1 -1
  32. package/dist/{chunk-YI3AIJJL.js → chunk-3JG5JEKX.js} +3 -3
  33. package/dist/{chunk-YI3AIJJL.js.map → chunk-3JG5JEKX.js.map} +1 -1
  34. package/dist/{chunk-RVNDGKE5.js → chunk-3WWYKE4R.js} +3 -3
  35. package/dist/{chunk-RVNDGKE5.js.map → chunk-3WWYKE4R.js.map} +1 -1
  36. package/dist/{chunk-YBKHXKRR.js → chunk-4MVIJIOL.js} +3 -3
  37. package/dist/{chunk-YBKHXKRR.js.map → chunk-4MVIJIOL.js.map} +1 -1
  38. package/dist/chunk-4WQYXT2I.cjs +12 -0
  39. package/dist/chunk-4WQYXT2I.cjs.map +1 -0
  40. package/dist/{chunk-YYRE76UM.js → chunk-6SPMCTI2.js} +4 -4
  41. package/dist/{chunk-YYRE76UM.js.map → chunk-6SPMCTI2.js.map} +1 -1
  42. package/dist/{chunk-P67M4R6G.js → chunk-ASFX33CM.js} +5 -5
  43. package/dist/{chunk-P67M4R6G.js.map → chunk-ASFX33CM.js.map} +1 -1
  44. package/dist/{chunk-SJO2HEVU.cjs → chunk-AV5QBG6P.cjs} +185 -125
  45. package/dist/chunk-AV5QBG6P.cjs.map +1 -0
  46. package/dist/{chunk-OYHHJUTH.cjs → chunk-EJB4UMEV.cjs} +12 -12
  47. package/dist/{chunk-OYHHJUTH.cjs.map → chunk-EJB4UMEV.cjs.map} +1 -1
  48. package/dist/{chunk-JLVFFZT7.cjs → chunk-GOA5GU6X.cjs} +4 -4
  49. package/dist/{chunk-JLVFFZT7.cjs.map → chunk-GOA5GU6X.cjs.map} +1 -1
  50. package/dist/{chunk-D3UG2YLU.cjs → chunk-HT57W63C.cjs} +4 -4
  51. package/dist/{chunk-D3UG2YLU.cjs.map → chunk-HT57W63C.cjs.map} +1 -1
  52. package/dist/{chunk-ZIDWSQFD.cjs → chunk-HYKEC3OC.cjs} +8 -8
  53. package/dist/{chunk-ZIDWSQFD.cjs.map → chunk-HYKEC3OC.cjs.map} +1 -1
  54. package/dist/chunk-KETY3ZMA.cjs +808 -0
  55. package/dist/chunk-KETY3ZMA.cjs.map +1 -0
  56. package/dist/{chunk-IMDDMIVR.cjs → chunk-L52VPDJB.cjs} +6 -6
  57. package/dist/{chunk-IMDDMIVR.cjs.map → chunk-L52VPDJB.cjs.map} +1 -1
  58. package/dist/chunk-NEBAQHIS.js +737 -0
  59. package/dist/chunk-NEBAQHIS.js.map +1 -0
  60. package/dist/chunk-PJKCPRYF.js +3 -0
  61. package/dist/chunk-PJKCPRYF.js.map +1 -0
  62. package/dist/{chunk-6RVOPJVP.cjs → chunk-PUTAA3ZN.cjs} +7 -7
  63. package/dist/{chunk-6RVOPJVP.cjs.map → chunk-PUTAA3ZN.cjs.map} +1 -1
  64. package/dist/{chunk-DUABZASJ.js → chunk-RAR5G5S3.js} +4 -4
  65. package/dist/{chunk-DUABZASJ.js.map → chunk-RAR5G5S3.js.map} +1 -1
  66. package/dist/{chunk-UGCG7DI3.cjs → chunk-VVUCWRGD.cjs} +855 -87
  67. package/dist/chunk-VVUCWRGD.cjs.map +1 -0
  68. package/dist/{chunk-2NKNTPFR.js → chunk-W5K2KOZX.js} +834 -85
  69. package/dist/chunk-W5K2KOZX.js.map +1 -0
  70. package/dist/{chunk-BQ43NQXK.js → chunk-WAN6BRTN.js} +182 -122
  71. package/dist/chunk-WAN6BRTN.js.map +1 -0
  72. package/dist/index.cjs +38 -38
  73. package/dist/index.js +7 -7
  74. package/dist/llm/model/base.types.d.ts +6 -4
  75. package/dist/llm/model/base.types.d.ts.map +1 -1
  76. package/dist/llm/model/model.d.ts +0 -2
  77. package/dist/llm/model/model.d.ts.map +1 -1
  78. package/dist/llm/model/model.loop.d.ts.map +1 -1
  79. package/dist/loop/index.cjs +2 -2
  80. package/dist/loop/index.js +1 -1
  81. package/dist/loop/loop.d.ts.map +1 -1
  82. package/dist/loop/network/index.d.ts +139 -0
  83. package/dist/loop/network/index.d.ts.map +1 -0
  84. package/dist/loop/types.d.ts +2 -0
  85. package/dist/loop/types.d.ts.map +1 -1
  86. package/dist/loop/workflow/llm-execution.d.ts +5 -5
  87. package/dist/loop/workflow/llm-execution.d.ts.map +1 -1
  88. package/dist/loop/workflow/outer-llm-step.d.ts +2 -2
  89. package/dist/loop/workflow/schema.d.ts +12 -12
  90. package/dist/loop/workflow/stream.d.ts.map +1 -1
  91. package/dist/loop/workflow/tool-call-step.d.ts +10 -10
  92. package/dist/mastra/index.cjs +2 -2
  93. package/dist/mastra/index.js +1 -1
  94. package/dist/memory/index.cjs +4 -4
  95. package/dist/memory/index.js +1 -1
  96. package/dist/network/index.cjs +6 -3
  97. package/dist/network/index.cjs.map +1 -1
  98. package/dist/network/index.js +5 -2
  99. package/dist/network/index.js.map +1 -1
  100. package/dist/network/network.d.ts.map +1 -1
  101. package/dist/network/vNext/index.cjs +32 -30
  102. package/dist/network/vNext/index.cjs.map +1 -1
  103. package/dist/network/vNext/index.d.ts +7 -7
  104. package/dist/network/vNext/index.d.ts.map +1 -1
  105. package/dist/network/vNext/index.js +5 -3
  106. package/dist/network/vNext/index.js.map +1 -1
  107. package/dist/processors/index.cjs +8 -8
  108. package/dist/processors/index.js +2 -2
  109. package/dist/processors/runner.d.ts +2 -2
  110. package/dist/processors/runner.d.ts.map +1 -1
  111. package/dist/relevance/index.cjs +4 -4
  112. package/dist/relevance/index.js +1 -1
  113. package/dist/scores/index.cjs +8 -8
  114. package/dist/scores/index.js +1 -1
  115. package/dist/scores/types.d.ts +2 -2
  116. package/dist/storage/index.cjs +3 -3
  117. package/dist/storage/index.js +1 -1
  118. package/dist/stream/MastraWorkflowStream.d.ts +1 -1
  119. package/dist/stream/base/output-format-handlers.d.ts.map +1 -1
  120. package/dist/stream/base/output.d.ts +13 -3
  121. package/dist/stream/base/output.d.ts.map +1 -1
  122. package/dist/stream/base/schema.d.ts +3 -2
  123. package/dist/stream/base/schema.d.ts.map +1 -1
  124. package/dist/stream/index.cjs +3 -3
  125. package/dist/stream/index.d.ts +1 -1
  126. package/dist/stream/index.d.ts.map +1 -1
  127. package/dist/stream/index.js +1 -1
  128. package/dist/stream/types.d.ts +139 -1
  129. package/dist/stream/types.d.ts.map +1 -1
  130. package/dist/test-utils/llm-mock.cjs +2 -2
  131. package/dist/test-utils/llm-mock.js +1 -1
  132. package/dist/utils.cjs +17 -17
  133. package/dist/utils.js +1 -1
  134. package/dist/workflows/default.d.ts +3 -2
  135. package/dist/workflows/default.d.ts.map +1 -1
  136. package/dist/workflows/evented/index.cjs +10 -10
  137. package/dist/workflows/evented/index.js +1 -1
  138. package/dist/workflows/execution-engine.d.ts +2 -2
  139. package/dist/workflows/execution-engine.d.ts.map +1 -1
  140. package/dist/workflows/index.cjs +10 -10
  141. package/dist/workflows/index.js +1 -1
  142. package/dist/workflows/legacy/index.cjs +22 -22
  143. package/dist/workflows/legacy/index.js +1 -1
  144. package/dist/workflows/legacy/machine.d.ts +1 -1
  145. package/dist/workflows/legacy/workflow.d.ts +1 -1
  146. package/dist/workflows/types.d.ts +5 -4
  147. package/dist/workflows/types.d.ts.map +1 -1
  148. package/dist/workflows/workflow.d.ts +8 -4
  149. package/dist/workflows/workflow.d.ts.map +1 -1
  150. package/dist/zod-to-json.cjs +2 -2
  151. package/dist/zod-to-json.cjs.map +1 -1
  152. package/dist/zod-to-json.js +1 -1
  153. package/dist/zod-to-json.js.map +1 -1
  154. package/package.json +5 -5
  155. package/dist/chunk-2NKNTPFR.js.map +0 -1
  156. package/dist/chunk-3MSZBGO3.js +0 -15991
  157. package/dist/chunk-3MSZBGO3.js.map +0 -1
  158. package/dist/chunk-BJASJTXK.cjs +0 -16061
  159. package/dist/chunk-BJASJTXK.cjs.map +0 -1
  160. package/dist/chunk-BQ43NQXK.js.map +0 -1
  161. package/dist/chunk-KB4IEMPV.cjs +0 -548
  162. package/dist/chunk-KB4IEMPV.cjs.map +0 -1
  163. package/dist/chunk-SJO2HEVU.cjs.map +0 -1
  164. package/dist/chunk-TDLB5JKT.js +0 -527
  165. package/dist/chunk-TDLB5JKT.js.map +0 -1
  166. package/dist/chunk-UGCG7DI3.cjs.map +0 -1
@@ -1,6 +1,13 @@
1
+ import { RuntimeContext } from './chunk-HLRWYUFN.js';
1
2
  import { MastraError } from './chunk-MCOVMKIS.js';
3
+ import { ToolStream } from './chunk-YW7UILPE.js';
4
+ import { isVercelTool, validateToolInput } from './chunk-BJGHUKKM.js';
2
5
  import { MastraBase } from './chunk-6GF5M4GX.js';
3
- import { ConsoleLogger, LogLevel, RegisteredLogger } from './chunk-X3GXU6TZ.js';
6
+ import { RegisteredLogger, ConsoleLogger, LogLevel } from './chunk-X3GXU6TZ.js';
7
+ import { createHash } from 'crypto';
8
+ import jsonSchemaToZod from 'json-schema-to-zod';
9
+ import { z } from 'zod';
10
+ import { convertZodSchemaToAISDKSchema, OpenAIReasoningSchemaCompatLayer, OpenAISchemaCompatLayer, GoogleSchemaCompatLayer, AnthropicSchemaCompatLayer, DeepSeekSchemaCompatLayer, MetaSchemaCompatLayer, applyCompatLayer } from '@mastra/schema-compat';
4
11
 
5
12
  // src/ai-tracing/no-op.ts
6
13
  var NoOpAISpan = class _NoOpAISpan {
@@ -47,6 +54,9 @@ var NoOpAISpan = class _NoOpAISpan {
47
54
  get isRootSpan() {
48
55
  return !this.parent;
49
56
  }
57
+ get isValid() {
58
+ return false;
59
+ }
50
60
  };
51
61
 
52
62
  // src/ai-tracing/types.ts
@@ -88,7 +98,7 @@ var MastraAITracing = class extends MastraBase {
88
98
  super({ component: RegisteredLogger.AI_TRACING, name: config.serviceName });
89
99
  this.config = {
90
100
  serviceName: config.serviceName,
91
- instanceName: config.instanceName,
101
+ name: config.name,
92
102
  sampling: config.sampling ?? { type: "always" /* ALWAYS */ },
93
103
  exporters: config.exporters ?? [],
94
104
  processors: config.processors ?? []
@@ -100,7 +110,7 @@ var MastraAITracing = class extends MastraBase {
100
110
  __setLogger(logger) {
101
111
  super.__setLogger(logger);
102
112
  this.logger.debug(
103
- `[AI Tracing] Initialized [service=${this.config.serviceName}] [instance=${this.config.instanceName}] [sampling=${this.config.sampling.type}]`
113
+ `[AI Tracing] Initialized [service=${this.config.serviceName}] [instance=${this.config.name}] [sampling=${this.config.sampling.type}]`
104
114
  );
105
115
  }
106
116
  // ============================================================================
@@ -187,10 +197,18 @@ var MastraAITracing = class extends MastraBase {
187
197
  const originalEnd = span.end.bind(span);
188
198
  const originalUpdate = span.update.bind(span);
189
199
  span.end = (options) => {
200
+ if (span.isEvent) {
201
+ this.logger.warn(`End event is not available on event spans`);
202
+ return;
203
+ }
190
204
  originalEnd(options);
191
205
  this.emitSpanEnded(span);
192
206
  };
193
207
  span.update = (options) => {
208
+ if (span.isEvent) {
209
+ this.logger.warn(`Update() is not available on event spans`);
210
+ return;
211
+ }
194
212
  originalUpdate(options);
195
213
  this.emitSpanUpdated(span);
196
214
  };
@@ -311,6 +329,718 @@ var MastraAITracing = class extends MastraBase {
311
329
  this.logger.info(`[AI Tracing] Shutdown completed [name=${this.name}]`);
312
330
  }
313
331
  };
332
+ var CoreToolBuilder = class extends MastraBase {
333
+ originalTool;
334
+ options;
335
+ logType;
336
+ constructor(input) {
337
+ super({ name: "CoreToolBuilder" });
338
+ this.originalTool = input.originalTool;
339
+ this.options = input.options;
340
+ this.logType = input.logType;
341
+ }
342
+ // Helper to get parameters based on tool type
343
+ getParameters = () => {
344
+ if (isVercelTool(this.originalTool)) {
345
+ return this.originalTool.parameters ?? z.object({});
346
+ }
347
+ return this.originalTool.inputSchema ?? z.object({});
348
+ };
349
+ getOutputSchema = () => {
350
+ if ("outputSchema" in this.originalTool) return this.originalTool.outputSchema;
351
+ return null;
352
+ };
353
+ // For provider-defined tools, we need to include all required properties
354
+ buildProviderTool(tool) {
355
+ if ("type" in tool && tool.type === "provider-defined" && "id" in tool && typeof tool.id === "string" && tool.id.includes(".")) {
356
+ const parameters = this.getParameters();
357
+ const outputSchema = this.getOutputSchema();
358
+ return {
359
+ type: "provider-defined",
360
+ id: tool.id,
361
+ args: "args" in this.originalTool ? this.originalTool.args : {},
362
+ description: tool.description,
363
+ parameters: convertZodSchemaToAISDKSchema(parameters),
364
+ ...outputSchema ? { outputSchema: convertZodSchemaToAISDKSchema(outputSchema) } : {},
365
+ execute: this.originalTool.execute ? this.createExecute(
366
+ this.originalTool,
367
+ { ...this.options, description: this.originalTool.description },
368
+ this.logType
369
+ ) : void 0
370
+ };
371
+ }
372
+ return void 0;
373
+ }
374
+ createLogMessageOptions({ agentName, toolName, type }) {
375
+ if (!agentName) {
376
+ return {
377
+ start: `Executing tool ${toolName}`,
378
+ error: `Failed tool execution`
379
+ };
380
+ }
381
+ const prefix = `[Agent:${agentName}]`;
382
+ const toolType = type === "toolset" ? "toolset" : "tool";
383
+ return {
384
+ start: `${prefix} - Executing ${toolType} ${toolName}`,
385
+ error: `${prefix} - Failed ${toolType} execution`
386
+ };
387
+ }
388
+ createExecute(tool, options, logType) {
389
+ const { logger, mastra: _mastra, memory: _memory, runtimeContext, ...rest } = options;
390
+ const { start, error } = this.createLogMessageOptions({
391
+ agentName: options.agentName,
392
+ toolName: options.name,
393
+ type: logType
394
+ });
395
+ const execFunction = async (args, execOptions) => {
396
+ const toolSpan = options.tracingContext?.currentSpan?.createChildSpan({
397
+ type: "tool_call" /* TOOL_CALL */,
398
+ name: `tool: '${options.name}'`,
399
+ input: args,
400
+ attributes: {
401
+ toolId: options.name,
402
+ toolDescription: options.description,
403
+ toolType: logType || "tool"
404
+ }
405
+ });
406
+ try {
407
+ let result;
408
+ if (isVercelTool(tool)) {
409
+ result = await tool?.execute?.(args, execOptions);
410
+ } else {
411
+ const wrappedMastra = options.mastra ? wrapMastra(options.mastra, { currentSpan: toolSpan }) : options.mastra;
412
+ result = await tool?.execute?.(
413
+ {
414
+ context: args,
415
+ threadId: options.threadId,
416
+ resourceId: options.resourceId,
417
+ mastra: wrappedMastra,
418
+ memory: options.memory,
419
+ runId: options.runId,
420
+ runtimeContext: options.runtimeContext ?? new RuntimeContext(),
421
+ writer: new ToolStream(
422
+ {
423
+ prefix: "tool",
424
+ callId: execOptions.toolCallId,
425
+ name: options.name,
426
+ runId: options.runId
427
+ },
428
+ options.writableStream || execOptions.writableStream
429
+ ),
430
+ tracingContext: { currentSpan: toolSpan }
431
+ },
432
+ execOptions
433
+ );
434
+ }
435
+ toolSpan?.end({ output: result });
436
+ return result ?? void 0;
437
+ } catch (error2) {
438
+ toolSpan?.error({ error: error2 });
439
+ throw error2;
440
+ }
441
+ };
442
+ return async (args, execOptions) => {
443
+ let logger2 = options.logger || this.logger;
444
+ try {
445
+ logger2.debug(start, { ...rest, args });
446
+ const parameters = this.getParameters();
447
+ const { data, error: error2 } = validateToolInput(parameters, args, options.name);
448
+ if (error2) {
449
+ logger2.warn(`Tool input validation failed for '${options.name}'`, {
450
+ toolName: options.name,
451
+ errors: error2.validationErrors,
452
+ args
453
+ });
454
+ return error2;
455
+ }
456
+ args = data;
457
+ return await new Promise((resolve, reject) => {
458
+ setImmediate(async () => {
459
+ try {
460
+ const result = await execFunction(args, execOptions);
461
+ resolve(result);
462
+ } catch (err) {
463
+ reject(err);
464
+ }
465
+ });
466
+ });
467
+ } catch (err) {
468
+ const mastraError = new MastraError(
469
+ {
470
+ id: "TOOL_EXECUTION_FAILED",
471
+ domain: "TOOL" /* TOOL */,
472
+ category: "USER" /* USER */,
473
+ details: {
474
+ errorMessage: String(error),
475
+ argsJson: JSON.stringify(args),
476
+ model: rest.model?.modelId ?? ""
477
+ }
478
+ },
479
+ err
480
+ );
481
+ logger2.trackException(mastraError);
482
+ logger2.error(error, { ...rest, error: mastraError, args });
483
+ return mastraError;
484
+ }
485
+ };
486
+ }
487
+ buildV5() {
488
+ const builtTool = this.build();
489
+ if (!builtTool.parameters) {
490
+ throw new Error("Tool parameters are required");
491
+ }
492
+ return {
493
+ ...builtTool,
494
+ inputSchema: builtTool.parameters,
495
+ onInputStart: "onInputStart" in this.originalTool ? this.originalTool.onInputStart : void 0,
496
+ onInputDelta: "onInputDelta" in this.originalTool ? this.originalTool.onInputDelta : void 0,
497
+ onInputAvailable: "onInputAvailable" in this.originalTool ? this.originalTool.onInputAvailable : void 0
498
+ };
499
+ }
500
+ build() {
501
+ const providerTool = this.buildProviderTool(this.originalTool);
502
+ if (providerTool) {
503
+ return providerTool;
504
+ }
505
+ const definition = {
506
+ type: "function",
507
+ description: this.originalTool.description,
508
+ parameters: this.getParameters(),
509
+ outputSchema: this.getOutputSchema(),
510
+ execute: this.originalTool.execute ? this.createExecute(
511
+ this.originalTool,
512
+ { ...this.options, description: this.originalTool.description },
513
+ this.logType
514
+ ) : void 0
515
+ };
516
+ const model = this.options.model;
517
+ const schemaCompatLayers = [];
518
+ if (model) {
519
+ const supportsStructuredOutputs = model.specificationVersion !== "v2" ? model.supportsStructuredOutputs ?? false : false;
520
+ const modelInfo = {
521
+ modelId: model.modelId,
522
+ supportsStructuredOutputs,
523
+ provider: model.provider
524
+ };
525
+ schemaCompatLayers.push(
526
+ new OpenAIReasoningSchemaCompatLayer(modelInfo),
527
+ new OpenAISchemaCompatLayer(modelInfo),
528
+ new GoogleSchemaCompatLayer(modelInfo),
529
+ new AnthropicSchemaCompatLayer(modelInfo),
530
+ new DeepSeekSchemaCompatLayer(modelInfo),
531
+ new MetaSchemaCompatLayer(modelInfo)
532
+ );
533
+ }
534
+ const processedSchema = applyCompatLayer({
535
+ schema: this.getParameters(),
536
+ compatLayers: schemaCompatLayers,
537
+ mode: "aiSdkSchema"
538
+ });
539
+ let processedOutputSchema;
540
+ if (this.getOutputSchema()) {
541
+ processedOutputSchema = applyCompatLayer({
542
+ schema: this.getOutputSchema(),
543
+ compatLayers: schemaCompatLayers,
544
+ mode: "aiSdkSchema"
545
+ });
546
+ }
547
+ return {
548
+ ...definition,
549
+ id: "id" in this.originalTool ? this.originalTool.id : void 0,
550
+ parameters: processedSchema,
551
+ outputSchema: processedOutputSchema
552
+ };
553
+ }
554
+ };
555
+
556
+ // src/utils.ts
557
+ var delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
558
+ function deepMerge(target, source) {
559
+ const output = { ...target };
560
+ if (!source) return output;
561
+ Object.keys(source).forEach((key) => {
562
+ const targetValue = output[key];
563
+ const sourceValue = source[key];
564
+ if (Array.isArray(targetValue) && Array.isArray(sourceValue)) {
565
+ output[key] = sourceValue;
566
+ } else if (sourceValue instanceof Object && targetValue instanceof Object && !Array.isArray(sourceValue) && !Array.isArray(targetValue)) {
567
+ output[key] = deepMerge(targetValue, sourceValue);
568
+ } else if (sourceValue !== void 0) {
569
+ output[key] = sourceValue;
570
+ }
571
+ });
572
+ return output;
573
+ }
574
+ function generateEmptyFromSchema(schema) {
575
+ try {
576
+ const parsedSchema = JSON.parse(schema);
577
+ if (!parsedSchema || parsedSchema.type !== "object" || !parsedSchema.properties) return {};
578
+ const obj = {};
579
+ const TYPE_DEFAULTS = {
580
+ string: "",
581
+ array: [],
582
+ object: {},
583
+ number: 0,
584
+ integer: 0,
585
+ boolean: false
586
+ };
587
+ for (const [key, prop] of Object.entries(parsedSchema.properties)) {
588
+ obj[key] = TYPE_DEFAULTS[prop.type] ?? null;
589
+ }
590
+ return obj;
591
+ } catch {
592
+ return {};
593
+ }
594
+ }
595
+ async function* maskStreamTags(stream, tag, options = {}) {
596
+ const { onStart, onEnd, onMask } = options;
597
+ const openTag = `<${tag}>`;
598
+ const closeTag = `</${tag}>`;
599
+ let buffer = "";
600
+ let fullContent = "";
601
+ let isMasking = false;
602
+ let isBuffering = false;
603
+ const trimOutsideDelimiter = (text, delimiter, trim) => {
604
+ if (!text.includes(delimiter)) {
605
+ return text;
606
+ }
607
+ const parts = text.split(delimiter);
608
+ if (trim === `before-start`) {
609
+ return `${delimiter}${parts[1]}`;
610
+ }
611
+ return `${parts[0]}${delimiter}`;
612
+ };
613
+ const startsWith = (text, pattern) => {
614
+ if (pattern.includes(openTag.substring(0, 3))) {
615
+ pattern = trimOutsideDelimiter(pattern, `<`, `before-start`);
616
+ }
617
+ return text.trim().startsWith(pattern.trim());
618
+ };
619
+ for await (const chunk of stream) {
620
+ fullContent += chunk;
621
+ if (isBuffering) buffer += chunk;
622
+ const chunkHasTag = startsWith(chunk, openTag);
623
+ const bufferHasTag = !chunkHasTag && isBuffering && startsWith(openTag, buffer);
624
+ let toYieldBeforeMaskedStartTag = ``;
625
+ if (!isMasking && (chunkHasTag || bufferHasTag)) {
626
+ isMasking = true;
627
+ isBuffering = false;
628
+ const taggedTextToMask = trimOutsideDelimiter(buffer, `<`, `before-start`);
629
+ if (taggedTextToMask !== buffer.trim()) {
630
+ toYieldBeforeMaskedStartTag = buffer.replace(taggedTextToMask, ``);
631
+ }
632
+ buffer = "";
633
+ onStart?.();
634
+ }
635
+ if (!isMasking && !isBuffering && startsWith(openTag, chunk) && chunk.trim() !== "") {
636
+ isBuffering = true;
637
+ buffer += chunk;
638
+ continue;
639
+ }
640
+ if (isBuffering && buffer && !startsWith(openTag, buffer)) {
641
+ yield buffer;
642
+ buffer = "";
643
+ isBuffering = false;
644
+ continue;
645
+ }
646
+ if (isMasking && fullContent.includes(closeTag)) {
647
+ onMask?.(chunk);
648
+ onEnd?.();
649
+ isMasking = false;
650
+ const lastFullContent = fullContent;
651
+ fullContent = ``;
652
+ const textUntilEndTag = trimOutsideDelimiter(lastFullContent, closeTag, "after-end");
653
+ if (textUntilEndTag !== lastFullContent) {
654
+ yield lastFullContent.replace(textUntilEndTag, ``);
655
+ }
656
+ continue;
657
+ }
658
+ if (isMasking) {
659
+ onMask?.(chunk);
660
+ if (toYieldBeforeMaskedStartTag) {
661
+ yield toYieldBeforeMaskedStartTag;
662
+ }
663
+ continue;
664
+ }
665
+ yield chunk;
666
+ }
667
+ }
668
+ function resolveSerializedZodOutput(schema) {
669
+ return Function("z", `"use strict";return (${schema});`)(z);
670
+ }
671
+ function isZodType(value) {
672
+ return typeof value === "object" && value !== null && "_def" in value && "parse" in value && typeof value.parse === "function" && "safeParse" in value && typeof value.safeParse === "function";
673
+ }
674
+ function createDeterministicId(input) {
675
+ return createHash("sha256").update(input).digest("hex").slice(0, 8);
676
+ }
677
+ function setVercelToolProperties(tool) {
678
+ const inputSchema = convertVercelToolParameters(tool);
679
+ const toolId = !("id" in tool) ? tool.description ? `tool-${createDeterministicId(tool.description)}` : `tool-${Math.random().toString(36).substring(2, 9)}` : tool.id;
680
+ return {
681
+ ...tool,
682
+ id: toolId,
683
+ inputSchema
684
+ };
685
+ }
686
+ function ensureToolProperties(tools) {
687
+ const toolsWithProperties = Object.keys(tools).reduce((acc, key) => {
688
+ const tool = tools?.[key];
689
+ if (tool) {
690
+ if (isVercelTool(tool)) {
691
+ acc[key] = setVercelToolProperties(tool);
692
+ } else {
693
+ acc[key] = tool;
694
+ }
695
+ }
696
+ return acc;
697
+ }, {});
698
+ return toolsWithProperties;
699
+ }
700
+ function convertVercelToolParameters(tool) {
701
+ const schema = tool.parameters ?? z.object({});
702
+ return isZodType(schema) ? schema : resolveSerializedZodOutput(jsonSchemaToZod(schema));
703
+ }
704
+ function makeCoreTool(originalTool, options, logType) {
705
+ return new CoreToolBuilder({ originalTool, options, logType }).build();
706
+ }
707
+ function makeCoreToolV5(originalTool, options, logType) {
708
+ return new CoreToolBuilder({ originalTool, options, logType }).buildV5();
709
+ }
710
+ function createMastraProxy({ mastra, logger }) {
711
+ return new Proxy(mastra, {
712
+ get(target, prop) {
713
+ const hasProp = Reflect.has(target, prop);
714
+ if (hasProp) {
715
+ const value = Reflect.get(target, prop);
716
+ const isFunction = typeof value === "function";
717
+ if (isFunction) {
718
+ return value.bind(target);
719
+ }
720
+ return value;
721
+ }
722
+ if (prop === "logger") {
723
+ logger.warn(`Please use 'getLogger' instead, logger is deprecated`);
724
+ return Reflect.apply(target.getLogger, target, []);
725
+ }
726
+ if (prop === "telemetry") {
727
+ logger.warn(`Please use 'getTelemetry' instead, telemetry is deprecated`);
728
+ return Reflect.apply(target.getTelemetry, target, []);
729
+ }
730
+ if (prop === "storage") {
731
+ logger.warn(`Please use 'getStorage' instead, storage is deprecated`);
732
+ return Reflect.get(target, "storage");
733
+ }
734
+ if (prop === "agents") {
735
+ logger.warn(`Please use 'getAgents' instead, agents is deprecated`);
736
+ return Reflect.apply(target.getAgents, target, []);
737
+ }
738
+ if (prop === "tts") {
739
+ logger.warn(`Please use 'getTTS' instead, tts is deprecated`);
740
+ return Reflect.apply(target.getTTS, target, []);
741
+ }
742
+ if (prop === "vectors") {
743
+ logger.warn(`Please use 'getVectors' instead, vectors is deprecated`);
744
+ return Reflect.apply(target.getVectors, target, []);
745
+ }
746
+ if (prop === "memory") {
747
+ logger.warn(`Please use 'getMemory' instead, memory is deprecated`);
748
+ return Reflect.get(target, "memory");
749
+ }
750
+ return Reflect.get(target, prop);
751
+ }
752
+ });
753
+ }
754
+ function checkEvalStorageFields(traceObject, logger) {
755
+ const missingFields = [];
756
+ if (!traceObject.input) missingFields.push("input");
757
+ if (!traceObject.output) missingFields.push("output");
758
+ if (!traceObject.agentName) missingFields.push("agent_name");
759
+ if (!traceObject.metricName) missingFields.push("metric_name");
760
+ if (!traceObject.instructions) missingFields.push("instructions");
761
+ if (!traceObject.globalRunId) missingFields.push("global_run_id");
762
+ if (!traceObject.runId) missingFields.push("run_id");
763
+ if (missingFields.length > 0) {
764
+ if (logger) {
765
+ logger.warn("Skipping evaluation storage due to missing required fields", {
766
+ missingFields,
767
+ runId: traceObject.runId,
768
+ agentName: traceObject.agentName
769
+ });
770
+ } else {
771
+ console.warn("Skipping evaluation storage due to missing required fields", {
772
+ missingFields,
773
+ runId: traceObject.runId,
774
+ agentName: traceObject.agentName
775
+ });
776
+ }
777
+ return false;
778
+ }
779
+ return true;
780
+ }
781
+ function detectSingleMessageCharacteristics(message) {
782
+ if (typeof message === "object" && message !== null && (message.role === "function" || // UI-only role
783
+ message.role === "data" || // UI-only role
784
+ "toolInvocations" in message || // UI-specific field
785
+ "parts" in message || // UI-specific field
786
+ "experimental_attachments" in message)) {
787
+ return "has-ui-specific-parts";
788
+ } else if (typeof message === "object" && message !== null && "content" in message && (Array.isArray(message.content) || // Core messages can have array content
789
+ "experimental_providerMetadata" in message || "providerOptions" in message)) {
790
+ return "has-core-specific-parts";
791
+ } else if (typeof message === "object" && message !== null && "role" in message && "content" in message && typeof message.content === "string" && ["system", "user", "assistant", "tool"].includes(message.role)) {
792
+ return "message";
793
+ } else {
794
+ return "other";
795
+ }
796
+ }
797
+ function isUiMessage(message) {
798
+ return detectSingleMessageCharacteristics(message) === `has-ui-specific-parts`;
799
+ }
800
+ function isCoreMessage(message) {
801
+ return [`has-core-specific-parts`, `message`].includes(detectSingleMessageCharacteristics(message));
802
+ }
803
+ var SQL_IDENTIFIER_PATTERN = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
804
+ function parseSqlIdentifier(name, kind = "identifier") {
805
+ if (!SQL_IDENTIFIER_PATTERN.test(name) || name.length > 63) {
806
+ throw new Error(
807
+ `Invalid ${kind}: ${name}. Must start with a letter or underscore, contain only letters, numbers, or underscores, and be at most 63 characters long.`
808
+ );
809
+ }
810
+ return name;
811
+ }
812
+ function parseFieldKey(key) {
813
+ if (!key) throw new Error("Field key cannot be empty");
814
+ const segments = key.split(".");
815
+ for (const segment of segments) {
816
+ if (!SQL_IDENTIFIER_PATTERN.test(segment) || segment.length > 63) {
817
+ throw new Error(`Invalid field key segment: ${segment} in ${key}`);
818
+ }
819
+ }
820
+ return key;
821
+ }
822
+ async function fetchWithRetry(url, options = {}, maxRetries = 3) {
823
+ let retryCount = 0;
824
+ let lastError = null;
825
+ while (retryCount < maxRetries) {
826
+ try {
827
+ const response = await fetch(url, options);
828
+ if (!response.ok) {
829
+ throw new Error(`Request failed with status: ${response.status} ${response.statusText}`);
830
+ }
831
+ return response;
832
+ } catch (error) {
833
+ lastError = error instanceof Error ? error : new Error(String(error));
834
+ retryCount++;
835
+ if (retryCount >= maxRetries) {
836
+ break;
837
+ }
838
+ const delay2 = Math.min(1e3 * Math.pow(2, retryCount) * 1e3, 1e4);
839
+ await new Promise((resolve) => setTimeout(resolve, delay2));
840
+ }
841
+ }
842
+ throw lastError || new Error("Request failed after multiple retry attempts");
843
+ }
844
+
845
+ // src/ai-tracing/exporters/cloud.ts
846
+ var CloudExporter = class {
847
+ name = "mastra-cloud-ai-tracing-exporter";
848
+ config;
849
+ buffer;
850
+ flushTimer = null;
851
+ logger;
852
+ isDisabled = false;
853
+ constructor(config = {}) {
854
+ this.logger = config.logger ?? new ConsoleLogger({ level: LogLevel.INFO });
855
+ const accessToken = config.accessToken ?? process.env.MASTRA_CLOUD_ACCESS_TOKEN;
856
+ if (!accessToken) {
857
+ this.logger.warn(
858
+ "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."
859
+ );
860
+ this.isDisabled = true;
861
+ }
862
+ const endpoint = config.endpoint ?? process.env.MASTRA_CLOUD_AI_TRACES_ENDPOINT ?? "https://api.mastra.ai/ai/spans/publish";
863
+ this.config = {
864
+ maxBatchSize: config.maxBatchSize ?? 1e3,
865
+ maxBatchWaitMs: config.maxBatchWaitMs ?? 5e3,
866
+ maxRetries: config.maxRetries ?? 3,
867
+ accessToken: accessToken || "",
868
+ // Empty string if no token
869
+ endpoint,
870
+ logger: this.logger
871
+ };
872
+ this.buffer = {
873
+ spans: [],
874
+ totalSize: 0
875
+ };
876
+ }
877
+ async exportEvent(event) {
878
+ if (this.isDisabled) {
879
+ return;
880
+ }
881
+ if (event.type !== "span_ended" /* SPAN_ENDED */) {
882
+ return;
883
+ }
884
+ this.addToBuffer(event);
885
+ if (this.shouldFlush()) {
886
+ this.flush().catch((error) => {
887
+ this.logger.error("Batch flush failed", {
888
+ error: error instanceof Error ? error.message : String(error)
889
+ });
890
+ });
891
+ } else if (this.buffer.totalSize === 1) {
892
+ this.scheduleFlush();
893
+ }
894
+ }
895
+ addToBuffer(event) {
896
+ if (this.buffer.totalSize === 0) {
897
+ this.buffer.firstEventTime = /* @__PURE__ */ new Date();
898
+ }
899
+ const spanRecord = this.formatSpan(event.span);
900
+ this.buffer.spans.push(spanRecord);
901
+ this.buffer.totalSize++;
902
+ }
903
+ formatSpan(span) {
904
+ const spanRecord = {
905
+ traceId: span.traceId,
906
+ spanId: span.id,
907
+ parentSpanId: span.parent?.id ?? null,
908
+ name: span.name,
909
+ spanType: span.type,
910
+ attributes: span.attributes ?? null,
911
+ metadata: span.metadata ?? null,
912
+ startedAt: span.startTime,
913
+ endedAt: span.endTime ?? null,
914
+ input: span.input ?? null,
915
+ output: span.output ?? null,
916
+ error: span.errorInfo,
917
+ isEvent: span.isEvent,
918
+ createdAt: /* @__PURE__ */ new Date(),
919
+ updatedAt: null
920
+ };
921
+ return spanRecord;
922
+ }
923
+ shouldFlush() {
924
+ if (this.buffer.totalSize >= this.config.maxBatchSize) {
925
+ return true;
926
+ }
927
+ if (this.buffer.firstEventTime && this.buffer.totalSize > 0) {
928
+ const elapsed = Date.now() - this.buffer.firstEventTime.getTime();
929
+ if (elapsed >= this.config.maxBatchWaitMs) {
930
+ return true;
931
+ }
932
+ }
933
+ return false;
934
+ }
935
+ scheduleFlush() {
936
+ if (this.flushTimer) {
937
+ clearTimeout(this.flushTimer);
938
+ }
939
+ this.flushTimer = setTimeout(() => {
940
+ this.flush().catch((error) => {
941
+ const mastraError = new MastraError(
942
+ {
943
+ id: `CLOUD_AI_TRACING_FAILED_TO_SCHEDULE_FLUSH`,
944
+ domain: "MASTRA_OBSERVABILITY" /* MASTRA_OBSERVABILITY */,
945
+ category: "USER" /* USER */
946
+ },
947
+ error
948
+ );
949
+ this.logger.trackException(mastraError);
950
+ this.logger.error("Scheduled flush failed", mastraError);
951
+ });
952
+ }, this.config.maxBatchWaitMs);
953
+ }
954
+ async flush() {
955
+ if (this.flushTimer) {
956
+ clearTimeout(this.flushTimer);
957
+ this.flushTimer = null;
958
+ }
959
+ if (this.buffer.totalSize === 0) {
960
+ return;
961
+ }
962
+ const startTime = Date.now();
963
+ const spansCopy = [...this.buffer.spans];
964
+ const flushReason = this.buffer.totalSize >= this.config.maxBatchSize ? "size" : "time";
965
+ this.resetBuffer();
966
+ try {
967
+ await this.batchUpload(spansCopy);
968
+ const elapsed = Date.now() - startTime;
969
+ this.logger.debug("Batch flushed successfully", {
970
+ batchSize: spansCopy.length,
971
+ flushReason,
972
+ durationMs: elapsed
973
+ });
974
+ } catch (error) {
975
+ const mastraError = new MastraError(
976
+ {
977
+ id: `CLOUD_AI_TRACING_FAILED_TO_BATCH_UPLOAD`,
978
+ domain: "MASTRA_OBSERVABILITY" /* MASTRA_OBSERVABILITY */,
979
+ category: "USER" /* USER */,
980
+ details: {
981
+ droppedBatchSize: spansCopy.length
982
+ }
983
+ },
984
+ error
985
+ );
986
+ this.logger.trackException(mastraError);
987
+ this.logger.error("Batch upload failed after all retries, dropping batch", mastraError);
988
+ }
989
+ }
990
+ /**
991
+ * Uploads spans to cloud API using fetchWithRetry for all retry logic
992
+ */
993
+ async batchUpload(spans) {
994
+ const url = `${this.config.endpoint}`;
995
+ const headers = {
996
+ Authorization: `Bearer ${this.config.accessToken}`,
997
+ "Content-Type": "application/json"
998
+ };
999
+ const options = {
1000
+ method: "POST",
1001
+ headers,
1002
+ body: JSON.stringify({ spans })
1003
+ };
1004
+ await fetchWithRetry(url, options, this.config.maxRetries);
1005
+ }
1006
+ resetBuffer() {
1007
+ this.buffer.spans = [];
1008
+ this.buffer.firstEventTime = void 0;
1009
+ this.buffer.totalSize = 0;
1010
+ }
1011
+ async shutdown() {
1012
+ if (this.isDisabled) {
1013
+ return;
1014
+ }
1015
+ if (this.flushTimer) {
1016
+ clearTimeout(this.flushTimer);
1017
+ this.flushTimer = null;
1018
+ }
1019
+ if (this.buffer.totalSize > 0) {
1020
+ this.logger.info("Flushing remaining events on shutdown", {
1021
+ remainingEvents: this.buffer.totalSize
1022
+ });
1023
+ try {
1024
+ await this.flush();
1025
+ } catch (error) {
1026
+ const mastraError = new MastraError(
1027
+ {
1028
+ id: `CLOUD_AI_TRACING_FAILED_TO_FLUSH_REMAINING_EVENTS_DURING_SHUTDOWN`,
1029
+ domain: "MASTRA_OBSERVABILITY" /* MASTRA_OBSERVABILITY */,
1030
+ category: "USER" /* USER */,
1031
+ details: {
1032
+ remainingEvents: this.buffer.totalSize
1033
+ }
1034
+ },
1035
+ error
1036
+ );
1037
+ this.logger.trackException(mastraError);
1038
+ this.logger.error("Failed to flush remaining events during shutdown", mastraError);
1039
+ }
1040
+ }
1041
+ this.logger.info("CloudExporter shutdown complete");
1042
+ }
1043
+ };
314
1044
 
315
1045
  // src/ai-tracing/exporters/console.ts
316
1046
  var ConsoleExporter = class {
@@ -463,7 +1193,8 @@ var DefaultExporter = class {
463
1193
  }
464
1194
  const storage = this.mastra.getStorage();
465
1195
  if (!storage) {
466
- throw new Error("DefaultExporter: Storage not available during initialization");
1196
+ this.logger.warn("DefaultExporter disabled: Storage not available. Traces will not be persisted.");
1197
+ return;
467
1198
  }
468
1199
  this.initializeStrategy(storage);
469
1200
  }
@@ -779,12 +1510,12 @@ var DefaultExporter = class {
779
1510
  */
780
1511
  async flush() {
781
1512
  if (!this.mastra) {
782
- this.logger.warn("Cannot flush traces. Mastra instance not registered yet.");
1513
+ this.logger.debug("Cannot flush traces. Mastra instance not registered yet.");
783
1514
  return;
784
1515
  }
785
1516
  const storage = this.mastra.getStorage();
786
1517
  if (!storage) {
787
- this.logger.warn("Cannot flush traces. Mastra storage is not initialized");
1518
+ this.logger.debug("Cannot flush traces. Mastra storage is not initialized");
788
1519
  return;
789
1520
  }
790
1521
  if (this.flushTimer) {
@@ -864,12 +1595,12 @@ var DefaultExporter = class {
864
1595
  }
865
1596
  async exportEvent(event) {
866
1597
  if (!this.mastra) {
867
- this.logger.warn("Cannot export AI tracing event. Mastra instance not registered yet.");
1598
+ this.logger.debug("Cannot export AI tracing event. Mastra instance not registered yet.");
868
1599
  return;
869
1600
  }
870
1601
  const storage = this.mastra.getStorage();
871
1602
  if (!storage) {
872
- this.logger.warn("Cannot store traces. Mastra storage is not initialized");
1603
+ this.logger.debug("Cannot store traces. Mastra storage is not initialized");
873
1604
  return;
874
1605
  }
875
1606
  if (!this.strategyInitialized) {
@@ -1023,59 +1754,77 @@ function isAITracingInstance(obj) {
1023
1754
  return obj instanceof MastraAITracing;
1024
1755
  }
1025
1756
  function setupAITracing(config) {
1026
- const entries = Object.entries(config.instances);
1027
- entries.forEach(([name, tracingDef], index) => {
1028
- const instance = isAITracingInstance(tracingDef) ? tracingDef : new DefaultAITracing({ ...tracingDef, instanceName: name });
1029
- const isDefault = index === 0;
1030
- registerAITracing(name, instance, isDefault);
1031
- });
1032
- if (config.selector) {
1033
- setAITracingSelector(config.selector);
1757
+ if (!config) {
1758
+ return;
1759
+ }
1760
+ if (config.default?.enabled && config.configs?.["default"]) {
1761
+ throw new Error(
1762
+ "Cannot use 'default' as a custom config name when default tracing is enabled. Please rename your custom config to avoid conflicts."
1763
+ );
1764
+ }
1765
+ if (config.default?.enabled) {
1766
+ const defaultInstance = new DefaultAITracing({
1767
+ serviceName: "mastra",
1768
+ name: "default",
1769
+ sampling: { type: "always" /* ALWAYS */ },
1770
+ exporters: [new DefaultExporter(), new CloudExporter()],
1771
+ processors: [new SensitiveDataFilter()]
1772
+ });
1773
+ registerAITracing("default", defaultInstance, true);
1774
+ }
1775
+ if (config.configs) {
1776
+ const instances = Object.entries(config.configs);
1777
+ instances.forEach(([name, tracingDef], index) => {
1778
+ const instance = isAITracingInstance(tracingDef) ? tracingDef : new DefaultAITracing({ ...tracingDef, name });
1779
+ const isDefault = !config.default?.enabled && index === 0;
1780
+ registerAITracing(name, instance, isDefault);
1781
+ });
1782
+ }
1783
+ if (config.configSelector) {
1784
+ setAITracingSelector(config.configSelector);
1034
1785
  }
1035
1786
  }
1036
1787
 
1037
1788
  // src/ai-tracing/utils.ts
1038
- function shallowCleanObject(obj) {
1039
- const cleaned = {};
1040
- for (const [key, value] of Object.entries(obj)) {
1789
+ var DEFAULT_KEYS_TO_STRIP = /* @__PURE__ */ new Set([
1790
+ "logger",
1791
+ "experimental_providerMetadata",
1792
+ "providerMetadata",
1793
+ "steps",
1794
+ "tracingContext"
1795
+ ]);
1796
+ function deepClean(value, options = {}, _seen = /* @__PURE__ */ new WeakSet(), _depth = 0) {
1797
+ const { keysToStrip = DEFAULT_KEYS_TO_STRIP, maxDepth = 10 } = options;
1798
+ if (_depth > maxDepth) {
1799
+ return "[MaxDepth]";
1800
+ }
1801
+ if (value === null || typeof value !== "object") {
1041
1802
  try {
1042
1803
  JSON.stringify(value);
1043
- cleaned[key] = value;
1804
+ return value;
1044
1805
  } catch (error) {
1045
- cleaned[key] = `[${error instanceof Error ? error.message : String(error)}]`;
1806
+ return `[${error instanceof Error ? error.message : String(error)}]`;
1046
1807
  }
1047
1808
  }
1048
- return cleaned;
1049
- }
1050
- function shallowCleanArray(arr) {
1051
- return arr.map((item) => {
1052
- if (item && typeof item === "object" && !Array.isArray(item)) {
1053
- return shallowCleanObject(item);
1809
+ if (_seen.has(value)) {
1810
+ return "[Circular]";
1811
+ }
1812
+ _seen.add(value);
1813
+ if (Array.isArray(value)) {
1814
+ return value.map((item) => deepClean(item, options, _seen, _depth + 1));
1815
+ }
1816
+ const cleaned = {};
1817
+ for (const [key, val] of Object.entries(value)) {
1818
+ if (keysToStrip.has(key)) {
1819
+ continue;
1054
1820
  }
1055
1821
  try {
1056
- JSON.stringify(item);
1057
- return item;
1822
+ cleaned[key] = deepClean(val, options, _seen, _depth + 1);
1058
1823
  } catch (error) {
1059
- return `[${error instanceof Error ? error.message : String(error)}]`;
1824
+ cleaned[key] = `[${error instanceof Error ? error.message : String(error)}]`;
1060
1825
  }
1061
- });
1062
- }
1063
- function shallowClean(value) {
1064
- if (value === null || value === void 0) {
1065
- return value;
1066
- }
1067
- if (Array.isArray(value)) {
1068
- return shallowCleanArray(value);
1069
- }
1070
- if (typeof value === "object") {
1071
- return shallowCleanObject(value);
1072
- }
1073
- try {
1074
- JSON.stringify(value);
1075
- return value;
1076
- } catch (error) {
1077
- return `[${error instanceof Error ? error.message : String(error)}]`;
1078
1826
  }
1827
+ return cleaned;
1079
1828
  }
1080
1829
  function omitKeys(obj, keysToOmit) {
1081
1830
  return Object.fromEntries(Object.entries(obj).filter(([key]) => !keysToOmit.includes(key)));
@@ -1113,12 +1862,17 @@ function setNestedValue(obj, path, value) {
1113
1862
  target[lastKey] = value;
1114
1863
  }
1115
1864
  function getOrCreateSpan(options) {
1116
- const { type, attributes, tracingContext, runtimeContext, ...rest } = options;
1865
+ const { type, attributes, tracingContext, tracingOptions, runtimeContext, ...rest } = options;
1866
+ const metadata = {
1867
+ ...rest.metadata ?? {},
1868
+ ...tracingOptions?.metadata ?? {}
1869
+ };
1117
1870
  if (tracingContext?.currentSpan) {
1118
1871
  return tracingContext.currentSpan.createChildSpan({
1119
1872
  type,
1120
1873
  attributes,
1121
- ...rest
1874
+ ...rest,
1875
+ metadata
1122
1876
  });
1123
1877
  }
1124
1878
  const aiTracing = getSelectedAITracing({
@@ -1130,9 +1884,13 @@ function getOrCreateSpan(options) {
1130
1884
  startOptions: {
1131
1885
  runtimeContext
1132
1886
  },
1133
- ...rest
1887
+ ...rest,
1888
+ metadata
1134
1889
  });
1135
1890
  }
1891
+ function getValidTraceId(span) {
1892
+ return span?.isValid ? span.traceId : void 0;
1893
+ }
1136
1894
 
1137
1895
  // src/ai-tracing/default.ts
1138
1896
  function generateSpanId() {
@@ -1172,51 +1930,43 @@ var DefaultAISpan = class {
1172
1930
  output;
1173
1931
  errorInfo;
1174
1932
  metadata;
1175
- logger;
1176
1933
  constructor(options, aiTracing) {
1177
1934
  this.id = generateSpanId();
1178
1935
  this.name = options.name;
1179
1936
  this.type = options.type;
1180
- this.attributes = shallowClean(options.attributes) || {};
1181
- this.metadata = shallowClean(options.metadata);
1937
+ this.attributes = deepClean(options.attributes) || {};
1938
+ this.metadata = deepClean(options.metadata);
1182
1939
  this.parent = options.parent;
1183
1940
  this.startTime = /* @__PURE__ */ new Date();
1184
1941
  this.aiTracing = aiTracing;
1185
- this.input = shallowClean(options.input);
1942
+ this.input = deepClean(options.input);
1186
1943
  this.isEvent = options.isEvent;
1187
- this.logger = new ConsoleLogger({
1188
- name: "default-ai-span",
1189
- level: LogLevel.INFO
1190
- // Set to INFO so that info() calls actually log
1191
- });
1192
1944
  if (!options.parent) {
1193
1945
  this.traceId = generateTraceId();
1194
1946
  } else {
1195
1947
  this.traceId = options.parent.traceId;
1196
1948
  }
1197
1949
  if (this.isEvent) {
1198
- this.output = shallowClean(options.output);
1950
+ this.output = deepClean(options.output);
1199
1951
  }
1200
1952
  }
1201
1953
  end(options) {
1202
1954
  if (this.isEvent) {
1203
- this.logger.warn(`End event is not available on event spans`);
1204
1955
  return;
1205
1956
  }
1206
1957
  this.endTime = /* @__PURE__ */ new Date();
1207
1958
  if (options?.output !== void 0) {
1208
- this.output = shallowClean(options.output);
1959
+ this.output = deepClean(options.output);
1209
1960
  }
1210
1961
  if (options?.attributes) {
1211
- this.attributes = { ...this.attributes, ...shallowClean(options.attributes) };
1962
+ this.attributes = { ...this.attributes, ...deepClean(options.attributes) };
1212
1963
  }
1213
1964
  if (options?.metadata) {
1214
- this.metadata = { ...this.metadata, ...shallowClean(options.metadata) };
1965
+ this.metadata = { ...this.metadata, ...deepClean(options.metadata) };
1215
1966
  }
1216
1967
  }
1217
1968
  error(options) {
1218
1969
  if (this.isEvent) {
1219
- this.logger.warn(`Error event is not available on event spans`);
1220
1970
  return;
1221
1971
  }
1222
1972
  const { error, endSpan = true, attributes, metadata } = options;
@@ -1230,10 +1980,10 @@ var DefaultAISpan = class {
1230
1980
  message: error.message
1231
1981
  };
1232
1982
  if (attributes) {
1233
- this.attributes = { ...this.attributes, ...shallowClean(attributes) };
1983
+ this.attributes = { ...this.attributes, ...deepClean(attributes) };
1234
1984
  }
1235
1985
  if (metadata) {
1236
- this.metadata = { ...this.metadata, ...shallowClean(metadata) };
1986
+ this.metadata = { ...this.metadata, ...deepClean(metadata) };
1237
1987
  }
1238
1988
  if (endSpan) {
1239
1989
  this.end();
@@ -1257,25 +2007,27 @@ var DefaultAISpan = class {
1257
2007
  }
1258
2008
  update(options) {
1259
2009
  if (this.isEvent) {
1260
- this.logger.warn(`Update() is not available on event spans`);
1261
2010
  return;
1262
2011
  }
1263
2012
  if (options?.input !== void 0) {
1264
- this.input = shallowClean(options.input);
2013
+ this.input = deepClean(options.input);
1265
2014
  }
1266
2015
  if (options?.output !== void 0) {
1267
- this.output = shallowClean(options.output);
2016
+ this.output = deepClean(options.output);
1268
2017
  }
1269
2018
  if (options?.attributes) {
1270
- this.attributes = { ...this.attributes, ...shallowClean(options.attributes) };
2019
+ this.attributes = { ...this.attributes, ...deepClean(options.attributes) };
1271
2020
  }
1272
2021
  if (options?.metadata) {
1273
- this.metadata = { ...this.metadata, ...shallowClean(options.metadata) };
2022
+ this.metadata = { ...this.metadata, ...deepClean(options.metadata) };
1274
2023
  }
1275
2024
  }
1276
2025
  get isRootSpan() {
1277
2026
  return !this.parent;
1278
2027
  }
2028
+ get isValid() {
2029
+ return true;
2030
+ }
1279
2031
  async export() {
1280
2032
  return JSON.stringify({
1281
2033
  id: this.id,
@@ -1352,16 +2104,13 @@ var SensitiveDataFilter = class {
1352
2104
  async shutdown() {
1353
2105
  }
1354
2106
  };
1355
- var aiTracingDefaultConfig = {
1356
- serviceName: "mastra-ai-service",
1357
- instanceName: "default",
1358
- sampling: { type: "always" /* ALWAYS */ },
1359
- exporters: [new ConsoleExporter()],
1360
- processors: [new SensitiveDataFilter()]
1361
- };
1362
2107
  var DefaultAITracing = class extends MastraAITracing {
1363
- constructor(config = aiTracingDefaultConfig) {
1364
- super(config);
2108
+ constructor(config) {
2109
+ const configWithDefaults = {
2110
+ ...config,
2111
+ exporters: config.exporters?.length ? config.exporters : [new ConsoleExporter()]
2112
+ };
2113
+ super(configWithDefaults);
1365
2114
  }
1366
2115
  // ============================================================================
1367
2116
  // Abstract Method Implementations
@@ -1377,7 +2126,7 @@ var AGENT_METHODS_TO_WRAP = ["generate", "stream", "generateVNext", "streamVNext
1377
2126
  var WORKFLOW_GETTERS = ["getWorkflow", "getWorkflowById"];
1378
2127
  var WORKFLOW_METHODS_TO_WRAP = ["execute", "createRun", "createRunAsync"];
1379
2128
  function isNoOpSpan(span) {
1380
- return span.constructor.name === "NoOpAISpan" || span.__isNoOp === true || !span.aiTracing;
2129
+ return span.constructor.name === "NoOpAISpan" || span.__isNoOp === true;
1381
2130
  }
1382
2131
  function isMastra(mastra) {
1383
2132
  const hasAgentGetters = AGENT_GETTERS.every((method) => typeof mastra?.[method] === "function");
@@ -1518,6 +2267,6 @@ function wrapRun(run, tracingContext) {
1518
2267
  }
1519
2268
  }
1520
2269
 
1521
- export { AISpanType, AITracingEventType, ConsoleExporter, DefaultAITracing, DefaultExporter, MastraAITracing, SamplingStrategyType, SensitiveDataFilter, aiTracingDefaultConfig, clearAITracingRegistry, getAITracing, getAllAITracing, getDefaultAITracing, getOrCreateSpan, getSelectedAITracing, hasAITracing, isMastra, omitKeys, registerAITracing, selectFields, setAITracingSelector, setupAITracing, shallowClean, shallowCleanArray, shallowCleanObject, shutdownAITracingRegistry, unregisterAITracing, wrapMastra };
1522
- //# sourceMappingURL=chunk-2NKNTPFR.js.map
1523
- //# sourceMappingURL=chunk-2NKNTPFR.js.map
2270
+ export { AISpanType, AITracingEventType, CloudExporter, ConsoleExporter, DefaultAITracing, DefaultExporter, MastraAITracing, SamplingStrategyType, SensitiveDataFilter, checkEvalStorageFields, clearAITracingRegistry, createMastraProxy, deepClean, deepMerge, delay, ensureToolProperties, fetchWithRetry, generateEmptyFromSchema, getAITracing, getAllAITracing, getDefaultAITracing, getOrCreateSpan, getSelectedAITracing, getValidTraceId, hasAITracing, isCoreMessage, isMastra, isUiMessage, isZodType, makeCoreTool, makeCoreToolV5, maskStreamTags, omitKeys, parseFieldKey, parseSqlIdentifier, registerAITracing, resolveSerializedZodOutput, selectFields, setAITracingSelector, setupAITracing, shutdownAITracingRegistry, unregisterAITracing, wrapMastra };
2271
+ //# sourceMappingURL=chunk-W5K2KOZX.js.map
2272
+ //# sourceMappingURL=chunk-W5K2KOZX.js.map