@mastra/core 1.0.0-beta.7 → 1.0.0-beta.9

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 (183) hide show
  1. package/CHANGELOG.md +77 -0
  2. package/dist/agent/agent.d.ts +1 -1
  3. package/dist/agent/agent.d.ts.map +1 -1
  4. package/dist/agent/index.cjs +9 -9
  5. package/dist/agent/index.js +2 -2
  6. package/dist/agent/message-list/index.cjs +3 -3
  7. package/dist/agent/message-list/index.js +1 -1
  8. package/dist/agent/workflows/prepare-stream/index.d.ts +2 -1
  9. package/dist/agent/workflows/prepare-stream/index.d.ts.map +1 -1
  10. package/dist/agent/workflows/prepare-stream/stream-step.d.ts +2 -1
  11. package/dist/agent/workflows/prepare-stream/stream-step.d.ts.map +1 -1
  12. package/dist/{chunk-PJ7AYWAX.cjs → chunk-3DRGAKUH.cjs} +382 -13
  13. package/dist/chunk-3DRGAKUH.cjs.map +1 -0
  14. package/dist/{chunk-EE5NIGJ4.js → chunk-4GLDYGNN.js} +3 -3
  15. package/dist/{chunk-EE5NIGJ4.js.map → chunk-4GLDYGNN.js.map} +1 -1
  16. package/dist/{chunk-4GTU7MB2.js → chunk-7IMDJAYQ.js} +5 -5
  17. package/dist/{chunk-4GTU7MB2.js.map → chunk-7IMDJAYQ.js.map} +1 -1
  18. package/dist/{chunk-M7CQULF7.cjs → chunk-7S7TLMTS.cjs} +287 -10
  19. package/dist/chunk-7S7TLMTS.cjs.map +1 -0
  20. package/dist/{chunk-NAKPEQEQ.js → chunk-A4C3AGVS.js} +5 -5
  21. package/dist/{chunk-NAKPEQEQ.js.map → chunk-A4C3AGVS.js.map} +1 -1
  22. package/dist/{chunk-DMPHPHMU.js → chunk-APMPOYPI.js} +3 -3
  23. package/dist/{chunk-DMPHPHMU.js.map → chunk-APMPOYPI.js.map} +1 -1
  24. package/dist/{chunk-POM7FCH5.js → chunk-ARSSSQQP.js} +141 -48
  25. package/dist/chunk-ARSSSQQP.js.map +1 -0
  26. package/dist/{chunk-HJNEZRI4.cjs → chunk-CKRWR5DS.cjs} +15 -15
  27. package/dist/{chunk-HJNEZRI4.cjs.map → chunk-CKRWR5DS.cjs.map} +1 -1
  28. package/dist/{chunk-26YAGTXK.cjs → chunk-DWB7SBVC.cjs} +28 -32
  29. package/dist/chunk-DWB7SBVC.cjs.map +1 -0
  30. package/dist/{chunk-URMN7TTH.cjs → chunk-EGXQVF75.cjs} +380 -6
  31. package/dist/chunk-EGXQVF75.cjs.map +1 -0
  32. package/dist/{chunk-4AP234N6.cjs → chunk-F77YTHXI.cjs} +4 -4
  33. package/dist/{chunk-4AP234N6.cjs.map → chunk-F77YTHXI.cjs.map} +1 -1
  34. package/dist/{chunk-6C2PU6J4.cjs → chunk-HSRQXO6F.cjs} +6 -6
  35. package/dist/{chunk-6C2PU6J4.cjs.map → chunk-HSRQXO6F.cjs.map} +1 -1
  36. package/dist/{chunk-YUXTDKYN.cjs → chunk-IISGCZJ4.cjs} +15 -15
  37. package/dist/{chunk-YUXTDKYN.cjs.map → chunk-IISGCZJ4.cjs.map} +1 -1
  38. package/dist/{chunk-EPMSC67U.js → chunk-LB7UOP2X.js} +376 -7
  39. package/dist/chunk-LB7UOP2X.js.map +1 -0
  40. package/dist/{chunk-URBPEE67.js → chunk-MCRIVYUB.js} +3 -3
  41. package/dist/{chunk-URBPEE67.js.map → chunk-MCRIVYUB.js.map} +1 -1
  42. package/dist/{chunk-AZQMPE7G.cjs → chunk-MRFUISXC.cjs} +3 -3
  43. package/dist/{chunk-AZQMPE7G.cjs.map → chunk-MRFUISXC.cjs.map} +1 -1
  44. package/dist/{chunk-TLLXRG2Z.js → chunk-OEIVMCWX.js} +3 -3
  45. package/dist/{chunk-TLLXRG2Z.js.map → chunk-OEIVMCWX.js.map} +1 -1
  46. package/dist/{chunk-FNSFXWDN.js → chunk-PIHOAJTA.js} +2 -2
  47. package/dist/chunk-PIHOAJTA.js.map +1 -0
  48. package/dist/{chunk-ZUWJCGLM.js → chunk-QM5SRDJX.js} +4 -5
  49. package/dist/chunk-QM5SRDJX.js.map +1 -0
  50. package/dist/{chunk-Z4Y554NX.js → chunk-QTEIZ2XG.js} +8 -12
  51. package/dist/chunk-QTEIZ2XG.js.map +1 -0
  52. package/dist/{chunk-VBKMNIWK.cjs → chunk-RIG4JP3V.cjs} +11 -11
  53. package/dist/{chunk-VBKMNIWK.cjs.map → chunk-RIG4JP3V.cjs.map} +1 -1
  54. package/dist/{chunk-5T53HHNP.js → chunk-SLX3NVAC.js} +4 -4
  55. package/dist/{chunk-5T53HHNP.js.map → chunk-SLX3NVAC.js.map} +1 -1
  56. package/dist/{chunk-TQB2HMEC.cjs → chunk-SVLMF4UZ.cjs} +44 -45
  57. package/dist/chunk-SVLMF4UZ.cjs.map +1 -0
  58. package/dist/{chunk-3EYBRHB2.cjs → chunk-UVM27J4A.cjs} +2 -2
  59. package/dist/chunk-UVM27J4A.cjs.map +1 -0
  60. package/dist/{chunk-GZ6MCDK2.js → chunk-VQ3FTSRC.js} +379 -5
  61. package/dist/chunk-VQ3FTSRC.js.map +1 -0
  62. package/dist/{chunk-YBEW5YWC.cjs → chunk-VRFSEZBA.cjs} +6 -6
  63. package/dist/{chunk-YBEW5YWC.cjs.map → chunk-VRFSEZBA.cjs.map} +1 -1
  64. package/dist/{chunk-RBBEMTMA.cjs → chunk-XMT5T4F2.cjs} +184 -89
  65. package/dist/chunk-XMT5T4F2.cjs.map +1 -0
  66. package/dist/{chunk-G32WDDGV.js → chunk-ZINZHEXZ.js} +282 -9
  67. package/dist/chunk-ZINZHEXZ.js.map +1 -0
  68. package/dist/evals/index.cjs +9 -9
  69. package/dist/evals/index.js +2 -2
  70. package/dist/evals/scoreTraces/index.cjs +5 -5
  71. package/dist/evals/scoreTraces/index.js +2 -2
  72. package/dist/evals/types.d.ts +21 -20
  73. package/dist/evals/types.d.ts.map +1 -1
  74. package/dist/index.cjs +2 -2
  75. package/dist/index.js +1 -1
  76. package/dist/llm/index.cjs +11 -11
  77. package/dist/llm/index.js +3 -3
  78. package/dist/llm/model/model.loop.d.ts +1 -1
  79. package/dist/llm/model/model.loop.d.ts.map +1 -1
  80. package/dist/llm/model/provider-types.generated.d.ts +180 -1
  81. package/dist/loop/index.cjs +2 -2
  82. package/dist/loop/index.js +1 -1
  83. package/dist/loop/network/index.d.ts +2 -2
  84. package/dist/loop/network/index.d.ts.map +1 -1
  85. package/dist/loop/types.d.ts +1 -0
  86. package/dist/loop/types.d.ts.map +1 -1
  87. package/dist/mastra/index.cjs +2 -2
  88. package/dist/mastra/index.d.ts +191 -5
  89. package/dist/mastra/index.d.ts.map +1 -1
  90. package/dist/mastra/index.js +1 -1
  91. package/dist/memory/index.cjs +6 -6
  92. package/dist/memory/index.js +1 -1
  93. package/dist/memory/memory.d.ts +6 -0
  94. package/dist/memory/memory.d.ts.map +1 -1
  95. package/dist/models-dev-23RN2WHG.js +3 -0
  96. package/dist/{models-dev-6GD3644V.js.map → models-dev-23RN2WHG.js.map} +1 -1
  97. package/dist/models-dev-EO3SUIY2.cjs +12 -0
  98. package/dist/{models-dev-IUQBXJSS.cjs.map → models-dev-EO3SUIY2.cjs.map} +1 -1
  99. package/dist/observability/index.cjs +10 -10
  100. package/dist/observability/index.js +1 -1
  101. package/dist/observability/types/tracing.d.ts +4 -0
  102. package/dist/observability/types/tracing.d.ts.map +1 -1
  103. package/dist/processors/index.cjs +17 -17
  104. package/dist/processors/index.js +1 -1
  105. package/dist/provider-registry-FM3IVY6C.js +3 -0
  106. package/dist/{provider-registry-ZTMZMTVV.js.map → provider-registry-FM3IVY6C.js.map} +1 -1
  107. package/dist/provider-registry-Q6T32VC5.cjs +40 -0
  108. package/dist/{provider-registry-7IFOXWPR.cjs.map → provider-registry-Q6T32VC5.cjs.map} +1 -1
  109. package/dist/provider-registry.json +376 -2
  110. package/dist/relevance/index.cjs +2 -2
  111. package/dist/relevance/index.js +1 -1
  112. package/dist/storage/base.d.ts +50 -2
  113. package/dist/storage/base.d.ts.map +1 -1
  114. package/dist/storage/constants.d.ts +3 -1
  115. package/dist/storage/constants.d.ts.map +1 -1
  116. package/dist/storage/domains/agents/base.d.ts +49 -0
  117. package/dist/storage/domains/agents/base.d.ts.map +1 -0
  118. package/dist/storage/domains/agents/index.d.ts +3 -0
  119. package/dist/storage/domains/agents/index.d.ts.map +1 -0
  120. package/dist/storage/domains/agents/inmemory.d.ts +22 -0
  121. package/dist/storage/domains/agents/inmemory.d.ts.map +1 -0
  122. package/dist/storage/domains/index.d.ts +1 -0
  123. package/dist/storage/domains/index.d.ts.map +1 -1
  124. package/dist/storage/domains/operations/inmemory.d.ts.map +1 -1
  125. package/dist/storage/domains/scores/base.d.ts +2 -2
  126. package/dist/storage/domains/scores/base.d.ts.map +1 -1
  127. package/dist/storage/domains/scores/inmemory.d.ts +2 -2
  128. package/dist/storage/domains/scores/inmemory.d.ts.map +1 -1
  129. package/dist/storage/index.cjs +50 -34
  130. package/dist/storage/index.js +1 -1
  131. package/dist/storage/mock.d.ts +3 -2
  132. package/dist/storage/mock.d.ts.map +1 -1
  133. package/dist/storage/types.d.ts +82 -0
  134. package/dist/storage/types.d.ts.map +1 -1
  135. package/dist/stream/base/output-format-handlers.d.ts +13 -0
  136. package/dist/stream/base/output-format-handlers.d.ts.map +1 -1
  137. package/dist/stream/index.cjs +15 -11
  138. package/dist/stream/index.d.ts +1 -1
  139. package/dist/stream/index.d.ts.map +1 -1
  140. package/dist/stream/index.js +2 -2
  141. package/dist/test-utils/llm-mock.cjs +10 -10
  142. package/dist/test-utils/llm-mock.js +3 -3
  143. package/dist/utils.cjs +22 -22
  144. package/dist/utils.d.ts +1 -1
  145. package/dist/utils.d.ts.map +1 -1
  146. package/dist/utils.js +1 -1
  147. package/dist/vector/index.cjs +2 -2
  148. package/dist/vector/index.js +1 -1
  149. package/dist/workflows/default.d.ts +2 -2
  150. package/dist/workflows/default.d.ts.map +1 -1
  151. package/dist/workflows/evented/index.cjs +10 -10
  152. package/dist/workflows/evented/index.js +1 -1
  153. package/dist/workflows/evented/step-executor.d.ts.map +1 -1
  154. package/dist/workflows/handlers/control-flow.d.ts.map +1 -1
  155. package/dist/workflows/handlers/step.d.ts.map +1 -1
  156. package/dist/workflows/index.cjs +24 -20
  157. package/dist/workflows/index.js +1 -1
  158. package/dist/workflows/step.d.ts +4 -3
  159. package/dist/workflows/step.d.ts.map +1 -1
  160. package/dist/workflows/utils.d.ts +10 -1
  161. package/dist/workflows/utils.d.ts.map +1 -1
  162. package/dist/workflows/workflow.d.ts +3 -3
  163. package/dist/workflows/workflow.d.ts.map +1 -1
  164. package/package.json +3 -3
  165. package/src/llm/model/provider-types.generated.d.ts +180 -1
  166. package/dist/chunk-26YAGTXK.cjs.map +0 -1
  167. package/dist/chunk-3EYBRHB2.cjs.map +0 -1
  168. package/dist/chunk-EPMSC67U.js.map +0 -1
  169. package/dist/chunk-FNSFXWDN.js.map +0 -1
  170. package/dist/chunk-G32WDDGV.js.map +0 -1
  171. package/dist/chunk-GZ6MCDK2.js.map +0 -1
  172. package/dist/chunk-M7CQULF7.cjs.map +0 -1
  173. package/dist/chunk-PJ7AYWAX.cjs.map +0 -1
  174. package/dist/chunk-POM7FCH5.js.map +0 -1
  175. package/dist/chunk-RBBEMTMA.cjs.map +0 -1
  176. package/dist/chunk-TQB2HMEC.cjs.map +0 -1
  177. package/dist/chunk-URMN7TTH.cjs.map +0 -1
  178. package/dist/chunk-Z4Y554NX.js.map +0 -1
  179. package/dist/chunk-ZUWJCGLM.js.map +0 -1
  180. package/dist/models-dev-6GD3644V.js +0 -3
  181. package/dist/models-dev-IUQBXJSS.cjs +0 -12
  182. package/dist/provider-registry-7IFOXWPR.cjs +0 -40
  183. package/dist/provider-registry-ZTMZMTVV.js +0 -3
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/observability/types/tracing.ts","../src/observability/no-op.ts","../src/observability/utils.ts","../src/observability/context.ts"],"names":["SpanType","InternalSpans","SamplingStrategyType","TracingEventType"],"mappings":";;;AAgB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AAA,CAA0B,KAAQ,cAAA,EAAmC;AAE5E,EAAA,IAAI,CAAC,cAAA,CAAe,WAAA,IAAe,UAAA,CAAW,cAAA,CAAe,WAAW,CAAA,EAAG;AACzE,IAAA,OAAO,GAAA;AAAA,EACT;AAEA,EAAA,IAAI;AACF,IAAA,OAAO,IAAI,MAAM,GAAA,EAAK;AAAA,MACpB,GAAA,CAAI,QAAQ,IAAA,EAAM;AAChB,QAAA,IAAI;AACF,UAAA,IAAI,SAAS,OAAA,EAAS;AACpB,YAAA,OAAO,CAAC,YAAA,GAAoB,EAAC,KAAM;AACjC,cAAA,OAAQ,OAAe,KAAA,CAAM;AAAA,gBAC3B,GAAG,YAAA;AAAA,gBACH,cAAA,EAAgB,aAAa,cAAA,IAAkB;AAAA,eAChD,CAAA;AAAA,YACH,CAAA;AAAA,UACF;AAGA,UAAA,MAAM,KAAA,GAAS,OAAe,IAAI,CAAA;AAClC,UAAA,OAAO,OAAO,KAAA,KAAU,UAAA,GAAa,KAAA,CAAM,IAAA,CAAK,MAAM,CAAA,GAAI,KAAA;AAAA,QAC5D,SAAS,KAAA,EAAO;AACd,UAAA,OAAA,CAAQ,IAAA,CAAK,gEAAgE,KAAK,CAAA;AAClF,UAAA,MAAM,KAAA,GAAS,OAAe,IAAI,CAAA;AAClC,UAAA,OAAO,OAAO,KAAA,KAAU,UAAA,GAAa,KAAA,CAAM,IAAA,CAAK,MAAM,CAAA,GAAI,KAAA;AAAA,QAC5D;AAAA,MACF;AAAA,KACD,CAAA;AAAA,EACH,SAAS,KAAA,EAAO;AACd,IAAA,OAAA,CAAQ,IAAA,CAAK,gEAAgE,KAAK,CAAA;AAClF,IAAA,OAAO,GAAA;AAAA,EACT;AACF","file":"chunk-3EYBRHB2.cjs","sourcesContent":["/**\n * Tracing interfaces\n */\nimport type { MastraError } from '../../error';\nimport type { IMastraLogger } from '../../logger';\nimport type { Mastra } from '../../mastra';\nimport type { RequestContext } from '../../request-context';\nimport type { WorkflowRunStatus, WorkflowStepStatus } from '../../workflows';\n\n// ============================================================================\n// Span Types\n// ============================================================================\n\n/**\n * AI-specific span types with their associated metadata\n */\nexport enum SpanType {\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 /** Human-readable agent name */\n agentName?: string;\n /** Conversation/thread/session identifier for multi-turn interactions */\n conversationId?: 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 * When the first token/chunk of the completion was received.\n * Used to calculate time-to-first-token (TTFT) metrics.\n * Only applicable for streaming responses.\n */\n completionStartTime?: Date;\n /** Actual model used in the response (may differ from request model) */\n responseModel?: string;\n /** Unique identifier for the response */\n responseId?: string;\n /** Server address for the model endpoint */\n serverAddress?: string;\n /** Server port for the model endpoint */\n serverPort?: number;\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 /** MessageList mutations performed by this processor */\n messageListMutations?: Array<{\n type: 'add' | 'addSystem' | 'removeByIds' | 'clear';\n source?: string;\n count?: number;\n ids?: string[];\n text?: string;\n tag?: string;\n message?: any;\n }>;\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 SpanTypeMap {\n [SpanType.AGENT_RUN]: AgentRunAttributes;\n [SpanType.WORKFLOW_RUN]: WorkflowRunAttributes;\n [SpanType.MODEL_GENERATION]: ModelGenerationAttributes;\n [SpanType.MODEL_STEP]: ModelStepAttributes;\n [SpanType.MODEL_CHUNK]: ModelChunkAttributes;\n [SpanType.TOOL_CALL]: ToolCallAttributes;\n [SpanType.MCP_TOOL_CALL]: MCPToolCallAttributes;\n [SpanType.PROCESSOR_RUN]: ProcessorRunAttributes;\n [SpanType.WORKFLOW_STEP]: WorkflowStepAttributes;\n [SpanType.WORKFLOW_CONDITIONAL]: WorkflowConditionalAttributes;\n [SpanType.WORKFLOW_CONDITIONAL_EVAL]: WorkflowConditionalEvalAttributes;\n [SpanType.WORKFLOW_PARALLEL]: WorkflowParallelAttributes;\n [SpanType.WORKFLOW_LOOP]: WorkflowLoopAttributes;\n [SpanType.WORKFLOW_SLEEP]: WorkflowSleepAttributes;\n [SpanType.WORKFLOW_WAIT_EVENT]: WorkflowWaitEventAttributes;\n [SpanType.GENERIC]: AIBaseAttributes;\n}\n\n/**\n * Union type for cases that need to handle any span type\n */\nexport type AnySpanAttributes = SpanTypeMap[keyof SpanTypeMap];\n\n// ============================================================================\n// Span Interfaces\n// ============================================================================\n\n/**\n * Base Span interface\n */\ninterface BaseSpan<TType extends SpanType> {\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 /** Span-type specific attributes */\n attributes?: SpanTypeMap[TType];\n /** User-defined metadata */\n metadata?: Record<string, any>;\n /** Labels used to categorize and filter traces. Only valid on root spans. */\n tags?: string[];\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 * Span interface, used internally for tracing\n */\nexport interface Span<TType extends SpanType> 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?: AnySpan;\n /** Pointer to the ObservabilityInstance instance */\n observabilityInstance: ObservabilityInstance;\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(options: ChildSpanOptions<SpanType.MODEL_GENERATION>): AIModelGenerationSpan;\n createChildSpan<TChildType extends SpanType>(options: ChildSpanOptions<TChildType>): Span<TChildType>;\n\n /** Create event span - can be any span type independent of parent */\n createEventSpan<TChildType extends SpanType>(options: ChildEventOptions<TChildType>): Span<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 SpanType>(spanType: T): Span<T> | undefined;\n\n /** Returns a lightweight span ready for export */\n exportSpan(includeInternalSpans?: boolean): ExportedSpan<TType> | undefined;\n\n /** Returns the traceId on span, unless NoOpSpan, then undefined */\n get externalTraceId(): string | undefined;\n\n /**\n * Execute an async function within this span's tracing context.\n *\n * When a bridge is configured, this enables auto-instrumented operations\n * (HTTP requests, database queries, etc.) to be properly nested under this\n * span in the external tracing system.\n *\n * @param fn - The async function to execute within the span context\n * @returns The result of the function execution\n *\n * @example\n * ```typescript\n * const result = await modelSpan.executeInContext(async () => {\n * return model.generateText(...);\n * });\n * ```\n */\n executeInContext<T>(fn: () => Promise<T>): Promise<T>;\n\n /**\n * Execute a synchronous function within this span's tracing context.\n *\n * When a bridge is configured, this enables auto-instrumented operations\n * (HTTP requests, database queries, etc.) to be properly nested under this\n * span in the external tracing system.\n *\n * @param fn - The synchronous function to execute within the span context\n * @returns The result of the function execution\n *\n * @example\n * ```typescript\n * const result = modelSpan.executeInContextSync(() => {\n * return model.streamText(...);\n * });\n * ```\n */\n executeInContextSync<T>(fn: () => T): T;\n}\n\nexport interface BridgeSpanContext {\n /**\n * Execute an async function within this span's tracing context.\n *\n * When a bridge is configured, this enables auto-instrumented operations\n * (HTTP requests, database queries, etc.) to be properly nested under this\n * span in the external tracing system.\n *\n * @param fn - The async function to execute within the span context\n * @returns The result of the function execution\n *\n * @example\n * ```typescript\n * const result = await modelSpan.executeInContext(async () => {\n * return model.generateText(...);\n * });\n * ```\n */\n executeInContext<T>(fn: () => Promise<T>): Promise<T>;\n\n /**\n * Execute a synchronous function within this span's tracing context.\n *\n * When a bridge is configured, this enables auto-instrumented operations\n * (HTTP requests, database queries, etc.) to be properly nested under this\n * span in the external tracing system.\n *\n * @param fn - The synchronous function to execute within the span context\n * @returns The result of the function execution\n *\n * @example\n * ```typescript\n * const result = modelSpan.executeInContextSync(() => {\n * return model.streamText(...);\n * });\n * ```\n */\n executeInContextSync<T>(fn: () => T): T;\n}\n\n/**\n * Specialized span interface for MODEL_GENERATION spans\n * Provides access to creating a ModelSpanTracker for tracking MODEL_STEP and MODEL_CHUNK spans\n */\nexport interface AIModelGenerationSpan extends Span<SpanType.MODEL_GENERATION> {\n /** Create a ModelSpanTracker for tracking model execution steps and chunks */\n createTracker(): IModelSpanTracker | undefined;\n}\n\n/**\n * Exported Span interface, used for tracing exporters\n */\nexport interface ExportedSpan<TType extends SpanType> 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 * Tags for this trace (only present on root spans).\n * Tags are string labels used to categorize and filter traces.\n */\n tags?: string[];\n}\n\nexport interface IModelSpanTracker {\n getTracingContext(): TracingContext;\n reportGenerationError(options: ErrorSpanOptions<SpanType.MODEL_GENERATION>): void;\n endGeneration(options?: EndSpanOptions<SpanType.MODEL_GENERATION>): void;\n wrapStream<T extends { pipeThrough: Function }>(stream: T): T;\n}\n\n/**\n * Union type for cases that need to handle any span\n */\nexport type AnySpan = Span<keyof SpanTypeMap>;\n\n/**\n * Union type for cases that need to handle any exported span\n */\nexport type AnyExportedSpan = ExportedSpan<keyof SpanTypeMap>;\n\n// ============================================================================\n// Tracing Interfaces\n// ============================================================================\n\n/**\n * Primary interface for Observability\n */\nexport interface ObservabilityInstance {\n /**\n * Get current configuration\n */\n getConfig(): Readonly<ObservabilityInstanceConfig>;\n\n /**\n * Get all exporters\n */\n getExporters(): readonly ObservabilityExporter[];\n\n /**\n * Get all span output processors\n */\n getSpanOutputProcessors(): readonly SpanOutputProcessor[];\n\n /**\n * Get the logger instance (for exporters and other components)\n */\n getLogger(): IMastraLogger;\n\n /**\n * Get the bridge instance if configured\n */\n getBridge(): ObservabilityBridge | undefined;\n\n /**\n * Start a new span of a specific SpanType\n */\n startSpan<TType extends SpanType>(options: StartSpanOptions<TType>): Span<TType>;\n\n /**\n * Shutdown tracing and clean up resources\n */\n shutdown(): Promise<void>;\n\n /**\n * Override setLogger to add 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 SpanType> {\n /** Span attributes */\n attributes?: SpanTypeMap[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 /** Request Context for metadata extraction */\n requestContext?: RequestContext;\n}\n\n/**\n * Options for creating new spans\n */\nexport interface CreateSpanOptions<TType extends SpanType> extends CreateBaseOptions<TType> {\n /** Input data */\n input?: any;\n /** Output data (for event spans) */\n output?: any;\n /** Labels used to categorize and filter traces. Only valid on root spans. */\n tags?: string[];\n /** Parent span */\n parent?: AnySpan;\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 SpanType> 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 SpanType> 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 SpanType> extends CreateBaseOptions<TType> {\n /** Output data */\n output?: any;\n}\n\ninterface UpdateBaseOptions<TType extends SpanType> {\n /** Span attributes */\n attributes?: Partial<SpanTypeMap[TType]>;\n /** Span metadata */\n metadata?: Record<string, any>;\n}\n\nexport interface EndSpanOptions<TType extends SpanType> extends UpdateBaseOptions<TType> {\n /** Output data */\n output?: any;\n}\n\nexport interface UpdateSpanOptions<TType extends SpanType> extends UpdateBaseOptions<TType> {\n /** Input data */\n input?: any;\n /** Output data */\n output?: any;\n}\n\nexport interface ErrorSpanOptions<TType extends SpanType> 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\nexport interface GetOrCreateSpanOptions<TType extends SpanType> {\n type: TType;\n name: string;\n input?: any;\n attributes?: SpanTypeMap[TType];\n metadata?: Record<string, any>;\n tracingPolicy?: TracingPolicy;\n tracingOptions?: TracingOptions;\n tracingContext?: TracingContext;\n requestContext?: RequestContext;\n mastra?: Mastra;\n}\n\n// ============================================================================\n// Lifecycle Types\n// ============================================================================\n\nexport interface ObservabilityEntrypoint {\n shutdown(): Promise<void>;\n\n setMastraContext(options: { mastra: Mastra }): void;\n\n setLogger(options: { logger: IMastraLogger }): void;\n\n getSelectedInstance(options: ConfigSelectorOptions): ObservabilityInstance | undefined;\n\n // Registry management methods\n registerInstance(name: string, instance: ObservabilityInstance, isDefault?: boolean): void;\n getInstance(name: string): ObservabilityInstance | undefined;\n getDefaultInstance(): ObservabilityInstance | undefined;\n listInstances(): ReadonlyMap<string, ObservabilityInstance>;\n unregisterInstance(name: string): boolean;\n hasInstance(name: string): boolean;\n setConfigSelector(selector: ConfigSelector): void;\n clear(): void;\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 * RequestContext keys to extract as metadata for all spans in this trace.\n * Computed by merging the tracing config's requestContextKeys\n * with the per-request requestContextKeys.\n */\n requestContextKeys: 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 RequestContext keys to extract as metadata for this trace.\n * These keys are added to the requestContextKeys config.\n * Supports dot notation for nested values (e.g., 'user.id', 'session.data.experimentId').\n */\n requestContextKeys?: 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 * Tags to apply to this trace.\n * Tags are string labels that can be used to categorize and filter traces\n * Note: Tags are only applied to the root span of a trace.\n */\n tags?: string[];\n}\n\nexport interface SpanIds {\n traceId: string;\n spanId: string;\n parentSpanId?: string;\n}\n\n/**\n * Context for tracing that flows through workflow and agent execution\n */\nexport interface TracingContext {\n /** Current Span for creating child spans and adding metadata */\n currentSpan?: AnySpan;\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 observability instance\n */\nexport interface ObservabilityInstanceConfig {\n /** Unique identifier for this config in the observability registry */\n name: string;\n /** Service name for observability */\n serviceName: string;\n /** Sampling strategy - controls whether tracing is collected (defaults to ALWAYS) */\n sampling?: SamplingStrategy;\n /** Custom exporters */\n exporters?: ObservabilityExporter[];\n /** Custom processors */\n spanOutputProcessors?: SpanOutputProcessor[];\n /** OpenTelemetry bridge for integration with existing OTEL infrastructure */\n bridge?: ObservabilityBridge;\n /** Set to `true` if you want to see spans internal to the operation of mastra */\n includeInternalSpans?: boolean;\n /**\n * RequestContext keys to automatically extract as metadata for all spans\n * created with this observablity configuration.\n * Supports dot notation for nested values.\n */\n requestContextKeys?: string[];\n}\n\n/**\n * Complete Observability 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<ObservabilityInstanceConfig, 'name'> | ObservabilityInstance>;\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 requestContext?: RequestContext;\n metadata?: Record<string, any>;\n}\n\n// ============================================================================\n// Exporter and Processor Interfaces\n// ============================================================================\n\n/**\n * Tracing event types\n */\nexport enum TracingEventType {\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 TracingEvent =\n | { type: TracingEventType.SPAN_STARTED; exportedSpan: AnyExportedSpan }\n | { type: TracingEventType.SPAN_UPDATED; exportedSpan: AnyExportedSpan }\n | { type: TracingEventType.SPAN_ENDED; exportedSpan: AnyExportedSpan };\n\nexport interface InitExporterOptions {\n mastra?: Mastra;\n config?: ObservabilityInstanceConfig;\n}\n\nexport interface InitBridgeOptions {\n mastra?: Mastra;\n config?: ObservabilityInstanceConfig;\n}\n\n/**\n * Interface for tracing exporters\n */\nexport interface ObservabilityExporter {\n /** Exporter name */\n name: string;\n\n /** Initialize exporter with tracing configuration and/or access to Mastra */\n init?(options: InitExporterOptions): void;\n\n /** Sets logger instance on the exporter. */\n __setLogger?(logger: IMastraLogger): void;\n\n /** Export tracing events */\n exportTracingEvent(event: TracingEvent): 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 observability bridges\n */\nexport interface ObservabilityBridge {\n /** Bridge name */\n name: string;\n\n /** Initialize bridge with observability configuration and/or access to Mastra */\n init?(options: InitBridgeOptions): void;\n\n /** Sets logger instance on the bridge */\n __setLogger?(logger: IMastraLogger): void;\n\n /**\n * Export Mastra tracing events to OTEL infrastructure\n * Called for SPAN_STARTED, SPAN_UPDATED, SPAN_ENDED events\n *\n * @param event - Tracing event with exported span\n */\n exportTracingEvent(event: TracingEvent): Promise<void>;\n\n /**\n * Execute an async function within the tracing context of a Mastra span.\n * This enables auto-instrumented operations (HTTP, DB) to have correct parent spans\n * in the external tracing system (e.g., OpenTelemetry, DataDog, etc.).\n *\n * @param spanId - The ID of the Mastra span to use as context\n * @param fn - The async function to execute within the span context\n * @returns The result of the function execution\n */\n executeInContext?<T>(spanId: string, fn: () => Promise<T>): Promise<T>;\n\n /**\n * Execute a synchronous function within the tracing context of a Mastra span.\n * This enables auto-instrumented operations (HTTP, DB) to have correct parent spans\n * in the external tracing system (e.g., OpenTelemetry, DataDog, etc.).\n *\n * @param spanId - The ID of the Mastra span to use as context\n * @param fn - The synchronous function to execute within the span context\n * @returns The result of the function execution\n */\n executeInContextSync?<T>(spanId: string, fn: () => T): T;\n\n /**\n * Create a span in the bridge's tracing system.\n * Called during Mastra span construction to get bridge-generated identifiers.\n *\n * @param options - Span creation options from Mastra\n * @returns Span identifiers (spanId, traceId, parentSpanId) from bridge, or undefined if creation fails\n */\n createSpan(options: CreateSpanOptions<SpanType>): SpanIds | undefined;\n\n /** Shutdown bridge and cleanup resources */\n shutdown(): Promise<void>;\n}\n\n/**\n * Interface for span processors\n */\nexport interface SpanOutputProcessor {\n /** Processor name */\n name: string;\n /** Process span before export */\n process(span?: AnySpan): AnySpan | 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 /** Request Context */\n requestContext?: RequestContext;\n}\n\n/**\n * Function to select which 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, ObservabilityInstance>,\n) => string | undefined;\n\n// ============================================================================\n// Tracing Storage Interfaces\n// ============================================================================\n\nexport type TracingStorageStrategy = 'realtime' | 'batch-with-updates' | 'insert-only';\n","import type { Mastra } from '..';\nimport type { IMastraLogger } from '../logger';\nimport type { ObservabilityInstance, ConfigSelectorOptions, ObservabilityEntrypoint, ConfigSelector } from './types';\n\nexport class NoOpObservability implements ObservabilityEntrypoint {\n setMastraContext(_options: { mastra: Mastra }): void {\n return;\n }\n\n setLogger(_options: { logger: IMastraLogger }): void {\n return;\n }\n\n getSelectedInstance(_options: ConfigSelectorOptions): ObservabilityInstance | undefined {\n return;\n }\n\n registerInstance(_name: string, _instance: ObservabilityInstance, _isDefault = false): void {\n return;\n }\n\n getInstance(_name: string): ObservabilityInstance | undefined {\n return;\n }\n\n getDefaultInstance(): ObservabilityInstance | undefined {\n return;\n }\n\n listInstances(): ReadonlyMap<string, ObservabilityInstance> {\n return new Map();\n }\n\n unregisterInstance(_name: string): boolean {\n return false;\n }\n\n hasInstance(_name: string): boolean {\n return false;\n }\n\n setConfigSelector(_selector: ConfigSelector): void {\n return;\n }\n\n clear(): void {\n return;\n }\n\n async shutdown(): Promise<void> {\n return;\n }\n}\n","import type { Span, SpanType, GetOrCreateSpanOptions, AnySpan } from './types';\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 Span or undefined if tracing is disabled\n */\nexport function getOrCreateSpan<T extends SpanType>(options: GetOrCreateSpanOptions<T>): Span<T> | undefined {\n const { type, attributes, tracingContext, requestContext, 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 instance = options.mastra?.observability?.getSelectedInstance({ requestContext });\n\n return instance?.startSpan<T>({\n type,\n attributes,\n ...rest,\n metadata,\n requestContext,\n tracingOptions,\n traceId: tracingOptions?.traceId,\n parentSpanId: tracingOptions?.parentSpanId,\n customSamplerOptions: {\n requestContext,\n metadata,\n },\n });\n}\n\n/**\n * Execute an async function within the span's tracing context if available.\n * Falls back to direct execution if no span exists.\n *\n * When a bridge is configured, this enables auto-instrumented operations\n * (HTTP requests, database queries, etc.) to be properly nested under the\n * current span in the external tracing system.\n *\n * @param span - The span to use as context (or undefined to execute without context)\n * @param fn - The async function to execute\n * @returns The result of the function execution\n *\n * @example\n * ```typescript\n * const result = await executeWithContext(llmSpan, async () =>\n * model.generateText(args)\n * );\n * ```\n */\nexport async function executeWithContext<T>(params: { span?: AnySpan; fn: () => Promise<T> }): Promise<T> {\n const { span, fn } = params;\n\n if (span?.executeInContext) {\n return span.executeInContext(fn);\n }\n\n return fn();\n}\n\n/**\n * Execute a synchronous function within the span's tracing context if available.\n * Falls back to direct execution if no span exists.\n *\n * When a bridge is configured, this enables auto-instrumented operations\n * (HTTP requests, database queries, etc.) to be properly nested under the\n * current span in the external tracing system.\n *\n * @param span - The span to use as context (or undefined to execute without context)\n * @param fn - The synchronous function to execute\n * @returns The result of the function execution\n *\n * @example\n * ```typescript\n * const result = executeWithContextSync(llmSpan, () =>\n * model.streamText(args)\n * );\n * ```\n */\nexport function executeWithContextSync<T>(params: { span?: AnySpan; fn: () => T }): T {\n const { span, fn } = params;\n\n if (span?.executeInContextSync) {\n return span.executeInContextSync(fn);\n }\n\n return fn();\n}\n","/**\n * Tracing Context Integration\n *\n * This module provides automatic 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, AnySpan } 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', 'createRun'];\n\n/**\n * Helper function to detect NoOp spans to avoid unnecessary wrapping\n */\nfunction isNoOpSpan(span: AnySpan): boolean {\n // Check if this is a NoOp span implementation\n return span.constructor.name === 'NoOpSpan' || (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 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 * 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('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('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 * 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('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('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 * 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 createRun methods differently\n if (prop === 'createRun' || prop === 'createRun') {\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('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('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 * 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('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('Tracing: Failed to create run proxy, using original instance', error);\n return run;\n }\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/events/event-emitter.ts","../src/mastra/hooks.ts","../src/mastra/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;AAIO,IAAM,kBAAA,GAAN,cAAiC,MAAA,CAAO;AAAA,EACrC,OAAA;AAAA,EAER,WAAA,GAAc;AACZ,IAAA,KAAA,EAAM;AACN,IAAA,IAAA,CAAK,OAAA,GAAU,IAAI,YAAA,EAAa;AAAA,EAClC;AAAA,EAEA,MAAM,OAAA,CAAQ,KAAA,EAAe,KAAA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AAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EA2BA,MAAM,QAAA,GAA0B;AAC9B,IAAA,MAAM,KAAK,eAAA,EAAgB;AAE3B,IAAA,MAAM,IAAA,CAAK,eAAe,QAAA,EAAS;AAEnC,IAAA,IAAA,CAAK,OAAA,EAAS,KAAK,2BAA2B,CAAA;AAAA,EAChD;AAAA;AAAA,EAGA,IAAW,WAAA,GAAc;AACvB,IAAA,OAAO,IAAA,CAAK,YAAA;AAAA,EACd;AACF","file":"chunk-EPMSC67U.js","sourcesContent":["import EventEmitter from 'node:events';\nimport { PubSub } from './pubsub';\nimport type { Event } from './types';\n\nexport class EventEmitterPubSub extends PubSub {\n private emitter: EventEmitter;\n\n constructor() {\n super();\n this.emitter = new EventEmitter();\n }\n\n async publish(topic: string, event: Omit<Event, 'id' | 'createdAt'>): Promise<void> {\n const id = crypto.randomUUID();\n const createdAt = new Date();\n this.emitter.emit(topic, {\n ...event,\n id,\n createdAt,\n });\n }\n\n async subscribe(topic: string, cb: (event: Event, ack?: () => Promise<void>) => void): Promise<void> {\n this.emitter.on(topic, cb);\n }\n\n async unsubscribe(topic: string, cb: (event: Event, ack?: () => Promise<void>) => void): Promise<void> {\n this.emitter.off(topic, cb);\n }\n\n async flush(): Promise<void> {\n // no-op\n }\n}\n","import pMap from 'p-map';\nimport { ErrorCategory, ErrorDomain, MastraError } from '../error';\nimport { saveScorePayloadSchema } from '../evals';\nimport type { ScoringHookInput } from '../evals/types';\nimport type { Mastra } from '../mastra';\nimport type { MastraStorage } from '../storage';\n\nexport function createOnScorerHook(mastra: Mastra) {\n return async (hookData: ScoringHookInput) => {\n const storage = mastra.getStorage();\n\n if (!storage) {\n mastra.getLogger()?.warn('Storage not found, skipping score validation and saving');\n return;\n }\n\n const entityId = hookData.entity.id;\n const entityType = hookData.entityType;\n const scorer = hookData.scorer;\n const scorerId = scorer.id;\n\n if (!scorerId) {\n mastra.getLogger()?.warn('Scorer ID not found, skipping score validation and saving');\n return;\n }\n\n try {\n const scorerToUse = await findScorer(mastra, entityId, entityType, scorerId);\n\n if (!scorerToUse) {\n throw new MastraError({\n id: 'MASTRA_SCORER_NOT_FOUND',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: `Scorer with ID ${scorerId} not found`,\n });\n }\n\n let input = hookData.input;\n let output = hookData.output;\n\n const { structuredOutput, ...rest } = hookData;\n\n const runResult = await scorerToUse.scorer.run({\n ...rest,\n input,\n output,\n });\n\n let spanId;\n let traceId;\n const currentSpan = hookData.tracingContext?.currentSpan;\n if (currentSpan && currentSpan.isValid) {\n spanId = currentSpan.id;\n traceId = currentSpan.traceId;\n }\n\n const payload = {\n ...rest,\n ...runResult,\n entityId,\n scorerId: scorerId,\n spanId,\n traceId,\n metadata: {\n structuredOutput: !!structuredOutput,\n },\n };\n await validateAndSaveScore(storage, payload);\n\n if (currentSpan && spanId && traceId) {\n await pMap(\n currentSpan.observabilityInstance.getExporters(),\n async exporter => {\n if (exporter.addScoreToTrace) {\n try {\n await exporter.addScoreToTrace({\n traceId: traceId,\n spanId: spanId,\n score: runResult.score as number,\n reason: runResult.reason as string,\n scorerName: scorerToUse.scorer.id,\n metadata: {\n ...(currentSpan.metadata ?? {}),\n },\n });\n } catch (error) {\n // Log error but don't fail the hook if exporter fails\n mastra.getLogger()?.error(`Failed to add score to trace via exporter: ${error}`);\n }\n }\n },\n { concurrency: 3 },\n );\n }\n } catch (error) {\n const mastraError = new MastraError(\n {\n id: 'MASTRA_SCORER_FAILED_TO_RUN_HOOK',\n domain: ErrorDomain.SCORER,\n category: ErrorCategory.USER,\n details: {\n scorerId: scorer.id,\n entityId,\n entityType,\n },\n },\n error,\n );\n\n mastra.getLogger()?.trackException(mastraError);\n mastra.getLogger()?.error(mastraError.toString());\n }\n };\n}\n\nexport async function validateAndSaveScore(storage: MastraStorage, payload: unknown) {\n const payloadToSave = saveScorePayloadSchema.parse(payload);\n await storage?.saveScore(payloadToSave);\n}\n\nasync function findScorer(mastra: Mastra, entityId: string, entityType: string, scorerId: string) {\n let scorerToUse;\n if (entityType === 'AGENT') {\n const scorers = await mastra.getAgentById(entityId).listScorers();\n for (const [_, scorer] of Object.entries(scorers)) {\n if (scorer.scorer.id === scorerId) {\n scorerToUse = scorer;\n break;\n }\n }\n } else if (entityType === 'WORKFLOW') {\n const scorers = await mastra.getWorkflowById(entityId).listScorers();\n for (const [_, scorer] of Object.entries(scorers)) {\n if (scorer.scorer.id === scorerId) {\n scorerToUse = scorer;\n break;\n }\n }\n }\n\n // Fallback to mastra-registered scorer\n if (!scorerToUse) {\n const mastraRegisteredScorer = mastra.getScorerById(scorerId);\n scorerToUse = mastraRegisteredScorer ? { scorer: mastraRegisteredScorer } : undefined;\n }\n\n return scorerToUse;\n}\n","import { randomUUID } from 'node:crypto';\nimport type { Agent } from '../agent';\nimport type { BundlerConfig } from '../bundler/types';\nimport { InMemoryServerCache } from '../cache';\nimport type { MastraServerCache } from '../cache';\nimport type { MastraDeployer } from '../deployer';\nimport { MastraError, ErrorDomain, ErrorCategory } from '../error';\nimport type { MastraScorer } from '../evals';\nimport { EventEmitterPubSub } from '../events/event-emitter';\nimport type { PubSub } from '../events/pubsub';\nimport type { Event } from '../events/types';\nimport { AvailableHooks, registerHook } from '../hooks';\nimport type { MastraModelGateway } from '../llm/model/gateways';\nimport { LogLevel, noopLogger, ConsoleLogger } from '../logger';\nimport type { IMastraLogger } from '../logger';\nimport type { MCPServerBase } from '../mcp';\nimport type { ObservabilityEntrypoint } from '../observability';\nimport { NoOpObservability } from '../observability';\nimport type { Processor } from '../processors';\nimport type { MastraServerBase } from '../server/base';\nimport type { Middleware, ServerConfig } from '../server/types';\nimport type { MastraStorage, WorkflowRuns } from '../storage';\nimport { augmentWithInit } from '../storage/storageWithInit';\nimport type { ToolAction } from '../tools';\nimport type { MastraTTS } from '../tts';\nimport type { MastraIdGenerator } from '../types';\nimport type { MastraVector } from '../vector';\nimport type { Workflow } from '../workflows';\nimport { WorkflowEventProcessor } from '../workflows/evented/workflow-event-processor';\nimport { createOnScorerHook } from './hooks';\n\n/**\n * Creates an error for when a null/undefined value is passed to an add* method.\n * This commonly occurs when config is spread ({ ...config }) and the original\n * object had getters or non-enumerable properties.\n */\nfunction createUndefinedPrimitiveError(\n type: 'agent' | 'tool' | 'processor' | 'vector' | 'scorer' | 'workflow' | 'mcp-server' | 'gateway',\n value: null | undefined,\n key?: string,\n): MastraError {\n const typeLabel = type === 'mcp-server' ? 'MCP server' : type;\n const errorId = `MASTRA_ADD_${type.toUpperCase().replace('-', '_')}_UNDEFINED` as Uppercase<string>;\n return new MastraError({\n id: errorId,\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: `Cannot add ${typeLabel}: ${typeLabel} is ${value === null ? 'null' : 'undefined'}. This may occur if config was spread ({ ...config }) and the original object had getters or non-enumerable properties.`,\n details: { status: 400, ...(key && { key }) },\n });\n}\n\n/**\n * Configuration interface for initializing a Mastra instance.\n *\n * The Config interface defines all the optional components that can be registered\n * with a Mastra instance, including agents, workflows, storage, logging, and more.\n *\n * @template TAgents - Record of agent instances keyed by their names\n * @template TWorkflows - Record of workflow instances\n * @template TVectors - Record of vector store instances\n * @template TTTS - Record of text-to-speech instances\n * @template TLogger - Logger implementation type\n * @template TVNextNetworks - Record of agent network instances\n * @template TMCPServers - Record of MCP server instances\n * @template TScorers - Record of scorer instances\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * agents: {\n * weatherAgent: new Agent({\n * id: 'weather-agent',\n * name: 'Weather Agent',\n * instructions: 'You help with weather information',\n * model: 'openai/gpt-5'\n * })\n * },\n * storage: new LibSQLStore({ id: 'mastra-storage', url: ':memory:' }),\n * logger: new PinoLogger({ name: 'MyApp' })\n * });\n * ```\n */\nexport interface Config<\n TAgents extends Record<string, Agent<any>> = Record<string, Agent<any>>,\n TWorkflows extends Record<string, Workflow<any, any, any, any, any, any>> = Record<\n string,\n Workflow<any, any, any, any, any, any>\n >,\n TVectors extends Record<string, MastraVector<any>> = Record<string, MastraVector<any>>,\n TTTS extends Record<string, MastraTTS> = Record<string, MastraTTS>,\n TLogger extends IMastraLogger = IMastraLogger,\n TMCPServers extends Record<string, MCPServerBase<any>> = Record<string, MCPServerBase<any>>,\n TScorers extends Record<string, MastraScorer<any, any, any, any>> = Record<string, MastraScorer<any, any, any, any>>,\n TTools extends Record<string, ToolAction<any, any, any, any, any, any>> = Record<\n string,\n ToolAction<any, any, any, any, any, any>\n >,\n TProcessors extends Record<string, Processor<any>> = Record<string, Processor<any>>,\n> {\n /**\n * Agents are autonomous systems that can make decisions and take actions.\n */\n agents?: TAgents;\n\n /**\n * Storage provider for persisting data, conversation history, and workflow state.\n * Required for agent memory and workflow persistence.\n */\n storage?: MastraStorage;\n\n /**\n * Vector stores for semantic search and retrieval-augmented generation (RAG).\n * Used for storing and querying embeddings.\n */\n vectors?: TVectors;\n\n /**\n * Logger implementation for application logging and debugging.\n * Set to `false` to disable logging entirely.\n * @default `INFO` level in development, `WARN` in production.\n */\n logger?: TLogger | false;\n\n /**\n * Workflows provide type-safe, composable task execution with built-in error handling.\n */\n workflows?: TWorkflows;\n\n /**\n * Text-to-speech providers for voice synthesis capabilities.\n */\n tts?: TTTS;\n\n /**\n * Observability entrypoint for tracking model interactions and tracing.\n * Pass an instance of the Observability class from @mastra/observability.\n *\n * @example\n * ```typescript\n * import { Observability } from '@mastra/observability';\n *\n * new Mastra({\n * observability: new Observability({\n * default: { enabled: true }\n * })\n * })\n * ```\n */\n observability?: ObservabilityEntrypoint;\n\n /**\n * Custom ID generator function for creating unique identifiers.\n * @default `crypto.randomUUID()`\n */\n idGenerator?: MastraIdGenerator;\n\n /**\n * Deployment provider for publishing applications to cloud platforms.\n */\n deployer?: MastraDeployer;\n\n /**\n * Server configuration for HTTP endpoints and middleware.\n */\n server?: ServerConfig;\n\n /**\n * MCP servers provide tools and resources that agents can use.\n */\n mcpServers?: TMCPServers;\n\n /**\n * Bundler configuration for packaging and deployment.\n */\n bundler?: BundlerConfig;\n\n /**\n * Pub/sub system for event-driven communication between components.\n * @default EventEmitterPubSub\n */\n pubsub?: PubSub;\n\n /**\n * Scorers help assess the quality of agent responses and workflow outputs.\n */\n scorers?: TScorers;\n\n /**\n * Tools are reusable functions that agents can use to interact with external systems.\n */\n tools?: TTools;\n\n /**\n * Processors transform inputs and outputs for agents and workflows.\n */\n processors?: TProcessors;\n\n /**\n * Custom model router gateways for accessing LLM providers.\n * Gateways handle provider-specific authentication, URL construction, and model resolution.\n */\n gateways?: Record<string, MastraModelGateway>;\n\n /**\n * Event handlers for custom application events.\n * Maps event topics to handler functions for event-driven architectures.\n */\n events?: {\n [topic: string]: (\n event: Event,\n cb?: () => Promise<void>,\n ) => Promise<void> | ((event: Event, cb?: () => Promise<void>) => Promise<void>)[];\n };\n}\n\n/**\n * The central orchestrator for Mastra applications, managing agents, workflows, storage, logging, observability, and more.\n *\n * The `Mastra` class serves as the main entry point and registry for all components in a Mastra application.\n * It coordinates the interaction between agents, workflows, storage systems, and other services.\n\n * @template TAgents - Record of agent instances keyed by their names\n * @template TWorkflows - Record of modern workflow instances\n * @template TVectors - Record of vector store instances for semantic search and RAG\n * @template TTTS - Record of text-to-speech provider instances\n * @template TLogger - Logger implementation type for application logging\n * @template TVNextNetworks - Record of next-generation agent network instances\n * @template TMCPServers - Record of Model Context Protocol server instances\n * @template TScorers - Record of evaluation scorer instances for measuring AI performance\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * agents: {\n * weatherAgent: new Agent({\n * id: 'weather-agent',\n * name: 'Weather Agent',\n * instructions: 'You provide weather information',\n * model: 'openai/gpt-5',\n * tools: [getWeatherTool]\n * })\n * },\n * workflows: { dataWorkflow },\n * storage: new LibSQLStore({ id: 'mastra-storage', url: ':memory:' }),\n * logger: new PinoLogger({ name: 'MyApp' })\n * });\n * ```\n */\nexport class Mastra<\n TAgents extends Record<string, Agent<any>> = Record<string, Agent<any>>,\n TWorkflows extends Record<string, Workflow<any, any, any, any, any, any>> = Record<\n string,\n Workflow<any, any, any, any, any, any>\n >,\n TVectors extends Record<string, MastraVector<any>> = Record<string, MastraVector<any>>,\n TTTS extends Record<string, MastraTTS> = Record<string, MastraTTS>,\n TLogger extends IMastraLogger = IMastraLogger,\n TMCPServers extends Record<string, MCPServerBase<any>> = Record<string, MCPServerBase<any>>,\n TScorers extends Record<string, MastraScorer<any, any, any, any>> = Record<string, MastraScorer<any, any, any, any>>,\n TTools extends Record<string, ToolAction<any, any, any, any, any, any>> = Record<\n string,\n ToolAction<any, any, any, any, any, any>\n >,\n TProcessors extends Record<string, Processor<any>> = Record<string, Processor<any>>,\n> {\n #vectors?: TVectors;\n #agents: TAgents;\n #logger: TLogger;\n #workflows: TWorkflows;\n #observability: ObservabilityEntrypoint;\n #tts?: TTTS;\n #deployer?: MastraDeployer;\n #serverMiddleware: Array<{\n handler: (c: any, next: () => Promise<void>) => Promise<Response | void>;\n path: string;\n }> = [];\n\n #storage?: MastraStorage;\n #scorers?: TScorers;\n #tools?: TTools;\n #processors?: TProcessors;\n #server?: ServerConfig;\n #serverAdapter?: MastraServerBase;\n #mcpServers?: TMCPServers;\n #bundler?: BundlerConfig;\n #idGenerator?: MastraIdGenerator;\n #pubsub: PubSub;\n #gateways?: Record<string, MastraModelGateway>;\n #events: {\n [topic: string]: ((event: Event, cb?: () => Promise<void>) => Promise<void>)[];\n } = {};\n #internalMastraWorkflows: Record<string, Workflow> = {};\n // This is only used internally for server handlers that require temporary persistence\n #serverCache: MastraServerCache;\n\n get pubsub() {\n return this.#pubsub;\n }\n\n /**\n * Gets the currently configured ID generator function.\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * idGenerator: () => `custom-${Date.now()}`\n * });\n * const generator = mastra.getIdGenerator();\n * console.log(generator?.()); // \"custom-1234567890\"\n * ```\n */\n public getIdGenerator() {\n return this.#idGenerator;\n }\n\n /**\n * Generates a unique identifier using the configured generator or defaults to `crypto.randomUUID()`.\n *\n * This method is used internally by Mastra for creating unique IDs for various entities\n * like workflow runs, agent conversations, and other resources that need unique identification.\n *\n * @throws {MastraError} When the custom ID generator returns an empty string\n *\n * @example\n * ```typescript\n * const mastra = new Mastra();\n * const id = mastra.generateId();\n * console.log(id); // \"550e8400-e29b-41d4-a716-446655440000\"\n * ```\n */\n public generateId(): string {\n if (this.#idGenerator) {\n const id = this.#idGenerator();\n if (!id) {\n const error = new MastraError({\n id: 'MASTRA_ID_GENERATOR_RETURNED_EMPTY_STRING',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: 'ID generator returned an empty string, which is not allowed',\n });\n this.#logger?.trackException(error);\n throw error;\n }\n return id;\n }\n return randomUUID();\n }\n\n /**\n * Sets a custom ID generator function for creating unique identifiers.\n *\n * The ID generator function will be used by `generateId()` instead of the default\n * `crypto.randomUUID()`. This is useful for creating application-specific ID formats\n * or integrating with existing ID generation systems.\n *\n * @example\n * ```typescript\n * const mastra = new Mastra();\n * mastra.setIdGenerator(() => `custom-${Date.now()}`);\n * const id = mastra.generateId();\n * console.log(id); // \"custom-1234567890\"\n * ```\n */\n public setIdGenerator(idGenerator: MastraIdGenerator) {\n this.#idGenerator = idGenerator;\n }\n\n /**\n * Creates a new Mastra instance with the provided configuration.\n *\n * The constructor initializes all the components specified in the config, sets up\n * internal systems like logging and observability, and registers components with each other.\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * agents: {\n * assistant: new Agent({\n * id: 'assistant',\n * name: 'Assistant',\n * instructions: 'You are a helpful assistant',\n * model: 'openai/gpt-5'\n * })\n * },\n * storage: new PostgresStore({\n * connectionString: process.env.DATABASE_URL\n * }),\n * logger: new PinoLogger({ name: 'MyApp' }),\n * observability: { default: { enabled: true }},\n * });\n * ```\n */\n constructor(\n config?: Config<TAgents, TWorkflows, TVectors, TTTS, TLogger, TMCPServers, TScorers, TTools, TProcessors>,\n ) {\n // This is only used internally for server handlers that require temporary persistence\n this.#serverCache = new InMemoryServerCache();\n\n if (config?.pubsub) {\n this.#pubsub = config.pubsub;\n } else {\n this.#pubsub = new EventEmitterPubSub();\n }\n\n this.#events = {};\n for (const topic in config?.events ?? {}) {\n if (!Array.isArray(config?.events?.[topic])) {\n this.#events[topic] = [config?.events?.[topic] as any];\n } else {\n this.#events[topic] = config?.events?.[topic] ?? [];\n }\n }\n\n const workflowEventProcessor = new WorkflowEventProcessor({ mastra: this });\n const workflowEventCb = async (event: Event, cb?: () => Promise<void>): Promise<void> => {\n try {\n await workflowEventProcessor.process(event, cb);\n } catch (e) {\n console.error('Error processing event', e);\n }\n };\n if (this.#events.workflows) {\n this.#events.workflows.push(workflowEventCb);\n } else {\n this.#events.workflows = [workflowEventCb];\n }\n\n let logger: TLogger;\n if (config?.logger === false) {\n logger = noopLogger as unknown as TLogger;\n } else {\n if (config?.logger) {\n logger = config.logger;\n } else {\n const levelOnEnv =\n process.env.NODE_ENV === 'production' && process.env.MASTRA_DEV !== 'true' ? LogLevel.WARN : LogLevel.INFO;\n logger = new ConsoleLogger({ name: 'Mastra', level: levelOnEnv }) as unknown as TLogger;\n }\n }\n this.#logger = logger;\n\n this.#idGenerator = config?.idGenerator;\n\n let storage = config?.storage;\n\n if (storage) {\n storage = augmentWithInit(storage);\n }\n\n // Validate and assign observability instance\n if (config?.observability) {\n if (typeof config.observability.getDefaultInstance === 'function') {\n this.#observability = config.observability;\n // Set logger early\n this.#observability.setLogger({ logger: this.#logger });\n } else {\n this.#logger?.warn(\n 'Observability configuration error: Expected an Observability instance, but received a config object. ' +\n 'Import and instantiate: import { Observability } from \"@mastra/observability\"; ' +\n 'then pass: observability: new Observability({ default: { enabled: true } }). ' +\n 'Observability has been disabled.',\n );\n this.#observability = new NoOpObservability();\n }\n } else {\n this.#observability = new NoOpObservability();\n }\n\n this.#storage = storage;\n\n // Initialize all primitive storage objects first, we need to do this before adding primitives to avoid circular dependencies\n this.#vectors = {} as TVectors;\n this.#mcpServers = {} as TMCPServers;\n this.#tts = {} as TTTS;\n this.#agents = {} as TAgents;\n this.#scorers = {} as TScorers;\n this.#tools = {} as TTools;\n this.#processors = {} as TProcessors;\n this.#workflows = {} as TWorkflows;\n this.#gateways = {} as Record<string, MastraModelGateway>;\n\n // Now add primitives - order matters for auto-registration\n // Tools and processors should be added before agents and MCP servers that might use them\n // Note: We validate each entry to handle cases where config was spread ({ ...config })\n // which can cause undefined values if the source object had getters or non-enumerable properties\n if (config?.tools) {\n Object.entries(config.tools).forEach(([key, tool]) => {\n if (tool != null) {\n this.addTool(tool, key);\n }\n });\n }\n\n if (config?.processors) {\n Object.entries(config.processors).forEach(([key, processor]) => {\n if (processor != null) {\n this.addProcessor(processor, key);\n }\n });\n }\n\n if (config?.vectors) {\n Object.entries(config.vectors).forEach(([key, vector]) => {\n if (vector != null) {\n this.addVector(vector, key);\n }\n });\n }\n\n if (config?.scorers) {\n Object.entries(config.scorers).forEach(([key, scorer]) => {\n if (scorer != null) {\n this.addScorer(scorer, key);\n }\n });\n }\n\n if (config?.workflows) {\n Object.entries(config.workflows).forEach(([key, workflow]) => {\n if (workflow != null) {\n this.addWorkflow(workflow, key);\n }\n });\n }\n\n if (config?.gateways) {\n Object.entries(config.gateways).forEach(([key, gateway]) => {\n if (gateway != null) {\n this.addGateway(gateway, key);\n }\n });\n }\n\n // Add MCP servers and agents last since they might reference other primitives\n if (config?.mcpServers) {\n Object.entries(config.mcpServers).forEach(([key, server]) => {\n if (server != null) {\n this.addMCPServer(server, key);\n }\n });\n }\n\n if (config?.agents) {\n Object.entries(config.agents).forEach(([key, agent]) => {\n if (agent != null) {\n this.addAgent(agent, key);\n }\n });\n }\n\n if (config?.tts) {\n Object.entries(config.tts).forEach(([key, tts]) => {\n if (tts != null) {\n (this.#tts as Record<string, MastraTTS>)[key] = tts;\n }\n });\n }\n\n if (config?.server) {\n this.#server = config.server;\n }\n\n registerHook(AvailableHooks.ON_SCORER_RUN, createOnScorerHook(this));\n\n /*\n Initialize observability with Mastra context (after storage configured)\n */\n this.#observability.setMastraContext({ mastra: this });\n\n this.setLogger({ logger });\n }\n\n /**\n * Retrieves a registered agent by its name.\n *\n * @template TAgentName - The specific agent name type from the registered agents\n * @throws {MastraError} When the agent with the specified name is not found\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * agents: {\n * weatherAgent: new Agent({\n * id: 'weather-agent',\n * name: 'weather-agent',\n * instructions: 'You provide weather information',\n * model: 'openai/gpt-5'\n * })\n * }\n * });\n * const agent = mastra.getAgent('weatherAgent');\n * const response = await agent.generate('What is the weather?');\n * ```\n */\n public getAgent<TAgentName extends keyof TAgents>(name: TAgentName): TAgents[TAgentName] {\n const agent = this.#agents?.[name];\n if (!agent) {\n const error = new MastraError({\n id: 'MASTRA_GET_AGENT_BY_NAME_NOT_FOUND',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: `Agent with name ${String(name)} not found`,\n details: {\n status: 404,\n agentName: String(name),\n agents: Object.keys(this.#agents ?? {}).join(', '),\n },\n });\n this.#logger?.trackException(error);\n throw error;\n }\n return this.#agents[name];\n }\n\n /**\n * Retrieves a registered agent by its unique ID.\n *\n * This method searches for an agent using its internal ID property. If no agent\n * is found with the given ID, it also attempts to find an agent using the ID as\n * a name.\n *\n * @throws {MastraError} When no agent is found with the specified ID\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * agents: {\n * assistant: new Agent({\n * id: 'assistant',\n * name: 'assistant',\n * instructions: 'You are a helpful assistant',\n * model: 'openai/gpt-5'\n * })\n * }\n * });\n *\n * const assistant = mastra.getAgent('assistant');\n * const sameAgent = mastra.getAgentById(assistant.id);\n * ```\n */\n public getAgentById<TAgentName extends keyof TAgents>(id: TAgents[TAgentName]['id']): TAgents[TAgentName] {\n let agent = Object.values(this.#agents).find(a => a.id === id);\n\n if (!agent) {\n try {\n agent = this.getAgent(id);\n } catch {\n // do nothing\n }\n }\n\n if (!agent) {\n const error = new MastraError({\n id: 'MASTRA_GET_AGENT_BY_AGENT_ID_NOT_FOUND',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: `Agent with id ${String(id)} not found`,\n details: {\n status: 404,\n agentId: String(id),\n agents: Object.keys(this.#agents ?? {}).join(', '),\n },\n });\n this.#logger?.trackException(error);\n throw error;\n }\n\n return agent as TAgents[TAgentName];\n }\n\n /**\n * Returns all registered agents as a record keyed by their names.\n *\n * This method provides access to the complete registry of agents, allowing you to\n * iterate over them, check what agents are available, or perform bulk operations.\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * agents: {\n * weatherAgent: new Agent({ id: 'weather-agent', name: 'weather', model: 'openai/gpt-4o' }),\n * supportAgent: new Agent({ id: 'support-agent', name: 'support', model: 'openai/gpt-4o' })\n * }\n * });\n *\n * const allAgents = mastra.listAgents();\n * console.log(Object.keys(allAgents)); // ['weatherAgent', 'supportAgent']\n * ```\n */\n public listAgents() {\n return this.#agents;\n }\n\n /**\n * Adds a new agent to the Mastra instance.\n *\n * This method allows dynamic registration of agents after the Mastra instance\n * has been created. The agent will be initialized with the current logger.\n *\n * @throws {MastraError} When an agent with the same key already exists\n *\n * @example\n * ```typescript\n * const mastra = new Mastra();\n * const newAgent = new Agent({\n * id: 'chat-agent',\n * name: 'Chat Assistant',\n * model: 'openai/gpt-4o'\n * });\n * mastra.addAgent(newAgent); // Uses agent.id as key\n * // or\n * mastra.addAgent(newAgent, 'customKey'); // Uses custom key\n * ```\n */\n public addAgent<A extends Agent<any>>(agent: A, key?: string): void {\n if (!agent) {\n throw createUndefinedPrimitiveError('agent', agent, key);\n }\n const agentKey = key || agent.id;\n const agents = this.#agents as Record<string, Agent<any>>;\n if (agents[agentKey]) {\n const logger = this.getLogger();\n logger.debug(`Agent with key ${agentKey} already exists. Skipping addition.`);\n return;\n }\n\n // Initialize the agent\n agent.__setLogger(this.#logger);\n agent.__registerMastra(this);\n agent.__registerPrimitives({\n logger: this.getLogger(),\n storage: this.getStorage(),\n agents: agents,\n tts: this.#tts,\n vectors: this.#vectors,\n });\n agents[agentKey] = agent;\n }\n\n /**\n * Retrieves a registered vector store by its name.\n *\n * @template TVectorName - The specific vector store name type from the registered vectors\n * @throws {MastraError} When the vector store with the specified name is not found\n *\n * @example Using a vector store for semantic search\n * ```typescript\n * import { PineconeVector } from '@mastra/pinecone';\n * import { OpenAIEmbedder } from '@mastra/embedders';\n *\n * const mastra = new Mastra({\n * vectors: {\n * knowledge: new PineconeVector({\n * apiKey: process.env.PINECONE_API_KEY,\n * indexName: 'knowledge-base',\n * embedder: new OpenAIEmbedder({\n * apiKey: process.env.OPENAI_API_KEY,\n * model: 'text-embedding-3-small'\n * })\n * }),\n * products: new PineconeVector({\n * apiKey: process.env.PINECONE_API_KEY,\n * indexName: 'product-catalog'\n * })\n * }\n * });\n *\n * // Get a vector store and perform semantic search\n * const knowledgeBase = mastra.getVector('knowledge');\n * const results = await knowledgeBase.query({\n * query: 'How to reset password?',\n * topK: 5\n * });\n *\n * console.log('Relevant documents:', results);\n * ```\n */\n public getVector<TVectorName extends keyof TVectors>(name: TVectorName): TVectors[TVectorName] {\n const vector = this.#vectors?.[name];\n if (!vector) {\n const error = new MastraError({\n id: 'MASTRA_GET_VECTOR_BY_NAME_NOT_FOUND',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: `Vector with name ${String(name)} not found`,\n details: {\n status: 404,\n vectorName: String(name),\n vectors: Object.keys(this.#vectors ?? {}).join(', '),\n },\n });\n this.#logger?.trackException(error);\n throw error;\n }\n return vector;\n }\n\n /**\n * Retrieves a specific vector store instance by its ID.\n *\n * This method searches for a vector store by its internal ID property.\n * If not found by ID, it falls back to searching by registration key.\n *\n * @throws {MastraError} When the specified vector store is not found\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * vectors: {\n * embeddings: chromaVector\n * }\n * });\n *\n * const vectorStore = mastra.getVectorById('chroma-123');\n * ```\n */\n public getVectorById<TVectorName extends keyof TVectors>(id: TVectors[TVectorName]['id']): TVectors[TVectorName] {\n const allVectors = this.#vectors ?? ({} as Record<string, MastraVector>);\n\n // First try to find by internal ID\n for (const vector of Object.values(allVectors)) {\n if (vector.id === id) {\n return vector as TVectors[TVectorName];\n }\n }\n\n // Fallback to searching by registration key\n const vectorByKey = allVectors[id];\n if (vectorByKey) {\n return vectorByKey as TVectors[TVectorName];\n }\n\n const error = new MastraError({\n id: 'MASTRA_GET_VECTOR_BY_ID_NOT_FOUND',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: `Vector store with id ${id} not found`,\n details: {\n status: 404,\n vectorId: String(id),\n vectors: Object.keys(allVectors).join(', '),\n },\n });\n this.#logger?.trackException(error);\n throw error;\n }\n\n /**\n * Returns all registered vector stores as a record keyed by their names.\n *\n * @example Listing all vector stores\n * ```typescript\n * const mastra = new Mastra({\n * vectors: {\n * documents: new PineconeVector({ indexName: 'docs' }),\n * images: new PineconeVector({ indexName: 'images' }),\n * products: new ChromaVector({ collectionName: 'products' })\n * }\n * });\n *\n * const allVectors = mastra.getVectors();\n * console.log(Object.keys(allVectors)); // ['documents', 'images', 'products']\n *\n * // Check vector store types and configurations\n * for (const [name, vectorStore] of Object.entries(allVectors)) {\n * console.log(`Vector store ${name}:`, vectorStore.constructor.name);\n * }\n * ```\n */\n public listVectors(): TVectors | undefined {\n return this.#vectors;\n }\n\n /**\n * Adds a new vector store to the Mastra instance.\n *\n * This method allows dynamic registration of vector stores after the Mastra instance\n * has been created. The vector store will be initialized with the current logger.\n *\n * @throws {MastraError} When a vector store with the same key already exists\n *\n * @example\n * ```typescript\n * const mastra = new Mastra();\n * const newVector = new ChromaVector({ id: 'chroma-embeddings' });\n * mastra.addVector(newVector); // Uses vector.id as key\n * // or\n * mastra.addVector(newVector, 'customKey'); // Uses custom key\n * ```\n */\n public addVector<V extends MastraVector>(vector: V, key?: string): void {\n if (!vector) {\n throw createUndefinedPrimitiveError('vector', vector, key);\n }\n const vectorKey = key || vector.id;\n const vectors = this.#vectors as Record<string, MastraVector>;\n if (vectors[vectorKey]) {\n const logger = this.getLogger();\n logger.debug(`Vector with key ${vectorKey} already exists. Skipping addition.`);\n return;\n }\n\n // Initialize the vector with the logger\n vector.__setLogger(this.#logger || this.getLogger());\n vectors[vectorKey] = vector;\n }\n\n /**\n * @deprecated Use listVectors() instead\n */\n public getVectors(): TVectors | undefined {\n console.warn('getVectors() is deprecated. Use listVectors() instead.');\n return this.listVectors();\n }\n\n /**\n * Gets the currently configured deployment provider.\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * deployer: new VercelDeployer({\n * token: process.env.VERCEL_TOKEN,\n * projectId: process.env.VERCEL_PROJECT_ID\n * })\n * });\n *\n * const deployer = mastra.getDeployer();\n * if (deployer) {\n * await deployer.deploy({\n * name: 'my-mastra-app',\n * environment: 'production'\n * });\n * }\n * ```\n */\n public getDeployer() {\n return this.#deployer;\n }\n\n /**\n * Retrieves a registered workflow by its ID.\n *\n * @template TWorkflowId - The specific workflow ID type from the registered workflows\n * @throws {MastraError} When the workflow with the specified ID is not found\n *\n * @example Getting and executing a workflow\n * ```typescript\n * import { createWorkflow, createStep } from '@mastra/core/workflows';\n * import { z } from 'zod';\n *\n * const processDataWorkflow = createWorkflow({\n * name: 'process-data',\n * triggerSchema: z.object({ input: z.string() })\n * })\n * .then(validateStep)\n * .then(transformStep)\n * .then(saveStep)\n * .commit();\n *\n * const mastra = new Mastra({\n * workflows: {\n * dataProcessor: processDataWorkflow\n * }\n * });\n * ```\n */\n public getWorkflow<TWorkflowId extends keyof TWorkflows>(\n id: TWorkflowId,\n { serialized }: { serialized?: boolean } = {},\n ): TWorkflows[TWorkflowId] {\n const workflow = this.#workflows?.[id];\n if (!workflow) {\n const error = new MastraError({\n id: 'MASTRA_GET_WORKFLOW_BY_ID_NOT_FOUND',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: `Workflow with ID ${String(id)} not found`,\n details: {\n status: 404,\n workflowId: String(id),\n workflows: Object.keys(this.#workflows ?? {}).join(', '),\n },\n });\n this.#logger?.trackException(error);\n throw error;\n }\n\n if (serialized) {\n return { name: workflow.name } as TWorkflows[TWorkflowId];\n }\n\n return workflow;\n }\n\n __registerInternalWorkflow(workflow: Workflow) {\n workflow.__registerMastra(this);\n workflow.__registerPrimitives({\n logger: this.getLogger(),\n });\n this.#internalMastraWorkflows[workflow.id] = workflow;\n }\n\n __hasInternalWorkflow(id: string): boolean {\n return Object.values(this.#internalMastraWorkflows).some(workflow => workflow.id === id);\n }\n\n __getInternalWorkflow(id: string): Workflow {\n const workflow = Object.values(this.#internalMastraWorkflows).find(a => a.id === id);\n if (!workflow) {\n throw new MastraError({\n id: 'MASTRA_GET_INTERNAL_WORKFLOW_BY_ID_NOT_FOUND',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.SYSTEM,\n text: `Workflow with id ${String(id)} not found`,\n details: {\n status: 404,\n workflowId: String(id),\n },\n });\n }\n\n return workflow;\n }\n\n /**\n * Retrieves a registered workflow by its unique ID.\n *\n * This method searches for a workflow using its internal ID property. If no workflow\n * is found with the given ID, it also attempts to find a workflow using the ID as\n * a name.\n *\n * @throws {MastraError} When no workflow is found with the specified ID\n *\n * @example Finding a workflow by ID\n * ```typescript\n * const mastra = new Mastra({\n * workflows: {\n * dataProcessor: createWorkflow({\n * name: 'process-data',\n * triggerSchema: z.object({ input: z.string() })\n * }).commit()\n * }\n * });\n *\n * // Get the workflow's ID\n * const workflow = mastra.getWorkflow('dataProcessor');\n * const workflowId = workflow.id;\n *\n * // Later, retrieve the workflow by ID\n * const sameWorkflow = mastra.getWorkflowById(workflowId);\n * console.log(sameWorkflow.name); // \"process-data\"\n * ```\n */\n public getWorkflowById<TWorkflowName extends keyof TWorkflows>(\n id: TWorkflows[TWorkflowName]['id'],\n ): TWorkflows[TWorkflowName] {\n let workflow = Object.values(this.#workflows).find(a => a.id === id);\n\n if (!workflow) {\n try {\n workflow = this.getWorkflow(id);\n } catch {\n // do nothing\n }\n }\n\n if (!workflow) {\n const error = new MastraError({\n id: 'MASTRA_GET_WORKFLOW_BY_ID_NOT_FOUND',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: `Workflow with id ${String(id)} not found`,\n details: {\n status: 404,\n workflowId: String(id),\n workflows: Object.keys(this.#workflows ?? {}).join(', '),\n },\n });\n this.#logger?.trackException(error);\n throw error;\n }\n\n return workflow as TWorkflows[TWorkflowName];\n }\n\n public async listActiveWorkflowRuns(): Promise<WorkflowRuns> {\n const storage = this.#storage;\n if (!storage) {\n this.#logger.debug('Cannot get active workflow runs. Mastra storage is not initialized');\n return { runs: [], total: 0 };\n }\n\n // Get all workflows with default engine type\n const defaultEngineWorkflows = Object.values(this.#workflows).filter(workflow => workflow.engineType === 'default');\n\n // Collect all active runs for workflows with default engine type\n const allRuns: WorkflowRuns['runs'] = [];\n let allTotal = 0;\n\n for (const workflow of defaultEngineWorkflows) {\n const runningRuns = await workflow.listWorkflowRuns({ status: 'running' });\n const waitingRuns = await workflow.listWorkflowRuns({ status: 'waiting' });\n\n allRuns.push(...runningRuns.runs, ...waitingRuns.runs);\n allTotal += runningRuns.total + waitingRuns.total;\n }\n\n return {\n runs: allRuns,\n total: allTotal,\n };\n }\n\n public async restartAllActiveWorkflowRuns(): Promise<void> {\n const activeRuns = await this.listActiveWorkflowRuns();\n if (activeRuns.runs.length > 0) {\n this.#logger.debug(\n `Restarting ${activeRuns.runs.length} active workflow run${activeRuns.runs.length > 1 ? 's' : ''}`,\n );\n }\n for (const runSnapshot of activeRuns.runs) {\n const workflow = this.getWorkflowById(runSnapshot.workflowName);\n try {\n const run = await workflow.createRun({ runId: runSnapshot.runId });\n await run.restart();\n this.#logger.debug(`Restarted ${runSnapshot.workflowName} workflow run ${runSnapshot.runId}`);\n } catch (error) {\n this.#logger.error(`Failed to restart ${runSnapshot.workflowName} workflow run ${runSnapshot.runId}: ${error}`);\n }\n }\n }\n\n /**\n * Returns all registered scorers as a record keyed by their IDs.\n *\n * @example Listing all scorers\n * ```typescript\n * import { HelpfulnessScorer, AccuracyScorer, RelevanceScorer } from '@mastra/scorers';\n *\n * const mastra = new Mastra({\n * scorers: {\n * helpfulness: new HelpfulnessScorer(),\n * accuracy: new AccuracyScorer(),\n * relevance: new RelevanceScorer()\n * }\n * });\n *\n * const allScorers = mastra.listScorers();\n * console.log(Object.keys(allScorers)); // ['helpfulness', 'accuracy', 'relevance']\n *\n * // Check scorer configurations\n * for (const [id, scorer] of Object.entries(allScorers)) {\n * console.log(`Scorer ${id}:`, scorer.id, scorer.name, scorer.description);\n * }\n * ```\n */\n public listScorers() {\n return this.#scorers;\n }\n\n /**\n * Adds a new scorer to the Mastra instance.\n *\n * This method allows dynamic registration of scorers after the Mastra instance\n * has been created.\n *\n * @throws {MastraError} When a scorer with the same key already exists\n *\n * @example\n * ```typescript\n * const mastra = new Mastra();\n * const newScorer = new MastraScorer({\n * id: 'quality-scorer',\n * name: 'Quality Scorer'\n * });\n * mastra.addScorer(newScorer); // Uses scorer.id as key\n * // or\n * mastra.addScorer(newScorer, 'customKey'); // Uses custom key\n * ```\n */\n public addScorer<S extends MastraScorer<any, any, any, any>>(scorer: S, key?: string): void {\n if (!scorer) {\n throw createUndefinedPrimitiveError('scorer', scorer, key);\n }\n const scorerKey = key || scorer.id;\n const scorers = this.#scorers as Record<string, MastraScorer<any, any, any, any>>;\n if (scorers[scorerKey]) {\n const logger = this.getLogger();\n logger.debug(`Scorer with key ${scorerKey} already exists. Skipping addition.`);\n return;\n }\n\n // Register Mastra instance with scorer to enable custom gateway access\n scorer.__registerMastra(this);\n\n scorers[scorerKey] = scorer;\n }\n\n /**\n * Retrieves a registered scorer by its key.\n *\n * @template TScorerKey - The specific scorer key type from the registered scorers\n * @throws {MastraError} When the scorer with the specified key is not found\n *\n * @example Getting and using a scorer\n * ```typescript\n * import { HelpfulnessScorer, AccuracyScorer } from '@mastra/scorers';\n *\n * const mastra = new Mastra({\n * scorers: {\n * helpfulness: new HelpfulnessScorer({\n * model: 'openai/gpt-4o',\n * criteria: 'Rate how helpful this response is'\n * }),\n * accuracy: new AccuracyScorer({\n * model: 'openai/gpt-5'\n * })\n * }\n * });\n *\n * // Get a specific scorer\n * const helpfulnessScorer = mastra.getScorer('helpfulness');\n * const score = await helpfulnessScorer.score({\n * input: 'How do I reset my password?',\n * output: 'You can reset your password by clicking the forgot password link.',\n * expected: 'Detailed password reset instructions'\n * });\n *\n * console.log('Helpfulness score:', score);\n * ```\n */\n public getScorer<TScorerKey extends keyof TScorers>(key: TScorerKey): TScorers[TScorerKey] {\n const scorer = this.#scorers?.[key];\n if (!scorer) {\n const error = new MastraError({\n id: 'MASTRA_GET_SCORER_NOT_FOUND',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: `Scorer with ${String(key)} not found`,\n });\n this.#logger?.trackException(error);\n throw error;\n }\n return scorer;\n }\n\n /**\n * Retrieves a registered scorer by its name.\n *\n * This method searches through all registered scorers to find one with the specified name.\n * Unlike `getScorer()` which uses the registration key, this method uses the scorer's\n * internal name property.\n *\n * @throws {MastraError} When no scorer is found with the specified name\n *\n * @example Finding a scorer by name\n * ```typescript\n * import { HelpfulnessScorer } from '@mastra/scorers';\n *\n * const mastra = new Mastra({\n * scorers: {\n * myHelpfulnessScorer: new HelpfulnessScorer({\n * name: 'helpfulness-evaluator',\n * model: 'openai/gpt-5'\n * })\n * }\n * });\n *\n * // Find scorer by its internal name, not the registration key\n * const scorer = mastra.getScorerById('helpfulness-evaluator');\n * const score = await scorer.score({\n * input: 'question',\n * output: 'answer'\n * });\n * ```\n */\n public getScorerById<TScorerName extends keyof TScorers>(id: TScorers[TScorerName]['id']): TScorers[TScorerName] {\n for (const [_key, value] of Object.entries(this.#scorers ?? {})) {\n if (value.id === id || value?.name === id) {\n return value as TScorers[TScorerName];\n }\n }\n\n const error = new MastraError({\n id: 'MASTRA_GET_SCORER_BY_ID_NOT_FOUND',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: `Scorer with id ${String(id)} not found`,\n });\n this.#logger?.trackException(error);\n throw error;\n }\n\n /**\n * Retrieves a specific tool by registration key.\n *\n * @throws {MastraError} When the specified tool is not found\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * tools: {\n * calculator: calculatorTool,\n * weather: weatherTool\n * }\n * });\n *\n * const tool = mastra.getTool('calculator');\n * ```\n */\n public getTool<TToolName extends keyof TTools>(name: TToolName): TTools[TToolName] {\n if (!this.#tools || !this.#tools[name]) {\n const error = new MastraError({\n id: 'MASTRA_GET_TOOL_BY_NAME_NOT_FOUND',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: `Tool with name ${String(name)} not found`,\n details: {\n status: 404,\n toolName: String(name),\n tools: Object.keys(this.#tools ?? {}).join(', '),\n },\n });\n this.#logger?.trackException(error);\n throw error;\n }\n return this.#tools[name];\n }\n\n /**\n * Retrieves a specific tool by its ID.\n *\n * @throws {MastraError} When the specified tool is not found\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * tools: {\n * calculator: calculatorTool\n * }\n * });\n *\n * const tool = mastra.getToolById('calculator-tool-id');\n * ```\n */\n public getToolById<TToolName extends keyof TTools>(id: TTools[TToolName]['id']): TTools[TToolName] {\n const allTools = this.#tools;\n\n if (!allTools) {\n throw new MastraError({\n id: 'MASTRA_GET_TOOL_BY_ID_NOT_FOUND',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: `Tool with id ${id} not found`,\n });\n }\n // First try to find by internal ID\n for (const tool of Object.values(allTools)) {\n if (tool.id === id) {\n return tool as TTools[TToolName];\n }\n }\n\n // Fallback to searching by registration key\n const toolByKey = allTools[id];\n if (toolByKey) {\n return toolByKey as TTools[TToolName];\n }\n\n const error = new MastraError({\n id: 'MASTRA_GET_TOOL_BY_ID_NOT_FOUND',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: `Tool with id ${id} not found`,\n details: {\n status: 404,\n toolId: String(id),\n tools: Object.keys(allTools).join(', '),\n },\n });\n this.#logger?.trackException(error);\n throw error;\n }\n\n /**\n * Lists all configured tools.\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * tools: {\n * calculator: calculatorTool,\n * weather: weatherTool\n * }\n * });\n *\n * const tools = mastra.listTools();\n * Object.entries(tools || {}).forEach(([name, tool]) => {\n * console.log(`Tool \"${name}\":`, tool.id);\n * });\n * ```\n */\n public listTools(): TTools | undefined {\n return this.#tools;\n }\n\n /**\n * Adds a new tool to the Mastra instance.\n *\n * This method allows dynamic registration of tools after the Mastra instance\n * has been created.\n *\n * @throws {MastraError} When a tool with the same key already exists\n *\n * @example\n * ```typescript\n * const mastra = new Mastra();\n * const newTool = createTool({\n * id: 'calculator-tool',\n * description: 'Performs calculations'\n * });\n * mastra.addTool(newTool); // Uses tool.id as key\n * // or\n * mastra.addTool(newTool, 'customKey'); // Uses custom key\n * ```\n */\n public addTool<T extends ToolAction<any, any, any, any>>(tool: T, key?: string): void {\n if (!tool) {\n throw createUndefinedPrimitiveError('tool', tool, key);\n }\n const toolKey = key || tool.id;\n const tools = this.#tools as Record<string, ToolAction<any, any, any, any>>;\n if (tools[toolKey]) {\n const logger = this.getLogger();\n logger.debug(`Tool with key ${toolKey} already exists. Skipping addition.`);\n return;\n }\n\n tools[toolKey] = tool;\n }\n\n /**\n * Retrieves a specific processor by registration key.\n *\n * @throws {MastraError} When the specified processor is not found\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * processors: {\n * validator: validatorProcessor,\n * transformer: transformerProcessor\n * }\n * });\n *\n * const processor = mastra.getProcessor('validator');\n * ```\n */\n public getProcessor<TProcessorName extends keyof TProcessors>(name: TProcessorName): TProcessors[TProcessorName] {\n if (!this.#processors || !this.#processors[name]) {\n const error = new MastraError({\n id: 'MASTRA_GET_PROCESSOR_BY_NAME_NOT_FOUND',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: `Processor with name ${String(name)} not found`,\n details: {\n status: 404,\n processorName: String(name),\n processors: Object.keys(this.#processors ?? {}).join(', '),\n },\n });\n this.#logger?.trackException(error);\n throw error;\n }\n return this.#processors[name];\n }\n\n /**\n * Retrieves a specific processor by its ID.\n *\n * @throws {MastraError} When the specified processor is not found\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * processors: {\n * validator: validatorProcessor\n * }\n * });\n *\n * const processor = mastra.getProcessorById('validator-processor-id');\n * ```\n */\n public getProcessorById<TProcessorName extends keyof TProcessors>(\n id: TProcessors[TProcessorName]['id'],\n ): TProcessors[TProcessorName] {\n const allProcessors = this.#processors;\n\n if (!allProcessors) {\n throw new MastraError({\n id: 'MASTRA_GET_PROCESSOR_BY_ID_NOT_FOUND',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: `Processor with id ${id} not found`,\n });\n }\n\n // First try to find by internal ID\n for (const processor of Object.values(allProcessors)) {\n if (processor.id === id) {\n return processor as TProcessors[TProcessorName];\n }\n }\n\n // Fallback to searching by registration key\n const processorByKey = allProcessors[id];\n if (processorByKey) {\n return processorByKey as TProcessors[TProcessorName];\n }\n\n const error = new MastraError({\n id: 'MASTRA_GET_PROCESSOR_BY_ID_NOT_FOUND',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: `Processor with id ${id} not found`,\n details: {\n status: 404,\n processorId: String(id),\n processors: Object.keys(allProcessors).join(', '),\n },\n });\n this.#logger?.trackException(error);\n throw error;\n }\n\n /**\n * Lists all configured processors.\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * processors: {\n * validator: validatorProcessor,\n * transformer: transformerProcessor\n * }\n * });\n *\n * const processors = mastra.listProcessors();\n * Object.entries(processors || {}).forEach(([name, processor]) => {\n * console.log(`Processor \"${name}\":`, processor.id);\n * });\n * ```\n */\n public listProcessors(): TProcessors | undefined {\n return this.#processors;\n }\n\n /**\n * Adds a new processor to the Mastra instance.\n *\n * This method allows dynamic registration of processors after the Mastra instance\n * has been created.\n *\n * @throws {MastraError} When a processor with the same key already exists\n *\n * @example\n * ```typescript\n * const mastra = new Mastra();\n * const newProcessor = {\n * id: 'text-processor',\n * processInput: async (messages) => messages\n * };\n * mastra.addProcessor(newProcessor); // Uses processor.id as key\n * // or\n * mastra.addProcessor(newProcessor, 'customKey'); // Uses custom key\n * ```\n */\n public addProcessor<P extends Processor>(processor: P, key?: string): void {\n if (!processor) {\n throw createUndefinedPrimitiveError('processor', processor, key);\n }\n const processorKey = key || processor.id;\n const processors = this.#processors as Record<string, Processor>;\n if (processors[processorKey]) {\n const logger = this.getLogger();\n logger.debug(`Processor with key ${processorKey} already exists. Skipping addition.`);\n return;\n }\n\n processors[processorKey] = processor;\n }\n\n /**\n * Returns all registered workflows as a record keyed by their IDs.\n *\n * @example Listing all workflows\n * ```typescript\n * const mastra = new Mastra({\n * workflows: {\n * dataProcessor: createWorkflow({...}).commit(),\n * emailSender: createWorkflow({...}).commit(),\n * reportGenerator: createWorkflow({...}).commit()\n * }\n * });\n *\n * const allWorkflows = mastra.listWorkflows();\n * console.log(Object.keys(allWorkflows)); // ['dataProcessor', 'emailSender', 'reportGenerator']\n *\n * // Execute all workflows with sample data\n * for (const [id, workflow] of Object.entries(allWorkflows)) {\n * console.log(`Workflow ${id}:`, workflow.name);\n * // const result = await workflow.execute(sampleData);\n * }\n * ```\n */\n public listWorkflows(props: { serialized?: boolean } = {}): Record<string, Workflow> {\n if (props.serialized) {\n return Object.entries(this.#workflows).reduce((acc, [k, v]) => {\n return {\n ...acc,\n [k]: { name: v.name },\n };\n }, {});\n }\n return this.#workflows;\n }\n\n /**\n * Adds a new workflow to the Mastra instance.\n *\n * This method allows dynamic registration of workflows after the Mastra instance\n * has been created. The workflow will be initialized with Mastra and primitives.\n *\n * @throws {MastraError} When a workflow with the same key already exists\n *\n * @example\n * ```typescript\n * const mastra = new Mastra();\n * const newWorkflow = createWorkflow({\n * id: 'data-pipeline',\n * name: 'Data Pipeline'\n * }).commit();\n * mastra.addWorkflow(newWorkflow); // Uses workflow.id as key\n * // or\n * mastra.addWorkflow(newWorkflow, 'customKey'); // Uses custom key\n * ```\n */\n public addWorkflow<W extends Workflow<any, any, any, any, any, any>>(workflow: W, key?: string): void {\n if (!workflow) {\n throw createUndefinedPrimitiveError('workflow', workflow, key);\n }\n const workflowKey = key || workflow.id;\n const workflows = this.#workflows as Record<string, Workflow<any, any, any, any, any, any>>;\n if (workflows[workflowKey]) {\n const logger = this.getLogger();\n logger.debug(`Workflow with key ${workflowKey} already exists. Skipping addition.`);\n return;\n }\n\n // Initialize the workflow with Mastra and primitives\n workflow.__registerMastra(this);\n workflow.__registerPrimitives({\n logger: this.getLogger(),\n storage: this.getStorage(),\n });\n if (!workflow.committed) {\n workflow.commit();\n }\n workflows[workflowKey] = workflow;\n }\n\n /**\n * Sets the storage provider for the Mastra instance.\n *\n * @example\n * ```typescript\n * const mastra = new Mastra();\n *\n * // Set PostgreSQL storage\n * mastra.setStorage(new PostgresStore({\n * connectionString: process.env.DATABASE_URL\n * }));\n *\n * // Now agents can use memory with the storage\n * const agent = new Agent({\n * id: 'assistant',\n * name: 'assistant',\n * memory: new Memory({ storage: mastra.getStorage() })\n * });\n * ```\n */\n public setStorage(storage: MastraStorage) {\n this.#storage = augmentWithInit(storage);\n }\n\n public setLogger({ logger }: { logger: TLogger }) {\n this.#logger = logger;\n\n if (this.#agents) {\n Object.keys(this.#agents).forEach(key => {\n this.#agents?.[key]?.__setLogger(this.#logger);\n });\n }\n\n if (this.#deployer) {\n this.#deployer.__setLogger(this.#logger);\n }\n\n if (this.#tts) {\n Object.keys(this.#tts).forEach(key => {\n this.#tts?.[key]?.__setLogger(this.#logger);\n });\n }\n\n if (this.#storage) {\n this.#storage.__setLogger(this.#logger);\n }\n\n if (this.#vectors) {\n Object.keys(this.#vectors).forEach(key => {\n this.#vectors?.[key]?.__setLogger(this.#logger);\n });\n }\n\n if (this.#mcpServers) {\n Object.keys(this.#mcpServers).forEach(key => {\n this.#mcpServers?.[key]?.__setLogger(this.#logger);\n });\n }\n\n if (this.#serverAdapter) {\n this.#serverAdapter.__setLogger(this.#logger);\n }\n\n this.#observability.setLogger({ logger: this.#logger });\n }\n\n /**\n * Gets all registered text-to-speech (TTS) providers.\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * tts: {\n * openai: new OpenAITTS({\n * apiKey: process.env.OPENAI_API_KEY,\n * voice: 'alloy'\n * })\n * }\n * });\n *\n * const ttsProviders = mastra.getTTS();\n * const openaiTTS = ttsProviders?.openai;\n * if (openaiTTS) {\n * const audioBuffer = await openaiTTS.synthesize('Hello, world!');\n * }\n * ```\n */\n public getTTS() {\n return this.#tts;\n }\n\n /**\n * Gets the currently configured logger instance.\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * logger: new PinoLogger({\n * name: 'MyApp',\n * level: 'info'\n * })\n * });\n *\n * const logger = mastra.getLogger();\n * logger.info('Application started');\n * logger.error('An error occurred', { error: 'details' });\n * ```\n */\n public getLogger() {\n return this.#logger;\n }\n\n /**\n * Gets the currently configured storage provider.\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * storage: new LibSQLStore({ id: 'mastra-storage', url: 'file:./data.db' })\n * });\n *\n * // Use the storage in agent memory\n * const agent = new Agent({\n * id: 'assistant',\n * name: 'assistant',\n * memory: new Memory({\n * storage: mastra.getStorage()\n * })\n * });\n * ```\n */\n public getStorage() {\n return this.#storage;\n }\n\n get observability(): ObservabilityEntrypoint {\n return this.#observability;\n }\n\n public getServerMiddleware() {\n return this.#serverMiddleware;\n }\n\n public getServerCache() {\n return this.#serverCache;\n }\n\n public setServerMiddleware(serverMiddleware: Middleware | Middleware[]) {\n if (typeof serverMiddleware === 'function') {\n this.#serverMiddleware = [\n {\n handler: serverMiddleware,\n path: '/api/*',\n },\n ];\n return;\n }\n\n if (!Array.isArray(serverMiddleware)) {\n const error = new MastraError({\n id: 'MASTRA_SET_SERVER_MIDDLEWARE_INVALID_TYPE',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: `Invalid middleware: expected a function or array, received ${typeof serverMiddleware}`,\n });\n this.#logger?.trackException(error);\n throw error;\n }\n\n this.#serverMiddleware = serverMiddleware.map(m => {\n if (typeof m === 'function') {\n return {\n handler: m,\n path: '/api/*',\n };\n }\n return {\n handler: m.handler,\n path: m.path || '/api/*',\n };\n });\n }\n\n public getServer() {\n return this.#server;\n }\n\n /**\n * Sets the server adapter for this Mastra instance.\n *\n * The server adapter provides access to the underlying server app (e.g., Hono, Express)\n * and allows users to call routes directly via `app.fetch()` instead of making HTTP requests.\n *\n * This is typically called by `createHonoServer` or similar factory functions during\n * server initialization.\n *\n * @param adapter - The server adapter instance (e.g., MastraServer from @mastra/hono or @mastra/express)\n *\n * @example\n * ```typescript\n * const app = new Hono();\n * const adapter = new MastraServer({ app, mastra });\n * mastra.setMastraServer(adapter);\n * ```\n */\n public setMastraServer(adapter: MastraServerBase): void {\n if (this.#serverAdapter) {\n this.#logger?.debug(\n 'Replacing existing server adapter. Only one adapter should be registered per Mastra instance.',\n );\n }\n this.#serverAdapter = adapter;\n // Inject the logger into the adapter\n if (this.#logger) {\n adapter.__setLogger(this.#logger);\n }\n }\n\n /**\n * Gets the server adapter for this Mastra instance.\n *\n * @returns The server adapter, or undefined if not set\n *\n * @example\n * ```typescript\n * const adapter = mastra.getMastraServer();\n * if (adapter) {\n * const app = adapter.getApp<Hono>();\n * }\n * ```\n */\n public getMastraServer(): MastraServerBase | undefined {\n return this.#serverAdapter;\n }\n\n /**\n * Gets the server app from the server adapter.\n *\n * This is a convenience method that calls `getMastraServer()?.getApp<T>()`.\n * Use this to access the underlying server framework's app instance (e.g., Hono, Express)\n * for direct operations like calling routes via `app.fetch()`.\n *\n * @template T - The expected type of the app (e.g., Hono, Express Application)\n * @returns The server app, or undefined if no adapter is set\n *\n * @example\n * ```typescript\n * // After createHonoServer() is called:\n * const app = mastra.getServerApp<Hono>();\n *\n * // Call routes directly without HTTP overhead\n * const response = await app?.fetch(new Request('http://localhost/health'));\n * const data = await response?.json();\n * ```\n */\n public getServerApp<T = unknown>(): T | undefined {\n return this.#serverAdapter?.getApp<T>();\n }\n\n public getBundlerConfig() {\n return this.#bundler;\n }\n\n public async listLogsByRunId({\n runId,\n transportId,\n fromDate,\n toDate,\n logLevel,\n filters,\n page,\n perPage,\n }: {\n runId: string;\n transportId: string;\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n page?: number;\n perPage?: number;\n }) {\n if (!transportId) {\n const error = new MastraError({\n id: 'MASTRA_LIST_LOGS_BY_RUN_ID_MISSING_TRANSPORT',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: 'Transport ID is required',\n details: {\n runId,\n transportId,\n },\n });\n this.#logger?.trackException(error);\n throw error;\n }\n\n if (!this.#logger?.listLogsByRunId) {\n const error = new MastraError({\n id: 'MASTRA_GET_LOGS_BY_RUN_ID_LOGGER_NOT_CONFIGURED',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.SYSTEM,\n text: 'Logger is not configured or does not support listLogsByRunId operation',\n details: {\n runId,\n transportId,\n },\n });\n this.#logger?.trackException(error);\n throw error;\n }\n\n return await this.#logger.listLogsByRunId({\n runId,\n transportId,\n fromDate,\n toDate,\n logLevel,\n filters,\n page,\n perPage,\n });\n }\n\n public async listLogs(\n transportId: string,\n params?: {\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n page?: number;\n perPage?: number;\n },\n ) {\n if (!transportId) {\n const error = new MastraError({\n id: 'MASTRA_GET_LOGS_MISSING_TRANSPORT',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: 'Transport ID is required',\n details: {\n transportId,\n },\n });\n this.#logger?.trackException(error);\n throw error;\n }\n\n if (!this.#logger) {\n const error = new MastraError({\n id: 'MASTRA_GET_LOGS_LOGGER_NOT_CONFIGURED',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.SYSTEM,\n text: 'Logger is not set',\n details: {\n transportId,\n },\n });\n throw error;\n }\n\n return await this.#logger.listLogs(transportId, params);\n }\n\n /**\n * Gets all registered Model Context Protocol (MCP) server instances.\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * mcpServers: {\n * filesystem: new FileSystemMCPServer({\n * rootPath: '/app/data'\n * })\n * }\n * });\n *\n * const mcpServers = mastra.getMCPServers();\n * if (mcpServers) {\n * const fsServer = mcpServers.filesystem;\n * const tools = await fsServer.listTools();\n * }\n * ```\n */\n public listMCPServers(): Record<string, MCPServerBase> | undefined {\n return this.#mcpServers;\n }\n\n /**\n * Adds a new MCP server to the Mastra instance.\n *\n * This method allows dynamic registration of MCP servers after the Mastra instance\n * has been created. The server will be initialized with ID, Mastra instance, and logger.\n *\n * @throws {MastraError} When an MCP server with the same key already exists\n *\n * @example\n * ```typescript\n * const mastra = new Mastra();\n * const newServer = new FileSystemMCPServer({\n * rootPath: '/data'\n * });\n * mastra.addMCPServer(newServer); // Uses server.id as key\n * // or\n * mastra.addMCPServer(newServer, 'customKey'); // Uses custom key\n * ```\n */\n public addMCPServer<M extends MCPServerBase>(server: M, key?: string): void {\n if (!server) {\n throw createUndefinedPrimitiveError('mcp-server', server, key);\n }\n // If a key is provided, try to set it as the ID\n // The setId method will only update if the ID wasn't explicitly set by the user\n if (key) {\n server.setId(key);\n }\n\n // Now resolve the ID after potentially setting it\n const resolvedId = server.id;\n if (!resolvedId) {\n const error = new MastraError({\n id: 'MASTRA_ADD_MCP_SERVER_MISSING_ID',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: 'MCP server must expose an id or be registered under one',\n details: { status: 400 },\n });\n this.#logger?.trackException(error);\n throw error;\n }\n\n const serverKey = key ?? resolvedId;\n const servers = this.#mcpServers as Record<string, MCPServerBase>;\n if (servers[serverKey]) {\n const logger = this.getLogger();\n logger.debug(`MCP server with key ${serverKey} already exists. Skipping addition.`);\n return;\n }\n\n // Initialize the server\n server.__registerMastra(this);\n server.__setLogger(this.getLogger());\n servers[serverKey] = server;\n }\n\n /**\n * Retrieves a specific MCP server instance by registration key.\n *\n * @throws {MastraError} When the specified MCP server is not found\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * mcpServers: {\n * filesystem: new FileSystemMCPServer({...})\n * }\n * });\n *\n * const fsServer = mastra.getMCPServer('filesystem');\n * const tools = await fsServer.listTools();\n * ```\n */\n public getMCPServer<TMCPServerName extends keyof TMCPServers>(\n name: TMCPServerName,\n ): TMCPServers[TMCPServerName] | undefined {\n if (!this.#mcpServers || !this.#mcpServers[name]) {\n this.#logger?.debug(`MCP server with name ${String(name)} not found`);\n return undefined as TMCPServers[TMCPServerName] | undefined;\n }\n return this.#mcpServers[name];\n }\n\n /**\n * Retrieves a specific Model Context Protocol (MCP) server instance by its logical ID.\n *\n * This method searches for an MCP server using its logical ID. If a version is specified,\n * it returns the exact version match. If no version is provided, it returns the server\n * with the most recent release date.\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * mcpServers: {\n * filesystem: new FileSystemMCPServer({\n * id: 'fs-server',\n * version: '1.0.0',\n * rootPath: '/app/data'\n * })\n * }\n * });\n *\n * const fsServer = mastra.getMCPServerById('fs-server');\n * if (fsServer) {\n * const tools = await fsServer.listTools();\n * }\n * ```\n */\n public getMCPServerById<TMCPServerName extends keyof TMCPServers>(\n serverId: TMCPServers[TMCPServerName]['id'],\n version?: string,\n ): TMCPServers[TMCPServerName] | undefined {\n if (!this.#mcpServers) {\n return undefined;\n }\n\n const allRegisteredServers = Object.values(this.#mcpServers || {});\n\n const matchingLogicalIdServers = allRegisteredServers.filter(server => server.id === serverId);\n\n if (matchingLogicalIdServers.length === 0) {\n this.#logger?.debug(`No MCP servers found with logical ID: ${serverId}`);\n return undefined;\n }\n\n if (version) {\n const specificVersionServer = matchingLogicalIdServers.find(server => server.version === version);\n if (!specificVersionServer) {\n this.#logger?.debug(`MCP server with logical ID '${serverId}' found, but not version '${version}'.`);\n }\n return specificVersionServer as TMCPServers[TMCPServerName] | undefined;\n } else {\n // No version specified, find the one with the most recent releaseDate\n if (matchingLogicalIdServers.length === 1) {\n return matchingLogicalIdServers[0] as TMCPServers[TMCPServerName];\n }\n\n matchingLogicalIdServers.sort((a, b) => {\n // Ensure releaseDate exists and is a string before creating a Date object\n const dateAVal = a.releaseDate && typeof a.releaseDate === 'string' ? new Date(a.releaseDate).getTime() : NaN;\n const dateBVal = b.releaseDate && typeof b.releaseDate === 'string' ? new Date(b.releaseDate).getTime() : NaN;\n\n if (isNaN(dateAVal) && isNaN(dateBVal)) return 0;\n if (isNaN(dateAVal)) return 1; // Treat invalid/missing dates as older\n if (isNaN(dateBVal)) return -1; // Treat invalid/missing dates as older\n\n return dateBVal - dateAVal; // Sorts in descending order of time (latest first)\n });\n\n // After sorting, the first element should be the latest if its date is valid\n if (matchingLogicalIdServers.length > 0) {\n const latestServer = matchingLogicalIdServers[0];\n if (\n latestServer &&\n latestServer.releaseDate &&\n typeof latestServer.releaseDate === 'string' &&\n !isNaN(new Date(latestServer.releaseDate).getTime())\n ) {\n return latestServer as TMCPServers[TMCPServerName];\n }\n }\n this.#logger?.warn(\n `Could not determine the latest server for logical ID '${serverId}' due to invalid or missing release dates, or no servers left after filtering.`,\n );\n return undefined;\n }\n }\n\n public async addTopicListener(topic: string, listener: (event: any) => Promise<void>) {\n await this.#pubsub.subscribe(topic, listener);\n }\n\n public async removeTopicListener(topic: string, listener: (event: any) => Promise<void>) {\n await this.#pubsub.unsubscribe(topic, listener);\n }\n\n public async startEventEngine() {\n for (const topic in this.#events) {\n if (!this.#events[topic]) {\n continue;\n }\n\n const listeners = Array.isArray(this.#events[topic]) ? this.#events[topic] : [this.#events[topic]];\n for (const listener of listeners) {\n await this.#pubsub.subscribe(topic, listener);\n }\n }\n }\n\n public async stopEventEngine() {\n for (const topic in this.#events) {\n if (!this.#events[topic]) {\n continue;\n }\n\n const listeners = Array.isArray(this.#events[topic]) ? this.#events[topic] : [this.#events[topic]];\n for (const listener of listeners) {\n await this.#pubsub.unsubscribe(topic, listener);\n }\n }\n\n await this.#pubsub.flush();\n }\n\n /**\n * Retrieves a registered gateway by its key.\n *\n * @throws {MastraError} When the gateway with the specified key is not found\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * gateways: {\n * myGateway: new CustomGateway()\n * }\n * });\n *\n * const gateway = mastra.getGateway('myGateway');\n * ```\n */\n public getGateway(key: string): MastraModelGateway {\n const gateway = this.#gateways?.[key];\n if (!gateway) {\n const error = new MastraError({\n id: 'MASTRA_GET_GATEWAY_BY_KEY_NOT_FOUND',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: `Gateway with key ${key} not found`,\n details: {\n status: 404,\n gatewayKey: key,\n gateways: Object.keys(this.#gateways ?? {}).join(', '),\n },\n });\n this.#logger?.trackException(error);\n throw error;\n }\n return gateway;\n }\n\n /**\n * Retrieves a registered gateway by its ID.\n *\n * Searches through all registered gateways and returns the one whose ID matches.\n * If a gateway doesn't have an explicit ID, its name is used as the ID.\n *\n * @throws {MastraError} When no gateway with the specified ID is found\n *\n * @example\n * ```typescript\n * class CustomGateway extends MastraModelGateway {\n * readonly id = 'custom-gateway-v1';\n * readonly name = 'Custom Gateway';\n * // ...\n * }\n *\n * const mastra = new Mastra({\n * gateways: {\n * myGateway: new CustomGateway()\n * }\n * });\n *\n * const gateway = mastra.getGatewayById('custom-gateway-v1');\n * ```\n */\n public getGatewayById(id: string): MastraModelGateway {\n const gateways = this.#gateways ?? {};\n for (const gateway of Object.values(gateways)) {\n if (gateway.getId() === id) {\n return gateway;\n }\n }\n\n const error = new MastraError({\n id: 'MASTRA_GET_GATEWAY_BY_ID_NOT_FOUND',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: `Gateway with ID ${id} not found`,\n details: {\n status: 404,\n gatewayId: id,\n availableIds: Object.values(gateways)\n .map(g => g.getId())\n .join(', '),\n },\n });\n this.#logger?.trackException(error);\n throw error;\n }\n\n /**\n * Returns all registered gateways as a record keyed by their names.\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * gateways: {\n * netlify: new NetlifyGateway(),\n * custom: new CustomGateway()\n * }\n * });\n *\n * const allGateways = mastra.listGateways();\n * console.log(Object.keys(allGateways)); // ['netlify', 'custom']\n * ```\n */\n public listGateways(): Record<string, MastraModelGateway> | undefined {\n return this.#gateways;\n }\n\n /**\n * Adds a new gateway to the Mastra instance.\n *\n * This method allows dynamic registration of gateways after the Mastra instance\n * has been created. Gateways enable access to LLM providers through custom\n * authentication and routing logic.\n *\n * If no key is provided, the gateway's ID (or name if no ID is set) will be used as the key.\n *\n * @example\n * ```typescript\n * import { MastraModelGateway } from '@mastra/core';\n *\n * class CustomGateway extends MastraModelGateway {\n * readonly id = 'custom-gateway-v1'; // Optional, defaults to name\n * readonly name = 'custom';\n * readonly prefix = 'custom';\n *\n * async fetchProviders() {\n * return {\n * myProvider: {\n * name: 'My Provider',\n * models: ['model-1', 'model-2'],\n * apiKeyEnvVar: 'MY_API_KEY',\n * gateway: 'custom'\n * }\n * };\n * }\n *\n * buildUrl(modelId: string) {\n * return 'https://api.myprovider.com/v1';\n * }\n *\n * async getApiKey(modelId: string) {\n * return process.env.MY_API_KEY || '';\n * }\n *\n * async resolveLanguageModel({ modelId, providerId, apiKey }) {\n * const baseURL = this.buildUrl(`${providerId}/${modelId}`);\n * return createOpenAICompatible({\n * name: providerId,\n * apiKey,\n * baseURL,\n * supportsStructuredOutputs: true,\n * }).chatModel(modelId);\n * }\n * }\n *\n * const mastra = new Mastra();\n * const newGateway = new CustomGateway();\n * mastra.addGateway(newGateway); // Uses gateway.getId() as key (gateway.id)\n * // or\n * mastra.addGateway(newGateway, 'customKey'); // Uses custom key\n * ```\n */\n public addGateway(gateway: MastraModelGateway, key?: string): void {\n if (!gateway) {\n throw createUndefinedPrimitiveError('gateway', gateway, key);\n }\n const gatewayKey = key || gateway.getId();\n const gateways = this.#gateways as Record<string, MastraModelGateway>;\n if (gateways[gatewayKey]) {\n const logger = this.getLogger();\n logger.debug(`Gateway with key ${gatewayKey} already exists. Skipping addition.`);\n return;\n }\n\n gateways[gatewayKey] = gateway;\n\n // Register custom gateways with the registry for type generation\n this.#syncGatewayRegistry();\n }\n\n /**\n * Sync custom gateways with the GatewayRegistry for type generation\n * @private\n */\n #syncGatewayRegistry(): void {\n try {\n // Only sync in dev mode (when MASTRA_DEV is set)\n if (process.env.MASTRA_DEV !== 'true' && process.env.MASTRA_DEV !== '1') {\n return;\n }\n\n // Trigger sync immediately (non-blocking, but logs progress)\n import('../llm/model/provider-registry.js')\n .then(async ({ GatewayRegistry }) => {\n const registry = GatewayRegistry.getInstance();\n const customGateways = Object.values(this.#gateways || {});\n registry.registerCustomGateways(customGateways);\n\n // Log that we're syncing\n const logger = this.getLogger();\n logger.info('🔄 Syncing custom gateway types...');\n\n // Trigger a sync to regenerate types\n await registry.syncGateways(true);\n\n logger.info('✅ Custom gateway types synced! Restart your TypeScript server to see autocomplete.');\n })\n .catch(err => {\n const logger = this.getLogger();\n logger.debug('Gateway registry sync skipped:', err);\n });\n } catch (err) {\n // Silent fail - this is a dev-only feature\n const logger = this.getLogger();\n logger.debug('Gateway registry sync failed:', err);\n }\n }\n\n /**\n * Gracefully shuts down the Mastra instance and cleans up all resources.\n *\n * This method performs a clean shutdown of all Mastra components, including:\n * - tracing registry and all tracing instances\n * - Event engine and pub/sub system\n * - All registered components and their resources\n *\n * It's important to call this method when your application is shutting down\n * to ensure proper cleanup and prevent resource leaks.\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * agents: { myAgent },\n * workflows: { myWorkflow }\n * });\n *\n * // Graceful shutdown on SIGINT\n * process.on('SIGINT', async () => {\n * await mastra.shutdown();\n * process.exit(0);\n * });\n * ```\n */\n async shutdown(): Promise<void> {\n await this.stopEventEngine();\n // Shutdown observability registry, exporters, etc...\n await this.#observability.shutdown();\n\n this.#logger?.info('Mastra shutdown completed');\n }\n\n // This method is only used internally for server hnadlers that require temporary persistence\n public get serverCache() {\n return this.#serverCache;\n }\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/observability/types/tracing.ts","../src/observability/no-op.ts","../src/observability/utils.ts","../src/observability/context.ts"],"names":["SpanType","InternalSpans","SamplingStrategyType","TracingEventType"],"mappings":";AAgBO,IAAK,QAAA,qBAAAA,SAAAA,KAAL;AAEL,EAAAA,UAAA,WAAA,CAAA,GAAY,WAAA;AAEZ,EAAAA,UAAA,SAAA,CAAA,GAAU,SAAA;AAEV,EAAAA,UAAA,kBAAA,CAAA,GAAmB,kBAAA;AAEnB,EAAAA,UAAA,YAAA,CAAA,GAAa,YAAA;AAEb,EAAAA,UAAA,aAAA,CAAA,GAAc,aAAA;AAEd,EAAAA,UAAA,eAAA,CAAA,GAAgB,eAAA;AAEhB,EAAAA,UAAA,eAAA,CAAA,GAAgB,eAAA;AAEhB,EAAAA,UAAA,WAAA,CAAA,GAAY,WAAA;AAEZ,EAAAA,UAAA,cAAA,CAAA,GAAe,cAAA;AAEf,EAAAA,UAAA,eAAA,CAAA,GAAgB,eAAA;AAEhB,EAAAA,UAAA,sBAAA,CAAA,GAAuB,sBAAA;AAEvB,EAAAA,UAAA,2BAAA,CAAA,GAA4B,2BAAA;AAE5B,EAAAA,UAAA,mBAAA,CAAA,GAAoB,mBAAA;AAEpB,EAAAA,UAAA,eAAA,CAAA,GAAgB,eAAA;AAEhB,EAAAA,UAAA,gBAAA,CAAA,GAAiB,gBAAA;AAEjB,EAAAA,UAAA,qBAAA,CAAA,GAAsB,qBAAA;AAhCZ,EAAA,OAAAA,SAAAA;AAAA,CAAA,EAAA,QAAA,IAAA,EAAA;AA+sBL,IAAK,aAAA,qBAAAC,cAAAA,KAAL;AAEL,EAAAA,cAAAA,CAAAA,cAAAA,CAAA,UAAO,CAAA,CAAA,GAAP,MAAA;AAEA,EAAAA,cAAAA,CAAAA,cAAAA,CAAA,cAAW,CAAA,CAAA,GAAX,UAAA;AAEA,EAAAA,cAAAA,CAAAA,cAAAA,CAAA,WAAQ,CAAA,CAAA,GAAR,OAAA;AAEA,EAAAA,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faces\n */\nimport type { MastraError } from '../../error';\nimport type { IMastraLogger } from '../../logger';\nimport type { Mastra } from '../../mastra';\nimport type { RequestContext } from '../../request-context';\nimport type { WorkflowRunStatus, WorkflowStepStatus } from '../../workflows';\n\n// ============================================================================\n// Span Types\n// ============================================================================\n\n/**\n * AI-specific span types with their associated metadata\n */\nexport enum SpanType {\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 /** Human-readable agent name */\n agentName?: string;\n /** Conversation/thread/session identifier for multi-turn interactions */\n conversationId?: 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 * When the first token/chunk of the completion was received.\n * Used to calculate time-to-first-token (TTFT) metrics.\n * Only applicable for streaming responses.\n */\n completionStartTime?: Date;\n /** Actual model used in the response (may differ from request model) */\n responseModel?: string;\n /** Unique identifier for the response */\n responseId?: string;\n /** Server address for the model endpoint */\n serverAddress?: string;\n /** Server port for the model endpoint */\n serverPort?: number;\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 /** MessageList mutations performed by this processor */\n messageListMutations?: Array<{\n type: 'add' | 'addSystem' | 'removeByIds' | 'clear';\n source?: string;\n count?: number;\n ids?: string[];\n text?: string;\n tag?: string;\n message?: any;\n }>;\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 SpanTypeMap {\n [SpanType.AGENT_RUN]: AgentRunAttributes;\n [SpanType.WORKFLOW_RUN]: WorkflowRunAttributes;\n [SpanType.MODEL_GENERATION]: ModelGenerationAttributes;\n [SpanType.MODEL_STEP]: ModelStepAttributes;\n [SpanType.MODEL_CHUNK]: ModelChunkAttributes;\n [SpanType.TOOL_CALL]: ToolCallAttributes;\n [SpanType.MCP_TOOL_CALL]: MCPToolCallAttributes;\n [SpanType.PROCESSOR_RUN]: ProcessorRunAttributes;\n [SpanType.WORKFLOW_STEP]: WorkflowStepAttributes;\n [SpanType.WORKFLOW_CONDITIONAL]: WorkflowConditionalAttributes;\n [SpanType.WORKFLOW_CONDITIONAL_EVAL]: WorkflowConditionalEvalAttributes;\n [SpanType.WORKFLOW_PARALLEL]: WorkflowParallelAttributes;\n [SpanType.WORKFLOW_LOOP]: WorkflowLoopAttributes;\n [SpanType.WORKFLOW_SLEEP]: WorkflowSleepAttributes;\n [SpanType.WORKFLOW_WAIT_EVENT]: WorkflowWaitEventAttributes;\n [SpanType.GENERIC]: AIBaseAttributes;\n}\n\n/**\n * Union type for cases that need to handle any span type\n */\nexport type AnySpanAttributes = SpanTypeMap[keyof SpanTypeMap];\n\n// ============================================================================\n// Span Interfaces\n// ============================================================================\n\n/**\n * Base Span interface\n */\ninterface BaseSpan<TType extends SpanType> {\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 /** Span-type specific attributes */\n attributes?: SpanTypeMap[TType];\n /** User-defined metadata */\n metadata?: Record<string, any>;\n /** Labels used to categorize and filter traces. Only valid on root spans. */\n tags?: string[];\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 * Span interface, used internally for tracing\n */\nexport interface Span<TType extends SpanType> 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?: AnySpan;\n /** Pointer to the ObservabilityInstance instance */\n observabilityInstance: ObservabilityInstance;\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(options: ChildSpanOptions<SpanType.MODEL_GENERATION>): AIModelGenerationSpan;\n createChildSpan<TChildType extends SpanType>(options: ChildSpanOptions<TChildType>): Span<TChildType>;\n\n /** Create event span - can be any span type independent of parent */\n createEventSpan<TChildType extends SpanType>(options: ChildEventOptions<TChildType>): Span<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 SpanType>(spanType: T): Span<T> | undefined;\n\n /** Returns a lightweight span ready for export */\n exportSpan(includeInternalSpans?: boolean): ExportedSpan<TType> | undefined;\n\n /** Returns the traceId on span, unless NoOpSpan, then undefined */\n get externalTraceId(): string | undefined;\n\n /**\n * Execute an async function within this span's tracing context.\n *\n * When a bridge is configured, this enables auto-instrumented operations\n * (HTTP requests, database queries, etc.) to be properly nested under this\n * span in the external tracing system.\n *\n * @param fn - The async function to execute within the span context\n * @returns The result of the function execution\n *\n * @example\n * ```typescript\n * const result = await modelSpan.executeInContext(async () => {\n * return model.generateText(...);\n * });\n * ```\n */\n executeInContext<T>(fn: () => Promise<T>): Promise<T>;\n\n /**\n * Execute a synchronous function within this span's tracing context.\n *\n * When a bridge is configured, this enables auto-instrumented operations\n * (HTTP requests, database queries, etc.) to be properly nested under this\n * span in the external tracing system.\n *\n * @param fn - The synchronous function to execute within the span context\n * @returns The result of the function execution\n *\n * @example\n * ```typescript\n * const result = modelSpan.executeInContextSync(() => {\n * return model.streamText(...);\n * });\n * ```\n */\n executeInContextSync<T>(fn: () => T): T;\n}\n\nexport interface BridgeSpanContext {\n /**\n * Execute an async function within this span's tracing context.\n *\n * When a bridge is configured, this enables auto-instrumented operations\n * (HTTP requests, database queries, etc.) to be properly nested under this\n * span in the external tracing system.\n *\n * @param fn - The async function to execute within the span context\n * @returns The result of the function execution\n *\n * @example\n * ```typescript\n * const result = await modelSpan.executeInContext(async () => {\n * return model.generateText(...);\n * });\n * ```\n */\n executeInContext<T>(fn: () => Promise<T>): Promise<T>;\n\n /**\n * Execute a synchronous function within this span's tracing context.\n *\n * When a bridge is configured, this enables auto-instrumented operations\n * (HTTP requests, database queries, etc.) to be properly nested under this\n * span in the external tracing system.\n *\n * @param fn - The synchronous function to execute within the span context\n * @returns The result of the function execution\n *\n * @example\n * ```typescript\n * const result = modelSpan.executeInContextSync(() => {\n * return model.streamText(...);\n * });\n * ```\n */\n executeInContextSync<T>(fn: () => T): T;\n}\n\n/**\n * Specialized span interface for MODEL_GENERATION spans\n * Provides access to creating a ModelSpanTracker for tracking MODEL_STEP and MODEL_CHUNK spans\n */\nexport interface AIModelGenerationSpan extends Span<SpanType.MODEL_GENERATION> {\n /** Create a ModelSpanTracker for tracking model execution steps and chunks */\n createTracker(): IModelSpanTracker | undefined;\n}\n\n/**\n * Exported Span interface, used for tracing exporters\n */\nexport interface ExportedSpan<TType extends SpanType> 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 * Tags for this trace (only present on root spans).\n * Tags are string labels used to categorize and filter traces.\n */\n tags?: string[];\n}\n\nexport interface IModelSpanTracker {\n getTracingContext(): TracingContext;\n reportGenerationError(options: ErrorSpanOptions<SpanType.MODEL_GENERATION>): void;\n endGeneration(options?: EndSpanOptions<SpanType.MODEL_GENERATION>): void;\n wrapStream<T extends { pipeThrough: Function }>(stream: T): T;\n}\n\n/**\n * Union type for cases that need to handle any span\n */\nexport type AnySpan = Span<keyof SpanTypeMap>;\n\n/**\n * Union type for cases that need to handle any exported span\n */\nexport type AnyExportedSpan = ExportedSpan<keyof SpanTypeMap>;\n\n// ============================================================================\n// Tracing Interfaces\n// ============================================================================\n\n/**\n * Primary interface for Observability\n */\nexport interface ObservabilityInstance {\n /**\n * Get current configuration\n */\n getConfig(): Readonly<ObservabilityInstanceConfig>;\n\n /**\n * Get all exporters\n */\n getExporters(): readonly ObservabilityExporter[];\n\n /**\n * Get all span output processors\n */\n getSpanOutputProcessors(): readonly SpanOutputProcessor[];\n\n /**\n * Get the logger instance (for exporters and other components)\n */\n getLogger(): IMastraLogger;\n\n /**\n * Get the bridge instance if configured\n */\n getBridge(): ObservabilityBridge | undefined;\n\n /**\n * Start a new span of a specific SpanType\n */\n startSpan<TType extends SpanType>(options: StartSpanOptions<TType>): Span<TType>;\n\n /**\n * Shutdown tracing and clean up resources\n */\n shutdown(): Promise<void>;\n\n /**\n * Override setLogger to add 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 SpanType> {\n /** Span attributes */\n attributes?: SpanTypeMap[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 /** Request Context for metadata extraction */\n requestContext?: RequestContext;\n}\n\n/**\n * Options for creating new spans\n */\nexport interface CreateSpanOptions<TType extends SpanType> extends CreateBaseOptions<TType> {\n /** Input data */\n input?: any;\n /** Output data (for event spans) */\n output?: any;\n /** Labels used to categorize and filter traces. Only valid on root spans. */\n tags?: string[];\n /** Parent span */\n parent?: AnySpan;\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 SpanType> 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 SpanType> 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 SpanType> extends CreateBaseOptions<TType> {\n /** Output data */\n output?: any;\n}\n\ninterface UpdateBaseOptions<TType extends SpanType> {\n /** Span attributes */\n attributes?: Partial<SpanTypeMap[TType]>;\n /** Span metadata */\n metadata?: Record<string, any>;\n}\n\nexport interface EndSpanOptions<TType extends SpanType> extends UpdateBaseOptions<TType> {\n /** Output data */\n output?: any;\n}\n\nexport interface UpdateSpanOptions<TType extends SpanType> extends UpdateBaseOptions<TType> {\n /** Input data */\n input?: any;\n /** Output data */\n output?: any;\n}\n\nexport interface ErrorSpanOptions<TType extends SpanType> 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\nexport interface GetOrCreateSpanOptions<TType extends SpanType> {\n type: TType;\n name: string;\n input?: any;\n attributes?: SpanTypeMap[TType];\n metadata?: Record<string, any>;\n tracingPolicy?: TracingPolicy;\n tracingOptions?: TracingOptions;\n tracingContext?: TracingContext;\n requestContext?: RequestContext;\n mastra?: Mastra;\n}\n\n// ============================================================================\n// Lifecycle Types\n// ============================================================================\n\nexport interface ObservabilityEntrypoint {\n shutdown(): Promise<void>;\n\n setMastraContext(options: { mastra: Mastra }): void;\n\n setLogger(options: { logger: IMastraLogger }): void;\n\n getSelectedInstance(options: ConfigSelectorOptions): ObservabilityInstance | undefined;\n\n // Registry management methods\n registerInstance(name: string, instance: ObservabilityInstance, isDefault?: boolean): void;\n getInstance(name: string): ObservabilityInstance | undefined;\n getDefaultInstance(): ObservabilityInstance | undefined;\n listInstances(): ReadonlyMap<string, ObservabilityInstance>;\n unregisterInstance(name: string): boolean;\n hasInstance(name: string): boolean;\n setConfigSelector(selector: ConfigSelector): void;\n clear(): void;\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 * RequestContext keys to extract as metadata for all spans in this trace.\n * Computed by merging the tracing config's requestContextKeys\n * with the per-request requestContextKeys.\n */\n requestContextKeys: 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 RequestContext keys to extract as metadata for this trace.\n * These keys are added to the requestContextKeys config.\n * Supports dot notation for nested values (e.g., 'user.id', 'session.data.experimentId').\n */\n requestContextKeys?: 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 * Tags to apply to this trace.\n * Tags are string labels that can be used to categorize and filter traces\n * Note: Tags are only applied to the root span of a trace.\n */\n tags?: string[];\n}\n\nexport interface SpanIds {\n traceId: string;\n spanId: string;\n parentSpanId?: string;\n}\n\n/**\n * Context for tracing that flows through workflow and agent execution\n */\nexport interface TracingContext {\n /** Current Span for creating child spans and adding metadata */\n currentSpan?: AnySpan;\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 observability instance\n */\nexport interface ObservabilityInstanceConfig {\n /** Unique identifier for this config in the observability registry */\n name: string;\n /** Service name for observability */\n serviceName: string;\n /** Sampling strategy - controls whether tracing is collected (defaults to ALWAYS) */\n sampling?: SamplingStrategy;\n /** Custom exporters */\n exporters?: ObservabilityExporter[];\n /** Custom processors */\n spanOutputProcessors?: SpanOutputProcessor[];\n /** OpenTelemetry bridge for integration with existing OTEL infrastructure */\n bridge?: ObservabilityBridge;\n /** Set to `true` if you want to see spans internal to the operation of mastra */\n includeInternalSpans?: boolean;\n /**\n * RequestContext keys to automatically extract as metadata for all spans\n * created with this observablity configuration.\n * Supports dot notation for nested values.\n */\n requestContextKeys?: string[];\n}\n\n/**\n * Complete Observability 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<ObservabilityInstanceConfig, 'name'> | ObservabilityInstance>;\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 requestContext?: RequestContext;\n metadata?: Record<string, any>;\n}\n\n// ============================================================================\n// Exporter and Processor Interfaces\n// ============================================================================\n\n/**\n * Tracing event types\n */\nexport enum TracingEventType {\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 TracingEvent =\n | { type: TracingEventType.SPAN_STARTED; exportedSpan: AnyExportedSpan }\n | { type: TracingEventType.SPAN_UPDATED; exportedSpan: AnyExportedSpan }\n | { type: TracingEventType.SPAN_ENDED; exportedSpan: AnyExportedSpan };\n\nexport interface InitExporterOptions {\n mastra?: Mastra;\n config?: ObservabilityInstanceConfig;\n}\n\nexport interface InitBridgeOptions {\n mastra?: Mastra;\n config?: ObservabilityInstanceConfig;\n}\n\n/**\n * Interface for tracing exporters\n */\nexport interface ObservabilityExporter {\n /** Exporter name */\n name: string;\n\n /** Initialize exporter with tracing configuration and/or access to Mastra */\n init?(options: InitExporterOptions): void;\n\n /** Sets logger instance on the exporter. */\n __setLogger?(logger: IMastraLogger): void;\n\n /** Export tracing events */\n exportTracingEvent(event: TracingEvent): 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 observability bridges\n */\nexport interface ObservabilityBridge {\n /** Bridge name */\n name: string;\n\n /** Initialize bridge with observability configuration and/or access to Mastra */\n init?(options: InitBridgeOptions): void;\n\n /** Sets logger instance on the bridge */\n __setLogger?(logger: IMastraLogger): void;\n\n /**\n * Export Mastra tracing events to OTEL infrastructure\n * Called for SPAN_STARTED, SPAN_UPDATED, SPAN_ENDED events\n *\n * @param event - Tracing event with exported span\n */\n exportTracingEvent(event: TracingEvent): Promise<void>;\n\n /**\n * Execute an async function within the tracing context of a Mastra span.\n * This enables auto-instrumented operations (HTTP, DB) to have correct parent spans\n * in the external tracing system (e.g., OpenTelemetry, DataDog, etc.).\n *\n * @param spanId - The ID of the Mastra span to use as context\n * @param fn - The async function to execute within the span context\n * @returns The result of the function execution\n */\n executeInContext?<T>(spanId: string, fn: () => Promise<T>): Promise<T>;\n\n /**\n * Execute a synchronous function within the tracing context of a Mastra span.\n * This enables auto-instrumented operations (HTTP, DB) to have correct parent spans\n * in the external tracing system (e.g., OpenTelemetry, DataDog, etc.).\n *\n * @param spanId - The ID of the Mastra span to use as context\n * @param fn - The synchronous function to execute within the span context\n * @returns The result of the function execution\n */\n executeInContextSync?<T>(spanId: string, fn: () => T): T;\n\n /**\n * Create a span in the bridge's tracing system.\n * Called during Mastra span construction to get bridge-generated identifiers.\n *\n * @param options - Span creation options from Mastra\n * @returns Span identifiers (spanId, traceId, parentSpanId) from bridge, or undefined if creation fails\n */\n createSpan(options: CreateSpanOptions<SpanType>): SpanIds | undefined;\n\n /** Shutdown bridge and cleanup resources */\n shutdown(): Promise<void>;\n}\n\n/**\n * Interface for span processors\n */\nexport interface SpanOutputProcessor {\n /** Processor name */\n name: string;\n /** Process span before export */\n process(span?: AnySpan): AnySpan | 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 /** Request Context */\n requestContext?: RequestContext;\n}\n\n/**\n * Function to select which 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, ObservabilityInstance>,\n) => string | undefined;\n\n// ============================================================================\n// Tracing Storage Interfaces\n// ============================================================================\n\nexport type TracingStorageStrategy = 'realtime' | 'batch-with-updates' | 'insert-only';\n","import type { Mastra } from '..';\nimport type { IMastraLogger } from '../logger';\nimport type { ObservabilityInstance, ConfigSelectorOptions, ObservabilityEntrypoint, ConfigSelector } from './types';\n\nexport class NoOpObservability implements ObservabilityEntrypoint {\n setMastraContext(_options: { mastra: Mastra }): void {\n return;\n }\n\n setLogger(_options: { logger: IMastraLogger }): void {\n return;\n }\n\n getSelectedInstance(_options: ConfigSelectorOptions): ObservabilityInstance | undefined {\n return;\n }\n\n registerInstance(_name: string, _instance: ObservabilityInstance, _isDefault = false): void {\n return;\n }\n\n getInstance(_name: string): ObservabilityInstance | undefined {\n return;\n }\n\n getDefaultInstance(): ObservabilityInstance | undefined {\n return;\n }\n\n listInstances(): ReadonlyMap<string, ObservabilityInstance> {\n return new Map();\n }\n\n unregisterInstance(_name: string): boolean {\n return false;\n }\n\n hasInstance(_name: string): boolean {\n return false;\n }\n\n setConfigSelector(_selector: ConfigSelector): void {\n return;\n }\n\n clear(): void {\n return;\n }\n\n async shutdown(): Promise<void> {\n return;\n }\n}\n","import type { Span, SpanType, GetOrCreateSpanOptions, AnySpan } from './types';\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 Span or undefined if tracing is disabled\n */\nexport function getOrCreateSpan<T extends SpanType>(options: GetOrCreateSpanOptions<T>): Span<T> | undefined {\n const { type, attributes, tracingContext, requestContext, 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 instance = options.mastra?.observability?.getSelectedInstance({ requestContext });\n\n return instance?.startSpan<T>({\n type,\n attributes,\n ...rest,\n metadata,\n requestContext,\n tracingOptions,\n traceId: tracingOptions?.traceId,\n parentSpanId: tracingOptions?.parentSpanId,\n customSamplerOptions: {\n requestContext,\n metadata,\n },\n });\n}\n\n/**\n * Execute an async function within the span's tracing context if available.\n * Falls back to direct execution if no span exists.\n *\n * When a bridge is configured, this enables auto-instrumented operations\n * (HTTP requests, database queries, etc.) to be properly nested under the\n * current span in the external tracing system.\n *\n * @param span - The span to use as context (or undefined to execute without context)\n * @param fn - The async function to execute\n * @returns The result of the function execution\n *\n * @example\n * ```typescript\n * const result = await executeWithContext(llmSpan, async () =>\n * model.generateText(args)\n * );\n * ```\n */\nexport async function executeWithContext<T>(params: { span?: AnySpan; fn: () => Promise<T> }): Promise<T> {\n const { span, fn } = params;\n\n if (span?.executeInContext) {\n return span.executeInContext(fn);\n }\n\n return fn();\n}\n\n/**\n * Execute a synchronous function within the span's tracing context if available.\n * Falls back to direct execution if no span exists.\n *\n * When a bridge is configured, this enables auto-instrumented operations\n * (HTTP requests, database queries, etc.) to be properly nested under the\n * current span in the external tracing system.\n *\n * @param span - The span to use as context (or undefined to execute without context)\n * @param fn - The synchronous function to execute\n * @returns The result of the function execution\n *\n * @example\n * ```typescript\n * const result = executeWithContextSync(llmSpan, () =>\n * model.streamText(args)\n * );\n * ```\n */\nexport function executeWithContextSync<T>(params: { span?: AnySpan; fn: () => T }): T {\n const { span, fn } = params;\n\n if (span?.executeInContextSync) {\n return span.executeInContextSync(fn);\n }\n\n return fn();\n}\n","/**\n * Tracing Context Integration\n *\n * This module provides automatic 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, AnySpan } 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', 'createRun'];\n\n/**\n * Helper function to detect NoOp spans to avoid unnecessary wrapping\n */\nfunction isNoOpSpan(span: AnySpan): boolean {\n // Check if this is a NoOp span implementation\n return span.constructor.name === 'NoOpSpan' || (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 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 * 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('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('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 * 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('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('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 * 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 createRun methods differently\n if (prop === 'createRun' || prop === 'createRun') {\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('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('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 * 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('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('Tracing: Failed to create run proxy, using original instance', error);\n return run;\n }\n}\n"]}