@sentry/server-utils 11.13.0 → 11.14.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 (88) hide show
  1. package/build/cjs/chunks/config.js +19 -5
  2. package/build/cjs/chunks/config.js.map +1 -1
  3. package/build/cjs/chunks/exports.js +72 -26
  4. package/build/cjs/chunks/exports.js.map +1 -1
  5. package/build/cjs/chunks/moduleInjectedTransform.js +6 -5
  6. package/build/cjs/chunks/moduleInjectedTransform.js.map +1 -1
  7. package/build/cjs/index.js +161 -65
  8. package/build/cjs/index.js.map +1 -1
  9. package/build/cjs/orchestrion/bundler/rollup.js +4 -4
  10. package/build/cjs/orchestrion/bundler/rollup.js.map +1 -1
  11. package/build/esm/ai/google-genai/constants.js +2 -1
  12. package/build/esm/ai/google-genai/constants.js.map +1 -1
  13. package/build/esm/ai/google-genai/decisions.js +25 -0
  14. package/build/esm/ai/google-genai/decisions.js.map +1 -0
  15. package/build/esm/ai/google-genai/index.js +16 -5
  16. package/build/esm/ai/google-genai/index.js.map +1 -1
  17. package/build/esm/ai/mistral/index.js +9 -8
  18. package/build/esm/ai/mistral/index.js.map +1 -1
  19. package/build/esm/ai/mistral/streaming.js +3 -7
  20. package/build/esm/ai/mistral/streaming.js.map +1 -1
  21. package/build/esm/ai/mistral/utils.js +9 -1
  22. package/build/esm/ai/mistral/utils.js.map +1 -1
  23. package/build/esm/ai/vercel-ai/index.js +3 -1
  24. package/build/esm/ai/vercel-ai/index.js.map +1 -1
  25. package/build/esm/ai/workers-ai/index.js +8 -7
  26. package/build/esm/ai/workers-ai/index.js.map +1 -1
  27. package/build/esm/ai/workers-ai/streaming.js +3 -7
  28. package/build/esm/ai/workers-ai/streaming.js.map +1 -1
  29. package/build/esm/index.js +3 -2
  30. package/build/esm/index.js.map +1 -1
  31. package/build/esm/integrations/cron.js +2 -2
  32. package/build/esm/integrations/cron.js.map +1 -1
  33. package/build/esm/integrations/google-genai.js +10 -6
  34. package/build/esm/integrations/google-genai.js.map +1 -1
  35. package/build/esm/integrations/mistral.js +4 -3
  36. package/build/esm/integrations/mistral.js.map +1 -1
  37. package/build/esm/integrations/node-cron.js +5 -4
  38. package/build/esm/integrations/node-cron.js.map +1 -1
  39. package/build/esm/integrations/node-schedule.js +2 -2
  40. package/build/esm/integrations/node-schedule.js.map +1 -1
  41. package/build/esm/integrations/vercel-ai/vercel-ai-dc-subscriber.js +9 -1
  42. package/build/esm/integrations/vercel-ai/vercel-ai-dc-subscriber.js.map +1 -1
  43. package/build/esm/orchestrion/bundler/moduleInjectedTransform.js +6 -5
  44. package/build/esm/orchestrion/bundler/moduleInjectedTransform.js.map +1 -1
  45. package/build/esm/orchestrion/bundler/rollup.js +4 -4
  46. package/build/esm/orchestrion/bundler/rollup.js.map +1 -1
  47. package/build/esm/orchestrion/config/google-genai.js +19 -5
  48. package/build/esm/orchestrion/config/google-genai.js.map +1 -1
  49. package/build/esm/package.json +1 -1
  50. package/build/esm/utils/cronMonitoring.js +128 -50
  51. package/build/esm/utils/cronMonitoring.js.map +1 -1
  52. package/build/types/ai/google-genai/constants.d.ts +3 -0
  53. package/build/types/ai/google-genai/constants.d.ts.map +1 -1
  54. package/build/types/ai/google-genai/decisions.d.ts +8 -0
  55. package/build/types/ai/google-genai/decisions.d.ts.map +1 -0
  56. package/build/types/ai/google-genai/index.d.ts +3 -1
  57. package/build/types/ai/google-genai/index.d.ts.map +1 -1
  58. package/build/types/ai/mistral/index.d.ts.map +1 -1
  59. package/build/types/ai/mistral/streaming.d.ts +1 -1
  60. package/build/types/ai/mistral/streaming.d.ts.map +1 -1
  61. package/build/types/ai/mistral/utils.d.ts +5 -0
  62. package/build/types/ai/mistral/utils.d.ts.map +1 -1
  63. package/build/types/ai/vercel-ai/index.d.ts.map +1 -1
  64. package/build/types/ai/vercel-ai/vercel-ai-attributes.d.ts +3 -0
  65. package/build/types/ai/vercel-ai/vercel-ai-attributes.d.ts.map +1 -1
  66. package/build/types/ai/workers-ai/index.d.ts.map +1 -1
  67. package/build/types/ai/workers-ai/streaming.d.ts +1 -1
  68. package/build/types/ai/workers-ai/streaming.d.ts.map +1 -1
  69. package/build/types/index.d.ts +3 -1
  70. package/build/types/index.d.ts.map +1 -1
  71. package/build/types/integrations/cron.d.ts.map +1 -1
  72. package/build/types/integrations/google-genai.d.ts +3 -3
  73. package/build/types/integrations/google-genai.d.ts.map +1 -1
  74. package/build/types/integrations/mistral.d.ts.map +1 -1
  75. package/build/types/integrations/node-cron.d.ts +1 -1
  76. package/build/types/integrations/node-cron.d.ts.map +1 -1
  77. package/build/types/integrations/node-schedule.d.ts.map +1 -1
  78. package/build/types/integrations/vercel-ai/vercel-ai-dc-subscriber.d.ts.map +1 -1
  79. package/build/types/orchestrion/bundler/moduleInjectedTransform.d.ts.map +1 -1
  80. package/build/types/orchestrion/bundler/rollup.d.ts +3 -3
  81. package/build/types/orchestrion/bundler/rollup.d.ts.map +1 -1
  82. package/build/types/orchestrion/channels.d.ts +1 -0
  83. package/build/types/orchestrion/channels.d.ts.map +1 -1
  84. package/build/types/orchestrion/config/google-genai.d.ts +13 -0
  85. package/build/types/orchestrion/config/google-genai.d.ts.map +1 -1
  86. package/build/types/utils/cronMonitoring.d.ts +4 -5
  87. package/build/types/utils/cronMonitoring.d.ts.map +1 -1
  88. package/package.json +3 -3
@@ -5,7 +5,7 @@ import { LAST_STEP_ONLY_USAGE_KEYS, getProviderMetadataAttributes } from "../../
5
5
  import { WORKERS_AI_INTEGRATION_NAME } from "../../ai/workers-ai/constants.js";
6
6
  import { bindTracingChannelToSpan } from "../../tracing-channel.js";
7
7
  import { asNumber, asString, sum, tapModelCallStream } from "./util.js";
8
- import { GEN_AI_CONVERSATION_ID, GEN_AI_EMBEDDINGS_INPUT, GEN_AI_FUNCTION_ID, GEN_AI_INPUT_MESSAGES, GEN_AI_OPERATION_NAME, GEN_AI_OUTPUT_MESSAGES, GEN_AI_PROVIDER_NAME, GEN_AI_REQUEST_MODEL, GEN_AI_RESPONSE_FINISH_REASONS, GEN_AI_RESPONSE_ID, GEN_AI_RESPONSE_MODEL, GEN_AI_RESPONSE_STREAMING, GEN_AI_SYSTEM_INSTRUCTIONS, GEN_AI_TOOL_CALL_ARGUMENTS, GEN_AI_TOOL_CALL_RESULT, GEN_AI_TOOL_DEFINITIONS, GEN_AI_TOOL_DESCRIPTION, GEN_AI_TOOL_NAME, GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS, GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS, GEN_AI_USAGE_INPUT_TOKENS, GEN_AI_USAGE_OUTPUT_TOKENS, GEN_AI_USAGE_REASONING_OUTPUT_TOKENS, GEN_AI_USAGE_TOTAL_TOKENS, SENTRY_OP, SENTRY_ORIGIN, VERCEL_AI_SETTINGS_CONTEXT_KEY_BASE, VERCEL_AI_TOOL_CALL_CONTEXT_KEY_BASE } from "@sentry/conventions/attributes";
8
+ import { GEN_AI_CONVERSATION_ID, GEN_AI_COST_TOTAL_TOKENS, GEN_AI_EMBEDDINGS_INPUT, GEN_AI_FUNCTION_ID, GEN_AI_INPUT_MESSAGES, GEN_AI_OPERATION_NAME, GEN_AI_OUTPUT_MESSAGES, GEN_AI_PROVIDER_NAME, GEN_AI_REQUEST_MODEL, GEN_AI_RESPONSE_FINISH_REASONS, GEN_AI_RESPONSE_ID, GEN_AI_RESPONSE_MODEL, GEN_AI_RESPONSE_STREAMING, GEN_AI_SYSTEM_INSTRUCTIONS, GEN_AI_TOOL_CALL_ARGUMENTS, GEN_AI_TOOL_CALL_RESULT, GEN_AI_TOOL_DEFINITIONS, GEN_AI_TOOL_DESCRIPTION, GEN_AI_TOOL_NAME, GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS, GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS, GEN_AI_USAGE_INPUT_TOKENS, GEN_AI_USAGE_OUTPUT_TOKENS, GEN_AI_USAGE_REASONING_OUTPUT_TOKENS, GEN_AI_USAGE_TOTAL_TOKENS, SENTRY_OP, SENTRY_ORIGIN, VERCEL_AI_SETTINGS_CONTEXT_KEY_BASE, VERCEL_AI_TOOL_CALL_CONTEXT_KEY_BASE } from "@sentry/conventions/attributes";
9
9
  import { SPAN_STATUS_ERROR, _INTERNAL_skipAiProviderWrapping, captureException, getActiveSpan, getClient, isObjectLike, isPlainObject, spanToJSON, spanToTraceContext, startInactiveSpan, stringify, withScope } from "@sentry/core";
10
10
  import { GEN_AI_DECIDE, GEN_AI_EMBEDDINGS, GEN_AI_EXECUTE_TOOL, GEN_AI_GENERATE_CONTENT, GEN_AI_INVOKE_AGENT, GEN_AI_RERANK } from "@sentry/conventions/op";
11
11
  // src/integrations/vercel-ai/vercel-ai-dc-subscriber.ts
@@ -41,6 +41,13 @@ const ROOT_OPERATION_TYPES = /* @__PURE__ */ new Set([
41
41
  "embedMany",
42
42
  "rerank"
43
43
  ]);
44
+ const PARTIAL_COST_OPERATION_TYPES = /* @__PURE__ */ new Set([
45
+ "generateText",
46
+ "streamText",
47
+ "streamObject",
48
+ "generateObject",
49
+ "embedMany"
50
+ ]);
44
51
  /** Drop the per-operation `callId` maps once the owning top-level operation settles (success or error). */
45
52
  function clearOperationId(data) {
46
53
  if (!ROOT_OPERATION_TYPES.has(data.type)) return;
@@ -91,6 +98,7 @@ function dropLastStepOnlyUsage(providerAttributes, type) {
91
98
  const hasRecomputedOutput = GEN_AI_USAGE_OUTPUT_TOKENS in providerAttributes;
92
99
  for (const key of LAST_STEP_ONLY_USAGE_KEYS) delete providerAttributes[key];
93
100
  if (hasRecomputedOutput) delete providerAttributes[GEN_AI_USAGE_REASONING_OUTPUT_TOKENS];
101
+ if (PARTIAL_COST_OPERATION_TYPES.has(type)) delete providerAttributes[GEN_AI_COST_TOTAL_TOKENS];
94
102
  }
95
103
  /** Record tool name → description from an event's `tools`, so tool spans can backfill the description. */
96
104
  function recordToolDescriptions(callId, tools) {
@@ -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_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 { isEveGenAiRecordingDefault } from './gen-ai-recording-mode';\nimport { getEvaluationOutputMessages, type GenAiOptions } 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/** 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}\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/** Integration-level recording options, pinned at subscribe time so we never look the integration up per event. */\nexport type VercelAiChannelOptions = 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\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, options);\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, options, end),\n },\n );\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(\n span: Span,\n data: VercelAiChannelMessage,\n options: VercelAiChannelOptions,\n end: (error?: unknown) => void,\n): 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 { recordOutputs } = getRecordingOptions(data.event, options, data.result === undefined);\n result.stream = tapModelCallStream(\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 enrichInvokeAgentFromStream(callId, final, recordOutputs);\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(\n callId: string | undefined,\n final: StreamedModelCallResult,\n recordOutputs: boolean,\n): void {\n const span = callId ? invokeAgentSpanByCallId.get(callId) : undefined;\n if (!span) {\n return;\n }\n\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 { recordInputs } = getRecordingOptions(event, channelOptions);\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(\n span: Span,\n data: VercelAiChannelMessage,\n channelOptions: VercelAiChannelOptions,\n): 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(data.event, channelOptions, data.result === undefined);\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 channelOptions: VercelAiChannelOptions,\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(channelOptions.recordInputs, event.recordInputs, genAI?.inputs, eveMode),\n recordOutputs: resolveRecording(channelOptions.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":";;;;;;;;;;;;;;;;AAoEA,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,IAAI,IAA4B;AAIzE,MAAM,uCAAuB,IAAI,IAAsB;CACrD;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;;AAGD,SAAgB,iBAAiB,MAAoC;CACnE,IAAI,CAAC,qBAAqB,IAAI,KAAK,IAAI,GACrC;CAEF,MAAM,SAAS,SAAS,KAAK,MAAM,MAAM;CACzC,IAAI,QACF,qBAAqB,MAAM;AAE/B;;;;;;;;AASA,SAAgB,qBAAqB,QAAsB;CACzD,oBAAoB,OAAO,MAAM;CACjC,yBAAyB,OAAO,MAAM;CACtC,wBAAwB,OAAO,MAAM;CACrC,iCAAiC,OAAO,MAAM;AAChD;;;;;;AAOA,SAAS,wBAAwB,iBAA8C;CAC7E,IAAI,CAAC,aAAa,eAAe,GAC/B;CAEF,KAAK,MAAM,OAAO,CAAC,UAAU,OAAO,GAAG;EACrC,MAAM,UAAU,gBAAgB;EAChC,MAAM,eAAe,aAAa,OAAO,IAAI,SAAS,QAAQ,YAAY,IAAI,KAAA;EAC9E,IAAI,cACF,OAAO;CAEX;AAEF;;AAGA,SAAS,8BAAk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AA4D;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_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 { isEveGenAiRecordingDefault } from './gen-ai-recording-mode';\nimport { getEvaluationOutputMessages, type GenAiOptions } 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/** Integration-level recording options, pinned at subscribe time so we never look the integration up per event. */\nexport type VercelAiChannelOptions = 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\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, options);\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, options, end),\n },\n );\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(\n span: Span,\n data: VercelAiChannelMessage,\n options: VercelAiChannelOptions,\n end: (error?: unknown) => void,\n): 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 { recordOutputs } = getRecordingOptions(data.event, options, data.result === undefined);\n result.stream = tapModelCallStream(\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 enrichInvokeAgentFromStream(callId, final, recordOutputs);\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(\n callId: string | undefined,\n final: StreamedModelCallResult,\n recordOutputs: boolean,\n): void {\n const span = callId ? invokeAgentSpanByCallId.get(callId) : undefined;\n if (!span) {\n return;\n }\n\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 { recordInputs } = getRecordingOptions(event, channelOptions);\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(\n span: Span,\n data: VercelAiChannelMessage,\n channelOptions: VercelAiChannelOptions,\n): 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(data.event, channelOptions, data.result === undefined);\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 channelOptions: VercelAiChannelOptions,\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(channelOptions.recordInputs, event.recordInputs, genAI?.inputs, eveMode),\n recordOutputs: resolveRecording(channelOptions.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":";;;;;;;;;;;;;;;;AAqEA,MAAa,mCAAmC;AAEhD,MAAM,SAAS;AAGf,MAAM,4BAA4B;CAChC,YAAY;CAIZ,QAAQ;CACR,QAAQ;CACR,cAAc;CACd,cAAc;CAGd,kBAAkB;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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,6 +1,7 @@
1
1
  import { parse } from "../../vendored/meriyah/dist/meriyah2.js";
2
2
  import { subscriberExportForModule } from "../config/channel-integration-definitions.js";
3
3
  import { MODULE_REGISTRATION_TRANSFORM } from "../config/registration-only.js";
4
+ import { stringifyForCodeInjection } from "@sentry/core";
4
5
  // src/orchestrion/bundler/moduleInjectedTransform.ts
5
6
  const injectedPrograms = /* @__PURE__ */ new WeakSet();
6
7
  const DEFAULT_IMPORT_SPECIFIER = "@sentry/server-utils";
@@ -37,8 +38,8 @@ const ORCHESTRION_BUNDLER_MARKER_BANNER = ";(function(){var g=globalThis.__SENTR
37
38
  *
38
39
  * The specifier is parameterized for bundlers where the bare import emitted
39
40
  * inside a transformed `node_modules` file can't resolve (Turbopack under
40
- * isolated installs); it's embedded via `JSON.stringify` so absolute Windows
41
- * paths survive.
41
+ * isolated installs); it's embedded via `stringifyForCodeInjection` so
42
+ * absolute Windows paths survive.
42
43
  *
43
44
  * The call result is assigned to a global rather than discarded. The helper
44
45
  * returns `void` and `@sentry/server-utils` is `sideEffects: false`, so a bare
@@ -49,8 +50,8 @@ const ORCHESTRION_BUNDLER_MARKER_BANNER = ";(function(){var g=globalThis.__SENTR
49
50
  */
50
51
  function moduleInjectedSnippet(moduleName, exportName, esm, importSpecifier) {
51
52
  const bindings = exportName ? `orchestrionModuleInjected, ${exportName}` : "orchestrionModuleInjected";
52
- const importStmt = esm ? `import { ${bindings} } from ${JSON.stringify(importSpecifier)};` : `const { ${bindings} } = require(${JSON.stringify(importSpecifier)});`;
53
- const args = exportName ? `${JSON.stringify(moduleName)}, () => ${exportName}()` : JSON.stringify(moduleName);
53
+ const importStmt = esm ? `import { ${bindings} } from ${stringifyForCodeInjection(importSpecifier)};` : `const { ${bindings} } = require(${stringifyForCodeInjection(importSpecifier)});`;
54
+ const args = exportName ? `${stringifyForCodeInjection(moduleName)}, () => ${exportName}()` : stringifyForCodeInjection(moduleName);
54
55
  return `${importStmt}\n${MODULE_INJECTED_SINK} = orchestrionModuleInjected(${args});`;
55
56
  }
56
57
  /**
@@ -68,7 +69,7 @@ function moduleInjectedSnippet(moduleName, exportName, esm, importSpecifier) {
68
69
  function selfProvidedSnippet(moduleName, filePath) {
69
70
  const marker = "globalThis.__SENTRY_ORCHESTRION__";
70
71
  const self = `./${filePath.split("/").pop()}`;
71
- return `import * as __SENTRY_SELF_PROVIDED__ from ${JSON.stringify(self)};\n(${marker} = ${marker} || {});\n(${marker}.providedModules = ${marker}.providedModules || {});\nObject.defineProperty(${marker}.providedModules, ${JSON.stringify(moduleName)}, { configurable: true, enumerable: true, get() { return __SENTRY_SELF_PROVIDED__; } });`;
72
+ return `import * as __SENTRY_SELF_PROVIDED__ from ${stringifyForCodeInjection(self)};\n(${marker} = ${marker} || {});\n(${marker}.providedModules = ${marker}.providedModules || {});\nObject.defineProperty(${marker}.providedModules, ${stringifyForCodeInjection(moduleName)}, { configurable: true, enumerable: true, get() { return __SENTRY_SELF_PROVIDED__; } });`;
72
73
  }
73
74
  /**
74
75
  * The unified `customTransforms` every orchestrion bundler plugin (and the
@@ -1 +1 @@
1
- {"version":3,"file":"moduleInjectedTransform.js","names":[],"sources":["../../../../src/orchestrion/bundler/moduleInjectedTransform.ts"],"sourcesContent":["import type { CustomTransform } from '../apmTypes';\nimport { parse } from 'meriyah';\nimport { subscriberExportForModule } from '../config/channel-integration-definitions';\nimport { MODULE_REGISTRATION_TRANSFORM } from '../config/registration-only';\n\n// Tracks Program nodes we already injected into, so a package with several\n// instrumented files (or several configs pointing at one file) is injected only\n// once per file. A `WeakSet` keyed by the node avoids mutating the emitted AST.\nconst injectedPrograms = new WeakSet<object>();\n\ninterface ProgramNode {\n type: string;\n body: Array<{ type: string; directive?: string }>;\n}\n\n// Where the injected snippet imports from: the `orchestrionModuleInjected`\n// helper and the module's channel-subscriber factory both live on the main\n// `@sentry/server-utils` entry, so a single import serves both. The ESM barrel\n// tree-shakes to just the helper and the factories actually referenced.\nconst DEFAULT_IMPORT_SPECIFIER = '@sentry/server-utils';\n\n/**\n * Assignment target that keeps the injected call from being tree-shaken. See\n * {@link moduleInjectedSnippet}. The value written is always `undefined`; only\n * the assignment matters.\n */\nconst MODULE_INJECTED_SINK = 'globalThis.__SENTRY_ORCHESTRION_INJECT__';\n\n/**\n * Entry-chunk banner that marks \"the bundler plugin ran\" for\n * `detectOrchestrionSetup()`. Merge-only (`g.bundler = g.bundler || new Set()`)\n * so it can never clobber module names already recorded by an injected snippet\n * that happened to run first; the names themselves arrive per module, when each\n * transformed module is evaluated and its snippet calls\n * `orchestrionModuleInjected`.\n */\nexport const ORCHESTRION_BUNDLER_MARKER_BANNER =\n ';(function(){var g=globalThis.__SENTRY_ORCHESTRION__=globalThis.__SENTRY_ORCHESTRION__||{};g.bundler=g.bundler||new Set();})();';\n\n/**\n * Snippet injected into each instrumented module. It imports the\n * `orchestrionModuleInjected` helper — plus the module's channel-subscriber\n * factory, when it has one — from `@sentry/server-utils` and calls the helper\n * with the module's real name. The helper records the module on the global\n * marker, stores the factory, and emits the `orchestrion.module-injected` client\n * event, so it runs exactly when the module is evaluated — the moment its\n * channels can start publishing. That per-module timing is what keeps\n * subscriptions lazy (Node caps diagnostics channels in use at 1024).\n *\n * Importing the single named factory (rather than a central dispatch that pulls\n * in every subscriber) is what makes this tree-shake: a bundle carries only the\n * subscriber code for packages actually transformed into it. The helper is\n * generic (references no factory), so importing it alongside doesn't pull\n * siblings.\n *\n * The specifier is parameterized for bundlers where the bare import emitted\n * inside a transformed `node_modules` file can't resolve (Turbopack under\n * isolated installs); it's embedded via `JSON.stringify` so absolute Windows\n * paths survive.\n *\n * The call result is assigned to a global rather than discarded. The helper\n * returns `void` and `@sentry/server-utils` is `sideEffects: false`, so a bare\n * call statement is something a bundler can prove droppable: rollup >= 4.63.0\n * does exactly that and removes the whole registration, leaving the module\n * instrumented but unsubscribed. Writing to a property of `globalThis` is a\n * side effect no bundler can shake out, so the call survives.\n */\nfunction moduleInjectedSnippet(\n moduleName: string,\n exportName: string | undefined,\n esm: boolean,\n importSpecifier: string,\n): string {\n const bindings = exportName ? `orchestrionModuleInjected, ${exportName}` : 'orchestrionModuleInjected';\n const importStmt = esm\n ? `import { ${bindings} } from ${JSON.stringify(importSpecifier)};`\n : `const { ${bindings} } = require(${JSON.stringify(importSpecifier)});`;\n\n // The arrow defers reading `exportName` to `init()`. `@sentry/*/vite` imports some packages into\n // their own integration module (e.g. Mastra's), and in that cycle a direct read would hit the TDZ.\n const args = exportName ? `${JSON.stringify(moduleName)}, () => ${exportName}()` : JSON.stringify(moduleName);\n return `${importStmt}\\n${MODULE_INJECTED_SINK} = orchestrionModuleInjected(${args});`;\n}\n\n/**\n * Publishes the module's own namespace on `providedModules`. For `@flue/runtime`'s `dist/index.mjs`,\n * this prepends roughly:\n *\n * ```js\n * import * as __SENTRY_SELF_PROVIDED__ from \"./index.mjs\";\n * globalThis.__SENTRY_ORCHESTRION__.providedModules[\"@flue/runtime\"] = __SENTRY_SELF_PROVIDED__; // as a getter\n * ```\n *\n * A self-import adds no edge to the module graph; importing the package into a Sentry module would\n * close a cycle through every instrumented dependency, since those all import `@sentry/server-utils`.\n */\nfunction selfProvidedSnippet(moduleName: string, filePath: string): string {\n const marker = 'globalThis.__SENTRY_ORCHESTRION__';\n const self = `./${filePath.split('/').pop()}`;\n return (\n `import * as __SENTRY_SELF_PROVIDED__ from ${JSON.stringify(self)};\\n` +\n `(${marker} = ${marker} || {});\\n` +\n `(${marker}.providedModules = ${marker}.providedModules || {});\\n` +\n `Object.defineProperty(${marker}.providedModules, ${JSON.stringify(moduleName)}, ` +\n '{ configurable: true, enumerable: true, get() { return __SENTRY_SELF_PROVIDED__; } });'\n );\n}\n\nexport interface ModuleInjectedTransformsOptions {\n /** Packages whose ESM entry publishes its own namespace on `providedModules`. */\n selfProvidedModules?: readonly string[];\n}\n\n/**\n * The unified `customTransforms` every orchestrion bundler plugin (and the\n * webpack/Turbopack loader) applies: an override for orchestrion's built-in\n * `tracingChannelImport` transform, which runs (via `tracingChannelDeclaration`)\n * for every file that gets a channel wrapped — the one hook that reaches every\n * instrumented module without any extra instrumentation configs. It chains the\n * default (which splices the `diagnostics_channel` import and bails when it is\n * already present), then splices the module-injected snippet in after any\n * `'use strict'` directive.\n *\n * Invoked once per wrapped channel, so the `WeakSet` keeps the snippet to one\n * per file. Requires `@apm-js-collab/code-transformer` >= 0.18.1, where\n * built-ins dispatch through the override map and expose the originals on\n * `state.transforms.defaults`.\n *\n * Also carries the registration-only operator, which splices the same snippet\n * without any channel injection — for library versions whose tracing channels\n * are native.\n */\nexport function moduleInjectedTransforms(\n // A function is read per injected file — the webpack/Turbopack loader uses it\n // to supply a per-file relative specifier (Turbopack supports neither\n // absolute-path imports nor bare specifiers that don't resolve from the\n // importing file's location).\n importSpecifier?: string | (() => string | undefined),\n { selfProvidedModules = [] }: ModuleInjectedTransformsOptions = {},\n): Record<string, CustomTransform> {\n const spliceModuleInjected = (state: unknown, program: unknown): void => {\n const { moduleType, module } = state as {\n moduleType?: string;\n module?: { name?: string; filePath?: string | RegExp };\n };\n\n const node = program as ProgramNode;\n if (injectedPrograms.has(node)) {\n return;\n }\n\n const moduleName = module?.name;\n if (!moduleName) {\n return;\n }\n\n injectedPrograms.add(node);\n\n const specifier =\n (typeof importSpecifier === 'function' ? importSpecifier() : importSpecifier) ?? DEFAULT_IMPORT_SPECIFIER;\n const exportName = subscriberExportForModule(moduleName);\n const esm = moduleType === 'esm';\n const selfProvided =\n esm && typeof module?.filePath === 'string' && selfProvidedModules.includes(moduleName)\n ? `${selfProvidedSnippet(moduleName, module.filePath)}\\n`\n : '';\n const statements = parse(selfProvided + moduleInjectedSnippet(moduleName, exportName, esm, specifier), {\n module: esm,\n next: true,\n }).body as ProgramNode['body'];\n\n const directiveIndex = node.body.findIndex(n => n.type === 'ExpressionStatement' && n.directive === 'use strict');\n node.body.splice(directiveIndex + 1, 0, ...statements);\n };\n\n const injectModuleInjected: CustomTransform = (state, program, parent, ancestry) => {\n const { transforms } = state as {\n transforms: { defaults: { tracingChannelImport: CustomTransform } };\n };\n\n transforms.defaults.tracingChannelImport(state, program, parent, ancestry);\n spliceModuleInjected(state, program);\n };\n\n // Operator for registration-only configs (`transform` field, see\n // `config/registration-only.ts`): dispatched INSTEAD of `traceSync`, so no\n // channel is declared and no function is wrapped. Their `astQuery: 'Program'`\n // matches only the file root, so `node` is the Program itself.\n const injectRegistrationOnly: CustomTransform = (state, node) => {\n spliceModuleInjected(state, node);\n };\n\n return {\n tracingChannelImport: injectModuleInjected,\n [MODULE_REGISTRATION_TRANSFORM]: injectRegistrationOnly,\n };\n}\n"],"mappings":";;;;AAQA,MAAM,mCAAmB,IAAI,QAAgB;AAW7C,MAAM,2BAA2B;;;;;;AAOjC,MAAM,uBAAuB;;;;;;;;;AAU7B,MAAa,oCACX;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BF,SAAS,sBACP,YACA,YACA,KACA,iBACQ;CACR,MAAM,WAAW,aAAa,8BAA8B,eAAe;CAC3E,MAAM,aAAa,MACf,YAAY,SAAS,UAAU,KAAK,UAAU,eAAe,EAAE,KAC/D,WAAW,SAAS,eAAe,KAAK,UAAU,eAAe,EAAE;CAIvE,MAAM,OAAO,aAAa,GAAG,KAAK,UAAU,UAAU,EAAE,UAAU,WAAW,MAAM,KAAK,UAAU,UAAU;CAC5G,OAAO,GAAG,WAAW,IAAI,qBAAqB,+BAA+B,KAAK;AACpF;;;;;;;;;;;;;AAcA,SAAS,oBAAoB,YAAoB,UAA0B;CACzE,MAAM,SAAS;CACf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sBAAsB;GACrB,gCAAgC;CACnC;AACF"}
1
+ {"version":3,"file":"moduleInjectedTransform.js","names":[],"sources":["../../../../src/orchestrion/bundler/moduleInjectedTransform.ts"],"sourcesContent":["import type { CustomTransform } from '../apmTypes';\nimport { parse } from 'meriyah';\nimport { subscriberExportForModule } from '../config/channel-integration-definitions';\nimport { MODULE_REGISTRATION_TRANSFORM } from '../config/registration-only';\nimport { stringifyForCodeInjection } from '@sentry/core';\n\n// Tracks Program nodes we already injected into, so a package with several\n// instrumented files (or several configs pointing at one file) is injected only\n// once per file. A `WeakSet` keyed by the node avoids mutating the emitted AST.\nconst injectedPrograms = new WeakSet<object>();\n\ninterface ProgramNode {\n type: string;\n body: Array<{ type: string; directive?: string }>;\n}\n\n// Where the injected snippet imports from: the `orchestrionModuleInjected`\n// helper and the module's channel-subscriber factory both live on the main\n// `@sentry/server-utils` entry, so a single import serves both. The ESM barrel\n// tree-shakes to just the helper and the factories actually referenced.\nconst DEFAULT_IMPORT_SPECIFIER = '@sentry/server-utils';\n\n/**\n * Assignment target that keeps the injected call from being tree-shaken. See\n * {@link moduleInjectedSnippet}. The value written is always `undefined`; only\n * the assignment matters.\n */\nconst MODULE_INJECTED_SINK = 'globalThis.__SENTRY_ORCHESTRION_INJECT__';\n\n/**\n * Entry-chunk banner that marks \"the bundler plugin ran\" for\n * `detectOrchestrionSetup()`. Merge-only (`g.bundler = g.bundler || new Set()`)\n * so it can never clobber module names already recorded by an injected snippet\n * that happened to run first; the names themselves arrive per module, when each\n * transformed module is evaluated and its snippet calls\n * `orchestrionModuleInjected`.\n */\nexport const ORCHESTRION_BUNDLER_MARKER_BANNER =\n ';(function(){var g=globalThis.__SENTRY_ORCHESTRION__=globalThis.__SENTRY_ORCHESTRION__||{};g.bundler=g.bundler||new Set();})();';\n\n/**\n * Snippet injected into each instrumented module. It imports the\n * `orchestrionModuleInjected` helper — plus the module's channel-subscriber\n * factory, when it has one — from `@sentry/server-utils` and calls the helper\n * with the module's real name. The helper records the module on the global\n * marker, stores the factory, and emits the `orchestrion.module-injected` client\n * event, so it runs exactly when the module is evaluated — the moment its\n * channels can start publishing. That per-module timing is what keeps\n * subscriptions lazy (Node caps diagnostics channels in use at 1024).\n *\n * Importing the single named factory (rather than a central dispatch that pulls\n * in every subscriber) is what makes this tree-shake: a bundle carries only the\n * subscriber code for packages actually transformed into it. The helper is\n * generic (references no factory), so importing it alongside doesn't pull\n * siblings.\n *\n * The specifier is parameterized for bundlers where the bare import emitted\n * inside a transformed `node_modules` file can't resolve (Turbopack under\n * isolated installs); it's embedded via `stringifyForCodeInjection` so\n * absolute Windows paths survive.\n *\n * The call result is assigned to a global rather than discarded. The helper\n * returns `void` and `@sentry/server-utils` is `sideEffects: false`, so a bare\n * call statement is something a bundler can prove droppable: rollup >= 4.63.0\n * does exactly that and removes the whole registration, leaving the module\n * instrumented but unsubscribed. Writing to a property of `globalThis` is a\n * side effect no bundler can shake out, so the call survives.\n */\nfunction moduleInjectedSnippet(\n moduleName: string,\n exportName: string | undefined,\n esm: boolean,\n importSpecifier: string,\n): string {\n const bindings = exportName ? `orchestrionModuleInjected, ${exportName}` : 'orchestrionModuleInjected';\n const importStmt = esm\n ? `import { ${bindings} } from ${stringifyForCodeInjection(importSpecifier)};`\n : `const { ${bindings} } = require(${stringifyForCodeInjection(importSpecifier)});`;\n\n // The arrow defers reading `exportName` to `init()`. `@sentry/*/vite` imports some packages into\n // their own integration module (e.g. Mastra's), and in that cycle a direct read would hit the TDZ.\n const args = exportName\n ? `${stringifyForCodeInjection(moduleName)}, () => ${exportName}()`\n : stringifyForCodeInjection(moduleName);\n return `${importStmt}\\n${MODULE_INJECTED_SINK} = orchestrionModuleInjected(${args});`;\n}\n\n/**\n * Publishes the module's own namespace on `providedModules`. For `@flue/runtime`'s `dist/index.mjs`,\n * this prepends roughly:\n *\n * ```js\n * import * as __SENTRY_SELF_PROVIDED__ from \"./index.mjs\";\n * globalThis.__SENTRY_ORCHESTRION__.providedModules[\"@flue/runtime\"] = __SENTRY_SELF_PROVIDED__; // as a getter\n * ```\n *\n * A self-import adds no edge to the module graph; importing the package into a Sentry module would\n * close a cycle through every instrumented dependency, since those all import `@sentry/server-utils`.\n */\nfunction selfProvidedSnippet(moduleName: string, filePath: string): string {\n const marker = 'globalThis.__SENTRY_ORCHESTRION__';\n const self = `./${filePath.split('/').pop()}`;\n return (\n `import * as __SENTRY_SELF_PROVIDED__ from ${stringifyForCodeInjection(self)};\\n` +\n `(${marker} = ${marker} || {});\\n` +\n `(${marker}.providedModules = ${marker}.providedModules || {});\\n` +\n `Object.defineProperty(${marker}.providedModules, ${stringifyForCodeInjection(moduleName)}, ` +\n '{ configurable: true, enumerable: true, get() { return __SENTRY_SELF_PROVIDED__; } });'\n );\n}\n\nexport interface ModuleInjectedTransformsOptions {\n /** Packages whose ESM entry publishes its own namespace on `providedModules`. */\n selfProvidedModules?: readonly string[];\n}\n\n/**\n * The unified `customTransforms` every orchestrion bundler plugin (and the\n * webpack/Turbopack loader) applies: an override for orchestrion's built-in\n * `tracingChannelImport` transform, which runs (via `tracingChannelDeclaration`)\n * for every file that gets a channel wrapped — the one hook that reaches every\n * instrumented module without any extra instrumentation configs. It chains the\n * default (which splices the `diagnostics_channel` import and bails when it is\n * already present), then splices the module-injected snippet in after any\n * `'use strict'` directive.\n *\n * Invoked once per wrapped channel, so the `WeakSet` keeps the snippet to one\n * per file. Requires `@apm-js-collab/code-transformer` >= 0.18.1, where\n * built-ins dispatch through the override map and expose the originals on\n * `state.transforms.defaults`.\n *\n * Also carries the registration-only operator, which splices the same snippet\n * without any channel injection — for library versions whose tracing channels\n * are native.\n */\nexport function moduleInjectedTransforms(\n // A function is read per injected file — the webpack/Turbopack loader uses it\n // to supply a per-file relative specifier (Turbopack supports neither\n // absolute-path imports nor bare specifiers that don't resolve from the\n // importing file's location).\n importSpecifier?: string | (() => string | undefined),\n { selfProvidedModules = [] }: ModuleInjectedTransformsOptions = {},\n): Record<string, CustomTransform> {\n const spliceModuleInjected = (state: unknown, program: unknown): void => {\n const { moduleType, module } = state as {\n moduleType?: string;\n module?: { name?: string; filePath?: string | RegExp };\n };\n\n const node = program as ProgramNode;\n if (injectedPrograms.has(node)) {\n return;\n }\n\n const moduleName = module?.name;\n if (!moduleName) {\n return;\n }\n\n injectedPrograms.add(node);\n\n const specifier =\n (typeof importSpecifier === 'function' ? importSpecifier() : importSpecifier) ?? DEFAULT_IMPORT_SPECIFIER;\n const exportName = subscriberExportForModule(moduleName);\n const esm = moduleType === 'esm';\n const selfProvided =\n esm && typeof module?.filePath === 'string' && selfProvidedModules.includes(moduleName)\n ? `${selfProvidedSnippet(moduleName, module.filePath)}\\n`\n : '';\n const statements = parse(selfProvided + moduleInjectedSnippet(moduleName, exportName, esm, specifier), {\n module: esm,\n next: true,\n }).body as ProgramNode['body'];\n\n const directiveIndex = node.body.findIndex(n => n.type === 'ExpressionStatement' && n.directive === 'use strict');\n node.body.splice(directiveIndex + 1, 0, ...statements);\n };\n\n const injectModuleInjected: CustomTransform = (state, program, parent, ancestry) => {\n const { transforms } = state as {\n transforms: { defaults: { tracingChannelImport: CustomTransform } };\n };\n\n transforms.defaults.tracingChannelImport(state, program, parent, ancestry);\n spliceModuleInjected(state, program);\n };\n\n // Operator for registration-only configs (`transform` field, see\n // `config/registration-only.ts`): dispatched INSTEAD of `traceSync`, so no\n // channel is declared and no function is wrapped. Their `astQuery: 'Program'`\n // matches only the file root, so `node` is the Program itself.\n const injectRegistrationOnly: CustomTransform = (state, node) => {\n spliceModuleInjected(state, node);\n };\n\n return {\n tracingChannelImport: injectModuleInjected,\n [MODULE_REGISTRATION_TRANSFORM]: injectRegistrationOnly,\n };\n}\n"],"mappings":";;;;;AASA,MAAM,mCAAmB,IAAI,QAAgB;AAW7C,MAAM,2BAA2B;;;;;;AAOjC,MAAM,uBAAuB;;;;;;;;;AAU7B,MAAa,oCACX;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BF,SAAS,sBACP,YACA,YACA,KACA,iBACQ;C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AU,MAAK,EAAE,SAAS,yBAAyB,EAAE,cAAc,YAAY;EAChH,KAAK,KAAK,OAAO,iBAAiB,GAAG,GAAG,GAAG,UAAU;CACvD;CAEA,MAAM,wBAAyC,OAAO,SAAS,QAAQ,aAAa;EAClF,MAAM,EAAE,eAAe;EAIvB,WAAW,SAAS,qBAAqB,OAAO,SAAS,QAAQ,QAAQ;EACzE,qBAAqB,OAAO,OAAO;CACrC;CAMA,MAAM,0BAA2C,OAAO,SAAS;EAC/D,qBAAqB,OAAO,IAAI;CAClC;CAEA,OAAO;EACL,sBAAsB;GACrB,gCAAgC;CACnC;AACF"}
@@ -19,7 +19,7 @@ function rawExternalMatchesModule(external, name) {
19
19
  * `@rollup/plugin-commonjs` options for builds that bundle CommonJS packages while their
20
20
  * dependencies stay external. Builtin `require()`s unwrap to the module (a namespace breaks
21
21
  * direct calls) and convert inside `try` blocks (a bare `require` throws in ESM output).
22
- * Externals keep `'auto'`, which {@link sentryCommonJSInteropPlugin} fixes for Node >= 23.
22
+ * Externals keep `'auto'`, which {@link sentryCommonJSInteropPlugin} fixes for Node >= 23, Deno and Bun.
23
23
  */
24
24
  function commonJSInteropOptions() {
25
25
  return {
@@ -29,10 +29,10 @@ function commonJSInteropOptions() {
29
29
  }
30
30
  const COMMONJS_HELPERS_ID = "\0commonjsHelpers.js";
31
31
  const BROKEN_NAMESPACE_CHECK = "Object.keys(n).length === 1";
32
- const FIXED_NAMESPACE_CHECK = "Object.keys(n).filter(k => k !== 'module.exports').length === 1";
32
+ const FIXED_NAMESPACE_CHECK = "(Object.keys(n).filter(k => k !== 'module.exports').length === 1 || (typeof n['default'] === 'function' && Object.keys(n).every(k => k === 'default' || k === 'module.exports' || n[k] === n['default'][k]) && Object.keys(n).some(k => Object.getOwnPropertyDescriptor(n['default'], k)?.enumerable === false)))";
33
33
  /**
34
- * Fixes `@rollup/plugin-commonjs`' `'auto'` interop for Node >= 23 by patching the broken
35
- * namespace check in its helpers module. The patch applies only while the exact broken
34
+ * Fixes `@rollup/plugin-commonjs`' `'auto'` interop for Node >= 23, Deno and Bun by patching the
35
+ * broken namespace check in its helpers module. The patch applies only while the exact broken
36
36
  * expression exists, so it retires itself once the plugin is fixed upstream.
37
37
  */
38
38
  function sentryCommonJSInteropPlugin() {
@@ -1 +1 @@
1
- {"version":3,"file":"rollup.js","names":["codeTransformer"],"sources":["../../../../src/orchestrion/bundler/rollup.ts"],"sourcesContent":["import { isBuiltin } from 'node:module';\n\nimport codeTransformer from '@apm-js-collab/code-transformer-bundler-plugins/rollup';\nimport type {\n ExternalOption,\n InputOptions,\n NormalizedInputOptions,\n Plugin,\n PluginContext,\n ResolveIdHook,\n} from 'rollup';\n\nexport type { Plugin as RollupPlugin } from 'rollup';\nimport { instrumentedModuleNames } from '../config';\nimport type { PluginOptions } from './options';\nimport { externalEntryMatchesModule, externalizedModulesWarning, orchestrionTransformOptions } from './options';\nimport { resolveOrchestrionRuntimeRequest, SNIPPET_IMPORT_SPECIFIER } from './resolve';\n\n/**\n * Whether a raw (un-normalized) `external` input option marks `name` as\n * external. String entries use the shared subpath-aware matching so a\n * `'mysql/lib/...'` entry flags `mysql`, consistent with the esbuild and\n * webpack plugins.\n */\nfunction rawExternalMatchesModule(external: ExternalOption, name: string): boolean {\n if (typeof external === 'function') {\n return !!external(name, undefined, false);\n }\n const entries = Array.isArray(external) ? external : [external];\n return entries.some(entry =>\n typeof entry === 'string' ? externalEntryMatchesModule(entry, name) : entry.test(name),\n );\n}\n\n/**\n * Structural subset of `@rollup/plugin-commonjs` options, so this package needs no dependency on\n * the plugin for its types.\n */\nexport interface CommonJSInteropOptions {\n requireReturnsDefault: (id: string) => boolean | 'auto' | 'preferred' | 'namespace';\n ignoreTryCatch: (id: string) => boolean;\n}\n\n/**\n * `@rollup/plugin-commonjs` options for builds that bundle CommonJS packages while their\n * dependencies stay external. Builtin `require()`s unwrap to the module (a namespace breaks\n * direct calls) and convert inside `try` blocks (a bare `require` throws in ESM output).\n * Externals keep `'auto'`, which {@link sentryCommonJSInteropPlugin} fixes for Node >= 23.\n */\nexport function commonJSInteropOptions(): CommonJSInteropOptions {\n return {\n requireReturnsDefault: id => (isBuiltin(id) ? true : 'auto'),\n ignoreTryCatch: id => !isBuiltin(id),\n };\n}\n\nconst COMMONJS_HELPERS_ID = '\\0commonjsHelpers.js';\n\n// The plugin's `'auto'` helper unwraps a required external module only when `default` is the\n// sole key on its namespace. Node >= 23 adds a `'module.exports'` key to every CommonJS\n// namespace (nodejs/node#53848), so the check never passes. Ignoring that key restores it.\nconst BROKEN_NAMESPACE_CHECK = 'Object.keys(n).length === 1';\nconst FIXED_NAMESPACE_CHECK = \"Object.keys(n).filter(k => k !== 'module.exports').length === 1\";\n\n/**\n * Fixes `@rollup/plugin-commonjs`' `'auto'` interop for Node >= 23 by patching the broken\n * namespace check in its helpers module. The patch applies only while the exact broken\n * expression exists, so it retires itself once the plugin is fixed upstream.\n */\nexport function sentryCommonJSInteropPlugin(): Plugin {\n return {\n name: 'sentry-commonjs-interop',\n transform(code: string, id: string) {\n if (id !== COMMONJS_HELPERS_ID || !code.includes(BROKEN_NAMESPACE_CHECK)) {\n return null;\n }\n return { code: code.replace(BROKEN_NAMESPACE_CHECK, FIXED_NAMESPACE_CHECK), map: null };\n },\n };\n}\n\n/**\n * Rollup plugin that runs the orchestrion code transform on the bundled output.\n *\n * Use when bundling a Node app with Rollup. For unbundled Node processes use the\n * runtime hook instead (`node --import @sentry/node/orchestrion app.js`).\n *\n * @example\n * ```ts\n * // rollup.config.js\n * import { sentryOrchestrionPlugin } from '@sentry/server-utils/orchestrion/rollup';\n * export default { plugins: [sentryOrchestrionPlugin()] };\n * ```\n */\nexport function sentryOrchestrionPlugin(options: PluginOptions = {}): Plugin {\n if (options.buildTimeInstrumentation === false) {\n // Inert plugin — no code transform, so no instrumentation lands in the bundle.\n return { name: 'sentry-orchestrion-disabled' };\n }\n\n const moduleNames = instrumentedModuleNames(options.instrumentations);\n\n // Rolldown omits `external` from the normalized options passed to\n // `buildStart` (function-typed options don't cross its Rust/JS boundary —\n // rolldown/rolldown#1041), so capture the raw value for the probe below.\n let rawExternal: ExternalOption | undefined;\n\n return {\n ...codeTransformer(orchestrionTransformOptions(options)),\n options(inputOptions: InputOptions): null {\n rawExternal = inputOptions.external;\n return null;\n },\n // The module-injected snippet imports `@sentry/server-utils` from INSIDE\n // transformed `node_modules` files. Under isolated installs (pnpm) that bare\n // specifier doesn't resolve from an instrumented package's location, so when\n // normal resolution fails, fall back to this package's own resolution so it\n // gets bundled from its real on-disk path.\n //\n // Forward `options` unchanged: it carries the `custom` metadata `@rollup/plugin-commonjs`\n // uses to recognize a `require()` it is already resolving. Drop it and that plugin warns\n // (THIS_RESOLVE_WITHOUT_OPTIONS), then abandons the resolution.\n async resolveId(\n this: PluginContext,\n source: string,\n importer: string | undefined,\n options: Parameters<ResolveIdHook>[2],\n ) {\n if (source !== SNIPPET_IMPORT_SPECIFIER) {\n return null;\n }\n const resolved = await this.resolve(source, importer, { ...options, skipSelf: true });\n if (resolved) {\n return resolved;\n }\n return resolveOrchestrionRuntimeRequest(source) ?? null;\n },\n buildStart(this: PluginContext, rollupOptions: NormalizedInputOptions): void {\n // An externalized dependency never passes through the code transform, so\n // its diagnostics_channel calls are silently never injected. Rollup has\n // normalized `external` into a single predicate by the time buildStart\n // runs; Rolldown doesn't provide it here at all, so probe the raw value\n // captured in the `options` hook instead.\n const externalizedModules = moduleNames.filter(name =>\n typeof rollupOptions.external === 'function'\n ? rollupOptions.external(name, undefined, false)\n : rawExternal != null && rawExternalMatchesModule(rawExternal, name),\n );\n if (externalizedModules.length > 0) {\n this.warn(externalizedModulesWarning(externalizedModules));\n }\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;AAwBA,SAAS,yBAAyB,UAA0B,MAAuB;CACjF,IAAI,OAAO,aAAa,YACtB,OAAO,CAAC,CAAC,SAAS,MAAM,KAAA,GAAW,KAAK;CAG1C,QADgB,MAAM,QAAQ,QAAQ,IAAI,WAAW,CA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AAK,KAAK,2BAA2B,mBAAmB,CAAC;EAE7D;CACF;AACF"}
1
+ {"version":3,"file":"rollup.js","names":["codeTransformer"],"sources":["../../../../src/orchestrion/bundler/rollup.ts"],"sourcesContent":["import { isBuiltin } from 'node:module';\n\nimport codeTransformer from '@apm-js-collab/code-transformer-bundler-plugins/rollup';\nimport type {\n ExternalOption,\n InputOptions,\n NormalizedInputOptions,\n Plugin,\n PluginContext,\n ResolveIdHook,\n} from 'rollup';\n\nexport type { Plugin as RollupPlugin } from 'rollup';\nimport { instrumentedModuleNames } from '../config';\nimport type { PluginOptions } from './options';\nimport { externalEntryMatchesModule, externalizedModulesWarning, orchestrionTransformOptions } from './options';\nimport { resolveOrchestrionRuntimeRequest, SNIPPET_IMPORT_SPECIFIER } from './resolve';\n\n/**\n * Whether a raw (un-normalized) `external` input option marks `name` as\n * external. String entries use the shared subpath-aware matching so a\n * `'mysql/lib/...'` entry flags `mysql`, consistent with the esbuild and\n * webpack plugins.\n */\nfunction rawExternalMatchesModule(external: ExternalOption, name: string): boolean {\n if (typeof external === 'function') {\n return !!external(name, undefined, false);\n }\n const entries = Array.isArray(external) ? external : [external];\n return entries.some(entry =>\n typeof entry === 'string' ? externalEntryMatchesModule(entry, name) : entry.test(name),\n );\n}\n\n/**\n * Structural subset of `@rollup/plugin-commonjs` options, so this package needs no dependency on\n * the plugin for its types.\n */\nexport interface CommonJSInteropOptions {\n requireReturnsDefault: (id: string) => boolean | 'auto' | 'preferred' | 'namespace';\n ignoreTryCatch: (id: string) => boolean;\n}\n\n/**\n * `@rollup/plugin-commonjs` options for builds that bundle CommonJS packages while their\n * dependencies stay external. Builtin `require()`s unwrap to the module (a namespace breaks\n * direct calls) and convert inside `try` blocks (a bare `require` throws in ESM output).\n * Externals keep `'auto'`, which {@link sentryCommonJSInteropPlugin} fixes for Node >= 23, Deno and Bun.\n */\nexport function commonJSInteropOptions(): CommonJSInteropOptions {\n return {\n requireReturnsDefault: id => (isBuiltin(id) ? true : 'auto'),\n ignoreTryCatch: id => !isBuiltin(id),\n };\n}\n\nconst COMMONJS_HELPERS_ID = '\\0commonjsHelpers.js';\n\n// The plugin's `'auto'` helper unwraps a required external module only when `default` is the\n// sole key on its namespace. Node >= 23 and Deno add a `'module.exports'` key to every CommonJS\n// namespace (nodejs/node#53848), so ignoring that key restores the check there. Bun adds a key\n// for each own property of `module.exports`, which for a function includes the non-enumerable\n// `length` and `name`. So on Bun, a namespace whose keys all mirror its function default, at least\n// one of them a non-enumerable property, is unwrapped. An ES module namespace can match only when\n// its named exports equal the same properties of its default export, which loses nothing.\nconst BROKEN_NAMESPACE_CHECK = 'Object.keys(n).length === 1';\nconst FIXED_NAMESPACE_CHECK =\n \"(Object.keys(n).filter(k => k !== 'module.exports').length === 1 || (typeof n['default'] === 'function' && Object.keys(n).every(k => k === 'default' || k === 'module.exports' || n[k] === n['default'][k]) && Object.keys(n).some(k => Object.getOwnPropertyDescriptor(n['default'], k)?.enumerable === false)))\";\n\n/**\n * Fixes `@rollup/plugin-commonjs`' `'auto'` interop for Node >= 23, Deno and Bun by patching the\n * broken namespace check in its helpers module. The patch applies only while the exact broken\n * expression exists, so it retires itself once the plugin is fixed upstream.\n */\nexport function sentryCommonJSInteropPlugin(): Plugin {\n return {\n name: 'sentry-commonjs-interop',\n transform(code: string, id: string) {\n if (id !== COMMONJS_HELPERS_ID || !code.includes(BROKEN_NAMESPACE_CHECK)) {\n return null;\n }\n return { code: code.replace(BROKEN_NAMESPACE_CHECK, FIXED_NAMESPACE_CHECK), map: null };\n },\n };\n}\n\n/**\n * Rollup plugin that runs the orchestrion code transform on the bundled output.\n *\n * Use when bundling a Node app with Rollup. For unbundled Node processes use the\n * runtime hook instead (`node --import @sentry/node/orchestrion app.js`).\n *\n * @example\n * ```ts\n * // rollup.config.js\n * import { sentryOrchestrionPlugin } from '@sentry/server-utils/orchestrion/rollup';\n * export default { plugins: [sentryOrchestrionPlugin()] };\n * ```\n */\nexport function sentryOrchestrionPlugin(options: PluginOptions = {}): Plugin {\n if (options.buildTimeInstrumentation === false) {\n // Inert plugin — no code transform, so no instrumentation lands in the bundle.\n return { name: 'sentry-orchestrion-disabled' };\n }\n\n const moduleNames = instrumentedModuleNames(options.instrumentations);\n\n // Rolldown omits `external` from the normalized options passed to\n // `buildStart` (function-typed options don't cross its Rust/JS boundary —\n // rolldown/rolldown#1041), so capture the raw value for the probe below.\n let rawExternal: ExternalOption | undefined;\n\n return {\n ...codeTransformer(orchestrionTransformOptions(options)),\n options(inputOptions: InputOptions): null {\n rawExternal = inputOptions.external;\n return null;\n },\n // The module-injected snippet imports `@sentry/server-utils` from INSIDE\n // transformed `node_modules` files. Under isolated installs (pnpm) that bare\n // specifier doesn't resolve from an instrumented package's location, so when\n // normal resolution fails, fall back to this package's own resolution so it\n // gets bundled from its real on-disk path.\n //\n // Forward `options` unchanged: it carries the `custom` metadata `@rollup/plugin-commonjs`\n // uses to recognize a `require()` it is already resolving. Drop it and that plugin warns\n // (THIS_RESOLVE_WITHOUT_OPTIONS), then abandons the resolution.\n async resolveId(\n this: PluginContext,\n source: string,\n importer: string | undefined,\n options: Parameters<ResolveIdHook>[2],\n ) {\n if (source !== SNIPPET_IMPORT_SPECIFIER) {\n return null;\n }\n const resolved = await this.resolve(source, importer, { ...options, skipSelf: true });\n if (resolved) {\n return resolved;\n }\n return resolveOrchestrionRuntimeRequest(source) ?? null;\n },\n buildStart(this: PluginContext, rollupOptions: NormalizedInputOptions): void {\n // An externalized dependency never passes through the code transform, so\n // its diagnostics_channel calls are silently never injected. Rollup has\n // normalized `external` into a single predicate by the time buildStart\n // runs; Rolldown doesn't provide it here at all, so probe the raw value\n // captured in the `options` hook instead.\n const externalizedModules = moduleNames.filter(name =>\n typeof rollupOptions.external === 'function'\n ? rollupOptions.external(name, undefined, false)\n : rawExternal != null && rawExternalMatchesModule(rawExternal, name),\n );\n if (externalizedModules.length > 0) {\n this.warn(externalizedModulesWarning(externalizedModules));\n }\n },\n };\n}\n"],"mappings":";;;;;;;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AAsB,YAAY,QAAO,SAC7C,OAAO,cAAc,aAAa,aAC9B,cAAc,SAAS,MAAM,KAAA,GAAW,KAAK,IAC7C,eAAe,QAAQ,yBAAyB,aAAa,IAAI,CACvE;GACA,IAAI,oBAAoB,SAAS,GAC/B,KAAK,KAAK,2BAA2B,mBAAmB,CAAC;EAE7D;CACF;AACF"}
@@ -10,7 +10,7 @@ const googleGenAiConfig = [
10
10
  channelName: "generate-content",
11
11
  module: {
12
12
  name: "@google/genai",
13
- versionRange: ">=0.10.0 <3",
13
+ versionRange: ">=0.10.0 <4",
14
14
  filePath
15
15
  },
16
16
  functionQuery: {
@@ -22,7 +22,7 @@ const googleGenAiConfig = [
22
22
  channelName: "embed-content",
23
23
  module: {
24
24
  name: "@google/genai",
25
- versionRange: ">=0.10.0 <3",
25
+ versionRange: ">=0.10.0 <4",
26
26
  filePath
27
27
  },
28
28
  functionQuery: {
@@ -35,7 +35,7 @@ const googleGenAiConfig = [
35
35
  channelName: "chat",
36
36
  module: {
37
37
  name: "@google/genai",
38
- versionRange: ">=0.10.0 <3",
38
+ versionRange: ">=0.10.0 <4",
39
39
  filePath
40
40
  },
41
41
  functionQuery: {
@@ -43,13 +43,27 @@ const googleGenAiConfig = [
43
43
  methodName,
44
44
  kind: "Auto"
45
45
  }
46
- })))
46
+ }))),
47
+ ...NODE_DIST_FILES.map((filePath) => ({
48
+ channelName: "decide",
49
+ module: {
50
+ name: "@google/genai",
51
+ versionRange: ">=3.2.0 <4",
52
+ filePath
53
+ },
54
+ functionQuery: {
55
+ className: "GeminiNextGenDecisions",
56
+ methodName: "create",
57
+ kind: "Async"
58
+ }
59
+ }))
47
60
  ];
48
61
  const googleGenAiModuleNames = getModuleNames(googleGenAiConfig);
49
62
  const googleGenAiChannels = {
50
63
  GOOGLE_GENAI_GENERATE_CONTENT: "orchestrion:@google/genai:generate-content",
51
64
  GOOGLE_GENAI_EMBED_CONTENT: "orchestrion:@google/genai:embed-content",
52
- GOOGLE_GENAI_CHAT: "orchestrion:@google/genai:chat"
65
+ GOOGLE_GENAI_CHAT: "orchestrion:@google/genai:chat",
66
+ GOOGLE_GENAI_DECIDE: "orchestrion:@google/genai:decide"
53
67
  };
54
68
  export { googleGenAiChannels, googleGenAiConfig, googleGenAiModuleNames };
55
69
 
@@ -1 +1 @@
1
- {"version":3,"file":"google-genai.js","names":[],"sources":["../../../../src/orchestrion/config/google-genai.ts"],"sourcesContent":["import type { InstrumentationConfig } from '../apmTypes';\n\nimport { getModuleNames } from './module-names';\n\n// `@google/genai` ships one bundled file per module format and the matcher compares `filePath` exactly,\n// so we list every file the `node` export condition resolves to across the supported range: `index.js`\n// (ESM+CJS for <0.15.0, CJS for <1.1.0), `index.mjs` (ESM for >=0.15.0), and `index.cjs` (CJS for >=1.1.0).\n// A file that doesn't exist in a given version simply never matches, so listing all three is safe.\nconst NODE_DIST_FILES = ['dist/node/index.js', 'dist/node/index.mjs', 'dist/node/index.cjs'];\n\nexport const googleGenAiConfig = [\n // `generateContent`/`generateContentStream` are arrow properties assigned in the constructor, not class\n // methods, so they need `expressionName` rather than `className`/`methodName`.\n ...NODE_DIST_FILES.flatMap(filePath =>\n (['generateContent', 'generateContentStream'] as const).map(expressionName => ({\n channelName: 'generate-content',\n module: { name: '@google/genai', versionRange: '>=0.10.0 <3', filePath },\n functionQuery: { expressionName, kind: 'Auto' as const },\n })),\n ),\n // `embedContent` is a real class method in v1 but a constructor-assigned arrow in v2; the\n // `className`/`methodName` selector matches both shapes.\n ...NODE_DIST_FILES.map(filePath => ({\n channelName: 'embed-content',\n module: { name: '@google/genai', versionRange: '>=0.10.0 <3', filePath },\n functionQuery: { className: 'Models', methodName: 'embedContent', kind: 'Auto' as const },\n })),\n // `sendMessage`/`sendMessageStream` internally delegate to `Models.generateContent(Stream)`; the\n // subscriber suppresses that nested `generate-content` event so a chat call yields a single span.\n ...NODE_DIST_FILES.flatMap(filePath =>\n (['sendMessage', 'sendMessageStream'] as const).map(methodName => ({\n channelName: 'chat',\n module: { name: '@google/genai', versionRange: '>=0.10.0 <3', filePath },\n functionQuery: { className: 'Chat', methodName, kind: 'Auto' as const },\n })),\n ),\n] satisfies InstrumentationConfig[];\n\nexport const googleGenAiModuleNames = getModuleNames(googleGenAiConfig);\n\nexport const googleGenAiChannels = {\n GOOGLE_GENAI_GENERATE_CONTENT: 'orchestrion:@google/genai:generate-content',\n GOOGLE_GENAI_EMBED_CONTENT: 'orchestrion:@google/genai:embed-content',\n GOOGLE_GENAI_CHAT: 'orchestrion:@google/genai:chat',\n} as const;\n"],"mappings":";;AAQA,MAAM,kBAAkB;CAAC;CAAsB;CAAuB;AAAqB;AAE3F,MAAa,oBAAoB;CAG/B,GAAG,gBAAgB,SAAQ,aACxB,CAAC,mBAAmB,uBAAuB,CAAC,CAAW,KAAI,oBAAmB;EAC7E,aAAa;EACb,QAAQ;GAAE,MAAM;GAAiB,cAAc;GAAe;EAAS;EACvE,eAAe;GAAE;GAAgB,MAAM;EAAgB;CACzD,EAAE,CACJ;CAGA,GAAG,gBAAgB,KAAI,cAAa;EAClC,aAAa;EACb,QAAQ;GAAE,MAAM;GAAiB,cAAc;GAAe;EAAS;EACvE,eAAe;GAAE,WAAW;GAAU,YAAY;GAAgB,MAAM;EAAgB;CAC1F,EAAE;CAGF,GAAG,gBAAgB,SAAQ,aACxB,CAAC,eAAe,mBAAmB,CAAC,CAAW,KAAI,gBAAe;EACjE,aAAa;EACb,QAAQ;GAAE,MAAM;GAAiB,cAAc;GAAe;EAAS;EACvE,eAAe;GAAE,WAAW;GAAQ;GAAY,MAAM;EAAgB;CACxE,EAAE,CACJ;AACF;AAEA,MAAa,yBAAyB,eAAe,iBAAiB;AAEtE,MAAa,sBAAsB;CACjC,+BAA+B;CAC/B,4BAA4B;CAC5B,mBAAmB;AACrB"}
1
+ {"version":3,"file":"google-genai.js","names":[],"sources":["../../../../src/orchestrion/config/google-genai.ts"],"sourcesContent":["import type { InstrumentationConfig } from '../apmTypes';\n\nimport { getModuleNames } from './module-names';\n\n// `@google/genai` ships one bundled file per module format and the matcher compares `filePath` exactly,\n// so we list every file the `node` export condition resolves to across the supported range: `index.js`\n// (ESM+CJS for <0.15.0, CJS for <1.1.0), `index.mjs` (ESM for >=0.15.0), and `index.cjs` (CJS for >=1.1.0).\n// A file that doesn't exist in a given version simply never matches, so listing all three is safe.\nconst NODE_DIST_FILES = ['dist/node/index.js', 'dist/node/index.mjs', 'dist/node/index.cjs'];\n\nexport const googleGenAiConfig = [\n // `generateContent`/`generateContentStream` are arrow properties assigned in the constructor, not class\n // methods, so they need `expressionName` rather than `className`/`methodName`.\n ...NODE_DIST_FILES.flatMap(filePath =>\n (['generateContent', 'generateContentStream'] as const).map(expressionName => ({\n channelName: 'generate-content',\n module: { name: '@google/genai', versionRange: '>=0.10.0 <4', filePath },\n functionQuery: { expressionName, kind: 'Auto' as const },\n })),\n ),\n // `embedContent` is a real class method in v1 but a constructor-assigned arrow in v2; the\n // `className`/`methodName` selector matches both shapes.\n ...NODE_DIST_FILES.map(filePath => ({\n channelName: 'embed-content',\n module: { name: '@google/genai', versionRange: '>=0.10.0 <4', filePath },\n functionQuery: { className: 'Models', methodName: 'embedContent', kind: 'Auto' as const },\n })),\n // `sendMessage`/`sendMessageStream` internally delegate to `Models.generateContent(Stream)`; the\n // subscriber suppresses that nested `generate-content` event so a chat call yields a single span.\n ...NODE_DIST_FILES.flatMap(filePath =>\n (['sendMessage', 'sendMessageStream'] as const).map(methodName => ({\n channelName: 'chat',\n module: { name: '@google/genai', versionRange: '>=0.10.0 <4', filePath },\n functionQuery: { className: 'Chat', methodName, kind: 'Auto' as const },\n })),\n ),\n // `client.decisions` (`@google/genai` >= 3.2.0) returns typed answers rather than generated content.\n ...NODE_DIST_FILES.map(filePath => ({\n channelName: 'decide',\n module: { name: '@google/genai', versionRange: '>=3.2.0 <4', filePath },\n functionQuery: { className: 'GeminiNextGenDecisions', methodName: 'create', kind: 'Async' as const },\n })),\n] satisfies InstrumentationConfig[];\n\nexport const googleGenAiModuleNames = getModuleNames(googleGenAiConfig);\n\nexport const googleGenAiChannels = {\n GOOGLE_GENAI_GENERATE_CONTENT: 'orchestrion:@google/genai:generate-content',\n GOOGLE_GENAI_EMBED_CONTENT: 'orchestrion:@google/genai:embed-content',\n GOOGLE_GENAI_CHAT: 'orchestrion:@google/genai:chat',\n GOOGLE_GENAI_DECIDE: 'orchestrion:@google/genai:decide',\n} as const;\n"],"mappings":";;AAQA,MAAM,kBAAkB;CAAC;CAAsB;CAAuB;AAAqB;AAE3F,MAAa,oBAAoB;CAG/B,GAAG,gBAAgB,SAAQ,aACxB,CAAC,mBAAmB,uBAAuB,CAAC,CAAW,KAAI,oBAAmB;EAC7E,aAAa;EACb,QAAQ;GAAE,MAAM;GAAiB,cAAc;GAAe;EAAS;EACvE,eAAe;GAAE;GAAgB,MAAM;EAAgB;CACzD,EAAE,CACJ;CAGA,GAAG,gBAAgB,KAAI,cAAa;EAClC,aAAa;EACb,QAAQ;GAAE,MAAM;GAAiB,cAAc;GAAe;EAAS;EACvE,eAAe;GAAE,WAAW;GAAU,YAAY;GAAgB,MAAM;EAAgB;CAC1F,EAAE;CAGF,GAAG,gBAAgB,SAAQ,aACxB,CAAC,eAAe,mBAAmB,CAAC,CAAW,KAAI,gBAAe;EACjE,aAAa;EACb,QAAQ;GAAE,MAAM;GAAiB,cAAc;GAAe;EAAS;EACvE,eAAe;GAAE,WAAW;GAAQ;GAAY,MAAM;EAAgB;CACxE,EAAE,CACJ;CAEA,GAAG,gBAAgB,KAAI,cAAa;EAClC,aAAa;EACb,QAAQ;GAAE,MAAM;GAAiB,cAAc;GAAc;EAAS;EACtE,eAAe;GAAE,WAAW;GAA0B,YAAY;GAAU,MAAM;EAAiB;CACrG,EAAE;AACJ;AAEA,MAAa,yBAAyB,eAAe,iBAAiB;AAEtE,MAAa,sBAAsB;CACjC,+BAA+B;CAC/B,4BAA4B;CAC5B,mBAAmB;CACnB,qBAAqB;AACvB"}
@@ -1 +1 @@
1
- {"type":"module","version":"11.13.0","sideEffects":false}
1
+ {"type":"module","version":"11.14.0","sideEffects":false}