@sentry/server-utils 11.19.0 → 11.20.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.
- package/build/cjs/index.js +96 -73
- package/build/cjs/index.js.map +1 -1
- package/build/esm/ai/vercel-ai/index.js +1 -12
- package/build/esm/ai/vercel-ai/index.js.map +1 -1
- package/build/esm/integrations/nitro/captureTracingEvents.js +4 -3
- package/build/esm/integrations/nitro/captureTracingEvents.js.map +1 -1
- package/build/esm/integrations/nitro/index.js +2 -2
- package/build/esm/integrations/nitro/index.js.map +1 -1
- package/build/esm/integrations/openai-compatible.js.map +1 -1
- package/build/esm/integrations/vercel-ai/vercel-ai-dc-subscriber.js +70 -42
- package/build/esm/integrations/vercel-ai/vercel-ai-dc-subscriber.js.map +1 -1
- package/build/esm/integrations/vercel-ai/vercel-ai-orchestrion-subscriber.js +21 -16
- package/build/esm/integrations/vercel-ai/vercel-ai-orchestrion-subscriber.js.map +1 -1
- package/build/esm/package.json +1 -1
- package/build/types/ai/vercel-ai/index.d.ts +0 -6
- package/build/types/ai/vercel-ai/index.d.ts.map +1 -1
- package/build/types/integrations/nitro/captureTracingEvents.d.ts +3 -1
- package/build/types/integrations/nitro/captureTracingEvents.d.ts.map +1 -1
- package/build/types/integrations/nitro/index.d.ts +6 -0
- package/build/types/integrations/nitro/index.d.ts.map +1 -1
- package/build/types/integrations/openai-compatible.d.ts.map +1 -1
- package/build/types/integrations/vercel-ai/vercel-ai-dc-subscriber.d.ts.map +1 -1
- package/package.json +3 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"vercel-ai-dc-subscriber.js","names":[],"sources":["../../../../src/integrations/vercel-ai/vercel-ai-dc-subscriber.ts"],"sourcesContent":["/* eslint-disable max-lines */\nimport {\n GEN_AI_CONVERSATION_ID,\n GEN_AI_COST_TOTAL_TOKENS,\n GEN_AI_EMBEDDINGS_INPUT,\n GEN_AI_FUNCTION_ID,\n GEN_AI_INPUT_MESSAGES,\n GEN_AI_OPERATION_NAME,\n GEN_AI_OUTPUT_MESSAGES,\n GEN_AI_PROVIDER_NAME,\n GEN_AI_REQUEST_MODEL,\n GEN_AI_RESPONSE_FINISH_REASONS,\n GEN_AI_RESPONSE_ID,\n GEN_AI_RESPONSE_MODEL,\n GEN_AI_RESPONSE_STREAMING,\n GEN_AI_SYSTEM_INSTRUCTIONS,\n GEN_AI_TOOL_CALL_ARGUMENTS,\n GEN_AI_TOOL_CALL_RESULT,\n GEN_AI_TOOL_DEFINITIONS,\n GEN_AI_TOOL_DESCRIPTION,\n GEN_AI_TOOL_NAME,\n GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS,\n GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS,\n GEN_AI_USAGE_INPUT_TOKENS,\n GEN_AI_USAGE_OUTPUT_TOKENS,\n GEN_AI_USAGE_REASONING_OUTPUT_TOKENS,\n GEN_AI_USAGE_TOTAL_TOKENS,\n SENTRY_OP,\n SENTRY_ORIGIN,\n VERCEL_AI_SETTINGS_CONTEXT_KEY_BASE,\n VERCEL_AI_TOOL_CALL_CONTEXT_KEY_BASE,\n} from '@sentry/conventions/attributes';\nimport {\n GEN_AI_DECIDE,\n GEN_AI_EMBEDDINGS,\n GEN_AI_EXECUTE_TOOL,\n GEN_AI_EXTRACT,\n GEN_AI_GENERATE_CONTENT,\n GEN_AI_INVOKE_AGENT,\n GEN_AI_RERANK,\n} from '@sentry/conventions/op';\nimport type { Span, SpanAttributes } from '@sentry/core';\nimport {\n _INTERNAL_skipAiProviderWrapping,\n captureException,\n getActiveSpan,\n getClient,\n isObjectLike,\n isPlainObject,\n SPAN_STATUS_ERROR,\n spanToJSON,\n spanToTraceContext,\n startInactiveSpan,\n stringify,\n withScope,\n} from '@sentry/core';\nimport type { TracingChannel } from 'node:diagnostics_channel';\nimport { GEN_AI_TOOL_CALL_ID_ATTRIBUTE } from '../../ai/core/gen-ai-attributes';\nimport {\n type GenAiSpanHooks,\n type GenAiSpanResult,\n runGenAiSpanEnd,\n runGenAiSpanStart,\n} from '../../ai/core/span-hooks';\nimport { isEveGenAiRecordingDefault } from './gen-ai-recording-mode';\nimport {\n type GenAiCallOptions,\n type GenAiOptions,\n getEvaluationOutputMessages,\n resolveRecordingOption,\n} from '../../ai/core/utils';\nimport { getProviderMetadataAttributes, LAST_STEP_ONLY_USAGE_KEYS } from '../../ai/vercel-ai';\nimport { WORKERS_AI_INTEGRATION_NAME } from '../../ai/workers-ai/constants';\nimport { bindTracingChannelToSpan } from '../../tracing-channel';\nimport { toExtractAnswers, toExtractFields, toExtractState } from './extract';\nimport {\n asNumber,\n asString,\n isReadableStream,\n mapObjectValues,\n type StreamedModelCallResult,\n sum,\n tapModelCallStream,\n} from './util';\n\n/**\n * The single tracing channel the `ai` package (>= 7) publishes all telemetry lifecycle events to\n * via `node:diagnostics_channel`. Events are discriminated by their `type` field.\n * @see https://github.com/vercel/ai/pull/15660\n */\nexport const AI_SDK_TELEMETRY_TRACING_CHANNEL = 'ai:telemetry';\n\nconst ORIGIN = 'auto.ai.vercelai';\n\n// `gen_ai.operation.name` values, keyed to the span op they map to.\nconst GEN_AI_OPERATION_SPAN_OPS = {\n embeddings: GEN_AI_EMBEDDINGS,\n // `GEN_AI_RERANK` is deprecated because the product doesn't support rerank spans, but we keep\n // emitting it so existing rerank spans keep their op.\n // oxlint-disable-next-line typescript/no-deprecated\n rerank: GEN_AI_RERANK,\n decide: GEN_AI_DECIDE,\n extract: GEN_AI_EXTRACT,\n invoke_agent: GEN_AI_INVOKE_AGENT,\n execute_tool: GEN_AI_EXECUTE_TOOL,\n // The model-call op matches the Vercel AI OTel integration (`gen_ai.generate_content`) rather than\n // the generic `gen_ai.chat`, so v6 (OTel) and v7 (channel) produce the same spans.\n generate_content: GEN_AI_GENERATE_CONTENT,\n} as const;\n\ntype GenAiOperation = keyof typeof GEN_AI_OPERATION_SPAN_OPS;\n\n// Subset of the `vercel.ai.*` passthrough attributes the OTel integration emits that we reproduce.\nconst VERCEL_AI_OPERATION_ID_ATTRIBUTE = 'vercel.ai.operationId';\nconst VERCEL_AI_MODEL_PROVIDER_ATTRIBUTE = 'vercel.ai.model.provider';\nconst VERCEL_AI_SETTINGS_MAX_RETRIES_ATTRIBUTE = 'vercel.ai.settings.maxRetries';\nconst VERCEL_AI_TELEMETRY_METADATA_ATTRIBUTE_PREFIX = 'vercel.ai.telemetry.metadata.';\n\n// Tracks the top-level operationId (and whether it streams) per `callId` so a model-call span can\n// name its `doGenerate`/`doStream` operation the same way the OTel integration does. `isStream` is\n// the authoritative event-type signal rather than a substring check on the (possibly custom)\n// operationId. Cleared when the top-level span ends.\nconst operationIdByCallId = new Map<string, { operationId: string; isStream: boolean }>();\n\n// Per-operation map of tool name → description, harvested from a model-call /\n// top-level event's `tools` (keyed by the shared `callId`). The AI SDK's\n// `executeTool` event doesn't carry the tool's description, so we backfill it\n// onto the tool span here — without relying on the OTel `vercelAiEventProcessor`\n// (which isn't registered in channel/orchestrion mode). Cleared with the\n// operation. Only populated when inputs are recorded, matching the OTel path\n// (which sources descriptions from the recorded `tool.definitions`).\nconst toolDescriptionsByCallId = new Map<string, Map<string, string>>();\n\n// A streamed `streamText` operation's own channel result is always `undefined` (the SDK exposes the\n// stream only on the model call), so its `invoke_agent` span can't be enriched from the channel. We\n// key the span by `callId` and enrich it as each streamed model call drains — the model calls flush\n// before the operation's own span ends. The running token sum lives on the span's own attributes.\nconst invokeAgentSpanByCallId = new Map<string, Span>();\n\n// Only an operation's start event carries `runtimeContext`; its model-call and tool events copy the\n// resulting attributes from here. Cleared with the operation.\nconst runtimeContextAttributesByCallId = new Map<string, SpanAttributes>();\n\n// Only top-level operations own the `callId` → operationId mapping; `step`/`languageModelCall`/\n// `executeTool` share the parent's `callId`, so they must not clear it.\nconst ROOT_OPERATION_TYPES = new Set<ChannelEventType>([\n 'generateText',\n 'streamText',\n 'streamObject',\n 'generateObject',\n 'embed',\n 'embedMany',\n 'rerank',\n]);\n\n// Operations whose `providerMetadata` cost covers only one of their provider calls: the last step of a\n// text or object operation, whose cost the `generate_content` spans carry, or one `embedMany` chunk.\nconst PARTIAL_COST_OPERATION_TYPES = new Set<ChannelEventType>([\n 'generateText',\n 'streamText',\n 'streamObject',\n 'generateObject',\n 'embedMany',\n]);\n\n/** Drop the per-operation `callId` maps once the owning top-level operation settles (success or error). */\nexport function clearOperationId(data: VercelAiChannelMessage): void {\n if (!ROOT_OPERATION_TYPES.has(data.type)) {\n return;\n }\n const callId = asString(data.event.callId);\n if (callId) {\n clearOperationCallId(callId);\n }\n}\n\n/**\n * Drop the per-operation `callId` maps for a single id. The v6 orchestrion adapter uses this to clear a\n * `streamText`/`streamObject` operation only after its lazily-run model call settles — the operation's own\n * span ends synchronously (when the call returns) but the model call runs later as the stream is consumed,\n * and it still needs the operation's `operationId`/`isStream` entry to name itself `ai.streamText.doStream`\n * (or `ai.streamObject.doStream`).\n */\nexport function clearOperationCallId(callId: string): void {\n operationIdByCallId.delete(callId);\n toolDescriptionsByCallId.delete(callId);\n invokeAgentSpanByCallId.delete(callId);\n runtimeContextAttributesByCallId.delete(callId);\n}\n\n/**\n * The OpenAI Conversations API id from `providerOptions.openai.conversation` (or `azure`): the one\n * provider-level value that is the same on every turn. A `Sentry.setConversationId()` value still wins,\n * since `conversationIdIntegration` writes it on `spanStart`, after these start attributes.\n */\nfunction getOpenAiConversationId(providerOptions: unknown): string | undefined {\n if (!isObjectLike(providerOptions)) {\n return undefined;\n }\n for (const key of ['openai', 'azure']) {\n const options = providerOptions[key];\n const conversation = isObjectLike(options) ? asString(options.conversation) : undefined;\n if (conversation) {\n return conversation;\n }\n }\n return undefined;\n}\n\n/** The `gen_ai.conversation.id` already on the active span, which for a child event is its operation span. */\nfunction getActiveSpanConversationId(): string | undefined {\n const active = getActiveSpan();\n return active ? asString(spanToJSON(active).attributes[GEN_AI_CONVERSATION_ID]) : undefined;\n}\n\n/**\n * `providerMetadata` is last-step only; drop derived usage on spans that report an aggregate.\n *\n * Reasoning goes only when it accompanies a recomputed output (Google), because dropping that\n * output leaves the span's own count reasoning-exclusive and the documented subset relationship\n * would not hold. A provider that reports reasoning against an already-inclusive output (OpenAI)\n * keeps it.\n */\nfunction dropLastStepOnlyUsage(providerAttributes: Record<string, number | string>, type: ChannelEventType): void {\n if (!ROOT_OPERATION_TYPES.has(type)) {\n return;\n }\n const hasRecomputedOutput = GEN_AI_USAGE_OUTPUT_TOKENS in providerAttributes;\n for (const key of LAST_STEP_ONLY_USAGE_KEYS) {\n // oxlint-disable-next-line typescript/no-dynamic-delete\n delete providerAttributes[key];\n }\n if (hasRecomputedOutput) {\n // oxlint-disable-next-line typescript/no-dynamic-delete\n delete providerAttributes[GEN_AI_USAGE_REASONING_OUTPUT_TOKENS];\n }\n if (PARTIAL_COST_OPERATION_TYPES.has(type)) {\n // oxlint-disable-next-line typescript/no-dynamic-delete\n delete providerAttributes[GEN_AI_COST_TOTAL_TOKENS];\n }\n}\n\n/** Record tool name → description from an event's `tools`, so tool spans can backfill the description. */\nfunction recordToolDescriptions(callId: string | undefined, tools: unknown): void {\n if (!callId || !Array.isArray(tools)) {\n return;\n }\n let descriptions = toolDescriptionsByCallId.get(callId);\n for (const tool of tools) {\n if (isObjectLike(tool) && typeof tool.name === 'string' && typeof tool.description === 'string') {\n descriptions = descriptions ?? new Map();\n if (!descriptions.has(tool.name)) {\n descriptions.set(tool.name, tool.description);\n }\n }\n }\n if (descriptions) {\n toolDescriptionsByCallId.set(callId, descriptions);\n }\n}\n\n/**\n * Resolve a tool's description, preferring the per-operation map (populated from the model-call /\n * top-level event's `tools`, v7) and falling back to a `tools` collection on the event itself —\n * which may be an array of `{ name, description }` or a record keyed by tool name (v6).\n */\nfunction resolveToolDescription(callId: string | undefined, toolName: string, tools: unknown): string | undefined {\n const fromMap = callId ? toolDescriptionsByCallId.get(callId)?.get(toolName) : undefined;\n if (fromMap) {\n return fromMap;\n }\n if (Array.isArray(tools)) {\n const match = tools.find(tool => isObjectLike(tool) && tool.name === toolName);\n return isObjectLike(match) ? asString(match.description) : undefined;\n }\n if (isObjectLike(tools)) {\n const tool = tools[toolName];\n return isObjectLike(tool) ? asString(tool.description) : undefined;\n }\n return undefined;\n}\n\n/** The lifecycle event types the `ai:telemetry` channel can carry. */\nexport type ChannelEventType =\n | 'generateText'\n | 'streamText'\n | 'streamObject'\n | 'generateObject'\n | 'step'\n | 'languageModelCall'\n | 'executeTool'\n | 'embed'\n | 'embedMany'\n | 'rerank'\n | 'experimental_evaluate'\n | 'experimental_decide'\n | 'experimental_extract';\n\n/**\n * The context object the AI SDK passes through one tracing-channel call. It is the same object\n * identity across `start`/`end`/`asyncEnd`/`error`, and Node's `tracingChannel` attaches\n * `result`/`error` to it as the traced promise settles.\n */\nexport interface VercelAiChannelMessage {\n type: ChannelEventType;\n event: Record<string, unknown>;\n result?: unknown;\n error?: unknown;\n}\n\n/**\n * Platform-provided factory that returns a tracing channel for the given channel name. The factory\n * is responsible for, when `start` fires, calling `transformStart(data)` and storing the returned\n * span on `data._sentrySpan` so the subscriber's `asyncEnd`/`error` handlers can read it.\n *\n * Node passes `@sentry/opentelemetry/tracing-channel`, which uses `bindStore` to additionally make\n * the span the active OTel context for the duration of the traced operation. That is what makes\n * nested AI SDK operations (model calls, tool calls) become children of the enclosing span without\n * any manual parent bookkeeping here.\n */\nexport type VercelAiTracingChannelFactory = <T extends object>(name: string) => TracingChannel<T, T>;\n\n/**\n * The call that `recordInputs`/`recordOutputs` decide on, and that the span hooks get: one span, with the AI SDK\n * telemetry event as published.\n */\nexport interface VercelAiCallInfo {\n /** The channel event type, such as `generateText`, `languageModelCall` or `executeTool`. */\n type: ChannelEventType;\n /** The AI SDK telemetry event of the call. */\n event: Record<string, unknown>;\n}\n\n/**\n * Integration options, pinned at subscribe time so we never look the integration up per event. `onSpanEnd` gets the\n * AI SDK result of the call as `response`; for streams it is `undefined`.\n */\nexport type VercelAiChannelOptions = GenAiCallOptions<VercelAiCallInfo> & GenAiSpanHooks<VercelAiCallInfo>;\n\n// The integration-level decision of each span, made at span start in the caller's async context. The rest of the\n// precedence (eve mode, the per-call flags, `dataCollection.genAI`) is applied when it is needed, because whether\n// `ai` withheld the result is only known at span end.\nconst integrationRecordingBySpan = new WeakMap<Span, GenAiOptions>();\n\n// `ai` >= 7.0.163 publishes no channel `result` for calls with `recordInputs`/`recordOutputs: false`. These stay\n// here rather than on the shared channel message, which other subscribers can read.\nexport const fallbackChannelResults = new WeakMap<Span, unknown>();\n\nconst spanEndHooks = new WeakMap<Span, (result: GenAiSpanResult<unknown>) => void>();\n\n/** Runs the `onSpanEnd` hook of a span that `createSpanFromMessage` started. Call it right before the span ends. */\nexport function runVercelAiSpanEnd(span: Span, result: GenAiSpanResult<unknown>): void {\n spanEndHooks.get(span)?.(result);\n}\n\n/**\n * Subscribe Sentry span handlers to the `ai` SDK's native telemetry tracing channel (`ai:telemetry`,\n * available in `ai` >= 7) and emit fully-formed `gen_ai.*` spans directly — no OpenTelemetry span\n * post-processing involved.\n *\n * The integration passes its options in directly (rather than us looking the integration up on every\n * event); the global `dataCollection.genAI` default is still read from the client per event.\n *\n * Safe to always call: on `ai` versions that don't publish to the channel (e.g. < 7) nothing is\n * ever emitted and this is inert, so there is no double-instrumentation against the OTel-based\n * patcher. The integration's `setupOnce` guarantees this runs a single time.\n */\nexport function subscribeVercelAiTracingChannel(\n tracingChannel: VercelAiTracingChannelFactory,\n options: VercelAiChannelOptions = {},\n): void {\n bindTracingChannelToSpan(\n tracingChannel<VercelAiChannelMessage>(AI_SDK_TELEMETRY_TRACING_CHANNEL),\n data => createSpanFromMessage(data, options),\n {\n // The helper ends the span; we enrich it from the settled result first (tokens, output messages,\n // finish reasons, response model/id, provider metadata) and drop the per-operation `callId` maps.\n beforeSpanEnd: (span, data) => {\n enrichSpanOnEnd(span, data);\n runVercelAiSpanEnd(\n span,\n 'error' in data ? { error: data.error } : { response: getNonStreamResult(span, data) },\n );\n // The result can hold the provider request and response bodies, and spans outlive the call.\n fallbackChannelResults.delete(span);\n clearOperationId(data);\n },\n // A streamed model call resolves before its stream is drained, so we tap the stream, keep the\n // span open, and end it (via `end`) once the final usage/finish/output chunks arrive.\n deferSpanEnd: ({ span, data, end }) => deferStreamedModelCallEnd(span, data, end),\n },\n );\n}\n\nfunction getNonStreamResult(span: Span, data: VercelAiChannelMessage): unknown {\n const result = fallbackChannelResults.get(span) ?? data.result;\n return isObjectLike(result) && isReadableStream(result.stream) ? undefined : result;\n}\n\n/**\n * When a `languageModelCall` resolves to a live `ReadableStream`, defer ending its span: swap in a\n * passthrough that forwards chunks to the SDK untouched while aggregating usage/finish/output, then\n * enrich and end the span once the stream settles. Returns `false` for anything that isn't a streamed\n * model call so the helper ends the span as usual.\n */\nfunction deferStreamedModelCallEnd(span: Span, data: VercelAiChannelMessage, end: (error?: unknown) => void): boolean {\n const result = fallbackChannelResults.get(span) ?? data.result;\n if (data.type !== 'languageModelCall' || !isObjectLike(result)) {\n return false;\n }\n const stream = result.stream;\n if (!isReadableStream(stream)) {\n return false;\n }\n\n const callId = asString(data.event.callId);\n const invokeAgentSpan = callId ? invokeAgentSpanByCallId.get(callId) : undefined;\n const { recordOutputs } = getRecordingOptions(\n data.event,\n invokeAgentSpan && integrationRecordingBySpan.get(invokeAgentSpan),\n data.result === undefined,\n );\n result.stream = tapModelCallStream(\n span,\n stream,\n final => {\n // Reshape the aggregate into the result `enrichSpanOnEnd` expects, then let `end` run it (it calls\n // `beforeSpanEnd`). Enriching the model-call span and the parent from the same aggregate keeps\n // streamed and non-streamed spans identical.\n fallbackChannelResults.set(span, { ...result, ...streamedResultToChannelResult(final) });\n end();\n if (invokeAgentSpan) {\n enrichInvokeAgentFromStream(invokeAgentSpan, final, recordOutputs);\n }\n },\n error => end(error),\n );\n\n return true;\n}\n\n/** Map the tapped stream aggregate onto the `languageModelCall` result shape `enrichSpanOnEnd` reads. */\nexport function streamedResultToChannelResult(final: StreamedModelCallResult): Record<string, unknown> {\n const content: Array<Record<string, unknown>> = [];\n if (final.text) {\n content.push({ type: 'text', text: final.text });\n }\n for (const toolCall of final.toolCalls) {\n content.push({ type: 'tool-call', ...toolCall });\n }\n\n return {\n content,\n ...(final.usage !== undefined ? { usage: final.usage } : {}),\n ...(final.finishReason !== undefined ? { finishReason: final.finishReason } : {}),\n ...(final.providerMetadata !== undefined ? { providerMetadata: final.providerMetadata } : {}),\n ...(final.responseId || final.responseModel\n ? {\n response: {\n ...(final.responseId ? { id: final.responseId } : {}),\n ...(final.responseModel ? { modelId: final.responseModel } : {}),\n },\n }\n : {}),\n };\n}\n\n/**\n * Propagate a streamed model call's usage (summed across the operation's model calls) and output onto\n * the enclosing `invoke_agent` span, which has no channel result of its own. Runs before that span ends\n * because the operation's completion promise settles only after every model-call stream has drained.\n */\nfunction enrichInvokeAgentFromStream(span: Span, final: StreamedModelCallResult, recordOutputs: boolean): void {\n const usage = isObjectLike(final.usage) ? final.usage : undefined;\n if (usage) {\n const input = tokenCount(usage.inputTokens) ?? tokenCount(usage.promptTokens) ?? tokenCount(usage.tokens);\n const output = tokenCount(usage.outputTokens) ?? tokenCount(usage.completionTokens);\n addTokensToSpan(span, GEN_AI_USAGE_INPUT_TOKENS, input);\n addTokensToSpan(span, GEN_AI_USAGE_OUTPUT_TOKENS, output);\n addTokensToSpan(span, GEN_AI_USAGE_TOTAL_TOKENS, tokenCount(usage.totalTokens) ?? sum(input, output));\n const { cacheRead, cacheWrite } = cacheTokens(usage);\n addTokensToSpan(span, GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS, cacheRead);\n addTokensToSpan(span, GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS, cacheWrite);\n }\n\n if (recordOutputs) {\n const parts = partsFromTextAndToolCalls(final.text, final.toolCalls);\n const outputMessages = buildOutputMessages(parts, getFinishReason({ finishReason: final.finishReason }));\n if (outputMessages) {\n span.setAttribute(GEN_AI_OUTPUT_MESSAGES, outputMessages);\n }\n }\n}\n\n/** Add `value` into a span's numeric token attribute, using the span itself as the running sum. */\nfunction addTokensToSpan(span: Span, attribute: string, value: number | undefined): void {\n if (value === undefined) {\n return;\n }\n const current = spanToJSON(span).attributes[attribute];\n span.setAttribute(attribute, (typeof current === 'number' ? current : 0) + value);\n}\n\n/**\n * Transform a channel `start` payload into the span that should be active for the operation. For\n * `step` we deliberately don't open a span (model calls and tool calls are siblings under the\n * invoke_agent span, matching the OTel-based output), so we reuse the active span and mark the\n * payload to skip ending it.\n */\nexport function createSpanFromMessage(\n data: VercelAiChannelMessage,\n channelOptions: VercelAiChannelOptions,\n): Span | undefined {\n const { type, event } = data;\n\n if (type === 'step' || !event || typeof event !== 'object') {\n // Opt out: returning `undefined` leaves the enclosing `invoke_agent` span as the active context\n // (model-call and tool-call events nest under it) without opening — or ending — a span of its own.\n return undefined;\n }\n\n const call: VercelAiCallInfo = { type, event };\n const integrationRecording: GenAiOptions = {\n recordInputs: resolveRecordingOption(channelOptions.recordInputs, call),\n recordOutputs: resolveRecordingOption(channelOptions.recordOutputs, call),\n };\n const span = startSpanFromEvent(type, event, getRecordingOptions(event, integrationRecording).recordInputs);\n if (span) {\n integrationRecordingBySpan.set(span, integrationRecording);\n runGenAiSpanStart(channelOptions, span, call);\n spanEndHooks.set(span, result => runGenAiSpanEnd(channelOptions, span, call, result));\n }\n return span;\n}\n\nfunction startSpanFromEvent(\n type: ChannelEventType,\n event: Record<string, unknown>,\n recordInputs: boolean,\n): Span | undefined {\n const provider = asString(event.provider);\n const modelId = asString(event.modelId);\n const callId = asString(event.callId);\n const maxRetries = asNumber(event.maxRetries);\n\n // Harvest tool descriptions from the operation/model-call `tools` so tool spans can backfill them.\n // Gated on `recordInputs` to match the OTel path, which only records `tool.definitions` then.\n if (recordInputs) {\n recordToolDescriptions(callId, event.tools);\n }\n\n // Only an operation's start event carries `providerOptions`; its model-call and tool events start\n // while the operation span is active, so they inherit the id from it. A root operation never\n // inherits, so a nested call (e.g. inside a tool's `execute`) is not folded into the outer conversation.\n const conversationId =\n getOpenAiConversationId(event.providerOptions) ??\n (ROOT_OPERATION_TYPES.has(type) ? undefined : getActiveSpanConversationId());\n\n const runtimeContextAttributes =\n (callId ? runtimeContextAttributesByCallId.get(callId) : undefined) ??\n contextAttributes(event, event.runtimeContext, VERCEL_AI_SETTINGS_CONTEXT_KEY_BASE);\n if (callId && ROOT_OPERATION_TYPES.has(type)) {\n runtimeContextAttributesByCallId.set(callId, runtimeContextAttributes);\n }\n\n const baseAttributes: SpanAttributes = {\n [SENTRY_ORIGIN]: ORIGIN,\n ...telemetryMetadataAttributes(event.telemetryMetadata),\n ...runtimeContextAttributes,\n [GEN_AI_PROVIDER_NAME]: provider,\n [VERCEL_AI_MODEL_PROVIDER_ATTRIBUTE]: provider,\n [GEN_AI_REQUEST_MODEL]: modelId,\n [VERCEL_AI_SETTINGS_MAX_RETRIES_ATTRIBUTE]: maxRetries,\n [GEN_AI_CONVERSATION_ID]: conversationId,\n };\n\n switch (type) {\n case 'generateText':\n case 'streamText':\n case 'generateObject':\n case 'streamObject':\n // The object variants' operationId rides on `event.operationId`. The JSON-schema attribute the OTel\n // path derives from the SDK's Zod schema is not reconstructed on the channel path.\n return buildInvokeAgentSpan(\n event,\n baseAttributes,\n recordInputs,\n callId,\n type === 'streamText' || type === 'streamObject',\n );\n case 'languageModelCall':\n _INTERNAL_skipAiProviderWrapping([WORKERS_AI_INTEGRATION_NAME]);\n\n return buildModelCallSpan(event, baseAttributes, recordInputs, callId, modelId);\n case 'executeTool':\n return buildToolSpan(event, recordInputs, conversationId, runtimeContextAttributes);\n case 'embed':\n case 'embedMany': {\n // `embed` carries a single `value`; `embedMany` a `values` array — both map to the embeddings input.\n const input = type === 'embedMany' ? event.values : event.value;\n return startGenAiSpan('embeddings', modelId, {\n ...baseAttributes,\n ...(recordInputs && !isStrippedInput(input) ? { [GEN_AI_EMBEDDINGS_INPUT]: stringify(input) } : {}),\n });\n }\n case 'rerank':\n return startGenAiSpan('rerank', modelId, baseAttributes);\n // `ai` 7.0.128 renamed `experimental_evaluate` to `experimental_decide`; older 7.x still publishes the old name.\n case 'experimental_evaluate':\n case 'experimental_decide':\n return startGenAiSpan('decide', modelId, {\n ...baseAttributes,\n ...(recordInputs && !(isStrippedInput(event.state) && isStrippedInput(event.questions))\n ? {\n [GEN_AI_INPUT_MESSAGES]: stringify([\n { type: 'evaluation', state: event.state, questions: event.questions },\n ]),\n }\n : {}),\n });\n case 'experimental_extract':\n return startGenAiSpan('extract', modelId, {\n ...baseAttributes,\n ...(recordInputs && !(isStrippedInput(event.state) && isStrippedInput(event.fields))\n ? {\n [GEN_AI_INPUT_MESSAGES]: stringify([\n {\n ...toExtractState(event.state).request,\n fields: toExtractFields(event.fields),\n reference_date: event.referenceDate,\n },\n ]),\n }\n : {}),\n });\n default:\n // Unknown event type: opt out rather than open a span we can't shape correctly.\n return undefined;\n }\n}\n\n/**\n * `experimental_telemetry.metadata` (`ai` <= 6) as `vercel.ai.telemetry.metadata.<key>`, the names the OTel\n * integration produced from the SDK's `ai.telemetry.metadata.*`. Only the orchestrion adapter sets\n * `event.telemetryMetadata`; `ai` 7 has no `telemetry.metadata`.\n */\nfunction telemetryMetadataAttributes(metadata: unknown): Record<string, string> {\n const attributes: Record<string, string> = {};\n if (isObjectLike(metadata)) {\n for (const [key, value] of Object.entries(metadata)) {\n if (value === null || value === undefined) continue;\n attributes[`${VERCEL_AI_TELEMETRY_METADATA_ATTRIBUTE_PREFIX}${key}`] = String(value);\n }\n }\n return attributes;\n}\n\n/**\n * One string attribute per context key, as `<prefix><key>`. `ai` < 7.0.114 published the full context to the\n * channel, ignoring `telemetry.includeRuntimeContext`/`includeToolsContext`, and a filtered context\n * looks the same as an unfiltered one. `aiVersion` (added in 7.0.154) is the only reliable sign that\n * the AI SDK filtered it, so without it we record nothing.\n */\nfunction contextAttributes(event: Record<string, unknown>, context: unknown, keyBase: string): SpanAttributes {\n const attributes: SpanAttributes = {};\n if (typeof event.aiVersion !== 'string' || !isObjectLike(context)) {\n return attributes;\n }\n for (const [key, value] of Object.entries(context)) {\n const attributeValue = stringify(value);\n if (value !== null && attributeValue !== undefined) {\n attributes[`${keyBase}.${key}`] = attributeValue;\n }\n }\n return attributes;\n}\n\n/** Start a `gen_ai.<operation>` span named `<operation> <suffix>` (or just `<operation>` when no suffix). */\nfunction startGenAiSpan(operation: GenAiOperation, suffix: string | undefined, attributes: SpanAttributes): Span {\n return startInactiveSpan({\n name: suffix ? `${operation} ${suffix}` : operation,\n attributes: {\n [SENTRY_OP]: GEN_AI_OPERATION_SPAN_OPS[operation],\n [GEN_AI_OPERATION_NAME]: operation,\n ...attributes,\n },\n });\n}\n\nfunction buildInvokeAgentSpan(\n event: Record<string, unknown>,\n baseAttributes: SpanAttributes,\n recordInputs: boolean,\n callId: string | undefined,\n isStream: boolean,\n): Span {\n const functionId = asString(event.functionId);\n const operationId = asString(event.operationId) ?? (isStream ? 'ai.streamText' : 'ai.generateText');\n if (callId) {\n operationIdByCallId.set(callId, { operationId, isStream });\n }\n const span = startGenAiSpan('invoke_agent', functionId, {\n ...baseAttributes,\n [VERCEL_AI_OPERATION_ID_ATTRIBUTE]: operationId,\n [GEN_AI_RESPONSE_STREAMING]: isStream,\n [GEN_AI_FUNCTION_ID]: functionId,\n ...(recordInputs ? buildInputMessageAttributes(event) : {}),\n });\n if (isStream && callId) {\n invokeAgentSpanByCallId.set(callId, span);\n }\n\n return span;\n}\n\nfunction buildModelCallSpan(\n event: Record<string, unknown>,\n baseAttributes: SpanAttributes,\n recordInputs: boolean,\n callId: string | undefined,\n modelId: string | undefined,\n): Span {\n const parent = callId ? operationIdByCallId.get(callId) : undefined;\n const operationId = parent\n ? `${parent.operationId}.${parent.isStream ? 'doStream' : 'doGenerate'}`\n : 'ai.generateText.doGenerate';\n return startGenAiSpan('generate_content', modelId, {\n ...baseAttributes,\n [VERCEL_AI_OPERATION_ID_ATTRIBUTE]: operationId,\n ...(recordInputs ? buildInputMessageAttributes(event) : {}),\n ...(recordInputs && Array.isArray(event.tools) ? { [GEN_AI_TOOL_DEFINITIONS]: stringify(event.tools) } : {}),\n });\n}\n\nfunction buildToolSpan(\n event: Record<string, unknown>,\n recordInputs: boolean,\n conversationId: string | undefined,\n runtimeContextAttributes: SpanAttributes,\n): Span {\n const toolCall = isObjectLike(event.toolCall) ? event.toolCall : {};\n const toolName = asString(toolCall.toolName);\n const toolCallId = asString(event.toolCallId) ?? asString(toolCall.toolCallId);\n const toolInput = toolCall.input ?? toolCall.args;\n // The `executeTool` event has no description; backfill it from the operation's recorded tools.\n // Gated on `recordInputs` to match the OTel path (descriptions come from the recorded tools list).\n const description =\n recordInputs && toolName ? resolveToolDescription(asString(event.callId), toolName, event.tools) : undefined;\n return startGenAiSpan('execute_tool', toolName, {\n [SENTRY_ORIGIN]: ORIGIN,\n ...runtimeContextAttributes,\n ...contextAttributes(event, event.toolContext, VERCEL_AI_TOOL_CALL_CONTEXT_KEY_BASE),\n [GEN_AI_TOOL_NAME]: toolName,\n [GEN_AI_TOOL_CALL_ID_ATTRIBUTE]: toolCallId,\n [GEN_AI_TOOL_DESCRIPTION]: description,\n ...(recordInputs && toolInput !== undefined ? { [GEN_AI_TOOL_CALL_ARGUMENTS]: stringify(toolInput) } : {}),\n [GEN_AI_CONVERSATION_ID]: conversationId,\n });\n}\n\n/**\n * Best-effort enrichment from the resolved value the AI SDK attaches to the channel context.\n * Everything here is guarded: when a field is missing or the shape differs across `ai` versions,\n * we simply don't set the attribute rather than emit a malformed span.\n */\nexport function enrichSpanOnEnd(span: Span, data: VercelAiChannelMessage): void {\n const { type } = data;\n const result = fallbackChannelResults.get(span) ?? data.result;\n if (!isObjectLike(result)) {\n return;\n }\n\n const { recordOutputs } = getRecordingOptions(\n data.event,\n integrationRecordingBySpan.get(span),\n data.result === undefined,\n );\n\n if (type === 'executeTool') {\n // From V5 on, tool errors are not rejected (so the `error` channel verb never fires) — they\n // surface as `tool-error` content on the resolved result. Mirror the OTel path by marking the\n // span and capturing the error, which carry the failure instead of the result attribute.\n const output = isObjectLike(result.output) ? result.output : undefined;\n if (output?.type === 'tool-error') {\n captureToolError(span, data, output.error);\n } else if (recordOutputs) {\n span.setAttribute(GEN_AI_TOOL_CALL_RESULT, stringify(result.output ?? result));\n }\n return;\n }\n\n // `languageModelCall` results report usage as `{ total }` objects; top-level/step results report\n // flat numbers. `tokenCount` handles both. v4 names tokens `promptTokens`/`completionTokens`\n // (v5+ uses `inputTokens`/`outputTokens`); the fallbacks are `undefined`-inert on v5+.\n const usage = isObjectLike(result.usage) ? result.usage : undefined;\n if (usage) {\n const inputTokens = tokenCount(usage.inputTokens) ?? tokenCount(usage.promptTokens) ?? tokenCount(usage.tokens);\n const outputTokens = tokenCount(usage.outputTokens) ?? tokenCount(usage.completionTokens);\n const totalTokens = tokenCount(usage.totalTokens) ?? sum(inputTokens, outputTokens);\n if (inputTokens !== undefined) {\n span.setAttribute(GEN_AI_USAGE_INPUT_TOKENS, inputTokens);\n }\n if (outputTokens !== undefined) {\n span.setAttribute(GEN_AI_USAGE_OUTPUT_TOKENS, outputTokens);\n }\n if (totalTokens !== undefined) {\n span.setAttribute(GEN_AI_USAGE_TOTAL_TOKENS, totalTokens);\n }\n setCacheTokens(span, usage);\n }\n\n // Match the OTel integration: finish reasons live on the model-call (`generate_content`) span, not\n // on the top-level `invoke_agent` span.\n const finishReason = getFinishReason(result);\n if (finishReason && type === 'languageModelCall') {\n span.setAttribute(GEN_AI_RESPONSE_FINISH_REASONS, stringify([finishReason]));\n }\n\n const response = isObjectLike(result.response) ? result.response : undefined;\n const responseId = asString(response?.id) ?? asString(result.responseId);\n if (responseId) {\n span.setAttribute(GEN_AI_RESPONSE_ID, responseId);\n }\n const responseModel = asString(response?.modelId) ?? asString(data.event.modelId);\n if (responseModel) {\n span.setAttribute(GEN_AI_RESPONSE_MODEL, responseModel);\n }\n\n // Provider-specific cache/reasoning/prediction token breakdowns. The channel exposes `providerMetadata`\n // as an object (the OTel path parses it from a string); both share `getProviderMetadataAttributes` so\n // the emitted shape is identical.\n const providerMetadata = (result as { providerMetadata?: unknown }).providerMetadata;\n const providerAttributes = getProviderMetadataAttributes(providerMetadata);\n dropLastStepOnlyUsage(providerAttributes, type);\n span.setAttributes(providerAttributes);\n\n if (recordOutputs) {\n const outputMessages = getOutputMessages(type, result, finishReason, data.event);\n if (outputMessages) {\n span.setAttribute(GEN_AI_OUTPUT_MESSAGES, outputMessages);\n }\n }\n}\n\nfunction getOutputMessages(\n type: ChannelEventType,\n result: Record<string, unknown>,\n finishReason: string | undefined,\n event: Record<string, unknown>,\n): string | undefined {\n if (type === 'experimental_evaluate' || type === 'experimental_decide') {\n return getEvaluationOutputMessages(withProviderAnswerFields(result));\n }\n if (type === 'experimental_extract') {\n return isObjectLike(result.answers)\n ? stringify([{ answers: toExtractAnswers(result.answers, toExtractState(event.state).parts) }])\n : undefined;\n }\n // `languageModelCall` exposes the response as a `content` parts array; top-level results expose\n // `text` + `toolCalls`. Both normalize into the OTel `gen_ai.output.messages` assistant message.\n const parts =\n type === 'languageModelCall' && Array.isArray(result.content)\n ? partsFromContent(result.content)\n : partsFromTextAndToolCalls(result.text, result.toolCalls);\n return buildOutputMessages(parts, finishReason);\n}\n\n/**\n * Providers move answer fields into `providerMetadata`: TypeSafe and OpenAI as `<provider>.confidence[id]`,\n * OpenRouter as `openrouter.answers[id].{confidence,legend}`. Put them back on the answers.\n */\nfunction withProviderAnswerFields(result: Record<string, unknown>): unknown {\n const { answers, providerMetadata } = result;\n if (!isObjectLike(answers) || !isObjectLike(providerMetadata)) {\n return answers;\n }\n const confidenceById = [providerMetadata.typesafe, providerMetadata.openai]\n .map(metadata => (isObjectLike(metadata) ? metadata.confidence : undefined))\n .find(isObjectLike);\n const { openrouter } = providerMetadata;\n const openrouterById = isObjectLike(openrouter) && isObjectLike(openrouter.answers) ? openrouter.answers : undefined;\n if (!confidenceById && !openrouterById) {\n return answers;\n }\n\n return mapObjectValues(answers, (answer, id) => {\n const openrouterAnswer = openrouterById?.[id];\n const fields = isObjectLike(openrouterAnswer) ? openrouterAnswer : {};\n const {\n confidence = asNumber(confidenceById?.[id]) ?? asNumber(fields.confidence),\n legend = isObjectLike(fields.legend) ? fields.legend : undefined,\n } = answer;\n return { ...answer, confidence, legend };\n });\n}\n\n/** Maps a Vercel AI finish reason to the OTel `gen_ai.output.messages` form (`tool-calls` → `tool_call`). */\nfunction normalizeFinishReason(finishReason: string | undefined): string {\n return finishReason === 'tool-calls' ? 'tool_call' : (finishReason ?? 'stop');\n}\n\n/** Reads the finish reason from a result — a string on top-level results, `{ unified }` on model calls. */\nfunction getFinishReason(result: Record<string, unknown>): string | undefined {\n const finishReason = result.finishReason;\n if (typeof finishReason === 'string') {\n return finishReason;\n }\n return isObjectLike(finishReason) ? asString(finishReason.unified) : undefined;\n}\n\n/** Reads a token count that may be a plain number or a `{ total }` object (model-call usage). */\nfunction tokenCount(value: unknown): number | undefined {\n return asNumber(value) ?? (isObjectLike(value) ? asNumber(value.total) : undefined);\n}\n\n/**\n * Cache token counts as the AI SDK normalizes them: v5 `cachedInputTokens`, v6 `inputTokenDetails`,\n * v7 `inputTokens.{cacheRead,cacheWrite}`.\n */\nfunction setCacheTokens(span: Span, usage: Record<string, unknown>): void {\n const { cacheRead, cacheWrite } = cacheTokens(usage);\n if (cacheRead !== undefined) {\n span.setAttribute(GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS, cacheRead);\n }\n if (cacheWrite !== undefined) {\n span.setAttribute(GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS, cacheWrite);\n }\n}\n\nfunction cacheTokens(usage: Record<string, unknown>): { cacheRead?: number; cacheWrite?: number } {\n const inputTokens = isObjectLike(usage.inputTokens) ? usage.inputTokens : undefined;\n const inputTokenDetails = isObjectLike(usage.inputTokenDetails) ? usage.inputTokenDetails : undefined;\n return {\n cacheRead:\n asNumber(inputTokens?.cacheRead) ??\n asNumber(inputTokenDetails?.cacheReadTokens) ??\n asNumber(usage.cachedInputTokens),\n cacheWrite: asNumber(inputTokens?.cacheWrite) ?? asNumber(inputTokenDetails?.cacheWriteTokens),\n };\n}\n\nfunction buildOutputMessages(\n parts: Array<Record<string, unknown>>,\n finishReason: string | undefined,\n): string | undefined {\n if (!parts.length) {\n return undefined;\n }\n return stringify([{ role: 'assistant', parts, finish_reason: normalizeFinishReason(finishReason) }]);\n}\n\nfunction toolCallPart(toolCall: Record<string, unknown>): Record<string, unknown> {\n const args = toolCall.input ?? toolCall.args;\n return {\n type: 'tool_call',\n id: asString(toolCall.toolCallId),\n name: asString(toolCall.toolName),\n arguments: typeof args === 'string' ? args : stringify(args ?? {}),\n };\n}\n\nfunction partsFromContent(content: unknown[]): Array<Record<string, unknown>> {\n const parts: Array<Record<string, unknown>> = [];\n for (const item of content) {\n if (!isObjectLike(item)) {\n continue;\n }\n if (item.type === 'text' && typeof item.text === 'string') {\n parts.push({ type: 'text', content: item.text });\n } else if (item.type === 'tool-call') {\n parts.push(toolCallPart(item));\n }\n }\n return parts;\n}\n\nfunction partsFromTextAndToolCalls(text: unknown, toolCalls: unknown): Array<Record<string, unknown>> {\n const parts: Array<Record<string, unknown>> = [];\n if (typeof text === 'string' && text.length) {\n parts.push({ type: 'text', content: text });\n }\n if (Array.isArray(toolCalls)) {\n for (const toolCall of toolCalls) {\n if (isObjectLike(toolCall)) {\n parts.push(toolCallPart(toolCall));\n }\n }\n }\n return parts;\n}\n\nexport function captureToolError(span: Span, data: VercelAiChannelMessage, error: unknown): void {\n span.setStatus({\n code: SPAN_STATUS_ERROR,\n message: error instanceof Error ? error.message : 'tool_error',\n });\n\n const toolCall = isObjectLike(data.event.toolCall) ? data.event.toolCall : {};\n const toolName = asString(toolCall.toolName);\n const toolCallId = asString(data.event.toolCallId) ?? asString(toolCall.toolCallId);\n\n withScope(scope => {\n scope.setContext('trace', spanToTraceContext(span));\n if (toolName) {\n scope.setTag('vercel.ai.tool.name', toolName);\n }\n if (toolCallId) {\n scope.setTag('vercel.ai.tool.callId', toolCallId);\n }\n scope.setLevel('error');\n captureException(\n error instanceof Error ? error : new Error(typeof error === 'string' ? error : 'Tool execution failed'),\n {\n mechanism: { type: 'auto.ai.vercelai', handled: false },\n },\n );\n });\n}\n\nfunction getRecordingOptions(\n event: Record<string, unknown>,\n integrationRecording: GenAiOptions = {},\n channelWithheldResult = false,\n): {\n recordInputs: boolean;\n recordOutputs: boolean;\n} {\n const client = getClient();\n const genAI = client?.getDataCollectionOptions().genAI;\n // `ai` withheld the result because of the per-call flag, which eve >= 1.0.0-rc.10 sets from trace policies, so\n // the flag is a content decision there rather than eve's blanket default.\n const eveMode = client && !channelWithheldResult ? isEveGenAiRecordingDefault(client) : false;\n\n return {\n recordInputs: resolveRecording(integrationRecording.recordInputs, event.recordInputs, genAI?.inputs, eveMode),\n recordOutputs: resolveRecording(integrationRecording.recordOutputs, event.recordOutputs, genAI?.outputs, eveMode),\n };\n}\n\n/**\n * Mirrors the OTel integration's `determineRecordingSettings` precedence: an integration-level option\n * wins, then the per-call `experimental_telemetry.recordInputs/recordOutputs` flag the AI SDK forwards\n * on the channel event, then the global `dataCollection.genAI` default.\n *\n * NOTE: the OTel integration also defaults recording to `true` for a call with\n * `experimental_telemetry: { isEnabled: true }`. The `ai:telemetry` channel does not expose `isEnabled`\n * (nor a resolved recording flag), so that per-call default cannot be reproduced here — v7 users who\n * want inputs/outputs recorded must enable `dataCollection.genAI` or set `recordInputs`/`recordOutputs`.\n *\n * Under `eveMode` (set by `eveIntegration()`) the per-call flag is eve's blanket framework default\n * rather than an end-user decision, so it is skipped: an explicit `dataCollection.genAI` still wins,\n * otherwise recording defaults to `true`. An integration-level option outranks both regardless.\n */\nfunction resolveRecording(\n integrationOption: unknown,\n perCallOption: unknown,\n globalDefault: unknown,\n eveMode = false,\n): boolean {\n if (typeof integrationOption === 'boolean') {\n return integrationOption;\n }\n if (eveMode) {\n return typeof globalDefault === 'boolean' ? globalDefault : true;\n }\n if (typeof perCallOption === 'boolean') {\n return perCallOption;\n }\n return globalDefault === true;\n}\n\n/** `ai` >= 7.0.163 replaces inputs with empty values when `recordInputs` is false. */\nfunction isStrippedInput(input: unknown): boolean {\n return (\n input === undefined ||\n input === '' ||\n (Array.isArray(input) && !input.length) ||\n (isPlainObject(input) && !Object.keys(input).length)\n );\n}\n\n/** The `ai` SDK accepts the system prompt as `string | SystemModelMessage | SystemModelMessage[]`. */\nfunction getSystemInstructionParts(instructions: unknown): { type: 'text'; content: string }[] {\n const messages = Array.isArray(instructions) ? instructions : [instructions];\n return messages.flatMap(message => {\n const content = asString(isObjectLike(message) ? message.content : message);\n return content ? [{ type: 'text' as const, content }] : [];\n });\n}\n\nfunction buildInputMessageAttributes(event: Record<string, unknown>): Record<string, string | number | undefined> {\n const attributes: Record<string, string | number | undefined> = {};\n\n // `ai` >= 7 forbids system messages in `messages`/`prompt` and exposes the system prompt as a\n // separate `instructions` field. The OTel path lifts the system message out of the prompt into\n // `gen_ai.system_instructions` as `[{ type: 'text', content }]`; mirror that shape here.\n const instructions = getSystemInstructionParts(event.instructions);\n if (instructions.length) {\n attributes[GEN_AI_SYSTEM_INSTRUCTIONS] = stringify(instructions);\n }\n\n // The AI SDK start events extend `StandardizedPrompt`; messages live on `messages`, otherwise the\n // simpler `prompt` field is used.\n const messages = event.messages ?? event.prompt;\n if (!isStrippedInput(messages)) {\n attributes[GEN_AI_INPUT_MESSAGES] = stringify(messages);\n }\n\n return attributes;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA0FA,MAAa,mCAAmC;AAEhD,MAAM,SAAS;AAGf,MAAM,4BAA4B;CAChC,YAAY;CAIZ,QAAQ;CACR,QAAQ;CACR,SAAS;CACT,cAAc;CACd,cAAc;CAGd,kBAAkB;AACpB;AAKA,MAAM,mCAAmC;AACzC,MAAM,qCAAqC;AAC3C,MAAM,2CAA2C;AACjD,MAAM,gDAAgD;AAMtD,MAAM,sCAAsB,IAAI,IAAwD;AASxF,MAAM,2CAA2B,IAAI,IAAiC;AAMtE,MAAM,0CAA0B,IAAI,IAAkB;AAItD,MAAM,mDAAmC,IAAI,IAA4B;AAI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W,yBAAyB,UAAU,QAAQ;CAGxD,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"vercel-ai-dc-subscriber.js","names":[],"sources":["../../../../src/integrations/vercel-ai/vercel-ai-dc-subscriber.ts"],"sourcesContent":["/* eslint-disable max-lines */\nimport {\n GEN_AI_CONVERSATION_ID,\n GEN_AI_COST_TOTAL_TOKENS,\n GEN_AI_EMBEDDINGS_INPUT,\n GEN_AI_FUNCTION_ID,\n GEN_AI_INPUT_MESSAGES,\n GEN_AI_OPERATION_NAME,\n GEN_AI_OUTPUT_MESSAGES,\n GEN_AI_PROVIDER_NAME,\n GEN_AI_REQUEST_MODEL,\n GEN_AI_RESPONSE_FINISH_REASONS,\n GEN_AI_RESPONSE_ID,\n GEN_AI_RESPONSE_MODEL,\n GEN_AI_RESPONSE_STREAMING,\n GEN_AI_SYSTEM_INSTRUCTIONS,\n GEN_AI_TOOL_CALL_ARGUMENTS,\n GEN_AI_TOOL_CALL_RESULT,\n GEN_AI_TOOL_DEFINITIONS,\n GEN_AI_TOOL_DESCRIPTION,\n GEN_AI_TOOL_NAME,\n GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS,\n GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS,\n GEN_AI_USAGE_INPUT_TOKENS,\n GEN_AI_USAGE_OUTPUT_TOKENS,\n GEN_AI_USAGE_REASONING_OUTPUT_TOKENS,\n GEN_AI_USAGE_TOTAL_TOKENS,\n SENTRY_OP,\n SENTRY_ORIGIN,\n VERCEL_AI_SETTINGS_CONTEXT_KEY_BASE,\n VERCEL_AI_TOOL_CALL_CONTEXT_KEY_BASE,\n} from '@sentry/conventions/attributes';\nimport {\n GEN_AI_DECIDE,\n GEN_AI_EMBEDDINGS,\n GEN_AI_EXECUTE_TOOL,\n GEN_AI_EXTRACT,\n GEN_AI_GENERATE_CONTENT,\n GEN_AI_INVOKE_AGENT,\n GEN_AI_RERANK,\n} from '@sentry/conventions/op';\nimport type { Span, SpanAttributes } from '@sentry/core';\nimport {\n _INTERNAL_skipAiProviderWrapping,\n captureException,\n getActiveSpan,\n getClient,\n isObjectLike,\n isPlainObject,\n SPAN_STATUS_ERROR,\n spanToJSON,\n spanToTraceContext,\n startInactiveSpan,\n stringify,\n withScope,\n} from '@sentry/core';\nimport type { TracingChannel } from 'node:diagnostics_channel';\nimport { GEN_AI_TOOL_CALL_ID_ATTRIBUTE } from '../../ai/core/gen-ai-attributes';\nimport {\n type GenAiSpanHooks,\n type GenAiSpanResult,\n runGenAiSpanEnd,\n runGenAiSpanStart,\n} from '../../ai/core/span-hooks';\nimport { isEveGenAiRecordingDefault } from './gen-ai-recording-mode';\nimport {\n type GenAiCallOptions,\n type GenAiOptions,\n getEvaluationOutputMessages,\n resolveRecordingOption,\n} from '../../ai/core/utils';\nimport { getProviderMetadataAttributes } from '../../ai/vercel-ai';\nimport { WORKERS_AI_INTEGRATION_NAME } from '../../ai/workers-ai/constants';\nimport { bindTracingChannelToSpan } from '../../tracing-channel';\nimport { toExtractAnswers, toExtractFields, toExtractState } from './extract';\nimport {\n asNumber,\n asString,\n isReadableStream,\n mapObjectValues,\n type StreamedModelCallResult,\n sum,\n tapModelCallStream,\n} from './util';\n\n/**\n * The single tracing channel the `ai` package (>= 7) publishes all telemetry lifecycle events to\n * via `node:diagnostics_channel`. Events are discriminated by their `type` field.\n * @see https://github.com/vercel/ai/pull/15660\n */\nexport const AI_SDK_TELEMETRY_TRACING_CHANNEL = 'ai:telemetry';\n\nconst ORIGIN = 'auto.ai.vercelai';\n\n// `gen_ai.operation.name` values, keyed to the span op they map to.\nconst GEN_AI_OPERATION_SPAN_OPS = {\n embeddings: GEN_AI_EMBEDDINGS,\n // `GEN_AI_RERANK` is deprecated because the product doesn't support rerank spans, but we keep\n // emitting it so existing rerank spans keep their op.\n // oxlint-disable-next-line typescript/no-deprecated\n rerank: GEN_AI_RERANK,\n decide: GEN_AI_DECIDE,\n extract: GEN_AI_EXTRACT,\n invoke_agent: GEN_AI_INVOKE_AGENT,\n execute_tool: GEN_AI_EXECUTE_TOOL,\n // The model-call op matches the Vercel AI OTel integration (`gen_ai.generate_content`) rather than\n // the generic `gen_ai.chat`, so v6 (OTel) and v7 (channel) produce the same spans.\n generate_content: GEN_AI_GENERATE_CONTENT,\n} as const;\n\ntype GenAiOperation = keyof typeof GEN_AI_OPERATION_SPAN_OPS;\n\n// Subset of the `vercel.ai.*` passthrough attributes the OTel integration emits that we reproduce.\nconst VERCEL_AI_OPERATION_ID_ATTRIBUTE = 'vercel.ai.operationId';\nconst VERCEL_AI_MODEL_PROVIDER_ATTRIBUTE = 'vercel.ai.model.provider';\nconst VERCEL_AI_SETTINGS_MAX_RETRIES_ATTRIBUTE = 'vercel.ai.settings.maxRetries';\nconst VERCEL_AI_TELEMETRY_METADATA_ATTRIBUTE_PREFIX = 'vercel.ai.telemetry.metadata.';\n\n// Tracks the top-level operationId (and whether it streams) per `callId` so a model-call span can\n// name its `doGenerate`/`doStream` operation the same way the OTel integration does. `isStream` is\n// the authoritative event-type signal rather than a substring check on the (possibly custom)\n// operationId. Cleared when the top-level span ends.\nconst operationIdByCallId = new Map<string, { operationId: string; isStream: boolean }>();\n\n// Per-operation map of tool name → description, harvested from a model-call /\n// top-level event's `tools` (keyed by the shared `callId`). The AI SDK's\n// `executeTool` event doesn't carry the tool's description, so we backfill it\n// onto the tool span here — without relying on the OTel `vercelAiEventProcessor`\n// (which isn't registered in channel/orchestrion mode). Cleared with the\n// operation. Only populated when inputs are recorded, matching the OTel path\n// (which sources descriptions from the recorded `tool.definitions`).\nconst toolDescriptionsByCallId = new Map<string, Map<string, string>>();\n\n// A streamed `streamText` operation's own channel result is always `undefined` (the SDK exposes the\n// stream only on the model call), so its `invoke_agent` span can't be enriched from the channel. We\n// key the span by `callId` and enrich it as each streamed model call drains — the model calls flush\n// before the operation's own span ends. The running token sum lives on the span's own attributes.\nconst invokeAgentSpanByCallId = new Map<string, Span>();\n\n// Only an operation's start event carries `runtimeContext`; its model-call and tool events copy the\n// resulting attributes from here. Cleared with the operation.\nconst runtimeContextAttributesByCallId = new Map<string, SpanAttributes>();\n\n// Only top-level operations own the `callId` → operationId mapping; `step`/`languageModelCall`/\n// `executeTool` share the parent's `callId`, so they must not clear it.\nconst ROOT_OPERATION_TYPES = new Set<ChannelEventType>([\n 'generateText',\n 'streamText',\n 'streamObject',\n 'generateObject',\n 'embed',\n 'embedMany',\n 'rerank',\n]);\n\n// Operations whose `providerMetadata` cost covers only one of their provider calls: the last step of a\n// text or object operation, whose cost the `generate_content` spans carry, or one `embedMany` chunk.\nconst PARTIAL_COST_OPERATION_TYPES = new Set<ChannelEventType>([\n 'generateText',\n 'streamText',\n 'streamObject',\n 'generateObject',\n 'embedMany',\n]);\n\n/** Drop the per-operation `callId` maps once the owning top-level operation settles (success or error). */\nexport function clearOperationId(data: VercelAiChannelMessage): void {\n if (!ROOT_OPERATION_TYPES.has(data.type)) {\n return;\n }\n const callId = asString(data.event.callId);\n if (callId) {\n clearOperationCallId(callId);\n }\n}\n\n/**\n * Drop the per-operation `callId` maps for a single id. The v6 orchestrion adapter uses this to clear a\n * `streamText`/`streamObject` operation only after its lazily-run model call settles — the operation's own\n * span ends synchronously (when the call returns) but the model call runs later as the stream is consumed,\n * and it still needs the operation's `operationId`/`isStream` entry to name itself `ai.streamText.doStream`\n * (or `ai.streamObject.doStream`).\n */\nexport function clearOperationCallId(callId: string): void {\n operationIdByCallId.delete(callId);\n toolDescriptionsByCallId.delete(callId);\n invokeAgentSpanByCallId.delete(callId);\n runtimeContextAttributesByCallId.delete(callId);\n}\n\n/**\n * The OpenAI Conversations API id from `providerOptions.openai.conversation` (or `azure`): the one\n * provider-level value that is the same on every turn. A `Sentry.setConversationId()` value still wins,\n * since `conversationIdIntegration` writes it on `spanStart`, after these start attributes.\n */\nfunction getOpenAiConversationId(providerOptions: unknown): string | undefined {\n if (!isObjectLike(providerOptions)) {\n return undefined;\n }\n for (const key of ['openai', 'azure']) {\n const options = providerOptions[key];\n const conversation = isObjectLike(options) ? asString(options.conversation) : undefined;\n if (conversation) {\n return conversation;\n }\n }\n return undefined;\n}\n\n/** The `gen_ai.conversation.id` already on the active span, which for a child event is its operation span. */\nfunction getActiveSpanConversationId(): string | undefined {\n const active = getActiveSpan();\n return active ? asString(spanToJSON(active).attributes[GEN_AI_CONVERSATION_ID]) : undefined;\n}\n\n/**\n * The `providerMetadata` attributes other than token counts. A partial-cost operation's cost covers\n * only its last provider call, so it stays on the `generate_content` spans.\n */\nfunction getProviderOnlyAttributes(providerMetadata: unknown, type: ChannelEventType): Record<string, number | string> {\n const attributes = getProviderMetadataAttributes(providerMetadata);\n for (const key of Object.values(TOKEN_ATTRIBUTES)) {\n // oxlint-disable-next-line typescript/no-dynamic-delete\n delete attributes[key];\n }\n if (PARTIAL_COST_OPERATION_TYPES.has(type)) {\n // oxlint-disable-next-line typescript/no-dynamic-delete\n delete attributes[GEN_AI_COST_TOTAL_TOKENS];\n }\n return attributes;\n}\n\n/** Record tool name → description from an event's `tools`, so tool spans can backfill the description. */\nfunction recordToolDescriptions(callId: string | undefined, tools: unknown): void {\n if (!callId || !Array.isArray(tools)) {\n return;\n }\n let descriptions = toolDescriptionsByCallId.get(callId);\n for (const tool of tools) {\n if (isObjectLike(tool) && typeof tool.name === 'string' && typeof tool.description === 'string') {\n descriptions = descriptions ?? new Map();\n if (!descriptions.has(tool.name)) {\n descriptions.set(tool.name, tool.description);\n }\n }\n }\n if (descriptions) {\n toolDescriptionsByCallId.set(callId, descriptions);\n }\n}\n\n/**\n * Resolve a tool's description, preferring the per-operation map (populated from the model-call /\n * top-level event's `tools`, v7) and falling back to a `tools` collection on the event itself —\n * which may be an array of `{ name, description }` or a record keyed by tool name (v6).\n */\nfunction resolveToolDescription(callId: string | undefined, toolName: string, tools: unknown): string | undefined {\n const fromMap = callId ? toolDescriptionsByCallId.get(callId)?.get(toolName) : undefined;\n if (fromMap) {\n return fromMap;\n }\n if (Array.isArray(tools)) {\n const match = tools.find(tool => isObjectLike(tool) && tool.name === toolName);\n return isObjectLike(match) ? asString(match.description) : undefined;\n }\n if (isObjectLike(tools)) {\n const tool = tools[toolName];\n return isObjectLike(tool) ? asString(tool.description) : undefined;\n }\n return undefined;\n}\n\n/** The lifecycle event types the `ai:telemetry` channel can carry. */\nexport type ChannelEventType =\n | 'generateText'\n | 'streamText'\n | 'streamObject'\n | 'generateObject'\n | 'step'\n | 'languageModelCall'\n | 'executeTool'\n | 'embed'\n | 'embedMany'\n | 'rerank'\n | 'experimental_evaluate'\n | 'experimental_decide'\n | 'experimental_extract';\n\n/**\n * The context object the AI SDK passes through one tracing-channel call. It is the same object\n * identity across `start`/`end`/`asyncEnd`/`error`, and Node's `tracingChannel` attaches\n * `result`/`error` to it as the traced promise settles.\n */\nexport interface VercelAiChannelMessage {\n type: ChannelEventType;\n event: Record<string, unknown>;\n result?: unknown;\n error?: unknown;\n}\n\n/**\n * Platform-provided factory that returns a tracing channel for the given channel name. The factory\n * is responsible for, when `start` fires, calling `transformStart(data)` and storing the returned\n * span on `data._sentrySpan` so the subscriber's `asyncEnd`/`error` handlers can read it.\n *\n * Node passes `@sentry/opentelemetry/tracing-channel`, which uses `bindStore` to additionally make\n * the span the active OTel context for the duration of the traced operation. That is what makes\n * nested AI SDK operations (model calls, tool calls) become children of the enclosing span without\n * any manual parent bookkeeping here.\n */\nexport type VercelAiTracingChannelFactory = <T extends object>(name: string) => TracingChannel<T, T>;\n\n/**\n * The call that `recordInputs`/`recordOutputs` decide on, and that the span hooks get: one span, with the AI SDK\n * telemetry event as published.\n */\nexport interface VercelAiCallInfo {\n /** The channel event type, such as `generateText`, `languageModelCall` or `executeTool`. */\n type: ChannelEventType;\n /** The AI SDK telemetry event of the call. */\n event: Record<string, unknown>;\n}\n\n/**\n * Integration options, pinned at subscribe time so we never look the integration up per event. `onSpanEnd` gets the\n * AI SDK result of the call as `response`; for streams it is `undefined`.\n */\nexport type VercelAiChannelOptions = GenAiCallOptions<VercelAiCallInfo> & GenAiSpanHooks<VercelAiCallInfo>;\n\n// The integration-level decision of each span, made at span start in the caller's async context. The rest of the\n// precedence (eve mode, the per-call flags, `dataCollection.genAI`) is applied when it is needed, because whether\n// `ai` withheld the result is only known at span end.\nconst integrationRecordingBySpan = new WeakMap<Span, GenAiOptions>();\n\n// `ai` >= 7.0.163 publishes no channel `result` for calls with `recordInputs`/`recordOutputs: false`. These stay\n// here rather than on the shared channel message, which other subscribers can read.\nexport const fallbackChannelResults = new WeakMap<Span, unknown>();\n\nconst spanEndHooks = new WeakMap<Span, (result: GenAiSpanResult<unknown>) => void>();\n\n/** Runs the `onSpanEnd` hook of a span that `createSpanFromMessage` started. Call it right before the span ends. */\nexport function runVercelAiSpanEnd(span: Span, result: GenAiSpanResult<unknown>): void {\n spanEndHooks.get(span)?.(result);\n}\n\n/**\n * Subscribe Sentry span handlers to the `ai` SDK's native telemetry tracing channel (`ai:telemetry`,\n * available in `ai` >= 7) and emit fully-formed `gen_ai.*` spans directly — no OpenTelemetry span\n * post-processing involved.\n *\n * The integration passes its options in directly (rather than us looking the integration up on every\n * event); the global `dataCollection.genAI` default is still read from the client per event.\n *\n * Safe to always call: on `ai` versions that don't publish to the channel (e.g. < 7) nothing is\n * ever emitted and this is inert, so there is no double-instrumentation against the OTel-based\n * patcher. The integration's `setupOnce` guarantees this runs a single time.\n */\nexport function subscribeVercelAiTracingChannel(\n tracingChannel: VercelAiTracingChannelFactory,\n options: VercelAiChannelOptions = {},\n): void {\n bindTracingChannelToSpan(\n tracingChannel<VercelAiChannelMessage>(AI_SDK_TELEMETRY_TRACING_CHANNEL),\n data => createSpanFromMessage(data, options),\n {\n // The helper ends the span; we enrich it from the settled result first (tokens, output messages,\n // finish reasons, response model/id, provider metadata) and drop the per-operation `callId` maps.\n beforeSpanEnd: (span, data) => {\n enrichSpanOnEnd(span, data);\n runVercelAiSpanEnd(\n span,\n 'error' in data ? { error: data.error } : { response: getNonStreamResult(span, data) },\n );\n // The result can hold the provider request and response bodies, and spans outlive the call.\n fallbackChannelResults.delete(span);\n clearOperationId(data);\n },\n // A streamed model call resolves before its stream is drained, so we tap the stream, keep the\n // span open, and end it (via `end`) once the final usage/finish/output chunks arrive.\n deferSpanEnd: ({ span, data, end }) => deferStreamedModelCallEnd(span, data, end),\n },\n );\n}\n\nfunction getNonStreamResult(span: Span, data: VercelAiChannelMessage): unknown {\n const result = fallbackChannelResults.get(span) ?? data.result;\n return isObjectLike(result) && isReadableStream(result.stream) ? undefined : result;\n}\n\n/**\n * When a `languageModelCall` resolves to a live `ReadableStream`, defer ending its span: swap in a\n * passthrough that forwards chunks to the SDK untouched while aggregating usage/finish/output, then\n * enrich and end the span once the stream settles. Returns `false` for anything that isn't a streamed\n * model call so the helper ends the span as usual.\n */\nfunction deferStreamedModelCallEnd(span: Span, data: VercelAiChannelMessage, end: (error?: unknown) => void): boolean {\n const result = fallbackChannelResults.get(span) ?? data.result;\n if (data.type !== 'languageModelCall' || !isObjectLike(result)) {\n return false;\n }\n const stream = result.stream;\n if (!isReadableStream(stream)) {\n return false;\n }\n\n const callId = asString(data.event.callId);\n const invokeAgentSpan = callId ? invokeAgentSpanByCallId.get(callId) : undefined;\n const { recordOutputs } = getRecordingOptions(\n data.event,\n invokeAgentSpan && integrationRecordingBySpan.get(invokeAgentSpan),\n data.result === undefined,\n );\n result.stream = tapModelCallStream(\n span,\n stream,\n final => {\n // Reshape the aggregate into the result `enrichSpanOnEnd` expects, then let `end` run it (it calls\n // `beforeSpanEnd`). Enriching the model-call span and the parent from the same aggregate keeps\n // streamed and non-streamed spans identical.\n fallbackChannelResults.set(span, { ...result, ...streamedResultToChannelResult(final) });\n end();\n if (invokeAgentSpan) {\n enrichInvokeAgentFromStream(invokeAgentSpan, final, recordOutputs);\n }\n },\n error => end(error),\n );\n\n return true;\n}\n\n/** Map the tapped stream aggregate onto the `languageModelCall` result shape `enrichSpanOnEnd` reads. */\nexport function streamedResultToChannelResult(final: StreamedModelCallResult): Record<string, unknown> {\n const content: Array<Record<string, unknown>> = [];\n if (final.text) {\n content.push({ type: 'text', text: final.text });\n }\n for (const toolCall of final.toolCalls) {\n content.push({ type: 'tool-call', ...toolCall });\n }\n\n return {\n content,\n ...(final.usage !== undefined ? { usage: final.usage } : {}),\n ...(final.finishReason !== undefined ? { finishReason: final.finishReason } : {}),\n ...(final.providerMetadata !== undefined ? { providerMetadata: final.providerMetadata } : {}),\n ...(final.responseId || final.responseModel\n ? {\n response: {\n ...(final.responseId ? { id: final.responseId } : {}),\n ...(final.responseModel ? { modelId: final.responseModel } : {}),\n },\n }\n : {}),\n };\n}\n\n/**\n * Propagate a streamed model call's usage (summed across the operation's model calls) and output onto\n * the enclosing `invoke_agent` span, which has no channel result of its own. Runs before that span ends\n * because the operation's completion promise settles only after every model-call stream has drained.\n */\nfunction enrichInvokeAgentFromStream(span: Span, final: StreamedModelCallResult, recordOutputs: boolean): void {\n const usage = modelCallUsage(final.usage, final.providerMetadata);\n for (const key of TOKEN_KEYS) {\n addTokensToSpan(span, TOKEN_ATTRIBUTES[key], usage[key]);\n }\n\n if (recordOutputs) {\n const parts = partsFromTextAndToolCalls(final.text, final.toolCalls);\n const outputMessages = buildOutputMessages(parts, getFinishReason({ finishReason: final.finishReason }));\n if (outputMessages) {\n span.setAttribute(GEN_AI_OUTPUT_MESSAGES, outputMessages);\n }\n }\n}\n\n/** Add `value` into a span's numeric token attribute, using the span itself as the running sum. */\nfunction addTokensToSpan(span: Span, attribute: string, value: number | undefined): void {\n if (value === undefined) {\n return;\n }\n const current = spanToJSON(span).attributes[attribute];\n span.setAttribute(attribute, (typeof current === 'number' ? current : 0) + value);\n}\n\n/**\n * Transform a channel `start` payload into the span that should be active for the operation. For\n * `step` we deliberately don't open a span (model calls and tool calls are siblings under the\n * invoke_agent span, matching the OTel-based output), so we reuse the active span and mark the\n * payload to skip ending it.\n */\nexport function createSpanFromMessage(\n data: VercelAiChannelMessage,\n channelOptions: VercelAiChannelOptions,\n): Span | undefined {\n const { type, event } = data;\n\n if (type === 'step' || !event || typeof event !== 'object') {\n // Opt out: returning `undefined` leaves the enclosing `invoke_agent` span as the active context\n // (model-call and tool-call events nest under it) without opening — or ending — a span of its own.\n return undefined;\n }\n\n const call: VercelAiCallInfo = { type, event };\n const integrationRecording: GenAiOptions = {\n recordInputs: resolveRecordingOption(channelOptions.recordInputs, call),\n recordOutputs: resolveRecordingOption(channelOptions.recordOutputs, call),\n };\n const span = startSpanFromEvent(type, event, getRecordingOptions(event, integrationRecording).recordInputs);\n if (span) {\n integrationRecordingBySpan.set(span, integrationRecording);\n runGenAiSpanStart(channelOptions, span, call);\n spanEndHooks.set(span, result => runGenAiSpanEnd(channelOptions, span, call, result));\n }\n return span;\n}\n\nfunction startSpanFromEvent(\n type: ChannelEventType,\n event: Record<string, unknown>,\n recordInputs: boolean,\n): Span | undefined {\n const provider = asString(event.provider);\n const modelId = asString(event.modelId);\n const callId = asString(event.callId);\n const maxRetries = asNumber(event.maxRetries);\n\n // Harvest tool descriptions from the operation/model-call `tools` so tool spans can backfill them.\n // Gated on `recordInputs` to match the OTel path, which only records `tool.definitions` then.\n if (recordInputs) {\n recordToolDescriptions(callId, event.tools);\n }\n\n // Only an operation's start event carries `providerOptions`; its model-call and tool events start\n // while the operation span is active, so they inherit the id from it. A root operation never\n // inherits, so a nested call (e.g. inside a tool's `execute`) is not folded into the outer conversation.\n const conversationId =\n getOpenAiConversationId(event.providerOptions) ??\n (ROOT_OPERATION_TYPES.has(type) ? undefined : getActiveSpanConversationId());\n\n const runtimeContextAttributes =\n (callId ? runtimeContextAttributesByCallId.get(callId) : undefined) ??\n contextAttributes(event, event.runtimeContext, VERCEL_AI_SETTINGS_CONTEXT_KEY_BASE);\n if (callId && ROOT_OPERATION_TYPES.has(type)) {\n runtimeContextAttributesByCallId.set(callId, runtimeContextAttributes);\n }\n\n const baseAttributes: SpanAttributes = {\n [SENTRY_ORIGIN]: ORIGIN,\n ...telemetryMetadataAttributes(event.telemetryMetadata),\n ...runtimeContextAttributes,\n [GEN_AI_PROVIDER_NAME]: provider,\n [VERCEL_AI_MODEL_PROVIDER_ATTRIBUTE]: provider,\n [GEN_AI_REQUEST_MODEL]: modelId,\n [VERCEL_AI_SETTINGS_MAX_RETRIES_ATTRIBUTE]: maxRetries,\n [GEN_AI_CONVERSATION_ID]: conversationId,\n };\n\n switch (type) {\n case 'generateText':\n case 'streamText':\n case 'generateObject':\n case 'streamObject':\n // The object variants' operationId rides on `event.operationId`. The JSON-schema attribute the OTel\n // path derives from the SDK's Zod schema is not reconstructed on the channel path.\n return buildInvokeAgentSpan(\n event,\n baseAttributes,\n recordInputs,\n callId,\n type === 'streamText' || type === 'streamObject',\n );\n case 'languageModelCall':\n _INTERNAL_skipAiProviderWrapping([WORKERS_AI_INTEGRATION_NAME]);\n\n return buildModelCallSpan(event, baseAttributes, recordInputs, callId, modelId);\n case 'executeTool':\n return buildToolSpan(event, recordInputs, conversationId, runtimeContextAttributes);\n case 'embed':\n case 'embedMany': {\n // `embed` carries a single `value`; `embedMany` a `values` array — both map to the embeddings input.\n const input = type === 'embedMany' ? event.values : event.value;\n return startGenAiSpan('embeddings', modelId, {\n ...baseAttributes,\n ...(recordInputs && !isStrippedInput(input) ? { [GEN_AI_EMBEDDINGS_INPUT]: stringify(input) } : {}),\n });\n }\n case 'rerank':\n return startGenAiSpan('rerank', modelId, baseAttributes);\n // `ai` 7.0.128 renamed `experimental_evaluate` to `experimental_decide`; older 7.x still publishes the old name.\n case 'experimental_evaluate':\n case 'experimental_decide':\n return startGenAiSpan('decide', modelId, {\n ...baseAttributes,\n ...(recordInputs && !(isStrippedInput(event.state) && isStrippedInput(event.questions))\n ? {\n [GEN_AI_INPUT_MESSAGES]: stringify([\n { type: 'evaluation', state: event.state, questions: event.questions },\n ]),\n }\n : {}),\n });\n case 'experimental_extract':\n return startGenAiSpan('extract', modelId, {\n ...baseAttributes,\n ...(recordInputs && !(isStrippedInput(event.state) && isStrippedInput(event.fields))\n ? {\n [GEN_AI_INPUT_MESSAGES]: stringify([\n {\n ...toExtractState(event.state).request,\n fields: toExtractFields(event.fields),\n reference_date: event.referenceDate,\n },\n ]),\n }\n : {}),\n });\n default:\n // Unknown event type: opt out rather than open a span we can't shape correctly.\n return undefined;\n }\n}\n\n/**\n * `experimental_telemetry.metadata` (`ai` <= 6) as `vercel.ai.telemetry.metadata.<key>`, the names the OTel\n * integration produced from the SDK's `ai.telemetry.metadata.*`. Only the orchestrion adapter sets\n * `event.telemetryMetadata`; `ai` 7 has no `telemetry.metadata`.\n */\nfunction telemetryMetadataAttributes(metadata: unknown): Record<string, string> {\n const attributes: Record<string, string> = {};\n if (isObjectLike(metadata)) {\n for (const [key, value] of Object.entries(metadata)) {\n if (value === null || value === undefined) continue;\n attributes[`${VERCEL_AI_TELEMETRY_METADATA_ATTRIBUTE_PREFIX}${key}`] = String(value);\n }\n }\n return attributes;\n}\n\n/**\n * One string attribute per context key, as `<prefix><key>`. `ai` < 7.0.114 published the full context to the\n * channel, ignoring `telemetry.includeRuntimeContext`/`includeToolsContext`, and a filtered context\n * looks the same as an unfiltered one. `aiVersion` (added in 7.0.154) is the only reliable sign that\n * the AI SDK filtered it, so without it we record nothing.\n */\nfunction contextAttributes(event: Record<string, unknown>, context: unknown, keyBase: string): SpanAttributes {\n const attributes: SpanAttributes = {};\n if (typeof event.aiVersion !== 'string' || !isObjectLike(context)) {\n return attributes;\n }\n for (const [key, value] of Object.entries(context)) {\n const attributeValue = stringify(value);\n if (value !== null && attributeValue !== undefined) {\n attributes[`${keyBase}.${key}`] = attributeValue;\n }\n }\n return attributes;\n}\n\n/** Start a `gen_ai.<operation>` span named `<operation> <suffix>` (or just `<operation>` when no suffix). */\nfunction startGenAiSpan(operation: GenAiOperation, suffix: string | undefined, attributes: SpanAttributes): Span {\n return startInactiveSpan({\n name: suffix ? `${operation} ${suffix}` : operation,\n attributes: {\n [SENTRY_OP]: GEN_AI_OPERATION_SPAN_OPS[operation],\n [GEN_AI_OPERATION_NAME]: operation,\n ...attributes,\n },\n });\n}\n\nfunction buildInvokeAgentSpan(\n event: Record<string, unknown>,\n baseAttributes: SpanAttributes,\n recordInputs: boolean,\n callId: string | undefined,\n isStream: boolean,\n): Span {\n const functionId = asString(event.functionId);\n const operationId = asString(event.operationId) ?? (isStream ? 'ai.streamText' : 'ai.generateText');\n if (callId) {\n operationIdByCallId.set(callId, { operationId, isStream });\n }\n const span = startGenAiSpan('invoke_agent', functionId, {\n ...baseAttributes,\n [VERCEL_AI_OPERATION_ID_ATTRIBUTE]: operationId,\n [GEN_AI_RESPONSE_STREAMING]: isStream,\n [GEN_AI_FUNCTION_ID]: functionId,\n ...(recordInputs ? buildInputMessageAttributes(event) : {}),\n });\n if (isStream && callId) {\n invokeAgentSpanByCallId.set(callId, span);\n }\n\n return span;\n}\n\nfunction buildModelCallSpan(\n event: Record<string, unknown>,\n baseAttributes: SpanAttributes,\n recordInputs: boolean,\n callId: string | undefined,\n modelId: string | undefined,\n): Span {\n const parent = callId ? operationIdByCallId.get(callId) : undefined;\n const operationId = parent\n ? `${parent.operationId}.${parent.isStream ? 'doStream' : 'doGenerate'}`\n : 'ai.generateText.doGenerate';\n return startGenAiSpan('generate_content', modelId, {\n ...baseAttributes,\n [VERCEL_AI_OPERATION_ID_ATTRIBUTE]: operationId,\n ...(recordInputs ? buildInputMessageAttributes(event) : {}),\n ...(recordInputs && Array.isArray(event.tools) ? { [GEN_AI_TOOL_DEFINITIONS]: stringify(event.tools) } : {}),\n });\n}\n\nfunction buildToolSpan(\n event: Record<string, unknown>,\n recordInputs: boolean,\n conversationId: string | undefined,\n runtimeContextAttributes: SpanAttributes,\n): Span {\n const toolCall = isObjectLike(event.toolCall) ? event.toolCall : {};\n const toolName = asString(toolCall.toolName);\n const toolCallId = asString(event.toolCallId) ?? asString(toolCall.toolCallId);\n const toolInput = toolCall.input ?? toolCall.args;\n // The `executeTool` event has no description; backfill it from the operation's recorded tools.\n // Gated on `recordInputs` to match the OTel path (descriptions come from the recorded tools list).\n const description =\n recordInputs && toolName ? resolveToolDescription(asString(event.callId), toolName, event.tools) : undefined;\n return startGenAiSpan('execute_tool', toolName, {\n [SENTRY_ORIGIN]: ORIGIN,\n ...runtimeContextAttributes,\n ...contextAttributes(event, event.toolContext, VERCEL_AI_TOOL_CALL_CONTEXT_KEY_BASE),\n [GEN_AI_TOOL_NAME]: toolName,\n [GEN_AI_TOOL_CALL_ID_ATTRIBUTE]: toolCallId,\n [GEN_AI_TOOL_DESCRIPTION]: description,\n ...(recordInputs && toolInput !== undefined ? { [GEN_AI_TOOL_CALL_ARGUMENTS]: stringify(toolInput) } : {}),\n [GEN_AI_CONVERSATION_ID]: conversationId,\n });\n}\n\n/**\n * Best-effort enrichment from the resolved value the AI SDK attaches to the channel context.\n * Everything here is guarded: when a field is missing or the shape differs across `ai` versions,\n * we simply don't set the attribute rather than emit a malformed span.\n */\nexport function enrichSpanOnEnd(span: Span, data: VercelAiChannelMessage): void {\n const { type } = data;\n const result = fallbackChannelResults.get(span) ?? data.result;\n if (!isObjectLike(result)) {\n return;\n }\n\n const { recordOutputs } = getRecordingOptions(\n data.event,\n integrationRecordingBySpan.get(span),\n data.result === undefined,\n );\n\n if (type === 'executeTool') {\n // From V5 on, tool errors are not rejected (so the `error` channel verb never fires) — they\n // surface as `tool-error` content on the resolved result. Mirror the OTel path by marking the\n // span and capturing the error, which carry the failure instead of the result attribute.\n const output = isObjectLike(result.output) ? result.output : undefined;\n if (output?.type === 'tool-error') {\n captureToolError(span, data, output.error);\n } else if (recordOutputs) {\n span.setAttribute(GEN_AI_TOOL_CALL_RESULT, stringify(result.output ?? result));\n }\n return;\n }\n\n const providerMetadata = result.providerMetadata;\n const usage = ROOT_OPERATION_TYPES.has(type)\n ? operationUsage(result, providerMetadata)\n : modelCallUsage(result.usage, providerMetadata);\n for (const key of TOKEN_KEYS) {\n const value = usage[key];\n if (value !== undefined) {\n span.setAttribute(TOKEN_ATTRIBUTES[key], value);\n }\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 span.setAttributes(getProviderOnlyAttributes(providerMetadata, type));\n\n if (recordOutputs) {\n const outputMessages = getOutputMessages(type, result, finishReason, data.event);\n if (outputMessages) {\n span.setAttribute(GEN_AI_OUTPUT_MESSAGES, outputMessages);\n }\n }\n}\n\nfunction getOutputMessages(\n type: ChannelEventType,\n result: Record<string, unknown>,\n finishReason: string | undefined,\n event: Record<string, unknown>,\n): string | undefined {\n if (type === 'experimental_evaluate' || type === 'experimental_decide') {\n return getEvaluationOutputMessages(withProviderAnswerFields(result));\n }\n if (type === 'experimental_extract') {\n return isObjectLike(result.answers)\n ? stringify([{ answers: toExtractAnswers(result.answers, toExtractState(event.state).parts) }])\n : undefined;\n }\n // `languageModelCall` exposes the response as a `content` parts array; top-level results expose\n // `text` + `toolCalls`. Both normalize into the OTel `gen_ai.output.messages` assistant message.\n const parts =\n type === 'languageModelCall' && Array.isArray(result.content)\n ? partsFromContent(result.content)\n : partsFromTextAndToolCalls(result.text, result.toolCalls);\n return buildOutputMessages(parts, finishReason);\n}\n\n/**\n * Providers move answer fields into `providerMetadata`: TypeSafe and OpenAI as `<provider>.confidence[id]`,\n * OpenRouter as `openrouter.answers[id].{confidence,legend}`. Put them back on the answers.\n */\nfunction withProviderAnswerFields(result: Record<string, unknown>): unknown {\n const { answers, providerMetadata } = result;\n if (!isObjectLike(answers) || !isObjectLike(providerMetadata)) {\n return answers;\n }\n const confidenceById = [providerMetadata.typesafe, providerMetadata.openai]\n .map(metadata => (isObjectLike(metadata) ? metadata.confidence : undefined))\n .find(isObjectLike);\n const { openrouter } = providerMetadata;\n const openrouterById = isObjectLike(openrouter) && isObjectLike(openrouter.answers) ? openrouter.answers : undefined;\n if (!confidenceById && !openrouterById) {\n return answers;\n }\n\n return mapObjectValues(answers, (answer, id) => {\n const openrouterAnswer = openrouterById?.[id];\n const fields = isObjectLike(openrouterAnswer) ? openrouterAnswer : {};\n const {\n confidence = asNumber(confidenceById?.[id]) ?? asNumber(fields.confidence),\n legend = isObjectLike(fields.legend) ? fields.legend : undefined,\n } = answer;\n return { ...answer, confidence, legend };\n });\n}\n\n/** Maps a Vercel AI finish reason to the OTel `gen_ai.output.messages` form (`tool-calls` → `tool_call`). */\nfunction normalizeFinishReason(finishReason: string | undefined): string {\n return finishReason === 'tool-calls' ? 'tool_call' : (finishReason ?? 'stop');\n}\n\n/** Reads the finish reason from a result — a string on top-level results, `{ unified }` on model calls. */\nfunction getFinishReason(result: Record<string, unknown>): string | undefined {\n const finishReason = result.finishReason;\n if (typeof finishReason === 'string') {\n return finishReason;\n }\n return isObjectLike(finishReason) ? asString(finishReason.unified) : undefined;\n}\n\n/** Reads a token count that may be a plain number or a `{ total }` object (model-call usage). */\nfunction tokenCount(value: unknown): number | undefined {\n return asNumber(value) ?? (isObjectLike(value) ? asNumber(value.total) : undefined);\n}\n\n/**\n * Reasoning from the SDK's usage: v6+ for every provider, v5 only for OpenAI, whose output includes it.\n * Other v5 providers don't say whether their output does, and Google's comes from `providerMetadata`.\n */\nfunction reasoningTokens(usage: Record<string, unknown>, providerMetadata: unknown): number | undefined {\n const outputTokens = isObjectLike(usage.outputTokens) ? usage.outputTokens : undefined;\n const outputTokenDetails = isObjectLike(usage.outputTokenDetails) ? usage.outputTokenDetails : undefined;\n const reasoning = asNumber(outputTokens?.reasoning) ?? asNumber(outputTokenDetails?.reasoningTokens);\n if (reasoning !== undefined) {\n return reasoning;\n }\n const metadata = isObjectLike(providerMetadata) ? providerMetadata : undefined;\n return metadata?.openai || metadata?.azure ? asNumber(usage.reasoningTokens) : undefined;\n}\n\ninterface TokenUsage {\n input?: number;\n output?: number;\n total?: number;\n cacheRead?: number;\n cacheWrite?: number;\n reasoning?: number;\n}\n\nconst TOKEN_ATTRIBUTES: Record<keyof TokenUsage, string> = {\n input: GEN_AI_USAGE_INPUT_TOKENS,\n output: GEN_AI_USAGE_OUTPUT_TOKENS,\n total: GEN_AI_USAGE_TOTAL_TOKENS,\n cacheRead: GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS,\n cacheWrite: GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS,\n reasoning: GEN_AI_USAGE_REASONING_OUTPUT_TOKENS,\n};\n\nconst TOKEN_KEYS = Object.keys(TOKEN_ATTRIBUTES) as Array<keyof TokenUsage>;\n\n/**\n * One model call's final token counts: its usage (flat or `{ total }`, v4 `promptTokens`/`completionTokens`)\n * corrected by its own `providerMetadata`.\n */\nfunction modelCallUsage(usage: unknown, providerMetadata: unknown): TokenUsage {\n const derived = getProviderMetadataAttributes(providerMetadata);\n const counts = isObjectLike(usage) ? usage : {};\n const input = tokenCount(counts.inputTokens) ?? tokenCount(counts.promptTokens) ?? tokenCount(counts.tokens);\n const output =\n asNumber(derived[GEN_AI_USAGE_OUTPUT_TOKENS]) ??\n tokenCount(counts.outputTokens) ??\n tokenCount(counts.completionTokens);\n const { cacheRead, cacheWrite } = cacheTokens(counts);\n return {\n input,\n output,\n total: asNumber(derived[GEN_AI_USAGE_TOTAL_TOKENS]) ?? tokenCount(counts.totalTokens) ?? sum(input, output),\n cacheRead: asNumber(derived[GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS]) ?? cacheRead,\n cacheWrite: asNumber(derived[GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS]) ?? cacheWrite,\n reasoning: reasoningTokens(counts, providerMetadata) ?? asNumber(derived[GEN_AI_USAGE_REASONING_OUTPUT_TOKENS]),\n };\n}\n\n/**\n * An operation's token counts, summed over its steps, which can use different providers. Every text\n * operation from v4 on has `steps`; the others are a single model call.\n */\nfunction operationUsage(result: Record<string, unknown>, providerMetadata: unknown): TokenUsage {\n const steps = Array.isArray(result.steps) ? result.steps.filter(isObjectLike) : [];\n if (!steps.length) {\n return modelCallUsage(result.usage, providerMetadata);\n }\n const total: TokenUsage = {};\n for (const step of steps) {\n const stepUsage = modelCallUsage(step.usage, step.providerMetadata);\n for (const key of TOKEN_KEYS) {\n total[key] = sum(total[key], stepUsage[key]);\n }\n }\n return total;\n}\n\n/**\n * Cache token counts as the AI SDK normalizes them: v5 `cachedInputTokens`, v6 `inputTokenDetails`,\n * v7 `inputTokens.{cacheRead,cacheWrite}`.\n */\nfunction cacheTokens(usage: Record<string, unknown>): { cacheRead?: number; cacheWrite?: number } {\n const inputTokens = isObjectLike(usage.inputTokens) ? usage.inputTokens : undefined;\n const inputTokenDetails = isObjectLike(usage.inputTokenDetails) ? usage.inputTokenDetails : undefined;\n return {\n cacheRead:\n asNumber(inputTokens?.cacheRead) ??\n asNumber(inputTokenDetails?.cacheReadTokens) ??\n asNumber(usage.cachedInputTokens),\n cacheWrite: asNumber(inputTokens?.cacheWrite) ?? asNumber(inputTokenDetails?.cacheWriteTokens),\n };\n}\n\nfunction buildOutputMessages(\n parts: Array<Record<string, unknown>>,\n finishReason: string | undefined,\n): string | undefined {\n if (!parts.length) {\n return undefined;\n }\n return stringify([{ role: 'assistant', parts, finish_reason: normalizeFinishReason(finishReason) }]);\n}\n\nfunction toolCallPart(toolCall: Record<string, unknown>): Record<string, unknown> {\n const args = toolCall.input ?? toolCall.args;\n return {\n type: 'tool_call',\n id: asString(toolCall.toolCallId),\n name: asString(toolCall.toolName),\n arguments: typeof args === 'string' ? args : stringify(args ?? {}),\n };\n}\n\nfunction partsFromContent(content: unknown[]): Array<Record<string, unknown>> {\n const parts: Array<Record<string, unknown>> = [];\n for (const item of content) {\n if (!isObjectLike(item)) {\n continue;\n }\n if (item.type === 'text' && typeof item.text === 'string') {\n parts.push({ type: 'text', content: item.text });\n } else if (item.type === 'tool-call') {\n parts.push(toolCallPart(item));\n }\n }\n return parts;\n}\n\nfunction partsFromTextAndToolCalls(text: unknown, toolCalls: unknown): Array<Record<string, unknown>> {\n const parts: Array<Record<string, unknown>> = [];\n if (typeof text === 'string' && text.length) {\n parts.push({ type: 'text', content: text });\n }\n if (Array.isArray(toolCalls)) {\n for (const toolCall of toolCalls) {\n if (isObjectLike(toolCall)) {\n parts.push(toolCallPart(toolCall));\n }\n }\n }\n return parts;\n}\n\nexport function captureToolError(span: Span, data: VercelAiChannelMessage, error: unknown): void {\n span.setStatus({\n code: SPAN_STATUS_ERROR,\n message: error instanceof Error ? error.message : 'tool_error',\n });\n\n const toolCall = isObjectLike(data.event.toolCall) ? data.event.toolCall : {};\n const toolName = asString(toolCall.toolName);\n const toolCallId = asString(data.event.toolCallId) ?? asString(toolCall.toolCallId);\n\n withScope(scope => {\n scope.setContext('trace', spanToTraceContext(span));\n if (toolName) {\n scope.setTag('vercel.ai.tool.name', toolName);\n }\n if (toolCallId) {\n scope.setTag('vercel.ai.tool.callId', toolCallId);\n }\n scope.setLevel('error');\n captureException(\n error instanceof Error ? error : new Error(typeof error === 'string' ? error : 'Tool execution failed'),\n {\n mechanism: { type: 'auto.ai.vercelai', handled: false },\n },\n );\n });\n}\n\nfunction getRecordingOptions(\n event: Record<string, unknown>,\n integrationRecording: GenAiOptions = {},\n channelWithheldResult = false,\n): {\n recordInputs: boolean;\n recordOutputs: boolean;\n} {\n const client = getClient();\n const genAI = client?.getDataCollectionOptions().genAI;\n // `ai` withheld the result because of the per-call flag, which eve >= 1.0.0-rc.10 sets from trace policies, so\n // the flag is a content decision there rather than eve's blanket default.\n const eveMode = client && !channelWithheldResult ? isEveGenAiRecordingDefault(client) : false;\n\n return {\n recordInputs: resolveRecording(integrationRecording.recordInputs, event.recordInputs, genAI?.inputs, eveMode),\n recordOutputs: resolveRecording(integrationRecording.recordOutputs, event.recordOutputs, genAI?.outputs, eveMode),\n };\n}\n\n/**\n * Mirrors the OTel integration's `determineRecordingSettings` precedence: an integration-level option\n * wins, then the per-call `experimental_telemetry.recordInputs/recordOutputs` flag the AI SDK forwards\n * on the channel event, then the global `dataCollection.genAI` default.\n *\n * NOTE: the OTel integration also defaults recording to `true` for a call with\n * `experimental_telemetry: { isEnabled: true }`. The `ai:telemetry` channel does not expose `isEnabled`\n * (nor a resolved recording flag), so that per-call default cannot be reproduced here — v7 users who\n * want inputs/outputs recorded must enable `dataCollection.genAI` or set `recordInputs`/`recordOutputs`.\n *\n * Under `eveMode` (set by `eveIntegration()`) the per-call flag is eve's blanket framework default\n * rather than an end-user decision, so it is skipped: an explicit `dataCollection.genAI` still wins,\n * otherwise recording defaults to `true`. An integration-level option outranks both regardless.\n */\nfunction resolveRecording(\n integrationOption: unknown,\n perCallOption: unknown,\n globalDefault: unknown,\n eveMode = false,\n): boolean {\n if (typeof integrationOption === 'boolean') {\n return integrationOption;\n }\n if (eveMode) {\n return typeof globalDefault === 'boolean' ? globalDefault : true;\n }\n if (typeof perCallOption === 'boolean') {\n return perCallOption;\n }\n return globalDefault === true;\n}\n\n/** `ai` >= 7.0.163 replaces inputs with empty values when `recordInputs` is false. */\nfunction isStrippedInput(input: unknown): boolean {\n return (\n input === undefined ||\n input === '' ||\n (Array.isArray(input) && !input.length) ||\n (isPlainObject(input) && !Object.keys(input).length)\n );\n}\n\n/** The `ai` SDK accepts the system prompt as `string | SystemModelMessage | SystemModelMessage[]`. */\nfunction getSystemInstructionParts(instructions: unknown): { type: 'text'; content: string }[] {\n const messages = Array.isArray(instructions) ? instructions : [instructions];\n return messages.flatMap(message => {\n const content = asString(isObjectLike(message) ? message.content : message);\n return content ? [{ type: 'text' as const, content }] : [];\n });\n}\n\nfunction buildInputMessageAttributes(event: Record<string, unknown>): Record<string, string | number | undefined> {\n const attributes: Record<string, string | number | undefined> = {};\n\n // `ai` >= 7 forbids system messages in `messages`/`prompt` and exposes the system prompt as a\n // separate `instructions` field. The OTel path lifts the system message out of the prompt into\n // `gen_ai.system_instructions` as `[{ type: 'text', content }]`; mirror that shape here.\n const instructions = getSystemInstructionParts(event.instructions);\n if (instructions.length) {\n attributes[GEN_AI_SYSTEM_INSTRUCTIONS] = stringify(instructions);\n }\n\n // The AI SDK start events extend `StandardizedPrompt`; messages live on `messages`, otherwise the\n // simpler `prompt` field is used.\n const messages = event.messages ?? event.prompt;\n if (!isStrippedInput(messages)) {\n attributes[GEN_AI_INPUT_MESSAGES] = stringify(messages);\n }\n\n return attributes;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA0FA,MAAa,mCAAmC;AAEhD,MAAM,SAAS;AAGf,MAAM,4BAA4B;CAChC,YAAY;CAIZ,QAAQ;CACR,QAAQ;CACR,SAAS;CACT,cAAc;CACd,cAAc;CAGd,kBAAkB;AACpB;AAKA,MAAM,mCAAmC;AACzC,MAAM,qCAAqC;AAC3C,MAAM,2CAA2C;AACjD,MAAM,gDAAgD;AAMtD,MAAM,sCAAsB,IAAI,IAAwD;AASxF,MAAM,2CAA2B,IAAI,IAAiC;AAMtE,MAAM,0CAA0B,IAAI,IAAkB;AAItD,MAAM,mDAAmC,IAAI,IAA4B;AAIzE,MAAM,uCAAuB,IAAI,IAAsB;CACrD;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAID,MAAM,+CAA+B,IAAI,IAAsB;CAC7D;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;CAC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AU,YAAY;CAKjE,MAAM,WAAW,MAAM,YAAY,MAAM;CACzC,IAAI,CAAC,gBAAgB,QAAQ,GAC3B,WAAW,yBAAyB,UAAU,QAAQ;CAGxD,OAAO;AACT"}
|
|
@@ -147,8 +147,8 @@ function deferStreamTextOperationEnd(span, data, end) {
|
|
|
147
147
|
const streamResult = data.result;
|
|
148
148
|
(async () => {
|
|
149
149
|
try {
|
|
150
|
-
const [usage, text, objectOutcome, toolCalls, finishReason, response] = await Promise.all([
|
|
151
|
-
streamResult.
|
|
150
|
+
const [usage, text, objectOutcome, toolCalls, finishReason, response, steps, providerMetadata] = await Promise.all([
|
|
151
|
+
streamResult.usage,
|
|
152
152
|
streamResult.text,
|
|
153
153
|
type === "streamObject" ? Promise.resolve(streamResult.object).then((value) => ({ value }), (error) => ({
|
|
154
154
|
value: void 0,
|
|
@@ -156,26 +156,28 @@ function deferStreamTextOperationEnd(span, data, end) {
|
|
|
156
156
|
})) : { value: void 0 },
|
|
157
157
|
streamResult.toolCalls,
|
|
158
158
|
streamResult.finishReason,
|
|
159
|
-
streamResult.response
|
|
159
|
+
streamResult.response,
|
|
160
|
+
streamResult.steps,
|
|
161
|
+
streamResult.providerMetadata
|
|
160
162
|
]);
|
|
163
|
+
const result = {
|
|
164
|
+
usage,
|
|
165
|
+
toolCalls,
|
|
166
|
+
finishReason,
|
|
167
|
+
response,
|
|
168
|
+
steps,
|
|
169
|
+
providerMetadata
|
|
170
|
+
};
|
|
161
171
|
if ("error" in objectOutcome) {
|
|
162
|
-
message.result =
|
|
163
|
-
usage,
|
|
164
|
-
toolCalls,
|
|
165
|
-
finishReason,
|
|
166
|
-
response
|
|
167
|
-
};
|
|
172
|
+
message.result = result;
|
|
168
173
|
enrichSpanOnEnd(span, message);
|
|
169
174
|
end(objectOutcome.error);
|
|
170
175
|
return;
|
|
171
176
|
}
|
|
172
177
|
const object = objectOutcome.value;
|
|
173
178
|
data.result = {
|
|
174
|
-
|
|
175
|
-
text: text ?? (isObjectLike(object) ? JSON.stringify(object) : object)
|
|
176
|
-
toolCalls,
|
|
177
|
-
finishReason,
|
|
178
|
-
response
|
|
179
|
+
...result,
|
|
180
|
+
text: text ?? (isObjectLike(object) ? JSON.stringify(object) : object)
|
|
179
181
|
};
|
|
180
182
|
end();
|
|
181
183
|
} catch (error) {
|
|
@@ -184,9 +186,12 @@ function deferStreamTextOperationEnd(span, data, end) {
|
|
|
184
186
|
})();
|
|
185
187
|
return true;
|
|
186
188
|
}
|
|
187
|
-
/**
|
|
189
|
+
/**
|
|
190
|
+
* A streamed result exposes its aggregates as promises; a settled result does not. Reading `totalUsage`
|
|
191
|
+
* would create a promise that rejects unobserved when the stream aborts.
|
|
192
|
+
*/
|
|
188
193
|
function isStreamingResult(result) {
|
|
189
|
-
return isObjectLike(result) && (isThenable(result.
|
|
194
|
+
return isObjectLike(result) && (isThenable(result.steps) || isThenable(result.usage));
|
|
190
195
|
}
|
|
191
196
|
function isThenable(value) {
|
|
192
197
|
return isObjectLike(value) && typeof value.then === "function";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"vercel-ai-orchestrion-subscriber.js","names":[],"sources":["../../../../src/integrations/vercel-ai/vercel-ai-orchestrion-subscriber.ts"],"sourcesContent":["/* eslint-disable max-lines */\nimport type { Span } from '@sentry/core';\nimport {\n addNonEnumerableProperty,\n debug,\n getActiveSpan,\n isObjectLike,\n SPAN_STATUS_ERROR,\n withActiveSpan,\n} from '@sentry/core';\nimport { DEBUG_BUILD } from '../../debug-build';\nimport type { OrchestrionChannelContext } from '../../orchestrion/types';\nimport { CHANNELS } from '../../orchestrion/channels';\nimport { bindTracingChannelToSpan, type TracingChannelPayloadWithSpan } from '../../tracing-channel';\nimport type { GenAiSpanResult } from '../../ai/core/span-hooks';\nimport {\n captureToolError,\n clearOperationCallId,\n clearOperationId,\n createSpanFromMessage,\n enrichSpanOnEnd,\n runVercelAiSpanEnd,\n streamedResultToChannelResult,\n type VercelAiChannelMessage,\n type VercelAiChannelOptions,\n type VercelAiTracingChannelFactory,\n} from './vercel-ai-dc-subscriber';\nimport { asString, isReadableStream, tapModelCallStream } from './util';\n\n/**\n * v4, v5 & v6 channel adapter for the Vercel AI (`ai`) SDK.\n *\n * `ai` >= 7 publishes a normalized `ai:telemetry` tracing channel natively\n * (consumed by `subscribeVercelAiTracingChannel`). v4/v5/v6 have no such channel, so\n * orchestrion injects `orchestrion:ai:*` channels around the top-level\n * functions (see `orchestrion/config/index.ts`). The injected channels carry only the\n * wrapped call's `{ arguments, result, error }` — NOT v7's normalized `event`\n * object — so this adapter reconstructs an equivalent {@link VercelAiChannelMessage}\n * from each version's argument/result shapes and delegates to the SAME span-building core\n * (`createSpanFromMessage` / `enrichSpanOnEnd`) the v7 subscriber uses, so the\n * emitted spans are identical between v4, v5, v6 and v7. The shared core reads both v4-style\n * (`promptTokens`/`completionTokens`) and v5+-style (`inputTokens`/`outputTokens`) token names.\n *\n * The model call (`languageModelCall` / `generate_content` span) has no\n * injectable definition in `ai`. On v5/v6 we wrap `resolveLanguageModel` (the\n * single chokepoint every model call flows through) and monkey-patch\n * `doGenerate`/`doStream` on the returned model. v4 has no `resolveLanguageModel`\n * — the passed `LanguageModelV1` (`specificationVersion: 'v1'`) is called directly —\n * so we patch its `doGenerate`/`doStream` at the operation start instead (see\n * `buildOperationSpan`), gated on `'v1'` so it never touches v5/v6 models.\n *\n * Tool-call spans differ by version: v6 exposes a per-call `executeToolCall`\n * function orchestrion wraps into its own channel. v4/v5 have no such export (only a\n * batch `executeTools`), so instead we monkey-patch each tool's `execute` from\n * the operation's `tools`. On v6 that patch is inert: `executeToolCall` runs\n * `execute` inside its own tool-call span (the active async context), so the\n * patch sees that span as its parent and skips — only v4/v5 (where the parent is\n * the enclosing `invoke_agent` span) emit the patched span, so v6 never\n * double-counts tool spans.\n */\n\n/** Builds the normalized message for a channel from the wrapped call's first-arg options. */\ntype MessageBuilder = (options: Record<string, unknown>, telemetry: Record<string, unknown>) => VercelAiChannelMessage;\n\n/** A resolved `ai` language model — has `doGenerate`/`doStream` and identity fields. */\ninterface ResolvedModel {\n modelId?: string;\n provider?: string;\n doGenerate?: (...args: unknown[]) => Promise<unknown>;\n doStream?: (...args: unknown[]) => Promise<unknown>;\n}\n\nconst PATCHED = Symbol('SentryVercelAiModelPatched');\nconst TOOL_PATCHED = Symbol('SentryVercelAiToolPatched');\n\n/** A resolved model with our patch bookkeeping (idempotency flag). */\ntype PatchableModel = ResolvedModel & { [PATCHED]?: boolean };\n\n/** A tool definition off an operation's `tools`, with our patch bookkeeping. */\ntype PatchableTool = { execute?: (...args: unknown[]) => unknown; [TOOL_PATCHED]?: boolean };\n\n// Per-operation correlation id. No Date/random (unavailable / non-deterministic) — a counter is enough.\nlet callIdCounter = 0;\nfunction nextCallId(): string {\n return `v6-${++callIdCounter}`;\n}\n\n// The message built on `start` for each operation, keyed by the (stable-identity) channel context, so\n// the `beforeSpanEnd` handler can enrich the span from the settled result and clear the `callId` maps.\nconst messages = new WeakMap<object, VercelAiChannelMessage>();\n// The spans we opened for top-level operations, and each one's `callId`. A model call resolves its\n// parent against this set (so it never mis-attributes to the enclosing `main`/user span) and reads the\n// parent's `callId` so its span can be named after the operation (e.g. `ai.streamText.doStream`).\nconst operationSpans = new WeakSet<Span>();\n// Tool-call spans — only v6's `executeToolCall` channel opens these. The v5 tool-`execute` patch\n// consults this to avoid double-counting: `executeToolCall` runs `execute` inside its span (which is\n// therefore the active parent), so a resolved parent in this set means v6 already spanned the call.\nconst toolCallSpans = new WeakSet<Span>();\nconst callIdBySpan = new WeakMap<Span, string>();\n// The operation's per-call recording flags (`experimental_telemetry.recordInputs/recordOutputs`), keyed by\n// its span. A model call carries no telemetry of its own, so it inherits the enclosing operation's flags —\n// otherwise a per-call `recordInputs: true` would record inputs on the `invoke_agent` span but not on the\n// child `generate_content` span (whose event would fall back to the global default). v7's channel forwards\n// these flags on every event, so this keeps v6 identical.\nconst recordingBySpan = new WeakMap<Span, ReturnType<typeof recording>>();\n// The operation's `experimental_telemetry.metadata`, keyed by its span, so the model-call span records it\n// too. The OTel integration put it on both, but not on tool-call spans.\nconst telemetryMetadataBySpan = new WeakMap<Span, unknown>();\ninterface OperationErrorInfo {\n // The span active when the operation was invoked (its call site, e.g. the enclosing request/`main` span).\n // When an operation's error bubbles out unhandled it reaches the global handler outside any span, so — as\n // the OTel path does — we stamp this span onto the error (in `beforeSpanEnd`) so the unhandled-rejection\n // handler can restore it and correlate the captured error to the operation's trace.\n callSiteSpan: Span | undefined;\n // Whether a thrown tool error bubbles out of the `ai` call (v4). On v4 a tool-`execute` rejection is\n // wrapped in `AI_ToolExecutionError` and re-thrown, so it reaches the user's own error handling (or our\n // global handlers) — capturing it at the tool span too would double-report it, matching how the OTel path\n // leaves v4 tool errors to bubble. On v5 `executeTools` swallows the rejection into `tool-error` content,\n // so it never surfaces and we must capture it ourselves (see `failSpan`).\n toolErrorsBubbleToCaller: boolean;\n}\n// Per-operation error-handling info, keyed by the operation span (see `OperationErrorInfo`).\nconst operationErrorInfoBySpan = new WeakMap<Span, OperationErrorInfo>();\n\n// The `experimental_telemetry` objects we swapped in to suppress `ai`'s native OTel spans (see\n// `suppressNativeTelemetry`). Our skip logic treats `isEnabled === false` as \"user disabled telemetry,\n// emit no span\"; without this set, a call whose options object we already neutralized — or a user-shared\n// telemetry object we replaced on a prior call — would be misread as user-disabled and lose its span.\nconst suppressedTelemetry = new WeakSet<object>();\n\nlet subscribed = false;\n\n/**\n * Subscribe the v6 orchestrion channel adapter. Safe to always call: inert on\n * `ai` >= 7 (those channels are never published) and when orchestrion injection\n * isn't active. Idempotent.\n *\n * `tracingChannel` is the platform-provided factory (the same one passed to\n * `subscribeVercelAiTracingChannel`); `options` pins the recording settings at\n * subscribe time so we never look the integration up per event.\n */\nexport function subscribeVercelAiOrchestrionChannels(\n tracingChannel: VercelAiTracingChannelFactory,\n options: VercelAiChannelOptions = {},\n): void {\n if (subscribed) {\n return;\n }\n subscribed = true;\n\n try {\n bindOperation(tracingChannel, CHANNELS.VERCEL_AI_GENERATE_TEXT, buildTextMessage('generateText'), options);\n bindOperation(tracingChannel, CHANNELS.VERCEL_AI_STREAM_TEXT, buildTextMessage('streamText'), options);\n bindOperation(tracingChannel, CHANNELS.VERCEL_AI_STREAM_OBJECT, buildTextMessage('streamObject'), options);\n bindOperation(tracingChannel, CHANNELS.VERCEL_AI_GENERATE_OBJECT, buildTextMessage('generateObject'), options);\n bindOperation(\n tracingChannel,\n CHANNELS.VERCEL_AI_EMBED,\n (callOptions, telemetry) => ({\n type: 'embed',\n event: {\n callId: nextCallId(),\n ...modelFields(callOptions.model),\n maxRetries: callOptions.maxRetries,\n value: callOptions.value,\n telemetryMetadata: telemetry.metadata,\n ...recording(telemetry),\n },\n }),\n options,\n );\n bindOperation(\n tracingChannel,\n CHANNELS.VERCEL_AI_EMBED_MANY,\n // `embedMany` takes a `values` array (vs `embed`'s single `value`); the shared core reads it as the\n // embeddings input, matching the OTel path's batch `ai.embedMany` span.\n (callOptions, telemetry) => ({\n type: 'embedMany',\n event: {\n callId: nextCallId(),\n ...modelFields(callOptions.model),\n maxRetries: callOptions.maxRetries,\n values: callOptions.values,\n telemetryMetadata: telemetry.metadata,\n ...recording(telemetry),\n },\n }),\n options,\n );\n bindOperation(\n tracingChannel,\n CHANNELS.VERCEL_AI_EXECUTE_TOOL_CALL,\n (callOptions, telemetry) => ({\n type: 'executeTool',\n // v6 carries the tool definitions on the executeToolCall args (a record keyed by name);\n // the shared core reads the matching tool's `description` for the span.\n event: {\n callId: nextCallId(),\n toolCall: callOptions.toolCall,\n tools: callOptions.tools,\n ...recording(telemetry),\n },\n }),\n options,\n );\n subscribeResolveLanguageModel(tracingChannel, CHANNELS.VERCEL_AI_RESOLVE_LANGUAGE_MODEL, options);\n } catch {\n DEBUG_BUILD && debug.log('Vercel AI channel subscription failed.');\n }\n}\n\n/**\n * Bind one operation channel: `getSpan` opens a span from the message reconstructed out of the wrapped\n * call's first argument; `beforeSpanEnd` enriches it from the settled result (tokens, output messages,\n * finish reasons, …) before the helper ends the span.\n *\n * An operation whose `experimental_telemetry.isEnabled` is explicitly `false` is skipped entirely (no\n * span): the orchestrion channel fires regardless of that flag, whereas v7's native `ai:telemetry`\n * channel is simply not published in that case — so we reproduce v7's \"no telemetry → no span\".\n */\nfunction bindOperation(\n tracingChannel: VercelAiTracingChannelFactory,\n channelName: string,\n build: MessageBuilder,\n options: VercelAiChannelOptions,\n): void {\n const channel = tracingChannel<OrchestrionChannelContext>(channelName);\n\n // Build the operation span from the wrapped call's first argument and track it (so a model call can\n // resolve it as its parent). `bindTracingChannelToSpan` calls this once at channel `start` and makes\n // the returned span the active async context for the operation's duration — that active span is what\n // `resolveModelCallParent` reads. It also sets `data._sentrySpan`, so we don't here.\n const buildOperationSpan = (data: TracingChannelPayloadWithSpan<OrchestrionChannelContext>): Span | undefined => {\n const callOptions = isObjectLike(data.arguments[0]) ? data.arguments[0] : {};\n const telemetry = isObjectLike(callOptions.experimental_telemetry) ? callOptions.experimental_telemetry : {};\n // `isEnabled === false` means the user opted out — emit no span. But `isEnabled` is also `false` on\n // the telemetry object we swap in to suppress native spans, so don't mistake our own object for a\n // user opt-out (which would drop the span on a call whose options we already neutralized).\n if (telemetry.isEnabled === false && !suppressedTelemetry.has(telemetry)) {\n return undefined;\n }\n const message = build(callOptions, telemetry);\n // Stop `ai` from emitting its own native OTel spans for this call — we build the equivalent spans\n // from the channels, so the SDK's would be duplicates. Reads above have already captured everything\n // we need off `telemetry`.\n suppressNativeTelemetry(callOptions, telemetry);\n // The span active here is the operation's call site — `bindTracingChannelToSpan` only makes the\n // operation span active *after* this returns — so this is the span we later restore for a bubbled error.\n const callSiteSpan = getActiveSpan();\n const span = createSpanFromMessage(message, options);\n if (span) {\n messages.set(data, message);\n operationSpans.add(span);\n // `'v1'` models are v4 (v5/v6 are `'v2'`), where a thrown tool error bubbles out of the call rather\n // than being swallowed into `tool-error` content — so its tool spans must not self-capture the error.\n const isV4 = isObjectLike(callOptions.model) && callOptions.model.specificationVersion === 'v1';\n operationErrorInfoBySpan.set(span, { callSiteSpan, toolErrorsBubbleToCaller: isV4 });\n // v6's `executeToolCall` span: tracked so the v5 tool-`execute` patch can recognize (and skip)\n // tool calls it runs, since that patch sees this span as its active parent (see `patchToolExecute`).\n if (message.type === 'executeTool') {\n toolCallSpans.add(span);\n }\n const callId = asString(message.event.callId);\n if (callId) {\n callIdBySpan.set(span, callId);\n }\n recordingBySpan.set(span, recording(telemetry));\n telemetryMetadataBySpan.set(span, telemetry.metadata);\n // v5 has no `executeToolCall` channel, so patch each tool's `execute` to emit the tool-call span.\n // Inert on v6 (guarded inside `patchToolExecute` when the parent is `executeToolCall`'s own span).\n if (isObjectLike(callOptions.tools)) {\n patchOperationTools(callOptions.tools, options);\n }\n // v4 has no `resolveLanguageModel` chokepoint — the passed `LanguageModelV1` is called directly — so\n // patch its `doGenerate`/`doStream` here, at the operation start, instead. v5/v6 models are patched via\n // `resolveLanguageModel`, so restricting to v4 keeps this strictly additive and avoids double-patching.\n // Embedding models are also `'v1'` but expose no `doGenerate`/`doStream`, so the patch is a no-op for\n // `embed`/`embedMany`.\n if (isV4) {\n patchModelMethods(callOptions.model as PatchableModel, options);\n }\n }\n return span;\n };\n\n bindTracingChannelToSpan(\n channel,\n (data: TracingChannelPayloadWithSpan<OrchestrionChannelContext>) => buildOperationSpan(data),\n {\n beforeSpanEnd: (span, data) => {\n const message = messages.get(data);\n if (!message) {\n return;\n }\n // The helper's `error` handler already set the span status; only enrich from a successful result.\n if ('error' in data) {\n // The error bubbles out of the `ai` call. If nothing handles it before our global handler, that\n // handler runs outside any span — so stamp the operation's call-site span onto the error, letting\n // the unhandled-rejection handler restore it and correlate the report to this trace. This mirrors\n // the OTel path; it's a no-op when the error is handled earlier (e.g. a framework error handler).\n const callSiteSpan = operationErrorInfoBySpan.get(span)?.callSiteSpan;\n if (callSiteSpan && isObjectLike(data.error)) {\n addNonEnumerableProperty(data.error, '_sentry_active_span', callSiteSpan);\n }\n } else {\n // v6's `executeToolCall` returns the tool result/error object directly, whereas the shared core\n // (matching v7) expects it nested under `output`; wrap it so tool-error detection works.\n message.result = message.type === 'executeTool' ? { output: data.result } : data.result;\n enrichSpanOnEnd(span, message);\n }\n const isStream = message.type === 'streamText' || message.type === 'streamObject';\n runVercelAiSpanEnd(\n span,\n 'error' in data ? { error: data.error } : { response: isStream ? undefined : message.result },\n );\n // A `streamText`/`streamObject` model call runs after this (synchronously-returning) operation's\n // span has already ended, so its `callId` entry must outlive the operation — it's cleared once the\n // model call settles (see `patchModelMethod`). Every other operation can clear here.\n if (!isStream) {\n clearOperationId(message);\n }\n messages.delete(data);\n },\n // `streamText`/`streamObject` return synchronously, so their operation span would otherwise end\n // before the stream drains — losing the aggregate usage/output. Defer the end and await the result's\n // completion promises (`totalUsage`/`text`/…, which resolve on drain), mirroring how v7's channel\n // defers the operation span on the SDK's total-usage promise.\n deferSpanEnd: ({ span, data, end }) => deferStreamTextOperationEnd(span, data, end),\n },\n );\n}\n\n/**\n * Keep a streamed `streamText`/`streamObject` operation span open until the stream drains, then enrich it\n * from the result's completion promises (usage/output/finish reason) and end it. `streamObject` resolves\n * `object` rather than `text`; `getOutputMessages` reads `text`, so a resolved object is stringified into\n * that field. Returns `false` for anything that isn't a streamed result, so the helper ends the span as usual.\n *\n * `streamObject`'s `object` rejects when the output fails schema validation, even though the model call\n * succeeded and `usage` resolved. It's awaited separately so that case still records the token usage on\n * the span before ending it as an error.\n */\nfunction deferStreamTextOperationEnd(\n span: Span,\n data: TracingChannelPayloadWithSpan<OrchestrionChannelContext>,\n end: (error?: unknown) => void,\n): boolean {\n const message = messages.get(data);\n const type = message?.type;\n if (\n !message ||\n (type !== 'streamText' && type !== 'streamObject') ||\n 'error' in data ||\n !isStreamingResult(data.result)\n ) {\n return false;\n }\n\n const streamResult = data.result;\n void (async () => {\n try {\n const [usage, text, objectOutcome, toolCalls, finishReason, response] = await Promise.all([\n streamResult.totalUsage ?? streamResult.usage,\n streamResult.text,\n // Settle `object` into an outcome so a validation failure can't short-circuit the usage read.\n type === 'streamObject'\n ? Promise.resolve(streamResult.object).then(\n value => ({ value }),\n (error: unknown) => ({ value: undefined, error }),\n )\n : { value: undefined },\n streamResult.toolCalls,\n streamResult.finishReason,\n streamResult.response,\n ]);\n if ('error' in objectOutcome) {\n // The model call itself succeeded, so keep its usage on the span; `beforeSpanEnd` skips\n // enrichment once `end(error)` marks the payload as errored.\n message.result = { usage, toolCalls, finishReason, response };\n enrichSpanOnEnd(span, message);\n end(objectOutcome.error);\n return;\n }\n const object = objectOutcome.value;\n // Feed the resolved values back through the shared enrichment: `beforeSpanEnd` reads `data.result`.\n data.result = {\n usage,\n text: text ?? (isObjectLike(object) ? JSON.stringify(object) : object),\n toolCalls,\n finishReason,\n response,\n };\n end();\n } catch (error) {\n end(error);\n }\n })();\n\n return true;\n}\n\n/** A streamed result exposes its aggregates as promises (`totalUsage`/`usage`); a settled result does not. */\nfunction isStreamingResult(result: unknown): result is Record<string, PromiseLike<unknown> | undefined> {\n return isObjectLike(result) && (isThenable(result.totalUsage) || isThenable(result.usage));\n}\n\nfunction isThenable(value: unknown): boolean {\n return isObjectLike(value) && typeof value.then === 'function';\n}\n\n/**\n * Neutralize `ai`'s native OpenTelemetry instrumentation for this call by pointing\n * `experimental_telemetry` at a copy with `isEnabled: false`. `ai`'s `getTracer` then returns its\n * internal no-op tracer, so it never creates (nor sets active) the duplicate `ai.*` spans we'd\n * otherwise have to drop.\n *\n * Only a call that explicitly enabled telemetry emits native spans — otherwise `ai` already uses its\n * no-op tracer, so there's nothing to suppress and we leave the user's options untouched. When\n * `isEnabled === true`, `telemetry` is `callOptions.experimental_telemetry` and `callOptions` is the\n * real first argument the SDK will read, so the reassignment takes effect for the wrapped call. We\n * replace rather than mutate in place, so a telemetry object the user shares across calls keeps its own\n * `isEnabled: true`; the replacement is tracked in `suppressedTelemetry` so our skip logic doesn't\n * later read it back as a user opt-out.\n */\nfunction suppressNativeTelemetry(callOptions: Record<string, unknown>, telemetry: Record<string, unknown>): void {\n if (telemetry.isEnabled !== true) {\n return;\n }\n const suppressed = { ...telemetry, isEnabled: false };\n suppressedTelemetry.add(suppressed);\n callOptions.experimental_telemetry = suppressed;\n}\n\n/**\n * `resolveLanguageModel` returns the model every call flows through. We don't span it — on `end` we\n * monkey-patch `doGenerate`/`doStream` on the returned model so each invocation produces a\n * `languageModelCall` span parented to the enclosing invoke_agent span.\n */\nfunction subscribeResolveLanguageModel(\n tracingChannel: VercelAiTracingChannelFactory,\n channelName: string,\n options: VercelAiChannelOptions,\n): void {\n tracingChannel<OrchestrionChannelContext>(channelName).subscribe({\n end(rawCtx) {\n const ctx = rawCtx;\n if (!isObjectLike(ctx.result)) {\n return;\n }\n // Patch the model's `doGenerate`/`doStream` once. The model call recovers its parent from the\n // active async context at call time (the operation span `bindTracingChannelToSpan` bound), which\n // propagates into the model call for `streamText` too, so there is nothing to capture on the model here.\n patchModelMethods(ctx.result, options);\n },\n start() {\n /* no-op */\n },\n asyncStart() {\n /* no-op */\n },\n asyncEnd() {\n /* no-op */\n },\n error() {\n /* no-op */\n },\n });\n}\n\n/**\n * Pick the invoke_agent span a model call should hang under: the operation span that\n * `bindTracingChannelToSpan` planted as the active async context for the enclosing operation.\n *\n * Because we suppress `ai`'s native telemetry (so it never installs its own span as active), the active\n * span inside `doGenerate`/`doStream` is our operation span. The `operationSpans` gate makes this return\n * `undefined` when the active span isn't one of ours — e.g. telemetry was disabled for the call so we\n * opened no operation span and the active span is the user's enclosing span — so the model call is\n * skipped rather than mis-parented.\n *\n * This covers `generateText`/`embed` (whose model call is awaited inside the operation body) and\n * `streamText` alike — `ai` initiates the stream synchronously within the operation's bound context, so\n * the later `doStream` continuation restores the same active span even though the operation's span has\n * already ended. The per-operation binding also disambiguates concurrent calls that share one model\n * instance (a single mutable slot on the shared model could not — it would hold whichever operation\n * resolved the model last).\n */\nfunction resolveModelCallParent(): Span | undefined {\n const active = getActiveSpan();\n return active && operationSpans.has(active) ? active : undefined;\n}\n\n/**\n * Idempotently patch a resolved model's `doGenerate`/`doStream` so each invocation emits a\n * `languageModelCall` span. Shared by the v5/v6 `resolveLanguageModel` path and the v4 path (which\n * patches the passed model at the operation start, as v4 has no `resolveLanguageModel`).\n */\nfunction patchModelMethods(model: PatchableModel, options: VercelAiChannelOptions): void {\n if (model[PATCHED]) {\n return;\n }\n model[PATCHED] = true;\n patchModelMethod(model, 'doGenerate', options);\n patchModelMethod(model, 'doStream', options);\n}\n\nfunction patchModelMethod(\n model: PatchableModel,\n method: 'doGenerate' | 'doStream',\n options: VercelAiChannelOptions,\n): void {\n const original = model[method];\n if (typeof original !== 'function') {\n return;\n }\n model[method] = function (this: unknown, ...args: unknown[]): Promise<unknown> {\n const parent = resolveModelCallParent();\n // No enclosing operation span (e.g. telemetry disabled for the call) → don't open a model-call span.\n if (!parent) {\n return Promise.resolve(original.apply(this, args));\n }\n\n const callArgs = isObjectLike(args[0]) ? args[0] : {};\n // Carry the operation's `callId` so the shared core can name the span after it\n // (`ai.generateText.doGenerate` / `ai.streamText.doStream`).\n const callId = callIdBySpan.get(parent);\n const message: VercelAiChannelMessage = {\n type: 'languageModelCall',\n event: {\n callId,\n provider: model.provider,\n modelId: model.modelId,\n // v4 nests the tool list under `mode.tools` (the `LanguageModelV1` call shape); v5+ passes a\n // top-level `tools` array. Reading both keeps `tool.definitions` populated on the model-call span.\n tools: callArgs.tools ?? (isObjectLike(callArgs.mode) ? callArgs.mode.tools : undefined),\n messages: callArgs.prompt,\n telemetryMetadata: telemetryMetadataBySpan.get(parent),\n // Inherit the enclosing operation's per-call recording flags so inputs/tools/outputs are recorded on\n // the model-call span whenever they are on the parent `invoke_agent` span.\n ...recordingBySpan.get(parent),\n },\n };\n const span = withActiveSpan(parent, () => createSpanFromMessage(message, options));\n // `languageModelCall` always opens a span; the guard just keeps the wrapper safe if that changes.\n if (!span) {\n return Promise.resolve(original.apply(this, args));\n }\n\n // `streamText` ends its operation span synchronously, so its `callId` entry was deliberately left in\n // place for this later model call; drop it now that we've used it.\n const clearStreamCallId = (): void => {\n if (method === 'doStream' && callId) {\n clearOperationCallId(callId);\n }\n };\n\n // Both the synchronous throw and the async rejection of the model call must end the span with an\n // error status (an `async` `doGenerate`/`doStream` that throws rejects rather than throwing here).\n const failSpan = (error: unknown): never => {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: error instanceof Error ? error.message : 'unknown_error' });\n endSpan(span, { error });\n clearStreamCallId();\n throw error;\n };\n\n try {\n const result = Promise.resolve(original.apply(this, args));\n return result.then(value => {\n // A streamed model call resolves to `{ stream, ... }` before the stream is consumed, so its\n // usage/finish/output only arrive as the stream drains. Tap it (same helper as the v7 path) and\n // defer ending this model-call span until then. The parent `invoke_agent` span is enriched\n // separately by `deferStreamTextOperationEnd`, which awaits the operation's own result promises.\n if (method === 'doStream' && isObjectLike(value) && isReadableStream(value.stream)) {\n value.stream = tapModelCallStream(\n span,\n value.stream,\n final => {\n message.result = { ...value, ...streamedResultToChannelResult(final) };\n enrichSpanOnEnd(span, message);\n endSpan(span, {});\n clearStreamCallId();\n },\n error => {\n span.setStatus({\n code: SPAN_STATUS_ERROR,\n message: error instanceof Error ? error.message : 'unknown_error',\n });\n endSpan(span, { error });\n clearStreamCallId();\n },\n );\n\n return value;\n }\n // `doGenerate` (and any non-stream result) settles with the full result; end here, start/end\n // bracket the call to match the channel timing.\n message.result = value;\n enrichSpanOnEnd(span, message);\n endSpan(span, { response: value });\n clearStreamCallId();\n\n return value;\n }, failSpan);\n } catch (error) {\n return failSpan(error);\n }\n };\n}\n\n/**\n * Patch every executable tool on an operation's `tools` (a record keyed by tool name) so each\n * invocation emits a `gen_ai.execute_tool` span. v5 routes tool execution through the batch\n * `executeTools`, which binds `tool.execute` at call time — so replacing the `execute` property here\n * (before the call runs) is picked up. Tools without an `execute` (client-side tools) are skipped,\n * matching `executeTools`.\n */\nfunction patchOperationTools(tools: Record<string, unknown>, options: VercelAiChannelOptions): void {\n // This runs inside the channel `start` transform (no upstream try/catch), so a throw here would break\n // the user's `ai` call. Instrumentation must never do that — degrade to no tool span instead.\n try {\n for (const [toolName, tool] of Object.entries(tools)) {\n if (isObjectLike(tool)) {\n patchToolExecute(toolName, tool, tools, options);\n }\n }\n } catch {\n DEBUG_BUILD && debug.log('Vercel AI tool patching failed.');\n }\n}\n\nfunction patchToolExecute(\n toolName: string,\n tool: PatchableTool,\n tools: Record<string, unknown>,\n options: VercelAiChannelOptions,\n): void {\n const original = tool.execute;\n if (typeof original !== 'function' || tool[TOOL_PATCHED]) {\n return;\n }\n tool[TOOL_PATCHED] = true;\n tool.execute = function (this: unknown, input: unknown, ...rest: unknown[]): unknown {\n // Skip if there's no enclosing operation span (telemetry disabled for the call), or if that parent\n // is itself a tool-call span — the latter means v6's `executeToolCall` already opened a span for\n // this call and is running `execute` inside it, so spanning again here would double-count. On v5\n // the parent is the enclosing `invoke_agent` operation span, so we proceed.\n const parent = resolveModelCallParent();\n if (!parent || toolCallSpans.has(parent)) {\n return original.apply(this, [input, ...rest]);\n }\n\n // v5 passes `{ toolCallId, messages, abortSignal, ... }` as the second argument to `execute`.\n const callOptions = isObjectLike(rest[0]) ? rest[0] : {};\n const message: VercelAiChannelMessage = {\n type: 'executeTool',\n event: {\n callId: callIdBySpan.get(parent),\n toolCall: { toolName, toolCallId: asString(callOptions.toolCallId), input },\n // The `tools` record (keyed by name) lets the shared core backfill the tool's `description`.\n tools,\n // Inherit the enclosing operation's per-call recording flags so tool inputs/outputs are recorded\n // whenever they are on the parent `invoke_agent` span.\n ...recordingBySpan.get(parent),\n },\n };\n const span = withActiveSpan(parent, () => createSpanFromMessage(message, options));\n // `executeTool` always opens a span; the guard just keeps the wrapper safe if that changes.\n if (!span) {\n return original.apply(this, [input, ...rest]);\n }\n\n // v5's `executeTools` catches a thrown tool error and turns it into `tool-error` content rather than\n // rejecting, so the user never sees a rejection — we must capture it here. On v4 the rejection bubbles\n // out of the call and reaches the user's error handling (or our global handlers), so we only mark the\n // span and leave the capture to them, avoiding a duplicate report. Rethrow either way so `executeTools`\n // still produces its `tool-error` result (v5) and the rejection propagates (v4).\n const failSpan = (error: unknown): never => {\n if (operationErrorInfoBySpan.get(parent)?.toolErrorsBubbleToCaller) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: error instanceof Error ? error.message : 'tool_error' });\n } else {\n captureToolError(span, message, error);\n }\n endSpan(span, { error });\n throw error;\n };\n\n try {\n const result = Promise.resolve(original.apply(this, [input, ...rest]));\n return result.then(value => {\n // The shared core (matching v6/v7) expects the tool result nested under `output`.\n message.result = { output: value };\n enrichSpanOnEnd(span, message);\n endSpan(span, { response: message.result });\n return value;\n }, failSpan);\n } catch (error) {\n return failSpan(error);\n }\n };\n}\n\nfunction endSpan(span: Span, result: GenAiSpanResult<unknown>): void {\n runVercelAiSpanEnd(span, result);\n span.end();\n}\n\nfunction buildTextMessage(type: 'generateText' | 'streamText' | 'streamObject' | 'generateObject'): MessageBuilder {\n return (options, telemetry) => ({\n type,\n event: {\n callId: nextCallId(),\n operationId: `ai.${type}`,\n functionId: asString(telemetry.functionId),\n ...modelFields(options.model),\n maxRetries: options.maxRetries,\n // The `ai` SDK takes the system prompt as a top-level `system` option (all of v4/v5/v6); the\n // shared core lifts `event.instructions` into the system-instructions attribute, matching v7's\n // native channel (which carries it as a distinct field rather than inside the messages array).\n instructions: options.system,\n // Normalize to the message-array shape the shared core (and v7's channel) expects: a bare string\n // `prompt` becomes a single user message, matching the SDK's own normalization.\n messages: normalizePromptMessages(options),\n // v7's native start event carries `providerOptions`; the shared core reads the OpenAI\n // Conversations API id from it.\n providerOptions: options.providerOptions,\n telemetryMetadata: telemetry.metadata,\n ...recording(telemetry),\n },\n });\n}\n\nfunction normalizePromptMessages(options: Record<string, unknown>): unknown {\n if (Array.isArray(options.messages)) {\n return options.messages;\n }\n if (typeof options.prompt === 'string') {\n return [{ role: 'user', content: options.prompt }];\n }\n return options.messages ?? options.prompt;\n}\n\nfunction recording(telemetry: Record<string, unknown>): { recordInputs: unknown; recordOutputs: unknown } {\n // Match the OTel integration's per-call default: an explicit `recordInputs`/`recordOutputs` wins, but a\n // call that merely enables telemetry (`isEnabled: true`, no explicit flags) defaults both to `true`.\n // Unlike v7's native `ai:telemetry` channel, the orchestrion channels expose `isEnabled`, so — as noted\n // in `resolveRecording` — we CAN reproduce that default here (the native-channel subscriber cannot).\n const enabledDefault = telemetry.isEnabled === true ? true : undefined;\n return {\n recordInputs: telemetry.recordInputs ?? enabledDefault,\n recordOutputs: telemetry.recordOutputs ?? enabledDefault,\n };\n}\n\nfunction modelFields(model: unknown): { provider?: string; modelId?: string } {\n return { provider: modelField(model, 'provider'), modelId: modelField(model, 'modelId') };\n}\n\nfunction modelField(model: unknown, field: 'modelId' | 'provider'): string | undefined {\n return isObjectLike(model) ? asString(model[field]) : undefined;\n}\n"],"mappings":";;;;;;;;AAwEA,MAAM,UAAU,OAAO,4BAA4B;AACnD,MAAM,eAAe,OAAO,2BAA2B;AASvD,IAAI,gBAAgB;AACpB,SAAS,aAAqB;CAC5B,OAAO,MAAM,EAAE;AACjB;AAIA,MAAM,2BAAW,IAAI,QAAwC;AAI7D,MAAM,iCAAiB,IAAI,QAAc;AAIzC,MAAM,gCAAgB,IAAI,QAAc;AACxC,MAAM,+BAAe,IAAI,QAAsB;AAM/C,MAAM,kCAAkB,IAAI,QAA4C;AAGxE,MAAM,0CAA0B,IAAI,QAAuB;AAe3D,MAAM,2CAA2B,IAAI,QAAkC;AAMvE,MAAM,sCAAsB,IAAI,QAAgB;AAEhD,IAAI,aAAa;;;;;;;;;;AAWjB,SAAgB,qCACd,gBACA,UAAkC,CAAC,GAC7B;CACN,IAAI,YACF;CAEF,aAAa;CAEb,IAAI;EACF,cAAc,gBAAgB,SAAS,yBAAyB,iBAAiB,cAAc,GAAG,OAAO;EACzG,cAAc,gBAAgB,SAAS,uBAAuB,iBAAiB,YAAY,GAAG,OAAO;EACrG,cAAc,gBAAgB,SAAS,yBAAyB,iBAAiB,cAAc,GAA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AC1C,OAAO;GACT,GAAG,QAAQ;EACb,SAAS,OAAO;GACd,OAAO,SAAS,KAAK;EACvB;CACF;AACF;AAEA,SAAS,QAAQ,MAAY,QAAwC;CACnE,mBAAmB,MAAM,MAAM;CAC/B,KAAK,IAAI;AACX;AAEA,SAAS,iBAAiB,MAAyF;CACjH,QAAQ,SAAS,eAAe;EAC9B;EACA,OAAO;GACL,QAAQ,WAAW;GACnB,aAAa,MAAM;GACnB,YAAY,SAAS,UAAU,UAAU;GACzC,GAAG,YAAY,QAAQ,KAAK;GAC5B,YAAY,QAAQ;GAIpB,cAAc,QAAQ;GAGtB,UAAU,wBAAwB,OAAO;GAGzC,iBAAiB,QAAQ;GACzB,mBAAmB,UAAU;GAC7B,GAAG,UAAU,SAAS;EACxB;CACF;AACF;AAEA,SAAS,wBAAwB,SAA2C;CAC1E,IAAI,MAAM,QAAQ,QAAQ,QAAQ,GAChC,OAAO,QAAQ;CAEjB,IAAI,OAAO,QAAQ,WAAW,UAC5B,OAAO,CAAC;EAAE,MAAM;EAAQ,SAAS,QAAQ;CAAO,CAAC;CAEnD,OAAO,QAAQ,YAAY,QAAQ;AACrC;AAEA,SAAS,UAAU,WAAuF;CAKxG,MAAM,iBAAiB,UAAU,cAAc,OAAO,OAAO,KAAA;CAC7D,OAAO;EACL,cAAc,UAAU,gBAAgB;EACxC,eAAe,UAAU,iBAAiB;CAC5C;AACF;AAEA,SAAS,YAAY,OAAyD;CAC5E,OAAO;EAAE,UAAU,WAAW,OAAO,UAAU;EAAG,SAAS,WAAW,OAAO,SAAS;CAAE;AAC1F;AAEA,SAAS,WAAW,OAAgB,OAAmD;CACrF,OAAO,aAAa,KAAK,IAAI,SAAS,MAAM,MAAM,IAAI,KAAA;AACxD"}
|
|
1
|
+
{"version":3,"file":"vercel-ai-orchestrion-subscriber.js","names":[],"sources":["../../../../src/integrations/vercel-ai/vercel-ai-orchestrion-subscriber.ts"],"sourcesContent":["/* eslint-disable max-lines */\nimport type { Span } from '@sentry/core';\nimport {\n addNonEnumerableProperty,\n debug,\n getActiveSpan,\n isObjectLike,\n SPAN_STATUS_ERROR,\n withActiveSpan,\n} from '@sentry/core';\nimport { DEBUG_BUILD } from '../../debug-build';\nimport type { OrchestrionChannelContext } from '../../orchestrion/types';\nimport { CHANNELS } from '../../orchestrion/channels';\nimport { bindTracingChannelToSpan, type TracingChannelPayloadWithSpan } from '../../tracing-channel';\nimport type { GenAiSpanResult } from '../../ai/core/span-hooks';\nimport {\n captureToolError,\n clearOperationCallId,\n clearOperationId,\n createSpanFromMessage,\n enrichSpanOnEnd,\n runVercelAiSpanEnd,\n streamedResultToChannelResult,\n type VercelAiChannelMessage,\n type VercelAiChannelOptions,\n type VercelAiTracingChannelFactory,\n} from './vercel-ai-dc-subscriber';\nimport { asString, isReadableStream, tapModelCallStream } from './util';\n\n/**\n * v4, v5 & v6 channel adapter for the Vercel AI (`ai`) SDK.\n *\n * `ai` >= 7 publishes a normalized `ai:telemetry` tracing channel natively\n * (consumed by `subscribeVercelAiTracingChannel`). v4/v5/v6 have no such channel, so\n * orchestrion injects `orchestrion:ai:*` channels around the top-level\n * functions (see `orchestrion/config/index.ts`). The injected channels carry only the\n * wrapped call's `{ arguments, result, error }` — NOT v7's normalized `event`\n * object — so this adapter reconstructs an equivalent {@link VercelAiChannelMessage}\n * from each version's argument/result shapes and delegates to the SAME span-building core\n * (`createSpanFromMessage` / `enrichSpanOnEnd`) the v7 subscriber uses, so the\n * emitted spans are identical between v4, v5, v6 and v7. The shared core reads both v4-style\n * (`promptTokens`/`completionTokens`) and v5+-style (`inputTokens`/`outputTokens`) token names.\n *\n * The model call (`languageModelCall` / `generate_content` span) has no\n * injectable definition in `ai`. On v5/v6 we wrap `resolveLanguageModel` (the\n * single chokepoint every model call flows through) and monkey-patch\n * `doGenerate`/`doStream` on the returned model. v4 has no `resolveLanguageModel`\n * — the passed `LanguageModelV1` (`specificationVersion: 'v1'`) is called directly —\n * so we patch its `doGenerate`/`doStream` at the operation start instead (see\n * `buildOperationSpan`), gated on `'v1'` so it never touches v5/v6 models.\n *\n * Tool-call spans differ by version: v6 exposes a per-call `executeToolCall`\n * function orchestrion wraps into its own channel. v4/v5 have no such export (only a\n * batch `executeTools`), so instead we monkey-patch each tool's `execute` from\n * the operation's `tools`. On v6 that patch is inert: `executeToolCall` runs\n * `execute` inside its own tool-call span (the active async context), so the\n * patch sees that span as its parent and skips — only v4/v5 (where the parent is\n * the enclosing `invoke_agent` span) emit the patched span, so v6 never\n * double-counts tool spans.\n */\n\n/** Builds the normalized message for a channel from the wrapped call's first-arg options. */\ntype MessageBuilder = (options: Record<string, unknown>, telemetry: Record<string, unknown>) => VercelAiChannelMessage;\n\n/** A resolved `ai` language model — has `doGenerate`/`doStream` and identity fields. */\ninterface ResolvedModel {\n modelId?: string;\n provider?: string;\n doGenerate?: (...args: unknown[]) => Promise<unknown>;\n doStream?: (...args: unknown[]) => Promise<unknown>;\n}\n\nconst PATCHED = Symbol('SentryVercelAiModelPatched');\nconst TOOL_PATCHED = Symbol('SentryVercelAiToolPatched');\n\n/** A resolved model with our patch bookkeeping (idempotency flag). */\ntype PatchableModel = ResolvedModel & { [PATCHED]?: boolean };\n\n/** A tool definition off an operation's `tools`, with our patch bookkeeping. */\ntype PatchableTool = { execute?: (...args: unknown[]) => unknown; [TOOL_PATCHED]?: boolean };\n\n// Per-operation correlation id. No Date/random (unavailable / non-deterministic) — a counter is enough.\nlet callIdCounter = 0;\nfunction nextCallId(): string {\n return `v6-${++callIdCounter}`;\n}\n\n// The message built on `start` for each operation, keyed by the (stable-identity) channel context, so\n// the `beforeSpanEnd` handler can enrich the span from the settled result and clear the `callId` maps.\nconst messages = new WeakMap<object, VercelAiChannelMessage>();\n// The spans we opened for top-level operations, and each one's `callId`. A model call resolves its\n// parent against this set (so it never mis-attributes to the enclosing `main`/user span) and reads the\n// parent's `callId` so its span can be named after the operation (e.g. `ai.streamText.doStream`).\nconst operationSpans = new WeakSet<Span>();\n// Tool-call spans — only v6's `executeToolCall` channel opens these. The v5 tool-`execute` patch\n// consults this to avoid double-counting: `executeToolCall` runs `execute` inside its span (which is\n// therefore the active parent), so a resolved parent in this set means v6 already spanned the call.\nconst toolCallSpans = new WeakSet<Span>();\nconst callIdBySpan = new WeakMap<Span, string>();\n// The operation's per-call recording flags (`experimental_telemetry.recordInputs/recordOutputs`), keyed by\n// its span. A model call carries no telemetry of its own, so it inherits the enclosing operation's flags —\n// otherwise a per-call `recordInputs: true` would record inputs on the `invoke_agent` span but not on the\n// child `generate_content` span (whose event would fall back to the global default). v7's channel forwards\n// these flags on every event, so this keeps v6 identical.\nconst recordingBySpan = new WeakMap<Span, ReturnType<typeof recording>>();\n// The operation's `experimental_telemetry.metadata`, keyed by its span, so the model-call span records it\n// too. The OTel integration put it on both, but not on tool-call spans.\nconst telemetryMetadataBySpan = new WeakMap<Span, unknown>();\ninterface OperationErrorInfo {\n // The span active when the operation was invoked (its call site, e.g. the enclosing request/`main` span).\n // When an operation's error bubbles out unhandled it reaches the global handler outside any span, so — as\n // the OTel path does — we stamp this span onto the error (in `beforeSpanEnd`) so the unhandled-rejection\n // handler can restore it and correlate the captured error to the operation's trace.\n callSiteSpan: Span | undefined;\n // Whether a thrown tool error bubbles out of the `ai` call (v4). On v4 a tool-`execute` rejection is\n // wrapped in `AI_ToolExecutionError` and re-thrown, so it reaches the user's own error handling (or our\n // global handlers) — capturing it at the tool span too would double-report it, matching how the OTel path\n // leaves v4 tool errors to bubble. On v5 `executeTools` swallows the rejection into `tool-error` content,\n // so it never surfaces and we must capture it ourselves (see `failSpan`).\n toolErrorsBubbleToCaller: boolean;\n}\n// Per-operation error-handling info, keyed by the operation span (see `OperationErrorInfo`).\nconst operationErrorInfoBySpan = new WeakMap<Span, OperationErrorInfo>();\n\n// The `experimental_telemetry` objects we swapped in to suppress `ai`'s native OTel spans (see\n// `suppressNativeTelemetry`). Our skip logic treats `isEnabled === false` as \"user disabled telemetry,\n// emit no span\"; without this set, a call whose options object we already neutralized — or a user-shared\n// telemetry object we replaced on a prior call — would be misread as user-disabled and lose its span.\nconst suppressedTelemetry = new WeakSet<object>();\n\nlet subscribed = false;\n\n/**\n * Subscribe the v6 orchestrion channel adapter. Safe to always call: inert on\n * `ai` >= 7 (those channels are never published) and when orchestrion injection\n * isn't active. Idempotent.\n *\n * `tracingChannel` is the platform-provided factory (the same one passed to\n * `subscribeVercelAiTracingChannel`); `options` pins the recording settings at\n * subscribe time so we never look the integration up per event.\n */\nexport function subscribeVercelAiOrchestrionChannels(\n tracingChannel: VercelAiTracingChannelFactory,\n options: VercelAiChannelOptions = {},\n): void {\n if (subscribed) {\n return;\n }\n subscribed = true;\n\n try {\n bindOperation(tracingChannel, CHANNELS.VERCEL_AI_GENERATE_TEXT, buildTextMessage('generateText'), options);\n bindOperation(tracingChannel, CHANNELS.VERCEL_AI_STREAM_TEXT, buildTextMessage('streamText'), options);\n bindOperation(tracingChannel, CHANNELS.VERCEL_AI_STREAM_OBJECT, buildTextMessage('streamObject'), options);\n bindOperation(tracingChannel, CHANNELS.VERCEL_AI_GENERATE_OBJECT, buildTextMessage('generateObject'), options);\n bindOperation(\n tracingChannel,\n CHANNELS.VERCEL_AI_EMBED,\n (callOptions, telemetry) => ({\n type: 'embed',\n event: {\n callId: nextCallId(),\n ...modelFields(callOptions.model),\n maxRetries: callOptions.maxRetries,\n value: callOptions.value,\n telemetryMetadata: telemetry.metadata,\n ...recording(telemetry),\n },\n }),\n options,\n );\n bindOperation(\n tracingChannel,\n CHANNELS.VERCEL_AI_EMBED_MANY,\n // `embedMany` takes a `values` array (vs `embed`'s single `value`); the shared core reads it as the\n // embeddings input, matching the OTel path's batch `ai.embedMany` span.\n (callOptions, telemetry) => ({\n type: 'embedMany',\n event: {\n callId: nextCallId(),\n ...modelFields(callOptions.model),\n maxRetries: callOptions.maxRetries,\n values: callOptions.values,\n telemetryMetadata: telemetry.metadata,\n ...recording(telemetry),\n },\n }),\n options,\n );\n bindOperation(\n tracingChannel,\n CHANNELS.VERCEL_AI_EXECUTE_TOOL_CALL,\n (callOptions, telemetry) => ({\n type: 'executeTool',\n // v6 carries the tool definitions on the executeToolCall args (a record keyed by name);\n // the shared core reads the matching tool's `description` for the span.\n event: {\n callId: nextCallId(),\n toolCall: callOptions.toolCall,\n tools: callOptions.tools,\n ...recording(telemetry),\n },\n }),\n options,\n );\n subscribeResolveLanguageModel(tracingChannel, CHANNELS.VERCEL_AI_RESOLVE_LANGUAGE_MODEL, options);\n } catch {\n DEBUG_BUILD && debug.log('Vercel AI channel subscription failed.');\n }\n}\n\n/**\n * Bind one operation channel: `getSpan` opens a span from the message reconstructed out of the wrapped\n * call's first argument; `beforeSpanEnd` enriches it from the settled result (tokens, output messages,\n * finish reasons, …) before the helper ends the span.\n *\n * An operation whose `experimental_telemetry.isEnabled` is explicitly `false` is skipped entirely (no\n * span): the orchestrion channel fires regardless of that flag, whereas v7's native `ai:telemetry`\n * channel is simply not published in that case — so we reproduce v7's \"no telemetry → no span\".\n */\nfunction bindOperation(\n tracingChannel: VercelAiTracingChannelFactory,\n channelName: string,\n build: MessageBuilder,\n options: VercelAiChannelOptions,\n): void {\n const channel = tracingChannel<OrchestrionChannelContext>(channelName);\n\n // Build the operation span from the wrapped call's first argument and track it (so a model call can\n // resolve it as its parent). `bindTracingChannelToSpan` calls this once at channel `start` and makes\n // the returned span the active async context for the operation's duration — that active span is what\n // `resolveModelCallParent` reads. It also sets `data._sentrySpan`, so we don't here.\n const buildOperationSpan = (data: TracingChannelPayloadWithSpan<OrchestrionChannelContext>): Span | undefined => {\n const callOptions = isObjectLike(data.arguments[0]) ? data.arguments[0] : {};\n const telemetry = isObjectLike(callOptions.experimental_telemetry) ? callOptions.experimental_telemetry : {};\n // `isEnabled === false` means the user opted out — emit no span. But `isEnabled` is also `false` on\n // the telemetry object we swap in to suppress native spans, so don't mistake our own object for a\n // user opt-out (which would drop the span on a call whose options we already neutralized).\n if (telemetry.isEnabled === false && !suppressedTelemetry.has(telemetry)) {\n return undefined;\n }\n const message = build(callOptions, telemetry);\n // Stop `ai` from emitting its own native OTel spans for this call — we build the equivalent spans\n // from the channels, so the SDK's would be duplicates. Reads above have already captured everything\n // we need off `telemetry`.\n suppressNativeTelemetry(callOptions, telemetry);\n // The span active here is the operation's call site — `bindTracingChannelToSpan` only makes the\n // operation span active *after* this returns — so this is the span we later restore for a bubbled error.\n const callSiteSpan = getActiveSpan();\n const span = createSpanFromMessage(message, options);\n if (span) {\n messages.set(data, message);\n operationSpans.add(span);\n // `'v1'` models are v4 (v5/v6 are `'v2'`), where a thrown tool error bubbles out of the call rather\n // than being swallowed into `tool-error` content — so its tool spans must not self-capture the error.\n const isV4 = isObjectLike(callOptions.model) && callOptions.model.specificationVersion === 'v1';\n operationErrorInfoBySpan.set(span, { callSiteSpan, toolErrorsBubbleToCaller: isV4 });\n // v6's `executeToolCall` span: tracked so the v5 tool-`execute` patch can recognize (and skip)\n // tool calls it runs, since that patch sees this span as its active parent (see `patchToolExecute`).\n if (message.type === 'executeTool') {\n toolCallSpans.add(span);\n }\n const callId = asString(message.event.callId);\n if (callId) {\n callIdBySpan.set(span, callId);\n }\n recordingBySpan.set(span, recording(telemetry));\n telemetryMetadataBySpan.set(span, telemetry.metadata);\n // v5 has no `executeToolCall` channel, so patch each tool's `execute` to emit the tool-call span.\n // Inert on v6 (guarded inside `patchToolExecute` when the parent is `executeToolCall`'s own span).\n if (isObjectLike(callOptions.tools)) {\n patchOperationTools(callOptions.tools, options);\n }\n // v4 has no `resolveLanguageModel` chokepoint — the passed `LanguageModelV1` is called directly — so\n // patch its `doGenerate`/`doStream` here, at the operation start, instead. v5/v6 models are patched via\n // `resolveLanguageModel`, so restricting to v4 keeps this strictly additive and avoids double-patching.\n // Embedding models are also `'v1'` but expose no `doGenerate`/`doStream`, so the patch is a no-op for\n // `embed`/`embedMany`.\n if (isV4) {\n patchModelMethods(callOptions.model as PatchableModel, options);\n }\n }\n return span;\n };\n\n bindTracingChannelToSpan(\n channel,\n (data: TracingChannelPayloadWithSpan<OrchestrionChannelContext>) => buildOperationSpan(data),\n {\n beforeSpanEnd: (span, data) => {\n const message = messages.get(data);\n if (!message) {\n return;\n }\n // The helper's `error` handler already set the span status; only enrich from a successful result.\n if ('error' in data) {\n // The error bubbles out of the `ai` call. If nothing handles it before our global handler, that\n // handler runs outside any span — so stamp the operation's call-site span onto the error, letting\n // the unhandled-rejection handler restore it and correlate the report to this trace. This mirrors\n // the OTel path; it's a no-op when the error is handled earlier (e.g. a framework error handler).\n const callSiteSpan = operationErrorInfoBySpan.get(span)?.callSiteSpan;\n if (callSiteSpan && isObjectLike(data.error)) {\n addNonEnumerableProperty(data.error, '_sentry_active_span', callSiteSpan);\n }\n } else {\n // v6's `executeToolCall` returns the tool result/error object directly, whereas the shared core\n // (matching v7) expects it nested under `output`; wrap it so tool-error detection works.\n message.result = message.type === 'executeTool' ? { output: data.result } : data.result;\n enrichSpanOnEnd(span, message);\n }\n const isStream = message.type === 'streamText' || message.type === 'streamObject';\n runVercelAiSpanEnd(\n span,\n 'error' in data ? { error: data.error } : { response: isStream ? undefined : message.result },\n );\n // A `streamText`/`streamObject` model call runs after this (synchronously-returning) operation's\n // span has already ended, so its `callId` entry must outlive the operation — it's cleared once the\n // model call settles (see `patchModelMethod`). Every other operation can clear here.\n if (!isStream) {\n clearOperationId(message);\n }\n messages.delete(data);\n },\n // `streamText`/`streamObject` return synchronously, so their operation span would otherwise end\n // before the stream drains — losing the aggregate usage/output. Defer the end and await the result's\n // completion promises (`steps`/`text`/…, which resolve on drain), mirroring how v7's channel\n // defers the operation span on the SDK's total-usage promise.\n deferSpanEnd: ({ span, data, end }) => deferStreamTextOperationEnd(span, data, end),\n },\n );\n}\n\n/**\n * Keep a streamed `streamText`/`streamObject` operation span open until the stream drains, then enrich it\n * from the result's completion promises (usage/output/finish reason) and end it. `streamObject` resolves\n * `object` rather than `text`; `getOutputMessages` reads `text`, so a resolved object is stringified into\n * that field. Returns `false` for anything that isn't a streamed result, so the helper ends the span as usual.\n *\n * `streamObject`'s `object` rejects when the output fails schema validation, even though the model call\n * succeeded and `usage` resolved. It's awaited separately so that case still records the token usage on\n * the span before ending it as an error.\n */\nfunction deferStreamTextOperationEnd(\n span: Span,\n data: TracingChannelPayloadWithSpan<OrchestrionChannelContext>,\n end: (error?: unknown) => void,\n): boolean {\n const message = messages.get(data);\n const type = message?.type;\n if (\n !message ||\n (type !== 'streamText' && type !== 'streamObject') ||\n 'error' in data ||\n !isStreamingResult(data.result)\n ) {\n return false;\n }\n\n const streamResult = data.result;\n void (async () => {\n try {\n const [usage, text, objectOutcome, toolCalls, finishReason, response, steps, providerMetadata] =\n await Promise.all([\n streamResult.usage,\n streamResult.text,\n // Settle `object` into an outcome so a validation failure can't short-circuit the usage read.\n type === 'streamObject'\n ? Promise.resolve(streamResult.object).then(\n value => ({ value }),\n (error: unknown) => ({ value: undefined, error }),\n )\n : { value: undefined },\n streamResult.toolCalls,\n streamResult.finishReason,\n streamResult.response,\n streamResult.steps,\n streamResult.providerMetadata,\n ]);\n const result = { usage, toolCalls, finishReason, response, steps, providerMetadata };\n if ('error' in objectOutcome) {\n // The model call itself succeeded, so keep its usage on the span; `beforeSpanEnd` skips\n // enrichment once `end(error)` marks the payload as errored.\n message.result = result;\n enrichSpanOnEnd(span, message);\n end(objectOutcome.error);\n return;\n }\n const object = objectOutcome.value;\n // Feed the resolved values back through the shared enrichment: `beforeSpanEnd` reads `data.result`.\n data.result = { ...result, text: text ?? (isObjectLike(object) ? JSON.stringify(object) : object) };\n end();\n } catch (error) {\n end(error);\n }\n })();\n\n return true;\n}\n\n/**\n * A streamed result exposes its aggregates as promises; a settled result does not. Reading `totalUsage`\n * would create a promise that rejects unobserved when the stream aborts.\n */\nfunction isStreamingResult(result: unknown): result is Record<string, PromiseLike<unknown> | undefined> {\n return isObjectLike(result) && (isThenable(result.steps) || isThenable(result.usage));\n}\n\nfunction isThenable(value: unknown): boolean {\n return isObjectLike(value) && typeof value.then === 'function';\n}\n\n/**\n * Neutralize `ai`'s native OpenTelemetry instrumentation for this call by pointing\n * `experimental_telemetry` at a copy with `isEnabled: false`. `ai`'s `getTracer` then returns its\n * internal no-op tracer, so it never creates (nor sets active) the duplicate `ai.*` spans we'd\n * otherwise have to drop.\n *\n * Only a call that explicitly enabled telemetry emits native spans — otherwise `ai` already uses its\n * no-op tracer, so there's nothing to suppress and we leave the user's options untouched. When\n * `isEnabled === true`, `telemetry` is `callOptions.experimental_telemetry` and `callOptions` is the\n * real first argument the SDK will read, so the reassignment takes effect for the wrapped call. We\n * replace rather than mutate in place, so a telemetry object the user shares across calls keeps its own\n * `isEnabled: true`; the replacement is tracked in `suppressedTelemetry` so our skip logic doesn't\n * later read it back as a user opt-out.\n */\nfunction suppressNativeTelemetry(callOptions: Record<string, unknown>, telemetry: Record<string, unknown>): void {\n if (telemetry.isEnabled !== true) {\n return;\n }\n const suppressed = { ...telemetry, isEnabled: false };\n suppressedTelemetry.add(suppressed);\n callOptions.experimental_telemetry = suppressed;\n}\n\n/**\n * `resolveLanguageModel` returns the model every call flows through. We don't span it — on `end` we\n * monkey-patch `doGenerate`/`doStream` on the returned model so each invocation produces a\n * `languageModelCall` span parented to the enclosing invoke_agent span.\n */\nfunction subscribeResolveLanguageModel(\n tracingChannel: VercelAiTracingChannelFactory,\n channelName: string,\n options: VercelAiChannelOptions,\n): void {\n tracingChannel<OrchestrionChannelContext>(channelName).subscribe({\n end(rawCtx) {\n const ctx = rawCtx;\n if (!isObjectLike(ctx.result)) {\n return;\n }\n // Patch the model's `doGenerate`/`doStream` once. The model call recovers its parent from the\n // active async context at call time (the operation span `bindTracingChannelToSpan` bound), which\n // propagates into the model call for `streamText` too, so there is nothing to capture on the model here.\n patchModelMethods(ctx.result, options);\n },\n start() {\n /* no-op */\n },\n asyncStart() {\n /* no-op */\n },\n asyncEnd() {\n /* no-op */\n },\n error() {\n /* no-op */\n },\n });\n}\n\n/**\n * Pick the invoke_agent span a model call should hang under: the operation span that\n * `bindTracingChannelToSpan` planted as the active async context for the enclosing operation.\n *\n * Because we suppress `ai`'s native telemetry (so it never installs its own span as active), the active\n * span inside `doGenerate`/`doStream` is our operation span. The `operationSpans` gate makes this return\n * `undefined` when the active span isn't one of ours — e.g. telemetry was disabled for the call so we\n * opened no operation span and the active span is the user's enclosing span — so the model call is\n * skipped rather than mis-parented.\n *\n * This covers `generateText`/`embed` (whose model call is awaited inside the operation body) and\n * `streamText` alike — `ai` initiates the stream synchronously within the operation's bound context, so\n * the later `doStream` continuation restores the same active span even though the operation's span has\n * already ended. The per-operation binding also disambiguates concurrent calls that share one model\n * instance (a single mutable slot on the shared model could not — it would hold whichever operation\n * resolved the model last).\n */\nfunction resolveModelCallParent(): Span | undefined {\n const active = getActiveSpan();\n return active && operationSpans.has(active) ? active : undefined;\n}\n\n/**\n * Idempotently patch a resolved model's `doGenerate`/`doStream` so each invocation emits a\n * `languageModelCall` span. Shared by the v5/v6 `resolveLanguageModel` path and the v4 path (which\n * patches the passed model at the operation start, as v4 has no `resolveLanguageModel`).\n */\nfunction patchModelMethods(model: PatchableModel, options: VercelAiChannelOptions): void {\n if (model[PATCHED]) {\n return;\n }\n model[PATCHED] = true;\n patchModelMethod(model, 'doGenerate', options);\n patchModelMethod(model, 'doStream', options);\n}\n\nfunction patchModelMethod(\n model: PatchableModel,\n method: 'doGenerate' | 'doStream',\n options: VercelAiChannelOptions,\n): void {\n const original = model[method];\n if (typeof original !== 'function') {\n return;\n }\n model[method] = function (this: unknown, ...args: unknown[]): Promise<unknown> {\n const parent = resolveModelCallParent();\n // No enclosing operation span (e.g. telemetry disabled for the call) → don't open a model-call span.\n if (!parent) {\n return Promise.resolve(original.apply(this, args));\n }\n\n const callArgs = isObjectLike(args[0]) ? args[0] : {};\n // Carry the operation's `callId` so the shared core can name the span after it\n // (`ai.generateText.doGenerate` / `ai.streamText.doStream`).\n const callId = callIdBySpan.get(parent);\n const message: VercelAiChannelMessage = {\n type: 'languageModelCall',\n event: {\n callId,\n provider: model.provider,\n modelId: model.modelId,\n // v4 nests the tool list under `mode.tools` (the `LanguageModelV1` call shape); v5+ passes a\n // top-level `tools` array. Reading both keeps `tool.definitions` populated on the model-call span.\n tools: callArgs.tools ?? (isObjectLike(callArgs.mode) ? callArgs.mode.tools : undefined),\n messages: callArgs.prompt,\n telemetryMetadata: telemetryMetadataBySpan.get(parent),\n // Inherit the enclosing operation's per-call recording flags so inputs/tools/outputs are recorded on\n // the model-call span whenever they are on the parent `invoke_agent` span.\n ...recordingBySpan.get(parent),\n },\n };\n const span = withActiveSpan(parent, () => createSpanFromMessage(message, options));\n // `languageModelCall` always opens a span; the guard just keeps the wrapper safe if that changes.\n if (!span) {\n return Promise.resolve(original.apply(this, args));\n }\n\n // `streamText` ends its operation span synchronously, so its `callId` entry was deliberately left in\n // place for this later model call; drop it now that we've used it.\n const clearStreamCallId = (): void => {\n if (method === 'doStream' && callId) {\n clearOperationCallId(callId);\n }\n };\n\n // Both the synchronous throw and the async rejection of the model call must end the span with an\n // error status (an `async` `doGenerate`/`doStream` that throws rejects rather than throwing here).\n const failSpan = (error: unknown): never => {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: error instanceof Error ? error.message : 'unknown_error' });\n endSpan(span, { error });\n clearStreamCallId();\n throw error;\n };\n\n try {\n const result = Promise.resolve(original.apply(this, args));\n return result.then(value => {\n // A streamed model call resolves to `{ stream, ... }` before the stream is consumed, so its\n // usage/finish/output only arrive as the stream drains. Tap it (same helper as the v7 path) and\n // defer ending this model-call span until then. The parent `invoke_agent` span is enriched\n // separately by `deferStreamTextOperationEnd`, which awaits the operation's own result promises.\n if (method === 'doStream' && isObjectLike(value) && isReadableStream(value.stream)) {\n value.stream = tapModelCallStream(\n span,\n value.stream,\n final => {\n message.result = { ...value, ...streamedResultToChannelResult(final) };\n enrichSpanOnEnd(span, message);\n endSpan(span, {});\n clearStreamCallId();\n },\n error => {\n span.setStatus({\n code: SPAN_STATUS_ERROR,\n message: error instanceof Error ? error.message : 'unknown_error',\n });\n endSpan(span, { error });\n clearStreamCallId();\n },\n );\n\n return value;\n }\n // `doGenerate` (and any non-stream result) settles with the full result; end here, start/end\n // bracket the call to match the channel timing.\n message.result = value;\n enrichSpanOnEnd(span, message);\n endSpan(span, { response: value });\n clearStreamCallId();\n\n return value;\n }, failSpan);\n } catch (error) {\n return failSpan(error);\n }\n };\n}\n\n/**\n * Patch every executable tool on an operation's `tools` (a record keyed by tool name) so each\n * invocation emits a `gen_ai.execute_tool` span. v5 routes tool execution through the batch\n * `executeTools`, which binds `tool.execute` at call time — so replacing the `execute` property here\n * (before the call runs) is picked up. Tools without an `execute` (client-side tools) are skipped,\n * matching `executeTools`.\n */\nfunction patchOperationTools(tools: Record<string, unknown>, options: VercelAiChannelOptions): void {\n // This runs inside the channel `start` transform (no upstream try/catch), so a throw here would break\n // the user's `ai` call. Instrumentation must never do that — degrade to no tool span instead.\n try {\n for (const [toolName, tool] of Object.entries(tools)) {\n if (isObjectLike(tool)) {\n patchToolExecute(toolName, tool, tools, options);\n }\n }\n } catch {\n DEBUG_BUILD && debug.log('Vercel AI tool patching failed.');\n }\n}\n\nfunction patchToolExecute(\n toolName: string,\n tool: PatchableTool,\n tools: Record<string, unknown>,\n options: VercelAiChannelOptions,\n): void {\n const original = tool.execute;\n if (typeof original !== 'function' || tool[TOOL_PATCHED]) {\n return;\n }\n tool[TOOL_PATCHED] = true;\n tool.execute = function (this: unknown, input: unknown, ...rest: unknown[]): unknown {\n // Skip if there's no enclosing operation span (telemetry disabled for the call), or if that parent\n // is itself a tool-call span — the latter means v6's `executeToolCall` already opened a span for\n // this call and is running `execute` inside it, so spanning again here would double-count. On v5\n // the parent is the enclosing `invoke_agent` operation span, so we proceed.\n const parent = resolveModelCallParent();\n if (!parent || toolCallSpans.has(parent)) {\n return original.apply(this, [input, ...rest]);\n }\n\n // v5 passes `{ toolCallId, messages, abortSignal, ... }` as the second argument to `execute`.\n const callOptions = isObjectLike(rest[0]) ? rest[0] : {};\n const message: VercelAiChannelMessage = {\n type: 'executeTool',\n event: {\n callId: callIdBySpan.get(parent),\n toolCall: { toolName, toolCallId: asString(callOptions.toolCallId), input },\n // The `tools` record (keyed by name) lets the shared core backfill the tool's `description`.\n tools,\n // Inherit the enclosing operation's per-call recording flags so tool inputs/outputs are recorded\n // whenever they are on the parent `invoke_agent` span.\n ...recordingBySpan.get(parent),\n },\n };\n const span = withActiveSpan(parent, () => createSpanFromMessage(message, options));\n // `executeTool` always opens a span; the guard just keeps the wrapper safe if that changes.\n if (!span) {\n return original.apply(this, [input, ...rest]);\n }\n\n // v5's `executeTools` catches a thrown tool error and turns it into `tool-error` content rather than\n // rejecting, so the user never sees a rejection — we must capture it here. On v4 the rejection bubbles\n // out of the call and reaches the user's error handling (or our global handlers), so we only mark the\n // span and leave the capture to them, avoiding a duplicate report. Rethrow either way so `executeTools`\n // still produces its `tool-error` result (v5) and the rejection propagates (v4).\n const failSpan = (error: unknown): never => {\n if (operationErrorInfoBySpan.get(parent)?.toolErrorsBubbleToCaller) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: error instanceof Error ? error.message : 'tool_error' });\n } else {\n captureToolError(span, message, error);\n }\n endSpan(span, { error });\n throw error;\n };\n\n try {\n const result = Promise.resolve(original.apply(this, [input, ...rest]));\n return result.then(value => {\n // The shared core (matching v6/v7) expects the tool result nested under `output`.\n message.result = { output: value };\n enrichSpanOnEnd(span, message);\n endSpan(span, { response: message.result });\n return value;\n }, failSpan);\n } catch (error) {\n return failSpan(error);\n }\n };\n}\n\nfunction endSpan(span: Span, result: GenAiSpanResult<unknown>): void {\n runVercelAiSpanEnd(span, result);\n span.end();\n}\n\nfunction buildTextMessage(type: 'generateText' | 'streamText' | 'streamObject' | 'generateObject'): MessageBuilder {\n return (options, telemetry) => ({\n type,\n event: {\n callId: nextCallId(),\n operationId: `ai.${type}`,\n functionId: asString(telemetry.functionId),\n ...modelFields(options.model),\n maxRetries: options.maxRetries,\n // The `ai` SDK takes the system prompt as a top-level `system` option (all of v4/v5/v6); the\n // shared core lifts `event.instructions` into the system-instructions attribute, matching v7's\n // native channel (which carries it as a distinct field rather than inside the messages array).\n instructions: options.system,\n // Normalize to the message-array shape the shared core (and v7's channel) expects: a bare string\n // `prompt` becomes a single user message, matching the SDK's own normalization.\n messages: normalizePromptMessages(options),\n // v7's native start event carries `providerOptions`; the shared core reads the OpenAI\n // Conversations API id from it.\n providerOptions: options.providerOptions,\n telemetryMetadata: telemetry.metadata,\n ...recording(telemetry),\n },\n });\n}\n\nfunction normalizePromptMessages(options: Record<string, unknown>): unknown {\n if (Array.isArray(options.messages)) {\n return options.messages;\n }\n if (typeof options.prompt === 'string') {\n return [{ role: 'user', content: options.prompt }];\n }\n return options.messages ?? options.prompt;\n}\n\nfunction recording(telemetry: Record<string, unknown>): { recordInputs: unknown; recordOutputs: unknown } {\n // Match the OTel integration's per-call default: an explicit `recordInputs`/`recordOutputs` wins, but a\n // call that merely enables telemetry (`isEnabled: true`, no explicit flags) defaults both to `true`.\n // Unlike v7's native `ai:telemetry` channel, the orchestrion channels expose `isEnabled`, so — as noted\n // in `resolveRecording` — we CAN reproduce that default here (the native-channel subscriber cannot).\n const enabledDefault = telemetry.isEnabled === true ? true : undefined;\n return {\n recordInputs: telemetry.recordInputs ?? enabledDefault,\n recordOutputs: telemetry.recordOutputs ?? enabledDefault,\n };\n}\n\nfunction modelFields(model: unknown): { provider?: string; modelId?: string } {\n return { provider: modelField(model, 'provider'), modelId: modelField(model, 'modelId') };\n}\n\nfunction modelField(model: unknown, field: 'modelId' | 'provider'): string | undefined {\n return isObjectLike(model) ? asString(model[field]) : undefined;\n}\n"],"mappings":";;;;;;;;AAwEA,MAAM,UAAU,OAAO,4BAA4B;AACnD,MAAM,eAAe,OAAO,2BAA2B;AASvD,IAAI,gBAAgB;AACpB,SAAS,aAAqB;CAC5B,OAAO,MAAM,EAAE;AACjB;AAIA,MAAM,2BAAW,IAAI,QAAwC;AAI7D,MAAM,iCAAiB,IAAI,QAAc;AAIzC,MAAM,gCAAgB,IAAI,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