@sentry/server-utils 11.16.0 → 11.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (172) hide show
  1. package/build/cjs/chunks/config.js +62 -2
  2. package/build/cjs/chunks/config.js.map +1 -1
  3. package/build/cjs/chunks/exports.js +231 -66
  4. package/build/cjs/chunks/exports.js.map +1 -1
  5. package/build/cjs/chunks/moduleInjectedTransform.js +8 -0
  6. package/build/cjs/chunks/moduleInjectedTransform.js.map +1 -1
  7. package/build/cjs/index.js +447 -199
  8. package/build/cjs/index.js.map +1 -1
  9. package/build/cjs/index.no-diagnostic-channels.js +1 -0
  10. package/build/cjs/index.request-handler.js +48 -3
  11. package/build/cjs/index.request-handler.js.map +1 -1
  12. package/build/esm/ai/langchain/embeddings.js +23 -8
  13. package/build/esm/ai/langchain/embeddings.js.map +1 -1
  14. package/build/esm/ai/langchain/index.js +41 -30
  15. package/build/esm/ai/langchain/index.js.map +1 -1
  16. package/build/esm/ai/langchain/utils.js +1 -5
  17. package/build/esm/ai/langchain/utils.js.map +1 -1
  18. package/build/esm/ai/langgraph/agent-span.js +6 -2
  19. package/build/esm/ai/langgraph/agent-span.js.map +1 -1
  20. package/build/esm/ai/langgraph/index.js +5 -1
  21. package/build/esm/ai/langgraph/index.js.map +1 -1
  22. package/build/esm/ai/langgraph/stream.js +4 -1
  23. package/build/esm/ai/langgraph/stream.js.map +1 -1
  24. package/build/esm/ai/mistral/streaming.js.map +1 -1
  25. package/build/esm/ai/pi-durable/index.js +10 -13
  26. package/build/esm/ai/pi-durable/index.js.map +1 -1
  27. package/build/esm/ai/pi-durable/runs.js +6 -5
  28. package/build/esm/ai/pi-durable/runs.js.map +1 -1
  29. package/build/esm/ai/pi-durable/tools.js +21 -17
  30. package/build/esm/ai/pi-durable/tools.js.map +1 -1
  31. package/build/esm/exports.js +2 -1
  32. package/build/esm/index.js +5 -2
  33. package/build/esm/index.js.map +1 -1
  34. package/build/esm/index.no-diagnostic-channels.js +2 -1
  35. package/build/esm/index.request-handler.js +3 -1
  36. package/build/esm/integrations/amqplib.js.map +1 -1
  37. package/build/esm/integrations/anthropic.js.map +1 -1
  38. package/build/esm/integrations/bullmq/tracer.js.map +1 -1
  39. package/build/esm/integrations/clickhouse-sql.js +31 -0
  40. package/build/esm/integrations/clickhouse-sql.js.map +1 -0
  41. package/build/esm/integrations/clickhouse.js +88 -0
  42. package/build/esm/integrations/clickhouse.js.map +1 -0
  43. package/build/esm/integrations/express/instrumentation.js +1 -0
  44. package/build/esm/integrations/express/instrumentation.js.map +1 -1
  45. package/build/esm/integrations/fastify/instrumentation.js +3 -1
  46. package/build/esm/integrations/fastify/instrumentation.js.map +1 -1
  47. package/build/esm/integrations/graphql/utils.js.map +1 -1
  48. package/build/esm/integrations/hapi/hapi-utils.js +6 -9
  49. package/build/esm/integrations/hapi/hapi-utils.js.map +1 -1
  50. package/build/esm/integrations/hapi/index.js +15 -1
  51. package/build/esm/integrations/hapi/index.js.map +1 -1
  52. package/build/esm/integrations/hono/isMiddleware.js.map +1 -1
  53. package/build/esm/integrations/hono/middlewareHandlers.js +3 -1
  54. package/build/esm/integrations/hono/middlewareHandlers.js.map +1 -1
  55. package/build/esm/integrations/hono/patchRoute.js +2 -1
  56. package/build/esm/integrations/hono/patchRoute.js.map +1 -1
  57. package/build/esm/integrations/hono/unwrapThrownValue.js +20 -0
  58. package/build/esm/integrations/hono/unwrapThrownValue.js.map +1 -0
  59. package/build/esm/integrations/index.js +2 -0
  60. package/build/esm/integrations/index.js.map +1 -1
  61. package/build/esm/integrations/langchain.js +10 -3
  62. package/build/esm/integrations/langchain.js.map +1 -1
  63. package/build/esm/integrations/mongodb/mongodb-span.js +7 -9
  64. package/build/esm/integrations/mongodb/mongodb-span.js.map +1 -1
  65. package/build/esm/integrations/pino.js +2 -2
  66. package/build/esm/integrations/pino.js.map +1 -1
  67. package/build/esm/integrations/prisma/tracing-helper.js.map +1 -1
  68. package/build/esm/integrations/serveTunnel.js +2 -2
  69. package/build/esm/integrations/serveTunnel.js.map +1 -1
  70. package/build/esm/integrations/vercel-ai/extract.js +88 -0
  71. package/build/esm/integrations/vercel-ai/extract.js.map +1 -0
  72. package/build/esm/integrations/vercel-ai/util.js +5 -1
  73. package/build/esm/integrations/vercel-ai/util.js.map +1 -1
  74. package/build/esm/integrations/vercel-ai/vercel-ai-dc-subscriber.js +19 -9
  75. package/build/esm/integrations/vercel-ai/vercel-ai-dc-subscriber.js.map +1 -1
  76. package/build/esm/integrations/winston.js +2 -2
  77. package/build/esm/integrations/winston.js.map +1 -1
  78. package/build/esm/orchestrion/channels.js +2 -0
  79. package/build/esm/orchestrion/channels.js.map +1 -1
  80. package/build/esm/orchestrion/config/channel-integration-definitions.js +8 -0
  81. package/build/esm/orchestrion/config/channel-integration-definitions.js.map +1 -1
  82. package/build/esm/orchestrion/config/clickhouse.js +51 -0
  83. package/build/esm/orchestrion/config/clickhouse.js.map +1 -0
  84. package/build/esm/orchestrion/config/hono.js +2 -2
  85. package/build/esm/orchestrion/config/hono.js.map +1 -1
  86. package/build/esm/orchestrion/config/index.js +2 -0
  87. package/build/esm/orchestrion/config/index.js.map +1 -1
  88. package/build/esm/package.json +1 -1
  89. package/build/esm/utils/installedModules.js +87 -0
  90. package/build/esm/utils/installedModules.js.map +1 -0
  91. package/build/esm/utils/module.js +29 -0
  92. package/build/esm/utils/module.js.map +1 -0
  93. package/build/esm/utils/serverTimingTraceHeader.js +49 -0
  94. package/build/esm/utils/serverTimingTraceHeader.js.map +1 -0
  95. package/build/esm/utils/sql.js +41 -19
  96. package/build/esm/utils/sql.js.map +1 -1
  97. package/build/esm/utils/tunnelServer.js +3 -3
  98. package/build/esm/utils/tunnelServer.js.map +1 -1
  99. package/build/esm/utils/wrapServerRequestHandler.js +5 -4
  100. package/build/esm/utils/wrapServerRequestHandler.js.map +1 -1
  101. package/build/types/ai/langchain/embeddings.d.ts +2 -2
  102. package/build/types/ai/langchain/embeddings.d.ts.map +1 -1
  103. package/build/types/ai/langchain/index.d.ts.map +1 -1
  104. package/build/types/ai/langchain/types.d.ts +8 -4
  105. package/build/types/ai/langchain/types.d.ts.map +1 -1
  106. package/build/types/ai/langchain/utils.d.ts.map +1 -1
  107. package/build/types/ai/langgraph/agent-span.d.ts +5 -2
  108. package/build/types/ai/langgraph/agent-span.d.ts.map +1 -1
  109. package/build/types/ai/langgraph/index.d.ts.map +1 -1
  110. package/build/types/ai/langgraph/stream.d.ts.map +1 -1
  111. package/build/types/ai/langgraph/types.d.ts +10 -2
  112. package/build/types/ai/langgraph/types.d.ts.map +1 -1
  113. package/build/types/ai/mistral/streaming.d.ts.map +1 -1
  114. package/build/types/ai/pi-durable/index.d.ts.map +1 -1
  115. package/build/types/ai/pi-durable/runs.d.ts +4 -2
  116. package/build/types/ai/pi-durable/runs.d.ts.map +1 -1
  117. package/build/types/ai/pi-durable/tools.d.ts +4 -6
  118. package/build/types/ai/pi-durable/tools.d.ts.map +1 -1
  119. package/build/types/ai/pi-durable/types.d.ts +10 -1
  120. package/build/types/ai/pi-durable/types.d.ts.map +1 -1
  121. package/build/types/exports.d.ts +1 -0
  122. package/build/types/exports.d.ts.map +1 -1
  123. package/build/types/index.d.ts +5 -3
  124. package/build/types/index.d.ts.map +1 -1
  125. package/build/types/index.request-handler.d.ts +1 -0
  126. package/build/types/index.request-handler.d.ts.map +1 -1
  127. package/build/types/integrations/amqplib.d.ts.map +1 -1
  128. package/build/types/integrations/anthropic.d.ts.map +1 -1
  129. package/build/types/integrations/bullmq/tracer.d.ts.map +1 -1
  130. package/build/types/integrations/clickhouse-sql.d.ts +8 -0
  131. package/build/types/integrations/clickhouse-sql.d.ts.map +1 -0
  132. package/build/types/integrations/clickhouse.d.ts +11 -0
  133. package/build/types/integrations/clickhouse.d.ts.map +1 -0
  134. package/build/types/integrations/express/types.d.ts +1 -0
  135. package/build/types/integrations/express/types.d.ts.map +1 -1
  136. package/build/types/integrations/fastify/instrumentation.d.ts.map +1 -1
  137. package/build/types/integrations/hapi/hapi-utils.d.ts.map +1 -1
  138. package/build/types/integrations/hapi/index.d.ts +12 -0
  139. package/build/types/integrations/hapi/index.d.ts.map +1 -1
  140. package/build/types/integrations/hono/isMiddleware.d.ts.map +1 -1
  141. package/build/types/integrations/hono/middlewareHandlers.d.ts.map +1 -1
  142. package/build/types/integrations/hono/patchRoute.d.ts.map +1 -1
  143. package/build/types/integrations/hono/unwrapThrownValue.d.ts +10 -0
  144. package/build/types/integrations/hono/unwrapThrownValue.d.ts.map +1 -0
  145. package/build/types/integrations/index.d.ts.map +1 -1
  146. package/build/types/integrations/langchain.d.ts.map +1 -1
  147. package/build/types/integrations/mongodb/mongodb-span.d.ts.map +1 -1
  148. package/build/types/integrations/prisma/tracing-helper.d.ts.map +1 -1
  149. package/build/types/integrations/vercel-ai/extract.d.ts +27 -0
  150. package/build/types/integrations/vercel-ai/extract.d.ts.map +1 -0
  151. package/build/types/integrations/vercel-ai/util.d.ts +2 -0
  152. package/build/types/integrations/vercel-ai/util.d.ts.map +1 -1
  153. package/build/types/integrations/vercel-ai/vercel-ai-dc-subscriber.d.ts +1 -1
  154. package/build/types/integrations/vercel-ai/vercel-ai-dc-subscriber.d.ts.map +1 -1
  155. package/build/types/orchestrion/channels.d.ts +12 -0
  156. package/build/types/orchestrion/channels.d.ts.map +1 -1
  157. package/build/types/orchestrion/config/channel-integration-definitions.d.ts +3 -0
  158. package/build/types/orchestrion/config/channel-integration-definitions.d.ts.map +1 -1
  159. package/build/types/orchestrion/config/clickhouse.d.ts +18 -0
  160. package/build/types/orchestrion/config/clickhouse.d.ts.map +1 -0
  161. package/build/types/orchestrion/config/index.d.ts.map +1 -1
  162. package/build/types/utils/installedModules.d.ts +17 -0
  163. package/build/types/utils/installedModules.d.ts.map +1 -0
  164. package/build/types/utils/module.d.ts +3 -0
  165. package/build/types/utils/module.d.ts.map +1 -0
  166. package/build/types/utils/serverTimingTraceHeader.d.ts +18 -0
  167. package/build/types/utils/serverTimingTraceHeader.d.ts.map +1 -0
  168. package/build/types/utils/sql.d.ts +28 -3
  169. package/build/types/utils/sql.d.ts.map +1 -1
  170. package/build/types/utils/tunnelServer.d.ts.map +1 -1
  171. package/build/types/utils/wrapServerRequestHandler.d.ts.map +1 -1
  172. package/package.json +4 -4
@@ -1 +1 @@
1
- {"version":3,"file":"vercel-ai-dc-subscriber.js","names":[],"sources":["../../../../src/integrations/vercel-ai/vercel-ai-dc-subscriber.ts"],"sourcesContent":["/* eslint-disable max-lines */\nimport {\n GEN_AI_CONVERSATION_ID,\n GEN_AI_COST_TOTAL_TOKENS,\n GEN_AI_EMBEDDINGS_INPUT,\n GEN_AI_FUNCTION_ID,\n GEN_AI_INPUT_MESSAGES,\n GEN_AI_OPERATION_NAME,\n GEN_AI_OUTPUT_MESSAGES,\n GEN_AI_PROVIDER_NAME,\n GEN_AI_REQUEST_MODEL,\n GEN_AI_RESPONSE_FINISH_REASONS,\n GEN_AI_RESPONSE_ID,\n GEN_AI_RESPONSE_MODEL,\n GEN_AI_RESPONSE_STREAMING,\n GEN_AI_SYSTEM_INSTRUCTIONS,\n GEN_AI_TOOL_CALL_ARGUMENTS,\n GEN_AI_TOOL_CALL_RESULT,\n GEN_AI_TOOL_DEFINITIONS,\n GEN_AI_TOOL_DESCRIPTION,\n GEN_AI_TOOL_NAME,\n GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS,\n GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS,\n GEN_AI_USAGE_INPUT_TOKENS,\n GEN_AI_USAGE_OUTPUT_TOKENS,\n GEN_AI_USAGE_REASONING_OUTPUT_TOKENS,\n GEN_AI_USAGE_TOTAL_TOKENS,\n SENTRY_OP,\n SENTRY_ORIGIN,\n VERCEL_AI_SETTINGS_CONTEXT_KEY_BASE,\n VERCEL_AI_TOOL_CALL_CONTEXT_KEY_BASE,\n} from '@sentry/conventions/attributes';\nimport {\n GEN_AI_DECIDE,\n GEN_AI_EMBEDDINGS,\n GEN_AI_EXECUTE_TOOL,\n GEN_AI_GENERATE_CONTENT,\n GEN_AI_INVOKE_AGENT,\n GEN_AI_RERANK,\n} from '@sentry/conventions/op';\nimport type { Span, SpanAttributes } from '@sentry/core';\nimport {\n _INTERNAL_skipAiProviderWrapping,\n captureException,\n getActiveSpan,\n getClient,\n isObjectLike,\n isPlainObject,\n SPAN_STATUS_ERROR,\n spanToJSON,\n spanToTraceContext,\n startInactiveSpan,\n stringify,\n withScope,\n} from '@sentry/core';\nimport type { TracingChannel } from 'node:diagnostics_channel';\nimport { GEN_AI_TOOL_CALL_ID_ATTRIBUTE } from '../../ai/core/gen-ai-attributes';\nimport {\n type GenAiSpanHooks,\n type GenAiSpanResult,\n runGenAiSpanEnd,\n runGenAiSpanStart,\n} from '../../ai/core/span-hooks';\nimport { isEveGenAiRecordingDefault } from './gen-ai-recording-mode';\nimport {\n type GenAiCallOptions,\n type GenAiOptions,\n getEvaluationOutputMessages,\n resolveRecordingOption,\n} from '../../ai/core/utils';\nimport { getProviderMetadataAttributes, LAST_STEP_ONLY_USAGE_KEYS } from '../../ai/vercel-ai';\nimport { WORKERS_AI_INTEGRATION_NAME } from '../../ai/workers-ai/constants';\nimport { bindTracingChannelToSpan } from '../../tracing-channel';\nimport { asNumber, asString, isReadableStream, type StreamedModelCallResult, sum, tapModelCallStream } from './util';\n\n/**\n * The single tracing channel the `ai` package (>= 7) publishes all telemetry lifecycle events to\n * via `node:diagnostics_channel`. Events are discriminated by their `type` field.\n * @see https://github.com/vercel/ai/pull/15660\n */\nexport const AI_SDK_TELEMETRY_TRACING_CHANNEL = 'ai:telemetry';\n\nconst ORIGIN = 'auto.ai.vercelai';\n\n// `gen_ai.operation.name` values, keyed to the span op they map to.\nconst GEN_AI_OPERATION_SPAN_OPS = {\n embeddings: GEN_AI_EMBEDDINGS,\n // `GEN_AI_RERANK` is deprecated because the product doesn't support rerank spans, but we keep\n // emitting it so existing rerank spans keep their op.\n // oxlint-disable-next-line typescript/no-deprecated\n rerank: GEN_AI_RERANK,\n decide: GEN_AI_DECIDE,\n invoke_agent: GEN_AI_INVOKE_AGENT,\n execute_tool: GEN_AI_EXECUTE_TOOL,\n // The model-call op matches the Vercel AI OTel integration (`gen_ai.generate_content`) rather than\n // the generic `gen_ai.chat`, so v6 (OTel) and v7 (channel) produce the same spans.\n generate_content: GEN_AI_GENERATE_CONTENT,\n} as const;\n\ntype GenAiOperation = keyof typeof GEN_AI_OPERATION_SPAN_OPS;\n\n// Subset of the `vercel.ai.*` passthrough attributes the OTel integration emits that we reproduce.\nconst VERCEL_AI_OPERATION_ID_ATTRIBUTE = 'vercel.ai.operationId';\nconst VERCEL_AI_MODEL_PROVIDER_ATTRIBUTE = 'vercel.ai.model.provider';\nconst VERCEL_AI_SETTINGS_MAX_RETRIES_ATTRIBUTE = 'vercel.ai.settings.maxRetries';\nconst VERCEL_AI_TELEMETRY_METADATA_ATTRIBUTE_PREFIX = 'vercel.ai.telemetry.metadata.';\n\n// Tracks the top-level operationId (and whether it streams) per `callId` so a model-call span can\n// name its `doGenerate`/`doStream` operation the same way the OTel integration does. `isStream` is\n// the authoritative event-type signal rather than a substring check on the (possibly custom)\n// operationId. Cleared when the top-level span ends.\nconst operationIdByCallId = new Map<string, { operationId: string; isStream: boolean }>();\n\n// Per-operation map of tool name → description, harvested from a model-call /\n// top-level event's `tools` (keyed by the shared `callId`). The AI SDK's\n// `executeTool` event doesn't carry the tool's description, so we backfill it\n// onto the tool span here — without relying on the OTel `vercelAiEventProcessor`\n// (which isn't registered in channel/orchestrion mode). Cleared with the\n// operation. Only populated when inputs are recorded, matching the OTel path\n// (which sources descriptions from the recorded `tool.definitions`).\nconst toolDescriptionsByCallId = new Map<string, Map<string, string>>();\n\n// A streamed `streamText` operation's own channel result is always `undefined` (the SDK exposes the\n// stream only on the model call), so its `invoke_agent` span can't be enriched from the channel. We\n// key the span by `callId` and enrich it as each streamed model call drains — the model calls flush\n// before the operation's own span ends. The running token sum lives on the span's own attributes.\nconst invokeAgentSpanByCallId = new Map<string, Span>();\n\n// Only an operation's start event carries `runtimeContext`; its model-call and tool events copy the\n// resulting attributes from here. Cleared with the operation.\nconst runtimeContextAttributesByCallId = new Map<string, SpanAttributes>();\n\n// Only top-level operations own the `callId` → operationId mapping; `step`/`languageModelCall`/\n// `executeTool` share the parent's `callId`, so they must not clear it.\nconst ROOT_OPERATION_TYPES = new Set<ChannelEventType>([\n 'generateText',\n 'streamText',\n 'streamObject',\n 'generateObject',\n 'embed',\n 'embedMany',\n 'rerank',\n]);\n\n// Operations whose `providerMetadata` cost covers only one of their provider calls: the last step of a\n// text or object operation, whose cost the `generate_content` spans carry, or one `embedMany` chunk.\nconst PARTIAL_COST_OPERATION_TYPES = new Set<ChannelEventType>([\n 'generateText',\n 'streamText',\n 'streamObject',\n 'generateObject',\n 'embedMany',\n]);\n\n/** Drop the per-operation `callId` maps once the owning top-level operation settles (success or error). */\nexport function clearOperationId(data: VercelAiChannelMessage): void {\n if (!ROOT_OPERATION_TYPES.has(data.type)) {\n return;\n }\n const callId = asString(data.event.callId);\n if (callId) {\n clearOperationCallId(callId);\n }\n}\n\n/**\n * Drop the per-operation `callId` maps for a single id. The v6 orchestrion adapter uses this to clear a\n * `streamText`/`streamObject` operation only after its lazily-run model call settles — the operation's own\n * span ends synchronously (when the call returns) but the model call runs later as the stream is consumed,\n * and it still needs the operation's `operationId`/`isStream` entry to name itself `ai.streamText.doStream`\n * (or `ai.streamObject.doStream`).\n */\nexport function clearOperationCallId(callId: string): void {\n operationIdByCallId.delete(callId);\n toolDescriptionsByCallId.delete(callId);\n invokeAgentSpanByCallId.delete(callId);\n runtimeContextAttributesByCallId.delete(callId);\n}\n\n/**\n * The OpenAI Conversations API id from `providerOptions.openai.conversation` (or `azure`): the one\n * provider-level value that is the same on every turn. A `Sentry.setConversationId()` value still wins,\n * since `conversationIdIntegration` writes it on `spanStart`, after these start attributes.\n */\nfunction getOpenAiConversationId(providerOptions: unknown): string | undefined {\n if (!isObjectLike(providerOptions)) {\n return undefined;\n }\n for (const key of ['openai', 'azure']) {\n const options = providerOptions[key];\n const conversation = isObjectLike(options) ? asString(options.conversation) : undefined;\n if (conversation) {\n return conversation;\n }\n }\n return undefined;\n}\n\n/** The `gen_ai.conversation.id` already on the active span, which for a child event is its operation span. */\nfunction getActiveSpanConversationId(): string | undefined {\n const active = getActiveSpan();\n return active ? asString(spanToJSON(active).attributes[GEN_AI_CONVERSATION_ID]) : undefined;\n}\n\n/**\n * `providerMetadata` is last-step only; drop derived usage on spans that report an aggregate.\n *\n * Reasoning goes only when it accompanies a recomputed output (Google), because dropping that\n * output leaves the span's own count reasoning-exclusive and the documented subset relationship\n * would not hold. A provider that reports reasoning against an already-inclusive output (OpenAI)\n * keeps it.\n */\nfunction dropLastStepOnlyUsage(providerAttributes: Record<string, number | string>, type: ChannelEventType): void {\n if (!ROOT_OPERATION_TYPES.has(type)) {\n return;\n }\n const hasRecomputedOutput = GEN_AI_USAGE_OUTPUT_TOKENS in providerAttributes;\n for (const key of LAST_STEP_ONLY_USAGE_KEYS) {\n // oxlint-disable-next-line typescript/no-dynamic-delete\n delete providerAttributes[key];\n }\n if (hasRecomputedOutput) {\n // oxlint-disable-next-line typescript/no-dynamic-delete\n delete providerAttributes[GEN_AI_USAGE_REASONING_OUTPUT_TOKENS];\n }\n if (PARTIAL_COST_OPERATION_TYPES.has(type)) {\n // oxlint-disable-next-line typescript/no-dynamic-delete\n delete providerAttributes[GEN_AI_COST_TOTAL_TOKENS];\n }\n}\n\n/** Record tool name → description from an event's `tools`, so tool spans can backfill the description. */\nfunction recordToolDescriptions(callId: string | undefined, tools: unknown): void {\n if (!callId || !Array.isArray(tools)) {\n return;\n }\n let descriptions = toolDescriptionsByCallId.get(callId);\n for (const tool of tools) {\n if (isObjectLike(tool) && typeof tool.name === 'string' && typeof tool.description === 'string') {\n descriptions = descriptions ?? new Map();\n if (!descriptions.has(tool.name)) {\n descriptions.set(tool.name, tool.description);\n }\n }\n }\n if (descriptions) {\n toolDescriptionsByCallId.set(callId, descriptions);\n }\n}\n\n/**\n * Resolve a tool's description, preferring the per-operation map (populated from the model-call /\n * top-level event's `tools`, v7) and falling back to a `tools` collection on the event itself —\n * which may be an array of `{ name, description }` or a record keyed by tool name (v6).\n */\nfunction resolveToolDescription(callId: string | undefined, toolName: string, tools: unknown): string | undefined {\n const fromMap = callId ? toolDescriptionsByCallId.get(callId)?.get(toolName) : undefined;\n if (fromMap) {\n return fromMap;\n }\n if (Array.isArray(tools)) {\n const match = tools.find(tool => isObjectLike(tool) && tool.name === toolName);\n return isObjectLike(match) ? asString(match.description) : undefined;\n }\n if (isObjectLike(tools)) {\n const tool = tools[toolName];\n return isObjectLike(tool) ? asString(tool.description) : undefined;\n }\n return undefined;\n}\n\n/** The lifecycle event types the `ai:telemetry` channel can carry. */\nexport type ChannelEventType =\n | 'generateText'\n | 'streamText'\n | 'streamObject'\n | 'generateObject'\n | 'step'\n | 'languageModelCall'\n | 'executeTool'\n | 'embed'\n | 'embedMany'\n | 'rerank'\n | 'experimental_evaluate'\n | 'experimental_decide';\n\n/**\n * The context object the AI SDK passes through one tracing-channel call. It is the same object\n * identity across `start`/`end`/`asyncEnd`/`error`, and Node's `tracingChannel` attaches\n * `result`/`error` to it as the traced promise settles.\n */\nexport interface VercelAiChannelMessage {\n type: ChannelEventType;\n event: Record<string, unknown>;\n result?: unknown;\n error?: unknown;\n}\n\n/**\n * Platform-provided factory that returns a tracing channel for the given channel name. The factory\n * is responsible for, when `start` fires, calling `transformStart(data)` and storing the returned\n * span on `data._sentrySpan` so the subscriber's `asyncEnd`/`error` handlers can read it.\n *\n * Node passes `@sentry/opentelemetry/tracing-channel`, which uses `bindStore` to additionally make\n * the span the active OTel context for the duration of the traced operation. That is what makes\n * nested AI SDK operations (model calls, tool calls) become children of the enclosing span without\n * any manual parent bookkeeping here.\n */\nexport type VercelAiTracingChannelFactory = <T extends object>(name: string) => TracingChannel<T, T>;\n\n/**\n * The call that `recordInputs`/`recordOutputs` decide on, and that the span hooks get: one span, with the AI SDK\n * telemetry event as published.\n */\nexport interface VercelAiCallInfo {\n /** The channel event type, such as `generateText`, `languageModelCall` or `executeTool`. */\n type: ChannelEventType;\n /** The AI SDK telemetry event of the call. */\n event: Record<string, unknown>;\n}\n\n/**\n * Integration options, pinned at subscribe time so we never look the integration up per event. `onSpanEnd` gets the\n * AI SDK result of the call as `response`; for streams it is `undefined`.\n */\nexport type VercelAiChannelOptions = GenAiCallOptions<VercelAiCallInfo> & GenAiSpanHooks<VercelAiCallInfo>;\n\n// The integration-level decision of each span, made at span start in the caller's async context. The rest of the\n// precedence (eve mode, the per-call flags, `dataCollection.genAI`) is applied when it is needed, because whether\n// `ai` withheld the result is only known at span end.\nconst integrationRecordingBySpan = new WeakMap<Span, GenAiOptions>();\n\n// `ai` >= 7.0.163 publishes no channel `result` for calls with `recordInputs`/`recordOutputs: false`. These stay\n// here rather than on the shared channel message, which other subscribers can read.\nexport const fallbackChannelResults = new WeakMap<Span, unknown>();\n\nconst spanEndHooks = new WeakMap<Span, (result: GenAiSpanResult<unknown>) => void>();\n\n/** Runs the `onSpanEnd` hook of a span that `createSpanFromMessage` started. Call it right before the span ends. */\nexport function runVercelAiSpanEnd(span: Span, result: GenAiSpanResult<unknown>): void {\n spanEndHooks.get(span)?.(result);\n}\n\n/**\n * Subscribe Sentry span handlers to the `ai` SDK's native telemetry tracing channel (`ai:telemetry`,\n * available in `ai` >= 7) and emit fully-formed `gen_ai.*` spans directly — no OpenTelemetry span\n * post-processing involved.\n *\n * The integration passes its options in directly (rather than us looking the integration up on every\n * event); the global `dataCollection.genAI` default is still read from the client per event.\n *\n * Safe to always call: on `ai` versions that don't publish to the channel (e.g. < 7) nothing is\n * ever emitted and this is inert, so there is no double-instrumentation against the OTel-based\n * patcher. The integration's `setupOnce` guarantees this runs a single time.\n */\nexport function subscribeVercelAiTracingChannel(\n tracingChannel: VercelAiTracingChannelFactory,\n options: VercelAiChannelOptions = {},\n): void {\n bindTracingChannelToSpan(\n tracingChannel<VercelAiChannelMessage>(AI_SDK_TELEMETRY_TRACING_CHANNEL),\n data => createSpanFromMessage(data, options),\n {\n // The helper ends the span; we enrich it from the settled result first (tokens, output messages,\n // finish reasons, response model/id, provider metadata) and drop the per-operation `callId` maps.\n beforeSpanEnd: (span, data) => {\n enrichSpanOnEnd(span, data);\n runVercelAiSpanEnd(\n span,\n 'error' in data ? { error: data.error } : { response: getNonStreamResult(span, data) },\n );\n // The result can hold the provider request and response bodies, and spans outlive the call.\n fallbackChannelResults.delete(span);\n clearOperationId(data);\n },\n // A streamed model call resolves before its stream is drained, so we tap the stream, keep the\n // span open, and end it (via `end`) once the final usage/finish/output chunks arrive.\n deferSpanEnd: ({ span, data, end }) => deferStreamedModelCallEnd(span, data, end),\n },\n );\n}\n\nfunction getNonStreamResult(span: Span, data: VercelAiChannelMessage): unknown {\n const result = fallbackChannelResults.get(span) ?? data.result;\n return isObjectLike(result) && isReadableStream(result.stream) ? undefined : result;\n}\n\n/**\n * When a `languageModelCall` resolves to a live `ReadableStream`, defer ending its span: swap in a\n * passthrough that forwards chunks to the SDK untouched while aggregating usage/finish/output, then\n * enrich and end the span once the stream settles. Returns `false` for anything that isn't a streamed\n * model call so the helper ends the span as usual.\n */\nfunction deferStreamedModelCallEnd(span: Span, data: VercelAiChannelMessage, end: (error?: unknown) => void): boolean {\n const result = fallbackChannelResults.get(span) ?? data.result;\n if (data.type !== 'languageModelCall' || !isObjectLike(result)) {\n return false;\n }\n const stream = result.stream;\n if (!isReadableStream(stream)) {\n return false;\n }\n\n const callId = asString(data.event.callId);\n const invokeAgentSpan = callId ? invokeAgentSpanByCallId.get(callId) : undefined;\n const { recordOutputs } = getRecordingOptions(\n data.event,\n invokeAgentSpan && integrationRecordingBySpan.get(invokeAgentSpan),\n data.result === undefined,\n );\n result.stream = tapModelCallStream(\n span,\n stream,\n final => {\n // Reshape the aggregate into the result `enrichSpanOnEnd` expects, then let `end` run it (it calls\n // `beforeSpanEnd`). Enriching the model-call span and the parent from the same aggregate keeps\n // streamed and non-streamed spans identical.\n fallbackChannelResults.set(span, { ...result, ...streamedResultToChannelResult(final) });\n end();\n if (invokeAgentSpan) {\n enrichInvokeAgentFromStream(invokeAgentSpan, final, recordOutputs);\n }\n },\n error => end(error),\n );\n\n return true;\n}\n\n/** Map the tapped stream aggregate onto the `languageModelCall` result shape `enrichSpanOnEnd` reads. */\nexport function streamedResultToChannelResult(final: StreamedModelCallResult): Record<string, unknown> {\n const content: Array<Record<string, unknown>> = [];\n if (final.text) {\n content.push({ type: 'text', text: final.text });\n }\n for (const toolCall of final.toolCalls) {\n content.push({ type: 'tool-call', ...toolCall });\n }\n\n return {\n content,\n ...(final.usage !== undefined ? { usage: final.usage } : {}),\n ...(final.finishReason !== undefined ? { finishReason: final.finishReason } : {}),\n ...(final.providerMetadata !== undefined ? { providerMetadata: final.providerMetadata } : {}),\n ...(final.responseId || final.responseModel\n ? {\n response: {\n ...(final.responseId ? { id: final.responseId } : {}),\n ...(final.responseModel ? { modelId: final.responseModel } : {}),\n },\n }\n : {}),\n };\n}\n\n/**\n * Propagate a streamed model call's usage (summed across the operation's model calls) and output onto\n * the enclosing `invoke_agent` span, which has no channel result of its own. Runs before that span ends\n * because the operation's completion promise settles only after every model-call stream has drained.\n */\nfunction enrichInvokeAgentFromStream(span: Span, final: StreamedModelCallResult, recordOutputs: boolean): void {\n const usage = isObjectLike(final.usage) ? final.usage : undefined;\n if (usage) {\n const input = tokenCount(usage.inputTokens) ?? tokenCount(usage.promptTokens) ?? tokenCount(usage.tokens);\n const output = tokenCount(usage.outputTokens) ?? tokenCount(usage.completionTokens);\n addTokensToSpan(span, GEN_AI_USAGE_INPUT_TOKENS, input);\n addTokensToSpan(span, GEN_AI_USAGE_OUTPUT_TOKENS, output);\n addTokensToSpan(span, GEN_AI_USAGE_TOTAL_TOKENS, tokenCount(usage.totalTokens) ?? sum(input, output));\n const { cacheRead, cacheWrite } = cacheTokens(usage);\n addTokensToSpan(span, GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS, cacheRead);\n addTokensToSpan(span, GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS, cacheWrite);\n }\n\n if (recordOutputs) {\n const parts = partsFromTextAndToolCalls(final.text, final.toolCalls);\n const outputMessages = buildOutputMessages(parts, getFinishReason({ finishReason: final.finishReason }));\n if (outputMessages) {\n span.setAttribute(GEN_AI_OUTPUT_MESSAGES, outputMessages);\n }\n }\n}\n\n/** Add `value` into a span's numeric token attribute, using the span itself as the running sum. */\nfunction addTokensToSpan(span: Span, attribute: string, value: number | undefined): void {\n if (value === undefined) {\n return;\n }\n const current = spanToJSON(span).attributes[attribute];\n span.setAttribute(attribute, (typeof current === 'number' ? current : 0) + value);\n}\n\n/**\n * Transform a channel `start` payload into the span that should be active for the operation. For\n * `step` we deliberately don't open a span (model calls and tool calls are siblings under the\n * invoke_agent span, matching the OTel-based output), so we reuse the active span and mark the\n * payload to skip ending it.\n */\nexport function createSpanFromMessage(\n data: VercelAiChannelMessage,\n channelOptions: VercelAiChannelOptions,\n): Span | undefined {\n const { type, event } = data;\n\n if (type === 'step' || !event || typeof event !== 'object') {\n // Opt out: returning `undefined` leaves the enclosing `invoke_agent` span as the active context\n // (model-call and tool-call events nest under it) without opening — or ending — a span of its own.\n return undefined;\n }\n\n const call: VercelAiCallInfo = { type, event };\n const integrationRecording: GenAiOptions = {\n recordInputs: resolveRecordingOption(channelOptions.recordInputs, call),\n recordOutputs: resolveRecordingOption(channelOptions.recordOutputs, call),\n };\n const span = startSpanFromEvent(type, event, getRecordingOptions(event, integrationRecording).recordInputs);\n if (span) {\n integrationRecordingBySpan.set(span, integrationRecording);\n runGenAiSpanStart(channelOptions, span, call);\n spanEndHooks.set(span, result => runGenAiSpanEnd(channelOptions, span, call, result));\n }\n return span;\n}\n\nfunction startSpanFromEvent(\n type: ChannelEventType,\n event: Record<string, unknown>,\n recordInputs: boolean,\n): Span | undefined {\n const provider = asString(event.provider);\n const modelId = asString(event.modelId);\n const callId = asString(event.callId);\n const maxRetries = asNumber(event.maxRetries);\n\n // Harvest tool descriptions from the operation/model-call `tools` so tool spans can backfill them.\n // Gated on `recordInputs` to match the OTel path, which only records `tool.definitions` then.\n if (recordInputs) {\n recordToolDescriptions(callId, event.tools);\n }\n\n // Only an operation's start event carries `providerOptions`; its model-call and tool events start\n // while the operation span is active, so they inherit the id from it. A root operation never\n // inherits, so a nested call (e.g. inside a tool's `execute`) is not folded into the outer conversation.\n const conversationId =\n getOpenAiConversationId(event.providerOptions) ??\n (ROOT_OPERATION_TYPES.has(type) ? undefined : getActiveSpanConversationId());\n\n const runtimeContextAttributes =\n (callId ? runtimeContextAttributesByCallId.get(callId) : undefined) ??\n contextAttributes(event, event.runtimeContext, VERCEL_AI_SETTINGS_CONTEXT_KEY_BASE);\n if (callId && ROOT_OPERATION_TYPES.has(type)) {\n runtimeContextAttributesByCallId.set(callId, runtimeContextAttributes);\n }\n\n const baseAttributes: SpanAttributes = {\n [SENTRY_ORIGIN]: ORIGIN,\n ...telemetryMetadataAttributes(event.telemetryMetadata),\n ...runtimeContextAttributes,\n [GEN_AI_PROVIDER_NAME]: provider,\n [VERCEL_AI_MODEL_PROVIDER_ATTRIBUTE]: provider,\n [GEN_AI_REQUEST_MODEL]: modelId,\n [VERCEL_AI_SETTINGS_MAX_RETRIES_ATTRIBUTE]: maxRetries,\n [GEN_AI_CONVERSATION_ID]: conversationId,\n };\n\n switch (type) {\n case 'generateText':\n case 'streamText':\n case 'generateObject':\n case 'streamObject':\n // The object variants' operationId rides on `event.operationId`. The JSON-schema attribute the OTel\n // path derives from the SDK's Zod schema is not reconstructed on the channel path.\n return buildInvokeAgentSpan(\n event,\n baseAttributes,\n recordInputs,\n callId,\n type === 'streamText' || type === 'streamObject',\n );\n case 'languageModelCall':\n _INTERNAL_skipAiProviderWrapping([WORKERS_AI_INTEGRATION_NAME]);\n\n return buildModelCallSpan(event, baseAttributes, recordInputs, callId, modelId);\n case 'executeTool':\n return buildToolSpan(event, recordInputs, conversationId, runtimeContextAttributes);\n case 'embed':\n case 'embedMany': {\n // `embed` carries a single `value`; `embedMany` a `values` array — both map to the embeddings input.\n const input = type === 'embedMany' ? event.values : event.value;\n return startGenAiSpan('embeddings', modelId, {\n ...baseAttributes,\n ...(recordInputs && !isStrippedInput(input) ? { [GEN_AI_EMBEDDINGS_INPUT]: stringify(input) } : {}),\n });\n }\n case 'rerank':\n return startGenAiSpan('rerank', modelId, baseAttributes);\n // `ai` 7.0.128 renamed `experimental_evaluate` to `experimental_decide`; older 7.x still publishes the old name.\n case 'experimental_evaluate':\n case 'experimental_decide':\n return startGenAiSpan('decide', modelId, {\n ...baseAttributes,\n ...(recordInputs && !(isStrippedInput(event.state) && isStrippedInput(event.questions))\n ? {\n [GEN_AI_INPUT_MESSAGES]: stringify([\n { type: 'evaluation', state: event.state, questions: event.questions },\n ]),\n }\n : {}),\n });\n default:\n // Unknown event type: opt out rather than open a span we can't shape correctly.\n return undefined;\n }\n}\n\n/**\n * `experimental_telemetry.metadata` (`ai` <= 6) as `vercel.ai.telemetry.metadata.<key>`, the names the OTel\n * integration produced from the SDK's `ai.telemetry.metadata.*`. Only the orchestrion adapter sets\n * `event.telemetryMetadata`; `ai` 7 has no `telemetry.metadata`.\n */\nfunction telemetryMetadataAttributes(metadata: unknown): Record<string, string> {\n const attributes: Record<string, string> = {};\n if (isObjectLike(metadata)) {\n for (const [key, value] of Object.entries(metadata)) {\n if (value === null || value === undefined) continue;\n attributes[`${VERCEL_AI_TELEMETRY_METADATA_ATTRIBUTE_PREFIX}${key}`] = String(value);\n }\n }\n return attributes;\n}\n\n/**\n * One string attribute per context key, as `<prefix><key>`. `ai` < 7.0.114 published the full context to the\n * channel, ignoring `telemetry.includeRuntimeContext`/`includeToolsContext`, and a filtered context\n * looks the same as an unfiltered one. `aiVersion` (added in 7.0.154) is the only reliable sign that\n * the AI SDK filtered it, so without it we record nothing.\n */\nfunction contextAttributes(event: Record<string, unknown>, context: unknown, keyBase: string): SpanAttributes {\n const attributes: SpanAttributes = {};\n if (typeof event.aiVersion !== 'string' || !isObjectLike(context)) {\n return attributes;\n }\n for (const [key, value] of Object.entries(context)) {\n const attributeValue = stringify(value);\n if (value !== null && attributeValue !== undefined) {\n attributes[`${keyBase}.${key}`] = attributeValue;\n }\n }\n return attributes;\n}\n\n/** Start a `gen_ai.<operation>` span named `<operation> <suffix>` (or just `<operation>` when no suffix). */\nfunction startGenAiSpan(operation: GenAiOperation, suffix: string | undefined, attributes: SpanAttributes): Span {\n return startInactiveSpan({\n name: suffix ? `${operation} ${suffix}` : operation,\n attributes: {\n [SENTRY_OP]: GEN_AI_OPERATION_SPAN_OPS[operation],\n [GEN_AI_OPERATION_NAME]: operation,\n ...attributes,\n },\n });\n}\n\nfunction buildInvokeAgentSpan(\n event: Record<string, unknown>,\n baseAttributes: SpanAttributes,\n recordInputs: boolean,\n callId: string | undefined,\n isStream: boolean,\n): Span {\n const functionId = asString(event.functionId);\n const operationId = asString(event.operationId) ?? (isStream ? 'ai.streamText' : 'ai.generateText');\n if (callId) {\n operationIdByCallId.set(callId, { operationId, isStream });\n }\n const span = startGenAiSpan('invoke_agent', functionId, {\n ...baseAttributes,\n [VERCEL_AI_OPERATION_ID_ATTRIBUTE]: operationId,\n [GEN_AI_RESPONSE_STREAMING]: isStream,\n [GEN_AI_FUNCTION_ID]: functionId,\n ...(recordInputs ? buildInputMessageAttributes(event) : {}),\n });\n if (isStream && callId) {\n invokeAgentSpanByCallId.set(callId, span);\n }\n\n return span;\n}\n\nfunction buildModelCallSpan(\n event: Record<string, unknown>,\n baseAttributes: SpanAttributes,\n recordInputs: boolean,\n callId: string | undefined,\n modelId: string | undefined,\n): Span {\n const parent = callId ? operationIdByCallId.get(callId) : undefined;\n const operationId = parent\n ? `${parent.operationId}.${parent.isStream ? 'doStream' : 'doGenerate'}`\n : 'ai.generateText.doGenerate';\n return startGenAiSpan('generate_content', modelId, {\n ...baseAttributes,\n [VERCEL_AI_OPERATION_ID_ATTRIBUTE]: operationId,\n ...(recordInputs ? buildInputMessageAttributes(event) : {}),\n ...(recordInputs && Array.isArray(event.tools) ? { [GEN_AI_TOOL_DEFINITIONS]: stringify(event.tools) } : {}),\n });\n}\n\nfunction buildToolSpan(\n event: Record<string, unknown>,\n recordInputs: boolean,\n conversationId: string | undefined,\n runtimeContextAttributes: SpanAttributes,\n): Span {\n const toolCall = isObjectLike(event.toolCall) ? event.toolCall : {};\n const toolName = asString(toolCall.toolName);\n const toolCallId = asString(event.toolCallId) ?? asString(toolCall.toolCallId);\n const toolInput = toolCall.input ?? toolCall.args;\n // The `executeTool` event has no description; backfill it from the operation's recorded tools.\n // Gated on `recordInputs` to match the OTel path (descriptions come from the recorded tools list).\n const description =\n recordInputs && toolName ? resolveToolDescription(asString(event.callId), toolName, event.tools) : undefined;\n return startGenAiSpan('execute_tool', toolName, {\n [SENTRY_ORIGIN]: ORIGIN,\n ...runtimeContextAttributes,\n ...contextAttributes(event, event.toolContext, VERCEL_AI_TOOL_CALL_CONTEXT_KEY_BASE),\n [GEN_AI_TOOL_NAME]: toolName,\n [GEN_AI_TOOL_CALL_ID_ATTRIBUTE]: toolCallId,\n [GEN_AI_TOOL_DESCRIPTION]: description,\n ...(recordInputs && toolInput !== undefined ? { [GEN_AI_TOOL_CALL_ARGUMENTS]: stringify(toolInput) } : {}),\n [GEN_AI_CONVERSATION_ID]: conversationId,\n });\n}\n\n/**\n * Best-effort enrichment from the resolved value the AI SDK attaches to the channel context.\n * Everything here is guarded: when a field is missing or the shape differs across `ai` versions,\n * we simply don't set the attribute rather than emit a malformed span.\n */\nexport function enrichSpanOnEnd(span: Span, data: VercelAiChannelMessage): void {\n const { type } = data;\n const result = fallbackChannelResults.get(span) ?? data.result;\n if (!isObjectLike(result)) {\n return;\n }\n\n const { recordOutputs } = getRecordingOptions(\n data.event,\n integrationRecordingBySpan.get(span),\n data.result === undefined,\n );\n\n if (type === 'executeTool') {\n // From V5 on, tool errors are not rejected (so the `error` channel verb never fires) — they\n // surface as `tool-error` content on the resolved result. Mirror the OTel path by marking the\n // span and capturing the error, which carry the failure instead of the result attribute.\n const output = isObjectLike(result.output) ? result.output : undefined;\n if (output?.type === 'tool-error') {\n captureToolError(span, data, output.error);\n } else if (recordOutputs) {\n span.setAttribute(GEN_AI_TOOL_CALL_RESULT, stringify(result.output ?? result));\n }\n return;\n }\n\n // `languageModelCall` results report usage as `{ total }` objects; top-level/step results report\n // flat numbers. `tokenCount` handles both. v4 names tokens `promptTokens`/`completionTokens`\n // (v5+ uses `inputTokens`/`outputTokens`); the fallbacks are `undefined`-inert on v5+.\n const usage = isObjectLike(result.usage) ? result.usage : undefined;\n if (usage) {\n const inputTokens = tokenCount(usage.inputTokens) ?? tokenCount(usage.promptTokens) ?? tokenCount(usage.tokens);\n const outputTokens = tokenCount(usage.outputTokens) ?? tokenCount(usage.completionTokens);\n const totalTokens = tokenCount(usage.totalTokens) ?? sum(inputTokens, outputTokens);\n if (inputTokens !== undefined) {\n span.setAttribute(GEN_AI_USAGE_INPUT_TOKENS, inputTokens);\n }\n if (outputTokens !== undefined) {\n span.setAttribute(GEN_AI_USAGE_OUTPUT_TOKENS, outputTokens);\n }\n if (totalTokens !== undefined) {\n span.setAttribute(GEN_AI_USAGE_TOTAL_TOKENS, totalTokens);\n }\n setCacheTokens(span, usage);\n }\n\n // Match the OTel integration: finish reasons live on the model-call (`generate_content`) span, not\n // on the top-level `invoke_agent` span.\n const finishReason = getFinishReason(result);\n if (finishReason && type === 'languageModelCall') {\n span.setAttribute(GEN_AI_RESPONSE_FINISH_REASONS, stringify([finishReason]));\n }\n\n const response = isObjectLike(result.response) ? result.response : undefined;\n const responseId = asString(response?.id) ?? asString(result.responseId);\n if (responseId) {\n span.setAttribute(GEN_AI_RESPONSE_ID, responseId);\n }\n const responseModel = asString(response?.modelId) ?? asString(data.event.modelId);\n if (responseModel) {\n span.setAttribute(GEN_AI_RESPONSE_MODEL, responseModel);\n }\n\n // Provider-specific cache/reasoning/prediction token breakdowns. The channel exposes `providerMetadata`\n // as an object (the OTel path parses it from a string); both share `getProviderMetadataAttributes` so\n // the emitted shape is identical.\n const providerMetadata = (result as { providerMetadata?: unknown }).providerMetadata;\n const providerAttributes = getProviderMetadataAttributes(providerMetadata);\n dropLastStepOnlyUsage(providerAttributes, type);\n span.setAttributes(providerAttributes);\n\n if (recordOutputs) {\n const outputMessages = getOutputMessages(type, result, finishReason);\n if (outputMessages) {\n span.setAttribute(GEN_AI_OUTPUT_MESSAGES, outputMessages);\n }\n }\n}\n\nfunction getOutputMessages(\n type: ChannelEventType,\n result: Record<string, unknown>,\n finishReason: string | undefined,\n): string | undefined {\n if (type === 'experimental_evaluate' || type === 'experimental_decide') {\n return getEvaluationOutputMessages(withProviderAnswerFields(result));\n }\n // `languageModelCall` exposes the response as a `content` parts array; top-level results expose\n // `text` + `toolCalls`. Both normalize into the OTel `gen_ai.output.messages` assistant message.\n const parts =\n type === 'languageModelCall' && Array.isArray(result.content)\n ? partsFromContent(result.content)\n : partsFromTextAndToolCalls(result.text, result.toolCalls);\n return buildOutputMessages(parts, finishReason);\n}\n\n/**\n * Providers move answer fields into `providerMetadata`: TypeSafe and OpenAI as `<provider>.confidence[id]`,\n * OpenRouter as `openrouter.answers[id].{confidence,legend}`. Put them back on the answers.\n */\nfunction withProviderAnswerFields(result: Record<string, unknown>): unknown {\n const { answers, providerMetadata } = result;\n if (!isObjectLike(answers) || !isObjectLike(providerMetadata)) {\n return answers;\n }\n const confidenceById = [providerMetadata.typesafe, providerMetadata.openai]\n .map(metadata => (isObjectLike(metadata) ? metadata.confidence : undefined))\n .find(isObjectLike);\n const { openrouter } = providerMetadata;\n const openrouterById = isObjectLike(openrouter) && isObjectLike(openrouter.answers) ? openrouter.answers : undefined;\n if (!confidenceById && !openrouterById) {\n return answers;\n }\n\n return Object.fromEntries(\n Object.entries(answers).map(([id, answer]) => {\n if (!isObjectLike(answer)) {\n return [id, answer];\n }\n const openrouterAnswer = openrouterById?.[id];\n const fields = isObjectLike(openrouterAnswer) ? openrouterAnswer : {};\n const {\n confidence = asNumber(confidenceById?.[id]) ?? asNumber(fields.confidence),\n legend = isObjectLike(fields.legend) ? fields.legend : undefined,\n } = answer;\n return [id, { ...answer, confidence, legend }];\n }),\n );\n}\n\n/** Maps a Vercel AI finish reason to the OTel `gen_ai.output.messages` form (`tool-calls` → `tool_call`). */\nfunction normalizeFinishReason(finishReason: string | undefined): string {\n return finishReason === 'tool-calls' ? 'tool_call' : (finishReason ?? 'stop');\n}\n\n/** Reads the finish reason from a result — a string on top-level results, `{ unified }` on model calls. */\nfunction getFinishReason(result: Record<string, unknown>): string | undefined {\n const finishReason = result.finishReason;\n if (typeof finishReason === 'string') {\n return finishReason;\n }\n return isObjectLike(finishReason) ? asString(finishReason.unified) : undefined;\n}\n\n/** Reads a token count that may be a plain number or a `{ total }` object (model-call usage). */\nfunction tokenCount(value: unknown): number | undefined {\n return asNumber(value) ?? (isObjectLike(value) ? asNumber(value.total) : undefined);\n}\n\n/**\n * Cache token counts as the AI SDK normalizes them: v5 `cachedInputTokens`, v6 `inputTokenDetails`,\n * v7 `inputTokens.{cacheRead,cacheWrite}`.\n */\nfunction setCacheTokens(span: Span, usage: Record<string, unknown>): void {\n const { cacheRead, cacheWrite } = cacheTokens(usage);\n if (cacheRead !== undefined) {\n span.setAttribute(GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS, cacheRead);\n }\n if (cacheWrite !== undefined) {\n span.setAttribute(GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS, cacheWrite);\n }\n}\n\nfunction cacheTokens(usage: Record<string, unknown>): { cacheRead?: number; cacheWrite?: number } {\n const inputTokens = isObjectLike(usage.inputTokens) ? usage.inputTokens : undefined;\n const inputTokenDetails = isObjectLike(usage.inputTokenDetails) ? usage.inputTokenDetails : undefined;\n return {\n cacheRead:\n asNumber(inputTokens?.cacheRead) ??\n asNumber(inputTokenDetails?.cacheReadTokens) ??\n asNumber(usage.cachedInputTokens),\n cacheWrite: asNumber(inputTokens?.cacheWrite) ?? asNumber(inputTokenDetails?.cacheWriteTokens),\n };\n}\n\nfunction buildOutputMessages(\n parts: Array<Record<string, unknown>>,\n finishReason: string | undefined,\n): string | undefined {\n if (!parts.length) {\n return undefined;\n }\n return stringify([{ role: 'assistant', parts, finish_reason: normalizeFinishReason(finishReason) }]);\n}\n\nfunction toolCallPart(toolCall: Record<string, unknown>): Record<string, unknown> {\n const args = toolCall.input ?? toolCall.args;\n return {\n type: 'tool_call',\n id: asString(toolCall.toolCallId),\n name: asString(toolCall.toolName),\n arguments: typeof args === 'string' ? args : stringify(args ?? {}),\n };\n}\n\nfunction partsFromContent(content: unknown[]): Array<Record<string, unknown>> {\n const parts: Array<Record<string, unknown>> = [];\n for (const item of content) {\n if (!isObjectLike(item)) {\n continue;\n }\n if (item.type === 'text' && typeof item.text === 'string') {\n parts.push({ type: 'text', content: item.text });\n } else if (item.type === 'tool-call') {\n parts.push(toolCallPart(item));\n }\n }\n return parts;\n}\n\nfunction partsFromTextAndToolCalls(text: unknown, toolCalls: unknown): Array<Record<string, unknown>> {\n const parts: Array<Record<string, unknown>> = [];\n if (typeof text === 'string' && text.length) {\n parts.push({ type: 'text', content: text });\n }\n if (Array.isArray(toolCalls)) {\n for (const toolCall of toolCalls) {\n if (isObjectLike(toolCall)) {\n parts.push(toolCallPart(toolCall));\n }\n }\n }\n return parts;\n}\n\nexport function captureToolError(span: Span, data: VercelAiChannelMessage, error: unknown): void {\n span.setStatus({\n code: SPAN_STATUS_ERROR,\n message: error instanceof Error ? error.message : 'tool_error',\n });\n\n const toolCall = isObjectLike(data.event.toolCall) ? data.event.toolCall : {};\n const toolName = asString(toolCall.toolName);\n const toolCallId = asString(data.event.toolCallId) ?? asString(toolCall.toolCallId);\n\n withScope(scope => {\n scope.setContext('trace', spanToTraceContext(span));\n if (toolName) {\n scope.setTag('vercel.ai.tool.name', toolName);\n }\n if (toolCallId) {\n scope.setTag('vercel.ai.tool.callId', toolCallId);\n }\n scope.setLevel('error');\n captureException(\n error instanceof Error ? error : new Error(typeof error === 'string' ? error : 'Tool execution failed'),\n {\n mechanism: { type: 'auto.ai.vercelai', handled: false },\n },\n );\n });\n}\n\nfunction getRecordingOptions(\n event: Record<string, unknown>,\n integrationRecording: GenAiOptions = {},\n channelWithheldResult = false,\n): {\n recordInputs: boolean;\n recordOutputs: boolean;\n} {\n const client = getClient();\n const genAI = client?.getDataCollectionOptions().genAI;\n // `ai` withheld the result because of the per-call flag, which eve >= 1.0.0-rc.10 sets from trace policies, so\n // the flag is a content decision there rather than eve's blanket default.\n const eveMode = client && !channelWithheldResult ? isEveGenAiRecordingDefault(client) : false;\n\n return {\n recordInputs: resolveRecording(integrationRecording.recordInputs, event.recordInputs, genAI?.inputs, eveMode),\n recordOutputs: resolveRecording(integrationRecording.recordOutputs, event.recordOutputs, genAI?.outputs, eveMode),\n };\n}\n\n/**\n * Mirrors the OTel integration's `determineRecordingSettings` precedence: an integration-level option\n * wins, then the per-call `experimental_telemetry.recordInputs/recordOutputs` flag the AI SDK forwards\n * on the channel event, then the global `dataCollection.genAI` default.\n *\n * NOTE: the OTel integration also defaults recording to `true` for a call with\n * `experimental_telemetry: { isEnabled: true }`. The `ai:telemetry` channel does not expose `isEnabled`\n * (nor a resolved recording flag), so that per-call default cannot be reproduced here — v7 users who\n * want inputs/outputs recorded must enable `dataCollection.genAI` or set `recordInputs`/`recordOutputs`.\n *\n * Under `eveMode` (set by `eveIntegration()`) the per-call flag is eve's blanket framework default\n * rather than an end-user decision, so it is skipped: an explicit `dataCollection.genAI` still wins,\n * otherwise recording defaults to `true`. An integration-level option outranks both regardless.\n */\nfunction resolveRecording(\n integrationOption: unknown,\n perCallOption: unknown,\n globalDefault: unknown,\n eveMode = false,\n): boolean {\n if (typeof integrationOption === 'boolean') {\n return integrationOption;\n }\n if (eveMode) {\n return typeof globalDefault === 'boolean' ? globalDefault : true;\n }\n if (typeof perCallOption === 'boolean') {\n return perCallOption;\n }\n return globalDefault === true;\n}\n\n/** `ai` >= 7.0.163 replaces inputs with empty values when `recordInputs` is false. */\nfunction isStrippedInput(input: unknown): boolean {\n return (\n input === undefined ||\n input === '' ||\n (Array.isArray(input) && !input.length) ||\n (isPlainObject(input) && !Object.keys(input).length)\n );\n}\n\n/** The `ai` SDK accepts the system prompt as `string | SystemModelMessage | SystemModelMessage[]`. */\nfunction getSystemInstructionParts(instructions: unknown): { type: 'text'; content: string }[] {\n const messages = Array.isArray(instructions) ? instructions : [instructions];\n return messages.flatMap(message => {\n const content = asString(isObjectLike(message) ? message.content : message);\n return content ? [{ type: 'text' as const, content }] : [];\n });\n}\n\nfunction buildInputMessageAttributes(event: Record<string, unknown>): Record<string, string | number | undefined> {\n const attributes: Record<string, string | number | undefined> = {};\n\n // `ai` >= 7 forbids system messages in `messages`/`prompt` and exposes the system prompt as a\n // separate `instructions` field. The OTel path lifts the system message out of the prompt into\n // `gen_ai.system_instructions` as `[{ type: 'text', content }]`; mirror that shape here.\n const instructions = getSystemInstructionParts(event.instructions);\n if (instructions.length) {\n attributes[GEN_AI_SYSTEM_INSTRUCTIONS] = stringify(instructions);\n }\n\n // The AI SDK start events extend `StandardizedPrompt`; messages live on `messages`, otherwise the\n // simpler `prompt` field is used.\n const messages = event.messages ?? event.prompt;\n if (!isStrippedInput(messages)) {\n attributes[GEN_AI_INPUT_MESSAGES] = stringify(messages);\n }\n\n return attributes;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAgFA,MAAa,mCAAmC;AAEhD,MAAM,SAAS;AAGf,MAAM,4BAA4B;CAChC,YAAY;CAIZ,QAAQ;CACR,QAAQ;CACR,cAAc;CACd,cAAc;CAGd,kBAAkB;AACpB;AAKA,MAAM,mCAAmC;AACzC,MAAM,qCAAqC;AAC3C,MAAM,2CAA2C;AACjD,MAAM,gDAAgD;AAMtD,MAAM,sCAAsB,IAAI,IAAwD;AASxF,MAAM,2CAA2B,IAAI,IAAiC;AAMtE,MAAM,0CAA0B,IAAI,IAAkB;AAItD,MAAM,mDAAmC,IA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O;CAClH;AACF;;;;;;;;;;;;;;;AAgBA,SAAS,iBACP,mBACA,eACA,eACA,UAAU,OACD;CACT,IAAI,OAAO,sBAAsB,WAC/B,OAAO;CAET,IAAI,SACF,OAAO,OAAO,kBAAkB,YAAY,gBAAgB;CAE9D,IAAI,OAAO,kBAAkB,WAC3B,OAAO;CAET,OAAO,kBAAkB;AAC3B;;AAGA,SAAS,gBAAgB,OAAyB;CAChD,OACE,UAAU,KAAA,KACV,UAAU,MACT,MAAM,QAAQ,KAAK,KAAK,CAAC,MAAM,UAC/B,cAAc,KAAK,KAAK,CAAC,OAAO,KAAK,KAAK,CAAC,CAAC;AAEjD;;AAGA,SAAS,0BAA0B,cAA4D;CAE7F,QADiB,MAAM,QAAQ,YAAY,IAAI,eAAe,CAAC,YAAY,EAAA,CAC3D,SAAQ,YAAW;EACjC,MAAM,UAAU,SAAS,aAAa,OAAO,IAAI,QAAQ,UAAU,OAAO;EAC1E,OAAO,UAAU,CAAC;GAAE,MAAM;GAAiB;EAAQ,CAAC,IAAI,CAAC;CAC3D,CAAC;AACH;AAEA,SAAS,4BAA4B,OAA6E;CAChH,MAAM,aAA0D,CAAC;CAKjE,MAAM,eAAe,0BAA0B,MAAM,YAAY;CACjE,IAAI,aAAa,QACf,WAAW,8BAA8B,UAAU,YAAY;CAKjE,MAAM,WAAW,MAAM,YAAY,MAAM;CACzC,IAAI,CAAC,gBAAgB,QAAQ,GAC3B,WAAW,yBAAyB,UAAU,QAAQ;CAGxD,OAAO;AACT"}
1
+ {"version":3,"file":"vercel-ai-dc-subscriber.js","names":[],"sources":["../../../../src/integrations/vercel-ai/vercel-ai-dc-subscriber.ts"],"sourcesContent":["/* eslint-disable max-lines */\nimport {\n GEN_AI_CONVERSATION_ID,\n GEN_AI_COST_TOTAL_TOKENS,\n GEN_AI_EMBEDDINGS_INPUT,\n GEN_AI_FUNCTION_ID,\n GEN_AI_INPUT_MESSAGES,\n GEN_AI_OPERATION_NAME,\n GEN_AI_OUTPUT_MESSAGES,\n GEN_AI_PROVIDER_NAME,\n GEN_AI_REQUEST_MODEL,\n GEN_AI_RESPONSE_FINISH_REASONS,\n GEN_AI_RESPONSE_ID,\n GEN_AI_RESPONSE_MODEL,\n GEN_AI_RESPONSE_STREAMING,\n GEN_AI_SYSTEM_INSTRUCTIONS,\n GEN_AI_TOOL_CALL_ARGUMENTS,\n GEN_AI_TOOL_CALL_RESULT,\n GEN_AI_TOOL_DEFINITIONS,\n GEN_AI_TOOL_DESCRIPTION,\n GEN_AI_TOOL_NAME,\n GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS,\n GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS,\n GEN_AI_USAGE_INPUT_TOKENS,\n GEN_AI_USAGE_OUTPUT_TOKENS,\n GEN_AI_USAGE_REASONING_OUTPUT_TOKENS,\n GEN_AI_USAGE_TOTAL_TOKENS,\n SENTRY_OP,\n SENTRY_ORIGIN,\n VERCEL_AI_SETTINGS_CONTEXT_KEY_BASE,\n VERCEL_AI_TOOL_CALL_CONTEXT_KEY_BASE,\n} from '@sentry/conventions/attributes';\nimport {\n GEN_AI_DECIDE,\n GEN_AI_EMBEDDINGS,\n GEN_AI_EXECUTE_TOOL,\n GEN_AI_EXTRACT,\n GEN_AI_GENERATE_CONTENT,\n GEN_AI_INVOKE_AGENT,\n GEN_AI_RERANK,\n} from '@sentry/conventions/op';\nimport type { Span, SpanAttributes } from '@sentry/core';\nimport {\n _INTERNAL_skipAiProviderWrapping,\n captureException,\n getActiveSpan,\n getClient,\n isObjectLike,\n isPlainObject,\n SPAN_STATUS_ERROR,\n spanToJSON,\n spanToTraceContext,\n startInactiveSpan,\n stringify,\n withScope,\n} from '@sentry/core';\nimport type { TracingChannel } from 'node:diagnostics_channel';\nimport { GEN_AI_TOOL_CALL_ID_ATTRIBUTE } from '../../ai/core/gen-ai-attributes';\nimport {\n type GenAiSpanHooks,\n type GenAiSpanResult,\n runGenAiSpanEnd,\n runGenAiSpanStart,\n} from '../../ai/core/span-hooks';\nimport { isEveGenAiRecordingDefault } from './gen-ai-recording-mode';\nimport {\n type GenAiCallOptions,\n type GenAiOptions,\n getEvaluationOutputMessages,\n resolveRecordingOption,\n} from '../../ai/core/utils';\nimport { getProviderMetadataAttributes, LAST_STEP_ONLY_USAGE_KEYS } from '../../ai/vercel-ai';\nimport { WORKERS_AI_INTEGRATION_NAME } from '../../ai/workers-ai/constants';\nimport { bindTracingChannelToSpan } from '../../tracing-channel';\nimport { toExtractAnswers, toExtractFields, toExtractState } from './extract';\nimport {\n asNumber,\n asString,\n isReadableStream,\n mapObjectValues,\n type StreamedModelCallResult,\n sum,\n tapModelCallStream,\n} from './util';\n\n/**\n * The single tracing channel the `ai` package (>= 7) publishes all telemetry lifecycle events to\n * via `node:diagnostics_channel`. Events are discriminated by their `type` field.\n * @see https://github.com/vercel/ai/pull/15660\n */\nexport const AI_SDK_TELEMETRY_TRACING_CHANNEL = 'ai:telemetry';\n\nconst ORIGIN = 'auto.ai.vercelai';\n\n// `gen_ai.operation.name` values, keyed to the span op they map to.\nconst GEN_AI_OPERATION_SPAN_OPS = {\n embeddings: GEN_AI_EMBEDDINGS,\n // `GEN_AI_RERANK` is deprecated because the product doesn't support rerank spans, but we keep\n // emitting it so existing rerank spans keep their op.\n // oxlint-disable-next-line typescript/no-deprecated\n rerank: GEN_AI_RERANK,\n decide: GEN_AI_DECIDE,\n extract: GEN_AI_EXTRACT,\n invoke_agent: GEN_AI_INVOKE_AGENT,\n execute_tool: GEN_AI_EXECUTE_TOOL,\n // The model-call op matches the Vercel AI OTel integration (`gen_ai.generate_content`) rather than\n // the generic `gen_ai.chat`, so v6 (OTel) and v7 (channel) produce the same spans.\n generate_content: GEN_AI_GENERATE_CONTENT,\n} as const;\n\ntype GenAiOperation = keyof typeof GEN_AI_OPERATION_SPAN_OPS;\n\n// Subset of the `vercel.ai.*` passthrough attributes the OTel integration emits that we reproduce.\nconst VERCEL_AI_OPERATION_ID_ATTRIBUTE = 'vercel.ai.operationId';\nconst VERCEL_AI_MODEL_PROVIDER_ATTRIBUTE = 'vercel.ai.model.provider';\nconst VERCEL_AI_SETTINGS_MAX_RETRIES_ATTRIBUTE = 'vercel.ai.settings.maxRetries';\nconst VERCEL_AI_TELEMETRY_METADATA_ATTRIBUTE_PREFIX = 'vercel.ai.telemetry.metadata.';\n\n// Tracks the top-level operationId (and whether it streams) per `callId` so a model-call span can\n// name its `doGenerate`/`doStream` operation the same way the OTel integration does. `isStream` is\n// the authoritative event-type signal rather than a substring check on the (possibly custom)\n// operationId. Cleared when the top-level span ends.\nconst operationIdByCallId = new Map<string, { operationId: string; isStream: boolean }>();\n\n// Per-operation map of tool name → description, harvested from a model-call /\n// top-level event's `tools` (keyed by the shared `callId`). The AI SDK's\n// `executeTool` event doesn't carry the tool's description, so we backfill it\n// onto the tool span here — without relying on the OTel `vercelAiEventProcessor`\n// (which isn't registered in channel/orchestrion mode). Cleared with the\n// operation. Only populated when inputs are recorded, matching the OTel path\n// (which sources descriptions from the recorded `tool.definitions`).\nconst toolDescriptionsByCallId = new Map<string, Map<string, string>>();\n\n// A streamed `streamText` operation's own channel result is always `undefined` (the SDK exposes the\n// stream only on the model call), so its `invoke_agent` span can't be enriched from the channel. We\n// key the span by `callId` and enrich it as each streamed model call drains — the model calls flush\n// before the operation's own span ends. The running token sum lives on the span's own attributes.\nconst invokeAgentSpanByCallId = new Map<string, Span>();\n\n// Only an operation's start event carries `runtimeContext`; its model-call and tool events copy the\n// resulting attributes from here. Cleared with the operation.\nconst runtimeContextAttributesByCallId = new Map<string, SpanAttributes>();\n\n// Only top-level operations own the `callId` → operationId mapping; `step`/`languageModelCall`/\n// `executeTool` share the parent's `callId`, so they must not clear it.\nconst ROOT_OPERATION_TYPES = new Set<ChannelEventType>([\n 'generateText',\n 'streamText',\n 'streamObject',\n 'generateObject',\n 'embed',\n 'embedMany',\n 'rerank',\n]);\n\n// Operations whose `providerMetadata` cost covers only one of their provider calls: the last step of a\n// text or object operation, whose cost the `generate_content` spans carry, or one `embedMany` chunk.\nconst PARTIAL_COST_OPERATION_TYPES = new Set<ChannelEventType>([\n 'generateText',\n 'streamText',\n 'streamObject',\n 'generateObject',\n 'embedMany',\n]);\n\n/** Drop the per-operation `callId` maps once the owning top-level operation settles (success or error). */\nexport function clearOperationId(data: VercelAiChannelMessage): void {\n if (!ROOT_OPERATION_TYPES.has(data.type)) {\n return;\n }\n const callId = asString(data.event.callId);\n if (callId) {\n clearOperationCallId(callId);\n }\n}\n\n/**\n * Drop the per-operation `callId` maps for a single id. The v6 orchestrion adapter uses this to clear a\n * `streamText`/`streamObject` operation only after its lazily-run model call settles — the operation's own\n * span ends synchronously (when the call returns) but the model call runs later as the stream is consumed,\n * and it still needs the operation's `operationId`/`isStream` entry to name itself `ai.streamText.doStream`\n * (or `ai.streamObject.doStream`).\n */\nexport function clearOperationCallId(callId: string): void {\n operationIdByCallId.delete(callId);\n toolDescriptionsByCallId.delete(callId);\n invokeAgentSpanByCallId.delete(callId);\n runtimeContextAttributesByCallId.delete(callId);\n}\n\n/**\n * The OpenAI Conversations API id from `providerOptions.openai.conversation` (or `azure`): the one\n * provider-level value that is the same on every turn. A `Sentry.setConversationId()` value still wins,\n * since `conversationIdIntegration` writes it on `spanStart`, after these start attributes.\n */\nfunction getOpenAiConversationId(providerOptions: unknown): string | undefined {\n if (!isObjectLike(providerOptions)) {\n return undefined;\n }\n for (const key of ['openai', 'azure']) {\n const options = providerOptions[key];\n const conversation = isObjectLike(options) ? asString(options.conversation) : undefined;\n if (conversation) {\n return conversation;\n }\n }\n return undefined;\n}\n\n/** The `gen_ai.conversation.id` already on the active span, which for a child event is its operation span. */\nfunction getActiveSpanConversationId(): string | undefined {\n const active = getActiveSpan();\n return active ? asString(spanToJSON(active).attributes[GEN_AI_CONVERSATION_ID]) : undefined;\n}\n\n/**\n * `providerMetadata` is last-step only; drop derived usage on spans that report an aggregate.\n *\n * Reasoning goes only when it accompanies a recomputed output (Google), because dropping that\n * output leaves the span's own count reasoning-exclusive and the documented subset relationship\n * would not hold. A provider that reports reasoning against an already-inclusive output (OpenAI)\n * keeps it.\n */\nfunction dropLastStepOnlyUsage(providerAttributes: Record<string, number | string>, type: ChannelEventType): void {\n if (!ROOT_OPERATION_TYPES.has(type)) {\n return;\n }\n const hasRecomputedOutput = GEN_AI_USAGE_OUTPUT_TOKENS in providerAttributes;\n for (const key of LAST_STEP_ONLY_USAGE_KEYS) {\n // oxlint-disable-next-line typescript/no-dynamic-delete\n delete providerAttributes[key];\n }\n if (hasRecomputedOutput) {\n // oxlint-disable-next-line typescript/no-dynamic-delete\n delete providerAttributes[GEN_AI_USAGE_REASONING_OUTPUT_TOKENS];\n }\n if (PARTIAL_COST_OPERATION_TYPES.has(type)) {\n // oxlint-disable-next-line typescript/no-dynamic-delete\n delete providerAttributes[GEN_AI_COST_TOTAL_TOKENS];\n }\n}\n\n/** Record tool name → description from an event's `tools`, so tool spans can backfill the description. */\nfunction recordToolDescriptions(callId: string | undefined, tools: unknown): void {\n if (!callId || !Array.isArray(tools)) {\n return;\n }\n let descriptions = toolDescriptionsByCallId.get(callId);\n for (const tool of tools) {\n if (isObjectLike(tool) && typeof tool.name === 'string' && typeof tool.description === 'string') {\n descriptions = descriptions ?? new Map();\n if (!descriptions.has(tool.name)) {\n descriptions.set(tool.name, tool.description);\n }\n }\n }\n if (descriptions) {\n toolDescriptionsByCallId.set(callId, descriptions);\n }\n}\n\n/**\n * Resolve a tool's description, preferring the per-operation map (populated from the model-call /\n * top-level event's `tools`, v7) and falling back to a `tools` collection on the event itself —\n * which may be an array of `{ name, description }` or a record keyed by tool name (v6).\n */\nfunction resolveToolDescription(callId: string | undefined, toolName: string, tools: unknown): string | undefined {\n const fromMap = callId ? toolDescriptionsByCallId.get(callId)?.get(toolName) : undefined;\n if (fromMap) {\n return fromMap;\n }\n if (Array.isArray(tools)) {\n const match = tools.find(tool => isObjectLike(tool) && tool.name === toolName);\n return isObjectLike(match) ? asString(match.description) : undefined;\n }\n if (isObjectLike(tools)) {\n const tool = tools[toolName];\n return isObjectLike(tool) ? asString(tool.description) : undefined;\n }\n return undefined;\n}\n\n/** The lifecycle event types the `ai:telemetry` channel can carry. */\nexport type ChannelEventType =\n | 'generateText'\n | 'streamText'\n | 'streamObject'\n | 'generateObject'\n | 'step'\n | 'languageModelCall'\n | 'executeTool'\n | 'embed'\n | 'embedMany'\n | 'rerank'\n | 'experimental_evaluate'\n | 'experimental_decide'\n | 'experimental_extract';\n\n/**\n * The context object the AI SDK passes through one tracing-channel call. It is the same object\n * identity across `start`/`end`/`asyncEnd`/`error`, and Node's `tracingChannel` attaches\n * `result`/`error` to it as the traced promise settles.\n */\nexport interface VercelAiChannelMessage {\n type: ChannelEventType;\n event: Record<string, unknown>;\n result?: unknown;\n error?: unknown;\n}\n\n/**\n * Platform-provided factory that returns a tracing channel for the given channel name. The factory\n * is responsible for, when `start` fires, calling `transformStart(data)` and storing the returned\n * span on `data._sentrySpan` so the subscriber's `asyncEnd`/`error` handlers can read it.\n *\n * Node passes `@sentry/opentelemetry/tracing-channel`, which uses `bindStore` to additionally make\n * the span the active OTel context for the duration of the traced operation. That is what makes\n * nested AI SDK operations (model calls, tool calls) become children of the enclosing span without\n * any manual parent bookkeeping here.\n */\nexport type VercelAiTracingChannelFactory = <T extends object>(name: string) => TracingChannel<T, T>;\n\n/**\n * The call that `recordInputs`/`recordOutputs` decide on, and that the span hooks get: one span, with the AI SDK\n * telemetry event as published.\n */\nexport interface VercelAiCallInfo {\n /** The channel event type, such as `generateText`, `languageModelCall` or `executeTool`. */\n type: ChannelEventType;\n /** The AI SDK telemetry event of the call. */\n event: Record<string, unknown>;\n}\n\n/**\n * Integration options, pinned at subscribe time so we never look the integration up per event. `onSpanEnd` gets the\n * AI SDK result of the call as `response`; for streams it is `undefined`.\n */\nexport type VercelAiChannelOptions = GenAiCallOptions<VercelAiCallInfo> & GenAiSpanHooks<VercelAiCallInfo>;\n\n// The integration-level decision of each span, made at span start in the caller's async context. The rest of the\n// precedence (eve mode, the per-call flags, `dataCollection.genAI`) is applied when it is needed, because whether\n// `ai` withheld the result is only known at span end.\nconst integrationRecordingBySpan = new WeakMap<Span, GenAiOptions>();\n\n// `ai` >= 7.0.163 publishes no channel `result` for calls with `recordInputs`/`recordOutputs: false`. These stay\n// here rather than on the shared channel message, which other subscribers can read.\nexport const fallbackChannelResults = new WeakMap<Span, unknown>();\n\nconst spanEndHooks = new WeakMap<Span, (result: GenAiSpanResult<unknown>) => void>();\n\n/** Runs the `onSpanEnd` hook of a span that `createSpanFromMessage` started. Call it right before the span ends. */\nexport function runVercelAiSpanEnd(span: Span, result: GenAiSpanResult<unknown>): void {\n spanEndHooks.get(span)?.(result);\n}\n\n/**\n * Subscribe Sentry span handlers to the `ai` SDK's native telemetry tracing channel (`ai:telemetry`,\n * available in `ai` >= 7) and emit fully-formed `gen_ai.*` spans directly — no OpenTelemetry span\n * post-processing involved.\n *\n * The integration passes its options in directly (rather than us looking the integration up on every\n * event); the global `dataCollection.genAI` default is still read from the client per event.\n *\n * Safe to always call: on `ai` versions that don't publish to the channel (e.g. < 7) nothing is\n * ever emitted and this is inert, so there is no double-instrumentation against the OTel-based\n * patcher. The integration's `setupOnce` guarantees this runs a single time.\n */\nexport function subscribeVercelAiTracingChannel(\n tracingChannel: VercelAiTracingChannelFactory,\n options: VercelAiChannelOptions = {},\n): void {\n bindTracingChannelToSpan(\n tracingChannel<VercelAiChannelMessage>(AI_SDK_TELEMETRY_TRACING_CHANNEL),\n data => createSpanFromMessage(data, options),\n {\n // The helper ends the span; we enrich it from the settled result first (tokens, output messages,\n // finish reasons, response model/id, provider metadata) and drop the per-operation `callId` maps.\n beforeSpanEnd: (span, data) => {\n enrichSpanOnEnd(span, data);\n runVercelAiSpanEnd(\n span,\n 'error' in data ? { error: data.error } : { response: getNonStreamResult(span, data) },\n );\n // The result can hold the provider request and response bodies, and spans outlive the call.\n fallbackChannelResults.delete(span);\n clearOperationId(data);\n },\n // A streamed model call resolves before its stream is drained, so we tap the stream, keep the\n // span open, and end it (via `end`) once the final usage/finish/output chunks arrive.\n deferSpanEnd: ({ span, data, end }) => deferStreamedModelCallEnd(span, data, end),\n },\n );\n}\n\nfunction getNonStreamResult(span: Span, data: VercelAiChannelMessage): unknown {\n const result = fallbackChannelResults.get(span) ?? data.result;\n return isObjectLike(result) && isReadableStream(result.stream) ? undefined : result;\n}\n\n/**\n * When a `languageModelCall` resolves to a live `ReadableStream`, defer ending its span: swap in a\n * passthrough that forwards chunks to the SDK untouched while aggregating usage/finish/output, then\n * enrich and end the span once the stream settles. Returns `false` for anything that isn't a streamed\n * model call so the helper ends the span as usual.\n */\nfunction deferStreamedModelCallEnd(span: Span, data: VercelAiChannelMessage, end: (error?: unknown) => void): boolean {\n const result = fallbackChannelResults.get(span) ?? data.result;\n if (data.type !== 'languageModelCall' || !isObjectLike(result)) {\n return false;\n }\n const stream = result.stream;\n if (!isReadableStream(stream)) {\n return false;\n }\n\n const callId = asString(data.event.callId);\n const invokeAgentSpan = callId ? invokeAgentSpanByCallId.get(callId) : undefined;\n const { recordOutputs } = getRecordingOptions(\n data.event,\n invokeAgentSpan && integrationRecordingBySpan.get(invokeAgentSpan),\n data.result === undefined,\n );\n result.stream = tapModelCallStream(\n span,\n stream,\n final => {\n // Reshape the aggregate into the result `enrichSpanOnEnd` expects, then let `end` run it (it calls\n // `beforeSpanEnd`). Enriching the model-call span and the parent from the same aggregate keeps\n // streamed and non-streamed spans identical.\n fallbackChannelResults.set(span, { ...result, ...streamedResultToChannelResult(final) });\n end();\n if (invokeAgentSpan) {\n enrichInvokeAgentFromStream(invokeAgentSpan, final, recordOutputs);\n }\n },\n error => end(error),\n );\n\n return true;\n}\n\n/** Map the tapped stream aggregate onto the `languageModelCall` result shape `enrichSpanOnEnd` reads. */\nexport function streamedResultToChannelResult(final: StreamedModelCallResult): Record<string, unknown> {\n const content: Array<Record<string, unknown>> = [];\n if (final.text) {\n content.push({ type: 'text', text: final.text });\n }\n for (const toolCall of final.toolCalls) {\n content.push({ type: 'tool-call', ...toolCall });\n }\n\n return {\n content,\n ...(final.usage !== undefined ? { usage: final.usage } : {}),\n ...(final.finishReason !== undefined ? { finishReason: final.finishReason } : {}),\n ...(final.providerMetadata !== undefined ? { providerMetadata: final.providerMetadata } : {}),\n ...(final.responseId || final.responseModel\n ? {\n response: {\n ...(final.responseId ? { id: final.responseId } : {}),\n ...(final.responseModel ? { modelId: final.responseModel } : {}),\n },\n }\n : {}),\n };\n}\n\n/**\n * Propagate a streamed model call's usage (summed across the operation's model calls) and output onto\n * the enclosing `invoke_agent` span, which has no channel result of its own. Runs before that span ends\n * because the operation's completion promise settles only after every model-call stream has drained.\n */\nfunction enrichInvokeAgentFromStream(span: Span, final: StreamedModelCallResult, recordOutputs: boolean): void {\n const usage = isObjectLike(final.usage) ? final.usage : undefined;\n if (usage) {\n const input = tokenCount(usage.inputTokens) ?? tokenCount(usage.promptTokens) ?? tokenCount(usage.tokens);\n const output = tokenCount(usage.outputTokens) ?? tokenCount(usage.completionTokens);\n addTokensToSpan(span, GEN_AI_USAGE_INPUT_TOKENS, input);\n addTokensToSpan(span, GEN_AI_USAGE_OUTPUT_TOKENS, output);\n addTokensToSpan(span, GEN_AI_USAGE_TOTAL_TOKENS, tokenCount(usage.totalTokens) ?? sum(input, output));\n const { cacheRead, cacheWrite } = cacheTokens(usage);\n addTokensToSpan(span, GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS, cacheRead);\n addTokensToSpan(span, GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS, cacheWrite);\n }\n\n if (recordOutputs) {\n const parts = partsFromTextAndToolCalls(final.text, final.toolCalls);\n const outputMessages = buildOutputMessages(parts, getFinishReason({ finishReason: final.finishReason }));\n if (outputMessages) {\n span.setAttribute(GEN_AI_OUTPUT_MESSAGES, outputMessages);\n }\n }\n}\n\n/** Add `value` into a span's numeric token attribute, using the span itself as the running sum. */\nfunction addTokensToSpan(span: Span, attribute: string, value: number | undefined): void {\n if (value === undefined) {\n return;\n }\n const current = spanToJSON(span).attributes[attribute];\n span.setAttribute(attribute, (typeof current === 'number' ? current : 0) + value);\n}\n\n/**\n * Transform a channel `start` payload into the span that should be active for the operation. For\n * `step` we deliberately don't open a span (model calls and tool calls are siblings under the\n * invoke_agent span, matching the OTel-based output), so we reuse the active span and mark the\n * payload to skip ending it.\n */\nexport function createSpanFromMessage(\n data: VercelAiChannelMessage,\n channelOptions: VercelAiChannelOptions,\n): Span | undefined {\n const { type, event } = data;\n\n if (type === 'step' || !event || typeof event !== 'object') {\n // Opt out: returning `undefined` leaves the enclosing `invoke_agent` span as the active context\n // (model-call and tool-call events nest under it) without opening — or ending — a span of its own.\n return undefined;\n }\n\n const call: VercelAiCallInfo = { type, event };\n const integrationRecording: GenAiOptions = {\n recordInputs: resolveRecordingOption(channelOptions.recordInputs, call),\n recordOutputs: resolveRecordingOption(channelOptions.recordOutputs, call),\n };\n const span = startSpanFromEvent(type, event, getRecordingOptions(event, integrationRecording).recordInputs);\n if (span) {\n integrationRecordingBySpan.set(span, integrationRecording);\n runGenAiSpanStart(channelOptions, span, call);\n spanEndHooks.set(span, result => runGenAiSpanEnd(channelOptions, span, call, result));\n }\n return span;\n}\n\nfunction startSpanFromEvent(\n type: ChannelEventType,\n event: Record<string, unknown>,\n recordInputs: boolean,\n): Span | undefined {\n const provider = asString(event.provider);\n const modelId = asString(event.modelId);\n const callId = asString(event.callId);\n const maxRetries = asNumber(event.maxRetries);\n\n // Harvest tool descriptions from the operation/model-call `tools` so tool spans can backfill them.\n // Gated on `recordInputs` to match the OTel path, which only records `tool.definitions` then.\n if (recordInputs) {\n recordToolDescriptions(callId, event.tools);\n }\n\n // Only an operation's start event carries `providerOptions`; its model-call and tool events start\n // while the operation span is active, so they inherit the id from it. A root operation never\n // inherits, so a nested call (e.g. inside a tool's `execute`) is not folded into the outer conversation.\n const conversationId =\n getOpenAiConversationId(event.providerOptions) ??\n (ROOT_OPERATION_TYPES.has(type) ? undefined : getActiveSpanConversationId());\n\n const runtimeContextAttributes =\n (callId ? runtimeContextAttributesByCallId.get(callId) : undefined) ??\n contextAttributes(event, event.runtimeContext, VERCEL_AI_SETTINGS_CONTEXT_KEY_BASE);\n if (callId && ROOT_OPERATION_TYPES.has(type)) {\n runtimeContextAttributesByCallId.set(callId, runtimeContextAttributes);\n }\n\n const baseAttributes: SpanAttributes = {\n [SENTRY_ORIGIN]: ORIGIN,\n ...telemetryMetadataAttributes(event.telemetryMetadata),\n ...runtimeContextAttributes,\n [GEN_AI_PROVIDER_NAME]: provider,\n [VERCEL_AI_MODEL_PROVIDER_ATTRIBUTE]: provider,\n [GEN_AI_REQUEST_MODEL]: modelId,\n [VERCEL_AI_SETTINGS_MAX_RETRIES_ATTRIBUTE]: maxRetries,\n [GEN_AI_CONVERSATION_ID]: conversationId,\n };\n\n switch (type) {\n case 'generateText':\n case 'streamText':\n case 'generateObject':\n case 'streamObject':\n // The object variants' operationId rides on `event.operationId`. The JSON-schema attribute the OTel\n // path derives from the SDK's Zod schema is not reconstructed on the channel path.\n return buildInvokeAgentSpan(\n event,\n baseAttributes,\n recordInputs,\n callId,\n type === 'streamText' || type === 'streamObject',\n );\n case 'languageModelCall':\n _INTERNAL_skipAiProviderWrapping([WORKERS_AI_INTEGRATION_NAME]);\n\n return buildModelCallSpan(event, baseAttributes, recordInputs, callId, modelId);\n case 'executeTool':\n return buildToolSpan(event, recordInputs, conversationId, runtimeContextAttributes);\n case 'embed':\n case 'embedMany': {\n // `embed` carries a single `value`; `embedMany` a `values` array — both map to the embeddings input.\n const input = type === 'embedMany' ? event.values : event.value;\n return startGenAiSpan('embeddings', modelId, {\n ...baseAttributes,\n ...(recordInputs && !isStrippedInput(input) ? { [GEN_AI_EMBEDDINGS_INPUT]: stringify(input) } : {}),\n });\n }\n case 'rerank':\n return startGenAiSpan('rerank', modelId, baseAttributes);\n // `ai` 7.0.128 renamed `experimental_evaluate` to `experimental_decide`; older 7.x still publishes the old name.\n case 'experimental_evaluate':\n case 'experimental_decide':\n return startGenAiSpan('decide', modelId, {\n ...baseAttributes,\n ...(recordInputs && !(isStrippedInput(event.state) && isStrippedInput(event.questions))\n ? {\n [GEN_AI_INPUT_MESSAGES]: stringify([\n { type: 'evaluation', state: event.state, questions: event.questions },\n ]),\n }\n : {}),\n });\n case 'experimental_extract':\n return startGenAiSpan('extract', modelId, {\n ...baseAttributes,\n ...(recordInputs && !(isStrippedInput(event.state) && isStrippedInput(event.fields))\n ? {\n [GEN_AI_INPUT_MESSAGES]: stringify([\n {\n ...toExtractState(event.state).request,\n fields: toExtractFields(event.fields),\n reference_date: event.referenceDate,\n },\n ]),\n }\n : {}),\n });\n default:\n // Unknown event type: opt out rather than open a span we can't shape correctly.\n return undefined;\n }\n}\n\n/**\n * `experimental_telemetry.metadata` (`ai` <= 6) as `vercel.ai.telemetry.metadata.<key>`, the names the OTel\n * integration produced from the SDK's `ai.telemetry.metadata.*`. Only the orchestrion adapter sets\n * `event.telemetryMetadata`; `ai` 7 has no `telemetry.metadata`.\n */\nfunction telemetryMetadataAttributes(metadata: unknown): Record<string, string> {\n const attributes: Record<string, string> = {};\n if (isObjectLike(metadata)) {\n for (const [key, value] of Object.entries(metadata)) {\n if (value === null || value === undefined) continue;\n attributes[`${VERCEL_AI_TELEMETRY_METADATA_ATTRIBUTE_PREFIX}${key}`] = String(value);\n }\n }\n return attributes;\n}\n\n/**\n * One string attribute per context key, as `<prefix><key>`. `ai` < 7.0.114 published the full context to the\n * channel, ignoring `telemetry.includeRuntimeContext`/`includeToolsContext`, and a filtered context\n * looks the same as an unfiltered one. `aiVersion` (added in 7.0.154) is the only reliable sign that\n * the AI SDK filtered it, so without it we record nothing.\n */\nfunction contextAttributes(event: Record<string, unknown>, context: unknown, keyBase: string): SpanAttributes {\n const attributes: SpanAttributes = {};\n if (typeof event.aiVersion !== 'string' || !isObjectLike(context)) {\n return attributes;\n }\n for (const [key, value] of Object.entries(context)) {\n const attributeValue = stringify(value);\n if (value !== null && attributeValue !== undefined) {\n attributes[`${keyBase}.${key}`] = attributeValue;\n }\n }\n return attributes;\n}\n\n/** Start a `gen_ai.<operation>` span named `<operation> <suffix>` (or just `<operation>` when no suffix). */\nfunction startGenAiSpan(operation: GenAiOperation, suffix: string | undefined, attributes: SpanAttributes): Span {\n return startInactiveSpan({\n name: suffix ? `${operation} ${suffix}` : operation,\n attributes: {\n [SENTRY_OP]: GEN_AI_OPERATION_SPAN_OPS[operation],\n [GEN_AI_OPERATION_NAME]: operation,\n ...attributes,\n },\n });\n}\n\nfunction buildInvokeAgentSpan(\n event: Record<string, unknown>,\n baseAttributes: SpanAttributes,\n recordInputs: boolean,\n callId: string | undefined,\n isStream: boolean,\n): Span {\n const functionId = asString(event.functionId);\n const operationId = asString(event.operationId) ?? (isStream ? 'ai.streamText' : 'ai.generateText');\n if (callId) {\n operationIdByCallId.set(callId, { operationId, isStream });\n }\n const span = startGenAiSpan('invoke_agent', functionId, {\n ...baseAttributes,\n [VERCEL_AI_OPERATION_ID_ATTRIBUTE]: operationId,\n [GEN_AI_RESPONSE_STREAMING]: isStream,\n [GEN_AI_FUNCTION_ID]: functionId,\n ...(recordInputs ? buildInputMessageAttributes(event) : {}),\n });\n if (isStream && callId) {\n invokeAgentSpanByCallId.set(callId, span);\n }\n\n return span;\n}\n\nfunction buildModelCallSpan(\n event: Record<string, unknown>,\n baseAttributes: SpanAttributes,\n recordInputs: boolean,\n callId: string | undefined,\n modelId: string | undefined,\n): Span {\n const parent = callId ? operationIdByCallId.get(callId) : undefined;\n const operationId = parent\n ? `${parent.operationId}.${parent.isStream ? 'doStream' : 'doGenerate'}`\n : 'ai.generateText.doGenerate';\n return startGenAiSpan('generate_content', modelId, {\n ...baseAttributes,\n [VERCEL_AI_OPERATION_ID_ATTRIBUTE]: operationId,\n ...(recordInputs ? buildInputMessageAttributes(event) : {}),\n ...(recordInputs && Array.isArray(event.tools) ? { [GEN_AI_TOOL_DEFINITIONS]: stringify(event.tools) } : {}),\n });\n}\n\nfunction buildToolSpan(\n event: Record<string, unknown>,\n recordInputs: boolean,\n conversationId: string | undefined,\n runtimeContextAttributes: SpanAttributes,\n): Span {\n const toolCall = isObjectLike(event.toolCall) ? event.toolCall : {};\n const toolName = asString(toolCall.toolName);\n const toolCallId = asString(event.toolCallId) ?? asString(toolCall.toolCallId);\n const toolInput = toolCall.input ?? toolCall.args;\n // The `executeTool` event has no description; backfill it from the operation's recorded tools.\n // Gated on `recordInputs` to match the OTel path (descriptions come from the recorded tools list).\n const description =\n recordInputs && toolName ? resolveToolDescription(asString(event.callId), toolName, event.tools) : undefined;\n return startGenAiSpan('execute_tool', toolName, {\n [SENTRY_ORIGIN]: ORIGIN,\n ...runtimeContextAttributes,\n ...contextAttributes(event, event.toolContext, VERCEL_AI_TOOL_CALL_CONTEXT_KEY_BASE),\n [GEN_AI_TOOL_NAME]: toolName,\n [GEN_AI_TOOL_CALL_ID_ATTRIBUTE]: toolCallId,\n [GEN_AI_TOOL_DESCRIPTION]: description,\n ...(recordInputs && toolInput !== undefined ? { [GEN_AI_TOOL_CALL_ARGUMENTS]: stringify(toolInput) } : {}),\n [GEN_AI_CONVERSATION_ID]: conversationId,\n });\n}\n\n/**\n * Best-effort enrichment from the resolved value the AI SDK attaches to the channel context.\n * Everything here is guarded: when a field is missing or the shape differs across `ai` versions,\n * we simply don't set the attribute rather than emit a malformed span.\n */\nexport function enrichSpanOnEnd(span: Span, data: VercelAiChannelMessage): void {\n const { type } = data;\n const result = fallbackChannelResults.get(span) ?? data.result;\n if (!isObjectLike(result)) {\n return;\n }\n\n const { recordOutputs } = getRecordingOptions(\n data.event,\n integrationRecordingBySpan.get(span),\n data.result === undefined,\n );\n\n if (type === 'executeTool') {\n // From V5 on, tool errors are not rejected (so the `error` channel verb never fires) — they\n // surface as `tool-error` content on the resolved result. Mirror the OTel path by marking the\n // span and capturing the error, which carry the failure instead of the result attribute.\n const output = isObjectLike(result.output) ? result.output : undefined;\n if (output?.type === 'tool-error') {\n captureToolError(span, data, output.error);\n } else if (recordOutputs) {\n span.setAttribute(GEN_AI_TOOL_CALL_RESULT, stringify(result.output ?? result));\n }\n return;\n }\n\n // `languageModelCall` results report usage as `{ total }` objects; top-level/step results report\n // flat numbers. `tokenCount` handles both. v4 names tokens `promptTokens`/`completionTokens`\n // (v5+ uses `inputTokens`/`outputTokens`); the fallbacks are `undefined`-inert on v5+.\n const usage = isObjectLike(result.usage) ? result.usage : undefined;\n if (usage) {\n const inputTokens = tokenCount(usage.inputTokens) ?? tokenCount(usage.promptTokens) ?? tokenCount(usage.tokens);\n const outputTokens = tokenCount(usage.outputTokens) ?? tokenCount(usage.completionTokens);\n const totalTokens = tokenCount(usage.totalTokens) ?? sum(inputTokens, outputTokens);\n if (inputTokens !== undefined) {\n span.setAttribute(GEN_AI_USAGE_INPUT_TOKENS, inputTokens);\n }\n if (outputTokens !== undefined) {\n span.setAttribute(GEN_AI_USAGE_OUTPUT_TOKENS, outputTokens);\n }\n if (totalTokens !== undefined) {\n span.setAttribute(GEN_AI_USAGE_TOTAL_TOKENS, totalTokens);\n }\n setCacheTokens(span, usage);\n }\n\n // Match the OTel integration: finish reasons live on the model-call (`generate_content`) span, not\n // on the top-level `invoke_agent` span.\n const finishReason = getFinishReason(result);\n if (finishReason && type === 'languageModelCall') {\n span.setAttribute(GEN_AI_RESPONSE_FINISH_REASONS, stringify([finishReason]));\n }\n\n const response = isObjectLike(result.response) ? result.response : undefined;\n const responseId = asString(response?.id) ?? asString(result.responseId);\n if (responseId) {\n span.setAttribute(GEN_AI_RESPONSE_ID, responseId);\n }\n const responseModel = asString(response?.modelId) ?? asString(data.event.modelId);\n if (responseModel) {\n span.setAttribute(GEN_AI_RESPONSE_MODEL, responseModel);\n }\n\n // Provider-specific cache/reasoning/prediction token breakdowns. The channel exposes `providerMetadata`\n // as an object (the OTel path parses it from a string); both share `getProviderMetadataAttributes` so\n // the emitted shape is identical.\n const providerMetadata = (result as { providerMetadata?: unknown }).providerMetadata;\n const providerAttributes = getProviderMetadataAttributes(providerMetadata);\n dropLastStepOnlyUsage(providerAttributes, type);\n span.setAttributes(providerAttributes);\n\n if (recordOutputs) {\n const outputMessages = getOutputMessages(type, result, finishReason, data.event);\n if (outputMessages) {\n span.setAttribute(GEN_AI_OUTPUT_MESSAGES, outputMessages);\n }\n }\n}\n\nfunction getOutputMessages(\n type: ChannelEventType,\n result: Record<string, unknown>,\n finishReason: string | undefined,\n event: Record<string, unknown>,\n): string | undefined {\n if (type === 'experimental_evaluate' || type === 'experimental_decide') {\n return getEvaluationOutputMessages(withProviderAnswerFields(result));\n }\n if (type === 'experimental_extract') {\n return isObjectLike(result.answers)\n ? stringify([{ answers: toExtractAnswers(result.answers, toExtractState(event.state).parts) }])\n : undefined;\n }\n // `languageModelCall` exposes the response as a `content` parts array; top-level results expose\n // `text` + `toolCalls`. Both normalize into the OTel `gen_ai.output.messages` assistant message.\n const parts =\n type === 'languageModelCall' && Array.isArray(result.content)\n ? partsFromContent(result.content)\n : partsFromTextAndToolCalls(result.text, result.toolCalls);\n return buildOutputMessages(parts, finishReason);\n}\n\n/**\n * Providers move answer fields into `providerMetadata`: TypeSafe and OpenAI as `<provider>.confidence[id]`,\n * OpenRouter as `openrouter.answers[id].{confidence,legend}`. Put them back on the answers.\n */\nfunction withProviderAnswerFields(result: Record<string, unknown>): unknown {\n const { answers, providerMetadata } = result;\n if (!isObjectLike(answers) || !isObjectLike(providerMetadata)) {\n return answers;\n }\n const confidenceById = [providerMetadata.typesafe, providerMetadata.openai]\n .map(metadata => (isObjectLike(metadata) ? metadata.confidence : undefined))\n .find(isObjectLike);\n const { openrouter } = providerMetadata;\n const openrouterById = isObjectLike(openrouter) && isObjectLike(openrouter.answers) ? openrouter.answers : undefined;\n if (!confidenceById && !openrouterById) {\n return answers;\n }\n\n return mapObjectValues(answers, (answer, id) => {\n const openrouterAnswer = openrouterById?.[id];\n const fields = isObjectLike(openrouterAnswer) ? openrouterAnswer : {};\n const {\n confidence = asNumber(confidenceById?.[id]) ?? asNumber(fields.confidence),\n legend = isObjectLike(fields.legend) ? fields.legend : undefined,\n } = answer;\n return { ...answer, confidence, legend };\n });\n}\n\n/** Maps a Vercel AI finish reason to the OTel `gen_ai.output.messages` form (`tool-calls` → `tool_call`). */\nfunction normalizeFinishReason(finishReason: string | undefined): string {\n return finishReason === 'tool-calls' ? 'tool_call' : (finishReason ?? 'stop');\n}\n\n/** Reads the finish reason from a result — a string on top-level results, `{ unified }` on model calls. */\nfunction getFinishReason(result: Record<string, unknown>): string | undefined {\n const finishReason = result.finishReason;\n if (typeof finishReason === 'string') {\n return finishReason;\n }\n return isObjectLike(finishReason) ? asString(finishReason.unified) : undefined;\n}\n\n/** Reads a token count that may be a plain number or a `{ total }` object (model-call usage). */\nfunction tokenCount(value: unknown): number | undefined {\n return asNumber(value) ?? (isObjectLike(value) ? asNumber(value.total) : undefined);\n}\n\n/**\n * Cache token counts as the AI SDK normalizes them: v5 `cachedInputTokens`, v6 `inputTokenDetails`,\n * v7 `inputTokens.{cacheRead,cacheWrite}`.\n */\nfunction setCacheTokens(span: Span, usage: Record<string, unknown>): void {\n const { cacheRead, cacheWrite } = cacheTokens(usage);\n if (cacheRead !== undefined) {\n span.setAttribute(GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS, cacheRead);\n }\n if (cacheWrite !== undefined) {\n span.setAttribute(GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS, cacheWrite);\n }\n}\n\nfunction cacheTokens(usage: Record<string, unknown>): { cacheRead?: number; cacheWrite?: number } {\n const inputTokens = isObjectLike(usage.inputTokens) ? usage.inputTokens : undefined;\n const inputTokenDetails = isObjectLike(usage.inputTokenDetails) ? usage.inputTokenDetails : undefined;\n return {\n cacheRead:\n asNumber(inputTokens?.cacheRead) ??\n asNumber(inputTokenDetails?.cacheReadTokens) ??\n asNumber(usage.cachedInputTokens),\n cacheWrite: asNumber(inputTokens?.cacheWrite) ?? asNumber(inputTokenDetails?.cacheWriteTokens),\n };\n}\n\nfunction buildOutputMessages(\n parts: Array<Record<string, unknown>>,\n finishReason: string | undefined,\n): string | undefined {\n if (!parts.length) {\n return undefined;\n }\n return stringify([{ role: 'assistant', parts, finish_reason: normalizeFinishReason(finishReason) }]);\n}\n\nfunction toolCallPart(toolCall: Record<string, unknown>): Record<string, unknown> {\n const args = toolCall.input ?? toolCall.args;\n return {\n type: 'tool_call',\n id: asString(toolCall.toolCallId),\n name: asString(toolCall.toolName),\n arguments: typeof args === 'string' ? args : stringify(args ?? {}),\n };\n}\n\nfunction partsFromContent(content: unknown[]): Array<Record<string, unknown>> {\n const parts: Array<Record<string, unknown>> = [];\n for (const item of content) {\n if (!isObjectLike(item)) {\n continue;\n }\n if (item.type === 'text' && typeof item.text === 'string') {\n parts.push({ type: 'text', content: item.text });\n } else if (item.type === 'tool-call') {\n parts.push(toolCallPart(item));\n }\n }\n return parts;\n}\n\nfunction partsFromTextAndToolCalls(text: unknown, toolCalls: unknown): Array<Record<string, unknown>> {\n const parts: Array<Record<string, unknown>> = [];\n if (typeof text === 'string' && text.length) {\n parts.push({ type: 'text', content: text });\n }\n if (Array.isArray(toolCalls)) {\n for (const toolCall of toolCalls) {\n if (isObjectLike(toolCall)) {\n parts.push(toolCallPart(toolCall));\n }\n }\n }\n return parts;\n}\n\nexport function captureToolError(span: Span, data: VercelAiChannelMessage, error: unknown): void {\n span.setStatus({\n code: SPAN_STATUS_ERROR,\n message: error instanceof Error ? error.message : 'tool_error',\n });\n\n const toolCall = isObjectLike(data.event.toolCall) ? data.event.toolCall : {};\n const toolName = asString(toolCall.toolName);\n const toolCallId = asString(data.event.toolCallId) ?? asString(toolCall.toolCallId);\n\n withScope(scope => {\n scope.setContext('trace', spanToTraceContext(span));\n if (toolName) {\n scope.setTag('vercel.ai.tool.name', toolName);\n }\n if (toolCallId) {\n scope.setTag('vercel.ai.tool.callId', toolCallId);\n }\n scope.setLevel('error');\n captureException(\n error instanceof Error ? error : new Error(typeof error === 'string' ? error : 'Tool execution failed'),\n {\n mechanism: { type: 'auto.ai.vercelai', handled: false },\n },\n );\n });\n}\n\nfunction getRecordingOptions(\n event: Record<string, unknown>,\n integrationRecording: GenAiOptions = {},\n channelWithheldResult = false,\n): {\n recordInputs: boolean;\n recordOutputs: boolean;\n} {\n const client = getClient();\n const genAI = client?.getDataCollectionOptions().genAI;\n // `ai` withheld the result because of the per-call flag, which eve >= 1.0.0-rc.10 sets from trace policies, so\n // the flag is a content decision there rather than eve's blanket default.\n const eveMode = client && !channelWithheldResult ? isEveGenAiRecordingDefault(client) : false;\n\n return {\n recordInputs: resolveRecording(integrationRecording.recordInputs, event.recordInputs, genAI?.inputs, eveMode),\n recordOutputs: resolveRecording(integrationRecording.recordOutputs, event.recordOutputs, genAI?.outputs, eveMode),\n };\n}\n\n/**\n * Mirrors the OTel integration's `determineRecordingSettings` precedence: an integration-level option\n * wins, then the per-call `experimental_telemetry.recordInputs/recordOutputs` flag the AI SDK forwards\n * on the channel event, then the global `dataCollection.genAI` default.\n *\n * NOTE: the OTel integration also defaults recording to `true` for a call with\n * `experimental_telemetry: { isEnabled: true }`. The `ai:telemetry` channel does not expose `isEnabled`\n * (nor a resolved recording flag), so that per-call default cannot be reproduced here — v7 users who\n * want inputs/outputs recorded must enable `dataCollection.genAI` or set `recordInputs`/`recordOutputs`.\n *\n * Under `eveMode` (set by `eveIntegration()`) the per-call flag is eve's blanket framework default\n * rather than an end-user decision, so it is skipped: an explicit `dataCollection.genAI` still wins,\n * otherwise recording defaults to `true`. An integration-level option outranks both regardless.\n */\nfunction resolveRecording(\n integrationOption: unknown,\n perCallOption: unknown,\n globalDefault: unknown,\n eveMode = false,\n): boolean {\n if (typeof integrationOption === 'boolean') {\n return integrationOption;\n }\n if (eveMode) {\n return typeof globalDefault === 'boolean' ? globalDefault : true;\n }\n if (typeof perCallOption === 'boolean') {\n return perCallOption;\n }\n return globalDefault === true;\n}\n\n/** `ai` >= 7.0.163 replaces inputs with empty values when `recordInputs` is false. */\nfunction isStrippedInput(input: unknown): boolean {\n return (\n input === undefined ||\n input === '' ||\n (Array.isArray(input) && !input.length) ||\n (isPlainObject(input) && !Object.keys(input).length)\n );\n}\n\n/** The `ai` SDK accepts the system prompt as `string | SystemModelMessage | SystemModelMessage[]`. */\nfunction getSystemInstructionParts(instructions: unknown): { type: 'text'; content: string }[] {\n const messages = Array.isArray(instructions) ? instructions : [instructions];\n return messages.flatMap(message => {\n const content = asString(isObjectLike(message) ? message.content : message);\n return content ? [{ type: 'text' as const, content }] : [];\n });\n}\n\nfunction buildInputMessageAttributes(event: Record<string, unknown>): Record<string, string | number | undefined> {\n const attributes: Record<string, string | number | undefined> = {};\n\n // `ai` >= 7 forbids system messages in `messages`/`prompt` and exposes the system prompt as a\n // separate `instructions` field. The OTel path lifts the system message out of the prompt into\n // `gen_ai.system_instructions` as `[{ type: 'text', content }]`; mirror that shape here.\n const instructions = getSystemInstructionParts(event.instructions);\n if (instructions.length) {\n attributes[GEN_AI_SYSTEM_INSTRUCTIONS] = stringify(instructions);\n }\n\n // The AI SDK start events extend `StandardizedPrompt`; messages live on `messages`, otherwise the\n // simpler `prompt` field is used.\n const messages = event.messages ?? event.prompt;\n if (!isStrippedInput(messages)) {\n attributes[GEN_AI_INPUT_MESSAGES] = stringify(messages);\n }\n\n return attributes;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA0FA,MAAa,mCAAmC;AAEhD,MAAM,SAAS;AAGf,MAAM,4BAA4B;CAChC,YAAY;CAIZ,QAAQ;CACR,QAAQ;CACR,SAAS;CACT,cAAc;CACd,cAAc;CAGd,kBAAkB;AACpB;AAKA,MAAM,mCAAmC;AACzC,MAAM,qCAAqC;AAC3C,MAAM,2CAA2C;AACjD,MAAM,gDAAgD;AAMtD,MAAM,sCAAsB,IAAI,IAAwD;AASxF,MAAM,2CAA2B,IAAI,IAAiC;AAMtE,MAAM,0CAA0B,IAAI,IAAkB;AAItD,MAAM,mDAAmC,IAAI,IAA4B;AAIzE,MAAM,uCAAuB,IAAI,IAAsB;CACrD;CACA;CACA;CACA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,6 +1,6 @@
1
1
  import { DEBUG_BUILD } from "../debug-build.js";
2
2
  import { SENTRY_ORIGIN } from "@sentry/conventions/attributes";
3
- import { _INTERNAL_captureLog, debug, isObjectLike } from "@sentry/core";
3
+ import { captureLogEvent, debug, isObjectLike } from "@sentry/core";
4
4
  // src/integrations/winston.ts
5
5
  const DEFAULT_CAPTURED_LEVELS = [
6
6
  "trace",
@@ -56,7 +56,7 @@ function createSentryWinstonTransport(TransportClass, sentryWinstonOptions) {
56
56
  const customLevel = sentryWinstonOptions?.customLevelMap?.[levelFromSymbol];
57
57
  const winstonLogLevel = WINSTON_LEVEL_TO_LOG_SEVERITY_LEVEL_MAP[levelFromSymbol];
58
58
  const logSeverityLevel = customLevel ?? winstonLogLevel ?? "info";
59
- if (this._levels.has(logSeverityLevel)) _INTERNAL_captureLog({
59
+ if (this._levels.has(logSeverityLevel)) captureLogEvent({
60
60
  level: logSeverityLevel,
61
61
  message,
62
62
  attributes: {
@@ -1 +1 @@
1
- {"version":3,"file":"winston.js","names":[],"sources":["../../../src/integrations/winston.ts"],"sourcesContent":["import { SENTRY_ORIGIN } from '@sentry/conventions/attributes';\n/* eslint-disable @typescript-eslint/ban-ts-comment */\nimport type { LogSeverityLevel } from '@sentry/core';\nimport { _INTERNAL_captureLog, debug, isObjectLike } from '@sentry/core';\nimport { DEBUG_BUILD } from '../debug-build';\n\nconst DEFAULT_CAPTURED_LEVELS: Array<LogSeverityLevel> = ['trace', 'debug', 'info', 'warn', 'error', 'fatal'];\n\n// See: https://github.com/winstonjs/triple-beam\nconst LEVEL_SYMBOL = Symbol.for('level');\nconst MESSAGE_SYMBOL = Symbol.for('message');\nconst SPLAT_SYMBOL = Symbol.for('splat');\n\n/**\n * Options for the Sentry Winston transport.\n */\ninterface WinstonTransportOptions {\n /**\n * Use this option to filter which levels should be captured. By default, all levels are captured.\n *\n * @example\n * ```ts\n * const SentryWinstonTransport = Sentry.createSentryWinstonTransport(Transport, {\n * // Only capture error and warn logs\n * levels: ['error', 'warn'],\n * });\n * ```\n */\n levels?: Array<LogSeverityLevel>;\n\n /**\n * Use this option to map custom levels to Sentry log severity levels.\n *\n * @example\n * ```ts\n * const SentryWinstonTransport = Sentry.createSentryWinstonTransport(Transport, {\n * customLevelMap: {\n * myCustomLevel: 'info',\n * customError: 'error',\n * },\n * });\n * ```\n */\n customLevelMap?: Record<string, LogSeverityLevel>;\n}\n\n/**\n * Creates a new Sentry Winston transport that fowards logs to Sentry.\n *\n * Supports Winston 3.x.x.\n *\n * @param TransportClass - The Winston transport class to extend.\n * @returns The extended transport class.\n *\n * @example\n * ```ts\n * const winston = require('winston');\n * const Transport = require('winston-transport');\n *\n * const SentryWinstonTransport = Sentry.createSentryWinstonTransport(Transport);\n *\n * const logger = winston.createLogger({\n * transports: [new SentryWinstonTransport()],\n * });\n * ```\n */\nexport function createSentryWinstonTransport<TransportStreamInstance extends object>(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n TransportClass: new (options?: any) => TransportStreamInstance,\n sentryWinstonOptions?: WinstonTransportOptions,\n): typeof TransportClass {\n // @ts-ignore - We know this is safe because SentryWinstonTransport extends TransportClass\n class SentryWinstonTransport extends TransportClass {\n private _levels: Set<LogSeverityLevel>;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n public constructor(options?: any) {\n super(options);\n this._levels = new Set(sentryWinstonOptions?.levels ?? DEFAULT_CAPTURED_LEVELS);\n }\n\n /**\n * Forwards a winston log to the Sentry SDK.\n */\n public log(info: unknown, callback: () => void): void {\n try {\n setImmediate(() => {\n // @ts-ignore - We know this is safe because SentryWinstonTransport extends TransportClass\n this.emit('logged', info);\n });\n\n if (!isObjectLike(info)) {\n return;\n }\n\n const levelFromSymbol = info[LEVEL_SYMBOL];\n\n // See: https://github.com/winstonjs/winston?tab=readme-ov-file#streams-objectmode-and-info-objects\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { level, message, timestamp, ...attributes } = info;\n // Remove all symbols from the remaining attributes\n attributes[LEVEL_SYMBOL] = undefined;\n attributes[MESSAGE_SYMBOL] = undefined;\n attributes[SPLAT_SYMBOL] = undefined;\n\n const customLevel = sentryWinstonOptions?.customLevelMap?.[levelFromSymbol as string];\n const winstonLogLevel = WINSTON_LEVEL_TO_LOG_SEVERITY_LEVEL_MAP[levelFromSymbol as string];\n const logSeverityLevel = customLevel ?? winstonLogLevel ?? 'info';\n\n if (this._levels.has(logSeverityLevel)) {\n _INTERNAL_captureLog({\n level: logSeverityLevel,\n message: message as string,\n attributes: {\n ...attributes,\n [SENTRY_ORIGIN]: 'auto.log.winston',\n },\n });\n } else if (!customLevel && !winstonLogLevel) {\n DEBUG_BUILD &&\n debug.log(\n `Winston log level ${levelFromSymbol} is not captured by Sentry. Please add ${levelFromSymbol} to the \"customLevelMap\" option of the Sentry Winston transport.`,\n );\n }\n } catch {\n // do nothing\n }\n\n if (callback) {\n callback();\n }\n }\n }\n\n return SentryWinstonTransport as typeof TransportClass;\n}\n\n// npm\n// {\n// error: 0,\n// warn: 1,\n// info: 2,\n// http: 3,\n// verbose: 4,\n// debug: 5,\n// silly: 6\n// }\n//\n// syslog\n// {\n// emerg: 0,\n// alert: 1,\n// crit: 2,\n// error: 3,\n// warning: 4,\n// notice: 5,\n// info: 6,\n// debug: 7,\n// }\nconst WINSTON_LEVEL_TO_LOG_SEVERITY_LEVEL_MAP: Record<string, LogSeverityLevel> = {\n // npm\n silly: 'trace',\n // npm and syslog\n debug: 'debug',\n // npm\n verbose: 'debug',\n // npm\n http: 'debug',\n // npm and syslog\n info: 'info',\n // syslog\n notice: 'info',\n // npm\n warn: 'warn',\n // syslog\n warning: 'warn',\n // npm and syslog\n error: 'error',\n // syslog\n emerg: 'fatal',\n // syslog\n alert: 'fatal',\n // syslog\n crit: 'fatal',\n};\n"],"mappings":";;;;AAMA,MAAM,0BAAmD;CAAC;CAAS;CAAS;CAAQ;CAAQ;CAAS;AAAO;AAG5G,MAAM,eAAe,OAAO,IAAI,OAAO;AACvC,MAAM,iBAAiB,OAAO,IAAI,SAAS;AAC3C,MAAM,eAAe,OAAO,IAAI,OAAO;;;;;;;;;;;;;;;;;;;;;AAuDvC,SAAgB,6BAEd,gBACA,sBACuB;CAEvB,MAAM,+BAA+B,eAAe;EAG3C,YAAY,SAAe;GAChC,MAAM,OAAO;GACb,KAAK,UAAU,IAAI,IAAI,sBAAsB,UAAU,uBAAuB;EAChF;;;;EAKO,IAAI,MAAe,UAA4B;GACpD,IAAI;IACF,mBAAmB;KAEjB,KAAK,KAAK,UAAU,IAAI;IAC1B,CAAC;IAED,IAAI,CAAC,aAAa,IAAI,GACpB;IAGF,MAAM,kBAAkB,KAAK;IAI7B,MAAM,EAAE,OAAO,SAAS,WAAW,GAAG,eAAe;IAErD,WAAW,gBAAgB,KAAA;IAC3B,WAAW,kBAAkB,KAAA;IAC7B,WAAW,gBAAgB,KAAA;IAE3B,MAAM,cAAc,sBAAsB,iBAAiB;IAC3D,MAAM,kBAAkB,wCAAwC;IAChE,MAAM,mBAAmB,eAAe,mBAAmB;IAE3D,IAAI,KAAK,QAAQ,IAAI,gBAAgB,GACnC,qBAAqB;KACnB,OAAO;KACE;KACT,YAAY;MACV,GAAG;OACF,gBAAgB;KACnB;IACF,CAAC;SACI,IAAI,CAAC,eAAe,CAAC,iBAC1B,eACE,MAAM,IACJ,qBAAqB,gBAAgB,yCAAyC,gBAAgB,iEAChG;GAEN,QAAQ,CAER;GAEA,IAAI,UACF,SAAS;EAEb;CACF;CAEA,OAAO;AACT;AAwBA,MAAM,0CAA4E;CAEhF,OAAO;CAEP,OAAO;CAEP,SAAS;CAET,MAAM;CAEN,MAAM;CAEN,QAAQ;CAER,MAAM;CAEN,SAAS;CAET,OAAO;CAEP,OAAO;CAEP,OAAO;CAEP,MAAM;AACR"}
1
+ {"version":3,"file":"winston.js","names":[],"sources":["../../../src/integrations/winston.ts"],"sourcesContent":["import { SENTRY_ORIGIN } from '@sentry/conventions/attributes';\n/* eslint-disable @typescript-eslint/ban-ts-comment */\nimport type { LogSeverityLevel } from '@sentry/core';\nimport { captureLogEvent, debug, isObjectLike } from '@sentry/core';\nimport { DEBUG_BUILD } from '../debug-build';\n\nconst DEFAULT_CAPTURED_LEVELS: Array<LogSeverityLevel> = ['trace', 'debug', 'info', 'warn', 'error', 'fatal'];\n\n// See: https://github.com/winstonjs/triple-beam\nconst LEVEL_SYMBOL = Symbol.for('level');\nconst MESSAGE_SYMBOL = Symbol.for('message');\nconst SPLAT_SYMBOL = Symbol.for('splat');\n\n/**\n * Options for the Sentry Winston transport.\n */\ninterface WinstonTransportOptions {\n /**\n * Use this option to filter which levels should be captured. By default, all levels are captured.\n *\n * @example\n * ```ts\n * const SentryWinstonTransport = Sentry.createSentryWinstonTransport(Transport, {\n * // Only capture error and warn logs\n * levels: ['error', 'warn'],\n * });\n * ```\n */\n levels?: Array<LogSeverityLevel>;\n\n /**\n * Use this option to map custom levels to Sentry log severity levels.\n *\n * @example\n * ```ts\n * const SentryWinstonTransport = Sentry.createSentryWinstonTransport(Transport, {\n * customLevelMap: {\n * myCustomLevel: 'info',\n * customError: 'error',\n * },\n * });\n * ```\n */\n customLevelMap?: Record<string, LogSeverityLevel>;\n}\n\n/**\n * Creates a new Sentry Winston transport that fowards logs to Sentry.\n *\n * Supports Winston 3.x.x.\n *\n * @param TransportClass - The Winston transport class to extend.\n * @returns The extended transport class.\n *\n * @example\n * ```ts\n * const winston = require('winston');\n * const Transport = require('winston-transport');\n *\n * const SentryWinstonTransport = Sentry.createSentryWinstonTransport(Transport);\n *\n * const logger = winston.createLogger({\n * transports: [new SentryWinstonTransport()],\n * });\n * ```\n */\nexport function createSentryWinstonTransport<TransportStreamInstance extends object>(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n TransportClass: new (options?: any) => TransportStreamInstance,\n sentryWinstonOptions?: WinstonTransportOptions,\n): typeof TransportClass {\n // @ts-ignore - We know this is safe because SentryWinstonTransport extends TransportClass\n class SentryWinstonTransport extends TransportClass {\n private _levels: Set<LogSeverityLevel>;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n public constructor(options?: any) {\n super(options);\n this._levels = new Set(sentryWinstonOptions?.levels ?? DEFAULT_CAPTURED_LEVELS);\n }\n\n /**\n * Forwards a winston log to the Sentry SDK.\n */\n public log(info: unknown, callback: () => void): void {\n try {\n setImmediate(() => {\n // @ts-ignore - We know this is safe because SentryWinstonTransport extends TransportClass\n this.emit('logged', info);\n });\n\n if (!isObjectLike(info)) {\n return;\n }\n\n const levelFromSymbol = info[LEVEL_SYMBOL];\n\n // See: https://github.com/winstonjs/winston?tab=readme-ov-file#streams-objectmode-and-info-objects\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { level, message, timestamp, ...attributes } = info;\n // Remove all symbols from the remaining attributes\n attributes[LEVEL_SYMBOL] = undefined;\n attributes[MESSAGE_SYMBOL] = undefined;\n attributes[SPLAT_SYMBOL] = undefined;\n\n const customLevel = sentryWinstonOptions?.customLevelMap?.[levelFromSymbol as string];\n const winstonLogLevel = WINSTON_LEVEL_TO_LOG_SEVERITY_LEVEL_MAP[levelFromSymbol as string];\n const logSeverityLevel = customLevel ?? winstonLogLevel ?? 'info';\n\n if (this._levels.has(logSeverityLevel)) {\n captureLogEvent({\n level: logSeverityLevel,\n message: message as string,\n attributes: {\n ...attributes,\n [SENTRY_ORIGIN]: 'auto.log.winston',\n },\n });\n } else if (!customLevel && !winstonLogLevel) {\n DEBUG_BUILD &&\n debug.log(\n `Winston log level ${levelFromSymbol} is not captured by Sentry. Please add ${levelFromSymbol} to the \"customLevelMap\" option of the Sentry Winston transport.`,\n );\n }\n } catch {\n // do nothing\n }\n\n if (callback) {\n callback();\n }\n }\n }\n\n return SentryWinstonTransport as typeof TransportClass;\n}\n\n// npm\n// {\n// error: 0,\n// warn: 1,\n// info: 2,\n// http: 3,\n// verbose: 4,\n// debug: 5,\n// silly: 6\n// }\n//\n// syslog\n// {\n// emerg: 0,\n// alert: 1,\n// crit: 2,\n// error: 3,\n// warning: 4,\n// notice: 5,\n// info: 6,\n// debug: 7,\n// }\nconst WINSTON_LEVEL_TO_LOG_SEVERITY_LEVEL_MAP: Record<string, LogSeverityLevel> = {\n // npm\n silly: 'trace',\n // npm and syslog\n debug: 'debug',\n // npm\n verbose: 'debug',\n // npm\n http: 'debug',\n // npm and syslog\n info: 'info',\n // syslog\n notice: 'info',\n // npm\n warn: 'warn',\n // syslog\n warning: 'warn',\n // npm and syslog\n error: 'error',\n // syslog\n emerg: 'fatal',\n // syslog\n alert: 'fatal',\n // syslog\n crit: 'fatal',\n};\n"],"mappings":";;;;AAMA,MAAM,0BAAmD;CAAC;CAAS;CAAS;CAAQ;CAAQ;CAAS;AAAO;AAG5G,MAAM,eAAe,OAAO,IAAI,OAAO;AACvC,MAAM,iBAAiB,OAAO,IAAI,SAAS;AAC3C,MAAM,eAAe,OAAO,IAAI,OAAO;;;;;;;;;;;;;;;;;;;;;AAuDvC,SAAgB,6BAEd,gBACA,sBACuB;CAEvB,MAAM,+BAA+B,eAAe;EAG3C,YAAY,SAAe;GAChC,MAAM,OAAO;GACb,KAAK,UAAU,IAAI,IAAI,sBAAsB,UAAU,uBAAuB;EAChF;;;;EAKO,IAAI,MAAe,UAA4B;GACpD,IAAI;IACF,mBAAmB;KAEjB,KAAK,KAAK,UAAU,IAAI;IAC1B,CAAC;IAED,IAAI,CAAC,aAAa,IAAI,GACpB;IAGF,MAAM,kBAAkB,KAAK;IAI7B,MAAM,EAAE,OAAO,SAAS,WAAW,GAAG,eAAe;IAErD,WAAW,gBAAgB,KAAA;IAC3B,WAAW,kBAAkB,KAAA;IAC7B,WAAW,gBAAgB,KAAA;IAE3B,MAAM,cAAc,sBAAsB,iBAAiB;IAC3D,MAAM,kBAAkB,wCAAwC;IAChE,MAAM,mBAAmB,eAAe,mBAAmB;IAE3D,IAAI,KAAK,QAAQ,IAAI,gBAAgB,GACnC,gBAAgB;KACd,OAAO;KACE;KACT,YAAY;MACV,GAAG;OACF,gBAAgB;KACnB;IACF,CAAC;SACI,IAAI,CAAC,eAAe,CAAC,iBAC1B,eACE,MAAM,IACJ,qBAAqB,gBAAgB,yCAAyC,gBAAgB,iEAChG;GAEN,QAAQ,CAER;GAEA,IAAI,UACF,SAAS;EAEb;CACF;CAEA,OAAO;AACT;AAwBA,MAAM,0CAA4E;CAEhF,OAAO;CAEP,OAAO;CAEP,SAAS;CAET,MAAM;CAEN,MAAM;CAEN,QAAQ;CAER,MAAM;CAEN,SAAS;CAET,OAAO;CAEP,OAAO;CAEP,OAAO;CAEP,MAAM;AACR"}
@@ -1,6 +1,7 @@
1
1
  import { amqplibChannels } from "./config/amqplib.js";
2
2
  import { anthropicAiChannels } from "./config/anthropic-ai.js";
3
3
  import { awsSdkChannels } from "./config/aws-sdk.js";
4
+ import { clickhouseChannels } from "./config/clickhouse.js";
4
5
  import { cronChannels } from "./config/cron.js";
5
6
  import { dataloaderChannels } from "./config/dataloader.js";
6
7
  import { expressChannels } from "./config/express.js";
@@ -62,6 +63,7 @@ const CHANNELS = {
62
63
  ...amqplibChannels,
63
64
  ...anthropicAiChannels,
64
65
  ...awsSdkChannels,
66
+ ...clickhouseChannels,
65
67
  ...cronChannels,
66
68
  ...dataloaderChannels,
67
69
  ...expressChannels,
@@ -1 +1 @@
1
- {"version":3,"file":"channels.js","names":[],"sources":["../../../src/orchestrion/channels.ts"],"sourcesContent":["import { amqplibChannels } from './config/amqplib';\nimport { anthropicAiChannels } from './config/anthropic-ai';\nimport { awsSdkChannels } from './config/aws-sdk';\nimport { cronChannels } from './config/cron';\nimport { dataloaderChannels } from './config/dataloader';\nimport { expressChannels } from './config/express';\nimport { firebaseChannels } from './config/firebase';\nimport { genericPoolChannels } from './config/generic-pool';\nimport { googleGenAiChannels } from './config/google-genai';\nimport { graphqlChannels } from './config/graphql';\nimport { groqChannels } from './config/groq';\nimport { hapiChannels } from './config/hapi';\nimport { honoChannels } from './config/hono';\nimport { ioredisChannels } from './config/ioredis';\nimport { kafkajsChannels } from './config/kafkajs';\nimport { knexChannels } from './config/knex';\nimport { koaChannels } from './config/koa';\nimport { langchainChannels } from './config/langchain';\nimport { langgraphChannels } from './config/langgraph';\nimport { lruMemoizerChannels } from './config/lru-memoizer';\nimport { mastraChannels } from './config/mastra';\nimport { mcpServerChannels } from './config/mcp-server';\nimport { mistralChannels } from './config/mistral';\nimport { mongodbChannels } from './config/mongodb';\nimport { mongooseChannels } from './config/mongoose';\nimport { mysql2Channels } from './config/mysql2';\nimport { mysqlChannels } from './config/mysql';\nimport { neonChannels } from './config/neon';\nimport { nestjsChannels } from './config/nestjs';\nimport { nodeCronChannels } from './config/node-cron';\nimport { nodeScheduleChannels } from './config/node-schedule';\nimport { openaiChannels } from './config/openai';\nimport { pgChannels } from './config/pg';\nimport { piAiChannels } from './config/pi-ai';\nimport { piDurableChannels } from './config/pi-durable';\nimport { postgresJsChannels } from './config/postgres';\nimport { prismaChannels } from './config/prisma';\nimport { redisChannels } from './config/redis';\nimport { remixChannels } from './config/remix';\nimport { tediousChannels } from './config/tedious';\nimport { togetherAiChannels } from './config/together-ai';\nimport { typesafeChannels } from './config/typesafe';\nimport { vercelAiChannels } from './config/vercel-ai';\n\n/**\n * Fully-qualified `diagnostics_channel` names that orchestrion publishes to.\n *\n * Orchestrion's transform always prefixes the configured `channelName` with\n * `orchestrion:${module.name}:`. So a config of\n * `{ channelName: 'query', module: { name: 'mysql' } }`\n * publishes to `orchestrion:mysql:query`.\n *\n * Subscribers (`integrations/<lib>/tracing-channel.ts`) consume the full\n * prefixed string from this map; the config files set only the unprefixed\n * suffix in `channelName`. Keeping both pieces in one file is what guarantees\n * they don't drift apart and silently stop firing.\n *\n * Kept sorted alphabetically by module so concurrent additions insert at different\n * points rather than all appending to the end (fewer merge conflicts).\n */\nexport const CHANNELS = {\n ...amqplibChannels,\n ...anthropicAiChannels,\n ...awsSdkChannels,\n ...cronChannels,\n ...dataloaderChannels,\n ...expressChannels,\n ...firebaseChannels,\n ...genericPoolChannels,\n ...googleGenAiChannels,\n ...graphqlChannels,\n ...groqChannels,\n ...hapiChannels,\n ...honoChannels,\n ...ioredisChannels,\n ...kafkajsChannels,\n ...knexChannels,\n ...koaChannels,\n ...langchainChannels,\n ...langgraphChannels,\n ...lruMemoizerChannels,\n ...mastraChannels,\n ...mcpServerChannels,\n ...mistralChannels,\n ...mongodbChannels,\n ...mongooseChannels,\n ...mysql2Channels,\n ...mysqlChannels,\n ...neonChannels,\n ...nestjsChannels,\n ...nodeCronChannels,\n ...nodeScheduleChannels,\n ...openaiChannels,\n ...pgChannels,\n ...piAiChannels,\n ...piDurableChannels,\n ...postgresJsChannels,\n ...prismaChannels,\n ...redisChannels,\n ...remixChannels,\n ...tediousChannels,\n ...togetherAiChannels,\n ...typesafeChannels,\n ...vercelAiChannels,\n} as const;\n\nexport type ChannelName = (typeof CHANNELS)[keyof typeof CHANNELS];\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4DA,MAAa,WAAW;CACtB,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;AACL"}
1
+ {"version":3,"file":"channels.js","names":[],"sources":["../../../src/orchestrion/channels.ts"],"sourcesContent":["import { amqplibChannels } from './config/amqplib';\nimport { anthropicAiChannels } from './config/anthropic-ai';\nimport { awsSdkChannels } from './config/aws-sdk';\nimport { clickhouseChannels } from './config/clickhouse';\nimport { cronChannels } from './config/cron';\nimport { dataloaderChannels } from './config/dataloader';\nimport { expressChannels } from './config/express';\nimport { firebaseChannels } from './config/firebase';\nimport { genericPoolChannels } from './config/generic-pool';\nimport { googleGenAiChannels } from './config/google-genai';\nimport { graphqlChannels } from './config/graphql';\nimport { groqChannels } from './config/groq';\nimport { hapiChannels } from './config/hapi';\nimport { honoChannels } from './config/hono';\nimport { ioredisChannels } from './config/ioredis';\nimport { kafkajsChannels } from './config/kafkajs';\nimport { knexChannels } from './config/knex';\nimport { koaChannels } from './config/koa';\nimport { langchainChannels } from './config/langchain';\nimport { langgraphChannels } from './config/langgraph';\nimport { lruMemoizerChannels } from './config/lru-memoizer';\nimport { mastraChannels } from './config/mastra';\nimport { mcpServerChannels } from './config/mcp-server';\nimport { mistralChannels } from './config/mistral';\nimport { mongodbChannels } from './config/mongodb';\nimport { mongooseChannels } from './config/mongoose';\nimport { mysql2Channels } from './config/mysql2';\nimport { mysqlChannels } from './config/mysql';\nimport { neonChannels } from './config/neon';\nimport { nestjsChannels } from './config/nestjs';\nimport { nodeCronChannels } from './config/node-cron';\nimport { nodeScheduleChannels } from './config/node-schedule';\nimport { openaiChannels } from './config/openai';\nimport { pgChannels } from './config/pg';\nimport { piAiChannels } from './config/pi-ai';\nimport { piDurableChannels } from './config/pi-durable';\nimport { postgresJsChannels } from './config/postgres';\nimport { prismaChannels } from './config/prisma';\nimport { redisChannels } from './config/redis';\nimport { remixChannels } from './config/remix';\nimport { tediousChannels } from './config/tedious';\nimport { togetherAiChannels } from './config/together-ai';\nimport { typesafeChannels } from './config/typesafe';\nimport { vercelAiChannels } from './config/vercel-ai';\n\n/**\n * Fully-qualified `diagnostics_channel` names that orchestrion publishes to.\n *\n * Orchestrion's transform always prefixes the configured `channelName` with\n * `orchestrion:${module.name}:`. So a config of\n * `{ channelName: 'query', module: { name: 'mysql' } }`\n * publishes to `orchestrion:mysql:query`.\n *\n * Subscribers (`integrations/<lib>/tracing-channel.ts`) consume the full\n * prefixed string from this map; the config files set only the unprefixed\n * suffix in `channelName`. Keeping both pieces in one file is what guarantees\n * they don't drift apart and silently stop firing.\n *\n * Kept sorted alphabetically by module so concurrent additions insert at different\n * points rather than all appending to the end (fewer merge conflicts).\n */\nexport const CHANNELS = {\n ...amqplibChannels,\n ...anthropicAiChannels,\n ...awsSdkChannels,\n ...clickhouseChannels,\n ...cronChannels,\n ...dataloaderChannels,\n ...expressChannels,\n ...firebaseChannels,\n ...genericPoolChannels,\n ...googleGenAiChannels,\n ...graphqlChannels,\n ...groqChannels,\n ...hapiChannels,\n ...honoChannels,\n ...ioredisChannels,\n ...kafkajsChannels,\n ...knexChannels,\n ...koaChannels,\n ...langchainChannels,\n ...langgraphChannels,\n ...lruMemoizerChannels,\n ...mastraChannels,\n ...mcpServerChannels,\n ...mistralChannels,\n ...mongodbChannels,\n ...mongooseChannels,\n ...mysql2Channels,\n ...mysqlChannels,\n ...neonChannels,\n ...nestjsChannels,\n ...nodeCronChannels,\n ...nodeScheduleChannels,\n ...openaiChannels,\n ...pgChannels,\n ...piAiChannels,\n ...piDurableChannels,\n ...postgresJsChannels,\n ...prismaChannels,\n ...redisChannels,\n ...remixChannels,\n ...tediousChannels,\n ...togetherAiChannels,\n ...typesafeChannels,\n ...vercelAiChannels,\n} as const;\n\nexport type ChannelName = (typeof CHANNELS)[keyof typeof CHANNELS];\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6DA,MAAa,WAAW;CACtB,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;AACL"}
@@ -29,6 +29,14 @@ const CHANNEL_INTEGRATION_DEFINITIONS = [
29
29
  exportName: "neonIntegration",
30
30
  modules: ["@neondatabase/serverless"]
31
31
  },
32
+ {
33
+ exportName: "clickhouseIntegration",
34
+ modules: [
35
+ "@clickhouse/client",
36
+ "@clickhouse/client-web",
37
+ "@clickhouse/client-common"
38
+ ]
39
+ },
32
40
  {
33
41
  exportName: "prismaIntegration",
34
42
  modules: ["@prisma/orm-family-sql"]
@@ -1 +1 @@
1
- {"version":3,"file":"channel-integration-definitions.js","names":[],"sources":["../../../../src/orchestrion/config/channel-integration-definitions.ts"],"sourcesContent":["/**\n * Build-time metadata mapping each channel-subscriber integration — by the\n * `exportName` it is published under from `@sentry/server-utils` — to the\n * instrumented packages (orchestrion `module.name`) whose channels it\n * consumes.\n *\n * Kept in a separate, factory-free module on purpose: the module-injected\n * transform (reachable from every orchestrion bundler plugin) reads this to\n * generate the tiny snippet it injects into each instrumented file, and must\n * not drag any subscriber code — or its `@sentry/core` span machinery — into\n * the plugin's own build to do so.\n *\n * `exportName` must be a named export of `@sentry/server-utils`.\n * `modules` must match `module.name` values in `SENTRY_INSTRUMENTATIONS` — e.g.\n * `postgresIntegration` covers both `pg` and `pg-pool`, and `redisIntegration`\n * covers `redis`, `@redis/client` and `ioredis`.\n */\nexport const CHANNEL_INTEGRATION_DEFINITIONS = [\n { exportName: 'postgresIntegration', modules: ['pg', 'pg-pool'] },\n { exportName: 'postgresJsIntegration', modules: ['postgres'] },\n { exportName: 'neonIntegration', modules: ['@neondatabase/serverless'] },\n { exportName: 'prismaIntegration', modules: ['@prisma/orm-family-sql'] },\n { exportName: 'mysqlIntegration', modules: ['mysql'] },\n { exportName: 'mysql2Integration', modules: ['mysql2'] },\n { exportName: 'mongoIntegration', modules: ['mongodb'] },\n { exportName: 'mongooseIntegration', modules: ['mongoose'] },\n { exportName: 'knexIntegration', modules: ['knex'] },\n { exportName: 'tediousIntegration', modules: ['tedious'] },\n { exportName: 'genericPoolIntegration', modules: ['generic-pool'] },\n { exportName: 'lruMemoizerIntegration', modules: ['lru-memoizer'] },\n { exportName: 'openAIIntegration', modules: ['openai'] },\n { exportName: 'anthropicAIIntegration', modules: ['@anthropic-ai/sdk'] },\n { exportName: 'googleGenAIIntegration', modules: ['@google/genai'] },\n { exportName: 'mistralAIIntegration', modules: ['@mistralai/mistralai'] },\n { exportName: 'groqIntegration', modules: ['groq-sdk'] },\n { exportName: 'togetherAIIntegration', modules: ['together-ai'] },\n { exportName: 'typesafeIntegration', modules: ['@typesafe-ai/sdk'] },\n { exportName: 'vercelAIIntegration', modules: ['ai'] },\n {\n exportName: 'langChainIntegration',\n modules: [\n '@langchain/core',\n '@langchain/openai',\n '@langchain/google-common',\n '@langchain/google-genai',\n '@langchain/mistralai',\n '@langchain/typesafe',\n ],\n },\n { exportName: 'langGraphIntegration', modules: ['@langchain/langgraph'] },\n { exportName: 'mastraIntegration', modules: ['@mastra/core'] },\n { exportName: 'flueIntegration', modules: ['@flue/runtime'] },\n { exportName: 'piAiIntegration', modules: ['@earendil-works/pi-ai'] },\n { exportName: 'piDurableIntegration', modules: ['@earendil-works/pi-durable'] },\n { exportName: 'mcpServerIntegration', modules: ['@modelcontextprotocol/server', '@modelcontextprotocol/sdk'] },\n { exportName: 'awsIntegration', modules: ['@aws-sdk/smithy-client', '@smithy/core', '@smithy/smithy-client'] },\n { exportName: 'firebaseIntegration', modules: ['@firebase/firestore', 'firebase-functions'] },\n { exportName: 'amqplibIntegration', modules: ['amqplib'] },\n { exportName: 'hapiIntegration', modules: ['@hapi/hapi'] },\n { exportName: 'honoIntegration', modules: ['hono'] },\n { exportName: 'koaIntegration', modules: ['koa'] },\n { exportName: 'expressIntegration', modules: ['express', 'router'] },\n { exportName: 'graphqlIntegration', modules: ['graphql'] },\n { exportName: 'kafkaIntegration', modules: ['kafkajs'] },\n { exportName: 'redisIntegration', modules: ['redis', '@redis/client', 'ioredis'] },\n { exportName: 'dataloaderIntegration', modules: ['dataloader'] },\n { exportName: 'nitroIntegration', modules: ['h3'] },\n] as const satisfies ReadonlyArray<{ exportName: string; modules: readonly string[] }>;\n\n/** Look up the subscriber export name for an instrumented package, if any. */\nexport function subscriberExportForModule(moduleName: string): string | undefined {\n return CHANNEL_INTEGRATION_DEFINITIONS.find(d => (d.modules as readonly string[]).includes(moduleName))?.exportName;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAiBA,MAAa,kCAAkC;CAC7C;EAAE,YAAY;EAAuB,SAAS,CAAC,MAAM,SAAS;CAAE;CAChE;EAAE,YAAY;EAAyB,SAAS,CAAC,UAAU;CAAE;CAC7D;EAAE,YAAY;EAAmB,SAAS,CAAC,0BAA0B;CAAE;CACvE;EAAE,YAAY;EAAqB,SAAS,CAAC,wBAAwB;CAAE;CACvE;EAAE,YAAY;EAAoB,SAAS,CAAC,OAAO;CAAE;CACrD;EAAE,YAAY;EAAqB,SAAS,CAAC,QAAQ;CAAE;CACvD;EAAE,YAAY;EAAoB,SAAS,CAAC,SAAS;CAAE;CACvD;EAAE,YAAY;EAAuB,SAAS,CAAC,UAAU;CAAE;CAC3D;EAAE,YAAY;EAAmB,SAAS,CAAC,MAAM;CAAE;CACnD;EAAE,YAAY;EAAsB,SAAS,CAAC,SAAS;CAAE;CACzD;EAAE,YAAY;EAA0B,SAAS,CAAC,cAAc;CAAE;CAClE;EAAE,YAAY;EAA0B,SAAS,CAAC,cAAc;CAAE;CAClE;EAAE,YAAY;EAAqB,SAAS,CAAC,QAAQ;CAAE;CACvD;EAAE,YAAY;EAA0B,SAAS,CAAC,mBAAmB;CAAE;CACvE;EAAE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AY;EAAyB,SAAS,CAAC,YAAY;CAAE;CAC/D;EAAE,YAAY;EAAoB,SAAS,CAAC,IAAI;CAAE;AACpD;;AAGA,SAAgB,0BAA0B,YAAwC;CAChF,OAAO,gCAAgC,MAAK,MAAM,EAAE,QAA8B,SAAS,UAAU,CAAC,CAAC,EAAE;AAC3G"}
1
+ {"version":3,"file":"channel-integration-definitions.js","names":[],"sources":["../../../../src/orchestrion/config/channel-integration-definitions.ts"],"sourcesContent":["/**\n * Build-time metadata mapping each channel-subscriber integration — by the\n * `exportName` it is published under from `@sentry/server-utils` — to the\n * instrumented packages (orchestrion `module.name`) whose channels it\n * consumes.\n *\n * Kept in a separate, factory-free module on purpose: the module-injected\n * transform (reachable from every orchestrion bundler plugin) reads this to\n * generate the tiny snippet it injects into each instrumented file, and must\n * not drag any subscriber code — or its `@sentry/core` span machinery — into\n * the plugin's own build to do so.\n *\n * `exportName` must be a named export of `@sentry/server-utils`.\n * `modules` must match `module.name` values in `SENTRY_INSTRUMENTATIONS` — e.g.\n * `postgresIntegration` covers both `pg` and `pg-pool`, and `redisIntegration`\n * covers `redis`, `@redis/client` and `ioredis`.\n */\nexport const CHANNEL_INTEGRATION_DEFINITIONS = [\n { exportName: 'postgresIntegration', modules: ['pg', 'pg-pool'] },\n { exportName: 'postgresJsIntegration', modules: ['postgres'] },\n { exportName: 'neonIntegration', modules: ['@neondatabase/serverless'] },\n {\n exportName: 'clickhouseIntegration',\n modules: ['@clickhouse/client', '@clickhouse/client-web', '@clickhouse/client-common'],\n },\n { exportName: 'prismaIntegration', modules: ['@prisma/orm-family-sql'] },\n { exportName: 'mysqlIntegration', modules: ['mysql'] },\n { exportName: 'mysql2Integration', modules: ['mysql2'] },\n { exportName: 'mongoIntegration', modules: ['mongodb'] },\n { exportName: 'mongooseIntegration', modules: ['mongoose'] },\n { exportName: 'knexIntegration', modules: ['knex'] },\n { exportName: 'tediousIntegration', modules: ['tedious'] },\n { exportName: 'genericPoolIntegration', modules: ['generic-pool'] },\n { exportName: 'lruMemoizerIntegration', modules: ['lru-memoizer'] },\n { exportName: 'openAIIntegration', modules: ['openai'] },\n { exportName: 'anthropicAIIntegration', modules: ['@anthropic-ai/sdk'] },\n { exportName: 'googleGenAIIntegration', modules: ['@google/genai'] },\n { exportName: 'mistralAIIntegration', modules: ['@mistralai/mistralai'] },\n { exportName: 'groqIntegration', modules: ['groq-sdk'] },\n { exportName: 'togetherAIIntegration', modules: ['together-ai'] },\n { exportName: 'typesafeIntegration', modules: ['@typesafe-ai/sdk'] },\n { exportName: 'vercelAIIntegration', modules: ['ai'] },\n {\n exportName: 'langChainIntegration',\n modules: [\n '@langchain/core',\n '@langchain/openai',\n '@langchain/google-common',\n '@langchain/google-genai',\n '@langchain/mistralai',\n '@langchain/typesafe',\n ],\n },\n { exportName: 'langGraphIntegration', modules: ['@langchain/langgraph'] },\n { exportName: 'mastraIntegration', modules: ['@mastra/core'] },\n { exportName: 'flueIntegration', modules: ['@flue/runtime'] },\n { exportName: 'piAiIntegration', modules: ['@earendil-works/pi-ai'] },\n { exportName: 'piDurableIntegration', modules: ['@earendil-works/pi-durable'] },\n { exportName: 'mcpServerIntegration', modules: ['@modelcontextprotocol/server', '@modelcontextprotocol/sdk'] },\n { exportName: 'awsIntegration', modules: ['@aws-sdk/smithy-client', '@smithy/core', '@smithy/smithy-client'] },\n { exportName: 'firebaseIntegration', modules: ['@firebase/firestore', 'firebase-functions'] },\n { exportName: 'amqplibIntegration', modules: ['amqplib'] },\n { exportName: 'hapiIntegration', modules: ['@hapi/hapi'] },\n { exportName: 'honoIntegration', modules: ['hono'] },\n { exportName: 'koaIntegration', modules: ['koa'] },\n { exportName: 'expressIntegration', modules: ['express', 'router'] },\n { exportName: 'graphqlIntegration', modules: ['graphql'] },\n { exportName: 'kafkaIntegration', modules: ['kafkajs'] },\n { exportName: 'redisIntegration', modules: ['redis', '@redis/client', 'ioredis'] },\n { exportName: 'dataloaderIntegration', modules: ['dataloader'] },\n { exportName: 'nitroIntegration', modules: ['h3'] },\n] as const satisfies ReadonlyArray<{ exportName: string; modules: readonly string[] }>;\n\n/** Look up the subscriber export name for an instrumented package, if any. */\nexport function subscriberExportForModule(moduleName: string): string | undefined {\n return CHANNEL_INTEGRATION_DEFINITIONS.find(d => (d.modules as readonly string[]).includes(moduleName))?.exportName;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAiBA,MAAa,kCAAkC;CAC7C;EAAE,YAAY;EAAuB,SAAS,CAAC,MAAM,SAAS;CAAE;CAChE;EAAE,YAAY;EAAyB,SAAS,CAAC,UAAU;CAAE;CAC7D;EAAE,YAAY;EAAmB,SAAS,CAAC,0BAA0B;CAAE;CACvE;EACE,YAAY;EACZ,SAAS;GAAC;GAAsB;GAA0B;EAA2B;CACvF;CACA;EAAE,YAAY;EAAqB,SAAS,CAAC,wBAAwB;CAAE;CACvE;EAAE,YAAY;EAAoB,SAAS,CAAC,OAAO;CAAE;CACrD;EAAE,YAAY;EAAqB,SAAS,CAAC,QAAQ;CAAE;CACvD;EAAE,YAAY;EAAoB,SAAS,CAAC,SAAS;CAAE;CACvD;EAAE,YAAY;EAAuB,SAAS,CAAC,UAAU;CAAE;CAC3D;EAAE,YAAY;EAAmB,SAAS,CAAC,MAAM;CAAE;CACnD;EAAE,YAAY;EAAsB,SAAS,CAAC,SAAS;CAAE;CACzD;EAAE,YAAY;EAA0B,SAAS,CAAC,cAAc;CAAE;CAClE;EAAE,YAAY;EAA0B,SAAS,CAAC,cAAc;CAAE;CAClE;EAAE,YAAY;EAAqB,SAAS,CAAC,QAAQ;CAAE;CACvD;EAAE,YAAY;EAA0B,SAAS,CAAC,mBAAmB;CAAE;CACvE;EAAE,YAAY;EAA0B,SAAS,CAAC,eAAe;CAAE;CACnE;EAAE,YAAY;EAAwB,SAAS,CAAC,sBAAsB;CAAE;CACxE;EAAE,YAAY;EAAmB,SAAS,CAAC,UAAU;CAAE;CACvD;EAAE,YAAY;EAAyB,SAAS,CAAC,aAAa;CAAE;CAChE;E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;AAC3G"}
@@ -0,0 +1,51 @@
1
+ import { getModuleNames } from "./module-names.js";
2
+ // src/orchestrion/config/clickhouse.ts
3
+ const METHODS = [
4
+ "query",
5
+ "command",
6
+ "exec",
7
+ "insert"
8
+ ];
9
+ const clickhouseConfig = [
10
+ {
11
+ name: "@clickhouse/client-common",
12
+ versionRange: ">=1.1.0 <1.23.0",
13
+ filePath: "dist/client.js"
14
+ },
15
+ {
16
+ name: "@clickhouse/client",
17
+ versionRange: ">=1.23.0 <2",
18
+ filePath: "dist/common/client.js"
19
+ },
20
+ {
21
+ name: "@clickhouse/client-web",
22
+ versionRange: ">=1.23.0 <2",
23
+ filePath: "dist/common/client.js"
24
+ }
25
+ ].flatMap((module) => METHODS.map((methodName) => ({
26
+ channelName: methodName,
27
+ module,
28
+ functionQuery: {
29
+ className: "ClickHouseClient",
30
+ methodName,
31
+ kind: "Async"
32
+ }
33
+ })));
34
+ const clickhouseModuleNames = getModuleNames(clickhouseConfig);
35
+ const clickhouseChannels = {
36
+ CLICKHOUSE_QUERY: "orchestrion:@clickhouse/client:query",
37
+ CLICKHOUSE_COMMAND: "orchestrion:@clickhouse/client:command",
38
+ CLICKHOUSE_EXEC: "orchestrion:@clickhouse/client:exec",
39
+ CLICKHOUSE_INSERT: "orchestrion:@clickhouse/client:insert",
40
+ CLICKHOUSE_WEB_QUERY: "orchestrion:@clickhouse/client-web:query",
41
+ CLICKHOUSE_WEB_COMMAND: "orchestrion:@clickhouse/client-web:command",
42
+ CLICKHOUSE_WEB_EXEC: "orchestrion:@clickhouse/client-web:exec",
43
+ CLICKHOUSE_WEB_INSERT: "orchestrion:@clickhouse/client-web:insert",
44
+ CLICKHOUSE_COMMON_QUERY: "orchestrion:@clickhouse/client-common:query",
45
+ CLICKHOUSE_COMMON_COMMAND: "orchestrion:@clickhouse/client-common:command",
46
+ CLICKHOUSE_COMMON_EXEC: "orchestrion:@clickhouse/client-common:exec",
47
+ CLICKHOUSE_COMMON_INSERT: "orchestrion:@clickhouse/client-common:insert"
48
+ };
49
+ export { clickhouseChannels, clickhouseConfig, clickhouseModuleNames };
50
+
51
+ //# sourceMappingURL=clickhouse.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"clickhouse.js","names":[],"sources":["../../../../src/orchestrion/config/clickhouse.ts"],"sourcesContent":["import type { InstrumentationConfig } from '../apmTypes';\n\nimport { getModuleNames } from './module-names';\n\n// `ClickHouseClient` sends every statement through four `async` methods: `query`, `command`, `exec`\n// and `insert`. None of them calls another, so each call is traced as exactly one db span. `ping`\n// and `close` carry no statement and are left alone.\n//\n// Two file layouts across the supported range:\n// - `< 1.23.0` → the class lives in the separate `@clickhouse/client-common` package (`dist/client.js`)\n// - `>= 1.23.0` → `@clickhouse/client` and `@clickhouse/client-web` each ship that code in\n// `dist/common/client.js`\n//\n// Starts at 1.1.0: before it, `command` delegated to `exec` (two spans per command) and the client\n// did not keep the `connectionParams` the span attributes are read from.\n//\n// The Node.js `NodeClickHouseClient` subclass only forwards `query` to `super`, and its class name\n// doesn't match `className`, so it doesn't add a second span.\nconst METHODS = ['query', 'command', 'exec', 'insert'] as const;\n\nconst MODULES = [\n { name: '@clickhouse/client-common', versionRange: '>=1.1.0 <1.23.0', filePath: 'dist/client.js' },\n { name: '@clickhouse/client', versionRange: '>=1.23.0 <2', filePath: 'dist/common/client.js' },\n { name: '@clickhouse/client-web', versionRange: '>=1.23.0 <2', filePath: 'dist/common/client.js' },\n];\n\nexport const clickhouseConfig: InstrumentationConfig[] = MODULES.flatMap(module =>\n METHODS.map(methodName => ({\n channelName: methodName,\n module,\n functionQuery: { className: 'ClickHouseClient', methodName, kind: 'Async' as const },\n })),\n);\n\nexport const clickhouseModuleNames = getModuleNames(clickhouseConfig);\n\nexport const clickhouseChannels = {\n CLICKHOUSE_QUERY: 'orchestrion:@clickhouse/client:query',\n CLICKHOUSE_COMMAND: 'orchestrion:@clickhouse/client:command',\n CLICKHOUSE_EXEC: 'orchestrion:@clickhouse/client:exec',\n CLICKHOUSE_INSERT: 'orchestrion:@clickhouse/client:insert',\n CLICKHOUSE_WEB_QUERY: 'orchestrion:@clickhouse/client-web:query',\n CLICKHOUSE_WEB_COMMAND: 'orchestrion:@clickhouse/client-web:command',\n CLICKHOUSE_WEB_EXEC: 'orchestrion:@clickhouse/client-web:exec',\n CLICKHOUSE_WEB_INSERT: 'orchestrion:@clickhouse/client-web:insert',\n CLICKHOUSE_COMMON_QUERY: 'orchestrion:@clickhouse/client-common:query',\n CLICKHOUSE_COMMON_COMMAND: 'orchestrion:@clickhouse/client-common:command',\n CLICKHOUSE_COMMON_EXEC: 'orchestrion:@clickhouse/client-common:exec',\n CLICKHOUSE_COMMON_INSERT: 'orchestrion:@clickhouse/client-common:insert',\n} as const;\n"],"mappings":";;AAkBA,MAAM,UAAU;CAAC;CAAS;CAAW;CAAQ;AAAQ;AAQrD,MAAa,mBAA4C;CALvD;EAAE,MAAM;EAA6B,cAAc;EAAmB,UAAU;CAAiB;CACjG;EAAE,MAAM;EAAsB,cAAc;EAAe,UAAU;CAAwB;CAC7F;EAAE,MAAM;EAA0B,cAAc;EAAe,UAAU;CAAwB;AAG1C,CAAA,CAAQ,SAAQ,WACvE,QAAQ,KAAI,gBAAe;CACzB,aAAa;CACb;CACA,eAAe;EAAE,WAAW;EAAoB;EAAY,MAAM;CAAiB;AACrF,EAAE,CACJ;AAEA,MAAa,wBAAwB,eAAe,gBAAgB;AAEpE,MAAa,qBAAqB;CAChC,kBAAkB;CAClB,oBAAoB;CACpB,iBAAiB;CACjB,mBAAmB;CACnB,sBAAsB;CACtB,wBAAwB;CACxB,qBAAqB;CACrB,uBAAuB;CACvB,yBAAyB;CACzB,2BAA2B;CAC3B,wBAAwB;CACxB,0BAA0B;AAC5B"}
@@ -3,7 +3,7 @@ const honoConfig = [{
3
3
  channelName: "context",
4
4
  module: {
5
5
  name: "hono",
6
- versionRange: ">=4.0.0 <5",
6
+ versionRange: ">=4.0.0 <6",
7
7
  filePath: /^dist\/(?:cjs\/)?context\.js$/
8
8
  },
9
9
  functionQuery: { className: "Context" }
@@ -11,7 +11,7 @@ const honoConfig = [{
11
11
  channelName: "request",
12
12
  module: {
13
13
  name: "hono",
14
- versionRange: ">=4.0.0 <5",
14
+ versionRange: ">=4.0.0 <6",
15
15
  filePath: /^dist\/(?:cjs\/)?hono-base\.js$/
16
16
  },
17
17
  astQuery: "PropertyDefinition[key.name='request'] > ArrowFunctionExpression",
@@ -1 +1 @@
1
- {"version":3,"file":"hono.js","names":[],"sources":["../../../../src/orchestrion/config/hono.ts"],"sourcesContent":["import type { InstrumentationConfig } from '../apmTypes';\nimport { getModuleNames } from './module-names';\n\n// Hono is hooked through per-request internals only — never at module scope — which is what lets the\n// same config run on Cloudflare Workers, where workerd forbids `diagnostics_channel` at module scope.\n// The subscribers live in `honoIntegration`.\nconst honoInstrumentationConfig: InstrumentationConfig[] = [\n {\n // `new Context()` runs once per request: where the Sentry middleware is injected and matched\n // middleware handlers are wrapped for spans.\n // TODO(v12): Raise the minimum Hono version to 4.4.9, here and in the `@sentry/hono` peer range.\n // Before 4.4.9, Hono passes `matchResult` to `new HonoRequest()`, so this hook does nothing.\n channelName: 'context',\n module: { name: 'hono', versionRange: '>=4.0.0 <5', filePath: /^dist\\/(?:cjs\\/)?context\\.js$/ },\n functionQuery: { className: 'Context' },\n },\n {\n // `app.request(...)` — Hono's internal dispatch for sub-app-to-sub-app fetches. A class-field\n // arrow, hence `astQuery` instead of `methodName`.\n channelName: 'request',\n module: { name: 'hono', versionRange: '>=4.0.0 <5', filePath: /^dist\\/(?:cjs\\/)?hono-base\\.js$/ },\n astQuery: \"PropertyDefinition[key.name='request'] > ArrowFunctionExpression\",\n functionQuery: { kind: 'Auto' },\n },\n];\n\nexport const honoConfig = honoInstrumentationConfig satisfies InstrumentationConfig[];\n\nexport const honoModuleNames = getModuleNames(honoConfig);\n\nexport const honoChannels = {\n HONO_CONTEXT: 'orchestrion:hono:context',\n HONO_REQUEST: 'orchestrion:hono:request',\n} as const;\n"],"mappings":";AA0BA,MAAa,aAAa,CAnBxB;CAKE,aAAa;CACb,QAAQ;EAAE,MAAM;EAAQ,cAAc;EAAc,UAAU;CAAgC;CAC9F,eAAe,EAAE,WAAW,UAAU;AACxC,GACA;CAGE,aAAa;CACb,QAAQ;EAAE,MAAM;EAAQ,cAAc;EAAc,UAAU;CAAkC;CAChG,UAAU;CACV,eAAe,EAAE,MAAM,OAAO;AAChC,CAGwB;AAE1B,MAAa,kBAAkB,eAAe,UAAU;AAExD,MAAa,eAAe;CAC1B,cAAc;CACd,cAAc;AAChB"}
1
+ {"version":3,"file":"hono.js","names":[],"sources":["../../../../src/orchestrion/config/hono.ts"],"sourcesContent":["import type { InstrumentationConfig } from '../apmTypes';\nimport { getModuleNames } from './module-names';\n\n// Hono is hooked through per-request internals only — never at module scope — which is what lets the\n// same config run on Cloudflare Workers, where workerd forbids `diagnostics_channel` at module scope.\n// The subscribers live in `honoIntegration`.\nconst honoInstrumentationConfig: InstrumentationConfig[] = [\n {\n // `new Context()` runs once per request: where the Sentry middleware is injected and matched\n // middleware handlers are wrapped for spans.\n // TODO(v12): Raise the minimum Hono version to 4.4.9, here and in the `@sentry/hono` peer range.\n // Before 4.4.9, Hono passes `matchResult` to `new HonoRequest()`, so this hook does nothing.\n channelName: 'context',\n module: { name: 'hono', versionRange: '>=4.0.0 <6', filePath: /^dist\\/(?:cjs\\/)?context\\.js$/ },\n functionQuery: { className: 'Context' },\n },\n {\n // `app.request(...)` — Hono's internal dispatch for sub-app-to-sub-app fetches. A class-field\n // arrow, hence `astQuery` instead of `methodName`.\n channelName: 'request',\n module: { name: 'hono', versionRange: '>=4.0.0 <6', filePath: /^dist\\/(?:cjs\\/)?hono-base\\.js$/ },\n astQuery: \"PropertyDefinition[key.name='request'] > ArrowFunctionExpression\",\n functionQuery: { kind: 'Auto' },\n },\n];\n\nexport const honoConfig = honoInstrumentationConfig satisfies InstrumentationConfig[];\n\nexport const honoModuleNames = getModuleNames(honoConfig);\n\nexport const honoChannels = {\n HONO_CONTEXT: 'orchestrion:hono:context',\n HONO_REQUEST: 'orchestrion:hono:request',\n} as const;\n"],"mappings":";AA0BA,MAAa,aAAa,CAnBxB;CAKE,aAAa;CACb,QAAQ;EAAE,MAAM;EAAQ,cAAc;EAAc,UAAU;CAAgC;CAC9F,eAAe,EAAE,WAAW,UAAU;AACxC,GACA;CAGE,aAAa;CACb,QAAQ;EAAE,MAAM;EAAQ,cAAc;EAAc,UAAU;CAAkC;CAChG,UAAU;CACV,eAAe,EAAE,MAAM,OAAO;AAChC,CAGwB;AAE1B,MAAa,kBAAkB,eAAe,UAAU;AAExD,MAAa,eAAe;CAC1B,cAAc;CACd,cAAc;AAChB"}
@@ -1,6 +1,7 @@
1
1
  import { awsSdkConfig } from "./aws-sdk.js";
2
2
  import { amqplibConfig } from "./amqplib.js";
3
3
  import { anthropicAiConfig } from "./anthropic-ai.js";
4
+ import { clickhouseConfig } from "./clickhouse.js";
4
5
  import { cronConfig } from "./cron.js";
5
6
  import { dataloaderConfig } from "./dataloader.js";
6
7
  import { expressConfig } from "./express.js";
@@ -63,6 +64,7 @@ const SENTRY_INSTRUMENTATIONS = [
63
64
  ...amqplibConfig,
64
65
  ...anthropicAiConfig,
65
66
  ...awsSdkConfig,
67
+ ...clickhouseConfig,
66
68
  ...cronConfig,
67
69
  ...dataloaderConfig,
68
70
  ...expressConfig,