{"version":3,"file":"index.cjs","names":["SeverityNumber","dateToHrTime","_exhaustive","observability","coreFeatures","ATTR_GEN_AI_USAGE_INPUT_TOKENS","ATTR_GEN_AI_USAGE_OUTPUT_TOKENS","ATTR_GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS","ATTR_GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS","ATTR_GEN_AI_REQUEST_MODEL","ATTR_GEN_AI_PROVIDER_NAME","SpanType","ATTR_GEN_AI_OPERATION_NAME","ATTR_GEN_AI_INPUT_MESSAGES","ATTR_GEN_AI_OUTPUT_MESSAGES","ATTR_GEN_AI_AGENT_ID","ATTR_GEN_AI_AGENT_NAME","ATTR_GEN_AI_REQUEST_TEMPERATURE","ATTR_GEN_AI_REQUEST_MAX_TOKENS","ATTR_GEN_AI_REQUEST_TOP_P","ATTR_GEN_AI_REQUEST_TOP_K","ATTR_GEN_AI_REQUEST_PRESENCE_PENALTY","ATTR_GEN_AI_REQUEST_FREQUENCY_PENALTY","ATTR_GEN_AI_REQUEST_STOP_SEQUENCES","ATTR_GEN_AI_REQUEST_SEED","ATTR_GEN_AI_RESPONSE_FINISH_REASONS","ATTR_GEN_AI_RESPONSE_MODEL","ATTR_GEN_AI_RESPONSE_ID","ATTR_SERVER_ADDRESS","ATTR_SERVER_PORT","ATTR_GEN_AI_TOOL_NAME","ATTR_GEN_AI_TOOL_DESCRIPTION","ATTR_GEN_AI_CONVERSATION_ID","ATTR_GEN_AI_SYSTEM_INSTRUCTIONS","ATTR_ERROR_TYPE","ATTR_ERROR_MESSAGE","ATTR_SERVICE_NAME","ATTR_SERVICE_VERSION","ATTR_TELEMETRY_SDK_NAME","ATTR_TELEMETRY_SDK_VERSION","ATTR_TELEMETRY_SDK_LANGUAGE","TraceFlags","SpanKind","SpanType","SpanStatusCode","ExportResultCode","BaseExporter","DiagConsoleLogger","DiagLogLevel","BatchSpanProcessor","ATTR_SERVICE_NAME","LoggerProvider","BatchLogRecordProcessor","TracingEventType","apiContext","trace","TraceFlags"],"sources":["../src/loadExporter.ts","../src/log-converter.ts","../src/provider-configs.ts","../src/features.ts","../src/gen-ai-messages.ts","../src/gen-ai-semantics.ts","../src/span-converter.ts","../src/tracing.ts"],"sourcesContent":["/**\n * Dynamic loader for optional OTel signal exporters.\n *\n * Each combination of signal (traces/logs) and protocol (http/json,\n * http/protobuf, grpc, zipkin) maps to a different npm package. We dynamically\n * import only the one the user's provider config requires, and cache the\n * constructor so subsequent calls are free.\n */\n\nimport type { ExportProtocol } from './types.js';\n\nexport type SignalType = 'traces' | 'logs';\n\n// ---------------------------------------------------------------------------\n// Package / export-name matrix\n// ---------------------------------------------------------------------------\n\ninterface ExporterSpec {\n  /** npm package to dynamic-import */\n  pkg: string;\n  /** Named export to pull from the package */\n  exportName: string;\n  /** Extra packages to mention in the install hint (e.g. @grpc/grpc-js) */\n  extras?: string[];\n}\n\ntype ProtocolKey = 'http/json' | 'http/protobuf' | 'grpc' | 'zipkin';\n\nconst EXPORTER_SPECS: Record<SignalType, Partial<Record<ProtocolKey, ExporterSpec>>> = {\n  traces: {\n    'http/json': { pkg: '@opentelemetry/exporter-trace-otlp-http', exportName: 'OTLPTraceExporter' },\n    'http/protobuf': { pkg: '@opentelemetry/exporter-trace-otlp-proto', exportName: 'OTLPTraceExporter' },\n    grpc: {\n      pkg: '@opentelemetry/exporter-trace-otlp-grpc',\n      exportName: 'OTLPTraceExporter',\n      extras: ['@grpc/grpc-js'],\n    },\n    zipkin: { pkg: '@opentelemetry/exporter-zipkin', exportName: 'ZipkinExporter' },\n  },\n  logs: {\n    'http/json': { pkg: '@opentelemetry/exporter-logs-otlp-http', exportName: 'OTLPLogExporter' },\n    'http/protobuf': { pkg: '@opentelemetry/exporter-logs-otlp-proto', exportName: 'OTLPLogExporter' },\n    grpc: {\n      pkg: '@opentelemetry/exporter-logs-otlp-grpc',\n      exportName: 'OTLPLogExporter',\n      extras: ['@grpc/grpc-js'],\n    },\n    // zipkin: not supported\n  },\n};\n\n// ---------------------------------------------------------------------------\n// Cache + loader\n// ---------------------------------------------------------------------------\n\n/** Cache keyed by \"signal:protocol\" */\nconst cache = new Map<string, any>();\n\n/**\n * Load a trace exporter for the given protocol.\n * Backward-compatible with existing usage in tracing.ts.\n */\nexport async function loadExporter(protocol: ExportProtocol, provider?: string): Promise<any> {\n  return loadSignalExporter('traces', protocol, provider);\n}\n\n/**\n * Load a signal-specific exporter class for the given protocol.\n * Returns the constructor, or null if the package isn't installed.\n */\nexport async function loadSignalExporter(\n  signal: SignalType,\n  protocol: ExportProtocol,\n  provider?: string,\n): Promise<any> {\n  const spec = EXPORTER_SPECS[signal]?.[protocol];\n\n  if (!spec) {\n    if (protocol === 'zipkin') {\n      console.warn(\n        `[OtelExporter] Zipkin does not support OTLP ${signal}. ${capitalize(signal)} export will be disabled.`,\n      );\n    }\n    return null;\n  }\n\n  const cacheKey = `${signal}:${protocol}`;\n  if (cache.has(cacheKey)) {\n    return cache.get(cacheKey);\n  }\n\n  try {\n    const mod = await import(spec.pkg);\n    const ExporterClass = mod[spec.exportName];\n    if (typeof ExporterClass !== 'function') {\n      console.error(\n        `[OtelExporter] ${capitalize(signal)} ${protocol} exporter package \"${spec.pkg}\" did not expose a \"${spec.exportName}\" export. ` +\n          `${capitalize(signal)} export will be disabled.`,\n      );\n      return null;\n    }\n    cache.set(cacheKey, ExporterClass);\n    return ExporterClass;\n  } catch {\n    const providerInfo = provider ? ` (required for ${provider})` : '';\n    const allPkgs = [spec.pkg, ...(spec.extras ?? [])].join(' ');\n    console.error(\n      `[OtelExporter] ${capitalize(signal)} ${protocol} exporter is not installed${providerInfo}.\\n` +\n        `  Install the required package(s):\\n` +\n        `  npm install ${allPkgs}`,\n    );\n    return null;\n  }\n}\n\nfunction capitalize(s: string): string {\n  return s.charAt(0).toUpperCase() + s.slice(1);\n}\n","/**\n * Convert Mastra ExportedLog to OpenTelemetry LogRecord format\n */\n\nimport type { ExportedLog, LogLevel } from '@mastra/core/observability';\nimport type { HrTime } from '@opentelemetry/api';\nimport type { LogAttributes } from '@opentelemetry/api-logs';\nimport { SeverityNumber } from '@opentelemetry/api-logs';\n\n/**\n * Map Mastra LogLevel to OTEL SeverityNumber\n */\nexport function mapSeverity(level: LogLevel): SeverityNumber {\n  switch (level) {\n    case 'debug':\n      return SeverityNumber.DEBUG;\n    case 'info':\n      return SeverityNumber.INFO;\n    case 'warn':\n      return SeverityNumber.WARN;\n    case 'error':\n      return SeverityNumber.ERROR;\n    case 'fatal':\n      return SeverityNumber.FATAL;\n    default:\n      return SeverityNumber.UNSPECIFIED;\n  }\n}\n\n/**\n * Convert a Date to OTEL HrTime [seconds, nanoseconds]\n */\nfunction dateToHrTime(date: Date): HrTime {\n  const ms = date.getTime();\n  const seconds = Math.floor(ms / 1000);\n  const nanoseconds = (ms % 1000) * 1_000_000;\n  return [seconds, nanoseconds];\n}\n\n/**\n * Stringify a value for use as an OTEL log attribute. Falls back to a\n * placeholder rather than throwing if the value contains a circular\n * reference, throws from a custom toJSON, or otherwise cannot be serialized.\n */\nfunction safeStringify(value: unknown): string {\n  try {\n    return JSON.stringify(value);\n  } catch {\n    return '[unserializable]';\n  }\n}\n\n/**\n * Build OTEL log attributes from ExportedLog fields.\n * Includes trace correlation and metadata.\n */\nexport function buildLogAttributes(log: ExportedLog): LogAttributes {\n  const attributes: LogAttributes = {};\n\n  // Add structured data fields as attributes\n  if (log.data) {\n    for (const [key, value] of Object.entries(log.data)) {\n      if (value === null || value === undefined) continue;\n      attributes[`mastra.log.${key}`] =\n        typeof value === 'object' ? safeStringify(value) : (value as string | number | boolean);\n    }\n  }\n\n  // Add metadata as attributes\n  if (log.metadata) {\n    for (const [key, value] of Object.entries(log.metadata)) {\n      if (value === null || value === undefined) continue;\n      attributes[`mastra.metadata.${key}`] =\n        typeof value === 'object' ? safeStringify(value) : (value as string | number | boolean);\n    }\n  }\n\n  // Add tags if present\n  if (log.tags?.length) {\n    attributes['mastra.tags'] = safeStringify(log.tags);\n  }\n\n  return attributes;\n}\n\n/**\n * Parameters for emitting an OTEL log record from a Mastra ExportedLog.\n */\nexport interface OtelLogEmitParams {\n  timestamp: HrTime;\n  severityNumber: SeverityNumber;\n  severityText: string;\n  body: string;\n  attributes: LogAttributes;\n  traceId?: string;\n  spanId?: string;\n}\n\n/**\n * Convert an ExportedLog into parameters suitable for OTEL Logger.emit()\n */\nexport function convertLog(log: ExportedLog): OtelLogEmitParams {\n  return {\n    timestamp: dateToHrTime(log.timestamp),\n    severityNumber: mapSeverity(log.level),\n    severityText: log.level.toUpperCase(),\n    body: log.message,\n    attributes: buildLogAttributes(log),\n    traceId: log.traceId,\n    spanId: log.spanId,\n  };\n}\n","/**\n * Provider-specific configurations for OtelExporters\n */\n\nimport type {\n  ProviderConfig,\n  ExportProtocol,\n  Dash0Config,\n  SignozConfig,\n  NewRelicConfig,\n  TraceloopConfig,\n  LaminarConfig,\n  CustomConfig,\n} from './types.js';\n\nexport interface ResolvedProviderConfig {\n  endpoint: string;\n  headers: Record<string, string>;\n  protocol: ExportProtocol;\n}\n\nexport function resolveProviderConfig(config: ProviderConfig, debug?: boolean): ResolvedProviderConfig | null {\n  const providerName = Object.keys(config)[0];\n\n  if (debug) {\n    console.info(`[OtelExporter:debug] Resolving provider config for: ${providerName}`);\n  }\n\n  let resolved: ResolvedProviderConfig | null;\n\n  if ('dash0' in config) {\n    resolved = resolveDash0Config(config.dash0);\n  } else if ('signoz' in config) {\n    resolved = resolveSignozConfig(config.signoz);\n  } else if ('newrelic' in config) {\n    resolved = resolveNewRelicConfig(config.newrelic);\n  } else if ('traceloop' in config) {\n    resolved = resolveTraceloopConfig(config.traceloop);\n  } else if ('laminar' in config) {\n    resolved = resolveLaminarConfig(config.laminar);\n  } else if ('custom' in config) {\n    resolved = resolveCustomConfig(config.custom);\n  } else {\n    // TypeScript exhaustiveness check\n    const _exhaustive: never = config;\n    return _exhaustive;\n  }\n\n  if (debug && resolved) {\n    // Header values frequently carry credentials (Bearer tokens, API keys, Basic auth).\n    // Don't log any portion of the value — even prefix/suffix slices can leak.\n    const maskedHeaders: Record<string, string> = {};\n    for (const [key, value] of Object.entries(resolved.headers)) {\n      maskedHeaders[key] = value ? '[REDACTED]' : '[EMPTY]';\n    }\n    console.info(`[OtelExporter:debug] Provider \"${providerName}\" resolved:`, {\n      endpoint: resolved.endpoint,\n      protocol: resolved.protocol,\n      headers: maskedHeaders,\n    });\n  } else if (debug && !resolved) {\n    console.info(`[OtelExporter:debug] Provider \"${providerName}\" resolution returned null (disabled)`);\n  }\n\n  return resolved;\n}\n\nfunction resolveDash0Config(config: Dash0Config): ResolvedProviderConfig | null {\n  // Read from config or environment variables\n  const apiKey = config.apiKey ?? process.env.DASH0_API_KEY;\n  const configEndpoint = config.endpoint ?? process.env.DASH0_ENDPOINT;\n  const dataset = config.dataset ?? process.env.DASH0_DATASET;\n\n  if (!apiKey) {\n    console.error(\n      '[OtelExporter] Dash0 configuration requires apiKey. ' +\n        'Set DASH0_API_KEY environment variable or pass it in config. Tracing will be disabled.',\n    );\n    return null;\n  }\n\n  if (!configEndpoint) {\n    console.error(\n      '[OtelExporter] Dash0 configuration requires endpoint. ' +\n        'Set DASH0_ENDPOINT environment variable or pass it in config. Tracing will be disabled.',\n    );\n    return null;\n  }\n\n  // Dash0 uses gRPC by default\n  // Endpoint should be like: ingress.us-west-2.aws.dash0.com:4317\n  // gRPC endpoints also need /v1/traces suffix\n  // Requires: npm install @opentelemetry/exporter-trace-otlp-grpc @grpc/grpc-js\n  let endpoint = configEndpoint;\n  if (!endpoint.includes('/v1/traces')) {\n    endpoint = `${endpoint}/v1/traces`;\n  }\n\n  const headers: Record<string, string> = {\n    authorization: `Bearer ${apiKey}`, // lowercase for gRPC metadata\n  };\n\n  if (dataset) {\n    headers['dash0-dataset'] = dataset; // lowercase for gRPC metadata\n  }\n\n  return {\n    endpoint,\n    headers,\n    protocol: 'grpc', // Use gRPC for Dash0\n  };\n}\n\nfunction resolveSignozConfig(config: SignozConfig): ResolvedProviderConfig | null {\n  // Read from config or environment variables\n  const apiKey = config.apiKey ?? process.env.SIGNOZ_API_KEY;\n  const region = config.region ?? (process.env.SIGNOZ_REGION as 'us' | 'eu' | 'in' | undefined);\n  const configEndpoint = config.endpoint ?? process.env.SIGNOZ_ENDPOINT;\n\n  if (!apiKey) {\n    console.error(\n      '[OtelExporter] SigNoz configuration requires apiKey. ' +\n        'Set SIGNOZ_API_KEY environment variable or pass it in config. Tracing will be disabled.',\n    );\n    return null;\n  }\n\n  // SigNoz uses OTLP endpoint with /v1/traces suffix\n  const endpoint = configEndpoint || `https://ingest.${region || 'us'}.signoz.cloud:443/v1/traces`;\n\n  return {\n    endpoint,\n    headers: {\n      'signoz-ingestion-key': apiKey,\n    },\n    protocol: 'http/protobuf',\n  };\n}\n\nfunction resolveNewRelicConfig(config: NewRelicConfig): ResolvedProviderConfig | null {\n  // Read from config or environment variables\n  const apiKey = config.apiKey ?? process.env.NEW_RELIC_LICENSE_KEY;\n  const configEndpoint = config.endpoint ?? process.env.NEW_RELIC_ENDPOINT;\n\n  if (!apiKey) {\n    console.error(\n      '[OtelExporter] New Relic configuration requires apiKey (license key). ' +\n        'Set NEW_RELIC_LICENSE_KEY environment variable or pass it in config. Tracing will be disabled.',\n    );\n    return null;\n  }\n\n  // New Relic recommends HTTP/protobuf over gRPC\n  // New Relic uses OTLP endpoint with /v1/traces suffix\n  const endpoint = configEndpoint || 'https://otlp.nr-data.net:443/v1/traces';\n\n  return {\n    endpoint,\n    headers: {\n      'api-key': apiKey,\n    },\n    protocol: 'http/protobuf',\n  };\n}\n\nfunction resolveTraceloopConfig(config: TraceloopConfig): ResolvedProviderConfig | null {\n  // Read from config or environment variables\n  const apiKey = config.apiKey ?? process.env.TRACELOOP_API_KEY;\n  const destinationId = config.destinationId ?? process.env.TRACELOOP_DESTINATION_ID;\n  const configEndpoint = config.endpoint ?? process.env.TRACELOOP_ENDPOINT;\n\n  if (!apiKey) {\n    console.error(\n      '[OtelExporter] Traceloop configuration requires apiKey. ' +\n        'Set TRACELOOP_API_KEY environment variable or pass it in config. Tracing will be disabled.',\n    );\n    return null;\n  }\n\n  // Traceloop uses OTLP endpoint with /v1/traces suffix\n  const endpoint = configEndpoint || 'https://api.traceloop.com/v1/traces';\n\n  const headers: Record<string, string> = {\n    Authorization: `Bearer ${apiKey}`,\n  };\n\n  if (destinationId) {\n    headers['x-traceloop-destination-id'] = destinationId;\n  }\n\n  return {\n    endpoint,\n    headers,\n    protocol: 'http/json',\n  };\n}\n\nfunction resolveLaminarConfig(config: LaminarConfig): ResolvedProviderConfig | null {\n  // Read from config or environment variables\n  // LMNR_PROJECT_API_KEY is the standard Laminar environment variable\n  const apiKey = config.apiKey ?? process.env.LMNR_PROJECT_API_KEY;\n  const configEndpoint = config.endpoint ?? process.env.LAMINAR_ENDPOINT;\n\n  if (!apiKey) {\n    console.error(\n      '[OtelExporter] Laminar configuration requires apiKey. ' +\n        'Set LMNR_PROJECT_API_KEY environment variable or pass it in config. Tracing will be disabled.',\n    );\n    return null;\n  }\n\n  // Laminar uses OTLP endpoint with /v1/traces suffix for HTTP\n  // They support both gRPC and HTTP, but we'll use HTTP for consistency\n  const endpoint = configEndpoint || 'https://api.lmnr.ai/v1/traces';\n\n  const headers: Record<string, string> = {\n    Authorization: `Bearer ${apiKey}`,\n  };\n\n  return {\n    endpoint,\n    headers,\n    protocol: 'http/protobuf', // Use HTTP/protobuf instead of gRPC for better compatibility\n  };\n}\n\nfunction resolveCustomConfig(config: CustomConfig): ResolvedProviderConfig | null {\n  if (!config.endpoint) {\n    console.error('[OtelExporter] Custom configuration requires endpoint. Tracing will be disabled.');\n    return null;\n  }\n\n  return {\n    endpoint: config.endpoint,\n    headers: config.headers || {},\n    protocol: config.protocol || 'http/json',\n  };\n}\n","/**\n * Feature detection for paired @mastra/core and @mastra/observability versions.\n *\n * Both are resolved synchronously so span classification is stable from the\n * very first span: `OtelBridge.createSpan()` picks the OTEL SpanKind at\n * `startSpan()` time, where it can no longer change, so detection must not\n * depend on a pending dynamic import.\n *\n * `@mastra/observability` is a hard dependency, but older versions do not\n * export `observabilityFeatures`. The namespace import reads it as `undefined`\n * in that case instead of failing to link, which is the graceful fallback\n * documented in `observability/mastra/src/features.ts`.\n */\n\nimport { coreFeatures } from '@mastra/core/features';\nimport * as observability from '@mastra/observability';\n\nconst FEATURE = 'model-inference-span';\n\nlet observabilityFeatures: ReadonlySet<string> | undefined = (\n  observability as { observabilityFeatures?: ReadonlySet<string> }\n).observabilityFeatures;\n\n/**\n * Returns true when both packages report the `model-inference-span` feature,\n * meaning MODEL_INFERENCE spans are emitted by the tracker. Drives which span\n * is exported as the GenAI `chat` call (new: MODEL_INFERENCE; legacy:\n * MODEL_GENERATION).\n */\nexport function isModelInferenceEnabled(): boolean {\n  return observabilityFeatures?.has(FEATURE) === true && coreFeatures.has(FEATURE);\n}\n\n/**\n * @internal Test-only override. Allows tests to simulate a paired older or\n * newer `@mastra/observability` without juggling module mocks.\n */\nexport function __setObservabilityFeaturesForTest(features: ReadonlySet<string> | undefined): void {\n  observabilityFeatures = features;\n}\n","/**\n * Utilities for converting Mastra messages to OpenTelemetry gen_ai message format\n * Based on OpenTelemetry GenAI semantic conventions\n * @see https://opentelemetry.io/docs/specs/semconv/registry/attributes/gen-ai/#gen-ai-input-messages\n * @see https://opentelemetry.io/docs/specs/semconv/gen-ai/gen-ai-input-messages.json\n */\n\n/**\n * Type representation of a gen_ai chat message part\n */\ntype GenAIMessagePart =\n  | {\n      type: 'text';\n      content: string;\n    }\n  | {\n      type: 'tool_call';\n      id: string;\n      name: string;\n      arguments: string;\n    }\n  | {\n      type: 'tool_call_response';\n      id: string;\n      name: string;\n      response: string;\n    };\n\n/**\n * Type representation of a gen_ai chat message\n */\ntype GenAIMessage = {\n  role: string;\n  parts: GenAIMessagePart[];\n};\n\n/**\n * Assumed type representation of a Mastra message content type\n */\ntype MastraMessagePart =\n  | {\n      type: 'text';\n      text: string;\n    }\n  | { type: 'tool-call'; toolCallId: string; toolName: string; input: unknown }\n  | { type: 'tool-result'; toolCallId: string; toolName: string; output: { value: unknown } };\n\n/**\n * Assumed type representation of a Mastra message\n */\ntype MastraMessage = {\n  role: string;\n  content: MastraMessagePart[] | string;\n};\n\nconst isMastraMessagePart = (p: unknown): p is MastraMessagePart => {\n  return (\n    typeof p === 'object' &&\n    p != null &&\n    'type' in p &&\n    (p.type === 'text' || p.type === 'tool-call' || p.type === 'tool-result') &&\n    ((p.type === 'text' && 'text' in p) ||\n      (p.type === 'tool-call' && 'toolCallId' in p && 'toolName' in p && 'input' in p) ||\n      (p.type === 'tool-result' && 'toolCallId' in p && 'toolName' in p && 'output' in p))\n  );\n};\n\nconst isMastraMessage = (m: unknown): m is MastraMessage => {\n  return (\n    typeof m === 'object' &&\n    m != null &&\n    'role' in m &&\n    'content' in m &&\n    (typeof m.content === 'string' || (Array.isArray(m.content) && m.content.every(isMastraMessagePart)))\n  );\n};\n\n/**\n * Convert an Input/Output string from a MastraSpan into a jsonified string that adheres to\n * OpenTelemetry gen_ai.input.messages and gen_ai.output.messages schema.\n * If parsing fails at any step, the original inputOutputString is returned unmodified.\n *\n * This conversion is best effort; It assumes a consistent shape for mastra messages, and converts\n * into the gen_ai input and output schemas as of October 20th, 2025.\n *\n * @see https://opentelemetry.io/docs/specs/semconv/registry/attributes/gen-ai/#gen-ai-input-messages\n * @see https://opentelemetry.io/docs/specs/semconv/gen-ai/gen-ai-input-messages.json\n * @see https://opentelemetry.io/docs/specs/semconv/registry/attributes/gen-ai/#gen-ai-output-messages\n * @see https://opentelemetry.io/docs/specs/semconv/gen-ai/gen-ai-output-messages.json\n *\n * @param inputOutputString a jsonified string that contains messages adhering to what appears to be\n * Mastra's message shape.\n * @returns a jsonified string that contains messages adhering to the OpenTelemetry gen_ai.input.messages and gen_ai.output.messages schema.\n * If parsing fails at any step, the original inputOutputString is returned unmodified.\n */\nconst toGenAIMessage = (m: MastraMessage): GenAIMessage => {\n  const parts: GenAIMessagePart[] = Array.isArray(m.content)\n    ? m.content.map((c): GenAIMessagePart => {\n        switch (c.type) {\n          case 'text':\n            return { type: 'text', content: c.text };\n          case 'tool-call':\n            return { type: 'tool_call', id: c.toolCallId, name: c.toolName, arguments: JSON.stringify(c.input) };\n          case 'tool-result':\n            return {\n              type: 'tool_call_response',\n              id: c.toolCallId,\n              name: c.toolName,\n              response: JSON.stringify(c.output.value),\n            };\n        }\n      })\n    : [{ type: 'text', content: m.content }];\n  return { role: m.role, parts };\n};\n\n/**\n * Model output as recorded on MODEL_STEP / MODEL_INFERENCE spans: `{ text, toolCalls }`.\n * A tool-only step has `text: ''` and one or more tool calls.\n */\ntype MastraModelOutput = {\n  text?: unknown;\n  toolCalls?: unknown;\n};\n\nconst toGenAIOutputMessage = (output: MastraModelOutput): GenAIMessage => {\n  const parts: GenAIMessagePart[] = [];\n  const toolCalls = Array.isArray(output.toolCalls) ? output.toolCalls : [];\n  const text = typeof output.text === 'string' ? output.text : undefined;\n  // Keep the text part unless it is empty and the step was tool-only.\n  if (text !== undefined && (text.length > 0 || toolCalls.length === 0)) {\n    parts.push({ type: 'text', content: text });\n  }\n  for (const call of toolCalls) {\n    if (typeof call !== 'object' || call == null) continue;\n    const c = call as { toolCallId?: unknown; toolName?: unknown; args?: unknown; input?: unknown };\n    parts.push({\n      type: 'tool_call',\n      id: String(c.toolCallId ?? ''),\n      name: String(c.toolName ?? ''),\n      arguments: JSON.stringify(c.args ?? c.input),\n    });\n  }\n  return { role: 'assistant', parts };\n};\n\nexport const convertMastraMessagesToGenAIMessages = (inputOutputString: string): string => {\n  try {\n    const parsedIO = JSON.parse(inputOutputString) as unknown;\n    if (typeof parsedIO !== 'object' || parsedIO == null) {\n      return inputOutputString;\n    }\n    // A bare message list: the shallow prompt preview recorded on\n    // MODEL_STEP / MODEL_INFERENCE spans.\n    if (Array.isArray(parsedIO)) {\n      return parsedIO.every(isMastraMessage) ? JSON.stringify(parsedIO.map(toGenAIMessage)) : inputOutputString;\n    }\n    // Model output `{ text, toolCalls }` becomes one assistant message with a\n    // text part and a tool_call part per tool call.\n    if ('text' in parsedIO || 'toolCalls' in parsedIO) {\n      return JSON.stringify([toGenAIOutputMessage(parsedIO as MastraModelOutput)]);\n    }\n    // if the IO contains messages, convert them to gen_ai messages\n    if ('messages' in parsedIO && Array.isArray(parsedIO.messages)) {\n      return JSON.stringify((parsedIO.messages as unknown[]).map(m => (isMastraMessage(m) ? toGenAIMessage(m) : m)));\n    }\n    // we've failed type-guards, just return original I/O string\n    return inputOutputString;\n  } catch {\n    // silently fallback to original I/O string\n    return inputOutputString;\n  }\n};\n","/**\n * Utilities for converting Mastra Spans to OTel Spans\n * with Semantic conventions for generative AI systems\n * @see https://github.com/open-telemetry/semantic-conventions/blob/v1.38.0/docs/gen-ai/README.md\n * @see https://github.com/open-telemetry/semantic-conventions/blob/v1.38.0/docs/gen-ai/gen-ai-events.md\n * @see https://github.com/open-telemetry/semantic-conventions/blob/v1.38.0/docs/gen-ai/gen-ai-spans.md\n * @see https://github.com/open-telemetry/semantic-conventions/blob/v1.38.0/docs/gen-ai/gen-ai-agent-spans.md\n * @see https://opentelemetry.io/docs/specs/semconv/gen-ai/non-normative/examples-llm-calls/\n * @see https://opentelemetry.io/docs/specs/semconv/registry/attributes/gen-ai/\n */\n\nimport { SpanType } from '@mastra/core/observability';\nimport type {\n  AgentRunAttributes,\n  AnyExportedSpan,\n  MCPServerRequestAttributes,\n  MCPToolCallAttributes,\n  ModelGenerationAttributes,\n  ModelInferenceAttributes,\n  ModelStepAttributes,\n  RagEmbeddingAttributes,\n  ToolCallAttributes,\n  UsageStats,\n  WorkflowConditionalAttributes,\n  WorkflowConditionalEvalAttributes,\n  WorkflowLoopAttributes,\n  WorkflowParallelAttributes,\n  WorkflowRunAttributes,\n  WorkflowSleepAttributes,\n  WorkflowStepAttributes,\n  WorkflowWaitEventAttributes,\n} from '@mastra/core/observability';\nimport type { Attributes } from '@opentelemetry/api';\nimport {\n  ATTR_ERROR_MESSAGE,\n  ATTR_ERROR_TYPE,\n  ATTR_GEN_AI_PROVIDER_NAME,\n  ATTR_GEN_AI_REQUEST_MODEL,\n  ATTR_GEN_AI_RESPONSE_MODEL,\n  ATTR_GEN_AI_REQUEST_MAX_TOKENS,\n  ATTR_GEN_AI_REQUEST_TEMPERATURE,\n  ATTR_GEN_AI_REQUEST_TOP_P,\n  ATTR_GEN_AI_REQUEST_TOP_K,\n  ATTR_GEN_AI_REQUEST_PRESENCE_PENALTY,\n  ATTR_GEN_AI_REQUEST_FREQUENCY_PENALTY,\n  ATTR_GEN_AI_REQUEST_STOP_SEQUENCES,\n  ATTR_GEN_AI_REQUEST_SEED,\n  ATTR_GEN_AI_INPUT_MESSAGES,\n  ATTR_GEN_AI_OUTPUT_MESSAGES,\n  ATTR_GEN_AI_USAGE_INPUT_TOKENS,\n  ATTR_GEN_AI_USAGE_OUTPUT_TOKENS,\n  ATTR_GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS,\n  ATTR_GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS,\n  ATTR_GEN_AI_AGENT_ID,\n  ATTR_GEN_AI_AGENT_NAME,\n  ATTR_GEN_AI_TOOL_DESCRIPTION,\n  ATTR_GEN_AI_OPERATION_NAME,\n  ATTR_GEN_AI_RESPONSE_FINISH_REASONS,\n  ATTR_GEN_AI_RESPONSE_ID,\n  ATTR_GEN_AI_CONVERSATION_ID,\n  ATTR_GEN_AI_SYSTEM_INSTRUCTIONS,\n  ATTR_SERVER_ADDRESS,\n  ATTR_SERVER_PORT,\n  ATTR_GEN_AI_TOOL_NAME,\n} from '@opentelemetry/semantic-conventions/incubating';\nimport { isModelInferenceEnabled } from './features';\nimport { convertMastraMessagesToGenAIMessages } from './gen-ai-messages';\n\n/**\n * Token usage attributes following OTel GenAI semantic conventions.\n * @see https://opentelemetry.io/docs/specs/semconv/gen-ai/gen-ai-spans/\n */\nexport interface OtelUsageMetrics {\n  [ATTR_GEN_AI_USAGE_INPUT_TOKENS]?: number;\n  [ATTR_GEN_AI_USAGE_OUTPUT_TOKENS]?: number;\n  [ATTR_GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS]?: number;\n  [ATTR_GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS]?: number;\n  'gen_ai.usage.cache_creation.5m_input_tokens'?: number;\n  'gen_ai.usage.cache_creation.1h_input_tokens'?: number;\n  'gen_ai.usage.reasoning_tokens'?: number;\n  'gen_ai.usage.audio_input_tokens'?: number;\n  'gen_ai.usage.audio_output_tokens'?: number;\n}\n\n/**\n * Formats UsageStats to OTel GenAI semantic convention attributes.\n */\nexport function formatUsageMetrics(usage?: UsageStats): OtelUsageMetrics {\n  if (!usage) return {};\n\n  const metrics: OtelUsageMetrics = {};\n\n  if (usage.inputTokens !== undefined) {\n    metrics[ATTR_GEN_AI_USAGE_INPUT_TOKENS] = usage.inputTokens;\n  }\n\n  if (usage.outputTokens !== undefined) {\n    metrics[ATTR_GEN_AI_USAGE_OUTPUT_TOKENS] = usage.outputTokens;\n  }\n\n  // Reasoning tokens from outputDetails\n  if (usage.outputDetails?.reasoning !== undefined) {\n    metrics['gen_ai.usage.reasoning_tokens'] = usage.outputDetails.reasoning;\n  }\n\n  // Cache read input tokens (subset of input_tokens)\n  if (usage.inputDetails?.cacheRead !== undefined) {\n    metrics[ATTR_GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS] = usage.inputDetails.cacheRead;\n  }\n\n  // Cache creation input tokens (subset of input_tokens)\n  if (usage.inputDetails?.cacheWrite !== undefined) {\n    metrics[ATTR_GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS] = usage.inputDetails.cacheWrite;\n  }\n  if (usage.inputDetails?.cacheWrite5m !== undefined) {\n    metrics['gen_ai.usage.cache_creation.5m_input_tokens'] = usage.inputDetails.cacheWrite5m;\n  }\n  if (usage.inputDetails?.cacheWrite1h !== undefined) {\n    metrics['gen_ai.usage.cache_creation.1h_input_tokens'] = usage.inputDetails.cacheWrite1h;\n  }\n\n  // Audio tokens from inputDetails/outputDetails\n  if (usage.inputDetails?.audio !== undefined) {\n    metrics['gen_ai.usage.audio_input_tokens'] = usage.inputDetails.audio;\n  }\n  if (usage.outputDetails?.audio !== undefined) {\n    metrics['gen_ai.usage.audio_output_tokens'] = usage.outputDetails.audio;\n  }\n\n  return metrics;\n}\n\nfunction addModelRequestAttributes(\n  attributes: Attributes,\n  attrs: Pick<ModelGenerationAttributes | RagEmbeddingAttributes, 'model' | 'provider' | 'usage'>,\n): void {\n  if (attrs.model) {\n    attributes[ATTR_GEN_AI_REQUEST_MODEL] = attrs.model;\n  }\n\n  if (attrs.provider) {\n    attributes[ATTR_GEN_AI_PROVIDER_NAME] = normalizeProvider(attrs.provider);\n  }\n\n  Object.assign(attributes, formatUsageMetrics(attrs.usage));\n}\n\n/** Attributes of whichever span represents the model call. */\ntype ModelCallAttributes = ModelGenerationAttributes & ModelInferenceAttributes;\n\n/**\n * Whether this span is exported as the GenAI inference (`chat`) span.\n *\n * Exactly one span per model call carries `gen_ai.request.model`, the messages\n * and `gen_ai.usage.*`, because OTel backends (Langfuse, Phoenix, ...) sum usage\n * across nested spans. With paired packages that emit MODEL_INFERENCE, that is\n * the call; MODEL_GENERATION is then the parent loop and MODEL_STEP one turn of\n * it. Older pairings only emit MODEL_GENERATION, which keeps the `chat` role.\n */\nexport function isModelCallSpan(type: SpanType): boolean {\n  return type === (isModelInferenceEnabled() ? SpanType.MODEL_INFERENCE : SpanType.MODEL_GENERATION);\n}\n\nexport interface GenAISemanticsOptions {\n  /**\n   * Override {@link isModelCallSpan} for this span. Exporters that flatten the\n   * generation loop into a single `chat` span pass `true` for MODEL_GENERATION.\n   */\n  modelCall?: boolean;\n}\n\n/**\n * Get the operation name based on span type for gen_ai.operation.name\n */\nfunction getOperationName(span: AnyExportedSpan, modelCall = isModelCallSpan(span.type)): string {\n  if (modelCall) {\n    return 'chat';\n  }\n  switch (span.type) {\n    case SpanType.MODEL_STEP:\n      return 'agent_step';\n    case SpanType.RAG_EMBEDDING:\n      return 'embeddings';\n    case SpanType.TOOL_CALL:\n    case SpanType.MCP_TOOL_CALL:\n    case SpanType.PROVIDER_TOOL_CALL:\n      return 'execute_tool';\n    case SpanType.AGENT_RUN:\n      return 'invoke_agent';\n    case SpanType.WORKFLOW_RUN:\n      return 'invoke_workflow';\n    default:\n      return span.type.toLowerCase();\n  }\n}\n/**\n * Keep only unicode letters, numbers, dot, underscore, space, dash.\n */\nfunction sanitizeSpanName(name: string): string {\n  return name.replace(/[^\\p{L}\\p{N}._ -]/gu, '');\n}\n\nfunction getSpanIdentifier(span: AnyExportedSpan): string | undefined {\n  switch (span.type) {\n    case SpanType.MODEL_GENERATION:\n    case SpanType.MODEL_INFERENCE: {\n      const attrs = span.attributes as ModelCallAttributes | undefined;\n      return attrs?.model;\n    }\n    case SpanType.RAG_EMBEDDING: {\n      const attrs = span.attributes as RagEmbeddingAttributes;\n      return attrs?.model;\n    }\n\n    // Workflow step spans set their own entityId (the step id) but inherit\n    // entityName from the enclosing workflow, so identify them by entityId.\n    case SpanType.WORKFLOW_STEP:\n      return span.entityId;\n\n    // Control-flow spans set no entity of their own and would otherwise inherit\n    // the enclosing workflow's entityName, collapsing siblings onto one name.\n    // Fall through to the authored span name, which already carries the\n    // condition index / branch descriptor.\n    case SpanType.WORKFLOW_CONDITIONAL:\n    case SpanType.WORKFLOW_CONDITIONAL_EVAL:\n    case SpanType.WORKFLOW_PARALLEL:\n    case SpanType.WORKFLOW_LOOP:\n    case SpanType.WORKFLOW_SLEEP:\n    case SpanType.WORKFLOW_WAIT_EVENT:\n      return undefined;\n\n    default:\n      return span.entityName ?? span.entityId;\n  }\n}\n\n/**\n * Get an OTEL-compliant span name based on span type and attributes\n */\nexport function getSpanName(span: AnyExportedSpan, options?: GenAISemanticsOptions): string {\n  const identifier = getSpanIdentifier(span);\n\n  if (identifier) {\n    const operation = getOperationName(span, options?.modelCall);\n    return `${operation} ${identifier}`;\n  }\n\n  // For other types, use a simplified version of the original name\n  return sanitizeSpanName(span.name);\n}\n\n/**\n * Adds authored workflow entry identity (id, description, metadata) for\n * control-flow spans. Metadata is JSON-serialized to keep nested values and\n * falsy members (false, 0) intact; absent fields add no key.\n */\nfunction addEntryAttributes(\n  attributes: Attributes,\n  spanType: string,\n  attrs: { entryId?: string; entryDescription?: string; entryMetadata?: Record<string, unknown> },\n): void {\n  if (attrs.entryId !== undefined) {\n    attributes[`mastra.${spanType}.entry_id`] = attrs.entryId;\n  }\n  if (attrs.entryDescription !== undefined) {\n    attributes[`mastra.${spanType}.entry_description`] = attrs.entryDescription;\n  }\n  if (attrs.entryMetadata !== undefined) {\n    attributes[`mastra.${spanType}.entry_metadata`] = JSON.stringify(attrs.entryMetadata);\n  }\n}\n\n/**\n * Gets OpenTelemetry attributes from Mastra Span\n * Following OTEL Semantic Conventions for GenAI\n */\nexport function getAttributes(span: AnyExportedSpan, options?: GenAISemanticsOptions): Attributes {\n  const attributes: Attributes = {};\n  const spanType = span.type.toLowerCase();\n  const modelCall = options?.modelCall ?? isModelCallSpan(span.type);\n\n  // Add gen_ai.operation.name based on span type\n  attributes[ATTR_GEN_AI_OPERATION_NAME] = getOperationName(span, modelCall);\n\n  // Add span type for better visibility\n  attributes['mastra.span.type'] = span.type;\n\n  // Handle input/output based on span type\n  // Always add input/output for Laminar compatibility\n  if (span.input !== undefined) {\n    const inputStr = typeof span.input === 'string' ? span.input : JSON.stringify(span.input);\n    // Add specific attributes based on span type\n    if (modelCall) {\n      attributes[ATTR_GEN_AI_INPUT_MESSAGES] = convertMastraMessagesToGenAIMessages(inputStr);\n    } else if (\n      span.type === SpanType.TOOL_CALL ||\n      span.type === SpanType.MCP_TOOL_CALL ||\n      span.type === SpanType.PROVIDER_TOOL_CALL\n    ) {\n      attributes['gen_ai.tool.call.arguments'] = inputStr;\n    } else {\n      attributes[`mastra.${spanType}.input`] = inputStr;\n    }\n  }\n\n  if (span.output !== undefined) {\n    const outputStr = typeof span.output === 'string' ? span.output : JSON.stringify(span.output);\n    // Add specific attributes based on span type\n    if (modelCall) {\n      attributes[ATTR_GEN_AI_OUTPUT_MESSAGES] = convertMastraMessagesToGenAIMessages(outputStr);\n      // TODO\n      // attributes['gen_ai.output.type'] = image/json/speech/text/<other>\n    } else if (\n      span.type === SpanType.TOOL_CALL ||\n      span.type === SpanType.MCP_TOOL_CALL ||\n      span.type === SpanType.PROVIDER_TOOL_CALL\n    ) {\n      attributes['gen_ai.tool.call.result'] = outputStr;\n    } else {\n      attributes[`mastra.${spanType}.output`] = outputStr;\n    }\n  }\n\n  // Add model-specific attributes using OTEL semantic conventions\n  if (modelCall && span.attributes) {\n    const modelAttrs = span.attributes as ModelCallAttributes;\n\n    addModelRequestAttributes(attributes, modelAttrs);\n\n    // Agent context - allows correlating model generation with the agent that invoked it\n    if (span.entityId) {\n      attributes[ATTR_GEN_AI_AGENT_ID] = span.entityId;\n    }\n\n    if (span.entityName) {\n      attributes[ATTR_GEN_AI_AGENT_NAME] = span.entityName;\n    }\n\n    // Parameters using OTEL conventions\n    if (modelAttrs.parameters) {\n      if (modelAttrs.parameters.temperature !== undefined) {\n        attributes[ATTR_GEN_AI_REQUEST_TEMPERATURE] = modelAttrs.parameters.temperature;\n      }\n      if (modelAttrs.parameters.maxOutputTokens !== undefined) {\n        attributes[ATTR_GEN_AI_REQUEST_MAX_TOKENS] = modelAttrs.parameters.maxOutputTokens;\n      }\n      if (modelAttrs.parameters.topP !== undefined) {\n        attributes[ATTR_GEN_AI_REQUEST_TOP_P] = modelAttrs.parameters.topP;\n      }\n      if (modelAttrs.parameters.topK !== undefined) {\n        attributes[ATTR_GEN_AI_REQUEST_TOP_K] = modelAttrs.parameters.topK;\n      }\n      if (modelAttrs.parameters.presencePenalty !== undefined) {\n        attributes[ATTR_GEN_AI_REQUEST_PRESENCE_PENALTY] = modelAttrs.parameters.presencePenalty;\n      }\n      if (modelAttrs.parameters.frequencyPenalty !== undefined) {\n        attributes[ATTR_GEN_AI_REQUEST_FREQUENCY_PENALTY] = modelAttrs.parameters.frequencyPenalty;\n      }\n      if (modelAttrs.parameters.stopSequences) {\n        attributes[ATTR_GEN_AI_REQUEST_STOP_SEQUENCES] = JSON.stringify(modelAttrs.parameters.stopSequences);\n      }\n      if (modelAttrs.parameters.seed) {\n        attributes[ATTR_GEN_AI_REQUEST_SEED] = modelAttrs.parameters.seed;\n      }\n    }\n\n    // Completion start time (TTFT) - used by observability backends for time-to-first-token metrics\n    if (modelAttrs.completionStartTime) {\n      attributes['mastra.completion_start_time'] = modelAttrs.completionStartTime.toISOString();\n    }\n\n    // Response attributes\n    if (modelAttrs.finishReason) {\n      attributes[ATTR_GEN_AI_RESPONSE_FINISH_REASONS] = JSON.stringify([modelAttrs.finishReason]);\n    }\n    if (modelAttrs.responseModel) {\n      attributes[ATTR_GEN_AI_RESPONSE_MODEL] = modelAttrs.responseModel;\n    }\n    if (modelAttrs.responseId) {\n      attributes[ATTR_GEN_AI_RESPONSE_ID] = modelAttrs.responseId;\n    }\n\n    // Server attributes\n    if (modelAttrs.serverAddress) {\n      attributes[ATTR_SERVER_ADDRESS] = modelAttrs.serverAddress;\n    }\n    if (modelAttrs.serverPort !== undefined) {\n      attributes[ATTR_SERVER_PORT] = modelAttrs.serverPort;\n    }\n  }\n\n  if (span.type === SpanType.MODEL_STEP && span.attributes) {\n    const stepAttrs = span.attributes as ModelStepAttributes;\n    if (stepAttrs.stepIndex !== undefined) {\n      attributes[`mastra.${spanType}.step_index`] = stepAttrs.stepIndex;\n    }\n    if (stepAttrs.isContinued !== undefined) {\n      attributes[`mastra.${spanType}.is_continued`] = stepAttrs.isContinued;\n    }\n  }\n\n  if (span.type === SpanType.RAG_EMBEDDING && span.attributes) {\n    const embeddingAttrs = span.attributes as RagEmbeddingAttributes;\n\n    addModelRequestAttributes(attributes, embeddingAttrs);\n\n    if (embeddingAttrs.mode) {\n      attributes[`mastra.${spanType}.mode`] = embeddingAttrs.mode;\n    }\n    if (embeddingAttrs.dimensions !== undefined) {\n      attributes['gen_ai.embeddings.dimension.count'] = embeddingAttrs.dimensions;\n      attributes[`mastra.${spanType}.dimensions`] = embeddingAttrs.dimensions;\n    }\n    if (embeddingAttrs.inputCount !== undefined) {\n      attributes[`mastra.${spanType}.input_count`] = embeddingAttrs.inputCount;\n    }\n  }\n\n  // Add tool-specific attributes using OTEL conventions\n  if (\n    span.type === SpanType.TOOL_CALL ||\n    span.type === SpanType.MCP_TOOL_CALL ||\n    span.type === SpanType.PROVIDER_TOOL_CALL\n  ) {\n    // Tool identification (entityName/entityId are always set by producers)\n    attributes[ATTR_GEN_AI_TOOL_NAME] = span.entityName ?? span.entityId;\n\n    const toolCallId =\n      (span.attributes as { toolCallId?: string } | undefined)?.toolCallId ?? span.metadata?.toolCallId;\n    if (toolCallId) {\n      attributes['gen_ai.tool.call.id'] = toolCallId;\n    }\n\n    // Attribute-dependent fields (description, type, MCP server)\n    if (span.attributes) {\n      const toolAttrs = span.attributes as ToolCallAttributes;\n      if (toolAttrs.toolDescription) {\n        attributes[ATTR_GEN_AI_TOOL_DESCRIPTION] = toolAttrs.toolDescription;\n      }\n      if (toolAttrs.toolType) {\n        attributes['gen_ai.tool.type'] = toolAttrs.toolType;\n      }\n      if (span.type === SpanType.MCP_TOOL_CALL) {\n        const mcpAttrs = span.attributes as MCPToolCallAttributes;\n        if (mcpAttrs.mcpServer) {\n          attributes[ATTR_SERVER_ADDRESS] = mcpAttrs.mcpServer;\n          attributes[`mastra.${spanType}.server_name`] = mcpAttrs.mcpServer;\n        }\n        if (mcpAttrs.serverVersion) {\n          attributes[`mastra.${spanType}.server_version`] = mcpAttrs.serverVersion;\n        }\n      }\n    }\n  }\n\n  // Add agent-specific attributes\n  if (span.type === SpanType.AGENT_RUN && span.attributes) {\n    const agentAttrs = span.attributes as AgentRunAttributes;\n    if (span.entityId) {\n      attributes[ATTR_GEN_AI_AGENT_ID] = span.entityId;\n    }\n    if (span.entityName) {\n      attributes[ATTR_GEN_AI_AGENT_NAME] = span.entityName;\n    }\n    if (agentAttrs.conversationId) {\n      attributes[ATTR_GEN_AI_CONVERSATION_ID] = agentAttrs.conversationId;\n    }\n    if (agentAttrs.maxSteps) {\n      attributes[`mastra.${spanType}.max_steps`] = agentAttrs.maxSteps;\n    }\n    if (agentAttrs.availableTools) {\n      attributes[`gen_ai.tool.definitions`] = JSON.stringify(agentAttrs.availableTools);\n    }\n\n    //TODO:\n    // attributes[ATTR_GEN_AI_AGENT_DESCRIPTION] = agentAttrs.description;\n    // attributes[ATTR_GEN_AI_REQUEST_MODEL] = agentAttrs.model.name;\n\n    attributes[ATTR_GEN_AI_SYSTEM_INSTRUCTIONS] = agentAttrs.instructions;\n  }\n\n  // Add MCP server request attributes (OTel MCP semantic conventions where they exist)\n  if (span.type === SpanType.MCP_SERVER_REQUEST && span.attributes) {\n    const requestAttrs = span.attributes as MCPServerRequestAttributes;\n    attributes['mcp.method.name'] = requestAttrs.mcpMethod;\n    attributes[`mastra.${spanType}.server_name`] = requestAttrs.mcpServer;\n    if (requestAttrs.targetName) {\n      attributes[`mastra.${spanType}.target_name`] = requestAttrs.targetName;\n    }\n    if (requestAttrs.serverVersion) {\n      attributes[`mastra.${spanType}.server_version`] = requestAttrs.serverVersion;\n    }\n    if (requestAttrs.mcpProtocolVersion) {\n      attributes['mcp.protocol.version'] = requestAttrs.mcpProtocolVersion;\n    }\n    if (requestAttrs.clientName) {\n      attributes[`mastra.${spanType}.client_name`] = requestAttrs.clientName;\n    }\n    if (requestAttrs.clientVersion) {\n      attributes[`mastra.${spanType}.client_version`] = requestAttrs.clientVersion;\n    }\n  }\n\n  // Add workflow-specific attributes. Control-flow spans carry native branch,\n  // loop, sleep and wait metadata that is otherwise dropped on export. Values\n  // are emitted under the existing `mastra.<span_type>.<snake_case>` convention;\n  // arrays/dates are serialized and false/0 are preserved (guard on !== undefined).\n  if (span.type === SpanType.WORKFLOW_RUN && span.attributes) {\n    const runAttrs = span.attributes as WorkflowRunAttributes;\n    if (runAttrs.status !== undefined) {\n      attributes[`mastra.${spanType}.status`] = runAttrs.status;\n    }\n  }\n\n  if (span.type === SpanType.WORKFLOW_STEP) {\n    if (span.entityId) {\n      attributes[`mastra.${spanType}.step_id`] = span.entityId;\n    }\n    if (span.attributes) {\n      const stepAttrs = span.attributes as WorkflowStepAttributes;\n      if (stepAttrs.status !== undefined) {\n        attributes[`mastra.${spanType}.status`] = stepAttrs.status;\n      }\n      addEntryAttributes(attributes, spanType, stepAttrs);\n    }\n  }\n\n  if (span.type === SpanType.WORKFLOW_CONDITIONAL && span.attributes) {\n    const condAttrs = span.attributes as WorkflowConditionalAttributes;\n    if (condAttrs.conditionCount !== undefined) {\n      attributes[`mastra.${spanType}.condition_count`] = condAttrs.conditionCount;\n    }\n    if (condAttrs.truthyIndexes !== undefined) {\n      attributes[`mastra.${spanType}.truthy_indexes`] = JSON.stringify(condAttrs.truthyIndexes);\n    }\n    if (condAttrs.selectedSteps !== undefined) {\n      attributes[`mastra.${spanType}.selected_steps`] = JSON.stringify(condAttrs.selectedSteps);\n    }\n    addEntryAttributes(attributes, spanType, condAttrs);\n  }\n\n  if (span.type === SpanType.WORKFLOW_CONDITIONAL_EVAL && span.attributes) {\n    const evalAttrs = span.attributes as WorkflowConditionalEvalAttributes;\n    if (evalAttrs.conditionIndex !== undefined) {\n      attributes[`mastra.${spanType}.condition_index`] = evalAttrs.conditionIndex;\n    }\n    if (evalAttrs.result !== undefined) {\n      attributes[`mastra.${spanType}.result`] = evalAttrs.result;\n    }\n  }\n\n  if (span.type === SpanType.WORKFLOW_PARALLEL && span.attributes) {\n    const parallelAttrs = span.attributes as WorkflowParallelAttributes;\n    if (parallelAttrs.branchCount !== undefined) {\n      attributes[`mastra.${spanType}.branch_count`] = parallelAttrs.branchCount;\n    }\n    if (parallelAttrs.parallelSteps !== undefined) {\n      attributes[`mastra.${spanType}.parallel_steps`] = JSON.stringify(parallelAttrs.parallelSteps);\n    }\n    addEntryAttributes(attributes, spanType, parallelAttrs);\n  }\n\n  if (span.type === SpanType.WORKFLOW_LOOP && span.attributes) {\n    const loopAttrs = span.attributes as WorkflowLoopAttributes;\n    if (loopAttrs.loopType !== undefined) {\n      attributes[`mastra.${spanType}.loop_type`] = loopAttrs.loopType;\n    }\n    if (loopAttrs.iteration !== undefined) {\n      attributes[`mastra.${spanType}.iteration`] = loopAttrs.iteration;\n    }\n    if (loopAttrs.totalIterations !== undefined) {\n      attributes[`mastra.${spanType}.total_iterations`] = loopAttrs.totalIterations;\n    }\n    if (loopAttrs.concurrency !== undefined) {\n      attributes[`mastra.${spanType}.concurrency`] = loopAttrs.concurrency;\n    }\n    addEntryAttributes(attributes, spanType, loopAttrs);\n  }\n\n  if (span.type === SpanType.WORKFLOW_SLEEP && span.attributes) {\n    const sleepAttrs = span.attributes as WorkflowSleepAttributes;\n    if (sleepAttrs.durationMs !== undefined) {\n      attributes[`mastra.${spanType}.duration_ms`] = sleepAttrs.durationMs;\n    }\n    if (sleepAttrs.untilDate !== undefined) {\n      attributes[`mastra.${spanType}.until_date`] = sleepAttrs.untilDate.toISOString();\n    }\n    if (sleepAttrs.sleepType !== undefined) {\n      attributes[`mastra.${spanType}.sleep_type`] = sleepAttrs.sleepType;\n    }\n    addEntryAttributes(attributes, spanType, sleepAttrs);\n  }\n\n  if (span.type === SpanType.WORKFLOW_WAIT_EVENT && span.attributes) {\n    const waitAttrs = span.attributes as WorkflowWaitEventAttributes;\n    if (waitAttrs.eventName !== undefined) {\n      attributes[`mastra.${spanType}.event_name`] = waitAttrs.eventName;\n    }\n    if (waitAttrs.timeoutMs !== undefined) {\n      attributes[`mastra.${spanType}.timeout_ms`] = waitAttrs.timeoutMs;\n    }\n    if (waitAttrs.eventReceived !== undefined) {\n      attributes[`mastra.${spanType}.event_received`] = waitAttrs.eventReceived;\n    }\n    if (waitAttrs.waitDurationMs !== undefined) {\n      attributes[`mastra.${spanType}.wait_duration_ms`] = waitAttrs.waitDurationMs;\n    }\n  }\n\n  // Add error information if present\n  if (span.errorInfo) {\n    attributes[ATTR_ERROR_TYPE] = span.errorInfo.id || 'unknown';\n    attributes[ATTR_ERROR_MESSAGE] = span.errorInfo.message;\n    if (span.errorInfo.domain) {\n      attributes['error.domain'] = span.errorInfo.domain;\n    }\n    if (span.errorInfo.category) {\n      attributes['error.category'] = span.errorInfo.category;\n    }\n  }\n\n  const threadId = span.metadata?.threadId;\n  if (typeof threadId === 'string' && threadId.length > 0) {\n    attributes[ATTR_GEN_AI_CONVERSATION_ID] = threadId;\n  }\n\n  return attributes;\n}\n\n/**\n * Canonical OTel provider keys mapped to a list of possible fuzzy aliases.\n */\nconst PROVIDER_ALIASES: Record<string, string[]> = {\n  anthropic: ['anthropic', 'claude'],\n  'aws.bedrock': ['awsbedrock', 'bedrock', 'amazonbedrock'],\n  'azure.ai.inference': ['azureaiinference', 'azureinference'],\n  'azure.ai.openai': ['azureaiopenai', 'azureopenai', 'msopenai', 'microsoftopenai'],\n  cohere: ['cohere'],\n  deepseek: ['deepseek'],\n  'gcp.gemini': ['gcpgemini', 'gemini'],\n  'gcp.gen_ai': ['gcpgenai', 'googlegenai', 'googleai'],\n  'gcp.vertex_ai': ['gcpvertexai', 'vertexai'],\n  groq: ['groq'],\n  'ibm.watsonx.ai': ['ibmwatsonxai', 'watsonx', 'watsonxai'],\n  mistral_ai: ['mistral', 'mistralai'],\n  openai: ['openai', 'oai'],\n  perplexity: ['perplexity', 'pplx'],\n  x_ai: ['xai', 'x-ai', 'x_ai', 'x.com ai'],\n};\n\n/**\n * Normalize a provider input string into a matchable token.\n * Keep only alphanumerics and lowercase the result.\n */\nfunction normalizeProviderString(input: string): string {\n  return input.toLowerCase().replace(/[^a-z0-9]/g, '');\n}\n\n/**\n * Attempts to map a providerName to one of the canonical OTel provider names.\n * If no match is found, returns the original providerName unchanged.\n */\nfunction normalizeProvider(providerName: string): string {\n  const normalized = normalizeProviderString(providerName);\n\n  for (const [canonical, aliases] of Object.entries(PROVIDER_ALIASES)) {\n    for (const alias of aliases) {\n      if (normalized === alias) {\n        return canonical;\n      }\n    }\n  }\n\n  // No match → return the raw input in lowercase\n  return providerName.toLowerCase();\n}\n","/**\n * Convert Mastra Spans to OpenTelemetry spans\n */\nimport { readFileSync } from 'node:fs';\nimport { fileURLToPath } from 'node:url';\nimport { SpanType } from '@mastra/core/observability';\nimport type { AnyExportedSpan } from '@mastra/core/observability';\nimport { SpanKind, SpanStatusCode, TraceFlags } from '@opentelemetry/api';\nimport type { HrTime, Link, SpanContext, SpanStatus } from '@opentelemetry/api';\nimport type { InstrumentationScope } from '@opentelemetry/core';\nimport type { Resource } from '@opentelemetry/resources';\nimport { resourceFromAttributes } from '@opentelemetry/resources';\n\nimport type { ReadableSpan, TimedEvent } from '@opentelemetry/sdk-trace-base';\nimport {\n  ATTR_SERVICE_NAME,\n  ATTR_SERVICE_VERSION,\n  ATTR_TELEMETRY_SDK_LANGUAGE,\n  ATTR_TELEMETRY_SDK_NAME,\n  ATTR_TELEMETRY_SDK_VERSION,\n} from '@opentelemetry/semantic-conventions';\n\nimport { getAttributes, getSpanName, isModelCallSpan } from './gen-ai-semantics.js';\nimport type { OtelExporterConfig } from './types.js';\n\nexport type SpanFormat = 'GenAI_v1_38_0';\n\n// If more formats come later:\n// export type SpanFormat =\n//   | \"GenAI_v1_38_0\"\n//   | \"GenAI_v1_38_0\"\n//   | \"Custom_v2\";\n\nexport class SpanConverter {\n  private resource?: Resource;\n  private scope?: InstrumentationScope;\n  private initPromise?: Promise<void>;\n  private format: SpanFormat;\n\n  constructor(\n    private readonly params: {\n      format: SpanFormat;\n      packageName: string;\n      serviceName?: string;\n      config?: OtelExporterConfig;\n    },\n  ) {\n    this.format = params.format;\n  }\n\n  /**\n   * Lazily initialize resource & scope on first use.\n   * Subsequent calls reuse the same promise (no races).\n   */\n  private async initIfNeeded(): Promise<void> {\n    if (this.initPromise) {\n      return this.initPromise;\n    }\n\n    this.initPromise = (async () => {\n      const packageVersion = (await getPackageVersion(this.params.packageName)) ?? 'unknown';\n\n      const serviceVersion = (await getPackageVersion('@mastra/core')) ?? 'unknown';\n\n      let resource = resourceFromAttributes({\n        [ATTR_SERVICE_NAME]: this.params.serviceName || 'mastra-service',\n        [ATTR_SERVICE_VERSION]: serviceVersion,\n        [ATTR_TELEMETRY_SDK_NAME]: this.params.packageName,\n        [ATTR_TELEMETRY_SDK_VERSION]: packageVersion,\n        [ATTR_TELEMETRY_SDK_LANGUAGE]: 'nodejs',\n      });\n\n      if (this.params.config?.resourceAttributes) {\n        resource = resource.merge(\n          // Duplicate attributes from config will override defaults above\n          resourceFromAttributes(this.params.config.resourceAttributes),\n        );\n      }\n\n      this.resource = resource;\n      this.scope = {\n        name: this.params.packageName,\n        version: packageVersion,\n      };\n    })();\n\n    return this.initPromise;\n  }\n\n  /**\n   * Convert a Mastra Span to an OpenTelemetry ReadableSpan\n   */\n  async convertSpan(span: AnyExportedSpan): Promise<ReadableSpan> {\n    await this.initIfNeeded();\n\n    if (!this.resource || !this.scope) {\n      throw new Error('SpanConverter not initialized correctly');\n    }\n\n    // --- Core fields derived from Mastra span ---\n    const name = getSpanName(span);\n    const kind = getSpanKind(span.type);\n    const attributes = getAttributes(span);\n\n    // Add metadata as custom attributes (not gen_ai specific)\n    if (span.metadata) {\n      for (const [k, v] of Object.entries(span.metadata)) {\n        if (v === null || v === undefined) {\n          continue;\n        }\n        attributes[`mastra.metadata.${k}`] = typeof v === 'object' ? JSON.stringify(v) : v;\n      }\n    }\n\n    // Add tags for root spans (only root spans can have tags)\n    // Tags are JSON-stringified for maximum backend compatibility\n    // While OTEL spec supports arrays, many backends (Jaeger, Zipkin, Tempo) don't fully support them\n    if (span.isRootSpan && span.tags?.length) {\n      attributes['mastra.tags'] = JSON.stringify(span.tags);\n    }\n\n    const startTime = dateToHrTime(span.startTime);\n    const endTime = span.endTime ? dateToHrTime(span.endTime) : startTime;\n    const duration = computeDuration(span.startTime, span.endTime);\n\n    const { status, events } = buildStatusAndEvents(span, startTime);\n\n    const spanContext: SpanContext = {\n      traceId: span.traceId,\n      spanId: span.id,\n      traceFlags: TraceFlags.SAMPLED,\n      isRemote: false,\n    };\n\n    // External parents (ambient OTel spans Mastra did not create) are real\n    // spans in the OTel namespace this exporter targets, so keep them as the\n    // OTel-side parent when no Mastra parent exists.\n    const exportedParentSpanId = span.parentSpanId ?? span.externalParentSpanId;\n    const parentSpanContext = exportedParentSpanId\n      ? {\n          traceId: span.traceId,\n          spanId: exportedParentSpanId,\n          traceFlags: TraceFlags.SAMPLED,\n          isRemote: false,\n        }\n      : undefined;\n\n    // Spans in other traces, such as the caller of a served MCP request.\n    const links: Link[] = (span.links ?? []).map(link => ({\n      context: { traceId: link.traceId, spanId: link.spanId, traceFlags: TraceFlags.SAMPLED, isRemote: true },\n    }));\n\n    const readable: ReadableSpan = {\n      name,\n      kind,\n      spanContext: () => spanContext,\n      parentSpanContext,\n      startTime,\n      endTime,\n      status,\n      attributes,\n      links,\n      events,\n      duration,\n      ended: !!span.endTime,\n      resource: this.resource,\n      instrumentationScope: this.scope,\n      droppedAttributesCount: 0,\n      droppedEventsCount: 0,\n      droppedLinksCount: 0,\n    };\n\n    return readable;\n  }\n}\n\nasync function getPackageVersion(pkgName: string): Promise<string | undefined> {\n  try {\n    // Resolve `package.json` for the given package\n    const manifestUrl = new URL(await import.meta.resolve(`${pkgName}/package.json`));\n\n    const path = fileURLToPath(manifestUrl);\n    const pkgJson = JSON.parse(readFileSync(path, 'utf8'));\n    return pkgJson.version;\n  } catch {\n    return undefined;\n  }\n}\n\n/**\n * Get the appropriate Otel SpanKind based on Mastra SpanType.\n *\n * @param type - The Mastra span type\n * @returns The appropriate OTEL SpanKind\n */\nexport function getSpanKind(type: SpanType): SpanKind {\n  if (isModelCallSpan(type)) {\n    return SpanKind.CLIENT;\n  }\n  switch (type) {\n    case SpanType.RAG_EMBEDDING:\n    case SpanType.MCP_TOOL_CALL:\n      return SpanKind.CLIENT;\n    case SpanType.MCP_SERVER_REQUEST:\n      return SpanKind.SERVER;\n    default:\n      return SpanKind.INTERNAL;\n  }\n}\n\n/**\n * Convert JavaScript Date to hrtime format\n */\nfunction dateToHrTime(date: Date): HrTime {\n  const ms = date.getTime();\n  const seconds = Math.floor(ms / 1000);\n  const nanoseconds = (ms % 1000) * 1000000;\n  return [seconds, nanoseconds];\n}\n\nfunction computeDuration(start: Date, end?: Date): HrTime {\n  if (!end) return [0, 0];\n  const diffMs = end.getTime() - start.getTime();\n  return [Math.floor(diffMs / 1000), (diffMs % 1000) * 1_000_000];\n}\n\n/**\n * Build status + events from span.errorInfo (if present)\n */\nfunction buildStatusAndEvents(\n  span: AnyExportedSpan,\n  defaultTime: HrTime,\n): { status: SpanStatus; events: TimedEvent[] } {\n  const events: TimedEvent[] = [];\n\n  if (span.errorInfo) {\n    const status: SpanStatus = {\n      code: SpanStatusCode.ERROR,\n      message: span.errorInfo.message,\n    };\n\n    events.push({\n      name: 'exception',\n      attributes: {\n        'exception.message': span.errorInfo.message,\n        'exception.type': 'Error',\n        ...(span.errorInfo.details?.stack && {\n          'exception.stacktrace': span.errorInfo.details.stack as string,\n        }),\n      },\n      time: defaultTime,\n      droppedAttributesCount: 0,\n    });\n\n    return { status, events };\n  }\n\n  if (span.endTime) {\n    return {\n      status: { code: SpanStatusCode.OK },\n      events,\n    };\n  }\n\n  return {\n    status: { code: SpanStatusCode.UNSET },\n    events,\n  };\n}\n","/**\n * OpenTelemetry Exporter for Mastra\n *\n * Exports traces and logs to any OTLP-compatible endpoint.\n */\n\nimport type {\n  TracingEvent,\n  LogEvent,\n  InitExporterOptions,\n  ObservabilityInstanceConfig,\n} from '@mastra/core/observability';\nimport { TracingEventType } from '@mastra/core/observability';\nimport { BaseExporter } from '@mastra/observability';\nimport { context as apiContext, diag, DiagConsoleLogger, DiagLogLevel, trace, TraceFlags } from '@opentelemetry/api';\nimport type { Logger } from '@opentelemetry/api-logs';\n\nimport type { ExportResult } from '@opentelemetry/core';\nimport { ExportResultCode } from '@opentelemetry/core';\n\nimport { resourceFromAttributes } from '@opentelemetry/resources';\nimport { LoggerProvider, BatchLogRecordProcessor } from '@opentelemetry/sdk-logs';\nimport type { SpanExporter, ReadableSpan } from '@opentelemetry/sdk-trace-base';\nimport { BatchSpanProcessor } from '@opentelemetry/sdk-trace-base';\nimport { ATTR_SERVICE_NAME } from '@opentelemetry/semantic-conventions';\n\nimport { loadExporter, loadSignalExporter } from './loadExporter.js';\nimport { convertLog } from './log-converter.js';\nimport { resolveProviderConfig } from './provider-configs.js';\nimport type { ResolvedProviderConfig } from './provider-configs.js';\nimport { SpanConverter } from './span-converter.js';\nimport type { ExportProtocol, OtelExporterConfig } from './types.js';\n\n/**\n * Wrapper around a SpanExporter that logs export results when debug mode is enabled.\n * The OTel SDK intentionally does not log on success, making debugging difficult.\n * This wrapper adds visibility into each batch export's outcome.\n */\nclass DebugSpanExporterWrapper implements SpanExporter {\n  constructor(\n    private inner: SpanExporter,\n    private debugLog: (msg: string) => void,\n  ) {}\n\n  export(spans: ReadableSpan[], resultCallback: (result: ExportResult) => void): void {\n    const count = spans.length;\n    this.inner.export(spans, (result: ExportResult) => {\n      if (result.code === ExportResultCode.SUCCESS) {\n        this.debugLog(`[OtelExporter] Export completed: ${count} spans sent successfully`);\n      } else {\n        this.debugLog(`[OtelExporter] Export FAILED: ${count} spans, error: ${result.error?.message ?? 'unknown'}`);\n      }\n      resultCallback(result);\n    });\n  }\n\n  async shutdown(): Promise<void> {\n    return this.inner.shutdown();\n  }\n\n  async forceFlush(): Promise<void> {\n    return this.inner.forceFlush?.();\n  }\n}\n\n/**\n * Wrapper around a LogRecordExporter that logs export results when debug mode is enabled.\n * Same pattern as DebugSpanExporterWrapper but for log records.\n */\nclass DebugLogExporterWrapper {\n  constructor(\n    private inner: any,\n    private debugLog: (msg: string) => void,\n  ) {}\n\n  export(logs: any[], resultCallback: (result: ExportResult) => void): void {\n    const count = logs.length;\n    this.inner.export(logs, (result: ExportResult) => {\n      if (result.code === ExportResultCode.SUCCESS) {\n        this.debugLog(`[OtelExporter] Log export completed: ${count} logs sent successfully`);\n      } else {\n        this.debugLog(`[OtelExporter] Log export FAILED: ${count} logs, error: ${result.error?.message ?? 'unknown'}`);\n      }\n      resultCallback(result);\n    });\n  }\n\n  async shutdown(): Promise<void> {\n    return this.inner.shutdown();\n  }\n\n  async forceFlush(): Promise<void> {\n    return this.inner.forceFlush?.();\n  }\n}\n\nexport class OtelExporter extends BaseExporter {\n  private config: OtelExporterConfig;\n  private observabilityConfig?: ObservabilityInstanceConfig;\n\n  // Trace signal\n  private spanConverter?: SpanConverter;\n  private processor?: BatchSpanProcessor;\n  private exporter?: SpanExporter;\n\n  // Log signal\n  private loggerProvider?: LoggerProvider;\n  private otelLogger?: Logger;\n\n  // Provider config (resolved once, shared across signals)\n  private resolvedConfig?: ResolvedProviderConfig | null;\n  private providerName?: string;\n\n  // Single setup promise — all signals initialize together at init() time.\n  // Event handlers await this before processing. Never rejects.\n  private setupPromise?: Promise<void>;\n\n  name = 'opentelemetry';\n\n  constructor(config: OtelExporterConfig) {\n    super(config);\n\n    this.config = config;\n\n    // Set OTel SDK diagnostics to INFO level so we see warnings/errors from\n    // the SDK internals. We intentionally do NOT use DEBUG here because:\n    // 1. OTLPExportDelegate dumps enormous payloads at DEBUG level\n    // 2. diag.setLogger() is global and can be overwritten by other code\n    // Our DebugSpanExporterWrapper provides export-result logging instead.\n    if (config.logLevel === 'debug') {\n      diag.setLogger(new DiagConsoleLogger(), DiagLogLevel.INFO);\n    }\n  }\n\n  /**\n   * Initialize with observability configuration and eagerly set up the trace\n   * and log signal exporters in parallel.\n   *\n   * Called by Mastra during component registration. The async setup runs in the\n   * background — event handlers await the resulting promise before processing.\n   */\n  init(options: InitExporterOptions) {\n    this.observabilityConfig = options.config;\n    this.setupPromise = this.setupAllSignals();\n  }\n\n  // ===========================================================================\n  // Provider config resolution (shared across all signals)\n  // ===========================================================================\n\n  private get isDebug(): boolean {\n    return this.config.logLevel === 'debug';\n  }\n\n  /**\n   * Debug logging that bypasses the Mastra logger.\n   *\n   * The Mastra framework replaces our logger via __setLogger() with one at\n   * INFO level, which silently swallows all this.logger.debug() calls.\n   * For debug output we need to go through console.info directly.\n   */\n\n  private debugLog = (...args: unknown[]) => this.isDebug && console.info('[OtelExporter:debug]', ...args);\n\n  private resolveProvider(): ResolvedProviderConfig | null {\n    if (this.resolvedConfig !== undefined) {\n      return this.resolvedConfig;\n    }\n\n    if (!this.config.provider) {\n      this.setDisabled(\n        '[OtelExporter] Provider configuration is required. Use the \"custom\" provider for generic endpoints.',\n      );\n      this.resolvedConfig = null;\n      return null;\n    }\n\n    this.providerName = Object.keys(this.config.provider)[0];\n    const resolved = resolveProviderConfig(this.config.provider, this.isDebug);\n    if (!resolved) {\n      this.setDisabled('[OtelExporter] Provider configuration validation failed.');\n      this.resolvedConfig = null;\n      return null;\n    }\n\n    this.resolvedConfig = resolved;\n    return resolved;\n  }\n\n  /**\n   * Derive the endpoint for a specific signal from the resolved provider config.\n   * Strips trailing slashes and any existing signal-path suffix so we never\n   * produce a doubled \"//v1/logs\" or leave a stale \"/v1/traces\" on a logs URL.\n   */\n  private getSignalEndpoint(resolved: ResolvedProviderConfig, signal: 'traces' | 'logs'): string {\n    const signalPaths: Record<string, string> = {\n      traces: '/v1/traces',\n      logs: '/v1/logs',\n    };\n\n    // Drop trailing slashes first so the suffix check below also matches\n    // endpoints written like \".../v1/traces/\". Bounded loop instead of\n    // /\\/+$/ to avoid the polynomial-regex pattern CodeQL flags.\n    let base = resolved.endpoint;\n    while (base.endsWith('/')) {\n      base = base.slice(0, -1);\n    }\n\n    // Strip any existing signal-path suffix (with or without leading slash variations)\n    for (const path of Object.values(signalPaths)) {\n      if (base.endsWith(path)) {\n        base = base.slice(0, -path.length);\n        break;\n      }\n    }\n\n    return base + signalPaths[signal];\n  }\n\n  /**\n   * Build exporter constructor options for the given signal endpoint.\n   * For gRPC, converts headers to Metadata. For HTTP protocols, passes headers directly.\n   */\n  private async buildExporterOptions(\n    protocol: ExportProtocol,\n    url: string,\n    headers: Record<string, string>,\n  ): Promise<Record<string, unknown>> {\n    if (protocol === 'grpc') {\n      const grpcModule = await import('@grpc/grpc-js');\n      const metadata = new grpcModule.Metadata();\n      for (const [key, value] of Object.entries(headers)) {\n        metadata.set(key, value);\n      }\n      return { url, metadata, timeoutMillis: this.config.timeout };\n    }\n    return { url, headers, timeoutMillis: this.config.timeout };\n  }\n\n  // ===========================================================================\n  // Setup — eager, parallel initialization of all signals\n  // ===========================================================================\n\n  /**\n   * Wait for setup to complete. If init() was called, this awaits the\n   * already-in-flight setup promise. If init() was never called (standalone\n   * usage without Mastra), this triggers setup on first use.\n   */\n  private ensureSetup(): Promise<void> {\n    if (!this.setupPromise) {\n      this.setupPromise = this.setupAllSignals();\n    }\n    return this.setupPromise;\n  }\n\n  /**\n   * Resolve provider config once and set up all enabled signals in parallel.\n   * Each signal setup catches its own errors — this method never rejects.\n   */\n  private async setupAllSignals(): Promise<void> {\n    const resolved = this.resolveProvider();\n    if (!resolved) {\n      this.debugLog('Setup skipped: provider not resolved');\n      return;\n    }\n\n    const protocol = resolved.protocol;\n    const setupTasks: Promise<void>[] = [];\n\n    if (this.config.signals?.traces !== false) {\n      setupTasks.push(this.setupTraces(resolved, protocol));\n    } else {\n      this.debugLog('Trace export disabled via config');\n    }\n\n    if (this.config.signals?.logs !== false) {\n      setupTasks.push(this.setupLogs(resolved, protocol));\n    } else {\n      this.debugLog('Log export disabled via config');\n    }\n\n    await Promise.all(setupTasks);\n\n    this.debugLog(`Setup complete [traces=${!!this.processor}, logs=${!!this.otelLogger}]`);\n  }\n\n  // ---------------------------------------------------------------------------\n  // Trace setup\n  // ---------------------------------------------------------------------------\n\n  private async setupTraces(resolved: ResolvedProviderConfig, protocol: ExportProtocol): Promise<void> {\n    try {\n      // Create or use the provided SpanExporter\n      if (this.config.exporter) {\n        this.exporter = this.config.exporter;\n      } else {\n        const headers = resolved.headers;\n        // Zipkin doesn't follow OTLP signal-path conventions; pass its endpoint through unchanged.\n        const endpoint = protocol === 'zipkin' ? resolved.endpoint : this.getSignalEndpoint(resolved, 'traces');\n\n        this.debugLog(`Setting up trace exporter: protocol=${protocol}, endpoint=${endpoint}`);\n\n        const ExporterClass = await loadExporter(protocol, this.providerName);\n        if (!ExporterClass) {\n          this.debugLog(`Trace exporter not available for protocol: ${protocol}`);\n          return;\n        }\n\n        const exporterOptions =\n          protocol === 'zipkin'\n            ? { url: endpoint, headers }\n            : await this.buildExporterOptions(protocol, endpoint, headers);\n        this.exporter = new ExporterClass(exporterOptions);\n\n        this.debugLog(`Trace exporter created: ${this.exporter?.constructor?.name ?? 'unknown'} -> ${endpoint}`);\n      }\n\n      // Create processor\n      const serviceName = this.observabilityConfig?.serviceName || 'mastra-service';\n\n      this.spanConverter = new SpanConverter({\n        packageName: '@mastra/otel-exporter',\n        serviceName,\n        config: this.config,\n        format: 'GenAI_v1_38_0',\n      });\n\n      const exporterForProcessor = this.isDebug\n        ? new DebugSpanExporterWrapper(this.exporter!, msg => this.debugLog(msg))\n        : this.exporter!;\n\n      this.processor = new BatchSpanProcessor(exporterForProcessor, {\n        maxExportBatchSize: this.config.batchSize || 512,\n        maxQueueSize: 2048,\n        scheduledDelayMillis: 5000,\n        exportTimeoutMillis: this.config.timeout || 30000,\n      });\n\n      this.debugLog(\n        `Trace export initialized (service.name: \"${serviceName}\", batch size: ${this.config.batchSize || 512}, delay: 5s)`,\n      );\n    } catch (error) {\n      this.logger.warn('[OtelExporter] Failed to initialize trace export');\n      this.debugLog('Trace setup error:', error);\n    }\n  }\n\n  // ---------------------------------------------------------------------------\n  // Log setup\n  // ---------------------------------------------------------------------------\n\n  private async setupLogs(resolved: ResolvedProviderConfig, protocol: ExportProtocol): Promise<void> {\n    try {\n      const LogExporterClass = await loadSignalExporter('logs', protocol, this.providerName);\n      if (!LogExporterClass) {\n        this.debugLog(`Log exporter package not available for protocol \"${protocol}\". Log export disabled.`);\n        return;\n      }\n\n      const logEndpoint = this.getSignalEndpoint(resolved, 'logs');\n      const headers = resolved.headers;\n\n      this.debugLog(`Setting up log exporter: protocol=${protocol}, endpoint=${logEndpoint}`);\n\n      const logExporterOptions = await this.buildExporterOptions(protocol, logEndpoint, headers);\n      const logExporter = new LogExporterClass(logExporterOptions);\n\n      const exporterForProcessor = this.isDebug\n        ? new DebugLogExporterWrapper(logExporter, msg => this.debugLog(msg))\n        : logExporter;\n\n      const resource = resourceFromAttributes({\n        ...(this.config.resourceAttributes ?? {}),\n        [ATTR_SERVICE_NAME]: this.observabilityConfig?.serviceName || 'mastra-service',\n      });\n\n      this.loggerProvider = new LoggerProvider({\n        resource,\n        processors: [\n          new BatchLogRecordProcessor({\n            exporter: exporterForProcessor,\n            maxExportBatchSize: this.config.batchSize || 512,\n            maxQueueSize: 2048,\n            scheduledDelayMillis: 5000,\n            exportTimeoutMillis: this.config.timeout || 30000,\n          }),\n        ],\n      });\n\n      this.otelLogger = this.loggerProvider.getLogger('@mastra/otel-exporter');\n\n      this.debugLog(`Log export initialized (endpoint: ${logEndpoint})`);\n    } catch (error) {\n      this.logger.warn('[OtelExporter] Failed to initialize log export');\n      this.debugLog('Log setup error:', error);\n    }\n  }\n\n  // ===========================================================================\n  // Trace event handler\n  // ===========================================================================\n\n  protected async _exportTracingEvent(event: TracingEvent): Promise<void> {\n    if (this.config.signals?.traces === false) return;\n    if (event.type !== TracingEventType.SPAN_ENDED) return;\n\n    await this.ensureSetup();\n\n    if (this.isDisabled || !this.processor) return;\n\n    const span = event.exportedSpan;\n\n    try {\n      const otelSpan = await this.spanConverter!.convertSpan(span);\n      this.processor.onEnd(otelSpan);\n\n      this.debugLog(\n        `Queued span ${span.id} (trace: ${span.traceId}, parent: ${span.parentSpanId || 'none'}, type: ${span.type})`,\n      );\n    } catch (error) {\n      this.logger.error(`[OtelExporter] Failed to export span ${span.id}:`, error);\n    }\n  }\n\n  // ===========================================================================\n  // Log event handler\n  // ===========================================================================\n\n  async onLogEvent(event: LogEvent): Promise<void> {\n    this.debugLog(`onLogEvent received (level: ${event.log.level}, message: \"${event.log.message}\")`);\n\n    await this.ensureSetup();\n\n    if (this.isDisabled) {\n      this.debugLog('Log event skipped: exporter is disabled');\n      return;\n    }\n\n    if (!this.otelLogger) {\n      this.debugLog('Log event skipped: log exporter not available');\n      return;\n    }\n\n    try {\n      const logParams = convertLog(event.log);\n\n      // Mirror trace context into the OTEL log Context so backends (Grafana, Datadog,\n      // Honeycomb, etc.) correlate logs with traces using the standard OTLP fields.\n      // Also keep mastra.traceId / mastra.spanId attributes for backends that key\n      // off attributes only.\n      const attributes = { ...logParams.attributes };\n      let logContext = apiContext.active();\n      if (logParams.traceId && logParams.spanId) {\n        attributes['mastra.traceId'] = logParams.traceId;\n        attributes['mastra.spanId'] = logParams.spanId;\n        logContext = trace.setSpanContext(logContext, {\n          traceId: logParams.traceId,\n          spanId: logParams.spanId,\n          traceFlags: TraceFlags.SAMPLED,\n          isRemote: false,\n        });\n      }\n\n      this.otelLogger.emit({\n        timestamp: logParams.timestamp,\n        severityNumber: logParams.severityNumber,\n        severityText: logParams.severityText,\n        body: logParams.body,\n        attributes,\n        context: logContext,\n      });\n\n      this.debugLog(`Exported log (level: ${event.log.level}, trace: ${event.log.traceId || 'none'})`);\n    } catch (error) {\n      this.logger.error('[OtelExporter] Failed to export log:', error);\n    }\n  }\n\n  // ===========================================================================\n  // Lifecycle\n  // ===========================================================================\n\n  /**\n   * Force flush any buffered data without shutting down the exporter.\n   * Delegates to all active processors/providers.\n   */\n  async flush(): Promise<void> {\n    // Wait for setup so we don't miss providers that are still being initialized.\n    if (this.setupPromise) {\n      await this.setupPromise;\n    }\n\n    const flushPromises: Promise<void>[] = [];\n    const signals: string[] = [];\n\n    if (this.processor) {\n      flushPromises.push(this.flushTraces());\n      signals.push('traces');\n    }\n    if (this.loggerProvider) {\n      flushPromises.push(this.loggerProvider.forceFlush());\n      signals.push('logs');\n    }\n\n    if (flushPromises.length > 0) {\n      this.debugLog(`Flushing signals: ${signals.join(', ')}...`);\n      await Promise.all(flushPromises);\n      this.debugLog('Flushed all pending data');\n    } else {\n      this.debugLog('Flush called but no active exporters');\n    }\n  }\n\n  /**\n   * The BatchSpanProcessor removes a batch from its queue before the export\n   * completes and its forceFlush() only exports what is still queued, so a\n   * timer- or size-triggered batch can still be in flight when it resolves.\n   * OTLP exporters wait for in-flight sends in forceFlush(); call it even when\n   * the processor flush rejects, so a failed batch doesn't skip the wait.\n   */\n  private async flushTraces(): Promise<void> {\n    try {\n      await this.processor!.forceFlush();\n    } finally {\n      await this.exporter?.forceFlush?.();\n    }\n  }\n\n  async shutdown(): Promise<void> {\n    // Wait for setup so we don't shut down before providers finish initializing.\n    if (this.setupPromise) {\n      await this.setupPromise;\n    }\n\n    const shutdownPromises: Promise<void>[] = [];\n\n    if (this.processor) {\n      shutdownPromises.push(this.processor.shutdown());\n    }\n    if (this.loggerProvider) {\n      shutdownPromises.push(this.loggerProvider.shutdown());\n    }\n\n    if (shutdownPromises.length > 0) {\n      await Promise.all(shutdownPromises);\n    }\n  }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BA,MAAM,iBAAiF;CACrF,QAAQ;EACN,aAAa;GAAE,KAAK;GAA2C,YAAY;EAAoB;EAC/F,iBAAiB;GAAE,KAAK;GAA4C,YAAY;EAAoB;EACpG,MAAM;GACJ,KAAK;GACL,YAAY;GACZ,QAAQ,CAAC,eAAe;EAC1B;EACA,QAAQ;GAAE,KAAK;GAAkC,YAAY;EAAiB;CAChF;CACA,MAAM;EACJ,aAAa;GAAE,KAAK;GAA0C,YAAY;EAAkB;EAC5F,iBAAiB;GAAE,KAAK;GAA2C,YAAY;EAAkB;EACjG,MAAM;GACJ,KAAK;GACL,YAAY;GACZ,QAAQ,CAAC,eAAe;EAC1B;CAEF;AACF;;AAOA,MAAM,wBAAQ,IAAI,IAAiB;;;;;AAMnC,eAAsB,aAAa,UAA0B,UAAiC;CAC5F,OAAO,mBAAmB,UAAU,UAAU,QAAQ;AACxD;;;;;AAMA,eAAsB,mBACpB,QACA,UACA,UACc;CACd,MAAM,OAAO,eAAe,OAAO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