@mastra/core
Version:
1 lines • 139 kB
Source Map (JSON)
{"version":3,"file":"observability-fxVZWiFW.cjs","names":["z","getOrCreateSpan","EntityType"],"sources":["../src/observability/types/outcome.ts","../src/observability/outcome-schema.ts","../src/observability/execution-outcome.ts","../src/loop/shared/execution-outcome.ts","../src/observability/no-op.ts","../src/observability/context-factory.ts","../src/observability/context.ts","../src/observability/types/core.ts","../src/observability/w3c.ts","../src/observability/processor-span-record.ts","../src/observability/span-record.ts","../src/observability/rag-ingestion.ts","../src/observability/span-previews.ts","../src/observability/usage.ts"],"sourcesContent":["/** An individual execution's result, reported by its runtime (OBS-724). */\nexport const SPAN_OUTCOMES = [\n 'success',\n 'error',\n 'abort',\n 'interrupted',\n 'suspend',\n 'limit',\n 'blocked',\n 'unknown',\n] as const;\nexport type SpanOutcome = (typeof SPAN_OUTCOMES)[number];\n\n/** Supplemental facts for runtime/model failures; never used to infer an outcome. */\nexport type SpanFailureContext = {\n provider?: string;\n errorCode?: string;\n retryable?: boolean;\n};\n\n/** Context for the initial OBS-724 reason codes. Runtime producers supply these facts. */\nexport interface SpanStopReasonContextMap {\n max_steps: { maxSteps?: number; completedSteps?: number };\n max_tokens: { maxTokens?: number };\n timeout: { timeoutMs?: number; timeoutType?: 'step' | 'total' | 'firstChunk' };\n runtime_error: SpanFailureContext;\n model_error: SpanFailureContext;\n caller_cancelled: Record<string, never>;\n signal_received: { signalId?: string; signalType?: 'user' | 'state' | 'reactive' | 'notification' };\n observer_failed: {\n observerSpanId?: string;\n /** Keep the observer's own result distinct from the interrupted primary execution. */\n causeOutcome?: SpanOutcome;\n causeStopReason?: SpanStopReason;\n };\n context_window_exceeded: { provider?: string; errorCode?: string; contextWindow?: number };\n guardrail: { processorId?: string };\n content_filter: { provider?: string };\n approval_required: { toolCallId?: string; toolName?: string };\n stop_condition: Record<string, never>;\n iteration_hook: { feedbackCompleted?: boolean };\n delegation_bail: { causeOutcome?: SpanOutcome; causeStopReason?: SpanStopReason };\n authentication: SpanFailureContext;\n authorization: SpanFailureContext;\n}\n\nexport type SpanStopReason = keyof SpanStopReasonContextMap;\n\n/** Exhaustive reason registry shared by runtime validation and storage consumers. */\nexport const SPAN_STOP_REASONS = {\n max_steps: true,\n max_tokens: true,\n timeout: true,\n runtime_error: true,\n model_error: true,\n caller_cancelled: true,\n signal_received: true,\n observer_failed: true,\n context_window_exceeded: true,\n guardrail: true,\n content_filter: true,\n approval_required: true,\n stop_condition: true,\n iteration_hook: true,\n delegation_bail: true,\n authentication: true,\n authorization: true,\n} as const satisfies Record<SpanStopReason, true>;\n\n/** @internal Runtime tripwire input. Its payload is never copied into exported stop-reason context. */\nexport interface SpanTripwireContext {\n processorId?: string;\n /** Existing human-readable tripwire explanation, not a machine stop reason. */\n reason?: string;\n retry?: boolean;\n metadata?: unknown;\n}\n\n/** Flat tooltip facts only: at most three scalar fields, with strings bounded to 128 characters. */\nexport type SpanStopReasonContext<Reason extends SpanStopReason = SpanStopReason> = SpanStopReasonContextMap[Reason];\n\n/** Narrow this envelope by stopReason to access its cause-specific context. */\nexport type SpanTermination = { outcome: SpanOutcome } & (\n | {\n [Reason in SpanStopReason]: {\n stopReason: Reason;\n stopReasonContext?: SpanStopReasonContext<Reason> | null;\n };\n }[SpanStopReason]\n | { stopReason?: null; stopReasonContext?: null }\n);\n\n/** Native fields shared by live spans, snapshots, exports and lifecycle options.\n * Custom producers retain arbitrary values; framework producers use SpanTermination.\n */\nexport interface SpanOutcomeFields {\n /** Null or absence means no recorded outcome. Use endTime to determine completion. */\n outcome?: string | null;\n /** Nullable machine-readable cause, supplied at the authoritative runtime boundary. */\n stopReason?: string | null;\n stopReasonContext?: Record<string, unknown> | null;\n}\n\n/** Typed metadata retained when an OM processor interrupts its primary agent. */\nexport interface ObserverFailureMetadata {\n observerFailure: {\n observerSpanId?: string;\n cause: SpanTermination;\n };\n}\n","import { z } from 'zod/v4';\nimport { SPAN_OUTCOMES, SPAN_STOP_REASONS } from './types/outcome';\nimport type { SpanStopReason, SpanStopReasonContext, SpanTermination } from './types/outcome';\n\nconst label = z.string().max(128).optional();\nconst reason = z.enum(Object.keys(SPAN_STOP_REASONS) as [SpanStopReason, ...SpanStopReason[]]);\nconst failure = { provider: label, errorCode: label, retryable: z.boolean().optional() };\nconst cause = { causeOutcome: z.enum(SPAN_OUTCOMES).optional(), causeStopReason: reason.optional() };\n\n// Select a small, flat context using the envelope's stopReason. Never copy diagnostic payloads.\nconst contexts = {\n max_steps: z.strictObject({ maxSteps: z.number().optional(), completedSteps: z.number().optional() }),\n max_tokens: z.strictObject({ maxTokens: z.number().optional() }),\n timeout: z.strictObject({\n timeoutMs: z.number().optional(),\n timeoutType: z.enum(['step', 'total', 'firstChunk']).optional(),\n }),\n runtime_error: z.strictObject(failure),\n model_error: z.strictObject(failure),\n caller_cancelled: z.strictObject({}),\n observer_failed: z.strictObject({ observerSpanId: label, ...cause }),\n context_window_exceeded: z.strictObject({ provider: label, errorCode: label, contextWindow: z.number().optional() }),\n guardrail: z.strictObject({ processorId: label }),\n content_filter: z.strictObject({ provider: label }),\n approval_required: z.strictObject({ toolCallId: label, toolName: label }),\n signal_received: z.strictObject({\n signalId: label,\n signalType: z.enum(['user', 'state', 'reactive', 'notification']).optional(),\n }),\n stop_condition: z.strictObject({}),\n iteration_hook: z.strictObject({ feedbackCompleted: z.boolean().optional() }),\n delegation_bail: z.strictObject(cause),\n authentication: z.strictObject(failure),\n authorization: z.strictObject(failure),\n} satisfies { [Reason in SpanStopReason]: z.ZodType<SpanStopReasonContext<Reason>> };\n\n/** @internal Allowlist tooltip facts for framework producers, including untyped runtime inputs. */\nexport function compactStopReasonContext<Reason extends SpanStopReason>(\n stopReason: Reason | null | undefined,\n context: unknown,\n): SpanStopReasonContext<Reason> | null {\n if (!stopReason || !Object.hasOwn(contexts, stopReason) || !context || typeof context !== 'object') return null;\n try {\n const result: Record<string, unknown> = {};\n for (const [key, schema] of Object.entries(contexts[stopReason].shape)) {\n const value = (context as Record<string, unknown>)[key];\n // Omit oversized identifiers rather than truncate them into broken links.\n const parsed = schema.safeParse(value);\n if (parsed.success && parsed.data !== undefined) result[key] = parsed.data;\n }\n return Object.keys(result).length ? (result as SpanStopReasonContext<Reason>) : null;\n } catch {\n // Optional observability details must never change execution behavior.\n return null;\n }\n}\n\nfunction termination<Reason extends SpanStopReason>(stopReason: Reason) {\n return z.object({\n outcome: z.enum(SPAN_OUTCOMES),\n stopReason: z.literal(stopReason),\n stopReasonContext: (contexts[stopReason] as z.ZodType<SpanStopReasonContext<Reason>>).nullish(),\n });\n}\n\nexport const spanTerminationSchema = z.union([\n ...(Object.keys(SPAN_STOP_REASONS) as SpanStopReason[]).map(termination),\n z.object({ outcome: z.enum(SPAN_OUTCOMES), stopReason: z.null().optional(), stopReasonContext: z.null().optional() }),\n]) as z.ZodType<SpanTermination>;\n","import { compactStopReasonContext } from './outcome-schema';\nimport { SPAN_OUTCOMES, SPAN_STOP_REASONS } from './types/outcome';\nimport type { SpanOutcome, SpanStopReason, SpanTermination, SpanTripwireContext } from './types/outcome';\n\n/** Read a provider's structured code without inferring a cause from diagnostic text. */\nfunction providerFailureCode(value: Record<string | symbol, unknown>): string | undefined {\n if (typeof value.code === 'string') return value.code;\n let data = value.data;\n if (data == null && typeof value.responseBody === 'string') {\n try {\n data = JSON.parse(value.responseBody);\n } catch {\n return undefined;\n }\n }\n if (!data || typeof data !== 'object') return undefined;\n const record = data as Record<string, unknown>;\n const error = record.error && typeof record.error === 'object' ? (record.error as Record<string, unknown>) : record;\n return typeof error.code === 'string' ? error.code : undefined;\n}\n\n/** @internal Classify explicit failure facts, including wrapped/serialized causes. Never match error-message text. */\nexport function executionFailureTermination(\n error: unknown,\n layer: 'runtime_error' | 'model_error' = 'runtime_error',\n): SpanTermination {\n // Runs on failure paths: a throwing getter or Proxy trap must not replace the original error.\n try {\n const termination = classifyExecutionFailure(error, layer);\n return {\n ...termination,\n stopReasonContext: compactStopReasonContext(termination.stopReason, termination.stopReasonContext),\n } as SpanTermination;\n } catch {\n return { outcome: 'error', stopReason: layer };\n }\n}\n\nfunction classifyExecutionFailure(error: unknown, layer: 'runtime_error' | 'model_error'): SpanTermination {\n const seen = new Set<unknown>();\n let current = error;\n let failure: Record<string, unknown> | undefined;\n let modelFailure = layer === 'model_error';\n while (current && typeof current === 'object' && !seen.has(current)) {\n seen.add(current);\n const value = current as Record<string | symbol, unknown>;\n // Durable workflow transports wrap the original serialized error in a failed result.\n // The envelope itself has no diagnostic message or provider classification.\n if (value.status === 'failed' && value.error && typeof value.error === 'object') {\n current = value.error;\n continue;\n }\n // TripWire's serialized name distinguishes it from user errors with similar fields.\n // Durable transports may still report the public workflow status as `failed`.\n if (\n value.name === 'TripWire' &&\n (value.processorId === undefined || typeof value.processorId === 'string') &&\n value.options &&\n typeof value.options === 'object' &&\n typeof value.message === 'string'\n ) {\n const options = value.options as { retry?: boolean; metadata?: unknown };\n return tripwireTermination({ processorId: value.processorId, reason: value.message, ...options });\n }\n failure = value;\n if (value.name === 'MastraTimeoutError' && typeof value.timeoutMs === 'number') {\n return {\n outcome: 'limit',\n stopReason: 'timeout',\n stopReasonContext: {\n timeoutMs: value.timeoutMs,\n ...(value.timeoutType === 'step' || value.timeoutType === 'total' || value.timeoutType === 'firstChunk'\n ? { timeoutType: value.timeoutType }\n : {}),\n },\n };\n }\n if (value.name === 'FGADeniedError') {\n return { outcome: 'blocked', stopReason: 'authorization' };\n }\n const apiError = value[Symbol.for('vercel.ai.error.AI_APICallError')] === true || value.name === 'AI_APICallError';\n // The LLM domain also wraps user callbacks and runtime hooks; it alone\n // does not establish a provider failure.\n if (apiError) modelFailure = true;\n if (apiError && (value.statusCode === 401 || value.statusCode === 403)) {\n const reason = value.statusCode === 401 ? 'authentication' : 'authorization';\n return {\n outcome: 'blocked',\n stopReason: reason,\n stopReasonContext: {\n errorCode: String(value.statusCode),\n provider: typeof value.provider === 'string' ? value.provider : undefined,\n },\n };\n }\n if (apiError) {\n const errorCode = providerFailureCode(value);\n if (errorCode === 'content_filter') {\n return {\n outcome: 'blocked',\n stopReason: 'content_filter',\n stopReasonContext: { provider: typeof value.provider === 'string' ? value.provider : undefined },\n };\n }\n if (errorCode === 'context_length_exceeded' || errorCode === 'context_window_exceeded') {\n return {\n outcome: 'limit',\n stopReason: 'context_window_exceeded',\n stopReasonContext: { errorCode },\n };\n }\n }\n current = value.cause;\n }\n const reason = modelFailure ? 'model_error' : 'runtime_error';\n return {\n outcome: 'error',\n stopReason: reason,\n stopReasonContext: {\n provider: typeof failure?.provider === 'string' ? failure.provider : undefined,\n errorCode:\n typeof failure?.code === 'string' ? failure.code : typeof failure?.id === 'string' ? failure.id : undefined,\n retryable: typeof failure?.isRetryable === 'boolean' ? failure.isRetryable : undefined,\n },\n };\n}\n\n/** Link to the observer's diagnostics without copying its payload into the interrupted span. */\nexport function tripwireTermination(tripwire?: SpanTripwireContext): SpanTermination {\n try {\n const metadata = tripwire?.metadata;\n const observer =\n metadata && typeof metadata === 'object' && 'observerFailure' in metadata ? metadata.observerFailure : undefined;\n if (\n observer &&\n typeof observer === 'object' &&\n 'cause' in observer &&\n observer.cause &&\n typeof observer.cause === 'object'\n ) {\n const cause = observer.cause as { outcome?: unknown; stopReason?: unknown };\n if (\n SPAN_OUTCOMES.includes(cause.outcome as SpanOutcome) &&\n cause.outcome !== 'success' &&\n cause.outcome !== 'suspend'\n ) {\n return {\n outcome: 'interrupted',\n stopReason: 'observer_failed',\n stopReasonContext: compactStopReasonContext('observer_failed', {\n observerSpanId: 'observerSpanId' in observer ? observer.observerSpanId : undefined,\n causeOutcome: cause.outcome,\n causeStopReason:\n typeof cause.stopReason === 'string' && Object.hasOwn(SPAN_STOP_REASONS, cause.stopReason)\n ? (cause.stopReason as SpanStopReason)\n : undefined,\n }),\n };\n }\n }\n return {\n outcome: 'blocked',\n stopReason: 'guardrail',\n stopReasonContext: compactStopReasonContext('guardrail', { processorId: tripwire?.processorId }),\n };\n } catch {\n return { outcome: 'blocked', stopReason: 'guardrail' };\n }\n}\n","import { tripwireTermination } from '../../observability/execution-outcome';\nimport { compactStopReasonContext } from '../../observability/outcome-schema';\nimport type { SpanTermination, SpanTripwireContext } from '../../observability/types/outcome';\nimport type { ContinuationStopCause } from './continuation-core';\n\nexport { executionFailureTermination } from '../../observability/execution-outcome';\n\n/**\n * @internal\n * Classify a settled agent loop using its runtime stop boundary. A provider\n * finish reason refines the result; it cannot establish successful execution\n * without a continuation decision. Call only after finish-time work succeeds.\n */\nexport function agentLoopTermination(input: {\n stopCause?: ContinuationStopCause;\n delegationFailure?: SpanTermination;\n finishReason?: string;\n maxSteps?: number;\n suspension?: { approvalRequired: boolean; toolCallId?: string; toolName?: string };\n tripwire?: SpanTripwireContext;\n}): SpanTermination {\n const { stopCause, finishReason, maxSteps, tripwire } = input;\n if (tripwire || finishReason === 'tripwire') return tripwireTermination(tripwire);\n if (finishReason === 'suspended') {\n const suspension = input.suspension;\n if (suspension?.approvalRequired)\n return {\n outcome: 'suspend',\n stopReason: 'approval_required',\n stopReasonContext: compactStopReasonContext('approval_required', {\n toolCallId: suspension.toolCallId,\n toolName: suspension.toolName,\n }),\n };\n return { outcome: 'suspend', stopReason: null, stopReasonContext: null };\n }\n if (finishReason === 'length') return { outcome: 'limit', stopReason: 'max_tokens' };\n if (finishReason === 'content-filter') return { outcome: 'blocked', stopReason: 'content_filter' };\n if (finishReason === 'abort' || finishReason === 'aborted')\n return { outcome: 'abort', stopReason: 'caller_cancelled' };\n if (finishReason === 'error') return { outcome: 'error', stopReason: 'model_error' };\n switch (stopCause) {\n case 'max_steps':\n return { outcome: 'limit', stopReason: 'max_steps', stopReasonContext: { maxSteps } };\n case 'stop_condition':\n return { outcome: 'success', stopReason: 'stop_condition' };\n case 'iteration_hook':\n case 'feedback_complete':\n return {\n outcome: 'success',\n stopReason: 'iteration_hook',\n stopReasonContext: {\n feedbackCompleted: stopCause === 'feedback_complete',\n },\n };\n case 'delegation':\n if (input.delegationFailure)\n return {\n outcome: 'interrupted',\n stopReason: 'delegation_bail',\n stopReasonContext: {\n causeOutcome: input.delegationFailure.outcome,\n causeStopReason: input.delegationFailure.stopReason ?? undefined,\n },\n };\n return { outcome: 'success', stopReason: 'delegation_bail' };\n case 'model_finished':\n // Unknown/unrecognized provider endings do not prove normal completion.\n if (finishReason === 'stop' || finishReason === 'tool-calls') {\n return { outcome: 'success', stopReason: null, stopReasonContext: null };\n }\n }\n return { outcome: 'unknown', stopReason: null, stopReasonContext: null };\n}\n","import type { Mastra } from '..';\nimport type { IMastraLogger } from '../logger';\nimport type {\n CorrelationContext,\n ConfigSelector,\n ConfigSelectorOptions,\n Counter,\n FeedbackInput,\n Gauge,\n Histogram,\n LoggerContext,\n MetricsContext,\n ObservabilityEntrypoint,\n ObservabilityInstance,\n RecordedTrace,\n ScoreInput,\n TracingContext,\n} from './types';\n\n// ============================================================================\n// No-Op Metric Instruments\n// ============================================================================\n\nconst noOpCounter: Counter = {\n add() {},\n};\n\nconst noOpGauge: Gauge = {\n set() {},\n};\n\nconst noOpHistogram: Histogram = {\n record() {},\n};\n\n// ============================================================================\n// No-Op TracingContext\n// ============================================================================\n\n/**\n * No-op tracing context used when observability is not configured.\n */\nexport const noOpTracingContext: TracingContext = {\n currentSpan: undefined,\n};\n\n// ============================================================================\n// No-Op LoggerContext\n// ============================================================================\n\n/**\n * No-op logger context that silently discards all log calls.\n * Used when observability is not configured.\n */\nexport const noOpLoggerContext: LoggerContext = {\n debug() {},\n info() {},\n warn() {},\n error() {},\n fatal() {},\n};\n\n// ============================================================================\n// No-Op MetricsContext\n// ============================================================================\n\n/**\n * No-op metrics context that silently discards all metric operations.\n * Used when observability is not configured.\n */\nexport const noOpMetricsContext: MetricsContext = {\n emit() {},\n counter() {\n return noOpCounter;\n },\n gauge() {\n return noOpGauge;\n },\n histogram() {\n return noOpHistogram;\n },\n};\n\n// ============================================================================\n// No-Op Observability\n// ============================================================================\n\n/** No-op observability entrypoint that silently discards all operations. */\nexport class NoOpObservability implements ObservabilityEntrypoint {\n setMastraContext(_options: { mastra: Mastra }): void {}\n\n setLogger(_options: { logger: IMastraLogger }): void {}\n\n getSelectedInstance(_options: ConfigSelectorOptions): ObservabilityInstance | undefined {\n return undefined;\n }\n\n async getRecordedTrace(_args: { traceId: string }): Promise<RecordedTrace | null> {\n return null;\n }\n\n async addScore(_args: {\n traceId?: string;\n spanId?: string;\n correlationContext?: CorrelationContext;\n score: ScoreInput;\n }): Promise<void> {}\n\n async addFeedback(_args: {\n traceId?: string;\n spanId?: string;\n correlationContext?: CorrelationContext;\n feedback: FeedbackInput;\n }): Promise<void> {}\n\n registerInstance(_name: string, _instance: ObservabilityInstance, _isDefault = false): void {}\n\n getInstance(_name: string): ObservabilityInstance | undefined {\n return undefined;\n }\n\n getDefaultInstance(): ObservabilityInstance | undefined {\n return undefined;\n }\n\n listInstances(): ReadonlyMap<string, ObservabilityInstance> {\n return new Map();\n }\n\n unregisterInstance(_name: string): boolean {\n return false;\n }\n\n hasInstance(_name: string): boolean {\n return false;\n }\n\n setConfigSelector(_selector: ConfigSelector): void {}\n\n clear(): void {}\n\n async flush(): Promise<void> {}\n\n async shutdown(): Promise<void> {}\n}\n","// packages/core/src/observability/context-factory.ts\n\nimport { noOpLoggerContext, noOpMetricsContext, noOpTracingContext } from './no-op';\nimport type { LoggerContext, MetricsContext, ObservabilityContext, TracingContext } from './types';\n\n// ============================================================================\n// Context Derivation\n// ============================================================================\n\n/**\n * Derives a LoggerContext from the current span's ObservabilityInstance.\n * Falls back to no-op when there is no span or the instance doesn't support logging.\n */\nfunction deriveLoggerContext(tracing: TracingContext): LoggerContext {\n const span = tracing.currentSpan;\n return span?.observabilityInstance?.getLoggerContext?.(span) ?? noOpLoggerContext;\n}\n\n/**\n * Derives a MetricsContext from the current span's ObservabilityInstance.\n * Falls back to no-op when there is no span or the instance doesn't support metrics.\n */\nfunction deriveMetricsContext(tracing: TracingContext): MetricsContext {\n const span = tracing.currentSpan;\n return span?.observabilityInstance?.getMetricsContext?.(span) ?? noOpMetricsContext;\n}\n\n// ============================================================================\n// Context Factory\n// ============================================================================\n\n/**\n * Creates an observability context with real or no-op implementations for\n * tracing, logging, and metrics.\n *\n * When a TracingContext with a current span is provided, the logger and metrics\n * contexts are derived from the span's ObservabilityInstance so that log entries\n * and metric data points are automatically correlated to the active trace.\n *\n * @param tracingContext - TracingContext with current span, or undefined for no-op\n * @returns ObservabilityContext with all three signals (tracing, logger, metrics)\n */\nexport function createObservabilityContext(tracingContext?: TracingContext): ObservabilityContext {\n const tracing = tracingContext ?? noOpTracingContext;\n\n return {\n tracing,\n loggerVNext: deriveLoggerContext(tracing),\n metrics: deriveMetricsContext(tracing),\n tracingContext: tracing, // alias — preferred at forwarding sites\n };\n}\n\n/**\n * Resolves a partial observability context (from execute params) into a\n * complete ObservabilityContext with no-op defaults for any missing fields.\n *\n * Explicitly provided logger/metrics contexts are preserved (e.g. when set\n * upstream). When missing, they are derived from the tracing context's span,\n * following the same derivation logic as createObservabilityContext().\n *\n * @param partial - Partial context from ExecuteFunctionParams\n * @returns Complete ObservabilityContext\n */\nexport function resolveObservabilityContext(partial: Partial<ObservabilityContext>): ObservabilityContext {\n const tracing = partial.tracing ?? partial.tracingContext ?? noOpTracingContext;\n\n return {\n tracing,\n loggerVNext: partial.loggerVNext ?? deriveLoggerContext(tracing),\n metrics: partial.metrics ?? deriveMetricsContext(tracing),\n tracingContext: tracing, // alias — preferred at forwarding sites\n };\n}\n","/**\n * Tracing Context Integration\n *\n * This module provides automatic tracing context propagation throughout Mastra's execution contexts.\n * It uses JavaScript Proxies to transparently wrap Mastra, Agent, and Workflow instances so that\n * tracing context is automatically injected without requiring manual passing by users.\n */\n\nimport type { MastraPrimitives } from '../action';\nimport type { Agent } from '../agent';\nimport type { Mastra } from '../mastra';\nimport type { Workflow } from '../workflows';\nimport { createObservabilityContext } from './context-factory';\nimport type { TracingContext, AnySpan } from './types';\n\nconst AGENT_GETTERS = ['getAgent', 'getAgentById'];\nconst AGENT_METHODS_TO_WRAP = ['generate', 'stream', 'generateLegacy', 'streamLegacy'];\n\nconst WORKFLOW_GETTERS = ['getWorkflow', 'getWorkflowById'];\nconst WORKFLOW_METHODS_TO_WRAP = ['execute', 'createRun', 'createRun'];\n\n/**\n * Maps a tracing proxy back to the instance it wraps. `wrapMastra` returns a\n * Proxy that forwards property reads but is a distinct object identity from its\n * target, so identity-sensitive lookups keyed on the Mastra instance would treat\n * the proxy as a different Mastra. Cycles are impossible: a proxy's recorded\n * target always existed before the proxy was created.\n */\nconst tracingProxyTargets = new WeakMap<object, object>();\n\n/**\n * Helper function to detect NoOp spans to avoid unnecessary wrapping\n */\nfunction isNoOpSpan(span: AnySpan): boolean {\n // Check if this is a NoOp span implementation\n return span.constructor.name === 'NoOpSpan' || (span as any).__isNoOp === true;\n}\n\n/**\n * Checks to see if a passed object is an actual instance of Mastra\n * (for the purposes of wrapping it for Tracing)\n */\nexport function isMastra<T extends Mastra | (Mastra & MastraPrimitives) | MastraPrimitives>(mastra: T): boolean {\n const hasAgentGetters = AGENT_GETTERS.every(method => typeof (mastra as any)?.[method] === 'function');\n const hasWorkflowGetters = WORKFLOW_GETTERS.every(method => typeof (mastra as any)?.[method] === 'function');\n\n return hasAgentGetters && hasWorkflowGetters;\n}\n\n/**\n * Creates a tracing-aware Mastra proxy that automatically injects\n * tracing context into agent and workflow method calls\n */\nexport function wrapMastra<T extends Mastra | (Mastra & MastraPrimitives) | MastraPrimitives>(\n mastra: T,\n tracingContext: TracingContext,\n): T {\n // Don't wrap if no current span or if using NoOp span\n if (!tracingContext.currentSpan || isNoOpSpan(tracingContext.currentSpan)) {\n return mastra;\n }\n\n // Check if this object has the methods we want to wrap - if not, return as is\n if (!isMastra(mastra)) {\n return mastra;\n }\n\n try {\n const proxy = new Proxy(mastra, {\n get(target, prop) {\n try {\n if (AGENT_GETTERS.includes(prop as string)) {\n return (...args: any[]) => {\n const agent = (target as any)[prop](...args);\n return wrapAgent(agent, tracingContext);\n };\n }\n\n // Wrap workflow getters\n if (WORKFLOW_GETTERS.includes(prop as string)) {\n return (...args: any[]) => {\n const workflow = (target as any)[prop](...args);\n return wrapWorkflow(workflow, tracingContext);\n };\n }\n\n // Pass through all other methods unchanged - bind functions to preserve 'this' context\n const value = (target as any)[prop];\n return typeof value === 'function' ? value.bind(target) : value;\n } catch (error) {\n console.warn('Tracing: Failed to wrap method, falling back to original', error);\n const value = (target as any)[prop];\n return typeof value === 'function' ? value.bind(target) : value;\n }\n },\n });\n tracingProxyTargets.set(proxy, mastra);\n return proxy;\n } catch (error) {\n console.warn('Tracing: Failed to create proxy, using original Mastra instance', error);\n return mastra;\n }\n}\n\n/**\n * Resolve a tracing proxy back to the underlying instance. Returns the argument\n * unchanged when it is not a proxy this module created. Transitive: a tool\n * executed inside a traced workflow step receives an already-wrapped mastra and\n * `tools/tool-builder/builder.ts` wraps it again, so nesting is real.\n */\nexport function unwrapMastraTracingProxy<T>(mastra: T): T {\n let current: any = mastra;\n let target = tracingProxyTargets.get(current);\n while (target) {\n current = target;\n target = tracingProxyTargets.get(current);\n }\n return current as T;\n}\n\n/**\n * Creates a tracing-aware Agent proxy that automatically injects\n * tracing context into generation method calls\n */\nfunction wrapAgent<T extends Agent>(agent: T, tracingContext: TracingContext): T {\n // Don't wrap if no current span or if using NoOp span\n if (!tracingContext.currentSpan || isNoOpSpan(tracingContext.currentSpan)) {\n return agent;\n }\n\n try {\n return new Proxy(agent, {\n get(target, prop) {\n try {\n if (AGENT_METHODS_TO_WRAP.includes(prop as string)) {\n return (input: any, options: any = {}) => {\n return (target as any)[prop](input, {\n ...options,\n ...createObservabilityContext(tracingContext),\n });\n };\n }\n\n // Bind functions to preserve 'this' context for private member access\n const value = (target as any)[prop];\n return typeof value === 'function' ? value.bind(target) : value;\n } catch (error) {\n console.warn('Tracing: Failed to wrap agent method, falling back to original', error);\n const value = (target as any)[prop];\n return typeof value === 'function' ? value.bind(target) : value;\n }\n },\n });\n } catch (error) {\n console.warn('Tracing: Failed to create agent proxy, using original instance', error);\n return agent;\n }\n}\n\n/**\n * Creates a tracing-aware Workflow proxy that automatically injects\n * tracing context into execution method calls\n */\nfunction wrapWorkflow<T extends Workflow>(workflow: T, tracingContext: TracingContext): T {\n // Don't wrap if no current span or if using NoOp span\n if (!tracingContext.currentSpan || isNoOpSpan(tracingContext.currentSpan)) {\n return workflow;\n }\n\n try {\n return new Proxy(workflow, {\n get(target, prop) {\n try {\n // Wrap workflow execution methods with tracing context\n if (WORKFLOW_METHODS_TO_WRAP.includes(prop as string)) {\n // Handle createRun and createRun methods differently\n if (prop === 'createRun' || prop === 'createRun') {\n return async (options: any = {}) => {\n const run = await (target as any)[prop](options);\n return run ? wrapRun(run, tracingContext) : run;\n };\n }\n\n // Handle other methods like execute\n return (input: any, options: any = {}) => {\n return (target as any)[prop](input, {\n ...options,\n ...createObservabilityContext(tracingContext),\n });\n };\n }\n\n // Bind functions to preserve 'this' context for private member access\n const value = (target as any)[prop];\n return typeof value === 'function' ? value.bind(target) : value;\n } catch (error) {\n console.warn('Tracing: Failed to wrap workflow method, falling back to original', error);\n const value = (target as any)[prop];\n return typeof value === 'function' ? value.bind(target) : value;\n }\n },\n });\n } catch (error) {\n console.warn('Tracing: Failed to create workflow proxy, using original instance', error);\n return workflow;\n }\n}\n\n/**\n * Creates a tracing-aware Run proxy that automatically injects\n * tracing context into start method calls\n */\nfunction wrapRun<T extends object>(run: T, tracingContext: TracingContext): T {\n // Don't wrap if no current span or if using NoOp span\n if (!tracingContext.currentSpan || isNoOpSpan(tracingContext.currentSpan)) {\n return run;\n }\n\n try {\n return new Proxy(run, {\n get(target, prop) {\n try {\n if (prop === 'start') {\n return (startOptions: any = {}) => {\n return (target as any).start({\n ...startOptions,\n ...createObservabilityContext(startOptions.tracingContext ?? tracingContext),\n });\n };\n }\n\n // Pass through all other properties and methods unchanged\n const value = (target as any)[prop];\n return typeof value === 'function' ? value.bind(target) : value;\n } catch (error) {\n console.warn('Tracing: Failed to wrap run method, falling back to original', error);\n const value = (target as any)[prop];\n return typeof value === 'function' ? value.bind(target) : value;\n }\n },\n });\n } catch (error) {\n console.warn('Tracing: Failed to create run proxy, using original instance', error);\n return run;\n }\n}\n","/**\n * Top-level observability infrastructure types.\n *\n * This file contains the core observability interfaces for managing instances,\n * exporters, bridges, configuration, event bus, and the context mixin.\n *\n * For tracing-specific types (spans, span types, attributes, etc.), see tracing.ts.\n */\nimport type { IMastraLogger } from '../../logger';\nimport type { Mastra } from '../../mastra';\nimport type { RequestContext } from '../../request-context';\nimport type { ClientObservabilityProxy } from './client';\nimport type {\n FeedbackEvent,\n FeedbackInput,\n FeedbackReplacementEvent,\n FeedbackReplacementInput,\n FeedbackReviewStatusInput,\n FeedbackReviewStatusEvent,\n} from './feedback';\nimport type { LoggerContext, LogEvent } from './logging';\nimport type { MetricsContext, MetricEvent } from './metrics';\nimport type { ScoreEvent, ScoreInput } from './scores';\nimport type {\n AnySpan,\n AnyExportedSpan,\n RecordedTrace,\n CreateSpanOptions,\n EntityType,\n ExportedSpan,\n Span,\n SpanIds,\n SpanSnapshot,\n SpanOutputProcessor,\n SpanType,\n StartSpanOptions,\n TracingContext,\n TracingEvent,\n} from './tracing';\n\n// ============================================================================\n// ObservabilityContext\n// ============================================================================\n\n/**\n * Canonical observability correlation and execution context.\n * These fields can travel alongside observability signals without being encoded in labels.\n */\nexport interface CorrelationContext {\n /**\n * @deprecated Use the signal's top-level `traceId` instead.\n */\n traceId?: string;\n /**\n * @deprecated Use the signal's top-level `spanId` instead.\n */\n spanId?: string;\n entityType?: EntityType;\n entityId?: string;\n entityName?: string;\n entityVersionId?: string;\n parentEntityType?: EntityType;\n parentEntityId?: string;\n parentEntityName?: string;\n parentEntityVersionId?: string;\n rootEntityType?: EntityType;\n rootEntityId?: string;\n rootEntityName?: string;\n rootEntityVersionId?: string;\n userId?: string;\n organizationId?: string;\n resourceId?: string;\n runId?: string;\n sessionId?: string;\n threadId?: string;\n requestId?: string;\n environment?: string;\n source?: string;\n serviceName?: string;\n experimentId?: string;\n tags?: string[];\n}\n\n/**\n * Mixin interface that provides unified observability access.\n * All execution contexts (tools, workflow steps, processors) extend this\n * to gain access to tracing, logging, and metrics.\n *\n * ## Naming conventions\n *\n * `tracingContext` is the **source** — it represents your position in the span tree.\n * Creating a child span produces a new `tracingContext` with that child as `currentSpan`.\n *\n * `loggerVNext` and `metrics` are **derived** — they are rebuilt from the current span so that\n * log entries and metric data points are automatically correlated to the active trace:\n *\n * ```\n * tracingContext → create child span → new tracingContext\n * → new loggerVNext (correlated to child span)\n * → new metrics (tagged with child span metadata)\n * ```\n *\n * The short names (`tracing`, `loggerVNext`, `metrics`) read naturally at **usage sites**:\n * `tracing.createSpan()`, `loggerVNext.info()`, `metrics.record()`.\n *\n * `loggerVNext` uses the VNext suffix to distinguish from the existing `logger: IMastraLogger`\n * infrastructure logger used throughout the codebase (e.g. `MastraPrimitives.logger`).\n *\n * The `tracingContext` alias is preferred at **forwarding sites** where the \"Context\"\n * suffix clarifies that a structural context object is being passed, not a subsystem.\n */\nexport interface ObservabilityContext {\n /** Tracing context for span creation and tree navigation. */\n tracing: TracingContext;\n\n /** Logger derived from the current span — log entries are trace-correlated. Uses VNext suffix to avoid conflict with IMastraLogger. */\n loggerVNext: LoggerContext;\n\n /** Metrics derived from the current span — data points are span-tagged. */\n metrics: MetricsContext;\n\n /**\n * Alias for `tracing`. Preferred at forwarding sites where the \"Context\" suffix\n * clarifies that a structural context object is being passed between functions.\n */\n tracingContext: TracingContext;\n}\n\n// ============================================================================\n// Shared Scorer Types\n// ============================================================================\n\n/** Where a registered definition came from. */\nexport type DefinitionSource = 'code' | 'stored' | 'fs';\n\n/** What kind of scoring flow produced the score. */\nexport type ScorerScoreSource = 'live' | 'trace' | 'experiment';\n\n/** How the scorer interpreted the target data. */\nexport type ScorerTargetScope = 'span' | 'trajectory';\n\n/** Execution style for a scorer step. */\nexport type ScorerStepType = 'function' | 'prompt';\n\n// ============================================================================\n// ObservabilityEventBus\n// ============================================================================\n\n/**\n * Generic event bus interface for observability events.\n * Implementations handle buffering, batching, and delivery to exporters.\n */\nexport interface ObservabilityEventBus<TEvent> {\n /** Emit an event to the bus */\n emit(event: TEvent): void;\n\n /** Subscribe to events. Returns unsubscribe function. */\n subscribe(handler: (event: TEvent) => void): () => void;\n\n /** Flush any buffered events */\n flush(): Promise<void>;\n\n /** Shutdown the bus and release resources */\n shutdown(): Promise<void>;\n}\n\n/**\n * Union of all observability event types.\n * Used by the unified ObservabilityBus that handles all signals.\n */\nexport type ObservabilityEvent =\n | TracingEvent\n | LogEvent\n | MetricEvent\n | ScoreEvent\n | FeedbackEvent\n | FeedbackReplacementEvent\n | FeedbackReviewStatusEvent;\n\n/** Signal whose event was dropped by the observability exporter pipeline. */\nexport type ObservabilityDropSignal = 'tracing' | 'log' | 'metric' | 'score' | 'feedback';\n\n/**\n * Reason an observability event was dropped by the exporter pipeline.\n *\n * `span-not-updatable`: a span update or end reached storage, but no unended span\n * with that ID was stored (it was never persisted, or it had already ended).\n */\nexport type ObservabilityDropReason = 'unsupported-storage' | 'retry-exhausted' | 'span-not-updatable';\n\n/** Sanitized error details for observability drop events. */\nexport interface ObservabilityDropError {\n id?: string;\n domain?: string;\n message: string;\n}\n\n/**\n * Structured event emitted when the exporter pipeline drops observability events.\n */\nexport interface ObservabilityDropEvent {\n type: 'drop';\n signal: ObservabilityDropSignal;\n reason: ObservabilityDropReason;\n count: number;\n timestamp: Date;\n exporterName: string;\n storageName?: string;\n error?: ObservabilityDropError;\n}\n\n// ============================================================================\n// ObservabilityInstance\n// ============================================================================\n\n/**\n * Primary interface for Observability\n */\nexport interface ObservabilityInstance {\n /**\n * Get current configuration\n */\n getConfig(): Readonly<ObservabilityInstanceConfig>;\n\n /**\n * Get all exporters\n */\n getExporters(): readonly ObservabilityExporter[];\n\n /**\n * Get all span output processors\n */\n getSpanOutputProcessors(): readonly SpanOutputProcessor[];\n\n /**\n * Get the logger instance (for exporters and other components)\n */\n getLogger(): IMastraLogger;\n\n /**\n * Get the bridge instance if configured\n */\n getBridge(): ObservabilityBridge | undefined;\n\n /**\n * Start a new span of a specific SpanType\n */\n startSpan<TType extends SpanType>(options: StartSpanOptions<TType>): Span<TType>;\n\n /**\n * Rebuild a span from exported data for lifecycle operations.\n * Used by durable execution engines (e.g., Inngest) to end/update spans\n * that were created in a previous durable operation.\n *\n * @param cached - The exported span data to rebuild from\n * @returns A span that can have end()/update()/error() called on it\n */\n rebuildSpan<TType extends SpanType>(cached: SpanSnapshot<TType>): Span<TType>;\n\n /**\n * Force flush any buffered/queued spans from all exporters and the bridge\n * without shutting down the observability instance.\n *\n * This is useful in serverless environments (like Vercel's fluid compute) where\n * you need to ensure all spans are exported before the runtime instance is\n * terminated, while keeping the observability system active for future requests.\n *\n * Unlike shutdown(), flush() does not release resources or prevent future tracing.\n */\n flush(): Promise<void>;\n\n /**\n * Shutdown tracing and clean up resources\n */\n shutdown(): Promise<void>;\n\n /**\n * Override setLogger to add tracing specific initialization log\n */\n __setLogger(logger: IMastraLogger): void;\n\n /**\n * Get a LoggerContext for this instance, optionally correlated to a span.\n * When a span is provided, the returned logger automatically includes\n * the span's traceId, spanId, and other metadata in every log entry.\n * Returns no-op context when logging is not configured on this instance.\n *\n * @param span - Optional span to correlate logs with\n */\n getLoggerContext?(span?: AnySpan): LoggerContext;\n\n /**\n * Get a MetricsContext for this instance, optionally tagged from a span.\n * When a span is provided, the returned metrics context automatically\n * includes the span's metadata as labels/tags on emitted data points.\n * Returns no-op context when metrics are not configured on this instance.\n *\n * @param span - Optional span to derive metric tags from\n */\n getMetricsContext?(span?: AnySpan): MetricsContext;\n\n /**\n * Register an additional exporter to this instance at runtime.\n * Duplicate registrations (same instance) are silently ignored.\n *\n * @param exporter - The exporter to register\n */\n registerExporter?(exporter: ObservabilityExporter): void;\n\n /**\n * Returns the deployment environment propagated from the parent Mastra\n * instance (resolved from `Mastra` config `environment` or `process.env.NODE_ENV`).\n * Used by spans as a fallback when `metadata.environment` isn't set on a\n * specific span.\n */\n getMastraEnvironment?(): string | undefined;\n\n /**\n * Internal hook used by the parent `Observability` entrypoint to push the\n * resolved Mastra-level environment into this instance during\n * `setMastraContext`. Implementations should store the value for later reads\n * via `getMastraEnvironment()`.\n */\n __setMastraEnvironment?(environment: string | undefined): void;\n}\n\n// ============================================================================\n// ObservabilityEntrypoint\n// ============================================================================\n\nexport interface ObservabilityEntrypoint {\n flush(): Promise<void>;\n\n shutdown(): Promise<void>;\n\n setMastraContext(options: { mastra: Mastra }): void;\n\n setLogger(options: { logger: IMastraLogger }): void;\n\n getSelectedInstance(options: ConfigSelectorOptions): ObservabilityInstance | undefined;\n\n /**\n * Load a persisted trace as a hydrated RecordedTrace object.\n * Returns null when storage is unavailable or the trace does not exist.\n */\n getRecordedTrace?(args: { traceId: string }): Promise<RecordedTrace | null>;\n\n /**\n * Add a score to a persisted trace or span without hydrating a RecordedTrace.\n * Useful for durable executions that persist only identifiers across serialization boundaries.\n *\n * `traceId` anchors the scored target when available.\n * Include `spanId` when the score is about a specific span.\n * Include `correlationContext` to supply context from live span/trace state.\n * Without it, context resolution depends on the exporter: storage exporters look up\n * local spans, while exporters such as PostHog receive the event without that lookup.\n */\n addScore?(args: {\n traceId?: string;\n spanId?: string;\n correlationContext?: CorrelationContext;\n score: ScoreInput;\n }): Promise<void>;\n\n /**\n * Add feedback to a persisted trace or span without hydrating a RecordedTrace.\n * Useful for durable executions that persist only identifiers across serialization boundaries.\n *\n * `traceId` anchors the feedback target when available.\n * Include `spanId` when the feedback is about a specific span.\n * Include `correlationContext` to supply context from live span/trace state.\n * Without it, context resolution depends on the exporter: storage exporters look up\n * local spans, while exporters such as PostHog receive the event without that lookup.\n */\n addFeedback?(args: {\n traceId?: string;\n spanId?: string;\n correlationContext?: CorrelationContext;\n feedback: FeedbackInput;\n }): Promise<void>;\n\n /** Replace complete feedback independently at each supporting exporter. */\n replaceFeedback?(args: FeedbackReplacementInput): Promise<void>;\n\n /** Update review status independently at each supporting exporter. */\n updateFeedbackReviewStatus?(args: FeedbackReviewStatusInput): Promise<void>;\n\n /** @internal Notify non-storage exporters after the server has persisted a record. */\n __exportPersistedEvent?(\n event: ScoreEvent | FeedbackEvent | FeedbackReplacementEvent | FeedbackReviewStatusEvent,\n ): Promise<void>;\n\n /**\n * Returns the proxy responsible for client observability (W3C trace\n * context injection + OTLP/JSON payload reception for spans/logs\n * returned from client-side execution).\n *\n * Returns `undefined` when no implementation is registered (e.g.\n * `NoOpObservability`, or when `@mastra/observability` is not\n * installed). Callers must treat `undefined` as \"no cross-boundary\n * client observability\" and skip inject/receive accordingly.\n */\n getClientObservabilityProxy?(): ClientObservabilityProxy | undefined;\n\n // Registry management methods\n registerInstance(name: string, instance: ObservabilityInstance, isDefault?: boolean): void;\n getInstance(name: string): ObservabilityInstance | undefined;\n getDefaultInstance(): ObservabilityInstance | undefined;\n listInstances(): ReadonlyMap<string, ObservabilityInstance>;\n unregisterInstance(name: string): boolean;\n hasInstance(name: string): boolean;\n setConfigSelector(selector: ConfigSelector): void;\n clear(): void;\n}\n\n// ============================================================================\n// Sampling Strategy\n// ============================================================================\n\n/**\n * Sampling strategy types\n */\nexport enum SamplingStrategyType {\n ALWAYS = 'always',\n NEVER = 'never',\n RATIO = 'ratio',\n CUSTOM = 'custom',\n}\n\n/**\n * Sampling strategy configuration\n */\nexport type SamplingStrategy =\n | { type: SamplingStrategyType.ALWAYS }\n | { type: SamplingStrategyType.NEVER }\n | { type: SamplingStrategyType.RATIO; probability: number }\n | { type: SamplingStrategyType.CUSTOM; sampler: (options?: CustomSamplerOptions) => boolean };\n\n/**\n * Options passed when using a custom sampler strategy\n */\nexport interface CustomSamplerOptions {\n requestContext?: RequestContext;\n metadata?: Record<string, any>;\n}\n\n// ============================================================================\n// Serialization Options\n// ============================================================================\n\n/**\n * Options for controlling serialization of span data.\n * These options control how input, output, and attributes are cleaned before export.\n */\nexport interface SerializationOptions {\n /**\n * Maximum length for string values\n * @default 131072 (128 KB)\n */\n maxStringLength?: number;\n /**\n * Maximum depth for nested objects\n * @default 8\n */\n maxDepth?: number;\n /**\n * Maximum number of items in arrays\n * @default 50\n */\n maxArrayLength?: number;\n /**\n * Maximum number of keys in objects\n * @default 50\n */\n maxObjectKeys?: number;\n}\n\n// ============================================================================\n// Registry Config\n// ============================================================================\n\n/**\n * Configuration for a single observability instance\n */\nexport interface ObservabilityInstanceConfig {\n /** Unique identifier for this config in the observability registry */\n name: string;\n /** Service name for observability */\n serviceName: string;\n /** Sampling strategy - controls whether tracing is collected (defaults to ALWAYS) */\n sampling?: SamplingStrategy;\n /** Custom exporters */\n exporters?: ObservabilityExporter[];\n /** Custom processors */\n spanOutputProcessors?: SpanOutputProcessor[];\n /** OpenTelemetry bridge for integration with existing OTEL infrastructure */\n bridge?: ObservabilityBridge;\n /** Set to `true` if you want to see spans internal to the operation of mastra */\n includeInternalSpans?: boolean;\n /**\n * Span types to exclude from export. Spans of these types are silently dropped\n * before reaching exporters. This is useful for reducing noise and costs in\n * observability platforms that charge per-span (e.g., Langfuse).\n *\n * @example\n * ```typescript\n * excludeSpanTypes: [SpanType.MODEL_CHUNK, SpanType.MODEL_STEP]\n * ```\n */\n excludeSpanTypes?: SpanType[];\n /**\n * Filter function to control which spans are exported. Return `true` to keep\n * the span, `false` to drop it. This runs after `excludeSpanTypes` and\n * `spanOutputProcessors`, giving you access to the final exported span data\n * for fine-grained filtering by type, attributes, entity, metadata, or any\n * combination.\n *\n * @example\n * ```typescript\n * spanFilter: (span) => {\n * // Drop all model chunks\n * if (span.type === SpanType.MODEL_CHUNK) return false;\n * // Only keep tool calls that failed\n * if (span.type === SpanType.TOOL_CALL && span.attributes?.success) return false;\n * return true;\n * }\n * ```\n */\n spanFilter?: (span: AnyExportedSpan) => boolean;\n /**\n * RequestContext keys to automatically extract as metadata for all spans\n * created with this observability configuration.\n * Supports dot notation for nested values.\n */\n requestContextKeys?: string[];\n /**\n * Options for controlling serialization of span data (input/output/attributes).\n * Use these to customize truncation limits for large payloads.\n */\n serializationOptions?: SerializationOptions;\n}\n\n/**\n * Complete Observability registry configuration\n */\nexport interface ObservabilityRegistryConfig {\n /** Enables default exporters, with sampling: always, and sensitive data filtering */\n default?: {\n enabled?: boolean;\n };\n /** Map of tracing instance names to their configurations or pre-instantiated instances */\n configs?: Record<string, Omit<ObservabilityInstanceConfig, 'name'> | ObservabilityInstance>;\n /** Optional selector function to choose which tracing instance to use */\n configSelector?: ConfigSelector;\n}\n\n// ============================================================================\n// Config Selector\n// ============================================================================\n\n/**\n * Options passed when using a custom tracing config selector\n */\nexport interface ConfigSelectorOptions {\n /** Request Context */\n requestContext?: RequestContext;\n}\n\n/**\n * Function to select which tracing instance to use for a given span\n * Returns the name of the tracing instance, or undefined to use default\n */\nexport type ConfigSelector = (\n options: ConfigSelectorOptions,\n availableConfigs: ReadonlyMap<string, ObservabilityInstance>,\n) => string | undefined;\n\n// ============================================================================\n// Exporter and Bridge Interfaces\n// ============================================================================\n\nexport interface InitExporterOptions {\n mastra?: Mastra;\n config?: ObservabilityInstanceConfig;\n emitDropEvent?: (event: ObservabilityDropEvent) => void;\n}\n\nexport interface InitBridgeOptions {\n mastra?: Mastra;\n config?: ObservabilityInstanceConfig;\n}\n\n/**\n * Shared Observability event interface for Exporters & Bridges\n */\nexport interface ObservabilityEvents {\n /** Handle tracing events */\n onTracingEvent?(event: TracingEvent): void | Promise<void>;\n\n /** Handle log events */\n onLogEvent?(event: LogEvent): void | Promise<void>;\n\n /** Handle metric events */\n onMetricEvent?(event: MetricEvent): void | Promise<void>;\n\n /** Handle score events */\n onScoreEvent?(event: ScoreEvent): void | Promise<void>;\n\n /** Handle full feedback replacements; unsupported exporters ignore them. */\n onFeedbackReplacementEvent?(event: FeedbackReplacementEvent): void | Promise<void>;\n\n /** Review-only update; unsupported exporters skip it. */\n onFeedbackReviewStatusEvent?(event: FeedbackReviewStatusEvent): void | Promise<void>;\n\n /** Handle feedback events */\n onFeedbackEvent?(event: FeedbackEvent): void | Promise<void>;\n\n /** Handle exporter pipeline droppedEvent */\n onDroppedEvent?(event: ObservabilityDropEvent): void | Promise<void>;\n\n /** Export tracing events */\n exportTracingEvent(event: TracingEvent): Promise<void>;\n}\n\n/**\n * Interface for tracing exporters\n */\nexport interface ObservabilityExporter extends ObservabilityEvents {\n /** Exporter name */\n name: string;\n\n /** Initialize exporter with tracing configuration and/or access to Mastra */\n init?(options: InitExporterOptions): void;\n\n /** Sets logger instance on the exporter. */\n __setLogger?(logger: IMastraLogger): void;\n\n addScoreToTrace?({\n traceId,\n spanId,\n score,\n reason,\n scorerName,\n metadata,\n }: {\n traceId: string;\n spanId?: string;\n score: number;\n reason?: string;\n scorerName: string;\n metadata?: Record<string, any>;\n }): Promise<void>;\n\n /**\n * Force flush any buffered/queued spans without shutting down the exporter.\n * This is useful in serverless environments where you need to ensure spans\n * are exported before the runtime instance is terminated, while keeping\n * the exporter active for future requests.\n *\n * Unlike shutdown(), flush() does not release resources or prevent future exports.\n */\n flush(): Promise<void>;\n\n /** Shutdown exporter */\n shutdown(): Promise<void>;\n}\n\n/**\n * Interface for observability bridges\n */\nexport interface ObservabilityBridge extends ObservabilityEvents {\n /** Bridge name */\n name: string;\n\n /** Initialize bridge with observability configuration and/or access to Mastra */\n init?(options: InitBridgeOptions): void;\n\n /** Sets logger instance on the bridge */\n __setLogger?(logger: IMastraLogger): void;\n\n /**\n * Execute an async function within the tracing context of a Mastra span.\n * This enables auto-instrumented operations (HTTP, DB) to have correct parent spans\n * in the external tracing system (e.g., OpenTelemetry, DataDog, etc.).\n *\n * @param spanId - The ID of the Mastra span to use as context\n * @param fn - The async function to execute within the span context\n * @returns The result of the function execution\n */\n executeInContext?<T>(spanId: string, fn: () => Promise<T>): Promise<T>;\n\n /**\n * Execute a synchronous function within the tracing context of a Mastra span.\n * This enables auto-instrumented operations (HTTP, DB) to have correct parent spans\n * in the external tracing system (e.g., OpenTelemetry, DataDog, etc.).\n *\n * @param spanId - The ID of the Mastra span to use as context\n * @param fn - The synchronous function to execute within the span context\n * @returns The result of the function execution\n */\n executeInContextSync?<T>(spanId: string, fn: () => T): T;\n\n /**\n * Create a span in the bridge's tracing system.\n * Called during Mastra span construction to get bridge-generated identifiers.\n *\n * @param options - Span creation options from Mastra\n * @returns Span identifiers (spanId, traceId, parentSpanId) from bridge, or undefined if creation fails\n */\n createSpan(options: CreateSpanOptions<SpanType>): SpanIds | undefined;\n\n /**\n * Release any state the bridge holds for a span that ended but will not be\n * exported. Bridges keep per-span state from `createSpan()` until the span\n * ends; span-end events are only emitted for spans that survive export\n * filtering, so without this the state for a span dropped by\n * `excludeSpanTypes`, a `spanFilter`, or a span output processor is never\n * freed.\n *\n * The bridge should only drop its bookkeeping here. It must not end/finish\n * the underlying span, which would export data the user filtered out.\n *\n * @param spanId - The ID of the Mastra span whose bridge state can be dropped\n * @param traceId - The trace the span belonged to, for per-trace bridge state\n */\n releaseSpan?(spanId: string, traceId: string): void;\n\n /**\n * Force flush any buffered/queued spans without shutting down the bridge.\n * This is useful in serverless environments where you need to ensure spans\n * are exported before the runtime instance is terminated, while keeping\n * the bridge active for future requests.\n *\n * Unlike shutdown(), flush() does not release resources or prevent future exports.\n */\n flush(): Promise<void>;\n\n /** Shutdown bridge and cleanup resources */\n shutdown(): Promise<void>;\n}\n","/**\n * W3C Trace Context `traceparent` parsing and formatting.\n * @see https://www.w3.org/TR/trace-context/#traceparent-header\n */\n\nconst TRACEPARENT_RE = /^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/;\n\n/** The parts of a W3C `traceparent`. */\nexport interface TraceparentParts {\n /** Version, currently always \"00\". */\n version: string;\n /** 32 hex chars. */\n traceId: string;\n /** 16 hex chars. The span this `traceparent` names. */\n spanId: string;\n /** 2 hex chars. Bit 0 is the sampled flag. */\n flags: string;\n}\n\n/** Parses a W3C `traceparent`. Values that aren't strings, are malformed, or use all-zero IDs yield `null`. */\nexport function parseTraceparent(value: unknown): TraceparentParts | null {\n if (typeof value !== 'string') return null;\n const match = TRACEPARENT_RE.exec(value.trim());\n if (!match) return null;\n const [, version, traceId, spanId, flags] = match as unknown as [string, string, string, string, string];\n if (version === 'ff' || /^0+$/.test(traceId) || /^0+$/.test(spanId)) return null;\n return { version, traceId, spanId, flags };\n}\n\n/** Formats a W3C `traceparent` for a span. */\nexport function formatTraceparent(traceId: string, spanId: string, sampled: boolean): string {\n return `00-${traceId}-${spanId}-${sampled ? '01' : '00'}`;\n}\n","import type { SpanRecord } from '../storage/domains/observability/tracing';\nimport type {\n ProcessorPipelineAttributes,\n ProcessorRunInputByPhase,\n ProcessorRunOutputByPhase,\n ProcessorSpanPayloadPhase,\n} from './types';\n\n/**\n * A processor span's payload with the phase that produced it, so a renderer can\n * switch on `phase` instead of sniffing the payload's shape.\n *\n * A union over the phases rather than one `phase` field beside a union of\n * payloads: narrowing on `phase` then narrows `data` to that phase's shape.\n */\nexport type ProcessorSpanPayload<TByPhase extends Record<ProcessorSpanPayloadPhase, unknown>> = {\n [P in ProcessorSpanPayloadPhase]: {\n phase: P;\n /** The phase written for people, e.g. `'Tool result'`. */\n phaseLabel: string;\n data: TByPhase[P];\n };\n}[ProcessorSpanPayloadPhase];\n\n/** Phase names as they are shown to a reader. */\nconst PROCESSOR_PHASE_LABELS: Record<ProcessorSpanPayloadPhase, string> = {\n input: 'Input',\n inputStep: 'Input step',\n llmRequest: 'LLM request',\n llmResponse: 'LLM response',\n outputStream: 'Output stream',\n outputResult: 'Output result',\n outputStep: 'Output step',\n toolResult: 'Tool result',\n requestError: 'Request error',\n};\n\n/**\n * The phase a processor span recorded, or `undefined` when it recorded none.\n *\n * Read from `attributes` rather than `spanType`, so a processor that retyped\n * its span (`Processor.spanType`) still describes its payloads — the runner\n * writes the same shapes either way. Spans stored before the attribute existed,\n * and spans a newer version wrote with a phase this one does not know, return\n * `undefined` and fall back to JSON.\n */\nexport function describeProcessorPhase(span: SpanRecord): ProcessorSpanPayloadPhase | undefined {\n const phase = span.attributes?.processorPhase;\n return typeof phase === 'string' && Object.hasOwn(PROCESSOR_PHASE_LABELS, phase)\n ? (phase as ProcessorSpanPayloadPhase)\n : undefined;\n}\n\n/**\n * Tags a processor payload with the phase that recorded it.\n *\n * The payload itself is not validated, matching what `isSpanRecordOfType` and\n * the other `describeSpan*` helpers already do: the typed view trusts that the\n * producer for a phase wrote the shape core declares. Renderers guard each\n * field they read, so a partially populated span shows what it has rather than\n * losing the whole view to one unexpected value.\n */\nfunction describeProcessorPayload<TByPhase extends Record<ProcessorSpanPayloadPhase, unknown>>(\n span: SpanRecord,\n data: Record<string, unknown>,\n): ProcessorSpanPayload<TByPhase> | undefined {\n const phase = describeProcessorPhase(span);\n // An empty payload has nothing to describe; it stays JSON like any other span's.\n if (!phase || Object.keys(data).length === 0) return undefined;\n return { phase, phaseLabel: PROCESSOR_PHASE_LABELS[phase], data } as ProcessorSpanPayload<TByPhase>;\n}\n\n/** The `input` a processor span recorded, tagged by the phase that produced it. */\nexport function describeProcessorInput(\n span: SpanRecord,\n data: Record<string, unknown>,\n): ProcessorSpanPayload<ProcessorRunInputByPhase> | undefined {\n return describeProcessorPayload<ProcessorRunInputByPhase>(span, data);\n}\n\n/** The `output` a processor span recorded, tagged by the phase that produced it. */\nexport function describeProcessorOutput(\n span: SpanRecord,\n data: Record<string, unknown>,\n): ProcessorSpanPayload<ProcessorRunOutputByPhase> | undefined {\n return describeProcessorPayload<ProcessorRunOutputByPhase>(span, data);\n}\n\n/**\n * The pipeline facts a processor span records, with the phase resolved and the\n * remaining attributes kept apart.\n *\n * `rest` is everything this view does not explain: a declared span type's own\n * attributes, and anything a processor set itself. Keeping it separate is what\n * lets a reader show the known fields as labelled values without repeating them\n * in an undifferentiated JSON blob beside them.\n */\nexport interface ProcessorPipelineDescription {\n phase: ProcessorSpanPayloadPhase;\n phaseLabel: string;\n executor?: 'workflow' | 'legacy';\n processorIndex?: number;\n hookDurationMs?: number;\n messageListMutations?: ProcessorPipelineAttributes['messageListMutations'];\n tripwireAbort?: ProcessorPipelineAttributes['tripwireAbort'];\n /** Attributes this description does not cover; `undefined` when there are none. */\n rest?: Record<string, unknown>;\n}\n\n/** Attribute keys `describeProcessorPipeline` accounts for. */\nconst PROCESSOR_PIPELINE_KEYS = [\n 'processorPhase',\n 'processorExecutor',\n 'processorIndex',\n 'hookDurationMs',\n 'messageListMutations',\n 'tripwireAbort',\n] as const satisfies readonly (keyof ProcessorPipelineAttributes)[];\n\n/**\n * Describes the runner-owned attributes of a processor span for rendering.\n * Returns `undefined` when the span recorded no phase, so a legacy or\n * non-processor span falls back to its raw attributes.\n */\nexport function describeProcessorPipeline(span: SpanRecord): ProcessorPipelineDescription | undefined {\n const phase = describeProcessorPhase(span);\n if (!phase) return undefined;\n\n const attributes = (span.attributes ?? {}) as ProcessorPipelineAttributes & Record<string, unknown>;\n\n // The two structured fields are checked for the shape this view iterates, and\n // only for that. A value it cannot walk stays in `rest` so the reader still\n // sees it as JSON, rather than the whole description disappearing over one\n // field — a bad mutation log should not hide a good tripwire reason.\n const mutations = Array.isArray(attributes.messageListMutations) ? attributes.messageListMutations : undefined;\n const tripwireAbort =\n typeof attributes.tripwireAbort === 'object' && attributes.tripwireAbort !== null\n ? attributes.tripwireAbort\n : undefined;\n\n const presented = new Set<string>(PROCESSOR_PIPELINE_KEYS);\n if (attributes.messageListMutations !== undefined && !mutations) presented.delete('messageListMutations');\n if (attributes.tripwireAbort !== undefined && !tripwireAbort) presented.delete('tripwireAbort');\n\n const rest: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(attributes)) {\n if (!presented.has(key)) rest[key] = value;\n }\n\n return {\n phase,\n phaseLabel: PROCESSOR_PHASE_LABELS[phase],\n executor: attributes.processorExecutor,\n processorIndex: attributes.processorIndex,\n hookDurationMs: attributes.hookDurationMs,\n messageListMutations: mutations,\n tripwireAbort,\n ...(Object.keys(rest).length > 0 ? { rest } : {}),\n };\n}\n","import type { MessageListItem } from '../agent/message-list/types';\nimport type { SpanRecord } from '../storage/domains/observability/tracing';\nimport { describeProcessorInput, describeProcessorOutput, describeProcessorPhase } from './processor-span-record';\nimport type { ProcessorSpanPayload } from './processor-span-record';\nimport type {\n AgentRunResult,\n AgentRunResumeInput,\n InterruptedSpanOutput,\n ModelGenerationResult,\n ModelStepMessage,\n ModelStepResult,\n ProcessorRunInputByPhase,\n ProcessorRunOutputByPhase,\n SpanErrorInfo,\n} from './types';\nimport { SpanType } from './types';\n\nexport { describeProcessorPhase, describeProcessorPipeline } from './processor-span-record';\nexport type { ProcessorPipelineDescription, ProcessorSpanPayload } from './processor-span-record';\n\n/**\n * Narrows a stored span record to one or more span types, typing its\n * `attributes`, `input` and `output` for that type.\n *\n * The check is on `spanType` only. Payloads are not validated: the typed view\n * trusts that the producer for that span type wrote the shape core declares,\n * the same trust `SpanTypeMap` already places in `attributes`.\n *\n * This module uses only the `SpanType` enum and browser-safe payload helpers\n * at runtime, without pulling in the rest of the observability utilities.\n *\n * @example\n * if (isSpanRecordOfType(span, SpanType.MODEL_GENERATION)) {\n * span.attributes?.usage; // UsageStats | undefined\n * }\n */\nexport function isSpanRecordOfType<TType extends SpanType>(\n span: SpanRecord,\n type: TType | readonly TType[],\n): span is SpanRecord<TType> {\n return Array.isArray(type) ? type.includes(span.spanType as TType) : span.spanType === type;\n}\n\n/** A message as it appears in a span input: a caller message, or the shallow preview a model step records. */\nexport type SpanInputMessage = MessageListItem | ModelStepMessage;\n\n/**\n * A span's `input`, tagged by what it holds so a renderer can switch on `type`.\n * The tag is derived at read time from `spanType` and the value's shape; it is\n * never stored.\n */\nexport type SpanInputDescription =\n | { type: 'text'; value: string }\n | { type: 'messages'; value: SpanInputMessage[] }\n | { type: 'agent-run-resume'; value: AgentRunResumeInput }\n | { type: 'processor'; value: ProcessorSpanPayload<ProcessorRunInputByPhase> }\n | { type: 'json'; value: unknown };\n\n/** A span's `output`, tagged by what it holds so a renderer can switch on `type`. */\nexport type SpanOutputDescription =\n | { type: 'interrupted'; value: InterruptedSpanOutput }\n | { type: 'agent-run-result'; value: AgentRunResult }\n | { type: 'model-generation-result'; value: ModelGenerationResult }\n | { type: 'model-step-result'; value: ModelStepResult }\n | { type: 'processor'; value: ProcessorSpanPayload<ProcessorRunOutputByPhase> }\n | { type: 'text'; value: string }\n | { type: 'json'; value: unknown };\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n\nconst isInterrupted = (value: Record<string, unknown>): value is Record<string, unknown> & InterruptedSpanOutput =>\n value.status === 'suspended' || value.status === 'aborted' || value.status === 'interrupted';\n\n/** Span types whose `input` is a message list when it is an array. */\nconst MESSAGE_LIST_INPUT_SPANS: readonly SpanType[] = [\n SpanType.AGENT_RUN,\n SpanType.MODEL_STEP,\n SpanType.MODEL_INFERENCE,\n];\n\n/**\n * Describes a stored span's `input` for rendering: the value tagged by what it\n * holds. Returns `undefined` when the span recorded no input.\n *\n * - `text`: a plain string, such as the prompt passed to an agent\n * - `messages`: a message list, unwrapped from the `{ messages }` envelope\n * model generation spans and legacy agent spans record\n * - `agent-run-resume`: the resume data of a resumed agent run, whatever shape it has\n * - `processor`: a processor payload, tagged with the pipeline phase that recorded it\n * - `json`: anything else, such as tool arguments or workflow step data\n */\nexport function describeSpanInput(span: SpanRecord): SpanInputDescription | undefined {\n const input: unknown = span.input;\n if (input == null) return undefined;\n\n // A resumed run's input is resume data whatever it looks like, so the resumed marker\n // settles it before any shape check. Runs resumed before core always recorded an\n // object can hold a bare string, array or number here, which is normalized to match.\n if (span.spanType === SpanType.AGENT_RUN && span.metadata?.resumed === true) {\n const value = isRecord(input) ? input : { resumeData: input };\n return { type: 'agent-run-resume', value: value as AgentRunResumeInput };\n }\n\n if (describeProcessorPhase(span)) {\n const processor = isRecord(input) ? describeProcessorInput(span, input) : undefined;\n return processor ? { type: 'processor', value: processor } : { type: 'json', value: input };\n }\n\n if (typeof input === 'string') return { type: 'text', value: input };\n if (Array.isArray(input)) {\n return MESSAGE_LIST_INPUT_SPANS.includes(span.spanType)\n ? { type: 'messages', value: input as SpanInputMessage[] }\n : { type: 'json', value: input };\n }\n if (!isRecord(input)) return { type: 'json', value: input };\n\n const isAgentRun = span.spanType === SpanType.AGENT_RUN;\n if ((isAgentRun || span.spanType === SpanType.MODEL_GENERATION) && 'messages' in input) {\n const { messages } = input;\n if (typeof messages === 'string') return { type: 'text', value: messages };\n if (Array.isArray(messages)) return { type: 'messages', value: messages as SpanInputMessage[] };\n if (isRecord(messages)) return { type: 'messages', value: [messages as SpanInputMessage] };\n }\n if (isAgentRun) {\n if (typeof input.role === 'string') return { type: 'messages', value: [input as SpanInputMessage] };\n if ('toolCallId' in input || 'toolName' in input || 'resumeData' in input) {\n return { type: 'agent-run-resume', value: input as AgentRunResumeInput };\n }\n }\n return { type: 'json', value: input };\n}\n\n/**\n * Describes a stored span's `output` for rendering: the value tagged by what it\n * holds. Returns `undefined` when the span recorded no output.\n *\n * - `interrupted`: the run suspended or was aborted before the span's result existed\n * - `agent-run-result`, `model-generation-result`, `model-step-result`: the\n * result of the span type that recorded it\n * - `processor`: a processor payload, tagged with the pipeline phase that recorded it\n * - `text`: a plain string\n * - `json`: anything else, such as a tool result or workflow step output\n */\nexport function describeSpanOutput(span: SpanRecord): SpanOutputDescription | undefined {\n const output: unknown = span.output;\n if (output == null) return undefined;\n if (describeProcessorPhase(span)) {\n const processor = isRecord(output) ? describeProcessorOutput(span, output) : undefined;\n return processor ? { type: 'processor', value: processor } : { type: 'json', value: output };\n }\n if (typeof output === 'string') return { type: 'text', value: output };\n if (!isRecord(output)) return { type: 'json', value: output };\n\n switch (span.spanType) {\n case SpanType.AGENT_RUN:\n return isInterrupted(output)\n ? { type: 'interrupted', value: output }\n : { type: 'agent-run-result', value: output as AgentRunResult };\n case SpanType.MODEL_GENERATION:\n return isInterrupted(output)\n ? { type: 'interrupted', value: output }\n : { type: 'model-generation-result', value: output as ModelGenerationResult };\n case SpanType.MODEL_STEP:\n return isInterrupted(output)\n ? { type: 'interrupted', value: output }\n : { type: 'model-step-result', value: output as ModelStepResult };\n case SpanType.MODEL_INFERENCE:\n return { type: 'model-step-result', value: output as ModelStepResult };\n default:\n return { type: 'json', value: output };\n }\n}\n\nconst isSpanErrorInfo = (value: unknown): value is SpanErrorInfo =>\n isRecord(value) && typeof value.message === 'string';\n\n/** The error a stored span recorded, typed, or `undefined` when the span succeeded. */\nexport function describeSpanError(span: SpanRecord): SpanErrorInfo | undefined {\n return isSpanErrorInfo(span.error) ? span.error : undefined;\n}\n","/**\n * RAG ingestion helpers.\n *\n * Provides a thin wrapper around `getOrCreateSpan` for starting a\n * `RAG_INGESTION` root span without reaching into observability internals.\n *\n * Two surfaces:\n * - `startRagIngestion(...)` — manual: returns `{ span, observabilityContext }`,\n * caller is responsible for `.end()` / `.error()`.\n * - `withRagIngestion(opts, fn)` — scoped: runs `fn(observabilityContext)`,\n * automatically attaches the return value as the span's `output` and\n * routes thrown errors to `span.error(...)`.\n *\n * ## Observability data\n *\n * Mastra emits raw span data (start/end timestamps, attributes, input,\n * output) — exporters and downstream consumers do their own aggregation.\n * The shapes below are designed to make the common derivations cheap:\n *\n * - **Duration**: every span has start/end, so per-operation latency\n * falls out for free.\n * - **Embedding cost**: `RAG_EMBEDDING` spans (and only `RAG_EMBEDDING`\n * spans) expose `attributes.usage` using the same `UsageStats` shape as\n * `MODEL_GENERATION`, so any existing LLM cost-extraction pipeline that\n * parses `usage.inputTokens` handles embeddings uniformly. Cost\n * dimensions are `{model, provider, mode}` (mode is `'ingest'` or\n * `'query'`). Token counts are deliberately NOT duplicated on the\n * `RAG_INGESTION` root — aggregating at the root would double-count\n * when summing child spans. Mirrors how `AGENT_RUN` does not carry\n * aggregated `MODEL_GENERATION` usage.\n * - **Vector store throughput**: `RAG_VECTOR_OPERATION` spans carry\n * `{operation, store, indexName}` as attributes; result counts live on\n * `output` (e.g. `output.returned`, `output.vectorCount`).\n * - **Ingestion roll-ups**: `RAG_INGESTION` (root) carries\n * `{vectorStore, indexName, embeddingModel, embeddingProvider}` as\n * attributes and aggregate `usage` summed across child embed calls.\n */\n\nimport { createObservabilityContext } from './context-factory';\nimport { EntityType, SpanType } from './types';\nimport type { GetOrCreateSpanOptions, ObservabilityContext, RagIngestionAttributes, Span } from './types';\nimport { getOrCreateSpan } from './utils';\n\nexport type StartRagIngestionOptions = Omit<GetOrCreateSpanOptions<SpanType.RAG_INGESTION>, 'type' | 'entityType'>;\n\nexport interface StartRagIngestionResult {\n /**\n * The RAG_INGESTION span. May be undefined if observability is disabled\n * or no Mastra instance / parent span is available.\n */\n span: Span<SpanType.RAG_INGESTION> | undefined;\n /**\n * Full observability context to thread through chunk / embed / upsert calls.\n * Always defined; falls back to no-op when `span` is undefined.\n */\n observabilityContext: ObservabilityContext;\n}\n\n/**\n * Start a `RAG_INGESTION` root span. Caller is responsible for closing it\n * via `result.span?.end(...)` or `result.span?.error(...)`.\n *\n * Prefer `withRagIngestion` for the common try/catch/end flow.\n *\n * @example\n * ```ts\n * const { span, observabilityContext } = startRagIngestion({\n * mastra,\n * name: 'docs ingestion',\n * attributes: { vectorStore: 'pgvector', indexName: 'docs' },\n * });\n * try {\n * const chunks = await doc.chunk({ observabilityContext });\n * // ...\n * span?.end({ output: { chunkCount: chunks.length } });\n * } catch (err) {\n * span?.error({ error: err as Error });\n * throw err;\n * }\n * ```\n */\nexport function startRagIngestion(options: StartRagIngestionOptions): StartRagIngestionResult {\n const span = getOrCreateSpan<SpanType.RAG_INGESTION>({\n ...options,\n entityType: EntityType.RAG_INGESTION,\n type: SpanType.RAG_INGESTION,\n });\n\n const observabilityContext = createObservabilityContext(span ? { currentSpan: span } : undefined);\n\n return { span, observabilityContext };\n}\n\n/**\n * Run an async function inside a `RAG_INGESTION` root span.\n *\n * The callback receives an `ObservabilityContext` to thread into chunk,\n * embed, and vector-store calls. The return value is attached to the span\n * as `output`. Thrown errors are recorded via `span.error(...)` and\n * re-thrown.\n *\n * @example\n * ```ts\n * await withRagIngestion(\n * {\n * mastra,\n * name: 'docs ingestion',\n * attributes: { vectorStore: 'pgvector', indexName: 'docs' },\n * },\n * async (observabilityContext) => {\n * const chunks = await doc.chunk({ observabilityContext });\n * const { embeddings } = await embed(chunks, { observabilityContext });\n * await vectorStore.upsert({\n * indexName: 'docs',\n * vectors: embeddings,\n * observabilityContext,\n * });\n * return { chunkCount: chunks.length };\n * },\n * );\n * ```\n */\nexport async function withRagIngestion<T>(\n options: StartRagIngestionOptions,\n fn: (observabilityContext: ObservabilityContext) => Promise<T>,\n): Promise<T> {\n const { span, observabilityContext } = startRagIngestion(options);\n\n try {\n const result = await fn(observabilityContext);\n span?.end({ output: result as any });\n return result;\n } catch (err) {\n span?.error({ error: err as Error, endSpan: true });\n throw err;\n }\n}\n\nexport type { RagIngestionAttributes };\n","import type { AnyExportedSpan } from './types/tracing';\nimport { SpanType } from './types/tracing';\n\n/** Maximum preview length, before the trailing `…`, including supplied previews. */\nexport const PREVIEW_MAX_LENGTH = 100;\n\nexport function truncatePreview(text: string, maxLength = PREVIEW_MAX_LENGTH): string | null {\n const trimmed = text.trim();\n if (!trimmed) return null;\n if (trimmed.length <= maxLength) return trimmed;\n // Never end on half of a surrogate pair.\n const end = maxLength > 0 && /[\\uD800-\\uDBFF]/.test(trimmed[maxLength - 1]!) ? maxLength - 1 : maxLength;\n return `${trimmed.slice(0, end)}…`;\n}\n\ntype RecordValue = Record<string, unknown>;\ntype Direction = 'input' | 'output';\ntype PreviewWriter = (span: AnyExportedSpan, direction: Direction) => string | null | undefined;\n\nconst record = (value: unknown): RecordValue | undefined =>\n value !== null && typeof value === 'object' && !Array.isArray(value) ? (value as RecordValue) : undefined;\nconst text = (value: unknown): string | undefined =>\n typeof value === 'string' && value.trim() ? value.trim() : undefined;\nconst limit = (value: string): string => truncatePreview(value) ?? '';\n\n/** Only serialize enough JSON for a preview. Never walk an entire embedding, message history,\n * or tool result just to return 100 characters. Cycles/deep values remain readable. */\nfunction jsonPreview(value: unknown): string {\n let result = '';\n let visited = 0;\n const ancestors = new Set<object>();\n const append = (part: string) => {\n result += part.slice(0, PREVIEW_MAX_LENGTH + 1 - result.length);\n };\n const visit = (item: unknown, depth: number): void => {\n if (result.length > PREVIEW_MAX_LENGTH) return;\n if (++visited > 128) {\n append('\"[More values]\"');\n return;\n }\n if (typeof item === 'string') {\n append(JSON.stringify(item.slice(0, PREVIEW_MAX_LENGTH + 1)));\n } else if (typeof item === 'bigint') {\n append(JSON.stringify(String(item)));\n } else if (item === null || typeof item !== 'object') {\n append(JSON.stringify(item) ?? 'null');\n } else if (item instanceof Date) {\n append(JSON.stringify(item));\n } else if (ancestors.has(item) || depth >= 8) {\n append(JSON.stringify(ancestors.has(item) ? '[Circular]' : '[Nested value]'));\n } else {\n ancestors.add(item);\n if (Array.isArray(item)) {\n append('[');\n for (let i = 0; i < item.length && result.length <= PREVIEW_MAX_LENGTH; i++) {\n if (i) append(',');\n visit(item[i], depth + 1);\n }\n append(']');\n } else {\n append('{');\n let first = true;\n let keys = 0;\n for (const key in item) {\n if (result.length > PREVIEW_MAX_LENGTH) break;\n if (!Object.hasOwn(item, key)) continue;\n if (++keys > 128) {\n if (!first) append(',');\n append('\"…\":\"[More fields]\"');\n break;\n }\n const field = (item as RecordValue)[key];\n if (field === undefined || typeof field === 'function' || typeof field === 'symbol') continue;\n if (!first) append(',');\n first = false;\n append(JSON.stringify(key.slice(0, PREVIEW_MAX_LENGTH + 1)));\n append(':');\n visit(field, depth + 1);\n }\n append('}');\n }\n ancestors.delete(item);\n }\n };\n visit(value, 0);\n return limit(result);\n}\n\nfunction generic(value: unknown): string {\n if (value == null) return '';\n if (typeof value === 'string') return limit(value);\n const data = record(value);\n if (data?.__isCreatedSignal === true) return signalPreview(data);\n const content = text(data?.text) ?? text(data?.message);\n return content ? limit(content) : jsonPreview(value);\n}\n\n/** Created signals are caller input, rather than messages with a role. */\nfunction signalPreview(signal: RecordValue): string {\n const content = messageContent(signal.contents);\n if (signal.type === 'user' || signal.type === 'user-message') return content;\n const tagName = text(signal.tagName);\n const skillName = text(record(signal.attributes)?.name);\n const label = tagName === 'skill' && skillName ? `Skill ${skillName}` : (tagName ?? text(signal.type) ?? 'signal');\n return limit(content ? `${label}: ${content}` : label);\n}\n\n/** Content parts are deliberately shallow: never serialize binary data or an entire tool result. */\nfunction messageContent(value: unknown): string {\n if (typeof value === 'string') return limit(value);\n const container = record(value);\n if (container) return messageContent(container.parts ?? container.content);\n if (!Array.isArray(value)) return '';\n const parts: string[] = [];\n // Prefer the answer over internal reasoning when both are present.\n const hasAnswer = value.some(item => record(item)?.type === 'text' && text(record(item)?.text));\n let length = 0;\n for (const item of value) {\n const part = record(item);\n if (hasAnswer && part?.type === 'reasoning') continue;\n let content = typeof item === 'string' ? limit(item) : text(part?.text);\n if (!content && part) {\n const type = text(part.type);\n if (type === 'step-start') continue;\n if (type === 'reasoning') {\n content = text(part.reasoning);\n } else if (\n type === 'tool-invocation' ||\n type === 'dynamic-tool' ||\n (type?.startsWith('tool-') && type !== 'tool-call' && type !== 'tool-result')\n ) {\n const invocation = record(part.toolInvocation) ?? part;\n const name = text(invocation.toolName) ?? (type?.startsWith('tool-') ? type.slice(5) : undefined) ?? 'unknown';\n const state = text(invocation.state);\n const action =\n state === 'result' || state === 'output-available'\n ? 'tool-result'\n : state === 'output-error'\n ? 'tool-error'\n : state === 'output-denied'\n ? 'tool-denied'\n : state?.startsWith('approval-')\n ? 'tool-approval'\n : 'tool-call';\n content = `[${action}: ${name}]`;\n } else if (type === 'tool-call' || type === 'tool-result') {\n content = `[${type}: ${text(part.toolName) ?? 'unknown'}]`;\n } else if (type === 'image' || type === 'image_url' || type === 'input_image') {\n content = '[image]';\n } else if (type === 'audio' || type === 'input_audio') {\n content = '[audio]';\n } else if (type === 'file' || type === 'resource' || type === 'resource_link') {\n content = `[${type}]`;\n } else if (type) {\n content = `[${type}]`;\n }\n }\n if (content) {\n parts.push(limit(content));\n length += content.length + 1;\n if (length > PREVIEW_MAX_LENGTH) break;\n }\n }\n return limit(parts.join(' '));\n}\n\nfunction messages(value: unknown, preferUser: boolean, label = false): string | undefined {\n if (typeof value === 'string') return limit(value);\n const data = record(value);\n if (data && 'messages' in data) return messages(data.messages, preferUser, label);\n const list = Array.isArray(value) ? value : data?.role ? [data] : undefined;\n if (!list) return undefined;\n let latest: string | undefined;\n for (let i = list.length - 1; i >= 0; i--) {\n const item = list[i];\n const message = record(item);\n const role = typeof item === 'string' ? 'user' : text(message?.role);\n if (!role || role === 'system' || role === 'developer') continue;\n const body = record(message?.content) ?? message;\n let content = typeof item === 'string' ? limit(item) : messageContent(message?.parts ?? message?.content);\n if (!content && Array.isArray(body?.toolInvocations)) {\n content = messageContent(\n body.toolInvocations.map(toolInvocation => ({ type: 'tool-invocation', toolInvocation })),\n );\n }\n if (!content && Array.isArray(body?.experimental_attachments) && body.experimental_attachments.length) {\n content = '[attachment]';\n }\n content ||= text(body?.reasoning) ?? '';\n if (!content) continue;\n const preview = label ? `${role[0]!.toUpperCase()}${role.slice(1)}: ${content}` : content;\n latest ??= preview;\n const signalType = record(record(record(message?.content)?.metadata)?.signal)?.type;\n if (\n !preferUser ||\n role === 'user' ||\n (role === 'signal' && (signalType === 'user' || signalType === 'user-message'))\n )\n return preview;\n }\n // A recognized but empty message list should not fall back to serializing its wrappers/binary data.\n return latest ?? '';\n}\n\nfunction toolCalls(value: unknown): string | undefined {\n if (!Array.isArray(value) || !value.length) return undefined;\n const names = value.slice(0, 4).map(call => {\n const data = record(call);\n return text(data?.toolName) ?? text(data?.name) ?? text(record(data?.function)?.name) ?? 'unknown';\n });\n return `Tool calls: ${names.join(', ')}${value.length > 4 ? ` (+${value.length - 4})` : ''}`;\n}\n\nconst modelWriter: PreviewWriter = (span, direction) => {\n const value = span[direction];\n const data = record(value);\n if (direction === 'input') {\n if (\n span.type === SpanType.AGENT_RUN &&\n data &&\n (span.metadata?.resumed === true || 'resumeData' in data || 'toolCallId' in data || 'toolName' in data)\n ) {\n return `Resume${text(data.toolName) ? ` ${data.toolName}` : ''}: ${generic(data.resumeData ?? value)}`;\n }\n if (span.type === SpanType.AGENT_RUN && span.metadata?.resumed === true && value != null) {\n return `Resume: ${generic(value)}`;\n }\n const step = span.type === SpanType.MODEL_STEP || span.type === SpanType.MODEL_INFERENCE;\n return messages(value, !step, step);\n }\n if (!data) return undefined;\n if (['suspended', 'aborted', 'interrupted'].includes(String(data.status))) {\n const status = String(data.status);\n return `${status[0]!.toUpperCase()}${status.slice(1)}${text(data.reason) ? `: ${data.reason}` : ''}${text(data.toolName) ? ` (${data.toolName})` : ''}`;\n }\n const tripwire = record(data.tripwire);\n if (tripwire) return `Tripwire${text(tripwire.reason) ? `: ${tripwire.reason}` : ''}`;\n if (data.object != null) return jsonPreview(data.object);\n const calls = toolCalls(data.toolCalls);\n if (text(data.text)) return `${data.text}${calls ? ` — ${calls}` : ''}`;\n if (calls) return calls;\n if (Array.isArray(data.files) && data.files.length) return `${data.files.length} generated file(s)`;\n if (text(data.reasoningText)) return `Reasoning: ${data.reasoningText}`;\n return undefined;\n};\n\nconst processorWriter: PreviewWriter = (span, direction) => {\n const data = record(span[direction]);\n if (!data) return undefined;\n const phase = record(span.attributes)?.processorPhase;\n if (phase === 'outputStream') {\n return (\n text(data.accumulatedText) ?? (typeof data.totalChunks === 'number' ? `${data.totalChunks} chunks` : undefined)\n );\n }\n if (direction === 'input') {\n if (phase === 'requestError' && text(data.error)) return `Request error: ${data.error}`;\n if (phase === 'toolResult' && text(data.toolName)) return `Tool result: ${data.toolName}`;\n return messages(data.messages ?? data.prompt, phase === 'input' || phase === 'inputStep') ?? text(data.text);\n }\n const changes: string[] = [];\n if (record(data.model)) changes.push(`Model: ${generic(data.model)}`);\n for (const key of ['messages', 'systemMessages', 'tools', 'activeTools', 'toolChoice']) {\n if (Object.hasOwn(data, key)) changes.push(`${key} replaced`);\n }\n if (changes.length) return changes.join('; ');\n if (Object.keys(data).length === 0) return 'No recorded changes';\n return undefined;\n};\n\nconst processorPhases = new Set([\n 'input',\n 'inputStep',\n 'outputStream',\n 'outputResult',\n 'outputStep',\n 'toolResult',\n 'llmRequest',\n 'llmResponse',\n 'requestError',\n]);\n\nconst writers: Partial<Record<SpanType, PreviewWriter>> = {\n [SpanType.AGENT_RUN]: modelWriter,\n [SpanType.MODEL_GENERATION]: modelWriter,\n [SpanType.MODEL_STEP]: modelWriter,\n [SpanType.MODEL_INFERENCE]: modelWriter,\n [SpanType.MODEL_CHUNK]: (span, direction) => {\n if (direction !== 'output') return undefined;\n const data = record(span.output);\n if (!data) return undefined;\n if (text(data.text) ?? text(data.delta)) return text(data.text) ?? text(data.delta);\n if (text(data.toolName))\n return `${data.toolName}: ${generic(data.toolInput ?? data.args ?? data.input ?? data.result)}`;\n if (record(span.attributes)?.chunkType === 'file') return '[file]';\n return undefined;\n },\n [SpanType.MCP_TOOL_CALL]: mcpWriter,\n [SpanType.MCP_SERVER_REQUEST]: mcpWriter,\n [SpanType.SCORER_RUN]: (span, direction) => {\n const data = record(span[direction]);\n if (!data) return undefined;\n if (direction === 'input' && data.output != null) return `Response: ${generic(data.output)}`;\n if (direction === 'output' && typeof data.score === 'number') {\n return `Score: ${data.score}${text(data.reason) ? ` — ${data.reason}` : ''}`;\n }\n return undefined;\n },\n [SpanType.CLASSIFIER_EVALUATION]: (span, direction) => {\n const data = record(span[direction]);\n return data && (direction === 'input' ? data.questions : data.answers) != null\n ? generic(direction === 'input' ? data.questions : data.answers)\n : undefined;\n },\n [SpanType.RAG_EMBEDDING]: (span, direction) => {\n const value = span[direction];\n if (direction === 'input' && Array.isArray(value)) return `${value.length} texts: ${generic(value[0])}`;\n const data = record(value);\n if (direction === 'output' && typeof data?.dimensions === 'number') return `${data.dimensions} dimensions`;\n return undefined;\n },\n [SpanType.RAG_VECTOR_OPERATION]: returnedWriter,\n [SpanType.RAG_ACTION]: (span, direction) => {\n const data = record(span[direction]);\n if (direction === 'input' && record(span.attributes)?.action === 'rerank' && data?.query != null)\n return generic(data.query);\n return returnedWriter(span, direction);\n },\n [SpanType.GRAPH_ACTION]: returnedWriter,\n};\n\nfunction returnedWriter(span: AnyExportedSpan, direction: Direction): string | undefined {\n const data = record(span[direction]);\n return direction === 'output' && typeof data?.returned === 'number' ? `${data.returned} results` : undefined;\n}\n\nfunction mcpWriter(span: AnyExportedSpan, direction: Direction): string | undefined {\n if (direction !== 'output') return undefined;\n const data = record(span.output);\n if (data?.structuredContent != null) return jsonPreview(data.structuredContent);\n if (Array.isArray(data?.content)) return messageContent(data.content) || undefined;\n return undefined;\n}\n\nfunction errorPreview(value: unknown): string {\n if (typeof value === 'string') return limit(value);\n const data = record(value);\n if (!data) return '';\n const field = (key: string): string | undefined => {\n try {\n return text(data[key]);\n } catch {\n return undefined;\n }\n };\n const message = field('message');\n const name = field('name');\n if (message)\n return limit(name && name !== 'Error' && !message.startsWith(`${name}:`) ? `${name}: ${message}` : message);\n return limit(name ?? field('id') ?? field('domain') ?? field('category') ?? '');\n}\n\n/** Readable previews of a processed/redacted span. Explicit strings, including\n * empty strings, take precedence. Does not mutate the span or retain snapshots. */\nexport function buildSpanPreviews(span: AnyExportedSpan): {\n inputPreview: string;\n outputPreview: string;\n errorPreview: string;\n} {\n const preview = (direction: Direction): string => {\n try {\n const upstream = span[direction === 'input' ? 'inputPreview' : 'outputPreview'];\n if (typeof upstream === 'string') return limit(upstream);\n if (span[direction] == null) return '';\n const phase = record(span.attributes)?.processorPhase;\n const writer = typeof phase === 'string' && processorPhases.has(phase) ? processorWriter : writers[span.type];\n return limit(writer?.(span, direction) ?? generic(span[direction]));\n } catch {\n // A specialized field may be unreadable while the payload still has useful\n // text. Keep fallback bounded here rather than asking storage to serialize it.\n try {\n return generic(span[direction]);\n } catch {\n // Neither formatter can safely preview this payload.\n return '';\n }\n }\n };\n let error = '';\n try {\n error = typeof span.errorPreview === 'string' ? limit(span.errorPreview) : errorPreview(span.errorInfo);\n } catch {\n // Keep errors bounded and safe; never fall back to serializing stack/details.\n }\n return { inputPreview: preview('input'), outputPreview: preview('output'), errorPreview: error };\n}\n","import type { LanguageModelUsage, ProviderMetadata } from '../stream/types';\nimport type { InputTokenDetails, OutputTokenDetails, UsageStats } from './types';\n\nconst usageCountKeys = [\n 'inputTokens',\n 'outputTokens',\n 'totalTokens',\n 'reasoningTokens',\n 'cachedInputTokens',\n 'cacheCreationInputTokens',\n 'cacheCreationInputTokens5m',\n 'cacheCreationInputTokens1h',\n] as const;\n\nexport function isUsageIncomplete(usage: LanguageModelUsage | undefined): boolean {\n return usage?.inputTokens === undefined || usage.outputTokens === undefined || usage.totalTokens === undefined;\n}\n\n/**\n * Usage left after removing what earlier generations of the same run already reported.\n * A resumed run reports cumulative usage, but its suspended legs already recorded part of it.\n */\nexport function subtractReportedUsage(\n usage: LanguageModelUsage | undefined,\n reported: LanguageModelUsage | undefined,\n): LanguageModelUsage | undefined {\n if (!usage || !reported) return usage;\n const remaining: LanguageModelUsage = { ...usage };\n for (const key of usageCountKeys) {\n const value = usage[key];\n if (value !== undefined) {\n remaining[key] = Math.max(0, value - (reported[key] ?? 0));\n }\n }\n return remaining;\n}\n\nexport function calculateObservedUsage(steps: Array<{ usage?: LanguageModelUsage | undefined }>): LanguageModelUsage {\n const usage: LanguageModelUsage = {\n inputTokens: undefined,\n outputTokens: undefined,\n totalTokens: undefined,\n };\n\n for (const step of steps) {\n for (const key of usageCountKeys) {\n const value = step.usage?.[key];\n if (value !== undefined) {\n usage[key] = (usage[key] ?? 0) + value;\n }\n }\n }\n\n if (usage.inputTokens !== undefined && usage.outputTokens !== undefined) {\n usage.totalTokens = usage.inputTokens + usage.outputTokens;\n }\n\n return usage;\n}\n\n/**\n * Provider-specific metadata shapes for type-safe access.\n * These match the actual shapes from AI SDK providers.\n */\ninterface AnthropicCacheCreation {\n ephemeral_5m_input_tokens?: number;\n ephemeral_1h_input_tokens?: number;\n ephemeral5mInputTokens?: number;\n ephemeral1hInputTokens?: number;\n}\n\ninterface AnthropicMetadata {\n cacheReadInputTokens?: number;\n cacheCreationInputTokens?: number;\n cacheCreation?: AnthropicCacheCreation;\n /** Raw API usage object; @ai-sdk/anthropic passes the TTL split through here, not as `cacheCreation`. */\n usage?: { cache_creation?: AnthropicCacheCreation };\n}\n\ninterface GoogleUsageMetadata {\n cachedContentTokenCount?: number;\n thoughtsTokenCount?: number;\n}\n\ninterface GoogleMetadata {\n usageMetadata?: GoogleUsageMetadata;\n}\n\ninterface V3InputUsage {\n total?: number;\n noCache?: number;\n cacheRead?: number;\n cacheWrite?: number;\n}\n\ninterface V3RawUsage {\n inputTokens?: V3InputUsage;\n}\n\nfunction isV3RawUsage(raw: unknown): raw is V3RawUsage {\n return typeof raw === 'object' && raw !== null && 'inputTokens' in raw;\n}\n\n/**\n * AI SDK aggregated input token details.\n * Available on totalUsage in multi-step runs - properly summed across all steps.\n */\ninterface AISdkInputTokenDetails {\n cacheReadTokens?: number;\n cacheWriteTokens?: number;\n}\n\n/**\n * Null-safe check: returns true if value is a number (including 0).\n */\nfunction isDefined(value: unknown): value is number {\n return value != null;\n}\n\n/**\n * Extracts and normalizes token usage from AI SDK response, including\n * provider-specific cache tokens from providerMetadata.\n *\n * Cache token extraction priority (highest to lowest):\n * 1. AI SDK aggregated inputTokenDetails (properly summed across all steps in multi-step runs)\n * 2. Mastra-aggregated top-level usage fields (usage.cachedInputTokens, usage.cacheCreationInputTokens) -\n * summed across steps by RunOutput, so they are correct for multi-step runs.\n * 3. Provider-specific providerMetadata (accurate for single-step, LAST STEP ONLY in multi-step).\n *\n * Handles:\n * - OpenAI: cachedInputTokens in usage object\n * - Anthropic: cacheCreationInputTokens, cacheReadInputTokens in providerMetadata.anthropic\n * - Google/Gemini: cachedContentTokenCount, thoughtsTokenCount in providerMetadata.google.usageMetadata\n * - OpenRouter: Uses OpenAI-compatible structure (cache tokens in usage)\n *\n * Kept in sync with `observability/mastra/src/usage.ts` (duplicated so exporters do not need a newer core).\n * Change both copies together; the parity test in @mastra/observability fails if they drift.\n *\n * @param usage - The LanguageModelV2Usage from AI SDK response\n * @param providerMetadata - Optional provider-specific metadata\n * @returns UsageStats with inputDetails and outputDetails\n */\nexport function extractUsageMetrics(usage?: LanguageModelUsage, providerMetadata?: ProviderMetadata): UsageStats {\n if (!usage) {\n return {};\n }\n\n const inputDetails: InputTokenDetails = {};\n const outputDetails: OutputTokenDetails = {};\n\n let inputTokens = usage.inputTokens;\n const outputTokens = usage.outputTokens;\n\n // ===== AI SDK aggregated format (inputTokenDetails) =====\n // In multi-step runs, providerMetadata only reflects the LAST step.\n // AI SDK's inputTokenDetails is properly aggregated across all steps,\n // so we prefer it as the primary source for cache tokens.\n const aiSdkDetails = (usage as { inputTokenDetails?: AISdkInputTokenDetails }).inputTokenDetails;\n\n if (isDefined(aiSdkDetails?.cacheReadTokens)) {\n inputDetails.cacheRead = aiSdkDetails.cacheReadTokens;\n }\n if (isDefined(aiSdkDetails?.cacheWriteTokens)) {\n inputDetails.cacheWrite = aiSdkDetails.cacheWriteTokens;\n }\n\n // Mastra-aggregated fields — summed across steps by RunOutput; prefer over per-step providerMetadata.\n if (!isDefined(inputDetails.cacheRead) && isDefined(usage.cachedInputTokens)) {\n inputDetails.cacheRead = usage.cachedInputTokens;\n }\n if (isDefined(usage.cacheCreationInputTokens5m)) {\n inputDetails.cacheWrite5m = usage.cacheCreationInputTokens5m;\n }\n if (isDefined(usage.cacheCreationInputTokens1h)) {\n inputDetails.cacheWrite1h = usage.cacheCreationInputTokens1h;\n }\n if (!isDefined(inputDetails.cacheWrite) && isDefined(usage.cacheCreationInputTokens)) {\n inputDetails.cacheWrite = usage.cacheCreationInputTokens;\n }\n // Anthropic cache-creation TTL split. @ai-sdk/anthropic never sets `cacheCreation`; the split\n // arrives raw as `cache_creation` on providerMetadata.anthropic.usage and on usage.raw.\n const anthropic = providerMetadata?.anthropic as AnthropicMetadata | undefined;\n const cacheCreation =\n anthropic?.cacheCreation ??\n anthropic?.usage?.cache_creation ??\n (usage.raw as { cache_creation?: AnthropicCacheCreation } | undefined)?.cache_creation;\n const cacheWrite5m = cacheCreation?.ephemeral_5m_input_tokens ?? cacheCreation?.ephemeral5mInputTokens;\n const cacheWrite1h = cacheCreation?.ephemeral_1h_input_tokens ?? cacheCreation?.ephemeral1hInputTokens;\n if (!isDefined(inputDetails.cacheWrite5m) && isDefined(cacheWrite5m)) {\n inputDetails.cacheWrite5m = cacheWrite5m;\n }\n if (!isDefined(inputDetails.cacheWrite1h) && isDefined(cacheWrite1h)) {\n inputDetails.cacheWrite1h = cacheWrite1h;\n }\n if (\n !isDefined(inputDetails.cacheWrite) &&\n (isDefined(inputDetails.cacheWrite5m) || isDefined(inputDetails.cacheWrite1h))\n ) {\n inputDetails.cacheWrite = (inputDetails.cacheWrite5m ?? 0) + (inputDetails.cacheWrite1h ?? 0);\n }\n\n // reasoningTokens from usage (OpenAI o1 models)\n if (isDefined(usage.reasoningTokens)) {\n outputDetails.reasoning = usage.reasoningTokens;\n }\n\n // ===== Anthropic =====\n // inputTokens does NOT include cache tokens - need to sum them\n if (anthropic) {\n const rawV3InputUsage = isV3RawUsage(usage.raw) ? usage.raw.inputTokens : undefined;\n const hasV3CachedTotals =\n rawV3InputUsage?.total !== undefined &&\n (rawV3InputUsage.cacheRead !== undefined || rawV3InputUsage.cacheWrite !== undefined);\n\n if (!isDefined(inputDetails.cacheRead) && isDefined(anthropic.cacheReadInputTokens)) {\n inputDetails.cacheRead = anthropic.cacheReadInputTokens;\n }\n if (!isDefined(inputDetails.cacheWrite) && isDefined(anthropic.cacheCreationInputTokens)) {\n inputDetails.cacheWrite = anthropic.cacheCreationInputTokens;\n }\n\n // Skip adjustment when inputTokens already includes cache tokens (V3 raw or any positive Mastra-aggregated cache field).\n const inputAlreadyIncludesCache =\n hasV3CachedTotals ||\n (isDefined(usage.cachedInputTokens) && usage.cachedInputTokens > 0) ||\n (isDefined(usage.cacheCreationInputTokens) && usage.cacheCreationInputTokens > 0);\n\n if (!inputAlreadyIncludesCache && (isDefined(inputDetails.cacheRead) || isDefined(inputDetails.cacheWrite))) {\n inputTokens = (usage.inputTokens ?? 0) + (inputDetails.cacheRead ?? 0) + (inputDetails.cacheWrite ?? 0);\n }\n }\n\n // ===== Google/Gemini =====\n // Cache tokens and thoughts are in providerMetadata.google.usageMetadata\n const google = providerMetadata?.google as GoogleMetadata | undefined;\n\n if (google?.usageMetadata) {\n if (!isDefined(inputDetails.cacheRead) && isDefined(google.usageMetadata.cachedContentTokenCount)) {\n inputDetails.cacheRead = google.usageMetadata.cachedContentTokenCount;\n }\n // Gemini \"thoughts\" are similar to reasoning tokens\n if (isDefined(google.usageMetadata.thoughtsTokenCount)) {\n outputDetails.reasoning = google.usageMetadata.thoughtsTokenCount;\n }\n }\n\n if (isDefined(inputTokens)) {\n inputDetails.text = Math.max(\n 0,\n inputTokens - sumDefinedValues(inputDetails, ['cacheRead', 'cacheWrite', 'audio', 'image']),\n );\n }\n\n if (isDefined(outputTokens)) {\n outputDetails.text = Math.max(0, outputTokens - sumDefinedValues(outputDetails, ['reasoning', 'audio', 'image']));\n }\n\n // Build the final UsageStats object\n const result: UsageStats = {\n inputTokens,\n outputTokens,\n };\n\n // Only include details if there's data\n if (Object.keys(inputDetails).length > 0) {\n result.inputDetails = inputDetails;\n }\n if (Object.keys(outputDetails).length > 0) {\n result.outputDetails = outputDetails;\n }\n\n return result;\n}\n\nfunction sumDefinedValues<T extends object, K extends keyof T>(obj: T, keys: K[]): number {\n return keys.reduce((sum, key) => sum + ((obj[key] as number | undefined) ?? 0), 0);\n}\n"],"mappings":";;;;;AACA,MAAa,gBAAgB;CAC3B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;AAuCA,MAAa,oBAAoB;CAC/B,WAAW;CACX,YAAY;CACZ,SAAS;CACT,eAAe;CACf,aAAa;CACb,kBAAkB;CAClB,iBAAiB;CACjB,iBAAiB;CACjB,yBAAyB;CACzB,WAAW;CACX,gBAAgB;CAChB,mBAAmB;CACnB,gBAAgB;CAChB,gBAAgB;CAChB,iBAAiB;CACjB,gBAAgB;CAChB,eAAe;AACjB;;AC/DA,MAAM,QAAQA,OAAAA,EAAE,OAAO,CAAC,CAAC,IAAI,GAAG,CAAC,CAAC,SA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