@mastra/core
Version:
1 lines • 112 kB
Source Map (JSON)
{"version":3,"file":"utils-D-eNsgDM.cjs","names":["EntityType"],"sources":["../src/observability/types/tracing.ts","../src/observability/utils.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 { MessageListInput } from '../../agent/message-list/types';\nimport type { MastraError } from '../../error';\nimport type { Mastra } from '../../mastra';\nimport type { RequestContext } from '../../request-context';\nimport type {\n LanguageModelUsage,\n ProviderMetadata,\n StepStartPayload,\n StepFinishPayload,\n ChunkType,\n StepTripwireData,\n} 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 { SpanOutcomeFields, SpanTermination } from './outcome';\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 /** Classifier evaluation */\n CLASSIFIER_EVALUATION = 'classifier_evaluation',\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 /** A request served by a Mastra MCPServer (the server side of an MCP edge) */\n MCP_SERVER_REQUEST = 'mcp_server_request',\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 /** Dynamic agent skills resolver run */\n /**\n * @deprecated Use {@link SpanType.SKILL_ACTION} with `operation: 'resolve'`.\n * No longer emitted; retained so existing exporters and stored traces keep\n * resolving the value.\n */\n SKILL_RESOLUTION = 'skill_resolution',\n /** Any skill lifecycle operation: resolve, inject, activate, search, read */\n SKILL_ACTION = 'skill_action',\n /**\n * An agent state signal emitted onto the model context (point-in-time event,\n * not a duration).\n */\n AGENT_SIGNAL = 'agent_signal',\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 /**\n * Model the run was configured with, resolved at run preparation (call-time\n * override, then agent config). The first enabled candidate of a fallback list.\n * Never updated by later steps; see MODEL_STEP `model` for what each step ran.\n */\n model?: string;\n /** Provider of `model`, taken from the same model object */\n provider?: string;\n /** The agent signal that started this run, when the run input was a signal */\n signal?: {\n id: string;\n type: string;\n tagName?: string;\n attributes?: Record<string, string | number | boolean | null>;\n };\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 * When the run's model streamed its first chunk; copied from the first\n * MODEL_GENERATION of the agent's own loop. Absent when no chunk was streamed.\n */\n completionStartTime?: Date;\n /**\n * Milliseconds from the start of the MODEL_INFERENCE that streamed the run's first\n * chunk to that chunk; copied the same way as `completionStartTime`. Absent when no\n * chunk was streamed.\n */\n timeToFirstTokenMs?: number;\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 * Classifier evaluation attributes\n */\nexport interface ClassifierEvaluationAttributes extends AIBaseAttributes {\n classifierId?: string;\n modelId?: string;\n provider?: string;\n questionCount?: number;\n questionTypes?: string[];\n maxRetries?: number;\n attemptCount?: number;\n retryCount?: number;\n durationMs?: number;\n usage?: UsageStats;\n errorType?: string;\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 /** Tokens written to Anthropic's 5-minute ephemeral cache */\n cacheWrite5m?: number;\n /** Tokens written to Anthropic's 1-hour ephemeral cache */\n cacheWrite1h?: 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. The definitions sent on each provider call\n * (after per-step changes) live on MODEL_INFERENCE spans as `tools`.\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 /** Whether one or more model steps omitted a primary token count */\n usageIncomplete?: boolean;\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 /** Time to first token of the MODEL_INFERENCE that streamed the generation's first chunk. Absent when no chunk was streamed. */\n timeToFirstTokenMs?: number;\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 /**\n * Model actually invoked for this step, after per-step overrides (input\n * processors, fallback). Recorded at invocation, so a failed provider call\n * still carries it. Absent when no model was invoked, e.g. a cached response.\n */\n model?: string;\n /** Provider of `model`, taken from the same model object */\n provider?: string;\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 /** When the step's first inference streamed its first chunk. Absent when no chunk was streamed. */\n completionStartTime?: Date;\n /** Time to first token of the MODEL_INFERENCE that streamed the step's first chunk. Absent when no chunk was streamed. */\n timeToFirstTokenMs?: number;\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 /** Milliseconds from this inference's start to its first streamed chunk. Absent when no chunk was streamed. */\n timeToFirstTokenMs?: number;\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 * Definitions of the tools sent to the provider on this inference call\n * (name, description, JSON-schema parameters), after per-step changes from\n * processors, `prepareStep`, `activeTools`, and `toolChoice`.\n */\n tools?: ModelToolDefinition[];\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 /** True when a dataset experiment tool mock intercepted the call (served, mismatched, exhausted or denied) and the tool never ran */\n mocked?: 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 /** Tool category, e.g. 'tool', 'function' */\n toolType?: string;\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 * MCP Server Request attributes\n */\nexport interface MCPServerRequestAttributes extends AIBaseAttributes {\n /** MCP method served, e.g. 'tools/call', 'resources/list', 'prompts/get' */\n mcpMethod: string;\n /** Name or URI of the tool, prompt, or resource requested. Absent on list-style calls. */\n targetName?: string;\n /** Configured MCPServer name */\n mcpServer: string;\n /** Configured MCPServer version */\n serverVersion?: string;\n /** Negotiated MCP protocol revision for this request */\n mcpProtocolVersion?: string;\n /** Client implementation name, when the client reported one */\n clientName?: string;\n /** Client implementation version, when the client reported one */\n clientVersion?: string;\n /** W3C `traceparent` the caller sent, when it parses */\n callerTraceparent?: string;\n /** W3C `tracestate` the caller sent with a valid `traceparent`, capped at 512 characters */\n callerTracestate?: string;\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 * Skill resolution attributes.\n *\n * Emitted from two places, distinguished by `phase`:\n * - `'resolver'` — a dynamic agent skills resolver run (`skills` configured as\n * a function), spanning the resolver call itself.\n * - `'injection'` — the skills processor injecting the catalog into the system\n * message. This fires for static skills too, so a misconfigured skills path\n * surfaces as `skillCount: 0` instead of producing no skill span at all.\n *\n * Extends `ProcessorPipelineAttributes` because the injection phase is emitted\n * by a processor and must still carry the runner's pipeline facts.\n */\n/** @deprecated Use {@link SkillActionAttributes}. */\nexport interface SkillResolutionAttributes extends AIBaseAttributes, ProcessorPipelineAttributes {\n /** Agent whose skills resolver ran */\n agentId?: string;\n /** Number of skills resolved (resolver) or advertised to the model (injection) */\n skillCount?: number;\n /** Which half of skill resolution this span covers */\n phase?: 'resolver' | 'injection';\n /** Format the catalog was rendered in (injection only) */\n skillFormat?: string;\n}\n\n/**\n * Skill action attributes — one span type for the whole skill lifecycle,\n * discriminated by `operation`, mirroring how `WORKSPACE_ACTION` covers\n * filesystem/sandbox/search under one type.\n *\n * The agent-internal half:\n * - `'resolve'` — a dynamic skills resolver run (`skills` configured as a function).\n * - `'inject'` — the skills processor advertising the catalog in the system\n * message. Emitted for static skills too, so a skills path that resolves to\n * nothing surfaces as `skillCount: 0` rather than producing no span at all.\n *\n * The model-initiated half, emitted by the skill tools:\n * - `'activate'` | `'search'` | `'read'`\n *\n * Extends `ProcessorPipelineAttributes` because the `inject` operation is\n * emitted by a processor and must still carry the runner's pipeline facts.\n */\nexport interface SkillActionAttributes extends AIBaseAttributes, ProcessorPipelineAttributes {\n /** Which skill lifecycle operation this span covers */\n operation: 'resolve' | 'inject' | 'activate' | 'search' | 'read';\n /** Agent the skills belong to */\n agentId?: string;\n /** Number of skills resolved (resolve) or advertised to the model (inject) */\n skillCount?: number;\n /** Format the catalog was rendered in (inject only) */\n skillFormat?: string;\n /** Configured catalog-injection option; `false` means no catalog was rendered (inject only) */\n injectCatalog?: boolean;\n /** Skill the operation targeted (activate / read) */\n skillName?: string;\n /** Whether the operation succeeded */\n success?: boolean;\n}\n\n/**\n * Pipeline phase a processor span is created for. One value per site where a\n * processor executor creates a span, so a processor that runs in more than one\n * phase can name, describe and narrow each of them separately.\n *\n * Re-exported from `@mastra/core/processors` as `ProcessorSpanPhase`; it lives\n * here because `ProcessorPipelineAttributes` records it and observability types\n * cannot import from `processors`.\n */\nexport type ProcessorSpanPhase =\n | 'input'\n | 'inputStep'\n | 'llmRequest'\n | 'llmResponse'\n | 'output'\n | 'outputStep'\n | 'toolResult'\n | 'requestError';\n\n/**\n * Phase recorded on a processor span, and the discriminant its payloads narrow\n * on.\n *\n * Finer-grained than `ProcessorSpanPhase`, which collapses the two output hooks\n * into one `'output'` because a processor naming its span does not care which\n * ran. A reader does: `outputStream` records chunk counts and accumulated text,\n * `outputResult` records messages and a summarized result. One value for both\n * would leave the payload ambiguous, which is the whole reason this attribute\n * exists.\n */\nexport type ProcessorSpanPayloadPhase = Exclude<ProcessorSpanPhase, 'output'> | 'outputStream' | 'outputResult';\n\n/**\n * Attributes recorded for every processor the processor runner executes,\n * independent of the span type that processor declares.\n *\n * A processor may opt out of the default `PROCESSOR_RUN` span type (see\n * `Processor.spanType`) so its span is labelled with the Mastra subsystem it\n * belongs to — e.g. the skills processor emits `SKILL_ACTION` rather than\n * an anonymous processor span. The runner still records the pipeline facts\n * below on that span, so retyping never loses the mutation log or the\n * processor's position in the chain. Any attributes interface reachable from a\n * declared `spanType` must therefore extend this.\n */\nexport interface ProcessorPipelineAttributes {\n /** Processor executor type (workflow or legacy) */\n processorExecutor?: 'workflow' | 'legacy';\n /** Processor index in the agent */\n processorIndex?: number;\n /**\n * Pipeline phase the span was created for. The discriminant a reader narrows\n * a processor span's payloads on: `entityType` cannot serve, because\n * `llmRequest`/`llmResponse` share `INPUT_PROCESSOR` and\n * `outputStep`/`requestError` share `OUTPUT_STEP_PROCESSOR`.\n *\n * Absent on spans recorded before this attribute existed, which is why the\n * typed payload views fall back to the untyped shape rather than assuming a\n * phase.\n */\n processorPhase?: ProcessorSpanPayloadPhase;\n /**\n * Milliseconds spent inside `processOutputStream`, summed across every\n * chunk of the stream. Only set on output stream processor spans. The\n * span's own duration covers its step, from the first chunk to the step's\n * end with model latency and tool calls included, so this is what separates\n * a slow processor from the rest of the step.\n */\n hookDurationMs?: 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 * Processor attributes — the default span type for a processor that does not\n * declare one of its own.\n */\nexport interface ProcessorRunAttributes extends AIBaseAttributes, ProcessorPipelineAttributes {}\n\n/**\n * Agent signal attributes — one emission on a processor's state-signal lane.\n *\n * Recorded as an **event** span: a signal is a point-in-time fact about what\n * entered the model's context, not a unit of work with a duration. The work of\n * computing it is already timed by the enclosing processor span.\n *\n * Emitted only when a signal is actually produced. A step where the lane\n * computed no change records nothing, so an unchanged turn stays silent.\n */\nexport interface AgentSignalAttributes extends AIBaseAttributes {\n /** State lane this signal belongs to (`stateId`), e.g. 'tasks', 'goal', 'browser' */\n stateId?: string;\n /** Whether this emission replaced the state or carried only the change since the last snapshot */\n mode?: 'snapshot' | 'delta';\n /** Tag the signal is wrapped in for the model, e.g. 'current-task-list' */\n tagName?: string;\n /** Processor that produced the signal */\n processorId?: string;\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 /** Authored graph entry description */\n entryDescription?: string;\n /** Authored graph entry metadata */\n entryMetadata?: Record<string, any>;\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 /** Authored graph entry id for this control-flow operation */\n entryId?: string;\n /** Authored graph entry description */\n entryDescription?: string;\n /** Authored graph entry metadata */\n entryMetadata?: Record<string, any>;\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 /** Authored graph entry id for this control-flow operation */\n entryId?: string;\n /** Authored graph entry description */\n entryDescription?: string;\n /** Authored graph entry metadata */\n entryMetadata?: Record<string, any>;\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 /** Authored graph entry id for this control-flow operation */\n entryId?: string;\n /** Authored graph entry description */\n entryDescription?: string;\n /** Authored graph entry metadata */\n entryMetadata?: Record<string, any>;\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 /** Authored graph entry id for this sleep operation */\n entryId?: string;\n /** Authored graph entry description */\n entryDescription?: string;\n /** Authored graph entry metadata */\n entryMetadata?: Record<string, any>;\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, ProcessorPipelineAttributes {\n /**\n * Which memory operation this span covers.\n *\n * `observe` and `reflect` are the observational-memory model passes; the rest\n * are the read/write operations on stored memory.\n */\n operationType?: 'recall' | 'save' | 'delete' | 'update' | 'observe' | 'reflect';\n messageCount?: number;\n embeddingTokens?: number;\n semanticRecallEnabled?: boolean;\n vectorResultCount?: number;\n workingMemoryEnabled?: boolean;\n lastMessages?: number | false;\n /** Tokens fed to the observational-memory pass (observe / reflect) */\n inputTokens?: number;\n /** Model the observational-memory pass selected, or '(dynamic-model)' when resolved per call */\n selectedModel?: string;\n /** Whether an `observe` pass ran across multiple threads */\n multiThread?: boolean;\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, ProcessorPipelineAttributes {\n /** Workspace identifier */\n workspaceId?: string;\n /** Human-readable workspace name */\n workspaceName?: string;\n /** Action category */\n category: 'filesystem' | 'sandbox' | 'search' | 'skill' | 'mount' | 'computer';\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.CLASSIFIER_EVALUATION]: ClassifierEvaluationAttributes;\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.MCP_SERVER_REQUEST]: MCPServerRequestAttributes;\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 [SpanType.SKILL_RESOLUTION]: SkillResolutionAttributes;\n [SpanType.SKILL_ACTION]: SkillActionAttributes;\n [SpanType.AGENT_SIGNAL]: AgentSignalAttributes;\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 Input & Output Payloads\n// ============================================================================\n\n/**\n * Output recorded on `AGENT_RUN`, `MODEL_GENERATION` and `MODEL_STEP` spans\n * when the run stops before the span's own result exists: a durable run\n * suspended, the caller aborted, or the process running a durable run stopped\n * and the run was recovered elsewhere.\n */\nexport interface InterruptedSpanOutput {\n status: 'suspended' | 'aborted' | 'interrupted';\n /** Why the run stopped */\n reason?: string;\n /** Tool that suspended the run */\n toolName?: string;\n /** Tool call that suspended the run */\n toolCallId?: string;\n}\n\n/**\n * Input recorded on a resumed `AGENT_RUN` span: the resume data the caller\n * passed, plus the suspended tool's identity when it is known.\n */\nexport interface AgentRunResumeInput {\n /** Resume data, kept nested when it names a different tool than the suspended one */\n resumeData?: unknown;\n /** Tool the run resumes into */\n toolName?: string;\n /** Tool call the run resumes into */\n toolCallId?: string;\n [key: string]: unknown;\n}\n\n/**\n * Input recorded on `AGENT_RUN` spans: the messages the caller passed for a\n * fresh run, or the resume data for a resumed run.\n */\nexport type AgentRunInput = MessageListInput | { messages: MessageListInput } | AgentRunResumeInput;\n\n/** Output recorded on an `AGENT_RUN` span when the run finishes. */\nexport interface AgentRunResult {\n /** Final response text */\n text?: string;\n /** Final structured output */\n object?: unknown;\n /** Generated files */\n files?: unknown[];\n /** Tripwire that aborted the run */\n tripwire?: StepTripwireData;\n}\n\n/** Output recorded on `AGENT_RUN` spans. */\nexport type AgentRunOutput = AgentRunResult | InterruptedSpanOutput;\n\n/**\n * Input recorded on `MODEL_GENERATION` spans.\n *\n * Mastra's own loop records the normalized model messages, system messages\n * first. SDK agents (`@mastra/claude`, `@mastra/openai`, ...) record the raw\n * messages the caller passed, so `messages` keeps the full `MessageListInput`\n * shape rather than a single message format.\n */\nexport interface ModelGenerationInput {\n /** Messages sent to the model */\n messages: MessageListInput;\n /** Output schema, when structured output was requested */\n schema?: unknown;\n}\n\n/**\n * Output recorded on a `MODEL_GENERATION` span when the generation finishes.\n * Every field is optional: a durable run records only `text`.\n */\nexport interface ModelGenerationResult {\n /** Generated text */\n text?: string;\n /** Generated structured output */\n object?: unknown;\n /** Reasoning details */\n reasoning?: unknown;\n /** Reasoning as plain text */\n reasoningText?: string;\n /** Generated files */\n files?: unknown[];\n /** Sources the model cited */\n sources?: unknown[];\n /** Tool calls the model requested */\n toolCalls?: unknown[];\n /** Provider warnings */\n warnings?: unknown[];\n}\n\n/** Output recorded on `MODEL_GENERATION` spans. */\nexport type ModelGenerationOutput = ModelGenerationResult | InterruptedSpanOutput;\n\n/** One message in the shallow conversation preview a model step records. */\nexport interface ModelStepMessage {\n /** Message role (e.g., 'system', 'user', 'assistant', 'tool') */\n role: string;\n /** Message text, with non-text parts summarized */\n content: string;\n}\n\n/**\n * Input recorded on `MODEL_STEP` and `MODEL_INFERENCE` spans: a shallow\n * preview of what the step sent to the model. A normalized message list when\n * the step carries messages; otherwise a summary of the request body, or the\n * raw request when it cannot be summarized.\n */\nexport type ModelStepInput = ModelStepMessage[] | Record<string, unknown> | string;\n\n/**\n * Output recorded on `MODEL_STEP` and `MODEL_INFERENCE` spans when the step\n * finishes: the step result without `usage`, which lives on the attributes.\n */\nexport interface ModelStepResult {\n /** Text generated in this step */\n text?: string;\n /** Tool calls the model requested in this step */\n toolCalls?: unknown[];\n /** Accumulated step results, when the loop reports them */\n steps?: unknown[];\n /** Structured output generated in this step */\n object?: unknown;\n}\n\n/** Output recorded on `MODEL_STEP` spans. `MODEL_INFERENCE` spans record a `ModelStepResult` only. */\nexport type ModelStepOutput = ModelStepResult | InterruptedSpanOutput;\n\n/** Model a processor saw or swapped in, summarized to the fields worth tracing. */\nexport interface ProcessorModelSummary {\n modelId?: string;\n provider?: string;\n specificationVersion?: string;\n}\n\n/** A tool as a processor span records it. */\nexport interface ProcessorToolSummary {\n id: string;\n name: string;\n description?: string;\n}\n\n/** A tool named in `activeTools`, resolved against the tool registry where possible. */\nexport interface ProcessorActiveToolSummary {\n id: string;\n name: string;\n}\n\n/** The step's tool choice as a processor span records it. */\nexport interface ProcessorToolChoiceSummary {\n type: string;\n tool?: ProcessorActiveToolSummary;\n}\n\n/**\n * Messages and system messages a processor changed. Both executors omit a key\n * when the processor left it untouched, so an absent key means \"unchanged\"\n * rather than \"empty\" — the diff is the point, not the full list again.\n */\nexport interface ProcessorMessageChanges {\n messages?: unknown[];\n systemMessages?: unknown[];\n}\n\n/** The model-call configuration an `inputStep` processor saw. */\ninterface ProcessorStepConfig {\n model?: ProcessorModelSummary;\n tools?: ProcessorToolSummary[];\n toolChoice?: ProcessorToolChoiceSummary;\n activeTools?: ProcessorActiveToolSummary[];\n}\n\n/**\n * `input` payload a processor span records, per phase.\n *\n * Every member is what the executors actually write today; a field either\n * executor omits conditionally is optional here. `llmRequest`, `llmResponse`\n * and `requestError` come from the legacy runner only — the processor workflow\n * has no step for them.\n */\nexport interface ProcessorRunInputByPhase {\n input: { messages: unknown[]; systemMessages?: unknown[]; retryCount?: number };\n inputStep: {\n messages: unknown[];\n systemMessages?: unknown[];\n stepNumber?: number;\n messageId?: string;\n retryCount?: number;\n } & ProcessorStepConfig;\n outputStream: { totalChunks: number; accumulatedText?: string };\n outputResult: { messages: unknown[]; result?: Record<string, unknown>; retryCount?: number };\n outputStep: {\n messages: unknown[];\n systemMessages?: unknown[];\n stepNumber?: number;\n finishReason?: string;\n text?: string;\n toolCalls?: unknown[];\n retryCount?: number;\n };\n toolResult: {\n stepNumber?: number;\n toolName?: string;\n toolCallId?: string;\n providerExecuted?: boolean;\n retryCount?: number;\n };\n llmRequest: { prompt?: unknown; stepNumber?: number; retryCount?: number };\n llmResponse: { stepNumber?: number; retryCount?: number; fromCache?: boolean; chunkCount?: number };\n requestError: { messages: unknown[]; error: string; stepNumber?: number; messageId?: string; retryCount?: number };\n}\n\n/**\n * `output` payload a processor span records, per phase.\n *\n * Most phases record only what the processor changed, so an absent key means\n * unchanged. The output-stream hook is the exception: it has no message list to\n * diff, so it records the chunk totals it produced.\n */\nexport interface ProcessorRunOutputByPhase {\n input: ProcessorMessageChanges;\n inputStep: { messageId?: string; retryCount?: number } & ProcessorMessageChanges & ProcessorStepConfig;\n /** The processor workflow records only `totalChunks`; the legacy runner also records the text. */\n outputStream: { totalChunks: number; accumulatedText?: string };\n outputResult: ProcessorMessageChanges;\n outputStep: ProcessorMessageChanges;\n toolResult: ProcessorMessageChanges;\n llmRequest: ProcessorMessageChanges;\n llmResponse: ProcessorMessageChanges;\n requestError: ProcessorMessageChanges;\n}\n\n/** `input` of a processor span before its phase is known. */\nexport type ProcessorRunInput = ProcessorRunInputByPhase[ProcessorSpanPayloadPhase];\n\n/** `output` of a processor span before its phase is known. */\nexport type ProcessorRunOutput = ProcessorRunOutputByPhase[ProcessorSpanPayloadPhase];\n\n/**\n * Span types whose `input` Mastra writes itself with a fixed shape. Every\n * other span type keeps `any`, as before: tool arguments, workflow data and\n * the like are caller-defined, `MODEL_CHUNK` multiplexes several chunk shapes\n * on one span type, and `GENERIC` is the escape hatch for custom spans.\n *\n * `PROCESSOR_RUN` is absent on purpose. Three executors emit processor spans —\n * the legacy runner, the processor workflow, and the Inngest workflow — and they\n * record different shapes, so a mapped type here would type the write side\n * against a contract two of them do not meet. The read side is where the shape\n * is known: `describeSpanInput` / `describeSpanOutput` narrow a payload by the\n * phase the span recorded, and fall back to JSON when it recorded none.\n */\nexport interface SpanInputMap {\n [SpanType.AGENT_RUN]: AgentRunInput;\n [SpanType.MODEL_GENERATION]: ModelGenerationInput;\n [SpanType.MODEL_STEP]: ModelStepInput;\n [SpanType.MODEL_INFERENCE]: ModelStepInput;\n}\n\n/** Span types whose `output` Mastra writes itself with a fixed shape. Same rules as `SpanInputMap`. */\nexport interface SpanOutputMap {\n [SpanType.AGENT_RUN]: AgentRunOutput;\n [SpanType.MODEL_GENERATION]: ModelGenerationOutput;\n [SpanType.MODEL_STEP]: ModelStepOutput;\n [SpanType.MODEL_INFERENCE]: ModelStepResult;\n}\n\n/** `input` payload of a span: the mapped shape when `SpanInputMap` lists the type, otherwise `any`. */\nexport type SpanInput<TType extends SpanType> = TType extends keyof SpanInputMap ? SpanInputMap[TType] : any;\n\n/** `output` payload of a span: the mapped shape when `SpanOutputMap` lists the type, otherwise `any`. */\nexport type SpanOutput<TType extends SpanType> = TType extends keyof SpanOutputMap ? SpanOutputMap[TType] : any;\n\n/**\n * Span types a processor may declare via `Processor.spanType`.\n *\n * Restricted to those whose attributes extend `ProcessorPipelineAttributes`,\n * so the runner can always record `processorIndex`, `messageListMutations` and\n * `tripwireAbort` on the span regardless of which type the processor picked.\n * Adding a domain span type to this set is therefore a matter of mixing\n * `ProcessorPipelineAttributes` into its attributes interface.\n */\nexport type ProcessorSpanType = Exclude<\n {\n [K in keyof SpanTypeMap]: SpanTypeMap[K] extends ProcessorPipelineAttributes ? K : never;\n }[keyof SpanTypeMap],\n // `ProcessorPipelineAttributes` is all-optional, so the check above is\n // structural rather than nominal: a span type satisfies it by not\n // conflicting with it, not by mixing it in. Two types pass that way and are\n // excluded explicitly.\n //\n // `AGENT_RUN`, because a processor labelling its span as the agent run that\n // contains it would reparent the trace's own root.\n //\n // `SKILL_RESOLUTION`, because it is deprecated and no longer emitted; it\n // stays in `SpanTypeMap` so stored traces keep resolving, but nothing new\n // should declare it. Declare `SKILL_ACTION` with `operation: 'resolve'`.\n SpanType.AGENT_RUN | SpanType.SKILL_RESOLUTION\n>;\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 * A reference to a span in another trace. Unlike a parent, a link does not put\n * the two spans in the same trace: each trace keeps its own root and summary.\n */\nexport interface SpanLink {\n /** Trace ID of the linked span (1-32 hexadecimal characters) */\n traceId: string;\n /** Span ID of the linked span (1-16 hexadecimal characters) */\n spanId: string;\n}\n\n/**\n * Base Span interface\n */\ninterface BaseSpan<TType extends SpanType> extends SpanOutcomeFields {\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?: SpanInput<TType>;\n /** Optional display previews. Empty strings are intentional; nullish values request generation. */\n inputPreview?: string | null;\n outputPreview?: string | null;\n errorPreview?: string | null;\n /** Output generated at the end of the span */\n output?: SpanOutput<TType>;\n /** Error information if span failed */\n errorInfo?: SpanErrorInfo;\n /** Snapshot of the RequestContext */\n requestContext?: Record<string, any>;\n /** Is an event span? (point-in-time: endTime equals startTime) */\n isEvent: boolean;\n /** Spans in other traces this span is related to, such as the span that sent a request this span serves */\n links?: SpanLink[];\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 /** End the span and any descendant spans that are still open, applying `options` to each */\n endTree(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 /** Record a local failure without changing outcome, payload or completion. Older implementations may omit this. */\n recordError?(error: Error, options?: { occurrenceId?: string; origin?: 'new' | 'propagated' }): 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 /**\n * Optional hook returning the spanId observability signals (logs, metrics,\n * scores) should reference: the span's own id when it reaches exporters,\n * otherwise the nearest exportable ancestor's id, or undefined when none\n * exists. Covers exclusions known when the span is created (internal spans,\n * `excludeSpanTypes`); a `spanFilter` or a span output processor can still\n * drop a span at export time, since those only run once the span has ended.\n */\n getExportedSpanId?(): 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 span saved for a later `rebuildSpan()`, with its trace state */\n snapshot(): SpanSnapshot<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(options?: ModelSpanTrackerOptions): IModelSpanTracker | undefined;\n}\n\nexport interface ModelSpanTrackerOptions {\n /**\n * The AGENT_RUN span that owns this generation. Only the agent's main loop\n * passes it, so the first chunk's `completionStartTime` lands on that span\n * and never on an outer agent's run (nested agents, title generation).\n */\n agentRunSpan?: Span<SpanType.AGENT_RUN>;\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 — a span Mastra created within this trace (undefined for root spans) */\n parentSpanId?: string;\n /** Parent from an external tracing system (ambient OTel / dd-trace) that Mastra did not create; carried for external correlation, not Mastra's own parentage */\n externalParentSpanId?: string;\n /**\n * Native span fields, stored in their own columns alongside `externalParentSpanId`.\n * An unset field is stored as null.\n */\n /** Span id of the initial invocation a resumed execution continues (unset on the initial execution) */\n resumedFromSpanId?: string;\n /**\n * Requested model id, filled at export from this span's own `attributes.model`; the live span does not carry it.\n * Set together with `provider` only when both attributes are non-empty strings, otherwise neither is set.\n */\n model?: string;\n /** Provider paired with `model`, from this span's own `attributes.provider` */\n provider?: string;\n /** Milliseconds from the model call to the first token received, filled at export; the live span does not carry it */\n timeToFirstTokenMs?: number;\n /** Failures originating directly on this span, excluding propagated/descendant failures. Unset when unknown. */\n errorCount?: number;\n /** `TRUE` if the span is the root span of a trace */\n isRootSpan: boolean;\n /**\n * `TRUE` on every span of a run that the caller attached under an existing\n * span with `tracingOptions.nestUnderParent`. The run does not own the\n * trace, so exporters must not write trace-level fields from its spans.\n */\n nestedUnderParent?: 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 /** Set when the span is internal, so `rebuildSpan()` can restore its internal status */\n isInternal?: boolean;\n /**\n * Version of the span's own entity: declared for it, or inherited from a parent of the same entity.\n * Omitted when it only inherited another entity's version through `metadata.entityVersionId`.\n */\n entityVersionId?: string;\n /** Service name from the span's `metadata.serviceName`, else the Observability config's `serviceName` */\n serviceName?: string;\n /**\n * Entity of the nearest ancestor span that is not internal or excluded. Omitted when there is none.\n * Independent of `includeInternalSpans`, so it can skip the span `parentSpanId` points to.\n */\n parentEntityType?: EntityType;\n parentEntityId?: string;\n parentEntityName?: string;\n /** Omitted when the parent entity has no version of its own, even if it inherited one from an ancestor */\n parentEntityVersionId?: string;\n /**\n * Entity of the top span in this process's parent chain (the span's own entity when it is that span).\n * For a trace continued from another service, this is the local root, not the distributed trace's root.\n * Internal spans are not skipped.\n */\n rootEntityType?: EntityType;\n rootEntityId?: string;\n rootEntityName?: string;\n rootEntityVersionId?: string;\n}\n\n/**\n * A span saved between durable steps, for `rebuildSpan()`. Extends the exported\n * form with runtime state that exporters do not need, so spans created under\n * the rebuilt span keep honouring the trace's `requestContextKeys`,\n * `hideInput` and `hideOutput`.\n */\nexport interface SpanSnapshot<TType extends SpanType> extends ExportedSpan<TType> {\n /** @internal Local occurrences already accounted for; retained across durable reconstruction. */\n errorOccurrenceIds?: string[];\n traceState?: TraceState;\n /** Version of the span's own entity, `null` when it has none. Absent in snapshots from older versions. */\n ownEntityVersionId?: string | null;\n}\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 /** Provider metadata for every completed model step, when the caller has it available. */\n stepProviderMetadata?: readonly (ProviderMetadata | undefined)[];\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 tools?: ModelInferenceAttributes['tools'];\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 /**\n * When the first inference seen by this tracker streamed its first chunk.\n * Durable execution reads it per step and carries it to the final\n * `endGeneration`, since that step uses a fresh tracker.\n */\n getCompletionStartTime?(): Date | undefined;\n /** Track provider chunks and completion in their original stream order. */\n wrapInferenceStream?<T extends { pipeThrough: Function }>(stream: T): T;\n /** Time to first token of the first inference seen by this tracker; carried the same way. */\n getTimeToFirstTokenMs?(): number | undefined;\n wrapStream<T extends { pipeThrough: Function }>(stream: T): T;\n /** @internal Record a chunk after the runtime has applied output processors. */\n recordChunk?<OUTPUT>(chunk: ChunkType<OUTPUT>): void;\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 * Pass the prompt (`inputMessages`) so the span records what this call sent.\n * Falls back to auto-creation on first chunk if the caller forgets.\n */\n startInference?(payload?: StepStartPayload): void;\n /** Close the current attempt without ending the generation or agent. */\n endAttempt?(termination: SpanTermination): void;\n\n /**\n * End the open MODEL_INFERENCE span as interrupted, keeping the MODEL_STEP open.\n * Called when a queued signal cancels the model request so its replacement\n * opens its own inference span under the same step.\n */\n interruptInference?(termination?: SpanTermination): void;\n\n /**\n * End the open MODEL_INFERENCE span as failed, keeping the MODEL_STEP open.\n * Called when a model call fails and a retry or fallback model will open its\n * own inference span under the same step.\n */\n failInference?(error: Error): void;\n\n /**\n * Set the request-side context applied to subsequent MODEL_INFERENCE spans\n * (parameters, providerOptions, availableTools, tools, 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(): SpanSnapshot<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> extends SpanOutcomeFields {\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 /** Spans in other traces this span is related to. Links with invalid IDs are ignored. */\n links?: SpanLink[];\n}\n\n/**\n * Options for creating new spans\n */\nexport interface CreateSpanOptions<TType extends SpanType> extends CreateBaseOptions<TType> {\n /** Input data */\n input?: SpanInput<TType>;\n /** Output data (for event spans) */\n output?: SpanOutput<TType>;\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 * Must reference a Mastra span within this trace (a rebuilt span's parent,\n * or the suspended span a resumed run links back to).\n * Only used for root spans without a parent.\n */\n parentSpanId?: string;\n /**\n * Parent span ID from an external tracing system (1-16 hexadecimal characters),\n * such as an ambient OpenTelemetry span Mastra did not create. Exported to\n * external tracing exporters for correlation; not part of Mastra's own parentage.\n * Only used for root spans without a parent.\n */\n externalParentSpanId?: string;\n /** Native resume linkage, restored by rebuildSpan. */\n resumedFromSpanId?: 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 /** @internal Reuse the sampling decision when starting a resumed execution in an existing trace. */\n samplingDecision?: boolean;\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?: SpanInput<TType>;\n /** Span id of the initial invocation this resumed execution continues */\n resumedFromSpanId?: string;\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 their endTime equals their startTime\n */\nexport interface ChildEventOptions<TType extends SpanType> extends CreateBaseOptions<TType> {\n /** Output data */\n output?: SpanOutput<TType>;\n}\n\ninterface UpdateBaseOptions<TType extends SpanType> extends SpanOutcomeFields {\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?: SpanOutput<TType>;\n /**\n * Also close any descendant spans still open, without applying these\n * options to them. Use at terminal points (error, abort, suspension) where\n * nothing below this span may keep running. Unlike `endTree()`, options\n * apply to this span only.\n */\n endTree?: boolean;\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?: SpanInput<TType>;\n /** Output data */\n output?: SpanOutput<TType>;\n}\n\n/** Options for recording an error on a span. */\nexport interface ErrorSpanOptions<TType extends SpanType> extends UpdateBaseOptions<TType> {\n /** Explicitly identify a new failure or a propagated report when Error/cause identity is insufficient. */\n origin?: 'new' | 'propagated';\n /** The error associated with the issue */\n error: MastraError | Error;\n /** End the span when true */\n endSpan?: boolean;\n /**\n * Also close any descendant spans still open, without recording the error\n * on them. Implies ending this span. Use at terminal points where nothing\n * below this span may keep running.\n */\n endTree?: boolean;\n}\n\n/** What a suspending run saves so that its resume continues the same invocation. Persisted in workflow snapshots. */\nexport interface ResumeTracingContext {\n traceId?: string;\n /** Span the resumed root span attaches under (its parentSpanId) */\n spanId?: string;\n parentSpanId?: string;\n /**\n * Initial invocation of this run, exported by each resume as `resumedFromSpanId`.\n * Snapshots from older versions lack it, so readers fall back to `spanId`.\n */\n resumedFromSpanId?: string;\n /** External parent of the suspended invocation, kept by a resume that gives none of its own */\n externalParentSpanId?: string;\n /**\n * Whether the suspended invocation was sampled. Workflow runs save it (see\n * `getWorkflowResumeTracingContext`) and their resumes repeat the decision instead of sampling\n * again. Agent runs and snapshots from older versions lack it, so those resumes decide as before.\n */\n sampled?: boolean;\n /**\n * Trace-level state of the suspended invocation. A resume keeps its hidden input/output and keys\n * where the resume call sets none of its own.\n */\n traceState?: TraceState;\n}\n\n/** Options for retrieving an existing span or creating a new one from a tracing context. */\nexport interface GetOrCreateSpanOptions<TType extends SpanType> extends SpanOutcomeFields {\n /** @internal Original trace state and sampling decision for a resumed execution. */\n traceState?: TraceState;\n samplingDecision?: boolean;\n type: TType;\n name: string;\n entityType?: EntityType;\n entityId?: string;\n entityName?: string;\n input?: SpanInput<TType>;\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 /** Spans in other traces this span is related to. Links with invalid IDs are ignored. */\n links?: SpanLink[];\n /**\n * Saved context of the run this call resumes. Together with `tracingOptions`\n * it decides the trace, the parent, `resumedFromSpanId` and `externalParentSpanId`.\n */\n resumeFrom?: ResumeTracingContext;\n /**\n * Span id of the suspended span a resumed run links back to. It is a Mastra\n * span within the trace, so it becomes the new root span's parent.\n * @deprecated Use `resumeFrom`, which also sets the resumed span's `resumedFromSpanId` and external parent.\n */\n resumedFromSpanId?: string;\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 * When true, this run was attached under an existing span with\n * `tracingOptions.nestUnderParent` and does not own the trace.\n */\n nestedUnderParent?: boolean;\n}\n\n/**\n * Options passed when starting a new agent or workflow execution\n */\nexport interface TracingOptions {\n /**\n * Display name for the root span of this trace, replacing the default\n * `agent run: '<id>'` / `workflow run: '<id>'` name. Use it to tell runs of the\n * same agent or workflow apart in trace lists. Only applied to the root span.\n */\n rootSpanName?: string;\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 * Intended for correlating with an external tracing system (e.g. an\n * OpenTelemetry span in the calling service): the id is exported for\n * external tracing but is not treated as a parent within Mastra storage.\n */\n parentSpanId?: string;\n /**\n * Set to true together with `parentSpanId` to attach this run as a child of\n * that span inside the existing trace, for example an LLM judge under the\n * run it scores. Exporters then keep the trace's own name, input, output,\n * and tags instead of replacing them with this run's. Leave unset when\n * `parentSpanId` points at a span from your own tracing system: there the\n * Mastra run is the top of the trace. Ignored without a valid `traceId` and `parentSpanId`.\n */\n nestUnderParent?: boolean;\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 /** Parent that is a Mastra span (one this bridge created within the trace). */\n parentSpanId?: string;\n /**\n * Parent that belongs to the external tracing system (e.g. an ambient\n * OpenTelemetry or dd-trace span) that Mastra did not create.\n * Bridges set exactly one of `parentSpanId` / `externalParentSpanId`.\n */\n externalParentSpanId?: 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 /** Root span ID used on the execution (if the execution was traced). */\n spanId?: string;\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\n/**\n * Interface for span processors\n */\nexport interface SpanOutputProcessor {\n /** Processor name */\n name: string;\n /**\n * Process span before export.\n *\n * Mutate the span you receive and return the same instance, or return\n * `undefined` to drop it. Do not return a copy: `exportSpan` and `isValid`\n * are instance members of the live span, so a copy cannot be exported and\n * is dropped with a logged processor error.\n */\n process(span?: AnySpan): AnySpan | undefined;\n /** Shutdown processor */\n shutdown(): Promise<void>;\n}\n\n/**\n * Function type for formatting exported spans at the exporter level.\n *\n * This allows customization of how spans appear in vendor-specific observability platforms\n * (e.g., Langfuse, Braintrust). Unlike SpanOutputProcessor which operates on the internal\n * Span object before export, this formatter operates on the ExportedSpan data structure\n * after the span has been prepared for export.\n *\n * Formatters can be synchronous or asynchronous, enabling use cases like:\n * - Extract plain text from structured AI SDK messages for better readability\n * - Transform input/output format for specific vendor requirements\n * - Add or remove fields based on the target platform\n * - Redact or transform sensitive data in a vendor-specific way\n * - Enrich spans with data from external APIs (async)\n * - Perform database lookups to add context (async)\n *\n * @param span - The exported span to format\n * @returns The formatted span (sync) or a Promise resolving to the formatted span (async)\n *\n * @example\n * ```typescript\n * // Synchronous formatter that extracts plain text from AI messages\n * const plainTextFormatter: CustomSpanFormatter = (span) => {\n * if (span.type === SpanType.AGENT_RUN && Array.isArray(span.input)) {\n * const userMessage = span.input.find(m => m.role === 'user');\n * return {\n * ...span,\n * input: userMessage?.content ?? span.input,\n * };\n * }\n * return span;\n * };\n *\n * // Async formatter that enriches spans with external data\n * const enrichmentFormatter: CustomSpanFormatter = async (span) => {\n * const userData = await fetchUserData(span.metadata?.userId);\n * return {\n * ...span,\n * metadata: { ...span.metadata, userName: userData.name },\n * };\n * };\n *\n * // Use with an exporter\n * new BraintrustExporter({\n * customSpanFormatter: plainTextFormatter,\n * });\n * ```\n */\nexport type CustomSpanFormatter = (span: AnyExportedSpan) => AnyExportedSpan | Promise<AnyExportedSpan>;\n","/**\n * Browser-safe observability utilities.\n *\n * Functions that depend on AsyncLocalStorage (getCurrentSpan, executeWithContext,\n * executeWithContextSync) are in context-storage.ts and should only be imported\n * by server-side code.\n */\n\nimport { EntityType, SpanType } from './types';\nimport type {\n Span,\n GetOrCreateSpanOptions,\n AnySpan,\n AnyExportedSpan,\n ResumeTracingContext,\n SpanSnapshot,\n TracingOptions,\n TracingProperties,\n} from './types';\n\nconst entityTypeValues = new Set<EntityType>(Object.values(EntityType));\nlet currentSpanResolver: (() => AnySpan | undefined) | undefined;\n\nexport function setCurrentSpanResolver(resolver: (() => AnySpan | undefined) | undefined): void {\n currentSpanResolver = resolver;\n}\n\nexport function resolveCurrentSpan(): AnySpan | undefined {\n return currentSpanResolver?.();\n}\n\n/** Generate a unique id for an observability signal (log, metric, score, feedback). */\nexport function generateSignalId(): string {\n return crypto.randomUUID();\n}\n\n/**\n * Compute the names of tools the model can call on a single inference step,\n * applying `activeTools` filtering when present. Used to populate the\n * `availableTools` attribute on MODEL_INFERENCE spans so observers see the\n * post-processor tool set, which can differ per-step from the AGENT_RUN view.\n *\n * `activeTools` is treated by presence, not truthiness: an explicit empty\n * array means \"no tools enabled for this step\" and is honored as such.\n * Returns `[]` (not `undefined`) when `tools` is provided but empty, so a\n * tool-less agent still reports a definitive empty list to observers.\n *\n * @deprecated No longer used. `availableTools` is now derived from the tool\n * definitions serialized for the MODEL_INFERENCE `tools` attribute, which\n * also apply `toolChoice` and drop names that are not registered tools.\n */\nexport function getStepAvailableToolNames(\n tools?: Record<string, unknown> | undefined,\n activeTools?: readonly string[] | undefined,\n): string[] | undefined {\n if (activeTools !== undefined) {\n return [...activeTools];\n }\n if (tools) {\n return Object.keys(tools);\n }\n return undefined;\n}\n\n// --- Lazy resolvers for executeWithContext / executeWithContextSync ---\n// The real implementations live in context-storage.ts (which imports AsyncLocalStorage).\n// context-storage.ts registers them at import time so that consumer code can call these\n// browser-safe wrappers without pulling async_hooks into shared chunks.\n\ntype ExecuteWithContextFn = <T>(params: { span?: AnySpan; fn: () => Promise<T> }) => Promise<T>;\ntype ExecuteWithContextSyncFn = <T>(params: { span?: AnySpan; fn: () => T }) => T;\n\nlet executeWithContextImpl: ExecuteWithContextFn | undefined;\nlet executeWithContextSyncImpl: ExecuteWithContextSyncFn | undefined;\n\nexport function setExecuteWithContext(impl: ExecuteWithContextFn): void {\n executeWithContextImpl = impl;\n}\n\nexport function setExecuteWithContextSync(impl: ExecuteWithContextSyncFn): void {\n executeWithContextSyncImpl = impl;\n}\n\n/**\n * Execute an async function within a span's tracing context.\n * Falls back to direct execution if no context-storage implementation is registered or no span exists.\n */\nexport async function executeWithContext<T>(params: { span?: AnySpan; fn: () => Promise<T> }): Promise<T> {\n if (executeWithContextImpl) {\n return executeWithContextImpl(params);\n }\n const { span, fn } = params;\n if (span?.executeInContext) {\n return span.executeInContext(fn);\n }\n return fn();\n}\n\n/**\n * Execute a sync function within a span's tracing context.\n * Falls back to direct execution if no context-storage implementation is registered or no span exists.\n */\nexport function executeWithContextSync<T>(params: { span?: AnySpan; fn: () => T }): T {\n if (executeWithContextSyncImpl) {\n return executeWithContextSyncImpl(params);\n }\n const { span, fn } = params;\n if (span?.executeInContextSync) {\n return span.executeInContextSync(fn);\n }\n return fn();\n}\n\n/**\n * Resolve the spanId an observability signal should reference for a span.\n *\n * Signals (logs, metrics, and a suspending run's resume link) must name a span\n * that actually reached exporters. An internal or excluded span is never\n * stored, so referencing its raw id leaves the signal pointing at nothing:\n * log/metric span lookups 404, and a resumed run's exported children inherit a\n * dangling parentSpanId and land as orphans. `undefined` is a valid answer — it\n * omits the reference rather than pointing it at a span that does not exist.\n *\n * `getExportedSpanId` is optional on the `Span` interface, so the typeof guard\n * separates \"this implementation predates the method\" (keep the old behavior of\n * referencing the span's own id) from \"the method ran and found nothing\n * exportable\" (undefined). Without it the two collapse and custom span\n * implementations silently lose correlation.\n */\nexport function resolveExportedSpanId(\n span: { id?: string; getExportedSpanId?: () => string | undefined } | undefined | null,\n): string | undefined {\n if (!span) return undefined;\n return typeof span.getExportedSpanId === 'function' ? span.getExportedSpanId() : span.id;\n}\n\nconst NO_OP_TRACE_ID = 'no-op-trace';\nconst NO_OP_SPAN_ID = 'no-op';\n\n/**\n * The lineage a suspending run saves so that its resume continues it (see `resumeFrom`).\n * Takes the run's live span, or its exported span when another process persisted it.\n * An unsampled run saves nothing: its no-op span has no real trace for a resume to join.\n */\nexport function getResumeTracingContext(span: AnySpan | AnyExportedSpan | undefined): ResumeTracingContext | undefined {\n if (!span) return undefined;\n const live = 'exportSpan' in span;\n if (live ? !span.isValid : span.id === NO_OP_SPAN_ID) return undefined;\n const exported = live ? span.exportSpan(span.observabilityInstance?.getConfig?.().includeInternalSpans) : span;\n return {\n traceId: span.traceId,\n spanId: live ? resolveExportedSpanId(span) : span.id,\n parentSpanId: exported?.parentSpanId,\n resumedFromSpanId: exported && (exported.resumedFromSpanId ?? exported.id),\n externalParentSpanId: exported?.externalParentSpanId,\n };\n}\n\n/**\n * The context a suspending workflow run saves: its lineage plus the trace's sampling decision and\n * state, so a resume continues the trace as it was instead of deciding again. An unsampled run\n * saves only that decision, since its no-op span has no trace for a resume to join. Agent runs\n * save `getResumeTracingContext` alone and decide on resume.\n */\nexport function getWorkflowResumeTracingContext(\n span: AnySpan | AnyExportedSpan | undefined,\n): ResumeTracingContext | undefined {\n if (!span) return undefined;\n const lineage = getResumeTracingContext(span);\n if (!lineage) return { sampled: false };\n const traceState = 'exportSpan' in span ? span.traceState : (span as SpanSnapshot<SpanType>).traceState;\n if (!traceState) return { ...lineage, sampled: true };\n // `nestedUnderParent` describes the original call's own parent; a resume supplies its own.\n const { nestedUnderParent: _nested, ...ownTraceState } = traceState;\n return { ...lineage, sampled: true, traceState: ownTraceState };\n}\n\nfunction resumeInSavedTrace(saved: ResumeTracingContext | undefined, targetTraceId: string | undefined) {\n if (!saved?.traceId || saved.traceId === NO_OP_TRACE_ID) return undefined;\n if ((targetTraceId ?? saved.traceId) !== saved.traceId) return undefined;\n return {\n traceId: saved.traceId,\n parentSpanId: saved.spanId,\n resumedFromSpanId: saved.resumedFromSpanId ?? saved.spanId,\n externalParentSpanId: saved.externalParentSpanId,\n };\n}\n\n/**\n * Creates or gets a child span from existing tracing context or starts a new trace.\n * This helper consolidates the common pattern of creating spans that can either be:\n * 1. Children of an existing span (when tracingContext.currentSpan exists)\n * 2. New root spans (when no current span exists)\n *\n * @param options - Configuration object for span creation\n * @returns The created Span or undefined if tracing is disabled\n */\nexport function getOrCreateSpan<T extends SpanType>(options: GetOrCreateSpanOptions<T>): Span<T> | undefined {\n const {\n type,\n attributes,\n tracingContext,\n requestContext,\n tracingOptions,\n resumeFrom,\n resumedFromSpanId,\n samplingDecision,\n ...rest\n } = options;\n\n // tracingOptions.metadata takes precedence, but a key it merely names with\n // an `undefined` value must not erase the span's own metadata value.\n const metadata = {\n ...(rest.metadata ?? {}),\n ...Object.fromEntries(Object.entries(tracingOptions?.metadata ?? {}).filter(([, value]) => value !== undefined)),\n };\n const resumed = resumeInSavedTrace(resumeFrom, tracingContext?.currentSpan?.traceId ?? tracingOptions?.traceId);\n // The saved decision holds when the resume continues the saved trace, or when the original was unsampled and\n // the resume names no trace of its own. An explicit caller decision wins, as it does for resumed agent runs.\n const staysUnsampled = resumeFrom?.sampled === false && !tracingOptions?.traceId;\n const saved = resumeFrom && (resumed || staysUnsampled) ? resumeFrom : undefined;\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 requestContext,\n resumedFromSpanId: resumed?.resumedFromSpanId,\n });\n }\n\n // Otherwise, try to create a new root span\n const instance = options.mastra?.observability?.getSelectedInstance({ requestContext });\n // The resume call's own tracing options win field by field; the saved trace state fills what it left unset.\n const savedState = saved?.traceState;\n const rootTracingOptions: TracingOptions | undefined =\n resumed || savedState\n ? {\n ...tracingOptions,\n ...(resumed ? { traceId: resumed.traceId } : {}),\n ...(savedState\n ? {\n hideInput: tracingOptions?.hideInput ?? savedState.hideInput,\n hideOutput: tracingOptions?.hideOutput ?? savedState.hideOutput,\n requestContextKeys: tracingOptions?.requestContextKeys ?? savedState.requestContextKeys,\n }\n : {}),\n }\n : tracingOptions;\n\n return instance?.startSpan<T>({\n type,\n attributes,\n ...rest,\n metadata,\n requestContext,\n tracingOptions: rootTracingOptions,\n traceId: rootTracingOptions?.traceId,\n samplingDecision: samplingDecision ?? saved?.sampled,\n // A resumed run's parent is the suspended span, a Mastra span in the trace.\n parentSpanId: resumed ? resumed.parentSpanId : resumedFromSpanId,\n resumedFromSpanId: resumed?.resumedFromSpanId,\n // tracingOptions.parentSpanId is the public external-correlation channel;\n // the id belongs to the caller's tracing system, not Mastra's own parentage.\n externalParentSpanId: tracingOptions?.parentSpanId ?? resumed?.externalParentSpanId,\n customSamplerOptions: {\n requestContext,\n metadata,\n },\n });\n}\n\n/**\n * Builds `tracingOptions` that attach the next run as a child of a previous\n * run, for example an LLM judge under the run it scores. Pass the previous\n * run's result (or its `traceId` and `spanId`). When that run was not traced,\n * the given options are returned unchanged.\n */\nexport function nestUnderRun(run: TracingProperties, tracingOptions?: TracingOptions): TracingOptions | undefined {\n if (!run.traceId || !run.spanId) {\n return tracingOptions;\n }\n return { ...tracingOptions, traceId: run.traceId, parentSpanId: run.spanId, nestUnderParent: true };\n}\n\n/**\n * Returns the top-most non-internal span that would appear in exported tracing output.\n *\n * Public API results should use this span for trace/span correlation because internal Mastra\n * workflow spans are omitted from external exporters.\n */\nexport function getRootExportSpan(span?: AnySpan): AnySpan | undefined {\n if (!span?.isValid) {\n return undefined;\n }\n\n let current: AnySpan | undefined = span;\n let rootExportSpan: AnySpan | undefined = span.isInternal ? undefined : span;\n\n while (current?.parent) {\n current = current.parent;\n\n if (!current.isInternal) {\n rootExportSpan = current;\n }\n }\n\n return rootExportSpan;\n}\n\n/**\n * Resolves the best available entity type for a span-like record.\n *\n * Prefers an explicit `entityType` when present and valid, then falls back to the\n * span type for common observability entities.\n */\nexport function getEntityTypeForSpan(span: {\n entityType?: string | null;\n spanType?: SpanType | string | null;\n}): EntityType | undefined {\n if (span.entityType && entityTypeValues.has(span.entityType as EntityType)) {\n return span.entityType as EntityType;\n }\n\n switch (span.spanType) {\n case SpanType.AGENT_RUN:\n return EntityType.AGENT;\n case SpanType.RAG_INGESTION:\n return EntityType.RAG_INGESTION;\n case SpanType.SCORER_RUN:\n case SpanType.SCORER_STEP:\n return EntityType.SCORER;\n case SpanType.WORKFLOW_RUN:\n return EntityType.WORKFLOW_RUN;\n case SpanType.WORKFLOW_STEP:\n return EntityType.WORKFLOW_STEP;\n case SpanType.TOOL_CALL:\n case SpanType.MCP_TOOL_CALL:\n case SpanType.PROVIDER_TOOL_CALL:\n return EntityType.TOOL;\n case SpanType.MCP_SERVER_REQUEST:\n return EntityType.MCP_SERVER;\n case SpanType.PROCESSOR_RUN:\n return EntityType.OUTPUT_PROCESSOR;\n case SpanType.CLASSIFIER_EVALUATION:\n return EntityType.CLASSIFIER;\n default:\n return undefined;\n }\n}\n\n/**\n * Time to first chunk in milliseconds for any span whose attributes carry\n * `completionStartTime`, measured from that span's own start. Undefined when\n * the span never saw a chunk.\n */\nexport function getTimeToFirstChunkMs(span: {\n startTime: Date | string;\n attributes?: object | undefined;\n}): number | undefined {\n const completionStartTime = (span.attributes as { completionStartTime?: Date | string } | undefined)\n ?.completionStartTime;\n if (!completionStartTime) return undefined;\n const ms = new Date(completionStartTime).getTime() - new Date(span.startTime).getTime();\n // Clock skew between workers (durable runs) can put the first chunk before the start.\n return Number.isNaN(ms) ? undefined : Math.max(0, ms);\n}\n"],"mappings":"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"}