@mastra/core 0.23.0 → 0.23.2-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 (113) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/dist/agent/agent.d.ts.map +1 -1
  3. package/dist/agent/index.cjs +13 -13
  4. package/dist/agent/index.js +2 -2
  5. package/dist/agent/input-processor/index.cjs +6 -6
  6. package/dist/agent/input-processor/index.js +1 -1
  7. package/dist/ai-tracing/index.cjs +36 -36
  8. package/dist/ai-tracing/index.d.ts +1 -1
  9. package/dist/ai-tracing/index.js +1 -1
  10. package/dist/ai-tracing/model-tracing.d.ts +63 -0
  11. package/dist/ai-tracing/model-tracing.d.ts.map +1 -0
  12. package/dist/{chunk-NVDVFJWA.js → chunk-32ZQNYMV.js} +3 -3
  13. package/dist/{chunk-NVDVFJWA.js.map → chunk-32ZQNYMV.js.map} +1 -1
  14. package/dist/{chunk-MRJUTTCU.js → chunk-455LR5KI.js} +3 -3
  15. package/dist/{chunk-MRJUTTCU.js.map → chunk-455LR5KI.js.map} +1 -1
  16. package/dist/{chunk-HANVMC6C.cjs → chunk-4PYSODHR.cjs} +12 -12
  17. package/dist/{chunk-HANVMC6C.cjs.map → chunk-4PYSODHR.cjs.map} +1 -1
  18. package/dist/{chunk-PS4ABZY7.js → chunk-6GDXSCHL.js} +5 -5
  19. package/dist/{chunk-PS4ABZY7.js.map → chunk-6GDXSCHL.js.map} +1 -1
  20. package/dist/{chunk-34WQUECJ.cjs → chunk-CE2Y5BC2.cjs} +52 -52
  21. package/dist/chunk-CE2Y5BC2.cjs.map +1 -0
  22. package/dist/{chunk-4YHU6R7W.cjs → chunk-CL6Z33KH.cjs} +18 -18
  23. package/dist/chunk-CL6Z33KH.cjs.map +1 -0
  24. package/dist/{chunk-ONKGWHY6.js → chunk-DTTOVV72.js} +194 -146
  25. package/dist/chunk-DTTOVV72.js.map +1 -0
  26. package/dist/{chunk-ZWF7AVLU.js → chunk-E3PG7G6E.js} +3 -3
  27. package/dist/{chunk-ZWF7AVLU.js.map → chunk-E3PG7G6E.js.map} +1 -1
  28. package/dist/{chunk-JZ7I64PK.js → chunk-ICGCDCJE.js} +17 -17
  29. package/dist/chunk-ICGCDCJE.js.map +1 -0
  30. package/dist/{chunk-ITCG6QJR.js → chunk-JZGCSEW5.js} +5 -5
  31. package/dist/{chunk-ITCG6QJR.js.map → chunk-JZGCSEW5.js.map} +1 -1
  32. package/dist/{chunk-HFXV34OE.js → chunk-KAEQISOW.js} +3 -3
  33. package/dist/{chunk-HFXV34OE.js.map → chunk-KAEQISOW.js.map} +1 -1
  34. package/dist/{chunk-4XE7GVZM.cjs → chunk-MCASUJWY.cjs} +35 -35
  35. package/dist/chunk-MCASUJWY.cjs.map +1 -0
  36. package/dist/{chunk-JTI6TVDV.cjs → chunk-MJMID7LX.cjs} +4 -4
  37. package/dist/{chunk-JTI6TVDV.cjs.map → chunk-MJMID7LX.cjs.map} +1 -1
  38. package/dist/{chunk-7KYNQSR4.js → chunk-N4DKYHQH.js} +15 -15
  39. package/dist/chunk-N4DKYHQH.js.map +1 -0
  40. package/dist/{chunk-QOTPNUIA.js → chunk-NNBF7NYQ.js} +4 -4
  41. package/dist/{chunk-QOTPNUIA.js.map → chunk-NNBF7NYQ.js.map} +1 -1
  42. package/dist/{chunk-A55YFHFT.js → chunk-NR77P3TK.js} +32 -32
  43. package/dist/chunk-NR77P3TK.js.map +1 -0
  44. package/dist/{chunk-DPE27ECD.cjs → chunk-NTKOVUTG.cjs} +11 -11
  45. package/dist/{chunk-DPE27ECD.cjs.map → chunk-NTKOVUTG.cjs.map} +1 -1
  46. package/dist/{chunk-5P4S4AVU.cjs → chunk-OOMWL2VB.cjs} +4 -4
  47. package/dist/{chunk-5P4S4AVU.cjs.map → chunk-OOMWL2VB.cjs.map} +1 -1
  48. package/dist/{chunk-PDST7KX7.cjs → chunk-P35FNLTQ.cjs} +194 -146
  49. package/dist/chunk-P35FNLTQ.cjs.map +1 -0
  50. package/dist/{chunk-7XAVBWZI.cjs → chunk-SKAKD7UJ.cjs} +12 -12
  51. package/dist/{chunk-7XAVBWZI.cjs.map → chunk-SKAKD7UJ.cjs.map} +1 -1
  52. package/dist/{chunk-VTNVK7HN.cjs → chunk-UZKIGB7M.cjs} +4 -4
  53. package/dist/{chunk-VTNVK7HN.cjs.map → chunk-UZKIGB7M.cjs.map} +1 -1
  54. package/dist/{chunk-TYWQLUF6.cjs → chunk-WCTRQHTG.cjs} +8 -8
  55. package/dist/{chunk-TYWQLUF6.cjs.map → chunk-WCTRQHTG.cjs.map} +1 -1
  56. package/dist/index.cjs +48 -48
  57. package/dist/index.js +8 -8
  58. package/dist/llm/index.cjs +7 -7
  59. package/dist/llm/index.js +1 -1
  60. package/dist/llm/model/model.d.ts.map +1 -1
  61. package/dist/llm/model/model.loop.d.ts.map +1 -1
  62. package/dist/llm/model/provider-registry.d.ts.map +1 -1
  63. package/dist/loop/index.cjs +2 -2
  64. package/dist/loop/index.js +1 -1
  65. package/dist/loop/loop.d.ts +1 -1
  66. package/dist/loop/loop.d.ts.map +1 -1
  67. package/dist/loop/test-utils/options.d.ts.map +1 -1
  68. package/dist/loop/types.d.ts +1 -2
  69. package/dist/loop/types.d.ts.map +1 -1
  70. package/dist/loop/workflows/stream.d.ts +1 -1
  71. package/dist/loop/workflows/stream.d.ts.map +1 -1
  72. package/dist/mastra/index.cjs +2 -2
  73. package/dist/mastra/index.js +1 -1
  74. package/dist/memory/index.cjs +4 -4
  75. package/dist/memory/index.js +1 -1
  76. package/dist/processors/index.cjs +11 -11
  77. package/dist/processors/index.js +1 -1
  78. package/dist/relevance/index.cjs +4 -4
  79. package/dist/relevance/index.js +1 -1
  80. package/dist/scores/index.cjs +9 -9
  81. package/dist/scores/index.js +2 -2
  82. package/dist/scores/scoreTraces/index.cjs +8 -8
  83. package/dist/scores/scoreTraces/index.js +3 -3
  84. package/dist/storage/index.cjs +3 -3
  85. package/dist/storage/index.js +1 -1
  86. package/dist/stream/index.cjs +11 -11
  87. package/dist/stream/index.js +2 -2
  88. package/dist/test-utils/llm-mock.cjs +2 -2
  89. package/dist/test-utils/llm-mock.js +1 -1
  90. package/dist/tools/tool-builder/builder.d.ts.map +1 -1
  91. package/dist/utils.cjs +17 -17
  92. package/dist/utils.js +1 -1
  93. package/dist/workflows/evented/index.cjs +10 -10
  94. package/dist/workflows/evented/index.js +1 -1
  95. package/dist/workflows/execution-engine.d.ts +1 -0
  96. package/dist/workflows/execution-engine.d.ts.map +1 -1
  97. package/dist/workflows/index.cjs +13 -13
  98. package/dist/workflows/index.js +1 -1
  99. package/dist/workflows/legacy/index.cjs +22 -22
  100. package/dist/workflows/legacy/index.js +1 -1
  101. package/dist/workflows/workflow.d.ts +3 -1
  102. package/dist/workflows/workflow.d.ts.map +1 -1
  103. package/package.json +5 -5
  104. package/dist/ai-tracing/chunk-tracing.d.ts +0 -76
  105. package/dist/ai-tracing/chunk-tracing.d.ts.map +0 -1
  106. package/dist/chunk-34WQUECJ.cjs.map +0 -1
  107. package/dist/chunk-4XE7GVZM.cjs.map +0 -1
  108. package/dist/chunk-4YHU6R7W.cjs.map +0 -1
  109. package/dist/chunk-7KYNQSR4.js.map +0 -1
  110. package/dist/chunk-A55YFHFT.js.map +0 -1
  111. package/dist/chunk-JZ7I64PK.js.map +0 -1
  112. package/dist/chunk-ONKGWHY6.js.map +0 -1
  113. package/dist/chunk-PDST7KX7.cjs.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/ai-tracing/types.ts","../src/ai-tracing/spans/base.ts","../src/ai-tracing/spans/default.ts","../src/ai-tracing/spans/no-op.ts","../src/ai-tracing/exporters/base.ts","../src/tools/tool-builder/builder.ts","../src/utils.ts","../src/ai-tracing/exporters/cloud.ts","../src/ai-tracing/exporters/console.ts","../src/ai-tracing/exporters/default.ts","../src/ai-tracing/span_processors/sensitive-data-filter.ts","../src/ai-tracing/registry.ts","../src/ai-tracing/utils.ts","../src/ai-tracing/tracers/base.ts","../src/ai-tracing/tracers/default.ts","../src/ai-tracing/context.ts","../src/ai-tracing/model-tracing.ts"],"names":["AISpanType","InternalSpans","SamplingStrategyType","AITracingEventType","MastraError","ConsoleLogger","LogLevel","MastraBase","isVercelTool","schema","z","convertZodSchemaToAISDKSchema","RuntimeContext","ToolStream","error","logger","validateToolInput","OpenAIReasoningSchemaCompatLayer","OpenAISchemaCompatLayer","GoogleSchemaCompatLayer","AnthropicSchemaCompatLayer","DeepSeekSchemaCompatLayer","MetaSchemaCompatLayer","applyCompatLayer","createHash","jsonSchemaToZod","delay","RegisteredLogger","TransformStream"],"mappings":";;;;;;;;;;;;;;;;;;;AAgBO,IAAK,UAAA,qBAAAA,WAAAA,KAAL;AAEL,EAAAA,YAAA,WAAA,CAAA,GAAY,WAAA;AAEZ,EAAAA,YAAA,SAAA,CAAA,GAAU,SAAA;AAEV,EAAAA,YAAA,kBAAA,CAAA,GAAmB,kBAAA;AAEnB,EAAAA,YAAA,YAAA,CAAA,GAAa,YAAA;AAEb,EAAAA,YAAA,aAAA,CAAA,GAAc,aAAA;AAEd,EAAAA,YAAA,eAAA,CAAA,GAAgB,eAAA;AAEhB,EAAAA,YAAA,eAAA,CAAA,GAAgB,eAAA;AAEhB,EAAAA,YAAA,WAAA,CAAA,GAAY,WAAA;AAEZ,EAAAA,YAAA,cAAA,CAAA,GAAe,cAAA;AAEf,EAAAA,YAAA,eAAA,CAAA,GAAgB,eAAA;AAEhB,EAAAA,YAAA,sBAAA,CAAA,GAAuB,sBAAA;AAEvB,EAAAA,YAAA,2BAAA,CAAA,GAA4B,2BAAA;AAE5B,EAAAA,YAAA,mBAAA,CAAA,GAAoB,mBAAA;AAEpB,EAAAA,YAAA,eAAA,CAAA,GAAgB,eAAA;AAEhB,EAAAA,YAAA,gBAAA,CAAA,GAAiB,gBAAA;AAEjB,EAAAA,YAAA,qBAAA,CAAA,GAAsB,qBAAA;AAhCZ,EAAA,OAAAA,WAAAA;AAAA,CAAA,E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AA,IAAA,CAAK,gBAAA,CAAiB,KAAA,CAAM,IAAA,EAAM,aAAa,CAAA;AAC/C,cAAA;AAAA,YACF;AAAA;AACF,QACF;AAAA,OACD;AAAA,KACH;AAAA,EACF;AACF","file":"chunk-P35FNLTQ.cjs","sourcesContent":["/**\n * AI Tracing interfaces\n */\n\nimport type { MastraError } from '../error';\nimport type { IMastraLogger } from '../logger';\nimport type { RuntimeContext } from '../runtime-context';\nimport type { WorkflowRunStatus, WorkflowStepStatus } from '../workflows';\n\n// ============================================================================\n// Core AI-Specific Span Types\n// ============================================================================\n\n/**\n * AI-specific span types with their associated metadata\n */\nexport enum AISpanType {\n /** Agent run - root span for agent processes */\n AGENT_RUN = 'agent_run',\n /** Generic span for custom operations */\n GENERIC = 'generic',\n /** Model generation with model calls, token usage, prompts, completions */\n MODEL_GENERATION = 'model_generation',\n /** Single model execution step within a generation (one API call) */\n MODEL_STEP = 'model_step',\n /** Individual model streaming chunk/event */\n MODEL_CHUNK = 'model_chunk',\n /** MCP (Model Context Protocol) tool execution */\n MCP_TOOL_CALL = 'mcp_tool_call',\n /** Input or Output Processor execution */\n PROCESSOR_RUN = 'processor_run',\n /** Function/tool execution with inputs, outputs, errors */\n TOOL_CALL = 'tool_call',\n /** Workflow run - root span for workflow processes */\n WORKFLOW_RUN = 'workflow_run',\n /** Workflow step execution with step status, data flow */\n WORKFLOW_STEP = 'workflow_step',\n /** Workflow conditional execution with condition evaluation */\n WORKFLOW_CONDITIONAL = 'workflow_conditional',\n /** Individual condition evaluation within conditional */\n WORKFLOW_CONDITIONAL_EVAL = 'workflow_conditional_eval',\n /** Workflow parallel execution */\n WORKFLOW_PARALLEL = 'workflow_parallel',\n /** Workflow loop execution */\n WORKFLOW_LOOP = 'workflow_loop',\n /** Workflow sleep operation */\n WORKFLOW_SLEEP = 'workflow_sleep',\n /** Workflow wait for event operation */\n WORKFLOW_WAIT_EVENT = 'workflow_wait_event',\n}\n\n// ============================================================================\n// Type-Specific Attributes Interfaces\n// ============================================================================\n\n/**\n * Base attributes that all spans can have\n */\nexport interface AIBaseAttributes {}\n\n/**\n * Agent Run attributes\n */\nexport interface AgentRunAttributes extends AIBaseAttributes {\n /** Agent identifier */\n agentId: string;\n /** Agent Instructions **/\n instructions?: string;\n /** Agent Prompt **/\n prompt?: string;\n /** Available tools for this execution */\n availableTools?: string[];\n /** Maximum steps allowed */\n maxSteps?: number;\n}\n\n/** Token usage statistics - supports both v5 and legacy formats */\nexport interface UsageStats {\n // VNext paths\n inputTokens?: number;\n outputTokens?: number;\n // Legacy format (for backward compatibility)\n promptTokens?: number;\n completionTokens?: number;\n // Common fields\n totalTokens?: number;\n reasoningTokens?: number;\n cachedInputTokens?: number;\n promptCacheHitTokens?: number;\n promptCacheMissTokens?: number;\n}\n\n/**\n * Model Generation attributes\n */\nexport interface ModelGenerationAttributes extends AIBaseAttributes {\n /** Model name (e.g., 'gpt-4', 'claude-3') */\n model?: string;\n /** Model provider (e.g., 'openai', 'anthropic') */\n provider?: string;\n /** Type of result/output this LLM call produced */\n resultType?: 'tool_selection' | 'response_generation' | 'reasoning' | 'planning';\n /** Token usage statistics - supports both v5 and legacy formats */\n usage?: UsageStats;\n /** Model parameters */\n parameters?: {\n maxOutputTokens?: number;\n temperature?: number;\n topP?: number;\n topK?: number;\n presencePenalty?: number;\n frequencyPenalty?: number;\n stopSequences?: string[];\n seed?: number;\n maxRetries?: number;\n abortSignal?: any;\n headers?: Record<string, string | undefined>;\n };\n /** Whether this was a streaming response */\n streaming?: boolean;\n /** Reason the generation finished */\n finishReason?: string;\n}\n\n/**\n * Model Step attributes - for a single model execution within a generation\n */\nexport interface ModelStepAttributes extends AIBaseAttributes {\n /** Index of this step in the generation (0, 1, 2, ...) */\n stepIndex?: number;\n /** Token usage statistics */\n usage?: UsageStats;\n /** Reason this step finished (stop, tool-calls, length, etc.) */\n finishReason?: string;\n /** Should execution continue */\n isContinued?: boolean;\n /** Result warnings */\n warnings?: Record<string, any>;\n}\n\n/**\n * Model Chunk attributes - for individual streaming chunks/events\n */\nexport interface ModelChunkAttributes extends AIBaseAttributes {\n /** Type of chunk (text-delta, reasoning-delta, tool-call, etc.) */\n chunkType?: string;\n /** Sequence number of this chunk in the stream */\n sequenceNumber?: number;\n}\n\n/**\n * Tool Call attributes\n */\nexport interface ToolCallAttributes extends AIBaseAttributes {\n toolId?: string;\n toolType?: string;\n toolDescription?: string;\n success?: boolean;\n}\n\n/**\n * MCP Tool Call attributes\n */\nexport interface MCPToolCallAttributes extends AIBaseAttributes {\n /** Id of the MCP tool/function */\n toolId: string;\n /** MCP server identifier */\n mcpServer: string;\n /** MCP server version */\n serverVersion?: string;\n /** Whether tool execution was successful */\n success?: boolean;\n}\n\n/**\n * Processor attributes\n */\nexport interface ProcessorRunAttributes extends AIBaseAttributes {\n /** Name of the Processor */\n processorName: string;\n /** Processor type (input or output) */\n processorType: 'input' | 'output';\n /** Processor index in the agent */\n processorIndex?: number;\n}\n\n/**\n * Workflow Run attributes\n */\nexport interface WorkflowRunAttributes extends AIBaseAttributes {\n /** Workflow identifier */\n workflowId: string;\n /** Workflow status */\n status?: WorkflowRunStatus;\n}\n\n/**\n * Workflow Step attributes\n */\nexport interface WorkflowStepAttributes extends AIBaseAttributes {\n /** Step identifier */\n stepId: string;\n /** Step status */\n status?: WorkflowStepStatus;\n}\n\n/**\n * Workflow Conditional attributes\n */\nexport interface WorkflowConditionalAttributes extends AIBaseAttributes {\n /** Number of conditions evaluated */\n conditionCount: number;\n /** Which condition indexes evaluated to true */\n truthyIndexes?: number[];\n /** Which steps will be executed */\n selectedSteps?: string[];\n}\n\n/**\n * Workflow Conditional Evaluation attributes\n */\nexport interface WorkflowConditionalEvalAttributes extends AIBaseAttributes {\n /** Index of this condition in the conditional */\n conditionIndex: number;\n /** Result of condition evaluation */\n result?: boolean;\n}\n\n/**\n * Workflow Parallel attributes\n */\nexport interface WorkflowParallelAttributes extends AIBaseAttributes {\n /** Number of parallel branches */\n branchCount: number;\n /** Step IDs being executed in parallel */\n parallelSteps?: string[];\n}\n\n/**\n * Workflow Loop attributes\n */\nexport interface WorkflowLoopAttributes extends AIBaseAttributes {\n /** Type of loop (foreach, dowhile, dountil) */\n loopType?: 'foreach' | 'dowhile' | 'dountil';\n /** Current iteration number (for individual iterations) */\n iteration?: number;\n /** Total iterations (if known) */\n totalIterations?: number;\n /** Number of steps to run concurrently in foreach loop */\n concurrency?: number;\n}\n\n/**\n * Workflow Sleep attributes\n */\nexport interface WorkflowSleepAttributes extends AIBaseAttributes {\n /** Sleep duration in milliseconds */\n durationMs?: number;\n /** Sleep until date */\n untilDate?: Date;\n /** Sleep type */\n sleepType?: 'fixed' | 'dynamic';\n}\n\n/**\n * Workflow Wait Event attributes\n */\nexport interface WorkflowWaitEventAttributes extends AIBaseAttributes {\n /** Event name being waited for */\n eventName?: string;\n /** Timeout in milliseconds */\n timeoutMs?: number;\n /** Whether event was received or timed out */\n eventReceived?: boolean;\n /** Wait duration in milliseconds */\n waitDurationMs?: number;\n}\n\n/**\n * AI-specific span types mapped to their attributes\n */\nexport interface AISpanTypeMap {\n [AISpanType.AGENT_RUN]: AgentRunAttributes;\n [AISpanType.WORKFLOW_RUN]: WorkflowRunAttributes;\n [AISpanType.MODEL_GENERATION]: ModelGenerationAttributes;\n [AISpanType.MODEL_STEP]: ModelStepAttributes;\n [AISpanType.MODEL_CHUNK]: ModelChunkAttributes;\n [AISpanType.TOOL_CALL]: ToolCallAttributes;\n [AISpanType.MCP_TOOL_CALL]: MCPToolCallAttributes;\n [AISpanType.PROCESSOR_RUN]: ProcessorRunAttributes;\n [AISpanType.WORKFLOW_STEP]: WorkflowStepAttributes;\n [AISpanType.WORKFLOW_CONDITIONAL]: WorkflowConditionalAttributes;\n [AISpanType.WORKFLOW_CONDITIONAL_EVAL]: WorkflowConditionalEvalAttributes;\n [AISpanType.WORKFLOW_PARALLEL]: WorkflowParallelAttributes;\n [AISpanType.WORKFLOW_LOOP]: WorkflowLoopAttributes;\n [AISpanType.WORKFLOW_SLEEP]: WorkflowSleepAttributes;\n [AISpanType.WORKFLOW_WAIT_EVENT]: WorkflowWaitEventAttributes;\n [AISpanType.GENERIC]: AIBaseAttributes;\n}\n\n/**\n * Union type for cases that need to handle any span type\n */\nexport type AnyAISpanAttributes = AISpanTypeMap[keyof AISpanTypeMap];\n\n// ============================================================================\n// Span Interfaces\n// ============================================================================\n\n/**\n * Base Span interface\n */\ninterface BaseSpan<TType extends AISpanType> {\n /** Unique span identifier */\n id: string;\n /** OpenTelemetry-compatible trace ID (32 hex chars) - present on all spans */\n traceId: string;\n /** Name of the span */\n name: string;\n /** Type of the span */\n type: TType;\n /** When span started */\n startTime: Date;\n /** When span ended */\n endTime?: Date;\n /** Is an internal span? (spans internal to the operation of mastra) */\n attributes?: AISpanTypeMap[TType];\n /** User-defined metadata */\n metadata?: Record<string, any>;\n /** Input passed at the start of the span */\n input?: any;\n /** Output generated at the end of the span */\n output?: any;\n /** Error information if span failed */\n errorInfo?: {\n message: string;\n id?: string;\n domain?: string;\n category?: string;\n details?: Record<string, any>;\n };\n /** Is an event span? (event occurs at startTime, has no endTime) */\n isEvent: boolean;\n}\n\n/**\n * AI Span interface, used internally for tracing\n */\nexport interface AISpan<TType extends AISpanType> extends BaseSpan<TType> {\n /** Is an internal span? (spans internal to the operation of mastra) */\n isInternal: boolean;\n /** Parent span reference (undefined for root spans) */\n parent?: AnyAISpan;\n /** Pointer to the AITracing instance */\n aiTracing: AITracing;\n /** Trace-level state shared across all spans in this trace */\n traceState?: TraceState;\n\n // Methods for span lifecycle\n /** End the span */\n end(options?: EndSpanOptions<TType>): void;\n\n /** Record an error for the span, optionally end the span as well */\n error(options: ErrorSpanOptions<TType>): void;\n\n /** Update span attributes */\n update(options: UpdateSpanOptions<TType>): void;\n\n /** Create child span - can be any span type independent of parent */\n createChildSpan<TChildType extends AISpanType>(options: ChildSpanOptions<TChildType>): AISpan<TChildType>;\n\n /** Create event span - can be any span type independent of parent */\n createEventSpan<TChildType extends AISpanType>(options: ChildEventOptions<TChildType>): AISpan<TChildType>;\n\n /** Returns `TRUE` if the span is the root span of a trace */\n get isRootSpan(): boolean;\n\n /** Returns `TRUE` if the span is a valid span (not a NO-OP Span) */\n get isValid(): boolean;\n\n /** Get the closest parent spanId that isn't an internal span */\n getParentSpanId(includeInternalSpans?: boolean): string | undefined;\n\n /** Find the closest parent span of a specific type by walking up the parent chain */\n findParent<T extends AISpanType>(spanType: T): AISpan<T> | undefined;\n\n /** Returns a lightweight span ready for export */\n exportSpan(includeInternalSpans?: boolean): ExportedAISpan<TType> | undefined;\n}\n\n/**\n * Exported AI Span interface, used for tracing exporters\n */\nexport interface ExportedAISpan<TType extends AISpanType> extends BaseSpan<TType> {\n /** Parent span id reference (undefined for root spans) */\n parentSpanId?: string;\n /** `TRUE` if the span is the root span of a trace */\n isRootSpan: boolean;\n}\n\n/**\n * Union type for cases that need to handle any span\n */\nexport type AnyAISpan = AISpan<keyof AISpanTypeMap>;\n\n/**\n * Union type for cases that need to handle any exported span\n */\nexport type AnyExportedAISpan = ExportedAISpan<keyof AISpanTypeMap>;\n\n// ============================================================================\n// Tracing Interfaces\n// ============================================================================\n\n/**\n * Primary interface for AI Tracing\n */\nexport interface AITracing {\n /**\n * Get current configuration\n */\n getConfig(): Readonly<Required<TracingConfig>>;\n\n /**\n * Get all exporters\n */\n getExporters(): readonly AITracingExporter[];\n\n /**\n * Get all processors\n */\n getProcessors(): readonly AISpanProcessor[];\n\n /**\n * Get the logger instance (for exporters and other components)\n */\n getLogger(): IMastraLogger;\n\n /**\n * Start a new span of a specific AISpanType\n */\n startSpan<TType extends AISpanType>(options: StartSpanOptions<TType>): AISpan<TType>;\n\n /**\n * Shutdown AI tracing and clean up resources\n */\n shutdown(): Promise<void>;\n\n /**\n * Override setLogger to add AI tracing specific initialization log\n */\n __setLogger(logger: IMastraLogger): void;\n}\n\n// ============================================================================\n// Span Create/Update/Error Option Types\n// ============================================================================\n\ninterface CreateBaseOptions<TType extends AISpanType> {\n /** Span attributes */\n attributes?: AISpanTypeMap[TType];\n /** Span metadata */\n metadata?: Record<string, any>;\n /** Span name */\n name: string;\n /** Span type */\n type: TType;\n /** Policy-level tracing configuration */\n tracingPolicy?: TracingPolicy;\n /** Runtime context for metadata extraction */\n runtimeContext?: RuntimeContext;\n}\n\n/**\n * Options for creating new spans\n */\nexport interface CreateSpanOptions<TType extends AISpanType> extends CreateBaseOptions<TType> {\n /** Input data */\n input?: any;\n /** Output data (for event spans) */\n output?: any;\n /** Parent span */\n parent?: AnyAISpan;\n /** Is an event span? */\n isEvent?: boolean;\n /**\n * Trace ID to use for this span (1-32 hexadecimal characters).\n * Only used for root spans without a parent.\n */\n traceId?: string;\n /**\n * Parent span ID to use for this span (1-16 hexadecimal characters).\n * Only used for root spans without a parent.\n */\n parentSpanId?: string;\n /** Trace-level state shared across all spans in this trace */\n traceState?: TraceState;\n}\n\n/**\n * Options for starting new spans\n */\nexport interface StartSpanOptions<TType extends AISpanType> extends CreateSpanOptions<TType> {\n /**\n * Options passed when using a custom sampler strategy\n */\n customSamplerOptions?: CustomSamplerOptions;\n /** Tracing options for this execution */\n tracingOptions?: TracingOptions;\n}\n\n/**\n * Options for new child spans\n */\nexport interface ChildSpanOptions<TType extends AISpanType> extends CreateBaseOptions<TType> {\n /** Input data */\n input?: any;\n}\n\n/**\n * Options for new child events\n * Event spans have no input, and no endTime\n */\nexport interface ChildEventOptions<TType extends AISpanType> extends CreateBaseOptions<TType> {\n /** Output data */\n output?: any;\n}\n\ninterface UpdateBaseOptions<TType extends AISpanType> {\n /** Span attributes */\n attributes?: Partial<AISpanTypeMap[TType]>;\n /** Span metadata */\n metadata?: Record<string, any>;\n}\n\nexport interface EndSpanOptions<TType extends AISpanType> extends UpdateBaseOptions<TType> {\n /** Output data */\n output?: any;\n}\n\nexport interface UpdateSpanOptions<TType extends AISpanType> extends UpdateBaseOptions<TType> {\n /** Input data */\n input?: any;\n /** Output data */\n output?: any;\n}\n\nexport interface ErrorSpanOptions<TType extends AISpanType> extends UpdateBaseOptions<TType> {\n /** The error associated with the issue */\n error: MastraError | Error;\n /** End the span when true */\n endSpan?: boolean;\n}\n\n// ============================================================================\n// Lifecycle Types\n// ============================================================================\n\n/**\n * Bitwise options to set different types of spans as internal in\n * a workflow or agent execution.\n */\nexport enum InternalSpans {\n /** No spans are marked internal */\n NONE = 0,\n /** Workflow spans are marked internal */\n WORKFLOW = 1 << 0, // 0001\n /** Agent spans are marked internal */\n AGENT = 1 << 1, // 0010\n /** Tool spans are marked internal */\n TOOL = 1 << 2, // 0100\n /** Model spans are marked internal */\n MODEL = 1 << 3, // 1000\n\n /** All spans are marked internal */\n ALL = (1 << 4) - 1, // 1111 (all bits set up to 3)\n}\n\n/**\n * Policy-level tracing configuration applied when creating\n * a workflow or agent. Unlike TracingOptions, which are\n * provided at execution time, policies define persistent rules\n * for how spans are treated across all executions of the\n * workflow/agent.\n */\nexport interface TracingPolicy {\n /**\n * Bitwise options to set different types of spans as Internal in\n * a workflow or agent execution. Internal spans are hidden by\n * default in exported traces.\n */\n internal?: InternalSpans;\n}\n\n/**\n * Trace-level state computed once at the start of a trace\n * and shared by all spans within that trace.\n */\nexport interface TraceState {\n /**\n * RuntimeContext keys to extract as metadata for all spans in this trace.\n * Computed by merging the tracing config's runtimeContextKeys\n * with the per-request runtimeContextKeys.\n */\n runtimeContextKeys: string[];\n}\n\n/**\n * Options passed when starting a new agent or workflow execution\n */\nexport interface TracingOptions {\n /** Metadata to add to the root trace span */\n metadata?: Record<string, any>;\n /**\n * Additional RuntimeContext keys to extract as metadata for this trace.\n * These keys are added to the runtimeContextKeys config.\n * Supports dot notation for nested values (e.g., 'user.id', 'session.data.experimentId').\n */\n runtimeContextKeys?: string[];\n /**\n * Trace ID to use for this execution (1-32 hexadecimal characters).\n * If provided, this trace will be part of the specified trace rather than starting a new one.\n */\n traceId?: string;\n /**\n * Parent span ID to use for this execution (1-16 hexadecimal characters).\n * If provided, the root span will be created as a child of this span.\n */\n parentSpanId?: string;\n}\n\n/**\n * Context for AI tracing that flows through workflow and agent execution\n */\nexport interface TracingContext {\n /** Current AI span for creating child spans and adding metadata */\n currentSpan?: AnyAISpan;\n}\n\n/**\n * Properties returned to the user for working with traces externally.\n */\nexport type TracingProperties = {\n /** Trace ID used on the execution (if the execution was traced). */\n traceId?: string;\n};\n\n// ============================================================================\n// Registry Config Interfaces\n// ============================================================================\n\n/**\n * Configuration for a single tracing instance\n */\nexport interface TracingConfig {\n /** Unique identifier for this config in the ai tracing registry */\n name: string;\n /** Service name for tracing */\n serviceName: string;\n /** Sampling strategy - controls whether tracing is collected (defaults to ALWAYS) */\n sampling?: SamplingStrategy;\n /** Custom exporters */\n exporters?: AITracingExporter[];\n /** Custom processors */\n processors?: AISpanProcessor[];\n /** Set to `true` if you want to see spans internal to the operation of mastra */\n includeInternalSpans?: boolean;\n /**\n * RuntimeContext keys to automatically extract as metadata for all spans\n * created with this tracing configuration.\n * Supports dot notation for nested values.\n */\n runtimeContextKeys?: string[];\n}\n\n/**\n * Complete AI Tracing registry configuration\n */\nexport interface ObservabilityRegistryConfig {\n /** Enables default exporters, with sampling: always, and sensitive data filtering */\n default?: {\n enabled?: boolean;\n };\n /** Map of tracing instance names to their configurations or pre-instantiated instances */\n configs?: Record<string, Omit<TracingConfig, 'name'> | AITracing>;\n /** Optional selector function to choose which tracing instance to use */\n configSelector?: ConfigSelector;\n}\n\n// ============================================================================\n// Sampling Strategy Interfaces\n// ============================================================================\n\n/**\n * Sampling strategy types\n */\nexport enum SamplingStrategyType {\n ALWAYS = 'always',\n NEVER = 'never',\n RATIO = 'ratio',\n CUSTOM = 'custom',\n}\n\n/**\n * Sampling strategy configuration\n */\nexport type SamplingStrategy =\n | { type: SamplingStrategyType.ALWAYS }\n | { type: SamplingStrategyType.NEVER }\n | { type: SamplingStrategyType.RATIO; probability: number }\n | { type: SamplingStrategyType.CUSTOM; sampler: (options?: CustomSamplerOptions) => boolean };\n\n/**\n * Options passed when using a custom sampler strategy\n */\nexport interface CustomSamplerOptions {\n runtimeContext?: RuntimeContext;\n metadata?: Record<string, any>;\n}\n\n// ============================================================================\n// Exporter and Processor Interfaces\n// ============================================================================\n\n/**\n * AI Tracing event types\n */\nexport enum AITracingEventType {\n SPAN_STARTED = 'span_started',\n SPAN_UPDATED = 'span_updated',\n SPAN_ENDED = 'span_ended',\n}\n\n/**\n * Tracing events that can be exported\n */\nexport type AITracingEvent =\n | { type: AITracingEventType.SPAN_STARTED; exportedSpan: AnyExportedAISpan }\n | { type: AITracingEventType.SPAN_UPDATED; exportedSpan: AnyExportedAISpan }\n | { type: AITracingEventType.SPAN_ENDED; exportedSpan: AnyExportedAISpan };\n\n/**\n * Interface for tracing exporters\n */\nexport interface AITracingExporter {\n /** Exporter name */\n name: string;\n\n /** Initialize exporter with tracing configuration */\n init?(config: TracingConfig): void;\n\n /** Set logger (called by AITracing during initialization) */\n __setLogger?(logger: IMastraLogger): void;\n\n /** Export tracing events */\n exportEvent(event: AITracingEvent): Promise<void>;\n\n addScoreToTrace?({\n traceId,\n spanId,\n score,\n reason,\n scorerName,\n metadata,\n }: {\n traceId: string;\n spanId?: string;\n score: number;\n reason?: string;\n scorerName: string;\n metadata?: Record<string, any>;\n }): Promise<void>;\n\n /** Shutdown exporter */\n shutdown(): Promise<void>;\n}\n\n/**\n * Interface for span processors\n */\nexport interface AISpanProcessor {\n /** Processor name */\n name: string;\n /** Process span before export */\n process(span?: AnyAISpan): AnyAISpan | undefined;\n /** Shutdown processor */\n shutdown(): Promise<void>;\n}\n\n// ============================================================================\n// Tracing Config Selector Interfaces\n// ============================================================================\n\n/**\n * Options passed when using a custom tracing config selector\n */\nexport interface ConfigSelectorOptions {\n /** Runtime context */\n runtimeContext?: RuntimeContext;\n}\n\n/**\n * Function to select which AI tracing instance to use for a given span\n * Returns the name of the tracing instance, or undefined to use default\n */\nexport type ConfigSelector = (\n options: ConfigSelectorOptions,\n availableConfigs: ReadonlyMap<string, AITracing>,\n) => string | undefined;\n\n// ============================================================================\n// Tracing Storage Interfaces\n// ============================================================================\n\nexport type TracingStrategy = 'realtime' | 'batch-with-updates' | 'insert-only';\n","import type {\n AISpan,\n AISpanTypeMap,\n AnyAISpan,\n ChildSpanOptions,\n ChildEventOptions,\n EndSpanOptions,\n ErrorSpanOptions,\n UpdateSpanOptions,\n CreateSpanOptions,\n AITracing,\n ExportedAISpan,\n TraceState,\n} from '../types';\n\nimport { AISpanType, InternalSpans } from '../types';\n\n/**\n * Determines if a span type should be considered internal based on flags.\n * Returns false if flags are undefined.\n */\nfunction isSpanInternal(spanType: AISpanType, flags?: InternalSpans): boolean {\n if (flags === undefined || flags === InternalSpans.NONE) {\n return false;\n }\n\n switch (spanType) {\n // Workflow-related spans\n case AISpanType.WORKFLOW_RUN:\n case AISpanType.WORKFLOW_STEP:\n case AISpanType.WORKFLOW_CONDITIONAL:\n case AISpanType.WORKFLOW_CONDITIONAL_EVAL:\n case AISpanType.WORKFLOW_PARALLEL:\n case AISpanType.WORKFLOW_LOOP:\n case AISpanType.WORKFLOW_SLEEP:\n case AISpanType.WORKFLOW_WAIT_EVENT:\n return (flags & InternalSpans.WORKFLOW) !== 0;\n\n // Agent-related spans\n case AISpanType.AGENT_RUN:\n return (flags & InternalSpans.AGENT) !== 0;\n\n // Tool-related spans\n case AISpanType.TOOL_CALL:\n case AISpanType.MCP_TOOL_CALL:\n return (flags & InternalSpans.TOOL) !== 0;\n\n // Model-related spans\n case AISpanType.MODEL_GENERATION:\n case AISpanType.MODEL_STEP:\n case AISpanType.MODEL_CHUNK:\n return (flags & InternalSpans.MODEL) !== 0;\n\n // Default: never internal\n default:\n return false;\n }\n}\n\nexport abstract class BaseAISpan<TType extends AISpanType = any> implements AISpan<TType> {\n public abstract id: string;\n public abstract traceId: string;\n\n public name: string;\n public type: TType;\n public attributes: AISpanTypeMap[TType];\n public parent?: AnyAISpan;\n public startTime: Date;\n public endTime?: Date;\n public isEvent: boolean;\n public isInternal: boolean;\n public aiTracing: AITracing;\n public input?: any;\n public output?: any;\n public errorInfo?: {\n message: string;\n id?: string;\n domain?: string;\n category?: string;\n details?: Record<string, any>;\n };\n public metadata?: Record<string, any>;\n public traceState?: TraceState;\n /** Parent span ID (for root spans that are children of external spans) */\n protected parentSpanId?: string;\n\n constructor(options: CreateSpanOptions<TType>, aiTracing: AITracing) {\n this.name = options.name;\n this.type = options.type;\n this.attributes = deepClean(options.attributes) || ({} as AISpanTypeMap[TType]);\n this.metadata = deepClean(options.metadata);\n this.parent = options.parent;\n this.startTime = new Date();\n this.aiTracing = aiTracing;\n this.isEvent = options.isEvent ?? false;\n this.isInternal = isSpanInternal(this.type, options.tracingPolicy?.internal);\n this.traceState = options.traceState;\n\n if (this.isEvent) {\n // Event spans don't have endTime or input.\n // Event spans are immediately emitted by the BaseAITracing class via the end() event.\n this.output = deepClean(options.output);\n } else {\n this.input = deepClean(options.input);\n }\n }\n\n // Methods for span lifecycle\n /** End the span */\n abstract end(options?: EndSpanOptions<TType>): void;\n\n /** Record an error for the span, optionally end the span as well */\n abstract error(options: ErrorSpanOptions<TType>): void;\n\n /** Update span attributes */\n abstract update(options: UpdateSpanOptions<TType>): void;\n\n createChildSpan<TChildType extends AISpanType>(options: ChildSpanOptions<TChildType>): AISpan<TChildType> {\n return this.aiTracing.startSpan<TChildType>({ ...options, parent: this, isEvent: false });\n }\n\n createEventSpan<TChildType extends AISpanType>(options: ChildEventOptions<TChildType>): AISpan<TChildType> {\n return this.aiTracing.startSpan<TChildType>({ ...options, parent: this, isEvent: true });\n }\n\n /** Returns `TRUE` if the span is the root span of a trace */\n get isRootSpan(): boolean {\n return !this.parent;\n }\n\n /** Returns `TRUE` if the span is a valid span (not a NO-OP Span) */\n abstract get isValid(): boolean;\n\n /** Get the closest parent spanId that isn't an internal span */\n public getParentSpanId(includeInternalSpans?: boolean): string | undefined {\n if (!this.parent) {\n // Return parent span ID if available, otherwise undefined\n return this.parentSpanId;\n }\n if (includeInternalSpans) return this.parent.id;\n if (this.parent.isInternal) return this.parent.getParentSpanId(includeInternalSpans);\n\n return this.parent.id;\n }\n\n /** Find the closest parent span of a specific type by walking up the parent chain */\n public findParent<T extends AISpanType>(spanType: T): AISpan<T> | undefined {\n let current: AnyAISpan | undefined = this.parent;\n\n while (current) {\n if (current.type === spanType) {\n return current as AISpan<T>;\n }\n current = current.parent;\n }\n\n return undefined;\n }\n\n /** Returns a lightweight span ready for export */\n public exportSpan(includeInternalSpans?: boolean): ExportedAISpan<TType> {\n return {\n id: this.id,\n traceId: this.traceId,\n name: this.name,\n type: this.type,\n attributes: this.attributes,\n metadata: this.metadata,\n startTime: this.startTime,\n endTime: this.endTime,\n input: this.input,\n output: this.output,\n errorInfo: this.errorInfo,\n isEvent: this.isEvent,\n isRootSpan: this.isRootSpan,\n parentSpanId: this.getParentSpanId(includeInternalSpans),\n };\n }\n}\n\nconst DEFAULT_KEYS_TO_STRIP = new Set([\n 'logger',\n 'experimental_providerMetadata',\n 'providerMetadata',\n 'steps',\n 'tracingContext',\n]);\nexport interface DeepCleanOptions {\n keysToStrip?: Set<string>;\n maxDepth?: number;\n}\n\n/**\n * Recursively cleans a value by removing circular references and stripping problematic or sensitive keys.\n * Circular references are replaced with \"[Circular]\". Unserializable values are replaced with error messages.\n * Keys like \"logger\" and \"tracingContext\" are stripped by default.\n * A maximum recursion depth is enforced to avoid stack overflow or excessive memory usage.\n *\n * @param value - The value to clean (object, array, primitive, etc.)\n * @param options - Optional configuration:\n * - keysToStrip: Set of keys to remove from objects (default: logger, tracingContext)\n * - maxDepth: Maximum recursion depth before values are replaced with \"[MaxDepth]\" (default: 10)\n * @returns A cleaned version of the input with circular references, specified keys, and overly deep values handled\n */\nexport function deepClean(\n value: any,\n options: DeepCleanOptions = {},\n _seen: WeakSet<any> = new WeakSet(),\n _depth: number = 0,\n): any {\n const { keysToStrip = DEFAULT_KEYS_TO_STRIP, maxDepth = 10 } = options;\n\n if (_depth > maxDepth) {\n return '[MaxDepth]';\n }\n\n if (value === null || typeof value !== 'object') {\n try {\n JSON.stringify(value);\n return value;\n } catch (error) {\n return `[${error instanceof Error ? error.message : String(error)}]`;\n }\n }\n\n if (_seen.has(value)) {\n return '[Circular]';\n }\n\n _seen.add(value);\n\n if (Array.isArray(value)) {\n return value.map(item => deepClean(item, options, _seen, _depth + 1));\n }\n\n const cleaned: Record<string, any> = {};\n for (const [key, val] of Object.entries(value)) {\n if (keysToStrip.has(key)) {\n continue;\n }\n\n try {\n cleaned[key] = deepClean(val, options, _seen, _depth + 1);\n } catch (error) {\n cleaned[key] = `[${error instanceof Error ? error.message : String(error)}]`;\n }\n }\n\n return cleaned;\n}\n","import { MastraError } from '../../error';\nimport type {\n AISpanType,\n AITracing,\n EndSpanOptions,\n ErrorSpanOptions,\n UpdateSpanOptions,\n CreateSpanOptions,\n} from '../types';\nimport { BaseAISpan, deepClean } from './base';\n\nexport class DefaultAISpan<TType extends AISpanType> extends BaseAISpan<TType> {\n public id: string;\n public traceId: string;\n\n constructor(options: CreateSpanOptions<TType>, aiTracing: AITracing) {\n super(options, aiTracing);\n this.id = generateSpanId();\n\n // Set trace ID based on context:\n if (options.parent) {\n // Child span inherits trace ID from parent span\n this.traceId = options.parent.traceId;\n } else if (options.traceId) {\n // Root span with provided trace ID\n if (isValidTraceId(options.traceId)) {\n this.traceId = options.traceId;\n } else {\n console.error(\n `[Mastra Tracing] Invalid traceId: must be 1-32 hexadecimal characters, got \"${options.traceId}\". Generating new trace ID.`,\n );\n this.traceId = generateTraceId();\n }\n } else {\n // Root span without provided trace ID - generate new\n this.traceId = generateTraceId();\n }\n\n // Set parent span ID if provided\n if (!options.parent && options.parentSpanId) {\n if (isValidSpanId(options.parentSpanId)) {\n this.parentSpanId = options.parentSpanId;\n } else {\n console.error(\n `[Mastra Tracing] Invalid parentSpanId: must be 1-16 hexadecimal characters, got \"${options.parentSpanId}\". Ignoring parent span ID.`,\n );\n }\n }\n }\n\n end(options?: EndSpanOptions<TType>): void {\n if (this.isEvent) {\n return;\n }\n this.endTime = new Date();\n if (options?.output !== undefined) {\n this.output = deepClean(options.output);\n }\n if (options?.attributes) {\n this.attributes = { ...this.attributes, ...deepClean(options.attributes) };\n }\n if (options?.metadata) {\n this.metadata = { ...this.metadata, ...deepClean(options.metadata) };\n }\n // Tracing events automatically handled by base class\n }\n\n error(options: ErrorSpanOptions<TType>): void {\n if (this.isEvent) {\n return;\n }\n\n const { error, endSpan = true, attributes, metadata } = options;\n\n this.errorInfo =\n error instanceof MastraError\n ? {\n id: error.id,\n details: error.details,\n category: error.category,\n domain: error.domain,\n message: error.message,\n }\n : {\n message: error.message,\n };\n\n // Update attributes if provided\n if (attributes) {\n this.attributes = { ...this.attributes, ...deepClean(attributes) };\n }\n if (metadata) {\n this.metadata = { ...this.metadata, ...deepClean(metadata) };\n }\n\n if (endSpan) {\n this.end();\n } else {\n // Trigger span update event when not ending the span\n this.update({});\n }\n }\n\n update(options: UpdateSpanOptions<TType>): void {\n if (this.isEvent) {\n return;\n }\n\n if (options.input !== undefined) {\n this.input = deepClean(options.input);\n }\n if (options.output !== undefined) {\n this.output = deepClean(options.output);\n }\n if (options.attributes) {\n this.attributes = { ...this.attributes, ...deepClean(options.attributes) };\n }\n if (options.metadata) {\n this.metadata = { ...this.metadata, ...deepClean(options.metadata) };\n }\n // Tracing events automatically handled by base class\n }\n\n get isValid(): boolean {\n return true;\n }\n\n async export(): Promise<string> {\n return JSON.stringify({\n spanId: this.id,\n traceId: this.traceId,\n startTime: this.startTime,\n endTime: this.endTime,\n attributes: this.attributes,\n metadata: this.metadata,\n });\n }\n}\n\n/**\n * Generate OpenTelemetry-compatible span ID (64-bit, 16 hex chars)\n */\nfunction generateSpanId(): string {\n // Generate 8 random bytes (64 bits) in hex format\n const bytes = new Uint8Array(8);\n if (typeof crypto !== 'undefined' && crypto.getRandomValues) {\n crypto.getRandomValues(bytes);\n } else {\n // Fallback for environments without crypto.getRandomValues\n for (let i = 0; i < 8; i++) {\n bytes[i] = Math.floor(Math.random() * 256);\n }\n }\n return Array.from(bytes, byte => byte.toString(16).padStart(2, '0')).join('');\n}\n\n/**\n * Generate OpenTelemetry-compatible trace ID (128-bit, 32 hex chars)\n */\nfunction generateTraceId(): string {\n // Generate 16 random bytes (128 bits) in hex format\n const bytes = new Uint8Array(16);\n if (typeof crypto !== 'undefined' && crypto.getRandomValues) {\n crypto.getRandomValues(bytes);\n } else {\n // Fallback for environments without crypto.getRandomValues\n for (let i = 0; i < 16; i++) {\n bytes[i] = Math.floor(Math.random() * 256);\n }\n }\n return Array.from(bytes, byte => byte.toString(16).padStart(2, '0')).join('');\n}\n\n/**\n * Validate OpenTelemetry-compatible trace ID (1-32 hex characters)\n */\nfunction isValidTraceId(traceId: string): boolean {\n return /^[0-9a-f]{1,32}$/i.test(traceId);\n}\n\n/**\n * Validate OpenTelemetry-compatible span ID (1-16 hex characters)\n */\nfunction isValidSpanId(spanId: string): boolean {\n return /^[0-9a-f]{1,16}$/i.test(spanId);\n}\n","/**\n * No Op Implementation for MastraAITracing\n */\n\nimport type {\n AITracing,\n AISpanType,\n CreateSpanOptions,\n EndSpanOptions,\n UpdateSpanOptions,\n ErrorSpanOptions,\n} from '../types';\nimport { BaseAISpan } from './base';\n\nexport class NoOpAISpan<TType extends AISpanType = any> extends BaseAISpan<TType> {\n public id: string;\n public traceId: string;\n\n constructor(options: CreateSpanOptions<TType>, aiTracing: AITracing) {\n super(options, aiTracing);\n this.id = 'no-op';\n this.traceId = 'no-op-trace';\n }\n\n end(_options?: EndSpanOptions<TType>): void {}\n\n error(_options: ErrorSpanOptions<TType>): void {}\n\n update(_options: UpdateSpanOptions<TType>): void {}\n\n get isValid(): boolean {\n return false;\n }\n}\n","/**\n * Base Exporter for AI Tracing\n *\n * Provides common functionality shared by all AI tracing exporters:\n * - Logger initialization with proper Mastra logger support\n * - Disabled state management\n * - Graceful shutdown lifecycle\n */\n\nimport { ConsoleLogger, LogLevel } from '../../logger';\nimport type { IMastraLogger } from '../../logger';\nimport type { AITracingEvent, AITracingExporter } from '../types';\n\n/**\n * Base configuration that all exporters should support\n */\nexport interface BaseExporterConfig {\n /** Optional Mastra logger instance */\n logger?: IMastraLogger;\n /** Log level for the exporter (defaults to INFO) - accepts both enum and string */\n logLevel?: LogLevel | 'debug' | 'info' | 'warn' | 'error';\n}\n\n/**\n * Abstract base class for AI tracing exporters\n *\n * Handles common concerns:\n * - Logger setup with proper Mastra logger\n * - Disabled state management\n * - Basic lifecycle methods\n *\n * @example\n * ```typescript\n * class MyExporter extends BaseExporter {\n * name = 'my-exporter';\n *\n * constructor(config: MyExporterConfig) {\n * super(config);\n *\n * if (!config.apiKey) {\n * this.setDisabled('Missing API key');\n * return;\n * }\n *\n * // Initialize exporter-specific logic\n * }\n *\n * async _exportEvent(event: AITracingEvent): Promise<void> {\n * // Export logic\n * }\n * }\n * ```\n */\nexport abstract class BaseExporter implements AITracingExporter {\n /** Exporter name - must be implemented by subclasses */\n abstract name: string;\n\n /** Mastra logger instance */\n protected logger: IMastraLogger;\n\n /** Whether this exporter is disabled */\n protected isDisabled: boolean = false;\n\n /**\n * Initialize the base exporter with logger\n */\n constructor(config: BaseExporterConfig = {}) {\n // Map string log level to LogLevel enum if needed\n const logLevel = this.resolveLogLevel(config.logLevel);\n // Use constructor name as fallback since this.name isn't set yet (subclass initializes it)\n this.logger = config.logger ?? new ConsoleLogger({ level: logLevel, name: this.constructor.name });\n }\n\n /**\n * Set the logger for the exporter (called by Mastra/AITracing during initialization)\n */\n __setLogger(logger: IMastraLogger): void {\n this.logger = logger;\n // Use this.name here since it's guaranteed to be set by the subclass at this point\n this.logger.debug(`Logger updated for exporter [name=${this.name}]`);\n }\n\n /**\n * Convert string log level to LogLevel enum\n */\n private resolveLogLevel(logLevel?: LogLevel | 'debug' | 'info' | 'warn' | 'error'): LogLevel {\n if (!logLevel) {\n return LogLevel.INFO;\n }\n\n // If already a LogLevel enum, return as-is\n if (typeof logLevel === 'number') {\n return logLevel;\n }\n\n // Map string to enum\n const logLevelMap: Record<string, LogLevel> = {\n debug: LogLevel.DEBUG,\n info: LogLevel.INFO,\n warn: LogLevel.WARN,\n error: LogLevel.ERROR,\n };\n\n return logLevelMap[logLevel] ?? LogLevel.INFO;\n }\n\n /**\n * Mark the exporter as disabled and log a message\n *\n * @param reason - Reason why the exporter is disabled\n */\n protected setDisabled(reason: string): void {\n this.isDisabled = true;\n this.logger.warn(`${this.name} disabled: ${reason}`);\n }\n\n /**\n * Export a tracing event\n *\n * This method checks if the exporter is disabled before calling _exportEvent.\n * Subclasses should implement _exportEvent instead of overriding this method.\n */\n async exportEvent(event: AITracingEvent): Promise<void> {\n if (this.isDisabled) {\n return;\n }\n await this._exportEvent(event);\n }\n\n /**\n * Export a tracing event - must be implemented by subclasses\n *\n * This method is called by exportEvent after checking if the exporter is disabled.\n */\n protected abstract _exportEvent(event: AITracingEvent): Promise<void>;\n\n /**\n * Optional initialization hook called after Mastra is fully configured\n */\n init?(_config?: any): void;\n\n /**\n * Optional method to add scores to traces\n */\n addScoreToTrace?(_args: {\n traceId: string;\n spanId?: string;\n score: number;\n reason?: string;\n scorerName: string;\n metadata?: Record<string, any>;\n }): Promise<void>;\n\n /**\n * Shutdown the exporter and clean up resources\n *\n * Default implementation just logs. Override to add custom cleanup.\n */\n async shutdown(): Promise<void> {\n this.logger.info(`${this.name} shutdown complete`);\n }\n}\n","import type { ToolCallOptions, ProviderDefinedTool } from '@internal/external-types';\nimport {\n OpenAIReasoningSchemaCompatLayer,\n OpenAISchemaCompatLayer,\n GoogleSchemaCompatLayer,\n AnthropicSchemaCompatLayer,\n DeepSeekSchemaCompatLayer,\n MetaSchemaCompatLayer,\n applyCompatLayer,\n convertZodSchemaToAISDKSchema,\n} from '@mastra/schema-compat';\nimport type { ToolExecutionOptions } from 'ai';\nimport { z } from 'zod';\nimport { AISpanType, wrapMastra } from '../../ai-tracing';\nimport { MastraBase } from '../../base';\nimport { ErrorCategory, MastraError, ErrorDomain } from '../../error';\nimport { RuntimeContext } from '../../runtime-context';\nimport { isVercelTool } from '../../tools/toolchecks';\nimport type { ToolOptions } from '../../utils';\nimport { ToolStream } from '../stream';\nimport type { CoreTool, MastraToolInvocationOptions, ToolAction, VercelTool, VercelToolV5 } from '../types';\nimport { validateToolInput } from '../validation';\n\n/**\n * Types that can be converted to Mastra tools.\n * Includes provider-defined tools from external packages via ProviderDefinedTool.\n */\nexport type ToolToConvert = VercelTool | ToolAction<any, any, any> | VercelToolV5 | ProviderDefinedTool;\nexport type LogType = 'tool' | 'toolset' | 'client-tool';\n\ninterface LogOptions {\n agentName?: string;\n toolName: string;\n type?: 'tool' | 'toolset' | 'client-tool';\n}\n\ninterface LogMessageOptions {\n start: string;\n error: string;\n}\n\nexport class CoreToolBuilder extends MastraBase {\n private originalTool: ToolToConvert;\n private options: ToolOptions;\n private logType?: LogType;\n\n constructor(input: { originalTool: ToolToConvert; options: ToolOptions; logType?: LogType }) {\n super({ name: 'CoreToolBuilder' });\n this.originalTool = input.originalTool;\n this.options = input.options;\n this.logType = input.logType;\n }\n\n // Helper to get parameters based on tool type\n private getParameters = () => {\n if (isVercelTool(this.originalTool)) {\n // Handle both 'parameters' (v4) and 'inputSchema' (v5) properties\n // Also handle case where the schema is a function that returns a schema\n let schema =\n this.originalTool.parameters ??\n ('inputSchema' in this.originalTool ? (this.originalTool as any).inputSchema : undefined) ??\n z.object({});\n\n // If schema is a function, call it to get the actual schema\n if (typeof schema === 'function') {\n schema = schema();\n }\n\n return schema;\n }\n\n // For Mastra tools, inputSchema might also be a function\n let schema = this.originalTool.inputSchema ?? z.object({});\n\n // If schema is a function, call it to get the actual schema\n if (typeof schema === 'function') {\n schema = schema();\n }\n\n return schema;\n };\n\n private getOutputSchema = () => {\n if ('outputSchema' in this.originalTool) {\n let schema = this.originalTool.outputSchema;\n\n // If schema is a function, call it to get the actual schema\n if (typeof schema === 'function') {\n schema = schema();\n }\n\n return schema;\n }\n return null;\n };\n\n // For provider-defined tools, we need to include all required properties\n private buildProviderTool(tool: ToolToConvert): (CoreTool & { id: `${string}.${string}` }) | undefined {\n if (\n 'type' in tool &&\n tool.type === 'provider-defined' &&\n 'id' in tool &&\n typeof tool.id === 'string' &&\n tool.id.includes('.')\n ) {\n const parameters = this.getParameters();\n const outputSchema = this.getOutputSchema();\n\n return {\n type: 'provider-defined' as const,\n id: tool.id as `${string}.${string}`,\n args: ('args' in this.originalTool ? this.originalTool.args : {}) as Record<string, unknown>,\n description: tool.description,\n parameters: parameters.jsonSchema ? parameters : convertZodSchemaToAISDKSchema(parameters),\n ...(outputSchema\n ? { outputSchema: outputSchema.jsonSchema ? outputSchema : convertZodSchemaToAISDKSchema(outputSchema) }\n : {}),\n execute: this.originalTool.execute\n ? this.createExecute(\n this.originalTool,\n { ...this.options, description: this.originalTool.description },\n this.logType,\n )\n : undefined,\n };\n }\n\n return undefined;\n }\n\n private createLogMessageOptions({ agentName, toolName, type }: LogOptions): LogMessageOptions {\n // If no agent name, use default format\n if (!agentName) {\n return {\n start: `Executing tool ${toolName}`,\n error: `Failed tool execution`,\n };\n }\n\n const prefix = `[Agent:${agentName}]`;\n const toolType = type === 'toolset' ? 'toolset' : 'tool';\n\n return {\n start: `${prefix} - Executing ${toolType} ${toolName}`,\n error: `${prefix} - Failed ${toolType} execution`,\n };\n }\n\n private createExecute(\n tool: ToolToConvert,\n options: ToolOptions,\n logType?: 'tool' | 'toolset' | 'client-tool',\n processedSchema?: z.ZodTypeAny,\n ) {\n // dont't add memory or mastra to logging\n const { logger, mastra: _mastra, memory: _memory, runtimeContext, model, ...rest } = options;\n const logModelObject = {\n modelId: model?.modelId,\n provider: model?.provider,\n specificationVersion: model?.specificationVersion,\n };\n\n const { start, error } = this.createLogMessageOptions({\n agentName: options.agentName,\n toolName: options.name,\n type: logType,\n });\n\n const execFunction = async (args: unknown, execOptions: MastraToolInvocationOptions) => {\n // Prefer execution-time tracingContext (passed at runtime for VNext methods)\n // Fall back to build-time context for Legacy methods (AI SDK v4 doesn't support passing custom options)\n const tracingContext = execOptions.tracingContext || options.tracingContext;\n\n // Create tool span if we have a current span available\n const toolSpan = tracingContext?.currentSpan?.createChildSpan({\n type: AISpanType.TOOL_CALL,\n name: `tool: '${options.name}'`,\n input: args,\n attributes: {\n toolId: options.name,\n toolDescription: options.description,\n toolType: logType || 'tool',\n },\n tracingPolicy: options.tracingPolicy,\n });\n\n try {\n let result;\n\n if (isVercelTool(tool)) {\n // Handle Vercel tools (AI SDK tools)\n result = await tool?.execute?.(args, execOptions as ToolExecutionOptions);\n } else {\n // Handle Mastra tools - wrap mastra instance with tracing context for context propagation\n\n /**\n * MASTRA INSTANCE TYPES IN TOOL EXECUTION:\n *\n * Full Mastra & MastraPrimitives (has getAgent, getWorkflow, etc.):\n * - Auto-generated workflow tools from agent.getWorkflows()\n * - These get this.#mastra directly and can be wrapped\n *\n * MastraPrimitives only (limited interface):\n * - Memory tools (from memory.getTools())\n * - Assigned tools (agent.tools)\n * - Toolset tools (from toolsets)\n * - Client tools (passed as tools in generate/stream options)\n * - These get mastraProxy and have limited functionality\n *\n * TODO: Consider providing full Mastra instance to more tool types for enhanced functionality\n */\n // Wrap mastra with tracing context - wrapMastra will handle whether it's a full instance or primitives\n const wrappedMastra = options.mastra ? wrapMastra(options.mastra, { currentSpan: toolSpan }) : options.mastra;\n\n result = await tool?.execute?.(\n {\n context: args,\n threadId: options.threadId,\n resourceId: options.resourceId,\n mastra: wrappedMastra,\n memory: options.memory,\n runId: options.runId,\n runtimeContext: options.runtimeContext ?? new RuntimeContext(),\n writer: new ToolStream(\n {\n prefix: 'tool',\n callId: execOptions.toolCallId,\n name: options.name,\n runId: options.runId!,\n },\n options.writableStream || execOptions.writableStream,\n ),\n tracingContext: { currentSpan: toolSpan },\n },\n execOptions as ToolExecutionOptions & ToolCallOptions,\n );\n }\n\n toolSpan?.end({ output: result });\n return result ?? undefined;\n } catch (error) {\n toolSpan?.error({ error: error as Error });\n throw error;\n }\n };\n\n return async (args: unknown, execOptions?: MastraToolInvocationOptions) => {\n let logger = options.logger || this.logger;\n try {\n logger.debug(start, { ...rest, model: logModelObject, args });\n\n // Validate input parameters if schema exists\n // Use the processed schema for validation if available, otherwise fall back to original\n const parameters = processedSchema || this.getParameters();\n const { data, error } = validateToolInput(parameters, args, options.name);\n if (error) {\n logger.warn(`Tool input validation failed for '${options.name}'`, {\n toolName: options.name,\n errors: error.validationErrors,\n args,\n });\n return error;\n }\n // Use validated/transformed data\n args = data;\n\n // there is a small delay in stream output so we add an immediate to ensure the stream is ready\n return await new Promise((resolve, reject) => {\n setImmediate(async () => {\n try {\n const result = await execFunction(args, execOptions!);\n resolve(result);\n } catch (err) {\n reject(err);\n }\n });\n });\n } catch (err) {\n const mastraError = new MastraError(\n {\n id: 'TOOL_EXECUTION_FAILED',\n domain: ErrorDomain.TOOL,\n category: ErrorCategory.USER,\n details: {\n errorMessage: String(error),\n argsJson: JSON.stringify(args),\n model: model?.modelId ?? '',\n },\n },\n err,\n );\n logger.trackException(mastraError);\n logger.error(error, { ...rest, model: logModelObject, error: mastraError, args });\n return mastraError;\n }\n };\n }\n\n buildV5() {\n const builtTool = this.build();\n\n if (!builtTool.parameters) {\n throw new Error('Tool parameters are required');\n }\n\n const base = {\n ...builtTool,\n inputSchema: builtTool.parameters,\n onInputStart: 'onInputStart' in this.originalTool ? this.originalTool.onInputStart : undefined,\n onInputDelta: 'onInputDelta' in this.originalTool ? this.originalTool.onInputDelta : undefined,\n onInputAvailable: 'onInputAvailable' in this.originalTool ? this.originalTool.onInputAvailable : undefined,\n };\n\n // For provider-defined tools, exclude execute and add name as per v5 spec\n if (builtTool.type === 'provider-defined') {\n const { execute, parameters, ...rest } = base;\n const name = builtTool.id.split('.')[1] || builtTool.id;\n return {\n ...rest,\n type: builtTool.type,\n id: builtTool.id,\n name,\n args: builtTool.args,\n } satisfies VercelToolV5;\n }\n\n return base as VercelToolV5;\n }\n\n build(): CoreTool {\n const providerTool = this.buildProviderTool(this.originalTool);\n if (providerTool) {\n return providerTool;\n }\n\n const model = this.options.model;\n\n const schemaCompatLayers = [];\n\n if (model) {\n const supportsStructuredOutputs =\n model.specificationVersion !== 'v2' ? (model.supportsStructuredOutputs ?? false) : false;\n\n const modelInfo = {\n modelId: model.modelId,\n supportsStructuredOutputs,\n provider: model.provider,\n };\n\n schemaCompatLayers.push(\n new OpenAIReasoningSchemaCompatLayer(modelInfo),\n new OpenAISchemaCompatLayer(modelInfo),\n new GoogleSchemaCompatLayer(modelInfo),\n new AnthropicSchemaCompatLayer(modelInfo),\n new DeepSeekSchemaCompatLayer(modelInfo),\n new MetaSchemaCompatLayer(modelInfo),\n );\n }\n\n // Apply schema compatibility to get both the transformed Zod schema (for validation)\n // and the AI SDK Schema (for the LLM)\n let processedZodSchema: z.ZodTypeAny | undefined;\n let processedSchema;\n\n const originalSchema = this.getParameters();\n\n // Find the first applicable compatibility layer\n const applicableLayer = schemaCompatLayers.find(layer => layer.shouldApply());\n\n if (applicableLayer && originalSchema) {\n // Get the transformed Zod schema (with constraints removed/modified)\n processedZodSchema = applicableLayer.processZodType(originalSchema);\n // Convert to AI SDK Schema for the LLM\n processedSchema = applyCompatLayer({\n schema: originalSchema,\n compatLayers: schemaCompatLayers,\n mode: 'aiSdkSchema',\n });\n } else {\n // No compatibility layer applies, use original schema\n processedZodSchema = originalSchema;\n processedSchema = applyCompatLayer({\n schema: originalSchema,\n compatLayers: schemaCompatLayers,\n mode: 'aiSdkSchema',\n });\n }\n\n let processedOutputSchema;\n\n if (this.getOutputSchema()) {\n processedOutputSchema = applyCompatLayer({\n schema: this.getOutputSchema(),\n compatLayers: schemaCompatLayers,\n mode: 'aiSdkSchema',\n });\n }\n\n const definition = {\n type: 'function' as const,\n description: this.originalTool.description,\n parameters: this.getParameters(),\n outputSchema: this.getOutputSchema(),\n requireApproval: this.options.requireApproval,\n execute: this.originalTool.execute\n ? this.createExecute(\n this.originalTool,\n { ...this.options, description: this.originalTool.description },\n this.logType,\n processedZodSchema, // Pass the processed Zod schema for validation\n )\n : undefined,\n };\n\n return {\n ...definition,\n id: 'id' in this.originalTool ? this.originalTool.id : undefined,\n parameters: processedSchema,\n outputSchema: processedOutputSchema,\n };\n }\n}\n","import { createHash } from 'crypto';\nimport type { WritableStream } from 'stream/web';\nimport type { CoreMessage } from 'ai';\nimport jsonSchemaToZod from 'json-schema-to-zod';\nimport { z } from 'zod';\nimport type { MastraPrimitives } from './action';\nimport type { ToolsInput } from './agent';\nimport type { TracingContext, TracingPolicy } from './ai-tracing';\nimport type { MastraLanguageModel } from './llm/model/shared.types';\nimport type { IMastraLogger } from './logger';\nimport type { Mastra } from './mastra';\nimport type { AiMessageType, MastraMemory } from './memory';\nimport type { RuntimeContext } from './runtime-context';\nimport type { ChunkType } from './stream/types';\nimport type { CoreTool, VercelTool, VercelToolV5 } from './tools';\nimport { CoreToolBuilder } from './tools/tool-builder/builder';\nimport type { ToolToConvert } from './tools/tool-builder/builder';\nimport { isVercelTool } from './tools/toolchecks';\n\nexport const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));\n\n/**\n * Deep merges two objects, recursively merging nested objects and arrays\n */\nexport function deepMerge<T extends object = object>(target: T, source: Partial<T>): T {\n const output = { ...target };\n\n if (!source) return output;\n\n Object.keys(source).forEach(key => {\n const targetValue = output[key as keyof T];\n const sourceValue = source[key as keyof T];\n\n if (Array.isArray(targetValue) && Array.isArray(sourceValue)) {\n (output as any)[key] = sourceValue;\n } else if (\n sourceValue instanceof Object &&\n targetValue instanceof Object &&\n !Array.isArray(sourceValue) &&\n !Array.isArray(targetValue)\n ) {\n (output as any)[key] = deepMerge(targetValue, sourceValue as T);\n } else if (sourceValue !== undefined) {\n (output as any)[key] = sourceValue;\n }\n });\n\n return output;\n}\n\nexport function generateEmptyFromSchema(schema: string) {\n try {\n const parsedSchema = JSON.parse(schema);\n if (!parsedSchema || parsedSchema.type !== 'object' || !parsedSchema.properties) return {};\n const obj: Record<string, any> = {};\n const TYPE_DEFAULTS = {\n string: '',\n array: [],\n object: {},\n number: 0,\n integer: 0,\n boolean: false,\n };\n for (const [key, prop] of Object.entries<any>(parsedSchema.properties)) {\n obj[key] = TYPE_DEFAULTS[prop.type as keyof typeof TYPE_DEFAULTS] ?? null;\n }\n return obj;\n } catch {\n return {};\n }\n}\n\nexport interface TagMaskOptions {\n /** Called when masking begins */\n onStart?: () => void;\n /** Called when masking ends */\n onEnd?: () => void;\n /** Called for each chunk that is masked */\n onMask?: (chunk: string) => void;\n}\n\n/**\n * Transforms a stream by masking content between XML tags.\n * @param stream Input stream to transform\n * @param tag Tag name to mask between (e.g. for <foo>...</foo>, use 'foo')\n * @param options Optional configuration for masking behavior\n */\nexport async function* maskStreamTags(\n stream: AsyncIterable<string>,\n tag: string,\n options: TagMaskOptions = {},\n): AsyncIterable<string> {\n const { onStart, onEnd, onMask } = options;\n const openTag = `<${tag}>`;\n const closeTag = `</${tag}>`;\n\n let buffer = '';\n let fullContent = '';\n let isMasking = false;\n let isBuffering = false;\n\n // used for checking in chunks that include tags or partial tags + some other non-tag text\n // eg: \"o <tag_name\" or \"name> w\", can trim before-start to get \"<tag_name\" or after-end to get \"name>\"\n const trimOutsideDelimiter = (text: string, delimiter: string, trim: 'before-start' | 'after-end') => {\n if (!text.includes(delimiter)) {\n return text;\n }\n\n const parts = text.split(delimiter);\n\n if (trim === `before-start`) {\n return `${delimiter}${parts[1]}`;\n }\n\n return `${parts[0]}${delimiter}`;\n };\n\n // Helper to check if text starts with pattern (ignoring whitespace)\n // When checking partial tags: startsWith(buffer, openTag) checks if buffer could be start of tag\n // When checking full tags: startsWith(chunk, openTag) checks if chunk starts with full tag\n const startsWith = (text: string, pattern: string) => {\n // check start of opening tag\n if (pattern.includes(openTag.substring(0, 3))) {\n // our pattern for checking the start is always based on xml-like tags\n // if the pattern looks like our opening tag and the pattern also includes\n // some other chunked text before it, we just wanted to check the xml part of the pattern\n pattern = trimOutsideDelimiter(pattern, `<`, `before-start`);\n }\n\n return text.trim().startsWith(pattern.trim());\n };\n\n for await (const chunk of stream) {\n fullContent += chunk;\n\n if (isBuffering) buffer += chunk;\n\n const chunkHasTag = startsWith(chunk, openTag);\n const bufferHasTag = !chunkHasTag && isBuffering && startsWith(openTag, buffer);\n\n let toYieldBeforeMaskedStartTag = ``;\n // Check if we should start masking chunks\n if (!isMasking && (chunkHasTag || bufferHasTag)) {\n isMasking = true;\n isBuffering = false;\n\n // check if the buffered text includes text before the start tag. ex \"o <tag_name\", \"o\" should be yielded and not masked\n const taggedTextToMask = trimOutsideDelimiter(buffer, `<`, `before-start`);\n if (taggedTextToMask !== buffer.trim()) {\n toYieldBeforeMaskedStartTag = buffer.replace(taggedTextToMask, ``);\n }\n\n buffer = '';\n onStart?.();\n }\n\n // Check if we should start buffering (looks like part of the opening tag but it's not the full <tag> yet eg <ta - could be <table> but we don't know yet)\n if (!isMasking && !isBuffering && startsWith(openTag, chunk) && chunk.trim() !== '') {\n isBuffering = true;\n buffer += chunk;\n continue;\n }\n\n // We're buffering, need to check again if our buffer has deviated from the opening <tag> eg <tag2>\n if (isBuffering && buffer && !startsWith(openTag, buffer)) {\n yield buffer;\n buffer = '';\n isBuffering = false;\n continue;\n }\n\n // Check if we should stop masking chunks (since the content includes the closing </tag>)\n if (isMasking && fullContent.includes(closeTag)) {\n onMask?.(chunk);\n onEnd?.();\n isMasking = false;\n const lastFullContent = fullContent;\n fullContent = ``; // reset to handle streams with multiple full tags that have text inbetween\n\n // check to see if we have a partial chunk outside the close tag. if we do we need to yield it so it isn't swallowed with the masked text\n const textUntilEndTag = trimOutsideDelimiter(lastFullContent, closeTag, 'after-end');\n if (textUntilEndTag !== lastFullContent) {\n yield lastFullContent.replace(textUntilEndTag, ``);\n }\n\n continue;\n }\n\n // We're currently masking chunks inside a <tag>\n if (isMasking) {\n onMask?.(chunk);\n // in the case that there was a chunk that included a tag to mask and some other text, ex \"o <tag_name\" we need to still yield the\n // text before the tag (\"o \") so it's not swallowed with the masked text\n if (toYieldBeforeMaskedStartTag) {\n yield toYieldBeforeMaskedStartTag;\n }\n continue;\n }\n\n // default yield the chunk\n yield chunk;\n }\n}\n\n/**\n * Resolve serialized zod output - This function takes the string output ot the `jsonSchemaToZod` function\n * and instantiates the zod object correctly.\n *\n * @param schema - serialized zod object\n * @returns resolved zod object\n */\nexport function resolveSerializedZodOutput(schema: string): z.ZodType {\n // Creates and immediately executes a new function that takes 'z' as a parameter\n // The function body is a string that returns the serialized zod schema\n // When executed with the 'z' parameter, it reconstructs the zod schema in the current context\n return Function('z', `\"use strict\";return (${schema});`)(z);\n}\n\nexport interface ToolOptions {\n name: string;\n runId?: string;\n threadId?: string;\n resourceId?: string;\n logger?: IMastraLogger;\n description?: string;\n mastra?: (Mastra & MastraPrimitives) | MastraPrimitives;\n runtimeContext: RuntimeContext;\n /** Build-time tracing context (fallback for Legacy methods that can't pass runtime context) */\n tracingContext?: TracingContext;\n tracingPolicy?: TracingPolicy;\n memory?: MastraMemory;\n agentName?: string;\n model?: MastraLanguageModel;\n writableStream?: WritableStream<ChunkType>;\n requireApproval?: boolean;\n}\n\n/**\n * Checks if a value is a Zod type\n * @param value - The value to check\n * @returns True if the value is a Zod type, false otherwise\n */\nexport function isZodType(value: unknown): value is z.ZodType {\n // Check if it's a Zod schema by looking for common Zod properties and methods\n return (\n typeof value === 'object' &&\n value !== null &&\n '_def' in value &&\n 'parse' in value &&\n typeof (value as any).parse === 'function' &&\n 'safeParse' in value &&\n typeof (value as any).safeParse === 'function'\n );\n}\n\n// Helper function to create a deterministic hash\nfunction createDeterministicId(input: string): string {\n return createHash('sha256').update(input).digest('hex').slice(0, 8); // Take first 8 characters for a shorter but still unique ID\n}\n\n/**\n * Sets the properties for a Vercel Tool, including an ID and inputSchema\n * @param tool - The tool to set the properties for\n * @returns The tool with the properties set\n */\nfunction setVercelToolProperties(tool: VercelTool) {\n // Check if the tool already has inputSchema (v5 format)\n // If it does, use it directly (it might be a function)\n // Otherwise, convert the parameters to inputSchema\n const inputSchema = 'inputSchema' in tool ? tool.inputSchema : convertVercelToolParameters(tool);\n\n const toolId = !('id' in tool)\n ? tool.description\n ? `tool-${createDeterministicId(tool.description)}`\n : `tool-${Math.random().toString(36).substring(2, 9)}`\n : tool.id;\n\n return {\n ...tool,\n id: toolId,\n inputSchema,\n };\n}\n\n/**\n * Ensures a tool has an ID and inputSchema by generating one if not present\n * @param tool - The tool to ensure has an ID and inputSchema\n * @returns The tool with an ID and inputSchema\n */\nexport function ensureToolProperties(tools: ToolsInput): ToolsInput {\n const toolsWithProperties = Object.keys(tools).reduce<ToolsInput>((acc, key) => {\n const tool = tools?.[key];\n if (tool) {\n if (isVercelTool(tool)) {\n acc[key] = setVercelToolProperties(tool) as VercelTool;\n } else {\n acc[key] = tool;\n }\n }\n return acc;\n }, {});\n\n return toolsWithProperties;\n}\n\nfunction convertVercelToolParameters(tool: VercelTool): z.ZodType {\n // If the tool is a Vercel Tool, check if the parameters are already a zod object\n // If not, convert the parameters to a zod object using jsonSchemaToZod\n // Handle case where parameters (or inputSchema in v5) is a function that returns a schema\n let schema = tool.parameters ?? z.object({});\n\n // If schema is a function, call it to get the actual schema\n if (typeof schema === 'function') {\n schema = schema();\n }\n\n return isZodType(schema) ? schema : resolveSerializedZodOutput(jsonSchemaToZod(schema));\n}\n\n/**\n * Converts a Vercel Tool or Mastra Tool into a CoreTool format\n * @param originalTool - The tool to convert (either VercelTool or ToolAction)\n * @param options - Tool options including Mastra-specific settings\n * @param logType - Type of tool to log (tool or toolset)\n * @returns A CoreTool that can be used by the system\n */\nexport function makeCoreTool(\n originalTool: ToolToConvert,\n options: ToolOptions,\n logType?: 'tool' | 'toolset' | 'client-tool',\n): CoreTool {\n return new CoreToolBuilder({ originalTool, options, logType }).build();\n}\n\nexport function makeCoreToolV5(\n originalTool: ToolToConvert,\n options: ToolOptions,\n logType?: 'tool' | 'toolset' | 'client-tool',\n): VercelToolV5 {\n return new CoreToolBuilder({ originalTool, options, logType }).buildV5();\n}\n\n/**\n * Creates a proxy for a Mastra instance to handle deprecated properties\n * @param mastra - The Mastra instance to proxy\n * @param logger - The logger to use for warnings\n * @returns A proxy for the Mastra instance\n */\nexport function createMastraProxy({ mastra, logger }: { mastra: Mastra; logger: IMastraLogger }) {\n return new Proxy(mastra, {\n get(target, prop) {\n const hasProp = Reflect.has(target, prop);\n\n if (hasProp) {\n const value = Reflect.get(target, prop);\n const isFunction = typeof value === 'function';\n if (isFunction) {\n return value.bind(target);\n }\n return value;\n }\n\n if (prop === 'logger') {\n logger.warn(`Please use 'getLogger' instead, logger is deprecated`);\n return Reflect.apply(target.getLogger, target, []);\n }\n\n if (prop === 'telemetry') {\n logger.warn(`Please use 'getTelemetry' instead, telemetry is deprecated`);\n return Reflect.apply(target.getTelemetry, target, []);\n }\n\n if (prop === 'storage') {\n logger.warn(`Please use 'getStorage' instead, storage is deprecated`);\n return Reflect.get(target, 'storage');\n }\n\n if (prop === 'agents') {\n logger.warn(`Please use 'getAgents' instead, agents is deprecated`);\n return Reflect.apply(target.getAgents, target, []);\n }\n\n if (prop === 'tts') {\n logger.warn(`Please use 'getTTS' instead, tts is deprecated`);\n return Reflect.apply(target.getTTS, target, []);\n }\n\n if (prop === 'vectors') {\n logger.warn(`Please use 'getVectors' instead, vectors is deprecated`);\n return Reflect.apply(target.getVectors, target, []);\n }\n\n if (prop === 'memory') {\n logger.warn(`Please use 'getMemory' instead, memory is deprecated`);\n return Reflect.get(target, 'memory');\n }\n\n return Reflect.get(target, prop);\n },\n });\n}\n\nexport function checkEvalStorageFields(traceObject: any, logger?: IMastraLogger) {\n const missingFields = [];\n if (!traceObject.input) missingFields.push('input');\n if (!traceObject.output) missingFields.push('output');\n if (!traceObject.agentName) missingFields.push('agent_name');\n if (!traceObject.metricName) missingFields.push('metric_name');\n if (!traceObject.instructions) missingFields.push('instructions');\n if (!traceObject.globalRunId) missingFields.push('global_run_id');\n if (!traceObject.runId) missingFields.push('run_id');\n\n if (missingFields.length > 0) {\n if (logger) {\n logger.warn('Skipping evaluation storage due to missing required fields', {\n missingFields,\n runId: traceObject.runId,\n agentName: traceObject.agentName,\n });\n } else {\n console.warn('Skipping evaluation storage due to missing required fields', {\n missingFields,\n runId: traceObject.runId,\n agentName: traceObject.agentName,\n });\n }\n return false;\n }\n\n return true;\n}\n\n// lifted from https://github.com/vercel/ai/blob/main/packages/ai/core/prompt/detect-prompt-type.ts#L27\nfunction detectSingleMessageCharacteristics(\n message: any,\n): 'has-ui-specific-parts' | 'has-core-specific-parts' | 'message' | 'other' {\n if (\n typeof message === 'object' &&\n message !== null &&\n (message.role === 'function' || // UI-only role\n message.role === 'data' || // UI-only role\n 'toolInvocations' in message || // UI-specific field\n 'parts' in message || // UI-specific field\n 'experimental_attachments' in message)\n ) {\n return 'has-ui-specific-parts';\n } else if (\n typeof message === 'object' &&\n message !== null &&\n 'content' in message &&\n (Array.isArray(message.content) || // Core messages can have array content\n 'experimental_providerMetadata' in message ||\n 'providerOptions' in message)\n ) {\n return 'has-core-specific-parts';\n } else if (\n typeof message === 'object' &&\n message !== null &&\n 'role' in message &&\n 'content' in message &&\n typeof message.content === 'string' &&\n ['system', 'user', 'assistant', 'tool'].includes(message.role)\n ) {\n return 'message';\n } else {\n return 'other';\n }\n}\n\nexport function isUiMessage(message: CoreMessage | AiMessageType): message is AiMessageType {\n return detectSingleMessageCharacteristics(message) === `has-ui-specific-parts`;\n}\nexport function isCoreMessage(message: CoreMessage | AiMessageType): message is CoreMessage {\n return [`has-core-specific-parts`, `message`].includes(detectSingleMessageCharacteristics(message));\n}\n\n/** Represents a validated SQL identifier (e.g., table or column name). */\ntype SqlIdentifier = string & { __brand: 'SqlIdentifier' };\n/** Represents a validated dot-separated SQL field key. */\ntype FieldKey = string & { __brand: 'FieldKey' };\n\nconst SQL_IDENTIFIER_PATTERN = /^[a-zA-Z_][a-zA-Z0-9_]*$/;\n\n/**\n * Parses and returns a valid SQL identifier (such as a table or column name).\n * The identifier must:\n * - Start with a letter (a-z, A-Z) or underscore (_)\n * - Contain only letters, numbers, or underscores\n * - Be at most 63 characters long\n *\n * @param name - The identifier string to parse.\n * @param kind - Optional label for error messages (e.g., 'table name').\n * @returns The validated identifier as a branded type.\n * @throws {Error} If the identifier does not conform to SQL naming rules.\n *\n * @example\n * const id = parseSqlIdentifier('my_table'); // Ok\n * parseSqlIdentifier('123table'); // Throws error\n */\nexport function parseSqlIdentifier(name: string, kind = 'identifier'): SqlIdentifier {\n if (!SQL_IDENTIFIER_PATTERN.test(name) || name.length > 63) {\n throw new Error(\n `Invalid ${kind}: ${name}. Must start with a letter or underscore, contain only letters, numbers, or underscores, and be at most 63 characters long.`,\n );\n }\n return name as SqlIdentifier;\n}\n\n/**\n * Parses and returns a valid dot-separated SQL field key (e.g., 'user.profile.name').\n * Each segment must:\n * - Start with a letter (a-z, A-Z) or underscore (_)\n * - Contain only letters, numbers, or underscores\n * - Be at most 63 characters long\n *\n * @param key - The dot-separated field key string to parse.\n * @returns The validated field key as a branded type.\n * @throws {Error} If any segment of the key is invalid.\n *\n * @example\n * const key = parseFieldKey('user_profile.name'); // Ok\n * parseFieldKey('user..name'); // Throws error\n * parseFieldKey('user.123name'); // Throws error\n */\nexport function parseFieldKey(key: string): FieldKey {\n if (!key) throw new Error('Field key cannot be empty');\n const segments = key.split('.');\n for (const segment of segments) {\n if (!SQL_IDENTIFIER_PATTERN.test(segment) || segment.length > 63) {\n throw new Error(`Invalid field key segment: ${segment} in ${key}`);\n }\n }\n return key as FieldKey;\n}\n\n/**\n * Performs a fetch request with automatic retries using exponential backoff\n * @param url The URL to fetch from\n * @param options Standard fetch options\n * @param maxRetries Maximum number of retry attempts\n * @param validateResponse Optional function to validate the response beyond HTTP status\n * @returns The fetch Response if successful\n */\nexport async function fetchWithRetry(\n url: string,\n options: RequestInit = {},\n maxRetries: number = 3,\n): Promise<Response> {\n let retryCount = 0;\n let lastError: Error | null = null;\n\n while (retryCount < maxRetries) {\n try {\n const response = await fetch(url, options);\n\n if (!response.ok) {\n throw new Error(`Request failed with status: ${response.status} ${response.statusText}`);\n }\n\n return response;\n } catch (error) {\n lastError = error instanceof Error ? error : new Error(String(error));\n retryCount++;\n\n if (retryCount >= maxRetries) {\n break;\n }\n\n const delay = Math.min(1000 * Math.pow(2, retryCount) * 1000, 10000);\n await new Promise(resolve => setTimeout(resolve, delay));\n }\n }\n\n throw lastError || new Error('Request failed after multiple retry attempts');\n}\n","import { ErrorCategory, ErrorDomain, MastraError } from '../../error';\nimport { LogLevel } from '../../logger';\nimport { fetchWithRetry } from '../../utils';\nimport { AITracingEventType } from '../types';\nimport type { AITracingEvent, AnyExportedAISpan } from '../types';\nimport { BaseExporter } from './base';\nimport type { BaseExporterConfig } from './base';\n\nexport interface CloudExporterConfig extends BaseExporterConfig {\n maxBatchSize?: number; // Default: 1000 spans\n maxBatchWaitMs?: number; // Default: 5000ms\n maxRetries?: number; // Default: 3\n\n // Cloud-specific configuration\n accessToken?: string; // Cloud access token (from env or config)\n endpoint?: string; // Cloud AI tracing endpoint\n}\n\ninterface MastraCloudBuffer {\n spans: MastraCloudSpanRecord[];\n firstEventTime?: Date;\n totalSize: number;\n}\n\ninterface MastraCloudSpanRecord {\n traceId: string;\n spanId: string;\n parentSpanId: string | null;\n name: string;\n spanType: string;\n attributes: Record<string, any> | null;\n metadata: Record<string, any> | null;\n startedAt: Date;\n endedAt: Date | null;\n input: any;\n output: any;\n error: any;\n isEvent: boolean;\n createdAt: Date;\n updatedAt: Date | null;\n}\n\nexport class CloudExporter extends BaseExporter {\n name = 'mastra-cloud-ai-tracing-exporter';\n\n private config: Required<CloudExporterConfig>;\n private buffer: MastraCloudBuffer;\n private flushTimer: NodeJS.Timeout | null = null;\n\n constructor(config: CloudExporterConfig = {}) {\n super(config);\n\n const accessToken = config.accessToken ?? process.env.MASTRA_CLOUD_ACCESS_TOKEN;\n if (!accessToken) {\n this.setDisabled(\n 'MASTRA_CLOUD_ACCESS_TOKEN environment variable not set. ' +\n '🚀 Sign up for Mastra Cloud at https://cloud.mastra.ai to see your AI traces online and obtain your access token.',\n );\n }\n\n const endpoint =\n config.endpoint ?? process.env.MASTRA_CLOUD_AI_TRACES_ENDPOINT ?? 'https://api.mastra.ai/ai/spans/publish';\n\n this.config = {\n logger: this.logger,\n logLevel: config.logLevel ?? LogLevel.INFO,\n maxBatchSize: config.maxBatchSize ?? 1000,\n maxBatchWaitMs: config.maxBatchWaitMs ?? 5000,\n maxRetries: config.maxRetries ?? 3,\n accessToken: accessToken || '',\n endpoint,\n };\n\n this.buffer = {\n spans: [],\n totalSize: 0,\n };\n }\n\n protected async _exportEvent(event: AITracingEvent): Promise<void> {\n // Cloud AI Observability only process SPAN_ENDED events\n if (event.type !== AITracingEventType.SPAN_ENDED) {\n return;\n }\n\n this.addToBuffer(event);\n\n if (this.shouldFlush()) {\n this.flush().catch(error => {\n this.logger.error('Batch flush failed', {\n error: error instanceof Error ? error.message : String(error),\n });\n });\n } else if (this.buffer.totalSize === 1) {\n this.scheduleFlush();\n }\n }\n\n private addToBuffer(event: AITracingEvent): void {\n // Set first event time if buffer is empty\n if (this.buffer.totalSize === 0) {\n this.buffer.firstEventTime = new Date();\n }\n\n const spanRecord = this.formatSpan(event.exportedSpan);\n this.buffer.spans.push(spanRecord);\n this.buffer.totalSize++;\n }\n\n private formatSpan(span: AnyExportedAISpan): MastraCloudSpanRecord {\n const spanRecord: MastraCloudSpanRecord = {\n traceId: span.traceId,\n spanId: span.id,\n parentSpanId: span.parentSpanId ?? null,\n name: span.name,\n spanType: span.type,\n attributes: span.attributes ?? null,\n metadata: span.metadata ?? null,\n startedAt: span.startTime,\n endedAt: span.endTime ?? null,\n input: span.input ?? null,\n output: span.output ?? null,\n error: span.errorInfo,\n isEvent: span.isEvent,\n createdAt: new Date(),\n updatedAt: null,\n };\n\n return spanRecord;\n }\n\n private shouldFlush(): boolean {\n // Size-based flush\n if (this.buffer.totalSize >= this.config.maxBatchSize) {\n return true;\n }\n\n // Time-based flush\n if (this.buffer.firstEventTime && this.buffer.totalSize > 0) {\n const elapsed = Date.now() - this.buffer.firstEventTime.getTime();\n if (elapsed >= this.config.maxBatchWaitMs) {\n return true;\n }\n }\n\n return false;\n }\n\n private scheduleFlush(): void {\n if (this.flushTimer) {\n clearTimeout(this.flushTimer);\n }\n this.flushTimer = setTimeout(() => {\n this.flush().catch(error => {\n const mastraError = new MastraError(\n {\n id: `CLOUD_AI_TRACING_FAILED_TO_SCHEDULE_FLUSH`,\n domain: ErrorDomain.MASTRA_OBSERVABILITY,\n category: ErrorCategory.USER,\n },\n error,\n );\n this.logger.trackException(mastraError);\n this.logger.error('Scheduled flush failed', mastraError);\n });\n }, this.config.maxBatchWaitMs);\n }\n\n private async flush(): Promise<void> {\n // Clear timer since we're flushing\n if (this.flushTimer) {\n clearTimeout(this.flushTimer);\n this.flushTimer = null;\n }\n\n if (this.buffer.totalSize === 0) {\n return; // Nothing to flush\n }\n\n const startTime = Date.now();\n const spansCopy = [...this.buffer.spans];\n const flushReason = this.buffer.totalSize >= this.config.maxBatchSize ? 'size' : 'time';\n\n // Reset buffer immediately to prevent blocking new events\n this.resetBuffer();\n\n try {\n // Use fetchWithRetry for all retry logic\n await this.batchUpload(spansCopy);\n\n const elapsed = Date.now() - startTime;\n this.logger.debug('Batch flushed successfully', {\n batchSize: spansCopy.length,\n flushReason,\n durationMs: elapsed,\n });\n } catch (error) {\n const mastraError = new MastraError(\n {\n id: `CLOUD_AI_TRACING_FAILED_TO_BATCH_UPLOAD`,\n domain: ErrorDomain.MASTRA_OBSERVABILITY,\n category: ErrorCategory.USER,\n details: {\n droppedBatchSize: spansCopy.length,\n },\n },\n error,\n );\n this.logger.trackException(mastraError);\n this.logger.error('Batch upload failed after all retries, dropping batch', mastraError);\n // Don't re-throw - we want to continue processing new events\n }\n }\n\n /**\n * Uploads spans to cloud API using fetchWithRetry for all retry logic\n */\n private async batchUpload(spans: MastraCloudSpanRecord[]): Promise<void> {\n const headers = {\n Authorization: `Bearer ${this.config.accessToken}`,\n 'Content-Type': 'application/json',\n };\n\n const options: RequestInit = {\n method: 'POST',\n headers,\n body: JSON.stringify({ spans }),\n };\n\n await fetchWithRetry(this.config.endpoint, options, this.config.maxRetries);\n }\n\n private resetBuffer(): void {\n this.buffer.spans = [];\n this.buffer.firstEventTime = undefined;\n this.buffer.totalSize = 0;\n }\n\n async shutdown(): Promise<void> {\n // Skip if disabled\n if (this.isDisabled) {\n return;\n }\n\n // Clear any pending timer\n if (this.flushTimer) {\n clearTimeout(this.flushTimer);\n this.flushTimer = null;\n }\n\n // Flush any remaining events\n if (this.buffer.totalSize > 0) {\n this.logger.info('Flushing remaining events on shutdown', {\n remainingEvents: this.buffer.totalSize,\n });\n try {\n await this.flush();\n } catch (error) {\n const mastraError = new MastraError(\n {\n id: `CLOUD_AI_TRACING_FAILED_TO_FLUSH_REMAINING_EVENTS_DURING_SHUTDOWN`,\n domain: ErrorDomain.MASTRA_OBSERVABILITY,\n category: ErrorCategory.USER,\n details: {\n remainingEvents: this.buffer.totalSize,\n },\n },\n error,\n );\n\n this.logger.trackException(mastraError);\n this.logger.error('Failed to flush remaining events during shutdown', mastraError);\n }\n }\n\n this.logger.info('CloudExporter shutdown complete');\n }\n}\n","import { AITracingEventType } from '../types';\nimport type { AITracingEvent } from '../types';\nimport { BaseExporter } from './base';\nimport type { BaseExporterConfig } from './base';\n\nexport class ConsoleExporter extends BaseExporter {\n name = 'tracing-console-exporter';\n\n constructor(config: BaseExporterConfig = {}) {\n super(config);\n }\n\n protected async _exportEvent(event: AITracingEvent): Promise<void> {\n const span = event.exportedSpan;\n\n // Helper to safely stringify attributes (filtering already done by processor)\n const formatAttributes = (attributes: any) => {\n try {\n return JSON.stringify(attributes, null, 2);\n } catch (error) {\n const errMsg = error instanceof Error ? error.message : 'Unknown formatting error';\n return `[Unable to serialize attributes: ${errMsg}]`;\n }\n };\n\n // Helper to format duration\n const formatDuration = (startTime: Date, endTime?: Date) => {\n if (!endTime) return 'N/A';\n const duration = endTime.getTime() - startTime.getTime();\n return `${duration}ms`;\n };\n\n switch (event.type) {\n case AITracingEventType.SPAN_STARTED:\n this.logger.info(`🚀 SPAN_STARTED`);\n this.logger.info(` Type: ${span.type}`);\n this.logger.info(` Name: ${span.name}`);\n this.logger.info(` ID: ${span.id}`);\n this.logger.info(` Trace ID: ${span.traceId}`);\n if (span.input !== undefined) {\n this.logger.info(` Input: ${formatAttributes(span.input)}`);\n }\n this.logger.info(` Attributes: ${formatAttributes(span.attributes)}`);\n this.logger.info('─'.repeat(80));\n break;\n\n case AITracingEventType.SPAN_ENDED:\n const duration = formatDuration(span.startTime, span.endTime);\n this.logger.info(`✅ SPAN_ENDED`);\n this.logger.info(` Type: ${span.type}`);\n this.logger.info(` Name: ${span.name}`);\n this.logger.info(` ID: ${span.id}`);\n this.logger.info(` Duration: ${duration}`);\n this.logger.info(` Trace ID: ${span.traceId}`);\n if (span.input !== undefined) {\n this.logger.info(` Input: ${formatAttributes(span.input)}`);\n }\n if (span.output !== undefined) {\n this.logger.info(` Output: ${formatAttributes(span.output)}`);\n }\n if (span.errorInfo) {\n this.logger.info(` Error: ${formatAttributes(span.errorInfo)}`);\n }\n this.logger.info(` Attributes: ${formatAttributes(span.attributes)}`);\n this.logger.info('─'.repeat(80));\n break;\n\n case AITracingEventType.SPAN_UPDATED:\n this.logger.info(`📝 SPAN_UPDATED`);\n this.logger.info(` Type: ${span.type}`);\n this.logger.info(` Name: ${span.name}`);\n this.logger.info(` ID: ${span.id}`);\n this.logger.info(` Trace ID: ${span.traceId}`);\n if (span.input !== undefined) {\n this.logger.info(` Input: ${formatAttributes(span.input)}`);\n }\n if (span.output !== undefined) {\n this.logger.info(` Output: ${formatAttributes(span.output)}`);\n }\n if (span.errorInfo) {\n this.logger.info(` Error: ${formatAttributes(span.errorInfo)}`);\n }\n this.logger.info(` Updated Attributes: ${formatAttributes(span.attributes)}`);\n this.logger.info('─'.repeat(80));\n break;\n\n default:\n this.logger.warn(`Tracing event type not implemented: ${(event as any).type}`);\n }\n }\n\n async shutdown(): Promise<void> {\n this.logger.info('ConsoleExporter shutdown');\n }\n}\n","import { ConsoleLogger, LogLevel } from '../../logger';\nimport type { IMastraLogger } from '../../logger';\nimport type { Mastra } from '../../mastra';\nimport type { MastraStorage } from '../../storage/base';\nimport type { CreateAISpanRecord, UpdateAISpanRecord } from '../../storage/types';\nimport { AITracingEventType } from '../types';\nimport type { AITracingEvent, AITracingExporter, AnyExportedAISpan, TracingConfig, TracingStrategy } from '../types';\n\ninterface BatchingConfig {\n maxBatchSize?: number; // Default: 1000 spans\n maxBufferSize?: number; // Default: 10000 spans\n maxBatchWaitMs?: number; // Default: 5000ms\n maxRetries?: number; // Default: 4\n retryDelayMs?: number; // Default: 500ms (base delay for exponential backoff)\n\n // Strategy selection (optional)\n strategy?: TracingStrategy | 'auto';\n}\n\ninterface BatchBuffer {\n // For batch-with-updates strategy\n creates: CreateAISpanRecord[];\n updates: UpdateRecord[];\n\n // For insert-only strategy\n insertOnly: CreateAISpanRecord[];\n\n // Ordering enforcement (batch-with-updates only)\n seenSpans: Set<string>; // \"traceId:spanId\" combinations we've seen creates for\n spanSequences: Map<string, number>; // \"traceId:spanId\" -> next sequence number\n\n // Track completed spans for cleanup\n completedSpans: Set<string>; // Spans that have received SPAN_ENDED\n\n // Metrics\n outOfOrderCount: number;\n\n // Metadata\n firstEventTime?: Date;\n totalSize: number;\n}\n\ninterface UpdateRecord {\n traceId: string;\n spanId: string;\n updates: Partial<UpdateAISpanRecord>;\n sequenceNumber: number; // For ordering updates to same span\n}\n\n/**\n * Resolves the final strategy based on user config and storage hints\n */\nfunction resolveStrategy(userConfig: BatchingConfig, storage: MastraStorage, logger: IMastraLogger): TracingStrategy {\n if (userConfig.strategy && userConfig.strategy !== 'auto') {\n const hints = storage.aiTracingStrategy;\n if (hints.supported.includes(userConfig.strategy)) {\n return userConfig.strategy;\n }\n // Log warning and fall through to auto-selection\n logger.warn('User-specified AI tracing strategy not supported by storage adapter, falling back to auto-selection', {\n userStrategy: userConfig.strategy,\n storageAdapter: storage.constructor.name,\n supportedStrategies: hints.supported,\n fallbackStrategy: hints.preferred,\n });\n }\n return storage.aiTracingStrategy.preferred;\n}\n\nexport class DefaultExporter implements AITracingExporter {\n name = 'tracing-default-exporter';\n private logger: IMastraLogger;\n private mastra: Mastra | null = null;\n private config: Required<BatchingConfig>;\n private resolvedStrategy: TracingStrategy;\n private buffer: BatchBuffer;\n private flushTimer: NodeJS.Timeout | null = null;\n\n // Track all spans that have been created, persists across flushes\n private allCreatedSpans: Set<string> = new Set();\n\n constructor(config: BatchingConfig = {}, logger?: IMastraLogger) {\n if (logger) {\n this.logger = logger;\n } else {\n // Fallback: create a direct ConsoleLogger instance if none provided\n this.logger = new ConsoleLogger({ level: LogLevel.INFO });\n }\n\n // Set default configuration\n this.config = {\n maxBatchSize: config.maxBatchSize ?? 1000,\n maxBufferSize: config.maxBufferSize ?? 10000,\n maxBatchWaitMs: config.maxBatchWaitMs ?? 5000,\n maxRetries: config.maxRetries ?? 4,\n retryDelayMs: config.retryDelayMs ?? 500,\n strategy: config.strategy ?? 'auto',\n };\n\n // Initialize buffer\n this.buffer = {\n creates: [],\n updates: [],\n insertOnly: [],\n seenSpans: new Set(),\n spanSequences: new Map(),\n completedSpans: new Set(),\n outOfOrderCount: 0,\n totalSize: 0,\n };\n\n // Resolve strategy - we'll do this lazily on first export since we need storage\n this.resolvedStrategy = 'batch-with-updates'; // temporary default\n }\n\n private strategyInitialized = false;\n\n /**\n * Register the Mastra instance (called after Mastra construction is complete)\n */\n __registerMastra(mastra: Mastra): void {\n this.mastra = mastra;\n }\n\n /**\n * Initialize the exporter (called after all dependencies are ready)\n */\n init(_config?: TracingConfig): void {\n if (!this.mastra) {\n throw new Error('DefaultExporter: init() called before __registerMastra()');\n }\n\n const storage = this.mastra.getStorage();\n if (!storage) {\n this.logger.warn('DefaultExporter disabled: Storage not available. Traces will not be persisted.');\n return;\n }\n\n this.initializeStrategy(storage);\n }\n\n /**\n * Initialize the resolved strategy once storage is available\n */\n private initializeStrategy(storage: MastraStorage): void {\n if (this.strategyInitialized) return;\n\n this.resolvedStrategy = resolveStrategy(this.config, storage, this.logger);\n this.strategyInitialized = true;\n\n this.logger.debug('AI tracing exporter initialized', {\n strategy: this.resolvedStrategy,\n source: this.config.strategy !== 'auto' ? 'user' : 'auto',\n storageAdapter: storage.constructor.name,\n maxBatchSize: this.config.maxBatchSize,\n maxBatchWaitMs: this.config.maxBatchWaitMs,\n });\n }\n\n /**\n * Builds a unique span key for tracking\n */\n private buildSpanKey(traceId: string, spanId: string): string {\n return `${traceId}:${spanId}`;\n }\n\n /**\n * Gets the next sequence number for a span\n */\n private getNextSequence(spanKey: string): number {\n const current = this.buffer.spanSequences.get(spanKey) || 0;\n const next = current + 1;\n this.buffer.spanSequences.set(spanKey, next);\n return next;\n }\n\n /**\n * Handles out-of-order span updates by logging and skipping\n */\n private handleOutOfOrderUpdate(event: AITracingEvent): void {\n this.logger.warn('Out-of-order span update detected - skipping event', {\n spanId: event.exportedSpan.id,\n traceId: event.exportedSpan.traceId,\n spanName: event.exportedSpan.name,\n eventType: event.type,\n });\n }\n\n /**\n * Adds an event to the appropriate buffer based on strategy\n */\n private addToBuffer(event: AITracingEvent): void {\n const spanKey = this.buildSpanKey(event.exportedSpan.traceId, event.exportedSpan.id);\n\n // Set first event time if buffer is empty\n if (this.buffer.totalSize === 0) {\n this.buffer.firstEventTime = new Date();\n }\n\n switch (event.type) {\n case AITracingEventType.SPAN_STARTED:\n if (this.resolvedStrategy === 'batch-with-updates') {\n const createRecord = this.buildCreateRecord(event.exportedSpan);\n this.buffer.creates.push(createRecord);\n this.buffer.seenSpans.add(spanKey);\n // Track this span as created persistently\n this.allCreatedSpans.add(spanKey);\n }\n // insert-only ignores SPAN_STARTED\n break;\n\n case AITracingEventType.SPAN_UPDATED:\n if (this.resolvedStrategy === 'batch-with-updates') {\n if (this.allCreatedSpans.has(spanKey)) {\n // Span was created previously (possibly in a prior batch)\n this.buffer.updates.push({\n traceId: event.exportedSpan.traceId,\n spanId: event.exportedSpan.id,\n updates: this.buildUpdateRecord(event.exportedSpan),\n sequenceNumber: this.getNextSequence(spanKey),\n });\n } else {\n // Out-of-order case: log and skip\n this.handleOutOfOrderUpdate(event);\n this.buffer.outOfOrderCount++;\n }\n }\n // insert-only ignores SPAN_UPDATED\n break;\n\n case AITracingEventType.SPAN_ENDED:\n if (this.resolvedStrategy === 'batch-with-updates') {\n if (this.allCreatedSpans.has(spanKey)) {\n // Span was created previously (possibly in a prior batch)\n this.buffer.updates.push({\n traceId: event.exportedSpan.traceId,\n spanId: event.exportedSpan.id,\n updates: this.buildUpdateRecord(event.exportedSpan),\n sequenceNumber: this.getNextSequence(spanKey),\n });\n // Mark this span as completed\n this.buffer.completedSpans.add(spanKey);\n } else if (event.exportedSpan.isEvent) {\n // Event-type spans only emit SPAN_ENDED (no prior SPAN_STARTED)\n const createRecord = this.buildCreateRecord(event.exportedSpan);\n this.buffer.creates.push(createRecord);\n this.buffer.seenSpans.add(spanKey);\n // Track this span as created persistently\n this.allCreatedSpans.add(spanKey);\n // Event spans are immediately complete\n this.buffer.completedSpans.add(spanKey);\n } else {\n // Out-of-order case: log and skip\n this.handleOutOfOrderUpdate(event);\n this.buffer.outOfOrderCount++;\n }\n } else if (this.resolvedStrategy === 'insert-only') {\n // Only process SPAN_ENDED for insert-only strategy\n const createRecord = this.buildCreateRecord(event.exportedSpan);\n this.buffer.insertOnly.push(createRecord);\n // Mark as completed for insert-only strategy\n this.buffer.completedSpans.add(spanKey);\n this.allCreatedSpans.add(spanKey);\n }\n break;\n }\n\n // Update total size\n this.buffer.totalSize = this.buffer.creates.length + this.buffer.updates.length + this.buffer.insertOnly.length;\n }\n\n /**\n * Checks if buffer should be flushed based on size or time triggers\n */\n private shouldFlush(): boolean {\n // Emergency flush - buffer overflow\n if (this.buffer.totalSize >= this.config.maxBufferSize) {\n return true;\n }\n\n // Size-based flush\n if (this.buffer.totalSize >= this.config.maxBatchSize) {\n return true;\n }\n\n // Time-based flush\n if (this.buffer.firstEventTime && this.buffer.totalSize > 0) {\n const elapsed = Date.now() - this.buffer.firstEventTime.getTime();\n if (elapsed >= this.config.maxBatchWaitMs) {\n return true;\n }\n }\n\n return false;\n }\n\n /**\n * Resets the buffer after successful flush\n */\n private resetBuffer(completedSpansToCleanup: Set<string> = new Set()): void {\n this.buffer.creates = [];\n this.buffer.updates = [];\n this.buffer.insertOnly = [];\n this.buffer.seenSpans.clear();\n this.buffer.spanSequences.clear();\n this.buffer.completedSpans.clear();\n this.buffer.outOfOrderCount = 0;\n this.buffer.firstEventTime = undefined;\n this.buffer.totalSize = 0;\n\n // Clean up completed spans from persistent tracking\n for (const spanKey of completedSpansToCleanup) {\n this.allCreatedSpans.delete(spanKey);\n }\n }\n\n /**\n * Schedules a flush using setTimeout\n */\n private scheduleFlush(): void {\n if (this.flushTimer) {\n clearTimeout(this.flushTimer);\n }\n this.flushTimer = setTimeout(() => {\n this.flush().catch(error => {\n this.logger.error('Scheduled flush failed', {\n error: error instanceof Error ? error.message : String(error),\n });\n });\n }, this.config.maxBatchWaitMs);\n }\n\n /**\n * Serializes span attributes to storage record format\n * Handles all AI span types and their specific attributes\n */\n private serializeAttributes(span: AnyExportedAISpan): Record<string, any> | null {\n if (!span.attributes) {\n return null;\n }\n\n try {\n // Convert the typed attributes to a plain object\n // This handles nested objects, dates, and other complex types\n return JSON.parse(\n JSON.stringify(span.attributes, (_key, value) => {\n // Handle Date objects\n if (value instanceof Date) {\n return value.toISOString();\n }\n // Handle other objects that might not serialize properly\n if (typeof value === 'object' && value !== null) {\n // For arrays and plain objects, let JSON.stringify handle them\n return value;\n }\n // For primitives, return as-is\n return value;\n }),\n );\n } catch (error) {\n this.logger.warn('Failed to serialize span attributes, storing as null', {\n spanId: span.id,\n spanType: span.type,\n error: error instanceof Error ? error.message : String(error),\n });\n return null;\n }\n }\n\n private buildCreateRecord(span: AnyExportedAISpan): CreateAISpanRecord {\n return {\n traceId: span.traceId,\n spanId: span.id,\n parentSpanId: span.parentSpanId ?? null,\n name: span.name,\n scope: null,\n spanType: span.type,\n attributes: this.serializeAttributes(span),\n metadata: span.metadata ?? null,\n links: null,\n startedAt: span.startTime,\n endedAt: span.endTime ?? null,\n input: span.input,\n output: span.output,\n error: span.errorInfo,\n isEvent: span.isEvent,\n };\n }\n\n private buildUpdateRecord(span: AnyExportedAISpan): Partial<UpdateAISpanRecord> {\n return {\n name: span.name,\n scope: null,\n attributes: this.serializeAttributes(span),\n metadata: span.metadata ?? null,\n links: null,\n endedAt: span.endTime ?? null,\n input: span.input,\n output: span.output,\n error: span.errorInfo,\n };\n }\n\n /**\n * Handles realtime strategy - processes each event immediately\n */\n private async handleRealtimeEvent(event: AITracingEvent, storage: MastraStorage): Promise<void> {\n const span = event.exportedSpan;\n const spanKey = this.buildSpanKey(span.traceId, span.id);\n\n // Event spans only have an end event\n if (span.isEvent) {\n if (event.type === AITracingEventType.SPAN_ENDED) {\n await storage.createAISpan(this.buildCreateRecord(event.exportedSpan));\n // For event spans in realtime, we don't need to track them since they're immediately complete\n } else {\n this.logger.warn(`Tracing event type not implemented for event spans: ${event.type}`);\n }\n } else {\n switch (event.type) {\n case AITracingEventType.SPAN_STARTED:\n await storage.createAISpan(this.buildCreateRecord(event.exportedSpan));\n // Track this span as created persistently\n this.allCreatedSpans.add(spanKey);\n break;\n case AITracingEventType.SPAN_UPDATED:\n await storage.updateAISpan({\n traceId: span.traceId,\n spanId: span.id,\n updates: this.buildUpdateRecord(span),\n });\n break;\n case AITracingEventType.SPAN_ENDED:\n await storage.updateAISpan({\n traceId: span.traceId,\n spanId: span.id,\n updates: this.buildUpdateRecord(span),\n });\n // Clean up immediately for realtime strategy\n this.allCreatedSpans.delete(spanKey);\n break;\n default:\n this.logger.warn(`Tracing event type not implemented for span spans: ${(event as any).type}`);\n }\n }\n }\n\n /**\n * Handles batch-with-updates strategy - buffers events and processes in batches\n */\n private handleBatchWithUpdatesEvent(event: AITracingEvent): void {\n this.addToBuffer(event);\n\n if (this.shouldFlush()) {\n // Immediate flush for size/emergency triggers\n this.flush().catch(error => {\n this.logger.error('Batch flush failed', {\n error: error instanceof Error ? error.message : String(error),\n });\n });\n } else if (this.buffer.totalSize === 1) {\n // Schedule flush for the first event in buffer\n this.scheduleFlush();\n }\n }\n\n /**\n * Handles insert-only strategy - only processes SPAN_ENDED events in batches\n */\n private handleInsertOnlyEvent(event: AITracingEvent): void {\n // Only process SPAN_ENDED events for insert-only strategy\n if (event.type === AITracingEventType.SPAN_ENDED) {\n this.addToBuffer(event);\n\n if (this.shouldFlush()) {\n // Immediate flush for size/emergency triggers\n this.flush().catch(error => {\n this.logger.error('Batch flush failed', {\n error: error instanceof Error ? error.message : String(error),\n });\n });\n } else if (this.buffer.totalSize === 1) {\n // Schedule flush for the first event in buffer\n this.scheduleFlush();\n }\n }\n // Ignore SPAN_STARTED and SPAN_UPDATED events\n }\n\n /**\n * Calculates retry delay using exponential backoff\n */\n private calculateRetryDelay(attempt: number): number {\n return this.config.retryDelayMs * Math.pow(2, attempt);\n }\n\n /**\n * Flushes the current buffer to storage with retry logic\n */\n private async flush(): Promise<void> {\n if (!this.mastra) {\n this.logger.debug('Cannot flush traces. Mastra instance not registered yet.');\n return;\n }\n\n const storage = this.mastra.getStorage();\n if (!storage) {\n this.logger.debug('Cannot flush traces. Mastra storage is not initialized');\n return;\n }\n\n // Clear timer since we're flushing\n if (this.flushTimer) {\n clearTimeout(this.flushTimer);\n this.flushTimer = null;\n }\n\n if (this.buffer.totalSize === 0) {\n return; // Nothing to flush\n }\n\n const startTime = Date.now();\n const flushReason =\n this.buffer.totalSize >= this.config.maxBufferSize\n ? 'overflow'\n : this.buffer.totalSize >= this.config.maxBatchSize\n ? 'size'\n : 'time';\n\n // Create a copy of the buffer to work with\n const bufferCopy: BatchBuffer = {\n creates: [...this.buffer.creates],\n updates: [...this.buffer.updates],\n insertOnly: [...this.buffer.insertOnly],\n seenSpans: new Set(this.buffer.seenSpans),\n spanSequences: new Map(this.buffer.spanSequences),\n completedSpans: new Set(this.buffer.completedSpans),\n outOfOrderCount: this.buffer.outOfOrderCount,\n firstEventTime: this.buffer.firstEventTime,\n totalSize: this.buffer.totalSize,\n };\n\n // Reset buffer immediately to prevent blocking new events\n // Note: We don't clean up completed spans yet - we'll do that after successful flush\n this.resetBuffer();\n\n // Attempt to flush with retry logic\n await this.flushWithRetries(storage, bufferCopy, 0);\n\n const elapsed = Date.now() - startTime;\n this.logger.debug('Batch flushed', {\n strategy: this.resolvedStrategy,\n batchSize: bufferCopy.totalSize,\n flushReason,\n durationMs: elapsed,\n outOfOrderCount: bufferCopy.outOfOrderCount > 0 ? bufferCopy.outOfOrderCount : undefined,\n });\n }\n\n /**\n * Attempts to flush with exponential backoff retry logic\n */\n private async flushWithRetries(storage: MastraStorage, buffer: BatchBuffer, attempt: number): Promise<void> {\n try {\n if (this.resolvedStrategy === 'batch-with-updates') {\n // Process creates first (always safe)\n if (buffer.creates.length > 0) {\n await storage.batchCreateAISpans({ records: buffer.creates });\n }\n\n // Sort updates by span, then by sequence number\n if (buffer.updates.length > 0) {\n const sortedUpdates = buffer.updates.sort((a, b) => {\n const spanCompare = this.buildSpanKey(a.traceId, a.spanId).localeCompare(\n this.buildSpanKey(b.traceId, b.spanId),\n );\n if (spanCompare !== 0) return spanCompare;\n return a.sequenceNumber - b.sequenceNumber;\n });\n\n await storage.batchUpdateAISpans({ records: sortedUpdates });\n }\n } else if (this.resolvedStrategy === 'insert-only') {\n // Simple batch insert for insert-only strategy\n if (buffer.insertOnly.length > 0) {\n await storage.batchCreateAISpans({ records: buffer.insertOnly });\n }\n }\n\n // Success! Clean up completed spans from persistent tracking\n for (const spanKey of buffer.completedSpans) {\n this.allCreatedSpans.delete(spanKey);\n }\n } catch (error) {\n if (attempt < this.config.maxRetries) {\n const retryDelay = this.calculateRetryDelay(attempt);\n this.logger.warn('Batch flush failed, retrying', {\n attempt: attempt + 1,\n maxRetries: this.config.maxRetries,\n nextRetryInMs: retryDelay,\n error: error instanceof Error ? error.message : String(error),\n });\n\n await new Promise(resolve => setTimeout(resolve, retryDelay));\n return this.flushWithRetries(storage, buffer, attempt + 1);\n } else {\n this.logger.error('Batch flush failed after all retries, dropping batch', {\n finalAttempt: attempt + 1,\n maxRetries: this.config.maxRetries,\n droppedBatchSize: buffer.totalSize,\n error: error instanceof Error ? error.message : String(error),\n });\n // Even on failure, we should clean up completed spans to avoid memory leak\n // These spans will be lost but at least we prevent memory issues\n for (const spanKey of buffer.completedSpans) {\n this.allCreatedSpans.delete(spanKey);\n }\n }\n }\n }\n\n async exportEvent(event: AITracingEvent): Promise<void> {\n if (!this.mastra) {\n this.logger.debug('Cannot export AI tracing event. Mastra instance not registered yet.');\n return;\n }\n\n const storage = this.mastra.getStorage();\n if (!storage) {\n this.logger.debug('Cannot store traces. Mastra storage is not initialized');\n return;\n }\n\n // Initialize strategy if not already done (fallback for edge cases)\n if (!this.strategyInitialized) {\n this.initializeStrategy(storage);\n }\n\n // Clear strategy routing - explicit and readable\n switch (this.resolvedStrategy) {\n case 'realtime':\n await this.handleRealtimeEvent(event, storage);\n break;\n case 'batch-with-updates':\n this.handleBatchWithUpdatesEvent(event);\n break;\n case 'insert-only':\n this.handleInsertOnlyEvent(event);\n break;\n }\n }\n\n async shutdown(): Promise<void> {\n // Clear any pending timer\n if (this.flushTimer) {\n clearTimeout(this.flushTimer);\n this.flushTimer = null;\n }\n\n // Flush any remaining events\n if (this.buffer.totalSize > 0) {\n this.logger.info('Flushing remaining events on shutdown', {\n remainingEvents: this.buffer.totalSize,\n });\n try {\n await this.flush();\n } catch (error) {\n this.logger.error('Failed to flush remaining events during shutdown', {\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n\n this.logger.info('DefaultExporter shutdown complete');\n }\n}\n","import type { AISpanProcessor, AnyAISpan } from '../types';\n\nexport type RedactionStyle = 'full' | 'partial';\n\n/**\n * Options for configuring the SensitiveDataFilter.\n */\nexport interface SensitiveDataFilterOptions {\n /**\n * List of sensitive field names to redact.\n * Matching is case-insensitive and normalizes separators (`api-key`, `api_key`, `Api Key` → `apikey`).\n *\n * Defaults include: password, token, secret, key, apikey, auth, authorization,\n * bearer, bearertoken, jwt, credential, clientsecret, privatekey, refresh, ssn.\n */\n sensitiveFields?: string[];\n\n /**\n * The token used for full redaction.\n * Default: \"[REDACTED]\"\n */\n redactionToken?: string;\n\n /**\n * Style of redaction to use:\n * - \"full\": always replace with redactionToken.\n * - \"partial\": show 3 characters from the start and end, redact the middle.\n *\n * Default: \"full\"\n */\n redactionStyle?: RedactionStyle;\n}\n\n/**\n * SensitiveDataFilter\n *\n * An AISpanProcessor that redacts sensitive information from span fields.\n *\n * - Sensitive keys are matched case-insensitively, normalized to remove separators.\n * - Sensitive values are redacted using either full or partial redaction.\n * - Partial redaction always keeps 3 chars at the start and end.\n * - If filtering a field fails, the field is replaced with:\n * `{ error: { processor: \"sensitive-data-filter\" } }`\n */\nexport class SensitiveDataFilter implements AISpanProcessor {\n name = 'sensitive-data-filter';\n private sensitiveFields: string[];\n private redactionToken: string;\n private redactionStyle: RedactionStyle;\n\n constructor(options: SensitiveDataFilterOptions = {}) {\n this.sensitiveFields = (\n options.sensitiveFields || [\n 'password',\n 'token',\n 'secret',\n 'key',\n 'apikey',\n 'auth',\n 'authorization',\n 'bearer',\n 'bearertoken',\n 'jwt',\n 'credential',\n 'clientsecret',\n 'privatekey',\n 'refresh',\n 'ssn',\n ]\n ).map(f => this.normalizeKey(f));\n\n this.redactionToken = options.redactionToken ?? '[REDACTED]';\n this.redactionStyle = options.redactionStyle ?? 'full';\n }\n\n /**\n * Process a span by filtering sensitive data across its key fields.\n * Fields processed: attributes, metadata, input, output, errorInfo.\n *\n * @param span - The input span to filter\n * @returns A new span with sensitive values redacted\n */\n process(span: AnyAISpan): AnyAISpan {\n span.attributes = this.tryFilter(span.attributes);\n span.metadata = this.tryFilter(span.metadata);\n span.input = this.tryFilter(span.input);\n span.output = this.tryFilter(span.output);\n span.errorInfo = this.tryFilter(span.errorInfo);\n return span;\n }\n\n /**\n * Recursively filter objects/arrays for sensitive keys.\n * Handles circular references by replacing with a marker.\n */\n private deepFilter(obj: any, seen = new WeakSet()): any {\n if (obj === null || typeof obj !== 'object') {\n return obj;\n }\n\n if (seen.has(obj)) {\n return '[Circular Reference]';\n }\n seen.add(obj);\n\n if (Array.isArray(obj)) {\n return obj.map(item => this.deepFilter(item, seen));\n }\n\n const filtered: any = {};\n for (const key of Object.keys(obj)) {\n const normKey = this.normalizeKey(key);\n\n if (this.isSensitive(normKey)) {\n if (obj[key] && typeof obj[key] === 'object') {\n filtered[key] = this.deepFilter(obj[key], seen);\n } else {\n filtered[key] = this.redactValue(obj[key]);\n }\n } else {\n filtered[key] = this.deepFilter(obj[key], seen);\n }\n }\n\n return filtered;\n }\n\n private tryFilter(value: any): any {\n try {\n return this.deepFilter(value);\n } catch {\n return { error: { processor: this.name } };\n }\n }\n\n /**\n * Normalize keys by lowercasing and stripping non-alphanumeric characters.\n * Ensures consistent matching for variants like \"api-key\", \"api_key\", \"Api Key\".\n */\n private normalizeKey(key: string): string {\n return key.toLowerCase().replace(/[^a-z0-9]/g, '');\n }\n\n /**\n * Check whether a normalized key exactly matches any sensitive field.\n * Both key and sensitive fields are normalized by removing all non-alphanumeric\n * characters and converting to lowercase before comparison.\n *\n * Examples:\n * - \"api_key\", \"api-key\", \"ApiKey\" all normalize to \"apikey\" → MATCHES \"apikey\"\n * - \"promptTokens\", \"prompt_tokens\" normalize to \"prompttokens\" → DOES NOT MATCH \"token\"\n */\n private isSensitive(normalizedKey: string): boolean {\n return this.sensitiveFields.some(sensitiveField => {\n // Simple case-insensitive match after normalization\n return normalizedKey === sensitiveField;\n });\n }\n\n /**\n * Redact a sensitive value.\n * - Full style: replaces with a fixed token.\n * - Partial style: shows 3 chars at start and end, hides the middle.\n *\n * Non-string values are converted to strings before partial redaction.\n */\n private redactValue(value: any): string {\n if (this.redactionStyle === 'full') {\n return this.redactionToken;\n }\n\n const str = String(value);\n const len = str.length;\n if (len <= 6) {\n return this.redactionToken; // too short, redact fully\n }\n return str.slice(0, 3) + '…' + str.slice(len - 3);\n }\n\n async shutdown(): Promise<void> {\n // No cleanup needed\n }\n}\n","/**\n * AI Tracing Registry for Mastra\n *\n * Provides a global registry for AI tracing instances.\n */\n\nimport { CloudExporter, DefaultExporter } from './exporters';\nimport { SensitiveDataFilter } from './span_processors';\nimport { BaseAITracing, DefaultAITracing } from './tracers';\nimport { SamplingStrategyType } from './types';\nimport type {\n AITracing,\n ConfigSelectorOptions,\n ConfigSelector,\n TracingConfig,\n ObservabilityRegistryConfig,\n} from './types';\n\n// ============================================================================\n// Global AI Tracing Registry\n// ============================================================================\n\n/**\n * Global registry for AI Tracing instances.\n */\nclass AITracingRegistry {\n private instances = new Map<string, AITracing>();\n private defaultInstance?: AITracing;\n private configSelector?: ConfigSelector;\n\n /**\n * Register a tracing instance\n */\n register(name: string, instance: AITracing, isDefault = false): void {\n if (this.instances.has(name)) {\n throw new Error(`AI Tracing instance '${name}' already registered`);\n }\n\n this.instances.set(name, instance);\n\n // Set as default if explicitly marked or if it's the first instance\n if (isDefault || !this.defaultInstance) {\n this.defaultInstance = instance;\n }\n }\n\n /**\n * Get a tracing instance by name\n */\n get(name: string): AITracing | undefined {\n return this.instances.get(name);\n }\n\n /**\n * Get the default tracing instance\n */\n getDefault(): AITracing | undefined {\n return this.defaultInstance;\n }\n\n /**\n * Set the tracing selector function\n */\n setSelector(selector: ConfigSelector): void {\n this.configSelector = selector;\n }\n\n /**\n * Get the selected tracing instance based on context\n */\n getSelected(options: ConfigSelectorOptions): AITracing | undefined {\n // 1. Try selector function if provided\n if (this.configSelector) {\n const selected = this.configSelector(options, this.instances);\n if (selected && this.instances.has(selected)) {\n return this.instances.get(selected);\n }\n }\n\n // 2. Fall back to default\n return this.defaultInstance;\n }\n\n /**\n * Unregister a tracing instance\n */\n unregister(name: string): boolean {\n return this.instances.delete(name);\n }\n\n /**\n * Shutdown all instances and clear the registry\n */\n async shutdown(): Promise<void> {\n const shutdownPromises = Array.from(this.instances.values()).map(instance => instance.shutdown());\n\n await Promise.allSettled(shutdownPromises);\n this.instances.clear();\n }\n\n /**\n * Clear all instances without shutdown\n */\n clear(): void {\n this.instances.clear();\n this.defaultInstance = undefined;\n this.configSelector = undefined;\n }\n\n /**\n * Get all registered instances\n */\n getAll(): ReadonlyMap<string, AITracing> {\n return new Map(this.instances);\n }\n}\n\nconst aiTracingRegistry = new AITracingRegistry();\n\n// ============================================================================\n// Registry Management Functions\n// ============================================================================\n\n/**\n * Register an AI tracing instance globally\n */\nexport function registerAITracing(name: string, instance: AITracing, isDefault = false): void {\n aiTracingRegistry.register(name, instance, isDefault);\n}\n\n/**\n * Get an AI tracing instance from the registry\n */\nexport function getAITracing(name: string): AITracing | undefined {\n return aiTracingRegistry.get(name);\n}\n\n/**\n * Get the default AI tracing instance\n */\nexport function getDefaultAITracing(): AITracing | undefined {\n return aiTracingRegistry.getDefault();\n}\n\n/**\n * Set the AI tracing config selector\n */\nexport function setSelector(selector: ConfigSelector): void {\n aiTracingRegistry.setSelector(selector);\n}\n\n/**\n * Get the selected AI tracing instance based on options\n */\nexport function getSelectedAITracing(options: ConfigSelectorOptions): AITracing | undefined {\n return aiTracingRegistry.getSelected(options);\n}\n\n/**\n * Unregister an AI tracing instance\n */\nexport function unregisterAITracing(name: string): boolean {\n return aiTracingRegistry.unregister(name);\n}\n\n/**\n * Shutdown all AI tracing instances and clear the registry\n */\nexport async function shutdownAITracingRegistry(): Promise<void> {\n await aiTracingRegistry.shutdown();\n}\n\n/**\n * Clear all AI tracing instances without shutdown\n */\nexport function clearAITracingRegistry(): void {\n aiTracingRegistry.clear();\n}\n\n/**\n * Get all registered AI tracing instances\n */\nexport function getAllAITracing(): ReadonlyMap<string, AITracing> {\n return aiTracingRegistry.getAll();\n}\n\n/**\n * Check if AI tracing is available and enabled\n */\nexport function hasAITracing(name: string): boolean {\n const tracing = getAITracing(name);\n if (!tracing) return false;\n\n const config = tracing.getConfig();\n const sampling = config.sampling;\n\n // Check if sampling allows tracing\n return sampling.type !== SamplingStrategyType.NEVER;\n}\n\n/**\n * Type guard to check if an object is a BaseAITracing instance\n */\nfunction isAITracingInstance(obj: Omit<TracingConfig, 'name'> | AITracing): obj is AITracing {\n return obj instanceof BaseAITracing;\n}\n\n/**\n * Setup AI tracing from the ObservabilityRegistryConfig\n */\nexport function setupAITracing(config: ObservabilityRegistryConfig): void {\n // Handle undefined/null config\n if (!config) {\n return;\n }\n\n // Check for naming conflict if default is enabled\n if (config.default?.enabled && config.configs?.['default']) {\n throw new Error(\n \"Cannot use 'default' as a custom config name when default tracing is enabled. \" +\n 'Please rename your custom config to avoid conflicts.',\n );\n }\n\n // Setup default config if enabled\n if (config.default?.enabled) {\n const defaultInstance = new DefaultAITracing({\n serviceName: 'mastra',\n name: 'default',\n sampling: { type: SamplingStrategyType.ALWAYS },\n exporters: [new DefaultExporter(), new CloudExporter()],\n processors: [new SensitiveDataFilter()],\n });\n\n // Register as default with high priority\n registerAITracing('default', defaultInstance, true);\n }\n\n if (config.configs) {\n // Process user-provided configs\n const instances = Object.entries(config.configs);\n\n instances.forEach(([name, tracingDef], index) => {\n const instance = isAITracingInstance(tracingDef)\n ? tracingDef // Pre-instantiated custom implementation\n : new DefaultAITracing({ ...tracingDef, name }); // Config -> DefaultAITracing with instance name\n\n // First user-provided instance becomes default only if no default config\n const isDefault = !config.default?.enabled && index === 0;\n registerAITracing(name, instance, isDefault);\n });\n }\n\n // Set selector function if provided\n if (config.configSelector) {\n setSelector(config.configSelector);\n }\n}\n","/**\n * Utility functions for cleaning and manipulating metadata objects\n * used in AI tracing and observability.\n */\n\nimport type { RuntimeContext } from '../runtime-context';\nimport { getSelectedAITracing } from './registry';\nimport type {\n AISpan,\n AISpanTypeMap,\n AnyAISpan,\n TracingContext,\n TracingOptions,\n TracingPolicy,\n AISpanType,\n} from './types';\n\n/**\n * Removes specific keys from an object.\n * @param obj - The original object\n * @param keysToOmit - Keys to exclude from the returned object\n * @returns A new object with the specified keys removed\n */\nexport function omitKeys<T extends Record<string, any>>(obj: T, keysToOmit: string[]): Partial<T> {\n return Object.fromEntries(Object.entries(obj).filter(([key]) => !keysToOmit.includes(key))) as Partial<T>;\n}\n\n/**\n * Selectively extracts specific fields from an object using dot notation.\n * Does not error if fields don't exist - simply omits them from the result.\n * @param obj - The source object to extract fields from\n * @param fields - Array of field paths (supports dot notation like 'output.text')\n * @returns New object containing only the specified fields\n */\nexport function selectFields(obj: any, fields: string[]): any {\n if (!obj || typeof obj !== 'object') {\n return obj;\n }\n\n const result: any = {};\n\n for (const field of fields) {\n const value = getNestedValue(obj, field);\n if (value !== undefined) {\n setNestedValue(result, field, value);\n }\n }\n\n return result;\n}\n\n/**\n * Gets a nested value from an object using dot notation\n * @param obj - Source object\n * @param path - Dot notation path (e.g., 'output.text')\n * @returns The value at the path, or undefined if not found\n */\nexport function getNestedValue(obj: any, path: string): any {\n return path.split('.').reduce((current, key) => {\n return current && typeof current === 'object' ? current[key] : undefined;\n }, obj);\n}\n\n/**\n * Sets a nested value in an object using dot notation\n * @param obj - Target object\n * @param path - Dot notation path (e.g., 'output.text')\n * @param value - Value to set\n */\nexport function setNestedValue(obj: any, path: string, value: any): void {\n const keys = path.split('.');\n const lastKey = keys.pop();\n if (!lastKey) {\n return;\n }\n\n const target = keys.reduce((current, key) => {\n if (!current[key] || typeof current[key] !== 'object') {\n current[key] = {};\n }\n return current[key];\n }, obj);\n\n target[lastKey] = value;\n}\n\n/**\n * Extracts the trace ID from a span if it is valid.\n *\n * This helper is typically used to safely retrieve the `traceId` from a span object,\n * while gracefully handling invalid spans — such as no-op spans — by returning `undefined`.\n *\n * A span is considered valid if `span.isValid` is `true`.\n *\n * @param span - The span object to extract the trace ID from. May be `undefined`.\n * @returns The `traceId` if the span is valid, otherwise `undefined`.\n */\nexport function getValidTraceId(span?: AnyAISpan): string | undefined {\n return span?.isValid ? span.traceId : undefined;\n}\n\n/**\n * Creates or gets a child span from existing tracing context or starts a new trace.\n * This helper consolidates the common pattern of creating spans that can either be:\n * 1. Children of an existing span (when tracingContext.currentSpan exists)\n * 2. New root spans (when no current span exists)\n *\n * @param options - Configuration object for span creation\n * @returns The created AI span or undefined if tracing is disabled\n */\nexport function getOrCreateSpan<T extends AISpanType>(options: {\n type: T;\n name: string;\n input?: any;\n attributes?: AISpanTypeMap[T];\n metadata?: Record<string, any>;\n tracingPolicy?: TracingPolicy;\n tracingOptions?: TracingOptions;\n tracingContext?: TracingContext;\n runtimeContext?: RuntimeContext;\n}): AISpan<T> | undefined {\n const { type, attributes, tracingContext, runtimeContext, tracingOptions, ...rest } = options;\n\n const metadata = {\n ...(rest.metadata ?? {}),\n ...(tracingOptions?.metadata ?? {}),\n };\n\n // If we have a current span, create a child span\n if (tracingContext?.currentSpan) {\n return tracingContext.currentSpan.createChildSpan({\n type,\n attributes,\n ...rest,\n metadata,\n });\n }\n\n // Otherwise, try to create a new root span\n const aiTracing = getSelectedAITracing({\n runtimeContext: runtimeContext,\n });\n\n return aiTracing?.startSpan<T>({\n type,\n attributes,\n ...rest,\n metadata,\n runtimeContext,\n tracingOptions,\n traceId: tracingOptions?.traceId,\n parentSpanId: tracingOptions?.parentSpanId,\n customSamplerOptions: {\n runtimeContext,\n metadata,\n },\n });\n}\n","/**\n * MastraAITracing - Abstract base class for AI Tracing implementations\n */\n\nimport { MastraBase } from '../../base';\nimport type { IMastraLogger } from '../../logger';\nimport { RegisteredLogger } from '../../logger/constants';\nimport type { RuntimeContext } from '../../runtime-context';\nimport { NoOpAISpan } from '../spans/no-op';\nimport type {\n TracingConfig,\n AISpan,\n AISpanType,\n AITracingExporter,\n AISpanProcessor,\n AITracingEvent,\n AnyAISpan,\n EndSpanOptions,\n UpdateSpanOptions,\n StartSpanOptions,\n CreateSpanOptions,\n AITracing,\n CustomSamplerOptions,\n AnyExportedAISpan,\n TraceState,\n TracingOptions,\n} from '../types';\nimport { SamplingStrategyType, AITracingEventType } from '../types';\nimport { getNestedValue, setNestedValue } from '../utils';\n\n// ============================================================================\n// Abstract Base Class\n// ============================================================================\n\n/**\n * Abstract base class for all AI Tracing implementations in Mastra.\n */\nexport abstract class BaseAITracing extends MastraBase implements AITracing {\n protected config: Required<TracingConfig>;\n\n constructor(config: TracingConfig) {\n super({ component: RegisteredLogger.AI_TRACING, name: config.serviceName });\n\n // Apply defaults for optional fields\n this.config = {\n serviceName: config.serviceName,\n name: config.name,\n sampling: config.sampling ?? { type: SamplingStrategyType.ALWAYS },\n exporters: config.exporters ?? [],\n processors: config.processors ?? [],\n includeInternalSpans: config.includeInternalSpans ?? false,\n runtimeContextKeys: config.runtimeContextKeys ?? [],\n };\n }\n\n /**\n * Override setLogger to add AI tracing specific initialization log\n * and propagate logger to exporters\n */\n __setLogger(logger: IMastraLogger) {\n super.__setLogger(logger);\n\n // Propagate logger to all exporters that support it\n this.exporters.forEach(exporter => {\n if (typeof exporter.__setLogger === 'function') {\n exporter.__setLogger(logger);\n }\n });\n\n // Log AI tracing initialization details after logger is properly set\n this.logger.debug(\n `[AI Tracing] Initialized [service=${this.config.serviceName}] [instance=${this.config.name}] [sampling=${this.config.sampling.type}]`,\n );\n }\n\n // ============================================================================\n // Protected getters for clean config access\n // ============================================================================\n\n protected get exporters(): AITracingExporter[] {\n return this.config.exporters || [];\n }\n\n protected get processors(): AISpanProcessor[] {\n return this.config.processors || [];\n }\n\n // ============================================================================\n // Public API - Single type-safe span creation method\n // ============================================================================\n\n /**\n * Start a new span of a specific AISpanType\n */\n startSpan<TType extends AISpanType>(options: StartSpanOptions<TType>): AISpan<TType> {\n const { customSamplerOptions, runtimeContext, metadata, tracingOptions, ...rest } = options;\n\n if (!this.shouldSample(customSamplerOptions)) {\n return new NoOpAISpan<TType>({ ...rest, metadata }, this);\n }\n\n // Compute or inherit TraceState\n let traceState: TraceState | undefined;\n\n if (options.parent) {\n // Child span: inherit from parent\n traceState = options.parent.traceState;\n } else {\n // Root span: compute new TraceState\n traceState = this.computeTraceState(tracingOptions);\n }\n\n // Extract metadata from RuntimeContext\n const enrichedMetadata = this.extractMetadataFromRuntimeContext(runtimeContext, metadata, traceState);\n\n const span = this.createSpan<TType>({\n ...rest,\n metadata: enrichedMetadata,\n traceState,\n });\n\n if (span.isEvent) {\n this.emitSpanEnded(span);\n } else {\n // Automatically wire up tracing lifecycle\n this.wireSpanLifecycle(span);\n\n // Emit span started event\n this.emitSpanStarted(span);\n }\n\n return span;\n }\n\n // ============================================================================\n // Abstract Methods - Must be implemented by concrete classes\n // ============================================================================\n\n /**\n * Create a new span (called after sampling)\n *\n * Implementations should:\n * 1. Create a plain span with the provided attributes\n * 2. Return the span - base class handles all tracing lifecycle automatically\n *\n * The base class will automatically:\n * - Set trace relationships\n * - Wire span lifecycle callbacks\n * - Emit span_started event\n */\n protected abstract createSpan<TType extends AISpanType>(options: CreateSpanOptions<TType>): AISpan<TType>;\n\n // ============================================================================\n // Configuration Management\n // ============================================================================\n\n /**\n * Get current configuration\n */\n getConfig(): Readonly<Required<TracingConfig>> {\n return { ...this.config };\n }\n\n // ============================================================================\n // Plugin Access\n // ============================================================================\n\n /**\n * Get all exporters\n */\n getExporters(): readonly AITracingExporter[] {\n return [...this.exporters];\n }\n\n /**\n * Get all processors\n */\n getProcessors(): readonly AISpanProcessor[] {\n return [...this.processors];\n }\n\n /**\n * Get the logger instance (for exporters and other components)\n */\n getLogger() {\n return this.logger;\n }\n\n // ============================================================================\n // Span Lifecycle Management\n // ============================================================================\n\n /**\n * Automatically wires up AI tracing lifecycle events for any span\n * This ensures all spans emit events regardless of implementation\n */\n private wireSpanLifecycle<TType extends AISpanType>(span: AISpan<TType>): void {\n // bypass wire up if internal span and not includeInternalSpans\n if (!this.config.includeInternalSpans && span.isInternal) {\n return;\n }\n\n // Store original methods\n const originalEnd = span.end.bind(span);\n const originalUpdate = span.update.bind(span);\n\n // Wrap methods to automatically emit tracing events\n span.end = (options?: EndSpanOptions<TType>) => {\n if (span.isEvent) {\n this.logger.warn(`End event is not available on event spans`);\n return;\n }\n originalEnd(options);\n this.emitSpanEnded(span);\n };\n\n span.update = (options: UpdateSpanOptions<TType>) => {\n if (span.isEvent) {\n this.logger.warn(`Update() is not available on event spans`);\n return;\n }\n originalUpdate(options);\n this.emitSpanUpdated(span);\n };\n }\n\n // ============================================================================\n // Utility Methods\n // ============================================================================\n\n /**\n * Check if an AI trace should be sampled\n */\n protected shouldSample(options?: CustomSamplerOptions): boolean {\n // Check built-in sampling strategy\n const { sampling } = this.config;\n\n switch (sampling.type) {\n case SamplingStrategyType.ALWAYS:\n return true;\n case SamplingStrategyType.NEVER:\n return false;\n case SamplingStrategyType.RATIO:\n if (sampling.probability === undefined || sampling.probability < 0 || sampling.probability > 1) {\n this.logger.warn(\n `Invalid sampling probability: ${sampling.probability}. Expected value between 0 and 1. Defaulting to no sampling.`,\n );\n return false;\n }\n return Math.random() < sampling.probability;\n case SamplingStrategyType.CUSTOM:\n return sampling.sampler(options);\n default:\n throw new Error(`Sampling strategy type not implemented: ${(sampling as any).type}`);\n }\n }\n\n /**\n * Compute TraceState for a new trace based on configured and per-request keys\n */\n protected computeTraceState(tracingOptions?: TracingOptions): TraceState | undefined {\n const configuredKeys = this.config.runtimeContextKeys ?? [];\n const additionalKeys = tracingOptions?.runtimeContextKeys ?? [];\n\n // Merge: configured + additional\n const allKeys = [...configuredKeys, ...additionalKeys];\n\n if (allKeys.length === 0) {\n return undefined; // No metadata extraction needed\n }\n\n return {\n runtimeContextKeys: allKeys,\n };\n }\n\n /**\n * Extract metadata from RuntimeContext using TraceState\n */\n protected extractMetadataFromRuntimeContext(\n runtimeContext: RuntimeContext | undefined,\n explicitMetadata: Record<string, any> | undefined,\n traceState: TraceState | undefined,\n ): Record<string, any> | undefined {\n if (!runtimeContext || !traceState || traceState.runtimeContextKeys.length === 0) {\n return explicitMetadata;\n }\n\n const extracted = this.extractKeys(runtimeContext, traceState.runtimeContextKeys);\n\n // Only return an object if we have extracted or explicit metadata\n if (Object.keys(extracted).length === 0 && !explicitMetadata) {\n return undefined;\n }\n\n return {\n ...extracted,\n ...explicitMetadata, // Explicit metadata always wins\n };\n }\n\n /**\n * Extract specific keys from RuntimeContext\n */\n protected extractKeys(runtimeContext: RuntimeContext, keys: string[]): Record<string, any> {\n const result: Record<string, any> = {};\n\n for (const key of keys) {\n // Handle dot notation: get first part from RuntimeContext, then navigate nested properties\n const parts = key.split('.');\n const rootKey = parts[0]!; // parts[0] always exists since key is a non-empty string\n const value = runtimeContext.get(rootKey);\n\n if (value !== undefined) {\n // If there are nested parts, extract them from the value\n if (parts.length > 1) {\n const nestedPath = parts.slice(1).join('.');\n const nestedValue = getNestedValue(value, nestedPath);\n if (nestedValue !== undefined) {\n setNestedValue(result, key, nestedValue);\n }\n } else {\n // Simple key, set directly\n setNestedValue(result, key, value);\n }\n }\n }\n\n return result;\n }\n\n /**\n * Process a span through all processors\n */\n private processSpan(span?: AnyAISpan): AnyAISpan | undefined {\n for (const processor of this.processors) {\n if (!span) {\n break;\n }\n\n try {\n span = processor.process(span);\n } catch (error) {\n this.logger.error(`[AI Tracing] Processor error [name=${processor.name}]`, error);\n // Continue with other processors\n }\n }\n\n return span;\n }\n\n // ============================================================================\n // Event-driven Export Methods\n // ============================================================================\n\n getSpanForExport(span: AnyAISpan): AnyExportedAISpan | undefined {\n if (!span.isValid) return undefined;\n if (span.isInternal && !this.config.includeInternalSpans) return undefined;\n\n const processedSpan = this.processSpan(span);\n return processedSpan?.exportSpan(this.config.includeInternalSpans);\n }\n\n /**\n * Emit a span started event\n */\n protected emitSpanStarted(span: AnyAISpan): void {\n const exportedSpan = this.getSpanForExport(span);\n if (exportedSpan) {\n this.exportEvent({ type: AITracingEventType.SPAN_STARTED, exportedSpan }).catch(error => {\n this.logger.error('[AI Tracing] Failed to export span_started event', error);\n });\n }\n }\n\n /**\n * Emit a span ended event (called automatically when spans end)\n */\n protected emitSpanEnded(span: AnyAISpan): void {\n const exportedSpan = this.getSpanForExport(span);\n if (exportedSpan) {\n this.exportEvent({ type: AITracingEventType.SPAN_ENDED, exportedSpan }).catch(error => {\n this.logger.error('[AI Tracing] Failed to export span_ended event', error);\n });\n }\n }\n\n /**\n * Emit a span updated event\n */\n protected emitSpanUpdated(span: AnyAISpan): void {\n const exportedSpan = this.getSpanForExport(span);\n if (exportedSpan) {\n this.exportEvent({ type: AITracingEventType.SPAN_UPDATED, exportedSpan }).catch(error => {\n this.logger.error('[AI Tracing] Failed to export span_updated event', error);\n });\n }\n }\n\n /**\n * Export tracing event through all exporters (realtime mode)\n */\n protected async exportEvent(event: AITracingEvent): Promise<void> {\n const exportPromises = this.exporters.map(async exporter => {\n try {\n if (exporter.exportEvent) {\n await exporter.exportEvent(event);\n this.logger.debug(`[AI Tracing] Event exported [exporter=${exporter.name}] [type=${event.type}]`);\n }\n } catch (error) {\n this.logger.error(`[AI Tracing] Export error [exporter=${exporter.name}]`, error);\n // Don't rethrow - continue with other exporters\n }\n });\n\n await Promise.allSettled(exportPromises);\n }\n\n // ============================================================================\n // Lifecycle Management\n // ============================================================================\n\n /**\n * Initialize AI tracing (called by Mastra during component registration)\n */\n init(): void {\n this.logger.debug(`[AI Tracing] Initialization started [name=${this.name}]`);\n\n // Any initialization logic for the AI tracing system\n // This could include setting up queues, starting background processes, etc.\n\n this.logger.info(`[AI Tracing] Initialized successfully [name=${this.name}]`);\n }\n\n /**\n * Shutdown AI tracing and clean up resources\n */\n async shutdown(): Promise<void> {\n this.logger.debug(`[AI Tracing] Shutdown started [name=${this.name}]`);\n\n // Shutdown all components\n const shutdownPromises = [...this.exporters.map(e => e.shutdown()), ...this.processors.map(p => p.shutdown())];\n\n await Promise.allSettled(shutdownPromises);\n\n this.logger.info(`[AI Tracing] Shutdown completed [name=${this.name}]`);\n }\n}\n","import { DefaultAISpan } from '../spans';\nimport type { AISpanType, AISpan, TracingConfig, CreateSpanOptions } from '../types';\nimport { BaseAITracing } from './base';\n\nexport class DefaultAITracing extends BaseAITracing {\n constructor(config: TracingConfig) {\n super(config);\n }\n\n protected createSpan<TType extends AISpanType>(options: CreateSpanOptions<TType>): AISpan<TType> {\n // Simple span creation - base class handles all tracing lifecycle automatically\n return new DefaultAISpan<TType>(options, this);\n }\n}\n","/**\n * AI Tracing Context Integration\n *\n * This module provides automatic AI tracing context propagation throughout Mastra's execution contexts.\n * It uses JavaScript Proxies to transparently wrap Mastra, Agent, and Workflow instances so that\n * tracing context is automatically injected without requiring manual passing by users.\n */\n\nimport type { MastraPrimitives } from '../action';\nimport type { Agent } from '../agent';\nimport type { Mastra } from '../mastra';\nimport type { Workflow } from '../workflows';\nimport type { TracingContext, AnyAISpan } from './types';\n\nconst AGENT_GETTERS = ['getAgent', 'getAgentById'];\nconst AGENT_METHODS_TO_WRAP = ['generate', 'stream', 'generateLegacy', 'streamLegacy'];\n\nconst WORKFLOW_GETTERS = ['getWorkflow', 'getWorkflowById'];\nconst WORKFLOW_METHODS_TO_WRAP = ['execute', 'createRun', 'createRunAsync'];\n\n/**\n * Helper function to detect NoOp spans to avoid unnecessary wrapping\n */\nfunction isNoOpSpan(span: AnyAISpan): boolean {\n // Check if this is a NoOp span implementation\n return span.constructor.name === 'NoOpAISpan' || (span as any).__isNoOp === true;\n}\n\n/**\n * Checks to see if a passed object is an actual instance of Mastra\n * (for the purposes of wrapping it for AI Tracing)\n */\nexport function isMastra<T extends Mastra | (Mastra & MastraPrimitives) | MastraPrimitives>(mastra: T): boolean {\n const hasAgentGetters = AGENT_GETTERS.every(method => typeof (mastra as any)?.[method] === 'function');\n const hasWorkflowGetters = WORKFLOW_GETTERS.every(method => typeof (mastra as any)?.[method] === 'function');\n\n return hasAgentGetters && hasWorkflowGetters;\n}\n\n/**\n * Creates a tracing-aware Mastra proxy that automatically injects\n * AI tracing context into agent and workflow method calls\n */\nexport function wrapMastra<T extends Mastra | (Mastra & MastraPrimitives) | MastraPrimitives>(\n mastra: T,\n tracingContext: TracingContext,\n): T {\n // Don't wrap if no current span or if using NoOp span\n if (!tracingContext.currentSpan || isNoOpSpan(tracingContext.currentSpan)) {\n return mastra;\n }\n\n // Check if this object has the methods we want to wrap - if not, return as is\n if (!isMastra(mastra)) {\n return mastra;\n }\n\n try {\n return new Proxy(mastra, {\n get(target, prop) {\n try {\n if (AGENT_GETTERS.includes(prop as string)) {\n return (...args: any[]) => {\n const agent = (target as any)[prop](...args);\n return wrapAgent(agent, tracingContext);\n };\n }\n\n // Wrap workflow getters\n if (WORKFLOW_GETTERS.includes(prop as string)) {\n return (...args: any[]) => {\n const workflow = (target as any)[prop](...args);\n return wrapWorkflow(workflow, tracingContext);\n };\n }\n\n // Pass through all other methods unchanged - bind functions to preserve 'this' context\n const value = (target as any)[prop];\n return typeof value === 'function' ? value.bind(target) : value;\n } catch (error) {\n console.warn('AI Tracing: Failed to wrap method, falling back to original', error);\n const value = (target as any)[prop];\n return typeof value === 'function' ? value.bind(target) : value;\n }\n },\n });\n } catch (error) {\n console.warn('AI Tracing: Failed to create proxy, using original Mastra instance', error);\n return mastra;\n }\n}\n\n/**\n * Creates a tracing-aware Agent proxy that automatically injects\n * AI tracing context into generation method calls\n */\nfunction wrapAgent<T extends Agent>(agent: T, tracingContext: TracingContext): T {\n // Don't wrap if no current span or if using NoOp span\n if (!tracingContext.currentSpan || isNoOpSpan(tracingContext.currentSpan)) {\n return agent;\n }\n\n try {\n return new Proxy(agent, {\n get(target, prop) {\n try {\n if (AGENT_METHODS_TO_WRAP.includes(prop as string)) {\n return (input: any, options: any = {}) => {\n return (target as any)[prop](input, {\n ...options,\n tracingContext,\n });\n };\n }\n\n // Bind functions to preserve 'this' context for private member access\n const value = (target as any)[prop];\n return typeof value === 'function' ? value.bind(target) : value;\n } catch (error) {\n console.warn('AI Tracing: Failed to wrap agent method, falling back to original', error);\n const value = (target as any)[prop];\n return typeof value === 'function' ? value.bind(target) : value;\n }\n },\n });\n } catch (error) {\n console.warn('AI Tracing: Failed to create agent proxy, using original instance', error);\n return agent;\n }\n}\n\n/**\n * Creates a tracing-aware Workflow proxy that automatically injects\n * AI tracing context into execution method calls\n */\nfunction wrapWorkflow<T extends Workflow>(workflow: T, tracingContext: TracingContext): T {\n // Don't wrap if no current span or if using NoOp span\n if (!tracingContext.currentSpan || isNoOpSpan(tracingContext.currentSpan)) {\n return workflow;\n }\n\n try {\n return new Proxy(workflow, {\n get(target, prop) {\n try {\n // Wrap workflow execution methods with tracing context\n if (WORKFLOW_METHODS_TO_WRAP.includes(prop as string)) {\n // Handle createRun and createRunAsync methods differently\n if (prop === 'createRun' || prop === 'createRunAsync') {\n return async (options: any = {}) => {\n const run = await (target as any)[prop](options);\n return run ? wrapRun(run, tracingContext) : run;\n };\n }\n\n // Handle other methods like execute\n return (input: any, options: any = {}) => {\n return (target as any)[prop](input, {\n ...options,\n tracingContext,\n });\n };\n }\n\n // Bind functions to preserve 'this' context for private member access\n const value = (target as any)[prop];\n return typeof value === 'function' ? value.bind(target) : value;\n } catch (error) {\n console.warn('AI Tracing: Failed to wrap workflow method, falling back to original', error);\n const value = (target as any)[prop];\n return typeof value === 'function' ? value.bind(target) : value;\n }\n },\n });\n } catch (error) {\n console.warn('AI Tracing: Failed to create workflow proxy, using original instance', error);\n return workflow;\n }\n}\n\n/**\n * Creates a tracing-aware Run proxy that automatically injects\n * AI tracing context into start method calls\n */\nfunction wrapRun<T extends object>(run: T, tracingContext: TracingContext): T {\n // Don't wrap if no current span or if using NoOp span\n if (!tracingContext.currentSpan || isNoOpSpan(tracingContext.currentSpan)) {\n return run;\n }\n\n try {\n return new Proxy(run, {\n get(target, prop) {\n try {\n if (prop === 'start') {\n return (startOptions: any = {}) => {\n return (target as any).start({\n ...startOptions,\n tracingContext: startOptions.tracingContext ?? tracingContext,\n });\n };\n }\n\n // Pass through all other properties and methods unchanged\n const value = (target as any)[prop];\n return typeof value === 'function' ? value.bind(target) : value;\n } catch (error) {\n console.warn('AI Tracing: Failed to wrap run method, falling back to original', error);\n const value = (target as any)[prop];\n return typeof value === 'function' ? value.bind(target) : value;\n }\n },\n });\n } catch (error) {\n console.warn('AI Tracing: Failed to create run proxy, using original instance', error);\n return run;\n }\n}\n","/**\n * Model Span Tracing\n *\n * Provides span tracking for Model generations, including:\n * - MODEL_STEP spans (one per Model API call)\n * - MODEL_CHUNK spans (individual streaming chunks within a step)\n *\n * Hierarchy: MODEL_GENERATION -> MODEL_STEP -> MODEL_CHUNK\n */\n\nimport { TransformStream } from 'stream/web';\nimport type { ToolSet } from 'ai-v5';\nimport type { MastraError } from '../error';\nimport type { OutputSchema } from '../stream/base/schema';\nimport type { ChunkType, StepStartPayload, StepFinishPayload } from '../stream/types';\nimport { AISpanType } from './types';\nimport type { AISpan, AnyAISpan, ModelGenerationAttributes } from './types';\n\n/**\n * Manages MODEL_STEP and MODEL_CHUNK span tracking for streaming Model responses.\n *\n * Should be instantiated once per MODEL_GENERATION span and shared across\n * all streaming steps (including after tool calls).\n */\nexport class ModelSpanTracker {\n #modelSpan?: AISpan<AISpanType.MODEL_GENERATION>;\n #currentStepSpan?: AISpan<AISpanType.MODEL_STEP>;\n #currentChunkSpan?: AISpan<AISpanType.MODEL_CHUNK>;\n #accumulator: Record<string, any> = {};\n #stepIndex: number = 0;\n #chunkSequence: number = 0;\n\n constructor(modelSpan?: AISpan<AISpanType.MODEL_GENERATION>) {\n this.#modelSpan = modelSpan;\n }\n\n /**\n * Get the tracing context for creating child spans.\n * Returns the current step span if active, otherwise the model span.\n */\n getTracingContext(): { currentSpan?: AnyAISpan } {\n return {\n currentSpan: this.#currentStepSpan ?? this.#modelSpan,\n };\n }\n\n /**\n * Report an error on the generation span\n */\n reportGenerationError(options: { error: MastraError | Error; endSpan?: boolean }): void {\n this.#modelSpan?.error(options);\n }\n\n /**\n * End the generation span\n */\n endGeneration(options?: {\n output?: any;\n attributes?: Partial<ModelGenerationAttributes>;\n metadata?: Record<string, any>;\n }): void {\n this.#modelSpan?.end(options);\n }\n\n /**\n * Update the generation span\n */\n updateGeneration(options: {\n input?: any;\n output?: any;\n attributes?: Partial<ModelGenerationAttributes>;\n metadata?: Record<string, any>;\n }): void {\n this.#modelSpan?.update(options);\n }\n\n /**\n * Start a new Model execution step\n */\n #startStepSpan(payload?: StepStartPayload) {\n this.#currentStepSpan = this.#modelSpan?.createChildSpan({\n name: `step: ${this.#stepIndex}`,\n type: AISpanType.MODEL_STEP,\n attributes: {\n stepIndex: this.#stepIndex,\n ...(payload?.messageId ? { messageId: payload.messageId } : {}),\n ...(payload?.warnings?.length ? { warnings: payload.warnings } : {}),\n },\n input: payload?.request,\n });\n // Reset chunk sequence for new step\n this.#chunkSequence = 0;\n }\n\n /**\n * End the current Model execution step with token usage, finish reason, output, and metadata\n */\n #endStepSpan<OUTPUT extends OutputSchema>(payload: StepFinishPayload<ToolSet, OUTPUT>) {\n if (!this.#currentStepSpan) return;\n\n // Extract all data from step-finish chunk\n const output = payload.output;\n const { usage, ...otherOutput } = output;\n const stepResult = payload.stepResult;\n const metadata = payload.metadata;\n\n // Remove request object from metadata (too verbose)\n const cleanMetadata = metadata ? { ...metadata } : undefined;\n if (cleanMetadata?.request) {\n delete cleanMetadata.request;\n }\n\n this.#currentStepSpan.end({\n output: otherOutput,\n attributes: {\n usage,\n isContinued: stepResult.isContinued,\n finishReason: stepResult.reason,\n warnings: stepResult.warnings,\n },\n metadata: {\n ...cleanMetadata,\n },\n });\n this.#currentStepSpan = undefined;\n this.#stepIndex++;\n }\n\n /**\n * Create a new chunk span (for multi-part chunks like text-start/delta/end)\n */\n #startChunkSpan(chunkType: string, initialData?: Record<string, any>) {\n // Auto-create step if we see a chunk before step-start\n if (!this.#currentStepSpan) {\n this.#startStepSpan();\n }\n\n this.#currentChunkSpan = this.#currentStepSpan?.createChildSpan({\n name: `chunk: '${chunkType}'`,\n type: AISpanType.MODEL_CHUNK,\n attributes: {\n chunkType,\n sequenceNumber: this.#chunkSequence,\n },\n });\n this.#accumulator = initialData || {};\n }\n\n /**\n * Append string content to a specific field in the accumulator\n */\n #appendToAccumulator(field: string, text: string) {\n if (this.#accumulator[field] === undefined) {\n this.#accumulator[field] = text;\n } else {\n this.#accumulator[field] += text;\n }\n }\n\n /**\n * End the current chunk span.\n * Safe to call multiple times - will no-op if span already ended.\n */\n #endChunkSpan(output?: any) {\n if (!this.#currentChunkSpan) return;\n\n this.#currentChunkSpan.end({\n output: output !== undefined ? output : this.#accumulator,\n });\n this.#currentChunkSpan = undefined;\n this.#accumulator = {};\n this.#chunkSequence++;\n }\n\n /**\n * Create an event span (for single chunks like tool-call)\n */\n #createEventSpan(chunkType: string, output: any) {\n // Auto-create step if we see a chunk before step-start\n if (!this.#currentStepSpan) {\n this.#startStepSpan();\n }\n\n const span = this.#currentStepSpan?.createEventSpan({\n name: `chunk: '${chunkType}'`,\n type: AISpanType.MODEL_CHUNK,\n attributes: {\n chunkType,\n sequenceNumber: this.#chunkSequence,\n },\n output,\n });\n\n if (span) {\n this.#chunkSequence++;\n }\n }\n\n /**\n * Check if there is currently an active chunk span\n */\n #hasActiveChunkSpan(): boolean {\n return !!this.#currentChunkSpan;\n }\n\n /**\n * Get the current accumulator value\n */\n #getAccumulator(): Record<string, any> {\n return this.#accumulator;\n }\n\n /**\n * Handle text chunk spans (text-start/delta/end)\n */\n #handleTextChunk<OUTPUT extends OutputSchema>(chunk: ChunkType<OUTPUT>) {\n switch (chunk.type) {\n case 'text-start':\n this.#startChunkSpan('text');\n break;\n\n case 'text-delta':\n this.#appendToAccumulator('text', chunk.payload.text);\n break;\n\n case 'text-end': {\n this.#endChunkSpan();\n break;\n }\n }\n }\n\n /**\n * Handle reasoning chunk spans (reasoning-start/delta/end)\n */\n #handleReasoningChunk<OUTPUT extends OutputSchema>(chunk: ChunkType<OUTPUT>) {\n switch (chunk.type) {\n case 'reasoning-start':\n this.#startChunkSpan('reasoning');\n break;\n\n case 'reasoning-delta':\n this.#appendToAccumulator('text', chunk.payload.text);\n break;\n\n case 'reasoning-end': {\n this.#endChunkSpan();\n break;\n }\n }\n }\n\n /**\n * Handle tool call chunk spans (tool-call-input-streaming-start/delta/end, tool-call)\n */\n #handleToolCallChunk<OUTPUT extends OutputSchema>(chunk: ChunkType<OUTPUT>) {\n switch (chunk.type) {\n case 'tool-call-input-streaming-start':\n this.#startChunkSpan('tool-call', {\n toolName: chunk.payload.toolName,\n toolCallId: chunk.payload.toolCallId,\n });\n break;\n\n case 'tool-call-delta':\n this.#appendToAccumulator('toolInput', chunk.payload.argsTextDelta);\n break;\n\n case 'tool-call-input-streaming-end':\n case 'tool-call': {\n // Build output with toolName, toolCallId, and parsed toolInput\n const acc = this.#getAccumulator();\n let toolInput;\n try {\n toolInput = acc.toolInput ? JSON.parse(acc.toolInput) : {};\n } catch {\n toolInput = acc.toolInput; // Keep as string if parsing fails\n }\n this.#endChunkSpan({\n toolName: acc.toolName,\n toolCallId: acc.toolCallId,\n toolInput,\n });\n break;\n }\n }\n }\n\n /**\n * Handle object chunk spans (object, object-result)\n */\n #handleObjectChunk<OUTPUT extends OutputSchema>(chunk: ChunkType<OUTPUT>) {\n switch (chunk.type) {\n case 'object':\n // Start span on first partial object chunk (only if not already started)\n // Multiple object chunks may arrive as the object is being generated\n if (!this.#hasActiveChunkSpan()) {\n this.#startChunkSpan('object');\n }\n break;\n\n case 'object-result':\n // End the span with the final complete object as output\n this.#endChunkSpan(chunk.object);\n break;\n }\n }\n\n /**\n * Wraps a stream with model tracing transform to track MODEL_STEP and MODEL_CHUNK spans.\n *\n * This should be added to the stream pipeline to automatically\n * create MODEL_STEP and MODEL_CHUNK spans for each semantic unit in the stream.\n */\n wrapStream<T extends { pipeThrough: Function }>(stream: T): T {\n return stream.pipeThrough(\n new TransformStream({\n transform: (chunk, controller) => {\n controller.enqueue(chunk);\n\n // Handle chunk span tracking based on chunk type\n switch (chunk.type) {\n case 'text-start':\n case 'text-delta':\n case 'text-end':\n this.#handleTextChunk(chunk);\n break;\n\n case 'tool-call-input-streaming-start':\n case 'tool-call-delta':\n case 'tool-call-input-streaming-end':\n case 'tool-call':\n this.#handleToolCallChunk(chunk);\n break;\n\n case 'reasoning-start':\n case 'reasoning-delta':\n case 'reasoning-end':\n this.#handleReasoningChunk(chunk);\n break;\n\n case 'object':\n case 'object-result':\n this.#handleObjectChunk(chunk);\n break;\n\n case 'step-start':\n this.#startStepSpan(chunk.payload);\n break;\n\n case 'step-finish':\n this.#endStepSpan(chunk.payload);\n break;\n\n case 'raw': // Skip raw chunks as they're redundant\n case 'start':\n case 'finish':\n // don't output these chunks that don't have helpful output\n break;\n\n // Default: auto-create event span for all other chunk types\n default: {\n let outputPayload = chunk.payload;\n\n // Special handling: if payload has 'data' field, replace with size\n if (outputPayload && typeof outputPayload === 'object' && 'data' in outputPayload) {\n const typedPayload = outputPayload as any;\n outputPayload = { ...typedPayload };\n if (typedPayload.data) {\n (outputPayload as any).size =\n typeof typedPayload.data === 'string'\n ? typedPayload.data.length\n : typedPayload.data instanceof Uint8Array\n ? typedPayload.data.length\n : undefined;\n delete (outputPayload as any).data;\n }\n }\n\n this.#createEventSpan(chunk.type, outputPayload);\n break;\n }\n }\n },\n }),\n ) as T;\n }\n}\n"]}