@sentry/server-utils 11.14.0 → 11.16.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 +604 -219
- 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/cjs/index.request-handler.js +1 -0
- package/build/cjs/index.request-handler.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 +25 -17
- package/build/esm/ai/flue/utils.js.map +1 -1
- package/build/esm/ai/google-genai/decisions.js +29 -1
- package/build/esm/ai/google-genai/decisions.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/mapping.js +48 -1
- package/build/esm/ai/openai/mapping.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/esm/utils/wrapServerRequestHandler.js +2 -1
- package/build/esm/utils/wrapServerRequestHandler.js.map +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/decisions.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/mapping.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/types.d.ts +1 -1
- package/build/types/ai/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/build/types/utils/wrapServerRequestHandler.d.ts.map +1 -1
- package/package.json +4 -4
|
@@ -162,6 +162,7 @@ async function wrapServerRequestHandler(config, handler) {
|
|
|
162
162
|
Object.assign(attributes, (0, _sentry_core.httpHeadersToSpanAttributes)(headers, dataCollection));
|
|
163
163
|
Object.assign(attributes, config.attributes);
|
|
164
164
|
attributes[_sentry_conventions_attributes.SENTRY_OP] = _sentry_conventions_op.HTTP_SERVER;
|
|
165
|
+
attributes[_sentry_conventions_attributes.SENTRY_KIND] = "server";
|
|
165
166
|
return (0, _sentry_core.startSpanManual)({
|
|
166
167
|
name,
|
|
167
168
|
attributes
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.request-handler.js","names":["isError","DEBUG_BUILD","debug","captureException","winterCGRequestToRequestData","isServedTunnelRequest","startRequestSession","classifyResponseStreaming","safeCallback","DEBUG_BUILD","captureBodyFromWinterCGRequest","parseStringToURLObject","continueTrace","getHttpSpanDetailsFromUrlObject","SENTRY_SEGMENT_NAME_SOURCE","hasSpanStreamingEnabled","HTTP_SPAN_NAME_FALLBACK","HTTP_REQUEST_BODY_SIZE","USER_AGENT_ORIGINAL","winterCGHeadersToDict","getClientIPAddress","CLIENT_ADDRESS","CLIENT_PORT","NETWORK_PROTOCOL_NAME","httpHeadersToSpanAttributes","SENTRY_OP","HTTP_SERVER","startSpanManual","SPAN_STATUS_ERROR","setHttpStatus","getCurrentScope","withIsolationScope","withScope","hasSpansEnabled","isStaticAssetRequest"],"sources":["../../src/utils/monitorStream.ts","../../src/utils/wrapServerRequestHandler.ts"],"sourcesContent":["import { debug, isError } from '@sentry/core';\nimport { DEBUG_BUILD } from '../debug-build';\n\n/**\n * Monitor the source without reading ahead or treating cancellation as a source failure.\n *\n * `onDone` runs once, while the returned stream is still open: before it closes, before it errors,\n * or when the consumer cancels it. A runtime can end the request when the response body closes\n * (Cloudflare Workers then reject `waitUntil`), so work that `onDone` starts must begin first.\n */\nexport function monitorStream(\n stream: ReadableStream<Uint8Array>,\n onDone: () => void,\n onError: (error: unknown) => void,\n): ReadableStream<Uint8Array> {\n let reader: ReadableStreamDefaultReader<Uint8Array>;\n let finished = false;\n const finish = (error?: { error: unknown }): void => {\n if (finished) {\n return;\n }\n finished = true;\n // A callback that throws must not fail the response body.\n try {\n // A source that stops on `request.signal` errors with an `AbortError` when the client\n // disconnects, which is a cancellation too.\n if (error && !(isError(error.error) && error.error.name === 'AbortError')) {\n onError(error.error);\n }\n onDone();\n } catch (e) {\n DEBUG_BUILD && debug.error('Error when a monitored stream finished:', e);\n }\n };\n\n return new ReadableStream<Uint8Array>(\n {\n // Locks the source only once the stream exists, so a constructor that throws leaves it usable.\n start() {\n reader = stream.getReader();\n // A source can fail while no one reads from it. A cancelled reader closes normally; only a\n // source failure should be captured as an error.\n void reader.closed.then(\n () => finish(),\n error => finish({ error }),\n );\n },\n async pull(controller) {\n try {\n const { done, value } = await reader.read();\n if (done) {\n finish();\n controller.close();\n reader.releaseLock();\n } else {\n controller.enqueue(value);\n }\n } catch (error) {\n finish({ error });\n controller.error(error);\n reader.releaseLock();\n }\n },\n async cancel(reason) {\n finish();\n try {\n await reader.cancel(reason);\n } finally {\n reader.releaseLock();\n }\n },\n },\n { highWaterMark: 0 },\n );\n}\n","import {\n CLIENT_ADDRESS,\n CLIENT_PORT,\n HTTP_REQUEST_BODY_SIZE,\n NETWORK_PROTOCOL_NAME,\n SENTRY_OP,\n SENTRY_SEGMENT_NAME_SOURCE,\n USER_AGENT_ORIGINAL,\n} from '@sentry/conventions/attributes';\nimport { HTTP_SERVER } from '@sentry/conventions/op';\nimport type { Client, Mechanism, Scope, SpanAttributes } from '@sentry/core';\nimport {\n captureBodyFromWinterCGRequest,\n captureException,\n continueTrace,\n getCurrentScope,\n getHttpSpanDetailsFromUrlObject,\n hasSpansEnabled,\n hasSpanStreamingEnabled,\n httpHeadersToSpanAttributes,\n HTTP_SPAN_NAME_FALLBACK,\n parseStringToURLObject,\n safeCallback,\n setHttpStatus,\n SPAN_STATUS_ERROR,\n startSpanManual,\n winterCGHeadersToDict,\n winterCGRequestToRequestData,\n withIsolationScope,\n withScope,\n} from '@sentry/core';\nimport type { ServerRequestOptions } from '@sentry/core/server';\nimport {\n _INTERNAL_isServedTunnelRequest as isServedTunnelRequest,\n classifyResponseStreaming,\n getClientIPAddress,\n isStaticAssetRequest,\n startRequestSession,\n} from '@sentry/core/server';\nimport { DEBUG_BUILD } from '../debug-build';\nimport { monitorStream } from './monitorStream';\n\nexport interface ServerRequestHandlerConfig {\n request: Request;\n client: Client;\n /** The isolation scope of this request. */\n isolationScope: Scope;\n /** The options of the runtime's integration for incoming requests. */\n options: ServerRequestOptions<Request, Response> | undefined;\n /** Origin of the span, e.g. `auto.http.deno`. */\n origin: string;\n /** Mechanism of errors that the handler or the response stream throws. Omit to not capture them. */\n mechanism?: Mechanism;\n /** The address and port of the socket, if the runtime knows them. */\n getSocketAddress?: () => { address: string; port?: number } | undefined;\n /** The matched route of the server framework, e.g. `/users/:id`. Sets `http.route` and the span name. */\n routeName?: string;\n /** Span attributes that only the runtime knows, e.g. the route parameters. */\n attributes?: SpanAttributes;\n /**\n * Called in the scope of the continued trace, before the span starts. Lets the runtime continue\n * its own trace, e.g. the trace that Cloudflare exports for the invocation.\n */\n onTraceContinued?: () => void;\n /** Whether the response streams. Return `undefined` to use the default classification. */\n isStreamingResponse?: (response: Response) => boolean | undefined;\n /**\n * Called once when the request is done: when the response is returned, when a streamed body\n * finishes, or when the handler throws (then without a response).\n */\n onDone?: (response: Response | undefined) => void;\n}\n\n/**\n * Wraps a handler of a web `Request`, as used by `Deno.serve`, `Bun.serve` and Cloudflare Workers.\n *\n * It records the request session, attaches the request data and body, continues the incoming\n * trace, creates the `http.server` span, and captures errors that the handler throws. The rules\n * follow core's `node:http` server code:\n *\n * - `OPTIONS` and `HEAD` requests get no span and no body capture.\n * - The static asset filter applies only to `GET`.\n * - The span and the session of a streamed response end when the stream finishes.\n *\n * The handler can return no response, as Bun's `fetch` does after a WebSocket upgrade.\n */\nexport async function wrapServerRequestHandler<R extends Response | undefined = Response>(\n config: ServerRequestHandlerConfig,\n handler: () => R | Promise<R>,\n): Promise<R> {\n const { request, client, isolationScope, options, mechanism } = config;\n\n const method = request.method.toUpperCase();\n const captureError = (error: unknown): void => {\n if (mechanism) {\n captureException(error, { mechanism });\n }\n };\n\n const socketAddress = config.getSocketAddress?.();\n // Without `AsyncLocalStorage`, all requests share one isolation scope, so clear what an earlier\n // request left on it: the merge keeps its body, and its response context would stay set.\n isolationScope.setSDKProcessingMetadata({\n normalizedRequest: { ...winterCGRequestToRequestData(request), data: undefined },\n ipAddress: socketAddress?.address,\n });\n isolationScope.setContext('response', null);\n\n // Tunnel requests get no session, body or span, whether the SDK or the app answers them. The app answers them with\n // `intercept: false`, from its own code, so its errors are still captured.\n if (isServedTunnelRequest(request, client)) {\n let response: R | undefined;\n try {\n response = await handler();\n return response;\n } catch (e) {\n captureError(e);\n throw e;\n } finally {\n config.onDone?.(response);\n }\n }\n\n const endSession = options?.sessions\n ? startRequestSession(client, {\n requestIsolationScope: isolationScope,\n sessionFlushingDelayMS: options.sessionFlushingDelayMS,\n })\n : undefined;\n const finish = (response: Response | undefined): void => {\n endSession?.();\n config.onDone?.(response);\n };\n const isStreamingResponse = (response: Response): boolean => {\n const classification = config.isStreamingResponse?.(response);\n return typeof classification === 'boolean' ? classification : classifyResponseStreaming(response).isStreaming;\n };\n\n if (method === 'OPTIONS' || method === 'HEAD') {\n let response: R | undefined;\n try {\n response = await handler();\n return response;\n } catch (e) {\n captureError(e);\n throw e;\n } finally {\n finish(response);\n }\n }\n\n const dataCollection = client.getDataCollectionOptions();\n const effectiveBodySize =\n options?.maxRequestBodySize ?? (dataCollection.httpBodies.includes('incomingRequest') ? 'medium' : 'none');\n const ignoreRequestBody = options?.ignoreRequestBody;\n if (\n method !== 'GET' &&\n effectiveBodySize !== 'none' &&\n // If the filter throws, skip the body so it cannot leak data the filter was meant to hide.\n !(\n ignoreRequestBody &&\n safeCallback(\n DEBUG_BUILD ? 'Error in `ignoreRequestBody`, skipping the body:' : '',\n () => ignoreRequestBody(request.url, request),\n () => true,\n )\n )\n ) {\n await captureBodyFromWinterCGRequest(request, isolationScope, effectiveBodySize);\n }\n\n const urlObject = parseStringToURLObject(request.url);\n const urlPath = urlObject ? `${urlObject.pathname}${urlObject.search}` : '/';\n const createSpan = shouldCreateSpan(client, options, request, urlPath);\n\n return continueTrace(\n {\n sentryTrace: request.headers.get('sentry-trace') || '',\n baggage: request.headers.get('baggage'),\n },\n async () => {\n config.onTraceContinued?.();\n\n if (!createSpan) {\n let response: R;\n try {\n response = await handler();\n } catch (e) {\n captureError(e);\n finish(undefined);\n throw e;\n }\n if (response) {\n isolationScope.setContext('response', { status_code: response.status });\n }\n const inRequestScope = bindToRequestScope(isolationScope);\n return onResponseDone(\n response,\n !!response && isStreamingResponse(response),\n inRequestScope(() => finish(response)),\n inRequestScope(captureError),\n );\n }\n\n const [rawName, attributes] = getHttpSpanDetailsFromUrlObject(\n urlObject,\n 'server',\n config.origin,\n request,\n config.routeName,\n client,\n );\n // With span streaming, span names have to be low cardinality, so we can't fall back to the URL.\n // A `route` source means the name already is (e.g. the `/` path), so it is kept as-is.\n const name =\n attributes[SENTRY_SEGMENT_NAME_SOURCE] === 'route' || !hasSpanStreamingEnabled(client)\n ? rawName\n : method || HTTP_SPAN_NAME_FALLBACK;\n\n const contentLength = request.headers.get('content-length');\n if (contentLength) {\n attributes[HTTP_REQUEST_BODY_SIZE] = parseInt(contentLength, 10);\n }\n const userAgent = request.headers.get('user-agent');\n if (userAgent) {\n attributes[USER_AGENT_ORIGINAL] = userAgent;\n }\n\n const headers = winterCGHeadersToDict(request.headers);\n if (dataCollection.userInfo) {\n // `client.address` is the originating client, so a forwarding header wins over the socket, which\n // behind a proxy holds the proxy's address. The socket port is the proxy's too, so `client.port`\n // stays unset then.\n const forwardedAddress = getClientIPAddress(headers);\n if (forwardedAddress) {\n attributes[CLIENT_ADDRESS] = forwardedAddress;\n } else if (socketAddress) {\n attributes[CLIENT_ADDRESS] = socketAddress.address;\n if (socketAddress.port !== undefined) {\n attributes[CLIENT_PORT] = socketAddress.port;\n }\n }\n }\n\n // describes the OSI application-layer protocol (http), not the scheme (might be https)\n attributes[NETWORK_PROTOCOL_NAME] = 'http';\n Object.assign(attributes, httpHeadersToSpanAttributes(headers, dataCollection));\n Object.assign(attributes, config.attributes);\n attributes[SENTRY_OP] = HTTP_SERVER;\n\n return startSpanManual({ name, attributes }, async span => {\n const { onSpanCreated, onSpanEnd } = options ?? {};\n if (onSpanCreated) {\n safeCallback(\n DEBUG_BUILD ? 'Error in `onSpanCreated`:' : '',\n () => onSpanCreated(span, request),\n () => undefined,\n );\n }\n\n let response: R;\n try {\n response = await handler();\n } catch (e) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n span.end();\n captureError(e);\n finish(undefined);\n throw e;\n }\n\n if (response) {\n setHttpStatus(span, response.status);\n isolationScope.setContext('response', { status_code: response.status });\n span.setAttributes(\n httpHeadersToSpanAttributes(responseHeadersToDict(response.headers), dataCollection, 'response'),\n );\n }\n\n const inRequestScope = bindToRequestScope(isolationScope);\n return onResponseDone(\n response,\n !!response && isStreamingResponse(response),\n inRequestScope(() => {\n if (onSpanEnd && response) {\n safeCallback(\n DEBUG_BUILD ? 'Error in `onSpanEnd`:' : '',\n () => onSpanEnd(span, request, response),\n () => undefined,\n );\n }\n span.end();\n finish(response);\n }),\n inRequestScope((error: unknown) => {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n captureError(error);\n }),\n );\n });\n },\n );\n}\n\n/**\n * Returns a function that binds a callback to the request's isolation scope and the current scope.\n *\n * A streamed body finishes after the handler returns. Without `AsyncLocalStorage` (Cloudflare\n * Workers without `nodejs_compat`), its callbacks then run outside the request's scopes, where\n * `getClient()` finds no client: the segment span would be sent as a transaction, and a captured\n * error would not update the request session.\n */\nfunction bindToRequestScope(\n isolationScope: Scope,\n): <A extends unknown[]>(fn: (...args: A) => void) => (...args: A) => void {\n const scope = getCurrentScope();\n return fn =>\n (...args) =>\n withIsolationScope(isolationScope, () => withScope(scope, () => fn(...args)));\n}\n\nfunction shouldCreateSpan(\n client: Client,\n options: ServerRequestOptions<Request, Response> | undefined,\n request: Request,\n urlPath: string,\n): boolean {\n if (!(options?.spans ?? hasSpansEnabled(client.getOptions()))) {\n return false;\n }\n if (options?.ignoreStaticAssets && request.method.toUpperCase() === 'GET' && isStaticAssetRequest(urlPath)) {\n return false;\n }\n const ignoreIncomingRequests = options?.ignoreIncomingRequests;\n return !(\n ignoreIncomingRequests &&\n safeCallback(\n DEBUG_BUILD ? 'Error in `ignoreIncomingRequests`, creating the span:' : '',\n () => ignoreIncomingRequests(urlPath, request),\n () => false,\n )\n );\n}\n\n/**\n * Calls `onDone` when the response is done: at once, or when a streamed body finishes.\n * Returns the response to send.\n */\nfunction onResponseDone<R extends Response | undefined>(\n response: R,\n isStreaming: boolean,\n onDone: () => void,\n onStreamError: (error: unknown) => void,\n): R {\n if (isStreaming && response?.body && !response.body.locked) {\n try {\n // Passing the original response as the init keeps its status, status text and headers, and\n // on Cloudflare also `encodeBody: 'manual'`, so workerd does not compress a compressed body again.\n return new Response(monitorStream(response.body, onDone, onStreamError), response) as R;\n } catch {\n // Workers with a compatibility date before 2022-11-30 and without the\n // `streams_enable_constructors` flag cannot construct a `ReadableStream`, so end at once.\n }\n }\n onDone();\n return response;\n}\n\n// `Headers.forEach` lists each `Set-Cookie` header on its own, so a plain dict keeps only the last one.\nfunction responseHeadersToDict(headers: Headers): Record<string, string | string[]> {\n const dict: Record<string, string | string[]> = winterCGHeadersToDict(headers);\n const setCookie = typeof headers.getSetCookie === 'function' ? headers.getSetCookie() : [];\n if (setCookie.length) {\n dict['set-cookie'] = setCookie;\n }\n return dict;\n}\n"],"mappings":";;;;;;;;;;;;;;AAUA,SAAgB,cACd,QACA,QACA,SAC4B;CAC5B,IAAI;CACJ,IAAI,WAAW;CACf,MAAM,UAAU,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G_BUILD","debug","captureException","winterCGRequestToRequestData","isServedTunnelRequest","startRequestSession","classifyResponseStreaming","safeCallback","DEBUG_BUILD","captureBodyFromWinterCGRequest","parseStringToURLObject","continueTrace","getHttpSpanDetailsFromUrlObject","SENTRY_SEGMENT_NAME_SOURCE","hasSpanStreamingEnabled","HTTP_SPAN_NAME_FALLBACK","HTTP_REQUEST_BODY_SIZE","USER_AGENT_ORIGINAL","winterCGHeadersToDict","getClientIPAddress","CLIENT_ADDRESS","CLIENT_PORT","NETWORK_PROTOCOL_NAME","httpHeadersToSpanAttributes","SENTRY_OP","HTTP_SERVER","SENTRY_KIND","startSpanManual","SPAN_STATUS_ERROR","setHttpStatus","getCurrentScope","withIsolationScope","withScope","hasSpansEnabled","isStaticAssetRequest"],"sources":["../../src/utils/monitorStream.ts","../../src/utils/wrapServerRequestHandler.ts"],"sourcesContent":["import { debug, isError } from '@sentry/core';\nimport { DEBUG_BUILD } from '../debug-build';\n\n/**\n * Monitor the source without reading ahead or treating cancellation as a source failure.\n *\n * `onDone` runs once, while the returned stream is still open: before it closes, before it errors,\n * or when the consumer cancels it. A runtime can end the request when the response body closes\n * (Cloudflare Workers then reject `waitUntil`), so work that `onDone` starts must begin first.\n */\nexport function monitorStream(\n stream: ReadableStream<Uint8Array>,\n onDone: () => void,\n onError: (error: unknown) => void,\n): ReadableStream<Uint8Array> {\n let reader: ReadableStreamDefaultReader<Uint8Array>;\n let finished = false;\n const finish = (error?: { error: unknown }): void => {\n if (finished) {\n return;\n }\n finished = true;\n // A callback that throws must not fail the response body.\n try {\n // A source that stops on `request.signal` errors with an `AbortError` when the client\n // disconnects, which is a cancellation too.\n if (error && !(isError(error.error) && error.error.name === 'AbortError')) {\n onError(error.error);\n }\n onDone();\n } catch (e) {\n DEBUG_BUILD && debug.error('Error when a monitored stream finished:', e);\n }\n };\n\n return new ReadableStream<Uint8Array>(\n {\n // Locks the source only once the stream exists, so a constructor that throws leaves it usable.\n start() {\n reader = stream.getReader();\n // A source can fail while no one reads from it. A cancelled reader closes normally; only a\n // source failure should be captured as an error.\n void reader.closed.then(\n () => finish(),\n error => finish({ error }),\n );\n },\n async pull(controller) {\n try {\n const { done, value } = await reader.read();\n if (done) {\n finish();\n controller.close();\n reader.releaseLock();\n } else {\n controller.enqueue(value);\n }\n } catch (error) {\n finish({ error });\n controller.error(error);\n reader.releaseLock();\n }\n },\n async cancel(reason) {\n finish();\n try {\n await reader.cancel(reason);\n } finally {\n reader.releaseLock();\n }\n },\n },\n { highWaterMark: 0 },\n );\n}\n","import {\n CLIENT_ADDRESS,\n CLIENT_PORT,\n HTTP_REQUEST_BODY_SIZE,\n NETWORK_PROTOCOL_NAME,\n SENTRY_KIND,\n SENTRY_OP,\n SENTRY_SEGMENT_NAME_SOURCE,\n USER_AGENT_ORIGINAL,\n} from '@sentry/conventions/attributes';\nimport { HTTP_SERVER } from '@sentry/conventions/op';\nimport type { Client, Mechanism, Scope, SpanAttributes } from '@sentry/core';\nimport {\n captureBodyFromWinterCGRequest,\n captureException,\n continueTrace,\n getCurrentScope,\n getHttpSpanDetailsFromUrlObject,\n hasSpansEnabled,\n hasSpanStreamingEnabled,\n httpHeadersToSpanAttributes,\n HTTP_SPAN_NAME_FALLBACK,\n parseStringToURLObject,\n safeCallback,\n setHttpStatus,\n SPAN_STATUS_ERROR,\n startSpanManual,\n winterCGHeadersToDict,\n winterCGRequestToRequestData,\n withIsolationScope,\n withScope,\n} from '@sentry/core';\nimport type { ServerRequestOptions } from '@sentry/core/server';\nimport {\n _INTERNAL_isServedTunnelRequest as isServedTunnelRequest,\n classifyResponseStreaming,\n getClientIPAddress,\n isStaticAssetRequest,\n startRequestSession,\n} from '@sentry/core/server';\nimport { DEBUG_BUILD } from '../debug-build';\nimport { monitorStream } from './monitorStream';\n\nexport interface ServerRequestHandlerConfig {\n request: Request;\n client: Client;\n /** The isolation scope of this request. */\n isolationScope: Scope;\n /** The options of the runtime's integration for incoming requests. */\n options: ServerRequestOptions<Request, Response> | undefined;\n /** Origin of the span, e.g. `auto.http.deno`. */\n origin: string;\n /** Mechanism of errors that the handler or the response stream throws. Omit to not capture them. */\n mechanism?: Mechanism;\n /** The address and port of the socket, if the runtime knows them. */\n getSocketAddress?: () => { address: string; port?: number } | undefined;\n /** The matched route of the server framework, e.g. `/users/:id`. Sets `http.route` and the span name. */\n routeName?: string;\n /** Span attributes that only the runtime knows, e.g. the route parameters. */\n attributes?: SpanAttributes;\n /**\n * Called in the scope of the continued trace, before the span starts. Lets the runtime continue\n * its own trace, e.g. the trace that Cloudflare exports for the invocation.\n */\n onTraceContinued?: () => void;\n /** Whether the response streams. Return `undefined` to use the default classification. */\n isStreamingResponse?: (response: Response) => boolean | undefined;\n /**\n * Called once when the request is done: when the response is returned, when a streamed body\n * finishes, or when the handler throws (then without a response).\n */\n onDone?: (response: Response | undefined) => void;\n}\n\n/**\n * Wraps a handler of a web `Request`, as used by `Deno.serve`, `Bun.serve` and Cloudflare Workers.\n *\n * It records the request session, attaches the request data and body, continues the incoming\n * trace, creates the `http.server` span, and captures errors that the handler throws. The rules\n * follow core's `node:http` server code:\n *\n * - `OPTIONS` and `HEAD` requests get no span and no body capture.\n * - The static asset filter applies only to `GET`.\n * - The span and the session of a streamed response end when the stream finishes.\n *\n * The handler can return no response, as Bun's `fetch` does after a WebSocket upgrade.\n */\nexport async function wrapServerRequestHandler<R extends Response | undefined = Response>(\n config: ServerRequestHandlerConfig,\n handler: () => R | Promise<R>,\n): Promise<R> {\n const { request, client, isolationScope, options, mechanism } = config;\n\n const method = request.method.toUpperCase();\n const captureError = (error: unknown): void => {\n if (mechanism) {\n captureException(error, { mechanism });\n }\n };\n\n const socketAddress = config.getSocketAddress?.();\n // Without `AsyncLocalStorage`, all requests share one isolation scope, so clear what an earlier\n // request left on it: the merge keeps its body, and its response context would stay set.\n isolationScope.setSDKProcessingMetadata({\n normalizedRequest: { ...winterCGRequestToRequestData(request), data: undefined },\n ipAddress: socketAddress?.address,\n });\n isolationScope.setContext('response', null);\n\n // Tunnel requests get no session, body or span, whether the SDK or the app answers them. The app answers them with\n // `intercept: false`, from its own code, so its errors are still captured.\n if (isServedTunnelRequest(request, client)) {\n let response: R | undefined;\n try {\n response = await handler();\n return response;\n } catch (e) {\n captureError(e);\n throw e;\n } finally {\n config.onDone?.(response);\n }\n }\n\n const endSession = options?.sessions\n ? startRequestSession(client, {\n requestIsolationScope: isolationScope,\n sessionFlushingDelayMS: options.sessionFlushingDelayMS,\n })\n : undefined;\n const finish = (response: Response | undefined): void => {\n endSession?.();\n config.onDone?.(response);\n };\n const isStreamingResponse = (response: Response): boolean => {\n const classification = config.isStreamingResponse?.(response);\n return typeof classification === 'boolean' ? classification : classifyResponseStreaming(response).isStreaming;\n };\n\n if (method === 'OPTIONS' || method === 'HEAD') {\n let response: R | undefined;\n try {\n response = await handler();\n return response;\n } catch (e) {\n captureError(e);\n throw e;\n } finally {\n finish(response);\n }\n }\n\n const dataCollection = client.getDataCollectionOptions();\n const effectiveBodySize =\n options?.maxRequestBodySize ?? (dataCollection.httpBodies.includes('incomingRequest') ? 'medium' : 'none');\n const ignoreRequestBody = options?.ignoreRequestBody;\n if (\n method !== 'GET' &&\n effectiveBodySize !== 'none' &&\n // If the filter throws, skip the body so it cannot leak data the filter was meant to hide.\n !(\n ignoreRequestBody &&\n safeCallback(\n DEBUG_BUILD ? 'Error in `ignoreRequestBody`, skipping the body:' : '',\n () => ignoreRequestBody(request.url, request),\n () => true,\n )\n )\n ) {\n await captureBodyFromWinterCGRequest(request, isolationScope, effectiveBodySize);\n }\n\n const urlObject = parseStringToURLObject(request.url);\n const urlPath = urlObject ? `${urlObject.pathname}${urlObject.search}` : '/';\n const createSpan = shouldCreateSpan(client, options, request, urlPath);\n\n return continueTrace(\n {\n sentryTrace: request.headers.get('sentry-trace') || '',\n baggage: request.headers.get('baggage'),\n },\n async () => {\n config.onTraceContinued?.();\n\n if (!createSpan) {\n let response: R;\n try {\n response = await handler();\n } catch (e) {\n captureError(e);\n finish(undefined);\n throw e;\n }\n if (response) {\n isolationScope.setContext('response', { status_code: response.status });\n }\n const inRequestScope = bindToRequestScope(isolationScope);\n return onResponseDone(\n response,\n !!response && isStreamingResponse(response),\n inRequestScope(() => finish(response)),\n inRequestScope(captureError),\n );\n }\n\n const [rawName, attributes] = getHttpSpanDetailsFromUrlObject(\n urlObject,\n 'server',\n config.origin,\n request,\n config.routeName,\n client,\n );\n // With span streaming, span names have to be low cardinality, so we can't fall back to the URL.\n // A `route` source means the name already is (e.g. the `/` path), so it is kept as-is.\n const name =\n attributes[SENTRY_SEGMENT_NAME_SOURCE] === 'route' || !hasSpanStreamingEnabled(client)\n ? rawName\n : method || HTTP_SPAN_NAME_FALLBACK;\n\n const contentLength = request.headers.get('content-length');\n if (contentLength) {\n attributes[HTTP_REQUEST_BODY_SIZE] = parseInt(contentLength, 10);\n }\n const userAgent = request.headers.get('user-agent');\n if (userAgent) {\n attributes[USER_AGENT_ORIGINAL] = userAgent;\n }\n\n const headers = winterCGHeadersToDict(request.headers);\n if (dataCollection.userInfo) {\n // `client.address` is the originating client, so a forwarding header wins over the socket, which\n // behind a proxy holds the proxy's address. The socket port is the proxy's too, so `client.port`\n // stays unset then.\n const forwardedAddress = getClientIPAddress(headers);\n if (forwardedAddress) {\n attributes[CLIENT_ADDRESS] = forwardedAddress;\n } else if (socketAddress) {\n attributes[CLIENT_ADDRESS] = socketAddress.address;\n if (socketAddress.port !== undefined) {\n attributes[CLIENT_PORT] = socketAddress.port;\n }\n }\n }\n\n // describes the OSI application-layer protocol (http), not the scheme (might be https)\n attributes[NETWORK_PROTOCOL_NAME] = 'http';\n Object.assign(attributes, httpHeadersToSpanAttributes(headers, dataCollection));\n Object.assign(attributes, config.attributes);\n attributes[SENTRY_OP] = HTTP_SERVER;\n attributes[SENTRY_KIND] = 'server';\n\n return startSpanManual({ name, attributes }, async span => {\n const { onSpanCreated, onSpanEnd } = options ?? {};\n if (onSpanCreated) {\n safeCallback(\n DEBUG_BUILD ? 'Error in `onSpanCreated`:' : '',\n () => onSpanCreated(span, request),\n () => undefined,\n );\n }\n\n let response: R;\n try {\n response = await handler();\n } catch (e) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n span.end();\n captureError(e);\n finish(undefined);\n throw e;\n }\n\n if (response) {\n setHttpStatus(span, response.status);\n isolationScope.setContext('response', { status_code: response.status });\n span.setAttributes(\n httpHeadersToSpanAttributes(responseHeadersToDict(response.headers), dataCollection, 'response'),\n );\n }\n\n const inRequestScope = bindToRequestScope(isolationScope);\n return onResponseDone(\n response,\n !!response && isStreamingResponse(response),\n inRequestScope(() => {\n if (onSpanEnd && response) {\n safeCallback(\n DEBUG_BUILD ? 'Error in `onSpanEnd`:' : '',\n () => onSpanEnd(span, request, response),\n () => undefined,\n );\n }\n span.end();\n finish(response);\n }),\n inRequestScope((error: unknown) => {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n captureError(error);\n }),\n );\n });\n },\n );\n}\n\n/**\n * Returns a function that binds a callback to the request's isolation scope and the current scope.\n *\n * A streamed body finishes after the handler returns. Without `AsyncLocalStorage` (Cloudflare\n * Workers without `nodejs_compat`), its callbacks then run outside the request's scopes, where\n * `getClient()` finds no client: the segment span would be sent as a transaction, and a captured\n * error would not update the request session.\n */\nfunction bindToRequestScope(\n isolationScope: Scope,\n): <A extends unknown[]>(fn: (...args: A) => void) => (...args: A) => void {\n const scope = getCurrentScope();\n return fn =>\n (...args) =>\n withIsolationScope(isolationScope, () => withScope(scope, () => fn(...args)));\n}\n\nfunction shouldCreateSpan(\n client: Client,\n options: ServerRequestOptions<Request, Response> | undefined,\n request: Request,\n urlPath: string,\n): boolean {\n if (!(options?.spans ?? hasSpansEnabled(client.getOptions()))) {\n return false;\n }\n if (options?.ignoreStaticAssets && request.method.toUpperCase() === 'GET' && isStaticAssetRequest(urlPath)) {\n return false;\n }\n const ignoreIncomingRequests = options?.ignoreIncomingRequests;\n return !(\n ignoreIncomingRequests &&\n safeCallback(\n DEBUG_BUILD ? 'Error in `ignoreIncomingRequests`, creating the span:' : '',\n () => ignoreIncomingRequests(urlPath, request),\n () => false,\n )\n );\n}\n\n/**\n * Calls `onDone` when the response is done: at once, or when a streamed body finishes.\n * Returns the response to send.\n */\nfunction onResponseDone<R extends Response | undefined>(\n response: R,\n isStreaming: boolean,\n onDone: () => void,\n onStreamError: (error: unknown) => void,\n): R {\n if (isStreaming && response?.body && !response.body.locked) {\n try {\n // Passing the original response as the init keeps its status, status text and headers, and\n // on Cloudflare also `encodeBody: 'manual'`, so workerd does not compress a compressed body again.\n return new Response(monitorStream(response.body, onDone, onStreamError), response) as R;\n } catch {\n // Workers with a compatibility date before 2022-11-30 and without the\n // `streams_enable_constructors` flag cannot construct a `ReadableStream`, so end at once.\n }\n }\n onDone();\n return response;\n}\n\n// `Headers.forEach` lists each `Set-Cookie` header on its own, so a plain dict keeps only the last one.\nfunction responseHeadersToDict(headers: Headers): Record<string, string | string[]> {\n const dict: Record<string, string | string[]> = winterCGHeadersToDict(headers);\n const setCookie = typeof headers.getSetCookie === 'function' ? headers.getSetCookie() : [];\n if (setCookie.length) {\n dict['set-cookie'] = setCookie;\n }\n return dict;\n}\n"],"mappings":";;;;;;;;;;;;;;AAUA,SAAgB,cACd,QACA,QACA,SAC4B;CAC5B,IAAI;CACJ,IAAI,WAAW;CACf,MAAM,UAAU,UAAqC;EACnD,IAAI,UACF;EAEF,WAAW;EAEX,IAAI;GAGF,IAAI,SAAS,GAAA,GAAEA,aAAAA,QAAAA,CAAQ,MAAM,KAAK,KAAK,MAAM,MAAM,SAAS,eAC1D,QAAQ,MAAM,KAAK;GAErB,OAAO;EACT,SAAS,GAAG;GACVC,oBAAAA,eAAeC,aAAAA,MAAM,MAAM,2CAA2C,CAAC;EACzE;CACF;CAEA,OAAO,IAAI,eACT;EAEE,QAAQ;GACN,SAAS,OAAO,UAAU;GAGrB,OAAO,OAAO,WACX,OAAO,IACb,UAAS,OAAO,EAAE,MAAM,CAAC,CAC3B;EAC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AAC,CAAC;AAClF;AAEA,SAAS,iBACP,QACA,SACA,SACA,SACS;CACT,IAAI,EAAE,SAAS,UAAA,GAASC,aAAAA,gBAAAA,CAAgB,OAAO,WAAW,CAAC,IACzD,OAAO;CAET,IAAI,SAAS,sBAAsB,QAAQ,OAAO,YAAY,MAAM,UAAA,GAASC,oBAAAA,qBAAAA,CAAqB,OAAO,GACvG,OAAO;CAET,MAAM,yBAAyB,SAAS;CACxC,OAAO,EACL,2BAAA,GACA3B,aAAAA,aAAAA,CACEC,oBAAAA,cAAc,0DAA0D,UAClE,uBAAuB,SAAS,OAAO,SACvC,KACR;AAEJ;;;;;AAMA,SAAS,eACP,UACA,aACA,QACA,eACG;CACH,IAAI,eAAe,UAAU,QAAQ,CAAC,SAAS,KAAK,QAClD,IAAI;EAGF,OAAO,IAAI,SAAS,cAAc,SAAS,MAAM,QAAQ,aAAa,GAAG,QAAQ;CACnF,QAAQ,CAGR;CAEF,OAAO;CACP,OAAO;AACT;AAGA,SAAS,sBAAsB,SAAqD;CAClF,MAAM,QAAA,GAA0CU,aAAAA,sBAAAA,CAAsB,OAAO;CAC7E,MAAM,YAAY,OAAO,QAAQ,iBAAiB,aAAa,QAAQ,aAAa,IAAI,CAAC;CACzF,IAAI,UAAU,QACZ,KAAK,gBAAgB;CAEvB,OAAO;AACT"}
|
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
import { GEN_AI_REQUEST_STREAM_ATTRIBUTE } from "../core/gen-ai-attributes.js";
|
|
2
|
-
import {
|
|
2
|
+
import { runGenAiSpanEnd, runGenAiSpanStart } from "../core/span-hooks.js";
|
|
3
|
+
import { getErrorStatus, getGenAiSpanOp, getRequestSignal, resolveGenAiCallRecording, wrapPromiseWithMethods } from "../core/utils.js";
|
|
3
4
|
import { ANTHROPIC_AI_ORIGIN, ANTHROPIC_METHOD_REGISTRY } from "./constants.js";
|
|
4
5
|
import { instrumentAsyncIterableStream, instrumentMessageStream } from "./streaming.js";
|
|
5
6
|
import { instrumentSessionToolRunner, instrumentToolRunner, instrumentToolRunnerFactory } from "./tool-runner.js";
|
|
6
|
-
import { getMessagesAttributes, getProviderName,
|
|
7
|
-
import { GEN_AI_OPERATION_NAME, GEN_AI_PROVIDER_NAME, GEN_AI_REQUEST_FREQUENCY_PENALTY, GEN_AI_REQUEST_MAX_TOKENS, GEN_AI_REQUEST_MODEL, GEN_AI_REQUEST_TEMPERATURE, GEN_AI_REQUEST_TOP_K, GEN_AI_REQUEST_TOP_P,
|
|
7
|
+
import { addResponseAttributes, getMessagesAttributes, getProviderName, messagesFromParams } from "./utils.js";
|
|
8
|
+
import { GEN_AI_OPERATION_NAME, GEN_AI_PROVIDER_NAME, GEN_AI_REQUEST_FREQUENCY_PENALTY, GEN_AI_REQUEST_MAX_TOKENS, GEN_AI_REQUEST_MODEL, GEN_AI_REQUEST_TEMPERATURE, GEN_AI_REQUEST_TOP_K, GEN_AI_REQUEST_TOP_P, GEN_AI_TOOL_DEFINITIONS, SENTRY_ORIGIN } from "@sentry/conventions/attributes";
|
|
8
9
|
import { getClient, hasSpanStreamingEnabled, startSpan, startSpanManual } from "@sentry/core";
|
|
9
10
|
// src/ai/anthropic-ai/index.ts
|
|
10
11
|
let suppressDelegatedCreate = false;
|
|
@@ -40,49 +41,12 @@ function addPrivateRequestAttributes(span, params) {
|
|
|
40
41
|
span.setAttributes(getMessagesAttributes(messages));
|
|
41
42
|
}
|
|
42
43
|
/**
|
|
43
|
-
* Add content attributes when recordOutputs is enabled
|
|
44
|
-
*/
|
|
45
|
-
function addContentAttributes(span, response) {
|
|
46
|
-
if ("content" in response) {
|
|
47
|
-
if (Array.isArray(response.content)) {
|
|
48
|
-
span.setAttributes({ [GEN_AI_RESPONSE_TEXT]: response.content.map((item) => item.text).filter((text) => !!text).join("") });
|
|
49
|
-
const toolCalls = [];
|
|
50
|
-
for (const item of response.content) if (item.type === "tool_use" || item.type === "server_tool_use") toolCalls.push(item);
|
|
51
|
-
if (toolCalls.length > 0) span.setAttributes({ [GEN_AI_RESPONSE_TOOL_CALLS]: JSON.stringify(toolCalls) });
|
|
52
|
-
}
|
|
53
|
-
}
|
|
54
|
-
if ("completion" in response) span.setAttributes({ [GEN_AI_RESPONSE_TEXT]: response.completion });
|
|
55
|
-
}
|
|
56
|
-
/**
|
|
57
|
-
* Add basic metadata attributes from the response
|
|
58
|
-
*/
|
|
59
|
-
function addMetadataAttributes(span, response) {
|
|
60
|
-
if ("id" in response && "model" in response) {
|
|
61
|
-
span.setAttributes({
|
|
62
|
-
[GEN_AI_RESPONSE_ID]: response.id,
|
|
63
|
-
[GEN_AI_RESPONSE_MODEL]: response.model
|
|
64
|
-
});
|
|
65
|
-
if ("usage" in response && response.usage) span.setAttributes(getTokenUsageAttributes(response.usage.input_tokens + (response.usage.cache_creation_input_tokens ?? 0) + (response.usage.cache_read_input_tokens ?? 0), response.usage.output_tokens, response.usage.cache_creation_input_tokens, response.usage.cache_read_input_tokens));
|
|
66
|
-
}
|
|
67
|
-
}
|
|
68
|
-
/**
|
|
69
|
-
* Add response attributes to spans
|
|
70
|
-
*/
|
|
71
|
-
function addResponseAttributes(span, response, recordOutputs) {
|
|
72
|
-
if (!response || typeof response !== "object") return;
|
|
73
|
-
if ("type" in response && response.type === "error") {
|
|
74
|
-
handleResponseError(span, response);
|
|
75
|
-
return;
|
|
76
|
-
}
|
|
77
|
-
if (recordOutputs) addContentAttributes(span, response);
|
|
78
|
-
addMetadataAttributes(span, response);
|
|
79
|
-
}
|
|
80
|
-
/**
|
|
81
44
|
* Handle common error catching and reporting for streaming requests
|
|
82
45
|
*/
|
|
83
|
-
function handleStreamingError(error, span, abortSignal) {
|
|
46
|
+
function handleStreamingError(error, span, abortSignal, onSpanEnd) {
|
|
84
47
|
if (span.isRecording()) {
|
|
85
48
|
span.setStatus(getErrorStatus(abortSignal));
|
|
49
|
+
onSpanEnd({ error });
|
|
86
50
|
span.end();
|
|
87
51
|
}
|
|
88
52
|
throw error;
|
|
@@ -90,33 +54,37 @@ function handleStreamingError(error, span, abortSignal) {
|
|
|
90
54
|
/**
|
|
91
55
|
* Handle streaming cases with common logic
|
|
92
56
|
*/
|
|
93
|
-
function handleStreamingRequest(target, invocationThis, args, spanConfig, params,
|
|
57
|
+
function handleStreamingRequest(target, invocationThis, args, spanConfig, params, { recordInputs, recordOutputs }, isStreamRequested, isStreamingMethod, options, call) {
|
|
94
58
|
const abortSignal = getRequestSignal(args[1]);
|
|
95
59
|
if (isStreamRequested && !isStreamingMethod) {
|
|
96
60
|
let originalResult;
|
|
97
61
|
const instrumentedPromise = startSpanManual(spanConfig, (span) => {
|
|
98
62
|
originalResult = target.apply(invocationThis, args);
|
|
99
|
-
if (
|
|
63
|
+
if (recordInputs && params) addPrivateRequestAttributes(span, params);
|
|
64
|
+
runGenAiSpanStart(options, span, call);
|
|
65
|
+
const onSpanEnd = (result) => runGenAiSpanEnd(options, span, call, result);
|
|
100
66
|
return (async () => {
|
|
101
67
|
try {
|
|
102
68
|
const result = await originalResult;
|
|
103
|
-
return instrumentAsyncIterableStream(result, span,
|
|
69
|
+
return instrumentAsyncIterableStream(result, span, recordOutputs, onSpanEnd);
|
|
104
70
|
} catch (error) {
|
|
105
|
-
return handleStreamingError(error, span, abortSignal);
|
|
71
|
+
return handleStreamingError(error, span, abortSignal, onSpanEnd);
|
|
106
72
|
}
|
|
107
73
|
})();
|
|
108
74
|
});
|
|
109
75
|
return wrapPromiseWithMethods(originalResult, instrumentedPromise);
|
|
110
76
|
} else return startSpanManual(spanConfig, (span) => {
|
|
77
|
+
const onSpanEnd = (result) => runGenAiSpanEnd(options, span, call, result);
|
|
111
78
|
try {
|
|
112
|
-
if (
|
|
79
|
+
if (recordInputs && params) addPrivateRequestAttributes(span, params);
|
|
80
|
+
runGenAiSpanStart(options, span, call);
|
|
113
81
|
suppressDelegatedCreate = true;
|
|
114
82
|
const messageStream = target.apply(invocationThis, args);
|
|
115
83
|
suppressDelegatedCreate = false;
|
|
116
|
-
return instrumentMessageStream(messageStream, span,
|
|
84
|
+
return instrumentMessageStream(messageStream, span, recordOutputs, abortSignal, onSpanEnd);
|
|
117
85
|
} catch (error) {
|
|
118
86
|
suppressDelegatedCreate = false;
|
|
119
|
-
return handleStreamingError(error, span, abortSignal);
|
|
87
|
+
return handleStreamingError(error, span, abortSignal, onSpanEnd);
|
|
120
88
|
}
|
|
121
89
|
});
|
|
122
90
|
}
|
|
@@ -131,7 +99,13 @@ function instrumentMethod(originalMethod, methodPath, instrumentedMethod, contex
|
|
|
131
99
|
const isStreamingMethod = instrumentedMethod.streaming === true;
|
|
132
100
|
if (!isStreamingMethod && suppressDelegatedCreate) return target.apply(invocationThis, args);
|
|
133
101
|
const operationName = instrumentedMethod.operation || "unknown";
|
|
134
|
-
const
|
|
102
|
+
const params = typeof args[0] === "object" && args[0] !== null ? args[0] : void 0;
|
|
103
|
+
const call = {
|
|
104
|
+
operation: "chat",
|
|
105
|
+
request: params
|
|
106
|
+
};
|
|
107
|
+
const recording = resolveGenAiCallRecording(options, call);
|
|
108
|
+
const requestAttributes = extractRequestAttributes(args, operationName, recording.recordInputs, getProviderName(invocationThis));
|
|
135
109
|
const model = requestAttributes[GEN_AI_REQUEST_MODEL] || "unknown";
|
|
136
110
|
const client = getClient();
|
|
137
111
|
const spanConfig = {
|
|
@@ -139,19 +113,21 @@ function instrumentMethod(originalMethod, methodPath, instrumentedMethod, contex
|
|
|
139
113
|
op: getGenAiSpanOp(operationName),
|
|
140
114
|
attributes: requestAttributes
|
|
141
115
|
};
|
|
142
|
-
const params = typeof args[0] === "object" ? args[0] : void 0;
|
|
143
116
|
const isStreamRequested = Boolean(params?.stream);
|
|
144
|
-
if (isStreamRequested || isStreamingMethod) return handleStreamingRequest(target, invocationThis, args, spanConfig, params,
|
|
117
|
+
if (isStreamRequested || isStreamingMethod) return handleStreamingRequest(target, invocationThis, args, spanConfig, params, recording, isStreamRequested, isStreamingMethod, options, call);
|
|
145
118
|
const abortSignal = getRequestSignal(args[1]);
|
|
146
119
|
let originalResult;
|
|
147
120
|
const instrumentedPromise = startSpan(spanConfig, (span) => {
|
|
148
121
|
originalResult = target.apply(invocationThis, args);
|
|
149
|
-
if (
|
|
122
|
+
if (recording.recordInputs && params) addPrivateRequestAttributes(span, params);
|
|
123
|
+
runGenAiSpanStart(options, span, call);
|
|
150
124
|
return originalResult.then((result) => {
|
|
151
|
-
addResponseAttributes(span, result,
|
|
125
|
+
addResponseAttributes(span, result, recording.recordOutputs);
|
|
126
|
+
runGenAiSpanEnd(options, span, call, { response: result });
|
|
152
127
|
return result;
|
|
153
128
|
}, (error) => {
|
|
154
129
|
span.setStatus(getErrorStatus(abortSignal));
|
|
130
|
+
runGenAiSpanEnd(options, span, call, { error });
|
|
155
131
|
throw error;
|
|
156
132
|
});
|
|
157
133
|
});
|
|
@@ -197,8 +173,8 @@ function instrumentClientInPlace(client, options) {
|
|
|
197
173
|
* @returns The instrumented client with the same type as the input
|
|
198
174
|
*/
|
|
199
175
|
function instrumentAnthropicAiClient(anthropicAiClient, options) {
|
|
200
|
-
return instrumentClientInPlace(anthropicAiClient,
|
|
176
|
+
return instrumentClientInPlace(anthropicAiClient, options ?? {});
|
|
201
177
|
}
|
|
202
|
-
export { addPrivateRequestAttributes,
|
|
178
|
+
export { addPrivateRequestAttributes, extractRequestAttributes, instrumentAnthropicAiClient };
|
|
203
179
|
|
|
204
180
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../../../src/ai/anthropic-ai/index.ts"],"sourcesContent":["/* eslint-disable typescript-eslint/no-deprecated */\nimport { getClient, hasSpanStreamingEnabled, startSpan, startSpanManual } from '@sentry/core';\nimport type { Span, SpanAttributeValue } from '@sentry/core';\nimport {\n GEN_AI_OPERATION_NAME,\n GEN_AI_PROVIDER_NAME,\n GEN_AI_REQUEST_FREQUENCY_PENALTY,\n GEN_AI_REQUEST_MAX_TOKENS,\n GEN_AI_REQUEST_MODEL,\n GEN_AI_REQUEST_TEMPERATURE,\n GEN_AI_REQUEST_TOP_K,\n GEN_AI_REQUEST_TOP_P,\n GEN_AI_RESPONSE_ID,\n GEN_AI_RESPONSE_MODEL,\n GEN_AI_RESPONSE_TEXT,\n GEN_AI_RESPONSE_TOOL_CALLS,\n GEN_AI_TOOL_DEFINITIONS,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { GEN_AI_REQUEST_STREAM_ATTRIBUTE } from '../core/gen-ai-attributes';\nimport type { InstrumentedMethodEntry } from '../core/utils';\nimport {\n getErrorStatus,\n getGenAiSpanOp,\n getRequestSignal,\n getTokenUsageAttributes,\n resolveAIRecordingOptions,\n wrapPromiseWithMethods,\n} from '../core/utils';\nimport { ANTHROPIC_AI_ORIGIN, ANTHROPIC_METHOD_REGISTRY } from './constants';\nimport { instrumentAsyncIterableStream, instrumentMessageStream } from './streaming';\nimport { instrumentSessionToolRunner, instrumentToolRunner, instrumentToolRunnerFactory } from './tool-runner';\nimport type { AnthropicAiOptions, AnthropicAiResponse, AnthropicAiStreamingEvent, ContentBlock } from './types';\nimport { getMessagesAttributes, getProviderName, handleResponseError, messagesFromParams } from './utils';\n\n// Set only while a streaming helper (e.g. `messages.stream()`) synchronously delegates to the\n// underlying `create`. The SDK invokes that internal `create` synchronously, so a plain flag\n// suppresses exactly the duplicate delegation and nothing else: a `create` made later from a\n// stream event handler runs in a separate async continuation with the flag already cleared.\nlet suppressDelegatedCreate = false;\n\n// Methods that have already been wrapped, so instrumenting the same client twice is a no-op.\nconst INSTRUMENTED_METHODS = new WeakSet<object>();\n\n/**\n * Extract request attributes from method arguments\n */\nexport function extractRequestAttributes(\n args: unknown[],\n operationName: string,\n recordInputs: boolean,\n providerName = 'anthropic',\n): Record<string, unknown> {\n const attributes: Record<string, unknown> = {\n [GEN_AI_PROVIDER_NAME]: providerName,\n [GEN_AI_OPERATION_NAME]: operationName,\n [SENTRY_ORIGIN]: ANTHROPIC_AI_ORIGIN,\n };\n\n if (args.length > 0 && typeof args[0] === 'object' && args[0] !== null) {\n const params = args[0] as Record<string, unknown>;\n if (recordInputs && params.tools && Array.isArray(params.tools)) {\n attributes[GEN_AI_TOOL_DEFINITIONS] = JSON.stringify(params.tools);\n }\n\n attributes[GEN_AI_REQUEST_MODEL] = params.model ?? 'unknown';\n if ('temperature' in params) attributes[GEN_AI_REQUEST_TEMPERATURE] = params.temperature;\n if ('top_p' in params) attributes[GEN_AI_REQUEST_TOP_P] = params.top_p;\n if ('stream' in params) attributes[GEN_AI_REQUEST_STREAM_ATTRIBUTE] = params.stream;\n if ('top_k' in params) attributes[GEN_AI_REQUEST_TOP_K] = params.top_k;\n if ('frequency_penalty' in params) attributes[GEN_AI_REQUEST_FREQUENCY_PENALTY] = params.frequency_penalty;\n if ('max_tokens' in params) attributes[GEN_AI_REQUEST_MAX_TOKENS] = params.max_tokens;\n } else {\n attributes[GEN_AI_REQUEST_MODEL] = 'unknown';\n }\n\n return attributes;\n}\n\n/**\n * Add private request attributes to spans.\n * This is only recorded if recordInputs is true.\n */\nexport function addPrivateRequestAttributes(span: Span, params: Record<string, unknown>): void {\n const messages = messagesFromParams(params);\n span.setAttributes(getMessagesAttributes(messages));\n}\n\n/**\n * Add content attributes when recordOutputs is enabled\n */\nfunction addContentAttributes(span: Span, response: AnthropicAiResponse): void {\n // Messages.create\n if ('content' in response) {\n if (Array.isArray(response.content)) {\n span.setAttributes({\n [GEN_AI_RESPONSE_TEXT]: response.content\n .map((item: ContentBlock) => item.text)\n .filter(text => !!text)\n .join(''),\n });\n\n const toolCalls: Array<ContentBlock> = [];\n\n for (const item of response.content) {\n if (item.type === 'tool_use' || item.type === 'server_tool_use') {\n toolCalls.push(item);\n }\n }\n if (toolCalls.length > 0) {\n span.setAttributes({ [GEN_AI_RESPONSE_TOOL_CALLS]: JSON.stringify(toolCalls) });\n }\n }\n }\n // Completions.create\n if ('completion' in response) {\n span.setAttributes({ [GEN_AI_RESPONSE_TEXT]: response.completion });\n }\n}\n\n/**\n * Add basic metadata attributes from the response\n */\nfunction addMetadataAttributes(span: Span, response: AnthropicAiResponse): void {\n if ('id' in response && 'model' in response) {\n span.setAttributes({\n [GEN_AI_RESPONSE_ID]: response.id,\n [GEN_AI_RESPONSE_MODEL]: response.model,\n });\n\n if ('usage' in response && response.usage) {\n span.setAttributes(\n getTokenUsageAttributes(\n response.usage.input_tokens +\n (response.usage.cache_creation_input_tokens ?? 0) +\n (response.usage.cache_read_input_tokens ?? 0),\n response.usage.output_tokens,\n response.usage.cache_creation_input_tokens,\n response.usage.cache_read_input_tokens,\n ),\n );\n }\n }\n}\n\n/**\n * Add response attributes to spans\n */\nexport function addResponseAttributes(span: Span, response: AnthropicAiResponse, recordOutputs?: boolean): void {\n if (!response || typeof response !== 'object') return;\n\n // capture error, do not add attributes if error (they shouldn't exist)\n if ('type' in response && response.type === 'error') {\n handleResponseError(span, response);\n return;\n }\n\n // Private response attributes that are only recorded if recordOutputs is true.\n if (recordOutputs) {\n addContentAttributes(span, response);\n }\n\n // Add basic metadata attributes\n addMetadataAttributes(span, response);\n}\n\n/**\n * Handle common error catching and reporting for streaming requests\n */\nfunction handleStreamingError(error: unknown, span: Span, abortSignal: AbortSignal | undefined): never {\n if (span.isRecording()) {\n span.setStatus(getErrorStatus(abortSignal));\n span.end();\n }\n throw error;\n}\n\n/**\n * Handle streaming cases with common logic\n */\nfunction handleStreamingRequest<T extends unknown[], R>(\n target: (...args: T) => R | Promise<R>,\n invocationThis: unknown,\n args: T,\n spanConfig: { name: string; op: string; attributes: Record<string, SpanAttributeValue> },\n params: Record<string, unknown> | undefined,\n options: AnthropicAiOptions,\n isStreamRequested: boolean,\n isStreamingMethod: boolean,\n): R | Promise<R> {\n const abortSignal = getRequestSignal(args[1]);\n // messages.stream() always returns a sync MessageStream, even with stream: true param\n if (isStreamRequested && !isStreamingMethod) {\n let originalResult!: Promise<R>;\n\n const instrumentedPromise = startSpanManual(spanConfig, (span: Span) => {\n originalResult = target.apply(invocationThis, args) as Promise<R>;\n\n if (options.recordInputs && params) {\n addPrivateRequestAttributes(span, params);\n }\n\n return (async () => {\n try {\n const result = await originalResult;\n return instrumentAsyncIterableStream(\n result as AsyncIterable<AnthropicAiStreamingEvent>,\n span,\n options.recordOutputs ?? false,\n ) as unknown as R;\n } catch (error) {\n return handleStreamingError(error, span, abortSignal);\n }\n })();\n });\n\n return wrapPromiseWithMethods(originalResult, instrumentedPromise);\n } else {\n return startSpanManual(spanConfig, span => {\n try {\n if (options.recordInputs && params) {\n addPrivateRequestAttributes(span, params);\n }\n // The helper synchronously delegates to `create`; suppress that one internal call so it\n // does not produce a duplicate child span (see the dedup gate in `instrumentMethod`).\n suppressDelegatedCreate = true;\n const messageStream = target.apply(invocationThis, args);\n suppressDelegatedCreate = false;\n return instrumentMessageStream(messageStream, span, options.recordOutputs ?? false, abortSignal);\n } catch (error) {\n suppressDelegatedCreate = false;\n return handleStreamingError(error, span, abortSignal);\n }\n });\n }\n}\n\n/**\n * Instrument a method with Sentry spans\n * Following Sentry AI Agents Manual Instrumentation conventions\n * @see https://docs.sentry.io/platforms/javascript/guides/node/tracing/instrumentation/ai-agents-module/#manual-instrumentation\n */\nfunction instrumentMethod<T extends unknown[], R>(\n originalMethod: (...args: T) => R | Promise<R>,\n methodPath: string,\n instrumentedMethod: InstrumentedMethodEntry,\n context: unknown,\n options: AnthropicAiOptions,\n): (...args: T) => R | Promise<R> {\n return new Proxy(originalMethod, {\n apply(target, thisArg, args: T): R | Promise<R> {\n // Preserve the caller's `this` so instrumentation stays transparent: the SDK's methods\n // rely on private fields bound to the real instance, and internal delegation (e.g.\n // `messages.stream()` calling `this.create()`) must resolve against the same object it\n // would on an uninstrumented client. Fall back to the wrap-time owner for unbound calls.\n const invocationThis = thisArg !== undefined ? thisArg : context;\n\n const isStreamingMethod = instrumentedMethod.streaming === true;\n\n // If this is the SDK's internal `create` delegation from a streaming helper (e.g.\n // `messages.stream()` invoking `this.create()`), skip instrumentation: the helper span\n // already represents this operation, so a second span would be a duplicate.\n if (!isStreamingMethod && suppressDelegatedCreate) {\n return target.apply(invocationThis, args);\n }\n\n const operationName = instrumentedMethod.operation || 'unknown';\n const requestAttributes = extractRequestAttributes(\n args,\n operationName,\n !!options.recordInputs,\n getProviderName(invocationThis),\n );\n const model = requestAttributes[GEN_AI_REQUEST_MODEL] || 'unknown';\n const client = getClient();\n // With span streaming, omit the `'unknown'` model sentinel so the name stays low-cardinality.\n const spanConfig = {\n name:\n (typeof model === 'string' && model !== 'unknown') || !(client && hasSpanStreamingEnabled(client))\n ? `${operationName} ${model}`\n : operationName,\n op: getGenAiSpanOp(operationName),\n attributes: requestAttributes as Record<string, SpanAttributeValue>,\n };\n\n const params = typeof args[0] === 'object' ? (args[0] as Record<string, unknown>) : undefined;\n const isStreamRequested = Boolean(params?.stream);\n\n if (isStreamRequested || isStreamingMethod) {\n return handleStreamingRequest(\n target,\n invocationThis,\n args,\n spanConfig,\n params,\n options,\n isStreamRequested,\n isStreamingMethod,\n );\n }\n\n const abortSignal = getRequestSignal(args[1]);\n let originalResult!: Promise<R>;\n\n const instrumentedPromise = startSpan(spanConfig, span => {\n originalResult = target.apply(invocationThis, args) as Promise<R>;\n\n if (options.recordInputs && params) {\n addPrivateRequestAttributes(span, params);\n }\n\n return originalResult.then(\n result => {\n addResponseAttributes(span, result as AnthropicAiResponse, options.recordOutputs);\n return result;\n },\n error => {\n span.setStatus(getErrorStatus(abortSignal));\n throw error;\n },\n );\n });\n\n return wrapPromiseWithMethods(originalResult, instrumentedPromise);\n },\n });\n}\n\n/**\n * Instrument the Anthropic client's methods in place.\n *\n * We deliberately do not wrap the client in a Proxy. The Anthropic SDK relies on private class\n * fields (`this.#field`), which are invisible to a Proxy and throw if a method runs with a\n * proxied `this`. Wrapping the registered methods in place (as own properties shadowing the\n * prototype) keeps `this` bound to the real instance, so instrumentation stays observationally\n * transparent: internal delegation (e.g. `messages.stream()` calling `this.create()`) and\n * `instanceof` checks behave exactly as on an uninstrumented client, and non-instrumented\n * methods are left untouched.\n */\nfunction instrumentClientInPlace<T extends object>(client: T, options: AnthropicAiOptions): T {\n for (const methodPath of Object.keys(ANTHROPIC_METHOD_REGISTRY) as Array<keyof typeof ANTHROPIC_METHOD_REGISTRY>) {\n const segments = methodPath.split('.');\n const methodName = segments.pop() as string;\n\n let owner = client as Record<string, unknown> | undefined;\n for (const segment of segments) {\n owner = owner?.[segment] as Record<string, unknown> | undefined;\n }\n\n if (!owner || typeof owner[methodName] !== 'function') {\n continue;\n }\n\n const originalMethod = owner[methodName] as (...args: unknown[]) => unknown;\n if (INSTRUMENTED_METHODS.has(originalMethod)) {\n continue;\n }\n\n const instrumented = instrumentMethod(\n originalMethod,\n methodPath,\n ANTHROPIC_METHOD_REGISTRY[methodPath],\n owner,\n options,\n );\n INSTRUMENTED_METHODS.add(instrumented);\n owner[methodName] = instrumented;\n }\n\n const beta = (client as { beta?: { messages?: object; sessions?: { events?: object } } }).beta;\n if (beta?.messages) {\n instrumentToolRunnerFactory(beta.messages, instrumentToolRunner, options);\n }\n if (beta?.sessions?.events) {\n instrumentToolRunnerFactory(beta.sessions.events, instrumentSessionToolRunner, options);\n }\n\n return client;\n}\n\n/**\n * Instrument an Anthropic AI client with Sentry tracing\n * Can be used across Node.js, Cloudflare Workers, and Vercel Edge\n *\n * @template T - The type of the client that extends object\n * @param client - The Anthropic AI client to instrument\n * @param options - Optional configuration for recording inputs and outputs\n * @returns The instrumented client with the same type as the input\n */\nexport function instrumentAnthropicAiClient<T extends object>(anthropicAiClient: T, options?: AnthropicAiOptions): T {\n return instrumentClientInPlace(anthropicAiClient, resolveAIRecordingOptions(options));\n}\n"],"mappings":";;;;;;;;;AAuCA,IAAI,0BAA0B;AAG9B,MAAM,uCAAuB,IAAI,QAAgB;;;;AAKjD,SAAgB,yBACd,MACA,eACA,cACA,eAAe,aACU;CACzB,MAAM,aAAsC;GACzC,uBAAuB;GACvB,wBAAwB;GACxB,gBAAgB;CACnB;CAEA,IAAI,KAAK,SAAS,KAAK,OAAO,KAAK,OA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gB,IAAI;GAElD,IAAI,QAAQ,gBAAgB,QAC1B,4BAA4B,MAAM,MAAM;GAG1C,OAAO,eAAe,MACpB,WAAU;IACR,sBAAsB,MAAM,QAA+B,QAAQ,aAAa;IAChF,OAAO;GACT,IACA,UAAS;IACP,KAAK,UAAU,eAAe,WAAW,CAAC;IAC1C,MAAM;GACR,CACF;EACF,CAAC;EAED,OAAO,uBAAuB,gBAAgB,mBAAmB;CACnE,EACF,CAAC;AACH;;;;;;;;;;;;AAaA,SAAS,wBAA0C,QAAW,SAAgC;CAC5F,KAAK,MAAM,cAAc,OAAO,KAAK,yBAAyB,GAAoD;EAChH,MAAM,WAAW,WAAW,MAAM,GAAG;EACrC,MAAM,aAAa,SAAS,IAAI;EAEhC,IAAI,QAAQ;EACZ,KAAK,MAAM,WAAW,UACpB,QAAQ,QAAQ;EAGlB,IAAI,CAAC,SAAS,OAAO,MAAM,gBAAgB,YACzC;EAGF,MAAM,iBAAiB,MAAM;EAC7B,IAAI,qBAAqB,IAAI,cAAc,GACzC;EAGF,MAAM,eAAe,iBACnB,gBACA,YACA,0BAA0B,aAC1B,OACA,OACF;EACA,qBAAqB,IAAI,YAAY;EACrC,MAAM,cAAc;CACtB;CAEA,MAAM,OAAQ,OAA4E;CAC1F,IAAI,MAAM,UACR,4BAA4B,KAAK,UAAU,sBAAsB,OAAO;CAE1E,IAAI,MAAM,UAAU,QAClB,4BAA4B,KAAK,SAAS,QAAQ,6BAA6B,OAAO;CAGxF,OAAO;AACT;;;;;;;;;;AAWA,SAAgB,4BAA8C,mBAAsB,SAAiC;CACnH,OAAO,wBAAwB,mBAAmB,0BAA0B,OAAO,CAAC;AACtF"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../../../src/ai/anthropic-ai/index.ts"],"sourcesContent":["import { getClient, hasSpanStreamingEnabled, startSpan, startSpanManual } from '@sentry/core';\nimport type { Span, SpanAttributeValue } from '@sentry/core';\nimport {\n GEN_AI_OPERATION_NAME,\n GEN_AI_PROVIDER_NAME,\n GEN_AI_REQUEST_FREQUENCY_PENALTY,\n GEN_AI_REQUEST_MAX_TOKENS,\n GEN_AI_REQUEST_MODEL,\n GEN_AI_REQUEST_TEMPERATURE,\n GEN_AI_REQUEST_TOP_K,\n GEN_AI_REQUEST_TOP_P,\n GEN_AI_TOOL_DEFINITIONS,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { GEN_AI_REQUEST_STREAM_ATTRIBUTE } from '../core/gen-ai-attributes';\nimport { type GenAiSpanResult, runGenAiSpanEnd, runGenAiSpanStart } from '../core/span-hooks';\nimport type { GenAiOptions, InstrumentedMethodEntry } from '../core/utils';\nimport {\n getErrorStatus,\n getGenAiSpanOp,\n getRequestSignal,\n resolveGenAiCallRecording,\n wrapPromiseWithMethods,\n} from '../core/utils';\nimport { ANTHROPIC_AI_ORIGIN, ANTHROPIC_METHOD_REGISTRY } from './constants';\nimport { instrumentAsyncIterableStream, instrumentMessageStream } from './streaming';\nimport { instrumentSessionToolRunner, instrumentToolRunner, instrumentToolRunnerFactory } from './tool-runner';\nimport type { AnthropicAiCallInfo, AnthropicAiOptions, AnthropicAiResponse, AnthropicAiStreamingEvent } from './types';\nimport { addResponseAttributes, getMessagesAttributes, getProviderName, messagesFromParams } from './utils';\n\n// Set only while a streaming helper (e.g. `messages.stream()`) synchronously delegates to the\n// underlying `create`. The SDK invokes that internal `create` synchronously, so a plain flag\n// suppresses exactly the duplicate delegation and nothing else: a `create` made later from a\n// stream event handler runs in a separate async continuation with the flag already cleared.\nlet suppressDelegatedCreate = false;\n\n// Methods that have already been wrapped, so instrumenting the same client twice is a no-op.\nconst INSTRUMENTED_METHODS = new WeakSet<object>();\n\n/**\n * Extract request attributes from method arguments\n */\nexport function extractRequestAttributes(\n args: unknown[],\n operationName: string,\n recordInputs: boolean,\n providerName = 'anthropic',\n): Record<string, unknown> {\n const attributes: Record<string, unknown> = {\n [GEN_AI_PROVIDER_NAME]: providerName,\n [GEN_AI_OPERATION_NAME]: operationName,\n [SENTRY_ORIGIN]: ANTHROPIC_AI_ORIGIN,\n };\n\n if (args.length > 0 && typeof args[0] === 'object' && args[0] !== null) {\n const params = args[0] as Record<string, unknown>;\n if (recordInputs && params.tools && Array.isArray(params.tools)) {\n attributes[GEN_AI_TOOL_DEFINITIONS] = JSON.stringify(params.tools);\n }\n\n attributes[GEN_AI_REQUEST_MODEL] = params.model ?? 'unknown';\n if ('temperature' in params) attributes[GEN_AI_REQUEST_TEMPERATURE] = params.temperature;\n if ('top_p' in params) attributes[GEN_AI_REQUEST_TOP_P] = params.top_p;\n if ('stream' in params) attributes[GEN_AI_REQUEST_STREAM_ATTRIBUTE] = params.stream;\n if ('top_k' in params) attributes[GEN_AI_REQUEST_TOP_K] = params.top_k;\n if ('frequency_penalty' in params) attributes[GEN_AI_REQUEST_FREQUENCY_PENALTY] = params.frequency_penalty;\n if ('max_tokens' in params) attributes[GEN_AI_REQUEST_MAX_TOKENS] = params.max_tokens;\n } else {\n attributes[GEN_AI_REQUEST_MODEL] = 'unknown';\n }\n\n return attributes;\n}\n\n/**\n * Add private request attributes to spans.\n * This is only recorded if recordInputs is true.\n */\nexport function addPrivateRequestAttributes(span: Span, params: Record<string, unknown>): void {\n const messages = messagesFromParams(params);\n span.setAttributes(getMessagesAttributes(messages));\n}\n\n/**\n * Handle common error catching and reporting for streaming requests\n */\nfunction handleStreamingError(\n error: unknown,\n span: Span,\n abortSignal: AbortSignal | undefined,\n onSpanEnd: (result: GenAiSpanResult<unknown>) => void,\n): never {\n if (span.isRecording()) {\n span.setStatus(getErrorStatus(abortSignal));\n onSpanEnd({ error });\n span.end();\n }\n throw error;\n}\n\n/**\n * Handle streaming cases with common logic\n */\nfunction handleStreamingRequest<T extends unknown[], R>(\n target: (...args: T) => R | Promise<R>,\n invocationThis: unknown,\n args: T,\n spanConfig: { name: string; op: string; attributes: Record<string, SpanAttributeValue> },\n params: Record<string, unknown> | undefined,\n { recordInputs, recordOutputs }: Required<GenAiOptions>,\n isStreamRequested: boolean,\n isStreamingMethod: boolean,\n options: AnthropicAiOptions,\n call: AnthropicAiCallInfo,\n): R | Promise<R> {\n const abortSignal = getRequestSignal(args[1]);\n // messages.stream() always returns a sync MessageStream, even with stream: true param\n if (isStreamRequested && !isStreamingMethod) {\n let originalResult!: Promise<R>;\n\n const instrumentedPromise = startSpanManual(spanConfig, (span: Span) => {\n originalResult = target.apply(invocationThis, args) as Promise<R>;\n\n if (recordInputs && params) {\n addPrivateRequestAttributes(span, params);\n }\n runGenAiSpanStart(options, span, call);\n const onSpanEnd = (result: GenAiSpanResult<unknown>): void => runGenAiSpanEnd(options, span, call, result);\n\n return (async () => {\n try {\n const result = await originalResult;\n return instrumentAsyncIterableStream(\n result as AsyncIterable<AnthropicAiStreamingEvent>,\n span,\n recordOutputs,\n onSpanEnd,\n ) as unknown as R;\n } catch (error) {\n return handleStreamingError(error, span, abortSignal, onSpanEnd);\n }\n })();\n });\n\n return wrapPromiseWithMethods(originalResult, instrumentedPromise);\n } else {\n return startSpanManual(spanConfig, span => {\n const onSpanEnd = (result: GenAiSpanResult<unknown>): void => runGenAiSpanEnd(options, span, call, result);\n try {\n if (recordInputs && params) {\n addPrivateRequestAttributes(span, params);\n }\n runGenAiSpanStart(options, span, call);\n // The helper synchronously delegates to `create`; suppress that one internal call so it\n // does not produce a duplicate child span (see the dedup gate in `instrumentMethod`).\n suppressDelegatedCreate = true;\n const messageStream = target.apply(invocationThis, args);\n suppressDelegatedCreate = false;\n return instrumentMessageStream(messageStream, span, recordOutputs, abortSignal, onSpanEnd);\n } catch (error) {\n suppressDelegatedCreate = false;\n return handleStreamingError(error, span, abortSignal, onSpanEnd);\n }\n });\n }\n}\n\n/**\n * Instrument a method with Sentry spans\n * Following Sentry AI Agents Manual Instrumentation conventions\n * @see https://docs.sentry.io/platforms/javascript/guides/node/tracing/instrumentation/ai-agents-module/#manual-instrumentation\n */\nfunction instrumentMethod<T extends unknown[], R>(\n originalMethod: (...args: T) => R | Promise<R>,\n methodPath: string,\n instrumentedMethod: InstrumentedMethodEntry,\n context: unknown,\n options: AnthropicAiOptions,\n): (...args: T) => R | Promise<R> {\n return new Proxy(originalMethod, {\n apply(target, thisArg, args: T): R | Promise<R> {\n // Preserve the caller's `this` so instrumentation stays transparent: the SDK's methods\n // rely on private fields bound to the real instance, and internal delegation (e.g.\n // `messages.stream()` calling `this.create()`) must resolve against the same object it\n // would on an uninstrumented client. Fall back to the wrap-time owner for unbound calls.\n const invocationThis = thisArg !== undefined ? thisArg : context;\n\n const isStreamingMethod = instrumentedMethod.streaming === true;\n\n // If this is the SDK's internal `create` delegation from a streaming helper (e.g.\n // `messages.stream()` invoking `this.create()`), skip instrumentation: the helper span\n // already represents this operation, so a second span would be a duplicate.\n if (!isStreamingMethod && suppressDelegatedCreate) {\n return target.apply(invocationThis, args);\n }\n\n const operationName = instrumentedMethod.operation || 'unknown';\n const params = typeof args[0] === 'object' && args[0] !== null ? (args[0] as Record<string, unknown>) : undefined;\n const call: AnthropicAiCallInfo = { operation: 'chat', request: params };\n const recording = resolveGenAiCallRecording(options, call);\n const requestAttributes = extractRequestAttributes(\n args,\n operationName,\n recording.recordInputs,\n getProviderName(invocationThis),\n );\n const model = requestAttributes[GEN_AI_REQUEST_MODEL] || 'unknown';\n const client = getClient();\n // With span streaming, omit the `'unknown'` model sentinel so the name stays low-cardinality.\n const spanConfig = {\n name:\n (typeof model === 'string' && model !== 'unknown') || !(client && hasSpanStreamingEnabled(client))\n ? `${operationName} ${model}`\n : operationName,\n op: getGenAiSpanOp(operationName),\n attributes: requestAttributes as Record<string, SpanAttributeValue>,\n };\n\n const isStreamRequested = Boolean(params?.stream);\n\n if (isStreamRequested || isStreamingMethod) {\n return handleStreamingRequest(\n target,\n invocationThis,\n args,\n spanConfig,\n params,\n recording,\n isStreamRequested,\n isStreamingMethod,\n options,\n call,\n );\n }\n\n const abortSignal = getRequestSignal(args[1]);\n let originalResult!: Promise<R>;\n\n const instrumentedPromise = startSpan(spanConfig, span => {\n originalResult = target.apply(invocationThis, args) as Promise<R>;\n\n if (recording.recordInputs && params) {\n addPrivateRequestAttributes(span, params);\n }\n runGenAiSpanStart(options, span, call);\n\n return originalResult.then(\n result => {\n addResponseAttributes(span, result as AnthropicAiResponse, recording.recordOutputs);\n runGenAiSpanEnd(options, span, call, { response: result });\n return result;\n },\n error => {\n span.setStatus(getErrorStatus(abortSignal));\n runGenAiSpanEnd(options, span, call, { error });\n throw error;\n },\n );\n });\n\n return wrapPromiseWithMethods(originalResult, instrumentedPromise);\n },\n });\n}\n\n/**\n * Instrument the Anthropic client's methods in place.\n *\n * We deliberately do not wrap the client in a Proxy. The Anthropic SDK relies on private class\n * fields (`this.#field`), which are invisible to a Proxy and throw if a method runs with a\n * proxied `this`. Wrapping the registered methods in place (as own properties shadowing the\n * prototype) keeps `this` bound to the real instance, so instrumentation stays observationally\n * transparent: internal delegation (e.g. `messages.stream()` calling `this.create()`) and\n * `instanceof` checks behave exactly as on an uninstrumented client, and non-instrumented\n * methods are left untouched.\n */\nfunction instrumentClientInPlace<T extends object>(client: T, options: AnthropicAiOptions): T {\n for (const methodPath of Object.keys(ANTHROPIC_METHOD_REGISTRY) as Array<keyof typeof ANTHROPIC_METHOD_REGISTRY>) {\n const segments = methodPath.split('.');\n const methodName = segments.pop() as string;\n\n let owner = client as Record<string, unknown> | undefined;\n for (const segment of segments) {\n owner = owner?.[segment] as Record<string, unknown> | undefined;\n }\n\n if (!owner || typeof owner[methodName] !== 'function') {\n continue;\n }\n\n const originalMethod = owner[methodName] as (...args: unknown[]) => unknown;\n if (INSTRUMENTED_METHODS.has(originalMethod)) {\n continue;\n }\n\n const instrumented = instrumentMethod(\n originalMethod,\n methodPath,\n ANTHROPIC_METHOD_REGISTRY[methodPath],\n owner,\n options,\n );\n INSTRUMENTED_METHODS.add(instrumented);\n owner[methodName] = instrumented;\n }\n\n const beta = (client as { beta?: { messages?: object; sessions?: { events?: object } } }).beta;\n if (beta?.messages) {\n instrumentToolRunnerFactory(beta.messages, instrumentToolRunner, options);\n }\n if (beta?.sessions?.events) {\n instrumentToolRunnerFactory(beta.sessions.events, instrumentSessionToolRunner, options);\n }\n\n return client;\n}\n\n/**\n * Instrument an Anthropic AI client with Sentry tracing\n * Can be used across Node.js, Cloudflare Workers, and Vercel Edge\n *\n * @template T - The type of the client that extends object\n * @param client - The Anthropic AI client to instrument\n * @param options - Optional configuration for recording inputs and outputs\n * @returns The instrumented client with the same type as the input\n */\nexport function instrumentAnthropicAiClient<T extends object>(anthropicAiClient: T, options?: AnthropicAiOptions): T {\n return instrumentClientInPlace(anthropicAiClient, options ?? {});\n}\n"],"mappings":";;;;;;;;;;AAkCA,IAAI,0BAA0B;AAG9B,MAAM,uCAAuB,IAAI,QAAgB;;;;AAKjD,SAAgB,yBACd,MACA,eACA,cACA,eAAe,aACU;CACzB,MAAM,aAAsC;GACzC,uBAAuB;GACvB,wBAAwB;GACxB,gBAAgB;CACnB;CAEA,IAAI,KAAK,SAAS,KAAK,OAAO,KAAK,OAAO,YAAY,KAAK,OAAO,MAAM;EACtE,MAAM,SAAS,KAAK;EACpB,IAAI,gBAAgB,OAAO,SAAS,MAAM,QAAQ,OAAO,KAAK,GAC5D,WAAW,2BAA2B,KAAK,UAAU,OAAO,KAAK;EAGnE,WAAW,wBAAwB,OAAO,SAAS;EACnD,IAAI,iBAAiB,QAAQ,WAAW,8BAA8B,OAAO;EAC7E,IAAI,WAAW,QAAQ,WAAW,wBAAwB,OAAO;EACjE,IAAI,YAAY,QAAQ,WAAW,mCAAmC,OAAO;EAC7E,IAAI,WAAW,QAAQ,WAAW,wBAAwB,OAAO;EACjE,IAAI,uBAAuB,QAAQ,WAAW,oCAAoC,OAAO;EACzF,IAAI,gBAAgB,QAAQ,WAAW,6BAA6B,OAAO;CAC7E,OACE,WAAW,wBAAwB;CAGrC,OAAO;AACT;;;;;AAMA,SAAgB,4BAA4B,MAAY,QAAuC;CAC7F,MAAM,WAAW,mBAAmB,MAAM;CAC1C,KAAK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EAAE,UAAU,OAAO,CAAC;IACzD,OAAO;GACT,IACA,UAAS;IACP,KAAK,UAAU,eAAe,WAAW,CAAC;IAC1C,gBAAgB,SAAS,MAAM,MAAM,EAAE,MAAM,CAAC;IAC9C,MAAM;GACR,CACF;EACF,CAAC;EAED,OAAO,uBAAuB,gBAAgB,mBAAmB;CACnE,EACF,CAAC;AACH;;;;;;;;;;;;AAaA,SAAS,wBAA0C,QAAW,SAAgC;CAC5F,KAAK,MAAM,cAAc,OAAO,KAAK,yBAAyB,GAAoD;EAChH,MAAM,WAAW,WAAW,MAAM,GAAG;EACrC,MAAM,aAAa,SAAS,IAAI;EAEhC,IAAI,QAAQ;EACZ,KAAK,MAAM,WAAW,UACpB,QAAQ,QAAQ;EAGlB,IAAI,CAAC,SAAS,OAAO,MAAM,gBAAgB,YACzC;EAGF,MAAM,iBAAiB,MAAM;EAC7B,IAAI,qBAAqB,IAAI,cAAc,GACzC;EAGF,MAAM,eAAe,iBACnB,gBACA,YACA,0BAA0B,aAC1B,OACA,OACF;EACA,qBAAqB,IAAI,YAAY;EACrC,MAAM,cAAc;CACtB;CAEA,MAAM,OAAQ,OAA4E;CAC1F,IAAI,MAAM,UACR,4BAA4B,KAAK,UAAU,sBAAsB,OAAO;CAE1E,IAAI,MAAM,UAAU,QAClB,4BAA4B,KAAK,SAAS,QAAQ,6BAA6B,OAAO;CAGxF,OAAO;AACT;;;;;;;;;;AAWA,SAAgB,4BAA8C,mBAAsB,SAAiC;CACnH,OAAO,wBAAwB,mBAAmB,WAAW,CAAC,CAAC;AACjE"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { endStreamSpan, getErrorStatus } from "../core/utils.js";
|
|
2
|
+
import { recordTimeToFirstChunk } from "../core/time-to-first-chunk.js";
|
|
2
3
|
import { mapAnthropicErrorToStatusMessage } from "./utils.js";
|
|
3
4
|
import { SPAN_STATUS_ERROR, captureException } from "@sentry/core";
|
|
4
5
|
// src/ai/anthropic-ai/streaming.ts
|
|
@@ -105,6 +106,7 @@ function handleContentBlockStop(event, state) {
|
|
|
105
106
|
function processEvent(event, state, recordOutputs, span) {
|
|
106
107
|
if (!(event && typeof event === "object")) return;
|
|
107
108
|
if (isErrorEvent(event, span)) return;
|
|
109
|
+
recordTimeToFirstChunk(span);
|
|
108
110
|
handleMessageMetadata(event, state);
|
|
109
111
|
handleContentBlockStart(event, state);
|
|
110
112
|
handleContentBlockDelta(event, state, recordOutputs);
|
|
@@ -115,7 +117,7 @@ function processEvent(event, state, recordOutputs, span) {
|
|
|
115
117
|
* streaming attributes and (optionally) the aggregated output text, and yields
|
|
116
118
|
* each event from the input stream unchanged.
|
|
117
119
|
*/
|
|
118
|
-
async function* instrumentAsyncIterableStream(stream, span, recordOutputs) {
|
|
120
|
+
async function* instrumentAsyncIterableStream(stream, span, recordOutputs, beforeSpanEnd) {
|
|
119
121
|
const state = {
|
|
120
122
|
responseTexts: [],
|
|
121
123
|
finishReasons: [],
|
|
@@ -129,6 +131,7 @@ async function* instrumentAsyncIterableStream(stream, span, recordOutputs) {
|
|
|
129
131
|
toolCalls: [],
|
|
130
132
|
activeToolBlocks: {}
|
|
131
133
|
};
|
|
134
|
+
const result = {};
|
|
132
135
|
try {
|
|
133
136
|
for await (const event of stream) {
|
|
134
137
|
processEvent(event, state, recordOutputs, span);
|
|
@@ -139,15 +142,16 @@ async function* instrumentAsyncIterableStream(stream, span, recordOutputs) {
|
|
|
139
142
|
code: SPAN_STATUS_ERROR,
|
|
140
143
|
message: "internal_error"
|
|
141
144
|
});
|
|
145
|
+
result.error = error;
|
|
142
146
|
throw error;
|
|
143
147
|
} finally {
|
|
144
|
-
endStreamSpan(span, state, recordOutputs);
|
|
148
|
+
endStreamSpan(span, state, recordOutputs, () => beforeSpanEnd?.(result));
|
|
145
149
|
}
|
|
146
150
|
}
|
|
147
151
|
/**
|
|
148
152
|
* Instruments a MessageStream by registering event handlers and preserving the original stream API.
|
|
149
153
|
*/
|
|
150
|
-
function instrumentMessageStream(stream, span, recordOutputs, abortSignal) {
|
|
154
|
+
function instrumentMessageStream(stream, span, recordOutputs, abortSignal, beforeSpanEnd) {
|
|
151
155
|
const state = {
|
|
152
156
|
responseTexts: [],
|
|
153
157
|
finishReasons: [],
|
|
@@ -165,14 +169,14 @@ function instrumentMessageStream(stream, span, recordOutputs, abortSignal) {
|
|
|
165
169
|
processEvent(event, state, recordOutputs, span);
|
|
166
170
|
});
|
|
167
171
|
stream.on("message", () => {
|
|
168
|
-
endStreamSpan(span, state, recordOutputs);
|
|
172
|
+
endStreamSpan(span, state, recordOutputs, () => beforeSpanEnd?.({}));
|
|
169
173
|
});
|
|
170
174
|
stream.on("end", () => {
|
|
171
175
|
if (span.isRecording() && stream.aborted) span.setStatus(abortSignal?.aborted ? getErrorStatus(abortSignal) : {
|
|
172
176
|
code: SPAN_STATUS_ERROR,
|
|
173
177
|
message: "cancelled"
|
|
174
178
|
});
|
|
175
|
-
endStreamSpan(span, state, recordOutputs);
|
|
179
|
+
endStreamSpan(span, state, recordOutputs, () => beforeSpanEnd?.({}));
|
|
176
180
|
});
|
|
177
181
|
stream.on("error", (error) => {
|
|
178
182
|
captureException(error, { mechanism: {
|
|
@@ -184,7 +188,7 @@ function instrumentMessageStream(stream, span, recordOutputs, abortSignal) {
|
|
|
184
188
|
code: SPAN_STATUS_ERROR,
|
|
185
189
|
message: "internal_error"
|
|
186
190
|
});
|
|
187
|
-
endStreamSpan(span, state, recordOutputs);
|
|
191
|
+
endStreamSpan(span, state, recordOutputs, () => beforeSpanEnd?.({ error }));
|
|
188
192
|
}
|
|
189
193
|
});
|
|
190
194
|
return stream;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"streaming.js","names":[],"sources":["../../../../src/ai/anthropic-ai/streaming.ts"],"sourcesContent":["import { captureException, SPAN_STATUS_ERROR } from '@sentry/core';\nimport type { Span } from '@sentry/core';\nimport { endStreamSpan, getErrorStatus } from '../core/utils';\nimport type { AnthropicAiStreamingEvent } from './types';\nimport { mapAnthropicErrorToStatusMessage } from './utils';\n\n/**\n * State object used to accumulate information from a stream of Anthropic AI events.\n */\ninterface StreamingState {\n /** Collected response text fragments (for output recording). */\n responseTexts: string[];\n /** Reasons for finishing the response, as reported by the API. */\n finishReasons: string[];\n /** The response ID. */\n responseId: string;\n /** The model name. */\n responseModel: string;\n /** Number of input tokens, not counting cache reads and writes. */\n inputTokens: number | undefined;\n /** Number of prompt/input tokens used, including cache reads and writes. */\n promptTokens: number | undefined;\n /** Number of completion/output tokens used. */\n completionTokens: number | undefined;\n /** Number of cache creation input tokens used. */\n cacheCreationInputTokens: number | undefined;\n /** Number of cache read input tokens used. */\n cacheReadInputTokens: number | undefined;\n /** Accumulated tool calls (finalized) */\n toolCalls: Array<Record<string, unknown>>;\n /** In-progress tool call blocks keyed by index */\n activeToolBlocks: Record<\n number,\n {\n id?: string;\n name?: string;\n inputJsonParts: string[];\n }\n >;\n}\n\n/**\n * Checks if an event is an error event\n * @param event - The event to process\n * @param state - The state of the streaming process\n * @param recordOutputs - Whether to record outputs\n * @param span - The span to update\n * @returns Whether an error occurred\n */\n\nfunction isErrorEvent(event: AnthropicAiStreamingEvent, span: Span): boolean {\n if ('type' in event && typeof event.type === 'string') {\n if (event.type === 'error') {\n // The SDK surfaces this error to the caller (the async iterator rejects / their `error`\n // listener fires), so we only mark the span failed and do not record it.\n span.setStatus({ code: SPAN_STATUS_ERROR, message: mapAnthropicErrorToStatusMessage(event.error?.type) });\n return true;\n }\n }\n return false;\n}\n\n/**\n * Processes the message metadata of an event\n * @param event - The event to process\n * @param state - The state of the streaming process\n */\n\nfunction handleMessageMetadata(event: AnthropicAiStreamingEvent, state: StreamingState): void {\n // Cumulative token counts and the final stop reason both arrive on the message_delta event.\n // @see https://docs.anthropic.com/en/docs/build-with-claude/streaming#event-types\n if (event.type === 'message_delta') {\n if (event.usage) {\n // Input and cache counts can grow after message_start (e.g. with server tools), so the last value wins.\n applyInputUsage(event.usage, state);\n if (typeof event.usage.output_tokens === 'number') {\n state.completionTokens = event.usage.output_tokens;\n }\n }\n if (event.delta?.stop_reason) {\n state.finishReasons.push(event.delta.stop_reason);\n }\n }\n\n if (event.message) {\n const message = event.message;\n\n if (message.id) state.responseId = message.id;\n if (message.model) state.responseModel = message.model;\n\n if (message.usage) {\n applyInputUsage(message.usage, state);\n }\n }\n}\n\n/**\n * Records the input and cache token counts of a usage object that are numbers.\n */\nfunction applyInputUsage(\n usage: {\n input_tokens?: number | null;\n cache_creation_input_tokens?: number | null;\n cache_read_input_tokens?: number | null;\n },\n state: StreamingState,\n): void {\n if (typeof usage.input_tokens === 'number') state.inputTokens = usage.input_tokens;\n if (typeof usage.cache_creation_input_tokens === 'number')\n state.cacheCreationInputTokens = usage.cache_creation_input_tokens;\n if (typeof usage.cache_read_input_tokens === 'number') state.cacheReadInputTokens = usage.cache_read_input_tokens;\n\n if (typeof state.inputTokens === 'number') {\n state.promptTokens = state.inputTokens + (state.cacheCreationInputTokens ?? 0) + (state.cacheReadInputTokens ?? 0);\n }\n}\n\n/**\n * Handle start of a content block (e.g., tool_use)\n */\nfunction handleContentBlockStart(event: AnthropicAiStreamingEvent, state: StreamingState): void {\n if (event.type !== 'content_block_start' || typeof event.index !== 'number' || !event.content_block) return;\n if (event.content_block.type === 'tool_use' || event.content_block.type === 'server_tool_use') {\n state.activeToolBlocks[event.index] = {\n id: event.content_block.id,\n name: event.content_block.name,\n inputJsonParts: [],\n };\n }\n}\n\n/**\n * Handle deltas of a content block, including input_json_delta for tool_use\n */\nfunction handleContentBlockDelta(\n event: AnthropicAiStreamingEvent,\n state: StreamingState,\n recordOutputs: boolean,\n): void {\n if (event.type !== 'content_block_delta' || !event.delta) return;\n\n // Accumulate tool_use input JSON deltas only when we have an index and an active tool block\n if (\n typeof event.index === 'number' &&\n 'partial_json' in event.delta &&\n typeof event.delta.partial_json === 'string'\n ) {\n const active = state.activeToolBlocks[event.index];\n if (active) {\n active.inputJsonParts.push(event.delta.partial_json);\n }\n }\n\n // Accumulate streamed response text regardless of index\n if (recordOutputs && typeof event.delta.text === 'string') {\n state.responseTexts.push(event.delta.text);\n }\n}\n\n/**\n * Handle stop of a content block; finalize tool_use entries\n */\nfunction handleContentBlockStop(event: AnthropicAiStreamingEvent, state: StreamingState): void {\n if (event.type !== 'content_block_stop' || typeof event.index !== 'number') return;\n\n const active = state.activeToolBlocks[event.index];\n if (!active) return;\n\n const raw = active.inputJsonParts.join('');\n let parsedInput: unknown;\n\n try {\n parsedInput = raw ? JSON.parse(raw) : {};\n } catch {\n parsedInput = { __unparsed: raw };\n }\n\n state.toolCalls.push({\n type: 'tool_use',\n id: active.id,\n name: active.name,\n input: parsedInput,\n });\n\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete state.activeToolBlocks[event.index];\n}\n\n/**\n * Processes an event\n * @param event - The event to process\n * @param state - The state of the streaming process\n * @param recordOutputs - Whether to record outputs\n * @param span - The span to update\n */\nfunction processEvent(\n event: AnthropicAiStreamingEvent,\n state: StreamingState,\n recordOutputs: boolean,\n span: Span,\n): void {\n if (!(event && typeof event === 'object')) {\n return;\n }\n\n const isError = isErrorEvent(event, span);\n if (isError) return;\n\n handleMessageMetadata(event, state);\n\n // Tool call events are sent via 3 separate events:\n // - content_block_start (start of the tool call)\n // - content_block_delta (delta aka input of the tool call)\n // - content_block_stop (end of the tool call)\n // We need to handle them all to capture the full tool call.\n handleContentBlockStart(event, state);\n handleContentBlockDelta(event, state, recordOutputs);\n handleContentBlockStop(event, state);\n}\n\n/**\n * Instruments an async iterable stream of Anthropic events, updates the span with\n * streaming attributes and (optionally) the aggregated output text, and yields\n * each event from the input stream unchanged.\n */\nexport async function* instrumentAsyncIterableStream(\n stream: AsyncIterable<AnthropicAiStreamingEvent>,\n span: Span,\n recordOutputs: boolean,\n): AsyncGenerator<AnthropicAiStreamingEvent, void, unknown> {\n const state: StreamingState = {\n responseTexts: [],\n finishReasons: [],\n responseId: '',\n responseModel: '',\n inputTokens: undefined,\n promptTokens: undefined,\n completionTokens: undefined,\n cacheCreationInputTokens: undefined,\n cacheReadInputTokens: undefined,\n toolCalls: [],\n activeToolBlocks: {},\n };\n\n try {\n for await (const event of stream) {\n processEvent(event, state, recordOutputs, span);\n yield event;\n }\n } catch (error) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n throw error;\n } finally {\n endStreamSpan(span, state, recordOutputs);\n }\n}\n\n/**\n * Instruments a MessageStream by registering event handlers and preserving the original stream API.\n */\nexport function instrumentMessageStream<R extends { on: (...args: unknown[]) => void; aborted?: boolean }>(\n stream: R,\n span: Span,\n recordOutputs: boolean,\n abortSignal?: AbortSignal,\n): R {\n const state: StreamingState = {\n responseTexts: [],\n finishReasons: [],\n responseId: '',\n responseModel: '',\n inputTokens: undefined,\n promptTokens: undefined,\n completionTokens: undefined,\n cacheCreationInputTokens: undefined,\n cacheReadInputTokens: undefined,\n toolCalls: [],\n activeToolBlocks: {},\n };\n\n stream.on('streamEvent', (event: unknown) => {\n processEvent(event as AnthropicAiStreamingEvent, state, recordOutputs, span);\n });\n\n // The event fired when a message is done being streamed by the API. Corresponds to the message_stop SSE event.\n // @see https://github.com/anthropics/anthropic-sdk-typescript/blob/d3be31f5a4e6ebb4c0a2f65dbb8f381ae73a9166/helpers.md?plain=1#L42-L44\n stream.on('message', () => {\n endStreamSpan(span, state, recordOutputs);\n });\n\n // Fires last on every stream, so a stream that stops without 'message' (aborted, or the body closed early) still\n // ends its span. An 'abort' listener would also stop the SDK from raising an unobserved abort as a rejection.\n stream.on('end', () => {\n if (span.isRecording() && stream.aborted) {\n // `aborted` is also set when the caller's `AbortSignal.timeout()` fires, which is a timeout, not a cancellation.\n span.setStatus(\n abortSignal?.aborted ? getErrorStatus(abortSignal) : { code: SPAN_STATUS_ERROR, message: 'cancelled' },\n );\n }\n endStreamSpan(span, state, recordOutputs);\n });\n\n stream.on('error', (error: unknown) => {\n // Attaching this listener stops the stream error from being raised as an unhandled rejection, so\n // we capture it here to avoid swallowing it (e.g. for callers that don't await/iterate the stream).\n captureException(error, {\n mechanism: {\n handled: false,\n type: 'auto.ai.anthropic.stream_error',\n },\n });\n\n if (span.isRecording()) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n endStreamSpan(span, state, recordOutputs);\n }\n });\n\n return stream;\n}\n"],"mappings":";;;;;;;;;;;;AAkDA,SAAS,aAAa,OAAkC,MAAqB;CAC3E,IAAI,UAAU,SAAS,OAAO,MAAM,SAAS,UACvC;MAAA,MAAM,SAAS,SAAS;GAG1B,KAAK,UAAU;IAAE,MAAM;IAAmB,SAAS,iCAAiC,MAAM,OAAO,IAAI;GAAE,CAAC;GACxG,OAAO;EACT;;CAEF,OAAO;AACT;;;;;;AAQA,SAAS,sBAAsB,OAAkC,OAA6B;CAG5F,IAAI,MAAM,SAAS,iBAAiB;EAClC,IAAI,MAAM,OAAO;GAEf,gBAAgB,MAAM,OAAO,KAAK;GAClC,IAAI,OAAO,MAAM,MAAM,kBAAkB,UACvC,MAAM,mBAAmB,MAAM,MAAM;EAEzC;EACA,IAAI,MAAM,OAAO,aACf,MAAM,cAAc,KAAK,MAAM,MAAM,WAAW;CAEpD;CAEA,IAAI,MAAM,SAAS;EACjB,MAAM,UAAU,MAAM;EAEtB,IAAI,QAAQ,IAAI,MAAM,aAAa,QAAQ;EAC3C,IAAI,QAAQ,OAAO,MAAM,gBAAgB,QAAQ;EAEjD,IAAI,QAAQ,OACV,gBAAgB,QAAQ,OAAO,KAAK;CAExC;AACF;;;;AAKA,SAAS,gBACP,OAKA,OACM;CACN,IAAI,OAAO,MAAM,iBAAiB,UAAU,MAAM,cAAc,MAAM;CACtE,IAAI,OAAO,MAAM,gCAAgC,UAC/C,MAAM,2BAA2B,MAAM;CACzC,IAAI,OAAO,MAAM,4BAA4B,UAAU,MAAM,uBAAuB,MAAM;CAE1F,IAAI,OAAO,MAAM,gBAAgB,UAC/B,MAAM,eAAe,MAAM,eAAe,MAAM,4BAA4B,MAAM,MAAM,wBAAwB;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OAAO,GAAG,UAAU,UAAmB;EAGrC,iBAAiB,OAAO,EACtB,WAAW;GACT,SAAS;GACT,MAAM;EACR,EACF,CAAC;EAED,IAAI,KAAK,YAAY,GAAG;GACtB,KAAK,UAAU;IAAE,MAAM;IAAmB,SAAS;GAAiB,CAAC;GACrE,cAAc,MAAM,OAAO,aAAa;EAC1C;CACF,CAAC;CAED,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"streaming.js","names":[],"sources":["../../../../src/ai/anthropic-ai/streaming.ts"],"sourcesContent":["import { captureException, SPAN_STATUS_ERROR } from '@sentry/core';\nimport type { Span } from '@sentry/core';\nimport type { GenAiSpanResult } from '../core/span-hooks';\nimport { endStreamSpan, getErrorStatus } from '../core/utils';\nimport { recordTimeToFirstChunk } from '../core/time-to-first-chunk';\nimport type { AnthropicAiStreamingEvent } from './types';\nimport { mapAnthropicErrorToStatusMessage } from './utils';\n\n/**\n * State object used to accumulate information from a stream of Anthropic AI events.\n */\ninterface StreamingState {\n /** Collected response text fragments (for output recording). */\n responseTexts: string[];\n /** Reasons for finishing the response, as reported by the API. */\n finishReasons: string[];\n /** The response ID. */\n responseId: string;\n /** The model name. */\n responseModel: string;\n /** Number of input tokens, not counting cache reads and writes. */\n inputTokens: number | undefined;\n /** Number of prompt/input tokens used, including cache reads and writes. */\n promptTokens: number | undefined;\n /** Number of completion/output tokens used. */\n completionTokens: number | undefined;\n /** Number of cache creation input tokens used. */\n cacheCreationInputTokens: number | undefined;\n /** Number of cache read input tokens used. */\n cacheReadInputTokens: number | undefined;\n /** Accumulated tool calls (finalized) */\n toolCalls: Array<Record<string, unknown>>;\n /** In-progress tool call blocks keyed by index */\n activeToolBlocks: Record<\n number,\n {\n id?: string;\n name?: string;\n inputJsonParts: string[];\n }\n >;\n}\n\n/**\n * Checks if an event is an error event\n * @param event - The event to process\n * @param state - The state of the streaming process\n * @param recordOutputs - Whether to record outputs\n * @param span - The span to update\n * @returns Whether an error occurred\n */\n\nfunction isErrorEvent(event: AnthropicAiStreamingEvent, span: Span): boolean {\n if ('type' in event && typeof event.type === 'string') {\n if (event.type === 'error') {\n // The SDK surfaces this error to the caller (the async iterator rejects / their `error`\n // listener fires), so we only mark the span failed and do not record it.\n span.setStatus({ code: SPAN_STATUS_ERROR, message: mapAnthropicErrorToStatusMessage(event.error?.type) });\n return true;\n }\n }\n return false;\n}\n\n/**\n * Processes the message metadata of an event\n * @param event - The event to process\n * @param state - The state of the streaming process\n */\n\nfunction handleMessageMetadata(event: AnthropicAiStreamingEvent, state: StreamingState): void {\n // Cumulative token counts and the final stop reason both arrive on the message_delta event.\n // @see https://docs.anthropic.com/en/docs/build-with-claude/streaming#event-types\n if (event.type === 'message_delta') {\n if (event.usage) {\n // Input and cache counts can grow after message_start (e.g. with server tools), so the last value wins.\n applyInputUsage(event.usage, state);\n if (typeof event.usage.output_tokens === 'number') {\n state.completionTokens = event.usage.output_tokens;\n }\n }\n if (event.delta?.stop_reason) {\n state.finishReasons.push(event.delta.stop_reason);\n }\n }\n\n if (event.message) {\n const message = event.message;\n\n if (message.id) state.responseId = message.id;\n if (message.model) state.responseModel = message.model;\n\n if (message.usage) {\n applyInputUsage(message.usage, state);\n }\n }\n}\n\n/**\n * Records the input and cache token counts of a usage object that are numbers.\n */\nfunction applyInputUsage(\n usage: {\n input_tokens?: number | null;\n cache_creation_input_tokens?: number | null;\n cache_read_input_tokens?: number | null;\n },\n state: StreamingState,\n): void {\n if (typeof usage.input_tokens === 'number') state.inputTokens = usage.input_tokens;\n if (typeof usage.cache_creation_input_tokens === 'number')\n state.cacheCreationInputTokens = usage.cache_creation_input_tokens;\n if (typeof usage.cache_read_input_tokens === 'number') state.cacheReadInputTokens = usage.cache_read_input_tokens;\n\n if (typeof state.inputTokens === 'number') {\n state.promptTokens = state.inputTokens + (state.cacheCreationInputTokens ?? 0) + (state.cacheReadInputTokens ?? 0);\n }\n}\n\n/**\n * Handle start of a content block (e.g., tool_use)\n */\nfunction handleContentBlockStart(event: AnthropicAiStreamingEvent, state: StreamingState): void {\n if (event.type !== 'content_block_start' || typeof event.index !== 'number' || !event.content_block) return;\n if (event.content_block.type === 'tool_use' || event.content_block.type === 'server_tool_use') {\n state.activeToolBlocks[event.index] = {\n id: event.content_block.id,\n name: event.content_block.name,\n inputJsonParts: [],\n };\n }\n}\n\n/**\n * Handle deltas of a content block, including input_json_delta for tool_use\n */\nfunction handleContentBlockDelta(\n event: AnthropicAiStreamingEvent,\n state: StreamingState,\n recordOutputs: boolean,\n): void {\n if (event.type !== 'content_block_delta' || !event.delta) return;\n\n // Accumulate tool_use input JSON deltas only when we have an index and an active tool block\n if (\n typeof event.index === 'number' &&\n 'partial_json' in event.delta &&\n typeof event.delta.partial_json === 'string'\n ) {\n const active = state.activeToolBlocks[event.index];\n if (active) {\n active.inputJsonParts.push(event.delta.partial_json);\n }\n }\n\n // Accumulate streamed response text regardless of index\n if (recordOutputs && typeof event.delta.text === 'string') {\n state.responseTexts.push(event.delta.text);\n }\n}\n\n/**\n * Handle stop of a content block; finalize tool_use entries\n */\nfunction handleContentBlockStop(event: AnthropicAiStreamingEvent, state: StreamingState): void {\n if (event.type !== 'content_block_stop' || typeof event.index !== 'number') return;\n\n const active = state.activeToolBlocks[event.index];\n if (!active) return;\n\n const raw = active.inputJsonParts.join('');\n let parsedInput: unknown;\n\n try {\n parsedInput = raw ? JSON.parse(raw) : {};\n } catch {\n parsedInput = { __unparsed: raw };\n }\n\n state.toolCalls.push({\n type: 'tool_use',\n id: active.id,\n name: active.name,\n input: parsedInput,\n });\n\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete state.activeToolBlocks[event.index];\n}\n\n/**\n * Processes an event\n * @param event - The event to process\n * @param state - The state of the streaming process\n * @param recordOutputs - Whether to record outputs\n * @param span - The span to update\n */\nfunction processEvent(\n event: AnthropicAiStreamingEvent,\n state: StreamingState,\n recordOutputs: boolean,\n span: Span,\n): void {\n if (!(event && typeof event === 'object')) {\n return;\n }\n\n const isError = isErrorEvent(event, span);\n if (isError) return;\n\n recordTimeToFirstChunk(span);\n\n handleMessageMetadata(event, state);\n\n // Tool call events are sent via 3 separate events:\n // - content_block_start (start of the tool call)\n // - content_block_delta (delta aka input of the tool call)\n // - content_block_stop (end of the tool call)\n // We need to handle them all to capture the full tool call.\n handleContentBlockStart(event, state);\n handleContentBlockDelta(event, state, recordOutputs);\n handleContentBlockStop(event, state);\n}\n\n/**\n * Instruments an async iterable stream of Anthropic events, updates the span with\n * streaming attributes and (optionally) the aggregated output text, and yields\n * each event from the input stream unchanged.\n */\nexport async function* instrumentAsyncIterableStream(\n stream: AsyncIterable<AnthropicAiStreamingEvent>,\n span: Span,\n recordOutputs: boolean,\n beforeSpanEnd?: (result: GenAiSpanResult<never>) => void,\n): AsyncGenerator<AnthropicAiStreamingEvent, void, unknown> {\n const state: StreamingState = {\n responseTexts: [],\n finishReasons: [],\n responseId: '',\n responseModel: '',\n inputTokens: undefined,\n promptTokens: undefined,\n completionTokens: undefined,\n cacheCreationInputTokens: undefined,\n cacheReadInputTokens: undefined,\n toolCalls: [],\n activeToolBlocks: {},\n };\n const result: GenAiSpanResult<never> = {};\n\n try {\n for await (const event of stream) {\n processEvent(event, state, recordOutputs, span);\n yield event;\n }\n } catch (error) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n result.error = error;\n throw error;\n } finally {\n endStreamSpan(span, state, recordOutputs, () => beforeSpanEnd?.(result));\n }\n}\n\n/**\n * Instruments a MessageStream by registering event handlers and preserving the original stream API.\n */\nexport function instrumentMessageStream<R extends { on: (...args: unknown[]) => void; aborted?: boolean }>(\n stream: R,\n span: Span,\n recordOutputs: boolean,\n abortSignal?: AbortSignal,\n beforeSpanEnd?: (result: GenAiSpanResult<never>) => void,\n): R {\n const state: StreamingState = {\n responseTexts: [],\n finishReasons: [],\n responseId: '',\n responseModel: '',\n inputTokens: undefined,\n promptTokens: undefined,\n completionTokens: undefined,\n cacheCreationInputTokens: undefined,\n cacheReadInputTokens: undefined,\n toolCalls: [],\n activeToolBlocks: {},\n };\n\n stream.on('streamEvent', (event: unknown) => {\n processEvent(event as AnthropicAiStreamingEvent, state, recordOutputs, span);\n });\n\n // The event fired when a message is done being streamed by the API. Corresponds to the message_stop SSE event.\n // @see https://github.com/anthropics/anthropic-sdk-typescript/blob/d3be31f5a4e6ebb4c0a2f65dbb8f381ae73a9166/helpers.md?plain=1#L42-L44\n stream.on('message', () => {\n endStreamSpan(span, state, recordOutputs, () => beforeSpanEnd?.({}));\n });\n\n // Fires last on every stream, so a stream that stops without 'message' (aborted, or the body closed early) still\n // ends its span. An 'abort' listener would also stop the SDK from raising an unobserved abort as a rejection.\n stream.on('end', () => {\n if (span.isRecording() && stream.aborted) {\n // `aborted` is also set when the caller's `AbortSignal.timeout()` fires, which is a timeout, not a cancellation.\n span.setStatus(\n abortSignal?.aborted ? getErrorStatus(abortSignal) : { code: SPAN_STATUS_ERROR, message: 'cancelled' },\n );\n }\n endStreamSpan(span, state, recordOutputs, () => beforeSpanEnd?.({}));\n });\n\n stream.on('error', (error: unknown) => {\n // Attaching this listener stops the stream error from being raised as an unhandled rejection, so\n // we capture it here to avoid swallowing it (e.g. for callers that don't await/iterate the stream).\n captureException(error, {\n mechanism: {\n handled: false,\n type: 'auto.ai.anthropic.stream_error',\n },\n });\n\n if (span.isRecording()) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n endStreamSpan(span, state, recordOutputs, () => beforeSpanEnd?.({ error }));\n }\n });\n\n return stream;\n}\n"],"mappings":";;;;;;;;;;;;;AAoDA,SAAS,aAAa,OAAkC,MAAqB;CAC3E,IAAI,UAAU,SAAS,OAAO,MAAM,SAAS,UACvC;MAAA,MAAM,SAAS,SAAS;GAG1B,KAAK,UAAU;IAAE,MAAM;IAAmB,SAAS,iCAAiC,MAAM,OAAO,IAAI;GAAE,CAAC;GACxG,OAAO;EACT;;CAEF,OAAO;AACT;;;;;;AAQA,SAAS,sBAAsB,OAAkC,OAA6B;CAG5F,I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CALL_ID_ATTRIBUTE } from "../core/gen-ai-attributes.js";
|
|
2
|
-
import {
|
|
2
|
+
import { runGenAiSpanEnd, runGenAiSpanStart } from "../core/span-hooks.js";
|
|
3
|
+
import { getErrorStatus, resolveGenAiCallRecording } from "../core/utils.js";
|
|
3
4
|
import { withCleanScopes } from "../../utils/withCleanScopes.js";
|
|
4
5
|
import { ANTHROPIC_AI_ORIGIN } from "./constants.js";
|
|
5
6
|
import { GEN_AI_CONVERSATION_ID, GEN_AI_OPERATION_NAME, GEN_AI_PROVIDER_NAME, GEN_AI_TOOL_CALL_ARGUMENTS, GEN_AI_TOOL_CALL_RESULT, GEN_AI_TOOL_DESCRIPTION, GEN_AI_TOOL_NAME, SENTRY_ORIGIN } from "@sentry/conventions/attributes";
|
|
@@ -89,8 +90,13 @@ function wrapInPlace(owner, key, call) {
|
|
|
89
90
|
});
|
|
90
91
|
}
|
|
91
92
|
function runWithSpan(tool, run, thisArg, args, options) {
|
|
92
|
-
const { recordInputs, recordOutputs } = resolveAIRecordingOptions(options);
|
|
93
93
|
const [input, context] = args;
|
|
94
|
+
const call = {
|
|
95
|
+
operation: "execute_tool",
|
|
96
|
+
tool,
|
|
97
|
+
input
|
|
98
|
+
};
|
|
99
|
+
const { recordInputs, recordOutputs } = resolveGenAiCallRecording(options, call);
|
|
94
100
|
const callId = (context?.toolUse ?? context?.toolUseBlock)?.id;
|
|
95
101
|
return startSpan({
|
|
96
102
|
name: `execute_tool ${tool.name}`,
|
|
@@ -103,7 +109,16 @@ function runWithSpan(tool, run, thisArg, args, options) {
|
|
|
103
109
|
...typeof callId === "string" ? { [GEN_AI_TOOL_CALL_ID_ATTRIBUTE]: callId } : {},
|
|
104
110
|
...recordInputs ? { [GEN_AI_TOOL_CALL_ARGUMENTS]: stringify(input) } : {}
|
|
105
111
|
}
|
|
106
|
-
}, (span) =>
|
|
112
|
+
}, (span) => {
|
|
113
|
+
runGenAiSpanStart(options, span, call);
|
|
114
|
+
return handleCallbackErrors(() => run.apply(thisArg, args), (error) => {
|
|
115
|
+
handleToolError(span, error, context);
|
|
116
|
+
runGenAiSpanEnd(options, span, call, { error });
|
|
117
|
+
}, void 0, (result) => {
|
|
118
|
+
if (recordOutputs) span.setAttribute(GEN_AI_TOOL_CALL_RESULT, stringify(result));
|
|
119
|
+
runGenAiSpanEnd(options, span, call, { response: result });
|
|
120
|
+
});
|
|
121
|
+
});
|
|
107
122
|
}
|
|
108
123
|
function handleToolError(span, error, context) {
|
|
109
124
|
span.setStatus(getErrorStatus(context?.signal));
|