UNPKG

@mastra/core

Version:
1 lines 54.4 kB
{"version":3,"file":"tracing-BUrUJwCM.cjs","names":[],"sources":["../src/observability/types/tracing.ts"],"sourcesContent":["/**\n * Tracing interfaces\n *\n * Span types, attributes, span lifecycle, and tracing-specific types.\n * For top-level observability infrastructure (instances, exporters, bridges, config),\n * see observability.ts.\n */\nimport { EntityType } from '@internal/core/storage';\n\nimport type { MastraError } from '../../error';\nimport type { Mastra } from '../../mastra';\nimport type { RequestContext } from '../../request-context';\nimport type { LanguageModelUsage, ProviderMetadata, StepStartPayload } from '../../stream/types';\nimport type { WorkflowRunStatus, WorkflowStepStatus } from '../../workflows';\nimport type {\n CustomSamplerOptions,\n ObservabilityInstance,\n CorrelationContext,\n DefinitionSource,\n ScorerScoreSource,\n ScorerStepType,\n ScorerTargetScope,\n} from './core';\nimport type { FeedbackInput } from './feedback';\nimport type { CostContext } from './metrics';\nimport type { ScoreInput } from './scores';\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 /** Scorer execution */\n SCORER_RUN = 'scorer_run',\n /** Individual scorer pipeline step */\n SCORER_STEP = 'scorer_step',\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 /** Model provider call within a step - wraps only the inference, excluding processors and tool executions */\n MODEL_INFERENCE = 'model_inference',\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 /**\n * Client-side tool execution marker. The server creates this span\n * when the model emits a client tool call, injects its W3C carrier\n * into the outgoing tool-call chunk, then ends the span once tool\n * args are available. Child spans/logs from inside the client tool's\n * execute function flow back as OTLP/JSON via the ClientObservabilityProxy\n * interface in @mastra/observability and parent themselves under this\n * span via parentSpanId reference.\n */\n CLIENT_TOOL_CALL = 'client_tool_call',\n /**\n * Provider-executed (server-side) tool span. Reconstructed from\n * tool-call and tool-result stream chunks for tools the model\n * provider executes (e.g. Anthropic code execution, server-side\n * web search). Created on the tool-result chunk under the model\n * step that delivered it, with the start time backdated to the\n * tool-call chunk.\n */\n PROVIDER_TOOL_CALL = 'provider_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 /** Memory operation (recall, save, delete, update working memory) */\n MEMORY_OPERATION = 'memory_operation',\n /** Workspace action (filesystem, sandbox, search, skill, mount operations) */\n WORKSPACE_ACTION = 'workspace_action',\n /** RAG ingestion - root span for an ingestion pipeline run (load → chunk → extract → embed → upsert) */\n RAG_INGESTION = 'rag_ingestion',\n /** Embedding call (used by both RAG ingestion and query) */\n RAG_EMBEDDING = 'rag_embedding',\n /** Vector store I/O (query / upsert / delete / fetch) */\n RAG_VECTOR_OPERATION = 'rag_vector_operation',\n /** RAG-specific actions: chunk, extract_metadata, rerank */\n RAG_ACTION = 'rag_action',\n /** Graph operations (build / traverse) - not RAG-specific */\n GRAPH_ACTION = 'graph_action',\n /** Inline data mapping between pipeline stages (e.g. a tool's `toModelOutput` transform) */\n MAPPING = 'mapping',\n}\n\nexport { EntityType };\n\n// ============================================================================\n// Type-Specific Attributes Interfaces\n// ============================================================================\n\n/**\n * Base attributes that all spans can have\n */\nexport interface AIBaseAttributes {\n /**\n * Token usage rolled up from internal descendant spans whose own\n * MODEL_GENERATION spans are filtered from the exported trace (e.g.\n * Mastra-owned processors that run with `tracingPolicy.internal`).\n *\n * Accumulated on the closest exported ancestor at descendant-end time,\n * so cost / token attribution survives even when the descendant model\n * spans themselves are hidden. Token-usage metrics auto-extract from\n * this field on the ancestor when present.\n */\n internalUsage?: UsageStats;\n}\n\n/**\n * Agent Run attributes\n */\nexport interface AgentRunAttributes extends AIBaseAttributes {\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 /** The resolved agent version ID used for this execution */\n resolvedVersionId?: string;\n /** Tripwire abort details when a processor triggered a tripwire */\n tripwireAbort?: {\n /** Abort reason */\n reason?: string;\n /** Processor that triggered the tripwire */\n processorId?: string;\n /** Whether retry was requested */\n retry?: boolean;\n /** Additional metadata */\n metadata?: unknown;\n };\n}\n\n/**\n * Scorer Run attributes\n */\nexport interface ScorerRunAttributes extends AIBaseAttributes {\n scorerId?: string;\n scorerName?: string;\n scoreSource?: ScorerScoreSource;\n targetScope?: ScorerTargetScope;\n targetEntityType?: EntityType;\n scorerDefinition?: DefinitionSource;\n}\n\n/**\n * Scorer Step attributes\n */\nexport interface ScorerStepAttributes extends AIBaseAttributes {\n step?: string;\n stepType?: ScorerStepType;\n prompt?: string;\n judgeModel?: string;\n}\n\n/**\n * Detailed breakdown of input token usage by type.\n * Based on OpenInference semantic conventions.\n */\nexport interface InputTokenDetails {\n /** Regular text tokens (non-cached, non-audio, non-image) */\n text?: number;\n /** Tokens served from cache (cache hit/read) */\n cacheRead?: number;\n /** Tokens written to cache (cache creation - Anthropic only) */\n cacheWrite?: number;\n /** Audio input tokens */\n audio?: number;\n /** Image input tokens (includes PDF pages) */\n image?: number;\n}\n\n/**\n * Detailed breakdown of output token usage by type.\n * Based on OpenInference semantic conventions.\n */\nexport interface OutputTokenDetails {\n /** Regular text output tokens */\n text?: number;\n /** Reasoning/thinking tokens (o1, Claude thinking, Gemini thoughts) */\n reasoning?: number;\n /** Audio output tokens */\n audio?: number;\n /** Image output tokens (DALL-E, etc.) */\n image?: number;\n}\n\n/** Token usage statistics */\nexport interface UsageStats {\n /** Total input tokens (sum of all input details) */\n inputTokens?: number;\n /** Total output tokens (sum of all output details) */\n outputTokens?: number;\n /** Detailed breakdown of input token usage */\n inputDetails?: InputTokenDetails;\n /** Detailed breakdown of output token usage */\n outputDetails?: OutputTokenDetails;\n}\n\n/**\n * Serialized definition of one tool made available to the model, in the\n * provider-agnostic form sent on the wire. Attached to MODEL_GENERATION\n * spans so observability exporters can surface tool schemas (e.g. PostHog\n * `$ai_tools`, OpenInference `llm.tools.*`).\n */\nexport interface ModelToolDefinition {\n /** Tool type: 'function' for standard tools, or the provider tool type (e.g. 'provider-defined') */\n type: string;\n name: string;\n description?: string;\n /** JSON schema of the tool's input parameters (function tools) */\n parameters?: Record<string, unknown>;\n /** Provider tool id (e.g. 'anthropic.web_search_20250305') for provider-defined tools */\n id?: string;\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 /**\n * Definitions of the tools made available to the model for this generation,\n * captured once per generation. Per-step tool names (after `activeTools`\n * filtering) live on MODEL_INFERENCE spans as `availableTools`.\n */\n tools?: ModelToolDefinition[];\n /** Type of result/output this LLM call produced */\n resultType?: 'tool_selection' | 'response_generation' | 'reasoning' | 'planning';\n /** Token usage statistics */\n usage?: UsageStats;\n /** Estimated cost context, when provided directly by an SDK or provider */\n costContext?: CostContext;\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 Inference attributes - for the provider call within a MODEL_STEP.\n *\n * Wraps only the model's inference (HTTP roundtrip / stream lifetime),\n * excluding input/output processors and tool executions. Use this span\n * to measure pure model latency.\n *\n * Fields are intentionally duplicated from ModelStepAttributes /\n * ModelGenerationAttributes so existing integrations that read those\n * attributes continue to work unchanged.\n */\nexport interface ModelInferenceAttributes 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 /** Index of the parent step in the generation (0, 1, 2, ...) */\n stepIndex?: number;\n /** Token usage statistics */\n usage?: UsageStats;\n /** Reason this inference finished (stop, tool-calls, length, etc.) */\n finishReason?: string;\n /** Whether this was a streaming response */\n streaming?: boolean;\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 /** Result warnings */\n warnings?: Record<string, any>;\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 /** Model parameters sent on the request (temperature, maxOutputTokens, topP, etc.) */\n parameters?: Record<string, unknown>;\n /** Provider-specific options forwarded on the request */\n providerOptions?: Record<string, unknown>;\n /** Names of tools made available to the model on this inference call */\n availableTools?: string[];\n /**\n * How the model was instructed to choose tools: 'auto', 'none', 'required',\n * or a specific tool selection. Distinguishes \"model could have called a\n * tool but didn't\" from \"model was blocked/forced\".\n */\n toolChoice?: 'auto' | 'none' | 'required' | { type: 'tool'; toolName: string };\n /**\n * Requested response format. Distinguishes plain text generation from\n * structured-output (JSON / JSON schema) runs.\n */\n responseFormat?: 'text' | 'json' | 'json_schema' | { type: string; name?: string };\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 toolType?: string;\n toolDescription?: string;\n toolCallId?: string;\n success?: boolean;\n}\n\n/**\n * Client Tool Call attributes.\n *\n * CLIENT_TOOL_CALL is a server-side marker span for a tool call that\n * will execute in the client SDK. It is created early so its W3C\n * carrier can be sent to the client, then ended once tool args are\n * available. Richer telemetry from inside the client tool's execute\n * function (child spans, logs) is forwarded back via the\n * ClientObservabilityProxy interface in @mastra/observability and\n * parented under this span via parentSpanId reference.\n */\nexport interface ClientToolCallAttributes extends AIBaseAttributes {\n /** Tool category, e.g. 'tool', 'function' */\n toolType?: string;\n /** Tool description from createTool */\n toolDescription?: string;\n /** Optional environment hint reported by the client (browser, node, deno, etc.) */\n clientEnvironment?: string;\n}\n\n/**\n * Provider Tool Call attributes.\n *\n * PROVIDER_TOOL_CALL is a synthetic span reconstructed from stream\n * chunks for tools executed by the model provider (e.g. Anthropic\n * code execution, server-side web search). The span is opened on\n * the tool-call chunk and closed on the paired tool-result chunk.\n */\nexport interface ProviderToolCallAttributes extends AIBaseAttributes {\n /** Tool category: 'provider-tool' */\n toolType?: string;\n /** Tool description from tool definition */\n toolDescription?: string;\n /** Provider tool call ID (e.g. 'srvtoolu_...') */\n toolCallId?: string;\n /** Whether the provider reported success or error */\n success?: boolean;\n}\n\n/**\n * MCP Tool Call attributes\n */\nexport interface MCPToolCallAttributes extends AIBaseAttributes {\n /** MCP server identifier */\n mcpServer: string;\n /** MCP server version */\n serverVersion?: string;\n /** Tool description */\n toolDescription?: string;\n toolCallId?: string;\n /** Whether tool execution was successful */\n success?: boolean;\n}\n\n/**\n * Mapping attributes — for inline data transforms between pipeline stages\n * (e.g. a tool's `toModelOutput` reshaping the tool result before the model sees it).\n */\nexport interface MappingAttributes extends AIBaseAttributes {\n /** Identifier of the mapping (e.g. `toModelOutput`) so UIs can group related mappings */\n mappingType?: string;\n /** Associated tool call id when the mapping operates on a tool result */\n toolCallId?: string;\n}\n\n/**\n * Processor attributes\n */\nexport interface ProcessorRunAttributes extends AIBaseAttributes {\n /** Processor executor type (workflow or legacy) */\n processorExecutor?: 'workflow' | 'legacy';\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 /** Tripwire abort details when a processor triggered a tripwire */\n tripwireAbort?: {\n /** Abort reason */\n reason?: string;\n /** Whether retry was requested */\n retry?: boolean;\n /** Additional metadata */\n metadata?: unknown;\n };\n}\n\n/**\n * Workflow Run attributes\n */\nexport interface WorkflowRunAttributes extends AIBaseAttributes {\n /** Workflow status */\n status?: WorkflowRunStatus;\n}\n\n/**\n * Workflow Step attributes\n */\nexport interface WorkflowStepAttributes extends AIBaseAttributes {\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 * Memory operation attributes\n */\nexport interface MemoryOperationAttributes extends AIBaseAttributes {\n operationType?: 'recall' | 'save' | 'delete' | 'update';\n messageCount?: number;\n embeddingTokens?: number;\n semanticRecallEnabled?: boolean;\n vectorResultCount?: number;\n workingMemoryEnabled?: boolean;\n lastMessages?: number | false;\n}\n\n/**\n * Workspace Action attributes — metadata about the span context.\n * Operation-specific inputs/outputs are recorded via span input/output,\n * not as attributes.\n */\nexport interface WorkspaceActionAttributes extends AIBaseAttributes {\n /** Workspace identifier */\n workspaceId?: string;\n /** Human-readable workspace name */\n workspaceName?: string;\n /** Action category */\n category: 'filesystem' | 'sandbox' | 'search' | 'skill' | 'mount';\n /** Sandbox provider name (e.g. 'e2b', 'docker', 'local') */\n sandboxProvider?: string;\n /** Filesystem provider name (e.g. 'local', 'agentfs', 's3') */\n filesystemProvider?: string;\n /** Whether the operation succeeded */\n success?: boolean;\n}\n\n/**\n * RAG Ingestion attributes (root span for an ingestion pipeline run).\n *\n * Attributes are stable, low-cardinality dimensions describing the run.\n * Per-run results (final chunk count, etc.) belong on the span's `output`.\n *\n * Note: token usage / cost lives ONLY on `RAG_EMBEDDING` child spans.\n * Aggregating at the root would double-count when an exporter sums child\n * spans. Mirrors how `AGENT_RUN` does not carry aggregated `MODEL_GENERATION`\n * usage.\n */\nexport interface RagIngestionAttributes extends AIBaseAttributes {\n /** User-supplied pipeline name */\n pipelineName?: string;\n /** Number of source documents being ingested */\n sourceCount?: number;\n /** Vector store name */\n vectorStore?: string;\n /** Index/collection name being written to */\n indexName?: string;\n /** Embedding model id */\n embeddingModel?: string;\n /** Embedding model provider */\n embeddingProvider?: string;\n}\n\n/**\n * RAG Embedding attributes (single embed call, batch).\n *\n * The texts being embedded belong on the span's `input`. Returned vectors\n * are summarized via `output` (count + dims) rather than dumped wholesale.\n * Token usage uses the same `UsageStats` shape as `MODEL_GENERATION` so\n * cost-extraction pipelines work uniformly across LLM and embedding spans.\n */\nexport interface RagEmbeddingAttributes extends AIBaseAttributes {\n /** Embedding model id */\n model?: string;\n /** Embedding model provider */\n provider?: string;\n /** Embedding vector dimensions */\n dimensions?: number;\n /** Number of inputs in this batch (cardinality of the input array) */\n inputCount?: number;\n /** Whether this embed call is part of ingestion or query */\n mode?: 'ingest' | 'query';\n /** Token usage for this embed call. Drives cost metrics. */\n usage?: UsageStats;\n}\n\n/**\n * RAG Vector Operation attributes (vector store I/O).\n *\n * Query vectors / filters belong on `input`. Result counts belong on\n * `output`.\n */\nexport interface RagVectorOperationAttributes extends AIBaseAttributes {\n /** Vector store operation kind */\n operation: 'query' | 'upsert' | 'delete' | 'fetch';\n /** Vector store name */\n store?: string;\n /** Index/collection name */\n indexName?: string;\n /** Top-K parameter (query) */\n topK?: number;\n /** Vector dimensions */\n dimensions?: number;\n}\n\n/**\n * RAG Action attributes - chunk / extract_metadata / rerank.\n *\n * Per-call result counts (chunk count, etc.) belong on `output`.\n */\nexport interface RagChunkAction extends AIBaseAttributes {\n /** RAG action kind */\n action: 'chunk';\n /** Chunking strategy / transformer name */\n strategy?: string;\n chunkSize?: number;\n chunkOverlap?: number;\n}\n\nexport interface RagExtractMetadataAction extends AIBaseAttributes {\n /** RAG action kind */\n action: 'extract_metadata';\n /** Metadata extractor name */\n extractor?: string;\n model?: string;\n provider?: string;\n}\n\nexport interface RagRerankAction extends AIBaseAttributes {\n /** RAG action kind */\n action: 'rerank';\n /** Number of candidates fed into rerank (input array length) */\n candidateCount?: number;\n /** Configured top-N to keep after reranking */\n topN?: number;\n /** Scorer/provider name */\n scorer?: string;\n}\n\nexport type RagActionAttributes = RagChunkAction | RagExtractMetadataAction | RagRerankAction;\n\n/**\n * Graph Action attributes - non-RAG, used for any graph operation.\n *\n * Per-call traversal results (visited count, returned count) belong on\n * `output`. `nodeCount` / `edgeCount` describe the graph itself.\n */\nexport interface GraphActionAttributes extends AIBaseAttributes {\n /** Graph action kind */\n action: 'build' | 'traverse' | 'update' | 'prune';\n /** Number of nodes in the graph */\n nodeCount?: number;\n /** Number of edges in the graph */\n edgeCount?: number;\n /** Threshold parameter (build) */\n threshold?: number;\n /** Number of starting nodes (traverse) */\n startNodes?: number;\n /** Maximum traversal depth */\n maxDepth?: number;\n}\n\n/**\n * AI-specific span types mapped to their attributes\n */\nexport interface SpanTypeMap {\n [SpanType.AGENT_RUN]: AgentRunAttributes;\n [SpanType.SCORER_RUN]: ScorerRunAttributes;\n [SpanType.SCORER_STEP]: ScorerStepAttributes;\n [SpanType.WORKFLOW_RUN]: WorkflowRunAttributes;\n [SpanType.MODEL_GENERATION]: ModelGenerationAttributes;\n [SpanType.MODEL_STEP]: ModelStepAttributes;\n [SpanType.MODEL_INFERENCE]: ModelInferenceAttributes;\n [SpanType.MODEL_CHUNK]: ModelChunkAttributes;\n [SpanType.TOOL_CALL]: ToolCallAttributes;\n [SpanType.CLIENT_TOOL_CALL]: ClientToolCallAttributes;\n [SpanType.PROVIDER_TOOL_CALL]: ProviderToolCallAttributes;\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.WORKSPACE_ACTION]: WorkspaceActionAttributes;\n [SpanType.GENERIC]: AIBaseAttributes;\n [SpanType.MEMORY_OPERATION]: MemoryOperationAttributes;\n [SpanType.RAG_INGESTION]: RagIngestionAttributes;\n [SpanType.RAG_EMBEDDING]: RagEmbeddingAttributes;\n [SpanType.RAG_VECTOR_OPERATION]: RagVectorOperationAttributes;\n [SpanType.RAG_ACTION]: RagActionAttributes;\n [SpanType.GRAPH_ACTION]: GraphActionAttributes;\n [SpanType.MAPPING]: MappingAttributes;\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/** Error information attached to a span when it fails. */\nexport interface SpanErrorInfo {\n message: string;\n id?: string;\n /** Error class name (e.g. \"TypeError\", \"ValidationError\") */\n name?: string;\n /** Stack trace string */\n stack?: string;\n domain?: string;\n category?: string;\n details?: Record<string, any>;\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 /** Entity type that created the span */\n entityType?: EntityType;\n /** Entity id that created the span */\n entityId?: string;\n /** Entity name that created the span */\n entityName?: string;\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?: SpanErrorInfo;\n /** Snapshot of the RequestContext */\n requestContext?: Record<string, any>;\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 /** Tracing policy for this span (inherited from parent or explicitly set) */\n tracingPolicy?: TracingPolicy;\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 /**\n * Optional hook for implementations that expose canonical correlation\n * context directly from the span instance.\n */\n getCorrelationContext?(): CorrelationContext;\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\n/** Context for bridging Mastra spans with external tracing systems (e.g., OpenTelemetry). */\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 * Span data structure shared between exported and recorded spans.\n * Contains all span fields in a serializable format (no object references).\n *\n * This is the common base for:\n * - ExportedSpan: span data sent to exporters\n * - RecordedSpan: span data loaded from storage with annotation methods\n */\nexport interface SpanData<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\n/**\n * Exported Span interface, used for tracing exporters.\n * This is the format sent to ObservabilityExporter implementations.\n */\nexport interface ExportedSpan<TType extends SpanType> extends SpanData<TType> {}\n\n/**\n * Options for ending a model generation span\n */\nexport interface EndGenerationOptions extends EndSpanOptions<SpanType.MODEL_GENERATION> {\n /** Raw usage data from AI SDK - will be converted to UsageStats with cache token details */\n usage?: LanguageModelUsage;\n /** Provider-specific metadata for extracting cache tokens */\n providerMetadata?: ProviderMetadata;\n}\n\n/**\n * Static request-side context applied to every MODEL_INFERENCE span the\n * tracker creates. These fields describe what was sent to the model and\n * are constant across the steps of a single generation in the common case.\n */\nexport interface ModelInferenceContext {\n parameters?: ModelInferenceAttributes['parameters'];\n providerOptions?: ModelInferenceAttributes['providerOptions'];\n availableTools?: ModelInferenceAttributes['availableTools'];\n toolChoice?: ModelInferenceAttributes['toolChoice'];\n responseFormat?: ModelInferenceAttributes['responseFormat'];\n}\n\n/** Tracks model execution steps and streaming chunks within a MODEL_GENERATION span. */\nexport interface IModelSpanTracker {\n getTracingContext(): TracingContext;\n reportGenerationError(options: ErrorSpanOptions<SpanType.MODEL_GENERATION>): void;\n endGeneration(options?: EndGenerationOptions): void;\n updateGeneration(options: UpdateSpanOptions<SpanType.MODEL_GENERATION>): void;\n wrapStream<T extends { pipeThrough: Function }>(stream: T): T;\n startStep(payload?: StepStartPayload): void;\n updateStep?(payload?: StepStartPayload): void;\n\n /**\n * Open the MODEL_INFERENCE span for the current step. Call this immediately\n * before invoking the model so the span's startTime excludes input processor\n * work (and `setInferenceContext` reflects the post-processor tool set).\n * Falls back to auto-creation on first chunk if the caller forgets.\n */\n startInference?(payload?: StepStartPayload): void;\n\n /**\n * Set the request-side context applied to subsequent MODEL_INFERENCE spans\n * (parameters, providerOptions, availableTools, toolChoice, responseFormat).\n * Call after input processors have finalised the tool set, just before\n * `startInference()`; the next inference span snapshots this context.\n */\n setInferenceContext?(context: ModelInferenceContext): void;\n\n /**\n * Enable or disable deferred step closing for durable execution.\n * When enabled, step-finish chunks won't automatically close the step span.\n * Use exportCurrentStep() to get the span data, then endDeferredStep() to close later.\n */\n setDeferStepClose(defer: boolean): void;\n\n /**\n * Export the current step span for later rebuilding (durable execution).\n * Returns undefined if no step span is active.\n */\n exportCurrentStep(): ExportedSpan<SpanType.MODEL_STEP> | undefined;\n\n /**\n * Get the pending step finish payload (captured when defer mode is enabled).\n * This contains usage, finishReason, etc. for closing the step later.\n */\n getPendingStepFinishPayload(): unknown;\n\n /**\n * Set the starting step index for durable execution.\n * Used when resuming across agentic loop iterations to maintain step continuity.\n */\n setStepIndex(index: number): void;\n\n /**\n * Get the current step index.\n */\n getStepIndex(): number;\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// Recorded Span & Trace Interfaces\n// ============================================================================\n\n/**\n * A recorded span is span data that has been captured/persisted and can have\n * scores and feedback attached post-hoc. Unlike live Span objects, RecordedSpan\n * has immutable core data but supports annotation methods.\n *\n * Spans are organized in a tree structure via parent/children references,\n * with all references pointing to the same objects in memory.\n *\n * Use cases:\n * - Spans loaded from storage for evaluation\n * - Spans from completed traces being annotated\n * - Post-hoc quality scoring and user feedback\n *\n * RecordedSpan objects are hydrated runtime wrappers and should not be treated as\n * durable serialized state. Persist `traceId` / `spanId` and rehydrate, or use\n * top-level observability annotation APIs after resume.\n */\nexport interface RecordedSpan<TType extends SpanType> extends SpanData<TType> {\n /** Parent span reference (undefined for root spans) */\n readonly parent?: AnyRecordedSpan;\n\n /** Child spans in execution order */\n readonly children: ReadonlyArray<AnyRecordedSpan>;\n\n /**\n * Add a quality score to this recorded span.\n * Scores are emitted via the ObservabilityBus and can be persisted/exported.\n */\n addScore(score: ScoreInput): Promise<void>;\n\n /**\n * Add user feedback to this recorded span.\n * Feedback is emitted via the ObservabilityBus and can be persisted/exported.\n */\n addFeedback(feedback: FeedbackInput): Promise<void>;\n}\n\n/**\n * Union type for cases that need to handle any recorded span\n */\nexport type AnyRecordedSpan = RecordedSpan<keyof SpanTypeMap>;\n\n/**\n * A recorded trace is a complete execution trace loaded from storage.\n * Provides both tree access (via rootSpan) and flat access (via spans).\n * All references point to the same span objects - no memory duplication.\n *\n * Obtained via mastra.observability.getRecordedTrace({ traceId }) for post-execution annotation.\n * RecordedTrace objects are hydrated runtime wrappers and should not be stored\n * across durable workflow serialization boundaries. Persist identifiers instead\n * and rehydrate, or use top-level observability annotation APIs after resume.\n */\nexport interface RecordedTrace {\n /** The trace identifier */\n readonly traceId: string;\n\n /** Root span of the trace tree (entry point for tree traversal) */\n readonly rootSpan: AnyRecordedSpan;\n\n /** All spans in flat array for iteration (same objects as in tree) */\n readonly spans: ReadonlyArray<AnyRecordedSpan>;\n\n /**\n * Get a specific recorded span by ID.\n * @param spanId - The span identifier\n * @returns The recorded span if found, null otherwise\n */\n getSpan(spanId: string): AnyRecordedSpan | null;\n\n /**\n * Add a score at the trace level.\n * Uses root span's metadata for context inheritance.\n */\n addScore(score: ScoreInput): Promise<void>;\n\n /**\n * Add feedback at the trace level.\n * Uses root span's metadata for context inheritance.\n */\n addFeedback(feedback: FeedbackInput): Promise<void>;\n}\n\n// ============================================================================\n// Tracing Interfaces\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 /** Entity type that created the span */\n entityType?: EntityType;\n /** Entity id that created the span */\n entityId?: string;\n /** Entity name that created the span */\n entityName?: string;\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 * Span ID to use for this span (1-16 hexadecimal characters).\n * Only used when rebuilding a span from cached data.\n */\n spanId?: 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 /**\n * Start time for this span.\n * Used when rebuilding a span from cached data, or when a span is created\n * after the work it represents began (e.g. backdated PROVIDER_TOOL_CALL spans).\n */\n startTime?: Date;\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 * Start time for this span.\n * Used when a span is created after the work it represents began\n * (e.g. PROVIDER_TOOL_CALL spans created when the tool result arrives).\n */\n startTime?: Date;\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\n/** Options for ending a span, with optional final attributes and output. */\nexport interface EndSpanOptions<TType extends SpanType> extends UpdateBaseOptions<TType> {\n /** Output data */\n output?: any;\n}\n\n/** Options for updating a span's attributes, input, or output mid-flight. */\nexport interface UpdateSpanOptions<TType extends SpanType> extends UpdateBaseOptions<TType> {\n /** Span name override */\n name?: string;\n /** Input data */\n input?: any;\n /** Output data */\n output?: any;\n}\n\n/** Options for recording an error on a span. */\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\n/** Options for retrieving an existing span or creating a new one from a tracing context. */\nexport interface GetOrCreateSpanOptions<TType extends SpanType> {\n type: TType;\n name: string;\n entityType?: EntityType;\n entityId?: string;\n entityName?: 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 * 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 * When true, input data will be hidden from all spans in this trace.\n */\n hideInput?: boolean;\n /**\n * When true, output data will be hidden from all spans in this trace.\n */\n hideOutput?: boolean;\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 * When true, input data will be hidden from all spans in this trace.\n * Useful for protecting sensitive data from being logged.\n */\n hideInput?: boolean;\n /**\n * When true, output data will be hidden from all spans in this trace.\n * Useful for protecting sensitive data from being logged.\n */\n hideOutput?: boolean;\n}\n\n/** Trace and span identifiers for correlating spans across systems. */\nexport interface SpanIds {\n traceId: string;\n spanId: string;\n parentSpanId?: string;\n}\n\n/**\n * Context fo