@sentry/server-utils 11.14.0 → 11.15.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/chunks/exports.js +526 -217
- package/build/cjs/chunks/exports.js.map +1 -1
- package/build/cjs/index.js +1028 -120
- package/build/cjs/index.js.map +1 -1
- package/build/esm/ai/anthropic-ai/index.js +32 -56
- package/build/esm/ai/anthropic-ai/index.js.map +1 -1
- package/build/esm/ai/anthropic-ai/streaming.js +10 -6
- package/build/esm/ai/anthropic-ai/streaming.js.map +1 -1
- package/build/esm/ai/anthropic-ai/tool-runner.js +18 -3
- package/build/esm/ai/anthropic-ai/tool-runner.js.map +1 -1
- package/build/esm/ai/anthropic-ai/utils.js +41 -3
- package/build/esm/ai/anthropic-ai/utils.js.map +1 -1
- package/build/esm/ai/core/span-hooks.js +23 -0
- package/build/esm/ai/core/span-hooks.js.map +1 -0
- package/build/esm/ai/core/time-to-first-chunk.js +14 -0
- package/build/esm/ai/core/time-to-first-chunk.js.map +1 -0
- package/build/esm/ai/core/utils.js +29 -3
- package/build/esm/ai/core/utils.js.map +1 -1
- package/build/esm/ai/flue/index.js +15 -12
- package/build/esm/ai/flue/index.js.map +1 -1
- package/build/esm/ai/flue/utils.js +24 -17
- package/build/esm/ai/flue/utils.js.map +1 -1
- package/build/esm/ai/google-genai/index.js +21 -8
- package/build/esm/ai/google-genai/index.js.map +1 -1
- package/build/esm/ai/google-genai/streaming.js +6 -2
- package/build/esm/ai/google-genai/streaming.js.map +1 -1
- package/build/esm/ai/langchain/embeddings.js +5 -2
- package/build/esm/ai/langchain/embeddings.js.map +1 -1
- package/build/esm/ai/langchain/index.js +82 -24
- package/build/esm/ai/langchain/index.js.map +1 -1
- package/build/esm/ai/langchain/utils.js +9 -1
- package/build/esm/ai/langchain/utils.js.map +1 -1
- package/build/esm/ai/langgraph/agent-span.js +13 -5
- package/build/esm/ai/langgraph/agent-span.js.map +1 -1
- package/build/esm/ai/langgraph/index.js +13 -15
- package/build/esm/ai/langgraph/index.js.map +1 -1
- package/build/esm/ai/langgraph/stream.js +4 -3
- package/build/esm/ai/langgraph/stream.js.map +1 -1
- package/build/esm/ai/langgraph/utils.js +17 -8
- package/build/esm/ai/langgraph/utils.js.map +1 -1
- package/build/esm/ai/mastra/classifier-evaluation.js.map +1 -1
- package/build/esm/ai/mastra/index.js +33 -16
- package/build/esm/ai/mastra/index.js.map +1 -1
- package/build/esm/ai/mastra/utils.js +3 -5
- package/build/esm/ai/mastra/utils.js.map +1 -1
- package/build/esm/ai/mistral/index.js +21 -7
- package/build/esm/ai/mistral/index.js.map +1 -1
- package/build/esm/ai/mistral/streaming.js +4 -2
- package/build/esm/ai/mistral/streaming.js.map +1 -1
- package/build/esm/ai/openai/index.js +19 -8
- package/build/esm/ai/openai/index.js.map +1 -1
- package/build/esm/ai/openai/streaming.js +7 -2
- package/build/esm/ai/openai/streaming.js.map +1 -1
- package/build/esm/ai/pi-ai/chat.js +18 -1
- package/build/esm/ai/pi-ai/chat.js.map +1 -1
- package/build/esm/ai/pi-ai/recording.js +34 -15
- package/build/esm/ai/pi-ai/recording.js.map +1 -1
- package/build/esm/ai/pi-durable/index.js +7 -2
- package/build/esm/ai/pi-durable/index.js.map +1 -1
- package/build/esm/ai/pi-durable/runs.js.map +1 -1
- package/build/esm/ai/pi-durable/tools.js +18 -3
- package/build/esm/ai/pi-durable/tools.js.map +1 -1
- package/build/esm/ai/typesafe/index.js +14 -6
- package/build/esm/ai/typesafe/index.js.map +1 -1
- package/build/esm/ai/workers-ai/index.js +26 -9
- package/build/esm/ai/workers-ai/index.js.map +1 -1
- package/build/esm/ai/workers-ai/streaming.js +6 -4
- package/build/esm/ai/workers-ai/streaming.js.map +1 -1
- package/build/esm/cron/common.js +16 -0
- package/build/esm/cron/common.js.map +1 -0
- package/build/esm/cron/cron.js +82 -0
- package/build/esm/cron/cron.js.map +1 -0
- package/build/esm/cron/index.js +13 -0
- package/build/esm/cron/index.js.map +1 -0
- package/build/esm/cron/node-cron.js +66 -0
- package/build/esm/cron/node-cron.js.map +1 -0
- package/build/esm/cron/node-schedule.js +43 -0
- package/build/esm/cron/node-schedule.js.map +1 -0
- package/build/esm/index.js +6 -2
- package/build/esm/index.js.map +1 -1
- package/build/esm/integrations/anthropic.js +25 -16
- package/build/esm/integrations/anthropic.js.map +1 -1
- package/build/esm/integrations/aws-sdk/index.js +1 -0
- package/build/esm/integrations/aws-sdk/index.js.map +1 -1
- package/build/esm/integrations/aws-sdk/services/ServicesExtensions.js +3 -0
- package/build/esm/integrations/aws-sdk/services/ServicesExtensions.js.map +1 -1
- package/build/esm/integrations/aws-sdk/services/bedrock-runtime.js +45 -12
- package/build/esm/integrations/aws-sdk/services/bedrock-runtime.js.map +1 -1
- package/build/esm/integrations/bullmq/contextManager.js +45 -0
- package/build/esm/integrations/bullmq/contextManager.js.map +1 -0
- package/build/esm/integrations/bullmq/index.js +44 -0
- package/build/esm/integrations/bullmq/index.js.map +1 -0
- package/build/esm/integrations/bullmq/meter.js +86 -0
- package/build/esm/integrations/bullmq/meter.js.map +1 -0
- package/build/esm/integrations/bullmq/span.js +114 -0
- package/build/esm/integrations/bullmq/span.js.map +1 -0
- package/build/esm/integrations/bullmq/tracer.js +62 -0
- package/build/esm/integrations/bullmq/tracer.js.map +1 -0
- package/build/esm/integrations/express/instrumentation.js +10 -1
- package/build/esm/integrations/express/instrumentation.js.map +1 -1
- package/build/esm/integrations/google-genai.js +17 -9
- package/build/esm/integrations/google-genai.js.map +1 -1
- package/build/esm/integrations/langgraph.js +5 -7
- package/build/esm/integrations/langgraph.js.map +1 -1
- package/build/esm/integrations/mastra-classifier.js +1 -1
- package/build/esm/integrations/mastra-classifier.js.map +1 -1
- package/build/esm/integrations/mistral.js +13 -4
- package/build/esm/integrations/mistral.js.map +1 -1
- package/build/esm/integrations/openai-compatible.js +16 -8
- package/build/esm/integrations/openai-compatible.js.map +1 -1
- package/build/esm/integrations/openai.js +16 -8
- package/build/esm/integrations/openai.js.map +1 -1
- package/build/esm/integrations/pi-ai.js +39 -18
- package/build/esm/integrations/pi-ai.js.map +1 -1
- package/build/esm/integrations/pino.js +131 -0
- package/build/esm/integrations/pino.js.map +1 -0
- package/build/esm/integrations/typesafe.js +17 -3
- package/build/esm/integrations/typesafe.js.map +1 -1
- package/build/esm/integrations/vercel-ai/index.js.map +1 -1
- package/build/esm/integrations/vercel-ai/util.js +3 -2
- package/build/esm/integrations/vercel-ai/util.js.map +1 -1
- package/build/esm/integrations/vercel-ai/vercel-ai-dc-subscriber.js +44 -17
- 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 +22 -16
- package/build/esm/integrations/vercel-ai/vercel-ai-orchestrion-subscriber.js.map +1 -1
- package/build/esm/integrations/winston.js +90 -0
- package/build/esm/integrations/winston.js.map +1 -0
- package/build/esm/orchestrion/detect.js +1 -1
- package/build/esm/orchestrion/detect.js.map +1 -1
- package/build/esm/package.json +1 -1
- package/build/types/ai/anthropic-ai/index.d.ts +1 -5
- package/build/types/ai/anthropic-ai/index.d.ts.map +1 -1
- package/build/types/ai/anthropic-ai/streaming.d.ts +3 -2
- package/build/types/ai/anthropic-ai/streaming.d.ts.map +1 -1
- package/build/types/ai/anthropic-ai/tool-runner.d.ts.map +1 -1
- package/build/types/ai/anthropic-ai/types.d.ts +24 -3
- package/build/types/ai/anthropic-ai/types.d.ts.map +1 -1
- package/build/types/ai/anthropic-ai/utils.d.ts +2 -3
- package/build/types/ai/anthropic-ai/utils.d.ts.map +1 -1
- package/build/types/ai/core/span-hooks.d.ts +31 -0
- package/build/types/ai/core/span-hooks.d.ts.map +1 -0
- package/build/types/ai/core/time-to-first-chunk.d.ts +7 -0
- package/build/types/ai/core/time-to-first-chunk.d.ts.map +1 -0
- package/build/types/ai/core/utils.d.ts +30 -1
- package/build/types/ai/core/utils.d.ts.map +1 -1
- package/build/types/ai/flue/index.d.ts +13 -5
- package/build/types/ai/flue/index.d.ts.map +1 -1
- package/build/types/ai/flue/types.d.ts +20 -2
- package/build/types/ai/flue/types.d.ts.map +1 -1
- package/build/types/ai/flue/utils.d.ts +5 -9
- package/build/types/ai/flue/utils.d.ts.map +1 -1
- package/build/types/ai/google-genai/index.d.ts.map +1 -1
- package/build/types/ai/google-genai/streaming.d.ts +2 -1
- package/build/types/ai/google-genai/streaming.d.ts.map +1 -1
- package/build/types/ai/google-genai/types.d.ts +17 -3
- package/build/types/ai/google-genai/types.d.ts.map +1 -1
- package/build/types/ai/langchain/index.d.ts.map +1 -1
- package/build/types/ai/langchain/types.d.ts +49 -3
- package/build/types/ai/langchain/types.d.ts.map +1 -1
- package/build/types/ai/langchain/utils.d.ts +6 -0
- package/build/types/ai/langchain/utils.d.ts.map +1 -1
- package/build/types/ai/langgraph/agent-span.d.ts +4 -1
- package/build/types/ai/langgraph/agent-span.d.ts.map +1 -1
- package/build/types/ai/langgraph/index.d.ts +1 -1
- package/build/types/ai/langgraph/index.d.ts.map +1 -1
- package/build/types/ai/langgraph/stream.d.ts.map +1 -1
- package/build/types/ai/langgraph/types.d.ts +14 -3
- package/build/types/ai/langgraph/types.d.ts.map +1 -1
- package/build/types/ai/langgraph/utils.d.ts +3 -0
- package/build/types/ai/langgraph/utils.d.ts.map +1 -1
- package/build/types/ai/mastra/classifier-evaluation.d.ts +3 -3
- package/build/types/ai/mastra/classifier-evaluation.d.ts.map +1 -1
- package/build/types/ai/mastra/index.d.ts +17 -3
- package/build/types/ai/mastra/index.d.ts.map +1 -1
- package/build/types/ai/mastra/types.d.ts +2 -0
- package/build/types/ai/mastra/types.d.ts.map +1 -1
- package/build/types/ai/mastra/utils.d.ts.map +1 -1
- package/build/types/ai/mistral/index.d.ts.map +1 -1
- package/build/types/ai/mistral/streaming.d.ts +2 -1
- package/build/types/ai/mistral/streaming.d.ts.map +1 -1
- package/build/types/ai/mistral/types.d.ts +14 -3
- package/build/types/ai/mistral/types.d.ts.map +1 -1
- package/build/types/ai/openai/index.d.ts.map +1 -1
- package/build/types/ai/openai/streaming.d.ts +3 -1
- package/build/types/ai/openai/streaming.d.ts.map +1 -1
- package/build/types/ai/openai/types.d.ts +14 -3
- package/build/types/ai/openai/types.d.ts.map +1 -1
- package/build/types/ai/pi-ai/chat.d.ts +7 -1
- package/build/types/ai/pi-ai/chat.d.ts.map +1 -1
- package/build/types/ai/pi-ai/recording.d.ts +21 -9
- package/build/types/ai/pi-ai/recording.d.ts.map +1 -1
- package/build/types/ai/pi-ai/types.d.ts +16 -0
- package/build/types/ai/pi-ai/types.d.ts.map +1 -1
- package/build/types/ai/pi-durable/index.d.ts +12 -3
- package/build/types/ai/pi-durable/index.d.ts.map +1 -1
- package/build/types/ai/pi-durable/runs.d.ts +2 -0
- package/build/types/ai/pi-durable/runs.d.ts.map +1 -1
- package/build/types/ai/pi-durable/tools.d.ts +4 -3
- package/build/types/ai/pi-durable/tools.d.ts.map +1 -1
- package/build/types/ai/pi-durable/types.d.ts +15 -0
- package/build/types/ai/pi-durable/types.d.ts.map +1 -1
- package/build/types/ai/typesafe/index.d.ts +10 -2
- package/build/types/ai/typesafe/index.d.ts.map +1 -1
- package/build/types/ai/workers-ai/index.d.ts.map +1 -1
- package/build/types/ai/workers-ai/streaming.d.ts +2 -1
- package/build/types/ai/workers-ai/streaming.d.ts.map +1 -1
- package/build/types/ai/workers-ai/types.d.ts +18 -3
- package/build/types/ai/workers-ai/types.d.ts.map +1 -1
- package/build/types/cron/common.d.ts +8 -0
- package/build/types/cron/common.d.ts.map +1 -0
- package/build/types/cron/cron.d.ts +45 -0
- package/build/types/cron/cron.d.ts.map +1 -0
- package/build/types/cron/index.d.ts +10 -0
- package/build/types/cron/index.d.ts.map +1 -0
- package/build/types/cron/node-cron.d.ts +33 -0
- package/build/types/cron/node-cron.d.ts.map +1 -0
- package/build/types/cron/node-schedule.d.ts +19 -0
- package/build/types/cron/node-schedule.d.ts.map +1 -0
- package/build/types/index.d.ts +5 -2
- package/build/types/index.d.ts.map +1 -1
- package/build/types/integrations/anthropic.d.ts +2 -1
- package/build/types/integrations/anthropic.d.ts.map +1 -1
- package/build/types/integrations/aws-sdk/index.d.ts +3 -3
- package/build/types/integrations/aws-sdk/index.d.ts.map +1 -1
- package/build/types/integrations/aws-sdk/services/ServiceExtension.d.ts +1 -0
- package/build/types/integrations/aws-sdk/services/ServiceExtension.d.ts.map +1 -1
- package/build/types/integrations/aws-sdk/services/ServicesExtensions.d.ts +3 -2
- package/build/types/integrations/aws-sdk/services/ServicesExtensions.d.ts.map +1 -1
- package/build/types/integrations/aws-sdk/services/bedrock-runtime.d.ts +25 -4
- package/build/types/integrations/aws-sdk/services/bedrock-runtime.d.ts.map +1 -1
- package/build/types/integrations/bullmq/contextManager.d.ts +13 -0
- package/build/types/integrations/bullmq/contextManager.d.ts.map +1 -0
- package/build/types/integrations/bullmq/index.d.ts +43 -0
- package/build/types/integrations/bullmq/index.d.ts.map +1 -0
- package/build/types/integrations/bullmq/meter.d.ts +7 -0
- package/build/types/integrations/bullmq/meter.d.ts.map +1 -0
- package/build/types/integrations/bullmq/span.d.ts +35 -0
- package/build/types/integrations/bullmq/span.d.ts.map +1 -0
- package/build/types/integrations/bullmq/tracer.d.ts +5 -0
- package/build/types/integrations/bullmq/tracer.d.ts.map +1 -0
- package/build/types/integrations/bullmq/types.d.ts +72 -0
- package/build/types/integrations/bullmq/types.d.ts.map +1 -0
- package/build/types/integrations/express/types.d.ts +1 -0
- package/build/types/integrations/express/types.d.ts.map +1 -1
- package/build/types/integrations/flue.d.ts +2 -1
- package/build/types/integrations/flue.d.ts.map +1 -1
- package/build/types/integrations/google-genai.d.ts +2 -1
- package/build/types/integrations/google-genai.d.ts.map +1 -1
- package/build/types/integrations/groq.d.ts +1 -1
- package/build/types/integrations/langchain.d.ts +2 -1
- package/build/types/integrations/langchain.d.ts.map +1 -1
- package/build/types/integrations/langgraph.d.ts +2 -1
- package/build/types/integrations/langgraph.d.ts.map +1 -1
- package/build/types/integrations/mistral.d.ts +2 -1
- package/build/types/integrations/mistral.d.ts.map +1 -1
- package/build/types/integrations/openai-compatible.d.ts.map +1 -1
- package/build/types/integrations/openai.d.ts +2 -1
- package/build/types/integrations/openai.d.ts.map +1 -1
- package/build/types/integrations/pi-ai.d.ts +6 -3
- package/build/types/integrations/pi-ai.d.ts.map +1 -1
- package/build/types/integrations/pi-durable.d.ts +2 -1
- package/build/types/integrations/pi-durable.d.ts.map +1 -1
- package/build/types/integrations/pino.d.ts +61 -0
- package/build/types/integrations/pino.d.ts.map +1 -0
- package/build/types/integrations/together-ai.d.ts +1 -1
- package/build/types/integrations/typesafe.d.ts +2 -2
- package/build/types/integrations/typesafe.d.ts.map +1 -1
- package/build/types/integrations/vercel-ai/index.d.ts +3 -3
- package/build/types/integrations/vercel-ai/index.d.ts.map +1 -1
- package/build/types/integrations/vercel-ai/util.d.ts +2 -1
- package/build/types/integrations/vercel-ai/util.d.ts.map +1 -1
- package/build/types/integrations/vercel-ai/vercel-ai-dc-subscriber.d.ts +20 -4
- package/build/types/integrations/vercel-ai/vercel-ai-dc-subscriber.d.ts.map +1 -1
- package/build/types/integrations/vercel-ai/vercel-ai-orchestrion-subscriber.d.ts.map +1 -1
- package/build/types/integrations/winston.d.ts +55 -0
- package/build/types/integrations/winston.d.ts.map +1 -0
- package/package.json +3 -3
|
@@ -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 {\n captureToolError,\n clearOperationCallId,\n clearOperationId,\n createSpanFromMessage,\n enrichSpanOnEnd,\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, options);\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 (message.type !== 'streamText' && message.type !== 'streamObject') {\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, options),\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 options: VercelAiChannelOptions,\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, options);\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 span.end();\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 value.stream,\n final => {\n message.result = { ...value, ...streamedResultToChannelResult(final) };\n enrichSpanOnEnd(span, message, options);\n span.end();\n clearStreamCallId();\n },\n error => {\n span.setStatus({\n code: SPAN_STATUS_ERROR,\n message: error instanceof Error ? error.message : 'unknown_error',\n });\n span.end();\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, options);\n span.end();\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 span.end();\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, options);\n span.end();\n return value;\n }, failSpan);\n } catch (error) {\n return failSpan(error);\n }\n };\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":";;;;;;;;AAsEA,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,GAAG,OAAO;EACzG,cAAc,gBAAgB,S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,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 (`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,iB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|
+
import { SENTRY_ORIGIN } from "@sentry/conventions/attributes";
|
|
3
|
+
import { _INTERNAL_captureLog, debug, isObjectLike } from "@sentry/core";
|
|
4
|
+
// src/integrations/winston.ts
|
|
5
|
+
const DEFAULT_CAPTURED_LEVELS = [
|
|
6
|
+
"trace",
|
|
7
|
+
"debug",
|
|
8
|
+
"info",
|
|
9
|
+
"warn",
|
|
10
|
+
"error",
|
|
11
|
+
"fatal"
|
|
12
|
+
];
|
|
13
|
+
const LEVEL_SYMBOL = Symbol.for("level");
|
|
14
|
+
const MESSAGE_SYMBOL = Symbol.for("message");
|
|
15
|
+
const SPLAT_SYMBOL = Symbol.for("splat");
|
|
16
|
+
/**
|
|
17
|
+
* Creates a new Sentry Winston transport that fowards logs to Sentry.
|
|
18
|
+
*
|
|
19
|
+
* Supports Winston 3.x.x.
|
|
20
|
+
*
|
|
21
|
+
* @param TransportClass - The Winston transport class to extend.
|
|
22
|
+
* @returns The extended transport class.
|
|
23
|
+
*
|
|
24
|
+
* @example
|
|
25
|
+
* ```ts
|
|
26
|
+
* const winston = require('winston');
|
|
27
|
+
* const Transport = require('winston-transport');
|
|
28
|
+
*
|
|
29
|
+
* const SentryWinstonTransport = Sentry.createSentryWinstonTransport(Transport);
|
|
30
|
+
*
|
|
31
|
+
* const logger = winston.createLogger({
|
|
32
|
+
* transports: [new SentryWinstonTransport()],
|
|
33
|
+
* });
|
|
34
|
+
* ```
|
|
35
|
+
*/
|
|
36
|
+
function createSentryWinstonTransport(TransportClass, sentryWinstonOptions) {
|
|
37
|
+
class SentryWinstonTransport extends TransportClass {
|
|
38
|
+
constructor(options) {
|
|
39
|
+
super(options);
|
|
40
|
+
this._levels = new Set(sentryWinstonOptions?.levels ?? DEFAULT_CAPTURED_LEVELS);
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Forwards a winston log to the Sentry SDK.
|
|
44
|
+
*/
|
|
45
|
+
log(info, callback) {
|
|
46
|
+
try {
|
|
47
|
+
setImmediate(() => {
|
|
48
|
+
this.emit("logged", info);
|
|
49
|
+
});
|
|
50
|
+
if (!isObjectLike(info)) return;
|
|
51
|
+
const levelFromSymbol = info[LEVEL_SYMBOL];
|
|
52
|
+
const { level, message, timestamp, ...attributes } = info;
|
|
53
|
+
attributes[LEVEL_SYMBOL] = void 0;
|
|
54
|
+
attributes[MESSAGE_SYMBOL] = void 0;
|
|
55
|
+
attributes[SPLAT_SYMBOL] = void 0;
|
|
56
|
+
const customLevel = sentryWinstonOptions?.customLevelMap?.[levelFromSymbol];
|
|
57
|
+
const winstonLogLevel = WINSTON_LEVEL_TO_LOG_SEVERITY_LEVEL_MAP[levelFromSymbol];
|
|
58
|
+
const logSeverityLevel = customLevel ?? winstonLogLevel ?? "info";
|
|
59
|
+
if (this._levels.has(logSeverityLevel)) _INTERNAL_captureLog({
|
|
60
|
+
level: logSeverityLevel,
|
|
61
|
+
message,
|
|
62
|
+
attributes: {
|
|
63
|
+
...attributes,
|
|
64
|
+
[SENTRY_ORIGIN]: "auto.log.winston"
|
|
65
|
+
}
|
|
66
|
+
});
|
|
67
|
+
else if (!customLevel && !winstonLogLevel) DEBUG_BUILD && debug.log(`Winston log level ${levelFromSymbol} is not captured by Sentry. Please add ${levelFromSymbol} to the "customLevelMap" option of the Sentry Winston transport.`);
|
|
68
|
+
} catch {}
|
|
69
|
+
if (callback) callback();
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
return SentryWinstonTransport;
|
|
73
|
+
}
|
|
74
|
+
const WINSTON_LEVEL_TO_LOG_SEVERITY_LEVEL_MAP = {
|
|
75
|
+
silly: "trace",
|
|
76
|
+
debug: "debug",
|
|
77
|
+
verbose: "debug",
|
|
78
|
+
http: "debug",
|
|
79
|
+
info: "info",
|
|
80
|
+
notice: "info",
|
|
81
|
+
warn: "warn",
|
|
82
|
+
warning: "warn",
|
|
83
|
+
error: "error",
|
|
84
|
+
emerg: "fatal",
|
|
85
|
+
alert: "fatal",
|
|
86
|
+
crit: "fatal"
|
|
87
|
+
};
|
|
88
|
+
export { createSentryWinstonTransport };
|
|
89
|
+
|
|
90
|
+
//# sourceMappingURL=winston.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"winston.js","names":[],"sources":["../../../src/integrations/winston.ts"],"sourcesContent":["import { SENTRY_ORIGIN } from '@sentry/conventions/attributes';\n/* eslint-disable @typescript-eslint/ban-ts-comment */\nimport type { LogSeverityLevel } from '@sentry/core';\nimport { _INTERNAL_captureLog, debug, isObjectLike } from '@sentry/core';\nimport { DEBUG_BUILD } from '../debug-build';\n\nconst DEFAULT_CAPTURED_LEVELS: Array<LogSeverityLevel> = ['trace', 'debug', 'info', 'warn', 'error', 'fatal'];\n\n// See: https://github.com/winstonjs/triple-beam\nconst LEVEL_SYMBOL = Symbol.for('level');\nconst MESSAGE_SYMBOL = Symbol.for('message');\nconst SPLAT_SYMBOL = Symbol.for('splat');\n\n/**\n * Options for the Sentry Winston transport.\n */\ninterface WinstonTransportOptions {\n /**\n * Use this option to filter which levels should be captured. By default, all levels are captured.\n *\n * @example\n * ```ts\n * const SentryWinstonTransport = Sentry.createSentryWinstonTransport(Transport, {\n * // Only capture error and warn logs\n * levels: ['error', 'warn'],\n * });\n * ```\n */\n levels?: Array<LogSeverityLevel>;\n\n /**\n * Use this option to map custom levels to Sentry log severity levels.\n *\n * @example\n * ```ts\n * const SentryWinstonTransport = Sentry.createSentryWinstonTransport(Transport, {\n * customLevelMap: {\n * myCustomLevel: 'info',\n * customError: 'error',\n * },\n * });\n * ```\n */\n customLevelMap?: Record<string, LogSeverityLevel>;\n}\n\n/**\n * Creates a new Sentry Winston transport that fowards logs to Sentry.\n *\n * Supports Winston 3.x.x.\n *\n * @param TransportClass - The Winston transport class to extend.\n * @returns The extended transport class.\n *\n * @example\n * ```ts\n * const winston = require('winston');\n * const Transport = require('winston-transport');\n *\n * const SentryWinstonTransport = Sentry.createSentryWinstonTransport(Transport);\n *\n * const logger = winston.createLogger({\n * transports: [new SentryWinstonTransport()],\n * });\n * ```\n */\nexport function createSentryWinstonTransport<TransportStreamInstance extends object>(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n TransportClass: new (options?: any) => TransportStreamInstance,\n sentryWinstonOptions?: WinstonTransportOptions,\n): typeof TransportClass {\n // @ts-ignore - We know this is safe because SentryWinstonTransport extends TransportClass\n class SentryWinstonTransport extends TransportClass {\n private _levels: Set<LogSeverityLevel>;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n public constructor(options?: any) {\n super(options);\n this._levels = new Set(sentryWinstonOptions?.levels ?? DEFAULT_CAPTURED_LEVELS);\n }\n\n /**\n * Forwards a winston log to the Sentry SDK.\n */\n public log(info: unknown, callback: () => void): void {\n try {\n setImmediate(() => {\n // @ts-ignore - We know this is safe because SentryWinstonTransport extends TransportClass\n this.emit('logged', info);\n });\n\n if (!isObjectLike(info)) {\n return;\n }\n\n const levelFromSymbol = info[LEVEL_SYMBOL];\n\n // See: https://github.com/winstonjs/winston?tab=readme-ov-file#streams-objectmode-and-info-objects\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { level, message, timestamp, ...attributes } = info;\n // Remove all symbols from the remaining attributes\n attributes[LEVEL_SYMBOL] = undefined;\n attributes[MESSAGE_SYMBOL] = undefined;\n attributes[SPLAT_SYMBOL] = undefined;\n\n const customLevel = sentryWinstonOptions?.customLevelMap?.[levelFromSymbol as string];\n const winstonLogLevel = WINSTON_LEVEL_TO_LOG_SEVERITY_LEVEL_MAP[levelFromSymbol as string];\n const logSeverityLevel = customLevel ?? winstonLogLevel ?? 'info';\n\n if (this._levels.has(logSeverityLevel)) {\n _INTERNAL_captureLog({\n level: logSeverityLevel,\n message: message as string,\n attributes: {\n ...attributes,\n [SENTRY_ORIGIN]: 'auto.log.winston',\n },\n });\n } else if (!customLevel && !winstonLogLevel) {\n DEBUG_BUILD &&\n debug.log(\n `Winston log level ${levelFromSymbol} is not captured by Sentry. Please add ${levelFromSymbol} to the \"customLevelMap\" option of the Sentry Winston transport.`,\n );\n }\n } catch {\n // do nothing\n }\n\n if (callback) {\n callback();\n }\n }\n }\n\n return SentryWinstonTransport as typeof TransportClass;\n}\n\n// npm\n// {\n// error: 0,\n// warn: 1,\n// info: 2,\n// http: 3,\n// verbose: 4,\n// debug: 5,\n// silly: 6\n// }\n//\n// syslog\n// {\n// emerg: 0,\n// alert: 1,\n// crit: 2,\n// error: 3,\n// warning: 4,\n// notice: 5,\n// info: 6,\n// debug: 7,\n// }\nconst WINSTON_LEVEL_TO_LOG_SEVERITY_LEVEL_MAP: Record<string, LogSeverityLevel> = {\n // npm\n silly: 'trace',\n // npm and syslog\n debug: 'debug',\n // npm\n verbose: 'debug',\n // npm\n http: 'debug',\n // npm and syslog\n info: 'info',\n // syslog\n notice: 'info',\n // npm\n warn: 'warn',\n // syslog\n warning: 'warn',\n // npm and syslog\n error: 'error',\n // syslog\n emerg: 'fatal',\n // syslog\n alert: 'fatal',\n // syslog\n crit: 'fatal',\n};\n"],"mappings":";;;;AAMA,MAAM,0BAAmD;CAAC;CAAS;CAAS;CAAQ;CAAQ;CAAS;AAAO;AAG5G,MAAM,eAAe,OAAO,IAAI,OAAO;AACvC,MAAM,iBAAiB,OAAO,IAAI,SAAS;AAC3C,MAAM,eAAe,OAAO,IAAI,OAAO;;;;;;;;;;;;;;;;;;;;;AAuDvC,SAAgB,6BAEd,gBACA,sBACuB;CAEvB,MAAM,+BAA+B,eAAe;EAG3C,YAAY,SAAe;GAChC,MAAM,OAAO;GACb,KAAK,UAAU,IAAI,IAAI,sBAAsB,UAAU,uBAAuB;EAChF;;;;EAKO,IAAI,MAAe,UAA4B;GACpD,IAAI;IACF,mBAAmB;KAEjB,KAAK,KAAK,UAAU,IAAI;IAC1B,CAAC;IAED,IAAI,CAAC,aAAa,IAAI,GACpB;IAGF,MAAM,kBAAkB,KAAK;IAI7B,MAAM,EAAE,OAAO,SAAS,WAAW,GAAG,eAAe;IAErD,WAAW,gBAAgB,KAAA;IAC3B,WAAW,kBAAkB,KAAA;IAC7B,WAAW,gBAAgB,KAAA;IAE3B,MAAM,cAAc,sBAAsB,iBAAiB;IAC3D,MAAM,kBAAkB,wCAAwC;IAChE,MAAM,mBAAmB,eAAe,mBAAmB;IAE3D,IAAI,KAAK,QAAQ,IAAI,gBAAgB,GACnC,qBAAqB;KACnB,OAAO;KACE;KACT,YAAY;MACV,GAAG;OACF,gBAAgB;KACnB;IACF,CAAC;SACI,IAAI,CAAC,eAAe,CAAC,iBAC1B,eACE,MAAM,IACJ,qBAAqB,gBAAgB,yCAAyC,gBAAgB,iEAChG;GAEN,QAAQ,CAER;GAEA,IAAI,UACF,SAAS;EAEb;CACF;CAEA,OAAO;AACT;AAwBA,MAAM,0CAA4E;CAEhF,OAAO;CAEP,OAAO;CAEP,SAAS;CAET,MAAM;CAEN,MAAM;CAEN,QAAQ;CAER,MAAM;CAEN,SAAS;CAET,OAAO;CAEP,OAAO;CAEP,OAAO;CAEP,MAAM;AACR"}
|
|
@@ -39,7 +39,7 @@ function detectOrchestrionSetup() {
|
|
|
39
39
|
if (!marker.warnedBunRunNotInjected) {
|
|
40
40
|
marker.warnedBunRunNotInjected = true;
|
|
41
41
|
consoleSandbox(() => {
|
|
42
|
-
console.warn("[Sentry] No diagnostics-channel injection detected. Channel-based integrations will not record spans or capture errors
|
|
42
|
+
console.warn("[Sentry] No diagnostics-channel injection detected. Channel-based integrations will not record spans or capture errors. On Bun 1.4.6 or later, run your app with `bun --preload @sentry/bun/import`. Or build your app with `@sentry/bun/plugin`.");
|
|
43
43
|
});
|
|
44
44
|
}
|
|
45
45
|
return;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"detect.js","names":[],"sources":["../../../src/orchestrion/detect.ts"],"sourcesContent":["import { consoleSandbox, debug, GLOBAL_OBJ } from '@sentry/core';\nimport { isBun } from '../utils/runtime';\n\n/**\n * The module names (e.g. `mysql`, `@hapi/hapi`) orchestrion has already injected\n * into this process — from the runtime `--import` hook (`runtime`) and/or the\n * snippets a bundler transform spliced into each transformed module (`bundler`).\n * Channel-based integrations use it to decide whether to subscribe now (their\n * module is already loaded) or wait for the module-injected event.\n *\n * The `instanceof Set` guard is runtime safety, not typing: a banner from\n * another SDK copy or version may have written a non-Set flag here.\n */\nexport function getOrchestrionInjectedModules(): string[] {\n const { runtime, bundler } = GLOBAL_OBJ.__SENTRY_ORCHESTRION__ ?? {};\n return [...(runtime ?? []), ...(bundler instanceof Set ? bundler : [])];\n}\n\n/**\n * Verifies that the diagnostics channels have been injected either by the\n * runtime `--import` hook (or init-time registration), a bundler plugin, or\n * both, and warns if not. When at least one injector is active, logs for each\n * mechanism whether it hooked (a defined list, even empty, means it did) and\n * which libraries it injected. For the bundler path, the entry banner ensures\n * an empty `Set` at boot; module names arrive as each transformed module is\n * evaluated, so an empty set can also just mean none has loaded yet.\n *\n * Both injectors being active at once is fine: they operate on disjoint module\n * sets (a module is either loaded through Node's loader and transformed by the\n * runtime hook, or inlined by the bundler and transformed by the plugin), so\n * a single module can't be double-wrapped. A hybrid setup, with some deps\n * external and runtime-instrumented, others bundled and plugin-instrumented,\n * is fine.\n */\nexport function detectOrchestrionSetup(): void {\n const marker = GLOBAL_OBJ.__SENTRY_ORCHESTRION__ ?? {};\n const { runtime, bundler, channelIntegrations } = marker;\n\n if (!runtime && !bundler) {\n if (channelIntegrations && isBun()) {\n if (!marker.warnedBunRunNotInjected) {\n marker.warnedBunRunNotInjected = true;\n consoleSandbox(() => {\n // oxlint-disable-next-line no-console\n console.warn(\n '[Sentry] No diagnostics-channel injection detected. Channel-based integrations will not record ' +\n 'spans or capture errors
|
|
1
|
+
{"version":3,"file":"detect.js","names":[],"sources":["../../../src/orchestrion/detect.ts"],"sourcesContent":["import { consoleSandbox, debug, GLOBAL_OBJ } from '@sentry/core';\nimport { isBun } from '../utils/runtime';\n\n/**\n * The module names (e.g. `mysql`, `@hapi/hapi`) orchestrion has already injected\n * into this process — from the runtime `--import` hook (`runtime`) and/or the\n * snippets a bundler transform spliced into each transformed module (`bundler`).\n * Channel-based integrations use it to decide whether to subscribe now (their\n * module is already loaded) or wait for the module-injected event.\n *\n * The `instanceof Set` guard is runtime safety, not typing: a banner from\n * another SDK copy or version may have written a non-Set flag here.\n */\nexport function getOrchestrionInjectedModules(): string[] {\n const { runtime, bundler } = GLOBAL_OBJ.__SENTRY_ORCHESTRION__ ?? {};\n return [...(runtime ?? []), ...(bundler instanceof Set ? bundler : [])];\n}\n\n/**\n * Verifies that the diagnostics channels have been injected either by the\n * runtime `--import` hook (or init-time registration), a bundler plugin, or\n * both, and warns if not. When at least one injector is active, logs for each\n * mechanism whether it hooked (a defined list, even empty, means it did) and\n * which libraries it injected. For the bundler path, the entry banner ensures\n * an empty `Set` at boot; module names arrive as each transformed module is\n * evaluated, so an empty set can also just mean none has loaded yet.\n *\n * Both injectors being active at once is fine: they operate on disjoint module\n * sets (a module is either loaded through Node's loader and transformed by the\n * runtime hook, or inlined by the bundler and transformed by the plugin), so\n * a single module can't be double-wrapped. A hybrid setup, with some deps\n * external and runtime-instrumented, others bundled and plugin-instrumented,\n * is fine.\n */\nexport function detectOrchestrionSetup(): void {\n const marker = GLOBAL_OBJ.__SENTRY_ORCHESTRION__ ?? {};\n const { runtime, bundler, channelIntegrations } = marker;\n\n if (!runtime && !bundler) {\n if (channelIntegrations && isBun()) {\n if (!marker.warnedBunRunNotInjected) {\n marker.warnedBunRunNotInjected = true;\n consoleSandbox(() => {\n // oxlint-disable-next-line no-console\n console.warn(\n '[Sentry] No diagnostics-channel injection detected. Channel-based integrations will not record ' +\n 'spans or capture errors. On Bun 1.4.6 or later, run your app with `bun --preload @sentry/bun/import`. ' +\n 'Or build your app with `@sentry/bun/plugin`.',\n );\n });\n }\n return;\n }\n\n debug.warn(\n '[Sentry] No diagnostics-channel injection detected. Channel-based integrations ' +\n 'will not record spans. Make sure the diagnostics channels are injected ' +\n 'via the runtime `--import` hook or a bundler plugin before the instrumented modules load.',\n );\n return;\n }\n\n debug.log(\n runtime\n ? `[Sentry] Runtime hook registered, injected libraries=${JSON.stringify(runtime)}`\n : '[Sentry] Runtime hook not registered',\n );\n debug.log(\n bundler\n ? `[Sentry] Bundler plugin ran, injected libraries=${JSON.stringify(\n bundler instanceof Set ? [...bundler] : bundler,\n )}`\n : '[Sentry] Bundler plugin did not run',\n );\n}\n"],"mappings":";;;;;;;;;;;;;AAaA,SAAgB,gCAA0C;CACxD,MAAM,EAAE,SAAS,YAAY,WAAW,0BAA0B,CAAC;CACnE,OAAO,CAAC,GAAI,WAAW,CAAC,GAAI,GAAI,mBAAmB,MAAM,UAAU,CAAC,CAAE;AACxE;;;;;;;;;;;;;;;;;AAkBA,SAAgB,yBAA+B;CAC7C,MAAM,SAAS,WAAW,0BAA0B,CAAC;CACrD,MAAM,EAAE,SAAS,SAAS,wBAAwB;CAElD,IAAI,CAAC,WAAW,CAAC,SAAS;EACxB,IAAI,uBAAuB,MAAM,GAAG;GAClC,IAAI,CAAC,OAAO,yBAAyB;IACnC,OAAO,0BAA0B;IACjC,qBAAqB;KAEnB,QAAQ,KACN,mPAGF;IACF,CAAC;GACH;GACA;EACF;EAEA,MAAM,KACJ,iPAGF;EACA;CACF;CAEA,MAAM,IACJ,UACI,wDAAwD,KAAK,UAAU,OAAO,MAC9E,sCACN;CACA,MAAM,IACJ,UACI,mDAAmD,KAAK,UACtD,mBAAmB,MAAM,CAAC,GAAG,OAAO,IAAI,OAC1C,MACA,qCACN;AACF"}
|
package/build/esm/package.json
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"type":"module","version":"11.
|
|
1
|
+
{"type":"module","version":"11.15.0","sideEffects":false}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { Span } from '@sentry/core';
|
|
2
|
-
import type { AnthropicAiOptions
|
|
2
|
+
import type { AnthropicAiOptions } from './types';
|
|
3
3
|
/**
|
|
4
4
|
* Extract request attributes from method arguments
|
|
5
5
|
*/
|
|
@@ -9,10 +9,6 @@ export declare function extractRequestAttributes(args: unknown[], operationName:
|
|
|
9
9
|
* This is only recorded if recordInputs is true.
|
|
10
10
|
*/
|
|
11
11
|
export declare function addPrivateRequestAttributes(span: Span, params: Record<string, unknown>): void;
|
|
12
|
-
/**
|
|
13
|
-
* Add response attributes to spans
|
|
14
|
-
*/
|
|
15
|
-
export declare function addResponseAttributes(span: Span, response: AnthropicAiResponse, recordOutputs?: boolean): void;
|
|
16
12
|
/**
|
|
17
13
|
* Instrument an Anthropic AI client with Sentry tracing
|
|
18
14
|
* Can be used across Node.js, Cloudflare Workers, and Vercel Edge
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/ai/anthropic-ai/index.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/ai/anthropic-ai/index.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,IAAI,EAAsB,MAAM,cAAc,CAAC;AA0B7D,OAAO,KAAK,EAAuB,kBAAkB,EAAkD,MAAM,SAAS,CAAC;AAYvH;;GAEG;AACH,wBAAgB,wBAAwB,CACtC,IAAI,EAAE,OAAO,EAAE,EACf,aAAa,EAAE,MAAM,EACrB,YAAY,EAAE,OAAO,EACrB,YAAY,SAAc,GACzB,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAyBzB;AAED;;;GAGG;AACH,wBAAgB,2BAA2B,CAAC,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,CAG7F;AA4OD;;;;;;;;GAQG;AACH,wBAAgB,2BAA2B,CAAC,CAAC,SAAS,MAAM,EAAE,iBAAiB,EAAE,CAAC,EAAE,OAAO,CAAC,EAAE,kBAAkB,GAAG,CAAC,CAEnH"}
|
|
@@ -1,16 +1,17 @@
|
|
|
1
1
|
import type { Span } from '@sentry/core';
|
|
2
|
+
import type { GenAiSpanResult } from '../core/span-hooks';
|
|
2
3
|
import type { AnthropicAiStreamingEvent } from './types';
|
|
3
4
|
/**
|
|
4
5
|
* Instruments an async iterable stream of Anthropic events, updates the span with
|
|
5
6
|
* streaming attributes and (optionally) the aggregated output text, and yields
|
|
6
7
|
* each event from the input stream unchanged.
|
|
7
8
|
*/
|
|
8
|
-
export declare function instrumentAsyncIterableStream(stream: AsyncIterable<AnthropicAiStreamingEvent>, span: Span, recordOutputs: boolean): AsyncGenerator<AnthropicAiStreamingEvent, void, unknown>;
|
|
9
|
+
export declare function instrumentAsyncIterableStream(stream: AsyncIterable<AnthropicAiStreamingEvent>, span: Span, recordOutputs: boolean, beforeSpanEnd?: (result: GenAiSpanResult<never>) => void): AsyncGenerator<AnthropicAiStreamingEvent, void, unknown>;
|
|
9
10
|
/**
|
|
10
11
|
* Instruments a MessageStream by registering event handlers and preserving the original stream API.
|
|
11
12
|
*/
|
|
12
13
|
export declare function instrumentMessageStream<R extends {
|
|
13
14
|
on: (...args: unknown[]) => void;
|
|
14
15
|
aborted?: boolean;
|
|
15
|
-
}>(stream: R, span: Span, recordOutputs: boolean, abortSignal?: AbortSignal): R;
|
|
16
|
+
}>(stream: R, span: Span, recordOutputs: boolean, abortSignal?: AbortSignal, beforeSpanEnd?: (result: GenAiSpanResult<never>) => void): R;
|
|
16
17
|
//# sourceMappingURL=streaming.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"streaming.d.ts","sourceRoot":"","sources":["../../../../src/ai/anthropic-ai/streaming.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,cAAc,CAAC;
|
|
1
|
+
{"version":3,"file":"streaming.d.ts","sourceRoot":"","sources":["../../../../src/ai/anthropic-ai/streaming.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,cAAc,CAAC;AACzC,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AAG1D,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,SAAS,CAAC;AA2NzD;;;;GAIG;AACH,wBAAuB,6BAA6B,CAClD,MAAM,EAAE,aAAa,CAAC,yBAAyB,CAAC,EAChD,IAAI,EAAE,IAAI,EACV,aAAa,EAAE,OAAO,EACtB,aAAa,CAAC,EAAE,CAAC,MAAM,EAAE,eAAe,CAAC,KAAK,CAAC,KAAK,IAAI,GACvD,cAAc,CAAC,yBAAyB,EAAE,IAAI,EAAE,OAAO,CAAC,CA4B1D;AAED;;GAEG;AACH,wBAAgB,uBAAuB,CAAC,CAAC,SAAS;IAAE,EAAE,EAAE,CAAC,GAAG,IAAI,EAAE,OAAO,EAAE,KAAK,IAAI,CAAC;IAAC,OAAO,CAAC,EAAE,OAAO,CAAA;CAAE,EACvG,MAAM,EAAE,CAAC,EACT,IAAI,EAAE,IAAI,EACV,aAAa,EAAE,OAAO,EACtB,WAAW,CAAC,EAAE,WAAW,EACzB,aAAa,CAAC,EAAE,CAAC,MAAM,EAAE,eAAe,CAAC,KAAK,CAAC,KAAK,IAAI,GACvD,CAAC,CAsDH"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tool-runner.d.ts","sourceRoot":"","sources":["../../../../src/ai/anthropic-ai/tool-runner.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"tool-runner.d.ts","sourceRoot":"","sources":["../../../../src/ai/anthropic-ai/tool-runner.ts"],"names":[],"mappings":"AAmCA,OAAO,KAAK,EAAuB,kBAAkB,EAAE,MAAM,SAAS,CAAC;AAQvE,kGAAkG;AAClG,wBAAgB,2BAA2B,CACzC,KAAK,EAAE,MAAM,EACb,gBAAgB,EAAE,CAAC,MAAM,EAAE,OAAO,EAAE,OAAO,EAAE,kBAAkB,KAAK,IAAI,EACxE,OAAO,EAAE,kBAAkB,GAC1B,IAAI,CAMN;AAED,yEAAyE;AACzE,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,OAAO,EAAE,OAAO,EAAE,kBAAkB,GAAG,IAAI,CAiBvF;AAED,gIAAgI;AAChI,wBAAgB,2BAA2B,CAAC,MAAM,EAAE,OAAO,EAAE,OAAO,EAAE,kBAAkB,GAAG,IAAI,CAc9F"}
|
|
@@ -1,6 +1,27 @@
|
|
|
1
|
-
import type {
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
import type { GenAiSpanHooks } from '../core/span-hooks';
|
|
2
|
+
import type { GenAiCallOptions } from '../core/utils';
|
|
3
|
+
/**
|
|
4
|
+
* The call that `recordInputs`/`recordOutputs` decide on, and that the span hooks get: a model call, or a tool
|
|
5
|
+
* call of a tool runner.
|
|
6
|
+
*/
|
|
7
|
+
export type AnthropicAiCallInfo = {
|
|
8
|
+
operation: 'chat';
|
|
9
|
+
/** The request params, the first argument of the method (such as `messages.create`) as passed. */
|
|
10
|
+
request: Record<string, unknown> | undefined;
|
|
11
|
+
} | {
|
|
12
|
+
operation: 'execute_tool';
|
|
13
|
+
/** The runnable tool, as passed to the tool runner. */
|
|
14
|
+
tool: {
|
|
15
|
+
name: string;
|
|
16
|
+
};
|
|
17
|
+
/** The input the model called the tool with. */
|
|
18
|
+
input: unknown;
|
|
19
|
+
};
|
|
20
|
+
/**
|
|
21
|
+
* Options for the Anthropic AI integration. `onSpanEnd` gets the response the method resolved with, such as a
|
|
22
|
+
* `Message`, or the result of a tool call; for streams it is `undefined`.
|
|
23
|
+
*/
|
|
24
|
+
export type AnthropicAiOptions = GenAiCallOptions<AnthropicAiCallInfo> & GenAiSpanHooks<AnthropicAiCallInfo>;
|
|
4
25
|
export type Message = {
|
|
5
26
|
role: 'user' | 'assistant';
|
|
6
27
|
content: string | unknown[];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../../src/ai/anthropic-ai/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../../src/ai/anthropic-ai/types.ts"],"names":[],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f,cAAc,GACd,qBAAqB,GACrB,qBAAqB,GACrB,oBAAoB,GACpB,OAAO,CAAC;IACZ,KAAK,CAAC,EAAE;QACN,IAAI,EAAE,MAAM,CAAC;QACb,OAAO,EAAE,MAAM,CAAC;KACjB,CAAC;IACF,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,KAAK,CAAC,EAAE;QACN,IAAI,EAAE,OAAO,CAAC;QACd,IAAI,CAAC,EAAE,MAAM,CAAC;QACd,8CAA8C;QAC9C,YAAY,CAAC,EAAE,MAAM,CAAC;QACtB,WAAW,CAAC,EAAE,MAAM,CAAC;QACrB,aAAa,CAAC,EAAE,MAAM,CAAC;KACxB,CAAC;IACF,KAAK,CAAC,EAAE;QACN,aAAa,EAAE,MAAM,CAAC;QAEtB,YAAY,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;QAC7B,2BAA2B,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;QAC5C,uBAAuB,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;KACzC,CAAC;IACF,OAAO,CAAC,EAAE,kBAAkB,CAAC;IAC7B,8CAA8C;IAC9C,aAAa,CAAC,EAAE,YAAY,CAAC;CAC9B,CAAC"}
|
|
@@ -15,10 +15,9 @@ export declare function getMessagesAttributes(messages: unknown): Record<string,
|
|
|
15
15
|
*/
|
|
16
16
|
export declare function mapAnthropicErrorToStatusMessage(errorType: string | undefined): SpanStatusType;
|
|
17
17
|
/**
|
|
18
|
-
*
|
|
19
|
-
* @see https://docs.anthropic.com/en/api/errors#error-shapes
|
|
18
|
+
* Add response attributes to spans
|
|
20
19
|
*/
|
|
21
|
-
export declare function
|
|
20
|
+
export declare function addResponseAttributes(span: Span, response: AnthropicAiResponse, recordOutputs?: boolean): void;
|
|
22
21
|
/**
|
|
23
22
|
* Include the system prompt in the messages list, if available
|
|
24
23
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../../../src/ai/anthropic-ai/utils.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../../../src/ai/anthropic-ai/utils.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,IAAI,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAUzD,OAAO,KAAK,EAAE,mBAAmB,EAAgB,MAAM,SAAS,CAAC;AAEjE;;;GAGG;AACH,wBAAgB,eAAe,CAAC,QAAQ,EAAE,OAAO,GAAG,MAAM,CAIzD;AAED;;GAEG;AACH,wBAAgB,qBAAqB,CAAC,QAAQ,EAAE,OAAO,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,CAa3F;AAaD;;;GAGG;AACH,wBAAgB,gCAAgC,CAAC,SAAS,EAAE,MAAM,GAAG,SAAS,GAAG,cAAc,CAK9F;AA4ED;;GAEG;AACH,wBAAgB,qBAAqB,CAAC,IAAI,EAAE,IAAI,EAAE,QAAQ,EAAE,mBAAmB,EAAE,aAAa,CAAC,EAAE,OAAO,GAAG,IAAI,CAgB9G;AAaD;;GAEG;AACH,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,OAAO,EAAE,CAiB7E"}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { Span } from '@sentry/core';
|
|
2
|
+
/** How a gen_ai call ended, as passed to {@link GenAiSpanHooks.onSpanEnd}. */
|
|
3
|
+
export interface GenAiSpanResult<TResponse> {
|
|
4
|
+
/** The response as the library returned it. `undefined` for streams and failed calls. */
|
|
5
|
+
response?: TResponse;
|
|
6
|
+
/** Set when the call failed. */
|
|
7
|
+
error?: unknown;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Hooks that let an integration's users add their own attributes to its gen_ai spans. `TCall` is the same
|
|
11
|
+
* call info that `recordInputs`/`recordOutputs` get, and both hooks get the same object.
|
|
12
|
+
*
|
|
13
|
+
* They only run for spans that are recorded. A hook that throws is logged and does not affect the call.
|
|
14
|
+
*/
|
|
15
|
+
export interface GenAiSpanHooks<TCall, TResponse = unknown> {
|
|
16
|
+
/**
|
|
17
|
+
* Runs after the span started and the SDK set its request attributes, in the caller's async context, so
|
|
18
|
+
* it can read request-scoped state.
|
|
19
|
+
*/
|
|
20
|
+
onSpanStart?: (span: Span, call: TCall) => void;
|
|
21
|
+
/**
|
|
22
|
+
* Runs after the SDK set its response attributes, right before the span ends. That can be in another
|
|
23
|
+
* async context than the call, for example when a stream is consumed later.
|
|
24
|
+
*/
|
|
25
|
+
onSpanEnd?: (span: Span, call: TCall, result: GenAiSpanResult<TResponse>) => void;
|
|
26
|
+
}
|
|
27
|
+
/** Runs {@link GenAiSpanHooks.onSpanStart}. */
|
|
28
|
+
export declare function runGenAiSpanStart<TCall>(hooks: Pick<GenAiSpanHooks<TCall>, 'onSpanStart'>, span: Span, call: TCall): void;
|
|
29
|
+
/** Runs {@link GenAiSpanHooks.onSpanEnd}. Call it right before the span ends. */
|
|
30
|
+
export declare function runGenAiSpanEnd<TCall, TResponse>(hooks: GenAiSpanHooks<TCall, TResponse>, span: Span, call: TCall, result: GenAiSpanResult<TResponse>): void;
|
|
31
|
+
//# sourceMappingURL=span-hooks.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"span-hooks.d.ts","sourceRoot":"","sources":["../../../../src/ai/core/span-hooks.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,cAAc,CAAC;AAGzC,8EAA8E;AAC9E,MAAM,WAAW,eAAe,CAAC,SAAS;IACxC,yFAAyF;IACzF,QAAQ,CAAC,EAAE,SAAS,CAAC;IACrB,gCAAgC;IAChC,KAAK,CAAC,EAAE,OAAO,CAAC;CACjB;AAED;;;;;GAKG;AACH,MAAM,WAAW,cAAc,CAAC,KAAK,EAAE,SAAS,GAAG,OAAO;IACxD;;;OAGG;IACH,WAAW,CAAC,EAAE,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,KAAK,IAAI,CAAC;IAChD;;;OAGG;IACH,SAAS,CAAC,EAAE,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,MAAM,EAAE,eAAe,CAAC,SAAS,CAAC,KAAK,IAAI,CAAC;CACnF;AAED,+CAA+C;AAC/C,wBAAgB,iBAAiB,CAAC,KAAK,EACrC,KAAK,EAAE,IAAI,CAAC,cAAc,CAAC,KAAK,CAAC,EAAE,aAAa,CAAC,EACjD,IAAI,EAAE,IAAI,EACV,IAAI,EAAE,KAAK,GACV,IAAI,CAKN;AAED,iFAAiF;AACjF,wBAAgB,eAAe,CAAC,KAAK,EAAE,SAAS,EAC9C,KAAK,EAAE,cAAc,CAAC,KAAK,EAAE,SAAS,CAAC,EACvC,IAAI,EAAE,IAAI,EACV,IAAI,EAAE,KAAK,EACX,MAAM,EAAE,eAAe,CAAC,SAAS,CAAC,GACjC,IAAI,CAKN"}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { Span } from '@sentry/core';
|
|
2
|
+
/**
|
|
3
|
+
* Sets `gen_ai.response.time_to_first_chunk` on a streamed span, in seconds from the span start.
|
|
4
|
+
* Call it for each received chunk. Only the first call per span records a value.
|
|
5
|
+
*/
|
|
6
|
+
export declare function recordTimeToFirstChunk(span: Span): void;
|
|
7
|
+
//# sourceMappingURL=time-to-first-chunk.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"time-to-first-chunk.d.ts","sourceRoot":"","sources":["../../../../src/ai/core/time-to-first-chunk.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,cAAc,CAAC;AAGzC;;;GAGG;AACH,wBAAgB,sBAAsB,CAAC,IAAI,EAAE,IAAI,GAAG,IAAI,CAKvD"}
|
|
@@ -11,6 +11,26 @@ export interface GenAiOptions {
|
|
|
11
11
|
*/
|
|
12
12
|
recordOutputs?: boolean;
|
|
13
13
|
}
|
|
14
|
+
/**
|
|
15
|
+
* Whether to record the content of a gen_ai call: a boolean for every call, or a function that decides for
|
|
16
|
+
* each call. The function runs once when the call starts, in the caller's async context, so it can read
|
|
17
|
+
* request-scoped state. Returning `undefined` falls back to `dataCollection.genAI`. If it throws, the
|
|
18
|
+
* content is not recorded.
|
|
19
|
+
*/
|
|
20
|
+
export type GenAiRecordingOption<TCall> = boolean | ((call: TCall) => boolean | undefined);
|
|
21
|
+
/** {@link GenAiOptions} of an integration that can decide per call. `TCall` is what the function gets. */
|
|
22
|
+
export interface GenAiCallOptions<TCall> {
|
|
23
|
+
/**
|
|
24
|
+
* Record input messages/prompts on gen_ai spans. Defaults to the global
|
|
25
|
+
* `dataCollection.genAI.inputs` setting; an explicit value here takes precedence.
|
|
26
|
+
*/
|
|
27
|
+
recordInputs?: GenAiRecordingOption<TCall>;
|
|
28
|
+
/**
|
|
29
|
+
* Record output text/responses on gen_ai spans. Defaults to the global
|
|
30
|
+
* `dataCollection.genAI.outputs` setting; an explicit value here takes precedence.
|
|
31
|
+
*/
|
|
32
|
+
recordOutputs?: GenAiRecordingOption<TCall>;
|
|
33
|
+
}
|
|
14
34
|
/**
|
|
15
35
|
* A method registry entry describes a single instrumented method:
|
|
16
36
|
* which gen_ai operation it maps to and whether it is intrinsically streaming.
|
|
@@ -39,6 +59,14 @@ export declare function getGenAiSpanOp(operationName: string): string;
|
|
|
39
59
|
* Precedence: explicit option > dataCollection.genAI > true (genAI data collected by default)
|
|
40
60
|
*/
|
|
41
61
|
export declare function resolveAIRecordingOptions<T extends GenAiOptions>(options?: T): T & Required<GenAiOptions>;
|
|
62
|
+
/**
|
|
63
|
+
* Resolves the recording options of one call, like {@link resolveAIRecordingOptions}, and calls the
|
|
64
|
+
* options that are functions with `call`. Call it once when the call starts, so the functions run in the
|
|
65
|
+
* caller's async context.
|
|
66
|
+
*/
|
|
67
|
+
export declare function resolveGenAiCallRecording<TCall>(options: GenAiCallOptions<TCall> | undefined, call: TCall): Required<GenAiOptions>;
|
|
68
|
+
/** Calls `option` with `call` when it is a function; `undefined` means the option does not decide. */
|
|
69
|
+
export declare function resolveRecordingOption<TCall>(option: GenAiRecordingOption<TCall> | undefined, call: TCall): boolean | undefined;
|
|
42
70
|
/**
|
|
43
71
|
* Build method path from current traversal
|
|
44
72
|
*/
|
|
@@ -112,8 +140,9 @@ export declare function markCancelledIfAborted(span: Span, abortSignal: AbortSig
|
|
|
112
140
|
/**
|
|
113
141
|
* Ends a streaming span by setting all accumulated response attributes and ending the span.
|
|
114
142
|
* Shared across OpenAI, Anthropic, and Google GenAI streaming implementations.
|
|
143
|
+
* `beforeSpanEnd` runs after the attributes are set, right before the span ends.
|
|
115
144
|
*/
|
|
116
|
-
export declare function endStreamSpan(span: Span, state: StreamResponseState, recordOutputs: boolean): void;
|
|
145
|
+
export declare function endStreamSpan(span: Span, state: StreamResponseState, recordOutputs: boolean, beforeSpanEnd?: () => void): void;
|
|
117
146
|
/**
|
|
118
147
|
* Extract system instructions from messages array.
|
|
119
148
|
* Finds the first system message and formats it according to OpenTelemetry semantic conventions.
|